/**
  * the constructor
  * 
  * creates instance of Expressomail_Backend_Imap with parameters
  * Supported parameters are
  *   - user username
  *   - host hostname or ip address of IMAP server [optional, default = 'localhost']
  *   - password password for user 'username' [optional, default = '']
  *   - port port for IMAP server [optional, default = 110]
  *   - ssl 'SSL' or 'TLS' for secure sockets
  *   - folder select this folder [optional, default = 'INBOX']
  *
  * @param  array $params mail reader specific parameters
  * @throws Expressomail_Exception_IMAPInvalidCredentials
  * @return void
  */
 public function __construct($params, $_readOnly = FALSE)
 {
     if (is_array($params)) {
         $params = (object) $params;
     }
     if (!isset($params->user)) {
         throw new Expressomail_Exception_IMAPInvalidCredentials('Need at least user in params.');
     }
     $params->host = isset($params->host) ? $params->host : 'localhost';
     $params->password = isset($params->password) ? $params->password : '';
     $params->port = isset($params->port) ? $params->port : null;
     $params->ssl = isset($params->ssl) ? $params->ssl : false;
     $this->_params = $params;
     $expressomailConfig = Expressomail_Config::getInstance();
     $imapBackendConfigDefinition = $expressomailConfig->getDefinition(Expressomail_Config::IMAPBACKEND);
     $backendClassName = self::$_availableBackends[$imapBackendConfigDefinition['default']];
     $expressomailSettings = $expressomailConfig->get(Expressomail_Config::EXPRESSOMAIL_SETTINGS);
     $backendName = isset($expressomailSettings[Expressomail_Config::IMAPBACKEND]) ? $expressomailSettings[Expressomail_Config::IMAPBACKEND] : $imapBackendConfigDefinition['default'];
     if ($backendName != $imapBackendConfigDefinition['default']) {
         if (Tinebase_Helper::checkClassExistence(self::$_availableBackends[$backendName], true) && Tinebase_Helper::checkSubClassOf(self::$_availableBackends[$backendName], 'Expressomail_Backend_Imap_Interface', true)) {
             $backendClassName = self::$_availableBackends[$backendName];
         }
     }
     $this->_backend = new $backendClassName($params, $_readOnly);
 }
 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;
 }
 public function validate($username, $password)
 {
     if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
         Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Options: ' . print_r($this->_options, true));
     }
     $url = isset($this->_options['url']) ? $this->_options['url'] : 'https://localhost/validate/check';
     $adapter = new Zend_Http_Client_Adapter_Socket();
     $adapter->setStreamContext($this->_options = array('ssl' => array('verify_peer' => isset($this->_options['ignorePeerName']) ? false : true, 'allow_self_signed' => isset($this->_options['allowSelfSigned']) ? true : false)));
     $client = new Zend_Http_Client($url, array('maxredirects' => 0, 'timeout' => 30));
     $client->setAdapter($adapter);
     $params = array('user' => $username, 'pass' => $password);
     $client->setParameterPost($params);
     try {
         $response = $client->request(Zend_Http_Client::POST);
     } catch (Zend_Http_Client_Adapter_Exception $zhcae) {
         Tinebase_Exception::log($zhcae);
         return Tinebase_Auth::FAILURE;
     }
     $body = $response->getBody();
     if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
         Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Request: ' . $client->getLastRequest());
     }
     if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
         Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Response: ' . $body);
     }
     if ($response->getStatus() !== 200) {
         return Tinebase_Auth::FAILURE;
     }
     $result = Tinebase_Helper::jsonDecode($body);
     if (isset($result['result']) && $result['result']['status'] === true && $result['result']['value'] === true) {
         return Tinebase_Auth::SUCCESS;
     } else {
         return Tinebase_Auth::FAILURE;
     }
 }
 /**
  * factory function to return a selected account/imap backend class
  *
  * @param   string|Expressomail_Model_Account $_accountId
  * @return  Expressomail_Backend_Sieve
  */
 public static function factory($_accountId)
 {
     $accountId = $_accountId instanceof Expressomail_Model_Account ? $_accountId->getId() : $_accountId;
     if (!isset(self::$_backends[$accountId])) {
         $account = $_accountId instanceof Expressomail_Model_Account ? $_accountId : Expressomail_Controller_Account::getInstance()->get($accountId);
         // get imap config from account to connect with sieve server
         $sieveConfig = $account->getSieveConfig();
         // we need to instantiate a new sieve backend
         if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
             Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Connecting to server ' . $sieveConfig['host'] . ':' . $sieveConfig['port'] . ' (secure: ' . (array_key_exists('ssl', $sieveConfig) && $sieveConfig['ssl'] !== FALSE ? $sieveConfig['ssl'] : 'none') . ') with user ' . $sieveConfig['username']);
         }
         $expressomailConfig = Expressomail_Config::getInstance();
         $sieveBackendDefinition = $expressomailConfig->getDefinition(Expressomail_Config::SIEVEBACKEND);
         $backendClassName = self::$_availableBackends[$sieveBackendDefinition['default']];
         $expressomailSettings = $expressomailConfig->get(Expressomail_Config::EXPRESSOMAIL_SETTINGS);
         $backendName = isset($expressomailSettings[Expressomail_Config::SIEVEBACKEND]) ? $expressomailSettings[Expressomail_Config::SIEVEBACKEND] : $sieveBackendDefinition['default'];
         if ($sieveBackendName != $sieveBackendDefinition['default']) {
             if (Tinebase_Helper::checkClassExistence(self::$_availableBackends[$backendName], true)) {
                 $backendClassName = self::$_availableBackends[$backendName];
             }
         }
         self::$_backends[$accountId] = new $backendClassName($sieveConfig);
     }
     return self::$_backends[$accountId];
 }
 /**
  * testSearchArrayByRegexpKey
  * 
  * @see 0008782: Endless loop login windows when calling Active Sync Page
  */
 public function testSearchArrayByRegexpKey()
 {
     $server = array('REMOTE_USER' => '1', 'REDIRECT_REMOTE_USER' => '2', 'REDIRECT_REDIRECT_REMOTE_USER' => '3', 'OTHER' => '4');
     $remoteUserValues = Tinebase_Helper::searchArrayByRegexpKey('/REMOTE_USER$/', $server);
     $this->assertTrue(!empty($remoteUserValues));
     $this->assertEquals(3, count($remoteUserValues));
     $firstServerValue = array_shift($remoteUserValues);
     $this->assertEquals('1', $firstServerValue);
 }
 /**
  * (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;
 }
 /**
  * reads vcal blob and tries to repair some parsing problems that Sabre has
  *
  * @param string $blob
  * @param integer $failcount
  * @param integer $spacecount
  * @param integer $lastBrokenLineNumber
  * @param array $lastLines
  * @throws Sabre\VObject\ParseException
  * @return Sabre\VObject\Component\VCalendar
  *
  * @see 0006110: handle iMIP messages from outlook
  *
  * @todo maybe we can remove this when #7438 is resolved
  */
 public static function readVCalBlob($blob, $failcount = 0, $spacecount = 0, $lastBrokenLineNumber = 0, $lastLines = array())
 {
     // convert to utf-8
     $blob = Tinebase_Helper::mbConvertTo($blob);
     if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) {
         Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' ' . $blob);
     }
     try {
         $vcalendar = \Sabre\VObject\Reader::read($blob);
     } catch (Sabre\VObject\ParseException $svpe) {
         // NOTE: we try to repair\Sabre\VObject\Reader as it fails to detect followup lines that do not begin with a space or tab
         if ($failcount < 10 && preg_match('/Invalid VObject, line ([0-9]+) did not follow the icalendar\\/vcard format/', $svpe->getMessage(), $matches)) {
             if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
                 Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' ' . $svpe->getMessage() . ' lastBrokenLineNumber: ' . $lastBrokenLineNumber);
             }
             $brokenLineNumber = $matches[1] - 1 + $spacecount;
             if ($lastBrokenLineNumber === $brokenLineNumber) {
                 if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
                     Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Try again: concat this line to previous line.');
                 }
                 $lines = $lastLines;
                 $brokenLineNumber--;
                 // increase spacecount because one line got removed
                 $spacecount++;
             } else {
                 $lines = preg_split('/[\\r\\n]*\\n/', $blob);
                 if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
                     Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Concat next line to this one.');
                 }
                 $lastLines = $lines;
                 // for retry
             }
             $lines[$brokenLineNumber] .= $lines[$brokenLineNumber + 1];
             unset($lines[$brokenLineNumber + 1]);
             if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) {
                 Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' failcount: ' . $failcount . ' brokenLineNumber: ' . $brokenLineNumber . ' spacecount: ' . $spacecount);
             }
             $vcalendar = self::readVCalBlob(implode("\n", $lines), $failcount + 1, $spacecount, $brokenLineNumber, $lastLines);
         } else {
             throw $svpe;
         }
     }
     return $vcalendar;
 }
 /**
  * testCleanupCache
  */
 public function testCleanupCache()
 {
     $this->_instance->cleanupCache(Zend_Cache::CLEANING_MODE_ALL);
     $cache = Tinebase_Core::getCache();
     $oldLifetime = $cache->getOption('lifetime');
     $cache->setLifetime(1);
     $cacheId = Tinebase_Helper::convertCacheId('testCleanupCache');
     $cache->save('value', $cacheId);
     sleep(3);
     // cleanup with CLEANING_MODE_OLD
     $this->_instance->cleanupCache();
     $cache->setLifetime($oldLifetime);
     $this->assertFalse($cache->load($cacheId));
     // check for cache files
     $config = Tinebase_Core::getConfig();
     if ($config->caching && $config->caching->backend == 'File' && $config->caching->path) {
         $cacheFile = $this->_lookForCacheFile($config->caching->path);
         $this->assertEquals(NULL, $cacheFile, 'found cache file: ' . $cacheFile);
     }
 }
 /**
  * generic check admin rights function
  * rules: 
  * - ADMIN right includes all other rights
  * - MANAGE_* right includes VIEW_* right 
  * - results are cached if caching is active (with cache tag 'rights')
  * 
  * @param   string  $_right to check
  * @param   boolean $_throwException [optional]
  * @param   boolean $_includeTinebaseAdmin [optional]
  * @return  boolean
  * @throws  Tinebase_Exception_UnexpectedValue
  * @throws  Tinebase_Exception_AccessDenied
  * @throws  Tinebase_Exception
  * 
  * @todo move that to *_Acl_Rights
  * @todo include Tinebase admin? atm only the application admin right is checked
  * @todo think about moving the caching to Tinebase_Acl_Roles and use only a class cache as it is difficult (and slow?) to invalidate
  */
 public function checkRight($_right, $_throwException = TRUE, $_includeTinebaseAdmin = TRUE)
 {
     if (empty($this->_applicationName)) {
         throw new Tinebase_Exception_UnexpectedValue('No application name defined!');
     }
     if (!is_object(Tinebase_Core::getUser())) {
         throw new Tinebase_Exception('No user found for right check!');
     }
     $right = strtoupper($_right);
     $cache = Tinebase_Core::getCache();
     $cacheId = Tinebase_Helper::convertCacheId('checkRight' . Tinebase_Core::getUser()->getId() . $right . $this->_applicationName);
     $result = $cache->load($cacheId);
     if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) {
         Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' ' . $cacheId);
     }
     if (!$result) {
         $applicationRightsClass = $this->_applicationName . '_Acl_Rights';
         // array with the rights that should be checked, ADMIN is in it per default
         $rightsToCheck = $_includeTinebaseAdmin ? array(Tinebase_Acl_Rights::ADMIN) : array();
         if (preg_match("/VIEW_([A-Z_]*)/", $right, $matches)) {
             // manage right includes view right
             $rightsToCheck[] = constant($applicationRightsClass . '::MANAGE_' . $matches[1]);
         }
         $rightsToCheck[] = constant($applicationRightsClass . '::' . $right);
         $result = FALSE;
         if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) {
             Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' Checking rights: ' . print_r($rightsToCheck, TRUE));
         }
         foreach ($rightsToCheck as $rightToCheck) {
             if (Tinebase_Acl_Roles::getInstance()->hasRight($this->_applicationName, Tinebase_Core::getUser()->getId(), $rightToCheck)) {
                 $result = TRUE;
                 break;
             }
         }
         $cache->save($result, $cacheId, array('rights'), 120);
     }
     if (!$result && $_throwException) {
         throw new Tinebase_Exception_AccessDenied("You are not allowed to {$right} in application {$this->_applicationName} !");
     }
     return $result;
 }
 /**
  * filter input string for database as some databases (looking at you, MySQL) can't cope with some chars
  * 
  * @param string $string
  * @return string
  *
  * @see 0008644: error when sending mail with note (wrong charset)
  * @see http://stackoverflow.com/questions/1401317/remove-non-utf8-characters-from-string/8215387#8215387
  * @see http://stackoverflow.com/questions/8491431/remove-4-byte-characters-from-a-utf-8-string
  */
 public static function filterInputForDatabase($string)
 {
     if (self::getDb() instanceof Zend_Db_Adapter_Pdo_Mysql) {
         $string = Tinebase_Helper::mbConvertTo($string);
         // remove 4 byte utf8
         $result = preg_replace('/[\\xF0-\\xF7].../s', '?', $string);
     } else {
         $result = $string;
     }
     return $result;
 }
 /**
  * initializes the build constants like buildtype, package information, ...
  */
 public static function setupBuildConstants()
 {
     $config = self::getConfig();
     define('TINE20_BUILDTYPE', strtoupper($config->get('buildtype', 'DEVELOPMENT')));
     define('TINE20SETUP_CODENAME', Tinebase_Helper::getDevelopmentRevision());
     define('TINE20SETUP_PACKAGESTRING', 'none');
     define('TINE20SETUP_RELEASETIME', 'none');
 }
 /**
  * convert object with user data to ldap data array
  * 
  * @param  Tinebase_Model_FullUser  $_user
  * @param  array                    $_ldapData   the data to be written to ldap
  * @param  array                    $_ldapEntry  the data currently stored in ldap 
  */
 protected function _user2Ldap(Tinebase_Model_FullUser $_user, array &$_ldapData, array &$_ldapEntry = array())
 {
     if ($this instanceof Tinebase_EmailUser_Smtp_Interface) {
         if (empty($_user->smtpUser)) {
             return;
         }
         $mailSettings = $_user->smtpUser;
     } else {
         if (empty($_user->imapUser)) {
             return;
         }
         $mailSettings = $_user->imapUser;
     }
     foreach ($this->_propertyMapping as $objectProperty => $ldapAttribute) {
         $value = empty($mailSettings->{$objectProperty}) ? array() : $mailSettings->{$objectProperty};
         switch ($objectProperty) {
             case 'emailMailQuota':
                 // convert to bytes
                 $_ldapData[$ldapAttribute] = !empty($mailSettings->{$objectProperty}) ? Tinebase_Helper::convertToBytes($mailSettings->{$objectProperty} . 'M') : array();
                 break;
             case 'emailUID':
                 $_ldapData[$ldapAttribute] = $this->_appendDomain($_user->accountLoginName);
                 break;
             case 'emailGID':
                 $_ldapData[$ldapAttribute] = $this->_config['emailGID'];
                 break;
             case 'emailForwardOnly':
                 $_ldapData[$ldapAttribute] = $mailSettings->{$objectProperty} == true ? 'forwardonly' : array();
                 break;
             case 'emailAddress':
                 $_ldapData[$ldapAttribute] = $_user->accountEmailAddress;
                 break;
             default:
                 $_ldapData[$ldapAttribute] = $mailSettings->{$objectProperty};
                 break;
         }
     }
     if ((isset($this->_propertyMapping['emailForwards']) || array_key_exists('emailForwards', $this->_propertyMapping)) && empty($_ldapData[$this->_propertyMapping['emailForwards']])) {
         $_ldapData[$this->_propertyMapping['emailForwardOnly']] = 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;
         }
     }
 }
 /**
  * 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);
 }
 /**
  * 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;
 }
 /**
  * get max attachment size for outgoing mails
  * 
  * - currently it is set to memory_limit / 10
  * - returns size in Bytes
  * 
  * @return integer
  */
 protected function _getMaxAttachmentSize()
 {
     $configuredMemoryLimit = ini_get('memory_limit');
     if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
         Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' memory_limit = ' . $configuredMemoryLimit);
     }
     if ($configuredMemoryLimit === FALSE or $configuredMemoryLimit == -1) {
         // set to a big default value
         $configuredMemoryLimit = '512M';
     }
     return Tinebase_Helper::convertToBytes($configuredMemoryLimit) / 10;
 }
 /**
  * schema 3 = 1-x chars of firstname . lastname
  * 
  * @param Tinebase_Model_FullUser $_account
  * @return string
  */
 protected function _generateUserWithSchema3($_account)
 {
     $result = $_account->accountLastName;
     for ($i = 0; $i < strlen($_account->accountFirstName); $i++) {
         $userName = strtolower(substr(Tinebase_Helper::replaceSpecialChars($_account->accountFirstName), 0, $i + 1) . '.' . Tinebase_Helper::replaceSpecialChars($_account->accountLastName));
         if (!$this->nameExists('accountLoginName', $userName)) {
             $result = $userName;
             break;
         }
     }
     return $result;
 }
 /**
  * returns function parameter as object, decode Json if needed
  *
  * Prepare function input to be an array. Input maybe already an array or (empty) text.
  * Starting PHP 7 Zend_Json::decode can't handle empty strings.
  *
  * @param  mixed $_dataAsArrayOrJson
  * @return array
  */
 protected function _prepareParameter($_dataAsArrayOrJson)
 {
     return Tinebase_Helper::jsonDecode($_dataAsArrayOrJson);
 }
 /**
  * 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));
 }
 /**
  * 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');
 }
 /**
  * creates demo data for all applications
  * accepts same arguments as Tinebase_Frontend_Cli_Abstract::createDemoData
  * and the additional argument "skipAdmin" to force no user/group/role creation
  * 
  * @param Zend_Console_Getopt $_opts
  */
 public function createAllDemoData($_opts)
 {
     if (!$this->_checkAdminRight()) {
         return FALSE;
     }
     // fetch all applications and check if required are installed, otherwise remove app from array
     $applications = Tinebase_Application::getInstance()->getApplicationsByState(Tinebase_Application::ENABLED)->name;
     foreach ($applications as $appName) {
         echo 'Searching for DemoData in application "' . $appName . '"...' . PHP_EOL;
         $className = $appName . '_Setup_DemoData';
         if (class_exists($className)) {
             echo 'DemoData in application "' . $appName . '" found!' . PHP_EOL;
             $required = $className::getRequiredApplications();
             foreach ($required as $requiredApplication) {
                 if (!Tinebase_Helper::in_array_case($applications, $requiredApplication)) {
                     echo 'Creating DemoData for Application ' . $appName . ' is impossible, because application "' . $requiredApplication . '" is not installed.' . PHP_EOL;
                     continue 2;
                 }
             }
             $this->_applicationsToWorkOn[$appName] = array('appName' => $appName, 'required' => $required);
         } else {
             echo 'DemoData in application "' . $appName . '" not found.' . PHP_EOL . PHP_EOL;
         }
     }
     unset($applications);
     foreach ($this->_applicationsToWorkOn as $app => $cfg) {
         $this->_createDemoDataRecursive($app, $cfg, $_opts);
     }
     return 0;
 }
 /**
  * converts raw data from adapter into a set of records
  *
  * @param  array $_rawData of arrays
  * @return Tinebase_Record_RecordSet
  */
 protected function _rawDataToRecordSet(array $_rawData)
 {
     $events = new Tinebase_Record_RecordSet($this->_modelName);
     $events->addIndices(array('rrule', 'recurid'));
     foreach ($_rawData as $rawEvent) {
         $rawEvent['rrule_constraints'] = Tinebase_Helper::is_json($rawEvent['rrule_constraints']) ? json_decode($rawEvent['rrule_constraints'], true) : NULL;
         $events->addRecord(new Calendar_Model_Event($rawEvent, true));
     }
     $this->appendForeignRecordSetToRecordSet($events, 'attendee', 'id', Calendar_Backend_Sql_Attendee::FOREIGNKEY_EVENT, $this->_attendeeBackend);
     return $events;
 }
 /**
  * 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;
 }
 /**
  * do the mapping and replacements
  *
  * @param VCard $card
  * @param array $_headline [optional]
  * @return array
  * 
  * @todo split this into smaller parts
  */
 protected function _doMapping($card)
 {
     $data = array();
     $data = $this->_getName($card, $data);
     $data = $this->_getPhoto($card, $data);
     $data = $this->_getUrl($card, $data);
     // TODO check sample format support
     // BDAY:1996-04-15
     // BDAY:1953-10-15T23:10:00Z
     // BDAY:1987-09-27T08:30:00-06:00
     if ($card->getProperty('BDAY')) {
         $data['bday'] = $card->getProperty('BDAY')->value;
     }
     $addressProperty = $card->getProperty('ADR') ? 'ADR' : ($card->getProperty('ITEM1.ADR') ? 'ITEM1.ADR' : '');
     if ($addressProperty) {
         $properties = $card->getProperties($addressProperty);
         foreach ($properties as $property) {
             if (!array_key_exists('TYPE', $property->params)) {
                 $property->params['TYPE'] = 'work';
             }
             // types available from RFC : 'dom', 'intl', 'postal', 'parcel', 'home', 'work', 'pref'
             $types = $property->params['TYPE'];
             //post office box; the extended address; the street
             //address; the locality (e.g., city); the region (e.g., state or
             //province); the postal code; the country name
             $components = $property->getComponents();
             if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) {
                 Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' Address components ' . print_r($components, TRUE));
             }
             $mapping = array(NULL, 'street2', 'street', 'locality', 'region', 'postalcode', 'countryname');
             $adrType = $types && Tinebase_Helper::in_array_case($types, 'home') ? 'two' : 'one';
             foreach ($components as $index => $value) {
                 if (!isset($mapping[$index]) || $mapping[$index] === NULL) {
                     continue;
                 }
                 $data['adr_' . $adrType . '_' . $mapping[$index]] = $value;
             }
         }
     }
     // $properties = $card->getProperties('LABEL'); //NOT_IMPLEMENTED
     if ($card->getProperty('TEL')) {
         $properties = $card->getProperties('TEL');
         foreach ($properties as $property) {
             // types available from RFC : "home", "msg", "work", "pref", "voice", "fax", "cell", "video", "pager", "bbs", "modem", "car", "isdn", "pcs"
             $types = $property->params['TYPE'];
             $key = 'tel_work';
             if ($types) {
                 if (Tinebase_Helper::in_array_case($types, 'home') && !Tinebase_Helper::in_array_case($types, 'cell') && !Tinebase_Helper::in_array_case($types, 'fax')) {
                     $key = 'tel_home';
                 } else {
                     if (Tinebase_Helper::in_array_case($types, 'home') && Tinebase_Helper::in_array_case($types, 'cell')) {
                         $key = 'tel_cell_private';
                     } else {
                         if (Tinebase_Helper::in_array_case($types, 'home') && Tinebase_Helper::in_array_case($types, 'fax')) {
                             $key = 'tel_fax_home';
                         } else {
                             if (Tinebase_Helper::in_array_case($types, 'work') && !Tinebase_Helper::in_array_case($types, 'cell') && !Tinebase_Helper::in_array_case($types, 'fax')) {
                                 $key = 'tel_work';
                             } else {
                                 if (Tinebase_Helper::in_array_case($types, 'work') && Tinebase_Helper::in_array_case($types, 'cell')) {
                                     $key = 'tel_cell';
                                 } else {
                                     if (Tinebase_Helper::in_array_case($types, 'work') && !Tinebase_Helper::in_array_case($types, 'fax')) {
                                         $key = 'tel_fax';
                                     } else {
                                         if (Tinebase_Helper::in_array_case($types, 'car')) {
                                             $key = 'tel_car';
                                         } else {
                                             if (Tinebase_Helper::in_array_case($types, 'pager')) {
                                                 $key = 'tel_pager';
                                             } else {
                                                 if (Tinebase_Helper::in_array_case($types, 'fax')) {
                                                     $key = 'tel_fax';
                                                 } else {
                                                     if (Tinebase_Helper::in_array_case($types, 'cell')) {
                                                         $key = 'tel_cell';
                                                     }
                                                 }
                                             }
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
             $data[$key] = $property->value;
             //$data['tel_assistent'] = ''; //RFC has *a lot* of type, but not this one ^^
         }
     }
     if ($card->getProperty('EMAIL')) {
         $properties = $card->getProperties('EMAIL');
         foreach ($properties as $property) {
             // types available from RFC (custom allowed): "internet", "x400", "pref"
             // home and work are commons, so we manage them
             $types = $property->params['TYPE'];
             $key = 'email';
             if ($types) {
                 if (Tinebase_Helper::in_array_case($types, 'home')) {
                     $key = 'email_home';
                 }
             }
             $data[$key] = $property->value;
         }
     }
     // $properties = $card->getProperties('MAILER'); //NOT_IMPLEMENTED
     // TODO Check samples are supported
     // TZ:-05:00
     // TZ;VALUE=text:-05:00; EST; Raleigh/North America
     if ($card->getProperty('TZ')) {
         $data['tz'] = $card->getProperty('TZ')->value;
     }
     // $properties = $card->getProperties('GEO'); //NOT_IMPLEMENTED
     if ($card->getProperty('TITLE')) {
         $data['title'] = $card->getProperty('TITLE')->value;
     }
     if ($card->getProperty('ROLE')) {
         $data['role'] = $properties = $card->getProperty('ROLE')->value;
     }
     // $properties = $card->getProperties('LOGO'); // NOT_IMPLEMENTED
     // Type can be a specification "secretary", "assistant", etc.
     // Value can be a URI or a nested VCARD...
     // $data['assistent'] = $properties = $card->getProperties('AGENT'); // NESTED VCARD NOT SUPPORTED BY vcardphp
     if ($card->getProperty('ORG')) {
         $components = $card->getProperty('ORG')->getComponents();
         $data['org_name'] = $components[0];
         $data['org_unit'] = '';
         for ($i = 1; $i < count($components); $i++) {
             $data['org_unit'] .= $components[$i] . ";";
         }
     }
     // $properties = $card->getProperties('CATEGORIES'); // NOT_IMPLEMENTED
     if ($card->getProperty('NOTE')) {
         $data['note'] = $card->getProperty('NOTE')->value;
     }
     // $properties = $card->getProperties('PRODID'); // NOT_IMPLEMENTED
     // $properties = $card->getProperties('REV'); // NOT_IMPLEMENTED (could be with tine20 modification history)
     // $properties = $card->getProperties('SORT-STRING'); // NOT_IMPLEMENTED
     // $properties = $card->getProperties('SOUND'); // NOT_IMPLEMENTED
     // $properties = $card->getProperties('UID'); // NOT_IMPLEMENTED
     // $properties = $card->getProperties('VERSION'); // NOT_IMPLEMENTED
     // $properties = $card->getProperties('CLASS'); // NOT_IMPLEMENTED
     // TODO $data['pubkey'] = $properties = $card->getProperties('KEY'); // NOT_IMPLEMENTED // missing binary uncode
     return $data;
 }
 /**
  * get anonymous registry
  * 
  * @return array
  */
 protected function _getAnonymousRegistryData()
 {
     $locale = Tinebase_Core::get('locale');
     $tbFrontendHttp = new Tinebase_Frontend_Http();
     // default credentials
     if (isset(Tinebase_Core::getConfig()->login)) {
         $loginConfig = Tinebase_Core::getConfig()->login;
         $defaultUsername = isset($loginConfig->username) ? $loginConfig->username : '';
         $defaultPassword = isset($loginConfig->password) ? $loginConfig->password : '';
     } else {
         $defaultUsername = '';
         $defaultPassword = '';
     }
     $symbols = Zend_Locale::getTranslationList('symbols', $locale);
     $registryData = array('modSsl' => Tinebase_Auth::getConfiguredBackend() == Tinebase_Auth::MODSSL, 'serviceMap' => $tbFrontendHttp->getServiceMap(), 'locale' => array('locale' => $locale->toString(), 'language' => Zend_Locale::getTranslation($locale->getLanguage(), 'language', $locale), 'region' => Zend_Locale::getTranslation($locale->getRegion(), 'country', $locale)), 'version' => array('buildType' => TINE20_BUILDTYPE, 'codeName' => TINE20_CODENAME, 'packageString' => TINE20_PACKAGESTRING, 'releaseTime' => TINE20_RELEASETIME, 'filesHash' => TINE20_BUILDTYPE != 'DEVELOPMENT' ? $tbFrontendHttp->getJsCssHash() : null), 'defaultUsername' => $defaultUsername, 'defaultPassword' => $defaultPassword, 'denySurveys' => Tinebase_Core::getConfig()->denySurveys, 'titlePostfix' => Tinebase_Config::getInstance()->get(Tinebase_Config::PAGETITLEPOSTFIX), 'redirectUrl' => Tinebase_Config::getInstance()->get(Tinebase_Config::REDIRECTURL), 'helpUrl' => Tinebase_Core::getConfig()->helpUrl, 'maxFileUploadSize' => Tinebase_Helper::convertToBytes(ini_get('upload_max_filesize')), 'maxPostSize' => Tinebase_Helper::convertToBytes(ini_get('post_max_size')), 'thousandSeparator' => $symbols['group'], 'decimalSeparator' => $symbols['decimal'], 'filesystemAvailable' => Tinebase_Core::isFilesystemAvailable());
     if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) {
         Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' Anonymous registry: ' . print_r($registryData, TRUE));
     }
     return $registryData;
 }
 /**
  * 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;
 }
 /**
  * invalidate rights cache
  * 
  * @param int   $roleId
  * @param array $roleRights  the role rights to purge from cache
  */
 protected function _invalidateRightsCache($roleId, $roleRights)
 {
     if (Tinebase_Core::isLogLevel(Zend_Log::INFO)) {
         Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . ' Invalidating rights cache for role id ' . $roleId);
     }
     $rightsInvalidateCache = array();
     foreach ($roleRights as $right) {
         $rightsInvalidateCache[] = strtoupper($right['right']) . Tinebase_Application::getInstance()->getApplicationById($right['application_id'])->name;
     }
     // @todo can be further improved, by only selecting the users which are members of this role
     $userIds = Tinebase_User::getInstance()->getUsers()->getArrayOfIds();
     if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) {
         Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' ' . print_r($rightsInvalidateCache, TRUE));
     }
     foreach ($rightsInvalidateCache as $rightData) {
         foreach ($userIds as $userId) {
             $cacheId = Tinebase_Helper::convertCacheId('checkRight' . $userId . $rightData);
             if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) {
                 Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' Removing cache id ' . $cacheId);
             }
             Tinebase_Core::getCache()->remove($cacheId);
         }
     }
     $this->resetClassCache();
 }
 /**
  * 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);
         }
     }
 }
 /**
  * (mime) encode some headers ('subject', 'from', 'to', ...)
  * 
  * @param string $_header
  * @return string
  * 
  * @todo support multiple to, ... headers
  */
 protected function _fixHeaderEncoding($_header)
 {
     $result = $_header;
     $encoding = extension_loaded('mbstring') ? mb_detect_encoding($result) : 'unknown';
     if ($encoding !== 'ASCII' && preg_match('/[^\\x20-\\x7E]*/', $result)) {
         if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
             Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Non-ASCII character (encoding:' . $encoding . ') detected, mime encode some headers.');
         }
         foreach (array('subject', 'from', 'to', 'cc', 'bcc') as $field) {
             if (preg_match('/' . $field . ': (.*?[\\n][\\s]*?)/i', $result, $matches)) {
                 if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) {
                     Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' ' . print_r($matches, TRUE));
                 }
                 $headerValue = str_replace("\n", '', $matches[1]);
                 $headerValue = Tinebase_Helper::mbConvertTo($headerValue);
                 $headerString = iconv_mime_encode(ucfirst($field), $headerValue);
                 $result = str_replace($matches[0], $headerString . "\n", $result);
             }
         }
         if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) {
             Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' ' . $result);
         }
     }
     return $result;
 }
 /**
  * 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'];
 }