[ Index ]

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


Generated: Tue Apr 7 19:44:41 2020 Cross-referenced by PHPXref 0.7.1