PageRenderTime 105ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 2ms

/html/AppCode/expressionengine/modules/channel/mod.channel.php

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