Completed
Branch master (954431)
by Michael
04:17 queued 01:39
created

XoopstubeUtilities::xtubeCleanRequestVars()   C

Complexity

Conditions 11
Paths 9

Size

Total Lines 42
Code Lines 27

Duplication

Lines 16
Ratio 38.1 %

Importance

Changes 0
Metric Value
cc 11
eloc 27
nc 9
nop 5
dl 16
loc 42
rs 5.2653
c 0
b 0
f 0

How to fix   Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
/*
3
 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');
0 ignored issues
show
Unused Code Comprehensibility introduced by
70% 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...
31
32
use WideImage\WideImage;
33
34
/**
35
 * Class XoopstubeUtilities
36
 */
37
class XoopstubeUtilities
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
38
{
39
40
    const MODULE_NAME = 'xoopstube';
41
42
    /**
43
     * Access the only instance of this class
44
     *
45
     * @return XoopsObject
0 ignored issues
show
Documentation introduced by
Should the return type not be XoopstubeUtilities?

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...
46
     *
47
     * @static
48
     * @staticvar   object
49
     */
50
    public static function getInstance()
51
    {
52
        static $instance;
53
        if (null === $instance) {
54
            $instance = new static();
55
        }
56
57
        return $instance;
58
    }
59
60
    /**
61
     * Returns a module's option (with cache)
62
     *
63
     * @param string  $option    module option's name
64
     * @param boolean $withCache Do we have to use some cache ?
65
     *
66
     * @return mixed option's value
67
     */
68
    public static function getModuleOption($option, $withCache = true)
69
    {
70
        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...
71
        $repmodule = self::MODULE_NAME;
72
        static $options = array();
73
        if (is_array($options) && array_key_exists($option, $options) && $withCache) {
74
            return $options[$option];
75
        }
76
77
        $retval = false;
78
        if (isset($xoopsModuleConfig) && (is_object($xoopsModule) && $xoopsModule->getVar('dirname') == $repmodule && $xoopsModule->getVar('isactive'))) {
79
            if (isset($xoopsModuleConfig[$option])) {
80
                $retval = $xoopsModuleConfig[$option];
81
            }
82
        } else {
83
            $moduleHandler  = xoops_getHandler('module');
84
            $module         = $moduleHandler->getByDirname($repmodule);
85
            $config_handler = xoops_getHandler('config');
86
            if ($module) {
87
                $moduleConfig = $config_handler->getConfigsByCat(0, $module->getVar('mid'));
88
                if (isset($moduleConfig[$option])) {
89
                    $retval = $moduleConfig[$option];
90
                }
91
            }
92
        }
93
        $options[$option] = $retval;
94
95
        return $retval;
96
    }
97
98
    /**
99
     * Is Xoops 2.3.x ?
100
     *
101
     * @return boolean
102
     */
103 View Code Duplication
    public static function isX23()
0 ignored issues
show
Duplication introduced by
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...
104
    {
105
        $x23 = false;
106
        $xv  = str_replace('XOOPS ', '', XOOPS_VERSION);
107
        if ((int)substr($xv, 2, 1) >= 3) {
108
            $x23 = true;
109
        }
110
111
        return $x23;
112
    }
113
114
    /**
115
     * Is Xoops 2.0.x ?
116
     *
117
     * @return boolean
118
     */
119 View Code Duplication
    public static function isX20()
0 ignored issues
show
Duplication introduced by
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...
120
    {
121
        $x20 = false;
122
        $xv  = str_replace('XOOPS ', '', XOOPS_VERSION);
123
        if (substr($xv, 2, 1) == '0') {
124
            $x20 = true;
125
        }
126
127
        return $x20;
128
    }
129
130
    /**
131
     * Create (in a link) a javascript confirmation's box
132
     *
133
     * @param string  $message Message to display
134
     * @param boolean $form    Is this a confirmation for a form ?
135
     *
136
     * @return string the javascript code to insert in the link (or in the form)
137
     */
138
    public static function javascriptLinkConfirm($message, $form = false)
139
    {
140
        if (!$form) {
141
            return "onclick=\"javascript:return confirm('" . str_replace("'", ' ', $message) . "')\"";
142
        } else {
143
            return "onSubmit=\"javascript:return confirm('" . str_replace("'", ' ', $message) . "')\"";
144
        }
145
    }
146
147
    /**
148
     * Get current user IP
149
     *
150
     * @return string IP address (format Ipv4)
151
     */
152
    public static function IP()
0 ignored issues
show
Coding Style introduced by
IP uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
153
    {
154
        $proxy_ip = '';
155
        if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
156
            $proxy_ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
157
        } elseif (!empty($_SERVER['HTTP_X_FORWARDED'])) {
158
            $proxy_ip = $_SERVER['HTTP_X_FORWARDED'];
159
        } elseif (!empty($_SERVER['HTTP_FORWARDED_FOR'])) {
160
            $proxy_ip = $_SERVER['HTTP_FORWARDED_FOR'];
161
        } elseif (!empty($_SERVER['HTTP_FORWARDED'])) {
162
            $proxy_ip = $_SERVER['HTTP_FORWARDED'];
163
        } elseif (!empty($_SERVER['HTTP_VIA'])) {
164
            $proxy_ip = $_SERVER['HTTP_VIA'];
165
        } elseif (!empty($_SERVER['HTTP_X_COMING_FROM'])) {
166
            $proxy_ip = $_SERVER['HTTP_X_COMING_FROM'];
167
        } elseif (!empty($_SERVER['HTTP_COMING_FROM'])) {
168
            $proxy_ip = $_SERVER['HTTP_COMING_FROM'];
169
        }
170
        $regs = array();
171
        //if (!empty($proxy_ip) && $is_ip = ereg('^([0-9]{1,3}\.){3,3}[0-9]{1,3}', $proxy_ip, $regs) && count($regs) > 0) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
59% 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...
172
        if (!empty($proxy_ip) && filter_var($proxy_ip, FILTER_VALIDATE_IP) && count($regs) > 0) {
173
            $the_IP = $regs[0];
174
        } else {
175
            $the_IP = $_SERVER['REMOTE_ADDR'];
176
        }
177
178
        return $the_IP;
179
    }
180
181
    /**
182
     * Set the page's title, meta description and meta keywords
183
     * Datas are supposed to be sanitized
184
     *
185
     * @param string $pageTitle       Page's Title
186
     * @param string $metaDescription Page's meta description
187
     * @param string $metaKeywords    Page's meta keywords
188
     *
189
     * @return void
190
     */
191
    public static function setMetas($pageTitle = '', $metaDescription = '', $metaKeywords = '')
192
    {
193
        global $xoTheme, $xoTheme, $xoopsTpl;
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...
194
        $xoopsTpl->assign('xoops_pagetitle', $pageTitle);
195
        if (isset($xoTheme) && is_object($xoTheme)) {
196
            if (!empty($metaKeywords)) {
197
                $xoTheme->addMeta('meta', 'keywords', $metaKeywords);
198
            }
199
            if (!empty($metaDescription)) {
200
                $xoTheme->addMeta('meta', 'description', $metaDescription);
201
            }
202
        } elseif (isset($xoopsTpl) && is_object($xoopsTpl)) { // Compatibility for old Xoops versions
203
            if (!empty($metaKeywords)) {
204
                $xoopsTpl->assign('xoops_meta_keywords', $metaKeywords);
205
            }
206
            if (!empty($metaDescription)) {
207
                $xoopsTpl->assign('xoops_meta_description', $metaDescription);
208
            }
209
        }
210
    }
211
212
    /**
213
     * Send an email from a template to a list of recipients
214
     *
215
     * @param        $tplName
216
     * @param array  $recipients List of recipients
217
     * @param string $subject    Email's subject
218
     * @param array  $variables  Varirables to give to the template
219
     *
220
     * @internal param string $tpl_name Template's name
221
     * @return boolean Result of the send
222
     */
223
    public static function sendEmailFromTpl($tplName, $recipients, $subject, $variables)
224
    {
225
        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...
226
        require_once XOOPS_ROOT_PATH . '/class/xoopsmailer.php';
227
        if (!is_array($recipients)) {
228
            if ('' === trim($recipients)) {
229
                return false;
230
            }
231
        } else {
232
            if (count($recipients) == 0) {
233
                return false;
234
            }
235
        }
236
        if (function_exists('xoops_getMailer')) {
237
            $xoopsMailer =& xoops_getMailer();
238
        } else {
239
            $xoopsMailer =& getMailer();
240
        }
241
242
        $xoopsMailer->useMail();
243
        $templateDir = XOOPS_ROOT_PATH . '/modules/' . self::MODULE_NAME . '/language/' . $xoopsConfig['language'] . '/mail_template';
244
        if (!is_dir($templateDir)) {
245
            $templateDir = XOOPS_ROOT_PATH . '/modules/' . self::MODULE_NAME . '/language/english/mail_template';
246
        }
247
        $xoopsMailer->setTemplateDir($templateDir);
248
        $xoopsMailer->setTemplate($tplName);
249
        $xoopsMailer->setToEmails($recipients);
250
        // TODO: Change !
251
        // $xoopsMailer->setFromEmail('[email protected]');
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% 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...
252
        //$xoopsMailer->setFromName('MonSite');
0 ignored issues
show
Unused Code Comprehensibility introduced by
86% 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...
253
        $xoopsMailer->setSubject($subject);
254
        foreach ($variables as $key => $value) {
255
            $xoopsMailer->assign($key, $value);
256
        }
257
        $res = $xoopsMailer->send();
258
        unset($xoopsMailer);
259
        $filename = XOOPS_UPLOAD_PATH . '/logmail_' . self::MODULE_NAME . '.php';
260
        if (!file_exists($filename)) {
261
            $fp = @fopen($filename, 'a');
262
            if ($fp) {
263
                fwrite($fp, "<?php exit(); ?>\n");
264
                fclose($fp);
265
            }
266
        }
267
        $fp = @fopen($filename, 'a');
268
269
        if ($fp) {
270
            fwrite($fp, str_repeat('-', 120) . "\n");
271
            fwrite($fp, date('d/m/Y H:i:s') . "\n");
272
            fwrite($fp, 'Template name : ' . $tplName . "\n");
273
            fwrite($fp, 'Email subject : ' . $subject . "\n");
274
            if (is_array($recipients)) {
275
                fwrite($fp, 'Recipient(s) : ' . implode(',', $recipients) . "\n");
276
            } else {
277
                fwrite($fp, 'Recipient(s) : ' . $recipients . "\n");
278
            }
279
            fwrite($fp, 'Transmited variables : ' . implode(',', $variables) . "\n");
280
            fclose($fp);
281
        }
282
283
        return $res;
284
    }
285
286
    /**
287
     * Remove module's cache
288
     */
289
    public static function updateCache()
290
    {
291
        global $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...
292
        $folder  = $xoopsModule->getVar('dirname');
293
        $tpllist = array();
0 ignored issues
show
Unused Code introduced by
$tpllist 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...
294
        require_once XOOPS_ROOT_PATH . '/class/xoopsblock.php';
295
        require_once XOOPS_ROOT_PATH . '/class/template.php';
296
        $tplfile_handler = xoops_getHandler('tplfile');
297
        $tpllist         = $tplfile_handler->find(null, null, null, $folder);
298
        xoops_template_clear_module_cache($xoopsModule->getVar('mid')); // Clear module's blocks cache
299
300
        foreach ($tpllist as $onetemplate) { // Remove cache for each page.
301
            if ('module' === $onetemplate->getVar('tpl_type')) {
302
                //  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
303
                $files_del = array();
0 ignored issues
show
Unused Code introduced by
$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...
304
                $files_del = glob(XOOPS_CACHE_PATH . '/*' . $onetemplate->getVar('tpl_file') . '*');
305
                if (count($files_del) > 0 && is_array($files_del)) {
306
                    foreach ($files_del as $one_file) {
307
                        if (is_file($one_file)) {
308
                            unlink($one_file);
309
                        }
310
                    }
311
                }
312
            }
313
        }
314
    }
315
316
    /**
317
     * Redirect user with a message
318
     *
319
     * @param string $message message to display
320
     * @param string $url     The place where to go
321
     * @param        integer  timeout Time to wait before to redirect
322
     */
323
    public static function redirect($message = '', $url = 'index.php', $time = 2)
324
    {
325
        redirect_header($url, $time, $message);
326
        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...
327
    }
328
329
    /**
330
     * Internal function used to get the handler of the current module
331
     *
332
     * @return XoopsModule The module
333
     */
334
    protected static function _getModule()
335
    {
336
        static $mymodule;
337
        if (!isset($mymodule)) {
338
            global $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...
339
            if (isset($xoopsModule) && is_object($xoopsModule) && $xoopsModule->getVar('dirname') == OLEDRION_DIRNAME) {
340
                $mymodule = $xoopsModule;
341
            } else {
342
                $hModule  = xoops_getHandler('module');
343
                $mymodule = $hModule->getByDirname(OLEDRION_DIRNAME);
344
            }
345
        }
346
347
        return $mymodule;
348
    }
349
350
    /**
351
     * Returns the module's name (as defined by the user in the module manager) with cache
352
     *
353
     * @return string Module's name
354
     */
355
    public static function getModuleName()
356
    {
357
        static $moduleName;
358
        if (!isset($moduleName)) {
359
            $mymodule   = self::_getModule();
360
            $moduleName = $mymodule->getVar('name');
361
        }
362
363
        return $moduleName;
364
    }
365
366
    /**
367
     * Create a title for the href tags inside html links
368
     *
369
     * @param string $title Text to use
370
     *
371
     * @return string Formated text
372
     */
373
    public static function makeHrefTitle($title)
374
    {
375
        $s = "\"'";
376
        $r = '  ';
377
378
        return strtr($title, $s, $r);
379
    }
380
381
    /**
382
     * Retourne la liste des utilisateurs appartenants à un groupe
383
     *
384
     * @param int $groupId Searched group
385
     *
386
     * @return array Array of XoopsUsers
387
     */
388
    public static function getUsersFromGroup($groupId)
389
    {
390
        $users          = array();
0 ignored issues
show
Unused Code introduced by
$users 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...
391
        $member_handler = xoops_getHandler('member');
392
        $users          = $member_handler->getUsersByGroup($groupId, true);
393
394
        return $users;
395
    }
396
397
    /**
398
     * Retourne la liste des emails des utilisateurs membres d'un groupe
399
     *
400
     * @param $groupId
401
     *
402
     * @internal param int $group_id Group's number
403
     * @return array Emails list
404
     */
405
    public static function getEmailsFromGroup($groupId)
406
    {
407
        $ret   = array();
408
        $users = self::getUsersFromGroup($groupId);
409
        foreach ($users as $user) {
410
            $ret[] = $user->getVar('email');
411
        }
412
413
        return $ret;
414
    }
415
416
    /**
417
     * Vérifie que l'utilisateur courant fait partie du groupe des administrateurs
418
     *
419
     * @return booleean Admin or not
0 ignored issues
show
Documentation introduced by
Should the return type not be boolean?

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...
420
     */
421
    public static function isAdmin()
422
    {
423
        global $xoopsUser, $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...
424
        if (is_object($xoopsUser)) {
425
            if (in_array(XOOPS_GROUP_ADMIN, $xoopsUser->getGroups())) {
426
                return true;
427
            } elseif (isset($xoopsModule) && $xoopsUser->isAdmin($xoopsModule->getVar('mid'))) {
428
                return true;
429
            }
430
        }
431
432
        return false;
433
    }
434
435
    /**
436
     * Returns the current date in the Mysql format
437
     *
438
     * @return string Date in the Mysql format
439
     */
440
    public static function getCurrentSQLDate()
441
    {
442
        return date('Y-m-d'); // 2007-05-02
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...
443
    }
444
445
    /**
446
     * @return bool|string
447
     */
448
    public static function getCurrentSQLDateTime()
449
    {
450
        return date('Y-m-d H:i:s'); // 2007-05-02
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...
451
    }
452
453
    /**
454
     * Convert a Mysql date to the human's format
455
     *
456
     * @param string $date The date to convert
457
     * @param string $format
458
     *
459
     * @return string The date in a human form
460
     */
461
    public static function SQLDateToHuman($date, $format = 'l')
462
    {
463
        if ($date != '0000-00-00' && xoops_trim($date) != '') {
464
            return formatTimestamp(strtotime($date), $format);
465
        } else {
466
            return '';
467
        }
468
    }
469
470
    /**
471
     * Convert a timestamp to a Mysql date
472
     *
473
     * @param integer $timestamp The timestamp to use
474
     *
475
     * @return string The date in the Mysql format
476
     */
477
    public static function timestampToMysqlDate($timestamp)
478
    {
479
        return date('Y-m-d', (int)$timestamp);
480
    }
481
482
    /**
483
     * Conversion d'un dateTime Mysql en date lisible en français
484
     *
485
     * @param $dateTime
486
     *
487
     * @return bool|string
488
     */
489
    public static function sqlDateTimeToFrench($dateTime)
490
    {
491
        return date('d/m/Y H:i:s', strtotime($dateTime));
492
    }
493
494
    /**
495
     * Convert a timestamp to a Mysql datetime form
496
     *
497
     * @param integer $timestamp The timestamp to use
498
     *
499
     * @return string The date and time in the Mysql format
500
     */
501
    public static function timestampToMysqlDateTime($timestamp)
502
    {
503
        return date('Y-m-d H:i:s', $timestamp);
504
    }
505
506
    /**
507
     * This function indicates if the current Xoops version needs to add asterisks to required fields in forms
508
     *
509
     * @return boolean Yes = we need to add them, false = no
510
     */
511
    public static function needsAsterisk()
512
    {
513
        if (self::isX23()) {
514
            return false;
515
        }
516
        if (strpos(strtolower(XOOPS_VERSION), 'impresscms') !== false) {
517
            return false;
518
        }
519
        if (false === strpos(strtolower(XOOPS_VERSION), 'legacy')) {
520
            $xv = xoops_trim(str_replace('XOOPS ', '', XOOPS_VERSION));
521
            if ((int)substr($xv, 4, 2) >= 17) {
522
                return false;
523
            }
524
        }
525
526
        return true;
527
    }
528
529
    /**
530
     * Mark the mandatory fields of a form with a star
531
     *
532
     * @param XoopsObject $sform The form to modify
533
     *
534
     * @internal param string $caracter The character to use to mark fields
535
     * @return object The modified form
536
     */
537
    public static function &formMarkRequiredFields(XoopsObject $sform)
538
    {
539
        if (self::needsAsterisk()) {
540
            $required = array();
541
            foreach ($sform->getRequired() as $item) {
542
                $required[] = $item->_name;
543
            }
544
            $elements = array();
0 ignored issues
show
Unused Code introduced by
$elements 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...
545
            $elements = $sform->getElements();
546
            $cnt      = count($elements);
547
            for ($i = 0; $i < $cnt; ++$i) {
548
                if (is_object($elements[$i]) && in_array($elements[$i]->_name, $required)) {
549
                    $elements[$i]->_caption .= ' *';
550
                }
551
            }
552
        }
553
554
        return $sform;
555
    }
556
557
    /**
558
     * Create an html heading (from h1 to h6)
559
     *
560
     * @param string  $title The text to use
561
     * @param integer $level Level to return
562
     *
563
     * @return string The heading
0 ignored issues
show
Documentation introduced by
Should the return type not be string|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...
564
     */
565
    public static function htitle($title = '', $level = 1)
566
    {
567
        printf('<h%01d>%s</h%01d>', $level, $title, $level);
568
    }
569
570
    /**
571
     * Create a unique upload filename
572
     *
573
     * @param string  $folder   The folder where the file will be saved
574
     * @param string  $fileName Original filename (coming from the user)
575
     * @param boolean $trimName Do we need to create a "short" unique name ?
576
     *
577
     * @return string The unique filename to use (with its extension)
578
     */
579
    public static function createUploadName($folder, $fileName, $trimName = false)
0 ignored issues
show
Coding Style introduced by
createUploadName uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
580
    {
581
        $workingfolder = $folder;
582
        if (xoops_substr($workingfolder, strlen($workingfolder) - 1, 1) !== '/') {
583
            $workingfolder .= '/';
584
        }
585
        $ext  = basename($fileName);
586
        $ext  = explode('.', $ext);
587
        $ext  = '.' . $ext[count($ext) - 1];
588
        $true = true;
589
        while ($true) {
590
            $ipbits = explode('.', $_SERVER['REMOTE_ADDR']);
591
            list($usec, $sec) = explode(' ', microtime());
592
            $usec = (integer)($usec * 65536);
593
            $sec  = ((integer)$sec) & 0xFFFF;
594
595
            if ($trimName) {
596
                $uid = sprintf('%06x%04x%04x', ($ipbits[0] << 24) | ($ipbits[1] << 16) | ($ipbits[2] << 8) | $ipbits[3], $sec, $usec);
597
            } else {
598
                $uid = sprintf('%08x-%04x-%04x', ($ipbits[0] << 24) | ($ipbits[1] << 16) | ($ipbits[2] << 8) | $ipbits[3], $sec, $usec);
599
            }
600
            if (!file_exists($workingfolder . $uid . $ext)) {
601
                $true = false;
602
            }
603
        }
604
605
        return $uid . $ext;
0 ignored issues
show
Bug introduced by
The variable $uid 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...
606
    }
607
608
    /**
609
     * Replace html entities with their ASCII equivalent
610
     *
611
     * @param string $chaine The string undecode
612
     *
613
     * @return string The undecoded string
614
     */
615
    public static function unhtml($chaine)
616
    {
617
        $search = $replace = array();
618
        $chaine = html_entity_decode($chaine);
619
620
        for ($i = 0; $i <= 255; ++$i) {
621
            $search[]  = '&#' . $i . ';';
622
            $replace[] = chr($i);
623
        }
624
        $replace[] = '...';
625
        $search[]  = '…';
626
        $replace[] = "'";
627
        $search[]  = '‘';
628
        $replace[] = "'";
629
        $search[]  = '’';
630
        $replace[] = '-';
631
        $search[]  = '&bull;'; // $replace[] = '•';
0 ignored issues
show
Unused Code Comprehensibility introduced by
56% 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...
632
        $replace[] = '—';
633
        $search[]  = '&mdash;';
634
        $replace[] = '-';
635
        $search[]  = '&ndash;';
636
        $replace[] = '-';
637
        $search[]  = '&shy;';
638
        $replace[] = '"';
639
        $search[]  = '&quot;';
640
        $replace[] = '&';
641
        $search[]  = '&amp;';
642
        $replace[] = 'ˆ';
643
        $search[]  = '&circ;';
644
        $replace[] = '¡';
645
        $search[]  = '&iexcl;';
646
        $replace[] = '¦';
647
        $search[]  = '&brvbar;';
648
        $replace[] = '¨';
649
        $search[]  = '&uml;';
650
        $replace[] = '¯';
651
        $search[]  = '&macr;';
652
        $replace[] = '´';
653
        $search[]  = '&acute;';
654
        $replace[] = '¸';
655
        $search[]  = '&cedil;';
656
        $replace[] = '¿';
657
        $search[]  = '&iquest;';
658
        $replace[] = '˜';
659
        $search[]  = '&tilde;';
660
        $replace[] = "'";
661
        $search[]  = '&lsquo;'; // $replace[]='‘';
0 ignored issues
show
Unused Code Comprehensibility introduced by
72% 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...
662
        $replace[] = "'";
663
        $search[]  = '&rsquo;'; // $replace[]='’';
0 ignored issues
show
Unused Code Comprehensibility introduced by
72% 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...
664
        $replace[] = '‚';
665
        $search[]  = '&sbquo;';
666
        $replace[] = "'";
667
        $search[]  = '&ldquo;'; // $replace[]='“';
0 ignored issues
show
Unused Code Comprehensibility introduced by
72% 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...
668
        $replace[] = "'";
669
        $search[]  = '&rdquo;'; // $replace[]='”';
0 ignored issues
show
Unused Code Comprehensibility introduced by
72% 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...
670
        $replace[] = '„';
671
        $search[]  = '&bdquo;';
672
        $replace[] = '‹';
673
        $search[]  = '&lsaquo;';
674
        $replace[] = '›';
675
        $search[]  = '&rsaquo;';
676
        $replace[] = '<';
677
        $search[]  = '&lt;';
678
        $replace[] = '>';
679
        $search[]  = '&gt;';
680
        $replace[] = '±';
681
        $search[]  = '&plusmn;';
682
        $replace[] = '«';
683
        $search[]  = '&laquo;';
684
        $replace[] = '»';
685
        $search[]  = '&raquo;';
686
        $replace[] = '×';
687
        $search[]  = '&times;';
688
        $replace[] = '÷';
689
        $search[]  = '&divide;';
690
        $replace[] = '¢';
691
        $search[]  = '&cent;';
692
        $replace[] = '£';
693
        $search[]  = '&pound;';
694
        $replace[] = '¤';
695
        $search[]  = '&curren;';
696
        $replace[] = '¥';
697
        $search[]  = '&yen;';
698
        $replace[] = '§';
699
        $search[]  = '&sect;';
700
        $replace[] = '©';
701
        $search[]  = '&copy;';
702
        $replace[] = '¬';
703
        $search[]  = '&not;';
704
        $replace[] = '®';
705
        $search[]  = '&reg;';
706
        $replace[] = '°';
707
        $search[]  = '&deg;';
708
        $replace[] = 'µ';
709
        $search[]  = '&micro;';
710
        $replace[] = '¶';
711
        $search[]  = '&para;';
712
        $replace[] = '·';
713
        $search[]  = '&middot;';
714
        $replace[] = '†';
715
        $search[]  = '&dagger;';
716
        $replace[] = '‡';
717
        $search[]  = '&Dagger;';
718
        $replace[] = '‰';
719
        $search[]  = '&permil;';
720
        $replace[] = 'Euro';
721
        $search[]  = '&euro;'; // $replace[]='€'
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% 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...
722
        $replace[] = '¼';
723
        $search[]  = '&frac14;';
724
        $replace[] = '½';
725
        $search[]  = '&frac12;';
726
        $replace[] = '¾';
727
        $search[]  = '&frac34;';
728
        $replace[] = '¹';
729
        $search[]  = '&sup1;';
730
        $replace[] = '²';
731
        $search[]  = '&sup2;';
732
        $replace[] = '³';
733
        $search[]  = '&sup3;';
734
        $replace[] = 'á';
735
        $search[]  = '&aacute;';
736
        $replace[] = 'Á';
737
        $search[]  = '&Aacute;';
738
        $replace[] = 'â';
739
        $search[]  = '&acirc;';
740
        $replace[] = 'Â';
741
        $search[]  = '&Acirc;';
742
        $replace[] = 'à';
743
        $search[]  = '&agrave;';
744
        $replace[] = 'À';
745
        $search[]  = '&Agrave;';
746
        $replace[] = 'å';
747
        $search[]  = '&aring;';
748
        $replace[] = 'Å';
749
        $search[]  = '&Aring;';
750
        $replace[] = 'ã';
751
        $search[]  = '&atilde;';
752
        $replace[] = 'Ã';
753
        $search[]  = '&Atilde;';
754
        $replace[] = 'ä';
755
        $search[]  = '&auml;';
756
        $replace[] = 'Ä';
757
        $search[]  = '&Auml;';
758
        $replace[] = 'ª';
759
        $search[]  = '&ordf;';
760
        $replace[] = 'æ';
761
        $search[]  = '&aelig;';
762
        $replace[] = 'Æ';
763
        $search[]  = '&AElig;';
764
        $replace[] = 'ç';
765
        $search[]  = '&ccedil;';
766
        $replace[] = 'Ç';
767
        $search[]  = '&Ccedil;';
768
        $replace[] = 'ð';
769
        $search[]  = '&eth;';
770
        $replace[] = 'Ð';
771
        $search[]  = '&ETH;';
772
        $replace[] = 'é';
773
        $search[]  = '&eacute;';
774
        $replace[] = 'É';
775
        $search[]  = '&Eacute;';
776
        $replace[] = 'ê';
777
        $search[]  = '&ecirc;';
778
        $replace[] = 'Ê';
779
        $search[]  = '&Ecirc;';
780
        $replace[] = 'è';
781
        $search[]  = '&egrave;';
782
        $replace[] = 'È';
783
        $search[]  = '&Egrave;';
784
        $replace[] = 'ë';
785
        $search[]  = '&euml;';
786
        $replace[] = 'Ë';
787
        $search[]  = '&Euml;';
788
        $replace[] = 'ƒ';
789
        $search[]  = '&fnof;';
790
        $replace[] = 'í';
791
        $search[]  = '&iacute;';
792
        $replace[] = 'Í';
793
        $search[]  = '&Iacute;';
794
        $replace[] = 'î';
795
        $search[]  = '&icirc;';
796
        $replace[] = 'Î';
797
        $search[]  = '&Icirc;';
798
        $replace[] = 'ì';
799
        $search[]  = '&igrave;';
800
        $replace[] = 'Ì';
801
        $search[]  = '&Igrave;';
802
        $replace[] = 'ï';
803
        $search[]  = '&iuml;';
804
        $replace[] = 'Ï';
805
        $search[]  = '&Iuml;';
806
        $replace[] = 'ñ';
807
        $search[]  = '&ntilde;';
808
        $replace[] = 'Ñ';
809
        $search[]  = '&Ntilde;';
810
        $replace[] = 'ó';
811
        $search[]  = '&oacute;';
812
        $replace[] = 'Ó';
813
        $search[]  = '&Oacute;';
814
        $replace[] = 'ô';
815
        $search[]  = '&ocirc;';
816
        $replace[] = 'Ô';
817
        $search[]  = '&Ocirc;';
818
        $replace[] = 'ò';
819
        $search[]  = '&ograve;';
820
        $replace[] = 'Ò';
821
        $search[]  = '&Ograve;';
822
        $replace[] = 'º';
823
        $search[]  = '&ordm;';
824
        $replace[] = 'ø';
825
        $search[]  = '&oslash;';
826
        $replace[] = 'Ø';
827
        $search[]  = '&Oslash;';
828
        $replace[] = 'õ';
829
        $search[]  = '&otilde;';
830
        $replace[] = 'Õ';
831
        $search[]  = '&Otilde;';
832
        $replace[] = 'ö';
833
        $search[]  = '&ouml;';
834
        $replace[] = 'Ö';
835
        $search[]  = '&Ouml;';
836
        $replace[] = 'œ';
837
        $search[]  = '&oelig;';
838
        $replace[] = 'Œ';
839
        $search[]  = '&OElig;';
840
        $replace[] = 'š';
841
        $search[]  = '&scaron;';
842
        $replace[] = 'Š';
843
        $search[]  = '&Scaron;';
844
        $replace[] = 'ß';
845
        $search[]  = '&szlig;';
846
        $replace[] = 'þ';
847
        $search[]  = '&thorn;';
848
        $replace[] = 'Þ';
849
        $search[]  = '&THORN;';
850
        $replace[] = 'ú';
851
        $search[]  = '&uacute;';
852
        $replace[] = 'Ú';
853
        $search[]  = '&Uacute;';
854
        $replace[] = 'û';
855
        $search[]  = '&ucirc;';
856
        $replace[] = 'Û';
857
        $search[]  = '&Ucirc;';
858
        $replace[] = 'ù';
859
        $search[]  = '&ugrave;';
860
        $replace[] = 'Ù';
861
        $search[]  = '&Ugrave;';
862
        $replace[] = 'ü';
863
        $search[]  = '&uuml;';
864
        $replace[] = 'Ü';
865
        $search[]  = '&Uuml;';
866
        $replace[] = 'ý';
867
        $search[]  = '&yacute;';
868
        $replace[] = 'Ý';
869
        $search[]  = '&Yacute;';
870
        $replace[] = 'ÿ';
871
        $search[]  = '&yuml;';
872
        $replace[] = 'Ÿ';
873
        $search[]  = '&Yuml;';
874
        $chaine    = str_replace($search, $replace, $chaine);
875
876
        return $chaine;
877
    }
878
879
    /**
880
     * Création d'une titre pour être utilisé par l'url rewriting
881
     *
882
     * @param string  $content Le texte à utiliser pour créer l'url
883
     * @param integer $urw     La limite basse pour créer les mots
884
     *
885
     * @return string Le texte à utiliser pour l'url
886
     *                Note, some parts are from Solo's code
887
     */
888
    public static function makeSeoUrl($content, $urw = 1)
889
    {
890
        $s       = "ÀÁÂÃÄÅÒÓÔÕÖØÈÉÊËÇÌÍÎÏÙÚÛܟÑàáâãäåòóôõöøèéêëçìíîïùúûüÿñ '()";
891
        $r       = 'AAAAAAOOOOOOEEEECIIIIUUUUYNaaaaaaooooooeeeeciiiiuuuuyn----';
892
        $content = self::unhtml($content); // First, remove html entities
893
        $content = strtr($content, $s, $r);
894
        $content = strip_tags($content);
895
        $content = strtolower($content);
896
        $content = htmlentities($content); // TODO: Vérifier
897
        $content = preg_replace('/&([a-zA-Z])(uml|acute|grave|circ|tilde);/', '$1', $content);
898
        $content = html_entity_decode($content);
899
        $content = preg_replace('/quot/i', ' ', $content);
900
        $content = preg_replace("/'/i", ' ', $content);
901
        $content = preg_replace('/-/i', ' ', $content);
902
        $content = preg_replace('/[[:punct:]]/i', '', $content);
903
904
        // Selon option mais attention au fichier .htaccess !
905
        // $content = eregi_replace('[[:digit:]]','', $content);
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% 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...
906
        $content = preg_replace('/[^a-z|A-Z|0-9]/', '-', $content);
907
908
        $words    = explode(' ', $content);
909
        $keywords = '';
910
        foreach ($words as $word) {
911
            if (strlen($word) >= $urw) {
912
                $keywords .= '-' . trim($word);
913
            }
914
        }
915
        if (!$keywords) {
916
            $keywords = '-';
917
        }
918
        // Supprime les tirets en double
919
        $keywords = str_replace('---', '-', $keywords);
920
        $keywords = str_replace('--', '-', $keywords);
921
        // Supprime un éventuel tiret à la fin de la chaine
922
        if ('-' === substr($keywords, strlen($keywords) - 1, 1)) {
923
            $keywords = substr($keywords, 0, -1);
924
        }
925
926
        return $keywords;
927
    }
928
929
    /**
930
     * Create the meta keywords based on the content
931
     *
932
     * @param string $content Content from which we have to create metakeywords
933
     *
934
     * @return string The list of meta keywords
935
     */
936
    public static function createMetaKeywords($content)
0 ignored issues
show
Coding Style introduced by
createMetaKeywords uses the super-global variable $_SESSION which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
937
    {
938
        $keywordscount = self::getModuleOption('metagen_maxwords');
939
        $keywordsorder = self::getModuleOption('metagen_order');
940
941
        $tmp = array();
942
        // Search for the "Minimum keyword length"
943
        if (isset($_SESSION['oledrion_keywords_limit'])) {
944
            $limit = $_SESSION['oledrion_keywords_limit'];
945
        } else {
946
            $config_handler                      = xoops_getHandler('config');
947
            $xoopsConfigSearch                   = $config_handler->getConfigsByCat(XOOPS_CONF_SEARCH);
948
            $limit                               = $xoopsConfigSearch['keyword_min'];
949
            $_SESSION['oledrion_keywords_limit'] = $limit;
950
        }
951
        $myts            = MyTextSanitizer::getInstance();
952
        $content         = str_replace('<br>', ' ', $content);
953
        $content         = $myts->undoHtmlSpecialChars($content);
954
        $content         = strip_tags($content);
955
        $content         = strtolower($content);
956
        $search_pattern  = array('&nbsp;', "\t", "\r\n", "\r", "\n", ',', '.', "'", ';', ':', ')', '(', '"', '?', '!', '{', '}', '[', ']', '<', '>', '/', '+', '-', '_', '\\', '*');
957
        $replace_pattern = array(' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '');
958
        $content         = str_replace($search_pattern, $replace_pattern, $content);
959
        $keywords        = explode(' ', $content);
960
        switch ($keywordsorder) {
961
            case 0: // Ordre d'apparition dans le texte
962
                $keywords = array_unique($keywords);
963
                break;
964
            case 1: // Ordre de fréquence des mots
965
                $keywords = array_count_values($keywords);
966
                asort($keywords);
967
                $keywords = array_keys($keywords);
968
                break;
969
            case 2: // Ordre inverse de la fréquence des mots
970
                $keywords = array_count_values($keywords);
971
                arsort($keywords);
972
                $keywords = array_keys($keywords);
973
                break;
974
        }
975
        // Remove black listed words
976
        if (xoops_trim(self::getModuleOption('metagen_blacklist')) !== '') {
977
            $metagen_blacklist = str_replace("\r", '', self::getModuleOption('metagen_blacklist'));
978
            $metablack         = explode("\n", $metagen_blacklist);
979
            array_walk($metablack, 'trim');
980
            $keywords = array_diff($keywords, $metablack);
981
        }
982
983
        foreach ($keywords as $keyword) {
984
            if (strlen($keyword) >= $limit && !is_numeric($keyword)) {
985
                $tmp[] = $keyword;
986
            }
987
        }
988
        $tmp = array_slice($tmp, 0, $keywordscount);
989
        if (count($tmp) > 0) {
990
            return implode(',', $tmp);
991
        } else {
992
            if (!isset($config_handler) || !is_object($config_handler)) {
993
                $config_handler = xoops_getHandler('config');
994
            }
995
            $xoopsConfigMetaFooter = $config_handler->getConfigsByCat(XOOPS_CONF_METAFOOTER);
996
            if (isset($xoopsConfigMetaFooter['meta_keywords'])) {
997
                return $xoopsConfigMetaFooter['meta_keywords'];
998
            } else {
999
                return '';
1000
            }
1001
        }
1002
    }
1003
1004
    /**
1005
     * Fonction chargée de gérer l'upload
1006
     *
1007
     * @param integer $indice L'indice du fichier à télécharger
1008
     * @param string  $dstpath
1009
     * @param null    $mimeTypes
1010
     * @param null    $uploadMaxSize
1011
     * @param null    $maxWidth
1012
     * @param null    $maxHeight
1013
     *
1014
     * @return mixed True si l'upload s'est bien déroulé sinon le message d'erreur correspondant
1015
     */
1016
    public static function uploadFile($indice, $dstpath = XOOPS_UPLOAD_PATH, $mimeTypes = null, $uploadMaxSize = null, $maxWidth = null, $maxHeight = null)
0 ignored issues
show
Coding Style introduced by
uploadFile uses the super-global variable $_POST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
Coding Style introduced by
uploadFile uses the super-global variable $_FILES which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
1017
    {
1018
        require_once XOOPS_ROOT_PATH . '/class/uploader.php';
1019
        global $destname;
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...
1020
        if (isset($_POST['xoops_upload_file'])) {
1021
            require_once XOOPS_ROOT_PATH . '/class/uploader.php';
1022
            $fldname = '';
0 ignored issues
show
Unused Code introduced by
$fldname 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...
1023
            $fldname = $_FILES[$_POST['xoops_upload_file'][$indice]];
1024
            $fldname = $fldname['name'];
1025
            if (xoops_trim($fldname !== '')) {
1026
                $destname = self::createUploadName($dstpath, $fldname, true);
1027
                if (null === $mimeTypes) {
1028
                    $permittedtypes = explode("\n", str_replace("\r", '', self::getModuleOption('mimetypes')));
1029
                    array_walk($permittedtypes, 'trim');
1030
                } else {
1031
                    $permittedtypes = $mimeTypes;
1032
                }
1033
                $uploadSize = null === $uploadMaxSize ? self::getModuleOption('maxuploadsize') : $uploadMaxSize;
1034
                $uploader   = new XoopsMediaUploader($dstpath, $permittedtypes, $uploadSize, $maxWidth, $maxHeight);
0 ignored issues
show
Documentation introduced by
$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...
1035
                //$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...
1036
                $uploader->setTargetFileName($destname);
1037
                if ($uploader->fetchMedia($_POST['xoops_upload_file'][$indice])) {
1038
                    if ($uploader->upload()) {
1039
                        return true;
1040
                    } else {
1041
                        return _ERRORS . ' ' . htmlentities($uploader->getErrors());
1042
                    }
1043
                } else {
1044
                    return htmlentities($uploader->getErrors());
1045
                }
1046
            } else {
1047
                return false;
1048
            }
1049
        } else {
1050
            return false;
1051
        }
1052
    }
1053
1054
    /**
1055
     * Resize a Picture to some given dimensions (using the wideImage library)
1056
     *
1057
     * @param string  $src_path      Picture's source
1058
     * @param string  $dst_path      Picture's destination
1059
     * @param integer $param_width   Maximum picture's width
1060
     * @param integer $param_height  Maximum picture's height
1061
     * @param boolean $keep_original Do we have to keep the original picture ?
1062
     * @param string  $fit           Resize mode (see the wideImage library for more information)
1063
     *
1064
     * @return bool
1065
     */
1066
    public static function resizePicture($src_path, $dst_path, $param_width, $param_height, $keep_original = false, $fit = 'inside')
1067
    {
1068
        //        require_once OLEDRION_PATH . 'class/wideimage/WideImage.inc.php';
1069
        $resize = true;
1070
        if (OLEDRION_DONT_RESIZE_IF_SMALLER) {
1071
            $pictureDimensions = getimagesize($src_path);
1072
            if (is_array($pictureDimensions)) {
1073
                $width  = $pictureDimensions[0];
1074
                $height = $pictureDimensions[1];
1075
                if ($width < $param_width && $height < $param_height) {
1076
                    $resize = false;
1077
                }
1078
            }
1079
        }
1080
1081
        $img = WideImage::load($src_path);
1082
        if ($resize) {
1083
            $result = $img->resize($param_width, $param_height, $fit);
1084
            $result->saveToFile($dst_path);
1085
        } else {
1086
            @copy($src_path, $dst_path);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
1087
        }
1088
1089
        if (!$keep_original) {
1090
            @unlink($src_path);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
1091
        }
1092
1093
        return true;
1094
    }
1095
1096
    /**
1097
     * Déclenchement d'une alerte Xoops suite à un évènement
1098
     *
1099
     * @param string       $category La catégorie de l'évènement
1100
     * @param integer      $itemId   L'ID de l'élément (trop général pour être décris précisément)
1101
     * @param unknown_type $event    L'évènement qui est déclencé
1102
     * @param unknown_type $tags     Les variables à passer au template
1103
     */
1104
    public static function notify($category, $itemId, $event, $tags)
1105
    {
1106
        $notification_handler = xoops_getHandler('notification');
1107
        $tags['X_MODULE_URL'] = OLEDRION_URL;
1108
        $notification_handler->triggerEvent($category, $itemId, $event, $tags);
1109
    }
1110
1111
    /**
1112
     * Ajoute des jours à une date et retourne la nouvelle date au format Date de Mysql
1113
     *
1114
     * @param int     $duration
1115
     * @param integer $startingDate Date de départ (timestamp)
1116
     *
1117
     * @internal param int $durations Durée en jours
1118
     * @return bool|string
1119
     */
1120
    public static function addDaysToDate($duration = 1, $startingDate = 0)
1121
    {
1122
        if ($startingDate == 0) {
1123
            $startingDate = time();
1124
        }
1125
        $endingDate = $startingDate + ($duration * 86400);
1126
1127
        return date('Y-m-d', $endingDate);
1128
    }
1129
1130
    /**
1131
     * Retourne un breadcrumb en fonction des paramètres passés et en partant (d'office) de la racine du module
1132
     *
1133
     * @param array  $path  Le chemin complet (excepté la racine) du breadcrumb sous la forme clé=url valeur=titre
1134
     * @param string $raquo Le séparateur par défaut à utiliser
1135
     *
1136
     * @return string le breadcrumb
1137
     */
1138
    public static function breadcrumb($path, $raquo = ' &raquo; ')
1139
    {
1140
        $breadcrumb        = '';
1141
        $workingBreadcrumb = array();
1142
        if (is_array($path)) {
1143
            $moduleName          = self::getModuleName();
1144
            $workingBreadcrumb[] = "<a href='" . OLEDRION_URL . "' title='" . self::makeHrefTitle($moduleName) . "'>" . $moduleName . '</a>';
1145
            foreach ($path as $url => $title) {
1146
                $workingBreadcrumb[] = "<a href='" . $url . "'>" . $title . '</a>';
1147
            }
1148
            $cnt = count($workingBreadcrumb);
1149
            for ($i = 0; $i < $cnt; ++$i) {
1150
                if ($i == $cnt - 1) {
1151
                    $workingBreadcrumb[$i] = strip_tags($workingBreadcrumb[$i]);
1152
                }
1153
            }
1154
            $breadcrumb = implode($raquo, $workingBreadcrumb);
1155
        }
1156
1157
        return $breadcrumb;
1158
    }
1159
1160
    /**
1161
     * @param $string
1162
     *
1163
     * @return string
1164
     */
1165
    public static function close_tags($string)
1166
    {
1167
        // match opened tags
1168
        if (preg_match_all('/<([a-z\:\-]+)[^\/]>/', $string, $start_tags)) {
1169
            $start_tags = $start_tags[1];
1170
1171
            // match closed tags
1172
            if (preg_match_all('/<\/([a-z]+)>/', $string, $end_tags)) {
1173
                $complete_tags = array();
1174
                $end_tags      = $end_tags[1];
1175
1176
                foreach ($start_tags as $key => $val) {
1177
                    $posb = array_search($val, $end_tags);
1178
                    if (is_int($posb)) {
1179
                        unset($end_tags[$posb]);
1180
                    } else {
1181
                        $complete_tags[] = $val;
1182
                    }
1183
                }
1184
            } else {
1185
                $complete_tags = $start_tags;
1186
            }
1187
1188
            $complete_tags = array_reverse($complete_tags);
1189
            for ($i = 0, $iMax = count($complete_tags); $i < $iMax; ++$i) {
1190
                $string .= '</' . $complete_tags[$i] . '>';
1191
            }
1192
        }
1193
1194
        return $string;
1195
    }
1196
1197
    /**
1198
     * @param        $string
1199
     * @param int    $length
1200
     * @param string $etc
1201
     * @param bool   $break_words
1202
     *
1203
     * @return mixed|string
1204
     */
1205
    public static function truncate_tagsafe($string, $length = 80, $etc = '...', $break_words = false)
1206
    {
1207
        if ($length == 0) {
1208
            return '';
1209
        }
1210
1211
        if (strlen($string) > $length) {
1212
            $length -= strlen($etc);
1213
            if (!$break_words) {
1214
                $string = preg_replace('/\s+?(\S+)?$/', '', substr($string, 0, $length + 1));
1215
                $string = preg_replace('/<[^>]*$/', '', $string);
1216
                $string = self::close_tags($string);
1217
            }
1218
1219
            return $string . $etc;
1220
        } else {
1221
            return $string;
1222
        }
1223
    }
1224
1225
    /**
1226
     * Create an infotip
1227
     * @param $text
1228
     * @return string
1229
     */
1230
    public static function makeInfotips($text)
1231
    {
1232
        $ret      = '';
1233
        $infotips = self::getModuleOption('infotips');
1234
        if ($infotips > 0) {
1235
            $myts = MyTextSanitizer::getInstance();
1236
            $ret  = $myts->htmlSpecialChars(xoops_substr(strip_tags($text), 0, $infotips));
1237
        }
1238
1239
        return $ret;
1240
    }
1241
1242
    /**
1243
     * Mise en place de l'appel à la feuille de style du module dans le template
1244
     * @param string $url
1245
     */
1246
    public static function setCSS($url = '')
1247
    {
1248
        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...
1249
        if ('' === $url) {
1250
            $url = OLEDRION_URL . 'css/oledrion.css';
1251
        }
1252
1253
        if (!is_object($xoTheme)) {
1254
            $xoopsTpl->assign('xoops_module_header', $xoopsTpl->get_template_vars('xoops_module_header') . "<link rel=\"stylesheet\" type=\"text/css\" href=\"$url\" />");
1255
        } else {
1256
            $xoTheme->addStylesheet($url);
1257
        }
1258
    }
1259
1260
    /**
1261
     * Mise en place de l'appel à la feuille de style du module dans le template
1262
     * @param string $language
1263
     */
1264
    public static function setLocalCSS($language = 'english')
1265
    {
1266
        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...
1267
1268
        $localcss = OLEDRION_URL . 'language/' . $language . '/style.css';
1269
1270
        if (!is_object($xoTheme)) {
1271
            $xoopsTpl->assign('xoops_module_header', $xoopsTpl->get_template_vars('xoops_module_header') . "<link rel=\"stylesheet\" type=\"text/css\" href=\"$localcss\" />");
1272
        } else {
1273
            $xoTheme->addStylesheet($localcss);
1274
        }
1275
    }
1276
1277
    /**
1278
     * Calcul du TTC à partir du HT et de la TVA
1279
     *
1280
     * @param float   $ht     Montant HT
1281
     * @param float   $vat    Taux de TVA
1282
     * @param boolean $edit   Si faux alors le montant est formaté pour affichage sinon il reste tel quel
1283
     * @param string  $format Format d'affichage du résultat (long ou court)
1284
     *
1285
     * @return mixed Soit une chaine soit un flottant
1286
     */
1287
    public static function getTTC($ht, $vat, $edit = false, $format = 's')
1288
    {
1289
        $oledrion_Currency = oledrion_Currency::getInstance();
1290
        $ttc               = $ht * (1 + ($vat / 100));
1291
        if (!$edit) {
1292
            return $oledrion_Currency->amountForDisplay($ttc, $format);
1293
        } else {
1294
            return $ttc;
1295
        }
1296
    }
1297
1298
    /**
1299
     * Renvoie le montant de la tva à partir du montant HT
1300
     * @param $ht
1301
     * @param $vat
1302
     * @return float
1303
     */
1304
    public static function getVAT($ht, $vat)
1305
    {
1306
        return (float)($ht * $vat);
1307
    }
1308
1309
    /**
1310
     * Retourne le montant TTC
1311
     *
1312
     * @param floatval $product_price Le montant du produit
1313
     * @param integer  $vat_id        Le numéro de TVA
1314
     *
1315
     * @return floatval Le montant TTC si on a trouvé sa TVA sinon
1316
     */
1317
    public static function getAmountWithVat($product_price, $vat_id)
1318
    {
1319
        static $vats = array();
1320
        $vat_rate = null;
1321
        if (is_array($vats) && in_array($vat_id, $vats)) {
1322
            $vat_rate = $vats[$vat_id];
1323
        } else {
1324
            $handlers = oledrion_handler::getInstance();
1325
            $vat      = null;
0 ignored issues
show
Unused Code introduced by
$vat 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...
1326
            $vat      = $handlers->h_oledrion_vat->get($vat_id);
1327
            if (is_object($vat)) {
1328
                $vat_rate      = $vat->getVar('vat_rate', 'e');
1329
                $vats[$vat_id] = $vat_rate;
1330
            }
1331
        }
1332
1333
        if (!null === $vat_rate) {
1334
            return ((float)$product_price * (float)$vat_rate / 100) + (float)$product_price;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return (double) $product...double) $product_price; (double) is incompatible with the return type documented by XoopstubeUtilities::getAmountWithVat of type floatval.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
1335
        } else {
1336
            return $product_price;
1337
        }
1338
    }
1339
1340
    /**
1341
     * @param $datastream
1342
     * @param $url
1343
     *
1344
     * @return string
1345
     */
1346
    public static function postIt($datastream, $url)
1347
    {
1348
        $url     = preg_replace('@^http://@i', '', $url);
1349
        $host    = substr($url, 0, strpos($url, '/'));
1350
        $uri     = strstr($url, '/');
1351
        $reqbody = '';
1352
        foreach ($datastream as $key => $val) {
1353
            if (!empty($reqbody)) {
1354
                $reqbody .= '&';
1355
            }
1356
            $reqbody .= $key . '=' . urlencode($val);
1357
        }
1358
        $contentlength = strlen($reqbody);
1359
        $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";
1360
1361
        return $reqheader;
1362
    }
1363
1364
    /**
1365
     * Returns the mime type of a file using first finfo then mime_content
1366
     *      
1367
     * @param String $ filename The file (with full path) that you want to know the mime type
1368
     * @return string
1369
     */
1370
    public static function getMimeType($filename)
1371
    {
1372
        if (function_exists('finfo_open')) {
1373
            $finfo    = finfo_open();
1374
            $mimetype = finfo_file($finfo, $filename, FILEINFO_MIME_TYPE);
1375
            finfo_close($finfo);
1376
1377
            return $mimetype;
1378
        } else {
1379
            if (function_exists('mime_content_type')) {
1380
                return mime_content_type($filename);
1381
            } else {
1382
                return '';
1383
            }
1384
        }
1385
    }
1386
1387
    /**
1388
     * Retourne un criteria compo qui permet de filtrer les produits sur le mois courant
1389
     *
1390
     * @return object
1391
     */
1392
    public static function getThisMonthCriteria()
1393
    {
1394
        $start             = mktime(0, 1, 0, date('n'), date('j'), date('Y'));
1395
        $end               = mktime(0, 0, 0, date('n'), date('t'), date('Y'));
1396
        $criteriaThisMonth = new CriteriaCompo();
1397
        $criteriaThisMonth->add(new Criteria('product_submitted', $start, '>='));
1398
        $criteriaThisMonth->add(new Criteria('product_submitted', $end, '<='));
1399
1400
        return $criteriaThisMonth;
1401
    }
1402
1403
    /**
1404
     * Retourne une liste d'objets XoopsUsers à partir d'une liste d'identifiants
1405
     *
1406
     * @param array $xoopsUsersIDs La liste des ID
1407
     *
1408
     * @return array Les objets XoopsUsers
1409
     */
1410
    public static function getUsersFromIds($xoopsUsersIDs)
1411
    {
1412
        $users = array();
1413
        if (is_array($xoopsUsersIDs) && count($xoopsUsersIDs) > 0) {
1414
            $xoopsUsersIDs = array_unique($xoopsUsersIDs);
1415
            sort($xoopsUsersIDs);
1416
            if (count($xoopsUsersIDs) > 0) {
1417
                $member_handler = xoops_getHandler('user');
1418
                $criteria       = new Criteria('uid', '(' . implode(',', $xoopsUsersIDs) . ')', 'IN');
1419
                $criteria->setSort('uid');
1420
                $users = $member_handler->getObjects($criteria, true);
1421
            }
1422
        }
1423
1424
        return $users;
1425
    }
1426
1427
    /**
1428
     * Retourne l'ID de l'utilisateur courant (s'il est connecté)
1429
     *
1430
     * @return integer L'uid ou 0
1431
     */
1432
    public static function getCurrentUserID()
1433
    {
1434
        global $xoopsUser;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

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

1. Pass all data via parameters

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

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

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

    public function myFunction() {
        // Do something
    }
}
Loading history...
1435
        $uid = is_object($xoopsUser) ? $xoopsUser->getVar('uid') : 0;
1436
1437
        return $uid;
1438
    }
1439
1440
    /**
1441
     * Retourne la liste des groupes de l'utilisateur courant (avec cache)
1442
     *
1443
     * @param int $uid
1444
     *
1445
     * @return array Les ID des groupes auquel l'utilisateur courant appartient
1446
     */
1447
    public static function getMemberGroups($uid = 0)
1448
    {
1449
        static $buffer = array();
1450
        if ($uid == 0) {
1451
            $uid = self::getCurrentUserID();
1452
        }
1453
1454
        if (is_array($buffer) && count($buffer) > 0 && isset($buffer[$uid])) {
1455
            return $buffer[$uid];
1456
        } else {
1457
            if ($uid > 0) {
1458
                $member_handler = xoops_getHandler('member');
1459
                $buffer[$uid]   = $member_handler->getGroupsByUser($uid, false); // Renvoie un tableau d'ID (de groupes)
1460
            } else {
1461
                $buffer[$uid] = array(XOOPS_GROUP_ANONYMOUS);
1462
            }
1463
        }
1464
1465
        return $buffer[$uid];
1466
    }
1467
1468
    /**
1469
     * Indique si l'utilisateur courant fait partie d'une groupe donné (avec gestion de cache)
1470
     *
1471
     * @param integer $group Groupe recherché
1472
     * @param int     $uid
1473
     *
1474
     * @return boolean vrai si l'utilisateur fait partie du groupe, faux sinon
1475
     */
1476
    public static function isMemberOfGroup($group = 0, $uid = 0)
1477
    {
1478
        static $buffer = array();
1479
        $retval = false;
0 ignored issues
show
Unused Code introduced by
$retval 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...
1480
        if ($uid == 0) {
1481
            $uid = self::getCurrentUserID();
1482
        }
1483
        if (is_array($buffer) && array_key_exists($group, $buffer)) {
1484
            $retval = $buffer[$group];
1485
        } else {
1486
            $member_handler = xoops_getHandler('member');
1487
            $groups         = $member_handler->getGroupsByUser($uid, false); // Renvoie un tableau d'ID (de groupes)
1488
            $retval         = in_array($group, $groups);
1489
            $buffer[$group] = $retval;
1490
        }
1491
1492
        return $retval;
1493
    }
1494
1495
    /**
1496
     * Function responsible for verifying that a directory exists, we can write in and create an index.html file
1497
     * 
1498
     * @param String $ folder The full directory to verify
1499
     *
1500
     */
1501
    public static function prepareFolder($folder)
1502
    {
1503
        if (!is_dir($folder)) {
1504
            mkdir($folder);
1505
            file_put_contents($folder . '/index.html', '<script>history.go(-1);</script>');
1506
        }
1507
        //        chmod($folder, 0777);
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% 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...
1508
    }
1509
1510
    /**
1511
     * Duplicate a file in local
1512
     *
1513
     * @param string $path     The file's path
1514
     * @param string $filename The filename
1515
     *
1516
     * @return mixed If the copy succeed, the new filename else false
1517
     * @since 2.1
1518
     */
1519
    public static function duplicateFile($path, $filename)
1520
    {
1521
        $newName = self::createUploadName($path, $filename);
1522
        if (copy($path . DIRECTORY_SEPARATOR . $filename, $path . DIRECTORY_SEPARATOR . $newName)) {
1523
            return $newName;
1524
        } else {
1525
            return false;
1526
        }
1527
    }
1528
1529
    /**
1530
     * Load a language file
1531
     *
1532
     * @param string $languageFile     The required language file
1533
     * @param string $defaultExtension Default extension to use
1534
     *
1535
     * @since 2.2.2009.02.13
1536
     */
1537
    public static function loadLanguageFile($languageFile, $defaultExtension = '.php')
1538
    {
1539
        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...
1540
        $root = OLEDRION_PATH;
1541
        if (false === strpos($languageFile, $defaultExtension)) {
1542
            $languageFile .= $defaultExtension;
1543
        }
1544
        if (file_exists($root . 'language' . DIRECTORY_SEPARATOR . $xoopsConfig['language'] . DIRECTORY_SEPARATOR . $languageFile)) {
1545
            require_once $root . 'language' . DIRECTORY_SEPARATOR . $xoopsConfig['language'] . DIRECTORY_SEPARATOR . $languageFile;
1546
        } else { // Fallback
1547
            require_once $root . 'language' . DIRECTORY_SEPARATOR . 'english' . DIRECTORY_SEPARATOR . $languageFile;
1548
        }
1549
    }
1550
1551
    /**
1552
     * Formatage d'un floattant pour la base de données
1553
     *
1554
     * @param float    Le montant à formater
1555
     *
1556
     * @return string le montant formaté
1557
     * @since 2.2.2009.02.25
1558
     */
1559
    public static function formatFloatForDB($amount)
1560
    {
1561
        return number_format($amount, 2, '.', '');
1562
    }
1563
1564
    /**
1565
     * Appelle un fichier Javascript à la manière de Xoops
1566
     *
1567
     * @note, l'url complète ne doit pas être fournie, la méthode se charge d'ajouter
1568
     * le chemin vers le répertoire js en fonction de la requête, c'est à dire que si
1569
     * on appelle un fichier de langue, la méthode ajoute l'url vers le répertoire de
1570
     * langue, dans le cas contraire on ajoute l'url vers le répertoire JS du module.
1571
     *
1572
     * @param string $javascriptFile
1573
     * @param bool   $inLanguageFolder
1574
     * @param bool   $oldWay
1575
     *
1576
     * @return void
1577
     * @since 2.3.2009.03.14
1578
     */
1579
    public static function callJavascriptFile($javascriptFile, $inLanguageFolder = false, $oldWay = false)
0 ignored issues
show
Unused Code introduced by
The parameter $oldWay is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
1580
    {
1581
        global $xoopsConfig, $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...
1582
        $fileToCall = $javascriptFile;
0 ignored issues
show
Unused Code introduced by
$fileToCall 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...
1583
        if ($inLanguageFolder) {
1584
            $root    = OLEDRION_PATH;
1585
            $rootUrl = OLEDRION_URL;
1586
            if (file_exists($root . 'language' . DIRECTORY_SEPARATOR . $xoopsConfig['language'] . DIRECTORY_SEPARATOR . $javascriptFile)) {
1587
                $fileToCall = $rootUrl . 'language/' . $xoopsConfig['language'] . '/' . $javascriptFile;
1588
            } else { // Fallback
1589
                $fileToCall = $rootUrl . 'language/english/' . $javascriptFile;
1590
            }
1591
        } else {
1592
            $fileToCall = OLEDRION_JS_URL . $javascriptFile;
1593
        }
1594
1595
        $xoTheme->addScript('browse.php?Frameworks/jquery/jquery.js');
1596
        $xoTheme->addScript($fileToCall);
1597
    }
1598
1599
    /**
1600
     * Create the <option> of an html select
1601
     *
1602
     * @param array $array   Array of index and labels
1603
     * @param mixed $default the default value
1604
     * @param bool  $withNull
1605
     *
1606
     * @return string
1607
     * @since 2.3.2009.03.13
1608
     */
1609
    public static function htmlSelectOptions($array, $default = 0, $withNull = true)
1610
    {
1611
        $ret      = array();
1612
        $selected = '';
1613
        if ($withNull) {
1614
            if (0 == $default) {
1615
                $selected = " selected = 'selected'";
1616
            }
1617
            $ret[] = '<option value=0' . $selected . '>---</option>';
1618
        }
1619
1620
        foreach ($array as $index => $label) {
1621
            $selected = '';
1622
            if ($index == $default) {
1623
                $selected = " selected = 'selected'";
1624
            }
1625
            $ret[] = "<option value=\"" . $index . "\"" . $selected . '>' . $label . '</option>';
1626
        }
1627
1628
        return implode("\n", $ret);
1629
    }
1630
1631
    /**
1632
     * Creates an html select
1633
     *
1634
     * @param string  $selectName Selector's name
1635
     * @param array   $array      Options
1636
     * @param mixed   $default    Default's value
1637
     * @param boolean $withNull   Do we include a null option ?
1638
     *
1639
     * @return string
1640
     * @since 2.3.2009.03.13
1641
     */
1642
    public static function htmlSelect($selectName, $array, $default, $withNull = true)
1643
    {
1644
        $ret = '';
1645
        $ret .= "<select name='" . $selectName . "' id='" . $selectName . "'>\n";
1646
        $ret .= self::htmlSelectOptions($array, $default, $withNull);
1647
        $ret .= "</select>\n";
1648
1649
        return $ret;
1650
    }
1651
1652
    /**
1653
     * Extrait l'id d'une chaine formatée sous la forme xxxx-99 (duquel on récupère 99)
1654
     *
1655
     * @note: utilisé par les attributs produits
1656
     *
1657
     * @param string $string    La chaine de travail
1658
     * @param string $separator Le séparateur
1659
     *
1660
     * @return string
0 ignored issues
show
Documentation introduced by
Should the return type not be string|integer?

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...
1661
     */
1662
    public static function getId($string, $separator = '_')
1663
    {
1664
        $pos = strrpos($string, $separator);
1665
        if ($pos === false) {
1666
            return $string;
1667
        } else {
1668
            return (int)substr($string, $pos + 1);
1669
        }
1670
    }
1671
1672
    /**
1673
     * Fonction "inverse" de getId (depuis xxxx-99 on récupère xxxx)
1674
     *
1675
     * @note: utilisé par les attributs produits
1676
     *
1677
     * @param string $string    La chaine de travail
1678
     * @param string $separator Le séparateur
1679
     *
1680
     * @return string
1681
     */
1682
    public static function getName($string, $separator = '_')
1683
    {
1684
        $pos = strrpos($string, $separator);
1685
        return false === $pos ? $string : substr($string, 0, $pos);
1686
    }
1687
1688
    /**
1689
     * Renvoie un montant nul si le montant est négatif
1690
     *
1691
     * @param float $amount
1692
     *
1693
     * @return float
0 ignored issues
show
Documentation introduced by
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...
1694
     */
1695
    public static function doNotAcceptNegativeAmounts(&$amount)
1696
    {
1697
        if ($amount < 0.00) {
1698
            $amount = 0.00;
1699
        }
1700
    }
1701
1702
    /**
1703
     * Returns a string from the request
1704
     *
1705
     * @param string $valueName    Name of the parameter you want to get
1706
     * @param mixed  $defaultValue Default value to return if the parameter is not set in the request
1707
     *
1708
     * @return mixed
1709
     */
1710
    public static function getFromRequest($valueName, $defaultValue = '')
0 ignored issues
show
Coding Style introduced by
getFromRequest uses the super-global variable $_REQUEST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
1711
    {
1712
        return isset($_REQUEST[$valueName]) ? $_REQUEST[$valueName] : $defaultValue;
1713
    }
1714
1715
    /**
1716
     * Verify that a mysql table exists
1717
     *
1718
     * @package       Oledrion
1719
     * @author        Instant Zero (http://xoops.instant-zero.com)
1720
     * @copyright (c) Instant Zero
1721
     * @param $tablename
1722
     * @return bool
1723
     */
1724
    public static function tableExists($tablename)
1725
    {
1726
        global $xoopsDB;
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...
1727
        $result = $xoopsDB->queryF("SHOW TABLES LIKE '$tablename'");
1728
1729
        return ($xoopsDB->getRowsNum($result) > 0);
1730
    }
1731
1732
    /**
1733
     * Verify that a field exists inside a mysql table
1734
     *
1735
     * @package       Oledrion
1736
     * @author        Instant Zero (http://xoops.instant-zero.com)
1737
     * @copyright (c) Instant Zero
1738
     * @param $fieldname
1739
     * @param $table
1740
     * @return bool
1741
     */
1742
    public static function fieldExists($fieldname, $table)
1743
    {
1744
        global $xoopsDB;
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...
1745
        $result = $xoopsDB->queryF("SHOW COLUMNS FROM $table LIKE '$fieldname'");
1746
1747
        return ($xoopsDB->getRowsNum($result) > 0);
1748
    }
1749
1750
    /**
1751
     * Retourne la définition d'un champ
1752
     *
1753
     * @param string $fieldname
1754
     * @param string $table
1755
     *
1756
     * @return array
1757
     */
1758
    public static function getFieldDefinition($fieldname, $table)
1759
    {
1760
        global $xoopsDB;
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...
1761
        $result = $xoopsDB->queryF("SHOW COLUMNS FROM $table LIKE '$fieldname'");
1762
        if ($result) {
1763
            return $xoopsDB->fetchArray($result);
1764
        }
1765
1766
        return '';
0 ignored issues
show
Bug Best Practice introduced by
The return type of return ''; (string) is incompatible with the return type documented by XoopstubeUtilities::getFieldDefinition of type array.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
1767
    }
1768
1769
    /**
1770
     * Add a field to a mysql table
1771
     *
1772
     * @package       Oledrion
1773
     * @author        Instant Zero (http://xoops.instant-zero.com)
1774
     * @copyright (c) Instant Zero
1775
     * @param $field
1776
     * @param $table
1777
     * @return mixed
1778
     */
1779
    public static function addField($field, $table)
1780
    {
1781
        global $xoopsDB;
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...
1782
        $result = $xoopsDB->queryF("ALTER TABLE $table ADD $field;");
1783
1784
        return $result;
1785
    }
1786
1787
    /**
1788
     * @param $info
1789
     *
1790
     * @return string
1791
     */
1792
    public static function packingHtmlSelect($info)
1793
    {
1794
        $ret = '';
1795
        $ret .= '<div class="oledrion_htmlform">';
1796
        $ret .= '<img class="oledrion_htmlimage" src="' . $info['packing_image_url'] . '" alt="' . $info['packing_title'] . '" />';
1797
        $ret .= '<h3>' . $info['packing_title'] . '</h3>';
1798 View Code Duplication
        if ($info['packing_price'] > 0) {
0 ignored issues
show
Duplication introduced by
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...
1799
            $ret .= '<p><span class="bold">' . _OLEDRION_PRICE . '</span> : ' . $info['packing_price_fordisplay'] . '</p>';
1800
        } else {
1801
            $ret .= '<p><span class="bold">' . _OLEDRION_PRICE . '</span> : ' . _OLEDRION_FREE . '</p>';
1802
        }
1803
        $ret .= '<p>' . $info['packing_description'] . '</p>';
1804
        $ret .= '</div>';
1805
1806
        return $ret;
1807
    }
1808
1809
    /**
1810
     * @param $info
1811
     *
1812
     * @return string
1813
     */
1814
    public static function deliveryHtmlSelect($info)
1815
    {
1816
        $ret = '';
1817
        $ret .= '<div class="oledrion_htmlform">';
1818
        $ret .= '<img class="oledrion_htmlimage" src="' . $info['delivery_image_url'] . '" alt="' . $info['delivery_title'] . '" />';
1819
        $ret .= '<h3>' . $info['delivery_title'] . '</h3>';
1820 View Code Duplication
        if ($info['delivery_price'] > 0) {
0 ignored issues
show
Duplication introduced by
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...
1821
            $ret .= '<p><span class="bold">' . _OLEDRION_PRICE . '</span> : ' . $info['delivery_price_fordisplay'] . '</p>';
1822
        } else {
1823
            $ret .= '<p><span class="bold">' . _OLEDRION_PRICE . '</span> : ' . _OLEDRION_FREE . '</p>';
1824
        }
1825
        $ret .= '<p><span class="bold">' . _OLEDRION_DELIVERY_TIME . '</span> : ' . $info['delivery_time'] . _OLEDRION_DELIVERY_DAY . '</p>';
1826
        $ret .= '<p>' . $info['delivery_description'] . '</p>';
1827
        $ret .= '</div>';
1828
1829
        return $ret;
1830
    }
1831
1832
    /**
1833
     * @param $info
1834
     *
1835
     * @return string
1836
     */
1837
    public static function paymentHtmlSelect($info)
1838
    {
1839
        $ret = '';
1840
        $ret .= '<div class="oledrion_htmlform">';
1841
        $ret .= '<img class="oledrion_htmlimage" src="' . $info['payment_image_url'] . '" alt="' . $info['payment_title'] . '" />';
1842
        $ret .= '<h3>' . $info['payment_title'] . '</h3>';
1843
        $ret .= '<p>' . $info['payment_description'] . '</p>';
1844
        $ret .= '</div>';
1845
1846
        return $ret;
1847
    }
1848
1849
    /**
1850
     * @return array
1851
     */
1852
    public static function getCountriesList()
1853
    {
1854
        require_once XOOPS_ROOT_PATH . '/class/xoopslists.php';
1855
1856
        return XoopsLists::getCountryList();
1857
    }
1858
1859
    //=================================================================================================================================
1860
1861
    /**
1862
     * @param       $name
1863
     * @param  bool $optional
1864
     * @return bool
0 ignored issues
show
Documentation introduced by
Should the return type not be object|false?

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

Loading history...
1865
     */
1866
    public static function xtubeGetHandler($name, $optional = false)
0 ignored issues
show
Coding Style introduced by
xtubeGetHandler uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
1867
    {
1868
        global $handlers, $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...
1869
1870
        $name = strtolower(trim($name));
1871
        if (!isset($handlers[$name])) {
1872
            if (file_exists($hnd_file = XOOPS_ROOT_PATH . '/modules/' . $xoopsModule->getVar('dirname') . '/class/class_' . $name . '.php')) {
1873
                require_once $hnd_file;
1874
            }
1875
            $class = 'xtube' . ucfirst($name) . 'Handler';
1876
            if (class_exists($class)) {
1877
                $handlers[$name] = new $class($GLOBALS['xoopsDB']);
1878
            }
1879
        }
1880
        if (!isset($handlers[$name]) && !$optional) {
1881
            trigger_error('<div>Class <span style="font-weight: bold;">' . $class . '</span> does not exist.</div><div>Handler Name: ' . $name, E_USER_ERROR) . '</div>';
0 ignored issues
show
Bug introduced by
The variable $class does not seem to be defined for all execution paths leading up to this point.

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

Let’s take a look at an example:

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

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

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

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

Available Fixes

  1. Check for existence of the variable explicitly:

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

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

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
1882
        }
1883
1884
        return isset($handlers[$name]) ? $handlers[$name] : false;
1885
    }
1886
1887
    /**
1888
     * @param int    $cid
1889
     * @param string $permType
1890
     * @param bool   $redirect
1891
     *
1892
     * @return bool
1893
     */
1894
    public static function xtubeCheckGroups($cid = 0, $permType = 'XTubeCatPerm', $redirect = false)
0 ignored issues
show
Coding Style introduced by
xtubeCheckGroups uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
1895
    {
1896
        global $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...
1897
1898
        $groups       = is_object($GLOBALS['xoopsUser']) ? $GLOBALS['xoopsUser']->getGroups() : XOOPS_GROUP_ANONYMOUS;
1899
        $gpermHandler = xoops_getHandler('groupperm');
1900
        if (!$gpermHandler->checkRight($permType, $cid, $groups, $xoopsModule->getVar('mid'))) {
1901
            if (false === $redirect) {
1902
                return false;
1903
            } else {
1904
                redirect_header('index.php', 3, _NOPERM);
1905
            }
1906
        }
1907
1908
        return true;
1909
    }
1910
1911
    /**
1912
     * @param int $lid
1913
     *
1914
     * @return bool
1915
     */
1916
    public static function xtubeGetVoteDetails($lid = 0)
0 ignored issues
show
Coding Style introduced by
xtubeGetVoteDetails uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
1917
    {
1918
        $sql = 'SELECT
1919
        COUNT(rating) AS rate,
1920
        MIN(rating) AS min_rate,
1921
        MAX(rating) AS max_rate,
1922
        AVG(rating) AS avg_rate,
1923
        COUNT(ratinguser) AS rating_user,
1924
        MAX(ratinguser) AS max_user,
1925
        MAX(title) AS max_title,
1926
        MIN(title) AS min_title,
1927
        sum(ratinguser = 0) AS null_ratinguser
1928
            FROM ' . $GLOBALS['xoopsDB']->prefix('xoopstube_votedata');
1929
        if ($lid > 0) {
1930
            $sql .= ' WHERE lid=' . $lid;
1931
        }
1932
        if (!$result = $GLOBALS['xoopsDB']->query($sql)) {
1933
            return false;
1934
        }
1935
        $ret = $GLOBALS['xoopsDB']->fetchArray($result);
1936
1937
        return $ret;
1938
    }
1939
1940
    /**
1941
     * @param int $sel_id
1942
     *
1943
     * @return array|bool
1944
     */
1945
    public static function xtubeCalculateVoteData($sel_id = 0)
0 ignored issues
show
Coding Style introduced by
xtubeCalculateVoteData uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
1946
    {
1947
        $ret                  = array();
1948
        $ret['useravgrating'] = 0;
1949
1950
        $sql = 'SELECT rating FROM ' . $GLOBALS['xoopsDB']->prefix('xoopstube_votedata');
1951
        if ($sel_id !== 0) {
1952
            $sql .= ' WHERE lid=' . $sel_id;
1953
        }
1954
        if (!$result = $GLOBALS['xoopsDB']->query($sql)) {
1955
            return false;
1956
        }
1957
        $ret['uservotes'] = $GLOBALS['xoopsDB']->getRowsNum($result);
1958
        while (false !== (list($rating) = $GLOBALS['xoopsDB']->fetchRow($result))) {
1959
            $ret['useravgrating'] += (int)$rating;
1960
        }
1961
        if ($ret['useravgrating'] > 0) {
1962
            $ret['useravgrating'] = number_format($ret['useravgrating'] / $ret['uservotes'], 2);
1963
        }
1964
1965
        return $ret;
1966
    }
1967
1968
    /**
1969
     * @param      $array
1970
     * @param null $name
1971
     * @param null $def
1972
     * @param bool $strict
1973
     * @param int  $lengthcheck
1974
     *
1975
     * @return array|int|null|string
1976
     */
1977
    public static function xtubeCleanRequestVars(&$array, $name = null, $def = null, $strict = false, $lengthcheck = 15)
1978
    {
1979
        // Sanitise $_request for further use.  This method gives more control and security.
1980
        // Method is more for functionality rather than beauty at the moment, will correct later.
1981
        unset($array['usercookie'], $array['PHPSESSID']);
1982
1983
        if (is_array($array) && null === $name) {
1984
            $globals = array();
1985
            foreach (array_keys($array) as $k) {
1986
                $value = strip_tags(trim($array[$k]));
1987
                if (strlen($value >= $lengthcheck)) {
1988
                    return null;
1989
                }
1990 View Code Duplication
                if (ctype_digit($value)) {
0 ignored issues
show
Duplication introduced by
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...
1991
                    $value = (int)$value;
1992
                } else {
1993
                    if (true === $strict) {
1994
                        $value = preg_replace('/\W/', '', trim($value));
1995
                    }
1996
                    $value = strtolower((string)$value);
1997
                }
1998
                $globals[$k] = $value;
1999
            }
2000
2001
            return $globals;
2002
        }
2003
        if (!isset($array[$name]) || !array_key_exists($name, $array)) {
2004
            return $def;
2005
        } else {
2006
            $value = strip_tags(trim($array[$name]));
2007
        }
2008 View Code Duplication
        if (ctype_digit($value)) {
0 ignored issues
show
Duplication introduced by
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...
2009
            $value = (int)$value;
2010
        } else {
2011
            if (true === $strict) {
2012
                $value = preg_replace('/\W/', '', trim($value));
2013
            }
2014
            $value = strtolower((string)$value);
2015
        }
2016
2017
        return $value;
2018
    }
2019
2020
    /**
2021
     * @param int $cid
2022
     *
2023
     * @return string
2024
     */
2025
    public static function xtubeRenderToolbar($cid = 0)
2026
    {
2027
        $toolbar = '[ ';
2028
        if (true === XoopstubeUtilities::xtubeCheckGroups($cid, 'XTubeSubPerm')) {
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
2029
            $toolbar .= '<a href="submit.php?cid=' . $cid . '">' . _MD_XOOPSTUBE_SUBMITVIDEO . '</a> | ';
2030
        }
2031
        $toolbar .= '<a href="newlist.php?newvideoshowdays=7">' . _MD_XOOPSTUBE_LATESTLIST . '</a> | <a href="topten.php?list=hit">' . _MD_XOOPSTUBE_POPULARITY
2032
                    . '</a> | <a href="topten.php?list=rate">' . _MD_XOOPSTUBE_TOPRATED . '</a> ]';
2033
2034
        return $toolbar;
2035
    }
2036
2037
    /**
2038
     *
2039
     */
2040
    public static function xtubeGetServerStatistics()
2041
    {
2042
        global $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...
2043
        echo '<fieldset style="border: #E8E8E8 1px solid;">
2044
          <legend style="display: inline; font-weight: bold; color: #0A3760;">' . _AM_XOOPSTUBE_VIDEO_IMAGEINFO . '</legend>
2045
          <div style="padding: 8px;">
2046
            <img src="' . XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname') . '/assets/images/icon/server.png" alt="" style="float: left; padding-right: 10px;" />
2047
          <div>' . _AM_XOOPSTUBE_VIDEO_SPHPINI . '</div>';
2048
2049
        //    $safemode        = ini_get('safe_mode') ? _AM_XOOPSTUBE_VIDEO_ON . _AM_XOOPSTUBE_VIDEO_SAFEMODEPROBLEMS : _AM_XOOPSTUBE_VIDEO_OFF;
2050
        //    $registerglobals = (ini_get('register_globals') === '') ? _AM_XOOPSTUBE_VIDEO_OFF : _AM_XOOPSTUBE_VIDEO_ON;
0 ignored issues
show
Unused Code Comprehensibility introduced by
42% 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...
2051
        $videos = ini_get('file_uploads') ? _AM_XOOPSTUBE_VIDEO_ON : _AM_XOOPSTUBE_VIDEO_OFF;
2052
2053
        $gdlib = function_exists('gd_info') ? _AM_XOOPSTUBE_VIDEO_GDON : _AM_XOOPSTUBE_VIDEO_GDOFF;
2054
        echo '<li>' . _AM_XOOPSTUBE_VIDEO_GDLIBSTATUS . $gdlib;
2055
        if (function_exists('gd_info')) {
2056
            if (true === $gdlib = gd_info()) {
2057
                echo '<li>' . _AM_XOOPSTUBE_VIDEO_GDLIBVERSION . '<b>' . $gdlib['GD Version'] . '</b>';
2058
            }
2059
        }
2060
        echo '<br><br>';
2061
        //    echo '<li>' . _AM_XOOPSTUBE_VIDEO_SAFEMODESTATUS . $safemode;
2062
        //    echo '<li>' . _AM_XOOPSTUBE_VIDEO_REGISTERGLOBALS . $registerglobals;
2063
        echo '<li>' . _AM_XOOPSTUBE_VIDEO_SERVERUPLOADSTATUS . $videos;
2064
        echo '</div>';
2065
        echo '</fieldset>';
2066
    }
2067
2068
    // xtubeDisplayIcons()
2069
    //
2070
    // @param  $time
2071
    // @param integer $status
2072
    // @param integer $counter
2073
    // @return
2074
    /**
2075
     * @param     $time
2076
     * @param int $status
2077
     * @param int $counter
2078
     *
2079
     * @return string
2080
     */
2081
    public static function xtubeDisplayIcons($time, $status = 0, $counter = 0)
0 ignored issues
show
Coding Style introduced by
xtubeDisplayIcons uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
2082
    {
2083
        global $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...
2084
2085
        $new = '';
2086
        $pop = '';
2087
2088
        $newdate = (time() - (86400 * (int)$GLOBALS['xoopsModuleConfig']['daysnew']));
2089
        $popdate = (time() - (86400 * (int)$GLOBALS['xoopsModuleConfig']['daysupdated']));
2090
2091
        if (3 != $GLOBALS['xoopsModuleConfig']['displayicons']) {
2092
            if ($newdate < $time) {
2093
                if ((int)$status > 1) {
2094 View Code Duplication
                    if (1 == $GLOBALS['xoopsModuleConfig']['displayicons']) {
0 ignored issues
show
Duplication introduced by
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...
2095
                        $new = '&nbsp;<img src="' . XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname') . '/assets/images/icon/updated.gif" alt="" style="vertical-align: middle;" />';
2096
                    }
2097
                    if (2 == $GLOBALS['xoopsModuleConfig']['displayicons']) {
2098
                        $new = '<em>' . _MD_XOOPSTUBE_UPDATED . '</em>';
2099
                    }
2100
                } else {
2101 View Code Duplication
                    if (1 == $GLOBALS['xoopsModuleConfig']['displayicons']) {
0 ignored issues
show
Duplication introduced by
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...
2102
                        $new = '&nbsp;<img src="' . XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname') . '/assets/images/icon/new.gif" alt="" style="vertical-align: middle;" />';
2103
                    }
2104
                    if (2 == $GLOBALS['xoopsModuleConfig']['displayicons']) {
2105
                        $new = '<em>' . _MD_XOOPSTUBE_NEW . '</em>';
2106
                    }
2107
                }
2108
            }
2109
            if ($popdate > $time) {
2110
                if ($counter >= $GLOBALS['xoopsModuleConfig']['popular']) {
2111 View Code Duplication
                    if (1 == $GLOBALS['xoopsModuleConfig']['displayicons']) {
0 ignored issues
show
Duplication introduced by
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...
2112
                        $pop = '&nbsp;<img src="' . XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname') . '/assets/images/icon/popular.png" alt="" style="vertical-align: middle;" />';
2113
                    }
2114
                    if (2 == $GLOBALS['xoopsModuleConfig']['displayicons']) {
2115
                        $pop = '<em>' . _MD_XOOPSTUBE_POPULAR . '!</em>';
2116
                    }
2117
                }
2118
            }
2119
        }
2120
        $icons = $new . ' ' . $pop;
2121
2122
        return $icons;
2123
    }
2124
2125
    // Reusable Link Sorting Functions
2126
    // xtubeConvertOrderByIn()
2127
    // @param  $orderby
2128
    // @return
2129
    /**
2130
     * @param $orderby
2131
     *
2132
     * @return string
2133
     */
2134 View Code Duplication
    public static function xtubeConvertOrderByIn($orderby)
0 ignored issues
show
Duplication introduced by
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...
2135
    {
2136
        switch (trim($orderby)) {
2137
            case 'titleA':
2138
                $orderby = 'title ASC';
2139
                break;
2140
            case 'dateA':
2141
                $orderby = 'published ASC';
2142
                break;
2143
            case 'hitsA':
2144
                $orderby = 'hits ASC';
2145
                break;
2146
            case 'ratingA':
2147
                $orderby = 'rating ASC';
2148
                break;
2149
            case 'countryA':
2150
                $orderby = 'country ASC';
2151
                break;
2152
            case 'titleD':
2153
                $orderby = 'title DESC';
2154
                break;
2155
            case 'hitsD':
2156
                $orderby = 'hits DESC';
2157
                break;
2158
            case 'ratingD':
2159
                $orderby = 'rating DESC';
2160
                break;
2161
            case'dateD':
0 ignored issues
show
Coding Style introduced by
As per coding-style, case should be followed by a single space.

As per the PSR-2 coding standard, there must be a space after the case keyword, instead of the test immediately following it.

switch (true) {
    case!isset($a):  //wrong
        doSomething();
        break;
    case !isset($b):  //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
2162
                $orderby = 'published DESC';
2163
                break;
2164
            case 'countryD':
2165
                $orderby = 'country DESC';
2166
                break;
2167
        }
2168
2169
        return $orderby;
2170
    }
2171
2172
    /**
2173
     * @param $orderby
2174
     *
2175
     * @return string
2176
     */
2177
    public static function xtubeConvertOrderByTrans($orderby)
2178
    {
2179
        switch ($orderby) {
2180
            case 'hits ASC':
2181
                $orderByTrans = _MD_XOOPSTUBE_POPULARITYLTOM;
2182
                break;
2183
            case 'hits DESC':
2184
                $orderByTrans = _MD_XOOPSTUBE_POPULARITYMTOL;
2185
                break;
2186
            case 'title ASC':
2187
                $orderByTrans = _MD_XOOPSTUBE_TITLEATOZ;
2188
                break;
2189
            case 'title DESC':
2190
                $orderByTrans = _MD_XOOPSTUBE_TITLEZTOA;
2191
                break;
2192
            case 'published ASC':
2193
                $orderByTrans = _MD_XOOPSTUBE_DATEOLD;
2194
                break;
2195
            case 'published DESC':
2196
                $orderByTrans = _MD_XOOPSTUBE_DATENEW;
2197
                break;
2198
            case 'rating ASC':
2199
                $orderByTrans = _MD_XOOPSTUBE_RATINGLTOH;
2200
                break;
2201
            case 'rating DESC':
2202
                $orderByTrans = _MD_XOOPSTUBE_RATINGHTOL;
2203
                break;
2204
            case'country ASC':
0 ignored issues
show
Coding Style introduced by
As per coding-style, case should be followed by a single space.

As per the PSR-2 coding standard, there must be a space after the case keyword, instead of the test immediately following it.

switch (true) {
    case!isset($a):  //wrong
        doSomething();
        break;
    case !isset($b):  //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
2205
                $orderByTrans = _MD_XOOPSTUBE_COUNTRYLTOH;
2206
                break;
2207
            case 'country DESC':
2208
                $orderByTrans = _MD_XOOPSTUBE_COUNTRYHTOL;
2209
                break;
2210
        }
2211
2212
        return $orderByTrans;
0 ignored issues
show
Bug introduced by
The variable $orderByTrans 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...
2213
    }
2214
2215
    /**
2216
     * @param $orderby
2217
     *
2218
     * @return string
2219
     */
2220 View Code Duplication
    public static function xtubeConvertOrderByOut($orderby)
0 ignored issues
show
Duplication introduced by
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...
2221
    {
2222
        switch ($orderby) {
2223
            case 'title ASC':
2224
                $orderby = 'titleA';
2225
                break;
2226
            case 'published ASC':
2227
                $orderby = 'dateA';
2228
                break;
2229
            case 'hits ASC':
2230
                $orderby = 'hitsA';
2231
                break;
2232
            case 'rating ASC':
2233
                $orderby = 'ratingA';
2234
                break;
2235
            case 'country ASC':
2236
                $orderby = 'countryA';
2237
                break;
2238
            case 'title DESC':
2239
                $orderby = 'titleD';
2240
                break;
2241
            case 'published DESC':
2242
                $orderby = 'dateD';
2243
                break;
2244
            case 'hits DESC':
2245
                $orderby = 'hitsD';
2246
                break;
2247
            case 'rating DESC':
2248
                $orderby = 'ratingD';
2249
                break;
2250
            case 'country DESC':
2251
                $orderby = 'countryD';
2252
                break;
2253
        }
2254
2255
        return $orderby;
2256
    }
2257
2258
    // updaterating()
2259
    // @param  $sel_id
2260
    // @return updates rating data in itemtable for a given item
2261
    /**
2262
     * @param $sel_id
2263
     */
2264
    public static function xtubeUpdateRating($sel_id)
0 ignored issues
show
Coding Style introduced by
xtubeUpdateRating uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
2265
    {
2266
        $query       = 'SELECT rating FROM ' . $GLOBALS['xoopsDB']->prefix('xoopstube_votedata') . ' WHERE lid=' . $sel_id;
2267
        $voteresult  = $GLOBALS['xoopsDB']->query($query);
2268
        $votesDB     = $GLOBALS['xoopsDB']->getRowsNum($voteresult);
2269
        $totalrating = 0;
2270
        while (false !== (list($rating) = $GLOBALS['xoopsDB']->fetchRow($voteresult))) {
2271
            $totalrating += $rating;
2272
        }
2273
        $finalrating = $totalrating / $votesDB;
2274
        $finalrating = number_format($finalrating, 4);
2275
        $sql         = sprintf('UPDATE %s SET rating = %u, votes = %u WHERE lid = %u', $GLOBALS['xoopsDB']->prefix('xoopstube_videos'), $finalrating, $votesDB, $sel_id);
2276
        $GLOBALS['xoopsDB']->query($sql);
2277
    }
2278
2279
    // totalcategory()
2280
    // @param integer $pid
2281
    // @return
2282
    /**
2283
     * @param int $pid
2284
     *
2285
     * @return int
2286
     */
2287
    public static function xtubeGetTotalCategoryCount($pid = 0)
0 ignored issues
show
Coding Style introduced by
xtubeGetTotalCategoryCount uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
2288
    {
2289
        $sql = 'SELECT cid FROM ' . $GLOBALS['xoopsDB']->prefix('xoopstube_cat');
2290
        if ($pid > 0) {
2291
            $sql .= ' WHERE pid = 0';
2292
        }
2293
        $result     = $GLOBALS['xoopsDB']->query($sql);
2294
        $catlisting = 0;
2295
        while (false !== (list($cid) = $GLOBALS['xoopsDB']->fetchRow($result))) {
2296
            if (XoopstubeUtilities::xtubeCheckGroups($cid)) {
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
2297
                ++$catlisting;
2298
            }
2299
        }
2300
2301
        return $catlisting;
2302
    }
2303
2304
    // xtubeGetTotalItems()
2305
    // @param integer $sel_id
2306
    // @param integer $get_child
2307
    // @param integer $return_sql
2308
    // @return
2309
    /**
2310
     * @param int $sel_id
2311
     * @param int $get_child
2312
     * @param int $return_sql
2313
     *
2314
     * @return string
0 ignored issues
show
Documentation introduced by
Should the return type not be string|array?

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...
2315
     */
2316
    public static function xtubeGetTotalItems($sel_id = 0, $get_child = 0, $return_sql = 0)
0 ignored issues
show
Coding Style introduced by
xtubeGetTotalItems uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
2317
    {
2318
        global $mytree, $_check_array;
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...
2319
2320
        if ($sel_id > 0) {
2321
            $sql = 'SELECT a.lid, a.cid, a.published FROM ' . $GLOBALS['xoopsDB']->prefix('xoopstube_videos') . ' a LEFT JOIN ' . $GLOBALS['xoopsDB']->prefix('xoopstube_altcat') . ' b'
2322
                   . ' ON b.lid=a.lid' . ' WHERE a.published > 0 AND a.published <= ' . time() . ' AND (a.expired = 0 OR a.expired > ' . time() . ') AND offline = 0 ' . ' AND (b.cid=a.cid OR (a.cid='
2323
                   . $sel_id . ' OR b.cid=' . $sel_id . '))' . ' GROUP BY a.lid, a.cid, a.published';
2324
        } else {
2325
            $sql = 'SELECT lid, cid, published FROM ' . $GLOBALS['xoopsDB']->prefix('xoopstube_videos') . ' WHERE offline = 0 AND published > 0 AND published <= ' . time()
2326
                   . ' AND (expired = 0 OR expired > ' . time() . ')';
2327
        }
2328
        if (1 == $return_sql) {
2329
            return $sql;
2330
        }
2331
2332
        $count          = 0;
2333
        $published_date = 0;
2334
2335
        $arr    = array();
0 ignored issues
show
Unused Code introduced by
$arr 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...
2336
        $result = $GLOBALS['xoopsDB']->query($sql);
2337
        while (false !== (list($lid, $cid, $published) = $GLOBALS['xoopsDB']->fetchRow($result))) {
2338
            if (true === XoopstubeUtilities::xtubeCheckGroups()) {
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
2339
                ++$count;
2340
                $published_date = ($published > $published_date) ? $published : $published_date;
2341
            }
2342
        }
2343
2344
        $child_count = 0;
2345
        if (1 == $get_child) {
2346
            $arr  = $mytree->getAllChildId($sel_id);
2347
            $size = count($arr);
0 ignored issues
show
Unused Code introduced by
$size 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...
2348
            for ($i = 0, $iMax = count($arr); $i < $iMax; ++$i) {
2349
                $query2 = 'SELECT a.lid, a.published, a.cid FROM ' . $GLOBALS['xoopsDB']->prefix('xoopstube_videos') . ' a LEFT JOIN ' . $GLOBALS['xoopsDB']->prefix('xoopstube_altcat') . ' b'
2350
                          . ' ON b.lid = a.lid' . ' WHERE a.published > 0 AND a.published <= ' . time() . ' AND (a.expired = 0 OR a.expired > ' . time() . ') AND offline = 0'
2351
                          . ' AND (b.cid=a.cid OR (a.cid=' . $arr[$i] . ' OR b.cid=' . $arr[$i] . ')) GROUP BY a.lid, a.published, a.cid';
2352
2353
                $result2 = $GLOBALS['xoopsDB']->query($query2);
2354
                while (false !== (list($lid, $published) = $GLOBALS['xoopsDB']->fetchRow($result2))) {
2355
                    if (0 == $published) {
2356
                        continue;
2357
                    }
2358
                    $published_date = ($published > $published_date) ? $published : $published_date;
2359
                    ++$child_count;
2360
                }
2361
            }
2362
        }
2363
        $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...
2364
        $info['published'] = $published_date;
2365
2366
        return $info;
2367
    }
2368
2369
    /**
2370
     * @param string $indeximage
2371
     * @param string $indexheading
2372
     *
2373
     * @return string
2374
     */
2375
    public static function xtubeRenderImageHeader($indeximage = '', $indexheading = '')
0 ignored issues
show
Coding Style introduced by
xtubeRenderImageHeader uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
2376
    {
2377 View Code Duplication
        if ('' === $indeximage) {
0 ignored issues
show
Duplication introduced by
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...
2378
            $result = $GLOBALS['xoopsDB']->query('SELECT indeximage, indexheading FROM ' . $GLOBALS['xoopsDB']->prefix('xoopstube_indexpage'));
2379
            list($indeximage, $indexheading) = $GLOBALS['xoopsDB']->fetchrow($result);
2380
        }
2381
2382
        $image = '';
2383
        if (!empty($indeximage)) {
2384
            $image = XoopstubeUtilities::xtubeDisplayImage($indeximage, 'index.php', $GLOBALS['xoopsModuleConfig']['mainimagedir'], $indexheading);
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
2385
        }
2386
2387
        return $image;
2388
    }
2389
2390
    /**
2391
     * @param string $image
2392
     * @param string $path
2393
     * @param string $imgsource
2394
     * @param string $alttext
2395
     *
2396
     * @return string
2397
     */
2398
    public static function xtubeDisplayImage($image = '', $path = '', $imgsource = '', $alttext = '')
0 ignored issues
show
Coding Style introduced by
xtubeDisplayImage uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
2399
    {
2400
        global $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...
2401
2402
        $showimage = '';
2403
        // Check to see if link is given
2404
        if ($path) {
2405
            $showimage = '<a href="' . $path . '">';
2406
        }
2407
        // checks to see if the file is valid else displays default blank image
2408
        if (!is_dir(XOOPS_ROOT_PATH . "/{$imgsource}/{$image}") && file_exists(XOOPS_ROOT_PATH . "/{$imgsource}/{$image}")) {
2409
            $showimage .= "<img src='" . XOOPS_URL . "/{$imgsource}/{$image}' border='0' title='" . $alttext . "' alt='" . $alttext . "' /></a>";
2410
        } else {
2411
            if ($GLOBALS['xoopsUser'] && $GLOBALS['xoopsUser']->isAdmin($xoopsModule->getVar('mid'))) {
2412
                $showimage .= '<img src="' . XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname') . '/assets/images/brokenimg.png" alt="' . _MD_XOOPSTUBE_ISADMINNOTICE . '" /></a>';
2413
            } else {
2414
                $showimage .= '<img src="' . XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname') . '/assets/images/blank.png" alt="' . $alttext . '" /></a>';
2415
            }
2416
        }
2417
        clearstatcache();
2418
2419
        return $showimage;
2420
    }
2421
2422
    /**
2423
     * @param $published
2424
     *
2425
     * @return mixed
2426
     */
2427
    public static function xtubeIsNewImage($published)
2428
    {
2429
        global $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...
2430
2431
        $oneday    = (time() - (86400 * 1));
2432
        $threedays = (time() - (86400 * 3));
2433
        $week      = (time() - (86400 * 7));
2434
2435
        $path = 'modules/' . $xoopsModule->getVar('dirname') . '/assets/images/icon';
2436
2437
        if ($published > 0 && $published < $week) {
2438
            $indicator['image']   = "$path/linkload4.png";
0 ignored issues
show
Coding Style Comprehensibility introduced by
$indicator was never initialized. Although not strictly required by PHP, it is generally a good practice to add $indicator = 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...
2439
            $indicator['alttext'] = _MD_XOOPSTUBE_NEWLAST;
2440
        } elseif ($published >= $week && $published < $threedays) {
2441
            $indicator['image']   = "$path/linkload3.png";
0 ignored issues
show
Coding Style Comprehensibility introduced by
$indicator was never initialized. Although not strictly required by PHP, it is generally a good practice to add $indicator = 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...
2442
            $indicator['alttext'] = _MD_XOOPSTUBE_NEWTHIS;
2443
        } elseif ($published >= $threedays && $published < $oneday) {
2444
            $indicator['image']   = "$path/linkload2.png";
0 ignored issues
show
Coding Style Comprehensibility introduced by
$indicator was never initialized. Although not strictly required by PHP, it is generally a good practice to add $indicator = 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...
2445
            $indicator['alttext'] = _MD_XOOPSTUBE_THREE;
2446
        } elseif ($published >= $oneday) {
2447
            $indicator['image']   = "$path/linkload1.png";
0 ignored issues
show
Coding Style Comprehensibility introduced by
$indicator was never initialized. Although not strictly required by PHP, it is generally a good practice to add $indicator = 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...
2448
            $indicator['alttext'] = _MD_XOOPSTUBE_TODAY;
2449
        } else {
2450
            $indicator['image']   = "$path/linkload.png";
0 ignored issues
show
Coding Style Comprehensibility introduced by
$indicator was never initialized. Although not strictly required by PHP, it is generally a good practice to add $indicator = 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...
2451
            $indicator['alttext'] = _MD_XOOPSTUBE_NO_FILES;
2452
        }
2453
2454
        return $indicator;
2455
    }
2456
2457
    /**
2458
     * @param $haystack
2459
     * @param $needle
2460
     *
2461
     * @return string
2462
     */
2463
    public static function xtubeFindStringChar($haystack, $needle)
2464
    {
2465
        return substr($haystack, 0, strpos($haystack, $needle) + 1);
2466
    }
2467
2468
    /**
2469
     * @param string $header
2470
     * @param string $menu
2471
     * @param string $extra
2472
     * @param int    $scount
2473
     *
2474
     * @return bool|null
2475
     */
2476
    public static function xtubeRenderAdminMenu($header = '', $menu = '', $extra = '', $scount = 4)
0 ignored issues
show
Coding Style introduced by
xtubeRenderAdminMenu uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
2477
    {
2478
        global $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...
2479
2480
        $_named_vidid = xoops_getenv('PHP_SELF');
2481
        if ($_named_vidid) {
2482
            $thispage = basename($_named_vidid);
2483
        }
2484
2485
        //    $op = (isset($_GET['op'])) ? $op = '?op=' . $_GET['op'] : '';
0 ignored issues
show
Unused Code Comprehensibility introduced by
59% 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...
2486
        $op = XoopsRequest::getCmd('op', '', 'GET');
2487
        echo '<h4 style="color: #2F5376;">' . _AM_XOOPSTUBE_MODULE_NAME . '</h4>';
2488
        echo '
2489
        <div style="font-size: 10px; text-align: left; color: #2F5376; padding: 2px 6px; line-height: 18px;">
2490
        <span style="margin: 1px; padding: 4px; border: #E8E8E8 1px solid;">
2491
            <a href="../admin/index.php">' . _AM_XOOPSTUBE_BINDEX . '</a>
2492
        </span>
2493
        <span  style="margin: 1px; padding: 4px; border: #E8E8E8 1px solid;">
2494
            <a href="../index.php">' . _AM_XOOPSTUBE_GOMODULE . '</a>
2495
        </span>
2496
        <span  style="margin: 1px; padding: 4px; border: #E8E8E8 1px solid;">
2497
            <a href="../../system/admin.php?fct=preferences&op=showmod&mod=' . $xoopsModule->getVar('mid') . '">' . _AM_XOOPSTUBE_PREFS . '</a>
2498
        </span>
2499
        <span  style="margin: 1px; padding: 4px; border: #E8E8E8 1px solid;">
2500
            <a href="../admin/permissions.php">' . _AM_XOOPSTUBE_BPERMISSIONS . '</a>
2501
        </span>
2502
        <span  style="margin: 1px; padding: 4px; border: #E8E8E8 1px solid;">
2503
            <a href="../admin/myblocksadmin.php">' . _AM_XOOPSTUBE_BLOCKADMIN . '</a>
2504
        </span>
2505
        <span  style="margin: 1px; padding: 4px; border: #E8E8E8 1px solid;">
2506
            <a href="../../system/admin.php?fct=modulesadmin&op=update&module=' . $xoopsModule->getVar('dirname') . '">' . _AM_XOOPSTUBE_BUPDATE . '</a>
2507
        </span>
2508
        <span  style="margin: 1px; padding: 4px; border: #E8E8E8 1px solid;">
2509
            <a href="../admin/about.php">' . _AM_XOOPSTUBE_ABOUT . '</a>
2510
        </span>
2511
        </div><br>';
2512
2513
        if (empty($menu)) {
2514
            // You can change this part to suit your own module. Defining this here will save you form having to do this each time.
2515
            $menu = array(
2516
                _AM_XOOPSTUBE_MVIDEOS   => 'main.php?op=edit',
2517
                _AM_XOOPSTUBE_MCATEGORY => 'category.php',
2518
                _AM_XOOPSTUBE_INDEXPAGE => 'indexpage.php',
2519
                //            _AM_XOOPSTUBE_MXOOPSTUBE     => 'main.php?op=edit',
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% 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...
2520
                _AM_XOOPSTUBE_MUPLOADS  => 'upload.php',
2521
                _AM_XOOPSTUBE_VUPLOADS  => 'vupload.php',
2522
                _AM_XOOPSTUBE_MVOTEDATA => 'votedata.php',
2523
                _AM_XOOPSTUBE_MCOMMENTS => '../../system/admin.php?module=' . $xoopsModule->getVar('mid') . '&status=0&limit=100&fct=comments&selsubmit=Go'
2524
            );
2525
        }
2526
2527
        if (!is_array($menu)) {
2528
            echo '<table width="100%" cellpadding="2" cellspacing="1" class="outer">';
2529
            echo '<tr><td class="even" align="center"><b>' . _AM_XOOPSTUBE_NOMENUITEMS . '</b></td></tr></table><br>';
2530
2531
            return false;
2532
        }
2533
2534
        $oddnum = array(
2535
            1  => '1',
2536
            3  => '3',
2537
            5  => '5',
2538
            7  => '7',
2539
            9  => '9',
2540
            11 => '11',
2541
            13 => '13'
2542
        );
2543
        // number of rows per menu
2544
        $menurows = count($menu) / $scount;
2545
        // total amount of rows to complete menu
2546
        $menurow = ceil($menurows) * $scount;
2547
        // actual number of menuitems per row
2548
        $rowcount = $menurow / ceil($menurows);
0 ignored issues
show
Unused Code introduced by
$rowcount 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...
2549
        $count    = 0;
2550
        for ($i = count($menu); $i < $menurow; ++$i) {
2551
            $tempArray = array(1 => null);
2552
            $menu      = array_merge($menu, $tempArray);
2553
            ++$count;
2554
        }
2555
2556
        // Sets up the width of each menu cell
2557
        $width = 100 / $scount;
2558
        $width = ceil($width);
2559
2560
        $menucount = 0;
2561
        $count     = 0;
2562
        // Menu table output
2563
        echo '<table width="100%" cellpadding="2" cellspacing="1" class="outer" border="1"><tr>';
2564
        // Check to see if $menu is and array
2565
        if (is_array($menu)) {
2566
            $classcounts = 0;
2567
            $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...
2568
2569
            for ($i = 1; $i < $menurow; ++$i) {
2570
                ++$classcounts;
2571
                if ($classcounts >= $scount) {
2572
                    if ('odd' === $classcol[$i - 1]) {
2573
                        $classcol[$i] = ('odd' === $classcol[$i - 1] && in_array($classcounts, $oddnum)) ? 'even' : 'odd';
2574
                    } else {
2575
                        $classcol[$i] = ('even' === $classcol[$i - 1] && in_array($classcounts, $oddnum)) ? 'odd' : 'even';
2576
                    }
2577
                    $classcounts = 0;
2578
                } else {
2579
                    $classcol[$i] = ('even' === $classcol[$i - 1]) ? 'odd' : 'even';
2580
                }
2581
            }
2582
            unset($classcounts);
2583
2584
            foreach ($menu as $menutitle => $menuvideo) {
2585
                if ($thispage . $op == $menuvideo) {
0 ignored issues
show
Bug introduced by
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...
2586
                    $classcol[$count] = 'outer';
2587
                }
2588
                echo '<td class="' . $classcol[$count] . '" style="padding: 4px; text-align: center;" valign="middle" width="' . $width . '%">';
2589
                if (is_string($menuvideo)) {
2590
                    echo '<a href="' . $menuvideo . '"><span style="font-size: small;">' . $menutitle . '</span></a></td>';
2591
                } else {
2592
                    echo '&nbsp;</td>';
2593
                }
2594
                ++$menucount;
2595
                ++$count;
2596
                // Break menu cells to start a new row if $count > $scount
2597
                if ($menucount >= $scount) {
2598
                    echo '</tr>';
2599
                    $menucount = 0;
2600
                }
2601
            }
2602
            echo '</table><br>';
2603
            unset($count, $menucount);
2604
        }
2605
        // ###### Output warn messages for security ######
2606
        if (is_dir(XOOPS_ROOT_PATH . '/modules/' . $xoopsModule->getVar('dirname') . '/update/')) {
2607
            xoops_error(sprintf(_AM_XOOPSTUBE_WARNINSTALL1, XOOPS_ROOT_PATH . '/modules/' . $xoopsModule->getVar('dirname') . '/update/'));
2608
            echo '<br>';
2609
        }
2610
2611
        $_file = XOOPS_ROOT_PATH . '/modules/' . $xoopsModule->getVar('dirname') . '/update.php';
2612
        if (file_exists($_file)) {
2613
            xoops_error(sprintf(_AM_XOOPSTUBE_WARNINSTALL2, XOOPS_ROOT_PATH . '/modules/' . $xoopsModule->getVar('dirname') . '/update.php'));
2614
            echo '<br>';
2615
        }
2616
2617
        $path1 = XOOPS_ROOT_PATH . '/' . $GLOBALS['xoopsModuleConfig']['mainimagedir'];
2618
        if (!is_dir($path1)) {
2619
            xoops_error(sprintf(_AM_XOOPSTUBE_WARNINSTALL3, $path1));
2620
            echo '<br>';
2621
        }
2622
        if (!is_writable($path1)) {
2623
            xoops_error(sprintf(_AM_XOOPSTUBE_WARNINSTALL4, $path1));
2624
            echo '<br>';
2625
        }
2626
2627
        $path1_t = XOOPS_ROOT_PATH . '/' . $GLOBALS['xoopsModuleConfig']['mainimagedir'] . '/thumbs';
2628
        if (!is_dir($path1_t)) {
2629
            xoops_error(sprintf(_AM_XOOPSTUBE_WARNINSTALL3, $path1_t));
2630
            echo '<br>';
2631
        }
2632
        if (!is_writable($path1_t)) {
2633
            xoops_error(sprintf(_AM_XOOPSTUBE_WARNINSTALL4, $path1_t));
2634
            echo '<br>';
2635
        }
2636
2637
        $path2 = XOOPS_ROOT_PATH . '/' . $GLOBALS['xoopsModuleConfig']['videoimgdir'];
2638
        if (!is_dir($path2)) {
2639
            xoops_error(sprintf(_AM_XOOPSTUBE_WARNINSTALL3, $path2));
2640
            echo '<br>';
2641
        }
2642
        if (!is_writable($path2)) {
2643
            xoops_error(sprintf(_AM_XOOPSTUBE_WARNINSTALL4, $path2));
2644
            echo '<br>';
2645
        }
2646
2647
        //    $path2_t = XOOPS_ROOT_PATH . '/' . $GLOBALS['xoopsModuleConfig']['videoimgdir'] . '/thumbs';
0 ignored issues
show
Unused Code Comprehensibility introduced by
44% 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...
2648
        //    if ( !is_dir( $path2_t ) || !is_writable( $path2_t ) ) {
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...
2649
        //        xoops_error( sprintf( _AM_XOOPSTUBE_WARNINSTALL3, $path2_t ) );
0 ignored issues
show
Unused Code Comprehensibility introduced by
44% 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...
2650
        //        echo '<br>';
2651
        //    }
2652
2653
        $path3 = XOOPS_ROOT_PATH . '/' . $GLOBALS['xoopsModuleConfig']['catimage'];
2654
        if (!is_dir($path3)) {
2655
            xoops_error(sprintf(_AM_XOOPSTUBE_WARNINSTALL3, $path3));
2656
            echo '<br>';
2657
        }
2658
        if (!is_writable($path3)) {
2659
            xoops_error(sprintf(_AM_XOOPSTUBE_WARNINSTALL4, $path3));
2660
            echo '<br>';
2661
        }
2662
2663
        $path3_t = XOOPS_ROOT_PATH . '/' . $GLOBALS['xoopsModuleConfig']['catimage'] . '/thumbs';
2664
        if (!is_dir($path3_t)) {
2665
            xoops_error(sprintf(_AM_XOOPSTUBE_WARNINSTALL3, $path3_t));
2666
            echo '<br>';
2667
        }
2668
        if (!is_writable($path3_t)) {
2669
            xoops_error(sprintf(_AM_XOOPSTUBE_WARNINSTALL4, $path3_t));
2670
            echo '<br>';
2671
        }
2672
2673
        $path4 = XOOPS_ROOT_PATH . '/' . $GLOBALS['xoopsModuleConfig']['videodir'];
2674
        if (!is_dir($path4)) {
2675
            xoops_error(sprintf(_AM_XOOPSTUBE_WARNINSTALL3, $path4));
2676
            echo '<br>';
2677
        }
2678
        if (!is_writable($path4)) {
2679
            xoops_error(sprintf(_AM_XOOPSTUBE_WARNINSTALL4, $path4));
2680
            echo '<br>';
2681
        }
2682
2683
        echo '<h4 style="color: #2F5376;">' . $header . '</h4>';
2684
        if ($extra) {
2685
            echo '<div>' . $extra . '</div>';
2686
        }
2687
2688
        return null;
2689
    }
2690
2691
    /**
2692
     * @param $selected
2693
     * @param $dirarray
2694
     * @param $namearray
2695
     */
2696 View Code Duplication
    public static function xtubeGetDirSelectOption($selected, $dirarray, $namearray)
0 ignored issues
show
Unused Code introduced by
The parameter $dirarray is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Duplication introduced by
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...
2697
    {
2698
        echo "<select size='1' name='workd' onchange='location.href=\"upload.php?rootpath=\"+this.options[this.selectedIndex].value'>";
2699
        echo "<option value=''>--------------------------------------</option>";
2700
        foreach ($namearray as $namearray => $workd) {
2701
            if ($workd == $selected) {
2702
                $opt_selected = 'selected';
0 ignored issues
show
Unused Code introduced by
$opt_selected 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...
2703
            } else {
2704
                $opt_selected = '';
0 ignored issues
show
Unused Code introduced by
$opt_selected 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...
2705
            }
2706
            echo '<option value="' . htmlspecialchars($namearray, ENT_QUOTES) . '" $opt_selected>' . $workd . '</option>';
2707
        }
2708
        echo '</select>';
2709
    }
2710
2711
    /**
2712
     * @param $selected
2713
     * @param $dirarray
2714
     * @param $namearray
2715
     */
2716 View Code Duplication
    public static function xtubeVGetDirSelectOption($selected, $dirarray, $namearray)
0 ignored issues
show
Unused Code introduced by
The parameter $dirarray is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Duplication introduced by
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...
2717
    {
2718
        echo "<select size='1' name='workd' onchange='location.href=\"vupload.php?rootpath=\"+this.options[this.selectedIndex].value'>";
2719
        echo "<option value=''>--------------------------------------</option>";
2720
        foreach ($namearray as $namearray => $workd) {
2721
            if ($workd == $selected) {
2722
                $opt_selected = 'selected';
0 ignored issues
show
Unused Code introduced by
$opt_selected 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...
2723
            } else {
2724
                $opt_selected = '';
0 ignored issues
show
Unused Code introduced by
$opt_selected 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...
2725
            }
2726
            echo '<option value="' . htmlspecialchars($namearray, ENT_QUOTES) . '" $opt_selected>' . $workd . '</option>';
2727
        }
2728
        echo '</select>';
2729
    }
2730
2731
    /**
2732
     * @param        $FILES
2733
     * @param string $uploaddir
2734
     * @param string $allowed_mimetypes
2735
     * @param string $redirecturl
2736
     * @param int    $redirect
2737
     * @param int    $usertype
2738
     *
2739
     * @return array|null
2740
     */
2741
    public static function xtubeUploadFiles($FILES, $uploaddir = 'uploads', $allowed_mimetypes = '', $redirecturl = 'index.php', //    $num = 0,
0 ignored issues
show
Coding Style introduced by
xtubeUploadFiles uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
Unused Code Comprehensibility introduced by
43% 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...
2742
                                            $redirect = 0, $usertype = 1
2743
    )
2744
    {
2745
        global $FILES, $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...
2746
2747
        $down = array();
2748
//       include_once XOOPS_ROOT_PATH . '/modules/' . $xoopsModule->getVar('dirname') . '/class/uploader.php';
0 ignored issues
show
Unused Code Comprehensibility introduced by
41% 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...
2749
        include __DIR__ . '/uploader.php';
2750
//        include_once(XOOPS_ROOT_PATH . '/class/uploader.php');
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...
2751
2752
2753
        if (empty($allowed_mimetypes)) {
2754
            $allowed_mimetypes = xtube_retmime($FILES['userfile']['name'], $usertype);
2755
        }
2756
        $upload_dir = XOOPS_ROOT_PATH . '/' . $uploaddir . '/';
2757
2758
        $maxfilesize = $GLOBALS['xoopsModuleConfig']['maxfilesize'];
2759
2760
        $maxfilewidth  = $GLOBALS['xoopsModuleConfig']['maximgwidth'];
2761
        $maxfileheight = $GLOBALS['xoopsModuleConfig']['maximgheight'];
2762
2763
        $uploader = new XoopsMediaUploader($upload_dir, $allowed_mimetypes, $maxfilesize, $maxfilewidth, $maxfileheight);
2764
2765
        $uploader->noAdminSizeCheck(1);
2766
2767
        if ($uploader->fetchMedia(XoopsRequest::getArray('xoops_upload_file', '', 'POST')[0])) {
2768
            if (!$uploader->upload()) {
2769
                $errors = $uploader->getErrors();
2770
                redirect_header($redirecturl, 2, $errors);
2771
            } else {
2772
                if ($redirect) {
2773
                    redirect_header($redirecturl, 1, _AM_XOOPSTUBE_UPLOADFILE);
2774
                } else {
2775
                    if (is_file($uploader->savedDestination)) {
2776
                        $down['url']  = XOOPS_URL . '/' . $uploaddir . '/' . strtolower($uploader->savedFileName);
2777
                        $down['size'] = filesize(XOOPS_ROOT_PATH . '/' . $uploaddir . '/' . strtolower($uploader->savedFileName));
2778
                    }
2779
2780
                    return $down;
2781
                }
2782
            }
2783
        } else {
2784
            $errors = $uploader->getErrors();
2785
            redirect_header($redirecturl, 1, $errors);
2786
        }
2787
2788
        return null;
2789
    }
2790
2791
    /**
2792
     * @param $heading
2793
     */
2794 View Code Duplication
    public static function xtubeRenderCategoryListHeader($heading)
0 ignored issues
show
Duplication introduced by
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...
2795
    {
2796
        echo '
2797
        <h4 style="font-weight: bold; color: #0A3760;">' . $heading . '</h4>
2798
        <table width="100%" cellspacing="1" class="outer" summary>
2799
        <tr>
2800
            <th style="text-align: center; font-size: smaller;">' . _AM_XOOPSTUBE_MINDEX_ID . '</th>
2801
            <th style=" font-size: smaller;"><b>' . _AM_XOOPSTUBE_FCATEGORY_TITLE . '</th>
2802
            <th style="text-align: center; font-size: smaller;">' . _AM_XOOPSTUBE_FCATEGORY_WEIGHT . '</th>
2803
            <th style="text-align: center; font-size: smaller;">' . _AM_XOOPSTUBE_FCATEGORY_CIMAGE . '</th>
2804
            <th style="text-align: center; font-size: smaller;">' . _AM_XOOPSTUBE_CATSPONSOR . '</th>
2805
<!--            <th style="text-align: center; font-size: smaller;">' . _AM_XOOPSTUBE_MINDEX_PUBLISH . '</th>
2806
            <th style="text-align: center; font-size: smaller;">' . _AM_XOOPSTUBE_MINDEX_EXPIRE . '</th>
2807
            <th style="text-align: center; font-size: smaller;">' . _AM_XOOPSTUBE_MINDEX_ONLINE . '</th>
2808
            <th style="text-align: center; font-size: smaller;">' . _AM_XOOPSTUBE_MINDEX_ACTION . '</th> -->
2809
        </tr>
2810
        ';
2811
    }
2812
2813
    /**
2814
     * @param $published
2815
     */
2816
    public static function xtubeRenderCategoryListBody($published)
0 ignored issues
show
Coding Style introduced by
xtubeRenderCategoryListBody uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
2817
    {
2818
        global $xtubemyts, $xtubeImageArray;
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...
2819
2820
        $lid = $published['lid'];
2821
        $cid = $published['cid'];
2822
2823
        $title        = '<a href="../singlevideo.php?cid=' . $published['cid'] . '&amp;lid=' . $published['lid'] . '">' . $xtubemyts->htmlSpecialCharsStrip(trim($published['title'])) . '</a>';
2824
        $maintitle    = urlencode($xtubemyts->htmlSpecialChars(trim($published['title'])));
0 ignored issues
show
Unused Code introduced by
$maintitle 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...
2825
        $cattitle     = '<a href="../viewcat.php?cid=' . $published['cid'] . '">' . XoopstubeUtilities::xtubeGetCategoryTitle($published['cid']) . '</a>';
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
2826
        $submitter    = XoopstubeUtilities::xtubeGetLinkedUserNameFromId($published['submitter']);
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
2827
        $returnsource = xtubeReturnSource($published['vidsource']);
2828
        $submitted    = XoopstubeUtilities::xtubeGetTimestamp(formatTimestamp($published['date'], $GLOBALS['xoopsModuleConfig']['dateformatadmin']));
0 ignored issues
show
Unused Code introduced by
$submitted 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...
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
2829
        $publish      =
2830
            ($published['published'] > 0) ? XoopstubeUtilities::xtubeGetTimestamp(formatTimestamp($published['published'], $GLOBALS['xoopsModuleConfig']['dateformatadmin'])) : 'Not Published';
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
2831
        $expires      =
2832
            $published['expired'] ? XoopstubeUtilities::xtubeGetTimestamp(formatTimestamp($published['expired'], $GLOBALS['xoopsModuleConfig']['dateformatadmin'])) : _AM_XOOPSTUBE_MINDEX_NOTSET;
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
2833
2834
        if ((($published['expired'] && $published['expired'] > time()) || 0 == $published['expired'])
2835
            && ($published['published'] && $published['published'] < time())
2836
            && 0 == $published['offline']
2837
        ) {
2838
            $published_status = $xtubeImageArray['online'];
2839 View Code Duplication
        } elseif (($published['expired'] && $published['expired'] < time()) && 0 == $published['offline']) {
0 ignored issues
show
Duplication introduced by
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...
2840
            $published_status = $xtubeImageArray['expired'];
2841
        } else {
2842
            $published_status = (0 == $published['published']) ? '<a href="newvideos.php">' . $xtubeImageArray['offline'] . '</a>' : $xtubeImageArray['offline'];
2843
        }
2844
2845 View Code Duplication
        if (200 == $published['vidsource']) {
0 ignored issues
show
Duplication introduced by
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...
2846
            $icon = '<a href="main.php?op=edit&amp;lid=' . $lid . '" title="' . _AM_XOOPSTUBE_ICO_EDIT . '">' . $xtubeImageArray['editimg'] . '</a>&nbsp;';
2847
        } else {
2848
            $icon = '<a href="main.php?op=edit&amp;lid=' . $lid . '" title="' . _AM_XOOPSTUBE_ICO_EDIT . '">' . $xtubeImageArray['editimg'] . '</a>&nbsp;';
2849
        }
2850
        $icon .= '<a href="main.php?op=delete&amp;lid=' . $lid . '" title="' . _AM_XOOPSTUBE_ICO_DELETE . '">' . $xtubeImageArray['deleteimg'] . '</a>&nbsp;';
2851
        $icon .= '<a href="altcat.php?op=main&amp;cid=' . $cid . '&amp;lid=' . $lid . '&amp;title=' . $published['title'] . '" title="' . _AM_XOOPSTUBE_ALTCAT_CREATEF . '">'
2852
                 . $xtubeImageArray['altcat'] . '</a>';
2853
2854
        echo '
2855
        <tr style="text-align: center; font-size: smaller;">
2856
        <td class="head">' . $lid . '</span></td>
2857
        <td class="even" style="text-align: left;">' . $title . '</td>
2858
        <td class="even">' . $returnsource . '</td>
2859
        <td class="even">' . $cattitle . '</td>
2860
        <td class="even">' . $submitter . '</td>
2861
        <td class="even">' . $publish . '</td>
2862
        <td class="even">' . $expires . '</td>
2863
        <td class="even" style="width: 4%;">' . $published_status . '</td>
2864
        <td class="even" style="text-align: center; width: 6%; white-space: nowrap;">' . $icon . '</td>
2865
        </tr>';
2866
        //        unset($published);
0 ignored issues
show
Unused Code Comprehensibility introduced by
84% 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...
2867
    }
2868
2869
    /**
2870
     * @param        $pubrowamount
2871
     * @param        $start
2872
     * @param string $art
2873
     * @param string $_this
2874
     * @param        $align
2875
     *
2876
     * @return bool|null
2877
     */
2878 View Code Duplication
    public static function xtubeSetPageNavigationCategoryList($pubrowamount, $start, $art = 'art', $_this = '', $align)
0 ignored issues
show
Duplication introduced by
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...
Coding Style introduced by
xtubeSetPageNavigationCategoryList uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
2879
    {
2880
        if ($pubrowamount < $GLOBALS['xoopsModuleConfig']['admin_perpage']) {
2881
            return false;
2882
        }
2883
        // Display Page Nav if published is > total display pages amount.
2884
        include_once XOOPS_ROOT_PATH . '/class/pagenav.php';
2885
        $pagenav = new XoopsPageNav($pubrowamount, $GLOBALS['xoopsModuleConfig']['admin_perpage'], $start, 'st' . $art, $_this);
2886
        echo '<div style="text-align: ' . $align . '; padding: 8px;">' . $pagenav->renderNav() . '</div>';
2887
2888
        return null;
2889
    }
2890
2891
    /**
2892
     *
2893
     */
2894
    public static function xtubeRenderCategoryListFooter()
2895
    {
2896
        echo '<tr style="text-align: center;">
2897
            <td class="head" colspan="7">' . _AM_XOOPSTUBE_MINDEX_NOVIDEOSFOUND . '</td>
2898
          </tr>';
2899
    }
2900
2901
    /**
2902
     * @param $heading
2903
     */
2904 View Code Duplication
    public static function xtubeRenderVideoListHeader($heading)
0 ignored issues
show
Duplication introduced by
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...
2905
    {
2906
        echo '
2907
        <h4 style="font-weight: bold; color: #0A3760;">' . $heading . '</h4>
2908
        <table width="100%" cellspacing="1" class="outer" summary>
2909
        <tr>
2910
            <th style="text-align: center; font-size: smaller;">' . _AM_XOOPSTUBE_MINDEX_ID . '</th>
2911
            <th style=" font-size: smaller;"><b>' . _AM_XOOPSTUBE_MINDEX_TITLE . '</th>
2912
            <th style="text-align: center; font-size: smaller;">' . _AM_XOOPSTUBE_VIDSOURCE2 . '</th>
2913
            <th style="text-align: center; font-size: smaller;">' . _AM_XOOPSTUBE_CATTITLE . '</th>
2914
            <th style="text-align: center; font-size: smaller;">' . _AM_XOOPSTUBE_MINDEX_POSTER . '</th>
2915
            <th style="text-align: center; font-size: smaller;">' . _AM_XOOPSTUBE_MINDEX_PUBLISH . '</th>
2916
            <th style="text-align: center; font-size: smaller;">' . _AM_XOOPSTUBE_MINDEX_EXPIRE . '</th>
2917
            <th style="text-align: center; font-size: smaller;">' . _AM_XOOPSTUBE_MINDEX_ONLINE . '</th>
2918
            <th style="text-align: center; font-size: smaller;">' . _AM_XOOPSTUBE_MINDEX_ACTION . '</th>
2919
        </tr>
2920
        ';
2921
    }
2922
2923
    /**
2924
     * @param $published
2925
     */
2926
    public static function xtubeRenderVideoListBody($published)
0 ignored issues
show
Coding Style introduced by
xtubeRenderVideoListBody uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
2927
    {
2928
        global $xtubemyts, $xtubeImageArray, $pathIcon16;
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...
2929
2930
        $lid = $published['lid'];
2931
        $cid = $published['cid'];
2932
2933
        $title        = '<a href="../singlevideo.php?cid=' . $published['cid'] . '&amp;lid=' . $published['lid'] . '">' . $xtubemyts->htmlSpecialCharsStrip(trim($published['title'])) . '</a>';
2934
        $maintitle    = urlencode($xtubemyts->htmlSpecialChars(trim($published['title'])));
0 ignored issues
show
Unused Code introduced by
$maintitle 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...
2935
        $cattitle     = '<a href="../viewcat.php?cid=' . $published['cid'] . '">' . XoopstubeUtilities::xtubeGetCategoryTitle($published['cid']) . '</a>';
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
2936
        $submitter    = XoopstubeUtilities::xtubeGetLinkedUserNameFromId($published['submitter']);
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
2937
        $returnsource = xtubeReturnSource($published['vidsource']);
2938
        $submitted    = XoopstubeUtilities::xtubeGetTimestamp(formatTimestamp($published['date'], $GLOBALS['xoopsModuleConfig']['dateformatadmin']));
0 ignored issues
show
Unused Code introduced by
$submitted 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...
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
2939
        $publish      =
2940
            ($published['published'] > 0) ? XoopstubeUtilities::xtubeGetTimestamp(formatTimestamp($published['published'], $GLOBALS['xoopsModuleConfig']['dateformatadmin'])) : 'Not Published';
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
2941
        $expires      =
2942
            $published['expired'] ? XoopstubeUtilities::xtubeGetTimestamp(formatTimestamp($published['expired'], $GLOBALS['xoopsModuleConfig']['dateformatadmin'])) : _AM_XOOPSTUBE_MINDEX_NOTSET;
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
2943
2944
        if ((($published['expired'] && $published['expired'] > time()) || $published['expired'] == 0)
2945
            && ($published['published'] && $published['published'] < time())
2946
            && $published['offline'] == 0
2947
        ) {
2948
            //        $published_status = $xtubeImageArray['online'];
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% 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...
2949
            $published_status = '<a href="main.php?op=toggle&amp;lid=' . $lid . '&amp;offline=' . $published['offline'] . '"><img src="' . $pathIcon16 . '/1.png' . '" /></a>';
2950 View Code Duplication
        } elseif (($published['expired'] && $published['expired'] < time()) && $published['offline'] == 0) {
0 ignored issues
show
Duplication introduced by
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...
2951
            $published_status = $xtubeImageArray['expired'];
2952
        } else {
2953
            $published_status = ($published['published'] == 0) ? ('<a href="newvideos.php">' . $xtubeImageArray['offline'] . '</a>') : ('<a href="main.php?op=toggle&amp;lid=' . $lid . '&amp;offline='
2954
                                                                                                                                        . $published['offline'] . '"><img src="' . $pathIcon16
2955
                                                                                                                                        . '/0.png' . '" /></a>');
2956
        }
2957
2958 View Code Duplication
        if (200 == $published['vidsource']) {
0 ignored issues
show
Duplication introduced by
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...
2959
            $icon = '<a href="main.php?op=edit&amp;lid=' . $lid . '" title="' . _AM_XOOPSTUBE_ICO_EDIT . '">' . $xtubeImageArray['editimg'] . '</a>&nbsp;';
2960
        } else {
2961
            $icon = '<a href="main.php?op=edit&amp;lid=' . $lid . '" title="' . _AM_XOOPSTUBE_ICO_EDIT . '">' . $xtubeImageArray['editimg'] . '</a>&nbsp;';
2962
        }
2963
        $icon .= '<a href="main.php?op=delete&amp;lid=' . $lid . '" title="' . _AM_XOOPSTUBE_ICO_DELETE . '">' . $xtubeImageArray['deleteimg'] . '</a>&nbsp;';
2964
        $icon .= '<a href="altcat.php?op=main&amp;cid=' . $cid . '&amp;lid=' . $lid . '&amp;title=' . $published['title'] . '" title="' . _AM_XOOPSTUBE_ALTCAT_CREATEF . '">'
2965
                 . $xtubeImageArray['altcat'] . '</a>';
2966
2967
        echo '
2968
        <tr style="text-align: center; font-size: smaller;">
2969
        <td class="head">' . $lid . '</span></td>
2970
        <td class="even" style="text-align: left;">' . $title . '</td>
2971
        <td class="even">' . $returnsource . '</td>
2972
        <td class="even">' . $cattitle . '</td>
2973
        <td class="even">' . $submitter . '</td>
2974
        <td class="even">' . $publish . '</td>
2975
        <td class="even">' . $expires . '</td>
2976
        <td class="even" style="width: 4%;">' . $published_status . '</td>
2977
        <td class="even" style="text-align: center; width: 6%; white-space: nowrap;">' . $icon . '</td>
2978
        </tr>';
2979
        //        unset($published);
0 ignored issues
show
Unused Code Comprehensibility introduced by
84% 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...
2980
    }
2981
2982
    /**
2983
     * @param $catt
2984
     *
2985
     * @return mixed
2986
     */
2987
    public static function xtubeGetCategoryTitle($catt)
0 ignored issues
show
Coding Style introduced by
xtubeGetCategoryTitle uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
2988
    {
2989
        $sql    = 'SELECT title FROM ' . $GLOBALS['xoopsDB']->prefix('xoopstube_cat') . ' WHERE cid=' . $catt;
2990
        $result = $GLOBALS['xoopsDB']->query($sql);
2991
        $result = $GLOBALS['xoopsDB']->fetchArray($result);
2992
2993
        return $result['title'];
2994
    }
2995
2996
    /**
2997
     *
2998
     */
2999
    public static function xtubeRenderVideoListFooter()
3000
    {
3001
        echo '<tr style="text-align: center;">
3002
            <td class="head" colspan="7">' . _AM_XOOPSTUBE_MINDEX_NOVIDEOSFOUND . '</td>
3003
          </tr>';
3004
    }
3005
3006
    /**
3007
     * @param        $pubrowamount
3008
     * @param        $start
3009
     * @param string $art
3010
     * @param string $_this
3011
     * @param        $align
3012
     *
3013
     * @return bool|null
3014
     */
3015 View Code Duplication
    public static function xtubeSetPageNavigationVideoList($pubrowamount, $start, $art = 'art', $_this = '', $align)
0 ignored issues
show
Duplication introduced by
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...
Coding Style introduced by
xtubeSetPageNavigationVideoList uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
3016
    {
3017
        if ($pubrowamount < $GLOBALS['xoopsModuleConfig']['admin_perpage']) {
3018
            return false;
3019
        }
3020
        // Display Page Nav if published is > total display pages amount.
3021
        include_once XOOPS_ROOT_PATH . '/class/pagenav.php';
3022
        $pagenav = new XoopsPageNav($pubrowamount, $GLOBALS['xoopsModuleConfig']['admin_perpage'], $start, 'st' . $art, $_this);
3023
        echo '<div style="text-align: ' . $align . '; padding: 8px;">' . $pagenav->renderNav() . '</div>';
3024
3025
        return null;
3026
    }
3027
3028
    /**
3029
     * @param $document
3030
     *
3031
     * @return mixed
3032
     */
3033
    public static function xtubeConvertHtml2Text($document)
3034
    {
3035
        // PHP Manual:: function preg_replace
3036
        // $document should contain an HTML document.
3037
        // This will remove HTML tags, javascript sections
3038
        // and white space. It will also convert some
3039
        // common HTML entities to their text equivalent.
3040
        // Credits : newbb2
3041
        $search = array(
3042
            "'<script[^>]*?>.*?</script>'si", // Strip out javascript
3043
            "'<img.*?/>'si", // Strip out img tags
3044
            "'<[\/\!]*?[^<>]*?>'si", // Strip out HTML tags
3045
            "'([\r\n])[\s]+'", // Strip out white space
3046
            "'&(quot|#34);'i", // Replace HTML entities
3047
            "'&(amp|#38);'i",
3048
            "'&(lt|#60);'i",
3049
            "'&(gt|#62);'i",
3050
            "'&(nbsp|#160);'i",
3051
            "'&(iexcl|#161);'i",
3052
            "'&(cent|#162);'i",
3053
            "'&(pound|#163);'i",
3054
            "'&(copy|#169);'i"
3055
        ); // evaluate as php
3056
3057
        $replace = array(
3058
            '',
3059
            '',
3060
            '',
3061
            "\\1",
3062
            "\"",
3063
            '&',
3064
            '<',
3065
            '>',
3066
            ' ',
3067
            chr(161),
3068
            chr(162),
3069
            chr(163),
3070
            chr(169)
3071
        );
3072
3073
        $text = preg_replace($search, $replace, $document);
3074
3075
        return $text;
3076
    }
3077
3078
    // Check if Tag module is installed
3079
    /**
3080
     * @return bool
0 ignored issues
show
Documentation introduced by
Should the return type not be null|boolean?

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...
3081
     */
3082
    public static function xtubeIsModuleTagInstalled()
3083
    {
3084
        static $isModuleTagInstalled;
3085
        if (!isset($isModuleTagInstalled)) {
3086
            $moduleHandler = xoops_getHandler('module');
3087
            $tag_mod       = $moduleHandler->getByDirName('tag');
3088
            if (!$tag_mod) {
3089
                $tag_mod = false;
0 ignored issues
show
Unused Code introduced by
$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...
3090
            } else {
3091
                $isModuleTagInstalled = 1 == $tag_mod->getVar('isactive');
3092
            }
3093
        }
3094
3095
        return $isModuleTagInstalled;
3096
    }
3097
3098
    // Add item_tag to Tag-module
3099
    /**
3100
     * @param $lid
3101
     * @param $item_tag
3102
     */
3103
    public static function xtubeUpdateTag($lid, $item_tag)
3104
    {
3105
        global $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...
3106
        if (XoopstubeUtilities::xtubeIsModuleTagInstalled()) {
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
3107
            include_once XOOPS_ROOT_PATH . '/modules/tag/include/formtag.php';
3108
            $tagHandler = xoops_getModuleHandler('tag', 'tag');
3109
            $tagHandler->updateByItem($item_tag, $lid, $xoopsModule->getVar('dirname'), 0);
3110
        }
3111
    }
3112
3113
    /**
3114
     * @param $lid
3115
     */
3116
    public static function xtubeUpdateCounter($lid)
0 ignored issues
show
Coding Style introduced by
xtubeUpdateCounter uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
3117
    {
3118
        $sql    = 'UPDATE ' . $GLOBALS['xoopsDB']->prefix('xoopstube_videos') . ' SET hits=hits+1 WHERE lid=' . (int)$lid;
3119
        $result = $GLOBALS['xoopsDB']->queryF($sql);
0 ignored issues
show
Unused Code introduced by
$result 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...
3120
    }
3121
3122
    /**
3123
     * @param $banner_id
3124
     *
3125
     * @return null|string
3126
     */
3127 View Code Duplication
    public static function xtubeGetBannerFromBannerId($banner_id)
0 ignored issues
show
Duplication introduced by
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...
Coding Style introduced by
xtubeGetBannerFromBannerId uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
3128
    {
3129
        ###### Hack by www.stefanosilvestrini.com ######
3130
        $db      = XoopsDatabaseFactory::getDatabaseConnection();
3131
        $bresult = $db->query('SELECT COUNT(*) FROM ' . $db->prefix('banner') . ' WHERE bid=' . $banner_id);
3132
        list($numrows) = $db->fetchRow($bresult);
3133
        if ($numrows > 1) {
3134
            --$numrows;
3135
            mt_srand((double)microtime() * 1000000);
3136
            $bannum = mt_rand(0, $numrows);
3137
        } else {
3138
            $bannum = 0;
3139
        }
3140
        if ($numrows > 0) {
3141
            $bresult = $db->query('SELECT * FROM ' . $db->prefix('banner') . ' WHERE bid=' . $banner_id, 1, $bannum);
3142
            list($bid, $cid, $imptotal, $impmade, $clicks, $imageurl, $clickurl, $date, $htmlbanner, $htmlcode) = $db->fetchRow($bresult);
0 ignored issues
show
Unused Code introduced by
The assignment to $clickurl is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
3143
            if ($GLOBALS['xoopsConfig']['my_ip'] == xoops_getenv('REMOTE_ADDR')) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

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

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

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

could be turned into

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

This is much more concise to read.

Loading history...
3144
                // EMPTY
3145
            } else {
3146
                $db->queryF(sprintf('UPDATE %s SET impmade = impmade+1 WHERE bid = %u', $db->prefix('banner'), $bid));
3147
            }
3148
            /* Check if this impression is the last one and print the banner */
3149
            if ($imptotal == $impmade) {
3150
                $newid = $db->genId($db->prefix('bannerfinish') . '_bid_seq');
3151
                $sql   =
3152
                    sprintf('INSERT INTO %s (bid, cid, impressions, clicks, datestart, dateend) VALUES (%u, %u, %u, %u, %u, %u)', $db->prefix('bannerfinish'), $newid, $cid, $impmade, $clicks, $date,
3153
                            time());
3154
                $db->queryF($sql);
3155
                $db->queryF(sprintf('DELETE FROM %s WHERE bid = %u', $db->prefix('banner'), $bid));
3156
            }
3157
            if ($htmlbanner) {
3158
                $bannerobject = $htmlcode;
3159
            } else {
3160
                $bannerobject = '<div align="center"><a href="' . XOOPS_URL . '/banners.php?op=click&bid=' . $bid . '" target="_blank">';
3161
                if (false !== stripos($imageurl, '.swf')) {
3162
                    $bannerobject = $bannerobject
3163
                                    . '<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">'
3164
                                    . '<param name="movie" value="' . $imageurl . '"></param>' . '<param name="quality" value="high"></param>' . '<embed src="' . $imageurl
3165
                                    . '" quality="high" pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash" type="application/x-shockwave-flash" width="468" height="60">'
3166
                                    . '</embed>' . '</object>';
3167
                } else {
3168
                    $bannerobject = $bannerobject . '<img src="' . $imageurl . '" alt="" />';
3169
                }
3170
                $bannerobject .= '</a></div>';
3171
            }
3172
3173
            return $bannerobject;
3174
        }
3175
3176
        return null;
3177
    }
3178
3179
    /**
3180
     * @param $client_id
3181
     *
3182
     * @return null|string
3183
     */
3184 View Code Duplication
    public static function xtubeGetBannerFromClientId($client_id)
0 ignored issues
show
Duplication introduced by
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...
Coding Style introduced by
xtubeGetBannerFromClientId uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
3185
    {
3186
        ###### Hack by www.stefanosilvestrini.com ######
3187
        $db      = XoopsDatabaseFactory::getDatabaseConnection();
3188
        $bresult = $db->query('SELECT COUNT(*) FROM ' . $db->prefix('banner') . ' WHERE cid=' . $client_id);
3189
        list($numrows) = $db->fetchRow($bresult);
3190
        if ($numrows > 1) {
3191
            --$numrows;
3192
            mt_srand((double)microtime() * 1000000);
3193
            $bannum = mt_rand(0, $numrows);
3194
        } else {
3195
            $bannum = 0;
3196
        }
3197
        if ($numrows > 0) {
3198
            $bresult = $db->query('SELECT * FROM ' . $db->prefix('banner') . ' WHERE cid=' . $client_id . ' ORDER BY rand()', 1, $bannum);
3199
            list($bid, $cid, $imptotal, $impmade, $clicks, $imageurl, $clickurl, $date, $htmlbanner, $htmlcode) = $db->fetchRow($bresult);
0 ignored issues
show
Unused Code introduced by
The assignment to $clickurl is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
3200
            if ($GLOBALS['xoopsConfig']['my_ip'] == xoops_getenv('REMOTE_ADDR')) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

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

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

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

could be turned into

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

This is much more concise to read.

Loading history...
3201
                // EMPTY
3202
            } else {
3203
                $db->queryF(sprintf('UPDATE %s SET impmade = impmade+1 WHERE bid = %u', $db->prefix('banner'), $bid));
3204
            }
3205
            /* Check if this impression is the last one and print the banner */
3206
            if ($imptotal == $impmade) {
3207
                $newid = $db->genId($db->prefix('bannerfinish') . '_bid_seq');
3208
                $sql   =
3209
                    sprintf('INSERT INTO %s (bid, cid, impressions, clicks, datestart, dateend) VALUES (%u, %u, %u, %u, %u, %u)', $db->prefix('bannerfinish'), $newid, $cid, $impmade, $clicks, $date,
3210
                            time());
3211
                $db->queryF($sql);
3212
                $db->queryF(sprintf('DELETE FROM %s WHERE bid = %u', $db->prefix('banner'), $bid));
3213
            }
3214
            if ($htmlbanner) {
3215
                $bannerobject = $htmlcode;
3216
            } else {
3217
                $bannerobject = '<div align="center"><a href="' . XOOPS_URL . '/banners.php?op=click&bid=' . $bid . '" target="_blank">';
3218
                if (false !== stripos($imageurl, '.swf')) {
3219
                    $bannerobject = $bannerobject
3220
                                    . '<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">'
3221
                                    . '<param name="movie" value="' . $imageurl . '"></param>' . '<param name="quality" value="high"></param>' . '<embed src="' . $imageurl
3222
                                    . '" quality="high" pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash" type="application/x-shockwave-flash" width="468" height="60">'
3223
                                    . '</embed>' . '</object>';
3224
                } else {
3225
                    $bannerobject = $bannerobject . '<img src="' . $imageurl . '" alt="" />';
3226
                }
3227
                $bannerobject .= '</a></div>';
3228
            }
3229
3230
            return $bannerobject;
3231
        }
3232
3233
        return null;
3234
    }
3235
3236
    /**
3237
     *
3238
     */
3239
    public static function xtubeSetNoIndexNoFollow()
0 ignored issues
show
Coding Style introduced by
xtubeSetNoIndexNoFollow uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
3240
    {
3241
        global $xoopsTpl;
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...
3242
        if (is_object($GLOBALS['xoTheme'])) {
3243
            $GLOBALS['xoTheme']->addMeta('meta', 'robots', 'noindex,nofollow');
3244
        } else {
3245
            $xoopsTpl->assign('xoops_meta_robots', 'noindex,nofollow');
3246
        }
3247
    }
3248
3249
    /**
3250
     * @param $userid
3251
     *
3252
     * @return string
3253
     */
3254
    public static function xtubeGetLinkedUserNameFromId($userid)
0 ignored issues
show
Coding Style introduced by
xtubeGetLinkedUserNameFromId uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
3255
    {
3256
        $userid = (int)$userid;
3257
        if ($userid > 0) {
3258
            $memberHandler = xoops_getHandler('member');
3259
            $user          = $memberHandler->getUser($userid);
3260
            if (is_object($user)) {
3261
                $linkeduser = '<a href="' . XOOPS_URL . '/userinfo.php?uid=' . $userid . '">' . $user->getVar('uname') . '</a>';
3262
3263
                return $linkeduser;
3264
            }
3265
        }
3266
3267
        return $GLOBALS['xoopsConfig']['anonymous'];
3268
    }
3269
3270
    /**
3271
     * @param $time
3272
     *
3273
     * @return string
3274
     */
3275
    public static function xtubeGetTimestamp($time)
0 ignored issues
show
Coding Style introduced by
xtubeGetTimestamp uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
3276
    {
3277
        $moduleDirName = basename(dirname(__DIR__));
3278
        include_once XOOPS_ROOT_PATH . '/modules/' . $moduleDirName . '/language/' . $GLOBALS['xoopsConfig']['language'] . '/local.php';
3279
3280
        $trans     = array(
3281
            'Monday'    => _XOOPSTUBE_MONDAY,
3282
            'Tuesday'   => _XOOPSTUBE_TUESDAY,
3283
            'Wednesday' => _XOOPSTUBE_WEDNESDAY,
3284
            'Thursday'  => _XOOPSTUBE_THURSDAY,
3285
            'Friday'    => _XOOPSTUBE_FRIDAY,
3286
            'Saturday'  => _XOOPSTUBE_SATURDAY,
3287
            'Sunday'    => _XOOPSTUBE_SUNDAY,
3288
            'Mon'       => _XOOPSTUBE_MON,
3289
            'Tue'       => _XOOPSTUBE_TUE,
3290
            'Wed'       => _XOOPSTUBE_WED,
3291
            'Thu'       => _XOOPSTUBE_THU,
3292
            'Fri'       => _XOOPSTUBE_FRI,
3293
            'Sat'       => _XOOPSTUBE_SAT,
3294
            'Sun'       => _XOOPSTUBE_SUN,
3295
            'January'   => _XOOPSTUBE_JANUARI,
3296
            'February'  => _XOOPSTUBE_FEBRUARI,
3297
            'March'     => _XOOPSTUBE_MARCH,
3298
            'April'     => _XOOPSTUBE_APRIL,
3299
            'May'       => _XOOPSTUBE_MAY,
3300
            'June'      => _XOOPSTUBE_JUNE,
3301
            'July'      => _XOOPSTUBE_JULY,
3302
            'August'    => _XOOPSTUBE_AUGUST,
3303
            'September' => _XOOPSTUBE_SEPTEMBER,
3304
            'October'   => _XOOPSTUBE_OCTOBER,
3305
            'November'  => _XOOPSTUBE_NOVEMBER,
3306
            'December'  => _XOOPSTUBE_DECEMBER,
3307
            'Jan'       => _XOOPSTUBE_JAN,
3308
            'Feb'       => _XOOPSTUBE_FEB,
3309
            'Mar'       => _XOOPSTUBE_MAR,
3310
            'Apr'       => _XOOPSTUBE_APR,
3311
            //        'May'       => _XOOPSTUBE_MAY2,
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% 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...
3312
            'Jun'       => _XOOPSTUBE_JUN,
3313
            'Jul'       => _XOOPSTUBE_JUL,
3314
            'Aug'       => _XOOPSTUBE_AUG,
3315
            'Sep'       => _XOOPSTUBE_SEP,
3316
            'Oct'       => _XOOPSTUBE_OCT,
3317
            'Nov'       => _XOOPSTUBE_NOV,
3318
            'Dec'       => _XOOPSTUBE_DEC
3319
        );
3320
        $timestamp = strtr($time, $trans);
3321
3322
        return $timestamp;
3323
    }
3324
3325
    /**
3326
     * Do some basic file checks and stuff.
3327
     * Author: Andrew Mills  Email:  [email protected]
3328
     * from amReviews module
3329
     */
3330
    public static function xtubeFileChecks()
0 ignored issues
show
Coding Style introduced by
xtubeFileChecks uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
3331
    {
3332
        echo '<fieldset>';
3333
        echo "<legend style=\"color: #990000; font-weight: bold;\">" . _AM_XOOPSTUBE_FILECHECKS . '</legend>';
3334
3335
        $dirPhotos      = XOOPS_ROOT_PATH . '/' . $GLOBALS['xoopsModuleConfig']['catimage'];
3336
        $dirVideos      = XOOPS_ROOT_PATH . '/' . $GLOBALS['xoopsModuleConfig']['videodir'];
3337
        $dirScreenshots = XOOPS_ROOT_PATH . '/' . $GLOBALS['xoopsModuleConfig']['videoimgdir'];
3338
3339 View Code Duplication
        if (file_exists($dirPhotos)) {
0 ignored issues
show
Duplication introduced by
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...
3340
            if (!is_writable($dirPhotos)) {
3341
                echo "<span style=\" color: red; font-weight: bold;\">Warning:</span> " . _AM_XOOPSTUBE_UNABLE_TO_WRITE . $dirPhotos . '<br>';
3342
            } else {
3343
                echo "<span style=\" color: green; font-weight: bold;\">OK:</span> " . $dirPhotos . '<br>';
3344
            }
3345
        } else {
3346
            echo "<span style=\" color: red; font-weight: bold;\">" . _AM_XOOPSTUBE_WARNING . '</span> ' . $dirPhotos . " <span style=\" color: red; \">" . _AM_XOOPSTUBE_NOT_EXISTS . '</span> <br>';
3347
        }
3348
        // photothumbdir
3349 View Code Duplication
        if (file_exists($dirVideos)) {
0 ignored issues
show
Duplication introduced by
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...
3350
            if (!is_writable($dirVideos)) {
3351
                echo "<span style=\" color: red; font-weight: bold;\">" . _AM_XOOPSTUBE_WARNING . '</span> ' . _AM_XOOPSTUBE_UNABLE_TO_WRITE . $dirVideos . '<br>';
3352
            } else {
3353
                echo "<span style=\" color: green; font-weight: bold;\">OK:</span> " . $dirVideos . '<br>';
3354
            }
3355
        } else {
3356
            echo "<span style=\" color: red; font-weight: bold;\">" . _AM_XOOPSTUBE_WARNING . '</span> ' . $dirVideos . " <span style=\" color: red; \">" . _AM_XOOPSTUBE_NOT_EXISTS . '</span> <br>';
3357
        }
3358
        // photohighdir
3359 View Code Duplication
        if (file_exists($dirScreenshots)) {
0 ignored issues
show
Duplication introduced by
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...
3360
            if (!is_writable($dirScreenshots)) {
3361
                echo "<span style=\" color: red; font-weight: bold;\">Warning:</span> " . _AM_XOOPSTUBE_UNABLE_TO_WRITE . $dirScreenshots . '<br>';
3362
            } else {
3363
                echo "<span style=\" color: green; font-weight: bold;\">OK:</span> " . $dirScreenshots . '<br>';
3364
            }
3365
        } else {
3366
            echo "<span style=\" color: red; font-weight: bold;\">" . _AM_XOOPSTUBE_WARNING . '</span> ' . $dirScreenshots . " <span style=\" color: red; \">" . _AM_XOOPSTUBE_NOT_EXISTS
3367
                 . '</span> <br>';
3368
        }
3369
3370
        /**
3371
         * Some info.
3372
         */
3373
        $uploads = ini_get('file_uploads') ? _AM_XOOPSTUBE_UPLOAD_ON : _AM_XOOPSTUBE_UPLOAD_OFF;
3374
        echo '<br>';
3375
        echo '<ul>';
3376
        echo '<li>' . _AM_XOOPSTUBE_UPLOADMAX . '<b>' . ini_get('upload_max_filesize') . '</b></li>';
3377
        echo '<li>' . _AM_XOOPSTUBE_POSTMAX . '<b>' . ini_get('post_max_size') . '</b></li>';
3378
        echo '<li>' . _AM_XOOPSTUBE_UPLOADS . '<b>' . $uploads . '</b></li>';
3379
3380
        $gdinfo = gd_info();
3381
        if (function_exists('gd_info')) {
3382
            echo '<li>' . _AM_XOOPSTUBE_GDIMGSPPRT . '<b>' . _AM_XOOPSTUBE_GDIMGON . '</b></li>';
3383
            echo '<li>' . _AM_XOOPSTUBE_GDIMGVRSN . '<b>' . $gdinfo['GD Version'] . '</b></li>';
3384
        } else {
3385
            echo '<li>' . _AM_XOOPSTUBE_GDIMGSPPRT . '<b>' . _AM_XOOPSTUBE_GDIMGOFF . '</b></li>';
3386
        }
3387
        echo '</ul>';
3388
3389
        //$inithingy = ini_get_all();
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...
3390
        //print_r($inithingy);
3391
3392
        echo '</fieldset>';
3393
    }
3394
3395
    /**
3396
     * @param      $path
3397
     * @param int  $mode
3398
     * @param      $fileSource
3399
     * @param null $fileTarget
3400
     */
3401
    public static function xtubeCreateDirectory($path, $mode = 0777, $fileSource, $fileTarget = null)
3402
    {
3403
        if (!is_dir($path)) {
3404
            mkdir($path, $mode);
3405
            file_put_contents($path . '/index.html', '<script>history.go(-1);</script>');
3406
            if (!empty($fileSource) && !empty($fileTarget)) {
3407
                @copy($fileSource, $fileTarget);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
3408
            }
3409
        }
3410
        chmod($path, $mode);
3411
    }
3412
3413
    /**
3414
     * @return string
3415
     */
3416
    public static function xtubeGetLetters()
0 ignored issues
show
Coding Style introduced by
xtubeGetLetters uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
3417
    {
3418
        global $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...
3419
3420
        $letterchoice          = '<div>' . _MD_XOOPSTUBE_BROWSETOTOPIC . '</div>';
3421
        $alphabet              = getXtubeAlphabet();
3422
        $num                   = count($alphabet) - 1;
3423
        $counter               = 0;
3424
        $distinctDbLetters_arr = array();
3425
        $sql                   = 'SELECT DISTINCT (UPPER(LEFT(title, 1))) AS letter FROM ' . $GLOBALS['xoopsDB']->prefix('xoopstube_videos WHERE expired = 0 AND offline = 0');
3426
        if ($result = $GLOBALS['xoopsDB']->query($sql)) {
3427
            while (false !== ($row = $GLOBALS['xoopsDB']->fetchArray($result))) {
3428
                $distinctDbLetters_arr[] = $row['letter'];
3429
            }
3430
        }
3431
        unset($sql);
3432
3433
        while (false !== (list(, $ltr) = each($alphabet))) {
3434
            if (in_array($ltr, $distinctDbLetters_arr)) {
3435
                $letterchoice .= '<a class="xoopstube_letters xoopstube_letters_green" href="';
3436
            } else {
3437
                $letterchoice .= '<a class="xoopstube_letters" href="';
3438
            }
3439
            $letterchoice .= XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname') . '/viewcat.php?list=' . $ltr . '">' . $ltr . '</a>';
3440
            if ($counter == round($num / 2)) {
3441
                $letterchoice .= '<br>';
3442
            } elseif ($counter !== $num) {
3443
                $letterchoice .= '&nbsp;';
3444
            }
3445
            ++$counter;
3446
        }
3447
3448
        return $letterchoice;
3449
    }
3450
3451
    /**
3452
     * @return mixed|string
3453
     */
3454
    public static function xtubeLettersChoice()
0 ignored issues
show
Coding Style introduced by
xtubeLettersChoice uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
3455
    {
3456
        global $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...
3457
3458
        $moduleDirName = $xoopsModule->getVar('dirname');
3459
        include_once XOOPS_ROOT_PATH . "/modules/$moduleDirName/class/$moduleDirName.php";
3460
        $xoopstube = XoopstubeXoopstube::getInstance();
3461
3462
        $a             = $xoopstube->getHandler('xoopstube');
3463
        $b             = $a->getActiveCriteria();
0 ignored issues
show
Unused Code introduced by
$b 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...
3464
        $moduleDirName = basename(dirname(__DIR__));
3465
3466
        $criteria = $xoopstube->getHandler('xoopstube')->getActiveCriteria();
3467
        $criteria->setGroupby('UPPER(LEFT(title,1))');
3468
        $countsByLetters = $xoopstube->getHandler($moduleDirName)->getCounts($criteria);
3469
        // Fill alphabet array
3470
        $alphabet       = getXtubeAlphabet();
3471
        $alphabet_array = array();
3472 View Code Duplication
        foreach ($alphabet as $letter) {
0 ignored issues
show
Duplication introduced by
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...
3473
            $letter_array = array();
3474
            if (isset($countsByLetters[$letter])) {
3475
                $letter_array['letter'] = $letter;
3476
                $letter_array['count']  = $countsByLetters[$letter];
3477
                $letter_array['url']    = '' . XOOPS_URL . "/modules/$moduleDirName/viewcat.php?list={$letter}";
3478
            } else {
3479
                $letter_array['letter'] = $letter;
3480
                $letter_array['count']  = 0;
3481
                $letter_array['url']    = '';
3482
            }
3483
            $alphabet_array[$letter] = $letter_array;
3484
            unset($letter_array);
3485
        }
3486
        // Render output
3487 View Code Duplication
        if (!isset($GLOBALS['xoTheme']) || !is_object($GLOBALS['xoTheme'])) {
0 ignored issues
show
Duplication introduced by
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...
3488
            include_once $GLOBALS['xoops']->path('class/theme.php');
3489
            $GLOBALS['xoTheme'] = new xos_opal_Theme();
3490
        }
3491
        require_once $GLOBALS['xoops']->path('class/template.php');
3492
        $letterschoiceTpl          = new XoopsTpl();
3493
        $letterschoiceTpl->caching = false; // Disable cache
3494
        $letterschoiceTpl->assign('alphabet', $alphabet_array);
3495
        $html = $letterschoiceTpl->fetch('db:' . $xoopstube->getModule()->dirname() . '_common_letterschoice.tpl');
0 ignored issues
show
Bug introduced by
The method dirname cannot be called on $xoopstube->getModule() (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
3496
        unset($letterschoiceTpl);
3497
3498
        return $html;
3499
    }
3500
3501
    /**
3502
     * Create download by letter choice bar/menu
3503
     * updated starting from this idea http://xoops.org/modules/news/article.php?storyid=6497
3504
     *
3505
     * @return string html
3506
     *
3507
     * @access  public
3508
     * @author  luciorota
3509
     */
3510
    public static function xoopstubeLettersChoice()
0 ignored issues
show
Coding Style introduced by
xoopstubeLettersChoice uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
3511
    {
3512
        global $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...
3513
3514
        $moduleDirName = $xoopsModule->getVar('dirname');
3515
        include_once XOOPS_ROOT_PATH . "/modules/$moduleDirName/class/$moduleDirName.php";
3516
3517
        $xoopstube = XoopstubeXoopstube::getInstance();
3518
3519
        $criteria = $xoopstube->getHandler('xoopstube')->getActiveCriteria();
3520
        $criteria->setGroupby('UPPER(LEFT(title,1))');
3521
        $countsByLetters = $xoopstube->getHandler('xoopstube')->getCounts($criteria);
3522
        // Fill alphabet array
3523
        $alphabet       = array();
0 ignored issues
show
Unused Code introduced by
$alphabet 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...
3524
        $alphabet       = getXtubeAlphabet();
3525
        $alphabet_array = array();
3526 View Code Duplication
        foreach ($alphabet as $letter) {
0 ignored issues
show
Duplication introduced by
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...
3527
            $letter_array = array();
3528
            if (isset($countsByLetters[$letter])) {
3529
                $letter_array['letter'] = $letter;
3530
                $letter_array['count']  = $countsByLetters[$letter];
3531
                $letter_array['url']    = XOOPS_URL . "/modules/{$xoopstube->getModule()->dirname()}/viewcat.php?list={$letter}";
0 ignored issues
show
Bug introduced by
The method dirname cannot be called on $xoopstube->getModule() (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
3532
            } else {
3533
                $letter_array['letter'] = $letter;
3534
                $letter_array['count']  = 0;
3535
                $letter_array['url']    = '';
3536
            }
3537
            $alphabet_array[$letter] = $letter_array;
3538
            unset($letter_array);
3539
        }
3540
        // Render output
3541 View Code Duplication
        if (!isset($GLOBALS['xoTheme']) || !is_object($GLOBALS['xoTheme'])) {
0 ignored issues
show
Duplication introduced by
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...
3542
            include_once $GLOBALS['xoops']->path('/class/theme.php');
3543
            $GLOBALS['xoTheme'] = new xos_opal_Theme();
3544
        }
3545
        require_once $GLOBALS['xoops']->path('class/template.php');
3546
        $letterschoiceTpl          = new XoopsTpl();
3547
        $letterschoiceTpl->caching = false; // Disable cache
3548
        $letterschoiceTpl->assign('alphabet', $alphabet_array);
3549
        $html = $letterschoiceTpl->fetch("db:{$xoopstube->getModule()->dirname()}_co_letterschoice.tpl");
0 ignored issues
show
Bug introduced by
The method dirname cannot be called on $xoopstube->getModule() (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
3550
        unset($letterschoiceTpl);
3551
3552
        return $html;
3553
    }
3554
3555
3556
    //===============  from WF-Downloads   ======================================
3557
3558
    /**
3559
     * @return bool
3560
     */
3561
    public static function xtubeUserIsAdmin()
0 ignored issues
show
Coding Style introduced by
xtubeUserIsAdmin uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
3562
    {
3563
        $xoopstube = XoopstubeXoopstube::getInstance();
3564
3565
        static $xtubeIsAdmin;
3566
3567
        if (isset($xtubeIsAdmin)) {
3568
            return $xtubeIsAdmin;
3569
        }
3570
3571
        if (!$GLOBALS['xoopsUser']) {
3572
            $xtubeIsAdmin = false;
3573
        } else {
3574
            $xtubeIsAdmin = $GLOBALS['xoopsUser']->isAdmin($xoopstube->getModule()->getVar('mid'));
0 ignored issues
show
Bug introduced by
The method getVar cannot be called on $xoopstube->getModule() (of type null).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
3575
        }
3576
3577
        return $xtubeIsAdmin;
3578
    }
3579
}
3580