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