PageRenderTime 57ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/manager/cacheextender/orig/document.parser.class.inc.php

https://github.com/good-web-master/modx.evo.custom
PHP | 2884 lines | 2423 code | 213 blank | 248 comment | 589 complexity | 744655921c001c01b362ba6476c44646 MD5 | raw file
Possible License(s): LGPL-2.1, AGPL-1.0, GPL-2.0, MIT, BSD-3-Clause

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /**
  3. * MODx Document Parser
  4. * Function: This class contains the main document parsing functions
  5. *
  6. */
  7. class DocumentParser {
  8. var $db; // db object
  9. var $event, $Event; // event object
  10. var $pluginEvent;
  11. var $config= null;
  12. var $rs;
  13. var $result;
  14. var $sql;
  15. var $table_prefix;
  16. var $debug;
  17. var $documentIdentifier;
  18. var $documentMethod;
  19. var $documentGenerated;
  20. var $documentContent;
  21. var $tstart;
  22. var $minParserPasses;
  23. var $maxParserPasses;
  24. var $documentObject;
  25. var $templateObject;
  26. var $snippetObjects;
  27. var $stopOnNotice;
  28. var $executedQueries;
  29. var $queryTime;
  30. var $currentSnippet;
  31. var $documentName;
  32. var $aliases;
  33. var $visitor;
  34. var $entrypage;
  35. var $documentListing;
  36. var $dumpSnippets;
  37. var $chunkCache;
  38. var $snippetCache;
  39. var $contentTypes;
  40. var $dumpSQL;
  41. var $queryCode;
  42. var $virtualDir;
  43. var $placeholders;
  44. var $sjscripts;
  45. var $jscripts;
  46. var $loadedjscripts;
  47. var $documentMap;
  48. var $forwards= 3;
  49. // constructor
  50. function DocumentParser() {
  51. $this->loadExtension('DBAPI') or die('Could not load DBAPI class.'); // load DBAPI class
  52. $this->dbConfig= & $this->db->config; // alias for backward compatibility
  53. $this->jscripts= array ();
  54. $this->sjscripts= array ();
  55. $this->loadedjscripts= array ();
  56. // events
  57. $this->event= new SystemEvent();
  58. $this->Event= & $this->event; //alias for backward compatibility
  59. $this->pluginEvent= array ();
  60. // set track_errors ini variable
  61. @ ini_set("track_errors", "1"); // enable error tracking in $php_errormsg
  62. }
  63. // loads an extension from the extenders folder
  64. function loadExtension($extname) {
  65. global $database_type;
  66. switch ($extname) {
  67. // Database API
  68. case 'DBAPI' :
  69. if (!include_once MODX_BASE_PATH . 'manager/includes/extenders/dbapi.' . $database_type . '.class.inc.php')
  70. return false;
  71. $this->db= new DBAPI;
  72. return true;
  73. break;
  74. // Manager API
  75. case 'ManagerAPI' :
  76. if (!include_once MODX_BASE_PATH . 'manager/includes/extenders/manager.api.class.inc.php')
  77. return false;
  78. $this->manager= new ManagerAPI;
  79. return true;
  80. break;
  81. default :
  82. return false;
  83. }
  84. }
  85. function getMicroTime() {
  86. list ($usec, $sec)= explode(' ', microtime());
  87. return ((float) $usec + (float) $sec);
  88. }
  89. function sendRedirect($url, $count_attempts= 0, $type= '', $responseCode= '') {
  90. if (empty ($url)) {
  91. return false;
  92. } else {
  93. if ($count_attempts == 1) {
  94. // append the redirect count string to the url
  95. $currentNumberOfRedirects= isset ($_REQUEST['err']) ? $_REQUEST['err'] : 0;
  96. if ($currentNumberOfRedirects > 3) {
  97. $this->messageQuit('Redirection attempt failed - please ensure the document you\'re trying to redirect to exists. <p>Redirection URL: <i>' . $url . '</i></p>');
  98. } else {
  99. $currentNumberOfRedirects += 1;
  100. if (strpos($url, "?") > 0) {
  101. $url .= "&err=$currentNumberOfRedirects";
  102. } else {
  103. $url .= "?err=$currentNumberOfRedirects";
  104. }
  105. }
  106. }
  107. if ($type == 'REDIRECT_REFRESH') {
  108. $header= 'Refresh: 0;URL=' . $url;
  109. }
  110. elseif ($type == 'REDIRECT_META') {
  111. $header= '<META HTTP-EQUIV="Refresh" CONTENT="0; URL=' . $url . '" />';
  112. echo $header;
  113. exit;
  114. }
  115. elseif ($type == 'REDIRECT_HEADER' || empty ($type)) {
  116. // check if url has /$base_url
  117. global $base_url, $site_url;
  118. if (substr($url, 0, strlen($base_url)) == $base_url) {
  119. // append $site_url to make it work with Location:
  120. $url= $site_url . substr($url, strlen($base_url));
  121. }
  122. if (strpos($url, "\n") === false) {
  123. $header= 'Location: ' . $url;
  124. } else {
  125. $this->messageQuit('No newline allowed in redirect url.');
  126. }
  127. }
  128. if ($responseCode && (strpos($responseCode, '30') !== false)) {
  129. header($responseCode);
  130. }
  131. header($header);
  132. exit();
  133. }
  134. }
  135. function sendForward($id, $responseCode= '') {
  136. if ($this->forwards > 0) {
  137. $this->forwards= $this->forwards - 1;
  138. $this->documentIdentifier= $id;
  139. $this->documentMethod= 'id';
  140. $this->documentObject= $this->getDocumentObject('id', $id);
  141. if ($responseCode) {
  142. header($responseCode);
  143. }
  144. $this->prepareResponse();
  145. exit();
  146. } else {
  147. header('HTTP/1.0 500 Internal Server Error');
  148. die('<h1>ERROR: Too many forward attempts!</h1><p>The request could not be completed due to too many unsuccessful forward attempts.</p>');
  149. }
  150. }
  151. function sendErrorPage() {
  152. // invoke OnPageNotFound event
  153. $this->invokeEvent('OnPageNotFound');
  154. // $this->sendRedirect($this->makeUrl($this->config['error_page'], '', '&refurl=' . urlencode($_SERVER['PHP_SELF'] . '?' . $_SERVER['QUERY_STRING'])), 1);
  155. $this->sendForward($this->config['error_page'] ? $this->config['error_page'] : $this->config['site_start'], 'HTTP/1.0 404 Not Found');
  156. exit();
  157. }
  158. function sendUnauthorizedPage() {
  159. // invoke OnPageUnauthorized event
  160. $_REQUEST['refurl'] = $this->documentIdentifier;
  161. $this->invokeEvent('OnPageUnauthorized');
  162. if ($this->config['unauthorized_page']) {
  163. $unauthorizedPage= $this->config['unauthorized_page'];
  164. } elseif ($this->config['error_page']) {
  165. $unauthorizedPage= $this->config['error_page'];
  166. } else {
  167. $unauthorizedPage= $this->config['site_start'];
  168. }
  169. $this->sendForward($unauthorizedPage, 'HTTP/1.1 401 Unauthorized');
  170. exit();
  171. }
  172. // function to connect to the database
  173. // - deprecated use $modx->db->connect()
  174. function dbConnect() {
  175. $this->db->connect();
  176. $this->rs= $this->db->conn; // for compatibility
  177. }
  178. // function to query the database
  179. // - deprecated use $modx->db->query()
  180. function dbQuery($sql) {
  181. return $this->db->query($sql);
  182. }
  183. // function to count the number of rows in a record set
  184. function recordCount($rs) {
  185. return $this->db->getRecordCount($rs);
  186. }
  187. // - deprecated, use $modx->db->getRow()
  188. function fetchRow($rs, $mode= 'assoc') {
  189. return $this->db->getRow($rs, $mode);
  190. }
  191. // - deprecated, use $modx->db->getAffectedRows()
  192. function affectedRows($rs) {
  193. return $this->db->getAffectedRows($rs);
  194. }
  195. // - deprecated, use $modx->db->getInsertId()
  196. function insertId($rs) {
  197. return $this->db->getInsertId($rs);
  198. }
  199. // function to close a database connection
  200. // - deprecated, use $modx->db->disconnect()
  201. function dbClose() {
  202. $this->db->disconnect();
  203. }
  204. function getSettings() {
  205. if (!is_array($this->config) || empty ($this->config)) {
  206. if ($included= file_exists(MODX_BASE_PATH . 'assets/cache/siteCache.idx.php')) {
  207. $included= include_once (MODX_BASE_PATH . 'assets/cache/siteCache.idx.php');
  208. }
  209. if (!$included || !is_array($this->config) || empty ($this->config)) {
  210. include_once MODX_BASE_PATH . "/manager/processors/cache_sync.class.processor.php";
  211. $cache = new synccache();
  212. $cache->setCachepath(MODX_BASE_PATH . "/assets/cache/");
  213. $cache->setReport(false);
  214. $rebuilt = $cache->buildCache($this);
  215. $included = false;
  216. if($rebuilt && $included= file_exists(MODX_BASE_PATH . 'assets/cache/siteCache.idx.php')) {
  217. $included= include MODX_BASE_PATH . 'assets/cache/siteCache.idx.php';
  218. }
  219. if(!$included) {
  220. $result= $this->db->query('SELECT setting_name, setting_value FROM ' . $this->getFullTableName('system_settings'));
  221. while ($row= $this->db->getRow($result, 'both')) {
  222. $this->config[$row[0]]= $row[1];
  223. }
  224. }
  225. }
  226. // added for backwards compatibility - garry FS#104
  227. $this->config['etomite_charset'] = & $this->config['modx_charset'];
  228. // store base_url and base_path inside config array
  229. $this->config['base_url']= MODX_BASE_URL;
  230. $this->config['base_path']= MODX_BASE_PATH;
  231. $this->config['site_url']= MODX_SITE_URL;
  232. // load user setting if user is logged in
  233. $usrSettings= array ();
  234. if ($id= $this->getLoginUserID()) {
  235. $usrType= $this->getLoginUserType();
  236. if (isset ($usrType) && $usrType == 'manager')
  237. $usrType= 'mgr';
  238. if ($usrType == 'mgr' && $this->isBackend()) {
  239. // invoke the OnBeforeManagerPageInit event, only if in backend
  240. $this->invokeEvent("OnBeforeManagerPageInit");
  241. }
  242. if (isset ($_SESSION[$usrType . 'UsrConfigSet'])) {
  243. $usrSettings= & $_SESSION[$usrType . 'UsrConfigSet'];
  244. } else {
  245. if ($usrType == 'web')
  246. $query= $this->getFullTableName('web_user_settings') . ' WHERE webuser=\'' . $id . '\'';
  247. else
  248. $query= $this->getFullTableName('user_settings') . ' WHERE user=\'' . $id . '\'';
  249. $result= $this->db->query('SELECT setting_name, setting_value FROM ' . $query);
  250. while ($row= $this->db->getRow($result, 'both'))
  251. $usrSettings[$row[0]]= $row[1];
  252. if (isset ($usrType))
  253. $_SESSION[$usrType . 'UsrConfigSet']= $usrSettings; // store user settings in session
  254. }
  255. }
  256. if ($this->isFrontend() && $mgrid= $this->getLoginUserID('mgr')) {
  257. $musrSettings= array ();
  258. if (isset ($_SESSION['mgrUsrConfigSet'])) {
  259. $musrSettings= & $_SESSION['mgrUsrConfigSet'];
  260. } else {
  261. $query= $this->getFullTableName('user_settings') . ' WHERE user=\'' . $mgrid . '\'';
  262. if ($result= $this->db->query('SELECT setting_name, setting_value FROM ' . $query)) {
  263. while ($row= $this->db->getRow($result, 'both')) {
  264. $usrSettings[$row[0]]= $row[1];
  265. }
  266. $_SESSION['mgrUsrConfigSet']= $musrSettings; // store user settings in session
  267. }
  268. }
  269. if (!empty ($musrSettings)) {
  270. $usrSettings= array_merge($musrSettings, $usrSettings);
  271. }
  272. }
  273. $this->config= array_merge($this->config, $usrSettings);
  274. }
  275. }
  276. function getDocumentMethod() {
  277. // function to test the query and find the retrieval method
  278. if (isset ($_REQUEST['q'])) {
  279. return "alias";
  280. }
  281. elseif (isset ($_REQUEST['id'])) {
  282. return "id";
  283. } else {
  284. return "none";
  285. }
  286. }
  287. function getDocumentIdentifier($method) {
  288. // function to test the query and find the retrieval method
  289. $docIdentifier= $this->config['site_start'];
  290. switch ($method) {
  291. case 'alias' :
  292. $docIdentifier= $this->db->escape($_REQUEST['q']);
  293. break;
  294. case 'id' :
  295. if (!is_numeric($_REQUEST['id'])) {
  296. $this->sendErrorPage();
  297. } else {
  298. $docIdentifier= intval($_REQUEST['id']);
  299. }
  300. break;
  301. }
  302. return $docIdentifier;
  303. }
  304. // check for manager login session
  305. function checkSession() {
  306. if (isset ($_SESSION['mgrValidated'])) {
  307. return true;
  308. } else {
  309. return false;
  310. }
  311. }
  312. function checkPreview() {
  313. if ($this->checkSession() == true) {
  314. if (isset ($_REQUEST['z']) && $_REQUEST['z'] == 'manprev') {
  315. return true;
  316. } else {
  317. return false;
  318. }
  319. } else {
  320. return false;
  321. }
  322. }
  323. // check if site is offline
  324. function checkSiteStatus() {
  325. $siteStatus= $this->config['site_status'];
  326. if ($siteStatus == 1) {
  327. // site online
  328. return true;
  329. }
  330. elseif ($siteStatus == 0 && $this->checkSession()) {
  331. // site offline but launched via the manager
  332. return true;
  333. } else {
  334. // site is offline
  335. return false;
  336. }
  337. }
  338. function cleanDocumentIdentifier($qOrig) {
  339. (!empty($qOrig)) or $qOrig = $this->config['site_start'];
  340. $q= $qOrig;
  341. /* First remove any / before or after */
  342. if ($q[strlen($q) - 1] == '/')
  343. $q= substr($q, 0, -1);
  344. if ($q[0] == '/')
  345. $q= substr($q, 1);
  346. /* Save path if any */
  347. /* FS#476 and FS#308: only return virtualDir if friendly paths are enabled */
  348. if ($this->config['use_alias_path'] == 1) {
  349. $this->virtualDir= dirname($q);
  350. $this->virtualDir= ($this->virtualDir == '.' ? '' : $this->virtualDir);
  351. $q= basename($q);
  352. } else {
  353. $this->virtualDir= '';
  354. }
  355. $q= str_replace($this->config['friendly_url_prefix'], "", $q);
  356. $q= str_replace($this->config['friendly_url_suffix'], "", $q);
  357. if (is_numeric($q) && !$this->documentListing[$q]) { /* we got an ID returned, check to make sure it's not an alias */
  358. /* FS#476 and FS#308: check that id is valid in terms of virtualDir structure */
  359. if ($this->config['use_alias_path'] == 1) {
  360. 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))))) {
  361. $this->documentMethod= 'id';
  362. return $q;
  363. } else { /* not a valid id in terms of virtualDir, treat as alias */
  364. $this->documentMethod= 'alias';
  365. return $q;
  366. }
  367. } else {
  368. $this->documentMethod= 'id';
  369. return $q;
  370. }
  371. } else { /* we didn't get an ID back, so instead we assume it's an alias */
  372. if ($this->config['friendly_alias_urls'] != 1) {
  373. $q= $qOrig;
  374. }
  375. $this->documentMethod= 'alias';
  376. return $q;
  377. }
  378. }
  379. function checkCache($id) {
  380. $cacheFile= "assets/cache/docid_" . $id . ".pageCache.php";
  381. if (file_exists($cacheFile)) {
  382. $this->documentGenerated= 0;
  383. $flContent= implode("", file($cacheFile));
  384. $flContent= substr($flContent, 37); // remove php header
  385. $a= explode("<!--__MODxCacheSpliter__-->", $flContent, 2);
  386. if (count($a) == 1)
  387. return $a[0]; // return only document content
  388. else {
  389. $docObj= unserialize($a[0]); // rebuild document object
  390. // check page security
  391. if ($docObj['privateweb'] && isset ($docObj['__MODxDocGroups__'])) {
  392. $pass= false;
  393. $usrGrps= $this->getUserDocGroups();
  394. $docGrps= explode(",", $docObj['__MODxDocGroups__']);
  395. // check is user has access to doc groups
  396. if (is_array($usrGrps)) {
  397. foreach ($usrGrps as $k => $v)
  398. if (in_array($v, $docGrps)) {
  399. $pass= true;
  400. break;
  401. }
  402. }
  403. // diplay error pages if user has no access to cached doc
  404. if (!$pass) {
  405. if ($this->config['unauthorized_page']) {
  406. // check if file is not public
  407. $tbldg= $this->getFullTableName("document_groups");
  408. $secrs= $this->db->query("SELECT id FROM $tbldg WHERE document = '" . $id . "' LIMIT 1;");
  409. if ($secrs)
  410. $seclimit= mysql_num_rows($secrs);
  411. }
  412. if ($seclimit > 0) {
  413. // match found but not publicly accessible, send the visitor to the unauthorized_page
  414. $this->sendUnauthorizedPage();
  415. exit; // stop here
  416. } else {
  417. // no match found, send the visitor to the error_page
  418. $this->sendErrorPage();
  419. exit; // stop here
  420. }
  421. }
  422. }
  423. // Grab the Scripts
  424. if (isset($docObj['__MODxSJScripts__'])) $this->sjscripts = $docObj['__MODxSJScripts__'];
  425. if (isset($docObj['__MODxJScripts__'])) $this->jscripts = $docObj['__MODxJScripts__'];
  426. // Remove intermediate variables
  427. unset($docObj['__MODxDocGroups__'], $docObj['__MODxSJScripts__'], $docObj['__MODxJScripts__']);
  428. $this->documentObject= $docObj;
  429. return $a[1]; // return document content
  430. }
  431. } else {
  432. $this->documentGenerated= 1;
  433. return "";
  434. }
  435. }
  436. function outputContent($noEvent= false) {
  437. $this->documentOutput= $this->documentContent;
  438. if ($this->documentGenerated == 1 && $this->documentObject['cacheable'] == 1 && $this->documentObject['type'] == 'document' && $this->documentObject['published'] == 1) {
  439. if (!empty($this->sjscripts)) $this->documentObject['__MODxSJScripts__'] = $this->sjscripts;
  440. if (!empty($this->jscripts)) $this->documentObject['__MODxJScripts__'] = $this->jscripts;
  441. }
  442. // check for non-cached snippet output
  443. if (strpos($this->documentOutput, '[!') > -1) {
  444. $this->documentOutput= str_replace('[!', '[[', $this->documentOutput);
  445. $this->documentOutput= str_replace('!]', ']]', $this->documentOutput);
  446. // Parse document source
  447. $this->documentOutput= $this->parseDocumentSource($this->documentOutput);
  448. }
  449. // Moved from prepareResponse() by sirlancelot
  450. // Insert Startup jscripts & CSS scripts into template - template must have a <head> tag
  451. if ($js= $this->getRegisteredClientStartupScripts()) {
  452. // change to just before closing </head>
  453. // $this->documentContent = preg_replace("/(<head[^>]*>)/i", "\\1\n".$js, $this->documentContent);
  454. $this->documentOutput= preg_replace("/(<\/head>)/i", $js . "\n\\1", $this->documentOutput);
  455. }
  456. // Insert jscripts & html block into template - template must have a </body> tag
  457. if ($js= $this->getRegisteredClientScripts()) {
  458. $this->documentOutput= preg_replace("/(<\/body>)/i", $js . "\n\\1", $this->documentOutput);
  459. }
  460. // End fix by sirlancelot
  461. // remove all unused placeholders
  462. if (strpos($this->documentOutput, '[+') > -1) {
  463. $matches= array ();
  464. preg_match_all('~\[\+(.*?)\+\]~', $this->documentOutput, $matches);
  465. if ($matches[0])
  466. $this->documentOutput= str_replace($matches[0], '', $this->documentOutput);
  467. }
  468. $this->documentOutput= $this->rewriteUrls($this->documentOutput);
  469. // send out content-type and content-disposition headers
  470. if (IN_PARSER_MODE == "true") {
  471. $type= !empty ($this->contentTypes[$this->documentIdentifier]) ? $this->contentTypes[$this->documentIdentifier] : "text/html";
  472. header('Content-Type: ' . $type . '; charset=' . $this->config['modx_charset']);
  473. // if (($this->documentIdentifier == $this->config['error_page']) || $redirect_error)
  474. // header('HTTP/1.0 404 Not Found');
  475. if (!$this->checkPreview() && $this->documentObject['content_dispo'] == 1) {
  476. if ($this->documentObject['alias'])
  477. $name= $this->documentObject['alias'];
  478. else {
  479. // strip title of special characters
  480. $name= $this->documentObject['pagetitle'];
  481. $name= strip_tags($name);
  482. $name= strtolower($name);
  483. $name= preg_replace('/&.+?;/', '', $name); // kill entities
  484. $name= preg_replace('/[^\.%a-z0-9 _-]/', '', $name);
  485. $name= preg_replace('/\s+/', '-', $name);
  486. $name= preg_replace('|-+|', '-', $name);
  487. $name= trim($name, '-');
  488. }
  489. $header= 'Content-Disposition: attachment; filename=' . $name;
  490. header($header);
  491. }
  492. }
  493. $totalTime= ($this->getMicroTime() - $this->tstart);
  494. $queryTime= $this->queryTime;
  495. $phpTime= $totalTime - $queryTime;
  496. $queryTime= sprintf("%2.4f s", $queryTime);
  497. $totalTime= sprintf("%2.4f s", $totalTime);
  498. $phpTime= sprintf("%2.4f s", $phpTime);
  499. $source= $this->documentGenerated == 1 ? "database" : "cache";
  500. $queries= isset ($this->executedQueries) ? $this->executedQueries : 0;
  501. $out =& $this->documentOutput;
  502. if ($this->dumpSQL) {
  503. $out .= $this->queryCode;
  504. }
  505. $out= str_replace("[^q^]", $queries, $out);
  506. $out= str_replace("[^qt^]", $queryTime, $out);
  507. $out= str_replace("[^p^]", $phpTime, $out);
  508. $out= str_replace("[^t^]", $totalTime, $out);
  509. $out= str_replace("[^s^]", $source, $out);
  510. //$this->documentOutput= $out;
  511. // invoke OnWebPagePrerender event
  512. if (!$noEvent) {
  513. $this->invokeEvent("OnWebPagePrerender");
  514. }
  515. echo $this->documentOutput;
  516. ob_end_flush();
  517. }
  518. function checkPublishStatus() {
  519. $cacheRefreshTime= 0;
  520. @include $this->config["base_path"] . "assets/cache/sitePublishing.idx.php";
  521. $timeNow= time() + $this->config['server_offset_time'];
  522. if ($cacheRefreshTime <= $timeNow && $cacheRefreshTime != 0) {
  523. // now, check for documents that need publishing
  524. $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";
  525. if (@ !$result= $this->db->query($sql)) {
  526. $this->messageQuit("Execution of a query to the database failed", $sql);
  527. }
  528. // now, check for documents that need un-publishing
  529. $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";
  530. if (@ !$result= $this->db->query($sql)) {
  531. $this->messageQuit("Execution of a query to the database failed", $sql);
  532. }
  533. // clear the cache
  534. $basepath= $this->config["base_path"] . "assets/cache/";
  535. if ($handle= opendir($basepath)) {
  536. $filesincache= 0;
  537. $deletedfilesincache= 0;
  538. while (false !== ($file= readdir($handle))) {
  539. if ($file != "." && $file != "..") {
  540. $filesincache += 1;
  541. if (preg_match("/\.pageCache/", $file)) {
  542. $deletedfilesincache += 1;
  543. while (!unlink($basepath . "/" . $file));
  544. }
  545. }
  546. }
  547. closedir($handle);
  548. }
  549. // update publish time file
  550. $timesArr= array ();
  551. $sql= "SELECT MIN(pub_date) AS minpub FROM " . $this->getFullTableName("site_content") . " WHERE pub_date>$timeNow";
  552. if (@ !$result= $this->db->query($sql)) {
  553. $this->messageQuit("Failed to find publishing timestamps", $sql);
  554. }
  555. $tmpRow= $this->db->getRow($result);
  556. $minpub= $tmpRow['minpub'];
  557. if ($minpub != NULL) {
  558. $timesArr[]= $minpub;
  559. }
  560. $sql= "SELECT MIN(unpub_date) AS minunpub FROM " . $this->getFullTableName("site_content") . " WHERE unpub_date>$timeNow";
  561. if (@ !$result= $this->db->query($sql)) {
  562. $this->messageQuit("Failed to find publishing timestamps", $sql);
  563. }
  564. $tmpRow= $this->db->getRow($result);
  565. $minunpub= $tmpRow['minunpub'];
  566. if ($minunpub != NULL) {
  567. $timesArr[]= $minunpub;
  568. }
  569. if (count($timesArr) > 0) {
  570. $nextevent= min($timesArr);
  571. } else {
  572. $nextevent= 0;
  573. }
  574. $basepath= $this->config["base_path"] . "assets/cache";
  575. $fp= @ fopen($basepath . "/sitePublishing.idx.php", "wb");
  576. if ($fp) {
  577. @ flock($fp, LOCK_EX);
  578. @ fwrite($fp, "<?php \$cacheRefreshTime=$nextevent; ?>");
  579. @ flock($fp, LOCK_UN);
  580. @ fclose($fp);
  581. }
  582. }
  583. }
  584. function postProcess() {
  585. // if the current document was generated, cache it!
  586. if ($this->documentGenerated == 1 && $this->documentObject['cacheable'] == 1 && $this->documentObject['type'] == 'document' && $this->documentObject['published'] == 1) {
  587. $basepath= $this->config["base_path"] . "assets/cache";
  588. // invoke OnBeforeSaveWebPageCache event
  589. $this->invokeEvent("OnBeforeSaveWebPageCache");
  590. if ($fp= @ fopen($basepath . "/docid_" . $this->documentIdentifier . ".pageCache.php", "w")) {
  591. // get and store document groups inside document object. Document groups will be used to check security on cache pages
  592. $sql= "SELECT document_group FROM " . $this->getFullTableName("document_groups") . " WHERE document='" . $this->documentIdentifier . "'";
  593. $docGroups= $this->db->getColumn("document_group", $sql);
  594. // Attach Document Groups and Scripts
  595. if (is_array($docGroups)) $this->documentObject['__MODxDocGroups__'] = implode(",", $docGroups);
  596. $docObjSerial= serialize($this->documentObject);
  597. $cacheContent= $docObjSerial . "<!--__MODxCacheSpliter__-->" . $this->documentContent;
  598. fputs($fp, "<?php die('Unauthorized access.'); ?>$cacheContent");
  599. fclose($fp);
  600. }
  601. }
  602. // Useful for example to external page counters/stats packages
  603. $this->invokeEvent('OnWebPageComplete');
  604. // end post processing
  605. }
  606. function mergeDocumentMETATags($template) {
  607. if ($this->documentObject['haskeywords'] == 1) {
  608. // insert keywords
  609. $keywords = $this->getKeywords();
  610. if (is_array($keywords) && count($keywords) > 0) {
  611. $keywords = implode(", ", $keywords);
  612. $metas= "\t<meta name=\"keywords\" content=\"$keywords\" />\n";
  613. }
  614. // Don't process when cached
  615. $this->documentObject['haskeywords'] = '0';
  616. }
  617. if ($this->documentObject['hasmetatags'] == 1) {
  618. // insert meta tags
  619. $tags= $this->getMETATags();
  620. foreach ($tags as $n => $col) {
  621. $tag= strtolower($col['tag']);
  622. $tagvalue= $col['tagvalue'];
  623. $tagstyle= $col['http_equiv'] ? 'http-equiv' : 'name';
  624. $metas .= "\t<meta $tagstyle=\"$tag\" content=\"$tagvalue\" />\n";
  625. }
  626. // Don't process when cached
  627. $this->documentObject['hasmetatags'] = '0';
  628. }
  629. if ($metas) $template = preg_replace("/(<head>)/i", "\\1\n\t" . trim($metas), $template);
  630. return $template;
  631. }
  632. // mod by Raymond
  633. function mergeDocumentContent($template) {
  634. $replace= array ();
  635. preg_match_all('~\[\*(.*?)\*\]~', $template, $matches);
  636. $variableCount= count($matches[1]);
  637. $basepath= $this->config["base_path"] . "manager/includes";
  638. for ($i= 0; $i < $variableCount; $i++) {
  639. $key= $matches[1][$i];
  640. $key= substr($key, 0, 1) == '#' ? substr($key, 1) : $key; // remove # for QuickEdit format
  641. $value= $this->documentObject[$key];
  642. if (is_array($value)) {
  643. include_once $basepath . "/tmplvars.format.inc.php";
  644. include_once $basepath . "/tmplvars.commands.inc.php";
  645. $w= "100%";
  646. $h= "300";
  647. $value= getTVDisplayFormat($value[0], $value[1], $value[2], $value[3], $value[4]);
  648. }
  649. $replace[$i]= $value;
  650. }
  651. $template= str_replace($matches[0], $replace, $template);
  652. return $template;
  653. }
  654. function mergeSettingsContent($template) {
  655. $replace= array ();
  656. $matches= array ();
  657. if (preg_match_all('~\[\(([a-z\_]*?)\)\]~', $template, $matches)) {
  658. $settingsCount= count($matches[1]);
  659. for ($i= 0; $i < $settingsCount; $i++) {
  660. if (array_key_exists($matches[1][$i], $this->config))
  661. $replace[$i]= $this->config[$matches[1][$i]];
  662. }
  663. $template= str_replace($matches[0], $replace, $template);
  664. }
  665. return $template;
  666. }
  667. function mergeChunkContent($content) {
  668. $replace= array ();
  669. $matches= array ();
  670. if (preg_match_all('~{{(.*?)}}~', $content, $matches)) {
  671. $settingsCount= count($matches[1]);
  672. for ($i= 0; $i < $settingsCount; $i++) {
  673. if (isset ($this->chunkCache[$matches[1][$i]])) {
  674. $replace[$i]= $this->chunkCache[$matches[1][$i]];
  675. } else {
  676. $sql= "SELECT `snippet` FROM " . $this->getFullTableName("site_htmlsnippets") . " WHERE " . $this->getFullTableName("site_htmlsnippets") . ".`name`='" . $this->db->escape($matches[1][$i]) . "';";
  677. $result= $this->db->query($sql);
  678. $limit= $this->db->getRecordCount($result);
  679. if ($limit < 1) {
  680. $this->chunkCache[$matches[1][$i]]= "";
  681. $replace[$i]= "";
  682. } else {
  683. $row= $this->db->getRow($result);
  684. $this->chunkCache[$matches[1][$i]]= $row['snippet'];
  685. $replace[$i]= $row['snippet'];
  686. }
  687. }
  688. }
  689. $content= str_replace($matches[0], $replace, $content);
  690. }
  691. return $content;
  692. }
  693. // Added by Raymond
  694. function mergePlaceholderContent($content) {
  695. $replace= array ();
  696. $matches= array ();
  697. if (preg_match_all('~\[\+(.*?)\+\]~', $content, $matches)) {
  698. $cnt= count($matches[1]);
  699. for ($i= 0; $i < $cnt; $i++) {
  700. $v= '';
  701. $key= $matches[1][$i];
  702. if (is_array($this->placeholders) && array_key_exists($key, $this->placeholders))
  703. $v= $this->placeholders[$key];
  704. if ($v === '')
  705. unset ($matches[0][$i]); // here we'll leave empty placeholders for last.
  706. else
  707. $replace[$i]= $v;
  708. }
  709. $content= str_replace($matches[0], $replace, $content);
  710. }
  711. return $content;
  712. }
  713. // evalPlugin
  714. function evalPlugin($pluginCode, $params) {
  715. $etomite= $modx= & $this;
  716. $modx->event->params= & $params; // store params inside event object
  717. if (is_array($params)) {
  718. extract($params, EXTR_SKIP);
  719. }
  720. ob_start();
  721. eval ($pluginCode);
  722. $msg= ob_get_contents();
  723. ob_end_clean();
  724. if ($msg && isset ($php_errormsg)) {
  725. if (!strpos($php_errormsg, 'Deprecated')) { // ignore php5 strict errors
  726. // log error
  727. $this->logEvent(1, 3, "<b>$php_errormsg</b><br /><br /> $msg", $this->Event->activePlugin . " - Plugin");
  728. if ($this->isBackend())
  729. $this->Event->alert("An error occurred while loading. Please see the event log for more information.<p />$msg");
  730. }
  731. } else {
  732. echo $msg;
  733. }
  734. unset ($modx->event->params);
  735. }
  736. function evalSnippet($snippet, $params) {
  737. $etomite= $modx= & $this;
  738. $modx->event->params= & $params; // store params inside event object
  739. if (is_array($params)) {
  740. extract($params, EXTR_SKIP);
  741. }
  742. ob_start();
  743. $snip= eval ($snippet);
  744. $msg= ob_get_contents();
  745. ob_end_clean();
  746. if ($msg && isset ($php_errormsg)) {
  747. if (!strpos($php_errormsg, 'Deprecated')) { // ignore php5 strict errors
  748. // log error
  749. $this->logEvent(1, 3, "<b>$php_errormsg</b><br /><br /> $msg", $this->currentSnippet . " - Snippet");
  750. if ($this->isBackend())
  751. $this->Event->alert("An error occurred while loading. Please see the event log for more information<p />$msg");
  752. }
  753. }
  754. unset ($modx->event->params);
  755. return $msg . $snip;
  756. }
  757. function evalSnippets($documentSource) {
  758. preg_match_all('~\[\[(.*?)\]\]~ms', $documentSource, $matches);
  759. $etomite= & $this;
  760. if ($matchCount= count($matches[1])) {
  761. for ($i= 0; $i < $matchCount; $i++) {
  762. $spos= strpos($matches[1][$i], '?', 0);
  763. if ($spos !== false) {
  764. $params= substr($matches[1][$i], $spos, strlen($matches[1][$i]));
  765. } else {
  766. $params= '';
  767. }
  768. $matches[1][$i]= str_replace($params, '', $matches[1][$i]);
  769. $snippetParams[$i]= $params;
  770. }
  771. $nrSnippetsToGet= $matchCount;
  772. for ($i= 0; $i < $nrSnippetsToGet; $i++) { // Raymond: Mod for Snippet props
  773. if (isset ($this->snippetCache[$matches[1][$i]])) {
  774. $snippets[$i]['name']= $matches[1][$i];
  775. $snippets[$i]['snippet']= $this->snippetCache[$matches[1][$i]];
  776. if (array_key_exists($matches[1][$i] . "Props", $this->snippetCache))
  777. $snippets[$i]['properties']= $this->snippetCache[$matches[1][$i] . "Props"];
  778. } else {
  779. // get from db and store a copy inside cache
  780. $sql= "SELECT `name`, `snippet`, `properties` FROM " . $this->getFullTableName("site_snippets") . " WHERE " . $this->getFullTableName("site_snippets") . ".`name`='" . $this->db->escape($matches[1][$i]) . "';";
  781. $result= $this->db->query($sql);
  782. $added = false;
  783. if ($this->db->getRecordCount($result) == 1) {
  784. $row= $this->db->getRow($result);
  785. if($row['name'] == $matches[1][$i]) {
  786. $snippets[$i]['name']= $row['name'];
  787. $snippets[$i]['snippet']= $this->snippetCache[$row['name']]= $row['snippet'];
  788. $snippets[$i]['properties']= $this->snippetCache[$row['name'] . "Props"]= $row['properties'];
  789. $added = true;
  790. }
  791. }
  792. if(!$added) {
  793. $snippets[$i]['name']= $matches[1][$i];
  794. $snippets[$i]['snippet']= $this->snippetCache[$matches[1][$i]]= "return false;";
  795. $snippets[$i]['properties']= '';
  796. }
  797. }
  798. }
  799. for ($i= 0; $i < $nrSnippetsToGet; $i++) {
  800. $parameter= array ();
  801. $snippetName= $this->currentSnippet= $snippets[$i]['name'];
  802. // FIXME Undefined index: properties
  803. if (array_key_exists('properties', $snippets[$i])) {
  804. $snippetProperties= $snippets[$i]['properties'];
  805. } else {
  806. $snippetProperties= '';
  807. }
  808. // load default params/properties - Raymond
  809. // FIXME Undefined variable: snippetProperties
  810. $parameter= $this->parseProperties($snippetProperties);
  811. // current params
  812. $currentSnippetParams= $snippetParams[$i];
  813. if (!empty ($currentSnippetParams)) {
  814. $tempSnippetParams= str_replace("?", "", $currentSnippetParams);
  815. $splitter= "&";
  816. if (strpos($tempSnippetParams, "&amp;") > 0)
  817. $tempSnippetParams= str_replace("&amp;", "&", $tempSnippetParams);
  818. //$tempSnippetParams = html_entity_decode($tempSnippetParams, ENT_NOQUOTES, $this->config['etomite_charset']); //FS#334 and FS#456
  819. $tempSnippetParams= explode($splitter, $tempSnippetParams);
  820. $snippetParamCount= count($tempSnippetParams);
  821. for ($x= 0; $x < $snippetParamCount; $x++) {
  822. if (strpos($tempSnippetParams[$x], '=', 0)) {
  823. if ($parameterTemp= explode("=", $tempSnippetParams[$x])) {
  824. $parameterTemp[0] = trim($parameterTemp[0]);
  825. $parameterTemp[1] = trim($parameterTemp[1]);
  826. $fp= strpos($parameterTemp[1], '`');
  827. $lp= strrpos($parameterTemp[1], '`');
  828. if (!($fp === false && $lp === false))
  829. $parameterTemp[1]= substr($parameterTemp[1], $fp +1, $lp -1);
  830. $parameter[$parameterTemp[0]]= $parameterTemp[1];
  831. }
  832. }
  833. }
  834. }
  835. $executedSnippets[$i]= $this->evalSnippet($snippets[$i]['snippet'], $parameter);
  836. if ($this->dumpSnippets == 1) {
  837. echo "<fieldset><legend><b>$snippetName</b></legend><textarea style='width:60%; height:200px'>" . htmlentities($executedSnippets[$i]) . "</textarea></fieldset><br />";
  838. }
  839. $documentSource= str_replace("[[" . $snippetName . $currentSnippetParams . "]]", $executedSnippets[$i], $documentSource);
  840. }
  841. }
  842. return $documentSource;
  843. }
  844. function makeFriendlyURL($pre, $suff, $alias) {
  845. $Alias = explode('/',$alias);
  846. $alias = array_pop($Alias);
  847. $dir = implode('/', $Alias);
  848. unset($Alias);
  849. return ($dir != '' ? "$dir/" : '') . $pre . $alias . $suff;
  850. }
  851. function rewriteUrls($documentSource) {
  852. // rewrite the urls
  853. if ($this->config['friendly_urls'] == 1) {
  854. $aliases= array ();
  855. foreach ($this->aliasListing as $item) {
  856. $aliases[$item['id']]= (strlen($item['path']) > 0 ? $item['path'] . '/' : '') . $item['alias'];
  857. }
  858. $in= '!\[\~([0-9]+)\~\]!ise'; // Use preg_replace with /e to make it evaluate PHP
  859. $isfriendly= ($this->config['friendly_alias_urls'] == 1 ? 1 : 0);
  860. $pref= $this->config['friendly_url_prefix'];
  861. $suff= $this->config['friendly_url_suffix'];
  862. $thealias= '$aliases[\\1]';
  863. $found_friendlyurl= "\$this->makeFriendlyURL('$pref','$suff',$thealias)";
  864. $not_found_friendlyurl= "\$this->makeFriendlyURL('$pref','$suff','" . '\\1' . "')";
  865. $out= "({$isfriendly} && isset({$thealias}) ? {$found_friendlyurl} : {$not_found_friendlyurl})";
  866. $documentSource= preg_replace($in, $out, $documentSource);
  867. } else {
  868. $in= '!\[\~([0-9]+)\~\]!is';
  869. $out= "index.php?id=" . '\1';
  870. $documentSource= preg_replace($in, $out, $documentSource);
  871. }
  872. return $documentSource;
  873. }
  874. /**
  875. * name: getDocumentObject - used by parser
  876. * desc: returns a document object - $method: alias, id
  877. */
  878. function getDocumentObject($method, $identifier) {
  879. $tblsc= $this->getFullTableName("site_content");
  880. $tbldg= $this->getFullTableName("document_groups");
  881. // allow alias to be full path
  882. if($method == 'alias') {
  883. $identifier = $this->cleanDocumentIdentifier($identifier);
  884. $method = $this->documentMethod;
  885. }
  886. if($method == 'alias' && $this->config['use_alias_path'] && array_key_exists($identifier, $this->documentListing)) {
  887. $method = 'id';
  888. $identifier = $this->documentListing[$identifier];
  889. }
  890. // get document groups for current user
  891. if ($docgrp= $this->getUserDocGroups())
  892. $docgrp= implode(",", $docgrp);
  893. // get document
  894. $access= ($this->isFrontend() ? "sc.privateweb=0" : "1='" . $_SESSION['mgrRole'] . "' OR sc.privatemgr=0") .
  895. (!$docgrp ? "" : " OR dg.document_group IN ($docgrp)");
  896. $sql= "SELECT sc.*
  897. FROM $tblsc sc
  898. LEFT JOIN $tbldg dg ON dg.document = sc.id
  899. WHERE sc." . $method . " = '" . $identifier . "'
  900. AND ($access) LIMIT 1;";
  901. $result= $this->db->query($sql);
  902. $rowCount= $this->db->getRecordCount($result);
  903. if ($rowCount < 1) {
  904. if ($this->config['unauthorized_page']) {
  905. // method may still be alias, while identifier is not full path alias, e.g. id not found above
  906. if ($method === 'alias') {
  907. $q = "SELECT dg.id FROM $tbldg dg, $tblsc sc WHERE dg.document = sc.id AND sc.alias = '{$identifier}' LIMIT 1;";
  908. } else {
  909. $q = "SELECT id FROM $tbldg WHERE document = '{$identifier}' LIMIT 1;";
  910. }
  911. // check if file is not public
  912. $secrs= $this->db->query($q);
  913. if ($secrs)
  914. $seclimit= mysql_num_rows($secrs);
  915. }
  916. if ($seclimit > 0) {
  917. // match found but not publicly accessible, send the visitor to the unauthorized_page
  918. $this->sendUnauthorizedPage();
  919. exit; // stop here
  920. } else {
  921. $this->sendErrorPage();
  922. exit;
  923. }
  924. }
  925. # this is now the document :) #
  926. $documentObject= $this->db->getRow($result);
  927. // load TVs and merge with document - Orig by Apodigm - Docvars
  928. $sql= "SELECT tv.*, IF(tvc.value!='',tvc.value,tv.default_text) as value ";
  929. $sql .= "FROM " . $this->getFullTableName("site_tmplvars") . " tv ";
  930. $sql .= "INNER JOIN " . $this->getFullTableName("site_tmplvar_templates")." tvtpl ON tvtpl.tmplvarid = tv.id ";
  931. $sql .= "LEFT JOIN " . $this->getFullTableName("site_tmplvar_contentvalues")." tvc ON tvc.tmplvarid=tv.id AND tvc.contentid = '" . $documentObject['id'] . "' ";
  932. $sql .= "WHERE tvtpl.templateid = '" . $documentObject['template'] . "'";
  933. $rs= $this->db->query($sql);
  934. $rowCount= $this->db->getRecordCount($rs);
  935. if ($rowCount > 0) {
  936. for ($i= 0; $i < $rowCount; $i++) {
  937. $row= $this->db->getRow($rs);
  938. $tmplvars[$row['name']]= array (
  939. $row['name'],
  940. $row['value'],
  941. $row['display'],
  942. $row['display_params'],
  943. $row['type']
  944. );
  945. }
  946. $documentObject= array_merge($documentObject, $tmplvars);
  947. }
  948. return $documentObject;
  949. }
  950. /**
  951. * name: parseDocumentSource - used by parser
  952. * desc: return document source aftering parsing tvs, snippets, chunks, etc.
  953. */
  954. function parseDocumentSource($source) {
  955. // set the number of times we are to parse the document source
  956. $this->minParserPasses= empty ($this->minParserPasses) ? 2 : $this->minParserPasses;
  957. $this->maxParserPasses= empty ($this->maxParserPasses) ? 10 : $this->maxParserPasses;
  958. $passes= $this->minParserPasses;
  959. for ($i= 0; $i < $passes; $i++) {
  960. // get source length if this is the final pass
  961. if ($i == ($passes -1))
  962. $st= strlen($source);
  963. if ($this->dumpSnippets == 1) {
  964. 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'>";
  965. }
  966. // invoke OnParseDocument event
  967. $this->documentOutput= $source; // store source code so plugins can
  968. $this->invokeEvent("OnParseDocument"); // work on it via $modx->documentOutput
  969. $source= $this->documentOutput;
  970. // combine template and document variables
  971. $source= $this->mergeDocumentContent($source);
  972. // replace settings referenced in document
  973. $source= $this->mergeSettingsContent($source);
  974. // replace HTMLSnippets in document
  975. $source= $this->mergeChunkContent($source);
  976. // insert META tags & keywords
  977. $source= $this->mergeDocumentMETATags($source);
  978. // find and merge snippets
  979. $source= $this->evalSnippets($source);
  980. // find and replace Placeholders (must be parsed last) - Added by Raymond
  981. $source= $this->mergePlaceholderContent($source);
  982. if ($this->dumpSnippets == 1) {
  983. echo "</div></fieldset><br />";
  984. }
  985. if ($i == ($passes -1) && $i < ($this->maxParserPasses - 1)) {
  986. // check if source length was changed
  987. $et= strlen($source);
  988. if ($st != $et)
  989. $passes++; // if content change then increase passes because
  990. } // we have not yet reached maxParserPasses
  991. }
  992. return $source;
  993. }
  994. function executeParser() {
  995. //error_reporting(0);
  996. if (version_compare(phpversion(), "5.0.0", ">="))
  997. set_error_handler(array (
  998. & $this,
  999. "phpError"
  1000. ), E_ALL);
  1001. else
  1002. set_error_handler(array (
  1003. & $this,
  1004. "phpError"
  1005. ));
  1006. $this->db->connect();
  1007. // get the settings
  1008. if (empty ($this->config)) {
  1009. $this->getSettings();
  1010. }
  1011. // IIS friendly url fix
  1012. if ($this->config['friendly_urls'] == 1 && strpos($_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS') !== false) {
  1013. $url= $_SERVER['QUERY_STRING'];
  1014. $err= substr($url, 0, 3);
  1015. if ($err == '404' || $err == '405') {
  1016. $k= array_keys($_GET);
  1017. unset ($_GET[$k[0]]);
  1018. unset ($_REQUEST[$k[0]]); // remove 404,405 entry
  1019. $_SERVER['QUERY_STRING']= $qp['query'];
  1020. $qp= parse_url(str_replace($this->config['site_url'], '', substr($url, 4)));
  1021. if (!empty ($qp['query'])) {
  1022. parse_str($qp['query'], $qv);
  1023. foreach ($qv as $n => $v)
  1024. $_REQUEST[$n]= $_GET[$n]= $v;
  1025. }
  1026. $_SERVER['PHP_SELF']= $this->config['base_url'] . $qp['path'];
  1027. $_REQUEST['q']= $_GET['q']= $qp['path'];
  1028. }
  1029. }
  1030. // check site settings
  1031. if (!$this->checkSiteStatus()) {

Large files files are truncated, but you can click here to view the full file