Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 1074
n/a
0 / 0
CRAP
n/a
0 / 0
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*/
17define('IN_PHPBB', true);
18$phpbb_root_path = (defined('PHPBB_ROOT_PATH')) ? PHPBB_ROOT_PATH : './';
19$phpEx = substr(strrchr(__FILE__, '.'), 1);
20include($phpbb_root_path . 'common.' . $phpEx);
21include($phpbb_root_path . 'includes/functions_posting.' . $phpEx);
22include($phpbb_root_path . 'includes/functions_display.' . $phpEx);
23include($phpbb_root_path . 'includes/message_parser.' . $phpEx);
24
25
26// Start session management
27$user->session_begin();
28$auth->acl($user->data);
29
30
31// Grab only parameters needed here
32$draft_id    = $request->variable('d', 0);
33
34$preview    = (isset($_POST['preview'])) ? true : false;
35$save        = (isset($_POST['save'])) ? true : false;
36$load        = (isset($_POST['load'])) ? true : false;
37$confirm    = $request->is_set_post('confirm');
38$cancel        = (isset($_POST['cancel']) && !isset($_POST['save'])) ? true : false;
39
40$refresh    = (isset($_POST['add_file']) || isset($_POST['delete_file']) || $save || $load || $preview);
41$submit = $request->is_set_post('post') && !$refresh && !$preview;
42$mode        = $request->variable('mode', '');
43
44// Only assign required URL parameters
45$forum_id = 0;
46$topic_id = 0;
47$post_id = 0;
48
49switch ($mode)
50{
51    case 'popup':
52    case 'smilies':
53        $forum_id = $request->variable('f', 0);
54    break;
55
56    case 'post':
57        $forum_id = $request->variable('f', 0);
58        if (!$forum_id)
59        {
60            trigger_error('NO_FORUM');
61        }
62    break;
63
64    case 'bump':
65    case 'reply':
66        $topic_id = $request->variable('t', 0);
67        if ($topic_id)
68        {
69            $sql = 'SELECT forum_id
70                FROM ' . TOPICS_TABLE . "
71                WHERE topic_id = $topic_id";
72            $result = $db->sql_query($sql);
73            $forum_id = (int) $db->sql_fetchfield('forum_id');
74            $db->sql_freeresult($result);
75        }
76
77        if (!$topic_id || !$forum_id)
78        {
79            trigger_error('NO_TOPIC');
80        }
81    break;
82
83    case 'edit':
84    case 'delete':
85    case 'quote':
86    case 'soft_delete':
87        $post_id = $request->variable('p', 0);
88        if ($post_id)
89        {
90            $topic_forum = [];
91
92            $sql = 'SELECT t.topic_id, t.forum_id
93                FROM ' . TOPICS_TABLE . ' t, ' . POSTS_TABLE . ' p
94                WHERE p.post_id = ' . $post_id . '
95                AND t.topic_id = p.topic_id';
96            $result = $db->sql_query($sql);
97            $topic_forum = $db->sql_fetchrow($result);
98            $db->sql_freeresult($result);
99        }
100
101        if (!$post_id || !$topic_forum)
102        {
103            $user->setup('posting');
104            trigger_error('NO_POST');
105        }
106
107        // Need to update session forum_id to valid value for proper viewonline information
108        if (!$forum_id)
109        {
110            $user->page['forum'] = (int) $topic_forum['forum_id'];
111            $user->update_session_page = true;
112            $user->update_session_infos();
113        }
114
115        $topic_id = (int) $topic_forum['topic_id'];
116        $forum_id = (int) $topic_forum['forum_id'];
117
118    break;
119}
120
121// If the user is not allowed to delete the post, we try to soft delete it, so we overwrite the mode here.
122if ($mode == 'delete' && (($confirm && !$request->is_set_post('delete_permanent')) || !$auth->acl_gets('f_delete', 'm_delete', $forum_id)))
123{
124    $mode = 'soft_delete';
125}
126
127$error = $post_data = array();
128$current_time = time();
129
130/**
131* This event allows you to alter the above parameters, such as submit and mode
132*
133* Note: $refresh must be true to retain previously submitted form data.
134*
135* Note: The template class will not work properly until $user->setup() is
136* called, and it has not been called yet. Extensions requiring template
137* assignments should use an event that comes later in this file.
138*
139* @event core.modify_posting_parameters
140* @var    int        post_id        ID of the post
141* @var    int        topic_id    ID of the topic
142* @var    int        forum_id    ID of the forum
143* @var    int        draft_id    ID of the draft
144* @var    bool    submit        Whether or not the form has been submitted
145* @var    bool    preview        Whether or not the post is being previewed
146* @var    bool    save        Whether or not a draft is being saved
147* @var    bool    load        Whether or not a draft is being loaded
148* @var    bool    cancel        Whether or not to cancel the form (returns to
149*                            viewtopic or viewforum depending on if the user
150*                            is posting a new topic or editing a post)
151* @var    bool    refresh        Whether or not to retain previously submitted data
152* @var    string    mode        What action to take if the form has been submitted
153*                            post|reply|quote|edit|delete|bump|smilies|popup
154* @var    array    error        Any error strings; a non-empty array aborts
155*                            form submission.
156*                            NOTE: Should be actual language strings, NOT
157*                            language keys.
158* @since 3.1.0-a1
159* @changed 3.1.2-RC1            Removed 'delete' var as it does not exist
160* @changed 3.2.4-RC1        Remove unused 'lastclick' var
161*/
162$vars = array(
163    'post_id',
164    'topic_id',
165    'forum_id',
166    'draft_id',
167    'submit',
168    'preview',
169    'save',
170    'load',
171    'cancel',
172    'refresh',
173    'mode',
174    'error',
175);
176extract($phpbb_dispatcher->trigger_event('core.modify_posting_parameters', compact($vars)));
177
178// Was cancel pressed? If so then redirect to the appropriate page
179if ($cancel)
180{
181    $redirect = ($post_id) ? append_sid("{$phpbb_root_path}viewtopic.$phpEx", 'p=' . $post_id) . '#p' . $post_id : (($topic_id) ? append_sid("{$phpbb_root_path}viewtopic.$phpEx", 't=' . $topic_id) : (($forum_id) ? append_sid("{$phpbb_root_path}viewforum.$phpEx", 'f=' . $forum_id) : append_sid("{$phpbb_root_path}index.$phpEx")));
182    redirect($redirect);
183}
184
185/* @var $phpbb_content_visibility \phpbb\content_visibility */
186$phpbb_content_visibility = $phpbb_container->get('content.visibility');
187
188// We need to know some basic information in all cases before we do anything.
189switch ($mode)
190{
191    case 'post':
192        $sql = 'SELECT *
193            FROM ' . FORUMS_TABLE . "
194            WHERE forum_id = $forum_id";
195    break;
196
197    case 'bump':
198    case 'reply':
199        $sql = 'SELECT f.*, t.*
200            FROM ' . TOPICS_TABLE . ' t, ' . FORUMS_TABLE . " f
201            WHERE t.topic_id = $topic_id
202                AND f.forum_id = t.forum_id
203                AND " . $phpbb_content_visibility->get_visibility_sql('topic', $forum_id, 't.');
204    break;
205
206    case 'quote':
207    case 'edit':
208    case 'delete':
209    case 'soft_delete':
210        $sql = 'SELECT f.*, t.*, p.*, u.username, u.username_clean, u.user_sig, u.user_sig_bbcode_uid, u.user_sig_bbcode_bitfield
211            FROM ' . POSTS_TABLE . ' p, ' . TOPICS_TABLE . ' t, ' . FORUMS_TABLE . ' f, ' . USERS_TABLE . " u
212            WHERE p.post_id = $post_id
213                AND t.topic_id = p.topic_id
214                AND u.user_id = p.poster_id
215                AND f.forum_id = t.forum_id
216                AND " . $phpbb_content_visibility->get_visibility_sql('post', $forum_id, 'p.');
217    break;
218
219    case 'smilies':
220        $sql = '';
221        generate_smilies('window', $forum_id);
222    break;
223
224    case 'popup':
225        if ($forum_id)
226        {
227            $sql = 'SELECT forum_style
228                FROM ' . FORUMS_TABLE . '
229                WHERE forum_id = ' . $forum_id;
230        }
231        else
232        {
233            phpbb_upload_popup();
234            return;
235        }
236    break;
237
238    default:
239        $sql = '';
240    break;
241}
242
243if (!$sql)
244{
245    $user->setup('posting');
246    trigger_error('NO_POST_MODE');
247}
248
249$result = $db->sql_query($sql);
250$post_data = $db->sql_fetchrow($result);
251$db->sql_freeresult($result);
252
253if (!$post_data)
254{
255    if (!($mode == 'post' || $mode == 'bump' || $mode == 'reply'))
256    {
257        $user->setup('posting');
258    }
259    trigger_error(($mode == 'post' || $mode == 'bump' || $mode == 'reply') ? 'NO_TOPIC' : 'NO_POST');
260}
261
262/**
263* This event allows you to bypass reply/quote test of an unapproved post.
264*
265* @event core.posting_modify_row_data
266* @var    array    post_data    All post data from database
267* @var    string    mode        What action to take if the form has been submitted
268*                            post|reply|quote|edit|delete|bump|smilies|popup
269* @var    int        topic_id    ID of the topic
270* @var    int        forum_id    ID of the forum
271* @since 3.2.8-RC1
272*/
273$vars = array(
274    'post_data',
275    'mode',
276    'topic_id',
277    'forum_id',
278);
279extract($phpbb_dispatcher->trigger_event('core.posting_modify_row_data', compact($vars)));
280
281// Not able to reply to unapproved posts/topics
282// TODO: add more descriptive language key
283if ($auth->acl_get('m_approve', $forum_id) && ((($mode == 'reply' || $mode == 'bump') && $post_data['topic_visibility'] != ITEM_APPROVED) || ($mode == 'quote' && $post_data['post_visibility'] != ITEM_APPROVED)))
284{
285    trigger_error(($mode == 'reply' || $mode == 'bump') ? 'TOPIC_UNAPPROVED' : 'POST_UNAPPROVED');
286}
287
288if ($mode == 'popup')
289{
290    phpbb_upload_popup($post_data['forum_style']);
291    return;
292}
293
294$user->setup(array('posting', 'mcp', 'viewtopic'), $post_data['forum_style']);
295
296// Need to login to passworded forum first?
297if ($post_data['forum_password'])
298{
299    login_forum_box(array(
300        'forum_id'            => $forum_id,
301        'forum_name'        => $post_data['forum_name'],
302        'forum_password'    => $post_data['forum_password'])
303    );
304}
305
306// Check permissions
307if ($user->data['is_bot'])
308{
309    redirect(append_sid("{$phpbb_root_path}index.$phpEx"));
310}
311
312// Is the user able to read within this forum?
313if (!$auth->acl_get('f_read', $forum_id))
314{
315    if ($user->data['user_id'] != ANONYMOUS)
316    {
317        trigger_error('USER_CANNOT_READ');
318    }
319    $message = $user->lang['LOGIN_EXPLAIN_POST'];
320
321    if ($request->is_ajax())
322    {
323        $json = new phpbb\json_response();
324        $json->send(array(
325            'title'        => $user->lang['INFORMATION'],
326            'message'    => $message,
327        ));
328    }
329
330    login_box('', $message);
331}
332
333// Permission to do the action asked?
334$is_authed = false;
335
336switch ($mode)
337{
338    case 'post':
339        if ($auth->acl_get('f_post', $forum_id))
340        {
341            $is_authed = true;
342        }
343    break;
344
345    case 'bump':
346        if ($auth->acl_get('f_bump', $forum_id))
347        {
348            $is_authed = true;
349        }
350    break;
351
352    case 'quote':
353
354        $post_data['post_edit_locked'] = 0;
355
356    // no break;
357
358    case 'reply':
359        if ($auth->acl_get('f_reply', $forum_id))
360        {
361            $is_authed = true;
362        }
363    break;
364
365    case 'edit':
366        if ($user->data['is_registered'] && $auth->acl_gets('f_edit', 'm_edit', $forum_id))
367        {
368            $is_authed = true;
369        }
370    break;
371
372    case 'delete':
373        if ($user->data['is_registered'] && ($auth->acl_get('m_delete', $forum_id) || ($post_data['poster_id'] == $user->data['user_id'] && $auth->acl_get('f_delete', $forum_id))))
374        {
375            $is_authed = true;
376        }
377
378    // no break;
379
380    case 'soft_delete':
381        if (!$is_authed && $user->data['is_registered'] && $phpbb_content_visibility->can_soft_delete($forum_id, $post_data['poster_id'], $post_data['post_edit_locked']))
382        {
383            // Fall back to soft_delete if we have no permissions to delete posts but to soft delete them
384            $is_authed = true;
385            $mode = 'soft_delete';
386        }
387    break;
388}
389/**
390* This event allows you to do extra auth checks and verify if the user
391* has the required permissions
392*
393* Extensions should only change the error and is_authed variables.
394*
395* @event core.modify_posting_auth
396* @var    int        post_id        ID of the post
397* @var    int        topic_id    ID of the topic
398* @var    int        forum_id    ID of the forum
399* @var    int        draft_id    ID of the draft
400* @var    bool    submit        Whether or not the form has been submitted
401* @var    bool    preview        Whether or not the post is being previewed
402* @var    bool    save        Whether or not a draft is being saved
403* @var    bool    load        Whether or not a draft is being loaded
404* @var    bool    refresh        Whether or not to retain previously submitted data
405* @var    string    mode        What action to take if the form has been submitted
406*                            post|reply|quote|edit|delete|bump|smilies|popup
407* @var    array    error        Any error strings; a non-empty array aborts
408*                            form submission.
409*                            NOTE: Should be actual language strings, NOT
410*                            language keys.
411* @var    bool    is_authed    Does the user have the required permissions?
412* @var    array    post_data    All post data from database
413* @since 3.1.3-RC1
414* @changed 3.1.10-RC1 Added post_data
415* @changed 3.2.4-RC1         Remove unused 'lastclick' var
416*/
417$vars = array(
418    'post_id',
419    'topic_id',
420    'forum_id',
421    'draft_id',
422    'submit',
423    'preview',
424    'save',
425    'load',
426    'refresh',
427    'mode',
428    'error',
429    'is_authed',
430    'post_data',
431);
432extract($phpbb_dispatcher->trigger_event('core.modify_posting_auth', compact($vars)));
433
434if (!$is_authed || !empty($error))
435{
436    $check_auth = ($mode == 'quote') ? 'reply' : (($mode == 'soft_delete') ? 'delete' : $mode);
437
438    if ($user->data['is_registered'])
439    {
440        trigger_error(empty($error) ? 'USER_CANNOT_' . strtoupper($check_auth) : implode('<br/>', $error));
441    }
442    $message = $user->lang['LOGIN_EXPLAIN_' . strtoupper($mode)];
443
444    if ($request->is_ajax())
445    {
446        $json = new phpbb\json_response();
447        $json->send(array(
448            'title'        => $user->lang['INFORMATION'],
449            'message'    => $message,
450        ));
451    }
452
453    login_box('', $message);
454}
455
456if ($config['enable_post_confirm'] && !$user->data['is_registered'])
457{
458    /** @var \phpbb\captcha\factory $captcha_factory */
459    $captcha_factory = $phpbb_container->get('captcha.factory');
460    $captcha = $captcha_factory->get_instance($config['captcha_plugin']);
461    $captcha->init(\phpbb\captcha\plugins\confirm_type::POST);
462}
463
464// Is the user able to post within this forum?
465if ($post_data['forum_type'] != FORUM_POST && in_array($mode, array('post', 'bump', 'quote', 'reply')))
466{
467    trigger_error('USER_CANNOT_FORUM_POST');
468}
469
470// Forum/Topic locked?
471if (($post_data['forum_status'] == ITEM_LOCKED || (isset($post_data['topic_status']) && $post_data['topic_status'] == ITEM_LOCKED)) && !$auth->acl_get($mode == 'reply' ? 'm_lock' : 'm_edit', $forum_id))
472{
473    trigger_error(($post_data['forum_status'] == ITEM_LOCKED) ? 'FORUM_LOCKED' : 'TOPIC_LOCKED');
474}
475
476// Can we edit this post ... if we're a moderator with rights then always yes
477// else it depends on editing times, lock status and if we're the correct user
478if ($mode == 'edit' && !$auth->acl_get('m_edit', $forum_id))
479{
480    $force_edit_allowed = false;
481
482    $s_cannot_edit = $user->data['user_id'] != $post_data['poster_id'];
483    $s_cannot_edit_time = $config['edit_time'] && $post_data['post_time'] <= time() - ($config['edit_time'] * 60);
484    $s_cannot_edit_locked = $post_data['post_edit_locked'];
485
486    /**
487    * This event allows you to modify the conditions for the "cannot edit post" checks
488    *
489    * @event core.posting_modify_cannot_edit_conditions
490    * @var    array    post_data    Array with post data
491    * @var    bool    force_edit_allowed        Allow the user to edit the post (all permissions and conditions are ignored)
492    * @var    bool    s_cannot_edit            User can not edit the post because it's not his
493    * @var    bool    s_cannot_edit_locked    User can not edit the post because it's locked
494    * @var    bool    s_cannot_edit_time        User can not edit the post because edit_time has passed
495    * @since 3.1.0-b4
496    */
497    $vars = array(
498        'post_data',
499        'force_edit_allowed',
500        's_cannot_edit',
501        's_cannot_edit_locked',
502        's_cannot_edit_time',
503    );
504    extract($phpbb_dispatcher->trigger_event('core.posting_modify_cannot_edit_conditions', compact($vars)));
505
506    if (!$force_edit_allowed)
507    {
508        if ($s_cannot_edit)
509        {
510            trigger_error('USER_CANNOT_EDIT');
511        }
512        else if ($s_cannot_edit_time)
513        {
514            trigger_error('CANNOT_EDIT_TIME');
515        }
516        else if ($s_cannot_edit_locked)
517        {
518            trigger_error('CANNOT_EDIT_POST_LOCKED');
519        }
520    }
521}
522
523// Handle delete mode...
524if ($mode == 'delete' || $mode == 'soft_delete')
525{
526    if ($mode == 'soft_delete' && $post_data['post_visibility'] == ITEM_DELETED)
527    {
528        $user->setup('posting');
529        trigger_error('NO_POST');
530    }
531
532    $delete_reason = $request->variable('delete_reason', '', true);
533    phpbb_handle_post_delete($forum_id, $topic_id, $post_id, $post_data, ($mode == 'soft_delete' && !$request->is_set_post('delete_permanent')), $delete_reason);
534    return;
535}
536
537// Handle bump mode...
538if ($mode == 'bump')
539{
540    if ($bump_time = bump_topic_allowed($forum_id, $post_data['topic_bumped'], $post_data['topic_last_post_time'], $post_data['topic_poster'], $post_data['topic_last_poster_id'])
541        && check_link_hash($request->variable('hash', ''), "topic_{$post_data['topic_id']}"))
542    {
543        $meta_url = phpbb_bump_topic($forum_id, $topic_id, $post_data, $current_time);
544        meta_refresh(3, $meta_url);
545        $message = $user->lang['TOPIC_BUMPED'];
546
547        if (!$request->is_ajax())
548        {
549            $message .= '<br /><br />' . $user->lang('VIEW_MESSAGE', '<a href="' . $meta_url . '">', '</a>');
550            $message .= '<br /><br />' . $user->lang('RETURN_FORUM', '<a href="' . append_sid("{$phpbb_root_path}viewforum.$phpEx", 'f=' . $forum_id) . '">', '</a>');
551        }
552
553        trigger_error($message);
554    }
555
556    trigger_error('BUMP_ERROR');
557}
558
559// Subject length limiting to 60 characters if first post...
560if ($mode == 'post' || ($mode == 'edit' && $post_data['topic_first_post_id'] == $post_data['post_id']))
561{
562    $template->assign_var('S_NEW_MESSAGE', true);
563}
564
565// Determine some vars
566if (isset($post_data['poster_id']) && $post_data['poster_id'] == ANONYMOUS)
567{
568    $post_data['quote_username'] = (!empty($post_data['post_username'])) ? $post_data['post_username'] : $user->lang['GUEST'];
569}
570else
571{
572    $post_data['quote_username'] = isset($post_data['username']) ? $post_data['username'] : '';
573}
574
575$post_data['post_edit_locked']    = (isset($post_data['post_edit_locked'])) ? (int) $post_data['post_edit_locked'] : 0;
576$post_data['post_subject_md5']    = (isset($post_data['post_subject']) && $mode == 'edit') ? md5($post_data['post_subject']) : '';
577$post_data['post_subject']        = (in_array($mode, array('quote', 'edit'))) ? $post_data['post_subject'] : ((isset($post_data['topic_title'])) ? $post_data['topic_title'] : '');
578$post_data['topic_time_limit']    = (isset($post_data['topic_time_limit'])) ? (($post_data['topic_time_limit']) ? (int) $post_data['topic_time_limit'] / 86400 : (int) $post_data['topic_time_limit']) : 0;
579$post_data['poll_length']        = (!empty($post_data['poll_length'])) ? (int) $post_data['poll_length'] / 86400 : 0;
580$post_data['poll_start']        = (!empty($post_data['poll_start'])) ? (int) $post_data['poll_start'] : 0;
581$post_data['icon_id']            = (!isset($post_data['icon_id']) || in_array($mode, array('quote', 'reply'))) ? 0 : (int) $post_data['icon_id'];
582$post_data['poll_options']        = array();
583
584// Get Poll Data
585if ($post_data['poll_start'])
586{
587    $sql = 'SELECT poll_option_text
588        FROM ' . POLL_OPTIONS_TABLE . "
589        WHERE topic_id = $topic_id
590        ORDER BY poll_option_id";
591    $result = $db->sql_query($sql);
592
593    while ($row = $db->sql_fetchrow($result))
594    {
595        $post_data['poll_options'][] = trim($row['poll_option_text']);
596    }
597    $db->sql_freeresult($result);
598}
599
600/**
601* This event allows you to modify the post data before parsing
602*
603* @event core.posting_modify_post_data
604* @var    int        forum_id    ID of the forum
605* @var    string    mode        What action to take if the form has been submitted
606*                            post|reply|quote|edit|delete|bump|smilies|popup
607* @var    array    post_data    Array with post data
608* @var    int        post_id        ID of the post
609* @var    int        topic_id    ID of the topic
610* @since 3.2.2-RC1
611*/
612$vars = array(
613    'forum_id',
614    'mode',
615    'post_data',
616    'post_id',
617    'topic_id',
618);
619extract($phpbb_dispatcher->trigger_event('core.posting_modify_post_data', compact($vars)));
620
621if ($mode == 'edit')
622{
623    $original_poll_data = array(
624        'poll_title'        => $post_data['poll_title'],
625        'poll_length'        => $post_data['poll_length'],
626        'poll_max_options'    => $post_data['poll_max_options'],
627        'poll_option_text'    => implode("\n", $post_data['poll_options']),
628        'poll_start'        => $post_data['poll_start'],
629        'poll_last_vote'    => $post_data['poll_last_vote'],
630        'poll_vote_change'    => $post_data['poll_vote_change'],
631    );
632}
633
634$orig_poll_options_size = count($post_data['poll_options']);
635
636$message_parser = new parse_message();
637/* @var $plupload \phpbb\plupload\plupload */
638$plupload = $phpbb_container->get('plupload');
639
640/* @var $mimetype_guesser \phpbb\mimetype\guesser */
641$mimetype_guesser = $phpbb_container->get('mimetype.guesser');
642$message_parser->set_plupload($plupload);
643
644if (isset($post_data['post_text']))
645{
646    $message_parser->message = &$post_data['post_text'];
647    unset($post_data['post_text']);
648}
649
650// Set some default variables
651$uninit = array('post_attachment' => 0, 'poster_id' => $user->data['user_id'], 'enable_magic_url' => 0, 'topic_status' => 0, 'topic_type' => POST_NORMAL, 'post_subject' => '', 'topic_title' => '', 'post_time' => 0, 'post_edit_reason' => '', 'notify_set' => 0);
652
653/**
654* This event allows you to modify the default variables for post_data, and unset them in post_data if needed
655*
656* @event core.posting_modify_default_variables
657* @var    array    post_data    Array with post data
658* @var    array    uninit        Array with default vars to put into post_data, if they aren't there
659* @since 3.2.5-RC1
660*/
661$vars = array(
662    'post_data',
663    'uninit',
664);
665extract($phpbb_dispatcher->trigger_event('core.posting_modify_default_variables', compact($vars)));
666
667foreach ($uninit as $var_name => $default_value)
668{
669    if (!isset($post_data[$var_name]))
670    {
671        $post_data[$var_name] = $default_value;
672    }
673}
674unset($uninit);
675
676// Always check if the submitted attachment data is valid and belongs to the user.
677// Further down (especially in submit_post()) we do not check this again.
678$message_parser->get_submitted_attachment_data($post_data['poster_id']);
679
680if ($post_data['post_attachment'] && !$submit && !$refresh && !$preview && $mode == 'edit')
681{
682    // Do not change to SELECT *
683    $sql = 'SELECT attach_id, is_orphan, attach_comment, real_filename, filesize
684        FROM ' . ATTACHMENTS_TABLE . "
685        WHERE post_msg_id = $post_id
686            AND in_message = 0
687            AND is_orphan = 0
688        ORDER BY attach_id DESC";
689    $result = $db->sql_query($sql);
690    $message_parser->attachment_data = array_merge($message_parser->attachment_data, $db->sql_fetchrowset($result));
691    $db->sql_freeresult($result);
692}
693
694if ($post_data['poster_id'] == ANONYMOUS)
695{
696    $post_data['username'] = ($mode == 'quote' || $mode == 'edit') ? trim($post_data['post_username']) : '';
697}
698else
699{
700    $post_data['username'] = ($mode == 'quote' || $mode == 'edit') ? trim($post_data['username']) : '';
701}
702
703$post_data['enable_urls'] = $post_data['enable_magic_url'];
704
705if ($mode != 'edit')
706{
707    $post_data['enable_sig']        = ($config['allow_sig'] && $user->optionget('attachsig')) ? true: false;
708    $post_data['enable_smilies']    = ($config['allow_smilies'] && $user->optionget('smilies')) ? true : false;
709    $post_data['enable_bbcode']        = ($config['allow_bbcode'] && $user->optionget('bbcode')) ? true : false;
710    $post_data['enable_urls']        = true;
711}
712
713if ($mode == 'post')
714{
715    $post_data['topic_status']        = ($request->is_set_post('lock_topic') && $auth->acl_gets('m_lock', 'f_user_lock', $forum_id)) ? ITEM_LOCKED : ITEM_UNLOCKED;
716}
717
718$post_data['enable_magic_url'] = $post_data['drafts'] = false;
719
720// User own some drafts?
721if ($user->data['is_registered'] && $auth->acl_get('u_savedrafts') && ($mode == 'reply' || $mode == 'post' || $mode == 'quote'))
722{
723    $sql = 'SELECT draft_id
724        FROM ' . DRAFTS_TABLE . '
725        WHERE user_id = ' . $user->data['user_id'] .
726            (($forum_id) ? ' AND forum_id = ' . (int) $forum_id : '') .
727            (($topic_id) ? ' AND topic_id = ' . (int) $topic_id : '') .
728            (($draft_id) ? " AND draft_id <> $draft_id" : '');
729    $result = $db->sql_query_limit($sql, 1);
730
731    if ($db->sql_fetchrow($result))
732    {
733        $post_data['drafts'] = true;
734    }
735    $db->sql_freeresult($result);
736}
737
738$check_value = (($post_data['enable_bbcode']+1) << 8) + (($post_data['enable_smilies']+1) << 4) + (($post_data['enable_urls']+1) << 2) + (($post_data['enable_sig']+1) << 1);
739
740// Check if user is watching this topic
741if ($mode != 'post' && $config['allow_topic_notify'] && $user->data['is_registered'])
742{
743    $sql = 'SELECT topic_id
744        FROM ' . TOPICS_WATCH_TABLE . '
745        WHERE topic_id = ' . $topic_id . '
746            AND user_id = ' . $user->data['user_id'];
747    $result = $db->sql_query($sql);
748    $post_data['notify_set'] = (int) $db->sql_fetchfield('topic_id');
749    $db->sql_freeresult($result);
750}
751
752// Do we want to edit our post ?
753if ($mode == 'edit' && $post_data['bbcode_uid'])
754{
755    $message_parser->bbcode_uid = $post_data['bbcode_uid'];
756}
757
758// HTML, BBCode, Smilies and Images status
759$bbcode_status    = ($config['allow_bbcode'] && $auth->acl_get('f_bbcode', $forum_id)) ? true : false;
760$smilies_status    = ($config['allow_smilies'] && $auth->acl_get('f_smilies', $forum_id)) ? true : false;
761$img_status        = ($bbcode_status && $auth->acl_get('f_img', $forum_id)) ? true : false;
762$url_status        = ($config['allow_post_links']) ? true : false;
763$quote_status    = true;
764
765/**
766 * Event to override message BBCode status indications
767 *
768 * @event core.posting_modify_bbcode_status
769 *
770 * @var bool    bbcode_status    BBCode status
771 * @var bool    smilies_status    Smilies status
772 * @var bool    img_status        Image BBCode status
773 * @var bool    url_status        URL BBCode status
774 * @var bool    quote_status    Quote BBCode status
775 * @since 3.3.3-RC1
776 * @changed 4.0.0-a1 Removed flash_status
777 */
778$vars = [
779    'bbcode_status',
780    'smilies_status',
781    'img_status',
782    'url_status',
783    'quote_status',
784];
785extract($phpbb_dispatcher->trigger_event('core.posting_modify_bbcode_status', compact($vars)));
786
787// Save Draft
788if ($save && $user->data['is_registered'] && $auth->acl_get('u_savedrafts') && ($mode == 'reply' || $mode == 'post' || $mode == 'quote'))
789{
790    $subject = $request->variable('subject', '', true);
791    $subject = (!$subject && $mode != 'post') ? $post_data['topic_title'] : $subject;
792    $message = $request->variable('message', '', true);
793
794    /**
795     * Replace Emojis and other 4bit UTF-8 chars not allowed by MySQL to UCR/NCR.
796     * Using their Numeric Character Reference's Hexadecimal notation.
797     */
798    $subject = utf8_encode_ucr($subject);
799
800    if ($subject && $message)
801    {
802        if (confirm_box(true))
803        {
804            $message_parser->message = $message;
805            $message_parser->parse($post_data['enable_bbcode'], ($config['allow_post_links']) ? $post_data['enable_urls'] : false, $post_data['enable_smilies'], $img_status, $quote_status, $config['allow_post_links']);
806
807            $sql = 'INSERT INTO ' . DRAFTS_TABLE . ' ' . $db->sql_build_array('INSERT', array(
808                'user_id'        => (int) $user->data['user_id'],
809                'topic_id'        => (int) $topic_id,
810                'forum_id'        => (int) $forum_id,
811                'save_time'        => (int) $current_time,
812                'draft_subject'    => (string) $subject,
813                'draft_message'    => (string) $message_parser->message)
814            );
815            $db->sql_query($sql);
816
817            /** @var \phpbb\attachment\manager $attachment_manager */
818            $attachment_manager = $phpbb_container->get('attachment.manager');
819            $attachment_manager->delete('attach', array_column($message_parser->attachment_data, 'attach_id'));
820
821            $meta_info = ($mode == 'post') ? append_sid("{$phpbb_root_path}viewforum.$phpEx", 'f=' . $forum_id) : append_sid("{$phpbb_root_path}viewtopic.$phpEx", "t=$topic_id");
822
823            meta_refresh(3, $meta_info);
824
825            $message = $user->lang['DRAFT_SAVED'] . '<br /><br />';
826            $message .= ($mode != 'post') ? sprintf($user->lang['RETURN_TOPIC'], '<a href="' . $meta_info . '">', '</a>') . '<br /><br />' : '';
827            $message .= sprintf($user->lang['RETURN_FORUM'], '<a href="' . append_sid("{$phpbb_root_path}viewforum.$phpEx", 'f=' . $forum_id) . '">', '</a>');
828
829            trigger_error($message);
830        }
831        else
832        {
833            $s_hidden_fields = build_hidden_fields(array(
834                'mode'        => $mode,
835                'save'        => true,
836                'f'            => $forum_id,
837                't'            => $topic_id,
838                'subject'    => $subject,
839                'message'    => $message,
840                'attachment_data' => $message_parser->attachment_data,
841                )
842            );
843
844            $hidden_fields = array(
845                'icon_id'            => 0,
846
847                'disable_bbcode'    => false,
848                'disable_smilies'    => false,
849                'disable_magic_url'    => false,
850                'attach_sig'        => true,
851                'notify'            => false,
852                'lock_topic'        => false,
853
854                'topic_type'        => POST_NORMAL,
855                'topic_time_limit'    => 0,
856
857                'poll_title'        => '',
858                'poll_option_text'    => '',
859                'poll_max_options'    => 1,
860                'poll_length'        => 0,
861                'poll_vote_change'    => false,
862            );
863
864            foreach ($hidden_fields as $name => $default)
865            {
866                if (!isset($_POST[$name]))
867                {
868                    // Don't include it, if its not available
869                    unset($hidden_fields[$name]);
870                    continue;
871                }
872
873                if (is_bool($default))
874                {
875                    // Use the string representation
876                    $hidden_fields[$name] = $request->variable($name, '');
877                }
878                else
879                {
880                    $hidden_fields[$name] = $request->variable($name, $default);
881                }
882            }
883
884            $s_hidden_fields .= build_hidden_fields($hidden_fields);
885
886            confirm_box(false, 'SAVE_DRAFT', $s_hidden_fields);
887        }
888    }
889    else
890    {
891        if (utf8_clean_string($subject) === '')
892        {
893            $error[] = $user->lang['EMPTY_SUBJECT'];
894        }
895
896        if (utf8_clean_string($message) === '')
897        {
898            $error[] = $user->lang['TOO_FEW_CHARS'];
899        }
900    }
901    unset($subject, $message);
902}
903
904// Load requested Draft
905if ($draft_id && ($mode == 'reply' || $mode == 'quote' || $mode == 'post') && $user->data['is_registered'] && $auth->acl_get('u_savedrafts'))
906{
907    $sql = 'SELECT draft_subject, draft_message
908        FROM ' . DRAFTS_TABLE . "
909        WHERE draft_id = $draft_id
910            AND user_id = " . $user->data['user_id'];
911    $result = $db->sql_query_limit($sql, 1);
912    $row = $db->sql_fetchrow($result);
913    $db->sql_freeresult($result);
914
915    if ($row)
916    {
917        $post_data['post_subject'] = $row['draft_subject'];
918        $message_parser->message = $row['draft_message'];
919
920        $template->assign_var('S_DRAFT_LOADED', true);
921    }
922    else
923    {
924        $draft_id = 0;
925    }
926}
927
928// Load draft overview
929if ($load && ($mode == 'reply' || $mode == 'quote' || $mode == 'post') && $post_data['drafts'])
930{
931    load_drafts($topic_id, $forum_id);
932}
933
934/** @var \phpbb\textformatter\utils_interface $bbcode_utils */
935$bbcode_utils = $phpbb_container->get('text_formatter.utils');
936
937if ($submit || $preview || $refresh)
938{
939    $post_data['topic_cur_post_id']    = $request->variable('topic_cur_post_id', 0);
940    $post_data['post_subject']        = $request->variable('subject', '', true);
941    $message_parser->message        = $request->variable('message', '', true);
942
943    $post_data['username']            = $request->variable('username', $post_data['username'], true);
944    $post_data['post_edit_reason']    = ($request->variable('edit_reason', false, false, \phpbb\request\request_interface::POST) && $mode == 'edit' && $auth->acl_get('m_edit', $forum_id)) ? $request->variable('edit_reason', '', true) : '';
945
946    $post_data['orig_topic_type']    = $post_data['topic_type'];
947    $post_data['topic_type']        = $request->variable('topic_type', (($mode != 'post') ? (int) $post_data['topic_type'] : POST_NORMAL));
948    $post_data['topic_time_limit']    = $request->variable('topic_time_limit', (($mode != 'post') ? (int) $post_data['topic_time_limit'] : 0));
949
950    if ($post_data['enable_icons'] && $auth->acl_get('f_icons', $forum_id))
951    {
952        $post_data['icon_id'] = $request->variable('icon', (int) $post_data['icon_id']);
953    }
954
955    $post_data['enable_bbcode']        = (!$bbcode_status || isset($_POST['disable_bbcode'])) ? false : true;
956    $post_data['enable_smilies']    = (!$smilies_status || isset($_POST['disable_smilies'])) ? false : true;
957    $post_data['enable_urls']        = (isset($_POST['disable_magic_url'])) ? 0 : 1;
958    $post_data['enable_sig']        = (!$config['allow_sig'] || !$auth->acl_get('f_sigs', $forum_id) || !$auth->acl_get('u_sig')) ? false : ((isset($_POST['attach_sig']) && $user->data['is_registered']) ? true : false);
959
960    if ($config['allow_topic_notify'] && $user->data['is_registered'])
961    {
962        $notify = (isset($_POST['notify'])) ? true : false;
963    }
964    else
965    {
966        $notify = false;
967    }
968
969    $topic_lock            = (isset($_POST['lock_topic'])) ? true : false;
970    $post_lock            = (isset($_POST['lock_post'])) ? true : false;
971    $poll_delete        = (isset($_POST['poll_delete'])) ? true : false;
972
973    if ($submit)
974    {
975        $status_switch = (($post_data['enable_bbcode']+1) << 8) + (($post_data['enable_smilies']+1) << 4) + (($post_data['enable_urls']+1) << 2) + (($post_data['enable_sig']+1) << 1);
976        $status_switch = ($status_switch != $check_value);
977    }
978    else
979    {
980        $status_switch = 1;
981    }
982
983    // Delete Poll
984    if ($poll_delete && $mode == 'edit' && count($post_data['poll_options']) &&
985        ((!$post_data['poll_last_vote'] && $post_data['poster_id'] == $user->data['user_id'] && $auth->acl_get('f_delete', $forum_id)) || $auth->acl_get('m_delete', $forum_id)))
986    {
987        if ($submit && check_form_key('posting'))
988        {
989            $sql = 'DELETE FROM ' . POLL_OPTIONS_TABLE . "
990                WHERE topic_id = $topic_id";
991            $db->sql_query($sql);
992
993            $sql = 'DELETE FROM ' . POLL_VOTES_TABLE . "
994                WHERE topic_id = $topic_id";
995            $db->sql_query($sql);
996
997            $topic_sql = array(
998                'poll_title'        => '',
999                'poll_start'         => 0,
1000                'poll_length'        => 0,
1001                'poll_last_vote'    => 0,
1002                'poll_max_options'    => 0,
1003                'poll_vote_change'    => 0
1004            );
1005
1006            $sql = 'UPDATE ' . TOPICS_TABLE . '
1007                SET ' . $db->sql_build_array('UPDATE', $topic_sql) . "
1008                WHERE topic_id = $topic_id";
1009            $db->sql_query($sql);
1010        }
1011
1012        $post_data['poll_title'] = $post_data['poll_option_text'] = '';
1013        $post_data['poll_vote_change'] = $post_data['poll_max_options'] = $post_data['poll_length'] = 0;
1014    }
1015    else
1016    {
1017        $post_data['poll_title']        = $request->variable('poll_title', '', true);
1018        $post_data['poll_length']        = $request->variable('poll_length', 0);
1019        $post_data['poll_option_text']    = $request->variable('poll_option_text', '', true);
1020        $post_data['poll_max_options']    = $request->variable('poll_max_options', 1);
1021        $post_data['poll_vote_change']    = ($auth->acl_get('f_votechg', $forum_id) && $auth->acl_get('f_vote', $forum_id) && isset($_POST['poll_vote_change'])) ? 1 : 0;
1022    }
1023
1024    // If replying/quoting and last post id has changed
1025    // give user option to continue submit or return to post
1026    // notify and show user the post made between his request and the final submit
1027    if (($mode == 'reply' || $mode == 'quote') && $post_data['topic_cur_post_id'] && $post_data['topic_cur_post_id'] != $post_data['topic_last_post_id'])
1028    {
1029        // Only do so if it is allowed forum-wide
1030        if ($post_data['forum_flags'] & FORUM_FLAG_POST_REVIEW)
1031        {
1032            if (topic_review($topic_id, $forum_id, 'post_review', $post_data['topic_cur_post_id']))
1033            {
1034                $template->assign_var('S_POST_REVIEW', true);
1035            }
1036
1037            $submit = false;
1038            $refresh = true;
1039        }
1040    }
1041
1042    // Parse Attachments - before checksum is calculated
1043    if ($message_parser->check_attachment_form_token($language, $request, 'posting'))
1044    {
1045        $message_parser->parse_attachments('fileupload', $mode, $forum_id, $submit, $preview, $refresh);
1046    }
1047
1048    /**
1049    * This event allows you to modify message text before parsing
1050    *
1051    * @event core.posting_modify_message_text
1052    * @var    array    post_data    Array with post data
1053    * @var    string    mode        What action to take if the form is submitted
1054    *                post|reply|quote|edit|delete|bump|smilies|popup
1055    * @var    int    post_id        ID of the post
1056    * @var    int    topic_id    ID of the topic
1057    * @var    int    forum_id    ID of the forum
1058    * @var    bool    submit        Whether or not the form has been submitted
1059    * @var    bool    preview        Whether or not the post is being previewed
1060    * @var    bool    save        Whether or not a draft is being saved
1061    * @var    bool    load        Whether or not a draft is being loaded
1062    * @var    bool    cancel        Whether or not to cancel the form (returns to
1063    *                viewtopic or viewforum depending on if the user
1064    *                is posting a new topic or editing a post)
1065    * @var    bool    refresh        Whether or not to retain previously submitted data
1066    * @var    object    message_parser    The message parser object
1067    * @var    array    error        Array of errors
1068    * @since 3.1.2-RC1
1069    * @changed 3.1.11-RC1 Added error
1070    */
1071    $vars = array(
1072        'post_data',
1073        'mode',
1074        'post_id',
1075        'topic_id',
1076        'forum_id',
1077        'submit',
1078        'preview',
1079        'save',
1080        'load',
1081        'cancel',
1082        'refresh',
1083        'message_parser',
1084        'error',
1085    );
1086    extract($phpbb_dispatcher->trigger_event('core.posting_modify_message_text', compact($vars)));
1087
1088    // Grab md5 'checksum' of new message
1089    $message_md5 = md5($message_parser->message);
1090
1091    // If editing and checksum has changed we know the post was edited while we're editing
1092    // Notify and show user the changed post
1093    if ($mode == 'edit' && $post_data['forum_flags'] & FORUM_FLAG_POST_REVIEW)
1094    {
1095        $edit_post_message_checksum = $request->variable('edit_post_message_checksum', '');
1096        $edit_post_subject_checksum = $request->variable('edit_post_subject_checksum', '');
1097
1098        // $post_data['post_checksum'] is the checksum of the post submitted in the meantime
1099        // $message_md5 is the checksum of the post we're about to submit
1100        // $edit_post_message_checksum is the checksum of the post we're editing
1101        // ...
1102
1103        // We make sure nobody else made exactly the same change
1104        // we're about to submit by also checking $message_md5 != $post_data['post_checksum']
1105        if ($edit_post_message_checksum !== '' &&
1106            $edit_post_message_checksum != $post_data['post_checksum'] &&
1107            $message_md5 != $post_data['post_checksum']
1108            ||
1109            $edit_post_subject_checksum !== '' &&
1110            $edit_post_subject_checksum != $post_data['post_subject_md5'] &&
1111            md5($post_data['post_subject']) != $post_data['post_subject_md5'])
1112        {
1113            if (topic_review($topic_id, $forum_id, 'post_review_edit', $post_id))
1114            {
1115                $template->assign_vars(array(
1116                    'S_POST_REVIEW'            => true,
1117
1118                    'L_POST_REVIEW'            => $user->lang['POST_REVIEW_EDIT'],
1119                    'L_POST_REVIEW_EXPLAIN'    => $user->lang['POST_REVIEW_EDIT_EXPLAIN'],
1120                ));
1121            }
1122
1123            $submit = false;
1124            $refresh = true;
1125        }
1126    }
1127
1128    // Check checksum ... don't re-parse message if the same
1129    $update_message = ($mode != 'edit' || $message_md5 != $post_data['post_checksum'] || $status_switch || strlen($post_data['bbcode_uid']) < BBCODE_UID_LEN) ? true : false;
1130
1131    // Also check if subject got updated...
1132    $update_subject = $mode != 'edit' || ($post_data['post_subject_md5'] && $post_data['post_subject_md5'] != md5($post_data['post_subject']));
1133
1134    // Parse message
1135    if ($update_message)
1136    {
1137        if (count($message_parser->warn_msg))
1138        {
1139            $error[] = implode('<br />', $message_parser->warn_msg);
1140            $message_parser->warn_msg = array();
1141        }
1142
1143        if (!$preview || !empty($message_parser->message))
1144        {
1145            $message_parser->parse($post_data['enable_bbcode'], ($config['allow_post_links']) ? $post_data['enable_urls'] : false, $post_data['enable_smilies'], $img_status, $quote_status, $config['allow_post_links']);
1146        }
1147
1148        // On a refresh we do not care about message parsing errors
1149        if (count($message_parser->warn_msg) && $refresh && !$preview)
1150        {
1151            $message_parser->warn_msg = array();
1152        }
1153    }
1154    else
1155    {
1156        $message_parser->bbcode_bitfield = $post_data['bbcode_bitfield'];
1157    }
1158
1159    $ignore_flood = $auth->acl_get('u_ignoreflood') ? true : $auth->acl_get('f_ignoreflood', $forum_id);
1160    if ($mode != 'edit' && !$preview && !$refresh && $config['flood_interval'] && !$ignore_flood)
1161    {
1162        // Flood check
1163        $last_post_time = 0;
1164
1165        if ($user->data['is_registered'])
1166        {
1167            $last_post_time = $user->data['user_lastpost_time'];
1168        }
1169        else
1170        {
1171            $sql = 'SELECT post_time AS last_post_time
1172                FROM ' . POSTS_TABLE . "
1173                WHERE poster_ip = '" . $user->ip . "'
1174                    AND post_time > " . ($current_time - $config['flood_interval']);
1175            $result = $db->sql_query_limit($sql, 1);
1176            if ($row = $db->sql_fetchrow($result))
1177            {
1178                $last_post_time = $row['last_post_time'];
1179            }
1180            $db->sql_freeresult($result);
1181        }
1182
1183        if ($last_post_time && ($current_time - $last_post_time) < intval($config['flood_interval']))
1184        {
1185            $error[] = $user->lang['FLOOD_ERROR'];
1186        }
1187    }
1188
1189    // Validate username
1190    if (($post_data['username'] && !$user->data['is_registered']) || ($mode == 'edit' && $post_data['poster_id'] == ANONYMOUS && $post_data['username'] && $post_data['post_username'] && $post_data['post_username'] != $post_data['username']))
1191    {
1192        if (!function_exists('validate_username'))
1193        {
1194            include($phpbb_root_path . 'includes/functions_user.' . $phpEx);
1195        }
1196
1197        $user->add_lang('ucp');
1198
1199        if (($result = validate_username($post_data['username'], (!empty($post_data['post_username'])) ? $post_data['post_username'] : '')) !== false)
1200        {
1201            $error[] = $user->lang[$result . '_USERNAME'];
1202        }
1203
1204        if (($result = validate_string($post_data['username'], false, $config['min_name_chars'], $config['max_name_chars'])) !== false)
1205        {
1206            $min_max_amount = ($result == 'TOO_SHORT') ? $config['min_name_chars'] : $config['max_name_chars'];
1207            $error[] = $user->lang('FIELD_' . $result, $min_max_amount, $user->lang['USERNAME']);
1208        }
1209    }
1210
1211    if ($config['enable_post_confirm'] && !$user->data['is_registered'] && in_array($mode, array('quote', 'post', 'reply')))
1212    {
1213        if ($captcha->validate() !== true)
1214        {
1215            $error[] = $captcha->get_error();
1216        }
1217    }
1218
1219    // check form
1220    if (($submit || $preview) && !check_form_key('posting'))
1221    {
1222        $error[] = $user->lang['FORM_INVALID'];
1223    }
1224
1225    if ($submit && $mode == 'edit' && $post_data['post_visibility'] == ITEM_DELETED && !$request->is_set_post('delete') && $auth->acl_get('m_approve', $forum_id))
1226    {
1227        $is_first_post = ($post_id <= $post_data['topic_first_post_id'] || !$post_data['topic_posts_approved']);
1228        $is_last_post = ($post_id >= $post_data['topic_last_post_id'] || !$post_data['topic_posts_approved']);
1229        $updated_post_data = $phpbb_content_visibility->set_post_visibility(ITEM_APPROVED, $post_id, $post_data['topic_id'], $post_data['forum_id'], $user->data['user_id'], time(), '', $is_first_post, $is_last_post);
1230
1231        if (!empty($updated_post_data))
1232        {
1233            // Update the post_data, so we don't need to refetch it.
1234            $post_data = array_merge($post_data, $updated_post_data);
1235        }
1236    }
1237
1238    // Parse subject
1239    if (!$preview && !$refresh && utf8_clean_string($post_data['post_subject']) === '' && ($mode == 'post' || ($mode == 'edit' && $post_data['topic_first_post_id'] == $post_id)))
1240    {
1241        $error[] = $user->lang['EMPTY_SUBJECT'];
1242    }
1243
1244    /**
1245     * Replace Emojis and other 4bit UTF-8 chars not allowed by MySQL to UCR/NCR.
1246     * Using their Numeric Character Reference's Hexadecimal notation.
1247     * Check the permissions for posting Emojis first.
1248     */
1249    if ($auth->acl_get('u_emoji'))
1250    {
1251        $post_data['post_subject'] = utf8_encode_ucr($post_data['post_subject']);
1252    }
1253    else
1254    {
1255        /**
1256         * Check for out-of-bounds characters that are currently
1257         * not supported by utf8_bin in MySQL
1258         */
1259        if (preg_match_all('/[\x{10000}-\x{10FFFF}]/u', $post_data['post_subject'], $matches))
1260        {
1261            $character_list = implode('<br>', $matches[0]);
1262
1263            $error[] = $user->lang('UNSUPPORTED_CHARACTERS_SUBJECT', $character_list);
1264        }
1265    }
1266
1267    $post_data['poll_last_vote'] = (isset($post_data['poll_last_vote'])) ? $post_data['poll_last_vote'] : 0;
1268
1269    if ($post_data['poll_option_text'] &&
1270        ($mode == 'post' || ($mode == 'edit' && $post_id == $post_data['topic_first_post_id']/* && (!$post_data['poll_last_vote'] || $auth->acl_get('m_edit', $forum_id))*/))
1271        && $auth->acl_get('f_poll', $forum_id))
1272    {
1273        $poll = array(
1274            'poll_title'        => $post_data['poll_title'],
1275            'poll_length'        => $post_data['poll_length'],
1276            'poll_max_options'    => $post_data['poll_max_options'],
1277            'poll_option_text'    => $post_data['poll_option_text'],
1278            'poll_start'        => $post_data['poll_start'],
1279            'poll_last_vote'    => $post_data['poll_last_vote'],
1280            'poll_vote_change'    => $post_data['poll_vote_change'],
1281            'enable_bbcode'        => $post_data['enable_bbcode'],
1282            'enable_urls'        => $post_data['enable_urls'],
1283            'enable_smilies'    => $post_data['enable_smilies'],
1284            'img_status'        => $img_status
1285        );
1286
1287        $message_parser->parse_poll($poll);
1288
1289        $post_data['poll_options'] = (isset($poll['poll_options'])) ? $poll['poll_options'] : array();
1290        $post_data['poll_title'] = (isset($poll['poll_title'])) ? $poll['poll_title'] : '';
1291
1292        /* We reset votes, therefore also allow removing options
1293        if ($post_data['poll_last_vote'] && ($poll['poll_options_size'] < $orig_poll_options_size))
1294        {
1295            $message_parser->warn_msg[] = $user->lang['NO_DELETE_POLL_OPTIONS'];
1296        }*/
1297    }
1298    else if ($mode == 'edit' && $post_id == $post_data['topic_first_post_id'] && $auth->acl_get('f_poll', $forum_id))
1299    {
1300        // The user removed all poll options, this is equal to deleting the poll.
1301        $poll = array(
1302            'poll_title'        => '',
1303            'poll_length'        => 0,
1304            'poll_max_options'    => 0,
1305            'poll_option_text'    => '',
1306            'poll_start'        => 0,
1307            'poll_last_vote'    => 0,
1308            'poll_vote_change'    => 0,
1309            'poll_options'        => array(),
1310        );
1311
1312        $post_data['poll_options'] = array();
1313        $post_data['poll_title'] = '';
1314        $post_data['poll_start'] = $post_data['poll_length'] = $post_data['poll_max_options'] = $post_data['poll_last_vote'] = $post_data['poll_vote_change'] = 0;
1315    }
1316    else if (!$auth->acl_get('f_poll', $forum_id) && ($mode == 'edit') && ($post_id == $post_data['topic_first_post_id']) && !$bbcode_utils->is_empty($original_poll_data['poll_title']))
1317    {
1318        // We have a poll but the editing user is not permitted to create/edit it.
1319        // So we just keep the original poll-data.
1320        // Decode the poll title and options text fisrt.
1321        $original_poll_data['poll_title'] = $bbcode_utils->unparse($original_poll_data['poll_title']);
1322        $original_poll_data['poll_option_text'] = $bbcode_utils->unparse($original_poll_data['poll_option_text']);
1323        $original_poll_data['poll_options'] = explode("\n", $original_poll_data['poll_option_text']);
1324
1325        $poll = array_merge($original_poll_data, array(
1326            'enable_bbcode'        => $post_data['enable_bbcode'],
1327            'enable_urls'        => $post_data['enable_urls'],
1328            'enable_smilies'    => $post_data['enable_smilies'],
1329            'img_status'        => $img_status,
1330        ));
1331
1332        $message_parser->parse_poll($poll);
1333
1334        $post_data['poll_options'] = (isset($poll['poll_options'])) ? $poll['poll_options'] : array();
1335        $post_data['poll_title'] = (isset($poll['poll_title'])) ? $poll['poll_title'] : '';
1336    }
1337    else
1338    {
1339        $poll = array();
1340    }
1341
1342    // Check topic type
1343    if ($post_data['topic_type'] != POST_NORMAL && ($mode == 'post' || ($mode == 'edit' && $post_data['topic_first_post_id'] == $post_id)))
1344    {
1345        switch ($post_data['topic_type'])
1346        {
1347            case POST_GLOBAL:
1348                $auth_option = 'f_announce_global';
1349            break;
1350
1351            case POST_ANNOUNCE:
1352                $auth_option = 'f_announce';
1353            break;
1354
1355            case POST_STICKY:
1356                $auth_option = 'f_sticky';
1357            break;
1358
1359            default:
1360                $auth_option = '';
1361            break;
1362        }
1363
1364        if ($auth_option != '' && !$auth->acl_get($auth_option, $forum_id))
1365        {
1366            // There is a special case where a user edits his post whereby the topic type got changed by an admin/mod.
1367            // Another case would be a mod not having sticky permissions for example but edit permissions.
1368            if ($mode == 'edit')
1369            {
1370                // To prevent non-authed users messing around with the topic type we reset it to the original one.
1371                $post_data['topic_type'] = $post_data['orig_topic_type'];
1372            }
1373            else
1374            {
1375                $error[] = $user->lang['CANNOT_POST_' . str_replace('F_', '', strtoupper($auth_option))];
1376            }
1377        }
1378    }
1379
1380    if (count($message_parser->warn_msg))
1381    {
1382        $error[] = implode('<br />', $message_parser->warn_msg);
1383    }
1384
1385    // DNSBL check
1386    if ($config['check_dnsbl'] && !$refresh)
1387    {
1388        if (($dnsbl = $user->check_dnsbl('post')) !== false)
1389        {
1390            $error[] = sprintf($user->lang['IP_BLACKLISTED'], $user->ip, $dnsbl[1]);
1391        }
1392    }
1393
1394    /**
1395    * This event allows you to define errors before the post action is performed
1396    *
1397    * @event core.posting_modify_submission_errors
1398    * @var    array    post_data    Array with post data
1399    * @var    array    poll        Array with poll data from post (must be used instead of the post_data equivalent)
1400    * @var    string    mode        What action to take if the form is submitted
1401    *                post|reply|quote|edit|delete|bump|smilies|popup
1402    * @var    int    post_id        ID of the post
1403    * @var    int    topic_id    ID of the topic
1404    * @var    int    forum_id    ID of the forum
1405    * @var    bool    submit        Whether or not the form has been submitted
1406    * @var    array    error        Any error strings; a non-empty array aborts form submission.
1407    *                NOTE: Should be actual language strings, NOT language keys.
1408    * @since 3.1.0-RC5
1409    * @changed 3.1.5-RC1 Added poll array to the event
1410    * @changed 3.2.0-a1 Removed undefined page_title
1411    */
1412    $vars = array(
1413        'post_data',
1414        'poll',
1415        'mode',
1416        'post_id',
1417        'topic_id',
1418        'forum_id',
1419        'submit',
1420        'error',
1421    );
1422    extract($phpbb_dispatcher->trigger_event('core.posting_modify_submission_errors', compact($vars)));
1423
1424    // Store message, sync counters
1425    if (!count($error) && $submit)
1426    {
1427        /** @var \phpbb\lock\posting $posting_lock */
1428        $posting_lock = $phpbb_container->get('posting.lock');
1429
1430        // Get creation time and form token, must be already checked at this point
1431        $creation_time    = abs($request->variable('creation_time', 0));
1432        $form_token = $request->variable('form_token', '');
1433
1434        if ($posting_lock->acquire($creation_time, $form_token))
1435        {
1436            // Lock/Unlock Topic
1437            $change_topic_status = $post_data['topic_status'];
1438            $perm_lock_unlock = ($auth->acl_get('m_lock', $forum_id) || ($auth->acl_get('f_user_lock', $forum_id) && $user->data['is_registered'] && !empty($post_data['topic_poster']) && $user->data['user_id'] == $post_data['topic_poster'] && $post_data['topic_status'] == ITEM_UNLOCKED)) ? true : false;
1439
1440            if ($post_data['topic_status'] == ITEM_LOCKED && !$topic_lock && $perm_lock_unlock)
1441            {
1442                $change_topic_status = ITEM_UNLOCKED;
1443            }
1444            else if ($post_data['topic_status'] == ITEM_UNLOCKED && $topic_lock && $perm_lock_unlock)
1445            {
1446                $change_topic_status = ITEM_LOCKED;
1447            }
1448
1449            if ($change_topic_status != $post_data['topic_status'])
1450            {
1451                $sql = 'UPDATE ' . TOPICS_TABLE . "
1452                    SET topic_status = $change_topic_status
1453                    WHERE topic_id = $topic_id
1454                        AND topic_moved_id = 0";
1455                $db->sql_query($sql);
1456
1457                $user_lock = ($auth->acl_get('f_user_lock', $forum_id) && $user->data['is_registered'] && $user->data['user_id'] == $post_data['topic_poster']) ? 'USER_' : '';
1458
1459                $phpbb_log->add('mod', $user->data['user_id'], $user->ip, 'LOG_' . $user_lock . (($change_topic_status == ITEM_LOCKED) ? 'LOCK' : 'UNLOCK'), false, array(
1460                    'forum_id' => $forum_id,
1461                    'topic_id' => $topic_id,
1462                    $post_data['topic_title']
1463                ));
1464            }
1465
1466            // Lock/Unlock Post Edit
1467            if ($mode == 'edit' && $post_data['post_edit_locked'] == ITEM_LOCKED && !$post_lock && $auth->acl_get('m_edit', $forum_id))
1468            {
1469                $post_data['post_edit_locked'] = ITEM_UNLOCKED;
1470            }
1471            else if ($mode == 'edit' && $post_data['post_edit_locked'] == ITEM_UNLOCKED && $post_lock && $auth->acl_get('m_edit', $forum_id))
1472            {
1473                $post_data['post_edit_locked'] = ITEM_LOCKED;
1474            }
1475
1476            $data = array(
1477                'topic_title'            => (empty($post_data['topic_title'])) ? $post_data['post_subject'] : $post_data['topic_title'],
1478                'topic_first_post_id'    => (isset($post_data['topic_first_post_id'])) ? (int) $post_data['topic_first_post_id'] : 0,
1479                'topic_last_post_id'    => (isset($post_data['topic_last_post_id'])) ? (int) $post_data['topic_last_post_id'] : 0,
1480                'topic_time_limit'        => (int) $post_data['topic_time_limit'],
1481                'topic_attachment'        => (isset($post_data['topic_attachment'])) ? (int) $post_data['topic_attachment'] : 0,
1482                'post_id'                => (int) $post_id,
1483                'topic_id'                => (int) $topic_id,
1484                'forum_id'                => (int) $forum_id,
1485                'icon_id'                => (int) $post_data['icon_id'],
1486                'poster_id'                => (int) $post_data['poster_id'],
1487                'enable_sig'            => (bool) $post_data['enable_sig'],
1488                'enable_bbcode'            => (bool) $post_data['enable_bbcode'],
1489                'enable_smilies'        => (bool) $post_data['enable_smilies'],
1490                'enable_urls'            => (bool) $post_data['enable_urls'],
1491                'enable_indexing'        => (bool) $post_data['enable_indexing'],
1492                'message_md5'            => (string) $message_md5,
1493                'post_checksum'            => (isset($post_data['post_checksum'])) ? (string) $post_data['post_checksum'] : '',
1494                'post_edit_reason'        => $post_data['post_edit_reason'],
1495                'post_edit_user'        => ($mode == 'edit') ? $user->data['user_id'] : ((isset($post_data['post_edit_user'])) ? (int) $post_data['post_edit_user'] : 0),
1496                'forum_parents'            => $post_data['forum_parents'],
1497                'forum_name'            => $post_data['forum_name'],
1498                'notify'                => $notify,
1499                'notify_set'            => $post_data['notify_set'],
1500                'poster_ip'                => (isset($post_data['poster_ip'])) ? $post_data['poster_ip'] : $user->ip,
1501                'post_edit_locked'        => (int) $post_data['post_edit_locked'],
1502                'bbcode_bitfield'        => $message_parser->bbcode_bitfield,
1503                'bbcode_uid'            => $message_parser->bbcode_uid,
1504                'message'                => $message_parser->message,
1505                'attachment_data'        => $message_parser->attachment_data,
1506                'filename_data'            => $message_parser->filename_data,
1507                'topic_status'            => $post_data['topic_status'],
1508
1509                'topic_visibility'            => (isset($post_data['topic_visibility'])) ? $post_data['topic_visibility'] : false,
1510                'post_visibility'            => (isset($post_data['post_visibility'])) ? $post_data['post_visibility'] : false,
1511            );
1512
1513            if ($mode == 'edit')
1514            {
1515                $data['topic_posts_approved'] = $post_data['topic_posts_approved'];
1516                $data['topic_posts_unapproved'] = $post_data['topic_posts_unapproved'];
1517                $data['topic_posts_softdeleted'] = $post_data['topic_posts_softdeleted'];
1518            }
1519
1520            // Only return the username when it is either a guest posting or we are editing a post and
1521            // the username was supplied; otherwise post_data might hold the data of the post that is
1522            // being quoted (which could result in the username being returned being that of the quoted
1523            // post's poster, not the poster of the current post). See: PHPBB3-11769 for more information.
1524            $post_author_name = ((!$user->data['is_registered'] || $mode == 'edit') && $post_data['username'] !== '') ? $post_data['username'] : '';
1525
1526            /**
1527            * This event allows you to define errors before the post action is performed
1528            *
1529            * @event core.posting_modify_submit_post_before
1530            * @var    array    post_data    Array with post data
1531            * @var    array    poll        Array with poll data
1532            * @var    array    data        Array with post data going to be stored in the database
1533            * @var    string    mode        What action to take if the form is submitted
1534            *                post|reply|quote|edit|delete
1535            * @var    int    post_id        ID of the post
1536            * @var    int    topic_id    ID of the topic
1537            * @var    int    forum_id    ID of the forum
1538            * @var    string    post_author_name    Author name for guest posts
1539            * @var    bool    update_message        Boolean if the post message was changed
1540            * @var    bool    update_subject        Boolean if the post subject was changed
1541            *                NOTE: Should be actual language strings, NOT language keys.
1542            * @since 3.1.0-RC5
1543            * @changed 3.1.6-RC1 remove submit and error from event  Submit and Error are checked previously prior to running event
1544            * @change 3.2.0-a1 Removed undefined page_title
1545            */
1546            $vars = array(
1547                'post_data',
1548                'poll',
1549                'data',
1550                'mode',
1551                'post_id',
1552                'topic_id',
1553                'forum_id',
1554                'post_author_name',
1555                'update_message',
1556                'update_subject',
1557            );
1558            extract($phpbb_dispatcher->trigger_event('core.posting_modify_submit_post_before', compact($vars)));
1559
1560            // The last parameter tells submit_post if search indexer has to be run
1561            $redirect_url = submit_post($mode, $post_data['post_subject'], $post_author_name, $post_data['topic_type'], $poll, $data, $update_message, ($update_message || $update_subject) ? true : false);
1562
1563            /**
1564            * This event allows you to define errors after the post action is performed
1565            *
1566            * @event core.posting_modify_submit_post_after
1567            * @var    array    post_data    Array with post data
1568            * @var    array    poll        Array with poll data
1569            * @var    array    data        Array with post data going to be stored in the database
1570            * @var    string    mode        What action to take if the form is submitted
1571            *                post|reply|quote|edit|delete
1572            * @var    int    post_id        ID of the post
1573            * @var    int    topic_id    ID of the topic
1574            * @var    int    forum_id    ID of the forum
1575            * @var    string    post_author_name    Author name for guest posts
1576            * @var    bool    update_message        Boolean if the post message was changed
1577            * @var    bool    update_subject        Boolean if the post subject was changed
1578            * @var    string    redirect_url        URL the user is going to be redirected to
1579            *                NOTE: Should be actual language strings, NOT language keys.
1580            * @since 3.1.0-RC5
1581            * @changed 3.1.6-RC1 remove submit and error from event  Submit and Error are checked previously prior to running event
1582            * @change 3.2.0-a1 Removed undefined page_title
1583            */
1584            $vars = array(
1585                'post_data',
1586                'poll',
1587                'data',
1588                'mode',
1589                'post_id',
1590                'topic_id',
1591                'forum_id',
1592                'post_author_name',
1593                'update_message',
1594                'update_subject',
1595                'redirect_url',
1596            );
1597            extract($phpbb_dispatcher->trigger_event('core.posting_modify_submit_post_after', compact($vars)));
1598
1599            if ($config['enable_post_confirm'] && !$user->data['is_registered'] && $captcha->is_solved() === true && ($mode == 'post' || $mode == 'reply' || $mode == 'quote'))
1600            {
1601                $captcha->reset();
1602            }
1603
1604            // Handle delete mode...
1605            if ($request->is_set_post('delete_permanent') || ($request->is_set_post('delete') && $post_data['post_visibility'] != ITEM_DELETED))
1606            {
1607                $delete_reason = $request->variable('delete_reason', '', true);
1608                phpbb_handle_post_delete($forum_id, $topic_id, $post_id, $post_data, !$request->is_set_post('delete_permanent'), $delete_reason);
1609                return;
1610            }
1611
1612            // Check the permissions for post approval.
1613            // Moderators must go through post approval like ordinary users.
1614            if ((!$auth->acl_get('f_noapprove', $data['forum_id']) && empty($data['force_approved_state'])) || (isset($data['force_approved_state']) && !$data['force_approved_state']))
1615            {
1616                meta_refresh(10, $redirect_url);
1617                $message = ($mode == 'edit') ? $user->lang['POST_EDITED_MOD'] : $user->lang['POST_STORED_MOD'];
1618                $message .= (($user->data['user_id'] == ANONYMOUS) ? '' : ' '. $user->lang['POST_APPROVAL_NOTIFY']);
1619                $message .= '<br /><br />' . sprintf($user->lang['RETURN_FORUM'], '<a href="' . append_sid("{$phpbb_root_path}viewforum.$phpEx", 'f=' . $data['forum_id']) . '">', '</a>');
1620                trigger_error($message);
1621            }
1622
1623            redirect($redirect_url);
1624        }
1625        else
1626        {
1627            // Posting was already locked before, hence form submission was already attempted once and is now invalid
1628            $error[] = $language->lang('FORM_INVALID');
1629        }
1630    }
1631}
1632
1633// Preview
1634if (!count($error) && $preview)
1635{
1636    $post_data['post_time'] = ($mode == 'edit') ? $post_data['post_time'] : $current_time;
1637
1638    $preview_message = $message_parser->format_display($post_data['enable_bbcode'], $post_data['enable_urls'], $post_data['enable_smilies'], false);
1639
1640    $preview_signature = ($mode == 'edit') ? $post_data['user_sig'] : $user->data['user_sig'];
1641    $preview_signature_uid = ($mode == 'edit') ? $post_data['user_sig_bbcode_uid'] : $user->data['user_sig_bbcode_uid'];
1642    $preview_signature_bitfield = ($mode == 'edit') ? $post_data['user_sig_bbcode_bitfield'] : $user->data['user_sig_bbcode_bitfield'];
1643
1644    // Signature
1645    if ($post_data['enable_sig'] && $config['allow_sig'] && $preview_signature && $auth->acl_get('f_sigs', $forum_id))
1646    {
1647        $flags = ($config['allow_sig_bbcode']) ? OPTION_FLAG_BBCODE : 0;
1648        $flags |= ($config['allow_sig_links']) ? OPTION_FLAG_LINKS : 0;
1649        $flags |= ($config['allow_sig_smilies']) ? OPTION_FLAG_SMILIES : 0;
1650
1651        $preview_signature = generate_text_for_display($preview_signature, $preview_signature_uid, $preview_signature_bitfield, $flags, false);
1652    }
1653    else
1654    {
1655        $preview_signature = '';
1656    }
1657
1658    $preview_subject = censor_text($post_data['post_subject']);
1659
1660    // Poll Preview
1661    if (!$poll_delete && ($mode == 'post' || ($mode == 'edit' && $post_id == $post_data['topic_first_post_id']/* && (!$post_data['poll_last_vote'] || $auth->acl_get('m_edit', $forum_id))*/))
1662    && $auth->acl_get('f_poll', $forum_id))
1663    {
1664        $parse_poll = new parse_message($post_data['poll_title']);
1665        $parse_poll->bbcode_uid = $message_parser->bbcode_uid;
1666        $parse_poll->bbcode_bitfield = $message_parser->bbcode_bitfield;
1667
1668        $parse_poll->format_display($post_data['enable_bbcode'], $post_data['enable_urls'], $post_data['enable_smilies']);
1669
1670        if ($post_data['poll_length'])
1671        {
1672            $poll_end = ($post_data['poll_length'] * 86400) + (($post_data['poll_start']) ? $post_data['poll_start'] : time());
1673        }
1674
1675        $template->assign_vars(array(
1676            'S_HAS_POLL_OPTIONS'    => (count($post_data['poll_options'])),
1677            'S_IS_MULTI_CHOICE'        => ($post_data['poll_max_options'] > 1) ? true : false,
1678
1679            'POLL_QUESTION'        => $parse_poll->message,
1680
1681            'L_POLL_LENGTH'        => ($post_data['poll_length']) ? sprintf($user->lang['POLL_RUN_TILL'], $user->format_date($poll_end)) : '',
1682            'L_MAX_VOTES'        => $user->lang('MAX_OPTIONS_SELECT', (int) $post_data['poll_max_options']),
1683        ));
1684
1685        $preview_poll_options = array();
1686        foreach ($post_data['poll_options'] as $poll_option)
1687        {
1688            $parse_poll->message = $poll_option;
1689            $parse_poll->format_display($post_data['enable_bbcode'], $post_data['enable_urls'], $post_data['enable_smilies']);
1690            $preview_poll_options[] = $parse_poll->message;
1691        }
1692        unset($parse_poll);
1693
1694        foreach ($preview_poll_options as $key => $option)
1695        {
1696            $template->assign_block_vars('poll_option', array(
1697                'POLL_OPTION_CAPTION'    => $option,
1698                'POLL_OPTION_ID'        => $key + 1)
1699            );
1700        }
1701        unset($preview_poll_options);
1702    }
1703
1704    // Attachment Preview
1705    if (count($message_parser->attachment_data))
1706    {
1707        $template->assign_var('S_HAS_ATTACHMENTS', true);
1708
1709        $update_count = array();
1710        $attachment_data = $message_parser->attachment_data;
1711
1712        parse_attachments($forum_id, $preview_message, $attachment_data, $update_count, true);
1713
1714        foreach ($attachment_data as $i => $attachment)
1715        {
1716            $template->assign_block_vars('attachment', array(
1717                'DISPLAY_ATTACHMENT'    => $attachment)
1718            );
1719        }
1720        unset($attachment_data);
1721    }
1722
1723    if (!count($error))
1724    {
1725        $template->assign_vars(array(
1726            'PREVIEW_SUBJECT'        => $preview_subject,
1727            'PREVIEW_MESSAGE'        => $preview_message,
1728            'PREVIEW_SIGNATURE'        => $preview_signature,
1729
1730            'S_DISPLAY_PREVIEW'        => !empty($preview_message),
1731        ));
1732    }
1733}
1734
1735// Remove quotes that would become nested too deep before decoding the text
1736$generate_quote = ($mode == 'quote' && !$submit && !$preview && !$refresh);
1737if ($generate_quote && $config['max_quote_depth'] > 0)
1738{
1739    $tmp_bbcode_uid = $message_parser->bbcode_uid;
1740    $message_parser->bbcode_uid = $post_data['bbcode_uid'];
1741    $message_parser->remove_nested_quotes($config['max_quote_depth'] - 1);
1742    $message_parser->bbcode_uid = $tmp_bbcode_uid;
1743}
1744
1745// Decode text for message display
1746$post_data['bbcode_uid'] = ($mode == 'quote' && !$preview && !$refresh && !count($error)) ? $post_data['bbcode_uid'] : $message_parser->bbcode_uid;
1747$message_parser->decode_message($post_data['bbcode_uid']);
1748
1749if ($generate_quote)
1750{
1751    // Remove attachment bbcode tags from the quoted message to avoid mixing with the new post attachments if any
1752    $message_parser->message = preg_replace('#\[attachment=([0-9]+)\](.*?)\[\/attachment\]#uis', '\\2', $message_parser->message);
1753
1754    $quote_attributes = array(
1755                        'author'  => $post_data['quote_username'],
1756                        'post_id' => $post_data['post_id'],
1757                        'time'    => $post_data['post_time'],
1758                        'user_id' => $post_data['poster_id'],
1759    );
1760
1761    /**
1762    * This event allows you to modify the quote attributes of the post being quoted
1763    *
1764    * @event core.posting_modify_quote_attributes
1765    * @var    array    quote_attributes    Array with quote attributes
1766    * @var    array    post_data            Array with post data
1767    * @since 3.2.6-RC1
1768    */
1769    $vars = array(
1770        'quote_attributes',
1771        'post_data',
1772    );
1773    extract($phpbb_dispatcher->trigger_event('core.posting_modify_quote_attributes', compact($vars)));
1774
1775    /** @var \phpbb\language\language $language */
1776    $language = $phpbb_container->get('language');
1777    phpbb_format_quote($language, $message_parser, $bbcode_utils, $bbcode_status, $quote_attributes);
1778}
1779
1780if (($mode == 'reply' || $mode == 'quote') && !$submit && !$preview && !$refresh)
1781{
1782    $post_data['post_subject'] = ((strpos($post_data['post_subject'], 'Re: ') !== 0) ? 'Re: ' : '') . censor_text($post_data['post_subject']);
1783
1784    $post_subject = $post_data['post_subject'];
1785
1786    /**
1787    * This event allows you to modify the post subject of the post being quoted
1788    *
1789    * @event core.posting_modify_post_subject
1790    * @var    string        post_subject    String with the post subject already censored.
1791    * @since 3.2.8-RC1
1792    */
1793    $vars = array('post_subject');
1794    extract($phpbb_dispatcher->trigger_event('core.posting_modify_post_subject', compact($vars)));
1795
1796    $post_data['post_subject'] = $post_subject;
1797}
1798
1799$attachment_data = $message_parser->attachment_data;
1800$filename_data = $message_parser->filename_data;
1801$post_data['post_text'] = $message_parser->message;
1802
1803if (count($post_data['poll_options']) || (isset($post_data['poll_title']) && !$bbcode_utils->is_empty($post_data['poll_title'])))
1804{
1805    $message_parser->message = $post_data['poll_title'];
1806    $message_parser->bbcode_uid = $post_data['bbcode_uid'];
1807
1808    $message_parser->decode_message();
1809    $post_data['poll_title'] = $message_parser->message;
1810
1811    $message_parser->message = implode("\n", $post_data['poll_options']);
1812    $message_parser->decode_message();
1813    $post_data['poll_options'] = explode("\n", $message_parser->message);
1814}
1815
1816// MAIN POSTING PAGE BEGINS HERE
1817
1818// Forum moderators?
1819$moderators = array();
1820if ($config['load_moderators'])
1821{
1822    get_moderators($moderators, $forum_id);
1823}
1824
1825// Generate smiley listing
1826generate_smilies('inline', $forum_id);
1827
1828// Generate inline attachment select box
1829posting_gen_inline_attachments($attachment_data);
1830
1831// Do show topic type selection only in first post.
1832$topic_type_toggle = false;
1833
1834if ($mode == 'post' || ($mode == 'edit' && $post_id == $post_data['topic_first_post_id']))
1835{
1836    $topic_type_toggle = posting_gen_topic_types($forum_id, $post_data['topic_type']);
1837}
1838
1839$s_topic_icons = false;
1840if ($post_data['enable_icons'] && $auth->acl_get('f_icons', $forum_id))
1841{
1842    $s_topic_icons = posting_gen_topic_icons($mode, $post_data['icon_id']);
1843}
1844
1845$bbcode_checked        = (isset($post_data['enable_bbcode'])) ? !$post_data['enable_bbcode'] : (($config['allow_bbcode']) ? !$user->optionget('bbcode') : 1);
1846$smilies_checked    = (isset($post_data['enable_smilies'])) ? !$post_data['enable_smilies'] : (($config['allow_smilies']) ? !$user->optionget('smilies') : 1);
1847$urls_checked        = (isset($post_data['enable_urls'])) ? !$post_data['enable_urls'] : 0;
1848$sig_checked        = $post_data['enable_sig'];
1849$lock_topic_checked    = (isset($topic_lock) && $topic_lock) ? $topic_lock : (($post_data['topic_status'] == ITEM_LOCKED) ? 1 : 0);
1850$lock_post_checked    = (isset($post_lock)) ? $post_lock : $post_data['post_edit_locked'];
1851
1852// If the user is replying or posting and not already watching this topic but set to always being notified we need to overwrite this setting
1853$notify_set            = ($mode != 'edit' && $config['allow_topic_notify'] && $user->data['is_registered'] && !$post_data['notify_set']) ? $user->data['user_notify'] : $post_data['notify_set'];
1854$notify_checked        = (isset($notify)) ? $notify : (($mode == 'post') ? $user->data['user_notify'] : $notify_set);
1855
1856// Page title & action URL
1857$s_action = append_sid("{$phpbb_root_path}posting.$phpEx", "mode=$mode");
1858
1859switch ($mode)
1860{
1861    case 'post':
1862        $s_action .= $forum_id ? "&amp;f=$forum_id" : '';
1863        $page_title = $user->lang['POST_TOPIC'];
1864    break;
1865
1866    case 'reply':
1867        $s_action .= $topic_id ? "&amp;t=$topic_id" : '';
1868        $page_title = $user->lang['POST_REPLY'];
1869    break;
1870
1871    case 'quote':
1872        $s_action .= $post_id ? "&amp;p=$post_id" : '';
1873        $page_title = $user->lang['POST_REPLY'];
1874    break;
1875
1876    case 'delete':
1877    case 'edit':
1878        $s_action .= $post_id ? "&amp;p=$post_id" : '';
1879        $page_title = $user->lang['EDIT_POST'];
1880    break;
1881}
1882
1883// Build Navigation Links
1884generate_forum_nav($post_data);
1885
1886// Build Forum Rules
1887generate_forum_rules($post_data);
1888
1889// Posting uses is_solved for legacy reasons. Plugins have to use is_solved to force themselves to be displayed.
1890if ($config['enable_post_confirm'] && !$user->data['is_registered'] && (isset($captcha) && $captcha->is_solved() === false) && ($mode == 'post' || $mode == 'reply' || $mode == 'quote'))
1891{
1892
1893    $template->assign_vars(array(
1894        'S_CONFIRM_CODE'            => true,
1895        'CAPTCHA_TEMPLATE'            => $captcha->get_template(),
1896    ));
1897}
1898
1899$s_hidden_fields = ($mode == 'reply' || $mode == 'quote') ? '<input type="hidden" name="topic_cur_post_id" value="' . $post_data['topic_last_post_id'] . '" />' : '';
1900$s_hidden_fields .= ($draft_id || isset($_REQUEST['draft_loaded'])) ? '<input type="hidden" name="draft_loaded" value="' . $request->variable('draft_loaded', $draft_id) . '" />' : '';
1901
1902if ($mode == 'edit')
1903{
1904    $s_hidden_fields .= build_hidden_fields(array(
1905        'edit_post_message_checksum'    => $post_data['post_checksum'],
1906        'edit_post_subject_checksum'    => $post_data['post_subject_md5'],
1907    ));
1908}
1909
1910// Add the confirm id/code pair to the hidden fields, else an error is displayed on next submit/preview
1911if (isset($captcha) && $captcha->is_solved() !== false)
1912{
1913    $s_hidden_fields .= build_hidden_fields($captcha->get_hidden_fields());
1914}
1915
1916$form_enctype = (@ini_get('file_uploads') == '0' || strtolower(@ini_get('file_uploads')) == 'off' || !$config['allow_attachments'] || !$auth->acl_get('u_attach') || !$auth->acl_get('f_attach', $forum_id)) ? '' : ' enctype="multipart/form-data"';
1917add_form_key('posting');
1918
1919/** @var \phpbb\controller\helper $controller_helper */
1920$controller_helper = $phpbb_container->get('controller.helper');
1921
1922// Build array of variables for main posting page
1923$page_data = array(
1924    'L_POST_A'                    => $page_title,
1925    'L_ICON'                    => ($mode == 'reply' || $mode == 'quote' || ($mode == 'edit' && $post_id != $post_data['topic_first_post_id'])) ? $user->lang['POST_ICON'] : $user->lang['TOPIC_ICON'],
1926    'L_MESSAGE_BODY_EXPLAIN'    => $user->lang('MESSAGE_BODY_EXPLAIN', (int) $config['max_post_chars']),
1927    'L_DELETE_POST_PERMANENTLY'    => $user->lang('DELETE_POST_PERMANENTLY', 1),
1928
1929    'FORUM_NAME'            => $post_data['forum_name'],
1930    'FORUM_DESC'            => ($post_data['forum_desc']) ? generate_text_for_display($post_data['forum_desc'], $post_data['forum_desc_uid'], $post_data['forum_desc_bitfield'], $post_data['forum_desc_options']) : '',
1931    'TOPIC_TITLE'            => censor_text($post_data['topic_title']),
1932    'MODERATORS'            => (count($moderators)) ? implode($user->lang['COMMA_SEPARATOR'], $moderators[$forum_id]) : '',
1933    'USERNAME'                => ((!$preview && $mode != 'quote') || $preview) ? $post_data['username'] : '',
1934    'SUBJECT'                => $post_data['post_subject'],
1935    'MESSAGE'                => $post_data['post_text'],
1936    'BBCODE_STATUS'            => $user->lang(($bbcode_status ? 'BBCODE_IS_ON' : 'BBCODE_IS_OFF'), '<a href="' . $controller_helper->route('phpbb_help_bbcode_controller') . '">', '</a>'),
1937    'IMG_STATUS'            => ($img_status) ? $user->lang['IMAGES_ARE_ON'] : $user->lang['IMAGES_ARE_OFF'],
1938    'SMILIES_STATUS'        => ($smilies_status) ? $user->lang['SMILIES_ARE_ON'] : $user->lang['SMILIES_ARE_OFF'],
1939    'URL_STATUS'            => ($bbcode_status && $url_status) ? $user->lang['URL_IS_ON'] : $user->lang['URL_IS_OFF'],
1940    'MAX_FONT_SIZE'            => (int) $config['max_post_font_size'],
1941    'MINI_POST_IMG'            => $user->img('icon_post_target', $user->lang['POST']),
1942    'POST_DATE'                => ($post_data['post_time']) ? $user->format_date($post_data['post_time']) : '',
1943    'ERROR'                    => (count($error)) ? implode('<br />', $error) : '',
1944    'TOPIC_TIME_LIMIT'        => (int) $post_data['topic_time_limit'],
1945    'EDIT_REASON'            => $request->variable('edit_reason', '', true),
1946    'SHOW_PANEL'            => $request->variable('show_panel', ''),
1947    'U_VIEW_FORUM'            => append_sid("{$phpbb_root_path}viewforum.$phpEx", "f=$forum_id"),
1948    'U_VIEW_TOPIC'            => ($mode != 'post') ? append_sid("{$phpbb_root_path}viewtopic.$phpEx", "t=$topic_id") : '',
1949    'U_PROGRESS_BAR'        => append_sid("{$phpbb_root_path}posting.$phpEx", "f=$forum_id&amp;mode=popup"),
1950    'UA_PROGRESS_BAR'        => addslashes(append_sid("{$phpbb_root_path}posting.$phpEx", "f=$forum_id&amp;mode=popup")),
1951
1952    'S_PRIVMSGS'                => false,
1953    'S_CLOSE_PROGRESS_WINDOW'    => (isset($_POST['add_file'])) ? true : false,
1954    'S_EDIT_POST'                => ($mode == 'edit') ? true : false,
1955    'S_EDIT_REASON'                => ($mode == 'edit' && $auth->acl_get('m_edit', $forum_id)) ? true : false,
1956    'S_DISPLAY_USERNAME'        => (!$user->data['is_registered'] || ($mode == 'edit' && $post_data['poster_id'] == ANONYMOUS)) ? true : false,
1957    'S_SHOW_TOPIC_ICONS'        => $s_topic_icons,
1958    'S_DELETE_ALLOWED'            => ($mode == 'edit' && (($post_id == $post_data['topic_last_post_id'] && $post_data['poster_id'] == $user->data['user_id'] && $auth->acl_get('f_delete', $forum_id) && !$post_data['post_edit_locked'] && ($post_data['post_time'] > time() - ($config['delete_time'] * 60) || !$config['delete_time'])) || $auth->acl_get('m_delete', $forum_id))) ? true : false,
1959    'S_BBCODE_ALLOWED'            => ($bbcode_status) ? 1 : 0,
1960    'S_BBCODE_CHECKED'            => ($bbcode_checked) ? ' checked="checked"' : '',
1961    'S_SMILIES_ALLOWED'            => $smilies_status,
1962    'S_SMILIES_CHECKED'            => ($smilies_checked) ? ' checked="checked"' : '',
1963    'S_SIG_ALLOWED'                => ($user->data['is_registered'] && $config['allow_sig'] && $auth->acl_get('f_sigs', $forum_id) && $auth->acl_get('u_sig')) ? true : false,
1964    'S_SIGNATURE_CHECKED'        => ($sig_checked) ? ' checked="checked"' : '',
1965    'S_NOTIFY_ALLOWED'            => (!$user->data['is_registered'] || ($mode == 'edit' && $user->data['user_id'] != $post_data['poster_id']) || !$config['allow_topic_notify'] || !$config['email_enable']) ? false : true,
1966    'S_NOTIFY_CHECKED'            => ($notify_checked) ? ' checked="checked"' : '',
1967    'S_LOCK_TOPIC_ALLOWED'        => (($mode == 'edit' || $mode == 'reply' || $mode == 'quote' || $mode == 'post') && ($auth->acl_get('m_lock', $forum_id) || ($auth->acl_get('f_user_lock', $forum_id) && $user->data['is_registered'] && !empty($post_data['topic_poster']) && $user->data['user_id'] == $post_data['topic_poster'] && $post_data['topic_status'] == ITEM_UNLOCKED))) ? true : false,
1968    'S_LOCK_TOPIC_CHECKED'        => ($lock_topic_checked) ? ' checked="checked"' : '',
1969    'S_LOCK_POST_ALLOWED'        => ($mode == 'edit' && $auth->acl_get('m_edit', $forum_id)) ? true : false,
1970    'S_LOCK_POST_CHECKED'        => ($lock_post_checked) ? ' checked="checked"' : '',
1971    'S_SOFTDELETE_CHECKED'        => ($mode == 'edit' && $post_data['post_visibility'] == ITEM_DELETED) ? ' checked="checked"' : '',
1972    'S_SOFTDELETE_ALLOWED'        => ($mode == 'edit' && $phpbb_content_visibility->can_soft_delete($forum_id, $post_data['poster_id'], $lock_post_checked) && $post_id == $post_data['topic_last_post_id'] && ($post_data['post_time'] > time() - ($config['delete_time'] * 60) || !$config['delete_time'])) ? true : false,
1973    'S_RESTORE_ALLOWED'            => $auth->acl_get('m_approve', $forum_id),
1974    'S_IS_DELETED'                => ($mode == 'edit' && $post_data['post_visibility'] == ITEM_DELETED) ? true : false,
1975    'S_LINKS_ALLOWED'            => $url_status,
1976    'S_MAGIC_URL_CHECKED'        => ($urls_checked) ? ' checked="checked"' : '',
1977    'S_TYPE_TOGGLE'                => $topic_type_toggle,
1978    'S_SAVE_ALLOWED'            => ($auth->acl_get('u_savedrafts') && $user->data['is_registered'] && $mode != 'edit') ? true : false,
1979    'S_HAS_DRAFTS'                => ($auth->acl_get('u_savedrafts') && $user->data['is_registered'] && $post_data['drafts']) ? true : false,
1980    'S_FORM_ENCTYPE'            => $form_enctype,
1981
1982    'S_BBCODE_IMG'            => $img_status,
1983    'S_BBCODE_URL'            => $url_status,
1984    'S_BBCODE_QUOTE'        => $quote_status,
1985
1986    'S_POST_ACTION'            => $s_action,
1987    'S_HIDDEN_FIELDS'        => $s_hidden_fields,
1988    'S_ATTACH_DATA'            => json_encode($message_parser->attachment_data),
1989    'S_IN_POSTING'            => true,
1990);
1991
1992// Build custom bbcodes array
1993display_custom_bbcodes();
1994
1995// Poll entry
1996if (($mode == 'post' || ($mode == 'edit' && $post_id == $post_data['topic_first_post_id']/* && (!$post_data['poll_last_vote'] || $auth->acl_get('m_edit', $forum_id))*/))
1997    && $auth->acl_get('f_poll', $forum_id))
1998{
1999    $page_data = array_merge($page_data, array(
2000        'S_SHOW_POLL_BOX'        => true,
2001        'S_POLL_VOTE_CHANGE'    => ($auth->acl_get('f_votechg', $forum_id) && $auth->acl_get('f_vote', $forum_id)),
2002        'S_POLL_DELETE'            => ($mode == 'edit' && count($post_data['poll_options']) && ((!$post_data['poll_last_vote'] && $post_data['poster_id'] == $user->data['user_id'] && $auth->acl_get('f_delete', $forum_id)) || $auth->acl_get('m_delete', $forum_id))),
2003        'S_POLL_DELETE_CHECKED'    => (!empty($poll_delete)) ? true : false,
2004
2005        'L_POLL_OPTIONS_EXPLAIN'    => $user->lang('POLL_OPTIONS_' . (($mode == 'edit') ? 'EDIT_' : '') . 'EXPLAIN', (int) $config['max_poll_options']),
2006
2007        'VOTE_CHANGE_CHECKED'    => (!empty($post_data['poll_vote_change'])) ? ' checked="checked"' : '',
2008        'POLL_TITLE'            => (isset($post_data['poll_title'])) ? $post_data['poll_title'] : '',
2009        'POLL_OPTIONS'            => (!empty($post_data['poll_options'])) ? implode("\n", $post_data['poll_options']) : '',
2010        'POLL_MAX_OPTIONS'        => (isset($post_data['poll_max_options'])) ? (int) $post_data['poll_max_options'] : 1,
2011        'POLL_LENGTH'            => $post_data['poll_length'],
2012        )
2013    );
2014}
2015
2016/**
2017* This event allows you to modify template variables for the posting screen
2018*
2019* @event core.posting_modify_template_vars
2020* @var    array    post_data    Array with post data
2021* @var    array    moderators    Array with forum moderators
2022* @var    string    mode        What action to take if the form is submitted
2023*                post|reply|quote|edit|delete|bump|smilies|popup
2024* @var    string    page_title    Title of the mode page
2025* @var    bool    s_topic_icons    Whether or not to show the topic icons
2026* @var    string    form_enctype    If attachments are allowed for this form
2027*                "multipart/form-data" or empty string
2028* @var    string    s_action    The URL to submit the POST data to
2029* @var    string    s_hidden_fields    Concatenated hidden input tags of posting form
2030* @var    int    post_id        ID of the post
2031* @var    int    topic_id    ID of the topic
2032* @var    int    forum_id    ID of the forum
2033* @var    int    draft_id    ID of the draft
2034* @var    bool    submit        Whether or not the form has been submitted
2035* @var    bool    preview        Whether or not the post is being previewed
2036* @var    bool    save        Whether or not a draft is being saved
2037* @var    bool    load        Whether or not a draft is being loaded
2038* @var    bool    cancel        Whether or not to cancel the form (returns to
2039*                viewtopic or viewforum depending on if the user
2040*                is posting a new topic or editing a post)
2041* @var    array    error        Any error strings; a non-empty array aborts
2042*                form submission.
2043*                NOTE: Should be actual language strings, NOT
2044*                language keys.
2045* @var    bool    refresh        Whether or not to retain previously submitted data
2046* @var    array    page_data    Posting page data that should be passed to the
2047*                posting page via $template->assign_vars()
2048* @var    object    message_parser    The message parser object
2049* @since 3.1.0-a1
2050* @changed 3.1.0-b3 Added vars post_data, moderators, mode, page_title,
2051*        s_topic_icons, form_enctype, s_action, s_hidden_fields,
2052*        post_id, topic_id, forum_id, submit, preview, save, load,
2053*        delete, cancel, refresh, error, page_data, message_parser
2054* @changed 3.1.2-RC1 Removed 'delete' var as it does not exist
2055* @changed 3.1.5-RC1 Added poll variables to the page_data array
2056* @changed 3.1.6-RC1 Added 'draft_id' var
2057*/
2058$vars = array(
2059    'post_data',
2060    'moderators',
2061    'mode',
2062    'page_title',
2063    's_topic_icons',
2064    'form_enctype',
2065    's_action',
2066    's_hidden_fields',
2067    'post_id',
2068    'topic_id',
2069    'forum_id',
2070    'draft_id',
2071    'submit',
2072    'preview',
2073    'save',
2074    'load',
2075    'cancel',
2076    'refresh',
2077    'error',
2078    'page_data',
2079    'message_parser',
2080);
2081extract($phpbb_dispatcher->trigger_event('core.posting_modify_template_vars', compact($vars)));
2082
2083// Start assigning vars for main posting page ...
2084$template->assign_vars($page_data);
2085
2086// Show attachment box for adding attachments if true
2087$allowed = ($auth->acl_get('f_attach', $forum_id) && $auth->acl_get('u_attach') && $config['allow_attachments'] && $form_enctype);
2088
2089if ($allowed)
2090{
2091    $max_files = ($auth->acl_get('a_') || $auth->acl_get('m_', $forum_id)) ? 0 : (int) $config['max_attachments'];
2092    $plupload->configure($cache, $template, $s_action, $forum_id, $max_files);
2093}
2094
2095// Attachment entry
2096posting_gen_attachment_entry($attachment_data, $filename_data, $allowed, $forum_id);
2097
2098// Output page ...
2099page_header($page_title);
2100
2101$template->set_filenames(array(
2102    'body' => 'posting_body.html')
2103);
2104
2105make_jumpbox(append_sid("{$phpbb_root_path}viewforum.$phpEx"));
2106
2107// Topic review
2108if ($mode == 'reply' || $mode == 'quote')
2109{
2110    if (topic_review($topic_id, $forum_id))
2111    {
2112        $template->assign_var('S_DISPLAY_REVIEW', true);
2113    }
2114}
2115
2116page_footer();