RoundCube Webmail
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

690 lines
21 KiB

13 years ago
13 years ago
12 years ago
12 years ago
13 years ago
  1. <?php
  2. /*
  3. +-----------------------------------------------------------------------+
  4. | This file is part of the Roundcube Webmail client |
  5. | Copyright (C) 2006-2013, The Roundcube Dev Team |
  6. | |
  7. | Licensed under the GNU General Public License version 3 or |
  8. | any later version with exceptions for skins & plugins. |
  9. | See the README file for a full license statement. |
  10. | |
  11. | PURPOSE: |
  12. | Interface to the local address book database |
  13. +-----------------------------------------------------------------------+
  14. | Author: Thomas Bruederli <roundcube@gmail.com> |
  15. +-----------------------------------------------------------------------+
  16. */
  17. /**
  18. * Abstract skeleton of an address book/repository
  19. *
  20. * @package Framework
  21. * @subpackage Addressbook
  22. */
  23. abstract class rcube_addressbook
  24. {
  25. /** constants for error reporting **/
  26. const ERROR_READ_ONLY = 1;
  27. const ERROR_NO_CONNECTION = 2;
  28. const ERROR_VALIDATE = 3;
  29. const ERROR_SAVING = 4;
  30. const ERROR_SEARCH = 5;
  31. /** public properties (mandatory) */
  32. public $primary_key;
  33. public $groups = false;
  34. public $export_groups = true;
  35. public $readonly = true;
  36. public $searchonly = false;
  37. public $undelete = false;
  38. public $ready = false;
  39. public $group_id = null;
  40. public $list_page = 1;
  41. public $page_size = 10;
  42. public $sort_col = 'name';
  43. public $sort_order = 'ASC';
  44. public $coltypes = array('name' => array('limit'=>1), 'firstname' => array('limit'=>1), 'surname' => array('limit'=>1), 'email' => array('limit'=>1));
  45. public $date_cols = array();
  46. protected $error;
  47. /**
  48. * Returns addressbook name (e.g. for addressbooks listing)
  49. */
  50. abstract function get_name();
  51. /**
  52. * Save a search string for future listings
  53. *
  54. * @param mixed Search params to use in listing method, obtained by get_search_set()
  55. */
  56. abstract function set_search_set($filter);
  57. /**
  58. * Getter for saved search properties
  59. *
  60. * @return mixed Search properties used by this class
  61. */
  62. abstract function get_search_set();
  63. /**
  64. * Reset saved results and search parameters
  65. */
  66. abstract function reset();
  67. /**
  68. * Refresh saved search set after data has changed
  69. *
  70. * @return mixed New search set
  71. */
  72. function refresh_search()
  73. {
  74. return $this->get_search_set();
  75. }
  76. /**
  77. * List the current set of contact records
  78. *
  79. * @param array List of cols to show
  80. * @param int Only return this number of records, use negative values for tail
  81. * @return array Indexed list of contact records, each a hash array
  82. */
  83. abstract function list_records($cols=null, $subset=0);
  84. /**
  85. * Search records
  86. *
  87. * @param array List of fields to search in
  88. * @param string Search value
  89. * @param int Matching mode:
  90. * 0 - partial (*abc*),
  91. * 1 - strict (=),
  92. * 2 - prefix (abc*)
  93. * @param boolean True if results are requested, False if count only
  94. * @param boolean True to skip the count query (select only)
  95. * @param array List of fields that cannot be empty
  96. * @return object rcube_result_set List of contact records and 'count' value
  97. */
  98. abstract function search($fields, $value, $mode=0, $select=true, $nocount=false, $required=array());
  99. /**
  100. * Count number of available contacts in database
  101. *
  102. * @return rcube_result_set Result set with values for 'count' and 'first'
  103. */
  104. abstract function count();
  105. /**
  106. * Return the last result set
  107. *
  108. * @return rcube_result_set Current result set or NULL if nothing selected yet
  109. */
  110. abstract function get_result();
  111. /**
  112. * Get a specific contact record
  113. *
  114. * @param mixed record identifier(s)
  115. * @param boolean True to return record as associative array, otherwise a result set is returned
  116. *
  117. * @return mixed Result object with all record fields or False if not found
  118. */
  119. abstract function get_record($id, $assoc=false);
  120. /**
  121. * Returns the last error occurred (e.g. when updating/inserting failed)
  122. *
  123. * @return array Hash array with the following fields: type, message
  124. */
  125. function get_error()
  126. {
  127. return $this->error;
  128. }
  129. /**
  130. * Setter for errors for internal use
  131. *
  132. * @param int Error type (one of this class' error constants)
  133. * @param string Error message (name of a text label)
  134. */
  135. protected function set_error($type, $message)
  136. {
  137. $this->error = array('type' => $type, 'message' => $message);
  138. }
  139. /**
  140. * Close connection to source
  141. * Called on script shutdown
  142. */
  143. function close() { }
  144. /**
  145. * Set internal list page
  146. *
  147. * @param number Page number to list
  148. * @access public
  149. */
  150. function set_page($page)
  151. {
  152. $this->list_page = (int)$page;
  153. }
  154. /**
  155. * Set internal page size
  156. *
  157. * @param number Number of messages to display on one page
  158. * @access public
  159. */
  160. function set_pagesize($size)
  161. {
  162. $this->page_size = (int)$size;
  163. }
  164. /**
  165. * Set internal sort settings
  166. *
  167. * @param string $sort_col Sort column
  168. * @param string $sort_order Sort order
  169. */
  170. function set_sort_order($sort_col, $sort_order = null)
  171. {
  172. if ($sort_col != null && ($this->coltypes[$sort_col] || in_array($sort_col, $this->coltypes))) {
  173. $this->sort_col = $sort_col;
  174. }
  175. if ($sort_order != null) {
  176. $this->sort_order = strtoupper($sort_order) == 'DESC' ? 'DESC' : 'ASC';
  177. }
  178. }
  179. /**
  180. * Check the given data before saving.
  181. * If input isn't valid, the message to display can be fetched using get_error()
  182. *
  183. * @param array Assoziative array with data to save
  184. * @param boolean Attempt to fix/complete record automatically
  185. * @return boolean True if input is valid, False if not.
  186. */
  187. public function validate(&$save_data, $autofix = false)
  188. {
  189. $rcube = rcube::get_instance();
  190. $valid = true;
  191. // check validity of email addresses
  192. foreach ($this->get_col_values('email', $save_data, true) as $email) {
  193. if (strlen($email)) {
  194. if (!rcube_utils::check_email(rcube_utils::idn_to_ascii($email))) {
  195. $error = $rcube->gettext(array('name' => 'emailformaterror', 'vars' => array('email' => $email)));
  196. $this->set_error(self::ERROR_VALIDATE, $error);
  197. $valid = false;
  198. break;
  199. }
  200. }
  201. }
  202. // allow plugins to do contact validation and auto-fixing
  203. $plugin = $rcube->plugins->exec_hook('contact_validate', array(
  204. 'record' => $save_data,
  205. 'autofix' => $autofix,
  206. 'valid' => $valid,
  207. ));
  208. if ($valid && !$plugin['valid']) {
  209. $this->set_error(self::ERROR_VALIDATE, $plugin['error']);
  210. }
  211. if (is_array($plugin['record'])) {
  212. $save_data = $plugin['record'];
  213. }
  214. return $plugin['valid'];
  215. }
  216. /**
  217. * Create a new contact record
  218. *
  219. * @param array Assoziative array with save data
  220. * Keys: Field name with optional section in the form FIELD:SECTION
  221. * Values: Field value. Can be either a string or an array of strings for multiple values
  222. * @param boolean True to check for duplicates first
  223. * @return mixed The created record ID on success, False on error
  224. */
  225. function insert($save_data, $check=false)
  226. {
  227. /* empty for read-only address books */
  228. }
  229. /**
  230. * Create new contact records for every item in the record set
  231. *
  232. * @param object rcube_result_set Recordset to insert
  233. * @param boolean True to check for duplicates first
  234. * @return array List of created record IDs
  235. */
  236. function insertMultiple($recset, $check=false)
  237. {
  238. $ids = array();
  239. if (is_object($recset) && is_a($recset, rcube_result_set)) {
  240. while ($row = $recset->next()) {
  241. if ($insert = $this->insert($row, $check))
  242. $ids[] = $insert;
  243. }
  244. }
  245. return $ids;
  246. }
  247. /**
  248. * Update a specific contact record
  249. *
  250. * @param mixed Record identifier
  251. * @param array Assoziative array with save data
  252. * Keys: Field name with optional section in the form FIELD:SECTION
  253. * Values: Field value. Can be either a string or an array of strings for multiple values
  254. *
  255. * @return mixed On success if ID has been changed returns ID, otherwise True, False on error
  256. */
  257. function update($id, $save_cols)
  258. {
  259. /* empty for read-only address books */
  260. }
  261. /**
  262. * Mark one or more contact records as deleted
  263. *
  264. * @param array Record identifiers
  265. * @param bool Remove records irreversible (see self::undelete)
  266. */
  267. function delete($ids, $force=true)
  268. {
  269. /* empty for read-only address books */
  270. }
  271. /**
  272. * Unmark delete flag on contact record(s)
  273. *
  274. * @param array Record identifiers
  275. */
  276. function undelete($ids)
  277. {
  278. /* empty for read-only address books */
  279. }
  280. /**
  281. * Mark all records in database as deleted
  282. *
  283. * @param bool $with_groups Remove also groups
  284. */
  285. function delete_all($with_groups = false)
  286. {
  287. /* empty for read-only address books */
  288. }
  289. /**
  290. * Setter for the current group
  291. * (empty, has to be re-implemented by extending class)
  292. */
  293. function set_group($gid) { }
  294. /**
  295. * List all active contact groups of this source
  296. *
  297. * @param string Optional search string to match group name
  298. * @param int Matching mode:
  299. * 0 - partial (*abc*),
  300. * 1 - strict (=),
  301. * 2 - prefix (abc*)
  302. *
  303. * @return array Indexed list of contact groups, each a hash array
  304. */
  305. function list_groups($search = null, $mode = 0)
  306. {
  307. /* empty for address books don't supporting groups */
  308. return array();
  309. }
  310. /**
  311. * Get group properties such as name and email address(es)
  312. *
  313. * @param string Group identifier
  314. * @return array Group properties as hash array
  315. */
  316. function get_group($group_id)
  317. {
  318. /* empty for address books don't supporting groups */
  319. return null;
  320. }
  321. /**
  322. * Create a contact group with the given name
  323. *
  324. * @param string The group name
  325. * @return mixed False on error, array with record props in success
  326. */
  327. function create_group($name)
  328. {
  329. /* empty for address books don't supporting groups */
  330. return false;
  331. }
  332. /**
  333. * Delete the given group and all linked group members
  334. *
  335. * @param string Group identifier
  336. * @return boolean True on success, false if no data was changed
  337. */
  338. function delete_group($gid)
  339. {
  340. /* empty for address books don't supporting groups */
  341. return false;
  342. }
  343. /**
  344. * Rename a specific contact group
  345. *
  346. * @param string Group identifier
  347. * @param string New name to set for this group
  348. * @param string New group identifier (if changed, otherwise don't set)
  349. * @return boolean New name on success, false if no data was changed
  350. */
  351. function rename_group($gid, $newname, &$newid)
  352. {
  353. /* empty for address books don't supporting groups */
  354. return false;
  355. }
  356. /**
  357. * Add the given contact records the a certain group
  358. *
  359. * @param string Group identifier
  360. * @param array|string List of contact identifiers to be added
  361. *
  362. * @return int Number of contacts added
  363. */
  364. function add_to_group($group_id, $ids)
  365. {
  366. /* empty for address books don't supporting groups */
  367. return 0;
  368. }
  369. /**
  370. * Remove the given contact records from a certain group
  371. *
  372. * @param string Group identifier
  373. * @param array|string List of contact identifiers to be removed
  374. *
  375. * @return int Number of deleted group members
  376. */
  377. function remove_from_group($group_id, $ids)
  378. {
  379. /* empty for address books don't supporting groups */
  380. return 0;
  381. }
  382. /**
  383. * Get group assignments of a specific contact record
  384. *
  385. * @param mixed Record identifier
  386. *
  387. * @return array List of assigned groups as ID=>Name pairs
  388. * @since 0.5-beta
  389. */
  390. function get_record_groups($id)
  391. {
  392. /* empty for address books don't supporting groups */
  393. return array();
  394. }
  395. /**
  396. * Utility function to return all values of a certain data column
  397. * either as flat list or grouped by subtype
  398. *
  399. * @param string Col name
  400. * @param array Record data array as used for saving
  401. * @param boolean True to return one array with all values, False for hash array with values grouped by type
  402. * @return array List of column values
  403. */
  404. public static function get_col_values($col, $data, $flat = false)
  405. {
  406. $out = array();
  407. foreach ((array)$data as $c => $values) {
  408. if ($c === $col || strpos($c, $col.':') === 0) {
  409. if ($flat) {
  410. $out = array_merge($out, (array)$values);
  411. }
  412. else {
  413. list(, $type) = explode(':', $c);
  414. $out[$type] = array_merge((array)$out[$type], (array)$values);
  415. }
  416. }
  417. }
  418. // remove duplicates
  419. if ($flat && !empty($out)) {
  420. $out = array_unique($out);
  421. }
  422. return $out;
  423. }
  424. /**
  425. * Normalize the given string for fulltext search.
  426. * Currently only optimized for Latin-1 characters; to be extended
  427. *
  428. * @param string Input string (UTF-8)
  429. * @return string Normalized string
  430. * @deprecated since 0.9-beta
  431. */
  432. protected static function normalize_string($str)
  433. {
  434. return rcube_utils::normalize_string($str);
  435. }
  436. /**
  437. * Compose a valid display name from the given structured contact data
  438. *
  439. * @param array Hash array with contact data as key-value pairs
  440. * @param bool Don't attempt to extract components from the email address
  441. *
  442. * @return string Display name
  443. */
  444. public static function compose_display_name($contact, $full_email = false)
  445. {
  446. $contact = rcube::get_instance()->plugins->exec_hook('contact_displayname', $contact);
  447. $fn = $contact['name'];
  448. if (!$fn) // default display name composition according to vcard standard
  449. $fn = trim(join(' ', array_filter(array($contact['prefix'], $contact['firstname'], $contact['middlename'], $contact['surname'], $contact['suffix']))));
  450. // use email address part for name
  451. $email = self::get_col_values('email', $contact, true);
  452. $email = $email[0];
  453. if ($email && (empty($fn) || $fn == $email)) {
  454. // return full email
  455. if ($full_email)
  456. return $email;
  457. list($emailname) = explode('@', $email);
  458. if (preg_match('/(.*)[\.\-\_](.*)/', $emailname, $match))
  459. $fn = trim(ucfirst($match[1]).' '.ucfirst($match[2]));
  460. else
  461. $fn = ucfirst($emailname);
  462. }
  463. return $fn;
  464. }
  465. /**
  466. * Compose the name to display in the contacts list for the given contact record.
  467. * This respects the settings parameter how to list conacts.
  468. *
  469. * @param array Hash array with contact data as key-value pairs
  470. * @return string List name
  471. */
  472. public static function compose_list_name($contact)
  473. {
  474. static $compose_mode;
  475. if (!isset($compose_mode)) // cache this
  476. $compose_mode = rcube::get_instance()->config->get('addressbook_name_listing', 0);
  477. if ($compose_mode == 3)
  478. $fn = join(' ', array($contact['surname'] . ',', $contact['firstname'], $contact['middlename']));
  479. else if ($compose_mode == 2)
  480. $fn = join(' ', array($contact['surname'], $contact['firstname'], $contact['middlename']));
  481. else if ($compose_mode == 1)
  482. $fn = join(' ', array($contact['firstname'], $contact['middlename'], $contact['surname']));
  483. else if ($compose_mode == 0)
  484. $fn = !empty($contact['name']) ? $contact['name'] : join(' ', array($contact['prefix'], $contact['firstname'], $contact['middlename'], $contact['surname'], $contact['suffix']));
  485. else {
  486. $plugin = rcube::get_instance()->plugins->exec_hook('contact_listname', array('contact' => $contact));
  487. $fn = $plugin['fn'];
  488. }
  489. $fn = trim($fn, ', ');
  490. // fallbacks...
  491. if ($fn === '') {
  492. // ... display name
  493. if (!empty($contact['name'])) {
  494. $fn = $contact['name'];
  495. }
  496. // ... organization
  497. else if (!empty($contact['organization'])) {
  498. $fn = $contact['organization'];
  499. }
  500. // ... email address
  501. else if (($email = self::get_col_values('email', $contact, true)) && !empty($email)) {
  502. $fn = $email[0];
  503. }
  504. }
  505. return $fn;
  506. }
  507. /**
  508. * Build contact display name for autocomplete listing
  509. *
  510. * @param array Hash array with contact data as key-value pairs
  511. * @param string Optional email address
  512. * @param string Optional name (self::compose_list_name() result)
  513. * @param string Optional template to use (defaults to the 'contact_search_name' config option)
  514. *
  515. * @return string Display name
  516. */
  517. public static function compose_search_name($contact, $email = null, $name = null, $templ = null)
  518. {
  519. static $template;
  520. if (empty($templ) && !isset($template)) { // cache this
  521. $template = rcube::get_instance()->config->get('contact_search_name');
  522. if (empty($template)) {
  523. $template = '{name} <{email}>';
  524. }
  525. }
  526. $result = $templ ?: $template;
  527. if (preg_match_all('/\{[a-z]+\}/', $result, $matches)) {
  528. foreach ($matches[0] as $key) {
  529. $key = trim($key, '{}');
  530. $value = '';
  531. switch ($key) {
  532. case 'name':
  533. $value = $name ?: self::compose_list_name($contact);
  534. // If name(s) are undefined compose_list_name() may return an email address
  535. // here we prevent from returning the same name and email
  536. if ($name === $email && strpos($result, '{email}') !== false) {
  537. $value = '';
  538. }
  539. break;
  540. case 'email':
  541. $value = $email;
  542. break;
  543. }
  544. if (empty($value)) {
  545. $value = strpos($key, ':') ? $contact[$key] : self::get_col_values($key, $contact, true);
  546. if (is_array($value)) {
  547. $value = $value[0];
  548. }
  549. }
  550. $result = str_replace('{' . $key . '}', $value, $result);
  551. }
  552. }
  553. $result = preg_replace('/\s+/', ' ', $result);
  554. $result = preg_replace('/\s*(<>|\(\)|\[\])/', '', $result);
  555. $result = trim($result, '/ ');
  556. return $result;
  557. }
  558. /**
  559. * Create a unique key for sorting contacts
  560. */
  561. public static function compose_contact_key($contact, $sort_col)
  562. {
  563. $key = $contact[$sort_col] . ':' . $contact['sourceid'];
  564. // add email to a key to not skip contacts with the same name (#1488375)
  565. if (($email = self::get_col_values('email', $contact, true)) && !empty($email)) {
  566. $key .= ':' . implode(':', (array)$email);
  567. }
  568. return $key;
  569. }
  570. /**
  571. * Compare search value with contact data
  572. *
  573. * @param string $colname Data name
  574. * @param string|array $value Data value
  575. * @param string $search Search value
  576. * @param int $mode Search mode
  577. *
  578. * @return bool Comparision result
  579. */
  580. protected function compare_search_value($colname, $value, $search, $mode)
  581. {
  582. // The value is a date string, for date we'll
  583. // use only strict comparison (mode = 1)
  584. // @TODO: partial search, e.g. match only day and month
  585. if (in_array($colname, $this->date_cols)) {
  586. return (($value = rcube_utils::anytodatetime($value))
  587. && ($search = rcube_utils::anytodatetime($search))
  588. && $value->format('Ymd') == $search->format('Ymd'));
  589. }
  590. // composite field, e.g. address
  591. foreach ((array)$value as $val) {
  592. $val = mb_strtolower($val);
  593. switch ($mode) {
  594. case 1:
  595. $got = ($val == $search);
  596. break;
  597. case 2:
  598. $got = ($search == substr($val, 0, strlen($search)));
  599. break;
  600. default:
  601. $got = (strpos($val, $search) !== false);
  602. }
  603. if ($got) {
  604. return true;
  605. }
  606. }
  607. return false;
  608. }
  609. }