Completed
Pull Request — master (#325)
by Richard
08:44
created

functions.php ➔ xoops_getBaseDomain()   B

Complexity

Conditions 5
Paths 6

Size

Total Lines 18
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 12
nc 6
nop 1
dl 0
loc 18
rs 8.8571
c 0
b 0
f 0
1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 28 and the first side effect is on line 18.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
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 (http://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
/**
21
 * xoops_getHandler()
22
 *
23
 * @param mixed $name
24
 * @param mixed $optional
25
 *
26
 * @return XoopsObjectHandler|false
0 ignored issues
show
Documentation introduced by
Should the return type not be object|false?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
27
 */
28
function xoops_getHandler($name, $optional = false)
29
{
30
    static $handlers;
31
    $name = strtolower(trim($name));
32
    if (!isset($handlers[$name])) {
33
        if (file_exists($hnd_file = XOOPS_ROOT_PATH . '/kernel/' . $name . '.php')) {
34
            require_once $hnd_file;
35
        }
36
        $class = 'Xoops' . ucfirst($name) . 'Handler';
37
        if (class_exists($class)) {
38
            $xoopsDB         = XoopsDatabaseFactory::getDatabaseConnection();
39
            $handlers[$name] = new $class($xoopsDB);
40
        }
41
    }
42 View Code Duplication
    if (!isset($handlers[$name])) {
43
        trigger_error('Class <strong>' . $class . '</strong> does not exist<br>Handler Name: ' . $name, $optional ? E_USER_WARNING : E_USER_ERROR);
0 ignored issues
show
Bug introduced by
The variable $class does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
44
    }
45
    if (isset($handlers[$name])) {
46
        return $handlers[$name];
47
    }
48
    $inst = false;
49
50
    return $inst;
51
}
52
53
/**
54
 * xoops_getModuleHandler()
55
 *
56
 * @param mixed $name
57
 * @param mixed $module_dir
58
 * @param mixed $optional
59
 * @return XoopsObjectHandler|false
60
 */
61
function xoops_getModuleHandler($name = null, $module_dir = null, $optional = false)
62
{
63
    static $handlers;
64
    // if $module_dir is not specified
65
    if (!isset($module_dir)) {
66
        // if a module is loaded
67
        if (isset($GLOBALS['xoopsModule']) && is_object($GLOBALS['xoopsModule'])) {
68
            $module_dir = $GLOBALS['xoopsModule']->getVar('dirname', 'n');
69
        } else {
70
            trigger_error('No Module is loaded', E_USER_ERROR);
71
        }
72
    } else {
73
        $module_dir = trim($module_dir);
74
    }
75
    $name = (!isset($name)) ? $module_dir : trim($name);
76
    if (!isset($handlers[$module_dir][$name])) {
77
        if (file_exists($hnd_file = XOOPS_ROOT_PATH . "/modules/{$module_dir}/class/{$name}.php")) {
78
            include_once $hnd_file;
79
        }
80
        $class = ucfirst(strtolower($module_dir)) . ucfirst($name) . 'Handler';
81
        if (class_exists($class)) {
82
            $xoopsDB                      = XoopsDatabaseFactory::getDatabaseConnection();
83
            $handlers[$module_dir][$name] = new $class($xoopsDB);
84
        }
85
    }
86 View Code Duplication
    if (!isset($handlers[$module_dir][$name])) {
87
        trigger_error('Handler does not exist<br>Module: ' . $module_dir . '<br>Name: ' . $name, $optional ? E_USER_WARNING : E_USER_ERROR);
88
    }
89
    if (isset($handlers[$module_dir][$name])) {
90
        return $handlers[$module_dir][$name];
91
    }
92
    $inst = false;
93
94
    return $inst;
95
}
96
97
/**
98
 * XOOPS class loader wrapper
99
 *
100
 * Temporay solution for XOOPS 2.3
101
 *
102
 * @param string $name                                          Name of class to be loaded
103
 * @param string $type                                          domain of the class, potential values:   core - located in /class/;
104
 *                                                              framework - located in /Frameworks/;
105
 *                                                              other - module class, located in /modules/[$type]/class/
106
 *
107
 * @return boolean
108
 */
109
function xoops_load($name, $type = 'core')
110
{
111
    if (!class_exists('XoopsLoad')) {
112
        require_once XOOPS_ROOT_PATH . '/class/xoopsload.php';
113
    }
114
115
    return XoopsLoad::load($name, $type);
116
}
117
118
/**
119
 * XOOPS language loader wrapper
120
 *
121
 * Temporay solution, not encouraged to use
122
 *
123
 * @param   string $name     Name of language file to be loaded, without extension
124
 * @param   string $domain   Module dirname; global language file will be loaded if $domain is set to 'global' or not specified
125
 * @param   string $language Language to be loaded, current language content will be loaded if not specified
126
 * @return  boolean
127
 * @todo    expand domain to multiple categories, e.g. module:system, framework:filter, etc.
128
 *
129
 */
130
function xoops_loadLanguage($name, $domain = '', $language = null)
131
{
132
    /**
133
     * Set pageType
134
     */
135
    if ($name === 'pagetype') {
136
        $name = xoops_getOption('pagetype');
0 ignored issues
show
Deprecated Code introduced by
The function xoops_getOption() has been deprecated.

This function has been deprecated.

Loading history...
137
    }
138
    /**
139
     * We must check later for an empty value. As xoops_getOption could be empty
140
     */
141
    if (empty($name)) {
142
        return false;
143
    }
144
    $language = empty($language) ? $GLOBALS['xoopsConfig']['language'] : $language;
145
    $path     = ((empty($domain) || 'global' === $domain) ? '' : "modules/{$domain}/") . 'language';
146
    if (!file_exists($fileinc = $GLOBALS['xoops']->path("{$path}/{$language}/{$name}.php"))) {
147
        if (!file_exists($fileinc = $GLOBALS['xoops']->path("{$path}/english/{$name}.php"))) {
148
            return false;
149
        }
150
    }
151
    $ret = include_once $fileinc;
152
153
    return $ret;
154
}
155
156
/**
157
 * YOU SHOULD BE CAREFUL WITH USING THIS METHOD SINCE IT WILL BE DEPRECATED
158
 */
159
/**
160
 * xoops_getActiveModules()
161
 *
162
 * Get active modules from cache file
163
 *
164
 * @return array
165
 */
166
function xoops_getActiveModules()
167
{
168
    static $modules_active;
169
    if (is_array($modules_active)) {
170
        return $modules_active;
171
    }
172
    xoops_load('XoopsCache');
173
    if (!$modules_active = XoopsCache::read('system_modules_active')) {
174
        $modules_active = xoops_setActiveModules();
175
    }
176
177
    return $modules_active;
178
}
179
180
/**
181
 * YOU SHOULD BE CAREFUL WITH USING THIS METHOD SINCE IT WILL BE DEPRECATED
182
 */
183
/**
184
 * xoops_setActiveModules()
185
 *
186
 * Write active modules to cache file
187
 *
188
 * @return array
189
 */
190
function xoops_setActiveModules()
191
{
192
    xoops_load('XoopsCache');
193
    $module_handler = xoops_getHandler('module');
194
    $modules_obj    = $module_handler->getObjects(new Criteria('isactive', 1));
195
    $modules_active = array();
196
    foreach (array_keys($modules_obj) as $key) {
197
        $modules_active[] = $modules_obj[$key]->getVar('dirname');
198
    }
199
    unset($modules_obj);
200
    XoopsCache::write('system_modules_active', $modules_active);
201
202
    return $modules_active;
203
}
204
205
/**
206
 * YOU SHOULD BE CAREFUL WITH USING THIS METHOD SINCE IT WILL BE DEPRECATED
207
 */
208
/**
209
 * xoops_isActiveModule()
210
 *
211
 * Checks is module is installed and active
212
 *
213
 * @param $dirname
214
 * @return bool
215
 */
216
function xoops_isActiveModule($dirname)
217
{
218
    return isset($dirname) && in_array($dirname, xoops_getActiveModules());
219
}
220
221
/**
222
 * xoops_header()
223
 *
224
 * @param mixed $closehead
225
 * @return void
226
 */
227
function xoops_header($closehead = true)
228
{
229
    global $xoopsConfig;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
230
231
    $themeSet = $xoopsConfig['theme_set'];
232
    $themePath = XOOPS_THEME_PATH . '/' . $themeSet . '/';
233
    $themeUrl = XOOPS_THEME_URL . '/' . $themeSet . '/';
234
    include_once XOOPS_ROOT_PATH . '/class/template.php';
235
    $headTpl = new \XoopsTpl();
236
    $headTpl->assign(array(
237
        'closeHead'      => (bool) $closehead,
238
        'themeUrl'       => $themeUrl,
239
        'xoops_langcode' => _LANGCODE,
240
        'xoops_charset'  => _CHARSET,
241
        'xoops_sitename' => $xoopsConfig['sitename'],
242
        'xoops_url'      => XOOPS_URL,
243
    ));
244
245
    if (file_exists($themePath . 'theme_autorun.php')) {
246
        include_once($themePath . 'theme_autorun.php');
247
    }
248
249
    $headItems = array();
250
    $headItems[] = '<script type="text/javascript" src="' . XOOPS_URL . '/include/xoops.js"></script>';
251
    $headItems[] = '<link rel="stylesheet" type="text/css" media="all" href="' . XOOPS_URL . '/xoops.css">';
252
    $headItems[] = '<link rel="stylesheet" type="text/css" media="all" href="' . XOOPS_URL . '/media/font-awesome/css/font-awesome.min.css">';
253
    $languageFile = 'language/' . $GLOBALS['xoopsConfig']['language'] . '/style.css';
254
    if (file_exists($GLOBALS['xoops']->path($languageFile))) {
255
        $headItems[] = '<link rel="stylesheet" type="text/css" media="all" href="' . $GLOBALS['xoops']->url($languageFile) . '">';
256
    }
257
    $themecss = xoops_getcss($xoopsConfig['theme_set']);
258
    if ($themecss!=='') {
259
        $headItems[] = '<link rel="stylesheet" type="text/css" media="all" href="' . $themecss . '">';
260
    }
261
    $headTpl->assign('headItems', $headItems);
262
263 View Code Duplication
    if (!headers_sent()) {
264
        header('Content-Type:text/html; charset=' . _CHARSET);
265
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
266
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
267
        header('Cache-Control: no-store, no-cache, max-age=1, s-maxage=1, must-revalidate, post-check=0, pre-check=0');
268
        header('Pragma: no-cache');
269
    }
270
271
    $output = $headTpl->fetch('db:system_popup_header.tpl');
272
    echo $output;
273
}
274
275
/**
276
 * xoops_footer
277
 *
278
 * @return void
279
 */
280
function xoops_footer()
281
{
282
    global $xoopsConfig;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
283
284
    $themeSet = $xoopsConfig['theme_set'];
285
    $themePath = XOOPS_THEME_URL . '/' . $themeSet . '/';
286
    include_once XOOPS_ROOT_PATH . '/class/template.php';
287
    $footTpl = new \XoopsTpl();
288
    $footTpl->assign(array(
289
        'themePath'      => $themePath,
290
        'xoops_langcode' => _LANGCODE,
291
        'xoops_charset'  => _CHARSET,
292
        'xoops_sitename' => $xoopsConfig['sitename'],
293
        'xoops_url'      => XOOPS_URL,
294
    ));
295
    $output = $footTpl->fetch('db:system_popup_footer.tpl');
296
    echo $output;
297
    ob_end_flush();
298
}
299
300
/**
301
 * xoops_error
302
 *
303
 * @param mixed  $msg
304
 * @param string $title
305
 * @return void
306
 */
307 View Code Duplication
function xoops_error($msg, $title = '')
0 ignored issues
show
Duplication introduced by
This function seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
308
{
309
    echo '<div class="errorMsg">';
310
    if ($title != '') {
311
        echo '<strong>' . $title . '</strong><br><br>';
312
    }
313
    if (is_object($msg)) {
314
        $msg = (array)$msg;
315
    }
316
    if (is_array($msg)) {
317
        foreach ($msg as $key => $value) {
318
            if (is_numeric($key)) {
319
                $key = '';
320
            }
321
            xoops_error($value, $key);
322
        }
323
    } else {
324
        echo "<div>{$msg}</div>";
325
    }
326
    echo '</div>';
327
}
328
329
/**
330
 * xoops_result
331
 *
332
 * @param mixed  $msg
333
 * @param string $title
334
 * @return void
335
 */
336 View Code Duplication
function xoops_result($msg, $title = '')
0 ignored issues
show
Duplication introduced by
This function seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
337
{
338
    echo '<div class="resultMsg">';
339
    if ($title != '') {
340
        echo '<strong>' . $title . '</strong><br><br>';
341
    }
342
    if (is_object($msg)) {
343
        $msg = (array)$msg;
344
    }
345
    if (is_array($msg)) {
346
        foreach ($msg as $key => $value) {
347
            if (is_numeric($key)) {
348
                $key = '';
349
            }
350
            xoops_result($value, $key);
351
        }
352
    } else {
353
        echo "<div>{$msg}</div>";
354
    }
355
    echo '</div>';
356
}
357
358
/**
359
 * xoops_confirm()
360
 *
361
 * @param mixed  $hiddens
362
 * @param mixed  $action
363
 * @param mixed  $msg
364
 * @param string $submit
365
 * @param mixed  $addtoken
366
 * @return void
367
 */
368
function xoops_confirm($hiddens, $action, $msg, $submit = '', $addtoken = true)
369
{
370
    $submit = ($submit != '') ? trim($submit) : _SUBMIT;
371
    echo '<div class="confirmMsg">' . $msg . '<br>
372
          <form method="post" action="' . $action . '">';
373
    foreach ($hiddens as $name => $value) {
374
        if (is_array($value)) {
375
            foreach ($value as $caption => $newvalue) {
376
                echo '<input type="radio" name="' . $name . '" value="' . htmlspecialchars($newvalue) . '" /> ' . $caption;
377
            }
378
            echo '<br>';
379
        } else {
380
            echo '<input type="hidden" name="' . $name . '" value="' . htmlspecialchars($value) . '" />';
381
        }
382
    }
383
    if ($addtoken != false) {
384
        echo $GLOBALS['xoopsSecurity']->getTokenHTML();
385
    }
386
    echo '<input type="submit" name="confirm_submit" value="' . $submit . '" title="' . $submit . '"/>
387
          <input type="button" name="confirm_back" value="' . _CANCEL . '" onclick="javascript:history.go(-1);" title="' . _CANCEL . '" />
388
          </form>
389
          </div>';
390
}
391
392
/**
393
 * xoops_getUserTimestamp()
394
 *
395
 * @param mixed  $time
396
 * @param string $timeoffset
397
 * @return int
0 ignored issues
show
Documentation introduced by
Should the return type not be double?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
398
 */
399
function xoops_getUserTimestamp($time, $timeoffset = '')
400
{
401
    global $xoopsConfig, $xoopsUser;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
402
    if ($timeoffset == '') {
403
        if ($xoopsUser) {
404
            $timeoffset = $xoopsUser->getVar('timezone_offset');
405
        } else {
406
            $timeoffset = $xoopsConfig['default_TZ'];
407
        }
408
    }
409
    $usertimestamp = (int)$time + ((float)$timeoffset - $xoopsConfig['server_TZ']) * 3600;
410
411
    return $usertimestamp;
412
}
413
414
/**
415
 * Function to display formatted times in user timezone
416
 * @param        $time
417
 * @param string $format
418
 * @param string $timeoffset
419
 * @return string
420
 */
421
function formatTimestamp($time, $format = 'l', $timeoffset = '')
422
{
423
    xoops_load('XoopsLocal');
424
425
    return XoopsLocal::formatTimestamp($time, $format, $timeoffset);
426
}
427
428
/**
429
 * Function to calculate server timestamp from user entered time (timestamp)
430
 * @param      $timestamp
431
 * @param null $userTZ
432
 * @return
433
 */
434
function userTimeToServerTime($timestamp, $userTZ = null)
435
{
436
    global $xoopsConfig;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
437
    if (!isset($userTZ)) {
438
        $userTZ = $xoopsConfig['default_TZ'];
439
    }
440
    $timestamp -= (($userTZ - $xoopsConfig['server_TZ']) * 3600);
441
442
    return $timestamp;
443
}
444
445
/**
446
 * xoops_makepass()
447
 *
448
 * @return string
449
 */
450
function xoops_makepass()
451
{
452
    $makepass  = '';
453
    $syllables = array(
454
        'er',
455
        'in',
456
        'tia',
457
        'wol',
458
        'fe',
459
        'pre',
460
        'vet',
461
        'jo',
462
        'nes',
463
        'al',
464
        'len',
465
        'son',
466
        'cha',
467
        'ir',
468
        'ler',
469
        'bo',
470
        'ok',
471
        'tio',
472
        'nar',
473
        'sim',
474
        'ple',
475
        'bla',
476
        'ten',
477
        'toe',
478
        'cho',
479
        'co',
480
        'lat',
481
        'spe',
482
        'ak',
483
        'er',
484
        'po',
485
        'co',
486
        'lor',
487
        'pen',
488
        'cil',
489
        'li',
490
        'ght',
491
        'wh',
492
        'at',
493
        'the',
494
        'he',
495
        'ck',
496
        'is',
497
        'mam',
498
        'bo',
499
        'no',
500
        'fi',
501
        've',
502
        'any',
503
        'way',
504
        'pol',
505
        'iti',
506
        'cs',
507
        'ra',
508
        'dio',
509
        'sou',
510
        'rce',
511
        'sea',
512
        'rch',
513
        'pa',
514
        'per',
515
        'com',
516
        'bo',
517
        'sp',
518
        'eak',
519
        'st',
520
        'fi',
521
        'rst',
522
        'gr',
523
        'oup',
524
        'boy',
525
        'ea',
526
        'gle',
527
        'tr',
528
        'ail',
529
        'bi',
530
        'ble',
531
        'brb',
532
        'pri',
533
        'dee',
534
        'kay',
535
        'en',
536
        'be',
537
        'se');
538
    mt_srand((double)microtime() * 1000000);
539
    for ($count = 1; $count <= 4; ++$count) {
540
        if (mt_rand() % 10 == 1) {
541
            $makepass .= sprintf('%0.0f', (mt_rand() % 50) + 1);
542
        } else {
543
            $makepass .= sprintf('%s', $syllables[mt_rand() % 62]);
544
        }
545
    }
546
547
    return $makepass;
548
}
549
550
/**
551
 * checkEmail()
552
 *
553
 * @param mixed $email
554
 * @param mixed $antispam
555
 * @return bool|mixed
556
 */
557
function checkEmail($email, $antispam = false)
558
{
559
    if (!$email || !preg_match('/^[^@]{1,64}@[^@]{1,255}$/', $email)) {
560
        return false;
561
    }
562
    $email_array      = explode('@', $email);
563
    $local_array      = explode('.', $email_array[0]);
564
    $local_arrayCount = count($local_array);
565
    for ($i = 0; $i < $local_arrayCount; ++$i) {
566
        if (!preg_match("/^(([A-Za-z0-9!#$%&'*+\/\=?^_`{|}~-][A-Za-z0-9!#$%&'*+\/\=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$/", $local_array[$i])) {
567
            return false;
568
        }
569
    }
570
    if (!preg_match("/^\[?[0-9\.]+\]?$/", $email_array[1])) {
571
        $domain_array = explode('.', $email_array[1]);
572
        if (count($domain_array) < 2) {
573
            return false; // Not enough parts to domain
574
        }
575
        for ($i = 0; $i < count($domain_array); ++$i) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
576
            if (!preg_match("/^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$/", $domain_array[$i])) {
577
                return false;
578
            }
579
        }
580
    }
581
    if ($antispam) {
582
        $email = str_replace('@', ' at ', $email);
583
        $email = str_replace('.', ' dot ', $email);
584
    }
585
586
    return $email;
587
}
588
589
/**
590
 * formatURL()
591
 *
592
 * @param mixed $url
593
 * @return mixed|string
594
 */
595
function formatURL($url)
596
{
597
    $url = trim($url);
598
    if ($url != '') {
599
        if ((!preg_match('/^http[s]*:\/\//i', $url)) && (!preg_match('/^ftp*:\/\//i', $url)) && (!preg_match('/^ed2k*:\/\//i', $url))) {
600
            $url = 'http://' . $url;
601
        }
602
    }
603
604
    return $url;
605
}
606
607
/**
608
 * Function to get banner html tags for use in templates
609
 */
610
function xoops_getbanner()
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
611
{
612
    global $xoopsConfig;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
613
614
    $db      = XoopsDatabaseFactory::getDatabaseConnection();
615
    $bresult = $db->query('SELECT COUNT(*) FROM ' . $db->prefix('banner'));
616
    list($numrows) = $db->fetchRow($bresult);
617
    if ($numrows > 1) {
618
        --$numrows;
619
        mt_srand((double)microtime() * 1000000);
620
        $bannum = mt_rand(0, $numrows);
621
    } else {
622
        $bannum = 0;
623
    }
624
    if ($numrows > 0) {
625
        $bresult = $db->query('SELECT * FROM ' . $db->prefix('banner'), 1, $bannum);
626
        list($bid, $cid, $imptotal, $impmade, $clicks, $imageurl, $clickurl, $date, $htmlbanner, $htmlcode) = $db->fetchRow($bresult);
627
        if ($xoopsConfig['my_ip'] == xoops_getenv('REMOTE_ADDR')) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
628
            // EMPTY
629
        } else {
630
            ++$impmade;
631
            $db->queryF(sprintf('UPDATE %s SET impmade = %u WHERE bid = %u', $db->prefix('banner'), $impmade, $bid));
632
            /**
633
             * Check if this impression is the last one
634
             */
635
            if ($imptotal > 0 && $impmade >= $imptotal) {
636
                $newid = $db->genId($db->prefix('bannerfinish') . '_bid_seq');
637
                $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());
638
                $db->queryF($sql);
639
                $db->queryF(sprintf('DELETE FROM %s WHERE bid = %u', $db->prefix('banner'), $bid));
640
            }
641
        }
642
        /**
643
         * Print the banner
644
         */
645
        $bannerobject = '';
646
        if ($htmlbanner) {
647
            if ($htmlcode) {
648
                $bannerobject = $htmlcode;
649
            } else {
650
                $bannerobject = $bannerobject . '<div id="xo-bannerfix">';
651
                // $bannerobject = $bannerobject . '<div id="xo-fixbanner">';
652
                $bannerobject = $bannerobject . ' <iframe src=' . $imageurl . ' border="0" scrolling="no" allowtransparency="true" width="480px" height="60px" style="border:0" alt="' . $clickurl . ';"> </iframe>';
653
                $bannerobject .= '</div>';
654
                // $bannerobject .= '</div>';
655
            }
656
        } else {
657
            $bannerobject = '<div id="xo-bannerfix">';
658
            if (false !== stripos($imageurl, '.swf')) {
659
                $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>';
660
            } else {
661
                $bannerobject = $bannerobject . '<a href="' . XOOPS_URL . '/banners.php?op=click&amp;bid=' . $bid . '" rel="external" title="' . $clickurl . '"><img src="' . $imageurl . '" alt="' . $clickurl . '" /></a>';
662
            }
663
664
            $bannerobject .= '</div>';
665
        }
666
667
        return $bannerobject;
668
    }
669
    return null;
670
}
671
672
/**
673
 * Function to redirect a user to certain pages
674
 * @param        $url
675
 * @param int    $time
676
 * @param string $message
677
 * @param bool   $addredirect
678
 * @param bool   $allowExternalLink
679
 */
680
function redirect_header($url, $time = 3, $message = '', $addredirect = true, $allowExternalLink = false)
681
{
682
    global $xoopsConfig, $xoopsLogger, $xoopsUserIsAdmin;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
683
684
    $xoopsPreload = XoopsPreload::getInstance();
685
    $xoopsPreload->triggerEvent('core.include.functions.redirectheader.start', array($url, $time, $message, $addredirect, $allowExternalLink));
686
    // under normal circumstance this event will exit, so listen for the .start above
687
    $xoopsPreload->triggerEvent('core.include.functions.redirectheader', array($url, $time, $message, $addredirect, $allowExternalLink));
688
689
    if (preg_match("/[\\0-\\31]|about:|script:/i", $url)) {
690
        if (!preg_match('/^\b(java)?script:([\s]*)history\.go\(-\d*\)([\s]*[;]*[\s]*)$/si', $url)) {
691
            $url = XOOPS_URL;
692
        }
693
    }
694
    if (!$allowExternalLink && $pos = strpos($url, '://')) {
695
        $xoopsLocation = substr(XOOPS_URL, strpos(XOOPS_URL, '://') + 3);
696
        if (strcasecmp(substr($url, $pos + 3, strlen($xoopsLocation)), $xoopsLocation)) {
697
            $url = XOOPS_URL;
698
        }
699
    }
700
    if (defined('XOOPS_CPFUNC_LOADED')) {
701
        $theme = 'default';
702
    } else {
703
        $theme = $xoopsConfig['theme_set'];
704
    }
705
706
    require_once XOOPS_ROOT_PATH . '/class/template.php';
707
    require_once XOOPS_ROOT_PATH . '/class/theme.php';
708
    $xoopsThemeFactory                = null;
0 ignored issues
show
Unused Code introduced by
$xoopsThemeFactory is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
709
    $xoopsThemeFactory                = new xos_opal_ThemeFactory();
710
    $xoopsThemeFactory->allowedThemes = $xoopsConfig['theme_set_allowed'];
711
    $xoopsThemeFactory->defaultTheme  = $theme;
712
    $xoTheme                          = $xoopsThemeFactory->createInstance(array(
713
                                                                                'plugins'      => array(),
714
                                                                                'renderBanner' => false));
715
    $xoopsTpl                         = $xoTheme->template;
716
    $xoopsTpl->assign(array(
717
                          'xoops_theme'      => $theme,
718
                          'xoops_imageurl'   => XOOPS_THEME_URL . '/' . $theme . '/',
719
                          'xoops_themecss'   => xoops_getcss($theme),
720
                          'xoops_requesturi' => htmlspecialchars($_SERVER['REQUEST_URI'], ENT_QUOTES),
721
                          'xoops_sitename'   => htmlspecialchars($xoopsConfig['sitename'], ENT_QUOTES),
722
                          'xoops_slogan'     => htmlspecialchars($xoopsConfig['slogan'], ENT_QUOTES),
723
                          'xoops_dirname'    => isset($xoopsModule) && is_object($xoopsModule) ? $xoopsModule->getVar('dirname') : 'system',
0 ignored issues
show
Bug introduced by
The variable $xoopsModule seems to never exist, and therefore isset should always return false. Did you maybe rename this variable?

This check looks for calls to isset(...) or empty() on variables that are yet undefined. These calls will always produce the same result and can be removed.

This is most likely caused by the renaming of a variable or the removal of a function/method parameter.

Loading history...
724
                          'xoops_pagetitle'  => isset($xoopsModule) && is_object($xoopsModule) ? $xoopsModule->getVar('name') : htmlspecialchars($xoopsConfig['slogan'], ENT_QUOTES)));
725
    if ($xoopsConfig['debug_mode'] == 2 && $xoopsUserIsAdmin) {
726
        $xoopsTpl->assign('time', 300);
727
        $xoopsTpl->assign('xoops_logdump', $xoopsLogger->dump());
728
    } else {
729
        $xoopsTpl->assign('time', (int)$time);
730
    }
731
    if (!empty($_SERVER['REQUEST_URI']) && $addredirect && false !== strpos($url, 'user.php')) {
732
        if (false === strpos($url, '?')) {
733
            $url .= '?xoops_redirect=' . urlencode($_SERVER['REQUEST_URI']);
734
        } else {
735
            $url .= '&amp;xoops_redirect=' . urlencode($_SERVER['REQUEST_URI']);
736
        }
737
    }
738
    if (defined('SID') && SID && (!isset($_COOKIE[session_name()]) || ($xoopsConfig['use_mysession'] && $xoopsConfig['session_name'] != '' && !isset($_COOKIE[$xoopsConfig['session_name']])))) {
739
        if (false === strpos($url, '?')) {
740
            $url .= '?' . SID;
741
        } else {
742
            $url .= '&amp;' . SID;
743
        }
744
    }
745
    $url = preg_replace('/&amp;/i', '&', htmlspecialchars($url, ENT_QUOTES));
746
    $xoopsTpl->assign('url', $url);
747
    $message = trim($message) != '' ? $message : _TAKINGBACK;
748
    $xoopsTpl->assign('message', $message);
749
    $xoopsTpl->assign('lang_ifnotreload', sprintf(_IFNOTRELOAD, $url));
750
751
    $xoopsTpl->display('db:system_redirect.tpl');
752
    exit();
0 ignored issues
show
Coding Style Compatibility introduced by
The function redirect_header() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
753
}
754
755
/**
756
 * xoops_getenv()
757
 *
758
 * @param mixed $key
759
 * @return string
760
 */
761
function xoops_getenv($key)
762
{
763
    $ret = '';
764 View Code Duplication
    if (array_key_exists($key, $_SERVER) && isset($_SERVER[$key])) {
765
        $ret = $_SERVER[$key];
766
767
        return $ret;
768
    }
769 View Code Duplication
    if (array_key_exists($key, $_ENV) && isset($_ENV[$key])) {
770
        $ret = $_ENV[$key];
771
772
        return $ret;
773
    }
774
775
    return $ret;
776
}
777
778
/**
779
 * Function to get css file for a certain themeset
780
 * @param string $theme
781
 * @return string
782
 */
783
function xoops_getcss($theme = '')
784
{
785
    if ($theme == '') {
786
        $theme = $GLOBALS['xoopsConfig']['theme_set'];
787
    }
788
    $uagent  = xoops_getenv('HTTP_USER_AGENT');
789
    $str_css = 'styleNN.css';
790
    if (false !== stripos($uagent, 'mac')) {
791
        $str_css = 'styleMAC.css';
792
    } elseif (preg_match("/MSIE (\d\.\d{1,2})/i", $uagent)) {
793
        $str_css = 'style.css';
794
    }
795 View Code Duplication
    if (is_dir(XOOPS_THEME_PATH . '/' . $theme)) {
796
        if (file_exists(XOOPS_THEME_PATH . '/' . $theme . '/' . $str_css)) {
797
            return XOOPS_THEME_URL . '/' . $theme . '/' . $str_css;
798
        } elseif (file_exists(XOOPS_THEME_PATH . '/' . $theme . '/style.css')) {
799
            return XOOPS_THEME_URL . '/' . $theme . '/style.css';
800
        }
801
    }
802 View Code Duplication
    if (is_dir(XOOPS_THEME_PATH . '/' . $theme . '/css')) {
803
        if (file_exists(XOOPS_THEME_PATH . '/' . $theme . '/css/' . $str_css)) {
804
            return XOOPS_THEME_URL . '/' . $theme . '/css/' . $str_css;
805
        } elseif (file_exists(XOOPS_THEME_PATH . '/' . $theme . '/css/style.css')) {
806
            return XOOPS_THEME_URL . '/' . $theme . '/css/style.css';
807
        }
808
    }
809
810
    return '';
811
}
812
813
/**
814
 * xoops_getMailer()
815
 *
816
 * @return \XoopsMailer|\XoopsMailerLocal
817
 */
818
function &xoops_getMailer()
819
{
820
    static $mailer;
821
    global $xoopsConfig;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
822
    if (is_object($mailer)) {
823
        return $mailer;
824
    }
825
    include_once XOOPS_ROOT_PATH . '/class/xoopsmailer.php';
826
    if (file_exists($file = XOOPS_ROOT_PATH . '/language/' . $xoopsConfig['language'] . '/xoopsmailerlocal.php')) {
827
        include_once $file;
828
    } elseif (file_exists($file = XOOPS_ROOT_PATH . '/language/english/xoopsmailerlocal.php')) {
829
        include_once $file;
830
    }
831
    unset($mailer);
832
    if (class_exists('XoopsMailerLocal')) {
833
        $mailer = new XoopsMailerLocal();
834
    } else {
835
        $mailer = new XoopsMailer();
836
    }
837
838
    return $mailer;
839
}
840
841
/**
842
 * xoops_getrank()
843
 *
844
 * @param integer $rank_id
845
 * @param mixed   $posts
846
 * @return
847
 */
848
function xoops_getrank($rank_id = 0, $posts = 0)
849
{
850
    $db      = XoopsDatabaseFactory::getDatabaseConnection();
851
    $myts    = MyTextSanitizer::getInstance();
852
    $rank_id = (int)$rank_id;
853
    $posts   = (int)$posts;
854
    if ($rank_id != 0) {
855
        $sql = 'SELECT rank_title AS title, rank_image AS image FROM ' . $db->prefix('ranks') . ' WHERE rank_id = ' . $rank_id;
856
    } else {
857
        $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';
858
    }
859
    $rank          = $db->fetchArray($db->query($sql));
860
    $rank['title'] = $myts->htmlspecialchars($rank['title']);
861
    $rank['id']    = $rank_id;
862
863
    return $rank;
864
}
865
866
/**
867
 * 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 multi-byte characters if mb_* functions exist on the server.
868
 *
869
 * @param string $str
870
 * @param int    $start
871
 * @param int    $length
872
 * @param string $trimmarker
873
 * @return string
874
 */
875
function xoops_substr($str, $start, $length, $trimmarker = '...')
876
{
877
    xoops_load('XoopsLocal');
878
879
    return XoopsLocal::substr($str, $start, $length, $trimmarker);
880
}
881
882
// RMV-NOTIFY
883
// ################ Notification Helper Functions ##################
884
// We want to be able to delete by module, by user, or by item.
885
// How do we specify this??
886
/**
887
 * @param $module_id
888
 *
889
 * @return mixed
890
 */
891
function xoops_notification_deletebymodule($module_id)
892
{
893
    $notification_handler = xoops_getHandler('notification');
894
895
    return $notification_handler->unsubscribeByModule($module_id);
896
}
897
898
/**
899
 * xoops_notification_deletebyuser()
900
 *
901
 * @param mixed $user_id
902
 * @return
903
 */
904
function xoops_notification_deletebyuser($user_id)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
905
{
906
    $notification_handler = xoops_getHandler('notification');
907
908
    return $notification_handler->unsubscribeByUser($user_id);
909
}
910
911
/**
912
 * xoops_notification_deletebyitem()
913
 *
914
 * @param mixed $module_id
915
 * @param mixed $category
916
 * @param mixed $item_id
917
 * @return
918
 */
919
function xoops_notification_deletebyitem($module_id, $category, $item_id)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
920
{
921
    $notification_handler = xoops_getHandler('notification');
922
923
    return $notification_handler->unsubscribeByItem($module_id, $category, $item_id);
924
}
925
926
/**
927
 * xoops_comment_count()
928
 *
929
 * @param mixed $module_id
930
 * @param mixed $item_id
931
 * @return
932
 */
933 View Code Duplication
function xoops_comment_count($module_id, $item_id = null)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
Duplication introduced by
This function seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
934
{
935
    $comment_handler = xoops_getHandler('comment');
936
    $criteria        = new CriteriaCompo(new Criteria('com_modid', (int)$module_id));
937
    if (isset($item_id)) {
938
        $criteria->add(new Criteria('com_itemid', (int)$item_id));
939
    }
940
941
    return $comment_handler->getCount($criteria);
942
}
943
944
/**
945
 * xoops_comment_delete()
946
 *
947
 * @param mixed $module_id
948
 * @param mixed $item_id
949
 * @return bool
950
 */
951
function xoops_comment_delete($module_id, $item_id)
952
{
953
    if ((int)$module_id > 0 && (int)$item_id > 0) {
954
        $comment_handler = xoops_getHandler('comment');
955
        $comments        = $comment_handler->getByItemId($module_id, $item_id);
956
        if (is_array($comments)) {
957
            $count       = count($comments);
958
            $deleted_num = array();
959
            for ($i = 0; $i < $count; ++$i) {
960
                if (false !== $comment_handler->delete($comments[$i])) {
961
                    // store poster ID and deleted post number into array for later use
962
                    $poster_id = $comments[$i]->getVar('com_uid');
963 View Code Duplication
                    if ($poster_id != 0) {
964
                        $deleted_num[$poster_id] = !isset($deleted_num[$poster_id]) ? 1 : ($deleted_num[$poster_id] + 1);
965
                    }
966
                }
967
            }
968
            $member_handler = xoops_getHandler('member');
969 View Code Duplication
            foreach ($deleted_num as $user_id => $post_num) {
970
                // update user posts
971
                $com_poster = $member_handler->getUser($user_id);
972
                if (is_object($com_poster)) {
973
                    $member_handler->updateUserByField($com_poster, 'posts', $com_poster->getVar('posts') - $post_num);
974
                }
975
            }
976
977
            return true;
978
        }
979
    }
980
981
    return false;
982
}
983
984
/**
985
 * xoops_groupperm_deletebymoditem()
986
 *
987
 * Group Permission Helper Functions
988
 *
989
 * @param mixed $module_id
990
 * @param mixed $perm_name
991
 * @param mixed $item_id
992
 * @return bool
993
 */
994
function xoops_groupperm_deletebymoditem($module_id, $perm_name, $item_id = null)
995
{
996
    // do not allow system permissions to be deleted
997
    if ((int)$module_id <= 1) {
998
        return false;
999
    }
1000
    $gperm_handler = xoops_getHandler('groupperm');
1001
1002
    return $gperm_handler->deleteByModule($module_id, $perm_name, $item_id);
1003
}
1004
1005
/**
1006
 * xoops_utf8_encode()
1007
 *
1008
 * @param mixed $text
1009
 * @return string
1010
 */
1011
function xoops_utf8_encode(&$text)
1012
{
1013
    xoops_load('XoopsLocal');
1014
1015
    return XoopsLocal::utf8_encode($text);
1016
}
1017
1018
/**
1019
 * xoops_convert_encoding()
1020
 *
1021
 * @param mixed $text
1022
 * @return string
1023
 */
1024
function xoops_convert_encoding(&$text)
1025
{
1026
    return xoops_utf8_encode($text);
1027
}
1028
1029
/**
1030
 * xoops_trim()
1031
 *
1032
 * @param mixed $text
1033
 * @return string
1034
 */
1035
function xoops_trim($text)
1036
{
1037
    xoops_load('XoopsLocal');
1038
1039
    return XoopsLocal::trim($text);
1040
}
1041
1042
/**
1043
 * YOU SHOULD NOT USE THIS METHOD, IT WILL BE REMOVED
1044
 */
1045
/**
1046
 * xoops_getOption()
1047
 *
1048
 * @param mixed $option
1049
 * @internal param string $type
1050
 * @deprecated
1051
 * @return string
1052
 */
1053
function xoops_getOption($option)
1054
{
1055
    $ret = '';
1056
    if (isset($GLOBALS['xoopsOption'][$option])) {
1057
        $ret = $GLOBALS['xoopsOption'][$option];
1058
    }
1059
1060
    return $ret;
1061
}
1062
1063
/**
1064
 * YOU SHOULD NOT USE THIS METHOD, IT WILL BE REMOVED
1065
 */
1066
/**
1067
 * xoops_getConfigOption()
1068
 *
1069
 * @param mixed  $option
1070
 * @param array|string $type
1071
 * @internal param string $dirname
1072
 * @deprecated
1073
 * @return bool
1074
 */
1075
function xoops_getConfigOption($option, $type = 'XOOPS_CONF')
1076
{
1077
    static $coreOptions = array();
1078
1079
    if (is_array($coreOptions) && array_key_exists($option, $coreOptions)) {
1080
        return $coreOptions[$option];
1081
    }
1082
    $ret            = false;
1083
    $config_handler = xoops_getHandler('config');
1084
    $configs        = $config_handler->getConfigsByCat(is_array($type) ? $type : constant($type));
1085
    if ($configs) {
1086
        if (isset($configs[$option])) {
1087
            $ret = $configs[$option];
1088
        }
1089
    }
1090
    $coreOptions[$option] = $ret;
1091
1092
    return $ret;
1093
}
1094
1095
/**
1096
 * YOU SHOULD NOT USE THIS METHOD, IT WILL BE REMOVED
1097
 */
1098
/**
1099
 * xoops_setConfigOption()
1100
 *
1101
 * @param mixed $option
1102
 * @param null  $new
1103
 * @return void
1104
@deprecated
1105
 */
1106
function xoops_setConfigOption($option, $new = null)
1107
{
1108
    if (isset($GLOBALS['xoopsConfig'][$option]) && null !== $new) {
1109
        $GLOBALS['xoopsConfig'][$option] = $new;
1110
    }
1111
}
1112
1113
/**
1114
 * YOU SHOULD NOT USE THIS METHOD, IT WILL BE REMOVED
1115
 */
1116
/**
1117
 * xoops_getModuleOption
1118
 *
1119
 * Method for module developers getting a module config item. This could be from any module requested.
1120
 *
1121
 * @param mixed  $option
1122
 * @param string $dirname
1123
 * @return bool
1124
@deprecated
1125
 */
1126
function xoops_getModuleOption($option, $dirname = '')
1127
{
1128
    static $modOptions = array();
1129
    if (is_array($modOptions) && isset($modOptions[$dirname][$option])) {
1130
        return $modOptions[$dirname][$option];
1131
    }
1132
1133
    $ret            = false;
1134
    $module_handler = xoops_getHandler('module');
1135
    $module         = $module_handler->getByDirname($dirname);
1136
    $config_handler = xoops_getHandler('config');
1137
    if (is_object($module)) {
1138
        $moduleConfig = $config_handler->getConfigsByCat(0, $module->getVar('mid'));
1139
        if (isset($moduleConfig[$option])) {
1140
            $ret = $moduleConfig[$option];
1141
        }
1142
    }
1143
    $modOptions[$dirname][$option] = $ret;
1144
1145
    return $ret;
1146
}
1147
1148
/**
1149
 * Determine the base domain name for a URL. The primary use for this is to set the domain
1150
 * used for cookies to represent any subdomains.
1151
 *
1152
 * The registrable domain is determined using the public suffix list. If the domain is not
1153
 * registrable, an empty string is returned. This empty string can be used in setcookie()
1154
 * as the domain, which restricts cookie to just the current host.
1155
 *
1156
 * @param string $url URL or hostname to process
1157
 *
1158
 * @return string the registrable domain or an empty string
1159
 */
1160
function xoops_getBaseDomain($url)
1161
{
1162
    $parts = parse_url($url);
1163
    $host = '';
1164
    if (!empty($parts['host'])) {
1165
        $host = $parts['host'];
1166
        if (strtolower($host) === 'localhost') {
1167
            return 'localhost';
1168
        }
1169
        // bail if this is an IPv4 address (IPv6 will fail later)
1170
        if (false !== filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
1171
            return '';
1172
        }
1173
        $regdom = new \Geekwright\RegDom\RegisteredDomain();
1174
        $host = $regdom->getRegisteredDomain($host);
1175
    }
1176
    return (null === $host) ? '' : $host;
1177
}
1178
1179
/**
1180
 * YOU SHOULD NOT USE THIS METHOD, IT WILL BE REMOVED
1181
 */
1182
/**
1183
 * Function to get the domain from a URL.
1184
 *
1185
 * @param string $url the URL to be stripped.
1186
 * @return string
1187
 * @deprecated
1188
 */
1189
function xoops_getUrlDomain($url)
1190
{
1191
    $domain = '';
1192
    $_URL   = parse_url($url);
1193
1194
    if (!empty($_URL) || !empty($_URL['host'])) {
1195
        $domain = $_URL['host'];
1196
    }
1197
1198
    return $domain;
1199
}
1200
1201
include_once __DIR__ . '/functions.encoding.php';
1202
include_once __DIR__ . '/functions.legacy.php';
1203