]> git.donarmstrong.com Git - roundcube.git/blobdiff - program/include/rcube_addressbook.php
Imported Upstream version 0.6+dfsg
[roundcube.git] / program / include / rcube_addressbook.php
index 982ac25285638e909f91e6c3f54fd5a79da60a79..fc8c44156457280fcb1a06096718a995beaeead3 100644 (file)
@@ -5,7 +5,7 @@
  | program/include/rcube_addressbook.php                                 |
  |                                                                       |
  | This file is part of the Roundcube Webmail client                     |
- | Copyright (C) 2006-2009, Roundcube Dev. - Switzerland                 |
+ | Copyright (C) 2006-2011, The Roundcube Dev Team                       |
  | Licensed under the GNU GPL                                            |
  |                                                                       |
  | PURPOSE:                                                              |
@@ -15,7 +15,7 @@
  | Author: Thomas Bruederli <roundcube@gmail.com>                        |
  +-----------------------------------------------------------------------+
 
- $Id: rcube_addressbook.php 4145 2010-10-27 07:23:57Z alec $
+ $Id: rcube_addressbook.php 4965 2011-07-25 11:48:50Z alec $
 
 */
 
  */
 abstract class rcube_addressbook
 {
-    /** public properties */
-    var $primary_key;
-    var $groups = false;
-    var $readonly = true;
-    var $ready = false;
-    var $list_page = 1;
-    var $page_size = 10;
+    /** constants for error reporting **/
+    const ERROR_READ_ONLY = 1;
+    const ERROR_NO_CONNECTION = 2;
+    const ERROR_INCOMPLETE = 3;
+    const ERROR_SAVING = 4;
+    const ERROR_SEARCH = 5;
+
+    /** public properties (mandatory) */
+    public $primary_key;
+    public $groups = false;
+    public $readonly = true;
+    public $undelete = false;
+    public $ready = false;
+    public $group_id = null;
+    public $list_page = 1;
+    public $page_size = 10;
+    public $coltypes = array('name' => array('limit'=>1), 'firstname' => array('limit'=>1), 'surname' => array('limit'=>1), 'email' => array('limit'=>1));
+
+    protected $error;
+
+    /**
+     * Returns addressbook name (e.g. for addressbooks listing)
+     */
+    abstract function get_name();
 
     /**
      * Save a search string for future listings
@@ -54,6 +71,16 @@ abstract class rcube_addressbook
      */
     abstract function reset();
 
+    /**
+     * Refresh saved search set after data has changed
+     *
+     * @return mixed New search set
+     */
+    function refresh_search()
+    {
+        return $this->get_search_set();
+    }
+
     /**
      * List the current set of contact records
      *
@@ -69,9 +96,11 @@ abstract class rcube_addressbook
      * @param array   List of fields to search in
      * @param string  Search value
      * @param boolean True if results are requested, False if count only
-     * @return Indexed list of contact records and 'count' value
+     * @param boolean True to skip the count query (select only)
+     * @param array   List of fields that cannot be empty
+     * @return object rcube_result_set List of contact records and 'count' value
      */
-    abstract function search($fields, $value, $strict=false, $select=true);
+    abstract function search($fields, $value, $strict=false, $select=true, $nocount=false, $required=array());
 
     /**
      * Count number of available contacts in database
@@ -97,6 +126,27 @@ abstract class rcube_addressbook
      */
     abstract function get_record($id, $assoc=false);
 
+    /**
+     * Returns the last error occured (e.g. when updating/inserting failed)
+     *
+     * @return array Hash array with the following fields: type, message
+     */
+    function get_error()
+    {
+      return $this->error;
+    }
+
+    /**
+     * Setter for errors for internal use
+     *
+     * @param int Error type (one of this class' error constants)
+     * @param string Error message (name of a text label)
+     */
+    protected function set_error($type, $message)
+    {
+      $this->error = array('type' => $type, 'message' => $message);
+    }
+
     /**
      * Close connection to source
      * Called on script shutdown
@@ -125,10 +175,36 @@ abstract class rcube_addressbook
         $this->page_size = (int)$size;
     }
 
+
+    /**
+     * Check the given data before saving.
+     * If input isn't valid, the message to display can be fetched using get_error()
+     *
+     * @param array Assoziative array with data to save
+     * @return boolean True if input is valid, False if not.
+     */
+    public function validate($save_data)
+    {
+        // check validity of email addresses
+        foreach ($this->get_col_values('email', $save_data, true) as $email) {
+            if (strlen($email)) {
+                if (!check_email(rcube_idn_to_ascii($email))) {
+                    $this->set_error('warning', rcube_label(array('name' => 'emailformaterror', 'vars' => array('email' => $email))));
+                    return false;
+                }
+            }
+        }
+
+        return true;
+    }
+
+
     /**
      * Create a new contact record
      *
      * @param array Assoziative array with save data
+     *  Keys:   Field name with optional section in the form FIELD:SECTION
+     *  Values: Field value. Can be either a string or an array of strings for multiple values
      * @param boolean True to check for duplicates first
      * @return mixed The created record ID on success, False on error
      */
@@ -137,11 +213,32 @@ abstract class rcube_addressbook
         /* empty for read-only address books */
     }
 
+    /**
+     * Create new contact records for every item in the record set
+     *
+     * @param object rcube_result_set Recordset to insert
+     * @param boolean True to check for duplicates first
+     * @return array List of created record IDs
+     */
+    function insertMultiple($recset, $check=false)
+    {
+        $ids = array();
+        if (is_object($recset) && is_a($recset, rcube_result_set)) {
+            while ($row = $recset->next()) {
+                if ($insert = $this->insert($row, $check))
+                    $ids[] = $insert;
+            }
+        }
+        return $ids;
+    }
+
     /**
      * Update a specific contact record
      *
      * @param mixed Record identifier
      * @param array Assoziative array with save data
+     *  Keys:   Field name with optional section in the form FIELD:SECTION
+     *  Values: Field value. Can be either a string or an array of strings for multiple values
      * @return boolean True on success, False on error
      */
     function update($id, $save_cols)
@@ -153,14 +250,25 @@ abstract class rcube_addressbook
      * Mark one or more contact records as deleted
      *
      * @param array  Record identifiers
+     * @param bool   Remove records irreversible (see self::undelete)
      */
-    function delete($ids)
+    function delete($ids, $force=true)
     {
         /* empty for read-only address books */
     }
 
     /**
-     * Remove all records from the database
+     * Unmark delete flag on contact record(s)
+     *
+     * @param array  Record identifiers
+     */
+    function undelete($ids)
+    {
+        /* empty for read-only address books */
+    }
+
+    /**
+     * Mark all records in database as deleted
      */
     function delete_all()
     {
@@ -176,9 +284,10 @@ abstract class rcube_addressbook
     /**
      * List all active contact groups of this source
      *
+     * @param string  Optional search string to match group name
      * @return array  Indexed list of contact groups, each a hash array
      */
-    function list_groups()
+    function list_groups($search = null)
     {
         /* empty for address books don't supporting groups */
         return array();
@@ -213,9 +322,10 @@ abstract class rcube_addressbook
      *
      * @param string Group identifier
      * @param string New name to set for this group
+     * @param string New group identifier (if changed, otherwise don't set)
      * @return boolean New name on success, false if no data was changed
      */
-    function rename_group($gid, $newname)
+    function rename_group($gid, $newname, &$newid)
     {
         /* empty for address books don't supporting groups */
         return false;
@@ -260,5 +370,99 @@ abstract class rcube_addressbook
         /* empty for address books don't supporting groups */
         return array();
     }
+
+
+    /**
+     * Utility function to return all values of a certain data column
+     * either as flat list or grouped by subtype
+     *
+     * @param string Col name
+     * @param array  Record data array as used for saving
+     * @param boolean True to return one array with all values, False for hash array with values grouped by type
+     * @return array List of column values
+     */
+    function get_col_values($col, $data, $flat = false)
+    {
+        $out = array();
+        foreach ($data as $c => $values) {
+            if (strpos($c, $col) === 0) {
+                if ($flat) {
+                    $out = array_merge($out, (array)$values);
+                }
+                else {
+                    list($f, $type) = explode(':', $c);
+                    $out[$type] = array_merge((array)$out[$type], (array)$values);
+                }
+            }
+        }
+
+        return $out;
+    }
+
+
+    /**
+     * Normalize the given string for fulltext search.
+     * Currently only optimized for Latin-1 characters; to be extended
+     *
+     * @param string Input string (UTF-8)
+     * @return string Normalized string
+     */
+    protected static function normalize_string($str)
+    {
+        // split by words
+        $arr = explode(" ", preg_replace(
+            array('/[\s;\+\-\/]+/i', '/(\d)[-.\s]+(\d)/', '/\s\w{1,3}\s/'),
+            array(' ', '\\1\\2', ' '),
+            $str));
+
+        foreach ($arr as $i => $part) {
+            if (utf8_encode(utf8_decode($part)) == $part) {  // is latin-1 ?
+                $arr[$i] = utf8_encode(strtr(strtolower(strtr(utf8_decode($part),
+                    'ÇçäâàåéêëèïîìÅÉöôòüûùÿøØáíóúñÑÁÂÀãÃÊËÈÍÎÏÓÔõÕÚÛÙýÝ',
+                    'ccaaaaeeeeiiiaeooouuuyooaiounnaaaaaeeeiiioooouuuyy')),
+                    array('ß' => 'ss', 'ae' => 'a', 'oe' => 'o', 'ue' => 'u')));
+            }
+            else
+                $arr[$i] = mb_strtolower($part);
+        }
+
+        return join(" ", $arr);
+    }
+
+
+    /**
+     * Compose a valid display name from the given structured contact data
+     *
+     * @param array  Hash array with contact data as key-value pairs
+     * @param bool   The name will be used on the list
+     *
+     * @return string Display name
+     */
+    public static function compose_display_name($contact, $list_mode = false)
+    {
+        $contact = rcmail::get_instance()->plugins->exec_hook('contact_displayname', $contact);
+        $fn = $contact['name'];
+
+        if (!$fn)
+            $fn = join(' ', array_filter(array($contact['prefix'], $contact['firstname'], $contact['middlename'], $contact['surname'], $contact['suffix'])));
+
+        // use email address part for name
+        $email = is_array($contact['email']) ? $contact['email'][0] : $contact['email'];
+
+        if ($email && (empty($fn) || $fn == $email)) {
+            // Use full email address on contacts list
+            if ($list_mode)
+                return $email;
+
+            list($emailname) = explode('@', $email);
+            if (preg_match('/(.*)[\.\-\_](.*)/', $emailname, $match))
+                $fn = trim(ucfirst($match[1]).' '.ucfirst($match[2]));
+            else
+                $fn = ucfirst($emailname);
+        }
+
+        return $fn;
+    }
+
 }