/manager/includes/document.parser.class.inc.php
PHP | 2829 lines | 2372 code | 212 blank | 245 comment | 579 complexity | 4ee03fedd56977f867addd2714f4aa53 MD5 | raw file
Large files files are truncated, but you can click here to view the full file
- <?php
- /**
- * MODx Document Parser
- * Function: This class contains the main document parsing functions
- *
- */
- class DocumentParser {
- var $db; // db object
- var $event, $Event; // event object
- var $pluginEvent;
- var $config= null;
- var $rs, $result, $sql, $table_prefix, $debug, $documentIdentifier, $documentMethod, $documentGenerated, $documentContent, $tstart, $minParserPasses, $maxParserPasses, $documentObject, $templateObject, $snippetObjects, $stopOnNotice, $executedQueries, $queryTime, $currentSnippet, $documentName, $aliases, $visitor, $entrypage, $documentListing, $dumpSnippets, $chunkCache, $snippetCache, $contentTypes, $dumpSQL, $queryCode, $virtualDir, $placeholders, $sjscripts, $jscripts, $loadedjscripts, $documentMap;
- var $forwards= 3;
- // constructor
- function DocumentParser() {
- $this->loadExtension('DBAPI') or die('Could not load DBAPI class.'); // load DBAPI class
- $this->dbConfig= & $this->db->config; // alias for backward compatibility
- $this->jscripts= array ();
- $this->sjscripts= array ();
- $this->loadedjscripts= array ();
- // events
- $this->event= new SystemEvent();
- $this->Event= & $this->event; //alias for backward compatibility
- $this->pluginEvent= array ();
- // set track_errors ini variable
- @ ini_set("track_errors", "1"); // enable error tracking in $php_errormsg
- }
- // loads an extension from the extenders folder
- function loadExtension($extname) {
- global $database_type;
- switch ($extname) {
- // Database API
- case 'DBAPI' :
- if (!include_once MODX_BASE_PATH . 'manager/includes/extenders/dbapi.' . $database_type . '.class.inc.php')
- return false;
- $this->db= new DBAPI;
- return true;
- break;
- // Manager API
- case 'ManagerAPI' :
- if (!include_once MODX_BASE_PATH . 'manager/includes/extenders/manager.api.class.inc.php')
- return false;
- $this->manager= new ManagerAPI;
- return true;
- break;
- default :
- return false;
- }
- }
- function getMicroTime() {
- list ($usec, $sec)= explode(' ', microtime());
- return ((float) $usec + (float) $sec);
- }
- function sendRedirect($url, $count_attempts= 0, $type= '', $responseCode= '') {
- if (empty ($url)) {
- return false;
- } else {
- if ($count_attempts == 1) {
- // append the redirect count string to the url
- $currentNumberOfRedirects= isset ($_REQUEST['err']) ? $_REQUEST['err'] : 0;
- if ($currentNumberOfRedirects > 3) {
- $this->messageQuit('Redirection attempt failed - please ensure the document you\'re trying to redirect to exists. <p>Redirection URL: <i>' . $url . '</i></p>');
- } else {
- $currentNumberOfRedirects += 1;
- if (strpos($url, "?") > 0) {
- $url .= "&err=$currentNumberOfRedirects";
- } else {
- $url .= "?err=$currentNumberOfRedirects";
- }
- }
- }
- if ($type == 'REDIRECT_REFRESH') {
- $header= 'Refresh: 0;URL=' . $url;
- }
- elseif ($type == 'REDIRECT_META') {
- $header= '<META HTTP-EQUIV="Refresh" CONTENT="0; URL=' . $url . '" />';
- echo $header;
- exit;
- }
- elseif ($type == 'REDIRECT_HEADER' || empty ($type)) {
- // check if url has /$base_url
- global $base_url, $site_url;
- if (substr($url, 0, strlen($base_url)) == $base_url) {
- // append $site_url to make it work with Location:
- $url= $site_url . substr($url, strlen($base_url));
- }
- if (strpos($url, "\n") === false) {
- $header= 'Location: ' . $url;
- } else {
- $this->messageQuit('No newline allowed in redirect url.');
- }
- }
- if ($responseCode && (strpos($responseCode, '30') !== false)) {
- header($responseCode);
- }
- header($header);
- exit();
- }
- }
- function sendForward($id, $responseCode= '') {
- if ($this->forwards > 0) {
- $this->forwards= $this->forwards - 1;
- $this->documentIdentifier= $id;
- $this->documentMethod= 'id';
- $this->documentObject= $this->getDocumentObject('id', $id);
- if ($responseCode) {
- header($responseCode);
- }
- $this->prepareResponse();
- exit();
- } else {
- header('HTTP/1.0 500 Internal Server Error');
- die('<h1>ERROR: Too many forward attempts!</h1><p>The request could not be completed due to too many unsuccessful forward attempts.</p>');
- }
- }
- function sendErrorPage() {
- // invoke OnPageNotFound event
- $this->invokeEvent('OnPageNotFound');
- // $this->sendRedirect($this->makeUrl($this->config['error_page'], '', '&refurl=' . urlencode($_SERVER['PHP_SELF'] . '?' . $_SERVER['QUERY_STRING'])), 1);
- $this->sendForward($this->config['error_page'] ? $this->config['error_page'] : $this->config['site_start'], 'HTTP/1.0 404 Not Found');
- exit();
- }
- function sendUnauthorizedPage() {
- // invoke OnPageUnauthorized event
- $_REQUEST['refurl'] = $this->documentIdentifier;
- $this->invokeEvent('OnPageUnauthorized');
- if ($this->config['unauthorized_page']) {
- $unauthorizedPage= $this->config['unauthorized_page'];
- } elseif ($this->config['error_page']) {
- $unauthorizedPage= $this->config['error_page'];
- } else {
- $unauthorizedPage= $this->config['site_start'];
- }
- $this->sendForward($unauthorizedPage, 'HTTP/1.1 401 Unauthorized');
- exit();
- }
- // function to connect to the database
- // - deprecated use $modx->db->connect()
- function dbConnect() {
- $this->db->connect();
- $this->rs= $this->db->conn; // for compatibility
- }
- // function to query the database
- // - deprecated use $modx->db->query()
- function dbQuery($sql) {
- return $this->db->query($sql);
- }
- // function to count the number of rows in a record set
- function recordCount($rs) {
- return $this->db->getRecordCount($rs);
- }
- // - deprecated, use $modx->db->getRow()
- function fetchRow($rs, $mode= 'assoc') {
- return $this->db->getRow($rs, $mode);
- }
- // - deprecated, use $modx->db->getAffectedRows()
- function affectedRows($rs) {
- return $this->db->getAffectedRows($rs);
- }
- // - deprecated, use $modx->db->getInsertId()
- function insertId($rs) {
- return $this->db->getInsertId($rs);
- }
- // function to close a database connection
- // - deprecated, use $modx->db->disconnect()
- function dbClose() {
- $this->db->disconnect();
- }
- function getSettings() {
- if (!is_array($this->config) || empty ($this->config)) {
- if ($included= file_exists(MODX_BASE_PATH . 'assets/cache/siteCache.idx.php')) {
- $included= include_once (MODX_BASE_PATH . 'assets/cache/siteCache.idx.php');
- }
- if (!$included) {
- $result= $this->dbQuery('SELECT setting_name, setting_value FROM ' . $this->getFullTableName('system_settings'));
- while ($row= $this->fetchRow($result, 'both')) {
- $this->config[$row[0]]= $row[1];
- }
- }
- // added for backwards compatibility - garry FS#104
- $this->config['etomite_charset'] = & $this->config['modx_charset'];
- // store base_url and base_path inside config array
- $this->config['base_url']= MODX_BASE_URL;
- $this->config['base_path']= MODX_BASE_PATH;
- $this->config['site_url']= MODX_SITE_URL;
- // load user setting if user is logged in
- $usrSettings= array ();
- if ($id= $this->getLoginUserID()) {
- $usrType= $this->getLoginUserType();
- if (isset ($usrType) && $usrType == 'manager')
- $usrType= 'mgr';
- if ($usrType == 'mgr' && $this->isBackend()) {
- // invoke the OnBeforeManagerPageInit event, only if in backend
- $this->invokeEvent("OnBeforeManagerPageInit");
- }
- if (isset ($_SESSION[$usrType . 'UsrConfigSet'])) {
- $usrSettings= & $_SESSION[$usrType . 'UsrConfigSet'];
- } else {
- if ($usrType == 'web')
- $query= $this->getFullTableName('web_user_settings') . ' WHERE webuser=\'' . $id . '\'';
- else
- $query= $this->getFullTableName('user_settings') . ' WHERE user=\'' . $id . '\'';
- $result= $this->dbQuery('SELECT setting_name, setting_value FROM ' . $query);
- while ($row= $this->fetchRow($result, 'both'))
- $usrSettings[$row[0]]= $row[1];
- if (isset ($usrType))
- $_SESSION[$usrType . 'UsrConfigSet']= $usrSettings; // store user settings in session
- }
- }
- if ($this->isFrontend() && $mgrid= $this->getLoginUserID('mgr')) {
- $musrSettings= array ();
- if (isset ($_SESSION['mgrUsrConfigSet'])) {
- $musrSettings= & $_SESSION['mgrUsrConfigSet'];
- } else {
- $query= $this->getFullTableName('user_settings') . ' WHERE user=\'' . $mgrid . '\'';
- if ($result= $this->dbQuery('SELECT setting_name, setting_value FROM ' . $query)) {
- while ($row= $this->fetchRow($result, 'both')) {
- $usrSettings[$row[0]]= $row[1];
- }
- $_SESSION['mgrUsrConfigSet']= $musrSettings; // store user settings in session
- }
- }
- if (!empty ($musrSettings)) {
- $usrSettings= array_merge($musrSettings, $usrSettings);
- }
- }
- $this->config= array_merge($this->config, $usrSettings);
- }
- }
- function getDocumentMethod() {
- // function to test the query and find the retrieval method
- if (isset ($_REQUEST['q'])) {
- return "alias";
- }
- elseif (isset ($_REQUEST['id'])) {
- return "id";
- } else {
- return "none";
- }
- }
- function getDocumentIdentifier($method) {
- // function to test the query and find the retrieval method
- $docIdentifier= $this->config['site_start'];
- switch ($method) {
- case 'alias' :
- $docIdentifier= $this->db->escape($_REQUEST['q']);
- break;
- case 'id' :
- if (!is_numeric($_REQUEST['id'])) {
- $this->sendErrorPage();
- } else {
- $docIdentifier= intval($_REQUEST['id']);
- }
- break;
- }
- return $docIdentifier;
- }
- // check for manager login session
- function checkSession() {
- if (isset ($_SESSION['mgrValidated'])) {
- return true;
- } else {
- return false;
- }
- }
- function checkPreview() {
- if ($this->checkSession() == true) {
- if (isset ($_REQUEST['z']) && $_REQUEST['z'] == 'manprev') {
- return true;
- } else {
- return false;
- }
- } else {
- return false;
- }
- }
- // check if site is offline
- function checkSiteStatus() {
- $siteStatus= $this->config['site_status'];
- if ($siteStatus == 1) {
- // site online
- return true;
- }
- elseif ($siteStatus == 0 && $this->checkSession()) {
- // site offline but launched via the manager
- return true;
- } else {
- // site is offline
- return false;
- }
- }
- function cleanDocumentIdentifier($qOrig) {
- (!empty($qOrig)) or $qOrig = $this->config['site_start'];
- $q= $qOrig;
- /* First remove any / before or after */
- if ($q[strlen($q) - 1] == '/')
- $q= substr($q, 0, -1);
- if ($q[0] == '/')
- $q= substr($q, 1);
- /* Save path if any */
- /* FS#476 and FS#308: only return virtualDir if friendly paths are enabled */
- if ($this->config['use_alias_path'] == 1) {
- $this->virtualDir= dirname($q);
- $this->virtualDir= ($this->virtualDir == '.' ? '' : $this->virtualDir);
- $q= basename($q);
- } else {
- $this->virtualDir= '';
- }
- $q= str_replace($this->config['friendly_url_prefix'], "", $q);
- $q= str_replace($this->config['friendly_url_suffix'], "", $q);
- if (is_numeric($q) && !$this->documentListing[$q]) { /* we got an ID returned, check to make sure it's not an alias */
- /* FS#476 and FS#308: check that id is valid in terms of virtualDir structure */
- if ($this->config['use_alias_path'] == 1) {
- if ((($this->virtualDir != '' && !$this->documentListing[$this->virtualDir . '/' . $q]) || ($this->virtualDir == '' && !$this->documentListing[$q])) && (($this->virtualDir != '' && in_array($q, $this->getChildIds($this->documentListing[$this->virtualDir], 1))) || ($this->virtualDir == '' && in_array($q, $this->getChildIds(0, 1))))) {
- $this->documentMethod= 'id';
- return $q;
- } else { /* not a valid id in terms of virtualDir, treat as alias */
- $this->documentMethod= 'alias';
- return $q;
- }
- } else {
- $this->documentMethod= 'id';
- return $q;
- }
- } else { /* we didn't get an ID back, so instead we assume it's an alias */
- if ($this->config['friendly_alias_urls'] != 1) {
- $q= $qOrig;
- }
- $this->documentMethod= 'alias';
- return $q;
- }
- }
- function checkCache($id) {
- $cacheFile= "assets/cache/docid_" . $id . ".pageCache.php";
- if (file_exists($cacheFile)) {
- $this->documentGenerated= 0;
- $flContent= implode("", file($cacheFile));
- $flContent= substr($flContent, 37); // remove php header
- $a= explode("<!--__MODxCacheSpliter__-->", $flContent, 2);
- if (count($a) == 1)
- return $a[0]; // return only document content
- else {
- $docObj= unserialize($a[0]); // rebuild document object
- // check page security
- if ($docObj['privateweb'] && isset ($docObj['__MODxDocGroups__'])) {
- $pass= false;
- $usrGrps= $this->getUserDocGroups();
- $docGrps= explode(",", $docObj['__MODxDocGroups__']);
- // check is user has access to doc groups
- if (is_array($usrGrps)) {
- foreach ($usrGrps as $k => $v)
- if (in_array($v, $docGrps)) {
- $pass= true;
- break;
- }
- }
- // diplay error pages if user has no access to cached doc
- if (!$pass) {
- if ($this->config['unauthorized_page']) {
- // check if file is not public
- $tbldg= $this->getFullTableName("document_groups");
- $secrs= $this->dbQuery("SELECT id FROM $tbldg WHERE document = '" . $id . "' LIMIT 1;");
- if ($secrs)
- $seclimit= mysql_num_rows($secrs);
- }
- if ($seclimit > 0) {
- // match found but not publicly accessible, send the visitor to the unauthorized_page
- $this->sendUnauthorizedPage();
- exit; // stop here
- } else {
- // no match found, send the visitor to the error_page
- $this->sendErrorPage();
- exit; // stop here
- }
- }
- }
- // Grab the Scripts
- if (isset($docObj['__MODxSJScripts__'])) $this->sjscripts = $docObj['__MODxSJScripts__'];
- if (isset($docObj['__MODxJScripts__'])) $this->jscripts = $docObj['__MODxJScripts__'];
- // Remove intermediate variables
- unset($docObj['__MODxDocGroups__'], $docObj['__MODxSJScripts__'], $docObj['__MODxJScripts__']);
- $this->documentObject= $docObj;
- return $a[1]; // return document content
- }
- } else {
- $this->documentGenerated= 1;
- return "";
- }
- }
- function outputContent($noEvent= false) {
- $this->documentOutput= $this->documentContent;
- if ($this->documentGenerated == 1 && $this->documentObject['cacheable'] == 1 && $this->documentObject['type'] == 'document' && $this->documentObject['published'] == 1) {
- if (!empty($this->sjscripts)) $this->documentObject['__MODxSJScripts__'] = $this->sjscripts;
- if (!empty($this->jscripts)) $this->documentObject['__MODxJScripts__'] = $this->jscripts;
- }
- // check for non-cached snippet output
- if (strpos($this->documentOutput, '[!') > -1) {
- $this->documentOutput= str_replace('[!', '[[', $this->documentOutput);
- $this->documentOutput= str_replace('!]', ']]', $this->documentOutput);
- // Parse document source
- $this->documentOutput= $this->parseDocumentSource($this->documentOutput);
- }
- // Moved from prepareResponse() by sirlancelot
- // Insert Startup jscripts & CSS scripts into template - template must have a <head> tag
- if ($js= $this->getRegisteredClientStartupScripts()) {
- // change to just before closing </head>
- // $this->documentContent = preg_replace("/(<head[^>]*>)/i", "\\1\n".$js, $this->documentContent);
- $this->documentOutput= preg_replace("/(<\/head>)/i", $js . "\n\\1", $this->documentOutput);
- }
- // Insert jscripts & html block into template - template must have a </body> tag
- if ($js= $this->getRegisteredClientScripts()) {
- $this->documentOutput= preg_replace("/(<\/body>)/i", $js . "\n\\1", $this->documentOutput);
- }
- // End fix by sirlancelot
- // remove all unused placeholders
- if (strpos($this->documentOutput, '[+') > -1) {
- $matches= array ();
- preg_match_all('~\[\+(.*?)\+\]~', $this->documentOutput, $matches);
- if ($matches[0])
- $this->documentOutput= str_replace($matches[0], '', $this->documentOutput);
- }
- $this->documentOutput= $this->rewriteUrls($this->documentOutput);
- // send out content-type and content-disposition headers
- if (IN_PARSER_MODE == "true") {
- $type= !empty ($this->contentTypes[$this->documentIdentifier]) ? $this->contentTypes[$this->documentIdentifier] : "text/html";
- header('Content-Type: ' . $type . '; charset=' . $this->config['modx_charset']);
- // if (($this->documentIdentifier == $this->config['error_page']) || $redirect_error)
- // header('HTTP/1.0 404 Not Found');
- if (!$this->checkPreview() && $this->documentObject['content_dispo'] == 1) {
- if ($this->documentObject['alias'])
- $name= $this->documentObject['alias'];
- else {
- // strip title of special characters
- $name= $this->documentObject['pagetitle'];
- $name= strip_tags($name);
- $name= strtolower($name);
- $name= preg_replace('/&.+?;/', '', $name); // kill entities
- $name= preg_replace('/[^\.%a-z0-9 _-]/', '', $name);
- $name= preg_replace('/\s+/', '-', $name);
- $name= preg_replace('|-+|', '-', $name);
- $name= trim($name, '-');
- }
- $header= 'Content-Disposition: attachment; filename=' . $name;
- header($header);
- }
- }
- $totalTime= ($this->getMicroTime() - $this->tstart);
- $queryTime= $this->queryTime;
- $phpTime= $totalTime - $queryTime;
- $queryTime= sprintf("%2.4f s", $queryTime);
- $totalTime= sprintf("%2.4f s", $totalTime);
- $phpTime= sprintf("%2.4f s", $phpTime);
- $source= $this->documentGenerated == 1 ? "database" : "cache";
- $queries= isset ($this->executedQueries) ? $this->executedQueries : 0;
- $out =& $this->documentOutput;
- if ($this->dumpSQL) {
- $out .= $this->queryCode;
- }
- $out= str_replace("[^q^]", $queries, $out);
- $out= str_replace("[^qt^]", $queryTime, $out);
- $out= str_replace("[^p^]", $phpTime, $out);
- $out= str_replace("[^t^]", $totalTime, $out);
- $out= str_replace("[^s^]", $source, $out);
- //$this->documentOutput= $out;
- // invoke OnWebPagePrerender event
- if (!$noEvent) {
- $this->invokeEvent("OnWebPagePrerender");
- }
- echo $this->documentOutput;
- ob_end_flush();
- }
- function checkPublishStatus() {
- $cacheRefreshTime= 0;
- @include $this->config["base_path"] . "assets/cache/sitePublishing.idx.php";
- $timeNow= time() + $this->config['server_offset_time'];
- if ($cacheRefreshTime <= $timeNow && $cacheRefreshTime != 0) {
- // now, check for documents that need publishing
- $sql = "UPDATE ".$this->getFullTableName("site_content")." SET published=1, publishedon=".time()." WHERE ".$this->getFullTableName("site_content").".pub_date <= $timeNow AND ".$this->getFullTableName("site_content").".pub_date!=0 AND published=0";
- if (@ !$result= $this->dbQuery($sql)) {
- $this->messageQuit("Execution of a query to the database failed", $sql);
- }
- // now, check for documents that need un-publishing
- $sql= "UPDATE " . $this->getFullTableName("site_content") . " SET published=0, publishedon=0 WHERE " . $this->getFullTableName("site_content") . ".unpub_date <= $timeNow AND " . $this->getFullTableName("site_content") . ".unpub_date!=0 AND published=1";
- if (@ !$result= $this->dbQuery($sql)) {
- $this->messageQuit("Execution of a query to the database failed", $sql);
- }
- // clear the cache
- $basepath= $this->config["base_path"] . "assets/cache/";
- if ($handle= opendir($basepath)) {
- $filesincache= 0;
- $deletedfilesincache= 0;
- while (false !== ($file= readdir($handle))) {
- if ($file != "." && $file != "..") {
- $filesincache += 1;
- if (preg_match("/\.pageCache/", $file)) {
- $deletedfilesincache += 1;
- while (!unlink($basepath . "/" . $file));
- }
- }
- }
- closedir($handle);
- }
- // update publish time file
- $timesArr= array ();
- $sql= "SELECT MIN(pub_date) AS minpub FROM " . $this->getFullTableName("site_content") . " WHERE pub_date>$timeNow";
- if (@ !$result= $this->dbQuery($sql)) {
- $this->messageQuit("Failed to find publishing timestamps", $sql);
- }
- $tmpRow= $this->fetchRow($result);
- $minpub= $tmpRow['minpub'];
- if ($minpub != NULL) {
- $timesArr[]= $minpub;
- }
- $sql= "SELECT MIN(unpub_date) AS minunpub FROM " . $this->getFullTableName("site_content") . " WHERE unpub_date>$timeNow";
- if (@ !$result= $this->dbQuery($sql)) {
- $this->messageQuit("Failed to find publishing timestamps", $sql);
- }
- $tmpRow= $this->fetchRow($result);
- $minunpub= $tmpRow['minunpub'];
- if ($minunpub != NULL) {
- $timesArr[]= $minunpub;
- }
- if (count($timesArr) > 0) {
- $nextevent= min($timesArr);
- } else {
- $nextevent= 0;
- }
- $basepath= $this->config["base_path"] . "assets/cache";
- $fp= @ fopen($basepath . "/sitePublishing.idx.php", "wb");
- if ($fp) {
- @ flock($fp, LOCK_EX);
- @ fwrite($fp, "<?php \$cacheRefreshTime=$nextevent; ?>");
- @ flock($fp, LOCK_UN);
- @ fclose($fp);
- }
- }
- }
- function postProcess() {
- // if the current document was generated, cache it!
- if ($this->documentGenerated == 1 && $this->documentObject['cacheable'] == 1 && $this->documentObject['type'] == 'document' && $this->documentObject['published'] == 1) {
- $basepath= $this->config["base_path"] . "assets/cache";
- // invoke OnBeforeSaveWebPageCache event
- $this->invokeEvent("OnBeforeSaveWebPageCache");
- if ($fp= @ fopen($basepath . "/docid_" . $this->documentIdentifier . ".pageCache.php", "w")) {
- // get and store document groups inside document object. Document groups will be used to check security on cache pages
- $sql= "SELECT document_group FROM " . $this->getFullTableName("document_groups") . " WHERE document='" . $this->documentIdentifier . "'";
- $docGroups= $this->db->getColumn("document_group", $sql);
- // Attach Document Groups and Scripts
- if (is_array($docGroups)) $this->documentObject['__MODxDocGroups__'] = implode(",", $docGroups);
- $docObjSerial= serialize($this->documentObject);
- $cacheContent= $docObjSerial . "<!--__MODxCacheSpliter__-->" . $this->documentContent;
- fputs($fp, "<?php die('Unauthorized access.'); ?>$cacheContent");
- fclose($fp);
- }
- }
- // Useful for example to external page counters/stats packages
- $this->invokeEvent('OnWebPageComplete');
- // end post processing
- }
- function mergeDocumentMETATags($template) {
- if ($this->documentObject['haskeywords'] == 1) {
- // insert keywords
- $keywords = $this->getKeywords();
- if (is_array($keywords) && count($keywords) > 0) {
- $keywords = implode(", ", $keywords);
- $metas= "\t<meta name=\"keywords\" content=\"$keywords\" />\n";
- }
- // Don't process when cached
- $this->documentObject['haskeywords'] = '0';
- }
- if ($this->documentObject['hasmetatags'] == 1) {
- // insert meta tags
- $tags= $this->getMETATags();
- foreach ($tags as $n => $col) {
- $tag= strtolower($col['tag']);
- $tagvalue= $col['tagvalue'];
- $tagstyle= $col['http_equiv'] ? 'http-equiv' : 'name';
- $metas .= "\t<meta $tagstyle=\"$tag\" content=\"$tagvalue\" />\n";
- }
- // Don't process when cached
- $this->documentObject['hasmetatags'] = '0';
- }
- if ($metas) $template = preg_replace("/(<head>)/i", "\\1\n\t" . trim($metas), $template);
- return $template;
- }
- // mod by Raymond
- function mergeDocumentContent($template) {
- $replace= array ();
- preg_match_all('~\[\*(.*?)\*\]~', $template, $matches);
- $variableCount= count($matches[1]);
- $basepath= $this->config["base_path"] . "manager/includes";
- for ($i= 0; $i < $variableCount; $i++) {
- $key= $matches[1][$i];
- $key= substr($key, 0, 1) == '#' ? substr($key, 1) : $key; // remove # for QuickEdit format
- $value= $this->documentObject[$key];
- if (is_array($value)) {
- include_once $basepath . "/tmplvars.format.inc.php";
- include_once $basepath . "/tmplvars.commands.inc.php";
- $w= "100%";
- $h= "300";
- $value= getTVDisplayFormat($value[0], $value[1], $value[2], $value[3], $value[4]);
- }
- $replace[$i]= $value;
- }
- $template= str_replace($matches[0], $replace, $template);
- return $template;
- }
- function mergeSettingsContent($template) {
- $replace= array ();
- $matches= array ();
- if (preg_match_all('~\[\(([a-z\_]*?)\)\]~', $template, $matches)) {
- $settingsCount= count($matches[1]);
- for ($i= 0; $i < $settingsCount; $i++) {
- if (array_key_exists($matches[1][$i], $this->config))
- $replace[$i]= $this->config[$matches[1][$i]];
- }
- $template= str_replace($matches[0], $replace, $template);
- }
- return $template;
- }
- function mergeChunkContent($content) {
- $replace= array ();
- $matches= array ();
- if (preg_match_all('~{{(.*?)}}~', $content, $matches)) {
- $settingsCount= count($matches[1]);
- for ($i= 0; $i < $settingsCount; $i++) {
- if (isset ($this->chunkCache[$matches[1][$i]])) {
- $replace[$i]= $this->chunkCache[$matches[1][$i]];
- } else {
- $sql= "SELECT * FROM " . $this->getFullTableName("site_htmlsnippets") . " WHERE " . $this->getFullTableName("site_htmlsnippets") . ".name='" . $this->db->escape($matches[1][$i]) . "';";
- $result= $this->dbQuery($sql);
- $limit= $this->recordCount($result);
- if ($limit < 1) {
- $this->chunkCache[$matches[1][$i]]= "";
- $replace[$i]= "";
- } else {
- $row= $this->fetchRow($result);
- $this->chunkCache[$matches[1][$i]]= $row['snippet'];
- $replace[$i]= $row['snippet'];
- }
- }
- }
- $content= str_replace($matches[0], $replace, $content);
- }
- return $content;
- }
- // Added by Raymond
- function mergePlaceholderContent($content) {
- $replace= array ();
- $matches= array ();
- if (preg_match_all('~\[\+(.*?)\+\]~', $content, $matches)) {
- $cnt= count($matches[1]);
- for ($i= 0; $i < $cnt; $i++) {
- $v= '';
- $key= $matches[1][$i];
- if (is_array($this->placeholders) && array_key_exists($key, $this->placeholders))
- $v= $this->placeholders[$key];
- if ($v === '')
- unset ($matches[0][$i]); // here we'll leave empty placeholders for last.
- else
- $replace[$i]= $v;
- }
- $content= str_replace($matches[0], $replace, $content);
- }
- return $content;
- }
- // evalPlugin
- function evalPlugin($pluginCode, $params) {
- $etomite= $modx= & $this;
- $modx->event->params= & $params; // store params inside event object
- if (is_array($params)) {
- extract($params, EXTR_SKIP);
- }
- ob_start();
- eval ($pluginCode);
- $msg= ob_get_contents();
- ob_end_clean();
- if ($msg && isset ($php_errormsg)) {
- if (!strpos($php_errormsg, 'Deprecated')) { // ignore php5 strict errors
- // log error
- $this->logEvent(1, 3, "<b>$php_errormsg</b><br /><br /> $msg", $this->Event->activePlugin . " - Plugin");
- if ($this->isBackend())
- $this->Event->alert("An error occurred while loading. Please see the event log for more information.<p />$msg");
- }
- } else {
- echo $msg;
- }
- unset ($modx->event->params);
- }
- function evalSnippet($snippet, $params) {
- $etomite= $modx= & $this;
- $modx->event->params= & $params; // store params inside event object
- if (is_array($params)) {
- extract($params, EXTR_SKIP);
- }
- ob_start();
- $snip= eval ($snippet);
- $msg= ob_get_contents();
- ob_end_clean();
- if ($msg && isset ($php_errormsg)) {
- if (!strpos($php_errormsg, 'Deprecated')) { // ignore php5 strict errors
- // log error
- $this->logEvent(1, 3, "<b>$php_errormsg</b><br /><br /> $msg", $this->currentSnippet . " - Snippet");
- if ($this->isBackend())
- $this->Event->alert("An error occurred while loading. Please see the event log for more information<p />$msg");
- }
- }
- unset ($modx->event->params);
- return $msg . $snip;
- }
- function evalSnippets($documentSource) {
- preg_match_all('~\[\[(.*?)\]\]~ms', $documentSource, $matches);
- $etomite= & $this;
- if ($matchCount= count($matches[1])) {
- for ($i= 0; $i < $matchCount; $i++) {
- $spos= strpos($matches[1][$i], '?', 0);
- if ($spos !== false) {
- $params= substr($matches[1][$i], $spos, strlen($matches[1][$i]));
- } else {
- $params= '';
- }
- $matches[1][$i]= str_replace($params, '', $matches[1][$i]);
- $snippetParams[$i]= $params;
- }
- $nrSnippetsToGet= $matchCount;
- for ($i= 0; $i < $nrSnippetsToGet; $i++) { // Raymond: Mod for Snippet props
- if (isset ($this->snippetCache[$matches[1][$i]])) {
- $snippets[$i]['name']= $matches[1][$i];
- $snippets[$i]['snippet']= $this->snippetCache[$matches[1][$i]];
- if (array_key_exists($matches[1][$i] . "Props", $this->snippetCache))
- $snippets[$i]['properties']= $this->snippetCache[$matches[1][$i] . "Props"];
- } else {
- // get from db and store a copy inside cache
- $sql= "SELECT * FROM " . $this->getFullTableName("site_snippets") . " WHERE " . $this->getFullTableName("site_snippets") . ".name='" . $this->db->escape($matches[1][$i]) . "';";
- $result= $this->dbQuery($sql);
- if ($this->recordCount($result) == 1) {
- $row= $this->fetchRow($result);
- $snippets[$i]['name']= $row['name'];
- $snippets[$i]['snippet']= $this->snippetCache[$row['name']]= $row['snippet'];
- $snippets[$i]['properties']= $this->snippetCache[$row['name'] . "Props"]= $row['properties'];
- } else {
- $snippets[$i]['name']= $matches[1][$i];
- $snippets[$i]['snippet']= $this->snippetCache[$matches[1][$i]]= "return false;";
- $snippets[$i]['properties']= '';
- }
- }
- }
- for ($i= 0; $i < $nrSnippetsToGet; $i++) {
- $parameter= array ();
- $snippetName= $this->currentSnippet= $snippets[$i]['name'];
- // FIXME Undefined index: properties
- if (array_key_exists('properties', $snippets[$i])) {
- $snippetProperties= $snippets[$i]['properties'];
- } else {
- $snippetProperties= '';
- }
- // load default params/properties - Raymond
- // FIXME Undefined variable: snippetProperties
- $parameter= $this->parseProperties($snippetProperties);
- // current params
- $currentSnippetParams= $snippetParams[$i];
- if (!empty ($currentSnippetParams)) {
- $tempSnippetParams= str_replace("?", "", $currentSnippetParams);
- $splitter= "&";
- if (strpos($tempSnippetParams, "&") > 0)
- $tempSnippetParams= str_replace("&", "&", $tempSnippetParams);
- //$tempSnippetParams = html_entity_decode($tempSnippetParams, ENT_NOQUOTES, $this->config['etomite_charset']); //FS#334 and FS#456
- $tempSnippetParams= explode($splitter, $tempSnippetParams);
- $snippetParamCount= count($tempSnippetParams);
- for ($x= 0; $x < $snippetParamCount; $x++) {
- if (strpos($tempSnippetParams[$x], '=', 0)) {
- if ($parameterTemp= explode("=", $tempSnippetParams[$x])) {
- $parameterTemp[0] = trim($parameterTemp[0]);
- $parameterTemp[1] = trim($parameterTemp[1]);
- $fp= strpos($parameterTemp[1], '`');
- $lp= strrpos($parameterTemp[1], '`');
- if (!($fp === false && $lp === false))
- $parameterTemp[1]= substr($parameterTemp[1], $fp +1, $lp -1);
- $parameter[$parameterTemp[0]]= $parameterTemp[1];
- }
- }
- }
- }
- $executedSnippets[$i]= $this->evalSnippet($snippets[$i]['snippet'], $parameter);
- if ($this->dumpSnippets == 1) {
- echo "<fieldset><legend><b>$snippetName</b></legend><textarea style='width:60%; height:200px'>" . htmlentities($executedSnippets[$i]) . "</textarea></fieldset><br />";
- }
- $documentSource= str_replace("[[" . $snippetName . $currentSnippetParams . "]]", $executedSnippets[$i], $documentSource);
- }
- }
- return $documentSource;
- }
- function makeFriendlyURL($pre, $suff, $alias) {
- $Alias = explode('/',$alias);
- $alias = array_pop($Alias);
- $dir = implode('/', $Alias);
- unset($Alias);
- return ($dir != '' ? "$dir/" : '') . $pre . $alias . $suff;
- }
- function rewriteUrls($documentSource) {
- // rewrite the urls
- if ($this->config['friendly_urls'] == 1) {
- $aliases= array ();
- foreach ($this->aliasListing as $item) {
- $aliases[$item['id']]= (strlen($item['path']) > 0 ? $item['path'] . '/' : '') . $item['alias'];
- }
- $in= '!\[\~([0-9]+)\~\]!ise'; // Use preg_replace with /e to make it evaluate PHP
- $isfriendly= ($this->config['friendly_alias_urls'] == 1 ? 1 : 0);
- $pref= $this->config['friendly_url_prefix'];
- $suff= $this->config['friendly_url_suffix'];
- $thealias= '$aliases[\\1]';
- $found_friendlyurl= "\$this->makeFriendlyURL('$pref','$suff',$thealias)";
- $not_found_friendlyurl= "\$this->makeFriendlyURL('$pref','$suff','" . '\\1' . "')";
- $out= "({$isfriendly} && isset({$thealias}) ? {$found_friendlyurl} : {$not_found_friendlyurl})";
- $documentSource= preg_replace($in, $out, $documentSource);
- } else {
- $in= '!\[\~([0-9]+)\~\]!is';
- $out= "index.php?id=" . '\1';
- $documentSource= preg_replace($in, $out, $documentSource);
- }
- return $documentSource;
- }
- /**
- * name: getDocumentObject - used by parser
- * desc: returns a document object - $method: alias, id
- */
- function getDocumentObject($method, $identifier) {
- $tblsc= $this->getFullTableName("site_content");
- $tbldg= $this->getFullTableName("document_groups");
- // get document groups for current user
- if ($docgrp= $this->getUserDocGroups())
- $docgrp= implode(",", $docgrp);
- // get document
- $access= ($this->isFrontend() ? "sc.privateweb=0" : "1='" . $_SESSION['mgrRole'] . "' OR sc.privatemgr=0") .
- (!$docgrp ? "" : " OR dg.document_group IN ($docgrp)");
- $sql= "SELECT sc.*
- FROM $tblsc sc
- LEFT JOIN $tbldg dg ON dg.document = sc.id
- WHERE sc." . $method . " = '" . $identifier . "'
- AND ($access) LIMIT 1;";
- $result= $this->db->query($sql);
- $rowCount= $this->recordCount($result);
- if ($rowCount < 1) {
- if ($this->config['unauthorized_page']) {
- // Fix for FS #375 - netnoise 2006/08/14
- if ($method != 'id')
- $identifier= $this->cleanDocumentIdentifier($identifier);
- if (!is_numeric($identifier) && array_key_exists($identifier, $this->documentListing)) {
- $identifier= $this->documentListing[$identifier];
- $method= 'id';
- }
- // check if file is not public
- $secrs= $this->dbQuery("SELECT id FROM $tbldg WHERE document = '" . $identifier . "' LIMIT 1;");
- if ($secrs)
- $seclimit= mysql_num_rows($secrs);
- }
- if ($seclimit > 0) {
- // match found but not publicly accessible, send the visitor to the unauthorized_page
- $this->sendUnauthorizedPage();
- exit; // stop here
- } else {
- $this->sendErrorPage();
- exit;
- }
- }
- # this is now the document :) #
- $documentObject= $this->fetchRow($result);
- // load TVs and merge with document - Orig by Apodigm - Docvars
- $sql= "SELECT tv.*, IF(tvc.value!='',tvc.value,tv.default_text) as value ";
- $sql .= "FROM " . $this->getFullTableName("site_tmplvars") . " tv ";
- $sql .= "INNER JOIN " . $this->getFullTableName("site_tmplvar_templates")." tvtpl ON tvtpl.tmplvarid = tv.id ";
- $sql .= "LEFT JOIN " . $this->getFullTableName("site_tmplvar_contentvalues")." tvc ON tvc.tmplvarid=tv.id AND tvc.contentid = '" . $documentObject['id'] . "' ";
- $sql .= "WHERE tvtpl.templateid = '" . $documentObject['template'] . "'";
- $rs= $this->dbQuery($sql);
- $rowCount= $this->recordCount($rs);
- if ($rowCount > 0) {
- for ($i= 0; $i < $rowCount; $i++) {
- $row= $this->fetchRow($rs);
- $tmplvars[$row['name']]= array (
- $row['name'],
- $row['value'],
- $row['display'],
- $row['display_params'],
- $row['type']
- );
- }
- $documentObject= array_merge($documentObject, $tmplvars);
- }
- return $documentObject;
- }
- /**
- * name: parseDocumentSource - used by parser
- * desc: return document source aftering parsing tvs, snippets, chunks, etc.
- */
- function parseDocumentSource($source) {
- // set the number of times we are to parse the document source
- $this->minParserPasses= empty ($this->minParserPasses) ? 2 : $this->minParserPasses;
- $this->maxParserPasses= empty ($this->maxParserPasses) ? 10 : $this->maxParserPasses;
- $passes= $this->minParserPasses;
- for ($i= 0; $i < $passes; $i++) {
- // get source length if this is the final pass
- if ($i == ($passes -1))
- $st= strlen($source);
- if ($this->dumpSnippets == 1) {
- echo "<fieldset><legend><b style='color: #821517;'>PARSE PASS " . ($i +1) . "</b></legend>The following snippets (if any) were parsed during this pass.<div style='width:100%' align='center'>";
- }
- // invoke OnParseDocument event
- $this->documentOutput= $source; // store source code so plugins can
- $this->invokeEvent("OnParseDocument"); // work on it via $modx->documentOutput
- $source= $this->documentOutput;
- // combine template and document variables
- $source= $this->mergeDocumentContent($source);
- // replace settings referenced in document
- $source= $this->mergeSettingsContent($source);
- // replace HTMLSnippets in document
- $source= $this->mergeChunkContent($source);
- // insert META tags & keywords
- $source= $this->mergeDocumentMETATags($source);
- // find and merge snippets
- $source= $this->evalSnippets($source);
- // find and replace Placeholders (must be parsed last) - Added by Raymond
- $source= $this->mergePlaceholderContent($source);
- if ($this->dumpSnippets == 1) {
- echo "</div></fieldset><br />";
- }
- if ($i == ($passes -1) && $i < ($this->maxParserPasses - 1)) {
- // check if source length was changed
- $et= strlen($source);
- if ($st != $et)
- $passes++; // if content change then increase passes because
- } // we have not yet reached maxParserPasses
- }
- return $source;
- }
- function executeParser() {
- //error_reporting(0);
- if (version_compare(phpversion(), "5.0.0", ">="))
- set_error_handler(array (
- & $this,
- "phpError"
- ), E_ALL);
- else
- set_error_handler(array (
- & $this,
- "phpError"
- ));
- $this->db->connect();
- // get the settings
- if (empty ($this->config)) {
- $this->getSettings();
- }
- // IIS friendly url fix
- if ($this->config['friendly_urls'] == 1 && strpos($_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS') !== false) {
- $url= $_SERVER['QUERY_STRING'];
- $err= substr($url, 0, 3);
- if ($err == '404' || $err == '405') {
- $k= array_keys($_GET);
- unset ($_GET[$k[0]]);
- unset ($_REQUEST[$k[0]]); // remove 404,405 entry
- $_SERVER['QUERY_STRING']= $qp['query'];
- $qp= parse_url(str_replace($this->config['site_url'], '', substr($url, 4)));
- if (!empty ($qp['query'])) {
- parse_str($qp['query'], $qv);
- foreach ($qv as $n => $v)
- $_REQUEST[$n]= $_GET[$n]= $v;
- }
- $_SERVER['PHP_SELF']= $this->config['base_url'] . $qp['path'];
- $_REQUEST['q']= $_GET['q']= $qp['path'];
- }
- }
- // check site settings
- if (!$this->checkSiteStatus()) {
- header('HTTP/1.0 503 Service Unavailable');
- if (!$this->config['site_unavailable_page']) {
- // display offline message
- $this->documentContent= $this->config['site_unavailable_message'];
- $this->outputContent();
- exit; // stop processing here, as the site's offline
- } else {
- // setup offline page document settings
- $this->documentMethod= "id";
- $this->documentIdentifier= $this->config['site_unavailable_page'];
- }
- } else {
- // make sure the cache doesn't need updating
- $this->checkPublishStatus();
- // find out which document we need to display
- $this->documentMethod= $this->getDocumentMethod();
- $this->documentIdentifier= $this->getDocumentIdentifier($this->documentMethod);
- }
- if ($this->documentMethod == "none") {
- $this->documentMethod= "id"; // now we know the site_start, change the none method to id
- }
- if ($this->documentMethod == "alias") {
- $this->documentIdentifier= $this->cleanDocumentIdentifier($this->documentIdentifier);
- }
- if ($this->documentMethod == "alias") {
- // Check use_alias_path and check if $this->virtualDir is set to anything, then parse the path
- if ($this->config['use_alias_path'] == 1) {
- $alias= (strlen($this->virtualDir) > 0 ? $this->virtualDir . '/' : '') . $this->documentIdentifier;
- if (array_key_exists($alias, $this->documentListing)) {
- $this->documentIdentifier= $this->documentListing[$alias];
- } else {
- $this->sendErrorPage();
- }
- } else {
- $this->documentIdentifier= $this->documentListing[$this->documentIdentifier];
- }
- $this->documentMethod= 'id';
- }
- // invoke OnWebPageInit event
- $this->invokeEvent("OnWebPageInit");
- // invoke OnLogPageView event
- if ($this->config['track_visitors'] == 1) {
- $this->invokeEvent("OnLogPageHit");
- }
- $this->prepareResponse();
- }
- function prepareResponse() {
- // we now know the method and identifier, let's check the cache
- $this->documentContent= $this->checkCache($this->documentIdentifier);
- if ($this->documentContent != "") {
- // invoke OnLoadWebPageCache event
- $this->invokeEvent("OnLoadWebPageCache");
- } else {
- // get document object
- $this->documentObject= $this->getDocumentObject($this->documentMethod, $this->documentIdentifier);
- // write the documentName to…
Large files files are truncated, but you can click here to view the full file