Completed
Pull Request — master (#16)
by Michael
01:51
created

include/functions.php (36 issues)

Upgrade to new PHP Analysis Engine

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

1
<?php
2
/*
3
 * You may not change or alter any portion of this comment or credits
4
 * of supporting developers from this source code or any supporting source code
5
 * which is considered copyrighted (c) material of the original comment or credit authors.
6
 *
7
 * This program is distributed in the hope that it will be useful,
8
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
9
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10
 */
11
12
/**
13
 * @copyright      {@link https://xoops.org/ XOOPS Project}
14
 * @license        {@link http://www.gnu.org/licenses/gpl-2.0.html GNU GPL 2 or later}
15
 * @package
16
 * @since
17
 * @author         XOOPS Development Team
18
 * @author         Hervé Thouzard (http://www.herve-thouzard.com)
19
 */
20
21
// defined('XOOPS_ROOT_PATH') || exit('Restricted access.');
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...
22
23
/**
24
 * Returns a module's option
25
 *
26
 * Return's a module's option (for the news module)
27
 *
28
 * @param string $option module option's name
29
 *
30
 * @param string $repmodule
31
 *
32
 * @return bool
33
 */
34
35
use WideImage\WideImage;
36
37
/**
38
 * @param             $option
39
 * @param  string     $repmodule
40
 * @return bool|mixed
41
 */
42 View Code Duplication
function news_getmoduleoption($option, $repmodule = 'news')
0 ignored issues
show
This function 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...
43
{
44
    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...
45
    static $tbloptions = [];
46
    if (is_array($tbloptions) && array_key_exists($option, $tbloptions)) {
47
        return $tbloptions[$option];
48
    }
49
50
    $retval = false;
51
    if (isset($xoopsModuleConfig)
52
        && (is_object($xoopsModule) && $xoopsModule->getVar('dirname') == $repmodule
53
            && $xoopsModule->getVar('isactive'))) {
54
        if (isset($xoopsModuleConfig[$option])) {
55
            $retval = $xoopsModuleConfig[$option];
56
        }
57
    } else {
58
        /** @var XoopsModuleHandler $moduleHandler */
59
        $moduleHandler = xoops_getHandler('module');
60
        $module        = $moduleHandler->getByDirname($repmodule);
61
        $configHandler = xoops_getHandler('config');
62
        if ($module) {
63
            $moduleConfig = $configHandler->getConfigsByCat(0, $module->getVar('mid'));
64
            if (isset($moduleConfig[$option])) {
65
                $retval = $moduleConfig[$option];
66
            }
67
        }
68
    }
69
    $tbloptions[$option] = $retval;
70
71
    return $retval;
72
}
73
74
/**
75
 * Updates rating data in item table for a given item
76
 *
77
 * @package       News
78
 * @author        Hervé Thouzard (http://www.herve-thouzard.com)
79
 * @copyright (c) Hervé Thouzard
80
 * @param $storyid
81
 */
82 View Code Duplication
function news_updaterating($storyid)
0 ignored issues
show
This function 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...
83
{
84
    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...
85
    $query       = 'SELECT rating FROM ' . $xoopsDB->prefix('news_stories_votedata') . ' WHERE storyid = ' . $storyid;
86
    $voteresult  = $xoopsDB->query($query);
87
    $votesDB     = $xoopsDB->getRowsNum($voteresult);
88
    $totalrating = 0;
89
    while (list($rating) = $xoopsDB->fetchRow($voteresult)) {
90
        $totalrating += $rating;
91
    }
92
    $finalrating = $totalrating / $votesDB;
93
    $finalrating = number_format($finalrating, 4);
94
    $sql         = sprintf('UPDATE %s SET rating = %u, votes = %u WHERE storyid = %u', $xoopsDB->prefix('news_stories'), $finalrating, $votesDB, $storyid);
95
    $xoopsDB->queryF($sql);
96
}
97
98
/**
99
 * Internal function for permissions
100
 *
101
 * Returns a list of all the permitted topics Ids for the current user
102
 *
103
 * @param string $permtype
104
 *
105
 * @return array $topics    Permitted topics Ids
106
 *
107
 * @package       News
108
 * @author        Hervé Thouzard (http://www.herve-thouzard.com)
109
 * @copyright (c) Hervé Thouzard
110
 */
111 View Code Duplication
function news_MygetItemIds($permtype = 'news_view')
0 ignored issues
show
This function 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...
112
{
113
    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...
114
    static $tblperms = [];
115
    if (is_array($tblperms) && array_key_exists($permtype, $tblperms)) {
116
        return $tblperms[$permtype];
117
    }
118
119
    /** @var XoopsModuleHandler $moduleHandler */
120
    $moduleHandler       = xoops_getHandler('module');
121
    $newsModule          = $moduleHandler->getByDirname('news');
122
    $groups              = is_object($xoopsUser) ? $xoopsUser->getGroups() : XOOPS_GROUP_ANONYMOUS;
123
    $gpermHandler        = xoops_getHandler('groupperm');
124
    $topics              = $gpermHandler->getItemIds($permtype, $groups, $newsModule->getVar('mid'));
125
    $tblperms[$permtype] = $topics;
126
127
    return $topics;
128
}
129
130
/**
131
 * @param $document
132
 *
133
 * @return mixed
134
 */
135 View Code Duplication
function news_html2text($document)
0 ignored issues
show
This function 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...
136
{
137
    // PHP Manual:: function preg_replace
138
    // $document should contain an HTML document.
139
    // This will remove HTML tags, javascript sections
140
    // and white space. It will also convert some
141
    // common HTML entities to their text equivalent.
142
143
    $search = [
144
        "'<script[^>]*?>.*?</script>'si", // Strip out javascript
145
        "'<img.*?>'si", // Strip out img tags
146
        "'<[\/\!]*?[^<>]*?>'si", // Strip out HTML tags
147
        "'([\r\n])[\s]+'", // Strip out white space
148
        "'&(quot|#34);'i", // Replace HTML entities
149
        "'&(amp|#38);'i",
150
        "'&(lt|#60);'i",
151
        "'&(gt|#62);'i",
152
        "'&(nbsp|#160);'i",
153
        "'&(iexcl|#161);'i",
154
        "'&(cent|#162);'i",
155
        "'&(pound|#163);'i",
156
        "'&(copy|#169);'i"
157
    ]; // evaluate as php
158
159
    $replace = [
160
        '',
161
        '',
162
        '',
163
        "\\1",
164
        '"',
165
        '&',
166
        '<',
167
        '>',
168
        ' ',
169
        chr(161),
170
        chr(162),
171
        chr(163),
172
        chr(169),
173
    ];
174
175
    $text = preg_replace($search, $replace, $document);
176
177
    preg_replace_callback('/&#(\d+);/', function ($matches) {
178
        return chr($matches[1]);
179
    }, $document);
180
181
    return $text;
182
}
183
184
/**
185
 * Is Xoops 2.3.x ?
186
 *
187
 * @return boolean need to say it ?
188
 */
189 View Code Duplication
function news_isX23()
0 ignored issues
show
This function 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...
190
{
191
    $x23 = false;
192
    $xv  = str_replace('XOOPS ', '', XOOPS_VERSION);
193
    if (substr($xv, 2, 1) >= '3') {
194
        $x23 = true;
195
    }
196
197
    return $x23;
198
}
199
200
/**
201
 * Retreive an editor according to the module's option "form_options"
202
 *
203
 * @package       News
204
 * @author        Hervé Thouzard (http://www.herve-thouzard.com)
205
 * @copyright (c) Hervé Thouzard
206
 * @param                                                                                                                                 $caption
207
 * @param                                                                                                                                 $name
208
 * @param  string                                                                                                                         $value
209
 * @param  string                                                                                                                         $width
210
 * @param  string                                                                                                                         $height
211
 * @param  string                                                                                                                         $supplemental
212
 * @return bool|XoopsFormDhtmlTextArea|XoopsFormEditor|XoopsFormFckeditor|XoopsFormHtmlarea|XoopsFormTextArea|XoopsFormTinyeditorTextArea
0 ignored issues
show
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...
213
 */
214 View Code Duplication
function news_getWysiwygForm($caption, $name, $value = '', $width = '100%', $height = '400px', $supplemental = '')
0 ignored issues
show
This function 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...
215
{
216
    $editor_option            = strtolower(news_getmoduleoption('form_options'));
217
    $editor                   = false;
218
    $editor_configs           = [];
219
    $editor_configs['name']   = $name;
220
    $editor_configs['value']  = $value;
221
    $editor_configs['rows']   = 35;
222
    $editor_configs['cols']   = 60;
223
    $editor_configs['width']  = '100%';
224
    $editor_configs['height'] = '350px';
225
    $editor_configs['editor'] = $editor_option;
226
227
    if (news_isX23()) {
228
        $editor = new XoopsFormEditor($caption, $name, $editor_configs);
229
230
        return $editor;
231
    }
232
233
    // Only for Xoops 2.0.x
234
    switch ($editor_option) {
235
        case 'fckeditor':
236
            if (is_readable(XOOPS_ROOT_PATH . '/class/fckeditor/formfckeditor.php')) {
237
                require_once XOOPS_ROOT_PATH . '/class/fckeditor/formfckeditor.php';
238
                $editor = new XoopsFormFckeditor($caption, $name, $value);
239
            }
240
            break;
241
242
        case 'htmlarea':
243
            if (is_readable(XOOPS_ROOT_PATH . '/class/htmlarea/formhtmlarea.php')) {
244
                require_once XOOPS_ROOT_PATH . '/class/htmlarea/formhtmlarea.php';
245
                $editor = new XoopsFormHtmlarea($caption, $name, $value);
246
            }
247
            break;
248
249
        case 'dhtmltextarea':
250
        case 'dhtml':
251
            $editor = new XoopsFormDhtmlTextArea($caption, $name, $value, 10, 50, $supplemental);
252
            break;
253
254
        case 'textarea':
255
            $editor = new XoopsFormTextArea($caption, $name, $value);
256
            break;
257
258
        case 'tinyeditor':
259
        case 'tinymce':
260
            if (is_readable(XOOPS_ROOT_PATH . '/class/xoopseditor/tinyeditor/formtinyeditortextarea.php')) {
261
                require_once XOOPS_ROOT_PATH . '/class/xoopseditor/tinyeditor/formtinyeditortextarea.php';
262
                $editor = new XoopsFormTinyeditorTextArea([
263
                                                              'caption' => $caption,
264
                                                              'name'    => $name,
265
                                                              'value'   => $value,
266
                                                              'width'   => '100%',
267
                                                              'height'  => '400px'
268
                                                          ]);
269
            }
270
            break;
271
272
        case 'koivi':
273
            if (is_readable(XOOPS_ROOT_PATH . '/class/wysiwyg/formwysiwygtextarea.php')) {
274
                require_once XOOPS_ROOT_PATH . '/class/wysiwyg/formwysiwygtextarea.php';
275
                $editor = new XoopsFormWysiwygTextArea($caption, $name, $value, $width, $height, '');
276
            }
277
            break;
278
    }
279
280
    return $editor;
281
}
282
283
/**
284
 * Internal function
285
 *
286
 * @package       News
287
 * @author        Hervé Thouzard (http://www.herve-thouzard.com)
288
 * @copyright (c) Hervé Thouzard
289
 * @param $text
290
 * @return mixed
291
 */
292
function DublinQuotes($text)
293
{
294
    return str_replace('"', ' ', $text);
295
}
296
297
/**
298
 * Creates all the meta datas :
299
 * - For Mozilla/Netscape and Opera the site navigation's bar
300
 * - The Dublin's Core Metadata
301
 * - The link for Firefox 2 micro summaries
302
 * - The meta keywords
303
 * - The meta description
304
 *
305
 * @package       News
306
 * @author        Hervé Thouzard (http://www.herve-thouzard.com)
307
 * @copyright (c) Hervé Thouzard
308
 * @param null $story
309
 */
310
function news_CreateMetaDatas($story = null)
311
{
312
    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...
313
    $content = '';
314
    $myts    = MyTextSanitizer::getInstance();
315
    require_once XOOPS_ROOT_PATH . '/modules/news/class/class.newstopic.php';
316
317
    /**
318
     * Firefox and Opera Navigation's Bar
319
     */
320 View Code Duplication
    if (news_getmoduleoption('sitenavbar')) {
0 ignored issues
show
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
321
        $content .= sprintf("<link rel=\"Home\" title=\"%s\" href=\"%s/\">\n", $xoopsConfig['sitename'], XOOPS_URL);
322
        $content .= sprintf("<link rel=\"Contents\" href=\"%s\">\n", XOOPS_URL . '/modules/news/index.php');
323
        $content .= sprintf("<link rel=\"Search\" href=\"%s\">\n", XOOPS_URL . '/search.php');
324
        $content .= sprintf("<link rel=\"Glossary\" href=\"%s\">\n", XOOPS_URL . '/modules/news/archive.php');
325
        $content .= sprintf("<link rel=\"%s\" href=\"%s\">\n", $myts->htmlSpecialChars(_NW_SUBMITNEWS), XOOPS_URL . '/modules/news/submit.php');
326
        $content .= sprintf("<link rel=\"alternate\" type=\"application/rss+xml\" title=\"%s\" href=\"%s/\">\n", $xoopsConfig['sitename'], XOOPS_URL . '/backend.php');
327
328
        // Create chapters
329
        require_once XOOPS_ROOT_PATH . '/class/tree.php';
330
        require_once XOOPS_ROOT_PATH . '/modules/news/class/class.newstopic.php';
331
        $xt         = new NewsTopic();
332
        $allTopics  = $xt->getAllTopics(news_getmoduleoption('restrictindex'));
333
        $topic_tree = new XoopsObjectTree($allTopics, 'topic_id', 'topic_pid');
334
        $topics_arr = $topic_tree->getAllChild(0);
335
        foreach ($topics_arr as $onetopic) {
336
            $content .= sprintf("<link rel=\"Chapter\" title=\"%s\" href=\"%s\">\n", $onetopic->topic_title(), XOOPS_URL . '/modules/news/index.php?storytopic=' . $onetopic->topic_id());
337
        }
338
    }
339
340
    /**
341
     * Meta Keywords and Description
342
     * 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
343
     */
344
    $meta_keywords = '';
345 View Code Duplication
    if (isset($story) && is_object($story)) {
0 ignored issues
show
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
346
        if ('' !== xoops_trim($story->keywords())) {
347
            $meta_keywords = $story->keywords();
348
        } else {
349
            $meta_keywords = news_createmeta_keywords($story->hometext() . ' ' . $story->bodytext());
350
        }
351
        if ('' !== xoops_trim($story->description())) {
352
            $meta_description = strip_tags($story->description);
353
        } else {
354
            $meta_description = strip_tags($story->title);
355
        }
356
        if (isset($xoTheme) && is_object($xoTheme)) {
357
            $xoTheme->addMeta('meta', 'keywords', $meta_keywords);
358
            $xoTheme->addMeta('meta', 'description', $meta_description);
359
        } elseif (isset($xoopsTpl) && is_object($xoopsTpl)) { // Compatibility for old Xoops versions
360
            $xoopsTpl->assign('xoops_meta_keywords', $meta_keywords);
361
            $xoopsTpl->assign('xoops_meta_description', $meta_description);
362
        }
363
    }
364
365
    /**
366
     * Dublin Core's meta datas
367
     */
368 View Code Duplication
    if (news_getmoduleoption('dublincore') && isset($story) && is_object($story)) {
0 ignored issues
show
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
369
        $configHandler         = xoops_getHandler('config');
370
        $xoopsConfigMetaFooter = $configHandler->getConfigsByCat(XOOPS_CONF_METAFOOTER);
371
        $content               .= '<meta name="DC.Title" content="' . NewsUtility::getDublinQuotes($story->title()) . "\">\n";
372
        $content               .= '<meta name="DC.Creator" content="' . NewsUtility::getDublinQuotes($story->uname()) . "\">\n";
373
        $content               .= '<meta name="DC.Subject" content="' . NewsUtility::getDublinQuotes($meta_keywords) . "\">\n";
374
        $content               .= '<meta name="DC.Description" content="' . NewsUtility::getDublinQuotes($story->title()) . "\">\n";
375
        $content               .= '<meta name="DC.Publisher" content="' . NewsUtility::getDublinQuotes($xoopsConfig['sitename']) . "\">\n";
376
        $content               .= '<meta name="DC.Date.created" scheme="W3CDTF" content="' . date('Y-m-d', $story->created) . "\">\n";
377
        $content               .= '<meta name="DC.Date.issued" scheme="W3CDTF" content="' . date('Y-m-d', $story->published) . "\">\n";
378
        $content               .= '<meta name="DC.Identifier" content="' . XOOPS_URL . '/modules/news/article.php?storyid=' . $story->storyid() . "\">\n";
379
        $content               .= '<meta name="DC.Source" content="' . XOOPS_URL . "\">\n";
380
        $content               .= '<meta name="DC.Language" content="' . _LANGCODE . "\">\n";
381
        $content               .= '<meta name="DC.Relation.isReferencedBy" content="' . XOOPS_URL . '/modules/news/index.php?storytopic=' . $story->topicid() . "\">\n";
382
        if (isset($xoopsConfigMetaFooter['meta_copyright'])) {
383
            $content .= '<meta name="DC.Rights" content="' . NewsUtility::getDublinQuotes($xoopsConfigMetaFooter['meta_copyright']) . "\">\n";
384
        }
385
    }
386
387
    /**
388
     * Firefox 2 micro summaries
389
     */
390
    if (news_getmoduleoption('firefox_microsummaries')) {
391
        $content .= sprintf("<link rel=\"microsummary\" href=\"%s\">\n", XOOPS_URL . '/modules/news/micro_summary.php');
392
    }
393
394
    if (isset($xoopsTpl) && is_object($xoopsTpl)) {
395
        $xoopsTpl->assign('xoops_module_header', $content);
396
    }
397
}
398
399
/**
400
 * Create the meta keywords based on the content
401
 *
402
 * @package       News
403
 * @author        Hervé Thouzard (http://www.herve-thouzard.com)
404
 * @copyright (c) Hervé Thouzard
405
 * @param $content
406
 * @return string
407
 */
408 View Code Duplication
function news_createmeta_keywords($content)
0 ignored issues
show
This function 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...
409
{
410
    include XOOPS_ROOT_PATH . '/modules/news/config.php';
411
    require_once XOOPS_ROOT_PATH . '/modules/news/class/blacklist.php';
412
    require_once XOOPS_ROOT_PATH . '/modules/news/class/registryfile.php';
413
414
    if (!$cfg['meta_keywords_auto_generate']) {
0 ignored issues
show
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...
415
        return '';
416
    }
417
    $registry = new news_registryfile('news_metagen_options.txt');
418
    //    $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...
419
    $tcontent = $registry->getfile();
420
    if ('' !== xoops_trim($tcontent)) {
421
        list($keywordscount, $keywordsorder) = explode(',', $tcontent);
422
    } else {
423
        $keywordscount = $cfg['meta_keywords_count'];
424
        $keywordsorder = $cfg['meta_keywords_order'];
425
    }
426
427
    $tmp = [];
428
    // Search for the "Minimum keyword length"
429
    if (isset($_SESSION['news_keywords_limit'])) {
430
        $limit = $_SESSION['news_keywords_limit'];
431
    } else {
432
        $configHandler                   = xoops_getHandler('config');
433
        $xoopsConfigSearch               = $configHandler->getConfigsByCat(XOOPS_CONF_SEARCH);
434
        $limit                           = $xoopsConfigSearch['keyword_min'];
435
        $_SESSION['news_keywords_limit'] = $limit;
436
    }
437
    $myts            = MyTextSanitizer::getInstance();
438
    $content         = str_replace('<br>', ' ', $content);
439
    $content         = $myts->undoHtmlSpecialChars($content);
440
    $content         = strip_tags($content);
441
    $content         = strtolower($content);
442
    $search_pattern  = [
443
        '&nbsp;',
444
        "\t",
445
        "\r\n",
446
        "\r",
447
        "\n",
448
        ',',
449
        '.',
450
        "'",
451
        ';',
452
        ':',
453
        ')',
454
        '(',
455
        '"',
456
        '?',
457
        '!',
458
        '{',
459
        '}',
460
        '[',
461
        ']',
462
        '<',
463
        '>',
464
        '/',
465
        '+',
466
        '-',
467
        '_',
468
        '\\',
469
        '*'
470
    ];
471
    $replace_pattern = [
472
        ' ',
473
        ' ',
474
        ' ',
475
        ' ',
476
        ' ',
477
        ' ',
478
        ' ',
479
        ' ',
480
        '',
481
        '',
482
        '',
483
        '',
484
        '',
485
        '',
486
        '',
487
        '',
488
        '',
489
        '',
490
        '',
491
        '',
492
        '',
493
        '',
494
        '',
495
        '',
496
        '',
497
        '',
498
        ''
499
    ];
500
    $content         = str_replace($search_pattern, $replace_pattern, $content);
501
    $keywords        = explode(' ', $content);
502
    switch ($keywordsorder) {
503
        case 0: // Ordre d'apparition dans le texte
504
            $keywords = array_unique($keywords);
505
            break;
506
        case 1: // Ordre de fréquence des mots
507
            $keywords = array_count_values($keywords);
508
            asort($keywords);
509
            $keywords = array_keys($keywords);
510
            break;
511
        case 2: // Ordre inverse de la fréquence des mots
512
            $keywords = array_count_values($keywords);
513
            arsort($keywords);
514
            $keywords = array_keys($keywords);
515
            break;
516
    }
517
    // Remove black listed words
518
    $metablack = new news_blacklist();
519
    $words     = $metablack->getAllKeywords();
0 ignored issues
show
$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...
520
    $keywords  = $metablack->remove_blacklisted($keywords);
521
522
    foreach ($keywords as $keyword) {
523
        if (strlen($keyword) >= $limit && !is_numeric($keyword)) {
524
            $tmp[] = $keyword;
525
        }
526
    }
527
    $tmp = array_slice($tmp, 0, $keywordscount);
528
    if (count($tmp) > 0) {
529
        return implode(',', $tmp);
530
    } else {
531
        if (!isset($configHandler) || !is_object($configHandler)) {
532
            $configHandler = xoops_getHandler('config');
533
        }
534
        $xoopsConfigMetaFooter = $configHandler->getConfigsByCat(XOOPS_CONF_METAFOOTER);
535
        if (isset($xoopsConfigMetaFooter['meta_keywords'])) {
536
            return $xoopsConfigMetaFooter['meta_keywords'];
537
        } else {
538
            return '';
539
        }
540
    }
541
}
542
543
/**
544
 * Remove module's cache
545
 *
546
 * @package       News
547
 * @author        Hervé Thouzard (http://www.herve-thouzard.com)
548
 * @copyright (c) Hervé Thouzard
549
 */
550 View Code Duplication
function news_updateCache()
0 ignored issues
show
This function 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...
551
{
552
    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...
553
    $folder  = $xoopsModule->getVar('dirname');
554
    $tpllist = [];
0 ignored issues
show
$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...
555
    require_once XOOPS_ROOT_PATH . '/class/xoopsblock.php';
556
    require_once XOOPS_ROOT_PATH . '/class/template.php';
557
    $tplfileHandler = xoops_getHandler('tplfile');
558
    $tpllist        = $tplfileHandler->find(null, null, null, $folder);
559
    $xoopsTpl       = new XoopsTpl();
0 ignored issues
show
$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...
560
    xoops_template_clear_module_cache($xoopsModule->getVar('mid')); // Clear module's blocks cache
561
562
    // Remove cache for each page.
563
    foreach ($tpllist as $onetemplate) {
564
        if ('module' === $onetemplate->getVar('tpl_type')) {
565
            // 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
566
            $files_del = [];
0 ignored issues
show
$files_del is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
567
            $files_del = glob(XOOPS_CACHE_PATH . '/*' . $onetemplate->getVar('tpl_file') . '*');
568
            if (count($files_del) > 0) {
569
                foreach ($files_del as $one_file) {
570
                    unlink($one_file);
571
                }
572
            }
573
        }
574
    }
575
}
576
577
/**
578
 * Verify that a mysql table exists
579
 *
580
 * @package       News
581
 * @author        Hervé Thouzard (http://www.herve-thouzard.com)
582
 * @copyright (c) Hervé Thouzard
583
 * @param $tablename
584
 * @return bool
585
 */
586
function news_TableExists($tablename)
587
{
588
    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...
589
    $result = $xoopsDB->queryF("SHOW TABLES LIKE '$tablename'");
590
591
    return ($xoopsDB->getRowsNum($result) > 0);
592
}
593
594
/**
595
 * Verify that a field exists inside a mysql table
596
 *
597
 * @package       News
598
 * @author        Hervé Thouzard (http://www.herve-thouzard.com)
599
 * @copyright (c) Hervé Thouzard
600
 * @param $fieldname
601
 * @param $table
602
 * @return bool
603
 */
604
function news_FieldExists($fieldname, $table)
605
{
606
    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...
607
    $result = $xoopsDB->queryF("SHOW COLUMNS FROM   $table LIKE '$fieldname'");
608
609
    return ($xoopsDB->getRowsNum($result) > 0);
610
}
611
612
/**
613
 * Add a field to a mysql table
614
 *
615
 * @package       News
616
 * @author        Hervé Thouzard (http://www.herve-thouzard.com)
617
 * @copyright (c) Hervé Thouzard
618
 * @param $field
619
 * @param $table
620
 * @return bool|\mysqli_result
621
 */
622
function news_AddField($field, $table)
623
{
624
    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...
625
    $result = $xoopsDB->queryF('ALTER TABLE ' . $table . " ADD $field;");
626
627
    return $result;
628
}
629
630
/**
631
 * Verify that the current user is a member of the Admin group
632
 */
633 View Code Duplication
function news_is_admin_group()
0 ignored issues
show
This function 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...
634
{
635
    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...
636
    if (is_object($xoopsUser)) {
637
        if (in_array('1', $xoopsUser->getGroups())) {
638
            return true;
639
        } else {
640
            if ($xoopsUser->isAdmin($xoopsModule->mid())) {
641
                return true;
642
            } else {
643
                return false;
644
            }
645
        }
646
    } else {
647
        return false;
648
    }
649
}
650
651
/**
652
 * Verify if the current "user" is a bot or not
653
 *
654
 * If you have a problem with this function, insert the folowing code just before the line if (isset($_SESSION['news_cache_bot'])) { :
655
 * return false;
656
 *
657
 * @package       News
658
 * @author        Hervé Thouzard (http://www.herve-thouzard.com)
659
 * @copyright (c) Hervé Thouzard
660
 */
661 View Code Duplication
function news_isbot()
0 ignored issues
show
This function 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...
662
{
663
    if (isset($_SESSION['news_cache_bot'])) {
664
        return $_SESSION['news_cache_bot'];
665
    } else {
666
        // Add here every bot you know separated by a pipe | (not matter with the upper or lower cases)
667
        // If you want to see the result for yourself, add your navigator's user agent at the end (mozilla for example)
668
        $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';
669
        $botlist      = strtoupper($botlist);
670
        $currentagent = strtoupper(xoops_getenv('HTTP_USER_AGENT'));
671
        $retval       = false;
672
        $botarray     = explode('|', $botlist);
673
        foreach ($botarray as $onebot) {
674
            if (false !== strpos($currentagent, $onebot)) {
675
                $retval = true;
676
                break;
677
            }
678
        }
679
    }
680
    $_SESSION['news_cache_bot'] = $retval;
681
682
    return $retval;
683
}
684
685
/**
686
 * Create an infotip
687
 *
688
 * @package       News
689
 * @author        Hervé Thouzard (http://www.herve-thouzard.com)
690
 * @copyright (c) Hervé Thouzard
691
 * @param $text
692
 * @return null
693
 */
694 View Code Duplication
function news_make_infotips($text)
0 ignored issues
show
This function 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...
695
{
696
    $infotips = news_getmoduleoption('infotips');
697
    if ($infotips > 0) {
698
        $myts = MyTextSanitizer::getInstance();
699
700
        return $myts->htmlSpecialChars(xoops_substr(strip_tags($text), 0, $infotips));
701
    }
702
703
    return null;
704
}
705
706
/**
707
 * @author   Monte Ohrt <monte at ohrt dot com>, modified by Amos Robinson
708
 *           <amos dot robinson at gmail dot com>
709
 * @param $string
710
 * @return string
711
 */
712 View Code Duplication
function news_close_tags($string)
0 ignored issues
show
This function 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...
713
{
714
    // match opened tags
715
    if (preg_match_all('/<([a-z\:\-]+)[^\/]>/', $string, $start_tags)) {
716
        $start_tags = $start_tags[1];
717
        // match closed tags
718
        if (preg_match_all('/<\/([a-z]+)>/', $string, $end_tags)) {
719
            $complete_tags = [];
720
            $end_tags      = $end_tags[1];
721
722
            foreach ($start_tags as $key => $val) {
723
                $posb = array_search($val, $end_tags);
724
                if (is_int($posb)) {
725
                    unset($end_tags[$posb]);
726
                } else {
727
                    $complete_tags[] = $val;
728
                }
729
            }
730
        } else {
731
            $complete_tags = $start_tags;
732
        }
733
734
        $complete_tags = array_reverse($complete_tags);
735
        for ($i = 0, $iMax = count($complete_tags); $i < $iMax; ++$i) {
736
            $string .= '</' . $complete_tags[$i] . '>';
737
        }
738
    }
739
740
    return $string;
741
}
742
743
/**
744
 * Smarty truncate_tagsafe modifier plugin
745
 *
746
 * Type:     modifier<br>
747
 * Name:     truncate_tagsafe<br>
748
 * Purpose:  Truncate a string to a certain length if necessary,
749
 *           optionally splitting in the middle of a word, and
750
 *           appending the $etc string or inserting $etc into the middle.
751
 *           Makes sure no tags are left half-open or half-closed
752
 *           (e.g. "Banana in a <a...")
753
 *
754
 * @author   Monte Ohrt <monte at ohrt dot com>, modified by Amos Robinson
755
 *           <amos dot robinson at gmail dot com>
756
 *
757
 * @param string
758
 * @param integer
759
 * @param string
760
 * @param boolean
761
 * @param boolean
762
 *
763
 * @return string
764
 */
765 View Code Duplication
function news_truncate_tagsafe($string, $length = 80, $etc = '...', $break_words = false)
0 ignored issues
show
This function 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...
766
{
767
    if (0 == $length) {
768
        return '';
769
    }
770
    if (strlen($string) > $length) {
771
        $length -= strlen($etc);
772
        if (!$break_words) {
773
            $string = preg_replace('/\s+?(\S+)?$/', '', substr($string, 0, $length + 1));
774
            $string = preg_replace('/<[^>]*$/', '', $string);
775
            $string = news_close_tags($string);
776
        }
777
778
        return $string . $etc;
779
    } else {
780
        return $string;
781
    }
782
}
783
784
/**
785
 * Resize a Picture to some given dimensions (using the wideImage library)
786
 *
787
 * @param string  $src_path      Picture's source
788
 * @param string  $dst_path      Picture's destination
789
 * @param integer $param_width   Maximum picture's width
790
 * @param integer $param_height  Maximum picture's height
791
 * @param boolean $keep_original Do we have to keep the original picture ?
792
 * @param string  $fit           Resize mode (see the wideImage library for more information)
793
 *
794
 * @return bool
795
 */
796 View Code Duplication
function news_resizePicture(
0 ignored issues
show
This function 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...
797
    $src_path,
798
    $dst_path,
799
    $param_width,
800
    $param_height,
801
    $keep_original = false,
802
    $fit = 'inside'
803
) {
804
    //    require_once XOOPS_PATH . '/vendor/wideimage/WideImage.php';
805
    $resize            = true;
806
    $pictureDimensions = getimagesize($src_path);
807
    if (is_array($pictureDimensions)) {
808
        $pictureWidth  = $pictureDimensions[0];
809
        $pictureHeight = $pictureDimensions[1];
810
        if ($pictureWidth < $param_width && $pictureHeight < $param_height) {
811
            $resize = false;
812
        }
813
    }
814
815
    $img = WideImage::load($src_path);
816
    if ($resize) {
817
        $result = $img->resize($param_width, $param_height, $fit);
818
        $result->saveToFile($dst_path);
819
    } else {
820
        @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...
821
    }
822
    if (!$keep_original) {
823
        @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...
824
    }
825
826
    return true;
827
}
828