[ Index ]

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


Generated: Thu Jan 11 23:14:31 2018 Cross-referenced by PHPXref 0.7.1