PageRenderTime 58ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/system/expressionengine/libraries/Template.php

https://bitbucket.org/sims/heartbeets
PHP | 3860 lines | 3672 code | 80 blank | 108 comment | 52 complexity | 9b6fca1e70ebc2fb4ca0a444eaf28d2d MD5 | raw file

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

  1. <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
  2. /**
  3. * ExpressionEngine - by EllisLab
  4. *
  5. * @package ExpressionEngine
  6. * @author ExpressionEngine Dev Team
  7. * @copyright Copyright (c) 2003 - 2011, EllisLab, Inc.
  8. * @license http://expressionengine.com/user_guide/license.html
  9. * @link http://expressionengine.com
  10. * @since Version 2.0
  11. * @filesource
  12. */
  13. // ------------------------------------------------------------------------
  14. /**
  15. * ExpressionEngine Template Parser Class
  16. *
  17. * @package ExpressionEngine
  18. * @subpackage Core
  19. * @category Core
  20. * @author ExpressionEngine Dev Team
  21. * @link http://expressionengine.com
  22. */
  23. class EE_Template {
  24. var $loop_count = 0; // Main loop counter.
  25. var $depth = 0; // Sub-template loop depth
  26. var $in_point = ''; // String position of matched opening tag
  27. var $template = ''; // The requested template (page)
  28. var $final_template = ''; // The finalized template
  29. var $fl_tmpl = ''; // 'Floating' copy of the template. Used as a temporary "work area".
  30. var $cache_hash = ''; // md5 checksum of the template name. Used as title of cache file.
  31. var $cache_status = ''; // Status of page cache (NO_CACHE, CURRENT, EXPIRED)
  32. var $tag_cache_status = ''; // Status of tag cache (NO_CACHE, CURRENT, EXPIRED)
  33. var $cache_timestamp = '';
  34. var $template_type = ''; // Type of template (webpage, rss)
  35. var $embed_type = ''; // Type of template for embedded template
  36. var $template_hits = 0;
  37. var $php_parse_location = 'output'; // Where in the chain the PHP gets parsed
  38. var $template_edit_date = ''; // Template edit date
  39. var $templates_sofar = ''; // Templates processed so far, subtemplate tracker
  40. var $encode_email = TRUE; // Whether to use the email encoder. This is set automatically
  41. var $hit_lock_override = FALSE; // Set to TRUE if you want hits tracked on sub-templates
  42. var $hit_lock = FALSE; // Lets us lock the hit counter if sub-templates are contained in a template
  43. var $parse_php = FALSE; // Whether to parse PHP or not
  44. var $protect_javascript = TRUE; // Protect javascript in conditionals
  45. var $tag_data = array(); // Data contained in tags
  46. var $modules = array(); // List of installed modules
  47. var $module_data = array(); // Data for modules from exp_channels
  48. var $plugins = array(); // List of installed plug-ins
  49. var $var_single = array(); // "Single" variables
  50. var $var_cond = array(); // "Conditional" variables
  51. var $var_pair = array(); // "Paired" variables
  52. var $global_vars = array(); // This array can be set via the path.php file
  53. var $embed_vars = array(); // This array can be set via the {embed} tag
  54. var $segment_vars = array(); // Array of segment variables
  55. var $tagparts = array(); // The parts of the tag: {exp:comment:form}
  56. var $tagdata = ''; // The chunk between tag pairs. This is what modules will utilize
  57. var $tagproper = ''; // The full opening tag
  58. var $no_results = ''; // The contents of the {if no_results}{/if} conditionals
  59. var $no_results_block = ''; // The {if no_results}{/if} chunk
  60. var $search_fields = array(); // Special array of tag parameters that begin with 'search:'
  61. var $date_vars = array(); // Date variables found in the tagdata (FALSE if date variables do not exist in tagdata)
  62. var $unfound_vars = array(); // These are variables that have not been found in the tagdata and can be ignored
  63. var $conditional_vars = array(); // Used by the template variable parser to prep conditionals
  64. var $TYPE = FALSE; // FALSE if Typography has not been instantiated, Typography Class object otherwise
  65. var $related_data = array(); // A multi-dimensional array containing any related tags
  66. var $related_id = ''; // Used temporarily for the related ID number
  67. var $related_markers = array(); // Used temporarily
  68. var $site_ids = array(); // Site IDs for the Sites Request for a Tag
  69. var $sites = array(); // Array of sites with site_id as key and site_name as value, used to determine site_ids for tag, above.
  70. var $site_prefs_cache = array(); // Array of cached site prefs, to allow fetching of another site's template files
  71. var $reverse_related_data = array(); // A multi-dimensional array containing any reverse related tags
  72. var $t_cache_path = 'tag_cache/'; // Location of the tag cache file
  73. var $p_cache_path = 'page_cache/'; // Location of the page cache file
  74. var $disable_caching = FALSE;
  75. var $debugging = FALSE; // Template parser debugging on?
  76. var $cease_processing = FALSE; // Used with no_results() method.
  77. var $log = array(); // Log of Template processing
  78. var $start_microtime = 0; // For Logging (= microtime())
  79. var $strict_urls = FALSE; // Whether to make URLs operate strictly or not. This is set via a template global pref
  80. var $realm = 'ExpressionEngine Template'; // Localize?
  81. var $marker = '0o93H7pQ09L8X1t49cHY01Z5j4TT91fGfr'; // Temporary marker used as a place-holder for template data
  82. var $form_id = ''; // Form Id
  83. var $form_class = ''; // Form Class
  84. // --------------------------------------------------------------------
  85. /**
  86. * Constructor
  87. *
  88. * @return void
  89. */
  90. public function __construct()
  91. {
  92. // Make a local reference to the ExpressionEngine super object
  93. $this->EE =& get_instance();
  94. if ($this->EE->config->item('multiple_sites_enabled') != 'y')
  95. {
  96. $this->sites[$this->EE->config->item('site_id')] = $this->EE->config->item('site_short_name');
  97. }
  98. if ($this->EE->config->item('template_debugging') === 'y' && $this->EE->session->userdata['group_id'] == 1)
  99. {
  100. $this->debugging = TRUE;
  101. $this->start_microtime = microtime(TRUE);
  102. }
  103. }
  104. // --------------------------------------------------------------------
  105. /**
  106. * Run Template Engine
  107. *
  108. * Upon a Page or a Preview, it Runs the Processing of a Template
  109. * based on URI request or method arguments
  110. *
  111. * @param string
  112. * @param string
  113. * @return void
  114. */
  115. public function run_template_engine($template_group = '', $template = '')
  116. {
  117. $this->log_item(" - Begin Template Processing - ");
  118. // Set the name of the cache folder for both tag and page caching
  119. if ($this->EE->uri->uri_string != '')
  120. {
  121. $this->t_cache_path .= md5($this->EE->functions->fetch_site_index().$this->EE->uri->uri_string).'/';
  122. $this->p_cache_path .= md5($this->EE->functions->fetch_site_index().$this->EE->uri->uri_string).'/';
  123. }
  124. else
  125. {
  126. $this->t_cache_path .= md5($this->EE->config->item('site_url').'index'.$this->EE->uri->query_string).'/';
  127. $this->p_cache_path .= md5($this->EE->config->item('site_url').'index'.$this->EE->uri->query_string).'/';
  128. }
  129. // We limit the total number of cache files in order to
  130. // keep some sanity with large sites or ones that get
  131. // hit by over-ambitious crawlers.
  132. if ($this->disable_caching == FALSE)
  133. {
  134. if ($dh = @opendir(APPPATH.'cache/page_cache'))
  135. {
  136. $i = 0;
  137. while (FALSE !== (readdir($dh)))
  138. {
  139. $i++;
  140. }
  141. $max = ( ! $this->EE->config->item('max_caches') OR ! is_numeric($this->EE->config->item('max_caches')) OR $this->EE->config->item('max_caches') > 1000) ? 1000 : $this->EE->config->item('max_caches');
  142. if ($i > $max)
  143. {
  144. $this->EE->functions->clear_caching('page');
  145. }
  146. }
  147. }
  148. $this->log_item("URI: ".$this->EE->uri->uri_string);
  149. $this->log_item("Path.php Template: {$template_group}/{$template}");
  150. $this->fetch_and_parse($template_group, $template, FALSE);
  151. $this->log_item(" - End Template Processing - ");
  152. $this->log_item("Parse Global Variables");
  153. if ($this->template_type == 'static')
  154. {
  155. $this->final_template = $this->restore_xml_declaration($this->final_template);
  156. }
  157. else
  158. {
  159. $this->final_template = $this->parse_globals($this->final_template);
  160. }
  161. $this->log_item("Template Parsing Finished");
  162. $this->EE->output->out_type = $this->template_type;
  163. $this->EE->output->set_output($this->final_template);
  164. }
  165. // --------------------------------------------------------------------
  166. /**
  167. * Fetch and Process Template
  168. *
  169. * Determines what template to process, fetches the template and its preferences, and then processes all of it
  170. *
  171. * @param string
  172. * @param string
  173. * @param bool
  174. * @param int
  175. * @return void
  176. */
  177. public function fetch_and_parse($template_group = '', $template = '', $sub = FALSE, $site_id = '')
  178. {
  179. // add this template to our subtemplate tracker
  180. $this->templates_sofar = $this->templates_sofar.'|'.$site_id.':'.$template_group.'/'.$template.'|';
  181. // Fetch the requested template
  182. // The template can either come from the DB or a cache file
  183. // Do not use a reference!
  184. $this->cache_status = 'NO_CACHE';
  185. $this->log_item("Retrieving Template");
  186. $this->template = ($template_group != '' AND $template != '') ? $this->fetch_template($template_group, $template, FALSE, $site_id) : $this->parse_template_uri();
  187. $this->log_item("Template Type: ".$this->template_type);
  188. $this->parse($this->template, $sub, $site_id);
  189. }
  190. // --------------------------------------------------------------------
  191. /**
  192. * Parse a string as a template
  193. *
  194. * @param string
  195. * @param string
  196. * @return void
  197. */
  198. public function parse(&$str, $sub = FALSE, $site_id = '')
  199. {
  200. if ($str != '')
  201. {
  202. $this->template =& $str;
  203. }
  204. // Static Content, No Parsing
  205. if ($this->template_type == 'static' OR $this->embed_type == 'static')
  206. {
  207. if ($sub == FALSE)
  208. {
  209. $this->final_template = $this->template;
  210. }
  211. return;
  212. }
  213. /* -------------------------------------
  214. /* "Smart" Static Parsing
  215. /*
  216. /* Performed on embedded webpage templates only that do not have
  217. /* ExpressionEngine tags or PHP in them.
  218. /*
  219. /* Hidden Configuration Variable
  220. /* - smart_static_parsing => Bypass parsing of templates that could be
  221. /* of the type 'static' but aren't? (y/n)
  222. /* -------------------------------------*/
  223. if ($this->EE->config->item('smart_static_parsing') !== 'n' && $this->embed_type == 'webpage' && ! stristr($this->template, LD) && ! stristr($this->template, '<?'))
  224. {
  225. $this->log_item("Smart Static Parsing Triggered");
  226. if ($sub == FALSE)
  227. {
  228. $this->final_template = $this->template;
  229. }
  230. return;
  231. }
  232. // Parse 'Site' variables
  233. $this->log_item("Parsing Site Variables");
  234. // load site variables into the global_vars array
  235. foreach (array('site_id', 'site_label', 'site_short_name') as $site_var)
  236. {
  237. $this->EE->config->_global_vars[$site_var] = stripslashes($this->EE->config->item($site_var));
  238. }
  239. // Parse {last_segment} variable
  240. $seg_array = $this->EE->uri->segment_array();
  241. $this->EE->config->_global_vars['last_segment'] = end($seg_array);
  242. // Parse manual variables and Snippets
  243. // These are variables that can be set in the path.php file
  244. if (count($this->EE->config->_global_vars) > 0)
  245. {
  246. $this->log_item("Snippets (Keys): ".implode('|', array_keys($this->EE->config->_global_vars)));
  247. $this->log_item("Snippets (Values): ".trim(implode('|', $this->EE->config->_global_vars)));
  248. foreach ($this->EE->config->_global_vars as $key => $val)
  249. {
  250. $this->template = str_replace(LD.$key.RD, $val, $this->template);
  251. }
  252. // in case any of these variables have EE comments of their own
  253. $this->template = $this->remove_ee_comments($this->template);
  254. }
  255. // Parse URI segments
  256. // This code lets admins fetch URI segments which become
  257. // available as: {segment_1} {segment_2}
  258. for ($i = 1; $i < 10; $i++)
  259. {
  260. $this->template = str_replace(LD.'segment_'.$i.RD, $this->EE->uri->segment($i), $this->template);
  261. $this->segment_vars['segment_'.$i] = $this->EE->uri->segment($i);
  262. }
  263. // Parse {embed} tag variables
  264. if ($sub === TRUE && count($this->embed_vars) > 0)
  265. {
  266. $this->log_item("Embed Variables (Keys): ".implode('|', array_keys($this->embed_vars)));
  267. $this->log_item("Embed Variables (Values): ".trim(implode('|', $this->embed_vars)));
  268. foreach ($this->embed_vars as $key => $val)
  269. {
  270. // add 'embed:' to the key for replacement and so these variables work in conditionals
  271. $this->embed_vars['embed:'.$key] = $val;
  272. unset($this->embed_vars[$key]);
  273. $this->template = str_replace(LD.'embed:'.$key.RD, $val, $this->template);
  274. }
  275. }
  276. // cleanup of leftover/undeclared embed variables
  277. // don't worry with undeclared embed: vars in conditionals as the conditionals processor will handle that adequately
  278. if (strpos($this->template, LD.'embed:') !== FALSE)
  279. {
  280. $this->template = preg_replace('/'.LD.'embed:([^!]+?)'.RD.'/', '', $this->template);
  281. }
  282. // Parse date format string "constants"
  283. $date_constants = array('DATE_ATOM' => '%Y-%m-%dT%H:%i:%s%Q',
  284. 'DATE_COOKIE' => '%l, %d-%M-%y %H:%i:%s UTC',
  285. 'DATE_ISO8601' => '%Y-%m-%dT%H:%i:%s%Q',
  286. 'DATE_RFC822' => '%D, %d %M %y %H:%i:%s %O',
  287. 'DATE_RFC850' => '%l, %d-%M-%y %H:%m:%i UTC',
  288. 'DATE_RFC1036' => '%D, %d %M %y %H:%i:%s %O',
  289. 'DATE_RFC1123' => '%D, %d %M %Y %H:%i:%s %O',
  290. 'DATE_RFC2822' => '%D, %d %M %Y %H:%i:%s %O',
  291. 'DATE_RSS' => '%D, %d %M %Y %H:%i:%s %O',
  292. 'DATE_W3C' => '%Y-%m-%dT%H:%i:%s%Q'
  293. );
  294. foreach ($date_constants as $key => $val)
  295. {
  296. $this->template = str_replace(LD.$key.RD, $val, $this->template);
  297. }
  298. $this->log_item("Parse Date Format String Constants");
  299. // Template's Last Edit time {template_edit_date format="%Y %m %d %H:%i:%s"}
  300. if (strpos($this->template, LD.'template_edit_date') !== FALSE && preg_match_all("/".LD."template_edit_date\s+format=([\"\'])([^\\1]*?)\\1".RD."/", $this->template, $matches))
  301. {
  302. for ($j = 0; $j < count($matches[0]); $j++)
  303. {
  304. $this->template = str_replace($matches[0][$j], $this->EE->localize->decode_date($matches[2][$j], $this->template_edit_date), $this->template);
  305. }
  306. }
  307. // Current time {current_time format="%Y %m %d %H:%i:%s"}
  308. if (strpos($this->template, LD.'current_time') !== FALSE && preg_match_all("/".LD."current_time\s+format=([\"\'])([^\\1]*?)\\1".RD."/", $this->template, $matches))
  309. {
  310. for ($j = 0; $j < count($matches[0]); $j++)
  311. {
  312. $this->template = str_replace($matches[0][$j], $this->EE->localize->decode_date($matches[2][$j], $this->EE->localize->now), $this->template);
  313. }
  314. }
  315. $this->template = str_replace(LD.'current_time'.RD, $this->EE->localize->now, $this->template);
  316. $this->log_item("Parse Current Time Variables");
  317. // Is the main template cached?
  318. // If a cache file exists for the primary template
  319. // there is no reason to go further.
  320. // However we do need to fetch any subtemplates
  321. if ($this->cache_status == 'CURRENT' AND $sub == FALSE)
  322. {
  323. $this->log_item("Cached Template Used");
  324. $this->template = $this->parse_nocache($this->template);
  325. // Smite Our Enemies: Advanced Conditionals
  326. if (stristr($this->template, LD.'if'))
  327. {
  328. $this->template = $this->advanced_conditionals($this->template);
  329. }
  330. $this->log_item("Conditionals Parsed, Processing Sub Templates");
  331. $this->final_template = $this->template;
  332. $this->process_sub_templates($this->template);
  333. return;
  334. }
  335. // Remove whitespace from variables.
  336. // This helps prevent errors, particularly if PHP is used in a template
  337. $this->template = preg_replace("/".LD."\s*(\S+)\s*".RD."/U", LD."\\1".RD, $this->template);
  338. // Parse Input Stage PHP
  339. if ($this->parse_php == TRUE && $this->php_parse_location == 'input' && $this->cache_status != 'CURRENT')
  340. {
  341. $this->log_item("Parsing PHP on Input");
  342. $this->template = $this->parse_template_php($this->template);
  343. }
  344. // Smite Our Enemies: Conditionals
  345. $this->log_item("Parsing Segment, Embed, and Global Vars Conditionals");
  346. $this->template = $this->parse_simple_segment_conditionals($this->template);
  347. $this->template = $this->simple_conditionals($this->template, $this->embed_vars);
  348. $this->template = $this->simple_conditionals($this->template, $this->EE->config->_global_vars);
  349. // Assign Variables
  350. if (strpos($this->template, 'preload_replace') !== FALSE)
  351. {
  352. if (preg_match_all("/".LD."preload_replace:(.+?)=([\"\'])([^\\2]*?)\\2".RD."/i", $this->template, $matches))
  353. {
  354. $this->log_item("Processing Preload Text Replacements: ".trim(implode('|', $matches[1])));
  355. for ($j = 0; $j < count($matches[0]); $j++)
  356. {
  357. $this->template = str_replace($matches[0][$j], "", $this->template);
  358. $this->template = str_replace(LD.$matches[1][$j].RD, $matches[3][$j], $this->template);
  359. }
  360. }
  361. }
  362. // Parse Plugin and Module Tags
  363. $this->tags();
  364. if ($this->cease_processing === TRUE)
  365. {
  366. return;
  367. }
  368. // Parse Output Stage PHP
  369. if ($this->parse_php == TRUE AND $this->php_parse_location == 'output' AND $this->cache_status != 'CURRENT')
  370. {
  371. $this->log_item("Parsing PHP on Output");
  372. $this->template = $this->parse_template_php($this->template);
  373. }
  374. // Write the cache file if needed
  375. if ($this->cache_status == 'EXPIRED')
  376. {
  377. $this->template = $this->EE->functions->insert_action_ids($this->template);
  378. $this->write_cache_file($this->cache_hash, $this->template, 'template');
  379. }
  380. // Parse Our Uncacheable Forms
  381. $this->template = $this->parse_nocache($this->template);
  382. // Smite Our Enemies: Advanced Conditionals
  383. if (strpos($this->template, LD.'if') !== FALSE)
  384. {
  385. $this->log_item("Processing Advanced Conditionals");
  386. $this->template = $this->advanced_conditionals($this->template);
  387. }
  388. // Build finalized template
  389. // We only do this on the first pass.
  390. // The sub-template routine will insert embedded
  391. // templates into the master template
  392. if ($sub == FALSE)
  393. {
  394. $this->final_template = $this->template;
  395. $this->process_sub_templates($this->template);
  396. }
  397. }
  398. // --------------------------------------------------------------------
  399. /**
  400. * Processes Any Embedded Templates in String
  401. *
  402. * If any {embed=} tags are found, it processes those templates and does a replacement.
  403. *
  404. * @param string
  405. * @return void
  406. */
  407. public function process_sub_templates($template)
  408. {
  409. // Match all {embed=bla/bla} tags
  410. $matches = array();
  411. if ( ! preg_match_all("/(".LD."embed\s*=)(.*?)".RD."/s", $template, $matches))
  412. {
  413. return;
  414. }
  415. // Loop until we have parsed all sub-templates
  416. // For each embedded tag we encounter we'll run the template parsing
  417. // function - AND - through the beauty of recursive functions we
  418. // will also call THIS function as well, allowing us to parse
  419. // infinitely nested sub-templates in one giant loop o' love
  420. $this->log_item(" - Processing Sub Templates (Depth: ".($this->depth+1).") - ");
  421. $i = 0;
  422. $this->depth++;
  423. $this->log_item("List of Embeds: ".str_replace(array('"', "'"), '', trim(implode(',', $matches[2]))));
  424. // re-match the full tag of each if necessary before we start processing
  425. // necessary evil in case template globals are used inside the embed tag,
  426. // doing this within the processing loop will result in leaving unparsed
  427. // embed tags e.g. {embed="foo/bar" var="{global_var}/{custom_field}"}
  428. $temp = $template;
  429. foreach ($matches[2] as $key => $val)
  430. {
  431. if (strpos($val, LD) !== FALSE)
  432. {
  433. $matches[0][$key] = $this->EE->functions->full_tag($matches[0][$key], $temp);
  434. $matches[2][$key] = substr(str_replace($matches[1][$key], '', $matches[0][$key]), 0, -1);
  435. $temp = str_replace($matches[0][$key], '', $temp);
  436. }
  437. }
  438. // Load the string helper
  439. $this->EE->load->helper('string');
  440. foreach($matches[2] as $key => $val)
  441. {
  442. $parts = preg_split("/\s+/", $val, 2);
  443. $this->embed_vars = (isset($parts[1])) ? $this->EE->functions->assign_parameters($parts[1]) : array();
  444. if ($this->embed_vars === FALSE)
  445. {
  446. $this->embed_vars = array();
  447. }
  448. $val = trim_slashes(strip_quotes($parts[0]));
  449. if (strpos($val, '/') === FALSE)
  450. {
  451. continue;
  452. }
  453. $ex = explode("/", trim($val));
  454. if (count($ex) != 2)
  455. {
  456. continue;
  457. }
  458. // Determine Site
  459. $site_id = $this->EE->config->item('site_id');
  460. if (stristr($ex[0], ':'))
  461. {
  462. $name = substr($ex[0], 0, strpos($ex[0], ':'));
  463. if ($this->EE->config->item('multiple_sites_enabled') == 'y' && ! IS_FREELANCER)
  464. {
  465. if (count($this->sites) == 0)
  466. {
  467. // This should really be cached somewhere
  468. $this->EE->db->select('site_id, site_name');
  469. $sites_query = $this->EE->db->get('sites');
  470. foreach($sites_query->result_array() as $row)
  471. {
  472. $this->sites[$row['site_id']] = $row['site_name'];
  473. }
  474. }
  475. $site_id = array_search($name, $this->sites);
  476. if (empty($site_id))
  477. {
  478. $site_id = $this->EE->config->item('site_id');
  479. }
  480. }
  481. $ex[0] = str_replace($name.':', '', $ex[0]);
  482. }
  483. // Loop Prevention
  484. /* -------------------------------------------
  485. /* Hidden Configuration Variable
  486. /* - template_loop_prevention => 'n'
  487. Whether or not loop prevention is enabled - y/n
  488. /* -------------------------------------------*/
  489. if (substr_count($this->templates_sofar, '|'.$site_id.':'.$ex['0'].'/'.$ex['1'].'|') > 1 && $this->EE->config->item('template_loop_prevention') != 'n')
  490. {
  491. $this->final_template = ($this->EE->config->item('debug') >= 1) ? str_replace('%s', $ex['0'].'/'.$ex['1'], $this->EE->lang->line('template_loop')) : "";
  492. return;
  493. }
  494. // Process Subtemplate
  495. $this->log_item("Processing Sub Template: ".$ex[0]."/".$ex[1]);
  496. $this->fetch_and_parse($ex[0], $ex[1], TRUE, $site_id);
  497. $this->final_template = str_replace($matches[0][$key], $this->template, $this->final_template);
  498. $this->embed_type = '';
  499. // Here we go again! Wheeeeeee.....
  500. $this->process_sub_templates($this->template);
  501. // pull the subtemplate tracker back a level to the parent template
  502. $this->templates_sofar = substr($this->templates_sofar, 0, - strlen('|'.$site_id.':'.$ex[0].'/'.$ex[1].'|'));
  503. }
  504. $this->depth--;
  505. if ($this->depth == 0)
  506. {
  507. $this->templates_sofar = '';
  508. }
  509. }
  510. // --------------------------------------------------------------------
  511. /**
  512. * Finds Tags, Parses Them
  513. *
  514. * Goes Through the Template, Finds the Beginning and End of Tags, and Stores Tag Data in a Class Array
  515. *
  516. * @return void
  517. */
  518. public function parse_tags()
  519. {
  520. while (TRUE)
  521. {
  522. // Make a "floating" copy of the template which we'll progressively slice into pieces with each loop
  523. $this->fl_tmpl = $this->template;
  524. // Identify the string position of the first occurence of a matched tag
  525. $this->in_point = strpos($this->fl_tmpl, LD.'exp:');
  526. // If the above variable returns FALSE we are done looking for tags
  527. // This single conditional keeps the template engine from spiraling
  528. // out of control in an infinite loop.
  529. if (FALSE === $this->in_point)
  530. {
  531. break;
  532. }
  533. else
  534. {
  535. // Process the tag data
  536. // These REGEXs parse out the various components contained in any given tag.
  537. // Grab the opening portion of the tag: {exp:some:tag param="value" param="value"}
  538. if ( ! preg_match("/".LD.'exp:'.".*?".RD."/s", $this->fl_tmpl, $matches))
  539. {
  540. $this->template = preg_replace("/".LD.'exp:'.".*?$/", '', $this->template);
  541. break;
  542. }
  543. // Checking for variables/tags embedded within tags
  544. // {exp:channel:entries channel="{master_channel_name}"}
  545. if (stristr(substr($matches[0], 1), LD) !== FALSE)
  546. {
  547. $matches[0] = $this->EE->functions->full_tag($matches[0]);
  548. }
  549. $this->log_item("Tag: ".$matches[0]);
  550. $raw_tag = str_replace(array("\r\n", "\r", "\n", "\t"), " ", $matches[0]);
  551. $tag_length = strlen($raw_tag);
  552. $data_start = $this->in_point + $tag_length;
  553. $tag = trim(substr($raw_tag, 1, -1));
  554. $args = trim((preg_match("/\s+.*/", $tag, $matches))) ? $matches[0] : '';
  555. $tag = trim(str_replace($args, '', $tag));
  556. $cur_tag_close = LD.'/'.$tag.RD;
  557. // Deprecate "weblog" tags, but allow them to work until 2.1, then remove this.
  558. if (strpos($tag, ':weblog:') !== FALSE OR strpos($tag, ' weblog=') !== FALSE)
  559. {
  560. $tag = str_replace(array(':weblog:', ' weblog='), array(':channel:', ' channel='), $tag);
  561. $this->log_item("WARNING: Deprecated 'weblog' tag used, please change to 'channel'");
  562. }
  563. // -----------------------------------------
  564. // Grab the class name and method names contained in the tag
  565. $class = explode(':', substr($tag, strlen('exp') + 1));
  566. // Tags can either have one segment or two:
  567. // {exp:first_segment}
  568. // {exp:first_segment:second_segment}
  569. //
  570. // These two segments represent either a "class:constructor"
  571. // or a "class:method". We need to determine which one it is.
  572. // if (count($class) == 1)
  573. // {
  574. // $class[1] = $class[0];
  575. // }
  576. foreach($class as $key => $value)
  577. {
  578. $class[$key] = trim($value);
  579. }
  580. // -----------------------------------------
  581. // Assign parameters based on the arguments from the tag
  582. $args = $this->EE->functions->assign_parameters($args);
  583. // standardized mechanism for "search" type parameters get some extra lovin'
  584. $search_fields = array();
  585. if ($args !== FALSE)
  586. {
  587. foreach ($args as $key => $val)
  588. {
  589. if (strncmp($key, 'search:', 7) == 0)
  590. {
  591. $search_fields[substr($key, 7)] = $val;
  592. }
  593. }
  594. }
  595. // Trim the floating template, removing the tag we just parsed.
  596. $this->fl_tmpl = substr($this->fl_tmpl, $this->in_point + $tag_length);
  597. $out_point = strpos($this->fl_tmpl, $cur_tag_close);
  598. // Do we have a tag pair?
  599. if (FALSE !== $out_point)
  600. {
  601. // Assign the data contained between the opening/closing tag pair
  602. $this->log_item("Closing Tag Found");
  603. $block = substr($this->template, $data_start, $out_point);
  604. // Fetch the "no_results" data
  605. $no_results = '';
  606. $no_results_block = '';
  607. if (strpos($block, 'if no_results') !== FALSE && preg_match("/".LD."if no_results".RD."(.*?)".LD.'\/'."if".RD."/s", $block, $match))
  608. {
  609. // Match the entirety of the conditional, dude. Bad Rick!
  610. if (stristr($match[1], LD.'if'))
  611. {
  612. $match[0] = $this->EE->functions->full_tag($match[0], $block, LD.'if', LD.'\/'."if".RD);
  613. }
  614. $no_results = substr($match[0], strlen(LD."if no_results".RD), -strlen(LD.'/'."if".RD));
  615. $no_results_block = $match[0];
  616. }
  617. // Define the entire "chunk" - from the left edge of the opening tag
  618. // to the right edge of closing tag.
  619. $out_point = $out_point + $tag_length + strlen($cur_tag_close);
  620. $chunk = substr($this->template, $this->in_point, $out_point);
  621. }
  622. else
  623. {
  624. // Single tag...
  625. $this->log_item("No Closing Tag");
  626. $block = ''; // Single tags don't contain data blocks
  627. $no_results = '';
  628. $no_results_block = '';
  629. // Define the entire opening tag as a "chunk"
  630. $chunk = substr($this->template, $this->in_point, $tag_length);
  631. }
  632. // Strip the "chunk" from the template, replacing it with a unique marker.
  633. if (stristr($raw_tag, 'random'))
  634. {
  635. $this->template = preg_replace("|".preg_quote($chunk)."|s", 'M'.$this->loop_count.$this->marker, $this->template, 1);
  636. }
  637. else
  638. {
  639. $this->template = str_replace($chunk, 'M'.$this->loop_count.$this->marker, $this->template);
  640. }
  641. $cfile = md5($chunk); // This becomes the name of the cache file
  642. // Build a multi-dimensional array containing all of the tag data we've assembled
  643. $this->tag_data[$this->loop_count]['tag'] = $raw_tag;
  644. $this->tag_data[$this->loop_count]['class'] = $class[0];
  645. $this->tag_data[$this->loop_count]['method'] = (isset($class[1])) ? $class[1] : FALSE;
  646. $this->tag_data[$this->loop_count]['tagparts'] = $class;
  647. $this->tag_data[$this->loop_count]['params'] = $args;
  648. $this->tag_data[$this->loop_count]['chunk'] = $chunk; // Matched data block - including opening/closing tags
  649. $this->tag_data[$this->loop_count]['block'] = $block; // Matched data block - no tags
  650. $this->tag_data[$this->loop_count]['cache'] = $args;
  651. $this->tag_data[$this->loop_count]['cfile'] = $cfile;
  652. $this->tag_data[$this->loop_count]['no_results'] = $no_results;
  653. $this->tag_data[$this->loop_count]['no_results_block'] = $no_results_block;
  654. $this->tag_data[$this->loop_count]['search_fields'] = $search_fields;
  655. } // END IF
  656. // Increment counter
  657. $this->loop_count++;
  658. } // END WHILE
  659. }
  660. // --------------------------------------------------------------------
  661. /**
  662. * Looks Through Template Looking for Tags
  663. *
  664. * Goes Through the Template, Finds the Beginning and End of Tags, and Stores Tag Data in a Class Array
  665. *
  666. * @return void
  667. */
  668. public function tags()
  669. {
  670. // Fetch installed modules and plugins if needed
  671. if (count($this->modules) == 0)
  672. {
  673. $this->fetch_addons();
  674. }
  675. // Parse the template.
  676. $this->log_item(" - Beginning Tag Processing - ");
  677. while (is_int(strpos($this->template, LD.'exp:')))
  678. {
  679. // Initialize values between loops
  680. $this->tag_data = array();
  681. $this->var_single = array();
  682. $this->var_cond = array();
  683. $this->var_pair = array();
  684. $this->loop_count = 0;
  685. $this->log_item("Parsing Tags in Template");
  686. // Run the template parser
  687. $this->parse_tags();
  688. $this->log_item("Processing Tags");
  689. // Run the class/method handler
  690. $this->process_tags();
  691. if ($this->cease_processing === TRUE)
  692. {
  693. return;
  694. }
  695. }
  696. $this->log_item(" - End Tag Processing - ");
  697. }
  698. // --------------------------------------------------------------------
  699. /**
  700. * Process Tags
  701. *
  702. * Takes the Class Array Full of Tag Data and Processes the Tags One by One. Class class, feeds
  703. * data to class, takes results, and puts it back into the Template.
  704. *
  705. * @return void
  706. */
  707. public function process_tags()
  708. {
  709. $plugins = array();
  710. $modules = array();
  711. // Fill an array with the names of all the classes that we previously extracted from the tags
  712. for ($i = 0, $ctd = count($this->tag_data); $i < $ctd; $i++)
  713. {
  714. // Check the tag cache file
  715. $cache_contents = $this->fetch_cache_file($this->tag_data[$i]['cfile'], 'tag', $this->tag_data[$i]['cache']);
  716. // Set cache status for final processing
  717. $this->tag_data[$i]['cache'] = $this->tag_cache_status;
  718. if ($this->tag_cache_status == 'CURRENT')
  719. {
  720. // If so, replace the marker in the tag with the cache data
  721. $this->log_item("Tag Cached and Cache is Current");
  722. $this->template = str_replace('M'.$i.$this->marker, $cache_contents, $this->template);
  723. }
  724. else
  725. {
  726. // Is a module or plug-in being requested?
  727. if ( ! in_array($this->tag_data[$i]['class'] , $this->modules))
  728. {
  729. if ( ! in_array($this->tag_data[$i]['class'] , $this->plugins))
  730. {
  731. $this->log_item("Invalid Tag");
  732. if ($this->EE->config->item('debug') >= 1)
  733. {
  734. if (isset($this->tag_data[$i]['tagparts'][1]) &&
  735. $this->tag_data[$i]['tagparts'][0] == $this->tag_data[$i]['tagparts'][1] &&
  736. ! isset($this->tag_data[$i]['tagparts'][2]))
  737. {
  738. unset($this->tag_data[$i]['tagparts'][1]);
  739. }
  740. $error = $this->EE->lang->line('error_tag_syntax');
  741. $error .= '<br /><br />';
  742. $error .= htmlspecialchars(LD);
  743. $error .= 'exp:'.implode(':', $this->tag_data[$i]['tagparts']);
  744. $error .= htmlspecialchars(RD);
  745. $error .= '<br /><br />';
  746. $error .= $this->EE->lang->line('error_fix_syntax');
  747. $this->EE->output->fatal_error($error);
  748. }
  749. else
  750. return FALSE;
  751. }
  752. else
  753. {
  754. $plugins[] = $this->tag_data[$i]['class'];
  755. $this->log_item("Plugin Tag: ".ucfirst($this->tag_data[$i]['class']).'/'.$this->tag_data[$i]['method']);
  756. }
  757. }
  758. else
  759. {
  760. $modules[] = $this->tag_data[$i]['class'];
  761. $this->log_item("Module Tag: ".ucfirst($this->tag_data[$i]['class']).'/'.$this->tag_data[$i]['method']);
  762. }
  763. }
  764. }
  765. // Remove duplicate class names and re-order the array
  766. $plugins = array_values(array_unique($plugins));
  767. $modules = array_values(array_unique($modules));
  768. // Dynamically require the file that contains each class
  769. $this->log_item("Including Files for Plugins and Modules");
  770. foreach ($plugins as $plugin)
  771. {
  772. // make sure it's not already included just in case
  773. if ( ! class_exists($plugin))
  774. {
  775. if (in_array($plugin ,$this->EE->core->native_plugins))
  776. {
  777. require_once PATH_PI."pi.{$plugin}.php";
  778. }
  779. else
  780. {
  781. require_once PATH_THIRD."{$plugin}/pi.{$plugin}.php";
  782. }
  783. }
  784. }
  785. foreach ($modules as $module)
  786. {
  787. // make sure it's not already included just in case
  788. if ( ! class_exists($module))
  789. {
  790. if (in_array($module, $this->EE->core->native_modules))
  791. {
  792. require_once PATH_MOD."{$module}/mod.{$module}.php";
  793. }
  794. else
  795. {
  796. require_once PATH_THIRD."{$module}/mod.{$module}.php";
  797. }
  798. }
  799. }
  800. $this->log_item("Files for Plugins and Modules All Included");
  801. // Only Retrieve Data if Not Done Before and Modules Being Called
  802. if (count($this->module_data) == 0 && count(array_intersect($this->modules, $modules)) > 0)
  803. {
  804. $this->EE->db->select('module_version, module_name');
  805. $query = $this->EE->db->get('modules');
  806. foreach($query->result_array() as $row)
  807. {
  808. $this->module_data[$row['module_name']] = array('version' => $row['module_version']);
  809. }
  810. }
  811. // Final data processing
  812. // Loop through the master array containing our extracted template data
  813. $this->log_item("Beginning Final Tag Data Processing");
  814. reset($this->tag_data);
  815. for ($i = 0; $i < count($this->tag_data); $i++)
  816. {
  817. if ($this->tag_data[$i]['cache'] != 'CURRENT')
  818. {
  819. $this->log_item("Calling Class/Method: ".ucfirst($this->tag_data[$i]['class'])."/".$this->tag_data[$i]['method']);
  820. /* ---------------------------------
  821. /* Plugin as Parameter
  822. /*
  823. /* - Example: channel="{exp:some_plugin}"
  824. /* - A bit of a hidden feature. Has been tested but not quite
  825. /* ready to say it is ready for prime time as I might want to
  826. /* move it to earlier in processing so that if there are
  827. /* multiple plugins being used as parameters it is only called
  828. /* once instead of for every single parameter. - Paul
  829. /* ---------------------------------*/
  830. if (substr_count($this->tag_data[$i]['tag'], LD.'exp') > 1 && isset($this->tag_data[$i]['params']['parse']) && $this->tag_data[$i]['params']['parse'] == 'inward')
  831. {
  832. foreach($this->tag_data[$i]['params'] as $name => $param)
  833. {
  834. if (stristr($this->tag_data[$i]['params'][$name], LD.'exp'))
  835. {
  836. $this->log_item("Plugin in Parameter, Processing Plugin First");
  837. $TMPL2 = clone $this;
  838. while (is_int(strpos($TMPL2->tag_data[$i]['params'][$name], LD.'exp:')))
  839. {
  840. unset($this->EE->TMPL);
  841. $this->EE->TMPL = new EE_Template();
  842. $this->EE->TMPL->start_microtime = $this->start_microtime;
  843. $this->EE->TMPL->template = $TMPL2->tag_data[$i]['params'][$name];
  844. $this->EE->TMPL->tag_data = array();
  845. $this->EE->TMPL->var_single = array();
  846. $this->EE->TMPL->var_cond = array();
  847. $this->EE->TMPL->var_pair = array();
  848. $this->EE->TMPL->plugins = $TMPL2->plugins;
  849. $this->EE->TMPL->modules = $TMPL2->modules;
  850. $this->EE->TMPL->parse_tags();
  851. $this->EE->TMPL->process_tags();
  852. $this->EE->TMPL->loop_count = 0;
  853. $TMPL2->tag_data[$i]['params'][$name] = $this->EE->TMPL->template;
  854. $TMPL2->log = array_merge($TMPL2->log, $this->EE->TMPL->log);
  855. }
  856. foreach (get_object_vars($TMPL2) as $key => $value)
  857. {
  858. $this->$key = $value;
  859. }
  860. unset($TMPL2);
  861. $this->EE->TMPL = $this;
  862. }
  863. }
  864. }
  865. // Nested Plugins...
  866. if (in_array($this->tag_data[$i]['class'] , $this->plugins) && strpos($this->tag_data[$i]['block'], LD.'exp:') !== FALSE)
  867. {
  868. if ( ! isset($this->tag_data[$i]['params']['parse']) OR $this->tag_data[$i]['params']['parse'] != 'inward')
  869. {
  870. $this->log_item("Nested Plugins in Tag, Parsing Outward First");
  871. $TMPL2 = clone $this;
  872. while (is_int(strpos($TMPL2->tag_data[$i]['block'], LD.'exp:')))
  873. {
  874. unset($this->EE->TMPL);
  875. $this->EE->TMPL = new EE_Template();
  876. $this->EE->TMPL->start_microtime = $this->start_microtime;
  877. $this->EE->TMPL->template = $TMPL2->tag_data[$i]['block'];
  878. $this->EE->TMPL->tag_data = array();
  879. $this->EE->TMPL->var_single = array();
  880. $this->EE->TMPL->var_cond = array();
  881. $this->EE->TMPL->var_pair = array();
  882. $this->EE->TMPL->plugins = $TMPL2->plugins;
  883. $this->EE->TMPL->modules = $TMPL2->modules;
  884. $this->EE->TMPL->parse_tags();
  885. $this->EE->TMPL->process_tags();
  886. $this->EE->TMPL->loop_count = 0;
  887. $TMPL2->tag_data[$i]['block'] = $this->EE->TMPL->template;
  888. $TMPL2->log = array_merge($TMPL2->log, $this->EE->TMPL->log);
  889. }
  890. foreach (get_object_vars($TMPL2) as $key => $value)
  891. {
  892. $this->$key = $value;
  893. }
  894. unset($TMPL2);
  895. $this->EE->TMPL = $this;
  896. }
  897. }
  898. // Assign the data chunk, parameters
  899. // We moved the no_results_block here because of nested tags. The first
  900. // parsed tag has priority for that conditional.
  901. $this->tagdata = str_replace($this->tag_data[$i]['no_results_block'], '', $this->tag_data[$i]['block']);
  902. $this->tagparams = $this->tag_data[$i]['params'];
  903. $this->tagchunk = $this->tag_data[$i]['chunk'];
  904. $this->tagproper = $this->tag_data[$i]['tag'];
  905. $this->tagparts = $this->tag_data[$i]['tagparts'];
  906. $this->no_results = $this->tag_data[$i]['no_results'];
  907. $this->search_fields = $this->tag_data[$i]['search_fields'];
  908. // Assign Sites for Tag
  909. $this->_fetch_site_ids();
  910. // Fetch Form Class/Id Attributes
  911. $this->tag_data[$i] = $this->_assign_form_params($this->tag_data[$i]);
  912. // Relationship Data Pulled Out
  913. // If the channel:entries tag or search:search_results is being called
  914. // we need to extract any relationship data that might be present.
  915. // Note: This needs to happen before extracting the variables
  916. // in the tag so it doesn't get confused as to which entry the
  917. // variables belong to.
  918. if (($this->tag_data[$i]['class'] == 'channel' AND $this->tag_data[$i]['method'] == 'entries')
  919. OR ($this->tag_data[$i]['class'] == 'search' AND $this->tag_data[$i]['method'] == 'search_results'))
  920. {
  921. $this->tagdata = $this->assign_relationship_data($this->tagdata);
  922. }
  923. // LEGACY CODE
  924. // Fetch the variables for this particular tag
  925. // Hopefully, with Jones' new parsing code we should be able to stop using the
  926. // assign_variables and assign_conditional_variables() methods entirely. -Paul
  927. $vars = $this->EE->functions->assign_variables($this->tag_data[$i]['block']);
  928. if (count($this->related_markers) > 0)
  929. {
  930. foreach ($this->related_markers as $mkr)
  931. {
  932. if ( ! isset($vars['var_single'][$mkr]))
  933. {
  934. $vars['var_single'][$mkr] = $mkr;
  935. }
  936. }
  937. }
  938. $this->var_single = $vars['var_single'];
  939. $this->var_pair = $vars['var_pair'];
  940. if ($this->related_id != '')
  941. {
  942. $this->var_single[$this->related_id] = $this->related_id;
  943. $this->related_id = '';
  944. }
  945. // Assign the class name and method name
  946. $class_name = ucfirst($this->tag_data[$i]['class']);
  947. $meth_name = $this->tag_data[$i]['method'];
  948. // If it's a third party class or a first party module,
  949. // add the root folder to the loader paths so we can use
  950. // libraries, models, and helpers
  951. $package_path = '';
  952. if ( ! in_array($this->tag_data[$i]['class'], $this->EE->core->native_plugins))
  953. {
  954. $package_path = in_array($this->tag_data[$i]['class'], $this->EE->core->native_modules) ? PATH_MOD : PATH_THIRD;
  955. $package_path .= strtolower($this->tag_data[$i]['class'].'/');
  956. $this->EE->load->add_package_path($package_path, FALSE);
  957. }
  958. // Dynamically instantiate the class.
  959. // If module, only if it is installed...
  960. if (in_array($this->tag_data[$i]['class'], $this->modules) && ! isset($this->module_data[$class_name]))
  961. {
  962. $this->log_item("Problem Processing Module: Module Not Installed");
  963. }
  964. else
  965. {
  966. $this->log_item(" -> Class Called: ".$class_name);
  967. $EE = new $class_name();
  968. }
  969. // This gives proper PHP5 __construct() support in
  970. // plugins and modules with only a single __construct()
  971. // and allows them to be named __construct() instead of a
  972. // PHP4-style contructor.
  973. if ($meth_name === FALSE && isset($EE))
  974. {
  975. if (method_exists($EE, $class_name))
  976. {
  977. $meth_name = $class_name;
  978. }
  979. elseif (method_exists($EE, '__construct'))
  980. {
  981. $meth_name = '__construct';
  982. }
  983. }
  984. // Does method exist? Is This A Module and Is It Installed?
  985. if ((in_array($this->tag_data[$i]['class'], $this->modules) &&
  986. ! isset($this->module_data[$class_name])) OR
  987. ! method_exists($EE, $meth_name))
  988. {
  989. $this->log_item("Tag Not Processed: Method Inexistent or Module Not Installed");
  990. if ($this->EE->config->item('debug') >= 1)
  991. {
  992. if (isset($this->tag_data[$i]['tagparts'][1]) && $this->tag_data[$i]['tagparts'][0] == $this->tag_data[$i]['tagparts'][1] &&
  993. ! isset($this->tag_data[$i]['tagparts'][2]))
  994. {
  995. unset($this->tag_data[$i]['tagparts'][1]);
  996. }
  997. $error = $this->EE->lang->line('error_tag_module_processing');
  998. $error .= '<br /><br />';
  999. $error .= htmlspecialchars(LD);
  1000. $error .= 'exp:'.implode(':', $this->tag_data[$i]['tagparts']);
  1001. $error .= htmlspecialchars(RD);
  1002. $error .= '<br /><br />';
  1003. $error .= str_replace('%x', $this->tag_data[$i]['class'], str_replace('%y', $meth_name, $this->EE->lang->line('error_fix_module_processing')));
  1004. $this->EE->output->fatal_error($error);
  1005. }
  1006. else
  1007. {
  1008. return;
  1009. }
  1010. }
  1011. /*
  1012. OK, lets grab the data returned from the class.
  1013. First, however, lets determine if the tag has one or two segments.
  1014. If it only has one, we don't want to call the constructor again since
  1015. it was already called during instantiation.
  1016. Note: If it only has one segment, only the object constructor will be called.
  1017. Since constructors can't return a value just by initialializing the object
  1018. the output of the class must be assigned to a variable called $this->return_data
  1019. */
  1020. $this->log_item(" -> Method Called: ".$meth_name);
  1021. if ((strtolower($class_name) == strtolower($meth_name)) OR ($meth_name == '__construct'))
  1022. {
  1023. $return_data = (isset($EE->return_data)) ? $EE->return_data : '';
  1024. }
  1025. else
  1026. {
  1027. $return_data = $EE->$meth_name();
  1028. }
  1029. // if it's a third party add-on or module, remove the temporarily added path for local libraries, models, etc.
  1030. // if a "no results" template is returned, $this->tag_data will be reset inside of the scope
  1031. // of the tag being processed. So let's use the locally scoped variable for the class name
  1032. if ($package_path)
  1033. {
  1034. $this->EE->load->remove_package_path($package_path);
  1035. }
  1036. // 404 Page Triggered, Cease All Processing of Tags From Now On
  1037. if ($this->cease_processing === TRUE)
  1038. {
  1039. return;
  1040. }
  1041. $this->log_item(" -> Data Returned");
  1042. // Write cache file if needed
  1043. if ($this->tag_data[$i]['cache'] == 'EXPIRED')
  1044. {
  1045. $this->write_cache_file($this->tag_data[$i]['cfile'], $return_data);
  1046. }
  1047. // Replace the temporary markers we added earlier with the fully parsed data
  1048. $this->template = str_replace('M'.$i.$this->marker, $return_data, $this->template);
  1049. // Initialize data in case there are susequent loops
  1050. $this->var_single = array();
  1051. $this->var_cond = array();
  1052. $this->var_pair = array();
  1053. unset($return_data);
  1054. unset($class_name);
  1055. unset($meth_name);
  1056. unset($EE);
  1057. }
  1058. }
  1059. }
  1060. // --------------------------------------------------------------------
  1061. /**
  1062. * Process Tags
  1063. *
  1064. * Channel entries can have related entries embedded within them.
  1065. * We'll extract the related tag data, stash it away in an array, and
  1066. * replace it with a marker string so that the template parser
  1067. * doesn't see it. In the channel class we'll check to see if the
  1068. * $this->EE->TMPL->related_data array contains anything. If so, we'll celebrate
  1069. * wildly.
  1070. *
  1071. * @param string
  1072. * @return string
  1073. */
  1074. public function assign_relationship_data($chunk)
  1075. {
  1076. $this->related_markers = array();
  1077. if (preg_match_all("/".LD."related_entries\s+id\s*=\s*[\"\'](.+?)[\"\']".RD."(.+?)".LD.'\/'."related_entries".RD."/is", $chunk, $matches))
  1078. {
  1079. $this->log_item("Assigning Related Entry Data");
  1080. $no_rel_content = '';
  1081. for ($j = 0; $j < count($matches[0]); $j++)
  1082. {
  1083. $rand = $this->EE->functions->random('alnum', 8);
  1084. $marker = LD.'REL['.$matches[1][$j].']'.$rand.'REL'.RD;
  1085. if (preg_match("/".LD."if no_related_entries".RD."(.*?)".LD.'\/'."if".RD."/s", $matches[2][$j], $no_rel_match))
  1086. {
  1087. // Match the entirety of the conditional
  1088. if (stristr($no_rel_match[1], LD.'if'))
  1089. {
  1090. $match[0] = $this->EE->functions->full_tag($no_rel_match[0], $matches[2][$j], LD.'if', LD.'\/'."if".RD);
  1091. }
  1092. $no_rel_content = substr($no_rel_match[0], strlen(LD."if no_related_entries".RD), -strlen(LD.'/'."if".RD));
  1093. }
  1094. $this->related_markers[] = $matches[1][$j];
  1095. $vars = $this->EE->functions->assign_variables($matches[2][$j]);
  1096. $this->related_id = $matches[1][$j];
  1097. $this->related_data[$rand] = array(
  1098. 'marker' => $rand,
  1099. 'field_name' => $matches[1][$j],
  1100. 'tagdata' => $matches[2][$j],
  1101. 'var_single' => $vars['var_single'],
  1102. 'var_pair' => $vars['var_pair'],
  1103. 'var_cond' => $this->EE->functions->assign_conditional_variables($matches[2][$j], '\/', LD, RD),
  1104. 'no_rel_content' => $no_rel_content
  1105. );
  1106. $chunk = str_replace($matches[0][$j], $marker, $chunk);
  1107. }
  1108. }
  1109. if (preg_match_all("/".LD."reverse_related_entries\s*(.*?)".RD."(.+?)".LD.'\/'."reverse_related_entries".RD."/is", $chunk, $matches))
  1110. {
  1111. $this->log_item("Assigning Reverse Related Entry Data");
  1112. for ($j = 0; $j < count($matches[0]); $j++)
  1113. {
  1114. $rand = $this->EE->functions->random('alnum', 8);
  1115. $marker = LD.'REV_REL['.$rand.']REV_REL'.RD;
  1116. $vars = $this->EE->functions->assign_variables($matches[2][$j]);
  1117. $no_rev_content = '';
  1118. if (preg_match("/".LD."if no_reverse_related_entries".RD."(.*?)".LD.'\/'."if".RD."/s", $matches[2][$j], $no_rev_match))
  1119. {
  1120. // Match the entirety of the conditional
  1121. if (stristr($no_rev_match[1], LD.'if'))
  1122. {
  1123. $match[0] = $this->EE->functions->full_tag($no_rev_match[0], $matches[2][$j], LD.'if', LD.'\/'."if".RD);
  1124. }
  1125. $no_rev_content = substr($no_rev_match[0], strlen(LD."if no_reverse_related_entries".RD), -strlen(LD.'/'."if".RD));
  1126. }
  1127. $this->reverse_related_data[$rand] = array(
  1128. 'marker' => $rand,
  1129. 'tagdata' => $matches[2][$j],
  1130. 'var_single' => $vars['var_single'],
  1131. 'var_pair' => $vars['var_pair'],
  1132. 'var_cond' => $this->EE->functions->assign_conditional_variables($matches[2][$j], '\/', LD, RD),
  1133. 'params' => $this->EE->functions->assign_parameters($matches[1][$j]),
  1134. 'no_rev_content' => $no_rev_content
  1135. );
  1136. $chunk = str_replace($matches[0][$j], $marker, $chunk);
  1137. }
  1138. }
  1139. return $chunk;
  1140. }
  1141. // --------------------------------------------------------------------
  1142. /**
  1143. * Fetch Parameter for Tag
  1144. *
  1145. * Used by Modules to fetch a paramter for the tag currently be processed. We also have code
  1146. * in here to convert legacy values like 'y' and 'on' to their more respectable full values.
  1147. * Further, if one assigns the second argument, it will be returned as the value if a
  1148. * parameter of the $which name does not exist for this tag. Handy for default values!
  1149. *
  1150. * @access string
  1151. * @access bool
  1152. * @return string
  1153. */
  1154. public function fetch_param($which, $default = FALSE)
  1155. {
  1156. if ( ! isset($this->tagparams[$which]))
  1157. {
  1158. return $default;
  1159. }
  1160. else
  1161. {
  1162. // Making yes/no tag parameters consistent. No "y/n" or "on/off".
  1163. switch($this->tagparams[$which])
  1164. {
  1165. case 'y' :
  1166. case 'on' :
  1167. return 'yes';
  1168. break;
  1169. case 'n' :
  1170. case 'off' :
  1171. return 'no';
  1172. break;
  1173. default :
  1174. return $this->tagparams[$which];
  1175. break;
  1176. }
  1177. }
  1178. }
  1179. // --------------------------------------------------------------------
  1180. /**
  1181. * Replace a Single Variable with Its Value
  1182. *
  1183. * LEGACY!!!
  1184. *
  1185. * @deprecated
  1186. * @param string
  1187. * @param string
  1188. * @param string
  1189. * @return string
  1190. */
  1191. public function swap_var_single($search, $replace, $source)
  1192. {
  1193. return str_replace(LD.$search.RD, $replace, $so

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