Passed
Push — master ( 60a772...32eaa7 )
by Michael
18:28 queued 08:27
created

xoops_header()   B

Complexity

Conditions 5
Paths 16

Size

Total Lines 53
Code Lines 39

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 39
nc 16
nop 1
dl 0
loc 53
rs 8.9848
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 *  Xoops Functions
4
 *
5
 * You may not change or alter any portion of this comment or credits
6
 * of supporting developers from this source code or any supporting source code
7
 * which is considered copyrighted (c) material of the original comment or credit authors.
8
 * This program is distributed in the hope that it will be useful,
9
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
11
 *
12
 * @copyright       (c) 2000-2016 XOOPS Project (www.xoops.org)
13
 * @license             GNU GPL 2 (https://www.gnu.org/licenses/gpl-2.0.html)
14
 * @package             kernel
15
 * @since               2.0.0
16
 */
17
18
defined('XOOPS_ROOT_PATH') || exit('Restricted access');
19
20
/** @var \XoopsNotificationHandler $notification_handler */
21
22
/**
23
 * xoops_getHandler()
24
 *
25
 * @param string $name
26
 * @param bool   $optional
27
 *
28
 * @return XoopsObjectHandler|false
29
 */
30
function xoops_getHandler($name, $optional = false)
31
{
32
    static $handlers;
33
    $class = '';
34
    $name  = strtolower(trim($name));
35
    if (!isset($handlers[$name])) {
36
        if (file_exists($hnd_file = XOOPS_ROOT_PATH . '/kernel/' . $name . '.php')) {
37
            require_once $hnd_file;
38
        }
39
        $class = 'Xoops' . ucfirst($name) . 'Handler';
40
        if (class_exists($class)) {
41
            $xoopsDB         = XoopsDatabaseFactory::getDatabaseConnection();
42
            $handlers[$name] = new $class($xoopsDB);
43
        }
44
    }
45
    if (!isset($handlers[$name])) {
46
        trigger_error('Class <strong>' . $class . '</strong> does not exist<br>Handler Name: ' . $name, $optional ? E_USER_WARNING : E_USER_ERROR);
47
    }
48
    if (isset($handlers[$name])) {
49
        return $handlers[$name];
50
    }
51
    $inst = false;
52
53
    return $inst;
54
}
55
56
/**
57
 * xoops_getModuleHandler()
58
 *
59
 * @param string $name
60
 * @param mixed  $module_dir
61
 * @param bool   $optional
62
 * @return XoopsObjectHandler|false
63
 */
64
function xoops_getModuleHandler($name = null, $module_dir = null, $optional = false)
65
{
66
    static $handlers;
67
    // if $module_dir is not specified
68
    if (!isset($module_dir)) {
69
        // if a module is loaded
70
        if (isset($GLOBALS['xoopsModule']) && is_object($GLOBALS['xoopsModule'])) {
71
            $module_dir = $GLOBALS['xoopsModule']->getVar('dirname', 'n');
72
        } else {
73
            throw new \Exception('No Module is loaded');
74
        }
75
    } else {
76
        $module_dir = trim($module_dir);
77
    }
78
    $name = (!isset($name)) ? $module_dir : trim($name);
79
    if (!isset($handlers[$module_dir][$name])) {
80
        if (file_exists($hnd_file = XOOPS_ROOT_PATH . "/modules/{$module_dir}/class/{$name}.php")) {
81
            include_once $hnd_file;
82
        }
83
        $class = ucfirst(strtolower($module_dir)) . ucfirst($name) . 'Handler';
84
        if (class_exists($class)) {
85
            $xoopsDB                      = XoopsDatabaseFactory::getDatabaseConnection();
86
            $handlers[$module_dir][$name] = new $class($xoopsDB);
87
        }
88
    }
89
    if (!isset($handlers[$module_dir][$name])) {
90
    $message = 'Handler does not exist<br>Module: ' . $module_dir . '<br>Name: ' . $name;
91
    if ($optional) {
92
        trigger_error($message, E_USER_WARNING); 
93
    } else {
94
        throw new \Exception($message); 
95
    }
96
}
97
    if (isset($handlers[$module_dir][$name])) {
98
        return $handlers[$module_dir][$name];
99
    }
100
    $inst = false;
101
102
    return $inst;
103
}
104
105
/**
106
 * XOOPS class loader wrapper
107
 *
108
 * Temporay solution for XOOPS 2.3
109
 *
110
 * @param string $name                                          Name of class to be loaded
111
 * @param string $type                                          domain of the class, potential values:   core - located in /class/;
112
 *                                                              framework - located in /Frameworks/;
113
 *                                                              other - module class, located in /modules/[$type]/class/
114
 *
115
 * @return boolean
116
 */
117
function xoops_load($name, $type = 'core')
118
{
119
    if (!class_exists('XoopsLoad')) {
120
        require_once XOOPS_ROOT_PATH . '/class/xoopsload.php';
121
    }
122
123
    return XoopsLoad::load($name, $type);
124
}
125
126
/**
127
 * XOOPS language loader wrapper
128
 *
129
 * Temporay solution, not encouraged to use
130
 *
131
 * @param   string $name     Name of language file to be loaded, without extension
132
 * @param   string $domain   Module dirname; global language file will be loaded if $domain is set to 'global' or not specified
133
 * @param   string $language Language to be loaded, current language content will be loaded if not specified
134
 * @return  boolean
135
 * @todo    expand domain to multiple categories, e.g. module:system, framework:filter, etc.
136
 *
137
 */
138
function xoops_loadLanguage($name, $domain = '', $language = null)
139
{
140
    /**
141
     * Set pageType
142
     */
143
    if ($name === 'pagetype') {
144
        $name = xoops_getOption('pagetype');
0 ignored issues
show
Deprecated Code introduced by
The function xoops_getOption() has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

144
        $name = /** @scrutinizer ignore-deprecated */ xoops_getOption('pagetype');
Loading history...
145
    }
146
    /**
147
     * We must check later for an empty value. As xoops_getOption could be empty
148
     */
149
    if (empty($name)) {
150
        return false;
151
    }
152
    //    $language = empty($language) ? $GLOBALS['xoopsConfig']['language'] : $language;
153
    global $xoopsConfig;
154
    $language = empty($language) ? $xoopsConfig['language'] : $language;
155
    $path     = ((empty($domain) || 'global' === $domain) ? '' : "modules/{$domain}/") . 'language';
156
    if (!file_exists($fileinc = $GLOBALS['xoops']->path("{$path}/{$language}/{$name}.php"))) {
157
        if (!file_exists($fileinc = $GLOBALS['xoops']->path("{$path}/english/{$name}.php"))) {
158
            return false;
159
        }
160
    }
161
    $ret = include_once $fileinc;
162
163
    return $ret;
164
}
165
166
/**
167
 * YOU SHOULD BE CAREFUL WITH USING THIS METHOD SINCE IT WILL BE DEPRECATED
168
 */
169
/**
170
 * xoops_getActiveModules()
171
 *
172
 * Get active modules from cache file
173
 *
174
 * @return array
175
 */
176
function xoops_getActiveModules()
177
{
178
    static $modules_active;
179
    if (is_array($modules_active)) {
180
        return $modules_active;
181
    }
182
    xoops_load('XoopsCache');
183
    if (!$modules_active = XoopsCache::read('system_modules_active')) {
184
        $modules_active = xoops_setActiveModules();
185
    }
186
187
    return $modules_active;
188
}
189
190
/**
191
 * YOU SHOULD BE CAREFUL WITH USING THIS METHOD SINCE IT WILL BE DEPRECATED
192
 */
193
/**
194
 * xoops_setActiveModules()
195
 *
196
 * Write active modules to cache file
197
 *
198
 * @return array
199
 */
200
function xoops_setActiveModules()
201
{
202
    xoops_load('XoopsCache');
203
    /** @var XoopsModuleHandler $module_handler */
204
    $module_handler = xoops_getHandler('module');
205
    $modules_obj    = $module_handler->getObjects(new Criteria('isactive', 1));
206
    $modules_active = [];
207
    foreach (array_keys($modules_obj) as $key) {
208
        $modules_active[] = $modules_obj[$key]->getVar('dirname');
209
    }
210
    unset($modules_obj);
211
    XoopsCache::write('system_modules_active', $modules_active);
212
213
    return $modules_active;
214
}
215
216
/**
217
 * YOU SHOULD BE CAREFUL WITH USING THIS METHOD SINCE IT WILL BE DEPRECATED
218
 */
219
/**
220
 * xoops_isActiveModule()
221
 *
222
 * Checks is module is installed and active
223
 *
224
 * @param $dirname
225
 * @return bool
226
 */
227
function xoops_isActiveModule($dirname)
228
{
229
    return isset($dirname) && in_array($dirname, xoops_getActiveModules());
230
}
231
232
/**
233
 * xoops_header()
234
 *
235
 * @param mixed $closehead
236
 * @return void
237
 */
238
function xoops_header($closehead = true)
239
{
240
    global $xoopsConfig;
241
242
    $themeSet = $xoopsConfig['theme_set'];
243
    $themePath = XOOPS_THEME_PATH . '/' . $themeSet . '/';
244
    $themeUrl = XOOPS_THEME_URL . '/' . $themeSet . '/';
245
    include_once XOOPS_ROOT_PATH . '/class/template.php';
246
    $headTpl = new \XoopsTpl();
247
    $GLOBALS['xoopsHeadTpl'] = $headTpl;  // expose template for use by caller
248
    $headTpl->assign(
249
        [
250
            'closeHead'      => (bool) $closehead,
251
            'themeUrl'       => $themeUrl,
252
            'themePath'      => $themePath,
253
            'xoops_langcode' => _LANGCODE,
254
            'xoops_charset'  => _CHARSET,
255
            'xoops_sitename' => $xoopsConfig['sitename'],
256
            'xoops_url'      => XOOPS_URL,
257
        ],
258
    );
259
260
    if (file_exists($themePath . 'theme_autorun.php')) {
261
        include_once($themePath . 'theme_autorun.php');
262
    }
263
264
    $headItems = [];
265
    $headItems[] = '<script type="text/javascript" src="' . XOOPS_URL . '/include/xoops.js"></script>';
266
    $headItems[] = '<link rel="stylesheet" type="text/css" media="all" href="' . XOOPS_URL . '/xoops.css">';
267
    $headItems[] = '<link rel="stylesheet" type="text/css" media="all"  as="font" crossorigin="anonymous" href="' . XOOPS_URL . '/media/font-awesome6/css/fontawesome.min.css">';
268
    $headItems[] = '<link rel="stylesheet" type="text/css" media="all"  as="font" crossorigin="anonymous" href="' . XOOPS_URL . '/media/font-awesome6/css/solid.min.css">';
269
    $headItems[] = '<link rel="stylesheet" type="text/css" media="all"  as="font" crossorigin="anonymous" href="' . XOOPS_URL . '/media/font-awesome6/css/brands.min.css">';
270
    $headItems[] = '<link rel="stylesheet" type="text/css" media="all"  as="font" crossorigin="anonymous" href="' . XOOPS_URL . '/media/font-awesome6/css/v4-shims.min.css">';
271
    $languageFile = 'language/' . $GLOBALS['xoopsConfig']['language'] . '/style.css';
272
    if (file_exists($GLOBALS['xoops']->path($languageFile))) {
273
        $headItems[] = '<link rel="stylesheet" type="text/css" media="all" href="' . $GLOBALS['xoops']->url($languageFile) . '">';
274
    }
275
    $themecss = xoops_getcss($xoopsConfig['theme_set']);
276
    if ($themecss !== '') {
277
        $headItems[] = '<link rel="stylesheet" type="text/css" media="all" href="' . $themecss . '">';
278
    }
279
    $headTpl->assign('headItems', $headItems);
280
281
    if (!headers_sent()) {
282
        header('Content-Type:text/html; charset=' . _CHARSET);
283
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
284
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
285
        header('Cache-Control: no-store, no-cache, max-age=1, s-maxage=1, must-revalidate, post-check=0, pre-check=0');
286
        header('Pragma: no-cache');
287
    }
288
289
    $output = $headTpl->fetch('db:system_popup_header.tpl');
290
    echo $output;
291
}
292
293
/**
294
 * xoops_footer
295
 *
296
 * @return void
297
 */
298
function xoops_footer()
299
{
300
    global $xoopsConfig;
301
302
    $themeSet = $xoopsConfig['theme_set'];
303
    $themePath = XOOPS_THEME_URL . '/' . $themeSet . '/';
304
    include_once XOOPS_ROOT_PATH . '/class/template.php';
305
    $footTpl = new \XoopsTpl();
306
    $footTpl->assign(
307
        [
308
            'themePath'      => $themePath,
309
            'xoops_langcode' => _LANGCODE,
310
            'xoops_charset'  => _CHARSET,
311
            'xoops_sitename' => $xoopsConfig['sitename'],
312
            'xoops_url'      => XOOPS_URL,
313
        ],
314
    );
315
    $output = $footTpl->fetch('db:system_popup_footer.tpl');
316
    echo $output;
317
    ob_end_flush();
318
}
319
320
/**
321
 * xoops_error
322
 *
323
 * @param mixed  $msg
324
 * @param string $title
325
 * @return void
326
 */
327
function xoops_error($msg, $title = '')
328
{
329
    echo '<div class="errorMsg">';
330
    if ($title != '') {
331
        echo '<strong>' . $title . '</strong><br><br>';
332
    }
333
    if (is_object($msg)) {
334
        $msg = (array) $msg;
335
    }
336
    if (is_array($msg)) {
337
        foreach ($msg as $key => $value) {
338
            if (is_numeric($key)) {
339
                $key = '';
340
            }
341
            xoops_error($value, $key);
342
        }
343
    } else {
344
        echo "<div>{$msg}</div>";
345
    }
346
    echo '</div>';
347
}
348
349
/**
350
 * xoops_warning
351
 *
352
 * @param mixed  $msg
353
 * @param string $title
354
 * @return void
355
 */
356
function xoops_warning($msg, $title = '')
357
{
358
    echo '<div class="warningMsg">';
359
    if ($title != '') {
360
        echo '<strong>' . $title . '</strong><br><br>';
361
    }
362
    if (is_object($msg)) {
363
        $msg = (array) $msg;
364
    }
365
    if (is_array($msg)) {
366
        foreach ($msg as $key => $value) {
367
            if (is_numeric($key)) {
368
                $key = '';
369
            }
370
            xoops_warning($value, $key);
371
        }
372
    } else {
373
        echo "<div>{$msg}</div>";
374
    }
375
    echo '</div>';
376
}
377
378
/**
379
 * xoops_result
380
 *
381
 * @param mixed  $msg
382
 * @param string $title
383
 * @return void
384
 */
385
function xoops_result($msg, $title = '')
386
{
387
    echo '<div class="resultMsg">';
388
    if ($title != '') {
389
        echo '<strong>' . $title . '</strong><br><br>';
390
    }
391
    if (is_object($msg)) {
392
        $msg = (array) $msg;
393
    }
394
    if (is_array($msg)) {
395
        foreach ($msg as $key => $value) {
396
            if (is_numeric($key)) {
397
                $key = '';
398
            }
399
            xoops_result($value, $key);
400
        }
401
    } else {
402
        echo "<div>{$msg}</div>";
403
    }
404
    echo '</div>';
405
}
406
407
/**
408
 * xoops_confirm()
409
 *
410
 * @param mixed  $hiddens
411
 * @param mixed  $action
412
 * @param mixed  $msg
413
 * @param string $submit
414
 * @param mixed  $addtoken
415
 * @return void
416
 */
417
function xoops_confirm($hiddens, $action, $msg, $submit = '', $addtoken = true)
418
{
419
    if (!isset($GLOBALS['xoTheme']) || !is_object($GLOBALS['xoTheme'])) {
420
        include_once $GLOBALS['xoops']->path('/class/theme.php');
421
        $GLOBALS['xoTheme'] = new \xos_opal_Theme();
422
    }
423
    require_once $GLOBALS['xoops']->path('/class/template.php');
424
    $confirmTpl = new \XoopsTpl();
425
    $confirmTpl->assign('msg', $msg);
426
    $confirmTpl->assign('action', $action);
427
    $tempHiddens = '';
428
    foreach ($hiddens as $name => $value) {
429
        if (is_array($value)) {
430
            foreach ($value as $caption => $newvalue) {
431
                $tempHiddens .= '<input type="radio" name="' . $name . '" value="' . htmlspecialchars($newvalue, ENT_QUOTES | ENT_HTML5) . '" /> ' . $caption;
432
            }
433
            $tempHiddens .= '<br>';
434
        } else {
435
            $tempHiddens .= '<input type="hidden" name="' . $name . '" value="' . htmlspecialchars($value, ENT_QUOTES | ENT_HTML5) . '" />';
436
        }
437
    }
438
    $confirmTpl->assign('hiddens', $tempHiddens);
439
    $confirmTpl->assign('addtoken', $addtoken);
440
    if ($addtoken != false) {
441
        $confirmTpl->assign('token', $GLOBALS['xoopsSecurity']->getTokenHTML());
442
    }
443
    $submit = ($submit != '') ? trim($submit) : _SUBMIT;
444
    $confirmTpl->assign('submit', $submit);
445
    $html = $confirmTpl->fetch("db:system_confirm.tpl");
446
    if (!empty($html)) {
447
        echo $html;
448
    } else {
449
        $submit = ($submit != '') ? trim($submit) : _SUBMIT;
450
        echo '<div class="confirmMsg">' . $msg . '<br>
451
			  <form method="post" action="' . $action . '">';
452
        foreach ($hiddens as $name => $value) {
453
            if (is_array($value)) {
454
                foreach ($value as $caption => $newvalue) {
455
                    echo '<input type="radio" name="' . $name . '" value="' . htmlspecialchars($newvalue, ENT_QUOTES | ENT_HTML5) . '" /> ' . $caption;
456
                }
457
                echo '<br>';
458
            } else {
459
                echo '<input type="hidden" name="' . $name . '" value="' . htmlspecialchars($value, ENT_QUOTES | ENT_HTML5) . '" />';
460
            }
461
        }
462
        if ($addtoken != false) {
463
            echo $GLOBALS['xoopsSecurity']->getTokenHTML();
464
        }
465
        // TODO - these buttons should go through formRenderer
466
        echo '<input type="submit" class="btn btn-default btn-secondary" name="confirm_submit" value="' . $submit . '" title="' . $submit . '"/>
467
			  <input type="button" class="btn btn-default btn-secondary" name="confirm_back" value="' . _CANCEL . '" onclick="history.go(-1);" title="' . _CANCEL . '" />
468
			  </form>
469
			  </div>';
470
    }
471
}
472
473
/**
474
 * xoops_getUserTimestamp()
475
 *
476
 * @param mixed  $time
477
 * @param string $timeoffset
478
 * @return int
479
 */
480
function xoops_getUserTimestamp($time, $timeoffset = '')
481
{
482
    global $xoopsConfig, $xoopsUser;
483
    if ($timeoffset == '') {
484
        if ($xoopsUser) {
485
            $timeoffset = $xoopsUser->getVar('timezone_offset');
486
        } else {
487
            $timeoffset = $xoopsConfig['default_TZ'];
488
        }
489
    }
490
    $usertimestamp = (int) $time + ((float) $timeoffset - $xoopsConfig['server_TZ']) * 3600;
491
492
    return (int) $usertimestamp;
493
}
494
495
/**
496
 * Function to display formatted times in user timezone
497
 * @param        $time
498
 * @param string $format
499
 * @param string $timeoffset
500
 * @return string
501
 */
502
function formatTimestamp($time, $format = 'l', $timeoffset = '')
503
{
504
    xoops_load('XoopsLocal');
505
506
    return XoopsLocal::formatTimestamp($time, $format, $timeoffset);
507
}
508
509
/**
510
 * Function to calculate server timestamp from user entered time (timestamp)
511
 * @param      $timestamp
512
 * @param null $userTZ
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $userTZ is correct as it would always require null to be passed?
Loading history...
513
 * @return
514
 */
515
function userTimeToServerTime($timestamp, $userTZ = null)
516
{
517
    global $xoopsConfig;
518
    if (!isset($userTZ)) {
519
        $userTZ = $xoopsConfig['default_TZ'];
520
    }
521
    $timestamp -= (($userTZ - $xoopsConfig['server_TZ']) * 3600);
522
523
    return $timestamp;
524
}
525
526
/**
527
 * xoops_makepass()
528
 *
529
 * @return string
530
 */
531
function xoops_makepass()
532
{
533
    $makepass  = '';
534
    $syllables = [
535
        'er',
536
        'in',
537
        'tia',
538
        'wol',
539
        'fe',
540
        'pre',
541
        'vet',
542
        'jo',
543
        'nes',
544
        'al',
545
        'len',
546
        'son',
547
        'cha',
548
        'ir',
549
        'ler',
550
        'bo',
551
        'ok',
552
        'tio',
553
        'nar',
554
        'sim',
555
        'ple',
556
        'bla',
557
        'ten',
558
        'toe',
559
        'cho',
560
        'co',
561
        'lat',
562
        'spe',
563
        'ak',
564
        'er',
565
        'po',
566
        'co',
567
        'lor',
568
        'pen',
569
        'cil',
570
        'li',
571
        'ght',
572
        'wh',
573
        'at',
574
        'the',
575
        'he',
576
        'ck',
577
        'is',
578
        'mam',
579
        'bo',
580
        'no',
581
        'fi',
582
        've',
583
        'any',
584
        'way',
585
        'pol',
586
        'iti',
587
        'cs',
588
        'ra',
589
        'dio',
590
        'sou',
591
        'rce',
592
        'sea',
593
        'rch',
594
        'pa',
595
        'per',
596
        'com',
597
        'bo',
598
        'sp',
599
        'eak',
600
        'st',
601
        'fi',
602
        'rst',
603
        'gr',
604
        'oup',
605
        'boy',
606
        'ea',
607
        'gle',
608
        'tr',
609
        'ail',
610
        'bi',
611
        'ble',
612
        'brb',
613
        'pri',
614
        'dee',
615
        'kay',
616
        'en',
617
        'be',
618
        'se',
619
    ];
620
    for ($count = 1; $count <= 4; ++$count) {
621
        if (mt_rand() % 10 == 1) {
622
            $makepass .= sprintf('%0.0f', (mt_rand() % 50) + 1);
623
        } else {
624
            $makepass .= sprintf('%s', $syllables[mt_rand() % 62]);
625
        }
626
    }
627
628
    return $makepass;
629
}
630
631
/**
632
 * checkEmail()
633
 *
634
 * @param mixed $email
635
 * @param mixed $antispam
636
 * @return bool|mixed
637
 */
638
function checkEmail($email, $antispam = false)
639
{
640
    if (!$email || !preg_match('/^[^@]{1,64}@[^@]{1,255}$/', $email)) {
641
        return false;
642
    }
643
    $email_array      = explode('@', $email);
644
    $local_array      = explode('.', $email_array[0]);
645
    $local_arrayCount = count($local_array);
646
    for ($i = 0; $i < $local_arrayCount; ++$i) {
647
        if (!preg_match("/^(([A-Za-z0-9!#$%&'*+\/\=?^_`{|}~-][A-Za-z0-9!#$%&'*+\/\=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$/", $local_array[$i])) {
648
            return false;
649
        }
650
    }
651
    if (!preg_match("/^\[?[0-9\.]+\]?$/", $email_array[1])) {
652
        $domain_array = explode('.', $email_array[1]);
653
        if (count($domain_array) < 2) {
654
            return false; // Not enough parts to domain
655
        }
656
        for ($i = 0, $iMax = count($domain_array); $i < $iMax; ++$i) {
657
            if (!preg_match("/^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$/", $domain_array[$i])) {
658
                return false;
659
            }
660
        }
661
    }
662
    if ($antispam) {
663
        $email = str_replace('@', ' at ', $email);
664
        $email = str_replace('.', ' dot ', $email);
665
    }
666
667
    return $email;
668
}
669
670
/**
671
 * formatURL()
672
 *
673
 * @param mixed $url
674
 * @return mixed|string
675
 */
676
function formatURL($url)
677
{
678
    $url = trim($url);
679
    if ($url != '') {
680
        if ((!preg_match('/^http[s]*:\/\//i', $url)) && (!preg_match('/^ftp*:\/\//i', $url)) && (!preg_match('/^ed2k*:\/\//i', $url))) {
681
            $url = 'http://' . $url;
682
        }
683
    }
684
685
    return $url;
686
}
687
688
/**
689
 * Function to get banner html tags for use in templates
690
 */
691
function xoops_getbanner()
692
{
693
    global $xoopsConfig;
694
695
    $db      = XoopsDatabaseFactory::getDatabaseConnection();
696
    $sql = 'SELECT COUNT(*) FROM ' . $db->prefix('banner');
697
    $result = $db->query($sql);
0 ignored issues
show
Bug introduced by
The method query() does not exist on XoopsDatabase. Since it exists in all sub-types, consider adding an abstract or default implementation to XoopsDatabase. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

697
    /** @scrutinizer ignore-call */ 
698
    $result = $db->query($sql);
Loading history...
698
    if (!$db->isResultSet($result)) {
699
        throw new \RuntimeException(
700
            \sprintf(_DB_QUERY_ERROR, $sql) . $db->error(),
0 ignored issues
show
Bug introduced by
The method error() does not exist on XoopsDatabase. Since it exists in all sub-types, consider adding an abstract or default implementation to XoopsDatabase. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

700
            \sprintf(_DB_QUERY_ERROR, $sql) . $db->/** @scrutinizer ignore-call */ error(),
Loading history...
701
            E_USER_ERROR,
702
        );
703
    }
704
    [$numrows] = $db->fetchRow($result);
0 ignored issues
show
Bug introduced by
The method fetchRow() does not exist on XoopsDatabase. Since it exists in all sub-types, consider adding an abstract or default implementation to XoopsDatabase. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

704
    /** @scrutinizer ignore-call */ 
705
    [$numrows] = $db->fetchRow($result);
Loading history...
705
    if ($numrows > 1) {
706
        --$numrows;
707
        $bannum = mt_rand(0, $numrows);
708
    } else {
709
        $bannum = 0;
710
    }
711
    if ($numrows > 0) {
712
        $sql = 'SELECT * FROM ' . $db->prefix('banner');
713
        $result = $db->query($sql, 1, $bannum);
714
        if (!$db->isResultSet($result)) {
715
            throw new \RuntimeException(
716
                \sprintf(_DB_QUERY_ERROR, $sql) . $db->error(),
717
                E_USER_ERROR,
718
            );
719
        }
720
        [$bid, $cid, $imptotal, $impmade, $clicks, $imageurl, $clickurl, $date, $htmlbanner, $htmlcode] = $db->fetchRow($result);
721
        if ($xoopsConfig['my_ip'] == xoops_getenv('REMOTE_ADDR')) {
722
            // EMPTY
723
        } else {
724
            ++$impmade;
725
            $sql = sprintf('UPDATE %s SET impmade = %u WHERE bid = %u', $db->prefix('banner'), $impmade, $bid);
726
            $db->queryF($sql);
0 ignored issues
show
Bug introduced by
The method queryF() does not exist on XoopsDatabase. Since it exists in all sub-types, consider adding an abstract or default implementation to XoopsDatabase. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

726
            $db->/** @scrutinizer ignore-call */ 
727
                 queryF($sql);
Loading history...
727
            /**
728
             * Check if this impression is the last one
729
             */
730
            if ($imptotal > 0 && $impmade >= $imptotal) {
731
                $newid = $db->genId($db->prefix('bannerfinish') . '_bid_seq');
0 ignored issues
show
Bug introduced by
The method genId() does not exist on XoopsDatabase. Since it exists in all sub-types, consider adding an abstract or default implementation to XoopsDatabase. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

731
                /** @scrutinizer ignore-call */ 
732
                $newid = $db->genId($db->prefix('bannerfinish') . '_bid_seq');
Loading history...
732
                $sql   = sprintf('INSERT INTO %s (bid, cid, impressions, clicks, datestart, dateend) VALUES (%u, %u, %u, %u, %u, %u)', $db->prefix('bannerfinish'), $newid, $cid, $impmade, $clicks, $date, time());
733
                $db->queryF($sql);
734
                $db->queryF(sprintf('DELETE FROM %s WHERE bid = %u', $db->prefix('banner'), $bid));
735
            }
736
        }
737
        /**
738
         * Print the banner
739
         */
740
        $bannerobject = '';
741
        if ($htmlbanner) {
742
            if ($htmlcode) {
743
                $bannerobject = $htmlcode;
744
            } else {
745
                $bannerobject = $bannerobject . '<div id="xo-bannerfix">';
746
                // $bannerobject = $bannerobject . '<div id="xo-fixbanner">';
747
                $bannerobject = $bannerobject . ' <iframe src=' . $imageurl . ' border="0" scrolling="no" allowtransparency="true" width="480px" height="60px" style="border:0" alt="' . $clickurl . ';"> </iframe>';
748
                $bannerobject .= '</div>';
749
                // $bannerobject .= '</div>';
750
            }
751
        } else {
752
            $bannerobject = '<div id="xo-bannerfix">';
753
            if (false !== stripos($imageurl, '.swf')) {
754
                $bannerobject = $bannerobject . '<div id ="xo-fixbanner">' . '<a href="' . XOOPS_URL . '/banners.php?op=click&amp;bid=' . $bid . '" rel="external" title="' . $clickurl . '"></a></div>' . '<object type="application/x-shockwave-flash" width="468" height="60" data="' . $imageurl . '" style="z-index:100;">' . '<param name="movie" value="' . $imageurl . '" />' . '<param name="wmode" value="opaque" />' . '</object>';
755
            } else {
756
                $bannerobject = $bannerobject . '<a href="' . XOOPS_URL . '/banners.php?op=click&amp;bid=' . $bid . '" rel="external" title="' . $clickurl . '"><img src="' . $imageurl . '" alt="' . $clickurl . '" /></a>';
757
            }
758
759
            $bannerobject .= '</div>';
760
        }
761
762
        return $bannerobject;
763
    }
764
    return null;
765
}
766
767
/**
768
 * Function to redirect a user to certain pages
769
 * @param        $url
770
 * @param int    $time
771
 * @param string $message
772
 * @param bool   $addredirect
773
 * @param bool   $allowExternalLink
774
 */
775
function redirect_header($url, $time = 3, $message = '', $addredirect = true, $allowExternalLink = false)
776
{
777
    global $xoopsConfig, $xoopsLogger, $xoopsUserIsAdmin;
778
779
    $xoopsPreload = XoopsPreload::getInstance();
780
    $xoopsPreload->triggerEvent('core.include.functions.redirectheader.start', [$url, $time, $message, $addredirect, $allowExternalLink]);
781
    // under normal circumstance this event will exit, so listen for the .start above
782
    $xoopsPreload->triggerEvent('core.include.functions.redirectheader', [$url, $time, $message, $addredirect, $allowExternalLink]);
783
784
    if (preg_match("/[\\0-\\31]|about:|script:/i", $url)) {
785
        if (!preg_match('/^\b(java)?script:([\s]*)history\.go\(-\d*\)([\s]*[;]*[\s]*)$/si', $url)) {
786
            $url = XOOPS_URL;
787
        }
788
    }
789
    if (!$allowExternalLink && $pos = strpos($url, '://')) {
790
        $xoopsLocation = substr(XOOPS_URL, strpos(XOOPS_URL, '://') + 3);
791
        if (strcasecmp(substr($url, $pos + 3, strlen($xoopsLocation)), $xoopsLocation)) {
792
            $url = XOOPS_URL;
793
        }
794
    }
795
    if (defined('XOOPS_CPFUNC_LOADED')) {
796
        $theme = 'default';
797
    } else {
798
        $theme = $xoopsConfig['theme_set'];
799
    }
800
801
    require_once XOOPS_ROOT_PATH . '/class/template.php';
802
    require_once XOOPS_ROOT_PATH . '/class/theme.php';
803
    $xoopsThemeFactory                = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $xoopsThemeFactory is dead and can be removed.
Loading history...
804
    $xoopsThemeFactory                = new xos_opal_ThemeFactory();
805
    $xoopsThemeFactory->allowedThemes = $xoopsConfig['theme_set_allowed'];
806
    $xoopsThemeFactory->defaultTheme  = $theme;
807
    $xoTheme                          = $xoopsThemeFactory->createInstance(
808
        [
809
            'plugins'      => [],
810
            'renderBanner' => false,
811
        ],
812
    );
813
    $xoopsTpl                         = $xoTheme->template;
814
    $xoopsTpl->assign(
815
        [
816
            'xoops_theme'      => $theme,
817
            'xoops_imageurl'   => XOOPS_THEME_URL . '/' . $theme . '/',
818
            'xoops_themecss'   => xoops_getcss($theme),
819
            'xoops_requesturi' => htmlspecialchars($_SERVER['REQUEST_URI'], ENT_QUOTES | ENT_HTML5),
820
            'xoops_sitename'   => htmlspecialchars($xoopsConfig['sitename'], ENT_QUOTES | ENT_HTML5),
821
            'xoops_slogan'     => htmlspecialchars($xoopsConfig['slogan'], ENT_QUOTES | ENT_HTML5),
822
            'xoops_dirname'    => isset($xoopsModule) && is_object($xoopsModule) ? $xoopsModule->getVar('dirname') : 'system',
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $xoopsModule seems to never exist and therefore isset should always be false.
Loading history...
823
            'xoops_pagetitle'  => isset($xoopsModule) && is_object($xoopsModule) ? $xoopsModule->getVar('name') : htmlspecialchars($xoopsConfig['slogan'], ENT_QUOTES | ENT_HTML5),
824
        ],
825
    );
826
    if ($xoopsConfig['debug_mode'] == 2 && $xoopsUserIsAdmin) {
827
        $xoopsTpl->assign('time', 300);
828
        $xoopsTpl->assign('xoops_logdump', $xoopsLogger->dump());
829
    } else {
830
        $xoopsTpl->assign('time', (int) $time);
831
    }
832
    if (!empty($_SERVER['REQUEST_URI']) && $addredirect && false !== strpos($url, 'user.php')) {
833
        if (false === strpos($url, '?')) {
834
            $url .= '?xoops_redirect=' . urlencode($_SERVER['REQUEST_URI']);
835
        } else {
836
            $url .= '&amp;xoops_redirect=' . urlencode($_SERVER['REQUEST_URI']);
837
        }
838
    }
839
    if (defined('SID') && SID && (!isset($_COOKIE[session_name()]) || ($xoopsConfig['use_mysession'] && $xoopsConfig['session_name'] != '' && !isset($_COOKIE[$xoopsConfig['session_name']])))) {
840
        if (false === strpos($url, '?')) {
841
            $url .= '?' . SID;
842
        } else {
843
            $url .= '&amp;' . SID;
844
        }
845
    }
846
    $url = preg_replace('/&amp;/i', '&', htmlspecialchars($url, ENT_QUOTES | ENT_HTML5));
847
    $xoopsTpl->assign('url', $url);
848
    $message = trim($message) != '' ? $message : _TAKINGBACK;
849
    $xoopsTpl->assign('message', $message);
850
    $xoopsTpl->assign('lang_ifnotreload', sprintf(_IFNOTRELOAD, $url));
851
852
    $xoopsTpl->display('db:system_redirect.tpl');
853
    exit();
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
854
}
855
856
/**
857
 * xoops_getenv()
858
 *
859
 * @param mixed $key
860
 * @return string
861
 */
862
function xoops_getenv($key)
863
{
864
    $ret = '';
865
    if (array_key_exists($key, $_SERVER) && isset($_SERVER[$key])) {
866
        $ret = $_SERVER[$key];
867
868
        return $ret;
869
    }
870
    if (array_key_exists($key, $_ENV) && isset($_ENV[$key])) {
871
        $ret = $_ENV[$key];
872
873
        return $ret;
874
    }
875
876
    return $ret;
877
}
878
879
/**
880
 * Function to get css file for a certain themeset
881
 * @param string $theme
882
 * @return string
883
 */
884
function xoops_getcss($theme = '')
885
{
886
    if ($theme == '') {
887
        $theme = $GLOBALS['xoopsConfig']['theme_set'];
888
    }
889
    $uagent  = xoops_getenv('HTTP_USER_AGENT');
890
    $str_css = 'styleNN.css';
891
    if (false !== stripos($uagent, 'mac')) {
892
        $str_css = 'styleMAC.css';
893
    } elseif (preg_match("/MSIE (\d\.\d{1,2})/i", $uagent)) {
894
        $str_css = 'style.css';
895
    }
896
    if (is_dir(XOOPS_THEME_PATH . '/' . $theme)) {
897
        if (file_exists(XOOPS_THEME_PATH . '/' . $theme . '/' . $str_css)) {
898
            return XOOPS_THEME_URL . '/' . $theme . '/' . $str_css;
899
        } elseif (file_exists(XOOPS_THEME_PATH . '/' . $theme . '/style.css')) {
900
            return XOOPS_THEME_URL . '/' . $theme . '/style.css';
901
        }
902
    }
903
    if (is_dir(XOOPS_THEME_PATH . '/' . $theme . '/css')) {
904
        if (file_exists(XOOPS_THEME_PATH . '/' . $theme . '/css/' . $str_css)) {
905
            return XOOPS_THEME_URL . '/' . $theme . '/css/' . $str_css;
906
        } elseif (file_exists(XOOPS_THEME_PATH . '/' . $theme . '/css/style.css')) {
907
            return XOOPS_THEME_URL . '/' . $theme . '/css/style.css';
908
        }
909
    }
910
911
    return '';
912
}
913
914
/**
915
 * xoops_getMailer()
916
 *
917
 * @return \XoopsMailer|\XoopsMailerLocal
918
 */
919
function xoops_getMailer()
920
{
921
    static $mailer;
922
    global $xoopsConfig;
923
    if (is_object($mailer)) {
924
        return $mailer;
925
    }
926
    include_once XOOPS_ROOT_PATH . '/class/xoopsmailer.php';
927
    if (file_exists($file = XOOPS_ROOT_PATH . '/language/' . $xoopsConfig['language'] . '/xoopsmailerlocal.php')) {
928
        include_once $file;
929
    } elseif (file_exists($file = XOOPS_ROOT_PATH . '/language/english/xoopsmailerlocal.php')) {
930
        include_once $file;
931
    }
932
    unset($mailer);
933
    if (class_exists('XoopsMailerLocal')) {
934
        $mailer = new XoopsMailerLocal();
935
    } else {
936
        $mailer = new XoopsMailer();
937
    }
938
939
    return $mailer;
940
}
941
942
/**
943
 * xoops_getrank()
944
 *
945
 * @param integer $rank_id
946
 * @param mixed   $posts
947
 * @return
948
 */
949
function xoops_getrank($rank_id = 0, $posts = 0)
950
{
951
    $db      = XoopsDatabaseFactory::getDatabaseConnection();
952
    $myts    = \MyTextSanitizer::getInstance();
953
    $rank_id = (int) $rank_id;
954
    $posts   = (int) $posts;
955
    if ($rank_id != 0) {
956
        $sql = 'SELECT rank_title AS title, rank_image AS image FROM ' . $db->prefix('ranks') . ' WHERE rank_id = ' . $rank_id;
957
    } else {
958
        $sql = 'SELECT rank_title AS title, rank_image AS image FROM ' . $db->prefix('ranks') . ' WHERE rank_min <= ' . $posts . ' AND rank_max >= ' . $posts . ' AND rank_special = 0';
959
    }
960
    $result = $db->query($sql);
961
    if (!$db->isResultSet($result)) {
962
        throw new \RuntimeException(
963
            \sprintf(_DB_QUERY_ERROR, $sql) . $db->error(),
964
            E_USER_ERROR,
965
        );
966
    }
967
    $rank          = $db->fetchArray($result);
0 ignored issues
show
Bug introduced by
The method fetchArray() does not exist on XoopsDatabase. Since it exists in all sub-types, consider adding an abstract or default implementation to XoopsDatabase. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

967
    /** @scrutinizer ignore-call */ 
968
    $rank          = $db->fetchArray($result);
Loading history...
968
    $rank['title'] = $myts->htmlSpecialChars($rank['title']);
969
    $rank['id']    = $rank_id;
970
971
    return $rank;
972
}
973
974
/**
975
 * Returns the portion of string specified by the start and length parameters. If $trimmarker is supplied, it is appended to the return string. This function works fine with multibyte characters if mb_* functions exist on the server.
976
 *
977
 * @param string $str
978
 * @param int    $start
979
 * @param int    $length
980
 * @param string $trimmarker
981
 * @return string
982
 */
983
function xoops_substr($str, $start, $length, $trimmarker = '...')
984
{
985
    xoops_load('XoopsLocal');
986
987
    return XoopsLocal::substr($str, $start, $length, $trimmarker);
988
}
989
990
// RMV-NOTIFY
991
// ################ Notification Helper Functions ##################
992
// We want to be able to delete by module, by user, or by item.
993
// How do we specify this??
994
/**
995
 * @param $module_id
996
 *
997
 * @return mixed
998
 */
999
function xoops_notification_deletebymodule($module_id)
1000
{
1001
    $notification_handler = xoops_getHandler('notification');
1002
1003
    return $notification_handler->unsubscribeByModule($module_id);
0 ignored issues
show
Bug introduced by
The method unsubscribeByModule() does not exist on XoopsObjectHandler. It seems like you code against a sub-type of XoopsObjectHandler such as XoopsNotificationHandler or XoopsPersistableObjectHandler. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1003
    return $notification_handler->/** @scrutinizer ignore-call */ unsubscribeByModule($module_id);
Loading history...
1004
}
1005
1006
/**
1007
 * xoops_notification_deletebyuser()
1008
 *
1009
 * @param mixed $user_id
1010
 * @return
1011
 */
1012
function xoops_notification_deletebyuser($user_id)
1013
{
1014
    $notification_handler = xoops_getHandler('notification');
1015
1016
    return $notification_handler->unsubscribeByUser($user_id);
0 ignored issues
show
Bug introduced by
The method unsubscribeByUser() does not exist on XoopsObjectHandler. It seems like you code against a sub-type of XoopsObjectHandler such as XoopsNotificationHandler or XoopsPersistableObjectHandler. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1016
    return $notification_handler->/** @scrutinizer ignore-call */ unsubscribeByUser($user_id);
Loading history...
1017
}
1018
1019
/**
1020
 * xoops_notification_deletebyitem()
1021
 *
1022
 * @param mixed $module_id
1023
 * @param mixed $category
1024
 * @param mixed $item_id
1025
 * @return
1026
 */
1027
function xoops_notification_deletebyitem($module_id, $category, $item_id)
1028
{
1029
    $notification_handler = xoops_getHandler('notification');
1030
1031
    return $notification_handler->unsubscribeByItem($module_id, $category, $item_id);
0 ignored issues
show
Bug introduced by
The method unsubscribeByItem() does not exist on XoopsObjectHandler. It seems like you code against a sub-type of XoopsObjectHandler such as XoopsNotificationHandler or XoopsPersistableObjectHandler. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

1031
    return $notification_handler->/** @scrutinizer ignore-call */ unsubscribeByItem($module_id, $category, $item_id);
Loading history...
1032
}
1033
1034
/**
1035
 * xoops_comment_count()
1036
 *
1037
 * @param mixed $module_id
1038
 * @param mixed $item_id
1039
 * @return
1040
 */
1041
function xoops_comment_count($module_id, $item_id = null)
1042
{
1043
    /** @var \XoopsCommentHandler $comment_handler */
1044
    $comment_handler = xoops_getHandler('comment');
1045
    $criteria        = new CriteriaCompo(new Criteria('com_modid', (int) $module_id));
1046
    if (isset($item_id)) {
1047
        $criteria->add(new Criteria('com_itemid', (int) $item_id));
1048
    }
1049
1050
    return $comment_handler->getCount($criteria);
1051
}
1052
1053
/**
1054
 * xoops_comment_delete()
1055
 *
1056
 * @param mixed $module_id
1057
 * @param mixed $item_id
1058
 * @return bool
1059
 */
1060
function xoops_comment_delete($module_id, $item_id)
1061
{
1062
    if ((int) $module_id > 0 && (int) $item_id > 0) {
1063
        /** @var \XoopsCommentHandler $comment_handler */
1064
        $comment_handler = xoops_getHandler('comment');
1065
        $comments        = $comment_handler->getByItemId($module_id, $item_id);
1066
        if (is_array($comments)) {
0 ignored issues
show
introduced by
The condition is_array($comments) is always true.
Loading history...
1067
            $count       = count($comments);
1068
            $deleted_num = [];
1069
            for ($i = 0; $i < $count; ++$i) {
1070
                if (false !== $comment_handler->delete($comments[$i])) {
1071
                    // store poster ID and deleted post number into array for later use
1072
                    $poster_id = $comments[$i]->getVar('com_uid');
1073
                    if ($poster_id != 0) {
1074
                        $deleted_num[$poster_id] = !isset($deleted_num[$poster_id]) ? 1 : ($deleted_num[$poster_id] + 1);
1075
                    }
1076
                }
1077
            }
1078
            /** @var XoopsMemberHandler $member_handler */
1079
            $member_handler = xoops_getHandler('member');
1080
            foreach ($deleted_num as $user_id => $post_num) {
1081
                // update user posts
1082
                $com_poster = $member_handler->getUser($user_id);
1083
                if (is_object($com_poster)) {
1084
                    $member_handler->updateUserByField($com_poster, 'posts', $com_poster->getVar('posts') - $post_num);
1085
                }
1086
            }
1087
1088
            return true;
1089
        }
1090
    }
1091
1092
    return false;
1093
}
1094
1095
/**
1096
 * xoops_groupperm_deletebymoditem()
1097
 *
1098
 * Group Permission Helper Functions
1099
 *
1100
 * @param mixed $module_id
1101
 * @param mixed $perm_name
1102
 * @param mixed $item_id
1103
 * @return bool
1104
 */
1105
function xoops_groupperm_deletebymoditem($module_id, $perm_name, $item_id = null)
1106
{
1107
    // do not allow system permissions to be deleted
1108
    if ((int) $module_id <= 1) {
1109
        return false;
1110
    }
1111
    /** @var  XoopsGroupPermHandler $gperm_handler */
1112
    $gperm_handler = xoops_getHandler('groupperm');
1113
1114
    return $gperm_handler->deleteByModule($module_id, $perm_name, $item_id);
1115
}
1116
1117
/**
1118
 * xoops_utf8_encode()
1119
 *
1120
 * @param mixed $text
1121
 * @return string
1122
 */
1123
function xoops_utf8_encode($text)
1124
{
1125
    xoops_load('XoopsLocal');
1126
1127
    return XoopsLocal::utf8_encode($text);
1128
}
1129
1130
/**
1131
 * xoops_utf8_decode()
1132
 *
1133
 * @param mixed $text
1134
 * @return string
1135
 */
1136
function xoops_utf8_decode($text)
1137
{
1138
    xoops_load('XoopsLocal');
1139
1140
    return XoopsLocal::utf8_decode($text);
1141
}
1142
1143
/**
1144
 * xoops_convert_encoding()
1145
 *
1146
 * @param mixed $text
1147
 * @return string
1148
 */
1149
function xoops_convert_encoding($text)
1150
{
1151
    return xoops_utf8_encode($text);
1152
}
1153
1154
/**
1155
 * xoops_trim()
1156
 *
1157
 * @param mixed $text
1158
 * @return string
1159
 */
1160
function xoops_trim($text)
1161
{
1162
    xoops_load('XoopsLocal');
1163
1164
    return XoopsLocal::trim($text);
1165
}
1166
1167
/**
1168
 * YOU SHOULD NOT USE THIS METHOD, IT WILL BE REMOVED
1169
 */
1170
/**
1171
 * xoops_getOption()
1172
 *
1173
 * @param mixed $option
1174
 * @internal param string $type
1175
 * @deprecated
1176
 * @return string
1177
 */
1178
function xoops_getOption($option)
1179
{
1180
    $ret = $GLOBALS['xoopsOption'][$option] ?? '';
1181
1182
    return $ret;
1183
}
1184
1185
/**
1186
 * YOU SHOULD NOT USE THIS METHOD, IT WILL BE REMOVED
1187
 */
1188
/**
1189
 * xoops_getConfigOption()
1190
 *
1191
 * @param mixed  $option
1192
 * @param array|string $type
1193
 * @internal param string $dirname
1194
 * @deprecated
1195
 * @return bool
1196
 */
1197
function xoops_getConfigOption($option, $type = 'XOOPS_CONF')
1198
{
1199
    static $coreOptions = [];
1200
1201
    if (is_array($coreOptions) && array_key_exists($option, $coreOptions)) {
1202
        return $coreOptions[$option];
1203
    }
1204
    $ret            = false;
1205
    /** @var XoopsConfigHandler $config_handler */
1206
    $config_handler = xoops_getHandler('config');
1207
    $configs        = $config_handler->getConfigsByCat(is_array($type) ? $type : constant($type));
0 ignored issues
show
Bug introduced by
It seems like is_array($type) ? $type : constant($type) can also be of type array; however, parameter $category of XoopsConfigHandler::getConfigsByCat() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1207
    $configs        = $config_handler->getConfigsByCat(/** @scrutinizer ignore-type */ is_array($type) ? $type : constant($type));
Loading history...
1208
    if ($configs) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $configs of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
1209
        if (isset($configs[$option])) {
1210
            $ret = $configs[$option];
1211
        }
1212
    }
1213
    $coreOptions[$option] = $ret;
1214
1215
    return $ret;
1216
}
1217
1218
/**
1219
 * YOU SHOULD NOT USE THIS METHOD, IT WILL BE REMOVED
1220
 */
1221
/**
1222
 * xoops_setConfigOption()
1223
 *
1224
 * @param mixed $option
1225
 * @param null  $new
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $new is correct as it would always require null to be passed?
Loading history...
1226
 * @return void
1227
@deprecated
1228
 */
1229
function xoops_setConfigOption($option, $new = null)
1230
{
1231
    if (isset($GLOBALS['xoopsConfig'][$option]) && null !== $new) {
0 ignored issues
show
introduced by
The condition null !== $new is always false.
Loading history...
1232
        $GLOBALS['xoopsConfig'][$option] = $new;
1233
    }
1234
}
1235
1236
/**
1237
 * YOU SHOULD NOT USE THIS METHOD, IT WILL BE REMOVED
1238
 */
1239
/**
1240
 * xoops_getModuleOption
1241
 *
1242
 * Method for module developers getting a module config item. This could be from any module requested.
1243
 *
1244
 * @param mixed  $option
1245
 * @param string $dirname
1246
 * @return bool
1247
@deprecated
1248
 */
1249
function xoops_getModuleOption($option, $dirname = '')
1250
{
1251
    static $modOptions = [];
1252
    if (is_array($modOptions) && isset($modOptions[$dirname][$option])) {
1253
        return $modOptions[$dirname][$option];
1254
    }
1255
1256
    $ret            = false;
1257
    /** @var XoopsModuleHandler $module_handler */
1258
    $module_handler = xoops_getHandler('module');
1259
    $module         = $module_handler->getByDirname($dirname);
1260
    /** @var XoopsConfigHandler $config_handler */
1261
    $config_handler = xoops_getHandler('config');
1262
    if (is_object($module)) {
1263
        $moduleConfig = $config_handler->getConfigsByCat(0, $module->getVar('mid'));
1264
        if (isset($moduleConfig[$option])) {
1265
            $ret = $moduleConfig[$option];
1266
        }
1267
    }
1268
    $modOptions[$dirname][$option] = $ret;
1269
1270
    return $ret;
1271
}
1272
1273
/**
1274
 * Determine the base domain name for a URL. The primary use for this is to set the domain
1275
 * used for cookies to represent any subdomains.
1276
 *
1277
 * The registrable domain is determined using the public suffix list. If the domain is not
1278
 * registrable, an empty string is returned. This empty string can be used in setcookie()
1279
 * as the domain, which restricts cookie to just the current host.
1280
 *
1281
 * @param string $url URL or hostname to process
1282
 *
1283
 * @return string the registrable domain or an empty string
1284
 */
1285
function xoops_getBaseDomain($url)
1286
{
1287
    $parts = parse_url($url);
1288
    $host = '';
1289
    if (!empty($parts['host'])) {
1290
        $host = $parts['host'];
1291
        if (strtolower($host) === 'localhost') {
1292
            return 'localhost';
1293
        }
1294
        // bail if this is an IPv4 address (IPv6 will fail later)
1295
        if (false !== filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
1296
            return '';
1297
        }
1298
        $regdom = new \Xoops\RegDom\RegisteredDomain();
1299
        $host = $regdom->getRegisteredDomain($host);
1300
    }
1301
    return $host ?? '';
1302
}
1303
1304
/**
1305
 * YOU SHOULD NOT USE THIS METHOD, IT WILL BE REMOVED
1306
 */
1307
/**
1308
 * Function to get the domain from a URL.
1309
 *
1310
 * @param string $url the URL to be stripped.
1311
 * @return string
1312
 * @deprecated
1313
 */
1314
function xoops_getUrlDomain($url)
1315
{
1316
    $domain = '';
1317
    $_URL   = parse_url($url);
1318
1319
    if (!empty($_URL) || !empty($_URL['host'])) {
1320
        $domain = $_URL['host'];
1321
    }
1322
1323
    return $domain;
1324
}
1325
1326
/**
1327
 * Check that the variable passed as $name is set, and if not, set with the specified $default.
1328
 *
1329
 * Note that $name is passed by reference, so it will be established in the caller's context
1330
 * if not already set. The value of $name is returned for convenience as well.
1331
 *
1332
 * @param mixed $name    Passed by reference variable. Will be created if is not set.
1333
 * @param mixed $default The default to use if $name is not set
1334
 *
1335
 * @return mixed the value in $name
1336
 */
1337
function makeSet(&$name, $default)
1338
{
1339
    if (!isset($name)) {
1340
        $name = $default;
1341
    }
1342
    return $name;
1343
}
1344
1345
include_once __DIR__ . '/functions.encoding.php';
1346
include_once __DIR__ . '/functions.legacy.php';
1347