Verzeichnisstruktur phpBB-3.0.0


Veröffentlicht
12.12.2007

So funktioniert es


Auf das letzte Element klicken. Dies geht jeweils ein Schritt zurück

Auf das Icon klicken, dies öffnet das Verzeichnis. Nochmal klicken schließt das Verzeichnis.
Auf den Verzeichnisnamen klicken, dies zeigt nur das Verzeichnis mit Inhalt an

(Beispiel Datei-Icons)

Auf das Icon klicken um den Quellcode anzuzeigen

viewtopic.php

Zuletzt modifiziert: 09.10.2024, 12:50 - Dateigröße: 58.99 KiB


0001  <?php
0002  /**
0003  *
0004  * @package phpBB3
0005  * @version $Id$
0006  * @copyright (c) 2005 phpBB Group
0007  * @license http://opensource.org/licenses/gpl-license.php GNU Public License
0008  *
0009  */
0010   
0011  /**
0012  * @ignore
0013  */
0014  define('IN_PHPBB', true);
0015  $phpbb_root_path = (defined('PHPBB_ROOT_PATH')) ? PHPBB_ROOT_PATH : './';
0016  $phpEx = substr(strrchr(__FILE__, '.'), 1);
0017  include($phpbb_root_path . 'common.' . $phpEx);
0018  include($phpbb_root_path . 'includes/functions_display.' . $phpEx);
0019  include($phpbb_root_path . 'includes/bbcode.' . $phpEx);
0020   
0021  // Start session management
0022  $user->session_begin();
0023  $auth->acl($user->data);
0024   
0025  // Initial var setup
0026  $forum_id    = request_var('f', 0);
0027  $topic_id    = request_var('t', 0);
0028  $post_id    = request_var('p', 0);
0029  $voted_id    = request_var('vote_id', array('' => 0));
0030   
0031  $start        = request_var('start', 0);
0032  $view        = request_var('view', '');
0033   
0034  $sort_days    = request_var('st', ((!empty($user->data['user_post_show_days'])) ? $user->data['user_post_show_days'] : 0));
0035  $sort_key    = request_var('sk', ((!empty($user->data['user_post_sortby_type'])) ? $user->data['user_post_sortby_type'] : 't'));
0036  $sort_dir    = request_var('sd', ((!empty($user->data['user_post_sortby_dir'])) ? $user->data['user_post_sortby_dir'] : 'a'));
0037   
0038  $update        = request_var('update', false);
0039   
0040  /**
0041  * @todo normalize?
0042  */
0043  $hilit_words    = request_var('hilit', '', true);
0044   
0045  // Do we have a topic or post id?
0046  if (!$topic_id && !$post_id)
0047  {
0048      trigger_error('NO_TOPIC');
0049  }
0050   
0051  // Find topic id if user requested a newer or older topic
0052  if ($view && !$post_id)
0053  {
0054      if (!$forum_id)
0055      {
0056          $sql = 'SELECT forum_id
0057              FROM ' . TOPICS_TABLE . "
0058              WHERE topic_id = $topic_id";
0059          $result = $db->sql_query($sql);
0060          $forum_id = (int) $db->sql_fetchfield('forum_id');
0061          $db->sql_freeresult($result);
0062   
0063          if (!$forum_id)
0064          {
0065              trigger_error('NO_TOPIC');
0066          }
0067      }
0068   
0069      if ($view == 'unread')
0070      {
0071          // Get topic tracking info
0072          $topic_tracking_info = get_complete_topic_tracking($forum_id, $topic_id);
0073   
0074          $topic_last_read = (isset($topic_tracking_info[$topic_id])) ? $topic_tracking_info[$topic_id] : 0;
0075   
0076          $sql = 'SELECT post_id, topic_id, forum_id
0077              FROM ' . POSTS_TABLE . "
0078              WHERE topic_id = $topic_id
0079                  " . (($auth->acl_get('m_approve', $forum_id)) ? '' : 'AND post_approved = 1') . "
0080                  AND post_time > $topic_last_read
0081              ORDER BY post_time ASC";
0082          $result = $db->sql_query_limit($sql, 1);
0083          $row = $db->sql_fetchrow($result);
0084          $db->sql_freeresult($result);
0085   
0086          if (!$row)
0087          {
0088              $sql = 'SELECT topic_last_post_id as post_id, topic_id, forum_id
0089                  FROM ' . TOPICS_TABLE . '
0090                  WHERE topic_id = ' . $topic_id;
0091              $result = $db->sql_query($sql);
0092              $row = $db->sql_fetchrow($result);
0093              $db->sql_freeresult($result);
0094          }
0095   
0096          if (!$row)
0097          {
0098              // Setup user environment so we can process lang string
0099              $user->setup('viewtopic');
0100   
0101              trigger_error('NO_TOPIC');
0102          }
0103   
0104          $post_id = $row['post_id'];
0105          $topic_id = $row['topic_id'];
0106      }
0107      else if ($view == 'next' || $view == 'previous')
0108      {
0109          $sql_condition = ($view == 'next') ? '>' : '<';
0110          $sql_ordering = ($view == 'next') ? 'ASC' : 'DESC';
0111   
0112          $sql = 'SELECT forum_id, topic_last_post_time
0113              FROM ' . TOPICS_TABLE . '
0114              WHERE topic_id = ' . $topic_id;
0115          $result = $db->sql_query($sql);
0116          $row = $db->sql_fetchrow($result);
0117          $db->sql_freeresult($result);
0118   
0119          if (!$row)
0120          {
0121              $user->setup('viewtopic');
0122              // OK, the topic doesn't exist. This error message is not helpful, but technically correct.
0123              trigger_error(($view == 'next') ? 'NO_NEWER_TOPICS' : 'NO_OLDER_TOPICS');
0124          }
0125          else
0126          {
0127              $sql = 'SELECT topic_id, forum_id
0128                  FROM ' . TOPICS_TABLE . '
0129                  WHERE forum_id = ' . $row['forum_id'] . "
0130                      AND topic_moved_id = 0
0131                      AND topic_last_post_time $sql_condition {$row['topic_last_post_time']}
0132                      " . (($auth->acl_get('m_approve', $row['forum_id'])) ? '' : 'AND topic_approved = 1') . "
0133                  ORDER BY topic_last_post_time $sql_ordering";
0134              $result = $db->sql_query_limit($sql, 1);
0135              $row = $db->sql_fetchrow($result);
0136              $db->sql_freeresult($result);
0137   
0138              if (!$row)
0139              {
0140                  $user->setup('viewtopic');
0141                  trigger_error(($view == 'next') ? 'NO_NEWER_TOPICS' : 'NO_OLDER_TOPICS');
0142              }
0143              else
0144              {
0145                  $topic_id = $row['topic_id'];
0146   
0147                  // Check for global announcement correctness?
0148                  if (!$row['forum_id'] && !$forum_id)
0149                  {
0150                      trigger_error('NO_TOPIC');
0151                  }
0152                  else if ($row['forum_id'])
0153                  {
0154                      $forum_id = $row['forum_id'];
0155                  }
0156              }
0157          }
0158      }
0159   
0160      // Check for global announcement correctness?
0161      if ((!isset($row) || !$row['forum_id']) && !$forum_id)
0162      {
0163          trigger_error('NO_TOPIC');
0164      }
0165      else if (isset($row) && $row['forum_id'])
0166      {
0167          $forum_id = $row['forum_id'];
0168      }
0169  }
0170   
0171  // This rather complex gaggle of code handles querying for topics but
0172  // also allows for direct linking to a post (and the calculation of which
0173  // page the post is on and the correct display of viewtopic)
0174  $sql_array = array(
0175      'SELECT'    => 't.*, f.*',
0176   
0177      'FROM'        => array(
0178          FORUMS_TABLE    => 'f',
0179      )
0180  );
0181   
0182  if ($user->data['is_registered'])
0183  {
0184      $sql_array['SELECT'] .= ', tw.notify_status';
0185      $sql_array['LEFT_JOIN'] = array();
0186   
0187      $sql_array['LEFT_JOIN'][] = array(
0188          'FROM'    => array(TOPICS_WATCH_TABLE => 'tw'),
0189          'ON'    => 'tw.user_id = ' . $user->data['user_id'] . ' AND t.topic_id = tw.topic_id'
0190      );
0191   
0192      if ($config['allow_bookmarks'])
0193      {
0194          $sql_array['SELECT'] .= ', bm.topic_id as bookmarked';
0195          $sql_array['LEFT_JOIN'][] = array(
0196              'FROM'    => array(BOOKMARKS_TABLE => 'bm'),
0197              'ON'    => 'bm.user_id = ' . $user->data['user_id'] . ' AND t.topic_id = bm.topic_id'
0198          );
0199      }
0200   
0201      if ($config['load_db_lastread'])
0202      {
0203          $sql_array['SELECT'] .= ', tt.mark_time, ft.mark_time as forum_mark_time';
0204   
0205          $sql_array['LEFT_JOIN'][] = array(
0206              'FROM'    => array(TOPICS_TRACK_TABLE => 'tt'),
0207              'ON'    => 'tt.user_id = ' . $user->data['user_id'] . ' AND t.topic_id = tt.topic_id'
0208          );
0209   
0210          $sql_array['LEFT_JOIN'][] = array(
0211              'FROM'    => array(FORUMS_TRACK_TABLE => 'ft'),
0212              'ON'    => 'ft.user_id = ' . $user->data['user_id'] . ' AND t.forum_id = ft.forum_id'
0213          );
0214      }
0215  }
0216   
0217  if (!$post_id)
0218  {
0219      $sql_array['WHERE'] = "t.topic_id = $topic_id";
0220  }
0221  else
0222  {
0223      $sql_array['WHERE'] = "p.post_id = $post_id AND t.topic_id = p.topic_id" . ((!$auth->acl_get('m_approve', $forum_id)) ? ' AND p.post_approved = 1' : '');
0224      $sql_array['FROM'][POSTS_TABLE] = 'p';
0225  }
0226   
0227  $sql_array['WHERE'] .= ' AND (f.forum_id = t.forum_id';
0228   
0229  if (!$forum_id)
0230  {
0231      // If it is a global announcement make sure to set the forum id to a postable forum
0232      $sql_array['WHERE'] .= ' OR (t.topic_type = ' . POST_GLOBAL . '
0233          AND f.forum_type = ' . FORUM_POST . ')';
0234  }
0235  else
0236  {
0237      $sql_array['WHERE'] .= ' OR (t.topic_type = ' . POST_GLOBAL . "
0238          AND f.forum_id = $forum_id)";
0239  }
0240   
0241  $sql_array['WHERE'] .= ')';
0242  $sql_array['FROM'][TOPICS_TABLE] = 't';
0243   
0244  // Join to forum table on topic forum_id unless topic forum_id is zero
0245  // whereupon we join on the forum_id passed as a parameter ... this
0246  // is done so navigation, forum name, etc. remain consistent with where
0247  // user clicked to view a global topic
0248  $sql = $db->sql_build_query('SELECT', $sql_array);
0249  $result = $db->sql_query($sql);
0250  $topic_data = $db->sql_fetchrow($result);
0251  $db->sql_freeresult($result);
0252   
0253  if (!$topic_data)
0254  {
0255      // If post_id was submitted, we try at least to display the topic as a last resort...
0256      if ($post_id && $forum_id && $topic_id)
0257      {
0258          redirect(append_sid("{$phpbb_root_path}viewtopic.$phpEx", "f=$forum_id&amp;t=$topic_id"));
0259      }
0260   
0261      trigger_error('NO_TOPIC');
0262  }
0263   
0264  // This is for determining where we are (page)
0265  if ($post_id)
0266  {
0267      if ($post_id == $topic_data['topic_first_post_id'] || $post_id == $topic_data['topic_last_post_id'])
0268      {
0269          $check_sort = ($post_id == $topic_data['topic_first_post_id']) ? 'd' : 'a';
0270   
0271          if ($sort_dir == $check_sort)
0272          {
0273              $topic_data['prev_posts'] = ($auth->acl_get('m_approve', $forum_id)) ? $topic_data['topic_replies_real'] : $topic_data['topic_replies'];
0274          }
0275          else
0276          {
0277              $topic_data['prev_posts'] = 0;
0278          }
0279      }
0280      else
0281      {
0282          $sql = 'SELECT COUNT(p1.post_id) AS prev_posts
0283              FROM ' . POSTS_TABLE . ' p1, ' . POSTS_TABLE . " p2
0284              WHERE p1.topic_id = {$topic_data['topic_id']}
0285                  AND p2.post_id = {$post_id}
0286                  " . ((!$auth->acl_get('m_approve', $forum_id)) ? 'AND p1.post_approved = 1' : '') . '
0287                  AND ' . (($sort_dir == 'd') ? 'p1.post_time >= p2.post_time' : 'p1.post_time <= p2.post_time');
0288   
0289          $result = $db->sql_query($sql);
0290          $row = $db->sql_fetchrow($result);
0291          $db->sql_freeresult($result);
0292   
0293          $topic_data['prev_posts'] = $row['prev_posts'] - 1;
0294      }
0295  }
0296   
0297  $forum_id = (int) $topic_data['forum_id'];
0298  $topic_id = (int) $topic_data['topic_id'];
0299   
0300  //
0301  $topic_replies = ($auth->acl_get('m_approve', $forum_id)) ? $topic_data['topic_replies_real'] : $topic_data['topic_replies'];
0302   
0303  // Check sticky/announcement time limit
0304  if (($topic_data['topic_type'] == POST_STICKY || $topic_data['topic_type'] == POST_ANNOUNCE) && $topic_data['topic_time_limit'] && ($topic_data['topic_time'] + $topic_data['topic_time_limit']) < time())
0305  {
0306      $sql = 'UPDATE ' . TOPICS_TABLE . '
0307          SET topic_type = ' . POST_NORMAL . ', topic_time_limit = 0
0308          WHERE topic_id = ' . $topic_id;
0309      $db->sql_query($sql);
0310   
0311      $topic_data['topic_type'] = POST_NORMAL;
0312      $topic_data['topic_time_limit'] = 0;
0313  }
0314   
0315  // Setup look and feel
0316  $user->setup('viewtopic', $topic_data['forum_style']);
0317   
0318  if (!$topic_data['topic_approved'] && !$auth->acl_get('m_approve', $forum_id))
0319  {
0320      trigger_error('NO_TOPIC');
0321  }
0322   
0323  // Start auth check
0324  if (!$auth->acl_get('f_read', $forum_id))
0325  {
0326      if ($user->data['user_id'] != ANONYMOUS)
0327      {
0328          trigger_error('SORRY_AUTH_READ');
0329      }
0330   
0331      login_box('', $user->lang['LOGIN_VIEWFORUM']);
0332  }
0333   
0334  // Forum is passworded ... check whether access has been granted to this
0335  // user this session, if not show login box
0336  if ($topic_data['forum_password'])
0337  {
0338      login_forum_box($topic_data);
0339  }
0340   
0341  // Redirect to login or to the correct post upon emailed notification links
0342  if (isset($_GET['e']))
0343  {
0344      $jump_to = request_var('e', 0);
0345   
0346      $redirect_url = append_sid("{$phpbb_root_path}viewtopic.$phpEx", "f=$forum_id&amp;t=$topic_id");
0347   
0348      if ($user->data['user_id'] == ANONYMOUS)
0349      {
0350          login_box($redirect_url . "&amp;p=$post_id&amp;e=$jump_to", $user->lang['LOGIN_NOTIFY_TOPIC']);
0351      }
0352   
0353      if ($jump_to > 0)
0354      {
0355          // We direct the already logged in user to the correct post...
0356          redirect($redirect_url . ((!$post_id) ? "&amp;p=$jump_to" : "&amp;p=$post_id") . "#p$jump_to");
0357      }
0358  }
0359   
0360  // What is start equal to?
0361  if ($post_id)
0362  {
0363      $start = floor(($topic_data['prev_posts']) / $config['posts_per_page']) * $config['posts_per_page'];
0364  }
0365   
0366  // Get topic tracking info
0367  if (!isset($topic_tracking_info))
0368  {
0369      $topic_tracking_info = array();
0370   
0371      // Get topic tracking info
0372      if ($config['load_db_lastread'] && $user->data['is_registered'])
0373      {
0374          $tmp_topic_data = array($topic_id => $topic_data);
0375          $topic_tracking_info = get_topic_tracking($forum_id, $topic_id, $tmp_topic_data, array($forum_id => $topic_data['forum_mark_time']));
0376          unset($tmp_topic_data);
0377      }
0378      else if ($config['load_anon_lastread'] || $user->data['is_registered'])
0379      {
0380          $topic_tracking_info = get_complete_topic_tracking($forum_id, $topic_id);
0381      }
0382  }
0383   
0384  // Post ordering options
0385  $limit_days = array(0 => $user->lang['ALL_POSTS'], 1 => $user->lang['1_DAY'], 7 => $user->lang['7_DAYS'], 14 => $user->lang['2_WEEKS'], 30 => $user->lang['1_MONTH'], 90 => $user->lang['3_MONTHS'], 180 => $user->lang['6_MONTHS'], 365 => $user->lang['1_YEAR']);
0386   
0387  $sort_by_text = array('a' => $user->lang['AUTHOR'], 't' => $user->lang['POST_TIME'], 's' => $user->lang['SUBJECT']);
0388  $sort_by_sql = array('a' => 'u.username_clean', 't' => 'p.post_time', 's' => 'p.post_subject');
0389   
0390  $s_limit_days = $s_sort_key = $s_sort_dir = $u_sort_param = '';
0391  gen_sort_selects($limit_days, $sort_by_text, $sort_days, $sort_key, $sort_dir, $s_limit_days, $s_sort_key, $s_sort_dir, $u_sort_param);
0392   
0393  // Obtain correct post count and ordering SQL if user has
0394  // requested anything different
0395  if ($sort_days)
0396  {
0397      $min_post_time = time() - ($sort_days * 86400);
0398   
0399      $sql = 'SELECT COUNT(post_id) AS num_posts
0400          FROM ' . POSTS_TABLE . "
0401          WHERE topic_id = $topic_id
0402              AND post_time >= $min_post_time
0403          " . (($auth->acl_get('m_approve', $forum_id)) ? '' : 'AND post_approved = 1');
0404      $result = $db->sql_query($sql);
0405      $total_posts = (int) $db->sql_fetchfield('num_posts');
0406      $db->sql_freeresult($result);
0407   
0408      $limit_posts_time = "AND p.post_time >= $min_post_time ";
0409   
0410      if (isset($_POST['sort']))
0411      {
0412          $start = 0;
0413      }
0414  }
0415  else
0416  {
0417      $total_posts = $topic_replies + 1;
0418      $limit_posts_time = '';
0419  }
0420   
0421  // Was a highlight request part of the URI?
0422  $highlight_match = $highlight = '';
0423  if ($hilit_words)
0424  {
0425      foreach (explode(' ', trim($hilit_words)) as $word)
0426      {
0427          if (trim($word))
0428          {
0429              $word = str_replace('\*', '\w+?', preg_quote($word, '#'));
0430              $word = preg_replace('#(^|\s)\\\\w\*\?(\s|$)#', '$1\w+?$2', $word);
0431              $highlight_match .= (($highlight_match != '') ? '|' : '') . $word;
0432          }
0433      }
0434   
0435      $highlight = urlencode($hilit_words);
0436  }
0437   
0438  // Make sure $start is set to the last page if it exceeds the amount
0439  if ($start < 0 || $start > $total_posts)
0440  {
0441      $start = ($start < 0) ? 0 : floor(($total_posts - 1) / $config['posts_per_page']) * $config['posts_per_page'];
0442  }
0443   
0444  // General Viewtopic URL for return links
0445  $viewtopic_url = append_sid("{$phpbb_root_path}viewtopic.$phpEx", "f=$forum_id&amp;t=$topic_id&amp;start=$start&amp;$u_sort_param" . (($highlight_match) ? "&amp;hilit=$highlight" : ''));
0446   
0447  // Are we watching this topic?
0448  $s_watching_topic = $s_watching_topic_img = array();
0449  $s_watching_topic['link'] = $s_watching_topic['title'] = '';
0450  $s_watching_topic['is_watching'] = false;
0451   
0452  if ($config['email_enable'] && $config['allow_topic_notify'] && $user->data['is_registered'])
0453  {
0454      watch_topic_forum('topic', $s_watching_topic, $s_watching_topic_img, $user->data['user_id'], $forum_id, $topic_id, $topic_data['notify_status'], $start);
0455  }
0456   
0457  // Bookmarks
0458  if ($config['allow_bookmarks'] && $user->data['is_registered'] && request_var('bookmark', 0))
0459  {
0460      if (!$topic_data['bookmarked'])
0461      {
0462          $sql = 'INSERT INTO ' . BOOKMARKS_TABLE . ' ' . $db->sql_build_array('INSERT', array(
0463              'user_id'    => $user->data['user_id'],
0464              'topic_id'    => $topic_id,
0465          ));
0466          $db->sql_query($sql);
0467      }
0468      else
0469      {
0470          $sql = 'DELETE FROM ' . BOOKMARKS_TABLE . "
0471              WHERE user_id = {$user->data['user_id']}
0472                  AND topic_id = $topic_id";
0473          $db->sql_query($sql);
0474      }
0475   
0476      meta_refresh(3, $viewtopic_url);
0477   
0478      $message = (($topic_data['bookmarked']) ? $user->lang['BOOKMARK_REMOVED'] : $user->lang['BOOKMARK_ADDED']) . '<br /><br />' . sprintf($user->lang['RETURN_TOPIC'], '<a href="' . $viewtopic_url . '">', '</a>');
0479      trigger_error($message);
0480  }
0481   
0482  // Grab ranks
0483  $ranks = $cache->obtain_ranks();
0484   
0485  // Grab icons
0486  $icons = $cache->obtain_icons();
0487   
0488  // Grab extensions
0489  $extensions = array();
0490  if ($topic_data['topic_attachment'])
0491  {
0492      $extensions = $cache->obtain_attach_extensions($forum_id);
0493  }
0494   
0495  // Forum rules listing
0496  $s_forum_rules = '';
0497  gen_forum_auth_level('topic', $forum_id, $topic_data['forum_status']);
0498   
0499  // Quick mod tools
0500  $allow_change_type = ($auth->acl_get('m_', $forum_id) || ($user->data['is_registered'] && $user->data['user_id'] == $topic_data['topic_poster'])) ? true : false;
0501   
0502  $topic_mod = '';
0503  $topic_mod .= ($auth->acl_get('m_lock', $forum_id) || ($auth->acl_get('f_user_lock', $forum_id) && $user->data['is_registered'] && $user->data['user_id'] == $topic_data['topic_poster'] && $topic_data['topic_status'] == ITEM_UNLOCKED)) ? (($topic_data['topic_status'] == ITEM_UNLOCKED) ? '<option value="lock">' . $user->lang['LOCK_TOPIC'] . '</option>' : '<option value="unlock">' . $user->lang['UNLOCK_TOPIC'] . '</option>') : '';
0504  $topic_mod .= ($auth->acl_get('m_delete', $forum_id)) ? '<option value="delete_topic">' . $user->lang['DELETE_TOPIC'] . '</option>' : '';
0505  $topic_mod .= ($auth->acl_get('m_move', $forum_id) && $topic_data['topic_status'] != ITEM_MOVED) ? '<option value="move">' . $user->lang['MOVE_TOPIC'] . '</option>' : '';
0506  $topic_mod .= ($auth->acl_get('m_split', $forum_id)) ? '<option value="split">' . $user->lang['SPLIT_TOPIC'] . '</option>' : '';
0507  $topic_mod .= ($auth->acl_get('m_merge', $forum_id)) ? '<option value="merge">' . $user->lang['MERGE_POSTS'] . '</option>' : '';
0508  $topic_mod .= ($auth->acl_get('m_merge', $forum_id)) ? '<option value="merge_topic">' . $user->lang['MERGE_TOPIC'] . '</option>' : '';
0509  $topic_mod .= ($auth->acl_get('m_move', $forum_id)) ? '<option value="fork">' . $user->lang['FORK_TOPIC'] . '</option>' : '';
0510  $topic_mod .= ($allow_change_type && $auth->acl_gets('f_sticky', 'f_announce', $forum_id) && $topic_data['topic_type'] != POST_NORMAL) ? '<option value="make_normal">' . $user->lang['MAKE_NORMAL'] . '</option>' : '';
0511  $topic_mod .= ($allow_change_type && $auth->acl_get('f_sticky', $forum_id) && $topic_data['topic_type'] != POST_STICKY) ? '<option value="make_sticky">' . $user->lang['MAKE_STICKY'] . '</option>' : '';
0512  $topic_mod .= ($allow_change_type && $auth->acl_get('f_announce', $forum_id) && $topic_data['topic_type'] != POST_ANNOUNCE) ? '<option value="make_announce">' . $user->lang['MAKE_ANNOUNCE'] . '</option>' : '';
0513  $topic_mod .= ($allow_change_type && $auth->acl_get('f_announce', $forum_id) && $topic_data['topic_type'] != POST_GLOBAL) ? '<option value="make_global">' . $user->lang['MAKE_GLOBAL'] . '</option>' : '';
0514  $topic_mod .= ($auth->acl_get('m_', $forum_id)) ? '<option value="topic_logs">' . $user->lang['VIEW_TOPIC_LOGS'] . '</option>' : '';
0515   
0516  // If we've got a hightlight set pass it on to pagination.
0517  $pagination = generate_pagination(append_sid("{$phpbb_root_path}viewtopic.$phpEx", "f=$forum_id&amp;t=$topic_id&amp;$u_sort_param" . (($highlight_match) ? "&amp;hilit=$highlight" : '')), $total_posts, $config['posts_per_page'], $start);
0518   
0519  // Navigation links
0520  generate_forum_nav($topic_data);
0521   
0522  // Forum Rules
0523  generate_forum_rules($topic_data);
0524   
0525  // Moderators
0526  $forum_moderators = array();
0527  get_moderators($forum_moderators, $forum_id);
0528   
0529  // This is only used for print view so ...
0530  $server_path = (!$view) ? $phpbb_root_path : generate_board_url() . '/';
0531   
0532  // Replace naughty words in title
0533  $topic_data['topic_title'] = censor_text($topic_data['topic_title']);
0534   
0535  // Send vars to template
0536  $template->assign_vars(array(
0537      'FORUM_ID'         => $forum_id,
0538      'FORUM_NAME'     => $topic_data['forum_name'],
0539      'FORUM_DESC'    => generate_text_for_display($topic_data['forum_desc'], $topic_data['forum_desc_uid'], $topic_data['forum_desc_bitfield'], $topic_data['forum_desc_options']),
0540      'TOPIC_ID'         => $topic_id,
0541      'TOPIC_TITLE'     => $topic_data['topic_title'],
0542      'TOPIC_POSTER'    => $topic_data['topic_poster'],
0543   
0544      'TOPIC_AUTHOR_FULL'        => get_username_string('full', $topic_data['topic_poster'], $topic_data['topic_first_poster_name'], $topic_data['topic_first_poster_colour']),
0545      'TOPIC_AUTHOR_COLOUR'    => get_username_string('colour', $topic_data['topic_poster'], $topic_data['topic_first_poster_name'], $topic_data['topic_first_poster_colour']),
0546      'TOPIC_AUTHOR'            => get_username_string('username', $topic_data['topic_poster'], $topic_data['topic_first_poster_name'], $topic_data['topic_first_poster_colour']),
0547   
0548      'PAGINATION'     => $pagination,
0549      'PAGE_NUMBER'     => on_page($total_posts, $config['posts_per_page'], $start),
0550      'TOTAL_POSTS'    => ($total_posts == 1) ? $user->lang['VIEW_TOPIC_POST'] : sprintf($user->lang['VIEW_TOPIC_POSTS'], $total_posts),
0551      'U_MCP'         => ($auth->acl_get('m_', $forum_id)) ? append_sid("{$phpbb_root_path}mcp.$phpEx", "i=main&amp;mode=topic_view&amp;f=$forum_id&amp;t=$topic_id&amp;start=$start&amp;$u_sort_param", true, $user->session_id) : '',
0552      'MODERATORS'    => (isset($forum_moderators[$forum_id]) && sizeof($forum_moderators[$forum_id])) ? implode(', ', $forum_moderators[$forum_id]) : '',
0553   
0554      'POST_IMG'             => ($topic_data['forum_status'] == ITEM_LOCKED) ? $user->img('button_topic_locked', 'FORUM_LOCKED') : $user->img('button_topic_new', 'POST_NEW_TOPIC'),
0555      'QUOTE_IMG'         => $user->img('icon_post_quote', 'REPLY_WITH_QUOTE'),
0556      'REPLY_IMG'            => ($topic_data['forum_status'] == ITEM_LOCKED || $topic_data['topic_status'] == ITEM_LOCKED) ? $user->img('button_topic_locked', 'TOPIC_LOCKED') : $user->img('button_topic_reply', 'REPLY_TO_TOPIC'),
0557      'EDIT_IMG'             => $user->img('icon_post_edit', 'EDIT_POST'),
0558      'DELETE_IMG'         => $user->img('icon_post_delete', 'DELETE_POST'),
0559      'INFO_IMG'             => $user->img('icon_post_info', 'VIEW_INFO'),
0560      'PROFILE_IMG'        => $user->img('icon_user_profile', 'READ_PROFILE'),
0561      'SEARCH_IMG'         => $user->img('icon_user_search', 'SEARCH_USER_POSTS'),
0562      'PM_IMG'             => $user->img('icon_contact_pm', 'SEND_PRIVATE_MESSAGE'),
0563      'EMAIL_IMG'         => $user->img('icon_contact_email', 'SEND_EMAIL'),
0564      'WWW_IMG'             => $user->img('icon_contact_www', 'VISIT_WEBSITE'),
0565      'ICQ_IMG'             => $user->img('icon_contact_icq', 'ICQ'),
0566      'AIM_IMG'             => $user->img('icon_contact_aim', 'AIM'),
0567      'MSN_IMG'             => $user->img('icon_contact_msnm', 'MSNM'),
0568      'YIM_IMG'             => $user->img('icon_contact_yahoo', 'YIM'),
0569      'JABBER_IMG'        => $user->img('icon_contact_jabber', 'JABBER') ,
0570      'REPORT_IMG'        => $user->img('icon_post_report', 'REPORT_POST'),
0571      'REPORTED_IMG'        => $user->img('icon_topic_reported', 'POST_REPORTED'),
0572      'UNAPPROVED_IMG'    => $user->img('icon_topic_unapproved', 'POST_UNAPPROVED'),
0573      'WARN_IMG'            => $user->img('icon_user_warn', 'WARN_USER'),
0574   
0575      'S_IS_LOCKED'            =>($topic_data['topic_status'] == ITEM_UNLOCKED) ? false : true,
0576      'S_SELECT_SORT_DIR'     => $s_sort_dir,
0577      'S_SELECT_SORT_KEY'     => $s_sort_key,
0578      'S_SELECT_SORT_DAYS'     => $s_limit_days,
0579      'S_SINGLE_MODERATOR'    => (!empty($forum_moderators[$forum_id]) && sizeof($forum_moderators[$forum_id]) > 1) ? false : true,
0580      'S_TOPIC_ACTION'         => append_sid("{$phpbb_root_path}viewtopic.$phpEx", "f=$forum_id&amp;t=$topic_id&amp;start=$start"),
0581      'S_TOPIC_MOD'             => ($topic_mod != '') ? '<select name="action">' . $topic_mod . '</select>' : '',
0582      'S_MOD_ACTION'             => append_sid("{$phpbb_root_path}mcp.$phpEx", "f=$forum_id&amp;t=$topic_id&amp;quickmod=1&amp;redirect=" . urlencode(str_replace('&amp;', '&', $viewtopic_url)), true, $user->session_id),
0583   
0584      'S_VIEWTOPIC'            => true,
0585      'S_DISPLAY_SEARCHBOX'    => ($auth->acl_get('u_search') && $auth->acl_get('f_search', $forum_id) && $config['load_search']) ? true : false,
0586      'S_SEARCHBOX_ACTION'    => append_sid("{$phpbb_root_path}search.$phpEx", 't=' . $topic_id),
0587   
0588      'S_DISPLAY_POST_INFO'    => ($topic_data['forum_type'] == FORUM_POST && ($auth->acl_get('f_post', $forum_id) || $user->data['user_id'] == ANONYMOUS)) ? true : false,
0589      'S_DISPLAY_REPLY_INFO'    => ($topic_data['forum_type'] == FORUM_POST && ($auth->acl_get('f_reply', $forum_id) || $user->data['user_id'] == ANONYMOUS)) ? true : false,
0590   
0591      'U_TOPIC'                => "{$server_path}viewtopic.$phpEx?f=$forum_id&amp;t=$topic_id",
0592      'U_FORUM'                => $server_path,
0593      'U_VIEW_TOPIC'             => $viewtopic_url,
0594      'U_VIEW_FORUM'             => append_sid("{$phpbb_root_path}viewforum.$phpEx", 'f=' . $forum_id),
0595      'U_VIEW_OLDER_TOPIC'    => append_sid("{$phpbb_root_path}viewtopic.$phpEx", "f=$forum_id&amp;t=$topic_id&amp;view=previous"),
0596      'U_VIEW_NEWER_TOPIC'    => append_sid("{$phpbb_root_path}viewtopic.$phpEx", "f=$forum_id&amp;t=$topic_id&amp;view=next"),
0597      'U_PRINT_TOPIC'            => ($auth->acl_get('f_print', $forum_id)) ? $viewtopic_url . '&amp;view=print' : '',
0598      'U_EMAIL_TOPIC'            => ($auth->acl_get('f_email', $forum_id) && $config['email_enable']) ? append_sid("{$phpbb_root_path}memberlist.$phpEx", "mode=email&amp;t=$topic_id") : '',
0599   
0600      'U_WATCH_TOPIC'         => $s_watching_topic['link'],
0601      'L_WATCH_TOPIC'         => $s_watching_topic['title'],
0602      'S_WATCHING_TOPIC'        => $s_watching_topic['is_watching'],
0603   
0604      'U_BOOKMARK_TOPIC'        => ($user->data['is_registered'] && $config['allow_bookmarks']) ? $viewtopic_url . '&amp;bookmark=1' : '',
0605      'L_BOOKMARK_TOPIC'        => ($user->data['is_registered'] && $config['allow_bookmarks'] && $topic_data['bookmarked']) ? $user->lang['BOOKMARK_TOPIC_REMOVE'] : $user->lang['BOOKMARK_TOPIC'],
0606   
0607      'U_POST_NEW_TOPIC'         => ($auth->acl_get('f_post', $forum_id) || $user->data['user_id'] == ANONYMOUS) ? append_sid("{$phpbb_root_path}posting.$phpEx", "mode=post&amp;f=$forum_id") : '',
0608      'U_POST_REPLY_TOPIC'     => ($auth->acl_get('f_reply', $forum_id) || $user->data['user_id'] == ANONYMOUS) ? append_sid("{$phpbb_root_path}posting.$phpEx", "mode=reply&amp;f=$forum_id&amp;t=$topic_id") : '',
0609      'U_BUMP_TOPIC'            => (bump_topic_allowed($forum_id, $topic_data['topic_bumped'], $topic_data['topic_last_post_time'], $topic_data['topic_poster'], $topic_data['topic_last_poster_id'])) ? append_sid("{$phpbb_root_path}posting.$phpEx", "mode=bump&amp;f=$forum_id&amp;t=$topic_id") : '')
0610  );
0611   
0612  // Does this topic contain a poll?
0613  if (!empty($topic_data['poll_start']))
0614  {
0615      $sql = 'SELECT o.*, p.bbcode_bitfield, p.bbcode_uid
0616          FROM ' . POLL_OPTIONS_TABLE . ' o, ' . POSTS_TABLE . " p
0617          WHERE o.topic_id = $topic_id
0618              AND p.post_id = {$topic_data['topic_first_post_id']}
0619              AND p.topic_id = o.topic_id
0620          ORDER BY o.poll_option_id";
0621      $result = $db->sql_query($sql);
0622   
0623      $poll_info = array();
0624      while ($row = $db->sql_fetchrow($result))
0625      {
0626          $poll_info[] = $row;
0627      }
0628      $db->sql_freeresult($result);
0629   
0630      $cur_voted_id = array();
0631      if ($user->data['is_registered'])
0632      {
0633          $sql = 'SELECT poll_option_id
0634              FROM ' . POLL_VOTES_TABLE . '
0635              WHERE topic_id = ' . $topic_id . '
0636                  AND vote_user_id = ' . $user->data['user_id'];
0637          $result = $db->sql_query($sql);
0638   
0639          while ($row = $db->sql_fetchrow($result))
0640          {
0641              $cur_voted_id[] = $row['poll_option_id'];
0642          }
0643          $db->sql_freeresult($result);
0644      }
0645      else
0646      {
0647          // Cookie based guest tracking ... I don't like this but hum ho
0648          // it's oft requested. This relies on "nice" users who don't feel
0649          // the need to delete cookies to mess with results.
0650          if (isset($_COOKIE[$config['cookie_name'] . '_poll_' . $topic_id]))
0651          {
0652              $cur_voted_id = explode(',', $_COOKIE[$config['cookie_name'] . '_poll_' . $topic_id]);
0653              $cur_voted_id = array_map('intval', $cur_voted_id);
0654          }
0655      }
0656   
0657      $s_can_vote = (((!sizeof($cur_voted_id) && $auth->acl_get('f_vote', $forum_id)) ||
0658          ($auth->acl_get('f_votechg', $forum_id) && $topic_data['poll_vote_change'])) &&
0659          (($topic_data['poll_length'] != 0 && $topic_data['poll_start'] + $topic_data['poll_length'] > time()) || $topic_data['poll_length'] == 0) &&
0660          $topic_data['topic_status'] != ITEM_LOCKED &&
0661          $topic_data['forum_status'] != ITEM_LOCKED) ? true : false;
0662      $s_display_results = (!$s_can_vote || ($s_can_vote && sizeof($cur_voted_id)) || $view == 'viewpoll') ? true : false;
0663   
0664      if ($update && $s_can_vote)
0665      {
0666          
0667          if (!sizeof($voted_id) || sizeof($voted_id) > $topic_data['poll_max_options'] || in_array(VOTE_CONVERTED, $cur_voted_id))
0668          {
0669              $redirect_url = append_sid("{$phpbb_root_path}viewtopic.$phpEx", "f=$forum_id&amp;t=$topic_id&amp;start=$start");
0670   
0671              meta_refresh(5, $redirect_url);
0672              if (!sizeof($voted_id))
0673              {
0674                  $message = 'NO_VOTE_OPTION';
0675              }
0676              else if (sizeof($voted_id) > $topic_data['poll_max_options'])
0677              {
0678                  $message = 'TOO_MANY_VOTE_OPTIONS';
0679              }
0680              else
0681              {
0682                  $message = 'VOTE_CONVERTED';
0683              }
0684   
0685              $message = $user->lang[$message] . '<br /><br />' . sprintf($user->lang['RETURN_TOPIC'], '<a href="' . $redirect_url . '">', '</a>');
0686              trigger_error($message);
0687          }
0688   
0689          foreach ($voted_id as $option)
0690          {
0691              if (in_array($option, $cur_voted_id))
0692              {
0693                  continue;
0694              }
0695   
0696              $sql = 'UPDATE ' . POLL_OPTIONS_TABLE . '
0697                  SET poll_option_total = poll_option_total + 1
0698                  WHERE poll_option_id = ' . (int) $option . '
0699                      AND topic_id = ' . (int) $topic_id;
0700              $db->sql_query($sql);
0701   
0702              if ($user->data['is_registered'])
0703              {
0704                  $sql_ary = array(
0705                      'topic_id'            => (int) $topic_id,
0706                      'poll_option_id'    => (int) $option,
0707                      'vote_user_id'        => (int) $user->data['user_id'],
0708                      'vote_user_ip'        => (string) $user->ip,
0709                  );
0710   
0711                  $sql = 'INSERT INTO ' . POLL_VOTES_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary);
0712                  $db->sql_query($sql);
0713              }
0714          }
0715   
0716          foreach ($cur_voted_id as $option)
0717          {
0718              if (!in_array($option, $voted_id))
0719              {
0720                  $sql = 'UPDATE ' . POLL_OPTIONS_TABLE . '
0721                      SET poll_option_total = poll_option_total - 1
0722                      WHERE poll_option_id = ' . (int) $option . '
0723                          AND topic_id = ' . (int) $topic_id;
0724                  $db->sql_query($sql);
0725   
0726                  if ($user->data['is_registered'])
0727                  {
0728                      $sql = 'DELETE FROM ' . POLL_VOTES_TABLE . '
0729                          WHERE topic_id = ' . (int) $topic_id . '
0730                              AND poll_option_id = ' . (int) $option . '
0731                              AND vote_user_id = ' . (int) $user->data['user_id'];
0732                      $db->sql_query($sql);
0733                  }
0734              }
0735          }
0736   
0737          if ($user->data['user_id'] == ANONYMOUS && !$user->data['is_bot'])
0738          {
0739              $user->set_cookie('poll_' . $topic_id, implode(',', $voted_id), time() + 31536000);
0740          }
0741   
0742          $sql = 'UPDATE ' . TOPICS_TABLE . '
0743              SET poll_last_vote = ' . time() . "
0744              WHERE topic_id = $topic_id";
0745          //, topic_last_post_time = ' . time() . " -- for bumping topics with new votes, ignore for now
0746          $db->sql_query($sql);
0747   
0748          $redirect_url = append_sid("{$phpbb_root_path}viewtopic.$phpEx", "f=$forum_id&amp;t=$topic_id&amp;start=$start");
0749   
0750          meta_refresh(5, $redirect_url);
0751          trigger_error($user->lang['VOTE_SUBMITTED'] . '<br /><br />' . sprintf($user->lang['RETURN_TOPIC'], '<a href="' . $redirect_url . '">', '</a>'));
0752      }
0753   
0754      $poll_total = 0;
0755      foreach ($poll_info as $poll_option)
0756      {
0757          $poll_total += $poll_option['poll_option_total'];
0758      }
0759   
0760      if ($poll_info[0]['bbcode_bitfield'])
0761      {
0762          $poll_bbcode = new bbcode();
0763      }
0764      else
0765      {
0766          $poll_bbcode = false;
0767      }
0768   
0769      for ($i = 0, $size = sizeof($poll_info); $i < $size; $i++)
0770      {
0771          $poll_info[$i]['poll_option_text'] = censor_text($poll_info[$i]['poll_option_text']);
0772   
0773          if ($poll_bbcode !== false)
0774          {
0775              $poll_bbcode->bbcode_second_pass($poll_info[$i]['poll_option_text'], $poll_info[$i]['bbcode_uid'], $poll_option['bbcode_bitfield']);
0776          }
0777   
0778          $poll_info[$i]['poll_option_text'] = bbcode_nl2br($poll_info[$i]['poll_option_text']);
0779          $poll_info[$i]['poll_option_text'] = smiley_text($poll_info[$i]['poll_option_text']);
0780      }
0781   
0782      $topic_data['poll_title'] = censor_text($topic_data['poll_title']);
0783   
0784      if ($poll_bbcode !== false)
0785      {
0786          $poll_bbcode->bbcode_second_pass($topic_data['poll_title'], $poll_info[0]['bbcode_uid'], $poll_info[0]['bbcode_bitfield']);
0787      }
0788   
0789      $topic_data['poll_title'] = bbcode_nl2br($topic_data['poll_title']);
0790      $topic_data['poll_title'] = smiley_text($topic_data['poll_title']);
0791   
0792      unset($poll_bbcode);
0793   
0794      foreach ($poll_info as $poll_option)
0795      {
0796          $option_pct = ($poll_total > 0) ? $poll_option['poll_option_total'] / $poll_total : 0;
0797          $option_pct_txt = sprintf("%.1d%%", ($option_pct * 100));
0798   
0799          $template->assign_block_vars('poll_option', array(
0800              'POLL_OPTION_ID'         => $poll_option['poll_option_id'],
0801              'POLL_OPTION_CAPTION'     => $poll_option['poll_option_text'],
0802              'POLL_OPTION_RESULT'     => $poll_option['poll_option_total'],
0803              'POLL_OPTION_PERCENT'     => $option_pct_txt,
0804              'POLL_OPTION_PCT'        => round($option_pct * 100),
0805              'POLL_OPTION_IMG'         => $user->img('poll_center', $option_pct_txt, round($option_pct * 250)),
0806              'POLL_OPTION_VOTED'        => (in_array($poll_option['poll_option_id'], $cur_voted_id)) ? true : false)
0807          );
0808      }
0809   
0810      $poll_end = $topic_data['poll_length'] + $topic_data['poll_start'];
0811   
0812      $template->assign_vars(array(
0813          'POLL_QUESTION'        => $topic_data['poll_title'],
0814          'TOTAL_VOTES'         => $poll_total,
0815          'POLL_LEFT_CAP_IMG'    => $user->img('poll_left'),
0816          'POLL_RIGHT_CAP_IMG'=> $user->img('poll_right'),
0817   
0818          'L_MAX_VOTES'        => ($topic_data['poll_max_options'] == 1) ? $user->lang['MAX_OPTION_SELECT'] : sprintf($user->lang['MAX_OPTIONS_SELECT'], $topic_data['poll_max_options']),
0819          'L_POLL_LENGTH'        => ($topic_data['poll_length']) ? sprintf($user->lang[($poll_end > time()) ? 'POLL_RUN_TILL' : 'POLL_ENDED_AT'], $user->format_date($poll_end)) : '',
0820   
0821          'S_HAS_POLL'        => true,
0822          'S_CAN_VOTE'        => $s_can_vote,
0823          'S_DISPLAY_RESULTS'    => $s_display_results,
0824          'S_IS_MULTI_CHOICE'    => ($topic_data['poll_max_options'] > 1) ? true : false,
0825          'S_POLL_ACTION'        => $viewtopic_url,
0826   
0827          'U_VIEW_RESULTS'    => $viewtopic_url . '&amp;view=viewpoll')
0828      );
0829   
0830      unset($poll_end, $poll_info, $voted_id);
0831  }
0832   
0833  // If the user is trying to reach the second half of the topic, fetch it starting from the end
0834  $store_reverse = false;
0835  $sql_limit = $config['posts_per_page'];
0836   
0837  if ($start > $total_posts / 2)
0838  {
0839      $store_reverse = true;
0840   
0841      if ($start + $config['posts_per_page'] > $total_posts)
0842      {
0843          $sql_limit = min($config['posts_per_page'], max(1, $total_posts - $start));
0844      }
0845   
0846      // Select the sort order
0847      $sql_sort_order = $sort_by_sql[$sort_key] . ' ' . (($sort_dir == 'd') ? 'ASC' : 'DESC');
0848      $sql_start = max(0, $total_posts - $sql_limit - $start);
0849  }
0850  else
0851  {
0852      // Select the sort order
0853      $sql_sort_order = $sort_by_sql[$sort_key] . ' ' . (($sort_dir == 'd') ? 'DESC' : 'ASC');
0854      $sql_start = $start;
0855  }
0856   
0857  // Container for user details, only process once
0858  $post_list = $user_cache = $id_cache = $attachments = $attach_list = $rowset = $update_count = $post_edit_list = array();
0859  $has_attachments = $display_notice = false;
0860  $bbcode_bitfield = '';
0861  $i = $i_total = 0;
0862   
0863  // Go ahead and pull all data for this topic
0864  $sql = 'SELECT p.post_id
0865      FROM ' . POSTS_TABLE . ' p' . (($sort_by_sql[$sort_key][0] == 'u') ? ', ' . USERS_TABLE . ' u': '') . "
0866      WHERE p.topic_id = $topic_id
0867          " . ((!$auth->acl_get('m_approve', $forum_id)) ? 'AND p.post_approved = 1' : '') . "
0868          " . (($sort_by_sql[$sort_key][0] == 'u') ? 'AND u.user_id = p.poster_id': '') . "
0869          $limit_posts_time
0870      ORDER BY $sql_sort_order";
0871  $result = $db->sql_query_limit($sql, $sql_limit, $sql_start);
0872   
0873  $i = ($store_reverse) ? $sql_limit - 1 : 0;
0874  while ($row = $db->sql_fetchrow($result))
0875  {
0876      $post_list[$i] = $row['post_id'];
0877      ($store_reverse) ? $i-- : $i++;
0878  }
0879  $db->sql_freeresult($result);
0880   
0881  if (!sizeof($post_list))
0882  {
0883      if ($sort_days)
0884      {
0885          trigger_error('NO_POSTS_TIME_FRAME');
0886      }
0887      else
0888      {
0889          trigger_error('NO_TOPIC');
0890      }
0891  }
0892   
0893  // Holding maximum post time for marking topic read
0894  // We need to grab it because we do reverse ordering sometimes
0895  $max_post_time = 0;
0896   
0897  $sql = $db->sql_build_query('SELECT', array(
0898      'SELECT'    => 'u.*, z.friend, z.foe, p.*',
0899   
0900      'FROM'        => array(
0901          USERS_TABLE        => 'u',
0902          POSTS_TABLE        => 'p',
0903      ),
0904   
0905      'LEFT_JOIN'    => array(
0906          array(
0907              'FROM'    => array(ZEBRA_TABLE => 'z'),
0908              'ON'    => 'z.user_id = ' . $user->data['user_id'] . ' AND z.zebra_id = p.poster_id'
0909          )
0910      ),
0911   
0912      'WHERE'        => $db->sql_in_set('p.post_id', $post_list) . '
0913          AND u.user_id = p.poster_id'
0914  ));
0915   
0916  $result = $db->sql_query($sql);
0917   
0918  $now = getdate(time() + $user->timezone + $user->dst - date('Z'));
0919   
0920  // Posts are stored in the $rowset array while $attach_list, $user_cache
0921  // and the global bbcode_bitfield are built
0922  while ($row = $db->sql_fetchrow($result))
0923  {
0924      // Set max_post_time
0925      if ($row['post_time'] > $max_post_time)
0926      {
0927          $max_post_time = $row['post_time'];
0928      }
0929   
0930      $poster_id = $row['poster_id'];
0931   
0932      // Does post have an attachment? If so, add it to the list
0933      if ($row['post_attachment'] && $config['allow_attachments'])
0934      {
0935          $attach_list[] = $row['post_id'];
0936   
0937          if ($row['post_approved'])
0938          {
0939              $has_attachments = true;
0940          }
0941      }
0942   
0943      $rowset[$row['post_id']] = array(
0944          'hide_post'            => ($row['foe'] && ($view != 'show' || $post_id != $row['post_id'])) ? true : false,
0945   
0946          'post_id'            => $row['post_id'],
0947          'post_time'            => $row['post_time'],
0948          'user_id'            => $row['user_id'],
0949          'username'            => $row['username'],
0950          'user_colour'        => $row['user_colour'],
0951          'topic_id'            => $row['topic_id'],
0952          'forum_id'            => $row['forum_id'],
0953          'post_subject'        => $row['post_subject'],
0954          'post_edit_count'    => $row['post_edit_count'],
0955          'post_edit_time'    => $row['post_edit_time'],
0956          'post_edit_reason'    => $row['post_edit_reason'],
0957          'post_edit_user'    => $row['post_edit_user'],
0958   
0959          // Make sure the icon actually exists
0960          'icon_id'            => (isset($icons[$row['icon_id']]['img'], $icons[$row['icon_id']]['height'], $icons[$row['icon_id']]['width'])) ? $row['icon_id'] : 0,
0961          'post_attachment'    => $row['post_attachment'],
0962          'post_approved'        => $row['post_approved'],
0963          'post_reported'        => $row['post_reported'],
0964          'post_username'        => $row['post_username'],
0965          'post_text'            => $row['post_text'],
0966          'bbcode_uid'        => $row['bbcode_uid'],
0967          'bbcode_bitfield'    => $row['bbcode_bitfield'],
0968          'enable_smilies'    => $row['enable_smilies'],
0969          'enable_sig'        => $row['enable_sig'],
0970          'friend'            => $row['friend'],
0971          'foe'                => $row['foe'],
0972      );
0973   
0974      // Define the global bbcode bitfield, will be used to load bbcodes
0975      $bbcode_bitfield = $bbcode_bitfield | base64_decode($row['bbcode_bitfield']);
0976   
0977      // Is a signature attached? Are we going to display it?
0978      if ($row['enable_sig'] && $config['allow_sig'] && $user->optionget('viewsigs'))
0979      {
0980          $bbcode_bitfield = $bbcode_bitfield | base64_decode($row['user_sig_bbcode_bitfield']);
0981      }
0982   
0983      // Cache various user specific data ... so we don't have to recompute
0984      // this each time the same user appears on this page
0985      if (!isset($user_cache[$poster_id]))
0986      {
0987          if ($poster_id == ANONYMOUS)
0988          {
0989              $user_cache[$poster_id] = array(
0990                  'joined'        => '',
0991                  'posts'            => '',
0992                  'from'            => '',
0993   
0994                  'sig'                    => '',
0995                  'sig_bbcode_uid'        => '',
0996                  'sig_bbcode_bitfield'    => '',
0997   
0998                  'online'            => false,
0999                  'avatar'            => '',
1000                  'rank_title'        => '',
1001                  'rank_image'        => '',
1002                  'rank_image_src'    => '',
1003                  'sig'                => '',
1004                  'posts'                => '',
1005                  'profile'            => '',
1006                  'pm'                => '',
1007                  'email'                => '',
1008                  'www'                => '',
1009                  'icq_status_img'    => '',
1010                  'icq'                => '',
1011                  'aim'                => '',
1012                  'msn'                => '',
1013                  'yim'                => '',
1014                  'jabber'            => '',
1015                  'search'            => '',
1016                  'age'                => '',
1017   
1018                  'username'            => $row['username'],
1019                  'user_colour'        => $row['user_colour'],
1020   
1021                  'warnings'            => 0,
1022                  'allow_pm'            => 0,
1023              );
1024          }
1025          else
1026          {
1027              $user_sig = '';
1028   
1029              // We add the signature to every posters entry because enable_sig is post dependant
1030              if ($row['user_sig'] && $config['allow_sig'] && $user->optionget('viewsigs'))
1031              {
1032                  $user_sig = $row['user_sig'];
1033              }
1034   
1035              $id_cache[] = $poster_id;
1036   
1037              $user_cache[$poster_id] = array(
1038                  'joined'        => $user->format_date($row['user_regdate']),
1039                  'posts'            => $row['user_posts'],
1040                  'warnings'        => (isset($row['user_warnings'])) ? $row['user_warnings'] : 0,
1041                  'from'            => (!empty($row['user_from'])) ? $row['user_from'] : '',
1042   
1043                  'sig'                    => $user_sig,
1044                  'sig_bbcode_uid'        => (!empty($row['user_sig_bbcode_uid'])) ? $row['user_sig_bbcode_uid'] : '',
1045                  'sig_bbcode_bitfield'    => (!empty($row['user_sig_bbcode_bitfield'])) ? $row['user_sig_bbcode_bitfield'] : '',
1046   
1047                  'viewonline'    => $row['user_allow_viewonline'],
1048                  'allow_pm'        => $row['user_allow_pm'],
1049   
1050                  'avatar'        => ($user->optionget('viewavatars')) ? get_user_avatar($row['user_avatar'], $row['user_avatar_type'], $row['user_avatar_width'], $row['user_avatar_height']) : '',
1051                  'age'            => '',
1052   
1053                  'rank_title'        => '',
1054                  'rank_image'        => '',
1055                  'rank_image_src'    => '',
1056   
1057                  'username'            => $row['username'],
1058                  'user_colour'        => $row['user_colour'],
1059   
1060                  'online'        => false,
1061                  'profile'        => append_sid("{$phpbb_root_path}memberlist.$phpEx", "mode=viewprofile&amp;u=$poster_id"),
1062                  'www'            => $row['user_website'],
1063                  'aim'            => ($row['user_aim'] && $auth->acl_get('u_sendim')) ? append_sid("{$phpbb_root_path}memberlist.$phpEx", "mode=contact&amp;action=aim&amp;u=$poster_id") : '',
1064                  'msn'            => ($row['user_msnm'] && $auth->acl_get('u_sendim')) ? append_sid("{$phpbb_root_path}memberlist.$phpEx", "mode=contact&amp;action=msnm&amp;u=$poster_id") : '',
1065                  'yim'            => ($row['user_yim']) ? 'http://edit.yahoo.com/config/send_webmesg?.target=' . urlencode($row['user_yim']) . '&amp;.src=pg' : '',
1066                  'jabber'        => ($row['user_jabber'] && $auth->acl_get('u_sendim')) ? append_sid("{$phpbb_root_path}memberlist.$phpEx", "mode=contact&amp;action=jabber&amp;u=$poster_id") : '',
1067                  'search'        => ($auth->acl_get('u_search')) ? append_sid("{$phpbb_root_path}search.$phpEx", 'search_author=' . urlencode($row['username']) .'&amp;showresults=posts') : '',
1068              );
1069   
1070              get_user_rank($row['user_rank'], $row['user_posts'], $user_cache[$poster_id]['rank_title'], $user_cache[$poster_id]['rank_image'], $user_cache[$poster_id]['rank_image_src']);
1071   
1072              if (!empty($row['user_allow_viewemail']) || $auth->acl_get('a_email'))
1073              {
1074                  $user_cache[$poster_id]['email'] = ($config['board_email_form'] && $config['email_enable']) ? append_sid("{$phpbb_root_path}memberlist.$phpEx", "mode=email&amp;u=$poster_id") : (($config['board_hide_emails'] && !$auth->acl_get('a_email')) ? '' : 'mailto:' . $row['user_email']);
1075              }
1076              else
1077              {
1078                  $user_cache[$poster_id]['email'] = '';
1079              }
1080   
1081              if (!empty($row['user_icq']))
1082              {
1083                  $user_cache[$poster_id]['icq'] = 'http://www.icq.com/people/webmsg.php?to=' . $row['user_icq'];
1084                  $user_cache[$poster_id]['icq_status_img'] = '<img src="http://web.icq.com/whitepages/online?icq=' . $row['user_icq'] . '&amp;img=5" width="18" height="18" alt="" />';
1085              }
1086              else
1087              {
1088                  $user_cache[$poster_id]['icq_status_img'] = '';
1089                  $user_cache[$poster_id]['icq'] = '';
1090              }
1091   
1092              if ($config['allow_birthdays'] && !empty($row['user_birthday']))
1093              {
1094                  list($bday_day, $bday_month, $bday_year) = array_map('intval', explode('-', $row['user_birthday']));
1095   
1096                  if ($bday_year)
1097                  {
1098                      $diff = $now['mon'] - $bday_month;
1099                      if ($diff == 0)
1100                      {
1101                          $diff = ($now['mday'] - $bday_day < 0) ? 1 : 0;
1102                      }
1103                      else
1104                      {
1105                          $diff = ($diff < 0) ? 1 : 0;
1106                      }
1107   
1108                      $user_cache[$poster_id]['age'] = (int) ($now['year'] - $bday_year - $diff);
1109                  }
1110              }
1111          }
1112      }
1113  }
1114  $db->sql_freeresult($result);
1115   
1116  // Load custom profile fields
1117  if ($config['load_cpf_viewtopic'])
1118  {
1119      include($phpbb_root_path . 'includes/functions_profile_fields.' . $phpEx);
1120      $cp = new custom_profile();
1121   
1122      // Grab all profile fields from users in id cache for later use - similar to the poster cache
1123      $profile_fields_cache = $cp->generate_profile_fields_template('grab', $id_cache);
1124  }
1125   
1126  // Generate online information for user
1127  if ($config['load_onlinetrack'] && sizeof($id_cache))
1128  {
1129      $sql = 'SELECT session_user_id, MAX(session_time) as online_time, MIN(session_viewonline) AS viewonline
1130          FROM ' . SESSIONS_TABLE . '
1131          WHERE ' . $db->sql_in_set('session_user_id', $id_cache) . '
1132          GROUP BY session_user_id';
1133      $result = $db->sql_query($sql);
1134   
1135      $update_time = $config['load_online_time'] * 60;
1136      while ($row = $db->sql_fetchrow($result))
1137      {
1138          $user_cache[$row['session_user_id']]['online'] = (time() - $update_time < $row['online_time'] && (($row['viewonline']) || $auth->acl_get('u_viewonline'))) ? true : false;
1139      }
1140      $db->sql_freeresult($result);
1141  }
1142  unset($id_cache);
1143   
1144  // Pull attachment data
1145  if (sizeof($attach_list))
1146  {
1147      if ($auth->acl_get('u_download') && $auth->acl_get('f_download', $forum_id))
1148      {
1149          $sql = 'SELECT *
1150              FROM ' . ATTACHMENTS_TABLE . '
1151              WHERE ' . $db->sql_in_set('post_msg_id', $attach_list) . '
1152                  AND in_message = 0
1153              ORDER BY filetime DESC, post_msg_id ASC';
1154          $result = $db->sql_query($sql);
1155   
1156          while ($row = $db->sql_fetchrow($result))
1157          {
1158              $attachments[$row['post_msg_id']][] = $row;
1159          }
1160          $db->sql_freeresult($result);
1161   
1162          // No attachments exist, but post table thinks they do so go ahead and reset post_attach flags
1163          if (!sizeof($attachments))
1164          {
1165              $sql = 'UPDATE ' . POSTS_TABLE . '
1166                  SET post_attachment = 0
1167                  WHERE ' . $db->sql_in_set('post_id', $attach_list);
1168              $db->sql_query($sql);
1169   
1170              // We need to update the topic indicator too if the complete topic is now without an attachment
1171              if (sizeof($rowset) != $total_posts)
1172              {
1173                  // Not all posts are displayed so we query the db to find if there's any attachment for this topic
1174                  $sql = 'SELECT a.post_msg_id as post_id
1175                      FROM ' . ATTACHMENTS_TABLE . ' a, ' . POSTS_TABLE . " p
1176                      WHERE p.topic_id = $topic_id
1177                          AND p.post_approved = 1
1178                          AND p.topic_id = a.topic_id";
1179                  $result = $db->sql_query_limit($sql, 1);
1180                  $row = $db->sql_fetchrow($result);
1181                  $db->sql_freeresult($result);
1182   
1183                  if (!$row)
1184                  {
1185                      $sql = 'UPDATE ' . TOPICS_TABLE . "
1186                          SET topic_attachment = 0
1187                          WHERE topic_id = $topic_id";
1188                      $db->sql_query($sql);
1189                  }
1190              }
1191              else
1192              {
1193                  $sql = 'UPDATE ' . TOPICS_TABLE . "
1194                      SET topic_attachment = 0
1195                      WHERE topic_id = $topic_id";
1196                  $db->sql_query($sql);
1197              }
1198          }
1199          else if ($has_attachments && !$topic_data['topic_attachment'])
1200          {
1201              // Topic has approved attachments but its flag is wrong
1202              $sql = 'UPDATE ' . TOPICS_TABLE . "
1203                  SET topic_attachment = 1
1204                  WHERE topic_id = $topic_id";
1205              $db->sql_query($sql);
1206   
1207              $topic_data['topic_attachment'] = 1;
1208          }
1209      }
1210      else
1211      {
1212          $display_notice = true;
1213      }
1214  }
1215   
1216  // Instantiate BBCode if need be
1217  if ($bbcode_bitfield !== '')
1218  {
1219      $bbcode = new bbcode(base64_encode($bbcode_bitfield));
1220  }
1221   
1222  $i_total = sizeof($rowset) - 1;
1223  $prev_post_id = '';
1224   
1225  $template->assign_vars(array(
1226      'S_NUM_POSTS' => sizeof($post_list))
1227  );
1228   
1229  // Output the posts
1230  $first_unread = $post_unread = false;
1231  for ($i = 0, $end = sizeof($post_list); $i < $end; ++$i)
1232  {
1233      // A non-existing rowset only happens if there was no user present for the entered poster_id
1234      // This could be a broken posts table.
1235      if (!isset($rowset[$post_list[$i]]))
1236      {
1237          continue;
1238      }
1239   
1240      $row =& $rowset[$post_list[$i]];
1241      $poster_id = $row['user_id'];
1242   
1243      // End signature parsing, only if needed
1244      if ($user_cache[$poster_id]['sig'] && $row['enable_sig'] && empty($user_cache[$poster_id]['sig_parsed']))
1245      {
1246          $user_cache[$poster_id]['sig'] = censor_text($user_cache[$poster_id]['sig']);
1247   
1248          if ($user_cache[$poster_id]['sig_bbcode_bitfield'])
1249          {
1250              $bbcode->bbcode_second_pass($user_cache[$poster_id]['sig'], $user_cache[$poster_id]['sig_bbcode_uid'], $user_cache[$poster_id]['sig_bbcode_bitfield']);
1251          }
1252   
1253          $user_cache[$poster_id]['sig'] = bbcode_nl2br($user_cache[$poster_id]['sig']);
1254          $user_cache[$poster_id]['sig'] = smiley_text($user_cache[$poster_id]['sig']);
1255          $user_cache[$poster_id]['sig_parsed'] = true;
1256      }
1257   
1258      // Parse the message and subject
1259      $message = censor_text($row['post_text']);
1260   
1261      // Second parse bbcode here
1262      if ($row['bbcode_bitfield'])
1263      {
1264          $bbcode->bbcode_second_pass($message, $row['bbcode_uid'], $row['bbcode_bitfield']);
1265      }
1266   
1267      $message = bbcode_nl2br($message);
1268      $message = smiley_text($message);
1269   
1270      if (!empty($attachments[$row['post_id']]))
1271      {
1272          parse_attachments($forum_id, $message, $attachments[$row['post_id']], $update_count);
1273      }
1274   
1275      // Replace naughty words such as farty pants
1276      $row['post_subject'] = censor_text($row['post_subject']);
1277   
1278      // Highlight active words (primarily for search)
1279      if ($highlight_match)
1280      {
1281          $message = preg_replace('#(?!<.*)(?<!\w)(' . $highlight_match . ')(?!\w|[^<>]*(?:</s(?:cript|tyle))?>)#is', '<span class="posthilit">\1</span>', $message);
1282          $row['post_subject'] = preg_replace('#(?!<.*)(?<!\w)(' . $highlight_match . ')(?!\w|[^<>]*(?:</s(?:cript|tyle))?>)#is', '<span class="posthilit">\1</span>', $row['post_subject']);
1283      }
1284   
1285      // Editing information
1286      if (($row['post_edit_count'] && $config['display_last_edited']) || $row['post_edit_reason'])
1287      {
1288          // Get usernames for all following posts if not already stored
1289          if (!sizeof($post_edit_list) && ($row['post_edit_reason'] || ($row['post_edit_user'] && !isset($user_cache[$row['post_edit_user']]))))
1290          {
1291              // Remove all post_ids already parsed (we do not have to check them)
1292              $post_storage_list = (!$store_reverse) ? array_slice($post_list, $i) : array_slice(array_reverse($post_list), $i);
1293   
1294              $sql = 'SELECT DISTINCT u.user_id, u.username, u.user_colour
1295                  FROM ' . POSTS_TABLE . ' p, ' . USERS_TABLE . ' u
1296                  WHERE ' . $db->sql_in_set('p.post_id', $post_storage_list) . '
1297                      AND p.post_edit_count <> 0
1298                      AND p.post_edit_user <> 0
1299                      AND p.post_edit_user = u.user_id';
1300              $result2 = $db->sql_query($sql);
1301              while ($user_edit_row = $db->sql_fetchrow($result2))
1302              {
1303                  $post_edit_list[$user_edit_row['user_id']] = $user_edit_row;
1304              }
1305              $db->sql_freeresult($result2);
1306   
1307              unset($post_storage_list);
1308          }
1309   
1310          $l_edit_time_total = ($row['post_edit_count'] == 1) ? $user->lang['EDITED_TIME_TOTAL'] : $user->lang['EDITED_TIMES_TOTAL'];
1311   
1312          if ($row['post_edit_reason'])
1313          {
1314              // User having edited the post also being the post author?
1315              if (!$row['post_edit_user'] || $row['post_edit_user'] == $poster_id)
1316              {
1317                  $display_username = get_username_string('full', $poster_id, $row['username'], $row['user_colour'], $row['post_username']);
1318              }
1319              else
1320              {
1321                  $display_username = get_username_string('full', $row['post_edit_user'], $post_edit_list[$row['post_edit_user']]['username'], $post_edit_list[$row['post_edit_user']]['user_colour']);
1322              }
1323   
1324              $l_edited_by = sprintf($l_edit_time_total, $display_username, $user->format_date($row['post_edit_time']), $row['post_edit_count']);
1325          }
1326          else
1327          {
1328              if ($row['post_edit_user'] && !isset($user_cache[$row['post_edit_user']]))
1329              {
1330                  $user_cache[$row['post_edit_user']] = $post_edit_list[$row['post_edit_user']];
1331              }
1332   
1333              // User having edited the post also being the post author?
1334              if (!$row['post_edit_user'] || $row['post_edit_user'] == $poster_id)
1335              {
1336                  $display_username = get_username_string('full', $poster_id, $row['username'], $row['user_colour'], $row['post_username']);
1337              }
1338              else
1339              {
1340                  $display_username = get_username_string('full', $row['post_edit_user'], $user_cache[$row['post_edit_user']]['username'], $user_cache[$row['post_edit_user']]['user_colour']);
1341              }
1342   
1343              $l_edited_by = sprintf($l_edit_time_total, $display_username, $user->format_date($row['post_edit_time']), $row['post_edit_count']);
1344          }
1345      }
1346      else
1347      {
1348          $l_edited_by = '';
1349      }
1350   
1351      // Bump information
1352      if ($topic_data['topic_bumped'] && $row['post_id'] == $topic_data['topic_last_post_id'] && isset($user_cache[$topic_data['topic_bumper']]) )
1353      {
1354          // It is safe to grab the username from the user cache array, we are at the last
1355          // post and only the topic poster and last poster are allowed to bump.
1356          // Admins and mods are bound to the above rules too...
1357          $l_bumped_by = '<br /><br />' . sprintf($user->lang['BUMPED_BY'], $user_cache[$topic_data['topic_bumper']]['username'], $user->format_date($topic_data['topic_last_post_time']));
1358      }
1359      else
1360      {
1361          $l_bumped_by = '';
1362      }
1363   
1364      $cp_row = array();
1365   
1366      //
1367      if ($config['load_cpf_viewtopic'])
1368      {
1369          $cp_row = (isset($profile_fields_cache[$poster_id])) ? $cp->generate_profile_fields_template('show', false, $profile_fields_cache[$poster_id]) : array();
1370      }
1371   
1372      $post_unread = (isset($topic_tracking_info[$topic_id]) && $row['post_time'] > $topic_tracking_info[$topic_id]) ? true : false;
1373   
1374      $s_first_unread = false;
1375      if (!$first_unread && $post_unread)
1376      {
1377          $s_first_unread = $first_unread = true;
1378      }
1379   
1380      //
1381      $postrow = array(
1382          'POST_AUTHOR_FULL'        => get_username_string('full', $poster_id, $row['username'], $row['user_colour'], $row['post_username']),
1383          'POST_AUTHOR_COLOUR'    => get_username_string('colour', $poster_id, $row['username'], $row['user_colour'], $row['post_username']),
1384          'POST_AUTHOR'            => get_username_string('username', $poster_id, $row['username'], $row['user_colour'], $row['post_username']),
1385          'U_POST_AUTHOR'            => get_username_string('profile', $poster_id, $row['username'], $row['user_colour'], $row['post_username']),
1386   
1387          'RANK_TITLE'        => $user_cache[$poster_id]['rank_title'],
1388          'RANK_IMG'            => $user_cache[$poster_id]['rank_image'],
1389          'RANK_IMG_SRC'        => $user_cache[$poster_id]['rank_image_src'],
1390          'POSTER_JOINED'        => $user_cache[$poster_id]['joined'],
1391          'POSTER_POSTS'        => $user_cache[$poster_id]['posts'],
1392          'POSTER_FROM'        => $user_cache[$poster_id]['from'],
1393          'POSTER_AVATAR'        => $user_cache[$poster_id]['avatar'],
1394          'POSTER_WARNINGS'    => $user_cache[$poster_id]['warnings'],
1395          'POSTER_AGE'        => $user_cache[$poster_id]['age'],
1396   
1397          'POST_DATE'            => $user->format_date($row['post_time']),
1398          'POST_SUBJECT'        => $row['post_subject'],
1399          'MESSAGE'            => $message,
1400          'SIGNATURE'            => ($row['enable_sig']) ? $user_cache[$poster_id]['sig'] : '',
1401          'EDITED_MESSAGE'    => $l_edited_by,
1402          'EDIT_REASON'        => $row['post_edit_reason'],
1403          'BUMPED_MESSAGE'    => $l_bumped_by,
1404   
1405          'MINI_POST_IMG'            => ($post_unread) ? $user->img('icon_post_target_unread', 'NEW_POST') : $user->img('icon_post_target', 'POST'),
1406          'POST_ICON_IMG'            => ($topic_data['enable_icons'] && !empty($row['icon_id'])) ? $icons[$row['icon_id']]['img'] : '',
1407          'POST_ICON_IMG_WIDTH'    => ($topic_data['enable_icons'] && !empty($row['icon_id'])) ? $icons[$row['icon_id']]['width'] : '',
1408          'POST_ICON_IMG_HEIGHT'    => ($topic_data['enable_icons'] && !empty($row['icon_id'])) ? $icons[$row['icon_id']]['height'] : '',
1409          'ICQ_STATUS_IMG'        => $user_cache[$poster_id]['icq_status_img'],
1410          'ONLINE_IMG'            => ($poster_id == ANONYMOUS || !$config['load_onlinetrack']) ? '' : (($user_cache[$poster_id]['online']) ? $user->img('icon_user_online', 'ONLINE') : $user->img('icon_user_offline', 'OFFLINE')),
1411          'S_ONLINE'                => ($poster_id == ANONYMOUS || !$config['load_onlinetrack']) ? false : (($user_cache[$poster_id]['online']) ? true : false),
1412   
1413          'U_EDIT'            => (!$user->data['is_registered']) ? '' : ((($user->data['user_id'] == $poster_id && $auth->acl_get('f_edit', $forum_id) && ($row['post_time'] > time() - ($config['edit_time'] * 60) || !$config['edit_time'])) || $auth->acl_get('m_edit', $forum_id)) ? append_sid("{$phpbb_root_path}posting.$phpEx", "mode=edit&amp;f=$forum_id&amp;p={$row['post_id']}") : ''),
1414          'U_QUOTE'            => ($auth->acl_get('f_reply', $forum_id)) ? append_sid("{$phpbb_root_path}posting.$phpEx", "mode=quote&amp;f=$forum_id&amp;p={$row['post_id']}") : '',
1415          'U_INFO'            => ($auth->acl_get('m_info', $forum_id)) ? append_sid("{$phpbb_root_path}mcp.$phpEx", "i=main&amp;mode=post_details&amp;f=$forum_id&amp;p=" . $row['post_id'], true, $user->session_id) : '',
1416          'U_DELETE'            => (!$user->data['is_registered']) ? '' : ((($user->data['user_id'] == $poster_id && $auth->acl_get('f_delete', $forum_id) && $topic_data['topic_last_post_id'] == $row['post_id'] && ($row['post_time'] > time() - ($config['edit_time'] * 60) || !$config['edit_time'])) || $auth->acl_get('m_delete', $forum_id)) ? append_sid("{$phpbb_root_path}posting.$phpEx", "mode=delete&amp;f=$forum_id&amp;p={$row['post_id']}") : ''),
1417   
1418          'U_PROFILE'        => $user_cache[$poster_id]['profile'],
1419          'U_SEARCH'        => $user_cache[$poster_id]['search'],
1420          'U_PM'            => ($poster_id != ANONYMOUS && $config['allow_privmsg'] && $auth->acl_get('u_sendpm') && ($user_cache[$poster_id]['allow_pm'] || $auth->acl_gets('a_', 'm_') || $auth->acl_getf_global('m_'))) ? append_sid("{$phpbb_root_path}ucp.$phpEx", 'i=pm&amp;mode=compose&amp;action=quotepost&amp;p=' . $row['post_id']) : '',
1421          'U_EMAIL'        => $user_cache[$poster_id]['email'],
1422          'U_WWW'            => $user_cache[$poster_id]['www'],
1423          'U_ICQ'            => $user_cache[$poster_id]['icq'],
1424          'U_AIM'            => $user_cache[$poster_id]['aim'],
1425          'U_MSN'            => $user_cache[$poster_id]['msn'],
1426          'U_YIM'            => $user_cache[$poster_id]['yim'],
1427          'U_JABBER'        => $user_cache[$poster_id]['jabber'],
1428   
1429          'U_REPORT'            => ($auth->acl_get('f_report', $forum_id)) ? append_sid("{$phpbb_root_path}report.$phpEx", 'f=' . $forum_id . '&amp;p=' . $row['post_id']) : '',
1430          'U_MCP_REPORT'        => ($auth->acl_get('m_report', $forum_id)) ? append_sid("{$phpbb_root_path}mcp.$phpEx", 'i=reports&amp;mode=report_details&amp;f=' . $forum_id . '&amp;p=' . $row['post_id'], true, $user->session_id) : '',
1431          'U_MCP_APPROVE'        => ($auth->acl_get('m_approve', $forum_id)) ? append_sid("{$phpbb_root_path}mcp.$phpEx", 'i=queue&amp;mode=approve_details&amp;f=' . $forum_id . '&amp;p=' . $row['post_id'], true, $user->session_id) : '',
1432          'U_MINI_POST'        => append_sid("{$phpbb_root_path}viewtopic.$phpEx", 'p=' . $row['post_id']) . (($topic_data['topic_type'] == POST_GLOBAL) ? '&amp;f=' . $forum_id : '') . '#p' . $row['post_id'],
1433          'U_NEXT_POST_ID'    => ($i < $i_total && isset($rowset[$post_list[$i + 1]])) ? $rowset[$post_list[$i + 1]]['post_id'] : '',
1434          'U_PREV_POST_ID'    => $prev_post_id,
1435          'U_NOTES'            => ($auth->acl_getf_global('m_')) ? append_sid("{$phpbb_root_path}mcp.$phpEx", 'i=notes&amp;mode=user_notes&amp;u=' . $poster_id, true, $user->session_id) : '',
1436          'U_WARN'            => ($auth->acl_get('m_warn') && $poster_id != $user->data['user_id'] && $poster_id != ANONYMOUS) ? append_sid("{$phpbb_root_path}mcp.$phpEx", 'i=warn&amp;mode=warn_post&amp;f=' . $forum_id . '&amp;p=' . $row['post_id'], true, $user->session_id) : '',
1437   
1438          'POST_ID'            => $row['post_id'],
1439          'POSTER_ID'            => $poster_id,
1440   
1441          'S_HAS_ATTACHMENTS'    => (!empty($attachments[$row['post_id']])) ? true : false,
1442          'S_POST_UNAPPROVED'    => ($row['post_approved']) ? false : true,
1443          'S_POST_REPORTED'    => ($row['post_reported'] && $auth->acl_get('m_report', $forum_id)) ? true : false,
1444          'S_DISPLAY_NOTICE'    => $display_notice && $row['post_attachment'],
1445          'S_FRIEND'            => ($row['friend']) ? true : false,
1446          'S_UNREAD_POST'        => $post_unread,
1447          'S_FIRST_UNREAD'    => $s_first_unread,
1448          'S_CUSTOM_FIELDS'    => (isset($cp_row['row']) && sizeof($cp_row['row'])) ? true : false,
1449          'S_TOPIC_POSTER'    => ($topic_data['topic_poster'] == $poster_id) ? true : false,
1450   
1451          'S_IGNORE_POST'        => ($row['hide_post']) ? true : false,
1452          'L_IGNORE_POST'        => ($row['hide_post']) ? sprintf($user->lang['POST_BY_FOE'], get_username_string('full', $poster_id, $row['username'], $row['user_colour'], $row['post_username']), '<a href="' . $viewtopic_url . "&amp;p={$row['post_id']}&amp;view=show#p{$row['post_id']}" . '">', '</a>') : '',
1453      );
1454   
1455      if (isset($cp_row['row']) && sizeof($cp_row['row']))
1456      {
1457          $postrow = array_merge($postrow, $cp_row['row']);
1458      }
1459   
1460      // Dump vars into template
1461      $template->assign_block_vars('postrow', $postrow);
1462   
1463      if (!empty($cp_row['blockrow']))
1464      {
1465          foreach ($cp_row['blockrow'] as $field_data)
1466          {
1467              $template->assign_block_vars('postrow.custom_fields', $field_data);
1468          }
1469      }
1470   
1471      // Display not already displayed Attachments for this post, we already parsed them. ;)
1472      if (!empty($attachments[$row['post_id']]))
1473      {
1474          foreach ($attachments[$row['post_id']] as $attachment)
1475          {
1476              $template->assign_block_vars('postrow.attachment', array(
1477                  'DISPLAY_ATTACHMENT'    => $attachment)
1478              );
1479          }
1480      }
1481   
1482      $prev_post_id = $row['post_id'];
1483   
1484      unset($rowset[$post_list[$i]]);
1485      unset($attachments[$row['post_id']]);
1486  }
1487  unset($rowset, $user_cache);
1488   
1489  // Update topic view and if necessary attachment view counters ... but only if this is the first 'page view'
1490  if (isset($user->data['session_page']) && strpos($user->data['session_page'], '&t=' . $topic_id) === false)
1491  {
1492      $sql = 'UPDATE ' . TOPICS_TABLE . '
1493          SET topic_views = topic_views + 1, topic_last_view_time = ' . time() . "
1494          WHERE topic_id = $topic_id";
1495      $db->sql_query($sql);
1496   
1497      // Update the attachment download counts
1498      if (sizeof($update_count))
1499      {
1500          $sql = 'UPDATE ' . ATTACHMENTS_TABLE . '
1501              SET download_count = download_count + 1
1502              WHERE ' . $db->sql_in_set('attach_id', array_unique($update_count));
1503          $db->sql_query($sql);
1504      }
1505  }
1506   
1507  // Only mark topic if it's currently unread. Also make sure we do not set topic tracking back if earlier pages are viewed.
1508  if (isset($topic_tracking_info[$topic_id]) && $topic_data['topic_last_post_time'] > $topic_tracking_info[$topic_id] && $max_post_time > $topic_tracking_info[$topic_id])
1509  {
1510      markread('topic', $forum_id, $topic_id, $max_post_time);
1511   
1512      // Update forum info
1513      $all_marked_read = update_forum_tracking_info($forum_id, $topic_data['forum_last_post_time'], (isset($topic_data['forum_mark_time'])) ? $topic_data['forum_mark_time'] : false, false);
1514  }
1515  else
1516  {
1517      $all_marked_read = true;
1518  }
1519   
1520  // If there are absolutely no more unread posts in this forum and unread posts shown, we can savely show the #unread link
1521  if ($all_marked_read)
1522  {
1523      if ($post_unread)
1524      {
1525          $template->assign_vars(array(
1526              'U_VIEW_UNREAD_POST'    => '#unread',
1527          ));
1528      }
1529      else if (isset($topic_tracking_info[$topic_id]) && $topic_data['topic_last_post_time'] > $topic_tracking_info[$topic_id])
1530      {
1531          $template->assign_vars(array(
1532              'U_VIEW_UNREAD_POST'    => append_sid("{$phpbb_root_path}viewtopic.$phpEx", "f=$forum_id&amp;t=$topic_id&amp;view=unread") . '#unread',
1533          ));
1534      }
1535  }
1536  else if (!$all_marked_read)
1537  {
1538      $last_page = ((floor($start / $config['posts_per_page']) + 1) == max(ceil($total_posts / $config['posts_per_page']), 1)) ? true : false;
1539   
1540      // What can happen is that we are at the last displayed page. If so, we also display the #unread link based in $post_unread
1541      if ($last_page && $post_unread)
1542      {
1543          $template->assign_vars(array(
1544              'U_VIEW_UNREAD_POST'    => '#unread',
1545          ));
1546      }
1547      else if (!$last_page)
1548      {
1549          $template->assign_vars(array(
1550              'U_VIEW_UNREAD_POST'    => append_sid("{$phpbb_root_path}viewtopic.$phpEx", "f=$forum_id&amp;t=$topic_id&amp;view=unread") . '#unread',
1551          ));
1552      }
1553  }
1554   
1555  // We overwrite $_REQUEST['f'] if there is no forum specified
1556  // to be able to display the correct online list.
1557  // One downside is that the user currently viewing this topic/post is not taken into account.
1558  if (empty($_REQUEST['f']))
1559  {
1560      $_REQUEST['f'] = $forum_id;
1561  }
1562   
1563  // Output the page
1564  page_header($user->lang['VIEW_TOPIC'] .' - ' . $topic_data['topic_title']);
1565   
1566  $template->set_filenames(array(
1567      'body' => ($view == 'print') ? 'viewtopic_print.html' : 'viewtopic_body.html')
1568  );
1569  make_jumpbox(append_sid("{$phpbb_root_path}viewforum.$phpEx"), $forum_id);
1570   
1571  page_footer();
1572   
1573  ?>