[ Index ]

PHP Cross Reference of phpBB-3.1.12-deutsch

title

Body

[close]

/ -> viewtopic.php (source)

   1  <?php
   2  /**
   3  *
   4  * This file is part of the phpBB Forum Software package.
   5  *
   6  * @copyright (c) phpBB Limited <https://www.phpbb.com>
   7  * @license GNU General Public License, version 2 (GPL-2.0)
   8  *
   9  * For full copyright and license information, please see
  10  * the docs/CREDITS.txt file.
  11  *
  12  */
  13  
  14  /**
  15  * @ignore
  16  */
  17  define('IN_PHPBB', true);
  18  $phpbb_root_path = (defined('PHPBB_ROOT_PATH')) ? PHPBB_ROOT_PATH : './';
  19  $phpEx = substr(strrchr(__FILE__, '.'), 1);
  20  include($phpbb_root_path . 'common.' . $phpEx);
  21  include($phpbb_root_path . 'includes/functions_display.' . $phpEx);
  22  include($phpbb_root_path . 'includes/bbcode.' . $phpEx);
  23  include($phpbb_root_path . 'includes/functions_user.' . $phpEx);
  24  
  25  // Start session management
  26  $user->session_begin();
  27  $auth->acl($user->data);
  28  
  29  // Initial var setup
  30  $forum_id    = request_var('f', 0);
  31  $topic_id    = request_var('t', 0);
  32  $post_id    = request_var('p', 0);
  33  $voted_id    = request_var('vote_id', array('' => 0));
  34  
  35  $voted_id = (sizeof($voted_id) > 1) ? array_unique($voted_id) : $voted_id;
  36  
  37  
  38  $start        = request_var('start', 0);
  39  $view        = request_var('view', '');
  40  
  41  $default_sort_days    = (!empty($user->data['user_post_show_days'])) ? $user->data['user_post_show_days'] : 0;
  42  $default_sort_key    = (!empty($user->data['user_post_sortby_type'])) ? $user->data['user_post_sortby_type'] : 't';
  43  $default_sort_dir    = (!empty($user->data['user_post_sortby_dir'])) ? $user->data['user_post_sortby_dir'] : 'a';
  44  
  45  $sort_days    = request_var('st', $default_sort_days);
  46  $sort_key    = request_var('sk', $default_sort_key);
  47  $sort_dir    = request_var('sd', $default_sort_dir);
  48  
  49  $update        = request_var('update', false);
  50  
  51  $pagination = $phpbb_container->get('pagination');
  52  
  53  $s_can_vote = false;
  54  /**
  55  * @todo normalize?
  56  */
  57  $hilit_words    = request_var('hilit', '', true);
  58  
  59  // Do we have a topic or post id?
  60  if (!$topic_id && !$post_id)
  61  {
  62      trigger_error('NO_TOPIC');
  63  }
  64  
  65  $phpbb_content_visibility = $phpbb_container->get('content.visibility');
  66  
  67  // Find topic id if user requested a newer or older topic
  68  if ($view && !$post_id)
  69  {
  70      if (!$forum_id)
  71      {
  72          $sql = 'SELECT forum_id
  73              FROM ' . TOPICS_TABLE . "
  74              WHERE topic_id = $topic_id";
  75          $result = $db->sql_query($sql);
  76          $forum_id = (int) $db->sql_fetchfield('forum_id');
  77          $db->sql_freeresult($result);
  78  
  79          if (!$forum_id)
  80          {
  81              trigger_error('NO_TOPIC');
  82          }
  83      }
  84  
  85      if ($view == 'unread')
  86      {
  87          // Get topic tracking info
  88          $topic_tracking_info = get_complete_topic_tracking($forum_id, $topic_id);
  89          $topic_last_read = (isset($topic_tracking_info[$topic_id])) ? $topic_tracking_info[$topic_id] : 0;
  90  
  91          $sql = 'SELECT post_id, topic_id, forum_id
  92              FROM ' . POSTS_TABLE . "
  93              WHERE topic_id = $topic_id
  94                  AND " . $phpbb_content_visibility->get_visibility_sql('post', $forum_id) . "
  95                  AND post_time > $topic_last_read
  96                  AND forum_id = $forum_id
  97              ORDER BY post_time ASC, post_id ASC";
  98          $result = $db->sql_query_limit($sql, 1);
  99          $row = $db->sql_fetchrow($result);
 100          $db->sql_freeresult($result);
 101  
 102          if (!$row)
 103          {
 104              $sql = 'SELECT topic_last_post_id as post_id, topic_id, forum_id
 105                  FROM ' . TOPICS_TABLE . '
 106                  WHERE topic_id = ' . $topic_id;
 107              $result = $db->sql_query($sql);
 108              $row = $db->sql_fetchrow($result);
 109              $db->sql_freeresult($result);
 110          }
 111  
 112          if (!$row)
 113          {
 114              // Setup user environment so we can process lang string
 115              $user->setup('viewtopic');
 116  
 117              trigger_error('NO_TOPIC');
 118          }
 119  
 120          $post_id = $row['post_id'];
 121          $topic_id = $row['topic_id'];
 122      }
 123      else if ($view == 'next' || $view == 'previous')
 124      {
 125          $sql_condition = ($view == 'next') ? '>' : '<';
 126          $sql_ordering = ($view == 'next') ? 'ASC' : 'DESC';
 127  
 128          $sql = 'SELECT forum_id, topic_last_post_time
 129              FROM ' . TOPICS_TABLE . '
 130              WHERE topic_id = ' . $topic_id;
 131          $result = $db->sql_query($sql);
 132          $row = $db->sql_fetchrow($result);
 133          $db->sql_freeresult($result);
 134  
 135          if (!$row)
 136          {
 137              $user->setup('viewtopic');
 138              // OK, the topic doesn't exist. This error message is not helpful, but technically correct.
 139              trigger_error(($view == 'next') ? 'NO_NEWER_TOPICS' : 'NO_OLDER_TOPICS');
 140          }
 141          else
 142          {
 143              $sql = 'SELECT topic_id, forum_id
 144                  FROM ' . TOPICS_TABLE . '
 145                  WHERE forum_id = ' . $row['forum_id'] . "
 146                      AND topic_moved_id = 0
 147                      AND topic_last_post_time $sql_condition {$row['topic_last_post_time']}
 148                      AND " . $phpbb_content_visibility->get_visibility_sql('topic', $row['forum_id']) . "
 149                  ORDER BY topic_last_post_time $sql_ordering, topic_last_post_id $sql_ordering";
 150              $result = $db->sql_query_limit($sql, 1);
 151              $row = $db->sql_fetchrow($result);
 152              $db->sql_freeresult($result);
 153  
 154              if (!$row)
 155              {
 156                  $sql = 'SELECT forum_style
 157                      FROM ' . FORUMS_TABLE . "
 158                      WHERE forum_id = $forum_id";
 159                  $result = $db->sql_query($sql);
 160                  $forum_style = (int) $db->sql_fetchfield('forum_style');
 161                  $db->sql_freeresult($result);
 162  
 163                  $user->setup('viewtopic', $forum_style);
 164                  trigger_error(($view == 'next') ? 'NO_NEWER_TOPICS' : 'NO_OLDER_TOPICS');
 165              }
 166              else
 167              {
 168                  $topic_id = $row['topic_id'];
 169                  $forum_id = $row['forum_id'];
 170              }
 171          }
 172      }
 173  
 174      if (isset($row) && $row['forum_id'])
 175      {
 176          $forum_id = $row['forum_id'];
 177      }
 178  }
 179  
 180  // This rather complex gaggle of code handles querying for topics but
 181  // also allows for direct linking to a post (and the calculation of which
 182  // page the post is on and the correct display of viewtopic)
 183  $sql_array = array(
 184      'SELECT'    => 't.*, f.*',
 185  
 186      'FROM'        => array(FORUMS_TABLE => 'f'),
 187  );
 188  
 189  // The FROM-Order is quite important here, else t.* columns can not be correctly bound.
 190  if ($post_id)
 191  {
 192      $sql_array['SELECT'] .= ', p.post_visibility, p.post_time, p.post_id';
 193      $sql_array['FROM'][POSTS_TABLE] = 'p';
 194  }
 195  
 196  // Topics table need to be the last in the chain
 197  $sql_array['FROM'][TOPICS_TABLE] = 't';
 198  
 199  if ($user->data['is_registered'])
 200  {
 201      $sql_array['SELECT'] .= ', tw.notify_status';
 202      $sql_array['LEFT_JOIN'] = array();
 203  
 204      $sql_array['LEFT_JOIN'][] = array(
 205          'FROM'    => array(TOPICS_WATCH_TABLE => 'tw'),
 206          'ON'    => 'tw.user_id = ' . $user->data['user_id'] . ' AND t.topic_id = tw.topic_id'
 207      );
 208  
 209      if ($config['allow_bookmarks'])
 210      {
 211          $sql_array['SELECT'] .= ', bm.topic_id as bookmarked';
 212          $sql_array['LEFT_JOIN'][] = array(
 213              'FROM'    => array(BOOKMARKS_TABLE => 'bm'),
 214              'ON'    => 'bm.user_id = ' . $user->data['user_id'] . ' AND t.topic_id = bm.topic_id'
 215          );
 216      }
 217  
 218      if ($config['load_db_lastread'])
 219      {
 220          $sql_array['SELECT'] .= ', tt.mark_time, ft.mark_time as forum_mark_time';
 221  
 222          $sql_array['LEFT_JOIN'][] = array(
 223              'FROM'    => array(TOPICS_TRACK_TABLE => 'tt'),
 224              'ON'    => 'tt.user_id = ' . $user->data['user_id'] . ' AND t.topic_id = tt.topic_id'
 225          );
 226  
 227          $sql_array['LEFT_JOIN'][] = array(
 228              'FROM'    => array(FORUMS_TRACK_TABLE => 'ft'),
 229              'ON'    => 'ft.user_id = ' . $user->data['user_id'] . ' AND t.forum_id = ft.forum_id'
 230          );
 231      }
 232  }
 233  
 234  if (!$post_id)
 235  {
 236      $sql_array['WHERE'] = "t.topic_id = $topic_id";
 237  }
 238  else
 239  {
 240      $sql_array['WHERE'] = "p.post_id = $post_id AND t.topic_id = p.topic_id";
 241  }
 242  
 243  $sql_array['WHERE'] .= ' AND f.forum_id = t.forum_id';
 244  
 245  $sql = $db->sql_build_query('SELECT', $sql_array);
 246  $result = $db->sql_query($sql);
 247  $topic_data = $db->sql_fetchrow($result);
 248  $db->sql_freeresult($result);
 249  
 250  // link to unapproved post or incorrect link
 251  if (!$topic_data)
 252  {
 253      // If post_id was submitted, we try at least to display the topic as a last resort...
 254      if ($post_id && $topic_id)
 255      {
 256          redirect(append_sid("{$phpbb_root_path}viewtopic.$phpEx", "t=$topic_id" . (($forum_id) ? "&amp;f=$forum_id" : '')));
 257      }
 258  
 259      trigger_error('NO_TOPIC');
 260  }
 261  
 262  $forum_id = (int) $topic_data['forum_id'];
 263  
 264  // Now we know the forum_id and can check the permissions
 265  if ($topic_data['topic_visibility'] != ITEM_APPROVED && !$auth->acl_get('m_approve', $forum_id))
 266  {
 267      trigger_error('NO_TOPIC');
 268  }
 269  
 270  // This is for determining where we are (page)
 271  if ($post_id)
 272  {
 273      // are we where we are supposed to be?
 274      if (($topic_data['post_visibility'] == ITEM_UNAPPROVED || $topic_data['post_visibility'] == ITEM_REAPPROVE) && !$auth->acl_get('m_approve', $topic_data['forum_id']))
 275      {
 276          // If post_id was submitted, we try at least to display the topic as a last resort...
 277          if ($topic_id)
 278          {
 279              redirect(append_sid("{$phpbb_root_path}viewtopic.$phpEx", "t=$topic_id" . (($forum_id) ? "&amp;f=$forum_id" : '')));
 280          }
 281  
 282          trigger_error('NO_TOPIC');
 283      }
 284      if ($post_id == $topic_data['topic_first_post_id'] || $post_id == $topic_data['topic_last_post_id'])
 285      {
 286          $check_sort = ($post_id == $topic_data['topic_first_post_id']) ? 'd' : 'a';
 287  
 288          if ($sort_dir == $check_sort)
 289          {
 290              $topic_data['prev_posts'] = $phpbb_content_visibility->get_count('topic_posts', $topic_data, $forum_id) - 1;
 291          }
 292          else
 293          {
 294              $topic_data['prev_posts'] = 0;
 295          }
 296      }
 297      else
 298      {
 299          $sql = 'SELECT COUNT(p.post_id) AS prev_posts
 300              FROM ' . POSTS_TABLE . " p
 301              WHERE p.topic_id = {$topic_data['topic_id']}
 302                  AND " . $phpbb_content_visibility->get_visibility_sql('post', $forum_id, 'p.');
 303  
 304          if ($sort_dir == 'd')
 305          {
 306              $sql .= " AND (p.post_time > {$topic_data['post_time']} OR (p.post_time = {$topic_data['post_time']} AND p.post_id >= {$topic_data['post_id']}))";
 307          }
 308          else
 309          {
 310              $sql .= " AND (p.post_time < {$topic_data['post_time']} OR (p.post_time = {$topic_data['post_time']} AND p.post_id <= {$topic_data['post_id']}))";
 311          }
 312  
 313          $result = $db->sql_query($sql);
 314          $row = $db->sql_fetchrow($result);
 315          $db->sql_freeresult($result);
 316  
 317          $topic_data['prev_posts'] = $row['prev_posts'] - 1;
 318      }
 319  }
 320  
 321  $topic_id = (int) $topic_data['topic_id'];
 322  $topic_replies = $phpbb_content_visibility->get_count('topic_posts', $topic_data, $forum_id) - 1;
 323  
 324  // Check sticky/announcement time limit
 325  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())
 326  {
 327      $sql = 'UPDATE ' . TOPICS_TABLE . '
 328          SET topic_type = ' . POST_NORMAL . ', topic_time_limit = 0
 329          WHERE topic_id = ' . $topic_id;
 330      $db->sql_query($sql);
 331  
 332      $topic_data['topic_type'] = POST_NORMAL;
 333      $topic_data['topic_time_limit'] = 0;
 334  }
 335  
 336  // Setup look and feel
 337  $user->setup('viewtopic', $topic_data['forum_style']);
 338  
 339  $overrides_f_read_check = false;
 340  $overrides_forum_password_check = false;
 341  $topic_tracking_info = isset($topic_tracking_info) ? $topic_tracking_info : null;
 342  
 343  /**
 344  * Event to apply extra permissions and to override original phpBB's f_read permission and forum password check
 345  * on viewtopic access
 346  *
 347  * @event core.viewtopic_before_f_read_check
 348  * @var    int        forum_id                        The forum id from where the topic belongs
 349  * @var    int        topic_id                        The id of the topic the user tries to access
 350  * @var    int        post_id                            The id of the post the user tries to start viewing at.
 351  *                                                It may be 0 for none given.
 352  * @var    array    topic_data                        All the information from the topic and forum tables for this topic
 353  *                                                 It includes posts information if post_id is not 0
 354  * @var    bool    overrides_f_read_check            Set true to remove f_read check afterwards
 355  * @var    bool    overrides_forum_password_check    Set true to remove forum_password check afterwards
 356  * @var    array    topic_tracking_info                Information upon calling get_topic_tracking()
 357  *                                                Set it to NULL to allow auto-filling later.
 358  *                                                Set it to an array to override original data.
 359  * @since 3.1.3-RC1
 360  */
 361  $vars = array(
 362      'forum_id',
 363      'topic_id',
 364      'post_id',
 365      'topic_data',
 366      'overrides_f_read_check',
 367      'overrides_forum_password_check',
 368      'topic_tracking_info',
 369  );
 370  extract($phpbb_dispatcher->trigger_event('core.viewtopic_before_f_read_check', compact($vars)));
 371  
 372  // Start auth check
 373  if (!$overrides_f_read_check && !$auth->acl_get('f_read', $forum_id))
 374  {
 375      if ($user->data['user_id'] != ANONYMOUS)
 376      {
 377          trigger_error('SORRY_AUTH_READ');
 378      }
 379  
 380      login_box('', $user->lang['LOGIN_VIEWFORUM']);
 381  }
 382  
 383  // Forum is passworded ... check whether access has been granted to this
 384  // user this session, if not show login box
 385  if (!$overrides_forum_password_check && $topic_data['forum_password'])
 386  {
 387      login_forum_box($topic_data);
 388  }
 389  
 390  // Redirect to login upon emailed notification links if user is not logged in.
 391  if (isset($_GET['e']) && $user->data['user_id'] == ANONYMOUS)
 392  {
 393      login_box(build_url('e') . '#unread', $user->lang['LOGIN_NOTIFY_TOPIC']);
 394  }
 395  
 396  // What is start equal to?
 397  if ($post_id)
 398  {
 399      $start = floor(($topic_data['prev_posts']) / $config['posts_per_page']) * $config['posts_per_page'];
 400  }
 401  
 402  // Get topic tracking info
 403  if (!isset($topic_tracking_info))
 404  {
 405      $topic_tracking_info = array();
 406  
 407      // Get topic tracking info
 408      if ($config['load_db_lastread'] && $user->data['is_registered'])
 409      {
 410          $tmp_topic_data = array($topic_id => $topic_data);
 411          $topic_tracking_info = get_topic_tracking($forum_id, $topic_id, $tmp_topic_data, array($forum_id => $topic_data['forum_mark_time']));
 412          unset($tmp_topic_data);
 413      }
 414      else if ($config['load_anon_lastread'] || $user->data['is_registered'])
 415      {
 416          $topic_tracking_info = get_complete_topic_tracking($forum_id, $topic_id);
 417      }
 418  }
 419  
 420  // Post ordering options
 421  $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']);
 422  
 423  $sort_by_text = array('a' => $user->lang['AUTHOR'], 't' => $user->lang['POST_TIME'], 's' => $user->lang['SUBJECT']);
 424  $sort_by_sql = array('a' => array('u.username_clean', 'p.post_id'), 't' => array('p.post_time', 'p.post_id'), 's' => array('p.post_subject', 'p.post_id'));
 425  $join_user_sql = array('a' => true, 't' => false, 's' => false);
 426  
 427  $s_limit_days = $s_sort_key = $s_sort_dir = $u_sort_param = '';
 428  
 429  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, $default_sort_days, $default_sort_key, $default_sort_dir);
 430  
 431  // Obtain correct post count and ordering SQL if user has
 432  // requested anything different
 433  if ($sort_days)
 434  {
 435      $min_post_time = time() - ($sort_days * 86400);
 436  
 437      $sql = 'SELECT COUNT(post_id) AS num_posts
 438          FROM ' . POSTS_TABLE . "
 439          WHERE topic_id = $topic_id
 440              AND post_time >= $min_post_time
 441                  AND " . $phpbb_content_visibility->get_visibility_sql('post', $forum_id);
 442      $result = $db->sql_query($sql);
 443      $total_posts = (int) $db->sql_fetchfield('num_posts');
 444      $db->sql_freeresult($result);
 445  
 446      $limit_posts_time = "AND p.post_time >= $min_post_time ";
 447  
 448      if (isset($_POST['sort']))
 449      {
 450          $start = 0;
 451      }
 452  }
 453  else
 454  {
 455      $total_posts = $topic_replies + 1;
 456      $limit_posts_time = '';
 457  }
 458  
 459  // Was a highlight request part of the URI?
 460  $highlight_match = $highlight = '';
 461  if ($hilit_words)
 462  {
 463      $highlight_match = phpbb_clean_search_string($hilit_words);
 464      $highlight = urlencode($highlight_match);
 465      $highlight_match = str_replace('\*', '\w+?', preg_quote($highlight_match, '#'));
 466      $highlight_match = preg_replace('#(?<=^|\s)\\\\w\*\?(?=\s|$)#', '\w+?', $highlight_match);
 467      $highlight_match = str_replace(' ', '|', $highlight_match);
 468  }
 469  
 470  // Make sure $start is set to the last page if it exceeds the amount
 471  $start = $pagination->validate_start($start, $config['posts_per_page'], $total_posts);
 472  
 473  // General Viewtopic URL for return links
 474  $viewtopic_url = append_sid("{$phpbb_root_path}viewtopic.$phpEx", "f=$forum_id&amp;t=$topic_id" . (($start == 0) ? '' : "&amp;start=$start") . ((strlen($u_sort_param)) ? "&amp;$u_sort_param" : '') . (($highlight_match) ? "&amp;hilit=$highlight" : ''));
 475  
 476  // Are we watching this topic?
 477  $s_watching_topic = array(
 478      'link'            => '',
 479      'link_toggle'    => '',
 480      'title'            => '',
 481      'title_toggle'    => '',
 482      'is_watching'    => false,
 483  );
 484  
 485  if ($config['allow_topic_notify'])
 486  {
 487      $notify_status = (isset($topic_data['notify_status'])) ? $topic_data['notify_status'] : null;
 488      watch_topic_forum('topic', $s_watching_topic, $user->data['user_id'], $forum_id, $topic_id, $notify_status, $start, $topic_data['topic_title']);
 489  
 490      // Reset forum notification if forum notify is set
 491      if ($config['allow_forum_notify'] && $auth->acl_get('f_subscribe', $forum_id))
 492      {
 493          $s_watching_forum = $s_watching_topic;
 494          watch_topic_forum('forum', $s_watching_forum, $user->data['user_id'], $forum_id, 0);
 495      }
 496  }
 497  
 498  /**
 499  * Event to modify highlight.
 500  *
 501  * @event core.viewtopic_highlight_modify
 502  * @var    string    highlight            String to be highlighted
 503  * @var    string    highlight_match        Highlight string to be used in preg_replace
 504  * @var    array    topic_data            Topic data
 505  * @var    int        start                Pagination start
 506  * @var    int        total_posts            Number of posts
 507  * @var    string    viewtopic_url        Current viewtopic URL
 508  * @since 3.1.11-RC1
 509  */
 510  $vars = array(
 511      'highlight',
 512      'highlight_match',
 513      'topic_data',
 514      'start',
 515      'total_posts',
 516      'viewtopic_url',
 517  );
 518  extract($phpbb_dispatcher->trigger_event('core.viewtopic_highlight_modify', compact($vars)));
 519  
 520  // Bookmarks
 521  if ($config['allow_bookmarks'] && $user->data['is_registered'] && request_var('bookmark', 0))
 522  {
 523      if (check_link_hash(request_var('hash', ''), "topic_$topic_id"))
 524      {
 525          if (!$topic_data['bookmarked'])
 526          {
 527              $sql = 'INSERT INTO ' . BOOKMARKS_TABLE . ' ' . $db->sql_build_array('INSERT', array(
 528                  'user_id'    => $user->data['user_id'],
 529                  'topic_id'    => $topic_id,
 530              ));
 531              $db->sql_query($sql);
 532          }
 533          else
 534          {
 535              $sql = 'DELETE FROM ' . BOOKMARKS_TABLE . "
 536                  WHERE user_id = {$user->data['user_id']}
 537                      AND topic_id = $topic_id";
 538              $db->sql_query($sql);
 539          }
 540          $message = (($topic_data['bookmarked']) ? $user->lang['BOOKMARK_REMOVED'] : $user->lang['BOOKMARK_ADDED']);
 541  
 542          if (!$request->is_ajax())
 543          {
 544              $message .= '<br /><br />' . $user->lang('RETURN_TOPIC', '<a href="' . $viewtopic_url . '">', '</a>');
 545          }
 546      }
 547      else
 548      {
 549          $message = $user->lang['BOOKMARK_ERR'];
 550  
 551          if (!$request->is_ajax())
 552          {
 553              $message .= '<br /><br />' . $user->lang('RETURN_TOPIC', '<a href="' . $viewtopic_url . '">', '</a>');
 554          }
 555      }
 556      meta_refresh(3, $viewtopic_url);
 557  
 558      trigger_error($message);
 559  }
 560  
 561  // Grab ranks
 562  $ranks = $cache->obtain_ranks();
 563  
 564  // Grab icons
 565  $icons = $cache->obtain_icons();
 566  
 567  // Grab extensions
 568  $extensions = array();
 569  if ($topic_data['topic_attachment'])
 570  {
 571      $extensions = $cache->obtain_attach_extensions($forum_id);
 572  }
 573  
 574  // Forum rules listing
 575  $s_forum_rules = '';
 576  gen_forum_auth_level('topic', $forum_id, $topic_data['forum_status']);
 577  
 578  // Quick mod tools
 579  $allow_change_type = ($auth->acl_get('m_', $forum_id) || ($user->data['is_registered'] && $user->data['user_id'] == $topic_data['topic_poster'])) ? true : false;
 580  
 581  $s_quickmod_action = append_sid(
 582      "{$phpbb_root_path}mcp.$phpEx",
 583      array(
 584          'f'    => $forum_id,
 585          't'    => $topic_id,
 586          'start'        => $start,
 587          'quickmod'    => 1,
 588          'redirect'    => urlencode(str_replace('&amp;', '&', $viewtopic_url)),
 589      ),
 590      true,
 591      $user->session_id
 592  );
 593  
 594  $quickmod_array = array(
 595  //    'key'            => array('LANG_KEY', $userHasPermissions),
 596  
 597      'lock'                    => array('LOCK_TOPIC', ($topic_data['topic_status'] == ITEM_UNLOCKED) && ($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']))),
 598      'unlock'                => array('UNLOCK_TOPIC', ($topic_data['topic_status'] != ITEM_UNLOCKED) && ($auth->acl_get('m_lock', $forum_id))),
 599      'delete_topic'        => array('DELETE_TOPIC', ($auth->acl_get('m_delete', $forum_id) || (($topic_data['topic_visibility'] != ITEM_DELETED) && $auth->acl_get('m_softdelete', $forum_id)))),
 600      'restore_topic'        => array('RESTORE_TOPIC', (($topic_data['topic_visibility'] == ITEM_DELETED) && $auth->acl_get('m_approve', $forum_id))),
 601      'move'                    => array('MOVE_TOPIC', $auth->acl_get('m_move', $forum_id) && $topic_data['topic_status'] != ITEM_MOVED),
 602      'split'                    => array('SPLIT_TOPIC', $auth->acl_get('m_split', $forum_id)),
 603      'merge'                    => array('MERGE_POSTS', $auth->acl_get('m_merge', $forum_id)),
 604      'merge_topic'        => array('MERGE_TOPIC', $auth->acl_get('m_merge', $forum_id)),
 605      'fork'                    => array('FORK_TOPIC', $auth->acl_get('m_move', $forum_id)),
 606      'make_normal'        => array('MAKE_NORMAL', ($allow_change_type && $auth->acl_gets('f_sticky', 'f_announce', $forum_id) && $topic_data['topic_type'] != POST_NORMAL)),
 607      'make_sticky'        => array('MAKE_STICKY', ($allow_change_type && $auth->acl_get('f_sticky', $forum_id) && $topic_data['topic_type'] != POST_STICKY)),
 608      'make_announce'    => array('MAKE_ANNOUNCE', ($allow_change_type && $auth->acl_get('f_announce', $forum_id) && $topic_data['topic_type'] != POST_ANNOUNCE)),
 609      'make_global'        => array('MAKE_GLOBAL', ($allow_change_type && $auth->acl_get('f_announce', $forum_id) && $topic_data['topic_type'] != POST_GLOBAL)),
 610      'topic_logs'            => array('VIEW_TOPIC_LOGS', $auth->acl_get('m_', $forum_id)),
 611  );
 612  
 613  /**
 614  * Event to modify data in the quickmod_array before it gets sent to the
 615  * phpbb_add_quickmod_option function.
 616  *
 617  * @event core.viewtopic_add_quickmod_option_before
 618  * @var    int                forum_id                Forum ID
 619  * @var    int                post_id                    Post ID
 620  * @var    array            quickmod_array            Array with quick moderation options data
 621  * @var    array            topic_data                Array with topic data
 622  * @var    int                topic_id                Topic ID
 623  * @var    array            topic_tracking_info        Array with topic tracking data
 624  * @var    string            viewtopic_url            URL to the topic page
 625  * @var    bool            allow_change_type        Topic change permissions check
 626  * @since 3.1.9-RC1
 627  */
 628  $vars = array(
 629      'forum_id',
 630      'post_id',
 631      'quickmod_array',
 632      'topic_data',
 633      'topic_id',
 634      'topic_tracking_info',
 635      'viewtopic_url',
 636      'allow_change_type',
 637  );
 638  extract($phpbb_dispatcher->trigger_event('core.viewtopic_add_quickmod_option_before', compact($vars)));
 639  
 640  foreach ($quickmod_array as $option => $qm_ary)
 641  {
 642      if (!empty($qm_ary[1]))
 643      {
 644          phpbb_add_quickmod_option($s_quickmod_action, $option, $qm_ary[0]);
 645      }
 646  }
 647  
 648  // Navigation links
 649  generate_forum_nav($topic_data);
 650  
 651  // Forum Rules
 652  generate_forum_rules($topic_data);
 653  
 654  // Moderators
 655  $forum_moderators = array();
 656  if ($config['load_moderators'])
 657  {
 658      get_moderators($forum_moderators, $forum_id);
 659  }
 660  
 661  // This is only used for print view so ...
 662  $server_path = (!$view) ? $phpbb_root_path : generate_board_url() . '/';
 663  
 664  // Replace naughty words in title
 665  $topic_data['topic_title'] = censor_text($topic_data['topic_title']);
 666  
 667  $s_search_hidden_fields = array(
 668      't' => $topic_id,
 669      'sf' => 'msgonly',
 670  );
 671  if ($_SID)
 672  {
 673      $s_search_hidden_fields['sid'] = $_SID;
 674  }
 675  
 676  if (!empty($_EXTRA_URL))
 677  {
 678      foreach ($_EXTRA_URL as $url_param)
 679      {
 680          $url_param = explode('=', $url_param, 2);
 681          $s_search_hidden_fields[$url_param[0]] = $url_param[1];
 682      }
 683  }
 684  
 685  // If we've got a hightlight set pass it on to pagination.
 686  $base_url = append_sid("{$phpbb_root_path}viewtopic.$phpEx", "f=$forum_id&amp;t=$topic_id" . ((strlen($u_sort_param)) ? "&amp;$u_sort_param" : '') . (($highlight_match) ? "&amp;hilit=$highlight" : ''));
 687  
 688  /**
 689  * Event to modify data before template variables are being assigned
 690  *
 691  * @event core.viewtopic_assign_template_vars_before
 692  * @var    string    base_url            URL to be passed to generate pagination
 693  * @var    int        forum_id            Forum ID
 694  * @var    int        post_id                Post ID
 695  * @var    array    quickmod_array        Array with quick moderation options data
 696  * @var    int        start                Pagination information
 697  * @var    array    topic_data            Array with topic data
 698  * @var    int        topic_id            Topic ID
 699  * @var    array    topic_tracking_info    Array with topic tracking data
 700  * @var    int        total_posts            Topic total posts count
 701  * @var    string    viewtopic_url        URL to the topic page
 702  * @since 3.1.0-RC4
 703  * @changed 3.1.2-RC1 Added viewtopic_url
 704  */
 705  $vars = array(
 706      'base_url',
 707      'forum_id',
 708      'post_id',
 709      'quickmod_array',
 710      'start',
 711      'topic_data',
 712      'topic_id',
 713      'topic_tracking_info',
 714      'total_posts',
 715      'viewtopic_url',
 716  );
 717  extract($phpbb_dispatcher->trigger_event('core.viewtopic_assign_template_vars_before', compact($vars)));
 718  
 719  $pagination->generate_template_pagination($base_url, 'pagination', 'start', $total_posts, $config['posts_per_page'], $start);
 720  
 721  // Send vars to template
 722  $template->assign_vars(array(
 723      'FORUM_ID'         => $forum_id,
 724      'FORUM_NAME'     => $topic_data['forum_name'],
 725      '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']),
 726      'TOPIC_ID'         => $topic_id,
 727      'TOPIC_TITLE'     => $topic_data['topic_title'],
 728      'TOPIC_POSTER'    => $topic_data['topic_poster'],
 729  
 730      'TOPIC_AUTHOR_FULL'        => get_username_string('full', $topic_data['topic_poster'], $topic_data['topic_first_poster_name'], $topic_data['topic_first_poster_colour']),
 731      'TOPIC_AUTHOR_COLOUR'    => get_username_string('colour', $topic_data['topic_poster'], $topic_data['topic_first_poster_name'], $topic_data['topic_first_poster_colour']),
 732      'TOPIC_AUTHOR'            => get_username_string('username', $topic_data['topic_poster'], $topic_data['topic_first_poster_name'], $topic_data['topic_first_poster_colour']),
 733  
 734      'TOTAL_POSTS'    => $user->lang('VIEW_TOPIC_POSTS', (int) $total_posts),
 735      '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" . (($start == 0) ? '' : "&amp;start=$start") . ((strlen($u_sort_param)) ? "&amp;$u_sort_param" : ''), true, $user->session_id) : '',
 736      'MODERATORS'    => (isset($forum_moderators[$forum_id]) && sizeof($forum_moderators[$forum_id])) ? implode($user->lang['COMMA_SEPARATOR'], $forum_moderators[$forum_id]) : '',
 737  
 738      'POST_IMG'             => ($topic_data['forum_status'] == ITEM_LOCKED) ? $user->img('button_topic_locked', 'FORUM_LOCKED') : $user->img('button_topic_new', 'POST_NEW_TOPIC'),
 739      'QUOTE_IMG'         => $user->img('icon_post_quote', 'REPLY_WITH_QUOTE'),
 740      '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'),
 741      'EDIT_IMG'             => $user->img('icon_post_edit', 'EDIT_POST'),
 742      'DELETE_IMG'         => $user->img('icon_post_delete', 'DELETE_POST'),
 743      'DELETED_IMG'        => $user->img('icon_topic_deleted', 'POST_DELETED_RESTORE'),
 744      'INFO_IMG'             => $user->img('icon_post_info', 'VIEW_INFO'),
 745      'PROFILE_IMG'        => $user->img('icon_user_profile', 'READ_PROFILE'),
 746      'SEARCH_IMG'         => $user->img('icon_user_search', 'SEARCH_USER_POSTS'),
 747      'PM_IMG'             => $user->img('icon_contact_pm', 'SEND_PRIVATE_MESSAGE'),
 748      'EMAIL_IMG'         => $user->img('icon_contact_email', 'SEND_EMAIL'),
 749      'JABBER_IMG'        => $user->img('icon_contact_jabber', 'JABBER') ,
 750      'REPORT_IMG'        => $user->img('icon_post_report', 'REPORT_POST'),
 751      'REPORTED_IMG'        => $user->img('icon_topic_reported', 'POST_REPORTED'),
 752      'UNAPPROVED_IMG'    => $user->img('icon_topic_unapproved', 'POST_UNAPPROVED'),
 753      'WARN_IMG'            => $user->img('icon_user_warn', 'WARN_USER'),
 754  
 755      'S_IS_LOCKED'            => ($topic_data['topic_status'] == ITEM_UNLOCKED && $topic_data['forum_status'] == ITEM_UNLOCKED) ? false : true,
 756      'S_SELECT_SORT_DIR'     => $s_sort_dir,
 757      'S_SELECT_SORT_KEY'     => $s_sort_key,
 758      'S_SELECT_SORT_DAYS'     => $s_limit_days,
 759      'S_SINGLE_MODERATOR'    => (!empty($forum_moderators[$forum_id]) && sizeof($forum_moderators[$forum_id]) > 1) ? false : true,
 760      'S_TOPIC_ACTION'         => append_sid("{$phpbb_root_path}viewtopic.$phpEx", "f=$forum_id&amp;t=$topic_id" . (($start == 0) ? '' : "&amp;start=$start")),
 761      'S_MOD_ACTION'             => $s_quickmod_action,
 762  
 763      'L_RETURN_TO_FORUM'        => $user->lang('RETURN_TO', $topic_data['forum_name']),
 764      'S_VIEWTOPIC'            => true,
 765      'S_UNREAD_VIEW'            => $view == 'unread',
 766      'S_DISPLAY_SEARCHBOX'    => ($auth->acl_get('u_search') && $auth->acl_get('f_search', $forum_id) && $config['load_search']) ? true : false,
 767      'S_SEARCHBOX_ACTION'    => append_sid("{$phpbb_root_path}search.$phpEx"),
 768      'S_SEARCH_LOCAL_HIDDEN_FIELDS'    => build_hidden_fields($s_search_hidden_fields),
 769  
 770      'S_DISPLAY_POST_INFO'    => ($topic_data['forum_type'] == FORUM_POST && ($auth->acl_get('f_post', $forum_id) || $user->data['user_id'] == ANONYMOUS)) ? true : false,
 771      'S_DISPLAY_REPLY_INFO'    => ($topic_data['forum_type'] == FORUM_POST && ($auth->acl_get('f_reply', $forum_id) || $user->data['user_id'] == ANONYMOUS)) ? true : false,
 772      'S_ENABLE_FEEDS_TOPIC'    => ($config['feed_topic'] && !phpbb_optionget(FORUM_OPTION_FEED_EXCLUDE, $topic_data['forum_options'])) ? true : false,
 773  
 774      'U_TOPIC'                => "{$server_path}viewtopic.$phpEx?f=$forum_id&amp;t=$topic_id",
 775      'U_FORUM'                => $server_path,
 776      'U_VIEW_TOPIC'             => $viewtopic_url,
 777      'U_CANONICAL'            => generate_board_url() . '/' . append_sid("viewtopic.$phpEx", "t=$topic_id" . (($start) ? "&amp;start=$start" : ''), true, ''),
 778      'U_VIEW_FORUM'             => append_sid("{$phpbb_root_path}viewforum.$phpEx", 'f=' . $forum_id),
 779      'U_VIEW_OLDER_TOPIC'    => append_sid("{$phpbb_root_path}viewtopic.$phpEx", "f=$forum_id&amp;t=$topic_id&amp;view=previous"),
 780      'U_VIEW_NEWER_TOPIC'    => append_sid("{$phpbb_root_path}viewtopic.$phpEx", "f=$forum_id&amp;t=$topic_id&amp;view=next"),
 781      'U_PRINT_TOPIC'            => ($auth->acl_get('f_print', $forum_id)) ? $viewtopic_url . '&amp;view=print' : '',
 782      '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") : '',
 783  
 784      'U_WATCH_TOPIC'            => $s_watching_topic['link'],
 785      'U_WATCH_TOPIC_TOGGLE'    => $s_watching_topic['link_toggle'],
 786      'S_WATCH_TOPIC_TITLE'    => $s_watching_topic['title'],
 787      'S_WATCH_TOPIC_TOGGLE'    => $s_watching_topic['title_toggle'],
 788      'S_WATCHING_TOPIC'        => $s_watching_topic['is_watching'],
 789  
 790      'U_BOOKMARK_TOPIC'        => ($user->data['is_registered'] && $config['allow_bookmarks']) ? $viewtopic_url . '&amp;bookmark=1&amp;hash=' . generate_link_hash("topic_$topic_id") : '',
 791      'S_BOOKMARK_TOPIC'        => ($user->data['is_registered'] && $config['allow_bookmarks'] && $topic_data['bookmarked']) ? $user->lang['BOOKMARK_TOPIC_REMOVE'] : $user->lang['BOOKMARK_TOPIC'],
 792      'S_BOOKMARK_TOGGLE'        => (!$user->data['is_registered'] || !$config['allow_bookmarks'] || !$topic_data['bookmarked']) ? $user->lang['BOOKMARK_TOPIC_REMOVE'] : $user->lang['BOOKMARK_TOPIC'],
 793      'S_BOOKMARKED_TOPIC'    => ($user->data['is_registered'] && $config['allow_bookmarks'] && $topic_data['bookmarked']) ? true : false,
 794  
 795      '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") : '',
 796      '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") : '',
 797      '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&amp;hash=" . generate_link_hash("topic_$topic_id")) : '')
 798  );
 799  
 800  // Does this topic contain a poll?
 801  if (!empty($topic_data['poll_start']))
 802  {
 803      $sql = 'SELECT o.*, p.bbcode_bitfield, p.bbcode_uid
 804          FROM ' . POLL_OPTIONS_TABLE . ' o, ' . POSTS_TABLE . " p
 805          WHERE o.topic_id = $topic_id
 806              AND p.post_id = {$topic_data['topic_first_post_id']}
 807              AND p.topic_id = o.topic_id
 808          ORDER BY o.poll_option_id";
 809      $result = $db->sql_query($sql);
 810  
 811      $poll_info = $vote_counts = array();
 812      while ($row = $db->sql_fetchrow($result))
 813      {
 814          $poll_info[] = $row;
 815          $option_id = (int) $row['poll_option_id'];
 816          $vote_counts[$option_id] = (int) $row['poll_option_total'];
 817      }
 818      $db->sql_freeresult($result);
 819  
 820      $cur_voted_id = array();
 821      if ($user->data['is_registered'])
 822      {
 823          $sql = 'SELECT poll_option_id
 824              FROM ' . POLL_VOTES_TABLE . '
 825              WHERE topic_id = ' . $topic_id . '
 826                  AND vote_user_id = ' . $user->data['user_id'];
 827          $result = $db->sql_query($sql);
 828  
 829          while ($row = $db->sql_fetchrow($result))
 830          {
 831              $cur_voted_id[] = $row['poll_option_id'];
 832          }
 833          $db->sql_freeresult($result);
 834      }
 835      else
 836      {
 837          // Cookie based guest tracking ... I don't like this but hum ho
 838          // it's oft requested. This relies on "nice" users who don't feel
 839          // the need to delete cookies to mess with results.
 840          if ($request->is_set($config['cookie_name'] . '_poll_' . $topic_id, \phpbb\request\request_interface::COOKIE))
 841          {
 842              $cur_voted_id = explode(',', $request->variable($config['cookie_name'] . '_poll_' . $topic_id, '', true, \phpbb\request\request_interface::COOKIE));
 843              $cur_voted_id = array_map('intval', $cur_voted_id);
 844          }
 845      }
 846  
 847      // Can not vote at all if no vote permission
 848      $s_can_vote = ($auth->acl_get('f_vote', $forum_id) &&
 849          (($topic_data['poll_length'] != 0 && $topic_data['poll_start'] + $topic_data['poll_length'] > time()) || $topic_data['poll_length'] == 0) &&
 850          $topic_data['topic_status'] != ITEM_LOCKED &&
 851          $topic_data['forum_status'] != ITEM_LOCKED &&
 852          (!sizeof($cur_voted_id) ||
 853          ($auth->acl_get('f_votechg', $forum_id) && $topic_data['poll_vote_change']))) ? true : false;
 854      $s_display_results = (!$s_can_vote || ($s_can_vote && sizeof($cur_voted_id)) || $view == 'viewpoll') ? true : false;
 855  
 856      /**
 857      * Event to manipulate the poll data
 858      *
 859      * @event core.viewtopic_modify_poll_data
 860      * @var    array    cur_voted_id                Array with options' IDs current user has voted for
 861      * @var    int        forum_id                    The topic's forum id
 862      * @var    array    poll_info                    Array with the poll information
 863      * @var    bool    s_can_vote                    Flag indicating if a user can vote
 864      * @var    bool    s_display_results            Flag indicating if results or poll options should be displayed
 865      * @var    int        topic_id                    The id of the topic the user tries to access
 866      * @var    array    topic_data                    All the information from the topic and forum tables for this topic
 867      * @var    string    viewtopic_url                URL to the topic page
 868      * @var    array    vote_counts                    Array with the vote counts for every poll option
 869      * @var    array    voted_id                    Array with updated options' IDs current user is voting for
 870      * @since 3.1.5-RC1
 871      */
 872      $vars = array(
 873          'cur_voted_id',
 874          'forum_id',
 875          'poll_info',
 876          's_can_vote',
 877          's_display_results',
 878          'topic_id',
 879          'topic_data',
 880          'viewtopic_url',
 881          'vote_counts',
 882          'voted_id',
 883      );
 884      extract($phpbb_dispatcher->trigger_event('core.viewtopic_modify_poll_data', compact($vars)));
 885  
 886      if ($update && $s_can_vote)
 887      {
 888  
 889          if (!sizeof($voted_id) || sizeof($voted_id) > $topic_data['poll_max_options'] || in_array(VOTE_CONVERTED, $cur_voted_id) || !check_form_key('posting'))
 890          {
 891              $redirect_url = append_sid("{$phpbb_root_path}viewtopic.$phpEx", "f=$forum_id&amp;t=$topic_id" . (($start == 0) ? '' : "&amp;start=$start"));
 892  
 893              meta_refresh(5, $redirect_url);
 894              if (!sizeof($voted_id))
 895              {
 896                  $message = 'NO_VOTE_OPTION';
 897              }
 898              else if (sizeof($voted_id) > $topic_data['poll_max_options'])
 899              {
 900                  $message = 'TOO_MANY_VOTE_OPTIONS';
 901              }
 902              else if (in_array(VOTE_CONVERTED, $cur_voted_id))
 903              {
 904                  $message = 'VOTE_CONVERTED';
 905              }
 906              else
 907              {
 908                  $message = 'FORM_INVALID';
 909              }
 910  
 911              $message = $user->lang[$message] . '<br /><br />' . sprintf($user->lang['RETURN_TOPIC'], '<a href="' . $redirect_url . '">', '</a>');
 912              trigger_error($message);
 913          }
 914  
 915          foreach ($voted_id as $option)
 916          {
 917              if (in_array($option, $cur_voted_id))
 918              {
 919                  continue;
 920              }
 921  
 922              $sql = 'UPDATE ' . POLL_OPTIONS_TABLE . '
 923                  SET poll_option_total = poll_option_total + 1
 924                  WHERE poll_option_id = ' . (int) $option . '
 925                      AND topic_id = ' . (int) $topic_id;
 926              $db->sql_query($sql);
 927  
 928              $vote_counts[$option]++;
 929  
 930              if ($user->data['is_registered'])
 931              {
 932                  $sql_ary = array(
 933                      'topic_id'            => (int) $topic_id,
 934                      'poll_option_id'    => (int) $option,
 935                      'vote_user_id'        => (int) $user->data['user_id'],
 936                      'vote_user_ip'        => (string) $user->ip,
 937                  );
 938  
 939                  $sql = 'INSERT INTO ' . POLL_VOTES_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary);
 940                  $db->sql_query($sql);
 941              }
 942          }
 943  
 944          foreach ($cur_voted_id as $option)
 945          {
 946              if (!in_array($option, $voted_id))
 947              {
 948                  $sql = 'UPDATE ' . POLL_OPTIONS_TABLE . '
 949                      SET poll_option_total = poll_option_total - 1
 950                      WHERE poll_option_id = ' . (int) $option . '
 951                          AND topic_id = ' . (int) $topic_id;
 952                  $db->sql_query($sql);
 953  
 954                  $vote_counts[$option]--;
 955  
 956                  if ($user->data['is_registered'])
 957                  {
 958                      $sql = 'DELETE FROM ' . POLL_VOTES_TABLE . '
 959                          WHERE topic_id = ' . (int) $topic_id . '
 960                              AND poll_option_id = ' . (int) $option . '
 961                              AND vote_user_id = ' . (int) $user->data['user_id'];
 962                      $db->sql_query($sql);
 963                  }
 964              }
 965          }
 966  
 967          if ($user->data['user_id'] == ANONYMOUS && !$user->data['is_bot'])
 968          {
 969              $user->set_cookie('poll_' . $topic_id, implode(',', $voted_id), time() + 31536000);
 970          }
 971  
 972          $sql = 'UPDATE ' . TOPICS_TABLE . '
 973              SET poll_last_vote = ' . time() . "
 974              WHERE topic_id = $topic_id";
 975          //, topic_last_post_time = ' . time() . " -- for bumping topics with new votes, ignore for now
 976          $db->sql_query($sql);
 977  
 978          $redirect_url = append_sid("{$phpbb_root_path}viewtopic.$phpEx", "f=$forum_id&amp;t=$topic_id" . (($start == 0) ? '' : "&amp;start=$start"));
 979          $message = $user->lang['VOTE_SUBMITTED'] . '<br /><br />' . sprintf($user->lang['RETURN_TOPIC'], '<a href="' . $redirect_url . '">', '</a>');
 980  
 981          if ($request->is_ajax())
 982          {
 983              // Filter out invalid options
 984              $valid_user_votes = array_intersect(array_keys($vote_counts), $voted_id);
 985  
 986              $data = array(
 987                  'NO_VOTES'            => $user->lang['NO_VOTES'],
 988                  'success'            => true,
 989                  'user_votes'        => array_flip($valid_user_votes),
 990                  'vote_counts'        => $vote_counts,
 991                  'total_votes'        => array_sum($vote_counts),
 992                  'can_vote'            => !sizeof($valid_user_votes) || ($auth->acl_get('f_votechg', $forum_id) && $topic_data['poll_vote_change']),
 993              );
 994              $json_response = new \phpbb\json_response();
 995              $json_response->send($data);
 996          }
 997  
 998          meta_refresh(5, $redirect_url);
 999          trigger_error($message);
1000      }
1001  
1002      $poll_total = 0;
1003      $poll_most = 0;
1004      foreach ($poll_info as $poll_option)
1005      {
1006          $poll_total += $poll_option['poll_option_total'];
1007          $poll_most = ($poll_option['poll_option_total'] >= $poll_most) ? $poll_option['poll_option_total'] : $poll_most;
1008      }
1009  
1010      $parse_flags = ($poll_info[0]['bbcode_bitfield'] ? OPTION_FLAG_BBCODE : 0) | OPTION_FLAG_SMILIES;
1011  
1012      for ($i = 0, $size = sizeof($poll_info); $i < $size; $i++)
1013      {
1014          $poll_info[$i]['poll_option_text'] = generate_text_for_display($poll_info[$i]['poll_option_text'], $poll_info[$i]['bbcode_uid'], $poll_option['bbcode_bitfield'], $parse_flags, true);
1015      }
1016  
1017      $topic_data['poll_title'] = generate_text_for_display($topic_data['poll_title'], $poll_info[0]['bbcode_uid'], $poll_info[0]['bbcode_bitfield'], $parse_flags, true);
1018  
1019      $poll_template_data = $poll_options_template_data = array();
1020      foreach ($poll_info as $poll_option)
1021      {
1022          $option_pct = ($poll_total > 0) ? $poll_option['poll_option_total'] / $poll_total : 0;
1023          $option_pct_txt = sprintf("%.1d%%", round($option_pct * 100));
1024          $option_pct_rel = ($poll_most > 0) ? $poll_option['poll_option_total'] / $poll_most : 0;
1025          $option_pct_rel_txt = sprintf("%.1d%%", round($option_pct_rel * 100));
1026          $option_most_votes = ($poll_option['poll_option_total'] > 0 && $poll_option['poll_option_total'] == $poll_most) ? true : false;
1027  
1028          $poll_options_template_data[] = array(
1029              'POLL_OPTION_ID'             => $poll_option['poll_option_id'],
1030              'POLL_OPTION_CAPTION'         => $poll_option['poll_option_text'],
1031              'POLL_OPTION_RESULT'         => $poll_option['poll_option_total'],
1032              'POLL_OPTION_PERCENT'         => $option_pct_txt,
1033              'POLL_OPTION_PERCENT_REL'     => $option_pct_rel_txt,
1034              'POLL_OPTION_PCT'            => round($option_pct * 100),
1035              'POLL_OPTION_WIDTH'         => round($option_pct * 250),
1036              'POLL_OPTION_VOTED'            => (in_array($poll_option['poll_option_id'], $cur_voted_id)) ? true : false,
1037              'POLL_OPTION_MOST_VOTES'    => $option_most_votes,
1038          );
1039      }
1040  
1041      $poll_end = $topic_data['poll_length'] + $topic_data['poll_start'];
1042  
1043      $poll_template_data = array(
1044          'POLL_QUESTION'        => $topic_data['poll_title'],
1045          'TOTAL_VOTES'         => $poll_total,
1046          'POLL_LEFT_CAP_IMG'    => $user->img('poll_left'),
1047          'POLL_RIGHT_CAP_IMG'=> $user->img('poll_right'),
1048  
1049          'L_MAX_VOTES'        => $user->lang('MAX_OPTIONS_SELECT', (int) $topic_data['poll_max_options']),
1050          'L_POLL_LENGTH'        => ($topic_data['poll_length']) ? sprintf($user->lang[($poll_end > time()) ? 'POLL_RUN_TILL' : 'POLL_ENDED_AT'], $user->format_date($poll_end)) : '',
1051  
1052          'S_HAS_POLL'        => true,
1053          'S_CAN_VOTE'        => $s_can_vote,
1054          'S_DISPLAY_RESULTS'    => $s_display_results,
1055          'S_IS_MULTI_CHOICE'    => ($topic_data['poll_max_options'] > 1) ? true : false,
1056          'S_POLL_ACTION'        => $viewtopic_url,
1057  
1058          'U_VIEW_RESULTS'    => $viewtopic_url . '&amp;view=viewpoll',
1059      );
1060  
1061      /**
1062      * Event to add/modify poll template data
1063      *
1064      * @event core.viewtopic_modify_poll_template_data
1065      * @var    array    cur_voted_id                    Array with options' IDs current user has voted for
1066      * @var    int        poll_end                        The poll end time
1067      * @var    array    poll_info                        Array with the poll information
1068      * @var    array    poll_options_template_data        Array with the poll options template data
1069      * @var    array    poll_template_data                Array with the common poll template data
1070      * @var    int        poll_total                        Total poll votes count
1071      * @var    int        poll_most                        Mostly voted option votes count
1072      * @var    array    topic_data                        All the information from the topic and forum tables for this topic
1073      * @var    string    viewtopic_url                    URL to the topic page
1074      * @var    array    vote_counts                        Array with the vote counts for every poll option
1075      * @var    array    voted_id                        Array with updated options' IDs current user is voting for
1076      * @since 3.1.5-RC1
1077      */
1078      $vars = array(
1079          'cur_voted_id',
1080          'poll_end',
1081          'poll_info',
1082          'poll_options_template_data',
1083          'poll_template_data',
1084          'poll_total',
1085          'poll_most',
1086          'topic_data',
1087          'viewtopic_url',
1088          'vote_counts',
1089          'voted_id',
1090      );
1091      extract($phpbb_dispatcher->trigger_event('core.viewtopic_modify_poll_template_data', compact($vars)));
1092  
1093      $template->assign_block_vars_array('poll_option', $poll_options_template_data);
1094  
1095      $template->assign_vars($poll_template_data);
1096  
1097      unset($poll_end, $poll_info, $poll_options_template_data, $poll_template_data, $voted_id);
1098  }
1099  
1100  // If the user is trying to reach the second half of the topic, fetch it starting from the end
1101  $store_reverse = false;
1102  $sql_limit = $config['posts_per_page'];
1103  $sql_sort_order = $direction = '';
1104  
1105  if ($start > $total_posts / 2)
1106  {
1107      $store_reverse = true;
1108  
1109      // Select the sort order
1110      $direction = (($sort_dir == 'd') ? 'ASC' : 'DESC');
1111  
1112      $sql_limit = $pagination->reverse_limit($start, $sql_limit, $total_posts);
1113      $sql_start = $pagination->reverse_start($start, $sql_limit, $total_posts);
1114  }
1115  else
1116  {
1117      // Select the sort order
1118      $direction = (($sort_dir == 'd') ? 'DESC' : 'ASC');
1119      $sql_start = $start;
1120  }
1121  
1122  if (is_array($sort_by_sql[$sort_key]))
1123  {
1124      $sql_sort_order = implode(' ' . $direction . ', ', $sort_by_sql[$sort_key]) . ' ' . $direction;
1125  }
1126  else
1127  {
1128      $sql_sort_order = $sort_by_sql[$sort_key] . ' ' . $direction;
1129  }
1130  
1131  // Container for user details, only process once
1132  $post_list = $user_cache = $id_cache = $attachments = $attach_list = $rowset = $update_count = $post_edit_list = $post_delete_list = array();
1133  $has_unapproved_attachments = $has_approved_attachments = $display_notice = false;
1134  $i = $i_total = 0;
1135  
1136  // Go ahead and pull all data for this topic
1137  $sql = 'SELECT p.post_id
1138      FROM ' . POSTS_TABLE . ' p' . (($join_user_sql[$sort_key]) ? ', ' . USERS_TABLE . ' u': '') . "
1139      WHERE p.topic_id = $topic_id
1140          AND " . $phpbb_content_visibility->get_visibility_sql('post', $forum_id, 'p.') . "
1141          " . (($join_user_sql[$sort_key]) ? 'AND u.user_id = p.poster_id': '') . "
1142          $limit_posts_time
1143      ORDER BY $sql_sort_order";
1144  $result = $db->sql_query_limit($sql, $sql_limit, $sql_start);
1145  
1146  $i = ($store_reverse) ? $sql_limit - 1 : 0;
1147  while ($row = $db->sql_fetchrow($result))
1148  {
1149      $post_list[$i] = (int) $row['post_id'];
1150      ($store_reverse) ? $i-- : $i++;
1151  }
1152  $db->sql_freeresult($result);
1153  
1154  if (!sizeof($post_list))
1155  {
1156      if ($sort_days)
1157      {
1158          trigger_error('NO_POSTS_TIME_FRAME');
1159      }
1160      else
1161      {
1162          trigger_error('NO_TOPIC');
1163      }
1164  }
1165  
1166  // Holding maximum post time for marking topic read
1167  // We need to grab it because we do reverse ordering sometimes
1168  $max_post_time = 0;
1169  
1170  $sql_ary = array(
1171      'SELECT'    => 'u.*, z.friend, z.foe, p.*',
1172  
1173      'FROM'        => array(
1174          USERS_TABLE        => 'u',
1175          POSTS_TABLE        => 'p',
1176      ),
1177  
1178      'LEFT_JOIN'    => array(
1179          array(
1180              'FROM'    => array(ZEBRA_TABLE => 'z'),
1181              'ON'    => 'z.user_id = ' . $user->data['user_id'] . ' AND z.zebra_id = p.poster_id',
1182          ),
1183      ),
1184  
1185      'WHERE'        => $db->sql_in_set('p.post_id', $post_list) . '
1186          AND u.user_id = p.poster_id',
1187  );
1188  
1189  /**
1190  * Event to modify the SQL query before the post and poster data is retrieved
1191  *
1192  * @event core.viewtopic_get_post_data
1193  * @var    int        forum_id    Forum ID
1194  * @var    int        topic_id    Topic ID
1195  * @var    array    topic_data    Array with topic data
1196  * @var    array    post_list    Array with post_ids we are going to retrieve
1197  * @var    int        sort_days    Display posts of previous x days
1198  * @var    string    sort_key    Key the posts are sorted by
1199  * @var    string    sort_dir    Direction the posts are sorted by
1200  * @var    int        start        Pagination information
1201  * @var    array    sql_ary        The SQL array to get the data of posts and posters
1202  * @since 3.1.0-a1
1203  * @changed 3.1.0-a2 Added vars forum_id, topic_id, topic_data, post_list, sort_days, sort_key, sort_dir, start
1204  */
1205  $vars = array(
1206      'forum_id',
1207      'topic_id',
1208      'topic_data',
1209      'post_list',
1210      'sort_days',
1211      'sort_key',
1212      'sort_dir',
1213      'start',
1214      'sql_ary',
1215  );
1216  extract($phpbb_dispatcher->trigger_event('core.viewtopic_get_post_data', compact($vars)));
1217  
1218  $sql = $db->sql_build_query('SELECT', $sql_ary);
1219  $result = $db->sql_query($sql);
1220  
1221  $now = $user->create_datetime();
1222  $now = phpbb_gmgetdate($now->getTimestamp() + $now->getOffset());
1223  
1224  // Posts are stored in the $rowset array while $attach_list, $user_cache
1225  // and the global bbcode_bitfield are built
1226  while ($row = $db->sql_fetchrow($result))
1227  {
1228      // Set max_post_time
1229      if ($row['post_time'] > $max_post_time)
1230      {
1231          $max_post_time = $row['post_time'];
1232      }
1233  
1234      $poster_id = (int) $row['poster_id'];
1235  
1236      // Does post have an attachment? If so, add it to the list
1237      if ($row['post_attachment'] && $config['allow_attachments'])
1238      {
1239          $attach_list[] = (int) $row['post_id'];
1240  
1241          if ($row['post_visibility'] == ITEM_UNAPPROVED || $row['post_visibility'] == ITEM_REAPPROVE)
1242          {
1243              $has_unapproved_attachments = true;
1244          }
1245          else if ($row['post_visibility'] == ITEM_APPROVED)
1246          {
1247              $has_approved_attachments = true;
1248          }
1249      }
1250  
1251      $rowset_data = array(
1252          'hide_post'            => (($row['foe'] || $row['post_visibility'] == ITEM_DELETED) && ($view != 'show' || $post_id != $row['post_id'])) ? true : false,
1253  
1254          'post_id'            => $row['post_id'],
1255          'post_time'            => $row['post_time'],
1256          'user_id'            => $row['user_id'],
1257          'username'            => $row['username'],
1258          'user_colour'        => $row['user_colour'],
1259          'topic_id'            => $row['topic_id'],
1260          'forum_id'            => $row['forum_id'],
1261          'post_subject'        => $row['post_subject'],
1262          'post_edit_count'    => $row['post_edit_count'],
1263          'post_edit_time'    => $row['post_edit_time'],
1264          'post_edit_reason'    => $row['post_edit_reason'],
1265          'post_edit_user'    => $row['post_edit_user'],
1266          'post_edit_locked'    => $row['post_edit_locked'],
1267          'post_delete_time'    => $row['post_delete_time'],
1268          'post_delete_reason'=> $row['post_delete_reason'],
1269          'post_delete_user'    => $row['post_delete_user'],
1270  
1271          // Make sure the icon actually exists
1272          'icon_id'            => (isset($icons[$row['icon_id']]['img'], $icons[$row['icon_id']]['height'], $icons[$row['icon_id']]['width'])) ? $row['icon_id'] : 0,
1273          'post_attachment'    => $row['post_attachment'],
1274          'post_visibility'    => $row['post_visibility'],
1275          'post_reported'        => $row['post_reported'],
1276          'post_username'        => $row['post_username'],
1277          'post_text'            => $row['post_text'],
1278          'bbcode_uid'        => $row['bbcode_uid'],
1279          'bbcode_bitfield'    => $row['bbcode_bitfield'],
1280          'enable_smilies'    => $row['enable_smilies'],
1281          'enable_sig'        => $row['enable_sig'],
1282          'friend'            => $row['friend'],
1283          'foe'                => $row['foe'],
1284      );
1285  
1286      /**
1287      * Modify the post rowset containing data to be displayed with posts
1288      *
1289      * @event core.viewtopic_post_rowset_data
1290      * @var    array    rowset_data    Array with the rowset data for this post
1291      * @var    array    row            Array with original user and post data
1292      * @since 3.1.0-a1
1293      */
1294      $vars = array('rowset_data', 'row');
1295      extract($phpbb_dispatcher->trigger_event('core.viewtopic_post_rowset_data', compact($vars)));
1296  
1297      $rowset[$row['post_id']] = $rowset_data;
1298  
1299      // Cache various user specific data ... so we don't have to recompute
1300      // this each time the same user appears on this page
1301      if (!isset($user_cache[$poster_id]))
1302      {
1303          if ($poster_id == ANONYMOUS)
1304          {
1305              $user_cache_data = array(
1306                  'user_type'        => USER_IGNORE,
1307                  'joined'        => '',
1308                  'posts'            => '',
1309  
1310                  'sig'                    => '',
1311                  'sig_bbcode_uid'        => '',
1312                  'sig_bbcode_bitfield'    => '',
1313  
1314                  'online'            => false,
1315                  'avatar'            => ($user->optionget('viewavatars')) ? phpbb_get_user_avatar($row) : '',
1316                  'rank_title'        => '',
1317                  'rank_image'        => '',
1318                  'rank_image_src'    => '',
1319                  'pm'                => '',
1320                  'email'                => '',
1321                  'jabber'            => '',
1322                  'search'            => '',
1323                  'age'                => '',
1324  
1325                  'username'            => $row['username'],
1326                  'user_colour'        => $row['user_colour'],
1327                  'contact_user'        => '',
1328  
1329                  'warnings'            => 0,
1330                  'allow_pm'            => 0,
1331              );
1332  
1333              /**
1334              * Modify the guest user's data displayed with the posts
1335              *
1336              * @event core.viewtopic_cache_guest_data
1337              * @var    array    user_cache_data    Array with the user's data
1338              * @var    int        poster_id        Poster's user id
1339              * @var    array    row                Array with original user and post data
1340              * @since 3.1.0-a1
1341              */
1342              $vars = array('user_cache_data', 'poster_id', 'row');
1343              extract($phpbb_dispatcher->trigger_event('core.viewtopic_cache_guest_data', compact($vars)));
1344  
1345              $user_cache[$poster_id] = $user_cache_data;
1346  
1347              $user_rank_data = phpbb_get_user_rank($row, false);
1348              $user_cache[$poster_id]['rank_title'] = $user_rank_data['title'];
1349              $user_cache[$poster_id]['rank_image'] = $user_rank_data['img'];
1350              $user_cache[$poster_id]['rank_image_src'] = $user_rank_data['img_src'];
1351          }
1352          else
1353          {
1354              $user_sig = '';
1355  
1356              // We add the signature to every posters entry because enable_sig is post dependent
1357              if ($row['user_sig'] && $config['allow_sig'] && $user->optionget('viewsigs'))
1358              {
1359                  $user_sig = $row['user_sig'];
1360              }
1361  
1362              $id_cache[] = $poster_id;
1363  
1364              $user_cache_data = array(
1365                  'user_type'                    => $row['user_type'],
1366                  'user_inactive_reason'        => $row['user_inactive_reason'],
1367  
1368                  'joined'        => $user->format_date($row['user_regdate']),
1369                  'posts'            => $row['user_posts'],
1370                  'warnings'        => (isset($row['user_warnings'])) ? $row['user_warnings'] : 0,
1371  
1372                  'sig'                    => $user_sig,
1373                  'sig_bbcode_uid'        => (!empty($row['user_sig_bbcode_uid'])) ? $row['user_sig_bbcode_uid'] : '',
1374                  'sig_bbcode_bitfield'    => (!empty($row['user_sig_bbcode_bitfield'])) ? $row['user_sig_bbcode_bitfield'] : '',
1375  
1376                  'viewonline'    => $row['user_allow_viewonline'],
1377                  'allow_pm'        => $row['user_allow_pm'],
1378  
1379                  'avatar'        => ($user->optionget('viewavatars')) ? phpbb_get_user_avatar($row) : '',
1380                  'age'            => '',
1381  
1382                  'rank_title'        => '',
1383                  'rank_image'        => '',
1384                  'rank_image_src'    => '',
1385  
1386                  'username'            => $row['username'],
1387                  'user_colour'        => $row['user_colour'],
1388                  'contact_user'         => $user->lang('CONTACT_USER', get_username_string('username', $poster_id, $row['username'], $row['user_colour'], $row['username'])),
1389  
1390                  'online'        => false,
1391                  'jabber'        => ($config['jab_enable'] && $row['user_jabber'] && $auth->acl_get('u_sendim')) ? append_sid("{$phpbb_root_path}memberlist.$phpEx", "mode=contact&amp;action=jabber&amp;u=$poster_id") : '',
1392                  'search'        => ($config['load_search'] && $auth->acl_get('u_search')) ? append_sid("{$phpbb_root_path}search.$phpEx", "author_id=$poster_id&amp;sr=posts") : '',
1393  
1394                  'author_full'        => get_username_string('full', $poster_id, $row['username'], $row['user_colour']),
1395                  'author_colour'        => get_username_string('colour', $poster_id, $row['username'], $row['user_colour']),
1396                  'author_username'    => get_username_string('username', $poster_id, $row['username'], $row['user_colour']),
1397                  'author_profile'    => get_username_string('profile', $poster_id, $row['username'], $row['user_colour']),
1398              );
1399  
1400              /**
1401              * Modify the users' data displayed with their posts
1402              *
1403              * @event core.viewtopic_cache_user_data
1404              * @var    array    user_cache_data    Array with the user's data
1405              * @var    int        poster_id        Poster's user id
1406              * @var    array    row                Array with original user and post data
1407              * @since 3.1.0-a1
1408              */
1409              $vars = array('user_cache_data', 'poster_id', 'row');
1410              extract($phpbb_dispatcher->trigger_event('core.viewtopic_cache_user_data', compact($vars)));
1411  
1412              $user_cache[$poster_id] = $user_cache_data;
1413  
1414              $user_rank_data = phpbb_get_user_rank($row, $row['user_posts']);
1415              $user_cache[$poster_id]['rank_title'] = $user_rank_data['title'];
1416              $user_cache[$poster_id]['rank_image'] = $user_rank_data['img'];
1417              $user_cache[$poster_id]['rank_image_src'] = $user_rank_data['img_src'];
1418  
1419              if ((!empty($row['user_allow_viewemail']) && $auth->acl_get('u_sendemail')) || $auth->acl_get('a_email'))
1420              {
1421                  $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']);
1422              }
1423              else
1424              {
1425                  $user_cache[$poster_id]['email'] = '';
1426              }
1427  
1428              if ($config['allow_birthdays'] && !empty($row['user_birthday']))
1429              {
1430                  list($bday_day, $bday_month, $bday_year) = array_map('intval', explode('-', $row['user_birthday']));
1431  
1432                  if ($bday_year)
1433                  {
1434                      $diff = $now['mon'] - $bday_month;
1435                      if ($diff == 0)
1436                      {
1437                          $diff = ($now['mday'] - $bday_day < 0) ? 1 : 0;
1438                      }
1439                      else
1440                      {
1441                          $diff = ($diff < 0) ? 1 : 0;
1442                      }
1443  
1444                      $user_cache[$poster_id]['age'] = (int) ($now['year'] - $bday_year - $diff);
1445                  }
1446              }
1447          }
1448      }
1449  }
1450  $db->sql_freeresult($result);
1451  
1452  // Load custom profile fields
1453  if ($config['load_cpf_viewtopic'])
1454  {
1455      $cp = $phpbb_container->get('profilefields.manager');
1456  
1457      // Grab all profile fields from users in id cache for later use - similar to the poster cache
1458      $profile_fields_tmp = $cp->grab_profile_fields_data($id_cache);
1459  
1460      // filter out fields not to be displayed on viewtopic. Yes, it's a hack, but this shouldn't break any MODs.
1461      $profile_fields_cache = array();
1462      foreach ($profile_fields_tmp as $profile_user_id => $profile_fields)
1463      {
1464          $profile_fields_cache[$profile_user_id] = array();
1465          foreach ($profile_fields as $used_ident => $profile_field)
1466          {
1467              if ($profile_field['data']['field_show_on_vt'])
1468              {
1469                  $profile_fields_cache[$profile_user_id][$used_ident] = $profile_field;
1470              }
1471          }
1472      }
1473      unset($profile_fields_tmp);
1474  }
1475  
1476  // Generate online information for user
1477  if ($config['load_onlinetrack'] && sizeof($id_cache))
1478  {
1479      $sql = 'SELECT session_user_id, MAX(session_time) as online_time, MIN(session_viewonline) AS viewonline
1480          FROM ' . SESSIONS_TABLE . '
1481          WHERE ' . $db->sql_in_set('session_user_id', $id_cache) . '
1482          GROUP BY session_user_id';
1483      $result = $db->sql_query($sql);
1484  
1485      $update_time = $config['load_online_time'] * 60;
1486      while ($row = $db->sql_fetchrow($result))
1487      {
1488          $user_cache[$row['session_user_id']]['online'] = (time() - $update_time < $row['online_time'] && (($row['viewonline']) || $auth->acl_get('u_viewonline'))) ? true : false;
1489      }
1490      $db->sql_freeresult($result);
1491  }
1492  unset($id_cache);
1493  
1494  // Pull attachment data
1495  if (sizeof($attach_list))
1496  {
1497      if ($auth->acl_get('u_download') && $auth->acl_get('f_download', $forum_id))
1498      {
1499          $sql = 'SELECT *
1500              FROM ' . ATTACHMENTS_TABLE . '
1501              WHERE ' . $db->sql_in_set('post_msg_id', $attach_list) . '
1502                  AND in_message = 0
1503              ORDER BY attach_id DESC, post_msg_id ASC';
1504          $result = $db->sql_query($sql);
1505  
1506          while ($row = $db->sql_fetchrow($result))
1507          {
1508              $attachments[$row['post_msg_id']][] = $row;
1509          }
1510          $db->sql_freeresult($result);
1511  
1512          // No attachments exist, but post table thinks they do so go ahead and reset post_attach flags
1513          if (!sizeof($attachments))
1514          {
1515              $sql = 'UPDATE ' . POSTS_TABLE . '
1516                  SET post_attachment = 0
1517                  WHERE ' . $db->sql_in_set('post_id', $attach_list);
1518              $db->sql_query($sql);
1519  
1520              // We need to update the topic indicator too if the complete topic is now without an attachment
1521              if (sizeof($rowset) != $total_posts)
1522              {
1523                  // Not all posts are displayed so we query the db to find if there's any attachment for this topic
1524                  $sql = 'SELECT a.post_msg_id as post_id
1525                      FROM ' . ATTACHMENTS_TABLE . ' a, ' . POSTS_TABLE . " p
1526                      WHERE p.topic_id = $topic_id
1527                          AND p.post_visibility = " . ITEM_APPROVED . '
1528                          AND p.topic_id = a.topic_id';
1529                  $result = $db->sql_query_limit($sql, 1);
1530                  $row = $db->sql_fetchrow($result);
1531                  $db->sql_freeresult($result);
1532  
1533                  if (!$row)
1534                  {
1535                      $sql = 'UPDATE ' . TOPICS_TABLE . "
1536                          SET topic_attachment = 0
1537                          WHERE topic_id = $topic_id";
1538                      $db->sql_query($sql);
1539                  }
1540              }
1541              else
1542              {
1543                  $sql = 'UPDATE ' . TOPICS_TABLE . "
1544                      SET topic_attachment = 0
1545                      WHERE topic_id = $topic_id";
1546                  $db->sql_query($sql);
1547              }
1548          }
1549          else if ($has_approved_attachments && !$topic_data['topic_attachment'])
1550          {
1551              // Topic has approved attachments but its flag is wrong
1552              $sql = 'UPDATE ' . TOPICS_TABLE . "
1553                  SET topic_attachment = 1
1554                  WHERE topic_id = $topic_id";
1555              $db->sql_query($sql);
1556  
1557              $topic_data['topic_attachment'] = 1;
1558          }
1559          else if ($has_unapproved_attachments && !$topic_data['topic_attachment'])
1560          {
1561              // Topic has only unapproved attachments but we have the right to see and download them
1562              $topic_data['topic_attachment'] = 1;
1563          }
1564      }
1565      else
1566      {
1567          $display_notice = true;
1568      }
1569  }
1570  
1571  // Get the list of users who can receive private messages
1572  $can_receive_pm_list = $auth->acl_get_list(array_keys($user_cache), 'u_readpm');
1573  $can_receive_pm_list = (empty($can_receive_pm_list) || !isset($can_receive_pm_list[0]['u_readpm'])) ? array() : $can_receive_pm_list[0]['u_readpm'];
1574  
1575  // Get the list of permanently banned users
1576  $permanently_banned_users = phpbb_get_banned_user_ids(array_keys($user_cache), false);
1577  
1578  $i_total = sizeof($rowset) - 1;
1579  $prev_post_id = '';
1580  
1581  $template->assign_vars(array(
1582      'S_HAS_ATTACHMENTS' => $topic_data['topic_attachment'],
1583      'S_NUM_POSTS' => sizeof($post_list))
1584  );
1585  
1586  /**
1587  * Event to modify the post, poster and attachment data before assigning the posts
1588  *
1589  * @event core.viewtopic_modify_post_data
1590  * @var    int        forum_id    Forum ID
1591  * @var    int        topic_id    Topic ID
1592  * @var    array    topic_data    Array with topic data
1593  * @var    array    post_list    Array with post_ids we are going to display
1594  * @var    array    rowset        Array with post_id => post data
1595  * @var    array    user_cache    Array with prepared user data
1596  * @var    int        start        Pagination information
1597  * @var    int        sort_days    Display posts of previous x days
1598  * @var    string    sort_key    Key the posts are sorted by
1599  * @var    string    sort_dir    Direction the posts are sorted by
1600  * @var    bool    display_notice                Shall we display a notice instead of attachments
1601  * @var    bool    has_approved_attachments    Does the topic have approved attachments
1602  * @var    array    attachments                    List of attachments post_id => array of attachments
1603  * @var    array    permanently_banned_users    List of permanently banned users
1604  * @var    array    can_receive_pm_list            Array with posters that can receive pms
1605  * @since 3.1.0-RC3
1606  */
1607  $vars = array(
1608      'forum_id',
1609      'topic_id',
1610      'topic_data',
1611      'post_list',
1612      'rowset',
1613      'user_cache',
1614      'sort_days',
1615      'sort_key',
1616      'sort_dir',
1617      'start',
1618      'permanently_banned_users',
1619      'can_receive_pm_list',
1620      'display_notice',
1621      'has_approved_attachments',
1622      'attachments',
1623  );
1624  extract($phpbb_dispatcher->trigger_event('core.viewtopic_modify_post_data', compact($vars)));
1625  
1626  // Output the posts
1627  $first_unread = $post_unread = false;
1628  for ($i = 0, $end = sizeof($post_list); $i < $end; ++$i)
1629  {
1630      // A non-existing rowset only happens if there was no user present for the entered poster_id
1631      // This could be a broken posts table.
1632      if (!isset($rowset[$post_list[$i]]))
1633      {
1634          continue;
1635      }
1636  
1637      $row = $rowset[$post_list[$i]];
1638      $poster_id = $row['user_id'];
1639  
1640      // End signature parsing, only if needed
1641      if ($user_cache[$poster_id]['sig'] && $row['enable_sig'] && empty($user_cache[$poster_id]['sig_parsed']))
1642      {
1643          $parse_flags = ($user_cache[$poster_id]['sig_bbcode_bitfield'] ? OPTION_FLAG_BBCODE : 0) | OPTION_FLAG_SMILIES;
1644          $user_cache[$poster_id]['sig'] = generate_text_for_display($user_cache[$poster_id]['sig'], $user_cache[$poster_id]['sig_bbcode_uid'], $user_cache[$poster_id]['sig_bbcode_bitfield'],  $parse_flags, true);
1645      }
1646  
1647      // Parse the message and subject
1648      $parse_flags = ($row['bbcode_bitfield'] ? OPTION_FLAG_BBCODE : 0) | OPTION_FLAG_SMILIES;
1649      $message = generate_text_for_display($row['post_text'], $row['bbcode_uid'], $row['bbcode_bitfield'], $parse_flags, true);
1650  
1651      if (!empty($attachments[$row['post_id']]))
1652      {
1653          parse_attachments($forum_id, $message, $attachments[$row['post_id']], $update_count);
1654      }
1655  
1656      // Replace naughty words such as farty pants
1657      $row['post_subject'] = censor_text($row['post_subject']);
1658  
1659      // Highlight active words (primarily for search)
1660      if ($highlight_match)
1661      {
1662          $message = preg_replace('#(?!<.*)(?<!\w)(' . $highlight_match . ')(?!\w|[^<>]*(?:</s(?:cript|tyle))?>)#is', '<span class="posthilit">\1</span>', $message);
1663          $row['post_subject'] = preg_replace('#(?!<.*)(?<!\w)(' . $highlight_match . ')(?!\w|[^<>]*(?:</s(?:cript|tyle))?>)#is', '<span class="posthilit">\1</span>', $row['post_subject']);
1664      }
1665  
1666      // Editing information
1667      if (($row['post_edit_count'] && $config['display_last_edited']) || $row['post_edit_reason'])
1668      {
1669          // Get usernames for all following posts if not already stored
1670          if (!sizeof($post_edit_list) && ($row['post_edit_reason'] || ($row['post_edit_user'] && !isset($user_cache[$row['post_edit_user']]))))
1671          {
1672              // Remove all post_ids already parsed (we do not have to check them)
1673              $post_storage_list = (!$store_reverse) ? array_slice($post_list, $i) : array_slice(array_reverse($post_list), $i);
1674  
1675              $sql = 'SELECT DISTINCT u.user_id, u.username, u.user_colour
1676                  FROM ' . POSTS_TABLE . ' p, ' . USERS_TABLE . ' u
1677                  WHERE ' . $db->sql_in_set('p.post_id', $post_storage_list) . '
1678                      AND p.post_edit_count <> 0
1679                      AND p.post_edit_user <> 0
1680                      AND p.post_edit_user = u.user_id';
1681              $result2 = $db->sql_query($sql);
1682              while ($user_edit_row = $db->sql_fetchrow($result2))
1683              {
1684                  $post_edit_list[$user_edit_row['user_id']] = $user_edit_row;
1685              }
1686              $db->sql_freeresult($result2);
1687  
1688              unset($post_storage_list);
1689          }
1690  
1691          if ($row['post_edit_reason'])
1692          {
1693              // User having edited the post also being the post author?
1694              if (!$row['post_edit_user'] || $row['post_edit_user'] == $poster_id)
1695              {
1696                  $display_username = get_username_string('full', $poster_id, $row['username'], $row['user_colour'], $row['post_username']);
1697              }
1698              else
1699              {
1700                  $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']);
1701              }
1702  
1703              $l_edited_by = $user->lang('EDITED_TIMES_TOTAL', (int) $row['post_edit_count'], $display_username, $user->format_date($row['post_edit_time'], false, true));
1704          }
1705          else
1706          {
1707              if ($row['post_edit_user'] && !isset($user_cache[$row['post_edit_user']]))
1708              {
1709                  $user_cache[$row['post_edit_user']] = $post_edit_list[$row['post_edit_user']];
1710              }
1711  
1712              // User having edited the post also being the post author?
1713              if (!$row['post_edit_user'] || $row['post_edit_user'] == $poster_id)
1714              {
1715                  $display_username = get_username_string('full', $poster_id, $row['username'], $row['user_colour'], $row['post_username']);
1716              }
1717              else
1718              {
1719                  $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']);
1720              }
1721  
1722              $l_edited_by = $user->lang('EDITED_TIMES_TOTAL', (int) $row['post_edit_count'], $display_username, $user->format_date($row['post_edit_time'], false, true));
1723          }
1724      }
1725      else
1726      {
1727          $l_edited_by = '';
1728      }
1729  
1730      // Deleting information
1731      if ($row['post_visibility'] == ITEM_DELETED && $row['post_delete_user'])
1732      {
1733          // Get usernames for all following posts if not already stored
1734          if (!sizeof($post_delete_list) && ($row['post_delete_reason'] || ($row['post_delete_user'] && !isset($user_cache[$row['post_delete_user']]))))
1735          {
1736              // Remove all post_ids already parsed (we do not have to check them)
1737              $post_storage_list = (!$store_reverse) ? array_slice($post_list, $i) : array_slice(array_reverse($post_list), $i);
1738  
1739              $sql = 'SELECT DISTINCT u.user_id, u.username, u.user_colour
1740                  FROM ' . POSTS_TABLE . ' p, ' . USERS_TABLE . ' u
1741                  WHERE ' . $db->sql_in_set('p.post_id', $post_storage_list) . '
1742                      AND p.post_delete_user <> 0
1743                      AND p.post_delete_user = u.user_id';
1744              $result2 = $db->sql_query($sql);
1745              while ($user_delete_row = $db->sql_fetchrow($result2))
1746              {
1747                  $post_delete_list[$user_delete_row['user_id']] = $user_delete_row;
1748              }
1749              $db->sql_freeresult($result2);
1750  
1751              unset($post_storage_list);
1752          }
1753  
1754          if ($row['post_delete_user'] && !isset($user_cache[$row['post_delete_user']]))
1755          {
1756              $user_cache[$row['post_delete_user']] = $post_delete_list[$row['post_delete_user']];
1757          }
1758  
1759          $display_postername = get_username_string('full', $poster_id, $row['username'], $row['user_colour'], $row['post_username']);
1760  
1761          // User having deleted the post also being the post author?
1762          if (!$row['post_delete_user'] || $row['post_delete_user'] == $poster_id)
1763          {
1764              $display_username = $display_postername;
1765          }
1766          else
1767          {
1768              $display_username = get_username_string('full', $row['post_delete_user'], $user_cache[$row['post_delete_user']]['username'], $user_cache[$row['post_delete_user']]['user_colour']);
1769          }
1770  
1771          if ($row['post_delete_reason'])
1772          {
1773              $l_deleted_message = $user->lang('POST_DELETED_BY_REASON', $display_postername, $display_username, $user->format_date($row['post_delete_time'], false, true), $row['post_delete_reason']);
1774          }
1775          else
1776          {
1777              $l_deleted_message = $user->lang('POST_DELETED_BY', $display_postername, $display_username, $user->format_date($row['post_delete_time'], false, true));
1778          }
1779          $l_deleted_by = $user->lang('DELETED_INFORMATION', $display_username, $user->format_date($row['post_delete_time'], false, true));
1780      }
1781      else
1782      {
1783          $l_deleted_by = $l_deleted_message = '';
1784      }
1785  
1786      // Bump information
1787      if ($topic_data['topic_bumped'] && $row['post_id'] == $topic_data['topic_last_post_id'] && isset($user_cache[$topic_data['topic_bumper']]) )
1788      {
1789          // It is safe to grab the username from the user cache array, we are at the last
1790          // post and only the topic poster and last poster are allowed to bump.
1791          // Admins and mods are bound to the above rules too...
1792          $l_bumped_by = sprintf($user->lang['BUMPED_BY'], $user_cache[$topic_data['topic_bumper']]['username'], $user->format_date($topic_data['topic_last_post_time'], false, true));
1793      }
1794      else
1795      {
1796          $l_bumped_by = '';
1797      }
1798  
1799      $cp_row = array();
1800  
1801      //
1802      if ($config['load_cpf_viewtopic'])
1803      {
1804          $cp_row = (isset($profile_fields_cache[$poster_id])) ? $cp->generate_profile_fields_template_data($profile_fields_cache[$poster_id]) : array();
1805      }
1806  
1807      $post_unread = (isset($topic_tracking_info[$topic_id]) && $row['post_time'] > $topic_tracking_info[$topic_id]) ? true : false;
1808  
1809      $s_first_unread = false;
1810      if (!$first_unread && $post_unread)
1811      {
1812          $s_first_unread = $first_unread = true;
1813      }
1814  
1815      $force_edit_allowed = $force_delete_allowed = $force_softdelete_allowed = false;
1816  
1817      $s_cannot_edit = !$auth->acl_get('f_edit', $forum_id) || $user->data['user_id'] != $poster_id;
1818      $s_cannot_edit_time = $config['edit_time'] && $row['post_time'] <= time() - ($config['edit_time'] * 60);
1819      $s_cannot_edit_locked = $topic_data['topic_status'] == ITEM_LOCKED || $row['post_edit_locked'];
1820  
1821      $s_cannot_delete = $user->data['user_id'] != $poster_id || (
1822              !$auth->acl_get('f_delete', $forum_id) &&
1823              (!$auth->acl_get('f_softdelete', $forum_id) || $row['post_visibility'] == ITEM_DELETED)
1824      );
1825      $s_cannot_delete_lastpost = $topic_data['topic_last_post_id'] != $row['post_id'];
1826      $s_cannot_delete_time = $config['delete_time'] && $row['post_time'] <= time() - ($config['delete_time'] * 60);
1827      // we do not want to allow removal of the last post if a moderator locked it!
1828      $s_cannot_delete_locked = $topic_data['topic_status'] == ITEM_LOCKED || $row['post_edit_locked'];
1829  
1830      /**
1831      * This event allows you to modify the conditions for the "can edit post" and "can delete post" checks
1832      *
1833      * @event core.viewtopic_modify_post_action_conditions
1834      * @var    array    row            Array with post data
1835      * @var    array    topic_data    Array with topic data
1836      * @var    bool    force_edit_allowed        Allow the user to edit the post (all permissions and conditions are ignored)
1837      * @var    bool    s_cannot_edit            User can not edit the post because it's not his
1838      * @var    bool    s_cannot_edit_locked    User can not edit the post because it's locked
1839      * @var    bool    s_cannot_edit_time        User can not edit the post because edit_time has passed
1840      * @var    bool    force_delete_allowed        Allow the user to delete the post (all permissions and conditions are ignored)
1841      * @var    bool    s_cannot_delete                User can not delete the post because it's not his
1842      * @var    bool    s_cannot_delete_lastpost    User can not delete the post because it's not the last post of the topic
1843      * @var    bool    s_cannot_delete_locked        User can not delete the post because it's locked
1844      * @var    bool    s_cannot_delete_time        User can not delete the post because edit_time has passed
1845      * @var    bool    force_softdelete_allowed    Allow the user to —čoftdelete the post (all permissions and conditions are ignored)
1846      * @since 3.1.0-b4
1847      * @changed 3.1.11-RC1 Added force_softdelete_allowed var
1848      */
1849      $vars = array(
1850          'row',
1851          'topic_data',
1852          'force_edit_allowed',
1853          's_cannot_edit',
1854          's_cannot_edit_locked',
1855          's_cannot_edit_time',
1856          'force_delete_allowed',
1857          's_cannot_delete',
1858          's_cannot_delete_lastpost',
1859          's_cannot_delete_locked',
1860          's_cannot_delete_time',
1861          'force_softdelete_allowed',
1862      );
1863      extract($phpbb_dispatcher->trigger_event('core.viewtopic_modify_post_action_conditions', compact($vars)));
1864  
1865      $edit_allowed = $force_edit_allowed || ($user->data['is_registered'] && ($auth->acl_get('m_edit', $forum_id) || (
1866          !$s_cannot_edit &&
1867          !$s_cannot_edit_time &&
1868          !$s_cannot_edit_locked
1869      )));
1870  
1871      $quote_allowed = $auth->acl_get('m_edit', $forum_id) || ($topic_data['topic_status'] != ITEM_LOCKED &&
1872          ($user->data['user_id'] == ANONYMOUS || $auth->acl_get('f_reply', $forum_id))
1873      );
1874  
1875      // Only display the quote button if the post is quotable.  Posts not approved are not quotable.
1876      $quote_allowed = ($quote_allowed && $row['post_visibility'] == ITEM_APPROVED) ? true : false;
1877  
1878      $delete_allowed = $force_delete_allowed || ($user->data['is_registered'] && (
1879          ($auth->acl_get('m_delete', $forum_id) || ($auth->acl_get('m_softdelete', $forum_id) && $row['post_visibility'] != ITEM_DELETED)) ||
1880          (!$s_cannot_delete && !$s_cannot_delete_lastpost && !$s_cannot_delete_time && !$s_cannot_delete_locked)
1881      ));
1882  
1883      $softdelete_allowed = $force_softdelete_allowed || (($auth->acl_get('m_softdelete', $forum_id) ||
1884          ($auth->acl_get('f_softdelete', $forum_id) && $user->data['user_id'] == $poster_id)) && ($row['post_visibility'] != ITEM_DELETED));
1885  
1886      $permanent_delete_allowed = $force_delete_allowed || ($auth->acl_get('m_delete', $forum_id) ||
1887          ($auth->acl_get('f_delete', $forum_id) && $user->data['user_id'] == $poster_id));
1888  
1889      // Can this user receive a Private Message?
1890      $can_receive_pm = (
1891          // They must be a "normal" user
1892          $user_cache[$poster_id]['user_type'] != USER_IGNORE &&
1893  
1894          // They must not be deactivated by the administrator
1895          ($user_cache[$poster_id]['user_type'] != USER_INACTIVE || $user_cache[$poster_id]['user_inactive_reason'] != INACTIVE_MANUAL) &&
1896  
1897          // They must be able to read PMs
1898          in_array($poster_id, $can_receive_pm_list) &&
1899  
1900          // They must not be permanently banned
1901          !in_array($poster_id, $permanently_banned_users) &&
1902  
1903          // They must allow users to contact via PM
1904          (($auth->acl_gets('a_', 'm_') || $auth->acl_getf_global('m_')) || $user_cache[$poster_id]['allow_pm'])
1905      );
1906  
1907      $u_pm = '';
1908  
1909      if ($config['allow_privmsg'] && $auth->acl_get('u_sendpm') && $can_receive_pm)
1910      {
1911          $u_pm = append_sid("{$phpbb_root_path}ucp.$phpEx", 'i=pm&amp;mode=compose&amp;action=quotepost&amp;p=' . $row['post_id']);
1912      }
1913  
1914      //
1915      $post_row = array(
1916          'POST_AUTHOR_FULL'        => ($poster_id != ANONYMOUS) ? $user_cache[$poster_id]['author_full'] : get_username_string('full', $poster_id, $row['username'], $row['user_colour'], $row['post_username']),
1917          'POST_AUTHOR_COLOUR'    => ($poster_id != ANONYMOUS) ? $user_cache[$poster_id]['author_colour'] : get_username_string('colour', $poster_id, $row['username'], $row['user_colour'], $row['post_username']),
1918          'POST_AUTHOR'            => ($poster_id != ANONYMOUS) ? $user_cache[$poster_id]['author_username'] : get_username_string('username', $poster_id, $row['username'], $row['user_colour'], $row['post_username']),
1919          'U_POST_AUTHOR'            => ($poster_id != ANONYMOUS) ? $user_cache[$poster_id]['author_profile'] : get_username_string('profile', $poster_id, $row['username'], $row['user_colour'], $row['post_username']),
1920  
1921          'RANK_TITLE'        => $user_cache[$poster_id]['rank_title'],
1922          'RANK_IMG'            => $user_cache[$poster_id]['rank_image'],
1923          'RANK_IMG_SRC'        => $user_cache[$poster_id]['rank_image_src'],
1924          'POSTER_JOINED'        => $user_cache[$poster_id]['joined'],
1925          'POSTER_POSTS'        => $user_cache[$poster_id]['posts'],
1926          'POSTER_AVATAR'        => $user_cache[$poster_id]['avatar'],
1927          'POSTER_WARNINGS'    => $auth->acl_get('m_warn') ? $user_cache[$poster_id]['warnings'] : '',
1928          'POSTER_AGE'        => $user_cache[$poster_id]['age'],
1929          'CONTACT_USER'        => $user_cache[$poster_id]['contact_user'],
1930  
1931          'POST_DATE'            => $user->format_date($row['post_time'], false, ($view == 'print') ? true : false),
1932          'POST_SUBJECT'        => $row['post_subject'],
1933          'MESSAGE'            => $message,
1934          'SIGNATURE'            => ($row['enable_sig']) ? $user_cache[$poster_id]['sig'] : '',
1935          'EDITED_MESSAGE'    => $l_edited_by,
1936          'EDIT_REASON'        => $row['post_edit_reason'],
1937          'DELETED_MESSAGE'    => $l_deleted_by,
1938          'DELETE_REASON'        => $row['post_delete_reason'],
1939          'BUMPED_MESSAGE'    => $l_bumped_by,
1940  
1941          'MINI_POST_IMG'            => ($post_unread) ? $user->img('icon_post_target_unread', 'UNREAD_POST') : $user->img('icon_post_target', 'POST'),
1942          'POST_ICON_IMG'            => ($topic_data['enable_icons'] && !empty($row['icon_id'])) ? $icons[$row['icon_id']]['img'] : '',
1943          'POST_ICON_IMG_WIDTH'    => ($topic_data['enable_icons'] && !empty($row['icon_id'])) ? $icons[$row['icon_id']]['width'] : '',
1944          'POST_ICON_IMG_HEIGHT'    => ($topic_data['enable_icons'] && !empty($row['icon_id'])) ? $icons[$row['icon_id']]['height'] : '',
1945          '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')),
1946          'S_ONLINE'                => ($poster_id == ANONYMOUS || !$config['load_onlinetrack']) ? false : (($user_cache[$poster_id]['online']) ? true : false),
1947  
1948          'U_EDIT'            => ($edit_allowed) ? append_sid("{$phpbb_root_path}posting.$phpEx", "mode=edit&amp;f=$forum_id&amp;p={$row['post_id']}") : '',
1949          'U_QUOTE'            => ($quote_allowed) ? append_sid("{$phpbb_root_path}posting.$phpEx", "mode=quote&amp;f=$forum_id&amp;p={$row['post_id']}") : '',
1950          '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) : '',
1951          'U_DELETE'            => ($delete_allowed) ? append_sid("{$phpbb_root_path}posting.$phpEx", 'mode=' . (($softdelete_allowed) ? 'soft_delete' : 'delete') . "&amp;f=$forum_id&amp;p={$row['post_id']}") : '',
1952  
1953          'U_SEARCH'        => $user_cache[$poster_id]['search'],
1954          'U_PM'            => $u_pm,
1955          'U_EMAIL'        => $user_cache[$poster_id]['email'],
1956          'U_JABBER'        => $user_cache[$poster_id]['jabber'],
1957  
1958          'U_APPROVE_ACTION'        => append_sid("{$phpbb_root_path}mcp.$phpEx", "i=queue&amp;p={$row['post_id']}&amp;f=$forum_id&amp;redirect=" . urlencode(str_replace('&amp;', '&', $viewtopic_url . '&amp;p=' . $row['post_id'] . '#p' . $row['post_id']))),
1959          'U_REPORT'            => ($auth->acl_get('f_report', $forum_id)) ? append_sid("{$phpbb_root_path}report.$phpEx", 'f=' . $forum_id . '&amp;p=' . $row['post_id']) : '',
1960          '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) : '',
1961          '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) : '',
1962          'U_MCP_RESTORE'        => ($auth->acl_get('m_approve', $forum_id)) ? append_sid("{$phpbb_root_path}mcp.$phpEx", 'i=queue&amp;mode=' . (($topic_data['topic_visibility'] != ITEM_DELETED) ? 'deleted_posts' : 'deleted_topics') . '&amp;f=' . $forum_id . '&amp;p=' . $row['post_id'], true, $user->session_id) : '',
1963          'U_MINI_POST'        => append_sid("{$phpbb_root_path}viewtopic.$phpEx", 'p=' . $row['post_id']) . '#p' . $row['post_id'],
1964          'U_NEXT_POST_ID'    => ($i < $i_total && isset($rowset[$post_list[$i + 1]])) ? $rowset[$post_list[$i + 1]]['post_id'] : '',
1965          'U_PREV_POST_ID'    => $prev_post_id,
1966          '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) : '',
1967          '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) : '',
1968  
1969          'POST_ID'            => $row['post_id'],
1970          'POST_NUMBER'        => $i + $start + 1,
1971          'POSTER_ID'            => $poster_id,
1972  
1973          'S_HAS_ATTACHMENTS'    => (!empty($attachments[$row['post_id']])) ? true : false,
1974          'S_MULTIPLE_ATTACHMENTS'    => !empty($attachments[$row['post_id']]) && sizeof($attachments[$row['post_id']]) > 1,
1975          'S_POST_UNAPPROVED'    => ($row['post_visibility'] == ITEM_UNAPPROVED || $row['post_visibility'] == ITEM_REAPPROVE) ? true : false,
1976          'S_POST_DELETED'    => ($row['post_visibility'] == ITEM_DELETED) ? true : false,
1977          'L_POST_DELETED_MESSAGE'    => $l_deleted_message,
1978          'S_POST_REPORTED'    => ($row['post_reported'] && $auth->acl_get('m_report', $forum_id)) ? true : false,
1979          'S_DISPLAY_NOTICE'    => $display_notice && $row['post_attachment'],
1980          'S_FRIEND'            => ($row['friend']) ? true : false,
1981          'S_UNREAD_POST'        => $post_unread,
1982          'S_FIRST_UNREAD'    => $s_first_unread,
1983          'S_CUSTOM_FIELDS'    => (isset($cp_row['row']) && sizeof($cp_row['row'])) ? true : false,
1984          'S_TOPIC_POSTER'    => ($topic_data['topic_poster'] == $poster_id) ? true : false,
1985  
1986          'S_IGNORE_POST'        => ($row['foe']) ? true : false,
1987          'L_IGNORE_POST'        => ($row['foe']) ? sprintf($user->lang['POST_BY_FOE'], get_username_string('full', $poster_id, $row['username'], $row['user_colour'], $row['post_username'])) : '',
1988          'S_POST_HIDDEN'        => $row['hide_post'],
1989          'L_POST_DISPLAY'    => ($row['hide_post']) ? $user->lang('POST_DISPLAY', '<a class="display_post" data-post-id="' . $row['post_id'] . '" href="' . $viewtopic_url . "&amp;p={$row['post_id']}&amp;view=show#p{$row['post_id']}" . '">', '</a>') : '',
1990          'S_DELETE_PERMANENT'    => $permanent_delete_allowed,
1991      );
1992  
1993      $user_poster_data = $user_cache[$poster_id];
1994  
1995      $current_row_number = $i;
1996  
1997      /**
1998      * Modify the posts template block
1999      *
2000      * @event core.viewtopic_modify_post_row
2001      * @var    int        start                Start item of this page
2002      * @var    int        current_row_number    Number of the post on this page
2003      * @var    int        end                    Number of posts on this page
2004      * @var    int        total_posts            Total posts count
2005      * @var    int        poster_id            Post author id
2006      * @var    array    row                    Array with original post and user data
2007      * @var    array    cp_row                Custom profile field data of the poster
2008      * @var    array    attachments            List of attachments
2009      * @var    array    user_poster_data    Poster's data from user cache
2010      * @var    array    post_row            Template block array of the post
2011      * @var    array    topic_data            Array with topic data
2012      * @since 3.1.0-a1
2013      * @changed 3.1.0-a3 Added vars start, current_row_number, end, attachments
2014      * @changed 3.1.0-b3 Added topic_data array, total_posts
2015      * @changed 3.1.0-RC3 Added poster_id
2016      */
2017      $vars = array(
2018          'start',
2019          'current_row_number',
2020          'end',
2021          'total_posts',
2022          'poster_id',
2023          'row',
2024          'cp_row',
2025          'attachments',
2026          'user_poster_data',
2027          'post_row',
2028          'topic_data',
2029      );
2030      extract($phpbb_dispatcher->trigger_event('core.viewtopic_modify_post_row', compact($vars)));
2031  
2032      $i = $current_row_number;
2033  
2034      if (isset($cp_row['row']) && sizeof($cp_row['row']))
2035      {
2036          $post_row = array_merge($post_row, $cp_row['row']);
2037      }
2038  
2039      // Dump vars into template
2040      $template->assign_block_vars('postrow', $post_row);
2041  
2042      $contact_fields = array(
2043          array(
2044              'ID'        => 'pm',
2045              'NAME'         => $user->lang['SEND_PRIVATE_MESSAGE'],
2046              'U_CONTACT'    => $u_pm,
2047          ),
2048          array(
2049              'ID'        => 'email',
2050              'NAME'        => $user->lang['SEND_EMAIL'],
2051              'U_CONTACT'    => $user_cache[$poster_id]['email'],
2052          ),
2053          array(
2054              'ID'        => 'jabber',
2055              'NAME'        => $user->lang['JABBER'],
2056              'U_CONTACT'    => $user_cache[$poster_id]['jabber'],
2057          ),
2058      );
2059  
2060      foreach ($contact_fields as $field)
2061      {
2062          if ($field['U_CONTACT'])
2063          {
2064              $template->assign_block_vars('postrow.contact', $field);
2065          }
2066      }
2067  
2068      if (!empty($cp_row['blockrow']))
2069      {
2070          foreach ($cp_row['blockrow'] as $field_data)
2071          {
2072              $template->assign_block_vars('postrow.custom_fields', $field_data);
2073  
2074              if ($field_data['S_PROFILE_CONTACT'])
2075              {
2076                  $template->assign_block_vars('postrow.contact', array(
2077                      'ID'        => $field_data['PROFILE_FIELD_IDENT'],
2078                      'NAME'        => $field_data['PROFILE_FIELD_NAME'],
2079                      'U_CONTACT'    => $field_data['PROFILE_FIELD_CONTACT'],
2080                  ));
2081              }
2082          }
2083      }
2084  
2085      // Display not already displayed Attachments for this post, we already parsed them. ;)
2086      if (!empty($attachments[$row['post_id']]))
2087      {
2088          foreach ($attachments[$row['post_id']] as $attachment)
2089          {
2090              $template->assign_block_vars('postrow.attachment', array(
2091                  'DISPLAY_ATTACHMENT'    => $attachment)
2092              );
2093          }
2094      }
2095  
2096      $current_row_number = $i;
2097  
2098      /**
2099      * Event after the post data has been assigned to the template
2100      *
2101      * @event core.viewtopic_post_row_after
2102      * @var    int        start                Start item of this page
2103      * @var    int        current_row_number    Number of the post on this page
2104      * @var    int        end                    Number of posts on this page
2105      * @var    int        total_posts            Total posts count
2106      * @var    array    row                    Array with original post and user data
2107      * @var    array    cp_row                Custom profile field data of the poster
2108      * @var    array    attachments            List of attachments
2109      * @var    array    user_poster_data    Poster's data from user cache
2110      * @var    array    post_row            Template block array of the post
2111      * @var    array    topic_data            Array with topic data
2112      * @since 3.1.0-a3
2113      * @changed 3.1.0-b3 Added topic_data array, total_posts
2114      */
2115      $vars = array(
2116          'start',
2117          'current_row_number',
2118          'end',
2119          'total_posts',
2120          'row',
2121          'cp_row',
2122          'attachments',
2123          'user_poster_data',
2124          'post_row',
2125          'topic_data',
2126      );
2127      extract($phpbb_dispatcher->trigger_event('core.viewtopic_post_row_after', compact($vars)));
2128  
2129      $i = $current_row_number;
2130  
2131      $prev_post_id = $row['post_id'];
2132  
2133      unset($rowset[$post_list[$i]]);
2134      unset($attachments[$row['post_id']]);
2135  }
2136  unset($rowset, $user_cache);
2137  
2138  // Update topic view and if necessary attachment view counters ... but only for humans and if this is the first 'page view'
2139  if (isset($user->data['session_page']) && !$user->data['is_bot'] && (strpos($user->data['session_page'], '&t=' . $topic_id) === false || isset($user->data['session_created'])))
2140  {
2141      $sql = 'UPDATE ' . TOPICS_TABLE . '
2142          SET topic_views = topic_views + 1, topic_last_view_time = ' . time() . "
2143          WHERE topic_id = $topic_id";
2144      $db->sql_query($sql);
2145  
2146      // Update the attachment download counts
2147      if (sizeof($update_count))
2148      {
2149          $sql = 'UPDATE ' . ATTACHMENTS_TABLE . '
2150              SET download_count = download_count + 1
2151              WHERE ' . $db->sql_in_set('attach_id', array_unique($update_count));
2152          $db->sql_query($sql);
2153      }
2154  }
2155  
2156  // Only mark topic if it's currently unread. Also make sure we do not set topic tracking back if earlier pages are viewed.
2157  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])
2158  {
2159      markread('topic', $forum_id, $topic_id, $max_post_time);
2160  
2161      // Update forum info
2162      $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);
2163  }
2164  else
2165  {
2166      $all_marked_read = true;
2167  }
2168  
2169  // If there are absolutely no more unread posts in this forum
2170  // and unread posts shown, we can safely show the #unread link
2171  if ($all_marked_read)
2172  {
2173      if ($post_unread)
2174      {
2175          $template->assign_vars(array(
2176              'U_VIEW_UNREAD_POST'    => '#unread',
2177          ));
2178      }
2179      else if (isset($topic_tracking_info[$topic_id]) && $topic_data['topic_last_post_time'] > $topic_tracking_info[$topic_id])
2180      {
2181          $template->assign_vars(array(
2182              'U_VIEW_UNREAD_POST'    => append_sid("{$phpbb_root_path}viewtopic.$phpEx", "f=$forum_id&amp;t=$topic_id&amp;view=unread") . '#unread',
2183          ));
2184      }
2185  }
2186  else if (!$all_marked_read)
2187  {
2188      $last_page = ((floor($start / $config['posts_per_page']) + 1) == max(ceil($total_posts / $config['posts_per_page']), 1)) ? true : false;
2189  
2190      // What can happen is that we are at the last displayed page. If so, we also display the #unread link based in $post_unread
2191      if ($last_page && $post_unread)
2192      {
2193          $template->assign_vars(array(
2194              'U_VIEW_UNREAD_POST'    => '#unread',
2195          ));
2196      }
2197      else if (!$last_page)
2198      {
2199          $template->assign_vars(array(
2200              'U_VIEW_UNREAD_POST'    => append_sid("{$phpbb_root_path}viewtopic.$phpEx", "f=$forum_id&amp;t=$topic_id&amp;view=unread") . '#unread',
2201          ));
2202      }
2203  }
2204  
2205  // let's set up quick_reply
2206  $s_quick_reply = false;
2207  if ($user->data['is_registered'] && $config['allow_quick_reply'] && ($topic_data['forum_flags'] & FORUM_FLAG_QUICK_REPLY) && $auth->acl_get('f_reply', $forum_id))
2208  {
2209      // Quick reply enabled forum
2210      $s_quick_reply = (($topic_data['forum_status'] == ITEM_UNLOCKED && $topic_data['topic_status'] == ITEM_UNLOCKED) || $auth->acl_get('m_edit', $forum_id)) ? true : false;
2211  }
2212  
2213  if ($s_can_vote || $s_quick_reply)
2214  {
2215      add_form_key('posting');
2216  
2217      if ($s_quick_reply)
2218      {
2219          $s_attach_sig    = $config['allow_sig'] && $user->optionget('attachsig') && $auth->acl_get('f_sigs', $forum_id) && $auth->acl_get('u_sig');
2220          $s_smilies        = $config['allow_smilies'] && $user->optionget('smilies') && $auth->acl_get('f_smilies', $forum_id);
2221          $s_bbcode        = $config['allow_bbcode'] && $user->optionget('bbcode') && $auth->acl_get('f_bbcode', $forum_id);
2222          $s_notify        = $config['allow_topic_notify'] && ($user->data['user_notify'] || $s_watching_topic['is_watching']);
2223  
2224          $qr_hidden_fields = array(
2225              'topic_cur_post_id'        => (int) $topic_data['topic_last_post_id'],
2226              'lastclick'                => (int) time(),
2227              'topic_id'                => (int) $topic_data['topic_id'],
2228              'forum_id'                => (int) $forum_id,
2229          );
2230  
2231          // Originally we use checkboxes and check with isset(), so we only provide them if they would be checked
2232          (!$s_bbcode)                    ? $qr_hidden_fields['disable_bbcode'] = 1        : true;
2233          (!$s_smilies)                    ? $qr_hidden_fields['disable_smilies'] = 1        : true;
2234          (!$config['allow_post_links'])    ? $qr_hidden_fields['disable_magic_url'] = 1    : true;
2235          ($s_attach_sig)                    ? $qr_hidden_fields['attach_sig'] = 1            : true;
2236          ($s_notify)                        ? $qr_hidden_fields['notify'] = 1                : true;
2237          ($topic_data['topic_status'] == ITEM_LOCKED) ? $qr_hidden_fields['lock_topic'] = 1 : true;
2238  
2239          $template->assign_vars(array(
2240              'S_QUICK_REPLY'            => true,
2241              'U_QR_ACTION'            => append_sid("{$phpbb_root_path}posting.$phpEx", "mode=reply&amp;f=$forum_id&amp;t=$topic_id"),
2242              'QR_HIDDEN_FIELDS'        => build_hidden_fields($qr_hidden_fields),
2243              'SUBJECT'                => 'Re: ' . censor_text($topic_data['topic_title']),
2244          ));
2245      }
2246  }
2247  // now I have the urge to wash my hands :(
2248  
2249  
2250  // We overwrite $_REQUEST['f'] if there is no forum specified
2251  // to be able to display the correct online list.
2252  // One downside is that the user currently viewing this topic/post is not taken into account.
2253  if (!request_var('f', 0))
2254  {
2255      $request->overwrite('f', $forum_id);
2256  }
2257  
2258  // We need to do the same with the topic_id. See #53025.
2259  if (!request_var('t', 0) && !empty($topic_id))
2260  {
2261      $request->overwrite('t', $topic_id);
2262  }
2263  
2264  $page_title = $topic_data['topic_title'] . ($start ? ' - ' . sprintf($user->lang['PAGE_TITLE_NUMBER'], $pagination->get_on_page($config['posts_per_page'], $start)) : '');
2265  
2266  /**
2267  * You can use this event to modify the page title of the viewtopic page
2268  *
2269  * @event core.viewtopic_modify_page_title
2270  * @var    string    page_title        Title of the viewtopic page
2271  * @var    array    topic_data        Array with topic data
2272  * @var    int        forum_id        Forum ID of the topic
2273  * @var    int        start            Start offset used to calculate the page
2274  * @var    array    post_list        Array with post_ids we are going to display
2275  * @since 3.1.0-a1
2276  * @changed 3.1.0-RC4 Added post_list var
2277  */
2278  $vars = array('page_title', 'topic_data', 'forum_id', 'start', 'post_list');
2279  extract($phpbb_dispatcher->trigger_event('core.viewtopic_modify_page_title', compact($vars)));
2280  
2281  // Output the page
2282  page_header($page_title, true, $forum_id);
2283  
2284  $template->set_filenames(array(
2285      'body' => ($view == 'print') ? 'viewtopic_print.html' : 'viewtopic_body.html')
2286  );
2287  make_jumpbox(append_sid("{$phpbb_root_path}viewforum.$phpEx"), $forum_id);
2288  
2289  page_footer();


Generated: Thu Jan 11 00:25:41 2018 Cross-referenced by PHPXref 0.7.1