public function isValidSource($itemSource, $uidOwner) { // TODO: Cache address books. $app = new App($uidOwner); $userAddressBooks = $app->getAddressBooksForUser(); foreach ($userAddressBooks as $addressBook) { if ($addressBook->childExists($itemSource)) { return true; } } return false; }
/** * @brief Get a unique name of the item for the specified user * @param string Item * @param string|false User the item is being shared with * @param array|null List of similar item names already existing as shared items * @return string Target name * * This function needs to verify that the user does not already have an item with this name. * If it does generate a new name e.g. name_# */ public function generateTarget($itemSource, $shareWith, $exclude = null) { // Get app for the sharee $app = new App($shareWith); $backend = $app->getBackend('local'); // Get address book for the owner $addressBook = $this->app->getBackend('local')->getAddressBook($itemSource); $userAddressBooks = array(); foreach ($backend->getAddressBooksForUser() as $userAddressBook) { $userAddressBooks[] = $userAddressBook['displayname']; } $name = $addressBook['displayname'] . '(' . $addressBook['owner'] . ')'; $suffix = ''; while (in_array($name . $suffix, $userAddressBooks)) { $suffix++; } $suffix = $suffix ? ' ' . $suffix : ''; return $name . $suffix; }
/** * Store feeds into the Contacts * @param array $feed */ public static function parseFeed($feed) { $userid = \OCP\User::getUser(); foreach ($feed as $source) { $entry = Adapter::translateContact($source); if (isset($entry[self::CONTACT_GID]) && !empty($entry[self::CONTACT_GID])) { $oldContactId = self::findByGid($userid, $entry[self::CONTACT_GID]); if ($oldContactId) { //If exists and should not be updated - skip if (self::needUpdate($oldContactId)) { $vcard = self::toVcard($entry); \OCA\Contacts\VCard::edit($oldContactId, $vcard); } continue; } } $vcard = self::toVcard($entry); $bookid = self::getBookId($userid); \OCA\Contacts\VCard::add($bookid, $vcard); } \OCA\Contacts\App::getCategories(); }
/** * Get the backend for an address book * * @param mixed $addressbookid * @return array(string, \OCA\Contacts\Backend\AbstractBackend) */ public function getBackendForAddressBook($addressbookid) { list($backendName, $id) = explode('::', $addressbookid); $app = new Contacts\App(); $backend = $app->getBackend($backendName); if ($backend->name === $backendName && $backend->hasAddressBook($id)) { return array($id, $backend); } throw new \Sabre\DAV\Exception\NotFound('Backend not found: ' . $addressbookid); }
/** * @NoAdminRequired */ public function start() { $request = $this->request; $response = new JSONResponse(); $params = $this->request->urlParams; $app = new App($this->api->getUserId()); $addressBook = $app->getAddressBook($params['backend'], $params['addressBookId']); if (!$addressBook->hasPermission(\OCP\PERMISSION_CREATE)) { $response->setStatus('403'); $response->bailOut(App::$l10n->t('You do not have permissions to import into this address book.')); return $response; } $filename = isset($request->post['filename']) ? $request->post['filename'] : null; $progresskey = isset($request->post['progresskey']) ? $request->post['progresskey'] : null; if (is_null($filename)) { $response->bailOut(App::$l10n->t('File name missing from request.')); return $response; } if (is_null($progresskey)) { $response->bailOut(App::$l10n->t('Progress key missing from request.')); return $response; } $filename = strtr($filename, array('/' => '', "\\" => '')); if (\OC\Files\Filesystem::isFileBlacklisted($filename)) { $response->bailOut(App::$l10n->t('Attempt to access blacklisted file:') . $filename); return $response; } $view = \OCP\Files::getStorage('contacts'); $proxyStatus = \OC_FileProxy::$enabled; \OC_FileProxy::$enabled = false; $file = $view->file_get_contents('/imports/' . $filename); \OC_FileProxy::$enabled = $proxyStatus; $writeProgress = function ($pct) use($progresskey) { \OC_Cache::set($progresskey, $pct, 300); }; $cleanup = function () use($view, $filename, $progresskey) { if (!$view->unlink('/imports/' . $filename)) { $response->debug('Unable to unlink /imports/' . $filename); } \OC_Cache::remove($progresskey); }; $writeProgress('20'); $nl = "\n"; $file = str_replace(array("\r", "\n\n"), array("\n", "\n"), $file); $lines = explode($nl, $file); $inelement = false; $parts = array(); $card = array(); foreach ($lines as $line) { if (strtoupper(trim($line)) == 'BEGIN:VCARD') { $inelement = true; } elseif (strtoupper(trim($line)) == 'END:VCARD') { $card[] = $line; $parts[] = implode($nl, $card); $card = array(); $inelement = false; } if ($inelement === true && trim($line) != '') { $card[] = $line; } } if (count($parts) === 0) { $response->bailOut(App::$l10n->t('No contacts found in: ') . $filename); $cleanup(); return $response; } //import the contacts $imported = 0; $failed = 0; $partially = 0; $processed = 0; // TODO: Add a new group: "Imported at {date}" foreach ($parts as $part) { try { $vcard = VObject\Reader::read($part); } catch (VObject\ParseException $e) { try { $vcard = VObject\Reader::read($part, VObject\Reader::OPTION_IGNORE_INVALID_LINES); $partially += 1; $response->debug('Import: Retrying reading card. Error parsing VCard: ' . $e->getMessage()); } catch (\Exception $e) { $failed += 1; $response->debug('Import: skipping card. Error parsing VCard: ' . $e->getMessage()); continue; // Ditch cards that can't be parsed by Sabre. } } try { $vcard->validate(MyVCard::REPAIR | MyVCard::UPGRADE); } catch (\Exception $e) { \OCP\Util::writeLog('contacts', __METHOD__ . ' ' . 'Error validating vcard: ' . $e->getMessage(), \OCP\Util::ERROR); $failed += 1; } /** * TODO * - Check if a contact with identical UID exists. * - If so, fetch that contact and call $contact->mergeFromVCard($vcard); * - Increment $updated var (not present yet.) * - continue */ try { if ($addressBook->addChild($vcard)) { $imported += 1; } else { $failed += 1; } } catch (\Exception $e) { $response->debug('Error importing vcard: ' . $e->getMessage() . $nl . $vcard->serialize()); $failed += 1; } $processed += 1; $writeProgress($processed); } //done the import sleep(3); // Give client side a chance to read the progress. $response->setParams(array('backend' => $params['backend'], 'addressBookId' => $params['addressBookId'], 'imported' => $imported, 'partially' => $partially, 'failed' => $failed)); return $response; }
/** * @NoAdminRequired */ public function start() { $request = $this->request; $response = new JSONResponse(); $params = $this->request->urlParams; $app = new App(\OCP\User::getUser()); $addressBookId = $params['addressBookId']; $format = $params['importType']; $addressBook = $app->getAddressBook($params['backend'], $addressBookId); if (!$addressBook->hasPermission(\OCP\PERMISSION_CREATE)) { $response->setStatus('403'); $response->bailOut(App::$l10n->t('You do not have permissions to import into this address book.')); return $response; } $filename = isset($request->post['filename']) ? $request->post['filename'] : null; $progresskey = isset($request->post['progresskey']) ? $request->post['progresskey'] : null; if (is_null($filename)) { $response->bailOut(App::$l10n->t('File name missing from request.')); return $response; } if (is_null($progresskey)) { $response->bailOut(App::$l10n->t('Progress key missing from request.')); return $response; } $filename = strtr($filename, array('/' => '', "\\" => '')); if (\OC\Files\Filesystem::isFileBlacklisted($filename)) { $response->bailOut(App::$l10n->t('Attempt to access blacklisted file:') . $filename); return $response; } $view = \OCP\Files::getStorage('contacts'); $proxyStatus = \OC_FileProxy::$enabled; \OC_FileProxy::$enabled = false; $file = $view->file_get_contents('/imports/' . $filename); \OC_FileProxy::$enabled = $proxyStatus; $importManager = new ImportManager(); $formatList = $importManager->getTypes(); $found = false; $parts = array(); foreach ($formatList as $formatName => $formatDisplayName) { if ($formatName == $format) { $parts = $importManager->importFile($view->getLocalFile('/imports/' . $filename), $formatName); $found = true; } } if (!$found) { // detect file type $mostLikelyName = ""; $mostLikelyValue = 0; $probability = $importManager->detectFileType($view->getLocalFile('/imports/' . $filename)); foreach ($probability as $probName => $probValue) { if ($probValue > $mostLikelyValue) { $mostLikelyName = $probName; $mostLikelyValue = $probValue; } } if ($mostLikelyValue > 0) { // found one (most likely...) $parts = $importManager->importFile($view->getLocalFile('/imports/' . $filename), $mostLikelyName); } } if ($parts) { //import the contacts $imported = 0; $failed = 0; $processed = 0; $total = count($parts); foreach ($parts as $part) { /** * TODO * - Check if a contact with identical UID exists. * - If so, fetch that contact and call $contact->mergeFromVCard($part); * - Increment $updated var (not present yet.) * - continue */ try { $id = $addressBook->addChild($part); if ($id) { $imported++; $favourites = $part->select('X-FAVOURITES'); foreach ($favourites as $favourite) { if ($favourite->getValue() == 'yes') { $this->tagMgr->addToFavorites($id); } } } else { $failed++; } } catch (\Exception $e) { $response->debug('Error importing vcard: ' . $e->getMessage() . $nl . $part->serialize()); $failed++; } $processed++; $this->writeProcess($processed, $total, $progresskey); } } else { $imported = 0; $failed = 0; $processed = 0; $total = 0; } $this->cleanup($view, $filename, $progresskey, $response); //done the import sleep(3); // Give client side a chance to read the progress. $response->setParams(array('backend' => $params['backend'], 'addressBookId' => $params['addressBookId'], 'importType' => $params['importType'], 'imported' => $imported, 'count' => $processed, 'total' => $total, 'failed' => $failed)); return $response; }
} break; case 'EMAIL': case 'TEL': case 'IMPP': case 'URL': debug('Setting element: (EMAIL/TEL/ADR)' . $element); $property->setValue($value); break; default: $vcard->{$name} = $value; break; } setParameters($property, $parameters, true); // Do checksum and be happy if (in_array($name, $multi_properties)) { $checksum = substr(md5($property->serialize()), 0, 8); } } //debug('New checksum: '.$checksum); //$vcard->children[$line] = $property; ??? try { VCard::edit($id, $vcard); } catch (Exception $e) { bailOut($e->getMessage()); } if (in_array($name, $multi_properties)) { \OCP\JSON::success(array('data' => array('line' => $line, 'checksum' => $checksum, 'oldchecksum' => $_POST['checksum'], 'lastmodified' => App::lastModified($vcard)->format('U')))); } else { \OCP\JSON::success(array('data' => array('lastmodified' => App::lastModified($vcard)->format('U')))); }
public static function getBirthdayEvents($parameters) { //\OCP\Util::writeLog('contacts', __METHOD__.' parameters: '.print_r($parameters, true), \OCP\Util::DEBUG); $name = $parameters['calendar_id']; if (strpos($name, 'birthday_') != 0) { return; } $info = explode('_', $name); $backend = $info[1]; $aid = $info[2]; $app = new App(); $addressBook = $app->getAddressBook($backend, $aid); foreach ($addressBook->getBirthdayEvents() as $vevent) { $parameters['events'][] = array('id' => 0, 'vevent' => $vevent, 'repeating' => true, 'summary' => $vevent->SUMMARY, 'calendardata' => $vevent->serialize()); } }
/** * @brief deletes a card * @param integer $id id of card * @return boolean true on success, otherwise an exception will be thrown */ public static function delete($id) { $contact = self::find($id); if (!$contact) { \OCP\Util::writeLog('contacts', __METHOD__ . ', id: ' . $id . ' not found.', \OCP\Util::DEBUG); throw new \Exception(App::$l10n->t('Could not find the vCard with ID: ' . $id, 404)); } $addressbook = Addressbook::find($contact['addressbookid']); if (!$addressbook) { throw new \Exception(App::$l10n->t('Could not find the Addressbook with ID: ' . $contact['addressbookid'], 404)); } if ($addressbook['userid'] != \OCP\User::getUser() && !\OC_Group::inGroup(\OCP\User::getUser(), 'admin')) { \OCP\Util::writeLog('contacts', __METHOD__ . ', ' . $addressbook['userid'] . ' != ' . \OCP\User::getUser(), \OCP\Util::DEBUG); $sharedAddressbook = \OCP\Share::getItemSharedWithBySource('addressbook', $contact['addressbookid'], \OCP\Share::FORMAT_NONE, null, true); $sharedContact = \OCP\Share::getItemSharedWithBySource('contact', $id, \OCP\Share::FORMAT_NONE, null, true); $addressbook_permissions = 0; $contact_permissions = 0; if ($sharedAddressbook) { $addressbook_permissions = $sharedAddressbook['permissions']; } if ($sharedContact) { $contact_permissions = $sharedEvent['permissions']; } $permissions = max($addressbook_permissions, $contact_permissions); if (!($permissions & \OCP\PERMISSION_DELETE)) { throw new \Exception(App::$l10n->t('You do not have the permissions to delete this contact.', 403)); } } $aid = $contact['addressbookid']; \OC_Hook::emit('\\OCA\\Contacts\\VCard', 'pre_deleteVCard', array('aid' => null, 'id' => $id, 'uri' => null)); $stmt = \OCP\DB::prepare('DELETE FROM `*PREFIX*contacts_cards` WHERE `id` = ?'); try { $stmt->execute(array($id)); } catch (\Exception $e) { \OCP\Util::writeLog('contacts', __METHOD__ . ', exception: ' . $e->getMessage(), \OCP\Util::ERROR); \OCP\Util::writeLog('contacts', __METHOD__ . ', id: ' . $id, \OCP\Util::DEBUG); throw new \Exception(App::$l10n->t('There was an error deleting this contact.')); } App::updateDBProperties($id); App::getVCategories()->purgeObject($id); Addressbook::touch($addressbook['id']); \OCP\Share::unshareAll('contact', $id); return true; }
public static function cacheThumbnail($backendName, $addressBookId, $contactId, \OCP\Image $image = null, $vCard = null, $options = array()) { $cache = \OC::$server->getCache(); $key = self::THUMBNAIL_PREFIX . $backendName . '::' . $addressBookId . '::' . $contactId; //$cache->remove($key); $haskey = $cache->hasKey($key); if (!array_key_exists('remove', $options) && !array_key_exists('update', $options)) { if ($cache->hasKey($key) && $image === null) { return $cache->get($key); } } else { if (isset($options['remove']) && $options['remove'] === false && (isset($options['update']) && $options['update'] === false)) { return $cache->get($key); } } if (isset($options['remove']) && $options['remove']) { $cache->remove($key); if (!isset($options['update']) || !$options['update']) { return false; } } if (is_null($image)) { if (is_null($vCard)) { $app = new App(); $vCard = $app->getContact($backendName, $addressBookId, $contactId); } $image = new \OCP\Image(); if (!isset($vCard->PHOTO) || !$image->loadFromBase64((string) $vCard->PHOTO)) { return false; } } if (!$image->centerCrop()) { \OCP\Util::writeLog('contacts', __METHOD__ . '. Couldn\'t crop thumbnail for ID ' . $key, \OCP\Util::ERROR); return false; } if (!$image->resize(self::THUMBNAIL_SIZE)) { \OCP\Util::writeLog('contacts', __METHOD__ . '. Couldn\'t resize thumbnail for ID ' . $key, \OCP\Util::ERROR); return false; } // Cache as base64 for around a month $cache->set($key, strval($image), 3000000); return $cache->get($key); }
<?php /** * Copyright (c) 2013 Thomas Tanghus (thomas@tanghus.net) * This file is licensed under the Affero General Public License version 3 or * later. * See the COPYING-README file. */ namespace OCA\Contacts; use Sabre\VObject, OCP\AppFramework, OCA\Contacts\Controller\AddressBookController, OCA\Contacts\Controller\GroupController, OCA\Contacts\Controller\ContactController, OCA\Contacts\Controller\ContactPhotoController, OCA\Contacts\Controller\SettingsController, OCA\Contacts\Controller\ImportController; /** * This class manages our app actions */ App::$l10n = \OC_L10N::get('contacts'); class App { /** * @brief Categories of the user * @var OC_VCategories */ public static $categories = null; /** * @brief language object for calendar app * * @var OC_L10N */ public static $l10n; /** * An array holding the current users address books. * @var array
* @author Thomas Tanghus * @copyright 2013-2014 Thomas Tanghus (thomas@tanghus.net) * * This file is licensed under the Affero General Public License version 3 or * later. * See the COPYING-README file. */ namespace OCA\Contacts; use Sabre\VObject, OCP\AppFramework, OCA\Contacts\Controller\AddressBookController, OCA\Contacts\Controller\BackendController, OCA\Contacts\Controller\GroupController, OCA\Contacts\Controller\ContactController, OCA\Contacts\Controller\ContactPhotoController, OCA\Contacts\Controller\SettingsController, OCA\Contacts\Controller\ImportController; /** * This class manages our app actions * * TODO: Merge in Dispatcher */ App::$l10n = \OC::$server->getL10N('contacts'); class App { /** * @brief Categories of the user * @var OC_VCategories */ public static $categories = null; /** * @brief language object for calendar app * * @var \OCP\IL10N */ public static $l10n; /** * An array holding the current users address books.
/** * @param $properties * @return mixed */ public function createOrUpdate($properties) { $id = null; $vcard = null; if (array_key_exists('id', $properties)) { // TODO: test if $id belongs to this addressbook $id = $properties['id']; // TODO: Test $vcard $vcard = App::getContactVCard($properties['id']); foreach (array_keys($properties) as $name) { if (isset($vcard->{$name})) { unset($vcard->{$name}); } } } else { $vcard = \Sabre\VObject\Component::create('VCARD'); $uid = substr(md5(rand() . time()), 0, 10); $vcard->add('UID', $uid); try { $id = VCard::add($this->id, $vcard, null, true); } catch (Exception $e) { \OCP\Util::writeLog('contacts', __METHOD__ . ' ' . $e->getMessage(), \OCP\Util::ERROR); return false; } } foreach ($properties as $name => $value) { switch ($name) { case 'ADR': case 'N': if (is_array($value)) { $property = \Sabre\VObject\Property::create($name); $property->setParts($value); $vcard->add($property); } else { $vcard->{$name} = $value; } break; case 'BDAY': // TODO: try/catch $date = new \DateTime($value); $vcard->BDAY = $date->format('Y-m-d'); $vcard->BDAY->VALUE = 'DATE'; break; case 'EMAIL': case 'TEL': case 'IMPP': // NOTE: We don't know if it's GTalk, Jabber etc. only the protocol // NOTE: We don't know if it's GTalk, Jabber etc. only the protocol case 'URL': if (is_array($value)) { foreach ($value as $val) { $vcard->add($name, strip_tags($val)); } } else { $vcard->add($name, strip_tags($value)); } default: $vcard->{$name} = $value; break; } } try { VCard::edit($id, $vcard); } catch (Exception $e) { \OCP\Util::writeLog('contacts', __METHOD__ . ' ' . $e->getMessage(), \OCP\Util::ERROR); return false; } $asarray = VCard::structureContact($vcard); $asarray['id'] = $id; return $asarray; }
/** * @brief deletes a card with the data provided by sabredav * @param integer $aid Addressbook id * @param string $uri the uri of the card * @return boolean */ public static function deleteFromDAVData($aid, $uri) { $id = null; $addressbook = Addressbook::find($aid); if ($addressbook['userid'] != \OCP\User::getUser()) { $query = \OCP\DB::prepare('SELECT `id` FROM `*PREFIX*contacts_cards` WHERE `addressbookid` = ? AND `uri` = ?'); $id = $query->execute(array($aid, $uri))->fetchOne(); if (!$id) { return false; } $sharedContact = \OCP\Share::getItemSharedWithBySource('contact', $id, \OCP\Share::FORMAT_NONE, null, true); if (!$sharedContact || !($sharedContact['permissions'] & \OCP\PERMISSION_DELETE)) { return false; } } \OC_Hook::emit('\\OCA\\Contacts\\VCard', 'pre_deleteVCard', array('aid' => $aid, 'id' => null, 'uri' => $uri)); $stmt = \OCP\DB::prepare('DELETE FROM `*PREFIX*contacts_cards` WHERE `addressbookid` = ? AND `uri`=?'); try { $stmt->execute(array($aid, $uri)); } catch (\Exception $e) { \OCP\Util::writeLog('contacts', __METHOD__ . ', exception: ' . $e->getMessage(), \OCP\Util::ERROR); \OCP\Util::writeLog('contacts', __METHOD__ . ', aid: ' . $aid . ' uri: ' . $uri, \OCP\Util::DEBUG); return false; } Addressbook::touch($aid); if (!is_null($id)) { App::getVCategories()->purgeObject($id); App::updateDBProperties($id); \OCP\Share::unshareAll('contact', $id); } else { \OCP\Util::writeLog('contacts', __METHOD__ . ', Could not find id for ' . $uri, \OCP\Util::DEBUG); } return true; }
/** * Get a photo from the oC and crops it with the suplied geometry. * @NoAdminRequired * @NoCSRFRequired */ public function cropPhoto() { $params = $this->request->urlParams; $x = isset($this->request->post['x']) && $this->request->post['x'] ? $this->request->post['x'] : 0; $y = isset($this->request->post['y']) && $this->request->post['y'] ? $this->request->post['y'] : 0; $w = isset($this->request->post['w']) && $this->request->post['w'] ? $this->request->post['w'] : -1; $h = isset($this->request->post['h']) && $this->request->post['h'] ? $this->request->post['h'] : -1; $tmpkey = $params['key']; $maxSize = isset($this->request->post['maxSize']) ? $this->request->post['maxSize'] : 200; $app = new App($this->api->getUserId()); $addressBook = $app->getAddressBook($params['backend'], $params['addressBookId']); $contact = $addressBook->getChild($params['contactId']); $response = new JSONResponse(); if (!$contact) { return $response->bailOut(App::$l10n->t('Couldn\'t find contact.')); } $data = $this->server->getCache()->get($tmpkey); if (!$data) { return $response->bailOut(App::$l10n->t('Image has been removed from cache')); } $image = new \OCP\Image(); if (!$image->loadFromData($data)) { return $response->bailOut(App::$l10n->t('Error creating temporary image')); } $w = $w !== -1 ? $w : $image->width(); $h = $h !== -1 ? $h : $image->height(); if (!$image->crop($x, $y, $w, $h)) { return $response->bailOut(App::$l10n->t('Error cropping image')); } if ($image->width() < $maxSize || $image->height() < $maxSize) { if (!$image->resize(200)) { return $response->bailOut(App::$l10n->t('Error resizing image')); } } // For vCard 3.0 the type must be e.g. JPEG or PNG // For version 4.0 the full mimetype should be used. // https://tools.ietf.org/html/rfc2426#section-3.1.4 if (strval($contact->VERSION) === '4.0') { $type = $image->mimeType(); } else { $type = explode('/', $image->mimeType()); $type = strtoupper(array_pop($type)); } if (isset($contact->PHOTO)) { $property = $contact->PHOTO; if (!$property) { $this->server->getCache()->remove($tmpkey); return $response->bailOut(App::$l10n->t('Error getting PHOTO property.')); } $property->setValue(strval($image)); $property->parameters = array(); $property->parameters[] = new \Sabre\VObject\Parameter('ENCODING', 'b'); $property->parameters[] = new \Sabre\VObject\Parameter('TYPE', $image->mimeType()); $contact->PHOTO = $property; } else { $contact->add('PHOTO', strval($image), array('ENCODING' => 'b', 'TYPE' => $type)); // TODO: Fix this hack $contact->setSaved(false); } if (!$contact->save()) { return $response->bailOut(App::$l10n->t('Error saving contact.')); } $thumbnail = Properties::cacheThumbnail($params['backend'], $params['addressBookId'], $params['contactId'], $image); $response->setData(array('status' => 'success', 'data' => array('id' => $params['contactId'], 'thumbnail' => $thumbnail))); $this->server->getCache()->remove($tmpkey); return $response; }
\Sabre\VObject\Property::$classMap['ADR'] = '\\OC\\VObject\\CompoundProperty'; \Sabre\VObject\Property::$classMap['GEO'] = '\\OC\\VObject\\CompoundProperty'; \Sabre\VObject\Property::$classMap['ORG'] = '\\OC\\VObject\\CompoundProperty'; \OC::$server->getNavigationManager()->add(array('id' => 'contacts', 'order' => 10, 'href' => \OCP\Util::linkToRoute('contacts_index'), 'icon' => \OCP\Util::imagePath('contacts', 'contacts.svg'), 'name' => \OCP\Util::getL10N('contacts')->t('Contacts'))); $api = new API('contacts'); $api->connectHook('OC_User', 'post_createUser', '\\OCA\\Contacts\\Hooks', 'userCreated'); $api->connectHook('OC_User', 'post_deleteUser', '\\OCA\\Contacts\\Hooks', 'userDeleted'); $api->connectHook('OCA\\Contacts', 'pre_deleteAddressBook', '\\OCA\\Contacts\\Hooks', 'addressBookDeletion'); $api->connectHook('OCA\\Contacts', 'pre_deleteContact', '\\OCA\\Contacts\\Hooks', 'contactDeletion'); $api->connectHook('OCA\\Contacts', 'post_createContact', 'OCA\\Contacts\\Hooks', 'contactAdded'); $api->connectHook('OCA\\Contacts', 'post_updateContact', '\\OCA\\Contacts\\Hooks', 'contactUpdated'); $api->connectHook('OCA\\Contacts', 'scanCategories', '\\OCA\\Contacts\\Hooks', 'scanCategories'); $api->connectHook('OCA\\Contacts', 'indexProperties', '\\OCA\\Contacts\\Hooks', 'indexProperties'); $api->connectHook('OC_Calendar', 'getEvents', 'OCA\\Contacts\\Hooks', 'getBirthdayEvents'); $api->connectHook('OC_Calendar', 'getSources', 'OCA\\Contacts\\Hooks', 'getCalenderSources'); \OCP\Util::addscript('contacts', 'loader'); \OCP\Util::addscript('contacts', 'admin'); \OC_Search::registerProvider('OCA\\Contacts\\Search\\Provider'); //\OCP\Share::registerBackend('contact', 'OCA\Contacts\Share_Backend_Contact'); \OCP\Share::registerBackend('addressbook', 'OCA\\Contacts\\Share\\Addressbook', 'contact'); //\OCP\App::registerPersonal('contacts','personalsettings'); \OCP\App::registerAdmin('contacts', 'admin'); if (\OCP\User::isLoggedIn()) { $app = new App($api->getUserId()); $addressBooks = $app->getAddressBooksForUser(); foreach ($addressBooks as $addressBook) { if ($addressBook->isActive()) { \OCP\Contacts::registerAddressBook($addressBook->getSearchProvider()); } } }
public static function cacheThumbnail($backendName, $addressBookId, $contactId, \OCP\Image $image = null, $vCard = null, $options = array()) { $cache = \OC::$server->getCache(); $key = self::THUMBNAIL_PREFIX . $backendName . '::' . $addressBookId . '::' . $contactId; //$cache->remove($key); $haskey = $cache->hasKey($key); if (!array_key_exists('remove', $options) && !array_key_exists('update', $options)) { if ($cache->hasKey($key) && $image === null) { return $cache->get($key); } } else { if (isset($options['remove']) && $options['remove'] === false && (isset($options['update']) && $options['update'] === false)) { return $cache->get($key); } } if (isset($options['remove']) && $options['remove']) { $cache->remove($key); if (!isset($options['update']) || !$options['update']) { return false; } } if (is_null($image)) { if (is_null($vCard)) { $app = new App(); $vCard = $app->getContact($backendName, $addressBookId, $contactId); } if (!isset($vCard->PHOTO)) { return false; } $image = new \OCP\Image(); $photostring = (string) $vCard->PHOTO; if ($vCard->PHOTO instanceof \Sabre\VObject\Property\Uri && substr($photostring, 0, 5) === 'data:') { $mimeType = substr($photostring, 5, strpos($photostring, ',') - 5); if (strpos($mimeType, ';')) { $mimeType = substr($mimeType, 0, strpos($mimeType, ';')); } $photostring = substr($photostring, strpos($photostring, ',') + 1); } if (!$image->loadFromBase64($photostring)) { #\OCP\Util::writeLog('contacts', __METHOD__.', photo: ' . print_r($photostring, true), \OCP\Util::DEBUG); return false; } } if (!$image->centerCrop()) { \OCP\Util::writeLog('contacts', __METHOD__ . '. Couldn\'t crop thumbnail for ID ' . $key, \OCP\Util::ERROR); return false; } if (!$image->resize(self::THUMBNAIL_SIZE)) { \OCP\Util::writeLog('contacts', __METHOD__ . '. Couldn\'t resize thumbnail for ID ' . $key, \OCP\Util::ERROR); return false; } // Cache as base64 for around a month $cache->set($key, strval($image), 3000000); return $cache->get($key); }