[ Index ]

PHP Cross Reference of phpBB-3.1.10-deutsch

title

Body

[close]

/ -> viewtopic.php (source)

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


Generated: Sun Feb 19 19:52:41 2017 Cross-referenced by PHPXref 0.7.1