[ Index ]

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


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