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

/cp/expressionengine/modules/channel/mod.channel.php

https://bitbucket.org/sbeuken/artelux
PHP | 7675 lines | 5361 code | 1379 blank | 935 comment | 1189 complexity | 23ab38aa31a2e32a3b0967a28ba11509 MD5 | raw file
  1. <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
  2. /**
  3. * ExpressionEngine - by EllisLab
  4. *
  5. * @package ExpressionEngine
  6. * @author EllisLab Dev Team
  7. * @copyright Copyright (c) 2003 - 2012, EllisLab, Inc.
  8. * @license http://ellislab.com/expressionengine/user-guide/license.html
  9. * @link http://ellislab.com
  10. * @since Version 2.0
  11. * @filesource
  12. */
  13. // --------------------------------------------------------------------
  14. /**
  15. * ExpressionEngine Channel Module
  16. *
  17. * @package ExpressionEngine
  18. * @subpackage Modules
  19. * @category Modules
  20. * @author EllisLab Dev Team
  21. * @link http://ellislab.com
  22. */
  23. class Channel {
  24. public $limit = '100'; // Default maximum query results if not specified.
  25. // These variable are all set dynamically
  26. public $query;
  27. public $TYPE;
  28. public $entry_id = '';
  29. public $uri = '';
  30. public $uristr = '';
  31. public $return_data = ''; // Final data
  32. public $hit_tracking_id = FALSE;
  33. public $sql = FALSE;
  34. public $cfields = array();
  35. public $dfields = array();
  36. public $rfields = array();
  37. public $mfields = array();
  38. public $pfields = array();
  39. public $categories = array();
  40. public $catfields = array();
  41. public $channel_name = array();
  42. public $channels_array = array();
  43. public $related_entries = array();
  44. public $reverse_related_entries = array();
  45. public $reserved_cat_segment = '';
  46. public $use_category_names = FALSE;
  47. public $cat_request = FALSE;
  48. public $enable = array(); // modified by various tags with disable= parameter
  49. public $absolute_results = NULL; // absolute total results returned by the tag, useful when paginating
  50. public $display_by = '';
  51. // These are used with the nested category trees
  52. public $category_list = array();
  53. public $cat_full_array = array();
  54. public $cat_array = array();
  55. public $temp_array = array();
  56. public $category_count = 0;
  57. public $pagination;
  58. public $pager_sql = '';
  59. // SQL Caching
  60. public $sql_cache_dir = 'sql_cache/';
  61. // Misc. - Class variable usable by extensions
  62. public $misc = FALSE;
  63. // Array of parameters allowed to be set dynamically
  64. private $_dynamic_parameters = array();
  65. /**
  66. * Constructor
  67. */
  68. public function Channel()
  69. {
  70. // Make a local reference to the ExpressionEngine super object
  71. $this->EE =& get_instance();
  72. $this->EE->load->library('pagination');
  73. $this->pagination = new Pagination_object(__CLASS__);
  74. // $this->pagination->per_page = $this->limit;
  75. // Used by pagination to determine whether we're coming from the cache
  76. $this->pagination->dynamic_sql = FALSE;
  77. $this->query_string = ($this->EE->uri->page_query_string != '') ? $this->EE->uri->page_query_string : $this->EE->uri->query_string;
  78. if ($this->EE->config->item("use_category_name") == 'y' && $this->EE->config->item("reserved_category_word") != '')
  79. {
  80. $this->use_category_names = $this->EE->config->item("use_category_name");
  81. $this->reserved_cat_segment = $this->EE->config->item("reserved_category_word");
  82. }
  83. // a number of tags utilize the disable= parameter, set it here
  84. if (isset($this->EE->TMPL) && is_object($this->EE->TMPL))
  85. {
  86. $this->_fetch_disable_param();
  87. }
  88. $this->_dynamic_parameters = array('channel', 'entry_id', 'category', 'orderby',
  89. 'sort', 'sticky', 'show_future_entries', 'show_expired', 'entry_id_from',
  90. 'entry_id_to', 'not_entry_id', 'start_on', 'stop_before', 'year', 'month',
  91. 'day', 'display_by', 'limit', 'username', 'status', 'group_id', 'cat_limit',
  92. 'month_limit', 'offset', 'author_id', 'url_title');
  93. }
  94. // ------------------------------------------------------------------------
  95. /**
  96. * Initialize values
  97. */
  98. public function initialize()
  99. {
  100. $this->sql = '';
  101. $this->return_data = '';
  102. }
  103. // ------------------------------------------------------------------------
  104. /**
  105. * Fetch Cache
  106. */
  107. public function fetch_cache($identifier = '')
  108. {
  109. $tag = ($identifier == '') ? $this->EE->TMPL->tagproper : $this->EE->TMPL->tagproper.$identifier;
  110. if ($this->EE->TMPL->fetch_param('dynamic_parameters') !== FALSE && isset($_POST) && count($_POST) > 0)
  111. {
  112. foreach (explode('|', $this->EE->TMPL->fetch_param('dynamic_parameters')) as $var)
  113. {
  114. if (isset($_POST[$var]) && in_array($var, $this->_dynamic_parameters))
  115. {
  116. $tag .= $var.'="'.$_POST[$var].'"';
  117. }
  118. if (isset($_POST[$var]) && strncmp($var, 'search:', 7) == 0)
  119. {
  120. $tag .= $var.'="'.substr($_POST[$var], 7).'"';
  121. }
  122. }
  123. }
  124. $cache_file = APPPATH.'cache/'.$this->sql_cache_dir.md5($tag.$this->uri);
  125. if ( ! $fp = @fopen($cache_file, FOPEN_READ))
  126. {
  127. return FALSE;
  128. }
  129. flock($fp, LOCK_SH);
  130. $sql = @fread($fp, filesize($cache_file));
  131. flock($fp, LOCK_UN);
  132. fclose($fp);
  133. return $sql;
  134. }
  135. // ------------------------------------------------------------------------
  136. /**
  137. * Save Cache
  138. */
  139. public function save_cache($sql, $identifier = '')
  140. {
  141. $tag = ($identifier == '') ? $this->EE->TMPL->tagproper : $this->EE->TMPL->tagproper.$identifier;
  142. $cache_dir = APPPATH.'cache/'.$this->sql_cache_dir;
  143. $cache_file = $cache_dir.md5($tag.$this->uri);
  144. if ( ! @is_dir($cache_dir))
  145. {
  146. if ( ! @mkdir($cache_dir, DIR_WRITE_MODE))
  147. {
  148. return FALSE;
  149. }
  150. if ($fp = @fopen($cache_dir.'/index.html', FOPEN_WRITE_CREATE_DESTRUCTIVE))
  151. {
  152. fclose($fp);
  153. }
  154. @chmod($cache_dir, DIR_WRITE_MODE);
  155. }
  156. if ( ! $fp = @fopen($cache_file, FOPEN_WRITE_CREATE_DESTRUCTIVE))
  157. {
  158. return FALSE;
  159. }
  160. flock($fp, LOCK_EX);
  161. fwrite($fp, $sql);
  162. flock($fp, LOCK_UN);
  163. fclose($fp);
  164. @chmod($cache_file, FILE_WRITE_MODE);
  165. return TRUE;
  166. }
  167. // ------------------------------------------------------------------------
  168. /**
  169. * Channel entries
  170. */
  171. public function entries()
  172. {
  173. // If the "related_categories" mode is enabled
  174. // we'll call the "related_categories" function
  175. // and bail out.
  176. if ($this->EE->TMPL->fetch_param('related_categories_mode') == 'yes')
  177. {
  178. return $this->related_entries();
  179. }
  180. // Onward...
  181. $this->initialize();
  182. $this->uri = ($this->query_string != '') ? $this->query_string : 'index.php';
  183. if ($this->enable['custom_fields'] == TRUE)
  184. {
  185. $this->fetch_custom_channel_fields();
  186. }
  187. if ($this->enable['member_data'] == TRUE)
  188. {
  189. $this->fetch_custom_member_fields();
  190. }
  191. if ($this->enable['pagination'] == TRUE)
  192. {
  193. $this->pagination->get_template();
  194. }
  195. $save_cache = FALSE;
  196. if ($this->EE->config->item('enable_sql_caching') == 'y' && $this->EE->TMPL->fetch_param('author_id') != 'CURRENT_USER')
  197. {
  198. if (FALSE == ($this->sql = $this->fetch_cache()))
  199. {
  200. $save_cache = TRUE;
  201. }
  202. else
  203. {
  204. if ($this->EE->TMPL->fetch_param('dynamic') != 'no')
  205. {
  206. if (preg_match("#(^|\/)C(\d+)#", $this->query_string, $match) OR in_array($this->reserved_cat_segment, explode("/", $this->query_string)))
  207. {
  208. $this->cat_request = TRUE;
  209. }
  210. }
  211. }
  212. if (FALSE !== ($cache = $this->fetch_cache('pagination_count')))
  213. {
  214. if (FALSE !== ($this->fetch_cache('field_pagination')))
  215. {
  216. if (FALSE !== ($pg_query = $this->fetch_cache('pagination_query')))
  217. {
  218. $this->pagination->paginate = TRUE;
  219. $this->pagination->field_pagination = TRUE;
  220. $this->pagination->cfields = $this->cfields;
  221. $this->pagination->build(trim($cache), $this->sql, $this->EE->db->query(trim($pg_query)));
  222. }
  223. }
  224. else
  225. {
  226. $this->pagination->cfields = $this->cfields;
  227. $this->pagination->build(trim($cache), $this->sql);
  228. }
  229. }
  230. }
  231. if ($this->sql == '')
  232. {
  233. $this->build_sql_query();
  234. }
  235. if ($this->sql == '')
  236. {
  237. return $this->EE->TMPL->no_results();
  238. }
  239. if ($save_cache == TRUE)
  240. {
  241. $this->save_cache($this->sql);
  242. }
  243. $this->query = $this->EE->db->query($this->sql);
  244. if ($this->query->num_rows() == 0)
  245. {
  246. return $this->EE->TMPL->no_results();
  247. }
  248. // -------------------------------------
  249. // "Relaxed" View Tracking
  250. //
  251. // Some people have tags that are used to mimic a single-entry
  252. // page without it being dynamic. This allows Entry View Tracking
  253. // to work for ANY combination that results in only one entry
  254. // being returned by the tag, including channel query caching.
  255. //
  256. // Hidden Configuration Variable
  257. // - relaxed_track_views => Allow view tracking on non-dynamic
  258. // single entries (y/n)
  259. // -------------------------------------
  260. if ($this->EE->config->item('relaxed_track_views') === 'y' && $this->query->num_rows() == 1)
  261. {
  262. $this->hit_tracking_id = $this->query->row('entry_id') ;
  263. }
  264. $this->track_views();
  265. $this->EE->load->library('typography');
  266. $this->EE->typography->initialize(array(
  267. 'convert_curly' => FALSE
  268. ));
  269. if ($this->enable['categories'] == TRUE)
  270. {
  271. $this->fetch_categories();
  272. }
  273. $this->parse_channel_entries();
  274. if ($this->enable['pagination'] == TRUE)
  275. {
  276. $this->return_data = $this->pagination->render($this->return_data);
  277. }
  278. // Does the tag contain "related entries" that we need to parse out?
  279. if (count($this->EE->TMPL->related_data) > 0 && count($this->related_entries) > 0)
  280. {
  281. $this->parse_related_entries();
  282. }
  283. if (count($this->EE->TMPL->reverse_related_data) > 0 && count($this->reverse_related_entries) > 0)
  284. {
  285. $this->parse_reverse_related_entries();
  286. }
  287. return $this->return_data;
  288. }
  289. // ------------------------------------------------------------------------
  290. /**
  291. * Process related entries
  292. */
  293. public function parse_related_entries()
  294. {
  295. $sql = "SELECT rel_id, rel_parent_id, rel_child_id, rel_type, rel_data
  296. FROM exp_relationships
  297. WHERE rel_id IN (";
  298. $templates = array();
  299. foreach ($this->related_entries as $val)
  300. {
  301. $x = explode('_', $val);
  302. $sql .= "'".$x[0]."',";
  303. $templates[] = array($x[0], $x[1], $this->EE->TMPL->related_data[$x[1]]);
  304. }
  305. $sql = substr($sql, 0, -1).')';
  306. $query = $this->EE->db->query($sql);
  307. if ($query->num_rows() == 0)
  308. return;
  309. // --------------------------------
  310. // Without this the Related Entries were inheriting the parameters of
  311. // the enclosing Channel Entries tag. Sometime in the future we will
  312. // likely allow Related Entries to have their own parameters
  313. // --------------------------------
  314. $return_data = $this->return_data;
  315. foreach ($templates as $temp)
  316. {
  317. foreach ($query->result_array() as $row)
  318. {
  319. if ($row['rel_id'] != $temp[0])
  320. continue;
  321. // --------------------------------------
  322. // If the data is emptied (cache cleared), then we
  323. // rebuild it with fresh data so processing can continue.
  324. // --------------------------------------
  325. if (trim($row['rel_data']) == '')
  326. {
  327. $rewrite = array(
  328. 'type' => $row['rel_type'],
  329. 'parent_id' => $row['rel_parent_id'],
  330. 'child_id' => $row['rel_child_id'],
  331. 'related_id' => $row['rel_id']
  332. );
  333. $this->EE->functions->compile_relationship($rewrite, FALSE);
  334. $results = $this->EE->db->query("SELECT rel_data FROM exp_relationships WHERE rel_id = '".$row['rel_id']."'");
  335. $row['rel_data'] = $results->row('rel_data') ;
  336. }
  337. // Begin Processing
  338. $this->initialize();
  339. if ($reldata = @unserialize($row['rel_data']))
  340. {
  341. $this->EE->TMPL->var_single = $temp[2]['var_single'];
  342. $this->EE->TMPL->var_pair = $temp[2]['var_pair'];
  343. $this->EE->TMPL->var_cond = $temp[2]['var_cond'];
  344. $this->EE->TMPL->tagdata = $temp[2]['tagdata'];
  345. if ($row['rel_type'] == 'channel')
  346. {
  347. // Bug fix for when categories were not being inserted
  348. // correctly for related channel entries. Bummer.
  349. if (count($reldata['categories'] == 0) && ! isset($reldata['cats_fixed']))
  350. {
  351. $fixdata = array(
  352. 'type' => $row['rel_type'],
  353. 'parent_id' => $row['rel_parent_id'],
  354. 'child_id' => $row['rel_child_id'],
  355. 'related_id' => $row['rel_id']
  356. );
  357. $this->EE->functions->compile_relationship($fixdata, FALSE);
  358. $reldata['categories'] = $this->EE->functions->cat_array;
  359. $reldata['category_fields'] = $this->EE->functions->catfields;
  360. }
  361. $this->query = $reldata['query'];
  362. if ($this->query->num_rows != 0)
  363. {
  364. $this->categories = array($this->query->row('entry_id') => $reldata['categories']);
  365. if (isset($reldata['category_fields']))
  366. {
  367. $this->catfields = array($this->query->row('entry_id') => $reldata['category_fields']);
  368. }
  369. }
  370. $this->parse_channel_entries();
  371. $marker = LD."REL[".$row['rel_id']."][".$temp[2]['field_name']."]".$temp[1]."REL".RD;
  372. $return_data = str_replace($marker, $this->return_data, $return_data);
  373. }
  374. }
  375. }
  376. }
  377. $this->return_data = $return_data;
  378. }
  379. // ------------------------------------------------------------------------
  380. /**
  381. * Process reverse related entries
  382. */
  383. public function parse_reverse_related_entries()
  384. {
  385. $this->EE->db->select('rel_id, rel_parent_id, rel_child_id, rel_type, reverse_rel_data');
  386. $this->EE->db->where_in('rel_child_id', array_keys($this->reverse_related_entries));
  387. $this->EE->db->where('rel_type', 'channel');
  388. $query = $this->EE->db->get('relationships');
  389. if ($query->num_rows() == 0)
  390. {
  391. // remove Reverse Related tags for these entries
  392. foreach ($this->reverse_related_entries as $entry_id => $templates)
  393. {
  394. foreach($templates as $tkey => $template)
  395. {
  396. $this->return_data = str_replace(LD."REV_REL[".$this->EE->TMPL->reverse_related_data[$template]['marker']."][".$entry_id."]REV_REL".RD, $this->EE->TMPL->reverse_related_data[$template]['no_rev_content'], $this->return_data);
  397. }
  398. }
  399. return;
  400. }
  401. // Data Processing Time
  402. $entry_data = array();
  403. for ($i = 0, $total = count($query->result_array()); $i < $total; $i++)
  404. {
  405. $row = array_shift($query->result_array);
  406. // If the data is emptied (cache cleared or first process), then we
  407. // rebuild it with fresh data so processing can continue.
  408. if (trim($row['reverse_rel_data']) == '')
  409. {
  410. $rewrite = array(
  411. 'type' => $row['rel_type'],
  412. 'parent_id' => $row['rel_parent_id'],
  413. 'child_id' => $row['rel_child_id'],
  414. 'related_id' => $row['rel_id']
  415. );
  416. $this->EE->functions->compile_relationship($rewrite, FALSE, TRUE);
  417. $this->EE->db->select('reverse_rel_data');
  418. $this->EE->db->where('rel_parent_id', $row['rel_parent_id']);
  419. $results = $this->EE->db->get('relationships');
  420. $row['reverse_rel_data'] = $results->row('reverse_rel_data');
  421. }
  422. // Unserialize the entries data, please
  423. if ($revreldata = @unserialize($row['reverse_rel_data']))
  424. {
  425. $entry_data[$row['rel_child_id']][$row['rel_parent_id']] = $revreldata;
  426. }
  427. }
  428. // Without this the Reverse Related Entries were inheriting the parameters of
  429. // the enclosing Channel Entries tag, which is not appropriate.
  430. $return_data = $this->return_data;
  431. foreach ($this->reverse_related_entries as $entry_id => $templates)
  432. {
  433. // No Entries? Remove Reverse Related Tags and Continue to Next Entry
  434. if ( ! isset($entry_data[$entry_id]))
  435. {
  436. foreach($templates as $tkey => $template)
  437. {
  438. $return_data = str_replace(LD."REV_REL[".$this->EE->TMPL->reverse_related_data[$template]['marker']."][".$entry_id."]REV_REL".RD, $this->EE->TMPL->reverse_related_data[$template]['no_rev_content'], $return_data);
  439. }
  440. continue;
  441. }
  442. // Process Our Reverse Related Templates
  443. foreach($templates as $tkey => $template)
  444. {
  445. $i = 0;
  446. $cats = array();
  447. $params = $this->EE->TMPL->reverse_related_data[$template]['params'];
  448. if ( ! is_array($params))
  449. {
  450. $params = array('status' => 'open');
  451. }
  452. elseif ( ! isset($params['status']))
  453. {
  454. $params['status'] = 'open';
  455. }
  456. else
  457. {
  458. $params['status'] = trim($params['status'], " |\t\n\r");
  459. }
  460. // Entries have to be ordered, sorted and other stuff
  461. $new = array();
  462. $order = ( ! isset($params['orderby'])) ? 'date' : $params['orderby'];
  463. $offset = ( ! isset($params['offset']) OR ! is_numeric($params['offset'])) ? 0 : $params['offset'];
  464. $limit = ( ! isset($params['limit']) OR ! is_numeric($params['limit'])) ? 100 : $params['limit'];
  465. $sort = ( ! isset($params['sort'])) ? 'asc' : $params['sort'];
  466. $random = ($order == 'random') ? TRUE : FALSE;
  467. $base_orders = array('random', 'date', 'title', 'url_title', 'edit_date', 'comment_total', 'username', 'screen_name', 'most_recent_comment', 'expiration_date', 'entry_id',
  468. 'view_count_one', 'view_count_two', 'view_count_three', 'view_count_four', 'status');
  469. $str_sort = array('title', 'url_title', 'username', 'screen_name', 'status');
  470. if ( ! in_array($order, $base_orders))
  471. {
  472. $set = 'n';
  473. foreach($this->cfields as $site_id => $cfields)
  474. {
  475. if ( isset($cfields[$order]))
  476. {
  477. $multi_order[] = 'field_id_'.$cfields[$order];
  478. $set = 'y';
  479. $str_sort[] = 'field_id_'.$cfields[$order];
  480. //break;
  481. }
  482. }
  483. if ( $set == 'n' )
  484. {
  485. $order = 'date';
  486. }
  487. }
  488. if ($order == 'date' OR $order == 'random')
  489. {
  490. $order = 'entry_date';
  491. }
  492. if (isset($params['channel']) && trim($params['channel']) != '')
  493. {
  494. if (count($this->channels_array) == 0)
  495. {
  496. $this->EE->db->select('channel_id, channel_name');
  497. $this->EE->db->where_in('site_id', $this->EE->TMPL->site_ids);
  498. $results = $this->EE->db->get('channels');
  499. foreach($results->result_array() as $row)
  500. {
  501. $this->channels_array[$row['channel_id']] = $row['channel_name'];
  502. }
  503. }
  504. $channels = explode('|', trim($params['channel']));
  505. $allowed = array();
  506. if (strncmp($channels[0], 'not ', 4) == 0)
  507. {
  508. $channels[0] = trim(substr($channels[0], 3));
  509. $allowed = $this->channels_array;
  510. foreach($channels as $name)
  511. {
  512. if (in_array($name, $allowed))
  513. {
  514. foreach (array_keys($allowed, $name) AS $k)
  515. {
  516. unset($allowed[$k]);
  517. }
  518. }
  519. }
  520. }
  521. else
  522. {
  523. foreach($channels as $name)
  524. {
  525. if (in_array($name, $this->channels_array))
  526. {
  527. foreach (array_keys($this->channels_array, $name) AS $k)
  528. {
  529. $allowed[$k] = $name;
  530. }
  531. }
  532. }
  533. }
  534. }
  535. $stati = explode('|', $params['status']);
  536. $stati = array_map('strtolower', $stati); // match MySQL's case-insensitivity
  537. $status_state = 'positive';
  538. // Check for "not "
  539. if (substr($stati[0], 0, 4) == 'not ')
  540. {
  541. $status_state = 'negative';
  542. $stati[0] = trim(substr($stati[0], 3));
  543. $stati[] = 'closed';
  544. }
  545. $r = 1; // Fixes a problem when a sorting key occurs twice
  546. foreach($entry_data[$entry_id] as $relating_data)
  547. {
  548. $post_fix = ' '.$r;
  549. $order_set = FALSE;
  550. if ( ! isset($params['channel']) OR ($relating_data['query']->row('channel_id') && array_key_exists($relating_data['query']->row('channel_id'), $allowed)))
  551. {
  552. $query_row = $relating_data['query']->row_array();
  553. if (isset($multi_order))
  554. {
  555. foreach ($multi_order as $field_val)
  556. {
  557. if (isset($query_row[$field_val]))
  558. {
  559. $order_set = TRUE;
  560. $order_key = '';
  561. if ($query_row[$field_val] != '')
  562. {
  563. $order_key = $query_row[$field_val];
  564. $order = $field_val;
  565. break;
  566. }
  567. }
  568. }
  569. }
  570. elseif (isset($query_row[$order]))
  571. {
  572. $order_set = TRUE;
  573. $order_key = $query_row[$order];
  574. }
  575. // Needs to have the field we're ordering by
  576. if ($order_set)
  577. {
  578. if ($status_state == 'negative' && ! in_array(strtolower($query_row['status']) , $stati))
  579. {
  580. $new[$order_key.$post_fix] = $relating_data;
  581. }
  582. elseif (in_array(strtolower($query_row['status']) , $stati))
  583. {
  584. $new[$order_key.$post_fix] = $relating_data;
  585. }
  586. }
  587. ++$r;
  588. }
  589. }
  590. $sort_flags = SORT_REGULAR;
  591. // Check if the custom field to sort on is numeric, sort numericaly if it is
  592. if (strncmp($order, 'field_id_', 9) === 0)
  593. {
  594. $this->EE->load->library('api');
  595. $this->EE->api->instantiate('channel_fields');
  596. $field_settings = $this->EE->api_channel_fields->get_settings(substr($order, 9));
  597. if (isset($field_settings['field_content_type']) && in_array($field_settings['field_content_type'], array('numeric', 'integer', 'decimal')))
  598. {
  599. $sort_flags = SORT_NUMERIC;
  600. }
  601. }
  602. // Shuffle if random
  603. if ($random === TRUE)
  604. {
  605. shuffle($new);
  606. }
  607. else
  608. {
  609. // Sort keys by string comparison
  610. if (in_array($order, $str_sort))
  611. {
  612. uksort($new, 'strnatcasecmp');
  613. }
  614. // If it's in the base options and not a string?
  615. // Sort numeric
  616. elseif (in_array($order, $base_orders))
  617. {
  618. ksort($new, SORT_NUMERIC);
  619. }
  620. // Sort keys based on set sort flags
  621. else
  622. {
  623. ksort($new, $sort_flags);
  624. }
  625. // Reverse sorted array if we're sorting descending
  626. if ($sort != 'asc')
  627. {
  628. $new = array_reverse($new, TRUE);
  629. }
  630. }
  631. $output_data[$entry_id] = array_slice($new, $offset, $limit);
  632. if (count($output_data[$entry_id]) == 0)
  633. {
  634. $return_data = str_replace(LD."REV_REL[".$this->EE->TMPL->reverse_related_data[$template]['marker']."][".$entry_id."]REV_REL".RD, $this->EE->TMPL->reverse_related_data[$template]['no_rev_content'], $return_data);
  635. continue;
  636. }
  637. // Finally! We get to process our parents
  638. foreach($output_data[$entry_id] as $relating_data)
  639. {
  640. if ($i == 0)
  641. {
  642. $query = clone $relating_data['query'];
  643. }
  644. else
  645. {
  646. $query->result_array[] = $relating_data['query']->row_array();
  647. }
  648. $cats[$relating_data['query']->row('entry_id') ] = $relating_data['categories'];
  649. ++$i;
  650. }
  651. $query->num_rows = $i;
  652. $this->initialize();
  653. $this->EE->TMPL->var_single = $this->EE->TMPL->reverse_related_data[$template]['var_single'];
  654. $this->EE->TMPL->var_pair = $this->EE->TMPL->reverse_related_data[$template]['var_pair'];
  655. $this->EE->TMPL->var_cond = $this->EE->TMPL->reverse_related_data[$template]['var_cond'];
  656. $this->EE->TMPL->tagdata = $this->EE->TMPL->reverse_related_data[$template]['tagdata'];
  657. $this->query = $query;
  658. $this->categories = $cats;
  659. $this->parse_channel_entries();
  660. $return_data = str_replace( LD."REV_REL[".$this->EE->TMPL->reverse_related_data[$template]['marker']."][".$entry_id."]REV_REL".RD,
  661. $this->return_data,
  662. $return_data);
  663. }
  664. }
  665. $this->return_data = $return_data;
  666. }
  667. // ------------------------------------------------------------------------
  668. /**
  669. * Track Views
  670. */
  671. public function track_views()
  672. {
  673. if ($this->EE->config->item('enable_entry_view_tracking') == 'n')
  674. {
  675. return;
  676. }
  677. if ( ! $this->EE->TMPL->fetch_param('track_views') OR $this->hit_tracking_id === FALSE)
  678. {
  679. return;
  680. }
  681. if ($this->pagination->field_pagination == TRUE AND $this->pagination->offset > 0)
  682. {
  683. return;
  684. }
  685. foreach (explode('|', $this->EE->TMPL->fetch_param('track_views')) as $view)
  686. {
  687. if ( ! in_array(strtolower($view), array("one", "two", "three", "four")))
  688. {
  689. continue;
  690. }
  691. $sql = "UPDATE exp_channel_titles SET view_count_{$view} = (view_count_{$view} + 1) WHERE ";
  692. $sql .= (is_numeric($this->hit_tracking_id)) ? "entry_id = {$this->hit_tracking_id}" : "url_title = '".$this->EE->db->escape_str($this->hit_tracking_id)."'";
  693. $this->EE->db->query($sql);
  694. }
  695. }
  696. // ------------------------------------------------------------------------
  697. /**
  698. * Fetch custom channel field IDs
  699. */
  700. public function fetch_custom_channel_fields()
  701. {
  702. if (isset($this->EE->session->cache['channel']['custom_channel_fields']) && isset($this->EE->session->cache['channel']['date_fields'])
  703. && isset($this->EE->session->cache['channel']['relationship_fields']) && isset($this->EE->session->cache['channel']['pair_custom_fields']))
  704. {
  705. $this->cfields = $this->EE->session->cache['channel']['custom_channel_fields'];
  706. $this->dfields = $this->EE->session->cache['channel']['date_fields'];
  707. $this->rfields = $this->EE->session->cache['channel']['relationship_fields'];
  708. $this->pfields = $this->EE->session->cache['channel']['pair_custom_fields'];
  709. return;
  710. }
  711. $this->EE->load->library('api');
  712. $this->EE->api->instantiate('channel_fields');
  713. $fields = $this->EE->api_channel_fields->fetch_custom_channel_fields();
  714. $this->cfields = $fields['custom_channel_fields'];
  715. $this->dfields = $fields['date_fields'];
  716. $this->rfields = $fields['relationship_fields'];
  717. $this->pfields = $fields['pair_custom_fields'];
  718. $this->EE->session->cache['channel']['custom_channel_fields'] = $this->cfields;
  719. $this->EE->session->cache['channel']['date_fields'] = $this->dfields;
  720. $this->EE->session->cache['channel']['relationship_fields'] = $this->rfields;
  721. $this->EE->session->cache['channel']['pair_custom_fields'] = $this->pfields;
  722. }
  723. // ------------------------------------------------------------------------
  724. /**
  725. * Fetch custom member field IDs
  726. */
  727. public function fetch_custom_member_fields()
  728. {
  729. $this->EE->db->select('m_field_id, m_field_name, m_field_fmt');
  730. $query = $this->EE->db->get('member_fields');
  731. $fields_present = FALSE;
  732. $t1 = microtime(TRUE);
  733. foreach ($query->result_array() as $row)
  734. {
  735. if (strpos($this->EE->TMPL->tagdata, $row['m_field_name']) !== FALSE)
  736. {
  737. $fields_present = TRUE;
  738. }
  739. $this->mfields[$row['m_field_name']] = array($row['m_field_id'], $row['m_field_fmt']);
  740. }
  741. // If we can find no instance of the variable, then let's not process them at all.
  742. if ($fields_present === FALSE)
  743. {
  744. $this->mfields = array();
  745. }
  746. }
  747. // ------------------------------------------------------------------------
  748. /**
  749. * Fetch categories
  750. */
  751. public function fetch_categories()
  752. {
  753. if ($this->enable['category_fields'] === TRUE)
  754. {
  755. $query = $this->EE->db->query("SELECT field_id, field_name FROM exp_category_fields WHERE site_id IN ('".implode("','", $this->EE->TMPL->site_ids)."')");
  756. if ($query->num_rows() > 0)
  757. {
  758. foreach ($query->result_array() as $row)
  759. {
  760. $this->catfields[] = array('field_name' => $row['field_name'], 'field_id' => $row['field_id']);
  761. }
  762. }
  763. $field_sqla = ", cg.field_html_formatting, fd.* ";
  764. $field_sqlb = " LEFT JOIN exp_category_field_data AS fd ON fd.cat_id = c.cat_id
  765. LEFT JOIN exp_category_groups AS cg ON cg.group_id = c.group_id";
  766. }
  767. else
  768. {
  769. $field_sqla = '';
  770. $field_sqlb = '';
  771. }
  772. $sql = "SELECT c.cat_name, c.cat_url_title, c.cat_id, c.cat_image, c.cat_description, c.parent_id,
  773. p.cat_id, p.entry_id, c.group_id {$field_sqla}
  774. FROM (exp_categories AS c, exp_category_posts AS p)
  775. {$field_sqlb}
  776. WHERE c.cat_id = p.cat_id
  777. AND p.entry_id IN (";
  778. $categories = array();
  779. foreach ($this->query->result_array() as $row)
  780. {
  781. $sql .= "'".$row['entry_id']."',";
  782. $categories[] = $row['entry_id'];
  783. }
  784. $sql = substr($sql, 0, -1).')';
  785. $sql .= " ORDER BY c.group_id, c.parent_id, c.cat_order";
  786. $query = $this->EE->db->query($sql);
  787. if ($query->num_rows() == 0)
  788. {
  789. return;
  790. }
  791. foreach ($categories as $val)
  792. {
  793. $this->temp_array = array();
  794. $this->cat_array = array();
  795. $parents = array();
  796. foreach ($query->result_array() as $row)
  797. {
  798. if ($val == $row['entry_id'])
  799. {
  800. $this->temp_array[$row['cat_id']] = array($row['cat_id'], $row['parent_id'], $row['cat_name'], $row['cat_image'], $row['cat_description'], $row['group_id'], $row['cat_url_title']);
  801. foreach ($row as $k => $v)
  802. {
  803. if (strpos($k, 'field') !== FALSE)
  804. {
  805. $this->temp_array[$row['cat_id']][$k] = $v;
  806. }
  807. }
  808. if ($row['parent_id'] > 0 && ! isset($this->temp_array[$row['parent_id']])) $parents[$row['parent_id']] = '';
  809. unset($parents[$row['cat_id']]);
  810. }
  811. }
  812. if (count($this->temp_array) == 0)
  813. {
  814. $temp = FALSE;
  815. }
  816. else
  817. {
  818. foreach($this->temp_array as $k => $v)
  819. {
  820. if (isset($parents[$v[1]])) $v[1] = 0;
  821. if (0 == $v[1])
  822. {
  823. $this->cat_array[] = $this->temp_array[$k];
  824. $this->process_subcategories($k);
  825. }
  826. }
  827. }
  828. $this->categories[$val] = $this->cat_array;
  829. }
  830. unset($this->temp_array);
  831. unset($this->cat_array);
  832. }
  833. // ------------------------------------------------------------------------
  834. /****************************************************************
  835. * Field Searching
  836. *
  837. * Generate the sql for the where clause to implement field
  838. * searching. Implements cross site field searching with a
  839. * sloppy search, IE if there are any fields with the same name
  840. * in any of the sites specified in the [ site="" ] parameter then
  841. * all of those fields will be searched.
  842. *
  843. *****************************************************************/
  844. protected function generate_field_search_sql($search_fields, $site_ids)
  845. {
  846. $sql = '';
  847. foreach ($search_fields as $field_name => $search_terms)
  848. {
  849. $fields_sql = '';
  850. $sites = ($site_ids ? $site_ids : array($this->EE->config->item('site_id')));
  851. foreach ($sites as $site_name => $site_id)
  852. {
  853. $terms = $search_terms;
  854. if ( ! isset($this->cfields[$site_id][$field_name]))
  855. {
  856. continue;
  857. }
  858. if (strncmp($terms, '=', 1) == 0)
  859. {
  860. /** ---------------------------------------
  861. /** Exact Match e.g.: search:body="=pickle"
  862. /** ---------------------------------------*/
  863. $terms = substr($terms, 1);
  864. // special handling for IS_EMPTY
  865. if (strpos($terms, 'IS_EMPTY') !== FALSE)
  866. {
  867. // Did this because I don't like repeatedly checking
  868. // the beginning of the string with strncmp for that
  869. // 'not', much prefer to do it once and then set a
  870. // boolean. But..
  871. $not = false;
  872. if (strncmp($terms, 'not ', 4) == 0)
  873. {
  874. $not = true;
  875. $terms = substr($terms, 4);
  876. }
  877. if (strpos($terms, '|') !== false)
  878. {
  879. $terms = str_replace('IS_EMPTY|', '', $terms);
  880. }
  881. else
  882. {
  883. $terms = str_replace('IS_EMPTY', '', $terms);
  884. }
  885. $add_search = '';
  886. $conj = '';
  887. if ( ! empty($terms))
  888. {
  889. // ...it makes this a little hacky. Gonna leave it for the moment,
  890. // but may come back to it.
  891. $add_search = $this->EE->functions->sql_andor_string(($not ? 'not ' . $terms : $terms), 'wd.field_id_'.$this->cfields[$site_id][$field_name]);
  892. // remove the first AND output by $this->EE->functions->sql_andor_string() so we can parenthesize this clause
  893. $add_search = '(wd.site_id=' . $site_id . ' AND ' . substr($add_search, 3) . ')';
  894. $conj = ($add_search != '' && !$not) ? 'OR' : 'AND';
  895. }
  896. if ($not)
  897. {
  898. $fields_sql .= $add_search.' '.$conj.' (wd.site_id=' . $site_id . ' AND wd.field_id_'.$this->cfields[$site_id][$field_name].' != "")';
  899. }
  900. else
  901. {
  902. $fields_sql .= $add_search.' '.$conj.' (wd.site_id=' . $site_id . ' AND wd.field_id_'.$this->cfields[$site_id][$field_name].' = "")';
  903. }
  904. }
  905. else
  906. {
  907. $fields_sql .= substr($this->EE->functions->sql_andor_string($terms, 'wd.field_id_'.$this->cfields[$site_id][$field_name]), 3).' ';
  908. }
  909. }
  910. else
  911. {
  912. /** ---------------------------------------
  913. /** "Contains" e.g.: search:body="pickle"
  914. /** ---------------------------------------*/
  915. $not = '';
  916. if (strncmp($terms, 'not ', 4) == 0)
  917. {
  918. $terms = substr($terms, 4);
  919. $not = 'NOT';
  920. }
  921. if (strpos($terms, '&&') !== FALSE)
  922. {
  923. $terms = explode('&&', $terms);
  924. $andor = $not == 'NOT' ? 'OR' : 'AND';
  925. }
  926. else
  927. {
  928. $terms = explode('|', $terms);
  929. $andor = $not == 'NOT' ? 'AND' : 'OR';
  930. }
  931. foreach ($terms as $term)
  932. {
  933. if ($term == 'IS_EMPTY')
  934. {
  935. $fields_sql .= ' (wd.site_id=' . $site_id
  936. . ' AND wd.field_id_' . $this->cfields[$site_id][$field_name] . ($not=='NOT' ? '!' : '') . '="") '
  937. . $andor;
  938. }
  939. elseif (strpos($term, '\W') !== FALSE) // full word only, no partial matches
  940. {
  941. // Note: MySQL's nutty POSIX regex word boundary is [[:>:]]
  942. $term = '([[:<:]]|^)'.preg_quote(str_replace('\W', '', $term)).'([[:>:]]|$)';
  943. $fields_sql .= ' (wd.site_id=' . $site_id
  944. . ' AND wd.field_id_' . $this->cfields[$site_id][$field_name] . ' ' . $not
  945. . ' REGEXP "' . $this->EE->db->escape_str($term).'") '
  946. . $andor;
  947. }
  948. else
  949. {
  950. $fields_sql .= ' (wd.site_id=' . $site_id
  951. . ' AND wd.field_id_' . $this->cfields[$site_id][$field_name] . ' '
  952. . $not . ' LIKE "%' . $this->EE->db->escape_like_str($term) . '%") '
  953. . $andor;
  954. }
  955. }
  956. // Remove the extra "and" or "or".
  957. $fields_sql = substr($fields_sql, 0, -strlen($andor));
  958. }
  959. $fields_sql .= ' OR ';
  960. } // foreach($sites as $site_id)
  961. if ( ! empty($fields_sql))
  962. {
  963. $sql .= 'AND (' . substr($fields_sql, 0, -3) . ')';
  964. }
  965. }
  966. return $sql;
  967. }
  968. /**
  969. * Build SQL query
  970. */
  971. public function build_sql_query($qstring = '')
  972. {
  973. $entry_id = '';
  974. $year = '';
  975. $month = '';
  976. $day = '';
  977. $qtitle = '';
  978. $cat_id = '';
  979. $corder = array();
  980. $offset = 0;
  981. $page_marker = FALSE;
  982. $dynamic = TRUE;
  983. $this->pagination->dynamic_sql = TRUE;
  984. /**------
  985. /** Is dynamic='off' set?
  986. /**------*/
  987. // If so, we'll override all dynamically set variables
  988. if ($this->EE->TMPL->fetch_param('dynamic') == 'no')
  989. {
  990. $dynamic = FALSE;
  991. }
  992. /**------
  993. /** Do we allow dynamic POST variables to set parameters?
  994. /**------*/
  995. if ($this->EE->TMPL->fetch_param('dynamic_parameters') !== FALSE AND isset($_POST) AND count($_POST) > 0)
  996. {
  997. foreach (explode('|', $this->EE->TMPL->fetch_param('dynamic_parameters')) as $var)
  998. {
  999. if (isset($_POST[$var]) AND in_array($var, $this->_dynamic_parameters))
  1000. {
  1001. $this->EE->TMPL->tagparams[$var] = $_POST[$var];
  1002. }
  1003. if (isset($_POST[$var]) && strncmp($var, 'search:', 7) == 0)
  1004. {
  1005. $this->EE->TMPL->search_fields[substr($var, 7)] = $_POST[$var];
  1006. }
  1007. }
  1008. }
  1009. /**------
  1010. /** Parse the URL query string
  1011. /**------*/
  1012. $this->uristr = $this->EE->uri->uri_string;
  1013. if ($qstring == '')
  1014. {
  1015. $qstring = $this->query_string;
  1016. }
  1017. $this->pagination->basepath = $this->EE->functions->create_url($this->uristr);
  1018. if ($qstring == '')
  1019. {
  1020. if ($this->EE->TMPL->fetch_param('require_entry') == 'yes')
  1021. {
  1022. return '';
  1023. }
  1024. }
  1025. else
  1026. {
  1027. /** --------------------------------------
  1028. /** Do we have a pure ID number?
  1029. /** --------------------------------------*/
  1030. if ($dynamic && is_numeric($qstring))
  1031. {
  1032. $entry_id = $qstring;
  1033. }
  1034. else
  1035. {
  1036. // Load the string helper
  1037. $this->EE->load->helper('string');
  1038. /** --------------------------------------
  1039. /** Parse day
  1040. /** --------------------------------------*/
  1041. if ($dynamic && preg_match("#(^|\/)(\d{4}/\d{2}/\d{2})#", $qstring, $match))
  1042. {
  1043. $ex = explode('/', $match[2]);
  1044. $year = $ex[0];
  1045. $month = $ex[1];
  1046. $day = $ex[2];
  1047. $qstring = trim_slashes(str_replace($match[0], '', $qstring));
  1048. }
  1049. /** --------------------------------------
  1050. /** Parse /year/month/
  1051. /** --------------------------------------*/
  1052. // added (^|\/) to make sure this doesn't trigger with url titles like big_party_2006
  1053. if ($dynamic && preg_match("#(^|\/)(\d{4}/\d{2})(\/|$)#", $qstring, $match))
  1054. {
  1055. $ex = explode('/', $match[2]);
  1056. $year = $ex[0];
  1057. $month = $ex[1];
  1058. $qstring = trim_slashes(str_replace($match[2], '', $qstring));
  1059. }
  1060. /** --------------------------------------
  1061. /** Parse ID indicator
  1062. /** --------------------------------------*/
  1063. if ($dynamic && preg_match("#^(\d+)(.*)#", $qstring, $match))
  1064. {
  1065. $seg = ( ! isset($match[2])) ? '' : $match[2];
  1066. if (substr($seg, 0, 1) == "/" OR $seg == '')
  1067. {
  1068. $entry_id = $match[1];
  1069. $qstring = trim_slashes(preg_replace("#^".$match[1]."#", '', $qstring));
  1070. }
  1071. }
  1072. /** --------------------------------------
  1073. /** Parse page number
  1074. /** --------------------------------------*/
  1075. if (($dynamic OR $this->EE->TMPL->fetch_param('paginate')) && preg_match("#^P(\d+)|/P(\d+)#", $qstring, $match))
  1076. {
  1077. $this->pagination->offset = (isset($match[2])) ? $match[2] : $match[1];
  1078. $this->pagination->basepath = $this->EE->functions->remove_double_slashes(str_replace($match[0], '', $this->pagination->basepath));
  1079. $this->uristr = $this->EE->functions->remove_double_slashes(str_replace($match[0], '', $this->uristr));
  1080. $qstring = trim_slashes(str_replace($match[0], '', $qstring));
  1081. $page_marker = TRUE;
  1082. }
  1083. /** --------------------------------------
  1084. /** Parse category indicator
  1085. /** --------------------------------------*/
  1086. // Text version of the category
  1087. if ($qstring != '' AND $this->reserved_cat_segment != '' AND in_array($this->reserved_cat_segment, explode("/", $qstring)) AND $dynamic AND $this->EE->TMPL->fetch_param('channel'))
  1088. {
  1089. $qstring = preg_replace("/(.*?)\/".preg_quote($this->reserved_cat_segment)."\//i", '', '/'.$qstring);
  1090. $sql = "SELECT DISTINCT cat_group FROM exp_channels WHERE site_id IN ('".implode("','", $this->EE->TMPL->site_ids)."') AND ";
  1091. $xsql = $this->EE->functions->sql_andor_string($this->EE->TMPL->fetch_param('channel'), 'channel_name');
  1092. if (substr($xsql, 0, 3) == 'AND') $xsql = substr($xsql, 3);
  1093. $sql .= ' '.$xsql;
  1094. $query = $this->EE->db->query($sql);
  1095. if ($query->num_rows() > 0)
  1096. {
  1097. $valid = 'y';
  1098. $valid_cats = explode('|', $query->row('cat_group') );
  1099. foreach($query->result_array() as $row)
  1100. {
  1101. if ($this->EE->TMPL->fetch_param('relaxed_categories') == 'yes')
  1102. {
  1103. $valid_cats = array_merge($valid_cats, explode('|', $row['cat_group']));
  1104. }
  1105. else
  1106. {
  1107. $valid_cats = array_intersect($valid_cats, explode('|', $row['cat_group']));
  1108. }
  1109. $valid_cats = array_unique($valid_cats);
  1110. if (count($valid_cats) == 0)
  1111. {
  1112. $valid = 'n';
  1113. break;
  1114. }
  1115. }
  1116. }
  1117. else
  1118. {
  1119. $valid = 'n';
  1120. }
  1121. if ($valid == 'y')
  1122. {
  1123. // the category URL title should be the first segment left at this point in $qstring,
  1124. // but because prior to this feature being added, category names were used in URLs,
  1125. // and '/' is a valid character for category names. If they have not updated their
  1126. // category url titles since updating to 1.6, their category URL title could still
  1127. // contain a '/'. So we'll try to get the category the correct way first, and if
  1128. // it fails, we'll try the whole $qstring
  1129. // do this as separate commands to work around a PHP 5.0.x bug
  1130. $arr = explode('/', $qstring);
  1131. $cut_qstring = array_shift($arr);
  1132. unset($arr);
  1133. $result = $this->EE->db->query("SELECT cat_id FROM exp_categories
  1134. WHERE cat_url_title='".$this->EE->db->escape_str($cut_qstring)."'
  1135. AND group_id IN ('".implode("','", $valid_cats)."')");
  1136. if ($result->num_rows() == 1)
  1137. {
  1138. $qstring = str_replace($cut_qstring, 'C'.$result->row('cat_id') , $qstring);
  1139. $cat_id = $result->row('cat_id');
  1140. }
  1141. else
  1142. {
  1143. // give it one more try using the whole $qstring
  1144. $result = $this->EE->db->query("SELECT cat_id FROM exp_categories
  1145. WHERE cat_url_title='".$this->EE->db->escape_str($qstring)."'
  1146. AND group_id IN ('".implode("','", $valid_cats)."')");
  1147. if ($result->num_rows() == 1)
  1148. {
  1149. $qstring = 'C'.$result->row('cat_id') ;
  1150. $cat_id = $result->row('cat_id');
  1151. }
  1152. }
  1153. }
  1154. }
  1155. // If we got here, category may be numeric
  1156. if (empty($cat_id))
  1157. {
  1158. $this->EE->load->helper('segment');
  1159. $cat_id = parse_category($this->query_string);
  1160. }
  1161. // If we were able to get a numeric category ID
  1162. if (is_numeric($cat_id) AND $cat_id !== FALSE)
  1163. {
  1164. $this->cat_request = TRUE;
  1165. }
  1166. // parse_category did not return a numberic ID, blow away $cat_id
  1167. else
  1168. {
  1169. $cat_id = FALSE;
  1170. }
  1171. /** --------------------------------------
  1172. /** Remove "N"
  1173. /** --------------------------------------*/
  1174. // The recent comments feature uses "N" as the URL indicator
  1175. // It needs to be removed if presenst
  1176. if (preg_match("#^N(\d+)|/N(\d+)#", $qstring, $match))
  1177. {
  1178. $this->uristr = $this->EE->functions->remove_double_slashes(str_replace($match[0], '', $this->uristr));
  1179. $qstring = trim_slashes(str_replace($match[0], '', $qstring));
  1180. }
  1181. /** --------------------------------------
  1182. /** Parse URL title
  1183. /** --------------------------------------*/
  1184. if (($cat_id == '' AND $year == '') OR $this->EE->TMPL->fetch_param('require_entry') == 'yes')
  1185. {
  1186. if (strpos($qstring, '/') !== FALSE)
  1187. {
  1188. $xe = explode('/', $qstring);
  1189. $qstring = current($xe);
  1190. }
  1191. if ($dynamic == TRUE)
  1192. {
  1193. $sql = "SELECT count(*) AS count
  1194. FROM exp_channel_titles, exp_channels
  1195. WHERE exp_channel_titles.channel_id = exp_channels.channel_id";
  1196. if ($entry_id != '')
  1197. {
  1198. $sql .= " AND exp_channel_titles.entry_id = '".$this->EE->db->escape_str($entry_id)."'";
  1199. }
  1200. else
  1201. {
  1202. $sql .= " AND exp_channel_titles.url_title = '".$this->EE->db->escape_str($qstring)."'";
  1203. }
  1204. $sql .= " AND exp_channels.site_id IN ('".implode("','", $this->EE->TMPL->site_ids)."') ";
  1205. $query = $this->EE->db->query($sql);
  1206. if ($query->row('count') == 0)
  1207. {
  1208. if ($this->EE->TMPL->fetch_param('require_entry') == 'yes')
  1209. {
  1210. return '';
  1211. }
  1212. $qtitle = '';
  1213. }
  1214. else
  1215. {
  1216. $qtitle = $qstring;
  1217. }
  1218. }
  1219. }
  1220. }
  1221. }
  1222. /**------
  1223. /** Entry ID number
  1224. /**------*/
  1225. // If the "entry ID" was hard-coded, use it instead of
  1226. // using the dynamically set one above
  1227. if ($this->EE->TMPL->fetch_param('entry_id'))
  1228. {
  1229. $entry_id = $this->EE->TMPL->fetch_param('entry_id');
  1230. }
  1231. /**------
  1232. /** Only Entries with Pages
  1233. /**------*/
  1234. if ($this->EE->TMPL->fetch_param('show_pages') !== FALSE && in_array($this->EE->TMPL->fetch_param('show_pages'), array('only', 'no')) && ($pages = $this->EE->config->item('site_pages')) !== FALSE)
  1235. {
  1236. $pages_uris = array();
  1237. foreach ($pages as $data)
  1238. {
  1239. $pages_uris += $data['uris'];
  1240. }
  1241. if (count($pages_uris) > 0 OR $this->EE->TMPL->fetch_param('show_pages') == 'only')
  1242. {
  1243. // consider entry_id
  1244. if ($this->EE->TMPL->fetch_param('entry_id') !== FALSE)
  1245. {
  1246. $not = FALSE;
  1247. if (strncmp($entry_id, 'not', 3) == 0)
  1248. {
  1249. $not = TRUE;
  1250. $entry_id = trim(substr($entry_id, 3));
  1251. }
  1252. $ids = explode('|', $entry_id);
  1253. if ($this->EE->TMPL->fetch_param('show_pages') == 'only')
  1254. {
  1255. if ($not === TRUE)
  1256. {
  1257. $entry_id = implode('|', array_diff(array_flip($pages_uris), explode('|', $ids)));
  1258. }
  1259. else
  1260. {
  1261. $entry_id = implode('|',array_diff($ids, array_diff($ids, array_flip($pages_uris))));
  1262. }
  1263. }
  1264. else
  1265. {
  1266. if ($not === TRUE)
  1267. {
  1268. $entry_id = "not {$entry_id}|".implode('|', array_flip($pages_uris));
  1269. }
  1270. else
  1271. {
  1272. $entry_id = implode('|',array_diff($ids, array_flip($pages_uris)));
  1273. }
  1274. }
  1275. }
  1276. else
  1277. {
  1278. $entry_id = (($this->EE->TMPL->fetch_param('show_pages') == 'no') ? 'not ' : '').implode('|', array_flip($pages_uris));
  1279. }
  1280. // No pages and show_pages only
  1281. if ($entry_id == '' && $this->EE->TMPL->fetch_param('show_pages') == 'only')
  1282. {
  1283. $this->sql = '';
  1284. return;
  1285. }
  1286. }
  1287. }
  1288. /**------
  1289. /** Assing the order variables
  1290. /**------*/
  1291. $order = $this->EE->TMPL->fetch_param('orderby');
  1292. $sort = $this->EE->TMPL->fetch_param('sort');
  1293. $sticky = $this->EE->TMPL->fetch_param('sticky');
  1294. /** -------------------------------------
  1295. /** Multiple Orders and Sorts...
  1296. /** -------------------------------------*/
  1297. if ($order !== FALSE && stristr($order, '|'))
  1298. {
  1299. $order_array = explode('|', $order);
  1300. if ($order_array[0] == 'random')
  1301. {
  1302. $order_array = array('random');
  1303. }
  1304. }
  1305. else
  1306. {
  1307. $order_array = array($order);
  1308. }
  1309. if ($sort !== FALSE && stristr($sort, '|'))
  1310. {
  1311. $sort_array = explode('|', $sort);
  1312. }
  1313. else
  1314. {
  1315. $sort_array = array($sort);
  1316. }
  1317. /** -------------------------------------
  1318. /** Validate Results for Later Processing
  1319. /** -------------------------------------*/
  1320. $base_orders = array('status', 'random', 'entry_id', 'date', 'entry_date', 'title', 'url_title', 'edit_date', 'comment_total', 'username', 'screen_name', 'most_recent_comment', 'expiration_date',
  1321. 'view_count_one', 'view_count_two', 'view_count_three', 'view_count_four');
  1322. foreach($order_array as $key => $order)
  1323. {
  1324. if ( ! in_array($order, $base_orders))
  1325. {
  1326. if (FALSE !== $order)
  1327. {
  1328. $set = 'n';
  1329. /** -------------------------------------
  1330. /** Site Namespace is Being Used, Parse Out
  1331. /** -------------------------------------*/
  1332. if (strpos($order, ':') !== FALSE)
  1333. {
  1334. $order_parts = explode(':', $order, 2);
  1335. if (isset($this->EE->TMPL->site_ids[$order_parts[0]]) && isset($this->cfields[$this->EE->TMPL->site_ids[$order_parts[0]]][$order_parts[1]]))
  1336. {
  1337. $corder[$key] = $this->cfields[$this->EE->TMPL->site_ids[$order_parts[0]]][$order_parts[1]];
  1338. $order_array[$key] = 'custom_field';
  1339. $set = 'y';
  1340. }
  1341. }
  1342. /** -------------------------------------
  1343. /** Find the Custom Field, Cycle Through All Sites for Tag
  1344. /** - If multiple sites have the same short_name for a field, we do a CONCAT ORDERBY in query
  1345. /** -------------------------------------*/
  1346. if ($set == 'n')
  1347. {
  1348. foreach($this->cfields as $site_id => $cfields)
  1349. {
  1350. // Only those sites specified
  1351. if ( ! in_array($site_id, $this->EE->TMPL->site_ids))
  1352. {
  1353. continue;
  1354. }
  1355. if (isset($cfields[$order]))
  1356. {
  1357. if ($set == 'y')
  1358. {
  1359. $corder[$key] .= '|'.$cfields[$order];
  1360. }
  1361. else
  1362. {
  1363. $corder[$key] = $cfields[$order];
  1364. $order_array[$key] = 'custom_field';
  1365. $set = 'y';
  1366. }
  1367. }
  1368. }
  1369. }
  1370. if ($set == 'n')
  1371. {
  1372. $order_array[$key] = FALSE;
  1373. }
  1374. }
  1375. }
  1376. if ( ! isset($sort_array[$key]))
  1377. {
  1378. $sort_array[$key] = 'desc';
  1379. }
  1380. }
  1381. foreach($sort_array as $key => $sort)
  1382. {
  1383. if ($sort == FALSE OR ($sort != 'asc' AND $sort != 'desc'))
  1384. {
  1385. $sort_array[$key] = "desc";
  1386. }
  1387. }
  1388. // fixed entry id ordering
  1389. if (($fixed_order = $this->EE->TMPL->fetch_param('fixed_order')) === FALSE OR preg_match('/[^0-9\|]/', $fixed_order))
  1390. {
  1391. $fixed_order = FALSE;
  1392. }
  1393. else
  1394. {
  1395. // MySQL will not order the entries correctly unless the results are constrained
  1396. // to matching rows only, so we force the entry_id as well
  1397. $entry_id = $fixed_order;
  1398. $fixed_order = preg_split('/\|/', $fixed_order, -1, PREG_SPLIT_NO_EMPTY);
  1399. // some peeps might want to be able to 'flip' it
  1400. // the default sort order is 'desc' but in this context 'desc' has a stronger "reversing"
  1401. // connotation, so we look not at the sort array, but the tag parameter itself, to see the user's intent
  1402. if ($sort == 'desc')
  1403. {
  1404. $fixed_order = array_reverse($fixed_order);
  1405. }
  1406. }
  1407. /**------
  1408. /** Build the master SQL query
  1409. /**------*/
  1410. $sql_a = "SELECT ";
  1411. $sql_b = ($this->EE->TMPL->fetch_param('category') OR $this->EE->TMPL->fetch_param('category_group') OR $cat_id != '' OR $order_array[0] == 'random') ? "DISTINCT(t.entry_id) " : "t.entry_id ";
  1412. if ($this->pagination->field_pagination == TRUE)
  1413. {
  1414. $sql_b .= ",wd.* ";
  1415. }
  1416. $sql_c = "COUNT(t.entry_id) AS count ";
  1417. $sql = "FROM exp_channel_titles AS t
  1418. LEFT JOIN exp_channels ON t.channel_id = exp_channels.channel_id ";
  1419. if ($this->pagination->field_pagination == TRUE)
  1420. {
  1421. $sql .= "LEFT JOIN exp_channel_data AS wd ON t.entry_id = wd.entry_id ";
  1422. }
  1423. elseif (in_array('custom_field', $order_array))
  1424. {
  1425. $sql .= "LEFT JOIN exp_channel_data AS wd ON t.entry_id = wd.entry_id ";
  1426. }
  1427. elseif ( ! empty($this->EE->TMPL->search_fields))
  1428. {
  1429. $sql .= "LEFT JOIN exp_channel_data AS wd ON wd.entry_id = t.entry_id ";
  1430. }
  1431. $sql .= "LEFT JOIN exp_members AS m ON m.member_id = t.author_id ";
  1432. if ($this->EE->TMPL->fetch_param('category') OR $this->EE->TMPL->fetch_param('category_group') OR ($cat_id != '' && $dynamic == TRUE))
  1433. {
  1434. /* --------------------------------
  1435. /* We use LEFT JOIN when there is a 'not' so that we get
  1436. /* entries that are not assigned to a category.
  1437. /* --------------------------------*/
  1438. if ((substr($this->EE->TMPL->fetch_param('category_group'), 0, 3) == 'not' OR substr($this->EE->TMPL->fetch_param('category'), 0, 3) == 'not') && $this->EE->TMPL->fetch_param('uncategorized_entries') !== 'no')
  1439. {
  1440. $sql .= "LEFT JOIN exp_category_posts ON t.entry_id = exp_category_posts.entry_id
  1441. LEFT JOIN exp_categories ON exp_category_posts.cat_id = exp_categories.cat_id ";
  1442. }
  1443. else
  1444. {
  1445. $sql .= "INNER JOIN exp_category_posts ON t.entry_id = exp_category_posts.entry_id
  1446. INNER JOIN exp_categories ON exp_category_posts.cat_id = exp_categories.cat_id ";
  1447. }
  1448. }
  1449. $sql .= "WHERE t.entry_id !='' AND t.site_id IN ('".implode("','", $this->EE->TMPL->site_ids)."') ";
  1450. /**------
  1451. /** We only select entries that have not expired
  1452. /**------*/
  1453. $timestamp = ($this->EE->TMPL->cache_timestamp != '') ? $this->EE->TMPL->cache_timestamp : $this->EE->localize->now;
  1454. if ($this->EE->TMPL->fetch_param('show_future_entries') != 'yes')
  1455. {
  1456. $sql .= " AND t.entry_date < ".$timestamp." ";
  1457. }
  1458. if ($this->EE->TMPL->fetch_param('show_expired') != 'yes')
  1459. {
  1460. $sql .= " AND (t.expiration_date = 0 OR t.expiration_date > ".$timestamp.") ";
  1461. }
  1462. /**------
  1463. /** Limit query by post ID for individual entries
  1464. /**------*/
  1465. if ($entry_id != '')
  1466. {
  1467. $sql .= $this->EE->functions->sql_andor_string($entry_id, 't.entry_id').' ';
  1468. }
  1469. /**------
  1470. /** Limit query by post url_title for individual entries
  1471. /**------*/
  1472. if ($url_title = $this->EE->TMPL->fetch_param('url_title'))
  1473. {
  1474. $sql .= $this->EE->functions->sql_andor_string($url_title, 't.url_title').' ';
  1475. }
  1476. /**------
  1477. /** Limit query by entry_id range
  1478. /**------*/
  1479. if ($entry_id_from = $this->EE->TMPL->fetch_param('entry_id_from'))
  1480. {
  1481. $sql .= "AND t.entry_id >= '$entry_id_from' ";
  1482. }
  1483. if ($entry_id_to = $this->EE->TMPL->fetch_param('entry_id_to'))
  1484. {
  1485. $sql .= "AND t.entry_id <= '$entry_id_to' ";
  1486. }
  1487. /**------
  1488. /** Exclude an individual entry
  1489. /**------*/
  1490. if ($not_entry_id = $this->EE->TMPL->fetch_param('not_entry_id'))
  1491. {
  1492. $sql .= ( ! is_numeric($not_entry_id))
  1493. ? "AND t.url_title != '{$not_entry_id}' "
  1494. : "AND t.entry_id != '{$not_entry_id}' ";
  1495. }
  1496. /**------
  1497. /** Limit to/exclude specific channels
  1498. /**------*/
  1499. if ($channel = $this->EE->TMPL->fetch_param('channel'))
  1500. {
  1501. $xql = "SELECT channel_id FROM exp_channels WHERE ";
  1502. $str = $this->EE->functions->sql_andor_string($channel, 'channel_name');
  1503. if (substr($str, 0, 3) == 'AND')
  1504. {
  1505. $str = substr($str, 3);
  1506. }
  1507. $xql .= $str;
  1508. $query = $this->EE->db->query($xql);
  1509. if ($query->num_rows() == 0)
  1510. {
  1511. return '';
  1512. }
  1513. else
  1514. {
  1515. if ($query->num_rows() == 1)
  1516. {
  1517. $sql .= "AND t.channel_id = '".$query->row('channel_id') ."' ";
  1518. }
  1519. else
  1520. {
  1521. $sql .= "AND (";
  1522. foreach ($query->result_array() as $row)
  1523. {
  1524. $sql .= "t.channel_id = '".$row['channel_id']."' OR ";
  1525. }
  1526. $sql = substr($sql, 0, - 3);
  1527. $sql .= ") ";
  1528. }
  1529. }
  1530. }
  1531. /**------------
  1532. /** Limit query by date range given in tag parameters
  1533. /**------------*/
  1534. if ($this->EE->TMPL->fetch_param('start_on'))
  1535. {
  1536. $sql .= "AND t.entry_date >= '".$this->EE->localize->convert_human_date_to_gmt($this->EE->TMPL->fetch_param('start_on'))."' ";
  1537. }
  1538. if ($this->EE->TMPL->fetch_param('stop_before'))
  1539. {
  1540. $sql .= "AND t.entry_date < '".$this->EE->localize->convert_human_date_to_gmt($this->EE->TMPL->fetch_param('stop_before'))."' ";
  1541. }
  1542. /**-------------
  1543. /** Limit query by date contained in tag parameters
  1544. /**-------------*/
  1545. if ($this->EE->TMPL->fetch_param('year') OR $this->EE->TMPL->fetch_param('month') OR $this->EE->TMPL->fetch_param('day'))
  1546. {
  1547. $year = ( ! is_numeric($this->EE->TMPL->fetch_param('year'))) ? date('Y') : $this->EE->TMPL->fetch_param('year');
  1548. $smonth = ( ! is_numeric($this->EE->TMPL->fetch_param('month'))) ? '01' : $this->EE->TMPL->fetch_param('month');
  1549. $emonth = ( ! is_numeric($this->EE->TMPL->fetch_param('month'))) ? '12': $this->EE->TMPL->fetch_param('month');
  1550. $day = ( ! is_numeric($this->EE->TMPL->fetch_param('day'))) ? '' : $this->EE->TMPL->fetch_param('day');
  1551. if ($day != '' AND ! is_numeric($this->EE->TMPL->fetch_param('month')))
  1552. {
  1553. $smonth = date('m');
  1554. $emonth = date('m');
  1555. }
  1556. if (strlen($smonth) == 1)
  1557. {
  1558. $smonth = '0'.$smonth;
  1559. }
  1560. if (strlen($emonth) == 1)
  1561. {
  1562. $emonth = '0'.$emonth;
  1563. }
  1564. if ($day == '')
  1565. {
  1566. $sday = 1;
  1567. $eday = $this->EE->localize->fetch_days_in_month($emonth, $year);
  1568. }
  1569. else
  1570. {
  1571. $sday = $day;
  1572. $eday = $day;
  1573. }
  1574. $stime = gmmktime(0, 0, 0, $smonth, $sday, $year);
  1575. $etime = gmmktime(23, 59, 59, $emonth, $eday, $year);
  1576. $sql .= " AND t.entry_date >= ".$stime." AND t.entry_date <= ".$etime." ";
  1577. }
  1578. else
  1579. {
  1580. /**--------
  1581. /** Limit query by date in URI: /2003/12/14/
  1582. /**---------*/
  1583. if ($year != '' AND $month != '' AND $dynamic == TRUE)
  1584. {
  1585. if ($day == '')
  1586. {
  1587. $sday = 1;
  1588. $eday = $this->EE->localize->fetch_days_in_month($month, $year);
  1589. }
  1590. else
  1591. {
  1592. $sday = $day;
  1593. $eday = $day;
  1594. }
  1595. $stime = gmmktime(0, 0, 0, $month, $sday, $year);
  1596. $etime = gmmktime(23, 59, 59, $month, $eday, $year);
  1597. if (date("I", $this->EE->localize->now) AND ! date("I", $stime))
  1598. {
  1599. $stime -= 3600;
  1600. }
  1601. elseif ( ! date("I", $this->EE->localize->now) AND date("I", $stime))
  1602. {
  1603. $stime += 3600;
  1604. }
  1605. $stime += $this->EE->localize->set_localized_offset();
  1606. if (date("I", $this->EE->localize->now) AND ! date("I", $etime))
  1607. {
  1608. $etime -= 3600;
  1609. }
  1610. elseif ( ! date("I", $this->EE->localize->now) AND date("I", $etime))
  1611. {
  1612. $etime += 3600;
  1613. }
  1614. $etime += $this->EE->localize->set_localized_offset();
  1615. $sql .= " AND t.entry_date >= ".$stime." AND t.entry_date <= ".$etime." ";
  1616. }
  1617. else
  1618. {
  1619. $this->display_by = $this->EE->TMPL->fetch_param('display_by');
  1620. $lim = ( ! is_numeric($this->EE->TMPL->fetch_param('limit'))) ? '1' : $this->EE->TMPL->fetch_param('limit');
  1621. /**---
  1622. /** If display_by = "month"
  1623. /**---*/
  1624. if ($this->display_by == 'month')
  1625. {
  1626. // We need to run a query and fetch the distinct months in which there are entries
  1627. $dql = "SELECT t.year, t.month ".$sql;
  1628. /**------
  1629. /** Add status declaration
  1630. /**------*/
  1631. if ($status = $this->EE->TMPL->fetch_param('status'))
  1632. {
  1633. $status = str_replace('Open', 'open', $status);
  1634. $status = str_replace('Closed', 'closed', $status);
  1635. $sstr = $this->EE->functions->sql_andor_string($status, 't.status');
  1636. if (stristr($sstr, "'closed'") === FALSE)
  1637. {
  1638. $sstr .= " AND t.status != 'closed' ";
  1639. }
  1640. $dql .= $sstr;
  1641. }
  1642. else
  1643. {
  1644. $dql .= "AND t.status = 'open' ";
  1645. }
  1646. $query = $this->EE->db->query($dql);
  1647. $distinct = array();
  1648. if ($query->num_rows() > 0)
  1649. {
  1650. foreach ($query->result_array() as $row)
  1651. {
  1652. $distinct[] = $row['year'].$row['month'];
  1653. }
  1654. $distinct = array_unique($distinct);
  1655. sort($distinct);
  1656. if ($sort_array[0] == 'desc')
  1657. {
  1658. $distinct = array_reverse($distinct);
  1659. }
  1660. $this->pagination->total_rows = count($distinct);
  1661. $cur = ($this->pagination->offset == '') ? 0 : $this->pagination->offset;
  1662. $distinct = array_slice($distinct, $cur, $lim);
  1663. if ($distinct != FALSE)
  1664. {
  1665. $sql .= "AND (";
  1666. foreach ($distinct as $val)
  1667. {
  1668. $sql .= "(t.year = '".substr($val, 0, 4)."' AND t.month = '".substr($val, 4, 2)."') OR";
  1669. }
  1670. $sql = substr($sql, 0, -2).')';
  1671. }
  1672. }
  1673. }
  1674. /**---
  1675. /** If display_by = "day"
  1676. /**---*/
  1677. elseif ($this->display_by == 'day')
  1678. {
  1679. // We need to run a query and fetch the distinct days in which there are entries
  1680. $dql = "SELECT t.year, t.month, t.day ".$sql;
  1681. /**------
  1682. /** Add status declaration
  1683. /**------*/
  1684. if ($status = $this->EE->TMPL->fetch_param('status'))
  1685. {
  1686. $status = str_replace('Open', 'open', $status);
  1687. $status = str_replace('Closed', 'closed', $status);
  1688. $sstr = $this->EE->functions->sql_andor_string($status, 't.status');
  1689. if (stristr($sstr, "'closed'") === FALSE)
  1690. {
  1691. $sstr .= " AND t.status != 'closed' ";
  1692. }
  1693. $dql .= $sstr;
  1694. }
  1695. else
  1696. {
  1697. $dql .= "AND t.status = 'open' ";
  1698. }
  1699. $query = $this->EE->db->query($dql);
  1700. $distinct = array();
  1701. if ($query->num_rows() > 0)
  1702. {
  1703. foreach ($query->result_array() as $row)
  1704. {
  1705. $distinct[] = $row['year'].$row['month'].$row['day'];
  1706. }
  1707. $distinct = array_unique($distinct);
  1708. sort($distinct);
  1709. if ($sort_array[0] == 'desc')
  1710. {
  1711. $distinct = array_reverse($distinct);
  1712. }
  1713. $this->pagination->total_rows = count($distinct);
  1714. $cur = ($this->pagination->offset == '') ? 0 : $this->pagination->offset;
  1715. $distinct = array_slice($distinct, $cur, $lim);
  1716. if ($distinct != FALSE)
  1717. {
  1718. $sql .= "AND (";
  1719. foreach ($distinct as $val)
  1720. {
  1721. $sql .= "(t.year = '".substr($val, 0, 4)."' AND t.month = '".substr($val, 4, 2)."' AND t.day = '".substr($val, 6)."' ) OR";
  1722. }
  1723. $sql = substr($sql, 0, -2).')';
  1724. }
  1725. }
  1726. }
  1727. /**---
  1728. /** If display_by = "week"
  1729. /**---*/
  1730. elseif ($this->display_by == 'week')
  1731. {
  1732. /** ---------------------------------
  1733. /* Run a Query to get a combined Year and Week value. There is a downside
  1734. /* to this approach and that is the lack of localization and use of DST for
  1735. /* dates. Unfortunately, without making a complex and ultimately fubar'ed
  1736. /* PHP script this is the best approach possible.
  1737. /* ---------------------------------*/
  1738. $loc_offset = $this->EE->localize->zones[$this->EE->config->item('server_timezone')] * 3600;
  1739. if ($this->EE->TMPL->fetch_param('start_day') === 'Monday')
  1740. {
  1741. $yearweek = "DATE_FORMAT(FROM_UNIXTIME(entry_date + {$loc_offset}), '%x%v') AS yearweek ";
  1742. $dql = 'SELECT '.$yearweek.$sql;
  1743. }
  1744. else
  1745. {
  1746. $yearweek = "DATE_FORMAT(FROM_UNIXTIME(entry_date + {$loc_offset}), '%X%V') AS yearweek ";
  1747. $dql = 'SELECT '.$yearweek.$sql;
  1748. }
  1749. /**------
  1750. /** Add status declaration
  1751. /**------*/
  1752. if ($status = $this->EE->TMPL->fetch_param('status'))
  1753. {
  1754. $status = str_replace('Open', 'open', $status);
  1755. $status = str_replace('Closed', 'closed', $status);
  1756. $sstr = $this->EE->functions->sql_andor_string($status, 't.status');
  1757. if (stristr($sstr, "'closed'") === FALSE)
  1758. {
  1759. $sstr .= " AND t.status != 'closed' ";
  1760. }
  1761. $dql .= $sstr;
  1762. }
  1763. else
  1764. {
  1765. $dql .= "AND t.status = 'open' ";
  1766. }
  1767. $query = $this->EE->db->query($dql);
  1768. $distinct = array();
  1769. if ($query->num_rows() > 0)
  1770. {
  1771. /** ---------------------------------
  1772. /* Sort Default is ASC for Display By Week so that entries are displayed
  1773. /* oldest to newest in the week, which is how you would expect.
  1774. /* ---------------------------------*/
  1775. if ($this->EE->TMPL->fetch_param('sort') === FALSE)
  1776. {
  1777. $sort_array[0] = 'asc';
  1778. }
  1779. foreach ($query->result_array() as $row)
  1780. {
  1781. $distinct[] = $row['yearweek'];
  1782. }
  1783. $distinct = array_unique($distinct);
  1784. rsort($distinct);
  1785. /* Old code, did nothing
  1786. *
  1787. if ($this->EE->TMPL->fetch_param('week_sort') == 'desc')
  1788. {
  1789. $distinct = array_reverse($distinct);
  1790. }
  1791. *
  1792. */
  1793. $this->pagination->total_rows = count($distinct);
  1794. $cur = ($this->pagination->offset == '') ? 0 : $this->pagination->offset;
  1795. /** ---------------------------------
  1796. /* If no pagination, then the Current Week is shown by default with
  1797. /* all pagination correctly set and ready to roll, if used.
  1798. /* ---------------------------------*/
  1799. if ($this->EE->TMPL->fetch_param('show_current_week') === 'yes' && $this->pagination->offset == '')
  1800. {
  1801. if ($this->EE->TMPL->fetch_param('start_day') === 'Monday')
  1802. {
  1803. $query = $this->EE->db->query("SELECT DATE_FORMAT(CURDATE(), '%x%v') AS thisWeek");
  1804. }
  1805. else
  1806. {
  1807. $query = $this->EE->db->query("SELECT DATE_FORMAT(CURDATE(), '%X%V') AS thisWeek");
  1808. }
  1809. foreach($distinct as $key => $week)
  1810. {
  1811. if ($week == $query->row('thisWeek') )
  1812. {
  1813. $cur = $key;
  1814. $this->pagination->offset = $key;
  1815. break;
  1816. }
  1817. }
  1818. }
  1819. $distinct = array_slice($distinct, $cur, $lim);
  1820. /** ---------------------------------
  1821. /* Finally, we add the display by week SQL to the query
  1822. /* ---------------------------------*/
  1823. if ($distinct != FALSE)
  1824. {
  1825. // A Rough Attempt to Get the Localized Offset Added On
  1826. $offset = $this->EE->localize->set_localized_offset();
  1827. $dst_on = (date("I", $this->EE->localize->now) === 1) ? TRUE : FALSE;
  1828. $sql .= "AND (";
  1829. foreach ($distinct as $val)
  1830. {
  1831. if ($dst_on === TRUE AND (substr($val, 4) < 13 OR substr($val, 4) >= 43))
  1832. {
  1833. $offset -= 3600;
  1834. }
  1835. elseif ($dst_on === FALSE AND (substr($val, 4) >= 13 AND substr($val, 4) < 43))
  1836. {
  1837. $offset += 3600;
  1838. }
  1839. $sql_offset = ($offset < 0) ? "- ".abs($offset) : "+ ".$offset;
  1840. if ($this->EE->TMPL->fetch_param('start_day') === 'Monday')
  1841. {
  1842. $sql .= " DATE_FORMAT(FROM_UNIXTIME(entry_date {$sql_offset}), '%x%v') = '".$val."' OR";
  1843. }
  1844. else
  1845. {
  1846. $sql .= " DATE_FORMAT(FROM_UNIXTIME(entry_date {$sql_offset}), '%X%V') = '".$val."' OR";
  1847. }
  1848. }
  1849. $sql = substr($sql, 0, -2).')';
  1850. }
  1851. }
  1852. }
  1853. }
  1854. }
  1855. /**------
  1856. /** Limit query "URL title"
  1857. /**------*/
  1858. if ($qtitle != '' AND $dynamic)
  1859. {
  1860. $sql .= "AND t.url_title = '".$this->EE->db->escape_str($qtitle)."' ";
  1861. // We use this with hit tracking....
  1862. $this->hit_tracking_id = $qtitle;
  1863. }
  1864. // We set a
  1865. if ($entry_id != '' AND $this->entry_id !== FALSE)
  1866. {
  1867. $this->hit_tracking_id = $entry_id;
  1868. }
  1869. /**------
  1870. /** Limit query by category
  1871. /**------*/
  1872. if ($this->EE->TMPL->fetch_param('category'))
  1873. {
  1874. if (stristr($this->EE->TMPL->fetch_param('category'), '&'))
  1875. {
  1876. /** --------------------------------------
  1877. /** First, we find all entries with these categories
  1878. /** --------------------------------------*/
  1879. $for_sql = (substr($this->EE->TMPL->fetch_param('category'), 0, 3) == 'not') ? trim(substr($this->EE->TMPL->fetch_param('category'), 3)) : $this->EE->TMPL->fetch_param('category');
  1880. $csql = "SELECT exp_category_posts.entry_id, exp_category_posts.cat_id ".
  1881. $sql.
  1882. $this->EE->functions->sql_andor_string(str_replace('&', '|', $for_sql), 'exp_categories.cat_id');
  1883. //exit($csql);
  1884. $results = $this->EE->db->query($csql);
  1885. if ($results->num_rows() == 0)
  1886. {
  1887. return;
  1888. }
  1889. $type = 'IN';
  1890. $categories = explode('&', $this->EE->TMPL->fetch_param('category'));
  1891. $entry_array = array();
  1892. if (substr($categories[0], 0, 3) == 'not')
  1893. {
  1894. $type = 'NOT IN';
  1895. $categories[0] = trim(substr($categories[0], 3));
  1896. }
  1897. foreach($results->result_array() as $row)
  1898. {
  1899. $entry_array[$row['cat_id']][] = $row['entry_id'];
  1900. }
  1901. if (count($entry_array) < 2 OR count(array_diff($categories, array_keys($entry_array))) > 0)
  1902. {
  1903. return;
  1904. }
  1905. $chosen = call_user_func_array('array_intersect', $entry_array);
  1906. if (count($chosen) == 0)
  1907. {
  1908. return;
  1909. }
  1910. $sql .= "AND t.entry_id ".$type." ('".implode("','", $chosen)."') ";
  1911. }
  1912. else
  1913. {
  1914. if (substr($this->EE->TMPL->fetch_param('category'), 0, 3) == 'not' && $this->EE->TMPL->fetch_param('uncategorized_entries') !== 'no')
  1915. {
  1916. $sql .= $this->EE->functions->sql_andor_string($this->EE->TMPL->fetch_param('category'), 'exp_categories.cat_id', '', TRUE)." ";
  1917. }
  1918. else
  1919. {
  1920. $sql .= $this->EE->functions->sql_andor_string($this->EE->TMPL->fetch_param('category'), 'exp_categories.cat_id')." ";
  1921. }
  1922. }
  1923. }
  1924. if ($this->EE->TMPL->fetch_param('category_group'))
  1925. {
  1926. if (substr($this->EE->TMPL->fetch_param('category_group'), 0, 3) == 'not' && $this->EE->TMPL->fetch_param('uncategorized_entries') !== 'no')
  1927. {
  1928. $sql .= $this->EE->functions->sql_andor_string($this->EE->TMPL->fetch_param('category_group'), 'exp_categories.group_id', '', TRUE)." ";
  1929. }
  1930. else
  1931. {
  1932. $sql .= $this->EE->functions->sql_andor_string($this->EE->TMPL->fetch_param('category_group'), 'exp_categories.group_id')." ";
  1933. }
  1934. }
  1935. if ($this->EE->TMPL->fetch_param('category') === FALSE && $this->EE->TMPL->fetch_param('category_group') === FALSE)
  1936. {
  1937. if ($cat_id != '' AND $dynamic)
  1938. {
  1939. $sql .= " AND exp_categories.cat_id = '".$this->EE->db->escape_str($cat_id)."' ";
  1940. }
  1941. }
  1942. /**------
  1943. /** Limit to (or exclude) specific users
  1944. /**------*/
  1945. if ($username = $this->EE->TMPL->fetch_param('username'))
  1946. {
  1947. // Shows entries ONLY for currently logged in user
  1948. if ($username == 'CURRENT_USER')
  1949. {
  1950. $sql .= "AND m.member_id = '".$this->EE->session->userdata('member_id')."' ";
  1951. }
  1952. elseif ($username == 'NOT_CURRENT_USER')
  1953. {
  1954. $sql .= "AND m.member_id != '".$this->EE->session->userdata('member_id')."' ";
  1955. }
  1956. else
  1957. {
  1958. $sql .= $this->EE->functions->sql_andor_string($username, 'm.username');
  1959. }
  1960. }
  1961. /**------
  1962. /** Limit to (or exclude) specific author id(s)
  1963. /**------*/
  1964. if ($author_id = $this->EE->TMPL->fetch_param('author_id'))
  1965. {
  1966. // Shows entries ONLY for currently logged in user
  1967. if ($author_id == 'CURRENT_USER')
  1968. {
  1969. $sql .= "AND m.member_id = '".$this->EE->session->userdata('member_id')."' ";
  1970. }
  1971. elseif ($author_id == 'NOT_CURRENT_USER')
  1972. {
  1973. $sql .= "AND m.member_id != '".$this->EE->session->userdata('member_id')."' ";
  1974. }
  1975. else
  1976. {
  1977. $sql .= $this->EE->functions->sql_andor_string($author_id, 'm.member_id');
  1978. }
  1979. }
  1980. /**------
  1981. /** Add status declaration
  1982. /**------*/
  1983. if ($status = $this->EE->TMPL->fetch_param('status'))
  1984. {
  1985. $status = str_replace('Open', 'open', $status);
  1986. $status = str_replace('Closed', 'closed', $status);
  1987. $sstr = $this->EE->functions->sql_andor_string($status, 't.status');
  1988. if (stristr($sstr, "'closed'") === FALSE)
  1989. {
  1990. $sstr .= " AND t.status != 'closed' ";
  1991. }
  1992. $sql .= $sstr;
  1993. }
  1994. else
  1995. {
  1996. $sql .= "AND t.status = 'open' ";
  1997. }
  1998. /**------
  1999. /** Add Group ID clause
  2000. /**------*/
  2001. if ($group_id = $this->EE->TMPL->fetch_param('group_id'))
  2002. {
  2003. $sql .= $this->EE->functions->sql_andor_string($group_id, 'm.group_id');
  2004. }
  2005. /** ---------------------------------------
  2006. /** Field searching
  2007. /** ---------------------------------------*/
  2008. if ( ! empty($this->EE->TMPL->search_fields))
  2009. {
  2010. $sql .= $this->generate_field_search_sql($this->EE->TMPL->search_fields, $this->EE->TMPL->site_ids);
  2011. }
  2012. /**----------
  2013. /** Build sorting clause
  2014. /**----------*/
  2015. // We'll assign this to a different variable since we
  2016. // need to use this in two places
  2017. $end = 'ORDER BY ';
  2018. if ($fixed_order !== FALSE && ! empty($fixed_order))
  2019. {
  2020. $end .= 'FIELD(t.entry_id, '.implode(',', $fixed_order).') ';
  2021. }
  2022. else
  2023. {
  2024. // Used to eliminate sort issues with duplicated fields below
  2025. $entry_id_sort = $sort_array[0];
  2026. if (FALSE === $order_array[0])
  2027. {
  2028. if ($sticky == 'no')
  2029. {
  2030. $end .= "t.entry_date";
  2031. }
  2032. else
  2033. {
  2034. $end .= "t.sticky desc, t.entry_date";
  2035. }
  2036. if ($sort_array[0] == 'asc' OR $sort_array[0] == 'desc')
  2037. {
  2038. $end .= " ".$sort_array[0];
  2039. }
  2040. }
  2041. else
  2042. {
  2043. if ($sticky != 'no')
  2044. {
  2045. $end .= "t.sticky desc, ";
  2046. }
  2047. foreach($order_array as $key => $order)
  2048. {
  2049. if (in_array($order, array('view_count_one', 'view_count_two', 'view_count_three', 'view_count_four')))
  2050. {
  2051. $view_ct = substr($order, 10);
  2052. $order = "view_count";
  2053. }
  2054. if ($key > 0) $end .= ", ";
  2055. switch ($order)
  2056. {
  2057. case 'entry_id' :
  2058. $end .= "t.entry_id";
  2059. break;
  2060. case 'date' :
  2061. $end .= "t.entry_date";
  2062. break;
  2063. case 'edit_date' :
  2064. $end .= "t.edit_date";
  2065. break;
  2066. case 'expiration_date' :
  2067. $end .= "t.expiration_date";
  2068. break;
  2069. case 'status' :
  2070. $end .= "t.status";
  2071. break;
  2072. case 'title' :
  2073. $end .= "t.title";
  2074. break;
  2075. case 'url_title' :
  2076. $end .= "t.url_title";
  2077. break;
  2078. case 'view_count' :
  2079. $vc = $order.$view_ct;
  2080. $end .= " t.{$vc} ".$sort_array[$key];
  2081. if (count($order_array)-1 == $key)
  2082. {
  2083. $end .= ", t.entry_date ".$sort_array[$key];
  2084. }
  2085. $sort_array[$key] = FALSE;
  2086. break;
  2087. case 'comment_total' :
  2088. $end .= "t.comment_total ".$sort_array[$key];
  2089. if (count($order_array)-1 == $key)
  2090. {
  2091. $end .= ", t.entry_date ".$sort_array[$key];
  2092. }
  2093. $sort_array[$key] = FALSE;
  2094. break;
  2095. case 'most_recent_comment' :
  2096. $end .= "t.recent_comment_date ".$sort_array[$key];
  2097. if (count($order_array)-1 == $key)
  2098. {
  2099. $end .= ", t.entry_date ".$sort_array[$key];
  2100. }
  2101. $sort_array[$key] = FALSE;
  2102. break;
  2103. case 'username' :
  2104. $end .= "m.username";
  2105. break;
  2106. case 'screen_name' :
  2107. $end .= "m.screen_name";
  2108. break;
  2109. case 'custom_field' :
  2110. if (strpos($corder[$key], '|') !== FALSE)
  2111. {
  2112. $end .= "CONCAT(wd.field_id_".implode(", wd.field_id_", explode('|', $corder[$key])).")";
  2113. }
  2114. else
  2115. {
  2116. $end .= "wd.field_id_".$corder[$key];
  2117. }
  2118. break;
  2119. case 'random' :
  2120. $end = "ORDER BY rand()";
  2121. $sort_array[$key] = FALSE;
  2122. break;
  2123. default :
  2124. $end .= "t.entry_date";
  2125. break;
  2126. }
  2127. if ($sort_array[$key] == 'asc' OR $sort_array[$key] == 'desc')
  2128. {
  2129. // keep entries with the same timestamp in the correct order
  2130. $end .= " {$sort_array[$key]}";
  2131. }
  2132. }
  2133. }
  2134. // In the event of a sorted field containing identical information as another
  2135. // entry (title, entry_date, etc), they will sort on the order they were entered
  2136. // into ExpressionEngine, with the first "sort" parameter taking precedence.
  2137. // If no sort parameter is set, entries will descend by entry id.
  2138. if ( ! in_array('entry_id', $order_array))
  2139. {
  2140. $end .= ", t.entry_id ".$entry_id_sort;
  2141. }
  2142. }
  2143. // Determine the row limits
  2144. // Even thouth we don't use the LIMIT clause until the end,
  2145. // we need it to help create our pagination links so we'll
  2146. // set it here
  2147. if ($cat_id != '' AND is_numeric($this->EE->TMPL->fetch_param('cat_limit')))
  2148. {
  2149. $this->pagination->per_page = $this->EE->TMPL->fetch_param('cat_limit');
  2150. }
  2151. elseif ($month != '' AND is_numeric($this->EE->TMPL->fetch_param('month_limit')))
  2152. {
  2153. $this->pagination->per_page = $this->EE->TMPL->fetch_param('month_limit');
  2154. }
  2155. else
  2156. {
  2157. $this->pagination->per_page = ( ! is_numeric($this->EE->TMPL->fetch_param('limit'))) ? $this->limit : $this->EE->TMPL->fetch_param('limit');
  2158. }
  2159. /**------
  2160. /** Is there an offset?
  2161. /**------*/
  2162. // We do this hear so we can use the offset into next, then later one as well
  2163. $offset = ( ! $this->EE->TMPL->fetch_param('offset') OR ! is_numeric($this->EE->TMPL->fetch_param('offset'))) ? '0' : $this->EE->TMPL->fetch_param('offset');
  2164. // Do we need pagination?
  2165. // We'll run the query to find out
  2166. if ($this->pagination->paginate == TRUE)
  2167. {
  2168. $this->pager_sql = '';
  2169. if ($this->pagination->field_pagination == FALSE)
  2170. {
  2171. $this->pager_sql = $sql_a.$sql_b.$sql;
  2172. $query = $this->EE->db->query($this->pager_sql);
  2173. $total = $query->num_rows;
  2174. $this->absolute_results = $total;
  2175. // Adjust for offset
  2176. if ($total >= $offset)
  2177. {
  2178. $total = $total - $offset;
  2179. }
  2180. $this->pagination->cfields = $this->cfields;
  2181. $this->pagination->build($total, $this->sql);
  2182. }
  2183. else
  2184. {
  2185. $this->pager_sql = $sql_a.$sql_b.$sql;
  2186. $query = $this->EE->db->query($this->pager_sql);
  2187. $total = $query->num_rows;
  2188. $this->absolute_results = $total;
  2189. $this->pagination->cfields = $this->cfields;
  2190. $this->pagination->build($total, $this->sql, $query);
  2191. if ($this->EE->config->item('enable_sql_caching') == 'y')
  2192. {
  2193. $this->save_cache($this->pager_sql, 'pagination_query');
  2194. $this->save_cache('1', 'field_pagination');
  2195. }
  2196. }
  2197. if ($this->EE->config->item('enable_sql_caching') == 'y')
  2198. {
  2199. $this->save_cache($total, 'pagination_count');
  2200. }
  2201. }
  2202. /**------
  2203. /** Add Limits to query
  2204. /**------*/
  2205. $sql .= $end;
  2206. if ($this->pagination->paginate == FALSE)
  2207. {
  2208. $this->pagination->offset = 0;
  2209. }
  2210. // Adjust for offset
  2211. $this->pagination->offset += $offset;
  2212. if ($this->display_by == '')
  2213. {
  2214. if (($page_marker == FALSE AND $this->pagination->per_page != '') OR ($page_marker == TRUE AND $this->pagination->field_pagination != TRUE))
  2215. {
  2216. $sql .= ($this->pagination->offset == '') ? " LIMIT ".$offset.', '.$this->pagination->per_page : " LIMIT ".$this->pagination->offset.', '.$this->pagination->per_page;
  2217. }
  2218. elseif ($entry_id == '' AND $qtitle == '')
  2219. {
  2220. $sql .= ($this->pagination->offset == '') ? " LIMIT ".$this->limit : " LIMIT ".$this->pagination->offset.', '.$this->limit;
  2221. }
  2222. }
  2223. else
  2224. {
  2225. if ($offset != 0)
  2226. {
  2227. $sql .= ($this->pagination->offset == '') ? " LIMIT ".$offset.', '.$this->pagination->per_page : " LIMIT ".$this->pagination->offset.', '.$this->pagination->per_page;
  2228. }
  2229. }
  2230. /**------
  2231. /** Fetch the entry_id numbers
  2232. /**------*/
  2233. $query = $this->EE->db->query($sql_a.$sql_b.$sql);
  2234. //exit($sql_a.$sql_b.$sql);
  2235. if ($query->num_rows() == 0)
  2236. {
  2237. $this->sql = '';
  2238. return;
  2239. }
  2240. /**------
  2241. /** Build the full SQL query
  2242. /**------*/
  2243. $this->sql = "SELECT ";
  2244. if ($this->EE->TMPL->fetch_param('category') OR $this->EE->TMPL->fetch_param('category_group') OR $cat_id != '')
  2245. {
  2246. // Using DISTINCT like this is bogus but since
  2247. // FULL OUTER JOINs are not supported in older versions
  2248. // of MySQL it's our only choice
  2249. $this->sql .= " DISTINCT(t.entry_id), ";
  2250. }
  2251. if ($this->display_by == 'week' && isset($yearweek))
  2252. {
  2253. $this->sql .= $yearweek.', ';
  2254. }
  2255. // DO NOT CHANGE THE ORDER
  2256. // The exp_member_data table needs to be called before the exp_members table.
  2257. $this->sql .= " t.entry_id, t.channel_id, t.forum_topic_id, t.author_id, t.ip_address, t.title, t.url_title, t.status, t.dst_enabled, t.view_count_one, t.view_count_two, t.view_count_three, t.view_count_four, t.allow_comments, t.comment_expiration_date, t.sticky, t.entry_date, t.year, t.month, t.day, t.edit_date, t.expiration_date, t.recent_comment_date, t.comment_total, t.site_id as entry_site_id,
  2258. w.channel_title, w.channel_name, w.channel_url, w.comment_url, w.comment_moderate, w.channel_html_formatting, w.channel_allow_img_urls, w.channel_auto_link_urls, w.comment_system_enabled,
  2259. m.username, m.email, m.url, m.screen_name, m.location, m.occupation, m.interests, m.aol_im, m.yahoo_im, m.msn_im, m.icq, m.signature, m.sig_img_filename, m.sig_img_width, m.sig_img_height, m.avatar_filename, m.avatar_width, m.avatar_height, m.photo_filename, m.photo_width, m.photo_height, m.group_id, m.member_id, m.bday_d, m.bday_m, m.bday_y, m.bio,
  2260. md.*,
  2261. wd.*
  2262. FROM exp_channel_titles AS t
  2263. LEFT JOIN exp_channels AS w ON t.channel_id = w.channel_id
  2264. LEFT JOIN exp_channel_data AS wd ON t.entry_id = wd.entry_id
  2265. LEFT JOIN exp_members AS m ON m.member_id = t.author_id
  2266. LEFT JOIN exp_member_data AS md ON md.member_id = m.member_id ";
  2267. $this->sql .= "WHERE t.entry_id IN (";
  2268. $entries = array();
  2269. // Build ID numbers (checking for duplicates)
  2270. foreach ($query->result_array() as $row)
  2271. {
  2272. if ( ! isset($entries[$row['entry_id']]))
  2273. {
  2274. $entries[$row['entry_id']] = 'y';
  2275. }
  2276. else
  2277. {
  2278. continue;
  2279. }
  2280. $this->sql .= $row['entry_id'].',';
  2281. }
  2282. //cache the entry_id
  2283. $this->EE->session->cache['channel']['entry_ids'] = array_keys($entries);
  2284. unset($query);
  2285. unset($entries);
  2286. $this->sql = substr($this->sql, 0, -1).') ';
  2287. // modify the ORDER BY if displaying by week
  2288. if ($this->display_by == 'week' && isset($yearweek))
  2289. {
  2290. $weeksort = ($this->EE->TMPL->fetch_param('week_sort') == 'desc') ? 'DESC' : 'ASC';
  2291. $end = str_replace('ORDER BY ', 'ORDER BY yearweek '.$weeksort.', ', $end);
  2292. }
  2293. $this->sql .= $end;
  2294. }
  2295. // ------------------------------------------------------------------------
  2296. /**
  2297. * Parse channel entries - New Attempt
  2298. */
  2299. public function parse_channel_entries_new()
  2300. {
  2301. // Internal Tag Caching
  2302. $processed_member_fields = array();
  2303. $existing_variables = array();
  2304. if (preg_match_all("/".LD."([a-z\_]+)/i", $this->EE->TMPL->tagdata, $matches))
  2305. {
  2306. $existing_variables = array_flip($matches[1]);
  2307. }
  2308. // Set default date header variables
  2309. $heading_date_hourly = 0;
  2310. $heading_flag_hourly = 0;
  2311. $heading_flag_weekly = 1;
  2312. $heading_date_daily = 0;
  2313. $heading_flag_daily = 0;
  2314. $heading_date_monthly = 0;
  2315. $heading_flag_monthly = 0;
  2316. $heading_date_yearly = 0;
  2317. $heading_flag_yearly = 0;
  2318. // "Search by Member" link
  2319. // We use this with the {member_search_path} variable
  2320. if ( isset($existing_variables['member_search_path']))
  2321. {
  2322. $result_path = (preg_match("/".LD."member_search_path\s*=(.*?)".RD."/s", $this->EE->TMPL->tagdata, $match)) ? $match[1] : 'search/results';
  2323. $result_path = str_replace(array('"',"'"), "", $result_path);
  2324. $search_link = $this->EE->functions->fetch_site_index(0, 0).QUERY_MARKER.'ACT='.$this->EE->functions->fetch_action_id('Search', 'do_search').'&amp;result_path='.$result_path.'&amp;mbr=';
  2325. }
  2326. // Start the main processing loop
  2327. $total_results = count($this->query->result_array());
  2328. $site_pages = $this->EE->config->item('site_pages');
  2329. $parse_data = array();
  2330. foreach ($this->query->result_array() as $count => $row)
  2331. {
  2332. //$row['count'] = $count+1;
  2333. //$row['total_results'] = $total_results;
  2334. $row['absolute_count'] = $this->pagination->offset + $count + 1;
  2335. $row['page_uri'] = '';
  2336. $row['page_url'] = '';
  2337. if ($site_pages !== FALSE && isset($site_pages[$row['site_id']]['uris'][$row['entry_id']]))
  2338. {
  2339. $row['page_uri'] = $site_pages[$row['site_id']]['uris'][$row['entry_id']];
  2340. $row['page_url'] = $this->EE->functions->create_page_url($site_pages[$row['site_id']]['url'], $site_pages[$row['site_id']]['uris'][$row['entry_id']]);
  2341. }
  2342. // Adjust dates if needed
  2343. // If the "dst_enabled" item is set in any given entry
  2344. // we need to offset to the timestamp by an hour
  2345. if ( ! isset($row['dst_enabled']))
  2346. {
  2347. $row['dst_enabled'] = 'n';
  2348. }
  2349. // More Variables, Mostly for Conditionals
  2350. $row['logged_in'] = ($this->EE->session->userdata('member_id') == 0) ? 'FALSE' : 'TRUE';
  2351. $row['logged_out'] = ($this->EE->session->userdata('member_id') != 0) ? 'FALSE' : 'TRUE';
  2352. if ((($row['comment_expiration_date'] > 0 && $this->EE->localize->now > $row['comment_expiration_date']) && $this->EE->config->item('comment_moderation_override') !== 'y') OR $row['allow_comments'] == 'n' OR $row['comment_system_enabled'] == 'n')
  2353. {
  2354. $row['allow_comments'] = 'FALSE';
  2355. }
  2356. else
  2357. {
  2358. $row['allow_comments'] = 'TRUE';
  2359. }
  2360. foreach (array('avatar_filename', 'photo_filename', 'sig_img_filename') as $pv)
  2361. {
  2362. if ( ! isset($row[$pv]))
  2363. {
  2364. $row[$pv] = '';
  2365. }
  2366. }
  2367. $row['signature_image'] = ($row['sig_img_filename'] == '' OR $this->EE->config->item('enable_signatures') == 'n' OR $this->EE->session->userdata('display_signatures') == 'n') ? 'FALSE' : 'TRUE';
  2368. $row['avatar'] = ($row['avatar_filename'] == '' OR $this->EE->config->item('enable_avatars') == 'n' OR $this->EE->session->userdata('display_avatars') == 'n') ? 'FALSE' : 'TRUE';
  2369. $row['photo'] = ($row['photo_filename'] == '' OR $this->EE->config->item('enable_photos') == 'n' OR $this->EE->session->userdata('display_photos') == 'n') ? 'FALSE' : 'TRUE';
  2370. $row['forum_topic'] = (empty($row['forum_topic_id'])) ? 'FALSE' : 'TRUE';
  2371. $row['not_forum_topic'] = ( ! empty($row['forum_topic_id'])) ? 'FALSE' : 'TRUE';
  2372. $row['category_request'] = ($this->cat_request === FALSE) ? 'FALSE' : 'TRUE';
  2373. $row['not_category_request'] = ($this->cat_request !== FALSE) ? 'FALSE' : 'TRUE';
  2374. $row['channel'] = $row['channel_title'];
  2375. $row['channel_short_name'] = $row['channel_name'];
  2376. $row['author'] = ($row['screen_name'] != '') ? $row['screen_name'] : $row['username'];
  2377. $row['photo_url'] = $this->EE->config->slash_item('photo_url').$row['photo_filename'];
  2378. $row['photo_image_width'] = $row['photo_width'];
  2379. $row['photo_image_height'] = $row['photo_height'];
  2380. $row['avatar_url'] = $this->EE->config->slash_item('avatar_url').$row['avatar_filename'];
  2381. $row['avatar_image_width'] = $row['avatar_width'];
  2382. $row['avatar_image_height'] = $row['avatar_height'];
  2383. $row['signature_image_url'] = $this->EE->config->slash_item('sig_img_url').$row['sig_img_filename'];
  2384. $row['signature_image_width'] = $row['sig_img_width'];
  2385. $row['signature_image_height'] = $row['sig_img_height'];
  2386. if ( isset($existing_variables['relative_date']))
  2387. {
  2388. $row['relative_date'] = $this->EE->localize->format_timespan($this->EE->localize->now - $row['entry_date']);
  2389. }
  2390. // Date Variables
  2391. if ($row['recent_comment_date'] == 0) $row['recent_comment_date'] = '';
  2392. if ($row['expiration_date'] == 0) $row['expiration_date'] = '';
  2393. // "week_date"
  2394. if ( isset($existing_variables['week_start_date']))
  2395. {
  2396. // Subtract the number of days the entry is "into" the week to get zero (Sunday)
  2397. // If the entry date is for Sunday, and Monday is being used as the week's start day,
  2398. // then we must back things up by six days
  2399. $offset = 0;
  2400. if (strtolower($this->EE->TMPL->fetch_param('start_day')) == 'monday')
  2401. {
  2402. $day_of_week = $this->EE->localize->convert_timestamp('%w', $row['entry_date'], TRUE);
  2403. if ($day_of_week == '0')
  2404. {
  2405. $offset = -518400; // back six days
  2406. }
  2407. else
  2408. {
  2409. $offset = 86400; // plus one day
  2410. }
  2411. }
  2412. $row['week_start_date'] = $row['entry_date'] - ($this->EE->localize->convert_timestamp('%w', $row['entry_date'], TRUE) * 60 * 60 * 24) + $offset;
  2413. }
  2414. // PATH Variables
  2415. $row['profile_path'] = array('path', array('suffix' => $row['member_id'], 'default_path' => ''));
  2416. if ( isset($existing_variables['week_start_date']))
  2417. {
  2418. $row['week_start_date'] = array('path', array('suffix' => $row['member_id'], 'url' => $search_link));
  2419. }
  2420. $row['comment_path'] = array('path', array('suffix' => $row['entry_id']));
  2421. $row['entry_id_path'] = array('path', array('suffix' => $row['entry_id']));
  2422. $row['url_title_path'] = array('path', array('suffix' => $row['url_title']));
  2423. $row['title_permalink'] = array('path', array('suffix' => $row['url_title']));
  2424. $row['permalink'] = array('path', array('suffix' => $row['entry_id']));
  2425. $row['comment_auto_path'] = array('path', array('url' => ($row['comment_url'] == '') ? $row['channel_url'] : $row['comment_url']));
  2426. $row['comment_url_title_auto_path'] = array('path', array('url' => ($row['comment_url'] == '') ? $row['channel_url'] : $row['comment_url'], 'suffix' => $row['url_title']));
  2427. $row['comment_entry_id_auto_path'] = array('path', array('url' => ($row['comment_url'] == '') ? $row['channel_url'] : $row['comment_url'], 'suffix' => $row['entry_id']));
  2428. // Other Single Variables
  2429. $row['author'] = ($row['screen_name'] != '') ? $row['screen_name'] : $row['username'];
  2430. $row['channel'] = $row['channel_title'];
  2431. $row['channel_short_name'] = $row['channel_name'];
  2432. if ( isset($existing_variables['relative_date']))
  2433. {
  2434. $row['relative_date'] = $this->EE->localize->format_timespan($this->EE->localize->now - $row['entry_date']);
  2435. }
  2436. // Trimmed URL
  2437. $channel_url = str_replace(array('http://','www.'), '', (isset($row['channel_url']) AND $row['channel_url'] != '') ? $row['channel_url'] : '');
  2438. $xe = explode("/", $channel_url);
  2439. $row['trimmed_url'] = current($xe);
  2440. // Relative URL
  2441. if ($x = strpos($channel_url, "/"))
  2442. {
  2443. $channel_url = substr($channel_url, $x + 1);
  2444. }
  2445. $row['relative_url'] = rtrim($channel_url, '/');
  2446. $row['url_or_email'] = ($row['url'] != '') ? $row['url'] : $row['email'];
  2447. if ( isset($existing_variables['url_or_email_as_author']))
  2448. {
  2449. $row['url_or_email_as_author'] = ($row['url'] != '') ? "<a href=\"".$row['url']."\">".$row['author']."</a>" : $this->EE->typography->encode_email($row['email'], $row['author']);
  2450. }
  2451. if ( isset($existing_variables['url_or_email_as_link']))
  2452. {
  2453. $row['url_or_email_as_link'] = ($row['url'] != '') ? "<a href=\"".$row['url']."\">".$row['url']."</a>" : $this->EE->typography->encode_email($row['email']);
  2454. }
  2455. // {signature}
  2456. $row['signature'] = '';
  2457. if ( isset($existing_variables['signature']) && $this->EE->session->userdata('display_signatures') != 'n' && $row['signature'] != '' && $this->EE->session->userdata('display_signatures') != 'n')
  2458. {
  2459. $row['signature'] = array($row['signature'], array(
  2460. 'text_format' => 'xhtml',
  2461. 'html_format' => 'safe',
  2462. 'auto_links' => 'y',
  2463. 'allow_img_url' => $this->EE->config->item('sig_allow_img_hotlink')
  2464. ));
  2465. }
  2466. // Member Images and Whatnot
  2467. $row['signature_image_url'] = '';
  2468. $row['signature_image_width'] = '';
  2469. $row['signature_image_height'] = '';
  2470. $row['avatar_url'] = '';
  2471. $row['avatar_image_width'] = '';
  2472. $row['avatar_image_height'] = '';
  2473. $row['photo_url'] = '';
  2474. $row['photo_image_width'] = '';
  2475. $row['photo_image_height'] = '';
  2476. if ($this->EE->session->userdata('display_signatures') != 'n' && $row['sig_img_filename'] != '')
  2477. {
  2478. $row['signature_image_url'] = $this->EE->config->slash_item('sig_img_url').$row['sig_img_filename'];
  2479. $row['signature_image_width'] = $row['sig_img_width'];
  2480. $row['signature_image_height'] = $row['sig_img_height'];
  2481. }
  2482. if ($this->EE->session->userdata('display_avatars') != 'n' && $row['avatar_filename'] != '')
  2483. {
  2484. $row['avatar_url'] = $this->EE->config->slash_item('avatar_url').$row['avatar_filename'];
  2485. $row['avatar_image_width'] = $row['avatar_width'];
  2486. $row['avatar_image_height'] = $row['avatar_height'];
  2487. }
  2488. if ($this->EE->session->userdata('display_photos') != 'n' && $row['photo_filename'] != '')
  2489. {
  2490. $row['photo_url'] = $this->EE->config->slash_item('photo_url').$row['photo_filename'];
  2491. $row['photo_image_width'] = $row['photo_width'];
  2492. $row['photo_image_height'] = $row['photo_height'];
  2493. }
  2494. // Title
  2495. $row['title'] = str_replace(array('{', '}'), array('&#123;', '&#125;'), $row['title']);
  2496. //
  2497. // Custom Date Fields
  2498. //
  2499. if (isset($this->dfields[$row['site_id']]))
  2500. {
  2501. foreach ($this->dfields[$row['site_id']] as $dkey => $dval)
  2502. {
  2503. // Empty, Null, Zero, Zilch, Nada...
  2504. if ( ! isset($existing_variables[$dkey])) continue;
  2505. if ($row['field_id_'.$dval] == 0 OR $row['field_id_'.$dval] == '')
  2506. {
  2507. $row[$dkey] = '';
  2508. continue;
  2509. }
  2510. $row[$dkey] = $this->EE->localize->simpl_offset($row['field_id_'.$dval], $row['field_dt_'.$dval]);
  2511. }
  2512. }
  2513. // parse custom channel fields
  2514. if (isset($this->cfields[$row['site_id']]))
  2515. {
  2516. foreach ($this->cfields[$row['site_id']] as $name => $field_id)
  2517. {
  2518. $row[$name] = '';
  2519. if ( ! isset($existing_variables[$name])) continue;
  2520. if (isset($row['field_id_'.$field_id]) && $row['field_id_'.$field_id] != '')
  2521. {
  2522. $row[$name] = array( $this->EE->functions->encode_ee_tags($row['field_id_'.$field_id]),
  2523. array(
  2524. 'text_format' => $row['field_ft_'.$field_id],
  2525. 'html_format' => $row['channel_html_formatting'],
  2526. 'auto_links' => $row['channel_auto_link_urls'],
  2527. 'allow_img_url' => $row['channel_allow_img_urls'],
  2528. 'convert_curly' => 'n'
  2529. ));
  2530. }
  2531. }
  2532. }
  2533. // parse custom member fields
  2534. foreach ($this->mfields as $field_name => $field_meta)
  2535. {
  2536. if ( ! isset($existing_variables[$field_name])) continue;
  2537. if ( ! isset($processed_member_fields[$row['member_id']]['m_field_id_'.$field_meta[0]]))
  2538. {
  2539. $processed_member_fields[$row['member_id']]['m_field_id_'.$field_meta[0]] =
  2540. $this->EE->typography->parse_type(
  2541. $row['m_field_id_'.$field_meta[0]],
  2542. array(
  2543. 'text_format' => $field_meta[1],
  2544. 'html_format' => 'safe',
  2545. 'auto_links' => 'y',
  2546. 'allow_img_url' => 'n'
  2547. )
  2548. );
  2549. }
  2550. $row[$field_name] = $processed_member_fields[$row['member_id']]['m_field_id_'.$field_meta[0]];
  2551. }
  2552. // Load Row onto $parse_data array
  2553. $parse_data[] = $row;
  2554. }
  2555. // Do we have backspacing?
  2556. $this->EE->TMPL->tagparams['backspace'] = '';
  2557. // Process all tags and tagdata!!!
  2558. $this->return_data = $this->EE->TMPL->parse_variables( $this->EE->TMPL->tagdata, $parse_data);
  2559. // Kill multi_field variable
  2560. if (strpos($this->return_data, 'multi_field=') !== FALSE)
  2561. {
  2562. $this->return_data = preg_replace("/".LD."multi_field\=[\"'](.+?)[\"']".RD."/s", '', $this->return_data);
  2563. }
  2564. }
  2565. // ------------------------------------------------------------------------
  2566. /**
  2567. * Parse channel entries
  2568. */
  2569. public function parse_channel_entries()
  2570. {
  2571. $switch = array();
  2572. $processed_member_fields = array();
  2573. // Set default date header variables
  2574. $heading_date_hourly = 0;
  2575. $heading_flag_hourly = 0;
  2576. $heading_flag_weekly = 1;
  2577. $heading_date_daily = 0;
  2578. $heading_flag_daily = 0;
  2579. $heading_date_monthly = 0;
  2580. $heading_flag_monthly = 0;
  2581. $heading_date_yearly = 0;
  2582. $heading_flag_yearly = 0;
  2583. // Fetch the "category chunk"
  2584. // We'll grab the category data now to avoid processing cycles in the foreach loop below
  2585. $cat_chunk = array();
  2586. if (strpos($this->EE->TMPL->tagdata, LD.'/categories'.RD) !== FALSE)
  2587. {
  2588. if (preg_match_all("/".LD."categories(.*?)".RD."(.*?)".LD.'\/'.'categories'.RD."/s", $this->EE->TMPL->tagdata, $matches))
  2589. {
  2590. for ($j = 0; $j < count($matches[0]); $j++)
  2591. {
  2592. $cat_chunk[] = array($matches[2][$j], $this->EE->functions->assign_parameters($matches[1][$j]), $matches[0][$j]);
  2593. }
  2594. }
  2595. }
  2596. // Fetch all the date-related variables
  2597. $entry_date = array();
  2598. $gmt_date = array();
  2599. $gmt_entry_date = array();
  2600. $edit_date = array();
  2601. $gmt_edit_date = array();
  2602. $expiration_date = array();
  2603. $week_date = array();
  2604. // We do this here to avoid processing cycles in the foreach loop
  2605. $date_vars = array('entry_date', 'gmt_date', 'gmt_entry_date', 'edit_date', 'gmt_edit_date', 'expiration_date', 'recent_comment_date', 'week_date');
  2606. $date_variables_exist = FALSE;
  2607. foreach ($date_vars as $val)
  2608. {
  2609. if (strpos($this->EE->TMPL->tagdata, LD.$val) === FALSE) continue;
  2610. if (preg_match_all("/".LD.$val."\s+format=([\"'])([^\\1]*?)\\1".RD."/s", $this->EE->TMPL->tagdata, $matches))
  2611. {
  2612. $date_variables_exist = TRUE;
  2613. for ($j = 0; $j < count($matches[0]); $j++)
  2614. {
  2615. $matches[0][$j] = str_replace(array(LD,RD), '', $matches[0][$j]);
  2616. switch ($val)
  2617. {
  2618. case 'entry_date':
  2619. $entry_date[$matches[0][$j]] = $this->EE->localize->fetch_date_params($matches[2][$j]);
  2620. break;
  2621. case 'gmt_date':
  2622. $gmt_date[$matches[0][$j]] = $this->EE->localize->fetch_date_params($matches[2][$j]);
  2623. break;
  2624. case 'gmt_entry_date':
  2625. $gmt_entry_date[$matches[0][$j]] = $this->EE->localize->fetch_date_params($matches[2][$j]);
  2626. break;
  2627. case 'edit_date':
  2628. $edit_date[$matches[0][$j]] = $this->EE->localize->fetch_date_params($matches[2][$j]);
  2629. break;
  2630. case 'gmt_edit_date':
  2631. $gmt_edit_date[$matches[0][$j]] = $this->EE->localize->fetch_date_params($matches[2][$j]);
  2632. break;
  2633. case 'expiration_date':
  2634. $expiration_date[$matches[0][$j]] = $this->EE->localize->fetch_date_params($matches[2][$j]);
  2635. break;
  2636. case 'recent_comment_date':
  2637. $recent_comment_date[$matches[0][$j]] = $this->EE->localize->fetch_date_params($matches[2][$j]);
  2638. break;
  2639. case 'week_date':
  2640. $week_date[$matches[0][$j]] = $this->EE->localize->fetch_date_params($matches[2][$j]);
  2641. break;
  2642. }
  2643. }
  2644. }
  2645. }
  2646. // Are any of the custom fields dates?
  2647. $custom_date_fields = array();
  2648. if (count($this->dfields) > 0)
  2649. {
  2650. foreach ($this->dfields as $site_id => $dfields)
  2651. {
  2652. foreach($dfields as $key => $value)
  2653. {
  2654. if (strpos($this->EE->TMPL->tagdata, LD.$key) === FALSE) continue;
  2655. if (preg_match_all("/".LD.$key."\s+format=[\"'](.*?)[\"']".RD."/s", $this->EE->TMPL->tagdata, $matches))
  2656. {
  2657. for ($j = 0; $j < count($matches[0]); $j++)
  2658. {
  2659. $matches[0][$j] = str_replace(array(LD,RD), '', $matches[0][$j]);
  2660. $custom_date_fields[$matches[0][$j]] = $this->EE->localize->fetch_date_params($matches[1][$j]);
  2661. }
  2662. }
  2663. }
  2664. }
  2665. }
  2666. // And the same again for reverse related entries
  2667. $reverse_markers = array();
  2668. if (preg_match_all("/".LD."REV_REL\[([^\]]+)\]REV_REL".RD."/", $this->EE->TMPL->tagdata, $matches))
  2669. {
  2670. for ($j = 0; $j < count($matches['0']); $j++)
  2671. {
  2672. $reverse_markers[$matches['1'][$j]] = '';
  2673. }
  2674. }
  2675. // "Search by Member" link
  2676. // We use this with the {member_search_path} variable
  2677. $result_path = (preg_match("/".LD."member_search_path\s*=(.*?)".RD."/s", $this->EE->TMPL->tagdata, $match)) ? $match[1] : 'search/results';
  2678. $result_path = str_replace(array('"',"'"), "", $result_path);
  2679. $search_link = $this->EE->functions->fetch_site_index(0, 0).QUERY_MARKER.'ACT='.$this->EE->functions->fetch_action_id('Search', 'do_search').'&amp;result_path='.$result_path.'&amp;mbr=';
  2680. // Start the main processing loop
  2681. // For our hook to work, we need to grab the result array
  2682. $query_result = $this->query->result_array();
  2683. // Ditch everything else
  2684. $this->query->free_result();
  2685. unset($this->query);
  2686. // -------------------------------------------
  2687. // 'channel_entries_query_result' hook.
  2688. // - Take the whole query result array, do what you wish
  2689. // - added 1.6.7
  2690. //
  2691. if ($this->EE->extensions->active_hook('channel_entries_query_result') === TRUE)
  2692. {
  2693. $query_result = $this->EE->extensions->call('channel_entries_query_result', $this, $query_result);
  2694. if ($this->EE->extensions->end_script === TRUE) return $this->EE->TMPL->tagdata;
  2695. }
  2696. //
  2697. // -------------------------------------------
  2698. $total_results = count($query_result);
  2699. $site_pages = $this->EE->config->item('site_pages');
  2700. // Fetch Custom Field Chunks
  2701. // If any of our custom fields are tag pair fields, we'll grab those chunks now
  2702. // Moved below hook in 2.6
  2703. $pfield_chunk = array();
  2704. if (count($this->pfields) > 0)
  2705. {
  2706. foreach ($this->pfields as $site_id => $pfields)
  2707. {
  2708. $pfield_names = array_intersect($this->cfields[$site_id], array_keys($pfields));
  2709. foreach($pfield_names as $field_name => $field_id)
  2710. {
  2711. $offset = 0;
  2712. while (($end = strpos($this->EE->TMPL->tagdata, LD.'/'.$field_name.RD, $offset)) !== FALSE)
  2713. {
  2714. // This hurts soo much. Using custom fields as pair and single vars in the same
  2715. // channel tags could lead to something like this: {field}...{field}inner{/field}
  2716. // There's no efficient regex to match this case, so we'll find the last nested
  2717. // opening tag and re-cut the chunk.
  2718. if (preg_match("/".LD."{$field_name}(.*?)".RD."(.*?)".LD.'\/'."{$field_name}(.*?)".RD."/s", $this->EE->TMPL->tagdata, $matches, 0, $offset))
  2719. {
  2720. $chunk = $matches[0];
  2721. $params = $matches[1];
  2722. $inner = $matches[2];
  2723. // We might've sandwiched a single tag - no good, check again (:sigh:)
  2724. if ((strpos($chunk, LD.$field_name, 1) !== FALSE) && preg_match_all("/".LD."{$field_name}(.*?)".RD."/s", $chunk, $match))
  2725. {
  2726. // Let's start at the end
  2727. $idx = count($match[0]) - 1;
  2728. $tag = $match[0][$idx];
  2729. // Reassign the parameter
  2730. $params = $match[1][$idx];
  2731. // Cut the chunk at the last opening tag (PHP5 could do this with strrpos :-( )
  2732. while (strpos($chunk, $tag, 1) !== FALSE)
  2733. {
  2734. $chunk = substr($chunk, 1);
  2735. $chunk = strstr($chunk, LD.$field_name);
  2736. $inner = substr($chunk, strlen($tag), -strlen(LD.'/'.$field_name.RD));
  2737. }
  2738. }
  2739. $chunk_array = array($inner, $this->EE->functions->assign_parameters($params), $chunk);
  2740. // Grab modifier if it exists and add it to the chunk array
  2741. if (substr($params, 0, 1) == ':')
  2742. {
  2743. $chunk_array[] = str_replace(':', '', $params);
  2744. }
  2745. $pfield_chunk[$site_id][$field_name][] = $chunk_array;
  2746. }
  2747. $offset = $end + 1;
  2748. }
  2749. /*
  2750. if (($end = strpos($this->EE->TMPL->tagdata, LD.'/'.$field_name.RD)) !== FALSE)
  2751. {
  2752. // This hurts soo much. Using custom fields as pair and single vars in the same
  2753. // channel tags could lead to something like this: {field}...{field}inner{/field}
  2754. // There's no efficient regex to match this case, so we'll find the last nested
  2755. // opening tag and re-cut the chunk.
  2756. if (preg_match_all("/".LD."{$field_name}(.*?)".RD."(.*?)".LD.'\/'.$field_name.RD."/s", $this->EE->TMPL->tagdata, $matches))
  2757. {
  2758. for ($j = 0; $j < count($matches[0]); $j++)
  2759. {
  2760. $chunk = $matches[0][$j];
  2761. $params = $matches[1][$j];
  2762. $inner = $matches[2][$j];
  2763. // We might've sandwiched a single tag - no good, check again (:sigh:)
  2764. if ((strpos($chunk, LD.$field_name, 1) !== FALSE) && preg_match_all("/".LD."{$field_name}(.*?)".RD."/s", $chunk, $match))
  2765. {
  2766. // Let's start at the end
  2767. $idx = count($match[0]) - 1;
  2768. $tag = $match[0][$idx];
  2769. // Cut the chunk at the last opening tag (PHP5 could do this with strrpos :-( )
  2770. while (strpos($chunk, $tag, 1) !== FALSE)
  2771. {
  2772. $chunk = substr($chunk, 1);
  2773. $chunk = strstr($chunk, LD.$field_name);
  2774. $inner = substr($chunk, strlen($tag), -strlen(LD.'/'.$field_name.RD));
  2775. }
  2776. }
  2777. $pfield_chunk[$site_id][$field_name][] = array($inner, $this->EE->functions->assign_parameters($params), $chunk);
  2778. }
  2779. }
  2780. }
  2781. */
  2782. }
  2783. }
  2784. }
  2785. // One more preloop check - custom fields with modifiers in conditionals
  2786. $all_field_names = array();
  2787. foreach($this->cfields as $site_id => $fields)
  2788. {
  2789. $all_field_names = array_unique(array_merge($all_field_names, $fields));
  2790. }
  2791. $modified_field_options = implode('|', array_keys($all_field_names));
  2792. $modified_conditionals = array();
  2793. if (preg_match_all("/".preg_quote(LD)."((if:(else))*if)\s+(($modified_field_options):(\w+))(.*?)".preg_quote(RD)."/s", $this->EE->TMPL->tagdata, $matches))
  2794. {
  2795. foreach($matches[5] as $match_key => $field_name)
  2796. {
  2797. $modified_conditionals[$field_name][] = $matches[6][$match_key];
  2798. }
  2799. }
  2800. $modified_conditionals = array_map('array_unique', $modified_conditionals);
  2801. unset($all_field_names, $modified_field_options);
  2802. // If custom fields are enabled, notify them of the data we're about to send
  2803. if ( ! empty($this->cfields))
  2804. {
  2805. $this->_send_custom_field_data_to_fieldtypes($query_result);
  2806. }
  2807. foreach ($query_result as $count => $row)
  2808. {
  2809. // Fetch the tag block containing the variables that need to be parsed
  2810. $tagdata = $this->EE->TMPL->tagdata;
  2811. $row['count'] = $count+1;
  2812. $row['page_uri'] = '';
  2813. $row['page_url'] = '';
  2814. $row['total_results'] = $total_results;
  2815. $row['absolute_count'] = $this->pagination->offset + $row['count'];
  2816. $row['absolute_results'] = ($this->absolute_results === NULL) ? $total_results : $this->absolute_results;
  2817. if ($site_pages !== FALSE && isset($site_pages[$row['site_id']]['uris'][$row['entry_id']]))
  2818. {
  2819. $row['page_uri'] = $site_pages[$row['site_id']]['uris'][$row['entry_id']];
  2820. $row['page_url'] = $this->EE->functions->create_page_url($site_pages[$row['site_id']]['url'], $site_pages[$row['site_id']]['uris'][$row['entry_id']]);
  2821. }
  2822. // -------------------------------------------
  2823. // 'channel_entries_tagdata' hook.
  2824. // - Take the entry data and tag data, do what you wish
  2825. //
  2826. if ($this->EE->extensions->active_hook('channel_entries_tagdata') === TRUE)
  2827. {
  2828. $tagdata = $this->EE->extensions->call('channel_entries_tagdata', $tagdata, $row, $this);
  2829. if ($this->EE->extensions->end_script === TRUE) return $tagdata;
  2830. }
  2831. //
  2832. // -------------------------------------------
  2833. // -------------------------------------------
  2834. // 'channel_entries_row' hook.
  2835. // - Take the entry data, do what you wish
  2836. // - added 1.6.7
  2837. //
  2838. if ($this->EE->extensions->active_hook('channel_entries_row') === TRUE)
  2839. {
  2840. $row = $this->EE->extensions->call('channel_entries_row', $this, $row);
  2841. if ($this->EE->extensions->end_script === TRUE) return $tagdata;
  2842. }
  2843. //
  2844. // -------------------------------------------
  2845. // Adjust dates if needed
  2846. // If the "dst_enabled" item is set in any given entry
  2847. // we need to offset to the timestamp by an hour
  2848. if ( ! isset($row['dst_enabled']))
  2849. $row['dst_enabled'] = 'n';
  2850. /**--
  2851. /** Reset custom date fields
  2852. /**--*/
  2853. // Since custom date fields columns are integer types by default, if they
  2854. // don't contain any data they return a zero.
  2855. // This creates a problem if conditionals are used with those fields.
  2856. // For example, if an admin has this in a template: {if mydate == ''}
  2857. // Since the field contains a zero it would never evaluate TRUE.
  2858. // Therefore we'll reset any zero dates to nothing.
  2859. if (isset($this->dfields[$row['site_id']]) && count($this->dfields[$row['site_id']]) > 0)
  2860. {
  2861. foreach ($this->dfields[$row['site_id']] as $dkey => $dval)
  2862. {
  2863. // While we're at it, kill any formatting
  2864. $row['field_ft_'.$dval] = 'none';
  2865. if (isset($row['field_id_'.$dval]) AND $row['field_id_'.$dval] == 0)
  2866. {
  2867. $row['field_id_'.$dval] = '';
  2868. }
  2869. }
  2870. }
  2871. // While we're at it, do the same for related entries.
  2872. if (isset($this->rfields[$row['site_id']]) && count($this->rfields[$row['site_id']]) > 0)
  2873. {
  2874. foreach ($this->rfields[$row['site_id']] as $rkey => $rval)
  2875. {
  2876. $row['field_ft_'.$rval] = 'none';
  2877. }
  2878. }
  2879. // Reverse related markers
  2880. $j = 0;
  2881. foreach ($reverse_markers as $k => $v)
  2882. {
  2883. $this->reverse_related_entries[$row['entry_id']][$j] = $k;
  2884. $tagdata = str_replace( LD."REV_REL[".$k."]REV_REL".RD, LD."REV_REL[".$k."][".$row['entry_id']."]REV_REL".RD, $tagdata);
  2885. $j++;
  2886. }
  2887. // Conditionals
  2888. $cond = $row;
  2889. $cond['logged_in'] = ($this->EE->session->userdata('member_id') == 0) ? 'FALSE' : 'TRUE';
  2890. $cond['logged_out'] = ($this->EE->session->userdata('member_id') != 0) ? 'FALSE' : 'TRUE';
  2891. if ((($row['comment_expiration_date'] > 0 && $this->EE->localize->now > $row['comment_expiration_date']) && $this->EE->config->item('comment_moderation_override') !== 'y') OR $row['allow_comments'] == 'n' OR (isset($row['comment_system_enabled']) && $row['comment_system_enabled'] == 'n'))
  2892. {
  2893. $cond['allow_comments'] = 'FALSE';
  2894. }
  2895. else
  2896. {
  2897. $cond['allow_comments'] = 'TRUE';
  2898. }
  2899. foreach (array('avatar_filename', 'photo_filename', 'sig_img_filename') as $pv)
  2900. {
  2901. if ( ! isset($row[$pv]))
  2902. {
  2903. $row[$pv] = '';
  2904. }
  2905. }
  2906. $cond['signature_image'] = ($row['sig_img_filename'] == '' OR $this->EE->config->item('enable_signatures') == 'n' OR $this->EE->session->userdata('display_signatures') == 'n') ? 'FALSE' : 'TRUE';
  2907. $cond['avatar'] = ($row['avatar_filename'] == '' OR $this->EE->config->item('enable_avatars') == 'n' OR $this->EE->session->userdata('display_avatars') == 'n') ? 'FALSE' : 'TRUE';
  2908. $cond['photo'] = ($row['photo_filename'] == '' OR $this->EE->config->item('enable_photos') == 'n' OR $this->EE->session->userdata('display_photos') == 'n') ? 'FALSE' : 'TRUE';
  2909. $cond['forum_topic'] = (empty($row['forum_topic_id'])) ? 'FALSE' : 'TRUE';
  2910. $cond['not_forum_topic'] = ( ! empty($row['forum_topic_id'])) ? 'FALSE' : 'TRUE';
  2911. $cond['category_request'] = ($this->cat_request === FALSE) ? 'FALSE' : 'TRUE';
  2912. $cond['not_category_request'] = ($this->cat_request !== FALSE) ? 'FALSE' : 'TRUE';
  2913. $cond['channel'] = $row['channel_title'];
  2914. $cond['channel_short_name'] = $row['channel_name'];
  2915. $cond['author'] = ($row['screen_name'] != '') ? $row['screen_name'] : $row['username'];
  2916. $cond['photo_url'] = $this->EE->config->slash_item('photo_url').$row['photo_filename'];
  2917. $cond['photo_image_width'] = $row['photo_width'];
  2918. $cond['photo_image_height'] = $row['photo_height'];
  2919. $cond['avatar_url'] = $this->EE->config->slash_item('avatar_url').$row['avatar_filename'];
  2920. $cond['avatar_image_width'] = $row['avatar_width'];
  2921. $cond['avatar_image_height'] = $row['avatar_height'];
  2922. $cond['signature_image_url'] = $this->EE->config->slash_item('sig_img_url').$row['sig_img_filename'];
  2923. $cond['signature_image_width'] = $row['sig_img_width'];
  2924. $cond['signature_image_height'] = $row['sig_img_height'];
  2925. $cond['relative_date'] = $this->EE->localize->format_timespan($this->EE->localize->now - $row['entry_date']);
  2926. if (isset($this->cfields[$row['site_id']]))
  2927. {
  2928. foreach($this->cfields[$row['site_id']] as $key => $value)
  2929. {
  2930. $cond[$key] = ( ! isset($row['field_id_'.$value])) ? '' : $row['field_id_'.$value];
  2931. // Is this field used with a modifier anywhere?
  2932. if (isset($modified_conditionals[$key]) && count($modified_conditionals[$key]))
  2933. {
  2934. $this->EE->load->library('api');
  2935. $this->EE->api->instantiate('channel_fields');
  2936. if ($this->EE->api_channel_fields->setup_handler($value))
  2937. {
  2938. foreach($modified_conditionals[$key] as $modifier)
  2939. {
  2940. $this->EE->api_channel_fields->apply('_init', array(array('row' => $row)));
  2941. $data = $this->EE->api_channel_fields->apply('pre_process', array($cond[$key]));
  2942. if ($this->EE->api_channel_fields->check_method_exists('replace_'.$modifier))
  2943. {
  2944. $cond[$key.':'.$modifier] = $this->EE->api_channel_fields->apply('replace_'.$modifier, array($data, array(), FALSE));
  2945. }
  2946. else
  2947. {
  2948. $cond[$key.':'.$modifier] = FALSE;
  2949. $this->EE->TMPL->log_item('Unable to find parse type for custom field conditional: '.$key.':'.$modifier);
  2950. }
  2951. }
  2952. }
  2953. }
  2954. }
  2955. }
  2956. foreach($this->mfields as $key => $value)
  2957. {
  2958. $cond[$key] = ( ! array_key_exists('m_field_id_'.$value[0], $row)) ? '' : $row['m_field_id_'.$value[0]];
  2959. //( ! isset($row['m_field_id_'.$value[0]])) ? '' : $row['m_field_id_'.$value[0]];
  2960. }
  2961. //$tagdata = $this->EE->functions->prep_conditionals($tagdata, $cond);
  2962. // Reset custom variable pair cache
  2963. $parsed_custom_pairs = array();
  2964. // Parse Variable Pairs
  2965. foreach ($this->EE->TMPL->var_pair as $key => $val)
  2966. {
  2967. // parse categories
  2968. if (strncmp($key, 'categories', 10) == 0)
  2969. {
  2970. if (isset($this->categories[$row['entry_id']]) AND is_array($this->categories[$row['entry_id']]) AND count($cat_chunk) > 0)
  2971. {
  2972. // Get category ID from URL for {if active} conditional
  2973. $this->EE->load->helper('segment');
  2974. $active_cat = ($this->pagination->dynamic_sql && $this->cat_request) ? parse_category($this->query_string) : FALSE;
  2975. foreach ($cat_chunk as $catkey => $catval)
  2976. {
  2977. $cats = '';
  2978. $i = 0;
  2979. // We do the pulling out of categories before the "prepping" of conditionals
  2980. // So, we have to do it here again too. How annoying...
  2981. $catval[0] = $this->EE->functions->prep_conditionals($catval[0], $cond);
  2982. $catval[2] = $this->EE->functions->prep_conditionals($catval[2], $cond);
  2983. $not_these = array();
  2984. $these = array();
  2985. $not_these_groups = array();
  2986. $these_groups = array();
  2987. if (isset($catval[1]['show']))
  2988. {
  2989. if (strncmp($catval[1]['show'], 'not ', 4) == 0)
  2990. {
  2991. $not_these = explode('|', trim(substr($catval[1]['show'], 3)));
  2992. }
  2993. else
  2994. {
  2995. $these = explode('|', trim($catval[1]['show']));
  2996. }
  2997. }
  2998. if (isset($catval[1]['show_group']))
  2999. {
  3000. if (strncmp($catval[1]['show_group'], 'not ', 4) == 0)
  3001. {
  3002. $not_these_groups = explode('|', trim(substr($catval[1]['show_group'], 3)));
  3003. }
  3004. else
  3005. {
  3006. $these_groups = explode('|', trim($catval[1]['show_group']));
  3007. }
  3008. }
  3009. foreach ($this->categories[$row['entry_id']] as $k => $v)
  3010. {
  3011. if (in_array($v[0], $not_these) OR (isset($v[5]) && in_array($v[5], $not_these_groups)))
  3012. {
  3013. continue;
  3014. }
  3015. elseif( (count($these) > 0 && ! in_array($v[0], $these)) OR
  3016. (count($these_groups) > 0 && isset($v[5]) && ! in_array($v[5], $these_groups)))
  3017. {
  3018. continue;
  3019. }
  3020. $temp = $catval[0];
  3021. if (preg_match_all("#".LD."path=(.+?)".RD."#", $temp, $matches))
  3022. {
  3023. foreach ($matches[1] as $match)
  3024. {
  3025. if ($this->use_category_names == TRUE)
  3026. {
  3027. $temp = preg_replace("#".LD."path=.+?".RD."#", $this->EE->functions->remove_double_slashes($this->EE->functions->create_url($match).'/'.$this->reserved_cat_segment.'/'.$v[6]), $temp, 1);
  3028. }
  3029. else
  3030. {
  3031. $temp = preg_replace("#".LD."path=.+?".RD."#", $this->EE->functions->remove_double_slashes($this->EE->functions->create_url($match).'/C'.$v[0]), $temp, 1);
  3032. }
  3033. }
  3034. }
  3035. else
  3036. {
  3037. $temp = preg_replace("#".LD."path=.+?".RD."#", $this->EE->functions->create_url("SITE_INDEX"), $temp);
  3038. }
  3039. $this->EE->load->library('file_field');
  3040. $cat_image = $this->EE->file_field->parse_field($v[3]);
  3041. $cat_vars = array(
  3042. 'category_name' => $v[2],
  3043. 'category_url_title' => $v[6],
  3044. 'category_description' => (isset($v[4])) ? $v[4] : '',
  3045. 'category_group' => (isset($v[5])) ? $v[5] : '',
  3046. 'category_image' => $cat_image['url'],
  3047. 'category_id' => $v[0],
  3048. 'parent_id' => $v[1],
  3049. 'active' => ($active_cat == $v[0] || $active_cat == $v[6])
  3050. );
  3051. // add custom fields for conditionals prep
  3052. foreach ($this->catfields as $cv)
  3053. {
  3054. $cat_vars[$cv['field_name']] = ( ! isset($v['field_id_'.$cv['field_id']])) ? '' : $v['field_id_'.$cv['field_id']];
  3055. }
  3056. $temp = $this->EE->functions->prep_conditionals($temp, $cat_vars);
  3057. $temp = str_replace(
  3058. array(
  3059. LD."category_id".RD,
  3060. LD."category_name".RD,
  3061. LD."category_url_title".RD,
  3062. LD."category_image".RD,
  3063. LD."category_group".RD,
  3064. LD.'category_description'.RD,
  3065. LD.'parent_id'.RD
  3066. ),
  3067. array($v[0],
  3068. $v[2],
  3069. $v[6],
  3070. $cat_image['url'],
  3071. (isset($v[5])) ? $v[5] : '',
  3072. (isset($v[4])) ? $v[4] : '',
  3073. $v[1]
  3074. ),
  3075. $temp
  3076. );
  3077. foreach($this->catfields as $cv2)
  3078. {
  3079. if (isset($v['field_id_'.$cv2['field_id']]) AND $v['field_id_'.$cv2['field_id']] != '')
  3080. {
  3081. $field_content = $this->EE->typography->parse_type(
  3082. $v['field_id_'.$cv2['field_id']],
  3083. array(
  3084. 'text_format' => $v['field_ft_'.$cv2['field_id']],
  3085. 'html_format' => $v['field_html_formatting'],
  3086. 'auto_links' => 'n',
  3087. 'allow_img_url' => 'y'
  3088. )
  3089. );
  3090. $temp = str_replace(LD.$cv2['field_name'].RD, $field_content, $temp);
  3091. }
  3092. else
  3093. {
  3094. // garbage collection
  3095. $temp = str_replace(LD.$cv2['field_name'].RD, '', $temp);
  3096. }
  3097. $temp = $this->EE->functions->remove_double_slashes($temp);
  3098. }
  3099. $cats .= $temp;
  3100. if (is_array($catval[1]) && isset($catval[1]['limit']) && $catval[1]['limit'] == ++$i)
  3101. {
  3102. break;
  3103. }
  3104. }
  3105. if (is_array($catval[1]) AND isset($catval[1]['backspace']))
  3106. {
  3107. $cats = substr($cats, 0, - $catval[1]['backspace']);
  3108. }
  3109. // Check to see if we need to parse {filedir_n}
  3110. if (strpos($cats, '{filedir_') !== FALSE)
  3111. {
  3112. $this->EE->load->library('file_field');
  3113. $cats = $this->EE->file_field->parse_string($cats);
  3114. }
  3115. $tagdata = str_replace($catval[2], $cats, $tagdata);
  3116. }
  3117. }
  3118. else
  3119. {
  3120. $tagdata = $this->EE->TMPL->delete_var_pairs($key, 'categories', $tagdata);
  3121. }
  3122. }
  3123. // END CATEGORIES
  3124. // parse custom field pairs (file, checkbox, multiselect)
  3125. // First we need the key name out of the {name foo=bar|baz} mess
  3126. $key_name = $key;
  3127. $parse_fnc_catchall = 'replace_tag_catchall';
  3128. if (($spc = strpos($key, ' ')) !== FALSE)
  3129. {
  3130. $key_name = substr($key, 0, $spc);
  3131. }
  3132. if (($cln = strpos($key, ':')) !== FALSE)
  3133. {
  3134. $key_name = substr($key_name, 0, $cln);
  3135. }
  3136. // Is it a custom field?
  3137. if (isset($this->cfields[$row['site_id']][$key_name]) && ! in_array($key_name, $parsed_custom_pairs))
  3138. {
  3139. // We parse all chunks, but TMPL->var_pairs will still have the others
  3140. // so we'll keep track of these and bail if we've parsed it
  3141. $parsed_custom_pairs[] = $key_name;
  3142. // Is this custom field part of the current channel row?
  3143. if (isset($row['field_id_'.$this->cfields[$row['site_id']][$key_name]]) && isset($this->pfields[$row['site_id']][$this->cfields[$row['site_id']][$key_name]]))
  3144. {
  3145. $this->EE->load->library('api');
  3146. $this->EE->api->instantiate('channel_fields');
  3147. if ($this->EE->api_channel_fields->setup_handler($this->cfields[$row['site_id']][$key_name]))
  3148. {
  3149. $this->EE->api_channel_fields->apply('_init', array(array('row' => $row)));
  3150. // Preprocess
  3151. $data = $this->EE->api_channel_fields->apply('pre_process', array($row['field_id_'.$this->cfields[$row['site_id']][$key_name]]));
  3152. // Blast through all the chunks
  3153. if (isset($pfield_chunk[$row['site_id']][$key_name]))
  3154. {
  3155. foreach($pfield_chunk[$row['site_id']][$key_name] as $chk_data)
  3156. {
  3157. // Set up parse function name based on whether or not
  3158. // we have a modifier
  3159. $parse_fnc = (isset($chk_data[3]))
  3160. ? 'replace_'.$chk_data[3] : 'replace_tag';
  3161. if ($this->EE->api_channel_fields->check_method_exists($parse_fnc))
  3162. {
  3163. $tpl_chunk = $this->EE->api_channel_fields->apply(
  3164. $parse_fnc,
  3165. array($data, $chk_data[1], $chk_data[0])
  3166. );
  3167. }
  3168. // Go to catchall and include modifier
  3169. elseif ($this->EE->api_channel_fields->check_method_exists($parse_fnc_catchall)
  3170. AND isset($chk_data[3]))
  3171. {
  3172. $tpl_chunk = $this->EE->api_channel_fields->apply(
  3173. $parse_fnc_catchall,
  3174. array($data, $chk_data[1], $chk_data[0], $chk_data[3])
  3175. );
  3176. }
  3177. else
  3178. {
  3179. $tpl_chunk = '';
  3180. $this->EE->TMPL->log_item('Unable to find parse type for custom field: '.$key_name);
  3181. }
  3182. // Replace the chunk
  3183. $tagdata = str_replace($chk_data[2], $tpl_chunk, $tagdata);
  3184. }
  3185. }
  3186. }
  3187. else
  3188. {
  3189. $this->EE->TMPL->log_item('Unable to find field type for custom field: '.$key);
  3190. $tagdata = $this->EE->TMPL->delete_var_pairs($key, $key_name, $tagdata);
  3191. }
  3192. }
  3193. else
  3194. {
  3195. $tagdata = $this->EE->TMPL->delete_var_pairs($key, $key_name, $tagdata);
  3196. }
  3197. }
  3198. // END CUSTOM FIELD PAIRS
  3199. // parse date heading
  3200. if (strncmp($key, 'date_heading', 12) == 0)
  3201. {
  3202. // Set the display preference
  3203. $display = (is_array($val) AND isset($val['display'])) ? $val['display'] : 'daily';
  3204. // Hourly header
  3205. if ($display == 'hourly')
  3206. {
  3207. $heading_date_hourly = gmdate('YmdH', $this->EE->localize->set_localized_time($row['entry_date']));
  3208. if ($heading_date_hourly == $heading_flag_hourly)
  3209. {
  3210. $tagdata = $this->EE->TMPL->delete_var_pairs($key, 'date_heading', $tagdata);
  3211. }
  3212. else
  3213. {
  3214. $tagdata = $this->EE->TMPL->swap_var_pairs($key, 'date_heading', $tagdata);
  3215. $heading_flag_hourly = $heading_date_hourly;
  3216. }
  3217. }
  3218. // Weekly header
  3219. elseif ($display == 'weekly')
  3220. {
  3221. $temp_date = $this->EE->localize->set_localized_time($row['entry_date']);
  3222. // date()'s week variable 'W' starts weeks on Monday per ISO-8601.
  3223. // By default we start weeks on Sunday, so we need to do a little dance for
  3224. // entries made on Sundays to make sure they get placed in the right week heading
  3225. if (strtolower($this->EE->TMPL->fetch_param('start_day')) != 'monday' && gmdate('w', $this->EE->localize->set_localized_time($row['entry_date'])) == 0)
  3226. {
  3227. // add 7 days to toss us into the next ISO-8601 week
  3228. $heading_date_weekly = gmdate('YW', $temp_date + 604800);
  3229. }
  3230. else
  3231. {
  3232. $heading_date_weekly = gmdate('YW', $temp_date);
  3233. }
  3234. if ($heading_date_weekly == $heading_flag_weekly)
  3235. {
  3236. $tagdata = $this->EE->TMPL->delete_var_pairs($key, 'date_heading', $tagdata);
  3237. }
  3238. else
  3239. {
  3240. $tagdata = $this->EE->TMPL->swap_var_pairs($key, 'date_heading', $tagdata);
  3241. $heading_flag_weekly = $heading_date_weekly;
  3242. }
  3243. }
  3244. // Monthly header
  3245. elseif ($display == 'monthly')
  3246. {
  3247. $heading_date_monthly = gmdate('Ym', $this->EE->localize->set_localized_time($row['entry_date']));
  3248. if ($heading_date_monthly == $heading_flag_monthly)
  3249. {
  3250. $tagdata = $this->EE->TMPL->delete_var_pairs($key, 'date_heading', $tagdata);
  3251. }
  3252. else
  3253. {
  3254. $tagdata = $this->EE->TMPL->swap_var_pairs($key, 'date_heading', $tagdata);
  3255. $heading_flag_monthly = $heading_date_monthly;
  3256. }
  3257. }
  3258. // Yearly header
  3259. elseif ($display == 'yearly')
  3260. {
  3261. $heading_date_yearly = gmdate('Y', $this->EE->localize->set_localized_time($row['entry_date']));
  3262. if ($heading_date_yearly == $heading_flag_yearly)
  3263. {
  3264. $tagdata = $this->EE->TMPL->delete_var_pairs($key, 'date_heading', $tagdata);
  3265. }
  3266. else
  3267. {
  3268. $tagdata = $this->EE->TMPL->swap_var_pairs($key, 'date_heading', $tagdata);
  3269. $heading_flag_yearly = $heading_date_yearly;
  3270. }
  3271. }
  3272. // Default (daily) header
  3273. else
  3274. {
  3275. $heading_date_daily = gmdate('Ymd', $this->EE->localize->set_localized_time($row['entry_date']));
  3276. if ($heading_date_daily == $heading_flag_daily)
  3277. {
  3278. $tagdata = $this->EE->TMPL->delete_var_pairs($key, 'date_heading', $tagdata);
  3279. }
  3280. else
  3281. {
  3282. $tagdata = $this->EE->TMPL->swap_var_pairs($key, 'date_heading', $tagdata);
  3283. $heading_flag_daily = $heading_date_daily;
  3284. }
  3285. }
  3286. }
  3287. // END DATE HEADING
  3288. // parse date footer
  3289. if (strncmp($key, 'date_footer', 11) == 0)
  3290. {
  3291. // Set the display preference
  3292. $display = (is_array($val) AND isset($val['display'])) ? $val['display'] : 'daily';
  3293. // Hourly footer
  3294. if ($display == 'hourly')
  3295. {
  3296. if ( ! isset($query_result[$row['count']]) OR
  3297. gmdate('YmdH', $this->EE->localize->set_localized_time($row['entry_date'])) != gmdate('YmdH', $this->EE->localize->set_localized_time($query_result[$row['count']]['entry_date'])))
  3298. {
  3299. $tagdata = $this->EE->TMPL->swap_var_pairs($key, 'date_footer', $tagdata);
  3300. }
  3301. else
  3302. {
  3303. $tagdata = $this->EE->TMPL->delete_var_pairs($key, 'date_footer', $tagdata);
  3304. }
  3305. }
  3306. // Weekly footer
  3307. elseif ($display == 'weekly')
  3308. {
  3309. if ( ! isset($query_result[$row['count']]) OR
  3310. gmdate('YW', $this->EE->localize->set_localized_time($row['entry_date'])) != gmdate('YW', $this->EE->localize->set_localized_time($query_result[$row['count']]['entry_date'])))
  3311. {
  3312. $tagdata = $this->EE->TMPL->swap_var_pairs($key, 'date_footer', $tagdata);
  3313. }
  3314. else
  3315. {
  3316. $tagdata = $this->EE->TMPL->delete_var_pairs($key, 'date_footer', $tagdata);
  3317. }
  3318. }
  3319. // Monthly footer
  3320. elseif ($display == 'monthly')
  3321. {
  3322. if ( ! isset($query_result[$row['count']]) OR
  3323. gmdate('Ym', $this->EE->localize->set_localized_time($row['entry_date'])) != gmdate('Ym', $this->EE->localize->set_localized_time($query_result[$row['count']]['entry_date'])))
  3324. {
  3325. $tagdata = $this->EE->TMPL->swap_var_pairs($key, 'date_footer', $tagdata);
  3326. }
  3327. else
  3328. {
  3329. $tagdata = $this->EE->TMPL->delete_var_pairs($key, 'date_footer', $tagdata);
  3330. }
  3331. }
  3332. // Yearly footer
  3333. elseif ($display == 'yearly')
  3334. {
  3335. if ( ! isset($query_result[$row['count']]) OR
  3336. gmdate('Y', $this->EE->localize->set_localized_time($row['entry_date'])) != gmdate('Y', $this->EE->localize->set_localized_time($query_result[$row['count']]['entry_date'])))
  3337. {
  3338. $tagdata = $this->EE->TMPL->swap_var_pairs($key, 'date_footer', $tagdata);
  3339. }
  3340. else
  3341. {
  3342. $tagdata = $this->EE->TMPL->delete_var_pairs($key, 'date_footer', $tagdata);
  3343. }
  3344. }
  3345. // Default (daily) footer
  3346. else
  3347. {
  3348. if ( ! isset($query_result[$row['count']]) OR
  3349. gmdate('Ymd', $this->EE->localize->set_localized_time($row['entry_date'])) != gmdate('Ymd', $this->EE->localize->set_localized_time($query_result[$row['count']]['entry_date'])))
  3350. {
  3351. $tagdata = $this->EE->TMPL->swap_var_pairs($key, 'date_footer', $tagdata);
  3352. }
  3353. else
  3354. {
  3355. $tagdata = $this->EE->TMPL->delete_var_pairs($key, 'date_footer', $tagdata);
  3356. }
  3357. }
  3358. }
  3359. // END DATE FOOTER
  3360. }
  3361. // END VARIABLE PAIRS
  3362. // We swap out the conditionals after pairs are parsed so they don't interfere
  3363. // with the string replace
  3364. $tagdata = $this->EE->functions->prep_conditionals($tagdata, $cond);
  3365. // Parse "single" variables
  3366. foreach ($this->EE->TMPL->var_single as $key => $val)
  3367. {
  3368. /**--------
  3369. /** parse simple conditionals: {body|more|summary}
  3370. /**--------*/
  3371. // Note: This must happen first.
  3372. if (strpos($key, '|') !== FALSE && is_array($val))
  3373. {
  3374. foreach($val as $item)
  3375. {
  3376. // Basic fields
  3377. if (isset($row[$item]) AND $row[$item] != "")
  3378. {
  3379. $tagdata = $this->EE->TMPL->swap_var_single($key, $row[$item], $tagdata);
  3380. continue;
  3381. }
  3382. // Custom channel fields
  3383. if ( isset( $this->cfields[$row['site_id']][$item] ) AND isset( $row['field_id_'.$this->cfields[$row['site_id']][$item]] ) AND $row['field_id_'.$this->cfields[$row['site_id']][$item]] != "")
  3384. {
  3385. $entry = $this->EE->typography->parse_type(
  3386. $row['field_id_'.$this->cfields[$row['site_id']][$item]],
  3387. array(
  3388. 'text_format' => $row['field_ft_'.$this->cfields[$row['site_id']][$item]],
  3389. 'html_format' => $row['channel_html_formatting'],
  3390. 'auto_links' => $row['channel_auto_link_urls'],
  3391. 'allow_img_url' => $row['channel_allow_img_urls']
  3392. )
  3393. );
  3394. $tagdata = $this->EE->TMPL->swap_var_single($key, $entry, $tagdata);
  3395. continue;
  3396. }
  3397. }
  3398. // Garbage collection
  3399. $val = '';
  3400. $tagdata = $this->EE->TMPL->swap_var_single($key, "", $tagdata);
  3401. }
  3402. // parse {switch} variable
  3403. if (preg_match("/^switch\s*=.+/i", $key))
  3404. {
  3405. $sparam = $this->EE->functions->assign_parameters($key);
  3406. $sw = '';
  3407. if (isset($sparam['switch']))
  3408. {
  3409. $sopt = explode("|", $sparam['switch']);
  3410. $sw = $sopt[($count + count($sopt)) % count($sopt)];
  3411. }
  3412. $tagdata = $this->EE->TMPL->swap_var_single($key, $sw, $tagdata);
  3413. }
  3414. // parse entry date
  3415. if (isset($entry_date[$key]))
  3416. {
  3417. $val = str_replace($entry_date[$key], $this->EE->localize->convert_timestamp($entry_date[$key], $row['entry_date'], TRUE), $val);
  3418. $tagdata = $this->EE->TMPL->swap_var_single($key, $val, $tagdata);
  3419. }
  3420. // Recent Comment Date
  3421. if (isset($recent_comment_date[$key]))
  3422. {
  3423. if ($row['recent_comment_date'] != 0)
  3424. {
  3425. $val = str_replace($recent_comment_date[$key], $this->EE->localize->convert_timestamp($recent_comment_date[$key], $row['recent_comment_date'], TRUE), $val);
  3426. $tagdata = $this->EE->TMPL->swap_var_single($key, $val, $tagdata);
  3427. }
  3428. else
  3429. {
  3430. $tagdata = str_replace(LD.$key.RD, '', $tagdata);
  3431. }
  3432. }
  3433. // GMT date - entry date in GMT
  3434. if (isset($gmt_entry_date[$key]))
  3435. {
  3436. $val = str_replace($gmt_entry_date[$key], $this->EE->localize->convert_timestamp($gmt_entry_date[$key], $row['entry_date'], FALSE), $val);
  3437. $tagdata = $this->EE->TMPL->swap_var_single($key, $val, $tagdata);
  3438. }
  3439. if (isset($gmt_date[$key]))
  3440. {
  3441. $val = str_replace($gmt_date[$key], $this->EE->localize->convert_timestamp($gmt_date[$key], $row['entry_date'], FALSE), $val);
  3442. $tagdata = $this->EE->TMPL->swap_var_single($key, $val, $tagdata);
  3443. }
  3444. // parse "last edit" date
  3445. if (isset($edit_date[$key]))
  3446. {
  3447. $val = str_replace($edit_date[$key], $this->EE->localize->convert_timestamp($edit_date[$key], $this->EE->localize->timestamp_to_gmt($row['edit_date']), TRUE), $val);
  3448. $tagdata = $this->EE->TMPL->swap_var_single($key, $val, $tagdata);
  3449. }
  3450. // "last edit" date as GMT
  3451. if (isset($gmt_edit_date[$key]))
  3452. {
  3453. $val = str_replace($gmt_edit_date[$key], $this->EE->localize->convert_timestamp($gmt_edit_date[$key], $this->EE->localize->timestamp_to_gmt($row['edit_date']), FALSE), $val);
  3454. $tagdata = $this->EE->TMPL->swap_var_single($key, $val, $tagdata);
  3455. }
  3456. // parse expiration date
  3457. if (isset($expiration_date[$key]))
  3458. {
  3459. if ($row['expiration_date'] != 0)
  3460. {
  3461. $val = str_replace($expiration_date[$key], $this->EE->localize->convert_timestamp($expiration_date[$key], $row['expiration_date'], TRUE), $val);
  3462. $tagdata = $this->EE->TMPL->swap_var_single($key, $val, $tagdata);
  3463. }
  3464. else
  3465. {
  3466. $tagdata = str_replace(LD.$key.RD, "", $tagdata);
  3467. }
  3468. }
  3469. // "week_date"
  3470. if (isset($week_date[$key]))
  3471. {
  3472. // Subtract the number of days the entry is "into" the week to get zero (Sunday)
  3473. // If the entry date is for Sunday, and Monday is being used as the week's start day,
  3474. // then we must back things up by six days
  3475. $offset = 0;
  3476. if (strtolower($this->EE->TMPL->fetch_param('start_day')) == 'monday')
  3477. {
  3478. $day_of_week = $this->EE->localize->convert_timestamp('%w', $row['entry_date'], TRUE);
  3479. if ($day_of_week == '0')
  3480. {
  3481. $offset = -518400; // back six days
  3482. }
  3483. else
  3484. {
  3485. $offset = 86400; // plus one day
  3486. }
  3487. }
  3488. $week_start_date = $row['entry_date'] - ($this->EE->localize->convert_timestamp('%w', $row['entry_date'], TRUE) * 60 * 60 * 24) + $offset;
  3489. $val = str_replace($week_date[$key], $this->EE->localize->convert_timestamp($week_date[$key], $week_start_date, TRUE), $val);
  3490. $tagdata = $this->EE->TMPL->swap_var_single($key, $val, $tagdata);
  3491. }
  3492. // parse profile path
  3493. if (strncmp($key, 'profile_path', 12) == 0)
  3494. {
  3495. $tagdata = $this->EE->TMPL->swap_var_single(
  3496. $key,
  3497. $this->EE->functions->create_url($this->EE->functions->extract_path($key).'/'.$row['member_id']),
  3498. $tagdata
  3499. );
  3500. }
  3501. // {member_search_path}
  3502. if (strncmp($key, 'member_search_path', 18) == 0)
  3503. {
  3504. $tagdata = $this->EE->TMPL->swap_var_single(
  3505. $key,
  3506. $search_link.$row['member_id'],
  3507. $tagdata
  3508. );
  3509. }
  3510. // parse comment_path
  3511. if (strncmp($key, 'comment_path', 12) == 0 OR strncmp($key, 'entry_id_path', 13) == 0)
  3512. {
  3513. $path = ($this->EE->functions->extract_path($key) != '' AND $this->EE->functions->extract_path($key) != 'SITE_INDEX') ? $this->EE->functions->extract_path($key).'/'.$row['entry_id'] : $row['entry_id'];
  3514. $tagdata = $this->EE->TMPL->swap_var_single(
  3515. $key,
  3516. $this->EE->functions->create_url($path),
  3517. $tagdata
  3518. );
  3519. }
  3520. // parse URL title path
  3521. if (strncmp($key, 'url_title_path', 14) == 0)
  3522. {
  3523. $path = ($this->EE->functions->extract_path($key) != '' AND $this->EE->functions->extract_path($key) != 'SITE_INDEX') ? $this->EE->functions->extract_path($key).'/'.$row['url_title'] : $row['url_title'];
  3524. $tagdata = $this->EE->TMPL->swap_var_single(
  3525. $key,
  3526. $this->EE->functions->create_url($path),
  3527. $tagdata
  3528. );
  3529. }
  3530. // parse title permalink
  3531. if (strncmp($key, 'title_permalink', 15) == 0)
  3532. {
  3533. $path = ($this->EE->functions->extract_path($key) != '' AND $this->EE->functions->extract_path($key) != 'SITE_INDEX') ? $this->EE->functions->extract_path($key).'/'.$row['url_title'] : $row['url_title'];
  3534. $tagdata = $this->EE->TMPL->swap_var_single(
  3535. $key,
  3536. $this->EE->functions->create_url($path, FALSE),
  3537. $tagdata
  3538. );
  3539. }
  3540. // parse permalink
  3541. if (strncmp($key, 'permalink', 9) == 0)
  3542. {
  3543. $path = ($this->EE->functions->extract_path($key) != '' AND $this->EE->functions->extract_path($key) != 'SITE_INDEX') ? $this->EE->functions->extract_path($key).'/'.$row['entry_id'] : $row['entry_id'];
  3544. $tagdata = $this->EE->TMPL->swap_var_single(
  3545. $key,
  3546. $this->EE->functions->create_url($path, FALSE),
  3547. $tagdata
  3548. );
  3549. }
  3550. // {comment_auto_path}
  3551. if ($key == "comment_auto_path")
  3552. {
  3553. $path = ($row['comment_url'] == '') ? $row['channel_url'] : $row['comment_url'];
  3554. $tagdata = $this->EE->TMPL->swap_var_single($key, $path, $tagdata);
  3555. }
  3556. // {comment_url_title_auto_path}
  3557. if ($key == "comment_url_title_auto_path")
  3558. {
  3559. $path = ($row['comment_url'] == '') ? $row['channel_url'] : $row['comment_url'];
  3560. $tagdata = $this->EE->TMPL->swap_var_single(
  3561. $key,
  3562. reduce_double_slashes($path.'/'.$row['url_title']),
  3563. $tagdata
  3564. );
  3565. }
  3566. // {comment_entry_id_auto_path}
  3567. if ($key == "comment_entry_id_auto_path")
  3568. {
  3569. $path = ($row['comment_url'] == '') ? $row['channel_url'] : $row['comment_url'];
  3570. $tagdata = $this->EE->TMPL->swap_var_single(
  3571. $key,
  3572. reduce_double_slashes($path.'/'.$row['entry_id']),
  3573. $tagdata
  3574. );
  3575. }
  3576. // {author}
  3577. if ($key == "author")
  3578. {
  3579. $tagdata = $this->EE->TMPL->swap_var_single($val, ($row['screen_name'] != '') ? $row['screen_name'] : $row['username'], $tagdata);
  3580. }
  3581. // {channel}
  3582. if ($key == "channel")
  3583. {
  3584. $tagdata = $this->EE->TMPL->swap_var_single($val, $row['channel_title'], $tagdata);
  3585. }
  3586. // {channel_short_name}
  3587. if ($key == "channel_short_name")
  3588. {
  3589. $tagdata = $this->EE->TMPL->swap_var_single($val, $row['channel_name'], $tagdata);
  3590. }
  3591. // {relative_date}
  3592. if ($key == "relative_date")
  3593. {
  3594. $tagdata = $this->EE->TMPL->swap_var_single($val, $this->EE->localize->format_timespan($this->EE->localize->now - $row['entry_date']), $tagdata);
  3595. }
  3596. // {trimmed_url} - used by Atom feeds
  3597. if ($key == "trimmed_url")
  3598. {
  3599. $channel_url = (isset($row['channel_url']) AND $row['channel_url'] != '') ? $row['channel_url'] : '';
  3600. $channel_url = str_replace(array('http://','www.'), '', $channel_url);
  3601. $xe = explode("/", $channel_url);
  3602. $channel_url = current($xe);
  3603. $tagdata = $this->EE->TMPL->swap_var_single($val, $channel_url, $tagdata);
  3604. }
  3605. // {relative_url} - used by Atom feeds
  3606. if ($key == "relative_url")
  3607. {
  3608. $channel_url = (isset($row['channel_url']) AND $row['channel_url'] != '') ? $row['channel_url'] : '';
  3609. $channel_url = str_replace('http://', '', $channel_url);
  3610. if ($x = strpos($channel_url, "/"))
  3611. {
  3612. $channel_url = substr($channel_url, $x + 1);
  3613. }
  3614. $channel_url = rtrim($channel_url, '/');
  3615. $tagdata = $this->EE->TMPL->swap_var_single($val, $channel_url, $tagdata);
  3616. }
  3617. // {url_or_email}
  3618. if ($key == "url_or_email")
  3619. {
  3620. $tagdata = $this->EE->TMPL->swap_var_single($val, ($row['url'] != '') ? $row['url'] : $row['email'], $tagdata);
  3621. }
  3622. // {url_or_email_as_author}
  3623. if ($key == "url_or_email_as_author")
  3624. {
  3625. $name = ($row['screen_name'] != '') ? $row['screen_name'] : $row['username'];
  3626. if ($row['url'] != '')
  3627. {
  3628. $tagdata = $this->EE->TMPL->swap_var_single($val, "<a href=\"".$row['url']."\">".$name."</a>", $tagdata);
  3629. }
  3630. else
  3631. {
  3632. $tagdata = $this->EE->TMPL->swap_var_single($val, $this->EE->typography->encode_email($row['email'], $name), $tagdata);
  3633. }
  3634. }
  3635. // {url_or_email_as_link}
  3636. if ($key == "url_or_email_as_link")
  3637. {
  3638. if ($row['url'] != '')
  3639. {
  3640. $tagdata = $this->EE->TMPL->swap_var_single($val, "<a href=\"".$row['url']."\">".$row['url']."</a>", $tagdata);
  3641. }
  3642. else
  3643. {
  3644. $tagdata = $this->EE->TMPL->swap_var_single($val, $this->EE->typography->encode_email($row['email']), $tagdata);
  3645. }
  3646. }
  3647. // {signature}
  3648. if ($key == "signature")
  3649. {
  3650. if ($this->EE->session->userdata('display_signatures') == 'n' OR $row['signature'] == '' OR $this->EE->session->userdata('display_signatures') == 'n')
  3651. {
  3652. $tagdata = $this->EE->TMPL->swap_var_single($key, '', $tagdata);
  3653. }
  3654. else
  3655. {
  3656. $tagdata = $this->EE->TMPL->swap_var_single($key,
  3657. $this->EE->typography->parse_type($row['signature'], array(
  3658. 'text_format' => 'xhtml',
  3659. 'html_format' => 'safe',
  3660. 'auto_links' => 'y',
  3661. 'allow_img_url' => $this->EE->config->item('sig_allow_img_hotlink')
  3662. )
  3663. ), $tagdata);
  3664. }
  3665. }
  3666. if ($key == "signature_image_url")
  3667. {
  3668. if ($this->EE->session->userdata('display_signatures') == 'n' OR $row['sig_img_filename'] == '' OR $this->EE->session->userdata('display_signatures') == 'n')
  3669. {
  3670. $tagdata = $this->EE->TMPL->swap_var_single($key, '', $tagdata);
  3671. $tagdata = $this->EE->TMPL->swap_var_single('signature_image_width', '', $tagdata);
  3672. $tagdata = $this->EE->TMPL->swap_var_single('signature_image_height', '', $tagdata);
  3673. }
  3674. else
  3675. {
  3676. $tagdata = $this->EE->TMPL->swap_var_single($key, $this->EE->config->slash_item('sig_img_url').$row['sig_img_filename'], $tagdata);
  3677. $tagdata = $this->EE->TMPL->swap_var_single('signature_image_width', $row['sig_img_width'], $tagdata);
  3678. $tagdata = $this->EE->TMPL->swap_var_single('signature_image_height', $row['sig_img_height'], $tagdata);
  3679. }
  3680. }
  3681. if ($key == "avatar_url")
  3682. {
  3683. if ($this->EE->session->userdata('display_avatars') == 'n' OR $row['avatar_filename'] == '' OR $this->EE->session->userdata('display_avatars') == 'n')
  3684. {
  3685. $tagdata = $this->EE->TMPL->swap_var_single($key, '', $tagdata);
  3686. $tagdata = $this->EE->TMPL->swap_var_single('avatar_image_width', '', $tagdata);
  3687. $tagdata = $this->EE->TMPL->swap_var_single('avatar_image_height', '', $tagdata);
  3688. }
  3689. else
  3690. {
  3691. $tagdata = $this->EE->TMPL->swap_var_single($key, $this->EE->config->slash_item('avatar_url').$row['avatar_filename'], $tagdata);
  3692. $tagdata = $this->EE->TMPL->swap_var_single('avatar_image_width', $row['avatar_width'], $tagdata);
  3693. $tagdata = $this->EE->TMPL->swap_var_single('avatar_image_height', $row['avatar_height'], $tagdata);
  3694. }
  3695. }
  3696. if ($key == "photo_url")
  3697. {
  3698. if ($this->EE->session->userdata('display_photos') == 'n' OR $row['photo_filename'] == '' OR $this->EE->session->userdata('display_photos') == 'n')
  3699. {
  3700. $tagdata = $this->EE->TMPL->swap_var_single($key, '', $tagdata);
  3701. $tagdata = $this->EE->TMPL->swap_var_single('photo_image_width', '', $tagdata);
  3702. $tagdata = $this->EE->TMPL->swap_var_single('photo_image_height', '', $tagdata);
  3703. }
  3704. else
  3705. {
  3706. $tagdata = $this->EE->TMPL->swap_var_single($key, $this->EE->config->slash_item('photo_url').$row['photo_filename'], $tagdata);
  3707. $tagdata = $this->EE->TMPL->swap_var_single('photo_image_width', $row['photo_width'], $tagdata);
  3708. $tagdata = $this->EE->TMPL->swap_var_single('photo_image_height', $row['photo_height'], $tagdata);
  3709. }
  3710. }
  3711. // parse {title}
  3712. if ($key == 'title')
  3713. {
  3714. $row['title'] = str_replace(array('{', '}'), array('&#123;', '&#125;'), $row['title']);
  3715. $tagdata = $this->EE->TMPL->swap_var_single($val, $this->EE->typography->format_characters($row['title']), $tagdata);
  3716. }
  3717. // parse basic fields (username, screen_name, etc.)
  3718. // Use array_key_exists to handle null values
  3719. if ($val AND array_key_exists($val, $row))
  3720. {
  3721. $tagdata = $this->EE->TMPL->swap_var_single($val, $row[$val], $tagdata);
  3722. }
  3723. // parse custom date fields
  3724. if (isset($custom_date_fields[$key]) && isset($this->dfields[$row['site_id']]))
  3725. {
  3726. foreach ($this->dfields[$row['site_id']] as $dkey => $dval)
  3727. {
  3728. if (strncmp($key.' ', $dkey.' ', strlen($dkey.' ')) !== 0)
  3729. continue;
  3730. if ($row['field_id_'.$dval] == 0 OR $row['field_id_'.$dval] == '')
  3731. {
  3732. $tagdata = $this->EE->TMPL->swap_var_single($key, '', $tagdata);
  3733. continue;
  3734. }
  3735. // use a temporary variable in case the custom date variable is used
  3736. // multiple times with different formats; prevents localization from
  3737. // occurring multiple times on the same value
  3738. $temp_val = $row['field_id_'.$dval];
  3739. $localize = TRUE;
  3740. if (isset($row['field_dt_'.$dval]) AND $row['field_dt_'.$dval] != '')
  3741. {
  3742. $localize = TRUE;
  3743. if ($row['field_dt_'.$dval] != '')
  3744. {
  3745. $temp_val = $this->EE->localize->simpl_offset($temp_val, $row['field_dt_'.$dval]);
  3746. $localize = FALSE;
  3747. }
  3748. }
  3749. $val = str_replace($custom_date_fields[$key], $this->EE->localize->convert_timestamp($custom_date_fields[$key], $temp_val, $localize), $val);
  3750. $tagdata = $this->EE->TMPL->swap_var_single($key, $val, $tagdata);
  3751. }
  3752. }
  3753. // Assign Related Entry IDs
  3754. // When an entry has related entries within it, since the related entry ID
  3755. // is stored in the custom field itself we need to pull it out and set it
  3756. // aside so that when the related stuff is parsed out we'll have it.
  3757. // We also need to modify the marker in the template so that we can replace
  3758. // it with the right entry
  3759. if (isset($this->rfields[$row['site_id']][$val]))
  3760. {
  3761. // No relationship? Ditch the marker
  3762. if ( ! isset($row['field_id_'.$this->cfields[$row['site_id']][$val]]) OR
  3763. $row['field_id_'.$this->cfields[$row['site_id']][$val]] == 0 OR
  3764. ! preg_match_all("/".LD."REL\[".$val."\](.+?)REL".RD."/", $tagdata, $match)
  3765. )
  3766. {
  3767. // replace the marker with the {if no_related_entries} content
  3768. preg_match_all("/".LD."REL\[".$val."\](.+?)REL".RD."/", $tagdata, $matches);
  3769. foreach ($matches[1] as $match)
  3770. {
  3771. $tagdata = preg_replace("/".LD."REL\[".$val."\](.+?)REL".RD."/", $this->EE->TMPL->related_data[$match]['no_rel_content'], $tagdata);
  3772. }
  3773. }
  3774. else
  3775. {
  3776. for ($j = 0; $j < count($match[1]); $j++)
  3777. {
  3778. $this->related_entries[] = $row['field_id_'.$this->cfields[$row['site_id']][$val]].'_'.$match[1][$j];
  3779. $tagdata = preg_replace("/".LD."REL\[".$val."\](.+?)REL".RD."/", LD."REL[".$row['field_id_'.$this->cfields[$row['site_id']][$val]]."][".$val."]\\1REL".RD, $tagdata);
  3780. }
  3781. $tagdata = $this->EE->TMPL->swap_var_single($val, '', $tagdata);
  3782. }
  3783. }
  3784. // Clean up any unparsed relationship fields
  3785. if (isset($this->rfields[$row['site_id']]) && count($this->rfields[$row['site_id']]) > 0)
  3786. {
  3787. $tagdata = preg_replace("/".LD."REL\[".preg_quote($val,'/')."\](.+?)REL".RD."/", "", $tagdata);
  3788. }
  3789. // parse custom channel fields
  3790. $params = array();
  3791. $parse_fnc = 'replace_tag';
  3792. $parse_fnc_catchall = 'replace_tag_catchall';
  3793. $replace = $key;
  3794. if (($spc = strpos($key, ' ')) !== FALSE)
  3795. {
  3796. $params = $this->EE->functions->assign_parameters($key);
  3797. $val = $key = substr($key, 0, $spc);
  3798. }
  3799. if (($cln = strpos($key, ':')) !== FALSE)
  3800. {
  3801. $modifier = substr($key, $cln + 1);
  3802. $parse_fnc = 'replace_'.$modifier;
  3803. $val = $key = substr($key, 0, $cln);
  3804. }
  3805. if (isset($this->cfields[$row['site_id']][$key]))
  3806. {
  3807. if ( ! isset($row['field_id_'.$this->cfields[$row['site_id']][$val]]) OR $row['field_id_'.$this->cfields[$row['site_id']][$val]] == '')
  3808. {
  3809. $entry = '';
  3810. }
  3811. else
  3812. {
  3813. $this->EE->load->library('api');
  3814. $this->EE->api->instantiate('channel_fields');
  3815. $field_id = $this->cfields[$row['site_id']][$key];
  3816. if ($this->EE->api_channel_fields->setup_handler($field_id))
  3817. {
  3818. $this->EE->api_channel_fields->apply('_init', array(array('row' => $row)));
  3819. $data = $this->EE->api_channel_fields->apply('pre_process', array($row['field_id_'.$field_id]));
  3820. if ($this->EE->api_channel_fields->check_method_exists($parse_fnc))
  3821. {
  3822. $entry = $this->EE->api_channel_fields->apply($parse_fnc, array($data, $params, FALSE));
  3823. }
  3824. elseif ($this->EE->api_channel_fields->check_method_exists($parse_fnc_catchall))
  3825. {
  3826. $entry = $this->EE->api_channel_fields->apply($parse_fnc_catchall, array($data, $params, FALSE, $modifier));
  3827. }
  3828. else
  3829. {
  3830. $entry = '';
  3831. $this->EE->TMPL->log_item('Unable to find parse type for custom field: '.$parse_fnc);
  3832. }
  3833. }
  3834. else
  3835. {
  3836. // Couldn't find a fieldtype
  3837. $entry = $this->EE->typography->parse_type(
  3838. $this->EE->functions->encode_ee_tags($row['field_id_'.$this->cfields[$row['site_id']][$val]]),
  3839. array(
  3840. 'text_format' => $row['field_ft_'.$this->cfields[$row['site_id']][$val]],
  3841. 'html_format' => $row['channel_html_formatting'],
  3842. 'auto_links' => $row['channel_auto_link_urls'],
  3843. 'allow_img_url' => $row['channel_allow_img_urls']
  3844. )
  3845. );
  3846. }
  3847. }
  3848. // prevent accidental parsing of other channel variables in custom field data
  3849. if (strpos($entry, '{') !== FALSE)
  3850. {
  3851. $this->EE->load->helper('string');
  3852. $tagdata = $this->EE->TMPL->swap_var_single($replace, str_replace(array('{', '}'), array(unique_marker('channel_bracket_open'), unique_marker('channel_bracket_close')), $entry), $tagdata);
  3853. }
  3854. else
  3855. {
  3856. $tagdata = $this->EE->TMPL->swap_var_single($replace, $entry, $tagdata);
  3857. }
  3858. }
  3859. // parse custom member fields
  3860. if (isset($this->mfields[$val]) && array_key_exists('m_field_id_'.$value[0], $row))
  3861. {
  3862. if ( ! isset($processed_member_fields[$row['member_id']]['m_field_id_'.$this->mfields[$val][0]]))
  3863. {
  3864. $processed_member_fields[$row['member_id']]['m_field_id_'.$this->mfields[$val][0]] =
  3865. $this->EE->typography->parse_type(
  3866. $row['m_field_id_'.$this->mfields[$val][0]],
  3867. array(
  3868. 'text_format' => $this->mfields[$val][1],
  3869. 'html_format' => 'safe',
  3870. 'auto_links' => 'y',
  3871. 'allow_img_url' => 'n'
  3872. )
  3873. );
  3874. }
  3875. $tagdata = $this->EE->TMPL->swap_var_single(
  3876. $val,
  3877. $processed_member_fields[$row['member_id']]['m_field_id_'.$this->mfields[$val][0]],
  3878. $tagdata
  3879. );
  3880. }
  3881. }
  3882. // END SINGLE VARIABLES
  3883. // do we need to replace any curly braces that we protected in custom fields?
  3884. if (strpos($tagdata, unique_marker('channel_bracket_open')) !== FALSE)
  3885. {
  3886. $tagdata = str_replace(array(unique_marker('channel_bracket_open'), unique_marker('channel_bracket_close')), array('{', '}'), $tagdata);
  3887. }
  3888. // -------------------------------------------
  3889. // 'channel_entries_tagdata_end' hook.
  3890. // - Take the final results of an entry's parsing and do what you wish
  3891. //
  3892. if ($this->EE->extensions->active_hook('channel_entries_tagdata_end') === TRUE)
  3893. {
  3894. $tagdata = $this->EE->extensions->call('channel_entries_tagdata_end', $tagdata, $row, $this);
  3895. if ($this->EE->extensions->end_script === TRUE) return $tagdata;
  3896. }
  3897. //
  3898. // -------------------------------------------
  3899. $this->return_data .= $tagdata;
  3900. }
  3901. // END FOREACH LOOP
  3902. // Kill multi_field variable
  3903. if (strpos($this->return_data, 'multi_field=') !== FALSE)
  3904. {
  3905. $this->return_data = preg_replace("/".LD."multi_field\=[\"'](.+?)[\"']".RD."/s", "", $this->return_data);
  3906. }
  3907. // Do we have backspacing?
  3908. if ($back = $this->EE->TMPL->fetch_param('backspace'))
  3909. {
  3910. if (is_numeric($back))
  3911. {
  3912. $this->return_data = substr($this->return_data, 0, - $back);
  3913. }
  3914. }
  3915. }
  3916. /**
  3917. * Sends custom field data to fieldtypes before the entries loop runs.
  3918. * This is particularly helpful to fieldtypes that need to query the database
  3919. * based on what they're passed, like the File field. This allows them to run
  3920. * potentially a single query to gather needed data instead of a query for
  3921. * each row.
  3922. *
  3923. * @param string $entries_data
  3924. * @return void
  3925. */
  3926. private function _send_custom_field_data_to_fieldtypes($entries_data)
  3927. {
  3928. // We'll stick custom field data into this array in the form of:
  3929. // field_id => array('data1', 'data2', ...);
  3930. $custom_field_data = array();
  3931. // Loop through channel entry data
  3932. foreach ($entries_data as $row)
  3933. {
  3934. // Get array of custom fields for the row's current site
  3935. $custom_fields = $this->cfields[$row['site_id']];
  3936. foreach ($custom_fields as $field_name => $field_id)
  3937. {
  3938. // If the field exists and isn't empty
  3939. if (isset($row['field_id_'.$field_id]))
  3940. {
  3941. if ( ! empty($row['field_id_'.$field_id]))
  3942. {
  3943. // Add the data to our custom field data array
  3944. $custom_field_data[$field_id][] = $row['field_id_'.$field_id];
  3945. }
  3946. }
  3947. }
  3948. }
  3949. if ( ! empty($custom_field_data))
  3950. {
  3951. $this->EE->load->library('api');
  3952. $this->EE->api->instantiate('channel_fields');
  3953. // For each custom field, notify its fieldtype class of the data we collected
  3954. foreach ($custom_field_data as $field_id => $data)
  3955. {
  3956. if ($this->EE->api_channel_fields->setup_handler($field_id))
  3957. {
  3958. if ($this->EE->api_channel_fields->check_method_exists('pre_loop'))
  3959. {
  3960. $this->EE->api_channel_fields->apply('pre_loop', array($data));
  3961. }
  3962. }
  3963. }
  3964. }
  3965. }
  3966. // ------------------------------------------------------------------------
  3967. /**
  3968. * Channel Info Tag
  3969. */
  3970. public function info()
  3971. {
  3972. if ( ! $channel_name = $this->EE->TMPL->fetch_param('channel'))
  3973. {
  3974. return '';
  3975. }
  3976. if (count($this->EE->TMPL->var_single) == 0)
  3977. {
  3978. return '';
  3979. }
  3980. $params = array(
  3981. 'channel_title',
  3982. 'channel_url',
  3983. 'channel_description',
  3984. 'channel_lang'
  3985. );
  3986. $q = '';
  3987. $tags = FALSE;
  3988. $charset = $this->EE->config->item('charset');
  3989. foreach ($this->EE->TMPL->var_single as $val)
  3990. {
  3991. if (in_array($val, $params))
  3992. {
  3993. $tags = TRUE;
  3994. $q .= $val.',';
  3995. }
  3996. elseif ($val == 'channel_encoding')
  3997. {
  3998. $tags = TRUE;
  3999. }
  4000. }
  4001. $q = substr($q, 0, -1);
  4002. if ($tags == FALSE)
  4003. {
  4004. return '';
  4005. }
  4006. $sql = "SELECT ".$q." FROM exp_channels ";
  4007. $sql .= " WHERE site_id IN ('".implode("','", $this->EE->TMPL->site_ids)."') ";
  4008. if ($channel_name != '')
  4009. {
  4010. $sql .= " AND channel_name = '".$this->EE->db->escape_str($channel_name)."'";
  4011. }
  4012. $query = $this->EE->db->query($sql);
  4013. if ($query->num_rows() != 1)
  4014. {
  4015. return '';
  4016. }
  4017. // We add in the channel_encoding
  4018. $cond_vars = array_merge($query->row_array(), array('channel_encoding' => $charset));
  4019. $this->EE->TMPL->tagdata = $this->EE->functions->prep_conditionals($this->EE->TMPL->tagdata, $cond_vars);
  4020. foreach ($query->row_array() as $key => $val)
  4021. {
  4022. $this->EE->TMPL->tagdata = str_replace(LD.$key.RD, $val, $this->EE->TMPL->tagdata);
  4023. }
  4024. $this->EE->TMPL->tagdata = str_replace(LD.'channel_encoding'.RD, $charset, $this->EE->TMPL->tagdata);
  4025. return $this->EE->TMPL->tagdata;
  4026. }
  4027. // ------------------------------------------------------------------------
  4028. /**
  4029. * Channel Name
  4030. */
  4031. public function channel_name()
  4032. {
  4033. $channel_name = $this->EE->TMPL->fetch_param('channel');
  4034. if (isset($this->channel_name[$channel_name]))
  4035. {
  4036. return $this->channel_name[$channel_name];
  4037. }
  4038. $sql = "SELECT channel_title FROM exp_channels ";
  4039. $sql .= " WHERE site_id IN ('".implode("','", $this->EE->TMPL->site_ids)."') ";
  4040. if ($channel_name != '')
  4041. {
  4042. $sql .= " AND channel_name = '".$this->EE->db->escape_str($channel_name)."'";
  4043. }
  4044. $query = $this->EE->db->query($sql);
  4045. if ($query->num_rows() == 1)
  4046. {
  4047. $this->channel_name[$channel_name] = $query->row('channel_title') ;
  4048. return $query->row('channel_title') ;
  4049. }
  4050. else
  4051. {
  4052. return '';
  4053. }
  4054. }
  4055. // ------------------------------------------------------------------------
  4056. /**
  4057. * Channel Category Totals
  4058. *
  4059. * Need to finish this function. It lets a simple list of categories
  4060. * appear along with the post total.
  4061. */
  4062. public function category_totals()
  4063. {
  4064. $sql = "SELECT count( exp_category_posts.entry_id ) AS count,
  4065. exp_categories.cat_id,
  4066. exp_categories.cat_name
  4067. FROM exp_categories
  4068. LEFT JOIN exp_category_posts ON exp_category_posts.cat_id = exp_categories.cat_id
  4069. GROUP BY exp_categories.cat_id
  4070. ORDER BY group_id, parent_id, cat_order";
  4071. }
  4072. // ------------------------------------------------------------------------
  4073. /**
  4074. * Channel Categories
  4075. */
  4076. public function categories()
  4077. {
  4078. // -------------------------------------------
  4079. // 'channel_module_categories_start' hook.
  4080. // - Rewrite the displaying of categories, if you dare!
  4081. //
  4082. if ($this->EE->extensions->active_hook('channel_module_categories_start') === TRUE)
  4083. {
  4084. return $this->EE->extensions->call('channel_module_categories_start');
  4085. }
  4086. //
  4087. // -------------------------------------------
  4088. $sql = "SELECT DISTINCT cat_group, channel_id FROM exp_channels WHERE site_id IN ('".implode("','", $this->EE->TMPL->site_ids)."') ";
  4089. if ($channel = $this->EE->TMPL->fetch_param('channel'))
  4090. {
  4091. $sql .= $this->EE->functions->sql_andor_string($this->EE->TMPL->fetch_param('channel'), 'channel_name');
  4092. }
  4093. $cat_groups = $this->EE->db->query($sql);
  4094. if ($cat_groups->num_rows() == 0)
  4095. {
  4096. return;
  4097. }
  4098. $channel_ids = array();
  4099. $group_ids = array();
  4100. foreach ($cat_groups->result_array() as $group)
  4101. {
  4102. $channel_ids[] = $group['channel_id'];
  4103. $group_ids[] = $group['cat_group'];
  4104. }
  4105. // Combine the group IDs from multiple channels into a string
  4106. $group_ids = implode('|', $group_ids);
  4107. if ($category_group = $this->EE->TMPL->fetch_param('category_group'))
  4108. {
  4109. if (substr($category_group, 0, 4) == 'not ')
  4110. {
  4111. $x = explode('|', substr($category_group, 4));
  4112. $groups = array_diff(explode('|', $group_ids), $x);
  4113. }
  4114. else
  4115. {
  4116. $x = explode('|', $category_group);
  4117. $groups = array_intersect(explode('|', $group_ids), $x);
  4118. }
  4119. if (count($groups) == 0)
  4120. {
  4121. return '';
  4122. }
  4123. else
  4124. {
  4125. $group_ids = implode('|', $groups);
  4126. }
  4127. }
  4128. $parent_only = ($this->EE->TMPL->fetch_param('parent_only') == 'yes') ? TRUE : FALSE;
  4129. $path = array();
  4130. if (preg_match_all("#".LD."path(=.+?)".RD."#", $this->EE->TMPL->tagdata, $matches))
  4131. {
  4132. for ($i = 0; $i < count($matches[0]); $i++)
  4133. {
  4134. if ( ! isset($path[$matches[0][$i]]))
  4135. {
  4136. $path[$matches[0][$i]] = $this->EE->functions->create_url($this->EE->functions->extract_path($matches[1][$i]));
  4137. }
  4138. }
  4139. }
  4140. $str = '';
  4141. $strict_empty = ($this->EE->TMPL->fetch_param('restrict_channel') == 'no') ? 'no' : 'yes';
  4142. if ($this->EE->TMPL->fetch_param('style') == '' OR $this->EE->TMPL->fetch_param('style') == 'nested')
  4143. {
  4144. $this->category_tree(array(
  4145. 'group_id' => $group_ids,
  4146. 'channel_ids' => $channel_ids,
  4147. 'template' => $this->EE->TMPL->tagdata,
  4148. 'path' => $path,
  4149. 'channel_array' => '',
  4150. 'parent_only' => $parent_only,
  4151. 'show_empty' => $this->EE->TMPL->fetch_param('show_empty'),
  4152. 'strict_empty' => $strict_empty
  4153. ));
  4154. if (count($this->category_list) > 0)
  4155. {
  4156. $i = 0;
  4157. $id_name = ( ! $this->EE->TMPL->fetch_param('id')) ? 'nav_categories' : $this->EE->TMPL->fetch_param('id');
  4158. $class_name = ( ! $this->EE->TMPL->fetch_param('class')) ? 'nav_categories' : $this->EE->TMPL->fetch_param('class');
  4159. $this->category_list[0] = '<ul id="'.$id_name.'" class="'.$class_name.'">'."\n";
  4160. foreach ($this->category_list as $val)
  4161. {
  4162. $str .= $val;
  4163. }
  4164. }
  4165. }
  4166. else
  4167. {
  4168. // fetch category field names and id's
  4169. if ($this->enable['category_fields'] === TRUE)
  4170. {
  4171. $query = $this->EE->db->query("SELECT field_id, field_name FROM exp_category_fields
  4172. WHERE site_id IN ('".implode("','", $this->EE->TMPL->site_ids)."')
  4173. AND group_id IN ('".str_replace('|', "','", $this->EE->db->escape_str($group_ids))."')");
  4174. if ($query->num_rows() > 0)
  4175. {
  4176. foreach ($query->result_array() as $row)
  4177. {
  4178. $this->catfields[] = array('field_name' => $row['field_name'], 'field_id' => $row['field_id']);
  4179. }
  4180. }
  4181. $field_sqla = ", cg.field_html_formatting, fd.* ";
  4182. $field_sqlb = " LEFT JOIN exp_category_field_data AS fd ON fd.cat_id = c.cat_id
  4183. LEFT JOIN exp_category_groups AS cg ON cg.group_id = c.group_id";
  4184. }
  4185. else
  4186. {
  4187. $field_sqla = '';
  4188. $field_sqlb = '';
  4189. }
  4190. $show_empty = $this->EE->TMPL->fetch_param('show_empty');
  4191. if ($show_empty == 'no')
  4192. {
  4193. // First we'll grab all category ID numbers
  4194. $query = $this->EE->db->query("SELECT cat_id, parent_id
  4195. FROM exp_categories
  4196. WHERE group_id IN ('".str_replace('|', "','", $this->EE->db->escape_str($group_ids))."')
  4197. ORDER BY group_id, parent_id, cat_order");
  4198. $all = array();
  4199. // No categories exist? Let's go home..
  4200. if ($query->num_rows() == 0)
  4201. {
  4202. return FALSE;
  4203. }
  4204. foreach($query->result_array() as $row)
  4205. {
  4206. $all[$row['cat_id']] = $row['parent_id'];
  4207. }
  4208. // Next we'l grab only the assigned categories
  4209. $sql = "SELECT DISTINCT(exp_categories.cat_id), parent_id FROM exp_categories
  4210. LEFT JOIN exp_category_posts ON exp_categories.cat_id = exp_category_posts.cat_id
  4211. LEFT JOIN exp_channel_titles ON exp_category_posts.entry_id = exp_channel_titles.entry_id
  4212. WHERE group_id IN ('".str_replace('|', "','", $this->EE->db->escape_str($group_ids))."') ";
  4213. $sql .= "AND exp_category_posts.cat_id IS NOT NULL ";
  4214. if ($strict_empty == 'yes')
  4215. {
  4216. $sql .= "AND exp_channel_titles.channel_id IN ('".implode("','", $channel_ids)."') ";
  4217. }
  4218. else
  4219. {
  4220. $sql .= "AND exp_channel_titles.site_id IN ('".implode("','", $this->EE->TMPL->site_ids)."') ";
  4221. }
  4222. if (($status = $this->EE->TMPL->fetch_param('status')) !== FALSE)
  4223. {
  4224. $status = str_replace(array('Open', 'Closed'), array('open', 'closed'), $status);
  4225. $sql .= $this->EE->functions->sql_andor_string($status, 'exp_channel_titles.status');
  4226. }
  4227. else
  4228. {
  4229. $sql .= "AND exp_channel_titles.status != 'closed' ";
  4230. }
  4231. /**------
  4232. /** We only select entries that have not expired
  4233. /**------*/
  4234. $timestamp = ($this->EE->TMPL->cache_timestamp != '') ? $this->EE->TMPL->cache_timestamp : $this->EE->localize->now;
  4235. if ($this->EE->TMPL->fetch_param('show_future_entries') != 'yes')
  4236. {
  4237. $sql .= " AND exp_channel_titles.entry_date < ".$timestamp." ";
  4238. }
  4239. if ($this->EE->TMPL->fetch_param('show_expired') != 'yes')
  4240. {
  4241. $sql .= " AND (exp_channel_titles.expiration_date = 0 OR exp_channel_titles.expiration_date > ".$timestamp.") ";
  4242. }
  4243. if ($parent_only === TRUE)
  4244. {
  4245. $sql .= " AND parent_id = 0";
  4246. }
  4247. $sql .= " ORDER BY group_id, parent_id, cat_order";
  4248. $query = $this->EE->db->query($sql);
  4249. if ($query->num_rows() == 0)
  4250. {
  4251. return FALSE;
  4252. }
  4253. // All the magic happens here, baby!!
  4254. foreach($query->result_array() as $row)
  4255. {
  4256. if ($row['parent_id'] != 0)
  4257. {
  4258. $this->find_parent($row['parent_id'], $all);
  4259. }
  4260. $this->cat_full_array[] = $row['cat_id'];
  4261. }
  4262. $this->cat_full_array = array_unique($this->cat_full_array);
  4263. $sql = "SELECT c.cat_id, c.parent_id, c.cat_name, c.cat_url_title, c.cat_image, c.cat_description {$field_sqla}
  4264. FROM exp_categories AS c
  4265. {$field_sqlb}
  4266. WHERE c.cat_id IN (";
  4267. foreach ($this->cat_full_array as $val)
  4268. {
  4269. $sql .= $val.',';
  4270. }
  4271. $sql = substr($sql, 0, -1).')';
  4272. $sql .= " ORDER BY c.group_id, c.parent_id, c.cat_order";
  4273. $query = $this->EE->db->query($sql);
  4274. if ($query->num_rows() == 0)
  4275. {
  4276. return FALSE;
  4277. }
  4278. }
  4279. else
  4280. {
  4281. $sql = "SELECT c.cat_name, c.cat_url_title, c.cat_image, c.cat_description, c.cat_id, c.parent_id {$field_sqla}
  4282. FROM exp_categories AS c
  4283. {$field_sqlb}
  4284. WHERE c.group_id IN ('".str_replace('|', "','", $this->EE->db->escape_str($group_ids))."') ";
  4285. if ($parent_only === TRUE)
  4286. {
  4287. $sql .= " AND c.parent_id = 0";
  4288. }
  4289. $sql .= " ORDER BY c.group_id, c.parent_id, c.cat_order";
  4290. $query = $this->EE->db->query($sql);
  4291. if ($query->num_rows() == 0)
  4292. {
  4293. return '';
  4294. }
  4295. }
  4296. // Here we check the show parameter to see if we have any
  4297. // categories we should be ignoring or only a certain group of
  4298. // categories that we should be showing. By doing this here before
  4299. // all of the nested processing we should keep out all but the
  4300. // request categories while also not having a problem with having a
  4301. // child but not a parent. As we all know, categories are not asexual.
  4302. if ($this->EE->TMPL->fetch_param('show') !== FALSE)
  4303. {
  4304. if (strncmp($this->EE->TMPL->fetch_param('show'), 'not ', 4) == 0)
  4305. {
  4306. $not_these = explode('|', trim(substr($this->EE->TMPL->fetch_param('show'), 3)));
  4307. }
  4308. else
  4309. {
  4310. $these = explode('|', trim($this->EE->TMPL->fetch_param('show')));
  4311. }
  4312. }
  4313. foreach($query->result_array() as $row)
  4314. {
  4315. if (isset($not_these) && in_array($row['cat_id'], $not_these))
  4316. {
  4317. continue;
  4318. }
  4319. elseif(isset($these) && ! in_array($row['cat_id'], $these))
  4320. {
  4321. continue;
  4322. }
  4323. $this->temp_array[$row['cat_id']] = array($row['cat_id'], $row['parent_id'], '1', $row['cat_name'], $row['cat_description'], $row['cat_image'], $row['cat_url_title']);
  4324. foreach ($row as $key => $val)
  4325. {
  4326. if (strpos($key, 'field') !== FALSE)
  4327. {
  4328. $this->temp_array[$row['cat_id']][$key] = $val;
  4329. }
  4330. }
  4331. }
  4332. foreach($this->temp_array as $key => $val)
  4333. {
  4334. if (0 == $val[1])
  4335. {
  4336. $this->cat_array[] = $val;
  4337. $this->process_subcategories($key);
  4338. }
  4339. }
  4340. unset($this->temp_array);
  4341. $this->EE->load->library('typography');
  4342. $this->EE->typography->initialize(array(
  4343. 'convert_curly' => FALSE
  4344. ));
  4345. $this->category_count = 0;
  4346. $total_results = count($this->cat_array);
  4347. // Get category ID from URL for {if active} conditional
  4348. $this->EE->load->helper('segment');
  4349. $active_cat = parse_category($this->query_string);
  4350. foreach ($this->cat_array as $key => $val)
  4351. {
  4352. $chunk = $this->EE->TMPL->tagdata;
  4353. $this->EE->load->library('file_field');
  4354. $cat_image = $this->EE->file_field->parse_field($val[5]);
  4355. $cat_vars = array(
  4356. 'category_name' => $val[3],
  4357. 'category_url_title' => $val[6],
  4358. 'category_description' => $val[4],
  4359. 'category_image' => $cat_image['url'],
  4360. 'category_id' => $val[0],
  4361. 'parent_id' => $val[1],
  4362. 'active' => ($active_cat == $val[0] || $active_cat == $val[6])
  4363. );
  4364. // add custom fields for conditionals prep
  4365. foreach ($this->catfields as $v)
  4366. {
  4367. $cat_vars[$v['field_name']] = ( ! isset($val['field_id_'.$v['field_id']])) ? '' : $val['field_id_'.$v['field_id']];
  4368. }
  4369. $cat_vars['count'] = ++$this->category_count;
  4370. $cat_vars['total_results'] = $total_results;
  4371. $chunk = $this->EE->functions->prep_conditionals($chunk, $cat_vars);
  4372. $chunk = str_replace(
  4373. array(
  4374. LD.'category_name'.RD,
  4375. LD.'category_url_title'.RD,
  4376. LD.'category_description'.RD,
  4377. LD.'category_image'.RD,
  4378. LD.'category_id'.RD,
  4379. LD.'parent_id'.RD
  4380. ),
  4381. array(
  4382. $val[3],
  4383. $val[6],
  4384. $val[4],
  4385. $cat_image['url'],
  4386. $val[0],
  4387. $val[1]
  4388. ),
  4389. $chunk
  4390. );
  4391. foreach($path as $k => $v)
  4392. {
  4393. if ($this->use_category_names == TRUE)
  4394. {
  4395. $chunk = str_replace($k, $this->EE->functions->remove_double_slashes($v.'/'.$this->reserved_cat_segment.'/'.$val[6]), $chunk);
  4396. }
  4397. else
  4398. {
  4399. $chunk = str_replace($k, $this->EE->functions->remove_double_slashes($v.'/C'.$val[0]), $chunk);
  4400. }
  4401. }
  4402. // parse custom fields
  4403. foreach($this->catfields as $cv)
  4404. {
  4405. if (isset($val['field_id_'.$cv['field_id']]) AND $val['field_id_'.$cv['field_id']] != '')
  4406. {
  4407. $field_content = $this->EE->typography->parse_type(
  4408. $val['field_id_'.$cv['field_id']],
  4409. array(
  4410. 'text_format' => $val['field_ft_'.$cv['field_id']],
  4411. 'html_format' => $val['field_html_formatting'],
  4412. 'auto_links' => 'n',
  4413. 'allow_img_url' => 'y'
  4414. )
  4415. );
  4416. $chunk = str_replace(LD.$cv['field_name'].RD, $field_content, $chunk);
  4417. }
  4418. else
  4419. {
  4420. // garbage collection
  4421. $chunk = str_replace(LD.$cv['field_name'].RD, '', $chunk);
  4422. }
  4423. }
  4424. /** --------------------------------
  4425. /** {count}
  4426. /** --------------------------------*/
  4427. if (strpos($chunk, LD.'count'.RD) !== FALSE)
  4428. {
  4429. $chunk = str_replace(LD.'count'.RD, $this->category_count, $chunk);
  4430. }
  4431. /** --------------------------------
  4432. /** {total_results}
  4433. /** --------------------------------*/
  4434. if (strpos($chunk, LD.'total_results'.RD) !== FALSE)
  4435. {
  4436. $chunk = str_replace(LD.'total_results'.RD, $total_results, $chunk);
  4437. }
  4438. $str .= $chunk;
  4439. }
  4440. if ($this->EE->TMPL->fetch_param('backspace'))
  4441. {
  4442. $str = substr($str, 0, - $this->EE->TMPL->fetch_param('backspace'));
  4443. }
  4444. }
  4445. if (strpos($str, '{filedir_') !== FALSE)
  4446. {
  4447. $this->EE->load->library('file_field');
  4448. $str = $this->EE->file_field->parse_string($str);
  4449. }
  4450. return $str;
  4451. }
  4452. // ------------------------------------------------------------------------
  4453. /**
  4454. * Process Subcategories
  4455. */
  4456. public function process_subcategories($parent_id)
  4457. {
  4458. foreach($this->temp_array as $key => $val)
  4459. {
  4460. if ($parent_id == $val[1])
  4461. {
  4462. $this->cat_array[] = $val;
  4463. $this->process_subcategories($key);
  4464. }
  4465. }
  4466. }
  4467. // ------------------------------------------------------------------------
  4468. /**
  4469. * Category archives
  4470. */
  4471. public function category_archive()
  4472. {
  4473. $sql = "SELECT DISTINCT cat_group, channel_id FROM exp_channels WHERE site_id IN ('".implode("','", $this->EE->TMPL->site_ids)."') ";
  4474. if ($channel = $this->EE->TMPL->fetch_param('channel'))
  4475. {
  4476. $sql .= $this->EE->functions->sql_andor_string($this->EE->TMPL->fetch_param('channel'), 'channel_name');
  4477. }
  4478. $cat_groups = $this->EE->db->query($sql);
  4479. if ($cat_groups->num_rows() == 0)
  4480. {
  4481. return;
  4482. }
  4483. $group_ids = $cat_groups->row('cat_group');
  4484. $channel_ids = array();
  4485. $group_ids = array();
  4486. foreach ($cat_groups->result_array() as $group)
  4487. {
  4488. $channel_ids[] = $group['channel_id'];
  4489. $group_ids[] = $group['cat_group'];
  4490. }
  4491. // Combine the group IDs from multiple channels into a string
  4492. $group_ids = implode('|', $group_ids);
  4493. $sql = "SELECT exp_category_posts.cat_id, exp_channel_titles.entry_id, exp_channel_titles.title, exp_channel_titles.url_title, exp_channel_titles.entry_date
  4494. FROM exp_channel_titles, exp_category_posts
  4495. WHERE channel_id IN ('".implode("','", $channel_ids)."')
  4496. AND exp_channel_titles.entry_id = exp_category_posts.entry_id ";
  4497. $timestamp = ($this->EE->TMPL->cache_timestamp != '') ? $this->EE->TMPL->cache_timestamp : $this->EE->localize->now;
  4498. if ($this->EE->TMPL->fetch_param('show_future_entries') != 'yes')
  4499. {
  4500. $sql .= "AND exp_channel_titles.entry_date < ".$timestamp." ";
  4501. }
  4502. if ($this->EE->TMPL->fetch_param('show_expired') != 'yes')
  4503. {
  4504. $sql .= "AND (exp_channel_titles.expiration_date = 0 OR exp_channel_titles.expiration_date > ".$timestamp.") ";
  4505. }
  4506. $sql .= "AND exp_channel_titles.status != 'closed' ";
  4507. if ($status = $this->EE->TMPL->fetch_param('status'))
  4508. {
  4509. $status = str_replace('Open', 'open', $status);
  4510. $status = str_replace('Closed', 'closed', $status);
  4511. $sql .= $this->EE->functions->sql_andor_string($status, 'exp_channel_titles.status');
  4512. }
  4513. else
  4514. {
  4515. $sql .= "AND exp_channel_titles.status = 'open' ";
  4516. }
  4517. if ($this->EE->TMPL->fetch_param('show') !== FALSE)
  4518. {
  4519. $sql .= $this->EE->functions->sql_andor_string($this->EE->TMPL->fetch_param('show'), 'exp_category_posts.cat_id').' ';
  4520. }
  4521. $orderby = $this->EE->TMPL->fetch_param('orderby');
  4522. switch ($orderby)
  4523. {
  4524. case 'date':
  4525. $sql .= "ORDER BY exp_channel_titles.entry_date";
  4526. break;
  4527. case 'expiration_date':
  4528. $sql .= "ORDER BY exp_channel_titles.expiration_date";
  4529. break;
  4530. case 'title':
  4531. $sql .= "ORDER BY exp_channel_titles.title";
  4532. break;
  4533. case 'comment_total':
  4534. $sql .= "ORDER BY exp_channel_titles.entry_date";
  4535. break;
  4536. case 'most_recent_comment':
  4537. $sql .= "ORDER BY exp_channel_titles.recent_comment_date desc, exp_channel_titles.entry_date";
  4538. break;
  4539. default:
  4540. $sql .= "ORDER BY exp_channel_titles.title";
  4541. break;
  4542. }
  4543. $sort = $this->EE->TMPL->fetch_param('sort');
  4544. switch ($sort)
  4545. {
  4546. case 'asc':
  4547. $sql .= " asc";
  4548. break;
  4549. case 'desc':
  4550. $sql .= " desc";
  4551. break;
  4552. default:
  4553. $sql .= " asc";
  4554. break;
  4555. }
  4556. $result = $this->EE->db->query($sql);
  4557. $channel_array = array();
  4558. $parent_only = ($this->EE->TMPL->fetch_param('parent_only') == 'yes') ? TRUE : FALSE;
  4559. // Gather patterns for parsing and replacement of variable pairs
  4560. $categories_pattern = "/".LD."categories\s*".RD."(.*?)".LD.'\/'."categories\s*".RD."/s";
  4561. $titles_pattern = "/".LD."entry_titles\s*".RD."(.*?)".LD.'\/'."entry_titles\s*".RD."/s";
  4562. $cat_chunk = (preg_match($categories_pattern, $this->EE->TMPL->tagdata, $match)) ? $match[1] : '';
  4563. $c_path = array();
  4564. if (preg_match_all("#".LD."path(=.+?)".RD."#", $cat_chunk, $matches))
  4565. {
  4566. for ($i = 0; $i < count($matches[0]); $i++)
  4567. {
  4568. $c_path[$matches[0][$i]] = $this->EE->functions->create_url($this->EE->functions->extract_path($matches[1][$i]));
  4569. }
  4570. }
  4571. $title_chunk = (preg_match($titles_pattern, $this->EE->TMPL->tagdata, $match)) ? $match[1] : '';
  4572. $t_path = array();
  4573. if (preg_match_all("#".LD."path(=.+?)".RD."#", $title_chunk, $matches))
  4574. {
  4575. for ($i = 0; $i < count($matches[0]); $i++)
  4576. {
  4577. $t_path[$matches[0][$i]] = $this->EE->functions->create_url($this->EE->functions->extract_path($matches[1][$i]));
  4578. }
  4579. }
  4580. $id_path = array();
  4581. if (preg_match_all("#".LD."entry_id_path(=.+?)".RD."#", $title_chunk, $matches))
  4582. {
  4583. for ($i = 0; $i < count($matches[0]); $i++)
  4584. {
  4585. $id_path[$matches[0][$i]] = $this->EE->functions->create_url($this->EE->functions->extract_path($matches[1][$i]));
  4586. }
  4587. }
  4588. $entry_date = array();
  4589. preg_match_all("/".LD."entry_date\s+format\s*=\s*(\042|\047)([^\\1]*?)\\1".RD."/s", $title_chunk, $matches);
  4590. {
  4591. $j = count($matches[0]);
  4592. for ($i = 0; $i < $j; $i++)
  4593. {
  4594. $matches[0][$i] = str_replace(array(LD,RD), '', $matches[0][$i]);
  4595. $entry_date[$matches[0][$i]] = $this->EE->localize->fetch_date_params($matches[2][$i]);
  4596. }
  4597. }
  4598. $return_data = '';
  4599. if ($this->EE->TMPL->fetch_param('style') == '' OR $this->EE->TMPL->fetch_param('style') == 'nested')
  4600. {
  4601. if ($result->num_rows() > 0 && $title_chunk != '')
  4602. {
  4603. $i = 0;
  4604. foreach($result->result_array() as $row)
  4605. {
  4606. $chunk = "<li>".str_replace(LD.'category_name'.RD, '', $title_chunk)."</li>";
  4607. foreach($t_path as $tkey => $tval)
  4608. {
  4609. $chunk = str_replace($tkey, $this->EE->functions->remove_double_slashes($tval.'/'.$row['url_title']), $chunk);
  4610. }
  4611. foreach($id_path as $tkey => $tval)
  4612. {
  4613. $chunk = str_replace($tkey, $this->EE->functions->remove_double_slashes($tval.'/'.$row['entry_id']), $chunk);
  4614. }
  4615. foreach($this->EE->TMPL->var_single as $key => $val)
  4616. {
  4617. if (isset($entry_date[$key]))
  4618. {
  4619. $val = str_replace($entry_date[$key], $this->EE->localize->convert_timestamp($entry_date[$key], $row['entry_date'], TRUE), $val);
  4620. $chunk = $this->EE->TMPL->swap_var_single($key, $val, $chunk);
  4621. }
  4622. }
  4623. $channel_array[$i.'_'.$row['cat_id']] = str_replace(LD.'title'.RD, $row['title'], $chunk);
  4624. $i++;
  4625. }
  4626. }
  4627. $this->category_tree(array(
  4628. 'group_id' => $group_ids,
  4629. 'channel_ids' => $channel_ids,
  4630. 'path' => $c_path,
  4631. 'template' => $cat_chunk,
  4632. 'channel_array' => $channel_array,
  4633. 'parent_only' => $parent_only,
  4634. 'show_empty' => $this->EE->TMPL->fetch_param('show_empty'),
  4635. 'strict_empty' => 'yes'
  4636. ));
  4637. if (count($this->category_list) > 0)
  4638. {
  4639. $id_name = ($this->EE->TMPL->fetch_param('id') === FALSE) ? 'nav_cat_archive' : $this->EE->TMPL->fetch_param('id');
  4640. $class_name = ($this->EE->TMPL->fetch_param('class') === FALSE) ? 'nav_cat_archive' : $this->EE->TMPL->fetch_param('class');
  4641. $this->category_list[0] = '<ul id="'.$id_name.'" class="'.$class_name.'">'."\n";
  4642. foreach ($this->category_list as $val)
  4643. {
  4644. $return_data .= $val;
  4645. }
  4646. }
  4647. }
  4648. else
  4649. {
  4650. // fetch category field names and id's
  4651. if ($this->enable['category_fields'] === TRUE)
  4652. {
  4653. $query = $this->EE->db->query("SELECT field_id, field_name FROM exp_category_fields
  4654. WHERE site_id IN ('".implode("','", $this->EE->TMPL->site_ids)."')
  4655. AND group_id IN ('".str_replace('|', "','", $this->EE->db->escape_str($group_ids))."')");
  4656. if ($query->num_rows() > 0)
  4657. {
  4658. foreach ($query->result_array() as $row)
  4659. {
  4660. $this->catfields[] = array('field_name' => $row['field_name'], 'field_id' => $row['field_id']);
  4661. }
  4662. }
  4663. $field_sqla = ", cg.field_html_formatting, fd.* ";
  4664. $field_sqlb = " LEFT JOIN exp_category_field_data AS fd ON fd.cat_id = c.cat_id
  4665. LEFT JOIN exp_category_groups AS cg ON cg.group_id = c.group_id ";
  4666. }
  4667. else
  4668. {
  4669. $field_sqla = '';
  4670. $field_sqlb = '';
  4671. }
  4672. $sql = "SELECT DISTINCT (c.cat_id), c.cat_name, c.cat_url_title, c.cat_description, c.cat_image, c.parent_id {$field_sqla}
  4673. FROM (exp_categories AS c";
  4674. if ($this->EE->TMPL->fetch_param('show_empty') != 'no' AND count($channel_ids))
  4675. {
  4676. $sql .= ", exp_category_posts ";
  4677. }
  4678. $sql .= ") {$field_sqlb}";
  4679. if ($this->EE->TMPL->fetch_param('show_empty') == 'no')
  4680. {
  4681. $sql .= " LEFT JOIN exp_category_posts ON c.cat_id = exp_category_posts.cat_id ";
  4682. if (count($channel_ids))
  4683. {
  4684. $sql .= " LEFT JOIN exp_channel_titles ON exp_category_posts.entry_id = exp_channel_titles.entry_id ";
  4685. }
  4686. }
  4687. $sql .= " WHERE c.group_id IN ('".str_replace('|', "','", $this->EE->db->escape_str($group_ids))."') ";
  4688. if ($this->EE->TMPL->fetch_param('show_empty') == 'no')
  4689. {
  4690. if (count($channel_ids))
  4691. {
  4692. $sql .= "AND exp_channel_titles.channel_id IN ('".implode("','", $channel_ids)."') ";
  4693. }
  4694. else
  4695. {
  4696. $sql .= " AND exp_channel_titles.site_id IN ('".implode("','", $this->EE->TMPL->site_ids)."') ";
  4697. }
  4698. if ($status = $this->EE->TMPL->fetch_param('status'))
  4699. {
  4700. $status = str_replace('Open', 'open', $status);
  4701. $status = str_replace('Closed', 'closed', $status);
  4702. $sql .= $this->EE->functions->sql_andor_string($status, 'exp_channel_titles.status');
  4703. }
  4704. else
  4705. {
  4706. $sql .= "AND exp_channel_titles.status = 'open' ";
  4707. }
  4708. if ($this->EE->TMPL->fetch_param('show_empty') == 'no')
  4709. {
  4710. $sql .= "AND exp_category_posts.cat_id IS NOT NULL ";
  4711. }
  4712. }
  4713. if ($this->EE->TMPL->fetch_param('show') !== FALSE)
  4714. {
  4715. $sql .= $this->EE->functions->sql_andor_string($this->EE->TMPL->fetch_param('show'), 'c.cat_id').' ';
  4716. }
  4717. if ($parent_only == TRUE)
  4718. {
  4719. $sql .= " AND c.parent_id = 0";
  4720. }
  4721. $sql .= " ORDER BY c.group_id, c.parent_id, c.cat_order";
  4722. $query = $this->EE->db->query($sql);
  4723. if ($query->num_rows() > 0)
  4724. {
  4725. $this->EE->load->library('typography');
  4726. $this->EE->typography->initialize(array(
  4727. 'convert_curly' => FALSE)
  4728. );
  4729. $used = array();
  4730. // Get category ID from URL for {if active} conditional
  4731. $this->EE->load->helper('segment');
  4732. $active_cat = parse_category($this->query_string);
  4733. foreach($query->result_array() as $row)
  4734. {
  4735. // We'll concatenate parsed category and title chunks here for
  4736. // replacing in the tagdata later
  4737. $categories_parsed = '';
  4738. $titles_parsed = '';
  4739. if ( ! isset($used[$row['cat_name']]))
  4740. {
  4741. $chunk = $cat_chunk;
  4742. $this->EE->load->library('file_field');
  4743. $cat_image = $this->EE->file_field->parse_field($row['cat_image']);
  4744. $cat_vars = array('category_name' => $row['cat_name'],
  4745. 'category_url_title' => $row['cat_url_title'],
  4746. 'category_description' => $row['cat_description'],
  4747. 'category_image' => $cat_image['url'],
  4748. 'category_id' => $row['cat_id'],
  4749. 'parent_id' => $row['parent_id'],
  4750. 'active' => ($active_cat == $row['cat_id'] ||
  4751. $active_cat == $row['cat_url_title'])
  4752. );
  4753. foreach ($this->catfields as $v)
  4754. {
  4755. $cat_vars[$v['field_name']] = ( ! isset($row['field_id_'.$v['field_id']])) ? '' : $row['field_id_'.$v['field_id']];
  4756. }
  4757. $chunk = $this->EE->functions->prep_conditionals($chunk, $cat_vars);
  4758. $chunk = str_replace( array(LD.'category_id'.RD,
  4759. LD.'category_name'.RD,
  4760. LD.'category_url_title'.RD,
  4761. LD.'category_image'.RD,
  4762. LD.'category_description'.RD,
  4763. LD.'parent_id'.RD),
  4764. array($row['cat_id'],
  4765. $row['cat_name'],
  4766. $row['cat_url_title'],
  4767. $cat_image['url'],
  4768. $row['cat_description'],
  4769. $row['parent_id']),
  4770. $chunk);
  4771. foreach($c_path as $ckey => $cval)
  4772. {
  4773. $cat_seg = ($this->use_category_names == TRUE) ? $this->reserved_cat_segment.'/'.$row['cat_url_title'] : 'C'.$row['cat_id'];
  4774. $chunk = str_replace($ckey, $this->EE->functions->remove_double_slashes($cval.'/'.$cat_seg), $chunk);
  4775. }
  4776. // parse custom fields
  4777. foreach($this->catfields as $cfv)
  4778. {
  4779. if (isset($row['field_id_'.$cfv['field_id']]) AND $row['field_id_'.$cfv['field_id']] != '')
  4780. {
  4781. $field_content = $this->EE->typography->parse_type($row['field_id_'.$cfv['field_id']],
  4782. array(
  4783. 'text_format' => $row['field_ft_'.$cfv['field_id']],
  4784. 'html_format' => $row['field_html_formatting'],
  4785. 'auto_links' => 'n',
  4786. 'allow_img_url' => 'y'
  4787. )
  4788. );
  4789. $chunk = str_replace(LD.$cfv['field_name'].RD, $field_content, $chunk);
  4790. }
  4791. else
  4792. {
  4793. // garbage collection
  4794. $chunk = str_replace(LD.$cfv['field_name'].RD, '', $chunk);
  4795. }
  4796. }
  4797. // Check to see if we need to parse {filedir_n}
  4798. if (strpos($chunk, '{filedir_') !== FALSE)
  4799. {
  4800. $this->EE->load->library('file_field');
  4801. $chunk = $this->EE->file_field->parse_string($chunk);
  4802. }
  4803. $categories_parsed .= $chunk;
  4804. $used[$row['cat_name']] = TRUE;
  4805. }
  4806. foreach($result->result_array() as $trow)
  4807. {
  4808. if ($trow['cat_id'] == $row['cat_id'])
  4809. {
  4810. $chunk = str_replace(array(LD.'title'.RD, LD.'category_name'.RD),
  4811. array($trow['title'],$row['cat_name']),
  4812. $title_chunk);
  4813. foreach($t_path as $tkey => $tval)
  4814. {
  4815. $chunk = str_replace($tkey, $this->EE->functions->remove_double_slashes($tval.'/'.$trow['url_title']), $chunk);
  4816. }
  4817. foreach($id_path as $tkey => $tval)
  4818. {
  4819. $chunk = str_replace($tkey, $this->EE->functions->remove_double_slashes($tval.'/'.$trow['entry_id']), $chunk);
  4820. }
  4821. foreach($this->EE->TMPL->var_single as $key => $val)
  4822. {
  4823. if (isset($entry_date[$key]))
  4824. {
  4825. $val = str_replace($entry_date[$key], $this->EE->localize->convert_timestamp($entry_date[$key], $trow['entry_date'], TRUE), $val);
  4826. $chunk = $this->EE->TMPL->swap_var_single($key, $val, $chunk);
  4827. }
  4828. }
  4829. $titles_parsed .= $chunk;
  4830. }
  4831. }
  4832. // Parse row then concatenate on $return_data
  4833. $parsed_row = preg_replace($categories_pattern, $categories_parsed, $this->EE->TMPL->tagdata);
  4834. $parsed_row = preg_replace($titles_pattern, $titles_parsed, $parsed_row);
  4835. $return_data .= $parsed_row;
  4836. }
  4837. if ($this->EE->TMPL->fetch_param('backspace'))
  4838. {
  4839. $return_data = substr($return_data, 0, - $this->EE->TMPL->fetch_param('backspace'));
  4840. }
  4841. }
  4842. }
  4843. return $return_data;
  4844. }
  4845. // ------------------------------------------------------------------------
  4846. /** --------------------------------
  4847. /** Locate category parent
  4848. /** --------------------------------*/
  4849. // This little recursive gem will travel up the
  4850. // category tree until it finds the category ID
  4851. // number of any parents. It's used by the function
  4852. // below
  4853. public function find_parent($parent, $all)
  4854. {
  4855. foreach ($all as $cat_id => $parent_id)
  4856. {
  4857. if ($parent == $cat_id)
  4858. {
  4859. $this->cat_full_array[] = $cat_id;
  4860. if ($parent_id != 0)
  4861. $this->find_parent($parent_id, $all);
  4862. }
  4863. }
  4864. }
  4865. // ------------------------------------------------------------------------
  4866. /**
  4867. * Category Tree
  4868. *
  4869. * This function and the next create a nested, hierarchical category tree
  4870. */
  4871. public function category_tree($cdata = array())
  4872. {
  4873. $default = array('group_id', 'channel_ids', 'path', 'template', 'depth', 'channel_array', 'parent_only', 'show_empty', 'strict_empty');
  4874. foreach ($default as $val)
  4875. {
  4876. $$val = ( ! isset($cdata[$val])) ? '' : $cdata[$val];
  4877. }
  4878. if ($group_id == '')
  4879. {
  4880. return FALSE;
  4881. }
  4882. if ($this->enable['category_fields'] === TRUE)
  4883. {
  4884. $query = $this->EE->db->query("SELECT field_id, field_name
  4885. FROM exp_category_fields
  4886. WHERE site_id IN ('".implode("','", $this->EE->TMPL->site_ids)."')
  4887. AND group_id IN ('".str_replace('|', "','", $this->EE->db->escape_str($group_id))."')");
  4888. if ($query->num_rows() > 0)
  4889. {
  4890. foreach ($query->result_array() as $row)
  4891. {
  4892. $this->catfields[] = array('field_name' => $row['field_name'], 'field_id' => $row['field_id']);
  4893. }
  4894. }
  4895. $field_sqla = ", cg.field_html_formatting, fd.* ";
  4896. $field_sqlb = " LEFT JOIN exp_category_field_data AS fd ON fd.cat_id = c.cat_id
  4897. LEFT JOIN exp_category_groups AS cg ON cg.group_id = c.group_id";
  4898. }
  4899. else
  4900. {
  4901. $field_sqla = '';
  4902. $field_sqlb = '';
  4903. }
  4904. /** -----------------------------------
  4905. /** Are we showing empty categories
  4906. /** -----------------------------------*/
  4907. // If we are only showing categories that have been assigned to entries
  4908. // we need to run a couple queries and run a recursive function that
  4909. // figures out whether any given category has a parent.
  4910. // If we don't do this we will run into a problem in which parent categories
  4911. // that are not assigned to a channel will be supressed, and therefore, any of its
  4912. // children will be supressed also - even if they are assigned to entries.
  4913. // So... we will first fetch all the category IDs, then only the ones that are assigned
  4914. // to entries, and lastly we'll recursively run up the tree and fetch all parents.
  4915. // Follow that? No? Me neither...
  4916. if ($show_empty == 'no')
  4917. {
  4918. // First we'll grab all category ID numbers
  4919. $query = $this->EE->db->query("SELECT cat_id, parent_id FROM exp_categories
  4920. WHERE group_id IN ('".str_replace('|', "','", $this->EE->db->escape_str($group_id))."')
  4921. ORDER BY group_id, parent_id, cat_order");
  4922. $all = array();
  4923. // No categories exist? Back to the barn for the night..
  4924. if ($query->num_rows() == 0)
  4925. {
  4926. return FALSE;
  4927. }
  4928. foreach($query->result_array() as $row)
  4929. {
  4930. $all[$row['cat_id']] = $row['parent_id'];
  4931. }
  4932. // Next we'l grab only the assigned categories
  4933. $sql = "SELECT DISTINCT(exp_categories.cat_id), parent_id
  4934. FROM exp_categories
  4935. LEFT JOIN exp_category_posts ON exp_categories.cat_id = exp_category_posts.cat_id
  4936. LEFT JOIN exp_channel_titles ON exp_category_posts.entry_id = exp_channel_titles.entry_id ";
  4937. $sql .= "WHERE group_id IN ('".str_replace('|', "','", $this->EE->db->escape_str($group_id))."') ";
  4938. $sql .= "AND exp_category_posts.cat_id IS NOT NULL ";
  4939. if (count($channel_ids) && $strict_empty == 'yes')
  4940. {
  4941. $sql .= "AND exp_channel_titles.channel_id IN ('".implode("','", $channel_ids)."') ";
  4942. }
  4943. else
  4944. {
  4945. $sql .= "AND exp_channel_titles.site_id IN ('".implode("','", $this->EE->TMPL->site_ids)."') ";
  4946. }
  4947. if (($status = $this->EE->TMPL->fetch_param('status')) !== FALSE)
  4948. {
  4949. $status = str_replace(array('Open', 'Closed'), array('open', 'closed'), $status);
  4950. $sql .= $this->EE->functions->sql_andor_string($status, 'exp_channel_titles.status');
  4951. }
  4952. else
  4953. {
  4954. $sql .= "AND exp_channel_titles.status != 'closed' ";
  4955. }
  4956. /**------
  4957. /** We only select entries that have not expired
  4958. /**------*/
  4959. $timestamp = ($this->EE->TMPL->cache_timestamp != '') ? $this->EE->TMPL->cache_timestamp : $this->EE->localize->now;
  4960. if ($this->EE->TMPL->fetch_param('show_future_entries') != 'yes')
  4961. {
  4962. $sql .= " AND exp_channel_titles.entry_date < ".$timestamp." ";
  4963. }
  4964. if ($this->EE->TMPL->fetch_param('show_expired') != 'yes')
  4965. {
  4966. $sql .= " AND (exp_channel_titles.expiration_date = 0 OR exp_channel_titles.expiration_date > ".$timestamp.") ";
  4967. }
  4968. if ($parent_only === TRUE)
  4969. {
  4970. $sql .= " AND parent_id = 0";
  4971. }
  4972. $sql .= " ORDER BY group_id, parent_id, cat_order";
  4973. $query = $this->EE->db->query($sql);
  4974. if ($query->num_rows() == 0)
  4975. {
  4976. return FALSE;
  4977. }
  4978. // All the magic happens here, baby!!
  4979. foreach($query->result_array() as $row)
  4980. {
  4981. if ($row['parent_id'] != 0)
  4982. {
  4983. $this->find_parent($row['parent_id'], $all);
  4984. }
  4985. $this->cat_full_array[] = $row['cat_id'];
  4986. }
  4987. $this->cat_full_array = array_unique($this->cat_full_array);
  4988. $sql = "SELECT c.cat_id, c.parent_id, c.cat_name, c.cat_url_title, c.cat_image, c.cat_description {$field_sqla}
  4989. FROM exp_categories AS c
  4990. {$field_sqlb}
  4991. WHERE c.cat_id IN (";
  4992. foreach ($this->cat_full_array as $val)
  4993. {
  4994. $sql .= $val.',';
  4995. }
  4996. $sql = substr($sql, 0, -1).')';
  4997. $sql .= " ORDER BY c.group_id, c.parent_id, c.cat_order";
  4998. $query = $this->EE->db->query($sql);
  4999. if ($query->num_rows() == 0)
  5000. {
  5001. return FALSE;
  5002. }
  5003. }
  5004. else
  5005. {
  5006. $sql = "SELECT DISTINCT(c.cat_id), c.parent_id, c.cat_name, c.cat_url_title, c.cat_image, c.cat_description {$field_sqla}
  5007. FROM exp_categories AS c
  5008. {$field_sqlb}
  5009. WHERE c.group_id IN ('".str_replace('|', "','", $this->EE->db->escape_str($group_id))."') ";
  5010. if ($parent_only === TRUE)
  5011. {
  5012. $sql .= " AND c.parent_id = 0";
  5013. }
  5014. $sql .= " ORDER BY c.group_id, c.parent_id, c.cat_order";
  5015. $query = $this->EE->db->query($sql);
  5016. if ($query->num_rows() == 0)
  5017. {
  5018. return FALSE;
  5019. }
  5020. }
  5021. // Here we check the show parameter to see if we have any
  5022. // categories we should be ignoring or only a certain group of
  5023. // categories that we should be showing. By doing this here before
  5024. // all of the nested processing we should keep out all but the
  5025. // request categories while also not having a problem with having a
  5026. // child but not a parent. As we all know, categories are not asexual
  5027. if ($this->EE->TMPL->fetch_param('show') !== FALSE)
  5028. {
  5029. if (strncmp($this->EE->TMPL->fetch_param('show'), 'not ', 4) == 0)
  5030. {
  5031. $not_these = explode('|', trim(substr($this->EE->TMPL->fetch_param('show'), 3)));
  5032. }
  5033. else
  5034. {
  5035. $these = explode('|', trim($this->EE->TMPL->fetch_param('show')));
  5036. }
  5037. }
  5038. foreach($query->result_array() as $row)
  5039. {
  5040. if (isset($not_these) && in_array($row['cat_id'], $not_these))
  5041. {
  5042. continue;
  5043. }
  5044. elseif(isset($these) && ! in_array($row['cat_id'], $these))
  5045. {
  5046. continue;
  5047. }
  5048. $this->cat_array[$row['cat_id']] = array($row['parent_id'], $row['cat_name'], $row['cat_image'], $row['cat_description'], $row['cat_url_title']);
  5049. foreach ($row as $key => $val)
  5050. {
  5051. if (strpos($key, 'field') !== FALSE)
  5052. {
  5053. $this->cat_array[$row['cat_id']][$key] = $val;
  5054. }
  5055. }
  5056. }
  5057. $this->temp_array = $this->cat_array;
  5058. $open = 0;
  5059. $this->EE->load->library('typography');
  5060. $this->EE->typography->initialize(array(
  5061. 'convert_curly' => FALSE)
  5062. );
  5063. $this->category_count = 0;
  5064. $total_results = count($this->cat_array);
  5065. // Get category ID from URL for {if active} conditional
  5066. $this->EE->load->helper('segment');
  5067. $active_cat = parse_category($this->query_string);
  5068. $this->category_subtree(array(
  5069. 'parent_id' => '0',
  5070. 'path' => $path,
  5071. 'template' => $template,
  5072. 'channel_array' => $channel_array
  5073. ));
  5074. }
  5075. // ------------------------------------------------------------------------
  5076. /**
  5077. * Category Sub-tree
  5078. */
  5079. public function category_subtree($cdata = array())
  5080. {
  5081. $default = array('parent_id', 'path', 'template', 'depth', 'channel_array', 'show_empty');
  5082. foreach ($default as $val)
  5083. {
  5084. $$val = ( ! isset($cdata[$val])) ? '' : $cdata[$val];
  5085. }
  5086. $open = 0;
  5087. if ($depth == '')
  5088. $depth = 1;
  5089. $tab = '';
  5090. for ($i = 0; $i <= $depth; $i++)
  5091. $tab .= "\t";
  5092. $total_results = count($this->cat_array);
  5093. // Get category ID from URL for {if active} conditional
  5094. $this->EE->load->helper('segment');
  5095. $active_cat = parse_category($this->query_string);
  5096. foreach($this->cat_array as $key => $val)
  5097. {
  5098. if ($parent_id == $val[0])
  5099. {
  5100. if ($open == 0)
  5101. {
  5102. $open = 1;
  5103. $this->category_list[] = "\n".$tab."<ul>\n";
  5104. }
  5105. $chunk = $template;
  5106. $this->EE->load->library('file_field');
  5107. $cat_image = $this->EE->file_field->parse_field($val[2]);
  5108. $cat_vars = array('category_name' => $val[1],
  5109. 'category_url_title' => $val[4],
  5110. 'category_description' => $val[3],
  5111. 'category_image' => $cat_image['url'],
  5112. 'category_id' => $key,
  5113. 'parent_id' => $val[0],
  5114. 'active' => ($active_cat == $key || $active_cat == $val[4]));
  5115. // add custom fields for conditionals prep
  5116. foreach ($this->catfields as $v)
  5117. {
  5118. $cat_vars[$v['field_name']] = ( ! isset($val['field_id_'.$v['field_id']])) ? '' : $val['field_id_'.$v['field_id']];
  5119. }
  5120. $cat_vars['count'] = ++$this->category_count;
  5121. $cat_vars['total_results'] = $total_results;
  5122. $chunk = $this->EE->functions->prep_conditionals($chunk, $cat_vars);
  5123. $chunk = str_replace( array(LD.'category_id'.RD,
  5124. LD.'category_name'.RD,
  5125. LD.'category_url_title'.RD,
  5126. LD.'category_image'.RD,
  5127. LD.'category_description'.RD,
  5128. LD.'parent_id'.RD),
  5129. array($key,
  5130. $val[1],
  5131. $val[4],
  5132. $cat_image['url'],
  5133. $val[3],
  5134. $val[0]),
  5135. $chunk);
  5136. foreach($path as $pkey => $pval)
  5137. {
  5138. if ($this->use_category_names == TRUE)
  5139. {
  5140. $chunk = str_replace($pkey, $this->EE->functions->remove_double_slashes($pval.'/'.$this->reserved_cat_segment.'/'.$val[4]), $chunk);
  5141. }
  5142. else
  5143. {
  5144. $chunk = str_replace($pkey, $this->EE->functions->remove_double_slashes($pval.'/C'.$key), $chunk);
  5145. }
  5146. }
  5147. // parse custom fields
  5148. foreach($this->catfields as $ccv)
  5149. {
  5150. if (isset($val['field_id_'.$ccv['field_id']]) AND $val['field_id_'.$ccv['field_id']] != '')
  5151. {
  5152. $field_content = $this->EE->typography->parse_type($val['field_id_'.$ccv['field_id']],
  5153. array(
  5154. 'text_format' => $val['field_ft_'.$ccv['field_id']],
  5155. 'html_format' => $val['field_html_formatting'],
  5156. 'auto_links' => 'n',
  5157. 'allow_img_url' => 'y'
  5158. )
  5159. );
  5160. $chunk = str_replace(LD.$ccv['field_name'].RD, $field_content, $chunk);
  5161. }
  5162. else
  5163. {
  5164. // garbage collection
  5165. $chunk = str_replace(LD.$ccv['field_name'].RD, '', $chunk);
  5166. }
  5167. }
  5168. /** --------------------------------
  5169. /** {count}
  5170. /** --------------------------------*/
  5171. if (strpos($chunk, LD.'count'.RD) !== FALSE)
  5172. {
  5173. $chunk = str_replace(LD.'count'.RD, $this->category_count, $chunk);
  5174. }
  5175. /** --------------------------------
  5176. /** {total_results}
  5177. /** --------------------------------*/
  5178. if (strpos($chunk, LD.'total_results'.RD) !== FALSE)
  5179. {
  5180. $chunk = str_replace(LD.'total_results'.RD, $total_results, $chunk);
  5181. }
  5182. $this->category_list[] = $tab."\t<li>".$chunk;
  5183. if (is_array($channel_array))
  5184. {
  5185. $fillable_entries = 'n';
  5186. foreach($channel_array as $k => $v)
  5187. {
  5188. $k = substr($k, strpos($k, '_') + 1);
  5189. if ($key == $k)
  5190. {
  5191. if ( ! isset($fillable_entries) OR $fillable_entries == 'n')
  5192. {
  5193. $this->category_list[] = "\n{$tab}\t\t<ul>\n";
  5194. $fillable_entries = 'y';
  5195. }
  5196. $this->category_list[] = "{$tab}\t\t\t$v";
  5197. }
  5198. }
  5199. }
  5200. if (isset($fillable_entries) && $fillable_entries == 'y')
  5201. {
  5202. $this->category_list[] = "{$tab}\t\t</ul>\n";
  5203. }
  5204. $t = '';
  5205. if ($this->category_subtree(
  5206. array(
  5207. 'parent_id' => $key,
  5208. 'path' => $path,
  5209. 'template' => $template,
  5210. 'depth' => $depth + 2,
  5211. 'channel_array' => $channel_array
  5212. )
  5213. ) != 0 );
  5214. if (isset($fillable_entries) && $fillable_entries == 'y')
  5215. {
  5216. $t .= "$tab\t";
  5217. }
  5218. $this->category_list[] = $t."</li>\n";
  5219. unset($this->temp_array[$key]);
  5220. $this->close_ul($parent_id, $depth + 1);
  5221. }
  5222. }
  5223. return $open;
  5224. }
  5225. // ------------------------------------------------------------------------
  5226. /**
  5227. * Close </ul> tags
  5228. *
  5229. * This is a helper function to the above
  5230. */
  5231. public function close_ul($parent_id, $depth = 0)
  5232. {
  5233. $count = 0;
  5234. $tab = "";
  5235. for ($i = 0; $i < $depth; $i++)
  5236. {
  5237. $tab .= "\t";
  5238. }
  5239. foreach ($this->temp_array as $val)
  5240. {
  5241. if ($parent_id == $val[0])
  5242. $count++;
  5243. }
  5244. if ($count == 0)
  5245. $this->category_list[] = $tab."</ul>\n";
  5246. }
  5247. // ------------------------------------------------------------------------
  5248. /**
  5249. * Channel "category_heading" tag
  5250. */
  5251. public function category_heading()
  5252. {
  5253. if ($this->query_string == '')
  5254. {
  5255. return;
  5256. }
  5257. // -------------------------------------------
  5258. // 'channel_module_category_heading_start' hook.
  5259. // - Rewrite the displaying of category headings, if you dare!
  5260. //
  5261. if ($this->EE->extensions->active_hook('channel_module_category_heading_start') === TRUE)
  5262. {
  5263. $this->EE->TMPL->tagdata = $this->EE->extensions->call('channel_module_category_heading_start');
  5264. if ($this->EE->extensions->end_script === TRUE) return $this->EE->TMPL->tagdata;
  5265. }
  5266. //
  5267. // -------------------------------------------
  5268. $qstring = $this->query_string;
  5269. /** --------------------------------------
  5270. /** Remove page number
  5271. /** --------------------------------------*/
  5272. if (preg_match("#/P\d+#", $qstring, $match))
  5273. {
  5274. $qstring = $this->EE->functions->remove_double_slashes(str_replace($match[0], '', $qstring));
  5275. }
  5276. /** --------------------------------------
  5277. /** Remove "N"
  5278. /** --------------------------------------*/
  5279. if (preg_match("#/N(\d+)#", $qstring, $match))
  5280. {
  5281. $qstring = $this->EE->functions->remove_double_slashes(str_replace($match[0], '', $qstring));
  5282. }
  5283. // Is the category being specified by name?
  5284. if ($qstring != '' AND $this->reserved_cat_segment != '' AND in_array($this->reserved_cat_segment, explode("/", $qstring)) AND $this->EE->TMPL->fetch_param('channel'))
  5285. {
  5286. $qstring = preg_replace("/(.*?)\/".preg_quote($this->reserved_cat_segment)."\//i", '', '/'.$qstring);
  5287. $sql = "SELECT DISTINCT cat_group FROM exp_channels WHERE site_id IN ('".implode("','", $this->EE->TMPL->site_ids)."') AND ";
  5288. $xsql = $this->EE->functions->sql_andor_string($this->EE->TMPL->fetch_param('channel'), 'channel_name');
  5289. if (substr($xsql, 0, 3) == 'AND') $xsql = substr($xsql, 3);
  5290. $sql .= ' '.$xsql;
  5291. $query = $this->EE->db->query($sql);
  5292. if ($query->num_rows() > 0)
  5293. {
  5294. $valid = 'y';
  5295. $valid_cats = explode('|', $query->row('cat_group') );
  5296. foreach($query->result_array() as $row)
  5297. {
  5298. if ($this->EE->TMPL->fetch_param('relaxed_categories') == 'yes')
  5299. {
  5300. $valid_cats = array_merge($valid_cats, explode('|', $row['cat_group']));
  5301. }
  5302. else
  5303. {
  5304. $valid_cats = array_intersect($valid_cats, explode('|', $row['cat_group']));
  5305. }
  5306. $valid_cats = array_unique($valid_cats);
  5307. if (count($valid_cats) == 0)
  5308. {
  5309. $valid = 'n';
  5310. break;
  5311. }
  5312. }
  5313. }
  5314. else
  5315. {
  5316. $valid = 'n';
  5317. }
  5318. if ($valid == 'y')
  5319. {
  5320. // the category URL title should be the first segment left at this point in $qstring,
  5321. // but because prior to this feature being added, category names were used in URLs,
  5322. // and '/' is a valid character for category names. If they have not updated their
  5323. // category url titles since updating to 1.6, their category URL title could still
  5324. // contain a '/'. So we'll try to get the category the correct way first, and if
  5325. // it fails, we'll try the whole $qstring
  5326. $cut_qstring = array_shift($temp = explode('/', $qstring));
  5327. $result = $this->EE->db->query("SELECT cat_id FROM exp_categories
  5328. WHERE cat_url_title='".$this->EE->db->escape_str($cut_qstring)."'
  5329. AND group_id IN ('".implode("','", $valid_cats)."')");
  5330. if ($result->num_rows() == 1)
  5331. {
  5332. $qstring = str_replace($cut_qstring, 'C'.$result->row('cat_id') , $qstring);
  5333. }
  5334. else
  5335. {
  5336. // give it one more try using the whole $qstring
  5337. $result = $this->EE->db->query("SELECT cat_id FROM exp_categories
  5338. WHERE cat_url_title='".$this->EE->db->escape_str($qstring)."'
  5339. AND group_id IN ('".implode("','", $valid_cats)."')");
  5340. if ($result->num_rows() == 1)
  5341. {
  5342. $qstring = 'C'.$result->row('cat_id') ;
  5343. }
  5344. }
  5345. }
  5346. }
  5347. // Is the category being specified by ID?
  5348. if ( ! preg_match("#(^|\/)C(\d+)#", $qstring, $match))
  5349. {
  5350. return $this->EE->TMPL->no_results();
  5351. }
  5352. // fetch category field names and id's
  5353. if ($this->enable['category_fields'] === TRUE)
  5354. {
  5355. // limit to correct category group
  5356. $gquery = $this->EE->db->query("SELECT group_id FROM exp_categories WHERE cat_id = '".$this->EE->db->escape_str($match[2])."'");
  5357. if ($gquery->num_rows() == 0)
  5358. {
  5359. return $this->EE->TMPL->no_results();
  5360. }
  5361. $query = $this->EE->db->query("SELECT field_id, field_name
  5362. FROM exp_category_fields
  5363. WHERE site_id IN ('".implode("','", $this->EE->TMPL->site_ids)."')
  5364. AND group_id = '".$gquery->row('group_id')."'");
  5365. if ($query->num_rows() > 0)
  5366. {
  5367. foreach ($query->result_array() as $row)
  5368. {
  5369. $this->catfields[] = array('field_name' => $row['field_name'], 'field_id' => $row['field_id']);
  5370. }
  5371. }
  5372. $field_sqla = ", cg.field_html_formatting, fd.* ";
  5373. $field_sqlb = " LEFT JOIN exp_category_field_data AS fd ON fd.cat_id = c.cat_id
  5374. LEFT JOIN exp_category_groups AS cg ON cg.group_id = c.group_id ";
  5375. }
  5376. else
  5377. {
  5378. $field_sqla = '';
  5379. $field_sqlb = '';
  5380. }
  5381. $query = $this->EE->db->query("SELECT c.cat_name, c.parent_id, c.cat_url_title, c.cat_description, c.cat_image {$field_sqla}
  5382. FROM exp_categories AS c
  5383. {$field_sqlb}
  5384. WHERE c.cat_id = '".$this->EE->db->escape_str($match[2])."'");
  5385. if ($query->num_rows() == 0)
  5386. {
  5387. return $this->EE->TMPL->no_results();
  5388. }
  5389. $row = $query->row_array();
  5390. $this->EE->load->library('file_field');
  5391. $cat_image = $this->EE->file_field->parse_field($query->row('cat_image'));
  5392. $cat_vars = array('category_name' => $query->row('cat_name'),
  5393. 'category_description' => $query->row('cat_description'),
  5394. 'category_image' => $cat_image['url'],
  5395. 'category_id' => $match[2],
  5396. 'parent_id' => $query->row('parent_id'));
  5397. // add custom fields for conditionals prep
  5398. foreach ($this->catfields as $v)
  5399. {
  5400. $cat_vars[$v['field_name']] = ($query->row('field_id_'.$v['field_id'])) ? $query->row('field_id_'.$v['field_id']) : '';
  5401. }
  5402. $this->EE->TMPL->tagdata = $this->EE->functions->prep_conditionals($this->EE->TMPL->tagdata, $cat_vars);
  5403. $this->EE->TMPL->tagdata = str_replace( array(LD.'category_id'.RD,
  5404. LD.'category_name'.RD,
  5405. LD.'category_url_title'.RD,
  5406. LD.'category_image'.RD,
  5407. LD.'category_description'.RD,
  5408. LD.'parent_id'.RD),
  5409. array($match[2],
  5410. $query->row('cat_name'),
  5411. $query->row('cat_url_title'),
  5412. $cat_image['url'],
  5413. $query->row('cat_description'),
  5414. $query->row('parent_id')),
  5415. $this->EE->TMPL->tagdata);
  5416. // Check to see if we need to parse {filedir_n}
  5417. if (strpos($this->EE->TMPL->tagdata, '{filedir_') !== FALSE)
  5418. {
  5419. $this->EE->load->library('file_field');
  5420. $this->EE->TMPL->tagdata = $this->EE->file_field->parse_string($this->EE->TMPL->tagdata);
  5421. }
  5422. // parse custom fields
  5423. $this->EE->load->library('typography');
  5424. $this->EE->typography->initialize(array(
  5425. 'convert_curly' => FALSE)
  5426. );
  5427. // parse custom fields
  5428. foreach($this->catfields as $ccv)
  5429. {
  5430. if ($query->row('field_id_'.$ccv['field_id']) AND $query->row('field_id_'.$ccv['field_id']) != '')
  5431. {
  5432. $field_content = $this->EE->typography->parse_type($query->row('field_id_'.$ccv['field_id']),
  5433. array(
  5434. 'text_format' => $query->row('field_ft_'.$ccv['field_id']),
  5435. 'html_format' => $query->row('field_html_formatting'),
  5436. 'auto_links' => 'n',
  5437. 'allow_img_url' => 'y'
  5438. )
  5439. );
  5440. $this->EE->TMPL->tagdata = str_replace(LD.$ccv['field_name'].RD, $field_content, $this->EE->TMPL->tagdata);
  5441. }
  5442. else
  5443. {
  5444. // garbage collection
  5445. $this->EE->TMPL->tagdata = str_replace(LD.$ccv['field_name'].RD, '', $this->EE->TMPL->tagdata);
  5446. }
  5447. }
  5448. return $this->EE->TMPL->tagdata;
  5449. }
  5450. // ------------------------------------------------------------------------
  5451. /** ---------------------------------------
  5452. /** Next / Prev entry tags
  5453. /** ---------------------------------------*/
  5454. public function next_entry()
  5455. {
  5456. return $this->next_prev_entry('next');
  5457. }
  5458. public function prev_entry()
  5459. {
  5460. return $this->next_prev_entry('prev');
  5461. }
  5462. public function next_prev_entry($which = 'next')
  5463. {
  5464. $which = ($which != 'next' AND $which != 'prev') ? 'next' : $which;
  5465. $sort = ($which == 'next') ? 'ASC' : 'DESC';
  5466. // Don't repeat our work if we already know the single entry page details
  5467. if ( ! isset($this->EE->session->cache['channel']['single_entry_id']) OR ! isset($this->EE->session->cache['channel']['single_entry_date']))
  5468. {
  5469. // no query string? Nothing to do...
  5470. if (($qstring = $this->query_string) == '')
  5471. {
  5472. return;
  5473. }
  5474. /** --------------------------------------
  5475. /** Remove page number
  5476. /** --------------------------------------*/
  5477. if (preg_match("#/P\d+#", $qstring, $match))
  5478. {
  5479. $qstring = $this->EE->functions->remove_double_slashes(str_replace($match[0], '', $qstring));
  5480. }
  5481. /** --------------------------------------
  5482. /** Remove "N"
  5483. /** --------------------------------------*/
  5484. if (preg_match("#/N(\d+)#", $qstring, $match))
  5485. {
  5486. $qstring = $this->EE->functions->remove_double_slashes(str_replace($match[0], '', $qstring));
  5487. }
  5488. if (strpos($qstring, '/') !== FALSE)
  5489. {
  5490. $qstring = substr($qstring, 0, strpos($qstring, '/'));
  5491. }
  5492. /** ---------------------------------------
  5493. /** Query for the entry id and date
  5494. /** ---------------------------------------*/
  5495. $this->EE->db->select('t.entry_id, t.entry_date');
  5496. $this->EE->db->from('channel_titles AS t');
  5497. $this->EE->db->join('channels AS w', 'w.channel_id = t.channel_id', 'left');
  5498. // url_title parameter
  5499. if ($url_title = $this->EE->TMPL->fetch_param('url_title'))
  5500. {
  5501. $this->EE->db->where('t.url_title', $url_title);
  5502. }
  5503. else
  5504. {
  5505. // Found entry ID in query string
  5506. if (is_numeric($qstring))
  5507. {
  5508. $this->EE->db->where('t.entry_id', $qstring);
  5509. }
  5510. // Found URL title in query string
  5511. else
  5512. {
  5513. $this->EE->db->where('t.url_title', $qstring);
  5514. }
  5515. }
  5516. $this->EE->db->where_in('w.site_id', $this->EE->TMPL->site_ids);
  5517. // Channel paremter
  5518. if ($channel_name = $this->EE->TMPL->fetch_param('channel'))
  5519. {
  5520. $this->EE->functions->ar_andor_string($channel_name, 'channel_name', 'w');
  5521. }
  5522. $query = $this->EE->db->get();
  5523. // no results or more than one result? Buh bye!
  5524. if ($query->num_rows() != 1)
  5525. {
  5526. $this->EE->TMPL->log_item('Channel Next/Prev Entry tag error: Could not resolve single entry page id.');
  5527. return;
  5528. }
  5529. $row = $query->row_array();
  5530. $this->EE->session->cache['channel']['single_entry_id'] = $row['entry_id'];
  5531. $this->EE->session->cache['channel']['single_entry_date'] = $row['entry_date'];
  5532. }
  5533. /** ---------------------------------------
  5534. /** Find the next / prev entry
  5535. /** ---------------------------------------*/
  5536. $ids = '';
  5537. // Get included or excluded entry ids from entry_id parameter
  5538. if (($entry_id = $this->EE->TMPL->fetch_param('entry_id')) != FALSE)
  5539. {
  5540. $ids = $this->EE->functions->sql_andor_string($entry_id, 't.entry_id').' ';
  5541. }
  5542. $sql = 'SELECT t.entry_id, t.title, t.url_title
  5543. FROM (exp_channel_titles AS t)
  5544. LEFT JOIN exp_channels AS w ON w.channel_id = t.channel_id ';
  5545. /* --------------------------------
  5546. /* We use LEFT JOIN when there is a 'not' so that we get
  5547. /* entries that are not assigned to a category.
  5548. /* --------------------------------*/
  5549. if ((substr($this->EE->TMPL->fetch_param('category_group'), 0, 3) == 'not' OR substr($this->EE->TMPL->fetch_param('category'), 0, 3) == 'not') && $this->EE->TMPL->fetch_param('uncategorized_entries') !== 'no')
  5550. {
  5551. $sql .= 'LEFT JOIN exp_category_posts ON t.entry_id = exp_category_posts.entry_id
  5552. LEFT JOIN exp_categories ON exp_category_posts.cat_id = exp_categories.cat_id ';
  5553. }
  5554. elseif($this->EE->TMPL->fetch_param('category_group') OR $this->EE->TMPL->fetch_param('category'))
  5555. {
  5556. $sql .= 'INNER JOIN exp_category_posts ON t.entry_id = exp_category_posts.entry_id
  5557. INNER JOIN exp_categories ON exp_category_posts.cat_id = exp_categories.cat_id ';
  5558. }
  5559. $sql .= ' WHERE t.entry_id != '.$this->EE->session->cache['channel']['single_entry_id'].' '.$ids;
  5560. $timestamp = ($this->EE->TMPL->cache_timestamp != '') ? $this->EE->TMPL->cache_timestamp : $this->EE->localize->now;
  5561. if ($this->EE->TMPL->fetch_param('show_future_entries') != 'yes')
  5562. {
  5563. $sql .= " AND t.entry_date < {$timestamp} ";
  5564. }
  5565. // constrain by date depending on whether this is a 'next' or 'prev' tag
  5566. if ($which == 'next')
  5567. {
  5568. $sql .= ' AND t.entry_date >= '.$this->EE->session->cache['channel']['single_entry_date'].' ';
  5569. $sql .= ' AND IF (t.entry_date = '.$this->EE->session->cache['channel']['single_entry_date'].', t.entry_id > '.$this->EE->session->cache['channel']['single_entry_id'].', 1) ';
  5570. }
  5571. else
  5572. {
  5573. $sql .= ' AND t.entry_date <= '.$this->EE->session->cache['channel']['single_entry_date'].' ';
  5574. $sql .= ' AND IF (t.entry_date = '.$this->EE->session->cache['channel']['single_entry_date'].', t.entry_id < '.$this->EE->session->cache['channel']['single_entry_id'].', 1) ';
  5575. }
  5576. if ($this->EE->TMPL->fetch_param('show_expired') != 'yes')
  5577. {
  5578. $sql .= " AND (t.expiration_date = 0 OR t.expiration_date > {$timestamp}) ";
  5579. }
  5580. $sql .= " AND w.site_id IN ('".implode("','", $this->EE->TMPL->site_ids)."') ";
  5581. if ($channel_name = $this->EE->TMPL->fetch_param('channel'))
  5582. {
  5583. $sql .= $this->EE->functions->sql_andor_string($channel_name, 'channel_name', 'w')." ";
  5584. }
  5585. if ($status = $this->EE->TMPL->fetch_param('status'))
  5586. {
  5587. $status = str_replace('Open', 'open', $status);
  5588. $status = str_replace('Closed', 'closed', $status);
  5589. $sql .= $this->EE->functions->sql_andor_string($status, 't.status')." ";
  5590. }
  5591. else
  5592. {
  5593. $sql .= "AND t.status = 'open' ";
  5594. }
  5595. /**------
  5596. /** Limit query by category
  5597. /**------*/
  5598. if ($this->EE->TMPL->fetch_param('category'))
  5599. {
  5600. if (stristr($this->EE->TMPL->fetch_param('category'), '&'))
  5601. {
  5602. /** --------------------------------------
  5603. /** First, we find all entries with these categories
  5604. /** --------------------------------------*/
  5605. $for_sql = (substr($this->EE->TMPL->fetch_param('category'), 0, 3) == 'not') ? trim(substr($this->EE->TMPL->fetch_param('category'), 3)) : $this->EE->TMPL->fetch_param('category');
  5606. $csql = "SELECT exp_category_posts.entry_id, exp_category_posts.cat_id, ".
  5607. str_replace('SELECT', '', $sql).
  5608. $this->EE->functions->sql_andor_string(str_replace('&', '|', $for_sql), 'exp_categories.cat_id');
  5609. //exit($csql);
  5610. $results = $this->EE->db->query($csql);
  5611. if ($results->num_rows() == 0)
  5612. {
  5613. return;
  5614. }
  5615. $type = 'IN';
  5616. $categories = explode('&', $this->EE->TMPL->fetch_param('category'));
  5617. $entry_array = array();
  5618. if (substr($categories[0], 0, 3) == 'not')
  5619. {
  5620. $type = 'NOT IN';
  5621. $categories[0] = trim(substr($categories[0], 3));
  5622. }
  5623. foreach($results->result_array() as $row)
  5624. {
  5625. $entry_array[$row['cat_id']][] = $row['entry_id'];
  5626. }
  5627. if (count($entry_array) < 2 OR count(array_diff($categories, array_keys($entry_array))) > 0)
  5628. {
  5629. return;
  5630. }
  5631. $chosen = call_user_func_array('array_intersect', $entry_array);
  5632. if (count($chosen) == 0)
  5633. {
  5634. return;
  5635. }
  5636. $sql .= "AND t.entry_id ".$type." ('".implode("','", $chosen)."') ";
  5637. }
  5638. else
  5639. {
  5640. if (substr($this->EE->TMPL->fetch_param('category'), 0, 3) == 'not' && $this->EE->TMPL->fetch_param('uncategorized_entries') !== 'no')
  5641. {
  5642. $sql .= $this->EE->functions->sql_andor_string($this->EE->TMPL->fetch_param('category'), 'exp_categories.cat_id', '', TRUE)." ";
  5643. }
  5644. else
  5645. {
  5646. $sql .= $this->EE->functions->sql_andor_string($this->EE->TMPL->fetch_param('category'), 'exp_categories.cat_id')." ";
  5647. }
  5648. }
  5649. }
  5650. if ($this->EE->TMPL->fetch_param('category_group'))
  5651. {
  5652. if (substr($this->EE->TMPL->fetch_param('category_group'), 0, 3) == 'not' && $this->EE->TMPL->fetch_param('uncategorized_entries') !== 'no')
  5653. {
  5654. $sql .= $this->EE->functions->sql_andor_string($this->EE->TMPL->fetch_param('category_group'), 'exp_categories.group_id', '', TRUE)." ";
  5655. }
  5656. else
  5657. {
  5658. $sql .= $this->EE->functions->sql_andor_string($this->EE->TMPL->fetch_param('category_group'), 'exp_categories.group_id')." ";
  5659. }
  5660. }
  5661. $sql .= " ORDER BY t.entry_date {$sort}, t.entry_id {$sort} LIMIT 1";
  5662. $query = $this->EE->db->query($sql);
  5663. if ($query->num_rows() == 0)
  5664. {
  5665. return;
  5666. }
  5667. /** ---------------------------------------
  5668. /** Replace variables
  5669. /** ---------------------------------------*/
  5670. $this->EE->load->library('typography');
  5671. if (strpos($this->EE->TMPL->tagdata, LD.'path=') !== FALSE)
  5672. {
  5673. $path = (preg_match("#".LD."path=(.+?)".RD."#", $this->EE->TMPL->tagdata, $match)) ? $this->EE->functions->create_url($match[1]) : $this->EE->functions->create_url("SITE_INDEX");
  5674. $path .= '/'.$query->row('url_title');
  5675. $this->EE->TMPL->tagdata = preg_replace("#".LD."path=.+?".RD."#", $this->EE->functions->remove_double_slashes($path), $this->EE->TMPL->tagdata);
  5676. }
  5677. if (strpos($this->EE->TMPL->tagdata, LD.'id_path=') !== FALSE)
  5678. {
  5679. $id_path = (preg_match("#".LD."id_path=(.+?)".RD."#", $this->EE->TMPL->tagdata, $match)) ? $this->EE->functions->create_url($match[1]) : $this->EE->functions->create_url("SITE_INDEX");
  5680. $id_path .= '/'.$query->row('entry_id');
  5681. $this->EE->TMPL->tagdata = preg_replace("#".LD."id_path=.+?".RD."#", $this->EE->functions->remove_double_slashes($id_path), $this->EE->TMPL->tagdata);
  5682. }
  5683. if (strpos($this->EE->TMPL->tagdata, LD.'url_title') !== FALSE)
  5684. {
  5685. $this->EE->TMPL->tagdata = str_replace(LD.'url_title'.RD, $query->row('url_title'), $this->EE->TMPL->tagdata);
  5686. }
  5687. if (strpos($this->EE->TMPL->tagdata, LD.'entry_id') !== FALSE)
  5688. {
  5689. $this->EE->TMPL->tagdata = str_replace(LD.'entry_id'.RD, $query->row('entry_id'), $this->EE->TMPL->tagdata);
  5690. }
  5691. if (strpos($this->EE->TMPL->tagdata, LD.'title') !== FALSE)
  5692. {
  5693. $this->EE->TMPL->tagdata = str_replace(LD.'title'.RD, $this->EE->typography->format_characters($query->row('title')), $this->EE->TMPL->tagdata);
  5694. }
  5695. if (strpos($this->EE->TMPL->tagdata, '_entry->title') !== FALSE)
  5696. {
  5697. $this->EE->TMPL->tagdata = preg_replace('/'.LD.'(?:next|prev)_entry->title'.RD.'/',
  5698. $this->EE->typography->format_characters($query->row('title')),
  5699. $this->EE->TMPL->tagdata);
  5700. }
  5701. return $this->EE->TMPL->tagdata;
  5702. }
  5703. // ------------------------------------------------------------------------
  5704. /**
  5705. * Channel "month links"
  5706. */
  5707. public function month_links()
  5708. {
  5709. $return = '';
  5710. // Build query
  5711. // Fetch the timezone array and calculate the offset so we can localize the month/year
  5712. $zones = $this->EE->localize->zones();
  5713. $offset = ( ! isset($zones[$this->EE->session->userdata['timezone']]) OR $zones[$this->EE->session->userdata['timezone']] == '') ? 0 : ($zones[$this->EE->session->userdata['timezone']]*60*60);
  5714. if (substr($offset, 0, 1) == '-')
  5715. {
  5716. $calc = 'entry_date - '.substr($offset, 1);
  5717. }
  5718. elseif (substr($offset, 0, 1) == '+')
  5719. {
  5720. $calc = 'entry_date + '.substr($offset, 1);
  5721. }
  5722. else
  5723. {
  5724. $calc = 'entry_date + '.$offset;
  5725. }
  5726. $sql = "SELECT DISTINCT year(FROM_UNIXTIME(".$calc.")) AS year,
  5727. MONTH(FROM_UNIXTIME(".$calc.")) AS month
  5728. FROM exp_channel_titles
  5729. WHERE entry_id != ''
  5730. AND site_id IN ('".implode("','", $this->EE->TMPL->site_ids)."') ";
  5731. $timestamp = ($this->EE->TMPL->cache_timestamp != '') ? $this->EE->TMPL->cache_timestamp : $this->EE->localize->now;
  5732. if ($this->EE->TMPL->fetch_param('show_future_entries') != 'yes')
  5733. {
  5734. $sql .= " AND exp_channel_titles.entry_date < ".$timestamp." ";
  5735. }
  5736. if ($this->EE->TMPL->fetch_param('show_expired') != 'yes')
  5737. {
  5738. $sql .= " AND (exp_channel_titles.expiration_date = 0 OR exp_channel_titles.expiration_date > ".$timestamp.") ";
  5739. }
  5740. /**------
  5741. /** Limit to/exclude specific channels
  5742. /**------*/
  5743. if ($channel = $this->EE->TMPL->fetch_param('channel'))
  5744. {
  5745. $wsql = "SELECT channel_id FROM exp_channels WHERE site_id IN ('".implode("','", $this->EE->TMPL->site_ids)."') ";
  5746. $wsql .= $this->EE->functions->sql_andor_string($channel, 'channel_name');
  5747. $query = $this->EE->db->query($wsql);
  5748. if ($query->num_rows() > 0)
  5749. {
  5750. $sql .= " AND ";
  5751. if ($query->num_rows() == 1)
  5752. {
  5753. $sql .= "channel_id = '".$query->row('channel_id') ."' ";
  5754. }
  5755. else
  5756. {
  5757. $sql .= "(";
  5758. foreach ($query->result_array() as $row)
  5759. {
  5760. $sql .= "channel_id = '".$row['channel_id']."' OR ";
  5761. }
  5762. $sql = substr($sql, 0, - 3);
  5763. $sql .= ") ";
  5764. }
  5765. }
  5766. }
  5767. /**------
  5768. /** Add status declaration
  5769. /**------*/
  5770. if ($status = $this->EE->TMPL->fetch_param('status'))
  5771. {
  5772. $status = str_replace('Open', 'open', $status);
  5773. $status = str_replace('Closed', 'closed', $status);
  5774. $sstr = $this->EE->functions->sql_andor_string($status, 'status');
  5775. if (stristr($sstr, "'closed'") === FALSE)
  5776. {
  5777. $sstr .= " AND status != 'closed' ";
  5778. }
  5779. $sql .= $sstr;
  5780. }
  5781. else
  5782. {
  5783. $sql .= "AND status = 'open' ";
  5784. }
  5785. $sql .= " ORDER BY entry_date";
  5786. switch ($this->EE->TMPL->fetch_param('sort'))
  5787. {
  5788. case 'asc' : $sql .= " asc";
  5789. break;
  5790. case 'desc' : $sql .= " desc";
  5791. break;
  5792. default : $sql .= " desc";
  5793. break;
  5794. }
  5795. if (is_numeric($this->EE->TMPL->fetch_param('limit')))
  5796. {
  5797. $sql .= " LIMIT ".$this->EE->TMPL->fetch_param('limit');
  5798. }
  5799. $query = $this->EE->db->query($sql);
  5800. if ($query->num_rows() == 0)
  5801. {
  5802. return '';
  5803. }
  5804. $year_limit = (is_numeric($this->EE->TMPL->fetch_param('year_limit'))) ? $this->EE->TMPL->fetch_param('year_limit') : 50;
  5805. $total_years = 0;
  5806. $current_year = '';
  5807. foreach ($query->result_array() as $row)
  5808. {
  5809. $tagdata = $this->EE->TMPL->tagdata;
  5810. $month = (strlen($row['month']) == 1) ? '0'.$row['month'] : $row['month'];
  5811. $year = $row['year'];
  5812. $month_name = $this->EE->localize->localize_month($month);
  5813. // Dealing with {year_heading}
  5814. if (isset($this->EE->TMPL->var_pair['year_heading']))
  5815. {
  5816. if ($year == $current_year)
  5817. {
  5818. $tagdata = $this->EE->TMPL->delete_var_pairs('year_heading', 'year_heading', $tagdata);
  5819. }
  5820. else
  5821. {
  5822. $tagdata = $this->EE->TMPL->swap_var_pairs('year_heading', 'year_heading', $tagdata);
  5823. $total_years++;
  5824. if ($total_years > $year_limit)
  5825. {
  5826. break;
  5827. }
  5828. }
  5829. $current_year = $year;
  5830. }
  5831. /** ---------------------------------------
  5832. /** prep conditionals
  5833. /** ---------------------------------------*/
  5834. $cond = array();
  5835. $cond['month'] = $this->EE->lang->line($month_name[1]);
  5836. $cond['month_short'] = $this->EE->lang->line($month_name[0]);
  5837. $cond['month_num'] = $month;
  5838. $cond['year'] = $year;
  5839. $cond['year_short'] = substr($year, 2);
  5840. $tagdata = $this->EE->functions->prep_conditionals($tagdata, $cond);
  5841. // parse path
  5842. foreach ($this->EE->TMPL->var_single as $key => $val)
  5843. {
  5844. if (strncmp($key, 'path', 4) == 0)
  5845. {
  5846. $tagdata = $this->EE->TMPL->swap_var_single(
  5847. $val,
  5848. $this->EE->functions->create_url($this->EE->functions->extract_path($key).'/'.$year.'/'.$month),
  5849. $tagdata
  5850. );
  5851. }
  5852. // parse month (long)
  5853. if ($key == 'month')
  5854. {
  5855. $tagdata = $this->EE->TMPL->swap_var_single($key, $this->EE->lang->line($month_name[1]), $tagdata);
  5856. }
  5857. // parse month (short)
  5858. if ($key == 'month_short')
  5859. {
  5860. $tagdata = $this->EE->TMPL->swap_var_single($key, $this->EE->lang->line($month_name[0]), $tagdata);
  5861. }
  5862. // parse month (numeric)
  5863. if ($key == 'month_num')
  5864. {
  5865. $tagdata = $this->EE->TMPL->swap_var_single($key, $month, $tagdata);
  5866. }
  5867. // parse year
  5868. if ($key == 'year')
  5869. {
  5870. $tagdata = $this->EE->TMPL->swap_var_single($key, $year, $tagdata);
  5871. }
  5872. // parse year (short)
  5873. if ($key == 'year_short')
  5874. {
  5875. $tagdata = $this->EE->TMPL->swap_var_single($key, substr($year, 2), $tagdata);
  5876. }
  5877. }
  5878. $return .= trim($tagdata)."\n";
  5879. }
  5880. return $return;
  5881. }
  5882. // ------------------------------------------------------------------------
  5883. /**
  5884. * Related Categories Mode
  5885. *
  5886. * This function shows entries that are in the same category as
  5887. * the primary entry being shown. It calls the main "channel entries"
  5888. * function after setting some variables to control the content.
  5889. *
  5890. * Note: We have deprecated the calling of this tag directly via its own tag.
  5891. * Related entries are now shown using the standard {exp:channel:entries} tag.
  5892. * The reason we're deprecating it is to avoid confusion since the channel tag
  5893. * now supports relational capability via a pair of {related_entries} tags.
  5894. *
  5895. * To show "related entries" the following parameter is added to the {exp:channel:entries} tag:
  5896. *
  5897. * related_categories_mode="on"
  5898. */
  5899. public function related_entries()
  5900. {
  5901. if ($this->query_string == '')
  5902. {
  5903. return FALSE;
  5904. }
  5905. $qstring = $this->query_string;
  5906. /** --------------------------------------
  5907. /** Remove page number
  5908. /** --------------------------------------*/
  5909. if (preg_match("#/P\d+#", $qstring, $match))
  5910. {
  5911. $qstring = $this->EE->functions->remove_double_slashes(str_replace($match[0], '', $qstring));
  5912. }
  5913. /** --------------------------------------
  5914. /** Remove "N"
  5915. /** --------------------------------------*/
  5916. if (preg_match("#/N(\d+)#", $qstring, $match))
  5917. {
  5918. $qstring = $this->EE->functions->remove_double_slashes(str_replace($match[0], '', $qstring));
  5919. }
  5920. /** --------------------------------------
  5921. /** Make sure to only get one segment
  5922. /** --------------------------------------*/
  5923. if (strpos($qstring, '/') !== FALSE)
  5924. {
  5925. $qstring = substr($qstring, 0, strpos($qstring, '/'));
  5926. }
  5927. /** ----------------------------------
  5928. /** Find Categories for Entry
  5929. /** ----------------------------------*/
  5930. $sql = "SELECT exp_categories.cat_id, exp_categories.cat_name
  5931. FROM exp_channel_titles
  5932. INNER JOIN exp_category_posts ON exp_channel_titles.entry_id = exp_category_posts.entry_id
  5933. INNER JOIN exp_categories ON exp_category_posts.cat_id = exp_categories.cat_id
  5934. WHERE exp_categories.cat_id IS NOT NULL
  5935. AND exp_channel_titles.site_id IN ('".implode("','", $this->EE->TMPL->site_ids)."') ";
  5936. $sql .= ( ! is_numeric($qstring)) ? "AND exp_channel_titles.url_title = '".$this->EE->db->escape_str($qstring)."' " : "AND exp_channel_titles.entry_id = '".$this->EE->db->escape_str($qstring)."' ";
  5937. $query = $this->EE->db->query($sql);
  5938. if ($query->num_rows() == 0)
  5939. {
  5940. return $this->EE->TMPL->no_results();
  5941. }
  5942. /** ----------------------------------
  5943. /** Build category array
  5944. /** ----------------------------------*/
  5945. $cat_array = array();
  5946. // We allow the option of adding or subtracting cat_id's
  5947. $categories = ( ! $this->EE->TMPL->fetch_param('category')) ? '' : $this->EE->TMPL->fetch_param('category');
  5948. if (strncmp($categories, 'not ', 4) == 0)
  5949. {
  5950. $categories = substr($categories, 4);
  5951. $not_categories = explode('|',$categories);
  5952. }
  5953. else
  5954. {
  5955. $add_categories = explode('|',$categories);
  5956. }
  5957. foreach($query->result_array() as $row)
  5958. {
  5959. if ( ! isset($not_categories) OR array_search($row['cat_id'], $not_categories) === FALSE)
  5960. {
  5961. $cat_array[] = $row['cat_id'];
  5962. }
  5963. }
  5964. // User wants some categories added, so we add these cat_id's
  5965. if (isset($add_categories) && count($add_categories) > 0)
  5966. {
  5967. foreach($add_categories as $cat_id)
  5968. {
  5969. $cat_array[] = $cat_id;
  5970. }
  5971. }
  5972. // Just in case
  5973. $cat_array = array_unique($cat_array);
  5974. if (count($cat_array) == 0)
  5975. {
  5976. return $this->EE->TMPL->no_results();
  5977. }
  5978. /** ----------------------------------
  5979. /** Build category string
  5980. /** ----------------------------------*/
  5981. $cats = '';
  5982. foreach($cat_array as $cat_id)
  5983. {
  5984. if ($cat_id != '')
  5985. {
  5986. $cats .= $cat_id.'|';
  5987. }
  5988. }
  5989. $cats = substr($cats, 0, -1);
  5990. /** ----------------------------------
  5991. /** Manually set paramters
  5992. /** ----------------------------------*/
  5993. $this->EE->TMPL->tagparams['category'] = $cats;
  5994. $this->EE->TMPL->tagparams['dynamic'] = 'off';
  5995. $this->EE->TMPL->tagparams['not_entry_id'] = $qstring; // Exclude the current entry
  5996. // Set user submitted paramters
  5997. $params = array('channel', 'username', 'status', 'orderby', 'sort');
  5998. foreach ($params as $val)
  5999. {
  6000. if ($this->EE->TMPL->fetch_param($val) != FALSE)
  6001. {
  6002. $this->EE->TMPL->tagparams[$val] = $this->EE->TMPL->fetch_param($val);
  6003. }
  6004. }
  6005. if ( ! is_numeric($this->EE->TMPL->fetch_param('limit')))
  6006. {
  6007. $this->EE->TMPL->tagparams['limit'] = 10;
  6008. }
  6009. /** ----------------------------------
  6010. /** Run the channel parser
  6011. /** ----------------------------------*/
  6012. $this->initialize();
  6013. $this->entry_id = '';
  6014. $qstring = '';
  6015. if ($this->enable['custom_fields'] == TRUE && $this->EE->TMPL->fetch_param('custom_fields') == 'yes')
  6016. {
  6017. $this->fetch_custom_channel_fields();
  6018. }
  6019. $this->build_sql_query();
  6020. if ($this->sql == '')
  6021. {
  6022. return $this->EE->TMPL->no_results();
  6023. }
  6024. $this->query = $this->EE->db->query($this->sql);
  6025. if ($this->query->num_rows() == 0)
  6026. {
  6027. return $this->EE->TMPL->no_results();
  6028. }
  6029. $this->EE->load->library('typography');
  6030. $this->EE->typography->initialize(array(
  6031. 'convert_curly' => FALSE)
  6032. );
  6033. if ($this->EE->TMPL->fetch_param('member_data') !== FALSE && $this->EE->TMPL->fetch_param('member_data') == 'yes')
  6034. {
  6035. $this->fetch_custom_member_fields();
  6036. }
  6037. $this->parse_channel_entries();
  6038. return $this->return_data;
  6039. }
  6040. // ------------------------------------------------------------------------
  6041. /**
  6042. * Fetch Disable Parameter
  6043. */
  6044. function _fetch_disable_param()
  6045. {
  6046. $this->enable = array(
  6047. 'categories' => TRUE,
  6048. 'category_fields' => TRUE,
  6049. 'custom_fields' => TRUE,
  6050. 'member_data' => TRUE,
  6051. 'pagination' => TRUE,
  6052. );
  6053. if ($disable = $this->EE->TMPL->fetch_param('disable'))
  6054. {
  6055. if (strpos($disable, '|') !== FALSE)
  6056. {
  6057. foreach (explode("|", $disable) as $val)
  6058. {
  6059. if (isset($this->enable[$val]))
  6060. {
  6061. $this->enable[$val] = FALSE;
  6062. }
  6063. }
  6064. }
  6065. elseif (isset($this->enable[$disable]))
  6066. {
  6067. $this->enable[$disable] = FALSE;
  6068. }
  6069. }
  6070. }
  6071. // ------------------------------------------------------------------------
  6072. /**
  6073. * Channel Calendar
  6074. */
  6075. public function calendar()
  6076. {
  6077. // -------------------------------------------
  6078. // 'channel_module_calendar_start' hook.
  6079. // - Rewrite the displaying of the calendar tag
  6080. //
  6081. if ($this->EE->extensions->active_hook('channel_module_calendar_start') === TRUE)
  6082. {
  6083. $edata = $this->EE->extensions->call('channel_module_calendar_start');
  6084. if ($this->EE->extensions->end_script === TRUE) return $edata;
  6085. }
  6086. //
  6087. // -------------------------------------------
  6088. if ( ! class_exists('Channel_calendar'))
  6089. {
  6090. require PATH_MOD.'channel/mod.channel_calendar.php';
  6091. }
  6092. $WC = new Channel_calendar();
  6093. return $WC->calendar();
  6094. }
  6095. // ------------------------------------------------------------------------
  6096. /**
  6097. * Insert a new channel entry
  6098. *
  6099. * This function serves dual purpose:
  6100. * 1. It allows submitted data to be previewed
  6101. * 2. It allows submitted data to be inserted
  6102. */
  6103. public function insert_new_entry()
  6104. {
  6105. if ( ! class_exists('Channel_standalone'))
  6106. {
  6107. require PATH_MOD.'channel/mod.channel_standalone.php';
  6108. }
  6109. $WS = new Channel_standalone();
  6110. $WS->insert_new_entry();
  6111. }
  6112. // ------------------------------------------------------------------------
  6113. /**
  6114. * Ajax Image Upload
  6115. *
  6116. * Used by the SAEF
  6117. */
  6118. public function filemanager_endpoint($function = '', $params = array())
  6119. {
  6120. $this->EE->load->library('filemanager');
  6121. $this->EE->lang->loadfile('content');
  6122. //$this->EE->load->library('cp');
  6123. $config = array();
  6124. if ($function)
  6125. {
  6126. $this->EE->filemanager->_initialize($config);
  6127. return call_user_func_array(array($this->filemanager, $function), $params);
  6128. }
  6129. $this->EE->filemanager->process_request($config);
  6130. }
  6131. // ------------------------------------------------------------------------
  6132. /**
  6133. * Smiley pop up
  6134. *
  6135. * Used by the SAEF
  6136. */
  6137. public function smiley_pop()
  6138. {
  6139. if ($this->EE->session->userdata('member_id') == 0)
  6140. {
  6141. return $this->EE->output->fatal_error($this->EE->lang->line('must_be_logged_in'));
  6142. }
  6143. $class_path = PATH_MOD.'emoticon/emoticons.php';
  6144. if ( ! is_file($class_path) OR ! @include_once($class_path))
  6145. {
  6146. return $this->EE->output->fatal_error('Unable to locate the smiley images');
  6147. }
  6148. if ( ! is_array($smileys))
  6149. {
  6150. return;
  6151. }
  6152. $path = $this->EE->config->slash_item('emoticon_url');
  6153. ob_start();
  6154. ?>
  6155. <script type="text/javascript">
  6156. <!--
  6157. function add_smiley(smiley)
  6158. {
  6159. var el = opener.document.getElementById('submit_post').body;
  6160. if ('selectionStart' in el) {
  6161. newStart = el.selectionStart + smiley.length;
  6162. el.value = el.value.substr(0, el.selectionStart) +
  6163. smiley +
  6164. el.value.substr(el.selectionEnd, el.value.length);
  6165. el.setSelectionRange(newStart, newStart);
  6166. }
  6167. else if (opener.document.selection) {
  6168. opener.document.selection.createRange().text = smiley;
  6169. }
  6170. else {
  6171. el.value += " " + smiley + " ";
  6172. }
  6173. el.focus();
  6174. window.close();
  6175. }
  6176. //-->
  6177. </script>
  6178. <?php
  6179. $javascript = ob_get_contents();
  6180. ob_end_clean();
  6181. $r = $javascript;
  6182. $i = 1;
  6183. $dups = array();
  6184. foreach ($smileys as $key => $val)
  6185. {
  6186. if ($i == 1 AND substr($r, -5) != "<tr>\n")
  6187. {
  6188. $r .= "<tr>\n";
  6189. }
  6190. if (in_array($smileys[$key]['0'], $dups))
  6191. continue;
  6192. $r .= "<td class='tableCellOne' align='center'><a href=\"#\" onclick=\"return add_smiley('".$key."');\"><img src=\"".$path.$smileys[$key]['0']."\" width=\"".$smileys[$key]['1']."\" height=\"".$smileys[$key]['2']."\" alt=\"".$smileys[$key]['3']."\" border=\"0\" /></a></td>\n";
  6193. $dups[] = $smileys[$key]['0'];
  6194. if ($i == 10)
  6195. {
  6196. $r .= "</tr>\n";
  6197. $i = 1;
  6198. }
  6199. else
  6200. {
  6201. $i++;
  6202. }
  6203. }
  6204. $r = rtrim($r);
  6205. if (substr($r, -5) != "</tr>")
  6206. {
  6207. $r .= "</tr>\n";
  6208. }
  6209. $out = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'
  6210. .'"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
  6211. .'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="{lang}" lang="{lang}">'
  6212. .'<head>'
  6213. .'<meta http-equiv="content-type" content="text/html; charset={charset}" />'
  6214. .'<title>Smileys</title>'
  6215. .'</head><body>';
  6216. $out .= '<div id="content">'
  6217. .'<div class="tableBorderTopLeft">'
  6218. .'<table cellpadding="3" cellspacing="0" border="0" style="width:100%;" class="tableBG">';
  6219. $out .= $r;
  6220. $out .= '</table></div></div></body></html>';
  6221. print_r($out);
  6222. exit;
  6223. }
  6224. // ------------------------------------------------------------------------
  6225. /**
  6226. * Stand-alone version of the entry form
  6227. */
  6228. public function entry_form($return_form = FALSE, $captcha = '')
  6229. {
  6230. if ( ! class_exists('Channel_standalone'))
  6231. {
  6232. require PATH_MOD.'channel/mod.channel_standalone.php';
  6233. }
  6234. $WS = new Channel_standalone();
  6235. return $WS->entry_form($return_form, $captcha);
  6236. }
  6237. // ------------------------------------------------------------------------
  6238. /**
  6239. * ACT method for Stand Alone Entry Form Javascript
  6240. */
  6241. public function saef_filebrowser()
  6242. {
  6243. if ( ! class_exists('Channel_standalone'))
  6244. {
  6245. require PATH_MOD.'channel/mod.channel_standalone.php';
  6246. }
  6247. $channel_js = new Channel_standalone();
  6248. return $channel_js->saef_javascript();
  6249. }
  6250. }
  6251. // END CLASS
  6252. /* End of file mod.channel.php */
  6253. /* Location: ./system/expressionengine/modules/channel/mod.channel.php */