PageRenderTime 77ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 1ms

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

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