[ Index ]

PHP Cross Reference of phpBB-3.2.2-deutsch

title

Body

[close]

/includes/ -> functions_posting.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  if (!defined('IN_PHPBB'))
  18  {
  19      exit;
  20  }
  21  
  22  /**
  23  * Fill smiley templates (or just the variables) with smilies, either in a window or inline
  24  */
  25  function generate_smilies($mode, $forum_id)
  26  {
  27      global $db, $user, $config, $template, $phpbb_dispatcher, $request;
  28      global $phpEx, $phpbb_root_path, $phpbb_container, $phpbb_path_helper;
  29  
  30      /* @var $pagination \phpbb\pagination */
  31      $pagination = $phpbb_container->get('pagination');
  32      $base_url = append_sid("{$phpbb_root_path}posting.$phpEx", 'mode=smilies&amp;f=' . $forum_id);
  33      $start = $request->variable('start', 0);
  34  
  35      if ($mode == 'window')
  36      {
  37          if ($forum_id)
  38          {
  39              $sql = 'SELECT forum_style
  40                  FROM ' . FORUMS_TABLE . "
  41                  WHERE forum_id = $forum_id";
  42              $result = $db->sql_query_limit($sql, 1);
  43              $row = $db->sql_fetchrow($result);
  44              $db->sql_freeresult($result);
  45  
  46              $user->setup('posting', (int) $row['forum_style']);
  47          }
  48          else
  49          {
  50              $user->setup('posting');
  51          }
  52  
  53          page_header($user->lang['SMILIES']);
  54  
  55          $sql = 'SELECT COUNT(smiley_id) AS item_count
  56              FROM ' . SMILIES_TABLE . '
  57              GROUP BY smiley_url';
  58          $result = $db->sql_query($sql, 3600);
  59  
  60          $smiley_count = 0;
  61          while ($row = $db->sql_fetchrow($result))
  62          {
  63              ++$smiley_count;
  64          }
  65          $db->sql_freeresult($result);
  66  
  67          $template->set_filenames(array(
  68              'body' => 'posting_smilies.html')
  69          );
  70  
  71          $start = $pagination->validate_start($start, $config['smilies_per_page'], $smiley_count);
  72          $pagination->generate_template_pagination($base_url, 'pagination', 'start', $smiley_count, $config['smilies_per_page'], $start);
  73      }
  74  
  75      $display_link = false;
  76      if ($mode == 'inline')
  77      {
  78          $sql = 'SELECT smiley_id
  79              FROM ' . SMILIES_TABLE . '
  80              WHERE display_on_posting = 0';
  81          $result = $db->sql_query_limit($sql, 1, 0, 3600);
  82  
  83          if ($row = $db->sql_fetchrow($result))
  84          {
  85              $display_link = true;
  86          }
  87          $db->sql_freeresult($result);
  88      }
  89  
  90      if ($mode == 'window')
  91      {
  92          $sql = 'SELECT smiley_url, MIN(emotion) as emotion, MIN(code) AS code, smiley_width, smiley_height, MIN(smiley_order) AS min_smiley_order
  93              FROM ' . SMILIES_TABLE . '
  94              GROUP BY smiley_url, smiley_width, smiley_height
  95              ORDER BY min_smiley_order';
  96          $result = $db->sql_query_limit($sql, $config['smilies_per_page'], $start, 3600);
  97      }
  98      else
  99      {
 100          $sql = 'SELECT *
 101              FROM ' . SMILIES_TABLE . '
 102              WHERE display_on_posting = 1
 103              ORDER BY smiley_order';
 104          $result = $db->sql_query($sql, 3600);
 105      }
 106  
 107      $smilies = array();
 108      while ($row = $db->sql_fetchrow($result))
 109      {
 110          if (empty($smilies[$row['smiley_url']]))
 111          {
 112              $smilies[$row['smiley_url']] = $row;
 113          }
 114      }
 115      $db->sql_freeresult($result);
 116  
 117      if (count($smilies))
 118      {
 119          $root_path = (defined('PHPBB_USE_BOARD_URL_PATH') && PHPBB_USE_BOARD_URL_PATH) ? generate_board_url() . '/' : $phpbb_path_helper->get_web_root_path();
 120  
 121          foreach ($smilies as $row)
 122          {
 123              /**
 124              * Modify smiley root path before populating smiley list
 125              *
 126              * @event core.generate_smilies_before
 127              * @var string  root_path root_path for smilies
 128              * @since 3.1.11-RC1
 129              */
 130              $vars = array('root_path');
 131              extract($phpbb_dispatcher->trigger_event('core.generate_smilies_before', compact($vars)));
 132              $template->assign_block_vars('smiley', array(
 133                  'SMILEY_CODE'    => $row['code'],
 134                  'A_SMILEY_CODE'    => addslashes($row['code']),
 135                  'SMILEY_IMG'    => $root_path . $config['smilies_path'] . '/' . $row['smiley_url'],
 136                  'SMILEY_WIDTH'    => $row['smiley_width'],
 137                  'SMILEY_HEIGHT'    => $row['smiley_height'],
 138                  'SMILEY_DESC'    => $row['emotion'])
 139              );
 140          }
 141      }
 142  
 143      /**
 144      * This event is called after the smilies are populated
 145      *
 146      * @event core.generate_smilies_after
 147      * @var    string    mode            Mode of the smilies: window|inline
 148      * @var    int        forum_id        The forum ID we are currently in
 149      * @var    bool    display_link    Shall we display the "more smilies" link?
 150      * @since 3.1.0-a1
 151      */
 152      $vars = array('mode', 'forum_id', 'display_link');
 153      extract($phpbb_dispatcher->trigger_event('core.generate_smilies_after', compact($vars)));
 154  
 155      if ($mode == 'inline' && $display_link)
 156      {
 157          $template->assign_vars(array(
 158              'S_SHOW_SMILEY_LINK'     => true,
 159              'U_MORE_SMILIES'         => $base_url,
 160          ));
 161      }
 162  
 163      if ($mode == 'window')
 164      {
 165          page_footer();
 166      }
 167  }
 168  
 169  /**
 170  * Update last post information
 171  * Should be used instead of sync() if only the last post information are out of sync... faster
 172  *
 173  * @param    string    $type                Can be forum|topic
 174  * @param    mixed    $ids                topic/forum ids
 175  * @param    bool    $return_update_sql    true: SQL query shall be returned, false: execute SQL
 176  */
 177  function update_post_information($type, $ids, $return_update_sql = false)
 178  {
 179      global $db;
 180  
 181      if (empty($ids))
 182      {
 183          return;
 184      }
 185      if (!is_array($ids))
 186      {
 187          $ids = array($ids);
 188      }
 189  
 190      $update_sql = $empty_forums = $not_empty_forums = array();
 191  
 192      if ($type != 'topic')
 193      {
 194          $topic_join = ', ' . TOPICS_TABLE . ' t';
 195          $topic_condition = 'AND t.topic_id = p.topic_id AND t.topic_visibility = ' . ITEM_APPROVED;
 196      }
 197      else
 198      {
 199          $topic_join = '';
 200          $topic_condition = '';
 201      }
 202  
 203      if (count($ids) == 1)
 204      {
 205          $sql = 'SELECT MAX(p.post_id) as last_post_id
 206              FROM ' . POSTS_TABLE . " p $topic_join
 207              WHERE " . $db->sql_in_set('p.' . $type . '_id', $ids) . "
 208                  $topic_condition
 209                  AND p.post_visibility = " . ITEM_APPROVED;
 210      }
 211      else
 212      {
 213          $sql = 'SELECT p.' . $type . '_id, MAX(p.post_id) as last_post_id
 214              FROM ' . POSTS_TABLE . " p $topic_join
 215              WHERE " . $db->sql_in_set('p.' . $type . '_id', $ids) . "
 216                  $topic_condition
 217                  AND p.post_visibility = " . ITEM_APPROVED . "
 218              GROUP BY p.{$type}_id";
 219      }
 220      $result = $db->sql_query($sql);
 221  
 222      $last_post_ids = array();
 223      while ($row = $db->sql_fetchrow($result))
 224      {
 225          if (count($ids) == 1)
 226          {
 227              $row[$type . '_id'] = $ids[0];
 228          }
 229  
 230          if ($type == 'forum')
 231          {
 232              $not_empty_forums[] = $row['forum_id'];
 233  
 234              if (empty($row['last_post_id']))
 235              {
 236                  $empty_forums[] = $row['forum_id'];
 237              }
 238          }
 239  
 240          $last_post_ids[] = $row['last_post_id'];
 241      }
 242      $db->sql_freeresult($result);
 243  
 244      if ($type == 'forum')
 245      {
 246          $empty_forums = array_merge($empty_forums, array_diff($ids, $not_empty_forums));
 247  
 248          foreach ($empty_forums as $void => $forum_id)
 249          {
 250              $update_sql[$forum_id][] = 'forum_last_post_id = 0';
 251              $update_sql[$forum_id][] = "forum_last_post_subject = ''";
 252              $update_sql[$forum_id][] = 'forum_last_post_time = 0';
 253              $update_sql[$forum_id][] = 'forum_last_poster_id = 0';
 254              $update_sql[$forum_id][] = "forum_last_poster_name = ''";
 255              $update_sql[$forum_id][] = "forum_last_poster_colour = ''";
 256          }
 257      }
 258  
 259      if (count($last_post_ids))
 260      {
 261          $sql = 'SELECT p.' . $type . '_id, p.post_id, p.post_subject, p.post_time, p.poster_id, p.post_username, u.user_id, u.username, u.user_colour
 262              FROM ' . POSTS_TABLE . ' p, ' . USERS_TABLE . ' u
 263              WHERE p.poster_id = u.user_id
 264                  AND ' . $db->sql_in_set('p.post_id', $last_post_ids);
 265          $result = $db->sql_query($sql);
 266  
 267          while ($row = $db->sql_fetchrow($result))
 268          {
 269              $update_sql[$row["{$type}_id"]][] = $type . '_last_post_id = ' . (int) $row['post_id'];
 270              $update_sql[$row["{$type}_id"]][] = "{$type}_last_post_subject = '" . $db->sql_escape($row['post_subject']) . "'";
 271              $update_sql[$row["{$type}_id"]][] = $type . '_last_post_time = ' . (int) $row['post_time'];
 272              $update_sql[$row["{$type}_id"]][] = $type . '_last_poster_id = ' . (int) $row['poster_id'];
 273              $update_sql[$row["{$type}_id"]][] = "{$type}_last_poster_colour = '" . $db->sql_escape($row['user_colour']) . "'";
 274              $update_sql[$row["{$type}_id"]][] = "{$type}_last_poster_name = '" . (($row['poster_id'] == ANONYMOUS) ? $db->sql_escape($row['post_username']) : $db->sql_escape($row['username'])) . "'";
 275          }
 276          $db->sql_freeresult($result);
 277      }
 278      unset($empty_forums, $ids, $last_post_ids);
 279  
 280      if ($return_update_sql || !count($update_sql))
 281      {
 282          return $update_sql;
 283      }
 284  
 285      $table = ($type == 'forum') ? FORUMS_TABLE : TOPICS_TABLE;
 286  
 287      foreach ($update_sql as $update_id => $update_sql_ary)
 288      {
 289          $sql = "UPDATE $table
 290              SET " . implode(', ', $update_sql_ary) . "
 291              WHERE {$type}_id = $update_id";
 292          $db->sql_query($sql);
 293      }
 294  
 295      return;
 296  }
 297  
 298  /**
 299  * Generate Topic Icons for display
 300  */
 301  function posting_gen_topic_icons($mode, $icon_id)
 302  {
 303      global $phpbb_root_path, $config, $template, $cache;
 304  
 305      // Grab icons
 306      $icons = $cache->obtain_icons();
 307  
 308      if (!$icon_id)
 309      {
 310          $template->assign_var('S_NO_ICON_CHECKED', ' checked="checked"');
 311      }
 312  
 313      if (count($icons))
 314      {
 315          $root_path = (defined('PHPBB_USE_BOARD_URL_PATH') && PHPBB_USE_BOARD_URL_PATH) ? generate_board_url() . '/' : $phpbb_root_path;
 316  
 317          foreach ($icons as $id => $data)
 318          {
 319              if ($data['display'])
 320              {
 321                  $template->assign_block_vars('topic_icon', array(
 322                      'ICON_ID'        => $id,
 323                      'ICON_IMG'        => $root_path . $config['icons_path'] . '/' . $data['img'],
 324                      'ICON_WIDTH'    => $data['width'],
 325                      'ICON_HEIGHT'    => $data['height'],
 326                      'ICON_ALT'        => $data['alt'],
 327  
 328                      'S_CHECKED'            => ($id == $icon_id) ? true : false,
 329                      'S_ICON_CHECKED'    => ($id == $icon_id) ? ' checked="checked"' : '')
 330                  );
 331              }
 332          }
 333  
 334          return true;
 335      }
 336  
 337      return false;
 338  }
 339  
 340  /**
 341  * Build topic types able to be selected
 342  */
 343  function posting_gen_topic_types($forum_id, $cur_topic_type = POST_NORMAL)
 344  {
 345      global $auth, $user, $template;
 346  
 347      $toggle = false;
 348  
 349      $topic_types = array(
 350          'sticky'            => array('const' => POST_STICKY, 'lang' => 'POST_STICKY'),
 351          'announce'            => array('const' => POST_ANNOUNCE, 'lang' => 'POST_ANNOUNCEMENT'),
 352          'announce_global'    => array('const' => POST_GLOBAL, 'lang' => 'POST_GLOBAL')
 353      );
 354  
 355      $topic_type_array = array();
 356  
 357      foreach ($topic_types as $auth_key => $topic_value)
 358      {
 359          if ($auth->acl_get('f_' . $auth_key, $forum_id))
 360          {
 361              $toggle = true;
 362  
 363              $topic_type_array[] = array(
 364                  'VALUE'            => $topic_value['const'],
 365                  'S_CHECKED'        => ($cur_topic_type == $topic_value['const']) ? ' checked="checked"' : '',
 366                  'L_TOPIC_TYPE'    => $user->lang[$topic_value['lang']]
 367              );
 368          }
 369      }
 370  
 371      if ($toggle)
 372      {
 373          $topic_type_array = array_merge(array(0 => array(
 374              'VALUE'            => POST_NORMAL,
 375              'S_CHECKED'        => ($cur_topic_type == POST_NORMAL) ? ' checked="checked"' : '',
 376              'L_TOPIC_TYPE'    => $user->lang['POST_NORMAL'])),
 377  
 378              $topic_type_array
 379          );
 380  
 381          foreach ($topic_type_array as $array)
 382          {
 383              $template->assign_block_vars('topic_type', $array);
 384          }
 385  
 386          $template->assign_vars(array(
 387              'S_TOPIC_TYPE_STICKY'    => ($auth->acl_get('f_sticky', $forum_id)),
 388              'S_TOPIC_TYPE_ANNOUNCE'    => ($auth->acl_gets('f_announce', 'f_announce_global', $forum_id)),
 389          ));
 390      }
 391  
 392      return $toggle;
 393  }
 394  
 395  //
 396  // Attachment related functions
 397  //
 398  
 399  /**
 400  * Upload Attachment - filedata is generated here
 401  * Uses upload class
 402  *
 403  * @deprecated 3.2.0-a1 (To be removed: 3.4.0)
 404  *
 405  * @param string            $form_name        The form name of the file upload input
 406  * @param int            $forum_id        The id of the forum
 407  * @param bool            $local            Whether the file is local or not
 408  * @param string            $local_storage    The path to the local file
 409  * @param bool            $is_message        Whether it is a PM or not
 410  * @param array            $local_filedata    A filespec object created for the local file
 411  *
 412  * @return array File data array
 413  */
 414  function upload_attachment($form_name, $forum_id, $local = false, $local_storage = '', $is_message = false, $local_filedata = false)
 415  {
 416      global $phpbb_container;
 417  
 418      /** @var \phpbb\attachment\manager $attachment_manager */
 419      $attachment_manager = $phpbb_container->get('attachment.manager');
 420      $file = $attachment_manager->upload($form_name, $forum_id, $local, $local_storage, $is_message, $local_filedata);
 421      unset($attachment_manager);
 422  
 423      return $file;
 424  }
 425  
 426  /**
 427  * Calculate the needed size for Thumbnail
 428  */
 429  function get_img_size_format($width, $height)
 430  {
 431      global $config;
 432  
 433      // Maximum Width the Image can take
 434      $max_width = ($config['img_max_thumb_width']) ? $config['img_max_thumb_width'] : 400;
 435  
 436      if ($width > $height)
 437      {
 438          return array(
 439              round($width * ($max_width / $width)),
 440              round($height * ($max_width / $width))
 441          );
 442      }
 443      else
 444      {
 445          return array(
 446              round($width * ($max_width / $height)),
 447              round($height * ($max_width / $height))
 448          );
 449      }
 450  }
 451  
 452  /**
 453  * Return supported image types
 454  */
 455  function get_supported_image_types($type = false)
 456  {
 457      if (@extension_loaded('gd'))
 458      {
 459          $format = imagetypes();
 460          $new_type = 0;
 461  
 462          if ($type !== false)
 463          {
 464              // Type is one of the IMAGETYPE constants - it is fetched from getimagesize()
 465              switch ($type)
 466              {
 467                  // GIF
 468                  case IMAGETYPE_GIF:
 469                      $new_type = ($format & IMG_GIF) ? IMG_GIF : false;
 470                  break;
 471  
 472                  // JPG, JPC, JP2
 473                  case IMAGETYPE_JPEG:
 474                  case IMAGETYPE_JPC:
 475                  case IMAGETYPE_JPEG2000:
 476                  case IMAGETYPE_JP2:
 477                  case IMAGETYPE_JPX:
 478                  case IMAGETYPE_JB2:
 479                      $new_type = ($format & IMG_JPG) ? IMG_JPG : false;
 480                  break;
 481  
 482                  // PNG
 483                  case IMAGETYPE_PNG:
 484                      $new_type = ($format & IMG_PNG) ? IMG_PNG : false;
 485                  break;
 486  
 487                  // WBMP
 488                  case IMAGETYPE_WBMP:
 489                      $new_type = ($format & IMG_WBMP) ? IMG_WBMP : false;
 490                  break;
 491              }
 492          }
 493          else
 494          {
 495              $new_type = array();
 496              $go_through_types = array(IMG_GIF, IMG_JPG, IMG_PNG, IMG_WBMP);
 497  
 498              foreach ($go_through_types as $check_type)
 499              {
 500                  if ($format & $check_type)
 501                  {
 502                      $new_type[] = $check_type;
 503                  }
 504              }
 505          }
 506  
 507          return array(
 508              'gd'        => ($new_type) ? true : false,
 509              'format'    => $new_type,
 510              'version'    => (function_exists('imagecreatetruecolor')) ? 2 : 1
 511          );
 512      }
 513  
 514      return array('gd' => false);
 515  }
 516  
 517  /**
 518  * Create Thumbnail
 519  */
 520  function create_thumbnail($source, $destination, $mimetype)
 521  {
 522      global $config, $phpbb_filesystem;
 523  
 524      $min_filesize = (int) $config['img_min_thumb_filesize'];
 525      $img_filesize = (file_exists($source)) ? @filesize($source) : false;
 526  
 527      if (!$img_filesize || $img_filesize <= $min_filesize)
 528      {
 529          return false;
 530      }
 531  
 532      $dimension = @getimagesize($source);
 533  
 534      if ($dimension === false)
 535      {
 536          return false;
 537      }
 538  
 539      list($width, $height, $type, ) = $dimension;
 540  
 541      if (empty($width) || empty($height))
 542      {
 543          return false;
 544      }
 545  
 546      list($new_width, $new_height) = get_img_size_format($width, $height);
 547  
 548      // Do not create a thumbnail if the resulting width/height is bigger than the original one
 549      if ($new_width >= $width && $new_height >= $height)
 550      {
 551          return false;
 552      }
 553  
 554      $used_imagick = false;
 555  
 556      // Only use ImageMagick if defined and the passthru function not disabled
 557      if ($config['img_imagick'] && function_exists('passthru'))
 558      {
 559          if (substr($config['img_imagick'], -1) !== '/')
 560          {
 561              $config['img_imagick'] .= '/';
 562          }
 563  
 564          @passthru(escapeshellcmd($config['img_imagick']) . 'convert' . ((defined('PHP_OS') && preg_match('#^win#i', PHP_OS)) ? '.exe' : '') . ' -quality 85 -geometry ' . $new_width . 'x' . $new_height . ' "' . str_replace('\\', '/', $source) . '" "' . str_replace('\\', '/', $destination) . '"');
 565  
 566          if (file_exists($destination))
 567          {
 568              $used_imagick = true;
 569          }
 570      }
 571  
 572      if (!$used_imagick)
 573      {
 574          $type = get_supported_image_types($type);
 575  
 576          if ($type['gd'])
 577          {
 578              // If the type is not supported, we are not able to create a thumbnail
 579              if ($type['format'] === false)
 580              {
 581                  return false;
 582              }
 583  
 584              switch ($type['format'])
 585              {
 586                  case IMG_GIF:
 587                      $image = @imagecreatefromgif($source);
 588                  break;
 589  
 590                  case IMG_JPG:
 591                      @ini_set('gd.jpeg_ignore_warning', 1);
 592                      $image = @imagecreatefromjpeg($source);
 593                  break;
 594  
 595                  case IMG_PNG:
 596                      $image = @imagecreatefrompng($source);
 597                  break;
 598  
 599                  case IMG_WBMP:
 600                      $image = @imagecreatefromwbmp($source);
 601                  break;
 602              }
 603  
 604              if (empty($image))
 605              {
 606                  return false;
 607              }
 608  
 609              if ($type['version'] == 1)
 610              {
 611                  $new_image = imagecreate($new_width, $new_height);
 612  
 613                  if ($new_image === false)
 614                  {
 615                      return false;
 616                  }
 617  
 618                  imagecopyresized($new_image, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
 619              }
 620              else
 621              {
 622                  $new_image = imagecreatetruecolor($new_width, $new_height);
 623  
 624                  if ($new_image === false)
 625                  {
 626                      return false;
 627                  }
 628  
 629                  // Preserve alpha transparency (png for example)
 630                  @imagealphablending($new_image, false);
 631                  @imagesavealpha($new_image, true);
 632  
 633                  imagecopyresampled($new_image, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
 634              }
 635  
 636              // If we are in safe mode create the destination file prior to using the gd functions to circumvent a PHP bug
 637              if (@ini_get('safe_mode') || @strtolower(ini_get('safe_mode')) == 'on')
 638              {
 639                  @touch($destination);
 640              }
 641  
 642              switch ($type['format'])
 643              {
 644                  case IMG_GIF:
 645                      imagegif($new_image, $destination);
 646                  break;
 647  
 648                  case IMG_JPG:
 649                      imagejpeg($new_image, $destination, 90);
 650                  break;
 651  
 652                  case IMG_PNG:
 653                      imagepng($new_image, $destination);
 654                  break;
 655  
 656                  case IMG_WBMP:
 657                      imagewbmp($new_image, $destination);
 658                  break;
 659              }
 660  
 661              imagedestroy($new_image);
 662          }
 663          else
 664          {
 665              return false;
 666          }
 667      }
 668  
 669      if (!file_exists($destination))
 670      {
 671          return false;
 672      }
 673  
 674      try
 675      {
 676          $phpbb_filesystem->phpbb_chmod($destination, CHMOD_READ | CHMOD_WRITE);
 677      }
 678      catch (\phpbb\filesystem\exception\filesystem_exception $e)
 679      {
 680          // Do nothing
 681      }
 682  
 683      return true;
 684  }
 685  
 686  /**
 687  * Assign Inline attachments (build option fields)
 688  */
 689  function posting_gen_inline_attachments(&$attachment_data)
 690  {
 691      global $template;
 692  
 693      if (count($attachment_data))
 694      {
 695          $s_inline_attachment_options = '';
 696  
 697          foreach ($attachment_data as $i => $attachment)
 698          {
 699              $s_inline_attachment_options .= '<option value="' . $i . '">' . utf8_basename($attachment['real_filename']) . '</option>';
 700          }
 701  
 702          $template->assign_var('S_INLINE_ATTACHMENT_OPTIONS', $s_inline_attachment_options);
 703  
 704          return true;
 705      }
 706  
 707      return false;
 708  }
 709  
 710  /**
 711  * Generate inline attachment entry
 712  */
 713  function posting_gen_attachment_entry($attachment_data, &$filename_data, $show_attach_box = true)
 714  {
 715      global $template, $config, $phpbb_root_path, $phpEx, $user, $phpbb_dispatcher;
 716  
 717      // Some default template variables
 718      $template->assign_vars(array(
 719          'S_SHOW_ATTACH_BOX'    => $show_attach_box,
 720          'S_HAS_ATTACHMENTS'    => count($attachment_data),
 721          'FILESIZE'            => $config['max_filesize'],
 722          'FILE_COMMENT'        => (isset($filename_data['filecomment'])) ? $filename_data['filecomment'] : '',
 723      ));
 724  
 725      if (count($attachment_data))
 726      {
 727          // We display the posted attachments within the desired order.
 728          ($config['display_order']) ? krsort($attachment_data) : ksort($attachment_data);
 729  
 730          foreach ($attachment_data as $count => $attach_row)
 731          {
 732              $hidden = '';
 733              $attachrow_template_vars = array();
 734              $attach_row['real_filename'] = utf8_basename($attach_row['real_filename']);
 735  
 736              foreach ($attach_row as $key => $value)
 737              {
 738                  $hidden .= '<input type="hidden" name="attachment_data[' . $count . '][' . $key . ']" value="' . $value . '" />';
 739              }
 740  
 741              $download_link = append_sid("{$phpbb_root_path}download/file.$phpEx", 'mode=view&amp;id=' . (int) $attach_row['attach_id'], true, ($attach_row['is_orphan']) ? $user->session_id : false);
 742  
 743              $attachrow_template_vars[(int) $attach_row['attach_id']] = array(
 744                  'FILENAME'            => utf8_basename($attach_row['real_filename']),
 745                  'A_FILENAME'        => addslashes(utf8_basename($attach_row['real_filename'])),
 746                  'FILE_COMMENT'        => $attach_row['attach_comment'],
 747                  'ATTACH_ID'            => $attach_row['attach_id'],
 748                  'S_IS_ORPHAN'        => $attach_row['is_orphan'],
 749                  'ASSOC_INDEX'        => $count,
 750                  'FILESIZE'            => get_formatted_filesize($attach_row['filesize']),
 751  
 752                  'U_VIEW_ATTACHMENT'    => $download_link,
 753                  'S_HIDDEN'            => $hidden,
 754              );
 755          }
 756  
 757          /**
 758          * Modify inline attachments template vars
 759          *
 760          * @event core.modify_inline_attachments_template_vars
 761          * @var    array    attachment_data                Array containing attachments data
 762          * @var    array    attachrow_template_vars        Array containing attachments template vars
 763          * @since 3.2.2-RC1
 764          */
 765          $vars = array('attachment_data', 'attachrow_template_vars');
 766          extract($phpbb_dispatcher->trigger_event('core.modify_inline_attachments_template_vars', compact($vars)));
 767  
 768          $template->assign_block_vars_array('attach_row', $attachrow_template_vars);
 769      }
 770  
 771      return count($attachment_data);
 772  }
 773  
 774  //
 775  // General Post functions
 776  //
 777  
 778  /**
 779  * Load Drafts
 780  */
 781  function load_drafts($topic_id = 0, $forum_id = 0, $id = 0, $pm_action = '', $msg_id = 0)
 782  {
 783      global $user, $db, $template, $auth;
 784      global $phpbb_root_path, $phpbb_dispatcher, $phpEx;
 785  
 786      $topic_ids = $forum_ids = $draft_rows = array();
 787  
 788      // Load those drafts not connected to forums/topics
 789      // If forum_id == 0 AND topic_id == 0 then this is a PM draft
 790      if (!$topic_id && !$forum_id)
 791      {
 792          $sql_and = ' AND d.forum_id = 0 AND d.topic_id = 0';
 793      }
 794      else
 795      {
 796          $sql_and = '';
 797          $sql_and .= ($forum_id) ? ' AND d.forum_id = ' . (int) $forum_id : '';
 798          $sql_and .= ($topic_id) ? ' AND d.topic_id = ' . (int) $topic_id : '';
 799      }
 800  
 801      $sql = 'SELECT d.*, f.forum_id, f.forum_name
 802          FROM ' . DRAFTS_TABLE . ' d
 803          LEFT JOIN ' . FORUMS_TABLE . ' f ON (f.forum_id = d.forum_id)
 804              WHERE d.user_id = ' . $user->data['user_id'] . "
 805              $sql_and
 806          ORDER BY d.save_time DESC";
 807      $result = $db->sql_query($sql);
 808  
 809      while ($row = $db->sql_fetchrow($result))
 810      {
 811          if ($row['topic_id'])
 812          {
 813              $topic_ids[] = (int) $row['topic_id'];
 814          }
 815          $draft_rows[] = $row;
 816      }
 817      $db->sql_freeresult($result);
 818  
 819      if (!count($draft_rows))
 820      {
 821          return;
 822      }
 823  
 824      $topic_rows = array();
 825      if (count($topic_ids))
 826      {
 827          $sql = 'SELECT topic_id, forum_id, topic_title, topic_poster
 828              FROM ' . TOPICS_TABLE . '
 829              WHERE ' . $db->sql_in_set('topic_id', array_unique($topic_ids));
 830          $result = $db->sql_query($sql);
 831  
 832          while ($row = $db->sql_fetchrow($result))
 833          {
 834              $topic_rows[$row['topic_id']] = $row;
 835          }
 836          $db->sql_freeresult($result);
 837      }
 838  
 839      /**
 840      * Drafts found and their topics
 841      * Edit $draft_rows in order to add or remove drafts loaded
 842      *
 843      * @event core.load_drafts_draft_list_result
 844      * @var    array    draft_rows            The drafts query result. Includes its forum id and everything about the draft
 845      * @var    array    topic_ids            The list of topics got from the topics table
 846      * @var    array    topic_rows            The topics that draft_rows references
 847      * @since 3.1.0-RC3
 848      */
 849      $vars = array('draft_rows', 'topic_ids', 'topic_rows');
 850      extract($phpbb_dispatcher->trigger_event('core.load_drafts_draft_list_result', compact($vars)));
 851  
 852      unset($topic_ids);
 853  
 854      $template->assign_var('S_SHOW_DRAFTS', true);
 855  
 856      foreach ($draft_rows as $draft)
 857      {
 858          $link_topic = $link_forum = $link_pm = false;
 859          $view_url = $title = '';
 860  
 861          if (isset($topic_rows[$draft['topic_id']])
 862              && (
 863                  ($topic_rows[$draft['topic_id']]['forum_id'] && $auth->acl_get('f_read', $topic_rows[$draft['topic_id']]['forum_id']))
 864                  ||
 865                  (!$topic_rows[$draft['topic_id']]['forum_id'] && $auth->acl_getf_global('f_read'))
 866              ))
 867          {
 868              $topic_forum_id = ($topic_rows[$draft['topic_id']]['forum_id']) ? $topic_rows[$draft['topic_id']]['forum_id'] : $forum_id;
 869  
 870              $link_topic = true;
 871              $view_url = append_sid("{$phpbb_root_path}viewtopic.$phpEx", 'f=' . $topic_forum_id . '&amp;t=' . $draft['topic_id']);
 872              $title = $topic_rows[$draft['topic_id']]['topic_title'];
 873  
 874              $insert_url = append_sid("{$phpbb_root_path}posting.$phpEx", 'f=' . $topic_forum_id . '&amp;t=' . $draft['topic_id'] . '&amp;mode=reply&amp;d=' . $draft['draft_id']);
 875          }
 876          else if ($draft['forum_id'] && $auth->acl_get('f_read', $draft['forum_id']))
 877          {
 878              $link_forum = true;
 879              $view_url = append_sid("{$phpbb_root_path}viewforum.$phpEx", 'f=' . $draft['forum_id']);
 880              $title = $draft['forum_name'];
 881  
 882              $insert_url = append_sid("{$phpbb_root_path}posting.$phpEx", 'f=' . $draft['forum_id'] . '&amp;mode=post&amp;d=' . $draft['draft_id']);
 883          }
 884          else
 885          {
 886              // Either display as PM draft if forum_id and topic_id are empty or if access to the forums has been denied afterwards...
 887              $link_pm = true;
 888              $insert_url = append_sid("{$phpbb_root_path}ucp.$phpEx", "i=$id&amp;mode=compose&amp;d={$draft['draft_id']}" . (($pm_action) ? "&amp;action=$pm_action" : '') . (($msg_id) ? "&amp;p=$msg_id" : ''));
 889          }
 890  
 891          $template->assign_block_vars('draftrow', array(
 892              'DRAFT_ID'        => $draft['draft_id'],
 893              'DATE'            => $user->format_date($draft['save_time']),
 894              'DRAFT_SUBJECT'    => $draft['draft_subject'],
 895  
 896              'TITLE'            => $title,
 897              'U_VIEW'        => $view_url,
 898              'U_INSERT'        => $insert_url,
 899  
 900              'S_LINK_PM'        => $link_pm,
 901              'S_LINK_TOPIC'    => $link_topic,
 902              'S_LINK_FORUM'    => $link_forum)
 903          );
 904      }
 905  }
 906  
 907  /**
 908  * Topic Review
 909  */
 910  function topic_review($topic_id, $forum_id, $mode = 'topic_review', $cur_post_id = 0, $show_quote_button = true)
 911  {
 912      global $user, $auth, $db, $template;
 913      global $config, $phpbb_root_path, $phpEx, $phpbb_container, $phpbb_dispatcher;
 914  
 915      /* @var $phpbb_content_visibility \phpbb\content_visibility */
 916      $phpbb_content_visibility = $phpbb_container->get('content.visibility');
 917      $sql_sort = ($mode == 'post_review') ? 'ASC' : 'DESC';
 918  
 919      // Go ahead and pull all data for this topic
 920      $sql = 'SELECT p.post_id
 921          FROM ' . POSTS_TABLE . ' p' . "
 922          WHERE p.topic_id = $topic_id
 923              AND " . $phpbb_content_visibility->get_visibility_sql('post', $forum_id, 'p.') . '
 924              ' . (($mode == 'post_review') ? " AND p.post_id > $cur_post_id" : '') . '
 925              ' . (($mode == 'post_review_edit') ? " AND p.post_id = $cur_post_id" : '') . '
 926          ORDER BY p.post_time ' . $sql_sort . ', p.post_id ' . $sql_sort;
 927      $result = $db->sql_query_limit($sql, $config['posts_per_page']);
 928  
 929      $post_list = array();
 930  
 931      while ($row = $db->sql_fetchrow($result))
 932      {
 933          $post_list[] = $row['post_id'];
 934      }
 935  
 936      $db->sql_freeresult($result);
 937  
 938      if (!count($post_list))
 939      {
 940          return false;
 941      }
 942  
 943      // Handle 'post_review_edit' like 'post_review' from now on
 944      if ($mode == 'post_review_edit')
 945      {
 946          $mode = 'post_review';
 947      }
 948  
 949      $sql_ary = array(
 950          'SELECT'    => 'u.username, u.user_id, u.user_colour, p.*, z.friend, z.foe, uu.username as post_delete_username, uu.user_colour as post_delete_user_colour',
 951  
 952          'FROM'        => array(
 953              USERS_TABLE        => 'u',
 954              POSTS_TABLE        => 'p',
 955          ),
 956  
 957          'LEFT_JOIN'    => array(
 958              array(
 959                  'FROM'    => array(ZEBRA_TABLE => 'z'),
 960                  'ON'    => 'z.user_id = ' . $user->data['user_id'] . ' AND z.zebra_id = p.poster_id',
 961              ),
 962              array(
 963                  'FROM'    => array(USERS_TABLE => 'uu'),
 964                  'ON'    => 'uu.user_id = p.post_delete_user',
 965              ),
 966          ),
 967  
 968          'WHERE'        => $db->sql_in_set('p.post_id', $post_list) . '
 969              AND u.user_id = p.poster_id',
 970      );
 971  
 972      $sql = $db->sql_build_query('SELECT', $sql_ary);
 973      $result = $db->sql_query($sql);
 974  
 975      $rowset = array();
 976      $has_attachments = false;
 977      while ($row = $db->sql_fetchrow($result))
 978      {
 979          $rowset[$row['post_id']] = $row;
 980  
 981          if ($row['post_attachment'])
 982          {
 983              $has_attachments = true;
 984          }
 985      }
 986      $db->sql_freeresult($result);
 987  
 988      // Grab extensions
 989      $attachments = array();
 990      if ($has_attachments && $auth->acl_get('u_download') && $auth->acl_get('f_download', $forum_id))
 991      {
 992          // Get attachments...
 993          $sql = 'SELECT *
 994              FROM ' . ATTACHMENTS_TABLE . '
 995              WHERE ' . $db->sql_in_set('post_msg_id', $post_list) . '
 996                  AND in_message = 0
 997              ORDER BY filetime DESC, post_msg_id ASC';
 998          $result = $db->sql_query($sql);
 999  
1000          while ($row = $db->sql_fetchrow($result))
1001          {
1002              $attachments[$row['post_msg_id']][] = $row;
1003          }
1004          $db->sql_freeresult($result);
1005      }
1006  
1007      /**
1008      * Event to modify the posts list for topic reviews
1009      *
1010      * @event core.topic_review_modify_post_list
1011      * @var    array    attachments            Array with the post attachments data
1012      * @var    int        cur_post_id            Post offset ID
1013      * @var    int        forum_id            The topic's forum ID
1014      * @var    string    mode                The topic review mode
1015      * @var    array    post_list            Array with the post IDs
1016      * @var    array    rowset                Array with the posts data
1017      * @var    bool    show_quote_button    Flag indicating if the quote button should be displayed
1018      * @var    int        topic_id            The topic ID that is being reviewed
1019      * @since 3.1.9-RC1
1020      */
1021      $vars = array(
1022          'attachments',
1023          'cur_post_id',
1024          'forum_id',
1025          'mode',
1026          'post_list',
1027          'rowset',
1028          'show_quote_button',
1029          'topic_id',
1030      );
1031      extract($phpbb_dispatcher->trigger_event('core.topic_review_modify_post_list', compact($vars)));
1032  
1033      for ($i = 0, $end = count($post_list); $i < $end; ++$i)
1034      {
1035          // A non-existing rowset only happens if there was no user present for the entered poster_id
1036          // This could be a broken posts table.
1037          if (!isset($rowset[$post_list[$i]]))
1038          {
1039              continue;
1040          }
1041  
1042          $row = $rowset[$post_list[$i]];
1043  
1044          $poster_id        = $row['user_id'];
1045          $post_subject    = $row['post_subject'];
1046  
1047          $decoded_message = false;
1048  
1049          if ($show_quote_button && $auth->acl_get('f_reply', $forum_id))
1050          {
1051              $decoded_message = censor_text($row['post_text']);
1052              decode_message($decoded_message, $row['bbcode_uid']);
1053  
1054              $decoded_message = bbcode_nl2br($decoded_message);
1055          }
1056  
1057          $parse_flags = ($row['bbcode_bitfield'] ? OPTION_FLAG_BBCODE : 0);
1058          $parse_flags |= ($row['enable_smilies'] ? OPTION_FLAG_SMILIES : 0);
1059          $message = generate_text_for_display($row['post_text'], $row['bbcode_uid'], $row['bbcode_bitfield'], $parse_flags, true);
1060  
1061          if (!empty($attachments[$row['post_id']]))
1062          {
1063              $update_count = array();
1064              parse_attachments($forum_id, $message, $attachments[$row['post_id']], $update_count);
1065          }
1066  
1067          $post_subject = censor_text($post_subject);
1068  
1069          $post_anchor = ($mode == 'post_review') ? 'ppr' . $row['post_id'] : 'pr' . $row['post_id'];
1070          $u_show_post = append_sid($phpbb_root_path . 'viewtopic.' . $phpEx, "f=$forum_id&amp;t=$topic_id&amp;p={$row['post_id']}&amp;view=show#p{$row['post_id']}");
1071  
1072          $l_deleted_message = '';
1073          if ($row['post_visibility'] == ITEM_DELETED)
1074          {
1075              $display_postername = get_username_string('full', $poster_id, $row['username'], $row['user_colour'], $row['post_username']);
1076  
1077              // User having deleted the post also being the post author?
1078              if (!$row['post_delete_user'] || $row['post_delete_user'] == $poster_id)
1079              {
1080                  $display_username = $display_postername;
1081              }
1082              else
1083              {
1084                  $display_username = get_username_string('full', $row['post_delete_user'], $row['post_delete_username'], $row['post_delete_user_colour']);
1085              }
1086  
1087              if ($row['post_delete_reason'])
1088              {
1089                  $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']);
1090              }
1091              else
1092              {
1093                  $l_deleted_message = $user->lang('POST_DELETED_BY', $display_postername, $display_username, $user->format_date($row['post_delete_time'], false, true));
1094              }
1095          }
1096  
1097          $post_row = array(
1098              'POST_AUTHOR_FULL'        => get_username_string('full', $poster_id, $row['username'], $row['user_colour'], $row['post_username']),
1099              'POST_AUTHOR_COLOUR'    => get_username_string('colour', $poster_id, $row['username'], $row['user_colour'], $row['post_username']),
1100              'POST_AUTHOR'            => get_username_string('username', $poster_id, $row['username'], $row['user_colour'], $row['post_username']),
1101              'U_POST_AUTHOR'            => get_username_string('profile', $poster_id, $row['username'], $row['user_colour'], $row['post_username']),
1102  
1103              'S_HAS_ATTACHMENTS'    => (!empty($attachments[$row['post_id']])) ? true : false,
1104              'S_FRIEND'            => ($row['friend']) ? true : false,
1105              'S_IGNORE_POST'        => ($row['foe']) ? true : false,
1106              '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']), "<a href=\"{$u_show_post}\" onclick=\"phpbb.toggleDisplay('{$post_anchor}', 1); return false;\">", '</a>') : '',
1107              'S_POST_DELETED'    => ($row['post_visibility'] == ITEM_DELETED) ? true : false,
1108              'L_DELETE_POST'        => $l_deleted_message,
1109  
1110              'POST_SUBJECT'        => $post_subject,
1111              'MINI_POST_IMG'        => $user->img('icon_post_target', $user->lang['POST']),
1112              'POST_DATE'            => $user->format_date($row['post_time']),
1113              'MESSAGE'            => $message,
1114              'DECODED_MESSAGE'    => $decoded_message,
1115              'POST_ID'            => $row['post_id'],
1116              'POST_TIME'            => $row['post_time'],
1117              'USER_ID'            => $row['user_id'],
1118              'U_MINI_POST'        => append_sid("{$phpbb_root_path}viewtopic.$phpEx", 'p=' . $row['post_id']) . '#p' . $row['post_id'],
1119              'U_MCP_DETAILS'        => ($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) : '',
1120              'POSTER_QUOTE'        => ($show_quote_button && $auth->acl_get('f_reply', $forum_id)) ? addslashes(get_username_string('username', $poster_id, $row['username'], $row['user_colour'], $row['post_username'])) : '',
1121          );
1122  
1123          $current_row_number = $i;
1124  
1125          /**
1126          * Event to modify the template data block for topic reviews
1127          *
1128          * @event core.topic_review_modify_row
1129          * @var    string    mode                The review mode
1130          * @var    int        topic_id            The topic that is being reviewed
1131          * @var    int        forum_id            The topic's forum
1132          * @var    int        cur_post_id            Post offset id
1133          * @var    int        current_row_number    Number of the current row being iterated
1134          * @var    array    post_row            Template block array of the current post
1135          * @var    array    row                    Array with original post and user data
1136          * @since 3.1.4-RC1
1137          */
1138          $vars = array(
1139              'mode',
1140              'topic_id',
1141              'forum_id',
1142              'cur_post_id',
1143              'current_row_number',
1144              'post_row',
1145              'row',
1146          );
1147          extract($phpbb_dispatcher->trigger_event('core.topic_review_modify_row', compact($vars)));
1148  
1149          $template->assign_block_vars($mode . '_row', $post_row);
1150  
1151          // Display not already displayed Attachments for this post, we already parsed them. ;)
1152          if (!empty($attachments[$row['post_id']]))
1153          {
1154              foreach ($attachments[$row['post_id']] as $attachment)
1155              {
1156                  $template->assign_block_vars($mode . '_row.attachment', array(
1157                      'DISPLAY_ATTACHMENT'    => $attachment)
1158                  );
1159              }
1160          }
1161  
1162          unset($rowset[$post_list[$i]]);
1163      }
1164  
1165      if ($mode == 'topic_review')
1166      {
1167          $template->assign_var('QUOTE_IMG', $user->img('icon_post_quote', $user->lang['REPLY_WITH_QUOTE']));
1168      }
1169  
1170      return true;
1171  }
1172  
1173  //
1174  // Post handling functions
1175  //
1176  
1177  /**
1178  * Delete Post
1179  */
1180  function delete_post($forum_id, $topic_id, $post_id, &$data, $is_soft = false, $softdelete_reason = '')
1181  {
1182      global $db, $user, $phpbb_container, $phpbb_dispatcher;
1183      global $config, $phpEx, $phpbb_root_path;
1184  
1185      // Specify our post mode
1186      $post_mode = 'delete';
1187      if (($data['topic_first_post_id'] === $data['topic_last_post_id']) && ($data['topic_posts_approved'] + $data['topic_posts_unapproved'] + $data['topic_posts_softdeleted'] == 1))
1188      {
1189          $post_mode = 'delete_topic';
1190      }
1191      else if ($data['topic_first_post_id'] == $post_id)
1192      {
1193          $post_mode = 'delete_first_post';
1194      }
1195      else if ($data['topic_last_post_id'] == $post_id)
1196      {
1197          $post_mode = 'delete_last_post';
1198      }
1199      $sql_data = array();
1200      $next_post_id = false;
1201  
1202      include_once($phpbb_root_path . 'includes/functions_admin.' . $phpEx);
1203  
1204      $db->sql_transaction('begin');
1205  
1206      // we must make sure to update forums that contain the shadow'd topic
1207      if ($post_mode == 'delete_topic')
1208      {
1209          $shadow_forum_ids = array();
1210  
1211          $sql = 'SELECT forum_id
1212              FROM ' . TOPICS_TABLE . '
1213              WHERE ' . $db->sql_in_set('topic_moved_id', $topic_id);
1214          $result = $db->sql_query($sql);
1215          while ($row = $db->sql_fetchrow($result))
1216          {
1217              if (!isset($shadow_forum_ids[(int) $row['forum_id']]))
1218              {
1219                  $shadow_forum_ids[(int) $row['forum_id']] = 1;
1220              }
1221              else
1222              {
1223                  $shadow_forum_ids[(int) $row['forum_id']]++;
1224              }
1225          }
1226          $db->sql_freeresult($result);
1227      }
1228  
1229      /* @var $phpbb_content_visibility \phpbb\content_visibility */
1230      $phpbb_content_visibility = $phpbb_container->get('content.visibility');
1231  
1232      // (Soft) delete the post
1233      if ($is_soft && ($post_mode != 'delete_topic'))
1234      {
1235          $phpbb_content_visibility->set_post_visibility(ITEM_DELETED, $post_id, $topic_id, $forum_id, $user->data['user_id'], time(), $softdelete_reason, ($data['topic_first_post_id'] == $post_id), ($data['topic_last_post_id'] == $post_id));
1236      }
1237      else if (!$is_soft)
1238      {
1239          if (!delete_posts('post_id', array($post_id), false, false, false))
1240          {
1241              // Try to delete topic, we may had an previous error causing inconsistency
1242              if ($post_mode == 'delete_topic')
1243              {
1244                  delete_topics('topic_id', array($topic_id), false);
1245              }
1246              trigger_error('ALREADY_DELETED');
1247          }
1248      }
1249  
1250      $db->sql_transaction('commit');
1251  
1252      // Collect the necessary information for updating the tables
1253      $sql_data[FORUMS_TABLE] = $sql_data[TOPICS_TABLE] = '';
1254      switch ($post_mode)
1255      {
1256          case 'delete_topic':
1257  
1258              foreach ($shadow_forum_ids as $updated_forum => $topic_count)
1259              {
1260                  // counting is fun! we only have to do count($forum_ids) number of queries,
1261                  // even if the topic is moved back to where its shadow lives (we count how many times it is in a forum)
1262                  $sql = 'UPDATE ' . FORUMS_TABLE . '
1263                      SET forum_topics_approved = forum_topics_approved - ' . $topic_count . '
1264                      WHERE forum_id = ' . $updated_forum;
1265                  $db->sql_query($sql);
1266                  update_post_information('forum', $updated_forum);
1267              }
1268  
1269              if ($is_soft)
1270              {
1271                  $phpbb_content_visibility->set_topic_visibility(ITEM_DELETED, $topic_id, $forum_id, $user->data['user_id'], time(), $softdelete_reason);
1272              }
1273              else
1274              {
1275                  delete_topics('topic_id', array($topic_id), false);
1276  
1277                  $phpbb_content_visibility->remove_topic_from_statistic($data, $sql_data);
1278  
1279                  $update_sql = update_post_information('forum', $forum_id, true);
1280                  if (count($update_sql))
1281                  {
1282                      $sql_data[FORUMS_TABLE] .= ($sql_data[FORUMS_TABLE]) ? ', ' : '';
1283                      $sql_data[FORUMS_TABLE] .= implode(', ', $update_sql[$forum_id]);
1284                  }
1285              }
1286  
1287          break;
1288  
1289          case 'delete_first_post':
1290              $sql = 'SELECT p.post_id, p.poster_id, p.post_time, p.post_username, u.username, u.user_colour
1291                  FROM ' . POSTS_TABLE . ' p, ' . USERS_TABLE . " u
1292                  WHERE p.topic_id = $topic_id
1293                      AND p.poster_id = u.user_id
1294                      AND p.post_visibility = " . ITEM_APPROVED . '
1295                  ORDER BY p.post_time ASC, p.post_id ASC';
1296              $result = $db->sql_query_limit($sql, 1);
1297              $row = $db->sql_fetchrow($result);
1298              $db->sql_freeresult($result);
1299  
1300              if (!$row)
1301              {
1302                  // No approved post, so the first is a not-approved post (unapproved or soft deleted)
1303                  $sql = 'SELECT p.post_id, p.poster_id, p.post_time, p.post_username, u.username, u.user_colour
1304                      FROM ' . POSTS_TABLE . ' p, ' . USERS_TABLE . " u
1305                      WHERE p.topic_id = $topic_id
1306                          AND p.poster_id = u.user_id
1307                      ORDER BY p.post_time ASC, p.post_id ASC";
1308                  $result = $db->sql_query_limit($sql, 1);
1309                  $row = $db->sql_fetchrow($result);
1310                  $db->sql_freeresult($result);
1311              }
1312  
1313              $next_post_id = (int) $row['post_id'];
1314  
1315              $sql_data[TOPICS_TABLE] = $db->sql_build_array('UPDATE', array(
1316                  'topic_poster'                => (int) $row['poster_id'],
1317                  'topic_first_post_id'        => (int) $row['post_id'],
1318                  'topic_first_poster_colour'    => $row['user_colour'],
1319                  'topic_first_poster_name'    => ($row['poster_id'] == ANONYMOUS) ? $row['post_username'] : $row['username'],
1320                  'topic_time'                => (int) $row['post_time'],
1321              ));
1322          break;
1323  
1324          case 'delete_last_post':
1325              if (!$is_soft)
1326              {
1327                  // Update last post information when hard deleting. Soft delete already did that by itself.
1328                  $update_sql = update_post_information('forum', $forum_id, true);
1329                  if (count($update_sql))
1330                  {
1331                      $sql_data[FORUMS_TABLE] = (($sql_data[FORUMS_TABLE]) ? $sql_data[FORUMS_TABLE] . ', ' : '') . implode(', ', $update_sql[$forum_id]);
1332                  }
1333  
1334                  $sql_data[TOPICS_TABLE] = (($sql_data[TOPICS_TABLE]) ? $sql_data[TOPICS_TABLE] . ', ' : '') . 'topic_bumped = 0, topic_bumper = 0';
1335  
1336                  $update_sql = update_post_information('topic', $topic_id, true);
1337                  if (!empty($update_sql))
1338                  {
1339                      $sql_data[TOPICS_TABLE] .= ', ' . implode(', ', $update_sql[$topic_id]);
1340                      $next_post_id = (int) str_replace('topic_last_post_id = ', '', $update_sql[$topic_id][0]);
1341                  }
1342              }
1343  
1344              if (!$next_post_id)
1345              {
1346                  $sql = 'SELECT MAX(post_id) as last_post_id
1347                      FROM ' . POSTS_TABLE . "
1348                      WHERE topic_id = $topic_id
1349                          AND " . $phpbb_content_visibility->get_visibility_sql('post', $forum_id);
1350                  $result = $db->sql_query($sql);
1351                  $next_post_id = (int) $db->sql_fetchfield('last_post_id');
1352                  $db->sql_freeresult($result);
1353              }
1354          break;
1355  
1356          case 'delete':
1357              $sql = 'SELECT post_id
1358                  FROM ' . POSTS_TABLE . "
1359                  WHERE topic_id = $topic_id
1360                      AND " . $phpbb_content_visibility->get_visibility_sql('post', $forum_id) . '
1361                      AND post_time > ' . $data['post_time'] . '
1362                  ORDER BY post_time ASC, post_id ASC';
1363              $result = $db->sql_query_limit($sql, 1);
1364              $next_post_id = (int) $db->sql_fetchfield('post_id');
1365              $db->sql_freeresult($result);
1366          break;
1367      }
1368  
1369      if (($post_mode == 'delete') || ($post_mode == 'delete_last_post') || ($post_mode == 'delete_first_post'))
1370      {
1371          if (!$is_soft)
1372          {
1373              $phpbb_content_visibility->remove_post_from_statistic($data, $sql_data);
1374          }
1375  
1376          $sql = 'SELECT 1 AS has_attachments
1377              FROM ' . ATTACHMENTS_TABLE . '
1378              WHERE topic_id = ' . $topic_id;
1379          $result = $db->sql_query_limit($sql, 1);
1380          $has_attachments = (int) $db->sql_fetchfield('has_attachments');
1381          $db->sql_freeresult($result);
1382  
1383          if (!$has_attachments)
1384          {
1385              $sql_data[TOPICS_TABLE] = (($sql_data[TOPICS_TABLE]) ? $sql_data[TOPICS_TABLE] . ', ' : '') . 'topic_attachment = 0';
1386          }
1387      }
1388  
1389      $db->sql_transaction('begin');
1390  
1391      $where_sql = array(
1392          FORUMS_TABLE    => "forum_id = $forum_id",
1393          TOPICS_TABLE    => "topic_id = $topic_id",
1394          USERS_TABLE        => 'user_id = ' . $data['poster_id'],
1395      );
1396  
1397      foreach ($sql_data as $table => $update_sql)
1398      {
1399          if ($update_sql)
1400          {
1401              $db->sql_query("UPDATE $table SET $update_sql WHERE " . $where_sql[$table]);
1402          }
1403      }
1404  
1405      // Adjust posted info for this user by looking for a post by him/her within this topic...
1406      if ($post_mode != 'delete_topic' && $config['load_db_track'] && $data['poster_id'] != ANONYMOUS)
1407      {
1408          $sql = 'SELECT poster_id
1409              FROM ' . POSTS_TABLE . '
1410              WHERE topic_id = ' . $topic_id . '
1411                  AND poster_id = ' . $data['poster_id'];
1412          $result = $db->sql_query_limit($sql, 1);
1413          $poster_id = (int) $db->sql_fetchfield('poster_id');
1414          $db->sql_freeresult($result);
1415  
1416          // The user is not having any more posts within this topic
1417          if (!$poster_id)
1418          {
1419              $sql = 'DELETE FROM ' . TOPICS_POSTED_TABLE . '
1420                  WHERE topic_id = ' . $topic_id . '
1421                      AND user_id = ' . $data['poster_id'];
1422              $db->sql_query($sql);
1423          }
1424      }
1425  
1426      $db->sql_transaction('commit');
1427  
1428      if ($data['post_reported'] && ($post_mode != 'delete_topic'))
1429      {
1430          sync('topic_reported', 'topic_id', array($topic_id));
1431      }
1432  
1433      /**
1434      * This event is used for performing actions directly after a post or topic
1435      * has been deleted.
1436      *
1437      * @event core.delete_post_after
1438      * @var    int        forum_id            Post forum ID
1439      * @var    int        topic_id            Post topic ID
1440      * @var    int        post_id                Post ID
1441      * @var    array    data                Post data
1442      * @var    bool    is_soft                Soft delete flag
1443      * @var    string    softdelete_reason    Soft delete reason
1444      * @var    string    post_mode            delete_topic, delete_first_post, delete_last_post or delete
1445      * @var    mixed    next_post_id        Next post ID in the topic (post ID or false)
1446      *
1447      * @since 3.1.11-RC1
1448      */
1449      $vars = array(
1450          'forum_id',
1451          'topic_id',
1452          'post_id',
1453          'data',
1454          'is_soft',
1455          'softdelete_reason',
1456          'post_mode',
1457          'next_post_id',
1458      );
1459      extract($phpbb_dispatcher->trigger_event('core.delete_post_after', compact($vars)));
1460  
1461      return $next_post_id;
1462  }
1463  
1464  /**
1465  * Submit Post
1466  * @todo Split up and create lightweight, simple API for this.
1467  */
1468  function submit_post($mode, $subject, $username, $topic_type, &$poll_ary, &$data_ary, $update_message = true, $update_search_index = true)
1469  {
1470      global $db, $auth, $user, $config, $phpEx, $phpbb_root_path, $phpbb_container, $phpbb_dispatcher, $phpbb_log, $request;
1471  
1472      $poll = $poll_ary;
1473      $data = $data_ary;
1474      /**
1475      * Modify the data for post submitting
1476      *
1477      * @event core.modify_submit_post_data
1478      * @var    string    mode                Variable containing posting mode value
1479      * @var    string    subject                Variable containing post subject value
1480      * @var    string    username            Variable containing post author name
1481      * @var    int        topic_type            Variable containing topic type value
1482      * @var    array    poll                Array with the poll data for the post
1483      * @var    array    data                Array with the data for the post
1484      * @var    bool    update_message        Flag indicating if the post will be updated
1485      * @var    bool    update_search_index    Flag indicating if the search index will be updated
1486      * @since 3.1.0-a4
1487      */
1488      $vars = array(
1489          'mode',
1490          'subject',
1491          'username',
1492          'topic_type',
1493          'poll',
1494          'data',
1495          'update_message',
1496          'update_search_index',
1497      );
1498      extract($phpbb_dispatcher->trigger_event('core.modify_submit_post_data', compact($vars)));
1499      $poll_ary = $poll;
1500      $data_ary = $data;
1501      unset($poll);
1502      unset($data);
1503  
1504      // We do not handle erasing posts here
1505      if ($mode == 'delete')
1506      {
1507          return false;
1508      }
1509  
1510      if (!empty($data_ary['post_time']))
1511      {
1512          $current_time = $data_ary['post_time'];
1513      }
1514      else
1515      {
1516          $current_time = time();
1517      }
1518  
1519      if ($mode == 'post')
1520      {
1521          $post_mode = 'post';
1522          $update_message = true;
1523      }
1524      else if ($mode != 'edit')
1525      {
1526          $post_mode = 'reply';
1527          $update_message = true;
1528      }
1529      else if ($mode == 'edit')
1530      {
1531          $post_mode = ($data_ary['topic_posts_approved'] + $data_ary['topic_posts_unapproved'] + $data_ary['topic_posts_softdeleted'] == 1) ? 'edit_topic' : (($data_ary['topic_first_post_id'] == $data_ary['post_id']) ? 'edit_first_post' : (($data_ary['topic_last_post_id'] == $data_ary['post_id']) ? 'edit_last_post' : 'edit'));
1532      }
1533  
1534      // First of all make sure the subject and topic title are having the correct length.
1535      // To achieve this without cutting off between special chars we convert to an array and then count the elements.
1536      $subject = truncate_string($subject, 120);
1537      $data_ary['topic_title'] = truncate_string($data_ary['topic_title'], 120);
1538  
1539      // Collect some basic information about which tables and which rows to update/insert
1540      $sql_data = $topic_row = array();
1541      $poster_id = ($mode == 'edit') ? $data_ary['poster_id'] : (int) $user->data['user_id'];
1542  
1543      // Retrieve some additional information if not present
1544      if ($mode == 'edit' && (!isset($data_ary['post_visibility']) || !isset($data_ary['topic_visibility']) || $data_ary['post_visibility'] === false || $data_ary['topic_visibility'] === false))
1545      {
1546          $sql = 'SELECT p.post_visibility, t.topic_type, t.topic_posts_approved, t.topic_posts_unapproved, t.topic_posts_softdeleted, t.topic_visibility
1547              FROM ' . TOPICS_TABLE . ' t, ' . POSTS_TABLE . ' p
1548              WHERE t.topic_id = p.topic_id
1549                  AND p.post_id = ' . $data_ary['post_id'];
1550          $result = $db->sql_query($sql);
1551          $topic_row = $db->sql_fetchrow($result);
1552          $db->sql_freeresult($result);
1553  
1554          $data_ary['topic_visibility'] = $topic_row['topic_visibility'];
1555          $data_ary['post_visibility'] = $topic_row['post_visibility'];
1556      }
1557  
1558      // This variable indicates if the user is able to post or put into the queue
1559      $post_visibility = ITEM_APPROVED;
1560  
1561      // Check the permissions for post approval.
1562      // Moderators must go through post approval like ordinary users.
1563      if (!$auth->acl_get('f_noapprove', $data_ary['forum_id']))
1564      {
1565          // Post not approved, but in queue
1566          $post_visibility = ITEM_UNAPPROVED;
1567          switch ($post_mode)
1568          {
1569              case 'edit_first_post':
1570              case 'edit':
1571              case 'edit_last_post':
1572              case 'edit_topic':
1573                  $post_visibility = ITEM_REAPPROVE;
1574              break;
1575          }
1576      }
1577      else if (isset($data_ary['post_visibility']) && $data_ary['post_visibility'] !== false)
1578      {
1579          $post_visibility = $data_ary['post_visibility'];
1580      }
1581  
1582      // MODs/Extensions are able to force any visibility on posts
1583      if (isset($data_ary['force_approved_state']))
1584      {
1585          $post_visibility = (in_array((int) $data_ary['force_approved_state'], array(ITEM_APPROVED, ITEM_UNAPPROVED, ITEM_DELETED, ITEM_REAPPROVE))) ? (int) $data_ary['force_approved_state'] : $post_visibility;
1586      }
1587      if (isset($data_ary['force_visibility']))
1588      {
1589          $post_visibility = (in_array((int) $data_ary['force_visibility'], array(ITEM_APPROVED, ITEM_UNAPPROVED, ITEM_DELETED, ITEM_REAPPROVE))) ? (int) $data_ary['force_visibility'] : $post_visibility;
1590      }
1591  
1592      // Start the transaction here
1593      $db->sql_transaction('begin');
1594  
1595      // Collect Information
1596      switch ($post_mode)
1597      {
1598          case 'post':
1599          case 'reply':
1600              $sql_data[POSTS_TABLE]['sql'] = array(
1601                  'forum_id'            => $data_ary['forum_id'],
1602                  'poster_id'            => (int) $user->data['user_id'],
1603                  'icon_id'            => $data_ary['icon_id'],
1604                  'poster_ip'            => $user->ip,
1605                  'post_time'            => $current_time,
1606                  'post_visibility'    => $post_visibility,
1607                  'enable_bbcode'        => $data_ary['enable_bbcode'],
1608                  'enable_smilies'    => $data_ary['enable_smilies'],
1609                  'enable_magic_url'    => $data_ary['enable_urls'],
1610                  'enable_sig'        => $data_ary['enable_sig'],
1611                  'post_username'        => (!$user->data['is_registered']) ? $username : '',
1612                  'post_subject'        => $subject,
1613                  'post_text'            => $data_ary['message'],
1614                  'post_checksum'        => $data_ary['message_md5'],
1615                  'post_attachment'    => (!empty($data_ary['attachment_data'])) ? 1 : 0,
1616                  'bbcode_bitfield'    => $data_ary['bbcode_bitfield'],
1617                  'bbcode_uid'        => $data_ary['bbcode_uid'],
1618                  'post_postcount'    => ($auth->acl_get('f_postcount', $data_ary['forum_id'])) ? 1 : 0,
1619                  'post_edit_locked'    => $data_ary['post_edit_locked']
1620              );
1621          break;
1622  
1623          case 'edit_first_post':
1624          case 'edit':
1625  
1626          case 'edit_last_post':
1627          case 'edit_topic':
1628  
1629              // If edit reason is given always display edit info
1630  
1631              // If editing last post then display no edit info
1632              // If m_edit permission then display no edit info
1633              // If normal edit display edit info
1634  
1635              // Display edit info if edit reason given or user is editing his post, which is not the last within the topic.
1636              if ($data_ary['post_edit_reason'] || (!$auth->acl_get('m_edit', $data_ary['forum_id']) && ($post_mode == 'edit' || $post_mode == 'edit_first_post')))
1637              {
1638                  $data_ary['post_edit_reason']        = truncate_string($data_ary['post_edit_reason'], 255, 255, false);
1639  
1640                  $sql_data[POSTS_TABLE]['sql']    = array(
1641                      'post_edit_time'    => $current_time,
1642                      'post_edit_reason'    => $data_ary['post_edit_reason'],
1643                      'post_edit_user'    => (int) $data_ary['post_edit_user'],
1644                  );
1645  
1646                  $sql_data[POSTS_TABLE]['stat'][] = 'post_edit_count = post_edit_count + 1';
1647              }
1648              else if (!$data_ary['post_edit_reason'] && $mode == 'edit' && $auth->acl_get('m_edit', $data_ary['forum_id']))
1649              {
1650                  $sql_data[POSTS_TABLE]['sql'] = array(
1651                      'post_edit_reason'    => '',
1652                  );
1653              }
1654  
1655              // If the person editing this post is different to the one having posted then we will add a log entry stating the edit
1656              // Could be simplified by only adding to the log if the edit is not tracked - but this may confuse admins/mods
1657              if ($user->data['user_id'] != $poster_id)
1658              {
1659                  $log_subject = ($subject) ? $subject : $data_ary['topic_title'];
1660                  $phpbb_log->add('mod', $user->data['user_id'], $user->ip, 'LOG_POST_EDITED', false, array(
1661                      'forum_id' => $data_ary['forum_id'],
1662                      'topic_id' => $data_ary['topic_id'],
1663                      'post_id'  => $data_ary['post_id'],
1664                      $log_subject,
1665                      (!empty($username)) ? $username : $user->lang['GUEST'],
1666                      $data_ary['post_edit_reason']
1667                  ));
1668              }
1669  
1670              if (!isset($sql_data[POSTS_TABLE]['sql']))
1671              {
1672                  $sql_data[POSTS_TABLE]['sql'] = array();
1673              }
1674  
1675              $sql_data[POSTS_TABLE]['sql'] = array_merge($sql_data[POSTS_TABLE]['sql'], array(
1676                  'forum_id'            => $data_ary['forum_id'],
1677                  'poster_id'            => $data_ary['poster_id'],
1678                  'icon_id'            => $data_ary['icon_id'],
1679                  // We will change the visibility later
1680                  //'post_visibility'    => $post_visibility,
1681                  'enable_bbcode'        => $data_ary['enable_bbcode'],
1682                  'enable_smilies'    => $data_ary['enable_smilies'],
1683                  'enable_magic_url'    => $data_ary['enable_urls'],
1684                  'enable_sig'        => $data_ary['enable_sig'],
1685                  'post_username'        => ($username && $data_ary['poster_id'] == ANONYMOUS) ? $username : '',
1686                  'post_subject'        => $subject,
1687                  'post_checksum'        => $data_ary['message_md5'],
1688                  'post_attachment'    => (!empty($data_ary['attachment_data'])) ? 1 : 0,
1689                  'bbcode_bitfield'    => $data_ary['bbcode_bitfield'],
1690                  'bbcode_uid'        => $data_ary['bbcode_uid'],
1691                  'post_edit_locked'    => $data_ary['post_edit_locked'])
1692              );
1693  
1694              if ($update_message)
1695              {
1696                  $sql_data[POSTS_TABLE]['sql']['post_text'] = $data_ary['message'];
1697              }
1698  
1699          break;
1700      }
1701  
1702      // And the topic ladies and gentlemen
1703      switch ($post_mode)
1704      {
1705          case 'post':
1706              $sql_data[TOPICS_TABLE]['sql'] = array(
1707                  'topic_poster'                => (int) $user->data['user_id'],
1708                  'topic_time'                => $current_time,
1709                  'topic_last_view_time'        => $current_time,
1710                  'forum_id'                    => $data_ary['forum_id'],
1711                  'icon_id'                    => $data_ary['icon_id'],
1712                  'topic_posts_approved'        => ($post_visibility == ITEM_APPROVED) ? 1 : 0,
1713                  'topic_posts_softdeleted'    => ($post_visibility == ITEM_DELETED) ? 1 : 0,
1714                  'topic_posts_unapproved'    => ($post_visibility == ITEM_UNAPPROVED) ? 1 : 0,
1715                  'topic_visibility'            => $post_visibility,
1716                  'topic_delete_user'            => ($post_visibility != ITEM_APPROVED) ? (int) $user->data['user_id'] : 0,
1717                  'topic_title'                => $subject,
1718                  'topic_first_poster_name'    => (!$user->data['is_registered'] && $username) ? $username : (($user->data['user_id'] != ANONYMOUS) ? $user->data['username'] : ''),
1719                  'topic_first_poster_colour'    => $user->data['user_colour'],
1720                  'topic_type'                => $topic_type,
1721                  'topic_time_limit'            => $topic_type != POST_NORMAL ? ($data_ary['topic_time_limit'] * 86400) : 0,
1722                  'topic_attachment'            => (!empty($data_ary['attachment_data'])) ? 1 : 0,
1723                  'topic_status'                => (isset($data_ary['topic_status'])) ? $data_ary['topic_status'] : ITEM_UNLOCKED,
1724              );
1725  
1726              if (isset($poll_ary['poll_options']) && !empty($poll_ary['poll_options']))
1727              {
1728                  $poll_start = ($poll_ary['poll_start']) ? $poll_ary['poll_start'] : $current_time;
1729                  $poll_length = $poll_ary['poll_length'] * 86400;
1730                  if ($poll_length < 0)
1731                  {
1732                      $poll_start = $poll_start + $poll_length;
1733                      if ($poll_start < 0)
1734                      {
1735                          $poll_start = 0;
1736                      }
1737                      $poll_length = 1;
1738                  }
1739  
1740                  $sql_data[TOPICS_TABLE]['sql'] = array_merge($sql_data[TOPICS_TABLE]['sql'], array(
1741                      'poll_title'        => $poll_ary['poll_title'],
1742                      'poll_start'        => $poll_start,
1743                      'poll_max_options'    => $poll_ary['poll_max_options'],
1744                      'poll_length'        => $poll_length,
1745                      'poll_vote_change'    => $poll_ary['poll_vote_change'])
1746                  );
1747              }
1748  
1749              $sql_data[USERS_TABLE]['stat'][] = "user_lastpost_time = $current_time" . (($auth->acl_get('f_postcount', $data_ary['forum_id']) && $post_visibility == ITEM_APPROVED) ? ', user_posts = user_posts + 1' : '');
1750  
1751              if ($post_visibility == ITEM_APPROVED)
1752              {
1753                  $sql_data[FORUMS_TABLE]['stat'][] = 'forum_topics_approved = forum_topics_approved + 1';
1754                  $sql_data[FORUMS_TABLE]['stat'][] = 'forum_posts_approved = forum_posts_approved + 1';
1755              }
1756              else if ($post_visibility == ITEM_UNAPPROVED)
1757              {
1758                  $sql_data[FORUMS_TABLE]['stat'][] = 'forum_topics_unapproved = forum_topics_unapproved + 1';
1759                  $sql_data[FORUMS_TABLE]['stat'][] = 'forum_posts_unapproved = forum_posts_unapproved + 1';
1760              }
1761              else if ($post_visibility == ITEM_DELETED)
1762              {
1763                  $sql_data[FORUMS_TABLE]['stat'][] = 'forum_topics_softdeleted = forum_topics_softdeleted + 1';
1764                  $sql_data[FORUMS_TABLE]['stat'][] = 'forum_posts_softdeleted = forum_posts_softdeleted + 1';
1765              }
1766          break;
1767  
1768          case 'reply':
1769              $sql_data[TOPICS_TABLE]['stat'][] = 'topic_last_view_time = ' . $current_time . ',
1770                  topic_bumped = 0,
1771                  topic_bumper = 0' .
1772                  (($post_visibility == ITEM_APPROVED) ? ', topic_posts_approved = topic_posts_approved + 1' : '') .
1773                  (($post_visibility == ITEM_UNAPPROVED) ? ', topic_posts_unapproved = topic_posts_unapproved + 1' : '') .
1774                  (($post_visibility == ITEM_DELETED) ? ', topic_posts_softdeleted = topic_posts_softdeleted + 1' : '') .
1775                  ((!empty($data_ary['attachment_data']) || (isset($data_ary['topic_attachment']) && $data_ary['topic_attachment'])) ? ', topic_attachment = 1' : '');
1776  
1777              $sql_data[USERS_TABLE]['stat'][] = "user_lastpost_time = $current_time" . (($auth->acl_get('f_postcount', $data_ary['forum_id']) && $post_visibility == ITEM_APPROVED) ? ', user_posts = user_posts + 1' : '');
1778  
1779              if ($post_visibility == ITEM_APPROVED)
1780              {
1781                  $sql_data[FORUMS_TABLE]['stat'][] = 'forum_posts_approved = forum_posts_approved + 1';
1782              }
1783              else if ($post_visibility == ITEM_UNAPPROVED)
1784              {
1785                  $sql_data[FORUMS_TABLE]['stat'][] = 'forum_posts_unapproved = forum_posts_unapproved + 1';
1786              }
1787              else if ($post_visibility == ITEM_DELETED)
1788              {
1789                  $sql_data[FORUMS_TABLE]['stat'][] = 'forum_posts_softdeleted = forum_posts_softdeleted + 1';
1790              }
1791          break;
1792  
1793          case 'edit_topic':
1794          case 'edit_first_post':
1795              if (isset($poll_ary['poll_options']))
1796              {
1797                  $poll_start = ($poll_ary['poll_start'] || empty($poll_ary['poll_options'])) ? $poll_ary['poll_start'] : $current_time;
1798                  $poll_length = $poll_ary['poll_length'] * 86400;
1799                  if ($poll_length < 0)
1800                  {
1801                      $poll_start = $poll_start + $poll_length;
1802                      if ($poll_start < 0)
1803                      {
1804                          $poll_start = 0;
1805                      }
1806                      $poll_length = 1;
1807                  }
1808              }
1809  
1810              $sql_data[TOPICS_TABLE]['sql'] = array(
1811                  'forum_id'                    => $data_ary['forum_id'],
1812                  'icon_id'                    => $data_ary['icon_id'],
1813                  'topic_title'                => $subject,
1814                  'topic_first_poster_name'    => $username,
1815                  'topic_type'                => $topic_type,
1816                  'topic_time_limit'            => $topic_type != POST_NORMAL ? ($data_ary['topic_time_limit'] * 86400) : 0,
1817                  'poll_title'                => (isset($poll_ary['poll_options'])) ? $poll_ary['poll_title'] : '',
1818                  'poll_start'                => (isset($poll_ary['poll_options'])) ? $poll_start : 0,
1819                  'poll_max_options'            => (isset($poll_ary['poll_options'])) ? $poll_ary['poll_max_options'] : 1,
1820                  'poll_length'                => (isset($poll_ary['poll_options'])) ? $poll_length : 0,
1821                  'poll_vote_change'            => (isset($poll_ary['poll_vote_change'])) ? $poll_ary['poll_vote_change'] : 0,
1822                  'topic_last_view_time'        => $current_time,
1823  
1824                  'topic_attachment'            => (!empty($data_ary['attachment_data'])) ? 1 : (isset($data_ary['topic_attachment']) ? $data_ary['topic_attachment'] : 0),
1825              );
1826  
1827          break;
1828      }
1829  
1830      $poll = $poll_ary;
1831      $data = $data_ary;
1832      /**
1833      * Modify sql query data for post submitting
1834      *
1835      * @event core.submit_post_modify_sql_data
1836      * @var    array    data                Array with the data for the post
1837      * @var    array    poll                Array with the poll data for the post
1838      * @var    string    post_mode            Variable containing posting mode value
1839      * @var    bool    sql_data            Array with the data for the posting SQL query
1840      * @var    string    subject                Variable containing post subject value
1841      * @var    int        topic_type            Variable containing topic type value
1842      * @var    string    username            Variable containing post author name
1843      * @since 3.1.3-RC1
1844      */
1845      $vars = array(
1846          'data',
1847          'poll',
1848          'post_mode',
1849          'sql_data',
1850          'subject',
1851          'topic_type',
1852          'username',
1853      );
1854      extract($phpbb_dispatcher->trigger_event('core.submit_post_modify_sql_data', compact($vars)));
1855      $poll_ary = $poll;
1856      $data_ary = $data;
1857      unset($poll);
1858      unset($data);
1859  
1860      // Submit new topic
1861      if ($post_mode == 'post')
1862      {
1863          $sql = 'INSERT INTO ' . TOPICS_TABLE . ' ' .
1864              $db->sql_build_array('INSERT', $sql_data[TOPICS_TABLE]['sql']);
1865          $db->sql_query($sql);
1866  
1867          $data_ary['topic_id'] = $db->sql_nextid();
1868  
1869          $sql_data[POSTS_TABLE]['sql'] = array_merge($sql_data[POSTS_TABLE]['sql'], array(
1870              'topic_id' => $data_ary['topic_id'])
1871          );
1872          unset($sql_data[TOPICS_TABLE]['sql']);
1873      }
1874  
1875      // Submit new post
1876      if ($post_mode == 'post' || $post_mode == 'reply')
1877      {
1878          if ($post_mode == 'reply')
1879          {
1880              $sql_data[POSTS_TABLE]['sql'] = array_merge($sql_data[POSTS_TABLE]['sql'], array(
1881                  'topic_id' => $data_ary['topic_id'],
1882              ));
1883          }
1884  
1885          $sql = 'INSERT INTO ' . POSTS_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_data[POSTS_TABLE]['sql']);
1886          $db->sql_query($sql);
1887          $data_ary['post_id'] = $db->sql_nextid();
1888  
1889          if ($post_mode == 'post' || $post_visibility == ITEM_APPROVED)
1890          {
1891              $sql_data[TOPICS_TABLE]['sql'] = array(
1892                  'topic_last_post_id'        => $data_ary['post_id'],
1893                  'topic_last_post_time'        => $current_time,
1894                  'topic_last_poster_id'        => $sql_data[POSTS_TABLE]['sql']['poster_id'],
1895                  'topic_last_poster_name'    => ($user->data['user_id'] == ANONYMOUS) ? $sql_data[POSTS_TABLE]['sql']['post_username'] : $user->data['username'],
1896                  'topic_last_poster_colour'    => $user->data['user_colour'],
1897                  'topic_last_post_subject'    => (string) $subject,
1898              );
1899          }
1900  
1901          if ($post_mode == 'post')
1902          {
1903              $sql_data[TOPICS_TABLE]['sql']['topic_first_post_id'] = $data_ary['post_id'];
1904          }
1905  
1906          // Update total post count and forum information
1907          if ($post_visibility == ITEM_APPROVED)
1908          {
1909              if ($post_mode == 'post')
1910              {
1911                  $config->increment('num_topics', 1, false);
1912              }
1913              $config->increment('num_posts', 1, false);
1914  
1915              $sql_data[FORUMS_TABLE]['stat'][] = 'forum_last_post_id = ' . $data_ary['post_id'];
1916              $sql_data[FORUMS_TABLE]['stat'][] = "forum_last_post_subject = '" . $db->sql_escape($subject) . "'";
1917              $sql_data[FORUMS_TABLE]['stat'][] = 'forum_last_post_time = ' . $current_time;
1918              $sql_data[FORUMS_TABLE]['stat'][] = 'forum_last_poster_id = ' . (int) $user->data['user_id'];
1919              $sql_data[FORUMS_TABLE]['stat'][] = "forum_last_poster_name = '" . $db->sql_escape((!$user->data['is_registered'] && $username) ? $username : (($user->data['user_id'] != ANONYMOUS) ? $user->data['username'] : '')) . "'";
1920              $sql_data[FORUMS_TABLE]['stat'][] = "forum_last_poster_colour = '" . $db->sql_escape($user->data['user_colour']) . "'";
1921          }
1922  
1923          unset($sql_data[POSTS_TABLE]['sql']);
1924      }
1925  
1926      // Update the topics table
1927      if (isset($sql_data[TOPICS_TABLE]['sql']))
1928      {
1929          $sql = 'UPDATE ' . TOPICS_TABLE . '
1930              SET ' . $db->sql_build_array('UPDATE', $sql_data[TOPICS_TABLE]['sql']) . '
1931              WHERE topic_id = ' . $data_ary['topic_id'];
1932          $db->sql_query($sql);
1933  
1934          unset($sql_data[TOPICS_TABLE]['sql']);
1935      }
1936  
1937      // Update the posts table
1938      if (isset($sql_data[POSTS_TABLE]['sql']))
1939      {
1940          $sql = 'UPDATE ' . POSTS_TABLE . '
1941              SET ' . $db->sql_build_array('UPDATE', $sql_data[POSTS_TABLE]['sql']) . '
1942              WHERE post_id = ' . $data_ary['post_id'];
1943          $db->sql_query($sql);
1944  
1945          unset($sql_data[POSTS_TABLE]['sql']);
1946      }
1947  
1948      // Update Poll Tables
1949      if (isset($poll_ary['poll_options']))
1950      {
1951          $cur_poll_options = array();
1952  
1953          if ($mode == 'edit')
1954          {
1955              $sql = 'SELECT *
1956                  FROM ' . POLL_OPTIONS_TABLE . '
1957                  WHERE topic_id = ' . $data_ary['topic_id'] . '
1958                  ORDER BY poll_option_id';
1959              $result = $db->sql_query($sql);
1960  
1961              $cur_poll_options = array();
1962              while ($row = $db->sql_fetchrow($result))
1963              {
1964                  $cur_poll_options[] = $row;
1965              }
1966              $db->sql_freeresult($result);
1967          }
1968  
1969          $sql_insert_ary = array();
1970  
1971          for ($i = 0, $size = count($poll_ary['poll_options']); $i < $size; $i++)
1972          {
1973              if (strlen(trim($poll_ary['poll_options'][$i])))
1974              {
1975                  if (empty($cur_poll_options[$i]))
1976                  {
1977                      // If we add options we need to put them to the end to be able to preserve votes...
1978                      $sql_insert_ary[] = array(
1979                          'poll_option_id'    => (int) count($cur_poll_options) + 1 + count($sql_insert_ary),
1980                          'topic_id'            => (int) $data_ary['topic_id'],
1981                          'poll_option_text'    => (string) $poll_ary['poll_options'][$i]
1982                      );
1983                  }
1984                  else if ($poll_ary['poll_options'][$i] != $cur_poll_options[$i])
1985                  {
1986                      $sql = 'UPDATE ' . POLL_OPTIONS_TABLE . "
1987                          SET poll_option_text = '" . $db->sql_escape($poll_ary['poll_options'][$i]) . "'
1988                          WHERE poll_option_id = " . $cur_poll_options[$i]['poll_option_id'] . '
1989                              AND topic_id = ' . $data_ary['topic_id'];
1990                      $db->sql_query($sql);
1991                  }
1992              }
1993          }
1994  
1995          $db->sql_multi_insert(POLL_OPTIONS_TABLE, $sql_insert_ary);
1996  
1997          if (count($poll_ary['poll_options']) < count($cur_poll_options))
1998          {
1999              $sql = 'DELETE FROM ' . POLL_OPTIONS_TABLE . '
2000                  WHERE poll_option_id > ' . count($poll_ary['poll_options']) . '
2001                      AND topic_id = ' . $data_ary['topic_id'];
2002              $db->sql_query($sql);
2003          }
2004  
2005          // If edited, we would need to reset votes (since options can be re-ordered above, you can't be sure if the change is for changing the text or adding an option
2006          if ($mode == 'edit' && count($poll_ary['poll_options']) != count($cur_poll_options))
2007          {
2008              $db->sql_query('DELETE FROM ' . POLL_VOTES_TABLE . ' WHERE topic_id = ' . $data_ary['topic_id']);
2009              $db->sql_query('UPDATE ' . POLL_OPTIONS_TABLE . ' SET poll_option_total = 0 WHERE topic_id = ' . $data_ary['topic_id']);
2010          }
2011      }
2012  
2013      // Submit Attachments
2014      if (!empty($data_ary['attachment_data']) && $data_ary['post_id'] && in_array($mode, array('post', 'reply', 'quote', 'edit')))
2015      {
2016          $space_taken = $files_added = 0;
2017          $orphan_rows = array();
2018  
2019          foreach ($data_ary['attachment_data'] as $pos => $attach_row)
2020          {
2021              $orphan_rows[(int) $attach_row['attach_id']] = array();
2022          }
2023  
2024          if (count($orphan_rows))
2025          {
2026              $sql = 'SELECT attach_id, filesize, physical_filename
2027                  FROM ' . ATTACHMENTS_TABLE . '
2028                  WHERE ' . $db->sql_in_set('attach_id', array_keys($orphan_rows)) . '
2029                      AND is_orphan = 1
2030                      AND poster_id = ' . $user->data['user_id'];
2031              $result = $db->sql_query($sql);
2032  
2033              $orphan_rows = array();
2034              while ($row = $db->sql_fetchrow($result))
2035              {
2036                  $orphan_rows[$row['attach_id']] = $row;
2037              }
2038              $db->sql_freeresult($result);
2039          }
2040  
2041          foreach ($data_ary['attachment_data'] as $pos => $attach_row)
2042          {
2043              if ($attach_row['is_orphan'] && !isset($orphan_rows[$attach_row['attach_id']]))
2044              {
2045                  continue;
2046              }
2047  
2048              if (!$attach_row['is_orphan'])
2049              {
2050                  // update entry in db if attachment already stored in db and filespace
2051                  $sql = 'UPDATE ' . ATTACHMENTS_TABLE . "
2052                      SET attach_comment = '" . $db->sql_escape($attach_row['attach_comment']) . "'
2053                      WHERE attach_id = " . (int) $attach_row['attach_id'] . '
2054                          AND is_orphan = 0';
2055                  $db->sql_query($sql);
2056              }
2057              else
2058              {
2059                  // insert attachment into db
2060                  if (!@file_exists($phpbb_root_path . $config['upload_path'] . '/' . utf8_basename($orphan_rows[$attach_row['attach_id']]['physical_filename'])))
2061                  {
2062                      continue;
2063                  }
2064  
2065                  $space_taken += $orphan_rows[$attach_row['attach_id']]['filesize'];
2066                  $files_added++;
2067  
2068                  $attach_sql = array(
2069                      'post_msg_id'        => $data_ary['post_id'],
2070                      'topic_id'            => $data_ary['topic_id'],
2071                      'is_orphan'            => 0,
2072                      'poster_id'            => $poster_id,
2073                      'attach_comment'    => $attach_row['attach_comment'],
2074                  );
2075  
2076                  $sql = 'UPDATE ' . ATTACHMENTS_TABLE . ' SET ' . $db->sql_build_array('UPDATE', $attach_sql) . '
2077                      WHERE attach_id = ' . $attach_row['attach_id'] . '
2078                          AND is_orphan = 1
2079                          AND poster_id = ' . $user->data['user_id'];
2080                  $db->sql_query($sql);
2081              }
2082          }
2083  
2084          if ($space_taken && $files_added)
2085          {
2086              $config->increment('upload_dir_size', $space_taken, false);
2087              $config->increment('num_files', $files_added, false);
2088          }
2089      }
2090  
2091      $first_post_has_topic_info = ($post_mode == 'edit_first_post' &&
2092              (($post_visibility == ITEM_DELETED && $data_ary['topic_posts_softdeleted'] == 1) ||
2093              ($post_visibility == ITEM_UNAPPROVED && $data_ary['topic_posts_unapproved'] == 1) ||
2094              ($post_visibility == ITEM_REAPPROVE && $data_ary['topic_posts_unapproved'] == 1) ||
2095              ($post_visibility == ITEM_APPROVED && $data_ary['topic_posts_approved'] == 1)));
2096      // Fix the post's and topic's visibility and first/last post information, when the post is edited
2097      if (($post_mode != 'post' && $post_mode != 'reply') && $data_ary['post_visibility'] != $post_visibility)
2098      {
2099          // If the post was not approved, it could also be the starter,
2100          // so we sync the starter after approving/restoring, to ensure that the stats are correct
2101          // Same applies for the last post
2102          $is_starter = ($post_mode == 'edit_first_post' || $post_mode == 'edit_topic' || $data_ary['post_visibility'] != ITEM_APPROVED);
2103          $is_latest = ($post_mode == 'edit_last_post' || $post_mode == 'edit_topic' || $data_ary['post_visibility'] != ITEM_APPROVED);
2104  
2105          /* @var $phpbb_content_visibility \phpbb\content_visibility */
2106          $phpbb_content_visibility = $phpbb_container->get('content.visibility');
2107          $phpbb_content_visibility->set_post_visibility($post_visibility, $data_ary['post_id'], $data_ary['topic_id'], $data_ary['forum_id'], $user->data['user_id'], time(), '', $is_starter, $is_latest);
2108      }
2109      else if ($post_mode == 'edit_last_post' || $post_mode == 'edit_topic' || $first_post_has_topic_info)
2110      {
2111          if ($post_visibility == ITEM_APPROVED || $data_ary['topic_visibility'] == $post_visibility)
2112          {
2113              // only the subject can be changed from edit
2114              $sql_data[TOPICS_TABLE]['stat'][] = "topic_last_post_subject = '" . $db->sql_escape($subject) . "'";
2115  
2116              // Maybe not only the subject, but also changing anonymous usernames. ;)
2117              if ($data_ary['poster_id'] == ANONYMOUS)
2118              {
2119                  $sql_data[TOPICS_TABLE]['stat'][] = "topic_last_poster_name = '" . $db->sql_escape($username) . "'";
2120              }
2121  
2122              if ($post_visibility == ITEM_APPROVED)
2123              {
2124                  // this does not _necessarily_ mean that we must update the info again,
2125                  // it just means that we might have to
2126                  $sql = 'SELECT forum_last_post_id, forum_last_post_subject
2127                      FROM ' . FORUMS_TABLE . '
2128                      WHERE forum_id = ' . (int) $data_ary['forum_id'];
2129                  $result = $db->sql_query($sql);
2130                  $row = $db->sql_fetchrow($result);
2131                  $db->sql_freeresult($result);
2132  
2133                  // this post is the latest post in the forum, better update
2134                  if ($row['forum_last_post_id'] == $data_ary['post_id'] && ($row['forum_last_post_subject'] !== $subject || $data_ary['poster_id'] == ANONYMOUS))
2135                  {
2136                      // the post's subject changed
2137                      if ($row['forum_last_post_subject'] !== $subject)
2138                      {
2139                          $sql_data[FORUMS_TABLE]['stat'][] = "forum_last_post_subject = '" . $db->sql_escape($subject) . "'";
2140                      }
2141  
2142                      // Update the user name if poster is anonymous... just in case a moderator changed it
2143                      if ($data_ary['poster_id'] == ANONYMOUS)
2144                      {
2145                          $sql_data[FORUMS_TABLE]['stat'][] = "forum_last_poster_name = '" . $db->sql_escape($username) . "'";
2146                      }
2147                  }
2148              }
2149          }
2150      }
2151  
2152      // Update forum stats
2153      $where_sql = array(
2154          POSTS_TABLE        => 'post_id = ' . $data_ary['post_id'],
2155          TOPICS_TABLE    => 'topic_id = ' . $data_ary['topic_id'],
2156          FORUMS_TABLE    => 'forum_id = ' . $data_ary['forum_id'],
2157          USERS_TABLE        => 'user_id = ' . $poster_id
2158      );
2159  
2160      foreach ($sql_data as $table => $update_ary)
2161      {
2162          if (isset($update_ary['stat']) && implode('', $update_ary['stat']))
2163          {
2164              $sql = "UPDATE $table SET " . implode(', ', $update_ary['stat']) . ' WHERE ' . $where_sql[$table];
2165              $db->sql_query($sql);
2166          }
2167      }
2168  
2169      // Delete topic shadows (if any exist). We do not need a shadow topic for an global announcement
2170      if ($topic_type == POST_GLOBAL)
2171      {
2172          $sql = 'DELETE FROM ' . TOPICS_TABLE . '
2173              WHERE topic_moved_id = ' . $data_ary['topic_id'];
2174          $db->sql_query($sql);
2175      }
2176  
2177      // Committing the transaction before updating search index
2178      $db->sql_transaction('commit');
2179  
2180      // Delete draft if post was loaded...
2181      $draft_id = $request->variable('draft_loaded', 0);
2182      if ($draft_id)
2183      {
2184          $sql = 'DELETE FROM ' . DRAFTS_TABLE . "
2185              WHERE draft_id = $draft_id
2186                  AND user_id = {$user->data['user_id']}";
2187          $db->sql_query($sql);
2188      }
2189  
2190      // Index message contents
2191      if ($update_search_index && $data_ary['enable_indexing'])
2192      {
2193          // Select the search method and do some additional checks to ensure it can actually be utilised
2194          $search_type = $config['search_type'];
2195  
2196          if (!class_exists($search_type))
2197          {
2198              trigger_error('NO_SUCH_SEARCH_MODULE');
2199          }
2200  
2201          $error = false;
2202          $search = new $search_type($error, $phpbb_root_path, $phpEx, $auth, $config, $db, $user, $phpbb_dispatcher);
2203  
2204          if ($error)
2205          {
2206              trigger_error($error);
2207          }
2208  
2209          $search->index($mode, $data_ary['post_id'], $data_ary['message'], $subject, $poster_id, $data_ary['forum_id']);
2210      }
2211  
2212      // Topic Notification, do not change if moderator is changing other users posts...
2213      if ($user->data['user_id'] == $poster_id)
2214      {
2215          if (!$data_ary['notify_set'] && $data_ary['notify'])
2216          {
2217              $sql = 'INSERT INTO ' . TOPICS_WATCH_TABLE . ' (user_id, topic_id)
2218                  VALUES (' . $user->data['user_id'] . ', ' . $data_ary['topic_id'] . ')';
2219              $db->sql_query($sql);
2220          }
2221          else if (($config['email_enable'] || $config['jab_enable']) && $data_ary['notify_set'] && !$data_ary['notify'])
2222          {
2223              $sql = 'DELETE FROM ' . TOPICS_WATCH_TABLE . '
2224                  WHERE user_id = ' . $user->data['user_id'] . '
2225                      AND topic_id = ' . $data_ary['topic_id'];
2226              $db->sql_query($sql);
2227          }
2228      }
2229  
2230      if ($mode == 'post' || $mode == 'reply' || $mode == 'quote')
2231      {
2232          // Mark this topic as posted to
2233          markread('post', $data_ary['forum_id'], $data_ary['topic_id']);
2234      }
2235  
2236      // Mark this topic as read
2237      // We do not use post_time here, this is intended (post_time can have a date in the past if editing a message)
2238      markread('topic', $data_ary['forum_id'], $data_ary['topic_id'], time());
2239  
2240      //
2241      if ($config['load_db_lastread'] && $user->data['is_registered'])
2242      {
2243          $sql = 'SELECT mark_time
2244              FROM ' . FORUMS_TRACK_TABLE . '
2245              WHERE user_id = ' . $user->data['user_id'] . '
2246                  AND forum_id = ' . $data_ary['forum_id'];
2247          $result = $db->sql_query($sql);
2248          $f_mark_time = (int) $db->sql_fetchfield('mark_time');
2249          $db->sql_freeresult($result);
2250      }
2251      else if ($config['load_anon_lastread'] || $user->data['is_registered'])
2252      {
2253          $f_mark_time = false;
2254      }
2255  
2256      if (($config['load_db_lastread'] && $user->data['is_registered']) || $config['load_anon_lastread'] || $user->data['is_registered'])
2257      {
2258          // Update forum info
2259          $sql = 'SELECT forum_last_post_time
2260              FROM ' . FORUMS_TABLE . '
2261              WHERE forum_id = ' . $data_ary['forum_id'];
2262          $result = $db->sql_query($sql);
2263          $forum_last_post_time = (int) $db->sql_fetchfield('forum_last_post_time');
2264          $db->sql_freeresult($result);
2265  
2266          update_forum_tracking_info($data_ary['forum_id'], $forum_last_post_time, $f_mark_time, false);
2267      }
2268  
2269      // If a username was supplied or the poster is a guest, we will use the supplied username.
2270      // Doing it this way we can use "...post by guest-username..." in notifications when
2271      // "guest-username" is supplied or ommit the username if it is not.
2272      $username = ($username !== '' || !$user->data['is_registered']) ? $username : $user->data['username'];
2273  
2274      // Send Notifications
2275      $notification_data = array_merge($data_ary, array(
2276          'topic_title'        => (isset($data_ary['topic_title'])) ? $data_ary['topic_title'] : $subject,
2277          'post_username'        => $username,
2278          'poster_id'            => $poster_id,
2279          'post_text'            => $data_ary['message'],
2280          'post_time'            => $current_time,
2281          'post_subject'        => $subject,
2282      ));
2283  
2284      /* @var $phpbb_notifications \phpbb\notification\manager */
2285      $phpbb_notifications = $phpbb_container->get('notification_manager');
2286  
2287      if ($post_visibility == ITEM_APPROVED)
2288      {
2289          switch ($mode)
2290          {
2291              case 'post':
2292                  $phpbb_notifications->add_notifications(array(
2293                      'notification.type.quote',
2294                      'notification.type.topic',
2295                  ), $notification_data);
2296              break;
2297  
2298              case 'reply':
2299              case 'quote':
2300                  $phpbb_notifications->add_notifications(array(
2301                      'notification.type.quote',
2302                      'notification.type.bookmark',
2303                      'notification.type.post',
2304                  ), $notification_data);
2305              break;
2306  
2307              case 'edit_topic':
2308              case 'edit_first_post':
2309              case 'edit':
2310              case 'edit_last_post':
2311                  $phpbb_notifications->update_notifications(array(
2312                      'notification.type.quote',
2313                      'notification.type.bookmark',
2314                      'notification.type.topic',
2315                      'notification.type.post',
2316                  ), $notification_data);
2317              break;
2318          }
2319      }
2320      else if ($post_visibility == ITEM_UNAPPROVED)
2321      {
2322          switch ($mode)
2323          {
2324              case 'post':
2325                  $phpbb_notifications->add_notifications('notification.type.topic_in_queue', $notification_data);
2326              break;
2327  
2328              case 'reply':
2329              case 'quote':
2330                  $phpbb_notifications->add_notifications('notification.type.post_in_queue', $notification_data);
2331              break;
2332  
2333              case 'edit_topic':
2334              case 'edit_first_post':
2335              case 'edit':
2336              case 'edit_last_post':
2337                  // Nothing to do here
2338              break;
2339          }
2340      }
2341      else if ($post_visibility == ITEM_REAPPROVE)
2342      {
2343          switch ($mode)
2344          {
2345              case 'edit_topic':
2346              case 'edit_first_post':
2347                  $phpbb_notifications->add_notifications('notification.type.topic_in_queue', $notification_data);
2348  
2349                  // Delete the approve_post notification so we can notify the user again,
2350                  // when his post got reapproved
2351                  $phpbb_notifications->delete_notifications('notification.type.approve_post', $notification_data['post_id']);
2352              break;
2353  
2354              case 'edit':
2355              case 'edit_last_post':
2356                  $phpbb_notifications->add_notifications('notification.type.post_in_queue', $notification_data);
2357  
2358                  // Delete the approve_post notification so we can notify the user again,
2359                  // when his post got reapproved
2360                  $phpbb_notifications->delete_notifications('notification.type.approve_post', $notification_data['post_id']);
2361              break;
2362  
2363              case 'post':
2364              case 'reply':
2365              case 'quote':
2366                  // Nothing to do here
2367              break;
2368          }
2369      }
2370      else if ($post_visibility == ITEM_DELETED)
2371      {
2372          switch ($mode)
2373          {
2374              case 'post':
2375              case 'reply':
2376              case 'quote':
2377              case 'edit_topic':
2378              case 'edit_first_post':
2379              case 'edit':
2380              case 'edit_last_post':
2381                  // Nothing to do here
2382              break;
2383          }
2384      }
2385  
2386      $params = $add_anchor = '';
2387  
2388      if ($post_visibility == ITEM_APPROVED ||
2389          ($auth->acl_get('m_softdelete', $data_ary['forum_id']) && $post_visibility == ITEM_DELETED) ||
2390          ($auth->acl_get('m_approve', $data_ary['forum_id']) && in_array($post_visibility, array(ITEM_UNAPPROVED, ITEM_REAPPROVE))))
2391      {
2392          $params .= '&amp;t=' . $data_ary['topic_id'];
2393  
2394          if ($mode != 'post')
2395          {
2396              $params .= '&amp;p=' . $data_ary['post_id'];
2397              $add_anchor = '#p' . $data_ary['post_id'];
2398          }
2399      }
2400      else if ($mode != 'post' && $post_mode != 'edit_first_post' && $post_mode != 'edit_topic')
2401      {
2402          $params .= '&amp;t=' . $data_ary['topic_id'];
2403      }
2404  
2405      $url = (!$params) ? "{$phpbb_root_path}viewforum.$phpEx" : "{$phpbb_root_path}viewtopic.$phpEx";
2406      $url = append_sid($url, 'f=' . $data_ary['forum_id'] . $params) . $add_anchor;
2407  
2408      $poll = $poll_ary;
2409      $data = $data_ary;
2410      /**
2411      * This event is used for performing actions directly after a post or topic
2412      * has been submitted. When a new topic is posted, the topic ID is
2413      * available in the $data array.
2414      *
2415      * The only action that can be done by altering data made available to this
2416      * event is to modify the return URL ($url).
2417      *
2418      * @event core.submit_post_end
2419      * @var    string    mode                Variable containing posting mode value
2420      * @var    string    subject                Variable containing post subject value
2421      * @var    string    username            Variable containing post author name
2422      * @var    int        topic_type            Variable containing topic type value
2423      * @var    array    poll                Array with the poll data for the post
2424      * @var    array    data                Array with the data for the post
2425      * @var    int        post_visibility        Variable containing up to date post visibility
2426      * @var    bool    update_message        Flag indicating if the post will be updated
2427      * @var    bool    update_search_index    Flag indicating if the search index will be updated
2428      * @var    string    url                    The "Return to topic" URL
2429      *
2430      * @since 3.1.0-a3
2431      * @changed 3.1.0-RC3 Added vars mode, subject, username, topic_type,
2432      *        poll, update_message, update_search_index
2433      */
2434      $vars = array(
2435          'mode',
2436          'subject',
2437          'username',
2438          'topic_type',
2439          'poll',
2440          'data',
2441          'post_visibility',
2442          'update_message',
2443          'update_search_index',
2444          'url',
2445      );
2446      extract($phpbb_dispatcher->trigger_event('core.submit_post_end', compact($vars)));
2447      $data_ary = $data;
2448      $poll_ary = $poll;
2449      unset($data);
2450      unset($poll);
2451  
2452      return $url;
2453  }
2454  
2455  /**
2456  * Handle topic bumping
2457  * @param int $forum_id The ID of the forum the topic is being bumped belongs to
2458  * @param int $topic_id The ID of the topic is being bumping
2459  * @param array $post_data Passes some topic parameters:
2460  *                - 'topic_title'
2461  *                - 'topic_last_post_id'
2462  *                - 'topic_last_poster_id'
2463  *                - 'topic_last_post_subject'
2464  *                - 'topic_last_poster_name'
2465  *                - 'topic_last_poster_colour'
2466  * @param int $bump_time The time at which topic was bumped, usually it is a current time as obtained via time().
2467  * @return string An URL to the bumped topic, example: ./viewtopic.php?forum_id=1&amptopic_id=2&ampp=3#p3
2468  */
2469  function phpbb_bump_topic($forum_id, $topic_id, $post_data, $bump_time = false)
2470  {
2471      global $config, $db, $user, $phpEx, $phpbb_root_path, $phpbb_log;
2472  
2473      if ($bump_time === false)
2474      {
2475          $bump_time = time();
2476      }
2477  
2478      // Begin bumping
2479      $db->sql_transaction('begin');
2480  
2481      // Update the topic's last post post_time
2482      $sql = 'UPDATE ' . POSTS_TABLE . "
2483          SET post_time = $bump_time
2484          WHERE post_id = {$post_data['topic_last_post_id']}
2485              AND topic_id = $topic_id";
2486      $db->sql_query($sql);
2487  
2488      // Sync the topic's last post time, the rest of the topic's last post data isn't changed
2489      $sql = 'UPDATE ' . TOPICS_TABLE . "
2490          SET topic_last_post_time = $bump_time,
2491              topic_bumped = 1,
2492              topic_bumper = " . $user->data['user_id'] . "
2493          WHERE topic_id = $topic_id";
2494      $db->sql_query($sql);
2495  
2496      // Update the forum's last post info
2497      $sql = 'UPDATE ' . FORUMS_TABLE . "
2498          SET forum_last_post_id = " . $post_data['topic_last_post_id'] . ",
2499              forum_last_poster_id = " . $post_data['topic_last_poster_id'] . ",
2500              forum_last_post_subject = '" . $db->sql_escape($post_data['topic_last_post_subject']) . "',
2501              forum_last_post_time = $bump_time,
2502              forum_last_poster_name = '" . $db->sql_escape($post_data['topic_last_poster_name']) . "',
2503              forum_last_poster_colour = '" . $db->sql_escape($post_data['topic_last_poster_colour']) . "'
2504          WHERE forum_id = $forum_id";
2505      $db->sql_query($sql);
2506  
2507      // Update bumper's time of the last posting to prevent flood
2508      $sql = 'UPDATE ' . USERS_TABLE . "
2509          SET user_lastpost_time = $bump_time
2510          WHERE user_id = " . $user->data['user_id'];
2511      $db->sql_query($sql);
2512  
2513      $db->sql_transaction('commit');
2514  
2515      // Mark this topic as posted to
2516      markread('post', $forum_id, $topic_id, $bump_time);
2517  
2518      // Mark this topic as read
2519      markread('topic', $forum_id, $topic_id, $bump_time);
2520  
2521      // Update forum tracking info
2522      if ($config['load_db_lastread'] && $user->data['is_registered'])
2523      {
2524          $sql = 'SELECT mark_time
2525              FROM ' . FORUMS_TRACK_TABLE . '
2526              WHERE user_id = ' . $user->data['user_id'] . '
2527                  AND forum_id = ' . $forum_id;
2528          $result = $db->sql_query($sql);
2529          $f_mark_time = (int) $db->sql_fetchfield('mark_time');
2530          $db->sql_freeresult($result);
2531      }
2532      else if ($config['load_anon_lastread'] || $user->data['is_registered'])
2533      {
2534          $f_mark_time = false;
2535      }
2536  
2537      if (($config['load_db_lastread'] && $user->data['is_registered']) || $config['load_anon_lastread'] || $user->data['is_registered'])
2538      {
2539          // Update forum info
2540          $sql = 'SELECT forum_last_post_time
2541              FROM ' . FORUMS_TABLE . '
2542              WHERE forum_id = ' . $forum_id;
2543          $result = $db->sql_query($sql);
2544          $forum_last_post_time = (int) $db->sql_fetchfield('forum_last_post_time');
2545          $db->sql_freeresult($result);
2546  
2547          update_forum_tracking_info($forum_id, $forum_last_post_time, $f_mark_time, false);
2548      }
2549  
2550      $phpbb_log->add('mod', $user->data['user_id'], $user->ip, 'LOG_BUMP_TOPIC', false, array(
2551          'forum_id' => $forum_id,
2552          'topic_id' => $topic_id,
2553          $post_data['topic_title']
2554      ));
2555  
2556      $url = append_sid("{$phpbb_root_path}viewtopic.$phpEx", "f=$forum_id&amp;t=$topic_id&amp;p={$post_data['topic_last_post_id']}") . "#p{$post_data['topic_last_post_id']}";
2557  
2558      return $url;
2559  }
2560  
2561  /**
2562  * Show upload popup (progress bar)
2563  */
2564  function phpbb_upload_popup($forum_style = 0)
2565  {
2566      global $template, $user;
2567  
2568      ($forum_style) ? $user->setup('posting', $forum_style) : $user->setup('posting');
2569  
2570      page_header($user->lang['PROGRESS_BAR']);
2571  
2572      $template->set_filenames(array(
2573              'popup'    => 'posting_progress_bar.html')
2574      );
2575  
2576      $template->assign_vars(array(
2577              'PROGRESS_BAR'    => $user->img('upload_bar', $user->lang['UPLOAD_IN_PROGRESS']))
2578      );
2579  
2580      $template->display('popup');
2581  
2582      garbage_collection();
2583      exit_handler();
2584  }
2585  
2586  /**
2587  * Do the various checks required for removing posts as well as removing it
2588  *
2589  * @param int        $forum_id        The id of the forum
2590  * @param int        $topic_id        The id of the topic
2591  * @param int        $post_id        The id of the post
2592  * @param array        $post_data        Array with the post data
2593  * @param bool        $is_soft        The flag indicating whether it is the soft delete mode
2594  * @param string        $delete_reason    Description for the post deletion reason
2595  *
2596  * @return null
2597  */
2598  function phpbb_handle_post_delete($forum_id, $topic_id, $post_id, &$post_data, $is_soft = false, $delete_reason = '')
2599  {
2600      global $user, $auth, $config, $request;
2601      global $phpbb_root_path, $phpEx, $phpbb_log, $phpbb_dispatcher;
2602  
2603      $force_delete_allowed = $force_softdelete_allowed = false;
2604      $perm_check = ($is_soft) ? 'softdelete' : 'delete';
2605  
2606      /**
2607      * This event allows to modify the conditions for the post deletion
2608      *
2609      * @event core.handle_post_delete_conditions
2610      * @var    int        forum_id        The id of the forum
2611      * @var    int        topic_id        The id of the topic
2612      * @var    int        post_id            The id of the post
2613      * @var    array    post_data        Array with the post data
2614      * @var    bool    is_soft            The flag indicating whether it is the soft delete mode
2615      * @var    string    delete_reason    Description for the post deletion reason
2616      * @var    bool    force_delete_allowed        Allow the user to delete the post (all permissions and conditions are ignored)
2617      * @var    bool    force_softdelete_allowed    Allow the user to softdelete the post (all permissions and conditions are ignored)
2618      * @var    string    perm_check        The deletion mode softdelete|delete
2619      * @since 3.1.11-RC1
2620      */
2621      $vars = array(
2622          'forum_id',
2623          'topic_id',
2624          'post_id',
2625          'post_data',
2626          'is_soft',
2627          'delete_reason',
2628          'force_delete_allowed',
2629          'force_softdelete_allowed',
2630          'perm_check',
2631      );
2632      extract($phpbb_dispatcher->trigger_event('core.handle_post_delete_conditions', compact($vars)));
2633  
2634      // If moderator removing post or user itself removing post, present a confirmation screen
2635      if ($force_delete_allowed || ($is_soft && $force_softdelete_allowed) || $auth->acl_get("m_$perm_check", $forum_id) || ($post_data['poster_id'] == $user->data['user_id'] && $user->data['is_registered'] && $auth->acl_get("f_$perm_check", $forum_id) && $post_id == $post_data['topic_last_post_id'] && !$post_data['post_edit_locked'] && ($post_data['post_time'] > time() - ($config['delete_time'] * 60) || !$config['delete_time'])))
2636      {
2637          $s_hidden_fields = array(
2638              'p'        => $post_id,
2639              'f'        => $forum_id,
2640              'mode'    => ($is_soft) ? 'soft_delete' : 'delete',
2641          );
2642  
2643          if (confirm_box(true))
2644          {
2645              $data = array(
2646                  'topic_first_post_id'    => $post_data['topic_first_post_id'],
2647                  'topic_last_post_id'    => $post_data['topic_last_post_id'],
2648                  'topic_posts_approved'        => $post_data['topic_posts_approved'],
2649                  'topic_posts_unapproved'    => $post_data['topic_posts_unapproved'],
2650                  'topic_posts_softdeleted'    => $post_data['topic_posts_softdeleted'],
2651                  'topic_visibility'        => $post_data['topic_visibility'],
2652                  'topic_type'            => $post_data['topic_type'],
2653                  'post_visibility'        => $post_data['post_visibility'],
2654                  'post_reported'            => $post_data['post_reported'],
2655                  'post_time'                => $post_data['post_time'],
2656                  'poster_id'                => $post_data['poster_id'],
2657                  'post_postcount'        => $post_data['post_postcount'],
2658              );
2659  
2660              $next_post_id = delete_post($forum_id, $topic_id, $post_id, $data, $is_soft, $delete_reason);
2661              $post_username = ($post_data['poster_id'] == ANONYMOUS && !empty($post_data['post_username'])) ? $post_data['post_username'] : $post_data['username'];
2662  
2663              if ($next_post_id === false)
2664              {
2665                  $phpbb_log->add('mod', $user->data['user_id'], $user->ip, (($is_soft) ? 'LOG_SOFTDELETE_TOPIC' : 'LOG_DELETE_TOPIC'), false, array(
2666                      'forum_id' => $forum_id,
2667                      'topic_id' => $topic_id,
2668                      $post_data['topic_title'],
2669                      $post_username,
2670                      $delete_reason
2671                  ));
2672  
2673                  $meta_info = append_sid("{$phpbb_root_path}viewforum.$phpEx", "f=$forum_id");
2674                  $message = $user->lang['POST_DELETED'];
2675              }
2676              else
2677              {
2678                  $phpbb_log->add('mod', $user->data['user_id'], $user->ip, (($is_soft) ? 'LOG_SOFTDELETE_POST' : 'LOG_DELETE_POST'), false, array(
2679                      'forum_id' => $forum_id,
2680                      'topic_id' => $topic_id,
2681                      'post_id'  => $post_id,
2682                      $post_data['post_subject'],
2683                      $post_username,
2684                      $delete_reason
2685                  ));
2686  
2687                  $meta_info = append_sid("{$phpbb_root_path}viewtopic.$phpEx", "f=$forum_id&amp;t=$topic_id&amp;p=$next_post_id") . "#p$next_post_id";
2688                  $message = $user->lang['POST_DELETED'];
2689  
2690                  if (!$request->is_ajax())
2691                  {
2692                      $message .= '<br /><br />' . $user->lang('RETURN_TOPIC', '<a href="' . $meta_info . '">', '</a>');
2693                  }
2694              }
2695  
2696              meta_refresh(3, $meta_info);
2697              if (!$request->is_ajax())
2698              {
2699                  $message .= '<br /><br />' . $user->lang('RETURN_FORUM', '<a href="' . append_sid("{$phpbb_root_path}viewforum.$phpEx", 'f=' . $forum_id) . '">', '</a>');
2700              }
2701              trigger_error($message);
2702          }
2703          else
2704          {
2705              global $template;
2706  
2707              $can_delete = $force_delete_allowed || ($auth->acl_get('m_delete', $forum_id) || ($post_data['poster_id'] == $user->data['user_id'] && $user->data['is_registered'] && $auth->acl_get('f_delete', $forum_id)));
2708              $can_softdelete = $force_softdelete_allowed || ($auth->acl_get('m_softdelete', $forum_id) || ($post_data['poster_id'] == $user->data['user_id'] && $user->data['is_registered'] && $auth->acl_get('f_softdelete', $forum_id)));
2709  
2710              $template->assign_vars(array(
2711                  'S_SOFTDELETED'            => $post_data['post_visibility'] == ITEM_DELETED,
2712                  'S_CHECKED_PERMANENT'    => $request->is_set_post('delete_permanent') ? ' checked="checked"' : '',
2713                  'S_ALLOWED_DELETE'        => $can_delete,
2714                  'S_ALLOWED_SOFTDELETE'    => $can_softdelete,
2715              ));
2716  
2717              $l_confirm = 'DELETE_POST';
2718              if ($post_data['post_visibility'] == ITEM_DELETED)
2719              {
2720                  $l_confirm .= '_PERMANENTLY';
2721                  $s_hidden_fields['delete_permanent'] = '1';
2722              }
2723              else if (!$can_softdelete)
2724              {
2725                  $s_hidden_fields['delete_permanent'] = '1';
2726              }
2727  
2728              confirm_box(false, $l_confirm, build_hidden_fields($s_hidden_fields), 'confirm_delete_body.html');
2729          }
2730      }
2731  
2732      // If we are here the user is not able to delete - present the correct error message
2733      if ($post_data['poster_id'] != $user->data['user_id'] && $auth->acl_get('f_delete', $forum_id))
2734      {
2735          trigger_error('DELETE_OWN_POSTS');
2736      }
2737  
2738      if ($post_data['poster_id'] == $user->data['user_id'] && $auth->acl_get('f_delete', $forum_id) && $post_id != $post_data['topic_last_post_id'])
2739      {
2740          trigger_error('CANNOT_DELETE_REPLIED');
2741      }
2742  
2743      trigger_error('USER_CANNOT_DELETE');
2744  }


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