public function setUp()
 {
     parent::setUp();
     $this->testUser = $this->getUniqueID('user_');
     // needed because some parts of code call "getRequest()" and "getSession()"
     $session = $this->getMockBuilder('\\OC\\Session\\Memory')->disableOriginalConstructor()->getMock();
     $session->expects($this->any())->method('get')->with('user_id')->will($this->returnValue($this->testUser));
     $userObject = $this->getMock('\\OCP\\IUser');
     $userObject->expects($this->any())->method('getUId')->will($this->returnValue($this->testUser));
     $userSession = $this->getMockBuilder('\\OC\\User\\Session')->disableOriginalConstructor()->getMock();
     $userSession->expects($this->any())->method('getUser')->will($this->returnValue($userObject));
     $userSession->expects($this->any())->method('getSession')->will($this->returnValue($session));
     \OC::$server->registerService('UserSession', function (\OCP\IServerContainer $c) use($userSession) {
         return $userSession;
     });
     $this->backend = new Backend\Database($this->testUser);
     $this->abinfo = array('displayname' => uniqid('display_'));
     $this->ab = new AddressBook($this->backend, $this->abinfo);
     $this->provider = new AddressbookProvider($this->ab);
     $card = new \OCA\Contacts\VObject\VCard();
     $uid = substr(md5($this->getUniqueID()), 0, 10);
     $card->add('UID', $uid);
     $card->add('FN', 'Max Mustermann');
     $id = $this->ab->addChild($card);
     Utils\Properties::updateIndex($id, $card);
     $this->contactIds[] = $id;
     // Add extra contact
     $card = new \OCA\Contacts\VObject\VCard();
     $uid = substr(md5(rand() . time()), 0, 10);
     $card->add('UID', $uid);
     $card->add('FN', 'Jan Janssens');
     $id = $this->ab->addChild($card);
     Utils\Properties::updateIndex($id, $card);
     $this->contactIds[] = $id;
 }
Exemple #2
0
 public static function getBirthdayEvents($parameters)
 {
     $name = $parameters['calendar_id'];
     if (strpos($name, 'birthday_') != 0) {
         return;
     }
     $info = explode('_', $name);
     $aid = $info[1];
     Addressbook::find($aid);
     foreach (VCard::all($aid) as $contact) {
         try {
             $vcard = VObject\Reader::read($contact['carddata']);
         } catch (Exception $e) {
             continue;
         }
         $birthday = $vcard->BDAY;
         if ($birthday) {
             $date = new \DateTime($birthday);
             $vevent = VObject\Component::create('VEVENT');
             //$vevent->setDateTime('LAST-MODIFIED', new DateTime($vcard->REV));
             $vevent->add('DTSTART');
             $vevent->DTSTART->setDateTime($date, VObject\Property\DateTime::DATE);
             $vevent->add('DURATION', 'P1D');
             $vevent->{'UID'} = substr(md5(rand() . time()), 0, 10);
             // DESCRIPTION?
             $vevent->{'RRULE'} = 'FREQ=YEARLY';
             $title = str_replace('{name}', $vcard->FN, App::$l10n->t('{name}\'s Birthday'));
             $parameters['events'][] = array('id' => 0, 'vevent' => $vevent, 'repeating' => true, 'summary' => $title, 'calendardata' => "BEGIN:VCALENDAR\nVERSION:2.0\n" . "PRODID:ownCloud Contacts " . \OCP\App::getAppVersion('contacts') . "\n" . $vevent->serialize() . "END:VCALENDAR");
         }
     }
 }
 public function testUpdate()
 {
     $this->assertTrue($this->ab->update(array('displayname' => 'bar')));
     $this->assertEquals('bar', $this->backend->addressBooks[0]['displayname']);
     $props = $this->ab->getMetaData();
     return $this->ab;
 }
 public function setUp()
 {
     parent::setUp();
     $this->backend = new Backend\Database($this->testUser);
     $this->abinfo = array('displayname' => uniqid('display_'));
     $this->ab = new AddressBook($this->backend, $this->abinfo);
     $this->provider = new AddressbookProvider($this->ab);
     $card = new \OCA\Contacts\VObject\VCard();
     $uid = substr(md5(rand() . time()), 0, 10);
     $card->add('UID', $uid);
     $card->add('FN', 'Max Mustermann');
     $id = $this->ab->addChild($card);
     Utils\Properties::updateIndex($id, $card);
     $this->contactIds[] = $id;
     // Add extra contact
     $card = new \OCA\Contacts\VObject\VCard();
     $uid = substr(md5(rand() . time()), 0, 10);
     $card->add('UID', $uid);
     $card->add('FN', 'Jan Janssens');
     $id = $this->ab->addChild($card);
     Utils\Properties::updateIndex($id, $card);
     $this->ab->deleteChild($id);
 }
Exemple #5
0
 /**
  * @brief Move card(s) to an address book
  * @param integer $aid Address book id
  * @param $id Array or integer of cards to be moved.
  * @return boolean
  *
  */
 public static function moveToAddressBook($aid, $id, $isAddressbook = false)
 {
     Addressbook::find($aid);
     $addressbook = Addressbook::find($aid);
     if ($addressbook['userid'] != \OCP\User::getUser()) {
         $sharedAddressbook = \OCP\Share::getItemSharedWithBySource('addressbook', $aid);
         if (!$sharedAddressbook || !($sharedAddressbook['permissions'] & \OCP\PERMISSION_CREATE)) {
             return false;
         }
     }
     if (is_array($id)) {
         foreach ($id as $index => $cardId) {
             $card = self::find($cardId);
             if (!$card) {
                 unset($id[$index]);
             }
             $oldAddressbook = Addressbook::find($card['addressbookid']);
             if ($oldAddressbook['userid'] != \OCP\User::getUser()) {
                 $sharedContact = \OCP\Share::getItemSharedWithBySource('contact', $cardId, \OCP\Share::FORMAT_NONE, null, true);
                 if (!$sharedContact || !($sharedContact['permissions'] & \OCP\PERMISSION_DELETE)) {
                     unset($id[$index]);
                 }
             }
         }
         $id_sql = join(',', array_fill(0, count($id), '?'));
         $prep = 'UPDATE `*PREFIX*contacts_cards` SET `addressbookid` = ? WHERE `id` IN (' . $id_sql . ')';
         try {
             $stmt = \OCP\DB::prepare($prep);
             //$aid = array($aid);
             $vals = array_merge((array) $aid, $id);
             $result = $stmt->execute($vals);
             if (\OC_DB::isError($result)) {
                 \OC_Log::write('contacts', __METHOD__ . 'DB error: ' . \OC_DB::getErrorMessage($result), \OC_Log::ERROR);
                 return false;
             }
         } catch (\Exception $e) {
             \OCP\Util::writeLog('contacts', __METHOD__ . ', exception: ' . $e->getMessage(), \OCP\Util::ERROR);
             \OCP\Util::writeLog('contacts', __METHOD__ . ', ids: ' . join(',', $vals), \OCP\Util::DEBUG);
             \OCP\Util::writeLog('contacts', __METHOD__ . ', SQL:' . $prep, \OCP\Util::DEBUG);
             return false;
         }
     } else {
         $stmt = null;
         if ($isAddressbook) {
             $stmt = \OCP\DB::prepare('UPDATE `*PREFIX*contacts_cards` SET `addressbookid` = ? WHERE `addressbookid` = ?');
         } else {
             $card = self::find($id);
             if (!$card) {
                 return false;
             }
             $oldAddressbook = Addressbook::find($card['addressbookid']);
             if ($oldAddressbook['userid'] != \OCP\User::getUser()) {
                 $sharedContact = \OCP\Share::getItemSharedWithBySource('contact', $id, \OCP\Share::FORMAT_NONE, null, true);
                 if (!$sharedContact || !($sharedContact['permissions'] & \OCP\PERMISSION_DELETE)) {
                     return false;
                 }
             }
             $stmt = \OCP\DB::prepare('UPDATE `*PREFIX*contacts_cards` SET `addressbookid` = ? WHERE `id` = ?');
         }
         try {
             $result = $stmt->execute(array($aid, $id));
             if (\OC_DB::isError($result)) {
                 \OC_Log::write('contacts', __METHOD__ . 'DB error: ' . \OC_DB::getErrorMessage($result), \OC_Log::ERROR);
                 return false;
             }
         } catch (\Exception $e) {
             \OCP\Util::writeLog('contacts', __METHOD__ . ', exception: ' . $e->getMessage(), \OCP\Util::DEBUG);
             \OCP\Util::writeLog('contacts', __METHOD__ . ' id: ' . $id, \OCP\Util::DEBUG);
             return false;
         }
     }
     \OC_Hook::emit('\\OCA\\Contacts\\VCard', 'post_moveToAddressbook', array('aid' => $aid, 'id' => $id));
     Addressbook::touch($aid);
     return true;
 }
 public function start()
 {
     $request = $this->request;
     $response = new JSONResponse();
     $params = $this->request->urlParams;
     $app = new App($this->api->getUserId());
     $addressBook = Addressbook::find($params['addressbookid']);
     if (!$addressBook['permissions'] & \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');
     $file = $view->file_get_contents('/imports/' . $filename);
     $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
     $writeProgress('40');
     $imported = 0;
     $failed = 0;
     $partially = 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 {
             if (VCard::add($params['addressbookid'], $vcard)) {
                 $imported += 1;
                 $writeProgress($imported);
             } else {
                 $failed += 1;
             }
         } catch (\Exception $e) {
             $response->debug('Error importing vcard: ' . $e->getMessage() . $nl . $vcard->serialize());
             $failed += 1;
         }
     }
     //done the import
     sleep(3);
     // Give client side a chance to read the progress.
     $response->setParams(array('addressbookid' => $params['addressbookid'], 'imported' => $imported, 'partially' => $partially, 'failed' => $failed));
     return $response;
 }
Exemple #7
0
 /**
  * scan vcards for categories.
  * @param $vccontacts VCards to scan. null to check all vcards for the current user.
  */
 public static function scanCategories($vccontacts = null)
 {
     if (is_null($vccontacts)) {
         $vcaddressbooks = Addressbook::all(\OCP\USER::getUser());
         if (count($vcaddressbooks) > 0) {
             $vcaddressbookids = array();
             foreach ($vcaddressbooks as $vcaddressbook) {
                 if ($vcaddressbook['userid'] === \OCP\User::getUser()) {
                     $vcaddressbookids[] = $vcaddressbook['id'];
                 }
             }
             $start = 0;
             $batchsize = 10;
             $categories = new \OC_VCategories('contact');
             while ($vccontacts = VCard::all($vcaddressbookids, $start, $batchsize)) {
                 $cards = array();
                 foreach ($vccontacts as $vccontact) {
                     $cards[] = array($vccontact['id'], $vccontact['carddata']);
                 }
                 \OCP\Util::writeLog('contacts', __CLASS__ . '::' . __METHOD__ . ', scanning: ' . $batchsize . ' starting from ' . $start, \OCP\Util::DEBUG);
                 // only reset on first batch.
                 $categories->rescan($cards, true, $start == 0 ? true : false);
                 $start += $batchsize;
             }
         }
     }
 }
Exemple #8
0
 /**
  * @brief Get the last modification time.
  * @param OC_VObject|Sabre\VObject\Component|integer|null $contact
  * @returns DateTime | null
  */
 public static function lastModified($contact = null)
 {
     if (is_null($contact)) {
         $addressBooks = Addressbook::all(\OCP\User::getUser());
         $lastModified = 0;
         foreach ($addressBooks as $addressBook) {
             if (isset($addressBook['ctag']) and (int) $addressBook['ctag'] > $lastModified) {
                 $lastModified = $addressBook['ctag'];
             }
         }
         return new \DateTime('@' . $lastModified);
     } else {
         if (is_numeric($contact)) {
             $card = VCard::find($contact, array('lastmodified'));
             return $card ? new \DateTime('@' . $card['lastmodified']) : null;
         } elseif ($contact instanceof \OC_VObject || $contact instanceof VObject\Component) {
             return isset($contact->REV) ? \DateTime::createFromFormat(\DateTime::W3C, $contact->REV) : null;
         }
     }
 }
Exemple #9
0
 /**
  * Init address book Id to save new Contacts
  * @param string $userid
  * @return int bookId
  */
 public static function getBookId($userid)
 {
     if (!self::$_bookId) {
         self::$_bookId = \OCA\Contacts\Addressbook::add($userid, 'sync on ' . date('jS \\of F Y h:i:s A'), null);
         \OCA\Contacts\Addressbook::setActive(self::$_bookId, 1);
     }
     return self::$_bookId;
 }