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.

693 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. // search modes
  32. const SEARCH_ALL = 0;
  33. const SEARCH_STRICT = 1;
  34. const SEARCH_PREFIX = 2;
  35. const SEARCH_GROUPS = 4;
  36. // public properties (mandatory)
  37. public $primary_key;
  38. public $groups = false;
  39. public $export_groups = true;
  40. public $readonly = true;
  41. public $searchonly = false;
  42. public $undelete = false;
  43. public $ready = false;
  44. public $group_id = null;
  45. public $list_page = 1;
  46. public $page_size = 10;
  47. public $sort_col = 'name';
  48. public $sort_order = 'ASC';
  49. public $coltypes = array('name' => array('limit'=>1), 'firstname' => array('limit'=>1), 'surname' => array('limit'=>1), 'email' => array('limit'=>1));
  50. public $date_cols = array();
  51. protected $error;
  52. /**
  53. * Returns addressbook name (e.g. for addressbooks listing)
  54. */
  55. abstract function get_name();
  56. /**
  57. * Save a search string for future listings
  58. *
  59. * @param mixed Search params to use in listing method, obtained by get_search_set()
  60. */
  61. abstract function set_search_set($filter);
  62. /**
  63. * Getter for saved search properties
  64. *
  65. * @return mixed Search properties used by this class
  66. */
  67. abstract function get_search_set();
  68. /**
  69. * Reset saved results and search parameters
  70. */
  71. abstract function reset();
  72. /**
  73. * Refresh saved search set after data has changed
  74. *
  75. * @return mixed New search set
  76. */
  77. function refresh_search()
  78. {
  79. return $this->get_search_set();
  80. }
  81. /**
  82. * List the current set of contact records
  83. *
  84. * @param array List of cols to show
  85. * @param int Only return this number of records, use negative values for tail
  86. * @return array Indexed list of contact records, each a hash array
  87. */
  88. abstract function list_records($cols=null, $subset=0);
  89. /**
  90. * Search records
  91. *
  92. * @param array List of fields to search in
  93. * @param string Search value
  94. * @param int Search mode. Sum of self::SEARCH_*.
  95. * @param boolean True if results are requested, False if count only
  96. * @param boolean True to skip the count query (select only)
  97. * @param array List of fields that cannot be empty
  98. *
  99. * @return object rcube_result_set List of contact records and 'count' value
  100. */
  101. abstract function search($fields, $value, $mode=0, $select=true, $nocount=false, $required=array());
  102. /**
  103. * Count number of available contacts in database
  104. *
  105. * @return rcube_result_set Result set with values for 'count' and 'first'
  106. */
  107. abstract function count();
  108. /**
  109. * Return the last result set
  110. *
  111. * @return rcube_result_set Current result set or NULL if nothing selected yet
  112. */
  113. abstract function get_result();
  114. /**
  115. * Get a specific contact record
  116. *
  117. * @param mixed record identifier(s)
  118. * @param boolean True to return record as associative array, otherwise a result set is returned
  119. *
  120. * @return mixed Result object with all record fields or False if not found
  121. */
  122. abstract function get_record($id, $assoc=false);
  123. /**
  124. * Returns the last error occurred (e.g. when updating/inserting failed)
  125. *
  126. * @return array Hash array with the following fields: type, message
  127. */
  128. function get_error()
  129. {
  130. return $this->error;
  131. }
  132. /**
  133. * Setter for errors for internal use
  134. *
  135. * @param int Error type (one of this class' error constants)
  136. * @param string Error message (name of a text label)
  137. */
  138. protected function set_error($type, $message)
  139. {
  140. $this->error = array('type' => $type, 'message' => $message);
  141. }
  142. /**
  143. * Close connection to source
  144. * Called on script shutdown
  145. */
  146. function close() { }
  147. /**
  148. * Set internal list page
  149. *
  150. * @param number Page number to list
  151. * @access public
  152. */
  153. function set_page($page)
  154. {
  155. $this->list_page = (int)$page;
  156. }
  157. /**
  158. * Set internal page size
  159. *
  160. * @param number Number of messages to display on one page
  161. * @access public
  162. */
  163. function set_pagesize($size)
  164. {
  165. $this->page_size = (int)$size;
  166. }
  167. /**
  168. * Set internal sort settings
  169. *
  170. * @param string $sort_col Sort column
  171. * @param string $sort_order Sort order
  172. */
  173. function set_sort_order($sort_col, $sort_order = null)
  174. {
  175. if ($sort_col != null && ($this->coltypes[$sort_col] || in_array($sort_col, $this->coltypes))) {
  176. $this->sort_col = $sort_col;
  177. }
  178. if ($sort_order != null) {
  179. $this->sort_order = strtoupper($sort_order) == 'DESC' ? 'DESC' : 'ASC';
  180. }
  181. }
  182. /**
  183. * Check the given data before saving.
  184. * If input isn't valid, the message to display can be fetched using get_error()
  185. *
  186. * @param array Assoziative array with data to save
  187. * @param boolean Attempt to fix/complete record automatically
  188. * @return boolean True if input is valid, False if not.
  189. */
  190. public function validate(&$save_data, $autofix = false)
  191. {
  192. $rcube = rcube::get_instance();
  193. $valid = true;
  194. // check validity of email addresses
  195. foreach ($this->get_col_values('email', $save_data, true) as $email) {
  196. if (strlen($email)) {
  197. if (!rcube_utils::check_email(rcube_utils::idn_to_ascii($email))) {
  198. $error = $rcube->gettext(array('name' => 'emailformaterror', 'vars' => array('email' => $email)));
  199. $this->set_error(self::ERROR_VALIDATE, $error);
  200. $valid = false;
  201. break;
  202. }
  203. }
  204. }
  205. // allow plugins to do contact validation and auto-fixing
  206. $plugin = $rcube->plugins->exec_hook('contact_validate', array(
  207. 'record' => $save_data,
  208. 'autofix' => $autofix,
  209. 'valid' => $valid,
  210. ));
  211. if ($valid && !$plugin['valid']) {
  212. $this->set_error(self::ERROR_VALIDATE, $plugin['error']);
  213. }
  214. if (is_array($plugin['record'])) {
  215. $save_data = $plugin['record'];
  216. }
  217. return $plugin['valid'];
  218. }
  219. /**
  220. * Create a new contact record
  221. *
  222. * @param array Assoziative array with save data
  223. * Keys: Field name with optional section in the form FIELD:SECTION
  224. * Values: Field value. Can be either a string or an array of strings for multiple values
  225. * @param boolean True to check for duplicates first
  226. * @return mixed The created record ID on success, False on error
  227. */
  228. function insert($save_data, $check=false)
  229. {
  230. /* empty for read-only address books */
  231. }
  232. /**
  233. * Create new contact records for every item in the record set
  234. *
  235. * @param object rcube_result_set Recordset to insert
  236. * @param boolean True to check for duplicates first
  237. * @return array List of created record IDs
  238. */
  239. function insertMultiple($recset, $check=false)
  240. {
  241. $ids = array();
  242. if (is_object($recset) && is_a($recset, rcube_result_set)) {
  243. while ($row = $recset->next()) {
  244. if ($insert = $this->insert($row, $check))
  245. $ids[] = $insert;
  246. }
  247. }
  248. return $ids;
  249. }
  250. /**
  251. * Update a specific contact record
  252. *
  253. * @param mixed Record identifier
  254. * @param array Assoziative array with save data
  255. * Keys: Field name with optional section in the form FIELD:SECTION
  256. * Values: Field value. Can be either a string or an array of strings for multiple values
  257. *
  258. * @return mixed On success if ID has been changed returns ID, otherwise True, False on error
  259. */
  260. function update($id, $save_cols)
  261. {
  262. /* empty for read-only address books */
  263. }
  264. /**
  265. * Mark one or more contact records as deleted
  266. *
  267. * @param array Record identifiers
  268. * @param bool Remove records irreversible (see self::undelete)
  269. */
  270. function delete($ids, $force=true)
  271. {
  272. /* empty for read-only address books */
  273. }
  274. /**
  275. * Unmark delete flag on contact record(s)
  276. *
  277. * @param array Record identifiers
  278. */
  279. function undelete($ids)
  280. {
  281. /* empty for read-only address books */
  282. }
  283. /**
  284. * Mark all records in database as deleted
  285. *
  286. * @param bool $with_groups Remove also groups
  287. */
  288. function delete_all($with_groups = false)
  289. {
  290. /* empty for read-only address books */
  291. }
  292. /**
  293. * Setter for the current group
  294. * (empty, has to be re-implemented by extending class)
  295. */
  296. function set_group($gid) { }
  297. /**
  298. * List all active contact groups of this source
  299. *
  300. * @param string Optional search string to match group name
  301. * @param int Search mode. Sum of self::SEARCH_*
  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. // default display name composition according to vcard standard
  449. if (!$fn) {
  450. $fn = join(' ', array_filter(array($contact['prefix'], $contact['firstname'], $contact['middlename'], $contact['surname'], $contact['suffix'])));
  451. $fn = trim(preg_replace('/\s+/', ' ', $fn));
  452. }
  453. // use email address part for name
  454. $email = self::get_col_values('email', $contact, true);
  455. $email = $email[0];
  456. if ($email && (empty($fn) || $fn == $email)) {
  457. // return full email
  458. if ($full_email)
  459. return $email;
  460. list($emailname) = explode('@', $email);
  461. if (preg_match('/(.*)[\.\-\_](.*)/', $emailname, $match))
  462. $fn = trim(ucfirst($match[1]).' '.ucfirst($match[2]));
  463. else
  464. $fn = ucfirst($emailname);
  465. }
  466. return $fn;
  467. }
  468. /**
  469. * Compose the name to display in the contacts list for the given contact record.
  470. * This respects the settings parameter how to list conacts.
  471. *
  472. * @param array Hash array with contact data as key-value pairs
  473. * @return string List name
  474. */
  475. public static function compose_list_name($contact)
  476. {
  477. static $compose_mode;
  478. if (!isset($compose_mode)) // cache this
  479. $compose_mode = rcube::get_instance()->config->get('addressbook_name_listing', 0);
  480. if ($compose_mode == 3)
  481. $fn = join(' ', array($contact['surname'] . ',', $contact['firstname'], $contact['middlename']));
  482. else if ($compose_mode == 2)
  483. $fn = join(' ', array($contact['surname'], $contact['firstname'], $contact['middlename']));
  484. else if ($compose_mode == 1)
  485. $fn = join(' ', array($contact['firstname'], $contact['middlename'], $contact['surname']));
  486. else if ($compose_mode == 0)
  487. $fn = !empty($contact['name']) ? $contact['name'] : join(' ', array($contact['prefix'], $contact['firstname'], $contact['middlename'], $contact['surname'], $contact['suffix']));
  488. else {
  489. $plugin = rcube::get_instance()->plugins->exec_hook('contact_listname', array('contact' => $contact));
  490. $fn = $plugin['fn'];
  491. }
  492. $fn = trim($fn, ', ');
  493. $fn = preg_replace('/\s+/', ' ', $fn);
  494. // fallbacks...
  495. if ($fn === '') {
  496. // ... display name
  497. if (!empty($contact['name'])) {
  498. $fn = $contact['name'];
  499. }
  500. // ... organization
  501. else if (!empty($contact['organization'])) {
  502. $fn = $contact['organization'];
  503. }
  504. // ... email address
  505. else if (($email = self::get_col_values('email', $contact, true)) && !empty($email)) {
  506. $fn = $email[0];
  507. }
  508. }
  509. return $fn;
  510. }
  511. /**
  512. * Build contact display name for autocomplete listing
  513. *
  514. * @param array Hash array with contact data as key-value pairs
  515. * @param string Optional email address
  516. * @param string Optional name (self::compose_list_name() result)
  517. * @param string Optional template to use (defaults to the 'contact_search_name' config option)
  518. *
  519. * @return string Display name
  520. */
  521. public static function compose_search_name($contact, $email = null, $name = null, $templ = null)
  522. {
  523. static $template;
  524. if (empty($templ) && !isset($template)) { // cache this
  525. $template = rcube::get_instance()->config->get('contact_search_name');
  526. if (empty($template)) {
  527. $template = '{name} <{email}>';
  528. }
  529. }
  530. $result = $templ ?: $template;
  531. if (preg_match_all('/\{[a-z]+\}/', $result, $matches)) {
  532. foreach ($matches[0] as $key) {
  533. $key = trim($key, '{}');
  534. $value = '';
  535. switch ($key) {
  536. case 'name':
  537. $value = $name ?: self::compose_list_name($contact);
  538. // If name(s) are undefined compose_list_name() may return an email address
  539. // here we prevent from returning the same name and email
  540. if ($name === $email && strpos($result, '{email}') !== false) {
  541. $value = '';
  542. }
  543. break;
  544. case 'email':
  545. $value = $email;
  546. break;
  547. }
  548. if (empty($value)) {
  549. $value = strpos($key, ':') ? $contact[$key] : self::get_col_values($key, $contact, true);
  550. if (is_array($value)) {
  551. $value = $value[0];
  552. }
  553. }
  554. $result = str_replace('{' . $key . '}', $value, $result);
  555. }
  556. }
  557. $result = preg_replace('/\s+/', ' ', $result);
  558. $result = preg_replace('/\s*(<>|\(\)|\[\])/', '', $result);
  559. $result = trim($result, '/ ');
  560. return $result;
  561. }
  562. /**
  563. * Create a unique key for sorting contacts
  564. */
  565. public static function compose_contact_key($contact, $sort_col)
  566. {
  567. $key = $contact[$sort_col] . ':' . $contact['sourceid'];
  568. // add email to a key to not skip contacts with the same name (#1488375)
  569. if (($email = self::get_col_values('email', $contact, true)) && !empty($email)) {
  570. $key .= ':' . implode(':', (array)$email);
  571. }
  572. return $key;
  573. }
  574. /**
  575. * Compare search value with contact data
  576. *
  577. * @param string $colname Data name
  578. * @param string|array $value Data value
  579. * @param string $search Search value
  580. * @param int $mode Search mode
  581. *
  582. * @return bool Comparision result
  583. */
  584. protected function compare_search_value($colname, $value, $search, $mode)
  585. {
  586. // The value is a date string, for date we'll
  587. // use only strict comparison (mode = 1)
  588. // @TODO: partial search, e.g. match only day and month
  589. if (in_array($colname, $this->date_cols)) {
  590. return (($value = rcube_utils::anytodatetime($value))
  591. && ($search = rcube_utils::anytodatetime($search))
  592. && $value->format('Ymd') == $search->format('Ymd'));
  593. }
  594. // composite field, e.g. address
  595. foreach ((array)$value as $val) {
  596. $val = mb_strtolower($val);
  597. if ($mode & self::SEARCH_STRICT) {
  598. $got = ($val == $search);
  599. }
  600. else if ($mode & self::SEARCH_PREFIX) {
  601. $got = ($search == substr($val, 0, strlen($search)));
  602. }
  603. else {
  604. $got = (strpos($val, $search) !== false);
  605. }
  606. if ($got) {
  607. return true;
  608. }
  609. }
  610. return false;
  611. }
  612. }