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

/cp/expressionengine/libraries/Template.php

https://bitbucket.org/sbeuken/artelux
PHP | 3955 lines | 3760 code | 81 blank | 114 comment | 53 complexity | 11391eadc288d12a85eb932d03c7f3c2 MD5 | raw file
  1. <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
  2. /**
  3. * ExpressionEngine - by EllisLab
  4. *
  5. * @package ExpressionEngine
  6. * @author EllisLab Dev Team
  7. * @copyright Copyright (c) 2003 - 2012, EllisLab, Inc.
  8. * @license http://ellislab.com/expressionengine/user-guide/license.html
  9. * @link http://ellislab.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 EllisLab Dev Team
  21. * @link http://ellislab.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 = 'Restricted Content'; // 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 != '') ?
  187. $this->fetch_template($template_group, $template, FALSE, $site_id) :
  188. $this->parse_template_uri();
  189. $this->log_item("Template Type: ".$this->template_type);
  190. $this->parse($this->template, $sub, $site_id);
  191. // -------------------------------------------
  192. // 'template_post_parse' hook.
  193. // - Modify template after tag parsing
  194. //
  195. if ($this->EE->extensions->active_hook('template_post_parse') === TRUE)
  196. {
  197. $this->final_template = $this->EE->extensions->call(
  198. 'template_post_parse',
  199. $this->final_template,
  200. $sub,
  201. $site_id
  202. );
  203. }
  204. //
  205. // -------------------------------------------
  206. }
  207. // --------------------------------------------------------------------
  208. /**
  209. * Parse a string as a template
  210. *
  211. * @param string
  212. * @param string
  213. * @return void
  214. */
  215. public function parse(&$str, $sub = FALSE, $site_id = '')
  216. {
  217. if ($str != '')
  218. {
  219. $this->template =& $str;
  220. }
  221. // Static Content, No Parsing
  222. if ($this->template_type == 'static' OR $this->embed_type == 'static')
  223. {
  224. if ($sub == FALSE)
  225. {
  226. $this->final_template = $this->template;
  227. }
  228. return;
  229. }
  230. /* -------------------------------------
  231. /* "Smart" Static Parsing
  232. /*
  233. /* Performed on embedded webpage templates only that do not have
  234. /* ExpressionEngine tags or PHP in them.
  235. /*
  236. /* Hidden Configuration Variable
  237. /* - smart_static_parsing => Bypass parsing of templates that could be
  238. /* of the type 'static' but aren't? (y/n)
  239. /* -------------------------------------*/
  240. if ($this->EE->config->item('smart_static_parsing') !== 'n' && $this->embed_type == 'webpage' && ! stristr($this->template, LD) && ! stristr($this->template, '<?'))
  241. {
  242. $this->log_item("Smart Static Parsing Triggered");
  243. if ($sub == FALSE)
  244. {
  245. $this->final_template = $this->template;
  246. }
  247. return;
  248. }
  249. // Parse 'Site' variables
  250. $this->log_item("Parsing Site Variables");
  251. // load site variables into the global_vars array
  252. foreach (array('site_id', 'site_label', 'site_short_name') as $site_var)
  253. {
  254. $this->EE->config->_global_vars[$site_var] = stripslashes($this->EE->config->item($site_var));
  255. }
  256. // Parse {last_segment} variable
  257. $seg_array = $this->EE->uri->segment_array();
  258. $this->EE->config->_global_vars['last_segment'] = end($seg_array);
  259. // Parse manual variables and Snippets
  260. // These are variables that can be set in the path.php file
  261. if (count($this->EE->config->_global_vars) > 0)
  262. {
  263. $this->log_item("Snippets (Keys): ".implode('|', array_keys($this->EE->config->_global_vars)));
  264. $this->log_item("Snippets (Values): ".trim(implode('|', $this->EE->config->_global_vars)));
  265. foreach ($this->EE->config->_global_vars as $key => $val)
  266. {
  267. $this->template = str_replace(LD.$key.RD, $val, $this->template);
  268. }
  269. // in case any of these variables have EE comments of their own
  270. $this->template = $this->remove_ee_comments($this->template);
  271. }
  272. // Parse URI segments
  273. // This code lets admins fetch URI segments which become
  274. // available as: {segment_1} {segment_2}
  275. for ($i = 1; $i < 10; $i++)
  276. {
  277. $this->template = str_replace(LD.'segment_'.$i.RD, $this->EE->uri->segment($i), $this->template);
  278. $this->segment_vars['segment_'.$i] = $this->EE->uri->segment($i);
  279. }
  280. // Parse {embed} tag variables
  281. if ($sub === TRUE && count($this->embed_vars) > 0)
  282. {
  283. $this->log_item("Embed Variables (Keys): ".implode('|', array_keys($this->embed_vars)));
  284. $this->log_item("Embed Variables (Values): ".trim(implode('|', $this->embed_vars)));
  285. foreach ($this->embed_vars as $key => $val)
  286. {
  287. // add 'embed:' to the key for replacement and so these variables work in conditionals
  288. $this->embed_vars['embed:'.$key] = $val;
  289. unset($this->embed_vars[$key]);
  290. $this->template = str_replace(LD.'embed:'.$key.RD, $val, $this->template);
  291. }
  292. }
  293. // cleanup of leftover/undeclared embed variables
  294. // don't worry with undeclared embed: vars in conditionals as the conditionals processor will handle that adequately
  295. if (strpos($this->template, LD.'embed:') !== FALSE)
  296. {
  297. $this->template = preg_replace('/'.LD.'embed:([^!]+?)'.RD.'/', '', $this->template);
  298. }
  299. // Parse date format string "constants"
  300. $date_constants = array('DATE_ATOM' => '%Y-%m-%dT%H:%i:%s%Q',
  301. 'DATE_COOKIE' => '%l, %d-%M-%y %H:%i:%s UTC',
  302. 'DATE_ISO8601' => '%Y-%m-%dT%H:%i:%s%Q',
  303. 'DATE_RFC822' => '%D, %d %M %y %H:%i:%s %O',
  304. 'DATE_RFC850' => '%l, %d-%M-%y %H:%m:%i UTC',
  305. 'DATE_RFC1036' => '%D, %d %M %y %H:%i:%s %O',
  306. 'DATE_RFC1123' => '%D, %d %M %Y %H:%i:%s %O',
  307. 'DATE_RFC2822' => '%D, %d %M %Y %H:%i:%s %O',
  308. 'DATE_RSS' => '%D, %d %M %Y %H:%i:%s %O',
  309. 'DATE_W3C' => '%Y-%m-%dT%H:%i:%s%Q'
  310. );
  311. foreach ($date_constants as $key => $val)
  312. {
  313. $this->template = str_replace(LD.$key.RD, $val, $this->template);
  314. }
  315. $this->log_item("Parse Date Format String Constants");
  316. // Template's Last Edit time {template_edit_date format="%Y %m %d %H:%i:%s"}
  317. if (strpos($this->template, LD.'template_edit_date') !== FALSE && preg_match_all("/".LD."template_edit_date\s+format=([\"\'])([^\\1]*?)\\1".RD."/", $this->template, $matches))
  318. {
  319. for ($j = 0; $j < count($matches[0]); $j++)
  320. {
  321. $this->template = str_replace($matches[0][$j], $this->EE->localize->decode_date($matches[2][$j], $this->template_edit_date), $this->template);
  322. }
  323. }
  324. // Current time {current_time format="%Y %m %d %H:%i:%s"}
  325. if (strpos($this->template, LD.'current_time') !== FALSE && preg_match_all("/".LD."current_time\s+format=([\"\'])([^\\1]*?)\\1".RD."/", $this->template, $matches))
  326. {
  327. for ($j = 0; $j < count($matches[0]); $j++)
  328. {
  329. $this->template = str_replace($matches[0][$j], $this->EE->localize->decode_date($matches[2][$j], $this->EE->localize->now), $this->template);
  330. }
  331. }
  332. $this->template = str_replace(LD.'current_time'.RD, $this->EE->localize->now, $this->template);
  333. $this->log_item("Parse Current Time Variables");
  334. // Is the main template cached?
  335. // If a cache file exists for the primary template
  336. // there is no reason to go further.
  337. // However we do need to fetch any subtemplates
  338. if ($this->cache_status == 'CURRENT' AND $sub == FALSE)
  339. {
  340. $this->log_item("Cached Template Used");
  341. $this->template = $this->parse_nocache($this->template);
  342. // Smite Our Enemies: Advanced Conditionals
  343. if (stristr($this->template, LD.'if'))
  344. {
  345. $this->template = $this->advanced_conditionals($this->template);
  346. }
  347. $this->log_item("Conditionals Parsed, Processing Sub Templates");
  348. $this->final_template = $this->template;
  349. $this->process_sub_templates($this->template);
  350. return;
  351. }
  352. // Remove whitespace from variables.
  353. // This helps prevent errors, particularly if PHP is used in a template
  354. $this->template = preg_replace("/".LD."\s*(\S+)\s*".RD."/U", LD."\\1".RD, $this->template);
  355. // Parse Input Stage PHP
  356. if ($this->parse_php == TRUE && $this->php_parse_location == 'input' && $this->cache_status != 'CURRENT')
  357. {
  358. $this->log_item("Parsing PHP on Input");
  359. $this->template = $this->parse_template_php($this->template);
  360. }
  361. // Smite Our Enemies: Conditionals
  362. $this->log_item("Parsing Segment, Embed, and Global Vars Conditionals");
  363. $this->template = $this->parse_simple_segment_conditionals($this->template);
  364. $this->template = $this->simple_conditionals($this->template, $this->embed_vars);
  365. $this->template = $this->simple_conditionals($this->template, $this->EE->config->_global_vars);
  366. // Assign Variables
  367. if (strpos($this->template, 'preload_replace') !== FALSE)
  368. {
  369. if (preg_match_all("/".LD."preload_replace:(.+?)=([\"\'])([^\\2]*?)\\2".RD."/i", $this->template, $matches))
  370. {
  371. $this->log_item("Processing Preload Text Replacements: ".trim(implode('|', $matches[1])));
  372. for ($j = 0; $j < count($matches[0]); $j++)
  373. {
  374. $this->template = str_replace($matches[0][$j], "", $this->template);
  375. $this->template = str_replace(LD.$matches[1][$j].RD, $matches[3][$j], $this->template);
  376. }
  377. }
  378. }
  379. // Parse Plugin and Module Tags
  380. $this->tags();
  381. if ($this->cease_processing === TRUE)
  382. {
  383. return;
  384. }
  385. // Parse Output Stage PHP
  386. if ($this->parse_php == TRUE AND $this->php_parse_location == 'output' AND $this->cache_status != 'CURRENT')
  387. {
  388. $this->log_item("Parsing PHP on Output");
  389. $this->template = $this->parse_template_php($this->template);
  390. }
  391. // Write the cache file if needed
  392. if ($this->cache_status == 'EXPIRED')
  393. {
  394. $this->template = $this->EE->functions->insert_action_ids($this->template);
  395. $this->write_cache_file($this->cache_hash, $this->template, 'template');
  396. }
  397. // Parse Our Uncacheable Forms
  398. $this->template = $this->parse_nocache($this->template);
  399. // Smite Our Enemies: Advanced Conditionals
  400. if (strpos($this->template, LD.'if') !== FALSE)
  401. {
  402. $this->log_item("Processing Advanced Conditionals");
  403. $this->template = $this->advanced_conditionals($this->template);
  404. }
  405. // Build finalized template
  406. // We only do this on the first pass.
  407. // The sub-template routine will insert embedded
  408. // templates into the master template
  409. if ($sub == FALSE)
  410. {
  411. $this->final_template = $this->template;
  412. $this->process_sub_templates($this->template);
  413. }
  414. }
  415. // --------------------------------------------------------------------
  416. /**
  417. * Processes Any Embedded Templates in String
  418. *
  419. * If any {embed=} tags are found, it processes those templates and does a replacement.
  420. *
  421. * @param string
  422. * @return void
  423. */
  424. public function process_sub_templates($template)
  425. {
  426. // Match all {embed=bla/bla} tags
  427. $matches = array();
  428. if ( ! preg_match_all("/(".LD."embed\s*=)(.*?)".RD."/s", $template, $matches))
  429. {
  430. return;
  431. }
  432. // Loop until we have parsed all sub-templates
  433. // For each embedded tag we encounter we'll run the template parsing
  434. // function - AND - through the beauty of recursive functions we
  435. // will also call THIS function as well, allowing us to parse
  436. // infinitely nested sub-templates in one giant loop o' love
  437. $this->log_item(" - Processing Sub Templates (Depth: ".($this->depth+1).") - ");
  438. $i = 0;
  439. $this->depth++;
  440. $this->log_item("List of Embeds: ".str_replace(array('"', "'"), '', trim(implode(',', $matches[2]))));
  441. // re-match the full tag of each if necessary before we start processing
  442. // necessary evil in case template globals are used inside the embed tag,
  443. // doing this within the processing loop will result in leaving unparsed
  444. // embed tags e.g. {embed="foo/bar" var="{global_var}/{custom_field}"}
  445. $temp = $template;
  446. foreach ($matches[2] as $key => $val)
  447. {
  448. if (strpos($val, LD) !== FALSE)
  449. {
  450. $matches[0][$key] = $this->EE->functions->full_tag($matches[0][$key], $temp);
  451. $matches[2][$key] = substr(str_replace($matches[1][$key], '', $matches[0][$key]), 0, -1);
  452. $temp = str_replace($matches[0][$key], '', $temp);
  453. }
  454. }
  455. // Load the string helper
  456. $this->EE->load->helper('string');
  457. foreach($matches[2] as $key => $val)
  458. {
  459. $parts = preg_split("/\s+/", $val, 2);
  460. $this->embed_vars = (isset($parts[1])) ? $this->EE->functions->assign_parameters($parts[1]) : array();
  461. if ($this->embed_vars === FALSE)
  462. {
  463. $this->embed_vars = array();
  464. }
  465. $val = trim_slashes(strip_quotes($parts[0]));
  466. if (strpos($val, '/') === FALSE)
  467. {
  468. continue;
  469. }
  470. $ex = explode("/", trim($val));
  471. if (count($ex) != 2)
  472. {
  473. continue;
  474. }
  475. // Determine Site
  476. $site_id = $this->EE->config->item('site_id');
  477. if (stristr($ex[0], ':'))
  478. {
  479. $name = substr($ex[0], 0, strpos($ex[0], ':'));
  480. if ($this->EE->config->item('multiple_sites_enabled') == 'y' && ! IS_CORE)
  481. {
  482. if (count($this->sites) == 0)
  483. {
  484. // This should really be cached somewhere
  485. $this->EE->db->select('site_id, site_name');
  486. $sites_query = $this->EE->db->get('sites');
  487. foreach($sites_query->result_array() as $row)
  488. {
  489. $this->sites[$row['site_id']] = $row['site_name'];
  490. }
  491. }
  492. $site_id = array_search($name, $this->sites);
  493. if (empty($site_id))
  494. {
  495. $site_id = $this->EE->config->item('site_id');
  496. }
  497. }
  498. $ex[0] = str_replace($name.':', '', $ex[0]);
  499. }
  500. // Loop Prevention
  501. /* -------------------------------------------
  502. /* Hidden Configuration Variable
  503. /* - template_loop_prevention => 'n'
  504. Whether or not loop prevention is enabled - y/n
  505. /* -------------------------------------------*/
  506. if (substr_count($this->templates_sofar, '|'.$site_id.':'.$ex['0'].'/'.$ex['1'].'|') > 1 && $this->EE->config->item('template_loop_prevention') != 'n')
  507. {
  508. $this->final_template = ($this->EE->config->item('debug') >= 1) ? str_replace('%s', $ex['0'].'/'.$ex['1'], $this->EE->lang->line('template_loop')) : "";
  509. return;
  510. }
  511. // Process Subtemplate
  512. $this->log_item("Processing Sub Template: ".$ex[0]."/".$ex[1]);
  513. $this->fetch_and_parse($ex[0], $ex[1], TRUE, $site_id);
  514. $this->final_template = str_replace($matches[0][$key], $this->template, $this->final_template);
  515. $this->embed_type = '';
  516. // Here we go again! Wheeeeeee.....
  517. $this->process_sub_templates($this->template);
  518. // pull the subtemplate tracker back a level to the parent template
  519. $this->templates_sofar = substr($this->templates_sofar, 0, - strlen('|'.$site_id.':'.$ex[0].'/'.$ex[1].'|'));
  520. }
  521. $this->depth--;
  522. if ($this->depth == 0)
  523. {
  524. $this->templates_sofar = '';
  525. }
  526. }
  527. // --------------------------------------------------------------------
  528. /**
  529. * Finds Tags, Parses Them
  530. *
  531. * Goes Through the Template, Finds the Beginning and End of Tags, and Stores Tag Data in a Class Array
  532. *
  533. * @return void
  534. */
  535. public function parse_tags()
  536. {
  537. while (TRUE)
  538. {
  539. // Make a "floating" copy of the template which we'll progressively slice into pieces with each loop
  540. $this->fl_tmpl = $this->template;
  541. // Identify the string position of the first occurence of a matched tag
  542. $this->in_point = strpos($this->fl_tmpl, LD.'exp:');
  543. // If the above variable returns FALSE we are done looking for tags
  544. // This single conditional keeps the template engine from spiraling
  545. // out of control in an infinite loop.
  546. if (FALSE === $this->in_point)
  547. {
  548. break;
  549. }
  550. else
  551. {
  552. // Process the tag data
  553. // These REGEXs parse out the various components contained in any given tag.
  554. // Grab the opening portion of the tag: {exp:some:tag param="value" param="value"}
  555. if ( ! preg_match("/".LD.'exp:'.".*?".RD."/s", $this->fl_tmpl, $matches))
  556. {
  557. $this->template = preg_replace("/".LD.'exp:'.".*?$/", '', $this->template);
  558. break;
  559. }
  560. // Checking for variables/tags embedded within tags
  561. // {exp:channel:entries channel="{master_channel_name}"}
  562. if (stristr(substr($matches[0], 1), LD) !== FALSE)
  563. {
  564. $matches[0] = $this->EE->functions->full_tag($matches[0]);
  565. }
  566. $this->log_item("Tag: ".$matches[0]);
  567. $raw_tag = str_replace(array("\r\n", "\r", "\n", "\t"), " ", $matches[0]);
  568. $tag_length = strlen($raw_tag);
  569. $data_start = $this->in_point + $tag_length;
  570. $tag = trim(substr($raw_tag, 1, -1));
  571. $args = trim((preg_match("/\s+.*/", $tag, $matches))) ? $matches[0] : '';
  572. $tag = trim(str_replace($args, '', $tag));
  573. $cur_tag_close = LD.'/'.$tag.RD;
  574. // Deprecate "weblog" tags, but allow them to work until 2.1, then remove this.
  575. if (strpos($tag, ':weblog:') !== FALSE OR strpos($tag, ' weblog=') !== FALSE)
  576. {
  577. $tag = str_replace(array(':weblog:', ' weblog='), array(':channel:', ' channel='), $tag);
  578. $this->log_item("WARNING: Deprecated 'weblog' tag used, please change to 'channel'");
  579. }
  580. // -----------------------------------------
  581. // Grab the class name and method names contained in the tag
  582. $class = explode(':', substr($tag, strlen('exp') + 1));
  583. // Tags can either have one segment or two:
  584. // {exp:first_segment}
  585. // {exp:first_segment:second_segment}
  586. //
  587. // These two segments represent either a "class:constructor"
  588. // or a "class:method". We need to determine which one it is.
  589. // if (count($class) == 1)
  590. // {
  591. // $class[1] = $class[0];
  592. // }
  593. foreach($class as $key => $value)
  594. {
  595. $class[$key] = trim($value);
  596. }
  597. // -----------------------------------------
  598. // Assign parameters based on the arguments from the tag
  599. $args = $this->EE->functions->assign_parameters($args);
  600. // standardized mechanism for "search" type parameters get some extra lovin'
  601. $search_fields = array();
  602. if ($args !== FALSE)
  603. {
  604. foreach ($args as $key => $val)
  605. {
  606. if (strncmp($key, 'search:', 7) == 0)
  607. {
  608. $search_fields[substr($key, 7)] = $val;
  609. }
  610. }
  611. }
  612. // Trim the floating template, removing the tag we just parsed.
  613. $this->fl_tmpl = substr($this->fl_tmpl, $this->in_point + $tag_length);
  614. $out_point = strpos($this->fl_tmpl, $cur_tag_close);
  615. // Do we have a tag pair?
  616. if (FALSE !== $out_point)
  617. {
  618. // Assign the data contained between the opening/closing tag pair
  619. $this->log_item("Closing Tag Found");
  620. $block = substr($this->template, $data_start, $out_point);
  621. // Fetch the "no_results" data
  622. $no_results = '';
  623. $no_results_block = '';
  624. if (strpos($block, 'if no_results') !== FALSE && preg_match("/".LD."if no_results".RD."(.*?)".LD.'\/'."if".RD."/s", $block, $match))
  625. {
  626. // Match the entirety of the conditional, dude. Bad Rick!
  627. if (stristr($match[1], LD.'if'))
  628. {
  629. $match[0] = $this->EE->functions->full_tag($match[0], $block, LD.'if', LD.'\/'."if".RD);
  630. }
  631. $no_results = substr($match[0], strlen(LD."if no_results".RD), -strlen(LD.'/'."if".RD));
  632. $no_results_block = $match[0];
  633. }
  634. // Define the entire "chunk" - from the left edge of the opening tag
  635. // to the right edge of closing tag.
  636. $out_point = $out_point + $tag_length + strlen($cur_tag_close);
  637. $chunk = substr($this->template, $this->in_point, $out_point);
  638. }
  639. else
  640. {
  641. // Single tag...
  642. $this->log_item("No Closing Tag");
  643. $block = ''; // Single tags don't contain data blocks
  644. $no_results = '';
  645. $no_results_block = '';
  646. // Define the entire opening tag as a "chunk"
  647. $chunk = substr($this->template, $this->in_point, $tag_length);
  648. }
  649. // Strip the "chunk" from the template, replacing it with a unique marker.
  650. if (stristr($raw_tag, 'random'))
  651. {
  652. $this->template = preg_replace("|".preg_quote($chunk)."|s", 'M'.$this->loop_count.$this->marker, $this->template, 1);
  653. }
  654. else
  655. {
  656. $this->template = str_replace($chunk, 'M'.$this->loop_count.$this->marker, $this->template);
  657. }
  658. $cfile = md5($chunk); // This becomes the name of the cache file
  659. // Build a multi-dimensional array containing all of the tag data we've assembled
  660. $this->tag_data[$this->loop_count]['tag'] = $raw_tag;
  661. $this->tag_data[$this->loop_count]['class'] = $class[0];
  662. $this->tag_data[$this->loop_count]['method'] = (isset($class[1])) ? $class[1] : FALSE;
  663. $this->tag_data[$this->loop_count]['tagparts'] = $class;
  664. $this->tag_data[$this->loop_count]['params'] = $args;
  665. $this->tag_data[$this->loop_count]['chunk'] = $chunk; // Matched data block - including opening/closing tags
  666. $this->tag_data[$this->loop_count]['block'] = $block; // Matched data block - no tags
  667. $this->tag_data[$this->loop_count]['cache'] = $args;
  668. $this->tag_data[$this->loop_count]['cfile'] = $cfile;
  669. $this->tag_data[$this->loop_count]['no_results'] = $no_results;
  670. $this->tag_data[$this->loop_count]['no_results_block'] = $no_results_block;
  671. $this->tag_data[$this->loop_count]['search_fields'] = $search_fields;
  672. } // END IF
  673. // Increment counter
  674. $this->loop_count++;
  675. } // END WHILE
  676. }
  677. // --------------------------------------------------------------------
  678. /**
  679. * Looks Through Template Looking for Tags
  680. *
  681. * Goes Through the Template, Finds the Beginning and End of Tags, and Stores Tag Data in a Class Array
  682. *
  683. * @return void
  684. */
  685. public function tags()
  686. {
  687. // Fetch installed modules and plugins if needed
  688. if (count($this->modules) == 0)
  689. {
  690. $this->fetch_addons();
  691. }
  692. // Parse the template.
  693. $this->log_item(" - Beginning Tag Processing - ");
  694. while (is_int(strpos($this->template, LD.'exp:')))
  695. {
  696. // Initialize values between loops
  697. $this->tag_data = array();
  698. $this->var_single = array();
  699. $this->var_cond = array();
  700. $this->var_pair = array();
  701. $this->loop_count = 0;
  702. $this->log_item("Parsing Tags in Template");
  703. // Run the template parser
  704. $this->parse_tags();
  705. $this->log_item("Processing Tags");
  706. // Run the class/method handler
  707. $this->process_tags();
  708. if ($this->cease_processing === TRUE)
  709. {
  710. return;
  711. }
  712. }
  713. $this->log_item(" - End Tag Processing - ");
  714. }
  715. // --------------------------------------------------------------------
  716. /**
  717. * Process Tags
  718. *
  719. * Takes the Class Array Full of Tag Data and Processes the Tags One by One. Class class, feeds
  720. * data to class, takes results, and puts it back into the Template.
  721. *
  722. * @return void
  723. */
  724. public function process_tags()
  725. {
  726. $plugins = array();
  727. $modules = array();
  728. // Fill an array with the names of all the classes that we previously extracted from the tags
  729. for ($i = 0, $ctd = count($this->tag_data); $i < $ctd; $i++)
  730. {
  731. // Check the tag cache file
  732. $cache_contents = $this->fetch_cache_file($this->tag_data[$i]['cfile'], 'tag', $this->tag_data[$i]['cache']);
  733. // Set cache status for final processing
  734. $this->tag_data[$i]['cache'] = $this->tag_cache_status;
  735. if ($this->tag_cache_status == 'CURRENT')
  736. {
  737. // If so, replace the marker in the tag with the cache data
  738. $this->log_item("Tag Cached and Cache is Current");
  739. $this->template = str_replace('M'.$i.$this->marker, $cache_contents, $this->template);
  740. }
  741. else
  742. {
  743. // Is a module or plug-in being requested?
  744. if ( ! in_array($this->tag_data[$i]['class'] , $this->modules))
  745. {
  746. if ( ! in_array($this->tag_data[$i]['class'] , $this->plugins))
  747. {
  748. $this->log_item("Invalid Tag");
  749. if ($this->EE->config->item('debug') >= 1)
  750. {
  751. if (isset($this->tag_data[$i]['tagparts'][1]) &&
  752. $this->tag_data[$i]['tagparts'][0] == $this->tag_data[$i]['tagparts'][1] &&
  753. ! isset($this->tag_data[$i]['tagparts'][2]))
  754. {
  755. unset($this->tag_data[$i]['tagparts'][1]);
  756. }
  757. $error = $this->EE->lang->line('error_tag_syntax');
  758. $error .= '<br /><br />';
  759. $error .= htmlspecialchars(LD);
  760. $error .= 'exp:'.implode(':', $this->tag_data[$i]['tagparts']);
  761. $error .= htmlspecialchars(RD);
  762. $error .= '<br /><br />';
  763. $error .= $this->EE->lang->line('error_fix_syntax');
  764. $this->EE->output->fatal_error($error);
  765. }
  766. else
  767. return FALSE;
  768. }
  769. else
  770. {
  771. $plugins[] = $this->tag_data[$i]['class'];
  772. $this->log_item("Plugin Tag: ".ucfirst($this->tag_data[$i]['class']).'/'.$this->tag_data[$i]['method']);
  773. }
  774. }
  775. else
  776. {
  777. $modules[] = $this->tag_data[$i]['class'];
  778. $this->log_item("Module Tag: ".ucfirst($this->tag_data[$i]['class']).'/'.$this->tag_data[$i]['method']);
  779. }
  780. }
  781. }
  782. // Remove duplicate class names and re-order the array
  783. $plugins = array_values(array_unique($plugins));
  784. $modules = array_values(array_unique($modules));
  785. // Dynamically require the file that contains each class
  786. $this->log_item("Including Files for Plugins and Modules");
  787. foreach ($plugins as $plugin)
  788. {
  789. // make sure it's not already included just in case
  790. if ( ! class_exists($plugin))
  791. {
  792. if (in_array($plugin ,$this->EE->core->native_plugins))
  793. {
  794. require_once PATH_PI."pi.{$plugin}.php";
  795. }
  796. else
  797. {
  798. require_once PATH_THIRD."{$plugin}/pi.{$plugin}.php";
  799. }
  800. }
  801. }
  802. foreach ($modules as $module)
  803. {
  804. // make sure it's not already included just in case
  805. if ( ! class_exists($module))
  806. {
  807. if (in_array($module, $this->EE->core->native_modules))
  808. {
  809. require_once PATH_MOD."{$module}/mod.{$module}.php";
  810. }
  811. else
  812. {
  813. require_once PATH_THIRD."{$module}/mod.{$module}.php";
  814. }
  815. }
  816. }
  817. $this->log_item("Files for Plugins and Modules All Included");
  818. // Only Retrieve Data if Not Done Before and Modules Being Called
  819. if (count($this->module_data) == 0 && count(array_intersect($this->modules, $modules)) > 0)
  820. {
  821. $this->EE->db->select('module_version, module_name');
  822. $query = $this->EE->db->get('modules');
  823. foreach($query->result_array() as $row)
  824. {
  825. $this->module_data[$row['module_name']] = array('version' => $row['module_version']);
  826. }
  827. }
  828. // Final data processing
  829. // Loop through the master array containing our extracted template data
  830. $this->log_item("Beginning Final Tag Data Processing");
  831. reset($this->tag_data);
  832. for ($i = 0; $i < count($this->tag_data); $i++)
  833. {
  834. if ($this->tag_data[$i]['cache'] != 'CURRENT')
  835. {
  836. $this->log_item("Calling Class/Method: ".ucfirst($this->tag_data[$i]['class'])."/".$this->tag_data[$i]['method']);
  837. /* ---------------------------------
  838. /* Plugin as Parameter
  839. /*
  840. /* - Example: channel="{exp:some_plugin}"
  841. /* - A bit of a hidden feature. Has been tested but not quite
  842. /* ready to say it is ready for prime time as I might want to
  843. /* move it to earlier in processing so that if there are
  844. /* multiple plugins being used as parameters it is only called
  845. /* once instead of for every single parameter. - Paul
  846. /* ---------------------------------*/
  847. 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')
  848. {
  849. foreach($this->tag_data[$i]['params'] as $name => $param)
  850. {
  851. if (stristr($this->tag_data[$i]['params'][$name], LD.'exp'))
  852. {
  853. $this->log_item("Plugin in Parameter, Processing Plugin First");
  854. $TMPL2 = clone $this;
  855. while (is_int(strpos($TMPL2->tag_data[$i]['params'][$name], LD.'exp:')))
  856. {
  857. unset($this->EE->TMPL);
  858. $this->EE->TMPL = new EE_Template();
  859. $this->EE->TMPL->start_microtime = $this->start_microtime;
  860. $this->EE->TMPL->template = $TMPL2->tag_data[$i]['params'][$name];
  861. $this->EE->TMPL->tag_data = array();
  862. $this->EE->TMPL->var_single = array();
  863. $this->EE->TMPL->var_cond = array();
  864. $this->EE->TMPL->var_pair = array();
  865. $this->EE->TMPL->plugins = $TMPL2->plugins;
  866. $this->EE->TMPL->modules = $TMPL2->modules;
  867. $this->EE->TMPL->parse_tags();
  868. $this->EE->TMPL->process_tags();
  869. $this->EE->TMPL->loop_count = 0;
  870. $TMPL2->tag_data[$i]['params'][$name] = $this->EE->TMPL->template;
  871. $TMPL2->log = array_merge($TMPL2->log, $this->EE->TMPL->log);
  872. }
  873. foreach (get_object_vars($TMPL2) as $key => $value)
  874. {
  875. $this->$key = $value;
  876. }
  877. unset($TMPL2);
  878. $this->EE->TMPL = $this;
  879. }
  880. }
  881. }
  882. // Nested Plugins...
  883. if (in_array($this->tag_data[$i]['class'] , $this->plugins) && strpos($this->tag_data[$i]['block'], LD.'exp:') !== FALSE)
  884. {
  885. if ( ! isset($this->tag_data[$i]['params']['parse']) OR $this->tag_data[$i]['params']['parse'] != 'inward')
  886. {
  887. $this->log_item("Nested Plugins in Tag, Parsing Outward First");
  888. $TMPL2 = clone $this;
  889. while (is_int(strpos($TMPL2->tag_data[$i]['block'], LD.'exp:')))
  890. {
  891. unset($this->EE->TMPL);
  892. $this->EE->TMPL = new EE_Template();
  893. $this->EE->TMPL->start_microtime = $this->start_microtime;
  894. $this->EE->TMPL->template = $TMPL2->tag_data[$i]['block'];
  895. $this->EE->TMPL->tag_data = array();
  896. $this->EE->TMPL->var_single = array();
  897. $this->EE->TMPL->var_cond = array();
  898. $this->EE->TMPL->var_pair = array();
  899. $this->EE->TMPL->plugins = $TMPL2->plugins;
  900. $this->EE->TMPL->modules = $TMPL2->modules;
  901. $this->EE->TMPL->parse_tags();
  902. $this->EE->TMPL->process_tags();
  903. $this->EE->TMPL->loop_count = 0;
  904. $TMPL2->tag_data[$i]['block'] = $this->EE->TMPL->template;
  905. $TMPL2->log = array_merge($TMPL2->log, $this->EE->TMPL->log);
  906. }
  907. foreach (get_object_vars($TMPL2) as $key => $value)
  908. {
  909. $this->$key = $value;
  910. }
  911. unset($TMPL2);
  912. $this->EE->TMPL = $this;
  913. }
  914. }
  915. // Assign the data chunk, parameters
  916. // We moved the no_results_block here because of nested tags. The first
  917. // parsed tag has priority for that conditional.
  918. $this->tagdata = str_replace($this->tag_data[$i]['no_results_block'], '', $this->tag_data[$i]['block']);
  919. $this->tagparams = $this->tag_data[$i]['params'];
  920. $this->tagchunk = $this->tag_data[$i]['chunk'];
  921. $this->tagproper = $this->tag_data[$i]['tag'];
  922. $this->tagparts = $this->tag_data[$i]['tagparts'];
  923. $this->no_results = $this->tag_data[$i]['no_results'];
  924. $this->search_fields = $this->tag_data[$i]['search_fields'];
  925. // Assign Sites for Tag
  926. $this->_fetch_site_ids();
  927. // Fetch Form Class/Id Attributes
  928. $this->tag_data[$i] = $this->_assign_form_params($this->tag_data[$i]);
  929. // Relationship Data Pulled Out
  930. // If the channel:entries tag or search:search_results is being called
  931. // we need to extract any relationship data that might be present.
  932. // Note: This needs to happen before extracting the variables
  933. // in the tag so it doesn't get confused as to which entry the
  934. // variables belong to.
  935. if (($this->tag_data[$i]['class'] == 'channel' AND $this->tag_data[$i]['method'] == 'entries')
  936. OR ($this->tag_data[$i]['class'] == 'search' AND $this->tag_data[$i]['method'] == 'search_results'))
  937. {
  938. $this->tagdata = $this->assign_relationship_data($this->tagdata);
  939. }
  940. // LEGACY CODE
  941. // Fetch the variables for this particular tag
  942. // Hopefully, with Jones' new parsing code we should be able to stop using the
  943. // assign_variables and assign_conditional_variables() methods entirely. -Paul
  944. $vars = $this->EE->functions->assign_variables($this->tag_data[$i]['block']);
  945. if (count($this->related_markers) > 0)
  946. {
  947. foreach ($this->related_markers as $mkr)
  948. {
  949. if ( ! isset($vars['var_single'][$mkr]))
  950. {
  951. $vars['var_single'][$mkr] = $mkr;
  952. }
  953. }
  954. }
  955. $this->var_single = $vars['var_single'];
  956. $this->var_pair = $vars['var_pair'];
  957. if ($this->related_id != '')
  958. {
  959. $this->var_single[$this->related_id] = $this->related_id;
  960. $this->related_id = '';
  961. }
  962. // Assign the class name and method name
  963. $class_name = ucfirst($this->tag_data[$i]['class']);
  964. $meth_name = $this->tag_data[$i]['method'];
  965. // If it's a third party class or a first party module,
  966. // add the root folder to the loader paths so we can use
  967. // libraries, models, and helpers
  968. $package_path = '';
  969. if ( ! in_array($this->tag_data[$i]['class'], $this->EE->core->native_plugins))
  970. {
  971. $package_path = in_array($this->tag_data[$i]['class'], $this->EE->core->native_modules) ? PATH_MOD : PATH_THIRD;
  972. $package_path .= strtolower($this->tag_data[$i]['class'].'/');
  973. $this->EE->load->add_package_path($package_path, FALSE);
  974. }
  975. // Dynamically instantiate the class.
  976. // If module, only if it is installed...
  977. if (in_array($this->tag_data[$i]['class'], $this->modules) && ! isset($this->module_data[$class_name]))
  978. {
  979. $this->log_item("Problem Processing Module: Module Not Installed");
  980. }
  981. else
  982. {
  983. $this->log_item(" -> Class Called: ".$class_name);
  984. $EE = new $class_name();
  985. }
  986. // This gives proper PHP5 __construct() support in
  987. // plugins and modules with only a single __construct()
  988. // and allows them to be named __construct() instead of a
  989. // PHP4-style contructor.
  990. if ($meth_name === FALSE && isset($EE))
  991. {
  992. if (method_exists($EE, $class_name))
  993. {
  994. $meth_name = $class_name;
  995. }
  996. elseif (method_exists($EE, '__construct'))
  997. {
  998. $meth_name = '__construct';
  999. }
  1000. }
  1001. // Does method exist? Is This A Module and Is It Installed?
  1002. if ((in_array($this->tag_data[$i]['class'], $this->modules) &&
  1003. ! isset($this->module_data[$class_name])) OR
  1004. ! is_callable(array($EE, $meth_name)))
  1005. {
  1006. $this->log_item("Tag Not Processed: Method Inexistent or Module Not Installed");
  1007. if ($this->EE->config->item('debug') >= 1)
  1008. {
  1009. if (isset($this->tag_data[$i]['tagparts'][1]) && $this->tag_data[$i]['tagparts'][0] == $this->tag_data[$i]['tagparts'][1] &&
  1010. ! isset($this->tag_data[$i]['tagparts'][2]))
  1011. {
  1012. unset($this->tag_data[$i]['tagparts'][1]);
  1013. }
  1014. $error = $this->EE->lang->line('error_tag_module_processing');
  1015. $error .= '<br /><br />';
  1016. $error .= htmlspecialchars(LD);
  1017. $error .= 'exp:'.implode(':', $this->tag_data[$i]['tagparts']);
  1018. $error .= htmlspecialchars(RD);
  1019. $error .= '<br /><br />';
  1020. $error .= str_replace('%x', $this->tag_data[$i]['class'], str_replace('%y', $meth_name, $this->EE->lang->line('error_fix_module_processing')));
  1021. $this->EE->output->fatal_error($error);
  1022. }
  1023. else
  1024. {
  1025. return;
  1026. }
  1027. }
  1028. /*
  1029. OK, lets grab the data returned from the class.
  1030. First, however, lets determine if the tag has one or two segments.
  1031. If it only has one, we don't want to call the constructor again since
  1032. it was already called during instantiation.
  1033. Note: If it only has one segment, only the object constructor will be called.
  1034. Since constructors can't return a value just by initialializing the object
  1035. the output of the class must be assigned to a variable called $this->return_data
  1036. */
  1037. $this->log_item(" -> Method Called: ".$meth_name);
  1038. if ((strtolower($class_name) == strtolower($meth_name)) OR ($meth_name == '__construct'))
  1039. {
  1040. $return_data = (isset($EE->return_data)) ? $EE->return_data : '';
  1041. }
  1042. else
  1043. {
  1044. $return_data = $EE->$meth_name();
  1045. }
  1046. // if it's a third party add-on or module, remove the temporarily added path for local libraries, models, etc.
  1047. // if a "no results" template is returned, $this->tag_data will be reset inside of the scope
  1048. // of the tag being processed. So let's use the locally scoped variable for the class name
  1049. if ($package_path)
  1050. {
  1051. $this->EE->load->remove_package_path($package_path);
  1052. }
  1053. // 404 Page Triggered, Cease All Processing of Tags From Now On
  1054. if ($this->cease_processing === TRUE)
  1055. {
  1056. return;
  1057. }
  1058. $this->log_item(" -> Data Returned");
  1059. // Write cache file if needed
  1060. if ($this->tag_data[$i]['cache'] == 'EXPIRED')
  1061. {
  1062. $this->write_cache_file($this->tag_data[$i]['cfile'], $return_data);
  1063. }
  1064. // Replace the temporary markers we added earlier with the fully parsed data
  1065. $this->template = str_replace('M'.$i.$this->marker, $return_data, $this->template);
  1066. // Initialize data in case there are susequent loops
  1067. $this->var_single = array();
  1068. $this->var_cond = array();
  1069. $this->var_pair = array();
  1070. unset($return_data);
  1071. unset($class_name);
  1072. unset($meth_name);
  1073. unset($EE);
  1074. }
  1075. }
  1076. }
  1077. // --------------------------------------------------------------------
  1078. /**
  1079. * Process Tags
  1080. *
  1081. * Channel entries can have related entries embedded within them.
  1082. * We'll extract the related tag data, stash it away in an array, and
  1083. * replace it with a marker string so that the template parser
  1084. * doesn't see it. In the channel class we'll check to see if the
  1085. * $this->EE->TMPL->related_data array contains anything. If so, we'll celebrate
  1086. * wildly.
  1087. *
  1088. * @param string
  1089. * @return string
  1090. */
  1091. public function assign_relationship_data($chunk)
  1092. {
  1093. $this->related_markers = array();
  1094. if (preg_match_all("/".LD."related_entries\s+id\s*=\s*[\"\'](.+?)[\"\']".RD."(.+?)".LD.'\/'."related_entries".RD."/is", $chunk, $matches))
  1095. {
  1096. $this->log_item("Assigning Related Entry Data");
  1097. $no_rel_content = '';
  1098. for ($j = 0; $j < count($matches[0]); $j++)
  1099. {
  1100. $rand = $this->EE->functions->random('alnum', 8);
  1101. $marker = LD.'REL['.$matches[1][$j].']'.$rand.'REL'.RD;
  1102. if (preg_match("/".LD."if no_related_entries".RD."(.*?)".LD.'\/'."if".RD."/s", $matches[2][$j], $no_rel_match))
  1103. {
  1104. // Match the entirety of the conditional
  1105. if (stristr($no_rel_match[1], LD.'if'))
  1106. {
  1107. $match[0] = $this->EE->functions->full_tag($no_rel_match[0], $matches[2][$j], LD.'if', LD.'\/'."if".RD);
  1108. }
  1109. $no_rel_content = substr($no_rel_match[0], strlen(LD."if no_related_entries".RD), -strlen(LD.'/'."if".RD));
  1110. }
  1111. $this->related_markers[] = $matches[1][$j];
  1112. $vars = $this->EE->functions->assign_variables($matches[2][$j]);
  1113. $this->related_id = $matches[1][$j];
  1114. $this->related_data[$rand] = array(
  1115. 'marker' => $rand,
  1116. 'field_name' => $matches[1][$j],
  1117. 'tagdata' => $matches[2][$j],
  1118. 'var_single' => $vars['var_single'],
  1119. 'var_pair' => $vars['var_pair'],
  1120. 'var_cond' => $this->EE->functions->assign_conditional_variables($matches[2][$j], '\/', LD, RD),
  1121. 'no_rel_content' => $no_rel_content
  1122. );
  1123. $chunk = str_replace($matches[0][$j], $marker, $chunk);
  1124. }
  1125. }
  1126. if (preg_match_all("/".LD."reverse_related_entries\s*(.*?)".RD."(.+?)".LD.'\/'."reverse_related_entries".RD."/is", $chunk, $matches))
  1127. {
  1128. $this->log_item("Assigning Reverse Related Entry Data");
  1129. for ($j = 0; $j < count($matches[0]); $j++)
  1130. {
  1131. $rand = $this->EE->functions->random('alnum', 8);
  1132. $marker = LD.'REV_REL['.$rand.']REV_REL'.RD;
  1133. $vars = $this->EE->functions->assign_variables($matches[2][$j]);
  1134. $no_rev_content = '';
  1135. if (preg_match("/".LD."if no_reverse_related_entries".RD."(.*?)".LD.'\/'."if".RD."/s", $matches[2][$j], $no_rev_match))
  1136. {
  1137. // Match the entirety of the conditional
  1138. if (stristr($no_rev_match[1], LD.'if'))
  1139. {
  1140. $match[0] = $this->EE->functions->full_tag($no_rev_match[0], $matches[2][$j], LD.'if', LD.'\/'."if".RD);
  1141. }
  1142. $no_rev_content = substr($no_rev_match[0], strlen(LD."if no_reverse_related_entries".RD), -strlen(LD.'/'."if".RD));
  1143. }
  1144. $this->reverse_related_data[$rand] = array(
  1145. 'marker' => $rand,
  1146. 'tagdata' => $matches[2][$j],
  1147. 'var_single' => $vars['var_single'],
  1148. 'var_pair' => $vars['var_pair'],
  1149. 'var_cond' => $this->EE->functions->assign_conditional_variables($matches[2][$j], '\/', LD, RD),
  1150. 'params' => $this->EE->functions->assign_parameters($matches[1][$j]),
  1151. 'no_rev_content' => $no_rev_content
  1152. );
  1153. $chunk = str_replace($matches[0][$j], $marker, $chunk);
  1154. }
  1155. }
  1156. return $chunk;
  1157. }
  1158. // --------------------------------------------------------------------
  1159. /**
  1160. * Fetch Parameter for Tag
  1161. *
  1162. * Used by Modules to fetch a paramter for the tag currently be processed. We also have code
  1163. * in here to convert legacy values like 'y' and 'on' to their more respectable full values.
  1164. * Further, if one assigns the second argument, it will be returned as the value if a
  1165. * parameter of the $which name does not exist for this tag. Handy for default values!
  1166. *
  1167. * @access string
  1168. * @access bool
  1169. * @return string
  1170. */
  1171. public function fetch_param($which, $default = FALSE)
  1172. {
  1173. if ( ! isset($this->tagparams[$which]))
  1174. {
  1175. return $default;
  1176. }
  1177. else
  1178. {
  1179. // Making yes/no tag parameters consistent. No "y/n" or "on/off".
  1180. switch($this->tagparams[$which])
  1181. {
  1182. case 'y' :
  1183. case 'on' :
  1184. return 'yes';
  1185. break;
  1186. case 'n' :
  1187. case 'off' :
  1188. return 'no';
  1189. break;
  1190. default :
  1191. return $this->tagparams[$which];
  1192. break;
  1193. }
  1194. }
  1195. }
  1196. // --------------------------------------------------------------------
  1197. /**
  1198. * Replace a Single Variable with Its Value
  1199. *
  1200. * LEGACY!!!
  1201. *
  1202. * @deprecated
  1203. * @param string
  1204. * @param string
  1205. * @param string
  1206. * @return string
  1207. */
  1208. public function swap_var_single($search, $replace, $source)
  1209. {
  1210. return str_replace(LD.$search.RD, $replace, $source);
  1211. }
  1212. // --------------------------------------------------------------------
  1213. /**
  1214. * Seems to Take a Variable Pair and Replace it With Its COntents
  1215. *
  1216. * LEGACY!!!
  1217. *
  1218. * @deprecated
  1219. * @param string
  1220. * @param string
  1221. * @param string
  1222. * @return string
  1223. */
  1224. public function swap_var_pairs($open, $close, $source)
  1225. {
  1226. return preg_replace("/".LD.preg_quote($open).RD."(.*?)".LD.'\/'.$close.RD."/s", "\\1", $source);
  1227. }
  1228. // --------------------------------------------------------------------
  1229. /**
  1230. * Completely Removes a Variable Pair
  1231. *
  1232. * LEGACY!!!
  1233. *
  1234. * @deprecated
  1235. * @param string
  1236. * @param string
  1237. * @param string
  1238. * @return string
  1239. */
  1240. public function delete_var_pairs($open, $close, $source)
  1241. {
  1242. return preg_replace("/".LD.preg_quote($open).RD."(.*?)".LD.'\/'.$close.RD."/s", "", $source);
  1243. }
  1244. // --------------------------------------------------------------------
  1245. /**
  1246. * Fetches Variable Pair's Content
  1247. *
  1248. * LEGACY!!!
  1249. *
  1250. * @deprecated
  1251. * @param string
  1252. * @param string
  1253. * @return string
  1254. */
  1255. public function fetch_data_between_var_pairs($str, $variable)
  1256. {
  1257. if ($str == '' OR $variable == '')
  1258. return;
  1259. if ( ! preg_match("/".LD.$variable.".*?".RD."(.*?)".LD.'\/'.$variable.RD."/s", $str, $match))
  1260. return;
  1261. return $match[1];
  1262. }
  1263. // --------------------------------------------------------------------
  1264. /**
  1265. * Returns String with PHP Processed
  1266. *
  1267. * @param string
  1268. * @return string
  1269. */
  1270. public function parse_template_php($str)
  1271. {
  1272. ob_start();
  1273. echo $this->EE->functions->evaluate($str);
  1274. $str = ob_get_contents();
  1275. ob_end_clean();
  1276. $this->parse_php = FALSE;
  1277. return $str;
  1278. }
  1279. // --------------------------------------------------------------------
  1280. /**
  1281. * Get Cache File Data
  1282. *
  1283. * @param string
  1284. * @param string
  1285. * @param mixed
  1286. * @return string
  1287. */
  1288. public function fetch_cache_file($cfile, $cache_type = 'tag', $args = array())
  1289. {
  1290. // Which cache are we working on?
  1291. $status = ($cache_type == 'tag') ? 'tag_cache_status' : 'cache_status';
  1292. $status =& $this->$status;
  1293. if ( ! isset($args['cache']) OR $args['cache'] != 'yes')
  1294. {
  1295. $status = 'NO_CACHE';
  1296. return FALSE;
  1297. }
  1298. $cache_dir = ($cache_type == 'tag') ? APPPATH.'cache/'.$this->t_cache_path : $cache_dir = APPPATH.'cache/'.$this->p_cache_path;
  1299. $file = $cache_dir.$cfile;
  1300. if ( ! file_exists($file) OR ! ($fp = @fopen($file, FOPEN_READ)))
  1301. {
  1302. $status = 'EXPIRED';
  1303. return FALSE;
  1304. }
  1305. $cache = '';
  1306. $refresh = ( ! isset($args['refresh'])) ? 0 : $args['refresh'];
  1307. flock($fp, LOCK_SH);
  1308. // Read the first line (left a small buffer - just in case)
  1309. $timestamp = trim(fgets($fp, 30));
  1310. if ((strlen($timestamp) != 10) OR ($timestamp !== ((string)(int) $timestamp))) // Integer check
  1311. {
  1312. // Should never happen - so we'll log it
  1313. $this->log_item("Invalid Cache File Format: ".$file);
  1314. $status = 'EXPIRED';
  1315. }
  1316. elseif (time() > ($timestamp + ($refresh * 60)))
  1317. {
  1318. $status = 'EXPIRED';
  1319. }
  1320. else
  1321. {
  1322. // Timestamp valid - read rest of file
  1323. $this->cache_timestamp = (int) $timestamp;
  1324. $status = 'CURRENT';
  1325. $cache = @fread($fp, filesize($file));
  1326. }
  1327. flock($fp, LOCK_UN);
  1328. fclose($fp);
  1329. return $cache;
  1330. }
  1331. // --------------------------------------------------------------------
  1332. /**
  1333. * Write Data to Cache File
  1334. *
  1335. * Stores the Tag and Page Cache Data
  1336. *
  1337. * @param string
  1338. * @param string
  1339. * @param string
  1340. * @return string
  1341. */
  1342. public function write_cache_file($cfile, $data, $cache_type = 'tag')
  1343. {
  1344. if ($this->disable_caching == TRUE)
  1345. {
  1346. return;
  1347. }
  1348. /* -------------------------------------
  1349. /* Disable Tag Caching
  1350. /*
  1351. /* All for you, Nevin! Disables tag caching, which if used unwisely
  1352. /* on a high traffic site can lead to disastrous disk i/o
  1353. /* This setting allows quick thinking admins to temporarily disable
  1354. /* it without hacking or modifying folder permissions
  1355. /*
  1356. /* Hidden Configuration Variable
  1357. /* - disable_tag_caching => Disable tag caching? (y/n)
  1358. /* -------------------------------------*/
  1359. if ($cache_type == 'tag' && $this->EE->config->item('disable_tag_caching') == 'y')
  1360. {
  1361. return;
  1362. }
  1363. $cache_dir = ($cache_type == 'tag') ? APPPATH.'cache/'.$this->t_cache_path : $cache_dir = APPPATH.'cache/'.$this->p_cache_path;
  1364. $cache_base = ($cache_type == 'tag') ? APPPATH.'cache/tag_cache' : APPPATH.'cache/page_cache';
  1365. $cache_file = $cache_dir.$cfile;
  1366. $dirs = array($cache_base, $cache_dir);
  1367. foreach ($dirs as $dir)
  1368. {
  1369. if ( ! @is_dir($dir))
  1370. {
  1371. if ( ! @mkdir($dir, DIR_WRITE_MODE))
  1372. {
  1373. return;
  1374. }
  1375. if ($dir == $cache_base && $fp = @fopen($dir.'/index.html', FOPEN_WRITE_CREATE_DESTRUCTIVE))
  1376. {
  1377. fclose($fp);
  1378. }
  1379. @chmod($dir, DIR_WRITE_MODE);
  1380. }
  1381. }
  1382. if ( ! $fp = @fopen($cache_file, FOPEN_WRITE_CREATE_DESTRUCTIVE))
  1383. {
  1384. $this->log_item("Could not create/write to cache file: ".$cache_file);
  1385. return;
  1386. }
  1387. flock($fp, LOCK_EX);
  1388. if (fwrite($fp, time()."\n".$data) === FALSE)
  1389. {
  1390. $this->log_item("Could not write to cache file: ".$cache_file);
  1391. }
  1392. flock($fp, LOCK_UN);
  1393. fclose($fp);
  1394. @chmod($cache_file, FILE_WRITE_MODE);
  1395. }
  1396. // --------------------------------------------------------------------
  1397. /**
  1398. * Parse Template URI
  1399. *
  1400. * Determines Which Template to Fetch Based on the Page's URI.
  1401. * If invalid Template, shows Template Group's index page
  1402. * If invalid Template Group, depending on sendings may show 404 or default Template Group
  1403. *
  1404. * @return string
  1405. */
  1406. public function parse_template_uri()
  1407. {
  1408. $this->log_item("Parsing Template URI");
  1409. // Does the first segment exist? No? Show the default template
  1410. if ($this->EE->uri->segment(1) === FALSE)
  1411. {
  1412. return $this->fetch_template('', 'index', TRUE);
  1413. }
  1414. // Is only the pagination showing in the URI?
  1415. elseif(count($this->EE->uri->segments) == 1 &&
  1416. preg_match("#^(P\d+)$#", $this->EE->uri->segment(1), $match))
  1417. {
  1418. $this->EE->uri->query_string = $match['1'];
  1419. return $this->fetch_template('', 'index', TRUE);
  1420. }
  1421. // Set the strict urls pref
  1422. if ($this->EE->config->item('strict_urls') !== FALSE)
  1423. {
  1424. $this->strict_urls = ($this->EE->config->item('strict_urls') == 'y') ? TRUE : FALSE;
  1425. }
  1426. // Load the string helper
  1427. $this->EE->load->helper('string');
  1428. // At this point we know that we have at least one segment in the URI, so
  1429. // let's try to determine what template group/template we should show
  1430. // Is the first segment the name of a template group?
  1431. $this->EE->db->select('group_id');
  1432. $this->EE->db->where('group_name', $this->EE->uri->segment(1));
  1433. $this->EE->db->where('site_id', $this->EE->config->item('site_id'));
  1434. $query = $this->EE->db->get('template_groups');
  1435. // Template group found!
  1436. if ($query->num_rows() == 1)
  1437. {
  1438. // Set the name of our template group
  1439. $template_group = $this->EE->uri->segment(1);
  1440. $this->log_item("Template Group Found: ".$template_group);
  1441. // Set the group_id so we can use it in the next query
  1442. $group_id = $query->row('group_id');
  1443. // Does the second segment of the URI exist? If so...
  1444. if ($this->EE->uri->segment(2) !== FALSE)
  1445. {
  1446. // Is the second segment the name of a valid template?
  1447. $this->EE->db->select('COUNT(*) as count');
  1448. $this->EE->db->where('group_id', $group_id);
  1449. $this->EE->db->where('template_name', $this->EE->uri->segment(2));
  1450. $query = $this->EE->db->get('templates');
  1451. // We have a template name!
  1452. if ($query->row('count') == 1)
  1453. {
  1454. // Assign the template name
  1455. $template = $this->EE->uri->segment(2);
  1456. // Re-assign the query string variable in the Input class so the various tags can show the correct data
  1457. $this->EE->uri->query_string = ( ! $this->EE->uri->segment(3) AND $this->EE->uri->segment(2) != 'index') ? '' : trim_slashes(substr($this->EE->uri->uri_string, strlen('/'.$this->EE->uri->segment(1).'/'.$this->EE->uri->segment(2))));
  1458. }
  1459. else // A valid template was not found
  1460. {
  1461. // is there a file we can automatically create this template from?
  1462. if ($this->EE->config->item('save_tmpl_files') == 'y' && $this->EE->config->item('tmpl_file_basepath') != '')
  1463. {
  1464. if ($this->_create_from_file($template_group, $this->EE->uri->segment(2)))
  1465. {
  1466. return $this->fetch_template($template_group, $this->EE->uri->segment(2), FALSE);
  1467. }
  1468. }
  1469. // Set the template to index
  1470. $template = 'index';
  1471. // Re-assign the query string variable in the Input class so the various tags can show the correct data
  1472. $this->EE->uri->query_string = ( ! $this->EE->uri->segment(3)) ? $this->EE->uri->segment(2) : trim_slashes(substr($this->EE->uri->uri_string, strlen('/'.$this->EE->uri->segment(1))));
  1473. }
  1474. }
  1475. // The second segment of the URL does not exist
  1476. else
  1477. {
  1478. // Set the template as "index"
  1479. $template = 'index';
  1480. }
  1481. }
  1482. // The first segment in the URL does NOT correlate to a valid template group. Oh my!
  1483. else
  1484. {
  1485. // If we are enforcing strict URLs we need to show a 404
  1486. if ($this->strict_urls == TRUE)
  1487. {
  1488. // is there a file we can automatically create this template from?
  1489. if ($this->EE->config->item('save_tmpl_files') == 'y' && $this->EE->config->item('tmpl_file_basepath') != '')
  1490. {
  1491. if ($this->_create_from_file($this->EE->uri->segment(1), $this->EE->uri->segment(2)))
  1492. {
  1493. return $this->fetch_template($this->EE->uri->segment(1), $this->EE->uri->segment(2), FALSE);
  1494. }
  1495. }
  1496. if ($this->EE->config->item('site_404'))
  1497. {
  1498. $this->log_item("Template group and template not found, showing 404 page");
  1499. return $this->fetch_template('', '', FALSE);
  1500. }
  1501. else
  1502. {
  1503. return $this->_404();
  1504. }
  1505. }
  1506. // We we are not enforcing strict URLs, so Let's fetch the the name of the default template group
  1507. $result = $this->EE->db->select('group_name, group_id')
  1508. ->get_where(
  1509. 'template_groups',
  1510. array(
  1511. 'is_site_default' => 'y',
  1512. 'site_id' => $this->EE->config->item('site_id')
  1513. )
  1514. );
  1515. // No result? Bail out...
  1516. // There's really nothing else to do here. We don't have a valid
  1517. // template group in the URL and the admin doesn't have a template
  1518. // group defined as the site default.
  1519. if ($result->num_rows() == 0)
  1520. {
  1521. // Turn off caching
  1522. $this->disable_caching = TRUE;
  1523. // Show the user-specified 404
  1524. if ($this->EE->config->item('site_404'))
  1525. {
  1526. $this->log_item("Template group and template not found, showing 404 page");
  1527. return $this->fetch_template('', '', FALSE);
  1528. }
  1529. else
  1530. {
  1531. // Show the default 404
  1532. return $this->_404();
  1533. }
  1534. }
  1535. // Since the first URI segment isn't a template group name,
  1536. // could it be the name of a template in the default group?
  1537. $this->EE->db->select('COUNT(*) as count');
  1538. $this->EE->db->where('group_id', $result->row('group_id'));
  1539. $this->EE->db->where('template_name', $this->EE->uri->segment(1));
  1540. $query = $this->EE->db->get('templates');
  1541. // We found a valid template!
  1542. if ($query->row('count') == 1)
  1543. {
  1544. // Set the template group name from the prior query result (we
  1545. // use the default template group name)
  1546. $template_group = $result->row('group_name');
  1547. $this->log_item("Template Group Using Default: ".$template_group);
  1548. // Set the template name
  1549. $template = $this->EE->uri->segment(1);
  1550. // Re-assign the query string variable in the Input class so the
  1551. // various tags can show the correct data
  1552. if ($this->EE->uri->segment(2))
  1553. {
  1554. $this->EE->uri->query_string = trim_slashes(substr(
  1555. $this->EE->uri->uri_string,
  1556. strlen('/'.$this->EE->uri->segment(1))
  1557. ));
  1558. }
  1559. }
  1560. // A valid template was not found. At this point we do not have
  1561. // either a valid template group or a valid template name in the URL
  1562. else
  1563. {
  1564. // is there a file we can automatically create this template from?
  1565. if ($this->EE->config->item('save_tmpl_files') == 'y'
  1566. && $this->EE->config->item('tmpl_file_basepath') != '')
  1567. {
  1568. if ($this->_create_from_file($this->EE->uri->segment(1), $this->EE->uri->segment(2)))
  1569. {
  1570. return $this->fetch_template(
  1571. $this->EE->uri->segment(1),
  1572. $this->EE->uri->segment(2),
  1573. FALSE
  1574. );
  1575. }
  1576. }
  1577. // Turn off caching
  1578. $this->disable_caching = TRUE;
  1579. // Default to site's index template
  1580. $this->EE->uri->query_string = trim_slashes(
  1581. $this->EE->uri->uri_string
  1582. );
  1583. $template_group = $result->row('group_name');
  1584. $template = 'index';
  1585. }
  1586. }
  1587. // Fetch the template!
  1588. return $this->fetch_template($template_group, $template, FALSE);
  1589. }
  1590. // --------------------------------------------------------------------
  1591. /**
  1592. * 404 Page
  1593. *
  1594. * If users do not have a 404 template specified this is what gets shown
  1595. *
  1596. * @return string
  1597. */
  1598. protected function _404()
  1599. {
  1600. $this->log_item("404 Page Returned");
  1601. $this->EE->output->set_status_header(404);
  1602. echo '<html><head><title>404 Page Not Found</title></head><body><h1>Status: 404 Page Not Found</h1></body></html>';
  1603. exit;
  1604. }
  1605. // --------------------------------------------------------------------
  1606. /**
  1607. * Fetch Template Data
  1608. *
  1609. * Takes a Template Group, Template, and Site ID and will retrieve the Template and its metadata
  1610. * from the database (or file)
  1611. *
  1612. * @param string
  1613. * @param string
  1614. * @param bool
  1615. * @param int
  1616. * @return string
  1617. */
  1618. public function fetch_template($template_group, $template, $show_default = TRUE, $site_id = '')
  1619. {
  1620. if ($site_id == '' OR ! is_numeric($site_id))
  1621. {
  1622. $site_id = $this->EE->config->item('site_id');
  1623. }
  1624. $this->log_item("Retrieving Template from Database: ".$template_group.'/'.$template);
  1625. $show_404 = FALSE;
  1626. $template_group_404 = '';
  1627. $template_404 = '';
  1628. /* -------------------------------------------
  1629. /* Hidden Configuration Variable
  1630. /* - hidden_template_indicator => '.'
  1631. The character(s) used to designate a template as "hidden"
  1632. /* -------------------------------------------*/
  1633. $hidden_indicator = ($this->EE->config->item('hidden_template_indicator') === FALSE) ? '.' : $this->EE->config->item('hidden_template_indicator');
  1634. if ($this->depth == 0
  1635. AND substr($template, 0, 1) == $hidden_indicator
  1636. AND $this->EE->uri->page_query_string == '') // Allow hidden templates to be used for Pages requests
  1637. {
  1638. /* -------------------------------------------
  1639. /* Hidden Configuration Variable
  1640. /* - hidden_template_404 => y/n
  1641. If a hidden template is encountered, the default behavior is
  1642. to throw a 404. With this set to 'n', the template group's
  1643. index page will be shown instead
  1644. /* -------------------------------------------*/
  1645. if ($this->EE->config->item('hidden_template_404') !== 'n')
  1646. {
  1647. $x = explode("/", $this->EE->config->item('site_404'));
  1648. if (isset($x[0]) AND isset($x[1]))
  1649. {
  1650. $this->EE->output->out_type = '404';
  1651. $this->template_type = '404';
  1652. $template_group_404 = $this->EE->db->escape_str($x[0]);
  1653. $template_404 = $this->EE->db->escape_str($x[1]);
  1654. $this->EE->db->where(array(
  1655. 'template_groups.group_name' => $x[0],
  1656. 'templates.template_name' => $x[1]
  1657. ));
  1658. $show_404 = TRUE;
  1659. }
  1660. else
  1661. {
  1662. $template = 'index';
  1663. }
  1664. }
  1665. else
  1666. {
  1667. $template = 'index';
  1668. }
  1669. }
  1670. if ($template_group == '' && $show_default == FALSE && $this->EE->config->item('site_404') != '')
  1671. {
  1672. $treq = $this->EE->config->item('site_404');
  1673. $x = explode("/", $treq);
  1674. if (isset($x[0]) AND isset($x[1]))
  1675. {
  1676. $this->EE->output->out_type = '404';
  1677. $this->template_type = '404';
  1678. $template_group_404 = $this->EE->db->escape_str($x[0]);
  1679. $template_404 = $this->EE->db->escape_str($x[1]);
  1680. $this->EE->db->where(array(
  1681. 'template_groups.group_name' => $x[0],
  1682. 'templates.template_name' => $x[1]
  1683. ));
  1684. $show_404 = TRUE;
  1685. }
  1686. }
  1687. $this->EE->db->select('templates.*, template_groups.group_name')
  1688. ->from('templates')
  1689. ->join('template_groups', 'template_groups.group_id = templates.group_id')
  1690. ->where('template_groups.site_id', $site_id);
  1691. // If we're not dealing with a 404, what template and group do we need?
  1692. if ($show_404 === FALSE)
  1693. {
  1694. // Definitely need a template
  1695. if ($template != '')
  1696. {
  1697. $this->EE->db->where('templates.template_name', $template);
  1698. }
  1699. // But do we have a template group?
  1700. if ($show_default == TRUE)
  1701. {
  1702. $this->EE->db->where('template_groups.is_site_default', 'y');
  1703. }
  1704. else
  1705. {
  1706. $this->EE->db->where('template_groups.group_name', $template_group);
  1707. }
  1708. }
  1709. $query = $this->EE->db->get();
  1710. // Hmm, no template huh?
  1711. if ($query->num_rows() == 0)
  1712. {
  1713. // is there a file we can automatically create this template from?
  1714. if ($this->EE->config->item('save_tmpl_files') == 'y' && $this->EE->config->item('tmpl_file_basepath') != '')
  1715. {
  1716. $t_group = ($show_404) ? $template_group_404 : $template_group;
  1717. $t_template = ($show_404) ? $template_404 : $template;
  1718. if ($t_new_id = $this->_create_from_file($t_group, $t_template, TRUE))
  1719. {
  1720. // run the query again, as we just successfully created it
  1721. $query = $this->EE->db->select('templates.*, template_groups.group_name')
  1722. ->join('template_groups', 'template_groups.group_id = templates.group_id')
  1723. ->where('templates.template_id', $t_new_id)
  1724. ->get('templates');
  1725. }
  1726. else
  1727. {
  1728. $this->log_item("Template Not Found");
  1729. return FALSE;
  1730. }
  1731. }
  1732. else
  1733. {
  1734. $this->log_item("Template Not Found");
  1735. return FALSE;
  1736. }
  1737. }
  1738. $this->log_item("Template Found");
  1739. // HTTP Authentication
  1740. if ($query->row('enable_http_auth') == 'y')
  1741. {
  1742. $this->log_item("HTTP Authentication in Progress");
  1743. $this->EE->db->select('member_group');
  1744. $this->EE->db->where('template_id', $query->row('template_id'));
  1745. $results = $this->EE->db->get('template_no_access');
  1746. $not_allowed_groups = array();
  1747. if ($results->num_rows() > 0)
  1748. {
  1749. foreach($results->result_array() as $row)
  1750. {
  1751. $not_allowed_groups[] = $row['member_group'];
  1752. }
  1753. }
  1754. $this->EE->load->library('auth');
  1755. $this->EE->auth->authenticate_http_basic(
  1756. $not_allowed_groups,
  1757. $this->realm
  1758. );
  1759. }
  1760. // Is the current user allowed to view this template?
  1761. if ($query->row('enable_http_auth') != 'y' && $query->row('no_auth_bounce') != '')
  1762. {
  1763. $this->log_item("Determining Template Access Privileges");
  1764. $this->EE->db->select('COUNT(*) as count');
  1765. $this->EE->db->where('template_id', $query->row('template_id'));
  1766. $this->EE->db->where('member_group', $this->EE->session->userdata('group_id'));
  1767. $result = $this->EE->db->get('template_no_access');
  1768. if ($result->row('count') > 0)
  1769. {
  1770. if ($this->depth > 0)
  1771. {
  1772. return '';
  1773. }
  1774. $query = $this->EE->db->select('a.template_id, a.template_data,
  1775. a.template_name, a.template_type, a.edit_date,
  1776. a.save_template_file, a.cache, a.refresh, a.hits,
  1777. a.allow_php, a.php_parse_location, b.group_name')
  1778. ->from('templates a')
  1779. ->join('template_groups b', 'a.group_id = b.group_id')
  1780. ->where('template_id', $query->row('no_auth_bounce'))
  1781. ->get();
  1782. }
  1783. }
  1784. if ($query->num_rows() == 0)
  1785. {
  1786. return FALSE;
  1787. }
  1788. $row = $query->row_array();
  1789. // Is PHP allowed in this template?
  1790. if ($row['allow_php'] == 'y')
  1791. {
  1792. $this->parse_php = TRUE;
  1793. $this->php_parse_location = ($row['php_parse_location'] == 'i') ? 'input' : 'output';
  1794. }
  1795. // Increment hit counter
  1796. if (($this->hit_lock == FALSE OR $this->hit_lock_override == TRUE) &&
  1797. $this->EE->config->item('enable_hit_tracking') != 'n')
  1798. {
  1799. $this->template_hits = $row['hits'] + 1;
  1800. $this->hit_lock = TRUE;
  1801. $this->EE->db->update(
  1802. 'templates',
  1803. array('hits' => $this->template_hits),
  1804. array('template_id' => $row['template_id'])
  1805. );
  1806. }
  1807. // Set template edit date
  1808. $this->template_edit_date = $row['edit_date'];
  1809. // Set template type for our page headers
  1810. if ($this->template_type == '')
  1811. {
  1812. $this->template_type = $row['template_type'];
  1813. $this->EE->functions->template_type = $row['template_type'];
  1814. // If JS or CSS request, reset Tracker Cookie
  1815. if ($this->template_type == 'js' OR $this->template_type == 'css')
  1816. {
  1817. if (count($this->EE->session->tracker) <= 1)
  1818. {
  1819. $this->EE->session->tracker = array();
  1820. }
  1821. else
  1822. {
  1823. $removed = array_shift($this->EE->session->tracker);
  1824. }
  1825. $this->EE->functions->set_cookie('tracker', serialize($this->EE->session->tracker), '0');
  1826. }
  1827. }
  1828. if ($this->depth > 0)
  1829. {
  1830. $this->embed_type = $row['template_type'];
  1831. }
  1832. // Cache Override
  1833. // We can manually set certain things not to be cached, like the
  1834. // search template and the member directory after it's updated
  1835. // Note: I think search caching is OK.
  1836. // $cache_override = array('member' => 'U', 'search' => FALSE);
  1837. $cache_override = array('member');
  1838. foreach ($cache_override as $val)
  1839. {
  1840. if (strncmp($this->EE->uri->uri_string, "/{$val}/", strlen($val) + 2) == 0)
  1841. {
  1842. $row['cache'] = 'n';
  1843. }
  1844. }
  1845. // Retreive cache
  1846. $this->cache_hash = md5($site_id.'-'.$template_group.'-'.$template);
  1847. if ($row['cache'] == 'y')
  1848. {
  1849. $cache_contents = $this->fetch_cache_file($this->cache_hash, 'template', array('cache' => 'yes', 'refresh' => $row['refresh']));
  1850. if ($this->cache_status == 'CURRENT')
  1851. {
  1852. $row['template_data'] = $cache_contents;
  1853. // -------------------------------------------
  1854. // 'template_fetch_template' hook.
  1855. // - Access template data prior to template parsing
  1856. //
  1857. if ($this->EE->extensions->active_hook('template_fetch_template') === TRUE)
  1858. {
  1859. $this->EE->extensions->call('template_fetch_template', $row);
  1860. }
  1861. //
  1862. // -------------------------------------------
  1863. return $this->convert_xml_declaration($cache_contents);
  1864. }
  1865. }
  1866. // Retrieve template file if necessary
  1867. if ($row['save_template_file'] == 'y')
  1868. {
  1869. $site_switch = FALSE;
  1870. if ($this->EE->config->item('site_id') != $site_id)
  1871. {
  1872. $site_switch = $this->EE->config->config;
  1873. if (isset($this->site_prefs_cache[$site_id]))
  1874. {
  1875. $this->EE->config->config = $this->site_prefs_cache[$site_id];
  1876. }
  1877. else
  1878. {
  1879. $this->EE->config->site_prefs('', $site_id);
  1880. $this->site_prefs_cache[$site_id] = $this->EE->config->config;
  1881. }
  1882. }
  1883. if ($this->EE->config->item('save_tmpl_files') == 'y'
  1884. AND $this->EE->config->item('tmpl_file_basepath') != '')
  1885. {
  1886. $this->log_item("Retrieving Template from File");
  1887. $this->EE->load->library('api');
  1888. $this->EE->api->instantiate('template_structure');
  1889. $basepath = rtrim($this->EE->config->item('tmpl_file_basepath'), '/').'/';
  1890. $basepath .= $this->EE->config->item('site_short_name').'/'
  1891. .$row['group_name'].'.group/'.$row['template_name']
  1892. .$this->EE->api_template_structure->file_extensions($row['template_type']);
  1893. if (file_exists($basepath))
  1894. {
  1895. $row['template_data'] = file_get_contents($basepath);
  1896. }
  1897. }
  1898. if ($site_switch !== FALSE)
  1899. {
  1900. $this->EE->config->config = $site_switch;
  1901. }
  1902. }
  1903. // standardize newlines
  1904. $row['template_data'] = str_replace(array("\r\n", "\r"), "\n", $row['template_data']);
  1905. // -------------------------------------------
  1906. // 'template_fetch_template' hook.
  1907. // - Access template data prior to template parsing
  1908. //
  1909. if ($this->EE->extensions->active_hook('template_fetch_template') === TRUE)
  1910. {
  1911. $this->EE->extensions->call('template_fetch_template', $row);
  1912. }
  1913. //
  1914. // -------------------------------------------
  1915. return $this->convert_xml_declaration($this->remove_ee_comments($row['template_data']));
  1916. }
  1917. // --------------------------------------------------------------------
  1918. /**
  1919. * Create From File
  1920. *
  1921. * Attempts to create a template group / template from a file
  1922. *
  1923. * @param string template group name
  1924. * @param string template name
  1925. * @return bool
  1926. */
  1927. function _create_from_file($template_group, $template, $db_check = FALSE)
  1928. {
  1929. if ($this->EE->config->item('save_tmpl_files') != 'y' OR $this->EE->config->item('tmpl_file_basepath') == '')
  1930. {
  1931. return FALSE;
  1932. }
  1933. $template = ($template == '') ? 'index' : $template;
  1934. // Template Groups and Templates are limited to 50 characters in db
  1935. if (strlen($template) > 50 OR strlen($template_group) > 50)
  1936. {
  1937. return FALSE;
  1938. }
  1939. if ($db_check)
  1940. {
  1941. $this->EE->db->from('templates');
  1942. $this->EE->db->join('template_groups', 'templates.group_id = template_groups.group_id', 'left');
  1943. $this->EE->db->where('group_name', $template_group);
  1944. $this->EE->db->where('template_name', $template);
  1945. $valid_count = $this->EE->db->count_all_results();
  1946. // We found a valid template! Er- could this loop? Better just return FALSE
  1947. if ($valid_count > 0)
  1948. {
  1949. return FALSE;
  1950. }
  1951. }
  1952. $this->EE->load->library('api');
  1953. $this->EE->api->instantiate('template_structure');
  1954. $this->EE->load->model('template_model');
  1955. $basepath = $this->EE->config->slash_item('tmpl_file_basepath').$this->EE->config->item('site_short_name').'/'.$template_group.'.group';
  1956. if ( ! is_dir($basepath))
  1957. {
  1958. return FALSE;
  1959. }
  1960. $filename = FALSE;
  1961. // Note- we should add the extension before checking.
  1962. foreach ($this->EE->api_template_structure->file_extensions as $type => $temp_ext)
  1963. {
  1964. if (file_exists($basepath.'/'.$template.$temp_ext))
  1965. {
  1966. // found it with an extension
  1967. $filename = $template.$temp_ext;
  1968. $ext = $temp_ext;
  1969. $template_type = $type;
  1970. break;
  1971. }
  1972. }
  1973. // did we find anything?
  1974. if ($filename === FALSE)
  1975. {
  1976. return FALSE;
  1977. }
  1978. if ( ! $this->EE->api->is_url_safe($template))
  1979. {
  1980. // bail out
  1981. return FALSE;
  1982. }
  1983. $this->EE->db->select('group_id');
  1984. $this->EE->db->where('group_name', $template_group);
  1985. $this->EE->db->where('site_id', $this->EE->config->item('site_id'));
  1986. $query = $this->EE->db->get('template_groups');
  1987. if ($query->num_rows() != 0)
  1988. {
  1989. $group_id = $query->row('group_id');
  1990. }
  1991. else
  1992. {
  1993. // we have a new group to create!
  1994. if ( ! $this->EE->api->is_url_safe($template_group))
  1995. {
  1996. // bail out
  1997. return FALSE;
  1998. }
  1999. if (in_array($template_group, $this->EE->api_template_structure->reserved_names))
  2000. {
  2001. // bail out
  2002. return FALSE;
  2003. }
  2004. $data = array(
  2005. 'group_name' => $template_group,
  2006. 'group_order' => $this->EE->db->count_all('template_groups') + 1,
  2007. 'is_site_default' => 'n',
  2008. 'site_id' => $this->EE->config->item('site_id')
  2009. );
  2010. $group_id = $this->EE->template_model->create_group($data);
  2011. }
  2012. $data = array(
  2013. 'group_id' => $group_id,
  2014. 'template_name' => $template,
  2015. 'template_type' => $template_type,
  2016. 'template_data' => file_get_contents($basepath.'/'.$filename),
  2017. 'edit_date' => $this->EE->localize->now,
  2018. 'save_template_file' => 'y',
  2019. 'last_author_id' => '1', // assume a super admin
  2020. 'site_id' => $this->EE->config->item('site_id')
  2021. );
  2022. $template_id = $this->EE->template_model->create_template($data);
  2023. // Clear db cache or it will create a new template record each page load!
  2024. $this->EE->functions->clear_caching('db');
  2025. return $template_id;
  2026. }
  2027. // --------------------------------------------------------------------
  2028. /**
  2029. * No Results
  2030. *
  2031. * If a tag/class has no results to show, it can call this method. Any no_results variable in
  2032. * the tag will be followed. May be 404 page, content, or even a redirect.
  2033. *
  2034. * @return void
  2035. */
  2036. public function no_results()
  2037. {
  2038. if ( ! preg_match("/".LD."redirect\s*=\s*(\042|\047)([^\\1]*?)\\1".RD."/si", $this->no_results, $match))
  2039. {
  2040. $this->log_item("Returning No Results Content");
  2041. return $this->no_results;
  2042. }
  2043. else
  2044. {
  2045. $this->log_item("Processing No Results Redirect");
  2046. if ($match[2] == "404")
  2047. {
  2048. $template = explode('/', $this->EE->config->item('site_404'));
  2049. if (isset($template[1]))
  2050. {
  2051. $this->log_item('Processing "'.$template[0].'/'.$template[1].'" Template as 404 Page');
  2052. $this->EE->output->out_type = "404";
  2053. $this->template_type = "404";
  2054. $this->fetch_and_parse($template[0], $template[1]);
  2055. $this->cease_processing = TRUE;
  2056. }
  2057. else
  2058. {
  2059. $this->log_item('404 redirect requested, but no 404 page is specified in the Global Template Preferences');
  2060. return $this->no_results;
  2061. }
  2062. }
  2063. else
  2064. {
  2065. return $this->EE->functions->redirect($this->EE->functions->create_url($this->EE->functions->extract_path("=".$match[2])));
  2066. }
  2067. }
  2068. }
  2069. // --------------------------------------------------------------------
  2070. /**
  2071. * Make XML Declaration Safe
  2072. *
  2073. * Takes any XML declaration in the string and makes sure it is not interpreted as PHP during
  2074. * the processing of the template.
  2075. *
  2076. * This fixes a parsing error when PHP is used in RSS templates
  2077. *
  2078. * @param string
  2079. * @return string
  2080. */
  2081. public function convert_xml_declaration($str)
  2082. {
  2083. if (strpos($str, '<?xml') === FALSE) return $str;
  2084. return preg_replace("/\<\?xml(.+?)\?\>/", "<XXML\\1/XXML>", $str);
  2085. }
  2086. // --------------------------------------------------------------------
  2087. /**
  2088. * Restore XML Declaration
  2089. *
  2090. * @param string
  2091. * @return string
  2092. */
  2093. public function restore_xml_declaration($str)
  2094. {
  2095. if (strpos($str, '<XXML') === FALSE) return $str;
  2096. return preg_replace("/\<XXML(.+?)\/XXML\>/", "<?xml\\1?".">", $str); // <?
  2097. }
  2098. // --------------------------------------------------------------------
  2099. /**
  2100. * Remove all EE Code Comment Strings
  2101. *
  2102. * EE Templates have a special EE Code Comments for site designer notes and are removed prior
  2103. * to Template processing.
  2104. *
  2105. * @param string
  2106. * @return string
  2107. */
  2108. public function remove_ee_comments($str)
  2109. {
  2110. if (strpos($str, '{!--') === FALSE) return $str;
  2111. return preg_replace("/\{!--.*?--\}/s", '', $str);
  2112. }
  2113. // --------------------------------------------------------------------
  2114. /**
  2115. * Fetch Add-ons
  2116. *
  2117. * Gathers available modules and plugins
  2118. *
  2119. * @return void
  2120. */
  2121. public function fetch_addons()
  2122. {
  2123. $this->EE->load->helper('file');
  2124. $this->EE->load->helper('directory');
  2125. $ext_len = strlen('.php');
  2126. // first get first party modules
  2127. if (($map = directory_map(PATH_MOD, TRUE)) !== FALSE)
  2128. {
  2129. foreach ($map as $file)
  2130. {
  2131. if (strpos($file, '.') === FALSE)
  2132. {
  2133. if (IS_CORE && in_array($file, $this->EE->core->standard_modules))
  2134. {
  2135. continue;
  2136. }
  2137. $this->modules[] = $file;
  2138. }
  2139. }
  2140. }
  2141. // now first party plugins
  2142. if (($map = directory_map(PATH_PI, TRUE)) !== FALSE)
  2143. {
  2144. foreach ($map as $file)
  2145. {
  2146. if (strncasecmp($file, 'pi.', 3) == 0 &&
  2147. substr($file, -$ext_len) == '.php' &&
  2148. strlen($file) > strlen('pi..php') &&
  2149. in_array(substr($file, 3, -$ext_len), $this->EE->core->native_plugins))
  2150. {
  2151. $this->plugins[] = substr($file, 3, -$ext_len);
  2152. }
  2153. }
  2154. }
  2155. // now third party add-ons, which are arranged in "packages"
  2156. // only catch files that match the package name, as other files are merely assets
  2157. if (($map = directory_map(PATH_THIRD, 2)) !== FALSE)
  2158. {
  2159. foreach ($map as $pkg_name => $files)
  2160. {
  2161. if ( ! is_array($files))
  2162. {
  2163. $files = array($files);
  2164. }
  2165. foreach ($files as $file)
  2166. {
  2167. if (is_array($file))
  2168. {
  2169. // we're only interested in the top level files for the addon
  2170. continue;
  2171. }
  2172. // we gots a module?
  2173. if (strncasecmp($file, 'mod.', 4) == 0 &&
  2174. substr($file, -$ext_len) == '.php' &&
  2175. strlen($file) > strlen('mod..php'))
  2176. {
  2177. $file = substr($file, 4, -$ext_len);
  2178. if ($file == $pkg_name)
  2179. {
  2180. $this->modules[] = $file;
  2181. }
  2182. }
  2183. // how abouts a plugin?
  2184. elseif (strncasecmp($file, 'pi.', 3) == 0 &&
  2185. substr($file, -$ext_len) == '.php' &&
  2186. strlen($file) > strlen('pi..php'))
  2187. {
  2188. $file = substr($file, 3, -$ext_len);
  2189. if ($file == $pkg_name)
  2190. {
  2191. $this->plugins[] = $file;
  2192. }
  2193. }
  2194. }
  2195. }
  2196. }
  2197. }
  2198. // --------------------------------------------------------------------
  2199. /**
  2200. * Parse Globals
  2201. *
  2202. * The syntax is generally: {global:variable_name}
  2203. *
  2204. * Parses global variables like the currently logged in member's information, system variables,
  2205. * paths, action IDs, CAPTCHAs. Typically stuff that should only be done after caching to prevent
  2206. * any manner of changes in the system or who is viewing the page to affect the display.
  2207. *
  2208. * @param string
  2209. * @return string
  2210. */
  2211. public function parse_globals($str)
  2212. {
  2213. $charset = '';
  2214. $lang = '';
  2215. $user_vars = array(
  2216. 'member_id', 'group_id', 'group_description',
  2217. 'group_title', 'member_group', 'username', 'screen_name',
  2218. 'email', 'ip_address', 'location', 'total_entries',
  2219. 'total_comments', 'private_messages', 'total_forum_posts',
  2220. 'total_forum_topics', 'total_forum_replies'
  2221. );
  2222. // Redirect - if we have one of these, no need to go further
  2223. if (strpos($str, LD.'redirect') !== FALSE)
  2224. {
  2225. if (preg_match("/".LD."redirect\s*=\s*(\042|\047)([^\\1]*?)\\1".RD."/si", $str, $match))
  2226. {
  2227. if ($match['2'] == "404")
  2228. {
  2229. $template = explode('/', $this->EE->config->item('site_404'));
  2230. if (isset($template['1']))
  2231. {
  2232. $this->log_item('Processing "'.$template['0'].'/'.$template['1'].'" Template as 404 Page');
  2233. $this->template_type = "404";
  2234. $this->fetch_and_parse($template['0'], $template['1']);
  2235. $this->cease_processing = TRUE;
  2236. // the resulting template will not have globals parsed unless we do this
  2237. return $this->parse_globals($this->final_template);
  2238. }
  2239. else
  2240. {
  2241. $this->log_item('404 redirect requested, but no 404 page is specified in the Global Template Preferences');
  2242. return $this->_404();
  2243. }
  2244. }
  2245. else
  2246. {
  2247. // Functions::redirect() exit;s on its own
  2248. $this->EE->functions->redirect($this->EE->functions->create_url($this->EE->functions->extract_path("=".$match['2'])));
  2249. }
  2250. }
  2251. }
  2252. // Restore XML declaration if it was encoded
  2253. $str = $this->restore_xml_declaration($str);
  2254. // Parse User-defined Global Variables first so that
  2255. // they can use other standard globals
  2256. $this->EE->db->select('variable_name, variable_data');
  2257. $this->EE->db->where('site_id', $this->EE->config->item('site_id'));
  2258. $query = $this->EE->db->get('global_variables');
  2259. if ($query->num_rows() > 0)
  2260. {
  2261. foreach ($query->result_array() as $row)
  2262. {
  2263. $str = str_replace(LD.$row['variable_name'].RD, $row['variable_data'], $str);
  2264. }
  2265. }
  2266. // {hits}
  2267. $str = str_replace(LD.'hits'.RD, $this->template_hits, $str);
  2268. // {ip_address} and {ip_hostname}
  2269. $str = str_replace(LD.'ip_address'.RD, $this->EE->input->ip_address(), $str);
  2270. // Turns out gethostbyaddr() is WAY SLOW on many systems so I'm killing it.
  2271. // $str = str_replace(LD.'ip_hostname'.RD, @gethostbyaddr($this->EE->input->ip_address()), $str);
  2272. $str = str_replace(LD.'ip_hostname'.RD, $this->EE->input->ip_address(), $str);
  2273. // {homepage}
  2274. $str = str_replace(LD.'homepage'.RD, $this->EE->functions->fetch_site_index(), $str);
  2275. // {cp_url}
  2276. if ($this->EE->session->access_cp === TRUE)
  2277. {
  2278. $str = str_replace(LD.'cp_url'.RD, $this->EE->config->item('cp_url'), $str);
  2279. }
  2280. else
  2281. {
  2282. $str = str_replace(LD.'cp_url'.RD, '', $str);
  2283. }
  2284. // {site_name} {site_url} {site_index} {webmaster_email}
  2285. $str = str_replace(LD.'site_name'.RD, stripslashes($this->EE->config->item('site_name')), $str);
  2286. $str = str_replace(LD.'site_url'.RD, stripslashes($this->EE->config->item('site_url')), $str);
  2287. $str = str_replace(LD.'site_index'.RD, stripslashes($this->EE->config->item('site_index')), $str);
  2288. $str = str_replace(LD.'webmaster_email'.RD, stripslashes($this->EE->config->item('webmaster_email')), $str);
  2289. // Stylesheet variable: {stylesheet=group/template}
  2290. if (strpos($str, 'stylesheet=') !== FALSE && preg_match_all("/".LD."\s*stylesheet=[\042\047]?(.*?)[\042\047]?".RD."/", $str, $css_matches))
  2291. {
  2292. $css_versions = array();
  2293. if ($this->EE->config->item('send_headers') == 'y')
  2294. {
  2295. $sql = "SELECT t.template_name, tg.group_name, t.edit_date, t.save_template_file FROM exp_templates t, exp_template_groups tg
  2296. WHERE t.group_id = tg.group_id
  2297. AND t.template_type = 'css'
  2298. AND t.site_id = '".$this->EE->db->escape_str($this->EE->config->item('site_id'))."'";
  2299. foreach($css_matches[1] as $css_match)
  2300. {
  2301. $ex = explode('/', $css_match, 2);
  2302. if (isset($ex[1]))
  2303. {
  2304. $css_parts[] = "(t.template_name = '".$this->EE->db->escape_str($ex[1])."' AND tg.group_name = '".$this->EE->db->escape_str($ex[0])."')";
  2305. }
  2306. }
  2307. $css_query = ( ! isset($css_parts)) ? $this->EE->db->query($sql) : $this->EE->db->query($sql.' AND ('.implode(' OR ', $css_parts) .')');
  2308. if ($css_query->num_rows() > 0)
  2309. {
  2310. foreach($css_query->result_array() as $row)
  2311. {
  2312. $css_versions[$row['group_name'].'/'.$row['template_name']] = $row['edit_date'];
  2313. if ($this->EE->config->item('save_tmpl_files') == 'y' AND $this->EE->config->item('tmpl_file_basepath') != '' AND $row['save_template_file'] == 'y')
  2314. {
  2315. $basepath = $this->EE->config->slash_item('tmpl_file_basepath').$this->EE->config->item('site_short_name').'/';
  2316. $basepath .= $row['group_name'].'.group/'.$row['template_name'].'.css';
  2317. if (is_file($basepath))
  2318. {
  2319. $css_versions[$row['group_name'].'/'.$row['template_name']] = filemtime($basepath);
  2320. }
  2321. }
  2322. }
  2323. }
  2324. }
  2325. $s_index = $this->EE->functions->fetch_site_index();
  2326. if ( ! QUERY_MARKER && substr($s_index, -1) != '?')
  2327. {
  2328. $s_index .= '&';
  2329. }
  2330. for($ci=0, $cs=count($css_matches[0]); $ci < $cs; ++$ci)
  2331. {
  2332. $str = str_replace($css_matches[0][$ci], $s_index.QUERY_MARKER.'css='.$css_matches[1][$ci].(isset($css_versions[$css_matches[1][$ci]]) ? '.v.'.$css_versions[$css_matches[1][$ci]] : ''), $str);
  2333. }
  2334. unset($css_matches);
  2335. unset($css_versions);
  2336. }
  2337. // Email encode: {encode="you@yoursite.com" title="click Me"}
  2338. if (strpos($str, LD.'encode=') !== FALSE)
  2339. {
  2340. if ($this->encode_email == TRUE)
  2341. {
  2342. if (preg_match_all("/".LD."encode=(.+?)".RD."/i", $str, $matches))
  2343. {
  2344. for ($j = 0; $j < count($matches[0]); $j++)
  2345. {
  2346. $str = preg_replace('/'.preg_quote($matches['0'][$j], '/').'/', $this->EE->functions->encode_email($matches[1][$j]), $str, 1);
  2347. }
  2348. }
  2349. }
  2350. else
  2351. {
  2352. /* -------------------------------------------
  2353. /* Hidden Configuration Variable
  2354. /* - encode_removed_text => Text to display if there is an {encode=""}
  2355. tag but emails are not to be encoded
  2356. /* -------------------------------------------*/
  2357. $str = preg_replace("/".LD."\s*encode=(.+?)".RD."/",
  2358. ($this->EE->config->item('encode_removed_text') !== FALSE) ? $this->EE->config->item('encode_removed_text') : '',
  2359. $str);
  2360. }
  2361. }
  2362. // Debug mode: {debug_mode}
  2363. $str = str_replace(LD.'debug_mode'.RD, ($this->EE->config->item('debug') > 0) ? $this->EE->lang->line('on') : $this->EE->lang->line('off'), $str);
  2364. // GZip mode: {gzip_mode}
  2365. $str = str_replace(LD.'gzip_mode'.RD, ($this->EE->config->item('gzip_output') == 'y') ? $this->EE->lang->line('enabled') : $this->EE->lang->line('disabled'), $str);
  2366. // App version: {version}
  2367. $str = str_replace(LD.'app_version'.RD, APP_VER, $str);
  2368. $str = str_replace(LD.'version'.RD, APP_VER, $str);
  2369. // App version: {build}
  2370. $str = str_replace(LD.'app_build'.RD, APP_BUILD, $str);
  2371. $str = str_replace(LD.'build'.RD, APP_BUILD, $str);
  2372. // {charset} and {lang}
  2373. $str = str_replace(LD.'charset'.RD, $this->EE->config->item('output_charset'), $str);
  2374. $str = str_replace(LD.'lang'.RD, $this->EE->config->item('xml_lang'), $str);
  2375. // {doc_url}
  2376. $str = str_replace(LD.'doc_url'.RD, $this->EE->config->item('doc_url'), $str);
  2377. // {theme_folder_url}
  2378. $str = str_replace(LD.'theme_folder_url'.RD,
  2379. $this->EE->config->item('theme_folder_url'), $str);
  2380. // {member_profile_link}
  2381. if ($this->EE->session->userdata('member_id') != 0)
  2382. {
  2383. $name = ($this->EE->session->userdata['screen_name'] == '') ? $this->EE->session->userdata['username'] : $this->EE->session->userdata['screen_name'];
  2384. $path = "<a href='".$this->EE->functions->create_url('/member/'.$this->EE->session->userdata('member_id'))."'>".$name."</a>";
  2385. $str = str_replace(LD.'member_profile_link'.RD, $path, $str);
  2386. }
  2387. else
  2388. {
  2389. $str = str_replace(LD.'member_profile_link'.RD, '', $str);
  2390. }
  2391. // Fetch CAPTCHA
  2392. if (strpos($str, "{captcha}") !== FALSE)
  2393. {
  2394. $str = str_replace("{captcha}", $this->EE->functions->create_captcha(), $str);
  2395. }
  2396. // Add security hashes to forms
  2397. // We do this here to keep the security hashes from being cached
  2398. $str = $this->EE->functions->add_form_security_hash($str);
  2399. // Parse non-cachable variables
  2400. $this->EE->session->userdata['member_group'] = $this->EE->session->userdata['group_id'];
  2401. foreach ($user_vars as $val)
  2402. {
  2403. $replace = (isset($this->EE->session->userdata[$val]) && strval($this->EE->session->userdata[$val]) != '') ?
  2404. $this->EE->session->userdata[$val] : '';
  2405. $str = str_replace(LD.$val.RD, $replace, $str);
  2406. $str = str_replace('{out_'.$val.'}', $replace, $str);
  2407. $str = str_replace('{global->'.$val.'}', $replace, $str);
  2408. $str = str_replace('{logged_in_'.$val.'}', $replace, $str);
  2409. }
  2410. // Path variable: {path=group/template}
  2411. if (strpos($str, 'path=') !== FALSE)
  2412. {
  2413. $str = preg_replace_callback("/".LD."\s*path=(.*?)".RD."/", array(&$this->EE->functions, 'create_url'), $str);
  2414. }
  2415. // {current_url}
  2416. $str = str_replace(LD.'current_url'.RD, $this->EE->functions->fetch_current_uri(), $str);
  2417. // {current_path}
  2418. $str = str_replace(LD.'current_path'.RD, (($this->EE->uri->uri_string) ? $this->EE->uri->uri_string : '/'), $str);
  2419. // Add Action IDs form forms and links
  2420. $str = $this->EE->functions->insert_action_ids($str);
  2421. // and once again just in case global vars introduce EE comments
  2422. return $this->remove_ee_comments($str);
  2423. }
  2424. // --------------------------------------------------------------------
  2425. /**
  2426. * Parse Uncachaable Forms
  2427. *
  2428. * Parses and Process forms that cannot be stored in a cache file. Probably one of the most
  2429. * tedious parts of EE's Template parser for a while there in 2004...
  2430. *
  2431. * @param string
  2432. * @return string
  2433. */
  2434. public function parse_nocache($str)
  2435. {
  2436. if (strpos($str, '{NOCACHE') === FALSE)
  2437. {
  2438. return $str;
  2439. }
  2440. // Generate Comment Form if needed
  2441. // In order for the comment form not to cache the "save info"
  2442. // data we need to generate dynamically if necessary
  2443. if (preg_match_all("#{NOCACHE_(\S+)_FORM=\"(.*?)\"}(.+?){/NOCACHE_FORM}#s", $str, $match))
  2444. {
  2445. for($i=0, $s=count($match[0]); $i < $s; $i++)
  2446. {
  2447. $class = $this->EE->security->sanitize_filename(strtolower($match[1][$i]));
  2448. if ( ! class_exists($class))
  2449. {
  2450. require PATH_MOD.$class.'/mod.'.$class.'.php';
  2451. }
  2452. $this->tagdata = $match[3][$i];
  2453. $vars = $this->EE->functions->assign_variables($match[3][$i], '/');
  2454. $this->var_single = $vars['var_single'];
  2455. $this->var_pair = $vars['var_pair'];
  2456. $this->tagparams = $this->EE->functions->assign_parameters($match[2][$i]);
  2457. $this->var_cond = $this->EE->functions->assign_conditional_variables($match[3][$i], '/', LD, RD);
  2458. // Assign sites for the tag
  2459. $this->_fetch_site_ids();
  2460. // Assign Form ID/Classes
  2461. if (isset($this->tag_data[$i]))
  2462. {
  2463. $this->tag_data[$i] = $this->_assign_form_params($this->tag_data[$i]);
  2464. }
  2465. if ($class == 'comment')
  2466. {
  2467. $str = str_replace($match[0][$i], Comment::form(TRUE, $this->EE->functions->cached_captcha), $str);
  2468. }
  2469. $str = str_replace('{PREVIEW_TEMPLATE}', $match[2][$i], $str);
  2470. }
  2471. }
  2472. // Generate Stand-alone Publish form
  2473. if (preg_match_all("#{{NOCACHE_CHANNEL_FORM(.*?)}}(.+?){{/NOCACHE_FORM}}#s", $str, $match))
  2474. {
  2475. for($i=0, $s=count($match[0]); $i < $s; $i++)
  2476. {
  2477. if ( ! class_exists('Channel'))
  2478. {
  2479. require PATH_MOD.'channel/mod.channel.php';
  2480. }
  2481. $this->tagdata = $match[2][$i];
  2482. $vars = $this->EE->functions->assign_variables($match[2][$i], '/');
  2483. $this->var_single = $vars['var_single'];
  2484. $this->var_pair = $vars['var_pair'];
  2485. $this->tagparams = $this->EE->functions->assign_parameters($match[1][$i]);
  2486. // Assign sites for the tag
  2487. $this->_fetch_site_ids();
  2488. // Assign Form ID/Classes
  2489. if (isset($this->tag_data[$i]))
  2490. {
  2491. $this->tag_data[$i] = $this->_assign_form_params($this->tag_data[$i]);
  2492. }
  2493. $XX = new Channel();
  2494. $str = str_replace($match[0][$i], $XX->entry_form(TRUE, $this->EE->functions->cached_captcha), $str);
  2495. $str = str_replace('{PREVIEW_TEMPLATE}', (isset($_POST['PRV'])) ? $_POST['PRV'] : $this->fetch_param('preview'), $str);
  2496. }
  2497. }
  2498. return $str;
  2499. }
  2500. // --------------------------------------------------------------------
  2501. /**
  2502. * Process Advanced Conditionals
  2503. *
  2504. * The syntax is generally: {if whatever = ""}Dude{if:elseif something != ""}Yo{if:else}
  2505. *
  2506. * The final processing of Advanced Conditionals. Takes all of the member variables and uncachable
  2507. * variables and preps the conditionals with them. Then, it converts the conditionals to PHP so that
  2508. * PHP can do all of the really heavy lifting for us.
  2509. *
  2510. * @param string
  2511. * @return string
  2512. */
  2513. public function advanced_conditionals($str)
  2514. {
  2515. if (stristr($str, LD.'if') === FALSE)
  2516. {
  2517. return $str;
  2518. }
  2519. /* ---------------------------------
  2520. /* Hidden Configuration Variables
  2521. /* - protect_javascript => Prevents advanced conditional parser from processing anything in <script> tags
  2522. /* ---------------------------------*/
  2523. if ($this->EE->config->item('protect_javascript') == 'n')
  2524. {
  2525. $this->protect_javascript = FALSE;
  2526. }
  2527. $user_vars = array('member_id', 'group_id', 'group_description', 'group_title', 'username', 'screen_name',
  2528. 'email', 'ip_address', 'location', 'total_entries',
  2529. 'total_comments', 'private_messages', 'total_forum_posts', 'total_forum_topics', 'total_forum_replies');
  2530. for($i=0,$s=count($user_vars), $data = array(); $i < $s; ++$i)
  2531. {
  2532. $data[$user_vars[$i]] = $this->EE->session->userdata[$user_vars[$i]];
  2533. $data['logged_in_'.$user_vars[$i]] = $this->EE->session->userdata[$user_vars[$i]];
  2534. }
  2535. // Define an alternate variable for {group_id} since some tags use
  2536. // it natively, causing it to be unavailable as a global
  2537. $data['member_group'] = $data['logged_in_member_group'] = $this->EE->session->userdata['group_id'];
  2538. // Logged in and logged out variables
  2539. $data['logged_in'] = ($this->EE->session->userdata['member_id'] == 0) ? 'FALSE' : 'TRUE';
  2540. $data['logged_out'] = ($this->EE->session->userdata['member_id'] != 0) ? 'FALSE' : 'TRUE';
  2541. // current time
  2542. $data['current_time'] = $this->EE->localize->now;
  2543. // Member Group in_group('1') function, Super Secret! Shhhhh!
  2544. if (preg_match_all("/in_group\(([^\)]+)\)/", $str, $matches))
  2545. {
  2546. $groups = (is_array($this->EE->session->userdata['group_id'])) ? $this->EE->session->userdata['group_id'] : array($this->EE->session->userdata['group_id']);
  2547. for($i=0, $s=count($matches[0]); $i < $s; ++$i)
  2548. {
  2549. $check = explode('|', str_replace(array('"', "'"), '', $matches[1][$i]));
  2550. $str = str_replace($matches[0][$i], (count(array_intersect($check, $groups)) > 0) ? 'TRUE' : 'FALSE', $str);
  2551. }
  2552. }
  2553. // Final Prep, Safety On
  2554. $str = $this->EE->functions->prep_conditionals($str, array_merge($this->segment_vars, $this->embed_vars, $this->EE->config->_global_vars, $data), 'y');
  2555. // Protect Already Existing Unparsed PHP
  2556. $this->EE->load->helper('string');
  2557. $opener = unique_marker('tmpl_php_open');
  2558. $closer = unique_marker('tmpl_php_close');
  2559. $str = str_replace(array('<?', '?'.'>'),
  2560. array($opener.'?', '?'.$closer),
  2561. $str);
  2562. // Protect <script> tags
  2563. $protected = array();
  2564. $front_protect = unique_marker('tmpl_script_open');
  2565. $back_protect = unique_marker('tmpl_script_close');
  2566. if ($this->protect_javascript !== FALSE &&
  2567. stristr($str, '<script') &&
  2568. preg_match_all("/<script.*?".">.*?<\/script>/is", $str, $matches))
  2569. {
  2570. for($i=0, $s=count($matches[0]); $i < $s; ++$i)
  2571. {
  2572. $protected[$front_protect.$i.$back_protect] = $matches[0][$i];
  2573. }
  2574. $str = str_replace(array_values($protected), array_keys($protected), $str);
  2575. }
  2576. // Convert EE Conditionals to PHP
  2577. $str = str_replace(array(LD.'/if'.RD, LD.'if:else'.RD), array('<?php endif; ?'.'>','<?php else : ?'.'>'), $str);
  2578. if (strpos($str, LD.'if') !== FALSE)
  2579. {
  2580. $str = preg_replace("/".preg_quote(LD)."((if:(else))*if)\s+(.*?)".preg_quote(RD)."/s", '<?php \\3if(\\4) : ?'.'>', $str);
  2581. }
  2582. $str = $this->parse_template_php($str);
  2583. // Unprotect <script> tags
  2584. if (count($protected) > 0)
  2585. {
  2586. $str = str_replace(array_keys($protected), array_values($protected), $str);
  2587. }
  2588. // Unprotect Already Existing Unparsed PHP
  2589. $str = str_replace(array($opener.'?', '?'.$closer),
  2590. array('<'.'?', '?'.'>'),
  2591. $str);
  2592. return $str;
  2593. }
  2594. // --------------------------------------------------------------------
  2595. /**
  2596. * Parse Simple Segment Conditionals
  2597. *
  2598. * Back before Advanced Conditionals many people put embedded templates and preload_replace=""
  2599. * variables in segment conditionals to control what subpages were included and the values of
  2600. * many tag parameters. Since Advanced Conditionals are processed far later in Template parsing
  2601. * than that usage was required, we kept some separate processing in existence for the processing
  2602. * of "simple" segment conditionals. Only one variable, no elseif or else.
  2603. *
  2604. * @param string
  2605. * @return string
  2606. */
  2607. public function parse_simple_segment_conditionals($str)
  2608. {
  2609. if ( ! preg_match("/".LD."if\s+segment_.+".RD."/", $str))
  2610. {
  2611. return $str;
  2612. }
  2613. $this->var_cond = $this->EE->functions->assign_conditional_variables($str);
  2614. foreach ($this->var_cond as $val)
  2615. {
  2616. // Make sure this is for a segment conditional
  2617. // And that this is not an advanced conditional
  2618. if ( ! preg_match('/^segment_\d+$/i', $val['3']) OR
  2619. strpos($val[2], 'if:else') !== FALSE OR
  2620. strpos($val[0], 'if:else') !== FALSE OR
  2621. count(preg_split("/(\!=|==|<=|>=|<>|<|>|AND|XOR|OR|&&|\|\|)/", $val[0])) > 2)
  2622. {
  2623. continue;
  2624. }
  2625. $cond = $this->EE->functions->prep_conditional($val[0]);
  2626. $lcond = substr($cond, 0, strpos($cond, ' '));
  2627. $rcond = substr($cond, strpos($cond, ' '));
  2628. if (strpos($rcond, '"') == FALSE && strpos($rcond, "'") === FALSE) continue;
  2629. $n = substr($val[3], 8);
  2630. $temp = (isset($this->EE->uri->segments[$n])) ? $this->EE->uri->segments[$n] : '';
  2631. $lcond = str_replace($val[3], "\$temp", $lcond);
  2632. if (stristr($rcond, '\|') !== FALSE OR stristr($rcond, '&') !== FALSE)
  2633. {
  2634. $rcond = trim($rcond);
  2635. $operator = trim(substr($rcond, 0, strpos($rcond, ' ')));
  2636. $check = trim(substr($rcond, strpos($rcond, ' ')));
  2637. $quote = substr($check, 0, 1);
  2638. if (stristr($rcond, '\|') !== FALSE)
  2639. {
  2640. $array = explode('\|', str_replace($quote, '', $check));
  2641. $break_operator = ' OR ';
  2642. }
  2643. else
  2644. {
  2645. $array = explode('&', str_replace($quote, '', $check));
  2646. $break_operator = ' && ';
  2647. }
  2648. $rcond = $operator.' '.$quote;
  2649. $rcond .= implode($quote.$break_operator.$lcond.' '.$operator.' '.$quote, $array).$quote;
  2650. }
  2651. $cond = $lcond.' '.$rcond;
  2652. $cond = str_replace("\|", "|", $cond);
  2653. eval("\$result = (".$cond.");");
  2654. if ($result)
  2655. {
  2656. $str = str_replace($val[1], $val[2], $str);
  2657. }
  2658. else
  2659. {
  2660. $str = str_replace($val[1], '', $str);
  2661. }
  2662. }
  2663. return $str;
  2664. }
  2665. // --------------------------------------------------------------------
  2666. /**
  2667. * Parse Simple Conditionals
  2668. *
  2669. * Used for processing global_vars and embed and segment conditionals that need to occur far
  2670. * sooner than Advanced Conditionals. These conditionals are only one variable and have no
  2671. * {if:elseif} or {if:else} control structures.
  2672. *
  2673. * @access public
  2674. * @param string
  2675. * @param array
  2676. * @return string
  2677. */
  2678. public function simple_conditionals($str, $vars = array())
  2679. {
  2680. if (count($vars) == 0 OR ! stristr($str, LD.'if'))
  2681. {
  2682. return $str;
  2683. }
  2684. $this->var_cond = $this->EE->functions->assign_conditional_variables($str);
  2685. if (count($this->var_cond) == 0)
  2686. {
  2687. return $str;
  2688. }
  2689. foreach ($this->var_cond as $val)
  2690. {
  2691. // Make sure there is such a $global_var
  2692. // And that this is not an advanced conditional
  2693. if ( ! isset($vars[$val[3]]) OR
  2694. strpos($val[2], 'if:else') !== FALSE OR
  2695. strpos($val[0], 'if:else') !== FALSE OR
  2696. count(preg_split("/(\!=|==|<=|>=|<>|<|>|AND|XOR|OR|&&|\|\|)/", $val[0])) > 2)
  2697. {
  2698. continue;
  2699. }
  2700. $cond = $this->EE->functions->prep_conditional($val[0]);
  2701. $lcond = substr($cond, 0, strpos($cond, ' '));
  2702. $rcond = substr($cond, strpos($cond, ' '));
  2703. if (strpos($rcond, '"') == FALSE && strpos($rcond, "'") === FALSE) continue;
  2704. $temp = $vars[$val[3]];
  2705. $lcond = str_replace($val[3], "\$temp", $lcond);
  2706. if (stristr($rcond, '\|') !== FALSE OR stristr($rcond, '&') !== FALSE)
  2707. {
  2708. $rcond = trim($rcond);
  2709. $operator = trim(substr($rcond, 0, strpos($rcond, ' ')));
  2710. $check = trim(substr($rcond, strpos($rcond, ' ')));
  2711. $quote = substr($check, 0, 1);
  2712. if (stristr($rcond, '\|') !== FALSE)
  2713. {
  2714. $array = explode('\|', str_replace($quote, '', $check));
  2715. $break_operator = ' OR ';
  2716. }
  2717. else
  2718. {
  2719. $array = explode('&', str_replace($quote, '', $check));
  2720. $break_operator = ' && ';
  2721. }
  2722. $rcond = $operator.' '.$quote;
  2723. $rcond .= implode($quote.$break_operator.$lcond.' '.$operator.' '.$quote, $array).$quote;
  2724. }
  2725. $cond = $lcond.' '.$rcond;
  2726. $cond = str_replace("\|", "|", $cond);
  2727. eval("\$result = (".$cond.");");
  2728. if ($result)
  2729. {
  2730. $str = str_replace($val[1], $val[2], $str);
  2731. }
  2732. else
  2733. {
  2734. $str = str_replace($val[1], '', $str);
  2735. }
  2736. }
  2737. return $str;
  2738. }
  2739. // --------------------------------------------------------------------
  2740. /**
  2741. * Log Item for Template Processing Log
  2742. *
  2743. * @access public
  2744. * @param string
  2745. * @return void
  2746. */
  2747. function log_item($str)
  2748. {
  2749. if ($this->debugging !== TRUE)
  2750. {
  2751. return;
  2752. }
  2753. if ($this->depth > 0)
  2754. {
  2755. $str = str_repeat('&nbsp;', $this->depth * 5).$str;
  2756. }
  2757. $time = microtime(TRUE)-$this->start_microtime;
  2758. $memory_usage = '';
  2759. if (function_exists('memory_get_usage'))
  2760. {
  2761. $memory_usage = ' / '.number_format(round(memory_get_usage()/1024/1024, 2),2).'MB';
  2762. }
  2763. $this->log[] = '('.number_format($time, 6). $memory_usage . ') '.$str;
  2764. }
  2765. // --------------------------------------------------------------------
  2766. /**
  2767. * Basic HTTP Authentication for Templates
  2768. *
  2769. * @deprecated in 2.2 -- Moved to the Auth Library
  2770. *
  2771. * @access public
  2772. * @return header
  2773. */
  2774. function template_authentication_basic()
  2775. {
  2776. $this->EE->load->library('logger');
  2777. $this->EE->logger->deprecated('2.2', 'Auth Library');
  2778. @header('WWW-Authenticate: Basic realm="'.$this->realm.'"');
  2779. $this->EE->output->set_status_header(401);
  2780. @header("Date: ".gmdate("D, d M Y H:i:s")." GMT");
  2781. exit("HTTP/1.0 401 Unauthorized");
  2782. }
  2783. // --------------------------------------------------------------------
  2784. /**
  2785. * HTTP Authentication Validation
  2786. *
  2787. * Takes the username/password from the HTTP Authentication and validates it against the
  2788. * member database and see if this member's member group has access to the template.
  2789. *
  2790. * @deprecated -- Moved to the Auth Library in 2.2.
  2791. * @access public
  2792. * @param array
  2793. * @return header
  2794. */
  2795. function template_authentication_check_basic($not_allowed_groups = array())
  2796. {
  2797. $this->EE->load->library('logger');
  2798. $this->EE->logger->deprecated('2.2', 'Auth Library');
  2799. $this->EE->load->library('auth');
  2800. return $this->EE->auth->authenticate_http_basic($not_allowed_groups,
  2801. $this->realm);
  2802. }
  2803. // --------------------------------------------------------------------
  2804. /**
  2805. * Assign Form Params
  2806. *
  2807. * Extract form_class / form_id from tagdata, and assign it to a class property
  2808. * So it can be easily accessed.
  2809. *
  2810. * @access private
  2811. * @param array
  2812. * @return array
  2813. */
  2814. function _assign_form_params($tag_data)
  2815. {
  2816. $this->form_id = '';
  2817. $this->form_class = '';
  2818. if ( ! isset($tag_data['params']) OR ! is_array($tag_data['params']))
  2819. {
  2820. return $tag_data;
  2821. }
  2822. if (array_key_exists('form_id', $tag_data['params']))
  2823. {
  2824. $this->form_id = $tag_data['params']['form_id'];
  2825. }
  2826. if (array_key_exists('form_class', $tag_data['params']))
  2827. {
  2828. $this->form_class = $tag_data['params']['form_class'];
  2829. }
  2830. return $tag_data;
  2831. }
  2832. // --------------------------------------------------------------------
  2833. /**
  2834. * Fetch Site IDs for this Installation
  2835. *
  2836. * As ExpressionEngine can include data from other Sites in its installation, we need to validate
  2837. * these parameters and load the data from the correct site. We put it into a class variable
  2838. * so that it only has to happen once during a page request
  2839. *
  2840. * @access private
  2841. */
  2842. function _fetch_site_ids()
  2843. {
  2844. $this->site_ids = array();
  2845. if (isset($this->tagparams['site']))
  2846. {
  2847. if (count($this->sites) == 0 &&
  2848. $this->EE->config->item('multiple_sites_enabled') == 'y' && ! IS_CORE)
  2849. {
  2850. $sites_query = $this->EE->db->query("SELECT site_id, site_name FROM exp_sites ORDER BY site_id");
  2851. foreach($sites_query->result_array() as $row)
  2852. {
  2853. $this->sites[$row['site_id']] = $row['site_name'];
  2854. }
  2855. }
  2856. if (substr($this->tagparams['site'], 0, 4) == 'not ')
  2857. {
  2858. $sites = array_diff($this->sites, explode('|', substr($this->tagparams['site'], 4)));
  2859. }
  2860. else
  2861. {
  2862. $sites = array_intersect($this->sites, explode('|', $this->tagparams['site']));
  2863. }
  2864. // Let us hear it for the preservation of array keys!
  2865. $this->site_ids = array_flip($sites);
  2866. }
  2867. // If no sites were assigned via parameter, then we use the current site's
  2868. // Templates, Channels, and various Site data
  2869. if (count($this->site_ids) == 0)
  2870. {
  2871. $this->site_ids[] = $this->EE->config->item('site_id');
  2872. }
  2873. }
  2874. // --------------------------------------------------------------------
  2875. /**
  2876. * Parse Variables
  2877. *
  2878. * Simplifies variable parsing for plugin
  2879. * and modules developers
  2880. *
  2881. * @param string - the tagdata / text to be parsed
  2882. * @param array - the rows of variables and their data
  2883. * @param boolean - Option to disable backspace parameter
  2884. * @return string
  2885. */
  2886. public function parse_variables($tagdata, $variables, $enable_backspace = TRUE)
  2887. {
  2888. if ($tagdata == '' OR ! is_array($variables) OR empty($variables) OR ! is_array($variables[0]))
  2889. {
  2890. return $tagdata;
  2891. }
  2892. // Reset and Match date variables
  2893. $this->date_vars = array();
  2894. $this->_match_date_vars($tagdata);
  2895. // Unfound Variables that We Need Not Parse - Reset
  2896. $this->unfound_vars = array(array()); // nested for depth 0
  2897. // Match {switch="foo|bar"} variables
  2898. $switch = array();
  2899. if (preg_match_all("/".LD."(switch\s*=.+?)".RD."/i", $tagdata, $matches, PREG_SET_ORDER))
  2900. {
  2901. foreach ($matches as $match)
  2902. {
  2903. $sparam = $this->EE->functions->assign_parameters($match[1]);
  2904. if (isset($sparam['switch']))
  2905. {
  2906. $sopt = explode("|", $sparam['switch']);
  2907. $switch[$match[1]] = $sopt;
  2908. }
  2909. }
  2910. }
  2911. // Blast through the array to build our output
  2912. $str = '';
  2913. $count = 0;
  2914. $total_results = count($variables);
  2915. while (($row = array_shift($variables)) !== NULL)
  2916. {
  2917. $count++;
  2918. // Add {count} variable
  2919. if ( ! isset($row['count']))
  2920. {
  2921. $row['count'] = $count;
  2922. }
  2923. // Add {total_results} variable
  2924. if ( ! isset($row['total_results']))
  2925. {
  2926. $row['total_results'] = $total_results;
  2927. }
  2928. // Set {switch} variable values
  2929. foreach ($switch as $key => $val)
  2930. {
  2931. $row[$key] = $switch[$key][($count + count($val) -1) % count($val)];
  2932. }
  2933. $str .= $this->parse_variables_row($tagdata, $row, FALSE);
  2934. }
  2935. $backspace = $this->fetch_param('backspace', FALSE);
  2936. if (is_numeric($backspace) AND $enable_backspace)
  2937. {
  2938. $str = substr($str, 0, -$backspace);
  2939. }
  2940. return $str;
  2941. }
  2942. // --------------------------------------------------------------------
  2943. /**
  2944. * Parse Variables Row
  2945. *
  2946. * Handles a "row" of variable data from
  2947. * the parse_variables() method
  2948. *
  2949. * @param string - the tagdata / text to be parsed
  2950. * @param array - the variables and their data
  2951. * @param bool - coming from parse_variables() or part of set, forces some caching
  2952. *
  2953. * @return string
  2954. */
  2955. public function parse_variables_row($tagdata, $variables, $solo = TRUE)
  2956. {
  2957. if ($tagdata == '' OR ! is_array($variables) OR empty($variables))
  2958. {
  2959. return $tagdata;
  2960. }
  2961. if ($solo === TRUE)
  2962. {
  2963. $this->unfound_vars = array(array()); // nested for depth = 0
  2964. }
  2965. // Match date variables if necessary
  2966. if (empty($this->date_vars) && $this->date_vars !== FALSE)
  2967. {
  2968. $this->_match_date_vars($tagdata);
  2969. }
  2970. $this->conditional_vars = $variables;
  2971. foreach ($variables as $name => $value)
  2972. {
  2973. if (isset($this->unfound_vars[0][$name])) continue;
  2974. if (strpos($tagdata, LD.$name) === FALSE)
  2975. {
  2976. $this->unfound_vars[0][$name] = TRUE;
  2977. continue;
  2978. }
  2979. // Pair variables are an array of arrays
  2980. if (is_array($value))
  2981. {
  2982. if (empty($value))
  2983. {
  2984. // Weirdness. The most likely cause is an empty tag pair, we won't
  2985. // require developers to take care of this. This hack will blank them out.
  2986. $value = array(array());
  2987. }
  2988. if (isset($value[0]) && is_array($value[0]))
  2989. {
  2990. $tagdata = $this->_parse_var_pair($name, $value, $tagdata, 1);
  2991. continue;
  2992. }
  2993. }
  2994. $tagdata = $this->_parse_var_single($name, $value, $tagdata);
  2995. }
  2996. // Prep conditionals
  2997. $tagdata = $this->EE->functions->prep_conditionals($tagdata, $this->conditional_vars);
  2998. return $tagdata;
  2999. }
  3000. function create_url_check($matches)
  3001. {
  3002. print_r($matches);
  3003. }
  3004. // --------------------------------------------------------------------
  3005. /**
  3006. * Parse Var Single
  3007. *
  3008. * Parses single variables from the parse_variables() method
  3009. *
  3010. * @access public
  3011. * @param string - the variable's name
  3012. * @param string - the variable's value
  3013. * @param string - the text to parse
  3014. * @return string
  3015. */
  3016. function _parse_var_single($name, $value, $string)
  3017. {
  3018. // parse date variables where applicable
  3019. if (isset($this->date_vars[$name]))
  3020. {
  3021. foreach ($this->date_vars[$name] as $dvar => $dval)
  3022. {
  3023. $val = array_shift($dval);
  3024. $string = str_replace(LD.$dvar.RD,
  3025. str_replace($dval, $this->EE->localize->convert_timestamp($dval, $value, TRUE), $val),
  3026. $string);
  3027. }
  3028. // unformatted dates
  3029. if (strpos($string, LD.$name.RD) !== FALSE)
  3030. {
  3031. $string = str_replace(LD.$name.RD, $value, $string);
  3032. }
  3033. return $string;
  3034. }
  3035. // Simple Variable - Find & Replace & Return
  3036. if (is_string($value))
  3037. {
  3038. return str_replace(LD.$name.RD, $value, $string);
  3039. }
  3040. //
  3041. // Complex Paths and Typography Variables
  3042. //
  3043. // If the single variable's value is an array, then
  3044. // $value[0] is the content and $value[1] is an array
  3045. // of parameters for the Typography class OR an indicator of a path variable
  3046. if (is_array($value) && count($value) == 2 && is_array($value[1]))
  3047. {
  3048. $raw_content = $value[0];
  3049. // Make our path switches
  3050. if (isset($value[1]['path_variable']) && $value[1]['path_variable'] === TRUE)
  3051. {
  3052. if (preg_match_all("#".LD."\s*".$name."=(.*?)".RD."#", $string, $matches))
  3053. {
  3054. $done = array();
  3055. foreach ($matches[0] as $full)
  3056. {
  3057. if (in_array($full, $done))
  3058. {
  3059. continue;
  3060. }
  3061. $link = $this->EE->functions->create_url($this->EE->functions->extract_path($full).'/'.$value[0]);
  3062. //$single_quote = str_replace("'", '"', $matches['0']);
  3063. //$double_quote = str_replace("'", '"', $matches['0']);
  3064. //[0] => {id_path="about/test"}
  3065. //[1] => "about/test"
  3066. // Switch to double quotes
  3067. $single = str_replace(array('"', "'"), "'", $full);
  3068. $double = str_replace(array('"', "'"), '"', $full);
  3069. //echo $single.' - '.$double.'<br>';
  3070. $string = str_replace($single, $double, $string);
  3071. //echo $string;
  3072. //echo '<br>-----------------------<br>';
  3073. $string = str_replace($double, $link, $string);
  3074. $done[] = $full;
  3075. }
  3076. }
  3077. return $string;
  3078. }
  3079. $prefs = array();
  3080. foreach (array('text_format', 'html_format', 'auto_links', 'allow_img_url', 'convert_curly') as $pref)
  3081. {
  3082. if (isset($value[1][$pref]))
  3083. {
  3084. $prefs[$pref] = $value[1][$pref];
  3085. }
  3086. }
  3087. // Instantiate Typography only if necessary
  3088. $this->EE->load->library('typography');
  3089. $this->EE->typography->initialize(array(
  3090. 'convert_curly' => (isset($prefs['convert_curly']) && $prefs['convert_curly'] == 'n') ? FALSE : TRUE)
  3091. );
  3092. $value = $this->EE->typography->parse_type($raw_content, $prefs);
  3093. }
  3094. if (isset($raw_content))
  3095. {
  3096. $this->conditional_vars[$name] = $raw_content;
  3097. }
  3098. return str_replace(LD.$name.RD, $value, $string);
  3099. }
  3100. // --------------------------------------------------------------------
  3101. /**
  3102. * Parse Var Pair
  3103. *
  3104. * Parses pair variables from the parse_variables() method
  3105. *
  3106. * @access public
  3107. * @param string - the variable pair's name
  3108. * @param array - the variable pair's single variables
  3109. * @param string - the text to parse
  3110. * @param integer - iteration depth for unfound_vars
  3111. * @return string
  3112. */
  3113. function _parse_var_pair($name, $variables, $string, $depth = 0)
  3114. {
  3115. if ( ! $match_count = preg_match_all("|".LD.$name.'.*?'.RD.'(.*?)'.LD.'/'.$name.RD."|s", $string, $matches))
  3116. {
  3117. return $string;
  3118. }
  3119. if (empty($variables[0]))
  3120. {
  3121. return str_replace($matches[0], '', $string);
  3122. }
  3123. if ( ! isset($this->unfound_vars[$depth]))
  3124. {
  3125. // created a separate unfound vars for each matched pair (kind of a crazy array, need to investigate if it's hindering performance at this point)
  3126. $this->unfound_vars[$depth] = array();
  3127. }
  3128. foreach ($matches[1] as $k => $match)
  3129. {
  3130. $str = '';
  3131. $parameters = array();
  3132. $count = 1;
  3133. // Get parameters of variable pair
  3134. if (preg_match_all("|".LD.$name.'(.*?)'.RD."|s", $matches[0][$k], $param_matches))
  3135. {
  3136. $parameters = $this->EE->functions->assign_parameters($param_matches[1][0]);
  3137. }
  3138. // Limit parameter
  3139. $limit = (isset($parameters['limit'])) ? $parameters['limit'] : NULL;
  3140. foreach ($variables as $set)
  3141. {
  3142. $temp = $match;
  3143. foreach ($set as $key => $value)
  3144. {
  3145. if (isset($this->unfound_vars[$depth][$key]) OR
  3146. strpos($string, LD.$key) === FALSE)
  3147. {
  3148. continue;
  3149. }
  3150. // Pair variables are an array of arrays.
  3151. if (is_array($value))
  3152. {
  3153. if (empty($value))
  3154. {
  3155. // Weirdness. The most likely cause is an empty tag pair, we won't
  3156. // require developers to take care of this. This hack will blank them out.
  3157. $value = array(array());
  3158. }
  3159. if (isset($value[0]) && is_array($value[0]))
  3160. {
  3161. $temp = $this->_parse_var_pair($key, $value, $temp, $depth + 1);
  3162. continue;
  3163. }
  3164. }
  3165. $temp = $this->_parse_var_single($key, $value, $temp);
  3166. }
  3167. // Prep conditionals
  3168. $temp = $this->EE->functions->prep_conditionals($temp, $set);
  3169. $str .= $temp;
  3170. // Break if we're past the limit
  3171. if ($limit !== NULL AND $limit == $count++)
  3172. {
  3173. break;
  3174. }
  3175. }
  3176. // Backspace parameter
  3177. $backspace = (isset($parameters['backspace'])) ? $parameters['backspace'] : NULL;
  3178. if (is_numeric($backspace))
  3179. {
  3180. $str = substr($str, 0, -$backspace);
  3181. }
  3182. $string = str_replace($matches[0][$k], $str, $string);
  3183. }
  3184. return $string;
  3185. }
  3186. // --------------------------------------------------------------------
  3187. /**
  3188. * Match Date Vars
  3189. *
  3190. * Finds date variables within tagdata
  3191. * array structure:
  3192. * [name] => Array
  3193. * (
  3194. * [name format="%m/%d/%y"] => Array
  3195. * (
  3196. * [0] => %m/%d/%y
  3197. * [1] => %m
  3198. * [2] => %d
  3199. * [3] => %y
  3200. * )
  3201. *
  3202. * @access public
  3203. * @param string
  3204. * @return void
  3205. */
  3206. function _match_date_vars($str)
  3207. {
  3208. if (strpos($str, 'format=') === FALSE) return;
  3209. if (preg_match_all("/".LD."([\w:\-]+)\s+format=[\"'](.*?)[\"']".RD."/", $str, $matches, PREG_SET_ORDER))
  3210. {
  3211. for ($j = 0, $tot = count($matches); $j < $tot; $j++)
  3212. {
  3213. $matches[$j][0] = str_replace(array(LD,RD), '', $matches[$j][0]);
  3214. $this->date_vars[$matches[$j][1]][$matches[$j][0]] = array_merge(array($matches[$j][2]), $this->EE->localize->fetch_date_params($matches[$j][2]));
  3215. }
  3216. }
  3217. else
  3218. {
  3219. // make sure we don't try to parse date variables again on further calls to parse_variables() or parse_variables_row()
  3220. $this->date_vars = FALSE;
  3221. }
  3222. }
  3223. // --------------------------------------------------------------------
  3224. }
  3225. // END CLASS
  3226. /* End of file Template.php */
  3227. /* Location: ./system/expressionengine/libraries/Template.php */