Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
44.55% covered (danger)
44.55%
323 / 725
38.71% covered (danger)
38.71%
12 / 31
CRAP
0.00% covered (danger)
0.00%
0 / 1
gen_sort_selects
0.00% covered (danger)
0.00%
0 / 52
0.00% covered (danger)
0.00%
0 / 1
72
make_jumpbox
0.00% covered (danger)
0.00%
0 / 67
0.00% covered (danger)
0.00%
0 / 1
462
bump_topic_allowed
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
72
get_context
0.00% covered (danger)
0.00%
0 / 49
0.00% covered (danger)
0.00%
0 / 1
506
phpbb_clean_search_string
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
decode_message
100.00% covered (success)
100.00%
20 / 20
100.00% covered (success)
100.00%
1 / 1
3
strip_bbcode
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
3
generate_text_for_display
78.12% covered (warning)
78.12%
25 / 32
0.00% covered (danger)
0.00%
0 / 1
14.77
generate_text_for_storage
96.55% covered (success)
96.55%
28 / 29
0.00% covered (danger)
0.00%
0 / 1
6
generate_text_for_edit
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
4
make_clickable_callback
100.00% covered (success)
100.00%
61 / 61
100.00% covered (success)
100.00%
1 / 1
24
make_clickable
100.00% covered (success)
100.00%
53 / 53
100.00% covered (success)
100.00%
1 / 1
16
censor_text
81.82% covered (warning)
81.82%
9 / 11
0.00% covered (danger)
0.00%
0 / 1
8.38
bbcode_nl2br
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
smiley_text
42.86% covered (danger)
42.86%
3 / 7
0.00% covered (danger)
0.00%
0 / 1
6.99
parse_attachments
0.00% covered (danger)
0.00%
0 / 175
0.00% covered (danger)
0.00%
0 / 1
1806
extension_allowed
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
12
truncate_string
47.62% covered (danger)
47.62%
10 / 21
0.00% covered (danger)
0.00%
0 / 1
20.64
get_username_string
100.00% covered (success)
100.00%
47 / 47
100.00% covered (success)
100.00%
1 / 1
27
phpbb_add_quickmod_option
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
2
phpbb_generate_string_list
90.91% covered (success)
90.91%
10 / 11
0.00% covered (danger)
0.00%
0 / 1
4.01
phpbb_format_quote
94.12% covered (success)
94.12%
16 / 17
0.00% covered (danger)
0.00%
0 / 1
4.00
bitfield
53.85% covered (warning)
53.85%
14 / 26
44.44% covered (danger)
44.44%
4 / 9
29.62
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
 set
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
 clear
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 get_blob
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 get_base64
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 get_bin
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
 get_all_set
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 merge
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2/**
3*
4* This file is part of the phpBB Forum Software package.
5*
6* @copyright (c) phpBB Limited <https://www.phpbb.com>
7* @license GNU General Public License, version 2 (GPL-2.0)
8*
9* For full copyright and license information, please see
10* the docs/CREDITS.txt file.
11*
12*/
13
14/**
15* @ignore
16*/
17
18use phpbb\attachment\attachment_category;
19
20if (!defined('IN_PHPBB'))
21{
22    exit;
23}
24
25/**
26* gen_sort_selects()
27* make_jumpbox()
28* bump_topic_allowed()
29* get_context()
30* phpbb_clean_search_string()
31* decode_message()
32* strip_bbcode()
33* generate_text_for_display()
34* generate_text_for_storage()
35* generate_text_for_edit()
36* make_clickable_callback()
37* make_clickable()
38* censor_text()
39* bbcode_nl2br()
40* smiley_text()
41* parse_attachments()
42* extension_allowed()
43* truncate_string()
44* get_username_string()
45* class bitfield
46*/
47
48/**
49* Generate sort selection fields
50*/
51function gen_sort_selects(&$limit_days, &$sort_by_text, &$sort_days, &$sort_key, &$sort_dir, &$s_limit_days, &$s_sort_key, &$s_sort_dir, &$u_sort_param, $def_st = false, $def_sk = false, $def_sd = false)
52{
53    global $user, $phpbb_dispatcher;
54
55    $sort_dir_text = array('a' => $user->lang['ASCENDING'], 'd' => $user->lang['DESCENDING']);
56
57    $sorts = array(
58        'st'    => array(
59            'key'        => 'sort_days',
60            'default'    => $def_st,
61            'options'    => $limit_days,
62            'output'    => &$s_limit_days,
63        ),
64
65        'sk'    => array(
66            'key'        => 'sort_key',
67            'default'    => $def_sk,
68            'options'    => $sort_by_text,
69            'output'    => &$s_sort_key,
70        ),
71
72        'sd'    => array(
73            'key'        => 'sort_dir',
74            'default'    => $def_sd,
75            'options'    => $sort_dir_text,
76            'output'    => &$s_sort_dir,
77        ),
78    );
79    $u_sort_param  = '';
80
81    foreach ($sorts as $name => $sort_ary)
82    {
83        $key = $sort_ary['key'];
84        $selected = ${$sort_ary['key']};
85
86        // Check if the key is selectable. If not, we reset to the default or first key found.
87        // This ensures the values are always valid. We also set $sort_dir/sort_key/etc. to the
88        // correct value, else the protection is void. ;)
89        if (!isset($sort_ary['options'][$selected]))
90        {
91            if ($sort_ary['default'] !== false)
92            {
93                $selected = ${$key} = $sort_ary['default'];
94            }
95            else
96            {
97                @reset($sort_ary['options']);
98                $selected = ${$key} = key($sort_ary['options']);
99            }
100        }
101
102        $sort_ary['output'] = '<select name="' . $name . '" id="' . $name . '">';
103        foreach ($sort_ary['options'] as $option => $text)
104        {
105            $sort_ary['output'] .= '<option value="' . $option . '"' . (($selected == $option) ? ' selected="selected"' : '') . '>' . $text . '</option>';
106        }
107        $sort_ary['output'] .= '</select>';
108
109        $u_sort_param .= ($selected !== $sort_ary['default']) ? ((strlen($u_sort_param)) ? '&amp;' : '') . "{$name}={$selected}" : '';
110    }
111
112    /**
113     * Run code before generated sort selects are returned
114     *
115     * @event core.gen_sort_selects_after
116     * @var    int      limit_days     Days limit
117     * @var    array    sort_by_text   Sort by text options
118     * @var    int      sort_days      Sort by days flag
119     * @var    string   sort_key       Sort key
120     * @var    string   sort_dir       Sort dir
121     * @var    string   s_limit_days   String of days limit
122     * @var    string   s_sort_key     String of sort key
123     * @var    string   s_sort_dir     String of sort dir
124     * @var    string   u_sort_param   Sort URL params
125     * @var    bool     def_st         Default sort days
126     * @var    bool     def_sk         Default sort key
127     * @var    bool     def_sd         Default sort dir
128     * @var    array    sorts          Sorts
129     * @since 3.1.9-RC1
130     */
131    $vars = array(
132        'limit_days',
133        'sort_by_text',
134        'sort_days',
135        'sort_key',
136        'sort_dir',
137        's_limit_days',
138        's_sort_key',
139        's_sort_dir',
140        'u_sort_param',
141        'def_st',
142        'def_sk',
143        'def_sd',
144        'sorts',
145    );
146    extract($phpbb_dispatcher->trigger_event('core.gen_sort_selects_after', compact($vars)));
147}
148
149/**
150* Generate Jumpbox
151*/
152function make_jumpbox($action, $forum_id = false, $select_all = false, $acl_list = false, $force_display = false)
153{
154    global $config, $auth, $template, $user, $db, $phpbb_path_helper, $phpbb_dispatcher;
155
156    // We only return if the jumpbox is not forced to be displayed (in case it is needed for functionality)
157    if (!$config['load_jumpbox'] && $force_display === false)
158    {
159        return;
160    }
161
162    $sql = 'SELECT forum_id, forum_name, parent_id, forum_type, left_id, right_id
163        FROM ' . FORUMS_TABLE . '
164        ORDER BY left_id ASC';
165    $result = $db->sql_query($sql, 600);
166
167    $rowset = array();
168    while ($row = $db->sql_fetchrow($result))
169    {
170        $rowset[(int) $row['forum_id']] = $row;
171    }
172    $db->sql_freeresult($result);
173
174    $right = $padding = 0;
175    $padding_store = array('0' => 0);
176    $display_jumpbox = false;
177    $iteration = 0;
178
179    /**
180    * Modify the jumpbox forum list data
181    *
182    * @event core.make_jumpbox_modify_forum_list
183    * @var    array    rowset    Array with the forums list data
184    * @since 3.1.10-RC1
185    */
186    $vars = array('rowset');
187    extract($phpbb_dispatcher->trigger_event('core.make_jumpbox_modify_forum_list', compact($vars)));
188
189    // Sometimes it could happen that forums will be displayed here not be displayed within the index page
190    // This is the result of forums not displayed at index, having list permissions and a parent of a forum with no permissions.
191    // If this happens, the padding could be "broken"
192
193    foreach ($rowset as $row)
194    {
195        if ($row['left_id'] < $right)
196        {
197            $padding++;
198            $padding_store[$row['parent_id']] = $padding;
199        }
200        else if ($row['left_id'] > $right + 1)
201        {
202            // Ok, if the $padding_store for this parent is empty there is something wrong. For now we will skip over it.
203            // @todo digging deep to find out "how" this can happen.
204            $padding = (isset($padding_store[$row['parent_id']])) ? $padding_store[$row['parent_id']] : $padding;
205        }
206
207        $right = $row['right_id'];
208
209        if ($row['forum_type'] == FORUM_CAT && ($row['left_id'] + 1 == $row['right_id']))
210        {
211            // Non-postable forum with no subforums, don't display
212            continue;
213        }
214
215        if (!$auth->acl_get('f_list', $row['forum_id']))
216        {
217            // if the user does not have permissions to list this forum skip
218            continue;
219        }
220
221        if ($acl_list && !$auth->acl_gets($acl_list, $row['forum_id']))
222        {
223            continue;
224        }
225
226        $tpl_ary = array();
227        if (!$display_jumpbox)
228        {
229            $tpl_ary[] = array(
230                'FORUM_ID'        => ($select_all) ? 0 : -1,
231                'FORUM_NAME'    => ($select_all) ? $user->lang['ALL_FORUMS'] : $user->lang['SELECT_FORUM'],
232                'S_FORUM_COUNT'    => $iteration,
233                'LINK'            => $phpbb_path_helper->append_url_params($action, array('f' => $forum_id)),
234            );
235
236            $iteration++;
237            $display_jumpbox = true;
238        }
239
240        $tpl_ary[] = array(
241            'FORUM_ID'        => $row['forum_id'],
242            'FORUM_NAME'    => $row['forum_name'],
243            'SELECTED'        => ($row['forum_id'] == $forum_id) ? ' selected="selected"' : '',
244            'S_FORUM_COUNT'    => $iteration,
245            'S_IS_CAT'        => ($row['forum_type'] == FORUM_CAT) ? true : false,
246            'S_IS_LINK'        => ($row['forum_type'] == FORUM_LINK) ? true : false,
247            'S_IS_POST'        => ($row['forum_type'] == FORUM_POST) ? true : false,
248            'LINK'            => $phpbb_path_helper->append_url_params($action, array('f' => $row['forum_id'])),
249        );
250
251        /**
252         * Modify the jumpbox before it is assigned to the template
253         *
254         * @event core.make_jumpbox_modify_tpl_ary
255         * @var    array    row                The data of the forum
256         * @var    array    tpl_ary            Template data of the forum
257         * @since 3.1.10-RC1
258         */
259        $vars = array(
260            'row',
261            'tpl_ary',
262        );
263        extract($phpbb_dispatcher->trigger_event('core.make_jumpbox_modify_tpl_ary', compact($vars)));
264
265        $template->assign_block_vars_array('jumpbox_forums', $tpl_ary);
266
267        unset($tpl_ary);
268
269        for ($i = 0; $i < $padding; $i++)
270        {
271            $template->assign_block_vars('jumpbox_forums.level', array());
272        }
273        $iteration++;
274    }
275    unset($padding_store, $rowset);
276
277    $url_parts = $phpbb_path_helper->get_url_parts($action);
278
279    $template->assign_vars(array(
280        'S_DISPLAY_JUMPBOX'            => $display_jumpbox,
281        'S_JUMPBOX_ACTION'            => $action,
282        'HIDDEN_FIELDS_FOR_JUMPBOX'    => build_hidden_fields($url_parts['params']),
283    ));
284}
285
286/**
287* Bump Topic Check - used by posting and viewtopic
288*/
289function bump_topic_allowed($forum_id, $topic_bumped, $last_post_time, $topic_poster, $last_topic_poster)
290{
291    global $config, $auth, $user;
292
293    // Check permission and make sure the last post was not already bumped
294    if (!$auth->acl_get('f_bump', $forum_id) || $topic_bumped)
295    {
296        return false;
297    }
298
299    // Check bump time range, is the user really allowed to bump the topic at this time?
300    $bump_time = ($config['bump_type'] == 'm') ? $config['bump_interval'] * 60 : (($config['bump_type'] == 'h') ? $config['bump_interval'] * 3600 : $config['bump_interval'] * 86400);
301
302    // Check bump time
303    if ($last_post_time + $bump_time > time())
304    {
305        return false;
306    }
307
308    // Check bumper, only topic poster and last poster are allowed to bump
309    if ($topic_poster != $user->data['user_id'] && $last_topic_poster != $user->data['user_id'])
310    {
311        return false;
312    }
313
314    // A bump time of 0 will completely disable the bump feature... not intended but might be useful.
315    return $bump_time;
316}
317
318/**
319* Generates a text with approx. the specified length which contains the specified words and their context
320*
321* @param    string    $text    The full text from which context shall be extracted
322* @param    array    $words    An array of words which should be contained in the result, has to be a valid part of a PCRE pattern (escape with preg_quote!)
323* @param    int        $length    The desired length of the resulting text, however the result might be shorter or longer than this value
324*
325* @return    string            Context of the specified words separated by "..."
326*/
327function get_context(string $text, array $words, int $length = 400)
328{
329    // first replace all whitespaces with single spaces
330    $text = preg_replace('/ +/', ' ', strtr($text, "\t\n\r\x0C ", '     '));
331
332    // we need to turn the entities back into their original form, to not cut the message in between them
333    $entities = array('&lt;', '&gt;', '&#91;', '&#93;', '&#46;', '&#58;', '&#058;');
334    $characters = array('<', '>', '[', ']', '.', ':', ':');
335    $text = str_replace($entities, $characters, $text);
336
337    $word_indizes = array();
338    if (count($words))
339    {
340        $match = '';
341        // find the starting indizes of all words
342        foreach ($words as $word)
343        {
344            if ($word)
345            {
346                if (preg_match('#(?:[^\w]|^)(' . $word . ')(?:[^\w]|$)#i', $text, $match))
347                {
348                    if (empty($match[1]))
349                    {
350                        continue;
351                    }
352
353                    $pos = utf8_strpos($text, $match[1]);
354                    if ($pos !== false)
355                    {
356                        $word_indizes[] = $pos;
357                    }
358                }
359            }
360        }
361        unset($match);
362
363        if (count($word_indizes))
364        {
365            $word_indizes = array_unique($word_indizes);
366            sort($word_indizes);
367
368            $wordnum = count($word_indizes);
369            // number of characters on the right and left side of each word
370            $sequence_length = (int) ($length / (2 * $wordnum)) - 2;
371            $final_text = '';
372            $word = $j = 0;
373            $final_text_index = -1;
374
375            // cycle through every character in the original text
376            for ($i = $word_indizes[$word], $n = utf8_strlen($text); $i < $n; $i++)
377            {
378                // if the current position is the start of one of the words then append $sequence_length characters to the final text
379                if (isset($word_indizes[$word]) && ($i == $word_indizes[$word]))
380                {
381                    if ($final_text_index < $i - $sequence_length - 1)
382                    {
383                        $final_text .= '... ' . preg_replace('#^([^ ]*)#', '', utf8_substr($text, $i - $sequence_length, $sequence_length));
384                    }
385                    else
386                    {
387                        // if the final text is already nearer to the current word than $sequence_length we only append the text
388                        // from its current index on and distribute the unused length to all other sequenes
389                        $sequence_length += (int) (($final_text_index - $i + $sequence_length + 1) / (2 * $wordnum));
390                        $final_text .= utf8_substr($text, $final_text_index + 1, $i - $final_text_index - 1);
391                    }
392                    $final_text_index = $i - 1;
393
394                    // add the following characters to the final text (see below)
395                    $word++;
396                    $j = 1;
397                }
398
399                if ($j > 0)
400                {
401                    // add the character to the final text and increment the sequence counter
402                    $final_text .= utf8_substr($text, $i, 1);
403                    $final_text_index++;
404                    $j++;
405
406                    // if this is a whitespace then check whether we are done with this sequence
407                    if (utf8_substr($text, $i, 1) == ' ')
408                    {
409                        // only check whether we have to exit the context generation completely if we haven't already reached the end anyway
410                        if ($i + 4 < $n)
411                        {
412                            if (($j > $sequence_length && $word >= $wordnum) || utf8_strlen($final_text) > $length)
413                            {
414                                $final_text .= ' ...';
415                                break;
416                            }
417                        }
418                        else
419                        {
420                            // make sure the text really reaches the end
421                            $j -= 4;
422                        }
423
424                        // stop context generation and wait for the next word
425                        if ($j > $sequence_length)
426                        {
427                            $j = 0;
428                        }
429                    }
430                }
431            }
432            return str_replace($characters, $entities, $final_text);
433        }
434    }
435
436    if (!count($words) || !count($word_indizes))
437    {
438        return str_replace($characters, $entities, ((utf8_strlen($text) >= $length + 3) ? utf8_substr($text, 0, $length) . '...' : $text));
439    }
440
441    return '';
442}
443
444/**
445* Cleans a search string by removing single wildcards from it and replacing multiple spaces with a single one.
446*
447* @param string $search_string The full search string which should be cleaned.
448*
449* @return string The cleaned search string without any wildcards and multiple spaces.
450*/
451function phpbb_clean_search_string($search_string)
452{
453    // This regular expressions matches every single wildcard.
454    // That means one after a whitespace or the beginning of the string or one before a whitespace or the end of the string.
455    $search_string = preg_replace('#(?<=^|\s)\*+(?=\s|$)#', '', $search_string);
456    $search_string = trim($search_string);
457    $search_string = preg_replace(array('#\s+#u', '#\*+#u'), array(' ', '*'), $search_string);
458    return $search_string;
459}
460
461/**
462* Decode text whereby text is coming from the db and expected to be pre-parsed content
463* We are placing this outside of the message parser because we are often in need of it...
464*
465* NOTE: special chars are kept encoded
466*
467* @param string &$message Original message, passed by reference
468* @param string $bbcode_uid BBCode UID
469* @return void
470*/
471function decode_message(&$message, $bbcode_uid = '')
472{
473    global $phpbb_container, $phpbb_dispatcher;
474
475    /**
476     * Use this event to modify the message before it is decoded
477     *
478     * @event core.decode_message_before
479     * @var string    message_text    The message content
480     * @var string    bbcode_uid        The message BBCode UID
481     * @since 3.1.9-RC1
482     */
483    $message_text = $message;
484    $vars = array('message_text', 'bbcode_uid');
485    extract($phpbb_dispatcher->trigger_event('core.decode_message_before', compact($vars)));
486    $message = $message_text;
487
488    if (preg_match('#^<[rt][ >]#', $message))
489    {
490        $message = htmlspecialchars($phpbb_container->get('text_formatter.utils')->unparse($message), ENT_COMPAT);
491    }
492    else
493    {
494        if ($bbcode_uid)
495        {
496            $match = array('<br />', "[/*:m:$bbcode_uid]", ":u:$bbcode_uid", ":o:$bbcode_uid", ":$bbcode_uid");
497            $replace = array("\n", '', '', '', '');
498        }
499        else
500        {
501            $match = array('<br />');
502            $replace = array("\n");
503        }
504
505        $message = str_replace($match, $replace, $message);
506
507        $match = get_preg_expression('bbcode_htm');
508        $replace = array('\1', '\1', '\2', '\2', '\1', '', '');
509
510        $message = preg_replace($match, $replace, $message);
511    }
512
513    /**
514    * Use this event to modify the message after it is decoded
515    *
516    * @event core.decode_message_after
517    * @var string    message_text    The message content
518    * @var string    bbcode_uid        The message BBCode UID
519    * @since 3.1.9-RC1
520    */
521    $message_text = $message;
522    $vars = array('message_text', 'bbcode_uid');
523    extract($phpbb_dispatcher->trigger_event('core.decode_message_after', compact($vars)));
524    $message = $message_text;
525}
526
527/**
528* Strips all bbcode from a text in place
529*/
530function strip_bbcode(&$text, $uid = '')
531{
532    global $phpbb_container;
533
534    if (preg_match('#^<[rt][ >]#', $text))
535    {
536        $text = utf8_htmlspecialchars($phpbb_container->get('text_formatter.utils')->clean_formatting($text));
537    }
538    else
539    {
540        if (!$uid)
541        {
542            $uid = '[0-9a-z]{5,}';
543        }
544
545        $text = preg_replace("#\[\/?[a-z0-9\*\+\-]+(?:=(?:&quot;.*&quot;|[^\]]*))?(?::[a-z])?(\:$uid)\]#", ' ', $text);
546
547        $match = get_preg_expression('bbcode_htm');
548        $replace = array('\1', '\1', '\2', '\1', '', '');
549
550        $text = preg_replace($match, $replace, $text);
551    }
552}
553
554/**
555* For display of custom parsed text on user-facing pages
556* Expects $text to be the value directly from the database (stored value)
557*
558* @return string Generated text
559*/
560function generate_text_for_display($text, $uid, $bitfield, $flags, $censor_text = true)
561{
562    static $bbcode;
563    global $auth, $config, $user;
564    global $phpbb_dispatcher, $phpbb_container;
565
566    if ($text === '')
567    {
568        return '';
569    }
570
571    /**
572    * Use this event to modify the text before it is parsed
573    *
574    * @event core.modify_text_for_display_before
575    * @var string    text            The text to parse
576    * @var string    uid                The BBCode UID
577    * @var string    bitfield        The BBCode Bitfield
578    * @var int        flags            The BBCode Flags
579    * @var bool        censor_text        Whether or not to apply word censors
580    * @since 3.1.0-a1
581    */
582    $vars = array('text', 'uid', 'bitfield', 'flags', 'censor_text');
583    extract($phpbb_dispatcher->trigger_event('core.modify_text_for_display_before', compact($vars)));
584
585    if (preg_match('#^<[rt][ >]#', $text))
586    {
587        $renderer = $phpbb_container->get('text_formatter.renderer');
588
589        // Temporarily switch off viewcensors if applicable
590        $old_censor = $renderer->get_viewcensors();
591
592        // Check here if the user is having viewing censors disabled (and also allowed to do so).
593        if (!$user->optionget('viewcensors') && $config['allow_nocensors'] && $auth->acl_get('u_chgcensors'))
594        {
595            $censor_text = false;
596        }
597
598        if ($old_censor !== $censor_text)
599        {
600            $renderer->set_viewcensors($censor_text);
601        }
602
603        $text = $renderer->render($text);
604
605        // Restore the previous value
606        if ($old_censor !== $censor_text)
607        {
608            $renderer->set_viewcensors($old_censor);
609        }
610    }
611    else
612    {
613        if ($censor_text)
614        {
615            $text = censor_text($text);
616        }
617
618        // Parse bbcode if bbcode uid stored and bbcode enabled
619        if ($uid && ($flags & OPTION_FLAG_BBCODE))
620        {
621            if (!class_exists('bbcode'))
622            {
623                global $phpbb_root_path, $phpEx;
624                include($phpbb_root_path . 'includes/bbcode.' . $phpEx);
625            }
626
627            if (empty($bbcode))
628            {
629                $bbcode = new bbcode($bitfield);
630            }
631            else
632            {
633                $bbcode->bbcode_set_bitfield($bitfield);
634            }
635
636            $bbcode->bbcode_second_pass($text, $uid);
637        }
638
639        $text = bbcode_nl2br($text);
640        $text = smiley_text($text, !($flags & OPTION_FLAG_SMILIES));
641    }
642
643    /**
644    * Use this event to modify the text after it is parsed
645    *
646    * @event core.modify_text_for_display_after
647    * @var string    text        The text to parse
648    * @var string    uid            The BBCode UID
649    * @var string    bitfield    The BBCode Bitfield
650    * @var int        flags        The BBCode Flags
651    * @since 3.1.0-a1
652    */
653    $vars = array('text', 'uid', 'bitfield', 'flags');
654    extract($phpbb_dispatcher->trigger_event('core.modify_text_for_display_after', compact($vars)));
655
656    return $text;
657}
658
659/**
660* For parsing custom parsed text to be stored within the database.
661* This function additionally returns the uid and bitfield that needs to be stored.
662* Expects $text to be the value directly from $request->variable() and in it's non-parsed form
663*
664* @param string $text The text to be replaced with the parsed one
665* @param string $uid The BBCode uid for this parse
666* @param string $bitfield The BBCode bitfield for this parse
667* @param int $flags The allow_bbcode, allow_urls and allow_smilies compiled into a single integer.
668* @param bool $allow_bbcode If BBCode is allowed (i.e. if BBCode is parsed)
669* @param bool $allow_urls If urls is allowed
670* @param bool $allow_smilies If smilies are allowed
671* @param bool $allow_img_bbcode
672* @param bool $allow_quote_bbcode
673* @param bool $allow_url_bbcode
674* @param string $mode Mode to parse text as, e.g. post or sig
675*
676* @return array    An array of string with the errors that occurred while parsing
677*/
678function generate_text_for_storage(&$text, &$uid, &$bitfield, &$flags, $allow_bbcode = false, $allow_urls = false, $allow_smilies = false, $allow_img_bbcode = true, $allow_quote_bbcode = true, $allow_url_bbcode = true, $mode = 'post')
679{
680    global $phpbb_root_path, $phpEx, $phpbb_dispatcher;
681
682    /**
683    * Use this event to modify the text before it is prepared for storage
684    *
685    * @event core.modify_text_for_storage_before
686    * @var string    text            The text to parse
687    * @var string    uid                The BBCode UID
688    * @var string    bitfield        The BBCode Bitfield
689    * @var int        flags            The BBCode Flags
690    * @var bool        allow_bbcode    Whether or not to parse BBCode
691    * @var bool        allow_urls        Whether or not to parse URLs
692    * @var bool        allow_smilies    Whether or not to parse Smilies
693    * @var bool        allow_img_bbcode    Whether or not to parse the [img] BBCode
694    * @var bool        allow_quote_bbcode    Whether or not to parse the [quote] BBCode
695    * @var bool        allow_url_bbcode    Whether or not to parse the [url] BBCode
696    * @var string    mode                Mode to parse text as, e.g. post or sig
697    * @since 3.1.0-a1
698    * @changed 3.2.0-a1 Added mode
699    * @changed 4.0.0-a1 Removed allow_flash_bbcode
700    */
701    $vars = array(
702        'text',
703        'uid',
704        'bitfield',
705        'flags',
706        'allow_bbcode',
707        'allow_urls',
708        'allow_smilies',
709        'allow_img_bbcode',
710        'allow_quote_bbcode',
711        'allow_url_bbcode',
712        'mode',
713    );
714    extract($phpbb_dispatcher->trigger_event('core.modify_text_for_storage_before', compact($vars)));
715
716    $uid = $bitfield = '';
717    $flags = (($allow_bbcode) ? OPTION_FLAG_BBCODE : 0) + (($allow_smilies) ? OPTION_FLAG_SMILIES : 0) + (($allow_urls) ? OPTION_FLAG_LINKS : 0);
718
719    if (!class_exists('parse_message'))
720    {
721        include($phpbb_root_path . 'includes/message_parser.' . $phpEx);
722    }
723
724    $message_parser = new parse_message($text);
725    $message_parser->parse($allow_bbcode, $allow_urls, $allow_smilies, $allow_img_bbcode, $allow_quote_bbcode, $allow_url_bbcode, true, $mode);
726
727    $text = $message_parser->message;
728    $uid = $message_parser->bbcode_uid;
729
730    // If the bbcode_bitfield is empty, there is no need for the uid to be stored.
731    if (!$message_parser->bbcode_bitfield)
732    {
733        $uid = '';
734    }
735
736    $bitfield = $message_parser->bbcode_bitfield;
737
738    /**
739    * Use this event to modify the text after it is prepared for storage
740    *
741    * @event core.modify_text_for_storage_after
742    * @var string    text            The text to parse
743    * @var string    uid                The BBCode UID
744    * @var string    bitfield        The BBCode Bitfield
745    * @var int        flags            The BBCode Flags
746    * @var string    message_parser    The message_parser object
747    * @since 3.1.0-a1
748    * @changed 3.1.11-RC1            Added message_parser to vars
749    */
750    $vars = array('text', 'uid', 'bitfield', 'flags', 'message_parser');
751    extract($phpbb_dispatcher->trigger_event('core.modify_text_for_storage_after', compact($vars)));
752
753    return $message_parser->warn_msg;
754}
755
756/**
757* For decoding custom parsed text for edits as well as extracting the flags
758* Expects $text to be the value directly from the database (pre-parsed content)
759*/
760function generate_text_for_edit($text, $uid, $flags)
761{
762    global $phpbb_dispatcher;
763
764    /**
765    * Use this event to modify the text before it is decoded for editing
766    *
767    * @event core.modify_text_for_edit_before
768    * @var string    text            The text to parse
769    * @var string    uid                The BBCode UID
770    * @var int        flags            The BBCode Flags
771    * @since 3.1.0-a1
772    */
773    $vars = array('text', 'uid', 'flags');
774    extract($phpbb_dispatcher->trigger_event('core.modify_text_for_edit_before', compact($vars)));
775
776    decode_message($text, $uid);
777
778    /**
779    * Use this event to modify the text after it is decoded for editing
780    *
781    * @event core.modify_text_for_edit_after
782    * @var string    text            The text to parse
783    * @var int        flags            The BBCode Flags
784    * @since 3.1.0-a1
785    */
786    $vars = array('text', 'flags');
787    extract($phpbb_dispatcher->trigger_event('core.modify_text_for_edit_after', compact($vars)));
788
789    return array(
790        'allow_bbcode'    => ($flags & OPTION_FLAG_BBCODE) ? 1 : 0,
791        'allow_smilies'    => ($flags & OPTION_FLAG_SMILIES) ? 1 : 0,
792        'allow_urls'    => ($flags & OPTION_FLAG_LINKS) ? 1 : 0,
793        'text'            => $text
794    );
795}
796
797/**
798* A subroutine of make_clickable used with preg_replace
799* It places correct HTML around an url, shortens the displayed text
800* and makes sure no entities are inside URLs
801*/
802function make_clickable_callback($type, $whitespace, $url, $relative_url, $class)
803{
804    $orig_url        = $url;
805    $orig_relative    = $relative_url;
806    $append            = '';
807    $url            = html_entity_decode($url, ENT_COMPAT);
808    $relative_url    = html_entity_decode($relative_url, ENT_COMPAT);
809
810    // make sure no HTML entities were matched
811    $chars = array('<', '>', '"');
812    $split = false;
813
814    foreach ($chars as $char)
815    {
816        $next_split = strpos($url, $char);
817        if ($next_split !== false)
818        {
819            $split = ($split !== false) ? min($split, $next_split) : $next_split;
820        }
821    }
822
823    if ($split !== false)
824    {
825        // an HTML entity was found, so the URL has to end before it
826        $append            = substr($url, $split) . $relative_url;
827        $url            = substr($url, 0, $split);
828        $relative_url    = '';
829    }
830    else if ($relative_url)
831    {
832        // same for $relative_url
833        $split = false;
834        foreach ($chars as $char)
835        {
836            $next_split = strpos($relative_url, $char);
837            if ($next_split !== false)
838            {
839                $split = ($split !== false) ? min($split, $next_split) : $next_split;
840            }
841        }
842
843        if ($split !== false)
844        {
845            $append            = substr($relative_url, $split);
846            $relative_url    = substr($relative_url, 0, $split);
847        }
848    }
849    // if the last character of the url is a punctuation mark, exclude it from the url
850    $last_char = ($relative_url) ? $relative_url[strlen($relative_url) - 1] : $url[strlen($url) - 1];
851
852    switch ($last_char)
853    {
854        case '.':
855        case '?':
856        case '!':
857        case ':':
858        case ',':
859            $append = $last_char;
860            if ($relative_url)
861            {
862                $relative_url = substr($relative_url, 0, -1);
863            }
864            else
865            {
866                $url = substr($url, 0, -1);
867            }
868        break;
869
870        // set last_char to empty here, so the variable can be used later to
871        // check whether a character was removed
872        default:
873            $last_char = '';
874        break;
875    }
876
877    $short_url = (utf8_strlen($url) > 55) ? utf8_substr($url, 0, 39) . ' ... ' . utf8_substr($url, -10) : $url;
878
879    switch ($type)
880    {
881        case MAGIC_URL_LOCAL:
882            $tag            = 'l';
883            $relative_url    = preg_replace('/[&?]sid=[0-9a-f]{32}$/', '', preg_replace('/([&?])sid=[0-9a-f]{32}&/', '$1', $relative_url));
884            $url            = $url . '/' . $relative_url;
885            $text            = $relative_url;
886
887            // this url goes to http://domain.tld/path/to/board/ which
888            // would result in an empty link if treated as local so
889            // don't touch it and let MAGIC_URL_FULL take care of it.
890            if (!$relative_url)
891            {
892                return $whitespace . $orig_url . '/' . $orig_relative; // slash is taken away by relative url pattern
893            }
894        break;
895
896        case MAGIC_URL_FULL:
897            $tag    = 'm';
898            $text    = $short_url;
899        break;
900
901        case MAGIC_URL_WWW:
902            $tag    = 'w';
903            $url    = 'http://' . $url;
904            $text    = $short_url;
905        break;
906
907        case MAGIC_URL_EMAIL:
908            $tag    = 'e';
909            $text    = $short_url;
910            $url    = 'mailto:' . $url;
911        break;
912    }
913
914    $url    = htmlspecialchars($url, ENT_COMPAT);
915    $text    = htmlspecialchars($text, ENT_COMPAT);
916    $append    = htmlspecialchars($append, ENT_COMPAT);
917
918    $html    = "$whitespace<!-- $tag --><a$class href=\"$url\">$text</a><!-- $tag -->$append";
919
920    return $html;
921}
922
923/**
924 * Replaces magic urls of form http://xxx.xxx., www.xxx. and xxx@xxx.xxx.
925 * Cuts down displayed size of link if over 50 chars, turns absolute links
926 * into relative versions when the server/script path matches the link
927 *
928 * @param string        $text        Message text to parse URL/email entries
929 * @param bool|string    $server_url    The server URL. If false, the board URL will be used
930 * @param string        $class        CSS class selector to add to the parsed URL entries
931 *
932 * @return string    A text with parsed URL/email entries
933 */
934function make_clickable($text, $server_url = false, string $class = 'postlink')
935{
936    if ($server_url === false)
937    {
938        $server_url = generate_board_url();
939    }
940
941    static $static_class;
942    static $magic_url_match_args;
943
944    if (!isset($magic_url_match_args[$server_url]) || $static_class != $class)
945    {
946        $static_class = $class;
947        $class = ($static_class) ? ' class="' . $static_class . '"' : '';
948        $local_class = ($static_class) ? ' class="' . $static_class . '-local"' : '';
949
950        if (!is_array($magic_url_match_args))
951        {
952            $magic_url_match_args = array();
953        }
954
955        // Check if the match for this $server_url and $class already exists
956        $element_exists = false;
957        if (isset($magic_url_match_args[$server_url]))
958        {
959            array_walk_recursive($magic_url_match_args[$server_url], function($value) use (&$element_exists, $static_class)
960                {
961                    if ($value == $static_class)
962                    {
963                        $element_exists = true;
964                    }
965                }
966            );
967        }
968
969        // Only add new $server_url and $class matches if not exist
970        if (!$element_exists)
971        {
972            // relative urls for this board
973            $magic_url_match_args[$server_url][] = [
974                '#(^|[\n\t (>.])(' . preg_quote($server_url, '#') . ')/(' . get_preg_expression('relative_url_inline') . ')#iu',
975                MAGIC_URL_LOCAL,
976                $local_class,
977                $static_class,
978            ];
979
980            // matches a xxxx://aaaaa.bbb.cccc. ...
981            $magic_url_match_args[$server_url][] = [
982                '#(^|[\n\t (>.])(' . get_preg_expression('url_inline') . ')#iu',
983                MAGIC_URL_FULL,
984                $class,
985                $static_class,
986            ];
987
988            // matches a "www.xxxx.yyyy[/zzzz]" kinda lazy URL thing
989            $magic_url_match_args[$server_url][] = [
990                '#(^|[\n\t (>])(' . get_preg_expression('www_url_inline') . ')#iu',
991                MAGIC_URL_WWW,
992                $class,
993                $static_class,
994            ];
995        }
996
997        if (!isset($magic_url_match_args[$server_url]['email']))
998        {
999            // matches an email@domain type address at the start of a line, or after a space or after what might be a BBCode.
1000            $magic_url_match_args[$server_url]['email'] = [
1001                '/(^|[\n\t (>])(' . get_preg_expression('email') . ')/iu',
1002                MAGIC_URL_EMAIL,
1003                '',
1004            ];
1005        }
1006    }
1007
1008    foreach ($magic_url_match_args[$server_url] as $magic_args)
1009    {
1010        if (preg_match($magic_args[0], $text, $matches))
1011        {
1012            // Only apply $class from the corresponding function call argument (excepting emails which never has a class)
1013            if ($magic_args[1] != MAGIC_URL_EMAIL && $magic_args[3] != $static_class)
1014            {
1015                continue;
1016            }
1017
1018            $text = preg_replace_callback($magic_args[0], function($matches) use ($magic_args)
1019            {
1020                $relative_url = isset($matches[3]) ? $matches[3] : '';
1021                return make_clickable_callback($magic_args[1], $matches[1], $matches[2], $relative_url, $magic_args[2]);
1022            }, $text);
1023        }
1024    }
1025
1026    return $text;
1027}
1028
1029/**
1030* Censoring
1031*/
1032function censor_text($text)
1033{
1034    static $censors;
1035
1036    // Nothing to do?
1037    if ($text === '')
1038    {
1039        return '';
1040    }
1041
1042    // We moved the word censor checks in here because we call this function quite often - and then only need to do the check once
1043    if (!isset($censors) || !is_array($censors))
1044    {
1045        global $config, $user, $auth, $cache;
1046
1047        // We check here if the user is having viewing censors disabled (and also allowed to do so).
1048        if (!$user->optionget('viewcensors') && $config['allow_nocensors'] && $auth->acl_get('u_chgcensors'))
1049        {
1050            $censors = array();
1051        }
1052        else
1053        {
1054            $censors = $cache->obtain_word_list();
1055        }
1056    }
1057
1058    if (count($censors))
1059    {
1060        return preg_replace($censors['match'], $censors['replace'], $text);
1061    }
1062
1063    return $text;
1064}
1065
1066/**
1067* custom version of nl2br which takes custom BBCodes into account
1068*/
1069function bbcode_nl2br($text)
1070{
1071    // custom BBCodes might contain carriage returns so they
1072    // are not converted into <br /> so now revert that
1073    $text = str_replace(array("\n", "\r"), array('<br />', "\n"), $text);
1074    return $text;
1075}
1076
1077/**
1078* Smiley processing
1079*/
1080function smiley_text($text, $force_option = false)
1081{
1082    global $config, $user, $phpbb_path_helper, $phpbb_dispatcher;
1083
1084    if ($force_option || !$config['allow_smilies'] || !$user->optionget('viewsmilies'))
1085    {
1086        return preg_replace('#<!\-\- s(.*?) \-\-><img src="\{SMILIES_PATH\}\/.*? \/><!\-\- s\1 \-\->#', '\1', $text);
1087    }
1088    else
1089    {
1090        $root_path = $phpbb_path_helper->get_web_root_path();
1091
1092        /**
1093        * Event to override the root_path for smilies
1094        *
1095        * @event core.smiley_text_root_path
1096        * @var string root_path root_path for smilies
1097        * @since 3.1.11-RC1
1098        */
1099        $vars = array('root_path');
1100        extract($phpbb_dispatcher->trigger_event('core.smiley_text_root_path', compact($vars)));
1101        return preg_replace('#<!\-\- s(.*?) \-\-><img src="\{SMILIES_PATH\}\/(.*?) \/><!\-\- s\1 \-\->#', '<img class="smilies" src="' . $root_path . $config['smilies_path'] . '/\2 />', $text);
1102    }
1103}
1104
1105/**
1106* General attachment parsing
1107*
1108* @param mixed $forum_id The forum id the attachments are displayed in (false if in private message)
1109* @param string &$message The post/private message
1110* @param array &$attachments The attachments to parse for (inline) display. The attachments array will hold templated data after parsing.
1111* @param array &$update_count_ary The attachment counts to be updated - will be filled
1112* @param bool $preview If set to true the attachments are parsed for preview. Within preview mode the comments are fetched from the given $attachments array and not fetched from the database.
1113*/
1114function parse_attachments($forum_id, &$message, &$attachments, &$update_count_ary, $preview = false)
1115{
1116    if (!count($attachments))
1117    {
1118        return;
1119    }
1120
1121    global $template, $cache, $user, $phpbb_dispatcher;
1122    global $extensions, $config, $phpbb_root_path, $phpEx;
1123    global $phpbb_container;
1124
1125    $storage_attachment = $phpbb_container->get('storage.attachment');
1126
1127    /** @var \phpbb\controller\helper */
1128    $controller_helper = $phpbb_container->get('controller.helper');
1129
1130    //
1131    $compiled_attachments = array();
1132
1133    if (!isset($template->filename['attachment_tpl']))
1134    {
1135        $template->set_filenames(array(
1136            'attachment_tpl'    => 'attachment.html')
1137        );
1138    }
1139
1140    if (empty($extensions) || !is_array($extensions))
1141    {
1142        $extensions = $cache->obtain_attach_extensions($forum_id);
1143    }
1144
1145    // Look for missing attachment information...
1146    $attach_ids = array();
1147    foreach ($attachments as $pos => $attachment)
1148    {
1149        // If is_orphan is set, we need to retrieve the attachments again...
1150        if (!isset($attachment['extension']) && !isset($attachment['physical_filename']))
1151        {
1152            $attach_ids[(int) $attachment['attach_id']] = $pos;
1153        }
1154    }
1155
1156    // Grab attachments (security precaution)
1157    if (count($attach_ids))
1158    {
1159        global $db;
1160
1161        $new_attachment_data = array();
1162
1163        $sql = 'SELECT *
1164            FROM ' . ATTACHMENTS_TABLE . '
1165            WHERE ' . $db->sql_in_set('attach_id', array_keys($attach_ids));
1166        $result = $db->sql_query($sql);
1167
1168        while ($row = $db->sql_fetchrow($result))
1169        {
1170            if (!isset($attach_ids[$row['attach_id']]))
1171            {
1172                continue;
1173            }
1174
1175            // If we preview attachments we will set some retrieved values here
1176            if ($preview)
1177            {
1178                $row['attach_comment'] = $attachments[$attach_ids[$row['attach_id']]]['attach_comment'];
1179            }
1180
1181            $new_attachment_data[$attach_ids[$row['attach_id']]] = $row;
1182        }
1183        $db->sql_freeresult($result);
1184
1185        $attachments = $new_attachment_data;
1186        unset($new_attachment_data);
1187    }
1188
1189    // Make sure attachments are properly ordered
1190    ksort($attachments);
1191
1192    foreach ($attachments as $attachment)
1193    {
1194        if (!count($attachment))
1195        {
1196            continue;
1197        }
1198
1199        // We need to reset/empty the _file block var, because this function might be called more than once
1200        $template->destroy_block_vars('_file');
1201
1202        $block_array = array();
1203
1204        // Some basics...
1205        $attachment['extension'] = strtolower(trim($attachment['extension']));
1206        $filename = utf8_basename($attachment['physical_filename']);
1207
1208        $upload_icon = '';
1209        $download_link = '';
1210        $display_cat = false;
1211
1212        if (isset($extensions[$attachment['extension']]))
1213        {
1214            if ($user->img('icon_topic_attach', '') && !$extensions[$attachment['extension']]['upload_icon'])
1215            {
1216                $upload_icon = $user->img('icon_topic_attach', '');
1217            }
1218            else if ($extensions[$attachment['extension']]['upload_icon'])
1219            {
1220                $upload_icon = '<img src="' . $phpbb_root_path . $config['upload_icons_path'] . '/' . trim($extensions[$attachment['extension']]['upload_icon']) . '" alt="" />';
1221            }
1222        }
1223
1224        $filesize = get_formatted_filesize($attachment['filesize'], false);
1225
1226        $comment = bbcode_nl2br(censor_text($attachment['attach_comment']));
1227
1228        $block_array += array(
1229            'UPLOAD_ICON'        => $upload_icon,
1230            'FILESIZE'            => $filesize['value'],
1231            'MIMETYPE'            => $attachment['mimetype'],
1232            'SIZE_LANG'            => $filesize['unit'],
1233            'DOWNLOAD_NAME'        => utf8_basename($attachment['real_filename']),
1234            'COMMENT'            => $comment,
1235        );
1236
1237        $denied = false;
1238
1239        if (!extension_allowed($forum_id, $attachment['extension'], $extensions))
1240        {
1241            $denied = true;
1242
1243            $block_array += array(
1244                'S_DENIED'            => true,
1245                'DENIED_MESSAGE'    => sprintf($user->lang['EXTENSION_DISABLED_AFTER_POSTING'], $attachment['extension'])
1246            );
1247        }
1248
1249        if (!$denied)
1250        {
1251            $display_cat = $extensions[$attachment['extension']]['display_cat'];
1252
1253            if ($display_cat == attachment_category::IMAGE)
1254            {
1255                if ($attachment['thumbnail'])
1256                {
1257                    $display_cat = attachment_category::THUMB;
1258                }
1259                else
1260                {
1261                    if ($config['img_display_inlined'])
1262                    {
1263                        if ($config['img_link_width'] || $config['img_link_height'])
1264                        {
1265                            try
1266                            {
1267                                $file_info = $storage_attachment->file_info($filename);
1268
1269                                $display_cat = ($file_info->image_width <= $config['img_link_width'] && $file_info->image_height <= $config['img_link_height']) ? attachment_category::IMAGE : attachment_category::NONE;
1270                            }
1271                            catch (\Exception $e)
1272                            {
1273                                $display_cat = attachment_category::NONE;
1274                            }
1275                        }
1276                    }
1277                    else
1278                    {
1279                        $display_cat = attachment_category::NONE;
1280                    }
1281                }
1282            }
1283
1284            // Make some descisions based on user options being set.
1285            if (($display_cat == attachment_category::IMAGE || $display_cat == attachment_category::THUMB) && !$user->optionget('viewimg'))
1286            {
1287                $display_cat = attachment_category::NONE;
1288            }
1289
1290            $download_link = $controller_helper->route(
1291                'phpbb_storage_attachment',
1292                [
1293                    'id'        => (int) $attachment['attach_id'],
1294                    'filename'    => $attachment['real_filename'],
1295                ]
1296            );
1297            $l_downloaded_viewed = 'VIEWED_COUNTS';
1298
1299            switch ($display_cat)
1300            {
1301                // Images
1302                case attachment_category::IMAGE:
1303                    $inline_link = $controller_helper->route(
1304                        'phpbb_storage_attachment',
1305                        [
1306                            'id'        => (int) $attachment['attach_id'],
1307                            'filename'    => $attachment['real_filename'],
1308                        ]
1309                    );
1310
1311                    $block_array += array(
1312                        'S_IMAGE'        => true,
1313                        'U_INLINE_LINK'        => $inline_link,
1314                    );
1315
1316                    $update_count_ary[] = $attachment['attach_id'];
1317                break;
1318
1319                // Images, but display Thumbnail
1320                case attachment_category::THUMB:
1321                    $thumbnail_link = $controller_helper->route(
1322                        'phpbb_storage_attachment',
1323                        [
1324                            'id'        => (int) $attachment['attach_id'],
1325                            'filename'    => $attachment['real_filename'],
1326                            't'            => 1,
1327                        ]
1328                    );
1329
1330                    $block_array += array(
1331                        'S_THUMBNAIL'        => true,
1332                        'THUMB_IMAGE'        => $thumbnail_link,
1333                    );
1334
1335                    $update_count_ary[] = $attachment['attach_id'];
1336                break;
1337
1338                // Audio files
1339                case attachment_category::AUDIO:
1340                    $block_array += [
1341                        'S_AUDIO_FILE'            => true,
1342                    ];
1343
1344                    $update_count_ary[] = $attachment['attach_id'];
1345                break;
1346
1347                // Video files
1348                case attachment_category::VIDEO:
1349                    $block_array += [
1350                        'S_VIDEO_FILE'            => true,
1351                    ];
1352
1353                    $update_count_ary[] = $attachment['attach_id'];
1354                break;
1355
1356                default:
1357                    $l_downloaded_viewed = 'DOWNLOAD_COUNTS';
1358
1359                    $block_array += array(
1360                        'S_FILE'        => true,
1361                    );
1362                break;
1363            }
1364
1365            if (!isset($attachment['download_count']))
1366            {
1367                $attachment['download_count'] = 0;
1368            }
1369
1370            $block_array += array(
1371                'U_DOWNLOAD_LINK'        => $download_link,
1372                'L_DOWNLOAD_COUNT'        => $user->lang($l_downloaded_viewed, (int) $attachment['download_count']),
1373            );
1374        }
1375
1376        $update_count = $update_count_ary;
1377        /**
1378        * Use this event to modify the attachment template data.
1379        *
1380        * This event is triggered once per attachment.
1381        *
1382        * @event core.parse_attachments_modify_template_data
1383        * @var array    attachment        Array with attachment data
1384        * @var array    block_array        Template data of the attachment
1385        * @var int        display_cat        Attachment category data
1386        * @var string    download_link    Attachment download link
1387        * @var array    extensions        Array with attachment extensions data
1388        * @var mixed     forum_id         The forum id the attachments are displayed in (false if in private message)
1389        * @var bool        preview            Flag indicating if we are in post preview mode
1390        * @var array    update_count    Array with attachment ids to update download count
1391        * @since 3.1.0-RC5
1392        */
1393        $vars = array(
1394            'attachment',
1395            'block_array',
1396            'display_cat',
1397            'download_link',
1398            'extensions',
1399            'forum_id',
1400            'preview',
1401            'update_count',
1402        );
1403        extract($phpbb_dispatcher->trigger_event('core.parse_attachments_modify_template_data', compact($vars)));
1404        $update_count_ary = $update_count;
1405        unset($update_count, $display_cat, $download_link);
1406
1407        $template->assign_block_vars('_file', $block_array);
1408
1409        $compiled_attachments[] = $template->assign_display('attachment_tpl');
1410    }
1411
1412    $attachments = $compiled_attachments;
1413    unset($compiled_attachments);
1414
1415    $unset_tpl = array();
1416
1417    preg_match_all('#<!\-\- ia([0-9]+) \-\->(.*?)<!\-\- ia\1 \-\->#', $message, $matches, PREG_PATTERN_ORDER);
1418
1419    $replace = array();
1420    foreach (array_keys($matches[0]) as $num)
1421    {
1422        $index = $matches[1][$num];
1423
1424        $replace['from'][] = $matches[0][$num];
1425        $replace['to'][] = (isset($attachments[$index])) ? $attachments[$index] : sprintf($user->lang['MISSING_INLINE_ATTACHMENT'], $matches[2][array_search($index, $matches[1])]);
1426
1427        $unset_tpl[] = $index;
1428    }
1429
1430    if (isset($replace['from']))
1431    {
1432        $message = str_replace($replace['from'], $replace['to'], $message);
1433    }
1434
1435    $unset_tpl = array_unique($unset_tpl);
1436
1437    // Sort correctly
1438    if ($config['display_order'])
1439    {
1440        // Ascending sort
1441        krsort($attachments);
1442    }
1443    else
1444    {
1445        // Descending sort
1446        ksort($attachments);
1447    }
1448
1449    // Needed to let not display the inlined attachments at the end of the post again
1450    foreach ($unset_tpl as $index)
1451    {
1452        unset($attachments[$index]);
1453    }
1454}
1455
1456/**
1457* Check if extension is allowed to be posted.
1458*
1459* @param mixed $forum_id The forum id to check or false if private message
1460* @param string $extension The extension to check, for example zip.
1461* @param array &$extensions The extension array holding the information from the cache (will be obtained if empty)
1462*
1463* @return bool False if the extension is not allowed to be posted, else true.
1464*/
1465function extension_allowed($forum_id, $extension, &$extensions)
1466{
1467    if (empty($extensions))
1468    {
1469        global $cache;
1470        $extensions = $cache->obtain_attach_extensions($forum_id);
1471    }
1472
1473    return (!isset($extensions['_allowed_'][$extension])) ? false : true;
1474}
1475
1476/**
1477* Truncates string while retaining special characters if going over the max length
1478* The default max length is 60 at the moment
1479* The maximum storage length is there to fit the string within the given length. The string may be further truncated due to html entities.
1480* For example: string given is 'a "quote"' (length: 9), would be a stored as 'a &quot;quote&quot;' (length: 19)
1481*
1482* @param string $string The text to truncate to the given length. String is specialchared.
1483* @param int $max_length Maximum length of string (multibyte character count as 1 char / Html entity count as 1 char)
1484* @param int $max_store_length Maximum character length of string (multibyte character count as 1 char / Html entity count as entity chars).
1485* @param bool $allow_reply Allow Re: in front of string
1486*     NOTE: This parameter can cause undesired behavior (returning strings longer than $max_store_length) and is deprecated.
1487* @param string $append String to be appended
1488*/
1489function truncate_string($string, $max_length = 60, $max_store_length = 255, $allow_reply = false, $append = '')
1490{
1491    $strip_reply = false;
1492    $stripped = false;
1493    if ($allow_reply && strpos($string, 'Re: ') === 0)
1494    {
1495        $strip_reply = true;
1496        $string = substr($string, 4);
1497    }
1498
1499    $_chars = utf8_str_split(html_entity_decode($string, ENT_COMPAT));
1500    $chars = array_map('utf8_htmlspecialchars', $_chars);
1501
1502    // Now check the length ;)
1503    if (count($chars) > $max_length)
1504    {
1505        // Cut off the last elements from the array
1506        $string = implode('', array_slice($chars, 0, $max_length - utf8_strlen($append)));
1507        $stripped = true;
1508    }
1509
1510    // Due to specialchars, we may not be able to store the string...
1511    if (utf8_strlen($string) > $max_store_length)
1512    {
1513        // let's split again, we do not want half-baked strings where entities are split
1514        $_chars = utf8_str_split(html_entity_decode($string, ENT_COMPAT));
1515        $chars = array_map('utf8_htmlspecialchars', $_chars);
1516
1517        do
1518        {
1519            array_pop($chars);
1520            $string = implode('', $chars);
1521        }
1522        while (!empty($chars) && utf8_strlen($string) > $max_store_length);
1523    }
1524
1525    if ($strip_reply)
1526    {
1527        $string = 'Re: ' . $string;
1528    }
1529
1530    if ($append != '' && $stripped)
1531    {
1532        $string = $string . $append;
1533    }
1534
1535    return $string;
1536}
1537
1538/**
1539* Get username details for placing into templates.
1540* This function caches all modes on first call, except for no_profile and anonymous user - determined by $user_id.
1541*
1542* @html Username spans and links
1543*
1544* @param string $mode Can be profile (for getting an url to the profile), username (for obtaining the username), colour (for obtaining the user colour), full (for obtaining a html string representing a coloured link to the users profile) or no_profile (the same as full but forcing no profile link)
1545* @param int $user_id The users id
1546* @param string $username The users name
1547* @param string $username_colour The users colour
1548* @param string|false $guest_username optional parameter to specify the guest username. It will be used in favor of the GUEST language variable then.
1549* @param string|false $custom_profile_url optional parameter to specify a profile url. The user id get appended to this url as &amp;u={user_id}
1550*
1551* @return string A string consisting of what is wanted based on $mode.
1552*/
1553function get_username_string($mode, $user_id, $username, $username_colour = '', $guest_username = false, $custom_profile_url = false)
1554{
1555    static $_profile_cache;
1556    global $phpbb_dispatcher;
1557
1558    // We cache some common variables we need within this function
1559    if (empty($_profile_cache))
1560    {
1561        global $phpbb_root_path, $phpEx;
1562
1563        /** @html Username spans and links for usage in the template */
1564        $_profile_cache['base_url'] = append_sid("{$phpbb_root_path}memberlist.$phpEx", 'mode=viewprofile&amp;u={USER_ID}');
1565        $_profile_cache['tpl_noprofile'] = '<span class="username">{USERNAME}</span>';
1566        $_profile_cache['tpl_noprofile_colour'] = '<span style="color: {USERNAME_COLOUR};" class="username-coloured">{USERNAME}</span>';
1567        $_profile_cache['tpl_profile'] = '<a href="{PROFILE_URL}" class="username">{USERNAME}</a>';
1568        $_profile_cache['tpl_profile_colour'] = '<a href="{PROFILE_URL}" style="color: {USERNAME_COLOUR};" class="username-coloured">{USERNAME}</a>';
1569    }
1570
1571    global $user, $auth;
1572
1573    // This switch makes sure we only run code required for the mode
1574    switch ($mode)
1575    {
1576        case 'full':
1577        case 'no_profile':
1578        case 'colour':
1579
1580            // Build correct username colour
1581            $username_colour = ($username_colour) ? '#' . $username_colour : '';
1582
1583            // Return colour
1584            if ($mode == 'colour')
1585            {
1586                $username_string = $username_colour;
1587                break;
1588            }
1589
1590        // no break;
1591
1592        case 'username':
1593
1594            // Build correct username
1595            if ($guest_username === false)
1596            {
1597                $username = ($username) ? $username : $user->lang['GUEST'];
1598            }
1599            else
1600            {
1601                $username = ($user_id && $user_id != ANONYMOUS) ? $username : ((!empty($guest_username)) ? $guest_username : $user->lang['GUEST']);
1602            }
1603
1604            // Return username
1605            if ($mode == 'username')
1606            {
1607                $username_string = $username;
1608                break;
1609            }
1610
1611        // no break;
1612
1613        case 'profile':
1614
1615            // Build correct profile url - only show if not anonymous and permission to view profile if registered user
1616            // For anonymous the link leads to a login page.
1617            if ($user_id && $user_id != ANONYMOUS && ($user->data['user_id'] == ANONYMOUS || $auth->acl_get('u_viewprofile')))
1618            {
1619                $profile_url = ($custom_profile_url !== false) ? $custom_profile_url . '&amp;u=' . (int) $user_id : str_replace(array('={USER_ID}', '=%7BUSER_ID%7D'), '=' . (int) $user_id, $_profile_cache['base_url']);
1620            }
1621            else
1622            {
1623                $profile_url = '';
1624            }
1625
1626            // Return profile
1627            if ($mode == 'profile')
1628            {
1629                $username_string = $profile_url;
1630                break;
1631            }
1632
1633        // no break;
1634    }
1635
1636    if (!isset($username_string))
1637    {
1638        if (($mode == 'full' && !$profile_url) || $mode == 'no_profile')
1639        {
1640            $username_string = str_replace(array('{USERNAME_COLOUR}', '{USERNAME}'), array($username_colour, $username), (!$username_colour) ? $_profile_cache['tpl_noprofile'] : $_profile_cache['tpl_noprofile_colour']);
1641        }
1642        else
1643        {
1644            $username_string = str_replace(array('{PROFILE_URL}', '{USERNAME_COLOUR}', '{USERNAME}'), array($profile_url, $username_colour, $username), (!$username_colour) ? $_profile_cache['tpl_profile'] : $_profile_cache['tpl_profile_colour']);
1645        }
1646    }
1647
1648    /**
1649    * Use this event to change the output of get_username_string()
1650    *
1651    * @event core.modify_username_string
1652    * @var string mode                profile|username|colour|full|no_profile
1653    * @var int user_id                String or array of additional url
1654    *                                parameters
1655    * @var string username            The user's username
1656    * @var string username_colour    The user's colour
1657    * @var string guest_username    Optional parameter to specify the
1658    *                                guest username.
1659    * @var string custom_profile_url Optional parameter to specify a
1660    *                                profile url.
1661    * @var string username_string    The string that has been generated
1662    * @var array _profile_cache        Array of original return templates
1663    * @since 3.1.0-a1
1664    */
1665    $vars = array(
1666        'mode',
1667        'user_id',
1668        'username',
1669        'username_colour',
1670        'guest_username',
1671        'custom_profile_url',
1672        'username_string',
1673        '_profile_cache',
1674    );
1675    extract($phpbb_dispatcher->trigger_event('core.modify_username_string', compact($vars)));
1676
1677    return $username_string;
1678}
1679
1680/**
1681 * Add an option to the quick-mod tools.
1682 *
1683 * @param string $url The recepting URL for the quickmod actions.
1684 * @param string $option The language key for the value of the option.
1685 * @param string $lang_string The language string to use.
1686 */
1687function phpbb_add_quickmod_option($url, $option, $lang_string)
1688{
1689    global $template, $user, $phpbb_path_helper;
1690
1691    $lang_string = $user->lang($lang_string);
1692    $template->assign_block_vars('quickmod', array(
1693        'VALUE'        => $option,
1694        'TITLE'        => $lang_string,
1695        'LINK'        => $phpbb_path_helper->append_url_params($url, array('action' => $option)),
1696    ));
1697}
1698
1699/**
1700* Concatenate an array into a string list.
1701*
1702* @param array $items Array of items to concatenate
1703* @param object $user The phpBB $user object.
1704*
1705* @return string String list. Examples: "A"; "A and B"; "A, B, and C"
1706*/
1707function phpbb_generate_string_list($items, $user)
1708{
1709    if (empty($items))
1710    {
1711        return '';
1712    }
1713
1714    $count = count($items);
1715    $last_item = array_pop($items);
1716    $lang_key = 'STRING_LIST_MULTI';
1717
1718    if ($count == 1)
1719    {
1720        return $last_item;
1721    }
1722    else if ($count == 2)
1723    {
1724        $lang_key = 'STRING_LIST_SIMPLE';
1725    }
1726    $list = implode($user->lang['COMMA_SEPARATOR'], $items);
1727
1728    return $user->lang($lang_key, $list, $last_item);
1729}
1730
1731class bitfield
1732{
1733    var $data;
1734
1735    function __construct($bitfield = '')
1736    {
1737        $this->data = base64_decode($bitfield);
1738    }
1739
1740    /**
1741    */
1742    function get($n)
1743    {
1744        // Get the ($n / 8)th char
1745        $byte = $n >> 3;
1746
1747        if (strlen($this->data) >= $byte + 1)
1748        {
1749            $c = $this->data[$byte];
1750
1751            // Lookup the ($n % 8)th bit of the byte
1752            $bit = 7 - ($n & 7);
1753            return (bool) (ord($c) & (1 << $bit));
1754        }
1755        else
1756        {
1757            return false;
1758        }
1759    }
1760
1761    function set($n)
1762    {
1763        $byte = $n >> 3;
1764        $bit = 7 - ($n & 7);
1765
1766        if (strlen($this->data) >= $byte + 1)
1767        {
1768            $this->data[$byte] = $this->data[$byte] | chr(1 << $bit);
1769        }
1770        else
1771        {
1772            $this->data .= str_repeat("\0", $byte - strlen($this->data));
1773            $this->data .= chr(1 << $bit);
1774        }
1775    }
1776
1777    function clear($n)
1778    {
1779        $byte = $n >> 3;
1780
1781        if (strlen($this->data) >= $byte + 1)
1782        {
1783            $bit = 7 - ($n & 7);
1784            $this->data[$byte] = $this->data[$byte] &~ chr(1 << $bit);
1785        }
1786    }
1787
1788    function get_blob()
1789    {
1790        return $this->data;
1791    }
1792
1793    function get_base64()
1794    {
1795        return base64_encode($this->data);
1796    }
1797
1798    function get_bin()
1799    {
1800        $bin = '';
1801        $len = strlen($this->data);
1802
1803        for ($i = 0; $i < $len; ++$i)
1804        {
1805            $bin .= str_pad(decbin(ord($this->data[$i])), 8, '0', STR_PAD_LEFT);
1806        }
1807
1808        return $bin;
1809    }
1810
1811    function get_all_set()
1812    {
1813        return array_keys(array_filter(str_split($this->get_bin())));
1814    }
1815
1816    function merge($bitfield)
1817    {
1818        $this->data = $this->data | $bitfield->get_blob();
1819    }
1820}
1821
1822/**
1823 * Formats the quote according to the given BBCode status setting
1824 *
1825 * @param phpbb\language\language                $language Language class
1826 * @param parse_message                         $message_parser Message parser class
1827 * @param phpbb\textformatter\utils_interface    $text_formatter_utils Text formatter utilities
1828 * @param bool                                     $bbcode_status The status of the BBCode setting
1829 * @param array                                 $quote_attributes The attributes of the quoted post
1830 * @param string                                 $message_link Link of the original quoted post
1831 */
1832function phpbb_format_quote($language, $message_parser, $text_formatter_utils, $bbcode_status, $quote_attributes, $message_link = '')
1833{
1834    if ($bbcode_status)
1835    {
1836        $quote_text = $text_formatter_utils->generate_quote(
1837            censor_text($message_parser->message),
1838            $quote_attributes
1839        );
1840
1841        $message_parser->message = $quote_text . "\n\n";
1842    }
1843    else
1844    {
1845        $offset = 0;
1846        $quote_string = "&gt; ";
1847        $message = censor_text(trim($message_parser->message));
1848        // see if we are nesting. It's easily tricked but should work for one level of nesting
1849        if (strpos($message, "&gt;") !== false)
1850        {
1851            $offset = 10;
1852        }
1853        $message = utf8_wordwrap($message, 75 + $offset, "\n");
1854
1855        $message = $quote_string . $message;
1856        $message = str_replace("\n", "\n" . $quote_string, $message);
1857
1858        $message_parser->message = $quote_attributes['author'] . " " . $language->lang('WROTE') . ":\n" . $message . "\n";
1859    }
1860
1861    if ($message_link)
1862    {
1863        $message_parser->message = $message_link . $message_parser->message;
1864    }
1865}