PageRenderTime 41ms CodeModel.GetById 42ms RepoModel.GetById 0ms app.codeStats 1ms

/manager/includes/document.parser.class.inc.php

https://github.com/HenrikNielsen/evolution
PHP | 2851 lines | 2388 code | 215 blank | 248 comment | 589 complexity | 449c38c80d0ee0bd5012b61a79b59a25 MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1, BSD-3-Clause, AGPL-1.0
  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, $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;
  13. var $forwards= 3;
  14. // constructor
  15. function DocumentParser() {
  16. $this->loadExtension('DBAPI') or die('Could not load DBAPI class.'); // load DBAPI class
  17. $this->dbConfig= & $this->db->config; // alias for backward compatibility
  18. $this->jscripts= array ();
  19. $this->sjscripts= array ();
  20. $this->loadedjscripts= array ();
  21. // events
  22. $this->event= new SystemEvent();
  23. $this->Event= & $this->event; //alias for backward compatibility
  24. $this->pluginEvent= array ();
  25. // set track_errors ini variable
  26. @ ini_set("track_errors", "1"); // enable error tracking in $php_errormsg
  27. }
  28. // loads an extension from the extenders folder
  29. function loadExtension($extname) {
  30. global $database_type;
  31. switch ($extname) {
  32. // Database API
  33. case 'DBAPI' :
  34. if (!include_once MODX_BASE_PATH . 'manager/includes/extenders/dbapi.' . $database_type . '.class.inc.php')
  35. return false;
  36. $this->db= new DBAPI;
  37. return true;
  38. break;
  39. // Manager API
  40. case 'ManagerAPI' :
  41. if (!include_once MODX_BASE_PATH . 'manager/includes/extenders/manager.api.class.inc.php')
  42. return false;
  43. $this->manager= new ManagerAPI;
  44. return true;
  45. break;
  46. default :
  47. return false;
  48. }
  49. }
  50. function getMicroTime() {
  51. list ($usec, $sec)= explode(' ', microtime());
  52. return ((float) $usec + (float) $sec);
  53. }
  54. function sendRedirect($url, $count_attempts= 0, $type= '', $responseCode= '') {
  55. if (empty ($url)) {
  56. return false;
  57. } else {
  58. if ($count_attempts == 1) {
  59. // append the redirect count string to the url
  60. $currentNumberOfRedirects= isset ($_REQUEST['err']) ? $_REQUEST['err'] : 0;
  61. if ($currentNumberOfRedirects > 3) {
  62. $this->messageQuit('Redirection attempt failed - please ensure the document you\'re trying to redirect to exists. <p>Redirection URL: <i>' . $url . '</i></p>');
  63. } else {
  64. $currentNumberOfRedirects += 1;
  65. if (strpos($url, "?") > 0) {
  66. $url .= "&err=$currentNumberOfRedirects";
  67. } else {
  68. $url .= "?err=$currentNumberOfRedirects";
  69. }
  70. }
  71. }
  72. if ($type == 'REDIRECT_REFRESH') {
  73. $header= 'Refresh: 0;URL=' . $url;
  74. }
  75. elseif ($type == 'REDIRECT_META') {
  76. $header= '<META HTTP-EQUIV="Refresh" CONTENT="0; URL=' . $url . '" />';
  77. echo $header;
  78. exit;
  79. }
  80. elseif ($type == 'REDIRECT_HEADER' || empty ($type)) {
  81. // check if url has /$base_url
  82. global $base_url, $site_url;
  83. if (substr($url, 0, strlen($base_url)) == $base_url) {
  84. // append $site_url to make it work with Location:
  85. $url= $site_url . substr($url, strlen($base_url));
  86. }
  87. if (strpos($url, "\n") === false) {
  88. $header= 'Location: ' . $url;
  89. } else {
  90. $this->messageQuit('No newline allowed in redirect url.');
  91. }
  92. }
  93. if ($responseCode && (strpos($responseCode, '30') !== false)) {
  94. header($responseCode);
  95. }
  96. header($header);
  97. exit();
  98. }
  99. }
  100. function sendForward($id, $responseCode= '') {
  101. if ($this->forwards > 0) {
  102. $this->forwards= $this->forwards - 1;
  103. $this->documentIdentifier= $id;
  104. $this->documentMethod= 'id';
  105. $this->documentObject= $this->getDocumentObject('id', $id);
  106. if ($responseCode) {
  107. header($responseCode);
  108. }
  109. $this->prepareResponse();
  110. exit();
  111. } else {
  112. header('HTTP/1.0 500 Internal Server Error');
  113. die('<h1>ERROR: Too many forward attempts!</h1><p>The request could not be completed due to too many unsuccessful forward attempts.</p>');
  114. }
  115. }
  116. function sendErrorPage() {
  117. // invoke OnPageNotFound event
  118. $this->invokeEvent('OnPageNotFound');
  119. // $this->sendRedirect($this->makeUrl($this->config['error_page'], '', '&refurl=' . urlencode($_SERVER['PHP_SELF'] . '?' . $_SERVER['QUERY_STRING'])), 1);
  120. $this->sendForward($this->config['error_page'] ? $this->config['error_page'] : $this->config['site_start'], 'HTTP/1.0 404 Not Found');
  121. exit();
  122. }
  123. function sendUnauthorizedPage() {
  124. // invoke OnPageUnauthorized event
  125. $_REQUEST['refurl'] = $this->documentIdentifier;
  126. $this->invokeEvent('OnPageUnauthorized');
  127. if ($this->config['unauthorized_page']) {
  128. $unauthorizedPage= $this->config['unauthorized_page'];
  129. } elseif ($this->config['error_page']) {
  130. $unauthorizedPage= $this->config['error_page'];
  131. } else {
  132. $unauthorizedPage= $this->config['site_start'];
  133. }
  134. $this->sendForward($unauthorizedPage, 'HTTP/1.1 401 Unauthorized');
  135. exit();
  136. }
  137. // function to connect to the database
  138. // - deprecated use $modx->db->connect()
  139. function dbConnect() {
  140. $this->db->connect();
  141. $this->rs= $this->db->conn; // for compatibility
  142. }
  143. // function to query the database
  144. // - deprecated use $modx->db->query()
  145. function dbQuery($sql) {
  146. return $this->db->query($sql);
  147. }
  148. // function to count the number of rows in a record set
  149. function recordCount($rs) {
  150. return $this->db->getRecordCount($rs);
  151. }
  152. // - deprecated, use $modx->db->getRow()
  153. function fetchRow($rs, $mode= 'assoc') {
  154. return $this->db->getRow($rs, $mode);
  155. }
  156. // - deprecated, use $modx->db->getAffectedRows()
  157. function affectedRows($rs) {
  158. return $this->db->getAffectedRows($rs);
  159. }
  160. // - deprecated, use $modx->db->getInsertId()
  161. function insertId($rs) {
  162. return $this->db->getInsertId($rs);
  163. }
  164. // function to close a database connection
  165. // - deprecated, use $modx->db->disconnect()
  166. function dbClose() {
  167. $this->db->disconnect();
  168. }
  169. function getSettings() {
  170. if (!is_array($this->config) || empty ($this->config)) {
  171. if ($included= file_exists(MODX_BASE_PATH . 'assets/cache/siteCache.idx.php')) {
  172. $included= include_once (MODX_BASE_PATH . 'assets/cache/siteCache.idx.php');
  173. }
  174. if (!$included || !is_array($this->config) || empty ($this->config)) {
  175. include_once MODX_BASE_PATH . "/manager/processors/cache_sync.class.processor.php";
  176. $cache = new synccache();
  177. $cache->setCachepath(MODX_BASE_PATH . "/assets/cache/");
  178. $cache->setReport(false);
  179. $rebuilt = $cache->buildCache($this);
  180. $included = false;
  181. if($rebuilt && $included= file_exists(MODX_BASE_PATH . 'assets/cache/siteCache.idx.php')) {
  182. $included= include MODX_BASE_PATH . 'assets/cache/siteCache.idx.php';
  183. }
  184. if(!$included) {
  185. $result= $this->db->query('SELECT setting_name, setting_value FROM ' . $this->getFullTableName('system_settings'));
  186. while ($row= $this->db->getRow($result, 'both')) {
  187. $this->config[$row[0]]= $row[1];
  188. }
  189. }
  190. }
  191. // added for backwards compatibility - garry FS#104
  192. $this->config['etomite_charset'] = & $this->config['modx_charset'];
  193. // store base_url and base_path inside config array
  194. $this->config['base_url']= MODX_BASE_URL;
  195. $this->config['base_path']= MODX_BASE_PATH;
  196. $this->config['site_url']= MODX_SITE_URL;
  197. // load user setting if user is logged in
  198. $usrSettings= array ();
  199. if ($id= $this->getLoginUserID()) {
  200. $usrType= $this->getLoginUserType();
  201. if (isset ($usrType) && $usrType == 'manager')
  202. $usrType= 'mgr';
  203. if ($usrType == 'mgr' && $this->isBackend()) {
  204. // invoke the OnBeforeManagerPageInit event, only if in backend
  205. $this->invokeEvent("OnBeforeManagerPageInit");
  206. }
  207. if (isset ($_SESSION[$usrType . 'UsrConfigSet'])) {
  208. $usrSettings= & $_SESSION[$usrType . 'UsrConfigSet'];
  209. } else {
  210. if ($usrType == 'web')
  211. $query= $this->getFullTableName('web_user_settings') . ' WHERE webuser=\'' . $id . '\'';
  212. else
  213. $query= $this->getFullTableName('user_settings') . ' WHERE user=\'' . $id . '\'';
  214. $result= $this->db->query('SELECT setting_name, setting_value FROM ' . $query);
  215. while ($row= $this->db->getRow($result, 'both'))
  216. $usrSettings[$row[0]]= $row[1];
  217. if (isset ($usrType))
  218. $_SESSION[$usrType . 'UsrConfigSet']= $usrSettings; // store user settings in session
  219. }
  220. }
  221. if ($this->isFrontend() && $mgrid= $this->getLoginUserID('mgr')) {
  222. $musrSettings= array ();
  223. if (isset ($_SESSION['mgrUsrConfigSet'])) {
  224. $musrSettings= & $_SESSION['mgrUsrConfigSet'];
  225. } else {
  226. $query= $this->getFullTableName('user_settings') . ' WHERE user=\'' . $mgrid . '\'';
  227. if ($result= $this->db->query('SELECT setting_name, setting_value FROM ' . $query)) {
  228. while ($row= $this->db->getRow($result, 'both')) {
  229. $usrSettings[$row[0]]= $row[1];
  230. }
  231. $_SESSION['mgrUsrConfigSet']= $musrSettings; // store user settings in session
  232. }
  233. }
  234. if (!empty ($musrSettings)) {
  235. $usrSettings= array_merge($musrSettings, $usrSettings);
  236. }
  237. }
  238. $this->config= array_merge($this->config, $usrSettings);
  239. }
  240. }
  241. function getDocumentMethod() {
  242. // function to test the query and find the retrieval method
  243. if (isset ($_REQUEST['q'])) {
  244. return "alias";
  245. }
  246. elseif (isset ($_REQUEST['id'])) {
  247. return "id";
  248. } else {
  249. return "none";
  250. }
  251. }
  252. function getDocumentIdentifier($method) {
  253. // function to test the query and find the retrieval method
  254. $docIdentifier= $this->config['site_start'];
  255. switch ($method) {
  256. case 'alias' :
  257. $docIdentifier= $this->db->escape($_REQUEST['q']);
  258. break;
  259. case 'id' :
  260. if (!is_numeric($_REQUEST['id'])) {
  261. $this->sendErrorPage();
  262. } else {
  263. $docIdentifier= intval($_REQUEST['id']);
  264. }
  265. break;
  266. }
  267. return $docIdentifier;
  268. }
  269. // check for manager login session
  270. function checkSession() {
  271. if (isset ($_SESSION['mgrValidated'])) {
  272. return true;
  273. } else {
  274. return false;
  275. }
  276. }
  277. function checkPreview() {
  278. if ($this->checkSession() == true) {
  279. if (isset ($_REQUEST['z']) && $_REQUEST['z'] == 'manprev') {
  280. return true;
  281. } else {
  282. return false;
  283. }
  284. } else {
  285. return false;
  286. }
  287. }
  288. // check if site is offline
  289. function checkSiteStatus() {
  290. $siteStatus= $this->config['site_status'];
  291. if ($siteStatus == 1) {
  292. // site online
  293. return true;
  294. }
  295. elseif ($siteStatus == 0 && $this->checkSession()) {
  296. // site offline but launched via the manager
  297. return true;
  298. } else {
  299. // site is offline
  300. return false;
  301. }
  302. }
  303. function cleanDocumentIdentifier($qOrig) {
  304. (!empty($qOrig)) or $qOrig = $this->config['site_start'];
  305. $q= $qOrig;
  306. /* First remove any / before or after */
  307. if ($q[strlen($q) - 1] == '/')
  308. $q= substr($q, 0, -1);
  309. if ($q[0] == '/')
  310. $q= substr($q, 1);
  311. /* Save path if any */
  312. /* FS#476 and FS#308: only return virtualDir if friendly paths are enabled */
  313. if ($this->config['use_alias_path'] == 1) {
  314. $this->virtualDir= dirname($q);
  315. $this->virtualDir= ($this->virtualDir == '.' ? '' : $this->virtualDir);
  316. $q= basename($q);
  317. } else {
  318. $this->virtualDir= '';
  319. }
  320. $q= str_replace($this->config['friendly_url_prefix'], "", $q);
  321. $q= str_replace($this->config['friendly_url_suffix'], "", $q);
  322. if (is_numeric($q) && !$this->documentListing[$q]) { /* we got an ID returned, check to make sure it's not an alias */
  323. /* FS#476 and FS#308: check that id is valid in terms of virtualDir structure */
  324. if ($this->config['use_alias_path'] == 1) {
  325. 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))))) {
  326. $this->documentMethod= 'id';
  327. return $q;
  328. } else { /* not a valid id in terms of virtualDir, treat as alias */
  329. $this->documentMethod= 'alias';
  330. return $q;
  331. }
  332. } else {
  333. $this->documentMethod= 'id';
  334. return $q;
  335. }
  336. } else { /* we didn't get an ID back, so instead we assume it's an alias */
  337. if ($this->config['friendly_alias_urls'] != 1) {
  338. $q= $qOrig;
  339. }
  340. $this->documentMethod= 'alias';
  341. return $q;
  342. }
  343. }
  344. function checkCache($id) {
  345. $cacheFile= "assets/cache/docid_" . $id . ".pageCache.php";
  346. if (file_exists($cacheFile)) {
  347. $this->documentGenerated= 0;
  348. $flContent= implode("", file($cacheFile));
  349. $flContent= substr($flContent, 37); // remove php header
  350. $a= explode("<!--__MODxCacheSpliter__-->", $flContent, 2);
  351. if (count($a) == 1)
  352. return $a[0]; // return only document content
  353. else {
  354. $docObj= unserialize($a[0]); // rebuild document object
  355. // check page security
  356. if ($docObj['privateweb'] && isset ($docObj['__MODxDocGroups__'])) {
  357. $pass= false;
  358. $usrGrps= $this->getUserDocGroups();
  359. $docGrps= explode(",", $docObj['__MODxDocGroups__']);
  360. // check is user has access to doc groups
  361. if (is_array($usrGrps)) {
  362. foreach ($usrGrps as $k => $v)
  363. if (in_array($v, $docGrps)) {
  364. $pass= true;
  365. break;
  366. }
  367. }
  368. // diplay error pages if user has no access to cached doc
  369. if (!$pass) {
  370. if ($this->config['unauthorized_page']) {
  371. // check if file is not public
  372. $tbldg= $this->getFullTableName("document_groups");
  373. $secrs= $this->db->query("SELECT id FROM $tbldg WHERE document = '" . $id . "' LIMIT 1;");
  374. if ($secrs)
  375. $seclimit= mysql_num_rows($secrs);
  376. }
  377. if ($seclimit > 0) {
  378. // match found but not publicly accessible, send the visitor to the unauthorized_page
  379. $this->sendUnauthorizedPage();
  380. exit; // stop here
  381. } else {
  382. // no match found, send the visitor to the error_page
  383. $this->sendErrorPage();
  384. exit; // stop here
  385. }
  386. }
  387. }
  388. // Grab the Scripts
  389. if (isset($docObj['__MODxSJScripts__'])) $this->sjscripts = $docObj['__MODxSJScripts__'];
  390. if (isset($docObj['__MODxJScripts__'])) $this->jscripts = $docObj['__MODxJScripts__'];
  391. // Remove intermediate variables
  392. unset($docObj['__MODxDocGroups__'], $docObj['__MODxSJScripts__'], $docObj['__MODxJScripts__']);
  393. $this->documentObject= $docObj;
  394. return $a[1]; // return document content
  395. }
  396. } else {
  397. $this->documentGenerated= 1;
  398. return "";
  399. }
  400. }
  401. function outputContent($noEvent= false) {
  402. $this->documentOutput= $this->documentContent;
  403. if ($this->documentGenerated == 1 && $this->documentObject['cacheable'] == 1 && $this->documentObject['type'] == 'document' && $this->documentObject['published'] == 1) {
  404. if (!empty($this->sjscripts)) $this->documentObject['__MODxSJScripts__'] = $this->sjscripts;
  405. if (!empty($this->jscripts)) $this->documentObject['__MODxJScripts__'] = $this->jscripts;
  406. }
  407. // check for non-cached snippet output
  408. if (strpos($this->documentOutput, '[!') > -1) {
  409. $this->documentOutput= str_replace('[!', '[[', $this->documentOutput);
  410. $this->documentOutput= str_replace('!]', ']]', $this->documentOutput);
  411. // Parse document source
  412. $this->documentOutput= $this->parseDocumentSource($this->documentOutput);
  413. }
  414. // Moved from prepareResponse() by sirlancelot
  415. // Insert Startup jscripts & CSS scripts into template - template must have a <head> tag
  416. if ($js= $this->getRegisteredClientStartupScripts()) {
  417. // change to just before closing </head>
  418. // $this->documentContent = preg_replace("/(<head[^>]*>)/i", "\\1\n".$js, $this->documentContent);
  419. $this->documentOutput= preg_replace("/(<\/head>)/i", $js . "\n\\1", $this->documentOutput);
  420. }
  421. // Insert jscripts & html block into template - template must have a </body> tag
  422. if ($js= $this->getRegisteredClientScripts()) {
  423. $this->documentOutput= preg_replace("/(<\/body>)/i", $js . "\n\\1", $this->documentOutput);
  424. }
  425. // End fix by sirlancelot
  426. // remove all unused placeholders
  427. if (strpos($this->documentOutput, '[+') > -1) {
  428. $matches= array ();
  429. preg_match_all('~\[\+(.*?)\+\]~', $this->documentOutput, $matches);
  430. if ($matches[0])
  431. $this->documentOutput= str_replace($matches[0], '', $this->documentOutput);
  432. }
  433. $this->documentOutput= $this->rewriteUrls($this->documentOutput);
  434. // send out content-type and content-disposition headers
  435. if (IN_PARSER_MODE == "true") {
  436. $type= !empty ($this->contentTypes[$this->documentIdentifier]) ? $this->contentTypes[$this->documentIdentifier] : "text/html";
  437. header('Content-Type: ' . $type . '; charset=' . $this->config['modx_charset']);
  438. // if (($this->documentIdentifier == $this->config['error_page']) || $redirect_error)
  439. // header('HTTP/1.0 404 Not Found');
  440. if (!$this->checkPreview() && $this->documentObject['content_dispo'] == 1) {
  441. if ($this->documentObject['alias'])
  442. $name= $this->documentObject['alias'];
  443. else {
  444. // strip title of special characters
  445. $name= $this->documentObject['pagetitle'];
  446. $name= strip_tags($name);
  447. $name= strtolower($name);
  448. $name= preg_replace('/&.+?;/', '', $name); // kill entities
  449. $name= preg_replace('/[^\.%a-z0-9 _-]/', '', $name);
  450. $name= preg_replace('/\s+/', '-', $name);
  451. $name= preg_replace('|-+|', '-', $name);
  452. $name= trim($name, '-');
  453. }
  454. $header= 'Content-Disposition: attachment; filename=' . $name;
  455. header($header);
  456. }
  457. }
  458. $totalTime= ($this->getMicroTime() - $this->tstart);
  459. $queryTime= $this->queryTime;
  460. $phpTime= $totalTime - $queryTime;
  461. $queryTime= sprintf("%2.4f s", $queryTime);
  462. $totalTime= sprintf("%2.4f s", $totalTime);
  463. $phpTime= sprintf("%2.4f s", $phpTime);
  464. $source= $this->documentGenerated == 1 ? "database" : "cache";
  465. $queries= isset ($this->executedQueries) ? $this->executedQueries : 0;
  466. $out =& $this->documentOutput;
  467. if ($this->dumpSQL) {
  468. $out .= $this->queryCode;
  469. }
  470. $out= str_replace("[^q^]", $queries, $out);
  471. $out= str_replace("[^qt^]", $queryTime, $out);
  472. $out= str_replace("[^p^]", $phpTime, $out);
  473. $out= str_replace("[^t^]", $totalTime, $out);
  474. $out= str_replace("[^s^]", $source, $out);
  475. //$this->documentOutput= $out;
  476. // invoke OnWebPagePrerender event
  477. if (!$noEvent) {
  478. $this->invokeEvent("OnWebPagePrerender");
  479. }
  480. echo $this->documentOutput;
  481. ob_end_flush();
  482. }
  483. function checkPublishStatus() {
  484. $cacheRefreshTime= 0;
  485. @include $this->config["base_path"] . "assets/cache/sitePublishing.idx.php";
  486. $timeNow= time() + $this->config['server_offset_time'];
  487. if ($cacheRefreshTime <= $timeNow && $cacheRefreshTime != 0) {
  488. // now, check for documents that need publishing
  489. $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";
  490. if (@ !$result= $this->db->query($sql)) {
  491. $this->messageQuit("Execution of a query to the database failed", $sql);
  492. }
  493. // now, check for documents that need un-publishing
  494. $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";
  495. if (@ !$result= $this->db->query($sql)) {
  496. $this->messageQuit("Execution of a query to the database failed", $sql);
  497. }
  498. // clear the cache
  499. $basepath= $this->config["base_path"] . "assets/cache/";
  500. if ($handle= opendir($basepath)) {
  501. $filesincache= 0;
  502. $deletedfilesincache= 0;
  503. while (false !== ($file= readdir($handle))) {
  504. if ($file != "." && $file != "..") {
  505. $filesincache += 1;
  506. if (preg_match("/\.pageCache/", $file)) {
  507. $deletedfilesincache += 1;
  508. while (!unlink($basepath . "/" . $file));
  509. }
  510. }
  511. }
  512. closedir($handle);
  513. }
  514. // update publish time file
  515. $timesArr= array ();
  516. $sql= "SELECT MIN(pub_date) AS minpub FROM " . $this->getFullTableName("site_content") . " WHERE pub_date>$timeNow";
  517. if (@ !$result= $this->db->query($sql)) {
  518. $this->messageQuit("Failed to find publishing timestamps", $sql);
  519. }
  520. $tmpRow= $this->db->getRow($result);
  521. $minpub= $tmpRow['minpub'];
  522. if ($minpub != NULL) {
  523. $timesArr[]= $minpub;
  524. }
  525. $sql= "SELECT MIN(unpub_date) AS minunpub FROM " . $this->getFullTableName("site_content") . " WHERE unpub_date>$timeNow";
  526. if (@ !$result= $this->db->query($sql)) {
  527. $this->messageQuit("Failed to find publishing timestamps", $sql);
  528. }
  529. $tmpRow= $this->db->getRow($result);
  530. $minunpub= $tmpRow['minunpub'];
  531. if ($minunpub != NULL) {
  532. $timesArr[]= $minunpub;
  533. }
  534. if (count($timesArr) > 0) {
  535. $nextevent= min($timesArr);
  536. } else {
  537. $nextevent= 0;
  538. }
  539. $basepath= $this->config["base_path"] . "assets/cache";
  540. $fp= @ fopen($basepath . "/sitePublishing.idx.php", "wb");
  541. if ($fp) {
  542. @ flock($fp, LOCK_EX);
  543. @ fwrite($fp, "<?php \$cacheRefreshTime=$nextevent; ?>");
  544. @ flock($fp, LOCK_UN);
  545. @ fclose($fp);
  546. }
  547. }
  548. }
  549. function postProcess() {
  550. // if the current document was generated, cache it!
  551. if ($this->documentGenerated == 1 && $this->documentObject['cacheable'] == 1 && $this->documentObject['type'] == 'document' && $this->documentObject['published'] == 1) {
  552. $basepath= $this->config["base_path"] . "assets/cache";
  553. // invoke OnBeforeSaveWebPageCache event
  554. $this->invokeEvent("OnBeforeSaveWebPageCache");
  555. if ($fp= @ fopen($basepath . "/docid_" . $this->documentIdentifier . ".pageCache.php", "w")) {
  556. // get and store document groups inside document object. Document groups will be used to check security on cache pages
  557. $sql= "SELECT document_group FROM " . $this->getFullTableName("document_groups") . " WHERE document='" . $this->documentIdentifier . "'";
  558. $docGroups= $this->db->getColumn("document_group", $sql);
  559. // Attach Document Groups and Scripts
  560. if (is_array($docGroups)) $this->documentObject['__MODxDocGroups__'] = implode(",", $docGroups);
  561. $docObjSerial= serialize($this->documentObject);
  562. $cacheContent= $docObjSerial . "<!--__MODxCacheSpliter__-->" . $this->documentContent;
  563. fputs($fp, "<?php die('Unauthorized access.'); ?>$cacheContent");
  564. fclose($fp);
  565. }
  566. }
  567. // Useful for example to external page counters/stats packages
  568. $this->invokeEvent('OnWebPageComplete');
  569. // end post processing
  570. }
  571. function mergeDocumentMETATags($template) {
  572. if ($this->documentObject['haskeywords'] == 1) {
  573. // insert keywords
  574. $keywords = $this->getKeywords();
  575. if (is_array($keywords) && count($keywords) > 0) {
  576. $keywords = implode(", ", $keywords);
  577. $metas= "\t<meta name=\"keywords\" content=\"$keywords\" />\n";
  578. }
  579. // Don't process when cached
  580. $this->documentObject['haskeywords'] = '0';
  581. }
  582. if ($this->documentObject['hasmetatags'] == 1) {
  583. // insert meta tags
  584. $tags= $this->getMETATags();
  585. foreach ($tags as $n => $col) {
  586. $tag= strtolower($col['tag']);
  587. $tagvalue= $col['tagvalue'];
  588. $tagstyle= $col['http_equiv'] ? 'http-equiv' : 'name';
  589. $metas .= "\t<meta $tagstyle=\"$tag\" content=\"$tagvalue\" />\n";
  590. }
  591. // Don't process when cached
  592. $this->documentObject['hasmetatags'] = '0';
  593. }
  594. if ($metas) $template = preg_replace("/(<head>)/i", "\\1\n\t" . trim($metas), $template);
  595. return $template;
  596. }
  597. // mod by Raymond
  598. function mergeDocumentContent($template) {
  599. $replace= array ();
  600. preg_match_all('~\[\*(.*?)\*\]~', $template, $matches);
  601. $variableCount= count($matches[1]);
  602. $basepath= $this->config["base_path"] . "manager/includes";
  603. for ($i= 0; $i < $variableCount; $i++) {
  604. $key= $matches[1][$i];
  605. $key= substr($key, 0, 1) == '#' ? substr($key, 1) : $key; // remove # for QuickEdit format
  606. $value= $this->documentObject[$key];
  607. if (is_array($value)) {
  608. include_once $basepath . "/tmplvars.format.inc.php";
  609. include_once $basepath . "/tmplvars.commands.inc.php";
  610. $w= "100%";
  611. $h= "300";
  612. $value= getTVDisplayFormat($value[0], $value[1], $value[2], $value[3], $value[4]);
  613. }
  614. $replace[$i]= $value;
  615. }
  616. $template= str_replace($matches[0], $replace, $template);
  617. return $template;
  618. }
  619. function mergeSettingsContent($template) {
  620. $replace= array ();
  621. $matches= array ();
  622. if (preg_match_all('~\[\(([a-z\_]*?)\)\]~', $template, $matches)) {
  623. $settingsCount= count($matches[1]);
  624. for ($i= 0; $i < $settingsCount; $i++) {
  625. if (array_key_exists($matches[1][$i], $this->config))
  626. $replace[$i]= $this->config[$matches[1][$i]];
  627. }
  628. $template= str_replace($matches[0], $replace, $template);
  629. }
  630. return $template;
  631. }
  632. function mergeChunkContent($content) {
  633. $replace= array ();
  634. $matches= array ();
  635. if (preg_match_all('~{{(.*?)}}~', $content, $matches)) {
  636. $settingsCount= count($matches[1]);
  637. for ($i= 0; $i < $settingsCount; $i++) {
  638. if (isset ($this->chunkCache[$matches[1][$i]])) {
  639. $replace[$i]= $this->chunkCache[$matches[1][$i]];
  640. } else {
  641. $sql= "SELECT `snippet` FROM " . $this->getFullTableName("site_htmlsnippets") . " WHERE " . $this->getFullTableName("site_htmlsnippets") . ".`name`='" . $this->db->escape($matches[1][$i]) . "';";
  642. $result= $this->db->query($sql);
  643. $limit= $this->db->getRecordCount($result);
  644. if ($limit < 1) {
  645. $this->chunkCache[$matches[1][$i]]= "";
  646. $replace[$i]= "";
  647. } else {
  648. $row= $this->db->getRow($result);
  649. $this->chunkCache[$matches[1][$i]]= $row['snippet'];
  650. $replace[$i]= $row['snippet'];
  651. }
  652. }
  653. }
  654. $content= str_replace($matches[0], $replace, $content);
  655. }
  656. return $content;
  657. }
  658. // Added by Raymond
  659. function mergePlaceholderContent($content) {
  660. $replace= array ();
  661. $matches= array ();
  662. if (preg_match_all('~\[\+(.*?)\+\]~', $content, $matches)) {
  663. $cnt= count($matches[1]);
  664. for ($i= 0; $i < $cnt; $i++) {
  665. $v= '';
  666. $key= $matches[1][$i];
  667. if (is_array($this->placeholders) && array_key_exists($key, $this->placeholders))
  668. $v= $this->placeholders[$key];
  669. if ($v === '')
  670. unset ($matches[0][$i]); // here we'll leave empty placeholders for last.
  671. else
  672. $replace[$i]= $v;
  673. }
  674. $content= str_replace($matches[0], $replace, $content);
  675. }
  676. return $content;
  677. }
  678. // evalPlugin
  679. function evalPlugin($pluginCode, $params) {
  680. $etomite= $modx= & $this;
  681. $modx->event->params= & $params; // store params inside event object
  682. if (is_array($params)) {
  683. extract($params, EXTR_SKIP);
  684. }
  685. ob_start();
  686. eval ($pluginCode);
  687. $msg= ob_get_contents();
  688. ob_end_clean();
  689. if ($msg && isset ($php_errormsg)) {
  690. if (!strpos($php_errormsg, 'Deprecated')) { // ignore php5 strict errors
  691. // log error
  692. $this->logEvent(1, 3, "<b>$php_errormsg</b><br /><br /> $msg", $this->Event->activePlugin . " - Plugin");
  693. if ($this->isBackend())
  694. $this->Event->alert("An error occurred while loading. Please see the event log for more information.<p />$msg");
  695. }
  696. } else {
  697. echo $msg;
  698. }
  699. unset ($modx->event->params);
  700. }
  701. function evalSnippet($snippet, $params) {
  702. $etomite= $modx= & $this;
  703. $modx->event->params= & $params; // store params inside event object
  704. if (is_array($params)) {
  705. extract($params, EXTR_SKIP);
  706. }
  707. ob_start();
  708. $snip= eval ($snippet);
  709. $msg= ob_get_contents();
  710. ob_end_clean();
  711. if ($msg && isset ($php_errormsg)) {
  712. if (!strpos($php_errormsg, 'Deprecated')) { // ignore php5 strict errors
  713. // log error
  714. $this->logEvent(1, 3, "<b>$php_errormsg</b><br /><br /> $msg", $this->currentSnippet . " - Snippet");
  715. if ($this->isBackend())
  716. $this->Event->alert("An error occurred while loading. Please see the event log for more information<p />$msg");
  717. }
  718. }
  719. unset ($modx->event->params);
  720. return $msg . $snip;
  721. }
  722. function evalSnippets($documentSource) {
  723. preg_match_all('~\[\[(.*?)\]\]~ms', $documentSource, $matches);
  724. $etomite= & $this;
  725. if ($matchCount= count($matches[1])) {
  726. for ($i= 0; $i < $matchCount; $i++) {
  727. $spos= strpos($matches[1][$i], '?', 0);
  728. if ($spos !== false) {
  729. $params= substr($matches[1][$i], $spos, strlen($matches[1][$i]));
  730. } else {
  731. $params= '';
  732. }
  733. $matches[1][$i]= str_replace($params, '', $matches[1][$i]);
  734. $snippetParams[$i]= $params;
  735. }
  736. $nrSnippetsToGet= $matchCount;
  737. for ($i= 0; $i < $nrSnippetsToGet; $i++) { // Raymond: Mod for Snippet props
  738. if (isset ($this->snippetCache[$matches[1][$i]])) {
  739. $snippets[$i]['name']= $matches[1][$i];
  740. $snippets[$i]['snippet']= $this->snippetCache[$matches[1][$i]];
  741. if (array_key_exists($matches[1][$i] . "Props", $this->snippetCache))
  742. $snippets[$i]['properties']= $this->snippetCache[$matches[1][$i] . "Props"];
  743. } else {
  744. // get from db and store a copy inside cache
  745. $sql= "SELECT `name`, `snippet`, `properties` FROM " . $this->getFullTableName("site_snippets") . " WHERE " . $this->getFullTableName("site_snippets") . ".`name`='" . $this->db->escape($matches[1][$i]) . "';";
  746. $result= $this->db->query($sql);
  747. $added = false;
  748. if ($this->db->getRecordCount($result) == 1) {
  749. $row= $this->db->getRow($result);
  750. if($row['name'] == $matches[1][$i]) {
  751. $snippets[$i]['name']= $row['name'];
  752. $snippets[$i]['snippet']= $this->snippetCache[$row['name']]= $row['snippet'];
  753. $snippets[$i]['properties']= $this->snippetCache[$row['name'] . "Props"]= $row['properties'];
  754. $added = true;
  755. }
  756. }
  757. if(!$added) {
  758. $snippets[$i]['name']= $matches[1][$i];
  759. $snippets[$i]['snippet']= $this->snippetCache[$matches[1][$i]]= "return false;";
  760. $snippets[$i]['properties']= '';
  761. }
  762. }
  763. }
  764. for ($i= 0; $i < $nrSnippetsToGet; $i++) {
  765. $parameter= array ();
  766. $snippetName= $this->currentSnippet= $snippets[$i]['name'];
  767. // FIXME Undefined index: properties
  768. if (array_key_exists('properties', $snippets[$i])) {
  769. $snippetProperties= $snippets[$i]['properties'];
  770. } else {
  771. $snippetProperties= '';
  772. }
  773. // load default params/properties - Raymond
  774. // FIXME Undefined variable: snippetProperties
  775. $parameter= $this->parseProperties($snippetProperties);
  776. // current params
  777. $currentSnippetParams= $snippetParams[$i];
  778. if (!empty ($currentSnippetParams)) {
  779. $tempSnippetParams= str_replace("?", "", $currentSnippetParams);
  780. $splitter= "&";
  781. if (strpos($tempSnippetParams, "&amp;") > 0)
  782. $tempSnippetParams= str_replace("&amp;", "&", $tempSnippetParams);
  783. //$tempSnippetParams = html_entity_decode($tempSnippetParams, ENT_NOQUOTES, $this->config['etomite_charset']); //FS#334 and FS#456
  784. $tempSnippetParams= explode($splitter, $tempSnippetParams);
  785. $snippetParamCount= count($tempSnippetParams);
  786. for ($x= 0; $x < $snippetParamCount; $x++) {
  787. if (strpos($tempSnippetParams[$x], '=', 0)) {
  788. if ($parameterTemp= explode("=", $tempSnippetParams[$x])) {
  789. $parameterTemp[0] = trim($parameterTemp[0]);
  790. $parameterTemp[1] = trim($parameterTemp[1]);
  791. $fp= strpos($parameterTemp[1], '`');
  792. $lp= strrpos($parameterTemp[1], '`');
  793. if (!($fp === false && $lp === false))
  794. $parameterTemp[1]= substr($parameterTemp[1], $fp +1, $lp -1);
  795. $parameter[$parameterTemp[0]]= $parameterTemp[1];
  796. }
  797. }
  798. }
  799. }
  800. $executedSnippets[$i]= $this->evalSnippet($snippets[$i]['snippet'], $parameter);
  801. if ($this->dumpSnippets == 1) {
  802. echo "<fieldset><legend><b>$snippetName</b></legend><textarea style='width:60%; height:200px'>" . htmlentities($executedSnippets[$i]) . "</textarea></fieldset><br />";
  803. }
  804. $documentSource= str_replace("[[" . $snippetName . $currentSnippetParams . "]]", $executedSnippets[$i], $documentSource);
  805. }
  806. }
  807. return $documentSource;
  808. }
  809. function makeFriendlyURL($pre, $suff, $alias) {
  810. $Alias = explode('/',$alias);
  811. $alias = array_pop($Alias);
  812. $dir = implode('/', $Alias);
  813. unset($Alias);
  814. return ($dir != '' ? "$dir/" : '') . $pre . $alias . $suff;
  815. }
  816. function rewriteUrls($documentSource) {
  817. // rewrite the urls
  818. if ($this->config['friendly_urls'] == 1) {
  819. $aliases= array ();
  820. foreach ($this->aliasListing as $item) {
  821. $aliases[$item['id']]= (strlen($item['path']) > 0 ? $item['path'] . '/' : '') . $item['alias'];
  822. }
  823. $in= '!\[\~([0-9]+)\~\]!ise'; // Use preg_replace with /e to make it evaluate PHP
  824. $isfriendly= ($this->config['friendly_alias_urls'] == 1 ? 1 : 0);
  825. $pref= $this->config['friendly_url_prefix'];
  826. $suff= $this->config['friendly_url_suffix'];
  827. $thealias= '$aliases[\\1]';
  828. $found_friendlyurl= "\$this->makeFriendlyURL('$pref','$suff',$thealias)";
  829. $not_found_friendlyurl= "\$this->makeFriendlyURL('$pref','$suff','" . '\\1' . "')";
  830. $out= "({$isfriendly} && isset({$thealias}) ? {$found_friendlyurl} : {$not_found_friendlyurl})";
  831. $documentSource= preg_replace($in, $out, $documentSource);
  832. } else {
  833. $in= '!\[\~([0-9]+)\~\]!is';
  834. $out= "index.php?id=" . '\1';
  835. $documentSource= preg_replace($in, $out, $documentSource);
  836. }
  837. return $documentSource;
  838. }
  839. /**
  840. * name: getDocumentObject - used by parser
  841. * desc: returns a document object - $method: alias, id
  842. */
  843. function getDocumentObject($method, $identifier) {
  844. $tblsc= $this->getFullTableName("site_content");
  845. $tbldg= $this->getFullTableName("document_groups");
  846. // allow alias to be full path
  847. if($method == 'alias') {
  848. $identifier = $this->cleanDocumentIdentifier($identifier);
  849. $method = $this->documentMethod;
  850. }
  851. if($method == 'alias' && $this->config['use_alias_path'] && array_key_exists($identifier, $this->documentListing)) {
  852. $method = 'id';
  853. $identifier = $this->documentListing[$identifier];
  854. }
  855. // get document groups for current user
  856. if ($docgrp= $this->getUserDocGroups())
  857. $docgrp= implode(",", $docgrp);
  858. // get document
  859. $access= ($this->isFrontend() ? "sc.privateweb=0" : "1='" . $_SESSION['mgrRole'] . "' OR sc.privatemgr=0") .
  860. (!$docgrp ? "" : " OR dg.document_group IN ($docgrp)");
  861. $sql= "SELECT sc.*
  862. FROM $tblsc sc
  863. LEFT JOIN $tbldg dg ON dg.document = sc.id
  864. WHERE sc." . $method . " = '" . $identifier . "'
  865. AND ($access) LIMIT 1;";
  866. $result= $this->db->query($sql);
  867. $rowCount= $this->db->getRecordCount($result);
  868. if ($rowCount < 1) {
  869. if ($this->config['unauthorized_page']) {
  870. // method may still be alias, while identifier is not full path alias, e.g. id not found above
  871. if ($method === 'alias') {
  872. $q = "SELECT dg.id FROM $tbldg dg, $tblsc sc WHERE dg.document = sc.id AND sc.alias = '{$identifier}' LIMIT 1;";
  873. } else {
  874. $q = "SELECT id FROM $tbldg WHERE document = '{$identifier}' LIMIT 1;";
  875. }
  876. // check if file is not public
  877. $secrs= $this->db->query($q);
  878. if ($secrs)
  879. $seclimit= mysql_num_rows($secrs);
  880. }
  881. if ($seclimit > 0) {
  882. // match found but not publicly accessible, send the visitor to the unauthorized_page
  883. $this->sendUnauthorizedPage();
  884. exit; // stop here
  885. } else {
  886. $this->sendErrorPage();
  887. exit;
  888. }
  889. }
  890. # this is now the document :) #
  891. $documentObject= $this->db->getRow($result);
  892. // load TVs and merge with document - Orig by Apodigm - Docvars
  893. $sql= "SELECT tv.*, IF(tvc.value!='',tvc.value,tv.default_text) as value ";
  894. $sql .= "FROM " . $this->getFullTableName("site_tmplvars") . " tv ";
  895. $sql .= "INNER JOIN " . $this->getFullTableName("site_tmplvar_templates")." tvtpl ON tvtpl.tmplvarid = tv.id ";
  896. $sql .= "LEFT JOIN " . $this->getFullTableName("site_tmplvar_contentvalues")." tvc ON tvc.tmplvarid=tv.id AND tvc.contentid = '" . $documentObject['id'] . "' ";
  897. $sql .= "WHERE tvtpl.templateid = '" . $documentObject['template'] . "'";
  898. $rs= $this->db->query($sql);
  899. $rowCount= $this->db->getRecordCount($rs);
  900. if ($rowCount > 0) {
  901. for ($i= 0; $i < $rowCount; $i++) {
  902. $row= $this->db->getRow($rs);
  903. $tmplvars[$row['name']]= array (
  904. $row['name'],
  905. $row['value'],
  906. $row['display'],
  907. $row['display_params'],
  908. $row['type']
  909. );
  910. }
  911. $documentObject= array_merge($documentObject, $tmplvars);
  912. }
  913. return $documentObject;
  914. }
  915. /**
  916. * name: parseDocumentSource - used by parser
  917. * desc: return document source aftering parsing tvs, snippets, chunks, etc.
  918. */
  919. function parseDocumentSource($source) {
  920. // set the number of times we are to parse the document source
  921. $this->minParserPasses= empty ($this->minParserPasses) ? 2 : $this->minParserPasses;
  922. $this->maxParserPasses= empty ($this->maxParserPasses) ? 10 : $this->maxParserPasses;
  923. $passes= $this->minParserPasses;
  924. for ($i= 0; $i < $passes; $i++) {
  925. // get source length if this is the final pass
  926. if ($i == ($passes -1))
  927. $st= strlen($source);
  928. if ($this->dumpSnippets == 1) {
  929. 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'>";
  930. }
  931. // invoke OnParseDocument event
  932. $this->documentOutput= $source; // store source code so plugins can
  933. $this->invokeEvent("OnParseDocument"); // work on it via $modx->documentOutput
  934. $source= $this->documentOutput;
  935. // combine template and document variables
  936. $source= $this->mergeDocumentContent($source);
  937. // replace settings referenced in document
  938. $source= $this->mergeSettingsContent($source);
  939. // replace HTMLSnippets in document
  940. $source= $this->mergeChunkContent($source);
  941. // insert META tags & keywords
  942. $source= $this->mergeDocumentMETATags($source);
  943. // find and merge snippets
  944. $source= $this->evalSnippets($source);
  945. // find and replace Placeholders (must be parsed last) - Added by Raymond
  946. $source= $this->mergePlaceholderContent($source);
  947. if ($this->dumpSnippets == 1) {
  948. echo "</div></fieldset><br />";
  949. }
  950. if ($i == ($passes -1) && $i < ($this->maxParserPasses - 1)) {
  951. // check if source length was changed
  952. $et= strlen($source);
  953. if ($st != $et)
  954. $passes++; // if content change then increase passes because
  955. } // we have not yet reached maxParserPasses
  956. }
  957. return $source;
  958. }
  959. function executeParser() {
  960. //error_reporting(0);
  961. if (version_compare(phpversion(), "5.0.0", ">="))
  962. set_error_handler(array (
  963. & $this,
  964. "phpError"
  965. ), E_ALL);
  966. else
  967. set_error_handler(array (
  968. & $this,
  969. "phpError"
  970. ));
  971. $this->db->connect();
  972. // get the settings
  973. if (empty ($this->config)) {
  974. $this->getSettings();
  975. }
  976. // IIS friendly url fix
  977. if ($this->config['friendly_urls'] == 1 && strpos($_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS') !== false) {
  978. $url= $_SERVER['QUERY_STRING'];
  979. $err= substr($url, 0, 3);
  980. if ($err == '404' || $err == '405') {
  981. $k= array_keys($_GET);
  982. unset ($_GET[$k[0]]);
  983. unset ($_REQUEST[$k[0]]); // remove 404,405 entry
  984. $_SERVER['QUERY_STRING']= $qp['query'];
  985. $qp= parse_url(str_replace($this->config['site_url'], '', substr($url, 4)));
  986. if (!empty ($qp['query'])) {
  987. parse_str($qp['query'], $qv);
  988. foreach ($qv as $n => $v)
  989. $_REQUEST[$n]= $_GET[$n]= $v;
  990. }
  991. $_SERVER['PHP_SELF']= $this->config['base_url'] . $qp['path'];
  992. $_REQUEST['q']= $_GET['q']= $qp['path'];
  993. }
  994. }
  995. // check site settings
  996. if (!$this->checkSiteStatus()) {
  997. header('HTTP/1.0 503 Service Unavailable');
  998. if (!$this->config['site_unavailable_page']) {
  999. // display offline message
  1000. $this->documentContent= $this->config['site_unavailable_message'];
  1001. $this->outputContent();
  1002. exit; // stop processing here, as the site's offline
  1003. } else {
  1004. // setup offline page document settings
  1005. $this->documentMethod= "id";
  1006. $this->documentIdentifier= $this->config['site_unavailable_page'];
  1007. }
  1008. } else {
  1009. // make sure the cache doesn't need updating
  1010. $this->checkPublishStatus();
  1011. // find out which document we need to display
  1012. $this->documentMethod= $this->getDocumentMethod();
  1013. $this->documentIdentifier= $this->getDocumentIdentifier($this->documentMethod);
  1014. }
  1015. if ($this->documentMethod == "none") {
  1016. $this->documentMethod= "id"; // now we know the site_start, change the none method to id
  1017. }
  1018. if ($this->documentMethod == "alias") {
  1019. $this->documentIdentifier= $this->cleanDocumentIdentifier($this->documentIdentifier);
  1020. }
  1021. if ($this->documentMethod == "alias") {
  1022. // Check use_alias_path and check if $this->virtualDir is set to anything, then parse the path
  1023. if ($this->config['use_alias_path'] == 1) {
  1024. $alias= (strlen($this->virtualDir) > 0 ? $this->virtualDir . '/' : '') . $this->documentIdentifier;
  1025. if (array_key_exists($alias, $this->documentListing)) {
  1026. $this->documentIdentifier= $this->documentListing[$alias];
  1027. } else {
  1028. $this->sendErrorPage();
  1029. }
  1030. } else {
  1031. $this->documentIdentifier= $this->documentListing[$this->documentIdentifier];
  1032. }
  1033. $this->documentMethod= 'id';
  1034. }
  1035. // invoke OnWebPageInit event
  1036. $this->invokeEvent("OnWebPageInit");
  1037. // invoke OnLogPageView event
  1038. if ($this->config['track_visitors'] == 1) {
  1039. $this->invokeEvent("OnLogPageHit");
  1040. }
  1041. $this->prepareResponse();
  1042. }
  1043. function prepareResponse() {
  1044. // we now know the method and identifier, let's check the cache
  1045. $this->documentContent= $this->checkCache($this->documentIdentifier);
  1046. if ($this->documentContent != "") {
  1047. // invoke OnLoadWebPageCache event
  1048. $this->invokeEvent("OnLoadWebPageCache");
  1049. } else {
  1050. // get document object
  1051. $this->documentObject= $this->getDocumentObject($this->documentMethod, $this->documentIdentifier);
  1052. // write the documentName to the object
  1053. $this->documentName= $this->documentObject['pagetitle'];
  1054. // validation routines
  1055. if ($this->documentObject['deleted'] == 1) {
  1056. $this->sendErrorPage();
  1057. }
  1058. // && !$this->checkPreview()
  1059. if ($this->documentObject['published'] == 0) {
  1060. // Can't view unpublished pages
  1061. if (!$this->hasPermission('view_unpublished')) {
  1062. $this->sendErrorPage();
  1063. } else {
  1064. // Inculde the necessary files to check document permissions
  1065. include_once ($this->config['base_path'] . '/manager/processors/user_documents_permissions.class.php');
  1066. $udperms= new udperms();
  1067. $udperms->user= $this->getLoginUserID();
  1068. $udperms->document= $this->documentIdentifier;
  1069. $udperms->role= $_SESSION['mgrRole'];
  1070. // Doesn't have access to this document
  1071. if (!$udperms->checkPermissions()) {
  1072. $this->sendErrorPage();
  1073. }
  1074. }
  1075. }
  1076. // check whether it's a reference
  1077. if ($this->documentObject['type'] == "reference") {
  1078. if (is_numeric($this->documentObject['content'])) {
  1079. // if it's a bare document id
  1080. $this->documentObject['content']= $this->makeUrl($this->documentObject['content']);
  1081. }
  1082. elseif (strpos($this->documentObject['content'], '[~') !== false) {
  1083. // if it's an internal docid tag, process it
  1084. $this->documentObject['content']= $this->rewriteUrls($this->documentObject['content']);
  1085. }
  1086. $this->sendRedirect($this->documentObject['content'], 0, '', 'HTTP/1.0 301 Moved Permanently');
  1087. }
  1088. // check if we should not hit this document
  1089. if ($this->documentObject['donthit'] == 1) {
  1090. $this->config['track_visitors']= 0;
  1091. }
  1092. // get the template and start parsing!
  1093. if (!$this->documentObject['template'])
  1094. $this->documentContent= "[*content*]"; // use blank template
  1095. else {
  1096. $sql= "SELECT `content` FROM " . $this->getFullTableName("site_templates") . " WHERE " . $this->getFullTableName("site_templates") . ".`id` = '" . $this->documentObject['template'] . "';";
  1097. $result= $this->db->query($sql);
  1098. $rowCount= $this->db->getRecordCount($result);
  1099. if ($rowCount > 1) {
  1100. $this->messageQuit("Incorrect number of templates returned from database", $sql);
  1101. }
  1102. elseif ($rowCount == 1) {
  1103. $row= $this->db->getRow($result);
  1104. $this->documentContent= $row['content'];
  1105. }
  1106. }
  1107. // invoke OnLoadWebDocument event
  1108. $this->invokeEvent("OnLoadWebDocument");
  1109. // Parse document source
  1110. $this->documentContent= $this->parseDocumentSource($this->documentContent);
  1111. // setup <base> tag for friendly urls
  1112. // if($this->config['friendly_urls']==1 && $this->config['use_alias_path']==1) {
  1113. // $this->regClientStartupHTMLBlock('<base href="'.$this->config['site_url'].'" />');
  1114. // }
  1115. }
  1116. register_shutdown_function(array (
  1117. & $this,
  1118. "postProcess"
  1119. )); // tell PHP to call postProcess when it shuts down
  1120. $this->outputContent();
  1121. //$this->postProcess();
  1122. }
  1123. /***************************************************************************************/
  1124. /* API functions /
  1125. /***************************************************************************************/
  1126. function getParentIds($id, $height= 10) {
  1127. $parents= array ();
  1128. while ( $id && $height-- ) {
  1129. $thisid = $id;
  1130. $id = $this->aliasListing[$id]['parent'];
  1131. if (!$id) break;
  1132. $pkey = strlen($this->aliasListing[$thisid]['path']) ? $this->aliasListing[$thisid]['path'] : $this->aliasListing[$id]['alias'];
  1133. if (!strlen($pkey)) $pkey = "{$id}";
  1134. $parents[$pkey] = $id;
  1135. }
  1136. return $parents;
  1137. }
  1138. function getChildIds($id, $depth= 10, $children= array ()) {
  1139. // Initialise a static array to index parents->children
  1140. static $documentMap_cache = array();
  1141. if (!count($documentMap_cache)) {
  1142. foreach ($this->documentMap as $document) {
  1143. foreach ($document as $p => $c) {
  1144. $documentMap_cache[$p][] = $c;
  1145. }
  1146. }
  1147. }
  1148. // Get all the children for this parent node
  1149. if (isset($documentMap_cache[$id])) {
  1150. $depth--;
  1151. foreach ($documentMap_cache[$id] as $childId) {
  1152. $pkey = (strlen($this->aliasListing[$childId]['path']) ? "{$this->aliasListing[$childId]['path']}/" : '') . $this->aliasListing[$childId]['alias'];
  1153. if (!strlen($pkey)) $pkey = "{$childId}";
  1154. $children[$pkey] = $childId;
  1155. if ($depth) {
  1156. $children += $this->getChildIds($childId, $depth);
  1157. }
  1158. }
  1159. }
  1160. return $children;
  1161. }
  1162. # Displays a javascript alert message in the web browser
  1163. function webAlert($msg, $url= "") {
  1164. $msg= addslashes($this->db->escape($msg));
  1165. if (substr(strtolower($url), 0, 11) == "javascript:") {
  1166. $act= "__WebAlert();";
  1167. $fnc= "function __WebAlert(){" . substr($url, 11) . "};";
  1168. } else {
  1169. $act= ($url ? "window.location.href='" . addslashes($url) . "';" : "");
  1170. }
  1171. $html= "<script>$fnc window.setTimeout(\"alert('$msg');$act\",100);</script>";
  1172. if ($this->isFrontend())
  1173. $this->regClientScript($html);
  1174. else {
  1175. echo $html;
  1176. }
  1177. }
  1178. # Returns true if user has the currect permission
  1179. function hasPermission($pm) {
  1180. $state= false;
  1181. $pms= $_SESSION['mgrPermissions'];
  1182. if ($pms)
  1183. $state= ($pms[$pm] == 1);
  1184. return $state;
  1185. }
  1186. # Add an a alert message to the system event log
  1187. function logEvent($evtid, $type, $msg, $source= 'Parser') {
  1188. $msg= $this->db->escape($msg);
  1189. $source= $this->db->escape($source);
  1190. if ($GLOBALS['database_connection_charset'] == 'utf8' && extension_loaded('mbstring')) {
  1191. $source = mb_substr($source, 0, 50 , "UTF-8");
  1192. } else {
  1193. $source = substr($source, 0, 50);
  1194. }
  1195. $LoginUserID = $this->getLoginUserID();
  1196. if ($LoginUserID == '') $LoginUserID = 0;
  1197. $evtid= intval($evtid);
  1198. if ($type < 1) {
  1199. $type= 1;
  1200. }
  1201. elseif ($type > 3) {
  1202. $type= 3; // Types: 1 = information, 2 = warning, 3 = error
  1203. }
  1204. $sql= "INSERT INTO " . $this->getFullTableName("event_log") . " (eventid,type,createdon,source,description,user) " .
  1205. "VALUES($evtid,$type," . time() . ",'$source','$msg','" . $LoginUserID . "')";
  1206. $ds= @$this->db->query($sql);
  1207. if (!$ds) {
  1208. echo "Error while inserting event log into database.";
  1209. exit();
  1210. }
  1211. }
  1212. # Returns true if parser is executed in backend (manager) mode
  1213. function isBackend() {
  1214. return $this->insideManager() ? true : false;
  1215. }
  1216. # Returns true if parser is executed in frontend mode
  1217. function isFrontend() {
  1218. return !$this->insideManager() ? true : false;
  1219. }
  1220. function getAllChildren($id= 0, $sort= 'menuindex', $dir= 'ASC', $fields= 'id, pagetitle, description, parent, alias, menutitle') {
  1221. $tblsc= $this->getFullTableName("site_content");
  1222. $tbldg= $this->getFullTableName("document_groups");
  1223. // modify field names to use sc. table reference
  1224. $fields= 'sc.' . implode(',sc.', preg_replace("/^\s/i", "", explode(',', $fields)));
  1225. $sort= 'sc.' . implode(',sc.', preg_replace("/^\s/i", "", explode(',', $sort)));
  1226. // get document groups for current user
  1227. if ($docgrp= $this->getUserDocGroups())
  1228. $docgrp= implode(",", $docgrp);
  1229. // build query
  1230. $access= ($this->isFrontend() ? "sc.privateweb=0" : "1='" . $_SESSION['mgrRole'] . "' OR sc.privatemgr=0") .
  1231. (!$docgrp ? "" : " OR dg.document_group IN ($docgrp)");
  1232. $sql= "SELECT DISTINCT $fields FROM $tblsc sc
  1233. LEFT JOIN $tbldg dg on dg.document = sc.id
  1234. WHERE sc.parent = '$id'
  1235. AND ($access)
  1236. GROUP BY sc.id
  1237. ORDER BY $sort $dir;";
  1238. $result= $this->db->query($sql);
  1239. $resourceArray= array ();
  1240. for ($i= 0; $i < @ $this->db->getRecordCount($result); $i++) {
  1241. array_push($resourceArray, @ $this->db->getRow($result));
  1242. }
  1243. return $resourceArray;
  1244. }
  1245. function getActiveChildren($id= 0, $sort= 'menuindex', $dir= 'ASC', $fields= 'id, pagetitle, description, parent, alias, menutitle') {
  1246. $tblsc= $this->getFullTableName("site_content");
  1247. $tbldg= $this->getFullTableName("document_groups");
  1248. // modify field names to use sc. table reference
  1249. $fields= 'sc.' . implode(',sc.', preg_replace("/^\s/i", "", explode(',', $fields)));
  1250. $sort= 'sc.' . implode(',sc.', preg_replace("/^\s/i", "", explode(',', $sort)));
  1251. // get document groups for current user
  1252. if ($docgrp= $this->getUserDocGroups())
  1253. $docgrp= implode(",", $docgrp);
  1254. // build query
  1255. $access= ($this->isFrontend() ? "sc.privateweb=0" : "1='" . $_SESSION['mgrRole'] . "' OR sc.privatemgr=0") .
  1256. (!$docgrp ? "" : " OR dg.document_group IN ($docgrp)");
  1257. $sql= "SELECT DISTINCT $fields FROM $tblsc sc
  1258. LEFT JOIN $tbldg dg on dg.document = sc.id
  1259. WHERE sc.parent = '$id' AND sc.published=1 AND sc.deleted=0
  1260. AND ($access)
  1261. GROUP BY sc.id
  1262. ORDER BY $sort $dir;";
  1263. $result= $this->db->query($sql);
  1264. $resourceArray= array ();
  1265. for ($i= 0; $i < @ $this->db->getRecordCount($result); $i++) {
  1266. array_push($resourceArray, @ $this->db->getRow($result));
  1267. }
  1268. return $resourceArray;
  1269. }
  1270. function getDocumentChildren($parentid= 0, $published= 1, $deleted= 0, $fields= "*", $where= '', $sort= "menuindex", $dir= "ASC", $limit= "") {
  1271. $limit= ($limit != "") ? "LIMIT $limit" : "";
  1272. $tblsc= $this->getFullTableName("site_content");
  1273. $tbldg= $this->getFullTableName("document_groups");
  1274. // modify field names to use sc. table reference
  1275. $fields= 'sc.' . implode(',sc.', preg_replace("/^\s/i", "", explode(',', $fields)));
  1276. $sort= ($sort == "") ? "" : 'sc.' . implode(',sc.', preg_replace("/^\s/i", "", explode(',', $sort)));
  1277. if ($where != '')
  1278. $where= 'AND ' . $where;
  1279. // get document groups for current user
  1280. if ($docgrp= $this->getUserDocGroups())
  1281. $docgrp= implode(",", $docgrp);
  1282. // build query
  1283. $access= ($this->isFrontend() ? "sc.privateweb=0" : "1='" . $_SESSION['mgrRole'] . "' OR sc.privatemgr=0") .
  1284. (!$docgrp ? "" : " OR dg.document_group IN ($docgrp)");
  1285. $sql= "SELECT DISTINCT $fields
  1286. FROM $tblsc sc
  1287. LEFT JOIN $tbldg dg on dg.document = sc.id
  1288. WHERE sc.parent = '$parentid' AND sc.published=$published AND sc.deleted=$deleted $where
  1289. AND ($access)
  1290. GROUP BY sc.id " .
  1291. ($sort ? " ORDER BY $sort $dir " : "") . " $limit ";
  1292. $result= $this->db->query($sql);
  1293. $resourceArray= array ();
  1294. for ($i= 0; $i < @ $this->db->getRecordCount($result); $i++) {
  1295. array_push($resourceArray, @ $this->db->getRow($result));
  1296. }
  1297. return $resourceArray;
  1298. }
  1299. function getDocuments($ids= array (), $published= 1, $deleted= 0, $fields= "*", $where= '', $sort= "menuindex", $dir= "ASC", $limit= "") {
  1300. if (count($ids) == 0) {
  1301. return false;
  1302. } else {
  1303. $limit= ($limit != "") ? "LIMIT $limit" : ""; // LIMIT capabilities - rad14701
  1304. $tblsc= $this->getFullTableName("site_content");
  1305. $tbldg= $this->getFullTableName("document_groups");
  1306. // modify field names to use sc. table reference
  1307. $fields= 'sc.' . implode(',sc.', preg_replace("/^\s/i", "", explode(',', $fields)));
  1308. $sort= ($sort == "") ? "" : 'sc.' . implode(',sc.', preg_replace("/^\s/i", "", explode(',', $sort)));
  1309. if ($where != '')
  1310. $where= 'AND ' . $where;
  1311. // get document groups for current user
  1312. if ($docgrp= $this->getUserDocGroups())
  1313. $docgrp= implode(",", $docgrp);
  1314. $access= ($this->isFrontend() ? "sc.privateweb=0" : "1='" . $_SESSION['mgrRole'] . "' OR sc.privatemgr=0") .
  1315. (!$docgrp ? "" : " OR dg.document_group IN ($docgrp)");
  1316. $sql= "SELECT DISTINCT $fields FROM $tblsc sc
  1317. LEFT JOIN $tbldg dg on dg.document = sc.id
  1318. WHERE (sc.id IN (" . implode(",",$ids) . ") AND sc.published=$published AND sc.deleted=$deleted $where)
  1319. AND ($access)
  1320. GROUP BY sc.id " .
  1321. ($sort ? " ORDER BY $sort $dir" : "") . " $limit ";
  1322. $result= $this->db->query($sql);
  1323. $resourceArray= array ();
  1324. for ($i= 0; $i < @ $this->db->getRecordCount($result); $i++) {
  1325. array_push($resourceArray, @ $this->db->getRow($result));
  1326. }
  1327. return $resourceArray;
  1328. }
  1329. }
  1330. function getDocument($id= 0, $fields= "*", $published= 1, $deleted= 0) {
  1331. if ($id == 0) {
  1332. return false;
  1333. } else {
  1334. $tmpArr[]= $id;
  1335. $docs= $this->getDocuments($tmpArr, $published, $deleted, $fields, "", "", "", 1);
  1336. if ($docs != false) {
  1337. return $docs[0];
  1338. } else {
  1339. return false;
  1340. }
  1341. }
  1342. }
  1343. function getPageInfo($pageid= -1, $active= 1, $fields= 'id, pagetitle, description, alias') {
  1344. if ($pageid == 0) {
  1345. return false;
  1346. } else {
  1347. $tblsc= $this->getFullTableName("site_content");
  1348. $tbldg= $this->getFullTableName("document_groups");
  1349. $activeSql= $active == 1 ? "AND sc.published=1 AND sc.deleted=0" : "";
  1350. // modify field names to use sc. table reference
  1351. $fields= 'sc.' . implode(',sc.', preg_replace("/^\s/i", "", explode(',', $fields)));
  1352. // get document groups for current user
  1353. if ($docgrp= $this->getUserDocGroups())
  1354. $docgrp= implode(",", $docgrp);
  1355. $access= ($this->isFrontend() ? "sc.privateweb=0" : "1='" . $_SESSION['mgrRole'] . "' OR sc.privatemgr=0") .
  1356. (!$docgrp ? "" : " OR dg.document_group IN ($docgrp)");
  1357. $sql= "SELECT $fields
  1358. FROM $tblsc sc
  1359. LEFT JOIN $tbldg dg on dg.document = sc.id
  1360. WHERE (sc.id=$pageid $activeSql)
  1361. AND ($access)
  1362. LIMIT 1 ";
  1363. $result= $this->db->query($sql);
  1364. $pageInfo= @ $this->db->getRow($result);
  1365. return $pageInfo;
  1366. }
  1367. }
  1368. function getParent($pid= -1, $active= 1, $fields= 'id, pagetitle, description, alias, parent') {
  1369. if ($pid == -1) {
  1370. $pid= $this->documentObject['parent'];
  1371. return ($pid == 0) ? false : $this->getPageInfo($pid, $active, $fields);
  1372. } else
  1373. if ($pid == 0) {
  1374. return false;
  1375. } else {
  1376. // first get the child document
  1377. $child= $this->getPageInfo($pid, $active, "parent");
  1378. // now return the child's parent
  1379. $pid= ($child['parent']) ? $child['parent'] : 0;
  1380. return ($pid == 0) ? false : $this->getPageInfo($pid, $active, $fields);
  1381. }
  1382. }
  1383. function getSnippetId() {
  1384. if ($this->currentSnippet) {
  1385. $tbl= $this->getFullTableName("site_snippets");
  1386. $rs= $this->db->query("SELECT id FROM $tbl WHERE name='" . $this->db->escape($this->currentSnippet) . "' LIMIT 1");
  1387. $row= @ $this->db->getRow($rs);
  1388. if ($row['id'])
  1389. return $row['id'];
  1390. }
  1391. return 0;
  1392. }
  1393. function getSnippetName() {
  1394. return $this->currentSnippet;
  1395. }
  1396. function clearCache() {
  1397. $basepath= $this->config["base_path"] . "assets/cache";
  1398. if (@ $handle= opendir($basepath)) {
  1399. $filesincache= 0;
  1400. $deletedfilesincache= 0;
  1401. while (false !== ($file= readdir($handle))) {
  1402. if ($file != "." && $file != "..") {
  1403. $filesincache += 1;
  1404. if (preg_match("/\.pageCache/", $file)) {
  1405. $deletedfilesincache += 1;
  1406. unlink($basepath . "/" . $file);
  1407. }
  1408. }
  1409. }
  1410. closedir($handle);
  1411. return true;
  1412. } else {
  1413. return false;
  1414. }
  1415. }
  1416. function makeUrl($id, $alias= '', $args= '', $scheme= '') {
  1417. $url= '';
  1418. $virtualDir= '';
  1419. $f_url_prefix = $this->config['friendly_url_prefix'];
  1420. $f_url_suffix = $this->config['friendly_url_suffix'];
  1421. if (!is_numeric($id)) {
  1422. $this->messageQuit('`' . $id . '` is not numeric and may not be passed to makeUrl()');
  1423. }
  1424. if ($args != '' && $this->config['friendly_urls'] == 1) {
  1425. // add ? to $args if missing
  1426. $c= substr($args, 0, 1);
  1427. if (strpos($f_url_prefix, '?') === false) {
  1428. if ($c == '&')
  1429. $args= '?' . substr($args, 1);
  1430. elseif ($c != '?') $args= '?' . $args;
  1431. } else {
  1432. if ($c == '?')
  1433. $args= '&' . substr($args, 1);
  1434. elseif ($c != '&') $args= '&' . $args;
  1435. }
  1436. }
  1437. elseif ($args != '') {
  1438. // add & to $args if missing
  1439. $c= substr($args, 0, 1);
  1440. if ($c == '?')
  1441. $args= '&' . substr($args, 1);
  1442. elseif ($c != '&') $args= '&' . $args;
  1443. }
  1444. if ($this->config['friendly_urls'] == 1 && $alias != '') {
  1445. $url= $f_url_prefix . $alias . $f_url_suffix . $args;
  1446. }
  1447. elseif ($this->config['friendly_urls'] == 1 && $alias == '') {
  1448. $alias= $id;
  1449. if ($this->config['friendly_alias_urls'] == 1) {
  1450. $al= $this->aliasListing[$id];
  1451. $alPath= !empty ($al['path']) ? $al['path'] . '/' : '';
  1452. if ($al && $al['alias'])
  1453. $alias= $al['alias'];
  1454. }
  1455. $alias= $alPath . $f_url_prefix . $alias . $f_url_suffix;
  1456. $url= $alias . $args;
  1457. } else {
  1458. $url= 'index.php?id=' . $id . $args;
  1459. }
  1460. $host= $this->config['base_url'];
  1461. // check if scheme argument has been set
  1462. if ($scheme != '') {
  1463. // for backward compatibility - check if the desired scheme is different than the current scheme
  1464. if (is_numeric($scheme) && $scheme != $_SERVER['HTTPS']) {
  1465. $scheme= ($_SERVER['HTTPS'] ? 'http' : 'https');
  1466. }
  1467. // to-do: check to make sure that $site_url incudes the url :port (e.g. :8080)
  1468. $host= $scheme == 'full' ? $this->config['site_url'] : $scheme . '://' . $_SERVER['HTTP_HOST'] . $host;
  1469. }
  1470. if ($this->config['xhtml_urls']) {
  1471. return preg_replace("/&(?!amp;)/","&amp;", $host . $virtualDir . $url);
  1472. } else {
  1473. return $host . $virtualDir . $url;
  1474. }
  1475. }
  1476. function getConfig($name= '') {
  1477. if (!empty ($this->config[$name])) {
  1478. return $this->config[$name];
  1479. } else {
  1480. return false;
  1481. }
  1482. }
  1483. function getVersionData() {
  1484. include $this->config["base_path"] . "manager/includes/version.inc.php";
  1485. $v= array ();
  1486. $v['version']= $modx_version;
  1487. $v['branch']= $modx_branch;
  1488. $v['release_date']= $modx_release_date;
  1489. $v['full_appname']= $modx_full_appname;
  1490. return $v;
  1491. }
  1492. function makeList($array, $ulroot= 'root', $ulprefix= 'sub_', $type= '', $ordered= false, $tablevel= 0) {
  1493. // first find out whether the value passed is an array
  1494. if (!is_array($array)) {
  1495. return "<ul><li>Bad list</li></ul>";
  1496. }
  1497. if (!empty ($type)) {
  1498. $typestr= " style='list-style-type: $type'";
  1499. } else {
  1500. $typestr= "";
  1501. }
  1502. $tabs= "";
  1503. for ($i= 0; $i < $tablevel; $i++) {
  1504. $tabs .= "\t";
  1505. }
  1506. $listhtml= $ordered == true ? $tabs . "<ol class='$ulroot'$typestr>\n" : $tabs . "<ul class='$ulroot'$typestr>\n";
  1507. foreach ($array as $key => $value) {
  1508. if (is_array($value)) {
  1509. $listhtml .= $tabs . "\t<li>" . $key . "\n" . $this->makeList($value, $ulprefix . $ulroot, $ulprefix, $type, $ordered, $tablevel +2) . $tabs . "\t</li>\n";
  1510. } else {
  1511. $listhtml .= $tabs . "\t<li>" . $value . "</li>\n";
  1512. }
  1513. }
  1514. $listhtml .= $ordered == true ? $tabs . "</ol>\n" : $tabs . "</ul>\n";
  1515. return $listhtml;
  1516. }
  1517. function userLoggedIn() {
  1518. $userdetails= array ();
  1519. if ($this->isFrontend() && isset ($_SESSION['webValidated'])) {
  1520. // web user
  1521. $userdetails['loggedIn']= true;
  1522. $userdetails['id']= $_SESSION['webInternalKey'];
  1523. $userdetails['username']= $_SESSION['webShortname'];
  1524. $userdetails['usertype']= 'web'; // added by Raymond
  1525. return $userdetails;
  1526. } else
  1527. if ($this->isBackend() && isset ($_SESSION['mgrValidated'])) {
  1528. // manager user
  1529. $userdetails['loggedIn']= true;
  1530. $userdetails['id']= $_SESSION['mgrInternalKey'];
  1531. $userdetails['username']= $_SESSION['mgrShortname'];
  1532. $userdetails['usertype']= 'manager'; // added by Raymond
  1533. return $userdetails;
  1534. } else {
  1535. return false;
  1536. }
  1537. }
  1538. function getKeywords($id= 0) {
  1539. if ($id == 0) {
  1540. $id= $this->documentObject['id'];
  1541. }
  1542. $tblKeywords= $this->getFullTableName('site_keywords');
  1543. $tblKeywordXref= $this->getFullTableName('keyword_xref');
  1544. $sql= "SELECT keywords.keyword FROM " . $tblKeywords . " AS keywords INNER JOIN " . $tblKeywordXref . " AS xref ON keywords.id=xref.keyword_id WHERE xref.content_id = '$id'";
  1545. $result= $this->db->query($sql);
  1546. $limit= $this->db->getRecordCount($result);
  1547. $keywords= array ();
  1548. if ($limit > 0) {
  1549. for ($i= 0; $i < $limit; $i++) {
  1550. $row= $this->db->getRow($result);
  1551. $keywords[]= $row['keyword'];
  1552. }
  1553. }
  1554. return $keywords;
  1555. }
  1556. function getMETATags($id= 0) {
  1557. if ($id == 0) {
  1558. $id= $this->documentObject['id'];
  1559. }
  1560. $sql= "SELECT smt.* " .
  1561. "FROM " . $this->getFullTableName("site_metatags") . " smt " .
  1562. "INNER JOIN " . $this->getFullTableName("site_content_metatags") . " cmt ON cmt.metatag_id=smt.id " .
  1563. "WHERE cmt.content_id = '$id'";
  1564. $ds= $this->db->query($sql);
  1565. $limit= $this->db->getRecordCount($ds);
  1566. $metatags= array ();
  1567. if ($limit > 0) {
  1568. for ($i= 0; $i < $limit; $i++) {
  1569. $row= $this->db->getRow($ds);
  1570. $metatags[$row['name']]= array (
  1571. "tag" => $row['tag'],
  1572. "tagvalue" => $row['tagvalue'],
  1573. "http_equiv" => $row['http_equiv']
  1574. );
  1575. }
  1576. }
  1577. return $metatags;
  1578. }
  1579. function runSnippet($snippetName, $params= array ()) {
  1580. if (isset ($this->snippetCache[$snippetName])) {
  1581. $snippet= $this->snippetCache[$snippetName];
  1582. $properties= $this->snippetCache[$snippetName . "Props"];
  1583. } else { // not in cache so let's check the db
  1584. $sql= "SELECT `name`, `snippet`, `properties` FROM " . $this->getFullTableName("site_snippets") . " WHERE " . $this->getFullTableName("site_snippets") . ".`name`='" . $this->db->escape($snippetName) . "';";
  1585. $result= $this->db->query($sql);
  1586. if ($this->db->getRecordCount($result) == 1) {
  1587. $row= $this->db->getRow($result);
  1588. $snippet= $this->snippetCache[$row['name']]= $row['snippet'];
  1589. $properties= $this->snippetCache[$row['name'] . "Props"]= $row['properties'];
  1590. } else {
  1591. $snippet= $this->snippetCache[$snippetName]= "return false;";
  1592. $properties= '';
  1593. }
  1594. }
  1595. // load default params/properties
  1596. $parameters= $this->parseProperties($properties);
  1597. $parameters= array_merge($parameters, $params);
  1598. // run snippet
  1599. return $this->evalSnippet($snippet, $parameters);
  1600. }
  1601. function getChunk($chunkName) {
  1602. $t= $this->chunkCache[$chunkName];
  1603. return $t;
  1604. }
  1605. // deprecated
  1606. function putChunk($chunkName) { // alias name >.<
  1607. return $this->getChunk($chunkName);
  1608. }
  1609. function parseChunk($chunkName, $chunkArr, $prefix= "{", $suffix= "}") {
  1610. if (!is_array($chunkArr)) {
  1611. return false;
  1612. }
  1613. $chunk= $this->getChunk($chunkName);
  1614. foreach ($chunkArr as $key => $value) {
  1615. $chunk= str_replace($prefix . $key . $suffix, $value, $chunk);
  1616. }
  1617. return $chunk;
  1618. }
  1619. function getUserData() {
  1620. include $this->config["base_path"] . "manager/includes/extenders/getUserData.extender.php";
  1621. return $tmpArray;
  1622. }
  1623. function toDateFormat($timestamp = 0, $mode = '') {
  1624. $timestamp = trim($timestamp);
  1625. $timestamp = intval($timestamp);
  1626. switch($this->config['datetime_format']) {
  1627. case 'YYYY/mm/dd':
  1628. $dateFormat = '%Y/%m/%d';
  1629. break;
  1630. case 'dd-mm-YYYY':
  1631. $dateFormat = '%d-%m-%Y';
  1632. break;
  1633. case 'mm/dd/YYYY':
  1634. $dateFormat = '%m/%d/%Y';
  1635. break;
  1636. /*
  1637. case 'dd-mmm-YYYY':
  1638. $dateFormat = '%e-%b-%Y';
  1639. break;
  1640. */
  1641. }
  1642. if (empty($mode)) {
  1643. $strTime = strftime($dateFormat . " %H:%M:%S", $timestamp);
  1644. } elseif ($mode == 'dateOnly') {
  1645. $strTime = strftime($dateFormat, $timestamp);
  1646. } elseif ($mode == 'formatOnly') {
  1647. $strTime = $dateFormat;
  1648. }
  1649. return $strTime;
  1650. }
  1651. function toTimeStamp($str) {
  1652. $str = trim($str);
  1653. if (empty($str)) {return '';}
  1654. switch($this->config['datetime_format']) {
  1655. case 'YYYY/mm/dd':
  1656. if (!preg_match('/^[0-9]{4}\/[0-9]{2}\/[0-9]{2}[0-9 :]*$/', $str)) {return '';}
  1657. list ($Y, $m, $d, $H, $M, $S) = sscanf($str, '%4d/%2d/%2d %2d:%2d:%2d');
  1658. break;
  1659. case 'dd-mm-YYYY':
  1660. if (!preg_match('/^[0-9]{2}-[0-9]{2}-[0-9]{4}[0-9 :]*$/', $str)) {return '';}
  1661. list ($d, $m, $Y, $H, $M, $S) = sscanf($str, '%2d-%2d-%4d %2d:%2d:%2d');
  1662. break;
  1663. case 'mm/dd/YYYY':
  1664. if (!preg_match('/^[0-9]{2}\/[0-9]{2}\/[0-9]{4}[0-9 :]*$/', $str)) {return '';}
  1665. list ($m, $d, $Y, $H, $M, $S) = sscanf($str, '%2d/%2d/%4d %2d:%2d:%2d');
  1666. break;
  1667. /*
  1668. case 'dd-mmm-YYYY':
  1669. if (!preg_match('/^[0-9]{2}-[0-9a-z]+-[0-9]{4}[0-9 :]*$/i', $str)) {return '';}
  1670. list ($m, $d, $Y, $H, $M, $S) = sscanf($str, '%2d-%3s-%4d %2d:%2d:%2d');
  1671. break;
  1672. */
  1673. }
  1674. if (!$H && !$M && !$S) {$H = 0; $M = 0; $S = 0;}
  1675. $timeStamp = mktime($H, $M, $S, $m, $d, $Y);
  1676. $timeStamp = intval($timeStamp);
  1677. return $timeStamp;
  1678. }
  1679. #::::::::::::::::::::::::::::::::::::::::
  1680. # Added By: Raymond Irving - MODx
  1681. #
  1682. function getDocumentChildrenTVars($parentid= 0, $tvidnames= array (), $published= 1, $docsort= "menuindex", $docsortdir= "ASC", $tvfields= "*", $tvsort= "rank", $tvsortdir= "ASC") {
  1683. $docs= $this->getDocumentChildren($parentid, $published, 0, '*', '', $docsort, $docsortdir);
  1684. if (!$docs)
  1685. return false;
  1686. else {
  1687. $result= array ();
  1688. // get user defined template variables
  1689. $fields= ($tvfields == "") ? "tv.*" : 'tv.' . implode(',tv.', preg_replace("/^\s/i", "", explode(',', $tvfields)));
  1690. $tvsort= ($tvsort == "") ? "" : 'tv.' . implode(',tv.', preg_replace("/^\s/i", "", explode(',', $tvsort)));
  1691. if ($tvidnames == "*")
  1692. $query= "tv.id<>0";
  1693. else
  1694. $query= (is_numeric($tvidnames[0]) ? "tv.id" : "tv.name") . " IN ('" . implode("','", $tvidnames) . "')";
  1695. if ($docgrp= $this->getUserDocGroups())
  1696. $docgrp= implode(",", $docgrp);
  1697. $docCount= count($docs);
  1698. for ($i= 0; $i < $docCount; $i++) {
  1699. $tvs= array ();
  1700. $docRow= $docs[$i];
  1701. $docid= $docRow['id'];
  1702. $sql= "SELECT $fields, IF(tvc.value!='',tvc.value,tv.default_text) as value ";
  1703. $sql .= "FROM " . $this->getFullTableName('site_tmplvars') . " tv ";
  1704. $sql .= "INNER JOIN " . $this->getFullTableName('site_tmplvar_templates')." tvtpl ON tvtpl.tmplvarid = tv.id ";
  1705. $sql .= "LEFT JOIN " . $this->getFullTableName('site_tmplvar_contentvalues')." tvc ON tvc.tmplvarid=tv.id AND tvc.contentid = '" . $docid . "' ";
  1706. $sql .= "WHERE " . $query . " AND tvtpl.templateid = " . $docRow['template'];
  1707. if ($tvsort)
  1708. $sql .= " ORDER BY $tvsort $tvsortdir ";
  1709. $rs= $this->db->query($sql);
  1710. $limit= @ $this->db->getRecordCount($rs);
  1711. for ($x= 0; $x < $limit; $x++) {
  1712. array_push($tvs, @ $this->db->getRow($rs));
  1713. }
  1714. // get default/built-in template variables
  1715. ksort($docRow);
  1716. foreach ($docRow as $key => $value) {
  1717. if ($tvidnames == "*" || in_array($key, $tvidnames))
  1718. array_push($tvs, array (
  1719. "name" => $key,
  1720. "value" => $value
  1721. ));
  1722. }
  1723. if (count($tvs))
  1724. array_push($result, $tvs);
  1725. }
  1726. return $result;
  1727. }
  1728. }
  1729. function getDocumentChildrenTVarOutput($parentid= 0, $tvidnames= array (), $published= 1, $docsort= "menuindex", $docsortdir= "ASC") {
  1730. $docs= $this->getDocumentChildren($parentid, $published, 0, '*', '', $docsort, $docsortdir);
  1731. if (!$docs)
  1732. return false;
  1733. else {
  1734. $result= array ();
  1735. for ($i= 0; $i < count($docs); $i++) {
  1736. $tvs= $this->getTemplateVarOutput($tvidnames, $docs[$i]["id"], $published);
  1737. if ($tvs)
  1738. $result[$docs[$i]['id']]= $tvs; // Use docid as key - netnoise 2006/08/14
  1739. }
  1740. return $result;
  1741. }
  1742. }
  1743. // Modified by Raymond for TV - Orig Modified by Apodigm - DocVars
  1744. # returns a single TV record. $idnames - can be an id or name that belongs the template that the current document is using
  1745. function getTemplateVar($idname= "", $fields= "*", $docid= "", $published= 1) {
  1746. if ($idname == "") {
  1747. return false;
  1748. } else {
  1749. $result= $this->getTemplateVars(array ($idname), $fields, $docid, $published, "", ""); //remove sorting for speed
  1750. return ($result != false) ? $result[0] : false;
  1751. }
  1752. }
  1753. # returns an array of TV records. $idnames - can be an id or name that belongs the template that the current document is using
  1754. function getTemplateVars($idnames= array (), $fields= "*", $docid= "", $published= 1, $sort= "rank", $dir= "ASC") {
  1755. if (($idnames != '*' && !is_array($idnames)) || count($idnames) == 0) {
  1756. return false;
  1757. } else {
  1758. $result= array ();
  1759. // get document record
  1760. if ($docid == "") {
  1761. $docid= $this->documentIdentifier;
  1762. $docRow= $this->documentObject;
  1763. } else {
  1764. $docRow= $this->getDocument($docid, '*', $published);
  1765. if (!$docRow)
  1766. return false;
  1767. }
  1768. // get user defined template variables
  1769. $fields= ($fields == "") ? "tv.*" : 'tv.' . implode(',tv.', preg_replace("/^\s/i", "", explode(',', $fields)));
  1770. $sort= ($sort == "") ? "" : 'tv.' . implode(',tv.', preg_replace("/^\s/i", "", explode(',', $sort)));
  1771. if ($idnames == "*")
  1772. $query= "tv.id<>0";
  1773. else
  1774. $query= (is_numeric($idnames[0]) ? "tv.id" : "tv.name") . " IN ('" . implode("','", $idnames) . "')";
  1775. if ($docgrp= $this->getUserDocGroups())
  1776. $docgrp= implode(",", $docgrp);
  1777. $sql= "SELECT $fields, IF(tvc.value!='',tvc.value,tv.default_text) as value ";
  1778. $sql .= "FROM " . $this->getFullTableName('site_tmplvars')." tv ";
  1779. $sql .= "INNER JOIN " . $this->getFullTableName('site_tmplvar_templates')." tvtpl ON tvtpl.tmplvarid = tv.id ";
  1780. $sql .= "LEFT JOIN " . $this->getFullTableName('site_tmplvar_contentvalues')." tvc ON tvc.tmplvarid=tv.id AND tvc.contentid = '" . $docid . "' ";
  1781. $sql .= "WHERE " . $query . " AND tvtpl.templateid = " . $docRow['template'];
  1782. if ($sort)
  1783. $sql .= " ORDER BY $sort $dir ";
  1784. $rs= $this->db->query($sql);
  1785. for ($i= 0; $i < @ $this->db->getRecordCount($rs); $i++) {
  1786. array_push($result, @ $this->db->getRow($rs));
  1787. }
  1788. // get default/built-in template variables
  1789. ksort($docRow);
  1790. foreach ($docRow as $key => $value) {
  1791. if ($idnames == "*" || in_array($key, $idnames))
  1792. array_push($result, array (
  1793. "name" => $key,
  1794. "value" => $value
  1795. ));
  1796. }
  1797. return $result;
  1798. }
  1799. }
  1800. # returns an associative array containing TV rendered output values. $idnames - can be an id or name that belongs the template that the current document is using
  1801. function getTemplateVarOutput($idnames= array (), $docid= "", $published= 1, $sep='') {
  1802. if (count($idnames) == 0) {
  1803. return false;
  1804. } else {
  1805. $output= array ();
  1806. $vars= ($idnames == '*' || is_array($idnames)) ? $idnames : array ($idnames);
  1807. $docid= intval($docid) ? intval($docid) : $this->documentIdentifier;
  1808. $result= $this->getTemplateVars($vars, "*", $docid, $published, "", "", $sep); // remove sort for speed
  1809. if ($result == false)
  1810. return false;
  1811. else {
  1812. $baspath= $this->config["base_path"] . "manager/includes";
  1813. include_once $baspath . "/tmplvars.format.inc.php";
  1814. include_once $baspath . "/tmplvars.commands.inc.php";
  1815. for ($i= 0; $i < count($result); $i++) {
  1816. $row= $result[$i];
  1817. if (!$row['id'])
  1818. $output[$row['name']]= $row['value'];
  1819. else $output[$row['name']]= getTVDisplayFormat($row['name'], $row['value'], $row['display'], $row['display_params'], $row['type'], $docid, $sep);
  1820. }
  1821. return $output;
  1822. }
  1823. }
  1824. }
  1825. # returns the full table name based on db settings
  1826. function getFullTableName($tbl) {
  1827. return $this->db->config['dbase'] . ".`" . $this->db->config['table_prefix'] . $tbl . "`";
  1828. }
  1829. # return placeholder value
  1830. function getPlaceholder($name) {
  1831. return $this->placeholders[$name];
  1832. }
  1833. # sets a value for a placeholder
  1834. function setPlaceholder($name, $value) {
  1835. $this->placeholders[$name]= $value;
  1836. }
  1837. # set arrays or object vars as placeholders
  1838. function toPlaceholders($subject, $prefix= '') {
  1839. if (is_object($subject)) {
  1840. $subject= get_object_vars($subject);
  1841. }
  1842. if (is_array($subject)) {
  1843. foreach ($subject as $key => $value) {
  1844. $this->toPlaceholder($key, $value, $prefix);
  1845. }
  1846. }
  1847. }
  1848. function toPlaceholder($key, $value, $prefix= '') {
  1849. if (is_array($value) || is_object($value)) {
  1850. $this->toPlaceholders($value, "{$prefix}{$key}.");
  1851. } else {
  1852. $this->setPlaceholder("{$prefix}{$key}", $value);
  1853. }
  1854. }
  1855. # returns the virtual relative path to the manager folder
  1856. function getManagerPath() {
  1857. global $base_url;
  1858. $pth= $base_url . 'manager/';
  1859. return $pth;
  1860. }
  1861. # returns the virtual relative path to the cache folder
  1862. function getCachePath() {
  1863. global $base_url;
  1864. $pth= $base_url . 'assets/cache/';
  1865. return $pth;
  1866. }
  1867. # sends a message to a user's message box
  1868. function sendAlert($type, $to, $from, $subject, $msg, $private= 0) {
  1869. $private= ($private) ? 1 : 0;
  1870. if (!is_numeric($to)) {
  1871. // Query for the To ID
  1872. $sql= "SELECT id FROM " . $this->getFullTableName("manager_users") . " WHERE username='$to';";
  1873. $rs= $this->db->query($sql);
  1874. if ($this->db->getRecordCount($rs)) {
  1875. $rs= $this->db->getRow($rs);
  1876. $to= $rs['id'];
  1877. }
  1878. }
  1879. if (!is_numeric($from)) {
  1880. // Query for the From ID
  1881. $sql= "SELECT id FROM " . $this->getFullTableName("manager_users") . " WHERE username='$from';";
  1882. $rs= $this->db->query($sql);
  1883. if ($this->db->getRecordCount($rs)) {
  1884. $rs= $this->db->getRow($rs);
  1885. $from= $rs['id'];
  1886. }
  1887. }
  1888. // insert a new message into user_messages
  1889. $sql= "INSERT INTO " . $this->getFullTableName("user_messages") . " ( id , type , subject , message , sender , recipient , private , postdate , messageread ) VALUES ( '', '$type', '$subject', '$msg', '$from', '$to', '$private', '" . time() . "', '0' );";
  1890. $rs= $this->db->query($sql);
  1891. }
  1892. # Returns true, install or interact when inside manager
  1893. // deprecated
  1894. function insideManager() {
  1895. $m= false;
  1896. if (defined('IN_MANAGER_MODE') && IN_MANAGER_MODE == 'true') {
  1897. $m= true;
  1898. if (defined('SNIPPET_INTERACTIVE_MODE') && SNIPPET_INTERACTIVE_MODE == 'true')
  1899. $m= "interact";
  1900. else
  1901. if (defined('SNIPPET_INSTALL_MODE') && SNIPPET_INSTALL_MODE == 'true')
  1902. $m= "install";
  1903. }
  1904. return $m;
  1905. }
  1906. # Returns current user id
  1907. function getLoginUserID($context= '') {
  1908. if ($context && isset ($_SESSION[$context . 'Validated'])) {
  1909. return $_SESSION[$context . 'InternalKey'];
  1910. }
  1911. elseif ($this->isFrontend() && isset ($_SESSION['webValidated'])) {
  1912. return $_SESSION['webInternalKey'];
  1913. }
  1914. elseif ($this->isBackend() && isset ($_SESSION['mgrValidated'])) {
  1915. return $_SESSION['mgrInternalKey'];
  1916. }
  1917. }
  1918. # Returns current user name
  1919. function getLoginUserName($context= '') {
  1920. if (!empty($context) && isset ($_SESSION[$context . 'Validated'])) {
  1921. return $_SESSION[$context . 'Shortname'];
  1922. }
  1923. elseif ($this->isFrontend() && isset ($_SESSION['webValidated'])) {
  1924. return $_SESSION['webShortname'];
  1925. }
  1926. elseif ($this->isBackend() && isset ($_SESSION['mgrValidated'])) {
  1927. return $_SESSION['mgrShortname'];
  1928. }
  1929. }
  1930. # Returns current login user type - web or manager
  1931. function getLoginUserType() {
  1932. if ($this->isFrontend() && isset ($_SESSION['webValidated'])) {
  1933. return 'web';
  1934. }
  1935. elseif ($this->isBackend() && isset ($_SESSION['mgrValidated'])) {
  1936. return 'manager';
  1937. } else {
  1938. return '';
  1939. }
  1940. }
  1941. # Returns a record for the manager user
  1942. function getUserInfo($uid) {
  1943. $sql= "
  1944. SELECT mu.username, mu.password, mua.*
  1945. FROM " . $this->getFullTableName("manager_users") . " mu
  1946. INNER JOIN " . $this->getFullTableName("user_attributes") . " mua ON mua.internalkey=mu.id
  1947. WHERE mu.id = '$uid'
  1948. ";
  1949. $rs= $this->db->query($sql);
  1950. $limit= mysql_num_rows($rs);
  1951. if ($limit == 1) {
  1952. $row= $this->db->getRow($rs);
  1953. if (!$row["usertype"])
  1954. $row["usertype"]= "manager";
  1955. return $row;
  1956. }
  1957. }
  1958. # Returns a record for the web user
  1959. function getWebUserInfo($uid) {
  1960. $sql= "
  1961. SELECT wu.username, wu.password, wua.*
  1962. FROM " . $this->getFullTableName("web_users") . " wu
  1963. INNER JOIN " . $this->getFullTableName("web_user_attributes") . " wua ON wua.internalkey=wu.id
  1964. WHERE wu.id='$uid'
  1965. ";
  1966. $rs= $this->db->query($sql);
  1967. $limit= mysql_num_rows($rs);
  1968. if ($limit == 1) {
  1969. $row= $this->db->getRow($rs);
  1970. if (!$row["usertype"])
  1971. $row["usertype"]= "web";
  1972. return $row;
  1973. }
  1974. }
  1975. # Returns an array of document groups that current user is assigned to.
  1976. # This function will first return the web user doc groups when running from frontend otherwise it will return manager user's docgroup
  1977. # Set $resolveIds to true to return the document group names
  1978. function getUserDocGroups($resolveIds= false) {
  1979. if ($this->isFrontend() && isset ($_SESSION['webDocgroups']) && isset ($_SESSION['webValidated'])) {
  1980. $dg= $_SESSION['webDocgroups'];
  1981. $dgn= isset ($_SESSION['webDocgrpNames']) ? $_SESSION['webDocgrpNames'] : false;
  1982. } else
  1983. if ($this->isBackend() && isset ($_SESSION['mgrDocgroups']) && isset ($_SESSION['mgrValidated'])) {
  1984. $dg= $_SESSION['mgrDocgroups'];
  1985. $dgn= $_SESSION['mgrDocgrpNames'];
  1986. } else {
  1987. $dg= '';
  1988. }
  1989. if (!$resolveIds)
  1990. return $dg;
  1991. else
  1992. if (is_array($dgn))
  1993. return $dgn;
  1994. else
  1995. if (is_array($dg)) {
  1996. // resolve ids to names
  1997. $dgn= array ();
  1998. $tbl= $this->getFullTableName("documentgroup_names");
  1999. $ds= $this->db->query("SELECT name FROM $tbl WHERE id IN (" . implode(",", $dg) . ")");
  2000. while ($row= $this->db->getRow($ds))
  2001. $dgn[count($dgn)]= $row['name'];
  2002. // cache docgroup names to session
  2003. if ($this->isFrontend())
  2004. $_SESSION['webDocgrpNames']= $dgn;
  2005. else
  2006. $_SESSION['mgrDocgrpNames']= $dgn;
  2007. return $dgn;
  2008. }
  2009. }
  2010. function getDocGroups() {
  2011. return $this->getUserDocGroups();
  2012. } // deprecated
  2013. # Change current web user's password - returns true if successful, oterhwise return error message
  2014. function changeWebUserPassword($oldPwd, $newPwd) {
  2015. $rt= false;
  2016. if ($_SESSION["webValidated"] == 1) {
  2017. $tbl= $this->getFullTableName("web_users");
  2018. $ds= $this->db->query("SELECT `id`, `username`, `password` FROM $tbl WHERE `id`='" . $this->getLoginUserID() . "'");
  2019. $limit= mysql_num_rows($ds);
  2020. if ($limit == 1) {
  2021. $row= $this->db->getRow($ds);
  2022. if ($row["password"] == md5($oldPwd)) {
  2023. if (strlen($newPwd) < 6) {
  2024. return "Password is too short!";
  2025. }
  2026. elseif ($newPwd == "") {
  2027. return "You didn't specify a password for this user!";
  2028. } else {
  2029. $this->db->query("UPDATE $tbl SET password = md5('" . $this->db->escape($newPwd) . "') WHERE id='" . $this->getLoginUserID() . "'");
  2030. // invoke OnWebChangePassword event
  2031. $this->invokeEvent("OnWebChangePassword", array (
  2032. "userid" => $row["id"],
  2033. "username" => $row["username"],
  2034. "userpassword" => $newPwd
  2035. ));
  2036. return true;
  2037. }
  2038. } else {
  2039. return "Incorrect password.";
  2040. }
  2041. }
  2042. }
  2043. }
  2044. function changePassword($o, $n) {
  2045. return changeWebUserPassword($o, $n);
  2046. } // deprecated
  2047. # returns true if the current web user is a member the specified groups
  2048. function isMemberOfWebGroup($groupNames= array ()) {
  2049. if (!is_array($groupNames))
  2050. return false;
  2051. // check cache
  2052. $grpNames= isset ($_SESSION['webUserGroupNames']) ? $_SESSION['webUserGroupNames'] : false;
  2053. if (!is_array($grpNames)) {
  2054. $tbl= $this->getFullTableName("webgroup_names");
  2055. $tbl2= $this->getFullTableName("web_groups");
  2056. $sql= "SELECT wgn.name
  2057. FROM $tbl wgn
  2058. INNER JOIN $tbl2 wg ON wg.webgroup=wgn.id AND wg.webuser='" . $this->getLoginUserID() . "'";
  2059. $grpNames= $this->db->getColumn("name", $sql);
  2060. // save to cache
  2061. $_SESSION['webUserGroupNames']= $grpNames;
  2062. }
  2063. foreach ($groupNames as $k => $v)
  2064. if (in_array(trim($v), $grpNames))
  2065. return true;
  2066. return false;
  2067. }
  2068. # Registers Client-side CSS scripts - these scripts are loaded at inside the <head> tag
  2069. function regClientCSS($src, $media='') {
  2070. if (empty($src) || isset ($this->loadedjscripts[$src]))
  2071. return '';
  2072. $nextpos= max(array_merge(array(0),array_keys($this->sjscripts)))+1;
  2073. $this->loadedjscripts[$src]['startup']= true;
  2074. $this->loadedjscripts[$src]['version']= '0';
  2075. $this->loadedjscripts[$src]['pos']= $nextpos;
  2076. if (strpos(strtolower($src), "<style") !== false || strpos(strtolower($src), "<link") !== false) {
  2077. $this->sjscripts[$nextpos]= $src;
  2078. } else {
  2079. $this->sjscripts[$nextpos]= "\t" . '<link rel="stylesheet" type="text/css" href="'.$src.'" '.($media ? 'media="'.$media.'" ' : '').'/>';
  2080. }
  2081. }
  2082. # Registers Startup Client-side JavaScript - these scripts are loaded at inside the <head> tag
  2083. function regClientStartupScript($src, $options= array('name'=>'', 'version'=>'0', 'plaintext'=>false)) {
  2084. $this->regClientScript($src, $options, true);
  2085. }
  2086. # Registers Client-side JavaScript - these scripts are loaded at the end of the page unless $startup is true
  2087. function regClientScript($src, $options= array('name'=>'', 'version'=>'0', 'plaintext'=>false), $startup= false) {
  2088. if (empty($src))
  2089. return ''; // nothing to register
  2090. if (!is_array($options)) {
  2091. if (is_bool($options)) // backward compatibility with old plaintext parameter
  2092. $options=array('plaintext'=>$options);
  2093. elseif (is_string($options)) // Also allow script name as 2nd param
  2094. $options=array('name'=>$options);
  2095. else
  2096. $options=array();
  2097. }
  2098. $name= isset($options['name']) ? strtolower($options['name']) : '';
  2099. $version= isset($options['version']) ? $options['version'] : '0';
  2100. $plaintext= isset($options['plaintext']) ? $options['plaintext'] : false;
  2101. $key= !empty($name) ? $name : $src;
  2102. unset($overwritepos); // probably unnecessary--just making sure
  2103. $useThisVer= true;
  2104. if (isset($this->loadedjscripts[$key])) { // a matching script was found
  2105. // if existing script is a startup script, make sure the candidate is also a startup script
  2106. if ($this->loadedjscripts[$key]['startup'])
  2107. $startup= true;
  2108. if (empty($name)) {
  2109. $useThisVer= false; // if the match was based on identical source code, no need to replace the old one
  2110. } else {
  2111. $useThisVer = version_compare($this->loadedjscripts[$key]['version'], $version, '<');
  2112. }
  2113. if ($useThisVer) {
  2114. if ($startup==true && $this->loadedjscripts[$key]['startup']==false) {
  2115. // remove old script from the bottom of the page (new one will be at the top)
  2116. unset($this->jscripts[$this->loadedjscripts[$key]['pos']]);
  2117. } else {
  2118. // overwrite the old script (the position may be important for dependent scripts)
  2119. $overwritepos= $this->loadedjscripts[$key]['pos'];
  2120. }
  2121. } else { // Use the original version
  2122. if ($startup==true && $this->loadedjscripts[$key]['startup']==false) {
  2123. // need to move the exisiting script to the head
  2124. $version= $this->loadedjscripts[$key][$version];
  2125. $src= $this->jscripts[$this->loadedjscripts[$key]['pos']];
  2126. unset($this->jscripts[$this->loadedjscripts[$key]['pos']]);
  2127. } else {
  2128. return ''; // the script is already in the right place
  2129. }
  2130. }
  2131. }
  2132. if ($useThisVer && $plaintext!=true && (strpos(strtolower($src), "<script") === false))
  2133. $src= "\t" . '<script type="text/javascript" src="' . $src . '"></script>';
  2134. if ($startup) {
  2135. $pos= isset($overwritepos) ? $overwritepos : max(array_merge(array(0),array_keys($this->sjscripts)))+1;
  2136. $this->sjscripts[$pos]= $src;
  2137. } else {
  2138. $pos= isset($overwritepos) ? $overwritepos : max(array_merge(array(0),array_keys($this->jscripts)))+1;
  2139. $this->jscripts[$pos]= $src;
  2140. }
  2141. $this->loadedjscripts[$key]['version']= $version;
  2142. $this->loadedjscripts[$key]['startup']= $startup;
  2143. $this->loadedjscripts[$key]['pos']= $pos;
  2144. }
  2145. # Registers Client-side Startup HTML block
  2146. function regClientStartupHTMLBlock($html) {
  2147. $this->regClientScript($html, true, true);
  2148. }
  2149. # Registers Client-side HTML block
  2150. function regClientHTMLBlock($html) {
  2151. $this->regClientScript($html, true);
  2152. }
  2153. # Remove unwanted html tags and snippet, settings and tags
  2154. function stripTags($html, $allowed= "") {
  2155. $t= strip_tags($html, $allowed);
  2156. $t= preg_replace('~\[\*(.*?)\*\]~', "", $t); //tv
  2157. $t= preg_replace('~\[\[(.*?)\]\]~', "", $t); //snippet
  2158. $t= preg_replace('~\[\!(.*?)\!\]~', "", $t); //snippet
  2159. $t= preg_replace('~\[\((.*?)\)\]~', "", $t); //settings
  2160. $t= preg_replace('~\[\+(.*?)\+\]~', "", $t); //placeholders
  2161. $t= preg_replace('~{{(.*?)}}~', "", $t); //chunks
  2162. return $t;
  2163. }
  2164. # add an event listner to a plugin - only for use within the current execution cycle
  2165. function addEventListener($evtName, $pluginName) {
  2166. if (!$evtName || !$pluginName)
  2167. return false;
  2168. if (!array_key_exists($evtName,$this->pluginEvent))
  2169. $this->pluginEvent[$evtName] = array();
  2170. return array_push($this->pluginEvent[$evtName], $pluginName); // return array count
  2171. }
  2172. # remove event listner - only for use within the current execution cycle
  2173. function removeEventListener($evtName) {
  2174. if (!$evtName)
  2175. return false;
  2176. unset ($this->pluginEvent[$evtName]);
  2177. }
  2178. # remove all event listners - only for use within the current execution cycle
  2179. function removeAllEventListener() {
  2180. unset ($this->pluginEvent);
  2181. $this->pluginEvent= array ();
  2182. }
  2183. # invoke an event. $extParams - hash array: name=>value
  2184. function invokeEvent($evtName, $extParams= array ()) {
  2185. if (!$evtName)
  2186. return false;
  2187. if (!isset ($this->pluginEvent[$evtName]))
  2188. return false;
  2189. $el= $this->pluginEvent[$evtName];
  2190. $results= array ();
  2191. $numEvents= count($el);
  2192. if ($numEvents > 0)
  2193. for ($i= 0; $i < $numEvents; $i++) { // start for loop
  2194. $pluginName= $el[$i];
  2195. $pluginName = stripslashes($pluginName);
  2196. // reset event object
  2197. $e= & $this->Event;
  2198. $e->_resetEventObject();
  2199. $e->name= $evtName;
  2200. $e->activePlugin= $pluginName;
  2201. // get plugin code
  2202. if (isset ($this->pluginCache[$pluginName])) {
  2203. $pluginCode= $this->pluginCache[$pluginName];
  2204. $pluginProperties= $this->pluginCache[$pluginName . "Props"];
  2205. } else {
  2206. $sql= "SELECT `name`, `plugincode`, `properties` FROM " . $this->getFullTableName("site_plugins") . " WHERE `name`='" . $pluginName . "' AND `disabled`=0;";
  2207. $result= $this->db->query($sql);
  2208. if ($this->db->getRecordCount($result) == 1) {
  2209. $row= $this->db->getRow($result);
  2210. $pluginCode= $this->pluginCache[$row['name']]= $row['plugincode'];
  2211. $pluginProperties= $this->pluginCache[$row['name'] . "Props"]= $row['properties'];
  2212. } else {
  2213. $pluginCode= $this->pluginCache[$pluginName]= "return false;";
  2214. $pluginProperties= '';
  2215. }
  2216. }
  2217. // load default params/properties
  2218. $parameter= $this->parseProperties($pluginProperties);
  2219. if (!empty ($extParams))
  2220. $parameter= array_merge($parameter, $extParams);
  2221. // eval plugin
  2222. $this->evalPlugin($pluginCode, $parameter);
  2223. if ($e->_output != "")
  2224. $results[]= $e->_output;
  2225. if ($e->_propagate != true)
  2226. break;
  2227. }
  2228. $e->activePlugin= "";
  2229. return $results;
  2230. }
  2231. # parses a resource property string and returns the result as an array
  2232. function parseProperties($propertyString) {
  2233. $parameter= array ();
  2234. if (!empty ($propertyString)) {
  2235. $tmpParams= explode("&", $propertyString);
  2236. for ($x= 0; $x < count($tmpParams); $x++) {
  2237. if (strpos($tmpParams[$x], '=', 0)) {
  2238. $pTmp= explode("=", $tmpParams[$x]);
  2239. $pvTmp= explode(";", trim($pTmp[1]));
  2240. if ($pvTmp[1] == 'list' && $pvTmp[3] != "")
  2241. $parameter[trim($pTmp[0])]= $pvTmp[3]; //list default
  2242. else
  2243. if ($pvTmp[1] != 'list' && $pvTmp[2] != "")
  2244. $parameter[trim($pTmp[0])]= $pvTmp[2];
  2245. }
  2246. }
  2247. }
  2248. return $parameter;
  2249. }
  2250. /*############################################
  2251. Etomite_dbFunctions.php
  2252. New database functions for Etomite CMS
  2253. Author: Ralph A. Dahlgren - rad14701@yahoo.com
  2254. Etomite ID: rad14701
  2255. See documentation for usage details
  2256. ############################################*/
  2257. function getIntTableRows($fields= "*", $from= "", $where= "", $sort= "", $dir= "ASC", $limit= "") {
  2258. // function to get rows from ANY internal database table
  2259. if ($from == "") {
  2260. return false;
  2261. } else {
  2262. $where= ($where != "") ? "WHERE $where" : "";
  2263. $sort= ($sort != "") ? "ORDER BY $sort $dir" : "";
  2264. $limit= ($limit != "") ? "LIMIT $limit" : "";
  2265. $tbl= $this->getFullTableName($from);
  2266. $sql= "SELECT $fields FROM $tbl $where $sort $limit;";
  2267. $result= $this->db->query($sql);
  2268. $resourceArray= array ();
  2269. for ($i= 0; $i < @ $this->db->getRecordCount($result); $i++) {
  2270. array_push($resourceArray, @ $this->db->getRow($result));
  2271. }
  2272. return $resourceArray;
  2273. }
  2274. }
  2275. function putIntTableRow($fields= "", $into= "") {
  2276. // function to put a row into ANY internal database table
  2277. if (($fields == "") || ($into == "")) {
  2278. return false;
  2279. } else {
  2280. $tbl= $this->getFullTableName($into);
  2281. $sql= "INSERT INTO $tbl SET ";
  2282. foreach ($fields as $key => $value) {
  2283. $sql .= $key . "=";
  2284. if (is_numeric($value))
  2285. $sql .= $value . ",";
  2286. else
  2287. $sql .= "'" . $value . "',";
  2288. }
  2289. $sql= rtrim($sql, ",");
  2290. $sql .= ";";
  2291. $result= $this->db->query($sql);
  2292. return $result;
  2293. }
  2294. }
  2295. function updIntTableRow($fields= "", $into= "", $where= "", $sort= "", $dir= "ASC", $limit= "") {
  2296. // function to update a row into ANY internal database table
  2297. if (($fields == "") || ($into == "")) {
  2298. return false;
  2299. } else {
  2300. $where= ($where != "") ? "WHERE $where" : "";
  2301. $sort= ($sort != "") ? "ORDER BY $sort $dir" : "";
  2302. $limit= ($limit != "") ? "LIMIT $limit" : "";
  2303. $tbl= $this->getFullTableName($into);
  2304. $sql= "UPDATE $tbl SET ";
  2305. foreach ($fields as $key => $value) {
  2306. $sql .= $key . "=";
  2307. if (is_numeric($value))
  2308. $sql .= $value . ",";
  2309. else
  2310. $sql .= "'" . $value . "',";
  2311. }
  2312. $sql= rtrim($sql, ",");
  2313. $sql .= " $where $sort $limit;";
  2314. $result= $this->db->query($sql);
  2315. return $result;
  2316. }
  2317. }
  2318. function getExtTableRows($host= "", $user= "", $pass= "", $dbase= "", $fields= "*", $from= "", $where= "", $sort= "", $dir= "ASC", $limit= "") {
  2319. // function to get table rows from an external MySQL database
  2320. if (($host == "") || ($user == "") || ($pass == "") || ($dbase == "") || ($from == "")) {
  2321. return false;
  2322. } else {
  2323. $where= ($where != "") ? "WHERE $where" : "";
  2324. $sort= ($sort != "") ? "ORDER BY $sort $dir" : "";
  2325. $limit= ($limit != "") ? "LIMIT $limit" : "";
  2326. $tbl= $dbase . "." . $from;
  2327. $this->dbExtConnect($host, $user, $pass, $dbase);
  2328. $sql= "SELECT $fields FROM $tbl $where $sort $limit;";
  2329. $result= $this->db->query($sql);
  2330. $resourceArray= array ();
  2331. for ($i= 0; $i < @ $this->db->getRecordCount($result); $i++) {
  2332. array_push($resourceArray, @ $this->db->getRow($result));
  2333. }
  2334. return $resourceArray;
  2335. }
  2336. }
  2337. function putExtTableRow($host= "", $user= "", $pass= "", $dbase= "", $fields= "", $into= "") {
  2338. // function to put a row into an external database table
  2339. if (($host == "") || ($user == "") || ($pass == "") || ($dbase == "") || ($fields == "") || ($into == "")) {
  2340. return false;
  2341. } else {
  2342. $this->dbExtConnect($host, $user, $pass, $dbase);
  2343. $tbl= $dbase . "." . $into;
  2344. $sql= "INSERT INTO $tbl SET ";
  2345. foreach ($fields as $key => $value) {
  2346. $sql .= $key . "=";
  2347. if (is_numeric($value))
  2348. $sql .= $value . ",";
  2349. else
  2350. $sql .= "'" . $value . "',";
  2351. }
  2352. $sql= rtrim($sql, ",");
  2353. $sql .= ";";
  2354. $result= $this->db->query($sql);
  2355. return $result;
  2356. }
  2357. }
  2358. function updExtTableRow($host= "", $user= "", $pass= "", $dbase= "", $fields= "", $into= "", $where= "", $sort= "", $dir= "ASC", $limit= "") {
  2359. // function to update a row into an external database table
  2360. if (($fields == "") || ($into == "")) {
  2361. return false;
  2362. } else {
  2363. $this->dbExtConnect($host, $user, $pass, $dbase);
  2364. $tbl= $dbase . "." . $into;
  2365. $where= ($where != "") ? "WHERE $where" : "";
  2366. $sort= ($sort != "") ? "ORDER BY $sort $dir" : "";
  2367. $limit= ($limit != "") ? "LIMIT $limit" : "";
  2368. $sql= "UPDATE $tbl SET ";
  2369. foreach ($fields as $key => $value) {
  2370. $sql .= $key . "=";
  2371. if (is_numeric($value))
  2372. $sql .= $value . ",";
  2373. else
  2374. $sql .= "'" . $value . "',";
  2375. }
  2376. $sql= rtrim($sql, ",");
  2377. $sql .= " $where $sort $limit;";
  2378. $result= $this->db->query($sql);
  2379. return $result;
  2380. }
  2381. }
  2382. function dbExtConnect($host, $user, $pass, $dbase) {
  2383. // function to connect to external database
  2384. $tstart= $this->getMicroTime();
  2385. if (@ !$this->rs= mysql_connect($host, $user, $pass)) {
  2386. $this->messageQuit("Failed to create connection to the $dbase database!");
  2387. } else {
  2388. mysql_select_db($dbase);
  2389. $tend= $this->getMicroTime();
  2390. $totaltime= $tend - $tstart;
  2391. if ($this->dumpSQL) {
  2392. $this->queryCode .= "<fieldset style='text-align:left'><legend>Database connection</legend>" . sprintf("Database connection to %s was created in %2.4f s", $dbase, $totaltime) . "</fieldset><br />";
  2393. }
  2394. $this->queryTime= $this->queryTime + $totaltime;
  2395. }
  2396. }
  2397. function getFormVars($method= "", $prefix= "", $trim= "", $REQUEST_METHOD) {
  2398. // function to retrieve form results into an associative array
  2399. $results= array ();
  2400. $method= strtoupper($method);
  2401. if ($method == "")
  2402. $method= $REQUEST_METHOD;
  2403. if ($method == "POST")
  2404. $method= & $_POST;
  2405. elseif ($method == "GET") $method= & $_GET;
  2406. else
  2407. return false;
  2408. reset($method);
  2409. foreach ($method as $key => $value) {
  2410. if (($prefix != "") && (substr($key, 0, strlen($prefix)) == $prefix)) {
  2411. if ($trim) {
  2412. $pieces= explode($prefix, $key, 2);
  2413. $key= $pieces[1];
  2414. $results[$key]= $value;
  2415. } else
  2416. $results[$key]= $value;
  2417. }
  2418. elseif ($prefix == "") $results[$key]= $value;
  2419. }
  2420. return $results;
  2421. }
  2422. ########################################
  2423. // END New database functions - rad14701
  2424. ########################################
  2425. /***************************************************************************************/
  2426. /* End of API functions */
  2427. /***************************************************************************************/
  2428. function phpError($nr, $text, $file, $line) {
  2429. if (error_reporting() == 0 || $nr == 0 || ($nr == 8 && $this->stopOnNotice == false)) {
  2430. return true;
  2431. }
  2432. if (is_readable($file)) {
  2433. $source= file($file);
  2434. $source= htmlspecialchars($source[$line -1]);
  2435. } else {
  2436. $source= "";
  2437. } //Error $nr in $file at $line: <div><code>$source</code></div>
  2438. $this->messageQuit("PHP Parse Error", '', true, $nr, $file, $source, $text, $line);
  2439. }
  2440. function messageQuit($msg= 'unspecified error', $query= '', $is_error= true, $nr= '', $file= '', $source= '', $text= '', $line= '') {
  2441. $version= isset ($GLOBALS['version']) ? $GLOBALS['version'] : '';
  2442. $release_date= isset ($GLOBALS['release_date']) ? $GLOBALS['release_date'] : '';
  2443. $parsedMessageString= "
  2444. <html><head><title>MODx Content Manager $version &raquo; $release_date</title>
  2445. <style>TD, BODY { font-size: 11px; font-family:verdana; }</style>
  2446. <script type='text/javascript'>
  2447. function copyToClip()
  2448. {
  2449. holdtext.innerText = sqlHolder.innerText;
  2450. Copied = holdtext.createTextRange();
  2451. Copied.execCommand('Copy');
  2452. }
  2453. </script>
  2454. </head><body>
  2455. ";
  2456. if ($is_error) {
  2457. $parsedMessageString .= "<h3 style='color:red'>&laquo; MODx Parse Error &raquo;</h3>
  2458. <table border='0' cellpadding='1' cellspacing='0'>
  2459. <tr><td colspan='3'>MODx encountered the following error while attempting to parse the requested resource:</td></tr>
  2460. <tr><td colspan='3'><b style='color:red;'>&laquo; $msg &raquo;</b></td></tr>";
  2461. } else {
  2462. $parsedMessageString .= "<h3 style='color:#003399'>&laquo; MODx Debug/ stop message &raquo;</h3>
  2463. <table border='0' cellpadding='1' cellspacing='0'>
  2464. <tr><td colspan='3'>The MODx parser recieved the following debug/ stop message:</td></tr>
  2465. <tr><td colspan='3'><b style='color:#003399;'>&laquo; $msg &raquo;</b></td></tr>";
  2466. }
  2467. if (!empty ($query)) {
  2468. $parsedMessageString .= "<tr><td colspan='3'><b style='color:#999;font-size: 9px;'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;SQL:&nbsp;<span id='sqlHolder'>$query</span></b>
  2469. <br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href='javascript:copyToClip();' style='color:#821517;font-size: 9px; text-decoration: none'>[Copy SQL to ClipBoard]</a><textarea id='holdtext' style='display:none;'></textarea></td></tr>";
  2470. }
  2471. if ($text != '') {
  2472. $errortype= array (
  2473. E_ERROR => "Error",
  2474. E_WARNING => "Warning",
  2475. E_PARSE => "Parsing Error",
  2476. E_NOTICE => "Notice",
  2477. E_CORE_ERROR => "Core Error",
  2478. E_CORE_WARNING => "Core Warning",
  2479. E_COMPILE_ERROR => "Compile Error",
  2480. E_COMPILE_WARNING => "Compile Warning",
  2481. E_USER_ERROR => "User Error",
  2482. E_USER_WARNING => "User Warning",
  2483. E_USER_NOTICE => "User Notice",
  2484. );
  2485. $parsedMessageString .= "<tr><td>&nbsp;</td></tr><tr><td colspan='3'><b>PHP error debug</b></td></tr>";
  2486. $parsedMessageString .= "<tr><td valign='top'>&nbsp;&nbsp;Error: </td>";
  2487. $parsedMessageString .= "<td colspan='2'>$text</td><td>&nbsp;</td>";
  2488. $parsedMessageString .= "</tr>";
  2489. $parsedMessageString .= "<tr><td valign='top'>&nbsp;&nbsp;Error type/ Nr.: </td>";
  2490. $parsedMessageString .= "<td colspan='2'>" . $errortype[$nr] . " - $nr</b></td><td>&nbsp;</td>";
  2491. $parsedMessageString .= "</tr>";
  2492. $parsedMessageString .= "<tr><td>&nbsp;&nbsp;File: </td>";
  2493. $parsedMessageString .= "<td colspan='2'>$file</td><td>&nbsp;</td>";
  2494. $parsedMessageString .= "</tr>";
  2495. $parsedMessageString .= "<tr><td>&nbsp;&nbsp;Line: </td>";
  2496. $parsedMessageString .= "<td colspan='2'>$line</td><td>&nbsp;</td>";
  2497. $parsedMessageString .= "</tr>";
  2498. if ($source != '') {
  2499. $parsedMessageString .= "<tr><td valign='top'>&nbsp;&nbsp;Line $line source: </td>";
  2500. $parsedMessageString .= "<td colspan='2'>$source</td><td>&nbsp;</td>";
  2501. $parsedMessageString .= "</tr>";
  2502. }
  2503. }
  2504. $parsedMessageString .= "<tr><td>&nbsp;</td></tr><tr><td colspan='3'><b>Parser timing</b></td></tr>";
  2505. $parsedMessageString .= "<tr><td>&nbsp;&nbsp;MySQL: </td>";
  2506. $parsedMessageString .= "<td><i>[^qt^]</i></td><td>(<i>[^q^] Requests</i>)</td>";
  2507. $parsedMessageString .= "</tr>";
  2508. $parsedMessageString .= "<tr><td>&nbsp;&nbsp;PHP: </td>";
  2509. $parsedMessageString .= "<td><i>[^p^]</i></td><td>&nbsp;</td>";
  2510. $parsedMessageString .= "</tr>";
  2511. $parsedMessageString .= "<tr><td>&nbsp;&nbsp;Total: </td>";
  2512. $parsedMessageString .= "<td><i>[^t^]</i></td><td>&nbsp;</td>";
  2513. $parsedMessageString .= "</tr>";
  2514. $parsedMessageString .= "</table>";
  2515. $parsedMessageString .= "</body></html>";
  2516. $totalTime= ($this->getMicroTime() - $this->tstart);
  2517. $queryTime= $this->queryTime;
  2518. $phpTime= $totalTime - $queryTime;
  2519. $queries= isset ($this->executedQueries) ? $this->executedQueries : 0;
  2520. $queryTime= sprintf("%2.4f s", $queryTime);
  2521. $totalTime= sprintf("%2.4f s", $totalTime);
  2522. $phpTime= sprintf("%2.4f s", $phpTime);
  2523. $parsedMessageString= str_replace("[^q^]", $queries, $parsedMessageString);
  2524. $parsedMessageString= str_replace("[^qt^]", $queryTime, $parsedMessageString);
  2525. $parsedMessageString= str_replace("[^p^]", $phpTime, $parsedMessageString);
  2526. $parsedMessageString= str_replace("[^t^]", $totalTime, $parsedMessageString);
  2527. // Set 500 response header
  2528. header('HTTP/1.1 500 Internal Server Error');
  2529. // Display error
  2530. echo $parsedMessageString;
  2531. ob_end_flush();
  2532. // Log error
  2533. $this->logEvent(0, 3, $parsedMessageString, $source= 'Parser');
  2534. // Make sure and die!
  2535. exit();
  2536. }
  2537. function getRegisteredClientScripts() {
  2538. return implode("\n", $this->jscripts);
  2539. }
  2540. function getRegisteredClientStartupScripts() {
  2541. return implode("\n", $this->sjscripts);
  2542. }
  2543. /**
  2544. * Format alias to be URL-safe. Strip invalid characters.
  2545. *
  2546. * @param string Alias to be formatted
  2547. * @return string Safe alias
  2548. */
  2549. function stripAlias($alias) {
  2550. // let add-ons overwrite the default behavior
  2551. $results = $this->invokeEvent('OnStripAlias', array ('alias'=>$alias));
  2552. if (!empty($results)) {
  2553. // if multiple plugins are registered, only the last one is used
  2554. return end($results);
  2555. } else {
  2556. // default behavior: strip invalid characters and replace spaces with dashes.
  2557. $alias = strip_tags($alias); // strip HTML
  2558. $alias = preg_replace('/[^\.A-Za-z0-9 _-]/', '', $alias); // strip non-alphanumeric characters
  2559. $alias = preg_replace('/\s+/', '-', $alias); // convert white-space to dash
  2560. $alias = preg_replace('/-+/', '-', $alias); // convert multiple dashes to one
  2561. $alias = trim($alias, '-'); // trim excess
  2562. return $alias;
  2563. }
  2564. }
  2565. // End of class.
  2566. }
  2567. // SystemEvent Class
  2568. class SystemEvent {
  2569. var $name;
  2570. var $_propagate;
  2571. var $_output;
  2572. var $activated;
  2573. var $activePlugin;
  2574. function SystemEvent($name= "") {
  2575. $this->_resetEventObject();
  2576. $this->name= $name;
  2577. }
  2578. // used for displaying a message to the user
  2579. function alert($msg) {
  2580. global $SystemAlertMsgQueque;
  2581. if ($msg == "")
  2582. return;
  2583. if (is_array($SystemAlertMsgQueque)) {
  2584. if ($this->name && $this->activePlugin)
  2585. $title= "<div><b>" . $this->activePlugin . "</b> - <span style='color:maroon;'>" . $this->name . "</span></div>";
  2586. $SystemAlertMsgQueque[]= "$title<div style='margin-left:10px;margin-top:3px;'>$msg</div>";
  2587. }
  2588. }
  2589. // used for rendering an out on the screen
  2590. function output($msg) {
  2591. $this->_output .= $msg;
  2592. }
  2593. function stopPropagation() {
  2594. $this->_propagate= false;
  2595. }
  2596. function _resetEventObject() {
  2597. unset ($this->returnedValues);
  2598. $this->name= "";
  2599. $this->_output= "";
  2600. $this->_propagate= true;
  2601. $this->activated= false;
  2602. }
  2603. }
  2604. ?>