/**
* Add the template output to the cache and add the cache headers
*/
protected function addToCache()
{
/** @var PageModel $objPage */
global $objPage;
$intCache = 0;
// Decide whether the page shall be cached
if (!isset($_GET['file']) && !isset($_GET['token']) && empty($_POST) && !BE_USER_LOGGED_IN && !FE_USER_LOGGED_IN && !$_SESSION['DISABLE_CACHE'] && !isset($_SESSION['LOGIN_ERROR']) && !\Message::hasMessages() && intval($objPage->cache) > 0 && !$objPage->protected) {
$intCache = time() + intval($objPage->cache);
}
// Server-side cache
if ($intCache > 0 && (\Config::get('cacheMode') == 'both' || \Config::get('cacheMode') == 'server')) {
// If the request string is empty, use a special cache tag which considers the page language
if (\Environment::get('relativeRequest') == '') {
$strCacheKey = \Environment::get('host') . '/empty.' . $objPage->language;
} else {
$strCacheKey = \Environment::get('host') . '/' . \Environment::get('relativeRequest');
}
// HOOK: add custom logic
if (isset($GLOBALS['TL_HOOKS']['getCacheKey']) && is_array($GLOBALS['TL_HOOKS']['getCacheKey'])) {
foreach ($GLOBALS['TL_HOOKS']['getCacheKey'] as $callback) {
$this->import($callback[0]);
$strCacheKey = $this->{$callback[0]}->{$callback[1]}($strCacheKey);
}
}
// Add a suffix if there is a mobile layout (see #7826)
if ($objPage->mobileLayout > 0) {
if (\Input::cookie('TL_VIEW') == 'mobile' || \Environment::get('agent')->mobile && \Input::cookie('TL_VIEW') != 'desktop') {
$strCacheKey .= '.mobile';
} else {
$strCacheKey .= '.desktop';
}
}
// Replace insert tags for caching
$strBuffer = $this->replaceInsertTags($this->strBuffer);
$strBuffer = $this->replaceDynamicScriptTags($strBuffer);
// see #4203
// Add the cache file header
$strHeader = sprintf("<?php /* %s */ \$expire = %d; \$content = %s; \$type = %s; \$files = %s; \$assets = %s; ?>\n", $strCacheKey, (int) $intCache, var_export($this->strContentType, true), var_export($objPage->type, true), var_export(TL_FILES_URL, true), var_export(TL_ASSETS_URL, true));
$strCachePath = str_replace(TL_ROOT . '/', '', \System::getContainer()->getParameter('kernel.cache_dir'));
// Create the cache file
$strMd5CacheKey = md5($strCacheKey);
$objFile = new \File($strCachePath . '/contao/html/' . substr($strMd5CacheKey, 0, 1) . '/' . $strMd5CacheKey . '.html');
$objFile->write($strHeader);
$objFile->append($this->minifyHtml($strBuffer), '');
$objFile->close();
}
// Client-side cache
if (!headers_sent()) {
if ($intCache > 0 && (\Config::get('cacheMode') == 'both' || \Config::get('cacheMode') == 'browser')) {
header('Cache-Control: private, max-age=' . ($intCache - time()));
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
header('Expires: ' . gmdate('D, d M Y H:i:s', $intCache) . ' GMT');
} else {
header('Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Expires: Fri, 06 Jun 1975 15:10:00 GMT');
}
}
}