/** * the singleton pattern * * @return Tinebase_Tags */ public static function getInstance() { if (self::$_instance === NULL) { self::$_instance = new Tinebase_Tags(); } return self::$_instance; }
/** * resolve containers, tags and users * * @param Tinebase_Record_RecordSet $_records * @param array $_resolveUserFields */ public static function resolveContainerTagsUsers(Tinebase_Record_RecordSet $_records, $_resolveUserFields = array()) { if ($_records->getFirstRecord()->has('container_id')) { Tinebase_Container::getInstance()->getGrantsOfRecords($_records, Tinebase_Core::getUser()); } if ($_records->getFirstRecord()->has('tags')) { Tinebase_Tags::getInstance()->getMultipleTagsOfRecords($_records); } if (array_key_exists($_records->getRecordClassName(), $_resolveUserFields)) { Tinebase_User::getInstance()->resolveMultipleUsers($_records, $_resolveUserFields[$_records->getRecordClassName()], TRUE); } }
/** * returns array with the filter settings of this filter * * @param bool $_valueToJson resolve value for json api? * @return array */ public function toArray($_valueToJson = false) { $result = parent::toArray($_valueToJson); if ($_valueToJson == true) { $tags = Tinebase_Tags::getInstance()->getTagsById($this->_value)->toArray(); if (count($tags) > 0) { $result['value'] = is_array($this->_value) ? $tags : $tags[0]; } else { $result['value'] = ''; } } return $result; }
/** * 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; }
/** * test if the application parameter is used properly */ public function testSearchTagsForApplication() { $this->_createSharedTag(); $filter = new Tinebase_Model_TagFilter(array()); $ids = $this->_instance->searchTags($filter)->getId(); $this->_instance->deleteTags($ids); $t1 = $this->_createSharedTag('tag1'); $t2 = $this->_createSharedTag('tag2'); // this tag should not occur, search is in the addressbook application $crmAppId = Tinebase_Application::getInstance()->getApplicationByName('Crm')->getId(); $t3 = $this->_createSharedTag('tag3', array($crmAppId)); $filter = new Tinebase_Model_TagFilter(array('application' => 'Addressbook')); $tags = $this->_instance->searchTags($filter); $this->assertEquals(2, $tags->count()); }
/** * test search tags with 'attached' filter */ public function testSearchTagsByForeignFilter() { $sharedTag = $this->_createSharedTag(); $filter = new Addressbook_Model_ContactFilter(); Tinebase_Tags::getInstance()->attachTagToMultipleRecords($filter, $sharedTag); $tags = $this->_instance->searchTagsByForeignFilter($filter); $this->assertTrue(count($tags) > 0); $sharedTagInResult = NULL; foreach ($tags as $tag) { if ($tag->getId() === $sharedTag->getId()) { $sharedTagInResult = $tag; break; } } $this->assertTrue($sharedTagInResult instanceof Tinebase_Model_Tag, 'shared tag not found'); $this->assertEquals(Addressbook_Controller_Contact::getInstance()->searchCount($filter), $sharedTagInResult->selection_occurrence); }
/** * testCreateEvent */ public function testCreateEvent() { $scleverDisplayContainerId = Tinebase_Core::getPreference('Calendar')->getValueForUser(Calendar_Preference::DEFAULTCALENDAR, $this->_personas['sclever']->getId()); $contentSeqBefore = Tinebase_Container::getInstance()->getContentSequence($scleverDisplayContainerId); $eventData = $this->_getEvent()->toArray(); $tag = Tinebase_Tags::getInstance()->createTag(new Tinebase_Model_Tag(array('name' => 'phpunit-' . substr(Tinebase_Record_Abstract::generateUID(), 0, 10), 'type' => Tinebase_Model_Tag::TYPE_PERSONAL))); $eventData['tags'] = array($tag->toArray()); $note = new Tinebase_Model_Note(array('note' => 'very important note!', 'note_type_id' => Tinebase_Notes::getInstance()->getNoteTypes()->getFirstRecord()->getId())); $eventData['notes'] = array($note->toArray()); $persistentEventData = $this->_uit->saveEvent($eventData); $loadedEventData = $this->_uit->getEvent($persistentEventData['id']); $this->_assertJsonEvent($eventData, $loadedEventData, 'failed to create/load event'); $contentSeqAfter = Tinebase_Container::getInstance()->getContentSequence($scleverDisplayContainerId); $this->assertEquals($contentSeqBefore + 1, $contentSeqAfter, 'content sequence of display container should be increased by 1:' . $contentSeqAfter); $this->assertEquals($contentSeqAfter, Tinebase_Container::getInstance()->get($scleverDisplayContainerId)->content_seq); return $loadedEventData; }
/** * resolve and sanitize tags * * @param array $_autotagOptions * @return array */ protected function _handleAutotags($_autotagOptions) { $result = isset($_autotagOptions['tag']) ? $_autotagOptions['tag'] : $_autotagOptions; if (isset($result['name'])) { $result = array($result); } // resolve tags if they exist foreach ($result as $idx => $value) { if (isset($value['id'])) { try { $tag = Tinebase_Tags::getInstance()->get($value['id']); $result[$idx] = $tag->toArray(); } catch (Tinebase_Exception_NotFound $tenf) { // do nothing } } } return $result; }
/** * returns multiple records prepared for json transport * * NOTE: we can't use parent::_multipleRecordsToJson here because of the different container handling * * @param Tinebase_Record_RecordSet $_leads Crm_Model_Lead * @return array data */ protected function _multipleRecordsToJson(Tinebase_Record_RecordSet $_records, $_filter = NULL) { if (count($_records) == 0) { return array(); } switch ($_records->getRecordClassName()) { case 'Timetracker_Model_Timesheet': // resolve timeaccounts $timeaccountIds = $_records->timeaccount_id; $timeaccounts = $this->_timeaccountController->getMultiple(array_unique(array_values($timeaccountIds))); Timetracker_Model_TimeaccountGrants::getGrantsOfRecords($timeaccounts, Tinebase_Core::get('currentAccount')); foreach ($_records as $record) { $idx = $timeaccounts->getIndexById($record->timeaccount_id); if ($idx !== FALSE) { $record->timeaccount_id = $timeaccounts[$idx]; $record->timeaccount_id->account_grants = $this->_resolveTimesheetGrantsByTimeaccountGrants($record->timeaccount_id->account_grants, $record->account_id); } else { Tinebase_Core::getLogger()->warn(__METHOD__ . '::' . __LINE__ . ' Could not resolve timeaccount (id: ' . $record->timeaccount_id . '). No permission?'); } } // resolve user afterwards because we compare ids in _resolveTimesheetGrantsByTimeaccountGrants() Tinebase_User::getInstance()->resolveMultipleUsers($_records, array('account_id', 'created_by', 'last_modified_by'), true); break; case 'Timetracker_Model_Timeaccount': // resolve timeaccounts grants Timetracker_Model_TimeaccountGrants::getGrantsOfRecords($_records, Tinebase_Core::get('currentAccount')); $this->_resolveTimeaccountGrants($_records); break; } Tinebase_Tags::getInstance()->getMultipleTagsOfRecords($_records); $_records->setTimezone(Tinebase_Core::get('userTimeZone')); $_records->convertDates = true; $result = $_records->toArray(); return $result; }
/** * parse categories from Tine20 model to VCard and attach it to VCard $card * * @param Tinebase_Record_Abstract $record * @param Sabre\VObject\Component $card */ protected function _fromTine20ModelAddCategories(Tinebase_Record_Abstract $record, Sabre\VObject\Component $card) { if (!isset($record->tags)) { // If the record has not been populated yet with tags, let's try to get them all and update the record $record->tags = Tinebase_Tags::getInstance()->getTagsOfRecord($record); } if (isset($record->tags) && count($record->tags) > 0) { // we have some tags attached, so let's convert them and attach to the VCARD $card->add('CATEGORIES', (array) $record->tags->name); } }
/** * get special options * * @param string $_value * @return array */ protected function _getSpecialOptions($_value) { $translate = Tinebase_Translation::getTranslation($this->_application); $result = array(); switch ($_value) { case self::TSODSEXPORTCONFIG: // get names from import export definitions $filter = new Tinebase_Model_ImportExportDefinitionFilter(array(array('field' => 'plugin', 'operator' => 'equals', 'value' => 'Timetracker_Export_Ods_Timesheet'))); $configs = Tinebase_ImportExportDefinition::getInstance()->search($filter); if (!empty($configs)) { foreach ($configs as $tsConfig) { $result[] = array($tsConfig->name, $tsConfig->name); } } else { $result[] = array('default', $translate->_('default')); } break; case self::QUICKTAG: // Get all shared tags $tagController = Tinebase_Tags::getInstance(); $filter = new Tinebase_Model_TagFilter(array('type' => Tinebase_Model_Tag::TYPE_SHARED)); $tags = $tagController->searchTags($filter); $availableTags = array(); /* @var $tag Tinebase_Model_Tag */ foreach ($tags as $tag) { $availableTags[] = array($tag->id, $tag->name); } return $availableTags; break; default: $result = parent::_getSpecialOptions($_value); } return $result; }
/** * resolve containers and tags * * @param Tinebase_Record_RecordSet $_records * @param array $_resolveProperties */ public static function resolveContainersAndTags(Tinebase_Record_RecordSet $_records, $_resolveProperties = array('container_id', 'tags')) { $firstRecord = $_records->getFirstRecord(); if ($firstRecord) { if ($firstRecord->has('container_id') && in_array('container_id', $_resolveProperties)) { Tinebase_Container::getInstance()->getGrantsOfRecords($_records, Tinebase_Core::getUser()); } if ($firstRecord->has('tags') && in_array('tags', $_resolveProperties)) { Tinebase_Tags::getInstance()->getMultipleTagsOfRecords($_records); } } }
/** * create new tag with rights and context * * @param array $_catData * @return string tag_id */ protected function _createTag($_catData) { $tags = Tinebase_Tags::getInstance()->searchTags(new Tinebase_Model_TagFilter(array('name' => $this->_encode($_catData['cat_name']), 'type' => Tinebase_Model_Tag::TYPE_SHARED)), new Tinebase_Model_Pagination()); if (count($tags) == 0) { $catData = unserialize($_catData['cat_data']); // create tag $sharedTag = new Tinebase_Model_Tag(array('type' => Tinebase_Model_Tag::TYPE_SHARED, 'name' => $this->_encode($_catData['cat_name']), 'description' => 'Imported timesheet category ' . $this->_encode($_catData['cat_name']), 'color' => !empty($catData['color']) ? $catData['color'] : '#009B31')); $newTag = Tinebase_Tags::getInstance()->createTag($sharedTag); // set rights $tagRights = new Tinebase_Model_TagRight(array('tag_id' => $newTag->getId(), 'account_type' => Tinebase_Acl_Rights::ACCOUNT_TYPE_ANYONE, 'account_id' => 0, 'view_right' => TRUE, 'use_right' => TRUE)); Tinebase_Tags::getInstance()->setRights($tagRights); // set context (Timetracker app) $tagContext = array(Tinebase_Application::getInstance()->getApplicationByName('Timetracker')->getId()); Tinebase_Tags::getInstance()->setContexts($tagContext, $newTag->getId()); $result = $newTag->getId(); } else { $result = $tags[0]->getId(); } // return new tag id return $result; }
/** * delete multiple tags * * @param array $_tagIds * @void * * @todo replace this by parent::delete() */ public function delete($_tagIds) { $this->checkRight('MANAGE_SHARED_TAGS'); Tinebase_Tags::getInstance()->deleteTags($_tagIds); }
/** * converts category to tag * * @param int $catId * @return string tagid */ public function getTag($catId) { if (!(isset($this->_tagMapCache[$catId]) || array_key_exists($catId, $this->_tagMapCache))) { $select = $this->_egwDb->select()->from(array('cats' => 'egw_categories'))->where($this->_egwDb->quoteInto($this->_egwDb->quoteIdentifier('cat_id') . ' = ?', $catId)); $cat = $this->_egwDb->fetchAll($select, NULL, Zend_Db::FETCH_ASSOC); $cat = count($cat) === 1 ? $cat[0] : NULL; if (!$cat) { $this->_log->DEBUG(__METHOD__ . '::' . __LINE__ . " category {$catId} not found in egw, skipping tag"); return $this->_tagMapCache[$catId] = NULL; } $tineDb = Tinebase_Core::getDb(); $select = $tineDb->select()->from(array('tags' => $tineDb->table_prefix . 'tags'))->where($tineDb->quoteInto($tineDb->quoteIdentifier('name') . ' LIKE ?', $cat['cat_name'])); $tag = $tineDb->fetchAll($select, NULL, Zend_Db::FETCH_ASSOC); $tag = count($tag) > 0 ? $tag[0] : NULL; if ($tag) { return $this->_tagMapCache[$catId] = $tag['id']; } // create tag $catData = unserialize($cat['cat_data']); $tagId = Tinebase_Record_Abstract::generateUID(); $tagType = $cat['cat_access'] == 'public' ? Tinebase_Model_Tag::TYPE_SHARED : Tinebase_Model_Tag::TYPE_PERSONAL; $tagOwner = $tagType == Tinebase_Model_Tag::TYPE_SHARED ? 0 : $this->mapAccountIdEgw2Tine($cat['cat_owner']); $this->_log->NOTICE(__METHOD__ . '::' . __LINE__ . " creating new {$tagType} tag '{$cat['cat_name']}'"); $tineDb->insert($tineDb->table_prefix . 'tags', array('id' => $tagId, 'type' => $tagType, 'owner' => $tagOwner, 'name' => $cat['cat_name'], 'description' => $cat['cat_description'], 'color' => $catData['color'], 'created_by' => $tagOwner ? $tagOwner : Tinebase_Core::getUser()->getId(), 'creation_time' => $cat['last_mod'] ? $this->convertDate($cat['last_mod']) : Tinebase_DateTime::now())); $right = new Tinebase_Model_TagRight(array('tag_id' => $tagId, 'account_type' => $tagType == Tinebase_Model_Tag::TYPE_SHARED ? Tinebase_Acl_Rights::ACCOUNT_TYPE_ANYONE : Tinebase_Acl_Rights::ACCOUNT_TYPE_USER, 'account_id' => $tagOwner, 'view_right' => true, 'use_right' => true)); Tinebase_Tags::getInstance()->setRights($right); Tinebase_Tags::getInstance()->setContexts(array(0), $tagId); $this->_tagMapCache[$catId] = $tagId; } return $this->_tagMapCache[$catId]; }
/** * converts Tinebase_Record_RecordSet to external format * * @param Tinebase_Record_RecordSet $_records * @param Tinebase_Model_Filter_FilterGroup $_filter * @param Tinebase_Model_Pagination $_pagination * * @return mixed */ public function fromTine20RecordSet(Tinebase_Record_RecordSet $_records = NULL, $_filter = NULL, $_pagination = NULL) { if (count($_records) == 0) { return array(); } Tinebase_Notes::getInstance()->getMultipleNotesOfRecords($_records); Tinebase_Tags::getInstance()->getMultipleTagsOfRecords($_records); if (Tinebase_Core::isFilesystemAvailable()) { Tinebase_FileSystem_RecordAttachments::getInstance()->getMultipleAttachmentsOfRecords($_records); } Calendar_Model_Attender::resolveAttendee($_records->attendee, TRUE, $_records); Calendar_Convert_Event_Json::resolveRrule($_records); Calendar_Controller_Event::getInstance()->getAlarms($_records); Calendar_Convert_Event_Json::resolveGrantsOfExternalOrganizers($_records); Calendar_Model_Rrule::mergeAndRemoveNonMatchingRecurrences($_records, $_filter); $_records->sortByPagination($_pagination); Tinebase_Frontend_Json_Abstract::resolveContainersAndTags($_records, array('container_id')); $_records->setTimezone(Tinebase_Core::getUserTimezone()); $_records->convertDates = true; $eventsData = $_records->toArray(); foreach ($eventsData as $idx => $eventData) { if (!(isset($eventData[Tinebase_Model_Grants::GRANT_READ]) || array_key_exists(Tinebase_Model_Grants::GRANT_READ, $eventData)) || !$eventData[Tinebase_Model_Grants::GRANT_READ]) { $eventsData[$idx] = array_intersect_key($eventsData[$idx], array_flip(array('id', 'dtstart', 'dtend', 'transp', 'is_all_day_event'))); } } return $eventsData; }
/** * resolve multiple record fields (Tinebase_ModelConfiguration._recordsFields) * * @param Tinebase_Record_RecordSet $_records * @param Tinebase_ModelConfiguration $modelConfiguration * @param boolean $multiple * @throws Tinebase_Exception_UnexpectedValue */ protected function _resolveMultipleRecordFields(Tinebase_Record_RecordSet $_records, $modelConfiguration = NULL, $multiple = false) { if (!$modelConfiguration || !$_records->count()) { return; } if (!($resolveFields = $modelConfiguration->recordsFields)) { return; } $ownIds = $_records->{$modelConfiguration->idProperty}; // iterate fields to resolve foreach ($resolveFields as $fieldKey => $c) { $config = $c['config']; // resolve records, if omitOnSearch is definitively set to FALSE (by default they won't be resolved on search) if ($multiple && !(isset($config['omitOnSearch']) && $config['omitOnSearch'] === FALSE)) { continue; } if (!isset($config['controllerClassName'])) { throw new Tinebase_Exception_UnexpectedValue('Controller class name needed'); } // fetch the fields by the refIfField /** @var Tinebase_Controller_Record_Interface|Tinebase_Controller_SearchInterface $controller */ /** @noinspection PhpUndefinedMethodInspection */ $controller = $config['controllerClassName']::getInstance(); $filterName = $config['filterClassName']; $filterArray = array(); // addFilters can be added and must be added if the same model resides in more than one records fields if (isset($config['addFilters']) && is_array($config['addFilters'])) { $filterArray = $config['addFilters']; } /** @var Tinebase_Model_Filter_FilterGroup $filter */ $filter = new $filterName($filterArray); $filter->addFilter(new Tinebase_Model_Filter_Id(array('field' => $config['refIdField'], 'operator' => 'in', 'value' => $ownIds))); $paging = NULL; if (isset($config['paging']) && is_array($config['paging'])) { $paging = new Tinebase_Model_Pagination($config['paging']); } $foreignRecords = $controller->search($filter, $paging); /** @var Tinebase_Record_Interface $foreignRecordClass */ $foreignRecordClass = $foreignRecords->getRecordClassName(); $foreignRecordModelConfiguration = $foreignRecordClass::getConfiguration(); $foreignRecords->setTimezone(Tinebase_Core::getUserTimezone()); $foreignRecords->convertDates = true; $fr = $foreignRecords->getFirstRecord(); // @todo: resolve alarms? // @todo: use parts parameter? if ($foreignRecordModelConfiguration->resolveRelated && $fr) { if ($fr->has('notes')) { Tinebase_Notes::getInstance()->getMultipleNotesOfRecords($foreignRecords); } if ($fr->has('tags')) { Tinebase_Tags::getInstance()->getMultipleTagsOfRecords($foreignRecords); } if ($fr->has('relations')) { $relations = Tinebase_Relations::getInstance()->getMultipleRelations($foreignRecordClass, 'Sql', $foreignRecords->{$fr->getIdProperty()}); $foreignRecords->setByIndices('relations', $relations); } if ($fr->has('customfields')) { Tinebase_CustomField::getInstance()->resolveMultipleCustomfields($foreignRecords); } if ($fr->has('attachments') && Tinebase_Core::isFilesystemAvailable()) { Tinebase_FileSystem_RecordAttachments::getInstance()->getMultipleAttachmentsOfRecords($foreignRecords); } } if ($foreignRecords->count() > 0) { /** @var Tinebase_Record_Interface $record */ foreach ($_records as $record) { $filtered = $foreignRecords->filter($config['refIdField'], $record->getId())->toArray(); $filtered = $this->_resolveAfterToArray($filtered, $foreignRecordModelConfiguration, TRUE); $record->{$fieldKey} = $filtered; } } else { $_records->{$fieldKey} = NULL; } } }
/** * add auto tags from options * * @param Tinebase_Record_Abstract $_record */ protected function _addAutoTags($_record) { $autotags = $this->_sanitizeAutotagsOption(); if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Trying to add ' . count($autotags) . ' autotag(s) to record.'); } if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' ' . print_r($autotags, TRUE)); } if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' ' . print_r($_record->toArray(), TRUE)); } $tags = $_record->tags instanceof Tinebase_Record_RecordSet ? $_record->tags : new Tinebase_Record_RecordSet('Tinebase_Model_Tag'); foreach ($autotags as $tagData) { if (is_string($tagData)) { try { $tag = Tinebase_Tags::getInstance()->get($tagData); } catch (Tinebase_Exception_NotFound $tenf) { if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' ' . $tenf); } $tag = NULL; } } else { $tagData = $this->_doAutoTagReplacements($tagData); $tag = $this->_getSingleTag($tagData['name'], $tagData); } if ($tag !== NULL) { $tags->addRecord($tag); } } $_record->tags = $tags; if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' ' . print_r($tags->toArray(), TRUE)); } }
/** * returns the value of a matrix field * * @param Zend_Config $field * @param Tinebase_Record_Interface $record * @throws Tinebase_Exception_Data * @return number */ protected function _getMatrixCellValue($field, $record) { $result = 0; switch ($field->type) { case 'tags': if (!isset($this->_matrixCache[$field->identifier])) { $this->_matrixCache[$field->identifier] = array(); } if (!isset($this->_matrixCache[$field->identifier][$record->getId()])) { // clear cache, its not needed anymore (could have been filled by the previous record) $this->_matrixCache[$field->identifier] = array(); $this->_matrixCache[$field->identifier][$record->getId()] = Tinebase_Tags::getInstance()->getTagsOfRecord($record); } $result = $this->_matrixCache[$field->identifier][$record->getId()]->filter('name', $field->identifier)->count(); break; default: throw new Tinebase_Exception_Data('Other types than tags are not supported at the moment.'); } return $result; }
/** * set relations / tags / alarms * * @param Tinebase_Record_Interface $_updatedRecord the just updated record * @param Tinebase_Record_Interface $_record the update record */ protected function _setRelatedData($_updatedRecord, $_record) { if ($_record->has('relations') && isset($_record->relations) && is_array($_record->relations)) { Tinebase_Relations::getInstance()->setRelations($this->_modelName, $this->_backend->getType(), $_updatedRecord->getId(), $_record->relations); } if ($_record->has('tags') && isset($_record->tags) && (is_array($_record->tags) || $_record->tags instanceof Tinebase_Record_RecordSet)) { $_updatedRecord->tags = $_record->tags; Tinebase_Tags::getInstance()->setTagsOfRecord($_updatedRecord); } if ($_record->has('alarms') && isset($_record->alarms)) { $_updatedRecord->alarms = $_record->alarms; $this->_saveAlarms($_record); } }
/** * converts an array of tags names to a recordSet of Tinebase_Model_Tag * * @param iteratable $tagNames * @param bool $implicitAddMissingTags * @return Tinebase_Record_RecordSet */ public static function resolveTagNameToTag($tagNames, $applicationName, $implicitAddMissingTags = true) { if (empty($tagNames)) { return new Tinebase_Record_RecordSet('Tinebase_Model_Tag'); } $resolvedTags = array(); foreach ((array) $tagNames as $tagName) { if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Trying to allocate tag ' . $tagName); } $tagName = trim($tagName); if (empty($tagName)) { continue; } $existingTags = Tinebase_Tags::getInstance()->searchTags(new Tinebase_Model_TagFilter(array('name' => $tagName, 'application' => $applicationName)), new Tinebase_Model_Pagination(array('sort' => 'type', 'dir' => 'DESC', 'limit' => 1))); if (count($existingTags) === 1) { //var_dump($existingTags->toArray()); $resolvedTags[] = $existingTags->getFirstRecord(); } elseif ($implicitAddMissingTags === true) { // No tag found, lets create a personal tag $resolvedTag = Tinebase_Tags::GetInstance()->createTag(new Tinebase_Model_Tag(array('type' => Tinebase_Model_Tag::TYPE_PERSONAL, 'name' => $tagName))); $resolvedTags[] = $resolvedTag; } } return new Tinebase_Record_RecordSet('Tinebase_Model_Tag', $resolvedTags); }
/** * create some shared tags */ protected function _createSharedTags() { $appList = Tinebase_Application::getInstance()->getApplicationsByState(Tinebase_Application::ENABLED)->toArray(); $adminJson = new Admin_Frontend_Json(); foreach ($this->_tagNames as $tagName) { $savedSharedTag = Tinebase_Tags::getInstance()->createTag(new Tinebase_Model_Tag(array('type' => Tinebase_Model_Tag::TYPE_SHARED, 'name' => $tagName, 'description' => 'this is the shared tag ' . $tagName, 'color' => '#' . $this->_generateRandomColor(), 'contexts' => array('any'), 'appList' => $appList, 'rights' => array(array('account_type' => Tinebase_Acl_Rights::ACCOUNT_TYPE_ANYONE, 'account_id' => 0, 'view_right' => TRUE, 'use_right' => TRUE))))); } }
public function testAttachMultipleTagsToMultipleRecorstds() { $contact1 = $this->_addContact('contact1'); $contact2 = $this->_addContact('contact2'); $tag1 = Tinebase_Tags::getInstance()->create($this->_getTag(Tinebase_Model_Tag::TYPE_PERSONAL, 'tag1')); $tag2 = Tinebase_Tags::getInstance()->create($this->_getTag(Tinebase_Model_Tag::TYPE_PERSONAL, 'tag2')); $filter = array(array('field' => 'id', 'operator' => 'in', 'value' => array($contact1['id'], $contact2['id']))); $tinebaseJson = new Tinebase_Frontend_Json(); $tinebaseJson->attachMultipleTagsToMultipleRecords($filter, 'Addressbook_Model_ContactFilter', array($tag1->toArray(), $tag2->toArray())); $result = $this->_uit->searchContacts($filter, array()); $this->assertCount(2, $result['results'], 'search count failed'); foreach ($result['results'] as $contactData) { $this->assertCount(2, $contactData['tags'], $contactData['n_fn'] . ' tags failed'); } }
/** * test purge deleted records * * @see 0010249: Tinebase.purgeDeletedRecords fails */ public function testPurgeDeletedRecordsAllTables() { $opts = $this->_getOpts(); $deletedContact = $this->_addAndDeleteContact(); $deletedLead = $this->_addAndDeleteLead(); // delete personal adb container and tag, too Tinebase_Container::getInstance()->deleteContainer($this->_getPersonalContainer('Addressbook')->getId()); Tinebase_Tags::getInstance()->deleteTags($deletedContact->tags->getFirstRecord()->getId()); ob_start(); $this->_cli->purgeDeletedRecords($opts); $out = ob_get_clean(); $this->assertContains('Removing all deleted entries before', $out); $this->assertContains('Cleared table addressbook (deleted ', $out); $this->assertContains('Cleared table metacrm_lead (deleted ', $out); $this->assertNotContains('Failed to purge', $out); $contactBackend = Addressbook_Backend_Factory::factory(Addressbook_Backend_Factory::SQL); $contacts = $contactBackend->getMultipleByProperty($deletedContact->getId(), 'id', TRUE); $this->assertEquals(0, count($contacts)); $leadsBackend = new Crm_Backend_Lead(); $leads = $leadsBackend->getMultipleByProperty($deletedLead->getId(), 'id', TRUE); $this->assertEquals(0, count($leads)); }
/** * 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>"; }
/** * (non-PHPdoc) * @see Sabre\DAV\Collection::getChild() */ public function getChild($_name) { $modelName = $this->_application->name . '_Model_' . $this->_model; if ($_name instanceof $modelName) { $object = $_name; } else { $filterClass = $this->_application->name . '_Model_' . $this->_model . 'Filter'; $filter = new $filterClass(array(array('field' => 'container_id', 'operator' => 'equals', 'value' => $this->_container->getId()), array('field' => 'id', 'operator' => 'equals', 'value' => $this->_getIdFromName($_name)))); $object = $this->_getController()->search($filter, null, false, false, 'sync')->getFirstRecord(); if ($object == null) { throw new Sabre\DAV\Exception\NotFound('Object not found'); } } if ($object->has('tags') && !isset($object->tags)) { Tinebase_Tags::getInstance()->getTagsOfRecord($object); } $objectClass = $this->_application->name . '_Frontend_WebDAV_' . $this->_model; return new $objectClass($this->_container, $object); }
/** * get tag * * @param string $tagType * @param string $tagName * @param array $contexts * @return Tinebase_Model_Tag */ protected function _getTag($tagType = Tinebase_Model_Tag::TYPE_SHARED, $tagName = NULL, $contexts = NULL) { if ($tagName) { try { $tag = Tinebase_Tags::getInstance()->getTagByName($tagName); return $tag; } catch (Tinebase_Exception_NotFound $tenf) { } } else { $tagName = Tinebase_Record_Abstract::generateUID(); } $targ = array('type' => $tagType, 'name' => $tagName, 'description' => 'testTagDescription', 'color' => '#009B31'); if ($contexts) { $targ['contexts'] = $contexts; } return new Tinebase_Model_Tag($targ); }
/** * set relations / tags / alarms * * @param Tinebase_Record_Interface $updatedRecord the just updated record * @param Tinebase_Record_Interface $record the update record * @param boolean $returnUpdatedRelatedData * @return Tinebase_Record_Interface */ protected function _setRelatedData($updatedRecord, $record, $returnUpdatedRelatedData = FALSE) { if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) { Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' Update record: ' . print_r($record->toArray(), true)); } // relations won't be touched if the property is set to NULL // an empty array on the relations property will remove all relations if ($record->has('relations') && isset($record->relations) && is_array($record->relations)) { $type = $this->_getBackendType(); Tinebase_Relations::getInstance()->setRelations($this->_modelName, $type, $updatedRecord->getId(), $record->relations, FALSE, $this->_inspectRelatedRecords); } if ($record->has('tags') && isset($record->tags) && (is_array($record->tags) || $record->tags instanceof Tinebase_Record_RecordSet)) { $updatedRecord->tags = $record->tags; Tinebase_Tags::getInstance()->setTagsOfRecord($updatedRecord); } if ($record->has('alarms') && isset($record->alarms)) { $this->_saveAlarms($record); } if ($record->has('attachments') && isset($record->attachments) && Tinebase_Core::isFilesystemAvailable()) { $updatedRecord->attachments = $record->attachments; Tinebase_FileSystem_RecordAttachments::getInstance()->setRecordAttachments($updatedRecord); } if ($returnUpdatedRelatedData) { $this->_getRelatedData($updatedRecord); } return $updatedRecord; }
/** * deletes tags identified by an array of identifiers * * @param array $ids * @return array */ public function deleteTags($ids) { Tinebase_Tags::getInstance()->deleteTags($ids); return array('success' => true); }
/** * testOmitPersonalTagsOnSearch * * @see 0010732: add "use personal tags" right to all applications */ public function testOmitPersonalTagsOnSearch() { $personalTag = $this->_getTag(Tinebase_Model_Tag::TYPE_PERSONAL); Tinebase_Tags::getInstance()->createTag($personalTag); $this->_removeRoleRight('Addressbook', Tinebase_Acl_Rights::USE_PERSONAL_TAGS); $filter = array('application' => 'Addressbook', 'grant' => Tinebase_Model_TagRight::VIEW_RIGHT, 'type' => Tinebase_Model_Tag::TYPE_PERSONAL); $result = $this->_instance->searchTags($filter, array()); $this->assertEquals(0, $result['totalCount']); }