/** * Runs update index for all tenants * - but does not run processPreparationQueue or processUpdateIndexQueue * * @param $objectListClass * @param string $condition * @param bool $updateIndexStructures * @param string $loggername */ public static function updateIndex($objectListClass, $condition = "", $updateIndexStructures = false, $loggername = "indexupdater") { $updater = OnlineShop_Framework_Factory::getInstance()->getIndexService(); if ($updateIndexStructures) { \Pimcore\Model\Cache::clearTag("ecommerceconfig"); $updater->createOrUpdateIndexStructures(); } $page = 0; $pageSize = 100; $count = $pageSize; while ($count > 0) { self::log($loggername, "========================="); self::log($loggername, "Update Index Page: " . $page); self::log($loggername, "========================="); $products = new $objectListClass(); $products->setUnpublished(true); $products->setOffset($page * $pageSize); $products->setLimit($pageSize); $products->setObjectTypes(array("object", "folder", "variant")); $products->setIgnoreLocalizedFields(true); $products->setCondition($condition); foreach ($products as $p) { self::log($loggername, "Updating product " . $p->getId()); $updater->updateIndex($p); } $page++; $count = count($products->getObjects()); Pimcore::collectGarbage(); } }
public function __construct($config) { if (!(string) $config->disableDefaultTenant) { $this->defaultWorker = new OnlineShop_Framework_IndexService_Tenant_Worker_DefaultMysql(new OnlineShop_Framework_IndexService_Tenant_Config_DefaultMysql("default", $config)); } $this->tenantWorkers = array(); if ($config->tenants && $config->tenants instanceof Zend_Config) { foreach ($config->tenants as $name => $tenant) { $tenantConfigClass = (string) $tenant->class; $tenantConfig = $tenant; if ($tenant->file) { if (!($tenantConfig = \Pimcore\Model\Cache::load("onlineshop_config_assortment_tenant_" . $tenantConfigClass))) { $tenantConfig = new Zend_Config_Xml(PIMCORE_DOCUMENT_ROOT . (string) $tenant->file, null, true); $tenantConfig = $tenantConfig->tenant; \Pimcore\Model\Cache::save($tenantConfig, "onlineshop_config_assortment_tenant_" . $tenantConfigClass, array("ecommerceconfig"), 9999); } } /** * @var $tenantConfig OnlineShop_Framework_IndexService_Tenant_IConfig */ $tenantConfig = new $tenantConfigClass($name, $tenantConfig, $config); $worker = $tenantConfig->getTenantWorker(); $this->tenantWorkers[$name] = $worker; } } }
public function jobProceduralAction() { $status = array("success" => true); if ($this->getParam("type") == "files") { Update::installData($this->getParam("revision")); } else { if ($this->getParam("type") == "clearcache") { \Pimcore\Model\Cache::clearAll(); } else { if ($this->getParam("type") == "preupdate") { $status = Update::executeScript($this->getParam("revision"), "preupdate"); } else { if ($this->getParam("type") == "postupdate") { $status = Update::executeScript($this->getParam("revision"), "postupdate"); } else { if ($this->getParam("type") == "cleanup") { Update::cleanup(); } else { if ($this->getParam("type") == "languages") { Update::downloadLanguage(); } } } } } } $this->_helper->json($status); }
public function jobProceduralAction() { $status = array("success" => true); if ($this->getParam("type") == "files") { Update::installData($this->getParam("revision")); } else { if ($this->getParam("type") == "clearcache") { \Pimcore\Model\Cache::clearAll(); } else { if ($this->getParam("type") == "preupdate") { $status = Update::executeScript($this->getParam("revision"), "preupdate"); } else { if ($this->getParam("type") == "postupdate") { $status = Update::executeScript($this->getParam("revision"), "postupdate"); } else { if ($this->getParam("type") == "cleanup") { Update::cleanup(); } } } } } // we use pure PHP here, otherwise this can cause issues with dependencies that changed during the update header("Content-type: application/json"); echo json_encode($status); exit; }
/** * */ public function dispatchLoopShutdown() { $code = (string) $this->getResponse()->getHttpResponseCode(); if ($code && ($code[0] == "4" || $code[0] == "5")) { $this->writeLog(); // put the response into the cache, this is read in Pimcore_Controller_Action_Frontend::checkForErrors() $responseData = $this->getResponse()->getBody(); if (strlen($responseData) > 20) { $cacheKey = "error_page_response_" . \Pimcore\Tool\Frontend::getSiteKey(); \Pimcore\Model\Cache::save($responseData, $cacheKey, array("output"), 900, 9992); } } }
/** * gets mockup from cache and if not in cache, adds it to cache * * @param $objectId * @return OnlineShop_Framework_ProductList_DefaultMockup */ public function getMockupFromCache($objectId) { $key = $this->createMockupCacheKey($objectId); $cachedItem = \Pimcore\Model\Cache::load($key); if ($cachedItem) { $mockup = unserialize($cachedItem); if ($mockup instanceof OnlineShop_Framework_ProductList_DefaultMockup) { return $mockup; } } Logger::info("Element with ID {$objectId} was not found in cache, trying to put it there."); return $this->saveToMockupCache($objectId); }
/** * @param $domain */ public function __construct($domain) { $this->_domain = $domain; try { $robotsUrl = $domain . '/robots.txt'; $cacheKey = "robots_" . crc32($robotsUrl); if (!($robotsTxt = Cache::load($cacheKey))) { $robotsTxt = \Pimcore\Tool::getHttpData($robotsUrl); Cache::save($robotsTxt, $cacheKey, array("system"), 3600, 999, true); } $this->_rules = $this->_makeRules($robotsTxt); } catch (\Exception $e) { } }
/** * */ public function load() { $client = Api::getSimpleClient(); $config = $this->getConfig(); $perPage = $this->getPerPage(); $offset = $this->getOffset(); $query = $this->getQuery(); if ($client) { $search = new \Google_Service_Customsearch($client); // determine language $language = ""; if (\Zend_Registry::isRegistered("Zend_Locale")) { $locale = \Zend_Registry::get("Zend_Locale"); $language = $locale->getLanguage(); } if (!array_key_exists("hl", $config) && !empty($language)) { $config["hl"] = $language; } if (!array_key_exists("lr", $config) && !empty($language)) { $config["lr"] = "lang_" . $language; } if ($query) { if ($offset) { $config["start"] = $offset + 1; } if (empty($perPage)) { $perPage = 10; } $config["num"] = $perPage; $cacheKey = "google_cse_" . md5($query . serialize($config)); // this is just a protection so that no query get's sent twice in a request (loops, ...) if (\Zend_Registry::isRegistered($cacheKey)) { $result = \Zend_Registry::get($cacheKey); } else { if (!($result = Cache::load($cacheKey))) { $result = $search->cse->listCse($query, $config); Cache::save($result, $cacheKey, array("google_cse"), 3600, 999); \Zend_Registry::set($cacheKey, $result); } } $this->readGoogleResponse($result); return $this->getResults(false); } return array(); } else { throw new \Exception("Google Simple API Key is not configured in System-Settings."); } }
/** * @param Zend_Config $config -> configuration to contain * @param string $identifier -> cache identifier for caching sub files */ public function __construct(Zend_Config $config, $identifier) { $this->defaultConfig = $config; foreach ((array) $config->tenants as $tenantName => $tenantConfig) { if ($tenantConfig instanceof Zend_Config) { if ($tenantConfig->file) { $cacheKey = "onlineshop_config_" . $identifier . "_checkout_tenant_" . $tenantName; if (!($tenantConfigFile = \Pimcore\Model\Cache::load($cacheKey))) { $tenantConfigFile = new Zend_Config_Xml(PIMCORE_DOCUMENT_ROOT . (string) $tenantConfig->file, null, true); $tenantConfigFile = $tenantConfigFile->tenant; \Pimcore\Model\Cache::save($tenantConfigFile, $cacheKey, array("ecommerceconfig"), 9999); } $this->tenantConfigs[$tenantName] = $tenantConfigFile; } else { $this->tenantConfigs[$tenantName] = $tenantConfig; } } } }
/** * @return array|mixed */ public function getAllTranslations() { $cacheKey = static::getTableName() . "_data"; if (!($translations = Cache::load($cacheKey))) { $itemClass = static::getItemClass(); $translations = array(); $translationsData = $this->db->fetchAll("SELECT * FROM " . static::getTableName()); foreach ($translationsData as $t) { if (!$translations[$t["key"]]) { $translations[$t["key"]] = new $itemClass(); $translations[$t["key"]]->setKey($t["key"]); } $translations[$t["key"]]->addTranslation($t["language"], $t["text"]); //for legacy support if ($translations[$t["key"]]->getDate() < $t["creationDate"]) { $translations[$t["key"]]->setDate($t["creationDate"]); } $translations[$t["key"]]->setCreationDate($t["creationDate"]); $translations[$t["key"]]->setModificationDate($t["modificationDate"]); } Cache::save($translations, $cacheKey, array("translator", "translate"), 999); } return $translations; }
/** * @param null $data * @param $locale * @param array $options * @return array */ protected function _loadTranslationData($data, $locale, array $options = array()) { $locale = (string) $locale; $tmpKeyParts = explode("\\", self::getBackend()); $cacheKey = "Translate_" . array_pop($tmpKeyParts) . "_data_" . $locale; if (!($data = Cache::load($cacheKey))) { $data = array("__pimcore_dummy" => "only_a_dummy"); $listClass = self::getBackend() . "\\Listing"; $list = new $listClass(); if ($list->isCacheable()) { $list->setCondition("language = ?", array($locale)); $translations = $list->loadRaw(); foreach ($translations as $translation) { $data[mb_strtolower($translation["key"])] = Tool\Text::removeLineBreaks($translation["text"]); } Cache::save($data, $cacheKey, array("translator", "translator_website", "translate"), null, 999); $this->isCacheable = true; } else { $this->isCacheable = false; } } $this->_translate[$locale] = $data; return $this->_translate; }
/** * Checks for a suitable redirect * @throws Exception * @param bool $override * @return void */ protected function checkForRedirect($override = false) { // not for admin requests if (Tool::isFrontentRequestByAdmin()) { return; } try { $front = \Zend_Controller_Front::getInstance(); $config = Config::getSystemConfig(); // get current site if available $sourceSite = null; if (Site::isSiteRequest()) { $sourceSite = Site::getCurrentSite(); } $cacheKey = "system_route_redirect"; if (empty($this->redirects) && !($this->redirects = Cache::load($cacheKey))) { $list = new Redirect\Listing(); $list->setOrder("DESC"); $list->setOrderKey("priority"); $this->redirects = $list->load(); Cache::save($this->redirects, $cacheKey, array("system", "redirect", "route"), null, 998); } $requestScheme = $_SERVER['HTTPS'] == 'on' ? \Zend_Controller_Request_Http::SCHEME_HTTPS : \Zend_Controller_Request_Http::SCHEME_HTTP; $matchRequestUri = $_SERVER["REQUEST_URI"]; $matchUrl = $requestScheme . "://" . $_SERVER["HTTP_HOST"] . $matchRequestUri; foreach ($this->redirects as $redirect) { $matchAgainst = $matchRequestUri; if ($redirect->getSourceEntireUrl()) { $matchAgainst = $matchUrl; } // if override is true the priority has to be 99 which means that overriding is ok if (!$override || $override && $redirect->getPriority() == 99) { if (@preg_match($redirect->getSource(), $matchAgainst, $matches)) { // check for a site if ($sourceSite) { if ($sourceSite->getId() != $redirect->getSourceSite()) { continue; } } array_shift($matches); $target = $redirect->getTarget(); if (is_numeric($target)) { $d = Document::getById($target); if ($d instanceof Document\Page || $d instanceof Document\Link || $d instanceof Document\Hardlink) { $target = $d->getFullPath(); } else { \Logger::error("Target of redirect no found (Document-ID: " . $target . ")!"); continue; } } // replace escaped % signs so that they didn't have effects to vsprintf (PIMCORE-1215) $target = str_replace("\\%", "###URLENCODE_PLACEHOLDER###", $target); $url = vsprintf($target, $matches); $url = str_replace("###URLENCODE_PLACEHOLDER###", "%", $url); // support for pcre backreferences $url = replace_pcre_backreferences($url, $matches); if ($redirect->getTargetSite() && !preg_match("@http(s)?://@i", $url)) { try { $targetSite = Site::getById($redirect->getTargetSite()); // if the target site is specified and and the target-path is starting at root (not absolute to site) // the root-path will be replaced so that the page can be shown $url = preg_replace("@^" . $targetSite->getRootPath() . "/@", "/", $url); $url = $requestScheme . "://" . $targetSite->getMainDomain() . $url; } catch (\Exception $e) { \Logger::error("Site with ID " . $redirect->getTargetSite() . " not found."); continue; } } else { if (!preg_match("@http(s)?://@i", $url) && $config->general->domain && $redirect->getSourceEntireUrl()) { // prepend the host and scheme to avoid infinite loops when using "domain" redirects $url = ($front->getRequest()->isSecure() ? "https" : "http") . "://" . $config->general->domain . $url; } } // pass-through parameters if specified $queryString = $_SERVER["QUERY_STRING"]; if ($redirect->getPassThroughParameters() && !empty($queryString)) { $glue = "?"; if (strpos($url, "?")) { $glue = "&"; } $url .= $glue; $url .= $queryString; } header($redirect->getHttpStatus()); header("Location: " . $url, true, $redirect->getStatusCode()); // log all redirects to the redirect log \Pimcore\Log\Simple::log("redirect", Tool::getAnonymizedClientIp() . " \t Custom-Redirect ID: " . $redirect->getId() . " , Source: " . $_SERVER["REQUEST_URI"] . " -> " . $url); exit; } } } } catch (\Exception $e) { // no suitable route found } }
public function getText($page = null) { if (\Pimcore\Document::isAvailable() && \Pimcore\Document::isFileTypeSupported($this->getFilename())) { $cacheKey = "asset_document_text_" . $this->getId() . "_" . ($page ? $page : "all"); if (!($text = Cache::load($cacheKey))) { $document = \Pimcore\Document::getInstance(); $text = $document->getText($page, $this->getFileSystemPath()); Cache::save($text, $cacheKey, $this->getCacheTags(), null, 99, true); // force cache write } return $text; } else { \Logger::error("Couldn't get text out of document " . $this->getFullPath() . " no document adapter is available"); } return null; }
public function glossaryAction() { if ($this->getParam("data")) { $this->checkPermission("glossary"); Cache::clearTag("glossary"); if ($this->getParam("xaction") == "destroy") { $data = \Zend_Json::decode($this->getParam("data")); if (\Pimcore\Tool\Admin::isExtJS5()) { $id = $data["id"]; } else { $id = $data; } $glossary = Glossary::getById($id); $glossary->delete(); $this->_helper->json(array("success" => true, "data" => array())); } else { if ($this->getParam("xaction") == "update") { $data = \Zend_Json::decode($this->getParam("data")); // save glossary $glossary = Glossary::getById($data["id"]); if ($data["link"]) { if ($doc = Document::getByPath($data["link"])) { $tmpLink = $data["link"]; $data["link"] = $doc->getId(); } } $glossary->setValues($data); $glossary->save(); if ($link = $glossary->getLink()) { if (intval($link) > 0) { if ($doc = Document::getById(intval($link))) { $glossary->setLink($doc->getFullPath()); } } } $this->_helper->json(array("data" => $glossary, "success" => true)); } else { if ($this->getParam("xaction") == "create") { $data = \Zend_Json::decode($this->getParam("data")); unset($data["id"]); // save glossary $glossary = new Glossary(); if ($data["link"]) { if ($doc = Document::getByPath($data["link"])) { $tmpLink = $data["link"]; $data["link"] = $doc->getId(); } } $glossary->setValues($data); $glossary->save(); if ($link = $glossary->getLink()) { if (intval($link) > 0) { if ($doc = Document::getById(intval($link))) { $glossary->setLink($doc->getFullPath()); } } } $this->_helper->json(array("data" => $glossary, "success" => true)); } } } } else { // get list of glossaries $list = new Glossary\Listing(); $list->setLimit($this->getParam("limit")); $list->setOffset($this->getParam("start")); if ($this->getParam("sort")) { $list->setOrderKey($this->getParam("sort")); $list->setOrder($this->getParam("dir")); } if ($this->getParam("filter")) { $list->setCondition("`text` LIKE " . $list->quote("%" . $this->getParam("filter") . "%")); } $list->load(); $glossaries = array(); foreach ($list->getGlossary() as $glossary) { if ($link = $glossary->getLink()) { if (intval($link) > 0) { if ($doc = Document::getById(intval($link))) { $glossary->setLink($doc->getFullPath()); } } } $glossaries[] = $glossary; } $this->_helper->json(array("data" => $glossaries, "success" => true, "total" => $list->getTotalCount())); } $this->_helper->json(false); }
/** * this method is called with register_shutdown_function() and writes all data queued into the cache * @static * @return void */ public static function shutdown() { // set inShutdown to true so that the output-buffer knows that he is allowed to send the headers self::$inShutdown = true; // flush all custom output buffers while (@ob_end_flush()) { } // flush everything flush(); if (function_exists("fastcgi_finish_request")) { fastcgi_finish_request(); } // clear tags scheduled for the shutdown Cache::clearTagsOnShutdown(); // write collected items to cache backend and remove the write lock Cache::write(); Cache::removeWriteLock(); // release all open locks from this process Model\Tool\Lock::releaseAll(); // disable logging - otherwise this will cause problems in the ongoing shutdown process (session write, __destruct(), ...) \Logger::resetLoggers(); }
/** * @param AbstractListing $list */ protected static function loadToCache(AbstractListing $list) { $totalCount = $list->getTotalCount(); $iterations = ceil($totalCount / self::getPerIteration()); \Logger::info("New list of elements queued for storing into the cache with " . $iterations . " iterations and " . $totalCount . " total items"); for ($i = 0; $i < $iterations; $i++) { \Logger::info("Starting iteration " . $i . " with offset: " . self::getPerIteration() * $i); $list->setLimit(self::getPerIteration()); $list->setOffset(self::getPerIteration() * $i); $elements = $list->load(); foreach ($elements as $element) { $cacheKey = Element\Service::getElementType($element) . "_" . $element->getId(); Cache::storeToCache($element, $cacheKey, [], null, null, true); } \Pimcore::collectGarbage(); sleep(self::getTimoutBetweenIteration()); } }
/** * @static * @return mixed|\Zend_Config */ public static function getWebsiteConfig() { if (\Zend_Registry::isRegistered("pimcore_config_website")) { $config = \Zend_Registry::get("pimcore_config_website"); } else { $cacheKey = "website_config"; $siteId = null; if (Model\Site::isSiteRequest()) { $siteId = Model\Site::getCurrentSite()->getId(); $cacheKey = $cacheKey . "_site_" . $siteId; } if (!($config = Cache::load($cacheKey))) { $settingsArray = array(); $cacheTags = array("website_config", "system", "config", "output"); $list = new Model\WebsiteSetting\Listing(); $list = $list->load(); foreach ($list as $item) { $key = $item->getName(); $itemSiteId = $item->getSiteId(); if ($itemSiteId != 0 && $itemSiteId != $siteId) { continue; } $s = null; switch ($item->getType()) { case "document": case "asset": case "object": $s = Model\Element\Service::getElementById($item->getType(), $item->getData()); break; case "bool": $s = (bool) $item->getData(); break; case "text": $s = (string) $item->getData(); break; } if ($s instanceof Model\Element\ElementInterface) { $cacheTags = $s->getCacheTags($cacheTags); } if (isset($s)) { $settingsArray[$key] = $s; } } $config = new \Zend_Config($settingsArray, true); Cache::save($config, $cacheKey, $cacheTags, null, 998); } self::setWebsiteConfig($config); } return $config; }
/** Clears the column information for the given table. * @param $table */ protected function resetValidTableColumnsCache($table) { $cacheKey = self::CACHEKEY . $table; \Zend_Registry::getInstance()->offsetUnset($cacheKey); Cache::clearTags(array("system", "resource")); }
/** * @return array|mixed * @throws \Zend_Locale_Exception */ public static function getSupportedLocales() { // List of locales that are no longer part of CLDR // this was also changed in the Zend Framework, but here we need to provide an appropriate alternative // since this information isn't public in \Zend_Locale :-( $aliases = ['az_AZ' => true, 'bs_BA' => true, 'ha_GH' => true, 'ha_NE' => true, 'ha_NG' => true, 'kk_KZ' => true, 'ks_IN' => true, 'mn_MN' => true, 'ms_BN' => true, 'ms_MY' => true, 'ms_SG' => true, 'pa_IN' => true, 'pa_PK' => true, 'shi_MA' => true, 'sr_BA' => true, 'sr_ME' => true, 'sr_RS' => true, 'sr_XK' => true, 'tg_TJ' => true, 'tzm_MA' => true, 'uz_AF' => true, 'uz_UZ' => true, 'vai_LR' => true, 'zh_CN' => true, 'zh_HK' => true, 'zh_MO' => true, 'zh_SG' => true, 'zh_TW' => true]; $locale = \Zend_Locale::findLocale(); $cacheKey = "system_supported_locales_" . strtolower((string) $locale); if (!($languageOptions = Cache::load($cacheKey))) { // we use the locale here, because \Zend_Translate only supports locales not "languages" $languages = \Zend_Locale::getLocaleList(); $languages = array_merge($languages, $aliases); $languageOptions = array(); foreach ($languages as $code => $active) { if ($active) { $translation = \Zend_Locale::getTranslation($code, "language"); if (!$translation) { $tmpLocale = new \Zend_Locale($code); $lt = \Zend_Locale::getTranslation($tmpLocale->getLanguage(), "language"); $tt = \Zend_Locale::getTranslation($tmpLocale->getRegion(), "territory"); if ($lt && $tt) { $translation = $lt . " (" . $tt . ")"; } } if (!$translation) { $translation = $code; } $languageOptions[$code] = $translation; } } asort($languageOptions); Cache::save($languageOptions, $cacheKey, ["system"]); } return $languageOptions; }
public function cleanupAction() { $listClass = "\\Pimcore\\Model\\Translation\\" . ucfirst($this->getParam("type")) . "\\Listing"; if (Tool::classExists($listClass)) { $list = new $listClass(); $list->cleanup(); \Pimcore\Model\Cache::clearTags(array("translator", "translate")); $this->_helper->json(array("success" => true)); } $this->_helper->json(array("success" => false)); }
public function portletFeedAction() { $dashboard = $this->getCurrentConfiguration(); $id = $this->getParam("id"); $cache = \Pimcore\Model\Cache::getInstance(); if ($cache) { $cache->setLifetime(10); \Zend_Feed_Reader::setCache($cache); } $portlet = array(); foreach ($dashboard["positions"] as $col) { foreach ($col as $row) { if ($row['id'] == $id) { $portlet = $row; } } } $feedUrl = $portlet['config']; $feed = null; if (!empty($feedUrl)) { try { $feed = \Zend_Feed_Reader::import($feedUrl); } catch (\Exception $e) { \Logger::error($e); } } $count = 0; $entries = array(); if ($feed) { foreach ($feed as $entry) { // display only the latest 11 entries $count++; if ($count > 10) { break; } $entry = array("title" => $entry->getTitle(), "description" => $entry->getDescription(), 'authors' => $entry->getAuthors(), 'link' => $entry->getLink(), 'content' => $entry->getContent()); foreach ($entry as &$content) { $content = strip_tags($content, "<h1><h2><h3><h4><h5><p><br><a><img><div><b><strong><i>"); $content = preg_replace('/on([a-z]+)([ ]+)?=/i', "data-on\$1=", $content); } $entries[] = $entry; } } $this->_helper->json(array("entries" => $entries)); }
/** * */ public function dispatchLoopShutdown() { if (!Tool::isHtmlResponse($this->getResponse())) { return; } if ($this->enabled) { include_once "simple_html_dom.php"; $body = $this->getResponse()->getBody(); $html = str_get_html($body); if ($html) { $elements = $html->find("link[rel=stylesheet], img, script[src]"); foreach ($elements as $element) { if ($element->tag == "link") { if ($this->pathMatch($element->href)) { $element->href = $this->rewritePath($element->href); } } else { if ($element->tag == "img") { if ($this->pathMatch($element->src)) { $element->src = $this->rewritePath($element->src); } } else { if ($element->tag == "script") { if ($this->pathMatch($element->src)) { $element->src = $this->rewritePath($element->src); } } } } } $body = $html->save(); $html->clear(); unset($html); $this->getResponse()->setBody($body); // save storage CacheManager::save($this->cachedItems, self::cacheKey, array(), 3600); } } }
/** * @return Property[] */ public function getProperties() { if ($this->o_properties === null) { // try to get from cache $cacheKey = "object_properties_" . $this->getId(); $properties = Cache::load($cacheKey); if (!is_array($properties)) { $properties = $this->getResource()->getProperties(); $elementCacheTag = $this->getCacheTag(); $cacheTags = array("object_properties" => "object_properties", $elementCacheTag => $elementCacheTag); Cache::save($properties, $cacheKey, $cacheTags); } $this->setProperties($properties); } return $this->o_properties; }
/** * includes a document * * @param $include * @param array $params * @return string */ public function inc($include, $params = null, $cacheEnabled = true) { if (!is_array($params)) { $params = []; } // check if output-cache is enabled, if so, we're also using the cache here $cacheKey = null; $cacheConfig = false; if ($cacheEnabled) { if ($cacheConfig = Tool\Frontend::isOutputCacheEnabled()) { // cleanup params to avoid serializing Element\ElementInterface objects $cacheParams = $params; $cacheParams["~~include-document"] = $include; array_walk($cacheParams, function (&$value, $key) { if ($value instanceof Element\ElementInterface) { $value = $value->getId(); } else { if (is_object($value) && method_exists($value, "__toString")) { $value = (string) $value; } } }); $cacheKey = "tag_inc__" . md5(serialize($cacheParams)); if ($content = Model\Cache::load($cacheKey)) { return $content; } } } $editmodeBackup = \Zend_Registry::get("pimcore_editmode"); \Zend_Registry::set("pimcore_editmode", false); $includeBak = $include; // this is if $this->inc is called eg. with $this->href() as argument if (!$include instanceof Model\Document\PageSnippet && is_object($include) && method_exists($include, "__toString")) { $include = (string) $include; } if (is_string($include)) { try { $include = Model\Document::getByPath($include); } catch (\Exception $e) { $include = $includeBak; } } else { if (is_numeric($include)) { try { $include = Model\Document::getById($include); } catch (\Exception $e) { $include = $includeBak; } } } $params = array_merge($params, array("document" => $include)); $content = ""; if ($include instanceof Model\Document\PageSnippet && $include->isPublished()) { if ($include->getAction() && $include->getController()) { $content = $this->action($include->getAction(), $include->getController(), $include->getModule(), $params); } else { if ($include->getTemplate()) { $content = $this->action("default", "default", null, $params); } } // in editmode, we need to parse the returned html from the document include // add a class and the pimcore id / type so that it can be opened in editmode using the context menu // if there's no first level HTML container => add one (wrapper) if ($this->editmode) { include_once "simple_html_dom.php"; $editmodeClass = " pimcore_editable pimcore_tag_inc "; // this is if the content that is included does already contain markup/html // this is needed by the editmode to highlight included documents if ($html = str_get_html($content)) { $childs = $html->find("*"); if (is_array($childs)) { foreach ($childs as $child) { $child->class = $child->class . $editmodeClass; $child->pimcore_type = $include->getType(); $child->pimcore_id = $include->getId(); } } $content = $html->save(); $html->clear(); unset($html); } else { // add a div container if the include doesn't contain markup/html $content = '<div class="' . $editmodeClass . '" pimcore_id="' . $include->getId() . '" pimcore_type="' . $include->getType() . '">' . $content . '</div>'; } } // we need to add a component id to all first level html containers $componentId = ""; if ($this->document instanceof Model\Document) { $componentId .= 'document:' . $this->document->getId() . '.'; } $componentId .= 'type:inc.name:' . $include->getId(); $content = \Pimcore\Tool\Frontend::addComponentIdToHtml($content, $componentId); } \Zend_Registry::set("pimcore_editmode", $editmodeBackup); // write contents to the cache, if output-cache is enabled if ($cacheConfig) { Model\Cache::save($content, $cacheKey, array("output", "output_inline"), $cacheConfig["lifetime"]); } return $content; }
/** * @param $activeDocument * @param null $navigationRootDocument * @param null $htmlMenuIdPrefix * @param null $pageCallback * @param bool|string $cache * @return mixed|\Zend_Navigation * @throws \Exception * @throws \Zend_Navigation_Exception */ public function getNavigation($activeDocument, $navigationRootDocument = null, $htmlMenuIdPrefix = null, $pageCallback = null, $cache = true) { $cacheEnabled = (bool) $cache; $this->_htmlMenuIdPrefix = $htmlMenuIdPrefix; if (!$navigationRootDocument) { $navigationRootDocument = Document::getById(1); } $siteSuffix = ""; if (Site::isSiteRequest()) { $site = Site::getCurrentSite(); $siteSuffix = "__site_" . $site->getId(); } $cacheId = $navigationRootDocument->getId(); if (is_string($cache)) { $cacheId .= "_" . $cache; } $cacheKey = "navigation_" . $cacheId . $siteSuffix; $navigation = CacheManager::load($cacheKey); if (!$navigation || !$cacheEnabled) { $navigation = new \Zend_Navigation(); if ($navigationRootDocument->hasChilds()) { $rootPage = $this->buildNextLevel($navigationRootDocument, true, $pageCallback); $navigation->addPages($rootPage); } // we need to force caching here, otherwise the active classes and other settings will be set and later // also written into cache (pass-by-reference) ... when serializing the data directly here, we don't have this problem if ($cacheEnabled) { CacheManager::save($navigation, $cacheKey, ["output", "navigation"], null, 999, true); } } // set active path $activePage = $navigation->findOneBy("realFullPath", $activeDocument->getRealFullPath()); if (!$activePage) { // find by link target $activePage = $navigation->findOneBy("uri", $activeDocument->getRealFullPath()); } if ($activePage) { // we found an active document, so we can build the active trail by getting respectively the parent $this->addActiveCssClasses($activePage, true); } else { // we don't have an active document, so we try to build the trail on our own $allPages = $navigation->findAllBy("uri", "/.*/", true); foreach ($allPages as $page) { $activeTrail = false; if (strpos($activeDocument->getRealFullPath(), $page->getRealFullPath() . "/") === 0) { $activeTrail = true; } if ($page->getDocumentType() == "link") { if (strpos($activeDocument->getFullPath(), $page->getUri() . "/") === 0) { $activeTrail = true; } } if ($activeTrail) { $page->setActive(true); $page->setClass($page->getClass() . " active active-trail"); } } } return $navigation; }
public function clearCacheAction() { \Pimcore\Model\Cache::clearTag("ecommerceconfig"); exit; }
/** * */ public function dispatchLoopShutdown() { if ($this->enabled && session_id()) { $this->disable("session in use"); } if ($this->disableReason) { $this->getResponse()->setHeader("X-Pimcore-Output-Cache-Disable-Reason", $this->disableReason, true); } if ($this->enabled && $this->getResponse()->getHttpResponseCode() == 200) { try { if ($this->lifetime && $this->addExpireHeader) { // add cache control for proxies and http-caches like varnish, ... $this->getResponse()->setHeader("Cache-Control", "public, max-age=" . $this->lifetime, true); // add expire header $this->getResponse()->setHeader("Expires", \Zend_Date::now()->add($this->lifetime)->get(\Zend_Date::RFC_1123), true); } $cacheItem = array("headers" => $this->getResponse()->getHeaders(), "rawHeaders" => $this->getResponse()->getRawHeaders(), "content" => $this->getResponse()->getBody(), "date" => \Zend_Date::now()->getIso()); $cacheKey = $this->defaultCacheKey; $deviceDetector = Tool\DeviceDetector::getInstance(); if ($deviceDetector->wasUsed()) { $cacheKey .= "_" . $deviceDetector->getDevice(); } CacheManager::save($cacheItem, $cacheKey, array("output"), $this->lifetime, 1000); } catch (\Exception $e) { \Logger::error($e); return; } } else { // output-cache was disabled, add "output" as cleared tag to ensure that no other "output" tagged elements // like the inc and snippet cache get into the cache CacheManager::addClearedTag("output_inline"); } }
/** * @return void */ public function clearDependentCache() { // this is mostly called in Redirect\Resource not here try { \Pimcore\Model\Cache::clearTag("redirect"); } catch (\Exception $e) { \Logger::crit($e); } }
/** * @return array|mixed * @throws \Zend_Exception */ protected function getData() { if (\Zend_Registry::isRegistered("Zend_Locale")) { $locale = (string) \Zend_Registry::get("Zend_Locale"); } else { return array(); } $siteId = ""; try { $site = Model\Site::getCurrentSite(); if ($site instanceof Model\Site) { $siteId = $site->getId(); } } catch (\Exception $e) { // not inside a site } $cacheKey = "glossary_" . $locale . "_" . $siteId; try { $data = \Zend_Registry::get($cacheKey); return $data; } catch (\Exception $e) { } if (!($data = Model\Cache::load($cacheKey))) { $list = new Model\Glossary\Listing(); $list->setCondition("(language = ? OR language IS NULL OR language = '') AND (site = ? OR site IS NULL OR site = '')", array($locale, $siteId)); $list->setOrderKey("LENGTH(`text`)", false); $list->setOrder("DESC"); $data = $list->getDataArray(); $data = $this->prepareData($data); Model\Cache::save($data, $cacheKey, array("glossary"), null, 995); \Zend_Registry::set($cacheKey, $data); } return $data; }
/** * @throws \Zend_Controller_Response_Exception */ public function checkForErrors() { if ($error = $this->getParam('error_handler')) { if ($error->exception) { if ($error->exception instanceof \Zend_Controller_Router_Exception || $error->exception instanceof \Zend_Controller_Action_Exception) { header('HTTP/1.1 404 Not Found'); //$this->getResponse()->setRawHeader('HTTP/1.1 404 Not Found'); $this->getResponse()->setHttpResponseCode(404); // check if the resource that wasn't found is a common static file // for them we don't show the error page, as generating this is very heavy in terms of performance if (preg_match("/\\.(js|css|png|jpe?g|gif|eot|ttf|woff|svg|ico|map|swf|txt)\$/", $this->getRequest()->getPathInfo())) { echo "HTTP/1.1 404 Not Found\nFiltered by error handler (static file exception)"; exit; } } else { header('HTTP/1.1 503 Service Temporarily Unavailable'); //$this->getResponse()->setRawHeader('HTTP/1.1 503 Service Temporarily Unavailable'); $this->getResponse()->setHttpResponseCode(503); } \Logger::error("Unable to find URL: " . $_SERVER["REQUEST_URI"]); \Logger::error($error->exception); try { // check if we have the error page already in the cache // the cache is written in Pimcore_Controller_Plugin_HttpErrorLog::dispatchLoopShutdown() $cacheKey = "error_page_response_" . \Pimcore\Tool\Frontend::getSiteKey(); if ($responseBody = \Pimcore\Model\Cache::load($cacheKey)) { $this->getResponse()->setBody($responseBody); $this->getResponse()->sendResponse(); // write to http_error log $errorLogPlugin = \Zend_Controller_Front::getInstance()->getPlugin("Pimcore\\Controller\\Plugin\\HttpErrorLog"); if ($errorLogPlugin) { $errorLogPlugin->writeLog(); } exit; } else { $document = \Zend_Registry::get("pimcore_error_document"); $this->setDocument($document); $this->setParam("document", $document); $this->disableLayout(); // http_error log writing is done in Pimcore_Controller_Plugin_HttpErrorLog in this case } } catch (\Exception $e) { $m = "Unable to load error document"; Tool::exitWithError($m); } } } }