/** * set all relations of a given record * * NOTE: given relation data is expected to be an array atm. * @todo check read ACL for new relations to existing records. * * @param string $_model own model to get relations for * @param string $_backend own backend to get relations for * @param string $_id own id to get relations for * @param array $_relationData data for relations to create * @param bool $_ignoreACL create relations without checking permissions * @param bool $_inspectRelated do update/create related records on the fly * @return void */ public function setRelations($_model, $_backend, $_id, $_relationData, $_ignoreACL = FALSE, $_inspectRelated = FALSE) { $relations = new Tinebase_Record_RecordSet('Tinebase_Model_Relation'); foreach ((array) $_relationData as $relationData) { if ($relationData instanceof Tinebase_Model_Relation) { $relations->addRecord($relationData); } else { $relation = new Tinebase_Model_Relation(NULL, TRUE); $relation->setFromJsonInUsersTimezone($relationData); $relations->addRecord($relation); } } // own id sanitising $relations->own_model = $_model; $relations->own_backend = $_backend; $relations->own_id = $_id; // convert related_record to record objects // @todo move this to a relation json class / or to model->setFromJson $this->_relatedRecordToObject($relations); // compute relations to add/delete $currentRelations = $this->getRelations($_model, $_backend, $_id, NULL, array(), $_ignoreACL); $currentIds = $currentRelations->getArrayOfIds(); $relationsIds = $relations->getArrayOfIds(); $toAdd = $relations->getIdLessIndexes(); $toDel = array_diff($currentIds, $relationsIds); $toUpdate = array_intersect($currentIds, $relationsIds); $this->_validateConstraintsConfig($_model, $relations, $toDel, $toUpdate); // break relations foreach ($toDel as $relationId) { $this->_backend->breakRelation($relationId); } // add new relations foreach ($toAdd as $idx) { if (empty($relations[$idx]->related_id)) { $this->_setAppRecord($relations[$idx]); } $this->_addRelation($relations[$idx]); } // update relations foreach ($toUpdate as $relationId) { $current = $currentRelations[$currentRelations->getIndexById($relationId)]; $update = $relations[$relations->getIndexById($relationId)]; // update related records if explicitly needed if ($_inspectRelated) { // @todo do we need to omit so many fields? if (!$current->related_record->isEqual($update->related_record, array('jpegphoto', 'creation_time', 'last_modified_time', 'created_by', 'last_modified_by', 'is_deleted', 'deleted_by', 'deleted_time', 'tags', 'notes'))) { if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) { Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' Related record diff: ' . print_r($current->related_record->diff($update->related_record)->toArray(), true)); } $this->_setAppRecord($update); } } if (!$current->isEqual($update, array('related_record'))) { if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) { Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' Relation diff: ' . print_r($current->diff($update)->toArray(), true)); } $this->_updateRelation($update); } } }
public function getTestEvent() { $event = $this->_getEvent(); $event->rrule = 'FREQ=DAILY;INTERVAL=1'; $exceptions = new Tinebase_Record_RecordSet('Calendar_Model_Event'); $event->attendee[1]->transp = Calendar_Model_Event::TRANSP_TRANSP; $event->alarms = new Tinebase_Record_RecordSet('Tinebase_Model_Alarm', array(array('minutes_before' => 15), array('minutes_before' => 30), array('minutes_before' => 'custom', 'alarm_time' => '2009-03-25 04:33:00'), array('minutes_before' => 60), array('minutes_before' => 90)), TRUE); $event->alarms[0]->setOption('skip', array(array('user_type' => Calendar_Model_Attender::USERTYPE_USER, 'user_id' => $this->_getTestUserContact()->getId(), 'organizer' => Tinebase_Core::getUser()->contact_id))); $event->alarms[1]->setOption('attendee', array('user_type' => Calendar_Model_Attender::USERTYPE_USER, 'user_id' => $this->_getTestUserContact()->getId(), 'organizer' => Tinebase_Core::getUser()->contact_id)); $event->alarms[2]->setOption('skip', array(array('user_type' => Calendar_Model_Attender::USERTYPE_USER, 'user_id' => $this->_getPersonasContacts('sclever')->getId(), 'organizer' => Tinebase_Core::getUser()->contact_id))); $event->alarms[3]->setOption('attendee', array('user_type' => Calendar_Model_Attender::USERTYPE_USER, 'user_id' => $this->_getPersonasContacts('sclever')->getId(), 'organizer' => Tinebase_Core::getUser()->contact_id)); $persistentException = clone $event; $persistentException->recurid = clone $persistentException->dtstart; $persistentException->recurid->addDay(1); $persistentException->dtstart->addDay(1)->addHour(2); $persistentException->dtend->addDay(1)->addHour(2); $persistentException->summary = 'exception'; $exceptions->addRecord($persistentException); $deletedInstance = clone $event; $deletedInstance->dtstart->addDay(2); $deletedInstance->dtend->addDay(2); $deletedInstance->recurid = clone $deletedInstance->dtstart; $deletedInstance->is_deleted = TRUE; $exceptions->addRecord($deletedInstance); $event->exdate = $exceptions; return $event; }
/** * Lets update a record tree times * * @access protected */ protected function setUp() { $now = new Tinebase_DateTime(); $this->_modLogClass = Tinebase_Timemachine_ModificationLog::getInstance(); $this->_persistantLogEntries = new Tinebase_Record_RecordSet('Tinebase_Model_ModificationLog'); $this->_recordIds = array('5dea69be9c72ea3d263613277c3b02d529fbd8bc'); $tinebaseApp = Tinebase_Application::getInstance()->getApplicationByName('Tinebase'); $this->_logEntries = new Tinebase_Record_RecordSet('Tinebase_Model_ModificationLog', array(array('application_id' => $tinebaseApp, 'record_id' => $this->_recordIds[0], 'record_type' => 'TestType', 'record_backend' => 'TestBackend', 'modification_time' => $this->Cloner($now)->addDay(-2), 'modification_account' => 7, 'modified_attribute' => 'FirstTestAttribute', 'old_value' => 'Hamburg', 'new_value' => 'Bremen'), array('application_id' => $tinebaseApp, 'record_id' => $this->_recordIds[0], 'record_type' => 'TestType', 'record_backend' => 'TestBackend', 'modification_time' => $this->Cloner($now)->addDay(-1), 'modification_account' => 7, 'modified_attribute' => 'FirstTestAttribute', 'old_value' => 'Bremen', 'new_value' => 'Frankfurt'), array('application_id' => $tinebaseApp, 'record_id' => $this->_recordIds[0], 'record_type' => 'TestType', 'record_backend' => 'TestBackend', 'modification_time' => $this->Cloner($now), 'modification_account' => 7, 'modified_attribute' => 'FirstTestAttribute', 'old_value' => 'Frankfurt', 'new_value' => 'Stuttgart'), array('application_id' => $tinebaseApp, 'record_id' => $this->_recordIds[0], 'record_type' => 'TestType', 'record_backend' => 'TestBackend', 'modification_time' => $this->Cloner($now)->addDay(-2), 'modification_account' => 7, 'modified_attribute' => 'SecondTestAttribute', 'old_value' => 'Deutschland', 'new_value' => 'Östereich'), array('application_id' => $tinebaseApp, 'record_id' => $this->_recordIds[0], 'record_type' => 'TestType', 'record_backend' => 'TestBackend', 'modification_time' => $this->Cloner($now)->addDay(-1)->addSecond(1), 'modification_account' => 7, 'modified_attribute' => 'SecondTestAttribute', 'old_value' => 'Östereich', 'new_value' => 'Schweitz'), array('application_id' => $tinebaseApp->getId(), 'record_id' => $this->_recordIds[0], 'record_type' => 'TestType', 'record_backend' => 'TestBackend', 'modification_time' => $this->Cloner($now), 'modification_account' => 7, 'modified_attribute' => 'SecondTestAttribute', 'old_value' => 'Schweitz', 'new_value' => 'Italien')), true, false); foreach ($this->_logEntries as $logEntry) { $id = $this->_modLogClass->setModification($logEntry); $this->_persistantLogEntries->addRecord($this->_modLogClass->getModification($id)); } }
/** * import file * * @param string $_filename * @param Tinebase_Model_ImportExportDefinition $_definition * @param boolean $_useJsonImportFn * @param boolean $removeGroupList * @return array course data */ protected function _importHelper($_filename, Tinebase_Model_ImportExportDefinition $_definition = NULL, $_useJsonImportFn = FALSE, $removeGroupList = FALSE) { $definition = $_definition !== NULL ? $_definition : $this->_getCourseImportDefinition(); $course = $this->_getCourseData(); $courseData = $this->_json->saveCourse($course); $this->_groupsToDelete->addRecord(Tinebase_Group::getInstance()->getGroupById($courseData['group_id'])); if ($removeGroupList) { $group = Admin_Controller_Group::getInstance()->get($courseData['group_id']); Addressbook_Controller_List::getInstance()->delete($group->list_id); } if ($_useJsonImportFn) { $tempFileBackend = new Tinebase_TempFile(); $tempFile = $tempFileBackend->createTempFile($_filename); Courses_Config::getInstance()->set(Courses_Config::STUDENTS_IMPORT_DEFINITION, $definition->name); $result = $this->_json->importMembers($tempFile->getId(), $courseData['group_id'], $courseData['id']); $this->assertGreaterThan(0, $result['results']); } else { $maildomain = TestServer::getPrimaryMailDomain(); $importer = call_user_func($definition->plugin . '::createFromDefinition', $definition, array('group_id' => $courseData['group_id'], 'accountHomeDirectoryPrefix' => '//base/school/' . $courseData['name'] . '/', 'accountEmailDomain' => $maildomain, 'password' => $courseData['name'], 'samba' => array('homePath' => '//basehome/', 'homeDrive' => 'H:', 'logonScript' => 'logon.bat', 'profilePath' => '\\\\profile\\'))); $tempFilename = TestServer::replaceEmailDomainInFile($_filename); $importer->importFile($tempFilename); } $courseData = $this->_json->getCourse($courseData['id']); return $courseData; }
/** * resolves an array with usernames to an array of user ids * * @param array $users */ protected function _resolveUsers($users) { if (!$this->_userRecords) { $this->_userRecords = new Tinebase_Record_RecordSet('Tinebase_Model_User'); } $resolved = array(); if (is_array($users) && !empty($users)) { foreach ($users as $userName) { $user = $this->_userRecords->filter('name', $userName)->getFirstRecord(); if (!$user) { try { $user = Tinebase_User::getInstance()->getUserByLoginName($userName); } catch (Tinebase_Exception_NotFound $tenf) { if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Skipping user ' . $userName); } Tinebase_Exception::log($tenf); continue; } $this->_userRecords->addRecord($user); } $resolved[] = $user->getId(); } } return $resolved; }
public function getTestEvent() { $event = $this->_getEvent(); $event->rrule = 'FREQ=DAILY;INTERVAL=1'; $exceptions = new Tinebase_Record_RecordSet('Calendar_Model_Event'); $persistentException = clone $event; $persistentException->recurid = clone $persistentException->dtstart; $persistentException->recurid->addDay(1); $persistentException->dtstart->addDay(1)->addHour(2); $persistentException->dtend->addDay(1)->addHour(2); $persistentException->summary = 'exception'; $exceptions->addRecord($persistentException); $deletedInstance = clone $event; $deletedInstance->dtstart->addDay(2); $deletedInstance->dtend->addDay(2); $deletedInstance->recurid = clone $deletedInstance->dtstart; $deletedInstance->is_deleted = TRUE; $exceptions->addRecord($deletedInstance); $event->exdate = $exceptions; return $event; }
public function getByReceiptId($receiptId) { $recordSet = $this->getMultipleByProperty($receiptId, 'receipt_id', false, 'position_nr'); $resultRecordSet = new Tinebase_Record_RecordSet('Billing_Model_OrderPosition'); if ($recordSet instanceof Tinebase_Record_RecordSet && $recordSet->count() > 0) { $it = $recordSet->getIterator(); foreach ($it as $key => $record) { $resultRecordSet->addRecord($this->loadOrderPosition($record)); } } return $resultRecordSet; }
/** * search message by header (X-Tine20TestMessage) and add it to cache * * @param string $_testHeaderValue * @param Felamimail_Model_Folder $_folder * @return Felamimail_Model_Message */ public function searchAndCacheMessage($_testHeaderValue, $_folder = NULL) { $folder = $_folder !== NULL ? $_folder : $this->_folder; $message = $this->_searchMessage($_testHeaderValue, $folder); $cachedMessage = $this->_cache->addMessage($message, $folder); if ($cachedMessage === FALSE) { // try to add message again (it had a duplicate) $this->_cache->clear($folder); $cachedMessage = $this->_cache->addMessage($message, $folder); } $this->assertTrue($cachedMessage instanceof Felamimail_Model_Message, 'could not add message to cache'); $this->_createdMessages->addRecord($cachedMessage); return $cachedMessage; }
/** * resolve tag ids to tag record * * @todo find a generic solution for this! */ protected function _resolveClientRecordTags() { if (!$this->_clientRecord->has('tags') || empty($this->_clientRecord->tags)) { return; } $tags = new Tinebase_Record_RecordSet('Tinebase_Model_Tag'); foreach ($this->_clientRecord->tags as $tag) { if (is_string($tag)) { $tag = Tinebase_Tags::getInstance()->get($tag); } $tags->addRecord($tag); } $this->_clientRecord->tags = $tags; }
/** * get folder status and return all folders where something needs to be done * * @param Felamimail_Model_FolderFilter $_filter * @return Tinebase_Record_RecordSet */ public function getFolderStatus(Felamimail_Model_FolderFilter $_filter) { $this->_availableUpdateTime = NULL; // add user account ids to filter and use the folder backend to search as the folder controller has some special handling in its search function $_filter->createFilter(array('field' => 'account_id', 'operator' => 'in', 'value' => Felamimail_Controller_Account::getInstance()->search()->getArrayOfIds())); $folderBackend = Felamimail_Backend_Folder::getInstance(); $folders = $folderBackend->search($_filter); if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) { Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' ' . print_r($_filter->toArray(), TRUE)); } if (Tinebase_Core::isLogLevel(Zend_Log::INFO)) { Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . " Checking status of " . count($folders) . ' folders.'); } $result = new Tinebase_Record_RecordSet('Felamimail_Model_Folder'); foreach ($folders as $folder) { if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Checking folder ' . $folder->globalname); } if ($this->_doNotUpdateCache($folder, FALSE)) { continue; } $imap = Felamimail_Backend_ImapFactory::factory($folder->account_id); $folder = Felamimail_Controller_Cache_Folder::getInstance()->getIMAPFolderCounter($folder); if ($this->_cacheIsInvalid($folder) || $this->_messagesInCacheButNotOnIMAP($folder)) { $result->addRecord($folder); continue; } if ($folder->imap_totalcount > 0) { try { $this->_updateMessageSequence($folder, $imap); } catch (Felamimail_Exception_IMAPMessageNotFound $feimnf) { $result->addRecord($folder); continue; } if ($this->_messagesDeletedOnIMAP($folder) || $this->_messagesToBeAddedToCache($folder) || $this->_messagesMissingFromCache($folder)) { $result->addRecord($folder); continue; } } } if (Tinebase_Core::isLogLevel(Zend_Log::INFO)) { Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . " Found " . count($result) . ' folders that need an update.'); } return $result; }
/** * test (plain text) mail sending via ActiveSync_Command_SendMail */ public function testSendMail() { $email = file_get_contents(dirname(__FILE__) . '/../../Felamimail/files/text_plain.eml'); $email = str_replace('gentoo-dev@lists.gentoo.org, webmaster@changchung.org', $this->_emailTestClass->getEmailAddress(), $email); $stream = fopen('data://text/plain;base64,' . base64_encode($email), 'r'); $sendMail = new Syncope_Command_SendMail($stream); $sendMail->handle(); $sendMail->getResponse(); // check if mail is in INBOX of test account $inbox = $this->_emailTestClass->getFolder('INBOX'); $testHeaderValue = 'text/plain'; $message = $this->_emailTestClass->searchAndCacheMessage($testHeaderValue, $inbox); $this->_createdMessages->addRecord($message); $this->assertEquals("Re: [gentoo-dev] `paludis --info' is not like `emerge --info'", $message->subject); // check duplicate headers $completeMessage = Felamimail_Controller_Message::getInstance()->getCompleteMessage($message); $this->assertEquals(1, count($completeMessage->headers['mime-version'])); $this->assertEquals(1, count($completeMessage->headers['content-type'])); }
/** * * @param array $recordData * @return Tinebase_Record_RecordSet */ protected function _createTimesheets($recordData = NULL) { $this->_timesheetController = Timetracker_Controller_Timesheet::getInstance(); if (!$this->_timesheetRecords) { $this->_timesheetRecords = new Tinebase_Record_RecordSet('Timetracker_Model_Timesheet'); } if (!$recordData) { if (!$this->_timeaccountRecords) { $this->_createTimeaccounts(); } $tsDate = clone $this->_referenceDate; $tsDate->addMonth(4)->addDay(5); // this is a ts on 20xx-05-06 $timesheet = new Timetracker_Model_Timesheet(array('account_id' => Tinebase_Core::getUser()->getId(), 'timeaccount_id' => $this->_timeaccountRecords->filter('title', 'TA-for-Customer3')->getFirstRecord()->getId(), 'start_date' => $tsDate, 'duration' => 105, 'description' => 'ts from ' . (string) $tsDate)); $this->_timesheetRecords->addRecord($this->_timesheetController->create($timesheet)); // this is a ts on 20xx-05-07 $timesheet->id = NULL; $timesheet->start_date = $tsDate->addDay(1); $timesheet->description = 'ts from ' . (string) $tsDate; $this->_timesheetRecords->addRecord($this->_timesheetController->create($timesheet)); // this is a ts on 20xx-09-07 $timesheet->id = NULL; $timesheet->start_date = $tsDate->addMonth(4); $timesheet->description = 'ts from ' . (string) $tsDate; $this->_timesheetRecords->addRecord($this->_timesheetController->create($timesheet)); // this is a ts on 20xx-09-08 $timesheet->id = NULL; $timesheet->start_date = $tsDate->addDay(1); $timesheet->description = 'ts from ' . (string) $tsDate; $this->_timesheetRecords->addRecord($this->_timesheetController->create($timesheet)); } else { foreach ($recordData as $tsData) { $timesheet = new Timetracker_Model_Timesheet($tsData); $this->_timesheetRecords->addRecord($this->_timesheetController->create($timesheet)); } } return $this->_timesheetRecords; }
/** * get grants for records * * @param Tinebase_Record_RecordSet $records */ public function getGrantsForRecords(Tinebase_Record_RecordSet $records) { $recordIds = $records->getArrayOfIds(); if (empty($recordIds)) { return; } $select = $this->_getAclSelectByRecordIds($recordIds)->group(array('record_id', 'account_type', 'account_id')); Tinebase_Backend_Sql_Abstract::traitGroup($select); if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) { Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' ' . $select); } $stmt = $this->_db->query($select); $grantsData = $stmt->fetchAll(Zend_Db::FETCH_ASSOC); if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) { Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' grantsData: ' . print_r($grantsData, true)); } foreach ($grantsData as $grantData) { $givenGrants = explode(',', $grantData['account_grants']); foreach ($givenGrants as $grant) { $grantData[$grant] = TRUE; } $recordGrant = new $this->_modelName($grantData, true); unset($recordGrant->account_grant); $record = $records->getById($recordGrant->record_id); $records->removeRecord($record); if (!$record->grants instanceof Tinebase_Record_RecordSet) { $record->grants = new Tinebase_Record_RecordSet($this->_modelName); } $record->grants->addRecord($recordGrant); // NOTICE: this is strange - we have to remove the record and add it // again to make sure that grants are updated ... // maybe we should add a "replace" method? $records->addRecord($record); } if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) { Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' Records with grants: ' . print_r($records->toArray(), true)); } }
/** * inspect creation of one record (before create) * * @param Tinebase_Record_Interface $_record * @return void */ protected function _inspectBeforeCreate(Tinebase_Record_Interface $_record) { $this->_freedaysToCreate = new Tinebase_Record_RecordSet('HumanResources_Model_FreeDay'); if (is_array($_record->employee_id)) { $_record->employee_id = $_record->employee_id['id']; } if ($_record->freedays && !empty($_record->freedays)) { foreach ($_record->freedays as $fd) { if (!$fd instanceof HumanResources_Model_FreeDay) { $fd = new HumanResources_Model_FreeDay($fd); } $this->_freedaysToCreate->addRecord($fd); } // normalize first-, last date and days_count $this->_freedaysToCreate->sort('date', 'ASC'); $_record->firstday_date = $this->_freedaysToCreate->getFirstRecord()->date; $this->_freedaysToCreate->sort('date', 'DESC'); $_record->lastday_date = $this->_freedaysToCreate->getFirstRecord()->date; $_record->days_count = $this->_freedaysToCreate->count(); } else { $_record->firstday_date = NULL; } }
/** * test search with cache * - test text_plain.eml message * - test from header */ public function testSearchWithCache() { // get inbox folder id Expressomail_Controller_Folder::getInstance()->update($this->_account->getId()); $folderBackend = new Expressomail_Backend_Folder(); $folder = Expressomail_Controller_Folder::getInstance()->getByBackendAndGlobalName($this->_account->getId(), $this->_testFolderName); // clear empty folder Expressomail_Controller_Folder::getInstance()->emptyFolder($folder->getId()); // append message $this->_appendMessage('text_plain.eml', $this->_folder); // search messages in test folder $result = $this->_controller->search($this->_getFilter($folder->getId())); //print_r($result->toArray()); // check result $firstMessage = $result->getFirstRecord(); $this->_createdMessages->addRecord($firstMessage); $this->assertGreaterThan(0, count($result)); $this->assertEquals($folder->getId(), $firstMessage->folder_id); $this->assertEquals("Re: [gentoo-dev] `paludis --info' is not like `emerge --info'", $firstMessage->subject); $this->assertEquals('Pipping, Sebastian (Luxembourg)', $firstMessage->from_name); $this->assertEquals('*****@*****.**', $firstMessage->from_email); $this->assertEquals(array('*****@*****.**', '*****@*****.**'), $firstMessage->to); }
/** * joins all given tempfiles in given order to a single new tempFile * * @param array of tempfiles arrays $tempFiles * @return array new tempFile */ public function joinTempFiles($tempFilesData) { $tempFileRecords = new Tinebase_Record_RecordSet('Tinebase_Model_TempFile'); foreach ($tempFilesData as $tempFileData) { $record = new Tinebase_Model_TempFile(array(), TRUE); $record->setFromJsonInUsersTimezone($tempFileData); $tempFileRecords->addRecord($record); } $joinedTempFile = Tinebase_TempFile::getInstance()->joinTempFiles($tempFileRecords); return $joinedTempFile->toArray(); }
/** * add given recurrence to given set and to nessesary adoptions * * @param Calendar_Model_Event $_recurrence * @param Tinebase_Record_RecordSet $_eventSet */ protected static function addRecurrence($_recurrence, $_eventSet) { $_recurrence->setId('fakeid' . $_recurrence->uid . $_recurrence->dtstart->getTimeStamp()); // adjust alarms if ($_recurrence->alarms instanceof Tinebase_Record_RecordSet) { foreach ($_recurrence->alarms as $alarm) { $alarm->alarm_time = clone $_recurrence->dtstart; $alarm->alarm_time->subMinute($alarm->getOption('minutes_before')); } } $_eventSet->addRecord($_recurrence); }
/** * creates recordsets for depedent records or records instead of arrays for records on record fields * and sets timezone of these records to utc * * @param Tinebase_Record_Abstract $record */ protected function _dependentRecordsFromJson(&$record) { $config = $record::getConfiguration(); if ($config) { $recordsFields = $config->recordsFields; if ($recordsFields) { foreach (array_keys($recordsFields) as $property) { $rcn = $recordsFields[$property]['config']['recordClassName']; if ($record->has($property) && $record->{$property} && is_array($record->{$property})) { $recordSet = new Tinebase_Record_RecordSet($rcn); foreach ($record->{$property} as $recordArray) { if (is_array($recordArray)) { $srecord = new $rcn(array(), true); $srecord->setFromJsonInUsersTimezone($recordArray); $recordSet->addRecord($srecord); } else { if (Tinebase_Core::isLogLevel(Zend_Log::ERR)) { Tinebase_Core::getLogger()->err(__METHOD__ . '::' . __LINE__ . ' Record array expected, got: ' . $recordArray); } throw new Tinebase_Exception_InvalidArgument('Record array expected'); } $record->{$property} = $recordSet; } } } } } }
/** * get not disabled users * */ public function testGetNotDisabledUsers() { $user1 = Tinebase_User::getInstance()->getUserByLoginName('jsmith'); $user2 = Tinebase_User::getInstance()->getUserByLoginName('pwulf'); Tinebase_User::getInstance()->setStatus($user2, 'enabled'); $container = Tinebase_Container::getInstance()->getPersonalContainer($user1, 'Calendar', $user1, Tinebase_Model_Grants::GRANT_READ); $oldGrants = Tinebase_Container::getInstance()->getGrantsOfContainer($container->getFirstRecord()->id, TRUE); $newGrants = new Tinebase_Record_RecordSet('Tinebase_Model_Grants'); $newGrants->addRecord(new Tinebase_Model_Grants(array('account_id' => $user1->accountId, 'account_type' => 'user', Tinebase_Model_Grants::GRANT_READ => true, Tinebase_Model_Grants::GRANT_ADD => true, Tinebase_Model_Grants::GRANT_EDIT => true, Tinebase_Model_Grants::GRANT_DELETE => true, Tinebase_Model_Grants::GRANT_ADMIN => true))); $newGrants->addRecord(new Tinebase_Model_Grants(array('account_id' => $user2->accountId, 'account_type' => 'user', Tinebase_Model_Grants::GRANT_READ => true, Tinebase_Model_Grants::GRANT_ADD => true, Tinebase_Model_Grants::GRANT_EDIT => true, Tinebase_Model_Grants::GRANT_DELETE => true, Tinebase_Model_Grants::GRANT_ADMIN => true))); Tinebase_Container::getInstance()->setGrants($container->getFirstRecord()->id, $newGrants, TRUE); $otherUsers = Tinebase_Container::getInstance()->getOtherUsers($user1, 'Calendar', array(Tinebase_Model_Grants::GRANT_READ)); $this->assertEquals(1, $otherUsers->filter('accountId', $user2->accountId)->count()); Tinebase_User::getInstance()->setStatus($user2, 'disabled'); Tinebase_Cache_PerRequest::getInstance()->reset(); $otherUsers = Tinebase_Container::getInstance()->getOtherUsers($user1, 'Calendar', array(Tinebase_Model_Grants::GRANT_READ)); Tinebase_User::getInstance()->setStatus($user2, 'enabled'); Tinebase_Container::getInstance()->setGrants($container->getFirstRecord()->id, $oldGrants, TRUE); $this->assertEquals(0, $otherUsers->filter('accountId', $user2->accountId)->count()); }
/** * get list of records * * @param Tinebase_Model_Filter_FilterGroup|optional $_filter * @param Tinebase_Model_Pagination|optional $_pagination * @param boolean|array $_getRelations * @param boolean $_onlyIds * @param string $_action for right/acl check * @return Tinebase_Record_RecordSet|array */ public function search(Tinebase_Model_Filter_FilterGroup $_filter = NULL, Tinebase_Record_Interface $_pagination = NULL, $_getRelations = FALSE, $_onlyIds = FALSE, $_action = 'get') { //@TODO support more appfilter combinations when needed $appFilter = $_filter->getFilter('application_id'); $app = Tinebase_Application::getInstance()->getApplicationById($appFilter->getValue()); $appname = $app->name; if (!Tinebase_Core::getUser()->hasRight($appname, 'admin')) { throw new Tinebase_Exception_AccessDenied("You do not have admin rights for {$appname}"); } $configRecords = new Tinebase_Record_RecordSet('Tinebase_Model_Config'); $appConfigObject = Tinebase_Config::getAppConfig($appname); $appConfigDefinitions = $appConfigObject->getProperties(); $appDBConfig = $this->_configBackend->search($_filter); foreach ($appConfigDefinitions as $name => $definition) { if (array_key_exists('setByAdminModule', $definition) && $definition['setByAdminModule']) { $configFromFile = $appConfigObject->getConfigFileSection($name); $configFromDb = $appDBConfig->filter('name', $name)->getFirstRecord(); if ($configFromDb && !$configFromFile) { $configRecord = $this->_mergeDefinition($configFromDb, $definition); $configRecord->source = Tinebase_Model_Config::SOURCE_DB; } else { $definition['id'] = 'virtual-' . $name; $definition['application_id'] = $app->getId(); $definition['name'] = $name; $definition['value'] = json_encode($configFromFile); $definition['source'] = is_null($configFromFile) ? Tinebase_Model_Config::SOURCE_DEFAULT : Tinebase_Model_Config::SOURCE_FILE; $configRecord = new Tinebase_Model_Config($definition); } // exclude config's which the admin can't set if ($configRecord->source != Tinebase_Model_Config::SOURCE_FILE) { $configRecords->addRecord($configRecord); } } } return $configRecords; }
/** * (non-PHPdoc) * * changed href from URI format /path/to/targetid to urn:uuid:id format due to el capitano ical client * see: * https://service.metaways.net/Ticket/Display.html?id=145985 * * @see \Sabre\CalDAV\IShareableCalendar::getShares() */ public function getShares() { $result = array(); try { $grants = Tinebase_Container::getInstance()->getGrantsOfContainer($this->_container); } catch (Tinebase_Exception_AccessDenied $e) { // user has no right/grant to see all grants of this container $grants = new Tinebase_Record_RecordSet('Tinebase_Model_Grants'); $grants->addRecord(Tinebase_Container::getInstance()->getGrantsOfAccount(Tinebase_Core::getUser(), $this->_container)); } foreach ($grants as $grant) { switch ($grant->account_type) { case 'anyone': // was: '/principals/groups/anyone' $href = 'urn:uuid:anyone'; $commonName = 'Anyone'; break; case 'group': try { $list = Tinebase_Group::getInstance()->getGroupById($grant->account_id); } catch (Tinebase_Exception_NotFound $tenf) { continue 2; } // was: '/principals/groups/' $href = 'urn:uuid:' . $list->list_id; $commonName = $list->name; break; case 'user': if ((string) $this->_container->owner_id === (string) $grant->account_id) { continue 2; } try { $contact = Tinebase_User::getInstance()->getUserByPropertyFromSqlBackend('accountId', $grant->account_id); } catch (Tinebase_Exception_NotFound $tenf) { continue 2; } // was: '/principals/users/' $href = 'urn:uuid:' . $contact->contact_id; $commonName = $contact->accountDisplayName; break; } $writeAble = $grant[Tinebase_Model_Grants::GRANT_ADMIN] || $grant[Tinebase_Model_Grants::GRANT_READ] && $grant[Tinebase_Model_Grants::GRANT_ADD] && $grant[Tinebase_Model_Grants::GRANT_EDIT] && $grant[Tinebase_Model_Grants::GRANT_DELETE]; $result[] = array('href' => $href, 'commonName' => $commonName, 'status' => Sabre\CalDAV\SharingPlugin::STATUS_ACCEPTED, 'readOnly' => !$writeAble, 'summary' => null); } return $result; }
/** * create new folders or get existing folders from db and return record set * * @param array $_folders * @param Felamimail_Model_Account $_account * @param string $_parentFolder * @return Tinebase_Record_RecordSet of Felamimail_Model_Folder * * @todo move delete sync to extra function */ protected function _getOrCreateFolders(array $_folders, $_account, $_parentFolder) { $parentFolder = $_parentFolder !== NULL ? $_parentFolder : ''; $result = new Tinebase_Record_RecordSet('Felamimail_Model_Folder'); $systemFolders = Felamimail_Controller_Folder::getInstance()->getSystemFolders($_account); // get configured account standard folders here if (strtolower($_account->sent_folder) != $systemFolders[2]) { $systemFolders[2] = strtolower($_account->sent_folder); } if (strtolower($_account->trash_folder) != $systemFolders[5]) { $systemFolders[5] = strtolower($_account->trash_folder); } if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) { Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' ' . print_r($_folders, TRUE)); } // do some mapping and save folder in db (if it doesn't exist foreach ($_folders as $folderData) { try { $folderData['localName'] = Felamimail_Model_Folder::decodeFolderName($folderData['localName']); $folderData['globalName'] = Felamimail_Model_Folder::decodeFolderName($folderData['globalName']); $isSelectable = $this->_isSelectable($folderData, $_account); $folder = Felamimail_Controller_Folder::getInstance()->getByBackendAndGlobalName($_account->getId(), $folderData['globalName']); $folder->is_selectable = $isSelectable; $folder->supports_condstore = $this->_supportsCondStore($folder, $_account); $folder->imap_status = Felamimail_Model_Folder::IMAP_STATUS_OK; $folder->has_children = $folderData['hasChildren'] == '1'; $folder->parent = $parentFolder; if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Update cached folder ' . $folderData['globalName']); } } catch (Tinebase_Exception_NotFound $tenf) { // create new folder if (empty($folderData['localName'])) { // skip if (Tinebase_Core::isLogLevel(Zend_Log::INFO)) { Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . ' Do not add folder ' . $folderData['globalName'] . '. Localname is empty.'); } continue; } else { $delimiter = strlen($folderData['delimiter']) === 1 ? $folderData['delimiter'] : ''; $folder = new Felamimail_Model_Folder(array('localname' => $folderData['localName'], 'globalname' => $folderData['globalName'], 'is_selectable' => $isSelectable, 'supports_condstore' => $this->_supportsCondStore($folderData['globalName'], $_account), 'has_children' => $folderData['hasChildren'] == '1', 'account_id' => $_account->getId(), 'imap_timestamp' => Tinebase_DateTime::now(), 'imap_status' => Felamimail_Model_Folder::IMAP_STATUS_OK, 'user_id' => Tinebase_Core::getUser()->getId(), 'parent' => $parentFolder, 'system_folder' => in_array(strtolower($folderData['localName']), $systemFolders), 'delimiter' => $delimiter)); // update delimiter setting of account if ($folder->delimiter && $folder->delimiter !== $_account->delimiter && $folder->localname === 'INBOX') { $_account->delimiter = $folder->delimiter; $_account = Felamimail_Controller_Account::getInstance()->update($_account); } if (Tinebase_Core::isLogLevel(Zend_Log::INFO)) { Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . ' Adding new folder ' . $folderData['globalName'] . ' to cache.'); } if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) { Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . print_r($folder->toArray(), true)); } $folder = $this->_backend->create($folder); } } $result->addRecord($folder); } if (count($_folders) > 0) { $this->_removeFromCache($_account, $parentFolder, $result->getArrayOfIds()); } return $result; }
/** * import the addressbook from egw14 * * @param string $_oldTableName [OPTIONAL] * @param int $_useOldId [OPTIONAL] * * @todo use old group name for the (shared) container ? * @todo add more config params ( */ public function importAddressbook($_oldTableName = NULL, $_useOldId = TRUE) { // did nothing //@set_time_limit (120); $sharedContactsGroupId = -15; $sharedContactsContainerName = "Metaways Kontakte"; $setFileasFromName = TRUE; $tableName = $_oldTableName != NULL ? $_oldTableName : $this->oldTablePrefix . 'addressbook'; $contactsTable = new Tinebase_Db_Table(array('name' => $tableName)); // get contacts $contacts = $contactsTable->fetchAll(); // get categories $categories = $this->getCategories(); echo "Import Contacts from table " . $tableName . " ... <br/>"; foreach ($contacts as $contact) { echo "importing " . $contact->n_given . " " . $contact->n_family . " ..."; /******************** add container ************************/ if ($contact->contact_owner > 0) { // personal container for owner try { $container = Tinebase_Container::getInstance()->getContainerByName('Addressbook', 'Personal Contacts', Tinebase_Model_Container::TYPE_PERSONAL, Tinebase_Core::getUser()); } catch (Tinebase_Exception_NotFound $e) { $container = new Tinebase_Model_Container(array('name' => 'Personal Contacts', 'type' => Tinebase_Model_Container::TYPE_PERSONAL, 'owner_id' => Tinebase_Core::getUser(), 'backend' => 'Sql', 'application_id' => Tinebase_Application::getInstance()->getApplicationByName('Addressbook')->getId())); $container = Tinebase_Container::getInstance()->addContainer($container, NULL, TRUE); } } else { if ($contact->contact_owner == $sharedContactsGroupId) { // default users group -> shared container $userGroup = Tinebase_Group::getInstance()->getGroupByName('Users'); try { $container = Tinebase_Container::getInstance()->getContainerByName('Addressbook', $sharedContactsContainerName, Tinebase_Model_Container::TYPE_SHARED); } catch (Tinebase_Exception_NotFound $e) { $container = new Tinebase_Model_Container(array('name' => $sharedContactsContainerName, 'type' => Tinebase_Model_Container::TYPE_SHARED, 'backend' => 'Sql', 'application_id' => Tinebase_Application::getInstance()->getApplicationByName('Addressbook')->getId())); $container = Tinebase_Container::getInstance()->addContainer($container, NULL, TRUE); Tinebase_Container::getInstance()->addGrants($container, Tinebase_Acl_Rights::ACCOUNT_TYPE_GROUP, $userGroup, array(Tinebase_Model_Grants::GRANT_READ, Tinebase_Model_Grants::GRANT_ADD, Tinebase_Model_Grants::GRANT_EDIT, Tinebase_Model_Grants::GRANT_DELETE), TRUE); } } else { echo "skipped.<br/>"; continue; } } $containerId = $container->getId(); /******************** set fileas ************************/ if ($setFileasFromName) { $fileas = ""; if (!empty($contact->n_family)) { if (!empty($contact->n_given)) { $fileas = $contact->n_family . ", " . $contact->n_given; } else { $fileas = $contact->n_family; } } else { $fileas = $contact->n_given; } if (empty($fileas)) { $fileas = $contact->org_name; } elseif (!empty($contact->n_middle)) { $fileas .= " " . $contact->n_middle; } } else { $fileas = empty($contact->n_fileas) ? $contact->org_name : $contact->n_fileas; } /******************** set urls (add 'http://' if missing) ************************/ if (!preg_match("/https*:\\/\\//i", $contact->contact_url) && !empty($contact->contact_url)) { $url = "http://" . $contact->contact_url; } else { $url = $contact->contact_url; } if (!preg_match("/https*:\\/\\//i", $contact->contact_url_home) && !empty($contact->contact_url_home)) { $urlHome = "http://" . $contact->contact_url_home; } else { $urlHome = $contact->contact_url_home; } /******************** create contact record ************************/ $tineContact = new Addressbook_Model_Contact(array('id' => $_useOldId ? $contact->contact_id : 0, 'account_id' => $contact->account_id, 'owner' => $containerId, 'n_family' => empty($contact->n_family) ? 'imported' : $contact->n_family, 'n_fileas' => $fileas, 'n_fn' => empty($contact->n_fn) ? 'imported' : $contact->n_fn, 'adr_one_countryname' => isset($this->countryMapping[$contact->adr_one_countryname]) ? $this->countryMapping[$contact->adr_one_countryname] : "", 'adr_one_locality' => $contact->adr_one_locality, 'adr_one_postalcode' => $contact->adr_one_postalcode, 'adr_one_region' => $contact->adr_one_region, 'adr_one_street' => $contact->adr_one_street, 'adr_one_street2' => $contact->adr_one_street2, 'adr_two_countryname' => isset($this->countryMapping[$contact->adr_two_countryname]) ? $this->countryMapping[$contact->adr_two_countryname] : "", 'adr_two_locality' => $contact->adr_two_locality, 'adr_two_postalcode' => $contact->adr_two_postalcode, 'adr_two_region' => $contact->adr_two_region, 'adr_two_street' => $contact->adr_two_street, 'adr_two_street2' => $contact->adr_two_street2, 'last_modified_time' => new Tinebase_DateTime($contact->contact_modified), 'assistent' => $contact->contact_assistent, 'bday' => $contact->contact_bday, 'email' => $contact->contact_email, 'email_home' => $contact->contact_email_home, 'note' => $contact->contact_note, 'role' => $contact->contact_role, 'title' => $contact->contact_title, 'url' => $url, 'url_home' => $urlHome, 'n_given' => $contact->n_given, 'n_middle' => $contact->n_middle, 'n_prefix' => $contact->n_prefix, 'n_suffix' => $contact->n_suffix, 'org_name' => $contact->org_name, 'org_unit' => $contact->org_unit, 'tel_assistent' => $contact->tel_assistent, 'tel_car' => $contact->tel_car, 'tel_cell' => $contact->tel_cell, 'tel_cell_private' => $contact->tel_cell_private, 'tel_fax' => $contact->tel_fax, 'tel_fax_home' => $contact->tel_fax_home, 'tel_home' => $contact->tel_home, 'tel_pager' => $contact->tel_pager, 'tel_work' => $contact->tel_work, 'tags' => array())); $tineContact = Addressbook_Controller_Contact::getInstance()->create($tineContact); echo " ok.<br/>"; // get categories -> tags if (!empty($contact->cat_id)) { $catIds = explode(',', $contact->cat_id); $filter = new Tinebase_Model_TagFilter(array('name' => '%', 'application' => 'Addressbook')); $paging = new Tinebase_Model_Pagination(); $contactTags = new Tinebase_Record_RecordSet('Tinebase_Model_Tag'); foreach ($catIds as $catId) { if (isset($categories[$catId])) { $filter->name = $categories[$catId]->cat_name; $tags = Tinebase_Tags::getInstance()->searchTags($filter, $paging)->toArray(); if (empty($tags)) { $tag = new Tinebase_Model_Tag(array('type' => Tinebase_Model_Tag::TYPE_SHARED, 'name' => $categories[$catId]->cat_name)); $tag = Tinebase_Tags::getInstance()->createTag($tag); $contactTags->addRecord($tag); } else { $contactTags->addRecord(new Tinebase_Model_Tag($tags[0])); } } } $tineContact->tags = $contactTags; Tinebase_Tags::getInstance()->setTagsOfRecord($tineContact); } } echo "done! got " . sizeof($contacts) . " contacts.<br>"; }
/** * prepare message parts that could be interesting for other apps * * @param Expressomail_Model_Message $_message */ public function prepareAndProcessParts(Expressomail_Model_Message $_message) { $preparedParts = new Tinebase_Record_RecordSet('Expressomail_Model_PreparedMessagePart'); foreach ($this->_supportedForeignContentTypes as $application => $contentType) { if (!Tinebase_Application::getInstance()->isInstalled($application) || !Tinebase_Core::getUser()->hasRight($application, Tinebase_Acl_Rights::RUN)) { if (Tinebase_Core::isLogLevel(Zend_Log::INFO)) { Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . ' ' . $application . ' not installed or access denied.'); } continue; } if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Looking for ' . $application . '[' . $contentType . '] content ...'); } $parts = $_message->getBodyParts(NULL, $contentType); foreach ($parts as $partId => $partData) { if ($partData['contentType'] !== $contentType) { continue; } if (Tinebase_Core::isLogLevel(Zend_Log::INFO)) { Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . ' ' . $application . '[' . $contentType . '] content found.'); } $preparedPart = $this->_getForeignMessagePart($_message, $partId, $partData); if ($preparedPart) { $this->_processForeignMessagePart($application, $preparedPart); $preparedParts->addRecord(new Expressomail_Model_PreparedMessagePart(array('id' => $_message->getId() . '_' . $partId, 'contentType' => $contentType, 'preparedData' => $preparedPart))); } } } $_message->preparedParts = $preparedParts; }
/** * copy or move an array of nodes identified by their path * * @param array $_sourceFilenames array->multiple * @param string|array $_destinationFilenames string->singlefile OR directory, array->multiple files * @param string $_action copy|move * @param boolean $_forceOverwrite * @return Tinebase_Record_RecordSet of Tinebase_Model_Tree_Node */ protected function _copyOrMoveNodes($_sourceFilenames, $_destinationFilenames, $_action, $_forceOverwrite = FALSE) { $result = new Tinebase_Record_RecordSet('Tinebase_Model_Tree_Node'); $nodeExistsException = NULL; foreach ($_sourceFilenames as $idx => $source) { $sourcePathRecord = Tinebase_Model_Tree_Node_Path::createFromPath($this->addBasePath($source)); $destinationPathRecord = $this->_getDestinationPath($_destinationFilenames, $idx, $sourcePathRecord); if ($this->_backend->fileExists($destinationPathRecord->statpath) && $sourcePathRecord->flatpath == $destinationPathRecord->flatpath) { throw new Filemanager_Exception_DestinationIsSameNode(); } // test if destination is subfolder of source $dest = explode('/', $destinationPathRecord->statpath); $source = explode('/', $sourcePathRecord->statpath); $isSub = TRUE; for ($i = 0; $i < count($source); $i++) { if (!isset($dest[$i])) { break; } if ($source[$i] != $dest[$i]) { $isSub = FALSE; } } if ($isSub) { throw new Filemanager_Exception_DestinationIsOwnChild(); } try { if ($_action === 'move') { $node = $this->_moveNode($sourcePathRecord, $destinationPathRecord, $_forceOverwrite); } else { if ($_action === 'copy') { $node = $this->_copyNode($sourcePathRecord, $destinationPathRecord, $_forceOverwrite); } } $result->addRecord($node); } catch (Filemanager_Exception_NodeExists $fene) { $nodeExistsException = $this->_handleNodeExistsException($fene, $nodeExistsException); } } $this->resolveContainerAndAddPath($result, $destinationPathRecord->getParent()); if ($nodeExistsException) { // @todo add correctly moved/copied files here? throw $nodeExistsException; } return $result; }
/** * tests the correct values of the freetime record * @see 0009168: HR saving sickness days days_count failure * https://forge.tine20.org/mantisbt/view.php?id=9168 */ public function testFirstAndLastDayOfFreetime() { $employmentBegin = new Tinebase_DateTime('2012-12-15'); $employmentEnd = new Tinebase_DateTime('2014-06-30'); $referenceDate = new Tinebase_DateTime('2013-10-10'); $contractController = HumanResources_Controller_Contract::getInstance(); $employeeController = HumanResources_Controller_Employee::getInstance(); $contractBackend = new HumanResources_Backend_Contract(); $employee = $this->_getEmployee('unittest'); $employee->employment_begin = $employmentBegin; $employee->employment_end = $employmentEnd; $contract1 = $this->_getContract(); $contract1->start_date = $employmentBegin; $contract1->workingtime_json = '{"days": [8,8,8,8,8,0,0]}'; $contract1->vacation_days = 25; $rs = new Tinebase_Record_RecordSet('HumanResources_Model_Contract'); $rs->addRecord($contract1); $employee->contracts = $rs; $employee = $employeeController->create($employee); $accountController = Humanresources_Controller_Account::getInstance(); $accountController->createMissingAccounts(2013, $employee); $accountsFilter = array(array('field' => "employee_id", 'operator' => "AND", 'value' => array(array('field' => ':id', 'operator' => 'equals', 'value' => $employee->getId())))); $result = $this->_json->searchAccounts($accountsFilter, array('sort' => 'year', 'dir' => 'DESC')); $this->assertEquals('3', $result['totalcount'], 'One accounts should have been found!'); $accountId2013 = $result['results'][2]['id']; $day = Tinebase_DateTime::now()->setTimezone('UTC')->setDate(2013, 9, 23)->setTime(16, 0, 0); $newFreeTime = array('account_id' => $accountId2013, 'employee_id' => $employee->getId(), 'type' => 'vacation', 'status' => 'ACCEPTED'); $newFreeTime['freedays'] = array(array('duration' => '1', 'date' => $day->toString()), array('duration' => '1', 'date' => $day->addDay(1)->toString()), array('duration' => '1', 'date' => $day->addDay(1)->toString())); $freetime = $this->_json->saveFreeTime($newFreeTime); $this->assertEquals(3, count($freetime['freedays'])); $this->assertEquals('2013-09-23', substr($freetime['firstday_date'], 0, 10)); $this->assertEquals('2013-09-25', substr($freetime['lastday_date'], 0, 10)); }
/** * get matching preferences from recordset with multiple prefs) * * @param Tinebase_Record_RecordSet $_preferences */ public function getMatchingPreferences(Tinebase_Record_RecordSet $_preferences) { $_preferences->addIndices(array('name')); // get unique names, the matching preference and add it to result set $result = new Tinebase_Record_RecordSet('Tinebase_Model_Preference'); $uniqueNames = array_unique($_preferences->name); foreach ($uniqueNames as $name) { $singlePrefSet = $_preferences->filter('name', $name); $result->addRecord($this->_getMatchingPreference($singlePrefSet)); } return $result; }
/** * sort folder record set * - begin with INBOX + other standard/system folders, add other folders * * @param Tinebase_Record_RecordSet $_folders * @param string $_parentFolder * @return Tinebase_Record_RecordSet */ protected function _sortFolders(Tinebase_Record_RecordSet $_folders, $_parentFolder) { $sortedFolders = new Tinebase_Record_RecordSet('Felamimail_Model_Folder'); $_folders->sort('localname', 'ASC', 'natcasesort'); $_folders->addIndices(array('globalname')); Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . ' Sorting subfolders of "' . $_parentFolder . '".'); if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) { Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' ' . print_r($_folders->globalname, TRUE)); } foreach ($this->_systemFolders as $systemFolderName) { $folders = $_folders->filter('globalname', '@^' . $systemFolderName . '$@i', TRUE); //if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' ' . $systemFolderName . ' => ' . print_r($folders->toArray(), TRUE)); if (count($folders) > 0) { $sortedFolders->addRecord($folders->getFirstRecord()); } } foreach ($_folders as $folder) { if (!in_array(strtolower($folder->globalname), $this->_systemFolders)) { $sortedFolders->addRecord($folder); } } //if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' ' . print_r($sortedFolders->globalname, TRUE)); return $sortedFolders; }
/** * calls method with each event matching given rid * * breaks if method returns false * * @param Calendar_Model_Event $event * @param array $rid * @param callable $method * @return Tinebase_Record_RecordSet affectedEvents */ protected function _iterateByRid($event, $rid, $method) { $affectedEvents = new Tinebase_Record_RecordSet('Calendar_Model_Event'); if (!$rid || in_array('M', $rid)) { $affectedEvents->addRecord($event); } if ($event->exdate instanceof Tinebase_Record_RecordSet) { foreach ($event->exdate as $exception) { if (!$rid) { $affectedEvents->addRecord($exception); } } } foreach ($affectedEvents as $record) { if ($method($record) === false) { break; } } return $affectedEvents; }
/** * resolves given attendee for json representation * * @TODO move status_authkey cleanup elsewhere * * @param Tinebase_Record_RecordSet|array $_eventAttendee * @param bool $_resolveDisplayContainers * @param Calendar_Model_Event|array $_events */ public static function resolveAttendee($_eventAttendee, $_resolveDisplayContainers = TRUE, $_events = NULL) { $eventAttendee = $_eventAttendee instanceof Tinebase_Record_RecordSet ? array($_eventAttendee) : $_eventAttendee; $events = $_events instanceof Tinebase_Record_Abstract ? array($_events) : $_events; // set containing all attendee $allAttendee = new Tinebase_Record_RecordSet('Calendar_Model_Attender'); $typeMap = array(); // build type map foreach ($eventAttendee as $attendee) { foreach ($attendee as $attender) { $allAttendee->addRecord($attender); if ($attender->user_id instanceof Tinebase_Record_Abstract) { // already resolved continue; } elseif (array_key_exists($attender->user_type, self::$_resovedAttendeeCache) && array_key_exists($attender->user_id, self::$_resovedAttendeeCache[$attender->user_type])) { // already in cache $attender->user_id = self::$_resovedAttendeeCache[$attender->user_type][$attender->user_id]; } else { if (!array_key_exists($attender->user_type, $typeMap)) { $typeMap[$attender->user_type] = array(); } $typeMap[$attender->user_type][] = $attender->user_id; } } } // resolve display containers if ($_resolveDisplayContainers) { $displaycontainerIds = array_diff($allAttendee->displaycontainer_id, array('')); if (!empty($displaycontainerIds)) { Tinebase_Container::getInstance()->getGrantsOfRecords($allAttendee, Tinebase_Core::getUser(), 'displaycontainer_id'); } } // get all user_id entries foreach ($typeMap as $type => $ids) { switch ($type) { case self::USERTYPE_USER: case self::USERTYPE_GROUPMEMBER: $resolveCf = Addressbook_Controller_Contact::getInstance()->resolveCustomfields(FALSE); $typeMap[$type] = Addressbook_Controller_Contact::getInstance()->getMultiple(array_unique($ids), TRUE); Addressbook_Controller_Contact::getInstance()->resolveCustomfields($resolveCf); break; case self::USERTYPE_GROUP: case Calendar_Model_AttenderFilter::USERTYPE_MEMBEROF: // first fetch the groups, then the lists identified by list_id $typeMap[$type] = Tinebase_Group::getInstance()->getMultiple(array_unique($ids)); $typeMap[self::USERTYPE_LIST] = Addressbook_Controller_List::getInstance()->getMultiple($typeMap[$type]->list_id, true); break; case self::USERTYPE_RESOURCE: $typeMap[$type] = Calendar_Controller_Resource::getInstance()->getMultiple(array_unique($ids)); break; default: throw new Exception("type {$type} not supported"); break; } } // sort entries in foreach ($eventAttendee as $attendee) { foreach ($attendee as $attender) { if ($attender->user_id instanceof Tinebase_Record_Abstract) { // allready resolved from cache continue; } $idx = false; if ($attender->user_type == self::USERTYPE_GROUP) { $attendeeTypeSet = $typeMap[$attender->user_type]; $idx = $attendeeTypeSet->getIndexById($attender->user_id); if ($idx !== false) { $group = $attendeeTypeSet[$idx]; $idx = false; $attendeeTypeSet = $typeMap[self::USERTYPE_LIST]; $idx = $attendeeTypeSet->getIndexById($group->list_id); } } else { $attendeeTypeSet = $typeMap[$attender->user_type]; $idx = $attendeeTypeSet->getIndexById($attender->user_id); } if ($idx !== false) { // copy to cache if (!array_key_exists($attender->user_type, self::$_resovedAttendeeCache)) { self::$_resovedAttendeeCache[$attender->user_type] = array(); } self::$_resovedAttendeeCache[$attender->user_type][$attender->user_id] = $attendeeTypeSet[$idx]; $attender->user_id = $attendeeTypeSet[$idx]; } } } foreach ($eventAttendee as $idx => $attendee) { $event = is_array($events) && array_key_exists($idx, $events) ? $events[$idx] : NULL; foreach ($attendee as $attender) { // keep authkey if user has editGrant to displaycontainer if (isset($attender['displaycontainer_id']) && !is_scalar($attender['displaycontainer_id']) && array_key_exists(Tinebase_Model_Grants::GRANT_EDIT, $attender['displaycontainer_id']['account_grants']) && $attender['displaycontainer_id']['account_grants'][Tinebase_Model_Grants::GRANT_EDIT]) { continue; } // keep authkey if attender resource OR contact (no account) and user has editGrant for event if (in_array($attender->user_type, array(self::USERTYPE_USER, self::USERTYPE_RESOURCE)) && $attender->user_id instanceof Tinebase_Record_Abstract && (!$attender->user_id->has('account_id') || !$attender->user_id->account_id) && (!$event || $event->{Tinebase_Model_Grants::GRANT_EDIT})) { continue; } $attender->status_authkey = NULL; } } }