Esempio n. 1
0
 /**
  * Initialize the object
  */
 protected function __construct()
 {
     parent::__construct();
     $this->strIp = \Environment::get('ip');
     $this->strHash = \Input::cookie($this->strCookie);
 }
Esempio n. 2
0
 /**
  * Return the debug bar string
  *
  * @return string The debug bar markup
  */
 protected function getDebugBar()
 {
     $intReturned = 0;
     $intAffected = 0;
     // Count the totals (see #3884)
     if (is_array($GLOBALS['TL_DEBUG']['database_queries'])) {
         foreach ($GLOBALS['TL_DEBUG']['database_queries'] as $k => $v) {
             $intReturned += $v['return_count'];
             $intAffected += $v['affected_count'];
             unset($GLOBALS['TL_DEBUG']['database_queries'][$k]['return_count']);
             unset($GLOBALS['TL_DEBUG']['database_queries'][$k]['affected_count']);
         }
     }
     $intElapsed = microtime(true) - TL_START;
     $strDebug = sprintf("<!-- indexer::stop -->\n" . '<div id="contao-debug">' . '<p>' . '<span class="debug-time">Execution time: %s ms</span>' . '<span class="debug-memory">Memory usage: %s</span>' . '<span class="debug-db">Database queries: %d</span>' . '<span class="debug-rows">Rows: %d returned, %s affected</span>' . '<span class="debug-models">Registered models: %d</span>' . '<span id="debug-tog">&nbsp;</span>' . '</p>' . '<div><pre>', $this->getFormattedNumber($intElapsed * 1000, 0), $this->getReadableSize(memory_get_peak_usage()), count($GLOBALS['TL_DEBUG']['database_queries']), $intReturned, $intAffected, \Model\Registry::getInstance()->count());
     ksort($GLOBALS['TL_DEBUG']);
     ob_start();
     print_r($GLOBALS['TL_DEBUG']);
     $strDebug .= ob_get_contents();
     ob_end_clean();
     unset($GLOBALS['TL_DEBUG']);
     $strDebug .= '</pre></div></div>' . $this->generateInlineScript("(function(\$) {" . "\$(document.body).addClass('debug-enabled " . \Input::cookie('CONTAO_CONSOLE') . "');" . "\$('debug-tog').addEvent('click',function(e) {" . "\$(document.body).toggleClass('debug-closed');" . "Cookie.write('CONTAO_CONSOLE',\$(document.body).hasClass('debug-closed')?'debug-closed':'',{path:'" . (TL_PATH ?: '/') . "'});" . "});" . "})(document.id);", $this->strFormat == 'xhtml') . "\n<!-- indexer::continue -->\n\n";
     return $strDebug;
 }
Esempio n. 3
0
 /**
  * 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');
         }
     }
 }
Esempio n. 4
0
 /**
  * Check whether there is a cached version of the page and return a response object
  *
  * @return Response|null
  */
 public static function getResponseFromCache()
 {
     // Build the page if a user is (potentially) logged in or there is POST data
     if (!empty($_POST) || \Input::cookie('BE_USER_AUTH') || \Input::cookie('FE_USER_AUTH') || \Input::cookie('FE_AUTO_LOGIN') || $_SESSION['DISABLE_CACHE'] || isset($_SESSION['LOGIN_ERROR']) || \Message::hasMessages() || \Config::get('debugMode')) {
         return null;
     }
     $strCacheDir = \System::getContainer()->getParameter('kernel.cache_dir');
     // Try to map the empty request
     if (\Environment::get('relativeRequest') == '') {
         // Return if the language is added to the URL and the empty domain will be redirected
         if (\Config::get('addLanguageToUrl') && !\Config::get('doNotRedirectEmpty')) {
             return null;
         }
         $strCacheKey = null;
         $arrLanguage = \Environment::get('httpAcceptLanguage');
         $strMappingFile = $strCacheDir . '/contao/config/mapping.php';
         // Try to get the cache key from the mapper array
         if (file_exists($strMappingFile)) {
             $arrMapper = (include $strMappingFile);
             $arrPaths = array(\Environment::get('host'), '*');
             // Try the language specific keys
             foreach ($arrLanguage as $strLanguage) {
                 foreach ($arrPaths as $strPath) {
                     $strKey = $strPath . '/empty.' . $strLanguage;
                     if (isset($arrMapper[$strKey])) {
                         $strCacheKey = $arrMapper[$strKey];
                         break;
                     }
                 }
             }
             // Try the fallback key
             if ($strCacheKey === null) {
                 foreach ($arrPaths as $strPath) {
                     $strKey = $strPath . '/empty.fallback';
                     if (isset($arrMapper[$strKey])) {
                         $strCacheKey = $arrMapper[$strKey];
                         break;
                     }
                 }
             }
         }
         // Fall back to the first accepted language
         if ($strCacheKey === null) {
             $strCacheKey = \Environment::get('host') . '/empty.' . $arrLanguage[0];
         }
     } 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) {
             $strCacheKey = \System::importStatic($callback[0])->{$callback[1]}($strCacheKey);
         }
     }
     $blnFound = false;
     $strCacheFile = null;
     // Check for a mobile layout
     if (\Input::cookie('TL_VIEW') == 'mobile' || \Environment::get('agent')->mobile && \Input::cookie('TL_VIEW') != 'desktop') {
         $strMd5CacheKey = md5($strCacheKey . '.mobile');
         $strCacheFile = $strCacheDir . '/contao/html/' . substr($strMd5CacheKey, 0, 1) . '/' . $strMd5CacheKey . '.html';
         if (file_exists($strCacheFile)) {
             $blnFound = true;
         }
     } else {
         $strMd5CacheKey = md5($strCacheKey . '.desktop');
         $strCacheFile = $strCacheDir . '/contao/html/' . substr($strMd5CacheKey, 0, 1) . '/' . $strMd5CacheKey . '.html';
         if (file_exists($strCacheFile)) {
             $blnFound = true;
         }
     }
     // Check for a regular layout
     if (!$blnFound) {
         $strMd5CacheKey = md5($strCacheKey);
         $strCacheFile = $strCacheDir . '/contao/html/' . substr($strMd5CacheKey, 0, 1) . '/' . $strMd5CacheKey . '.html';
         if (file_exists($strCacheFile)) {
             $blnFound = true;
         }
     }
     // Return if the file does not exist
     if (!$blnFound) {
         return null;
     }
     $expire = null;
     $content = null;
     $type = null;
     $files = null;
     $assets = null;
     // Include the file
     ob_start();
     require_once $strCacheFile;
     // The file has expired
     if ($expire < time()) {
         ob_end_clean();
         return null;
     }
     // Define the static URL constants (see #7914)
     define('TL_FILES_URL', $files);
     define('TL_ASSETS_URL', $assets);
     // Read the buffer
     $strBuffer = ob_get_clean();
     /** @var AttributeBagInterface $session */
     $session = \System::getContainer()->get('session')->getBag('contao_frontend');
     // Session required to determine the referer
     $data = $session->all();
     // Set the new referer
     if (!isset($_GET['pdf']) && !isset($_GET['file']) && !isset($_GET['id']) && $data['referer']['current'] != \Environment::get('requestUri')) {
         $data['referer']['last'] = $data['referer']['current'];
         $data['referer']['current'] = substr(\Environment::get('requestUri'), strlen(\Environment::get('path')) + 1);
     }
     // Store the session data
     $session->replace($data);
     // Load the default language file (see #2644)
     \System::loadLanguageFile('default');
     // Replace the insert tags and then re-replace the request_token tag in case a form element has been loaded via insert tag
     $strBuffer = \Controller::replaceInsertTags($strBuffer, false);
     $strBuffer = str_replace(array('{{request_token}}', '[{]', '[}]'), array(REQUEST_TOKEN, '{{', '}}'), $strBuffer);
     // HOOK: allow to modify the compiled markup (see #4291 and #7457)
     if (isset($GLOBALS['TL_HOOKS']['modifyFrontendPage']) && is_array($GLOBALS['TL_HOOKS']['modifyFrontendPage'])) {
         foreach ($GLOBALS['TL_HOOKS']['modifyFrontendPage'] as $callback) {
             $strBuffer = \System::importStatic($callback[0])->{$callback[1]}($strBuffer, null);
         }
     }
     // Content type
     if (!$content) {
         $content = 'text/html';
     }
     $response = new Response($strBuffer);
     // Send the status header (see #6585)
     if ($type == 'error_403') {
         $response->setStatusCode(Response::HTTP_FORBIDDEN);
     } elseif ($type == 'error_404') {
         $response->setStatusCode(Response::HTTP_NOT_FOUND);
     }
     $response->headers->set('Vary', 'User-Agent', false);
     $response->headers->set('Content-Type', $content . '; charset=' . \Config::get('characterSet'));
     // Send the cache headers
     if ($expire !== null && (\Config::get('cacheMode') == 'both' || \Config::get('cacheMode') == 'browser')) {
         $response->headers->set('Cache-Control', 'public, max-age=' . ($expire - time()));
         $response->headers->set('Pragma', 'public');
         $response->headers->set('Last-Modified', gmdate('D, d M Y H:i:s', time()) . ' GMT');
         $response->headers->set('Expires', gmdate('D, d M Y H:i:s', $expire) . ' GMT');
     } else {
         $response->headers->set('Cache-Control', 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0');
         $response->headers->set('Pragma', 'no-cache');
         $response->headers->set('Last-Modified', gmdate('D, d M Y H:i:s') . ' GMT');
         $response->headers->set('Expires', 'Fri, 06 Jun 1975 15:10:00 GMT');
     }
     return $response;
 }
Esempio n. 5
0
 /**
  * Run the controller and parse the template
  *
  * @return Response
  */
 public function run()
 {
     $this->disableProfiler();
     if (\Environment::get('isAjaxRequest')) {
         $this->getDatalistOptions();
     }
     $strUser = '';
     $strHash = $this->getSessionHash('FE_USER_AUTH');
     // Get the front end user
     if (FE_USER_LOGGED_IN) {
         $objUser = $this->Database->prepare("SELECT username FROM tl_member WHERE id=(SELECT pid FROM tl_session WHERE hash=?)")->limit(1)->execute($strHash);
         if ($objUser->numRows) {
             $strUser = $objUser->username;
         }
     }
     /** @var BackendTemplate|object $objTemplate */
     $objTemplate = new \BackendTemplate('be_switch');
     $objTemplate->user = $strUser;
     $objTemplate->show = \Input::cookie('FE_PREVIEW');
     $objTemplate->update = false;
     // Switch
     if (\Input::post('FORM_SUBMIT') == 'tl_switch') {
         $time = time();
         // Hide unpublished elements
         if (\Input::post('unpublished') == 'hide') {
             $this->setCookie('FE_PREVIEW', 0, $time - 86400);
             $objTemplate->show = 0;
         } else {
             $this->setCookie('FE_PREVIEW', 1, $time + \Config::get('sessionTimeout'));
             $objTemplate->show = 1;
         }
         // Allow admins to switch user accounts
         if ($this->User->isAdmin) {
             // Remove old sessions
             $this->Database->prepare("DELETE FROM tl_session WHERE tstamp<? OR hash=?")->execute($time - \Config::get('sessionTimeout'), $strHash);
             // Log in the front end user
             if (\Input::post('user')) {
                 $objUser = \MemberModel::findByUsername(\Input::post('user'));
                 if ($objUser !== null) {
                     // Insert the new session
                     $this->Database->prepare("INSERT INTO tl_session (pid, tstamp, name, sessionID, ip, hash) VALUES (?, ?, ?, ?, ?, ?)")->execute($objUser->id, $time, 'FE_USER_AUTH', \System::getContainer()->get('session')->getId(), \Environment::get('ip'), $strHash);
                     // Set the cookie
                     $this->setCookie('FE_USER_AUTH', $strHash, $time + \Config::get('sessionTimeout'), null, null, false, true);
                     $objTemplate->user = \Input::post('user');
                 }
             } else {
                 // Remove cookie
                 $this->setCookie('FE_USER_AUTH', $strHash, $time - 86400, null, null, false, true);
                 $objTemplate->user = '';
             }
         }
         $objTemplate->update = true;
     }
     // Default variables
     $objTemplate->theme = \Backend::getTheme();
     $objTemplate->base = \Environment::get('base');
     $objTemplate->language = $GLOBALS['TL_LANGUAGE'];
     $objTemplate->apply = $GLOBALS['TL_LANG']['MSC']['apply'];
     $objTemplate->reload = $GLOBALS['TL_LANG']['MSC']['reload'];
     $objTemplate->feUser = $GLOBALS['TL_LANG']['MSC']['feUser'];
     $objTemplate->username = $GLOBALS['TL_LANG']['MSC']['username'];
     $objTemplate->charset = \Config::get('characterSet');
     $objTemplate->lblHide = $GLOBALS['TL_LANG']['MSC']['hiddenHide'];
     $objTemplate->lblShow = $GLOBALS['TL_LANG']['MSC']['hiddenShow'];
     $objTemplate->fePreview = $GLOBALS['TL_LANG']['MSC']['fePreview'];
     $objTemplate->hiddenElements = $GLOBALS['TL_LANG']['MSC']['hiddenElements'];
     $objTemplate->closeSrc = TL_FILES_URL . 'system/themes/' . \Backend::getTheme() . '/images/close.gif';
     $objTemplate->action = ampersand(\Environment::get('request'));
     $objTemplate->isAdmin = $this->User->isAdmin;
     return $objTemplate->getResponse();
 }
Esempio n. 6
0
 /**
  * Get a page layout and return it as database result object
  *
  * @param \PageModel $objPage
  *
  * @return \LayoutModel
  */
 protected function getPageLayout($objPage)
 {
     $blnMobile = $objPage->mobileLayout && \Environment::get('agent')->mobile;
     // Override the autodetected value
     if (\Input::cookie('TL_VIEW') == 'mobile') {
         $blnMobile = true;
     } elseif (\Input::cookie('TL_VIEW') == 'desktop') {
         $blnMobile = false;
     }
     $intId = $blnMobile && $objPage->mobileLayout ? $objPage->mobileLayout : $objPage->layout;
     $objLayout = \LayoutModel::findByPk($intId);
     // Die if there is no layout
     if (null === $objLayout) {
         $this->log('Could not find layout ID "' . $intId . '"', __METHOD__, TL_ERROR);
         throw new NoLayoutSpecifiedException('No layout specified');
     }
     $objPage->hasJQuery = $objLayout->addJQuery;
     $objPage->hasMooTools = $objLayout->addMooTools;
     $objPage->isMobile = $blnMobile;
     return $objLayout;
 }
 /**
  * Logout from phpbb
  */
 public function logout()
 {
     if ($this->debug) {
         System::log("phpbb_bridge: " . __METHOD__, __METHOD__, TL_ACCESS);
     }
     $cookie_prefix = $this->getDbConfig('cookie_name');
     $sid = Input::cookie($cookie_prefix . '_sid');
     System::getContainer()->get('session')->remove('phpbb_user');
     if ($sid) {
         $logoutUrl = Environment::get('url') . '/' . $this->getForumPath() . '/contao_connect/logout';
         $headers = $this->initForumRequestHeaders();
         $browser = $this->initForumRequest();
         $browser->get($logoutUrl, $headers);
         // Parse cookies and send them to the client
         foreach ($browser->getListener()->getCookies() as $cookie) {
             /* @var $cookie Cookie */
             // Stream cookies through to the client
             System::setCookie($cookie->getName(), $cookie->getValue(), strtotime($cookie->getAttribute('expires')), $cookie->getAttribute('path'), $cookie->getAttribute('domain'));
         }
     }
 }
Esempio n. 8
0
 /**
  * Generate the module
  *
  * @return string
  */
 public function run()
 {
     if (!\Config::get('enableSearch')) {
         return '';
     }
     $time = time();
     /** @var BackendTemplate|object $objTemplate */
     $objTemplate = new \BackendTemplate('be_rebuild_index');
     $objTemplate->action = ampersand(\Environment::get('request'));
     $objTemplate->indexHeadline = $GLOBALS['TL_LANG']['tl_maintenance']['searchIndex'];
     $objTemplate->isActive = $this->isActive();
     // Add the error message
     if ($_SESSION['REBUILD_INDEX_ERROR'] != '') {
         $objTemplate->indexMessage = $_SESSION['REBUILD_INDEX_ERROR'];
         $_SESSION['REBUILD_INDEX_ERROR'] = '';
     }
     // Rebuild the index
     if (\Input::get('act') == 'index') {
         // Check the request token (see #4007)
         if (!isset($_GET['rt']) || !\RequestToken::validate(\Input::get('rt'))) {
             /** @var SessionInterface $objSession */
             $objSession = \System::getContainer()->get('session');
             $objSession->set('INVALID_TOKEN_URL', \Environment::get('request'));
             $this->redirect('contao/confirm.php');
         }
         $arrPages = $this->findSearchablePages();
         // HOOK: take additional pages
         if (isset($GLOBALS['TL_HOOKS']['getSearchablePages']) && is_array($GLOBALS['TL_HOOKS']['getSearchablePages'])) {
             foreach ($GLOBALS['TL_HOOKS']['getSearchablePages'] as $callback) {
                 $this->import($callback[0]);
                 $arrPages = $this->{$callback[0]}->{$callback[1]}($arrPages);
             }
         }
         // Return if there are no pages
         if (empty($arrPages)) {
             $_SESSION['REBUILD_INDEX_ERROR'] = $GLOBALS['TL_LANG']['tl_maintenance']['noSearchable'];
             $this->redirect($this->getReferer());
         }
         // Truncate the search tables
         $this->import('Automator');
         $this->Automator->purgeSearchTables();
         // Hide unpublished elements
         $this->setCookie('FE_PREVIEW', 0, $time - 86400);
         // Calculate the hash
         $strHash = $this->getSessionHash('FE_USER_AUTH');
         // Remove old sessions
         $this->Database->prepare("DELETE FROM tl_session WHERE tstamp<? OR hash=?")->execute($time - \Config::get('sessionTimeout'), $strHash);
         // Log in the front end user
         if (is_numeric(\Input::get('user')) && \Input::get('user') > 0) {
             // Insert a new session
             $this->Database->prepare("INSERT INTO tl_session (pid, tstamp, name, sessionID, ip, hash) VALUES (?, ?, ?, ?, ?, ?)")->execute(\Input::get('user'), $time, 'FE_USER_AUTH', \System::getContainer()->get('session')->getId(), \Environment::get('ip'), $strHash);
             // Set the cookie
             $this->setCookie('FE_USER_AUTH', $strHash, $time + \Config::get('sessionTimeout'), null, null, false, true);
         } else {
             // Unset the cookies
             $this->setCookie('FE_USER_AUTH', $strHash, $time - 86400, null, null, false, true);
             $this->setCookie('FE_AUTO_LOGIN', \Input::cookie('FE_AUTO_LOGIN'), $time - 86400, null, null, false, true);
         }
         $strBuffer = '';
         $rand = rand();
         // Display the pages
         for ($i = 0, $c = count($arrPages); $i < $c; $i++) {
             $strBuffer .= '<span class="page_url" data-url="' . $arrPages[$i] . '#' . $rand . $i . '">' . \StringUtil::substr($arrPages[$i], 100) . '</span><br>';
             unset($arrPages[$i]);
             // see #5681
         }
         $objTemplate->content = $strBuffer;
         $objTemplate->note = $GLOBALS['TL_LANG']['tl_maintenance']['indexNote'];
         $objTemplate->loading = $GLOBALS['TL_LANG']['tl_maintenance']['indexLoading'];
         $objTemplate->complete = $GLOBALS['TL_LANG']['tl_maintenance']['indexComplete'];
         $objTemplate->indexContinue = $GLOBALS['TL_LANG']['MSC']['continue'];
         $objTemplate->theme = \Backend::getTheme();
         $objTemplate->isRunning = true;
         return $objTemplate->parse();
     }
     $arrUser = array('' => '-');
     // Get active front end users
     $objUser = $this->Database->execute("SELECT id, username FROM tl_member WHERE disable!='1' AND (start='' OR start<='{$time}') AND (stop='' OR stop>'" . ($time + 60) . "') ORDER BY username");
     while ($objUser->next()) {
         $arrUser[$objUser->id] = $objUser->username . ' (' . $objUser->id . ')';
     }
     // Default variables
     $objTemplate->user = $arrUser;
     $objTemplate->indexLabel = $GLOBALS['TL_LANG']['tl_maintenance']['frontendUser'][0];
     $objTemplate->indexHelp = \Config::get('showHelp') && strlen($GLOBALS['TL_LANG']['tl_maintenance']['frontendUser'][1]) ? $GLOBALS['TL_LANG']['tl_maintenance']['frontendUser'][1] : '';
     $objTemplate->indexSubmit = $GLOBALS['TL_LANG']['tl_maintenance']['indexSubmit'];
     return $objTemplate->parse();
 }
Esempio n. 9
0
 /**
  * Output the template file
  *
  * @return Response
  */
 protected function output()
 {
     // Default headline
     if ($this->Template->headline == '') {
         $this->Template->headline = \Config::get('websiteTitle');
     }
     // Default title
     if ($this->Template->title == '') {
         $this->Template->title = $this->Template->headline;
     }
     /** @var SessionInterface $objSession */
     $objSession = \System::getContainer()->get('session');
     // File picker reference
     if (\Input::get('popup') && \Input::get('act') != 'show' && (\Input::get('do') == 'page' || \Input::get('do') == 'files') && $objSession->get('filePickerRef')) {
         $this->Template->managerHref = ampersand($objSession->get('filePickerRef'));
         $this->Template->manager = strpos($objSession->get('filePickerRef'), 'contao/page?') !== false ? $GLOBALS['TL_LANG']['MSC']['pagePickerHome'] : $GLOBALS['TL_LANG']['MSC']['filePickerHome'];
     }
     // Website title
     if (\Config::get('websiteTitle') != 'Contao Open Source CMS') {
         $this->Template->websiteTitle = \Config::get('websiteTitle');
     }
     $this->Template->theme = \Backend::getTheme();
     $this->Template->base = \Environment::get('base');
     $this->Template->language = $GLOBALS['TL_LANGUAGE'];
     $this->Template->title = \StringUtil::specialchars($this->Template->title);
     $this->Template->charset = \Config::get('characterSet');
     $this->Template->account = $GLOBALS['TL_LANG']['MOD']['login'][1];
     $this->Template->preview = $GLOBALS['TL_LANG']['MSC']['fePreview'];
     $this->Template->previewTitle = \StringUtil::specialchars($GLOBALS['TL_LANG']['MSC']['fePreviewTitle']);
     $this->Template->pageOffset = \Input::cookie('BE_PAGE_OFFSET');
     $this->Template->logout = $GLOBALS['TL_LANG']['MSC']['logoutBT'];
     $this->Template->logoutTitle = \StringUtil::specialchars($GLOBALS['TL_LANG']['MSC']['logoutBTTitle']);
     $this->Template->backendModules = $GLOBALS['TL_LANG']['MSC']['backendModules'];
     $this->Template->username = $GLOBALS['TL_LANG']['MSC']['user'] . ' ' . $GLOBALS['TL_USERNAME'];
     $this->Template->skipNavigation = \StringUtil::specialchars($GLOBALS['TL_LANG']['MSC']['skipNavigation']);
     $this->Template->request = ampersand(\Environment::get('request'));
     $this->Template->top = $GLOBALS['TL_LANG']['MSC']['backToTop'];
     $this->Template->modules = $this->User->navigation();
     $this->Template->home = $GLOBALS['TL_LANG']['MSC']['home'];
     $this->Template->homeTitle = $GLOBALS['TL_LANG']['MSC']['homeTitle'];
     $this->Template->backToTop = \StringUtil::specialchars($GLOBALS['TL_LANG']['MSC']['backToTopTitle']);
     $this->Template->expandNode = $GLOBALS['TL_LANG']['MSC']['expandNode'];
     $this->Template->collapseNode = $GLOBALS['TL_LANG']['MSC']['collapseNode'];
     $this->Template->loadingData = $GLOBALS['TL_LANG']['MSC']['loadingData'];
     $this->Template->isPopup = \Input::get('popup');
     $this->Template->systemMessages = $GLOBALS['TL_LANG']['MSC']['systemMessages'];
     $strSystemMessages = \Backend::getSystemMessages();
     $this->Template->systemMessagesCount = substr_count($strSystemMessages, 'class="tl_');
     $this->Template->systemErrorMessagesCount = substr_count($strSystemMessages, 'class="tl_error"');
     // Front end preview links
     if (defined('CURRENT_ID') && CURRENT_ID != '') {
         if (\Input::get('do') == 'page') {
             $this->Template->frontendFile = '?page=' . CURRENT_ID;
         } elseif (\Input::get('do') == 'article' && ($objArticle = \ArticleModel::findByPk(CURRENT_ID)) !== null) {
             $this->Template->frontendFile = '?page=' . $objArticle->pid;
         } elseif (\Input::get('do') != '') {
             $event = new PreviewUrlCreateEvent(\Input::get('do'), CURRENT_ID);
             \System::getContainer()->get('event_dispatcher')->dispatch(ContaoCoreEvents::PREVIEW_URL_CREATE, $event);
             if (($strQuery = $event->getQuery()) !== null) {
                 $this->Template->frontendFile = '?' . $strQuery;
             }
         }
     }
     return $this->Template->getResponse();
 }
Esempio n. 10
0
 /**
  * @return string
  */
 protected function getUserID()
 {
     $hash = Input::cookie('BE_USER_AUTH');
     $id = '0';
     if (isset($hash) && $hash != '') {
         $sessionDB = $this->Database->prepare('SELECT * FROM tl_session WHERE hash = ?')->execute($hash);
         if ($sessionDB->count() > 0) {
             $id = $sessionDB->row()['pid'];
         }
     }
     return $id;
 }
Esempio n. 11
0
 /**
  * Check whether a back end or front end user is logged in
  *
  * @param string $strCookie
  *
  * @return boolean
  */
 protected function getLoginStatus($strCookie)
 {
     $cookie = \Input::cookie($strCookie);
     if ($cookie === null) {
         return false;
     }
     $hash = $this->getSessionHash($strCookie);
     // Validate the cookie hash
     if ($cookie == $hash) {
         // Try to find the session
         $objSession = \SessionModel::findByHashAndName($hash, $strCookie);
         // Validate the session ID and timeout
         if ($objSession !== null && $objSession->sessionID == \System::getContainer()->get('session')->getId() && (\System::getContainer()->getParameter('contao.security.disable_ip_check') || $objSession->ip == \Environment::get('ip')) && $objSession->tstamp + \Config::get('sessionTimeout') > time()) {
             // Disable the cache if a back end user is logged in
             if (TL_MODE == 'FE' && $strCookie == 'BE_USER_AUTH') {
                 $_SESSION['DISABLE_CACHE'] = true;
                 // Always return false if we are not in preview mode (show hidden elements)
                 if (!\Input::cookie('FE_PREVIEW')) {
                     return false;
                 }
             }
             // The session could be verified
             return true;
         }
     }
     // Reset the cache settings
     if (TL_MODE == 'FE' && $strCookie == 'BE_USER_AUTH') {
         $_SESSION['DISABLE_CACHE'] = false;
     }
     // Remove the cookie if it is invalid to enable loading cached pages
     $this->setCookie($strCookie, $hash, time() - 86400, null, null, \Environment::get('ssl'), true);
     return false;
 }
Esempio n. 12
0
 /**
  * Remove the authentication cookie and destroy the current session
  *
  * @return boolean True if the user could be logged out
  */
 public function logout()
 {
     // Return if the user has been logged out already
     if (!\Input::cookie($this->strCookie)) {
         return false;
     }
     $intUserid = null;
     // Find the session
     $objSession = $this->Database->prepare("SELECT * FROM tl_session WHERE hash=?")->limit(1)->execute($this->strHash);
     if ($objSession->numRows) {
         $this->strIp = $objSession->ip;
         $this->strHash = $objSession->hash;
         $intUserid = $objSession->pid;
     }
     $time = time();
     // Remove the session from the database
     $this->Database->prepare("DELETE FROM tl_session WHERE hash=?")->execute($this->strHash);
     // Remove cookie and hash
     $this->setCookie($this->strCookie, $this->strHash, $time - 86400, null, null, false, true);
     $this->strHash = '';
     \System::getContainer()->get('session')->invalidate();
     \System::getContainer()->get('security.token_storage')->setToken(null);
     // Add a log entry
     if ($this->findBy('id', $intUserid) != false) {
         $GLOBALS['TL_USERNAME'] = $this->username;
         $this->log('User "' . $this->username . '" has logged out', __METHOD__, TL_ACCESS);
     }
     // HOOK: post logout callback
     if (isset($GLOBALS['TL_HOOKS']['postLogout']) && is_array($GLOBALS['TL_HOOKS']['postLogout'])) {
         foreach ($GLOBALS['TL_HOOKS']['postLogout'] as $callback) {
             $this->import($callback[0], 'objLogout', true);
             $this->objLogout->{$callback[1]}($this);
         }
     }
     return true;
 }
Esempio n. 13
0
 /**
  * Output the template file
  *
  * @return Response
  */
 protected function output()
 {
     // Default headline
     if ($this->Template->headline == '') {
         $this->Template->headline = \Config::get('websiteTitle');
     }
     // Default title
     if ($this->Template->title == '') {
         $this->Template->title = $this->Template->headline;
     }
     /** @var SessionInterface $objSession */
     $objSession = \System::getContainer()->get('session');
     // File picker reference
     if (\Input::get('popup') && \Input::get('act') != 'show' && (\Input::get('do') == 'page' || \Input::get('do') == 'files') && $objSession->get('filePickerRef')) {
         $this->Template->managerHref = ampersand($this->Session->get('filePickerRef'));
         $this->Template->manager = strpos($objSession->get('filePickerRef'), 'contao/page?') !== false ? $GLOBALS['TL_LANG']['MSC']['pagePickerHome'] : $GLOBALS['TL_LANG']['MSC']['filePickerHome'];
     }
     $this->Template->theme = \Backend::getTheme();
     $this->Template->base = \Environment::get('base');
     $this->Template->language = $GLOBALS['TL_LANGUAGE'];
     $this->Template->title = specialchars($this->Template->title);
     $this->Template->charset = \Config::get('characterSet');
     $this->Template->account = $GLOBALS['TL_LANG']['MOD']['login'][1];
     $this->Template->preview = $GLOBALS['TL_LANG']['MSC']['fePreview'];
     $this->Template->previewTitle = specialchars($GLOBALS['TL_LANG']['MSC']['fePreviewTitle']);
     $this->Template->pageOffset = \Input::cookie('BE_PAGE_OFFSET');
     $this->Template->logout = $GLOBALS['TL_LANG']['MSC']['logoutBT'];
     $this->Template->logoutTitle = specialchars($GLOBALS['TL_LANG']['MSC']['logoutBTTitle']);
     $this->Template->backendModules = $GLOBALS['TL_LANG']['MSC']['backendModules'];
     $this->Template->username = $GLOBALS['TL_LANG']['MSC']['user'] . ' ' . $GLOBALS['TL_USERNAME'];
     $this->Template->skipNavigation = specialchars($GLOBALS['TL_LANG']['MSC']['skipNavigation']);
     $this->Template->request = ampersand(\Environment::get('request'));
     $this->Template->top = $GLOBALS['TL_LANG']['MSC']['backToTop'];
     $this->Template->modules = $this->User->navigation();
     $this->Template->home = $GLOBALS['TL_LANG']['MSC']['home'];
     $this->Template->homeTitle = $GLOBALS['TL_LANG']['MSC']['homeTitle'];
     $this->Template->backToTop = specialchars($GLOBALS['TL_LANG']['MSC']['backToTopTitle']);
     $this->Template->expandNode = $GLOBALS['TL_LANG']['MSC']['expandNode'];
     $this->Template->collapseNode = $GLOBALS['TL_LANG']['MSC']['collapseNode'];
     $this->Template->loadingData = $GLOBALS['TL_LANG']['MSC']['loadingData'];
     $this->Template->loadFonts = \Config::get('loadGoogleFonts');
     $this->Template->isAdmin = $this->User->isAdmin;
     $this->Template->isMaintenanceMode = \Config::get('maintenanceMode');
     $this->Template->maintenanceMode = $GLOBALS['TL_LANG']['MSC']['maintenanceMode'];
     $this->Template->maintenanceOff = specialchars($GLOBALS['TL_LANG']['MSC']['maintenanceOff']);
     $this->Template->maintenanceHref = $this->addToUrl('mmo=1');
     $this->Template->buildCacheLink = $GLOBALS['TL_LANG']['MSC']['buildCacheLink'];
     $this->Template->buildCacheText = sprintf($GLOBALS['TL_LANG']['MSC']['buildCacheText'], \System::getContainer()->getParameter('kernel.environment'));
     $this->Template->buildCacheHref = $this->addToUrl('bic=1');
     $this->Template->needsCacheBuild = !is_dir(\System::getContainer()->getParameter('kernel.cache_dir') . '/contao/sql');
     $this->Template->isPopup = \Input::get('popup');
     // Front end preview links
     if (defined('CURRENT_ID') && CURRENT_ID != '') {
         // Pages
         if (\Input::get('do') == 'page') {
             $this->Template->frontendFile = '?page=' . CURRENT_ID;
         } elseif (\Input::get('do') == 'article') {
             if (($objArticle = \ArticleModel::findByPk(CURRENT_ID)) !== null) {
                 $this->Template->frontendFile = '?page=' . $objArticle->pid;
             }
         }
     }
     return $this->Template->getResponse();
 }
Esempio n. 14
0
 /**
  * Replace insert tags with their values
  *
  * @param string  $strBuffer The text with the tags to be replaced
  * @param boolean $blnCache  If false, non-cacheable tags will be replaced
  *
  * @return string The text with the replaced tags
  */
 protected function doReplace($strBuffer, $blnCache)
 {
     /** @var PageModel $objPage */
     global $objPage;
     // Preserve insert tags
     if (\Config::get('disableInsertTags')) {
         return \StringUtil::restoreBasicEntities($strBuffer);
     }
     $tags = preg_split('/{{([^{}]+)}}/', $strBuffer, -1, PREG_SPLIT_DELIM_CAPTURE);
     if (count($tags) < 2) {
         return \StringUtil::restoreBasicEntities($strBuffer);
     }
     $strBuffer = '';
     // Create one cache per cache setting (see #7700)
     static $arrItCache;
     $arrCache =& $arrItCache[$blnCache];
     for ($_rit = 0, $_cnt = count($tags); $_rit < $_cnt; $_rit += 2) {
         $strBuffer .= $tags[$_rit];
         $strTag = $tags[$_rit + 1];
         // Skip empty tags
         if ($strTag == '') {
             continue;
         }
         $flags = explode('|', $strTag);
         $tag = array_shift($flags);
         $elements = explode('::', $tag);
         // Load the value from cache
         if (isset($arrCache[$strTag]) && !in_array('refresh', $flags)) {
             $strBuffer .= $arrCache[$strTag];
             continue;
         }
         // Skip certain elements if the output will be cached
         if ($blnCache) {
             if ($elements[0] == 'date' || $elements[0] == 'ua' || $elements[0] == 'post' || $elements[0] == 'file' && !\Validator::isStringUuid($elements[1]) || $elements[1] == 'back' || $elements[1] == 'referer' || $elements[0] == 'request_token' || $elements[0] == 'toggle_view' || strncmp($elements[0], 'cache_', 6) === 0 || in_array('uncached', $flags)) {
                 /** @var FragmentHandler $fragmentHandler */
                 $fragmentHandler = \System::getContainer()->get('fragment.handler');
                 $strBuffer .= $fragmentHandler->render(new ControllerReference('contao.controller.insert_tags:renderAction', ['insertTag' => '{{' . $strTag . '}}']), 'esi');
                 continue;
             }
         }
         $arrCache[$strTag] = '';
         // Replace the tag
         switch (strtolower($elements[0])) {
             // Date
             case 'date':
                 $arrCache[$strTag] = \Date::parse($elements[1] ?: \Config::get('dateFormat'));
                 break;
                 // Accessibility tags
             // Accessibility tags
             case 'lang':
                 if ($elements[1] == '') {
                     $arrCache[$strTag] = '</span>';
                 } else {
                     $arrCache[$strTag] = $arrCache[$strTag] = '<span lang="' . \StringUtil::specialchars($elements[1]) . '">';
                 }
                 break;
                 // Line break
             // Line break
             case 'br':
                 $arrCache[$strTag] = '<br>';
                 break;
                 // E-mail addresses
             // E-mail addresses
             case 'email':
             case 'email_open':
             case 'email_url':
                 if ($elements[1] == '') {
                     $arrCache[$strTag] = '';
                     break;
                 }
                 $strEmail = \StringUtil::encodeEmail($elements[1]);
                 // Replace the tag
                 switch (strtolower($elements[0])) {
                     case 'email':
                         $arrCache[$strTag] = '<a href="&#109;&#97;&#105;&#108;&#116;&#111;&#58;' . $strEmail . '" class="email">' . preg_replace('/\\?.*$/', '', $strEmail) . '</a>';
                         break;
                     case 'email_open':
                         $arrCache[$strTag] = '<a href="&#109;&#97;&#105;&#108;&#116;&#111;&#58;' . $strEmail . '" title="' . $strEmail . '" class="email">';
                         break;
                     case 'email_url':
                         $arrCache[$strTag] = $strEmail;
                         break;
                 }
                 break;
                 // Label tags
             // Label tags
             case 'label':
                 $keys = explode(':', $elements[1]);
                 if (count($keys) < 2) {
                     $arrCache[$strTag] = '';
                     break;
                 }
                 $file = $keys[0];
                 // Map the key (see #7217)
                 switch ($file) {
                     case 'CNT':
                         $file = 'countries';
                         break;
                     case 'LNG':
                         $file = 'languages';
                         break;
                     case 'MOD':
                     case 'FMD':
                         $file = 'modules';
                         break;
                     case 'FFL':
                         $file = 'tl_form_field';
                         break;
                     case 'CACHE':
                         $file = 'tl_page';
                         break;
                     case 'XPL':
                         $file = 'explain';
                         break;
                     case 'XPT':
                         $file = 'exception';
                         break;
                     case 'MSC':
                     case 'ERR':
                     case 'CTE':
                     case 'PTY':
                     case 'FOP':
                     case 'CHMOD':
                     case 'DAYS':
                     case 'MONTHS':
                     case 'UNITS':
                     case 'CONFIRM':
                     case 'DP':
                     case 'COLS':
                         $file = 'default';
                         break;
                 }
                 \System::loadLanguageFile($file);
                 if (count($keys) == 2) {
                     $arrCache[$strTag] = $GLOBALS['TL_LANG'][$keys[0]][$keys[1]];
                 } else {
                     $arrCache[$strTag] = $GLOBALS['TL_LANG'][$keys[0]][$keys[1]][$keys[2]];
                 }
                 break;
                 // Front end user
             // Front end user
             case 'user':
                 if (FE_USER_LOGGED_IN) {
                     $this->import('FrontendUser', 'User');
                     $value = $this->User->{$elements[1]};
                     if ($value == '') {
                         $arrCache[$strTag] = $value;
                         break;
                     }
                     $this->loadDataContainer('tl_member');
                     if ($GLOBALS['TL_DCA']['tl_member']['fields'][$elements[1]]['inputType'] == 'password') {
                         $arrCache[$strTag] = '';
                         break;
                     }
                     $value = \StringUtil::deserialize($value);
                     // Decrypt the value
                     if ($GLOBALS['TL_DCA']['tl_member']['fields'][$elements[1]]['eval']['encrypt']) {
                         $value = \Encryption::decrypt($value);
                     }
                     $rgxp = $GLOBALS['TL_DCA']['tl_member']['fields'][$elements[1]]['eval']['rgxp'];
                     $opts = $GLOBALS['TL_DCA']['tl_member']['fields'][$elements[1]]['options'];
                     $rfrc = $GLOBALS['TL_DCA']['tl_member']['fields'][$elements[1]]['reference'];
                     if ($rgxp == 'date') {
                         $arrCache[$strTag] = \Date::parse(\Config::get('dateFormat'), $value);
                     } elseif ($rgxp == 'time') {
                         $arrCache[$strTag] = \Date::parse(\Config::get('timeFormat'), $value);
                     } elseif ($rgxp == 'datim') {
                         $arrCache[$strTag] = \Date::parse(\Config::get('datimFormat'), $value);
                     } elseif (is_array($value)) {
                         $arrCache[$strTag] = implode(', ', $value);
                     } elseif (is_array($opts) && array_is_assoc($opts)) {
                         $arrCache[$strTag] = isset($opts[$value]) ? $opts[$value] : $value;
                     } elseif (is_array($rfrc)) {
                         $arrCache[$strTag] = isset($rfrc[$value]) ? is_array($rfrc[$value]) ? $rfrc[$value][0] : $rfrc[$value] : $value;
                     } else {
                         $arrCache[$strTag] = $value;
                     }
                     // Convert special characters (see #1890)
                     $arrCache[$strTag] = \StringUtil::specialchars($arrCache[$strTag]);
                 }
                 break;
                 // Link
             // Link
             case 'link':
             case 'link_open':
             case 'link_url':
             case 'link_title':
             case 'link_target':
             case 'link_name':
                 $strTarget = null;
                 // Back link
                 if ($elements[1] == 'back') {
                     $strUrl = 'javascript:history.go(-1)';
                     $strTitle = $GLOBALS['TL_LANG']['MSC']['goBack'];
                     // No language files if the page is cached
                     if (!strlen($strTitle)) {
                         $strTitle = 'Go back';
                     }
                     $strName = $strTitle;
                 } elseif (strncmp($elements[1], 'http://', 7) === 0 || strncmp($elements[1], 'https://', 8) === 0) {
                     $strUrl = $elements[1];
                     $strTitle = $elements[1];
                     $strName = str_replace(array('http://', 'https://'), '', $elements[1]);
                 } else {
                     // User login page
                     if ($elements[1] == 'login') {
                         if (!FE_USER_LOGGED_IN) {
                             break;
                         }
                         $this->import('FrontendUser', 'User');
                         $elements[1] = $this->User->loginPage;
                     }
                     $objNextPage = \PageModel::findByIdOrAlias($elements[1]);
                     if ($objNextPage === null) {
                         break;
                     }
                     // Page type specific settings (thanks to Andreas Schempp)
                     switch ($objNextPage->type) {
                         case 'redirect':
                             $strUrl = $objNextPage->url;
                             if (strncasecmp($strUrl, 'mailto:', 7) === 0) {
                                 $strUrl = \StringUtil::encodeEmail($strUrl);
                             }
                             break;
                         case 'forward':
                             if ($objNextPage->jumpTo) {
                                 /** @var PageModel $objNext */
                                 $objNext = $objNextPage->getRelated('jumpTo');
                             } else {
                                 $objNext = \PageModel::findFirstPublishedRegularByPid($objNextPage->id);
                             }
                             if ($objNext instanceof PageModel) {
                                 $strUrl = $objNext->getFrontendUrl();
                                 break;
                             }
                             // DO NOT ADD A break; STATEMENT
                         // DO NOT ADD A break; STATEMENT
                         default:
                             $strUrl = $objNextPage->getFrontendUrl();
                             break;
                     }
                     $strName = $objNextPage->title;
                     $strTarget = $objNextPage->target ? ' target="_blank"' : '';
                     $strTitle = $objNextPage->pageTitle ?: $objNextPage->title;
                 }
                 // Replace the tag
                 switch (strtolower($elements[0])) {
                     case 'link':
                         $arrCache[$strTag] = sprintf('<a href="%s" title="%s"%s>%s</a>', $strUrl, \StringUtil::specialchars($strTitle), $strTarget, $strName);
                         break;
                     case 'link_open':
                         $arrCache[$strTag] = sprintf('<a href="%s" title="%s"%s>', $strUrl, \StringUtil::specialchars($strTitle), $strTarget);
                         break;
                     case 'link_url':
                         $arrCache[$strTag] = $strUrl;
                         break;
                     case 'link_title':
                         $arrCache[$strTag] = \StringUtil::specialchars($strTitle);
                         break;
                     case 'link_target':
                         $arrCache[$strTag] = $strTarget;
                         break;
                     case 'link_name':
                         $arrCache[$strTag] = $strName;
                         break;
                 }
                 break;
                 // Closing link tag
             // Closing link tag
             case 'link_close':
             case 'email_close':
                 $arrCache[$strTag] = '</a>';
                 break;
                 // Insert article
             // Insert article
             case 'insert_article':
                 if (($strOutput = $this->getArticle($elements[1], false, true)) !== false) {
                     $arrCache[$strTag] = ltrim($strOutput);
                 } else {
                     $arrCache[$strTag] = '<p class="error">' . sprintf($GLOBALS['TL_LANG']['MSC']['invalidPage'], $elements[1]) . '</p>';
                 }
                 break;
                 // Insert content element
             // Insert content element
             case 'insert_content':
                 $arrCache[$strTag] = $this->getContentElement($elements[1]);
                 break;
                 // Insert module
             // Insert module
             case 'insert_module':
                 $arrCache[$strTag] = $this->getFrontendModule($elements[1]);
                 break;
                 // Insert form
             // Insert form
             case 'insert_form':
                 $arrCache[$strTag] = $this->getForm($elements[1]);
                 break;
                 // Article
             // Article
             case 'article':
             case 'article_open':
             case 'article_url':
             case 'article_title':
                 if (($objArticle = \ArticleModel::findByIdOrAlias($elements[1])) === null || !($objPid = $objArticle->getRelated('pid')) instanceof PageModel) {
                     break;
                 }
                 /** @var PageModel $objPid */
                 $strUrl = $objPid->getFrontendUrl('/articles/' . ($objArticle->alias ?: $objArticle->id));
                 // Replace the tag
                 switch (strtolower($elements[0])) {
                     case 'article':
                         $arrCache[$strTag] = sprintf('<a href="%s" title="%s">%s</a>', $strUrl, \StringUtil::specialchars($objArticle->title), $objArticle->title);
                         break;
                     case 'article_open':
                         $arrCache[$strTag] = sprintf('<a href="%s" title="%s">', $strUrl, \StringUtil::specialchars($objArticle->title));
                         break;
                     case 'article_url':
                         $arrCache[$strTag] = $strUrl;
                         break;
                     case 'article_title':
                         $arrCache[$strTag] = \StringUtil::specialchars($objArticle->title);
                         break;
                 }
                 break;
                 // Article teaser
             // Article teaser
             case 'article_teaser':
                 $objTeaser = \ArticleModel::findByIdOrAlias($elements[1]);
                 if ($objTeaser !== null) {
                     $arrCache[$strTag] = \StringUtil::toHtml5($objTeaser->teaser);
                 }
                 break;
                 // Last update
             // Last update
             case 'last_update':
                 $strQuery = "SELECT MAX(tstamp) AS tc";
                 $bundles = \System::getContainer()->getParameter('kernel.bundles');
                 if (isset($bundles['ContaoNewsBundle'])) {
                     $strQuery .= ", (SELECT MAX(tstamp) FROM tl_news) AS tn";
                 }
                 if (isset($bundles['ContaoCalendarBundle'])) {
                     $strQuery .= ", (SELECT MAX(tstamp) FROM tl_calendar_events) AS te";
                 }
                 $strQuery .= " FROM tl_content";
                 $objUpdate = \Database::getInstance()->query($strQuery);
                 if ($objUpdate->numRows) {
                     $arrCache[$strTag] = \Date::parse($elements[1] ?: \Config::get('datimFormat'), max($objUpdate->tc, $objUpdate->tn, $objUpdate->te));
                 }
                 break;
                 // Version
             // Version
             case 'version':
                 $arrCache[$strTag] = VERSION . '.' . BUILD;
                 break;
                 // Request token
             // Request token
             case 'request_token':
                 $arrCache[$strTag] = REQUEST_TOKEN;
                 break;
                 // POST data
             // POST data
             case 'post':
                 $arrCache[$strTag] = \Input::post($elements[1]);
                 break;
                 // Mobile/desktop toggle (see #6469)
             // Mobile/desktop toggle (see #6469)
             case 'toggle_view':
                 $strUrl = ampersand(\Environment::get('request'));
                 $strGlue = strpos($strUrl, '?') === false ? '?' : '&amp;';
                 if (\Input::cookie('TL_VIEW') == 'mobile' || \Environment::get('agent')->mobile && \Input::cookie('TL_VIEW') != 'desktop') {
                     $arrCache[$strTag] = '<a href="' . $strUrl . $strGlue . 'toggle_view=desktop" class="toggle_desktop" title="' . \StringUtil::specialchars($GLOBALS['TL_LANG']['MSC']['toggleDesktop'][1]) . '">' . $GLOBALS['TL_LANG']['MSC']['toggleDesktop'][0] . '</a>';
                 } else {
                     $arrCache[$strTag] = '<a href="' . $strUrl . $strGlue . 'toggle_view=mobile" class="toggle_mobile" title="' . \StringUtil::specialchars($GLOBALS['TL_LANG']['MSC']['toggleMobile'][1]) . '">' . $GLOBALS['TL_LANG']['MSC']['toggleMobile'][0] . '</a>';
                 }
                 break;
                 // Conditional tags (if)
             // Conditional tags (if)
             case 'iflng':
                 if ($elements[1] != '' && $elements[1] != $objPage->language) {
                     for (; $_rit < $_cnt; $_rit += 2) {
                         if ($tags[$_rit + 1] == 'iflng' || $tags[$_rit + 1] == 'iflng::' . $objPage->language) {
                             break;
                         }
                     }
                 }
                 unset($arrCache[$strTag]);
                 break;
                 // Conditional tags (if not)
             // Conditional tags (if not)
             case 'ifnlng':
                 if ($elements[1] != '') {
                     $langs = \StringUtil::trimsplit(',', $elements[1]);
                     if (in_array($objPage->language, $langs)) {
                         for (; $_rit < $_cnt; $_rit += 2) {
                             if ($tags[$_rit + 1] == 'ifnlng') {
                                 break;
                             }
                         }
                     }
                 }
                 unset($arrCache[$strTag]);
                 break;
                 // Environment
             // Environment
             case 'env':
                 switch ($elements[1]) {
                     case 'host':
                         $arrCache[$strTag] = \Idna::decode(\Environment::get('host'));
                         break;
                     case 'http_host':
                         $arrCache[$strTag] = \Idna::decode(\Environment::get('httpHost'));
                         break;
                     case 'url':
                         $arrCache[$strTag] = \Idna::decode(\Environment::get('url'));
                         break;
                     case 'path':
                         $arrCache[$strTag] = \Idna::decode(\Environment::get('base'));
                         break;
                     case 'request':
                         $arrCache[$strTag] = \Environment::get('indexFreeRequest');
                         break;
                     case 'ip':
                         $arrCache[$strTag] = \Environment::get('ip');
                         break;
                     case 'referer':
                         $arrCache[$strTag] = $this->getReferer(true);
                         break;
                     case 'files_url':
                         $arrCache[$strTag] = TL_FILES_URL;
                         break;
                     case 'assets_url':
                     case 'plugins_url':
                     case 'script_url':
                         $arrCache[$strTag] = TL_ASSETS_URL;
                         break;
                     case 'base_url':
                         $arrCache[$strTag] = \System::getContainer()->get('request_stack')->getCurrentRequest()->getBaseUrl();
                         break;
                 }
                 break;
                 // Page
             // Page
             case 'page':
                 if ($elements[1] == 'pageTitle' && $objPage->pageTitle == '') {
                     $elements[1] = 'title';
                 } elseif ($elements[1] == 'parentPageTitle' && $objPage->parentPageTitle == '') {
                     $elements[1] = 'parentTitle';
                 } elseif ($elements[1] == 'mainPageTitle' && $objPage->mainPageTitle == '') {
                     $elements[1] = 'mainTitle';
                 }
                 // Do not use \StringUtil::specialchars() here (see #4687)
                 $arrCache[$strTag] = $objPage->{$elements[1]};
                 break;
                 // User agent
             // User agent
             case 'ua':
                 $ua = \Environment::get('agent');
                 if ($elements[1] != '') {
                     $arrCache[$strTag] = $ua->{$elements[1]};
                 } else {
                     $arrCache[$strTag] = '';
                 }
                 break;
                 // Abbreviations
             // Abbreviations
             case 'abbr':
             case 'acronym':
                 if ($elements[1] != '') {
                     $arrCache[$strTag] = '<abbr title="' . \StringUtil::specialchars($elements[1]) . '">';
                 } else {
                     $arrCache[$strTag] = '</abbr>';
                 }
                 break;
                 // Images
             // Images
             case 'image':
             case 'picture':
                 $width = null;
                 $height = null;
                 $alt = '';
                 $class = '';
                 $rel = '';
                 $strFile = $elements[1];
                 $mode = '';
                 $size = null;
                 $strTemplate = 'picture_default';
                 // Take arguments
                 if (strpos($elements[1], '?') !== false) {
                     $arrChunks = explode('?', urldecode($elements[1]), 2);
                     $strSource = \StringUtil::decodeEntities($arrChunks[1]);
                     $strSource = str_replace('[&]', '&', $strSource);
                     $arrParams = explode('&', $strSource);
                     foreach ($arrParams as $strParam) {
                         list($key, $value) = explode('=', $strParam);
                         switch ($key) {
                             case 'width':
                                 $width = $value;
                                 break;
                             case 'height':
                                 $height = $value;
                                 break;
                             case 'alt':
                                 $alt = $value;
                                 break;
                             case 'class':
                                 $class = $value;
                                 break;
                             case 'rel':
                                 $rel = $value;
                                 break;
                             case 'mode':
                                 $mode = $value;
                                 break;
                             case 'size':
                                 $size = (int) $value;
                                 break;
                             case 'template':
                                 $strTemplate = preg_replace('/[^a-z0-9_]/i', '', $value);
                                 break;
                         }
                     }
                     $strFile = $arrChunks[0];
                 }
                 if (\Validator::isUuid($strFile)) {
                     // Handle UUIDs
                     $objFile = \FilesModel::findByUuid($strFile);
                     if ($objFile === null) {
                         $arrCache[$strTag] = '';
                         break;
                     }
                     $strFile = $objFile->path;
                 } elseif (is_numeric($strFile)) {
                     // Handle numeric IDs (see #4805)
                     $objFile = \FilesModel::findByPk($strFile);
                     if ($objFile === null) {
                         $arrCache[$strTag] = '';
                         break;
                     }
                     $strFile = $objFile->path;
                 } else {
                     // Check the path
                     if (\Validator::isInsecurePath($strFile)) {
                         throw new \RuntimeException('Invalid path ' . $strFile);
                     }
                 }
                 // Check the maximum image width
                 if (\Config::get('maxImageWidth') > 0 && $width > \Config::get('maxImageWidth')) {
                     $width = \Config::get('maxImageWidth');
                     $height = null;
                 }
                 // Generate the thumbnail image
                 try {
                     // Image
                     if (strtolower($elements[0]) == 'image') {
                         $dimensions = '';
                         $src = \System::getContainer()->get('contao.image.image_factory')->create(TL_ROOT . '/' . rawurldecode($strFile), array($width, $height, $mode))->getUrl(TL_ROOT);
                         $objFile = new \File(rawurldecode($src));
                         // Add the image dimensions
                         if (($imgSize = $objFile->imageSize) !== false) {
                             $dimensions = ' width="' . \StringUtil::specialchars($imgSize[0]) . '" height="' . \StringUtil::specialchars($imgSize[1]) . '"';
                         }
                         $arrCache[$strTag] = '<img src="' . TL_FILES_URL . $src . '" ' . $dimensions . ' alt="' . \StringUtil::specialchars($alt) . '"' . ($class != '' ? ' class="' . \StringUtil::specialchars($class) . '"' : '') . '>';
                     } else {
                         $picture = \System::getContainer()->get('contao.image.picture_factory')->create(TL_ROOT . '/' . $strFile, $size);
                         $picture = array('img' => $picture->getImg(TL_ROOT), 'sources' => $picture->getSources(TL_ROOT));
                         $picture['alt'] = $alt;
                         $picture['class'] = $class;
                         $pictureTemplate = new \FrontendTemplate($strTemplate);
                         $pictureTemplate->setData($picture);
                         $arrCache[$strTag] = $pictureTemplate->parse();
                     }
                     // Add a lightbox link
                     if ($rel != '') {
                         if (strncmp($rel, 'lightbox', 8) !== 0) {
                             $attribute = ' rel="' . \StringUtil::specialchars($rel) . '"';
                         } else {
                             $attribute = ' data-lightbox="' . \StringUtil::specialchars(substr($rel, 8)) . '"';
                         }
                         $arrCache[$strTag] = '<a href="' . TL_FILES_URL . $strFile . '"' . ($alt != '' ? ' title="' . \StringUtil::specialchars($alt) . '"' : '') . $attribute . '>' . $arrCache[$strTag] . '</a>';
                     }
                 } catch (\Exception $e) {
                     $arrCache[$strTag] = '';
                 }
                 break;
                 // Files (UUID or template path)
             // Files (UUID or template path)
             case 'file':
                 if (\Validator::isUuid($elements[1])) {
                     $objFile = \FilesModel::findByUuid($elements[1]);
                     if ($objFile !== null) {
                         $arrCache[$strTag] = $objFile->path;
                         break;
                     }
                 }
                 $arrGet = $_GET;
                 \Input::resetCache();
                 $strFile = $elements[1];
                 // Take arguments and add them to the $_GET array
                 if (strpos($elements[1], '?') !== false) {
                     $arrChunks = explode('?', urldecode($elements[1]));
                     $strSource = \StringUtil::decodeEntities($arrChunks[1]);
                     $strSource = str_replace('[&]', '&', $strSource);
                     $arrParams = explode('&', $strSource);
                     foreach ($arrParams as $strParam) {
                         $arrParam = explode('=', $strParam);
                         $_GET[$arrParam[0]] = $arrParam[1];
                     }
                     $strFile = $arrChunks[0];
                 }
                 // Check the path
                 if (\Validator::isInsecurePath($strFile)) {
                     throw new \RuntimeException('Invalid path ' . $strFile);
                 }
                 // Include .php, .tpl, .xhtml and .html5 files
                 if (preg_match('/\\.(php|tpl|xhtml|html5)$/', $strFile) && file_exists(TL_ROOT . '/templates/' . $strFile)) {
                     ob_start();
                     include TL_ROOT . '/templates/' . $strFile;
                     $arrCache[$strTag] = ob_get_clean();
                 }
                 $_GET = $arrGet;
                 \Input::resetCache();
                 break;
                 // HOOK: pass unknown tags to callback functions
             // HOOK: pass unknown tags to callback functions
             default:
                 if (isset($GLOBALS['TL_HOOKS']['replaceInsertTags']) && is_array($GLOBALS['TL_HOOKS']['replaceInsertTags'])) {
                     foreach ($GLOBALS['TL_HOOKS']['replaceInsertTags'] as $callback) {
                         $this->import($callback[0]);
                         $varValue = $this->{$callback[0]}->{$callback[1]}($tag, $blnCache, $arrCache[$strTag], $flags, $tags, $arrCache, $_rit, $_cnt);
                         // see #6672
                         // Replace the tag and stop the loop
                         if ($varValue !== false) {
                             $arrCache[$strTag] = $varValue;
                             break;
                         }
                     }
                 }
                 \System::getContainer()->get('monolog.logger.contao')->log(LogLevel::INFO, 'Unknown insert tag: ' . $strTag);
                 break;
         }
         // Handle the flags
         if (!empty($flags)) {
             foreach ($flags as $flag) {
                 switch ($flag) {
                     case 'addslashes':
                     case 'standardize':
                     case 'ampersand':
                     case 'specialchars':
                     case 'nl2br':
                     case 'nl2br_pre':
                     case 'strtolower':
                     case 'utf8_strtolower':
                     case 'strtoupper':
                     case 'utf8_strtoupper':
                     case 'ucfirst':
                     case 'lcfirst':
                     case 'ucwords':
                     case 'trim':
                     case 'rtrim':
                     case 'ltrim':
                     case 'utf8_romanize':
                     case 'urlencode':
                     case 'rawurlencode':
                         $arrCache[$strTag] = $flag($arrCache[$strTag]);
                         break;
                     case 'encodeEmail':
                         $arrCache[$strTag] = \StringUtil::$flag($arrCache[$strTag]);
                         break;
                     case 'number_format':
                         $arrCache[$strTag] = \System::getFormattedNumber($arrCache[$strTag], 0);
                         break;
                     case 'currency_format':
                         $arrCache[$strTag] = \System::getFormattedNumber($arrCache[$strTag], 2);
                         break;
                     case 'readable_size':
                         $arrCache[$strTag] = \System::getReadableSize($arrCache[$strTag]);
                         break;
                     case 'flatten':
                         if (!is_array($arrCache[$strTag])) {
                             break;
                         }
                         $it = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($arrCache[$strTag]));
                         $result = array();
                         foreach ($it as $leafValue) {
                             $keys = array();
                             foreach (range(0, $it->getDepth()) as $depth) {
                                 $keys[] = $it->getSubIterator($depth)->key();
                             }
                             $result[] = implode('.', $keys) . ': ' . $leafValue;
                         }
                         $arrCache[$strTag] = implode(', ', $result);
                         break;
                         // HOOK: pass unknown flags to callback functions
                     // HOOK: pass unknown flags to callback functions
                     default:
                         if (isset($GLOBALS['TL_HOOKS']['insertTagFlags']) && is_array($GLOBALS['TL_HOOKS']['insertTagFlags'])) {
                             foreach ($GLOBALS['TL_HOOKS']['insertTagFlags'] as $callback) {
                                 $this->import($callback[0]);
                                 $varValue = $this->{$callback[0]}->{$callback[1]}($flag, $tag, $arrCache[$strTag], $flags, $blnCache, $tags, $arrCache, $_rit, $_cnt);
                                 // see #5806
                                 // Replace the tag and stop the loop
                                 if ($varValue !== false) {
                                     $arrCache[$strTag] = $varValue;
                                     break;
                                 }
                             }
                         }
                         \System::getContainer()->get('monolog.logger.contao')->log(LogLevel::INFO, 'Unknown insert tag flag: ' . $flag);
                         break;
                 }
             }
         }
         $strBuffer .= $arrCache[$strTag];
     }
     return \StringUtil::restoreBasicEntities($strBuffer);
 }
Esempio n. 15
0
 /**
  * Check whether there is an authenticated back end user
  *
  * @return boolean True if there is an authenticated back end user
  */
 public function hasAuthenticatedBackendUser()
 {
     if (!isset($_COOKIE['BE_USER_AUTH'])) {
         return false;
     }
     return Input::cookie('BE_USER_AUTH') == $this->getSessionHash('BE_USER_AUTH');
 }
Esempio n. 16
0
 /**
  * Output the template file and exit
  */
 protected function outputAndExit()
 {
     $this->Template->theme = \Backend::getTheme();
     $this->Template->base = \Environment::get('base');
     $this->Template->language = $GLOBALS['TL_LANGUAGE'];
     $this->Template->charset = \Config::get('characterSet');
     $this->Template->pageOffset = \Input::cookie('BE_PAGE_OFFSET');
     $this->Template->action = ampersand(\Environment::get('request'));
     $this->Template->noCookies = $GLOBALS['TL_LANG']['MSC']['noCookies'];
     $this->Template->title = specialchars($GLOBALS['TL_LANG']['tl_install']['installTool'][0]);
     $this->Template->expandNode = $GLOBALS['TL_LANG']['MSC']['expandNode'];
     $this->Template->collapseNode = $GLOBALS['TL_LANG']['MSC']['collapseNode'];
     $this->Template->loadingData = $GLOBALS['TL_LANG']['MSC']['loadingData'];
     $this->Template->hasComposer = is_dir(TL_ROOT . '/system/modules/!composer');
     $this->Template->output();
     exit;
 }