public static function getConfig($appName, $modelNames = null)
 {
     $mappingDriver = new Tinebase_Record_DoctrineMappingDriver();
     if (!$modelNames) {
         $modelNames = array();
         foreach ($mappingDriver->getAllClassNames() as $modelName) {
             $modelConfig = $modelName::getConfiguration();
             if ($modelConfig->getApplName() == $appName) {
                 $modelNames[] = $modelName;
             }
         }
     }
     $tableNames = array();
     foreach ($modelNames as $modelName) {
         $modelConfig = $modelName::getConfiguration();
         if (!$mappingDriver->isTransient($modelName)) {
             throw new Setup_Exception('Model not yet doctrine2 ready');
         }
         $tableNames[] = SQL_TABLE_PREFIX . Tinebase_Helper::array_value('name', $modelConfig->getTable());
     }
     $config = Setup::createConfiguration();
     $config->setMetadataDriverImpl($mappingDriver);
     $config->setFilterSchemaAssetsExpression('/' . implode('|', $tableNames) . '/');
     return $config;
 }
 /**
  *
  * @return type
  */
 public function getFilterImap()
 {
     $format = "d-M-Y";
     // prepare value
     $value = (array) $this->_getDateValues($this->_operator, $this->_value);
     $timezone = Tinebase_Helper::array_value('timezone', $this->_options);
     $timezone = $timezone ? $timezone : Tinebase_Core::getUserTimezone();
     foreach ($value as &$date) {
         $date = new Tinebase_DateTime($date);
         // should be in user timezone
         $date->setTimezone(new DateTimeZone($timezone));
     }
     switch ($this->_operator) {
         case 'within':
         case 'inweek':
             $value[1]->add(new DateInterval('P1D'));
             // before is not inclusive, so we have to add a day
             $return = "SINCE {$value[0]->format($format)} BEFORE {$value[1]->format($format)}";
             break;
         case 'before':
             $return = "BEFORE {$value[0]->format($format)}";
             break;
         case 'after':
             $return = "SINCE {$value[0]->format($format)}";
             break;
         case 'equals':
             $return = "ON {$value[0]->format($format)}";
     }
     return $return;
 }
 /**
  * (non-PHPdoc)
  * @see Tinebase_WebDav_Collection_AbstractContainerTree::getChildren()
  */
 public function getChildren()
 {
     $children = parent::getChildren();
     // do this only for caldav request
     if ($this->_useIdAsName && count($this->_getPathParts()) == 2 && Tinebase_Core::getUser()->hasRight('Tasks', Tinebase_Acl_Rights::RUN)) {
         $tfwdavct = new Tasks_Frontend_WebDAV('tasks/' . Tinebase_Helper::array_value(1, $this->_getPathParts()), $this->_useIdAsName);
         $children = array_merge($children, $tfwdavct->getChildren());
     }
     return $children;
 }
 /**
  * testMaintenanceModeLoginFail
  */
 public function testMaintenanceModeLoginFail()
 {
     if (Tinebase_User::getConfiguredBackend() === Tinebase_User::LDAP || Tinebase_User::getConfiguredBackend() === Tinebase_User::ACTIVEDIRECTORY) {
         $this->markTestSkipped('FIXME: Does not work with LDAP/AD backend (full test suite run)');
     }
     Tinebase_Config::getInstance()->maintenanceMode = 1;
     try {
         $this->_instance->login('sclever', Tinebase_Helper::array_value('password', TestServer::getInstance()->getTestCredentials()), new \Zend\Http\PhpEnvironment\Request());
         $this->fail('expecting exception: Tinebase_Exception_MaintenanceMode');
     } catch (Tinebase_Exception_MaintenanceMode $temm) {
         $this->assertEquals('Installation is in maintenance mode. Please try again later', $temm->getMessage());
     }
 }
 /**
  * cache invalidation needs a second 
  */
 public function testSetGrantsCacheInvalidation()
 {
     $container = $this->objects['initialContainer'];
     $sclever = Tinebase_Helper::array_value('sclever', Zend_Registry::get('personas'));
     $this->assertEquals(FALSE, $this->_instance->hasGrant($sclever->getId(), $container->getId(), Tinebase_Model_Grants::GRANT_READ), 'sclever should _not_ have a read grant');
     // have readGrant for sclever
     $this->_instance->setGrants($container->getId(), new Tinebase_Record_RecordSet('Tinebase_Model_Grants', array(array('account_id' => Tinebase_Core::getUser()->getId(), 'account_type' => 'user', Tinebase_Model_Grants::GRANT_ADMIN => true), array('account_id' => $sclever->getId(), 'account_type' => 'user', Tinebase_Model_Grants::GRANT_READ => true))), TRUE);
     sleep(1);
     $this->assertEquals(TRUE, $this->_instance->hasGrant($sclever->getId(), $container->getId(), Tinebase_Model_Grants::GRANT_READ), 'sclever _should have_ a read grant');
     // remove readGrant for sclever again
     $this->_instance->setGrants($container->getId(), new Tinebase_Record_RecordSet('Tinebase_Model_Grants', array(array('account_id' => Tinebase_Core::getUser()->getId(), 'account_type' => 'user', Tinebase_Model_Grants::GRANT_ADMIN => true), array('account_id' => $sclever->getId(), 'account_type' => 'user', Tinebase_Model_Grants::GRANT_READ => false))), TRUE);
     sleep(1);
     $this->assertEquals(FALSE, $this->_instance->hasGrant($sclever->getId(), $container->getId(), Tinebase_Model_Grants::GRANT_READ), 'sclever should _not_ have a read grant');
 }
 /**
  * return application name
  * 
  * @return string
  */
 protected function _getApplicationName()
 {
     if (!$this->_applicationName) {
         $this->_applicationName = Tinebase_Helper::array_value(0, explode('_', get_class($this)));
     }
     return $this->_applicationName;
 }
 /**
  * update schema of modelconfig enabled app
  *
  * @param string $appName
  * @param array $modelNames
  * @throws Setup_Exception_NotFound
  */
 public function updateSchema($appName, $modelNames)
 {
     $updateRequired = false;
     $setNewVersions = array();
     foreach ($modelNames as $modelName) {
         $modelConfig = $modelName::getConfiguration();
         $tableName = Tinebase_Helper::array_value('name', $modelConfig->getTable());
         $currentVersion = $this->getTableVersion($tableName);
         $schemaVersion = $modelConfig->getVersion();
         if ($currentVersion < $schemaVersion) {
             $updateRequired = true;
             $setNewVersions[$tableName] = $schemaVersion;
         }
     }
     if ($updateRequired) {
         Setup_SchemaTool::updateSchema($appName, $modelNames);
         foreach ($setNewVersions as $table => $version) {
             $this->setTableVersion($table, $version);
         }
     }
 }
 /**
  * appends effective grant calculation to select object
  *
  * @param Zend_Db_Select $_select
  */
 protected function _appendEffectiveGrantCalculationSql($_select, $_attendeeFilters = NULL)
 {
     // groupmemberships of current user, needed to compute phys and inherited grants
     $_select->joinLeft(array('groupmemberships' => $this->_tablePrefix . 'group_members'), $this->_db->quoteInto($this->_db->quoteIdentifier('groupmemberships.account_id') . ' = ?', Tinebase_Core::getUser()->getId()), array());
     // attendee joins the attendee we need to compute the curr users effective grants
     // NOTE: 2010-04 the behaviour changed. Now, only the attendee the client filters for are
     //       taken into account for grants calculation
     $attendeeWhere = FALSE;
     if (is_array($_attendeeFilters) && !empty($_attendeeFilters)) {
         $attendeeSelect = $this->_db->select();
         foreach ((array) $_attendeeFilters as $attendeeFilter) {
             if ($attendeeFilter instanceof Calendar_Model_AttenderFilter) {
                 $attendeeFilter->appendFilterSql($attendeeSelect, $this);
             }
         }
         $whereArray = $attendeeSelect->getPart(Zend_Db_Select::SQL_WHERE);
         if (!empty($whereArray)) {
             $attendeeWhere = ' AND ' . Tinebase_Helper::array_value(0, $whereArray);
         }
     }
     $_select->joinLeft(array('attendee' => $this->_tablePrefix . 'cal_attendee'), $this->_db->quoteIdentifier('attendee.cal_event_id') . ' = ' . $this->_db->quoteIdentifier('cal_events.id') . $attendeeWhere, array());
     $_select->joinLeft(array('attendeeaccounts' => $this->_tablePrefix . 'accounts'), $this->_db->quoteIdentifier('attendeeaccounts.contact_id') . ' = ' . $this->_db->quoteIdentifier('attendee.user_id') . ' AND (' . $this->_db->quoteInto($this->_db->quoteIdentifier('attendee.user_type') . '= ?', Calendar_Model_Attender::USERTYPE_USER) . ' OR ' . $this->_db->quoteInto($this->_db->quoteIdentifier('attendee.user_type') . '= ?', Calendar_Model_Attender::USERTYPE_GROUPMEMBER) . ')', array());
     $_select->joinLeft(array('attendeegroupmemberships' => $this->_tablePrefix . 'group_members'), $this->_db->quoteIdentifier('attendeegroupmemberships.account_id') . ' = ' . $this->_db->quoteIdentifier('attendeeaccounts.contact_id'), array());
     $_select->joinLeft(array('dispgrants' => $this->_tablePrefix . 'container_acl'), $this->_db->quoteIdentifier('dispgrants.container_id') . ' = ' . $this->_db->quoteIdentifier('attendee.displaycontainer_id') . ' AND ' . $this->_getContainGrantCondition('dispgrants', 'groupmemberships'), array());
     $_select->joinLeft(array('physgrants' => $this->_tablePrefix . 'container_acl'), $this->_db->quoteIdentifier('physgrants.container_id') . ' = ' . $this->_db->quoteIdentifier('cal_events.container_id'), array());
     $allGrants = Tinebase_Model_Grants::getAllGrants();
     foreach ($allGrants as $grant) {
         if (in_array($grant, $this->_recordBasedGrants)) {
             $_select->columns(array($grant => "\n MAX( CASE WHEN ( \n" . '  /* physgrant */' . $this->_getContainGrantCondition('physgrants', 'groupmemberships', $grant) . " OR \n" . '  /* implicit  */' . $this->_getImplicitGrantCondition($grant) . " OR \n" . '  /* inherited */' . $this->_getInheritedGrantCondition($grant) . " \n" . ") THEN 1 ELSE 0 END ) "));
         } else {
             $_select->columns(array($grant => "\n MAX( CASE WHEN ( \n" . '  /* physgrant */' . $this->_getContainGrantCondition('physgrants', 'groupmemberships', $grant) . "\n" . ") THEN 1 ELSE 0 END ) "));
         }
     }
 }
 /**
  * checks if mail for persona got send
  * 
  * @param string $_personas
  * @param string $_assertString
  * @return void
  * 
  * @see #6800: add message-id to notification mails
  */
 protected function _assertMail($_personas, $_assertString = NULL, $_location = 'subject')
 {
     $messages = self::getMessages();
     foreach (explode(',', $_personas) as $personaName) {
         $mailsForPersona = array();
         $otherRecipients = array();
         $personaEmail = strstr($personaName, '@') ? $personaName : $this->_getPersona(trim($personaName))->accountEmailAddress;
         foreach ($messages as $message) {
             if (Tinebase_Helper::array_value(0, $message->getRecipients()) == $personaEmail) {
                 array_push($mailsForPersona, $message);
             } else {
                 array_push($otherRecipients, $message->getRecipients());
             }
         }
         if (!$_assertString) {
             $this->assertEquals(0, count($mailsForPersona), 'No mail should be send for ' . $personaName);
         } else {
             $this->assertEquals(1, count($mailsForPersona), 'One mail should be send for ' . $personaName . ' other recipients: ' . print_r($otherRecipients, true));
             $this->assertEquals('UTF-8', $mailsForPersona[0]->getCharset());
             switch ($_location) {
                 case 'subject':
                     $subject = $mailsForPersona[0]->getSubject();
                     $this->assertTrue(FALSE !== strpos($subject, $_assertString), 'Mail subject for ' . $personaName . ' should contain "' . $_assertString . '" but ' . $subject . ' is given');
                     break;
                 case 'body':
                     $bodyPart = $mailsForPersona[0]->getBodyText(FALSE);
                     // so odd!
                     $s = fopen('php://temp', 'r+');
                     fputs($s, $bodyPart->getContent());
                     rewind($s);
                     $bodyPartStream = new Zend_Mime_Part($s);
                     $bodyPartStream->encoding = $bodyPart->encoding;
                     $bodyText = $bodyPartStream->getDecodedContent();
                     if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
                         Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' body text: ' . $bodyText);
                     }
                     $this->assertContains($_assertString, $bodyText);
                     break;
                 default:
                     throw new Exception('no such location ' . $_location);
                     break;
             }
             $headers = $mailsForPersona[0]->getHeaders();
             $this->assertTrue(isset($headers['Message-Id']), 'message-id header not found');
             $this->assertContains('@' . php_uname('n'), $headers['Message-Id'][0], 'hostname not in message-id');
         }
     }
 }
 /**
  * test aclQuery method
  */
 public function testAclSetRoles()
 {
     // add user to grants of container
     $this->testAclAddUser();
     $body = '<?xml version="1.0" encoding="utf-8"?>
              <acl-query xmlns="urn:inverse:params:xml:ns:inverse-dav">
                  <set-roles user="******">
                      <ObjectEraser/>
                  </set-roles>
              </acl-query>';
     $request = new Sabre\HTTP\Request(array('REQUEST_METHOD' => 'POST', 'REQUEST_URI' => '/calendars/' . Tinebase_Core::getUser()->contact_id . '/' . $this->objects['initialContainer']->id, 'HTTP_DEPTH' => '1'));
     $request->setBody($body);
     $this->server->httpRequest = $request;
     $this->server->exec();
     $this->assertEquals('HTTP/1.1 201 Created', $this->response->status);
     $grantsOfPwulf = Tinebase_Container::getInstance()->getGrantsOfContainer($this->objects['initialContainer']->id)->filter('account_id', Tinebase_Helper::array_value('pwulf', Zend_Registry::get('personas'))->accountId)->getFirstRecord();
     $this->assertTrue($grantsOfPwulf->deleteGrant);
     $this->assertFalse($grantsOfPwulf->addGrant);
 }
 /**
  * return first namingContext from LDAP root DSE
  * 
  * @return string
  */
 public function getFirstNamingContext()
 {
     return Tinebase_Helper::array_value(0, $this->getRootDse()->getNamingContexts());
 }
 /**
  * test Calendar_Frontend_WebDAV_Container::getShares for container user has no admin grant for
  */
 public function testGetSharesWithoutRights()
 {
     $jmcblack = Tinebase_Helper::array_value('jmcblack', Zend_Registry::get('personas'));
     $jmcblacksCalId = Tinebase_Core::getPreference('Calendar')->getValueForUser(Calendar_Preference::DEFAULTCALENDAR, $jmcblack->getId());
     $jmcblacksCal = Tinebase_Container::getInstance()->get($jmcblacksCalId);
     $container = new Calendar_Frontend_WebDAV_Container($jmcblacksCal);
     $shares = $container->getShares();
     $this->assertEquals(1, count($shares));
     $this->assertTrue((bool) $shares[0]['readOnly']);
 }
 /**
  * contructor
  * 
  * @param  string|Tinebase_Model_Application  $_application  the current application
  * @param  string                             $_path         the current path
  */
 public function __construct($_path)
 {
     $this->_path = $_path;
     $this->_pathParts = $this->_parsePath($_path);
     $this->_applicationName = Tinebase_Helper::array_value(0, explode('_', get_class($this)));
 }
 /**
  * testAddAttachmentToRecurSeries
  * 
  * @see 0005024: allow to attach external files to records
  */
 public function testAddAttachmentToRecurSeries()
 {
     $tempFile = $this->_getTempFile();
     $recurSet = Tinebase_Helper::array_value('results', $this->testSearchRecuringIncludes());
     // update recurseries
     $someRecurInstance = $recurSet[2];
     $someRecurInstance['attachments'] = array(array('tempFile' => array('id' => $tempFile->getId())));
     $someRecurInstance['seq'] = 2;
     $this->_uit->updateRecurSeries($someRecurInstance, FALSE, FALSE);
     $searchResultData = $this->_searchRecurSeries($recurSet[0]);
     foreach ($searchResultData['results'] as $recurInstance) {
         $this->assertTrue(isset($recurInstance['attachments']), 'no attachments found in event: ' . print_r($recurInstance, TRUE));
         $this->assertEquals(1, count($recurInstance['attachments']));
         $attachment = $recurInstance['attachments'][0];
         $this->assertEquals('text/plain', $attachment['contenttype'], print_r($attachment, TRUE));
     }
 }
 /**
  * returns a single account dn
  *
  * @param string $_accountId
  * @return string
  */
 protected function _getAccountMetaData($_accountId)
 {
     return Tinebase_Helper::array_value(0, $this->_getAccountsMetaData(array($_accountId)));
 }
 /**
  * returns record prepared for json transport
  *
  * @param Tinebase_Record_Interface $_record
  * @return array record data
  * 
  * @todo move to converter
  */
 protected function _recordToJson($_record)
 {
     $recordSet = new Tinebase_Record_RecordSet('Tinebase_Model_PersistentFilter', array($_record));
     return Tinebase_Helper::array_value(0, $this->_multipleRecordsToJson($recordSet));
 }
 /**
  * testGetUserProfile
  */
 public function testGetUserProfile()
 {
     $profile = $this->_instance->getUserProfile(Tinebase_Core::getUser()->getId());
     $this->assertTrue(is_array($profile));
     $this->assertTrue(isset($profile['userProfile']) || array_key_exists('userProfile', $profile));
     $this->assertTrue(is_array($profile['userProfile']));
     $this->assertTrue(isset($profile['readableFields']) || array_key_exists('readableFields', $profile));
     $this->assertTrue(is_array($profile['readableFields']));
     $this->assertTrue(isset($profile['updateableFields']) || array_key_exists('updateableFields', $profile));
     $this->assertTrue(is_array($profile['updateableFields']));
     // try to get user profile of different user
     $this->setExpectedException('Tinebase_Exception_AccessDenied');
     $sclever = Tinebase_Helper::array_value('sclever', Zend_Registry::get('personas'));
     $this->_instance->getUserProfile($sclever->getId());
 }
 /**
  * get other users container
  * 
  * @return Tinebase_Model_Container
  */
 protected function _getOtherUserContainer()
 {
     if (!$this->_otherUserContainer) {
         $sclever = Tinebase_Helper::array_value('sclever', Zend_Registry::get('personas'));
         $this->_otherUserContainer = Tinebase_Container::getInstance()->getDefaultContainer('Filemanager', $sclever->getId());
         Tinebase_Container::getInstance()->addGrants($this->_otherUserContainer->getId(), Tinebase_Acl_Rights::ACCOUNT_TYPE_ANYONE, NULL, array(Tinebase_Model_Grants::GRANT_READ), TRUE);
     }
     return $this->_otherUserContainer;
 }
 /**
  * install given application
  *
  * @param  SimpleXMLElement $_xml
  * @param  array | optional $_options
  * @return void
  * @throws Tinebase_Exception_Backend_Database
  */
 protected function _installApplication(SimpleXMLElement $_xml, $_options = null)
 {
     if ($this->_backend === NULL) {
         throw new Tinebase_Exception_Backend_Database('Need configured and working database backend for install.');
     }
     try {
         if (Setup_Core::isLogLevel(Zend_Log::INFO)) {
             Setup_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . ' Installing application: ' . $_xml->name);
         }
         $createdTables = array();
         // traditional xml declaration
         if (isset($_xml->tables)) {
             foreach ($_xml->tables[0] as $tableXML) {
                 $table = Setup_Backend_Schema_Table_Factory::factory('Xml', $tableXML);
                 $this->_createTable($table);
                 $createdTables[] = $table;
             }
         } else {
             $application = Setup_Core::getApplicationInstance($_xml->name, '', true);
             $models = $application->getModels(true);
             if (count($models) > 0) {
                 // create tables using doctrine 2
                 Setup_SchemaTool::createSchema($_xml->name, $models);
                 // adopt to old workflow
                 foreach ($models as $model) {
                     $modelConfiguration = $model::getConfiguration();
                     $createdTables[] = (object) array('name' => Tinebase_Helper::array_value('name', $modelConfiguration->getTable()), 'version' => $modelConfiguration->getVersion());
                 }
             }
         }
         $application = new Tinebase_Model_Application(array('name' => (string) $_xml->name, 'status' => $_xml->status ? (string) $_xml->status : Tinebase_Application::ENABLED, 'order' => $_xml->order ? (string) $_xml->order : 99, 'version' => (string) $_xml->version));
         $application = Tinebase_Application::getInstance()->addApplication($application);
         // keep track of tables belonging to this application
         foreach ($createdTables as $table) {
             Tinebase_Application::getInstance()->addApplicationTable($application, (string) $table->name, (int) $table->version);
         }
         // insert default records
         if (isset($_xml->defaultRecords)) {
             foreach ($_xml->defaultRecords[0] as $record) {
                 $this->_backend->execInsertStatement($record);
             }
         }
         // look for import definitions and put them into the db
         $this->createImportExportDefinitions($application);
         Setup_Initialize::initialize($application, $_options);
     } catch (Exception $e) {
         Tinebase_Exception::log($e, false);
         throw $e;
     }
 }
 /**
  * returns array of ldap data
  *
  * @param  Tinebase_Model_FullUser $_user
  * @return array
  */
 protected function _user2ldap(Tinebase_Model_FullUser $_user, array $_ldapEntry = array())
 {
     $ldapData = array('useraccountcontrol' => isset($_ldapEntry['useraccountcontrol']) ? $_ldapEntry['useraccountcontrol'][0] : self::NORMAL_ACCOUNT);
     foreach ($_user as $key => $value) {
         $ldapProperty = isset($this->_rowNameMapping[$key]) || array_key_exists($key, $this->_rowNameMapping) ? $this->_rowNameMapping[$key] : false;
         if ($ldapProperty === false) {
             continue;
         }
         switch ($key) {
             case 'accountLastPasswordChange':
                 // field is readOnly
                 break;
             case 'accountExpires':
                 if ($value instanceof DateTime) {
                     $ldapData[$ldapProperty] = bcmul(bcadd($value->getTimestamp(), '11644473600'), '10000000');
                 } else {
                     $ldapData[$ldapProperty] = '9223372036854775807';
                 }
                 break;
             case 'accountStatus':
                 if ($value == 'enabled') {
                     // unset account disable flag
                     $ldapData['useraccountcontrol'] &= ~self::ACCOUNTDISABLE;
                 } else {
                     // set account disable flag
                     $ldapData['useraccountcontrol'] |= self::ACCOUNTDISABLE;
                 }
                 break;
             case 'accountPrimaryGroup':
                 $ldapData[$ldapProperty] = Tinebase_Group::getInstance()->resolveUUIdToGIdNumber($value);
                 if ($this->_options['useRfc2307']) {
                     $ldapData['gidNumber'] = Tinebase_Group::getInstance()->resolveGidNumber($value);
                 }
                 break;
             default:
                 $ldapData[$ldapProperty] = $value;
                 break;
         }
     }
     $domainConfig = $this->getDomainConfiguration();
     $ldapData['name'] = $ldapData['cn'];
     $ldapData['userPrincipalName'] = $_user->accountLoginName . '@' . $domainConfig['domainName'];
     if ($this->_options['useRfc2307']) {
         // homedir is an required attribute
         if (empty($ldapData['unixhomedirectory'])) {
             $ldapData['unixhomedirectory'] = '/dev/null';
         }
         // set uidNumber only when not set in AD already
         if (empty($_ldapEntry['uidnumber'])) {
             $ldapData['uidnumber'] = $this->_generateUidNumber();
         }
         $ldapData['gidnumber'] = Tinebase_Group::getInstance()->resolveGidNumber($_user->accountPrimaryGroup);
         $ldapData['msSFU30NisDomain'] = Tinebase_Helper::array_value(0, explode('.', $domainConfig['domainName']));
     }
     if (isset($_user->sambaSAM) && $_user->sambaSAM instanceof Tinebase_Model_SAMUser) {
         $ldapData['profilepath'] = $_user->sambaSAM->profilePath;
         $ldapData['scriptpath'] = $_user->sambaSAM->logonScript;
         $ldapData['homedrive'] = $_user->sambaSAM->homeDrive;
         $ldapData['homedirectory'] = $_user->sambaSAM->homePath;
     }
     $ldapData['objectclass'] = isset($_ldapEntry['objectclass']) ? $_ldapEntry['objectclass'] : array();
     // check if user has all required object classes. This is needed
     // when updating users which where created using different requirements
     foreach ($this->_requiredObjectClass as $className) {
         if (!in_array($className, $ldapData['objectclass'])) {
             // merge all required classes at once
             $ldapData['objectclass'] = array_unique(array_merge($ldapData['objectclass'], $this->_requiredObjectClass));
             break;
         }
     }
     if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) {
         Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' LDAP data ' . print_r($ldapData, true));
     }
     return $ldapData;
 }
 /**
  * return vcalendar as string and replace organizers email address with emailaddess of current user
  * 
  * @param string $_filename  file to open
  * @return string
  */
 public static function getVCalendar($_filename)
 {
     $vcalendar = file_get_contents($_filename);
     $unittestUserEmail = Tinebase_Core::getUser()->accountEmailAddress;
     $vcalendar = preg_replace(array('/l.kneschke@metaway\\n s.de/', '/un[\\r\\n ]{0,3}ittest@[\\r\\n ]{0,3}ti[\\r\\n ]{0,3}ne20.org/', '/pwulf(\\n )?@tine20.org/', '/sclever@tine20.org/'), array($unittestUserEmail, $unittestUserEmail, Tinebase_Helper::array_value('pwulf', Zend_Registry::get('personas'))->accountEmailAddress, Tinebase_Helper::array_value('sclever', Zend_Registry::get('personas'))->accountEmailAddress), $vcalendar);
     return $vcalendar;
 }
 public function testArray_value()
 {
     $array = array(0 => 'foo', 'one' => 'bar');
     $this->assertEquals('foo', Tinebase_Helper::array_value(0, $array));
     $this->assertEquals('bar', Tinebase_Helper::array_value('one', $array));
 }
 /**
  * create a new group in sync backend
  *
  * @param  Tinebase_Model_Group  $_group
  * 
  * @return Tinebase_Model_Group|NULL
  */
 public function addGroupInSyncBackend(Tinebase_Model_Group $_group)
 {
     if ($this->_isReadOnlyBackend) {
         return NULL;
     }
     $dn = $this->_generateDn($_group);
     $objectClass = array('top', 'group');
     $ldapData = array('objectclass' => $objectClass, 'cn' => $_group->name, 'description' => $_group->description, 'samaccountname' => $_group->name);
     if ($this->_options['useRfc2307']) {
         $ldapData['objectclass'][] = 'posixGroup';
         $ldapData['gidnumber'] = $this->_generateGidNumber();
         $domainConfig = $this->getDomainConfiguration();
         $ldapData['msSFU30NisDomain'] = Tinebase_Helper::array_value(0, explode('.', $domainConfig['domainName']));
     }
     if (Tinebase_Core::isLogLevel(Zend_Log::INFO)) {
         Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . ' add group $dn: ' . $dn);
     }
     if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
         Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . '  $ldapData: ' . print_r($ldapData, true));
     }
     $this->getLdap()->add($dn, $ldapData);
     $groupId = $this->getLdap()->getEntry($dn, array($this->_groupUUIDAttribute));
     $groupId = $this->_decodeGroupId($groupId[$this->_groupUUIDAttribute][0]);
     $group = $this->getGroupByIdFromSyncBackend($groupId);
     return $group;
 }
 public function testAttendeeGroupMembersChange()
 {
     $defaultAdminGroup = Tinebase_Group::getInstance()->getDefaultAdminGroup();
     // create event and invite admin group
     $event = $this->_getEvent();
     // only events in future will be changed!
     $event->dtstart = Tinebase_DateTime::now()->addHour(1);
     $event->dtend = Tinebase_DateTime::now()->addHour(2);
     $event->attendee = $this->_getAttendee();
     $event->attendee[1] = new Calendar_Model_Attender(array('user_id' => $defaultAdminGroup->getId(), 'user_type' => Calendar_Model_Attender::USERTYPE_GROUP, 'role' => Calendar_Model_Attender::ROLE_REQUIRED));
     $persistentEvent = $this->_controller->create($event);
     // assert test condition
     $pwulf = $persistentEvent->attendee->filter('user_type', Calendar_Model_Attender::USERTYPE_GROUPMEMBER)->filter('user_id', $this->_getPersonasContacts('pwulf')->getId());
     $this->assertEquals(0, count($pwulf), 'invalid test condition, pwulf should not be member or admin group');
     Admin_Controller_Group::getInstance()->addGroupMember($defaultAdminGroup->getId(), $this->_getPersonasContacts('pwulf')->account_id);
     if (isset(Tinebase_Core::getConfig()->actionqueue)) {
         Tinebase_ActionQueue::getInstance()->processQueue(10000);
     }
     $loadedEvent = $this->_controller->get($persistentEvent->getId());
     // assert pwulf is in
     $pwulf = $loadedEvent->attendee->filter('user_type', Calendar_Model_Attender::USERTYPE_GROUPMEMBER)->filter('user_id', $this->_getPersonasContacts('pwulf')->getId());
     $this->assertEquals(1, count($pwulf), 'pwulf is not attender of event, but should be');
     Admin_Controller_Group::getInstance()->removeGroupMember($defaultAdminGroup->getId(), $this->_getPersonasContacts('pwulf')->account_id);
     if (isset(Tinebase_Core::getConfig()->actionqueue)) {
         Tinebase_ActionQueue::getInstance()->processQueue(10000);
     }
     $loadedEvent = $this->_controller->get($persistentEvent->getId());
     // assert pwulf is missing
     $pwulf = $loadedEvent->attendee->filter('user_type', Calendar_Model_Attender::USERTYPE_GROUPMEMBER)->filter('user_id', $this->_getPersonasContacts('pwulf')->getId());
     $this->assertEquals(0, count($pwulf), 'pwulf is attender of event, but not should be');
     // Test the same with update
     $group = Admin_Controller_Group::getInstance()->get($defaultAdminGroup->getId());
     $group->members = array_merge(Admin_Controller_Group::getInstance()->getGroupMembers($defaultAdminGroup->getId()), array(Tinebase_Helper::array_value('pwulf', Zend_Registry::get('personas'))->getId()));
     Admin_Controller_Group::getInstance()->update($group);
     if (isset(Tinebase_Core::getConfig()->actionqueue)) {
         Tinebase_ActionQueue::getInstance()->processQueue(10000);
     }
     // assert pwulf is in
     $loadedEvent = $this->_controller->get($persistentEvent->getId());
     $pwulf = $loadedEvent->attendee->filter('user_type', Calendar_Model_Attender::USERTYPE_GROUPMEMBER)->filter('user_id', $this->_getPersonasContacts('pwulf')->getId());
     $this->assertEquals(1, count($pwulf), 'pwulf is not attender of event, but should be (via update)');
     $group->members = array_diff(Admin_Controller_Group::getInstance()->getGroupMembers($defaultAdminGroup->getId()), array(Tinebase_Helper::array_value('pwulf', Zend_Registry::get('personas'))->getId()));
     Admin_Controller_Group::getInstance()->update($group);
     if (isset(Tinebase_Core::getConfig()->actionqueue)) {
         Tinebase_ActionQueue::getInstance()->processQueue(10000);
     }
     // assert pwulf is missing
     $loadedEvent = $this->_controller->get($persistentEvent->getId());
     $pwulf = $loadedEvent->attendee->filter('user_type', Calendar_Model_Attender::USERTYPE_GROUPMEMBER)->filter('user_id', $this->_getPersonasContacts('pwulf')->getId());
     $this->assertEquals(0, count($pwulf), 'pwulf is attender of event, but not should be');
 }
 /**
  * get estimate count of records to import
  */
 protected function _getEgwRecordEstimate()
 {
     $select = $this->_egwDb->select()->from(array('records' => $this->_egwTableName), 'COUNT(*) AS count');
     $this->_appendRecordFilter($select);
     $recordCount = Tinebase_Helper::array_value(0, $this->_egwDb->fetchAll($select, NULL, Zend_Db::FETCH_ASSOC));
     return $recordCount['count'];
 }
 /**
  * testMaintenanceModeLoginFail
  */
 public function testMaintenanceModeLoginFail()
 {
     Tinebase_Config::getInstance()->maintenanceMode = 1;
     $this->setExpectedException('Tinebase_Exception_MaintenanceMode');
     $this->_instance->login('sclever', Tinebase_Helper::array_value('password', TestServer::getInstance()->getTestCredentials()), new \Zend\Http\PhpEnvironment\Request());
 }
 /**
  * calendar has different grant handling
  * @see 0007450: shared calendars of other users (iOS)
  */
 public function testGetAllFoldersWithContainerSyncFilter()
 {
     $device = $this->_getDevice(Syncroton_Model_Device::TYPE_IPHONE);
     $controller = Syncroton_Data_Factory::factory($this->_class, $device, new Tinebase_DateTime(null, null, 'de_DE'));
     $folderA = $this->testCreateFolder();
     // personal of test user
     $sclever = Tinebase_Helper::array_value('sclever', Zend_Registry::get('personas'));
     $folderB = Tinebase_Core::getPreference('Calendar')->getValueForUser(Calendar_Preference::DEFAULTCALENDAR, $sclever->getId());
     // have syncGerant for sclever
     Tinebase_Container::getInstance()->setGrants($folderB, new Tinebase_Record_RecordSet('Tinebase_Model_Grants', array(array('account_id' => $sclever->getId(), 'account_type' => 'user', Tinebase_Model_Grants::GRANT_ADMIN => true), array('account_id' => Tinebase_Core::getUser()->getId(), 'account_type' => 'user', Tinebase_Model_Grants::GRANT_READ => true, Tinebase_Model_Grants::GRANT_SYNC => true))), TRUE);
     $syncFilter = new Calendar_Model_EventFilter(array(array('field' => 'container_id', 'operator' => 'in', 'value' => array($folderA->serverId, $folderB))));
     $syncFavorite = Tinebase_PersistentFilter::getInstance()->create(new Tinebase_Model_PersistentFilter(array('application_id' => Tinebase_Application::getInstance()->getApplicationByName('Calendar')->getId(), 'account_id' => Tinebase_Core::getUser()->getId(), 'model' => 'Calendar_Model_EventFilter', 'filters' => $syncFilter, 'name' => 'testSyncFilter', 'description' => 'test two folders')));
     $device->calendarfilterId = $syncFavorite->getId();
     $allSyncrotonFolders = $controller->getAllFolders();
     $defaultFolderId = Tinebase_Core::getPreference('Calendar')->{Calendar_Preference::DEFAULTCALENDAR};
     foreach ($allSyncrotonFolders as $syncrotonFolder) {
         $this->assertTrue($syncrotonFolder->serverId == $defaultFolderId ? $syncrotonFolder->type === Syncroton_Command_FolderSync::FOLDERTYPE_CALENDAR : $syncrotonFolder->type === Syncroton_Command_FolderSync::FOLDERTYPE_CALENDAR_USER_CREATED);
     }
     $this->assertEquals(2, count($allSyncrotonFolders));
     $this->assertArrayHasKey($folderA->serverId, $allSyncrotonFolders);
     $this->assertArrayHasKey($folderB, $allSyncrotonFolders);
 }
 /**
  * test account capabilities
  */
 public function testGetAccountCapabilities()
 {
     $capabilities = $this->_controller->updateCapabilities($this->_account);
     $account = $this->_controller->get($this->_account);
     $accountToString = print_r($this->_account->toArray(), TRUE);
     $this->assertEquals('', $account->ns_personal, $accountToString);
     $this->assertEquals(1, preg_match('@/|\\.@', $account->delimiter), $accountToString);
     $this->assertTrue(in_array('IMAP4', $capabilities['capabilities']) || in_array('IMAP4rev1', $capabilities['capabilities']), 'no IMAP4(rev1) capability found in ' . print_r($capabilities['capabilities'], TRUE));
     $this->assertTrue(in_array('QUOTA', $capabilities['capabilities']), 'no QUOTA capability found in ' . print_r($capabilities['capabilities'], TRUE));
     $this->assertEquals($capabilities, Tinebase_Helper::array_value($this->_account->getId(), Felamimail_Session::getSessionNamespace()->account));
 }
 /**
  * returns weekstart in iCal day format
  * 
  * @param  string $locale
  * @return string
  */
 public static function getWeekStart($locale = NULL)
 {
     $locale = $locale ?: Tinebase_Core::getLocale();
     $weekInfo = Zend_Locale::getTranslationList('week', $locale);
     if (!isset($weekInfo['firstDay'])) {
         $weekInfo['firstDay'] = 'mon';
     }
     return Tinebase_Helper::array_value($weekInfo['firstDay'], array_flip(self::$WEEKDAY_MAP));
 }
 /**
  * update to 0.28
  * - repair db charset for users with non default utf8 client charset
  */
 public function update_27()
 {
     $config = Setup_Core::get(Setup_Core::CONFIG);
     $tableprefix = $config->database->tableprefix;
     // have a second db connection with default charset
     $orgDb = Zend_Db::factory('Pdo_Mysql', $config->database->toArray());
     // fix for signed / unsigned problem
     $declaration = new Setup_Backend_Schema_Field_Xml('
         <field>
             <name>id</name>
             <type>integer</type>
             <autoincrement>true</autoincrement>
         </field>
     ');
     $this->_backend->alterCol('addressbook', $declaration);
     /** addressbook: store image in separate table **/
     $tableDefinition = '
         <table>
             <name>addressbook_image</name>
             <version>1</version>
             <declaration>
                 <field>
                     <name>contact_id</name>
                     <type>integer</type>
                     <notnull>true</notnull>
                 </field>
                 <field>
                     <name>image</name>
                     <type>blob</type>
                 </field>
                 <index>
                     <name>contact_id</name>
                     <primary>true</primary>
                     <field>
                         <name>contact_id</name>
                     </field>
                 </index>
                 <index>
                     <name>addressbook_image::contact_id-addressbook::id</name>
                     <field>
                         <name>contact_id</name>
                     </field>
                     <foreign>true</foreign>
                     <reference>
                         <table>addressbook</table>
                         <field>id</field>
                         <ondelete>CASCADE</ondelete>
                     </reference>
                 </index>
             </declaration>
         </table>
     ';
     $table = Setup_Backend_Schema_Table_Factory::factory('String', $tableDefinition);
     $this->_backend->createTable($table);
     $select = $orgDb->select()->from("{$tableprefix}addressbook", array('id'))->where($orgDb->quoteIdentifier('jpegphoto') . " IS NOT NULL");
     $contactIds = $orgDb->fetchAll($select);
     foreach ($contactIds as $contactId) {
         $contactId = $contactId['id'];
         $select = $orgDb->select()->from("{$tableprefix}addressbook", array('id', 'jpegphoto'))->where($orgDb->quoteInto($orgDb->quoteIdentifier('id') . ' = ?', $contactId));
         $imageData = $orgDb->fetchRow($select);
         $orgDb->insert("{$tableprefix}addressbook_image", array('contact_id' => $imageData['id'], 'image' => base64_encode($imageData['jpegphoto'])));
     }
     $this->_backend->dropCol('addressbook', 'jpegphoto');
     /** convert serialized object into json objects **/
     $select = $orgDb->select()->from("{$tableprefix}filter", array('id', 'filters'));
     $filters = $orgDb->fetchAll($select);
     foreach ($filters as $filter) {
         $filterObject = unserialize($filter['filters']);
         $orgDb->update("{$tableprefix}filter", array('filters' => Zend_Json::encode($filterObject)), $orgDb->quoteInto($orgDb->quoteIdentifier('id') . ' = ?', $filter['id']));
     }
     /** convert db contenets for installations which had a clientcharset != utf8 **/
     $originalCharset = Tinebase_Helper::array_value('Value', Tinebase_Helper::array_value(0, $orgDb->query("SHOW VARIABLES LIKE 'character_set_client'")->fetchAll()));
     if (strtolower($originalCharset) != 'utf8') {
         $this->_db->query("SET FOREIGN_KEY_CHECKS=0");
         $orgDb->query("SET FOREIGN_KEY_CHECKS=0");
         // build the list of tables to convert
         $tables = array();
         $rawTables = $this->_db->query("SHOW TABLES")->fetchAll();
         foreach ($rawTables as $rawTable) {
             $tableName = array_values($rawTable);
             $tableName = $tableName[0];
             if (preg_match("/^{$tableprefix}/", $tableName) && $tableName != "{$tableprefix}addressbook_image") {
                 $tables[] = $tableName;
             }
         }
         // the actual charset conversion is done by the db.
         foreach ($tables as $tableName) {
             Setup_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Converting table ' . $tableName);
             //$this->_db->query("SET character_set_client = '$originalCharset'");
             $select = $orgDb->select()->from($tableName);
             $result = $orgDb->fetchAll($select);
             $orgDb->query("TRUNCATE TABLE " . $this->_db->quoteIdentifier($tableName));
             //$this->_db->query("SET character_set_client = 'utf8'");
             foreach ($result as $row) {
                 try {
                     $this->_db->insert($tableName, $row);
                 } catch (Zend_Db_Statement_Exception $zdse) {
                     Setup_Core::getLogger()->warn(__METHOD__ . '::' . __LINE__ . ' ' . $zdse->getMessage());
                     // try to convert strings if failure
                     if (preg_match('/(description|title|note|old_value|org_name|adr_one_street)/', $zdse->getMessage(), $match)) {
                         $field = $match[1];
                         Setup_Core::getLogger()->warn(__METHOD__ . '::' . __LINE__ . ' Converting field ' . $field . (isset($row['id']) || array_key_exists('id', $row) ? ' of record ' . $row['id'] : ''));
                         $row[$field] = utf8_encode($row[$field]);
                         $this->_db->insert($tableName, $row);
                     } else {
                         Setup_Core::getLogger()->warn(__METHOD__ . '::' . __LINE__ . ' Could not convert field');
                         throw $zdse;
                     }
                 }
             }
         }
         $this->_db->query("SET FOREIGN_KEY_CHECKS=1");
     }
     $orgDb->closeConnection();
     $this->setApplicationVersion('Tinebase', '0.28');
 }