Passed
Push — master ( 3c6c24...f7d05c )
by Richard
05:35 queued 13s
created

xoops_warning()   A

Complexity

Conditions 6
Paths 8

Size

Total Lines 20
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 13
nc 8
nop 2
dl 0
loc 20
rs 9.2222
c 0
b 0
f 0
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 mixed $name
26
 * @param mixed $optional
27
 *
28
 * @return XoopsObjectHandler|false
29
 */
30
function xoops_getHandler($name, $optional = false)
31
{
32
    static $handlers;
33
    $name = strtolower(trim($name));
34
    if (!isset($handlers[$name])) {
35
        if (file_exists($hnd_file = XOOPS_ROOT_PATH . '/kernel/' . $name . '.php')) {
36
            require_once $hnd_file;
37
        }
38
        $class = 'Xoops' . ucfirst($name) . 'Handler';
39
        if (class_exists($class)) {
40
            $xoopsDB         = XoopsDatabaseFactory::getDatabaseConnection();
41
            $handlers[$name] = new $class($xoopsDB);
42
        }
43
    }
44
    if (!isset($handlers[$name])) {
45
        trigger_error('Class <strong>' . $class . '</strong> does not exist<br>Handler Name: ' . $name, $optional ? E_USER_WARNING : E_USER_ERROR);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $class does not seem to be defined for all execution paths leading up to this point.
Loading history...
46
    }
47
    if (isset($handlers[$name])) {
48
        return $handlers[$name];
49
    }
50
    $inst = false;
51
52
    return $inst;
53
}
54
55
/**
56
 * xoops_getModuleHandler()
57
 *
58
 * @param mixed $name
59
 * @param mixed $module_dir
60
 * @param mixed $optional
61
 * @return XoopsObjectHandler|false
62
 */
63
function xoops_getModuleHandler($name = null, $module_dir = null, $optional = false)
64
{
65
    static $handlers;
66
    // if $module_dir is not specified
67
    if (!isset($module_dir)) {
68
        // if a module is loaded
69
        if (isset($GLOBALS['xoopsModule']) && is_object($GLOBALS['xoopsModule'])) {
70
            $module_dir = $GLOBALS['xoopsModule']->getVar('dirname', 'n');
71
        } else {
72
            trigger_error('No Module is loaded', E_USER_ERROR);
73
        }
74
    } else {
75
        $module_dir = trim($module_dir);
76
    }
77
    $name = (!isset($name)) ? $module_dir : trim($name);
78
    if (!isset($handlers[$module_dir][$name])) {
79
        if (file_exists($hnd_file = XOOPS_ROOT_PATH . "/modules/{$module_dir}/class/{$name}.php")) {
80
            include_once $hnd_file;
81
        }
82
        $class = ucfirst(strtolower($module_dir)) . ucfirst($name) . 'Handler';
83
        if (class_exists($class)) {
84
            $xoopsDB                      = XoopsDatabaseFactory::getDatabaseConnection();
85
            $handlers[$module_dir][$name] = new $class($xoopsDB);
86
        }
87
    }
88
    if (!isset($handlers[$module_dir][$name])) {
89
        trigger_error('Handler does not exist<br>Module: ' . $module_dir . '<br>Name: ' . $name, $optional ? E_USER_WARNING : E_USER_ERROR);
90
    }
91
    if (isset($handlers[$module_dir][$name])) {
92
        return $handlers[$module_dir][$name];
93
    }
94
    $inst = false;
95
96
    return $inst;
97
}
98
99
/**
100
 * XOOPS class loader wrapper
101
 *
102
 * Temporay solution for XOOPS 2.3
103
 *
104
 * @param string $name                                          Name of class to be loaded
105
 * @param string $type                                          domain of the class, potential values:   core - located in /class/;
106
 *                                                              framework - located in /Frameworks/;
107
 *                                                              other - module class, located in /modules/[$type]/class/
108
 *
109
 * @return boolean
110
 */
111
function xoops_load($name, $type = 'core')
112
{
113
    if (!class_exists('XoopsLoad')) {
114
        require_once XOOPS_ROOT_PATH . '/class/xoopsload.php';
115
    }
116
117
    return XoopsLoad::load($name, $type);
118
}
119
120
/**
121
 * XOOPS language loader wrapper
122
 *
123
 * Temporay solution, not encouraged to use
124
 *
125
 * @param   string $name     Name of language file to be loaded, without extension
126
 * @param   string $domain   Module dirname; global language file will be loaded if $domain is set to 'global' or not specified
127
 * @param   string $language Language to be loaded, current language content will be loaded if not specified
128
 * @return  boolean
129
 * @todo    expand domain to multiple categories, e.g. module:system, framework:filter, etc.
130
 *
131
 */
132
function xoops_loadLanguage($name, $domain = '', $language = null)
133
{
134
    /**
135
     * Set pageType
136
     */
137
    if ($name === 'pagetype') {
138
        $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

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

680
    /** @scrutinizer ignore-call */ 
681
    $bresult = $db->query('SELECT COUNT(*) FROM ' . $db->prefix('banner'));
Loading history...
681
    list($numrows) = $db->fetchRow($bresult);
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

681
    /** @scrutinizer ignore-call */ 
682
    list($numrows) = $db->fetchRow($bresult);
Loading history...
682
    if ($numrows > 1) {
683
        --$numrows;
684
        $bannum = mt_rand(0, $numrows);
685
    } else {
686
        $bannum = 0;
687
    }
688
    if ($numrows > 0) {
689
        $bresult = $db->query('SELECT * FROM ' . $db->prefix('banner'), 1, $bannum);
690
        list($bid, $cid, $imptotal, $impmade, $clicks, $imageurl, $clickurl, $date, $htmlbanner, $htmlcode) = $db->fetchRow($bresult);
691
        if ($xoopsConfig['my_ip'] == xoops_getenv('REMOTE_ADDR')) {
692
            // EMPTY
693
        } else {
694
            ++$impmade;
695
            $db->queryF(sprintf('UPDATE %s SET impmade = %u WHERE bid = %u', $db->prefix('banner'), $impmade, $bid));
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

695
            $db->/** @scrutinizer ignore-call */ 
696
                 queryF(sprintf('UPDATE %s SET impmade = %u WHERE bid = %u', $db->prefix('banner'), $impmade, $bid));
Loading history...
696
            /**
697
             * Check if this impression is the last one
698
             */
699
            if ($imptotal > 0 && $impmade >= $imptotal) {
700
                $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

700
                /** @scrutinizer ignore-call */ 
701
                $newid = $db->genId($db->prefix('bannerfinish') . '_bid_seq');
Loading history...
701
                $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());
702
                $db->queryF($sql);
703
                $db->queryF(sprintf('DELETE FROM %s WHERE bid = %u', $db->prefix('banner'), $bid));
704
            }
705
        }
706
        /**
707
         * Print the banner
708
         */
709
        $bannerobject = '';
710
        if ($htmlbanner) {
711
            if ($htmlcode) {
712
                $bannerobject = $htmlcode;
713
            } else {
714
                $bannerobject = $bannerobject . '<div id="xo-bannerfix">';
715
                // $bannerobject = $bannerobject . '<div id="xo-fixbanner">';
716
                $bannerobject = $bannerobject . ' <iframe src=' . $imageurl . ' border="0" scrolling="no" allowtransparency="true" width="480px" height="60px" style="border:0" alt="' . $clickurl . ';"> </iframe>';
717
                $bannerobject .= '</div>';
718
                // $bannerobject .= '</div>';
719
            }
720
        } else {
721
            $bannerobject = '<div id="xo-bannerfix">';
722
            if (false !== stripos($imageurl, '.swf')) {
723
                $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>';
724
            } else {
725
                $bannerobject = $bannerobject . '<a href="' . XOOPS_URL . '/banners.php?op=click&amp;bid=' . $bid . '" rel="external" title="' . $clickurl . '"><img src="' . $imageurl . '" alt="' . $clickurl . '" /></a>';
726
            }
727
728
            $bannerobject .= '</div>';
729
        }
730
731
        return $bannerobject;
732
    }
733
    return null;
734
}
735
736
/**
737
 * Function to redirect a user to certain pages
738
 * @param        $url
739
 * @param int    $time
740
 * @param string $message
741
 * @param bool   $addredirect
742
 * @param bool   $allowExternalLink
743
 */
744
function redirect_header($url, $time = 3, $message = '', $addredirect = true, $allowExternalLink = false)
745
{
746
    global $xoopsConfig, $xoopsLogger, $xoopsUserIsAdmin;
747
748
    $xoopsPreload = XoopsPreload::getInstance();
749
    $xoopsPreload->triggerEvent('core.include.functions.redirectheader.start', array($url, $time, $message, $addredirect, $allowExternalLink));
750
    // under normal circumstance this event will exit, so listen for the .start above
751
    $xoopsPreload->triggerEvent('core.include.functions.redirectheader', array($url, $time, $message, $addredirect, $allowExternalLink));
752
753
    if (preg_match("/[\\0-\\31]|about:|script:/i", $url)) {
754
        if (!preg_match('/^\b(java)?script:([\s]*)history\.go\(-\d*\)([\s]*[;]*[\s]*)$/si', $url)) {
755
            $url = XOOPS_URL;
756
        }
757
    }
758
    if (!$allowExternalLink && $pos = strpos($url, '://')) {
759
        $xoopsLocation = substr(XOOPS_URL, strpos(XOOPS_URL, '://') + 3);
760
        if (strcasecmp(substr($url, $pos + 3, strlen($xoopsLocation)), $xoopsLocation)) {
761
            $url = XOOPS_URL;
762
        }
763
    }
764
    if (defined('XOOPS_CPFUNC_LOADED')) {
765
        $theme = 'default';
766
    } else {
767
        $theme = $xoopsConfig['theme_set'];
768
    }
769
770
    require_once XOOPS_ROOT_PATH . '/class/template.php';
771
    require_once XOOPS_ROOT_PATH . '/class/theme.php';
772
    $xoopsThemeFactory                = null;
0 ignored issues
show
Unused Code introduced by
The assignment to $xoopsThemeFactory is dead and can be removed.
Loading history...
773
    $xoopsThemeFactory                = new xos_opal_ThemeFactory();
774
    $xoopsThemeFactory->allowedThemes = $xoopsConfig['theme_set_allowed'];
775
    $xoopsThemeFactory->defaultTheme  = $theme;
776
    $xoTheme                          = $xoopsThemeFactory->createInstance(array(
777
                                                                                'plugins'      => array(),
778
                                                                                'renderBanner' => false));
779
    $xoopsTpl                         = $xoTheme->template;
780
    $xoopsTpl->assign(array(
781
                          'xoops_theme'      => $theme,
782
                          'xoops_imageurl'   => XOOPS_THEME_URL . '/' . $theme . '/',
783
                          'xoops_themecss'   => xoops_getcss($theme),
784
                          'xoops_requesturi' => htmlspecialchars($_SERVER['REQUEST_URI'], ENT_QUOTES),
785
                          'xoops_sitename'   => htmlspecialchars($xoopsConfig['sitename'], ENT_QUOTES),
786
                          'xoops_slogan'     => htmlspecialchars($xoopsConfig['slogan'], ENT_QUOTES),
787
                          '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...
788
                          'xoops_pagetitle'  => isset($xoopsModule) && is_object($xoopsModule) ? $xoopsModule->getVar('name') : htmlspecialchars($xoopsConfig['slogan'], ENT_QUOTES)));
789
    if ($xoopsConfig['debug_mode'] == 2 && $xoopsUserIsAdmin) {
790
        $xoopsTpl->assign('time', 300);
791
        $xoopsTpl->assign('xoops_logdump', $xoopsLogger->dump());
792
    } else {
793
        $xoopsTpl->assign('time', (int)$time);
794
    }
795
    if (!empty($_SERVER['REQUEST_URI']) && $addredirect && false !== strpos($url, 'user.php')) {
796
        if (false === strpos($url, '?')) {
797
            $url .= '?xoops_redirect=' . urlencode($_SERVER['REQUEST_URI']);
798
        } else {
799
            $url .= '&amp;xoops_redirect=' . urlencode($_SERVER['REQUEST_URI']);
800
        }
801
    }
802
    if (defined('SID') && SID && (!isset($_COOKIE[session_name()]) || ($xoopsConfig['use_mysession'] && $xoopsConfig['session_name'] != '' && !isset($_COOKIE[$xoopsConfig['session_name']])))) {
803
        if (false === strpos($url, '?')) {
804
            $url .= '?' . SID;
805
        } else {
806
            $url .= '&amp;' . SID;
807
        }
808
    }
809
    $url = preg_replace('/&amp;/i', '&', htmlspecialchars($url, ENT_QUOTES));
810
    $xoopsTpl->assign('url', $url);
811
    $message = trim($message) != '' ? $message : _TAKINGBACK;
812
    $xoopsTpl->assign('message', $message);
813
    $xoopsTpl->assign('lang_ifnotreload', sprintf(_IFNOTRELOAD, $url));
814
815
    $xoopsTpl->display('db:system_redirect.tpl');
816
    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...
817
}
818
819
/**
820
 * xoops_getenv()
821
 *
822
 * @param mixed $key
823
 * @return string
824
 */
825
function xoops_getenv($key)
826
{
827
    $ret = '';
828
    if (array_key_exists($key, $_SERVER) && isset($_SERVER[$key])) {
829
        $ret = $_SERVER[$key];
830
831
        return $ret;
832
    }
833
    if (array_key_exists($key, $_ENV) && isset($_ENV[$key])) {
834
        $ret = $_ENV[$key];
835
836
        return $ret;
837
    }
838
839
    return $ret;
840
}
841
842
/**
843
 * Function to get css file for a certain themeset
844
 * @param string $theme
845
 * @return string
846
 */
847
function xoops_getcss($theme = '')
848
{
849
    if ($theme == '') {
850
        $theme = $GLOBALS['xoopsConfig']['theme_set'];
851
    }
852
    $uagent  = xoops_getenv('HTTP_USER_AGENT');
853
    $str_css = 'styleNN.css';
854
    if (false !== stripos($uagent, 'mac')) {
855
        $str_css = 'styleMAC.css';
856
    } elseif (preg_match("/MSIE (\d\.\d{1,2})/i", $uagent)) {
857
        $str_css = 'style.css';
858
    }
859
    if (is_dir(XOOPS_THEME_PATH . '/' . $theme)) {
860
        if (file_exists(XOOPS_THEME_PATH . '/' . $theme . '/' . $str_css)) {
861
            return XOOPS_THEME_URL . '/' . $theme . '/' . $str_css;
862
        } elseif (file_exists(XOOPS_THEME_PATH . '/' . $theme . '/style.css')) {
863
            return XOOPS_THEME_URL . '/' . $theme . '/style.css';
864
        }
865
    }
866
    if (is_dir(XOOPS_THEME_PATH . '/' . $theme . '/css')) {
867
        if (file_exists(XOOPS_THEME_PATH . '/' . $theme . '/css/' . $str_css)) {
868
            return XOOPS_THEME_URL . '/' . $theme . '/css/' . $str_css;
869
        } elseif (file_exists(XOOPS_THEME_PATH . '/' . $theme . '/css/style.css')) {
870
            return XOOPS_THEME_URL . '/' . $theme . '/css/style.css';
871
        }
872
    }
873
874
    return '';
875
}
876
877
/**
878
 * xoops_getMailer()
879
 *
880
 * @return \XoopsMailer|\XoopsMailerLocal
881
 */
882
function xoops_getMailer()
883
{
884
    static $mailer;
885
    global $xoopsConfig;
886
    if (is_object($mailer)) {
887
        return $mailer;
888
    }
889
    include_once XOOPS_ROOT_PATH . '/class/xoopsmailer.php';
890
    if (file_exists($file = XOOPS_ROOT_PATH . '/language/' . $xoopsConfig['language'] . '/xoopsmailerlocal.php')) {
891
        include_once $file;
892
    } elseif (file_exists($file = XOOPS_ROOT_PATH . '/language/english/xoopsmailerlocal.php')) {
893
        include_once $file;
894
    }
895
    unset($mailer);
896
    if (class_exists('XoopsMailerLocal')) {
897
        $mailer = new XoopsMailerLocal();
898
    } else {
899
        $mailer = new XoopsMailer();
900
    }
901
902
    return $mailer;
903
}
904
905
/**
906
 * xoops_getrank()
907
 *
908
 * @param integer $rank_id
909
 * @param mixed   $posts
910
 * @return
911
 */
912
function xoops_getrank($rank_id = 0, $posts = 0)
913
{
914
    $db      = XoopsDatabaseFactory::getDatabaseConnection();
915
    $myts    = MyTextSanitizer::getInstance();
916
    $rank_id = (int)$rank_id;
917
    $posts   = (int)$posts;
918
    if ($rank_id != 0) {
919
        $sql = 'SELECT rank_title AS title, rank_image AS image FROM ' . $db->prefix('ranks') . ' WHERE rank_id = ' . $rank_id;
920
    } else {
921
        $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';
922
    }
923
    $rank          = $db->fetchArray($db->query($sql));
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

923
    /** @scrutinizer ignore-call */ 
924
    $rank          = $db->fetchArray($db->query($sql));
Loading history...
924
    $rank['title'] = $myts->htmlSpecialChars($rank['title']);
925
    $rank['id']    = $rank_id;
926
927
    return $rank;
928
}
929
930
/**
931
 * 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.
932
 *
933
 * @param string $str
934
 * @param int    $start
935
 * @param int    $length
936
 * @param string $trimmarker
937
 * @return string
938
 */
939
function xoops_substr($str, $start, $length, $trimmarker = '...')
940
{
941
    xoops_load('XoopsLocal');
942
943
    return XoopsLocal::substr($str, $start, $length, $trimmarker);
944
}
945
946
// RMV-NOTIFY
947
// ################ Notification Helper Functions ##################
948
// We want to be able to delete by module, by user, or by item.
949
// How do we specify this??
950
/**
951
 * @param $module_id
952
 *
953
 * @return mixed
954
 */
955
function xoops_notification_deletebymodule($module_id)
956
{
957
    $notification_handler = xoops_getHandler('notification');
958
959
    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

959
    return $notification_handler->/** @scrutinizer ignore-call */ unsubscribeByModule($module_id);
Loading history...
960
}
961
962
/**
963
 * xoops_notification_deletebyuser()
964
 *
965
 * @param mixed $user_id
966
 * @return
967
 */
968
function xoops_notification_deletebyuser($user_id)
969
{
970
    $notification_handler = xoops_getHandler('notification');
971
972
    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

972
    return $notification_handler->/** @scrutinizer ignore-call */ unsubscribeByUser($user_id);
Loading history...
973
}
974
975
/**
976
 * xoops_notification_deletebyitem()
977
 *
978
 * @param mixed $module_id
979
 * @param mixed $category
980
 * @param mixed $item_id
981
 * @return
982
 */
983
function xoops_notification_deletebyitem($module_id, $category, $item_id)
984
{
985
    $notification_handler = xoops_getHandler('notification');
986
987
    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

987
    return $notification_handler->/** @scrutinizer ignore-call */ unsubscribeByItem($module_id, $category, $item_id);
Loading history...
988
}
989
990
/**
991
 * xoops_comment_count()
992
 *
993
 * @param mixed $module_id
994
 * @param mixed $item_id
995
 * @return
996
 */
997
function xoops_comment_count($module_id, $item_id = null)
998
{
999
    /** @var \XoopsCommentHandler $comment_handler */
1000
    $comment_handler = xoops_getHandler('comment');
1001
    $criteria        = new CriteriaCompo(new Criteria('com_modid', (int)$module_id));
1002
    if (isset($item_id)) {
1003
        $criteria->add(new Criteria('com_itemid', (int)$item_id));
1004
    }
1005
1006
    return $comment_handler->getCount($criteria);
1007
}
1008
1009
/**
1010
 * xoops_comment_delete()
1011
 *
1012
 * @param mixed $module_id
1013
 * @param mixed $item_id
1014
 * @return bool
1015
 */
1016
function xoops_comment_delete($module_id, $item_id)
1017
{
1018
    if ((int)$module_id > 0 && (int)$item_id > 0) {
1019
        /** @var \XoopsCommentHandler $comment_handler */
1020
        $comment_handler = xoops_getHandler('comment');
1021
        $comments        = $comment_handler->getByItemId($module_id, $item_id);
1022
        if (is_array($comments)) {
0 ignored issues
show
introduced by
The condition is_array($comments) is always true.
Loading history...
1023
            $count       = count($comments);
1024
            $deleted_num = array();
1025
            for ($i = 0; $i < $count; ++$i) {
1026
                if (false !== $comment_handler->delete($comments[$i])) {
1027
                    // store poster ID and deleted post number into array for later use
1028
                    $poster_id = $comments[$i]->getVar('com_uid');
1029
                    if ($poster_id != 0) {
1030
                        $deleted_num[$poster_id] = !isset($deleted_num[$poster_id]) ? 1 : ($deleted_num[$poster_id] + 1);
1031
                    }
1032
                }
1033
            }
1034
            /* @var XoopsMemberHandler $member_handler */
1035
            $member_handler = xoops_getHandler('member');
1036
            foreach ($deleted_num as $user_id => $post_num) {
1037
                // update user posts
1038
                $com_poster = $member_handler->getUser($user_id);
1039
                if (is_object($com_poster)) {
1040
                    $member_handler->updateUserByField($com_poster, 'posts', $com_poster->getVar('posts') - $post_num);
1041
                }
1042
            }
1043
1044
            return true;
1045
        }
1046
    }
1047
1048
    return false;
1049
}
1050
1051
/**
1052
 * xoops_groupperm_deletebymoditem()
1053
 *
1054
 * Group Permission Helper Functions
1055
 *
1056
 * @param mixed $module_id
1057
 * @param mixed $perm_name
1058
 * @param mixed $item_id
1059
 * @return bool
1060
 */
1061
function xoops_groupperm_deletebymoditem($module_id, $perm_name, $item_id = null)
1062
{
1063
    // do not allow system permissions to be deleted
1064
    if ((int)$module_id <= 1) {
1065
        return false;
1066
    }
1067
    /* @var  XoopsGroupPermHandler $gperm_handler */
1068
    $gperm_handler = xoops_getHandler('groupperm');
1069
1070
    return $gperm_handler->deleteByModule($module_id, $perm_name, $item_id);
1071
}
1072
1073
/**
1074
 * xoops_utf8_encode()
1075
 *
1076
 * @param mixed $text
1077
 * @return string
1078
 */
1079
function xoops_utf8_encode(&$text)
1080
{
1081
    xoops_load('XoopsLocal');
1082
1083
    return XoopsLocal::utf8_encode($text);
1084
}
1085
1086
/**
1087
 * xoops_convert_encoding()
1088
 *
1089
 * @param mixed $text
1090
 * @return string
1091
 */
1092
function xoops_convert_encoding(&$text)
1093
{
1094
    return xoops_utf8_encode($text);
1095
}
1096
1097
/**
1098
 * xoops_trim()
1099
 *
1100
 * @param mixed $text
1101
 * @return string
1102
 */
1103
function xoops_trim($text)
1104
{
1105
    xoops_load('XoopsLocal');
1106
1107
    return XoopsLocal::trim($text);
1108
}
1109
1110
/**
1111
 * YOU SHOULD NOT USE THIS METHOD, IT WILL BE REMOVED
1112
 */
1113
/**
1114
 * xoops_getOption()
1115
 *
1116
 * @param mixed $option
1117
 * @internal param string $type
1118
 * @deprecated
1119
 * @return string
1120
 */
1121
function xoops_getOption($option)
1122
{
1123
    $ret = '';
1124
    if (isset($GLOBALS['xoopsOption'][$option])) {
1125
        $ret = $GLOBALS['xoopsOption'][$option];
1126
    }
1127
1128
    return $ret;
1129
}
1130
1131
/**
1132
 * YOU SHOULD NOT USE THIS METHOD, IT WILL BE REMOVED
1133
 */
1134
/**
1135
 * xoops_getConfigOption()
1136
 *
1137
 * @param mixed  $option
1138
 * @param array|string $type
1139
 * @internal param string $dirname
1140
 * @deprecated
1141
 * @return bool
1142
 */
1143
function xoops_getConfigOption($option, $type = 'XOOPS_CONF')
1144
{
1145
    static $coreOptions = array();
1146
1147
    if (is_array($coreOptions) && array_key_exists($option, $coreOptions)) {
1148
        return $coreOptions[$option];
1149
    }
1150
    $ret            = false;
1151
    /* @var XoopsConfigHandler $config_handler */
1152
    $config_handler = xoops_getHandler('config');
1153
    $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

1153
    $configs        = $config_handler->getConfigsByCat(/** @scrutinizer ignore-type */ is_array($type) ? $type : constant($type));
Loading history...
1154
    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...
1155
        if (isset($configs[$option])) {
1156
            $ret = $configs[$option];
1157
        }
1158
    }
1159
    $coreOptions[$option] = $ret;
1160
1161
    return $ret;
1162
}
1163
1164
/**
1165
 * YOU SHOULD NOT USE THIS METHOD, IT WILL BE REMOVED
1166
 */
1167
/**
1168
 * xoops_setConfigOption()
1169
 *
1170
 * @param mixed $option
1171
 * @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...
1172
 * @return void
1173
@deprecated
1174
 */
1175
function xoops_setConfigOption($option, $new = null)
1176
{
1177
    if (isset($GLOBALS['xoopsConfig'][$option]) && null !== $new) {
0 ignored issues
show
introduced by
The condition null !== $new is always false.
Loading history...
1178
        $GLOBALS['xoopsConfig'][$option] = $new;
1179
    }
1180
}
1181
1182
/**
1183
 * YOU SHOULD NOT USE THIS METHOD, IT WILL BE REMOVED
1184
 */
1185
/**
1186
 * xoops_getModuleOption
1187
 *
1188
 * Method for module developers getting a module config item. This could be from any module requested.
1189
 *
1190
 * @param mixed  $option
1191
 * @param string $dirname
1192
 * @return bool
1193
@deprecated
1194
 */
1195
function xoops_getModuleOption($option, $dirname = '')
1196
{
1197
    static $modOptions = array();
1198
    if (is_array($modOptions) && isset($modOptions[$dirname][$option])) {
1199
        return $modOptions[$dirname][$option];
1200
    }
1201
1202
    $ret            = false;
1203
    /* @var XoopsModuleHandler $module_handler */
1204
    $module_handler = xoops_getHandler('module');
1205
    $module         = $module_handler->getByDirname($dirname);
1206
    /* @var XoopsConfigHandler $config_handler */
1207
    $config_handler = xoops_getHandler('config');
1208
    if (is_object($module)) {
1209
        $moduleConfig = $config_handler->getConfigsByCat(0, $module->getVar('mid'));
1210
        if (isset($moduleConfig[$option])) {
1211
            $ret = $moduleConfig[$option];
1212
        }
1213
    }
1214
    $modOptions[$dirname][$option] = $ret;
1215
1216
    return $ret;
1217
}
1218
1219
/**
1220
 * Determine the base domain name for a URL. The primary use for this is to set the domain
1221
 * used for cookies to represent any subdomains.
1222
 *
1223
 * The registrable domain is determined using the public suffix list. If the domain is not
1224
 * registrable, an empty string is returned. This empty string can be used in setcookie()
1225
 * as the domain, which restricts cookie to just the current host.
1226
 *
1227
 * @param string $url URL or hostname to process
1228
 *
1229
 * @return string the registrable domain or an empty string
1230
 */
1231
function xoops_getBaseDomain($url)
1232
{
1233
    $parts = parse_url($url);
1234
    $host = '';
1235
    if (!empty($parts['host'])) {
1236
        $host = $parts['host'];
1237
        if (strtolower($host) === 'localhost') {
1238
            return 'localhost';
1239
        }
1240
        // bail if this is an IPv4 address (IPv6 will fail later)
1241
        if (false !== filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
1242
            return '';
1243
        }
1244
        $regdom = new \Geekwright\RegDom\RegisteredDomain();
1245
        $host = $regdom->getRegisteredDomain($host);
1246
    }
1247
    return (null === $host) ? '' : $host;
1248
}
1249
1250
/**
1251
 * YOU SHOULD NOT USE THIS METHOD, IT WILL BE REMOVED
1252
 */
1253
/**
1254
 * Function to get the domain from a URL.
1255
 *
1256
 * @param string $url the URL to be stripped.
1257
 * @return string
1258
 * @deprecated
1259
 */
1260
function xoops_getUrlDomain($url)
1261
{
1262
    $domain = '';
1263
    $_URL   = parse_url($url);
1264
1265
    if (!empty($_URL) || !empty($_URL['host'])) {
1266
        $domain = $_URL['host'];
1267
    }
1268
1269
    return $domain;
1270
}
1271
1272
include_once __DIR__ . '/functions.encoding.php';
1273
include_once __DIR__ . '/functions.legacy.php';
1274