Completed
Push — master ( ddc2b8...394d4a )
by Michael
05:07 queued 02:30
created

class/utility.php (21 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
/*
3
 You may not change or alter any portion of this comment or credits
4
 of supporting developers from this source code or any supporting source code
5
 which is considered copyrighted (c) material of the original comment or credit authors.
6
7
 This program is distributed in the hope that it will be useful,
8
 but WITHOUT ANY WARRANTY; without even the implied warranty of
9
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10
*/
11
12
/**
13
 * xoopstube
14
 *
15
 * @copyright   XOOPS Project (http://xoops.org)
16
 * @license     http://www.fsf.org/copyleft/gpl.html GNU public license
17
 * @author      Hervé Thouzard (http://www.herve-thouzard.com/)
18
 */
19
20
/**
21
 * A set of useful and common functions
22
 *
23
 * @package       xoopstube
24
 * @author        Hervé Thouzard - Instant Zero (http://xoops.instant-zero.com)
25
 * @copyright (c) Instant Zero
26
 *
27
 * Note: You should be able to use it without the need to instantiate it.
28
 *
29
 */
30
// defined('XOOPS_ROOT_PATH') || die('XOOPS Root Path not defined');
31
32
use WideImage\WideImage;
33
34
/**
35
 * Class XoopstubeUtility
36
 */
37
class XoopstubeUtility
38
{
39
    const MODULE_NAME = 'xoopstube';
40
41
    /**
42
     * Access the only instance of this class
43
     *
44
     * @return object
45
     *
46
     * @static
47
     * @staticvar   object
48
     */
49
    public static function getInstance()
50
    {
51
        static $instance;
52
        if (null === $instance) {
53
            $instance = new static();
54
        }
55
56
        return $instance;
57
    }
58
59
    /**
60
     * Returns a module's option (with cache)
61
     *
62
     * @param string  $option    module option's name
63
     * @param boolean $withCache Do we have to use some cache ?
64
     *
65
     * @return mixed option's value
66
     */
67
    public static function getModuleOption($option, $withCache = true)
68
    {
69
        global $xoopsModuleConfig, $xoopsModule;
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...
70
        $repmodule = self::MODULE_NAME;
71
        static $options = array();
72
        if (is_array($options) && array_key_exists($option, $options) && $withCache) {
73
            return $options[$option];
74
        }
75
76
        $retval = false;
77
        if (isset($xoopsModuleConfig)
78
            && (is_object($xoopsModule) && $xoopsModule->getVar('dirname') == $repmodule
79
                && $xoopsModule->getVar('isactive'))
80
        ) {
81
            if (isset($xoopsModuleConfig[$option])) {
82
                $retval = $xoopsModuleConfig[$option];
83
            }
84
        } else {
85
            /** @var XoopsModuleHandler $moduleHandler */
86
            $moduleHandler  = xoops_getHandler('module');
87
            $module         = $moduleHandler->getByDirname($repmodule);
88
            $configHandler = xoops_getHandler('config');
89
            if ($module) {
90
                $moduleConfig = $configHandler->getConfigsByCat(0, $module->getVar('mid'));
91
                if (isset($moduleConfig[$option])) {
92
                    $retval = $moduleConfig[$option];
93
                }
94
            }
95
        }
96
        $options[$option] = $retval;
97
98
        return $retval;
99
    }
100
101
    /**
102
     * Is Xoops 2.3.x ?
103
     *
104
     * @return boolean
105
     */
106 View Code Duplication
    public static function isX23()
107
    {
108
        $x23 = false;
109
        $xv  = str_replace('XOOPS ', '', XOOPS_VERSION);
110
        if ((int)substr($xv, 2, 1) >= 3) {
111
            $x23 = true;
112
        }
113
114
        return $x23;
115
    }
116
117
    /**
118
     * Is Xoops 2.0.x ?
119
     *
120
     * @return boolean
121
     */
122 View Code Duplication
    public static function isX20()
123
    {
124
        $x20 = false;
125
        $xv  = str_replace('XOOPS ', '', XOOPS_VERSION);
126
        if (substr($xv, 2, 1) == '0') {
127
            $x20 = true;
128
        }
129
130
        return $x20;
131
    }
132
133
    /**
134
     * Create (in a link) a javascript confirmation's box
135
     *
136
     * @param string  $message Message to display
137
     * @param boolean $form    Is this a confirmation for a form ?
138
     *
139
     * @return string the javascript code to insert in the link (or in the form)
140
     */
141
    public static function javascriptLinkConfirm($message, $form = false)
142
    {
143
        if (!$form) {
144
            return "onclick=\"javascript:return confirm('" . str_replace("'", ' ', $message) . "')\"";
145
        } else {
146
            return "onSubmit=\"javascript:return confirm('" . str_replace("'", ' ', $message) . "')\"";
147
        }
148
    }
149
150
    /**
151
     * Get current user IP
152
     *
153
     * @return string IP address (format Ipv4)
154
     */
155
    public static function IP()
156
    {
157
        $proxy_ip = '';
158
        if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
159
            $proxy_ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
160
        } elseif (!empty($_SERVER['HTTP_X_FORWARDED'])) {
161
            $proxy_ip = $_SERVER['HTTP_X_FORWARDED'];
162
        } elseif (!empty($_SERVER['HTTP_FORWARDED_FOR'])) {
163
            $proxy_ip = $_SERVER['HTTP_FORWARDED_FOR'];
164
        } elseif (!empty($_SERVER['HTTP_FORWARDED'])) {
165
            $proxy_ip = $_SERVER['HTTP_FORWARDED'];
166
        } elseif (!empty($_SERVER['HTTP_VIA'])) {
167
            $proxy_ip = $_SERVER['HTTP_VIA'];
168
        } elseif (!empty($_SERVER['HTTP_X_COMING_FROM'])) {
169
            $proxy_ip = $_SERVER['HTTP_X_COMING_FROM'];
170
        } elseif (!empty($_SERVER['HTTP_COMING_FROM'])) {
171
            $proxy_ip = $_SERVER['HTTP_COMING_FROM'];
172
        }
173
        $regs = array();
174
        //if (!empty($proxy_ip) && $is_ip = ereg('^([0-9]{1,3}\.){3,3}[0-9]{1,3}', $proxy_ip, $regs) && count($regs) > 0) {
175
        if (!empty($proxy_ip) && filter_var($proxy_ip, FILTER_VALIDATE_IP) && count($regs) > 0) {
176
            $the_IP = $regs[0];
177
        } else {
178
            $the_IP = $_SERVER['REMOTE_ADDR'];
179
        }
180
181
        return $the_IP;
182
    }
183
184
    /**
185
     * Set the page's title, meta description and meta keywords
186
     * Datas are supposed to be sanitized
187
     *
188
     * @param string $pageTitle       Page's Title
189
     * @param string $metaDescription Page's meta description
190
     * @param string $metaKeywords    Page's meta keywords
191
     *
192
     * @return void
193
     */
194
    public static function setMetas($pageTitle = '', $metaDescription = '', $metaKeywords = '')
195
    {
196
        global $xoTheme, $xoTheme, $xoopsTpl;
197
        $xoopsTpl->assign('xoops_pagetitle', $pageTitle);
198
        if (isset($xoTheme) && is_object($xoTheme)) {
199
            if (!empty($metaKeywords)) {
200
                $xoTheme->addMeta('meta', 'keywords', $metaKeywords);
201
            }
202
            if (!empty($metaDescription)) {
203
                $xoTheme->addMeta('meta', 'description', $metaDescription);
204
            }
205
        } elseif (isset($xoopsTpl) && is_object($xoopsTpl)) { // Compatibility for old Xoops versions
206
            if (!empty($metaKeywords)) {
207
                $xoopsTpl->assign('xoops_meta_keywords', $metaKeywords);
208
            }
209
            if (!empty($metaDescription)) {
210
                $xoopsTpl->assign('xoops_meta_description', $metaDescription);
211
            }
212
        }
213
    }
214
215
    /**
216
     * Send an email from a template to a list of recipients
217
     *
218
     * @param        $tplName
219
     * @param array  $recipients List of recipients
220
     * @param string $subject    Email's subject
221
     * @param array  $variables  Varirables to give to the template
222
     *
223
     * @internal param string $tpl_name Template's name
224
     * @return boolean Result of the send
225
     */
226
    public static function sendEmailFromTpl($tplName, $recipients, $subject, $variables)
227
    {
228
        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...
229
        require_once XOOPS_ROOT_PATH . '/class/xoopsmailer.php';
230
        if (!is_array($recipients)) {
231
            if (trim($recipients) == '') {
232
                return false;
233
            }
234
        } else {
235
            if (count($recipients) == 0) {
236
                return false;
237
            }
238
        }
239
        if (function_exists('xoops_getMailer')) {
240
            $xoopsMailer =& xoops_getMailer();
241
        } else {
242
            $xoopsMailer =& getMailer();
243
        }
244
245
        $xoopsMailer->useMail();
246
        $templateDir = XOOPS_ROOT_PATH . '/modules/' . self::MODULE_NAME . '/language/' . $xoopsConfig['language'] . '/mail_template';
247
        if (!is_dir($templateDir)) {
248
            $templateDir = XOOPS_ROOT_PATH . '/modules/' . self::MODULE_NAME . '/language/english/mail_template';
249
        }
250
        $xoopsMailer->setTemplateDir($templateDir);
251
        $xoopsMailer->setTemplate($tplName);
252
        $xoopsMailer->setToEmails($recipients);
253
        // TODO: Change !
254
        // $xoopsMailer->setFromEmail('[email protected]');
255
        //$xoopsMailer->setFromName('MonSite');
256
        $xoopsMailer->setSubject($subject);
257
        foreach ($variables as $key => $value) {
258
            $xoopsMailer->assign($key, $value);
259
        }
260
        $res = $xoopsMailer->send();
261
        unset($xoopsMailer);
262
        $filename = XOOPS_UPLOAD_PATH . '/logmail_' . self::MODULE_NAME . '.php';
263
        if (!file_exists($filename)) {
264
            $fp = @fopen($filename, 'a');
265
            if ($fp) {
266
                fwrite($fp, "<?php exit(); ?>\n");
267
                fclose($fp);
268
            }
269
        }
270
        $fp = @fopen($filename, 'a');
271
272
        if ($fp) {
273
            fwrite($fp, str_repeat('-', 120) . "\n");
274
            fwrite($fp, date('d/m/Y H:i:s') . "\n");
275
            fwrite($fp, 'Template name : ' . $tplName . "\n");
276
            fwrite($fp, 'Email subject : ' . $subject . "\n");
277
            if (is_array($recipients)) {
278
                fwrite($fp, 'Recipient(s) : ' . implode(',', $recipients) . "\n");
279
            } else {
280
                fwrite($fp, 'Recipient(s) : ' . $recipients . "\n");
281
            }
282
            fwrite($fp, 'Transmited variables : ' . implode(',', $variables) . "\n");
283
            fclose($fp);
284
        }
285
286
        return $res;
287
    }
288
289
    /**
290
     * Remove module's cache
291
     */
292
    public static function updateCache()
293
    {
294
        global $xoopsModule;
295
        $folder  = $xoopsModule->getVar('dirname');
296
        $tpllist = array();
297
        require_once XOOPS_ROOT_PATH . '/class/xoopsblock.php';
298
        require_once XOOPS_ROOT_PATH . '/class/template.php';
299
        $tplfileHandler = xoops_getHandler('tplfile');
300
        $tpllist         = $tplfileHandler->find(null, null, null, $folder);
301
        xoops_template_clear_module_cache($xoopsModule->getVar('mid')); // Clear module's blocks cache
302
303
        foreach ($tpllist as $onetemplate) { // Remove cache for each page.
304
            if ($onetemplate->getVar('tpl_type') === 'module') {
305
                //  Note, I've been testing all the other methods (like the one of Smarty) and none of them run, that's why I have used this code
306
                $files_del = array();
0 ignored issues
show
$files_del 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...
307
                $files_del = glob(XOOPS_CACHE_PATH . '/*' . $onetemplate->getVar('tpl_file') . '*');
308
                if (count($files_del) > 0 && is_array($files_del)) {
309
                    foreach ($files_del as $one_file) {
310
                        if (is_file($one_file)) {
311
                            unlink($one_file);
312
                        }
313
                    }
314
                }
315
            }
316
        }
317
    }
318
319
    /**
320
     * Redirect user with a message
321
     *
322
     * @param string $message message to display
323
     * @param string $url     The place where to go
324
     * @param        integer  timeout Time to wait before to redirect
325
     */
326
    public static function redirect($message = '', $url = 'index.php', $time = 2)
327
    {
328
        redirect_header($url, $time, $message);
329
        exit();
0 ignored issues
show
Coding Style Compatibility introduced by
The method redirect() 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...
330
    }
331
332
    /**
333
     * Internal function used to get the handler of the current module
334
     *
335
     * @return object The module
336
     */
337
    protected static function _getModule()
338
    {
339
        static $mymodule;
340
        if (!isset($mymodule)) {
341
            global $xoopsModule;
342
            if (isset($xoopsModule) && is_object($xoopsModule) && $xoopsModule->getVar('dirname') == OLEDRION_DIRNAME) {
343
                $mymodule = $xoopsModule;
344
            } else {
345
                $hModule  = xoops_getHandler('module');
346
                $mymodule = $hModule->getByDirname(OLEDRION_DIRNAME);
347
            }
348
        }
349
350
        return $mymodule;
351
    }
352
353
    /**
354
     * Returns the module's name (as defined by the user in the module manager) with cache
355
     *
356
     * @return string Module's name
357
     */
358
    public static function getModuleName()
359
    {
360
        static $moduleName;
361
        if (!isset($moduleName)) {
362
            $mymodule   = self::_getModule();
363
            $moduleName = $mymodule->getVar('name');
364
        }
365
366
        return $moduleName;
367
    }
368
369
    /**
370
     * Create a title for the href tags inside html links
371
     *
372
     * @param string $title Text to use
373
     *
374
     * @return string Formated text
375
     */
376
    public static function makeHrefTitle($title)
377
    {
378
        $s = "\"'";
379
        $r = '  ';
380
381
        return strtr($title, $s, $r);
382
    }
383
384
    /**
385
     * Retourne la liste des utilisateurs appartenants à un groupe
386
     *
387
     * @param int $groupId Searched group
388
     *
389
     * @return array Array of XoopsUsers
390
     */
391
    public static function getUsersFromGroup($groupId)
392
    {
393
        $users          = array();
394
        $memberHandler = xoops_getHandler('member');
395
        $users          = $memberHandler->getUsersByGroup($groupId, true);
396
397
        return $users;
398
    }
399
400
    /**
401
     * Retourne la liste des emails des utilisateurs membres d'un groupe
402
     *
403
     * @param $groupId
404
     *
405
     * @internal param int $group_id Group's number
406
     * @return array Emails list
407
     */
408
    public static function getEmailsFromGroup($groupId)
409
    {
410
        $ret   = array();
411
        $users = self::getUsersFromGroup($groupId);
412
        foreach ($users as $user) {
413
            $ret[] = $user->getVar('email');
414
        }
415
416
        return $ret;
417
    }
418
419
    /**
420
     * Vérifie que l'utilisateur courant fait partie du groupe des administrateurs
421
     *
422
     * @return booleean Admin or not
423
     */
424
    public static function isAdmin()
425
    {
426
        global $xoopsUser, $xoopsModule;
427
        if (is_object($xoopsUser)) {
428
            if (in_array(XOOPS_GROUP_ADMIN, $xoopsUser->getGroups())) {
429
                return true;
430
            } elseif (isset($xoopsModule) && $xoopsUser->isAdmin($xoopsModule->getVar('mid'))) {
431
                return true;
432
            }
433
        }
434
435
        return false;
436
    }
437
438
    /**
439
     * Returns the current date in the Mysql format
440
     *
441
     * @return string Date in the Mysql format
442
     */
443
    public static function getCurrentSQLDate()
444
    {
445
        return date('Y-m-d'); // 2007-05-02
446
    }
447
448
    /**
449
     * @return bool|string
450
     */
451
    public static function getCurrentSQLDateTime()
452
    {
453
        return date('Y-m-d H:i:s'); // 2007-05-02
454
    }
455
456
    /**
457
     * Convert a Mysql date to the human's format
458
     *
459
     * @param string $date The date to convert
460
     * @param string $format
461
     *
462
     * @return string The date in a human form
463
     */
464
    public static function SQLDateToHuman($date, $format = 'l')
465
    {
466
        if ($date != '0000-00-00' && xoops_trim($date) != '') {
467
            return formatTimestamp(strtotime($date), $format);
468
        } else {
469
            return '';
470
        }
471
    }
472
473
    /**
474
     * Convert a timestamp to a Mysql date
475
     *
476
     * @param integer $timestamp The timestamp to use
477
     *
478
     * @return string The date in the Mysql format
479
     */
480
    public static function timestampToMysqlDate($timestamp)
481
    {
482
        return date('Y-m-d', (int)$timestamp);
483
    }
484
485
    /**
486
     * Conversion d'un dateTime Mysql en date lisible en français
487
     *
488
     * @param $dateTime
489
     *
490
     * @return bool|string
491
     */
492
    public static function sqlDateTimeToFrench($dateTime)
493
    {
494
        return date('d/m/Y H:i:s', strtotime($dateTime));
495
    }
496
497
    /**
498
     * Convert a timestamp to a Mysql datetime form
499
     *
500
     * @param integer $timestamp The timestamp to use
501
     *
502
     * @return string The date and time in the Mysql format
503
     */
504
    public static function timestampToMysqlDateTime($timestamp)
505
    {
506
        return date('Y-m-d H:i:s', $timestamp);
507
    }
508
509
    /**
510
     * This function indicates if the current Xoops version needs to add asterisks to required fields in forms
511
     *
512
     * @return boolean Yes = we need to add them, false = no
513
     */
514
    public static function needsAsterisk()
515
    {
516
        if (self::isX23()) {
517
            return false;
518
        }
519
        if (strpos(strtolower(XOOPS_VERSION), 'impresscms') !== false) {
520
            return false;
521
        }
522
        if (strpos(strtolower(XOOPS_VERSION), 'legacy') === false) {
523
            $xv = xoops_trim(str_replace('XOOPS ', '', XOOPS_VERSION));
524
            if ((int)substr($xv, 4, 2) >= 17) {
525
                return false;
526
            }
527
        }
528
529
        return true;
530
    }
531
532
    /**
533
     * Mark the mandatory fields of a form with a star
534
     *
535
     * @param object $sform The form to modify
536
     *
537
     * @internal param string $caracter The character to use to mark fields
538
     * @return object The modified form
539
     */
540
    public static function &formMarkRequiredFields(&$sform)
541
    {
542
        if (self::needsAsterisk()) {
543
            $required = array();
544
            foreach ($sform->getRequired() as $item) {
545
                $required[] = $item->_name;
546
            }
547
            $elements = array();
548
            $elements = $sform->getElements();
549
            $cnt      = count($elements);
550
            for ($i = 0; $i < $cnt; ++$i) {
551
                if (is_object($elements[$i]) && in_array($elements[$i]->_name, $required)) {
552
                    $elements[$i]->_caption .= ' *';
553
                }
554
            }
555
        }
556
557
        return $sform;
558
    }
559
560
    /**
561
     * Create an html heading (from h1 to h6)
562
     *
563
     * @param string  $title The text to use
564
     * @param integer $level Level to return
565
     *
566
     * @return string The heading
567
     */
568
    public static function htitle($title = '', $level = 1)
569
    {
570
        printf('<h%01d>%s</h%01d>', $level, $title, $level);
571
    }
572
573
    /**
574
     * Create a unique upload filename
575
     *
576
     * @param string  $folder   The folder where the file will be saved
577
     * @param string  $fileName Original filename (coming from the user)
578
     * @param boolean $trimName Do we need to create a "short" unique name ?
579
     *
580
     * @return string The unique filename to use (with its extension)
581
     */
582
    public static function createUploadName($folder, $fileName, $trimName = false)
583
    {
584
        $workingfolder = $folder;
585
        if (xoops_substr($workingfolder, strlen($workingfolder) - 1, 1) !== '/') {
586
            $workingfolder .= '/';
587
        }
588
        $ext  = basename($fileName);
589
        $ext  = explode('.', $ext);
590
        $ext  = '.' . $ext[count($ext) - 1];
591
        $true = true;
592
        while ($true) {
593
            $ipbits = explode('.', $_SERVER['REMOTE_ADDR']);
594
            list($usec, $sec) = explode(' ', microtime());
595
            $usec = (integer)($usec * 65536);
596
            $sec  = ((integer)$sec) & 0xFFFF;
597
598
            if ($trimName) {
599
                $uid = sprintf('%06x%04x%04x', ($ipbits[0] << 24) | ($ipbits[1] << 16) | ($ipbits[2] << 8) | $ipbits[3], $sec, $usec);
600
            } else {
601
                $uid = sprintf('%08x-%04x-%04x', ($ipbits[0] << 24) | ($ipbits[1] << 16) | ($ipbits[2] << 8) | $ipbits[3], $sec, $usec);
602
            }
603
            if (!file_exists($workingfolder . $uid . $ext)) {
604
                $true = false;
605
            }
606
        }
607
608
        return $uid . $ext;
609
    }
610
611
    /**
612
     * Replace html entities with their ASCII equivalent
613
     *
614
     * @param string $chaine The string undecode
615
     *
616
     * @return string The undecoded string
617
     */
618
    public static function unhtml($chaine)
619
    {
620
        $search = $replace = array();
621
        $chaine = html_entity_decode($chaine);
622
623
        for ($i = 0; $i <= 255; ++$i) {
624
            $search[]  = '&#' . $i . ';';
625
            $replace[] = chr($i);
626
        }
627
        $replace[] = '...';
628
        $search[]  = '…';
629
        $replace[] = "'";
630
        $search[]  = '‘';
631
        $replace[] = "'";
632
        $search[]  = '’';
633
        $replace[] = '-';
634
        $search[]  = '&bull;'; // $replace[] = '•';
635
        $replace[] = '—';
636
        $search[]  = '&mdash;';
637
        $replace[] = '-';
638
        $search[]  = '&ndash;';
639
        $replace[] = '-';
640
        $search[]  = '&shy;';
641
        $replace[] = '"';
642
        $search[]  = '&quot;';
643
        $replace[] = '&';
644
        $search[]  = '&amp;';
645
        $replace[] = 'ˆ';
646
        $search[]  = '&circ;';
647
        $replace[] = '¡';
648
        $search[]  = '&iexcl;';
649
        $replace[] = '¦';
650
        $search[]  = '&brvbar;';
651
        $replace[] = '¨';
652
        $search[]  = '&uml;';
653
        $replace[] = '¯';
654
        $search[]  = '&macr;';
655
        $replace[] = '´';
656
        $search[]  = '&acute;';
657
        $replace[] = '¸';
658
        $search[]  = '&cedil;';
659
        $replace[] = '¿';
660
        $search[]  = '&iquest;';
661
        $replace[] = '˜';
662
        $search[]  = '&tilde;';
663
        $replace[] = "'";
664
        $search[]  = '&lsquo;'; // $replace[]='‘';
665
        $replace[] = "'";
666
        $search[]  = '&rsquo;'; // $replace[]='’';
667
        $replace[] = '‚';
668
        $search[]  = '&sbquo;';
669
        $replace[] = "'";
670
        $search[]  = '&ldquo;'; // $replace[]='“';
671
        $replace[] = "'";
672
        $search[]  = '&rdquo;'; // $replace[]='”';
673
        $replace[] = '„';
674
        $search[]  = '&bdquo;';
675
        $replace[] = '‹';
676
        $search[]  = '&lsaquo;';
677
        $replace[] = '›';
678
        $search[]  = '&rsaquo;';
679
        $replace[] = '<';
680
        $search[]  = '&lt;';
681
        $replace[] = '>';
682
        $search[]  = '&gt;';
683
        $replace[] = '±';
684
        $search[]  = '&plusmn;';
685
        $replace[] = '«';
686
        $search[]  = '&laquo;';
687
        $replace[] = '»';
688
        $search[]  = '&raquo;';
689
        $replace[] = '×';
690
        $search[]  = '&times;';
691
        $replace[] = '÷';
692
        $search[]  = '&divide;';
693
        $replace[] = '¢';
694
        $search[]  = '&cent;';
695
        $replace[] = '£';
696
        $search[]  = '&pound;';
697
        $replace[] = '¤';
698
        $search[]  = '&curren;';
699
        $replace[] = '¥';
700
        $search[]  = '&yen;';
701
        $replace[] = '§';
702
        $search[]  = '&sect;';
703
        $replace[] = '©';
704
        $search[]  = '&copy;';
705
        $replace[] = '¬';
706
        $search[]  = '&not;';
707
        $replace[] = '®';
708
        $search[]  = '&reg;';
709
        $replace[] = '°';
710
        $search[]  = '&deg;';
711
        $replace[] = 'µ';
712
        $search[]  = '&micro;';
713
        $replace[] = '¶';
714
        $search[]  = '&para;';
715
        $replace[] = '·';
716
        $search[]  = '&middot;';
717
        $replace[] = '†';
718
        $search[]  = '&dagger;';
719
        $replace[] = '‡';
720
        $search[]  = '&Dagger;';
721
        $replace[] = '‰';
722
        $search[]  = '&permil;';
723
        $replace[] = 'Euro';
724
        $search[]  = '&euro;'; // $replace[]='€'
725
        $replace[] = '¼';
726
        $search[]  = '&frac14;';
727
        $replace[] = '½';
728
        $search[]  = '&frac12;';
729
        $replace[] = '¾';
730
        $search[]  = '&frac34;';
731
        $replace[] = '¹';
732
        $search[]  = '&sup1;';
733
        $replace[] = '²';
734
        $search[]  = '&sup2;';
735
        $replace[] = '³';
736
        $search[]  = '&sup3;';
737
        $replace[] = 'á';
738
        $search[]  = '&aacute;';
739
        $replace[] = 'Á';
740
        $search[]  = '&Aacute;';
741
        $replace[] = 'â';
742
        $search[]  = '&acirc;';
743
        $replace[] = 'Â';
744
        $search[]  = '&Acirc;';
745
        $replace[] = 'à';
746
        $search[]  = '&agrave;';
747
        $replace[] = 'À';
748
        $search[]  = '&Agrave;';
749
        $replace[] = 'å';
750
        $search[]  = '&aring;';
751
        $replace[] = 'Å';
752
        $search[]  = '&Aring;';
753
        $replace[] = 'ã';
754
        $search[]  = '&atilde;';
755
        $replace[] = 'Ã';
756
        $search[]  = '&Atilde;';
757
        $replace[] = 'ä';
758
        $search[]  = '&auml;';
759
        $replace[] = 'Ä';
760
        $search[]  = '&Auml;';
761
        $replace[] = 'ª';
762
        $search[]  = '&ordf;';
763
        $replace[] = 'æ';
764
        $search[]  = '&aelig;';
765
        $replace[] = 'Æ';
766
        $search[]  = '&AElig;';
767
        $replace[] = 'ç';
768
        $search[]  = '&ccedil;';
769
        $replace[] = 'Ç';
770
        $search[]  = '&Ccedil;';
771
        $replace[] = 'ð';
772
        $search[]  = '&eth;';
773
        $replace[] = 'Ð';
774
        $search[]  = '&ETH;';
775
        $replace[] = 'é';
776
        $search[]  = '&eacute;';
777
        $replace[] = 'É';
778
        $search[]  = '&Eacute;';
779
        $replace[] = 'ê';
780
        $search[]  = '&ecirc;';
781
        $replace[] = 'Ê';
782
        $search[]  = '&Ecirc;';
783
        $replace[] = 'è';
784
        $search[]  = '&egrave;';
785
        $replace[] = 'È';
786
        $search[]  = '&Egrave;';
787
        $replace[] = 'ë';
788
        $search[]  = '&euml;';
789
        $replace[] = 'Ë';
790
        $search[]  = '&Euml;';
791
        $replace[] = 'ƒ';
792
        $search[]  = '&fnof;';
793
        $replace[] = 'í';
794
        $search[]  = '&iacute;';
795
        $replace[] = 'Í';
796
        $search[]  = '&Iacute;';
797
        $replace[] = 'î';
798
        $search[]  = '&icirc;';
799
        $replace[] = 'Î';
800
        $search[]  = '&Icirc;';
801
        $replace[] = 'ì';
802
        $search[]  = '&igrave;';
803
        $replace[] = 'Ì';
804
        $search[]  = '&Igrave;';
805
        $replace[] = 'ï';
806
        $search[]  = '&iuml;';
807
        $replace[] = 'Ï';
808
        $search[]  = '&Iuml;';
809
        $replace[] = 'ñ';
810
        $search[]  = '&ntilde;';
811
        $replace[] = 'Ñ';
812
        $search[]  = '&Ntilde;';
813
        $replace[] = 'ó';
814
        $search[]  = '&oacute;';
815
        $replace[] = 'Ó';
816
        $search[]  = '&Oacute;';
817
        $replace[] = 'ô';
818
        $search[]  = '&ocirc;';
819
        $replace[] = 'Ô';
820
        $search[]  = '&Ocirc;';
821
        $replace[] = 'ò';
822
        $search[]  = '&ograve;';
823
        $replace[] = 'Ò';
824
        $search[]  = '&Ograve;';
825
        $replace[] = 'º';
826
        $search[]  = '&ordm;';
827
        $replace[] = 'ø';
828
        $search[]  = '&oslash;';
829
        $replace[] = 'Ø';
830
        $search[]  = '&Oslash;';
831
        $replace[] = 'õ';
832
        $search[]  = '&otilde;';
833
        $replace[] = 'Õ';
834
        $search[]  = '&Otilde;';
835
        $replace[] = 'ö';
836
        $search[]  = '&ouml;';
837
        $replace[] = 'Ö';
838
        $search[]  = '&Ouml;';
839
        $replace[] = 'œ';
840
        $search[]  = '&oelig;';
841
        $replace[] = 'Œ';
842
        $search[]  = '&OElig;';
843
        $replace[] = 'š';
844
        $search[]  = '&scaron;';
845
        $replace[] = 'Š';
846
        $search[]  = '&Scaron;';
847
        $replace[] = 'ß';
848
        $search[]  = '&szlig;';
849
        $replace[] = 'þ';
850
        $search[]  = '&thorn;';
851
        $replace[] = 'Þ';
852
        $search[]  = '&THORN;';
853
        $replace[] = 'ú';
854
        $search[]  = '&uacute;';
855
        $replace[] = 'Ú';
856
        $search[]  = '&Uacute;';
857
        $replace[] = 'û';
858
        $search[]  = '&ucirc;';
859
        $replace[] = 'Û';
860
        $search[]  = '&Ucirc;';
861
        $replace[] = 'ù';
862
        $search[]  = '&ugrave;';
863
        $replace[] = 'Ù';
864
        $search[]  = '&Ugrave;';
865
        $replace[] = 'ü';
866
        $search[]  = '&uuml;';
867
        $replace[] = 'Ü';
868
        $search[]  = '&Uuml;';
869
        $replace[] = 'ý';
870
        $search[]  = '&yacute;';
871
        $replace[] = 'Ý';
872
        $search[]  = '&Yacute;';
873
        $replace[] = 'ÿ';
874
        $search[]  = '&yuml;';
875
        $replace[] = 'Ÿ';
876
        $search[]  = '&Yuml;';
877
        $chaine    = str_replace($search, $replace, $chaine);
878
879
        return $chaine;
880
    }
881
882
    /**
883
     * Create a title to be used by the url rewriting
884
     *
885
     * @param string  $content The text to use to create the url
886
     * @param integer $urw     The lower limit to create words
887
     *
888
     * @return string The text to use for the url
889
     *                Note, some parts are from Solo's code
890
     */
891
    public static function makeSeoUrl($content, $urw = 1)
892
    {
893
        $s       = "ÀÁÂÃÄÅÒÓÔÕÖØÈÉÊËÇÌÍÎÏÙÚÛܟÑàáâãäåòóôõöøèéêëçìíîïùúûüÿñ '()";
894
        $r       = 'AAAAAAOOOOOOEEEECIIIIUUUUYNaaaaaaooooooeeeeciiiiuuuuyn----';
895
        $content = self::unhtml($content); // First, remove html entities
896
        $content = strtr($content, $s, $r);
897
        $content = strip_tags($content);
898
        $content = strtolower($content);
899
        $content = htmlentities($content); // TODO: Vérifier
900
        $content = preg_replace('/&([a-zA-Z])(uml|acute|grave|circ|tilde);/', '$1', $content);
901
        $content = html_entity_decode($content);
902
        $content = preg_replace('/quot/i', ' ', $content);
903
        $content = preg_replace("/'/i", ' ', $content);
904
        $content = preg_replace('/-/i', ' ', $content);
905
        $content = preg_replace('/[[:punct:]]/i', '', $content);
906
907
        // Selon option mais attention au fichier .htaccess !
908
        // $content = eregi_replace('[[:digit:]]','', $content);
909
        $content = preg_replace('/[^a-z|A-Z|0-9]/', '-', $content);
910
911
        $words    = explode(' ', $content);
912
        $keywords = '';
913
        foreach ($words as $word) {
914
            if (strlen($word) >= $urw) {
915
                $keywords .= '-' . trim($word);
916
            }
917
        }
918
        if (!$keywords) {
919
            $keywords = '-';
920
        }
921
        // Supprime les tirets en double
922
        $keywords = str_replace('---', '-', $keywords);
923
        $keywords = str_replace('--', '-', $keywords);
924
        // Supprime un éventuel tiret à la fin de la chaine
925
        if (substr($keywords, strlen($keywords) - 1, 1) == '-') {
926
            $keywords = substr($keywords, 0, -1);
927
        }
928
929
        return $keywords;
930
    }
931
932
    /**
933
     * Create the meta keywords based on the content
934
     *
935
     * @param string $content Content from which we have to create metakeywords
936
     *
937
     * @return string The list of meta keywords
938
     */
939
    public static function createMetaKeywords($content)
940
    {
941
        $keywordscount = self::getModuleOption('metagen_maxwords');
942
        $keywordsorder = self::getModuleOption('metagen_order');
943
944
        $tmp = array();
945
        // Search for the "Minimum keyword length"
946
        if (isset($_SESSION['oledrion_keywords_limit'])) {
947
            $limit = $_SESSION['oledrion_keywords_limit'];
948
        } else {
949
            $configHandler                      = xoops_getHandler('config');
950
            $xoopsConfigSearch                   = $configHandler->getConfigsByCat(XOOPS_CONF_SEARCH);
951
            $limit                               = $xoopsConfigSearch['keyword_min'];
952
            $_SESSION['oledrion_keywords_limit'] = $limit;
953
        }
954
        $myts            = MyTextSanitizer::getInstance();
955
        $content         = str_replace('<br>', ' ', $content);
956
        $content         = $myts->undoHtmlSpecialChars($content);
957
        $content         = strip_tags($content);
958
        $content         = strtolower($content);
959
        $search_pattern  = array(
960
            '&nbsp;',
961
            "\t",
962
            "\r\n",
963
            "\r",
964
            "\n",
965
            ',',
966
            '.',
967
            "'",
968
            ';',
969
            ':',
970
            ')',
971
            '(',
972
            '"',
973
            '?',
974
            '!',
975
            '{',
976
            '}',
977
            '[',
978
            ']',
979
            '<',
980
            '>',
981
            '/',
982
            '+',
983
            '-',
984
            '_',
985
            '\\',
986
            '*'
987
        );
988
        $replace_pattern = array(
989
            ' ',
990
            ' ',
991
            ' ',
992
            ' ',
993
            ' ',
994
            ' ',
995
            ' ',
996
            ' ',
997
            '',
998
            '',
999
            '',
1000
            '',
1001
            '',
1002
            '',
1003
            '',
1004
            '',
1005
            '',
1006
            '',
1007
            '',
1008
            '',
1009
            '',
1010
            '',
1011
            '',
1012
            '',
1013
            '',
1014
            '',
1015
            ''
1016
        );
1017
        $content         = str_replace($search_pattern, $replace_pattern, $content);
1018
        $keywords        = explode(' ', $content);
1019
        switch ($keywordsorder) {
1020
            case 0: // Ordre d'apparition dans le texte
1021
                $keywords = array_unique($keywords);
1022
                break;
1023
            case 1: // Ordre de fréquence des mots
1024
                $keywords = array_count_values($keywords);
1025
                asort($keywords);
1026
                $keywords = array_keys($keywords);
1027
                break;
1028
            case 2: // Ordre inverse de la fréquence des mots
1029
                $keywords = array_count_values($keywords);
1030
                arsort($keywords);
1031
                $keywords = array_keys($keywords);
1032
                break;
1033
        }
1034
        // Remove black listed words
1035
        if (xoops_trim(self::getModuleOption('metagen_blacklist')) != '') {
1036
            $metagen_blacklist = str_replace("\r", '', self::getModuleOption('metagen_blacklist'));
1037
            $metablack         = explode("\n", $metagen_blacklist);
1038
            array_walk($metablack, 'trim');
1039
            $keywords = array_diff($keywords, $metablack);
1040
        }
1041
1042
        foreach ($keywords as $keyword) {
1043
            if (strlen($keyword) >= $limit && !is_numeric($keyword)) {
1044
                $tmp[] = $keyword;
1045
            }
1046
        }
1047
        $tmp = array_slice($tmp, 0, $keywordscount);
1048
        if (count($tmp) > 0) {
1049
            return implode(',', $tmp);
1050
        } else {
1051
            if (!isset($configHandler) || !is_object($configHandler)) {
1052
                $configHandler = xoops_getHandler('config');
1053
            }
1054
            $xoopsConfigMetaFooter = $configHandler->getConfigsByCat(XOOPS_CONF_METAFOOTER);
1055
            if (isset($xoopsConfigMetaFooter['meta_keywords'])) {
1056
                return $xoopsConfigMetaFooter['meta_keywords'];
1057
            } else {
1058
                return '';
1059
            }
1060
        }
1061
    }
1062
1063
    /**
1064
     * Fonction chargée de gérer l'upload
1065
     *
1066
     * @param integer $indice L'indice du fichier à télécharger
1067
     * @param string  $dstpath
1068
     * @param null    $mimeTypes
1069
     * @param null    $uploadMaxSize
1070
     * @param null    $maxWidth
1071
     * @param null    $maxHeight
1072
     *
1073
     * @return mixed True si l'upload s'est bien déroulé sinon le message d'erreur correspondant
1074
     */
1075
    public static function uploadFile(
1076
        $indice,
1077
        $dstpath = XOOPS_UPLOAD_PATH,
1078
        $mimeTypes = null,
1079
        $uploadMaxSize = null,
1080
        $maxWidth = null,
1081
        $maxHeight = null
1082
    ) {
1083
        require_once XOOPS_ROOT_PATH . '/class/uploader.php';
1084
        global $destname;
1085
        if (isset($_POST['xoops_upload_file'])) {
1086
            require_once XOOPS_ROOT_PATH . '/class/uploader.php';
1087
            $fldname = '';
1088
            $fldname = $_FILES[$_POST['xoops_upload_file'][$indice]];
1089
            $fldname = $fldname['name'];
1090
            if (xoops_trim($fldname != '')) {
1091
                $destname = self::createUploadName($dstpath, $fldname, true);
1092
                if ($mimeTypes === null) {
1093
                    $permittedtypes = explode("\n", str_replace("\r", '', self::getModuleOption('mimetypes')));
1094
                    array_walk($permittedtypes, 'trim');
1095
                } else {
1096
                    $permittedtypes = $mimeTypes;
1097
                }
1098
                if ($uploadMaxSize === null) {
1099
                    $uploadSize = self::getModuleOption('maxuploadsize');
1100
                } else {
1101
                    $uploadSize = $uploadMaxSize;
1102
                }
1103
                $uploader = new XoopsMediaUploader($dstpath, $permittedtypes, $uploadSize, $maxWidth, $maxHeight);
0 ignored issues
show
$permittedtypes is of type array|null, but the function expects a integer.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
1104
                //$uploader->allowUnknownTypes = true;
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
1105
                $uploader->setTargetFileName($destname);
1106
                if ($uploader->fetchMedia($_POST['xoops_upload_file'][$indice])) {
1107
                    if ($uploader->upload()) {
1108
                        return true;
1109
                    } else {
1110
                        return _ERRORS . ' ' . htmlentities($uploader->getErrors());
1111
                    }
1112
                } else {
1113
                    return htmlentities($uploader->getErrors());
1114
                }
1115
            } else {
1116
                return false;
1117
            }
1118
        } else {
1119
            return false;
1120
        }
1121
    }
1122
1123
    /**
1124
     * Resize a Picture to some given dimensions (using the wideImage library)
1125
     *
1126
     * @param string  $src_path      Picture's source
1127
     * @param string  $dst_path      Picture's destination
1128
     * @param integer $param_width   Maximum picture's width
1129
     * @param integer $param_height  Maximum picture's height
1130
     * @param boolean $keep_original Do we have to keep the original picture ?
1131
     * @param string  $fit           Resize mode (see the wideImage library for more information)
1132
     *
1133
     * @return bool
1134
     */
1135
    public static function resizePicture(
1136
        $src_path,
1137
        $dst_path,
1138
        $param_width,
1139
        $param_height,
1140
        $keep_original = false,
1141
        $fit = 'inside'
1142
    ) {
1143
        //        require_once OLEDRION_PATH . 'class/wideimage/WideImage.inc.php';
1144
        $resize = true;
1145
        if (OLEDRION_DONT_RESIZE_IF_SMALLER) {
1146
            $pictureDimensions = getimagesize($src_path);
1147
            if (is_array($pictureDimensions)) {
1148
                $width  = $pictureDimensions[0];
1149
                $height = $pictureDimensions[1];
1150
                if ($width < $param_width && $height < $param_height) {
1151
                    $resize = false;
1152
                }
1153
            }
1154
        }
1155
1156
        $img = WideImage::load($src_path);
1157
        if ($resize) {
1158
            $result = $img->resize($param_width, $param_height, $fit);
1159
            $result->saveToFile($dst_path);
1160
        } else {
1161
            @copy($src_path, $dst_path);
1162
        }
1163
1164
        if (!$keep_original) {
1165
            @unlink($src_path);
1166
        }
1167
1168
        return true;
1169
    }
1170
1171
    /**
1172
     * Déclenchement d'une alerte Xoops suite à un évènement
1173
     *
1174
     * @param string       $category La catégorie de l'évènement
1175
     * @param integer      $itemId   L'ID de l'élément (trop général pour être décris précisément)
1176
     * @param unknown_type $event    L'évènement qui est déclencé
1177
     * @param unknown_type $tags     Les variables à passer au template
1178
     */
1179
    public static function notify($category, $itemId, $event, $tags)
1180
    {
1181
        $notificationHandler = xoops_getHandler('notification');
1182
        $tags['X_MODULE_URL'] = OLEDRION_URL;
1183
        $notificationHandler->triggerEvent($category, $itemId, $event, $tags);
1184
    }
1185
1186
    /**
1187
     * Ajoute des jours à une date et retourne la nouvelle date au format Date de Mysql
1188
     *
1189
     * @param int     $duration
1190
     * @param integer $startingDate Date de départ (timestamp)
1191
     *
1192
     * @internal param int $durations Durée en jours
1193
     * @return bool|string
1194
     */
1195
    public static function addDaysToDate($duration = 1, $startingDate = 0)
1196
    {
1197
        if ($startingDate == 0) {
1198
            $startingDate = time();
1199
        }
1200
        $endingDate = $startingDate + ($duration * 86400);
1201
1202
        return date('Y-m-d', $endingDate);
1203
    }
1204
1205
    /**
1206
     * Retourne un breadcrumb en fonction des paramètres passés et en partant (d'office) de la racine du module
1207
     *
1208
     * @param array  $path  Le chemin complet (excepté la racine) du breadcrumb sous la forme clé=url valeur=titre
1209
     * @param string $raquo Le séparateur par défaut à utiliser
1210
     *
1211
     * @return string le breadcrumb
1212
     */
1213
    public static function breadcrumb($path, $raquo = ' &raquo; ')
1214
    {
1215
        $breadcrumb        = '';
1216
        $workingBreadcrumb = array();
1217
        if (is_array($path)) {
1218
            $moduleName          = self::getModuleName();
1219
            $workingBreadcrumb[] = "<a href='" . OLEDRION_URL . "' title='" . self::makeHrefTitle($moduleName) . "'>" . $moduleName . '</a>';
1220
            foreach ($path as $url => $title) {
1221
                $workingBreadcrumb[] = "<a href='" . $url . "'>" . $title . '</a>';
1222
            }
1223
            $cnt = count($workingBreadcrumb);
1224
            for ($i = 0; $i < $cnt; ++$i) {
1225
                if ($i == $cnt - 1) {
1226
                    $workingBreadcrumb[$i] = strip_tags($workingBreadcrumb[$i]);
1227
                }
1228
            }
1229
            $breadcrumb = implode($raquo, $workingBreadcrumb);
1230
        }
1231
1232
        return $breadcrumb;
1233
    }
1234
1235
    /**
1236
     * @param $string
1237
     *
1238
     * @return string
1239
     */
1240
    public static function close_tags($string)
1241
    {
1242
        // match opened tags
1243
        if (preg_match_all('/<([a-z\:\-]+)[^\/]>/', $string, $start_tags)) {
1244
            $start_tags = $start_tags[1];
1245
1246
            // match closed tags
1247
            if (preg_match_all('/<\/([a-z]+)>/', $string, $end_tags)) {
1248
                $complete_tags = array();
1249
                $end_tags      = $end_tags[1];
1250
1251
                foreach ($start_tags as $key => $val) {
1252
                    $posb = array_search($val, $end_tags);
1253
                    if (is_int($posb)) {
1254
                        unset($end_tags[$posb]);
1255
                    } else {
1256
                        $complete_tags[] = $val;
1257
                    }
1258
                }
1259
            } else {
1260
                $complete_tags = $start_tags;
1261
            }
1262
1263
            $complete_tags = array_reverse($complete_tags);
1264
            for ($i = 0, $iMax = count($complete_tags); $i < $iMax; ++$i) {
1265
                $string .= '</' . $complete_tags[$i] . '>';
1266
            }
1267
        }
1268
1269
        return $string;
1270
    }
1271
1272
    /**
1273
     * @param        $string
1274
     * @param int    $length
1275
     * @param string $etc
1276
     * @param bool   $break_words
1277
     *
1278
     * @return mixed|string
1279
     */
1280
    public static function truncate_tagsafe($string, $length = 80, $etc = '...', $break_words = false)
1281
    {
1282
        if ($length == 0) {
1283
            return '';
1284
        }
1285
1286
        if (strlen($string) > $length) {
1287
            $length -= strlen($etc);
1288
            if (!$break_words) {
1289
                $string = preg_replace('/\s+?(\S+)?$/', '', substr($string, 0, $length + 1));
1290
                $string = preg_replace('/<[^>]*$/', '', $string);
1291
                $string = self::close_tags($string);
1292
            }
1293
1294
            return $string . $etc;
1295
        } else {
1296
            return $string;
1297
        }
1298
    }
1299
1300
    /**
1301
     * Create an infotip
1302
     * @param $text
1303
     * @return string
1304
     */
1305
    public static function makeInfotips($text)
1306
    {
1307
        $ret      = '';
1308
        $infotips = self::getModuleOption('infotips');
1309
        if ($infotips > 0) {
1310
            $myts = MyTextSanitizer::getInstance();
1311
            $ret  = $myts->htmlSpecialChars(xoops_substr(strip_tags($text), 0, $infotips));
1312
        }
1313
1314
        return $ret;
1315
    }
1316
1317
    /**
1318
     * Mise en place de l'appel à la feuille de style du module dans le template
1319
     * @param string $url
1320
     */
1321 View Code Duplication
    public static function setCSS($url = '')
0 ignored issues
show
This method 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...
1322
    {
1323
        global $xoopsTpl, $xoTheme;
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...
1324
        if ($url == '') {
1325
            $url = OLEDRION_URL . 'css/oledrion.css';
1326
        }
1327
1328
        if (!is_object($xoTheme)) {
1329
            $xoopsTpl->assign('xoops_module_header', $xoopsTpl->get_template_vars('xoops_module_header') . "<link rel=\"stylesheet\" type=\"text/css\" href=\"$url\" />");
1330
        } else {
1331
            $xoTheme->addStylesheet($url);
1332
        }
1333
    }
1334
1335
    /**
1336
     * Mise en place de l'appel à la feuille de style du module dans le template
1337
     * @param string $language
1338
     */
1339 View Code Duplication
    public static function setLocalCSS($language = 'english')
0 ignored issues
show
This method 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...
1340
    {
1341
        global $xoopsTpl, $xoTheme;
1342
1343
        $localcss = OLEDRION_URL . 'language/' . $language . '/style.css';
1344
1345
        if (!is_object($xoTheme)) {
1346
            $xoopsTpl->assign('xoops_module_header', $xoopsTpl->get_template_vars('xoops_module_header') . "<link rel=\"stylesheet\" type=\"text/css\" href=\"$localcss\" />");
1347
        } else {
1348
            $xoTheme->addStylesheet($localcss);
1349
        }
1350
    }
1351
1352
    /**
1353
     * Calcul du TTC à partir du HT et de la TVA
1354
     *
1355
     * @param float   $ht     Montant HT
1356
     * @param float   $vat    Taux de TVA
1357
     * @param boolean $edit   Si faux alors le montant est formaté pour affichage sinon il reste tel quel
1358
     * @param string  $format Format d'affichage du résultat (long ou court)
1359
     *
1360
     * @return mixed Soit une chaine soit un flottant
1361
     */
1362
    public static function getTTC($ht, $vat, $edit = false, $format = 's')
1363
    {
1364
        $oledrion_Currency = Oledrion_Currency::getInstance();
1365
        $ttc               = $ht * (1 + ($vat / 100));
1366
        if (!$edit) {
1367
            return $oledrion_Currency->amountForDisplay($ttc, $format);
1368
        } else {
1369
            return $ttc;
1370
        }
1371
    }
1372
1373
    /**
1374
     * Renvoie le montant de la tva à partir du montant HT
1375
     * @param $ht
1376
     * @param $vat
1377
     * @return float
1378
     */
1379
    public static function getVAT($ht, $vat)
1380
    {
1381
        return (float)($ht * $vat);
1382
    }
1383
1384
    /**
1385
     * Retourne le montant TTC
1386
     *
1387
     * @param floatval $product_price Le montant du produit
1388
     * @param integer  $vat_id        Le numéro de TVA
1389
     *
1390
     * @return floatval Le montant TTC si on a trouvé sa TVA sinon
1391
     */
1392
    public static function getAmountWithVat($product_price, $vat_id)
1393
    {
1394
        static $vats = array();
1395
        $vat_rate = null;
1396
        if (is_array($vats) && in_array($vat_id, $vats)) {
1397
            $vat_rate = $vats[$vat_id];
1398
        } else {
1399
            $handlers = OledrionHandler::getInstance();
1400
            $vat      = null;
1401
            $vat      = $handlers->h_oledrion_vat->get($vat_id);
1402
            if (is_object($vat)) {
1403
                $vat_rate      = $vat->getVar('vat_rate', 'e');
1404
                $vats[$vat_id] = $vat_rate;
1405
            }
1406
        }
1407
1408
        if (!null === $vat_rate) {
1409
            return ((float)$product_price * (float)$vat_rate / 100) + (float)$product_price;
1410
        } else {
1411
            return $product_price;
1412
        }
1413
    }
1414
1415
    /**
1416
     * @param $datastream
1417
     * @param $url
1418
     *
1419
     * @return string
1420
     */
1421
    public static function postIt($datastream, $url)
1422
    {
1423
        $url     = preg_replace('@^http://@i', '', $url);
1424
        $host    = substr($url, 0, strpos($url, '/'));
1425
        $uri     = strstr($url, '/');
1426
        $reqbody = '';
1427
        foreach ($datastream as $key => $val) {
1428
            if (!empty($reqbody)) {
1429
                $reqbody .= '&';
1430
            }
1431
            $reqbody .= $key . '=' . urlencode($val);
1432
        }
1433
        $contentlength = strlen($reqbody);
1434
        $reqheader     = "POST $uri HTTP/1.1\r\n" . "Host: $host\n" . "Content-Type: application/x-www-form-urlencoded\r\n" . "Content-Length: $contentlength\r\n\r\n" . "$reqbody\r\n";
1435
1436
        return $reqheader;
1437
    }
1438
1439
    /**
1440
     * Retourne le type Mime d'un fichier en utilisant d'abord finfo puis mime_content
1441
     *
1442
     * @param string $filename Le fichier (avec son chemin d'accès complet) dont on veut connaître le type mime
1443
     *
1444
     * @return string
1445
     */
1446
    public static function getMimeType($filename)
1447
    {
1448
        if (function_exists('finfo_open')) {
1449
            $finfo    = finfo_open();
1450
            $mimetype = finfo_file($finfo, $filename, FILEINFO_MIME_TYPE);
1451
            finfo_close($finfo);
1452
1453
            return $mimetype;
1454
        } else {
1455
            if (function_exists('mime_content_type')) {
1456
                return mime_content_type($filename);
1457
            } else {
1458
                return '';
1459
            }
1460
        }
1461
    }
1462
1463
    /**
1464
     * Retourne un criteria compo qui permet de filtrer les produits sur le mois courant
1465
     *
1466
     * @return object
1467
     */
1468
    public static function getThisMonthCriteria()
1469
    {
1470
        $start             = mktime(0, 1, 0, date('n'), date('j'), date('Y'));
1471
        $end               = mktime(0, 0, 0, date('n'), date('t'), date('Y'));
1472
        $criteriaThisMonth = new CriteriaCompo();
1473
        $criteriaThisMonth->add(new Criteria('product_submitted', $start, '>='));
1474
        $criteriaThisMonth->add(new Criteria('product_submitted', $end, '<='));
1475
1476
        return $criteriaThisMonth;
1477
    }
1478
1479
    /**
1480
     * Retourne une liste d'objets XoopsUsers à partir d'une liste d'identifiants
1481
     *
1482
     * @param array $xoopsUsersIDs La liste des ID
1483
     *
1484
     * @return array Les objets XoopsUsers
1485
     */
1486
    public static function getUsersFromIds($xoopsUsersIDs)
1487
    {
1488
        $users = array();
1489
        if (is_array($xoopsUsersIDs) && count($xoopsUsersIDs) > 0) {
1490
            $xoopsUsersIDs = array_unique($xoopsUsersIDs);
1491
            sort($xoopsUsersIDs);
1492
            if (count($xoopsUsersIDs) > 0) {
1493
                $memberHandler = xoops_getHandler('user');
1494
                $criteria       = new Criteria('uid', '(' . implode(',', $xoopsUsersIDs) . ')', 'IN');
1495
                $criteria->setSort('uid');
1496
                $users = $memberHandler->getObjects($criteria, true);
1497
            }
1498
        }
1499
1500
        return $users;
1501
    }
1502
1503
    /**
1504
     * Retourne l'ID de l'utilisateur courant (s'il est connecté)
1505
     *
1506
     * @return integer L'uid ou 0
1507
     */
1508
    public static function getCurrentUserID()
1509
    {
1510
        global $xoopsUser;
1511
        $uid = is_object($xoopsUser) ? $xoopsUser->getVar('uid') : 0;
1512
1513
        return $uid;
1514
    }
1515
1516
    /**
1517
     * Retourne la liste des groupes de l'utilisateur courant (avec cache)
1518
     *
1519
     * @param int $uid
1520
     *
1521
     * @return array Les ID des groupes auquel l'utilisateur courant appartient
1522
     */
1523
    public static function getMemberGroups($uid = 0)
1524
    {
1525
        static $buffer = array();
1526
        if ($uid == 0) {
1527
            $uid = self::getCurrentUserID();
1528
        }
1529
1530
        if (is_array($buffer) && count($buffer) > 0 && isset($buffer[$uid])) {
1531
            return $buffer[$uid];
1532
        } else {
1533
            if ($uid > 0) {
1534
                $memberHandler = xoops_getHandler('member');
1535
                $buffer[$uid]   = $memberHandler->getGroupsByUser($uid, false); // Renvoie un tableau d'ID (de groupes)
1536
            } else {
1537
                $buffer[$uid] = array(XOOPS_GROUP_ANONYMOUS);
1538
            }
1539
        }
1540
1541
        return $buffer[$uid];
1542
    }
1543
1544
    /**
1545
     * Indique si l'utilisateur courant fait partie d'une groupe donné (avec gestion de cache)
1546
     *
1547
     * @param integer $group Groupe recherché
1548
     * @param int     $uid
1549
     *
1550
     * @return boolean vrai si l'utilisateur fait partie du groupe, faux sinon
1551
     */
1552
    public static function isMemberOfGroup($group = 0, $uid = 0)
1553
    {
1554
        static $buffer = array();
1555
        $retval = false;
1556
        if ($uid == 0) {
1557
            $uid = self::getCurrentUserID();
1558
        }
1559
        if (is_array($buffer) && array_key_exists($group, $buffer)) {
1560
            $retval = $buffer[$group];
1561
        } else {
1562
            $memberHandler = xoops_getHandler('member');
1563
            $groups         = $memberHandler->getGroupsByUser($uid, false); // Renvoie un tableau d'ID (de groupes)
1564
            $retval         = in_array($group, $groups);
1565
            $buffer[$group] = $retval;
1566
        }
1567
1568
        return $retval;
1569
    }
1570
1571
    /**
1572
     * Fonction chargée de vérifier qu'un répertoire existe, qu'on peut écrire dedans et création d'un fichier index.html
1573
     *
1574
     * @param string $folder Le chemin complet du répertoire à vérifier
1575
     *
1576
     * @return void
1577
     */
1578
    public static function prepareFolder($folder)
1579
    {
1580
        if (!is_dir($folder)) {
1581
            mkdir($folder);
1582
            file_put_contents($folder . '/index.html', '<script>history.go(-1);</script>');
1583
        }
1584
        //        chmod($folder, 0777);
1585
    }
1586
1587
    /**
1588
     * Duplicate a file in local
1589
     *
1590
     * @param string $path     The file's path
1591
     * @param string $filename The filename
1592
     *
1593
     * @return mixed If the copy succeed, the new filename else false
1594
     * @since 2.1
1595
     */
1596
    public static function duplicateFile($path, $filename)
1597
    {
1598
        $newName = self::createUploadName($path, $filename);
1599
        if (copy($path . DIRECTORY_SEPARATOR . $filename, $path . DIRECTORY_SEPARATOR . $newName)) {
1600
            return $newName;
1601
        } else {
1602
            return false;
1603
        }
1604
    }
1605
1606
    /**
1607
     * Load a language file
1608
     *
1609
     * @param string $languageFile     The required language file
1610
     * @param string $defaultExtension Default extension to use
1611
     *
1612
     * @since 2.2.2009.02.13
1613
     */
1614
    public static function loadLanguageFile($languageFile, $defaultExtension = '.php')
1615
    {
1616
        global $xoopsConfig;
1617
        $root = OLEDRION_PATH;
1618
        if (false === strpos($languageFile, $defaultExtension)) {
1619
            $languageFile .= $defaultExtension;
1620
        }
1621
        if (file_exists($root . 'language' . DIRECTORY_SEPARATOR . $xoopsConfig['language'] . DIRECTORY_SEPARATOR . $languageFile)) {
1622
            require_once $root . 'language' . DIRECTORY_SEPARATOR . $xoopsConfig['language'] . DIRECTORY_SEPARATOR . $languageFile;
1623
        } else { // Fallback
1624
            require_once $root . 'language' . DIRECTORY_SEPARATOR . 'english' . DIRECTORY_SEPARATOR . $languageFile;
1625
        }
1626
    }
1627
1628
    /**
1629
     * Formatage d'un floattant pour la base de données
1630
     *
1631
     * @param float    Le montant à formater
1632
     *
1633
     * @return string le montant formaté
1634
     * @since 2.2.2009.02.25
1635
     */
1636
    public static function formatFloatForDB($amount)
1637
    {
1638
        return number_format($amount, 2, '.', '');
1639
    }
1640
1641
    /**
1642
     * Appelle un fichier Javascript à la manière de Xoops
1643
     *
1644
     * @note, l'url complète ne doit pas être fournie, la méthode se charge d'ajouter
1645
     * le chemin vers le répertoire js en fonction de la requête, c'est à dire que si
1646
     * on appelle un fichier de langue, la méthode ajoute l'url vers le répertoire de
1647
     * langue, dans le cas contraire on ajoute l'url vers le répertoire JS du module.
1648
     *
1649
     * @param string $javascriptFile
1650
     * @param bool   $inLanguageFolder
1651
     * @param bool   $oldWay
1652
     *
1653
     * @return void
1654
     * @since 2.3.2009.03.14
1655
     */
1656
    public static function callJavascriptFile($javascriptFile, $inLanguageFolder = false, $oldWay = false)
1657
    {
1658
        global $xoopsConfig, $xoTheme;
1659
        $fileToCall = $javascriptFile;
1660
        if ($inLanguageFolder) {
1661
            $root    = OLEDRION_PATH;
1662
            $rootUrl = OLEDRION_URL;
1663
            if (file_exists($root . 'language' . DIRECTORY_SEPARATOR . $xoopsConfig['language'] . DIRECTORY_SEPARATOR . $javascriptFile)) {
1664
                $fileToCall = $rootUrl . 'language/' . $xoopsConfig['language'] . '/' . $javascriptFile;
1665
            } else { // Fallback
1666
                $fileToCall = $rootUrl . 'language/english/' . $javascriptFile;
1667
            }
1668
        } else {
1669
            $fileToCall = OLEDRION_JS_URL . $javascriptFile;
1670
        }
1671
1672
        $xoTheme->addScript('browse.php?Frameworks/jquery/jquery.js');
1673
        $xoTheme->addScript($fileToCall);
1674
    }
1675
1676
    /**
1677
     * Create the <option> of an html select
1678
     *
1679
     * @param array $array   Array of index and labels
1680
     * @param mixed $default the default value
1681
     * @param bool  $withNull
1682
     *
1683
     * @return string
1684
     * @since 2.3.2009.03.13
1685
     */
1686
    public static function htmlSelectOptions($array, $default = 0, $withNull = true)
1687
    {
1688
        $ret      = array();
1689
        $selected = '';
1690
        if ($withNull) {
1691
            if ($default === 0) {
1692
                $selected = " selected = 'selected'";
1693
            }
1694
            $ret[] = '<option value=0' . $selected . '>---</option>';
1695
        }
1696
1697
        foreach ($array as $index => $label) {
1698
            $selected = '';
1699
            if ($index == $default) {
1700
                $selected = " selected = 'selected'";
1701
            }
1702
            $ret[] = "<option value=\"" . $index . "\"" . $selected . '>' . $label . '</option>';
1703
        }
1704
1705
        return implode("\n", $ret);
1706
    }
1707
1708
    /**
1709
     * Creates an html select
1710
     *
1711
     * @param string  $selectName Selector's name
1712
     * @param array   $array      Options
1713
     * @param mixed   $default    Default's value
1714
     * @param boolean $withNull   Do we include a null option ?
1715
     *
1716
     * @return string
1717
     * @since 2.3.2009.03.13
1718
     */
1719
    public static function htmlSelect($selectName, $array, $default, $withNull = true)
1720
    {
1721
        $ret = '';
1722
        $ret .= "<select name='" . $selectName . "' id='" . $selectName . "'>\n";
1723
        $ret .= self::htmlSelectOptions($array, $default, $withNull);
1724
        $ret .= "</select>\n";
1725
1726
        return $ret;
1727
    }
1728
1729
    /**
1730
     * Extrait l'id d'une chaine formatée sous la forme xxxx-99 (duquel on récupère 99)
1731
     *
1732
     * @note: utilisé par les attributs produits
1733
     *
1734
     * @param string $string    La chaine de travail
1735
     * @param string $separator Le séparateur
1736
     *
1737
     * @return string
1738
     */
1739 View Code Duplication
    public static function getId($string, $separator = '_')
0 ignored issues
show
This method 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...
1740
    {
1741
        $pos = strrpos($string, $separator);
1742
        if ($pos === false) {
1743
            return $string;
1744
        } else {
1745
            return (int)substr($string, $pos + 1);
1746
        }
1747
    }
1748
1749
    /**
1750
     * Fonction "inverse" de getId (depuis xxxx-99 on récupère xxxx)
1751
     *
1752
     * @note: utilisé par les attributs produits
1753
     *
1754
     * @param string $string    La chaine de travail
1755
     * @param string $separator Le séparateur
1756
     *
1757
     * @return string
1758
     */
1759 View Code Duplication
    public static function getName($string, $separator = '_')
0 ignored issues
show
This method 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...
1760
    {
1761
        $pos = strrpos($string, $separator);
1762
        if ($pos === false) {
1763
            return $string;
1764
        } else {
1765
            return substr($string, 0, $pos);
1766
        }
1767
    }
1768
1769
    /**
1770
     * Renvoie un montant nul si le montant est négatif
1771
     *
1772
     * @param float $amount
1773
     *
1774
     * @return float
0 ignored issues
show
Should the return type not be double|null?

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...
1775
     */
1776
    public static function doNotAcceptNegativeAmounts(&$amount)
1777
    {
1778
        if ($amount < 0) {
1779
            $amount = 0;
1780
        }
1781
    }
1782
1783
    /**
1784
     * Returns a string from the request
1785
     *
1786
     * @param string $valueName    Name of the parameter you want to get
1787
     * @param mixed  $defaultValue Default value to return if the parameter is not set in the request
1788
     *
1789
     * @return mixed
1790
     */
1791
    public static function getFromRequest($valueName, $defaultValue = '')
1792
    {
1793
        return isset($_REQUEST[$valueName]) ? $_REQUEST[$valueName] : $defaultValue;
1794
    }
1795
1796
    /**
1797
     * Verify that a mysql table exists
1798
     *
1799
     * @package       Oledrion
1800
     * @author        Instant Zero (http://xoops.instant-zero.com)
1801
     * @copyright (c) Instant Zero
1802
     * @param $tablename
1803
     * @return bool
1804
     */
1805
    public static function tableExists($tablename)
1806
    {
1807
        global $xoopsDB;
1808
        $result = $xoopsDB->queryF("SHOW TABLES LIKE '$tablename'");
1809
1810
        return ($xoopsDB->getRowsNum($result) > 0);
1811
    }
1812
1813
    /**
1814
     * Verify that a field exists inside a mysql table
1815
     *
1816
     * @package       Oledrion
1817
     * @author        Instant Zero (http://xoops.instant-zero.com)
1818
     * @copyright (c) Instant Zero
1819
     * @param $fieldname
1820
     * @param $table
1821
     * @return bool
1822
     */
1823
    public static function fieldExists($fieldname, $table)
1824
    {
1825
        global $xoopsDB;
1826
        $result = $xoopsDB->queryF("SHOW COLUMNS FROM $table LIKE '$fieldname'");
1827
1828
        return ($xoopsDB->getRowsNum($result) > 0);
1829
    }
1830
1831
    /**
1832
     * Retourne la définition d'un champ
1833
     *
1834
     * @param string $fieldname
1835
     * @param string $table
1836
     *
1837
     * @return array
1838
     */
1839
    public static function getFieldDefinition($fieldname, $table)
1840
    {
1841
        global $xoopsDB;
1842
        $result = $xoopsDB->queryF("SHOW COLUMNS FROM $table LIKE '$fieldname'");
1843
        if ($result) {
1844
            return $xoopsDB->fetchArray($result);
1845
        }
1846
1847
        return '';
1848
    }
1849
1850
    /**
1851
     * Add a field to a mysql table
1852
     *
1853
     * @package       Oledrion
1854
     * @author        Instant Zero (http://xoops.instant-zero.com)
1855
     * @copyright (c) Instant Zero
1856
     * @param $field
1857
     * @param $table
1858
     * @return mixed
1859
     */
1860
    public static function addField($field, $table)
1861
    {
1862
        global $xoopsDB;
1863
        $result = $xoopsDB->queryF("ALTER TABLE $table ADD $field;");
1864
1865
        return $result;
1866
    }
1867
1868
    /**
1869
     * @param $info
1870
     *
1871
     * @return string
1872
     */
1873
    public static function packingHtmlSelect($info)
1874
    {
1875
        $ret = '';
1876
        $ret .= '<div class="oledrion_htmlform">';
1877
        $ret .= '<img class="oledrion_htmlimage" src="' . $info['packing_image_url'] . '" alt="' . $info['packing_title'] . '" />';
1878
        $ret .= '<h3>' . $info['packing_title'] . '</h3>';
1879 View Code Duplication
        if ($info['packing_price'] > 0) {
1880
            $ret .= '<p><span class="bold">' . _OLEDRION_PRICE . '</span> : ' . $info['packing_price_fordisplay'] . '</p>';
1881
        } else {
1882
            $ret .= '<p><span class="bold">' . _OLEDRION_PRICE . '</span> : ' . _OLEDRION_FREE . '</p>';
1883
        }
1884
        $ret .= '<p>' . $info['packing_description'] . '</p>';
1885
        $ret .= '</div>';
1886
1887
        return $ret;
1888
    }
1889
1890
    /**
1891
     * @param $info
1892
     *
1893
     * @return string
1894
     */
1895
    public static function deliveryHtmlSelect($info)
1896
    {
1897
        $ret = '';
1898
        $ret .= '<div class="oledrion_htmlform">';
1899
        $ret .= '<img class="oledrion_htmlimage" src="' . $info['delivery_image_url'] . '" alt="' . $info['delivery_title'] . '" />';
1900
        $ret .= '<h3>' . $info['delivery_title'] . '</h3>';
1901 View Code Duplication
        if ($info['delivery_price'] > 0) {
1902
            $ret .= '<p><span class="bold">' . _OLEDRION_PRICE . '</span> : ' . $info['delivery_price_fordisplay'] . '</p>';
1903
        } else {
1904
            $ret .= '<p><span class="bold">' . _OLEDRION_PRICE . '</span> : ' . _OLEDRION_FREE . '</p>';
1905
        }
1906
        $ret .= '<p><span class="bold">' . _OLEDRION_DELIVERY_TIME . '</span> : ' . $info['delivery_time'] . _OLEDRION_DELIVERY_DAY . '</p>';
1907
        $ret .= '<p>' . $info['delivery_description'] . '</p>';
1908
        $ret .= '</div>';
1909
1910
        return $ret;
1911
    }
1912
1913
    /**
1914
     * @param $info
1915
     *
1916
     * @return string
1917
     */
1918
    public static function paymentHtmlSelect($info)
1919
    {
1920
        $ret = '';
1921
        $ret .= '<div class="oledrion_htmlform">';
1922
        $ret .= '<img class="oledrion_htmlimage" src="' . $info['payment_image_url'] . '" alt="' . $info['payment_title'] . '" />';
1923
        $ret .= '<h3>' . $info['payment_title'] . '</h3>';
1924
        $ret .= '<p>' . $info['payment_description'] . '</p>';
1925
        $ret .= '</div>';
1926
1927
        return $ret;
1928
    }
1929
1930
    /**
1931
     * @return array
1932
     */
1933
    public static function getCountriesList()
1934
    {
1935
        require_once XOOPS_ROOT_PATH . '/class/xoopslists.php';
1936
1937
        return XoopsLists::getCountryList();
1938
    }
1939
1940
    //=================================================================================================================================
1941
1942
    /**
1943
     * @param       $name
1944
     * @param  bool $optional
1945
     * @return bool
1946
     */
1947
    public static function xtubeGetHandler($name, $optional = false)
1948
    {
1949
        global $handlers, $xoopsModule;
1950
1951
        $name = strtolower(trim($name));
1952
        if (!isset($handlers[$name])) {
1953
            if (file_exists($hnd_file = XOOPS_ROOT_PATH . '/modules/' . $xoopsModule->getVar('dirname') . '/class/class_' . $name . '.php')) {
1954
                require_once $hnd_file;
1955
            }
1956
            $class = 'xtube' . ucfirst($name) . 'Handler';
1957
            if (class_exists($class)) {
1958
                $handlers[$name] = new $class($GLOBALS['xoopsDB']);
1959
            }
1960
        }
1961
        if (!isset($handlers[$name]) && !$optional) {
1962
            trigger_error('<div>Class <span style="font-weight: bold;">' . $class . '</span> does not exist.</div><div>Handler Name: ' . $name, E_USER_ERROR) . '</div>';
1963
        }
1964
1965
        return isset($handlers[$name]) ? $handlers[$name] : false;
1966
    }
1967
1968
    /**
1969
     * @param int    $cid
1970
     * @param string $permType
1971
     * @param bool   $redirect
1972
     *
1973
     * @return bool
1974
     */
1975
    public static function xtubeCheckGroups($cid = 0, $permType = 'XTubeCatPerm', $redirect = false)
1976
    {
1977
        global $xoopsModule;
1978
1979
        $groups       = is_object($GLOBALS['xoopsUser']) ? $GLOBALS['xoopsUser']->getGroups() : XOOPS_GROUP_ANONYMOUS;
1980
        $gpermHandler = xoops_getHandler('groupperm');
1981
        if (!$gpermHandler->checkRight($permType, $cid, $groups, $xoopsModule->getVar('mid'))) {
1982
            if ($redirect === false) {
1983
                return false;
1984
            } else {
1985
                redirect_header('index.php', 3, _NOPERM);
1986
            }
1987
        }
1988
1989
        return true;
1990
    }
1991
1992
    /**
1993
     * @param int $lid
1994
     *
1995
     * @return bool
1996
     */
1997
    public static function xtubeGetVoteDetails($lid = 0)
1998
    {
1999
        $sql = 'SELECT
2000
        COUNT(rating) AS rate,
2001
        MIN(rating) AS min_rate,
2002
        MAX(rating) AS max_rate,
2003
        AVG(rating) AS avg_rate,
2004
        COUNT(ratinguser) AS rating_user,
2005
        MAX(ratinguser) AS max_user,
2006
        MAX(title) AS max_title,
2007
        MIN(title) AS min_title,
2008
        sum(ratinguser = 0) AS null_ratinguser
2009
            FROM ' . $GLOBALS['xoopsDB']->prefix('xoopstube_votedata');
2010
        if ($lid > 0) {
2011
            $sql .= ' WHERE lid=' . $lid;
2012
        }
2013
        if (!$result = $GLOBALS['xoopsDB']->query($sql)) {
2014
            return false;
2015
        }
2016
        $ret = $GLOBALS['xoopsDB']->fetchArray($result);
2017
2018
        return $ret;
2019
    }
2020
2021
    /**
2022
     * @param int $sel_id
2023
     *
2024
     * @return array|bool
2025
     */
2026
    public static function xtubeCalculateVoteData($sel_id = 0)
2027
    {
2028
        $ret                  = array();
2029
        $ret['useravgrating'] = 0;
2030
2031
        $sql = 'SELECT rating FROM ' . $GLOBALS['xoopsDB']->prefix('xoopstube_votedata');
2032
        if ($sel_id !== 0) {
2033
            $sql .= ' WHERE lid=' . $sel_id;
2034
        }
2035
        if (!$result = $GLOBALS['xoopsDB']->query($sql)) {
2036
            return false;
2037
        }
2038
        $ret['uservotes'] = $GLOBALS['xoopsDB']->getRowsNum($result);
2039
        while (false !== (list($rating) = $GLOBALS['xoopsDB']->fetchRow($result))) {
2040
            $ret['useravgrating'] += (int)$rating;
2041
        }
2042
        if ($ret['useravgrating'] > 0) {
2043
            $ret['useravgrating'] = number_format($ret['useravgrating'] / $ret['uservotes'], 2);
2044
        }
2045
2046
        return $ret;
2047
    }
2048
2049
    /**
2050
     * @param      $array
2051
     * @param null $name
2052
     * @param null $def
2053
     * @param bool $strict
2054
     * @param int  $lengthcheck
2055
     *
2056
     * @return array|int|null|string
2057
     */
2058
    public static function xtubeCleanRequestVars(
2059
        &$array,
2060
        $name = null,
2061
        $def = null,
2062
        $strict = false,
2063
        $lengthcheck = 15
2064
    ) {
2065
        // Sanitise $_request for further use.  This method gives more control and security.
2066
        // Method is more for functionality rather than beauty at the moment, will correct later.
2067
        unset($array['usercookie']);
2068
        unset($array['PHPSESSID']);
2069
2070
        if (is_array($array) && $name === null) {
2071
            $globals = array();
2072
            foreach (array_keys($array) as $k) {
2073
                $value = strip_tags(trim($array[$k]));
2074
                if (strlen($value >= $lengthcheck)) {
2075
                    return null;
2076
                }
2077 View Code Duplication
                if (ctype_digit($value)) {
2078
                    $value = (int)$value;
2079
                } else {
2080
                    if ($strict === true) {
2081
                        $value = preg_replace('/\W/', '', trim($value));
2082
                    }
2083
                    $value = strtolower((string)$value);
2084
                }
2085
                $globals[$k] = $value;
2086
            }
2087
2088
            return $globals;
2089
        }
2090
        if (!isset($array[$name]) || !array_key_exists($name, $array)) {
2091
            return $def;
2092
        } else {
2093
            $value = strip_tags(trim($array[$name]));
2094
        }
2095 View Code Duplication
        if (ctype_digit($value)) {
2096
            $value = (int)$value;
2097
        } else {
2098
            if ($strict === true) {
2099
                $value = preg_replace('/\W/', '', trim($value));
2100
            }
2101
            $value = strtolower((string)$value);
2102
        }
2103
2104
        return $value;
2105
    }
2106
2107
    /**
2108
     * @param int $cid
2109
     *
2110
     * @return string
2111
     */
2112
    public static function xtubeRenderToolbar($cid = 0)
2113
    {
2114
        $toolbar = '[ ';
2115
        if (true === XoopstubeUtility::xtubeCheckGroups($cid, 'XTubeSubPerm')) {
2116
            $toolbar .= '<a href="submit.php?cid=' . $cid . '">' . _MD_XOOPSTUBE_SUBMITVIDEO . '</a> | ';
2117
        }
2118
        $toolbar .= '<a href="newlist.php?newvideoshowdays=7">'
2119
                    . _MD_XOOPSTUBE_LATESTLIST
2120
                    . '</a> | <a href="topten.php?list=hit">'
2121
                    . _MD_XOOPSTUBE_POPULARITY
2122
                    . '</a> | <a href="topten.php?list=rate">'
2123
                    . _MD_XOOPSTUBE_TOPRATED
2124
                    . '</a> ]';
2125
2126
        return $toolbar;
2127
    }
2128
2129
    /**
2130
     *
2131
     */
2132
    public static function xtubeGetServerStatistics()
2133
    {
2134
        global $xoopsModule;
2135
        echo '<fieldset style="border: #E8E8E8 1px solid;">
2136
          <legend style="display: inline; font-weight: bold; color: #0A3760;">' . _AM_XOOPSTUBE_VIDEO_IMAGEINFO . '</legend>
2137
          <div style="padding: 8px;">
2138
            <img src="' . XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname') . '/assets/images/icon/server.png" alt="" style="float: left; padding-right: 10px;" />
2139
          <div>' . _AM_XOOPSTUBE_VIDEO_SPHPINI . '</div>';
2140
2141
        //    $safemode        = ini_get('safe_mode') ? _AM_XOOPSTUBE_VIDEO_ON . _AM_XOOPSTUBE_VIDEO_SAFEMODEPROBLEMS : _AM_XOOPSTUBE_VIDEO_OFF;
2142
        //    $registerglobals = (ini_get('register_globals') === '') ? _AM_XOOPSTUBE_VIDEO_OFF : _AM_XOOPSTUBE_VIDEO_ON;
2143
        $videos = ini_get('file_uploads') ? _AM_XOOPSTUBE_VIDEO_ON : _AM_XOOPSTUBE_VIDEO_OFF;
2144
2145
        $gdlib = function_exists('gd_info') ? _AM_XOOPSTUBE_VIDEO_GDON : _AM_XOOPSTUBE_VIDEO_GDOFF;
2146
        echo '<li>' . _AM_XOOPSTUBE_VIDEO_GDLIBSTATUS . $gdlib;
2147
        if (function_exists('gd_info')) {
2148
            if (true === $gdlib = gd_info()) {
2149
                echo '<li>' . _AM_XOOPSTUBE_VIDEO_GDLIBVERSION . '<b>' . $gdlib['GD Version'] . '</b>';
2150
            }
2151
        }
2152
        echo '<br><br>';
2153
        //    echo '<li>' . _AM_XOOPSTUBE_VIDEO_SAFEMODESTATUS . $safemode;
2154
        //    echo '<li>' . _AM_XOOPSTUBE_VIDEO_REGISTERGLOBALS . $registerglobals;
2155
        echo '<li>' . _AM_XOOPSTUBE_VIDEO_SERVERUPLOADSTATUS . $videos;
2156
        echo '</div>';
2157
        echo '</fieldset>';
2158
    }
2159
2160
    // xtubeDisplayIcons()
2161
    //
2162
    // @param  $time
2163
    // @param integer $status
2164
    // @param integer $counter
2165
    // @return
2166
    /**
2167
     * @param     $time
2168
     * @param int $status
2169
     * @param int $counter
2170
     *
2171
     * @return string
2172
     */
2173
    public static function xtubeDisplayIcons($time, $status = 0, $counter = 0)
2174
    {
2175
        global $xoopsModule;
2176
2177
        $new = '';
2178
        $pop = '';
2179
2180
        $newdate = (time() - (86400 * (int)$GLOBALS['xoopsModuleConfig']['daysnew']));
2181
        $popdate = (time() - (86400 * (int)$GLOBALS['xoopsModuleConfig']['daysupdated']));
2182
2183
        if ($GLOBALS['xoopsModuleConfig']['displayicons'] !== 3) {
2184
            if ($newdate < $time) {
2185
                if ((int)$status > 1) {
2186 View Code Duplication
                    if ($GLOBALS['xoopsModuleConfig']['displayicons'] === 1) {
2187
                        $new = '&nbsp;<img src="' . XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname') . '/assets/images/icon/updated.gif" alt="" style="vertical-align: middle;" />';
2188
                    }
2189
                    if ($GLOBALS['xoopsModuleConfig']['displayicons'] === 2) {
2190
                        $new = '<em>' . _MD_XOOPSTUBE_UPDATED . '</em>';
2191
                    }
2192
                } else {
2193 View Code Duplication
                    if ($GLOBALS['xoopsModuleConfig']['displayicons'] === 1) {
2194
                        $new = '&nbsp;<img src="' . XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname') . '/assets/images/icon/new.gif" alt="" style="vertical-align: middle;" />';
2195
                    }
2196
                    if ($GLOBALS['xoopsModuleConfig']['displayicons'] === 2) {
2197
                        $new = '<em>' . _MD_XOOPSTUBE_NEW . '</em>';
2198
                    }
2199
                }
2200
            }
2201
            if ($popdate > $time) {
2202
                if ($counter >= $GLOBALS['xoopsModuleConfig']['popular']) {
2203 View Code Duplication
                    if ($GLOBALS['xoopsModuleConfig']['displayicons'] === 1) {
2204
                        $pop = '&nbsp;<img src="' . XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname') . '/assets/images/icon/popular.png" alt="" style="vertical-align: middle;" />';
2205
                    }
2206
                    if ($GLOBALS['xoopsModuleConfig']['displayicons'] === 2) {
2207
                        $pop = '<em>' . _MD_XOOPSTUBE_POPULAR . '!</em>';
2208
                    }
2209
                }
2210
            }
2211
        }
2212
        $icons = $new . ' ' . $pop;
2213
2214
        return $icons;
2215
    }
2216
2217
    // Reusable Link Sorting Functions
2218
    // xtubeConvertOrderByIn()
2219
    // @param  $orderby
2220
    // @return
2221
    /**
2222
     * @param $orderby
2223
     *
2224
     * @return string
2225
     */
2226 View Code Duplication
    public static function xtubeConvertOrderByIn($orderby)
2227
    {
2228
        switch (trim($orderby)) {
2229
            case 'titleA':
2230
                $orderby = 'title ASC';
2231
                break;
2232
            case 'dateA':
2233
                $orderby = 'published ASC';
2234
                break;
2235
            case 'hitsA':
2236
                $orderby = 'hits ASC';
2237
                break;
2238
            case 'ratingA':
2239
                $orderby = 'rating ASC';
2240
                break;
2241
            case 'countryA':
2242
                $orderby = 'country ASC';
2243
                break;
2244
            case 'titleD':
2245
                $orderby = 'title DESC';
2246
                break;
2247
            case 'hitsD':
2248
                $orderby = 'hits DESC';
2249
                break;
2250
            case 'ratingD':
2251
                $orderby = 'rating DESC';
2252
                break;
2253
            case'dateD':
2254
                $orderby = 'published DESC';
2255
                break;
2256
            case 'countryD':
2257
                $orderby = 'country DESC';
2258
                break;
2259
        }
2260
2261
        return $orderby;
2262
    }
2263
2264
    /**
2265
     * @param $orderby
2266
     *
2267
     * @return string
2268
     */
2269
    public static function xtubeConvertOrderByTrans($orderby)
2270
    {
2271
        switch ($orderby) {
2272
            case 'hits ASC':
2273
                $orderByTrans = _MD_XOOPSTUBE_POPULARITYLTOM;
2274
                break;
2275
            case 'hits DESC':
2276
                $orderByTrans = _MD_XOOPSTUBE_POPULARITYMTOL;
2277
                break;
2278
            case 'title ASC':
2279
                $orderByTrans = _MD_XOOPSTUBE_TITLEATOZ;
2280
                break;
2281
            case 'title DESC':
2282
                $orderByTrans = _MD_XOOPSTUBE_TITLEZTOA;
2283
                break;
2284
            case 'published ASC':
2285
                $orderByTrans = _MD_XOOPSTUBE_DATEOLD;
2286
                break;
2287
            case 'published DESC':
2288
                $orderByTrans = _MD_XOOPSTUBE_DATENEW;
2289
                break;
2290
            case 'rating ASC':
2291
                $orderByTrans = _MD_XOOPSTUBE_RATINGLTOH;
2292
                break;
2293
            case 'rating DESC':
2294
                $orderByTrans = _MD_XOOPSTUBE_RATINGHTOL;
2295
                break;
2296
            case'country ASC':
2297
                $orderByTrans = _MD_XOOPSTUBE_COUNTRYLTOH;
2298
                break;
2299
            case 'country DESC':
2300
                $orderByTrans = _MD_XOOPSTUBE_COUNTRYHTOL;
2301
                break;
2302
        }
2303
2304
        return $orderByTrans;
2305
    }
2306
2307
    /**
2308
     * @param $orderby
2309
     *
2310
     * @return string
2311
     */
2312 View Code Duplication
    public static function xtubeConvertOrderByOut($orderby)
2313
    {
2314
        switch ($orderby) {
2315
            case 'title ASC':
2316
                $orderby = 'titleA';
2317
                break;
2318
            case 'published ASC':
2319
                $orderby = 'dateA';
2320
                break;
2321
            case 'hits ASC':
2322
                $orderby = 'hitsA';
2323
                break;
2324
            case 'rating ASC':
2325
                $orderby = 'ratingA';
2326
                break;
2327
            case 'country ASC':
2328
                $orderby = 'countryA';
2329
                break;
2330
            case 'title DESC':
2331
                $orderby = 'titleD';
2332
                break;
2333
            case 'published DESC':
2334
                $orderby = 'dateD';
2335
                break;
2336
            case 'hits DESC':
2337
                $orderby = 'hitsD';
2338
                break;
2339
            case 'rating DESC':
2340
                $orderby = 'ratingD';
2341
                break;
2342
            case 'country DESC':
2343
                $orderby = 'countryD';
2344
                break;
2345
        }
2346
2347
        return $orderby;
2348
    }
2349
2350
    // updaterating()
2351
    // @param  $sel_id
2352
    // @return updates rating data in itemtable for a given item
2353
    /**
2354
     * @param $sel_id
2355
     */
2356
    public static function xtubeUpdateRating($sel_id)
2357
    {
2358
        $query       = 'SELECT rating FROM ' . $GLOBALS['xoopsDB']->prefix('xoopstube_votedata') . ' WHERE lid=' . $sel_id;
2359
        $voteresult  = $GLOBALS['xoopsDB']->query($query);
2360
        $votesDB     = $GLOBALS['xoopsDB']->getRowsNum($voteresult);
2361
        $totalrating = 0;
2362
        while (false !== (list($rating) = $GLOBALS['xoopsDB']->fetchRow($voteresult))) {
2363
            $totalrating += $rating;
2364
        }
2365
        $finalrating = $totalrating / $votesDB;
2366
        $finalrating = number_format($finalrating, 4);
2367
        $sql         = sprintf('UPDATE %s SET rating = %u, votes = %u WHERE lid = %u', $GLOBALS['xoopsDB']->prefix('xoopstube_videos'), $finalrating, $votesDB, $sel_id);
2368
        $GLOBALS['xoopsDB']->query($sql);
2369
    }
2370
2371
    // totalcategory()
2372
    // @param integer $pid
2373
    // @return
2374
    /**
2375
     * @param int $pid
2376
     *
2377
     * @return int
2378
     */
2379
    public static function xtubeGetTotalCategoryCount($pid = 0)
2380
    {
2381
        $sql = 'SELECT cid FROM ' . $GLOBALS['xoopsDB']->prefix('xoopstube_cat');
2382
        if ($pid > 0) {
2383
            $sql .= ' WHERE pid = 0';
2384
        }
2385
        $result     = $GLOBALS['xoopsDB']->query($sql);
2386
        $catlisting = 0;
2387
        while (false !== (list($cid) = $GLOBALS['xoopsDB']->fetchRow($result))) {
2388
            if (XoopstubeUtility::xtubeCheckGroups($cid)) {
2389
                ++$catlisting;
2390
            }
2391
        }
2392
2393
        return $catlisting;
2394
    }
2395
2396
    // xtubeGetTotalItems()
2397
    // @param integer $sel_id
2398
    // @param integer $get_child
2399
    // @param integer $return_sql
2400
    // @return
2401
    /**
2402
     * @param int $sel_id
2403
     * @param int $get_child
2404
     * @param int $return_sql
2405
     *
2406
     * @return string
2407
     */
2408
    public static function xtubeGetTotalItems($sel_id = 0, $get_child = 0, $return_sql = 0)
2409
    {
2410
        global $mytree, $_check_array;
2411
2412
        if ($sel_id > 0) {
2413
            $sql = 'SELECT a.lid, a.cid, a.published FROM '
2414
                   . $GLOBALS['xoopsDB']->prefix('xoopstube_videos')
2415
                   . ' a LEFT JOIN '
2416
                   . $GLOBALS['xoopsDB']->prefix('xoopstube_altcat')
2417
                   . ' b'
2418
                   . ' ON b.lid=a.lid'
2419
                   . ' WHERE a.published > 0 AND a.published <= '
2420
                   . time()
2421
                   . ' AND (a.expired = 0 OR a.expired > '
2422
                   . time()
2423
                   . ') AND offline = 0 '
2424
                   . ' AND (b.cid=a.cid OR (a.cid='
2425
                   . $sel_id
2426
                   . ' OR b.cid='
2427
                   . $sel_id
2428
                   . '))'
2429
                   . ' GROUP BY a.lid, a.cid, a.published';
2430
        } else {
2431
            $sql = 'SELECT lid, cid, published FROM '
2432
                   . $GLOBALS['xoopsDB']->prefix('xoopstube_videos')
2433
                   . ' WHERE offline = 0 AND published > 0 AND published <= '
2434
                   . time()
2435
                   . ' AND (expired = 0 OR expired > '
2436
                   . time()
2437
                   . ')';
2438
        }
2439
        if ($return_sql === 1) {
2440
            return $sql;
2441
        }
2442
2443
        $count          = 0;
2444
        $published_date = 0;
2445
2446
        $arr    = array();
2447
        $result = $GLOBALS['xoopsDB']->query($sql);
2448 View Code Duplication
        while (false !== (list($lid, $cid, $published) = $GLOBALS['xoopsDB']->fetchRow($result))) {
0 ignored issues
show
This code seems to be duplicated across 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...
2449
            if (true === XoopstubeUtility::xtubeCheckGroups()) {
2450
                ++$count;
2451
                $published_date = ($published > $published_date) ? $published : $published_date;
2452
            }
2453
        }
2454
2455
        $child_count = 0;
2456
        if ($get_child === 1) {
2457
            $arr  = $mytree->getAllChildId($sel_id);
2458
            $size = count($arr);
2459
            for ($i = 0, $iMax = count($arr); $i < $iMax; ++$i) {
2460
                $query2 = 'SELECT a.lid, a.published, a.cid FROM '
2461
                          . $GLOBALS['xoopsDB']->prefix('xoopstube_videos')
2462
                          . ' a LEFT JOIN '
2463
                          . $GLOBALS['xoopsDB']->prefix('xoopstube_altcat')
2464
                          . ' b'
2465
                          . ' ON b.lid = a.lid'
2466
                          . ' WHERE a.published > 0 AND a.published <= '
2467
                          . time()
2468
                          . ' AND (a.expired = 0 OR a.expired > '
2469
                          . time()
2470
                          . ') AND offline = 0'
2471
                          . ' AND (b.cid=a.cid OR (a.cid='
2472
                          . $arr[$i]
2473
                          . ' OR b.cid='
2474
                          . $arr[$i]
2475
                          . ')) GROUP BY a.lid, a.published, a.cid';
2476
2477
                $result2 = $GLOBALS['xoopsDB']->query($query2);
2478 View Code Duplication
                while (false !== (list($lid, $published) = $GLOBALS['xoopsDB']->fetchRow($result2))) {
0 ignored issues
show
This code seems to be duplicated across 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...
2479
                    if ($published === 0) {
2480
                        continue;
2481
                    }
2482
                    $published_date = ($published > $published_date) ? $published : $published_date;
2483
                    ++$child_count;
2484
                }
2485
            }
2486
        }
2487
        $info['count']     = $count + $child_count;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$info was never initialized. Although not strictly required by PHP, it is generally a good practice to add $info = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
2488
        $info['published'] = $published_date;
2489
2490
        return $info;
2491
    }
2492
2493
    /**
2494
     * @param string $indeximage
2495
     * @param string $indexheading
2496
     *
2497
     * @return string
2498
     */
2499
    public static function xtubeRenderImageHeader($indeximage = '', $indexheading = '')
2500
    {
2501 View Code Duplication
        if ($indeximage === '') {
2502
            $result = $GLOBALS['xoopsDB']->query('SELECT indeximage, indexheading FROM ' . $GLOBALS['xoopsDB']->prefix('xoopstube_indexpage'));
2503
            list($indeximage, $indexheading) = $GLOBALS['xoopsDB']->fetchrow($result);
2504
        }
2505
2506
        $image = '';
2507
        if (!empty($indeximage)) {
2508
            $image = XoopstubeUtility::xtubeDisplayImage($indeximage, 'index.php', $GLOBALS['xoopsModuleConfig']['mainimagedir'], $indexheading);
2509
        }
2510
2511
        return $image;
2512
    }
2513
2514
    /**
2515
     * @param string $image
2516
     * @param string $path
2517
     * @param string $imgsource
2518
     * @param string $alttext
2519
     *
2520
     * @return string
2521
     */
2522
    public static function xtubeDisplayImage($image = '', $path = '', $imgsource = '', $alttext = '')
2523
    {
2524
        global $xoopsModule;
2525
2526
        $showimage = '';
2527
        // Check to see if link is given
2528
        if ($path) {
2529
            $showimage = '<a href="' . $path . '">';
2530
        }
2531
        // checks to see if the file is valid else displays default blank image
2532
        if (!is_dir(XOOPS_ROOT_PATH . "/{$imgsource}/{$image}")
2533
            && file_exists(XOOPS_ROOT_PATH . "/{$imgsource}/{$image}")
2534
        ) {
2535
            $showimage .= "<img src='" . XOOPS_URL . "/{$imgsource}/{$image}' border='0' title='" . $alttext . "' alt='" . $alttext . "' /></a>";
2536
        } else {
2537
            if ($GLOBALS['xoopsUser'] && $GLOBALS['xoopsUser']->isAdmin($xoopsModule->getVar('mid'))) {
2538
                $showimage .= '<img src="' . XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname') . '/assets/images/brokenimg.png" alt="' . _MD_XOOPSTUBE_ISADMINNOTICE . '" /></a>';
2539
            } else {
2540
                $showimage .= '<img src="' . XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname') . '/assets/images/blank.png" alt="' . $alttext . '" /></a>';
2541
            }
2542
        }
2543
        clearstatcache();
2544
2545
        return $showimage;
2546
    }
2547
2548
    /**
2549
     * @param $published
2550
     *
2551
     * @return mixed
2552
     */
2553
    public static function xtubeIsNewImage($published)
2554
    {
2555
        global $xoopsModule;
2556
2557
        $oneday    = (time() - (86400 * 1));
2558
        $threedays = (time() - (86400 * 3));
2559
        $week      = (time() - (86400 * 7));
2560
2561
        $path = 'modules/' . $xoopsModule->getVar('dirname') . '/assets/images/icon';
2562
2563
        if ($published > 0 && $published < $week) {
2564
            $indicator['image']   = "$path/linkload4.png";
2565
            $indicator['alttext'] = _MD_XOOPSTUBE_NEWLAST;
2566
        } elseif ($published >= $week && $published < $threedays) {
2567
            $indicator['image']   = "$path/linkload3.png";
2568
            $indicator['alttext'] = _MD_XOOPSTUBE_NEWTHIS;
2569
        } elseif ($published >= $threedays && $published < $oneday) {
2570
            $indicator['image']   = "$path/linkload2.png";
2571
            $indicator['alttext'] = _MD_XOOPSTUBE_THREE;
2572
        } elseif ($published >= $oneday) {
2573
            $indicator['image']   = "$path/linkload1.png";
2574
            $indicator['alttext'] = _MD_XOOPSTUBE_TODAY;
2575
        } else {
2576
            $indicator['image']   = "$path/linkload.png";
2577
            $indicator['alttext'] = _MD_XOOPSTUBE_NO_FILES;
2578
        }
2579
2580
        return $indicator;
2581
    }
2582
2583
    /**
2584
     * @param $haystack
2585
     * @param $needle
2586
     *
2587
     * @return string
2588
     */
2589
    public static function xtubeFindStringChar($haystack, $needle)
2590
    {
2591
        return substr($haystack, 0, strpos($haystack, $needle) + 1);
2592
    }
2593
2594
    /**
2595
     * @param string $header
2596
     * @param string $menu
2597
     * @param string $extra
2598
     * @param int    $scount
2599
     *
2600
     * @return bool|null
2601
     */
2602
    public static function xtubeRenderAdminMenu($header = '', $menu = '', $extra = '', $scount = 4)
2603
    {
2604
        global $xoopsModule;
2605
2606
        $_named_vidid = xoops_getenv('PHP_SELF');
2607
        if ($_named_vidid) {
2608
            $thispage = basename($_named_vidid);
2609
        }
2610
2611
        //    $op = (isset($_GET['op'])) ? $op = '?op=' . $_GET['op'] : '';
2612
        $op = XoopsRequest::getCmd('op', '', 'GET');
2613
        echo '<h4 style="color: #2F5376;">' . _AM_XOOPSTUBE_MODULE_NAME . '</h4>';
2614
        echo '
2615
        <div style="font-size: 10px; text-align: left; color: #2F5376; padding: 2px 6px; line-height: 18px;">
2616
        <span style="margin: 1px; padding: 4px; border: #E8E8E8 1px solid;">
2617
            <a href="../admin/index.php">' . _AM_XOOPSTUBE_BINDEX . '</a>
2618
        </span>
2619
        <span  style="margin: 1px; padding: 4px; border: #E8E8E8 1px solid;">
2620
            <a href="../index.php">' . _AM_XOOPSTUBE_GOMODULE . '</a>
2621
        </span>
2622
        <span  style="margin: 1px; padding: 4px; border: #E8E8E8 1px solid;">
2623
            <a href="../../system/admin.php?fct=preferences&op=showmod&mod=' . $xoopsModule->getVar('mid') . '">' . _AM_XOOPSTUBE_PREFS . '</a>
2624
        </span>
2625
        <span  style="margin: 1px; padding: 4px; border: #E8E8E8 1px solid;">
2626
            <a href="../admin/permissions.php">' . _AM_XOOPSTUBE_BPERMISSIONS . '</a>
2627
        </span>
2628
        <span  style="margin: 1px; padding: 4px; border: #E8E8E8 1px solid;">
2629
            <a href="../admin/myblocksadmin.php">' . _AM_XOOPSTUBE_BLOCKADMIN . '</a>
2630
        </span>
2631
        <span  style="margin: 1px; padding: 4px; border: #E8E8E8 1px solid;">
2632
            <a href="../../system/admin.php?fct=modulesadmin&op=update&module=' . $xoopsModule->getVar('dirname') . '">' . _AM_XOOPSTUBE_BUPDATE . '</a>
2633
        </span>
2634
        <span  style="margin: 1px; padding: 4px; border: #E8E8E8 1px solid;">
2635
            <a href="../admin/about.php">' . _AM_XOOPSTUBE_ABOUT . '</a>
2636
        </span>
2637
        </div><br>';
2638
2639
        if (empty($menu)) {
2640
            // You can change this part to suit your own module. Defining this here will save you form having to do this each time.
2641
            $menu = array(
2642
                _AM_XOOPSTUBE_MVIDEOS   => 'main.php?op=edit',
2643
                _AM_XOOPSTUBE_MCATEGORY => 'category.php',
2644
                _AM_XOOPSTUBE_INDEXPAGE => 'indexpage.php',
2645
                //            _AM_XOOPSTUBE_MXOOPSTUBE     => 'main.php?op=edit',
2646
                _AM_XOOPSTUBE_MUPLOADS  => 'upload.php',
2647
                _AM_XOOPSTUBE_VUPLOADS  => 'vupload.php',
2648
                _AM_XOOPSTUBE_MVOTEDATA => 'votedata.php',
2649
                _AM_XOOPSTUBE_MCOMMENTS => '../../system/admin.php?module=' . $xoopsModule->getVar('mid') . '&status=0&limit=100&fct=comments&selsubmit=Go'
2650
            );
2651
        }
2652
2653
        if (!is_array($menu)) {
2654
            echo '<table width="100%" cellpadding="2" cellspacing="1" class="outer">';
2655
            echo '<tr><td class="even" align="center"><b>' . _AM_XOOPSTUBE_NOMENUITEMS . '</b></td></tr></table><br>';
2656
2657
            return false;
2658
        }
2659
2660
        $oddnum = array(
2661
            1  => '1',
2662
            3  => '3',
2663
            5  => '5',
2664
            7  => '7',
2665
            9  => '9',
2666
            11 => '11',
2667
            13 => '13'
2668
        );
2669
        // number of rows per menu
2670
        $menurows = count($menu) / $scount;
2671
        // total amount of rows to complete menu
2672
        $menurow = ceil($menurows) * $scount;
2673
        // actual number of menuitems per row
2674
        $rowcount = $menurow / ceil($menurows);
2675
        $count    = 0;
2676
        for ($i = count($menu); $i < $menurow; ++$i) {
2677
            $tempArray = array(1 => null);
2678
            $menu      = array_merge($menu, $tempArray);
2679
            ++$count;
2680
        }
2681
2682
        // Sets up the width of each menu cell
2683
        $width = 100 / $scount;
2684
        $width = ceil($width);
2685
2686
        $menucount = 0;
2687
        $count     = 0;
2688
        // Menu table output
2689
        echo '<table width="100%" cellpadding="2" cellspacing="1" class="outer" border="1"><tr>';
2690
        // Check to see if $menu is and array
2691
        if (is_array($menu)) {
2692
            $classcounts = 0;
2693
            $classcol[0] = 'even';
0 ignored issues
show
Coding Style Comprehensibility introduced by
$classcol was never initialized. Although not strictly required by PHP, it is generally a good practice to add $classcol = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
2694
2695
            for ($i = 1; $i < $menurow; ++$i) {
2696
                ++$classcounts;
2697
                if ($classcounts >= $scount) {
2698
                    if ($classcol[$i - 1] === 'odd') {
2699
                        $classcol[$i] = ($classcol[$i - 1] === 'odd'
2700
                                         && in_array($classcounts, $oddnum)) ? 'even' : 'odd';
2701
                    } else {
2702
                        $classcol[$i] = ($classcol[$i - 1] === 'even'
2703
                                         && in_array($classcounts, $oddnum)) ? 'odd' : 'even';
2704
                    }
2705
                    $classcounts = 0;
2706
                } else {
2707
                    $classcol[$i] = ($classcol[$i - 1] === 'even') ? 'odd' : 'even';
2708
                }
2709
            }
2710
            unset($classcounts);
2711
2712
            foreach ($menu as $menutitle => $menuvideo) {
2713
                if ($thispage . $op === $menuvideo) {
0 ignored issues
show
The variable $thispage 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...
2714
                    $classcol[$count] = 'outer';
2715
                }
2716
                echo '<td class="' . $classcol[$count] . '" style="padding: 4px; text-align: center;" valign="middle" width="' . $width . '%">';
2717
                if (is_string($menuvideo)) {
2718
                    echo '<a href="' . $menuvideo . '"><span style="font-size: small;">' . $menutitle . '</span></a></td>';
2719
                } else {
2720
                    echo '&nbsp;</td>';
2721
                }
2722
                ++$menucount;
2723
                ++$count;
2724
                // Break menu cells to start a new row if $count > $scount
2725
                if ($menucount >= $scount) {
2726
                    echo '</tr>';
2727
                    $menucount = 0;
2728
                }
2729
            }
2730
            echo '</table><br>';
2731
            unset($count);
2732
            unset($menucount);
2733
        }
2734
        // ###### Output warn messages for security ######
2735
        if (is_dir(XOOPS_ROOT_PATH . '/modules/' . $xoopsModule->getVar('dirname') . '/update/')) {
2736
            xoops_error(sprintf(_AM_XOOPSTUBE_WARNINSTALL1, XOOPS_ROOT_PATH . '/modules/' . $xoopsModule->getVar('dirname') . '/update/'));
2737
            echo '<br>';
2738
        }
2739
2740
        $_file = XOOPS_ROOT_PATH . '/modules/' . $xoopsModule->getVar('dirname') . '/update.php';
2741
        if (file_exists($_file)) {
2742
            xoops_error(sprintf(_AM_XOOPSTUBE_WARNINSTALL2, XOOPS_ROOT_PATH . '/modules/' . $xoopsModule->getVar('dirname') . '/update.php'));
2743
            echo '<br>';
2744
        }
2745
2746
        $path1 = XOOPS_ROOT_PATH . '/' . $GLOBALS['xoopsModuleConfig']['mainimagedir'];
2747
        if (!is_dir($path1)) {
2748
            xoops_error(sprintf(_AM_XOOPSTUBE_WARNINSTALL3, $path1));
2749
            echo '<br>';
2750
        }
2751
        if (!is_writable($path1)) {
2752
            xoops_error(sprintf(_AM_XOOPSTUBE_WARNINSTALL4, $path1));
2753
            echo '<br>';
2754
        }
2755
2756
        $path1_t = XOOPS_ROOT_PATH . '/' . $GLOBALS['xoopsModuleConfig']['mainimagedir'] . '/thumbs';
2757
        if (!is_dir($path1_t)) {
2758
            xoops_error(sprintf(_AM_XOOPSTUBE_WARNINSTALL3, $path1_t));
2759
            echo '<br>';
2760
        }
2761
        if (!is_writable($path1_t)) {
2762
            xoops_error(sprintf(_AM_XOOPSTUBE_WARNINSTALL4, $path1_t));
2763
            echo '<br>';
2764
        }
2765
2766
        $path2 = XOOPS_ROOT_PATH . '/' . $GLOBALS['xoopsModuleConfig']['videoimgdir'];
2767
        if (!is_dir($path2)) {
2768
            xoops_error(sprintf(_AM_XOOPSTUBE_WARNINSTALL3, $path2));
2769
            echo '<br>';
2770
        }
2771
        if (!is_writable($path2)) {
2772
            xoops_error(sprintf(_AM_XOOPSTUBE_WARNINSTALL4, $path2));
2773
            echo '<br>';
2774
        }
2775
2776
        //    $path2_t = XOOPS_ROOT_PATH . '/' . $GLOBALS['xoopsModuleConfig']['videoimgdir'] . '/thumbs';
2777
        //    if ( !is_dir( $path2_t ) || !is_writable( $path2_t ) ) {
2778
        //        xoops_error( sprintf( _AM_XOOPSTUBE_WARNINSTALL3, $path2_t ) );
2779
        //        echo '<br>';
2780
        //    }
2781
2782
        $path3 = XOOPS_ROOT_PATH . '/' . $GLOBALS['xoopsModuleConfig']['catimage'];
2783
        if (!is_dir($path3)) {
2784
            xoops_error(sprintf(_AM_XOOPSTUBE_WARNINSTALL3, $path3));
2785
            echo '<br>';
2786
        }
2787
        if (!is_writable($path3)) {
2788
            xoops_error(sprintf(_AM_XOOPSTUBE_WARNINSTALL4, $path3));
2789
            echo '<br>';
2790
        }
2791
2792
        $path3_t = XOOPS_ROOT_PATH . '/' . $GLOBALS['xoopsModuleConfig']['catimage'] . '/thumbs';
2793
        if (!is_dir($path3_t)) {
2794
            xoops_error(sprintf(_AM_XOOPSTUBE_WARNINSTALL3, $path3_t));
2795
            echo '<br>';
2796
        }
2797
        if (!is_writable($path3_t)) {
2798
            xoops_error(sprintf(_AM_XOOPSTUBE_WARNINSTALL4, $path3_t));
2799
            echo '<br>';
2800
        }
2801
2802
        $path4 = XOOPS_ROOT_PATH . '/' . $GLOBALS['xoopsModuleConfig']['videodir'];
2803
        if (!is_dir($path4)) {
2804
            xoops_error(sprintf(_AM_XOOPSTUBE_WARNINSTALL3, $path4));
2805
            echo '<br>';
2806
        }
2807
        if (!is_writable($path4)) {
2808
            xoops_error(sprintf(_AM_XOOPSTUBE_WARNINSTALL4, $path4));
2809
            echo '<br>';
2810
        }
2811
2812
        echo '<h4 style="color: #2F5376;">' . $header . '</h4>';
2813
        if ($extra) {
2814
            echo '<div>' . $extra . '</div>';
2815
        }
2816
2817
        return null;
2818
    }
2819
2820
    /**
2821
     * @param $selected
2822
     * @param $dirarray
2823
     * @param $namearray
2824
     */
2825 View Code Duplication
    public static function xtubeGetDirSelectOption($selected, $dirarray, $namearray)
2826
    {
2827
        echo "<select size='1' name='workd' onchange='location.href=\"upload.php?rootpath=\"+this.options[this.selectedIndex].value'>";
2828
        echo "<option value=''>--------------------------------------</option>";
2829
        foreach ($namearray as $namearray => $workd) {
2830
            if ($workd === $selected) {
2831
                $opt_selected = 'selected';
2832
            } else {
2833
                $opt_selected = '';
2834
            }
2835
            echo '<option value="' . htmlspecialchars($namearray, ENT_QUOTES) . '" $opt_selected>' . $workd . '</option>';
2836
        }
2837
        echo '</select>';
2838
    }
2839
2840
    /**
2841
     * @param $selected
2842
     * @param $dirarray
2843
     * @param $namearray
2844
     */
2845 View Code Duplication
    public static function xtubeVGetDirSelectOption($selected, $dirarray, $namearray)
2846
    {
2847
        echo "<select size='1' name='workd' onchange='location.href=\"vupload.php?rootpath=\"+this.options[this.selectedIndex].value'>";
2848
        echo "<option value=''>--------------------------------------</option>";
2849
        foreach ($namearray as $namearray => $workd) {
2850
            if ($workd === $selected) {
2851
                $opt_selected = 'selected';
2852
            } else {
2853
                $opt_selected = '';
2854
            }
2855
            echo '<option value="' . htmlspecialchars($namearray, ENT_QUOTES) . '" $opt_selected>' . $workd . '</option>';
2856
        }
2857
        echo '</select>';
2858
    }
2859
2860
    /**
2861
     * @param        $FILES
2862
     * @param string $uploaddir
2863
     * @param string $allowed_mimetypes
2864
     * @param string $redirecturl
2865
     * @param int    $redirect
2866
     * @param int    $usertype
2867
     *
2868
     * @return array|null
2869
     */
2870
    public static function xtubeUploadFiles(
2871
        $FILES,
2872
        $uploaddir = 'uploads',
2873
        $allowed_mimetypes = '',
2874
        $redirecturl = 'index.php', //    $num = 0,
2875
        $redirect = 0,
2876
        $usertype = 1
2877
    ) {
2878
        global $FILES, $xoopsModule;
2879
2880
        $down = array();
2881
        require_once XOOPS_ROOT_PATH . '/modules/' . $xoopsModule->getVar('dirname') . '/class/uploader.php';
2882
        if (empty($allowed_mimetypes)) {
2883
            $allowed_mimetypes = xtube_retmime($FILES['userfile']['name'], $usertype);
2884
        }
2885
        $upload_dir = XOOPS_ROOT_PATH . '/' . $uploaddir . '/';
2886
2887
        $maxfilesize = $GLOBALS['xoopsModuleConfig']['maxfilesize'];
2888
2889
        $maxfilewidth  = $GLOBALS['xoopsModuleConfig']['maximgwidth'];
2890
        $maxfileheight = $GLOBALS['xoopsModuleConfig']['maximgheight'];
2891
2892
        $uploader = new XoopsMediaUploader($upload_dir, $allowed_mimetypes, $maxfilesize, $maxfilewidth, $maxfileheight);
2893
        $uploader->noAdminSizeCheck(1);
2894
        if ($uploader->fetchMedia(XoopsRequest::getArray('xoops_upload_file[0]', array(), 'POST'))) {
2895
            if (!$uploader->upload()) {
2896
                $errors = $uploader->getErrors();
2897
                redirect_header($redirecturl, 2, $errors);
2898
            } else {
2899
                if ($redirect) {
2900
                    redirect_header($redirecturl, 1, _AM_XOOPSTUBE_UPLOADFILE);
2901
                } else {
2902
                    if (is_file($uploader->savedDestination)) {
2903
                        $down['url']  = XOOPS_URL . '/' . $uploaddir . '/' . strtolower($uploader->savedFileName);
2904
                        $down['size'] = filesize(XOOPS_ROOT_PATH . '/' . $uploaddir . '/' . strtolower($uploader->savedFileName));
2905
                    }
2906
2907
                    return $down;
2908
                }
2909
            }
2910
        } else {
2911
            $errors = $uploader->getErrors();
2912
            redirect_header($redirecturl, 1, $errors);
2913
        }
2914
2915
        return null;
2916
    }
2917
2918
    /**
2919
     * @param $heading
2920
     */
2921 View Code Duplication
    public static function xtubeRenderCategoryListHeader($heading)
2922
    {
2923
        echo '
2924
        <h4 style="font-weight: bold; color: #0A3760;">' . $heading . '</h4>
2925
        <table width="100%" cellspacing="1" class="outer" summary>
2926
        <tr>
2927
            <th style="text-align: center; font-size: smaller;">' . _AM_XOOPSTUBE_MINDEX_ID . '</th>
2928
            <th style=" font-size: smaller;"><b>' . _AM_XOOPSTUBE_FCATEGORY_TITLE . '</th>
2929
            <th style="text-align: center; font-size: smaller;">' . _AM_XOOPSTUBE_FCATEGORY_WEIGHT . '</th>
2930
            <th style="text-align: center; font-size: smaller;">' . _AM_XOOPSTUBE_FCATEGORY_CIMAGE . '</th>
2931
            <th style="text-align: center; font-size: smaller;">' . _AM_XOOPSTUBE_CATSPONSOR . '</th>
2932
<!--            <th style="text-align: center; font-size: smaller;">' . _AM_XOOPSTUBE_MINDEX_PUBLISH . '</th>
2933
            <th style="text-align: center; font-size: smaller;">' . _AM_XOOPSTUBE_MINDEX_EXPIRE . '</th>
2934
            <th style="text-align: center; font-size: smaller;">' . _AM_XOOPSTUBE_MINDEX_ONLINE . '</th>
2935
            <th style="text-align: center; font-size: smaller;">' . _AM_XOOPSTUBE_MINDEX_ACTION . '</th> -->
2936
        </tr>
2937
        ';
2938
    }
2939
2940
    /**
2941
     * @param $published
2942
     */
2943
    public static function xtubeRenderCategoryListBody($published)
2944
    {
2945
        global $xtubemyts, $xtubeImageArray;
2946
2947
        $lid = $published['lid'];
2948
        $cid = $published['cid'];
2949
2950
        $title        = '<a href="../singlevideo.php?cid=' . $published['cid'] . '&amp;lid=' . $published['lid'] . '">' . $xtubemyts->htmlSpecialCharsStrip(trim($published['title'])) . '</a>';
2951
        $maintitle    = urlencode($xtubemyts->htmlSpecialChars(trim($published['title'])));
2952
        $cattitle     = '<a href="../viewcat.php?cid=' . $published['cid'] . '">' . XoopstubeUtility::xtubeGetCategoryTitle($published['cid']) . '</a>';
2953
        $submitter    = XoopstubeUtility::xtubeGetLinkedUserNameFromId($published['submitter']);
2954
        $returnsource = xtubeReturnSource($published['vidsource']);
2955
        $submitted    = XoopstubeUtility::xtubeGetTimestamp(formatTimestamp($published['date'], $GLOBALS['xoopsModuleConfig']['dateformatadmin']));
2956
        $publish      = ($published['published'] > 0) ? XoopstubeUtility::xtubeGetTimestamp(formatTimestamp($published['published'],
2957
                                                                                                            $GLOBALS['xoopsModuleConfig']['dateformatadmin'])) : 'Not Published';
2958
        $expires      = $published['expired'] ? XoopstubeUtility::xtubeGetTimestamp(formatTimestamp($published['expired'],
2959
                                                                                                    $GLOBALS['xoopsModuleConfig']['dateformatadmin'])) : _AM_XOOPSTUBE_MINDEX_NOTSET;
2960
2961
        if ((($published['expired'] && $published['expired'] > time()) || $published['expired'] === 0)
2962
            && ($published['published'] && $published['published'] < time())
2963
            && $published['offline'] === 0
2964
        ) {
2965
            $published_status = $xtubeImageArray['online'];
2966 View Code Duplication
        } elseif (($published['expired'] && $published['expired'] < time()) && $published['offline'] === 0) {
0 ignored issues
show
This code seems to be duplicated across 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...
2967
            $published_status = $xtubeImageArray['expired'];
2968
        } else {
2969
            $published_status = ($published['published'] === 0) ? '<a href="newvideos.php">' . $xtubeImageArray['offline'] . '</a>' : $xtubeImageArray['offline'];
2970
        }
2971
2972 View Code Duplication
        if ($published['vidsource'] === 200) {
0 ignored issues
show
This code seems to be duplicated across 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...
2973
            $icon = '<a href="main.php?op=edit&amp;lid=' . $lid . '" title="' . _AM_XOOPSTUBE_ICO_EDIT . '">' . $xtubeImageArray['editimg'] . '</a>&nbsp;';
2974
        } else {
2975
            $icon = '<a href="main.php?op=edit&amp;lid=' . $lid . '" title="' . _AM_XOOPSTUBE_ICO_EDIT . '">' . $xtubeImageArray['editimg'] . '</a>&nbsp;';
2976
        }
2977
        $icon .= '<a href="main.php?op=delete&amp;lid=' . $lid . '" title="' . _AM_XOOPSTUBE_ICO_DELETE . '">' . $xtubeImageArray['deleteimg'] . '</a>&nbsp;';
2978
        $icon .= '<a href="altcat.php?op=main&amp;cid='
2979
                 . $cid
2980
                 . '&amp;lid='
2981
                 . $lid
2982
                 . '&amp;title='
2983
                 . $published['title']
2984
                 . '" title="'
2985
                 . _AM_XOOPSTUBE_ALTCAT_CREATEF
2986
                 . '">'
2987
                 . $xtubeImageArray['altcat']
2988
                 . '</a>';
2989
2990
        echo '
2991
        <tr style="text-align: center; font-size: smaller;">
2992
        <td class="head">' . $lid . '</span></td>
2993
        <td class="even" style="text-align: left;">' . $title . '</td>
2994
        <td class="even">' . $returnsource . '</td>
2995
        <td class="even">' . $cattitle . '</td>
2996
        <td class="even">' . $submitter . '</td>
2997
        <td class="even">' . $publish . '</td>
2998
        <td class="even">' . $expires . '</td>
2999
        <td class="even" style="width: 4%;">' . $published_status . '</td>
3000
        <td class="even" style="text-align: center; width: 6%; white-space: nowrap;">' . $icon . '</td>
3001
        </tr>';
3002
        unset($published);
3003
    }
3004
3005
    /**
3006
     * @param        $pubrowamount
3007
     * @param        $start
3008
     * @param string $art
3009
     * @param string $_this
3010
     * @param        $align
3011
     *
3012
     * @return bool|null
3013
     */
3014 View Code Duplication
    public static function xtubeSetPageNavigationCategoryList(
3015
        $pubrowamount,
3016
        $start,
3017
        $art = 'art',
3018
        $_this = '',
3019
        $align
3020
    ) {
3021
        if ($pubrowamount < $GLOBALS['xoopsModuleConfig']['admin_perpage']) {
3022
            return false;
3023
        }
3024
        // Display Page Nav if published is > total display pages amount.
3025
        require_once XOOPS_ROOT_PATH . '/class/pagenav.php';
3026
        $pagenav = new XoopsPageNav($pubrowamount, $GLOBALS['xoopsModuleConfig']['admin_perpage'], $start, 'st' . $art, $_this);
3027
        echo '<div style="text-align: ' . $align . '; padding: 8px;">' . $pagenav->renderNav() . '</div>';
3028
3029
        return null;
3030
    }
3031
3032
    /**
3033
     *
3034
     */
3035
    public static function xtubeRenderCategoryListFooter()
3036
    {
3037
        echo '<tr style="text-align: center;">
3038
            <td class="head" colspan="7">' . _AM_XOOPSTUBE_MINDEX_NOVIDEOSFOUND . '</td>
3039
          </tr>';
3040
    }
3041
3042
    /**
3043
     * @param $heading
3044
     */
3045 View Code Duplication
    public static function xtubeRenderVideoListHeader($heading)
3046
    {
3047
        echo '
3048
        <h4 style="font-weight: bold; color: #0A3760;">' . $heading . '</h4>
3049
        <table width="100%" cellspacing="1" class="outer" summary>
3050
        <tr>
3051
            <th style="text-align: center; font-size: smaller;">' . _AM_XOOPSTUBE_MINDEX_ID . '</th>
3052
            <th style=" font-size: smaller;"><b>' . _AM_XOOPSTUBE_MINDEX_TITLE . '</th>
3053
            <th style="text-align: center; font-size: smaller;">' . _AM_XOOPSTUBE_VIDSOURCE2 . '</th>
3054
            <th style="text-align: center; font-size: smaller;">' . _AM_XOOPSTUBE_CATTITLE . '</th>
3055
            <th style="text-align: center; font-size: smaller;">' . _AM_XOOPSTUBE_MINDEX_POSTER . '</th>
3056
            <th style="text-align: center; font-size: smaller;">' . _AM_XOOPSTUBE_MINDEX_PUBLISH . '</th>
3057
            <th style="text-align: center; font-size: smaller;">' . _AM_XOOPSTUBE_MINDEX_EXPIRE . '</th>
3058
            <th style="text-align: center; font-size: smaller;">' . _AM_XOOPSTUBE_MINDEX_ONLINE . '</th>
3059
            <th style="text-align: center; font-size: smaller;">' . _AM_XOOPSTUBE_MINDEX_ACTION . '</th>
3060
        </tr>
3061
        ';
3062
    }
3063
3064
    /**
3065
     * @param $published
3066
     */
3067
    public static function xtubeRenderVideoListBody($published)
3068
    {
3069
        global $xtubemyts, $xtubeImageArray, $pathIcon16;
3070
3071
        $lid = $published['lid'];
3072
        $cid = $published['cid'];
3073
3074
        $title        = '<a href="../singlevideo.php?cid=' . $published['cid'] . '&amp;lid=' . $published['lid'] . '">' . $xtubemyts->htmlSpecialCharsStrip(trim($published['title'])) . '</a>';
3075
        $maintitle    = urlencode($xtubemyts->htmlSpecialChars(trim($published['title'])));
3076
        $cattitle     = '<a href="../viewcat.php?cid=' . $published['cid'] . '">' . XoopstubeUtility::xtubeGetCategoryTitle($published['cid']) . '</a>';
3077
        $submitter    = XoopstubeUtility::xtubeGetLinkedUserNameFromId($published['submitter']);
3078
        $returnsource = xtubeReturnSource($published['vidsource']);
3079
        $submitted    = XoopstubeUtility::xtubeGetTimestamp(formatTimestamp($published['date'], $GLOBALS['xoopsModuleConfig']['dateformatadmin']));
3080
        $publish      = ($published['published'] > 0) ? XoopstubeUtility::xtubeGetTimestamp(formatTimestamp($published['published'],
3081
                                                                                                            $GLOBALS['xoopsModuleConfig']['dateformatadmin'])) : 'Not Published';
3082
        $expires      = $published['expired'] ? XoopstubeUtility::xtubeGetTimestamp(formatTimestamp($published['expired'],
3083
                                                                                                    $GLOBALS['xoopsModuleConfig']['dateformatadmin'])) : _AM_XOOPSTUBE_MINDEX_NOTSET;
3084
3085
        if ((($published['expired'] && $published['expired'] > time()) || $published['expired'] === 0)
3086
            && ($published['published'] && $published['published'] < time())
3087
            && $published['offline'] === 0
3088
        ) {
3089
            //        $published_status = $xtubeImageArray['online'];
3090
            $published_status = '<a href="main.php?op=toggle&amp;lid=' . $lid . '&amp;offline=' . $published['offline'] . '"><img src="' . $pathIcon16 . '/1.png' . '" /></a>';
3091 View Code Duplication
        } elseif (($published['expired'] && $published['expired'] < time()) && $published['offline'] === 0) {
3092
            $published_status = $xtubeImageArray['expired'];
3093
        } else {
3094
            $published_status = ($published['published'] === 0) ? '<a href="newvideos.php">' . $xtubeImageArray['offline'] . '</a>' : '<a href="main.php?op=toggle&amp;lid='
3095
                                                                                                                                      . $lid
3096
                                                                                                                                      . '&amp;offline='
3097
                                                                                                                                      . $published['offline']
3098
                                                                                                                                      . '"><img src="'
3099
                                                                                                                                      . $pathIcon16
3100
                                                                                                                                      . '/0.png'
3101
                                                                                                                                      . '" /></a>';
3102
        }
3103
3104 View Code Duplication
        if ($published['vidsource'] === 200) {
0 ignored issues
show
This code seems to be duplicated across 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...
3105
            $icon = '<a href="main.php?op=edit&amp;lid=' . $lid . '" title="' . _AM_XOOPSTUBE_ICO_EDIT . '">' . $xtubeImageArray['editimg'] . '</a>&nbsp;';
3106
        } else {
3107
            $icon = '<a href="main.php?op=edit&amp;lid=' . $lid . '" title="' . _AM_XOOPSTUBE_ICO_EDIT . '">' . $xtubeImageArray['editimg'] . '</a>&nbsp;';
3108
        }
3109
        $icon .= '<a href="main.php?op=delete&amp;lid=' . $lid . '" title="' . _AM_XOOPSTUBE_ICO_DELETE . '">' . $xtubeImageArray['deleteimg'] . '</a>&nbsp;';
3110
        $icon .= '<a href="altcat.php?op=main&amp;cid='
3111
                 . $cid
3112
                 . '&amp;lid='
3113
                 . $lid
3114
                 . '&amp;title='
3115
                 . $published['title']
3116
                 . '" title="'
3117
                 . _AM_XOOPSTUBE_ALTCAT_CREATEF
3118
                 . '">'
3119
                 . $xtubeImageArray['altcat']
3120
                 . '</a>';
3121
3122
        echo '
3123
        <tr style="text-align: center; font-size: smaller;">
3124
        <td class="head">' . $lid . '</span></td>
3125
        <td class="even" style="text-align: left;">' . $title . '</td>
3126
        <td class="even">' . $returnsource . '</td>
3127
        <td class="even">' . $cattitle . '</td>
3128
        <td class="even">' . $submitter . '</td>
3129
        <td class="even">' . $publish . '</td>
3130
        <td class="even">' . $expires . '</td>
3131
        <td class="even" style="width: 4%;">' . $published_status . '</td>
3132
        <td class="even" style="text-align: center; width: 6%; white-space: nowrap;">' . $icon . '</td>
3133
        </tr>';
3134
        unset($published);
3135
    }
3136
3137
    /**
3138
     * @param $catt
3139
     *
3140
     * @return mixed
3141
     */
3142
    public static function xtubeGetCategoryTitle($catt)
3143
    {
3144
        $sql    = 'SELECT title FROM ' . $GLOBALS['xoopsDB']->prefix('xoopstube_cat') . ' WHERE cid=' . $catt;
3145
        $result = $GLOBALS['xoopsDB']->query($sql);
3146
        $result = $GLOBALS['xoopsDB']->fetchArray($result);
3147
3148
        return $result['title'];
3149
    }
3150
3151
    /**
3152
     *
3153
     */
3154
    public static function xtubeRenderVideoListFooter()
3155
    {
3156
        echo '<tr style="text-align: center;">
3157
            <td class="head" colspan="7">' . _AM_XOOPSTUBE_MINDEX_NOVIDEOSFOUND . '</td>
3158
          </tr>';
3159
    }
3160
3161
    /**
3162
     * @param        $pubrowamount
3163
     * @param        $start
3164
     * @param string $art
3165
     * @param string $_this
3166
     * @param        $align
3167
     *
3168
     * @return bool|null
3169
     */
3170 View Code Duplication
    public static function xtubeSetPageNavigationVideoList($pubrowamount, $start, $art = 'art', $_this = '', $align)
3171
    {
3172
        if ($pubrowamount < $GLOBALS['xoopsModuleConfig']['admin_perpage']) {
3173
            return false;
3174
        }
3175
        // Display Page Nav if published is > total display pages amount.
3176
        require_once XOOPS_ROOT_PATH . '/class/pagenav.php';
3177
        $pagenav = new XoopsPageNav($pubrowamount, $GLOBALS['xoopsModuleConfig']['admin_perpage'], $start, 'st' . $art, $_this);
3178
        echo '<div style="text-align: ' . $align . '; padding: 8px;">' . $pagenav->renderNav() . '</div>';
3179
3180
        return null;
3181
    }
3182
3183
    /**
3184
     * @param $document
3185
     *
3186
     * @return mixed
3187
     */
3188
    public static function xtubeConvertHtml2Text($document)
3189
    {
3190
        // PHP Manual:: function preg_replace
3191
        // $document should contain an HTML document.
3192
        // This will remove HTML tags, javascript sections
3193
        // and white space. It will also convert some
3194
        // common HTML entities to their text equivalent.
3195
        // Credits : newbb2
3196
        $search = array(
3197
            "'<script[^>]*?>.*?</script>'si", // Strip out javascript
3198
            "'<img.*?/>'si", // Strip out img tags
3199
            "'<[\/\!]*?[^<>]*?>'si", // Strip out HTML tags
3200
            "'([\r\n])[\s]+'", // Strip out white space
3201
            "'&(quot|#34);'i", // Replace HTML entities
3202
            "'&(amp|#38);'i",
3203
            "'&(lt|#60);'i",
3204
            "'&(gt|#62);'i",
3205
            "'&(nbsp|#160);'i",
3206
            "'&(iexcl|#161);'i",
3207
            "'&(cent|#162);'i",
3208
            "'&(pound|#163);'i",
3209
            "'&(copy|#169);'i"
3210
        ); // evaluate as php
3211
3212
        $replace = array(
3213
            '',
3214
            '',
3215
            '',
3216
            "\\1",
3217
            "\"",
3218
            '&',
3219
            '<',
3220
            '>',
3221
            ' ',
3222
            chr(161),
3223
            chr(162),
3224
            chr(163),
3225
            chr(169),
3226
        );
3227
3228
        $text = preg_replace($search, $replace, $document);
3229
3230
        preg_replace_callback('/&#(\d+);/', function ($matches) {
3231
            return chr($matches[1]);
3232
        }, $document);
3233
3234
        return $text;
3235
    }
3236
3237
    // Check if Tag module is installed
3238
3239
    /**
3240
     * @return bool
3241
     */
3242
    public static function xtubeIsModuleTagInstalled()
3243
    {
3244
        static $isModuleTagInstalled;
3245
        if (!isset($isModuleTagInstalled)) {
3246
            /** @var XoopsModuleHandler $moduleHandler */
3247
            $moduleHandler = xoops_getHandler('module');
3248
            $tag_mod       = $moduleHandler->getByDirname('tag');
3249
            if (!$tag_mod) {
3250
                $tag_mod = false;
0 ignored issues
show
$tag_mod 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...
3251
            } else {
3252
                $isModuleTagInstalled = $tag_mod->getVar('isactive') === 1;
3253
            }
3254
        }
3255
3256
        return $isModuleTagInstalled;
3257
    }
3258
3259
    // Add item_tag to Tag-module
3260
3261
    /**
3262
     * @param $lid
3263
     * @param $item_tag
3264
     */
3265
    public static function xtubeUpdateTag($lid, $item_tag)
3266
    {
3267
        global $xoopsModule;
3268
        if (XoopstubeUtility::xtubeIsModuleTagInstalled()) {
3269
            require_once XOOPS_ROOT_PATH . '/modules/tag/include/formtag.php';
3270
            $tagHandler = xoops_getModuleHandler('tag', 'tag');
3271
            $tagHandler->updateByItem($item_tag, $lid, $xoopsModule->getVar('dirname'), 0);
3272
        }
3273
    }
3274
3275
    /**
3276
     * @param $lid
3277
     */
3278
    public static function xtubeUpdateCounter($lid)
3279
    {
3280
        $sql    = 'UPDATE ' . $GLOBALS['xoopsDB']->prefix('xoopstube_videos') . ' SET hits=hits+1 WHERE lid=' . (int)$lid;
3281
        $result = $GLOBALS['xoopsDB']->queryF($sql);
3282
    }
3283
3284
    /**
3285
     * @param $banner_id
3286
     *
3287
     * @return null|string
3288
     */
3289 View Code Duplication
    public static function xtubeGetBannerFromBannerId($banner_id)
3290
    {
3291
        ###### Hack by www.stefanosilvestrini.com ######
3292
        $db      = XoopsDatabaseFactory::getDatabaseConnection();
3293
        $bresult = $db->query('SELECT COUNT(*) FROM ' . $db->prefix('banner') . ' WHERE bid=' . $banner_id);
3294
        list($numrows) = $db->fetchRow($bresult);
3295
        if ($numrows > 1) {
3296
            --$numrows;
3297
            mt_srand((double)microtime() * 1000000);
3298
            $bannum = mt_rand(0, $numrows);
3299
        } else {
3300
            $bannum = 0;
3301
        }
3302
        if ($numrows > 0) {
3303
            $bresult = $db->query('SELECT * FROM ' . $db->prefix('banner') . ' WHERE bid=' . $banner_id, 1, $bannum);
3304
            list($bid, $cid, $imptotal, $impmade, $clicks, $imageurl, $clickurl, $date, $htmlbanner, $htmlcode) = $db->fetchRow($bresult);
3305
            if ($GLOBALS['xoopsConfig']['my_ip'] === xoops_getenv('REMOTE_ADDR')) {
3306
                // EMPTY
3307
            } else {
3308
                $db->queryF(sprintf('UPDATE %s SET impmade = impmade+1 WHERE bid = %u', $db->prefix('banner'), $bid));
3309
            }
3310
            /* Check if this impression is the last one and print the banner */
3311
            if ($imptotal === $impmade) {
3312
                $newid = $db->genId($db->prefix('bannerfinish') . '_bid_seq');
3313
                $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,
3314
                                 $date, time());
3315
                $db->queryF($sql);
3316
                $db->queryF(sprintf('DELETE FROM %s WHERE bid = %u', $db->prefix('banner'), $bid));
3317
            }
3318
            if ($htmlbanner) {
3319
                $bannerobject = $htmlcode;
3320
            } else {
3321
                $bannerobject = '<div align="center"><a href="' . XOOPS_URL . '/banners.php?op=click&bid=' . $bid . '" target="_blank">';
3322
                if (false !== stripos($imageurl, '.swf')) {
3323
                    $bannerobject = $bannerobject
3324
                                    . '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0" width="468" height="60">'
3325
                                    . '<param name="movie" value="'
3326
                                    . $imageurl
3327
                                    . '"></param>'
3328
                                    . '<param name="quality" value="high"></param>'
3329
                                    . '<embed src="'
3330
                                    . $imageurl
3331
                                    . '" quality="high" pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash" type="application/x-shockwave-flash" width="468" height="60">'
3332
                                    . '</embed>'
3333
                                    . '</object>';
3334
                } else {
3335
                    $bannerobject = $bannerobject . '<img src="' . $imageurl . '" alt="" />';
3336
                }
3337
                $bannerobject .= '</a></div>';
3338
            }
3339
3340
            return $bannerobject;
3341
        }
3342
3343
        return null;
3344
    }
3345
3346
    /**
3347
     * @param $client_id
3348
     *
3349
     * @return null|string
3350
     */
3351 View Code Duplication
    public static function xtubeGetBannerFromClientId($client_id)
3352
    {
3353
        ###### Hack by www.stefanosilvestrini.com ######
3354
        $db      = XoopsDatabaseFactory::getDatabaseConnection();
3355
        $bresult = $db->query('SELECT COUNT(*) FROM ' . $db->prefix('banner') . ' WHERE cid=' . $client_id);
3356
        list($numrows) = $db->fetchRow($bresult);
3357
        if ($numrows > 1) {
3358
            --$numrows;
3359
            mt_srand((double)microtime() * 1000000);
3360
            $bannum = mt_rand(0, $numrows);
3361
        } else {
3362
            $bannum = 0;
3363
        }
3364
        if ($numrows > 0) {
3365
            $bresult = $db->query('SELECT * FROM ' . $db->prefix('banner') . ' WHERE cid=' . $client_id . ' ORDER BY rand()', 1, $bannum);
3366
            list($bid, $cid, $imptotal, $impmade, $clicks, $imageurl, $clickurl, $date, $htmlbanner, $htmlcode) = $db->fetchRow($bresult);
3367
            if ($GLOBALS['xoopsConfig']['my_ip'] === xoops_getenv('REMOTE_ADDR')) {
3368
                // EMPTY
3369
            } else {
3370
                $db->queryF(sprintf('UPDATE %s SET impmade = impmade+1 WHERE bid = %u', $db->prefix('banner'), $bid));
3371
            }
3372
            /* Check if this impression is the last one and print the banner */
3373
            if ($imptotal === $impmade) {
3374
                $newid = $db->genId($db->prefix('bannerfinish') . '_bid_seq');
3375
                $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,
3376
                                 $date, time());
3377
                $db->queryF($sql);
3378
                $db->queryF(sprintf('DELETE FROM %s WHERE bid = %u', $db->prefix('banner'), $bid));
3379
            }
3380
            if ($htmlbanner) {
3381
                $bannerobject = $htmlcode;
3382
            } else {
3383
                $bannerobject = '<div align="center"><a href="' . XOOPS_URL . '/banners.php?op=click&bid=' . $bid . '" target="_blank">';
3384
                if (false !== stripos($imageurl, '.swf')) {
3385
                    $bannerobject = $bannerobject
3386
                                    . '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0" width="468" height="60">'
3387
                                    . '<param name="movie" value="'
3388
                                    . $imageurl
3389
                                    . '"></param>'
3390
                                    . '<param name="quality" value="high"></param>'
3391
                                    . '<embed src="'
3392
                                    . $imageurl
3393
                                    . '" quality="high" pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash" type="application/x-shockwave-flash" width="468" height="60">'
3394
                                    . '</embed>'
3395
                                    . '</object>';
3396
                } else {
3397
                    $bannerobject = $bannerobject . '<img src="' . $imageurl . '" alt="" />';
3398
                }
3399
                $bannerobject .= '</a></div>';
3400
            }
3401
3402
            return $bannerobject;
3403
        }
3404
3405
        return null;
3406
    }
3407
3408
    /**
3409
     *
3410
     */
3411
    public static function xtubeSetNoIndexNoFollow()
3412
    {
3413
        global $xoopsTpl;
3414
        if (is_object($GLOBALS['xoTheme'])) {
3415
            $GLOBALS['xoTheme']->addMeta('meta', 'robots', 'noindex,nofollow');
3416
        } else {
3417
            $xoopsTpl->assign('xoops_meta_robots', 'noindex,nofollow');
3418
        }
3419
    }
3420
3421
    /**
3422
     * @param $userid
3423
     *
3424
     * @return string
3425
     */
3426
    public static function xtubeGetLinkedUserNameFromId($userid)
3427
    {
3428
        $userid = (int)$userid;
3429
        if ($userid > 0) {
3430
            $memberHandler = xoops_getHandler('member');
3431
            $user          = $memberHandler->getUser($userid);
3432
            if (is_object($user)) {
3433
                $linkeduser = '<a href="' . XOOPS_URL . '/userinfo.php?uid=' . $userid . '">' . $user->getVar('uname') . '</a>';
3434
3435
                return $linkeduser;
3436
            }
3437
        }
3438
3439
        return $GLOBALS['xoopsConfig']['anonymous'];
3440
    }
3441
3442
    /**
3443
     * @param $time
3444
     *
3445
     * @return string
3446
     */
3447
    public static function xtubeGetTimestamp($time)
3448
    {
3449
        $moduleDirName = basename(dirname(__DIR__));
3450
        xoops_loadLanguage('local', $moduleDirName);
3451
3452
        $trans     = array(
3453
            'Monday'    => _XOOPSTUBE_MONDAY,
3454
            'Tuesday'   => _XOOPSTUBE_TUESDAY,
3455
            'Wednesday' => _XOOPSTUBE_WEDNESDAY,
3456
            'Thursday'  => _XOOPSTUBE_THURSDAY,
3457
            'Friday'    => _XOOPSTUBE_FRIDAY,
3458
            'Saturday'  => _XOOPSTUBE_SATURDAY,
3459
            'Sunday'    => _XOOPSTUBE_SUNDAY,
3460
            'Mon'       => _XOOPSTUBE_MON,
3461
            'Tue'       => _XOOPSTUBE_TUE,
3462
            'Wed'       => _XOOPSTUBE_WED,
3463
            'Thu'       => _XOOPSTUBE_THU,
3464
            'Fri'       => _XOOPSTUBE_FRI,
3465
            'Sat'       => _XOOPSTUBE_SAT,
3466
            'Sun'       => _XOOPSTUBE_SUN,
3467
            'January'   => _XOOPSTUBE_JANUARI,
3468
            'February'  => _XOOPSTUBE_FEBRUARI,
3469
            'March'     => _XOOPSTUBE_MARCH,
3470
            'April'     => _XOOPSTUBE_APRIL,
3471
            'May'       => _XOOPSTUBE_MAY,
3472
            'June'      => _XOOPSTUBE_JUNE,
3473
            'July'      => _XOOPSTUBE_JULY,
3474
            'August'    => _XOOPSTUBE_AUGUST,
3475
            'September' => _XOOPSTUBE_SEPTEMBER,
3476
            'October'   => _XOOPSTUBE_OCTOBER,
3477
            'November'  => _XOOPSTUBE_NOVEMBER,
3478
            'December'  => _XOOPSTUBE_DECEMBER,
3479
            'Jan'       => _XOOPSTUBE_JAN,
3480
            'Feb'       => _XOOPSTUBE_FEB,
3481
            'Mar'       => _XOOPSTUBE_MAR,
3482
            'Apr'       => _XOOPSTUBE_APR,
3483
            //        'May'       => _XOOPSTUBE_MAY2,
3484
            'Jun'       => _XOOPSTUBE_JUN,
3485
            'Jul'       => _XOOPSTUBE_JUL,
3486
            'Aug'       => _XOOPSTUBE_AUG,
3487
            'Sep'       => _XOOPSTUBE_SEP,
3488
            'Oct'       => _XOOPSTUBE_OCT,
3489
            'Nov'       => _XOOPSTUBE_NOV,
3490
            'Dec'       => _XOOPSTUBE_DEC
3491
        );
3492
        $timestamp = strtr($time, $trans);
3493
3494
        return $timestamp;
3495
    }
3496
3497
    /**
3498
     * Do some basic file checks and stuff.
3499
     * Author: Andrew Mills  Email:  [email protected]
3500
     * from amReviews module
3501
     */
3502
    public static function xtubeFileChecks()
3503
    {
3504
        echo '<fieldset>';
3505
        echo "<legend style=\"color: #990000; font-weight: bold;\">" . _AM_XOOPSTUBE_FILECHECKS . '</legend>';
3506
3507
        $dirPhotos      = XOOPS_ROOT_PATH . '/' . $GLOBALS['xoopsModuleConfig']['catimage'];
3508
        $dirVideos      = XOOPS_ROOT_PATH . '/' . $GLOBALS['xoopsModuleConfig']['videodir'];
3509
        $dirScreenshots = XOOPS_ROOT_PATH . '/' . $GLOBALS['xoopsModuleConfig']['videoimgdir'];
3510
3511 View Code Duplication
        if (file_exists($dirPhotos)) {
3512
            if (!is_writable($dirPhotos)) {
3513
                echo "<span style=\" color: red; font-weight: bold;\">Warning:</span> " . _AM_XOOPSTUBE_UNABLE_TO_WRITE . $dirPhotos . '<br>';
3514
            } else {
3515
                echo "<span style=\" color: green; font-weight: bold;\">OK:</span> " . $dirPhotos . '<br>';
3516
            }
3517
        } else {
3518
            echo "<span style=\" color: red; font-weight: bold;\">" . _AM_XOOPSTUBE_WARNING . '</span> ' . $dirPhotos . " <span style=\" color: red; \">" . _AM_XOOPSTUBE_NOT_EXISTS . '</span> <br>';
3519
        }
3520
        // photothumbdir
3521 View Code Duplication
        if (file_exists($dirVideos)) {
3522
            if (!is_writable($dirVideos)) {
3523
                echo "<span style=\" color: red; font-weight: bold;\">" . _AM_XOOPSTUBE_WARNING . '</span> ' . _AM_XOOPSTUBE_UNABLE_TO_WRITE . $dirVideos . '<br>';
3524
            } else {
3525
                echo "<span style=\" color: green; font-weight: bold;\">OK:</span> " . $dirVideos . '<br>';
3526
            }
3527
        } else {
3528
            echo "<span style=\" color: red; font-weight: bold;\">" . _AM_XOOPSTUBE_WARNING . '</span> ' . $dirVideos . " <span style=\" color: red; \">" . _AM_XOOPSTUBE_NOT_EXISTS . '</span> <br>';
3529
        }
3530
        // photohighdir
3531 View Code Duplication
        if (file_exists($dirScreenshots)) {
3532
            if (!is_writable($dirScreenshots)) {
3533
                echo "<span style=\" color: red; font-weight: bold;\">Warning:</span> " . _AM_XOOPSTUBE_UNABLE_TO_WRITE . $dirScreenshots . '<br>';
3534
            } else {
3535
                echo "<span style=\" color: green; font-weight: bold;\">OK:</span> " . $dirScreenshots . '<br>';
3536
            }
3537
        } else {
3538
            echo "<span style=\" color: red; font-weight: bold;\">"
3539
                 . _AM_XOOPSTUBE_WARNING
3540
                 . '</span> '
3541
                 . $dirScreenshots
3542
                 . " <span style=\" color: red; \">"
3543
                 . _AM_XOOPSTUBE_NOT_EXISTS
3544
                 . '</span> <br>';
3545
        }
3546
3547
        /**
3548
         * Some info.
3549
         */
3550
        $uploads = ini_get('file_uploads') ? _AM_XOOPSTUBE_UPLOAD_ON : _AM_XOOPSTUBE_UPLOAD_OFF;
3551
        echo '<br>';
3552
        echo '<ul>';
3553
        echo '<li>' . _AM_XOOPSTUBE_UPLOADMAX . '<b>' . ini_get('upload_max_filesize') . '</b></li>';
3554
        echo '<li>' . _AM_XOOPSTUBE_POSTMAX . '<b>' . ini_get('post_max_size') . '</b></li>';
3555
        echo '<li>' . _AM_XOOPSTUBE_UPLOADS . '<b>' . $uploads . '</b></li>';
3556
3557
        $gdinfo = gd_info();
3558
        if (function_exists('gd_info')) {
3559
            echo '<li>' . _AM_XOOPSTUBE_GDIMGSPPRT . '<b>' . _AM_XOOPSTUBE_GDIMGON . '</b></li>';
3560
            echo '<li>' . _AM_XOOPSTUBE_GDIMGVRSN . '<b>' . $gdinfo['GD Version'] . '</b></li>';
3561
        } else {
3562
            echo '<li>' . _AM_XOOPSTUBE_GDIMGSPPRT . '<b>' . _AM_XOOPSTUBE_GDIMGOFF . '</b></li>';
3563
        }
3564
        echo '</ul>';
3565
3566
        //$inithingy = ini_get_all();
3567
        //print_r($inithingy);
3568
3569
        echo '</fieldset>';
3570
    }
3571
3572
    /**
3573
     * @param      $path
3574
     * @param int  $mode
3575
     * @param      $fileSource
3576
     * @param null $fileTarget
3577
     */
3578
    public static function xtubeCreateDirectory($path, $mode = 0777, $fileSource, $fileTarget = null)
3579
    {
3580
        if (!is_dir($path)) {
3581
            mkdir($path, $mode);
3582
            file_put_contents($path . '/index.html', '<script>history.go(-1);</script>');
3583
            if (!empty($fileSource) && !empty($fileTarget)) {
3584
                @copy($fileSource, $fileTarget);
3585
            }
3586
        }
3587
        chmod($path, $mode);
3588
    }
3589
3590
    /**
3591
     * @return string
3592
     */
3593
    public static function xtubeGetLetters()
3594
    {
3595
        global $xoopsModule;
3596
3597
        $letterchoice          = '<div>' . _MD_XOOPSTUBE_BROWSETOTOPIC . '</div>';
3598
        $alphabet              = getXtubeAlphabet();
3599
        $num                   = count($alphabet) - 1;
3600
        $counter               = 0;
3601
        $distinctDbLetters_arr = array();
3602
        $sql                   = 'SELECT DISTINCT (UPPER(LEFT(title, 1))) AS letter FROM ' . $GLOBALS['xoopsDB']->prefix('xoopstube_videos WHERE expired = 0 AND offline = 0');
3603
        if ($result = $GLOBALS['xoopsDB']->query($sql)) {
3604
            while (false !== ($row = $GLOBALS['xoopsDB']->fetchArray($result))) {
3605
                $distinctDbLetters_arr[] = $row['letter'];
3606
            }
3607
        }
3608
        unset($sql);
3609
3610
//        while (false !== (list(, $ltr) = each($alphabet))) {
3611
        foreach ($alphabet as $key => $ltr) {
3612
            if (in_array($ltr, $distinctDbLetters_arr)) {
3613
                $letterchoice .= '<a class="xoopstube_letters xoopstube_letters_green" href="';
3614
            } else {
3615
                $letterchoice .= '<a class="xoopstube_letters" href="';
3616
            }
3617
            $letterchoice .= XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname') . '/viewcat.php?list=' . $ltr . '">' . $ltr . '</a>';
3618
            if ($counter === round($num / 2)) {
3619
                $letterchoice .= '<br>';
3620
            } elseif ($counter !== $num) {
3621
                $letterchoice .= '&nbsp;';
3622
            }
3623
            ++$counter;
3624
        }
3625
3626
        return $letterchoice;
3627
    }
3628
3629
    /**
3630
     * @return mixed|string
3631
     */
3632
    public static function xtubeLettersChoice()
3633
    {
3634
        global $xoopsModule;
3635
3636
        $moduleDirName = $xoopsModule->getVar('dirname');
3637
        require_once XOOPS_ROOT_PATH . "/modules/$moduleDirName/class/$moduleDirName.php";
3638
        $xoopstube = XoopstubeXoopstube::getInstance();
3639
3640
        $a             = $xoopstube->getHandler('xoopstube');
3641
        $b             = $a->getActiveCriteria();
3642
        $moduleDirName = basename(dirname(__DIR__));
3643
3644
        $criteria = $xoopstube->getHandler('xoopstube')->getActiveCriteria();
3645
        $criteria->setGroupby('UPPER(LEFT(title,1))');
3646
        $countsByLetters = $xoopstube->getHandler($moduleDirName)->getCounts($criteria);
3647
        // Fill alphabet array
3648
        $alphabet       = getXtubeAlphabet();
3649
        $alphabet_array = array();
3650
        foreach ($alphabet as $letter) {
3651
            $letter_array = array();
3652
            if (isset($countsByLetters[$letter])) {
3653
                $letter_array['letter'] = $letter;
3654
                $letter_array['count']  = $countsByLetters[$letter];
3655
                $letter_array['url']    = '' . XOOPS_URL . "/modules/$moduleDirName/viewcat.php?list={$letter}";
3656
            } else {
3657
                $letter_array['letter'] = $letter;
3658
                $letter_array['count']  = 0;
3659
                $letter_array['url']    = '';
3660
            }
3661
            $alphabet_array[$letter] = $letter_array;
3662
            unset($letter_array);
3663
        }
3664
        // Render output
3665
        if (!isset($GLOBALS['xoTheme']) || !is_object($GLOBALS['xoTheme'])) {
3666
            require_once $GLOBALS['xoops']->path('class/theme.php');
3667
            $GLOBALS['xoTheme'] = new xos_opal_Theme();
3668
        }
3669
        require_once $GLOBALS['xoops']->path('class/template.php');
3670
        $letterschoiceTpl          = new XoopsTpl();
3671
        $letterschoiceTpl->caching = false; // Disable cache
3672
        $letterschoiceTpl->assign('alphabet', $alphabet_array);
3673
        $html = $letterschoiceTpl->fetch('db:' . $xoopstube->getModule()->dirname() . '_common_letterschoice.tpl');
3674
        unset($letterschoiceTpl);
3675
3676
        return $html;
3677
    }
3678
3679
    //===============  from WF-Downloads   ======================================
3680
3681
    /**
3682
     * @return bool
3683
     */
3684
    public static function xtubeUserIsAdmin()
3685
    {
3686
        $xoopstube = XoopstubeXoopstube::getInstance();
3687
3688
        static $xtubeIsAdmin;
3689
3690
        if (isset($xtubeIsAdmin)) {
3691
            return $xtubeIsAdmin;
3692
        }
3693
3694
        if (!$GLOBALS['xoopsUser']) {
3695
            $xtubeIsAdmin = false;
3696
        } else {
3697
            $xtubeIsAdmin = $GLOBALS['xoopsUser']->isAdmin($xoopstube->getModule()->getVar('mid'));
3698
        }
3699
3700
        return $xtubeIsAdmin;
3701
    }
3702
}
3703