Mainly, it is PHP 5-ifying classes and getting rid of PEAR_Errors.
// 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');
// 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');
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) {
//
// 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) {}
// }
// }
// }
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;
$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();
}
}
}
/* 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;
}
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();
$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();
}
}
}
} 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');
}
}
}
/* 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."),
}
}
$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;
}
$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';
}
$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();
}
}
$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();
$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();
}
/* 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);
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) {}
}
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) {}
}
}
$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] . '/';
$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);
$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');
// 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]);
}
/**
$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) {
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']);
// 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');
}
/**
}
$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) {
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
+ );
}
/**
// 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;
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."));
$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) {
$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();
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;
}
/**
- * 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()
{
*
* @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 = '')
{
*
* @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())
{
* @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)
array($GLOBALS['conf']['client']['addressbook']),
array($GLOBALS['conf']['client']['addressbook'] => $fields),
$matchBegin,
- true);
+ true
+ );
}
/**
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)) {
$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)) {
} else {
return $driver->add(array('email' => $address, 'name' => $name, $field => $value, '__owner' => $GLOBALS['registry']->getAuth()));
}
-
- return;
}
/**
} elseif (empty($result)) {
throw new Turba_Exception(sprintf(_("No %s entry found for %s"), $field, $address));
}
+
return reset($result);
}
if (!$success) {
throw new Turba_Exception(sprintf(_("No %s entry found for %s"), $field, $address));
}
-
- return;
}
}
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');
}
}
}
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;
}
}
*
* @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();
* 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
*
* @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
*
* @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
*
* @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
*
* @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.
* @param array $params Hash containing additional configuration
* parameters.
*/
- function Turba_Driver($params)
+ public function __construct($params = array())
{
$this->_params = $params;
}
*
* @return array Hash containing the driver's additional parameters.
*/
- function getParams()
+ public function getParams()
{
return $this->_params;
}
*
* @return boolean Supported or not.
*/
- function hasCapability($capability)
+ public function hasCapability($capability)
{
return !empty($this->_capabilities[$capability]);
}
*
* @return array List of blob attributes in the array keys.
*/
- function getBlobs()
+ public function getBlobs()
{
global $attributes;
*
* @return array Translated version of $hash.
*/
- function toDriverKeys($hash)
+ public function toDriverKeys($hash)
{
/* Handle category. */
if (!empty($hash['category'])) {
// 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;
}
}
}
- 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();
} 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']);
*
* @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])) {
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 == '"') {
if ($lastChar == '"') {
$temp .= ' ' . substr($parts[$i + 1], 0, -1);
$done = true;
- $i++;
} else {
$temp .= ' ' . $parts[$i + 1];
- $i++;
}
+ ++$i;
}
$search_terms[] = $temp;
} else {
$search_terms[0] = $val;
$glue = 'OR';
}
+
foreach ($this->map[$key]['fields'] as $field) {
$field = $this->toDriver($field);
if (!empty($strict[$field])) {
/* 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',
}
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();
}
/**
*
* @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];
}
/**
*
* @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;
}
* @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. */
/* 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);
}
/**
* 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()
* @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. */
$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;
$list->insert(new Turba_Object($this, $object));
}
}
+
$list->sort($sort_order);
+
/* Return the filtered (sorted) results. */
return $list;
}
* @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();
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;
}
'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;
* @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);
}
* @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'));
}
/**
* @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();
$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;
* @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;
*
* @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'])) {
$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 {
/**
* 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;
}
* 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)) {
/**
* 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()
+ {
}
/**
* @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')) {
Horde::logMessage($e, 'ERR');
}
}
+
return $object_id;
}
*
* @return array An array containing the criteria.
*/
- function getCriteria()
+ public function getCriteria()
{
$criteria = $this->map;
unset($criteria['__key']);
+
return $criteria;
}
*
* @return array The field list.
*/
- function getFields()
+ public function getFields()
{
return array_flip($this->fields);
}
* 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)) {
$vcard->setAttribute('FN', $val, Horde_Mime::is8bit($val) ? $charset : array());
$formattedname = true;
break;
+
case 'nickname':
case 'alias':
if ($fields && !isset($fields['NICKNAME'])) {
$vcard->setAttribute('LABEL', $val, array('TYPE' => 'HOME'));
}
break;
+
case 'workAddress':
if ($fields &&
(!isset($fields['LABEL']) ||
$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']) ||
$vcard->setAttribute('TEL', $val, array('TYPE' => 'HOME'));
}
break;
+
case 'workPhone':
if ($fields &&
(!isset($fields['TEL']) ||
$vcard->setAttribute('TEL', $val, array('TYPE' => 'WORK'));
}
break;
+
case 'cellPhone':
if ($fields &&
(!isset($fields['TEL']) ||
$vcard->setAttribute('TEL', $val, array('TYPE' => 'CELL'));
}
break;
+
case 'homeCellPhone':
$parameters = array();
if ($fields) {
}
$vcard->setAttribute('TEL', $val, $parameters);
break;
+
case 'workCellPhone':
$parameters = array();
if ($fields) {
$vcard->setAttribute('TEL', $val, array('TYPE' => 'VIDEO'));
}
break;
+
case 'homeVideoCall':
$parameters = array();
if ($fields) {
}
$vcard->setAttribute('TEL', $val, $parameters);
break;
+
case 'workVideoCall':
$parameters = array();
if ($fields) {
$vcard->setAttribute('X-SIP', $val, array('TYPE' => 'POC'));
}
break;
+
case 'voip':
if ($fields &&
(!isset($fields['X-SIP']) ||
$vcard->setAttribute('X-SIP', $val, array('TYPE' => 'VOIP'));
}
break;
+
case 'shareView':
if ($fields &&
(!isset($fields['X-SIP']) ||
$vcard->setAttribute('TEL', $val, array('TYPE' => 'FAX'));
}
break;
+
case 'homeFax':
$parameters = array();
if ($fields) {
}
$vcard->setAttribute('TEL', $val, $parameters);
break;
+
case 'workFax':
$parameters = array();
if ($fields) {
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']) ||
array('TYPE' => 'HOME'));
}
break;
+
case 'workEmail':
if ($fields &&
(!isset($fields['EMAIL']) ||
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;
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':
}
$vcard->setAttribute('URL', $val);
break;
+
case 'homeWebsite':
if ($fields &&
(!isset($fields['URL']) ||
$vcard->setAttribute('URL', $val, array('TYPE' => 'HOME'));
}
break;
+
case 'workWebsite':
if ($fields &&
(!isset($fields['URL']) ||
'longitude' => $hash['longitude']));
}
break;
+
case 'homeLatitude':
if ($fields &&
(!isset($fields['GEO']) ||
}
}
break;
+
case 'workLatitude':
if ($fields &&
(!isset($fields['GEO']) ||
*
* @return array A Turba attribute hash.
*/
- function toHash(Horde_Icalendar_Vcard $vcard)
+ public function toHash(Horde_Icalendar_Vcard $vcard)
{
$hash = array();
$attr = $vcard->getAllAttributes();
$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;
$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;
case 'company':
$message->companyname = Horde_String::convertCharset($value, $charset, 'utf-8');
break;
+
case 'departnemt':
$message->department = Horde_String::convertCharset($value, $charset, 'utf-8');
break;
$message->bodysize = strlen($message->body);
$message->bodytruncated = false;
break;
+
case 'website':
$message->webpage = $value;
break;
}
/**
- * 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)
{
} elseif (!$message->isGhosted('businesscountry')) {
$hash['workCountry'] = null;
}
+
return $hash;
}
*
* @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;
}
*
* @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();
}
*
* @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);
}
*
* @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());
}
/**
}
/* Store name and title. */
- $driver->name = $name;
+ $driver->_name = $name;
$driver->title = $config['title'];
/* Initialize */
* @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."));
}
/**
* @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."));
}
/**
*
* @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'])) {
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;
* 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;
/**
*
* @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;
}
}
* @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']);
$results[$key] = $contact;
}
}
+
return $results;
}
* @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 ('
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'])) {
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);
}
* 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
{
*
* @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;
}
}
* @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) {
$results[$key] = $contact;
}
}
+
return $results;
}
* @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];
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) {
* 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
{
*
* @return boolean True if the user has permission, otherwise false.
*/
- function hasPermission($perm)
+ public function hasPermission($perm)
{
switch ($perm) {
case Horde_Perms::EDIT:
* @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) {
$results[$key] = $contact;
}
}
+
return $results;
}
* @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();
return $results;
}
- function _getAddressBook()
+ /**
+ * TODO
+ */
+ protected function _getAddressBook()
{
$groups = Horde_Group::singleton();
$members = $groups->listAllUsers($this->_gid);
// 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')
+ );
}
}
/**
* 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
{
*
* @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
);
/**
* 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)
{
*
* @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');
}
}
$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);
}
* 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]];
}
}
}
$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
// 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']);
}
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);
+ }
}
/**
* @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());
$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;
}
/**
*
* @return string A unique ID for the new object.
*/
- function _makeKey($attributes)
+ protected function _makeKey($attributes)
{
return $attributes['fullname'];
}
* 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];
}
*
* @return array Array containing contact names that match $criteria.
*/
- function _doSearch($criteria, $glue)
+ protected function _doSearch($criteria, $glue)
{
$results = array();
$names = array();
}
}
- 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);
}
/**
$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) {
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));
*
* @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;
}
}
*
* @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);
}
*
* @return boolean true if user has permission, false otherwise.
*/
- function hasPermission($perm)
+ public function hasPermission($perm)
{
return $this->_perms & $perm;
}
*
* @return integer Horde Permissions bitmask.
*/
- function _aclToHordePerms($acl)
+ protected function _aclToHordePerms($acl)
{
$hPerms = 0;
+
if (strpos($acl, 'w') !== false) {
$hPerms |= Horde_Perms::EDIT;
}
if (strpos($acl, 'l') !== false) {
$hPerms |= Horde_Perms::SHOW;
}
+
return $hPerms;
}
*
* @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'];
}
* 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'])) {
* 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
{
*
* @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,
);
{
$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);
}
/**
*
* @return Hash containing the search results.
*/
- function _search($criteria, $fields)
+ protected function _search($criteria, $fields)
{
return $this->_wrapper->_search($criteria, $fields);
}
*
* @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);
}
/**
* 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;
}
/**
* 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);
}
*
* @return boolean True if the operation worked.
*/
- function _deleteAll($sourceName = null)
+ protected function _deleteAll($sourceName = null)
{
return $this->_wrapper->_deleteAll($sourceName);
}
*
* @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());
*
* @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();
}
/**
*
* @return string A unique ID for the new object.
*/
- function generateUID()
+ public function generateUID()
{
return method_exists($this->_wrapper, 'generateUID')
? $this->_wrapper->generateUID()
}
/**
- * 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;
- }
}
--- /dev/null
+<?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;
+ }
+
+}
--- /dev/null
+<?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;
+ }
+
+}
--- /dev/null
+<?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;
+ }
+
+}
/**
* 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
{
*
* @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);
}
/**
* @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."));
}
/**
- * 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'])) {
($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,");
}
* 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 = '';
/* 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);
* @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') {
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);
* 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. */
} else {
$i = 0;
foreach ($this->_params['objectclass'] as $objectclass) {
- $attributes['objectclass'][$i] = $objectclass;
- $i++;
+ $attributes['objectclass'][$i++] = $objectclass;
}
}
* 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])) {
$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)));
}
}
* 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());
/* 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']));
}
}
$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]);
}
$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;
}
/**
*
* @return string The RDN for the new object.
*/
- function _makeRDN($attributes)
+ protected function _makeRDN($attributes)
{
if (!is_array($this->_params['dn'])) {
return '';
$pairs[] = array($param, $attributes[$param]);
}
}
+
return Horde_Ldap::quoteDN($pairs);
}
*
* @return string The DN for the new object.
*/
- function _makeKey($attributes)
+ protected function _makeKey($attributes)
{
return $this->_makeRDN($attributes) . ',' . $this->_params['root'];
}
*
* @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) . ')';
* @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();
/**
* 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. */
*
* @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'] . ')';
$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') {
/**
* 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);
* 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];
/**
* 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;
}
}
* 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
{
*
* @return array Hash containing the search results.
*/
- function _search($criteria, $fields)
+ protected function _search($criteria, $fields)
{
return array_values($this->_getAddressBook());
}
*
* @return Hash containing the search results.
*/
- function _read($criteria, $ids, $fields)
+ protected function _read($criteria, $ids, $fields)
{
$book = $this->_getAddressBook();
$results = array();
/**
* 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)
{
$this->_setAddressBook($book);
}
- function _getAddressBook()
+ /**
+ * TODO
+ *
+ * @return TODO
+ */
+ protected function _getAddressBook()
{
global $prefs;
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));
* 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
{
*
* @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.
*
* @return boolean Supported or not.
*/
- function hasCapability($capability)
+ public function hasCapability($capability)
{
return $this->_driver->hasCapability($capability);
}
*
* @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);
}
*
* @string Address book name
*/
- function getName()
+ public function getName()
{
$share_parts = explode(':', $this->_share->getName());
return array_pop($share_parts);
* 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."));
}
/**
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']);
}
/**
* @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);
}
* @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);
}
}
* 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
{
*
* @var array
*/
- var $_capabilities = array(
- 'delete_all' => true,
- 'delete_addressbook' => true
+ protected $_capabilities = array(
+ 'delete_addressbook' => true,
+ 'delete_all' => true
);
/**
*
* @var DB
*/
- var $_db;
+ protected $_db;
/**
* Handle for the current database connection, used for writing. Defaults
*
* @var DB
*/
- var $_write_db;
+ protected $_write_db;
+
+ /**
+ * count() cache.
+ *
+ * @var array
+ */
+ protected $_countCache = array();
/**
* @throws Turba_Exception
*
* @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') . ' = ?';
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];
}
/**
* 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 = '';
/* 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);
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;
}
}
$entry = 'a1.' . $entry . ' IS NOT NULL AND a1.' . $entry . ' <> \'\'';
}
+
return $array;
}
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;
}
* @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();
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();
case 'mssql':
$entry[$field] = pack('H' . strlen($row[$i]), $row[$i]);
break;
+
default:
$entry[$field] = $row[$i];
break;
/**
* 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) {
case 'pgsql':
$values[] = bin2hex($value);
break;
+
default:
$values[] = $value;
+ break;
}
} else {
$values[] = $this->_convertToDriver($value);
. ' 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;
}
/**
* 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 . ' = ?';
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 */
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 */
} 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)
{
case 'pgsql':
$values[] = bin2hex($value);
break;
+
default:
$values[] = $value;
+ break;
}
} else {
$values[] = $this->_convertToDriver($value);
$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;
*
* @return string A unique ID for the new object.
*/
- function _makeKey($attributes)
+ protected function _makeKey($attributes)
{
return strval(new Horde_Support_Randomid());
}
* @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();
*
* @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']);
}
*
* @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']);
}
*
* @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);
}
/**
* @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(
// 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);
} 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 ('
'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);
}
}
- $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));
}
}
* 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
{
*
* @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
*
* @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()
$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()
* @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
*
* @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);
}
*
* @return boolean True or False.
*/
- function hasPermission($perm)
+ public function hasPermission($perm)
{
return $this->_driver->hasPermission($perm);
}
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');
/* 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');
}
}
}
$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.
{
$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;
}
}
}
}
- $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;
}
}
function execute()
{
$result = parent::execute();
- if (is_a($result, 'PEAR_Error')) {
+ if ($result instanvceof PEAR_Error) {
return $result;
}
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();
/**
* Perform all functions for this task.
*
- * @return mixed True | PEAR_Error
+ * @return boolean Success.
*/
public function execute()
{
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')
));
$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>';
'" 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>';
/**
* 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));
}
/**
$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)) {
$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;
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;
{
// 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)) {
Horde::logMessage($e, 'ERR');
return array();
}
+
return $sources;
}
* @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 */
}
$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);
}
$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) {
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 {
}
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;
}
// 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');
}
$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 {
}
// 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;
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.
$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');
}
}
}
function getTitle()
{
- if (!$this->contact || is_a($this->contact, 'PEAR_Error')) {
+ if (!$this->contact) {
return _("Not Found");
}
return $this->contact->getValue('name');
{
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;
}
/* 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();
}
}
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'));
{
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;
}
<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>
$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');
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'));
{
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;
}
'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');
}
}
}
$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();
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');
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>';
}
$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');
}
}
}
// 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();
$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');
}
}
}
}
// 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');
}
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;
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);
}
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);
}
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);
}
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);
}
// 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);
}
// 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);
}
/* 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());
}
/* 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;
$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;
}
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;
}
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;
}
$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;
}
$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);
$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');
$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'];
$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;
}
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');
}
}
} 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');
}
}
}
$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();
}
$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)) {