Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
50.63% covered (warning)
50.63%
362 / 715
41.94% covered (danger)
41.94%
13 / 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
100.00% covered (success)
100.00%
39 / 39
100.00% covered (success)
100.00%
1 / 1
15
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): string
328{
329    if ($length <= 0)
330    {
331        return $text;
332    }
333
334    // We need to turn the entities back into their original form, to not cut the message in between them
335    $text = htmlspecialchars_decode($text);
336
337    // Replace all spaces/invisible characters with single spaces
338    $text = preg_replace("/[\p{Z}\h\v]+/u", ' ', $text);
339
340    $text_length = utf8_strlen($text);
341
342    // Get first occurrence of each word
343    $word_indexes = [];
344    foreach ($words as $word)
345    {
346        $pos = utf8_stripos($text, $word);
347
348        if ($pos !== false)
349        {
350            $word_indexes[$pos] = $word;
351        }
352    }
353    if (!empty($word_indexes))
354    {
355        ksort($word_indexes);
356
357        // Size of the fragment of text per word
358        $num_indexes = count($word_indexes);
359        $characters_per_word = (int) ($length / $num_indexes) + 2; // 2 to leave one character of margin at the sides to don't cut words
360
361        // Get text fragment indexes
362        $fragments = [];
363        foreach ($word_indexes as $index => $word)
364        {
365            $word_length = utf8_strlen($word);
366            $start = max(0, min($text_length - 1 - $characters_per_word, (int) ($index + ($word_length / 2) - ($characters_per_word / 2))));
367            $end = $start + $characters_per_word;
368
369            // Check if we can merge this fragment into the previous fragment
370            if (!empty($fragments))
371            {
372                [$prev_start, $prev_end] = end($fragments);
373
374                if ($prev_end + $characters_per_word >= $index + $word_length)
375                {
376                    array_pop($fragments);
377                    $start = $prev_start;
378                    $end = $prev_end + $characters_per_word;
379                }
380            }
381
382            $fragments[] = [$start, $end];
383        }
384    }
385    else
386    {
387        // There is no coincidences, so we just create a fragment with the first $length characters
388        $fragments[] = [0, $length];
389        $end = $length;
390    }
391
392    $output = [];
393    foreach ($fragments as [$start, $end])
394    {
395        $fragment = utf8_substr($text, $start, $end - $start + 1);
396
397        $fragment_start = 0;
398        $fragment_end = $end - $start + 1;
399
400        // Find the first valid alphanumeric character in the fragment to don't cut words
401        if ($start > 0 && preg_match('/[^\p{L}\p{N}][\p{L}\p{N}]/u', $fragment, $matches, PREG_OFFSET_CAPTURE))
402        {
403            $fragment_start = utf8_strlen(substr($fragment, 0, (int) $matches[0][1])) + 1;
404        }
405
406        // Find the last valid alphanumeric character in the fragment to don't cut words
407        if ($end < $text_length - 1 && preg_match_all('/[\p{L}\p{N}][^\p{L}\p{N}]/u', $fragment, $matches, PREG_OFFSET_CAPTURE))
408        {
409            $fragment_end = utf8_strlen(substr($fragment, 0, end($matches[0])[1]));
410        }
411
412        $output[] = utf8_substr($fragment, $fragment_start, $fragment_end - $fragment_start + 1);
413    }
414
415    return ($fragments[0][0] !== 0 ? '... ' : '') . utf8_htmlspecialchars(implode(' ... ', $output)) . ($end < $text_length - 1 ? ' ...' : '');
416}
417
418/**
419* Cleans a search string by removing single wildcards from it and replacing multiple spaces with a single one.
420*
421* @param string $search_string The full search string which should be cleaned.
422*
423* @return string The cleaned search string without any wildcards and multiple spaces.
424*/
425function phpbb_clean_search_string($search_string)
426{
427    // This regular expressions matches every single wildcard.
428    // That means one after a whitespace or the beginning of the string or one before a whitespace or the end of the string.
429    $search_string = preg_replace('#(?<=^|\s)\*+(?=\s|$)#', '', $search_string);
430    $search_string = trim($search_string);
431    $search_string = preg_replace(array('#\s+#u', '#\*+#u'), array(' ', '*'), $search_string);
432    return $search_string;
433}
434
435/**
436* Decode text whereby text is coming from the db and expected to be pre-parsed content
437* We are placing this outside of the message parser because we are often in need of it...
438*
439* NOTE: special chars are kept encoded
440*
441* @param string &$message Original message, passed by reference
442* @param string $bbcode_uid BBCode UID
443* @return void
444*/
445function decode_message(&$message, $bbcode_uid = '')
446{
447    global $phpbb_container, $phpbb_dispatcher;
448
449    /**
450     * Use this event to modify the message before it is decoded
451     *
452     * @event core.decode_message_before
453     * @var string    message_text    The message content
454     * @var string    bbcode_uid        The message BBCode UID
455     * @since 3.1.9-RC1
456     */
457    $message_text = $message;
458    $vars = array('message_text', 'bbcode_uid');
459    extract($phpbb_dispatcher->trigger_event('core.decode_message_before', compact($vars)));
460    $message = $message_text;
461
462    if (preg_match('#^<[rt][ >]#', $message))
463    {
464        $message = htmlspecialchars($phpbb_container->get('text_formatter.utils')->unparse($message), ENT_COMPAT);
465    }
466    else
467    {
468        if ($bbcode_uid)
469        {
470            $match = array('<br />', "[/*:m:$bbcode_uid]", ":u:$bbcode_uid", ":o:$bbcode_uid", ":$bbcode_uid");
471            $replace = array("\n", '', '', '', '');
472        }
473        else
474        {
475            $match = array('<br />');
476            $replace = array("\n");
477        }
478
479        $message = str_replace($match, $replace, $message);
480
481        $match = get_preg_expression('bbcode_htm');
482        $replace = array('\1', '\1', '\2', '\2', '\1', '', '');
483
484        $message = preg_replace($match, $replace, $message);
485    }
486
487    /**
488    * Use this event to modify the message after it is decoded
489    *
490    * @event core.decode_message_after
491    * @var string    message_text    The message content
492    * @var string    bbcode_uid        The message BBCode UID
493    * @since 3.1.9-RC1
494    */
495    $message_text = $message;
496    $vars = array('message_text', 'bbcode_uid');
497    extract($phpbb_dispatcher->trigger_event('core.decode_message_after', compact($vars)));
498    $message = $message_text;
499}
500
501/**
502* Strips all bbcode from a text in place
503*/
504function strip_bbcode(&$text, $uid = '')
505{
506    global $phpbb_container;
507
508    if (preg_match('#^<[rt][ >]#', $text))
509    {
510        $text = utf8_htmlspecialchars($phpbb_container->get('text_formatter.utils')->clean_formatting($text));
511    }
512    else
513    {
514        if (!$uid)
515        {
516            $uid = '[0-9a-z]{5,}';
517        }
518
519        $text = preg_replace("#\[\/?[a-z0-9\*\+\-]+(?:=(?:&quot;.*&quot;|[^\]]*))?(?::[a-z])?(\:$uid)\]#", ' ', $text);
520
521        $match = get_preg_expression('bbcode_htm');
522        $replace = array('\1', '\1', '\2', '\1', '', '');
523
524        $text = preg_replace($match, $replace, $text);
525    }
526}
527
528/**
529* For display of custom parsed text on user-facing pages
530* Expects $text to be the value directly from the database (stored value)
531*
532* @return string Generated text
533*/
534function generate_text_for_display($text, $uid, $bitfield, $flags, $censor_text = true)
535{
536    static $bbcode;
537    global $auth, $config, $user;
538    global $phpbb_dispatcher, $phpbb_container;
539
540    if ($text === '')
541    {
542        return '';
543    }
544
545    /**
546    * Use this event to modify the text before it is parsed
547    *
548    * @event core.modify_text_for_display_before
549    * @var string    text            The text to parse
550    * @var string    uid                The BBCode UID
551    * @var string    bitfield        The BBCode Bitfield
552    * @var int        flags            The BBCode Flags
553    * @var bool        censor_text        Whether or not to apply word censors
554    * @since 3.1.0-a1
555    */
556    $vars = array('text', 'uid', 'bitfield', 'flags', 'censor_text');
557    extract($phpbb_dispatcher->trigger_event('core.modify_text_for_display_before', compact($vars)));
558
559    if (preg_match('#^<[rt][ >]#', $text))
560    {
561        $renderer = $phpbb_container->get('text_formatter.renderer');
562
563        // Temporarily switch off viewcensors if applicable
564        $old_censor = $renderer->get_viewcensors();
565
566        // Check here if the user is having viewing censors disabled (and also allowed to do so).
567        if (!$user->optionget('viewcensors') && $config['allow_nocensors'] && $auth->acl_get('u_chgcensors'))
568        {
569            $censor_text = false;
570        }
571
572        if ($old_censor !== $censor_text)
573        {
574            $renderer->set_viewcensors($censor_text);
575        }
576
577        $text = $renderer->render($text);
578
579        // Restore the previous value
580        if ($old_censor !== $censor_text)
581        {
582            $renderer->set_viewcensors($old_censor);
583        }
584    }
585    else
586    {
587        if ($censor_text)
588        {
589            $text = censor_text($text);
590        }
591
592        // Parse bbcode if bbcode uid stored and bbcode enabled
593        if ($uid && ($flags & OPTION_FLAG_BBCODE))
594        {
595            if (!class_exists('bbcode'))
596            {
597                global $phpbb_root_path, $phpEx;
598                include($phpbb_root_path . 'includes/bbcode.' . $phpEx);
599            }
600
601            if (empty($bbcode))
602            {
603                $bbcode = new bbcode($bitfield);
604            }
605            else
606            {
607                $bbcode->bbcode_set_bitfield($bitfield);
608            }
609
610            $bbcode->bbcode_second_pass($text, $uid);
611        }
612
613        $text = bbcode_nl2br($text);
614        $text = smiley_text($text, !($flags & OPTION_FLAG_SMILIES));
615    }
616
617    /**
618    * Use this event to modify the text after it is parsed
619    *
620    * @event core.modify_text_for_display_after
621    * @var string    text        The text to parse
622    * @var string    uid            The BBCode UID
623    * @var string    bitfield    The BBCode Bitfield
624    * @var int        flags        The BBCode Flags
625    * @since 3.1.0-a1
626    */
627    $vars = array('text', 'uid', 'bitfield', 'flags');
628    extract($phpbb_dispatcher->trigger_event('core.modify_text_for_display_after', compact($vars)));
629
630    return $text;
631}
632
633/**
634* For parsing custom parsed text to be stored within the database.
635* This function additionally returns the uid and bitfield that needs to be stored.
636* Expects $text to be the value directly from $request->variable() and in it's non-parsed form
637*
638* @param string $text The text to be replaced with the parsed one
639* @param string $uid The BBCode uid for this parse
640* @param string $bitfield The BBCode bitfield for this parse
641* @param int $flags The allow_bbcode, allow_urls and allow_smilies compiled into a single integer.
642* @param bool $allow_bbcode If BBCode is allowed (i.e. if BBCode is parsed)
643* @param bool $allow_urls If urls is allowed
644* @param bool $allow_smilies If smilies are allowed
645* @param bool $allow_img_bbcode
646* @param bool $allow_quote_bbcode
647* @param bool $allow_url_bbcode
648* @param string $mode Mode to parse text as, e.g. post or sig
649*
650* @return array    An array of string with the errors that occurred while parsing
651*/
652function 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')
653{
654    global $phpbb_root_path, $phpEx, $phpbb_dispatcher;
655
656    /**
657    * Use this event to modify the text before it is prepared for storage
658    *
659    * @event core.modify_text_for_storage_before
660    * @var string    text            The text to parse
661    * @var string    uid                The BBCode UID
662    * @var string    bitfield        The BBCode Bitfield
663    * @var int        flags            The BBCode Flags
664    * @var bool        allow_bbcode    Whether or not to parse BBCode
665    * @var bool        allow_urls        Whether or not to parse URLs
666    * @var bool        allow_smilies    Whether or not to parse Smilies
667    * @var bool        allow_img_bbcode    Whether or not to parse the [img] BBCode
668    * @var bool        allow_quote_bbcode    Whether or not to parse the [quote] BBCode
669    * @var bool        allow_url_bbcode    Whether or not to parse the [url] BBCode
670    * @var string    mode                Mode to parse text as, e.g. post or sig
671    * @since 3.1.0-a1
672    * @changed 3.2.0-a1 Added mode
673    * @changed 4.0.0-a1 Removed allow_flash_bbcode
674    */
675    $vars = array(
676        'text',
677        'uid',
678        'bitfield',
679        'flags',
680        'allow_bbcode',
681        'allow_urls',
682        'allow_smilies',
683        'allow_img_bbcode',
684        'allow_quote_bbcode',
685        'allow_url_bbcode',
686        'mode',
687    );
688    extract($phpbb_dispatcher->trigger_event('core.modify_text_for_storage_before', compact($vars)));
689
690    $uid = $bitfield = '';
691    $flags = (($allow_bbcode) ? OPTION_FLAG_BBCODE : 0) + (($allow_smilies) ? OPTION_FLAG_SMILIES : 0) + (($allow_urls) ? OPTION_FLAG_LINKS : 0);
692
693    if (!class_exists('parse_message'))
694    {
695        include($phpbb_root_path . 'includes/message_parser.' . $phpEx);
696    }
697
698    $message_parser = new parse_message($text);
699    $message_parser->parse($allow_bbcode, $allow_urls, $allow_smilies, $allow_img_bbcode, $allow_quote_bbcode, $allow_url_bbcode, true, $mode);
700
701    $text = $message_parser->message;
702    $uid = $message_parser->bbcode_uid;
703
704    // If the bbcode_bitfield is empty, there is no need for the uid to be stored.
705    if (!$message_parser->bbcode_bitfield)
706    {
707        $uid = '';
708    }
709
710    $bitfield = $message_parser->bbcode_bitfield;
711
712    /**
713    * Use this event to modify the text after it is prepared for storage
714    *
715    * @event core.modify_text_for_storage_after
716    * @var string    text            The text to parse
717    * @var string    uid                The BBCode UID
718    * @var string    bitfield        The BBCode Bitfield
719    * @var int        flags            The BBCode Flags
720    * @var string    message_parser    The message_parser object
721    * @since 3.1.0-a1
722    * @changed 3.1.11-RC1            Added message_parser to vars
723    */
724    $vars = array('text', 'uid', 'bitfield', 'flags', 'message_parser');
725    extract($phpbb_dispatcher->trigger_event('core.modify_text_for_storage_after', compact($vars)));
726
727    return $message_parser->warn_msg;
728}
729
730/**
731* For decoding custom parsed text for edits as well as extracting the flags
732* Expects $text to be the value directly from the database (pre-parsed content)
733*/
734function generate_text_for_edit($text, $uid, $flags)
735{
736    global $phpbb_dispatcher;
737
738    /**
739    * Use this event to modify the text before it is decoded for editing
740    *
741    * @event core.modify_text_for_edit_before
742    * @var string    text            The text to parse
743    * @var string    uid                The BBCode UID
744    * @var int        flags            The BBCode Flags
745    * @since 3.1.0-a1
746    */
747    $vars = array('text', 'uid', 'flags');
748    extract($phpbb_dispatcher->trigger_event('core.modify_text_for_edit_before', compact($vars)));
749
750    decode_message($text, $uid);
751
752    /**
753    * Use this event to modify the text after it is decoded for editing
754    *
755    * @event core.modify_text_for_edit_after
756    * @var string    text            The text to parse
757    * @var int        flags            The BBCode Flags
758    * @since 3.1.0-a1
759    */
760    $vars = array('text', 'flags');
761    extract($phpbb_dispatcher->trigger_event('core.modify_text_for_edit_after', compact($vars)));
762
763    return array(
764        'allow_bbcode'    => ($flags & OPTION_FLAG_BBCODE) ? 1 : 0,
765        'allow_smilies'    => ($flags & OPTION_FLAG_SMILIES) ? 1 : 0,
766        'allow_urls'    => ($flags & OPTION_FLAG_LINKS) ? 1 : 0,
767        'text'            => $text
768    );
769}
770
771/**
772* A subroutine of make_clickable used with preg_replace
773* It places correct HTML around an url, shortens the displayed text
774* and makes sure no entities are inside URLs
775*/
776function make_clickable_callback($type, $whitespace, $url, $relative_url, $class)
777{
778    $orig_url        = $url;
779    $orig_relative    = $relative_url;
780    $append            = '';
781    $url            = html_entity_decode($url, ENT_COMPAT);
782    $relative_url    = html_entity_decode($relative_url, ENT_COMPAT);
783
784    // make sure no HTML entities were matched
785    $chars = array('<', '>', '"');
786    $split = false;
787
788    foreach ($chars as $char)
789    {
790        $next_split = strpos($url, $char);
791        if ($next_split !== false)
792        {
793            $split = ($split !== false) ? min($split, $next_split) : $next_split;
794        }
795    }
796
797    if ($split !== false)
798    {
799        // an HTML entity was found, so the URL has to end before it
800        $append            = substr($url, $split) . $relative_url;
801        $url            = substr($url, 0, $split);
802        $relative_url    = '';
803    }
804    else if ($relative_url)
805    {
806        // same for $relative_url
807        $split = false;
808        foreach ($chars as $char)
809        {
810            $next_split = strpos($relative_url, $char);
811            if ($next_split !== false)
812            {
813                $split = ($split !== false) ? min($split, $next_split) : $next_split;
814            }
815        }
816
817        if ($split !== false)
818        {
819            $append            = substr($relative_url, $split);
820            $relative_url    = substr($relative_url, 0, $split);
821        }
822    }
823    // if the last character of the url is a punctuation mark, exclude it from the url
824    $last_char = ($relative_url) ? $relative_url[strlen($relative_url) - 1] : $url[strlen($url) - 1];
825
826    switch ($last_char)
827    {
828        case '.':
829        case '?':
830        case '!':
831        case ':':
832        case ',':
833            $append = $last_char;
834            if ($relative_url)
835            {
836                $relative_url = substr($relative_url, 0, -1);
837            }
838            else
839            {
840                $url = substr($url, 0, -1);
841            }
842        break;
843
844        // set last_char to empty here, so the variable can be used later to
845        // check whether a character was removed
846        default:
847            $last_char = '';
848        break;
849    }
850
851    $short_url = (utf8_strlen($url) > 55) ? utf8_substr($url, 0, 39) . ' ... ' . utf8_substr($url, -10) : $url;
852
853    switch ($type)
854    {
855        case MAGIC_URL_LOCAL:
856            $tag            = 'l';
857            $relative_url    = preg_replace('/[&?]sid=[0-9a-f]{32}$/', '', preg_replace('/([&?])sid=[0-9a-f]{32}&/', '$1', $relative_url));
858            $url            = $url . '/' . $relative_url;
859            $text            = $relative_url;
860
861            // this url goes to http://domain.tld/path/to/board/ which
862            // would result in an empty link if treated as local so
863            // don't touch it and let MAGIC_URL_FULL take care of it.
864            if (!$relative_url)
865            {
866                return $whitespace . $orig_url . '/' . $orig_relative; // slash is taken away by relative url pattern
867            }
868        break;
869
870        case MAGIC_URL_FULL:
871            $tag    = 'm';
872            $text    = $short_url;
873        break;
874
875        case MAGIC_URL_WWW:
876            $tag    = 'w';
877            $url    = 'http://' . $url;
878            $text    = $short_url;
879        break;
880
881        case MAGIC_URL_EMAIL:
882            $tag    = 'e';
883            $text    = $short_url;
884            $url    = 'mailto:' . $url;
885        break;
886    }
887
888    $url    = htmlspecialchars($url, ENT_COMPAT);
889    $text    = htmlspecialchars($text, ENT_COMPAT);
890    $append    = htmlspecialchars($append, ENT_COMPAT);
891
892    $html    = "$whitespace<!-- $tag --><a$class href=\"$url\">$text</a><!-- $tag -->$append";
893
894    return $html;
895}
896
897/**
898 * Replaces magic urls of form http://xxx.xxx., www.xxx. and xxx@xxx.xxx.
899 * Cuts down displayed size of link if over 50 chars, turns absolute links
900 * into relative versions when the server/script path matches the link
901 *
902 * @param string        $text        Message text to parse URL/email entries
903 * @param bool|string    $server_url    The server URL. If false, the board URL will be used
904 * @param string        $class        CSS class selector to add to the parsed URL entries
905 *
906 * @return string    A text with parsed URL/email entries
907 */
908function make_clickable($text, $server_url = false, string $class = 'postlink')
909{
910    if ($server_url === false)
911    {
912        $server_url = generate_board_url();
913    }
914
915    static $static_class;
916    static $magic_url_match_args;
917
918    if (!isset($magic_url_match_args[$server_url]) || $static_class != $class)
919    {
920        $static_class = $class;
921        $class = ($static_class) ? ' class="' . $static_class . '"' : '';
922        $local_class = ($static_class) ? ' class="' . $static_class . '-local"' : '';
923
924        if (!is_array($magic_url_match_args))
925        {
926            $magic_url_match_args = array();
927        }
928
929        // Check if the match for this $server_url and $class already exists
930        $element_exists = false;
931        if (isset($magic_url_match_args[$server_url]))
932        {
933            array_walk_recursive($magic_url_match_args[$server_url], function($value) use (&$element_exists, $static_class)
934                {
935                    if ($value == $static_class)
936                    {
937                        $element_exists = true;
938                    }
939                }
940            );
941        }
942
943        // Only add new $server_url and $class matches if not exist
944        if (!$element_exists)
945        {
946            // relative urls for this board
947            $magic_url_match_args[$server_url][] = [
948                '#(^|[\n\t (>.])(' . preg_quote($server_url, '#') . ')/(' . get_preg_expression('relative_url_inline') . ')#iu',
949                MAGIC_URL_LOCAL,
950                $local_class,
951                $static_class,
952            ];
953
954            // matches a xxxx://aaaaa.bbb.cccc. ...
955            $magic_url_match_args[$server_url][] = [
956                '#(^|[\n\t (>.])(' . get_preg_expression('url_inline') . ')#iu',
957                MAGIC_URL_FULL,
958                $class,
959                $static_class,
960            ];
961
962            // matches a "www.xxxx.yyyy[/zzzz]" kinda lazy URL thing
963            $magic_url_match_args[$server_url][] = [
964                '#(^|[\n\t (>])(' . get_preg_expression('www_url_inline') . ')#iu',
965                MAGIC_URL_WWW,
966                $class,
967                $static_class,
968            ];
969        }
970
971        if (!isset($magic_url_match_args[$server_url]['email']))
972        {
973            // matches an email@domain type address at the start of a line, or after a space or after what might be a BBCode.
974            $magic_url_match_args[$server_url]['email'] = [
975                '/(^|[\n\t (>])(' . get_preg_expression('email') . ')/iu',
976                MAGIC_URL_EMAIL,
977                '',
978            ];
979        }
980    }
981
982    foreach ($magic_url_match_args[$server_url] as $magic_args)
983    {
984        if (preg_match($magic_args[0], $text, $matches))
985        {
986            // Only apply $class from the corresponding function call argument (excepting emails which never has a class)
987            if ($magic_args[1] != MAGIC_URL_EMAIL && $magic_args[3] != $static_class)
988            {
989                continue;
990            }
991
992            $text = preg_replace_callback($magic_args[0], function($matches) use ($magic_args)
993            {
994                $relative_url = isset($matches[3]) ? $matches[3] : '';
995                return make_clickable_callback($magic_args[1], $matches[1], $matches[2], $relative_url, $magic_args[2]);
996            }, $text);
997        }
998    }
999
1000    return $text;
1001}
1002
1003/**
1004* Censoring
1005*/
1006function censor_text($text)
1007{
1008    static $censors;
1009
1010    // Nothing to do?
1011    if ($text === '')
1012    {
1013        return '';
1014    }
1015
1016    // We moved the word censor checks in here because we call this function quite often - and then only need to do the check once
1017    if (!isset($censors) || !is_array($censors))
1018    {
1019        global $config, $user, $auth, $cache;
1020
1021        // We check here if the user is having viewing censors disabled (and also allowed to do so).
1022        if (!$user->optionget('viewcensors') && $config['allow_nocensors'] && $auth->acl_get('u_chgcensors'))
1023        {
1024            $censors = array();
1025        }
1026        else
1027        {
1028            $censors = $cache->obtain_word_list();
1029        }
1030    }
1031
1032    if (count($censors))
1033    {
1034        return preg_replace($censors['match'], $censors['replace'], $text);
1035    }
1036
1037    return $text;
1038}
1039
1040/**
1041* custom version of nl2br which takes custom BBCodes into account
1042*/
1043function bbcode_nl2br($text)
1044{
1045    // custom BBCodes might contain carriage returns so they
1046    // are not converted into <br /> so now revert that
1047    $text = str_replace(array("\n", "\r"), array('<br />', "\n"), $text);
1048    return $text;
1049}
1050
1051/**
1052* Smiley processing
1053*/
1054function smiley_text($text, $force_option = false)
1055{
1056    global $config, $user, $phpbb_path_helper, $phpbb_dispatcher;
1057
1058    if ($force_option || !$config['allow_smilies'] || !$user->optionget('viewsmilies'))
1059    {
1060        return preg_replace('#<!\-\- s(.*?) \-\-><img src="\{SMILIES_PATH\}\/.*? \/><!\-\- s\1 \-\->#', '\1', $text);
1061    }
1062    else
1063    {
1064        $root_path = $phpbb_path_helper->get_web_root_path();
1065
1066        /**
1067        * Event to override the root_path for smilies
1068        *
1069        * @event core.smiley_text_root_path
1070        * @var string root_path root_path for smilies
1071        * @since 3.1.11-RC1
1072        */
1073        $vars = array('root_path');
1074        extract($phpbb_dispatcher->trigger_event('core.smiley_text_root_path', compact($vars)));
1075        return preg_replace('#<!\-\- s(.*?) \-\-><img src="\{SMILIES_PATH\}\/(.*?) \/><!\-\- s\1 \-\->#', '<img class="smilies" src="' . $root_path . $config['smilies_path'] . '/\2 />', $text);
1076    }
1077}
1078
1079/**
1080* General attachment parsing
1081*
1082* @param mixed $forum_id The forum id the attachments are displayed in (false if in private message)
1083* @param string &$message The post/private message
1084* @param array &$attachments The attachments to parse for (inline) display. The attachments array will hold templated data after parsing.
1085* @param array &$update_count_ary The attachment counts to be updated - will be filled
1086* @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.
1087*/
1088function parse_attachments($forum_id, &$message, &$attachments, &$update_count_ary, $preview = false)
1089{
1090    if (!count($attachments))
1091    {
1092        return;
1093    }
1094
1095    global $template, $cache, $user, $phpbb_dispatcher;
1096    global $extensions, $config, $phpbb_root_path, $phpEx;
1097    global $phpbb_container;
1098
1099    $storage_attachment = $phpbb_container->get('storage.attachment');
1100
1101    /** @var \phpbb\controller\helper */
1102    $controller_helper = $phpbb_container->get('controller.helper');
1103
1104    //
1105    $compiled_attachments = array();
1106
1107    if (!isset($template->filename['attachment_tpl']))
1108    {
1109        $template->set_filenames(array(
1110            'attachment_tpl'    => 'attachment.html')
1111        );
1112    }
1113
1114    if (empty($extensions) || !is_array($extensions))
1115    {
1116        $extensions = $cache->obtain_attach_extensions($forum_id);
1117    }
1118
1119    // Look for missing attachment information...
1120    $attach_ids = array();
1121    foreach ($attachments as $pos => $attachment)
1122    {
1123        // If is_orphan is set, we need to retrieve the attachments again...
1124        if (!isset($attachment['extension']) && !isset($attachment['physical_filename']))
1125        {
1126            $attach_ids[(int) $attachment['attach_id']] = $pos;
1127        }
1128    }
1129
1130    // Grab attachments (security precaution)
1131    if (count($attach_ids))
1132    {
1133        global $db;
1134
1135        $new_attachment_data = array();
1136
1137        $sql = 'SELECT *
1138            FROM ' . ATTACHMENTS_TABLE . '
1139            WHERE ' . $db->sql_in_set('attach_id', array_keys($attach_ids));
1140        $result = $db->sql_query($sql);
1141
1142        while ($row = $db->sql_fetchrow($result))
1143        {
1144            if (!isset($attach_ids[$row['attach_id']]))
1145            {
1146                continue;
1147            }
1148
1149            // If we preview attachments we will set some retrieved values here
1150            if ($preview)
1151            {
1152                $row['attach_comment'] = $attachments[$attach_ids[$row['attach_id']]]['attach_comment'];
1153            }
1154
1155            $new_attachment_data[$attach_ids[$row['attach_id']]] = $row;
1156        }
1157        $db->sql_freeresult($result);
1158
1159        $attachments = $new_attachment_data;
1160        unset($new_attachment_data);
1161    }
1162
1163    // Make sure attachments are properly ordered
1164    ksort($attachments);
1165
1166    foreach ($attachments as $attachment)
1167    {
1168        if (!count($attachment))
1169        {
1170            continue;
1171        }
1172
1173        // We need to reset/empty the _file block var, because this function might be called more than once
1174        $template->destroy_block_vars('_file');
1175
1176        $block_array = array();
1177
1178        // Some basics...
1179        $attachment['extension'] = strtolower(trim($attachment['extension']));
1180        $filename = utf8_basename($attachment['physical_filename']);
1181
1182        $upload_icon = '';
1183        $download_link = '';
1184        $display_cat = false;
1185
1186        if (isset($extensions[$attachment['extension']]))
1187        {
1188            if ($user->img('icon_topic_attach', '') && !$extensions[$attachment['extension']]['upload_icon'])
1189            {
1190                $upload_icon = $user->img('icon_topic_attach', '');
1191            }
1192            else if ($extensions[$attachment['extension']]['upload_icon'])
1193            {
1194                $upload_icon = '<img src="' . $phpbb_root_path . $config['upload_icons_path'] . '/' . trim($extensions[$attachment['extension']]['upload_icon']) . '" alt="" />';
1195            }
1196        }
1197
1198        $filesize = get_formatted_filesize($attachment['filesize'], false);
1199
1200        $comment = bbcode_nl2br(censor_text($attachment['attach_comment']));
1201
1202        $block_array += array(
1203            'UPLOAD_ICON'        => $upload_icon,
1204            'FILESIZE'            => $filesize['value'],
1205            'MIMETYPE'            => $attachment['mimetype'],
1206            'SIZE_LANG'            => $filesize['unit'],
1207            'DOWNLOAD_NAME'        => utf8_basename($attachment['real_filename']),
1208            'COMMENT'            => $comment,
1209        );
1210
1211        $denied = false;
1212
1213        if (!extension_allowed($forum_id, $attachment['extension'], $extensions))
1214        {
1215            $denied = true;
1216
1217            $block_array += array(
1218                'S_DENIED'            => true,
1219                'DENIED_MESSAGE'    => sprintf($user->lang['EXTENSION_DISABLED_AFTER_POSTING'], $attachment['extension'])
1220            );
1221        }
1222
1223        if (!$denied)
1224        {
1225            $display_cat = $extensions[$attachment['extension']]['display_cat'];
1226
1227            if ($display_cat == attachment_category::IMAGE)
1228            {
1229                if ($attachment['thumbnail'])
1230                {
1231                    $display_cat = attachment_category::THUMB;
1232                }
1233                else
1234                {
1235                    if ($config['img_display_inlined'])
1236                    {
1237                        if ($config['img_link_width'] || $config['img_link_height'])
1238                        {
1239                            try
1240                            {
1241                                $file_info = $storage_attachment->file_info($filename);
1242
1243                                $display_cat = ($file_info->image_width <= $config['img_link_width'] && $file_info->image_height <= $config['img_link_height']) ? attachment_category::IMAGE : attachment_category::NONE;
1244                            }
1245                            catch (\Exception $e)
1246                            {
1247                                $display_cat = attachment_category::NONE;
1248                            }
1249                        }
1250                    }
1251                    else
1252                    {
1253                        $display_cat = attachment_category::NONE;
1254                    }
1255                }
1256            }
1257
1258            // Make some descisions based on user options being set.
1259            if (($display_cat == attachment_category::IMAGE || $display_cat == attachment_category::THUMB) && !$user->optionget('viewimg'))
1260            {
1261                $display_cat = attachment_category::NONE;
1262            }
1263
1264            $download_link = $controller_helper->route(
1265                'phpbb_storage_attachment',
1266                [
1267                    'id'        => (int) $attachment['attach_id'],
1268                    'filename'    => $attachment['real_filename'],
1269                ]
1270            );
1271            $l_downloaded_viewed = 'VIEWED_COUNTS';
1272
1273            switch ($display_cat)
1274            {
1275                // Images
1276                case attachment_category::IMAGE:
1277                    $inline_link = $controller_helper->route(
1278                        'phpbb_storage_attachment',
1279                        [
1280                            'id'        => (int) $attachment['attach_id'],
1281                            'filename'    => $attachment['real_filename'],
1282                        ]
1283                    );
1284
1285                    $block_array += array(
1286                        'S_IMAGE'        => true,
1287                        'U_INLINE_LINK'        => $inline_link,
1288                    );
1289
1290                    $update_count_ary[] = $attachment['attach_id'];
1291                break;
1292
1293                // Images, but display Thumbnail
1294                case attachment_category::THUMB:
1295                    $thumbnail_link = $controller_helper->route(
1296                        'phpbb_storage_attachment',
1297                        [
1298                            'id'        => (int) $attachment['attach_id'],
1299                            'filename'    => $attachment['real_filename'],
1300                            't'            => 1,
1301                        ]
1302                    );
1303
1304                    $block_array += array(
1305                        'S_THUMBNAIL'        => true,
1306                        'THUMB_IMAGE'        => $thumbnail_link,
1307                    );
1308
1309                    $update_count_ary[] = $attachment['attach_id'];
1310                break;
1311
1312                // Audio files
1313                case attachment_category::AUDIO:
1314                    $block_array += [
1315                        'S_AUDIO_FILE'            => true,
1316                    ];
1317
1318                    $update_count_ary[] = $attachment['attach_id'];
1319                break;
1320
1321                // Video files
1322                case attachment_category::VIDEO:
1323                    $block_array += [
1324                        'S_VIDEO_FILE'            => true,
1325                    ];
1326
1327                    $update_count_ary[] = $attachment['attach_id'];
1328                break;
1329
1330                default:
1331                    $l_downloaded_viewed = 'DOWNLOAD_COUNTS';
1332
1333                    $block_array += array(
1334                        'S_FILE'        => true,
1335                    );
1336                break;
1337            }
1338
1339            if (!isset($attachment['download_count']))
1340            {
1341                $attachment['download_count'] = 0;
1342            }
1343
1344            $block_array += array(
1345                'U_DOWNLOAD_LINK'        => $download_link,
1346                'L_DOWNLOAD_COUNT'        => $user->lang($l_downloaded_viewed, (int) $attachment['download_count']),
1347            );
1348        }
1349
1350        $update_count = $update_count_ary;
1351        /**
1352        * Use this event to modify the attachment template data.
1353        *
1354        * This event is triggered once per attachment.
1355        *
1356        * @event core.parse_attachments_modify_template_data
1357        * @var array    attachment        Array with attachment data
1358        * @var array    block_array        Template data of the attachment
1359        * @var int        display_cat        Attachment category data
1360        * @var string    download_link    Attachment download link
1361        * @var array    extensions        Array with attachment extensions data
1362        * @var mixed     forum_id         The forum id the attachments are displayed in (false if in private message)
1363        * @var bool        preview            Flag indicating if we are in post preview mode
1364        * @var array    update_count    Array with attachment ids to update download count
1365        * @since 3.1.0-RC5
1366        */
1367        $vars = array(
1368            'attachment',
1369            'block_array',
1370            'display_cat',
1371            'download_link',
1372            'extensions',
1373            'forum_id',
1374            'preview',
1375            'update_count',
1376        );
1377        extract($phpbb_dispatcher->trigger_event('core.parse_attachments_modify_template_data', compact($vars)));
1378        $update_count_ary = $update_count;
1379        unset($update_count, $display_cat, $download_link);
1380
1381        $template->assign_block_vars('_file', $block_array);
1382
1383        $compiled_attachments[] = $template->assign_display('attachment_tpl');
1384    }
1385
1386    $attachments = $compiled_attachments;
1387    unset($compiled_attachments);
1388
1389    $unset_tpl = array();
1390
1391    preg_match_all('#<!\-\- ia([0-9]+) \-\->(.*?)<!\-\- ia\1 \-\->#', $message, $matches, PREG_PATTERN_ORDER);
1392
1393    $replace = array();
1394    foreach (array_keys($matches[0]) as $num)
1395    {
1396        $index = $matches[1][$num];
1397
1398        $replace['from'][] = $matches[0][$num];
1399        $replace['to'][] = (isset($attachments[$index])) ? $attachments[$index] : sprintf($user->lang['MISSING_INLINE_ATTACHMENT'], $matches[2][array_search($index, $matches[1])]);
1400
1401        $unset_tpl[] = $index;
1402    }
1403
1404    if (isset($replace['from']))
1405    {
1406        $message = str_replace($replace['from'], $replace['to'], $message);
1407    }
1408
1409    $unset_tpl = array_unique($unset_tpl);
1410
1411    // Sort correctly
1412    if ($config['display_order'])
1413    {
1414        // Ascending sort
1415        krsort($attachments);
1416    }
1417    else
1418    {
1419        // Descending sort
1420        ksort($attachments);
1421    }
1422
1423    // Needed to let not display the inlined attachments at the end of the post again
1424    foreach ($unset_tpl as $index)
1425    {
1426        unset($attachments[$index]);
1427    }
1428}
1429
1430/**
1431* Check if extension is allowed to be posted.
1432*
1433* @param mixed $forum_id The forum id to check or false if private message
1434* @param string $extension The extension to check, for example zip.
1435* @param array &$extensions The extension array holding the information from the cache (will be obtained if empty)
1436*
1437* @return bool False if the extension is not allowed to be posted, else true.
1438*/
1439function extension_allowed($forum_id, $extension, &$extensions)
1440{
1441    if (empty($extensions))
1442    {
1443        global $cache;
1444        $extensions = $cache->obtain_attach_extensions($forum_id);
1445    }
1446
1447    return (!isset($extensions['_allowed_'][$extension])) ? false : true;
1448}
1449
1450/**
1451* Truncates string while retaining special characters if going over the max length
1452* The default max length is 60 at the moment
1453* The maximum storage length is there to fit the string within the given length. The string may be further truncated due to html entities.
1454* For example: string given is 'a "quote"' (length: 9), would be a stored as 'a &quot;quote&quot;' (length: 19)
1455*
1456* @param string $string The text to truncate to the given length. String is specialchared.
1457* @param int $max_length Maximum length of string (multibyte character count as 1 char / Html entity count as 1 char)
1458* @param int $max_store_length Maximum character length of string (multibyte character count as 1 char / Html entity count as entity chars).
1459* @param bool $allow_reply Allow Re: in front of string
1460*     NOTE: This parameter can cause undesired behavior (returning strings longer than $max_store_length) and is deprecated.
1461* @param string $append String to be appended
1462*/
1463function truncate_string($string, $max_length = 60, $max_store_length = 255, $allow_reply = false, $append = '')
1464{
1465    $strip_reply = false;
1466    $stripped = false;
1467    if ($allow_reply && strpos($string, 'Re: ') === 0)
1468    {
1469        $strip_reply = true;
1470        $string = substr($string, 4);
1471    }
1472
1473    $_chars = utf8_str_split(html_entity_decode($string, ENT_COMPAT));
1474    $chars = array_map('utf8_htmlspecialchars', $_chars);
1475
1476    // Now check the length ;)
1477    if (count($chars) > $max_length)
1478    {
1479        // Cut off the last elements from the array
1480        $string = implode('', array_slice($chars, 0, $max_length - utf8_strlen($append)));
1481        $stripped = true;
1482    }
1483
1484    // Due to specialchars, we may not be able to store the string...
1485    if (utf8_strlen($string) > $max_store_length)
1486    {
1487        // let's split again, we do not want half-baked strings where entities are split
1488        $_chars = utf8_str_split(html_entity_decode($string, ENT_COMPAT));
1489        $chars = array_map('utf8_htmlspecialchars', $_chars);
1490
1491        do
1492        {
1493            array_pop($chars);
1494            $string = implode('', $chars);
1495        }
1496        while (!empty($chars) && utf8_strlen($string) > $max_store_length);
1497    }
1498
1499    if ($strip_reply)
1500    {
1501        $string = 'Re: ' . $string;
1502    }
1503
1504    if ($append != '' && $stripped)
1505    {
1506        $string = $string . $append;
1507    }
1508
1509    return $string;
1510}
1511
1512/**
1513* Get username details for placing into templates.
1514* This function caches all modes on first call, except for no_profile and anonymous user - determined by $user_id.
1515*
1516* @html Username spans and links
1517*
1518* @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)
1519* @param int $user_id The users id
1520* @param string $username The users name
1521* @param string $username_colour The users colour
1522* @param string|false $guest_username optional parameter to specify the guest username. It will be used in favor of the GUEST language variable then.
1523* @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}
1524*
1525* @return string A string consisting of what is wanted based on $mode.
1526*/
1527function get_username_string($mode, $user_id, $username, $username_colour = '', $guest_username = false, $custom_profile_url = false)
1528{
1529    static $_profile_cache;
1530    global $phpbb_dispatcher;
1531
1532    // We cache some common variables we need within this function
1533    if (empty($_profile_cache))
1534    {
1535        global $phpbb_root_path, $phpEx;
1536
1537        /** @html Username spans and links for usage in the template */
1538        $_profile_cache['base_url'] = append_sid("{$phpbb_root_path}memberlist.$phpEx", 'mode=viewprofile&amp;u={USER_ID}');
1539        $_profile_cache['tpl_noprofile'] = '<span class="username">{USERNAME}</span>';
1540        $_profile_cache['tpl_noprofile_colour'] = '<span style="color: {USERNAME_COLOUR};" class="username-coloured">{USERNAME}</span>';
1541        $_profile_cache['tpl_profile'] = '<a href="{PROFILE_URL}" class="username">{USERNAME}</a>';
1542        $_profile_cache['tpl_profile_colour'] = '<a href="{PROFILE_URL}" style="color: {USERNAME_COLOUR};" class="username-coloured">{USERNAME}</a>';
1543    }
1544
1545    global $user, $auth;
1546
1547    // This switch makes sure we only run code required for the mode
1548    switch ($mode)
1549    {
1550        case 'full':
1551        case 'no_profile':
1552        case 'colour':
1553
1554            // Build correct username colour
1555            $username_colour = ($username_colour) ? '#' . $username_colour : '';
1556
1557            // Return colour
1558            if ($mode == 'colour')
1559            {
1560                $username_string = $username_colour;
1561                break;
1562            }
1563
1564        // no break;
1565
1566        case 'username':
1567
1568            // Build correct username
1569            if ($guest_username === false)
1570            {
1571                $username = ($username) ? $username : $user->lang['GUEST'];
1572            }
1573            else
1574            {
1575                $username = ($user_id && $user_id != ANONYMOUS) ? $username : ((!empty($guest_username)) ? $guest_username : $user->lang['GUEST']);
1576            }
1577
1578            // Return username
1579            if ($mode == 'username')
1580            {
1581                $username_string = $username;
1582                break;
1583            }
1584
1585        // no break;
1586
1587        case 'profile':
1588
1589            // Build correct profile url - only show if not anonymous and permission to view profile if registered user
1590            // For anonymous the link leads to a login page.
1591            if ($user_id && $user_id != ANONYMOUS && ($user->data['user_id'] == ANONYMOUS || $auth->acl_get('u_viewprofile')))
1592            {
1593                $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']);
1594            }
1595            else
1596            {
1597                $profile_url = '';
1598            }
1599
1600            // Return profile
1601            if ($mode == 'profile')
1602            {
1603                $username_string = $profile_url;
1604                break;
1605            }
1606
1607        // no break;
1608    }
1609
1610    if (!isset($username_string))
1611    {
1612        if (($mode == 'full' && !$profile_url) || $mode == 'no_profile')
1613        {
1614            $username_string = str_replace(array('{USERNAME_COLOUR}', '{USERNAME}'), array($username_colour, $username), (!$username_colour) ? $_profile_cache['tpl_noprofile'] : $_profile_cache['tpl_noprofile_colour']);
1615        }
1616        else
1617        {
1618            $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']);
1619        }
1620    }
1621
1622    /**
1623    * Use this event to change the output of get_username_string()
1624    *
1625    * @event core.modify_username_string
1626    * @var string mode                profile|username|colour|full|no_profile
1627    * @var int user_id                String or array of additional url
1628    *                                parameters
1629    * @var string username            The user's username
1630    * @var string username_colour    The user's colour
1631    * @var string guest_username    Optional parameter to specify the
1632    *                                guest username.
1633    * @var string custom_profile_url Optional parameter to specify a
1634    *                                profile url.
1635    * @var string username_string    The string that has been generated
1636    * @var array _profile_cache        Array of original return templates
1637    * @since 3.1.0-a1
1638    */
1639    $vars = array(
1640        'mode',
1641        'user_id',
1642        'username',
1643        'username_colour',
1644        'guest_username',
1645        'custom_profile_url',
1646        'username_string',
1647        '_profile_cache',
1648    );
1649    extract($phpbb_dispatcher->trigger_event('core.modify_username_string', compact($vars)));
1650
1651    return $username_string;
1652}
1653
1654/**
1655 * Add an option to the quick-mod tools.
1656 *
1657 * @param string $url The recepting URL for the quickmod actions.
1658 * @param string $option The language key for the value of the option.
1659 * @param string $lang_string The language string to use.
1660 */
1661function phpbb_add_quickmod_option($url, $option, $lang_string)
1662{
1663    global $template, $user, $phpbb_path_helper;
1664
1665    $lang_string = $user->lang($lang_string);
1666    $template->assign_block_vars('quickmod', array(
1667        'VALUE'        => $option,
1668        'TITLE'        => $lang_string,
1669        'LINK'        => $phpbb_path_helper->append_url_params($url, array('action' => $option)),
1670    ));
1671}
1672
1673/**
1674* Concatenate an array into a string list.
1675*
1676* @param array $items Array of items to concatenate
1677* @param object $user The phpBB $user object.
1678*
1679* @return string String list. Examples: "A"; "A and B"; "A, B, and C"
1680*/
1681function phpbb_generate_string_list($items, $user)
1682{
1683    if (empty($items))
1684    {
1685        return '';
1686    }
1687
1688    $count = count($items);
1689    $last_item = array_pop($items);
1690    $lang_key = 'STRING_LIST_MULTI';
1691
1692    if ($count == 1)
1693    {
1694        return $last_item;
1695    }
1696    else if ($count == 2)
1697    {
1698        $lang_key = 'STRING_LIST_SIMPLE';
1699    }
1700    $list = implode($user->lang['COMMA_SEPARATOR'], $items);
1701
1702    return $user->lang($lang_key, $list, $last_item);
1703}
1704
1705class bitfield
1706{
1707    var $data;
1708
1709    function __construct($bitfield = '')
1710    {
1711        $this->data = base64_decode($bitfield);
1712    }
1713
1714    /**
1715    */
1716    function get($n)
1717    {
1718        // Get the ($n / 8)th char
1719        $byte = $n >> 3;
1720
1721        if (strlen($this->data) >= $byte + 1)
1722        {
1723            $c = $this->data[$byte];
1724
1725            // Lookup the ($n % 8)th bit of the byte
1726            $bit = 7 - ($n & 7);
1727            return (bool) (ord($c) & (1 << $bit));
1728        }
1729        else
1730        {
1731            return false;
1732        }
1733    }
1734
1735    function set($n)
1736    {
1737        $byte = $n >> 3;
1738        $bit = 7 - ($n & 7);
1739
1740        if (strlen($this->data) >= $byte + 1)
1741        {
1742            $this->data[$byte] = $this->data[$byte] | chr(1 << $bit);
1743        }
1744        else
1745        {
1746            $this->data .= str_repeat("\0", $byte - strlen($this->data));
1747            $this->data .= chr(1 << $bit);
1748        }
1749    }
1750
1751    function clear($n)
1752    {
1753        $byte = $n >> 3;
1754
1755        if (strlen($this->data) >= $byte + 1)
1756        {
1757            $bit = 7 - ($n & 7);
1758            $this->data[$byte] = $this->data[$byte] &~ chr(1 << $bit);
1759        }
1760    }
1761
1762    function get_blob()
1763    {
1764        return $this->data;
1765    }
1766
1767    function get_base64()
1768    {
1769        return base64_encode($this->data);
1770    }
1771
1772    function get_bin()
1773    {
1774        $bin = '';
1775        $len = strlen($this->data);
1776
1777        for ($i = 0; $i < $len; ++$i)
1778        {
1779            $bin .= str_pad(decbin(ord($this->data[$i])), 8, '0', STR_PAD_LEFT);
1780        }
1781
1782        return $bin;
1783    }
1784
1785    function get_all_set()
1786    {
1787        return array_keys(array_filter(str_split($this->get_bin())));
1788    }
1789
1790    function merge($bitfield)
1791    {
1792        $this->data = $this->data | $bitfield->get_blob();
1793    }
1794}
1795
1796/**
1797 * Formats the quote according to the given BBCode status setting
1798 *
1799 * @param phpbb\language\language                $language Language class
1800 * @param parse_message                         $message_parser Message parser class
1801 * @param phpbb\textformatter\utils_interface    $text_formatter_utils Text formatter utilities
1802 * @param bool                                     $bbcode_status The status of the BBCode setting
1803 * @param array                                 $quote_attributes The attributes of the quoted post
1804 * @param string                                 $message_link Link of the original quoted post
1805 */
1806function phpbb_format_quote($language, $message_parser, $text_formatter_utils, $bbcode_status, $quote_attributes, $message_link = '')
1807{
1808    if ($bbcode_status)
1809    {
1810        $quote_text = $text_formatter_utils->generate_quote(
1811            censor_text($message_parser->message),
1812            $quote_attributes
1813        );
1814
1815        $message_parser->message = $quote_text . "\n\n";
1816    }
1817    else
1818    {
1819        $offset = 0;
1820        $quote_string = "&gt; ";
1821        $message = censor_text(trim($message_parser->message));
1822        // see if we are nesting. It's easily tricked but should work for one level of nesting
1823        if (strpos($message, "&gt;") !== false)
1824        {
1825            $offset = 10;
1826        }
1827        $message = utf8_wordwrap($message, 75 + $offset, "\n");
1828
1829        $message = $quote_string . $message;
1830        $message = str_replace("\n", "\n" . $quote_string, $message);
1831
1832        $message_parser->message = $quote_attributes['author'] . " " . $language->lang('WROTE') . ":\n" . $message . "\n";
1833    }
1834
1835    if ($message_link)
1836    {
1837        $message_parser->message = $message_link . $message_parser->message;
1838    }
1839}