Completed
Push — master ( b610c1...53db9c )
by Michael
03:25 queued 01:39
created

NewsUtility::isX23()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 10
Ratio 100 %

Importance

Changes 0
Metric Value
cc 2
eloc 6
nc 2
nop 0
dl 10
loc 10
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
use WideImage\WideImage;
4
use Xmf\Request;
5
6
//require_once dirname(__DIR__) . '/include/common.php';
0 ignored issues
show
Unused Code Comprehensibility introduced by
55% 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...
7
8
/**
9
 * Class NewsUtility
10
 */
11
class NewsUtility extends XoopsObject
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...
12
{
13
    /**
14
     * Function responsible for checking if a directory exists, we can also write in and create an index.html file
15
     *
16
     * @param string $folder The full path of the directory to check
17
     *
18
     * @return void
19
     */
20
    public static function createFolder($folder)
21
    {
22
        //        try {
23
        //            if (!mkdir($folder) && !is_dir($folder)) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
65% 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...
24
        //                throw new \RuntimeException(sprintf('Unable to create the %s directory', $folder));
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% 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...
25
        //            } else {
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...
26
        //                file_put_contents($folder . '/index.html', '<script>history.go(-1);</script>');
0 ignored issues
show
Unused Code Comprehensibility introduced by
54% 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...
27
        //            }
28
        //        }
29
        //        catch (Exception $e) {
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...
30
        //            echo 'Caught exception: ', $e->getMessage(), "\n", '<br>';
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...
31
        //        }
32
        try {
33
            if (!file_exists($folder)) {
34
                if (!mkdir($folder) && !is_dir($folder)) {
35
                    throw new \RuntimeException(sprintf('Unable to create the %s directory', $folder));
36
                } else {
37
                    file_put_contents($folder . '/index.html', '<script>history.go(-1);</script>');
38
                }
39
            }
40
        } catch (Exception $e) {
41
            echo 'Caught exception: ', $e->getMessage(), "\n", '<br>';
42
        }
43
    }
44
45
    /**
46
     * @param $file
47
     * @param $folder
48
     * @return bool
49
     */
50
    public static function copyFile($file, $folder)
51
    {
52
        return copy($file, $folder);
53
        //        try {
54
        //            if (!is_dir($folder)) {
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...
55
        //                throw new \RuntimeException(sprintf('Unable to copy file as: %s ', $folder));
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% 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...
56
        //            } else {
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...
57
        //                return copy($file, $folder);
0 ignored issues
show
Unused Code Comprehensibility introduced by
64% 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...
58
        //            }
59
        //        } catch (Exception $e) {
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...
60
        //            echo 'Caught exception: ', $e->getMessage(), "\n", "<br>";
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...
61
        //        }
62
        //        return false;
63
    }
64
65
    /**
66
     * @param $src
67
     * @param $dst
68
     */
69
    public static function recurseCopy($src, $dst)
70
    {
71
        $dir = opendir($src);
72
        //    @mkdir($dst);
73
        while (false !== ($file = readdir($dir))) {
74
            if (('.' !== $file) && ('..' !== $file)) {
75
                if (is_dir($src . '/' . $file)) {
76
                    self::recurseCopy($src . '/' . $file, $dst . '/' . $file);
77
                } else {
78
                    copy($src . '/' . $file, $dst . '/' . $file);
79
                }
80
            }
81
        }
82
        closedir($dir);
83
    }
84
85
    /**
86
     *
87
     * Verifies XOOPS version meets minimum requirements for this module
88
     * @static
89
     * @param XoopsModule $module
0 ignored issues
show
Documentation introduced by
Should the type for parameter $module not be null|XoopsModule?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
90
     *
91
     * @param null|string $requiredVer
92
     * @return bool true if meets requirements, false if not
93
     */
94
    public static function checkVerXoops(XoopsModule $module = null, $requiredVer = null)
95
    {
96
        $moduleDirName = basename(dirname(__DIR__));
97
        if (null === $module) {
98
            $module = XoopsModule::getByDirname($moduleDirName);
99
        }
100
        xoops_loadLanguage('admin', $moduleDirName);
101
        //check for minimum XOOPS version
102
        $currentVer = substr(XOOPS_VERSION, 6); // get the numeric part of string
103
        $currArray  = explode('.', $currentVer);
104
        if (null === $requiredVer) {
105
            $requiredVer = '' . $module->getInfo('min_xoops'); //making sure it's a string
106
        }
107
        $reqArray = explode('.', $requiredVer);
108
        $success  = true;
109
        foreach ($reqArray as $k => $v) {
110
            if (isset($currArray[$k])) {
111
                if ($currArray[$k] > $v) {
112
                    break;
113
                } elseif ($currArray[$k] == $v) {
114
                    continue;
115
                } else {
116
                    $success = false;
117
                    break;
118
                }
119
            } else {
120
                if ((int)$v > 0) { // handles versions like x.x.x.0_RC2
121
                    $success = false;
122
                    break;
123
                }
124
            }
125
        }
126
127
        if (false === $success) {
128
            $module->setErrors(sprintf(_AM_NEWS_ERROR_BAD_XOOPS, $requiredVer, $currentVer));
129
        }
130
131
        return $success;
132
    }
133
134
    /**
135
     *
136
     * Verifies PHP version meets minimum requirements for this module
137
     * @static
138
     * @param XoopsModule $module
139
     *
140
     * @return bool true if meets requirements, false if not
141
     */
142
    public static function checkVerPhp(XoopsModule $module)
143
    {
144
        xoops_loadLanguage('admin', $module->dirname());
145
        // check for minimum PHP version
146
        $success = true;
147
        $verNum  = PHP_VERSION;
148
        $reqVer  = $module->getInfo('min_php');
149
        if (false !== $reqVer && '' !== $reqVer) {
150
            if (version_compare($verNum, $reqVer, '<')) {
151
                $module->setErrors(sprintf(_AM_NEWS_ERROR_BAD_PHP, $reqVer, $verNum));
152
                $success = false;
153
            }
154
        }
155
156
        return $success;
157
    }
158
159
    /**
160
     * @param             $option
161
     * @param  string     $repmodule
162
     * @return bool|mixed
163
     */
164 View Code Duplication
    public static function getModuleOption($option, $repmodule = 'news')
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...
165
    {
166
        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...
167
        static $tbloptions = [];
168
        if (is_array($tbloptions) && array_key_exists($option, $tbloptions)) {
169
            return $tbloptions[$option];
170
        }
171
172
        $retval = false;
173
        if (isset($xoopsModuleConfig)
174
            && (is_object($xoopsModule) && $xoopsModule->getVar('dirname') == $repmodule
175
                && $xoopsModule->getVar('isactive'))) {
176
            if (isset($xoopsModuleConfig[$option])) {
177
                $retval = $xoopsModuleConfig[$option];
178
            }
179
        } else {
180
            /** @var XoopsModuleHandler $moduleHandler */
181
            $moduleHandler = xoops_getHandler('module');
182
            $module        = $moduleHandler->getByDirname($repmodule);
183
            $configHandler = xoops_getHandler('config');
184
            if ($module) {
185
                $moduleConfig = $configHandler->getConfigsByCat(0, $module->getVar('mid'));
186
                if (isset($moduleConfig[$option])) {
187
                    $retval = $moduleConfig[$option];
188
                }
189
            }
190
        }
191
        $tbloptions[$option] = $retval;
192
193
        return $retval;
194
    }
195
196
    /**
197
     * Updates rating data in item table for a given item
198
     *
199
     * @package       News
200
     * @author        Hervé Thouzard (http://www.herve-thouzard.com)
201
     * @copyright (c) Hervé Thouzard
202
     * @param $storyid
203
     */
204 View Code Duplication
    public static function updateRating($storyid)
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...
205
    {
206
        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...
207
        $query       = 'SELECT rating FROM ' . $xoopsDB->prefix('news_stories_votedata') . ' WHERE storyid = ' . $storyid;
208
        $voteresult  = $xoopsDB->query($query);
209
        $votesDB     = $xoopsDB->getRowsNum($voteresult);
210
        $totalrating = 0;
211
        while (list($rating) = $xoopsDB->fetchRow($voteresult)) {
212
            $totalrating += $rating;
213
        }
214
        $finalrating = $totalrating / $votesDB;
215
        $finalrating = number_format($finalrating, 4);
216
        $sql         = sprintf('UPDATE %s SET rating = %u, votes = %u WHERE storyid = %u', $xoopsDB->prefix('news_stories'), $finalrating, $votesDB, $storyid);
217
        $xoopsDB->queryF($sql);
218
    }
219
220
    /**
221
     * Internal function for permissions
222
     *
223
     * Returns a list of all the permitted topics Ids for the current user
224
     *
225
     * @param string $permtype
226
     *
227
     * @return array $topics    Permitted topics Ids
228
     *
229
     * @package       News
230
     * @author        Hervé Thouzard (http://www.herve-thouzard.com)
231
     * @copyright (c) Hervé Thouzard
232
     */
233 View Code Duplication
    public static function getMyItemIds($permtype = 'news_view')
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...
234
    {
235
        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...
236
        static $tblperms = [];
237
        if (is_array($tblperms) && array_key_exists($permtype, $tblperms)) {
238
            return $tblperms[$permtype];
239
        }
240
241
        /** @var XoopsModuleHandler $moduleHandler */
242
        $moduleHandler       = xoops_getHandler('module');
243
        $newsModule          = $moduleHandler->getByDirname('news');
244
        $groups              = is_object($xoopsUser) ? $xoopsUser->getGroups() : XOOPS_GROUP_ANONYMOUS;
245
        $gpermHandler        = xoops_getHandler('groupperm');
246
        $topics              = $gpermHandler->getItemIds($permtype, $groups, $newsModule->getVar('mid'));
247
        $tblperms[$permtype] = $topics;
248
249
        return $topics;
250
    }
251
252
    /**
253
     * @param $document
254
     *
255
     * @return mixed
256
     */
257 View Code Duplication
    public static function html2text($document)
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...
258
    {
259
        // PHP Manual:: function preg_replace
260
        // $document should contain an HTML document.
261
        // This will remove HTML tags, javascript sections
262
        // and white space. It will also convert some
263
        // common HTML entities to their text equivalent.
264
265
        $search = [
266
            "'<script[^>]*?>.*?</script>'si", // Strip out javascript
267
            "'<img.*?>'si", // Strip out img tags
268
            "'<[\/\!]*?[^<>]*?>'si", // Strip out HTML tags
269
            "'([\r\n])[\s]+'", // Strip out white space
270
            "'&(quot|#34);'i", // Replace HTML entities
271
            "'&(amp|#38);'i",
272
            "'&(lt|#60);'i",
273
            "'&(gt|#62);'i",
274
            "'&(nbsp|#160);'i",
275
            "'&(iexcl|#161);'i",
276
            "'&(cent|#162);'i",
277
            "'&(pound|#163);'i",
278
            "'&(copy|#169);'i"
279
        ]; // evaluate as php
280
281
        $replace = [
282
            '',
283
            '',
284
            '',
285
            "\\1",
286
            '"',
287
            '&',
288
            '<',
289
            '>',
290
            ' ',
291
            chr(161),
292
            chr(162),
293
            chr(163),
294
            chr(169),
295
        ];
296
297
        $text = preg_replace($search, $replace, $document);
298
299
        preg_replace_callback('/&#(\d+);/', function ($matches) {
300
            return chr($matches[1]);
301
        }, $document);
302
303
        return $text;
304
    }
305
306
    /**
307
     * Is Xoops 2.3.x ?
308
     *
309
     * @return boolean need to say it ?
310
     */
311 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...
312
    {
313
        $x23 = false;
314
        $xv  = str_replace('XOOPS ', '', XOOPS_VERSION);
315
        if (substr($xv, 2, 1) >= '3') {
316
            $x23 = true;
317
        }
318
319
        return $x23;
320
    }
321
322
    /**
323
     * Retreive an editor according to the module's option "form_options"
324
     *
325
     * @package       News
326
     * @author        Hervé Thouzard (http://www.herve-thouzard.com)
327
     * @copyright (c) Hervé Thouzard
328
     * @param                                                                                                                                 $caption
329
     * @param                                                                                                                                 $name
330
     * @param  string                                                                                                                         $value
331
     * @param  string                                                                                                                         $width
332
     * @param  string                                                                                                                         $height
333
     * @param  string                                                                                                                         $supplemental
334
     * @return bool|XoopsFormDhtmlTextArea|XoopsFormEditor|XoopsFormFckeditor|XoopsFormHtmlarea|XoopsFormTextArea|XoopsFormTinyeditorTextArea
0 ignored issues
show
Documentation introduced by
Should the return type not be XoopsFormEditor|XoopsFor...oopsFormWysiwygTextArea?

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...
335
     */
336 View Code Duplication
    public static function getWysiwygForm($caption, $name, $value = '', $width = '100%', $height = '400px', $supplemental = '')
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...
337
    {
338
        $editor_option            = strtolower(static::getModuleOption('form_options'));
339
        $editor                   = false;
340
        $editor_configs           = [];
341
        $editor_configs['name']   = $name;
342
        $editor_configs['value']  = $value;
343
        $editor_configs['rows']   = 35;
344
        $editor_configs['cols']   = 60;
345
        $editor_configs['width']  = '100%';
346
        $editor_configs['height'] = '350px';
347
        $editor_configs['editor'] = $editor_option;
348
349
        if (static::isX23()) {
350
            $editor = new XoopsFormEditor($caption, $name, $editor_configs);
351
352
            return $editor;
353
        }
354
355
        // Only for Xoops 2.0.x
356
        switch ($editor_option) {
357
            case 'fckeditor':
358
                if (is_readable(XOOPS_ROOT_PATH . '/class/fckeditor/formfckeditor.php')) {
359
                    require_once XOOPS_ROOT_PATH . '/class/fckeditor/formfckeditor.php';
360
                    $editor = new XoopsFormFckeditor($caption, $name, $value);
361
                }
362
                break;
363
364
            case 'htmlarea':
365
                if (is_readable(XOOPS_ROOT_PATH . '/class/htmlarea/formhtmlarea.php')) {
366
                    require_once XOOPS_ROOT_PATH . '/class/htmlarea/formhtmlarea.php';
367
                    $editor = new XoopsFormHtmlarea($caption, $name, $value);
368
                }
369
                break;
370
371
            case 'dhtmltextarea':
372
            case 'dhtml':
373
                $editor = new XoopsFormDhtmlTextArea($caption, $name, $value, 10, 50, $supplemental);
374
                break;
375
376
            case 'textarea':
377
                $editor = new XoopsFormTextArea($caption, $name, $value);
378
                break;
379
380
            case 'tinyeditor':
381
            case 'tinymce':
382
                if (is_readable(XOOPS_ROOT_PATH . '/class/xoopseditor/tinyeditor/formtinyeditortextarea.php')) {
383
                    require_once XOOPS_ROOT_PATH . '/class/xoopseditor/tinyeditor/formtinyeditortextarea.php';
384
                    $editor = new XoopsFormTinyeditorTextArea([
385
                                                                  'caption' => $caption,
386
                                                                  'name'    => $name,
387
                                                                  'value'   => $value,
388
                                                                  'width'   => '100%',
389
                                                                  'height'  => '400px'
390
                                                              ]);
391
                }
392
                break;
393
394
            case 'koivi':
395
                if (is_readable(XOOPS_ROOT_PATH . '/class/wysiwyg/formwysiwygtextarea.php')) {
396
                    require_once XOOPS_ROOT_PATH . '/class/wysiwyg/formwysiwygtextarea.php';
397
                    $editor = new XoopsFormWysiwygTextArea($caption, $name, $value, $width, $height, '');
398
                }
399
                break;
400
        }
401
402
        return $editor;
403
    }
404
405
    /**
406
     * Internal function
407
     *
408
     * @package       News
409
     * @author        Hervé Thouzard (http://www.herve-thouzard.com)
410
     * @copyright (c) Hervé Thouzard
411
     * @param $text
412
     * @return mixed
413
     */
414
    public static function getDublinQuotes($text)
415
    {
416
        return str_replace('"', ' ', $text);
417
    }
418
419
    /**
420
     * Creates all the meta datas :
421
     * - For Mozilla/Netscape and Opera the site navigation's bar
422
     * - The Dublin's Core Metadata
423
     * - The link for Firefox 2 micro summaries
424
     * - The meta keywords
425
     * - The meta description
426
     *
427
     * @package       News
428
     * @author        Hervé Thouzard (http://www.herve-thouzard.com)
429
     * @copyright (c) Hervé Thouzard
430
     * @param null $story
431
     */
432
    public static function createMetaDatas($story = null)
433
    {
434
        global $xoopsConfig, $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...
435
        $content = '';
436
        $myts    = MyTextSanitizer::getInstance();
437
        require_once XOOPS_ROOT_PATH . '/modules/news/class/class.newstopic.php';
438
439
        /**
440
         * Firefox and Opera Navigation's Bar
441
         */
442 View Code Duplication
        if (static::getModuleOption('sitenavbar')) {
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...
443
            $content .= sprintf("<link rel=\"Home\" title=\"%s\" href=\"%s/\">\n", $xoopsConfig['sitename'], XOOPS_URL);
444
            $content .= sprintf("<link rel=\"Contents\" href=\"%s\">\n", XOOPS_URL . '/modules/news/index.php');
445
            $content .= sprintf("<link rel=\"Search\" href=\"%s\">\n", XOOPS_URL . '/search.php');
446
            $content .= sprintf("<link rel=\"Glossary\" href=\"%s\">\n", XOOPS_URL . '/modules/news/archive.php');
447
            $content .= sprintf("<link rel=\"%s\" href=\"%s\">\n", $myts->htmlSpecialChars(_NW_SUBMITNEWS), XOOPS_URL . '/modules/news/submit.php');
448
            $content .= sprintf("<link rel=\"alternate\" type=\"application/rss+xml\" title=\"%s\" href=\"%s/\">\n", $xoopsConfig['sitename'], XOOPS_URL . '/backend.php');
449
450
            // Create chapters
451
            require_once XOOPS_ROOT_PATH . '/class/tree.php';
452
            require_once XOOPS_ROOT_PATH . '/modules/news/class/class.newstopic.php';
453
            $xt         = new NewsTopic();
454
            $allTopics  = $xt->getAllTopics(static::getModuleOption('restrictindex'));
455
            $topic_tree = new XoopsObjectTree($allTopics, 'topic_id', 'topic_pid');
456
            $topics_arr = $topic_tree->getAllChild(0);
457
            foreach ($topics_arr as $onetopic) {
458
                $content .= sprintf("<link rel=\"Chapter\" title=\"%s\" href=\"%s\">\n", $onetopic->topic_title(), XOOPS_URL . '/modules/news/index.php?storytopic=' . $onetopic->topic_id());
459
            }
460
        }
461
462
        /**
463
         * Meta Keywords and Description
464
         * If you have set this module's option to 'yes' and if the information was entered, then they are rendered in the page else they are computed
465
         */
466
        $meta_keywords = '';
467 View Code Duplication
        if (isset($story) && is_object($story)) {
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...
468
            if ('' !== xoops_trim($story->keywords())) {
469
                $meta_keywords = $story->keywords();
470
            } else {
471
                $meta_keywords = static::createMetaKeywords($story->hometext() . ' ' . $story->bodytext());
472
            }
473
            if ('' !== xoops_trim($story->description())) {
474
                $meta_description = strip_tags($story->description);
475
            } else {
476
                $meta_description = strip_tags($story->title);
477
            }
478
            if (isset($xoTheme) && is_object($xoTheme)) {
479
                $xoTheme->addMeta('meta', 'keywords', $meta_keywords);
480
                $xoTheme->addMeta('meta', 'description', $meta_description);
481
            } elseif (isset($xoopsTpl) && is_object($xoopsTpl)) { // Compatibility for old Xoops versions
482
                $xoopsTpl->assign('xoops_meta_keywords', $meta_keywords);
483
                $xoopsTpl->assign('xoops_meta_description', $meta_description);
484
            }
485
        }
486
487
        /**
488
         * Dublin Core's meta datas
489
         */
490 View Code Duplication
        if (static::getModuleOption('dublincore') && isset($story) && is_object($story)) {
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...
491
            $configHandler         = xoops_getHandler('config');
492
            $xoopsConfigMetaFooter = $configHandler->getConfigsByCat(XOOPS_CONF_METAFOOTER);
493
            $content               .= '<meta name="DC.Title" content="' . static::getDublinQuotes($story->title()) . "\">\n";
494
            $content               .= '<meta name="DC.Creator" content="' . static::getDublinQuotes($story->uname()) . "\">\n";
495
            $content               .= '<meta name="DC.Subject" content="' . static::getDublinQuotes($meta_keywords) . "\">\n";
496
            $content               .= '<meta name="DC.Description" content="' . static::getDublinQuotes($story->title()) . "\">\n";
497
            $content               .= '<meta name="DC.Publisher" content="' . static::getDublinQuotes($xoopsConfig['sitename']) . "\">\n";
498
            $content               .= '<meta name="DC.Date.created" scheme="W3CDTF" content="' . date('Y-m-d', $story->created) . "\">\n";
499
            $content               .= '<meta name="DC.Date.issued" scheme="W3CDTF" content="' . date('Y-m-d', $story->published) . "\">\n";
500
            $content               .= '<meta name="DC.Identifier" content="' . XOOPS_URL . '/modules/news/article.php?storyid=' . $story->storyid() . "\">\n";
501
            $content               .= '<meta name="DC.Source" content="' . XOOPS_URL . "\">\n";
502
            $content               .= '<meta name="DC.Language" content="' . _LANGCODE . "\">\n";
503
            $content               .= '<meta name="DC.Relation.isReferencedBy" content="' . XOOPS_URL . '/modules/news/index.php?storytopic=' . $story->topicid() . "\">\n";
504
            if (isset($xoopsConfigMetaFooter['meta_copyright'])) {
505
                $content .= '<meta name="DC.Rights" content="' . static::getDublinQuotes($xoopsConfigMetaFooter['meta_copyright']) . "\">\n";
506
            }
507
        }
508
509
        /**
510
         * Firefox 2 micro summaries
511
         */
512
        if (static::getModuleOption('firefox_microsummaries')) {
513
            $content .= sprintf("<link rel=\"microsummary\" href=\"%s\">\n", XOOPS_URL . '/modules/news/micro_summary.php');
514
        }
515
516
        if (isset($xoopsTpl) && is_object($xoopsTpl)) {
517
            $xoopsTpl->assign('xoops_module_header', $content);
518
        }
519
    }
520
521
    /**
522
     * Create the meta keywords based on the content
523
     *
524
     * @package       News
525
     * @author        Hervé Thouzard (http://www.herve-thouzard.com)
526
     * @copyright (c) Hervé Thouzard
527
     * @param $content
528
     * @return string
529
     */
530 View Code Duplication
    public static function createMetaKeywords($content)
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
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...
531
    {
532
        include XOOPS_ROOT_PATH . '/modules/news/config.php';
533
        require_once XOOPS_ROOT_PATH . '/modules/news/class/blacklist.php';
534
        require_once XOOPS_ROOT_PATH . '/modules/news/class/registryfile.php';
535
536
        if (!$cfg['meta_keywords_auto_generate']) {
0 ignored issues
show
Bug introduced by
The variable $cfg does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
537
            return '';
538
        }
539
        $registry = new news_registryfile('news_metagen_options.txt');
540
        //    $tcontent = '';
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...
541
        $tcontent = $registry->getfile();
542
        if ('' !== xoops_trim($tcontent)) {
543
            list($keywordscount, $keywordsorder) = explode(',', $tcontent);
544
        } else {
545
            $keywordscount = $cfg['meta_keywords_count'];
546
            $keywordsorder = $cfg['meta_keywords_order'];
547
        }
548
549
        $tmp = [];
550
        // Search for the "Minimum keyword length"
551
        if (isset($_SESSION['news_keywords_limit'])) {
552
            $limit = $_SESSION['news_keywords_limit'];
553
        } else {
554
            $configHandler                   = xoops_getHandler('config');
555
            $xoopsConfigSearch               = $configHandler->getConfigsByCat(XOOPS_CONF_SEARCH);
556
            $limit                           = $xoopsConfigSearch['keyword_min'];
557
            $_SESSION['news_keywords_limit'] = $limit;
558
        }
559
        $myts            = MyTextSanitizer::getInstance();
560
        $content         = str_replace('<br>', ' ', $content);
561
        $content         = $myts->undoHtmlSpecialChars($content);
562
        $content         = strip_tags($content);
563
        $content         = strtolower($content);
564
        $search_pattern  = [
565
            '&nbsp;',
566
            "\t",
567
            "\r\n",
568
            "\r",
569
            "\n",
570
            ',',
571
            '.',
572
            "'",
573
            ';',
574
            ':',
575
            ')',
576
            '(',
577
            '"',
578
            '?',
579
            '!',
580
            '{',
581
            '}',
582
            '[',
583
            ']',
584
            '<',
585
            '>',
586
            '/',
587
            '+',
588
            '-',
589
            '_',
590
            '\\',
591
            '*'
592
        ];
593
        $replace_pattern = [
594
            ' ',
595
            ' ',
596
            ' ',
597
            ' ',
598
            ' ',
599
            ' ',
600
            ' ',
601
            ' ',
602
            '',
603
            '',
604
            '',
605
            '',
606
            '',
607
            '',
608
            '',
609
            '',
610
            '',
611
            '',
612
            '',
613
            '',
614
            '',
615
            '',
616
            '',
617
            '',
618
            '',
619
            '',
620
            ''
621
        ];
622
        $content         = str_replace($search_pattern, $replace_pattern, $content);
623
        $keywords        = explode(' ', $content);
624
        switch ($keywordsorder) {
625
            case 0: // Ordre d'apparition dans le texte
626
                $keywords = array_unique($keywords);
627
                break;
628
            case 1: // Ordre de fréquence des mots
629
                $keywords = array_count_values($keywords);
630
                asort($keywords);
631
                $keywords = array_keys($keywords);
632
                break;
633
            case 2: // Ordre inverse de la fréquence des mots
634
                $keywords = array_count_values($keywords);
635
                arsort($keywords);
636
                $keywords = array_keys($keywords);
637
                break;
638
        }
639
        // Remove black listed words
640
        $metablack = new news_blacklist();
641
        $words     = $metablack->getAllKeywords();
0 ignored issues
show
Unused Code introduced by
$words 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...
642
        $keywords  = $metablack->remove_blacklisted($keywords);
643
644
        foreach ($keywords as $keyword) {
645
            if (strlen($keyword) >= $limit && !is_numeric($keyword)) {
646
                $tmp[] = $keyword;
647
            }
648
        }
649
        $tmp = array_slice($tmp, 0, $keywordscount);
650
        if (count($tmp) > 0) {
651
            return implode(',', $tmp);
652
        } else {
653
            if (!isset($configHandler) || !is_object($configHandler)) {
654
                $configHandler = xoops_getHandler('config');
655
            }
656
            $xoopsConfigMetaFooter = $configHandler->getConfigsByCat(XOOPS_CONF_METAFOOTER);
657
            if (isset($xoopsConfigMetaFooter['meta_keywords'])) {
658
                return $xoopsConfigMetaFooter['meta_keywords'];
659
            } else {
660
                return '';
661
            }
662
        }
663
    }
664
665
    /**
666
     * Remove module's cache
667
     *
668
     * @package       News
669
     * @author        Hervé Thouzard (http://www.herve-thouzard.com)
670
     * @copyright (c) Hervé Thouzard
671
     */
672 View Code Duplication
    public static function updateCache()
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...
673
    {
674
        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...
675
        $folder  = $xoopsModule->getVar('dirname');
676
        $tpllist = [];
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...
677
        require_once XOOPS_ROOT_PATH . '/class/xoopsblock.php';
678
        require_once XOOPS_ROOT_PATH . '/class/template.php';
679
        $tplfileHandler = xoops_getHandler('tplfile');
680
        $tpllist        = $tplfileHandler->find(null, null, null, $folder);
681
        $xoopsTpl       = new XoopsTpl();
0 ignored issues
show
Unused Code introduced by
$xoopsTpl 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...
682
        xoops_template_clear_module_cache($xoopsModule->getVar('mid')); // Clear module's blocks cache
683
684
        // Remove cache for each page.
685
        foreach ($tpllist as $onetemplate) {
686
            if ('module' === $onetemplate->getVar('tpl_type')) {
687
                // 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
688
                $files_del = [];
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...
689
                $files_del = glob(XOOPS_CACHE_PATH . '/*' . $onetemplate->getVar('tpl_file') . '*');
690
                if (count($files_del) > 0) {
691
                    foreach ($files_del as $one_file) {
692
                        unlink($one_file);
693
                    }
694
                }
695
            }
696
        }
697
    }
698
699
    /**
700
     * Verify that a mysql table exists
701
     *
702
     * @package       News
703
     * @author        Hervé Thouzard (http://www.herve-thouzard.com)
704
     * @copyright (c) Hervé Thouzard
705
     * @param $tablename
706
     * @return bool
707
     */
708
    public static function existTable($tablename)
709
    {
710
        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...
711
        $result = $xoopsDB->queryF("SHOW TABLES LIKE '$tablename'");
712
713
        return ($xoopsDB->getRowsNum($result) > 0);
714
    }
715
716
    /**
717
     * Verify that a field exists inside a mysql table
718
     *
719
     * @package       News
720
     * @author        Hervé Thouzard (http://www.herve-thouzard.com)
721
     * @copyright (c) Hervé Thouzard
722
     * @param $fieldname
723
     * @param $table
724
     * @return bool
725
     */
726
    public static function existField($fieldname, $table)
727
    {
728
        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...
729
        $result = $xoopsDB->queryF("SHOW COLUMNS FROM   $table LIKE '$fieldname'");
730
731
        return ($xoopsDB->getRowsNum($result) > 0);
732
    }
733
734
    /**
735
     * Add a field to a mysql table
736
     *
737
     * @package       News
738
     * @author        Hervé Thouzard (http://www.herve-thouzard.com)
739
     * @copyright (c) Hervé Thouzard
740
     * @param $field
741
     * @param $table
742
     * @return bool|\mysqli_result
743
     */
744
    public static function addField($field, $table)
745
    {
746
        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...
747
        $result = $xoopsDB->queryF('ALTER TABLE ' . $table . " ADD $field;");
748
749
        return $result;
750
    }
751
752
    /**
753
     * Verify that the current user is a member of the Admin group
754
     */
755 View Code Duplication
    public static function isAdminGroup()
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...
756
    {
757
        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...
758
        if (is_object($xoopsUser)) {
759
            if (in_array('1', $xoopsUser->getGroups())) {
760
                return true;
761
            } else {
762
                if ($xoopsUser->isAdmin($xoopsModule->mid())) {
763
                    return true;
764
                } else {
765
                    return false;
766
                }
767
            }
768
        } else {
769
            return false;
770
        }
771
    }
772
773
    /**
774
     * Verify if the current "user" is a bot or not
775
     *
776
     * If you have a problem with this function, insert the folowing code just before the line if (isset($_SESSION['news_cache_bot'])) { :
777
     * return false;
778
     *
779
     * @package       News
780
     * @author        Hervé Thouzard (http://www.herve-thouzard.com)
781
     * @copyright (c) Hervé Thouzard
782
     */
783 View Code Duplication
    public static function isBot()
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

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

Loading history...
Duplication introduced by
This 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
isBot 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...
784
    {
785
        if (isset($_SESSION['news_cache_bot'])) {
786
            return $_SESSION['news_cache_bot'];
787
        } else {
788
            // Add here every bot you know separated by a pipe | (not matter with the upper or lower cases)
789
            // If you want to see the result for yourself, add your navigator's user agent at the end (mozilla for example)
790
            $botlist      = 'AbachoBOT|Arachnoidea|ASPSeek|Atomz|cosmos|crawl25-public.alexa.com|CrawlerBoy Pinpoint.com|Crawler|DeepIndex|EchO!|exabot|Excalibur Internet Spider|FAST-WebCrawler|Fluffy the spider|GAIS Robot/1.0B2|GaisLab data gatherer|Google|Googlebot-Image|googlebot|Gulliver|ia_archiver|Infoseek|Links2Go|Lycos_Spider_(modspider)|Lycos_Spider_(T-Rex)|MantraAgent|Mata Hari|Mercator|MicrosoftPrototypeCrawler|[email protected]|MSNBOT|NEC Research Agent|NetMechanic|Nokia-WAPToolkit|nttdirectory_robot|Openfind|Oracle Ultra Search|PicoSearch|Pompos|Scooter|Slider_Search_v1-de|Slurp|Slurp.so|SlySearch|Spider|Spinne|SurferF3|Surfnomore Spider|suzuran|teomaagent1|TurnitinBot|Ultraseek|VoilaBot|vspider|W3C_Validator|Web Link Validator|WebTrends|WebZIP|whatUseek_winona|WISEbot|Xenu Link Sleuth|ZyBorg';
791
            $botlist      = strtoupper($botlist);
792
            $currentagent = strtoupper(xoops_getenv('HTTP_USER_AGENT'));
793
            $retval       = false;
794
            $botarray     = explode('|', $botlist);
795
            foreach ($botarray as $onebot) {
796
                if (false !== strpos($currentagent, $onebot)) {
797
                    $retval = true;
798
                    break;
799
                }
800
            }
801
        }
802
        $_SESSION['news_cache_bot'] = $retval;
803
804
        return $retval;
805
    }
806
807
    /**
808
     * Create an infotip
809
     *
810
     * @package       News
811
     * @author        Hervé Thouzard (http://www.herve-thouzard.com)
812
     * @copyright (c) Hervé Thouzard
813
     * @param $text
814
     * @return null
815
     */
816 View Code Duplication
    public static function makeInfotips($text)
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...
817
    {
818
        $infotips = static::getModuleOption('infotips');
819
        if ($infotips > 0) {
820
            $myts = MyTextSanitizer::getInstance();
821
822
            return $myts->htmlSpecialChars(xoops_substr(strip_tags($text), 0, $infotips));
823
        }
824
825
        return null;
826
    }
827
828
    /**
829
     * @author   Monte Ohrt <monte at ohrt dot com>, modified by Amos Robinson
830
     *           <amos dot robinson at gmail dot com>
831
     * @param $string
832
     * @return string
833
     */
834 View Code Duplication
    public static function closeTags($string)
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...
835
    {
836
        // match opened tags
837
        if (preg_match_all('/<([a-z\:\-]+)[^\/]>/', $string, $start_tags)) {
838
            $start_tags = $start_tags[1];
839
            // match closed tags
840
            if (preg_match_all('/<\/([a-z]+)>/', $string, $end_tags)) {
841
                $complete_tags = [];
842
                $end_tags      = $end_tags[1];
843
844
                foreach ($start_tags as $key => $val) {
845
                    $posb = array_search($val, $end_tags);
846
                    if (is_int($posb)) {
847
                        unset($end_tags[$posb]);
848
                    } else {
849
                        $complete_tags[] = $val;
850
                    }
851
                }
852
            } else {
853
                $complete_tags = $start_tags;
854
            }
855
856
            $complete_tags = array_reverse($complete_tags);
857
            for ($i = 0, $iMax = count($complete_tags); $i < $iMax; ++$i) {
858
                $string .= '</' . $complete_tags[$i] . '>';
859
            }
860
        }
861
862
        return $string;
863
    }
864
865
    /**
866
     * Smarty truncate_tagsafe modifier plugin
867
     *
868
     * Type:     modifier<br>
869
     * Name:     truncate_tagsafe<br>
870
     * Purpose:  Truncate a string to a certain length if necessary,
871
     *           optionally splitting in the middle of a word, and
872
     *           appending the $etc string or inserting $etc into the middle.
873
     *           Makes sure no tags are left half-open or half-closed
874
     *           (e.g. "Banana in a <a...")
875
     *
876
     * @author   Monte Ohrt <monte at ohrt dot com>, modified by Amos Robinson
877
     *           <amos dot robinson at gmail dot com>
878
     *
879
     * @param string
880
     * @param integer
881
     * @param string
882
     * @param boolean
883
     * @param boolean
884
     *
885
     * @return string
886
     */
887 View Code Duplication
    public static function truncateTagSafe($string, $length = 80, $etc = '...', $break_words = false)
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...
888
    {
889
        if (0 == $length) {
890
            return '';
891
        }
892
        if (strlen($string) > $length) {
893
            $length -= strlen($etc);
894
            if (!$break_words) {
895
                $string = preg_replace('/\s+?(\S+)?$/', '', substr($string, 0, $length + 1));
896
                $string = preg_replace('/<[^>]*$/', '', $string);
897
                $string = static::closeTags($string);
898
            }
899
900
            return $string . $etc;
901
        } else {
902
            return $string;
903
        }
904
    }
905
906
    /**
907
     * Resize a Picture to some given dimensions (using the wideImage library)
908
     *
909
     * @param string  $src_path      Picture's source
910
     * @param string  $dst_path      Picture's destination
911
     * @param integer $param_width   Maximum picture's width
912
     * @param integer $param_height  Maximum picture's height
913
     * @param boolean $keep_original Do we have to keep the original picture ?
914
     * @param string  $fit           Resize mode (see the wideImage library for more information)
915
     *
916
     * @return bool
917
     */
918 View Code Duplication
    public static function resizePicture(
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...
919
        $src_path,
920
        $dst_path,
921
        $param_width,
922
        $param_height,
923
        $keep_original = false,
924
        $fit = 'inside'
925
    ) {
926
        //    require_once XOOPS_PATH . '/vendor/wideimage/WideImage.php';
927
        $resize            = true;
928
        $pictureDimensions = getimagesize($src_path);
929
        if (is_array($pictureDimensions)) {
930
            $pictureWidth  = $pictureDimensions[0];
931
            $pictureHeight = $pictureDimensions[1];
932
            if ($pictureWidth < $param_width && $pictureHeight < $param_height) {
933
                $resize = false;
934
            }
935
        }
936
937
        $img = WideImage::load($src_path);
938
        if ($resize) {
939
            $result = $img->resize($param_width, $param_height, $fit);
940
            $result->saveToFile($dst_path);
941
        } else {
942
            @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...
943
        }
944
        if (!$keep_original) {
945
            @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...
946
        }
947
948
        return true;
949
    }
950
}
951