PageRenderTime 55ms CodeModel.GetById 8ms RepoModel.GetById 0ms app.codeStats 1ms

/system/expressionengine/modules/channel/mod.channel.php

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