Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
60.84% covered (warning)
60.84%
247 / 406
33.33% covered (danger)
33.33%
3 / 9
CRAP
n/a
0 / 0
adm_page_header
0.00% covered (danger)
0.00%
0 / 69
0.00% covered (danger)
0.00%
0 / 1
156
adm_page_footer
0.00% covered (danger)
0.00%
0 / 22
0.00% covered (danger)
0.00%
0 / 1
30
adm_back_link
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
build_select
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
3
phpbb_build_radio
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
2
phpbb_build_cfg_template
92.31% covered (success)
92.31%
144 / 156
0.00% covered (danger)
0.00%
0 / 1
56.38
validate_config_vars
46.46% covered (danger)
46.46%
46 / 99
0.00% covered (danger)
0.00%
0 / 1
631.93
validate_range
96.43% covered (success)
96.43%
27 / 28
0.00% covered (danger)
0.00%
0 / 1
11
phpbb_insert_config_array
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
4
1<?php
2/**
3*
4* This file is part of the phpBB Forum Software package.
5*
6* @copyright (c) phpBB Limited <https://www.phpbb.com>
7* @license GNU General Public License, version 2 (GPL-2.0)
8*
9* For full copyright and license information, please see
10* the docs/CREDITS.txt file.
11*
12*/
13
14/**
15* @ignore
16*/
17if (!defined('IN_PHPBB'))
18{
19    exit;
20}
21
22/**
23* Header for acp pages
24*/
25function adm_page_header($page_title)
26{
27    global $config, $user, $template;
28    global $phpbb_root_path, $phpbb_admin_path, $phpEx, $SID, $_SID;
29    global $phpbb_dispatcher, $phpbb_container;
30
31    if (defined('HEADER_INC'))
32    {
33        return;
34    }
35
36    define('HEADER_INC', true);
37
38    // A listener can set this variable to `true` when it overrides this function
39    $adm_page_header_override = false;
40
41    /**
42    * Execute code and/or overwrite adm_page_header()
43    *
44    * @event core.adm_page_header
45    * @var    string    page_title            Page title
46    * @var    bool    adm_page_header_override    Shall we return instead of
47    *                                    running the rest of adm_page_header()
48    * @since 3.1.0-a1
49    */
50    $vars = array('page_title', 'adm_page_header_override');
51    extract($phpbb_dispatcher->trigger_event('core.adm_page_header', compact($vars)));
52
53    if ($adm_page_header_override)
54    {
55        return;
56    }
57
58    $user->update_session_infos();
59
60    // gzip_compression
61    if ($config['gzip_compress'])
62    {
63        if (@extension_loaded('zlib') && !headers_sent())
64        {
65            ob_start('ob_gzhandler');
66        }
67    }
68
69    $phpbb_version_parts = explode('.', PHPBB_VERSION, 3);
70    $phpbb_major = $phpbb_version_parts[0] . '.' . $phpbb_version_parts[1];
71
72    $template->assign_vars(array(
73        'PAGE_TITLE'            => $page_title,
74        'USERNAME'                => $user->data['username'],
75
76        'SID'                    => $SID,
77        '_SID'                    => $_SID,
78        'SESSION_ID'            => $user->session_id,
79        'ROOT_PATH'                => $phpbb_root_path,
80        'ADMIN_ROOT_PATH'        => $phpbb_admin_path,
81        'PHPBB_VERSION'            => PHPBB_VERSION,
82        'PHPBB_MAJOR'            => $phpbb_major,
83
84        'U_LOGOUT'                => append_sid("{$phpbb_root_path}ucp.$phpEx", 'mode=logout'),
85        'U_ADM_LOGOUT'            => append_sid("{$phpbb_admin_path}index.$phpEx", 'action=admlogout&amp;hash=' . generate_link_hash('acp_logout')),
86        'U_ADM_INDEX'            => append_sid("{$phpbb_admin_path}index.$phpEx"),
87        'U_INDEX'                => append_sid("{$phpbb_root_path}index.$phpEx"),
88
89        'T_IMAGES_PATH'            => "{$phpbb_root_path}images/",
90        'T_SMILIES_PATH'        => "{$phpbb_root_path}{$config['smilies_path']}/",
91        'T_AVATAR_GALLERY_PATH'    => "{$phpbb_root_path}{$config['avatar_gallery_path']}/",
92        'T_ICONS_PATH'            => "{$phpbb_root_path}{$config['icons_path']}/",
93        'T_RANKS_PATH'            => "{$phpbb_root_path}{$config['ranks_path']}/",
94        'T_UPLOAD_PATH'            => "{$phpbb_root_path}{$config['upload_path']}/",
95
96        'T_FONT_AWESOME_LINK'    => !empty($config['allow_cdn']) && !empty($config['load_font_awesome_url']) ? $config['load_font_awesome_url'] : "{$phpbb_root_path}assets/css/font-awesome.min.css?assets_version=" . $config['assets_version'],
97
98        'T_ASSETS_VERSION'        => $config['assets_version'],
99        'T_ASSETS_PATH'            => "{$phpbb_root_path}assets",
100
101        'ICON_MOVE_UP'                => '<i class="acp-icon acp-icon-move-up fa-arrow-circle-up fa-fw fas" title="' . $user->lang('MOVE_UP') . '"></i>',
102        'ICON_MOVE_UP_DISABLED'        => '<i class="acp-icon acp-icon-disabled fa-arrow-circle-up fa-fw fas" title="' . $user->lang('MOVE_UP') . '"></i>',
103        'ICON_MOVE_DOWN'            => '<i class="acp-icon acp-icon-move-down fa-arrow-circle-down fa-fw fas" title="' . $user->lang('MOVE_DOWN') . '"></i>',
104        'ICON_MOVE_DOWN_DISABLED'    => '<i class="acp-icon acp-icon-disabled fa-arrow-circle-down fa-fw fas" title="' . $user->lang('MOVE_DOWN') . '"></i>',
105        'ICON_EDIT'                    => '<i class="acp-icon acp-icon-settings fa-gear fa-fw fas" title="' . $user->lang('EDIT') . '"></i>',
106        'ICON_EDIT_DISABLED'        => '<i class="acp-icon acp-icon-disabled fa-gear fa-fw fas" title="' . $user->lang('EDIT') . '"></i>',
107        'ICON_DELETE'                => '<i class="acp-icon acp-icon-delete fa-xmark-circle fa-fw fas" title="' . $user->lang('DELETE') . '"></i>',
108        'ICON_DELETE_DISABLED'        => '<i class="acp-icon acp-icon-disabled fa-xmark-circle fa-fw fas" title="' . $user->lang('DELETE') . '"></i>',
109        'ICON_SYNC'                    => '<i class="acp-icon acp-icon-resync fa-arrows-rotate fa-fw fas" title="' . $user->lang('RESYNC') . '"></i>',
110        'ICON_SYNC_DISABLED'        => '<i class="acp-icon acp-icon-disabled fa-arrows-rotate fa-fw fas" title="' . $user->lang('RESYNC') . '"></i>',
111
112        'S_USER_ID'                => $user->data['user_id'],
113        'S_USER_LANG'            => $user->lang('USER_LANG'),
114        'S_CONTENT_DIRECTION'    => $user->lang('DIRECTION'),
115        'S_CONTENT_ENCODING'    => 'UTF-8',
116        'S_CONTENT_FLOW_BEGIN'    => ($user->lang('DIRECTION')  == 'ltr') ? 'left' : 'right',
117        'S_CONTENT_FLOW_END'    => ($user->lang('DIRECTION')  == 'ltr') ? 'right' : 'left',
118
119        'CONTAINER_EXCEPTION'    => $phpbb_container->hasParameter('container_exception') ? $phpbb_container->getParameter('container_exception') : false,
120    ));
121
122    // An array of http headers that phpBB will set. The following event may override these.
123    $http_headers = array(
124        // application/xhtml+xml not used because of IE
125        'Content-type' => 'text/html; charset=UTF-8',
126        'Cache-Control' => 'private, no-cache="set-cookie"',
127        'Expires' => gmdate('D, d M Y H:i:s', time()) . ' GMT',
128        'Referrer-Policy' => 'strict-origin-when-cross-origin',
129    );
130
131    /**
132    * Execute code and/or overwrite _common_ template variables after they have been assigned.
133    *
134    * @event core.adm_page_header_after
135    * @var    string    page_title            Page title
136    * @var    array    http_headers            HTTP headers that should be set by phpbb
137    *
138    * @since 3.1.0-RC3
139    */
140    $vars = array('page_title', 'http_headers');
141    extract($phpbb_dispatcher->trigger_event('core.adm_page_header_after', compact($vars)));
142
143    foreach ($http_headers as $hname => $hval)
144    {
145        header((string) $hname . ': ' . (string) $hval);
146    }
147
148    return;
149}
150
151/**
152* Page footer for acp pages
153*/
154function adm_page_footer($copyright_html = true)
155{
156    global $db, $config, $template, $user, $auth;
157    global $phpbb_root_path, $phpbb_container;
158    global $phpbb_dispatcher;
159
160    /** @var \phpbb\controller\helper $controller_helper */
161    $controller_helper = $phpbb_container->get('controller.helper');
162
163    // A listener can set this variable to `true` when it overrides this function
164    $adm_page_footer_override = false;
165
166    /**
167    * Execute code and/or overwrite adm_page_footer()
168    *
169    * @event core.adm_page_footer
170    * @var    bool    copyright_html            Shall we display the copyright?
171    * @var    bool    adm_page_footer_override    Shall we return instead of
172    *                                    running the rest of adm_page_footer()
173    * @since 3.1.0-a1
174    */
175    $vars = array('copyright_html', 'adm_page_footer_override');
176    extract($phpbb_dispatcher->trigger_event('core.adm_page_footer', compact($vars)));
177
178    if ($adm_page_footer_override)
179    {
180        return;
181    }
182
183    $controller_helper->display_sql_report();
184
185    $template->assign_vars(array(
186        'DEBUG_OUTPUT'        => phpbb_generate_debug_output($db, $config, $auth, $user, $phpbb_dispatcher),
187        'TRANSLATION_INFO'    => (!empty($user->lang['TRANSLATION_INFO'])) ? $user->lang['TRANSLATION_INFO'] : '',
188        'S_COPYRIGHT_HTML'    => $copyright_html,
189        'CREDIT_LINE'        => $user->lang('POWERED_BY', '<a href="https://www.phpbb.com/">phpBB</a>&reg; Forum Software &copy; phpBB Limited'),
190        'T_JQUERY_LINK'        => !empty($config['allow_cdn']) && !empty($config['load_jquery_url']) ? $config['load_jquery_url'] : "{$phpbb_root_path}assets/javascript/jquery-3.7.1.min.js",
191        'S_ALLOW_CDN'        => !empty($config['allow_cdn']),
192        'VERSION'            => $config['version'])
193    );
194
195    $template->display('body');
196
197    garbage_collection();
198    exit_handler();
199}
200
201/**
202* Generate back link for acp pages
203*/
204function adm_back_link($u_action)
205{
206    global $user;
207    return '<br /><br /><a href="' . $u_action . '">&laquo; ' . $user->lang['BACK_TO_PREV'] . '</a>';
208}
209
210/**
211 * Build select field options in acp pages
212 *
213 * @param array                $options_ary Configuration options data
214 * @param int|string|bool    $option_default    Configuration option selected value
215 *
216 * @return array
217 */
218function build_select(array $options_ary, int|string|bool $option_default = false): array
219{
220    global $language;
221
222    $options = [];
223    foreach ($options_ary as $value => $title)
224    {
225        $options[] = [
226            'value'    => $value,
227            'selected'    => $option_default !== false && $value == $option_default,
228            'label'    => $language->lang($title),
229        ];
230    }
231
232    return $options;
233}
234
235/**
236 * Build radio fields in acp pages
237 *
238 * @param int|string    $value    Configuration option value
239 * @param string        $key    Configuration option key name
240 * @param array            $options Configuration options data
241 *                             representing array of [values => language_keys]
242 *
243 * @return array
244 */
245function phpbb_build_radio(int|string $value, string $key, array $options): array
246{
247    global $language;
248
249    $buttons = [];
250    foreach ($options as $val => $title)
251    {
252        $buttons[] = [
253            'type'        => 'radio',
254            'value'        => $val,
255            'name'        => 'config[' . $key . ']',
256            'checked'    => $val == $value,
257            'label'        => $language->lang($title),
258        ];
259    }
260
261    return [
262        'buttons' => $buttons,
263    ];
264}
265
266/**
267 * Build configuration data arrays or templates for configuration settings
268 *
269 * @param array            $tpl_type    Configuration setting type data
270 * @param string        $key        Configuration option name
271 * @param array|object    $new_ary    Updated configuration data
272 * @param string        $config_key    Configuration option name
273 * @param array            $vars        Configuration setting data
274 *
275 * @return array|string
276 */
277function phpbb_build_cfg_template(array $tpl_type, string $key, array|object &$new_ary, string $config_key, array $vars): array|string
278{
279    global $language, $module, $phpbb_dispatcher;
280
281    $tpl = [];
282    $name = 'config[' . $config_key . ']';
283
284    // Make sure there is no notice printed out for non-existent config options (we simply set them)
285    if (!isset($new_ary[$config_key]))
286    {
287        $new_ary[$config_key] = '';
288    }
289
290    switch ($tpl_type[0])
291    {
292        case 'password':
293            if ($new_ary[$config_key] !== '')
294            {
295                // replace passwords with asterixes
296                $new_ary[$config_key] = '********';
297            }
298            // no break
299
300        case 'text':
301        case 'url':
302        case 'email':
303        case 'tel':
304        case 'search':
305            // maxlength and size are only valid for these types and will be
306            // ignored for other input types.
307            $size = (int) $tpl_type[1];
308            $maxlength = (int) $tpl_type[2];
309
310            $tpl = [
311                'tag'        => 'input',
312                'id'        => $key,
313                'type'        => $tpl_type[0],
314                'name'        => $name,
315                'size'        => $size ?: '',
316                'maxlength'    => $maxlength ?: 255,
317                'value'        => $new_ary[$config_key],
318            ];
319        break;
320
321        case 'color':
322        case 'datetime':
323        case 'datetime-local':
324        case 'month':
325        case 'week':
326            $tpl = [
327                'tag'        => 'input',
328                'id'        => $key,
329                'type'        => $tpl_type[0],
330                'name'        => $name,
331                'value'        => $new_ary[$config_key],
332            ];
333        break;
334
335        case 'date':
336        case 'time':
337        case 'number':
338        case 'range':
339            $min = isset($tpl_type[1]) ? (int) $tpl_type[1] : false;
340            $max = isset($tpl_type[2]) ? (int) $tpl_type[2] : false;
341
342            $tpl = [
343                'tag'        => 'input',
344                'id'        => $key,
345                'type'        => $tpl_type[0],
346                'name'        => $name,
347                'min'        => $min !== false ? $min : '',
348                'max'        => $max !== false ? $max : '',
349                'value'        => $new_ary[$config_key],
350            ];
351        break;
352
353        case 'dimension':
354            $min = isset($tpl_type[1]) ? (int) $tpl_type[1] : false;
355            $max = isset($tpl_type[2]) ? (int) $tpl_type[2] : false;
356
357            $tpl = [
358                'tag'        => 'dimension',
359                'width' => [
360                    'id'        => $key,
361                    'type'        => 'number',
362                    'name'        => 'config[' . $config_key . '_width]',
363                    'min'        => $min !== false ? $min : '',
364                    'max'        => $max !== false ? $max : '',
365                    'value'        => $new_ary[$config_key . '_width'],
366                ],
367                'height' => [
368                    'type'        => 'number',
369                    'name'        => 'config[' . $config_key . '_height]',
370                    'min'        => $min !== false ? $min : '',
371                    'max'        => $max !== false ? $max : '',
372                    'value'        => $new_ary[$config_key . '_height'],
373                ],
374            ];
375        break;
376
377        case 'textarea':
378            $tpl = [
379                'tag'        => 'textarea',
380                'id'        => $key,
381                'name'        => $name,
382                'rows'        => (int) $tpl_type[1],
383                'cols'        => (int) $tpl_type[2],
384                'content'    => $new_ary[$config_key],
385            ];
386        break;
387
388        case 'radio':
389            if (!isset($vars['method']) && !isset($vars['function']))
390            {
391                if (in_array($tpl_type[1], ['yes_no', 'enabled_disabled']))
392                {
393                    $options = array_reverse(explode('_', strtoupper($tpl_type[1])));
394                    krsort($options);
395                    $tpl_type = array_merge ($tpl_type, phpbb_build_radio($new_ary[$config_key], $config_key, $options));
396                }
397            }
398        case 'button':
399        case 'select':
400        case 'custom':
401            $args = [];
402            $call = $vars['function'] ?? (isset($vars['method']) ? [$module->module, $vars['method']] : false);
403
404            if ($call)
405            {
406                if (isset($vars['params']))
407                {
408                    foreach ($vars['params'] as $value)
409                    {
410                        switch ($value)
411                        {
412                            case '{CONFIG_VALUE}':
413                                $value = $new_ary[$config_key];
414                            break;
415
416                            case '{KEY}':
417                                $value = $config_key;
418                            break;
419                        }
420
421                        $args[] = $value;
422                    }
423                }
424                else
425                {
426                    $args = array($new_ary[$config_key], $config_key);
427                }
428            }
429
430            $return = $call ? call_user_func_array($call, $args) : [];
431
432            if (in_array($tpl_type[0], ['select', 'radio', 'button']))
433            {
434                $tpl_type = array_merge($tpl_type, $return);
435
436                if ($tpl_type[0] == 'select')
437                {
438                    $tpl = [
439                        'tag'            => 'select',
440                        'class'            => $tpl_type['class'] ?? false,
441                        'id'            => $key,
442                        'data'            => $tpl_type['data'] ?? [],
443                        'name'            => $name,
444                        'toggleable'    => !empty($tpl_type[2]) || !empty($tpl_type['toggleable']),
445                        'options'        => $tpl_type['options'],
446                        'group_only'    => $tpl_type['group_only'] ?? false,
447                        'size'            => $tpl_type[1] ?? $tpl_type['size'] ?? 1,
448                        'multiple'        => $tpl_type['multiple'] ?? false,
449                    ];
450                }
451                else if ($tpl_type[0] == 'radio')
452                {
453                    // Only assign id to the one (1st) radio button in the list
454                    $id_assigned = false;
455                    foreach ($tpl_type['buttons'] as $i => $button)
456                    {
457                        if (!$id_assigned)
458                        {
459                            $tpl_type['buttons'][$i]['id'] = $key;
460                            $id_assigned = true;
461                        }
462                    }
463
464                    $tpl = [
465                        'tag'        => 'radio',
466                        'buttons'    => $tpl_type['buttons'],
467                    ];
468                }
469                else
470                {
471                    $tpl = [
472                        'tag'        => 'input',
473                        'class'        => $tpl_type['options']['class'],
474                        'id'        => $key,
475                        'type'        => $tpl_type['options']['type'],
476                        'name'        => $tpl_type['options']['name'] ?? $name,
477                        'value'        => $tpl_type['options']['value'],
478                    ];
479                }
480            }
481            else
482            {
483                $tpl = $return;
484            }
485        break;
486
487        default:
488        break;
489    }
490
491    if (isset($vars['append']))
492    {
493        if (is_array($tpl))
494        {
495            $tpl['append'] = $vars['append'];
496        }
497        else
498        {
499            $tpl .= $vars['append'];
500        }
501    }
502
503    $new = $new_ary;
504    /**
505    * Overwrite the html code we display for the config value
506    *
507    * @event core.build_config_template
508    * @var    array            tpl_type    Config type array:
509    *                            0 => data type
510    *                            1 [optional] => string: size, int: minimum
511    *                            2 [optional] => string: max. length, int: maximum
512    * @var    string            key            Should be used for the id attribute in html
513    * @var    array            new            Array with the config values we display
514    * @var    string            name        Should be used for the name attribute
515    * @var    array            vars        Array with the options for the config
516    * @var    array|string    tpl            The resulting html code we display
517    * @since 3.1.0-a1
518    * @changed 4.0.0-a1    The event location's function renamed from build_config_template() to phpbb_build_cfg_template()
519    */
520    $vars = array('tpl_type', 'key', 'new', 'name', 'vars', 'tpl');
521    extract($phpbb_dispatcher->trigger_event('core.build_config_template', compact($vars)));
522    $new_ary = $new;
523    unset($new);
524
525    return $tpl;
526}
527
528/**
529* Going through a config array and validate values, writing errors to $error. The validation method  accepts parameters separated by ':' for string and int.
530* The first parameter defines the type to be used, the second the lower bound and the third the upper bound. Only the type is required.
531*/
532function validate_config_vars($config_vars, &$cfg_array, &$error)
533{
534    global $phpbb_root_path, $user, $phpbb_dispatcher, $phpbb_filesystem, $language;
535
536    $type    = 0;
537    $min    = 1;
538    $max    = 2;
539
540    foreach ($config_vars as $config_name => $config_definition)
541    {
542        if (!isset($cfg_array[$config_name]) || strpos($config_name, 'legend') !== false)
543        {
544            continue;
545        }
546
547        if (!isset($config_definition['validate']))
548        {
549            continue;
550        }
551
552        $validator = explode(':', $config_definition['validate']);
553
554        // Validate a bit. ;) (0 = type, 1 = min, 2= max)
555        switch ($validator[$type])
556        {
557            case 'url':
558            case 'csv':
559                if ($validator[$type] == 'url')
560                {
561                    $cfg_array[$config_name] = trim($cfg_array[$config_name]);
562
563                    if (!empty($cfg_array[$config_name]) && !preg_match('#^' . get_preg_expression('url') . '$#iu', $cfg_array[$config_name]))
564                    {
565                        $error[] = $language->lang('URL_INVALID', $language->lang($config_definition['lang']));
566                    }
567                }
568                else if ($validator[$type] == 'csv')
569                {
570                    // Validate comma separated values
571                    $unfiltered_array = explode(',', $cfg_array[$config_name]);
572                    $filtered_array = array_filter($unfiltered_array);
573                    if (!empty($filtered_array) && count($unfiltered_array) !== count($filtered_array))
574                    {
575                        $error[] = $language->lang('CSV_INVALID', $language->lang($config_definition['lang']));
576                    }
577
578                }
579            // no break here
580
581            case 'string':
582                $length = utf8_strlen($cfg_array[$config_name]);
583
584                // the column is a VARCHAR
585                $validator[$max] = (isset($validator[$max])) ? min(255, $validator[$max]) : 255;
586
587                if (isset($validator[$min]) && $length < $validator[$min])
588                {
589                    $error[] = sprintf($user->lang['SETTING_TOO_SHORT'], $user->lang[$config_definition['lang']], $validator[$min]);
590                }
591                else if (isset($validator[$max]) && $length > $validator[2])
592                {
593                    $error[] = sprintf($user->lang['SETTING_TOO_LONG'], $user->lang[$config_definition['lang']], $validator[$max]);
594                }
595            break;
596
597            case 'bool':
598                $cfg_array[$config_name] = ($cfg_array[$config_name]) ? 1 : 0;
599            break;
600
601            case 'int':
602                $cfg_array[$config_name] = (int) $cfg_array[$config_name];
603
604                if (isset($validator[$min]) && $cfg_array[$config_name] < $validator[$min])
605                {
606                    $error[] = sprintf($user->lang['SETTING_TOO_LOW'], $user->lang[$config_definition['lang']], $validator[$min]);
607                }
608                else if (isset($validator[$max]) && $cfg_array[$config_name] > $validator[$max])
609                {
610                    $error[] = sprintf($user->lang['SETTING_TOO_BIG'], $user->lang[$config_definition['lang']], $validator[$max]);
611                }
612
613                if (strpos($config_name, '_max') !== false)
614                {
615                    // Min/max pairs of settings should ensure that min <= max
616                    // Replace _max with _min to find the name of the minimum
617                    // corresponding configuration variable
618                    $min_name = str_replace('_max', '_min', $config_name);
619
620                    if (isset($cfg_array[$min_name]) && is_numeric($cfg_array[$min_name]) && $cfg_array[$config_name] < $cfg_array[$min_name])
621                    {
622                        // A minimum value exists and the maximum value is less than it
623                        $error[] = sprintf($user->lang['SETTING_TOO_LOW'], $user->lang[$config_definition['lang']], (int) $cfg_array[$min_name]);
624                    }
625                }
626            break;
627
628            case 'email':
629                if (!preg_match('/^' . get_preg_expression('email') . '$/i', $cfg_array[$config_name]))
630                {
631                    $error[] = $user->lang['EMAIL_INVALID_EMAIL'];
632                }
633            break;
634
635            // Absolute path
636            case 'script_path':
637                if (!$cfg_array[$config_name])
638                {
639                    break;
640                }
641
642                $destination = str_replace('\\', '/', $cfg_array[$config_name]);
643
644                if ($destination !== '/')
645                {
646                    // Adjust destination path (no trailing slash)
647                    if (substr($destination, -1, 1) == '/')
648                    {
649                        $destination = substr($destination, 0, -1);
650                    }
651
652                    $destination = str_replace(array('../', './'), '', $destination);
653
654                    if ($destination[0] != '/')
655                    {
656                        $destination = '/' . $destination;
657                    }
658                }
659
660                $cfg_array[$config_name] = trim($destination);
661
662            break;
663
664            // Absolute path
665            case 'lang':
666                if (!$cfg_array[$config_name])
667                {
668                    break;
669                }
670
671                $cfg_array[$config_name] = basename($cfg_array[$config_name]);
672
673                if (!file_exists($phpbb_root_path . 'language/' . $cfg_array[$config_name] . '/'))
674                {
675                    $error[] = $user->lang['WRONG_DATA_LANG'];
676                }
677            break;
678
679            // Relative path (appended $phpbb_root_path)
680            case 'rpath':
681            case 'rwpath':
682                if (!$cfg_array[$config_name])
683                {
684                    break;
685                }
686
687                $destination = $cfg_array[$config_name];
688
689                // Adjust destination path (no trailing slash)
690                if (substr($destination, -1, 1) == '/' || substr($destination, -1, 1) == '\\')
691                {
692                    $destination = substr($destination, 0, -1);
693                }
694
695                $destination = str_replace(array('../', '..\\', './', '.\\'), '', $destination);
696                if ($destination && ($destination[0] == '/' || $destination[0] == "\\"))
697                {
698                    $destination = '';
699                }
700
701                $cfg_array[$config_name] = trim($destination);
702
703            // Path being relative (still prefixed by phpbb_root_path), but with the ability to escape the root dir...
704            case 'path':
705            case 'wpath':
706
707                if (!$cfg_array[$config_name])
708                {
709                    break;
710                }
711
712                $cfg_array[$config_name] = trim($cfg_array[$config_name]);
713
714                // Make sure no NUL byte is present...
715                if (strpos($cfg_array[$config_name], "\0") !== false || strpos($cfg_array[$config_name], '%00') !== false)
716                {
717                    $cfg_array[$config_name] = '';
718                    break;
719                }
720
721                $path = $phpbb_root_path . $cfg_array[$config_name];
722
723                if (!file_exists($path))
724                {
725                    $error[] = sprintf($user->lang['DIRECTORY_DOES_NOT_EXIST'], $cfg_array[$config_name]);
726                }
727
728                if (file_exists($path) && !is_dir($path))
729                {
730                    $error[] = sprintf($user->lang['DIRECTORY_NOT_DIR'], $cfg_array[$config_name]);
731                }
732
733                // Check if the path is writable
734                if ($config_definition['validate'] == 'wpath' || $config_definition['validate'] == 'rwpath')
735                {
736                    if (file_exists($path) && !$phpbb_filesystem->is_writable($path))
737                    {
738                        $error[] = sprintf($user->lang['DIRECTORY_NOT_WRITABLE'], $cfg_array[$config_name]);
739                    }
740                }
741
742            break;
743
744            default:
745                /**
746                * Validate a config value
747                *
748                * @event core.validate_config_variable
749                * @var    array    cfg_array    Array with config values
750                * @var    string    config_name    Name of the config we validate
751                * @var    array    config_definition    Array with the options for
752                *                                    this config
753                * @var    array    error        Array of errors, the errors should
754                *                            be strings only, language keys are
755                *                            not replaced afterwards
756                * @since 3.1.0-a1
757                */
758                $vars = array('cfg_array', 'config_name', 'config_definition', 'error');
759                extract($phpbb_dispatcher->trigger_event('core.validate_config_variable', compact($vars)));
760            break;
761        }
762    }
763
764    return;
765}
766
767/**
768* Checks whatever or not a variable is OK for use in the Database
769* param mixed $value_ary An array of the form array(array('lang' => ..., 'value' => ..., 'column_type' =>))'
770* param mixed $error The error array
771*/
772function validate_range($value_ary, &$error)
773{
774    global $user;
775
776    $column_types = array(
777        'BOOL'    => array('php_type' => 'int',         'min' => 0,                 'max' => 1),
778        'USINT'    => array('php_type' => 'int',        'min' => 0,                 'max' => 65535),
779        'UINT'    => array('php_type' => 'int',         'min' => 0,                 'max' => (int) 0x7fffffff),
780        // Do not use (int) 0x80000000 - it evaluates to different
781        // values on 32-bit and 64-bit systems.
782        // Apparently -2147483648 is a float on 32-bit systems,
783        // despite fitting in an int, thus explicit cast is needed.
784        'INT'    => array('php_type' => 'int',         'min' => (int) -2147483648,    'max' => (int) 0x7fffffff),
785        'TINT'    => array('php_type' => 'int',        'min' => -128,                'max' => 127),
786
787        'VCHAR'    => array('php_type' => 'string',     'min' => 0,                 'max' => 255),
788    );
789    foreach ($value_ary as $value)
790    {
791        $column = explode(':', $value['column_type']);
792        if (!isset($column_types[$column[0]]))
793        {
794            continue;
795        }
796        else
797        {
798            $type = $column_types[$column[0]];
799        }
800
801        switch ($type['php_type'])
802        {
803            case 'string' :
804                $max = (isset($column[1])) ? min($column[1],$type['max']) : $type['max'];
805                if (utf8_strlen($value['value']) > $max)
806                {
807                    $error[] = sprintf($user->lang['SETTING_TOO_LONG'], $user->lang[$value['lang']], $max);
808                }
809            break;
810
811            case 'int':
812                $min = (isset($column[1])) ? max($column[1],$type['min']) : $type['min'];
813                $max = (isset($column[2])) ? min($column[2],$type['max']) : $type['max'];
814                if ($value['value'] < $min)
815                {
816                    $error[] = sprintf($user->lang['SETTING_TOO_LOW'], $user->lang[$value['lang']], $min);
817                }
818                else if ($value['value'] > $max)
819                {
820                    $error[] = sprintf($user->lang['SETTING_TOO_BIG'], $user->lang[$value['lang']], $max);
821                }
822            break;
823        }
824    }
825}
826
827/**
828* Inserts new config display_vars into an exisiting display_vars array
829* at the given position.
830* Used by extensions.
831*
832* @param array $display_vars An array of existing config display vars
833* @param array $add_config_vars An array of new config display vars
834* @param array $where Where to place the new config vars,
835*              before or after an exisiting config, as an array
836*              of the form: array('after' => 'config_name') or
837*              array('before' => 'config_name').
838* @return array The array of config display vars
839*/
840function phpbb_insert_config_array($display_vars, $add_config_vars, $where)
841{
842    if (is_array($where) && array_key_exists(current($where), $display_vars))
843    {
844        $position = array_search(current($where), array_keys($display_vars)) + ((key($where) == 'before') ? 0 : 1);
845        $display_vars = array_merge(
846            array_slice($display_vars, 0, $position),
847            $add_config_vars,
848            array_slice($display_vars, $position)
849        );
850    }
851
852    return $display_vars;
853}