PageRenderTime 47ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/assets/snippets/jot/includes/phx.parser.class.inc.php

https://github.com/modxcms/evolution
PHP | 414 lines | 356 code | 16 blank | 42 comment | 12 complexity | d7857fdeac6465c2f6377042a2c6434e MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1, MIT, BSD-2-Clause, Apache-2.0, BSD-3-Clause
  1. <?php
  2. /*####
  3. #
  4. # Name: PHx (Placeholders Xtended)
  5. # Version: 2.1.2
  6. # Author: Armand "bS" Pondman (apondman@zerobarrier.nl)
  7. # Date: Feb 13, 2007 8:52 CET
  8. #
  9. ####*/
  10. class PHxParser {
  11. var $placeholders = array();
  12. function PHxParser($debug=0,$maxpass=50) {
  13. global $modx;
  14. $this->name = "PHx";
  15. $this->version = "2.1.2";
  16. $this->user["mgrid"] = intval($_SESSION['mgrInternalKey']);
  17. $this->user["usrid"] = intval($_SESSION['webInternalKey']);
  18. $this->user["id"] = ($this->user["usrid"] > 0 ) ? (-$this->user["usrid"]) : $this->user["mgrid"];
  19. $this->cache["cm"] = array();
  20. $this->cache["ui"] = array();
  21. $this->cache["mo"] = array();
  22. $this->safetags[0][0] = '~(?<![\[]|^\^)\[(?=[^\+\*\(\[]|$)~s';
  23. $this->safetags[0][1] = '~(?<=[^\+\*\)\]]|^)\](?=[^\]]|$)~s';
  24. $this->safetags[1][0] = '&_PHX_INTERNAL_091_&';
  25. $this->safetags[1][1] = '&_PHX_INTERNAL_093_&';
  26. $this->safetags[2][0] = '[';
  27. $this->safetags[2][1] = ']';
  28. $this->console = array();
  29. $this->debug = ($debug!='') ? $debug : 0;
  30. $this->debugLog = false;
  31. $this->curPass = 0;
  32. $this->maxPasses = ($maxpass!='') ? $maxpass : 50;
  33. $this->swapSnippetCache = array();
  34. $modx->setPlaceholder("phx", "&_PHX_INTERNAL_&");
  35. }
  36. // Plugin event hook for MODX
  37. function OnParseDocument() {
  38. global $modx;
  39. // Get document output from MODX
  40. $template = $modx->documentOutput;
  41. // To the parse cave .. let's go! *insert batman tune here*
  42. $template = $this->Parse($template);
  43. // Set processed document output in MODX
  44. $modx->documentOutput = $template;
  45. }
  46. // Parser: Preparation, cleaning and checkup
  47. function Parse($template='') {
  48. global $modx;
  49. // If we already reached max passes don't get at it again.
  50. if ($this->curPass == $this->maxPasses) return $template;
  51. // Set template pre-process hash
  52. $st = md5($template);
  53. // Replace non-call characters in the template: [, ]
  54. $template = preg_replace($this->safetags[0],$this->safetags[1],$template);
  55. // To the parse mobile.. let's go! *insert batman tune here*
  56. $template = $this->ParseValues($template);
  57. // clean up unused placeholders that have modifiers attached (MODX can't clean them)
  58. preg_match_all('~\[(\+|\*|\()([^:\+\[\]]+)([^\[\]]*?)(\1|\))\]~s', $template, $matches);
  59. if ($matches[0]) {
  60. $template = str_replace($matches[0], '', $template);
  61. $this->Log("Cleaning unsolved tags: \n" . implode("\n",$matches[2]) );
  62. }
  63. // Restore non-call characters in the template: [, ]
  64. $template = str_replace($this->safetags[1],$this->safetags[2],$template);
  65. // Set template post-process hash
  66. $et = md5($template);
  67. // If template has changed, parse it once more...
  68. if ($st!=$et) $template = $this->Parse($template);
  69. // Write an event log if debugging is enabled and there is something to log
  70. if ($this->debug && $this->debugLog) {
  71. $modx->logEvent($this->curPass,1,$this->createEventLog(), $this->name.' '.$this->version);
  72. $this->debugLog = false;
  73. }
  74. // Return the processed template
  75. return $template;
  76. }
  77. // Parser: Tag detection and replacements
  78. function ParseValues($template='') {
  79. global $modx;
  80. $this->curPass = $this->curPass + 1;
  81. $st = md5($template);
  82. //$this->LogSource($template);
  83. $this->LogPass();
  84. // MODX Chunks
  85. $this->Log("MODX Chunks -> Merging all chunk tags");
  86. $template = $modx->mergeChunkContent($template);
  87. // MODX Snippets
  88. //if ( preg_match_all('~\[(\[|!)([^\[]*?)(!|\])\]~s',$template, $matches)) {
  89. if ( preg_match_all('~\[(\[)([^\[]*?)(\])\]~s',$template, $matches)) {
  90. $count = count($matches[0]);
  91. $var_search = array();
  92. $var_replace = array();
  93. // for each detected snippet
  94. for($i=0; $i<$count; $i++) {
  95. $snippet = $matches[2][$i]; // snippet call
  96. $this->Log("MODX Snippet -> ".$snippet);
  97. // Let MODX evaluate snippet
  98. $replace = $modx->evalSnippets("[[".$snippet."]]");
  99. $this->LogSnippet($replace);
  100. // Replace values
  101. $var_search[] = $matches[0][$i];
  102. $var_replace[] = $replace;
  103. }
  104. $template = str_replace($var_search, $var_replace, $template);
  105. }
  106. // PHx / MODX Tags
  107. if ( preg_match_all('~\[(\+|\*|\()([^:\+\[\]]+)([^\[\]]*?)(\1|\))\]~s',$template, $matches)) {
  108. //$matches[0] // Complete string that's need to be replaced
  109. //$matches[1] // Type
  110. //$matches[2] // The placeholder(s)
  111. //$matches[3] // The modifiers
  112. //$matches[4] // Type (end character)
  113. $count = count($matches[0]);
  114. $var_search = array();
  115. $var_replace = array();
  116. for($i=0; $i<$count; $i++) {
  117. $replace = NULL;
  118. $match = $matches[0][$i];
  119. $type = $matches[1][$i];
  120. $type_end = $matches[4][$i];
  121. $input = $matches[2][$i];
  122. $modifiers = $matches[3][$i];
  123. $var_search[] = $match;
  124. switch($type) {
  125. // Document / Template Variable eXtended
  126. case "*":
  127. $this->Log("MODX TV/DV: " . $input);
  128. $input = $modx->mergeDocumentContent("[*".$input."*]");
  129. $replace = $this->Filter($input,$modifiers);
  130. break;
  131. // MODX Setting eXtended
  132. case "(":
  133. $this->Log("MODX Setting variable: " . $input);
  134. $input = $modx->mergeSettingsContent("[(".$input.")]");
  135. $replace = $this->Filter($input,$modifiers);
  136. break;
  137. // MODX Placeholder eXtended
  138. default:
  139. $this->Log("MODX / PHx placeholder variable: " . $input);
  140. // Check if placeholder is set
  141. if ( !array_key_exists($input, $this->placeholders) && !array_key_exists($input, $modx->placeholders) ) {
  142. // not set so try again later.
  143. $replace = $match;
  144. $this->Log(" |--- Skipping - hasn't been set yet.");
  145. }
  146. else {
  147. // is set, get value and run filter
  148. $input = $this->getPHxVariable($input);
  149. $replace = $this->Filter($input,$modifiers);
  150. }
  151. break;
  152. }
  153. $var_replace[] = $replace;
  154. }
  155. $template = str_replace($var_search, $var_replace, $template);
  156. }
  157. $et = md5($template); // Post-process template hash
  158. // Log an event if this was the maximum pass
  159. if ($this->curPass == $this->maxPasses) $this->Log("Max passes reached. infinite loop protection so exiting.\n If you need the extra passes set the max passes to the highest count of nested tags in your template.");
  160. // If this pass is not at maximum passes and the template hash is not the same, get at it again.
  161. if (($this->curPass < $this->maxPasses) && ($st!=$et)) $template = $this->ParseValues($template);
  162. return $template;
  163. }
  164. // Parser: modifier detection and eXtended processing if needed
  165. function Filter($input, $modifiers) {
  166. global $modx;
  167. $output = $input;
  168. $this->Log(" |--- Input = '". $output ."'");
  169. if (preg_match_all('~:([^:=]+)(?:=`(.*?)`(?=:[^:=]+|$))?~s',$modifiers, $matches)) {
  170. $modifier_cmd = $matches[1]; // modifier command
  171. $modifier_value = $matches[2]; // modifier value
  172. $count = count($modifier_cmd);
  173. $condition = array();
  174. for($i=0; $i<$count; $i++) {
  175. $output = trim($output);
  176. $this->Log(" |--- Modifier = '". $modifier_cmd[$i] ."'");
  177. if ($modifier_value[$i] != '') $this->Log(" |--- Options = '". $modifier_value[$i] ."'");
  178. switch ($modifier_cmd[$i]) {
  179. ##### Conditional Modifiers
  180. case "input": case "if": $output = $modifier_value[$i]; break;
  181. case "equals": case "is": case "eq": $condition[] = intval(($output==$modifier_value[$i])); break;
  182. case "notequals": case "isnot": case "isnt": case "ne":$condition[] = intval(($output!=$modifier_value[$i]));break;
  183. case "isgreaterthan": case "isgt": case "eg": $condition[] = intval(($output>=$modifier_value[$i]));break;
  184. case "islowerthan": case "islt": case "el": $condition[] = intval(($output<=$modifier_value[$i]));break;
  185. case "greaterthan": case "gt": $condition[] = intval(($output>$modifier_value[$i]));break;
  186. case "lowerthan": case "lt":$condition[] = intval(($output<$modifier_value[$i]));break;
  187. case "isinrole": case "ir": case "memberof": case "mo": // Is Member Of (same as inrole but this one can be stringed as a conditional)
  188. if ($output == "&_PHX_INTERNAL_&") $output = $this->user["id"];
  189. $grps = (strlen($modifier_value) > 0 ) ? array_filter(array_map('trim', explode(',', $modifier_value[$i]))) :array();
  190. $condition[] = intval($this->isMemberOfWebGroupByUserId($output,$grps));
  191. break;
  192. case "or":$condition[] = "||";break;
  193. case "and": $condition[] = "&&";break;
  194. case "show":
  195. $conditional = implode(' ',$condition);
  196. $isvalid = intval(eval("return (". $conditional. ");"));
  197. if (!$isvalid) { $output = NULL;}
  198. case "then":
  199. $conditional = implode(' ',$condition);
  200. $isvalid = intval(eval("return (". $conditional. ");"));
  201. if ($isvalid) { $output = $modifier_value[$i]; }
  202. else { $output = NULL; }
  203. break;
  204. case "else":
  205. $conditional = implode(' ',$condition);
  206. $isvalid = intval(eval("return (". $conditional. ");"));
  207. if (!$isvalid) { $output = $modifier_value[$i]; }
  208. break;
  209. case "select":
  210. $raw = explode("&",$modifier_value[$i]);
  211. $map = array();
  212. for($m=0; $m<(count($raw)); $m++) {
  213. $mi = explode("=",$raw[$m]);
  214. $map[$mi[0]] = $mi[1];
  215. }
  216. $output = $map[$output];
  217. break;
  218. ##### End of Conditional Modifiers
  219. ##### String Modifiers
  220. case "lcase": $output = strtolower($output); break;
  221. case "ucase": $output = strtoupper($output); break;
  222. case "ucfirst": $output = ucfirst($output); break;
  223. case "htmlent": $output = htmlentities($output,ENT_QUOTES,$modx->config['etomite_charset']); break;
  224. case "esc":
  225. $output = preg_replace("/&amp;(#[0-9]+|[a-z]+);/i", "&$1;", htmlspecialchars($output));
  226. $output = str_replace(array("[","]","`"),array("&#91;","&#93;","&#96;"),$output);
  227. break;
  228. case "strip": $output = preg_replace("~([\n\r\t\s]+)~"," ",$output); break;
  229. case "notags": $output = strip_tags($output); break;
  230. case "length": case "len": $output = strlen($output); break;
  231. case "reverse": $output = strrev($output); break;
  232. case "wordwrap": // default: 70
  233. $wrapat = intval($modifier_value[$i]) ? intval($modifier_value[$i]) : 70;
  234. $output = preg_replace("~(\b\w+\b)~e","wordwrap('\\1',\$wrapat,' ',1)",$output);
  235. break;
  236. case "limit": // default: 100
  237. $limit = intval($modifier_value[$i]) ? intval($modifier_value[$i]) : 100;
  238. $output = substr($output,0,$limit);
  239. break;
  240. ##### Special functions
  241. case "math":
  242. $filter = preg_replace("~([a-zA-Z\n\r\t\s])~","",$modifier_value[$i]);
  243. $filter = str_replace("?",$output,$filter);
  244. $output = eval("return ".$filter.";");
  245. break;
  246. case "ifempty": if (empty($output)) $output = $modifier_value[$i]; break;
  247. case "nl2br": $output = nl2br($output); break;
  248. case "date": $output = strftime($modifier_value[$i],0+$output); break;
  249. case "set":
  250. $c = $i+1;
  251. if ($count>$c&&$modifier_cmd[$c]=="value") $output = preg_replace("~([^a-zA-Z0-9])~","",$modifier_value[$i]);
  252. break;
  253. case "value":
  254. if ($i>0&&$modifier_cmd[$i-1]=="set") { $modx->SetPlaceholder("phx.".$output,$modifier_value[$i]); }
  255. $output = NULL;
  256. break;
  257. case "md5": $output = md5($output); break;
  258. case "userinfo":
  259. if ($output == "&_PHX_INTERNAL_&") $output = $this->user["id"];
  260. $output = $this->ModUser($output,$modifier_value[$i]);
  261. break;
  262. case "inrole": // deprecated
  263. if ($output == "&_PHX_INTERNAL_&") $output = $this->user["id"];
  264. $grps = (strlen($modifier_value) > 0 ) ? array_filter(array_map('trim', explode(',', $modifier_value[$i]))) :array();
  265. $output = intval($this->isMemberOfWebGroupByUserId($output,$grps));
  266. break;
  267. default:
  268. if (!array_key_exists($modifier_cmd[$i], $this->cache["cm"])) {
  269. $result = $modx->db->select('snippet', $modx->getFullTableName("site_snippets"), "name='phx:".$modifier_cmd[$i]."'");
  270. if ($snippet = $modx->db->getValue($result)) {
  271. $cm = $this->cache["cm"][$modifier_cmd[$i]] = $snippet;
  272. $this->Log(" |--- DB -> Custom Modifier");
  273. }
  274. } else {
  275. $cm = $this->cache["cm"][$modifier_cmd[$i]];
  276. $this->Log(" |--- Cache -> Custom Modifier");
  277. }
  278. ob_start();
  279. $options = $modifier_value[$i];
  280. $custom = eval($cm);
  281. $msg = ob_get_contents();
  282. $output = $msg.$custom;
  283. ob_end_clean();
  284. break;
  285. }
  286. if (count($condition)) $this->Log(" |--- Condition = '". $condition[count($condition)-1] ."'");
  287. $this->Log(" |--- Output = '". $output ."'");
  288. }
  289. }
  290. return $output;
  291. }
  292. // Event logging (debug)
  293. function createEventLog() {
  294. if($this->console) {
  295. $console = implode("\n",$this->console);
  296. $this->console = array();
  297. return '<pre style="overflow: auto;">' . $console . '</pre>';
  298. }
  299. }
  300. // Returns a cleaned string escaping the HTML and special MODX characters
  301. function LogClean($string) {
  302. $string = preg_replace("/&amp;(#[0-9]+|[a-z]+);/i", "&$1;", htmlspecialchars($string));
  303. $string = str_replace(array("[","]","`"),array("&#91;","&#93;","&#96;"),$string);
  304. return $string;
  305. }
  306. // Simple log entry
  307. function Log($string) {
  308. if ($this->debug) {$this->debugLog = true; $this->console[] = (count($this->console)+1-$this->curPass). " [". strftime("%H:%M:%S",time()). "] " . $this->LogClean($string);}
  309. }
  310. // Log snippet output
  311. function LogSnippet($string) {
  312. if ($this->debug) {$this->debugLog = true; $this->console[] = (count($this->console)+1-$this->curPass). " [". strftime("%H:%M:%S",time()). "] " . " |--- Returns: <div style='margin: 10px;'>".$this->LogClean($string)."</div>";}
  313. }
  314. // Log pass
  315. function LogPass() {
  316. $this->console[] = "<div style='margin: 2px;margin-top: 5px;border-bottom: 1px solid black;'>Pass " . $this->curPass . "</div>";
  317. }
  318. // Log pass
  319. function LogSource($string) {
  320. $this->console[] = "<div style='margin: 2px;margin-top: 5px;border-bottom: 1px solid black;'>Source:</div>" . $this->LogClean($string);
  321. }
  322. // Returns the specified field from the user record
  323. // positive userid = manager, negative integer = webuser
  324. function ModUser($userid,$field) {
  325. global $modx;
  326. if (!array_key_exists($userid, $this->cache["ui"])) {
  327. if (intval($userid) < 0) {
  328. $user = $modx->getWebUserInfo(-($userid));
  329. } else {
  330. $user = $modx->getUserInfo($userid);
  331. }
  332. $this->cache["ui"][$userid] = $user;
  333. } else {
  334. $user = $this->cache["ui"][$userid];
  335. }
  336. return $user[$field];
  337. }
  338. // Returns true if the user id is in one the specified webgroups
  339. function isMemberOfWebGroupByUserId($userid=0,$groupNames=array()) {
  340. global $modx;
  341. // if $groupNames is not an array return false
  342. if(!is_array($groupNames)) return false;
  343. // if the user id is a negative number make it positive
  344. if (intval($userid) < 0) { $userid = -($userid); }
  345. // Creates an array with all webgroups the user id is in
  346. if (!array_key_exists($userid, $this->cache["mo"])) {
  347. $tbl = $modx->getFullTableName("webgroup_names");
  348. $tbl2 = $modx->getFullTableName("web_groups");
  349. $rs = $modx->db->select('wgn.name', "$tbl AS wgn INNER JOIN $tbl2 AS wg ON wg.webgroup=wgn.id AND wg.webuser='{$userid}'");
  350. $this->cache["mo"][$userid] = $grpNames = $modx->db->getColumn("name",$rs);
  351. } else {
  352. $grpNames = $this->cache["mo"][$userid];
  353. }
  354. // Check if a supplied group matches a webgroup from the array we just created
  355. foreach($groupNames as $k=>$v)
  356. if(in_array(trim($v),$grpNames)) return true;
  357. // If we get here the above logic did not find a match, so return false
  358. return false;
  359. }
  360. // Returns the value of a PHx/MODX placeholder.
  361. function getPHxVariable($name) {
  362. global $modx;
  363. // Check if this variable is created by PHx
  364. if (array_key_exists($name, $this->placeholders)) {
  365. // Return the value from PHx
  366. return $this->placeholders[$name];
  367. } else {
  368. // Return the value from MODX
  369. return $modx->getPlaceholder($name);
  370. }
  371. }
  372. // Sets a placeholder variable which can only be access by PHx
  373. function setPHxVariable($name, $value) {
  374. if ($name != "phx") $this->placeholders[$name] = $value;
  375. }
  376. }
  377. ?>