/**
  * 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;
 }
 /**
  * returns binary string in given format
  *
  * @param string    $_mime
  * @param int       $_maxSize in bytes
  * @return string
  */
 public function getBlob($_mime = 'image/jpeg', $_maxSize = 0)
 {
     if ($this->mime != $_mime) {
         $img = @imagecreatefromstring($this->blob);
         $tmpPath = tempnam(Tinebase_Core::getTempDir(), 'tine20_tmp_gd');
         switch ($_mime) {
             case 'image/png':
                 imagepng($img, $tmpPath, 0);
                 break;
             case 'image/jpeg':
                 imagejpeg($img, $tmpPath, 100);
                 break;
             case 'image/gif':
                 imagegif($img, $tmpPath);
                 break;
             default:
                 throw new Tinebase_Exception_InvalidArgument("Unsupported image type: " . $_mime);
                 break;
         }
         $blob = file_get_contents($tmpPath);
         unlink($tmpPath);
     } else {
         $blob = $this->blob;
     }
     if ($_maxSize) {
         $originalSize = strlen($blob);
         if ($originalSize > $_maxSize) {
             $cacheId = Tinebase_Helper::convertCacheId(__METHOD__ . $this->id . $_mime . $_maxSize);
             if (Tinebase_Core::getCache()->test($cacheId)) {
                 $blob = Tinebase_Core::getCache()->load($cacheId);
                 return $blob;
             }
             // NOTE: resampling 1:1 through GD changes images size so
             //       we always to through GD before furthor calculations
             $qS = $_maxSize / strlen($blob);
             $qD = $_mime != $this->mime ? sqrt($qS) : 1;
             $qF = 1;
             $i = 0;
             do {
                 // feedback fault
                 $qD = $qD * $qF;
                 $clone = clone $this;
                 $clone->resize(floor($this->width * $qD), floor($this->height * $qD), self::RATIOMODE_PRESERVANDCROP);
                 $blob = $clone->getBlob();
                 $size = strlen($blob);
                 // size factor achieved;
                 $qSA = $size / $originalSize;
                 // size fault factor
                 $qF = sqrt($qS / $qSA);
                 if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
                     Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . " resized {$this->id}: qS: {$qS} qD: {$qD} qSA: {$qSA} sizeA: {$size} qF: {$qF} ");
                 }
                 // feedback size fault factor if we are still to big or more than 1% to small per attempt
             } while ($qF > 1 + $i++ * 0.01 || $qF < 1);
             Tinebase_Core::getCache()->save($blob, $cacheId, array(), null);
         }
     }
     return $blob;
 }
 /**
  * returns list of all available translations
  * 
  * NOTE available are those, having a Tinebase translation
  * 
  * @return array list of all available translation
  *
  * @todo add test
  */
 public static function getAvailableTranslations($appName = 'Tinebase')
 {
     $availableTranslations = array();
     // look for po files in Tinebase
     $officialTranslationsDir = dirname(__FILE__) . "/../{$appName}/translations";
     foreach (scandir($officialTranslationsDir) as $poFile) {
         list($localestring, $suffix) = explode('.', $poFile);
         if ($suffix == 'po') {
             $availableTranslations[$localestring] = array('path' => "{$officialTranslationsDir}/{$poFile}");
         }
     }
     // lookup/merge custom translations
     if (Tinebase_Config::isReady() === TRUE) {
         $logger = Tinebase_Core::getLogger();
         $customTranslationsDir = Tinebase_Config::getInstance()->translations;
         if ($customTranslationsDir) {
             foreach ((array) @scandir($customTranslationsDir) as $dir) {
                 $poFile = "{$customTranslationsDir}/{$dir}/{$appName}/translations/{$dir}.po";
                 if (is_readable($poFile)) {
                     $availableTranslations[$dir] = array('path' => $poFile);
                 }
             }
         }
     } else {
         $logger = null;
     }
     $filesToWatch = array();
     // compute information
     foreach ($availableTranslations as $localestring => $info) {
         if (!Zend_Locale::isLocale($localestring, TRUE, FALSE)) {
             if ($logger) {
                 $logger->WARN(__METHOD__ . '::' . __LINE__ . " {$localestring} is not supported, removing translation form list");
             }
             unset($availableTranslations[$localestring]);
             continue;
         }
         $filesToWatch[] = $info['path'];
     }
     if (Tinebase_Config::isReady()) {
         $cache = new Zend_Cache_Frontend_File(array('master_files' => $filesToWatch));
         $cache->setBackend(Tinebase_Core::get(Tinebase_Core::CACHE)->getBackend());
     } else {
         $cache = null;
     }
     if ($cache) {
         $cacheId = Tinebase_Helper::convertCacheId(__FUNCTION__ . $appName . sha1(serialize($filesToWatch)));
         $cache = new Zend_Cache_Frontend_File(array('master_files' => $filesToWatch));
         $cache->setBackend(Tinebase_Core::get(Tinebase_Core::CACHE)->getBackend());
         if ($cachedTranslations = $cache->load($cacheId)) {
             $cachedTranslations = unserialize($cachedTranslations);
             if ($cachedTranslations !== null) {
                 return $cachedTranslations;
             }
         }
     }
     // compute information
     foreach ($availableTranslations as $localestring => $info) {
         // fetch header grep for X-Poedit-Language, X-Poedit-Country
         $fh = fopen($info['path'], 'r');
         $header = fread($fh, 1024);
         fclose($fh);
         preg_match('/X-Tine20-Language: (.+)(?:\\\\n?)(?:"?)/', $header, $language);
         preg_match('/X-Tine20-Country: (.+)(?:\\\\n?)(?:"?)/', $header, $region);
         $locale = new Zend_Locale($localestring);
         $availableTranslations[$localestring]['locale'] = $localestring;
         $availableTranslations[$localestring]['language'] = isset($language[1]) ? $language[1] : Zend_Locale::getTranslation($locale->getLanguage(), 'language', $locale);
         $availableTranslations[$localestring]['region'] = isset($region[1]) ? $region[1] : Zend_Locale::getTranslation($locale->getRegion(), 'country', $locale);
     }
     ksort($availableTranslations);
     if ($cache) {
         $cache->save(serialize($availableTranslations), $cacheId, array(), 86400);
     }
     return $availableTranslations;
 }
 /**
  * return account ids of accounts which made personal container accessible to given account
  *
  * @param   string|Tinebase_Model_User          $_accountId
  * @param   string|Tinebase_Model_Application   $_application
  * @param   array|string                        $_grant
  * @param   bool                                $_ignoreACL
  * @param   bool                                $_andGrants
  * @return  array of array of containerData
  */
 protected function _getOtherAccountIds($_accountId, $_application, $_grant, $_ignoreACL = FALSE, $_andGrants = FALSE)
 {
     $accountId = Tinebase_Model_User::convertUserIdToInt($_accountId);
     $application = Tinebase_Application::getInstance()->getApplicationByName($_application);
     $grant = $_ignoreACL ? '*' : $_grant;
     $classCacheId = Tinebase_Helper::convertCacheId($accountId . $application->getId() . implode('', (array) $grant) . (int) $_ignoreACL . (int) $_andGrants);
     try {
         return $this->loadFromClassCache(__FUNCTION__, $classCacheId);
     } catch (Tinebase_Exception_NotFound $tenf) {
         // continue...
     }
     // first grab all container ids ...
     $select = $this->_db->select()->distinct()->from(array('container_acl' => SQL_TABLE_PREFIX . 'container_acl'), array())->join(array('container' => SQL_TABLE_PREFIX . 'container'), "{$this->_db->quoteIdentifier('container_acl.container_id')} = {$this->_db->quoteIdentifier('container.id')}", array('container_id' => 'container.id'))->where("{$this->_db->quoteIdentifier('container.application_id')} = ?", $application->getId())->where("{$this->_db->quoteIdentifier('container.type')} = ?", Tinebase_Model_Container::TYPE_PERSONAL)->where("{$this->_db->quoteIdentifier('container.is_deleted')} = ?", 0, Zend_Db::INT_TYPE);
     $this->addGrantsSql($select, $accountId, $grant, 'container_acl', $_andGrants, __CLASS__ . '::addGrantsSqlCallback');
     $stmt = $this->_db->query('/*' . __FUNCTION__ . '*/' . $select);
     $containerIds = $stmt->fetchAll(Zend_Db::FETCH_COLUMN);
     // no container ids found / can stop here
     if (empty($containerIds)) {
         return $containerIds;
     }
     // ... now get the owners of the containers
     $select = $this->_db->select()->distinct()->from(array('container_acl' => SQL_TABLE_PREFIX . 'container_acl'), array('account_id'))->join(array('container' => SQL_TABLE_PREFIX . 'container'), "{$this->_db->quoteIdentifier('container_acl.container_id')} = {$this->_db->quoteIdentifier('container.id')}", array())->join(array('accounts' => SQL_TABLE_PREFIX . 'accounts'), "{$this->_db->quoteIdentifier('container_acl.account_id')} = {$this->_db->quoteIdentifier('accounts.id')}", array())->where("{$this->_db->quoteIdentifier('container.id')} IN (?)", $containerIds)->where("{$this->_db->quoteIdentifier('container_acl.account_id')} != ?", $accountId)->where("{$this->_db->quoteIdentifier('container_acl.account_grant')} = ?", Tinebase_Model_Grants::GRANT_ADMIN)->where("{$this->_db->quoteIdentifier('accounts.status')} = ?", 'enabled');
     $stmt = $this->_db->query('/*' . __FUNCTION__ . '*/' . $select);
     $accountIds = $stmt->fetchAll(Zend_Db::FETCH_COLUMN);
     $this->saveInClassCache(__FUNCTION__, $classCacheId, $accountIds);
     return $accountIds;
 }
 /**
  * get nodes from cache
  * if cache miss or cache etag is outdated, updates cache with nodes from backend
  *
  * @param string $path path
  * @param string $etag hash etag
  * @return array of nodes
  */
 private function getNodesFromCache($path, $etag)
 {
     $cache = Tinebase_Core::get('cache');
     $cacheId = Tinebase_Helper::convertCacheId('getExpressodriveEtags' . sha1(Tinebase_Core::getUser()->getId() . $this->encodePath($path)));
     $result = $cache->load($cacheId);
     if (!$result) {
         $result = $this->getNodesFromBackend($path);
         $cache->save($result, $cacheId, array('expressodriverEtags'), $this->cacheLifetime);
     } else {
         if ($result[0]['hash'] != $etag) {
             $result = $this->getNodesFromBackend($path);
             $cache->save($result, $cacheId, array('expressodriverEtags'), $this->cacheLifetime);
         }
     }
     return $result;
 }
 /**
  * Returns settings for crm app
  * - result is cached
  *
  * @param boolean $_resolve if some values should be resolved (here yet unused)
  * @return  Crm_Model_Config
  * 
  * @todo check 'endslead' values
  * @todo use keyfield configs here
  */
 public function getConfigSettings($_resolve = FALSE)
 {
     $cache = Tinebase_Core::get('cache');
     $cacheId = Tinebase_Helper::convertCacheId('getCrmSettings');
     $result = $cache->load($cacheId);
     if (!$result) {
         if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
             Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Fetching Crm Settings ...');
         }
         $translate = Tinebase_Translation::getTranslation('Crm');
         $result = new Crm_Model_Config(array('defaults' => parent::getConfigSettings()));
         $others = array(Crm_Model_Config::LEADTYPES => array(array('id' => 1, 'leadtype' => $translate->_('Customer')), array('id' => 2, 'leadtype' => $translate->_('Partner')), array('id' => 3, 'leadtype' => $translate->_('Reseller'))), Crm_Model_Config::LEADSTATES => array(array('id' => 1, 'leadstate' => $translate->_('open'), 'probability' => 0, 'endslead' => 0), array('id' => 2, 'leadstate' => $translate->_('contacted'), 'probability' => 10, 'endslead' => 0), array('id' => 3, 'leadstate' => $translate->_('waiting for feedback'), 'probability' => 30, 'endslead' => 0), array('id' => 4, 'leadstate' => $translate->_('quote sent'), 'probability' => 50, 'endslead' => 0), array('id' => 5, 'leadstate' => $translate->_('accepted'), 'probability' => 100, 'endslead' => 1), array('id' => 6, 'leadstate' => $translate->_('lost'), 'probability' => 0, 'endslead' => 1)), Crm_Model_Config::LEADSOURCES => array(array('id' => 1, 'leadsource' => $translate->_('Market')), array('id' => 2, 'leadsource' => $translate->_('Email')), array('id' => 3, 'leadsource' => $translate->_('Telephone')), array('id' => 4, 'leadsource' => $translate->_('Website'))));
         foreach ($others as $setting => $defaults) {
             $result->{$setting} = Crm_Config::getInstance()->get($setting, new Tinebase_Config_Struct($defaults))->toArray();
         }
         // save result and tag it with 'settings'
         $cache->save($result, $cacheId, array('settings'));
     }
     return $result;
 }
 /**
  * @return array
  *
  * @param bool $MCV2only filter for new modelconfig with doctrine schema tool
  */
 public function getModels($MCV2only = false)
 {
     if ($this->_models === null && !empty($this->_applicationName)) {
         $cache = Tinebase_Core::getCache();
         $cacheId = Tinebase_Helper::convertCacheId('getModels' . $this->_applicationName);
         $models = $cache->load($cacheId);
         if (!$models) {
             $models = $this->_getModelsFromAppDir();
             // cache for a long time only on prod
             $cache->save($models, $cacheId, array(), TINE20_BUILDTYPE === 'DEVELOPMENT' ? 1 : 3600);
         }
         $this->_models = $models;
     }
     if ($MCV2only) {
         if (!Setup_Core::isDoctrineAvailable()) {
             if (Tinebase_Core::isLogLevel(Zend_Log::WARN)) {
                 Tinebase_Core::getLogger()->warn(__METHOD__ . '::' . __LINE__ . ' Doctrine not available, could not get modelconfig v2 models for application (php version id: ' . PHP_VERSION_ID . ')');
             }
             return array();
         }
         $md = new Tinebase_Record_DoctrineMappingDriver();
         $MCv2Models = array();
         foreach ((array) $this->_models as $model) {
             if ($md->isTransient($model)) {
                 $MCv2Models[] = $model;
             }
         }
         return $MCv2Models;
     }
     return $this->_models;
 }
 /**
  * findCalendarHomeSet
  * - result ($this->calendarHomeSet) is cached for 1 week
  * 
  * @return boolean
  */
 public function findCalendarHomeSet()
 {
     if ('' == $this->currentUserPrincipal && !$this->findCurrentUserPrincipal(3)) {
         if (Tinebase_Core::isLogLevel(Zend_Log::INFO)) {
             Tinebase_Core::getLogger()->info(__METHOD__ . ' ' . __LINE__ . ' No principal found for user ' . $this->userName);
         }
         return false;
     }
     $cacheId = Tinebase_Helper::convertCacheId('findCalendarHomeSet' . $this->userName);
     if (Tinebase_Core::getCache()->test($cacheId)) {
         $this->calendarHomeSet = Tinebase_Core::getCache()->load($cacheId);
         if (Tinebase_Core::isLogLevel(Zend_Log::INFO)) {
             Tinebase_Core::getLogger()->info(__METHOD__ . ' ' . __LINE__ . ' Loading user home set from cache');
         }
         return true;
     }
     $result = $this->calDavRequest('PROPFIND', $this->currentUserPrincipal, self::findCalendarHomeSetRequest);
     if (isset($result['{urn:ietf:params:xml:ns:caldav}calendar-home-set'])) {
         $this->calendarHomeSet = $result['{urn:ietf:params:xml:ns:caldav}calendar-home-set'];
         Tinebase_Core::getCache()->save($this->calendarHomeSet, $cacheId, array(), 24 * 3600 * 7);
         return true;
     }
     Tinebase_Core::getLogger()->err(__METHOD__ . '::' . __LINE__ . ' couldn\'t find calendar homeset');
     return false;
 }
 /**
  * returns all grants of a given timeaccount
  * - this function caches its result (with cache tag 'container')
  *
  * @param  Timetracker_Model_Timeaccount $_timeaccount
  * @param  boolean $_ignoreACL
  * @return Tinebase_Record_RecordSet
  */
 public static function getTimeaccountGrants($_timeaccount, $_ignoreACL = FALSE)
 {
     if (!$_ignoreACL) {
         if (!Timetracker_Controller_Timeaccount::getInstance()->checkRight(Timetracker_Acl_Rights::MANAGE_TIMEACCOUNTS, FALSE)) {
             if (!self::hasGrant($_timeaccount, Tinebase_Model_Grants::GRANT_ADMIN)) {
                 throw new Tinebase_Exception_AccessDenied("You nor have the RIGHT either the GRANT to get see all grants for this timeaccount");
             }
         }
     }
     $container = Tinebase_Container::getInstance()->getContainerById($_timeaccount->container_id);
     $cache = Tinebase_Core::getCache();
     $cacheId = Tinebase_Helper::convertCacheId('getTimeaccountGrants' . Tinebase_Core::getUser()->getId() . $_timeaccount->getId() . $_ignoreACL . $container->last_modified_time);
     $result = $cache->load($cacheId);
     if ($result === FALSE) {
         $allContainerGrants = Tinebase_Container::getInstance()->getGrantsOfContainer($_timeaccount->container_id, true, 'Timetracker_Model_TimeaccountGrants');
         $allTimeaccountGrants = new Tinebase_Record_RecordSet('Timetracker_Model_TimeaccountGrants');
         foreach ($allContainerGrants as $index => $containerGrants) {
             $timeaccountGrants = new Timetracker_Model_TimeaccountGrants($containerGrants->toArray());
             $allTimeaccountGrants->addRecord($timeaccountGrants);
         }
         $result = $allTimeaccountGrants;
         $cache->save($result, $cacheId, array('container'));
     }
     return $result;
 }
 /**
  * convert container grants to principals 
  * 
  * @param Tinebase_Record_RecordSet $containers
  * @return array
  * 
  * @todo improve algorithm to fetch all contact/list_ids at once
  */
 protected function _containerGrantsToPrincipals(Tinebase_Record_RecordSet $containers)
 {
     if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
         Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Converting grants to principals for ' . count($containers) . ' containers.');
     }
     $result = array();
     foreach ($containers as $container) {
         $cacheId = Tinebase_Helper::convertCacheId('_containerGrantsToPrincipals' . $container->getId() . $container->seq);
         $containerPrincipals = Tinebase_Core::getCache()->load($cacheId);
         if ($containerPrincipals === false) {
             $containerPrincipals = array();
             $grants = Tinebase_Container::getInstance()->getGrantsOfContainer($container);
             foreach ($grants as $grant) {
                 switch ($grant->account_type) {
                     case 'group':
                         $group = Tinebase_Group::getInstance()->getGroupById($grant->account_id);
                         if ($group->list_id) {
                             $containerPrincipals[] = self::PREFIX_GROUPS . '/' . $group->list_id;
                         }
                         break;
                     case 'user':
                         // skip if grant belongs to the owner of the calendar
                         if ($contact->account_id == $grant->account_id) {
                             continue;
                         }
                         $user = Tinebase_User::getInstance()->getUserByPropertyFromSqlBackend('accountId', $grant->account_id);
                         if ($user->contact_id) {
                             $containerPrincipals[] = self::PREFIX_USERS . '/' . $user->contact_id;
                         }
                         break;
                 }
             }
             Tinebase_Core::getCache()->save($containerPrincipals, $cacheId, array(), 24 * 60 * 60);
         }
         $result = array_merge($result, $containerPrincipals);
     }
     // users and groups can be duplicate
     $result = array_unique($result);
     return $result;
 }
 /**
  * get custom fields for an application
  * - results are cached in class cache $_cfByApplicationCache
  * - results are cached if caching is active (with cache tag 'customfields')
  *
  * @param string|Tinebase_Model_Application $_applicationId application object, id or name
  * @param string                            $_modelName
  * @param string                            $_requiredGrant (read grant by default)
  * @return Tinebase_Record_RecordSet|Tinebase_Model_CustomField_Config of Tinebase_Model_CustomField_Config records
  */
 public function getCustomFieldsForApplication($_applicationId, $_modelName = NULL, $_requiredGrant = Tinebase_Model_CustomField_Grant::GRANT_READ)
 {
     $applicationId = Tinebase_Model_Application::convertApplicationIdToInt($_applicationId);
     $userId = is_object(Tinebase_Core::getUser()) ? Tinebase_Core::getUser()->getId() : 'nouser';
     $cfIndex = $applicationId . ($_modelName !== NULL ? $_modelName : '') . $_requiredGrant . $userId;
     if (isset($this->_cfByApplicationCache[$cfIndex])) {
         return $this->_cfByApplicationCache[$cfIndex];
     }
     $cache = Tinebase_Core::getCache();
     $cacheId = Tinebase_Helper::convertCacheId('getCustomFieldsForApplication' . $cfIndex);
     $result = $cache->load($cacheId);
     if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) {
         Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' Before - MEMORY: ' . memory_get_usage(TRUE) / 1024 / 1024 . ' MBytes');
     }
     if (!$result) {
         $filterValues = array(array('field' => 'application_id', 'operator' => 'equals', 'value' => $applicationId));
         if ($_modelName !== NULL) {
             $filterValues[] = array('field' => 'model', 'operator' => 'equals', 'value' => $_modelName);
         }
         $filter = new Tinebase_Model_CustomField_ConfigFilter($filterValues);
         $filter->setRequiredGrants((array) $_requiredGrant);
         $result = $this->_backendConfig->search($filter);
         if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
             Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Got ' . count($result) . ' uncached custom fields for app id ' . $applicationId . ' (cacheid: ' . $cacheId . ')');
         }
         if (Tinebase_Core::isLogLevel(Zend_Log::TRACE) && count($result) > 0) {
             Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . print_r($result->toArray(), TRUE));
         }
         $cache->save($result, $cacheId, array('customfields'));
     }
     $this->_cfByApplicationCache[$cfIndex] = $result;
     if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) {
         Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' After - MEMORY: ' . memory_get_usage(TRUE) / 1024 / 1024 . ' MBytes');
     }
     return $result;
 }
 /**
  * Returns settings for SimpleFAQ app
  * - result is cached
  *
  * @param boolean $_resolve if some values should be resolved (here yet unused)
  * @return  SimpleFAQ_Model_Config
  *
  */
 public function getConfigSettings($_resolve = FALSE)
 {
     $cache = Tinebase_Core::get('cache');
     $cacheId = Tinebase_Helper::convertCacheId('getSimpleFAQSettings');
     $result = $cache->load($cacheId);
     if (!$result) {
         $translate = Tinebase_Translation::getTranslation('SimpleFAQ');
         $result = new SimpleFAQ_Model_Config(array('defaults' => parent::getConfigSettings()));
         $others = array(SimpleFAQ_Model_Config::FAQSTATUSES => array(array('id' => 1, 'faqstatus' => $translate->_('Draft')), array('id' => 2, 'faqstatus' => $translate->_('released')), array('id' => 3, 'faqstatus' => $translate->_('obsolete'))), SimpleFAQ_Model_Config::FAQTYPES => array(array('id' => 1, 'faqtype' => $translate->_('Internal')), array('id' => 2, 'faqtype' => $translate->_('Public'))));
         foreach ($others as $setting => $defaults) {
             $result->{$setting} = SimpleFAQ_Config::getInstance()->get($setting, new Tinebase_Config_Struct($defaults))->toArray();
         }
         // save result and tag it with 'settings'
         $cache->save($result, $cacheId, array('settings'));
     }
     return $result;
 }
 /**
  * invalidate cache by type/id
  * 
  * @param array $cacheIds
  */
 protected function _clearCache($cacheIds = array())
 {
     $cache = Tinebase_Core::getCache();
     foreach ($cacheIds as $type => $id) {
         $cacheId = Tinebase_Helper::convertCacheId($type . $id);
         $cache->remove($cacheId);
     }
     $this->resetClassCache();
 }
 /**
  * get JSON from cache or new instance
  * 
  * @param array $classes for Zend_Cache_Frontend_File
  * @return Zend_Json_Server
  */
 protected static function _getServer($classes = null)
 {
     // setup cache if available
     if (is_array($classes) && Tinebase_Core::getCache()) {
         $masterFiles = array();
         $dirname = dirname(__FILE__) . '/../../';
         foreach ($classes as $class => $namespace) {
             $masterFiles[] = $dirname . str_replace('_', '/', $class) . '.php';
         }
         try {
             $cache = new Zend_Cache_Frontend_File(array('master_files' => $masterFiles, 'lifetime' => null, 'automatic_serialization' => true, 'automatic_cleaning_factor' => 0, 'write_control' => false, 'logging' => Tinebase_Core::isLogLevel(Zend_Log::DEBUG), 'logger' => Tinebase_Core::getLogger()));
             $cache->setBackend(Tinebase_Core::getCache()->getBackend());
             $cacheId = Tinebase_Helper::convertCacheId('_handle_' . sha1(Zend_Json_Encoder::encode($classes)) . '_' . (self::userIsRegistered() ? Tinebase_Core::getUser()->getId() : 'anon'));
             $server = $cache->load($cacheId);
             if ($server instanceof Zend_Json_Server) {
                 return $server;
             }
         } catch (Zend_Cache_Exception $zce) {
             if (Tinebase_Core::isLogLevel(Zend_Log::NOTICE)) {
                 Tinebase_Core::getLogger()->notice(__METHOD__ . '::' . __LINE__ . " Failed to create cache. Exception: \n" . $zce);
             }
         }
     }
     $server = new Zend_Json_Server();
     $server->setAutoEmitResponse(false);
     $server->setAutoHandleExceptions(false);
     if (is_array($classes)) {
         foreach ($classes as $class => $namespace) {
             try {
                 $server->setClass($class, $namespace);
             } catch (Exception $e) {
                 if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) {
                     Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . " Failed to add JSON API for '{$class}' => '{$namespace}' Exception: \n" . $e);
                 }
             }
         }
     }
     if (self::userIsRegistered()) {
         $definitions = self::_getModelConfigMethods();
         $server->loadFunctions($definitions);
     }
     if (isset($cache)) {
         $cache->save($server, $cacheId, array(), null);
     }
     return $server;
 }
 /**
  * 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();
 }
 /**
  * get Tine 2.0 group for given principal (by display name)
  * - result is cached for 1 week
  * 
  * @param string $principal
  * @return null|Tinebase_Model_Group
  */
 protected function _getGroupForPrincipal($principal)
 {
     $cacheId = Tinebase_Helper::convertCacheId('_getGroupForPrincipal' . $principal);
     if (Tinebase_Core::getCache()->test($cacheId)) {
         $group = Tinebase_Core::getCache()->load($cacheId);
         if (Tinebase_Core::isLogLevel(Zend_Log::INFO)) {
             Tinebase_Core::getLogger()->info(__METHOD__ . ' ' . __LINE__ . ' Loading principal group from cache: ' . $group->name);
         }
         return $group;
     }
     $group = null;
     $result = $this->calDavRequest('PROPFIND', $principal, self::resolvePrincipalRequest);
     if (count($result['{DAV:}group-member-set']->getPrincipals()) > 0 && isset($result['{DAV:}displayname'])) {
         $groupDescription = $result['{DAV:}displayname'];
         try {
             $group = Tinebase_Group::getInstance()->getGroupByPropertyFromSqlBackend('description', $groupDescription);
             if (Tinebase_Core::isLogLevel(Zend_Log::INFO)) {
                 Tinebase_Core::getLogger()->info(__METHOD__ . ' ' . __LINE__ . ' Found matching group ' . $group->name . ' (' . $group->description . ') for principal ' . $principal);
             }
             Tinebase_Core::getCache()->save($group, $cacheId, array(), 24 * 3600 * 7);
         } catch (Tinebase_Exception_Record_NotDefined $ternd) {
             if (Tinebase_Core::isLogLevel(Zend_Log::NOTICE)) {
                 Tinebase_Core::getLogger()->notice(__METHOD__ . ' ' . __LINE__ . ' Group not found: ' . $groupDescription . ' ' . print_r($result, true));
             }
         }
     }
     return $group;
 }