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

XoopstubeUtility::xtubeGetBannerFromBannerId()   C

Complexity

Conditions 7
Paths 26

Size

Total Lines 51
Code Lines 38

Duplication

Lines 51
Ratio 100 %

Importance

Changes 0
Metric Value
cc 7
eloc 38
nc 26
nop 1
dl 51
loc 51
rs 6.9743
c 0
b 0
f 0

How to fix   Long Method   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
/*
3
 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
use Xmf\Request;
13
14
/**
15
 * xoopstube
16
 *
17
 * @copyright   XOOPS Project (http://xoops.org)
18
 * @license     http://www.fsf.org/copyleft/gpl.html GNU public license
19
 * @author      Hervé Thouzard (http://www.herve-thouzard.com/)
20
 */
21
22
/**
23
 * A set of useful and common functions
24
 *
25
 * @package       xoopstube
26
 * @author        Hervé Thouzard - Instant Zero (http://xoops.instant-zero.com)
27
 * @copyright (c) Instant Zero
28
 *
29
 * Note: You should be able to use it without the need to instantiate it.
30
 *
31
 */
32
// 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...
33
34
use WideImage\WideImage;
35
36
/**
37
 * Class XoopstubeUtility
38
 */
39
class XoopstubeUtility
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...
40
{
41
    const MODULE_NAME = 'xoopstube';
42
43
    /**
44
     * Access the only instance of this class
45
     *
46
     * @return XoopsObject
0 ignored issues
show
Documentation introduced by
Should the return type not be XoopstubeUtility?

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...
47
     *
48
     * @static
49
     * @staticvar   object
50
     */
51
    public static function getInstance()
52
    {
53
        static $instance;
54
        if (null === $instance) {
55
            $instance = new static();
56
        }
57
58
        return $instance;
59
    }
60
61
    /**
62
     * Returns a module's option (with cache)
63
     *
64
     * @param string  $option    module option's name
65
     * @param boolean $withCache Do we have to use some cache ?
66
     *
67
     * @return mixed option's value
68
     */
69
    public static function getModuleOption($option, $withCache = true)
70
    {
71
        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...
72
        $repmodule = self::MODULE_NAME;
73
        static $options = array();
74
        if (is_array($options) && array_key_exists($option, $options) && $withCache) {
75
            return $options[$option];
76
        }
77
78
        $retval = false;
79
        if (isset($xoopsModuleConfig) && (is_object($xoopsModule) && $xoopsModule->getVar('dirname') == $repmodule && $xoopsModule->getVar('isactive'))) {
80
            if (isset($xoopsModuleConfig[$option])) {
81
                $retval = $xoopsModuleConfig[$option];
82
            }
83
        } else {
84
            /** @var XoopsModuleHandler $moduleHandler */
85
            $moduleHandler  = xoops_getHandler('module');
86
            $module         = $moduleHandler->getByDirname($repmodule);
87
            $configHandler = xoops_getHandler('config');
88
            if ($module) {
89
                $moduleConfig = $configHandler->getConfigsByCat(0, $module->getVar('mid'));
90
                if (isset($moduleConfig[$option])) {
91
                    $retval = $moduleConfig[$option];
92
                }
93
            }
94
        }
95
        $options[$option] = $retval;
96
97
        return $retval;
98
    }
99
100
    /**
101
     * Is Xoops 2.3.x ?
102
     *
103
     * @return boolean
104
     */
105 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...
106
    {
107
        $x23 = false;
108
        $xv  = str_replace('XOOPS ', '', XOOPS_VERSION);
109
        if ((int)substr($xv, 2, 1) >= 3) {
110
            $x23 = true;
111
        }
112
113
        return $x23;
114
    }
115
116
    /**
117
     * Is Xoops 2.0.x ?
118
     *
119
     * @return boolean
120
     */
121 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...
122
    {
123
        $x20 = false;
124
        $xv  = str_replace('XOOPS ', '', XOOPS_VERSION);
125
        if (substr($xv, 2, 1) == '0') {
126
            $x20 = true;
127
        }
128
129
        return $x20;
130
    }
131
132
    /**
133
     * Create (in a link) a javascript confirmation's box
134
     *
135
     * @param string  $message Message to display
136
     * @param boolean $form    Is this a confirmation for a form ?
137
     *
138
     * @return string the javascript code to insert in the link (or in the form)
139
     */
140
    public static function javascriptLinkConfirm($message, $form = false)
141
    {
142
        if (!$form) {
143
            return "onclick=\"javascript:return confirm('" . str_replace("'", ' ', $message) . "')\"";
144
        } else {
145
            return "onSubmit=\"javascript:return confirm('" . str_replace("'", ' ', $message) . "')\"";
146
        }
147
    }
148
149
    /**
150
     * Get current user IP
151
     *
152
     * @return string IP address (format Ipv4)
153
     */
154
    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...
155
    {
156
        $proxy_ip = '';
157
        if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
158
            $proxy_ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
159
        } elseif (!empty($_SERVER['HTTP_X_FORWARDED'])) {
160
            $proxy_ip = $_SERVER['HTTP_X_FORWARDED'];
161
        } elseif (!empty($_SERVER['HTTP_FORWARDED_FOR'])) {
162
            $proxy_ip = $_SERVER['HTTP_FORWARDED_FOR'];
163
        } elseif (!empty($_SERVER['HTTP_FORWARDED'])) {
164
            $proxy_ip = $_SERVER['HTTP_FORWARDED'];
165
        } elseif (!empty($_SERVER['HTTP_VIA'])) {
166
            $proxy_ip = $_SERVER['HTTP_VIA'];
167
        } elseif (!empty($_SERVER['HTTP_X_COMING_FROM'])) {
168
            $proxy_ip = $_SERVER['HTTP_X_COMING_FROM'];
169
        } elseif (!empty($_SERVER['HTTP_COMING_FROM'])) {
170
            $proxy_ip = $_SERVER['HTTP_COMING_FROM'];
171
        }
172
        $regs = array();
173
        //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...
174
        if (!empty($proxy_ip) && filter_var($proxy_ip, FILTER_VALIDATE_IP) && count($regs) > 0) {
175
            $the_IP = $regs[0];
176
        } else {
177
            $the_IP = $_SERVER['REMOTE_ADDR'];
178
        }
179
180
        return $the_IP;
181
    }
182
183
    /**
184
     * Set the page's title, meta description and meta keywords
185
     * Datas are supposed to be sanitized
186
     *
187
     * @param string $pageTitle       Page's Title
188
     * @param string $metaDescription Page's meta description
189
     * @param string $metaKeywords    Page's meta keywords
190
     *
191
     * @return void
192
     */
193
    public static function setMetas($pageTitle = '', $metaDescription = '', $metaKeywords = '')
194
    {
195
        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...
196
        $xoopsTpl->assign('xoops_pagetitle', $pageTitle);
197
        if (isset($xoTheme) && is_object($xoTheme)) {
198
            if (!empty($metaKeywords)) {
199
                $xoTheme->addMeta('meta', 'keywords', $metaKeywords);
200
            }
201
            if (!empty($metaDescription)) {
202
                $xoTheme->addMeta('meta', 'description', $metaDescription);
203
            }
204
        } elseif (isset($xoopsTpl) && is_object($xoopsTpl)) { // Compatibility for old Xoops versions
205
            if (!empty($metaKeywords)) {
206
                $xoopsTpl->assign('xoops_meta_keywords', $metaKeywords);
207
            }
208
            if (!empty($metaDescription)) {
209
                $xoopsTpl->assign('xoops_meta_description', $metaDescription);
210
            }
211
        }
212
    }
213
214
    /**
215
     * Send an email from a template to a list of recipients
216
     *
217
     * @param        $tplName
218
     * @param array  $recipients List of recipients
219
     * @param string $subject    Email's subject
220
     * @param array  $variables  Varirables to give to the template
221
     *
222
     * @internal param string $tpl_name Template's name
223
     * @return boolean Result of the send
224
     */
225
    public static function sendEmailFromTpl($tplName, $recipients, $subject, $variables)
226
    {
227
        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...
228
        require_once XOOPS_ROOT_PATH . '/class/xoopsmailer.php';
229
        if (!is_array($recipients)) {
230
            if ('' === trim($recipients)) {
231
                return false;
232
            }
233
        } else {
234
            if (count($recipients) == 0) {
235
                return false;
236
            }
237
        }
238
        if (function_exists('xoops_getMailer')) {
239
            $xoopsMailer =& xoops_getMailer();
240
        } else {
241
            $xoopsMailer =& getMailer();
242
        }
243
244
        $xoopsMailer->useMail();
245
        $templateDir = XOOPS_ROOT_PATH . '/modules/' . self::MODULE_NAME . '/language/' . $xoopsConfig['language'] . '/mail_template';
246
        if (!is_dir($templateDir)) {
247
            $templateDir = XOOPS_ROOT_PATH . '/modules/' . self::MODULE_NAME . '/language/english/mail_template';
248
        }
249
        $xoopsMailer->setTemplateDir($templateDir);
250
        $xoopsMailer->setTemplate($tplName);
251
        $xoopsMailer->setToEmails($recipients);
252
        // TODO: Change !
253
        // $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...
254
        //$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...
255
        $xoopsMailer->setSubject($subject);
256
        foreach ($variables as $key => $value) {
257
            $xoopsMailer->assign($key, $value);
258
        }
259
        $res = $xoopsMailer->send();
260
        unset($xoopsMailer);
261
        $filename = XOOPS_UPLOAD_PATH . '/logmail_' . self::MODULE_NAME . '.php';
262
        if (!file_exists($filename)) {
263
            $fp = @fopen($filename, 'a');
264
            if ($fp) {
265
                fwrite($fp, "<?php exit(); ?>\n");
266
                fclose($fp);
267
            }
268
        }
269
        $fp = @fopen($filename, 'a');
270
271
        if ($fp) {
272
            fwrite($fp, str_repeat('-', 120) . "\n");
273
            fwrite($fp, date('d/m/Y H:i:s') . "\n");
274
            fwrite($fp, 'Template name : ' . $tplName . "\n");
275
            fwrite($fp, 'Email subject : ' . $subject . "\n");
276
            if (is_array($recipients)) {
277
                fwrite($fp, 'Recipient(s) : ' . implode(',', $recipients) . "\n");
278
            } else {
279
                fwrite($fp, 'Recipient(s) : ' . $recipients . "\n");
280
            }
281
            fwrite($fp, 'Transmited variables : ' . implode(',', $variables) . "\n");
282
            fclose($fp);
283
        }
284
285
        return $res;
286
    }
287
288
    /**
289
     * Remove module's cache
290
     */
291
    public static function updateCache()
292
    {
293
        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...
294
        $folder  = $xoopsModule->getVar('dirname');
295
        $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...
296
        require_once XOOPS_ROOT_PATH . '/class/xoopsblock.php';
297
        require_once XOOPS_ROOT_PATH . '/class/template.php';
298
        $tplfileHandler = xoops_getHandler('tplfile');
299
        $tpllist         = $tplfileHandler->find(null, null, null, $folder);
300
        xoops_template_clear_module_cache($xoopsModule->getVar('mid')); // Clear module's blocks cache
301
302
        foreach ($tpllist as $onetemplate) { // Remove cache for each page.
303
            if ('module' === $onetemplate->getVar('tpl_type')) {
304
                //  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
305
                $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...
306
                $files_del = glob(XOOPS_CACHE_PATH . '/*' . $onetemplate->getVar('tpl_file') . '*');
307
                if (count($files_del) > 0 && is_array($files_del)) {
308
                    foreach ($files_del as $one_file) {
309
                        if (is_file($one_file)) {
310
                            unlink($one_file);
311
                        }
312
                    }
313
                }
314
            }
315
        }
316
    }
317
318
    /**
319
     * Redirect user with a message
320
     *
321
     * @param string $message message to display
322
     * @param string $url     The place where to go
323
     * @param        integer  timeout Time to wait before to redirect
324
     */
325
    public static function redirect($message = '', $url = 'index.php', $time = 2)
326
    {
327
        redirect_header($url, $time, $message);
328
        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...
329
    }
330
331
    /**
332
     * Internal function used to get the handler of the current module
333
     *
334
     * @return XoopsModule The module
335
     */
336
    protected static function _getModule()
337
    {
338
        static $mymodule;
339
        if (!isset($mymodule)) {
340
            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...
341
            if (isset($xoopsModule) && is_object($xoopsModule) && $xoopsModule->getVar('dirname') == OLEDRION_DIRNAME) {
342
                $mymodule = $xoopsModule;
343
            } else {
344
                $hModule  = xoops_getHandler('module');
345
                $mymodule = $hModule->getByDirname(OLEDRION_DIRNAME);
346
            }
347
        }
348
349
        return $mymodule;
350
    }
351
352
    /**
353
     * Returns the module's name (as defined by the user in the module manager) with cache
354
     *
355
     * @return string Module's name
356
     */
357
    public static function getModuleName()
358
    {
359
        static $moduleName;
360
        if (!isset($moduleName)) {
361
            $mymodule   = self::_getModule();
362
            $moduleName = $mymodule->getVar('name');
363
        }
364
365
        return $moduleName;
366
    }
367
368
    /**
369
     * Create a title for the href tags inside html links
370
     *
371
     * @param string $title Text to use
372
     *
373
     * @return string Formated text
374
     */
375
    public static function makeHrefTitle($title)
376
    {
377
        $s = "\"'";
378
        $r = '  ';
379
380
        return strtr($title, $s, $r);
381
    }
382
383
    /**
384
     * Retourne la liste des utilisateurs appartenants à un groupe
385
     *
386
     * @param int $groupId Searched group
387
     *
388
     * @return array Array of XoopsUsers
389
     */
390
    public static function getUsersFromGroup($groupId)
391
    {
392
        $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...
393
        $memberHandler = xoops_getHandler('member');
394
        $users          = $memberHandler->getUsersByGroup($groupId, true);
395
396
        return $users;
397
    }
398
399
    /**
400
     * Retourne la liste des emails des utilisateurs membres d'un groupe
401
     *
402
     * @param $groupId
403
     *
404
     * @internal param int $group_id Group's number
405
     * @return array Emails list
406
     */
407
    public static function getEmailsFromGroup($groupId)
408
    {
409
        $ret   = array();
410
        $users = self::getUsersFromGroup($groupId);
411
        foreach ($users as $user) {
412
            $ret[] = $user->getVar('email');
413
        }
414
415
        return $ret;
416
    }
417
418
    /**
419
     * Vérifie que l'utilisateur courant fait partie du groupe des administrateurs
420
     *
421
     * @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...
422
     */
423
    public static function isAdmin()
424
    {
425
        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...
426
        if (is_object($xoopsUser)) {
427
            if (in_array(XOOPS_GROUP_ADMIN, $xoopsUser->getGroups())) {
428
                return true;
429
            } elseif (isset($xoopsModule) && $xoopsUser->isAdmin($xoopsModule->getVar('mid'))) {
430
                return true;
431
            }
432
        }
433
434
        return false;
435
    }
436
437
    /**
438
     * Returns the current date in the Mysql format
439
     *
440
     * @return string Date in the Mysql format
441
     */
442
    public static function getCurrentSQLDate()
443
    {
444
        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...
445
    }
446
447
    /**
448
     * @return bool|string
449
     */
450
    public static function getCurrentSQLDateTime()
451
    {
452
        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...
453
    }
454
455
    /**
456
     * Convert a Mysql date to the human's format
457
     *
458
     * @param string $date The date to convert
459
     * @param string $format
460
     *
461
     * @return string The date in a human form
462
     */
463
    public static function SQLDateToHuman($date, $format = 'l')
464
    {
465
        if ($date != '0000-00-00' && xoops_trim($date) != '') {
466
            return formatTimestamp(strtotime($date), $format);
467
        } else {
468
            return '';
469
        }
470
    }
471
472
    /**
473
     * Convert a timestamp to a Mysql date
474
     *
475
     * @param integer $timestamp The timestamp to use
476
     *
477
     * @return string The date in the Mysql format
478
     */
479
    public static function timestampToMysqlDate($timestamp)
480
    {
481
        return date('Y-m-d', (int)$timestamp);
482
    }
483
484
    /**
485
     * Conversion d'un dateTime Mysql en date lisible en français
486
     *
487
     * @param $dateTime
488
     *
489
     * @return bool|string
490
     */
491
    public static function sqlDateTimeToFrench($dateTime)
492
    {
493
        return date('d/m/Y H:i:s', strtotime($dateTime));
494
    }
495
496
    /**
497
     * Convert a timestamp to a Mysql datetime form
498
     *
499
     * @param integer $timestamp The timestamp to use
500
     *
501
     * @return string The date and time in the Mysql format
502
     */
503
    public static function timestampToMysqlDateTime($timestamp)
504
    {
505
        return date('Y-m-d H:i:s', $timestamp);
506
    }
507
508
    /**
509
     * This function indicates if the current Xoops version needs to add asterisks to required fields in forms
510
     *
511
     * @return boolean Yes = we need to add them, false = no
512
     */
513
    public static function needsAsterisk()
514
    {
515
        if (self::isX23()) {
516
            return false;
517
        }
518
        if (strpos(strtolower(XOOPS_VERSION), 'impresscms') !== false) {
519
            return false;
520
        }
521
        if (false === strpos(strtolower(XOOPS_VERSION), 'legacy')) {
522
            $xv = xoops_trim(str_replace('XOOPS ', '', XOOPS_VERSION));
523
            if ((int)substr($xv, 4, 2) >= 17) {
524
                return false;
525
            }
526
        }
527
528
        return true;
529
    }
530
531
    /**
532
     * Mark the mandatory fields of a form with a star
533
     *
534
     * @param XoopsObject $sform The form to modify
535
     *
536
     * @internal param string $caracter The character to use to mark fields
537
     * @return object The modified form
538
     */
539
    public static function &formMarkRequiredFields(XoopsObject $sform)
540
    {
541
        if (self::needsAsterisk()) {
542
            $required = array();
543
            foreach ($sform->getRequired() as $item) {
544
                $required[] = $item->_name;
545
            }
546
            $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...
547
            $elements = $sform->getElements();
548
            $cnt      = count($elements);
549
            for ($i = 0; $i < $cnt; ++$i) {
550
                if (is_object($elements[$i]) && in_array($elements[$i]->_name, $required)) {
551
                    $elements[$i]->_caption .= ' *';
552
                }
553
            }
554
        }
555
556
        return $sform;
557
    }
558
559
    /**
560
     * Create an html heading (from h1 to h6)
561
     *
562
     * @param string  $title The text to use
563
     * @param integer $level Level to return
564
     *
565
     * @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...
566
     */
567
    public static function htitle($title = '', $level = 1)
568
    {
569
        printf('<h%01d>%s</h%01d>', $level, $title, $level);
570
    }
571
572
    /**
573
     * Create a unique upload filename
574
     *
575
     * @param string  $folder   The folder where the file will be saved
576
     * @param string  $fileName Original filename (coming from the user)
577
     * @param boolean $trimName Do we need to create a "short" unique name ?
578
     *
579
     * @return string The unique filename to use (with its extension)
580
     */
581
    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...
582
    {
583
        $workingfolder = $folder;
584
        if (xoops_substr($workingfolder, strlen($workingfolder) - 1, 1) !== '/') {
585
            $workingfolder .= '/';
586
        }
587
        $ext  = basename($fileName);
588
        $ext  = explode('.', $ext);
589
        $ext  = '.' . $ext[count($ext) - 1];
590
        $true = true;
591
        while ($true) {
592
            $ipbits = explode('.', $_SERVER['REMOTE_ADDR']);
593
            list($usec, $sec) = explode(' ', microtime());
594
            $usec = (integer)($usec * 65536);
595
            $sec  = ((integer)$sec) & 0xFFFF;
596
597
            if ($trimName) {
598
                $uid = sprintf('%06x%04x%04x', ($ipbits[0] << 24) | ($ipbits[1] << 16) | ($ipbits[2] << 8) | $ipbits[3], $sec, $usec);
599
            } else {
600
                $uid = sprintf('%08x-%04x-%04x', ($ipbits[0] << 24) | ($ipbits[1] << 16) | ($ipbits[2] << 8) | $ipbits[3], $sec, $usec);
601
            }
602
            if (!file_exists($workingfolder . $uid . $ext)) {
603
                $true = false;
604
            }
605
        }
606
607
        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...
608
    }
609
610
    /**
611
     * Replace html entities with their ASCII equivalent
612
     *
613
     * @param string $chaine The string undecode
614
     *
615
     * @return string The undecoded string
616
     */
617
    public static function unhtml($chaine)
618
    {
619
        $search = $replace = array();
620
        $chaine = html_entity_decode($chaine);
621
622
        for ($i = 0; $i <= 255; ++$i) {
623
            $search[]  = '&#' . $i . ';';
624
            $replace[] = chr($i);
625
        }
626
        $replace[] = '...';
627
        $search[]  = '…';
628
        $replace[] = "'";
629
        $search[]  = '‘';
630
        $replace[] = "'";
631
        $search[]  = '’';
632
        $replace[] = '-';
633
        $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...
634
        $replace[] = '—';
635
        $search[]  = '&mdash;';
636
        $replace[] = '-';
637
        $search[]  = '&ndash;';
638
        $replace[] = '-';
639
        $search[]  = '&shy;';
640
        $replace[] = '"';
641
        $search[]  = '&quot;';
642
        $replace[] = '&';
643
        $search[]  = '&amp;';
644
        $replace[] = 'ˆ';
645
        $search[]  = '&circ;';
646
        $replace[] = '¡';
647
        $search[]  = '&iexcl;';
648
        $replace[] = '¦';
649
        $search[]  = '&brvbar;';
650
        $replace[] = '¨';
651
        $search[]  = '&uml;';
652
        $replace[] = '¯';
653
        $search[]  = '&macr;';
654
        $replace[] = '´';
655
        $search[]  = '&acute;';
656
        $replace[] = '¸';
657
        $search[]  = '&cedil;';
658
        $replace[] = '¿';
659
        $search[]  = '&iquest;';
660
        $replace[] = '˜';
661
        $search[]  = '&tilde;';
662
        $replace[] = "'";
663
        $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...
664
        $replace[] = "'";
665
        $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...
666
        $replace[] = '‚';
667
        $search[]  = '&sbquo;';
668
        $replace[] = "'";
669
        $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...
670
        $replace[] = "'";
671
        $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...
672
        $replace[] = '„';
673
        $search[]  = '&bdquo;';
674
        $replace[] = '‹';
675
        $search[]  = '&lsaquo;';
676
        $replace[] = '›';
677
        $search[]  = '&rsaquo;';
678
        $replace[] = '<';
679
        $search[]  = '&lt;';
680
        $replace[] = '>';
681
        $search[]  = '&gt;';
682
        $replace[] = '±';
683
        $search[]  = '&plusmn;';
684
        $replace[] = '«';
685
        $search[]  = '&laquo;';
686
        $replace[] = '»';
687
        $search[]  = '&raquo;';
688
        $replace[] = '×';
689
        $search[]  = '&times;';
690
        $replace[] = '÷';
691
        $search[]  = '&divide;';
692
        $replace[] = '¢';
693
        $search[]  = '&cent;';
694
        $replace[] = '£';
695
        $search[]  = '&pound;';
696
        $replace[] = '¤';
697
        $search[]  = '&curren;';
698
        $replace[] = '¥';
699
        $search[]  = '&yen;';
700
        $replace[] = '§';
701
        $search[]  = '&sect;';
702
        $replace[] = '©';
703
        $search[]  = '&copy;';
704
        $replace[] = '¬';
705
        $search[]  = '&not;';
706
        $replace[] = '®';
707
        $search[]  = '&reg;';
708
        $replace[] = '°';
709
        $search[]  = '&deg;';
710
        $replace[] = 'µ';
711
        $search[]  = '&micro;';
712
        $replace[] = '¶';
713
        $search[]  = '&para;';
714
        $replace[] = '·';
715
        $search[]  = '&middot;';
716
        $replace[] = '†';
717
        $search[]  = '&dagger;';
718
        $replace[] = '‡';
719
        $search[]  = '&Dagger;';
720
        $replace[] = '‰';
721
        $search[]  = '&permil;';
722
        $replace[] = 'Euro';
723
        $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...
724
        $replace[] = '¼';
725
        $search[]  = '&frac14;';
726
        $replace[] = '½';
727
        $search[]  = '&frac12;';
728
        $replace[] = '¾';
729
        $search[]  = '&frac34;';
730
        $replace[] = '¹';
731
        $search[]  = '&sup1;';
732
        $replace[] = '²';
733
        $search[]  = '&sup2;';
734
        $replace[] = '³';
735
        $search[]  = '&sup3;';
736
        $replace[] = 'á';
737
        $search[]  = '&aacute;';
738
        $replace[] = 'Á';
739
        $search[]  = '&Aacute;';
740
        $replace[] = 'â';
741
        $search[]  = '&acirc;';
742
        $replace[] = 'Â';
743
        $search[]  = '&Acirc;';
744
        $replace[] = 'à';
745
        $search[]  = '&agrave;';
746
        $replace[] = 'À';
747
        $search[]  = '&Agrave;';
748
        $replace[] = 'å';
749
        $search[]  = '&aring;';
750
        $replace[] = 'Å';
751
        $search[]  = '&Aring;';
752
        $replace[] = 'ã';
753
        $search[]  = '&atilde;';
754
        $replace[] = 'Ã';
755
        $search[]  = '&Atilde;';
756
        $replace[] = 'ä';
757
        $search[]  = '&auml;';
758
        $replace[] = 'Ä';
759
        $search[]  = '&Auml;';
760
        $replace[] = 'ª';
761
        $search[]  = '&ordf;';
762
        $replace[] = 'æ';
763
        $search[]  = '&aelig;';
764
        $replace[] = 'Æ';
765
        $search[]  = '&AElig;';
766
        $replace[] = 'ç';
767
        $search[]  = '&ccedil;';
768
        $replace[] = 'Ç';
769
        $search[]  = '&Ccedil;';
770
        $replace[] = 'ð';
771
        $search[]  = '&eth;';
772
        $replace[] = 'Ð';
773
        $search[]  = '&ETH;';
774
        $replace[] = 'é';
775
        $search[]  = '&eacute;';
776
        $replace[] = 'É';
777
        $search[]  = '&Eacute;';
778
        $replace[] = 'ê';
779
        $search[]  = '&ecirc;';
780
        $replace[] = 'Ê';
781
        $search[]  = '&Ecirc;';
782
        $replace[] = 'è';
783
        $search[]  = '&egrave;';
784
        $replace[] = 'È';
785
        $search[]  = '&Egrave;';
786
        $replace[] = 'ë';
787
        $search[]  = '&euml;';
788
        $replace[] = 'Ë';
789
        $search[]  = '&Euml;';
790
        $replace[] = 'ƒ';
791
        $search[]  = '&fnof;';
792
        $replace[] = 'í';
793
        $search[]  = '&iacute;';
794
        $replace[] = 'Í';
795
        $search[]  = '&Iacute;';
796
        $replace[] = 'î';
797
        $search[]  = '&icirc;';
798
        $replace[] = 'Î';
799
        $search[]  = '&Icirc;';
800
        $replace[] = 'ì';
801
        $search[]  = '&igrave;';
802
        $replace[] = 'Ì';
803
        $search[]  = '&Igrave;';
804
        $replace[] = 'ï';
805
        $search[]  = '&iuml;';
806
        $replace[] = 'Ï';
807
        $search[]  = '&Iuml;';
808
        $replace[] = 'ñ';
809
        $search[]  = '&ntilde;';
810
        $replace[] = 'Ñ';
811
        $search[]  = '&Ntilde;';
812
        $replace[] = 'ó';
813
        $search[]  = '&oacute;';
814
        $replace[] = 'Ó';
815
        $search[]  = '&Oacute;';
816
        $replace[] = 'ô';
817
        $search[]  = '&ocirc;';
818
        $replace[] = 'Ô';
819
        $search[]  = '&Ocirc;';
820
        $replace[] = 'ò';
821
        $search[]  = '&ograve;';
822
        $replace[] = 'Ò';
823
        $search[]  = '&Ograve;';
824
        $replace[] = 'º';
825
        $search[]  = '&ordm;';
826
        $replace[] = 'ø';
827
        $search[]  = '&oslash;';
828
        $replace[] = 'Ø';
829
        $search[]  = '&Oslash;';
830
        $replace[] = 'õ';
831
        $search[]  = '&otilde;';
832
        $replace[] = 'Õ';
833
        $search[]  = '&Otilde;';
834
        $replace[] = 'ö';
835
        $search[]  = '&ouml;';
836
        $replace[] = 'Ö';
837
        $search[]  = '&Ouml;';
838
        $replace[] = 'œ';
839
        $search[]  = '&oelig;';
840
        $replace[] = 'Œ';
841
        $search[]  = '&OElig;';
842
        $replace[] = 'š';
843
        $search[]  = '&scaron;';
844
        $replace[] = 'Š';
845
        $search[]  = '&Scaron;';
846
        $replace[] = 'ß';
847
        $search[]  = '&szlig;';
848
        $replace[] = 'þ';
849
        $search[]  = '&thorn;';
850
        $replace[] = 'Þ';
851
        $search[]  = '&THORN;';
852
        $replace[] = 'ú';
853
        $search[]  = '&uacute;';
854
        $replace[] = 'Ú';
855
        $search[]  = '&Uacute;';
856
        $replace[] = 'û';
857
        $search[]  = '&ucirc;';
858
        $replace[] = 'Û';
859
        $search[]  = '&Ucirc;';
860
        $replace[] = 'ù';
861
        $search[]  = '&ugrave;';
862
        $replace[] = 'Ù';
863
        $search[]  = '&Ugrave;';
864
        $replace[] = 'ü';
865
        $search[]  = '&uuml;';
866
        $replace[] = 'Ü';
867
        $search[]  = '&Uuml;';
868
        $replace[] = 'ý';
869
        $search[]  = '&yacute;';
870
        $replace[] = 'Ý';
871
        $search[]  = '&Yacute;';
872
        $replace[] = 'ÿ';
873
        $search[]  = '&yuml;';
874
        $replace[] = 'Ÿ';
875
        $search[]  = '&Yuml;';
876
        $chaine    = str_replace($search, $replace, $chaine);
877
878
        return $chaine;
879
    }
880
881
    /**
882
     * Create a title to be used by the url rewriting
883
     *
884
     * @param string  $content The text to use to create the url
885
     * @param integer $urw     The lower limit to create words
886
     *
887
     * @return string The text to use for the url
888
     *                Note, some parts are from Solo's code
889
     */
890
    public static function makeSeoUrl($content, $urw = 1)
891
    {
892
        $s       = "ÀÁÂÃÄÅÒÓÔÕÖØÈÉÊËÇÌÍÎÏÙÚÛܟÑàáâãäåòóôõöøèéêëçìíîïùúûüÿñ '()";
893
        $r       = 'AAAAAAOOOOOOEEEECIIIIUUUUYNaaaaaaooooooeeeeciiiiuuuuyn----';
894
        $content = self::unhtml($content); // First, remove html entities
895
        $content = strtr($content, $s, $r);
896
        $content = strip_tags($content);
897
        $content = strtolower($content);
898
        $content = htmlentities($content); // TODO: Vérifier
899
        $content = preg_replace('/&([a-zA-Z])(uml|acute|grave|circ|tilde);/', '$1', $content);
900
        $content = html_entity_decode($content);
901
        $content = preg_replace('/quot/i', ' ', $content);
902
        $content = preg_replace("/'/i", ' ', $content);
903
        $content = preg_replace('/-/i', ' ', $content);
904
        $content = preg_replace('/[[:punct:]]/i', '', $content);
905
906
        // Selon option mais attention au fichier .htaccess !
907
        // $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...
908
        $content = preg_replace('/[^a-z|A-Z|0-9]/', '-', $content);
909
910
        $words    = explode(' ', $content);
911
        $keywords = '';
912
        foreach ($words as $word) {
913
            if (strlen($word) >= $urw) {
914
                $keywords .= '-' . trim($word);
915
            }
916
        }
917
        if (!$keywords) {
918
            $keywords = '-';
919
        }
920
        // Supprime les tirets en double
921
        $keywords = str_replace('---', '-', $keywords);
922
        $keywords = str_replace('--', '-', $keywords);
923
        // Supprime un éventuel tiret à la fin de la chaine
924
        if ('-' === substr($keywords, strlen($keywords) - 1, 1)) {
925
            $keywords = substr($keywords, 0, -1);
926
        }
927
928
        return $keywords;
929
    }
930
931
    /**
932
     * Create the meta keywords based on the content
933
     *
934
     * @param string $content Content from which we have to create metakeywords
935
     *
936
     * @return string The list of meta keywords
937
     */
938
    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...
939
    {
940
        $keywordscount = self::getModuleOption('metagen_maxwords');
941
        $keywordsorder = self::getModuleOption('metagen_order');
942
943
        $tmp = array();
944
        // Search for the "Minimum keyword length"
945
        if (isset($_SESSION['oledrion_keywords_limit'])) {
946
            $limit = $_SESSION['oledrion_keywords_limit'];
947
        } else {
948
            $configHandler                      = xoops_getHandler('config');
949
            $xoopsConfigSearch                   = $configHandler->getConfigsByCat(XOOPS_CONF_SEARCH);
950
            $limit                               = $xoopsConfigSearch['keyword_min'];
951
            $_SESSION['oledrion_keywords_limit'] = $limit;
952
        }
953
        $myts            = MyTextSanitizer::getInstance();
954
        $content         = str_replace('<br>', ' ', $content);
955
        $content         = $myts->undoHtmlSpecialChars($content);
956
        $content         = strip_tags($content);
957
        $content         = strtolower($content);
958
        $search_pattern  = array('&nbsp;', "\t", "\r\n", "\r", "\n", ',', '.', "'", ';', ':', ')', '(', '"', '?', '!', '{', '}', '[', ']', '<', '>', '/', '+', '-', '_', '\\', '*');
959
        $replace_pattern = array(' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '');
960
        $content         = str_replace($search_pattern, $replace_pattern, $content);
961
        $keywords        = explode(' ', $content);
962
        switch ($keywordsorder) {
963
            case 0: // Ordre d'apparition dans le texte
964
                $keywords = array_unique($keywords);
965
                break;
966
            case 1: // Ordre de fréquence des mots
967
                $keywords = array_count_values($keywords);
968
                asort($keywords);
969
                $keywords = array_keys($keywords);
970
                break;
971
            case 2: // Ordre inverse de la fréquence des mots
972
                $keywords = array_count_values($keywords);
973
                arsort($keywords);
974
                $keywords = array_keys($keywords);
975
                break;
976
        }
977
        // Remove black listed words
978
        if (xoops_trim(self::getModuleOption('metagen_blacklist')) !== '') {
979
            $metagen_blacklist = str_replace("\r", '', self::getModuleOption('metagen_blacklist'));
980
            $metablack         = explode("\n", $metagen_blacklist);
981
            array_walk($metablack, 'trim');
982
            $keywords = array_diff($keywords, $metablack);
983
        }
984
985
        foreach ($keywords as $keyword) {
986
            if (strlen($keyword) >= $limit && !is_numeric($keyword)) {
987
                $tmp[] = $keyword;
988
            }
989
        }
990
        $tmp = array_slice($tmp, 0, $keywordscount);
991
        if (count($tmp) > 0) {
992
            return implode(',', $tmp);
993
        } else {
994
            if (!isset($configHandler) || !is_object($configHandler)) {
995
                $configHandler = xoops_getHandler('config');
996
            }
997
            $xoopsConfigMetaFooter = $configHandler->getConfigsByCat(XOOPS_CONF_METAFOOTER);
998
            if (isset($xoopsConfigMetaFooter['meta_keywords'])) {
999
                return $xoopsConfigMetaFooter['meta_keywords'];
1000
            } else {
1001
                return '';
1002
            }
1003
        }
1004
    }
1005
1006
    /**
1007
     * Fonction chargée de gérer l'upload
1008
     *
1009
     * @param integer $indice L'indice du fichier à télécharger
1010
     * @param string  $dstpath
1011
     * @param null    $mimeTypes
1012
     * @param null    $uploadMaxSize
1013
     * @param null    $maxWidth
1014
     * @param null    $maxHeight
1015
     *
1016
     * @return mixed True si l'upload s'est bien déroulé sinon le message d'erreur correspondant
1017
     */
1018
    public static function uploadFile(
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...
1019
        $indice,
1020
        $dstpath = XOOPS_UPLOAD_PATH,
1021
        $mimeTypes = null,
1022
        $uploadMaxSize = null,
1023
        $maxWidth = null,
1024
        $maxHeight = null
1025
    ) {
1026
        require_once XOOPS_ROOT_PATH . '/class/uploader.php';
1027
        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...
1028
        if (isset($_POST['xoops_upload_file'])) {
1029
            require_once XOOPS_ROOT_PATH . '/class/uploader.php';
1030
            $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...
1031
            $fldname = $_FILES[$_POST['xoops_upload_file'][$indice]];
1032
            $fldname = $fldname['name'];
1033
            if (xoops_trim($fldname !== '')) {
1034
                $destname = self::createUploadName($dstpath, $fldname, true);
1035
                if (null === $mimeTypes) {
1036
                    $permittedtypes = explode("\n", str_replace("\r", '', self::getModuleOption('mimetypes')));
1037
                    array_walk($permittedtypes, 'trim');
1038
                } else {
1039
                    $permittedtypes = $mimeTypes;
1040
                }
1041
                $uploadSize = null === $uploadMaxSize ? self::getModuleOption('maxuploadsize') : $uploadMaxSize;
1042
                $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...
1043
                //$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...
1044
                $uploader->setTargetFileName($destname);
1045
                if ($uploader->fetchMedia($_POST['xoops_upload_file'][$indice])) {
1046
                    if ($uploader->upload()) {
1047
                        return true;
1048
                    } else {
1049
                        return _ERRORS . ' ' . htmlentities($uploader->getErrors());
1050
                    }
1051
                } else {
1052
                    return htmlentities($uploader->getErrors());
1053
                }
1054
            } else {
1055
                return false;
1056
            }
1057
        } else {
1058
            return false;
1059
        }
1060
    }
1061
1062
    /**
1063
     * Resize a Picture to some given dimensions (using the wideImage library)
1064
     *
1065
     * @param string  $src_path      Picture's source
1066
     * @param string  $dst_path      Picture's destination
1067
     * @param integer $param_width   Maximum picture's width
1068
     * @param integer $param_height  Maximum picture's height
1069
     * @param boolean $keep_original Do we have to keep the original picture ?
1070
     * @param string  $fit           Resize mode (see the wideImage library for more information)
1071
     *
1072
     * @return bool
1073
     */
1074
    public static function resizePicture(
1075
        $src_path,
1076
        $dst_path,
1077
        $param_width,
1078
        $param_height,
1079
        $keep_original = false,
1080
        $fit = 'inside'
1081
    ) {
1082
        //        require_once OLEDRION_PATH . 'class/wideimage/WideImage.inc.php';
1083
        $resize = true;
1084
        if (OLEDRION_DONT_RESIZE_IF_SMALLER) {
1085
            $pictureDimensions = getimagesize($src_path);
1086
            if (is_array($pictureDimensions)) {
1087
                $width  = $pictureDimensions[0];
1088
                $height = $pictureDimensions[1];
1089
                if ($width < $param_width && $height < $param_height) {
1090
                    $resize = false;
1091
                }
1092
            }
1093
        }
1094
1095
        $img = WideImage::load($src_path);
1096
        if ($resize) {
1097
            $result = $img->resize($param_width, $param_height, $fit);
1098
            $result->saveToFile($dst_path);
1099
        } else {
1100
            @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...
1101
        }
1102
1103
        if (!$keep_original) {
1104
            @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...
1105
        }
1106
1107
        return true;
1108
    }
1109
1110
    /**
1111
     * Déclenchement d'une alerte Xoops suite à un évènement
1112
     *
1113
     * @param string       $category La catégorie de l'évènement
1114
     * @param integer      $itemId   L'ID de l'élément (trop général pour être décris précisément)
1115
     * @param unknown_type $event    L'évènement qui est déclencé
1116
     * @param unknown_type $tags     Les variables à passer au template
1117
     */
1118
    public static function notify($category, $itemId, $event, $tags)
1119
    {
1120
        $notificationHandler = xoops_getHandler('notification');
1121
        $tags['X_MODULE_URL'] = OLEDRION_URL;
1122
        $notificationHandler->triggerEvent($category, $itemId, $event, $tags);
1123
    }
1124
1125
    /**
1126
     * Ajoute des jours à une date et retourne la nouvelle date au format Date de Mysql
1127
     *
1128
     * @param int     $duration
1129
     * @param integer $startingDate Date de départ (timestamp)
1130
     *
1131
     * @internal param int $durations Durée en jours
1132
     * @return bool|string
1133
     */
1134
    public static function addDaysToDate($duration = 1, $startingDate = 0)
1135
    {
1136
        if ($startingDate == 0) {
1137
            $startingDate = time();
1138
        }
1139
        $endingDate = $startingDate + ($duration * 86400);
1140
1141
        return date('Y-m-d', $endingDate);
1142
    }
1143
1144
    /**
1145
     * Retourne un breadcrumb en fonction des paramètres passés et en partant (d'office) de la racine du module
1146
     *
1147
     * @param array  $path  Le chemin complet (excepté la racine) du breadcrumb sous la forme clé=url valeur=titre
1148
     * @param string $raquo Le séparateur par défaut à utiliser
1149
     *
1150
     * @return string le breadcrumb
1151
     */
1152
    public static function breadcrumb($path, $raquo = ' &raquo; ')
1153
    {
1154
        $breadcrumb        = '';
1155
        $workingBreadcrumb = array();
1156
        if (is_array($path)) {
1157
            $moduleName          = self::getModuleName();
1158
            $workingBreadcrumb[] = "<a href='" . OLEDRION_URL . "' title='" . self::makeHrefTitle($moduleName) . "'>" . $moduleName . '</a>';
1159
            foreach ($path as $url => $title) {
1160
                $workingBreadcrumb[] = "<a href='" . $url . "'>" . $title . '</a>';
1161
            }
1162
            $cnt = count($workingBreadcrumb);
1163
            for ($i = 0; $i < $cnt; ++$i) {
1164
                if ($i == $cnt - 1) {
1165
                    $workingBreadcrumb[$i] = strip_tags($workingBreadcrumb[$i]);
1166
                }
1167
            }
1168
            $breadcrumb = implode($raquo, $workingBreadcrumb);
1169
        }
1170
1171
        return $breadcrumb;
1172
    }
1173
1174
    /**
1175
     * @param $string
1176
     *
1177
     * @return string
1178
     */
1179
    public static function close_tags($string)
1180
    {
1181
        // match opened tags
1182
        if (preg_match_all('/<([a-z\:\-]+)[^\/]>/', $string, $start_tags)) {
1183
            $start_tags = $start_tags[1];
1184
1185
            // match closed tags
1186
            if (preg_match_all('/<\/([a-z]+)>/', $string, $end_tags)) {
1187
                $complete_tags = array();
1188
                $end_tags      = $end_tags[1];
1189
1190
                foreach ($start_tags as $key => $val) {
1191
                    $posb = array_search($val, $end_tags);
1192
                    if (is_int($posb)) {
1193
                        unset($end_tags[$posb]);
1194
                    } else {
1195
                        $complete_tags[] = $val;
1196
                    }
1197
                }
1198
            } else {
1199
                $complete_tags = $start_tags;
1200
            }
1201
1202
            $complete_tags = array_reverse($complete_tags);
1203
            for ($i = 0, $iMax = count($complete_tags); $i < $iMax; ++$i) {
1204
                $string .= '</' . $complete_tags[$i] . '>';
1205
            }
1206
        }
1207
1208
        return $string;
1209
    }
1210
1211
    /**
1212
     * @param        $string
1213
     * @param int    $length
1214
     * @param string $etc
1215
     * @param bool   $break_words
1216
     *
1217
     * @return mixed|string
1218
     */
1219
    public static function truncate_tagsafe($string, $length = 80, $etc = '...', $break_words = false)
1220
    {
1221
        if ($length == 0) {
1222
            return '';
1223
        }
1224
1225
        if (strlen($string) > $length) {
1226
            $length -= strlen($etc);
1227
            if (!$break_words) {
1228
                $string = preg_replace('/\s+?(\S+)?$/', '', substr($string, 0, $length + 1));
1229
                $string = preg_replace('/<[^>]*$/', '', $string);
1230
                $string = self::close_tags($string);
1231
            }
1232
1233
            return $string . $etc;
1234
        } else {
1235
            return $string;
1236
        }
1237
    }
1238
1239
    /**
1240
     * Create an infotip
1241
     * @param $text
1242
     * @return string
1243
     */
1244
    public static function makeInfotips($text)
1245
    {
1246
        $ret      = '';
1247
        $infotips = self::getModuleOption('infotips');
1248
        if ($infotips > 0) {
1249
            $myts = MyTextSanitizer::getInstance();
1250
            $ret  = $myts->htmlSpecialChars(xoops_substr(strip_tags($text), 0, $infotips));
1251
        }
1252
1253
        return $ret;
1254
    }
1255
1256
    /**
1257
     * Mise en place de l'appel à la feuille de style du module dans le template
1258
     * @param string $url
1259
     */
1260
    public static function setCSS($url = '')
1261
    {
1262
        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...
1263
        if ('' === $url) {
1264
            $url = OLEDRION_URL . 'css/oledrion.css';
1265
        }
1266
1267
        if (!is_object($xoTheme)) {
1268
            $xoopsTpl->assign('xoops_module_header', $xoopsTpl->get_template_vars('xoops_module_header') . "<link rel=\"stylesheet\" type=\"text/css\" href=\"$url\" />");
1269
        } else {
1270
            $xoTheme->addStylesheet($url);
1271
        }
1272
    }
1273
1274
    /**
1275
     * Mise en place de l'appel à la feuille de style du module dans le template
1276
     * @param string $language
1277
     */
1278
    public static function setLocalCSS($language = 'english')
1279
    {
1280
        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...
1281
1282
        $localcss = OLEDRION_URL . 'language/' . $language . '/style.css';
1283
1284
        if (!is_object($xoTheme)) {
1285
            $xoopsTpl->assign('xoops_module_header', $xoopsTpl->get_template_vars('xoops_module_header') . "<link rel=\"stylesheet\" type=\"text/css\" href=\"$localcss\" />");
1286
        } else {
1287
            $xoTheme->addStylesheet($localcss);
1288
        }
1289
    }
1290
1291
    /**
1292
     * Calcul du TTC à partir du HT et de la TVA
1293
     *
1294
     * @param float   $ht     Montant HT
1295
     * @param float   $vat    Taux de TVA
1296
     * @param boolean $edit   Si faux alors le montant est formaté pour affichage sinon il reste tel quel
1297
     * @param string  $format Format d'affichage du résultat (long ou court)
1298
     *
1299
     * @return mixed Soit une chaine soit un flottant
1300
     */
1301
    public static function getTTC($ht, $vat, $edit = false, $format = 's')
1302
    {
1303
        $oledrion_Currency = Oledrion_Currency::getInstance();
1304
        $ttc               = $ht * (1 + ($vat / 100));
1305
        if (!$edit) {
1306
            return $oledrion_Currency->amountForDisplay($ttc, $format);
1307
        } else {
1308
            return $ttc;
1309
        }
1310
    }
1311
1312
    /**
1313
     * Renvoie le montant de la tva à partir du montant HT
1314
     * @param $ht
1315
     * @param $vat
1316
     * @return float
1317
     */
1318
    public static function getVAT($ht, $vat)
1319
    {
1320
        return (float)($ht * $vat);
1321
    }
1322
1323
    /**
1324
     * Retourne le montant TTC
1325
     *
1326
     * @param floatval $product_price Le montant du produit
1327
     * @param integer  $vat_id        Le numéro de TVA
1328
     *
1329
     * @return floatval Le montant TTC si on a trouvé sa TVA sinon
1330
     */
1331
    public static function getAmountWithVat($product_price, $vat_id)
1332
    {
1333
        static $vats = array();
1334
        $vat_rate = null;
1335
        if (is_array($vats) && in_array($vat_id, $vats)) {
1336
            $vat_rate = $vats[$vat_id];
1337
        } else {
1338
            $handlers = OledrionHandler::getInstance();
1339
            $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...
1340
            $vat      = $handlers->h_oledrion_vat->get($vat_id);
1341
            if (is_object($vat)) {
1342
                $vat_rate      = $vat->getVar('vat_rate', 'e');
1343
                $vats[$vat_id] = $vat_rate;
1344
            }
1345
        }
1346
1347
        if (!null === $vat_rate) {
1348
            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 XoopstubeUtility::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...
1349
        } else {
1350
            return $product_price;
1351
        }
1352
    }
1353
1354
    /**
1355
     * @param $datastream
1356
     * @param $url
1357
     *
1358
     * @return string
1359
     */
1360
    public static function postIt($datastream, $url)
1361
    {
1362
        $url     = preg_replace('@^http://@i', '', $url);
1363
        $host    = substr($url, 0, strpos($url, '/'));
1364
        $uri     = strstr($url, '/');
1365
        $reqbody = '';
1366
        foreach ($datastream as $key => $val) {
1367
            if (!empty($reqbody)) {
1368
                $reqbody .= '&';
1369
            }
1370
            $reqbody .= $key . '=' . urlencode($val);
1371
        }
1372
        $contentlength = strlen($reqbody);
1373
        $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";
1374
1375
        return $reqheader;
1376
    }
1377
1378
    /**
1379
     * Returns the mime type of a file using first finfo then mime_content
1380
     *     
1381
     * @param String $ filename The file (with full path) that you want to know the mime type
1382
     * @return string
1383
     */
1384
    public static function getMimeType($filename)
1385
    {
1386
        if (function_exists('finfo_open')) {
1387
            $finfo    = finfo_open();
1388
            $mimetype = finfo_file($finfo, $filename, FILEINFO_MIME_TYPE);
1389
            finfo_close($finfo);
1390
1391
            return $mimetype;
1392
        } else {
1393
            if (function_exists('mime_content_type')) {
1394
                return mime_content_type($filename);
1395
            } else {
1396
                return '';
1397
            }
1398
        }
1399
    }
1400
1401
    /**
1402
     * Retourne un criteria compo qui permet de filtrer les produits sur le mois courant
1403
     *
1404
     * @return object
1405
     */
1406
    public static function getThisMonthCriteria()
1407
    {
1408
        $start             = mktime(0, 1, 0, date('n'), date('j'), date('Y'));
1409
        $end               = mktime(0, 0, 0, date('n'), date('t'), date('Y'));
1410
        $criteriaThisMonth = new CriteriaCompo();
1411
        $criteriaThisMonth->add(new Criteria('product_submitted', $start, '>='));
1412
        $criteriaThisMonth->add(new Criteria('product_submitted', $end, '<='));
1413
1414
        return $criteriaThisMonth;
1415
    }
1416
1417
    /**
1418
     * Retourne une liste d'objets XoopsUsers à partir d'une liste d'identifiants
1419
     *
1420
     * @param array $xoopsUsersIDs La liste des ID
1421
     *
1422
     * @return array Les objets XoopsUsers
1423
     */
1424
    public static function getUsersFromIds($xoopsUsersIDs)
1425
    {
1426
        $users = array();
1427
        if (is_array($xoopsUsersIDs) && count($xoopsUsersIDs) > 0) {
1428
            $xoopsUsersIDs = array_unique($xoopsUsersIDs);
1429
            sort($xoopsUsersIDs);
1430
            if (count($xoopsUsersIDs) > 0) {
1431
                $memberHandler = xoops_getHandler('user');
1432
                $criteria       = new Criteria('uid', '(' . implode(',', $xoopsUsersIDs) . ')', 'IN');
1433
                $criteria->setSort('uid');
1434
                $users = $memberHandler->getObjects($criteria, true);
1435
            }
1436
        }
1437
1438
        return $users;
1439
    }
1440
1441
    /**
1442
     * Retourne l'ID de l'utilisateur courant (s'il est connecté)
1443
     *
1444
     * @return integer L'uid ou 0
1445
     */
1446
    public static function getCurrentUserID()
1447
    {
1448
        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...
1449
        $uid = is_object($xoopsUser) ? $xoopsUser->getVar('uid') : 0;
1450
1451
        return $uid;
1452
    }
1453
1454
    /**
1455
     * Retourne la liste des groupes de l'utilisateur courant (avec cache)
1456
     *
1457
     * @param int $uid
1458
     *
1459
     * @return array Les ID des groupes auquel l'utilisateur courant appartient
1460
     */
1461
    public static function getMemberGroups($uid = 0)
1462
    {
1463
        static $buffer = array();
1464
        if ($uid == 0) {
1465
            $uid = self::getCurrentUserID();
1466
        }
1467
1468
        if (is_array($buffer) && count($buffer) > 0 && isset($buffer[$uid])) {
1469
            return $buffer[$uid];
1470
        } else {
1471
            if ($uid > 0) {
1472
                $memberHandler = xoops_getHandler('member');
1473
                $buffer[$uid]   = $memberHandler->getGroupsByUser($uid, false); // Renvoie un tableau d'ID (de groupes)
1474
            } else {
1475
                $buffer[$uid] = array(XOOPS_GROUP_ANONYMOUS);
1476
            }
1477
        }
1478
1479
        return $buffer[$uid];
1480
    }
1481
1482
    /**
1483
     * Indique si l'utilisateur courant fait partie d'une groupe donné (avec gestion de cache)
1484
     *
1485
     * @param integer $group Groupe recherché
1486
     * @param int     $uid
1487
     *
1488
     * @return boolean vrai si l'utilisateur fait partie du groupe, faux sinon
1489
     */
1490
    public static function isMemberOfGroup($group = 0, $uid = 0)
1491
    {
1492
        static $buffer = array();
1493
        $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...
1494
        if ($uid == 0) {
1495
            $uid = self::getCurrentUserID();
1496
        }
1497
        if (is_array($buffer) && array_key_exists($group, $buffer)) {
1498
            $retval = $buffer[$group];
1499
        } else {
1500
            $memberHandler = xoops_getHandler('member');
1501
            $groups         = $memberHandler->getGroupsByUser($uid, false); // Renvoie un tableau d'ID (de groupes)
1502
            $retval         = in_array($group, $groups);
1503
            $buffer[$group] = $retval;
1504
        }
1505
1506
        return $retval;
1507
    }
1508
1509
    /**
1510
     * Function responsible for verifying that a directory exists, we can write in and create an index.html file
1511
     *
1512
     * @param String $ folder The full directory to verify
1513
     *
1514
     */
1515
    public static function prepareFolder($folder)
1516
    {
1517
        if (!is_dir($folder)) {
1518
            mkdir($folder);
1519
            file_put_contents($folder . '/index.html', '<script>history.go(-1);</script>');
1520
        }
1521
        //        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...
1522
    }
1523
1524
    /**
1525
     * Duplicate a file in local
1526
     *
1527
     * @param string $path     The file's path
1528
     * @param string $filename The filename
1529
     *
1530
     * @return mixed If the copy succeed, the new filename else false
1531
     * @since 2.1
1532
     */
1533
    public static function duplicateFile($path, $filename)
1534
    {
1535
        $newName = self::createUploadName($path, $filename);
1536
        if (copy($path . DIRECTORY_SEPARATOR . $filename, $path . DIRECTORY_SEPARATOR . $newName)) {
1537
            return $newName;
1538
        } else {
1539
            return false;
1540
        }
1541
    }
1542
1543
    /**
1544
     * Load a language file
1545
     *
1546
     * @param string $languageFile     The required language file
1547
     * @param string $defaultExtension Default extension to use
1548
     *
1549
     * @since 2.2.2009.02.13
1550
     */
1551
    public static function loadLanguageFile($languageFile, $defaultExtension = '.php')
1552
    {
1553
        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...
1554
        $root = OLEDRION_PATH;
1555
        if (false === strpos($languageFile, $defaultExtension)) {
1556
            $languageFile .= $defaultExtension;
1557
        }
1558
        if (file_exists($root . 'language' . DIRECTORY_SEPARATOR . $xoopsConfig['language'] . DIRECTORY_SEPARATOR . $languageFile)) {
1559
            require_once $root . 'language' . DIRECTORY_SEPARATOR . $xoopsConfig['language'] . DIRECTORY_SEPARATOR . $languageFile;
1560
        } else { // Fallback
1561
            require_once $root . 'language' . DIRECTORY_SEPARATOR . 'english' . DIRECTORY_SEPARATOR . $languageFile;
1562
        }
1563
    }
1564
1565
    /**
1566
     * Formatage d'un floattant pour la base de données
1567
     *
1568
     * @param float    Le montant à formater
1569
     *
1570
     * @return string le montant formaté
1571
     * @since 2.2.2009.02.25
1572
     */
1573
    public static function formatFloatForDB($amount)
1574
    {
1575
        return number_format($amount, 2, '.', '');
1576
    }
1577
1578
    /**
1579
     * Appelle un fichier Javascript à la manière de Xoops
1580
     *
1581
     * @note, l'url complète ne doit pas être fournie, la méthode se charge d'ajouter
1582
     * le chemin vers le répertoire js en fonction de la requête, c'est à dire que si
1583
     * on appelle un fichier de langue, la méthode ajoute l'url vers le répertoire de
1584
     * langue, dans le cas contraire on ajoute l'url vers le répertoire JS du module.
1585
     *
1586
     * @param string $javascriptFile
1587
     * @param bool   $inLanguageFolder
1588
     * @param bool   $oldWay
1589
     *
1590
     * @return void
1591
     * @since 2.3.2009.03.14
1592
     */
1593
    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...
1594
    {
1595
        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...
1596
        $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...
1597
        if ($inLanguageFolder) {
1598
            $root    = OLEDRION_PATH;
1599
            $rootUrl = OLEDRION_URL;
1600
            if (file_exists($root . 'language' . DIRECTORY_SEPARATOR . $xoopsConfig['language'] . DIRECTORY_SEPARATOR . $javascriptFile)) {
1601
                $fileToCall = $rootUrl . 'language/' . $xoopsConfig['language'] . '/' . $javascriptFile;
1602
            } else { // Fallback
1603
                $fileToCall = $rootUrl . 'language/english/' . $javascriptFile;
1604
            }
1605
        } else {
1606
            $fileToCall = OLEDRION_JS_URL . $javascriptFile;
1607
        }
1608
1609
        $xoTheme->addScript('browse.php?Frameworks/jquery/jquery.js');
1610
        $xoTheme->addScript($fileToCall);
1611
    }
1612
1613
    /**
1614
     * Create the <option> of an html select
1615
     *
1616
     * @param array $array   Array of index and labels
1617
     * @param mixed $default the default value
1618
     * @param bool  $withNull
1619
     *
1620
     * @return string
1621
     * @since 2.3.2009.03.13
1622
     */
1623
    public static function htmlSelectOptions($array, $default = 0, $withNull = true)
1624
    {
1625
        $ret      = array();
1626
        $selected = '';
1627
        if ($withNull) {
1628
            if (0 === $default) {
1629
                $selected = " selected = 'selected'";
1630
            }
1631
            $ret[] = '<option value=0' . $selected . '>---</option>';
1632
        }
1633
1634
        foreach ($array as $index => $label) {
1635
            $selected = '';
1636
            if ($index == $default) {
1637
                $selected = " selected = 'selected'";
1638
            }
1639
            $ret[] = '<option value="' . $index . '"' . $selected . '>' . $label . '</option>';
1640
        }
1641
1642
        return implode("\n", $ret);
1643
    }
1644
1645
    /**
1646
     * Creates an html select
1647
     *
1648
     * @param string  $selectName Selector's name
1649
     * @param array   $array      Options
1650
     * @param mixed   $default    Default's value
1651
     * @param boolean $withNull   Do we include a null option ?
1652
     *
1653
     * @return string
1654
     * @since 2.3.2009.03.13
1655
     */
1656
    public static function htmlSelect($selectName, $array, $default, $withNull = true)
1657
    {
1658
        $ret = '';
1659
        $ret .= "<select name='" . $selectName . "' id='" . $selectName . "'>\n";
1660
        $ret .= self::htmlSelectOptions($array, $default, $withNull);
1661
        $ret .= "</select>\n";
1662
1663
        return $ret;
1664
    }
1665
1666
    /**
1667
     * Extrait l'id d'une chaine formatée sous la forme xxxx-99 (duquel on récupère 99)
1668
     *
1669
     * @note: utilisé par les attributs produits
1670
     *
1671
     * @param string $string    La chaine de travail
1672
     * @param string $separator Le séparateur
1673
     *
1674
     * @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...
1675
     */
1676
    public static function getId($string, $separator = '_')
1677
    {
1678
        $pos = strrpos($string, $separator);
1679
        if ($pos === false) {
1680
            return $string;
1681
        } else {
1682
            return (int)substr($string, $pos + 1);
1683
        }
1684
    }
1685
1686
    /**
1687
     * Fonction "inverse" de getId (depuis xxxx-99 on récupère xxxx)
1688
     *
1689
     * @note: utilisé par les attributs produits
1690
     *
1691
     * @param string $string    La chaine de travail
1692
     * @param string $separator Le séparateur
1693
     *
1694
     * @return string
1695
     */
1696
    public static function getName($string, $separator = '_')
1697
    {
1698
        $pos = strrpos($string, $separator);
1699
        return false === $pos ? $string : substr($string, 0, $pos);
1700
    }
1701
1702
    /**
1703
     * Renvoie un montant nul si le montant est négatif
1704
     *
1705
     * @param float $amount
1706
     *
1707
     * @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...
1708
     */
1709
    public static function doNotAcceptNegativeAmounts(&$amount)
1710
    {
1711
        if ($amount < 0.00) {
1712
            $amount = 0.00;
1713
        }
1714
    }
1715
1716
    /**
1717
     * Returns a string from the request
1718
     *
1719
     * @param string $valueName    Name of the parameter you want to get
1720
     * @param mixed  $defaultValue Default value to return if the parameter is not set in the request
1721
     *
1722
     * @return mixed
1723
     */
1724
    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...
1725
    {
1726
        return isset($_REQUEST[$valueName]) ? $_REQUEST[$valueName] : $defaultValue;
1727
    }
1728
1729
    /**
1730
     * Verify that a mysql table exists
1731
     *
1732
     * @package       Oledrion
1733
     * @author        Instant Zero (http://xoops.instant-zero.com)
1734
     * @copyright (c) Instant Zero
1735
     * @param $tablename
1736
     * @return bool
1737
     */
1738
    public static function tableExists($tablename)
1739
    {
1740
        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...
1741
        $result = $xoopsDB->queryF("SHOW TABLES LIKE '$tablename'");
1742
1743
        return ($xoopsDB->getRowsNum($result) > 0);
1744
    }
1745
1746
    /**
1747
     * Verify that a field exists inside a mysql table
1748
     *
1749
     * @package       Oledrion
1750
     * @author        Instant Zero (http://xoops.instant-zero.com)
1751
     * @copyright (c) Instant Zero
1752
     * @param $fieldname
1753
     * @param $table
1754
     * @return bool
1755
     */
1756
    public static function fieldExists($fieldname, $table)
1757
    {
1758
        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...
1759
        $result = $xoopsDB->queryF("SHOW COLUMNS FROM $table LIKE '$fieldname'");
1760
1761
        return ($xoopsDB->getRowsNum($result) > 0);
1762
    }
1763
1764
    /**
1765
     * Retourne la définition d'un champ
1766
     *
1767
     * @param string $fieldname
1768
     * @param string $table
1769
     *
1770
     * @return array
1771
     */
1772
    public static function getFieldDefinition($fieldname, $table)
1773
    {
1774
        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...
1775
        $result = $xoopsDB->queryF("SHOW COLUMNS FROM $table LIKE '$fieldname'");
1776
        if ($result) {
1777
            return $xoopsDB->fetchArray($result);
1778
        }
1779
1780
        return '';
0 ignored issues
show
Bug Best Practice introduced by
The return type of return ''; (string) is incompatible with the return type documented by XoopstubeUtility::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...
1781
    }
1782
1783
    /**
1784
     * Add a field to a mysql table
1785
     *
1786
     * @package       Oledrion
1787
     * @author        Instant Zero (http://xoops.instant-zero.com)
1788
     * @copyright (c) Instant Zero
1789
     * @param $field
1790
     * @param $table
1791
     * @return mixed
1792
     */
1793
    public static function addField($field, $table)
1794
    {
1795
        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...
1796
        $result = $xoopsDB->queryF("ALTER TABLE $table ADD $field;");
1797
1798
        return $result;
1799
    }
1800
1801
    /**
1802
     * @param $info
1803
     *
1804
     * @return string
1805
     */
1806
    public static function packingHtmlSelect($info)
1807
    {
1808
        $ret = '';
1809
        $ret .= '<div class="oledrion_htmlform">';
1810
        $ret .= '<img class="oledrion_htmlimage" src="' . $info['packing_image_url'] . '" alt="' . $info['packing_title'] . '" />';
1811
        $ret .= '<h3>' . $info['packing_title'] . '</h3>';
1812 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...
1813
            $ret .= '<p><span class="bold">' . _OLEDRION_PRICE . '</span> : ' . $info['packing_price_fordisplay'] . '</p>';
1814
        } else {
1815
            $ret .= '<p><span class="bold">' . _OLEDRION_PRICE . '</span> : ' . _OLEDRION_FREE . '</p>';
1816
        }
1817
        $ret .= '<p>' . $info['packing_description'] . '</p>';
1818
        $ret .= '</div>';
1819
1820
        return $ret;
1821
    }
1822
1823
    /**
1824
     * @param $info
1825
     *
1826
     * @return string
1827
     */
1828
    public static function deliveryHtmlSelect($info)
1829
    {
1830
        $ret = '';
1831
        $ret .= '<div class="oledrion_htmlform">';
1832
        $ret .= '<img class="oledrion_htmlimage" src="' . $info['delivery_image_url'] . '" alt="' . $info['delivery_title'] . '" />';
1833
        $ret .= '<h3>' . $info['delivery_title'] . '</h3>';
1834 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...
1835
            $ret .= '<p><span class="bold">' . _OLEDRION_PRICE . '</span> : ' . $info['delivery_price_fordisplay'] . '</p>';
1836
        } else {
1837
            $ret .= '<p><span class="bold">' . _OLEDRION_PRICE . '</span> : ' . _OLEDRION_FREE . '</p>';
1838
        }
1839
        $ret .= '<p><span class="bold">' . _OLEDRION_DELIVERY_TIME . '</span> : ' . $info['delivery_time'] . _OLEDRION_DELIVERY_DAY . '</p>';
1840
        $ret .= '<p>' . $info['delivery_description'] . '</p>';
1841
        $ret .= '</div>';
1842
1843
        return $ret;
1844
    }
1845
1846
    /**
1847
     * @param $info
1848
     *
1849
     * @return string
1850
     */
1851
    public static function paymentHtmlSelect($info)
1852
    {
1853
        $ret = '';
1854
        $ret .= '<div class="oledrion_htmlform">';
1855
        $ret .= '<img class="oledrion_htmlimage" src="' . $info['payment_image_url'] . '" alt="' . $info['payment_title'] . '" />';
1856
        $ret .= '<h3>' . $info['payment_title'] . '</h3>';
1857
        $ret .= '<p>' . $info['payment_description'] . '</p>';
1858
        $ret .= '</div>';
1859
1860
        return $ret;
1861
    }
1862
1863
    /**
1864
     * @return array
1865
     */
1866
    public static function getCountriesList()
1867
    {
1868
        require_once XOOPS_ROOT_PATH . '/class/xoopslists.php';
1869
1870
        return XoopsLists::getCountryList();
1871
    }
1872
1873
    //=================================================================================================================================
1874
1875
    /**
1876
     * @param       $name
1877
     * @param  bool $optional
1878
     * @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...
1879
     */
1880
    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...
1881
    {
1882
        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...
1883
1884
        $name = strtolower(trim($name));
1885
        if (!isset($handlers[$name])) {
1886
            if (file_exists($hnd_file = XOOPS_ROOT_PATH . '/modules/' . $xoopsModule->getVar('dirname') . '/class/class_' . $name . '.php')) {
1887
                require_once $hnd_file;
1888
            }
1889
            $class = 'xtube' . ucfirst($name) . 'Handler';
1890
            if (class_exists($class)) {
1891
                $handlers[$name] = new $class($GLOBALS['xoopsDB']);
1892
            }
1893
        }
1894
        if (!isset($handlers[$name]) && !$optional) {
1895
            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...
1896
        }
1897
1898
        return isset($handlers[$name]) ? $handlers[$name] : false;
1899
    }
1900
1901
    /**
1902
     * @param int    $cid
1903
     * @param string $permType
1904
     * @param bool   $redirect
1905
     *
1906
     * @return bool
1907
     */
1908
    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...
1909
    {
1910
        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...
1911
1912
        $groups       = is_object($GLOBALS['xoopsUser']) ? $GLOBALS['xoopsUser']->getGroups() : XOOPS_GROUP_ANONYMOUS;
1913
        $gpermHandler = xoops_getHandler('groupperm');
1914
        if (!$gpermHandler->checkRight($permType, $cid, $groups, $xoopsModule->getVar('mid'))) {
1915
            if (false === $redirect) {
1916
                return false;
1917
            } else {
1918
                redirect_header('index.php', 3, _NOPERM);
1919
            }
1920
        }
1921
1922
        return true;
1923
    }
1924
1925
    /**
1926
     * @param int $lid
1927
     *
1928
     * @return bool
1929
     */
1930
    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...
1931
    {
1932
        $sql = 'SELECT
1933
        COUNT(rating) AS rate,
1934
        MIN(rating) AS min_rate,
1935
        MAX(rating) AS max_rate,
1936
        AVG(rating) AS avg_rate,
1937
        COUNT(ratinguser) AS rating_user,
1938
        MAX(ratinguser) AS max_user,
1939
        MAX(title) AS max_title,
1940
        MIN(title) AS min_title,
1941
        sum(ratinguser = 0) AS null_ratinguser
1942
            FROM ' . $GLOBALS['xoopsDB']->prefix('xoopstube_votedata');
1943
        if ($lid > 0) {
1944
            $sql .= ' WHERE lid=' . $lid;
1945
        }
1946
        if (!$result = $GLOBALS['xoopsDB']->query($sql)) {
1947
            return false;
1948
        }
1949
        $ret = $GLOBALS['xoopsDB']->fetchArray($result);
1950
1951
        return $ret;
1952
    }
1953
1954
    /**
1955
     * @param int $sel_id
1956
     *
1957
     * @return array|bool
1958
     */
1959
    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...
1960
    {
1961
        $ret                  = array();
1962
        $ret['useravgrating'] = 0;
1963
1964
        $sql = 'SELECT rating FROM ' . $GLOBALS['xoopsDB']->prefix('xoopstube_votedata');
1965
        if ($sel_id !== 0) {
1966
            $sql .= ' WHERE lid=' . $sel_id;
1967
        }
1968
        if (!$result = $GLOBALS['xoopsDB']->query($sql)) {
1969
            return false;
1970
        }
1971
        $ret['uservotes'] = $GLOBALS['xoopsDB']->getRowsNum($result);
1972
        while (false !== (list($rating) = $GLOBALS['xoopsDB']->fetchRow($result))) {
1973
            $ret['useravgrating'] += (int)$rating;
1974
        }
1975
        if ($ret['useravgrating'] > 0) {
1976
            $ret['useravgrating'] = number_format($ret['useravgrating'] / $ret['uservotes'], 2);
1977
        }
1978
1979
        return $ret;
1980
    }
1981
1982
    /**
1983
     * @param      $array
1984
     * @param null $name
1985
     * @param null $def
1986
     * @param bool $strict
1987
     * @param int  $lengthcheck
1988
     *
1989
     * @return array|int|null|string
1990
     */
1991
    public static function xtubeCleanRequestVars(
1992
        &$array,
1993
        $name = null,
1994
        $def = null,
1995
        $strict = false,
1996
        $lengthcheck = 15
1997
    ) {
1998
        // Sanitise $_request for further use.  This method gives more control and security.
1999
        // Method is more for functionality rather than beauty at the moment, will correct later.
2000
        unset($array['usercookie'], $array['PHPSESSID']);
2001
2002
        if (is_array($array) && null === $name) {
2003
            $globals = array();
2004
            foreach (array_keys($array) as $k) {
2005
                $value = strip_tags(trim($array[$k]));
2006
                if (strlen($value >= $lengthcheck)) {
2007
                    return null;
2008
                }
2009 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...
2010
                    $value = (int)$value;
2011
                } else {
2012
                    if (true === $strict) {
2013
                        $value = preg_replace('/\W/', '', trim($value));
2014
                    }
2015
                    $value = strtolower((string)$value);
2016
                }
2017
                $globals[$k] = $value;
2018
            }
2019
2020
            return $globals;
2021
        }
2022
        if (!isset($array[$name]) || !array_key_exists($name, $array)) {
2023
            return $def;
2024
        } else {
2025
            $value = strip_tags(trim($array[$name]));
2026
        }
2027 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...
2028
            $value = (int)$value;
2029
        } else {
2030
            if (true === $strict) {
2031
                $value = preg_replace('/\W/', '', trim($value));
2032
            }
2033
            $value = strtolower((string)$value);
2034
        }
2035
2036
        return $value;
2037
    }
2038
2039
    /**
2040
     * @param int $cid
2041
     *
2042
     * @return string
2043
     */
2044
    public static function xtubeRenderToolbar($cid = 0)
2045
    {
2046
        $toolbar = '[ ';
2047
        if (true === XoopstubeUtility::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...
2048
            $toolbar .= '<a href="submit.php?cid=' . $cid . '">' . _MD_XOOPSTUBE_SUBMITVIDEO . '</a> | ';
2049
        }
2050
        $toolbar .= '<a href="newlist.php?newvideoshowdays=7">' . _MD_XOOPSTUBE_LATESTLIST . '</a> | <a href="topten.php?list=hit">' . _MD_XOOPSTUBE_POPULARITY
2051
                    . '</a> | <a href="topten.php?list=rate">' . _MD_XOOPSTUBE_TOPRATED . '</a> ]';
2052
2053
        return $toolbar;
2054
    }
2055
2056
    /**
2057
     *
2058
     */
2059
    public static function xtubeGetServerStatistics()
2060
    {
2061
        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...
2062
        echo '<fieldset style="border: #E8E8E8 1px solid;">
2063
          <legend style="display: inline; font-weight: bold; color: #0A3760;">' . _AM_XOOPSTUBE_VIDEO_IMAGEINFO . '</legend>
2064
          <div style="padding: 8px;">
2065
            <img src="' . XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname') . '/assets/images/icon/server.png" alt="" style="float: left; padding-right: 10px;" />
2066
          <div>' . _AM_XOOPSTUBE_VIDEO_SPHPINI . '</div>';
2067
2068
        //    $safemode        = ini_get('safe_mode') ? _AM_XOOPSTUBE_VIDEO_ON . _AM_XOOPSTUBE_VIDEO_SAFEMODEPROBLEMS : _AM_XOOPSTUBE_VIDEO_OFF;
2069
        //    $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...
2070
        $videos = ini_get('file_uploads') ? _AM_XOOPSTUBE_VIDEO_ON : _AM_XOOPSTUBE_VIDEO_OFF;
2071
2072
        $gdlib = function_exists('gd_info') ? _AM_XOOPSTUBE_VIDEO_GDON : _AM_XOOPSTUBE_VIDEO_GDOFF;
2073
        echo '<li>' . _AM_XOOPSTUBE_VIDEO_GDLIBSTATUS . $gdlib;
2074
        if (function_exists('gd_info')) {
2075
            if (true === $gdlib = gd_info()) {
2076
                echo '<li>' . _AM_XOOPSTUBE_VIDEO_GDLIBVERSION . '<b>' . $gdlib['GD Version'] . '</b>';
2077
            }
2078
        }
2079
        echo '<br><br>';
2080
        //    echo '<li>' . _AM_XOOPSTUBE_VIDEO_SAFEMODESTATUS . $safemode;
2081
        //    echo '<li>' . _AM_XOOPSTUBE_VIDEO_REGISTERGLOBALS . $registerglobals;
2082
        echo '<li>' . _AM_XOOPSTUBE_VIDEO_SERVERUPLOADSTATUS . $videos;
2083
        echo '</div>';
2084
        echo '</fieldset>';
2085
    }
2086
2087
    // xtubeDisplayIcons()
2088
    //
2089
    // @param  $time
2090
    // @param integer $status
2091
    // @param integer $counter
2092
    // @return
2093
    /**
2094
     * @param     $time
2095
     * @param int $status
2096
     * @param int $counter
2097
     *
2098
     * @return string
2099
     */
2100
    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...
2101
    {
2102
        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...
2103
2104
        $new = '';
2105
        $pop = '';
2106
2107
        $newdate = (time() - (86400 * (int)$GLOBALS['xoopsModuleConfig']['daysnew']));
2108
        $popdate = (time() - (86400 * (int)$GLOBALS['xoopsModuleConfig']['daysupdated']));
2109
2110
        if (3 != $GLOBALS['xoopsModuleConfig']['displayicons']) {
2111
            if ($newdate < $time) {
2112
                if ((int)$status > 1) {
2113 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...
2114
                        $new = '&nbsp;<img src="' . XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname') . '/assets/images/icon/updated.gif" alt="" style="vertical-align: middle;" />';
2115
                    }
2116
                    if (2 == $GLOBALS['xoopsModuleConfig']['displayicons']) {
2117
                        $new = '<em>' . _MD_XOOPSTUBE_UPDATED . '</em>';
2118
                    }
2119
                } else {
2120 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...
2121
                        $new = '&nbsp;<img src="' . XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname') . '/assets/images/icon/new.gif" alt="" style="vertical-align: middle;" />';
2122
                    }
2123
                    if (2 == $GLOBALS['xoopsModuleConfig']['displayicons']) {
2124
                        $new = '<em>' . _MD_XOOPSTUBE_NEW . '</em>';
2125
                    }
2126
                }
2127
            }
2128
            if ($popdate > $time) {
2129
                if ($counter >= $GLOBALS['xoopsModuleConfig']['popular']) {
2130 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...
2131
                        $pop = '&nbsp;<img src="' . XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname') . '/assets/images/icon/popular.png" alt="" style="vertical-align: middle;" />';
2132
                    }
2133
                    if (2 == $GLOBALS['xoopsModuleConfig']['displayicons']) {
2134
                        $pop = '<em>' . _MD_XOOPSTUBE_POPULAR . '!</em>';
2135
                    }
2136
                }
2137
            }
2138
        }
2139
        $icons = $new . ' ' . $pop;
2140
2141
        return $icons;
2142
    }
2143
2144
    // Reusable Link Sorting Functions
2145
    // xtubeConvertOrderByIn()
2146
    // @param  $orderby
2147
    // @return
2148
    /**
2149
     * @param $orderby
2150
     *
2151
     * @return string
2152
     */
2153 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...
2154
    {
2155
        switch (trim($orderby)) {
2156
            case 'titleA':
2157
                $orderby = 'title ASC';
2158
                break;
2159
            case 'dateA':
2160
                $orderby = 'published ASC';
2161
                break;
2162
            case 'hitsA':
2163
                $orderby = 'hits ASC';
2164
                break;
2165
            case 'ratingA':
2166
                $orderby = 'rating ASC';
2167
                break;
2168
            case 'countryA':
2169
                $orderby = 'country ASC';
2170
                break;
2171
            case 'titleD':
2172
                $orderby = 'title DESC';
2173
                break;
2174
            case 'hitsD':
2175
                $orderby = 'hits DESC';
2176
                break;
2177
            case 'ratingD':
2178
                $orderby = 'rating DESC';
2179
                break;
2180
            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...
2181
                $orderby = 'published DESC';
2182
                break;
2183
            case 'countryD':
2184
                $orderby = 'country DESC';
2185
                break;
2186
        }
2187
2188
        return $orderby;
2189
    }
2190
2191
    /**
2192
     * @param $orderby
2193
     *
2194
     * @return string
2195
     */
2196
    public static function xtubeConvertOrderByTrans($orderby)
2197
    {
2198
        switch ($orderby) {
2199
            case 'hits ASC':
2200
                $orderByTrans = _MD_XOOPSTUBE_POPULARITYLTOM;
2201
                break;
2202
            case 'hits DESC':
2203
                $orderByTrans = _MD_XOOPSTUBE_POPULARITYMTOL;
2204
                break;
2205
            case 'title ASC':
2206
                $orderByTrans = _MD_XOOPSTUBE_TITLEATOZ;
2207
                break;
2208
            case 'title DESC':
2209
                $orderByTrans = _MD_XOOPSTUBE_TITLEZTOA;
2210
                break;
2211
            case 'published ASC':
2212
                $orderByTrans = _MD_XOOPSTUBE_DATEOLD;
2213
                break;
2214
            case 'published DESC':
2215
                $orderByTrans = _MD_XOOPSTUBE_DATENEW;
2216
                break;
2217
            case 'rating ASC':
2218
                $orderByTrans = _MD_XOOPSTUBE_RATINGLTOH;
2219
                break;
2220
            case 'rating DESC':
2221
                $orderByTrans = _MD_XOOPSTUBE_RATINGHTOL;
2222
                break;
2223
            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...
2224
                $orderByTrans = _MD_XOOPSTUBE_COUNTRYLTOH;
2225
                break;
2226
            case 'country DESC':
2227
                $orderByTrans = _MD_XOOPSTUBE_COUNTRYHTOL;
2228
                break;
2229
        }
2230
2231
        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...
2232
    }
2233
2234
    /**
2235
     * @param $orderby
2236
     *
2237
     * @return string
2238
     */
2239 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...
2240
    {
2241
        switch ($orderby) {
2242
            case 'title ASC':
2243
                $orderby = 'titleA';
2244
                break;
2245
            case 'published ASC':
2246
                $orderby = 'dateA';
2247
                break;
2248
            case 'hits ASC':
2249
                $orderby = 'hitsA';
2250
                break;
2251
            case 'rating ASC':
2252
                $orderby = 'ratingA';
2253
                break;
2254
            case 'country ASC':
2255
                $orderby = 'countryA';
2256
                break;
2257
            case 'title DESC':
2258
                $orderby = 'titleD';
2259
                break;
2260
            case 'published DESC':
2261
                $orderby = 'dateD';
2262
                break;
2263
            case 'hits DESC':
2264
                $orderby = 'hitsD';
2265
                break;
2266
            case 'rating DESC':
2267
                $orderby = 'ratingD';
2268
                break;
2269
            case 'country DESC':
2270
                $orderby = 'countryD';
2271
                break;
2272
        }
2273
2274
        return $orderby;
2275
    }
2276
2277
    // updaterating()
2278
    // @param  $sel_id
2279
    // @return updates rating data in itemtable for a given item
2280
    /**
2281
     * @param $sel_id
2282
     */
2283
    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...
2284
    {
2285
        $query       = 'SELECT rating FROM ' . $GLOBALS['xoopsDB']->prefix('xoopstube_votedata') . ' WHERE lid=' . $sel_id;
2286
        $voteresult  = $GLOBALS['xoopsDB']->query($query);
2287
        $votesDB     = $GLOBALS['xoopsDB']->getRowsNum($voteresult);
2288
        $totalrating = 0;
2289
        while (false !== (list($rating) = $GLOBALS['xoopsDB']->fetchRow($voteresult))) {
2290
            $totalrating += $rating;
2291
        }
2292
        $finalrating = $totalrating / $votesDB;
2293
        $finalrating = number_format($finalrating, 4);
2294
        $sql         = sprintf('UPDATE %s SET rating = %u, votes = %u WHERE lid = %u', $GLOBALS['xoopsDB']->prefix('xoopstube_videos'), $finalrating, $votesDB, $sel_id);
2295
        $GLOBALS['xoopsDB']->query($sql);
2296
    }
2297
2298
    // totalcategory()
2299
    // @param integer $pid
2300
    // @return
2301
    /**
2302
     * @param int $pid
2303
     *
2304
     * @return int
2305
     */
2306
    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...
2307
    {
2308
        $sql = 'SELECT cid FROM ' . $GLOBALS['xoopsDB']->prefix('xoopstube_cat');
2309
        if ($pid > 0) {
2310
            $sql .= ' WHERE pid = 0';
2311
        }
2312
        $result     = $GLOBALS['xoopsDB']->query($sql);
2313
        $catlisting = 0;
2314
        while (false !== (list($cid) = $GLOBALS['xoopsDB']->fetchRow($result))) {
2315
            if (XoopstubeUtility::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...
2316
                ++$catlisting;
2317
            }
2318
        }
2319
2320
        return $catlisting;
2321
    }
2322
2323
    // xtubeGetTotalItems()
2324
    // @param integer $sel_id
2325
    // @param integer $get_child
2326
    // @param integer $return_sql
2327
    // @return
2328
    /**
2329
     * @param int $sel_id
2330
     * @param int $get_child
2331
     * @param int $return_sql
2332
     *
2333
     * @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...
2334
     */
2335
    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...
2336
    {
2337
        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...
2338
2339
        if ($sel_id > 0) {
2340
            $sql = 'SELECT a.lid, a.cid, a.published FROM ' . $GLOBALS['xoopsDB']->prefix('xoopstube_videos') . ' a LEFT JOIN ' . $GLOBALS['xoopsDB']->prefix('xoopstube_altcat') . ' b'
2341
                   . ' 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='
2342
                   . $sel_id . ' OR b.cid=' . $sel_id . '))' . ' GROUP BY a.lid, a.cid, a.published';
2343
        } else {
2344
            $sql = 'SELECT lid, cid, published FROM ' . $GLOBALS['xoopsDB']->prefix('xoopstube_videos') . ' WHERE offline = 0 AND published > 0 AND published <= ' . time()
2345
                   . ' AND (expired = 0 OR expired > ' . time() . ')';
2346
        }
2347
        if (1 == $return_sql) {
2348
            return $sql;
2349
        }
2350
2351
        $count          = 0;
2352
        $published_date = 0;
2353
2354
        $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...
2355
        $result = $GLOBALS['xoopsDB']->query($sql);
2356
        while (false !== (list($lid, $cid, $published) = $GLOBALS['xoopsDB']->fetchRow($result))) {
2357
            if (true === XoopstubeUtility::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...
2358
                ++$count;
2359
                $published_date = ($published > $published_date) ? $published : $published_date;
2360
            }
2361
        }
2362
2363
        $child_count = 0;
2364
        if (1 == $get_child) {
2365
            $arr  = $mytree->getAllChildId($sel_id);
2366
            $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...
2367
            for ($i = 0, $iMax = count($arr); $i < $iMax; ++$i) {
2368
                $query2 = 'SELECT a.lid, a.published, a.cid FROM ' . $GLOBALS['xoopsDB']->prefix('xoopstube_videos') . ' a LEFT JOIN ' . $GLOBALS['xoopsDB']->prefix('xoopstube_altcat') . ' b'
2369
                          . ' ON b.lid = a.lid' . ' WHERE a.published > 0 AND a.published <= ' . time() . ' AND (a.expired = 0 OR a.expired > ' . time() . ') AND offline = 0'
2370
                          . ' AND (b.cid=a.cid OR (a.cid=' . $arr[$i] . ' OR b.cid=' . $arr[$i] . ')) GROUP BY a.lid, a.published, a.cid';
2371
2372
                $result2 = $GLOBALS['xoopsDB']->query($query2);
2373
                while (false !== (list($lid, $published) = $GLOBALS['xoopsDB']->fetchRow($result2))) {
2374
                    if (0 == $published) {
2375
                        continue;
2376
                    }
2377
                    $published_date = ($published > $published_date) ? $published : $published_date;
2378
                    ++$child_count;
2379
                }
2380
            }
2381
        }
2382
        $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...
2383
        $info['published'] = $published_date;
2384
2385
        return $info;
2386
    }
2387
2388
    /**
2389
     * @param string $indeximage
2390
     * @param string $indexheading
2391
     *
2392
     * @return string
2393
     */
2394
    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...
2395
    {
2396 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...
2397
            $result = $GLOBALS['xoopsDB']->query('SELECT indeximage, indexheading FROM ' . $GLOBALS['xoopsDB']->prefix('xoopstube_indexpage'));
2398
            list($indeximage, $indexheading) = $GLOBALS['xoopsDB']->fetchrow($result);
2399
        }
2400
2401
        $image = '';
2402
        if (!empty($indeximage)) {
2403
            $image = XoopstubeUtility::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...
2404
        }
2405
2406
        return $image;
2407
    }
2408
2409
    /**
2410
     * @param string $image
2411
     * @param string $path
2412
     * @param string $imgsource
2413
     * @param string $alttext
2414
     *
2415
     * @return string
2416
     */
2417
    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...
2418
    {
2419
        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...
2420
2421
        $showimage = '';
2422
        // Check to see if link is given
2423
        if ($path) {
2424
            $showimage = '<a href="' . $path . '">';
2425
        }
2426
        // checks to see if the file is valid else displays default blank image
2427
        if (!is_dir(XOOPS_ROOT_PATH . "/{$imgsource}/{$image}")
2428
            && file_exists(XOOPS_ROOT_PATH . "/{$imgsource}/{$image}")
2429
        ) {
2430
            $showimage .= "<img src='" . XOOPS_URL . "/{$imgsource}/{$image}' border='0' title='" . $alttext . "' alt='" . $alttext . "' /></a>";
2431
        } else {
2432
            if ($GLOBALS['xoopsUser'] && $GLOBALS['xoopsUser']->isAdmin($xoopsModule->getVar('mid'))) {
2433
                $showimage .= '<img src="' . XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname') . '/assets/images/brokenimg.png" alt="' . _MD_XOOPSTUBE_ISADMINNOTICE . '" /></a>';
2434
            } else {
2435
                $showimage .= '<img src="' . XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname') . '/assets/images/blank.png" alt="' . $alttext . '" /></a>';
2436
            }
2437
        }
2438
        clearstatcache();
2439
2440
        return $showimage;
2441
    }
2442
2443
    /**
2444
     * @param $published
2445
     *
2446
     * @return mixed
2447
     */
2448
    public static function xtubeIsNewImage($published)
2449
    {
2450
        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...
2451
2452
        $oneday    = (time() - (86400 * 1));
2453
        $threedays = (time() - (86400 * 3));
2454
        $week      = (time() - (86400 * 7));
2455
2456
        $path = 'modules/' . $xoopsModule->getVar('dirname') . '/assets/images/icon';
2457
2458
        if ($published > 0 && $published < $week) {
2459
            $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...
2460
            $indicator['alttext'] = _MD_XOOPSTUBE_NEWLAST;
2461
        } elseif ($published >= $week && $published < $threedays) {
2462
            $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...
2463
            $indicator['alttext'] = _MD_XOOPSTUBE_NEWTHIS;
2464
        } elseif ($published >= $threedays && $published < $oneday) {
2465
            $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...
2466
            $indicator['alttext'] = _MD_XOOPSTUBE_THREE;
2467
        } elseif ($published >= $oneday) {
2468
            $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...
2469
            $indicator['alttext'] = _MD_XOOPSTUBE_TODAY;
2470
        } else {
2471
            $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...
2472
            $indicator['alttext'] = _MD_XOOPSTUBE_NO_FILES;
2473
        }
2474
2475
        return $indicator;
2476
    }
2477
2478
    /**
2479
     * @param $haystack
2480
     * @param $needle
2481
     *
2482
     * @return string
2483
     */
2484
    public static function xtubeFindStringChar($haystack, $needle)
2485
    {
2486
        return substr($haystack, 0, strpos($haystack, $needle) + 1);
2487
    }
2488
2489
    /**
2490
     * @param string $header
2491
     * @param string $menu
2492
     * @param string $extra
2493
     * @param int    $scount
2494
     *
2495
     * @return bool|null
2496
     */
2497
    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...
2498
    {
2499
        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...
2500
2501
        $_named_vidid = xoops_getenv('PHP_SELF');
2502
        if ($_named_vidid) {
2503
            $thispage = basename($_named_vidid);
2504
        }
2505
2506
        //    $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...
2507
        $op = Request::getCmd('op', '', 'GET');
2508
        echo '<h4 style="color: #2F5376;">' . _AM_XOOPSTUBE_MODULE_NAME . '</h4>';
2509
        echo '
2510
        <div style="font-size: 10px; text-align: left; color: #2F5376; padding: 2px 6px; line-height: 18px;">
2511
        <span style="margin: 1px; padding: 4px; border: #E8E8E8 1px solid;">
2512
            <a href="../admin/index.php">' . _AM_XOOPSTUBE_BINDEX . '</a>
2513
        </span>
2514
        <span  style="margin: 1px; padding: 4px; border: #E8E8E8 1px solid;">
2515
            <a href="../index.php">' . _AM_XOOPSTUBE_GOMODULE . '</a>
2516
        </span>
2517
        <span  style="margin: 1px; padding: 4px; border: #E8E8E8 1px solid;">
2518
            <a href="../../system/admin.php?fct=preferences&op=showmod&mod=' . $xoopsModule->getVar('mid') . '">' . _AM_XOOPSTUBE_PREFS . '</a>
2519
        </span>
2520
        <span  style="margin: 1px; padding: 4px; border: #E8E8E8 1px solid;">
2521
            <a href="../admin/permissions.php">' . _AM_XOOPSTUBE_BPERMISSIONS . '</a>
2522
        </span>
2523
        <span  style="margin: 1px; padding: 4px; border: #E8E8E8 1px solid;">
2524
            <a href="../admin/myblocksadmin.php">' . _AM_XOOPSTUBE_BLOCKADMIN . '</a>
2525
        </span>
2526
        <span  style="margin: 1px; padding: 4px; border: #E8E8E8 1px solid;">
2527
            <a href="../../system/admin.php?fct=modulesadmin&op=update&module=' . $xoopsModule->getVar('dirname') . '">' . _AM_XOOPSTUBE_BUPDATE . '</a>
2528
        </span>
2529
        <span  style="margin: 1px; padding: 4px; border: #E8E8E8 1px solid;">
2530
            <a href="../admin/about.php">' . _AM_XOOPSTUBE_ABOUT . '</a>
2531
        </span>
2532
        </div><br>';
2533
2534
        if (empty($menu)) {
2535
            // You can change this part to suit your own module. Defining this here will save you form having to do this each time.
2536
            $menu = array(
2537
                _AM_XOOPSTUBE_MVIDEOS   => 'main.php?op=edit',
2538
                _AM_XOOPSTUBE_MCATEGORY => 'category.php',
2539
                _AM_XOOPSTUBE_INDEXPAGE => 'indexpage.php',
2540
                //            _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...
2541
                _AM_XOOPSTUBE_MUPLOADS  => 'upload.php',
2542
                _AM_XOOPSTUBE_VUPLOADS  => 'vupload.php',
2543
                _AM_XOOPSTUBE_MVOTEDATA => 'votedata.php',
2544
                _AM_XOOPSTUBE_MCOMMENTS => '../../system/admin.php?module=' . $xoopsModule->getVar('mid') . '&status=0&limit=100&fct=comments&selsubmit=Go'
2545
            );
2546
        }
2547
2548
        if (!is_array($menu)) {
2549
            echo '<table width="100%" cellpadding="2" cellspacing="1" class="outer">';
2550
            echo '<tr><td class="even" align="center"><b>' . _AM_XOOPSTUBE_NOMENUITEMS . '</b></td></tr></table><br>';
2551
2552
            return false;
2553
        }
2554
2555
        $oddnum = array(
2556
            1  => '1',
2557
            3  => '3',
2558
            5  => '5',
2559
            7  => '7',
2560
            9  => '9',
2561
            11 => '11',
2562
            13 => '13'
2563
        );
2564
        // number of rows per menu
2565
        $menurows = count($menu) / $scount;
2566
        // total amount of rows to complete menu
2567
        $menurow = ceil($menurows) * $scount;
2568
        // actual number of menuitems per row
2569
        $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...
2570
        $count    = 0;
2571
        for ($i = count($menu); $i < $menurow; ++$i) {
2572
            $tempArray = array(1 => null);
2573
            $menu      = array_merge($menu, $tempArray);
2574
            ++$count;
2575
        }
2576
2577
        // Sets up the width of each menu cell
2578
        $width = 100 / $scount;
2579
        $width = ceil($width);
2580
2581
        $menucount = 0;
2582
        $count     = 0;
2583
        // Menu table output
2584
        echo '<table width="100%" cellpadding="2" cellspacing="1" class="outer" border="1"><tr>';
2585
        // Check to see if $menu is and array
2586
        if (is_array($menu)) {
2587
            $classcounts = 0;
2588
            $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...
2589
2590
            for ($i = 1; $i < $menurow; ++$i) {
2591
                ++$classcounts;
2592
                if ($classcounts >= $scount) {
2593
                    if ('odd' === $classcol[$i - 1]) {
2594
                        $classcol[$i] = ('odd' === $classcol[$i - 1] && in_array($classcounts, $oddnum)) ? 'even' : 'odd';
2595
                    } else {
2596
                        $classcol[$i] = ('even' === $classcol[$i - 1] && in_array($classcounts, $oddnum)) ? 'odd' : 'even';
2597
                    }
2598
                    $classcounts = 0;
2599
                } else {
2600
                    $classcol[$i] = ('even' === $classcol[$i - 1]) ? 'odd' : 'even';
2601
                }
2602
            }
2603
            unset($classcounts);
2604
2605
            foreach ($menu as $menutitle => $menuvideo) {
2606
                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...
2607
                    $classcol[$count] = 'outer';
2608
                }
2609
                echo '<td class="' . $classcol[$count] . '" style="padding: 4px; text-align: center;" valign="middle" width="' . $width . '%">';
2610
                if (is_string($menuvideo)) {
2611
                    echo '<a href="' . $menuvideo . '"><span style="font-size: small;">' . $menutitle . '</span></a></td>';
2612
                } else {
2613
                    echo '&nbsp;</td>';
2614
                }
2615
                ++$menucount;
2616
                ++$count;
2617
                // Break menu cells to start a new row if $count > $scount
2618
                if ($menucount >= $scount) {
2619
                    echo '</tr>';
2620
                    $menucount = 0;
2621
                }
2622
            }
2623
            echo '</table><br>';
2624
            unset($count, $menucount);
2625
        }
2626
        // ###### Output warn messages for security ######
2627
        if (is_dir(XOOPS_ROOT_PATH . '/modules/' . $xoopsModule->getVar('dirname') . '/update/')) {
2628
            xoops_error(sprintf(_AM_XOOPSTUBE_WARNINSTALL1, XOOPS_ROOT_PATH . '/modules/' . $xoopsModule->getVar('dirname') . '/update/'));
2629
            echo '<br>';
2630
        }
2631
2632
        $_file = XOOPS_ROOT_PATH . '/modules/' . $xoopsModule->getVar('dirname') . '/update.php';
2633
        if (file_exists($_file)) {
2634
            xoops_error(sprintf(_AM_XOOPSTUBE_WARNINSTALL2, XOOPS_ROOT_PATH . '/modules/' . $xoopsModule->getVar('dirname') . '/update.php'));
2635
            echo '<br>';
2636
        }
2637
2638
        $path1 = XOOPS_ROOT_PATH . '/' . $GLOBALS['xoopsModuleConfig']['mainimagedir'];
2639
        if (!is_dir($path1)) {
2640
            xoops_error(sprintf(_AM_XOOPSTUBE_WARNINSTALL3, $path1));
2641
            echo '<br>';
2642
        }
2643
        if (!is_writable($path1)) {
2644
            xoops_error(sprintf(_AM_XOOPSTUBE_WARNINSTALL4, $path1));
2645
            echo '<br>';
2646
        }
2647
2648
        $path1_t = XOOPS_ROOT_PATH . '/' . $GLOBALS['xoopsModuleConfig']['mainimagedir'] . '/thumbs';
2649
        if (!is_dir($path1_t)) {
2650
            xoops_error(sprintf(_AM_XOOPSTUBE_WARNINSTALL3, $path1_t));
2651
            echo '<br>';
2652
        }
2653
        if (!is_writable($path1_t)) {
2654
            xoops_error(sprintf(_AM_XOOPSTUBE_WARNINSTALL4, $path1_t));
2655
            echo '<br>';
2656
        }
2657
2658
        $path2 = XOOPS_ROOT_PATH . '/' . $GLOBALS['xoopsModuleConfig']['videoimgdir'];
2659
        if (!is_dir($path2)) {
2660
            xoops_error(sprintf(_AM_XOOPSTUBE_WARNINSTALL3, $path2));
2661
            echo '<br>';
2662
        }
2663
        if (!is_writable($path2)) {
2664
            xoops_error(sprintf(_AM_XOOPSTUBE_WARNINSTALL4, $path2));
2665
            echo '<br>';
2666
        }
2667
2668
        //    $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...
2669
        //    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...
2670
        //        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...
2671
        //        echo '<br>';
2672
        //    }
2673
2674
        $path3 = XOOPS_ROOT_PATH . '/' . $GLOBALS['xoopsModuleConfig']['catimage'];
2675
        if (!is_dir($path3)) {
2676
            xoops_error(sprintf(_AM_XOOPSTUBE_WARNINSTALL3, $path3));
2677
            echo '<br>';
2678
        }
2679
        if (!is_writable($path3)) {
2680
            xoops_error(sprintf(_AM_XOOPSTUBE_WARNINSTALL4, $path3));
2681
            echo '<br>';
2682
        }
2683
2684
        $path3_t = XOOPS_ROOT_PATH . '/' . $GLOBALS['xoopsModuleConfig']['catimage'] . '/thumbs';
2685
        if (!is_dir($path3_t)) {
2686
            xoops_error(sprintf(_AM_XOOPSTUBE_WARNINSTALL3, $path3_t));
2687
            echo '<br>';
2688
        }
2689
        if (!is_writable($path3_t)) {
2690
            xoops_error(sprintf(_AM_XOOPSTUBE_WARNINSTALL4, $path3_t));
2691
            echo '<br>';
2692
        }
2693
2694
        $path4 = XOOPS_ROOT_PATH . '/' . $GLOBALS['xoopsModuleConfig']['videodir'];
2695
        if (!is_dir($path4)) {
2696
            xoops_error(sprintf(_AM_XOOPSTUBE_WARNINSTALL3, $path4));
2697
            echo '<br>';
2698
        }
2699
        if (!is_writable($path4)) {
2700
            xoops_error(sprintf(_AM_XOOPSTUBE_WARNINSTALL4, $path4));
2701
            echo '<br>';
2702
        }
2703
2704
        echo '<h4 style="color: #2F5376;">' . $header . '</h4>';
2705
        if ($extra) {
2706
            echo '<div>' . $extra . '</div>';
2707
        }
2708
2709
        return null;
2710
    }
2711
2712
    /**
2713
     * @param $selected
2714
     * @param $dirarray
2715
     * @param $namearray
2716
     */
2717 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...
2718
    {
2719
        echo "<select size='1' name='workd' onchange='location.href=\"upload.php?rootpath=\"+this.options[this.selectedIndex].value'>";
2720
        echo "<option value=''>--------------------------------------</option>";
2721
        foreach ($namearray as $namearray => $workd) {
2722
            if ($workd == $selected) {
2723
                $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...
2724
            } else {
2725
                $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...
2726
            }
2727
            echo '<option value="' . htmlspecialchars($namearray, ENT_QUOTES) . '" $opt_selected>' . $workd . '</option>';
2728
        }
2729
        echo '</select>';
2730
    }
2731
2732
    /**
2733
     * @param $selected
2734
     * @param $dirarray
2735
     * @param $namearray
2736
     */
2737 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...
2738
    {
2739
        echo "<select size='1' name='workd' onchange='location.href=\"vupload.php?rootpath=\"+this.options[this.selectedIndex].value'>";
2740
        echo "<option value=''>--------------------------------------</option>";
2741
        foreach ($namearray as $namearray => $workd) {
2742
            if ($workd == $selected) {
2743
                $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...
2744
            } else {
2745
                $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...
2746
            }
2747
            echo '<option value="' . htmlspecialchars($namearray, ENT_QUOTES) . '" $opt_selected>' . $workd . '</option>';
2748
        }
2749
        echo '</select>';
2750
    }
2751
2752
    /**
2753
     * @param        $FILES
2754
     * @param string $uploaddir
2755
     * @param string $allowed_mimetypes
2756
     * @param string $redirecturl
2757
     * @param int    $redirect
2758
     * @param int    $usertype
2759
     *
2760
     * @return array|null
2761
     */
2762
    public static function xtubeUploadFiles(
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...
2763
        $FILES,
2764
        $uploaddir = 'uploads',
2765
        $allowed_mimetypes = '',
2766
        $redirecturl = 'index.php', //    $num = 0,
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...
2767
        $redirect = 0,
2768
        $usertype = 1
2769
    ) {
2770
        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...
2771
2772
        $down = array();
2773
//       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...
2774
        include __DIR__ . '/uploader.php';
2775
//        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...
2776
2777
2778
        if (empty($allowed_mimetypes)) {
2779
            $allowed_mimetypes = xtube_retmime($FILES['userfile']['name'], $usertype);
2780
        }
2781
        $upload_dir = XOOPS_ROOT_PATH . '/' . $uploaddir . '/';
2782
2783
        $maxfilesize = $GLOBALS['xoopsModuleConfig']['maxfilesize'];
2784
2785
        $maxfilewidth  = $GLOBALS['xoopsModuleConfig']['maximgwidth'];
2786
        $maxfileheight = $GLOBALS['xoopsModuleConfig']['maximgheight'];
2787
2788
        $uploader = new XoopsMediaUploader($upload_dir, $allowed_mimetypes, $maxfilesize, $maxfilewidth, $maxfileheight);
2789
        $uploader->noAdminSizeCheck(1);
2790
        //if ($uploader->fetchMedia(XoopsRequest::getArray('xoops_upload_file[0]', array(), 'POST'))) {
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...
2791
          if ($uploader->fetchMedia(XoopsRequest::getArray('xoops_upload_file', '', 'POST')[0])) {
2792
            if (!$uploader->upload()) {
2793
                $errors = $uploader->getErrors();
2794
                redirect_header($redirecturl, 2, $errors);
2795
            } else {
2796
                if ($redirect) {
2797
                    redirect_header($redirecturl, 1, _AM_XOOPSTUBE_UPLOADFILE);
2798
                } else {
2799
                    if (is_file($uploader->savedDestination)) {
2800
                        $down['url']  = XOOPS_URL . '/' . $uploaddir . '/' . strtolower($uploader->savedFileName);
2801
                        $down['size'] = filesize(XOOPS_ROOT_PATH . '/' . $uploaddir . '/' . strtolower($uploader->savedFileName));
2802
                    }
2803
2804
                    return $down;
2805
                }
2806
            }
2807
        } else {
2808
            $errors = $uploader->getErrors();
2809
            redirect_header($redirecturl, 1, $errors);
2810
        }
2811
2812
        return null;
2813
    }
2814
2815
    /**
2816
     * @param $heading
2817
     */
2818 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...
2819
    {
2820
        echo '
2821
        <h4 style="font-weight: bold; color: #0A3760;">' . $heading . '</h4>
2822
        <table width="100%" cellspacing="1" class="outer" summary>
2823
        <tr>
2824
            <th style="text-align: center; font-size: smaller;">' . _AM_XOOPSTUBE_MINDEX_ID . '</th>
2825
            <th style=" font-size: smaller;"><b>' . _AM_XOOPSTUBE_FCATEGORY_TITLE . '</th>
2826
            <th style="text-align: center; font-size: smaller;">' . _AM_XOOPSTUBE_FCATEGORY_WEIGHT . '</th>
2827
            <th style="text-align: center; font-size: smaller;">' . _AM_XOOPSTUBE_FCATEGORY_CIMAGE . '</th>
2828
            <th style="text-align: center; font-size: smaller;">' . _AM_XOOPSTUBE_CATSPONSOR . '</th>
2829
<!--            <th style="text-align: center; font-size: smaller;">' . _AM_XOOPSTUBE_MINDEX_PUBLISH . '</th>
2830
            <th style="text-align: center; font-size: smaller;">' . _AM_XOOPSTUBE_MINDEX_EXPIRE . '</th>
2831
            <th style="text-align: center; font-size: smaller;">' . _AM_XOOPSTUBE_MINDEX_ONLINE . '</th>
2832
            <th style="text-align: center; font-size: smaller;">' . _AM_XOOPSTUBE_MINDEX_ACTION . '</th> -->
2833
        </tr>
2834
        ';
2835
    }
2836
2837
    /**
2838
     * @param $published
2839
     */
2840
    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...
2841
    {
2842
        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...
2843
2844
        $lid = $published['lid'];
2845
        $cid = $published['cid'];
2846
2847
        $title        = '<a href="../singlevideo.php?cid=' . $published['cid'] . '&amp;lid=' . $published['lid'] . '">' . $xtubemyts->htmlSpecialCharsStrip(trim($published['title'])) . '</a>';
2848
        $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...
2849
        $cattitle     = '<a href="../viewcat.php?cid=' . $published['cid'] . '">' . XoopstubeUtility::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...
2850
        $submitter    = XoopstubeUtility::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...
2851
        $returnsource = xtubeReturnSource($published['vidsource']);
2852
        $submitted    = XoopstubeUtility::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...
2853
        $publish      = ($published['published'] > 0) ? XoopstubeUtility::xtubeGetTimestamp(formatTimestamp($published['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...
2854
                                                                                                            $GLOBALS['xoopsModuleConfig']['dateformatadmin'])) : 'Not Published';
2855
        $expires      = $published['expired'] ? XoopstubeUtility::xtubeGetTimestamp(formatTimestamp($published['expired'],
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...
2856
                                                                                                    $GLOBALS['xoopsModuleConfig']['dateformatadmin'])) : _AM_XOOPSTUBE_MINDEX_NOTSET;
2857
2858
        if ((($published['expired'] && $published['expired'] > time()) || 0 == $published['expired'])
2859
            && ($published['published'] && $published['published'] < time())
2860
            && 0 == $published['offline']
2861
        ) {
2862
            $published_status = $xtubeImageArray['online'];
2863 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...
2864
            $published_status = $xtubeImageArray['expired'];
2865
        } else {
2866
            $published_status = (0 == $published['published']) ? '<a href="newvideos.php">' . $xtubeImageArray['offline'] . '</a>' : $xtubeImageArray['offline'];
2867
        }
2868
2869 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...
2870
            $icon = '<a href="main.php?op=edit&amp;lid=' . $lid . '" title="' . _AM_XOOPSTUBE_ICO_EDIT . '">' . $xtubeImageArray['editimg'] . '</a>&nbsp;';
2871
        } else {
2872
            $icon = '<a href="main.php?op=edit&amp;lid=' . $lid . '" title="' . _AM_XOOPSTUBE_ICO_EDIT . '">' . $xtubeImageArray['editimg'] . '</a>&nbsp;';
2873
        }
2874
        $icon .= '<a href="main.php?op=delete&amp;lid=' . $lid . '" title="' . _AM_XOOPSTUBE_ICO_DELETE . '">' . $xtubeImageArray['deleteimg'] . '</a>&nbsp;';
2875
        $icon .= '<a href="altcat.php?op=main&amp;cid=' . $cid . '&amp;lid=' . $lid . '&amp;title=' . $published['title'] . '" title="' . _AM_XOOPSTUBE_ALTCAT_CREATEF . '">'
2876
                 . $xtubeImageArray['altcat'] . '</a>';
2877
2878
        echo '
2879
        <tr style="text-align: center; font-size: smaller;">
2880
        <td class="head">' . $lid . '</span></td>
2881
        <td class="even" style="text-align: left;">' . $title . '</td>
2882
        <td class="even">' . $returnsource . '</td>
2883
        <td class="even">' . $cattitle . '</td>
2884
        <td class="even">' . $submitter . '</td>
2885
        <td class="even">' . $publish . '</td>
2886
        <td class="even">' . $expires . '</td>
2887
        <td class="even" style="width: 4%;">' . $published_status . '</td>
2888
        <td class="even" style="text-align: center; width: 6%; white-space: nowrap;">' . $icon . '</td>
2889
        </tr>';
2890
        //        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...
2891
    }
2892
2893
    /**
2894
     * @param        $pubrowamount
2895
     * @param        $start
2896
     * @param string $art
2897
     * @param string $_this
2898
     * @param        $align
2899
     *
2900
     * @return bool|null
2901
     */
2902 View Code Duplication
    public static function xtubeSetPageNavigationCategoryList(
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...
2903
        $pubrowamount,
2904
        $start,
2905
        $art = 'art',
2906
        $_this = '',
2907
        $align
2908
    ) {
2909
        if ($pubrowamount < $GLOBALS['xoopsModuleConfig']['admin_perpage']) {
2910
            return false;
2911
        }
2912
        // Display Page Nav if published is > total display pages amount.
2913
        require_once XOOPS_ROOT_PATH . '/class/pagenav.php';
2914
        $pagenav = new XoopsPageNav($pubrowamount, $GLOBALS['xoopsModuleConfig']['admin_perpage'], $start, 'st' . $art, $_this);
2915
        echo '<div style="text-align: ' . $align . '; padding: 8px;">' . $pagenav->renderNav() . '</div>';
2916
2917
        return null;
2918
    }
2919
2920
    /**
2921
     *
2922
     */
2923
    public static function xtubeRenderCategoryListFooter()
2924
    {
2925
        echo '<tr style="text-align: center;">
2926
            <td class="head" colspan="7">' . _AM_XOOPSTUBE_MINDEX_NOVIDEOSFOUND . '</td>
2927
          </tr>';
2928
    }
2929
2930
    /**
2931
     * @param $heading
2932
     */
2933 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...
2934
    {
2935
        echo '
2936
        <h4 style="font-weight: bold; color: #0A3760;">' . $heading . '</h4>
2937
        <table width="100%" cellspacing="1" class="outer" summary>
2938
        <tr>
2939
            <th style="text-align: center; font-size: smaller;">' . _AM_XOOPSTUBE_MINDEX_ID . '</th>
2940
            <th style=" font-size: smaller;"><b>' . _AM_XOOPSTUBE_MINDEX_TITLE . '</th>
2941
            <th style="text-align: center; font-size: smaller;">' . _AM_XOOPSTUBE_VIDSOURCE2 . '</th>
2942
            <th style="text-align: center; font-size: smaller;">' . _AM_XOOPSTUBE_CATTITLE . '</th>
2943
            <th style="text-align: center; font-size: smaller;">' . _AM_XOOPSTUBE_MINDEX_POSTER . '</th>
2944
            <th style="text-align: center; font-size: smaller;">' . _AM_XOOPSTUBE_MINDEX_PUBLISH . '</th>
2945
            <th style="text-align: center; font-size: smaller;">' . _AM_XOOPSTUBE_MINDEX_EXPIRE . '</th>
2946
            <th style="text-align: center; font-size: smaller;">' . _AM_XOOPSTUBE_MINDEX_ONLINE . '</th>
2947
            <th style="text-align: center; font-size: smaller;">' . _AM_XOOPSTUBE_MINDEX_ACTION . '</th>
2948
        </tr>
2949
        ';
2950
    }
2951
2952
    /**
2953
     * @param $published
2954
     */
2955
    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...
2956
    {
2957
        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...
2958
2959
        $lid = $published['lid'];
2960
        $cid = $published['cid'];
2961
2962
        $title        = '<a href="../singlevideo.php?cid=' . $published['cid'] . '&amp;lid=' . $published['lid'] . '">' . $xtubemyts->htmlSpecialCharsStrip(trim($published['title'])) . '</a>';
2963
        $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...
2964
        $cattitle     = '<a href="../viewcat.php?cid=' . $published['cid'] . '">' . XoopstubeUtility::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...
2965
        $submitter    = XoopstubeUtility::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...
2966
        $returnsource = xtubeReturnSource($published['vidsource']);
2967
        $submitted    = XoopstubeUtility::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...
2968
        $publish      = ($published['published'] > 0) ? XoopstubeUtility::xtubeGetTimestamp(formatTimestamp($published['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...
2969
                                                                                                            $GLOBALS['xoopsModuleConfig']['dateformatadmin'])) : 'Not Published';
2970
        $expires      = $published['expired'] ? XoopstubeUtility::xtubeGetTimestamp(formatTimestamp($published['expired'],
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...
2971
                                                                                                    $GLOBALS['xoopsModuleConfig']['dateformatadmin'])) : _AM_XOOPSTUBE_MINDEX_NOTSET;
2972
2973
        if ((($published['expired'] && $published['expired'] > time()) || $published['expired'] === 0)
2974
            && ($published['published'] && $published['published'] < time())
2975
            && $published['offline'] === 0
2976
        ) {
2977
            //        $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...
2978
            $published_status = '<a href="main.php?op=toggle&amp;lid=' . $lid . '&amp;offline=' . $published['offline'] . '"><img src="' . $pathIcon16 . '/1.png' . '" /></a>';
2979 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...
2980
            $published_status = $xtubeImageArray['expired'];
2981
        } else {
2982
            $published_status = ($published['published'] === 0) ? '<a href="newvideos.php">' . $xtubeImageArray['offline'] . '</a>' : '<a href="main.php?op=toggle&amp;lid='
2983
                                                                                                                                      . $lid
2984
                                                                                                                                      . '&amp;offline='
2985
                                                                                                                                      . $published['offline']
2986
                                                                                                                                      . '"><img src="'
2987
                                                                                                                                      . $pathIcon16
2988
                                                                                                                                      . '/0.png'
2989
                                                                                                                                      . '" /></a>';
2990
        }
2991
2992 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...
2993
            $icon = '<a href="main.php?op=edit&amp;lid=' . $lid . '" title="' . _AM_XOOPSTUBE_ICO_EDIT . '">' . $xtubeImageArray['editimg'] . '</a>&nbsp;';
2994
        } else {
2995
            $icon = '<a href="main.php?op=edit&amp;lid=' . $lid . '" title="' . _AM_XOOPSTUBE_ICO_EDIT . '">' . $xtubeImageArray['editimg'] . '</a>&nbsp;';
2996
        }
2997
        $icon .= '<a href="main.php?op=delete&amp;lid=' . $lid . '" title="' . _AM_XOOPSTUBE_ICO_DELETE . '">' . $xtubeImageArray['deleteimg'] . '</a>&nbsp;';
2998
        $icon .= '<a href="altcat.php?op=main&amp;cid=' . $cid . '&amp;lid=' . $lid . '&amp;title=' . $published['title'] . '" title="' . _AM_XOOPSTUBE_ALTCAT_CREATEF . '">'
2999
                 . $xtubeImageArray['altcat'] . '</a>';
3000
3001
        echo '
3002
        <tr style="text-align: center; font-size: smaller;">
3003
        <td class="head">' . $lid . '</span></td>
3004
        <td class="even" style="text-align: left;">' . $title . '</td>
3005
        <td class="even">' . $returnsource . '</td>
3006
        <td class="even">' . $cattitle . '</td>
3007
        <td class="even">' . $submitter . '</td>
3008
        <td class="even">' . $publish . '</td>
3009
        <td class="even">' . $expires . '</td>
3010
        <td class="even" style="width: 4%;">' . $published_status . '</td>
3011
        <td class="even" style="text-align: center; width: 6%; white-space: nowrap;">' . $icon . '</td>
3012
        </tr>';
3013
        //        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...
3014
    }
3015
3016
    /**
3017
     * @param $catt
3018
     *
3019
     * @return mixed
3020
     */
3021
    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...
3022
    {
3023
        $sql    = 'SELECT title FROM ' . $GLOBALS['xoopsDB']->prefix('xoopstube_cat') . ' WHERE cid=' . $catt;
3024
        $result = $GLOBALS['xoopsDB']->query($sql);
3025
        $result = $GLOBALS['xoopsDB']->fetchArray($result);
3026
3027
        return $result['title'];
3028
    }
3029
3030
    /**
3031
     *
3032
     */
3033
    public static function xtubeRenderVideoListFooter()
3034
    {
3035
        echo '<tr style="text-align: center;">
3036
            <td class="head" colspan="7">' . _AM_XOOPSTUBE_MINDEX_NOVIDEOSFOUND . '</td>
3037
          </tr>';
3038
    }
3039
3040
    /**
3041
     * @param        $pubrowamount
3042
     * @param        $start
3043
     * @param string $art
3044
     * @param string $_this
3045
     * @param        $align
3046
     *
3047
     * @return bool|null
3048
     */
3049 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...
3050
    {
3051
        if ($pubrowamount < $GLOBALS['xoopsModuleConfig']['admin_perpage']) {
3052
            return false;
3053
        }
3054
        // Display Page Nav if published is > total display pages amount.
3055
        require_once XOOPS_ROOT_PATH . '/class/pagenav.php';
3056
        $pagenav = new XoopsPageNav($pubrowamount, $GLOBALS['xoopsModuleConfig']['admin_perpage'], $start, 'st' . $art, $_this);
3057
        echo '<div style="text-align: ' . $align . '; padding: 8px;">' . $pagenav->renderNav() . '</div>';
3058
3059
        return null;
3060
    }
3061
3062
    /**
3063
     * @param $document
3064
     *
3065
     * @return mixed
3066
     */
3067
    public static function xtubeConvertHtml2Text($document)
3068
    {
3069
        // PHP Manual:: function preg_replace
3070
        // $document should contain an HTML document.
3071
        // This will remove HTML tags, javascript sections
3072
        // and white space. It will also convert some
3073
        // common HTML entities to their text equivalent.
3074
        // Credits : newbb2
3075
        $search = array(
3076
            "'<script[^>]*?>.*?</script>'si", // Strip out javascript
3077
            "'<img.*?/>'si", // Strip out img tags
3078
            "'<[\/\!]*?[^<>]*?>'si", // Strip out HTML tags
3079
            "'([\r\n])[\s]+'", // Strip out white space
3080
            "'&(quot|#34);'i", // Replace HTML entities
3081
            "'&(amp|#38);'i",
3082
            "'&(lt|#60);'i",
3083
            "'&(gt|#62);'i",
3084
            "'&(nbsp|#160);'i",
3085
            "'&(iexcl|#161);'i",
3086
            "'&(cent|#162);'i",
3087
            "'&(pound|#163);'i",
3088
            "'&(copy|#169);'i"
3089
        ); // evaluate as php
3090
3091
        $replace = array(
3092
            '',
3093
            '',
3094
            '',
3095
            "\\1",
3096
            "\"",
3097
            '&',
3098
            '<',
3099
            '>',
3100
            ' ',
3101
            chr(161),
3102
            chr(162),
3103
            chr(163),
3104
            chr(169)
3105
        );
3106
3107
        $text = preg_replace($search, $replace, $document);
3108
3109
        preg_replace_callback('/&#(\d+);/', function ($matches) {
3110
            return chr($matches[1]);
3111
        }, $document);
3112
3113
        return $text;
3114
    }
3115
3116
    // Check if Tag module is installed
3117
    /**
3118
     * @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...
3119
     */
3120
    public static function xtubeIsModuleTagInstalled()
3121
    {
3122
        static $isModuleTagInstalled;
3123
        if (!isset($isModuleTagInstalled)) {
3124
            /** @var XoopsModuleHandler $moduleHandler */
3125
            $moduleHandler = xoops_getHandler('module');
3126
            $tag_mod       = $moduleHandler->getByDirName('tag');
3127
            if (!$tag_mod) {
3128
                $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...
3129
            } else {
3130
                $isModuleTagInstalled = 1 == $tag_mod->getVar('isactive');
3131
            }
3132
        }
3133
3134
        return $isModuleTagInstalled;
3135
    }
3136
3137
    // Add item_tag to Tag-module
3138
    /**
3139
     * @param $lid
3140
     * @param $item_tag
3141
     */
3142
    public static function xtubeUpdateTag($lid, $item_tag)
3143
    {
3144
        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...
3145
        if (XoopstubeUtility::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...
3146
            require_once XOOPS_ROOT_PATH . '/modules/tag/include/formtag.php';
3147
            $tagHandler = xoops_getModuleHandler('tag', 'tag');
3148
            $tagHandler->updateByItem($item_tag, $lid, $xoopsModule->getVar('dirname'), 0);
3149
        }
3150
    }
3151
3152
    /**
3153
     * @param $lid
3154
     */
3155
    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...
3156
    {
3157
        $sql    = 'UPDATE ' . $GLOBALS['xoopsDB']->prefix('xoopstube_videos') . ' SET hits=hits+1 WHERE lid=' . (int)$lid;
3158
        $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...
3159
    }
3160
3161
    /**
3162
     * @param $banner_id
3163
     *
3164
     * @return null|string
3165
     */
3166 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...
3167
    {
3168
        ###### Hack by www.stefanosilvestrini.com ######
3169
        $db      = XoopsDatabaseFactory::getDatabaseConnection();
3170
        $bresult = $db->query('SELECT COUNT(*) FROM ' . $db->prefix('banner') . ' WHERE bid=' . $banner_id);
3171
        list($numrows) = $db->fetchRow($bresult);
3172
        if ($numrows > 1) {
3173
            --$numrows;
3174
            mt_srand((double)microtime() * 1000000);
3175
            $bannum = mt_rand(0, $numrows);
3176
        } else {
3177
            $bannum = 0;
3178
        }
3179
        if ($numrows > 0) {
3180
            $bresult = $db->query('SELECT * FROM ' . $db->prefix('banner') . ' WHERE bid=' . $banner_id, 1, $bannum);
3181
            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...
3182
            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...
3183
                // EMPTY
3184
            } else {
3185
                $db->queryF(sprintf('UPDATE %s SET impmade = impmade+1 WHERE bid = %u', $db->prefix('banner'), $bid));
3186
            }
3187
            /* Check if this impression is the last one and print the banner */
3188
            if ($imptotal == $impmade) {
3189
                $newid = $db->genId($db->prefix('bannerfinish') . '_bid_seq');
3190
                $sql   =
3191
                    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,
3192
                            time());
3193
                $db->queryF($sql);
3194
                $db->queryF(sprintf('DELETE FROM %s WHERE bid = %u', $db->prefix('banner'), $bid));
3195
            }
3196
            if ($htmlbanner) {
3197
                $bannerobject = $htmlcode;
3198
            } else {
3199
                $bannerobject = '<div align="center"><a href="' . XOOPS_URL . '/banners.php?op=click&bid=' . $bid . '" target="_blank">';
3200
                if (false !== stripos($imageurl, '.swf')) {
3201
                    $bannerobject = $bannerobject
3202
                                    . '<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">'
3203
                                    . '<param name="movie" value="' . $imageurl . '"></param>' . '<param name="quality" value="high"></param>' . '<embed src="' . $imageurl
3204
                                    . '" quality="high" pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash" type="application/x-shockwave-flash" width="468" height="60">'
3205
                                    . '</embed>' . '</object>';
3206
                } else {
3207
                    $bannerobject = $bannerobject . '<img src="' . $imageurl . '" alt="" />';
3208
                }
3209
                $bannerobject .= '</a></div>';
3210
            }
3211
3212
            return $bannerobject;
3213
        }
3214
3215
        return null;
3216
    }
3217
3218
    /**
3219
     * @param $client_id
3220
     *
3221
     * @return null|string
3222
     */
3223 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...
3224
    {
3225
        ###### Hack by www.stefanosilvestrini.com ######
3226
        $db      = XoopsDatabaseFactory::getDatabaseConnection();
3227
        $bresult = $db->query('SELECT COUNT(*) FROM ' . $db->prefix('banner') . ' WHERE cid=' . $client_id);
3228
        list($numrows) = $db->fetchRow($bresult);
3229
        if ($numrows > 1) {
3230
            --$numrows;
3231
            mt_srand((double)microtime() * 1000000);
3232
            $bannum = mt_rand(0, $numrows);
3233
        } else {
3234
            $bannum = 0;
3235
        }
3236
        if ($numrows > 0) {
3237
            $bresult = $db->query('SELECT * FROM ' . $db->prefix('banner') . ' WHERE cid=' . $client_id . ' ORDER BY rand()', 1, $bannum);
3238
            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...
3239
            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...
3240
                // EMPTY
3241
            } else {
3242
                $db->queryF(sprintf('UPDATE %s SET impmade = impmade+1 WHERE bid = %u', $db->prefix('banner'), $bid));
3243
            }
3244
            /* Check if this impression is the last one and print the banner */
3245
            if ($imptotal == $impmade) {
3246
                $newid = $db->genId($db->prefix('bannerfinish') . '_bid_seq');
3247
                $sql   =
3248
                    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,
3249
                            time());
3250
                $db->queryF($sql);
3251
                $db->queryF(sprintf('DELETE FROM %s WHERE bid = %u', $db->prefix('banner'), $bid));
3252
            }
3253
            if ($htmlbanner) {
3254
                $bannerobject = $htmlcode;
3255
            } else {
3256
                $bannerobject = '<div align="center"><a href="' . XOOPS_URL . '/banners.php?op=click&bid=' . $bid . '" target="_blank">';
3257
                if (false !== stripos($imageurl, '.swf')) {
3258
                    $bannerobject = $bannerobject
3259
                                    . '<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">'
3260
                                    . '<param name="movie" value="' . $imageurl . '"></param>' . '<param name="quality" value="high"></param>' . '<embed src="' . $imageurl
3261
                                    . '" quality="high" pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash" type="application/x-shockwave-flash" width="468" height="60">'
3262
                                    . '</embed>' . '</object>';
3263
                } else {
3264
                    $bannerobject = $bannerobject . '<img src="' . $imageurl . '" alt="" />';
3265
                }
3266
                $bannerobject .= '</a></div>';
3267
            }
3268
3269
            return $bannerobject;
3270
        }
3271
3272
        return null;
3273
    }
3274
3275
    /**
3276
     *
3277
     */
3278
    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...
3279
    {
3280
        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...
3281
        if (is_object($GLOBALS['xoTheme'])) {
3282
            $GLOBALS['xoTheme']->addMeta('meta', 'robots', 'noindex,nofollow');
3283
        } else {
3284
            $xoopsTpl->assign('xoops_meta_robots', 'noindex,nofollow');
3285
        }
3286
    }
3287
3288
    /**
3289
     * @param $userid
3290
     *
3291
     * @return string
3292
     */
3293
    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...
3294
    {
3295
        $userid = (int)$userid;
3296
        if ($userid > 0) {
3297
            $memberHandler = xoops_getHandler('member');
3298
            $user          = $memberHandler->getUser($userid);
3299
            if (is_object($user)) {
3300
                $linkeduser = '<a href="' . XOOPS_URL . '/userinfo.php?uid=' . $userid . '">' . $user->getVar('uname') . '</a>';
3301
3302
                return $linkeduser;
3303
            }
3304
        }
3305
3306
        return $GLOBALS['xoopsConfig']['anonymous'];
3307
    }
3308
3309
    /**
3310
     * @param $time
3311
     *
3312
     * @return string
3313
     */
3314
    public static function xtubeGetTimestamp($time)
3315
    {
3316
        $moduleDirName = basename(dirname(__DIR__));
3317
        xoops_loadLanguage('local', $moduleDirName);
3318
3319
        $trans     = array(
3320
            'Monday'    => _XOOPSTUBE_MONDAY,
3321
            'Tuesday'   => _XOOPSTUBE_TUESDAY,
3322
            'Wednesday' => _XOOPSTUBE_WEDNESDAY,
3323
            'Thursday'  => _XOOPSTUBE_THURSDAY,
3324
            'Friday'    => _XOOPSTUBE_FRIDAY,
3325
            'Saturday'  => _XOOPSTUBE_SATURDAY,
3326
            'Sunday'    => _XOOPSTUBE_SUNDAY,
3327
            'Mon'       => _XOOPSTUBE_MON,
3328
            'Tue'       => _XOOPSTUBE_TUE,
3329
            'Wed'       => _XOOPSTUBE_WED,
3330
            'Thu'       => _XOOPSTUBE_THU,
3331
            'Fri'       => _XOOPSTUBE_FRI,
3332
            'Sat'       => _XOOPSTUBE_SAT,
3333
            'Sun'       => _XOOPSTUBE_SUN,
3334
            'January'   => _XOOPSTUBE_JANUARI,
3335
            'February'  => _XOOPSTUBE_FEBRUARI,
3336
            'March'     => _XOOPSTUBE_MARCH,
3337
            'April'     => _XOOPSTUBE_APRIL,
3338
            'May'       => _XOOPSTUBE_MAY,
3339
            'June'      => _XOOPSTUBE_JUNE,
3340
            'July'      => _XOOPSTUBE_JULY,
3341
            'August'    => _XOOPSTUBE_AUGUST,
3342
            'September' => _XOOPSTUBE_SEPTEMBER,
3343
            'October'   => _XOOPSTUBE_OCTOBER,
3344
            'November'  => _XOOPSTUBE_NOVEMBER,
3345
            'December'  => _XOOPSTUBE_DECEMBER,
3346
            'Jan'       => _XOOPSTUBE_JAN,
3347
            'Feb'       => _XOOPSTUBE_FEB,
3348
            'Mar'       => _XOOPSTUBE_MAR,
3349
            'Apr'       => _XOOPSTUBE_APR,
3350
            //        '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...
3351
            'Jun'       => _XOOPSTUBE_JUN,
3352
            'Jul'       => _XOOPSTUBE_JUL,
3353
            'Aug'       => _XOOPSTUBE_AUG,
3354
            'Sep'       => _XOOPSTUBE_SEP,
3355
            'Oct'       => _XOOPSTUBE_OCT,
3356
            'Nov'       => _XOOPSTUBE_NOV,
3357
            'Dec'       => _XOOPSTUBE_DEC
3358
        );
3359
        $timestamp = strtr($time, $trans);
3360
3361
        return $timestamp;
3362
    }
3363
3364
    /**
3365
     * Do some basic file checks and stuff.
3366
     * Author: Andrew Mills  Email:  [email protected]
3367
     * from amReviews module
3368
     */
3369
    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...
3370
    {
3371
        echo '<fieldset>';
3372
        echo "<legend style=\"color: #990000; font-weight: bold;\">" . _AM_XOOPSTUBE_FILECHECKS . '</legend>';
3373
3374
        $dirPhotos      = XOOPS_ROOT_PATH . '/' . $GLOBALS['xoopsModuleConfig']['catimage'];
3375
        $dirVideos      = XOOPS_ROOT_PATH . '/' . $GLOBALS['xoopsModuleConfig']['videodir'];
3376
        $dirScreenshots = XOOPS_ROOT_PATH . '/' . $GLOBALS['xoopsModuleConfig']['videoimgdir'];
3377
3378 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...
3379
            if (!is_writable($dirPhotos)) {
3380
                echo "<span style=\" color: red; font-weight: bold;\">Warning:</span> " . _AM_XOOPSTUBE_UNABLE_TO_WRITE . $dirPhotos . '<br>';
3381
            } else {
3382
                echo "<span style=\" color: green; font-weight: bold;\">OK:</span> " . $dirPhotos . '<br>';
3383
            }
3384
        } else {
3385
            echo "<span style=\" color: red; font-weight: bold;\">" . _AM_XOOPSTUBE_WARNING . '</span> ' . $dirPhotos . " <span style=\" color: red; \">" . _AM_XOOPSTUBE_NOT_EXISTS . '</span> <br>';
3386
        }
3387
        // photothumbdir
3388 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...
3389
            if (!is_writable($dirVideos)) {
3390
                echo "<span style=\" color: red; font-weight: bold;\">" . _AM_XOOPSTUBE_WARNING . '</span> ' . _AM_XOOPSTUBE_UNABLE_TO_WRITE . $dirVideos . '<br>';
3391
            } else {
3392
                echo "<span style=\" color: green; font-weight: bold;\">OK:</span> " . $dirVideos . '<br>';
3393
            }
3394
        } else {
3395
            echo "<span style=\" color: red; font-weight: bold;\">" . _AM_XOOPSTUBE_WARNING . '</span> ' . $dirVideos . " <span style=\" color: red; \">" . _AM_XOOPSTUBE_NOT_EXISTS . '</span> <br>';
3396
        }
3397
        // photohighdir
3398 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...
3399
            if (!is_writable($dirScreenshots)) {
3400
                echo "<span style=\" color: red; font-weight: bold;\">Warning:</span> " . _AM_XOOPSTUBE_UNABLE_TO_WRITE . $dirScreenshots . '<br>';
3401
            } else {
3402
                echo "<span style=\" color: green; font-weight: bold;\">OK:</span> " . $dirScreenshots . '<br>';
3403
            }
3404
        } else {
3405
            echo "<span style=\" color: red; font-weight: bold;\">" . _AM_XOOPSTUBE_WARNING . '</span> ' . $dirScreenshots . " <span style=\" color: red; \">" . _AM_XOOPSTUBE_NOT_EXISTS
3406
                 . '</span> <br>';
3407
        }
3408
3409
        /**
3410
         * Some info.
3411
         */
3412
        $uploads = ini_get('file_uploads') ? _AM_XOOPSTUBE_UPLOAD_ON : _AM_XOOPSTUBE_UPLOAD_OFF;
3413
        echo '<br>';
3414
        echo '<ul>';
3415
        echo '<li>' . _AM_XOOPSTUBE_UPLOADMAX . '<b>' . ini_get('upload_max_filesize') . '</b></li>';
3416
        echo '<li>' . _AM_XOOPSTUBE_POSTMAX . '<b>' . ini_get('post_max_size') . '</b></li>';
3417
        echo '<li>' . _AM_XOOPSTUBE_UPLOADS . '<b>' . $uploads . '</b></li>';
3418
3419
        $gdinfo = gd_info();
3420
        if (function_exists('gd_info')) {
3421
            echo '<li>' . _AM_XOOPSTUBE_GDIMGSPPRT . '<b>' . _AM_XOOPSTUBE_GDIMGON . '</b></li>';
3422
            echo '<li>' . _AM_XOOPSTUBE_GDIMGVRSN . '<b>' . $gdinfo['GD Version'] . '</b></li>';
3423
        } else {
3424
            echo '<li>' . _AM_XOOPSTUBE_GDIMGSPPRT . '<b>' . _AM_XOOPSTUBE_GDIMGOFF . '</b></li>';
3425
        }
3426
        echo '</ul>';
3427
3428
        //$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...
3429
        //print_r($inithingy);
3430
3431
        echo '</fieldset>';
3432
    }
3433
3434
    /**
3435
     * @param      $path
3436
     * @param int  $mode
3437
     * @param      $fileSource
3438
     * @param null $fileTarget
3439
     */
3440
    public static function xtubeCreateDirectory($path, $mode = 0777, $fileSource, $fileTarget = null)
3441
    {
3442
        if (!is_dir($path)) {
3443
            mkdir($path, $mode);
3444
            file_put_contents($path . '/index.html', '<script>history.go(-1);</script>');
3445
            if (!empty($fileSource) && !empty($fileTarget)) {
3446
                @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...
3447
            }
3448
        }
3449
        chmod($path, $mode);
3450
    }
3451
3452
    /**
3453
     * @return string
3454
     */
3455
    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...
3456
    {
3457
        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...
3458
3459
        $letterchoice          = '<div>' . _MD_XOOPSTUBE_BROWSETOTOPIC . '</div>';
3460
        $alphabet              = getXtubeAlphabet();
3461
        $num                   = count($alphabet) - 1;
3462
        $counter               = 0;
3463
        $distinctDbLetters_arr = array();
3464
        $sql                   = 'SELECT DISTINCT (UPPER(LEFT(title, 1))) AS letter FROM ' . $GLOBALS['xoopsDB']->prefix('xoopstube_videos WHERE expired = 0 AND offline = 0');
3465
        if ($result = $GLOBALS['xoopsDB']->query($sql)) {
3466
            while (false !== ($row = $GLOBALS['xoopsDB']->fetchArray($result))) {
3467
                $distinctDbLetters_arr[] = $row['letter'];
3468
            }
3469
        }
3470
        unset($sql);
3471
3472
//        while (false !== (list(, $ltr) = each($alphabet))) {
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...
3473
        foreach ($alphabet as $key => $ltr) {
3474
            if (in_array($ltr, $distinctDbLetters_arr)) {
3475
                $letterchoice .= '<a class="xoopstube_letters xoopstube_letters_green" href="';
3476
            } else {
3477
                $letterchoice .= '<a class="xoopstube_letters" href="';
3478
            }
3479
            $letterchoice .= XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname') . '/viewcat.php?list=' . $ltr . '">' . $ltr . '</a>';
3480
            if ($counter == round($num / 2)) {
3481
                $letterchoice .= '<br>';
3482
            } elseif ($counter !== $num) {
3483
                $letterchoice .= '&nbsp;';
3484
            }
3485
            ++$counter;
3486
        }
3487
3488
        return $letterchoice;
3489
    }
3490
3491
    /**
3492
     * @return mixed|string
3493
     */
3494
    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...
3495
    {
3496
        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...
3497
3498
        $moduleDirName = $xoopsModule->getVar('dirname');
3499
        require_once XOOPS_ROOT_PATH . "/modules/$moduleDirName/class/$moduleDirName.php";
3500
        $xoopstube = XoopstubeXoopstube::getInstance();
3501
3502
        $a             = $xoopstube->getHandler('xoopstube');
3503
        $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...
3504
        $moduleDirName = basename(dirname(__DIR__));
3505
3506
        $criteria = $xoopstube->getHandler('xoopstube')->getActiveCriteria();
3507
        $criteria->setGroupby('UPPER(LEFT(title,1))');
3508
        $countsByLetters = $xoopstube->getHandler($moduleDirName)->getCounts($criteria);
3509
        // Fill alphabet array
3510
        $alphabet       = getXtubeAlphabet();
3511
        $alphabet_array = array();
3512 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...
3513
            $letter_array = array();
3514
            if (isset($countsByLetters[$letter])) {
3515
                $letter_array['letter'] = $letter;
3516
                $letter_array['count']  = $countsByLetters[$letter];
3517
                $letter_array['url']    = '' . XOOPS_URL . "/modules/$moduleDirName/viewcat.php?list={$letter}";
3518
            } else {
3519
                $letter_array['letter'] = $letter;
3520
                $letter_array['count']  = 0;
3521
                $letter_array['url']    = '';
3522
            }
3523
            $alphabet_array[$letter] = $letter_array;
3524
            unset($letter_array);
3525
        }
3526
        // Render output
3527 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...
3528
            require_once $GLOBALS['xoops']->path('class/theme.php');
3529
            $GLOBALS['xoTheme'] = new xos_opal_Theme();
3530
        }
3531
        require_once $GLOBALS['xoops']->path('class/template.php');
3532
        $letterschoiceTpl          = new XoopsTpl();
3533
        $letterschoiceTpl->caching = false; // Disable cache
3534
        $letterschoiceTpl->assign('alphabet', $alphabet_array);
3535
        $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...
3536
        unset($letterschoiceTpl);
3537
3538
        return $html;
3539
    }
3540
3541
    /**
3542
     * Create download by letter choice bar/menu
3543
     * updated starting from this idea http://xoops.org/modules/news/article.php?storyid=6497
3544
     *
3545
     * @return string html
3546
     *
3547
     * @access  public
3548
     * @author  luciorota
3549
     */
3550
    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...
3551
    {
3552
        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...
3553
3554
        $moduleDirName = $xoopsModule->getVar('dirname');
3555
        include_once XOOPS_ROOT_PATH . "/modules/$moduleDirName/class/$moduleDirName.php";
3556
3557
        $xoopstube = XoopstubeXoopstube::getInstance();
3558
3559
        $criteria = $xoopstube->getHandler('xoopstube')->getActiveCriteria();
3560
        $criteria->setGroupby('UPPER(LEFT(title,1))');
3561
        $countsByLetters = $xoopstube->getHandler('xoopstube')->getCounts($criteria);
3562
        // Fill alphabet array
3563
        $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...
3564
        $alphabet       = getXtubeAlphabet();
3565
        $alphabet_array = array();
3566 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...
3567
            $letter_array = array();
3568
            if (isset($countsByLetters[$letter])) {
3569
                $letter_array['letter'] = $letter;
3570
                $letter_array['count']  = $countsByLetters[$letter];
3571
                $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...
3572
            } else {
3573
                $letter_array['letter'] = $letter;
3574
                $letter_array['count']  = 0;
3575
                $letter_array['url']    = '';
3576
            }
3577
            $alphabet_array[$letter] = $letter_array;
3578
            unset($letter_array);
3579
        }
3580
        // Render output
3581 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...
3582
            include_once $GLOBALS['xoops']->path('/class/theme.php');
3583
            $GLOBALS['xoTheme'] = new xos_opal_Theme();
3584
        }
3585
        require_once $GLOBALS['xoops']->path('class/template.php');
3586
        $letterschoiceTpl          = new XoopsTpl();
3587
        $letterschoiceTpl->caching = false; // Disable cache
3588
        $letterschoiceTpl->assign('alphabet', $alphabet_array);
3589
        $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...
3590
        unset($letterschoiceTpl);
3591
3592
        return $html;
3593
    }
3594
3595
3596
    //===============  from WF-Downloads   ======================================
3597
3598
    /**
3599
     * @return bool
3600
     */
3601
    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...
3602
    {
3603
        $xoopstube = XoopstubeXoopstube::getInstance();
3604
3605
        static $xtubeIsAdmin;
3606
3607
        if (isset($xtubeIsAdmin)) {
3608
            return $xtubeIsAdmin;
3609
        }
3610
3611
        if (!$GLOBALS['xoopsUser']) {
3612
            $xtubeIsAdmin = false;
3613
        } else {
3614
            $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...
3615
        }
3616
3617
        return $xtubeIsAdmin;
3618
    }
3619
}
3620