/**
  * returns array with the filter settings of this filter group
  *
  * @param  bool $_valueToJson resolve value for json api?
  * @return array
  */
 public function toArray($_valueToJson = false)
 {
     if (is_string($this->_value)) {
         $this->_value = Addressbook_Controller_List::getInstance()->get($this->_value)->toArray();
     }
     return parent::toArray($_valueToJson);
 }
 /**
  * repair groups
  * 
  * * add missing lists
  * * checks if list container has been deleted (and hides groups if that's the case)
  * 
  * @see 0010401: add repair script for groups without list_ids
  */
 public function repairGroups()
 {
     $count = 0;
     $be = new Tinebase_Group_Sql();
     $listBackend = new Addressbook_Backend_List();
     $groups = $be->getGroups();
     foreach ($groups as $group) {
         if ($group->list_id == null) {
             $list = Addressbook_Controller_List::getInstance()->createByGroup($group);
             $group->list_id = $list->getId();
             $group->visibility = Tinebase_Model_Group::VISIBILITY_DISPLAYED;
             if (Tinebase_Core::isLogLevel(Zend_Log::INFO)) {
                 Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . ' Add missing list for group ' . $group->name);
             }
             $be->updateGroupInSqlBackend($group);
             $count++;
         } else {
             if ($group->visibility === Tinebase_Model_Group::VISIBILITY_DISPLAYED) {
                 try {
                     $list = $listBackend->get($group->list_id);
                     $listContainer = Tinebase_Container::getInstance()->get($list->container_id);
                 } catch (Tinebase_Exception_NotFound $tenf) {
                     if (Tinebase_Core::isLogLevel(Zend_Log::INFO)) {
                         Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . ' Hide group ' . $group->name . ' without list / list container.');
                     }
                     $group->visibility = Tinebase_Model_Group::VISIBILITY_HIDDEN;
                     $be->updateGroupInSqlBackend($group);
                     $count++;
                 }
             }
         }
     }
     echo $count . " groups repaired!\n";
 }
 /**
  * the singleton pattern
  *
  * @return Addressbook_Controller_List
  */
 public static function getInstance()
 {
     if (self::$_instance === NULL) {
         self::$_instance = new Addressbook_Controller_List();
     }
     return self::$_instance;
 }
 /**
  * create group lists
  */
 protected function _initializeGroupLists()
 {
     Addressbook_Controller_List::getInstance()->doContainerACLChecks(false);
     foreach (Tinebase_Group::getInstance()->getGroups() as $group) {
         $group->members = Tinebase_Group::getInstance()->getGroupMembers($group);
         $group->container_id = $this->_getInternalAddressbook()->getId();
         $group->visibility = Tinebase_Model_Group::VISIBILITY_DISPLAYED;
         $list = Admin_Controller_Group::getInstance()->createOrUpdateList($group);
         $group->list_id = $list->getId();
         Tinebase_Group::getInstance()->updateGroup($group);
     }
 }
 /**
  * testHiddenMembers
  * 
  * @see 0007122: hide hidden users from lists
  */
 public function testHiddenMembers()
 {
     $group = new Tinebase_Model_Group(array('name' => 'testgroup', 'description' => 'test group', 'visibility' => Tinebase_Model_Group::VISIBILITY_DISPLAYED));
     $group = Admin_Controller_Group::getInstance()->create($group);
     $this->_groupIdsToDelete[] = $group->getId();
     $list = $this->_instance->get($group->list_id);
     $sclever = Tinebase_User::getInstance()->getFullUserByLoginName('sclever');
     $list->members = array($sclever->contact_id);
     $list = $this->_instance->update($list);
     // hide sclever
     $sclever->visibility = Tinebase_Model_User::VISIBILITY_HIDDEN;
     Admin_Controller_User::getInstance()->update($sclever, NULL, NULL);
     // fetch list and check hidden members
     $listGet = $this->_instance->get($list->getId());
     $listSearch = $this->_instance->search(new Addressbook_Model_ListFilter(array(array('field' => 'id', 'operator' => 'in', 'value' => array($list->getId())))))->getFirstRecord();
     $listGetMultiple = $this->_instance->getMultiple(array($list->getId()))->getFirstRecord();
     foreach (array('get' => $listGet, 'search' => $listSearch, 'getMultiple' => $listGetMultiple) as $fn => $listRecord) {
         $this->assertTrue($listRecord instanceof Addressbook_Model_List, $fn . ' did not return a list: ' . var_export($listRecord, TRUE));
         $this->assertEquals(0, count($listRecord->members), 'Hidden sclever should not appear in list members returned by ' . $fn . '(): ' . print_r($listRecord->toArray(), TRUE));
     }
 }
 /**
  * import single record (create password if in data)
  *
  * @param Tinebase_Record_Abstract $_record
  * @param string $_resolveStrategy
  * @param array $_recordData
  * @return Tinebase_Record_Interface
  * @throws Tinebase_Exception_Record_Validation
  */
 protected function _importRecord($_record, $_resolveStrategy = NULL, $_recordData = array())
 {
     $admCfg = Tinebase_Core::getConfig()->get('Admin');
     $excludeGroups = array();
     $be = new Tinebase_Group_Sql();
     $members = explode(' ', $_record->members);
     $_record->members = null;
     unset($_record->members);
     $this->_setController();
     try {
         $group = $be->getGroupByName($_record->name);
     } catch (Tinebase_Exception_Record_NotDefined $e) {
         $group = NULL;
         parent::_importRecord($_record, $_resolveStrategy, $_recordData);
     }
     if ($group) {
         $this->_handleGroupMemberShip($group, $members);
     } else {
         $group = Admin_Controller_Group::getInstance()->get($_record->getId());
         $list = Addressbook_Controller_List::getInstance()->createByGroup($group);
         $group->list_id = $list->getId();
         $group->visibility = Tinebase_Model_Group::VISIBILITY_DISPLAYED;
         $be->updateGroupInSqlBackend($group);
         $memberUids = array();
         if (!empty($members)) {
             $users = $this->_resolveUsers($members);
             foreach ($users as $userId) {
                 try {
                     $be->addGroupMember($_record->getId(), $userId);
                 } catch (Exception $e) {
                 }
             }
         }
     }
     return $group;
 }
 /**
  * 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;
         }
     }
 }
 /**
  * appends sql to given select statement
  *
  * @param  Zend_Db_Select                    $_select
  * @param  Tinebase_Backend_Sql_Abstract     $_backend
  */
 public function appendFilterSql($_select, $_backend)
 {
     if ($this->_value === 'all') {
         $_select->where('1=1');
         return;
     }
     $gs = new Tinebase_Backend_Sql_Filter_GroupSelect($_select);
     $adapter = $_backend->getAdapter();
     //if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . ' (' . __LINE__ . ') value: ' . print_r($this->_value, true));
     foreach ($this->_value as $attenderValue) {
         if (in_array($attenderValue['user_type'], array(Calendar_Model_Attender::USERTYPE_USER, Calendar_Model_Attender::USERTYPE_GROUPMEMBER))) {
             // @todo user_id might contain filter in the future -> get userids from adressbook controller with contact filter
             // transform CURRENTCONTACT
             $attenderValue['user_id'] = $attenderValue['user_id'] == Addressbook_Model_Contact::CURRENTCONTACT ? Tinebase_Core::getUser()->contact_id : $attenderValue['user_id'];
             $attendee = array(array('user_type' => Calendar_Model_Attender::USERTYPE_USER, 'user_id' => $attenderValue['user_id']), array('user_type' => Calendar_Model_Attender::USERTYPE_GROUPMEMBER, 'user_id' => $attenderValue['user_id']));
         } else {
             if ($attenderValue['user_type'] == self::USERTYPE_MEMBEROF) {
                 // resolve group members
                 $group = Tinebase_Group::getInstance()->getGroupById($attenderValue['user_id']);
                 $attendee = array();
                 // fetch list only if list_id is not NULL, otherwise we get back an empty list object
                 if (!empty($group->list_id)) {
                     $contactList = Addressbook_Controller_List::getInstance()->get($group->list_id);
                     foreach ($contactList->members as $member) {
                         $attendee[] = array('user_type' => Calendar_Model_Attender::USERTYPE_USER, 'user_id' => $member);
                         $attendee[] = array('user_type' => Calendar_Model_Attender::USERTYPE_GROUPMEMBER, 'user_id' => $member);
                     }
                 }
             } else {
                 $attendee = array($attenderValue);
             }
         }
         foreach ($attendee as $attender) {
             $gs->orWhere($adapter->quoteInto($adapter->quoteIdentifier('attendee.user_type') . ' = ?', $attender['user_type']) . ' AND ' . $adapter->quoteInto($adapter->quoteIdentifier('attendee.user_id') . ' = ?', $attender['user_id']));
         }
     }
     $gs->appendWhere(Zend_Db_Select::SQL_OR);
 }
 /**
  * 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;
 }
 /**
  * try to delete a list
  */
 public function testDeleteList()
 {
     Addressbook_Controller_List::getInstance()->delete($this->objects['initialList']->getId());
     $this->setExpectedException('Tinebase_Exception_NotFound');
     $list = Addressbook_Controller_List::getInstance()->get($this->objects['initialList']);
 }
Exemple #11
0
 /**
  * creates or updates addressbook lists for an array of group ids
  * 
  * @param array $groupIds
  * @param string $contactId
  */
 public static function syncListsOfUserContact($groupIds, $contactId)
 {
     if (!Tinebase_Application::getInstance()->isInstalled('Addressbook')) {
         return;
     }
     if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
         Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Syncing ' . count($groupIds) . ' group -> lists / memberships');
     }
     $listBackend = new Addressbook_Backend_List();
     $listIds = array();
     foreach ($groupIds as $groupId) {
         // get single groups to make sure that container id is joined
         $group = Tinebase_Group::getInstance()->getGroupById($groupId);
         if (!empty($group->list_id)) {
             try {
                 $list = $listBackend->get($group->list_id);
             } catch (Tinebase_Exception_NotFound $tenf) {
                 if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
                     Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' List ' . $group->name . ' not found.');
                 }
                 $list = Addressbook_Controller_List::getInstance()->createByGroup($group);
             }
         } else {
             $list = Addressbook_Controller_List::getInstance()->createByGroup($group);
         }
         if ($group->list_id !== $list->getId()) {
             // list id changed / is new -> update group
             $group->list_id = $list->getId();
             Tinebase_Group::getInstance()->updateGroup($group);
         }
         $listIds[] = $list->getId();
     }
     $listBackend->setMemberships($contactId, $listIds);
 }
Exemple #12
0
 /**
  * create or update list in addressbook sql backend
  * 
  * @param  Tinebase_Model_Group  $group
  * @return Addressbook_Model_List
  */
 public function createOrUpdateList(Tinebase_Model_Group $group)
 {
     return Addressbook_Controller_List::getInstance()->createOrUpdateByGroup($group);
 }
 /**
  * delete multiple lists
  *
  * @param array $ids list of listId's to delete
  * @return array
  */
 public function deleteLists($ids)
 {
     return $this->_delete($ids, Addressbook_Controller_List::getInstance());
 }
 /**
  * generates path for the contact
  *
  * - we add to the path:
  *      - lists contact is member of
  *      - we add list role memberships
  *
  * @param Tinebase_Record_Abstract $record
  * @return Tinebase_Record_RecordSet
  */
 public function generatePathForRecord($record)
 {
     $result = new Tinebase_Record_RecordSet('Tinebase_Model_Path');
     // fetch all groups and role memberships and add to path
     $listIds = Addressbook_Controller_List::getInstance()->getMemberships($record);
     foreach ($listIds as $listId) {
         /** @var Addressbook_Model_List $list */
         $list = Addressbook_Controller_List::getInstance()->get($listId);
         $listPaths = $this->_getPathsOfRecord($list);
         if (count($listPaths) === 0) {
             // add self
             $listPaths->addRecord(new Tinebase_Model_Path(array('path' => $this->_getPathPart($list), 'shadow_path' => '/' . $list->getId(), 'record_id' => $list->getId(), 'creation_time' => Tinebase_DateTime::now())));
         }
         foreach ($listPaths as $listPath) {
             if (count($list->memberroles) > 0) {
                 foreach ($list->memberroles as $role) {
                     $rolePath = clone $listPath;
                     if ($role->contact_id === $record->getId()) {
                         $role = Addressbook_Controller_ListRole::getInstance()->get($role->list_role_id);
                         $rolePath->path .= $this->_getPathPart($role);
                         $rolePath->shadow_path .= '/' . $role->getId();
                         $rolePath->record_id = $role->getId();
                         $result->addRecord($rolePath);
                     }
                 }
             } else {
                 $result->addRecord($listPath);
             }
         }
     }
     foreach ($result as $listPath) {
         $listPath->path .= $this->_getPathPart($record);
         $listPath->shadow_path .= '/' . $record->getId();
         $listPath->record_id = $record->getId();
     }
     return $result;
 }
 /**
  * Search for lists matching given arguments
  *
  * @param  array $filter
  * @param  array $paging
  * @return array
  */
 public function searchLists($filter, $paging)
 {
     return $this->_search($filter, $paging, Addressbook_Controller_List::getInstance(), 'Addressbook_Model_ListFilter');
 }
 /**
  * testSyncLists
  * 
  * @see 0005768: create addressbook lists when migrating users
  * 
  * @todo make this work for LDAP accounts backend: currently the user is not present in sync backend but in sql
  */
 public function testSyncLists()
 {
     if (Tinebase_Group::getInstance() instanceof Tinebase_Group_Ldap) {
         $this->markTestSkipped('@todo make this work for LDAP accounts backend');
     }
     $testGroup = $this->testAddGroup();
     // don't use any existing persona here => will break other tests
     $testUser = new Tinebase_Model_FullUser(array('accountLoginName' => Tinebase_Record_Abstract::generateUID(), 'accountPrimaryGroup' => $testGroup->getId(), 'accountDisplayName' => Tinebase_Record_Abstract::generateUID(), 'accountLastName' => Tinebase_Record_Abstract::generateUID(), 'accountFullName' => Tinebase_Record_Abstract::generateUID(), 'visibility' => Tinebase_Model_User::VISIBILITY_DISPLAYED));
     $contact = Admin_Controller_User::getInstance()->createOrUpdateContact($testUser);
     $testUser->contact_id = $contact->getId();
     $testUser = Tinebase_User::getInstance()->addUserInSqlBackend($testUser);
     Tinebase_User::createContactForSyncedUser($testUser);
     Tinebase_User::getInstance()->updateUserInSqlBackend($testUser);
     $this->testSetGroupMembers($testGroup, array($testUser->accountId));
     Tinebase_Group::syncListsOfUserContact(array($testGroup->getId()), $testUser->contact_id);
     $group = Tinebase_Group::getInstance()->getGroupById($testGroup);
     $this->assertTrue(!empty($group->list_id), 'list id empty: ' . print_r($group->toArray(), TRUE));
     $list = Addressbook_Controller_List::getInstance()->get($group->list_id);
     $this->assertEquals($group->getId(), $list->group_id);
     $this->assertEquals($group->name, $list->name);
     $this->assertTrue(!empty($list->members), 'list members empty: ' . print_r($list->toArray(), TRUE) . ' should contain: ' . print_r($testUser->toArray(), TRUE));
     $this->assertContains($testUser->contact_id, $list->members);
     $appConfigDefaults = Admin_Controller::getInstance()->getConfigSettings();
     $this->assertTrue(!empty($appConfigDefaults), 'app config defaults empty');
     $internal = $appConfigDefaults[Admin_Model_Config::DEFAULTINTERNALADDRESSBOOK];
     $this->assertEquals($internal, $list->container_id, 'did not get correct internal container');
     // sync again -> should not change anything
     Tinebase_Group::syncListsOfUserContact(array($group->getId()), $testUser->contact_id);
     $listAgain = Addressbook_Controller_List::getInstance()->get($group->list_id);
     $this->assertEquals($list->toArray(), $listAgain->toArray());
     // change list id -> should get list by (group) name
     $group->list_id = NULL;
     $group = Tinebase_Group::getInstance()->updateGroup($group);
     Tinebase_Group::syncListsOfUserContact(array($group->getId()), $testUser->contact_id);
     $this->assertEquals($list->getId(), Tinebase_Group::getInstance()->getGroupById($group)->list_id);
 }
 /**
  * testSyncLists
  * 
  * @see http://forge.tine20.org/mantisbt/view.php?id=5768
  */
 public function testSyncLists()
 {
     $group = $this->objects['initialGroup'];
     Tinebase_User::syncContact($this->objects['account1']);
     Tinebase_User::getInstance()->updateUserInSqlBackend($this->objects['account1']);
     $this->testSetGroupMembers();
     Tinebase_Group::syncListsOfUserContact(array($group->getId()), $this->objects['account1']->contact_id);
     $group = Tinebase_Group::getInstance()->getGroupById($this->objects['initialGroup']);
     $this->assertTrue(!empty($group->list_id), 'list id empty: ' . print_r($group->toArray(), TRUE));
     $list = Addressbook_Controller_List::getInstance()->get($group->list_id);
     $this->assertEquals($group->getId(), $list->group_id);
     $this->assertEquals($group->name, $list->name);
     $this->assertTrue(!empty($list->members), 'list members empty: ' . print_r($list->toArray(), TRUE));
     $this->assertEquals($this->objects['account1']->contact_id, $list->members[0]);
     $appConfigDefaults = Admin_Controller::getInstance()->getConfigSettings();
     $internal = $appConfigDefaults[Admin_Model_Config::DEFAULTINTERNALADDRESSBOOK];
     $this->assertEquals($internal, $list->container_id);
     // sync again -> should not change anything
     Tinebase_Group::syncListsOfUserContact(array($group->getId()), $this->objects['account1']->contact_id);
     $listAgain = Addressbook_Controller_List::getInstance()->get($group->list_id);
     $this->assertEquals($list->toArray(), $listAgain->toArray());
 }
 /**
  * This method is used to search for principals matching a set of
  * properties.
  *
  * This search is specifically used by RFC3744's principal-property-search
  * REPORT. You should at least allow searching on
  * http://sabredav.org/ns}email-address.
  *
  * The actual search should be a unicode-non-case-sensitive search. The
  * keys in searchProperties are the WebDAV property names, while the values
  * are the property values to search on.
  *
  * If multiple properties are being searched on, the search should be
  * AND'ed.
  *
  * This method should simply return an array with full principal uri's.
  *
  * If somebody attempted to search on a property the backend does not
  * support, you should simply return 0 results.
  *
  * You can also just return 0 results if you choose to not support
  * searching at all, but keep in mind that this may stop certain features
  * from working.
  *
  * @param string $prefixPath
  * @param array $searchProperties
  * @todo implement handling for shared pseudo user
  * @return array
  */
 public function searchPrincipals($prefixPath, array $searchProperties)
 {
     if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
         Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' path: ' . $prefixPath . ' properties: ' . print_r($searchProperties, true));
     }
     $principalUris = array();
     switch ($prefixPath) {
         case self::PREFIX_GROUPS:
         case self::PREFIX_INTELLIGROUPS:
             $filter = new Addressbook_Model_ListFilter(array(array('field' => 'type', 'operator' => 'equals', 'value' => Addressbook_Model_List::LISTTYPE_GROUP)));
             if (!empty($searchProperties['{http://calendarserver.org/ns/}search-token'])) {
                 $filter->addFilter($filter->createFilter(array('field' => 'query', 'operator' => 'contains', 'value' => $searchProperties['{http://calendarserver.org/ns/}search-token'])));
             }
             if (!empty($searchProperties['{DAV:}displayname'])) {
                 $filter->addFilter($filter->createFilter(array('field' => 'name', 'operator' => 'contains', 'value' => $searchProperties['{DAV:}displayname'])));
             }
             $result = Addressbook_Controller_List::getInstance()->search($filter, null, false, true);
             foreach ($result as $listId) {
                 $principalUris[] = $prefixPath . '/' . $listId;
             }
             break;
         case self::PREFIX_USERS:
             $filter = $this->_getContactFilterForUserContact();
             if (!empty($searchProperties['{http://calendarserver.org/ns/}search-token'])) {
                 $filter->addFilter($filter->createFilter(array('field' => 'query', 'operator' => 'contains', 'value' => $searchProperties['{http://calendarserver.org/ns/}search-token'])));
             }
             if (!empty($searchProperties['{http://sabredav.org/ns}email-address'])) {
                 $filter->addFilter($filter->createFilter(array('field' => 'email_query', 'operator' => 'contains', 'value' => $searchProperties['{http://sabredav.org/ns}email-address'])));
             }
             if (!empty($searchProperties['{DAV:}displayname'])) {
                 $filter->addFilter($filter->createFilter(array('field' => 'query', 'operator' => 'contains', 'value' => $searchProperties['{DAV:}displayname'])));
             }
             if (!empty($searchProperties['{' . \Sabre\CalDAV\Plugin::NS_CALENDARSERVER . '}first-name'])) {
                 $filter->addFilter($filter->createFilter(array('field' => 'n_given', 'operator' => 'contains', 'value' => $searchProperties['{' . \Sabre\CalDAV\Plugin::NS_CALENDARSERVER . '}first-name'])));
             }
             if (!empty($searchProperties['{' . \Sabre\CalDAV\Plugin::NS_CALENDARSERVER . '}last-name'])) {
                 $filter->addFilter($filter->createFilter(array('field' => 'n_family', 'operator' => 'contains', 'value' => $searchProperties['{' . \Sabre\CalDAV\Plugin::NS_CALENDARSERVER . '}last-name'])));
             }
             if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) {
                 Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' path: ' . $prefixPath . ' properties: ' . print_r($filter->toArray(), true));
             }
             $result = Addressbook_Controller_Contact::getInstance()->search($filter, null, false, true);
             foreach ($result as $contactId) {
                 $principalUris[] = $prefixPath . '/' . $contactId;
             }
             break;
     }
     return $principalUris;
 }
 /**
  * creates or updates addressbook lists for an array of group ids
  * 
  * @param array $groupIds
  * @param string $contactId
  */
 public static function syncListsOfUserContact($groupIds, $contactId)
 {
     // check addressbook and empty contact id (for example cronuser)
     if (!Tinebase_Application::getInstance()->isInstalled('Addressbook') || empty($contactId)) {
         return;
     }
     if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
         Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Syncing ' . count($groupIds) . ' group -> lists / memberships');
     }
     $listBackend = new Addressbook_Backend_List();
     $listIds = array();
     foreach ($groupIds as $groupId) {
         // get single groups to make sure that container id is joined
         $group = Tinebase_Group::getInstance()->getGroupById($groupId);
         $list = NULL;
         if (!empty($group->list_id)) {
             try {
                 $list = $listBackend->get($group->list_id);
             } catch (Tinebase_Exception_NotFound $tenf) {
                 if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
                     Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' List ' . $group->name . ' not found.');
                 }
             }
         }
         // could not get list by list_id -> try to get by name
         // if no list can be found, create new one
         if (!$list) {
             $list = $listBackend->getByGroupName($group->name);
             if (!$list) {
                 $list = Addressbook_Controller_List::getInstance()->createByGroup($group);
             }
         }
         if ($group->list_id !== $list->getId()) {
             // list id changed / is new -> update group and make group visible
             $group->list_id = $list->getId();
             $group->visibility = Tinebase_Model_Group::VISIBILITY_DISPLAYED;
             Tinebase_Timemachine_ModificationLog::setRecordMetaData($group, 'update');
             Tinebase_Group::getInstance()->updateGroup($group);
         }
         $listIds[] = $list->getId();
     }
     $listBackend->setMemberships($contactId, $listIds);
 }
 /**
  * try to delete a list
  *
  */
 public function testDeleteList()
 {
     Addressbook_Controller_List::getInstance()->delete($GLOBALS['Addressbook_ListControllerTest']['listId']);
     $this->setExpectedException('Tinebase_Exception_NotFound');
     $list = Addressbook_Controller_List::getInstance()->get($GLOBALS['Addressbook_ListControllerTest']['listId']);
 }
 /**
  * appends sql to given select statement
  *
  * @param  Zend_Db_Select                    $_select
  * @param  Tinebase_Backend_Sql_Abstract     $_backend
  */
 public function appendFilterSql($_select, $_backend)
 {
     if ($this->_value === 'all') {
         $_select->where('1=1');
         return;
     }
     $gs = new Tinebase_Backend_Sql_Filter_GroupSelect($_select);
     $adapter = $_backend->getAdapter();
     //if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) Tinebase_Core::getLogger()->debug(__METHOD__ . ' (' . __LINE__ . ') value: ' . print_r($this->_value, true));
     foreach ($this->_value as $attenderValue) {
         if (in_array($attenderValue['user_type'], array(Calendar_Model_Attender::USERTYPE_USER, Calendar_Model_Attender::USERTYPE_GROUPMEMBER))) {
             // @todo user_id might contain filter in the future -> get userids from adressbook controller with contact filter
             // transform CURRENTCONTACT
             $attenderValue['user_id'] = $attenderValue['user_id'] == Addressbook_Model_Contact::CURRENTCONTACT ? Tinebase_Core::getUser()->contact_id : $attenderValue['user_id'];
             $attendee = array(array('user_type' => Calendar_Model_Attender::USERTYPE_USER, 'user_id' => $attenderValue['user_id']), array('user_type' => Calendar_Model_Attender::USERTYPE_GROUPMEMBER, 'user_id' => $attenderValue['user_id']));
         } else {
             if ($attenderValue['user_type'] == self::USERTYPE_MEMBEROF) {
                 // resolve group members
                 $group = Tinebase_Group::getInstance()->getGroupById($attenderValue['user_id']);
                 $attendee = array();
                 // fetch list only if list_id is not NULL, otherwise we get back an empty list object
                 if (!empty($group->list_id)) {
                     $contactList = Addressbook_Controller_List::getInstance()->get($group->list_id);
                     foreach ($contactList->members as $member) {
                         $attendee[] = array('user_type' => Calendar_Model_Attender::USERTYPE_USER, 'user_id' => $member);
                         $attendee[] = array('user_type' => Calendar_Model_Attender::USERTYPE_GROUPMEMBER, 'user_id' => $member);
                     }
                 }
             } else {
                 $attendee = array($attenderValue);
             }
         }
         foreach ($attendee as $attender) {
             $gs->orWhere($adapter->quoteInto($adapter->quoteIdentifier('attendee.user_type') . ' = ?', $attender['user_type']) . ' AND ' . $adapter->quoteInto($adapter->quoteIdentifier('attendee.user_id') . ' = ?', $attender['user_id']));
         }
     }
     if (substr($this->_operator, 0, 3) === 'not') {
         // join attendee to be excluded as a new column. records having this column NULL don't have the attendee
         $dname = 'attendee-not-' . Tinebase_Record_Abstract::generateUID(5);
         $_select->joinLeft(array($dname => $_backend->getTablePrefix() . 'cal_attendee'), $adapter->quoteIdentifier($dname . '.cal_event_id') . ' = ' . $adapter->quoteIdentifier($_backend->getTableName() . '.id') . ' AND ' . $gs->getSQL(), array($dname => $_backend->getDbCommand()->getAggregate($dname . '.id')));
         $_select->having($_backend->getDbCommand()->getAggregate($dname . '.id') . ' IS NULL');
     } else {
         $gs->appendWhere(Zend_Db_Select::SQL_OR);
     }
 }
 /**
  * try to set grants
  */
 public function testSetGrants()
 {
     $newGrants = new Tinebase_Record_RecordSet('Tinebase_Model_Grants');
     $newGrants->addRecord(new Tinebase_Model_Grants(array('account_id' => Tinebase_Core::getUser()->getId(), 'account_type' => 'user', Tinebase_Model_Grants::GRANT_READ => true, Tinebase_Model_Grants::GRANT_ADD => false, Tinebase_Model_Grants::GRANT_EDIT => true, Tinebase_Model_Grants::GRANT_DELETE => true, Tinebase_Model_Grants::GRANT_ADMIN => true)));
     // get group and add grants for it
     $lists = Addressbook_Controller_List::getInstance()->search(new Addressbook_Model_ListFilter(array(array('field' => 'showHidden', 'operator' => 'equals', 'value' => TRUE))));
     $groupToAdd = $lists->getFirstRecord();
     $newGrants->addRecord(new Tinebase_Model_Grants(array('account_id' => $groupToAdd->group_id, 'account_type' => 'group', Tinebase_Model_Grants::GRANT_READ => true, Tinebase_Model_Grants::GRANT_ADD => false, Tinebase_Model_Grants::GRANT_EDIT => false, Tinebase_Model_Grants::GRANT_DELETE => false, Tinebase_Model_Grants::GRANT_ADMIN => false)));
     $grants = $this->_instance->setGrants($this->objects['initialContainer'], $newGrants);
     $this->assertEquals('Tinebase_Record_RecordSet', get_class($grants), 'wrong type');
     $this->assertEquals(2, count($grants));
     $grants = $grants->toArray();
     foreach ($grants as $grant) {
         if ($grant['account_id'] === Tinebase_Core::getUser()->getId()) {
             $this->assertTrue($grant["readGrant"], print_r($grant, TRUE));
             $this->assertFalse($grant["addGrant"], print_r($grant, TRUE));
             $this->assertTrue($grant["editGrant"], print_r($grant, TRUE));
             $this->assertTrue($grant["deleteGrant"], print_r($grant, TRUE));
             $this->assertTrue($grant["adminGrant"], print_r($grant, TRUE));
             $this->assertEquals(Tinebase_Acl_Rights::ACCOUNT_TYPE_USER, $grant['account_type']);
         } else {
             $this->assertTrue($grant["readGrant"], print_r($grant, TRUE));
             $this->assertEquals(Tinebase_Acl_Rights::ACCOUNT_TYPE_GROUP, $grant['account_type']);
         }
     }
 }
 /**
  * @see 0011522: improve handling of group-lists
  */
 public function testChangeListWithoutManageGrant()
 {
     // try to set memberships without MANAGE_ACCOUNTS
     $this->_removeRoleRight('Admin', Admin_Acl_Rights::MANAGE_ACCOUNTS, true);
     $listId = Tinebase_Group::getInstance()->getDefaultGroup()->list_id;
     try {
         Addressbook_Controller_List::getInstance()->addListMember($listId, array($this->objects['contact1']->getId()));
         $this->fail('should not be possible to add list member to system group');
     } catch (Tinebase_Exception_AccessDenied $tead) {
         $this->assertEquals('No permission to add list member.', $tead->getMessage());
     }
     $list = Addressbook_Controller_List::getInstance()->get($listId);
     $list->name = 'my new name';
     try {
         Addressbook_Controller_List::getInstance()->update($list);
         $this->fail('should not be possible to set name of system group');
     } catch (Tinebase_Exception_AccessDenied $tead) {
         $this->assertEquals('You are not allowed to MANAGE_ACCOUNTS in application Admin !', $tead->getMessage());
     }
 }