PageRenderTime 63ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/system/expressionengine/libraries/Template.php

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