/** * test uninstall application and cache clearing * */ public function testUninstallApplications() { $cache = Tinebase_Core::getCache(); $cacheId = 'unittestcache'; $cache->save('something', $cacheId); try { $result = $this->_uit->uninstallApplications(array('ActiveSync')); } catch (Tinebase_Exception_NotFound $e) { $this->_uit->installApplications(array('ActiveSync')); $result = $this->_uit->uninstallApplications(array('ActiveSync')); } $this->assertFalse($cache->test($cacheId), 'cache is not cleared'); $apps = $this->_uit->searchApplications(); // get active sync foreach ($apps['results'] as $app) { if ($app['name'] == 'ActiveSync') { $activeSyncApp = $app; break; } } // checks $this->assertTrue(isset($activeSyncApp)); $this->assertEquals('uninstalled', $activeSyncApp['install_status']); // cleanup $this->_uit->installApplications(array('ActiveSync')); }
/** * calls Timetracker_Controller_Timesheet::findTimesheetsByTimeaccountAndPeriod arguments suitable for async job * returns true if cache could be saved. * * @param array $args * @return boolean */ public function findTimesheetsForReport(array $args) { $cache = Tinebase_Core::getCache(); $results = Timetracker_Controller_Timesheet::getInstance()->findTimesheetsByTimeaccountAndPeriod($args['timeaccountId'], $args['startDate'], $args['endDate'], $args['destination'], $args['taCostCenter']); $m = str_replace('-', '', $args['month']); return $cache->save(array('results' => $results), $args['cacheId'], array($args['cacheId'] . '_' . $m)); }
/** * 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; }
/** * Sets up the fixture. * This method is called before a test is executed. * * @access protected */ protected function setUp() { parent::setUp(); // create shared folder and other users folder $this->sharedContainer = Tinebase_Container::getInstance()->addContainer(new Tinebase_Model_Container(array('name' => __CLASS__ . Tinebase_Record_Abstract::generateUID(), 'type' => Tinebase_Model_Container::TYPE_SHARED, 'application_id' => Tinebase_Application::getInstance()->getApplicationByName('Calendar')->getId(), 'backend' => 'Sql'))); $sclever = Tinebase_Helper::array_value('sclever', Zend_Registry::get('personas')); $this->otherUsersContainer = Tinebase_Container::getInstance()->addContainer(new Tinebase_Model_Container(array('name' => __CLASS__ . Tinebase_Record_Abstract::generateUID(), 'type' => Tinebase_Model_Container::TYPE_PERSONAL, 'owner_id' => $sclever->getId(), 'application_id' => Tinebase_Application::getInstance()->getApplicationByName('Calendar')->getId(), 'backend' => 'Sql'))); Tinebase_Container::getInstance()->addGrants($this->otherUsersContainer, Tinebase_Acl_Rights::ACCOUNT_TYPE_USER, Tinebase_Core::getUser(), array(Tinebase_Model_Grants::GRANT_READ, Tinebase_Model_Grants::GRANT_SYNC), true); // clear container caches (brute force) Tinebase_Core::getCache()->clean(Zend_Cache::CLEANING_MODE_ALL); $this->server = new Sabre\DAV\Server(new Tinebase_WebDav_Root()); $this->server->debugExceptions = true; $this->server->addPlugin(new \Sabre\CalDAV\Plugin()); $this->server->addPlugin(new \Sabre\CalDAV\SharingPlugin()); $aclPlugin = new \Sabre\DAVACL\Plugin(); $aclPlugin->defaultUsernamePath = Tinebase_WebDav_PrincipalBackend::PREFIX_USERS; $aclPlugin->principalCollectionSet = array(Tinebase_WebDav_PrincipalBackend::PREFIX_USERS, Tinebase_WebDav_PrincipalBackend::PREFIX_GROUPS); $this->server->addPlugin($aclPlugin); $this->response = new Sabre\HTTP\ResponseMock(); $this->server->httpResponse = $this->response; }
/** * update installed application * * @param Tinebase_Model_Application $_application * @param string $_majorVersion * @return array messages * @throws Setup_Exception if current app version is too high */ public function updateApplication(Tinebase_Model_Application $_application, $_majorVersion) { $setupXml = $this->getSetupXml($_application->name); $messages = array(); switch (version_compare($_application->version, $setupXml->version)) { case -1: $message = "Executing updates for " . $_application->name . " (starting at " . $_application->version . ")"; $messages[] = $message; Setup_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . ' ' . $message); $version = $_application->getMajorAndMinorVersion(); $minor = $version['minor']; $className = ucfirst($_application->name) . '_Setup_Update_Release' . $_majorVersion; if (!class_exists($className)) { $nextMajorRelease = $_majorVersion + 1 . ".0"; Setup_Core::getLogger()->notice(__METHOD__ . '::' . __LINE__ . " Update class {$className} does not exists, skipping release {$_majorVersion} for app " . "{$_application->name} and increasing version to {$nextMajorRelease}"); $_application->version = $nextMajorRelease; Tinebase_Application::getInstance()->updateApplication($_application); } else { $update = new $className($this->_backend); $classMethods = get_class_methods($update); // we must do at least one update do { $functionName = 'update_' . $minor; try { $db = Setup_Core::getDb(); $transactionId = Tinebase_TransactionManager::getInstance()->startTransaction($db); Setup_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . ' Updating ' . $_application->name . ' - ' . $functionName); $update->{$functionName}(); Tinebase_TransactionManager::getInstance()->commitTransaction($transactionId); } catch (Exception $e) { Tinebase_TransactionManager::getInstance()->rollBack(); Setup_Core::getLogger()->err(__METHOD__ . '::' . __LINE__ . ' ' . $e->getMessage()); Setup_Core::getLogger()->err(__METHOD__ . '::' . __LINE__ . ' ' . $e->getTraceAsString()); throw $e; } $minor++; } while (array_search('update_' . $minor, $classMethods) !== false); } $messages[] = "<strong> Updated " . $_application->name . " successfully to " . $_majorVersion . '.' . $minor . "</strong>"; // update app version $updatedApp = Tinebase_Application::getInstance()->getApplicationById($_application->getId()); $_application->version = $updatedApp->version; Setup_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . ' Updated ' . $_application->name . " successfully to " . $_application->version); $this->_updatedApplications++; break; case 0: Setup_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' No update needed for ' . $_application->name); break; case 1: throw new Setup_Exception('Current application version is higher than version from setup.xml: ' . $_application->version . ' > ' . $setupXml->version); break; } Setup_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . ' Clearing cache after update ...'); $this->_enableCaching(); Tinebase_Core::getCache()->clean(Zend_Cache::CLEANING_MODE_ALL); return $messages; }
/** * inspect update of normal user account * * @param Tinebase_Record_Interface $_record the update record * @param Tinebase_Record_Interface $_oldRecord the current persistent record * @return void */ protected function _beforeUpdateStandardAccount($_record, $_oldRecord) { $this->_beforeUpdateStandardAccountCredentials($_record, $_oldRecord); $diff = $_record->diff($_oldRecord); // delete message body cache because display format has changed if (array_key_exists('display_format', $diff)) { Tinebase_Core::getCache()->clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG, array('getMessageBody')); } // reset capabilities if imap host / port changed if (isset($_SESSION[$this->_applicationName]) && (array_key_exists('host', $diff) || array_key_exists('port', $diff))) { if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Resetting capabilities for account ' . $_record->name); } unset($_SESSION[$this->_applicationName][$_record->getId()]); } }
/** * 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(); }
/** * save message in tinebase cache * - only cache message headers if received during the last day * * @param Felamimail_Model_Message $_message * @param Felamimail_Model_Folder $_folder * @param array $_messageData * * @todo do we need the headers in the Tinebase cache? */ protected function _saveMessageInTinebaseCache(Felamimail_Model_Message $_message, Felamimail_Model_Folder $_folder, $_messageData) { if (!$_message->received->isLater(Tinebase_DateTime::now()->subDay(3))) { return; } $memory = function_exists('memory_get_peak_usage') ? memory_get_peak_usage(true) : memory_get_usage(true); if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' caching message ' . $_message->getId() . ' / memory usage: ' . $memory / 1024 / 1024 . ' MBytes'); } if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) { Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' ' . print_r($_message->toArray(), TRUE)); } $cacheId = 'getMessageHeaders' . $_message->getId(); Tinebase_Core::getCache()->save($_messageData['header'], $cacheId, array('getMessageHeaders')); // prefetch body to cache if (Felamimail_Config::getInstance()->get(Felamimail_Config::CACHE_EMAIL_BODY, TRUE) && $_message->size < $this->_maxMessageSizeToCacheBody) { $account = Felamimail_Controller_Account::getInstance()->get($_folder->account_id); $mimeType = $account->display_format == Felamimail_Model_Account::DISPLAY_HTML || $account->display_format == Felamimail_Model_Account::DISPLAY_CONTENT_TYPE ? Zend_Mime::TYPE_HTML : Zend_Mime::TYPE_TEXT; Felamimail_Controller_Message::getInstance()->getMessageBody($_message, null, $mimeType, $account); } }
/** * 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(); }
/** * remove one groupmember from the group * * @param mixed $_groupId * @param mixed $_accountId */ public function removeGroupMemberFromSqlBackend($_groupId, $_accountId) { $groupId = Tinebase_Model_Group::convertGroupIdToInt($_groupId); $accountId = Tinebase_Model_User::convertUserIdToInt($_accountId); $where = array($this->_db->quoteInto($this->_db->quoteIdentifier('group_id') . '= ?', $groupId), $this->_db->quoteInto($this->_db->quoteIdentifier('account_id') . '= ?', $accountId)); $this->groupMembersTable->delete($where); // invalidate cache $cacheId = convertCacheId('groupMembers' . $groupId); Tinebase_Core::getCache()->remove($cacheId); $cacheId = convertCacheId('groupMemberships' . $accountId); Tinebase_Core::getCache()->remove($cacheId); }
/** * Search server plugins from applications configuration * */ protected static function _searchServerPlugins() { $cache = Tinebase_Core::getCache(); if ($cache && ($plugins = $cache->load(self::TINEBASE_SERVER_PLUGINS))) { return $plugins; } // get list of available applications $applications = array(); $d = dir(realpath(__DIR__ . '/../')); while (false !== ($entry = $d->read())) { if ($entry[0] == '.') { continue; } if (ctype_upper($entry[0]) && is_dir($d->path . DIRECTORY_SEPARATOR . $entry)) { $applications[] = $entry; } } $d->close(); // get list of plugins $plugins = array(); foreach ($applications as $application) { $config = $application . '_Config'; try { if (class_exists($config)) { $reflectedClass = new ReflectionClass($config); if ($reflectedClass->isSubclassOf('Tinebase_Config_Abstract')) { $plugins = array_merge($plugins, call_user_func(array($config, 'getServerPlugins'))); } } } catch (Exception $e) { Tinebase_Exception::log($e); } } // sort plugins by priority asort($plugins); $plugins = array_keys($plugins); if ($cache) { $cache->save($plugins, self::TINEBASE_SERVER_PLUGINS); } return $plugins; }
/** * remove obsolete/outdated stuff from cache * notes: CLEANING_MODE_OLD -> removes obsolete cache entries (files for file cache) * CLEANING_MODE_ALL -> removes complete cache structure (directories for file cache) + cache entries * * @param string $_mode */ public function cleanupCache($_mode = Zend_Cache::CLEANING_MODE_OLD) { if (Tinebase_Core::isLogLevel(Zend_Log::INFO)) { Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . ' Cleaning up the cache (mode: ' . $_mode . ')'); } Tinebase_Core::getCache()->clean($_mode); }
/** * delete all messages in one folder -> be careful, they are completly removed and not moved to trash * -> delete subfolders if param set * * @param string $_folderId * @param boolean $_deleteSubfolders * @return Expressomail_Model_Folder * @throws Expressomail_Exception_IMAPServiceUnavailable */ public function emptyFolder($_folderId, $_deleteSubfolders = FALSE) { $folder = $this->_backend->get($_folderId); $account = Expressomail_Controller_Account::getInstance()->get($folder->account_id); if ($folder) { $cache = Tinebase_Core::getCache(); $cacheKey = 'Expressomail_Model_Folder_' . $folder->id; $cache->remove($cacheKey); } $imap = Expressomail_Backend_ImapFactory::factory($account); try { // try to delete messages in imap folder Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . ' Delete all messages in folder ' . $folder->globalname); $imap->emptyFolder(Expressomail_Model_Folder::encodeFolderName($folder->globalname)); } catch (Zend_Mail_Protocol_Exception $zmpe) { Tinebase_Core::getLogger()->warn(__METHOD__ . '::' . __LINE__ . ' ' . $zmpe->getMessage()); throw new Expressomail_Exception_IMAPServiceUnavailable($zmpe->getMessage()); } catch (Zend_Mail_Storage_Exception $zmse) { Tinebase_Core::getLogger()->warn(__METHOD__ . '::' . __LINE__ . ' Folder could be empty (' . $zmse->getMessage() . ')'); } if ($_deleteSubfolders) { $this->deleteSubfolders($folder); } return $folder; }
/** * reset cache entries * * @param string $class * @param string $method * @param string $cacheId * @return Tinebase_Cache_PerRequest */ public function reset($class = null, $method = null, $cacheId = null) { $persistentCache = Tinebase_Core::getCache(); $cacheId = $cacheId ? sha1($cacheId) : $cacheId; // reset all cache entries if (empty($class)) { if ($persistentCache instanceof Zend_Cache_Core) { foreach ($this->_inMemoryCache as $class => $methods) { foreach ($methods as $method => $cacheEntries) { foreach ($cacheEntries as $cacheId => $cacheEntry) { $this->_purgePersistentCacheEntry($persistentCache, $class, $method, $cacheId); } } } } $this->_inMemoryCache = array(); return $this; } // reset all cache entries of the given class if (empty($method)) { if ($persistentCache instanceof Zend_Cache_Core && isset($this->_inMemoryCache[$class])) { foreach ($this->_inMemoryCache[$class] as $method => $cacheEntries) { foreach ($cacheEntries as $cacheId => $cacheEntry) { $this->_purgePersistentCacheEntry($persistentCache, $class, $method, $cacheId); } } } $this->_inMemoryCache[$class] = array(); return $this; } // reset all cache entries of the method of the given class if (empty($cacheId)) { if ($persistentCache instanceof Zend_Cache_Core && isset($this->_inMemoryCache[$class]) && isset($this->_inMemoryCache[$class][$method])) { foreach ($this->_inMemoryCache[$class][$method] as $cacheId => $cacheEntry) { $this->_purgePersistentCacheEntry($persistentCache, $class, $method, $cacheId); } } $this->_inMemoryCache[$class][$method] = array(); return $this; } // reset single cache entry if (isset($this->_inMemoryCache[$class]) && isset($this->_inMemoryCache[$class][$method]) && isset($this->_inMemoryCache[$class][$method][$cacheId])) { if ($persistentCache instanceof Zend_Cache_Core) { $this->_purgePersistentCacheEntry($persistentCache, $class, $method, $cacheId); } unset($this->_inMemoryCache[$class][$method][$cacheId]); } return $this; }
/** * reinstall applications * and reset Demodata * php setup.php --reset_demodata USERNAME * * @param Zend_Console_Getopt $_opts */ protected function _resetDemodata(Zend_Console_Getopt $_opts) { $controller = Setup_Controller::getInstance(); $userController = Admin_Controller_User::getInstance(); $containerController = Tinebase_Container::getInstance(); $cli = new Tinebase_Frontend_Cli(); //Don't reset this applications $fixedApplications = array('Tinebase', 'Admin', 'Addressbook'); //Log in $opts = $_opts->getRemainingArgs(); $username = $opts[0]; if (empty($username)) { echo "Username is missing!\n"; exit; } $user = Tinebase_User::getInstance()->getUserByLoginName($username); Tinebase_Core::set(Tinebase_Core::USER, $user); //get all applications and remove some $applications = Tinebase_Application::getInstance()->getApplications(NULL, 'id'); foreach ($applications as $key => &$application) { if (in_array($application, $fixedApplications)) { unset($applications[$key]); } } //get set rights $users = Tinebase_Acl_Roles::getInstance()->getRoleByName('user role'); $rights = Tinebase_Acl_Roles::getInstance()->getRoleRights($users->getId()); //Uninstall Applications try { $controller->uninstallApplications($applications->name); echo "Successfully uninstalled " . count($applications) . " applications.\n"; } catch (Tinebase_Exception_NotFound $e) { } //Install Applications try { $controller->installApplications($applications->name); echo "Successfully installed " . count($applications) . " applications.\n"; } catch (Tinebase_Exception_NotFound $e) { } //set rights foreach ($applications as &$application) { $newApplicationId = Tinebase_Application::getInstance()->getApplicationByName($application->name)->getId(); foreach ($rights as &$right) { if ($right['application_id'] == $application->id) { $right['application_id'] = $newApplicationId; } } } Tinebase_Acl_Roles::getInstance()->setRoleRights($users->getId(), $rights); echo "Successfully restored user rights.\n"; //Clean up addressbooks $internalContacts = $userController->getDefaultInternalAddressbook(); $containers = $containerController->getAll(); foreach ($containers as $key => &$container) { if ($container->id == $internalContacts) { // Do nothing } else { try { $containerController->deleteContainer($container, true); } catch (Tinebase_Exception_NotFound $e) { } } } echo "Successfully cleand up containers.\n"; //remove state $db = Tinebase_Core::getDb(); $statement = "TRUNCATE TABLE " . $db->quoteIdentifier(SQL_TABLE_PREFIX . 'state'); $db->query($statement); echo "Successfully truncated state table.\n"; //Get Demodata $cli->createAllDemoData(); //clear Cache Tinebase_Core::getCache()->clean(Zend_Cache::CLEANING_MODE_ALL); echo "Successfully cleared Cache.\n"; echo "Every thing done!\n"; }
/** * clear the cache */ protected function _clearCache() { if (Setup_Core::isLogLevel(Zend_Log::DEBUG)) { Setup_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' clearing cache ... '); } Tinebase_Core::getCache()->clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG, array('config')); }
/** * remove all container related entries from cache * * @param int|Tinebase_Model_Container $containerId */ protected function _clearCache($containerId) { $containerId = Tinebase_Model_Container::convertContainerIdToInt($containerId); $cache = Tinebase_Core::getCache(); if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) { Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' Removing all cache entries for container id ' . $containerId); } $idsToDelete = array('getContainerById' . $containerId . 'd0', 'getContainerById' . $containerId . 'd1'); foreach ($idsToDelete as $id) { $cache->remove($id); } $this->resetClassCache(); }
/** * invalidate cache for this account * * @param Expressomail_Model_Account $_account * @return void */ protected function _invalidateAccountCache(Expressomail_Model_Account $_account) { Tinebase_Core::setupCache(); $cache = Tinebase_Core::getCache(); $cacheId = Tinebase_Core::createCacheId(array(Tinebase_Core::getUser()->accountId, $_account->getId())); $_filter = new Expressomail_Model_AccountFilter(array()); //Cleans cache generate in user login, when the method seach is called with a empty filter. $cacheSearch = Tinebase_Core::createCacheId(array('Expressomail_Controller_Account_search', Tinebase_Core::getUser()->accountId, $_filter->toArray())); $cache->remove($cacheId); $cache->remove($cacheSearch); }
/** * 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"); } } } $cache = Tinebase_Core::getCache(); $cacheId = convertCacheId('getTimeaccountGrants' . Tinebase_Core::getUser()->getId() . $_timeaccount->getId() . $_ignoreACL); $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; }
/** * try to get a message from imap server (with complete body, attachments, etc) * * @see 0006300: add unique message-id header to new messages (for message-id check) */ public function testGetMessage() { $message = $this->_sendMessage(); // get complete message $message = $this->_json->getMessage($message['id']); // check $this->assertTrue(isset($message['headers']) && $message['headers']['message-id']); $this->assertContains('@' . $this->_mailDomain, $message['headers']['message-id']); $this->assertGreaterThan(0, preg_match('/aaaaaä/', $message['body'])); // delete message on imap server and check if correct exception is thrown when trying to get it $this->_imap->selectFolder('INBOX'); $this->_imap->removeMessage($message['messageuid']); Tinebase_Core::getCache()->clean(); $this->setExpectedException('Felamimail_Exception_IMAPMessageNotFound'); $message = $this->_json->getMessage($message['id']); }
/** * 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; }
/** * import users from sync backend * * @param array $options */ public static function syncUsers($options) { if (Tinebase_Core::isLogLevel(Zend_Log::INFO)) { Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . ' Start synchronizing users with options ' . print_r($options, true)); } $users = Tinebase_User::getInstance()->getUsersFromSyncBackend(NULL, NULL, 'ASC', NULL, NULL, 'Tinebase_Model_FullUser'); if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' About to sync ' . count($users) . ' users from sync backend ...'); } foreach ($users as $user) { try { self::syncUser($user, $options); } catch (Tinebase_Exception_NotFound $ten) { Tinebase_Core::getLogger()->crit(__METHOD__ . '::' . __LINE__ . " User {$user->accountLoginName} not synced: " . $ten->getMessage()); } } if (isset($options['deleteUsers']) && $options['deleteUsers']) { self::_syncDeletedUsers($users); } // @todo this should be improved: only the cache of synced users + group memberships should be cleaned if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Finished synchronizing users. Clearing cache after user sync ...'); } Tinebase_Core::getCache()->clean(); }
/** * deletes one config setting * * @deprecated * @param Tinebase_Model_Config $_config record to delete * @return void */ public function deleteConfig(Tinebase_Model_Config $_config) { $this->_getBackend()->delete($_config->getId()); Tinebase_Core::getCache()->clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG, array('config')); }
/** * test french translations singular * * @see 0007014: Dates not formatted */ public function testFrench() { Tinebase_Core::getCache()->clean(); $jsTranslations = Tinebase_Translation::getJsTranslations('fr', 'Tinebase'); $this->assertTrue(preg_match("/: \"liste \\\\\"\n/", $jsTranslations, $matches) === 0, 'Translation string missing / preg_match fail: ' . print_r($matches, TRUE)); $this->assertContains(': "liste \\"à faire\\""', $jsTranslations, 'Could not find french singular of "todo lists"'); }
/** * get message body * * @param string|Felamimail_Model_Message $_messageId * @param string $_partId * @param string $_contentType * @param Felamimail_Model_Account $_account * @return string */ public function getMessageBody($_messageId, $_partId, $_contentType, $_account = NULL) { $message = $_messageId instanceof Felamimail_Model_Message ? $_messageId : $this->get($_messageId); if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Get Message body (part: ' . $_partId . ') of message id ' . $message->getId() . ' (content type ' . $_contentType . ')'); } $cacheBody = Felamimail_Config::getInstance()->get(Felamimail_Config::CACHE_EMAIL_BODY, TRUE); if ($cacheBody) { $cache = Tinebase_Core::getCache(); $cacheId = $this->_getMessageBodyCacheId($message, $_partId, $_contentType, $_account); if ($cache->test($cacheId)) { if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Getting Message from cache.'); } return $cache->load($cacheId); } } $messageBody = $this->_getAndDecodeMessageBody($message, $_partId, $_contentType, $_account); // activate garbage collection (@see 0008216: HTMLPurifier/TokenFactory.php : Allowed memory size exhausted) $cycles = gc_collect_cycles(); if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) { Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' Current mem usage after gc_collect_cycles(' . $cycles . ' ): ' . memory_get_usage() / 1024 / 1024); } if ($cacheBody) { if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Put message body into Tinebase cache (for 24 hours).'); } $cache->save($messageBody, $cacheId, array('getMessageBody'), 86400); } return $messageBody; }
public function testAccountAnyoneDisabled() { $container = new Tinebase_Model_Container(array('name' => 'tine20shared', 'type' => Tinebase_Model_Container::TYPE_SHARED, 'owner_id' => Tinebase_Core::getUser(), 'backend' => 'Sql', 'application_id' => Tinebase_Application::getInstance()->getApplicationByName('Addressbook')->getId())); $grants = new Tinebase_Record_RecordSet('Tinebase_Model_Grants', array(array('account_id' => '0', 'account_type' => Tinebase_Acl_Rights::ACCOUNT_TYPE_ANYONE, Tinebase_Model_Grants::GRANT_READ => true, Tinebase_Model_Grants::GRANT_EXPORT => true, Tinebase_Model_Grants::GRANT_SYNC => true)), TRUE); $sharedContainer = $this->_instance->addContainer($container, $grants); $readGrant = $this->_instance->hasGrant(Tinebase_Core::getUser(), $sharedContainer, Tinebase_Model_Grants::GRANT_READ); $this->assertTrue($readGrant); Tinebase_Config::getInstance()->set(Tinebase_Config::ANYONE_ACCOUNT_DISABLED, TRUE); Tinebase_Core::getCache()->clean(); $readGrant = $this->_instance->resetClassCache('hasGrant')->hasGrant(Tinebase_Core::getUser(), $sharedContainer, Tinebase_Model_Grants::GRANT_READ); $this->assertFalse($readGrant); }
/** * Deletes a set of records. * * If one of the records could not be deleted, no record is deleted * * @param array $_ids array of record identifiers * @return Tinebase_Record_RecordSet * @throws Tinebase_Exception_NotFound|Tinebase_Exception */ public function delete($_ids) { if ($_ids instanceof $this->_modelName) { $_ids = (array) $_ids->getId(); } $ids = $this->_inspectDelete((array) $_ids); $records = $this->_backend->getMultiple((array) $ids); if (count((array) $ids) != count($records)) { Tinebase_Core::getLogger()->notice(__METHOD__ . '::' . __LINE__ . ' Only ' . count($records) . ' of ' . count((array) $ids) . ' records exist.'); } if (empty($records)) { return $records; } if (Tinebase_Core::isLogLevel(Zend_Log::INFO)) { Tinebase_Core::getLogger()->info(__METHOD__ . '::' . __LINE__ . ' Deleting ' . count($records) . ' of ' . $this->_modelName . ' records ...'); } try { $db = $this->_backend->getAdapter(); $transactionId = Tinebase_TransactionManager::getInstance()->startTransaction($db); $this->_checkRight('delete'); foreach ($records as $record) { if ($this->sendNotifications()) { $this->_getRelatedData($record); } $this->_deleteRecord($record); } Tinebase_TransactionManager::getInstance()->commitTransaction($transactionId); // send notifications if ($this->sendNotifications()) { foreach ($records as $record) { $this->doSendNotifications($record, Tinebase_Core::getUser(), 'deleted'); } } } catch (Exception $e) { Tinebase_TransactionManager::getInstance()->rollBack(); Tinebase_Core::getLogger()->err(__METHOD__ . '::' . __LINE__ . ' ' . print_r($e->getMessage(), true)); throw $e; } if ($this->_clearCustomFieldsCache) { Tinebase_Core::getCache()->clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG, array('customfields')); } // returns deleted records return $records; }
/** * set structure and save into cache * * @param array $structure */ protected function _setStructure($structure) { if (!empty($structure['partId'])) { if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) { Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' Don\'t cache structure of subparts'); } return; } $cacheId = $this->_getStructureCacheId(); if (Tinebase_Core::isLogLevel(Zend_Log::TRACE)) { Tinebase_Core::getLogger()->trace(__METHOD__ . '::' . __LINE__ . ' Caching message structure: ' . $cacheId); } Tinebase_Core::getCache()->save($structure, $cacheId, array('messageStructure'), 86400); // 24 hours $this->structure = $structure; }
/** * Gets one entry (by id) * * @param string $_id * @param boolean $_useCache true to get folder from cache * @return Tinebase_Record_Interface * @throws Tinebase_Exception_NotFound * * @todo test to do a getQuota() shoudn't be hardcoded * */ public function get($_id, $_useCache = TRUE) { $cache = Tinebase_Core::getCache(); $cacheKey = 'Expressomail_Model_Folder_' . $_id; $folderFromCache = $_useCache ? $cache->load($cacheKey) : FALSE; if ($folderFromCache) { return $folderFromCache; } $folderDecoded = self::decodeFolderUid($_id); if (isset($folderDecoded['accountId'])) { $imap = Expressomail_Backend_ImapFactory::factory($folderDecoded['accountId'], TRUE); $folder = $imap->getFolders('', $folderDecoded['globalName'], $this->_accounts[$folderDecoded['accountId']]); //$status = $imap->examineFolder($folderDecoded['globalName']); $status = $imap->getFolderStatus($folderDecoded['globalName']); if ($status === FALSE) { // we can not access folder, create Model as unselectable $globalname = $folderDecoded['globalName']; $auxlocalname = explode(self::IMAPDELIMITER, $globalname); $localname = array_pop($auxlocalname); $translate = Tinebase_Translation::getTranslation("Expressomail"); $newFolder = new Expressomail_Model_Folder(array('id' => $_id, 'account_id' => Tinebase_Core::getPreference('Expressomail')->{Expressomail_Preference::DEFAULTACCOUNT}, 'localname' => $localname == 'user' ? $translate->_("Shared Folders") : $localname, 'globalname' => $folderDecoded['globalName'], 'parent' => $globalname === 'user' ? '' : substr($globalname, 0, strrpos($globalname, self::IMAPDELIMITER)), 'delimiter' => self::IMAPDELIMITER, 'is_selectable' => 0, 'has_children' => 1, 'system_folder' => 1, 'imap_status' => Expressomail_Model_Folder::IMAP_STATUS_OK, 'imap_timestamp' => Tinebase_DateTime::now(), 'cache_status' => 'complete', 'cache_timestamp' => Tinebase_DateTime::now(), 'cache_job_lowestuid' => 0, 'cache_job_startuid' => 0, 'cache_job_actions_est' => 0, 'cache_job_actions_done' => 0), true); $cache->save($newFolder, $cacheKey); return $newFolder; } $globalName = $folderDecoded['globalName']; if ($globalName == 'INBOX' || $globalName == 'user') { $folder[$folderDecoded['globalName']]['parent'] = ''; } else { $folder[$folderDecoded['globalName']]['parent'] = substr($globalName, 0, strrpos($globalName, self::IMAPDELIMITER)); } /* * @todo must see if it is not better do this on the model directly */ $systemFolders = FALSE; if (strtolower($globalName) === 'inbox' || strtolower($folder[$folderDecoded['globalName']]['parent']) === 'user') { $systemFolders = TRUE; } else { if (strtolower($folder[$folderDecoded['globalName']]['parent']) === 'inbox' && strtolower($folder[$folderDecoded['globalName']]['localName']) !== 'inbox') { $systemFolders = in_array(strtolower($folder[$folderDecoded['globalName']]['localName']), Expressomail_Controller_Folder::getInstance()->getSystemFolders($folderDecoded['accountId'])); } else { if (preg_match('/^user\\/[^\\/]+$/i', $folder[$folderDecoded['globalName']]['parent'])) { $systemFolders = in_array(strtolower($folder[$folderDecoded['globalName']]['localName']), Expressomail_Controller_Folder::getInstance()->getSystemFolders($folderDecoded['accountId'])); } } } $localName = Expressomail_Model_Folder::decodeFolderName($folder[$folderDecoded['globalName']]['localName']); if (preg_match("/^user\\/[0-9]{11}\$/", Expressomail_Model_Folder::decodeFolderName($folder[$folderDecoded['globalName']]['globalName']))) { try { $aux = Tinebase_User::getInstance()->getFullUserByLoginName($localName)->toArray(); $localName = $aux["accountFullName"]; } catch (Exception $exc) { } } $expressomailSession = Expressomail_Session::getSessionNamespace(); $userNameSpace = $imap->getUserNameSpace() . self::IMAPDELIMITER; $arrDecodedFolder = explode(self::IMAPDELIMITER, $folderDecoded['globalName']); if ($folderDecoded['globalName'] === 'INBOX' || $folderDecoded['globalName'] === 'INBOX' . self::IMAPDELIMITER . 'Arquivo Remoto' || substr($folderDecoded['globalName'], 0, strlen($userNameSpace)) === $userNameSpace && (!isset($arrDecodedFolder[2]) || $arrDecodedFolder[2] === 'Arquivo Remoto')) { if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Getting quota from IMAP for ' . $folderDecoded['globalName']); } $quota = $imap->getQuota($folderDecoded['globalName']); $expressomailSession->quota[$folderDecoded['globalName']] = $quota; } else { if ($arrDecodedFolder[0] === 'INBOX' && isset($arrDecodedFolder[1]) && $arrDecodedFolder[1] === 'Arquivo Remoto') { $globalNameFolder = $arrDecodedFolder[0] . self::IMAPDELIMITER . $arrDecodedFolder[1]; } else { $globalNameFolder = $arrDecodedFolder[0]; } if ($arrDecodedFolder[0] !== 'INBOX') { $globalNameFolder .= isset($arrDecodedFolder[1]) ? self::IMAPDELIMITER . $arrDecodedFolder[1] : ''; } if (Tinebase_Core::isLogLevel(Zend_Log::DEBUG)) { Tinebase_Core::getLogger()->debug(__METHOD__ . '::' . __LINE__ . ' Getting quota from Session for ' . $folderDecoded['globalName']); } $quota = isset($expressomailSession->quota[$globalNameFolder]) ? $expressomailSession->quota[$globalNameFolder] : 0; } $return = new Expressomail_Model_Folder(array('id' => $_id, 'account_id' => $folderDecoded['accountId'], 'localname' => $localName, 'globalname' => Expressomail_Model_Folder::decodeFolderName($folder[$folderDecoded['globalName']]['globalName']), 'parent' => Expressomail_Model_Folder::decodeFolderName($folder[$folderDecoded['globalName']]['parent']), 'delimiter' => $folder[$folderDecoded['globalName']]['delimiter'], 'is_selectable' => $folder[$folderDecoded['globalName']]['isSelectable'], 'has_children' => $folder[$folderDecoded['globalName']]['hasChildren'], 'system_folder' => $systemFolders, 'imap_status' => Expressomail_Model_Folder::IMAP_STATUS_OK, 'imap_uidvalidity' => $status['uidvalidity'], 'imap_totalcount' => array_key_exists('messages', $status) ? $status['messages'] : '', 'imap_timestamp' => Tinebase_DateTime::now(), 'cache_status' => 'complete', 'cache_totalcount' => array_key_exists('messages', $status) ? $status['messages'] : '', 'cache_recentcount' => array_key_exists('recent', $status) ? $status['recent'] : '', 'cache_unreadcount' => array_key_exists('unseen', $status) ? $status['unseen'] : '', 'cache_timestamp' => Tinebase_DateTime::now(), 'cache_job_lowestuid' => 0, 'cache_job_startuid' => 0, 'cache_job_actions_est' => 0, 'cache_job_actions_done' => 0, 'quota_usage' => !empty($quota) ? $quota['STORAGE']['usage'] : 0, 'quota_limit' => !empty($quota) ? $quota['STORAGE']['limit'] : 0), true); $cache->save($return, $cacheKey); return $return; } }