H4-ify Turba
authorMichael M Slusarz <slusarz@curecanti.org>
Sat, 28 Aug 2010 07:56:17 +0000 (01:56 -0600)
committerMichael M Slusarz <slusarz@curecanti.org>
Sat, 28 Aug 2010 20:54:07 +0000 (14:54 -0600)
Mainly, it is PHP 5-ifying classes and getting rid of PEAR_Errors.

56 files changed:
turba/addressbooks/create.php
turba/addressbooks/delete.php
turba/addressbooks/edit.php
turba/config/hooks.php.dist
turba/config/sources.php.dist
turba/contact.php
turba/data.php
turba/delete.php
turba/deletefile.php
turba/edit.php
turba/lib/Api.php
turba/lib/Application.php
turba/lib/Data/Ldif.php
turba/lib/Driver.php
turba/lib/Driver/Facebook.php
turba/lib/Driver/Favourites.php
turba/lib/Driver/Group.php
turba/lib/Driver/Imsp.php
turba/lib/Driver/Kolab.php
turba/lib/Driver/Kolab/Wrapper.php [new file with mode: 0644]
turba/lib/Driver/Kolab/Wrapper/New.php [new file with mode: 0644]
turba/lib/Driver/Kolab/Wrapper/Old.php [new file with mode: 0644]
turba/lib/Driver/Ldap.php
turba/lib/Driver/Prefs.php
turba/lib/Driver/Share.php
turba/lib/Driver/Sql.php
turba/lib/Driver/Vbook.php
turba/lib/Form/AddContact.php
turba/lib/Form/Contact.php
turba/lib/Form/DeleteAddressBook.php
turba/lib/Form/EditAddressBook.php
turba/lib/Form/EditContact.php
turba/lib/Form/EditContactGroup.php
turba/lib/LoginTasks/SystemTask/UpgradeLists.php
turba/lib/LoginTasks/SystemTask/UpgradePrefs.php
turba/lib/Object.php
turba/lib/Object/Group.php
turba/lib/Turba.php
turba/lib/View/Browse.php
turba/lib/View/Contact.php
turba/lib/View/DeleteContact.php
turba/lib/View/Duplicates.php
turba/lib/View/EditContact.php
turba/lib/View/List.php
turba/merge.php
turba/minisearch.php
turba/scripts/import_squirrelmail_file_abook.php
turba/scripts/import_squirrelmail_sql_abook.php
turba/scripts/import_vcards.php
turba/scripts/upgrades/2.1_to_2.2_sql_schema.php
turba/scripts/upgrades/2007-06-17_delete_old_vbooks.php
turba/scripts/upgrades/convert_datatree_shares_to_sql.php
turba/scripts/upgrades/public_to_horde_share.php
turba/search.php
turba/vcard.php
turba/view.php

index 037c985..545efa8 100644 (file)
@@ -25,7 +25,7 @@ $form = new Turba_Form_CreateAddressBook($vars);
 // Execute if the form is valid.
 if ($form->validate($vars)) {
     $result = $form->execute();
-    if (is_a($result, 'PEAR_Error')) {
+    if ($result instanceof PEAR_Error) {
         $notification->push($result, 'horde.error');
     } else {
         $notification->push(sprintf(_("The address book \"%s\" has been created."), $vars->get('name')), 'horde.success');
index ab55991..4623435 100644 (file)
@@ -44,7 +44,7 @@ $form = new Turba_Form_DeleteAddressBook($vars, $addressbook);
 // Execute if the form is valid (must pass with POST variables only).
 if ($form->validate(new Horde_Variables($_POST))) {
     $result = $form->execute();
-    if (is_a($result, 'PEAR_Error')) {
+    if ($result instanceof PEAR_Error) {
         $notification->push($result, 'horde.error');
     } elseif ($result) {
         $notification->push(sprintf(_("The addressbook \"%s\" has been deleted."), $addressbook->get('name')), 'horde.success');
index a3b1700..5ba5efa 100644 (file)
@@ -38,7 +38,7 @@ $form = new Turba_Form_EditAddressBook($vars, $addressbook);
 if ($form->validate($vars)) {
     $original_name = $addressbook->get('name');
     $result = $form->execute();
-    if (is_a($result, 'PEAR_Error')) {
+    if ($result instanceof PEAR_Error) {
         $notification->push($result, 'horde.error');
     } else {
         if ($addressbook->get('name') != $original_name) {
index 4902e21..f304b74 100644 (file)
@@ -31,22 +31,19 @@ class Turba_Hooks
 //
 //         require TURBA_BASE . '/config/sources.php';
 //         $shares = Turba::listShares(true);
-//         if (is_a($shares, 'PEAR_Error')) {
-//             return;
-//         }
 //
 //         foreach ($shares as $uid => $share) {
 //             $params = @unserialize($share->get('params'));
 //             if (empty($params['source'])) {
 //                 continue;
 //             }
-//             $driver = &Turba_Driver::factory($params['source'], $cfgSources[$params['source']]);
-//             if (is_a($driver, 'PEAR_Error')) {
-//                 continue;
-//             }
-//             if ($driver->checkDefaultShare($share, $cfgSources[$params['source']])) {
-//                 return $uid;
-//             }
+//
+//             try {
+//                 $driver = Turba_Driver::factory($params['source'], $cfgSources[$params['source']]);
+//                 if ($driver->checkDefaultShare($share, $cfgSources[$params['source']])) {
+//                     return $uid;
+//                 }
+//             } catch (Turba_Exception $e) {}
 //         }
 //     }
 // }
index 11b5a77..883c9bc 100644 (file)
@@ -832,9 +832,9 @@ if (!empty($GLOBALS['conf']['imsp']['enabled']) ||
      if (empty($cfgSources['imsp']['use_shares'])) {
         $result = Net_IMSP_Utils::getAllBooks($cfgSources['imsp']);
 
-        if (!is_a($result, 'PEAR_Error')) {
+        if (!$result instanceof PEAR_Error) {
             $resultCount = count($result);
-            for ($i = 0; $i < $resultCount; $i++) {
+            for ($i = 0; $i < $resultCount; ++$i) {
                 // Make sure we didn't define this source explicitly,
                 // but set the acls from the server regardless.
                 $dup = false;
index 08d3ed1..40b2386 100644 (file)
@@ -31,16 +31,19 @@ try {
 $contact = null;
 $uid = $vars->get('uid');
 if (!empty($uid)) {
-    $search = $driver->search(array('__uid' => $uid));
-    if (!($search instanceof PEAR_Error) && count($search)) {
-        $contact = $search->next();
-        $vars->set('key', $contact->getValue('__key'));
-    }
+    try {
+        $search = $driver->search(array('__uid' => $uid));
+        if (count($search)) {
+            $contact = $search->next();
+            $vars->set('key', $contact->getValue('__key'));
+        }
+    } catch (Turba_Exception $e) {}
 }
-if (!$contact || ($contact instanceof PEAR_Error)) {
-    $contact = $driver->getObject($vars->get('key'));
-    if ($contact instanceof PEAR_Error) {
-        $notification->push($contact->getMessage(), 'horde.error');
+if (!$contact) {
+    try {
+        $contact = $driver->getObject($vars->get('key'));
+    } catch (Turba_Exception $e) {
+        $notification->push($e, 'horde.error');
         Horde::applicationUrl($prefs->getValue('initial_page'), true)->redirect();
     }
 }
index 01b7520..d0784d2 100644 (file)
@@ -250,16 +250,12 @@ case 'export':
         }
 
         /* Get the full, sorted contact list. */
-        if (count($objectkeys)) {
-            $results = &$driver->getObjects($objectkeys);
-        } else {
-            $results = $driver->search(array());
-            if ($results instanceof Turba_List) {
-                $results = $results->objects;
-            }
-        }
-        if ($results instanceof PEAR_Error) {
-            $notification->push(sprintf(_("Failed to search the directory: %s"), $results->getMessage()), 'horde.error');
+        try {
+            $results = count($objectkeys)
+                ? $driver->getObjects($objectkeys)
+                : $driver->search(array())->objects;
+        } catch (Turba_Exception $e) {
+            $notification->push(sprintf(_("Failed to search the directory: %s"), $e->getMessage()), 'horde.error');
             $error = true;
             break;
         }
@@ -382,23 +378,26 @@ case Horde_Data::IMPORT_DATETIME:
 
 if (!$error && !empty($import_format)) {
     // TODO
-    if ($import_format == 'ldif') {
-        $data = new Turba_Data_Ldif(
-            array('browser' => $this->_injector->getInstance('Horde_Browser'),
-                  'vars' => Horde_Variables::getDefaultVariables(),
-                  'cleanup' => '_cleanupData'));
-    } else {
-        $data = $injector->getInstance('Horde_Data')->getData($import_format, array('cleanup' => '_cleanupData'));
-    }
-    if ($data instanceof PEAR_Error) {
+    try {
+        if ($import_format == 'ldif') {
+            $data = new Turba_Data_Ldif(array(
+                'browser' => $this->_injector->getInstance('Horde_Browser'),
+                'vars' => Horde_Variables::getDefaultVariables(),
+                'cleanup' => '_cleanupData'
+            ));
+        } else {
+            $data = $injector->getInstance('Horde_Data')->getData($import_format, array('cleanup' => '_cleanupData'));
+        }
+    } catch (Turba_Exception $e) {
         $notification->push(_("This file format is not supported."), 'horde.error');
+        $data = null;
         $next_step = Horde_Data::IMPORT_FILE;
-    } else {
-        $next_step = $data->nextStep($actionID, $param);
-        if ($next_step instanceof PEAR_Error) {
-            $notification->push($next_step->getMessage(), 'horde.error');
-            $next_step = $data->cleanup();
-        } else {
+    }
+
+    if ($data) {
+        try {
+            $next_step = $data->nextStep($actionID, $param);
+
             /* Raise warnings if some exist. */
             if (method_exists($data, 'warnings')) {
                 $warnings = $data->warnings();
@@ -409,6 +408,9 @@ if (!$error && !empty($import_format)) {
                     $notification->push(_("The import can be finished despite the warnings."), 'horde.message');
                 }
             }
+        } catch (Turba_Exception $e) {
+            $notification->push($e, 'horde.error');
+            $next_step = $data->cleanup();
         }
     }
 }
@@ -434,11 +436,11 @@ if (is_array($next_step)) {
     } elseif ($driver) {
         /* Purge old address book if requested. */
         if ($_SESSION['import_data']['purge']) {
-            $result = $driver->deleteAll();
-            if ($result instanceof PEAR_Error) {
-                $notification->push(sprintf(_("The address book could not be purged: %s"), $result->getMessage()), 'horde.error');
-            } else {
+            try {
+                $driver->deleteAll();
                 $notification->push(_("Address book successfully purged."), 'horde.success');
+            } catch (Turba_Exception $e) {
+                $notification->push(sprintf(_("The address book could not be purged: %s"), $e->getMessage()), 'horde.error');
             }
         }
 
@@ -449,13 +451,15 @@ if (is_array($next_step)) {
             }
 
             /* Don't search for empty attributes. */
-            $row = array_filter($row, '_emptyAttributeFilter');
-            $result = $driver->search($row);
-            if ($result instanceof PEAR_Error) {
-                $notification->push($result, 'horde.error');
+            try {
+                $result = $driver->search(array_filter($row, '_emptyAttributeFilter'));
+            } catch (Turba_Exception $e) {
+                $notification->push($e, 'horde.error');
                 $error = true;
                 break;
-            } elseif (count($result)) {
+            }
+
+            if (count($result)) {
                 $result->reset();
                 $object = $result->next();
                 $notification->push(sprintf(_("\"%s\" already exists and was not imported."),
@@ -470,10 +474,11 @@ if (is_array($next_step)) {
                     }
                 }
                 $row['__owner'] = $driver->getContactOwner();
-                $result = $driver->add($row);
-                if (is_a($result, 'PEAR_Error')) {
-                    $notification->push(sprintf(_("There was an error importing the data: %s"),
-                                                $result->getMessage()), 'horde.error');
+
+                try {
+                    $driver->add($row);
+                } catch (Turba_Exception $e) {
+                    $notification->push(sprintf(_("There was an error importing the data: %s"), $e->getMessage()), 'horde.error');
                     $error = true;
                     break;
                 }
index 63c9519..bcc32f2 100644 (file)
@@ -21,28 +21,25 @@ $key = Horde_Util::getFormData('key');
 $driver = $injector->getInstance('Turba_Driver')->getDriver($source);
 
 if ($conf['documents']['type'] != 'none') {
-    $object = $driver->getObject($key);
-    if ($object instanceof PEAR_Error) {
-        $notification->push($object->getMessage(), 'horde.error');
-        Horde::applicationUrl($prefs->getValue('initial_page'), true)->redirect();
-    }
-
-    $deleted = $object->deleteFiles();
-    if ($deleted instanceof PEAR_Error) {
-        $notification->push($deleted, 'horde.error');
+    try {
+        $object = $driver->getObject($key);
+        $object->deleteFiles();
+    } catch (Turba_Exception $e) {
+        $notification->push($e, 'horde.error');
         Horde::applicationUrl($prefs->getValue('initial_page'), true)->redirect();
     }
 }
 
-$result = $driver->delete($key);
-if (!($result instanceof PEAR_Error)) {
+try {
+    $driver->delete($key);
     $url = ($url = Horde_Util::getFormData('url'))
         ? new Horde_Url($url)
         : Horde::applicationUrl($prefs->getValue('initial_page'), true);
     $url->redirect();
+} catch (Turba_Exception $e) {
+    $notification->push(sprintf(_("There was an error deleting this contact: %s"), $e->getMessage()), 'horde.error');
 }
 
-$notification->push(sprintf(_("There was an error deleting this contact: %s"), $result->getMessage()), 'horde.error');
 $title = _("Deletion failed");
 require TURBA_TEMPLATES . '/common-header.inc';
 require TURBA_TEMPLATES . '/menu.inc';
index f49aa2e..2ca5f0d 100644 (file)
@@ -24,9 +24,11 @@ if ($source === null || !isset($cfgSources[$source])) {
 }
 
 $driver = $injector->getInstance('Turba_Driver')->getDriver($source);
-$contact = $driver->getObject(Horde_Util::getPost('key'));
-if (is_a($contact, 'PEAR_Error')) {
-    $notification->push($contact, 'horde.error');
+
+try {
+    $contact = $driver->getObject(Horde_Util::getPost('key'));
+} catch (Turba_Exception $e) {
+    $notification->push($e, 'horde.error');
     Horde::applicationUrl($prefs->getValue('initial_page'), true)->redirect();
 }
 
@@ -36,10 +38,12 @@ if (!$contact->isEditable()) {
 }
 
 $file = Horde_Util::getPost('file');
-$result = $contact->deleteFile($file);
-if (is_a($result, 'PEAR_Error')) {
-    $notification->push($result, 'horde.error');
-} else {
+
+try {
+    $contact->deleteFile($file);
     $notification->push(sprintf(_("The file \"%s\" has been deleted."), $file), 'horde.success');
+} catch (Turba_Exception $e) {
+    $notification->push($e, 'horde.error');
 }
+
 $contact->url('Contact', true)->redirect();
index 899aae4..d2caad5 100644 (file)
@@ -48,9 +48,10 @@ if ($source === null || !isset($cfgSources[$source])) {
 $driver = $injector->getInstance('Turba_Driver')->getDriver($source);
 
 /* Set the contact from the requested key. */
-$contact = $driver->getObject($key);
-if (is_a($contact, 'PEAR_Error')) {
-    $notification->push($contact, 'horde.error');
+try {
+    $contact = $driver->getObject($key);
+} catch (Turba_Exception $e) {
+    $notification->push($e, 'horde.error');
     $url->redirect();
 }
 
@@ -74,7 +75,7 @@ if ($groupedit) {
 
 /* Execute() checks validation first. */
 $edited = $form->execute();
-if (!is_a($edited, 'PEAR_Error')) {
+if (!($edited instanceof PEAR_Error)) {
     $url = Horde_Util::getFormData('url');
     if (empty($url)) {
         $url = $contact->url('Contact', true);
index 8ab43e8..ba47d65 100644 (file)
@@ -52,10 +52,7 @@ class Turba_Api extends Horde_Registry_Api
         if (isset($GLOBALS['cfgSources'][$source]) && $key) {
             try {
                 $driver = $GLOBALS['injector']->getInstance('Turba_Driver')->getDriver($source);
-                $object = $driver->getObject($key);
-                if (!($object instanceof PEAR_Error)) {
-                    return $object->getValue('name');
-                }
+                $object = $driver->getObject($key)->getValue('name');
             } catch (Turba_Exception $e) {}
         }
 
@@ -135,11 +132,13 @@ class Turba_Api extends Horde_Registry_Api
                 if (empty($params['source'])) {
                     continue;
                 }
-                $driver = Turba_Driver::factory($params['source'], $cfgSources[$params['source']]);
-                if (!($driver instanceof PEAR_Error) &&
-                    $driver->checkDefaultShare($share, $cfgSources[$params['source']])) {
-                    return $uid;
-                }
+
+                try {
+                    $driver = Turba_Driver::factory($params['source'], $cfgSources[$params['source']]);
+                    if ($driver->checkDefaultShare($share, $cfgSources[$params['source']])) {
+                        return $uid;
+                    }
+                } catch (Turba_Exception $e) {}
             }
         }
 
@@ -325,9 +324,6 @@ class Turba_Api extends Horde_Registry_Api
             $driver = $GLOBALS['injector']->getInstance('Turba_Driver')->getDriver($parts[1]);
 
             $contacts = $driver->search(array());
-            if ($contacts instanceof PEAR_Error) {
-                throw new Turba_Exception($contacts);
-            }
 
             $contacts->reset();
             $curpath = 'turba/' . $parts[0] . '/' . $parts[1] . '/';
@@ -346,8 +342,9 @@ class Turba_Api extends Horde_Registry_Api
                     $results[$key]['contenttype'] = 'text/x-vcard';
                 }
                 if (in_array('contentlength', $properties)) {
-                    $data = $this->export($contact->getValue('__uid'), 'text/x-vcard', $contact->getSource());
-                    if ($data instanceof PEAR_Error) {
+                    try {
+                        $data = $this->export($contact->getValue('__uid'), 'text/x-vcard', $contact->getSource());
+                    } catch (Turba_Exception $e) {
                         $data = '';
                     }
                     $results[$key]['contentlength'] = strlen($data);
@@ -376,9 +373,6 @@ class Turba_Api extends Horde_Registry_Api
             $driver = $GLOBALS['injector']->getInstance('Turba_Driver')->getDriver($parts[1]);
 
             $contact = $driver->getObject($parts[2]);
-            if ($contact instanceof PEAR_Error) {
-                throw new Turba_Exception($contact);
-            }
 
             $result = array('data' => $this->export($contact->getValue('__uid'), 'text/x-vcard', $contact->getSource()),
                 'mimetype' => 'text/x-vcard');
@@ -425,12 +419,7 @@ class Turba_Api extends Horde_Registry_Api
         // Load the Turba driver.
         $driver = $GLOBALS['injector']->getInstance('Turba_Driver')->getDriver($parts[1]);
 
-        $ret = $driver->delete($parts[2]);
-        if ($ret instanceof PEAR_Error) {
-            throw new Turba_Exception($ret->getMessage());
-        }
-
-        return $ret;
+        return $driver->delete($parts[2]);
     }
 
     /**
@@ -470,9 +459,10 @@ class Turba_Api extends Horde_Registry_Api
 
             $storage = $GLOBALS['injector']->getInstance('Turba_Driver')->getDriver($source);
 
-            $results = $storage->search(array());
-            if ($results instanceof PEAR_Error) {
-                throw new Turba_Exception(sprintf(_("Error searching the address book: %s"), $results->getMessage()));
+            try {
+                $results = $storage->search(array());
+            } catch (Turba_Exception $e) {
+                throw new Turba_Exception(sprintf(_("Error searching the address book: %s"), $e->getMessage()));
             }
 
             foreach ($results->objects as $o) {
@@ -663,15 +653,11 @@ class Turba_Api extends Horde_Registry_Api
                         if ($c instanceof Horde_Icalendar_Vcard) {
                             $content = $driver->toHash($c);
                             $result = $driver->search($content);
-                            if ($result instanceof PEAR_Error) {
-                                throw new Turba_Exception($result);
-                            } elseif (count($result)) {
+                            if (count($result)) {
                                 continue;
                             }
-                            $result = $driver->add($content);
-                            if ($result instanceof PEAR_Error) {
-                                throw new Turba_Exception($result);
-                            }
+
+                            $driver->add($content);
                             if (!empty($content['category']) &&
                                 !in_array($content['category'], $categories)) {
                                     $cManager->add($content['category']);
@@ -699,27 +685,19 @@ class Turba_Api extends Horde_Registry_Api
 
         // Check if the entry already exists in the data source:
         $result = $driver->search($content);
-        if ($result instanceof PEAR_Error) {
-            throw new Turba_Exception($result->getMessage());
-        } elseif (count($result)) {
+        if (count($result)) {
             $o = $result->objects[0];
             throw new Turba_Exception(_("Already Exists"));
         }
 
-        $result = $driver->add($content);
-        if ($result instanceof PEAR_Error) {
-            throw new Turba_Exception($result->getMessage());
-        }
+        $driver->add($content);
 
         if (!empty($content['category']) &&
             !in_array($content['category'], $categories)) {
                 $cManager->add($content['category']);
             }
 
-        $object = $driver->getObject($result);
-        return ($object instanceof PEAR_Error)
-            ? $object
-            : $object->getValue('__uid');
+        return $driver->getObject($result)->getValue('__uid');
     }
 
     /**
@@ -774,15 +752,12 @@ class Turba_Api extends Horde_Registry_Api
             }
 
             $result = $driver->search(array('__uid' => $uid));
-            if ($result instanceof PEAR_Error) {
-                throw new Turba_Exception($result->getMessage());
-            } elseif (count($result) == 0) {
+            if (count($result) == 0) {
                 continue;
             } elseif (count($result) > 1) {
                 throw new Turba_Exception("Internal Horde Error: multiple turba objects with same objectId.");
             }
 
-
             $version = '3.0';
             list($contentType,) = explode(';', $contentType);
             switch ($contentType) {
@@ -881,15 +856,16 @@ class Turba_Api extends Horde_Registry_Api
             throw new Turba_Exception(_("You don't have sufficient permissions to read the address book that contains your own contact."));
         }
 
-        $contact = $driver->getObject($id);
-        if ($contact instanceof PEAR_Error) {
+        try {
+            $contact = $driver->getObject($id);
+        } catch (Turba_Exception $e) {
             throw new Turba_Exception(_("Your own contact cannot be found in the address book."));
         }
 
-        $return = array('contact' => $contact,
-            'source'=> $source);
-
-        return $return;
+        return array(
+            'contact' => $contact,
+            'source'=> $source
+        );
     }
 
     /**
@@ -949,14 +925,12 @@ class Turba_Api extends Horde_Registry_Api
             // If the objectId isn't in $source in the first place, just return
             // true. Otherwise, try to delete it and return success or failure.
             $result = $driver->search(array('__uid' => $uid));
-            if ($result instanceof PEAR_Error) {
-                throw new Turba_Exception($result->getMessage());
-            } elseif (count($result) == 0) {
+            if (count($result) == 0) {
                 continue;
-            } else {
-                $r = $result->objects[0];
-                return $driver->delete($r->getValue('__key'));
             }
+
+            $r = $result->objects[0];
+            return $driver->delete($r->getValue('__key'));
         }
 
         return true;
@@ -1009,9 +983,7 @@ class Turba_Api extends Horde_Registry_Api
                 continue;
             }
             $result = $driver->search(array('__uid' => $uid));
-            if ($result instanceof PEAR_Error) {
-                throw new Turba_Exception($result);
-            } elseif (!count($result)) {
+            if (!count($result)) {
                 continue;
             } elseif (count($result) > 1) {
                 throw new Turba_Exception(_("Multiple contacts found with same unique ID."));
@@ -1287,9 +1259,6 @@ class Turba_Api extends Horde_Registry_Api
             $driver = $GLOBALS['injector']->getInstance('Turba_Driver')->getDriver($source);
 
             $object = $driver->getObject($objectId);
-            if ($object instanceof PEAR_Error) {
-                throw new Turba_Exception($object);
-            }
 
             $attributes = array();
             foreach ($cfgSources[$source]['map'] as $field => $map) {
@@ -1326,9 +1295,6 @@ class Turba_Api extends Horde_Registry_Api
             $driver = $GLOBALS['injector']->getInstance('Turba_Driver')->getDriver($source);
 
             $objects = $driver->getObjects($objectIds);
-            if ($objects instanceof PEAR_Error) {
-                throw new Turba_Exception($objects);
-            }
 
             foreach ($objects as $object) {
                 $attributes = array();
@@ -1435,11 +1401,7 @@ class Turba_Api extends Horde_Registry_Api
         foreach ($time_categories as $category) {
             list($category, $source) = explode('/', $category, 2);
             $driver = $GLOBALS['injector']->getInstance('Turba_Driver')->getDriver($source);
-            $new_objects = $driver->listTimeObjects($start, $end, $category);
-            if ($new_objects instanceof PEAR_Error) {
-                throw new Turba_Exception($new_objects);
-            }
-            $objects = array_merge($objects, $new_objects);
+            $objects = array_merge($objects, $driver->listTimeObjects($start, $end, $category));
         }
 
         return $objects;
@@ -1456,9 +1418,9 @@ class Turba_Api extends Horde_Registry_Api
     }
 
     /**
-     * Returns the availabble client fields
+     * Returns the available client fields
      *
-     * @return mixed  An array describing the fields | PEAR_Error
+     * @return array  An array describing the fields.
      */
     public function clientFields()
     {
@@ -1470,7 +1432,8 @@ class Turba_Api extends Horde_Registry_Api
      *
      * @param string $objectId  Client unique ID
      *
-     * @return mixed  Array of client data | PEAR_Error
+     * @return array  Array of client data.
+     * @throws Turba_Exception
      */
     public function getClient($objectId = '')
     {
@@ -1482,7 +1445,8 @@ class Turba_Api extends Horde_Registry_Api
      *
      * @param array $objectIds  client unique ids
      *
-     * @return mixed  An array of clients data | PEAR_Error
+     * @return array  An array of clients data.
+     * @throws Turba_Exception
      */
     public function getClients($objectIds = array())
     {
@@ -1531,7 +1495,8 @@ class Turba_Api extends Horde_Registry_Api
      * @param array $fields        The fields to serach in
      * @param boolean $matchBegin  Match word boundaries only
      *
-     * @return mixed  A hash containing the search results | PEAR_Error
+     * @return array  A hash containing the search results.
+     * @throws Turba_Exception
      */
     public function searchClients($names = array(), $fields = array(),
                                   $matchBegin = false)
@@ -1541,7 +1506,8 @@ class Turba_Api extends Horde_Registry_Api
             array($GLOBALS['conf']['client']['addressbook']),
             array($GLOBALS['conf']['client']['addressbook'] => $fields),
             $matchBegin,
-            true);
+            true
+        );
     }
 
     /**
@@ -1584,24 +1550,27 @@ class Turba_Api extends Horde_Registry_Api
             throw new Turba_Exception(_("Permission denied"));
         }
 
-        $res = $driver->search(array('email' => trim($address)), null, 'AND');
-        if ($res instanceof PEAR_Error) {
+        try {
+            $res = $driver->search(array('email' => trim($address)), null, 'AND');
+        } catch (Turba_Exception $e) {
             throw new Turba_Exception(sprintf(_("Search failed: %s"), $res->getMessage()));
         }
 
         if (count($res) > 1) {
-            $res2 = $driver->search(array('email' => trim($address), 'name' => trim($name)), null, 'AND');
-            if ($res2 instanceof PEAR_Error) {
-                throw new Turba_Exception(sprintf(_("Search failed: %s"), $res2->getMessage()));
+            try {
+                $res2 = $driver->search(array('email' => trim($address), 'name' => trim($name)), null, 'AND');
+            } catch (Turba_Exception $e) {
+                throw new Turba_Exception(sprintf(_("Search failed: %s"), $e->getMessage()));
             }
 
             if (!count($res2)) {
                 throw new Turba_Exception(sprintf(_("Multiple persons with address [%s], but none with name [%s] already exist"), trim($address), trim($name)));
             }
 
-            $res3 = $driver->search(array('email' => $address, 'name' => $name, $field => $value));
-            if ($res3 instanceof PEAR_Error) {
-                throw new Turba_Exception(sprintf(_("Search failed: %s"), $res3->getMessage()));
+            try {
+                $res3 = $driver->search(array('email' => $address, 'name' => $name, $field => $value));
+            } catch (Turba_Exception $e) {
+                throw new Turba_Exception(sprintf(_("Search failed: %s"), $e->getMessage()));
             }
 
             if (count($res3)) {
@@ -1612,9 +1581,10 @@ class Turba_Api extends Horde_Registry_Api
             $ob->setValue($field, $value);
             $ob->store();
         } elseif (count($res) == 1) {
-            $res4 = $driver->search(array('email' => $address, $field => $value));
-            if ($res4 instanceof PEAR_Error) {
-                throw new Turba_Exception(sprintf(_("Search failed: %s"), $res4->getMessage()));
+            try {
+                $res4 = $driver->search(array('email' => $address, $field => $value));
+            } catch (Turba_Exception $e) {
+                throw new Turba_Exception(sprintf(_("Search failed: %s"), $e->getMessage()));
             }
 
             if (count($res4)) {
@@ -1627,8 +1597,6 @@ class Turba_Api extends Horde_Registry_Api
         } else {
             return $driver->add(array('email' => $address, 'name' => $name, $field => $value, '__owner' => $GLOBALS['registry']->getAuth()));
         }
-
-        return;
     }
 
     /**
@@ -1690,6 +1658,7 @@ class Turba_Api extends Horde_Registry_Api
         } elseif (empty($result)) {
             throw new Turba_Exception(sprintf(_("No %s entry found for %s"), $field, $address));
         }
+
         return reset($result);
     }
 
@@ -1747,8 +1716,6 @@ class Turba_Api extends Horde_Registry_Api
         if (!$success) {
             throw new Turba_Exception(sprintf(_("No %s entry found for %s"), $field, $address));
         }
-
-        return;
     }
 
 }
index 821b57c..579d486 100644 (file)
@@ -411,9 +411,10 @@ class Turba_Application extends Horde_Registry_Application
                     continue;
                 }
 
-                $result = $driver->removeUserData($user);
-                if ($result instanceof PEAR_Error) {
-                    Horde::logMessage($result, 'ERR');
+                try {
+                    $driver->removeUserData($user);
+                } catch (Turba_Exception $e) {
+                    Horde::logMessage($e, 'ERR');
                 }
             }
         }
@@ -435,9 +436,10 @@ class Turba_Application extends Horde_Registry_Application
                         continue;
                     }
 
-                    $result = $driver->removeUserData($user);
-                    if ($result instanceof PEAR_Error) {
-                        Horde::logMessage($result, 'ERR');
+                    try {
+                        $driver->removeUserData($user);
+                    } catch (Turba_Exception $e) {
+                        Horde::logMessage($e, 'ERR');
                         $hasError = true;
                     }
                 }
index 39be80e..36ff5b4 100644 (file)
@@ -217,15 +217,13 @@ class Turba_Data_Ldif extends Horde_Data
      *
      * @return mixed  Either the next step as an integer constant or imported
      *                data set after the final step.
+     * @throws Horde_Data_Exception
      */
     function nextStep($action, $param = array())
     {
         switch ($action) {
         case Horde_Data::IMPORT_FILE:
-            $next_step = parent::nextStep($action, $param);
-            if (is_a($next_step, 'PEAR_Error')) {
-                return $next_step;
-            }
+            parent::nextStep($action, $param);
 
             $_SESSION['import_data']['data'] = $this->importFile($_FILES['import_file']['tmp_name']);
             $data = array();
index a110d43..2e2127f 100644 (file)
@@ -4,25 +4,25 @@
  * various directory search drivers.  It includes functions for searching,
  * adding, removing, and modifying directory entries.
  *
- * @author  Chuck Hagenbuch <chuck@horde.org>
- * @author  Jon Parise <jon@csh.rit.edu>
- * @package Turba
+ * Copyright 2000-2010 The Horde Project (http://www.horde.org/)
+ *
+ * See the enclosed file LICENSE for license information (ASL).  If you did
+ * did not receive this file, see http://www.horde.org/licenses/asl.php.
+ *
+ * @author   Chuck Hagenbuch <chuck@horde.org>
+ * @author   Jon Parise <jon@csh.rit.edu>
+ * @category Horde
+ * @license  http://www.horde.org/licenses/asl.php ASL
+ * @package  Turba
  */
 class Turba_Driver implements Countable
 {
     /**
-     * The internal name of this source.
-     *
-     * @var string
-     */
-    var $name;
-
-    /**
      * The symbolic title of this source.
      *
      * @var string
      */
-    var $title;
+    public $title;
 
     /**
      * Hash describing the mapping between Turba attributes and
@@ -30,14 +30,14 @@ class Turba_Driver implements Countable
      *
      * @var array
      */
-    var $map = array();
+    public $map = array();
 
     /**
      * Hash with all tabs and their fields.
      *
      * @var array
      */
-    var $tabs = array();
+    public $tabs = array();
 
     /**
      * List of all fields that can be accessed in the backend (excludes
@@ -45,14 +45,14 @@ class Turba_Driver implements Countable
      *
      * @var array
      */
-    var $fields = array();
+    public $fields = array();
 
     /**
      * Array of fields that must match exactly.
      *
      * @var array
      */
-    var $strict = array();
+    public $strict = array();
 
     /**
      * Array of fields to search "approximately" (@see
@@ -60,14 +60,14 @@ class Turba_Driver implements Countable
      *
      * @var array
      */
-    var $approximate = array();
+    public $approximate = array();
 
     /**
      * The name of a field to store contact list names in if not the default.
      *
      * @var string
      */
-    var $listNameField = null;
+    public $listNameField = null;
 
     /**
      * The name of a field to use as an alternative to the name field if that
@@ -75,35 +75,42 @@ class Turba_Driver implements Countable
      *
      * @var string
      */
-    var $alternativeName = null;
+    public $alternativeName = null;
+
+    /**
+     * The internal name of this source.
+     *
+     * @var string
+     */
+    protected $_name;
 
     /**
      * Hash holding the driver's additional parameters.
      *
      * @var array
      */
-    var $_params = array();
+    protected $_params = array();
 
     /**
      * What can this backend do?
      *
      * @var array
      */
-    var $_capabilities = array();
+    protected $_capabilities = array();
 
     /**
      * Number of contacts in this source.
      *
      * @var integer
      */
-    var $_count = null;
+    protected $_count = null;
 
     /**
      * Hold the value for the owner of this address book.
      *
      * @var string
      */
-    var $_contact_owner = '';
+    protected $_contact_owner = '';
 
     /**
      * Constructs a new Turba_Driver object.
@@ -111,7 +118,7 @@ class Turba_Driver implements Countable
      * @param array $params  Hash containing additional configuration
      *                       parameters.
      */
-    function Turba_Driver($params)
+    public function __construct($params = array())
     {
         $this->_params = $params;
     }
@@ -121,7 +128,7 @@ class Turba_Driver implements Countable
      *
      * @return array  Hash containing the driver's additional parameters.
      */
-    function getParams()
+    public function getParams()
     {
         return $this->_params;
     }
@@ -133,7 +140,7 @@ class Turba_Driver implements Countable
      *
      * @return boolean  Supported or not.
      */
-    function hasCapability($capability)
+    public function hasCapability($capability)
     {
         return !empty($this->_capabilities[$capability]);
     }
@@ -143,7 +150,7 @@ class Turba_Driver implements Countable
      *
      * @return array  List of blob attributes in the array keys.
      */
-    function getBlobs()
+    public function getBlobs()
     {
         global $attributes;
 
@@ -167,7 +174,7 @@ class Turba_Driver implements Countable
      *
      * @return array  Translated version of $hash.
      */
-    function toDriverKeys($hash)
+    public function toDriverKeys($hash)
     {
         /* Handle category. */
         if (!empty($hash['category'])) {
@@ -182,7 +189,8 @@ class Turba_Driver implements Countable
         // and the composite field will be saved to storage.
         // Otherwise composite fields won't be computed during an import.
         foreach ($this->map as $key => $val) {
-            if (!is_array($val) || empty($this->map[$key]['attribute']) ||
+            if (!is_array($val) ||
+                empty($this->map[$key]['attribute']) ||
                 array_key_exists($key, $hash)) {
                 continue;
             }
@@ -196,11 +204,13 @@ class Turba_Driver implements Countable
             }
         }
 
-        if (!empty($hash['name']) && !empty($this->listNameField) &&
-            !empty($hash['__type']) && is_array($this->map['name']) &&
-            $hash['__type'] == 'Group') {
-                $hash[$this->listNameField] = $hash['name'];
-                unset($hash['name']);
+        if (!empty($hash['name']) &&
+            !empty($this->listNameField) &&
+            !empty($hash['__type']) &&
+            is_array($this->map['name']) &&
+            ($hash['__type'] == 'Group')) {
+            $hash[$this->listNameField] = $hash['name'];
+            unset($hash['name']);
         }
 
         $fields = array();
@@ -211,19 +221,20 @@ class Turba_Driver implements Countable
                 } elseif (!empty($this->map[$key]['attribute'])) {
                     $fieldarray = array();
                     foreach ($this->map[$key]['fields'] as $mapfields) {
-                        if (isset($hash[$mapfields])) {
-                            $fieldarray[] = $hash[$mapfields];
-                        } else {
-                            $fieldarray[] = '';
-                        }
+                        $fieldarray[] = isset($hash[$mapfields])
+                            ? $hash[$mapfields]
+                            : '';
                     }
                     $fields[$this->map[$key]['attribute']] = preg_replace('/\s+/', ' ', trim(vsprintf($this->map[$key]['format'], $fieldarray), " \t\n\r\0\x0B,"));
                 } else {
                     // If 'parse' is not specified, use 'format' and 'fields'.
                     if (!isset($this->map[$key]['parse'])) {
                         $this->map[$key]['parse'] = array(
-                            array('format' => $this->map[$key]['format'],
-                                  'fields' => $this->map[$key]['fields']));
+                            array(
+                                'format' => $this->map[$key]['format'],
+                                'fields' => $this->map[$key]['fields']
+                            )
+                        );
                     }
                     foreach ($this->map[$key]['parse'] as $parse) {
                         $splitval = sscanf($val, $parse['format']);
@@ -264,15 +275,12 @@ class Turba_Driver implements Countable
      *
      * @return array  An array of search criteria.
      */
-    function makeSearch($criteria, $search_type, $strict, $match_begin = false)
+    public function makeSearch($criteria, $search_type, $strict,
+                               $match_begin = false)
     {
-        $search = array();
-        $strict_search = array();
-        $search_terms = array();
-        $subsearch = array();
-        $temp = '';
+        $search = $search_terms = $subsearch = $strict_search = array();
+        $glue = $temp = '';
         $lastChar = '\"';
-        $glue = '';
 
         foreach ($criteria as $key => $val) {
             if (isset($this->map[$key])) {
@@ -282,7 +290,7 @@ class Turba_Driver implements Countable
                     if (count($parts) > 1) {
                         /* Only parse if there was more than 1 search term and
                          * 'AND' the cumulative subsearches. */
-                        for ($i = 0; $i < count($parts); $i++) {
+                        for ($i = 0; $i < count($parts); ++$i) {
                             $term = $parts[$i];
                             $firstChar = substr($term, 0, 1);
                             if ($firstChar == '"') {
@@ -293,11 +301,10 @@ class Turba_Driver implements Countable
                                     if ($lastChar == '"') {
                                         $temp .= ' ' . substr($parts[$i + 1], 0, -1);
                                         $done = true;
-                                        $i++;
                                     } else {
                                         $temp .= ' ' . $parts[$i + 1];
-                                        $i++;
                                     }
+                                    ++$i;
                                 }
                                 $search_terms[] = $temp;
                             } else {
@@ -312,6 +319,7 @@ class Turba_Driver implements Countable
                         $search_terms[0] = $val;
                         $glue = 'OR';
                     }
+
                     foreach ($this->map[$key]['fields'] as $field) {
                         $field = $this->toDriver($field);
                         if (!empty($strict[$field])) {
@@ -329,7 +337,7 @@ class Turba_Driver implements Countable
                                 /* Build the 'OR' search for each search term
                                  * on this field. */
                                 $atomsearch = array();
-                                for ($i = 0; $i < count($search_terms); $i++) {
+                                for ($i = 0; $i < count($search_terms); ++$i) {
                                     $atomsearch[] = array(
                                         'field' => $field,
                                         'op' => 'LIKE',
@@ -389,15 +397,25 @@ class Turba_Driver implements Countable
         }
 
         if (count($strict_search) && count($search)) {
-            return array('AND' => array($search_type => $strict_search,
-                                        array($search_type => $search)));
+            return array(
+                'AND' => array(
+                    $search_type => $strict_search,
+                    array(
+                        $search_type => $search
+                    )
+                )
+            );
         } elseif (count($strict_search)) {
-            return array('AND' => $strict_search);
+            return array(
+                'AND' => $strict_search
+            );
         } elseif (count($search)) {
-            return array($search_type => $search);
-        } else {
-            return array();
+            return array(
+                $search_type => $search
+            );
         }
+
+        return array();
     }
 
     /**
@@ -409,17 +427,15 @@ class Turba_Driver implements Countable
      *
      * @return string  The driver name for this attribute.
      */
-    function toDriver($attribute)
+    public function toDriver($attribute)
     {
         if (!isset($this->map[$attribute])) {
             return null;
         }
 
-        if (is_array($this->map[$attribute])) {
-            return $this->map[$attribute]['fields'];
-        } else {
-            return $this->map[$attribute];
-        }
+        return is_array($this->map[$attribute])
+            ? $this->map[$attribute]['fields']
+            : $this->map[$attribute];
     }
 
     /**
@@ -431,17 +447,17 @@ class Turba_Driver implements Countable
      *
      * @return array  Translated version of $entry.
      */
-    function toTurbaKeys($entry)
+    public function toTurbaKeys($entry)
     {
         $new_entry = array();
         foreach ($this->map as $key => $val) {
             if (!is_array($val)) {
-                $new_entry[$key] = null;
-                if (isset($entry[$val]) && strlen($entry[$val])) {
-                    $new_entry[$key] = trim($entry[$val]);
-                }
+                $new_entry[$key] = (isset($entry[$val]) && strlen($entry[$val]))
+                    ? trim($entry[$val])
+                    : null;
             }
         }
+
         return $new_entry;
     }
 
@@ -462,11 +478,12 @@ class Turba_Driver implements Countable
      * @param boolean $match_begin    Whether to match only at beginning of
      *                                words.
      *
-     * @return  The sorted, filtered list of search results.
+     * @return Turba_List  The sorted, filtered list of search results.
+     * @throws Turba_Exception
      */
-    function &search($search_criteria, $sort_order = null,
-                     $search_type = 'AND', $return_fields = array(),
-                     $custom_strict = array(), $match_begin = false)
+    public function search($search_criteria, $sort_order = null,
+                           $search_type = 'AND', $return_fields = array(),
+                           $custom_strict = array(), $match_begin = false)
     {
         /* If we are not using Horde_Share, enforce the requirement that the
          * current user must be the owner of the addressbook. */
@@ -512,12 +529,8 @@ class Turba_Driver implements Countable
 
         /* Retrieve the search results from the driver. */
         $objects = $this->_search($fields, $return_fields);
-        if (is_a($objects, 'PEAR_Error')) {
-            return $objects;
-        }
 
-        $results = $this->_toTurbaObjects($objects, $sort_order);
-        return $results;
+        return $this->_toTurbaObjects($objects, $sort_order);
     }
 
     /**
@@ -527,9 +540,9 @@ class Turba_Driver implements Countable
      * first name values.
      *
      * @return array  A hash with the following format:
-     *                <code>
-     *                array('name' => array('John Doe' => Turba_List, ...), ...)
-     *                </code>
+     * <code>
+     * array('name' => array('John Doe' => Turba_List, ...), ...)
+     * </code>
      * @throws Turba_Exception
      */
     public function searchDuplicates()
@@ -544,14 +557,17 @@ class Turba_Driver implements Countable
      * @param array $objects  An array of object hashes (keyed to backend).
      * @param array $order    Array of hashes describing sort fields.  Each
      *                        hash has the following fields:
-     *                        - field:     String sort field
-     *                        - ascending: Boolean indicating sort direction
+     * <pre>
+     * ascending - (boolean) Indicating sort direction.
+     * field - (string) Sort field.
+     * </pre>
      *
-     * @return Turba_List containing requested Turba_Objects
+     * @return Turba_List  A list object.
      */
-    function _toTurbaObjects($objects, $sort_order = null)
+    protected function _toTurbaObjects($objects, $sort_order = null)
     {
         $list = new Turba_List();
+
         foreach ($objects as $object) {
             /* Translate the driver-specific fields in the result back to the
              * more generalized common Turba attributes using the map. */
@@ -560,12 +576,7 @@ class Turba_Driver implements Countable
             $done = false;
             if (!empty($object['__type']) &&
                 ucwords($object['__type']) != 'Object') {
-                $type = ucwords($object['__type']);
-                $class = 'Turba_Object_' . $type;
-                if (!class_exists($class)) {
-                    require_once TURBA_BASE . '/lib/Object/' . $type . '.php';
-                }
-
+                $class = 'Turba_Object_' . ucwords($object['__type']);
                 if (class_exists($class)) {
                     $list->insert(new $class($this, $object));
                     $done = true;
@@ -575,7 +586,9 @@ class Turba_Driver implements Countable
                 $list->insert(new Turba_Object($this, $object));
             }
         }
+
         $list->sort($sort_order);
+
         /* Return the filtered (sorted) results. */
         return $list;
     }
@@ -588,17 +601,16 @@ class Turba_Driver implements Countable
      * @param Horde_Date $end    The end date of the valid period.
      * @param $category          The timeObjects category to return.
      *
-     * @return mixed  A list of timeObject hashes || PEAR_Error
+     * @return mixed  A list of timeObject hashes.
+     * @throws Turba Exception
      */
-    function listTimeObjects($start, $end, $category)
+    public function listTimeObjects($start, $end, $category)
     {
-        $res = $this->_getTimeObjectTurbaList($start, $end, $category);
-        if (is_a($res, 'PEAR_Error')) {
+        try {
+            $res = $this->getTimeObjectTurbaList($start, $end, $category);
+        } catch (Turba_Exception $e) {
             /* Try the default implementation before returning an error */
             $res = $this->_getTimeObjectTurbaListFallback($start, $end, $category);
-            if (is_a($res, 'PEAR_Error')) {
-                return $res;
-            }
         }
 
         $t_objects = array();
@@ -610,9 +622,11 @@ class Turba_Driver implements Countable
                 continue;
             }
 
-            $t_object = new Horde_Date(array('mday' => $match[3],
-                                             'month' => $match[2],
-                                             'year' => $match[1]));
+            $t_object = new Horde_Date(array(
+                'mday' => $match[3],
+                'month' => $match[2],
+                'year' => $match[1]
+            ));
             if ($t_object->compareDate($end) > 0) {
                 continue;
             }
@@ -651,8 +665,8 @@ class Turba_Driver implements Countable
                 'category' => $ob->getValue('category'),
                 'recurrence' => array('type' => Horde_Date_Recurrence::RECUR_YEARLY_DATE,
                                       'interval' => 1),
-                'params' => array('source' => $this->name, 'key' => $key),
-                'link' => Horde::applicationUrl('contact.php', true)->add(array('source' => $this->name, 'key' => $key))->setRaw(true));
+                'params' => array('source' => $this->_name, 'key' => $key),
+                'link' => Horde::applicationUrl('contact.php', true)->add(array('source' => $this->_name, 'key' => $key))->setRaw(true));
         }
 
         return $t_objects;
@@ -665,11 +679,13 @@ class Turba_Driver implements Countable
      * @param Horde_Date $start  The starting date.
      * @param Horde_Date $end    The ending date.
      * @param string $field      The address book field containing the
-     *                           timeObject information (birthday, anniversary)
+     *                           timeObject information (birthday,
+     *                           anniversary).
      *
-     * @return mixed  A Tubra_List of objects || PEAR_Error
+     * @return Turba_List  A list of objects.
+     * @throws Turba_Exception
      */
-    function _getTimeObjectTurbaList($start, $end, $field)
+    public function getTimeObjectTurbaList($start, $end, $field)
     {
         return $this->_getTimeObjectTurbaListFallback($start, $end, $field);
     }
@@ -681,16 +697,15 @@ class Turba_Driver implements Countable
      * @param Horde_Date $start  The starting date.
      * @param Horde_Date $end    The ending date.
      * @param string $field      The address book field containing the
-     *                           timeObject information (birthday, anniversary)
+     *                           timeObject information (birthday,
+     *                           anniversary).
      *
-     * @return mixed  A Tubra_List of objects || PEAR_Error
+     * @return Turba_List  A list of objects.
+     * @throws Turba_Exception
      */
-    function _getTimeObjectTurbaListFallback($start, $end, $field)
+    protected function _getTimeObjectTurbaListFallback($start, $end, $field)
     {
-        $res = $this->search(array(), null, 'AND',
-                             array('name', $field, 'category'));
-
-        return $res;
+        return $this->search(array(), null, 'AND', array('name', $field, 'category'));
     }
 
     /**
@@ -699,19 +714,16 @@ class Turba_Driver implements Countable
      * @param array $objectIds  The unique ids of the objects to retrieve.
      *
      * @return array  The array of retrieved objects (Turba_Objects).
+     * @throws Turba_Exception
      */
-    function &getObjects($objectIds)
+    public function getObjects($objectIds)
     {
         $objects = $this->_read($this->map['__key'], $objectIds,
                                 $this->getContactOwner(),
                                 array_values($this->fields),
                                 $this->toDriverKeys($this->getBlobs()));
-        if (is_a($objects, 'PEAR_Error')) {
-            return $objects;
-        }
         if (!is_array($objects)) {
-            $result = PEAR::raiseError(_("Requested object not found."));
-            return $result;
+            throw new Turba_Exception(_("Requested object not found."));
         }
 
         $results = array();
@@ -720,13 +732,7 @@ class Turba_Driver implements Countable
             $done = false;
             if (!empty($object['__type']) &&
                 ucwords($object['__type']) != 'Object') {
-
-                $type = ucwords($object['__type']);
-                $class = 'Turba_Object_' . $type;
-                if (!class_exists($class)) {
-                    require_once TURBA_BASE . '/lib/Object/' . $type . '.php';
-                }
-
+                $class = 'Turba_Object_' . ucwords($object['__type']);
                 if (class_exists($class)) {
                     $results[] = new $class($this, $object);
                     $done = true;
@@ -746,19 +752,19 @@ class Turba_Driver implements Countable
      * @param string $objectId  The unique id of the object to retrieve.
      *
      * @return Turba_Object  The retrieved object.
+     * @throws Turba_Exception
      */
-    function &getObject($objectId)
+    public function getObject($objectId)
     {
-        $result = &$this->getObjects(array($objectId));
-        if (is_a($result, 'PEAR_Error')) {
-            // Fall through.
-        } elseif (empty($result[0])) {
-            $result = PEAR::raiseError('No results');
-        } else {
-            $result = $result[0];
-            if (!isset($this->map['__owner'])) {
-                $result->attributes['__owner'] = $this->getContactOwner();
-            }
+        $result = $this->getObjects(array($objectId));
+
+        if (empty($result[0])) {
+            throw new Turba_Exception('No results');
+        }
+
+        $result = $result[0];
+        if (!isset($this->map['__owner'])) {
+            $result->attributes['__owner'] = $this->getContactOwner();
         }
 
         return $result;
@@ -769,10 +775,10 @@ class Turba_Driver implements Countable
      *
      * @param array $attributes  The attributes of the new object to add.
      *
-     * @return mixed  The new __key value on success, or a PEAR_Error object
-     *                on failure.
+     * @return string  The new __key value on success.
+     * @throws Turba_Exception
      */
-    function add($attributes)
+    public function add($attributes)
     {
         /* Only set __type and __owner if they are not already set. */
         if (!isset($attributes['__type'])) {
@@ -790,10 +796,8 @@ class Turba_Driver implements Countable
         $uid = $attributes['__uid'];
 
         $attributes = $this->toDriverKeys($attributes);
-        $result = $this->_add($attributes, $this->toDriverKeys($this->getBlobs()));
-        if (is_a($result, 'PEAR_Error')) {
-            return $result;
-        }
+
+        $this->_add($attributes, $this->toDriverKeys($this->getBlobs()));
 
         /* Log the creation of this item in the history log. */
         try {
@@ -810,14 +814,19 @@ class Turba_Driver implements Countable
     /**
      * Returns ability of the backend to add new contacts.
      *
-     * @return boolean
+     * @return boolean  Can backend add?
      */
-    function canAdd()
+    public function canAdd()
     {
         return $this->_canAdd();
     }
 
-    function _canAdd()
+    /**
+     * Returns ability of the backend to add new contacts.
+     *
+     * @return boolean  Can backend add?
+     */
+    protected function _canAdd()
     {
         return false;
     }
@@ -826,22 +835,18 @@ class Turba_Driver implements Countable
      * Deletes the specified entry from the contact source.
      *
      * @param string $object_id  The ID of the object to delete.
+     *
+     * @throws Turba_Exception
      */
-    function delete($object_id)
+    public function delete($object_id)
     {
-        $object = &$this->getObject($object_id);
-        if (is_a($object, 'PEAR_Error')) {
-            return $object;
-        }
+        $object = $this->getObject($object_id);
 
         if (!$object->hasPermission(Horde_Perms::DELETE)) {
-            return PEAR::raiseError(_("Permission denied"));
+            throw new Turba_Exception(_("Permission denied"));
         }
 
-        $result = $this->_delete($this->toDriver('__key'), $object_id);
-        if (is_a($result, 'PEAR_Error')) {
-            return $result;
-        }
+        $this->_delete($this->toDriver('__key'), $object_id);
 
         $own_contact = $GLOBALS['prefs']->getValue('own_contact');
         if (!empty($own_contact)) {
@@ -868,20 +873,27 @@ class Turba_Driver implements Countable
     /**
      * Deletes all contacts from an address book.
      *
-     * @param string  $sourceName  The identifier of the address book to
-     *                             delete.  If omitted, will clear the current
-     *                             user's 'default' address book for this source
-     *                             type.
+     * @param string $sourceName  The identifier of the address book to
+     *                            delete.  If omitted, will clear the current
+     *                            user's 'default' address book for this
+     *                            source type.
      *
-     * @return mixed  True on success, PEAR_Error on failure.
+     * @throws Turba_Exception
      */
-    function deleteAll($sourceName = null)
+    public function deleteAll($sourceName = null)
     {
         if (!$this->hasCapability('delete_all')) {
-            return PEAR::raiseError('Not supported');
-        } else {
-            return $this->_deleteAll($sourceName);
+            throw new Turba_Exception('Not supported');
         }
+
+        $this->_deleteAll($sourceName);
+    }
+
+    /**
+     * TODO
+     */
+    protected function _deleteAll()
+    {
     }
 
     /**
@@ -890,13 +902,11 @@ class Turba_Driver implements Countable
      * @param Turba_Object $object  The object to update.
      *
      * @return string  The object id, possibly updated.
+     * @throws Turba_Exception
      */
-    function save($object)
+    public function save($object)
     {
         $object_id = $this->_save($object);
-        if (is_a($object_id, 'PEAR_Error')) {
-            return $object_id;
-        }
 
         /* Log the modification of this item in the history log. */
         if ($object->getValue('__uid')) {
@@ -908,6 +918,7 @@ class Turba_Driver implements Countable
                 Horde::logMessage($e, 'ERR');
             }
         }
+
         return $object_id;
     }
 
@@ -916,10 +927,11 @@ class Turba_Driver implements Countable
      *
      * @return array  An array containing the criteria.
      */
-    function getCriteria()
+    public function getCriteria()
     {
         $criteria = $this->map;
         unset($criteria['__key']);
+
         return $criteria;
     }
 
@@ -929,7 +941,7 @@ class Turba_Driver implements Countable
      *
      * @return array  The field list.
      */
-    function getFields()
+    public function getFields()
     {
         return array_flip($this->fields);
     }
@@ -943,14 +955,17 @@ class Turba_Driver implements Countable
      *                              properties with the requested fields.
      * @param boolean $skipEmpty    Whether to skip empty fields.
      *
-     * @return Horde_Icalendar_vcard  A Horde_Icalendar_vcard object.
+     * @return Horde_Icalendar_Vcard  A vcard object.
      */
-    function tovCard($object, $version = '2.1', $fields = null, $skipEmpty = false)
+    public function tovCard($object, $version = '2.1', $fields = null,
+                            $skipEmpty = false)
     {
         $hash = $object->getAttributes();
         $vcard = new Horde_Icalendar_Vcard($version);
         $formattedname = false;
-        $charset = $version == '2.1' ? array('CHARSET' => $GLOBALS['registry']->getCharset()) : array();
+        $charset = ($version == '2.1')
+            ? array('CHARSET' => $GLOBALS['registry']->getCharset())
+            : array();
 
         foreach ($hash as $key => $val) {
             if ($skipEmpty && !strlen($val)) {
@@ -969,6 +984,7 @@ class Turba_Driver implements Countable
                 $vcard->setAttribute('FN', $val, Horde_Mime::is8bit($val) ? $charset : array());
                 $formattedname = true;
                 break;
+
             case 'nickname':
             case 'alias':
                 if ($fields && !isset($fields['NICKNAME'])) {
@@ -991,6 +1007,7 @@ class Turba_Driver implements Countable
                     $vcard->setAttribute('LABEL', $val, array('TYPE' => 'HOME'));
                 }
                 break;
+
             case 'workAddress':
                 if ($fields &&
                     (!isset($fields['LABEL']) ||
@@ -1004,27 +1021,21 @@ class Turba_Driver implements Countable
                     $vcard->setAttribute('LABEL', $val, array('TYPE' => 'WORK'));
                 }
                 break;
+
             case 'otherAddress':
                 if ($fields && !isset($fields['LABEL'])) {
                     break;
                 }
-                if ($version == '2.1') {
-                    $vcard->setAttribute('LABEL', $val);
-                } else {
-                    $vcard->setAttribute('LABEL', $val);
-                }
+                $vcard->setAttribute('LABEL', $val);
                 break;
 
             case 'phone':
                 if ($fields && !isset($fields['TEL'])) {
                     break;
                 }
-                if ($version == '2.1') {
-                    $vcard->setAttribute('TEL', $val);
-                } else {
-                    $vcard->setAttribute('TEL', $val);
-                }
+                $vcard->setAttribute('TEL', $val);
                 break;
+
             case 'homePhone':
                 if ($fields &&
                     (!isset($fields['TEL']) ||
@@ -1038,6 +1049,7 @@ class Turba_Driver implements Countable
                     $vcard->setAttribute('TEL', $val, array('TYPE' => 'HOME'));
                 }
                 break;
+
             case 'workPhone':
                 if ($fields &&
                     (!isset($fields['TEL']) ||
@@ -1051,6 +1063,7 @@ class Turba_Driver implements Countable
                     $vcard->setAttribute('TEL', $val, array('TYPE' => 'WORK'));
                 }
                 break;
+
             case 'cellPhone':
                 if ($fields &&
                     (!isset($fields['TEL']) ||
@@ -1064,6 +1077,7 @@ class Turba_Driver implements Countable
                     $vcard->setAttribute('TEL', $val, array('TYPE' => 'CELL'));
                 }
                 break;
+
             case 'homeCellPhone':
                 $parameters = array();
                 if ($fields) {
@@ -1098,6 +1112,7 @@ class Turba_Driver implements Countable
                 }
                 $vcard->setAttribute('TEL', $val, $parameters);
                 break;
+
             case 'workCellPhone':
                 $parameters = array();
                 if ($fields) {
@@ -1146,6 +1161,7 @@ class Turba_Driver implements Countable
                     $vcard->setAttribute('TEL', $val, array('TYPE' => 'VIDEO'));
                 }
                 break;
+
             case 'homeVideoCall':
                 $parameters = array();
                 if ($fields) {
@@ -1180,6 +1196,7 @@ class Turba_Driver implements Countable
                 }
                 $vcard->setAttribute('TEL', $val, $parameters);
                 break;
+
             case 'workVideoCall':
                 $parameters = array();
                 if ($fields) {
@@ -1234,6 +1251,7 @@ class Turba_Driver implements Countable
                     $vcard->setAttribute('X-SIP', $val, array('TYPE' => 'POC'));
                 }
                 break;
+
             case 'voip':
                 if ($fields &&
                     (!isset($fields['X-SIP']) ||
@@ -1247,6 +1265,7 @@ class Turba_Driver implements Countable
                     $vcard->setAttribute('X-SIP', $val, array('TYPE' => 'VOIP'));
                 }
                 break;
+
             case 'shareView':
                 if ($fields &&
                     (!isset($fields['X-SIP']) ||
@@ -1281,6 +1300,7 @@ class Turba_Driver implements Countable
                     $vcard->setAttribute('TEL', $val, array('TYPE' => 'FAX'));
                 }
                 break;
+
             case 'homeFax':
                 $parameters = array();
                 if ($fields) {
@@ -1315,6 +1335,7 @@ class Turba_Driver implements Countable
                 }
                 $vcard->setAttribute('TEL', $val, $parameters);
                 break;
+
             case 'workFax':
                 $parameters = array();
                 if ($fields) {
@@ -1373,9 +1394,9 @@ class Turba_Driver implements Countable
                 if ($fields && !isset($fields['EMAIL'])) {
                     break;
                 }
-                $vcard->setAttribute('EMAIL',
-                                     Horde_Icalendar_Vcard::getBareEmail($val));
+                $vcard->setAttribute('EMAIL', Horde_Icalendar_Vcard::getBareEmail($val));
                 break;
+
             case 'homeEmail':
                 if ($fields &&
                     (!isset($fields['EMAIL']) ||
@@ -1393,6 +1414,7 @@ class Turba_Driver implements Countable
                                          array('TYPE' => 'HOME'));
                 }
                 break;
+
             case 'workEmail':
                 if ($fields &&
                     (!isset($fields['EMAIL']) ||
@@ -1410,14 +1432,14 @@ class Turba_Driver implements Countable
                                          array('TYPE' => 'WORK'));
                 }
                 break;
+
             case 'emails':
                 if ($fields && !isset($fields['EMAIL'])) {
                     break;
                 }
                 $emails = explode(',', $val);
                 foreach ($emails as $email) {
-                    $vcard->setAttribute('EMAIL',
-                                         Horde_Icalendar_Vcard::getBareEmail($email));
+                    $vcard->setAttribute('EMAIL', Horde_Icalendar_Vcard::getBareEmail($email));
                 }
                 break;
 
@@ -1425,23 +1447,21 @@ class Turba_Driver implements Countable
                 if ($fields && !isset($fields['TITLE'])) {
                     break;
                 }
-                $vcard->setAttribute('TITLE', $val,
-                                     Horde_Mime::is8bit($val) ? $charset : array());
+                $vcard->setAttribute('TITLE', $val, Horde_Mime::is8bit($val) ? $charset : array());
                 break;
+
             case 'role':
                 if ($fields && !isset($fields['ROLE'])) {
                     break;
                 }
-                $vcard->setAttribute('ROLE', $val,
-                                     Horde_Mime::is8bit($val) ? $charset : array());
+                $vcard->setAttribute('ROLE', $val, Horde_Mime::is8bit($val) ? $charset : array());
                 break;
 
             case 'notes':
                 if ($fields && !isset($fields['NOTE'])) {
                     break;
                 }
-                $vcard->setAttribute('NOTE', $val,
-                                     Horde_Mime::is8bit($val) ? $charset : array());
+                $vcard->setAttribute('NOTE', $val, Horde_Mime::is8bit($val) ? $charset : array());
                 break;
 
             case 'businessCategory':
@@ -1476,6 +1496,7 @@ class Turba_Driver implements Countable
                 }
                 $vcard->setAttribute('URL', $val);
                 break;
+
             case 'homeWebsite':
                 if ($fields &&
                     (!isset($fields['URL']) ||
@@ -1489,6 +1510,7 @@ class Turba_Driver implements Countable
                     $vcard->setAttribute('URL', $val, array('TYPE' => 'HOME'));
                 }
                 break;
+
             case 'workWebsite':
                 if ($fields &&
                     (!isset($fields['URL']) ||
@@ -1527,6 +1549,7 @@ class Turba_Driver implements Countable
                                                'longitude' => $hash['longitude']));
                 }
                 break;
+
             case 'homeLatitude':
                 if ($fields &&
                     (!isset($fields['GEO']) ||
@@ -1548,6 +1571,7 @@ class Turba_Driver implements Countable
                    }
                 }
                 break;
+
             case 'workLatitude':
                 if ($fields &&
                     (!isset($fields['GEO']) ||
@@ -1836,7 +1860,7 @@ class Turba_Driver implements Countable
      *
      * @return array  A Turba attribute hash.
      */
-    function toHash(Horde_Icalendar_Vcard $vcard)
+    public function toHash(Horde_Icalendar_Vcard $vcard)
     {
         $hash = array();
         $attr = $vcard->getAllAttributes();
@@ -2261,22 +2285,27 @@ class Turba_Driver implements Countable
         $charset = $GLOBALS['registry']->getCharset();
         $hash = $object->getAttributes();
         foreach ($hash as $field => $value) {
-           switch ($field) {
+            switch ($field) {
             case 'name':
                 $message->fileas = Horde_String::convertCharset($value, $charset, 'utf-8');
                 break;
+
             case 'lastname':
                 $message->lastname = Horde_String::convertCharset($value, $charset, 'utf-8');
                 break;
+
             case 'firstname':
                 $message->firstname = Horde_String::convertCharset($value, $charset, 'utf-8');
                 break;
+
             case 'middlenames':
                 $message->middlename = Horde_String::convertCharset($value, $charset, 'utf-8');
                 break;
+
             case 'namePrefix':
                 $message->title = Horde_String::convertCharset($value, $charset, 'utf-8');
                 break;
+
             case 'nameSuffix':
                 $message->suffix = Horde_String::convertCharset($value, $charset, 'utf-8');
                 break;
@@ -2285,50 +2314,64 @@ class Turba_Driver implements Countable
                 $message->picture = base64_encode($value);
                 break;
 
-            /* Address (TODO: check for a single home/workAddress field instead) */
             case 'homeStreet':
+                /* Address (TODO: check for a single home/workAddress field
+                 * instead) */
                 $message->homestreet = Horde_String::convertCharset($hash['homeStreet'], $charset, 'utf-8');
                 break;
+
             case 'homeCity':
                 $message->homecity = Horde_String::convertCharset($hash['homeCity'], $charset, 'utf-8');
                 break;
+
             case 'homeProvince':
                 $message->homestate = Horde_String::convertCharset($hash['homeProvince'], $charset, 'utf-8');
                 break;
+
             case 'homePostalCode':
                 $message->homepostalcode = Horde_String::convertCharset($hash['homePostalCode'], $charset, 'utf-8');
                 break;
+
             case 'homeCountry':
                 $message->homecountry = Horde_String::convertCharset(Horde_Nls::getCountryISO($hash['homeCountry']), $charset, 'utf-8');
                 break;
+
             case 'workStreet':
                 $message->businessstreet = Horde_String::convertCharset($hash['workStreet'], $charset, 'utf-8');
                 break;
+
             case 'workCity':
                 $message->businesscity = Horde_String::convertCharset($hash['workCity'], $charset, 'utf-8');
                 break;
+
             case 'workProvince':
                 $message->businessstate = Horde_String::convertCharset($hash['workProvince'], $charset, 'utf-8');
                 break;
+
             case 'workPostalCode':
                 $message->businesspostalcode = Horde_String::convertCharset($hash['workPostalCode'], $charset, 'utf-8');
                 break;
+
             case 'workCountry':
                 $message->businesscountry = Horde_String::convertCharset($hash['workCountry'], $charset, 'utf-8');
                 break;
+
             case 'homePhone':
                 /* Phone */
                 $message->homephonenumber = $hash['homePhone'];
                 break;
+
             case 'cellPhone':
                 $message->mobilephonenumber = $hash['cellPhone'];
                 break;
             case 'fax':
                 $message->businessfaxnumber = $hash['fax'];
                 break;
+
             case 'workPhone':
                 $message->businessphonenumber = $hash['workPhone'];
                 break;
+
             case 'pager':
                 $message->pagernumber = $hash['pager'];
                 break;
@@ -2344,6 +2387,7 @@ class Turba_Driver implements Countable
             case 'company':
                 $message->companyname = Horde_String::convertCharset($value, $charset, 'utf-8');
                 break;
+
             case 'departnemt':
                 $message->department = Horde_String::convertCharset($value, $charset, 'utf-8');
                 break;
@@ -2362,6 +2406,7 @@ class Turba_Driver implements Countable
                 $message->bodysize = strlen($message->body);
                 $message->bodytruncated = false;
                 break;
+
             case 'website':
                 $message->webpage = $value;
                 break;
@@ -2386,12 +2431,13 @@ class Turba_Driver implements Countable
     }
 
     /**
-     * Convert an ActiveSync contact message into a hash suitable for importing
-     * via add.
+     * Convert an ActiveSync contact message into a hash suitable for
+     * importing via self::add().
      *
-     * @param Horde_ActiveSync_Message_Contact $message  The contact message object
+     * @param Horde_ActiveSync_Message_Contact $message  The contact message
+     *                                                   object.
      *
-     * @return array  A contact hash
+     * @return array  A contact hash.
      */
     public function fromASContact($message)
     {
@@ -2495,6 +2541,7 @@ class Turba_Driver implements Countable
         } elseif (!$message->isGhosted('businesscountry')) {
             $hash['workCountry'] = null;
         }
+
         return $hash;
     }
 
@@ -2506,11 +2553,11 @@ class Turba_Driver implements Countable
      *
      * @return boolean  True if the user has permission, otherwise false.
      */
-    function hasPermission($perm)
+    public function hasPermission($perm)
     {
         $perms = $GLOBALS['injector']->getInstance('Horde_Perms');
-        return $perms->exists('turba:sources:' . $this->name)
-            ? $perms->hasPermission('turba:sources:' . $this->name, $GLOBALS['registry']->getAuth(), $perm)
+        return $perms->exists('turba:sources:' . $this->_name)
+            ? $perms->hasPermission('turba:sources:' . $this->_name, $GLOBALS['registry']->getAuth(), $perm)
             // Assume we have permissions if they're not explicitly set.
             : true;
     }
@@ -2521,26 +2568,31 @@ class Turba_Driver implements Countable
      *
      * @string Address book name
      */
-    function getName()
+    public function getName()
     {
-        return $this->name;
+        return $this->_name;
     }
 
     /**
      * Return the owner to use when searching or creating contacts in
      * this address book.
      *
-     * @return string
+     * @return string  Contact owner.
      */
-    function getContactOwner()
+    public function getContactOwner()
     {
-        if (empty($this->_contact_owner)) {
-           return $this->_getContactOwner();
-        }
-        return $this->_contact_owner;
+        return empty($this->_contact_owner)
+            ? $this->_getContactOwner()
+            : $this->_contact_owner;
     }
 
-    function _getContactOwner()
+    /**
+     * Return the owner to use when searching or creating contacts in
+     * this address book.
+     *
+     * @return string  Contact owner.
+     */
+    protected function _getContactOwner()
     {
         return $GLOBALS['registry']->getAuth();
     }
@@ -2552,12 +2604,13 @@ class Turba_Driver implements Countable
      *
      * @return Horde_Share  The share object.
      */
-    function createShare($share_id, $params)
+    public function createShare($share_id, $params)
     {
         // If the raw address book name is not set, use the share name
         if (empty($params['params']['name'])) {
             $params['params']['name'] = $share_id;
         }
+
         return Turba::createShare($share_id, $params);
     }
 
@@ -2569,9 +2622,9 @@ class Turba_Driver implements Countable
      *
      * @return string  A unique ID for the new object.
      */
-    function _makeKey($attributes)
+    protected function _makeKey($attributes)
     {
-        return md5(mt_rand());
+        return hash('md5', mt_rand());
     }
 
     /**
@@ -2596,7 +2649,7 @@ class Turba_Driver implements Countable
         }
 
         /* Store name and title. */
-        $driver->name = $name;
+        $driver->_name = $name;
         $driver->title = $config['title'];
 
         /* Initialize */
@@ -2650,10 +2703,11 @@ class Turba_Driver implements Countable
      * @param array $fields    List of fields to return.
      *
      * @return array  Hash containing the search results.
+     * @throws Turba_Exception
      */
-    function _search($criteria, $fields)
+    protected function _search($criteria, $fields)
     {
-        return PEAR::raiseError(_("Searching is not available."));
+        throw new Turba_Exception(_("Searching is not available."));
     }
 
     /**
@@ -2665,36 +2719,47 @@ class Turba_Driver implements Countable
      * @param array $fields  List of fields to return.
      *
      * @return array  Hash containing the search results.
+     * @throws Turba_Exception
      */
-    function _read($key, $ids, $owner, $fields)
+    protected function _read($key, $ids, $owner, $fields)
     {
-        return PEAR::raiseError(_("Reading contacts is not available."));
+        throw new Turba_Exception(_("Reading contacts is not available."));
     }
 
     /**
      * Adds the specified contact to the SQL database.
+     *
+     * @param array $attributes  TODO
+     *
+     * @throws Turba_Exception
      */
-    function _add($attributes)
+    protected function _add($attributes)
     {
-        return PEAR::raiseError(_("Adding contacts is not available."));
+        throw new Turba_Exception(_("Adding contacts is not available."));
     }
 
     /**
      * Deletes the specified contact from the SQL database.
+     *
+     * @param $object_key TODO
+     * @param $object_id TODO
+     *
+     * @throws Turba_Exception
      */
-    function _delete($object_key, $object_id)
+    protected function _delete($object_key, $object_id)
     {
-        return PEAR::raiseError(_("Deleting contacts is not available."));
+        throw new Turba_Exception(_("Deleting contacts is not available."));
     }
 
     /**
      * Saves the specified object in the SQL database.
      *
      * @return string  The object id, possibly updated.
+     * @throws Turba_Exception
      */
-    function _save($object)
+    protected function _save($object)
     {
-        return PEAR::raiseError(_("Saving contacts is not available."));
+        throw new Turba_Exception(_("Saving contacts is not available."));
     }
 
     /**
@@ -2702,23 +2767,22 @@ class Turba_Driver implements Countable
      *
      * @param string $user  The user's data to remove.
      *
-     * @return mixed True | PEAR_Error
+     * @throws Turba_Exception
      */
-    function removeUserData($user)
+    public function removeUserData($user)
     {
-        return PEAR::raiseError(_("Removing user data is not supported in the current address book storage driver."));
+        throw new Turba_Exception(_("Removing user data is not supported in the current address book storage driver."));
     }
 
     /**
      * Check if the passed in share is the default share for this source.
      *
-     * @param Horde_Share $share  The share object e
-     * @param array $srcconfig    The cfgSource entry for the share (not used in
-     *                            this method, but a child class may need it).
+     * @param Horde_Share $share  The share object.
+     * @param array $srcconfig    The cfgSource entry for the share.
      *
-     * @return boolean
+     * @return boolean TODO
      */
-    function checkDefaultShare($share, $srcconfig)
+    public function checkDefaultShare($share, $srcconfig)
     {
         $params = @unserialize($share->get('params'));
         if (!isset($params['default'])) {
@@ -2741,11 +2805,7 @@ class Turba_Driver implements Countable
     public function count()
     {
         if (is_null($this->_count)) {
-            $count = $this->_search(array('AND' => array(array('field' => $this->toDriver('__owner'), 'op' => '=', 'test' => $this->getContactOwner()))), array($this->toDriver('__key')));
-            if ($count instanceof PEAR_Error) {
-                throw new Turba_Exception($count);
-            }
-            $this->_count = count($count);
+            $this->_count = count($this->_search(array('AND' => array(array('field' => $this->toDriver('__owner'), 'op' => '=', 'test' => $this->getContactOwner()))), array($this->toDriver('__key'))));
         }
 
         return $this->_count;
index bed0d74..d6f1f61 100644 (file)
@@ -4,17 +4,26 @@
  * application to be setup on Facebook and configured in horde/config/conf.php.
  * This driver based on the favourites driver.
  *
- * Of limited utility since email addresses are not retrievable via the Facebook
- * API, unless the user allows the Horde application to access it - and even
- * then, it's a proxied email address.
+ * Of limited utility since email addresses are not retrievable via the
+ * Facebook API, unless the user allows the Horde application to access it -
+ * and even then, it's a proxied email address.
  *
  * Copyright 2009-2010 The Horde Project (http://www.horde.org)
  *
- * @author Michael J. Rubinsky <mrubinsk@horde.org>
- * @author  Jan Schneider <jan@horde.org>
+ * See the enclosed file LICENSE for license information (ASL).  If you did
+ * did not receive this file, see http://www.horde.org/licenses/asl.php.
+ *
+ * @author   Michael J. Rubinsky <mrubinsk@horde.org>
+ * @author   Jan Schneider <jan@horde.org>
+ * @category Horde
+ * @license  http://www.horde.org/licenses/asl.php ASL
+ * @package  Turba
  */
 class Turba_Driver_Facebook extends Turba_Driver
 {
+    /**
+     * TODO
+     */
     private $_facebook;
 
     /**
@@ -25,12 +34,15 @@ class Turba_Driver_Facebook extends Turba_Driver
      *
      * @return boolean  True if the user has permission, otherwise false.
      */
-     function hasPermission($perm)
+     public function hasPermission($perm)
      {
          switch ($perm) {
-             case Horde_Perms::EDIT: return false;
-             case Horde_Perms::DELETE: return false;
-             default: return true;
+         case Horde_Perms::DELETE:
+         case Horde_Perms::EDIT:
+             return false;
+
+         default:
+             return true;
          }
      }
 
@@ -43,14 +55,11 @@ class Turba_Driver_Facebook extends Turba_Driver
      * @param array $fields    List of fields to return.
      *
      * @return array  Hash containing the search results.
+     * @throws Turba_Exception
      */
-    function _search($criteria, $fields)
+    protected function _search($criteria, $fields)
     {
-        $results = array();
         $results = $this->_getAddressBook($fields);
-        if (is_a($results, 'PEAR_Error')) {
-            return $results;
-        }
 
         foreach ($results as $key => $contact) {
             $found = !isset($criteria['OR']);
@@ -87,6 +96,7 @@ class Turba_Driver_Facebook extends Turba_Driver
                 $results[$key] = $contact;
             }
         }
+
         return $results;
     }
 
@@ -98,49 +108,36 @@ class Turba_Driver_Facebook extends Turba_Driver
      * @param string $id       Data identifier.
      * @param array $fields    List of fields to return.
      *
-     * @return  Hash containing the search results.
+     * @return array  Hash containing the search results.
      */
-    function _read($criteria, $ids, $owner, $fields)
+    protected function _read($criteria, $ids, $owner, $fields)
     {
-        $results = $this->_getEntry($ids, $fields);
-        return $results;
+        return $this->_getEntry($ids, $fields);
     }
 
-    function _getEntry($keys, $fields)
+    /**
+     * TODO
+     */
+    protected function _getEntry($keys, $fields)
     {
-        try {
-            $facebook = $GLOBALS['injector']->getInstance('Horde_Service_Facebook');
-        } catch (Horde_Exception $e) {
-            $error = PEAR::raiseError($e->getMessage(), $e->getCode());
-            Horde::logMessage($error, 'ERR');
-
-            return $error;
-        }
+        $facebook = $GLOBALS['injector']->getInstance('Horde_Service_Facebook');
         $fields = implode(', ', $fields);
         $fql = 'SELECT ' . $fields . ' FROM user WHERE uid IN (' . implode(', ', $keys) . ')';
 
         try {
-            $results = $facebook->fql->run($fql);
+            return $facebook->fql->run($fql);
         } catch (Horde_Service_Facebook_Exception $e) {
-            $error = PEAR::raiseError($e->getMessage(), $e->getCode());
-            Horde::logMessage($error, 'ERR');
-
-            return $error;
+            Horde::logMessage($e, 'ERR');
+            throw new Turba_Exception($e);
         }
-
-        return $results;
     }
 
-    function _getAddressBook($fields = array())
+    /**
+     * TODO
+     */
+    protected function _getAddressBook($fields = array())
     {
-        try {
-            $facebook = $GLOBALS['injector']->getInstance('Horde_Service_Facebook');
-        } catch (Horde_Exception $e) {
-            $error = PEAR::raiseError($e->getMessage(), $e->getCode());
-            Horde::logMessage($error, 'ERR');
-
-            return $error;
-        }
+        $facebook = $GLOBALS['injector']->getInstance('Horde_Service_Facebook');
         $fields = implode(', ', $fields);
         // For now, just try a fql query with name and email.
         $fql = 'SELECT ' . $fields . ' FROM user WHERE uid IN ('
@@ -149,10 +146,10 @@ class Turba_Driver_Facebook extends Turba_Driver
         try {
             $results = $facebook->fql->run($fql);
         } catch (Horde_Service_Facebook_Exception $e) {
-            $error = PEAR::raiseError($e->getMessage(), $e->getCode());
-            Horde::logMessage($error, 'ERR');
+            Horde::logMessage($e, 'ERR');
             return array();
         }
+
         $addressbook = array();
         foreach ($results as $result) {
             if (!empty($result['birthday'])) {
@@ -167,23 +164,35 @@ class Turba_Driver_Facebook extends Turba_Driver
         return $addressbook;
     }
 
+    /**
+     * TODO
+     *
+     * @throws Turba_Exception
+     */
     function _getFacebook()
     {
         global $conf, $prefs;
+
         if (!$conf['facebook']['enabled']) {
-            return PEAR::raiseError(_("No Facebook integration exists."));
+            throw new Turba_Exception(_("No Facebook integration exists."));
         }
 
         if (empty($this->_facebook)) {
-            $context = array('http_client' => new Horde_Http_Client(),
-                             'http_request' => $GLOBALS['injector']->getInstance('Horde_Controller_Request'));
-            $this->_facebook = new Horde_Service_Facebook($conf['facebook']['key'],
-                                                   $conf['facebook']['secret'],
-                                                   $context);
+            $context = array(
+                'http_client' => new Horde_Http_Client(),
+                'http_request' => $GLOBALS['injector']->getInstance('Horde_Controller_Request')
+            );
+            $this->_facebook = new Horde_Service_Facebook(
+                $conf['facebook']['key'],
+                $conf['facebook']['secret'],
+                $context
+            );
 
             $session = unserialize($prefs->getValue('facebook'));
-            if (!$session || !isset($session['uid']) || !isset($session['sid'])) {
-                return PEAR::raiseError(_("You have to connect to Facebook in your address book preferences."));
+            if (!$session ||
+                !isset($session['uid']) ||
+                !isset($session['sid'])) {
+                throw new Turba_Exception(_("You have to connect to Facebook in your address book preferences."));
             }
             $this->_facebook->auth->setUser($session['uid'], $session['sid'], 0);
         }
index 18bb85f..6a8f47c 100644 (file)
@@ -3,8 +3,15 @@
  * Read-only Turba directory driver implementation for favourite
  * recipients. Relies on the contacts/favouriteRecipients API method.
  *
- * @author  Jan Schneider <jan@horde.org>
- * @package Turba
+ * Copyright 2010 The Horde Project (http://www.horde.org/)
+ *
+ * See the enclosed file LICENSE for license information (ASL).  If you did
+ * did not receive this file, see http://www.horde.org/licenses/asl.php.
+ *
+ * @author   Jan Schneider <jan@horde.org>
+ * @category Horde
+ * @license  http://www.horde.org/licenses/asl.php ASL
+ * @package  Turba
  */
 class Turba_Driver_Favourites extends Turba_Driver
 {
@@ -16,12 +23,15 @@ class Turba_Driver_Favourites extends Turba_Driver
      *
      * @return boolean  True if the user has permission, otherwise false.
      */
-     function hasPermission($perm)
+     public function hasPermission($perm)
      {
          switch ($perm) {
-             case Horde_Perms::EDIT: return false;
-             case Horde_Perms::DELETE: return false;
-             default: return true;
+         case Horde_Perms::DELETE:
+         case Horde_Perms::EDIT:
+             return false;
+
+         default:
+             return true;
          }
      }
 
@@ -34,10 +44,12 @@ class Turba_Driver_Favourites extends Turba_Driver
      * @param array $fields    List of fields to return.
      *
      * @return array  Hash containing the search results.
+     * @throws Turba_Exception
      */
-    function _search($criteria, $fields)
+    protected function _search($criteria, $fields)
     {
         $results = array();
+
         foreach ($this->_getAddressBook() as $key => $contact) {
             $found = !isset($criteria['OR']);
             foreach ($criteria as $op => $vals) {
@@ -73,6 +85,7 @@ class Turba_Driver_Favourites extends Turba_Driver
                 $results[$key] = $contact;
             }
         }
+
         return $results;
     }
 
@@ -84,19 +97,18 @@ class Turba_Driver_Favourites extends Turba_Driver
      * @param string $id       Data identifier.
      * @param array $fields    List of fields to return.
      *
-     * @return  Hash containing the search results.
+     * @return arry  Hash containing the search results.
+     * @throws Turba_Exception
      */
-    function _read($criteria, $ids, $owner, $fields)
+    protected function _read($criteria, $ids, $owner, $fields)
     {
         $book = $this->_getAddressBook();
-        if (is_a($book, 'PEAR_Error')) {
-            return $book;
-        }
 
         $results = array();
         if (!is_array($ids)) {
             $ids = array($ids);
         }
+
         foreach ($ids as $id) {
             if (isset($book[$id])) {
                 $results[] = $book[$id];
@@ -106,18 +118,20 @@ class Turba_Driver_Favourites extends Turba_Driver
         return $results;
     }
 
-    function _getAddressBook()
+    /**
+     * TODO
+     *
+     * @throws Turba_Exception
+     */
+    protected function _getAddressBook()
     {
         global $registry;
 
         if (!$registry->hasMethod('contacts/favouriteRecipients')) {
-            return PEAR::raiseError(_("No source for favourite recipients exists."));
+            throw new Turba_Exception(_("No source for favourite recipients exists."));
         }
 
         $addresses = $registry->call('contacts/favouriteRecipients', array($this->_params['limit']));
-        if (is_a($addresses, 'PEAR_Error')) {
-            return $addresses;
-        }
 
         $addressbook = array();
         foreach ($addresses as $address) {
index a1dedf8..f18148c 100644 (file)
@@ -3,8 +3,15 @@
  * Read-only Turba_Driver implementation for creating a Horde_Group based
  * address book.
  *
- * @author  Michael J. Rubinsky <mrubinsk@horde.org>
- * @package Turba
+ * Copyright 2010 The Horde Project (http://www.horde.org/)
+ *
+ * See the enclosed file LICENSE for license information (ASL).  If you did
+ * did not receive this file, see http://www.horde.org/licenses/asl.php.
+ *
+ * @author   Michael J. Rubinsky <mrubinsk@horde.org>
+ * @category Horde
+ * @license  http://www.horde.org/licenses/asl.php ASL
+ * @package  Turba
  */
 class Turba_Driver_Group extends Turba_Driver
 {
@@ -28,7 +35,7 @@ class Turba_Driver_Group extends Turba_Driver
      *
      * @return boolean  True if the user has permission, otherwise false.
      */
-    function hasPermission($perm)
+    public function hasPermission($perm)
     {
         switch ($perm) {
         case Horde_Perms::EDIT:
@@ -51,10 +58,12 @@ class Turba_Driver_Group extends Turba_Driver
      * @param array $fields    List of fields to return.
      *
      * @return array  Hash containing the search results.
+     * @throws Turba_Exception
      */
-    function _search($criteria, $fields)
+    protected function _search($criteria, $fields)
     {
         $results = array();
+
         foreach ($this->_getAddressBook() as $key => $contact) {
             $found = !isset($criteria['OR']);
             foreach ($criteria as $op => $vals) {
@@ -90,6 +99,7 @@ class Turba_Driver_Group extends Turba_Driver
                 $results[$key] = $contact;
             }
         }
+
         return $results;
     }
 
@@ -101,9 +111,9 @@ class Turba_Driver_Group extends Turba_Driver
      * @param string $id       Data identifier.
      * @param array $fields    List of fields to return.
      *
-     * @return  Hash containing the search results.
+     * @return array  Hash containing the search results.
      */
-    function _read($criteria, $ids, $fields)
+    protected function _read($criteria, $ids, $fields)
     {
         $book = $this->_getAddressBook();
         $results = array();
@@ -119,7 +129,10 @@ class Turba_Driver_Group extends Turba_Driver
         return $results;
     }
 
-    function _getAddressBook()
+    /**
+     * TODO
+     */
+    protected function _getAddressBook()
     {
         $groups = Horde_Group::singleton();
         $members = $groups->listAllUsers($this->_gid);
@@ -132,9 +145,9 @@ class Turba_Driver_Group extends Turba_Driver
             // with the same fullname, so no email = no entry in address book.
             if (!empty($email)) {
                 $addressbook[$email] = array(
-                                            'name' => ((!empty($name) ? $name : $member)),
-                                            'email' => $identity->getValue('from_addr')
-                                        );
+                    'name' => ((!empty($name) ? $name : $member)),
+                    'email' => $identity->getValue('from_addr')
+                );
             }
         }
 
index 7cbd4c8..299dbc0 100644 (file)
@@ -2,8 +2,15 @@
 /**
  * Turba directory driver implementation for an IMSP server.
  *
- * @author  Michael Rubinsky <mrubinsk@horde.org>
- * @package Turba
+ * Copyright 2010 The Horde Project (http://www.horde.org/)
+ *
+ * See the enclosed file LICENSE for license information (ASL).  If you did
+ * did not receive this file, see http://www.horde.org/licenses/asl.php.
+ *
+ * @author   Michael Rubinsky <mrubinsk@horde.org>
+ * @category Horde
+ * @license  http://www.horde.org/licenses/asl.php ASL
+ * @package  Turba
  */
 class Turba_Driver_Imsp extends Turba_Driver
 {
@@ -12,44 +19,49 @@ class Turba_Driver_Imsp extends Turba_Driver
      *
      * @var Net_IMSP
      */
-    var $_imsp;
+    protected $_imsp;
 
     /**
      * The name of the addressbook.
      *
      * @var string
      */
-    var $_bookName  = '';
+    protected $_bookName  = '';
 
     /**
      * Holds if we are authenticated.
      *
      * @var boolean
      */
-    var $_authenticated = '';
+    protected $_authenticated = '';
 
     /**
      * Holds name of the field indicating an IMSP group.
      *
      * @var string
      */
-    var $_groupField = '';
+    protected $_groupField = '';
 
     /**
      * Holds value that $_groupField will have if entry is an IMSP group.
      *
      * @var string
      */
-    var $_groupValue = '';
+    protected $_groupValue = '';
 
     /**
      * Used to set if the current search is for contacts only.
      *
      * @var boolean
      */
-    var $_noGroups = '';
+    protected $_noGroups = '';
 
-    var $_capabilities = array(
+    /**
+     * Driver capabilities.
+     *
+     * @var array
+     */
+    protected $_capabilities = array(
         'delete_all' => true,
         'delete_addressbook' => true
     );
@@ -57,7 +69,8 @@ class Turba_Driver_Imsp extends Turba_Driver
     /**
      * Constructs a new Turba imsp driver object.
      *
-     * @param array $params  Hash containing additional configuration parameters.
+     * @param array $params  Hash containing additional configuration
+     *                       parameters.
      */
     public function __construct($params)
     {
@@ -105,23 +118,20 @@ class Turba_Driver_Imsp extends Turba_Driver
      *
      * @return array  Hash containing the search results.
      */
-    function _search($criteria, $fields)
+    protected function _search($criteria, $fields)
     {
-        $query = array();
-        $results = array();
+        $query = $results = array();
 
         if (!$this->_authenticated) {
-            return array();
+            return $query;
         }
 
         /* Get the search criteria. */
         if (count($criteria)) {
             foreach ($criteria as $key => $vals) {
-                if (strval($key) == 'OR') {
-                    $names = $this->_doSearch($vals, 'OR');
-                } elseif (strval($key) == 'AND') {
-                    $names = $this->_doSearch($vals, 'AND');
-                }
+                $names = (strval($key) == 'OR')
+                    ? $this->_doSearch($vals, 'OR')
+                    : $this->_doSearch($vals, 'AND');
             }
         }
 
@@ -131,8 +141,8 @@ class Turba_Driver_Imsp extends Turba_Driver
             $results = $result;
         }
 
-        Horde::logMessage(sprintf('IMSP returned %s results',
-                                  count($results)), 'DEBUG');
+        Horde::logMessage(sprintf('IMSP returned %s results', count($results)), 'DEBUG');
+
         return array_values($results);
     }
 
@@ -140,113 +150,112 @@ class Turba_Driver_Imsp extends Turba_Driver
      * Reads the given data from the IMSP server and returns the
      * results.
      *
-     * @param string $key    The primary key field to use (always 'name' for IMSP).
+     * @param string $key    The primary key field to use (always 'name' for
+     *                       IMSP).
      * @param mixed $ids     The ids of the contacts to load.
      * @param string $owner  Only return contacts owned by this user.
      * @param array $fields  List of fields to return.
      *
      * @return array  Hash containing the search results.
+     * @throws Turba_Exception
      */
-    function _read($key, $ids, $owner, $fields)
+    protected function _read($key, $ids, $owner, $fields)
     {
         $results = array();
+
         if (!$this->_authenticated) {
             return $results;
         }
+
         $ids = array_values($ids);
         $idCount = count($ids);
-        $members = array();
-        $tmembers = array();
-        $IMSPGroups = array();
+        $IMSPGroups = $members = $tmembers = array();
 
-        for ($i = 0; $i < $idCount; $i++) {
+        for ($i = 0; $i < $idCount; ++$i) {
             $result = array();
-            if (!isset($IMSPGroups[$ids[$i]])) {
-                $temp = $this->_imsp->getEntry($this->_bookName, $ids[$i]);
-            } else {
-                $temp = $IMSPGroups[$ids[$i]];
-            }
-            if (is_a($temp, 'PEAR_Error')) {
+
+            $temp = isset($IMSPGroups[$ids[$i]])
+                ? $IMSPGroups[$ids[$i]]
+                : $this->_imsp->getEntry($this->_bookName, $ids[$i]);
+            if ($temp instanceof PEAR_Error) {
                 continue;
-            } else {
-                $temp['fullname'] = $temp['name'];
-                $isIMSPGroup = false;
-                if (!isset($temp['__owner'])) {
-                    $temp['__owner'] = $GLOBALS['registry']->getAuth();
-                }
+            }
 
-                if ((isset($temp[$this->_groupField])) &&
-                    ($temp[$this->_groupField] == $this->_groupValue)) {
-                    if ($this->_noGroups) {
-                        continue;
-                    }
-                    if (!isset($IMSPGroups[$ids[$i]])) {
-                        $IMSPGroups[$ids[$i]] = $temp;
-                    }
-                    // move group ids to end of list
-                    if ($idCount > count($IMSPGroups) &&
-                        $idCount - count($IMSPGroups) > $i) {
-                        $ids[] = $ids[$i];
-                        unset($ids[$i]);
-                        $ids = array_values($ids);
-                        $i--;
-                        continue;
-                    }
-                    $isIMSPGroup = true;
+            $temp['fullname'] = $temp['name'];
+            $isIMSPGroup = false;
+            if (!isset($temp['__owner'])) {
+                $temp['__owner'] = $GLOBALS['registry']->getAuth();
+            }
+
+            if ((isset($temp[$this->_groupField])) &&
+                ($temp[$this->_groupField] == $this->_groupValue)) {
+                if ($this->_noGroups) {
+                    continue;
+                }
+                if (!isset($IMSPGroups[$ids[$i]])) {
+                    $IMSPGroups[$ids[$i]] = $temp;
                 }
-                // Get the group members that might have been added from other
-                // IMSP applications, but only if we need more information than
-                // the group name
-                if ($isIMSPGroup &&
-                    array_search('__members', $fields) !== false) {
-
-                    if (isset($temp['email'])) {
-                        $emailList = $this->_getGroupEmails($temp['email']);
-                        $count = count($emailList);
-                        for ($j = 0; $j < $count; $j++) {
-                            $needMember = true;
-                            foreach ($results as $curResult) {
-                                if (!empty($curResult['email']) &&
-                                    strtolower($emailList[$j]) ==
-                                      strtolower(trim($curResult['email']))) {
-                                    $members[] = $curResult['name'];
-                                    $needMember = false;
-                                }
+                // move group ids to end of list
+                if ($idCount > count($IMSPGroups) &&
+                    $idCount - count($IMSPGroups) > $i) {
+                    $ids[] = $ids[$i];
+                    unset($ids[$i]);
+                    $ids = array_values($ids);
+                    --$i;
+                    continue;
+                }
+                $isIMSPGroup = true;
+            }
+            // Get the group members that might have been added from other
+            // IMSP applications, but only if we need more information than
+            // the group name
+            if ($isIMSPGroup &&
+                array_search('__members', $fields) !== false) {
+                if (isset($temp['email'])) {
+                    $emailList = $this->_getGroupEmails($temp['email']);
+                    $count = count($emailList);
+                    for ($j = 0; $j < $count; ++$j) {
+                        $needMember = true;
+                        foreach ($results as $curResult) {
+                            if (!empty($curResult['email']) &&
+                                strtolower($emailList[$j]) == strtolower(trim($curResult['email']))) {
+                                $members[] = $curResult['name'];
+                                $needMember = false;
                             }
-                            if ($needMember) {
-                                $memberName = $this->_imsp->search
-                                    ($this->_bookName,
-                                     array('email' => trim($emailList[$j])));
-
-                                if (count($memberName)) {
-                                    $members[] = $memberName[0];
-                                }
+                        }
+                        if ($needMember) {
+                            $memberName = $this->_imsp->search
+                                ($this->_bookName,
+                                 array('email' => trim($emailList[$j])));
+
+                            if (count($memberName)) {
+                                $members[] = $memberName[0];
                             }
                         }
                     }
-                    if (!empty($temp['__members'])) {
-                        $tmembers = @unserialize($temp['__members']);
-                    }
+                }
+                if (!empty($temp['__members'])) {
+                    $tmembers = @unserialize($temp['__members']);
+                }
 
-                    // TODO: Make sure that we are using the correct naming
-                    // convention for members regardless of if we are using
-                    // shares or not. This is needed to assure groups created
-                    // while not using shares won't be lost when transitioning
-                    // to shares and visa versa.
-                    //$tmembers = $this->_checkMemberFormat($tmembers);
-
-                    $temp['__members'] = serialize($this->_removeDuplicated(
-                                                   array($members, $tmembers)));
-                    $temp['__type'] = 'Group';
-                    $temp['email'] = null;
-                    $result = $temp;
-                } else {
-                    // IMSP contact.
-                    $count = count($fields);
-                    for ($j = 0; $j < $count; $j++) {
-                        if (isset($temp[$fields[$j]])) {
-                            $result[$fields[$j]] = $temp[$fields[$j]];
-                        }
+                // TODO: Make sure that we are using the correct naming
+                // convention for members regardless of if we are using
+                // shares or not. This is needed to assure groups created
+                // while not using shares won't be lost when transitioning
+                // to shares and visa versa.
+                //$tmembers = $this->_checkMemberFormat($tmembers);
+
+                $temp['__members'] = serialize($this->_removeDuplicated(
+                                               array($members, $tmembers)));
+                $temp['__type'] = 'Group';
+                $temp['email'] = null;
+                $result = $temp;
+            } else {
+                // IMSP contact.
+                $count = count($fields);
+                for ($j = 0; $j < $count; ++$j) {
+                    if (isset($temp[$fields[$j]])) {
+                        $result[$fields[$j]] = $temp[$fields[$j]];
                     }
                 }
             }
@@ -254,16 +263,13 @@ class Turba_Driver_Imsp extends Turba_Driver
             $results[] = $result;
         }
 
-        if (empty($results) && isset($temp) && is_a($temp, 'PEAR_Error')) {
-          return $temp;
-        }
         return $results;
     }
 
     /**
      * Adds the specified object to the IMSP server.
      */
-    function _add($attributes)
+    protected function _add($attributes)
     {
         /* We need to map out Turba_Object_Groups back to IMSP groups before
          * writing out to the server. We need to array_values() it in
@@ -288,21 +294,20 @@ class Turba_Driver_Imsp extends Turba_Driver
             // generally require an existing conact entry in the current
             // address book for each group member (this is necessary for
             // those sources that may be used both in AND out of Horde).
-            $result = $this->_read('name', $members, null, array('email'));
-            if (!is_a($result, 'PEAR_Error')) {
+            try {
+                $result = $this->_read('name', $members, null, array('email'));
                 $count = count($result);
-                for ($i = 0; $i < $count; $i++) {
+                for ($i = 0; $i < $count; ++$i) {
                     if (isset($result[$i]['email'])) {
                         $contact = sprintf("%s<%s>\n", $members[$i],
                                            $result[$i]['email']);
                         $attributes['email'] .= $contact;
                     }
                 }
-            }
+            } catch (Turba_Exception $e) {}
         }
 
-        unset($attributes['__type']);
-        unset($attributes['fullname']);
+        unset($attributes['__type'], unset($attributes['fullname']);
         if (!$this->params['contact_ownership']) {
             unset($attributes['__owner']);
         }
@@ -310,27 +315,38 @@ class Turba_Driver_Imsp extends Turba_Driver
         return $this->_imsp->addEntry($this->_bookName, $attributes);
     }
 
-    function _canAdd()
+    /**
+     * TODO
+     */
+    protected function _canAdd()
     {
         return true;
     }
 
     /**
      * Deletes the specified object from the IMSP server.
+     *
+     * @throws Turba_Exception
      */
-    function _delete($object_key, $object_id)
+    protected function _delete($object_key, $object_id)
     {
-        return $this->_imsp->deleteEntry($this->_bookName, $object_id);
+        $res = $this->_imsp->deleteEntry($this->_bookName, $object_id);
+        if ($res instanceof PEAR_Error) {
+            throw new Turba_Exception($res);
+        }
     }
 
     /**
      * Deletes the address book represented by this driver from the IMSP server.
      *
-     * @return mixed  true | PEAR_Error
+     * @throws Turba_Exception
      */
-     function _deleteAll()
+     protected function _deleteAll()
      {
-         $this->_imsp->deleteAddressbook($this->_bookName);
+         $res = $this->_imsp->deleteAddressbook($this->_bookName);
+         if ($res instanceof PEAR_Error) {
+             throw new Turba_Exception($res);
+         }
      }
 
     /**
@@ -339,8 +355,9 @@ class Turba_Driver_Imsp extends Turba_Driver
      * @param Turba_Object $object  The object to save/update.
      *
      * @return string  The object id, possibly updated.
+     * @throws Turba_Exception
      */
-    function _save($object)
+    protected function _save($object)
     {
         list($object_key, $object_id) = each($this->toDriverKeys(array('__key' => $object->getValue('__key'))));
         $attributes = $this->toDriverKeys($object->getAttributes());
@@ -352,8 +369,10 @@ class Turba_Driver_Imsp extends Turba_Driver
             $attributes['name'] = $this->_makeKey($attributes);
             $object_id = $attributes['name'];
         }
-        $result = $this->_add($attributes);
-        return is_a($result, 'PEAR_Error') ? $result : $object_id;
+
+        $this->_add($attributes);
+
+        return $object_id;
     }
 
     /**
@@ -364,7 +383,7 @@ class Turba_Driver_Imsp extends Turba_Driver
      *
      * @return string  A unique ID for the new object.
      */
-    function _makeKey($attributes)
+    protected function _makeKey($attributes)
     {
         return $attributes['fullname'];
     }
@@ -373,14 +392,13 @@ class Turba_Driver_Imsp extends Turba_Driver
      * Parses out $emailText into an array of pure email addresses
      * suitable for searching the IMSP datastore with.
      *
-     * @param $emailText string single string containing email addressses.
-     * @return array of pure email address.
+     * @param string $emailText  Single string containing email addressses.
+     *
+     * @return array  Pure email address.
      */
-    function _getGroupEmails($emailText)
+    protected function _getGroupEmails($emailText)
     {
-        $result = preg_match_all("(\w[-._\w]*\w@\w[-._\w]*\w\.\w{2,3})",
-                                 $emailText, $matches);
-
+        preg_match_all("(\w[-._\w]*\w@\w[-._\w]*\w\.\w{2,3})", $emailText, $matches);
         return $matches[0];
     }
 
@@ -393,7 +411,7 @@ class Turba_Driver_Imsp extends Turba_Driver
      *
      * @return array  Array containing contact names that match $criteria.
      */
-    function _doSearch($criteria, $glue)
+    protected function _doSearch($criteria, $glue)
     {
         $results = array();
         $names = array();
@@ -421,13 +439,9 @@ class Turba_Driver_Imsp extends Turba_Driver
             }
         }
 
-        if ($glue == 'AND') {
-            $names = $this->_getDuplicated($results);
-        } elseif ($glue == 'OR') {
-            $names = $this->_removeDuplicated($results);
-        }
-
-        return $names;
+        return ($glue == 'AND')
+            ? $this->_getDuplicated($results)
+            : $this->_removeDuplicated($results);
     }
 
     /**
@@ -509,11 +523,11 @@ class Turba_Driver_Imsp extends Turba_Driver
             $imspSearch['name'] = '*';
         }
 
-        /* Finally get to the command.  Check the cache first, since each 'Turba'
-           search may consist of a number of identical IMSP searchaddress calls in
-           order for the AND and OR parts to work correctly.  15 Second lifetime
-           should be reasonable for this. This should reduce load on IMSP server
-           somewhat.*/
+        /* Finally get to the command.  Check the cache first, since each
+         * 'Turba' search may consist of a number of identical IMSP
+         * searchaddress calls in order for the AND and OR parts to work
+         * correctly.  15 Second lifetime should be reasonable for this. This
+         * should reduce load on IMSP server somewhat.*/
         $results = $cache->get($key, 15);
 
         if ($results) {
@@ -522,7 +536,7 @@ class Turba_Driver_Imsp extends Turba_Driver
 
         if (!$names) {
             $names = $this->_imsp->search($this->_bookName, $imspSearch);
-            if (is_a($names, 'PEAR_Error')) {
+            if ($names instanceof PEAR_Error) {
                 $GLOBALS['notification']->push($names, 'horde.error');
             } else {
                 $cache->set($key, serialize($names));
@@ -540,24 +554,25 @@ class Turba_Driver_Imsp extends Turba_Driver
      *
      * @return array  Array containing the 'AND' of all arrays in $names
      */
-    function _getDuplicated($names)
+    protected function _getDuplicated($names)
     {
-        $results = array();
-        $matched = array();
+        $matched = $results = array();
+
         /* If there is only 1 array, simply return it. */
         if (count($names) < 2) {
             return $names[0];
-        } else {
-            for ($i = 0; $i < count($names); $i++) {
-                if (is_array($names[$i])) {
-                    $results = array_merge($results, $names[$i]);
-                }
+        }
+
+        for ($i = 0; $i < count($names); ++$i) {
+            if (is_array($names[$i])) {
+                $results = array_merge($results, $names[$i]);
             }
-            $search = array_count_values($results);
-            foreach ($search as $key => $value) {
-                if ($value > 1) {
-                    $matched[] = $key;
-                }
+        }
+
+        $search = array_count_values($results);
+        foreach ($search as $key => $value) {
+            if ($value > 1) {
+                $matched[] = $key;
             }
         }
 
@@ -571,14 +586,15 @@ class Turba_Driver_Imsp extends Turba_Driver
      *
      * @return array  Array containg the 'OR' of all arrays in $names.
      */
-    function _removeDuplicated($names)
+    protected function _removeDuplicated($names)
     {
         $unames = array();
-        for ($i = 0; $i < count($names); $i++) {
+        for ($i = 0; $i < count($names); ++$i) {
             if (is_array($names[$i])) {
                 $unames = array_merge($unames, $names[$i]);
             }
         }
+
         return array_unique($unames);
     }
 
@@ -590,7 +606,7 @@ class Turba_Driver_Imsp extends Turba_Driver
      *
      * @return boolean  true if user has permission, false otherwise.
      */
-    function hasPermission($perm)
+    public function hasPermission($perm)
     {
         return $this->_perms & $perm;
     }
@@ -602,9 +618,10 @@ class Turba_Driver_Imsp extends Turba_Driver
      *
      * @return integer  Horde Permissions bitmask.
      */
-    function _aclToHordePerms($acl)
+    protected function _aclToHordePerms($acl)
     {
         $hPerms = 0;
+
         if (strpos($acl, 'w') !== false) {
             $hPerms |= Horde_Perms::EDIT;
         }
@@ -617,6 +634,7 @@ class Turba_Driver_Imsp extends Turba_Driver
         if (strpos($acl, 'l') !== false) {
             $hPerms |= Horde_Perms::SHOW;
         }
+
         return $hPerms;
     }
 
@@ -626,51 +644,52 @@ class Turba_Driver_Imsp extends Turba_Driver
      *
      * @param array  The params for the share.
      *
-     * @return mixed  The share object or PEAR_Error.
+     * @return Horde_Share  The share object.
+     * @throws Turba_Exception
      */
-    function createShare($share_id, $params)
+    public function createShare($share_id, $params)
     {
-        if (isset($params['default']) && $params['default'] === true) {
-            $params['params']['name'] = $this->params['username'];
-        } else {
-            $params['params']['name'] = $this->params['username'] . '.' . $params['name'];
-        }
-        $result = Turba::createShare($share_id, $params);
-        if (is_a($result, 'PEAR_Error')) {
-            return $result;
+        $params['params']['name'] = $this->params['username'];
+        if (!isset($params['default']) || $params['default'] !== true) {
+            $params['params']['name'] .= '.' . $params['name'];
         }
 
+        $result = Turba::createShare($share_id, $params);
         $imsp_result = Net_IMSP_Utils::createBook($GLOBALS['cfgSources']['imsp'], $params['params']['name']);
-        if (is_a($imsp_result, 'PEAR_Error')) {
-            return $imsp_result;
+
+        if ($imsp_result instanceof PEAR_Error) {
+            throw new Turba_Exception($imsp_result);
         }
+
         return $result;
     }
 
     /**
-     * Helper function to count the occurances of the ':'
-     * delimter in group member entries.
+     * Helper function to count the occurances of the ':' * delimiter in group
+     * member entries.
      *
      * @param string $in  The group member entry.
      *
      * @return integer  The number of ':' in $in.
      */
-    function _countDelimiters($in)
+    protected function _countDelimiters($in)
     {
-        $cnt = 0;
-        $pos = 0;
+        $cnt = $pos = 0;
         $i = -1;
         while (($pos = strpos($in, ':', $pos + 1)) !== false) {
             ++$cnt;
         }
+
         return $cnt;
     }
 
     /**
      * Returns the owner for this contact. For an IMSP source, this should be
      * the name of the address book.
+     *
+     * @return string  TODO
      */
-    function _getContactOwner()
+    protected function _getContactOwner()
     {
        return $this->params['name'];
     }
@@ -679,8 +698,10 @@ class Turba_Driver_Imsp extends Turba_Driver
      * Check if the passed in share is the default share for this source.
      *
      * @see turba/lib/Turba_Driver#checkDefaultShare($share, $srcconfig)
+     *
+     * @return TODO
      */
-    function checkDefaultShare($share, $srcConfig)
+    protected function checkDefaultShare($share, $srcConfig)
     {
         $params = @unserialize($share->get('params'));
         if (!isset($params['default'])) {
index 19e1ca1..f58bf2f 100644 (file)
@@ -10,10 +10,12 @@ require_once 'Horde/Kolab.php';
  * See the enclosed file LICENSE for license information (ASL).  If you
  * did not receive this file, see http://www.horde.org/licenses/asl.php.
  *
- * @author  Thomas Jarosch <thomas.jarosch@intra2net.com>
- * @author  Gunnar Wrobel <wrobel@pardus.de>
- * @author  Stuart Binge <omicron@mighty.co.za>
- * @package Turba
+ * @author   Thomas Jarosch <thomas.jarosch@intra2net.com>
+ * @author   Gunnar Wrobel <wrobel@pardus.de>
+ * @author   Stuart Binge <omicron@mighty.co.za>
+ * @category Horde
+ * @license  http://www.horde.org/licenses/asl.php ASL
+ * @package  Turba
  */
 class Turba_Driver_Kolab extends Turba_Driver
 {
@@ -22,16 +24,16 @@ class Turba_Driver_Kolab extends Turba_Driver
      *
      * @var Kolab
      */
-    var $_kolab = null;
+    protected $_kolab = null;
 
     /**
      * The wrapper to decide between the Kolab implementation
      *
-     * @var Turba_Driver_kolab_wrapper
+     * @var Turba_Driver_kolab_Wrapper
      */
-    var $_wrapper = null;
+    protected $_wrapper = null;
 
-    var $_capabilities = array(
+    protected $_capabilities = array(
         'delete_addressbook' => true,
         'delete_all' => true,
     );
@@ -43,10 +45,10 @@ class Turba_Driver_Kolab extends Turba_Driver
     {
         $this->_kolab = new Kolab();
         $wrapper = empty($this->_kolab->version)
-            ? 'Turba_Driver_kolab_wrapper_old'
-            : 'Turba_Driver_kolab_wrapper_new';
+            ? 'Turba_Driver_Kolab_Wrapper_old'
+            : 'Turba_Driver_Kolab_Wrapper_new';
 
-        $this->_wrapper = new $wrapper($this->name, $this->_kolab);
+        $this->_wrapper = new $wrapper($this->_name, $this->_kolab);
     }
 
     /**
@@ -59,7 +61,7 @@ class Turba_Driver_Kolab extends Turba_Driver
      *
      * @return               Hash containing the search results.
      */
-    function _search($criteria, $fields)
+    protected function _search($criteria, $fields)
     {
         return $this->_wrapper->_search($criteria, $fields);
     }
@@ -75,7 +77,7 @@ class Turba_Driver_Kolab extends Turba_Driver
      *
      * @return array  Hash containing the search results.
      */
-    function _read($key, $ids, $owner, $fields)
+    protected function _read($key, $ids, $owner, $fields)
     {
         return $this->_wrapper->_read($key, $ids, $fields);
     }
@@ -83,12 +85,12 @@ class Turba_Driver_Kolab extends Turba_Driver
     /**
      * Adds the specified object to the Kolab message store.
      */
-    function _add($attributes)
+    protected function _add($attributes)
     {
         return $this->_wrapper->_add($attributes);
     }
 
-    function _canAdd()
+    protected function _canAdd()
     {
         return true;
     }
@@ -96,7 +98,7 @@ class Turba_Driver_Kolab extends Turba_Driver
     /**
      * Removes the specified object from the Kolab message store.
      */
-    function _delete($object_key, $object_id)
+    protected function _delete($object_key, $object_id)
     {
         return $this->_wrapper->_delete($object_key, $object_id);
     }
@@ -106,7 +108,7 @@ class Turba_Driver_Kolab extends Turba_Driver
      *
      * @return boolean  True if the operation worked.
      */
-    function _deleteAll($sourceName = null)
+    protected function _deleteAll($sourceName = null)
     {
         return $this->_wrapper->_deleteAll($sourceName);
     }
@@ -116,7 +118,7 @@ class Turba_Driver_Kolab extends Turba_Driver
      *
      * @return string  The object id, possibly updated.
      */
-    function _save($object)
+    protected function _save($object)
     {
         list($object_key, $object_id) = each($this->toDriverKeys(array('__key' => $object->getValue('__key'))));
         $attributes = $this->toDriverKeys($object->getAttributes());
@@ -132,12 +134,11 @@ class Turba_Driver_Kolab extends Turba_Driver
      *
      * @return string  A unique ID for the new object.
      */
-    function _makeKey($attributes)
+    protected function _makeKey($attributes)
     {
-        if (isset($attributes['uid'])) {
-            return $attributes['uid'];
-        }
-        return $this->generateUID();
+        return isset($attributes['uid'])
+            ? $attributes['uid']
+            : $this->generateUID();
     }
 
     /**
@@ -145,7 +146,7 @@ class Turba_Driver_Kolab extends Turba_Driver
      *
      * @return string  A unique ID for the new object.
      */
-    function generateUID()
+    public function generateUID()
     {
         return method_exists($this->_wrapper, 'generateUID')
             ? $this->_wrapper->generateUID()
@@ -153,1110 +154,30 @@ class Turba_Driver_Kolab extends Turba_Driver
     }
 
     /**
-     * Creates a new Horde_Share
+     * Creates a new Horde_Share.
      *
      * @param array  The params for the share.
      *
-     * @return mixed  The share object or PEAR_Error.
+     * @return Horde_Share  The share object.
      */
-    function createShare($share_id, $params)
+    public function createShare($share_id, $params)
     {
-        if (isset($params['params']['default']) && $params['params']['default'] === true) {
+        if (isset($params['params']['default']) &&
+            ($params['params']['default'] === true)) {
             $share_id = $GLOBALS['registry']->getAuth();
         }
 
-        $result = Turba::createShare($share_id, $params);
-        return $result;
-    }
-
-    function checkDefaultShare($share, $srcConfig)
-    {
-        $params = @unserialize($share->get('params'));
-        return isset($params['default']) ? $params['default'] : false;
-    }
-
-}
-
-/**
- * Horde Turba wrapper to distinguish between both Kolab driver implementations.
- *
- * Copyright 2004-2010 The Horde Project (http://www.horde.org/)
- *
- * See the enclosed file LICENSE for license information (ASL). If you
- * did not receive this file, see http://www.horde.org/licenses/asl.php.
- *
- * @author  Gunnar Wrobel <wrobel@pardus.de>
- * @package Turba
- */
-
-class Turba_Driver_Kolab_wrapper {
-
-    /**
-     * Indicates if the wrapper has connected or not
-     *
-     * @var boolean
-     */
-    var $_connected = false;
-
-    /**
-     * String containing the current addressbook name.
-     *
-     * @var string
-     */
-    var $_addressbook = '';
-
-    /**
-     * Our Kolab server connection.
-     *
-     * @var Kolab
-     */
-    var $_kolab = null;
-
-    /**
-     * Constructor
-     *
-     * @param string      $addressbook  The addressbook to load.
-     * @param Horde_Kolab $kolab        The Kolab connection object
-     */
-    public function __construct($addressbook, &$kolab)
-    {
-        if ($addressbook && $addressbook[0] == '_') {
-            $addressbook = substr($addressbook, 1);
-        }
-        $this->_addressbook = $addressbook;
-        $this->_kolab = &$kolab;
+        return Turba::createShare($share_id, $params);
     }
 
     /**
-     * Connect to the Kolab backend
-     *
-     * @param int    $loader         The version of the XML
-     *                               loader
-     *
-     * @return mixed True on success, a PEAR error otherwise
      */
-    function connect($loader = 0)
-    {
-        if ($this->_connected) {
-            return true;
-        }
-
-        $result = $this->_kolab->open($this->_addressbook, $loader);
-        if (is_a($result, 'PEAR_Error')) {
-            return $result;
-        }
-
-        $this->_connected = true;
-
-        return true;
-    }
-}
-
-/**
- * Horde Turba driver for the Kolab IMAP Server.
- * Copyright 2004-2010 The Horde Project (http://www.horde.org/)
- *
- * See the enclosed file LICENSE for license information (ASL).  If you
- * did not receive this file, see http://www.horde.org/licenses/asl.php.
- *
- * @author  Gunnar Wrobel <wrobel@pardus.de>
- * @author  Stuart Binge <omicron@mighty.co.za>
- * @package Turba
- */
-class Turba_Driver_Kolab_Wrapper_Old extends Turba_Driver_Kolab_Wrapper {
-
-    function _buildContact()
-    {
-        $k = &$this->_kolab;
-
-        $contact = array(
-            'uid' => $k->getUID(),
-            'owner' => $GLOBALS['registry']->getAuth(),
-            'job-title' => $k->getStr('job-title'),
-            'organization' => $k->getStr('organization'),
-            'body' => $k->getStr('body'),
-            'web-page' => $k->getStr('web-page'),
-            'nick-name' => $k->getStr('nick-name'),
-        );
-
-        $name = &$k->getRootElem('name');
-        $contact['full-name'] = $k->getElemStr($name, 'full-name');
-        $contact['given-name'] = $k->getElemStr($name, 'given-name');
-        $contact['last-name'] = $k->getElemStr($name, 'last-name');
-
-        $email = &$k->getRootElem('email');
-        $contact['smtp-address'] = $k->getElemStr($email, 'smtp-address');
-
-        $phones = &$k->getAllRootElems('phone');
-        for ($i = 0, $j = count($phones); $i < $j; $i++) {
-            $phone = &$phones[$i];
-            $type = $k->getElemStr($phone, 'type');
-
-            switch ($type) {
-            case 'home1':
-                $contact['home1'] = $k->getElemStr($phone, 'number');
-                break;
-
-            case 'business1':
-                $contact['business1'] = $k->getElemStr($phone, 'number');
-                break;
-
-            case 'mobile':
-                $contact['mobile'] = $k->getElemStr($phone, 'number');
-                break;
-
-            case 'businessfax':
-                $contact['businessfax'] = $k->getElemStr($phone, 'number');
-                break;
-            }
-        }
-
-        $addresses = &$k->getAllRootElems('address');
-        for ($i = 0, $j = count($addresses); $i < $j; $i++) {
-            $address = &$addresses[$i];
-            $type = $k->getElemStr($address, 'type');
-
-            switch ($type) {
-            case 'home':
-                $contact['home-street'] = $k->getElemStr($address, 'street');
-                $contact['home-locality'] = $k->getElemStr($address, 'locality');
-                $contact['home-region'] = $k->getElemStr($address, 'region');
-                $contact['home-postal-code'] = $k->getElemStr($address, 'postal-code');
-                $contact['home-country'] = $k->getElemStr($address, 'country');
-                break;
-
-            case 'business':
-                $contact['business-street'] = $k->getElemStr($address, 'street');
-                $contact['business-locality'] = $k->getElemStr($address, 'locality');
-                $contact['business-region'] = $k->getElemStr($address, 'region');
-                $contact['business-postal-code'] = $k->getElemStr($address, 'postal-code');
-                $contact['business-country'] = $k->getElemStr($address, 'country');
-                break;
-            }
-        }
-
-        return $contact;
-    }
-
-    function _setPhone($type, &$phone, $attributes)
-    {
-        if (empty($attributes[$type])) {
-            $this->_kolab->delRootElem($phone);
-        } else {
-            if ($phone === false) {
-                $phone = &$this->_kolab->appendRootElem('phone');
-                $this->_kolab->setElemStr($phone, 'type', $type);
-            }
-            $this->_kolab->setElemStr($phone, 'number', $attributes[$type]);
-        }
-    }
-
-    function _setAddress($type, &$address, $attributes)
-    {
-        if (empty($attributes["$type-street"]) && empty($attributes["$type-locality"]) &&
-            empty($attributes["$type-region"]) && empty($attributes["$type-postal-code"]) &&
-            empty($attributes["$type-country"])) {
-            $this->_kolab->delRootElem($address);
-        } else {
-            if ($address === false) {
-                $address = &$this->_kolab->appendRootElem('address');
-                $this->_kolab->setElemStr($address, 'type', $type);
-            }
-            $this->_kolab->setElemStr($address, 'street', $attributes["$type-street"]);
-            $this->_kolab->setElemStr($address, 'locality', $attributes["$type-locality"]);
-            $this->_kolab->setElemStr($address, 'region', $attributes["$type-region"]);
-            $this->_kolab->setElemStr($address, 'postal-code', $attributes["$type-postal-code"]);
-            $this->_kolab->setElemStr($address, 'country', $attributes["$type-country"]);
-        }
-    }
-
-    function _createContact(&$xml, $attributes)
+    public function checkDefaultShare($share, $srcConfig)
     {
-        $k = &$this->_kolab;
-
-        $name = &$k->initRootElem('name');
-        if (!empty($attributes['full-name'])) {
-            $k->setElemStr($name, 'full-name', $attributes['full-name']);
-        }
-        if (!empty($attributes['given-name'])) {
-            $k->setElemStr($name, 'given-name', $attributes['given-name']);
-        }
-        if (!empty($attributes['last-name'])) {
-            $k->setElemStr($name, 'last-name', $attributes['last-name']);
-        }
-
-        $email = &$k->initRootElem('email');
-        $k->setElemStr($email, 'display-name', $attributes['full-name']);
-        $k->setElemStr($email, 'smtp-address', $attributes['smtp-address']);
-
-        if (!empty($attributes['job-title'])) {
-            $k->setStr('job-title', $attributes['job-title']);
-        }
-        if (!empty($attributes['organization'])) {
-            $k->setStr('organization', $attributes['organization']);
-        }
-        if (!empty($attributes['body'])) {
-            $k->setStr('body', $attributes['body']);
-        }
-        if (!empty($attributes['web-page'])) {
-            $k->setStr('web-page', $attributes['web-page']);
-        }
-        if (!empty($attributes['nick-name'])) {
-            $k->setStr('nick-name', $attributes['nick-name']);
-        }
-
-        // Phones
-        $phones = &$k->getAllRootElems('phone');
-        $home = false;
-        $bus = false;
-        $mob = false;
-        $fax = false;
-        for ($i = 0, $j = count($phones); $i < $j; $i++) {
-            $phone = &$phones[$i];
-            $type = $k->getElemStr($phone, 'type');
-
-            switch ($type) {
-            case 'home1':
-                $home = &$phone;
-                break;
-
-            case 'business1':
-                $bus = &$phone;
-                break;
-
-            case 'mobile':
-                $mob = &$phone;
-                break;
-
-            case 'businessfax':
-                $fax = &$phone;
-                break;
-            }
-        }
-
-        $this->_setPhone('home1', $home, $attributes);
-        $this->_setPhone('business1', $bus, $attributes);
-        $this->_setPhone('mobile', $mob, $attributes);
-        $this->_setPhone('businessfax', $fax, $attributes);
-
-        // Addresses
-        $home = false;
-        $bus = false;
-        $addresses = &$k->getAllRootElems('address');
-        for ($i = 0, $j = count($addresses); $i < $j; $i++) {
-            $address = &$addresses[$i];
-            $type = $k->getElemStr($address, 'type');
-
-            switch ($type) {
-            case 'home':
-                $home = &$address;
-                break;
-
-            case 'business':
-                $bus = &$address;
-                break;
-            }
-        }
-
-        $this->_setAddress('home', $home, $attributes);
-        $this->_setAddress('business', $bus, $attributes);
-    }
-
-    /**
-     * Searches the Kolab message store with the given criteria and returns a
-     * filtered list of results. If the criteria parameter is an empty
-     * array, all records will be returned.
-     *
-     * @param $criteria      Array containing the search criteria.
-     * @param $fields        List of fields to return.
-     *
-     * @return               Hash containing the search results.
-     */
-    function _search($criteria, $fields)
-    {
-        $result = $this->connect();
-        if (is_a($result, 'PEAR_Error')) {
-            return $result;
-        }
-
-        if (!is_callable(array($this->_kolab, 'listObjectsInFolder'))) {
-            Horde::logMessage('The Framework Kolab package must be upgraded', 'ERR');
-            return PEAR::raiseError(_("Unable to search."));
-        }
-
-        $results = array();
-        $folders = $this->_kolab->listFolders();
-        foreach ($folders as $folder) {
-            if ($folder[1] != 'contact') {
-                continue;
-            }
-
-            $msg_list = $this->_kolab->listObjectsInFolder($folder[0]);
-            if (is_a($msg_list, 'PEAR_Error') || empty($msg_list)) {
-                return $msg_list;
-            }
-
-            foreach ($msg_list as $msg) {
-                $result = $this->_kolab->loadObject($msg, true);
-                if (is_a($result, 'PEAR_Error')) {
-                    return $result;
-                }
-
-                $contact = $this->_buildContact();
-
-                if ($this->_matchCriteria($contact, $criteria) == false) {
-                    continue;
-                }
-
-                $card = array();
-                foreach ($fields as $field) {
-                    $card[$field] = (isset($contact[$field]) ? $contact[$field] : '');
-                }
-
-                $results[] = $card;
-            }
-        }
-
-        return $results;
-    }
-
-    /**
-     * Read the given data from the Kolab message store and returns the
-     * result's fields.
-     *
-     * @param $criteria      Search criteria.
-     * @param $id            Data identifier.
-     * @param $fields        List of fields to return.
-     *
-     * @return               Hash containing the search results.
-     */
-    function _read($criteria, $id_list, $fields)
-    {
-        $result = $this->connect();
-        if (is_a($result, 'PEAR_Error')) {
-            return $result;
-        }
-
-        if ($criteria != 'uid') {
-            return array();
-        }
-
-        if (!is_array($id_list)) {
-            $id_list = array($id_list);
-        }
-
-        $results = array();
-        foreach ($id_list as $id) {
-            $result = $this->_kolab->loadObject($id);
-            if (is_a($result, 'PEAR_Error')) {
-                return $result;
-            }
-
-            $contact = $this->_buildContact($result);
-            $card = array();
-            foreach ($fields as $field) {
-                $card[$field] = (isset($contact[$field]) ? $contact[$field] : '');
-            }
-
-            $results[] = $card;
-        }
-
-        return $results;
-    }
-
-    /**
-     * Adds the specified object to the Kolab message store.
-     */
-    function _add($attributes)
-    {
-        $result = $this->connect();
-        if (is_a($result, 'PEAR_Error')) {
-            return $result;
-        }
-
-        $xml = &$this->_kolab->newObject($attributes['uid']);
-        if (is_a($xml, 'PEAR_Error')) {
-            return $xml;
-        }
-
-        $this->_createContact($xml, $attributes);
-
-        return $this->_kolab->saveObject();
-    }
-
-    /**
-     * Removes the specified object from the Kolab message store.
-     */
-    function _delete($object_key, $object_id)
-    {
-        $result = $this->connect();
-        if (is_a($result, 'PEAR_Error')) {
-            return $result;
-        }
-
-        if ($object_key != 'uid') {
-            return false;
-        }
-
-        return $this->_kolab->removeObjects($object_id);
-    }
-
-    /**
-     * Deletes all contacts from a specific address book.
-     *
-     * @return boolean  True if the operation worked.
-     */
-    function _deleteAll($sourceName = null)
-    {
-        $result = $this->connect();
-        if (is_a($result, 'PEAR_Error')) {
-            return $result;
-        }
-
-        if ($sourceName != null) {
-            Horde::logMessage('deleteAll only working for current share. Called for $sourceName', 'ERR');
-            return PEAR::raiseError(sprintf(_("Cannot delete all address book entries for %s"), $sourceName));
-        }
-
-        return $this->_kolab->removeAllObjects();
-    }
-
-    /**
-     * Updates an existing object in the Kolab message store.
-     *
-     * @return string  The object id, possibly updated.
-     */
-    function _save($object_key, $object_id, $attributes)
-    {
-        $result = $this->connect();
-        if (is_a($result, 'PEAR_Error')) {
-            return $result;
-        }
-
-        if ($object_key != 'uid') {
-            return PEAR::raiseError('key must be uid');
-        }
-
-        $xml = &$this->_kolab->loadObject($object_id);
-        if (is_a($xml, 'PEAR_Error')) {
-            return $xml;
-        }
-
-        $this->_createContact($xml, $attributes);
-
-        $result = $this->_kolab->saveObject();
-        if (is_a($result, 'PEAR_Error')) {
-            return $result;
-        }
-
-        return $object_id;
-    }
-
-    /**
-     * Checks whether a contact matches a given criteria.
-     *
-     * @param array $contact       The contact.
-     * @param array $criteria      The criteria.
-     *
-     * @return boolean  Wether the passed string corresponding to $criteria.
-     *
-     * @access private
-     */
-    function _matchCriteria($contact, $criteria)
-    {
-        $values = array_values($criteria);
-        $values = $values[0];
-        $ok = true;
-
-        for ($current = 0; $current < count($values); ++$current) {
-            $temp = $values[$current];
-
-            while (!empty($temp) && !array_key_exists('field', $temp)) {
-                $temp = array_values($temp);
-                $temp = $temp[0];
-            }
-
-            if (empty($temp)) {
-                continue;
-            }
-
-            $searchkey = $temp['field'];
-            $searchval = $temp['test'];
-
-            if (stristr($contact[$searchkey], $searchval) == false) {
-                $ok = $ok && false;
-            } else {
-                $ok = $ok && true;
-            }
-        }
-
-        return $ok;
-    }
-}
-
-/**
- * New Horde Turba driver for the Kolab IMAP Server.
- * Copyright 2004-2010 The Horde Project (http://www.horde.org/)
- *
- * See the enclosed file LICENSE for license information (ASL).  If you
- * did not receive this file, see http://www.horde.org/licenses/asl.php.
- *
- * @author  Gunnar Wrobel <wrobel@pardus.de>
- * @author  Thomas Jarosch <thomas.jarosch@intra2net.com>
- * @package Turba
- */
-class Turba_Driver_Kolab_Wrapper_New extends Turba_Driver_Kolab_Wrapper {
-
-    /**
-     * Internal cache of Kronolith_Event_kolab_new. eventID/UID is key
-     *
-     * @var array
-     */
-    var $_contacts_cache;
-
-    /**
-     * Shortcut to the imap connection
-     *
-     * @var Kolab_IMAP
-     */
-    var $_store = null;
-
-    /**
-     * Connect to the Kolab backend
-     *
-     * @return mixed True on success, a PEAR error otherwise
-     */
-    function connect()
-    {
-        $result = parent::connect(1);
-        if (is_a($result, 'PEAR_Error')) {
-            return $result;
-        }
-
-        $this->_store = &$this->_kolab->_storage;
-
-        /* Fetch the contacts first */
-        $raw_contacts = $this->_store->getObjectArray();
-        if (!$raw_contacts) {
-            $raw_contacts = array();
-        }
-        $contacts = array();
-        foreach ($raw_contacts as $id => $contact) {
-            if (isset($contact['email'])) {
-                unset($contact['email']);
-            }
-            if (isset($contact['picture'])) {
-                $name = $contact['picture'];
-                if (isset($contact['_attachments'][$name])) {
-                    $contact['photo'] =  $this->_store->_data->getAttachment($contact['_attachments'][$name]['key']);
-                    $contact['phototype'] = $contact['_attachments'][$name]['type'];
-                }
-            }
-
-            $contacts[$id] = $contact;
-        }
-
-        /* Now we retrieve distribution-lists */
-        $result = $this->_store->setObjectType('distribution-list');
-        if (is_a($result, 'PEAR_Error')) {
-            return $result;
-        }
-        $groups = $this->_store->getObjectArray();
-        if (!$groups) {
-            $groups = array();
-        }
-
-        /* Revert to the original state */
-        $result = $this->_store->setObjectType('contact');
-        if (is_a($result, 'PEAR_Error')) {
-            return $result;
-        }
-
-        /* Store the results in our cache */
-        $this->_contacts_cache = array_merge($contacts, $groups);
-
-        return true;
-    }
-
-    /**
-     * Searches the Kolab message store with the given criteria and returns a
-     * filtered list of results. If the criteria parameter is an empty
-     * array, all records will be returned.
-     *
-     * @param $criteria      Array containing the search criteria.
-     * @param $fields        List of fields to return.
-     *
-     * @return               Hash containing the search results.
-     */
-    function _search($criteria, $fields)
-    {
-        $result = $this->connect();
-        if (is_a($result, 'PEAR_Error')) {
-            return $result;
-        }
-
-        if (!count($criteria)) {
-            return $this->_contacts_cache;
-        }
-
-        // keep only entries matching criteria
-        $ids = array();
-        foreach ($criteria as $key => $criteria) {
-            $ids[] = $this->_doSearch($criteria, strval($key), $this->_contacts_cache);
-        }
-        $ids = $this->_removeDuplicated($ids);
-
-        /* Now we have a list of names, get the rest. */
-        $result = $this->_read('uid', $ids, $fields);
-        if (is_a($result, 'PEAR_Error')) {
-            return $result;
-        }
-
-        Horde::logMessage(sprintf('Kolab returned %s results',
-                                  count($result)), 'DEBUG');
-        return array_values($result);
-    }
-
-    /**
-     * Applies the filter criteria to a list of entries
-     *
-     * @param $criteria      Array containing the search criteria.
-     * @param $fields        List of fields to return.
-     *
-     * @return array         Array containing the ids of the selected entries
-     */
-    function _doSearch($criteria, $glue, &$entries)
-    {
-        $ids = array();
-        foreach ($criteria as $key => $vals) {
-            if (!empty($vals['OR'])) {
-                $ids[] = $this->_doSearch($vals['OR'], 'OR', $entries);
-            } elseif (!empty($vals['AND'])) {
-                $ids[] = $this->_doSearch($vals['AND'], 'AND', $entries);
-            } else {
-                /* If we are here, and we have a ['field'] then we
-                 * must either do the 'AND' or the 'OR' search. */
-                if (isset($vals['field'])) {
-                    $ids[] = $this->_selectEntries($vals, $entries);
-                } else {
-                    foreach ($vals as $test) {
-                        if (!empty($test['OR'])) {
-                            $ids[] = $this->_doSearch($test['OR'], 'OR');
-                        } elseif (!empty($test['AND'])) {
-                            $ids[] = $this->_doSearch($test['AND'], 'AND');
-                        } else {
-                            $ids[] = $this->_doSearch(array($test), $glue);
-                        }
-                    }
-                }
-            }
-        }
-
-        if ($glue == 'AND') {
-            $ids = $this->_getAND($ids);
-        } elseif ($glue == 'OR') {
-            $ids = $this->_removeDuplicated($ids);
-        }
-
-        return $ids;
-    }
-
-    /**
-     * Applies one filter criterium to a list of entries
-     *
-     * @param $test          Test criterium
-     * @param $entries       List of fields to return.
-     *
-     * @return array         Array containing the ids of the selected entries
-     */
-    function _selectEntries($test, &$entries)
-    {
-        $ids = array();
-
-        if (!isset($test['field'])) {
-            Horde::logMessage('Search field not set. Returning all entries.', 'DEBUG');
-            foreach ($entries as $entry) {
-                $ids[] = $entry['uid'];
-            }
-        } else {
-            $field = $test['field'];
-            if (isset($test['test'])) {
-                $value = $test['test'];
-            } else {
-                $value = '';
-            }
-            // Special emails hack
-            if ($field == 'email') {
-                $field = 'emails';
-                $test['op'] = 'LIKE';
-                $test['begin'] = false;
-            }
-            if (!isset($test['op']) || $test['op'] == '=') {
-                foreach ($entries as $entry) {
-                    if (isset($entry[$field]) && $entry[$field] == $value) {
-                        $ids[] = $entry['uid'];
-                    }
-                }
-            } else {
-                // 'op' is LIKE
-                foreach ($entries as $entry) {
-                    if (empty($value) ||
-                        (isset($entry[$field]) &&
-                         !empty($test['begin']) &&
-                         (($pos = stripos($entry[$field], $value)) !== false) &&
-                         ($pos == 0))) {
-                        $ids[] = $entry['uid'];
-                    }
-                }
-            }
-        }
-
-        return $ids;
-    }
-
-    /**
-     * Returns only those names that are duplicated in $ids
-     *
-     * @param array $ids  A nested array of arrays containing names
-     *
-     * @return array  Array containing the 'AND' of all arrays in $ids
-     */
-    function _getAND($ids)
-    {
-        $results = array();
-        $matched = array();
-        /* If there is only 1 array, simply return it. */
-        if (count($ids) < 2) {
-            return $ids[0];
-        } else {
-            for ($i = 0; $i < count($ids); $i++) {
-                if (is_array($ids[$i])) {
-                    $results = array_merge($results, $ids[$i]);
-                }
-            }
-        }
-        $search = array_count_values($results);
-        foreach ($search as $key => $value) {
-            if ($value == count($ids)) {
-                $matched[] = $key;
-            }
-        }
-
-        return $matched;
-    }
-
-    /**
-     * Returns an array with all duplicate names removed.
-     *
-     * @param array $ids  Nested array of arrays containing names.
-     *
-     * @return array  Array containg the 'OR' of all arrays in $ids.
-     */
-    function _removeDuplicated($ids)
-    {
-        $unames = array();
-        for ($i = 0; $i < count($ids); $i++) {
-            if (is_array($ids[$i])) {
-                $unames = array_merge($unames, $ids[$i]);
-            }
-        }
-        return array_unique($unames);
-    }
-
-    /**
-     * Read the given data from the Kolab message store and returns the
-     * result's fields.
-     *
-     * @param string $key    The primary key field to use (always 'uid' for Kolab).
-     * @param $ids           Data identifiers
-     * @param $fields        List of fields to return.
-     *
-     * @return               Hash containing the search results.
-     */
-    function _read($key, $ids, $fields)
-    {
-        $result = $this->connect();
-        if (is_a($result, 'PEAR_Error')) {
-            return $result;
-        }
-
-        $results = array();
-
-        if (!is_array($ids)) {
-            $ids = array($ids);
-        }
-
-        $count = count($fields);
-        foreach ($ids as $id) {
-            if (in_array($id, array_keys($this->_contacts_cache))) {
-                $object = $this->_contacts_cache[$id];
-
-                $object_type = $this->_contacts_cache[$id]['__type'];
-                if (!isset($object['__type']) || $object['__type'] == 'Object') {
-                    if ($count) {
-                        $result = array();
-                        foreach ($fields as $field) {
-                            if (isset($object[$field])) {
-                                $result[$field] = $object[$field];
-                            }
-                        }
-                        $results[] = $result;
-                    } else {
-                        $results[] = $object;
-                    }
-                } else {
-                    $member_ids = array();
-                    if (isset($object['member'])) {
-                        foreach ($object['member'] as $member) {
-                            if (isset($member['uid'])) {
-                                $member_ids[] = $member['uid'];
-                                continue;
-                            }
-                            $display_name = $member['display-name'];
-                            $smtp_address = $member['smtp-address'];
-                            $criteria = array(
-                                'AND' => array(
-                                    array(
-                                        'field' => 'full-name',
-                                        'op' => 'LIKE',
-                                        'test' => $display_name,
-                                        'begin' => false,
-                                    ),
-                                    array(
-                                        'field' => 'emails',
-                                        'op' => 'LIKE',
-                                        'test' => $smtp_address,
-                                        'begin' => false,
-                                    ),
-                                ),
-                            );
-                            $fields = array('uid');
-
-                            // we expect only one result here!!!
-                            $contacts = $this->_search($criteria, $fields);
-
-                            // and drop everything else except the first search result
-                            $member_ids[] = $contacts[0]['uid'];
-                        }
-                        $object['__members'] = serialize($member_ids);
-                        unset($object['member']);
-                    }
-                    $results[] = $object;;
-                }
-            }
-        }
-
-
-        return $results;
-    }
-
-    /**
-     * Adds the specified object to the Kolab message store.
-     */
-    function _add($attributes)
-    {
-        $result = $this->connect();
-        if (is_a($result, 'PEAR_Error')) {
-            return $result;
-        }
-
-        $attributes['full-name'] = $attributes['last-name'];
-        if (isset($attributes['middle-names'])) {
-            $attributes['full-name'] = $attributes['middle-names'] . ' ' . $attributes['full-name'];
-        }
-        if (isset($attributes['given-name'])) {
-            $attributes['full-name'] = $attributes['given-name'] . ' ' . $attributes['full-name'];
-        }
-
-        $result = $this->_store($attributes);
-        if (is_a($result, 'PEAR_Error')) {
-            return $result;
-        }
-        return true;
-    }
-
-    /**
-     * Updates an existing object in the Kolab message store.
-     *
-     * @return string  The object id, possibly updated.
-     */
-    function _save($object_key, $object_id, $attributes)
-    {
-        $result = $this->connect();
-        if (is_a($result, 'PEAR_Error')) {
-            return $result;
-        }
-
-        if ($object_key != 'uid') {
-            return PEAR::raiseError(sprintf('Key for saving must be \'uid\' not %s!', $object_key));
-        }
-
-        return $this->_store($attributes, $object_id);
-    }
-
-    /**
-     * Stores an object in the Kolab message store.
-     *
-     * @return string  The object id, possibly updated.
-     */
-    function _store($attributes, $object_id = null)
-    {
-        $group = false;
-        if (isset($attributes['__type']) && $attributes['__type'] == 'Group') {
-            $group = true;
-            $result = $this->_store->setObjectType('distribution-list');
-            if (is_a($result, 'PEAR_Error')) {
-                return $result;
-            }
-            $this->_convertMembers($attributes);
-        }
-
-        if (isset($attributes['photo']) && isset($attributes['phototype'])) {
-            $attributes['_attachments']['photo.attachment'] = array('type' => $attributes['phototype'],
-                                                                    'content' => $attributes['photo']);
-            $attributes['picture'] = 'photo.attachment';
-            unset($attributes['photo']);
-            unset($attributes['phototype']);
-        }
-
-        $result = $this->_store->save($attributes, $object_id);
-        if (is_a($result, 'PEAR_Error')) {
-            return $result;
-        }
-
-        if ($group) {
-            $result = $this->_store->setObjectType('contact');
-            if (is_a($result, 'PEAR_Error')) {
-                return $result;
-            }
-        }
-
-        return $object_id;
-    }
-
-    function _convertMembers(&$attributes)
-    {
-        if (isset($attributes['__members'])) {
-            $member_ids = unserialize($attributes['__members']);
-            $attributes['member'] = array();
-            foreach ($member_ids as $member_id) {
-                if (isset($this->_contacts_cache[$member_id])) {
-                    $member = $this->_contacts_cache[$member_id];
-                    $mail = array('uid' => $member_id);
-                    if (!empty($member['full-name'])) {
-                        $mail['display-name'] = $member['full-name'];
-                    }
-                    if (!empty($member['emails'])) {
-                        $emails = explode(',', $member['emails']);
-                        $mail['smtp-address'] = trim($emails[0]);
-                        if (!isset($mail['display-name'])) {
-                            $mail['display-name'] = $mail['smtp-address'];
-                        }
-                    }
-                    $attributes['member'][] = $mail;
-                }
-            }
-            unset($attributes['__members']);
-        }
-    }
-
-
-    /**
-     * Removes the specified object from the Kolab message store.
-     */
-    function _delete($object_key, $object_id)
-    {
-        $result = $this->connect();
-        if (is_a($result, 'PEAR_Error')) {
-            return $result;
-        }
-
-        if ($object_key != 'uid') {
-            return PEAR::raiseError(sprintf('Key for saving must be a UID not %s!', $object_key));
-        }
-
-        if (!in_array($object_id, array_keys($this->_contacts_cache))) {
-            return PEAR::raiseError(sprintf(_("Object with UID %s does not exist!"), $object_id));
-        }
-
-        $group = false;
-        if (isset($this->_contacts_cache[$object_id]['__type'])
-            && $this->_contacts_cache[$object_id]['__type'] == 'Group') {
-            $group = true;
-        }
-
-        if ($group) {
-            $result = $this->_store->setObjectType('distribution-list');
-            if (is_a($result, 'PEAR_Error')) {
-                return $result;
-            }
-        }
-
-        $result = $this->_store->delete($object_id);
-
-        if ($group) {
-            $result = $this->_store->setObjectType('contact');
-            if (is_a($result, 'PEAR_Error')) {
-                return $result;
-            }
-        }
-
-        return $result;
-    }
-
-    /**
-     * Deletes all contacts from a specific address book.
-     *
-     * @return boolean  True if the operation worked.
-     */
-    function _deleteAll($sourceName = null)
-    {
-        $result = $this->connect();
-        if (is_a($result, 'PEAR_Error')) {
-            return $result;
-        }
-
-        /* Delete contacts */
-        $result = $this->_store->deleteAll();
-        if (is_a($result, 'PEAR_Error')) {
-            return $result;
-        }
-
-        /* Delete groups */
-        $result = $this->_store->setObjectType('distribution-list');
-        if (is_a($result, 'PEAR_Error')) {
-            return $result;
-        }
-        $result = $this->_store->deleteAll();
-        if (is_a($result, 'PEAR_Error')) {
-            return $result;
-        }
-
-        /* Revert to the original state */
-        return $this->_store->setObjectType('contact');
-        if (is_a($result, 'PEAR_Error')) {
-            return $result;
-        }
-
-        return true;
+        $params = @unserialize($share->get('params'));
+        return isset($params['default'])
+            ? $params['default']
+            : false;
     }
 
-    /**
-     * Create an object key for a new object.
-     *
-     * @return string  A unique ID for the new object.
-     */
-    function generateUID()
-    {
-        $result = $this->connect();
-        if (is_a($result, 'PEAR_Error')) {
-            return $result;
-        }
-
-        do {
-            $key = strval(new Horde_Support_Uuid());
-        } while(in_array($key, array_keys($this->_contacts_cache)));
-
-        return $key;
-    }
 }
diff --git a/turba/lib/Driver/Kolab/Wrapper.php b/turba/lib/Driver/Kolab/Wrapper.php
new file mode 100644 (file)
index 0000000..90041ea
--- /dev/null
@@ -0,0 +1,73 @@
+<?php
+/**
+ * Horde Turba wrapper to distinguish between both Kolab driver
+ * implementations.
+ *
+ * Copyright 2004-2010 The Horde Project (http://www.horde.org/)
+ *
+ * See the enclosed file LICENSE for license information (ASL).  If you
+ * did not receive this file, see http://www.horde.org/licenses/asl.php.
+ *
+ * @author   Gunnar Wrobel <wrobel@pardus.de>
+ * @category Horde
+ * @license  http://www.horde.org/licenses/asl.php ASL
+ * @package  Turba
+ */
+class Turba_Driver_Kolab_Wrapper
+{
+    /**
+     * Indicates if the wrapper has connected or not
+     *
+     * @var boolean
+     */
+    protected $_connected = false;
+
+    /**
+     * String containing the current addressbook name.
+     *
+     * @var string
+     */
+    protected $_addressbook = '';
+
+    /**
+     * Our Kolab server connection.
+     *
+     * @var Kolab
+     */
+    protected $_kolab = null;
+
+    /**
+     * Constructor
+     *
+     * @param string      $addressbook  The addressbook to load.
+     * @param Horde_Kolab $kolab        The Kolab connection object
+     */
+    public function __construct($addressbook, &$kolab)
+    {
+        if ($addressbook && $addressbook[0] == '_') {
+            $addressbook = substr($addressbook, 1);
+        }
+        $this->_addressbook = $addressbook;
+        $this->_kolab = &$kolab;
+    }
+
+    /**
+     * Connect to the Kolab backend
+     *
+     * @param integer $loader  The version of the XML loader.
+     *
+     * @throws Turba_Exception
+     */
+    public function connect($loader = 0)
+    {
+        if (!$this->_connected) {
+            $result = $this->_kolab->open($this->_addressbook, $loader);
+            if ($result instanceof PEAR_Error) {
+                throw new Turba_Exception($result);
+            }
+        }
+
+        $this->_connected = true;
+    }
+
+}
diff --git a/turba/lib/Driver/Kolab/Wrapper/New.php b/turba/lib/Driver/Kolab/Wrapper/New.php
new file mode 100644 (file)
index 0000000..84fec84
--- /dev/null
@@ -0,0 +1,552 @@
+<?php
+/**
+ * New Horde Turba driver for the Kolab IMAP Server.
+ *
+ * Copyright 2004-2010 The Horde Project (http://www.horde.org/)
+ *
+ * See the enclosed file LICENSE for license information (ASL).  If you
+ * did not receive this file, see http://www.horde.org/licenses/asl.php.
+ *
+ * @author   Gunnar Wrobel <wrobel@pardus.de>
+ * @author   Thomas Jarosch <thomas.jarosch@intra2net.com>
+ * @category Horde
+ * @license  http://www.horde.org/licenses/asl.php ASL
+ * @package  Turba
+ */
+class Turba_Driver_Kolab_Wrapper_New extends Turba_Driver_Kolab_Wrapper
+{
+    /**
+     * Internal cache of Kronolith_Event_kolab_new. eventID/UID is key
+     *
+     * @var array
+     */
+    protected $_contacts_cache;
+
+    /**
+     * Shortcut to the imap connection
+     *
+     * @var Kolab_IMAP
+     */
+    protected $_store = null;
+
+    /**
+     * Connect to the Kolab backend.
+     *
+     * @throws Turba_Exception
+     */
+    function connect()
+    {
+        parent::connect(1);
+
+        $this->_store = &$this->_kolab->_storage;
+
+        /* Fetch the contacts first */
+        $raw_contacts = $this->_store->getObjectArray();
+        if (!$raw_contacts) {
+            $raw_contacts = array();
+        }
+        $contacts = array();
+        foreach ($raw_contacts as $id => $contact) {
+            if (isset($contact['email'])) {
+                unset($contact['email']);
+            }
+            if (isset($contact['picture'])) {
+                $name = $contact['picture'];
+                if (isset($contact['_attachments'][$name])) {
+                    $contact['photo'] =  $this->_store->_data->getAttachment($contact['_attachments'][$name]['key']);
+                    $contact['phototype'] = $contact['_attachments'][$name]['type'];
+                }
+            }
+
+            $contacts[$id] = $contact;
+        }
+
+        /* Now we retrieve distribution-lists */
+        $result = $this->_store->setObjectType('distribution-list');
+        if ($result instanceof PEAR_Error) {
+            throw new Turba_Exception($result);
+        }
+        $groups = $this->_store->getObjectArray();
+        if (!$groups) {
+            $groups = array();
+        }
+
+        /* Revert to the original state */
+        $result = $this->_store->setObjectType('contact');
+        if ($result instanceof PEAR_Error) {
+            throw new Turba_Exception($result);
+        }
+
+        /* Store the results in our cache */
+        $this->_contacts_cache = array_merge($contacts, $groups);
+    }
+
+    /**
+     * Searches the Kolab message store with the given criteria and returns a
+     * filtered list of results. If the criteria parameter is an empty
+     * array, all records will be returned.
+     *
+     * @param array $criteria  Array containing the search criteria.
+     * @param array $fields    List of fields to return.
+     *
+     * @return array Hash containing the search results.
+     * @throws Turba_Exception
+     */
+    protected function _search($criteria, $fields)
+    {
+        $this->connect();
+
+        if (!count($criteria)) {
+            return $this->_contacts_cache;
+        }
+
+        // keep only entries matching criteria
+        $ids = array();
+        foreach ($criteria as $key => $criteria) {
+            $ids[] = $this->_doSearch($criteria, strval($key), $this->_contacts_cache);
+        }
+        $ids = $this->_removeDuplicated($ids);
+
+        /* Now we have a list of names, get the rest. */
+        $this->_read('uid', $ids, $fields);
+
+        Horde::logMessage(sprintf('Kolab returned %s results',
+                                  count($result)), 'DEBUG');
+
+        return array_values($result);
+    }
+
+    /**
+     * Applies the filter criteria to a list of entries
+     *
+     * @param array $criteria  Array containing the search criteria.
+     * @param array $fields    List of fields to return.
+     *
+     * @return array  Array containing the ids of the selected entries.
+     */
+    protected function _doSearch($criteria, $glue, &$entries)
+    {
+        $ids = array();
+
+        foreach ($criteria as $key => $vals) {
+            if (!empty($vals['OR'])) {
+                $ids[] = $this->_doSearch($vals['OR'], 'OR', $entries);
+            } elseif (!empty($vals['AND'])) {
+                $ids[] = $this->_doSearch($vals['AND'], 'AND', $entries);
+            } else {
+                /* If we are here, and we have a ['field'] then we
+                 * must either do the 'AND' or the 'OR' search. */
+                if (isset($vals['field'])) {
+                    $ids[] = $this->_selectEntries($vals, $entries);
+                } else {
+                    foreach ($vals as $test) {
+                        if (!empty($test['OR'])) {
+                            $ids[] = $this->_doSearch($test['OR'], 'OR');
+                        } elseif (!empty($test['AND'])) {
+                            $ids[] = $this->_doSearch($test['AND'], 'AND');
+                        } else {
+                            $ids[] = $this->_doSearch(array($test), $glue);
+                        }
+                    }
+                }
+            }
+        }
+
+        if ($glue == 'AND') {
+            $ids = $this->_getAND($ids);
+        } elseif ($glue == 'OR') {
+            $ids = $this->_removeDuplicated($ids);
+        }
+
+        return $ids;
+    }
+
+    /**
+     * Applies one filter criterium to a list of entries
+     *
+     * @param $test          Test criterium
+     * @param &$entries       List of fields to return.
+     *
+     * @return array  Array containing the ids of the selected entries
+     */
+    protected function _selectEntries($test, &$entries)
+    {
+        $ids = array();
+
+        if (!isset($test['field'])) {
+            Horde::logMessage('Search field not set. Returning all entries.', 'DEBUG');
+            foreach ($entries as $entry) {
+                $ids[] = $entry['uid'];
+            }
+        } else {
+            $field = $test['field'];
+            $value = isset($test['test'])
+                ? $test['test']
+                : '';
+
+            // Special emails hack
+            if ($field == 'email') {
+                $field = 'emails';
+                $test['op'] = 'LIKE';
+                $test['begin'] = false;
+            }
+            if (!isset($test['op']) || $test['op'] == '=') {
+                foreach ($entries as $entry) {
+                    if (isset($entry[$field]) && $entry[$field] == $value) {
+                        $ids[] = $entry['uid'];
+                    }
+                }
+            } else {
+                // 'op' is LIKE
+                foreach ($entries as $entry) {
+                    if (empty($value) ||
+                        (isset($entry[$field]) &&
+                         !empty($test['begin']) &&
+                         (($pos = stripos($entry[$field], $value)) !== false) &&
+                         ($pos == 0))) {
+                        $ids[] = $entry['uid'];
+                    }
+                }
+            }
+        }
+
+        return $ids;
+    }
+
+    /**
+     * Returns only those names that are duplicated in $ids
+     *
+     * @param array $ids  A nested array of arrays containing names
+     *
+     * @return array  Array containing the 'AND' of all arrays in $ids
+     */
+    protected function _getAND($ids)
+    {
+        $matched = $results = array();
+
+        /* If there is only 1 array, simply return it. */
+        if (count($ids) < 2) {
+            return $ids[0];
+        }
+
+        for ($i = 0; $i < count($ids); ++$i) {
+            if (is_array($ids[$i])) {
+                $results = array_merge($results, $ids[$i]);
+            }
+        }
+
+        $search = array_count_values($results);
+        foreach ($search as $key => $value) {
+            if ($value == count($ids)) {
+                $matched[] = $key;
+            }
+        }
+
+        return $matched;
+    }
+
+    /**
+     * Returns an array with all duplicate names removed.
+     *
+     * @param array $ids  Nested array of arrays containing names.
+     *
+     * @return array  Array containg the 'OR' of all arrays in $ids.
+     */
+    protected function _removeDuplicated($ids)
+    {
+        for ($i = 0; $i < count($ids); ++$i) {
+            if (is_array($ids[$i])) {
+                $unames = array_merge($unames, $ids[$i]);
+            }
+        }
+
+        return array_unique($unames);
+    }
+
+    /**
+     * Read the given data from the Kolab message store and returns the
+     * result's fields.
+     *
+     * @param string $key    The primary key field to use (always 'uid' for
+     *                       Kolab).
+     * @param array $ids     Data identifiers
+     * @param array $fields  List of fields to return.
+     *
+     * @return array  Hash containing the search results.
+     * @throws Turba_Exception
+     */
+    protected function _read($key, $ids, $fields)
+    {
+        $this->connect();
+
+        $results = array();
+
+        if (!is_array($ids)) {
+            $ids = array($ids);
+        }
+
+        $count = count($fields);
+        foreach ($ids as $id) {
+            if (in_array($id, array_keys($this->_contacts_cache))) {
+                $object = $this->_contacts_cache[$id];
+
+                $object_type = $this->_contacts_cache[$id]['__type'];
+                if (!isset($object['__type']) || $object['__type'] == 'Object') {
+                    if ($count) {
+                        $result = array();
+                        foreach ($fields as $field) {
+                            if (isset($object[$field])) {
+                                $result[$field] = $object[$field];
+                            }
+                        }
+                        $results[] = $result;
+                    } else {
+                        $results[] = $object;
+                    }
+                } else {
+                    $member_ids = array();
+                    if (isset($object['member'])) {
+                        foreach ($object['member'] as $member) {
+                            if (isset($member['uid'])) {
+                                $member_ids[] = $member['uid'];
+                                continue;
+                            }
+                            $display_name = $member['display-name'];
+                            $smtp_address = $member['smtp-address'];
+                            $criteria = array(
+                                'AND' => array(
+                                    array(
+                                        'field' => 'full-name',
+                                        'op' => 'LIKE',
+                                        'test' => $display_name,
+                                        'begin' => false,
+                                    ),
+                                    array(
+                                        'field' => 'emails',
+                                        'op' => 'LIKE',
+                                        'test' => $smtp_address,
+                                        'begin' => false,
+                                    ),
+                                ),
+                            );
+                            $fields = array('uid');
+
+                            // we expect only one result here!!!
+                            $contacts = $this->_search($criteria, $fields);
+
+                            // and drop everything else except the first search result
+                            $member_ids[] = $contacts[0]['uid'];
+                        }
+                        $object['__members'] = serialize($member_ids);
+                        unset($object['member']);
+                    }
+                    $results[] = $object;;
+                }
+            }
+        }
+
+        return $results;
+    }
+
+    /**
+     * Adds the specified object to the Kolab message store.
+     *
+     * TODO
+     *
+     * @throws Turba_Exception
+     */
+    protected function _add($attributes)
+    {
+        $this->connect();
+
+        $attributes['full-name'] = $attributes['last-name'];
+        if (isset($attributes['middle-names'])) {
+            $attributes['full-name'] = $attributes['middle-names'] . ' ' . $attributes['full-name'];
+        }
+        if (isset($attributes['given-name'])) {
+            $attributes['full-name'] = $attributes['given-name'] . ' ' . $attributes['full-name'];
+        }
+
+        $this->_store($attributes);
+    }
+
+    /**
+     * Updates an existing object in the Kolab message store.
+     *
+     * TODO
+     *
+     * @return string  The object id, possibly updated.
+     * @throws Turba_Exception
+     */
+    function _save($object_key, $object_id, $attributes)
+    {
+        $this->connect();
+
+        if ($object_key != 'uid') {
+            throw new Turba_Exception(sprintf('Key for saving must be \'uid\' not %s!', $object_key));
+        }
+
+        return $this->_store($attributes, $object_id);
+    }
+
+    /**
+     * Stores an object in the Kolab message store.
+     *
+     * TODO
+     *
+     * @return string  The object id, possibly updated.
+     * @throws Turba_Exception
+     */
+    protected function _store($attributes, $object_id = null)
+    {
+        $group = false;
+        if (isset($attributes['__type']) && $attributes['__type'] == 'Group') {
+            $group = true;
+            $result = $this->_store->setObjectType('distribution-list');
+            if ($result instanceof PEAR_Error) {
+                throw new Turba_Exception($result);
+            }
+            $this->_convertMembers($attributes);
+        }
+
+        if (isset($attributes['photo']) && isset($attributes['phototype'])) {
+            $attributes['_attachments']['photo.attachment'] = array(
+                'type' => $attributes['phototype'],
+                'content' => $attributes['photo']
+            );
+            $attributes['picture'] = 'photo.attachment';
+            unset($attributes['photo'], $attributes['phototype']);
+        }
+
+        $result = $this->_store->save($attributes, $object_id);
+        if ($result instanceof PEAR_Error) {
+            throw new Turba_Exception($result);
+        }
+
+        if ($group) {
+            $result = $this->_store->setObjectType('contact');
+            if ($result instanceof PEAR_Error) {
+                throw new Turba_Exception($result);
+            }
+        }
+
+        return $object_id;
+    }
+
+    /**
+     * TODO
+     */
+    function _convertMembers(&$attributes)
+    {
+        if (isset($attributes['__members'])) {
+            $member_ids = unserialize($attributes['__members']);
+            $attributes['member'] = array();
+            foreach ($member_ids as $member_id) {
+                if (isset($this->_contacts_cache[$member_id])) {
+                    $member = $this->_contacts_cache[$member_id];
+                    $mail = array('uid' => $member_id);
+                    if (!empty($member['full-name'])) {
+                        $mail['display-name'] = $member['full-name'];
+                    }
+                    if (!empty($member['emails'])) {
+                        $emails = explode(',', $member['emails']);
+                        $mail['smtp-address'] = trim($emails[0]);
+                        if (!isset($mail['display-name'])) {
+                            $mail['display-name'] = $mail['smtp-address'];
+                        }
+                    }
+                    $attributes['member'][] = $mail;
+                }
+            }
+            unset($attributes['__members']);
+        }
+    }
+
+
+    /**
+     * Removes the specified object from the Kolab message store.
+     *
+     * @throws Turba_Exception
+     */
+    function _delete($object_key, $object_id)
+    {
+        $this->connect();
+
+        if ($object_key != 'uid') {
+            throw new Turba_Exception(sprintf('Key for saving must be a UID not %s!', $object_key));
+        }
+
+        if (!in_array($object_id, array_keys($this->_contacts_cache))) {
+            throw new Turba_Exception(sprintf(_("Object with UID %s does not exist!"), $object_id));
+        }
+
+        $group = (isset($this->_contacts_cache[$object_id]['__type']) &&
+                  $this->_contacts_cache[$object_id]['__type'] == 'Group');
+
+        if ($group) {
+            $result = $this->_store->setObjectType('distribution-list');
+            if ($result instanceof PEAR_Error) {
+                throw new Turba_Exception($result);
+            }
+        }
+
+        $result = $this->_store->delete($object_id);
+
+        if ($group) {
+            $result = $this->_store->setObjectType('contact');
+            if ($result instanceof PEAR_Error) {
+                throw new Turba_Exception($result);
+            }
+        }
+
+        return $result;
+    }
+
+    /**
+     * Deletes all contacts from a specific address book.
+     *
+     * @throws Turba_Exception
+     */
+    protected function _deleteAll($sourceName = null)
+    {
+        $this->connect();
+
+        /* Delete contacts */
+        $result = $this->_store->deleteAll();
+        if ($result instanceof PEAR_Error) {
+            throw new Turba_Exception($result);
+        }
+
+        /* Delete groups */
+        $result = $this->_store->setObjectType('distribution-list');
+        if ($result instanceof PEAR_Error) {
+            throw new Turba_Exception($result);
+        }
+
+        $result = $this->_store->deleteAll();
+        if ($result instanceof PEAR_Error) {
+            throw new Turba_Exception($result);
+        }
+
+        /* Revert to the original state */
+        $result = $this->_store->setObjectType('contact');
+        if ($result instanceof PEAR_Error) {
+            throw new Turba_Exception($result);
+        }
+    }
+
+    /**
+     * Create an object key for a new object.
+     *
+     * @return string  A unique ID for the new object.
+     */
+    public function generateUID()
+    {
+        do {
+            $key = strval(new Horde_Support_Uuid());
+        } while (in_array($key, array_keys($this->_contacts_cache)));
+
+        return $key;
+    }
+
+}
diff --git a/turba/lib/Driver/Kolab/Wrapper/Old.php b/turba/lib/Driver/Kolab/Wrapper/Old.php
new file mode 100644 (file)
index 0000000..fad5de6
--- /dev/null
@@ -0,0 +1,441 @@
+<?php
+/**
+ * Horde Turba driver for the Kolab IMAP Server.
+ *
+ * Copyright 2004-2010 The Horde Project (http://www.horde.org/)
+ *
+ * See the enclosed file LICENSE for license information (ASL).  If you
+ * did not receive this file, see http://www.horde.org/licenses/asl.php.
+ *
+ * @author   Gunnar Wrobel <wrobel@pardus.de>
+ * @author   Stuart Binge <omicron@mighty.co.za>
+ * @category Horde
+ * @license  http://www.horde.org/licenses/asl.php ASL
+ * @package  Turba
+ */
+class Turba_Driver_Kolab_Wrapper_Old extends Turba_Driver_Kolab_Wrapper
+{
+    protected function _buildContact()
+    {
+        $k = &$this->_kolab;
+
+        $contact = array(
+            'uid' => $k->getUID(),
+            'owner' => $GLOBALS['registry']->getAuth(),
+            'job-title' => $k->getStr('job-title'),
+            'organization' => $k->getStr('organization'),
+            'body' => $k->getStr('body'),
+            'web-page' => $k->getStr('web-page'),
+            'nick-name' => $k->getStr('nick-name'),
+        );
+
+        $name = &$k->getRootElem('name');
+        $contact['full-name'] = $k->getElemStr($name, 'full-name');
+        $contact['given-name'] = $k->getElemStr($name, 'given-name');
+        $contact['last-name'] = $k->getElemStr($name, 'last-name');
+
+        $email = &$k->getRootElem('email');
+        $contact['smtp-address'] = $k->getElemStr($email, 'smtp-address');
+
+        $phones = &$k->getAllRootElems('phone');
+        for ($i = 0, $j = count($phones); $i < $j; $i++) {
+            $phone = &$phones[$i];
+            $type = $k->getElemStr($phone, 'type');
+
+            switch ($type) {
+            case 'home1':
+                $contact['home1'] = $k->getElemStr($phone, 'number');
+                break;
+
+            case 'business1':
+                $contact['business1'] = $k->getElemStr($phone, 'number');
+                break;
+
+            case 'mobile':
+                $contact['mobile'] = $k->getElemStr($phone, 'number');
+                break;
+
+            case 'businessfax':
+                $contact['businessfax'] = $k->getElemStr($phone, 'number');
+                break;
+            }
+        }
+
+        $addresses = &$k->getAllRootElems('address');
+        for ($i = 0, $j = count($addresses); $i < $j; $i++) {
+            $address = &$addresses[$i];
+            $type = $k->getElemStr($address, 'type');
+
+            switch ($type) {
+            case 'home':
+                $contact['home-street'] = $k->getElemStr($address, 'street');
+                $contact['home-locality'] = $k->getElemStr($address, 'locality');
+                $contact['home-region'] = $k->getElemStr($address, 'region');
+                $contact['home-postal-code'] = $k->getElemStr($address, 'postal-code');
+                $contact['home-country'] = $k->getElemStr($address, 'country');
+                break;
+
+            case 'business':
+                $contact['business-street'] = $k->getElemStr($address, 'street');
+                $contact['business-locality'] = $k->getElemStr($address, 'locality');
+                $contact['business-region'] = $k->getElemStr($address, 'region');
+                $contact['business-postal-code'] = $k->getElemStr($address, 'postal-code');
+                $contact['business-country'] = $k->getElemStr($address, 'country');
+                break;
+            }
+        }
+
+        return $contact;
+    }
+
+    protected function _setPhone($type, &$phone, $attributes)
+    {
+        if (empty($attributes[$type])) {
+            $this->_kolab->delRootElem($phone);
+        } else {
+            if ($phone === false) {
+                $phone = &$this->_kolab->appendRootElem('phone');
+                $this->_kolab->setElemStr($phone, 'type', $type);
+            }
+            $this->_kolab->setElemStr($phone, 'number', $attributes[$type]);
+        }
+    }
+
+    protected function _setAddress($type, &$address, $attributes)
+    {
+        if (empty($attributes["$type-street"]) && empty($attributes["$type-locality"]) &&
+            empty($attributes["$type-region"]) && empty($attributes["$type-postal-code"]) &&
+            empty($attributes["$type-country"])) {
+            $this->_kolab->delRootElem($address);
+        } else {
+            if ($address === false) {
+                $address = &$this->_kolab->appendRootElem('address');
+                $this->_kolab->setElemStr($address, 'type', $type);
+            }
+            $this->_kolab->setElemStr($address, 'street', $attributes["$type-street"]);
+            $this->_kolab->setElemStr($address, 'locality', $attributes["$type-locality"]);
+            $this->_kolab->setElemStr($address, 'region', $attributes["$type-region"]);
+            $this->_kolab->setElemStr($address, 'postal-code', $attributes["$type-postal-code"]);
+            $this->_kolab->setElemStr($address, 'country', $attributes["$type-country"]);
+        }
+    }
+
+    protected function _createContact(&$xml, $attributes)
+    {
+        $k = &$this->_kolab;
+
+        $name = &$k->initRootElem('name');
+        if (!empty($attributes['full-name'])) {
+            $k->setElemStr($name, 'full-name', $attributes['full-name']);
+        }
+        if (!empty($attributes['given-name'])) {
+            $k->setElemStr($name, 'given-name', $attributes['given-name']);
+        }
+        if (!empty($attributes['last-name'])) {
+            $k->setElemStr($name, 'last-name', $attributes['last-name']);
+        }
+
+        $email = &$k->initRootElem('email');
+        $k->setElemStr($email, 'display-name', $attributes['full-name']);
+        $k->setElemStr($email, 'smtp-address', $attributes['smtp-address']);
+
+        if (!empty($attributes['job-title'])) {
+            $k->setStr('job-title', $attributes['job-title']);
+        }
+        if (!empty($attributes['organization'])) {
+            $k->setStr('organization', $attributes['organization']);
+        }
+        if (!empty($attributes['body'])) {
+            $k->setStr('body', $attributes['body']);
+        }
+        if (!empty($attributes['web-page'])) {
+            $k->setStr('web-page', $attributes['web-page']);
+        }
+        if (!empty($attributes['nick-name'])) {
+            $k->setStr('nick-name', $attributes['nick-name']);
+        }
+
+        // Phones
+        $phones = &$k->getAllRootElems('phone');
+        $home = false;
+        $bus = false;
+        $mob = false;
+        $fax = false;
+        for ($i = 0, $j = count($phones); $i < $j; $i++) {
+            $phone = &$phones[$i];
+            $type = $k->getElemStr($phone, 'type');
+
+            switch ($type) {
+            case 'home1':
+                $home = &$phone;
+                break;
+
+            case 'business1':
+                $bus = &$phone;
+                break;
+
+            case 'mobile':
+                $mob = &$phone;
+                break;
+
+            case 'businessfax':
+                $fax = &$phone;
+                break;
+            }
+        }
+
+        $this->_setPhone('home1', $home, $attributes);
+        $this->_setPhone('business1', $bus, $attributes);
+        $this->_setPhone('mobile', $mob, $attributes);
+        $this->_setPhone('businessfax', $fax, $attributes);
+
+        // Addresses
+        $home = false;
+        $bus = false;
+        $addresses = &$k->getAllRootElems('address');
+        for ($i = 0, $j = count($addresses); $i < $j; $i++) {
+            $address = &$addresses[$i];
+            $type = $k->getElemStr($address, 'type');
+
+            switch ($type) {
+            case 'home':
+                $home = &$address;
+                break;
+
+            case 'business':
+                $bus = &$address;
+                break;
+            }
+        }
+
+        $this->_setAddress('home', $home, $attributes);
+        $this->_setAddress('business', $bus, $attributes);
+    }
+
+    /**
+     * Searches the Kolab message store with the given criteria and returns a
+     * filtered list of results. If the criteria parameter is an empty
+     * array, all records will be returned.
+     *
+     * @param array $criteria  Array containing the search criteria.
+     * @param array $fields    List of fields to return.
+     *
+     * @return array  Hash containing the search results.
+     * @throws Turba_Exception
+     */
+    protected function _search($criteria, $fields)
+    {
+        $this->connect();
+
+        $results = array();
+        $folders = $this->_kolab->listFolders();
+        foreach ($folders as $folder) {
+            if ($folder[1] != 'contact') {
+                continue;
+            }
+
+            $msg_list = $this->_kolab->listObjectsInFolder($folder[0]);
+            if ($msg_list instanceof PEAR_Error) {
+                throw new Turba_Exception($msg_list);
+            } elseif (empty($msg_list)) {
+                return $msg_list;
+            }
+
+            foreach ($msg_list as $msg) {
+                $result = $this->_kolab->loadObject($msg, true);
+                if ($result instanceof PEAR_Error) {
+                    throw new Turba_Exception($result);
+                }
+
+                $contact = $this->_buildContact();
+
+                if ($this->_matchCriteria($contact, $criteria) == false) {
+                    continue;
+                }
+
+                $card = array();
+                foreach ($fields as $field) {
+                    $card[$field] = (isset($contact[$field]) ? $contact[$field] : '');
+                }
+
+                $results[] = $card;
+            }
+        }
+
+        return $results;
+    }
+
+    /**
+     * Read the given data from the Kolab message store and returns the
+     * result's fields.
+     *
+     * @param array $criteria  Search criteria.
+     * @param mixed $id_list   Data identifier.
+     * @param array $fields    List of fields to return.
+     *
+     * @return array  Hash containing the search results.
+     * @throws Turba_Exception
+     */
+    protected function _read($criteria, $id_list, $fields)
+    {
+        $this->connect();
+
+        if ($criteria != 'uid') {
+            return array();
+        }
+
+        if (!is_array($id_list)) {
+            $id_list = array($id_list);
+        }
+
+        $results = array();
+        foreach ($id_list as $id) {
+            $result = $this->_kolab->loadObject($id);
+            if ($result instanceof PEAR_Error) {
+                throw new Turba_Exception($result);
+            }
+
+            $contact = $this->_buildContact($result);
+            $card = array();
+            foreach ($fields as $field) {
+                $card[$field] = isset($contact[$field]
+                    ? $contact[$field]
+                    : '';
+            }
+
+            $results[] = $card;
+        }
+
+        return $results;
+    }
+
+    /**
+     * Adds the specified object to the Kolab message store.
+     *
+     * TODO
+     *
+     * @throws Turba_Exception
+     */
+    protected function _add($attributes)
+    {
+        $this->connect();
+
+        $xml = $this->_kolab->newObject($attributes['uid']);
+        if ($xml instanceof PEAR_Error) {
+            throw new Turba_Exception($xml);
+        }
+
+        $this->_createContact($xml, $attributes);
+
+        $res = $this->_kolab->saveObject();
+        if ($res instanceof PEAR_Error) {
+            throw new Turba_Exception($res);
+        }
+    }
+
+    /**
+     * Removes the specified object from the Kolab message store.
+     *
+     * TODO
+     *
+     * @throws Turba_Exception
+     */
+    protected function _delete($object_key, $object_id)
+    {
+        $this->connect();
+
+        if ($object_key == 'uid') {
+            $res = $this->_kolab->removeObjects($object_id);
+            if ($res instanceof PEAR_Error) {
+                throw new Turba_Exception($res);
+            }
+        }
+    }
+
+    /**
+     * Deletes all contacts from a specific address book.
+     *
+     * @throws Turba_Exception
+     */
+    protected function _deleteAll($sourceName = null)
+    {
+        $this->connect();
+
+        if ($sourceName != null) {
+            Horde::logMessage('deleteAll only working for current share. Called for $sourceName', 'ERR');
+            throw new Turba_Exception(sprintf(_("Cannot delete all address book entries for %s"), $sourceName));
+        }
+
+        $res = $this->_kolab->removeAllObjects();
+        if ($res instanceof PEAR_Error) {
+            throw new Turba_Exception($res);
+        }
+    }
+
+    /**
+     * Updates an existing object in the Kolab message store.
+     *
+     * @return string  The object id, possibly updated.
+     * @throws Turba_Exception
+     */
+    protected function _save($object_key, $object_id, $attributes)
+    {
+        $this->connect();
+
+        if ($object_key != 'uid') {
+            throw new Turba_Exception('key must be uid');
+        }
+
+        $xml = $this->_kolab->loadObject($object_id);
+        if ($xml instanceof PEAR_Error) {
+            throw new Turba_Exception($xml);
+        }
+
+        $this->_createContact($xml, $attributes);
+
+        $result = $this->_kolab->saveObject();
+        if ($result instanceof PEAR_Error) {
+            throw new Turba_Exception($result);
+        }
+
+        return $object_id;
+    }
+
+    /**
+     * Checks whether a contact matches a given criteria.
+     *
+     * @param array $contact       The contact.
+     * @param array $criteria      The criteria.
+     *
+     * @return boolean  Wether the passed string corresponding to $criteria.
+     */
+    protected function _matchCriteria($contact, $criteria)
+    {
+        $values = array_values($criteria);
+        $values = $values[0];
+        $ok = true;
+
+        for ($current = 0; $current < count($values); ++$current) {
+            $temp = $values[$current];
+
+            while (!empty($temp) && !array_key_exists('field', $temp)) {
+                $temp = array_values($temp);
+                $temp = $temp[0];
+            }
+
+            if (empty($temp)) {
+                continue;
+            }
+
+            $searchkey = $temp['field'];
+            $searchval = $temp['test'];
+
+            $ok = (stristr($contact[$searchkey], $searchval) == false)
+                ? $ok && false
+                : $ok && true;
+        }
+
+        return $ok;
+    }
+
+}
index 0e20249..bd9918b 100644 (file)
@@ -2,9 +2,16 @@
 /**
  * Turba directory driver implementation for PHP's LDAP extension.
  *
- * @author  Chuck Hagenbuch <chuck@horde.org>
- * @author  Jon Parise <jon@csh.rit.edu>
- * @package Turba
+ * Copyright 2010 The Horde Project (http://www.horde.org)
+ *
+ * See the enclosed file LICENSE for license information (ASL).  If you did
+ * did not receive this file, see http://www.horde.org/licenses/asl.php.
+ *
+ * @author   Chuck Hagenbuch <chuck@horde.org>
+ * @author   Jon Parise <jon@csh.rit.edu>
+ * @category Horde
+ * @license  http://www.horde.org/licenses/asl.php ASL
+ * @package  Turba
  */
 class Turba_Driver_Ldap extends Turba_Driver
 {
@@ -13,45 +20,38 @@ class Turba_Driver_Ldap extends Turba_Driver
      *
      * @var resource
      */
-    var $_ds = 0;
+    protected $_ds = 0;
+
+    /**
+     * Schema object.
+     *
+     * @var Net_LDAP_Schema
+     */
+    protected $_schema;
 
     /**
-     * Cache _getSyntax calls to avoid lots of repeated server calls.
+     * Cache _getSyntax() calls.
      *
      * @var array
      */
-    var $_syntaxCache = array();
+    protected $_syntaxCache = array();
 
     /**
      * Constructs a new Turba LDAP driver object.
      *
-     * @access private
-     *
      * @param $params  Hash containing additional configuration parameters.
      */
     public function __construct($params)
     {
-        if (empty($params['server'])) {
-            $params['server'] = 'localhost';
-        }
-        if (empty($params['port'])) {
-            $params['port'] = 389;
-        }
-        if (empty($params['root'])) {
-            $params['root'] = '';
-        }
-        if (empty($params['multiple_entry_separator'])) {
-            $params['multiple_entry_separator'] = ', ';
-        }
-        if (empty($params['charset'])) {
-            $params['charset'] = '';
-        }
-        if (empty($params['scope'])) {
-            $params['scope'] = 'sub';
-        }
-        if (empty($params['deref'])) {
-            $params['deref'] = LDAP_DEREF_NEVER;
-        }
+        $params = array_merge(array(
+            'charset' => '',
+            'deref' => LDAP_DEREF_NEVER,
+            'multiple_entry_separator' => ', ',
+            'port' => 389,
+            'root' => '',
+            'scope' => 'sub',
+            'server' => 'localhost'
+        ), $params);
 
         parent::__construct($params);
     }
@@ -59,7 +59,7 @@ class Turba_Driver_Ldap extends Turba_Driver
     /**
      * @throws Turba_Exception
      */
-    function _init()
+    protected function _init()
     {
         if (!Horde_Util::extensionExists('ldap')) {
             throw new Turba_Exception(_("LDAP support is required but the LDAP module is not available or not loaded."));
@@ -104,14 +104,14 @@ class Turba_Driver_Ldap extends Turba_Driver
     }
 
     /**
-     * Expands the parent->toDriverKeys Function to build composed fields needed for the dn
+     * Extends parent function to build composed fields needed for the dn
      * based on the contents of $this->map.
      *
      * @param array $hash  Hash using Turba keys.
      *
      * @return array  Translated version of $hash.
      */
-    function toDriverKeys($hash)
+    public function toDriverKeys($hash)
     {
         // First check for combined fields in the dn-fields and add them.
         if (is_array($this->_params['dn'])) {
@@ -122,11 +122,9 @@ class Turba_Driver_Ldap extends Turba_Driver
                         ($this->map[$turbaname]['attribute'] == $param)) {
                         $fieldarray = array();
                         foreach ($this->map[$turbaname]['fields'] as $mapfield) {
-                            if (isset($hash[$mapfield])) {
-                                $fieldarray[] = $hash[$mapfield];
-                            } else {
-                                $fieldarray[] = '';
-                            }
+                            $fieldarray[] = isset($hash[$mapfield])
+                                ? $hash[$mapfield]
+                                : '';
                         }
                         $hash[$turbaname] = trim(vsprintf($this->map[$turbaname]['format'], $fieldarray), " \t\n\r\0\x0B,");
                     }
@@ -143,12 +141,13 @@ class Turba_Driver_Ldap extends Turba_Driver
      * a filtered list of results. If no criteria are specified, all
      * records are returned.
      *
-     * @param $criteria      Array containing the search criteria.
-     * @param $fields        List of fields to return.
+     * @param array $criteria  Array containing the search criteria.
+     * @param array $fields    List of fields to return.
      *
      * @return array  Hash containing the search results.
+     * @throws Turba_Exception
      */
-    function _search($criteria, $fields)
+    protected function _search($criteria, $fields)
     {
         /* Build the LDAP filter. */
         $filter = '';
@@ -191,14 +190,12 @@ class Turba_Driver_Ldap extends Turba_Driver
 
         /* Send the query to the LDAP server and fetch the matching
          * entries. */
-        if ($this->_params['scope'] == 'one') {
-            $func = 'ldap_list';
-        } else {
-            $func = 'ldap_search';
-        }
+        $func = ($this->_params['scope'] == 'one')
+            ? 'ldap_list'
+            : 'ldap_search';
 
         if (!($res = @$func($this->_ds, $this->_params['root'], $filter, $attr, 0, $sizelimit))) {
-            return PEAR::raiseError(sprintf(_("Query failed: (%s) %s"), ldap_errno($this->_ds), ldap_error($this->_ds)));
+            throw Turba_Exception(sprintf(_("Query failed: (%s) %s"), ldap_errno($this->_ds), ldap_error($this->_ds)));
         }
 
         return $this->_getResults($fields, $res);
@@ -214,8 +211,9 @@ class Turba_Driver_Ldap extends Turba_Driver
      * @param array $fields  List of fields to return.
      *
      * @return array  Hash containing the search results.
+     * @throws Turba_Exception
      */
-    function _read($key, $ids, $owner, $fields)
+    protected function _read($key, $ids, $owner, $fields)
     {
         /* Only DN. */
         if ($key != 'dn') {
@@ -237,21 +235,18 @@ class Turba_Driver_Ldap extends Turba_Driver
             foreach ($ids as $d) {
                 $res = @ldap_read($this->_ds, Horde_String::convertCharset($d, $GLOBALS['registry']->getCharset(), $this->_params['charset']), $filter, $attr);
                 if ($res) {
-                    if (!is_a($result = $this->_getResults($fields, $res), 'PEAR_Error')) {
-                        $results = array_merge($results, $result);
-                    } else {
-                        return $result;
-                    }
+                    $results = array_merge($results, $this->_getResults($fields, $res));
                 } else {
-                    return PEAR::raiseError(sprintf(_("Read failed: (%s) %s"), ldap_errno($this->_ds), ldap_error($this->_ds)));
+                    throw new Turba_Exception(sprintf(_("Read failed: (%s) %s"), ldap_errno($this->_ds), ldap_error($this->_ds)));
                 }
             }
+
             return $results;
         }
 
         $res = @ldap_read($this->_ds, Horde_String::convertCharset($ids, $GLOBALS['registry']->getCharset(), $this->_params['charset']), $filter, $attr);
         if (!$res) {
-            return PEAR::raiseError(sprintf(_("Read failed: (%s) %s"), ldap_errno($this->_ds), ldap_error($this->_ds)));
+            throw new Turba_Exception(sprintf(_("Read failed: (%s) %s"), ldap_errno($this->_ds), ldap_error($this->_ds)));
         }
 
         return $this->_getResults($fields, $res);
@@ -261,13 +256,15 @@ class Turba_Driver_Ldap extends Turba_Driver
      * Adds the specified entry to the LDAP directory.
      *
      * @param array $attributes  The initial attributes for the new object.
+     *
+     * @throws Turba_Exception
      */
-    function _add($attributes)
+    protected function _add($attributes)
     {
         if (empty($attributes['dn'])) {
-            return PEAR::raiseError('Tried to add an object with no dn: [' . serialize($attributes) . '].');
+            throw new Turba_Exception('Tried to add an object with no dn: [' . serialize($attributes) . '].');
         } elseif (empty($this->_params['objectclass'])) {
-            return PEAR::raiseError('Tried to add an object with no objectclass: [' . serialize($attributes) . '].');
+            throw new Turba_Exception('Tried to add an object with no objectclass: [' . serialize($attributes) . '].');
         }
 
         /* Take the DN out of the attributes array. */
@@ -280,8 +277,7 @@ class Turba_Driver_Ldap extends Turba_Driver
         } else {
             $i = 0;
             foreach ($this->_params['objectclass'] as $objectclass) {
-                $attributes['objectclass'][$i] = $objectclass;
-                $i++;
+                $attributes['objectclass'][$i++] = $objectclass;
             }
         }
 
@@ -292,9 +288,6 @@ class Turba_Driver_Ldap extends Turba_Driver
          * value. */
         if (!empty($this->_params['checkrequired'])) {
             $required = $this->_checkRequiredAttributes($this->_params['objectclass']);
-            if (is_a($required, 'PEAR_Error')) {
-                return $required;
-            }
 
             foreach ($required as $k => $v) {
                 if (!isset($attributes[$v])) {
@@ -306,30 +299,35 @@ class Turba_Driver_Ldap extends Turba_Driver
         $this->_encodeAttributes($attributes);
 
         if (!@ldap_add($this->_ds, Horde_String::convertCharset($dn, $GLOBALS['registry']->getCharset(), $this->_params['charset']), $attributes)) {
-            return PEAR::raiseError('Failed to add an object: [' . ldap_errno($this->_ds) . '] "' . ldap_error($this->_ds) . '" DN: ' . $dn . ' (attributes: [' . serialize($attributes) . ']).' . "Charset:" . $GLOBALS['registry']->getCharset());
-        } else {
-            return true;
+            throw new Turba_Exception('Failed to add an object: [' . ldap_errno($this->_ds) . '] "' . ldap_error($this->_ds) . '" DN: ' . $dn . ' (attributes: [' . serialize($attributes) . ']).' . "Charset:" . $GLOBALS['registry']->getCharset());
         }
     }
 
-    function _canAdd()
+    /**
+     * TODO
+     *
+     * @return boolean  TODO
+     */
+    protected function _canAdd()
     {
         return true;
     }
 
     /**
      * Deletes the specified entry from the LDAP directory.
+     *
+     * TODO
+     *
+     * @throws Turba_Exception
      */
-    function _delete($object_key, $object_id)
+    protected function _delete($object_key, $object_id)
     {
         if ($object_key != 'dn') {
-            return PEAR::raiseError(_("Invalid key specified."));
+            throw new Turba_Exception(_("Invalid key specified."));
         }
 
         if (!@ldap_delete($this->_ds, Horde_String::convertCharset($object_id, $GLOBALS['registry']->getCharset(), $this->_params['charset']))) {
-            return PEAR::raiseError(sprintf(_("Delete failed: (%s) %s"), ldap_errno($this->_ds), ldap_error($this->_ds)));
-        } else {
-            return true;
+            throw new Turba_Exception(sprintf(_("Delete failed: (%s) %s"), ldap_errno($this->_ds), ldap_error($this->_ds)));
         }
     }
 
@@ -337,8 +335,9 @@ class Turba_Driver_Ldap extends Turba_Driver
      * Modifies the specified entry in the LDAP directory.
      *
      * @return string  The object id, possibly updated.
+     * @throw Turba_Exception
      */
-    function _save($object)
+    protected function _save($object)
     {
         list($object_key, $object_id) = each($this->toDriverKeys(array('__key' => $object->getValue('__key'))));
         $attributes = $this->toDriverKeys($object->getAttributes());
@@ -356,15 +355,14 @@ class Turba_Driver_Ldap extends Turba_Driver
             /* Need to rename the object. */
             $newrdn = $this->_makeRDN($attributes);
             if ($newrdn == '') {
-                return PEAR::raiseError(_("Missing DN in LDAP source configuration."));
+                throw new Turba_Exception(_("Missing DN in LDAP source configuration."));
             }
 
             if (ldap_rename($this->_ds, Horde_String::convertCharset($object_id, $GLOBALS['registry']->getCharset(), $this->_params['charset']),
                             Horde_String::convertCharset($newrdn, $GLOBALS['registry']->getCharset(), $this->_params['charset']), $this->_params['root'], true)) {
                 $object_id = $newrdn . ',' . $this->_params['root'];
             } else {
-                return PEAR::raiseError(sprintf(_("Failed to change name: (%s) %s; Old DN = %s, New DN = %s, Root = %s"),
-                                                ldap_errno($this->_ds), ldap_error($this->_ds), $object_id, $newrdn, $this->_params['root']));
+                throw new Turba_Exception(sprintf(_("Failed to change name: (%s) %s; Old DN = %s, New DN = %s, Root = %s"), ldap_errno($this->_ds), ldap_error($this->_ds), $object_id, $newrdn, $this->_params['root']));
             }
         }
 
@@ -385,7 +383,7 @@ class Turba_Driver_Ldap extends Turba_Driver
 
                 $oldval[$key] = $var[0];
                 if (!@ldap_mod_del($this->_ds, Horde_String::convertCharset($object_id, $GLOBALS['registry']->getCharset(), $this->_params['charset']), $oldval)) {
-                    return PEAR::raiseError(sprintf(_("Modify failed: (%s) %s"), ldap_errno($this->_ds), ldap_error($this->_ds)));
+                    throw new Turba_Exception(sprintf(_("Modify failed: (%s) %s"), ldap_errno($this->_ds), ldap_error($this->_ds)));
                 }
                 unset($attributes[$key]);
             }
@@ -401,10 +399,10 @@ class Turba_Driver_Ldap extends Turba_Driver
         $attributes['objectclass'] = array_values($attributes['objectclass']);
 
         if (!@ldap_modify($this->_ds, Horde_String::convertCharset($object_id, $GLOBALS['registry']->getCharset(), $this->_params['charset']), $attributes)) {
-            return PEAR::raiseError(sprintf(_("Modify failed: (%s) %s"), ldap_errno($this->_ds), ldap_error($this->_ds)));
-        } else {
-            return $object_id;
+            throw new Turba_Exception(sprintf(_("Modify failed: (%s) %s"), ldap_errno($this->_ds), ldap_error($this->_ds)));
         }
+
+        return $object_id;
     }
 
     /**
@@ -416,7 +414,7 @@ class Turba_Driver_Ldap extends Turba_Driver
      *
      * @return string  The RDN for the new object.
      */
-    function _makeRDN($attributes)
+    protected function _makeRDN($attributes)
     {
         if (!is_array($this->_params['dn'])) {
             return '';
@@ -428,6 +426,7 @@ class Turba_Driver_Ldap extends Turba_Driver
                 $pairs[] = array($param, $attributes[$param]);
             }
         }
+
         return Horde_Ldap::quoteDN($pairs);
     }
 
@@ -440,7 +439,7 @@ class Turba_Driver_Ldap extends Turba_Driver
      *
      * @return string  The DN for the new object.
      */
-    function _makeKey($attributes)
+    protected function _makeKey($attributes)
     {
         return $this->_makeRDN($attributes) . ',' . $this->_params['root'];
     }
@@ -452,9 +451,10 @@ class Turba_Driver_Ldap extends Turba_Driver
      *
      * @return string  An LDAP query fragment.
      */
-    function _buildSearchQuery($criteria)
+    protected function _buildSearchQuery($criteria)
     {
         $clause = '';
+
         foreach ($criteria as $key => $vals) {
             if (!empty($vals['OR'])) {
                 $clause .= '(|' . $this->_buildSearchQuery($vals) . ')';
@@ -489,17 +489,18 @@ class Turba_Driver_Ldap extends Turba_Driver
      * @param resource $res     Result identifier.
      *
      * @return array  Hash containing the results.
+     * @throws Turba_Exception
      */
-    function _getResults($fields, $res)
+    protected function _getResults($fields, $res)
     {
         $entries = @ldap_get_entries($this->_ds, $res);
         if ($entries === false) {
-            return PEAR::raiseError(sprintf(_("Read failed: (%s) %s"), ldap_errno($this->_ds), ldap_error($this->_ds)));
+            throw new Turba_Exception(sprintf(_("Read failed: (%s) %s"), ldap_errno($this->_ds), ldap_error($this->_ds)));
         }
 
         /* Return only the requested fields (from $fields, above). */
         $results = array();
-        for ($i = 0; $i < $entries['count']; $i++) {
+        for ($i = 0; $i < $entries['count']; ++$i) {
             $entry = $entries[$i];
             $result = array();
 
@@ -544,32 +545,34 @@ class Turba_Driver_Ldap extends Turba_Driver
     /**
      * Remove empty attributes from attributes array.
      *
-     * @param mixed $val    Value from attributes array.
+     * @param mixed $val  Value from attributes array.
      *
-     * @return boolean         Boolean used by array_filter.
+     * @return boolean  Boolean used by array_filter.
      */
-    function _emptyAttributeFilter($var)
+    protected function _emptyAttributeFilter($var)
     {
         if (!is_array($var)) {
-            return $var != '';
-        } else {
-            if (!count($var)) {
+            return ($var != '');
+        }
+
+        if (!count($var)) {
+            return false;
+        }
+
+        foreach ($var as $v) {
+            if ($v == '') {
                 return false;
             }
-            foreach ($var as $v) {
-                if ($v == '') {
-                    return false;
-                }
-            }
-            return true;
         }
+
+        return true;
     }
 
     /**
      * Format and encode attributes including postal addresses,
      * character set encoding, etc.
      */
-    function _encodeAttributes(&$attributes)
+    protected function _encodeAttributes(&$attributes)
     {
         foreach ($attributes as $key => $val) {
             /* If schema checking is enabled check the backend syntax. */
@@ -598,9 +601,10 @@ class Turba_Driver_Ldap extends Turba_Driver
      *
      * @return string  An LDAP filter.
      */
-    function _buildObjectclassFilter()
+    protected function _buildObjectclassFilter()
     {
         $filter = '';
+
         if (!empty($this->_params['objectclass'])) {
             if (!is_array($this->_params['objectclass'])) {
                 $filter = '(objectclass=' . $this->_params['objectclass'] . ')';
@@ -612,28 +616,24 @@ class Turba_Driver_Ldap extends Turba_Driver
                 $filter .= ')';
             }
         }
+
         return $filter;
     }
 
     /**
      * Returns a list of required attributes.
      *
-     * @access private
-     *
      * @param array $objectclasses  List of objectclasses that should be
      *                              checked for required attributes.
      *
      * @return array  List of attribute names of the specified objectclasses
      *                that have been configured as being required.
+     * @throws Turba_Exception
      */
-    function _checkRequiredAttributes($objectclasses)
+    protected function _checkRequiredAttributes($objectclasses)
     {
-       $schema = &$this->_getSchema();
-       if (is_a($schema, 'PEAR_Error')) {
-           return $schema;
-       }
-
        $retval = array();
+       $schema = $this->_getSchema();
 
        foreach ($objectclasses as $oc) {
            if (Horde_String::lower($oc) == 'top') {
@@ -657,13 +657,11 @@ class Turba_Driver_Ldap extends Turba_Driver
     /**
      * Checks if an attribute refers to a string.
      *
-     * @access private
-     *
      * @param string $attribute  An attribute name.
      *
      * @return boolean  True if the specified attribute refers to a string.
      */
-    function _isString($attribute)
+    protected function _isString($attribute)
     {
         $syntax = $this->_getSyntax($attribute);
 
@@ -671,61 +669,52 @@ class Turba_Driver_Ldap extends Turba_Driver
          * Syntaxes have the form:
          * 1.3.6.1.4.1.1466.115.121.1.$n{$y}
          * ... where $n is the integer used below and $y is a sizelimit. */
-        $okSyntax = array(44 => 1, /* Printable string. */
-                          41 => 1, /* Postal address. */
-                          39 => 1, /* Other mailbox. */
-                          34 => 1, /* Name and optional UID. */
-                          26 => 1, /* IA5 string. */
-                          15 => 1, /* Directory string. */
-                          );
-
-        if (preg_match('/^(.*)\.(\d+)\{\d+\}$/', $syntax, $matches) &&
-            $matches[1] == "1.3.6.1.4.1.1466.115.121.1" &&
-            isset($okSyntax[$matches[2]])) {
-            return true;
-        }
-        return false;
+        $okSyntax = array(
+            44 => 1, /* Printable string. */
+            41 => 1, /* Postal address. */
+            39 => 1, /* Other mailbox. */
+            34 => 1, /* Name and optional UID. */
+            26 => 1, /* IA5 string. */
+            15 => 1, /* Directory string. */
+        );
+
+        return (preg_match('/^(.*)\.(\d+)\{\d+\}$/', $syntax, $matches) &&
+                ($matches[1] == "1.3.6.1.4.1.1466.115.121.1") &&
+                isset($okSyntax[$matches[2]]));
     }
 
     /**
      * Checks if an attribute refers to a Postal Address.
      *
-     * @access private
-     *
      * @param string $attribute  An attribute name.
      *
-     * @return boolean  True if the specified attribute refers to a Postal Address.
+     * @return boolean  True if the specified attribute refers to a Postal
+     *                  Address.
      */
-    function _isPostalAddress($attribute)
+    protected function _isPostalAddress($attribute)
     {
         /* LDAP postal address syntax is
          * 1.3.6.1.4.1.1466.115.121.1.41 */
-        return $this->_getSyntax($attribute) == '1.3.6.1.4.1.1466.115.121.1.41';
+        return ($this->_getSyntax($attribute) == '1.3.6.1.4.1.1466.115.121.1.41');
     }
 
     /**
      * Returns the syntax of an attribute, if necessary recursively.
      *
-     * @access private
-     *
      * @param string $att  Attribute name.
      *
      * @return string  Attribute syntax.
+     * @throws Turba_Exception
      */
-    function _getSyntax($att)
+    protected function _getSyntax($att)
     {
-        $schema = &$this->_getSchema();
-        if (is_a($schema, 'PEAR_Error')) {
-            return $schema;
-        }
+        $schema = $this->_getSchema();
 
         if (!isset($this->_syntaxCache[$att])) {
             $attv = $schema->get('attribute', $att);
-            if (isset($attv['syntax'])) {
-                $this->_syntaxCache[$att] = $attv['syntax'];
-            } else {
-                $this->_syntaxCache[$att] = $this->_getSyntax($attv['sup'][0]);
-            }
+            $this->_syntaxCache[$att] = isset($attv['syntax'])
+                ? $attv['syntax']
+                : $this->_getSyntax($attv['sup'][0]);
         }
 
         return $this->_syntaxCache[$att];
@@ -734,30 +723,31 @@ class Turba_Driver_Ldap extends Turba_Driver
     /**
      * Returns an LDAP_Schema object that containts the LDAP schema.
      *
-     * @access private
-     *
      * @return Net_LDAP_Schema  Returns a reference to the ldap schema object.
+     * @throws Turba_Exception
      */
-    function &_getSchema()
+    protected function _getSchema()
     {
-        static $_schema;
-
         /* Check if the cached schema is valid, */
-        if (is_object($_schema) && is_a($_schema, 'Net_LDAP_Schema')) {
-            return $_schema;
+        if (isset($this->_schema)) {
+            return $this->_schema;
         }
 
-        $config = array('host' => $this->_params['server'],
-                        'port' => $this->_params['port']);
         if (!class_exists('Net_LDAP')) {
-            return PEAR::raiseError(_('You must have the Net_LDAP PEAR library installed to use the schema check function.'));
+            throw new Turba_Exception(_('You must have the Net_LDAP PEAR library installed to use the schema check function.'));
         }
+
+        $config = array(
+            'host' => $this->_params['server'],
+            'port' => $this->_params['port']
+        );
+
         $ldap = new Net_LDAP($config);
         $ldap->_link = $this->_ds;
 
-        $_schema = $ldap->schema();
+        $this->_schema = $ldap->schema();
 
-        return $_schema;
+        return $this->_schema;
     }
 
 }
index 1416134..2879c8f 100644 (file)
@@ -3,8 +3,15 @@
  * Turba directory driver implementation for Horde Preferences - very simple,
  * lightweight container.
  *
- * @author  Chuck Hagenbuch <chuck@horde.org>
- * @package Turba
+ * Copyright 2010 The Horde Project (http://www.horde.org)
+ *
+ * See the enclosed file LICENSE for license information (ASL).  If you did
+ * did not receive this file, see http://www.horde.org/licenses/asl.php.
+ *
+ * @author   Chuck Hagenbuch <chuck@horde.org>
+ * @category Horde
+ * @license  http://www.horde.org/licenses/asl.php ASL
+ * @package  Turba
  */
 class Turba_Driver_Prefs extends Turba_Driver
 {
@@ -17,7 +24,7 @@ class Turba_Driver_Prefs extends Turba_Driver
      *
      * @return array  Hash containing the search results.
      */
-    function _search($criteria, $fields)
+    protected function _search($criteria, $fields)
     {
         return array_values($this->_getAddressBook());
     }
@@ -32,7 +39,7 @@ class Turba_Driver_Prefs extends Turba_Driver
      *
      * @return  Hash containing the search results.
      */
-    function _read($criteria, $ids, $fields)
+    protected function _read($criteria, $ids, $fields)
     {
         $book = $this->_getAddressBook();
         $results = array();
@@ -50,35 +57,41 @@ class Turba_Driver_Prefs extends Turba_Driver
 
     /**
      * Adds the specified object to the preferences.
+     *
+     * @param array $attributes  TODO
      */
-    function _add($attributes)
+    protected function _add($attributes)
     {
         $book = $this->_getAddressBook();
         $book[$attributes['id']] = $attributes;
         $this->_setAddressbook($book);
-
-        return true;
     }
 
-    public function _canAdd()
+    /**
+     * TODO
+     */
+    protected function _canAdd()
     {
         return true;
     }
 
     /**
      * Deletes the specified object from the preferences.
+     *
+     * @param $object_key TODO
+     * @param $object_id  TODO
      */
-    function _delete($object_key, $object_id)
+    protected function _delete($object_key, $object_id)
     {
         $book = $this->_getAddressBook();
         unset($book[$object_id]);
         $this->_setAddressbook($book);
-
-        return true;
     }
 
     /**
      * Saves the specified object in the preferences.
+     *
+     * @param $object TODO
      */
     function _save($object)
     {
@@ -90,7 +103,12 @@ class Turba_Driver_Prefs extends Turba_Driver
         $this->_setAddressBook($book);
     }
 
-    function _getAddressBook()
+    /**
+     * TODO
+     *
+     * @return TODO
+     */
+    protected function _getAddressBook()
     {
         global $prefs;
 
@@ -98,21 +116,26 @@ class Turba_Driver_Prefs extends Turba_Driver
         if (!empty($val)) {
             $prefbooks = unserialize($val);
             return $prefbooks[$this->_params['name']];
-        } else {
-            return array();
         }
+
+        return array();
     }
 
-    function _setAddressBook($addressbook)
+    /**
+     * TODO
+     *
+     * @param $addressbook TODO
+     *
+     * @return TODO
+     */
+    protected function _setAddressBook($addressbook)
     {
         global $prefs;
 
         $val = $prefs->getValue('prefbooks');
-        if (!empty($val)) {
-            $prefbooks = unserialize($val);
-        } else {
-            $prefbooks = array();
-        }
+        $prefbooks = empty($val)
+            ? array()
+            : unserialize($val);
 
         $prefbooks[$this->_params['name']] = $addressbook;
         $prefs->setValue('prefbooks', serialize($prefbooks));
index 0278e69..bf3f8d3 100644 (file)
@@ -4,9 +4,16 @@
  * various directory search drivers.  It includes functions for searching,
  * adding, removing, and modifying directory entries.
  *
- * @author  Chuck Hagenbuch <chuck@horde.org>
- * @author  Jon Parise <jon@csh.rit.edu>
- * @package Turba
+ * Copyright 2009-2010 The Horde Project (http://www.horde.org)
+ *
+ * See the enclosed file LICENSE for license information (ASL).  If you did
+ * did not receive this file, see http://www.horde.org/licenses/asl.php.
+ *
+ * @author   Chuck Hagenbuch <chuck@horde.org>
+ * @author   Jon Parise <jon@csh.rit.edu>
+ * @category Horde
+ * @license  http://www.horde.org/licenses/asl.php ASL
+ * @package  Turba
  */
 class Turba_Driver_Share extends Turba_Driver
 {
@@ -15,14 +22,14 @@ class Turba_Driver_Share extends Turba_Driver
      *
      * @var Horde_Share
      */
-    var $_share;
+    protected $_share;
 
     /**
      * Underlying driver object for this source.
      *
      * @var Turba_Driver
      */
-    var $_driver;
+    protected $_driver;
 
     /**
      * Checks if this backend has a certain capability.
@@ -31,7 +38,7 @@ class Turba_Driver_Share extends Turba_Driver
      *
      * @return boolean  Supported or not.
      */
-    function hasCapability($capability)
+    public function hasCapability($capability)
     {
         return $this->_driver->hasCapability($capability);
     }
@@ -44,7 +51,7 @@ class Turba_Driver_Share extends Turba_Driver
      *
      * @return boolean  True if the user has permission, otherwise false.
      */
-    function hasPermission($perm)
+    public function hasPermission($perm)
     {
         return $this->_share->hasPermission($GLOBALS['registry']->getAuth(), $perm);
     }
@@ -54,7 +61,7 @@ class Turba_Driver_Share extends Turba_Driver
      *
      * @string Address book name
      */
-    function getName()
+    public function getName()
     {
         $share_parts = explode(':', $this->_share->getName());
         return array_pop($share_parts);
@@ -64,15 +71,17 @@ class Turba_Driver_Share extends Turba_Driver
      * Return the owner to use when searching or creating contacts in
      * this address book.
      *
-     * @return string
+     * @return string  TODO
+     * @throws Turba_Exception
      */
-    function _getContactOwner()
+    protected  function _getContactOwner()
     {
         $params = @unserialize($this->_share->get('params'));
         if (!empty($params['name'])) {
             return $params['name'];
         }
-        return PEAR::raiseError(_("Unable to find contact owner."));
+
+        throw new Turba_Exception(_("Unable to find contact owner."));
     }
 
     /**
@@ -81,8 +90,7 @@ class Turba_Driver_Share extends Turba_Driver
     protected function _init()
     {
         $this->_share = &$this->_params['config']['params']['share'];
-        $this->_driver = Turba_Driver::factory($this->name, $this->_params['config']);
-        $this->_driver->_contact_owner = $this->_getContactOwner();
+        $this->_driver = Turba_Driver::factory($this->_name, $this->_params['config']);
     }
 
     /**
@@ -94,8 +102,9 @@ class Turba_Driver_Share extends Turba_Driver
      * @param array $fields    List of fields to return.
      *
      * @return array  Hash containing the search results.
+     * @throws Turba_Exception
      */
-    function _search($criteria, $fields)
+    protected function _search($criteria, $fields)
     {
         return $this->_driver->_search($criteria, $fields);
     }
@@ -127,76 +136,90 @@ class Turba_Driver_Share extends Turba_Driver
      * @param array $fields  List of fields to return.
      *
      * @return array  Hash containing the search results.
+     * @throws Turba_Exception
      */
-    function _read($key, $ids, $owner, $fields, $blob_fields = array())
+    protected function _read($key, $ids, $owner, $fields,
+                             $blob_fields = array())
     {
         return $this->_driver->_read($key, $ids, $owner, $fields, $blob_fields);
     }
 
     /**
      * Adds the specified object to the SQL database.
+     *
+     * TODO
      */
-    function _add($attributes, $blob_fields = array())
+    protected function _add($attributes, $blob_fields = array())
     {
-        return $this->_driver->_add($attributes, $blob_fields);
+        $this->_driver->_add($attributes, $blob_fields);
     }
 
-    function _canAdd()
+    /**
+     * TODO
+     */
+    protected function _canAdd()
     {
         return $this->_driver->canAdd();
     }
 
     /**
      * Deletes the specified object from the SQL database.
+     *
+     * TODO
      */
-    function _delete($object_key, $object_id)
+    protected function _delete($object_key, $object_id)
     {
-        return $this->_driver->_delete($object_key, $object_id);
+        $this->_driver->_delete($object_key, $object_id);
     }
 
     /**
      * Deletes all contacts from a specific address book.
      *
-     * @return boolean  True if the operation worked.
+     * @throws Turba_Exception
      */
-    function _deleteAll($sourceName = null)
+    protected function _deleteAll($sourceName = null)
     {
         if (is_null($sourceName)) {
             $sourceName = $this->getContactOwner();
         }
-        return $this->_driver->_deleteAll($sourceName);
+        $this->_driver->_deleteAll($sourceName);
     }
 
     /**
      * Saves the specified object in the SQL database.
      *
      * @return string  The object id, possibly updated.
+     * @throws Turba_Exception
      */
-    function _save($object)
+    protected function _save($object)
     {
         return $this->_driver->_save($object);
     }
 
     /**
-     * Stub for removing all data for a specific user - to be overridden
-     * by child class.
+     * Stub for removing all data for a specific user.
      */
-    function removeUserData($user)
+    public function removeUserData($user)
     {
         $this->_deleteAll();
         $GLOBALS['turba_shares']->removeShare($this->_share);
         unset($this->_share);
-        return true;
     }
 
-    function _makeKey($attributes)
+    /**
+     * TODO
+     */
+    protected function _makeKey($attributes)
     {
         return $this->_driver->_makeKey($attributes);
     }
 
-    function _getTimeObjectTurbaList($start, $end, $field)
+    /**
+     * TODO
+     */
+    public function getTimeObjectTurbaList($start, $end, $field)
     {
-        return $this->_driver->_getTimeObjectTurbaList($start, $end, $field);
+        return $this->_driver->getTimeObjectTurbaList($start, $end, $field);
     }
 
 }
index 6d26691..6784f1b 100644 (file)
@@ -3,8 +3,15 @@
  * Turba directory driver implementation for PHP's PEAR database abstraction
  * layer.
  *
- * @author  Jon Parise <jon@csh.rit.edu>
- * @package Turba
+ * Copyright 2010 The Horde Project (http://www.horde.org)
+ *
+ * See the enclosed file LICENSE for license information (ASL).  If you did
+ * did not receive this file, see http://www.horde.org/licenses/asl.php.
+ *
+ * @author   Jon Parise <jon@csh.rit.edu>
+ * @category Horde
+ * @license  http://www.horde.org/licenses/asl.php ASL
+ * @package  Turba
  */
 class Turba_Driver_Sql extends Turba_Driver
 {
@@ -13,9 +20,9 @@ class Turba_Driver_Sql extends Turba_Driver
      *
      * @var array
      */
-    var $_capabilities = array(
-        'delete_all' => true,
-        'delete_addressbook' => true
+    protected $_capabilities = array(
+        'delete_addressbook' => true,
+        'delete_all' => true
     );
 
     /**
@@ -23,7 +30,7 @@ class Turba_Driver_Sql extends Turba_Driver
      *
      * @var DB
      */
-    var $_db;
+    protected $_db;
 
     /**
      * Handle for the current database connection, used for writing. Defaults
@@ -31,7 +38,14 @@ class Turba_Driver_Sql extends Turba_Driver
      *
      * @var DB
      */
-    var $_write_db;
+    protected $_write_db;
+
+    /**
+     * count() cache.
+     *
+     * @var array
+     */
+    protected $_countCache = array();
 
     /**
      * @throws Turba_Exception
@@ -51,12 +65,10 @@ class Turba_Driver_Sql extends Turba_Driver
      *
      * @return integer  The number of contacts that the user owns.
      */
-    function count()
+    public function count()
     {
-        static $count = array();
-
         $test = $this->getContactOwner();
-        if (!isset($count[$test])) {
+        if (!isset($this->_countCache[$test])) {
             /* Build up the full query. */
             $query = 'SELECT COUNT(*) FROM ' . $this->_params['table'] .
                      ' WHERE ' . $this->toDriver('__owner') . ' = ?';
@@ -66,10 +78,10 @@ class Turba_Driver_Sql extends Turba_Driver
             Horde::logMessage('SQL query by Turba_Driver_sql::count(): ' . $query, 'DEBUG');
 
             /* Run query. */
-            $count[$test] = $this->_db->getOne($query, $values);
+            $this->_countCache[$test] = $this->_db->getOne($query, $values);
         }
 
-        return $count[$test];
+        return $this->_countCache[$test];
     }
 
     /**
@@ -84,8 +96,9 @@ class Turba_Driver_Sql extends Turba_Driver
      *                             params are used as bind parameters.
      *
      * @return array  Hash containing the search results.
+     * @throws Turba_Exception
      */
-    function _search($criteria, $fields, $appendWhere = array())
+    protected function _search($criteria, $fields, $appendWhere = array())
     {
         /* Build the WHERE clause. */
         $where = '';
@@ -125,17 +138,17 @@ class Turba_Driver_Sql extends Turba_Driver
 
         /* Run query. */
         $result = $this->_db->query($query, $values);
-        if (is_a($result, 'PEAR_Error')) {
+        if ($result instanceof PEAR_Error) {
             Horde::logMessage($result, 'ERR');
-            return $result;
+            throw new Turba_Exception($result);
         }
 
         $results = array();
         $iMax = count($fields);
         while ($row = $result->fetchRow()) {
-            if (is_a($row, 'PEAR_Error')) {
+            if ($row instanceof PEAR_Error) {
                 Horde::logMessage($row, 'ERR');
-                return $row;
+                throw new Turba_Exception($row);
             }
 
             $row = $this->_convertFromDriver($row);
@@ -161,12 +174,11 @@ class Turba_Driver_Sql extends Turba_Driver
     protected function _buildFields($array)
     {
         foreach ($array as &$entry) {
-            if (is_array($entry)) {
-                $entry = implode(',', $this->_buildFields($entry));
-            } else {
-                $entry = 'a1.' . $entry;
-            }
+            $entry = is_array($entry)
+                ? implode(',', $this->_buildFields($entry))
+                : 'a1.' . $entry;
         }
+
         return $array;
     }
 
@@ -185,6 +197,7 @@ class Turba_Driver_Sql extends Turba_Driver
             }
             $entry = 'a1.' . $entry . ' IS NOT NULL AND a1.' . $entry . ' <> \'\'';
         }
+
         return $array;
     }
 
@@ -198,12 +211,11 @@ class Turba_Driver_Sql extends Turba_Driver
     protected function _buildJoin($array)
     {
         foreach ($array as &$entry) {
-            if (is_array($entry)) {
-                $entry = implode(' AND ', $this->_buildJoin($entry));
-            } else {
-                $entry = 'a1.' . $entry . ' = a2.' . $entry;
-            }
+            $entry = is_array($entry)
+                ? implode(' AND ', $this->_buildJoin($entry))
+                : 'a1.' . $entry . ' = a2.' . $entry;
         }
+
         return $array;
     }
 
@@ -311,8 +323,10 @@ class Turba_Driver_Sql extends Turba_Driver
      * @param array $fields  List of fields to return.
      *
      * @return array  Hash containing the search results.
+     * @throws Turba_Exception
      */
-    function _read($key, $ids, $owner, $fields, $blob_fields = array())
+    protected function _read($key, $ids, $owner, $fields,
+                             $blob_fields = array())
     {
         $values = array();
 
@@ -346,9 +360,9 @@ class Turba_Driver_Sql extends Turba_Driver
         Horde::logMessage('SQL query by Turba_Driver_sql::_read(): ' . $query, 'DEBUG');
 
         $result = $this->_db->getAll($query, $values);
-        if (is_a($result, 'PEAR_Error')) {
+        if ($result instanceof PEAR_Error) {
             Horde::logMessage($result, 'ERR');
-            return $result;
+            throw new Turba_Exception($result);
         }
 
         $results = array();
@@ -363,6 +377,7 @@ class Turba_Driver_Sql extends Turba_Driver
                     case 'mssql':
                         $entry[$field] = pack('H' . strlen($row[$i]), $row[$i]);
                         break;
+
                     default:
                         $entry[$field] = $row[$i];
                         break;
@@ -379,8 +394,12 @@ class Turba_Driver_Sql extends Turba_Driver
 
     /**
      * Adds the specified object to the SQL database.
+     *
+     * TODO
+     *
+     * @throws Turba_Exception
      */
-    function _add($attributes, $blob_fields = array())
+    protected function _add($attributes, $blob_fields = array())
     {
         $fields = $values = array();
         foreach ($attributes as $field => $value) {
@@ -391,8 +410,10 @@ class Turba_Driver_Sql extends Turba_Driver
                 case 'pgsql':
                     $values[] = bin2hex($value);
                     break;
+
                 default:
                     $values[] = $value;
+                    break;
                 }
             } else {
                 $values[] = $this->_convertToDriver($value);
@@ -403,15 +424,16 @@ class Turba_Driver_Sql extends Turba_Driver
             . ' VALUES (' . str_repeat('?, ', count($values) - 1) . '?)';
 
         $result = $this->_write_db->query($query, $values);
-        if (is_a($result, 'PEAR_Error')) {
+        if ($result instanceof PEAR_Error) {
             Horde::logMessage($result, 'ERR');
-            return $result;
+            throw new Turba_Exception($result);
         }
-
-        return true;
     }
 
-    function canAdd()
+    /**
+     * TODO
+     */
+    protected function _canAdd()
     {
         return true;
     }
@@ -419,7 +441,7 @@ class Turba_Driver_Sql extends Turba_Driver
     /**
      * Deletes the specified object from the SQL database.
      */
-    function _delete($object_key, $object_id)
+    protected function _delete($object_key, $object_id)
     {
         $query = 'DELETE FROM ' . $this->_params['table'] .
                  ' WHERE ' . $object_key . ' = ?';
@@ -429,38 +451,34 @@ class Turba_Driver_Sql extends Turba_Driver
         Horde::logMessage('SQL query by Turba_Driver_sql::_delete(): ' . $query, 'DEBUG');
 
         $result = $this->_write_db->query($query, $values);
-        if (is_a($result, 'PEAR_Error')) {
+        if ($result instanceof PEAR_Error) {
             Horde::logMessage($result, 'ERR');
-            return $result;
+            throw new Turba_Exception($result);
         }
-
-        return true;
     }
 
     /**
      * Deletes all contacts from a specific address book.
      *
-     * @return boolean  True if the operation worked.
+     * @throws Turba_Exception
      */
-    function _deleteAll($sourceName = null)
+    protected function _deleteAll($sourceName = null)
     {
         if (!$GLOBALS['registry']->getAuth()) {
-            return PEAR::raiseError('permission denied');
+            throw new Turba_Exception('Permission denied');
         }
 
         /* Get owner id */
-        if (empty($sourceName)) {
-            $values = array($GLOBALS['registry']->getAuth());
-        } else {
-            $values = array($sourceName);
-        }
+        $values = empty($sourceName)
+            ? array($GLOBALS['registry']->getAuth())
+            : array($sourceName);
 
         /* Need a list of UIDs so we can notify History */
         $query = 'SELECT '. $this->map['__uid'] . ' FROM ' . $this->_params['table'] . ' WHERE owner_id = ?';
         Horde::logMessage('SQL query by Turba_Driver_sql::_deleteAll(): ' . $query, 'DEBUG');
         $ids = $this->_write_db->query($query, $values);
-        if (is_a($ids, 'PEAR_Error')) {
-            return $ids;
+        if ($ids instanceof PEAR_Error) {
+            throw new Turba_Exception($ids);
         }
 
         /* Do the deletion */
@@ -468,8 +486,8 @@ class Turba_Driver_Sql extends Turba_Driver
         Horde::logMessage('SQL query by Turba_Driver_sql::_deleteAll(): ' . $query, 'DEBUG');
 
         $result = $this->_write_db->query($query, $values);
-        if (is_a($result, 'PEAR_Error')) {
-            return $result;
+        if ($result instanceof PEAR_Error) {
+            throw new Turba_Exception($result);
         }
 
         /* Update Horde_History */
@@ -486,14 +504,13 @@ class Turba_Driver_Sql extends Turba_Driver
         } catch (Exception $e) {
             Horde::logMessage($e, 'ERR');
         }
-
-        return true;
     }
 
     /**
      * Saves the specified object in the SQL database.
      *
      * @return string  The object id, possibly updated.
+     * @throws Turba_Exception
      */
     function _save($object)
     {
@@ -513,8 +530,10 @@ class Turba_Driver_Sql extends Turba_Driver
                 case 'pgsql':
                     $values[] = bin2hex($value);
                     break;
+
                 default:
                     $values[] = $value;
+                    break;
                 }
             } else {
                 $values[] = $this->_convertToDriver($value);
@@ -523,16 +542,15 @@ class Turba_Driver_Sql extends Turba_Driver
 
         $values[] = $object_id;
 
-        $query  = 'UPDATE ' . $this->_params['table'] . ' SET ' . implode(', ', $fields) . ' ';
-        $query .= 'WHERE ' . $where;
+        $query = 'UPDATE ' . $this->_params['table'] . ' SET ' . implode(', ', $fields) . ' WHERE ' . $where;
 
         /* Log the query at a DEBUG log level. */
         Horde::logMessage('SQL query by Turba_Driver_sql::_save(): ' . $query, 'DEBUG');
 
         $result = $this->_write_db->query($query, $values);
-        if (is_a($result, 'PEAR_Error')) {
+        if ($result instanceof PEAR_Error) {
             Horde::logMessage($result, 'ERR');
-            return $result;
+            throw new Turba_Exception($result);
         }
 
         return $object_id;
@@ -546,7 +564,7 @@ class Turba_Driver_Sql extends Turba_Driver
      *
      * @return string  A unique ID for the new object.
      */
-    function _makeKey($attributes)
+    protected function _makeKey($attributes)
     {
         return strval(new Horde_Support_Randomid());
     }
@@ -560,7 +578,7 @@ class Turba_Driver_Sql extends Turba_Driver
      * @return array  An SQL fragment and a list of values suitable for binding
      *                as an array.
      */
-    function _buildSearchQuery($glue, $criteria)
+    protected function _buildSearchQuery($glue, $criteria)
     {
         $clause = '';
         $values = array();
@@ -625,9 +643,9 @@ class Turba_Driver_Sql extends Turba_Driver
      *
      * @param mixed $value  A value to convert.
      *
-     * @return mixed        The converted value.
+     * @return mixed  The converted value.
      */
-    function _convertFromDriver($value)
+    protected function _convertFromDriver($value)
     {
         return Horde_String::convertCharset($value, $this->_params['charset']);
     }
@@ -637,9 +655,9 @@ class Turba_Driver_Sql extends Turba_Driver
      *
      * @param mixed $value  A value to convert.
      *
-     * @return mixed        The converted value.
+     * @return mixed  The converted value.
      */
-    function _convertToDriver($value)
+    protected function _convertToDriver($value)
     {
         return Horde_String::convertCharset($value, $GLOBALS['registry']->getCharset(), $this->_params['charset']);
     }
@@ -649,16 +667,16 @@ class Turba_Driver_Sql extends Turba_Driver
      *
      * @param string $user  The user's data to remove.
      *
-     * @return mixed True | PEAR_Error
+     * @throws Turba_Exception
      */
-    function removeUserData($user)
+    public function removeUserData($user)
     {
         // Make sure we are being called by an admin.
         if (!$GLOBALS['registry']->isAdmin()) {
-            return PEAR::raiseError(_("Permission denied"));
+            throw new Turba_Exception(_("Permission denied"));
         }
 
-        return $this->_deleteAll($user);
+        $this->_deleteAll($user);
     }
 
     /**
@@ -669,9 +687,10 @@ class Turba_Driver_Sql extends Turba_Driver
      * @param string $field      The address book field containing the
      *                           timeObject information (birthday, anniversary)
      *
-     * @return mixed  A Tubra_List of objects || PEAR_Error
+     * @return Turba_List  Object list.
+     * @throws Turba_Exception
      */
-    function _getTimeObjectTurbaList($start, $end, $field)
+    protected function _getTimeObjectTurbaList($start, $end, $field)
     {
         $t_object = $this->toDriver($field);
         $criteria = $this->makesearch(
@@ -682,9 +701,11 @@ class Turba_Driver_Sql extends Turba_Driver
 
         // Limit to entries that actually contain a birthday and that are in the
         // date range we are looking for.
-        $criteria['AND'][] = array('field' => $t_object,
-                                   'op' => '<>',
-                                   'test' => '');
+        $criteria['AND'][] = array(
+            'field' => $t_object,
+            'op' => '<>',
+            'test' => ''
+        );
 
         if ($start->year == $end->year) {
             $start = sprintf('%02d-%02d', $start->month, $start->mday);
@@ -695,12 +716,13 @@ class Turba_Driver_Sql extends Turba_Driver
         } else {
             $months = array();
             $diff = ($end->month + 12) - $start->month;
-            $newDate = new Horde_Date(array('month' => $start->month,
-                                            'mday' => $start->mday,
-                                            'year' => $start->year));
-            for ($i = 0; $i <= $diff; $i++) {
-                $months[] = sprintf('%02d', $newDate->month);
-                $newDate->month++;
+            $newDate = new Horde_Date(array(
+                'month' => $start->month,
+                'mday' => $start->mday,
+                'year' => $start->year
+            ));
+            for ($i = 0; $i <= $diff; ++$i) {
+                $months[] = sprintf('%02d', $newDate->month++);
             }
             $where = array('sql' => $t_object . ' IS NOT NULL AND SUBSTR('
                            . $t_object . ', 6, 2) IN ('
@@ -708,8 +730,11 @@ class Turba_Driver_Sql extends Turba_Driver
                            'params' => $months);
         }
 
-        $fields_pre = array('__key', '__type', '__owner', 'name',
-                            'birthday', 'category', 'anniversary');
+        $fields_pre = array(
+            '__key', '__type', '__owner', 'name', 'birthday', 'category',
+            'anniversary'
+        );
+
         $fields = array();
         foreach ($fields_pre as $field) {
             $result = $this->toDriver($field);
@@ -725,11 +750,7 @@ class Turba_Driver_Sql extends Turba_Driver
             }
         }
 
-        $res = $this->_search($criteria, $fields, $where);
-        if (is_a($res, 'PEAR_Error')) {
-            return $res;
-        }
-        return $this->_toTurbaObjects($res);
+        return $this->_toTurbaObjects($this->_search($criteria, $fields, $where));
     }
 
 }
index d51dd59..437e6ad 100644 (file)
@@ -7,8 +7,10 @@
  * See the enclosed file LICENSE for license information (ASL).  If you
  * did not receive this file, see http://www.horde.org/licenses/asl.php.
  *
- * @author  Michael Rubinsky <mrubinsk@horde.org>
- * @package Turba
+ * @author   Michael J. Rubinsky <mrubinsk@horde.org>
+ * @category Horde
+ * @license  http://www.horde.org/licenses/asl.php ASL
+ * @package  Turba
  */
 class Turba_Driver_Vbook extends Turba_Driver
 {
@@ -17,14 +19,14 @@ class Turba_Driver_Vbook extends Turba_Driver
      *
      * @var string
      */
-    var $searchType;
+    public $searchType;
 
     /**
      * The search criteria that defines this virtual address book.
      *
      * @var array
      */
-    var $searchCriteria;
+    public $searchCriteria;
 
     /**
      * Return the owner to use when searching or creating contacts in
@@ -32,24 +34,12 @@ class Turba_Driver_Vbook extends Turba_Driver
      *
      * @return string
      */
-    function _getContactOwner()
+    protected function _getContactOwner()
     {
         return $this->_driver->getContactOwner();
     }
 
     /**
-     * Deletes all contacts from an address book. Not implemented for
-     * virtual address books; just returns true so that the address
-     * book can be deleted.
-     *
-     * @return boolean  True
-     */
-    function deleteAll($sourceName = null)
-    {
-        return true;
-    }
-
-    /**
      * @throws Turba_Exception
      */
     protected function _init()
@@ -58,7 +48,7 @@ class Turba_Driver_Vbook extends Turba_Driver
         $this->_share = $this->_params['share'];
 
         /* Load the underlying driver. */
-        $driver = $GLOBALS['injector']->getInstance('Turba_Driver')->getDriver($this->_params['source']);
+        $this->_driver = $GLOBALS['injector']->getInstance('Turba_Driver')->getDriver($this->_params['source']);
 
         $this->searchCriteria = empty($this->_params['criteria'])
             ? array()
@@ -76,8 +66,9 @@ class Turba_Driver_Vbook extends Turba_Driver
      * @param array $fields    List of fields to return
      *
      * @return array  Hash containing the search results.
+     * @throws Turba_Exception
      */
-    function _search($criteria, $fields)
+    protected function _search($criteria, $fields)
     {
         /* Add the passed in search criteria to the vbook criteria
          * (which need to be mapped from turba fields to
@@ -97,31 +88,35 @@ class Turba_Driver_Vbook extends Turba_Driver
      *
      * @return array  Hash containing the search results.
      */
-    function _read($key, $ids, $owner, $fields)
+    protected function _read($key, $ids, $owner, $fields)
     {
         return $this->_driver->_read($key, $ids, $owner, $fields);
     }
 
     /**
      * Not supported for virtual address books.
+     *
+     * @throws Turba_Exception
      */
-    function _add($attributes)
+    protected function _add($attributes)
     {
-        return PEAR::raiseError(_("You cannot add new contacts to a virtual address book"));
+        throw new Turba_Exception(_("You cannot add new contacts to a virtual address book"));
     }
 
     /**
      * Not supported for virtual address books.
+     *
+     * @throws Turba_Exception
      */
-    function _delete($object_key, $object_id)
+    protected function _delete($object_key, $object_id)
     {
-        return PEAR::raiseError(_("You cannot delete contacts from a virtual address book"));
+        throw new Turba_Exception(_("You cannot delete contacts from a virtual address book"));
     }
 
     /**
-     * Not supported for virtual address books.
+     * TODO
      */
-    function _save($object)
+    protected function _save($object)
     {
         return $this->_driver->save($object);
     }
@@ -133,7 +128,7 @@ class Turba_Driver_Vbook extends Turba_Driver
      *
      * @return boolean  True or False.
      */
-    function hasPermission($perm)
+    public function hasPermission($perm)
     {
         return $this->_driver->hasPermission($perm);
     }
index 05dd7e9..f0e088e 100644 (file)
@@ -70,24 +70,27 @@ class Turba_Form_AddContact extends Turba_Form_Contact
         unset($contact['__owner']);
 
         /* Create Contact. */
-        $key = $driver->add($contact);
-        if (is_a($key, 'PEAR_Error')) {
-            Horde::logMessage($key, 'ERR');
-        } else {
+        try {
+            $key = $driver->add($contact);
+        } catch (Turba_Exception $e) {
+            Horde::logMessage($e, 'ERR');
+            $key = null;
+        }
+
+        if ($key) {
             // Try 3 times to get the new entry. We retry to allow setups like
             // LDAP replication to work.
-            for ($i = 0; $i < 3; $i++) {
-                $ob = $driver->getObject($key);
-                if (!is_a($ob, 'PEAR_Error')) {
+            for ($i = 0; $i < 3; ++$i) {
+                try {
+                    $ob = $driver->getObject($key);
                     $notification->push(sprintf(_("%s added."), $ob->getValue('name')), 'horde.success');
                     $url = empty($info['url'])
                         ? $ob->url('Contact', true)
                         : new Horde_Url($info['url']);
                     $url->redirect();
-                }
+                } catch (Turba_Exception $e) {}
                 sleep(1);
             }
-            Horde::logMessage($ob, 'ERR');
         }
 
         $notification->push(_("There was an error adding the new contact. Contact your system administrator for further help."), 'horde.error');
index 5021e10..1836023 100644 (file)
@@ -22,12 +22,12 @@ class Turba_Form_Contact extends Horde_Form
         /* List files. */
         $v_params = $GLOBALS['injector']->getInstance('Horde_Vfs')->getConfig('documents');
         if ($v_params['type'] != 'none') {
-            $files = $contact->listFiles();
-            if (is_a($files, 'PEAR_Error')) {
-                $notification->push($files, 'horde.error');
-            } else {
+            try {
+                $files = $contact->listFiles();
                 $this->addVariable(_("Files"), '__vfs', 'html', false);
                 $vars->set('__vfs', implode('<br />', array_map(array($contact, 'vfsEditUrl'), $files)));
+            } catch (Turba_Exception $e) {
+                $notification->push($files, 'horde.error');
             }
         }
     }
index 3075da2..19086bd 100644 (file)
@@ -53,10 +53,7 @@ class Turba_Form_DeleteAddressBook extends Horde_Form
         $driver = $GLOBALS['injector']->getInstance('Turba_Driver')->getDriver($this->_addressbook->getName());
 
         // We have a Turba_Driver, try to delete the address book.
-        $result = $driver->deleteAll();
-        if (is_a($result, 'PEAR_Error')) {
-            throw new Turba_Exception($result);
-        }
+        $driver->deleteAll();
 
         // Address book successfully deleted from backend, remove the
         // share.
index c0abb14..df21352 100644 (file)
@@ -38,11 +38,13 @@ class Turba_Form_EditAddressBook extends Horde_Form
     {
         $this->_addressbook->set('name', $this->_vars->get('name'));
         $this->_addressbook->set('desc', $this->_vars->get('description'));
-        $result = $this->_addressbook->save();
-        if (is_a($result, 'PEAR_Error')) {
-            return PEAR::raiseError(sprintf(_("Unable to save address book \"%s\": %s"), $id, $result->getMessage()));
+
+        try {
+            $this->_addressbook->save();
+            return true;
+        } catch (Turba_Exception $e) {
+            return PEAR::raiseError(sprintf(_("Unable to save address book \"%s\": %s"), $id, $e->getMessage()));
         }
-        return true;
     }
 
 }
index baf4ea2..1bcab1b 100644 (file)
@@ -66,24 +66,25 @@ class Turba_Form_EditContact extends Turba_Form_Contact
             }
         }
 
-        $result = $this->_contact->store();
-        if (!is_a($result, 'PEAR_Error')) {
-            if ($conf['documents']['type'] != 'none' && isset($info['vfs'])) {
-                $result = $this->_contact->addFile($info['vfs']);
-                if (is_a($result, 'PEAR_Error')) {
-                    $notification->push(sprintf(_("\"%s\" updated, but saving the uploaded file failed: %s"), $this->_contact->getValue('name'), $result->getMessage()), 'horde.warning');
-                } else {
-                    $notification->push(sprintf(_("\"%s\" updated."), $this->_contact->getValue('name')), 'horde.success');
-                }
-            } else {
+        try {
+            $this->_contact->store();
+        } catch (Turba_Exception $e) {
+            Horde::logMessage($e, 'ERR');
+            $notification->push(_("There was an error saving the contact. Contact your system administrator for further help."), 'horde.error');
+            return PEAR::raiseError($e->getMessage());
+        }
+
+        if ($conf['documents']['type'] != 'none' && isset($info['vfs'])) {
+            try {
+                $this->_contact->addFile($info['vfs']);
                 $notification->push(sprintf(_("\"%s\" updated."), $this->_contact->getValue('name')), 'horde.success');
-            }
-            return true;
+            } catch (Turba_Exception $e) {
+                $notification->push(sprintf(_("\"%s\" updated, but saving the uploaded file failed: %s"), $this->_contact->getValue('name'), $e->getMessage()), 'horde.warning');
         } else {
-            Horde::logMessage($result, 'ERR');
-            $notification->push(_("There was an error saving the contact. Contact your system administrator for further help."), 'horde.error');
-            return $result;
+            $notification->push(sprintf(_("\"%s\" updated."), $this->_contact->getValue('name')), 'horde.success');
         }
+
+        return true;
     }
 
 }
index aa22f83..c2248a2 100644 (file)
@@ -47,7 +47,7 @@ class Turba_Form_EditContactGroup extends Turba_Form_EditContact
     function execute()
     {
         $result = parent::execute();
-        if (is_a($result, 'PEAR_Error')) {
+        if ($result instanvceof PEAR_Error) {
             return $result;
         }
 
index 6a29868..eb73117 100644 (file)
@@ -41,15 +41,11 @@ class Turba_LoginTasks_SystemTask_UpgradeLists extends Horde_LoginTasks_SystemTa
             foreach ($sources as $sourcekey) {
                 try {
                     $driver = $GLOBALS['injector']->getInstance('Turba_Driver')->getDriver($sourcekey);
+                    $lists = $driver->search($criteria);
                 } catch (Turba_Exception $e) {
                     return false;
                 }
 
-                $lists = $driver->search($criteria);
-                if ($lists instanceof PEAR_Error) {
-                    return false;
-                }
-
                 for ($j = 0, $cnt = count($lists); $j < $cnt; ++$j) {
                     $list = $lists->next();
                     $attributes = $list->getAttributes();
index 508f883..1006e0d 100644 (file)
@@ -31,7 +31,7 @@ class Turba_LoginTasks_SystemTask_UpgradePrefs extends Horde_LoginTasks_SystemTa
     /**
      * Perform all functions for this task.
      *
-     * @return mixed True | PEAR_Error
+     * @return boolean  Success.
      */
     public function execute()
     {
index fd51542..7028ce2 100644 (file)
@@ -295,7 +295,7 @@ class Turba_Object {
     function url($view = null, $full = false)
     {
         $url = Horde::applicationUrl('contact.php', $full)->add(array(
-            'source' => $this->driver->name,
+            'source' => $this->driver->getName(),
             'key' => $this->getValue('__key')
         ));
 
@@ -409,7 +409,7 @@ class Turba_Object {
         $url_params = array('actionID' => 'download_file',
                             'file' => $file['name'],
                             'type' => $file['type'],
-                            'source' => $this->driver->name,
+                            'source' => $this->driver->getName(),
                             'key' => $this->getValue('__key'));
         $dl = Horde::link(Horde::downloadUrl($file['name'], $url_params), $file['name']) . Horde::img('download.png', _("Download")) . '</a>';
 
@@ -439,7 +439,7 @@ class Turba_Object {
             '" style="display:inline" method="post">' .
             Horde_Util::formInput() .
             '<input type="hidden" name="file" value="' . htmlspecialchars($file['name']) . '" />' .
-            '<input type="hidden" name="source" value="' . htmlspecialchars($this->driver->name) . '" />' .
+            '<input type="hidden" name="source" value="' . htmlspecialchars($this->driver->getName()) . '" />' .
             '<input type="hidden" name="key" value="' . htmlspecialchars($this->getValue('__key')) . '" />' .
             '<input type="image" class="img" src="' . Horde_Themes::img('delete.png') . '" />' .
             '</form>';
@@ -449,15 +449,12 @@ class Turba_Object {
 
     /**
      * Saves the current state of the object to the storage backend.
+     *
+     * @throws Turba_Exception
      */
-    function store()
+    public function store()
     {
-        $object_id = $this->driver->save($this);
-        if (is_a($object_id, 'PEAR_Error')) {
-            return $object_id;
-        }
-
-        return $this->setValue('__key', $object_id);
+        return $this->setValue('__key', $this->driver->save($this));
     }
 
     /**
index 3594253..b0ed988 100644 (file)
@@ -71,12 +71,6 @@ class Turba_Object_Group extends Turba_Object {
             $contact = $driver->getObject($contactId);
         }
 
-        // Bail out if the contact being added doesn't exist or can't
-        // be retrieved.
-        if (is_a($contact, 'PEAR_Error')) {
-            throw new Turba_Exception($contact);
-        }
-
         // Explode members.
         $members = @unserialize($this->attributes['__members']);
         if (!is_array($members)) {
@@ -160,8 +154,9 @@ class Turba_Object_Group extends Turba_Object {
         $modified = false;
         foreach ($children as $member) {
             if (strpos($member, ':') === false) {
-                $contact = $this->driver->getObject($member);
-                if (is_a($contact, 'PEAR_Error')) {
+                try {
+                    $contact = $this->driver->getObject($member);
+                } catch (Turba_Exception $e) {
                     // Remove the contact if it no longer exists
                     $this->removeMember($member);
                     $modified = true;
@@ -180,8 +175,9 @@ class Turba_Object_Group extends Turba_Object {
                     continue;
                 }
 
-                $contact = $driver->getObject($contactId);
-                if (is_a($contact, 'PEAR_Error')) {
+                try {
+                    $contact = $driver->getObject($contactId);
+                } catch (Turba_Exception $e) {
                     // Remove the contact if it no longer exists
                     $this->removeMember($member);
                     $modified = true;
index e233229..2558dd8 100644 (file)
@@ -308,7 +308,7 @@ class Turba {
     {
         // We want to check the base source as extended permissions
         // are enforced per backend, not per share.
-        $key = $addressBook->name . ':' . $permission;
+        $key = $addressBook->getName() . ':' . $permission;
 
         $perms = $GLOBALS['injector']->getInstance('Horde_Perms');
         if (!$perms->exists('turba:sources:' . $key)) {
@@ -543,6 +543,7 @@ class Turba {
             Horde::logMessage($e, 'ERR');
             return array();
         }
+
         return $sources;
     }
 
@@ -552,9 +553,10 @@ class Turba {
      * @param string $share_id The id for the new share.
      * @param array $params Parameters for the new share.
      *
-     * @return mixed  The new share object or PEAR_Error
+     * @return Horde_Share  The new share object.
+     * @throws Turba_Exception
      */
-    function createShare($share_id, $params)
+    static public function createShare($share_id, $params)
     {
         if (!isset($params['name'])) {
             /* Sensible default for empty display names */
@@ -585,7 +587,7 @@ class Turba {
             }
             $GLOBALS['turba_shares']->addShare($share);
             $result = $share->save();
-         } catch (Horde_Share_Exception $e) {
+        } catch (Horde_Share_Exception $e) {
             Horde::logMessage($e, 'ERR');
             throw new Turba_Exception($e);
         }
index 4e43386..386fb8f 100644 (file)
@@ -114,8 +114,10 @@ class Turba_View_Browse {
                     $errorCount = 0;
                     foreach ($keys as $sourceKey) {
                         list($objectSource, $objectKey) = explode(':', $sourceKey, 2);
-                        if (is_a($driver->delete($objectKey), 'PEAR_Error')) {
-                            $errorCount++;
+                        try {
+                            $driver->delete($objectKey);
+                        } catch (Turba_Exception $e) {
+                            ++$errorCount;
                         }
                     }
                     if (!$errorCount) {
@@ -175,11 +177,14 @@ class Turba_View_Browse {
                         continue;
                     }
 
-                    $object = &$sourceDriver->getObject($objectKey);
-                    if (is_a($object, 'PEAR_Error')) {
-                        $notification->push(sprintf(_("Failed to find object to be added: %s"), $object->getMessage()), 'horde.error');
+                    try {
+                        $object = $sourceDriver->getObject($objectKey);
+                    } catch (Turba_Exception $e) {
+                        $notification->push(sprintf(_("Failed to find object to be added: %s"), $e->getMessage()), 'horde.error');
                         continue;
-                    } elseif ($object->isGroup()) {
+                    }
+
+                    if ($object->isGroup()) {
                         if ($actionID == 'move') {
                             $notification->push(sprintf(_("\"%s\" was not moved because it is a list."), $object->getValue('name')), 'horde.warning');
                         } else {
@@ -204,9 +209,10 @@ class Turba_View_Browse {
                     }
                     unset($objAttributes['__owner']);
 
-                    $result = $targetDriver->add($objAttributes);
-                    if (is_a($result, 'PEAR_Error')) {
-                        $notification->push(sprintf(_("Failed to add %s to %s: %s"), $object->getValue('name'), $targetDriver->title, $result->getMessage()), 'horde.error');
+                    try {
+                        $targetDriver->add($objAttributes);
+                    } catch (Turba_Exception $e) {
+                        $notification->push(sprintf(_("Failed to add %s to %s: %s"), $object->getValue('name'), $targetDriver->title, $e), 'horde.error');
                         break;
                     }
 
@@ -215,7 +221,9 @@ class Turba_View_Browse {
                     // If we're moving objects, and we succeeded,
                     // delete them from the original source now.
                     if ($actionID == 'move') {
-                        if (is_a($sourceDriver->delete($objectKey), 'PEAR_Error')) {
+                        try {
+                            $sourceDriver->delete($objectKey);
+                        } catch (Turba_Exception $e) {
                             $notification->push(sprintf(_("There was an error deleting \"%s\" from the source address book."), $object->getValue('name')), 'horde.error');
                         }
 
@@ -254,9 +262,11 @@ class Turba_View_Browse {
                         $notification->push($e, 'horde.error');
                         break;
                     }
-                    $target = &$targetDriver->getObject($targetKey);
-                    if (is_a($target, 'PEAR_Error')) {
-                        $notification->push($target, 'horde.error');
+
+                    try {
+                        $target = $targetDriver->getObject($targetKey);
+                    } catch (Turba_Exception $e) {
+                        $notification->push($e, 'horde.error');
                         break;
                     }
                 } else {
@@ -302,34 +312,43 @@ class Turba_View_Browse {
                     }
 
                     // Adding contact to a new list.
-                    $newList = array('__owner' => $targetDriver->getContactOwner(),
-                                     '__type' => 'Group',
-                                     'name' => $targetKey);
-                    $targetKey = $targetDriver->add($newList);
-                    if (!is_a($targetKey, 'PEAR_Error')) {
-                        $target = &$targetDriver->getObject($targetKey);
-                        if (!is_a($target, 'PEAR_Error') && $target->isGroup()) {
-                            $notification->push(sprintf(_("Successfully created the contact list \"%s\"."), $newList['name']), 'horde.success');
-                            if (is_array($keys)) {
-                                $errorCount = 0;
-                                foreach ($keys as $sourceKey) {
-                                    list($objectSource, $objectKey) = explode(':', $sourceKey, 2);
-                                    if (!$target->addMember($objectKey, $objectSource)) {
-                                        $errorCount++;
+                    $newList = array(
+                        '__owner' => $targetDriver->getContactOwner(),
+                        '__type' => 'Group',
+                        'name' => $targetKey
+                    );
+
+                    try {
+                        $targetKey = $targetDriver->add($newList);
+                    } catch (Turba_Exception $e) {
+                        $notification->push(_("There was an error creating a new list."), 'horde.error');
+                        $targetKey = null;
+                    }
+
+                    if ($targetKey) {
+                        try {
+                            $target = $targetDriver->getObject($targetKey);
+                            if ($target->isGroup()) {
+                                $notification->push(sprintf(_("Successfully created the contact list \"%s\"."), $newList['name']), 'horde.success');
+                                if (is_array($keys)) {
+                                    $errorCount = 0;
+                                    foreach ($keys as $sourceKey) {
+                                        list($objectSource, $objectKey) = explode(':', $sourceKey, 2);
+                                        if (!$target->addMember($objectKey, $objectSource)) {
+                                            ++$errorCount;
+                                        }
                                     }
+                                    if (!$errorCount) {
+                                        $notification->push(sprintf(_("Successfully added %d contact(s) to list."), count($keys)), 'horde.success');
+                                    } elseif ($errorCount == count($keys)) {
+                                        $notification->push(sprintf(_("Error adding %d contact(s) to list."), count($keys)), 'horde.error');
+                                    } else {
+                                        $notification->push(sprintf(_("Error adding %d of %d requested contact(s) to list."), $errorCount, count($keys)), 'horde.error');
+                                    }
+                                    $target->store();
                                 }
-                                if (!$errorCount) {
-                                    $notification->push(sprintf(_("Successfully added %d contact(s) to list."), count($keys)), 'horde.success');
-                                } elseif ($errorCount == count($keys)) {
-                                    $notification->push(sprintf(_("Error adding %d contact(s) to list."), count($keys)), 'horde.error');
-                                } else {
-                                    $notification->push(sprintf(_("Error adding %d of %d requested contact(s) to list."), $errorCount, count($keys)), 'horde.error');
-                                }
-                                $target->store();
                             }
-                        }
-                    } else {
-                        $notification->push(_("There was an error creating a new list."), 'horde.error');
+                        } catch (Turba_Exception $e) {}
                     }
                 }
                 break;
@@ -354,26 +373,30 @@ class Turba_View_Browse {
 
             if ($vars->get('key')) {
                 // We are displaying a list.
-                $list = &$driver->getObject($vars->get('key'));
-                if (isset($list) && is_object($list) &&
-                    !is_a($list, 'PEAR_Error') && $list->isGroup()) {
+                try {
+                    $list = $driver->getObject($vars->get('key'));
+                } catch (Turba_Exception $e) {
+                    $notification->push(_("There was an error displaying the list"), 'horde.error');
+                    $list = null;
+                }
+
+                if ($list && $list->isGroup()) {
                     $title = sprintf(_("Contacts in list: %s"),
                                      $list->getValue('name'));
                     $templates[] = '/browse/header.inc';
 
                     // Show List Members.
-                    if (!is_object($results = $list->listMembers($sortorder))) {
-                        $notification->push(_("Failed to browse list"), 'horde.error');
-                    } else {
+                    try {
+                        $results = $list->listMembers($sortorder);
                         if (count($results) != count($list)) {
                             $count = count($list) - count($results);
                             $notification->push(sprintf(ngettext("There is %d contact in this list that is not viewable to you", "There are %d contacts in this list that are not viewable to you", $count), $count), 'horde.message');
                         }
                         $view = new Turba_View_List($results, null, $columns);
                         $view->setType('list');
+                    } catch (Turba_Exception $e) {
+                        $notification->push(_("Failed to browse list"), 'horde.error');
                     }
-                } else {
-                    $notification->push(_("There was an error displaying the list"), 'horde.error');
                 }
             } else {
                 // We are displaying an address book.
@@ -392,14 +415,13 @@ class Turba_View_Browse {
                         $type_filter = array('__type' => 'Group');
                         break;
                     }
-                    $results = $driver->search($type_filter, $sortorder, 'AND', $columns ? $columns : array('name'));
-                    if (!is_object($results)) {
-                        $notification->push(_("Failed to browse the directory"), 'horde.error');
-                    } elseif (is_a($results, 'PEAR_Error')) {
-                        $notification->push($results, 'horde.error');
-                    } else {
+
+                    try {
+                        $results = $driver->search($type_filter, $sortorder, 'AND', $columns ? $columns : array('name'));
                         $view = new Turba_View_List($results, null, $columns);
                         $view->setType('directory');
+                    } catch (Turba_Exception $e) {
+                        $notification->push($e, 'horde.error');
                     }
                 }
             }
index 3e5dc4a..436a87a 100644 (file)
@@ -22,7 +22,7 @@ class Turba_View_Contact {
 
     function getTitle()
     {
-        if (!$this->contact || is_a($this->contact, 'PEAR_Error')) {
+        if (!$this->contact) {
             return _("Not Found");
         }
         return $this->contact->getValue('name');
@@ -32,7 +32,8 @@ class Turba_View_Contact {
     {
         global $conf, $prefs, $registry;
 
-        if (!$this->contact || is_a($this->contact, 'PEAR_Error') || !$this->contact->hasPermission(Horde_Perms::READ)) {
+        if (!$this->contact ||
+            !$this->contact->hasPermission(Horde_Perms::READ)) {
             echo '<h3>' . _("The requested contact was not found.") . '</h3>';
             return;
         }
@@ -55,9 +56,10 @@ class Turba_View_Contact {
 
         /* Comments. */
         if (!empty($conf['comments']['allow']) && $registry->hasMethod('forums/doComments')) {
-            $comments = $registry->call('forums/doComments', array('turba', $this->contact->driver->name . '.' . $this->contact->getValue('__key'), 'commentCallback'));
-            if (is_a($comments, 'PEAR_Error')) {
-                Horde::logMessage($comments, 'DEBUG');
+            try {
+                $comments = $registry->call('forums/doComments', array('turba', $this->contact->driver->getName() . '.' . $this->contact->getValue('__key'), 'commentCallback'));
+            } catch (Horde_Exception $e) {
+                Horde::logMessage($e, 'DEBUG');
                 $comments = array();
             }
         }
index 96bd06d..bf31e22 100644 (file)
@@ -19,7 +19,7 @@ class Turba_View_DeleteContact {
 
     function getTitle()
     {
-        if (!$this->contact || is_a($this->contact, 'PEAR_Error')) {
+        if (!$this->contact) {
             return _("Not Found");
         }
         return sprintf(_("Delete %s"), $this->contact->getValue('name'));
@@ -29,7 +29,7 @@ class Turba_View_DeleteContact {
     {
         global $conf, $prefs;
 
-        if (!$this->contact || is_a($this->contact, 'PEAR_Error')) {
+        if (!$this->contact) {
             echo '<h3>' . _("The requested contact was not found.") . '</h3>';
             return;
         }
@@ -49,7 +49,7 @@ class Turba_View_DeleteContact {
     <form action="<?php echo Horde::applicationUrl('delete.php') ?>" method="post">
 <?php echo Horde_Util::formInput() ?>
 <input type="hidden" name="url" value="<?php echo htmlspecialchars(Horde_Util::getFormData('url')) ?>" />
-<input type="hidden" name="source" value="<?php echo htmlspecialchars($this->contact->driver->name) ?>" />
+<input type="hidden" name="source" value="<?php echo htmlspecialchars($this->contact->driver->getName()) ?>" />
 <input type="hidden" name="key" value="<?php echo htmlspecialchars($this->contact->getValue('__key')) ?>" />
 <div class="headerbox" style="padding: 8px">
  <p><?php echo _("Permanently delete this contact?") ?></p>
index fbeee2a..2ef8d88 100644 (file)
@@ -114,7 +114,7 @@ class Turba_View_Duplicates
         $view->hasDuplicate = (bool)$hasDuplicate;
         $view->attributes = $GLOBALS['attributes'];
         $view->link = Horde::applicationUrl('search.php')
-            ->add(array('source' => $this->_driver->name,
+            ->add(array('source' => $this->_driver->getName(),
                         'search_mode' => 'duplicate'));
 
         echo $view->render('list');
index 5ded8f5..83005bd 100644 (file)
@@ -19,7 +19,7 @@ class Turba_View_EditContact {
 
     function getTitle()
     {
-        if (!$this->contact || is_a($this->contact, 'PEAR_Error')) {
+        if (!$this->contact) {
             return _("Not Found");
         }
         return sprintf(_("Edit %s"), $this->contact->getValue('name'));
@@ -29,7 +29,7 @@ class Turba_View_EditContact {
     {
         global $conf, $prefs, $vars;
 
-        if (!$this->contact || is_a($this->contact, 'PEAR_Error')) {
+        if (!$this->contact) {
             echo '<h3>' . _("The requested contact was not found.") . '</h3>';
             return;
         }
index 5611d0f..e43e6c6 100644 (file)
@@ -395,22 +395,32 @@ class Turba_View_List implements Countable
                                             'source' => htmlspecialchars($src));
 
                 $srcDriver = $GLOBALS['injector']->getInstance('Turba_Driver')->getDriver($src);
-                $listList = $srcDriver->search(array('__type' => 'Group'),
-                                               array(array('field' => 'name',
-                                                           'ascending' => true)),
-                                               'AND', array('name'));
-                if (is_a($listList, 'PEAR_Error')) {
-                    $GLOBALS['notification']->push($listList, 'horde.error');
-                } else {
+                try {
+                    $listList = $srcDriver->search(
+                        array('__type' => 'Group'),
+                        array(
+                            array(
+                                'field' => 'name',
+                                'ascending' => true
+                            )
+                        ),
+                        'AND',
+                        array('name')
+                    );
+
                     $listList->reset();
                     $currentList = Horde_Util::getFormData('key');
                     while ($listObject = $listList->next()) {
                         if ($listObject->getValue('__key') != $currentList) {
-                            $addToList[] = array('name' => htmlspecialchars($listObject->getValue('name')),
-                                                 'source' => htmlspecialchars($src),
-                                                 'key' => htmlspecialchars($listObject->getValue('__key')));
+                            $addToList[] = array(
+                                'name' => htmlspecialchars($listObject->getValue('name')),
+                                'source' => htmlspecialchars($src),
+                                'key' => htmlspecialchars($listObject->getValue('__key'))
+                            );
                         }
                     }
+                } catch (Turba_Exception $e) {
+                    $GLOBALS['notification']->push($e, 'horde.error');
                 }
             }
         }
index ece6344..378b417 100644 (file)
@@ -22,26 +22,16 @@ if ($url = Horde_Util::getFormData('url')) {
     $url = new Horde_Url($url, true)->unique();
 }
 
-$contact = $driver->getObject($mergeInto);
-if (is_a($contact, 'PEAR_Error')) {
-    $notification->push($contact);
-    $url->redirect();
-}
-$toMerge = $driver->getObject($key);
-if (is_a($toMerge, 'PEAR_Error')) {
-    $notification->push($toMerge);
-    $url->redirect();
-}
+try {
+    $contact = $driver->getObject($mergeInto);
+    $toMerge = $driver->getObject($key);
+    $contact->merge($toMerge);
+    $contact->store();
+    $driver->delete($key);
 
-$contact->merge($toMerge);
-if (is_a($result = $contact->store(), 'PEAR_Error')) {
-    $notification->push($result);
-    $url->redirect();
-}
-if (is_a($result = $driver->delete($key), 'PEAR_Error')) {
-    $notification->push($result);
-    $url->redirect();
+    $notification->push(_("Successfully merged two contacts."), 'horde.success');
+} catch (Turba_Exception $e) {
+    $notification->push($e);
 }
 
-$notification->push(_("Successfully merged two contacts."), 'horde.success');
 $url->redirect();
index 2e43101..3c1534a 100644 (file)
@@ -23,31 +23,28 @@ $source = Horde_Util::getFormData('source', Turba::getDefaultAddressBook());
 if (!is_null($search)) {
     try {
         $driver = $injector->getInstance('Turba_Driver')->getDriver($source);
-    } catch (Turba_Exception $e) {
-        $driver = null;
-    }
-
-    if ($driver) {
         $criteria['name'] = trim($search);
         $res = $driver->search($criteria);
-        if ($res instanceof Turba_List) {
-            while ($ob = $res->next()) {
-                if ($ob->isGroup()) {
-                    continue;
-                }
-                $att = $ob->getAttributes();
-                foreach ($att as $key => $value) {
-                    if (!empty($attributes[$key]['type']) &&
-                        $attributes[$key]['type'] == 'email') {
-                        $results[] = array('name' => $ob->getValue('name'),
-                                           'email' => $value,
-                                           'url' => $ob->url());
-                        break;
-                    }
+
+        while ($ob = $res->next()) {
+            if ($ob->isGroup()) {
+                continue;
+            }
+
+            $att = $ob->getAttributes();
+            foreach ($att as $key => $value) {
+                if (!empty($attributes[$key]['type']) &&
+                    ($attributes[$key]['type'] == 'email')) {
+                    $results[] = array(
+                        'name' => $ob->getValue('name'),
+                        'email' => $value,
+                        'url' => $ob->url()
+                    );
+                    break;
                 }
             }
         }
-    }
+    } catch (Turba_Exception $e) {}
 }
 
 Horde::addScriptFile('prototype.js', 'horde');
@@ -61,22 +58,18 @@ if (count($results)) {
     foreach ($results as $contact) {
         echo '<li class="linedRow">';
 
-        $mail_link = $GLOBALS['registry']->call(
-            'mail/compose',
-            array(array('to' => addslashes($contact['email']))));
-        if (is_a($mail_link, 'PEAR_Error')) {
+        try {
+            $mail_link = $registry->call('mail/compose', array(
+                array('to' => addslashes($contact['email']))
+            ));
+        } catch (Turba_Exception $e) {
             $mail_link = 'mailto:' . urlencode($contact['email']);
-            $target = '';
-        } else {
-            $target = strpos($mail_link, 'javascript:') === 0
-                ? ''
-                : ' target="_parent"';
         }
 
         echo Horde::link(Horde::applicationUrl($contact['url']),
                         _("View Contact"), '', '_parent')
             . Horde::img('contact.png', _("View Contact")) . '</a> '
-            . '<a href="' . $mail_link . '"' . $target . '>'
+            . '<a href="' . $mail_link . '">'
             . htmlspecialchars($contact['name'] . ' <' . $contact['email'] . '>')
             . '</a></li>';
     }
index 7892ed4..7291ef5 100755 (executable)
@@ -109,29 +109,30 @@ foreach($files as $file) {
             $gid = $driver->add($attributes);
             $group = new Turba_Object_Group($driver, array_merge($attributes, array('__key' => $gid)));
             foreach ($members as $member) {
-                $result = $driver->add(array('firstname' => $member, 'email' => $member));
-                if ($result && !is_a($result, 'PEAR_Error')) {
-                    $added = $group->addMember($result, $import_source);
-                    if (is_a($added, 'PEAR_Error')) {
-                        $cli->message('  ' . $added->getMessage(), 'cli.error');
-                    } else {
-                        $cli->message('  Added ' . $member, 'cli.success');
-                    }
+                try {
+                    $result = $driver->add(array('firstname' => $member, 'email' => $member));
+                    $group->addMember($result, $import_source);
+                    $cli->message('  Added ' . $member, 'cli.success');
+                } catch (Turba_Exception $e) {
+                    $cli->message('  ' . $e->getMessage(), 'cli.error');
                 }
             }
             $group->store();
         } else {
             // entry only contains one contact, import it
-            $contact = array('alias' => $entry[0],
-                             'firstname' => $entry[1],
-                             'lastname' => $entry[2],
-                             'email' => $entry[3],
-                             'notes' => $entry[4]);
-            $added = $driver->add($contact);
-            if (is_a($added, 'PEAR_Error')) {
-                $cli->message('  ' . $added->getMessage(), 'cli.error');
-            } else {
+            $contact = array(
+                'alias' => $entry[0],
+                'firstname' => $entry[1],
+                'lastname' => $entry[2],
+                'email' => $entry[3],
+                'notes' => $entry[4]
+            );
+
+            try {
+                $driver->add($contact);
                 $cli->message('  Added ' . $entry[3], 'cli.success');
+            } catch (Turba_Exception $e) {
+                $cli->message('  ' . $e->getMessage(), 'cli.error');
             }
         }
     }
index 0cedbd5..8f8db05 100755 (executable)
@@ -35,7 +35,7 @@ if ($db instanceof PEAR_Error) {
 
 // Loop through SquirrelMail address books.
 $handle = $db->query('SELECT owner, nickname, firstname, lastname, email, label FROM address ORDER BY owner');
-if (is_a($handle, 'PEAR_Error')) {
+if ($handle instanceof PEAR_Error) {
     $cli->fatal($handle->toString());
 }
 $turba_shares = $GLOBALS['injector']->getInstance('Horde_Share')->getScope();
@@ -115,29 +115,30 @@ while ($row = $handle->fetchRow(DB_FETCHMODE_ASSOC)) {
         $group = new Turba_Object_Group($driver, array_merge($attributes, array('__key' => $gid)));
         $count++;
         foreach ($members as $member) {
-            $result = $driver->add(array('firstname' => $member, 'email' => $member));
-            if ($result && !is_a($result, 'PEAR_Error')) {
-                $added = $group->addMember($result, $import_source);
-                if (is_a($added, 'PEAR_Error')) {
-                    $cli->message('  ' . $added->getMessage(), 'cli.error');
-                } else {
-                    $count++;
-                }
+            try {
+                $result = $driver->add(array('firstname' => $member, 'email' => $member));
+                $group->addMember($result, $import_source);
+                ++$count;
+            } catch (Turba_Exception $e) {
+                $cli->message('  ' . $e->getMessage(), 'cli.error');
             }
         }
         $group->store();
     } else {
         // Entry only contains one contact, import it.
-        $contact = array('alias' => $row['nickname'],
-                         'firstname' => $row['firstname'],
-                         'lastname' => $row['lastname'],
-                         'email' => $row['email'],
-                         'notes' => $row['label']);
-        $added = $driver->add($contact);
-        if (is_a($added, 'PEAR_Error')) {
-            $cli->message('  ' . $added->getMessage(), 'cli.error');
-        } else {
-            $count++;
+        $contact = array(
+            'alias' => $row['nickname'],
+            'firstname' => $row['firstname'],
+            'lastname' => $row['lastname'],
+            'email' => $row['email'],
+            'notes' => $row['label']
+        );
+
+        try {
+            $driver->add($contact);
+            ++$count;
+        } catch (Turba_Exception $e) {
+            $cli->message('  ' . $e->getMessage(), 'cli.error');
         }
     }
 }
index c7fc44d..f2c666e 100755 (executable)
@@ -35,11 +35,7 @@ if (empty($vcard)) {
 }
 
 // Import data.
-$result = $registry->call('contacts/import',
-                          array($vcard, 'text/x-vcard', $source));
-if (is_a($result, 'PEAR_Error')) {
-    $cli->fatal($result->toString());
-}
+$result = $registry->call('contacts/import', array($vcard, 'text/x-vcard', $source));
 
 $cli->message('Imported successfully ' . count($result) . ' contacts', 'cli.success');
 
index 10b1645..56ccb47 100755 (executable)
@@ -112,7 +112,7 @@ foreach ($queries as $query) {
     }
     if ($for_real) {
         $results = $db->query($query);
-        if (is_a($results, 'PEAR_Error')) {
+        if ($results instanceof PEAR_Error) {
             $cli->message($results->toString(), 'cli.error');
             $error = true;
             continue;
@@ -130,7 +130,7 @@ if ($do_name) {
     require_once HORDE_BASE . '/turba/lib/Turba.php';
     $sql = 'SELECT object_id, ' . ($for_real ? 'object_lastname' : 'object_name') . ' FROM ' . $db_table;
     $names = $db->getAssoc($sql);
-    if (is_a($names, 'PEAR_Error')) {
+    if ($names instanceof PEAR_Error) {
         $cli->message($names->toString(), 'cli.error');
         exit(1);
     }
@@ -161,7 +161,7 @@ if ($do_name) {
 if ($do_home) {
     $sql = 'SELECT object_id, ' . ($for_real ? 'object_homestreet' : 'object_homeaddress') . ' FROM ' . $db_table;
     $addresses = $db->getAssoc($sql);
-    if (is_a($addresses, 'PEAR_Error')) {
+    if ($addresses instanceof PEAR_Error) {
         $cli->message($addresses->toString(), 'cli.error');
         exit(1);
     }
@@ -179,7 +179,7 @@ if ($do_home) {
 if ($do_work) {
     $sql = 'SELECT object_id, ' . ($for_real ? 'object_workstreet' : 'object_workaddress') . ' FROM ' . $db_table;
     $addresses = $db->getAssoc($sql);
-    if (is_a($addresses, 'PEAR_Error')) {
+    if ($addresses instanceof PEAR_Error) {
         $cli->message($addresses->toString(), 'cli.error');
         exit(1);
     }
@@ -197,7 +197,7 @@ if ($do_work) {
 if ($do_email) {
     $sql = 'SELECT object_id, object_email FROM ' . $db_table;
     $emails = $db->getAssoc($sql);
-    if (is_a($emails, 'PEAR_Error')) {
+    if ($emails instanceof PEAR_Error) {
         $cli->message($emails->toString(), 'cli.error');
         exit(1);
     }
index b42fece..334dd6b 100755 (executable)
@@ -21,7 +21,7 @@ $db = $datatree->_db;
 // Get the root vbook element.
 $sql = "SELECT datatree_id FROM horde_datatree WHERE group_uid = 'horde.shares.turba' AND datatree_name = 'vbook'";
 $vbook_parent = $db->getOne($sql);
-if (is_a($vbook_parent, 'PEAR_Error')) {
+if ($vbook_parent instanceof PEAR_Error) {
     var_dump($vbook_parent);
     exit(1);
 }
@@ -30,7 +30,7 @@ $vbook_parent = (int)$vbook_parent;
 // Get child vbooks.
 $sql = "SELECT datatree_id FROM horde_datatree WHERE group_uid = 'horde.shares.turba' AND (datatree_parents = ':$vbook_parent' OR datatree_parents LIKE ':$vbook_parent:%')";
 $vbook_children = $db->getCol($sql);
-if (is_a($vbook_children, 'PEAR_Error')) {
+if ($vbook_children instanceof PEAR_Error) {
     var_dump($vbook_children);
     exit(1);
 }
index 7736496..05e0803 100755 (executable)
@@ -32,7 +32,7 @@ if ($answer != 'y') {
 
 /* Get the share entries */
 $shares_result = $db->query('SELECT datatree_id, datatree_name FROM horde_datatree WHERE group_uid = \'horde.shares.turba\'');
-if (is_a($shares_result, 'PEAR_Error')) {
+if ($shares_result instanceof PEAR_Error) {
     die($shares_result->toString());
 }
 
@@ -43,7 +43,7 @@ while ($row = $shares_result->fetchRow(MDB2_FETCHMODE_ASSOC)) {
 
     /* Build an array to hold the new row data */
     $nextId = $db->nextId('turba_shares');
-    if (is_a($nextId, 'PEAR_Error')) {
+    if ($nextId instanceof PEAR_Error) {
         $cli->message($nextId->toString(), 'cli.error');
         $error_cnt++;
         continue;
@@ -111,14 +111,14 @@ while ($row = $shares_result->fetchRow(MDB2_FETCHMODE_ASSOC)) {
     $error = false;
     $db->beginTransaction();
     $result = insertData('turba_shares', $data);
-    if (is_a($result, 'PEAR_Error')) {
+    if ($result instanceof PEAR_Error) {
         $cli->message($result->toString(), 'cli.error');
         $error = true;
     }
     if (count($groups)) {
         foreach ($groups as $group) {
             $result = insertData('turba_shares_groups', $group);
-            if (is_a($result, 'PEAR_Error')) {
+            if ($result instanceof PEAR_Error) {
                 $cli->message($result->toString(), 'cli.error');
                 $error = true;
             }
@@ -127,7 +127,7 @@ while ($row = $shares_result->fetchRow(MDB2_FETCHMODE_ASSOC)) {
     if (count($users)) {
         foreach ($users as $user) {
             $result = insertData('turba_shares_users', $user);
-            if (is_a($result, 'PEAR_Error')) {
+            if ($result instanceof PEAR_Error) {
                 $cli->message($result->toString(), 'cli.error');
                 $error = true;
             }
@@ -138,12 +138,12 @@ while ($row = $shares_result->fetchRow(MDB2_FETCHMODE_ASSOC)) {
     if ($delete_dt_data && !$error) {
         $cli->message('DELETING datatree data for share_id: ' . $share_id, 'cli.message');
         $delete = $db->prepare('DELETE FROM horde_datatree_attributes WHERE datatree_id = ?', null, MDB2_PREPARE_MANIP);
-        if (is_a($delete, 'PEAR_Error')) {
+        if ($delete instanceof PEAR_Error) {
             $cli->message($delete->toString(), 'cli.error');
             $error = true;
         } else {
             $delete_result = $delete->execute(array($share_id));
-            if (is_a($delete_result, 'PEAR_Error')) {
+            if ($delete_result instanceof PEAR_Error) {
                 $cli->message($delete_result->toString(), 'cli.error');
                 $error = true;
             }
@@ -151,12 +151,12 @@ while ($row = $shares_result->fetchRow(MDB2_FETCHMODE_ASSOC)) {
         $delete->free();
 
         $delete = $db->prepare('DELETE FROM horde_datatree WHERE datatree_id = ?', null, MDB2_PREPARE_MANIP);
-        if (is_a($delete, 'PEAR_Error')) {
+        if ($delete instanceof PEAR_Error) {
             $cli->message($delete->toString(), 'cli.error');
             $error = true;
         } else {
             $delete_result = $delete->execute(array($share_id));
-            if (is_a($delete_result, 'PEAR_Error')) {
+            if ($delete_result instanceof PEAR_Error) {
                 $cli->message($delete_result->toString(), 'cli.error');
                 $error = true;
             }
@@ -191,7 +191,7 @@ function insertData($table, $data)
 
     $insert = $GLOBALS['db']->prepare('INSERT INTO ' . $table . ' (' . implode(', ', $fields) . ') VALUES (' . str_repeat('?, ', count($values) - 1) . '?)',
                                       null, MDB2_PREPARE_MANIP);
-    if (is_a($insert, 'PEAR_Error')) {
+    if ($insert instanceof PEAR_Error) {
         return $insert;
     }
     $insert_result = $insert->execute($values);
index 8ab075f..5be8a75 100755 (executable)
@@ -67,11 +67,7 @@ if ($share instanceof Horde_Share_Exception) {
 $share->set('owner', $owner);
 $share->set('name', $title);
 $share->set('perm_default', Horde_Perms::SHOW | Horde_Perms::READ);
-$result = $turba_shares->addShare($share);
-if (is_a($result, 'PEAR_Error')) {
-    var_dump($result);
-    exit;
-}
+$turba_shares->addShare($share);
 $share->save();
 $CLI->message('Created new Horde_Share object for the shared address book.', 'cli.success');
 
@@ -79,9 +75,6 @@ $CLI->message('Created new Horde_Share object for the shared address book.', 'cl
 $driver = $injector->getInstance('Turba_Driver')->getDriver($sourceKey);
 
 $db = &$driver->_db;
-if (is_a($db, 'PEAR_Error')) {
-    var_dump($db);
-}
 
 // Get the tablename in case we aren't using horde defaults.
 $tableName = $db->dsn['table'];
@@ -90,7 +83,7 @@ $count = $db->getOne($SQL);
 $CLI->message("Moving $count contacts to $title.", 'cli.message');
 $SQL = 'UPDATE ' . $tableName . ' SET owner_id=\'' . $owner_uid . '\';';
 $result = $db->query($SQL);
-if (is_a($result, 'PEAR_Error')) {
+if ($result instanceof PEAR_Error) {
     var_dump($result);
     exit;
 }
@@ -101,19 +94,19 @@ if ($prefDriver == 'sql') {
     if ($autoAppend) {
         $SQL = 'SELECT pref_uid, pref_value FROM horde_prefs WHERE pref_scope=\'turba\' AND pref_name=\'addressbooks\';';
         $results = $db->getAll($SQL);
-        if (is_a($results, 'PEAR_Error')) {
+        if ($results instanceof PEAR_Error) {
            $CLI->message('There was an error updating the user preferences: ' . $results->getMessage(), 'cli.error');
         } else {
             foreach ($results as $row) {
                 $newValue = $row[1] . "\n$sourceKey:$owner_uid";
                 $SQL = 'UPDATE horde_prefs SET pref_value=\'' . $newValue . '\' WHERE pref_uid=\'' . $row[0] . '\' AND pref_scope=\'turba\' AND pref_name=\'addressbooks\';';
                 $result = $db->query($SQL);
-                if (is_a($result, 'PEAR_Error')) {
+                if ($result instanceof PEAR_Error) {
                     $CLI->message('Could not update preferences for ' . $row[0] . ': ' . $result->getMessage(), 'cli.error');
                 }
             }
         }
-        if (!is_a($results, 'PEAR_Error')) {
+        if (!($results instanceof PEAR_Error)) {
             $CLI->message('Successfully added new shared address book to the user preferences.', 'cli.success');
         }
     }
index 1c869cc..4793a52 100644 (file)
@@ -162,23 +162,27 @@ if ($driver) {
             } catch (Exception $e) {
                 $notification->push($e);
             }
-        } elseif (($_SESSION['turba']['search_mode'] == 'basic' &&
-             is_object($results = $driver->search(array($criteria => $val)))) ||
-            ($_SESSION['turba']['search_mode'] == 'advanced' &&
-             is_object($results = $driver->search($criteria)))) {
-            if (is_a($results, 'PEAR_Error')) {
-                $notification->push($results, 'horde.error');
-            } else {
-                /* Read the columns to display from the preferences. */
-                $sources = Turba::getColumns();
-                $columns = isset($sources[$source]) ? $sources[$source] : array();
-                $results->sort(Turba::getPreferredSortOrder());
+        } else {
+            try {
+                if ((($_SESSION['turba']['search_mode'] == 'basic') &&
+                     ($results = $driver->search(array($criteria => $val)))) ||
+                    (($_SESSION['turba']['search_mode'] == 'advanced') &&
+                     ($results = $driver->search($criteria)))) {
+                    /* Read the columns to display from the preferences. */
+                    $sources = Turba::getColumns();
+                    $columns = isset($sources[$source])
+                        ? $sources[$source]
+                        : array();
+                    $results->sort(Turba::getPreferredSortOrder());
 
-                $view = new Turba_View_List($results, null, $columns);
-                $view->setType('search');
+                    $view = new Turba_View_List($results, null, $columns);
+                    $view->setType('search');
+                } else {
+                    $notification->push(_("Failed to search the address book"), 'horde.error');
+                }
+            } catch (Turba_Exception $e) {
+                $notification->push($results, 'horde.error');
             }
-        } else {
-            $notification->push(_("Failed to search the address book"), 'horde.error');
         }
     }
 }
index 745268c..7d8f4bc 100644 (file)
@@ -22,10 +22,10 @@ if (!isset($cfgSources[$source])) {
 $driver = $injector->getInstance('Turba_Driver')->getDriver($source);
 
 /* Set the contact from the key requested. */
-$key = Horde_Util::getFormData('key');
-$object = $driver->getObject($key);
-if (is_a($object, 'PEAR_Error')) {
-    $notification->push($object->getMessage(), 'horde.error');
+try {
+    $object = $driver->getObject(Horde_Util::getFormData('key'));
+} catch (Turba_Exception $e) {
+    $notification->push($e, 'horde.error');
     Horde::applicationUrl($prefs->getValue('initial_page'), true)->redirect();
 }
 
index 51f039b..8f1c957 100644 (file)
@@ -30,9 +30,6 @@ if (!isset($cfgSources[$source])) {
 
 $driver = $injector->getInstance('Turba_Driver')->getDriver($source);
 $object = $driver->getObject($key);
-if (is_a($object, 'PEAR_Error')) {
-    throw new Turba_Exception($object);
-}
 
 /* Check permissions. */
 if (!$object->hasPermission(Horde_Perms::READ)) {