Completed
Branch master (caa4fc)
by Michael
06:53 queued 04:04
created

functions.php ➔ news_CreateMetaDatas()   F

Complexity

Conditions 18
Paths 312

Size

Total Lines 88
Code Lines 56

Duplication

Lines 5
Ratio 5.68 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 18
eloc 56
c 2
b 0
f 0
nc 312
nop 1
dl 5
loc 88
rs 3.6714

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
// 
3
//  ------------------------------------------------------------------------ //
4
//                XOOPS - PHP Content Management System                      //
5
//                  Copyright (c) 2000-2016 XOOPS.org                        //
6
//                       <http://xoops.org/>                             //
7
//  ------------------------------------------------------------------------ //
8
//  This program is free software; you can redistribute it and/or modify     //
9
//  it under the terms of the GNU General Public License as published by     //
10
//  the Free Software Foundation; either version 2 of the License, or        //
11
//  (at your option) any later version.                                      //
12
//                                                                           //
13
//  You may not change or alter any portion of this comment or credits       //
14
//  of supporting developers from this source code or any supporting         //
15
//  source code which is considered copyrighted (c) material of the          //
16
//  original comment or credit authors.                                      //
17
//                                                                           //
18
//  This program is distributed in the hope that it will be useful,          //
19
//  but WITHOUT ANY WARRANTY; without even the implied warranty of           //
20
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            //
21
//  GNU General Public License for more details.                             //
22
//                                                                           //
23
//  You should have received a copy of the GNU General Public License        //
24
//  along with this program; if not, write to the Free Software              //
25
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA //
26
//  ------------------------------------------------------------------------ //
27
// defined('XOOPS_ROOT_PATH') || exit('XOOPS root path not defined');
28
29
/**
30
 * Returns a module's option
31
 *
32
 * Return's a module's option (for the news module)
33
 *
34
 * @package       News
35
 * @author        Hervé Thouzard (http://www.herve-thouzard.com)
36
 * @copyright (c) Hervé Thouzard
37
 *
38
 * @param string $option module option's name
39
 *
40
 * @param string $repmodule
41
 *
42
 * @return bool
43
 */
44
use WideImage\WideImage;
45
46
/**
47
 * @param             $option
48
 * @param  string     $repmodule
49
 * @return bool|mixed
50
 */
51
function news_getmoduleoption($option, $repmodule = 'news')
52
{
53
    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...
54
    static $tbloptions = array();
55
    if (is_array($tbloptions) && array_key_exists($option, $tbloptions)) {
56
        return $tbloptions[$option];
57
    }
58
59
    $retval = false;
60
    if (isset($xoopsModuleConfig) && (is_object($xoopsModule) && $xoopsModule->getVar('dirname') == $repmodule && $xoopsModule->getVar('isactive'))) {
61
        if (isset($xoopsModuleConfig[$option])) {
62
            $retval = $xoopsModuleConfig[$option];
63
        }
64
    } else {
65
        $moduleHandler  = xoops_getHandler('module');
66
        $module         = $moduleHandler->getByDirname($repmodule);
67
        $config_handler = xoops_getHandler('config');
68
        if ($module) {
69
            $moduleConfig = $config_handler->getConfigsByCat(0, $module->getVar('mid'));
70
            if (isset($moduleConfig[$option])) {
71
                $retval = $moduleConfig[$option];
72
            }
73
        }
74
    }
75
    $tbloptions[$option] = $retval;
76
77
    return $retval;
78
}
79
80
/**
81
 * Updates rating data in item table for a given item
82
 *
83
 * @package       News
84
 * @author        Hervé Thouzard (http://www.herve-thouzard.com)
85
 * @copyright (c) Hervé Thouzard
86
 * @param $storyid
87
 */
88
function news_updaterating($storyid)
89
{
90
    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...
91
    $query       = 'SELECT rating FROM ' . $xoopsDB->prefix('news_stories_votedata') . ' WHERE storyid = ' . $storyid;
92
    $voteresult  = $xoopsDB->query($query);
93
    $votesDB     = $xoopsDB->getRowsNum($voteresult);
94
    $totalrating = 0;
95
    while (list($rating) = $xoopsDB->fetchRow($voteresult)) {
96
        $totalrating += $rating;
97
    }
98
    $finalrating = $totalrating / $votesDB;
99
    $finalrating = number_format($finalrating, 4);
100
    $sql         = sprintf('UPDATE %s SET rating = %u, votes = %u WHERE storyid = %u', $xoopsDB->prefix('news_stories'), $finalrating, $votesDB, $storyid);
101
    $xoopsDB->queryF($sql);
102
}
103
104
/**
105
 * Internal function for permissions
106
 *
107
 * Returns a list of all the permitted topics Ids for the current user
108
 *
109
 * @param string $permtype
110
 *
111
 * @return array $topics    Permitted topics Ids
112
 *
113
 * @package       News
114
 * @author        Hervé Thouzard (http://www.herve-thouzard.com)
115
 * @copyright (c) Hervé Thouzard
116
 */
117
function news_MygetItemIds($permtype = 'news_view')
118
{
119
    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...
120
    static $tblperms = array();
121
    if (is_array($tblperms) && array_key_exists($permtype, $tblperms)) {
122
        return $tblperms[$permtype];
123
    }
124
125
    $moduleHandler       = xoops_getHandler('module');
126
    $newsModule          = $moduleHandler->getByDirname('news');
127
    $groups              = is_object($xoopsUser) ? $xoopsUser->getGroups() : XOOPS_GROUP_ANONYMOUS;
128
    $gperm_handler       = xoops_getHandler('groupperm');
129
    $topics              = $gperm_handler->getItemIds($permtype, $groups, $newsModule->getVar('mid'));
130
    $tblperms[$permtype] = $topics;
131
132
    return $topics;
133
}
134
135
/**
136
 * @param $document
137
 *
138
 * @return mixed
139
 */
140
function news_html2text($document)
141
{
142
    // PHP Manual:: function preg_replace
143
    // $document should contain an HTML document.
144
    // This will remove HTML tags, javascript sections
145
    // and white space. It will also convert some
146
    // common HTML entities to their text equivalent.
147
148
    $search = array(
149
        "'<script[^>]*?>.*?</script>'si", // Strip out javascript
150
        "'<[\/\!]*?[^<>]*?>'si", // Strip out HTML tags
151
        "'([\r\n])[\s]+'", // Strip out white space
152
        "'&(quot|#34);'i", // Replace HTML entities
153
        "'&(amp|#38);'i",
154
        "'&(lt|#60);'i",
155
        "'&(gt|#62);'i",
156
        "'&(nbsp|#160);'i",
157
        "'&(iexcl|#161);'i",
158
        "'&(cent|#162);'i",
159
        "'&(pound|#163);'i",
160
        "'&(copy|#169);'i",
161
        "'&#(\d+);'e"
162
    ); // evaluate as php
163
164
    $replace = array(
165
        '',
166
        '',
167
        "\\1",
168
        "\"",
169
        '&',
170
        '<',
171
        '>',
172
        ' ',
173
        chr(161),
174
        chr(162),
175
        chr(163),
176
        chr(169),
177
        "chr(\\1)"
178
    );
179
180
    $text = preg_replace($search, $replace, $document);
181
182
    return $text;
183
}
184
185
/**
186
 * Is Xoops 2.3.x ?
187
 *
188
 * @return boolean need to say it ?
189
 */
190
function news_isX23()
191
{
192
    $x23 = false;
193
    $xv  = str_replace('XOOPS ', '', XOOPS_VERSION);
194
    if (substr($xv, 2, 1) >= '3') {
195
        $x23 = true;
196
    }
197
198
    return $x23;
199
}
200
201
/**
202
 * Retreive an editor according to the module's option "form_options"
203
 *
204
 * @package       News
205
 * @author        Hervé Thouzard (http://www.herve-thouzard.com)
206
 * @copyright (c) Hervé Thouzard
207
 * @param                                                                                                                                 $caption
208
 * @param                                                                                                                                 $name
209
 * @param  string                                                                                                                         $value
210
 * @param  string                                                                                                                         $width
211
 * @param  string                                                                                                                         $height
212
 * @param  string                                                                                                                         $supplemental
213
 * @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...
214
 */
215
function news_getWysiwygForm($caption, $name, $value = '', $width = '100%', $height = '400px', $supplemental = '')
216
{
217
    $editor_option            = strtolower(news_getmoduleoption('form_options'));
218
    $editor                   = false;
219
    $editor_configs           = array();
220
    $editor_configs['name']   = $name;
221
    $editor_configs['value']  = $value;
222
    $editor_configs['rows']   = 35;
223
    $editor_configs['cols']   = 60;
224
    $editor_configs['width']  = '100%';
225
    $editor_configs['height'] = '350px';
226
    $editor_configs['editor'] = $editor_option;
227
228
    if (news_isX23()) {
229
        $editor = new XoopsFormEditor($caption, $name, $editor_configs);
230
231
        return $editor;
232
    }
233
234
    // Only for Xoops 2.0.x
235
    switch ($editor_option) {
236 View Code Duplication
        case 'fckeditor':
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...
237
            if (is_readable(XOOPS_ROOT_PATH . '/class/fckeditor/formfckeditor.php')) {
238
                require_once(XOOPS_ROOT_PATH . '/class/fckeditor/formfckeditor.php');
239
                $editor = new XoopsFormFckeditor($caption, $name, $value);
240
            }
241
            break;
242
243 View Code Duplication
        case 'htmlarea':
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...
244
            if (is_readable(XOOPS_ROOT_PATH . '/class/htmlarea/formhtmlarea.php')) {
245
                require_once(XOOPS_ROOT_PATH . '/class/htmlarea/formhtmlarea.php');
246
                $editor = new XoopsFormHtmlarea($caption, $name, $value);
247
            }
248
            break;
249
250
        case 'dhtmltextarea':
251
        case 'dhtml':
252
            $editor = new XoopsFormDhtmlTextArea($caption, $name, $value, 10, 50, $supplemental);
253
            break;
254
255
        case 'textarea':
256
            $editor = new XoopsFormTextArea($caption, $name, $value);
257
            break;
258
259
        case 'tinyeditor':
260
        case 'tinymce':
261
            if (is_readable(XOOPS_ROOT_PATH . '/class/xoopseditor/tinyeditor/formtinyeditortextarea.php')) {
262
                require_once XOOPS_ROOT_PATH . '/class/xoopseditor/tinyeditor/formtinyeditortextarea.php';
263
                $editor = new XoopsFormTinyeditorTextArea(array('caption' => $caption, 'name' => $name, 'value' => $value, 'width' => '100%', 'height' => '400px'));
264
            }
265
            break;
266
267 View Code Duplication
        case 'koivi':
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...
268
            if (is_readable(XOOPS_ROOT_PATH . '/class/wysiwyg/formwysiwygtextarea.php')) {
269
                require_once(XOOPS_ROOT_PATH . '/class/wysiwyg/formwysiwygtextarea.php');
270
                $editor = new XoopsFormWysiwygTextArea($caption, $name, $value, $width, $height, '');
271
            }
272
            break;
273
    }
274
275
    return $editor;
276
}
277
278
/**
279
 * Internal function
280
 *
281
 * @package       News
282
 * @author        Hervé Thouzard (http://www.herve-thouzard.com)
283
 * @copyright (c) Hervé Thouzard
284
 * @param $text
285
 * @return mixed
286
 */
287
function DublinQuotes($text)
288
{
289
    return str_replace("\"", ' ', $text);
290
}
291
292
/**
293
 * Creates all the meta datas :
294
 * - For Mozilla/Netscape and Opera the site navigation's bar
295
 * - The Dublin's Core Metadata
296
 * - The link for Firefox 2 micro summaries
297
 * - The meta keywords
298
 * - The meta description
299
 *
300
 * @package       News
301
 * @author        Hervé Thouzard (http://www.herve-thouzard.com)
302
 * @copyright (c) Hervé Thouzard
303
 * @param null $story
304
 */
305
function news_CreateMetaDatas($story = null)
306
{
307
    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...
308
    $content = '';
309
    $myts    = MyTextSanitizer::getInstance();
310
    include_once XOOPS_ROOT_PATH . '/modules/news/class/class.newstopic.php';
311
312
    /**
313
     * Firefox and Opera Navigation's Bar
314
     */
315
    if (news_getmoduleoption('sitenavbar')) {
316
        $content .= sprintf("<link rel=\"Home\" title=\"%s\" href=\"%s/\" />\n", $xoopsConfig['sitename'], XOOPS_URL);
317
        $content .= sprintf("<link rel=\"Contents\" href=\"%s\" />\n", XOOPS_URL . '/modules/news/index.php');
318
        $content .= sprintf("<link rel=\"Search\" href=\"%s\" />\n", XOOPS_URL . '/search.php');
319
        $content .= sprintf("<link rel=\"Glossary\" href=\"%s\" />\n", XOOPS_URL . '/modules/news/archive.php');
320
        $content .= sprintf("<link rel=\"%s\" href=\"%s\" />\n", $myts->htmlSpecialChars(_NW_SUBMITNEWS), XOOPS_URL . '/modules/news/submit.php');
321
        $content .= sprintf("<link rel=\"alternate\" type=\"application/rss+xml\" title=\"%s\" href=\"%s/\" />\n", $xoopsConfig['sitename'], XOOPS_URL . '/backend.php');
322
323
        // Create chapters
324
        include_once XOOPS_ROOT_PATH . '/class/tree.php';
325
        include_once XOOPS_ROOT_PATH . '/modules/news/class/class.newstopic.php';
326
        $xt         = new NewsTopic();
327
        $allTopics  = $xt->getAllTopics(news_getmoduleoption('restrictindex'));
328
        $topic_tree = new XoopsObjectTree($allTopics, 'topic_id', 'topic_pid');
329
        $topics_arr = $topic_tree->getAllChild(0);
330
        foreach ($topics_arr as $onetopic) {
331
            $content .= sprintf("<link rel=\"Chapter\" title=\"%s\" href=\"%s\" />\n", $onetopic->topic_title(), XOOPS_URL . '/modules/news/index.php?storytopic=' . $onetopic->topic_id());
332
        }
333
    }
334
335
    /**
336
     * Meta Keywords and Description
337
     * 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
338
     */
339
    $meta_keywords = '';
340
    if (isset($story) && is_object($story)) {
341 View Code Duplication
        if (xoops_trim($story->keywords()) !== '') {
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...
342
            $meta_keywords = $story->keywords();
343
        } else {
344
            $meta_keywords = news_createmeta_keywords($story->hometext() . ' ' . $story->bodytext());
345
        }
346
        if (xoops_trim($story->description()) !== '') {
347
            $meta_description = strip_tags($story->description);
348
        } else {
349
            $meta_description = strip_tags($story->title);
350
        }
351
        if (isset($xoTheme) && is_object($xoTheme)) {
352
            $xoTheme->addMeta('meta', 'keywords', $meta_keywords);
353
            $xoTheme->addMeta('meta', 'description', $meta_description);
354
        } elseif (isset($xoopsTpl) && is_object($xoopsTpl)) { // Compatibility for old Xoops versions
355
            $xoopsTpl->assign('xoops_meta_keywords', $meta_keywords);
356
            $xoopsTpl->assign('xoops_meta_description', $meta_description);
357
        }
358
    }
359
360
    /**
361
     * Dublin Core's meta datas
362
     */
363
    if (news_getmoduleoption('dublincore') && isset($story) && is_object($story)) {
364
        $config_handler        = xoops_getHandler('config');
365
        $xoopsConfigMetaFooter = $config_handler->getConfigsByCat(XOOPS_CONF_METAFOOTER);
366
        $content .= '<meta name="DC.Title" content="' . DublinQuotes($story->title()) . "\" />\n";
367
        $content .= '<meta name="DC.Creator" content="' . DublinQuotes($story->uname()) . "\" />\n";
368
        $content .= '<meta name="DC.Subject" content="' . DublinQuotes($meta_keywords) . "\" />\n";
369
        $content .= '<meta name="DC.Description" content="' . DublinQuotes($story->title()) . "\" />\n";
370
        $content .= '<meta name="DC.Publisher" content="' . DublinQuotes($xoopsConfig['sitename']) . "\" />\n";
371
        $content .= '<meta name="DC.Date.created" scheme="W3CDTF" content="' . date('Y-m-d', $story->created) . "\" />\n";
372
        $content .= '<meta name="DC.Date.issued" scheme="W3CDTF" content="' . date('Y-m-d', $story->published) . "\" />\n";
373
        $content .= '<meta name="DC.Identifier" content="' . XOOPS_URL . '/modules/news/article.php?storyid=' . $story->storyid() . "\" />\n";
374
        $content .= '<meta name="DC.Source" content="' . XOOPS_URL . "\" />\n";
375
        $content .= '<meta name="DC.Language" content="' . _LANGCODE . "\" />\n";
376
        $content .= '<meta name="DC.Relation.isReferencedBy" content="' . XOOPS_URL . '/modules/news/index.php?storytopic=' . $story->topicid() . "\" />\n";
377
        if (isset($xoopsConfigMetaFooter['meta_copyright'])) {
378
            $content .= '<meta name="DC.Rights" content="' . DublinQuotes($xoopsConfigMetaFooter['meta_copyright']) . "\" />\n";
379
        }
380
    }
381
382
    /**
383
     * Firefox 2 micro summaries
384
     */
385
    if (news_getmoduleoption('firefox_microsummaries')) {
386
        $content .= sprintf("<link rel=\"microsummary\" href=\"%s\" />\n", XOOPS_URL . '/modules/news/micro_summary.php');
387
    }
388
389
    if (isset($xoopsTpl) && is_object($xoopsTpl)) {
390
        $xoopsTpl->assign('xoops_module_header', $content);
391
    }
392
}
393
394
/**
395
 * Create the meta keywords based on the content
396
 *
397
 * @package       News
398
 * @author        Hervé Thouzard (http://www.herve-thouzard.com)
399
 * @copyright (c) Hervé Thouzard
400
 * @param $content
401
 * @return string
402
 */
403
function news_createmeta_keywords($content)
0 ignored issues
show
Coding Style introduced by
news_createmeta_keywords 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...
404
{
405
    include XOOPS_ROOT_PATH . '/modules/news/config.php';
406
    include_once XOOPS_ROOT_PATH . '/modules/news/class/blacklist.php';
407
    include_once XOOPS_ROOT_PATH . '/modules/news/class/registryfile.php';
408
409
    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...
410
        return '';
411
    }
412
    $registry = new news_registryfile('news_metagen_options.txt');
413
    //    $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...
414
    $tcontent = $registry->getfile();
415 View Code Duplication
    if (xoops_trim($tcontent) !== '') {
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...
416
        list($keywordscount, $keywordsorder) = explode(',', $tcontent);
417
    } else {
418
        $keywordscount = $cfg['meta_keywords_count'];
419
        $keywordsorder = $cfg['meta_keywords_order'];
420
    }
421
422
    $tmp = array();
423
    // Search for the "Minimum keyword length"
424
    if (isset($_SESSION['news_keywords_limit'])) {
425
        $limit = $_SESSION['news_keywords_limit'];
426
    } else {
427
        $config_handler                  = xoops_getHandler('config');
428
        $xoopsConfigSearch               = $config_handler->getConfigsByCat(XOOPS_CONF_SEARCH);
429
        $limit                           = $xoopsConfigSearch['keyword_min'];
430
        $_SESSION['news_keywords_limit'] = $limit;
431
    }
432
    $myts            = MyTextSanitizer::getInstance();
433
    $content         = str_replace('<br>', ' ', $content);
434
    $content         = $myts->undoHtmlSpecialChars($content);
435
    $content         = strip_tags($content);
436
    $content         = strtolower($content);
437
    $search_pattern  = array('&nbsp;', "\t", "\r\n", "\r", "\n", ',', '.', "'", ';', ':', ')', '(', '"', '?', '!', '{', '}', '[', ']', '<', '>', '/', '+', '-', '_', '\\', '*');
438
    $replace_pattern = array(' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '');
439
    $content         = str_replace($search_pattern, $replace_pattern, $content);
440
    $keywords        = explode(' ', $content);
441
    switch ($keywordsorder) {
442
        case 0: // Ordre d'apparition dans le texte
443
            $keywords = array_unique($keywords);
444
            break;
445
        case 1: // Ordre de fréquence des mots
446
            $keywords = array_count_values($keywords);
447
            asort($keywords);
448
            $keywords = array_keys($keywords);
449
            break;
450
        case 2: // Ordre inverse de la fréquence des mots
451
            $keywords = array_count_values($keywords);
452
            arsort($keywords);
453
            $keywords = array_keys($keywords);
454
            break;
455
    }
456
    // Remove black listed words
457
    $metablack = new news_blacklist();
458
    $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...
459
    $keywords  = $metablack->remove_blacklisted($keywords);
460
461
    foreach ($keywords as $keyword) {
462
        if (strlen($keyword) >= $limit && !is_numeric($keyword)) {
463
            $tmp[] = $keyword;
464
        }
465
    }
466
    $tmp = array_slice($tmp, 0, $keywordscount);
467
    if (count($tmp) > 0) {
468
        return implode(',', $tmp);
469
    } else {
470
        if (!isset($config_handler) || !is_object($config_handler)) {
471
            $config_handler = xoops_getHandler('config');
472
        }
473
        $xoopsConfigMetaFooter = $config_handler->getConfigsByCat(XOOPS_CONF_METAFOOTER);
474
        if (isset($xoopsConfigMetaFooter['meta_keywords'])) {
475
            return $xoopsConfigMetaFooter['meta_keywords'];
476
        } else {
477
            return '';
478
        }
479
    }
480
}
481
482
/**
483
 * Remove module's cache
484
 *
485
 * @package       News
486
 * @author        Hervé Thouzard (http://www.herve-thouzard.com)
487
 * @copyright (c) Hervé Thouzard
488
 */
489
function news_updateCache()
490
{
491
    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...
492
    $folder  = $xoopsModule->getVar('dirname');
493
    $tpllist = array();
0 ignored issues
show
Unused Code introduced by
$tpllist is not used, you could remove the assignment.

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

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

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

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

Loading history...
494
    include_once XOOPS_ROOT_PATH . '/class/xoopsblock.php';
495
    include_once XOOPS_ROOT_PATH . '/class/template.php';
496
    $tplfile_handler = xoops_getHandler('tplfile');
497
    $tpllist         = $tplfile_handler->find(null, null, null, $folder);
498
    $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...
499
    xoops_template_clear_module_cache($xoopsModule->getVar('mid')); // Clear module's blocks cache
500
501
    // Remove cache for each page.
502
    foreach ($tpllist as $onetemplate) {
503
        if ($onetemplate->getVar('tpl_type') === 'module') {
504
            // 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
505
            $files_del = array();
0 ignored issues
show
Unused Code introduced by
$files_del is not used, you could remove the assignment.

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

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

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

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

Loading history...
506
            $files_del = glob(XOOPS_CACHE_PATH . '/*' . $onetemplate->getVar('tpl_file') . '*');
507
            if (count($files_del) > 0) {
508
                foreach ($files_del as $one_file) {
509
                    unlink($one_file);
510
                }
511
            }
512
        }
513
    }
514
}
515
516
/**
517
 * Verify that a mysql table exists
518
 *
519
 * @package       News
520
 * @author        Hervé Thouzard (http://www.herve-thouzard.com)
521
 * @copyright (c) Hervé Thouzard
522
 * @param $tablename
523
 * @return bool
524
 */
525
function news_TableExists($tablename)
526
{
527
    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...
528
    $result = $xoopsDB->queryF("SHOW TABLES LIKE '$tablename'");
529
530
    return ($xoopsDB->getRowsNum($result) > 0);
531
}
532
533
/**
534
 * Verify that a field exists inside a mysql table
535
 *
536
 * @package       News
537
 * @author        Hervé Thouzard (http://www.herve-thouzard.com)
538
 * @copyright (c) Hervé Thouzard
539
 * @param $fieldname
540
 * @param $table
541
 * @return bool
542
 */
543
function news_FieldExists($fieldname, $table)
544
{
545
    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...
546
    $result = $xoopsDB->queryF("SHOW COLUMNS FROM   $table LIKE '$fieldname'");
547
548
    return ($xoopsDB->getRowsNum($result) > 0);
549
}
550
551
/**
552
 * Add a field to a mysql table
553
 *
554
 * @package       News
555
 * @author        Hervé Thouzard (http://www.herve-thouzard.com)
556
 * @copyright (c) Hervé Thouzard
557
 * @param $field
558
 * @param $table
559
 * @return
560
 */
561
function news_AddField($field, $table)
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...
562
{
563
    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...
564
    $result = $xoopsDB->queryF('ALTER TABLE ' . $table . " ADD $field;");
565
566
    return $result;
567
}
568
569
/**
570
 * Verify that the current user is a member of the Admin group
571
 */
572
function news_is_admin_group()
573
{
574
    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...
575
    if (is_object($xoopsUser)) {
576
        if (in_array('1', $xoopsUser->getGroups())) {
577
            return true;
578
        } else {
579
            if ($xoopsUser->isAdmin($xoopsModule->mid())) {
580
                return true;
581
            } else {
582
                return false;
583
            }
584
        }
585
    } else {
586
        return false;
587
    }
588
}
589
590
/**
591
 * Verify if the current "user" is a bot or not
592
 *
593
 * If you have a problem with this function, insert the folowing code just before the line if (isset($_SESSION['news_cache_bot'])) { :
594
 * return false;
595
 *
596
 * @package       News
597
 * @author        Hervé Thouzard (http://www.herve-thouzard.com)
598
 * @copyright (c) Hervé Thouzard
599
 */
600
function news_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...
Coding Style introduced by
news_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...
601
{
602
    if (isset($_SESSION['news_cache_bot'])) {
603
        return $_SESSION['news_cache_bot'];
604
    } else {
605
        // Add here every bot you know separated by a pipe | (not matter with the upper or lower cases)
606
        // If you want to see the result for yourself, add your navigator's user agent at the end (mozilla for example)
607
        $botlist      =
608
            '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';
609
        $botlist      = strtoupper($botlist);
610
        $currentagent = strtoupper(xoops_getenv('HTTP_USER_AGENT'));
611
        $retval       = false;
612
        $botarray     = explode('|', $botlist);
613
        foreach ($botarray as $onebot) {
614
            if (false !== strpos($currentagent, $onebot)) {
615
                $retval = true;
616
                break;
617
            }
618
        }
619
    }
620
    $_SESSION['news_cache_bot'] = $retval;
621
622
    return $retval;
623
}
624
625
/**
626
 * Create an infotip
627
 *
628
 * @package       News
629
 * @author        Hervé Thouzard (http://www.herve-thouzard.com)
630
 * @copyright (c) Hervé Thouzard
631
 * @param $text
632
 * @return null
633
 */
634
function news_make_infotips($text)
635
{
636
    $infotips = news_getmoduleoption('infotips');
637
    if ($infotips > 0) {
638
        $myts = MyTextSanitizer::getInstance();
639
640
        return $myts->htmlSpecialChars(xoops_substr(strip_tags($text), 0, $infotips));
641
    }
642
643
    return null;
644
}
645
646
/**
647
 * @author   Monte Ohrt <monte at ohrt dot com>, modified by Amos Robinson
648
 *           <amos dot robinson at gmail dot com>
649
 * @param $string
650
 * @return string
651
 */
652
function news_close_tags($string)
653
{
654
    // match opened tags
655
    if (preg_match_all('/<([a-z\:\-]+)[^\/]>/', $string, $start_tags)) {
656
        $start_tags = $start_tags[1];
657
        // match closed tags
658
        if (preg_match_all('/<\/([a-z]+)>/', $string, $end_tags)) {
659
            $complete_tags = array();
660
            $end_tags      = $end_tags[1];
661
662
            foreach ($start_tags as $key => $val) {
663
                $posb = array_search($val, $end_tags);
664
                if (is_int($posb)) {
665
                    unset($end_tags[$posb]);
666
                } else {
667
                    $complete_tags[] = $val;
668
                }
669
            }
670
        } else {
671
            $complete_tags = $start_tags;
672
        }
673
674
        $complete_tags = array_reverse($complete_tags);
675
        for ($i = 0, $iMax = count($complete_tags); $i < $iMax; ++$i) {
676
            $string .= '</' . $complete_tags[$i] . '>';
677
        }
678
    }
679
680
    return $string;
681
}
682
683
/**
684
 * Smarty truncate_tagsafe modifier plugin
685
 *
686
 * Type:     modifier<br>
687
 * Name:     truncate_tagsafe<br>
688
 * Purpose:  Truncate a string to a certain length if necessary,
689
 *           optionally splitting in the middle of a word, and
690
 *           appending the $etc string or inserting $etc into the middle.
691
 *           Makes sure no tags are left half-open or half-closed
692
 *           (e.g. "Banana in a <a...")
693
 *
694
 * @author   Monte Ohrt <monte at ohrt dot com>, modified by Amos Robinson
695
 *           <amos dot robinson at gmail dot com>
696
 *
697
 * @param string
698
 * @param integer
699
 * @param string
700
 * @param boolean
701
 * @param boolean
702
 *
703
 * @return string
704
 */
705
function news_truncate_tagsafe($string, $length = 80, $etc = '...', $break_words = false)
706
{
707
    if ($length == 0) {
708
        return '';
709
    }
710
    if (strlen($string) > $length) {
711
        $length -= strlen($etc);
712
        if (!$break_words) {
713
            $string = preg_replace('/\s+?(\S+)?$/', '', substr($string, 0, $length + 1));
714
            $string = preg_replace('/<[^>]*$/', '', $string);
715
            $string = news_close_tags($string);
716
        }
717
718
        return $string . $etc;
719
    } else {
720
        return $string;
721
    }
722
}
723
724
/**
725
 * Resize a Picture to some given dimensions (using the wideImage library)
726
 *
727
 * @param string  $src_path      Picture's source
728
 * @param string  $dst_path      Picture's destination
729
 * @param integer $param_width   Maximum picture's width
730
 * @param integer $param_height  Maximum picture's height
731
 * @param boolean $keep_original Do we have to keep the original picture ?
732
 * @param string  $fit           Resize mode (see the wideImage library for more information)
733
 *
734
 * @return bool
735
 */
736
function news_resizePicture($src_path, $dst_path, $param_width, $param_height, $keep_original = false, $fit = 'inside')
737
{
738
    //    require_once XOOPS_PATH . '/vendor/wideimage/WideImage.php';
739
    $resize            = true;
740
    $pictureDimensions = getimagesize($src_path);
741
    if (is_array($pictureDimensions)) {
742
        $pictureWidth  = $pictureDimensions[0];
743
        $pictureHeight = $pictureDimensions[1];
744
        if ($pictureWidth < $param_width && $pictureHeight < $param_height) {
745
            $resize = false;
746
        }
747
    }
748
749
    $img = WideImage::load($src_path);
750
    if ($resize) {
751
        $result = $img->resize($param_width, $param_height, $fit);
752
        $result->saveToFile($dst_path);
753
    } else {
754
        @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...
755
    }
756
    if (!$keep_original) {
757
        @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...
758
    }
759
760
    return true;
761
}
762