Example #1
0
 /**
  * Run the controller and parse the login template
  */
 public function run()
 {
     $this->Template = new BackendTemplate('be_files');
     $this->Template->main = '';
     // Ajax request
     if (Environment::get('isAjaxRequest')) {
         $this->objAjax = new Ajax(Input::post('action'));
         $this->objAjax->executePreActions();
     }
     $this->Template->main .= $this->getBackendModule('files');
     // Default headline
     if ($this->Template->headline == '') {
         $this->Template->headline = $GLOBALS['TL_CONFIG']['websiteTitle'];
     }
     $this->Template->theme = $this->getTheme();
     $this->Template->base = Environment::get('base');
     $this->Template->language = $GLOBALS['TL_LANGUAGE'];
     $this->Template->title = specialchars($GLOBALS['TL_LANG']['MSC']['filetree']);
     $this->Template->charset = $GLOBALS['TL_CONFIG']['characterSet'];
     $this->Template->pageOffset = Input::cookie('BE_PAGE_OFFSET');
     $this->Template->error = Input::get('act') == 'error' ? $GLOBALS['TL_LANG']['ERR']['general'] : '';
     $this->Template->skipNavigation = $GLOBALS['TL_LANG']['MSC']['skipNavigation'];
     $this->Template->request = ampersand(Environment::get('request'));
     $this->Template->top = $GLOBALS['TL_LANG']['MSC']['backToTop'];
     $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 = $GLOBALS['TL_CONFIG']['loadGoogleFonts'];
     $GLOBALS['TL_CONFIG']['debugMode'] = false;
     $this->Template->output();
 }
Example #2
0
 /**
  * Generate the content element
  */
 protected function compile()
 {
     $rows = deserialize($this->tableitems);
     $this->Template->id = 'table_' . $this->id;
     $this->Template->summary = specialchars($this->summary);
     $this->Template->useHeader = $this->thead ? true : false;
     $this->Template->useFooter = $this->tfoot ? true : false;
     $this->Template->useLeftTh = $this->tleft ? true : false;
     $this->Template->sortable = $this->sortable ? true : false;
     $arrHeader = array();
     $arrBody = array();
     $arrFooter = array();
     // Table header
     if ($this->thead) {
         foreach ($rows[0] as $i => $v) {
             // Set table sort cookie
             if ($this->sortable && $i == $this->sortIndex) {
                 $co = 'TS_TABLE_' . $this->id;
                 $so = $this->sortOrder == 'descending' ? 'desc' : 'asc';
                 if (\Input::cookie($co) == '') {
                     \System::setCookie($co, $i . '|' . $so, 0);
                 }
             }
             // Add cell
             $arrHeader[] = array('class' => 'head_' . $i . ($i == 0 ? ' col_first' : '') . ($i == count($rows[0]) - 1 ? ' col_last' : '') . ($i == 0 && $this->tleft ? ' unsortable' : ''), 'content' => $v != '' ? nl2br_html5($v) : ' ');
         }
         array_shift($rows);
     }
     $this->Template->header = $arrHeader;
     $limit = $this->tfoot ? count($rows) - 1 : count($rows);
     // Table body
     for ($j = 0; $j < $limit; $j++) {
         $class_tr = '';
         if ($j == 0) {
             $class_tr .= ' row_first';
         }
         if ($j == $limit - 1) {
             $class_tr .= ' row_last';
         }
         $class_eo = $j % 2 == 0 ? ' odd' : ' even';
         foreach ($rows[$j] as $i => $v) {
             $class_td = '';
             if ($i == 0) {
                 $class_td .= ' col_first';
             }
             if ($i == count($rows[$j]) - 1) {
                 $class_td .= ' col_last';
             }
             $arrBody['row_' . $j . $class_tr . $class_eo][] = array('class' => 'col_' . $i . $class_td, 'content' => $v != '' ? nl2br_html5($v) : '&nbsp;');
         }
     }
     $this->Template->body = $arrBody;
     // Table footer
     if ($this->tfoot) {
         foreach ($rows[count($rows) - 1] as $i => $v) {
             $arrFooter[] = array('class' => 'foot_' . $i . ($i == 0 ? ' col_first' : '') . ($i == count($rows[count($rows) - 1]) - 1 ? ' col_last' : ''), 'content' => $v != '' ? nl2br_html5($v) : '&nbsp;');
         }
     }
     $this->Template->footer = $arrFooter;
 }
Example #3
0
 /**
  * Class init
  *
  * Fetches CSRF settings and current token
  */
 public static function _init()
 {
     static::$csrf_token_key = \Config::get('security.csrf_token_key', 'fuel_csrf_token');
     static::$csrf_old_token = \Input::cookie(static::$csrf_token_key, false);
     if (\Config::get('security.csrf_autoload', true)) {
         static::check_token();
     }
 }
 /**
  * Resolve the user from the session.
  *
  * @return \UserModel
  *
  * @internal
  */
 public function resolveBackendUser()
 {
     if (TL_MODE == 'FE') {
         // request the BE_USER_AUTH login status
         $hash = $this->input->cookie(self::COOKIE_NAME);
         // Check the cookie hash
         if ($this->validateHash($hash)) {
             $session = $this->database->prepare("SELECT * FROM tl_session WHERE hash=? AND name=?")->execute($hash, self::COOKIE_NAME);
             // Try to find the session in the database
             if ($session->next() && $this->validateUserSession($hash, $session)) {
                 $userId = $session->pid;
                 $user = \UserModel::findByPk($userId);
                 return $user;
             }
         }
     }
     return null;
 }
Example #5
0
 /**
  * Class init
  *
  * Fetches CSRF settings and current token
  */
 public static function _init()
 {
     static::$csrf_token_key = \Config::get('security.csrf_token_key', 'fuel_csrf_token');
     static::$csrf_old_token = \Input::cookie(static::$csrf_token_key, false);
     if (\Config::get('security.csrf_autoload', true)) {
         static::check_token();
     }
     // throw an exception if no the output filter setting is missing from the app config
     if (\Config::get('security.output_filter', null) === null) {
         throw new \FuelException('There is no security.output_filter defined in your application config file');
     }
 }
 /**
  * Class init
  *
  * Fetches CSRF settings and current token
  */
 public static function _init()
 {
     static::$csrf_token_key = \Config::get('security.csrf_token_key', 'fuel_csrf_token');
     static::$csrf_old_token = \Input::cookie(static::$csrf_token_key, false);
     if (\Config::get('security.csrf_autoload', true)) {
         static::check_token();
     }
     // set a default output filter if none is defined in the config
     // this code is deprecated and will be removed in v1.2
     if (\Config::get('security.output_filter', null) === null) {
         \Config::set('security.output_filter', '\\Security::htmlentities');
         logger(\Fuel::L_WARNING, 'There is no security.output_filter defined in your application config file.', __METHOD__);
     }
 }
Example #7
0
    public function fakeLogin()
    {
        if (TL_MODE == 'FE') {
            $rootPage = $this->getRootPageFromUrl();
            if ($rootPage && is_array($GLOBALS['BROWSER_AUTH_MODULES'])) {
                foreach ($GLOBALS['BROWSER_AUTH_MODULES'] as $authModuleClass) {
                    $authModule = new $authModuleClass();
                    $member = $authModule->authenticate($rootPage);
                    if ($member) {
                        $database = \Database::getInstance();
                        $cookieName = 'FE_USER_AUTH';
                        $ip = \Environment::get('ip');
                        $time = time();
                        // Generate the cookie hash
                        $hash = sha1(session_id() . (!$GLOBALS['TL_CONFIG']['disableIpCheck'] ? $ip : '') . $cookieName);
                        if ($hash == \Input::cookie($cookieName)) {
                            $session = $database->prepare('SELECT * FROM tl_session WHERE hash=? AND name=?')->executeUncached($hash, $cookieName);
                            $update = array();
                            if ($session->numRows) {
                                // Validate the session
                                if ($session->sessionID != session_id()) {
                                    $update['sessionID'] = session_id();
                                }
                                if (!$GLOBALS['TL_CONFIG']['disableIpCheck'] && $session->ip != $ip) {
                                    $update['ip'] = $ip;
                                }
                                if ($session->hash != $hash) {
                                    $update['hash'] = $hash;
                                }
                                if ($session->tstamp + $GLOBALS['TL_CONFIG']['sessionTimeout'] < $time) {
                                    $update['tstamp'] = $time;
                                }
                                if (count($update)) {
                                    $database->prepare('UPDATE tl_session %s WHERE hash=? AND name=?')->set($update)->execute($hash, $cookieName);
                                }
                                break;
                            }
                        }
                        // fake a new session
                        $database->prepare('INSERT INTO tl_session (pid, tstamp, name, sessionID, ip, hash)
								 VALUES (?, ?, ?, ?, ?, ?)
								 ON DUPLICATE KEY UPDATE tstamp=?, name=?, sessionID=?, ip=?')->execute($member->id, $time, $cookieName, session_id(), $ip, $hash, $time, $cookieName, session_id(), $ip);
                        // fake authentication cookie
                        $this->setCookie($cookieName, $hash, $time + $GLOBALS['TL_CONFIG']['sessionTimeout'], null, null, false, true);
                        break;
                    }
                }
            }
        }
    }
 /**
  * Get the singleton instance.
  *
  * @return \ExtCSS\ExtCSS
  */
 public static function getInstance()
 {
     if (self::$instance == null) {
         self::$instance = new ExtCss();
         // remember cookie FE_PREVIEW state
         $fePreview = \Input::cookie('FE_PREVIEW');
         // set into preview mode
         \Input::setCookie('FE_PREVIEW', true);
         // request the BE_USER_AUTH login status
         static::setDesignerMode(self::$instance->getLoginStatus('BE_USER_AUTH'));
         // restore previous FE_PREVIEW state
         \Input::setCookie('FE_PREVIEW', $fePreview);
     }
     return self::$instance;
 }
Example #9
0
 /**
  * Display option field in backend login
  *
  * @param $strContent
  * @param $strTemplate
  * @return mixed
  */
 public function addServersToLoginPage($strContent, $strTemplate)
 {
     if ($strTemplate == 'be_login') {
         $template = new \BackendTemplate('mod_authclient_serverlist');
         $template->loginServers = \AuthClientServerModel::findAll();
         // TODO: Check if certificate is still valid
         // Preferred login provider
         $preferredServer = intval(\Input::cookie('cto_preferred_login_provider'));
         if ($preferredServer > 0) {
             $template->preferredServer = $preferredServer;
         } else {
             $template->preferredServer = false;
         }
         $searchString = '<table class="tl_login_table">';
         $strContent = str_replace($searchString, $searchString . $template->parse(), $strContent);
     }
     return $strContent;
 }
Example #10
0
 /**
  * Class init
  *
  * Fetches CSRF settings and current token
  */
 public static function _init()
 {
     static::$csrf_token_key = \Config::get('security.csrf_token_key', 'fuel_csrf_token');
     static::$csrf_old_token = \Input::cookie(static::$csrf_token_key, false);
     // if csrf automatic checking is enabled, and it fails validation, bail out!
     if (\Config::get('security.csrf_autoload', true)) {
         static::check_token();
     }
     // throw an exception if the output filter setting is missing from the app config
     if (\Config::get('security.output_filter', null) === null) {
         throw new \FuelException('There is no security.output_filter defined in your application config file');
     }
     // deal with duplicate filters, no need to slow the framework down
     foreach (array('output_filter', 'uri_filter', 'input_filter') as $setting) {
         $config = \Config::get('security.' . $setting, array());
         is_array($config) and \Config::set('security.' . $setting, array_keys(array_flip($config)));
     }
 }
Example #11
0
 /**
  * Register a page cache key.
  *
  * @param string $cacheKey The cache key.
  *
  * @return string
  */
 public function registerPageCacheKey($cacheKey)
 {
     global $objPage;
     // $objPage is only available when the hook is triggered by the FrontendTemplate::addToCache method.
     // If it's triggered by outputFromCache it's not available. Make use of this knowledge.
     if ($objPage) {
         $preparedKey = $cacheKey;
         if ($objPage->mobileLayout > 0) {
             if (\Input::cookie('TL_VIEW') == 'mobile' || \Environment::get('agent')->mobile && \Input::cookie('TL_VIEW') != 'desktop') {
                 // Mobile key is usually added after the hook. So add it here. See. contao/core#7826.
                 $preparedKey .= '.mobile';
             } elseif (version_compare(VERSION, '3.5', '>=')) {
                 // Contao 3.5 uses desktop suffix if mobile layout is enabled.
                 $preparedKey .= '.desktop';
             }
         }
         $this->service()->registerCacheKey($objPage->id, md5($preparedKey));
     }
     return $cacheKey;
 }
Example #12
0
 /**
  * Class init
  *
  * Fetches CSRF settings and current token
  *
  * @throws SecurityException it the CSRF token validation failed
  * @throws FuelException if no security output filter is defined
  */
 public static function _init()
 {
     static::$csrf_token_key = \Config::get('security.csrf_token_key', 'fuel_csrf_token');
     static::$csrf_old_token = \Input::cookie(static::$csrf_token_key, false);
     // if csrf automatic checking is enabled, and it fails validation, bail out!
     if (\Config::get('security.csrf_autoload', true)) {
         $check_token_methods = \Config::get('security.csrf_autoload_methods', array('post', 'put', 'delete'));
         if (in_array(strtolower(\Input::method()), $check_token_methods) and !static::check_token()) {
             throw new \SecurityException('CSRF validation failed, Possible hacking attempt detected!');
         }
     }
     // throw an exception if the output filter setting is missing from the app config
     if (\Config::get('security.output_filter', null) === null) {
         throw new \FuelException('There is no security.output_filter defined in your application config file');
     }
     // deal with duplicate filters, no need to slow the framework down
     foreach (array('output_filter', 'uri_filter', 'input_filter') as $setting) {
         $config = \Config::get('security.' . $setting, array());
         is_array($config) and \Config::set('security.' . $setting, \Arr::unique($config));
     }
 }
 protected function showTags()
 {
     $this->loadLanguageFile('tl_module');
     $strUrl = ampersand(\Environment::get('request'), ENCODE_AMPERSANDS);
     // Get target page
     $objPageObject = $this->Database->prepare("SELECT id, alias FROM tl_page WHERE id=?")->limit(1)->execute($this->tag_jumpTo);
     global $objPage;
     $default = $objPage != null ? $objPage->row() : array();
     $pageArr = $objPageObject->numRows ? $objPageObject->fetchAssoc() : $default;
     $strParams = '';
     if ($this->keep_url_params) {
         $strParams = \TagHelper::getSavedURLParams($this->Input);
     }
     foreach ($this->arrTags as $idx => $tag) {
         if (count($pageArr)) {
             if ($tag['tag_name'] != \Input::get('tag') && $tag['tag_name'] != str_replace('|slash|', '/', \Input::get('tag'))) {
                 $strUrl = ampersand($this->generateFrontendUrl($pageArr, '/tag/' . str_replace('/', '|slash|', \System::urlencode($tag['tag_name']))));
             } else {
                 $strUrl = ampersand($this->generateFrontendUrl($pageArr));
             }
             if (strlen($strParams)) {
                 if (strpos($strUrl, '?') !== false) {
                     $strUrl .= '&amp;' . $strParams;
                 } else {
                     $strUrl .= '?' . $strParams;
                 }
             }
         }
         $this->arrTags[$idx]['tag_url'] = $strUrl;
         if ($tag['tag_name'] == \Input::get('tag') || $tag['tag_name'] == str_replace('|slash|', '/', \Input::get('tag'))) {
             $this->arrTags[$idx]['tag_class'] .= ' active';
         }
         if ($this->checkForArticleOnPage) {
             global $objPage;
             // get articles on page
             $arrArticles = $this->Database->prepare("SELECT id FROM tl_article WHERE pid = ?")->execute($objPage->id)->fetchEach('id');
             $arrTagIds = $this->Database->prepare("SELECT tid FROM " . $this->tag_tagtable . " WHERE from_table = ? AND tag = ?")->execute('tl_article', $tag['tag_name'])->fetchEach('tid');
             if (count(array_intersect($arrArticles, $arrTagIds))) {
                 $this->arrTags[$idx]['tag_class'] .= ' here';
             }
         }
         if ($this->checkForContentElementOnPage) {
             global $objPage;
             // get articles on page
             $arrArticles = $this->Database->prepare("SELECT id FROM tl_article WHERE pid = ?")->execute($objPage->id)->fetchEach('id');
             if (count($arrArticles)) {
                 $arrCE = $this->Database->prepare("SELECT id FROM tl_content WHERE pid IN (" . implode(",", $arrArticles) . ")")->execute()->fetchEach('id');
                 $arrTagIds = $this->Database->prepare("SELECT tid FROM " . $this->tag_tagtable . " WHERE from_table = ? AND tag = ?")->execute('tl_content', $tag['tag_name'])->fetchEach('tid');
                 if (count(array_intersect($arrCE, $arrTagIds))) {
                     $this->arrTags[$idx]['tag_class'] .= ' here';
                 }
             }
         }
     }
     $relatedlist = strlen(\Input::get('related')) ? preg_split("/,/", \Input::get('related')) : array();
     foreach ($this->arrRelated as $idx => $tag) {
         if (count($pageArr)) {
             if ($tag['tag_name'] != \Input::get('tag')) {
                 $strUrl = ampersand($this->generateFrontendUrl($pageArr, '/tag/' . str_replace('/', '|slash|', \System::urlencode(\Input::get('tag'))) . '/related/' . str_replace('/', '|slash|', \System::urlencode(join(array_merge($relatedlist, array($tag['tag_name'])), ',')))));
             } else {
                 $strUrl = ampersand($this->generateFrontendUrl($pageArr));
             }
         }
         $this->arrRelated[$idx]['tag_url'] = $strUrl;
     }
     $this->Template->pageID = $this->id;
     $this->Template->tags = $this->arrTags;
     $this->Template->jumpTo = $this->jumpTo;
     $this->Template->relatedtags = $this->arrRelated;
     $this->Template->strRelatedTags = $GLOBALS['TL_LANG']['tl_module']['tag_relatedtags'];
     $this->Template->strAllTags = $GLOBALS['TL_LANG']['tl_module']['tag_alltags'];
     $this->Template->strTopTenTags = sprintf($GLOBALS['TL_LANG']['tl_module']['top_tags'], $this->tag_topten_number);
     $this->Template->tagcount = count($this->arrTags);
     $this->Template->selectedtags = strlen(\Input::get('tag')) ? count($this->arrRelated) + 1 : 0;
     if ($this->tag_show_reset) {
         $strEmptyUrl = ampersand($this->generateFrontendUrl($pageArr, ''));
         if (strlen($strParams)) {
             if (strpos($strUrl, '?') !== false) {
                 $strEmptyUrl .= '&amp;' . $strParams;
             } else {
                 $strEmptyUrl .= '?' . $strParams;
             }
         }
         $this->Template->empty_url = $strEmptyUrl;
         $this->Template->lngEmpty = $GLOBALS['TL_LANG']['tl_module']['tag_clear_tags'];
     }
     $GLOBALS['TL_JAVASCRIPT'][] = 'system/modules/tags/assets/tagcloud.js';
     if (count($pageArr)) {
         $this->Template->topten = $this->tag_topten;
         if ($this->tag_topten) {
             foreach ($this->arrTopTenTags as $idx => $tag) {
                 if (count($pageArr)) {
                     if ($tag['tag_name'] != \Input::get('tag')) {
                         $strUrl = ampersand($this->generateFrontendUrl($pageArr, '/tag/' . str_replace('/', '|slash|', \System::urlencode($tag['tag_name']))));
                     } else {
                         $strUrl = ampersand($this->generateFrontendUrl($pageArr));
                     }
                     if (strlen($strParams)) {
                         if (strpos($strUrl, '?') !== false) {
                             $strUrl .= '&amp;' . $strParams;
                         } else {
                             $strUrl .= '?' . $strParams;
                         }
                     }
                 }
                 if ($this->arrTopTenTags[$idx]['tag_name'] == str_replace('|slash|', '/', \Input::get('tag'))) {
                     $this->arrTopTenTags[$idx]['tag_class'] .= ' active';
                 }
                 $this->arrTopTenTags[$idx]['tag_url'] = $strUrl;
             }
             $ts = deserialize(\Input::cookie('tagcloud_states'), true);
             //				$ts = $this->Session->get('tagcloud_states');
             $this->Template->expandedTopTen = strlen($ts[$this->id]['topten']) ? strcmp($ts[$this->id]['topten'], 'none') == 0 ? 0 : 1 : $this->tag_topten_expanded;
             $this->Template->expandedAll = strlen($ts[$this->id]['alltags']) ? strcmp($ts[$this->id]['alltags'], 'none') == 0 ? 0 : 1 : $this->tag_all_expanded;
             $this->Template->expandedRelated = strlen($ts[$this->id]['related']) ? strcmp($ts[$this->id]['related'], 'none') == 0 ? 0 : 1 : 1;
             $this->Template->toptentags = $this->arrTopTenTags;
         }
     }
 }
Example #14
0
 /**
  * Try to load the page from the cache
  */
 protected function outputFromCache()
 {
     // Build the page if a user is (potentially) logged in or there is POST data
     if (!empty($_POST) || Input::cookie('FE_USER_AUTH') || Input::cookie('FE_AUTO_LOGIN') || $_SESSION['DISABLE_CACHE'] || isset($_SESSION['LOGIN_ERROR']) || Config::get('debugMode')) {
         return;
     }
     /**
      * If the request string is empty, look for a cached page matching the
      * primary browser language. This is a compromise between not caching
      * empty requests at all and considering all browser languages, which
      * is not possible for various reasons.
      */
     if (Environment::get('request') == '' || Environment::get('request') == 'index.php') {
         // Return if the language is added to the URL and the empty domain will be redirected
         if (Config::get('addLanguageToUrl') && !Config::get('doNotRedirectEmpty')) {
             return;
         }
         $arrLanguage = Environment::get('httpAcceptLanguage');
         $strCacheKey = Environment::get('base') . 'empty.' . $arrLanguage[0];
     } else {
         $strCacheKey = Environment::get('base') . Environment::get('request');
     }
     // 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);
         }
     }
     $blnFound = false;
     $strCacheFile = null;
     // Check for a mobile layout
     if (Input::cookie('TL_VIEW') == 'mobile' || Environment::get('agent')->mobile && Input::cookie('TL_VIEW') != 'desktop') {
         $strCacheKey = md5($strCacheKey . '.mobile');
         $strCacheFile = TL_ROOT . '/system/cache/html/' . substr($strCacheKey, 0, 1) . '/' . $strCacheKey . '.html';
         if (file_exists($strCacheFile)) {
             $blnFound = true;
         }
     }
     // Check for a regular layout
     if (!$blnFound) {
         $strCacheKey = md5($strCacheKey);
         $strCacheFile = TL_ROOT . '/system/cache/html/' . substr($strCacheKey, 0, 1) . '/' . $strCacheKey . '.html';
         if (file_exists($strCacheFile)) {
             $blnFound = true;
         }
     }
     // Return if the file does not exist
     if (!$blnFound) {
         return;
     }
     $expire = null;
     $content = null;
     $type = null;
     // Include the file
     ob_start();
     require_once $strCacheFile;
     // The file has expired
     if ($expire < time()) {
         ob_end_clean();
         return;
     }
     // Read the buffer
     $strBuffer = ob_get_contents();
     ob_end_clean();
     // Session required to determine the referer
     $this->import('Session');
     $session = $this->Session->getData();
     // Set the new referer
     if (!isset($_GET['pdf']) && !isset($_GET['file']) && !isset($_GET['id']) && $session['referer']['current'] != Environment::get('requestUri')) {
         $session['referer']['last'] = $session['referer']['current'];
         $session['referer']['current'] = substr(Environment::get('requestUri'), strlen(TL_PATH) + 1);
     }
     // Store the session data
     $this->Session->setData($session);
     // Load the default language file (see #2644)
     $this->import('Config');
     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 = $this->replaceInsertTags($strBuffer, false);
     $strBuffer = str_replace(array('{{request_token}}', '[{]', '[}]'), array(REQUEST_TOKEN, '{{', '}}'), $strBuffer);
     // Content type
     if (!$content) {
         $content = 'text/html';
     }
     // Send the status header (see #6585)
     if ($type == 'error_403') {
         header('HTTP/1.1 403 Forbidden');
     } elseif ($type == 'error_404') {
         header('HTTP/1.1 404 Not Found');
     } else {
         header('HTTP/1.1 200 Ok');
     }
     header('Vary: User-Agent', false);
     header('Content-Type: ' . $content . '; charset=' . Config::get('characterSet'));
     // Send the cache headers
     if ($expire !== null && (Config::get('cacheMode') == 'both' || Config::get('cacheMode') == 'browser')) {
         header('Cache-Control: public, max-age=' . ($expire - time()));
         header('Expires: ' . gmdate('D, d M Y H:i:s', $expire) . ' GMT');
         header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
         header('Pragma: public');
     } else {
         header('Cache-Control: no-cache');
         header('Cache-Control: pre-check=0, post-check=0', false);
         header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
         header('Expires: Fri, 06 Jun 1975 15:10:00 GMT');
         header('Pragma: no-cache');
     }
     echo $strBuffer;
     exit;
 }
Example #15
0
 /**
  * Gets the value of a signed cookie. Cookies without signatures will not
  * be returned. If the cookie signature is present, but invalid, the cookie
  * will be deleted.
  *
  *     // Get the "theme" cookie, or use "blue" if the cookie does not exist
  *     $theme = Cookie::get('theme', 'blue');
  *
  * @param   string  cookie name
  * @param   mixed   default value to return
  * @return  string
  */
 public static function get($name = null, $default = null)
 {
     return \Input::cookie($name, $default);
 }
 /**
  * Grab the ClientID from the _ga cookie for Universal Analytics
  * IMPORTANT: The cookie doesn't exist until the page is sent for the first time, so this dependency will
  * fail for the PHP library when the customer first views the site without the cookie.
  * 
  * @link https://segment.com/docs/integrations/google-analytics/#server-side
  */
 private function _set_ga_cookie_id()
 {
     $ga_cookie = explode('.', \Input::cookie('_ga'));
     // The explosives create an array with an empty string at position 0 when the cookie doesn't exist.
     if (!empty($ga_cookie[0])) {
         $this->_ga_cookie_id = $ga_cookie[count($ga_cookie) - 2] . '.' . $ga_cookie[count($ga_cookie) - 1];
     }
 }
Example #17
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->ie6warning = sprintf($GLOBALS['TL_LANG']['ERR']['ie6warning'], '<a href="http://ie6countdown.com">', '</a>');
     $this->Template->hasComposer = is_dir(TL_ROOT . '/system/modules/!composer');
     $this->Template->output();
     exit;
 }
 protected function getDimension($strType)
 {
     if (!in_array($strType, array(TL_VIEWPORT_WIDTH, TL_VIEWPORT_HEIGHT))) {
         return null;
     }
     if (!\Input::cookie(TL_VIEWPORT_COOKIE)) {
         return null;
     }
     $strDimension = \Input::cookie(TL_VIEWPORT_COOKIE);
     if (!preg_match('#(\\d+):(\\d+)#', $strDimension)) {
         return null;
     }
     $arrDimension = explode(':', $strDimension);
     if (!$arrDimension) {
         return null;
     }
     if (!isset($arrDimension[$strType]) && !is_numeric($arrDimension[$strType])) {
         return null;
     }
     return $arrDimension[$strType];
 }
Example #19
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;
     // Set the cookie
     if (isset($_GET['toggle_view'])) {
         if (\Input::get('toggle_view') == 'mobile') {
             $this->setCookie('TL_VIEW', 'mobile', 0);
         } else {
             $this->setCookie('TL_VIEW', 'desktop', 0);
         }
         $this->redirect($this->getReferer());
     }
     // 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) {
         header('HTTP/1.1 501 Not Implemented');
         $this->log('Could not find layout ID "' . $intId . '"', __METHOD__, TL_ERROR);
         die_nicely('be_no_layout', 'No layout specified');
     }
     $objPage->hasJQuery = $objLayout->addJQuery;
     $objPage->hasMooTools = $objLayout->addMooTools;
     $objPage->isMobile = $blnMobile;
     return $objLayout;
 }
Example #20
0
File: User.php Project: rikaix/core
 /**
  * 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;
     }
     $objSession = $this->Database->prepare("SELECT * FROM tl_session WHERE hash=? AND name=?")->limit(1)->execute($this->strHash, $this->strCookie);
     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, $GLOBALS['TL_CONFIG']['websitePath']);
     $this->strHash = '';
     // Destroy the current session
     session_destroy();
     session_write_close();
     // Reset the session cookie
     $this->setCookie(session_name(), session_id(), $time - 86400, '/');
     // Remove the login status
     $_SESSION['TL_USER_LOGGED_IN'] = false;
     // Add a log entry
     if ($this->findBy('id', $intUserid) != false) {
         $GLOBALS['TL_USERNAME'] = $this->username;
         $this->log('User "' . $this->username . '" has logged out', $this->strTable . ' logout()', 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;
 }
Example #21
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'))) {
             $this->Session->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 = sha1(session_id() . (!\Config::get('disableIpCheck') ? \Environment::get('ip') : '') . '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', session_id(), \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();
 }
Example #22
0
 /**
  * Output the template file
  */
 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;
     }
     // File picker reference
     if (\Input::get('popup') && \Input::get('act') != 'show' && (\Input::get('do') == 'page' || \Input::get('do') == 'files') && $this->Session->get('filePickerRef')) {
         $this->Template->managerHref = ampersand($this->Session->get('filePickerRef'));
         $this->Template->manager = strpos($this->Session->get('filePickerRef'), 'contao/page.php') !== 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->isCoreOnlyMode = \Config::get('coreOnlyMode');
     $this->Template->coreOnlyMode = $GLOBALS['TL_LANG']['MSC']['coreOnlyMode'];
     $this->Template->coreOnlyOff = specialchars($GLOBALS['TL_LANG']['MSC']['coreOnlyOff']);
     $this->Template->coreOnlyHref = $this->addToUrl('smo=1');
     $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 = $GLOBALS['TL_LANG']['MSC']['buildCacheText'];
     $this->Template->buildCacheHref = $this->addToUrl('bic=1');
     $this->Template->isPopup = \Input::get('popup');
     // Hide the cache message in the repository manager (see #5966)
     if (!\Config::get('bypassCache') && $this->User->isAdmin) {
         $this->Template->needsCacheBuild = (\Input::get('do') != 'repository_manager' || !isset($_GET['install']) && !isset($_GET['uninstall']) && !isset($_GET['update'])) && !is_dir(TL_ROOT . '/system/cache/dca');
     }
     // 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;
             }
         }
     }
     $this->Template->output();
 }
Example #23
0
 /**
  * Authenticate a user
  *
  * @return boolean
  */
 public function authenticate()
 {
     // Default authentication
     if (parent::authenticate()) {
         return true;
     }
     // Check whether auto login is enabled
     if (\Config::get('autologin') > 0 && ($strCookie = \Input::cookie('FE_AUTO_LOGIN')) != '') {
         // Try to find the user by his auto login cookie
         if ($this->findBy('autologin', $strCookie) !== false) {
             // Check the auto login period
             if ($this->createdOn >= time() - \Config::get('autologin')) {
                 // Validate the account status
                 if ($this->checkAccountStatus() !== false) {
                     $this->setUserFromDb();
                     // Last login date
                     $this->lastLogin = $this->currentLogin;
                     $this->currentLogin = time();
                     $this->save();
                     // Generate the session
                     $this->generateSession();
                     $this->log('User "' . $this->username . '" was logged in automatically', __METHOD__, TL_ACCESS);
                     // Reload the page
                     \Controller::reload();
                     return true;
                 }
             }
         }
         // Remove the cookie if it is invalid to enable loading cached pages
         $this->setCookie('FE_AUTO_LOGIN', $strCookie, time() - 86400, null, null, \Environment::get('ssl'), true);
     }
     return false;
 }
Example #24
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' || $elements[1] == 'back' || $elements[1] == 'referer' || $elements[0] == 'request_token' || $elements[0] == 'toggle_view' || strncmp($elements[0], 'cache_', 6) === 0 || in_array('uncached', $flags)) {
                 $strBuffer .= '{{' . $strTag . '}}';
                 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="' . $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="' . $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 = \StringUtil::specialchars($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 = '';
                         $imageObj = \Image::create($strFile, array($width, $height, $mode));
                         $src = $imageObj->executeResize()->getResizedPath();
                         $objFile = new \File(rawurldecode($src));
                         // Add the image dimensions
                         if (($imgSize = $objFile->imageSize) !== false) {
                             $dimensions = ' width="' . $imgSize[0] . '" height="' . $imgSize[1] . '"';
                         }
                         $arrCache[$strTag] = '<img src="' . TL_FILES_URL . $src . '" ' . $dimensions . ' alt="' . $alt . '"' . ($class != '' ? ' class="' . $class . '"' : '') . '>';
                     } else {
                         $picture = \Picture::create($strFile, array(0, 0, $size))->getTemplateData();
                         $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="' . $rel . '"';
                         } else {
                             $attribute = ' data-lightbox="' . substr($rel, 8) . '"';
                         }
                         $arrCache[$strTag] = '<a href="' . TL_FILES_URL . $strFile . '"' . ($alt != '' ? ' title="' . $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;
                         }
                     }
                 }
                 if (\Config::get('debugMode')) {
                     $GLOBALS['TL_DEBUG']['unknown_insert_tags'][] = $strTag;
                 }
                 break;
         }
         // Handle the flags
         if (!empty($flags)) {
             foreach ($flags as $flag) {
                 switch ($flag) {
                     case 'addslashes':
                     case 'stripslashes':
                     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 'strrev':
                     case 'urlencode':
                     case 'rawurlencode':
                         $arrCache[$strTag] = $flag($arrCache[$strTag]);
                         break;
                     case 'encodeEmail':
                     case 'decodeEntities':
                         $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;
                                 }
                             }
                         }
                         if (\Config::get('debugMode')) {
                             $GLOBALS['TL_DEBUG']['unknown_insert_tag_flags'][] = $flag;
                         }
                         break;
                 }
             }
         }
         $strBuffer .= $arrCache[$strTag];
     }
     return \StringUtil::restoreBasicEntities($strBuffer);
 }
Example #25
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" class="%s">' . '<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>', \Input::cookie('CONTAO_CONSOLE'), $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(\$) {" . "\$\$('#contao-debug>*').setStyle('width',window.getSize().x);" . "\$(document.body).setStyle('margin-bottom',\$('contao-debug').hasClass('closed')?'60px':'320px');" . "\$('debug-tog').addEvent('click',function(e) {" . "\$('contao-debug').toggleClass('closed');" . "Cookie.write('CONTAO_CONSOLE',\$('contao-debug').hasClass('closed')?'closed':'',{path:'" . (TL_PATH ?: '/') . "'});" . "\$(document.body).setStyle('margin-bottom',\$('contao-debug').hasClass('closed')?'60px':'320px');" . "});" . "window.addEvent('resize',function() {" . "\$\$('#contao-debug>*').setStyle('width',window.getSize().x);" . "});" . "})(document.id);", $this->strFormat == 'xhtml') . "\n<!-- indexer::continue -->\n\n";
     return $strDebug;
 }
Example #26
0
 /**
  * Check whether the cookiebar is enabled and should be displayed
  *
  * @param \PageModel $rootPage
  *
  * @return boolean
  */
 protected function isCookiebarEnabled(\PageModel $rootPage = null)
 {
     $objRoot = $rootPage !== null ? $rootPage : $this->getCurrentRootPage();
     if ($objRoot->cookiebar_enable && !\Input::cookie($this->getCookiebarName($objRoot))) {
         return true;
     }
     return false;
 }
 protected function isVisible(&$objChild)
 {
     $time = \Date::floorToMinute();
     $currentLang = array('', $GLOBALS['TL_LANGUAGE']);
     if (!in_array($objChild->language, $currentLang)) {
         return false;
     }
     $arrPages = deserialize($objChild->pages);
     /**
      * Filter out pages
      * (exclude == display module not on this page)
      * (include == display module only on this page)
      */
     if (is_array($arrPages) && count($arrPages) > 0) {
         // add nested pages to the filter
         if ($objChild->addPageDepth) {
             $arrPages = array_merge($arrPages, \Database::getInstance()->getChildRecords($arrPages, 'tl_page'));
         }
         $check = $objChild->addVisibility == 'exclude' ? true : false;
         if (in_array($this->objPage->id, $arrPages) == $check) {
             return false;
         }
     }
     // filter out modules by keywords
     if (strlen($objChild->keywords) > 0) {
         $arrKeywords = preg_split('/\\s*,\\s*/', trim($objChild->keywords), -1, PREG_SPLIT_NO_EMPTY);
         if (is_array($arrKeywords) && !empty($arrKeywords)) {
             foreach ($arrKeywords as $keyword) {
                 $negate = substr($keyword, 0, 1) == '!';
                 $keyword = $negate ? substr($keyword, 1, strlen($keyword)) : $keyword;
                 if ($this->Input->get($keyword) != $negate) {
                     return false;
                 }
             }
         }
     }
     // filter out by feature
     if ($objChild->feature) {
         $start = $objChild->feature_start;
         $stop = $objChild->feature_stop;
         // check if in time
         $blnFeatureActive = ($start == '' || $start <= $time) && ($stop == '' || $stop > $time + 60);
         $blnFeatureCookie = $objChild->feature_count > 0;
         if ($blnFeatureActive && $blnFeatureCookie) {
             $cookieCount = \Input::cookie($objChild->feature_cookie_name);
             $displayCount = $cookieCount == null ? 0 : intval($cookieCount);
             if ($cookieCount === null && session_status() == PHP_SESSION_DISABLED) {
                 $blnFeatureActive = true;
             } else {
                 if ($displayCount < $objChild->feature_count) {
                     setcookie($objChild->feature_cookie_name, ++$displayCount, $time + $objChild->feature_cookie_expire, '/');
                     $blnFeatureActive = true;
                 } else {
                     $blnFeatureActive = false;
                 }
             }
         }
         $objChild->featureActive = $blnFeatureActive;
         return $blnFeatureActive;
     }
     return true;
 }
Example #28
0
 /**
  * Initialize the object
  */
 protected function __construct()
 {
     parent::__construct();
     $this->strIp = \Environment::get('ip');
     $this->strHash = \Input::cookie($this->strCookie);
 }
Example #29
0
 /**
  * Check whether a back end or front end user is logged in
  * @param string
  * @return boolean
  */
 protected function getLoginStatus($strCookie)
 {
     $hash = sha1(session_id() . (!$GLOBALS['TL_CONFIG']['disableIpCheck'] ? \Environment::get('ip') : '') . $strCookie);
     // Validate the cookie hash
     if (\Input::cookie($strCookie) == $hash) {
         // Try to find the session
         $objSession = \SessionModel::findByHashAndName($hash, $strCookie);
         // Validate the session ID and timeout
         if ($objSession !== null && $objSession->sessionID == session_id() && ($GLOBALS['TL_CONFIG']['disableIpCheck'] || $objSession->ip == \Environment::get('ip')) && $objSession->tstamp + $GLOBALS['TL_CONFIG']['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')) {
                     $_SESSION['TL_USER_LOGGED_IN'] = false;
                     return false;
                 }
             }
             // The session could be verified
             $_SESSION['TL_USER_LOGGED_IN'] = true;
             return true;
         }
     }
     // Reset the cache settings
     if (TL_MODE == 'FE' && $strCookie == 'BE_USER_AUTH') {
         $_SESSION['DISABLE_CACHE'] = false;
     }
     // The session could not be verified
     $_SESSION['TL_USER_LOGGED_IN'] = false;
     return false;
 }
Example #30
0
 /**
  * Parse the template file and print it to the screen
  */
 public function output()
 {
     if (!$this->strBuffer) {
         $this->strBuffer = $this->parse();
     }
     // Minify the markup if activated
     $this->strBuffer = $this->minifyHtml($this->strBuffer);
     // Send some headers
     header('Vary: User-Agent', false);
     header('Content-Type: ' . $this->strContentType . '; charset=' . $GLOBALS['TL_CONFIG']['characterSet']);
     // Debug information
     if ($GLOBALS['TL_CONFIG']['debugMode']) {
         $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;
         // Switch to milliseconds if less than one second
         if ($intElapsed > 1) {
             $intTime = $intElapsed;
             $strUnit = 's';
         } else {
             $intTime = $intElapsed * 1000;
             $strUnit = 'ms';
         }
         $strDebug = '<div id="debug" class="' . \Input::cookie('CONTAO_CONSOLE') . '">' . "\n" . '<p><span class="info">Contao debug information</span> <span class="time">Execution time: ' . $this->getFormattedNumber($intTime, 0) . ' ' . $strUnit . '</span> <span class="memory">Memory usage: ' . $this->getReadableSize(memory_get_peak_usage()) . '</span> <span class="db">Database queries: ' . count($GLOBALS['TL_DEBUG']['database_queries']) . '</span> <span class="rows">Rows: ' . $intReturned . ' returned, ' . $intAffected . ' affected</span> <span id="tog">&nbsp;</span></p>' . "\n" . '<div><pre>' . "\n";
         ob_start();
         ksort($GLOBALS['TL_DEBUG']);
         print_r($GLOBALS['TL_DEBUG']);
         $strDebug .= ob_get_contents();
         ob_end_clean();
         if ($this->strFormat == 'xhtml') {
             $strScriptOpen = '<script type="text/javascript">' . "\n/* <![CDATA[ */\n";
             $strScriptClose = "\n/* ]]> */\n" . '</script>';
         } else {
             $strScriptOpen = '<script>';
             $strScriptClose = '</script>';
         }
         $strDebug .= '</pre></div></div>' . $strScriptOpen . 'window.MooTools || document.write(\'<script' . ($this->strFormat == 'xhtml' ? ' type="text/javascript"' : '') . ' src="' . TL_ASSETS_URL . 'assets/mootools/core/' . MOOTOOLS . '/mootools-core.js">\\x3C/script>\')' . $strScriptClose . $strScriptOpen . "(function(\$) {" . "\$\$('#debug p','#debug div').setStyle('width',window.getSize().x);" . "\$(document.body).setStyle('margin-bottom', \$('debug').hasClass('closed')?'60px':'320px');" . "\$('tog').addEvent('click',function(e) {" . "\$('debug').toggleClass('closed');" . "Cookie.write('CONTAO_CONSOLE',\$('debug').hasClass('closed')?'closed':'');" . "\$(document.body).setStyle('margin-bottom', \$('debug').hasClass('closed')?'60px':'320px');" . "});" . "window.addEvent('resize',function() {" . "\$\$('#debug p','#debug div').setStyle('width',window.getSize().x);" . "});" . "})(document.id);" . $strScriptClose . "\n\n";
         $this->strBuffer = str_replace('</body>', $strDebug . '</body>', $this->strBuffer);
     }
     echo $this->strBuffer;
     exit;
     // see #4565
 }