Completed
Push — master ( c1777d...d193e2 )
by Michael
13:22
created

LexikonUtility::getModuleOption()   D

Complexity

Conditions 10
Paths 6

Size

Total Lines 32
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
eloc 21
nc 6
nop 2
dl 0
loc 32
rs 4.8196
c 0
b 0
f 0

How to fix   Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
3
/*
4
 * You may not change or alter any portion of this comment or credits
5
 * of supporting developers from this source code or any supporting source code
6
 * which is considered copyrighted (c) material of the original comment or credit authors.
7
 *
8
 * This program is distributed in the hope that it will be useful,
9
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
11
 */
12
13
/**
14
 * @copyright    XOOPS Project (http://xoops.org)
15
 * @license      GNU GPL 2 or later (http://www.gnu.org/licenses/gpl-2.0.html)
16
 * @package
17
 * @since
18
 * @author       XOOPS Development Team, hsalazar
19
 */
20
21
use Xmf\Request;
22
use Xmf\Module\Helper;
23
24
/**
25
 * Class LexikonUtility
26
 */
27
class LexikonUtility
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

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

namespace YourVendor;

class YourClass { }

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

Loading history...
28
{
29
30
    /**
31
     * Function responsible for checking if a directory exists, we can also write in and create an index.html file
32
     *
33
     * @param string $folder The full path of the directory to check
34
     *
35
     * @return void
36
     */
37
    public static function createFolder($folder)
38
    {
39
        try {
40
            if (!file_exists($folder)) {
41
                if (!mkdir($folder) && !is_dir($folder)) {
42
                    throw new \RuntimeException(sprintf('Unable to create the %s directory', $folder));
43
                } else {
44
                    file_put_contents($folder . '/index.html', '<script>history.go(-1);</script>');
45
                }
46
            }
47
        } catch (Exception $e) {
48
            echo 'Caught exception: ', $e->getMessage(), "\n", '<br/>';
49
        }
50
    }
51
52
    /**
53
     * @param $file
54
     * @param $folder
55
     * @return bool
56
     */
57
    public static function copyFile($file, $folder)
58
    {
59
        return copy($file, $folder);
60
        //        try {
61
        //            if (!is_dir($folder)) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
62
        //                throw new \RuntimeException(sprintf('Unable to copy file as: %s ', $folder));
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
63
        //            } else {
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
64
        //                return copy($file, $folder);
0 ignored issues
show
Unused Code Comprehensibility introduced by
64% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
65
        //            }
66
        //        } catch (Exception $e) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
67
        //            echo 'Caught exception: ', $e->getMessage(), "\n", "<br/>";
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
68
        //        }
69
        //        return false;
70
    }
71
72
    /**
73
     * @param $src
74
     * @param $dst
75
     */
76
    public static function recurseCopy($src, $dst)
77
    {
78
        $dir = opendir($src);
79
        //    @mkdir($dst);
80
        while (false !== ($file = readdir($dir))) {
81
            if (($file !== '.') && ($file !== '..')) {
82
                if (is_dir($src . '/' . $file)) {
83
                    self::recurseCopy($src . '/' . $file, $dst . '/' . $file);
84
                } else {
85
                    copy($src . '/' . $file, $dst . '/' . $file);
86
                }
87
            }
88
        }
89
        closedir($dir);
90
    }
91
92
    /**
93
     *
94
     * Verifies XOOPS version meets minimum requirements for this module
95
     * @static
96
     * @param XoopsModule $module
97
     *
98
     * @return bool true if meets requirements, false if not
99
     */
100
    public static function checkXoopsVer(XoopsModule $module)
101
    {
102
        xoops_loadLanguage('admin', $module->dirname());
103
        //check for minimum XOOPS version
104
        $currentVer  = substr(XOOPS_VERSION, 6); // get the numeric part of string
105
        $currArray   = explode('.', $currentVer);
106
        $requiredVer = '' . $module->getInfo('min_xoops'); //making sure it's a string
107
        $reqArray    = explode('.', $requiredVer);
108
        $success     = true;
109
        foreach ($reqArray as $k => $v) {
110
            if (isset($currArray[$k])) {
111
                if ($currArray[$k] > $v) {
112
                    break;
113
                } elseif ($currArray[$k] == $v) {
114
                    continue;
115
                } else {
116
                    $success = false;
117
                    break;
118
                }
119
            } else {
120
                if ((int)$v > 0) { // handles things like x.x.x.0_RC2
121
                    $success = false;
122
                    break;
123
                }
124
            }
125
        }
126
127
        if (!$success) {
128
            $module->setErrors(sprintf(_AM_ADSLIGHT_ERROR_BAD_XOOPS, $requiredVer, $currentVer));
129
        }
130
131
        return $success;
132
    }
133
134
    /**
135
     *
136
     * Verifies PHP version meets minimum requirements for this module
137
     * @static
138
     * @param XoopsModule $module
139
     *
140
     * @return bool true if meets requirements, false if not
141
     */
142
    public static function checkPhpVer(XoopsModule $module)
143
    {
144
        xoops_loadLanguage('admin', $module->dirname());
145
        // check for minimum PHP version
146
        $success = true;
147
        $verNum  = phpversion();
148
        $reqVer  =& $module->getInfo('min_php');
149
        if (false !== $reqVer && '' !== $reqVer) {
150
            if (version_compare($verNum, $reqVer, '<')) {
151
                $module->setErrors(sprintf(_AM_ADSLIGHT_ERROR_BAD_PHP, $reqVer, $verNum));
152
                $success = false;
153
            }
154
        }
155
156
        return $success;
157
    }
158
159
    /**
160
     * LexikonUtility::getLinkedUnameFromId()
161
     *
162
     * @param  integer $userid Userid of author etc
163
     * @param  integer $name   :  0 Use Usenamer 1 Use realname
164
     * @return string
165
     */
166
public static function getLinkedUnameFromId($userid = 0, $name = 0)
0 ignored issues
show
Coding Style introduced by
getLinkedUnameFromId uses the super-global variable $GLOBALS which is generally not recommended.

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

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

// Better
class Router
{
    private $host;

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

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

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

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
167
{
168
    if (!is_numeric($userid)) {
169
        return $userid;
170
    }
171
172
    $userid = (int)$userid;
173
    if ($userid > 0) {
174
        $memberHandler = xoops_getHandler('member');
175
        $user          = $memberHandler->getUser($userid);
176
177
        if (is_object($user)) {
178
            $ts        = MyTextSanitizer::getInstance();
179
            $username  = $user->getVar('uname');
180
            $usernameu = $user->getVar('name');
181
182
            if ($name && !empty($usernameu)) {
183
                $username = $user->getVar('name');
184
            }
185
            if (!empty($usernameu)) {
186
                $linkeduser = "$usernameu [<a href='" . XOOPS_URL . '/userinfo.php?uid=' . $userid . "'>" . $ts->htmlSpecialChars($username) . '</a>]';
187
            } else {
188
                $linkeduser = "<a href='" . XOOPS_URL . '/userinfo.php?uid=' . $userid . "'>" . ucfirst($ts->htmlSpecialChars($username)) . '</a>';
189
            }
190
191
            return $linkeduser;
192
        }
193
    }
194
195
    return $GLOBALS['xoopsConfig']['anonymous'];
196
}
197
198
    /**
199
     * @param $user
200
     */
201
public static function getUserForm($user)
202
{
203
    global $xoopsDB, $xoopsConfig;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

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

1. Pass all data via parameters

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

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

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

    public function myFunction() {
        // Do something
    }
}
Loading history...
204
205
    echo "<select name='author'>";
206
    echo "<option value='-1'>------</option>";
207
    $result = $xoopsDB->query('SELECT uid, uname FROM ' . $xoopsDB->prefix('users') . ' ORDER BY uname');
208
209
    while (list($uid, $uname) = $xoopsDB->fetchRow($result)) {
210
        if ($uid == $user) {
211
            $opt_selected = 'selected';
212
        } else {
213
            $opt_selected = '';
214
        }
215
        echo "<option value='" . $uid . "' $opt_selected>" . $uname . '</option>';
216
    }
217
    echo '</select></div>';
218
}
219
220
    public static function calculateTotals()
221
    {
222
        global $xoopsUser, $xoopsDB, $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...
223
        $groups       = is_object($xoopsUser) ? $xoopsUser->getGroups() : XOOPS_GROUP_ANONYMOUS;
224
        $gpermHandler = xoops_getHandler('groupperm');
225
226
        $result01 = $xoopsDB->query('SELECT categoryID, total FROM ' . $xoopsDB->prefix('lxcategories') . ' ');
227
        list($totalcategories) = $xoopsDB->getRowsNum($result01);
0 ignored issues
show
Unused Code introduced by
The assignment to $totalcategories is unused. Consider omitting it like so list($first,,$third).

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

Consider the following code example.

<?php

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

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

print $a . " - " . $c;

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

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
228
        while (list($categoryID, $total) = $xoopsDB->fetchRow($result01)) {
0 ignored issues
show
Unused Code introduced by
The assignment to $total is unused. Consider omitting it like so list($first,,$third).

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

Consider the following code example.

<?php

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

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

print $a . " - " . $c;

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

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
229
            if ($gpermHandler->checkRight('lexikon_view', $categoryID, $groups, $xoopsModule->getVar('mid'))) {
230
                $newcount = LexikonUtility::countByCategory($categoryID);
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

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

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

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

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

Loading history...
231
                $xoopsDB->queryF('UPDATE ' . $xoopsDB->prefix('lxcategories') . " SET total = '$newcount' WHERE categoryID = '$categoryID'");
232
            }
233
        }
234
    }
235
236
    /**
237
     * @param $c
238
     * @return int
239
     */
240
public static function countByCategory($c)
241
{
242
    global $xoopsUser, $xoopsDB, $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...
243
    $groups       = is_object($xoopsUser) ? $xoopsUser->getGroups() : XOOPS_GROUP_ANONYMOUS;
0 ignored issues
show
Unused Code introduced by
$groups 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...
244
    $gpermHandler = xoops_getHandler('groupperm');
0 ignored issues
show
Unused Code introduced by
$gpermHandler 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...
245
    $count        = 0;
246
    $sql          = $xoopsDB->query('SELECT entryID FROM ' . $xoopsDB->prefix('lxentries') . " WHERE offline = '0' AND categoryID = '$c'");
247
    while ($myrow = $xoopsDB->fetchArray($sql)) {
0 ignored issues
show
Unused Code introduced by
$myrow 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...
248
        //if ($gpermHandler->checkRight('lexikon_view', $c, $groups, $xoopsModule->getVar('mid'))) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
74% 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...
249
            ++$count;
250
            //}
251
    }
252
253
    return $count;
254
}
255
256
    /**
257
     * @return int
258
     */
259
public static function countCats()
260
{
261
    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...
262
    $gpermHandler = xoops_getHandler('groupperm');
263
    $groups       = is_object($xoopsUser) ? $xoopsUser->getGroups() : XOOPS_GROUP_ANONYMOUS;
264
    $totalcats    = $gpermHandler->getItemIds('lexikon_view', $groups, $xoopsModule->getVar('mid'));
265
266
    return count($totalcats);
267
}
268
269
    /**
270
     * @return mixed
271
     */
272
public static function countWords()
273
{
274
    global $xoopsUser, $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...
275
    $gpermHandler = xoops_getHandler('groupperm');
276
    $groups       = is_object($xoopsUser) ? $xoopsUser->getGroups() : XOOPS_GROUP_ANONYMOUS;
277
        /** @var XoopsModuleHandler $moduleHandler */
278
        $moduleHandler = xoops_getHandler('module');
279
    $module        = $moduleHandler->getByDirname('lexikon');
280
    $module_id     = $module->getVar('mid');
281
    $allowed_cats  = $gpermHandler->getItemIds('lexikon_view', $groups, $module_id);
282
    $catids        = implode(',', $allowed_cats);
283
    $catperms      = " AND categoryID IN ($catids) ";
284
285
    $pubwords       = $xoopsDB->query('SELECT * FROM ' . $xoopsDB->prefix('lxentries') . " WHERE submit = '0' AND offline ='0' AND request = '0' " . $catperms . ' ');
286
    $publishedwords = $xoopsDB->getRowsNum($pubwords);
287
288
    return $publishedwords;
289
}
290
291
    // To display the list of categories
292
    /**
293
     * @return array
294
     */
295
public static function getCategoryArray()
296
{
297
    global $xoopsDB, $xoopsModuleConfig, $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...
298
    $myts         = MyTextSanitizer::getInstance();
299
    $groups       = is_object($xoopsUser) ? $xoopsUser->getGroups() : XOOPS_GROUP_ANONYMOUS;
300
    $gpermHandler = xoops_getHandler('groupperm');
301
    $block0       = array();
302
    $count        = 1;
303
    $resultcat    = $xoopsDB->query('SELECT categoryID, name, total, logourl FROM ' . $xoopsDB->prefix('lxcategories') . ' ORDER BY weight ASC');
304
    while (list($catID, $name, $total, $logourl) = $xoopsDB->fetchRow($resultcat)) {
305
        if ($gpermHandler->checkRight('lexikon_view', $catID, $groups, $xoopsModule->getVar('mid'))) {
306
            $catlinks = array();
307
            ++$count;
308
            if ($logourl && $logourl !== 'http://') {
309
                $logourl = $myts->htmlSpecialChars($logourl);
310
            } else {
311
                $logourl = '';
312
            }
313
            $xoopsModule          = XoopsModule::getByDirname('lexikon');
314
            $catlinks['id']       = (int)$catID;
315
            $catlinks['total']    = (int)$total;
316
            $catlinks['linktext'] = $myts->htmlSpecialChars($name);
317
            $catlinks['image']    = $logourl;
318
            $catlinks['count']    = (int)$count;
319
320
            $block0['categories'][] = $catlinks;
321
        }
322
    }
323
324
    return $block0;
325
}
326
327
    /**
328
     * @return array
329
     */
330
public static function getAlphaArray()
331
{
332
    global $xoopsUser, $xoopsDB, $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...
333
    $gpermHandler = xoops_getHandler('groupperm');
334
    $groups       = is_object($xoopsUser) ? $xoopsUser->getGroups() : XOOPS_GROUP_ANONYMOUS;
335
        /** @var XoopsModuleHandler $moduleHandler */
336
        $moduleHandler = xoops_getHandler('module');
337
    $module        = $moduleHandler->getByDirname('lexikon');
338
    $module_id     = $module->getVar('mid');
339
    $allowed_cats  = $gpermHandler->getItemIds('lexikon_view', $groups, $module_id);
340
    $catids        = implode(',', $allowed_cats);
341
    $catperms      = " AND categoryID IN ($catids) ";
342
    $alpha         = array();
343
    for ($a = 65; $a < (65 + 26); ++$a) {
344
        $letterlinks             = array();
345
        $initial                 = chr($a);
346
        $sql                     = $xoopsDB->query('SELECT entryID FROM '
347
                                                       . $xoopsDB->prefix('lxentries')
348
                                                       . " WHERE init = '$initial' AND submit = '0' AND offline ='0' AND request = '0' "
349
                                                       . $catperms
350
                                                       . '');
351
        $howmany                 = $xoopsDB->getRowsNum($sql);
352
        $letterlinks['total']    = $howmany;
353
        $letterlinks['id']       = chr($a);
354
        $letterlinks['linktext'] = chr($a);
355
356
        $alpha['initial'][] = $letterlinks;
357
    }
358
359
    return $alpha;
360
}
361
362
    /**
363
     * chr() with unicode support
364
     * I found this on this site http://en.php.net/chr
365
     * don't take credit for this.
366
     * @param $initials
367
     * @return string
368
     */
369
public static function getUchr($initials)
370
{
371
    if (is_scalar($initials)) {
372
        $initials = func_get_args();
373
    }
374
    $str = '';
375
    foreach ($initials as $init) {
376
        $str .= html_entity_decode('&#' . $init . ';', ENT_NOQUOTES, 'UTF-8');
377
    }
378
379
    return $str;
380
}
381
382
    /* sample */
383
    /*
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...
384
        echo LexikonUtility::getUchr(23383); echo '<br>';
385
        echo LexikonUtility::getUchr(23383,215,23383); echo '<br>';
386
        echo LexikonUtility::getUchr(array(23383,215,23383,215,23383)); echo '<br>';
387
    */
388
389
    // Functional links
390
    /**
391
     * @param $variable
392
     * @return string
393
     */
394
public static function getServiceLinks($variable)
395
{
396
    global $xoopsUser, $xoopsDB, $xoopsModule, $xoopsModuleConfig, $xoopsConfig, $entrytype;
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...
397
398
        /** @var XoopsModuleHandler $moduleHandler */
399
        $moduleHandler = xoops_getHandler('module');
400
    $moduleInfo    = $moduleHandler->get($xoopsModule->getVar('mid'));
0 ignored issues
show
Unused Code introduced by
$moduleInfo 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...
401
    $pathIcon16    = \Xmf\Module\Admin::iconUrl('', 16);
402
403
    $srvlinks = '';
404
    if ($xoopsUser) {
405
        if ($xoopsUser->isAdmin()) {
406
            $srvlinks .= "<a TITLE=\""
407
                             . _EDIT
408
                             . "\" href=\"admin/entry.php?op=mod&entryID="
409
                             . $variable['id']
410
                             . "\" target=\"_blank\"><img src=\""
411
                             . $pathIcon16 . "/edit.png\"   border=\"0\" alt=\""
412
                             . _MD_LEXIKON_EDITTERM
413
                             . "\" width=\"16\" height=\"16\"></a>&nbsp;<a TITLE=\""
414
                             . _DELETE
415
                             . "\" href=\"admin/entry.php?op=del&entryID="
416
                             . $variable['id']
417
                             . "\" target=\"_self\"><img src=\""
418
                             . $pathIcon16 . "/delete.png\"   border=\"0\" alt=\""
419
                             . _MD_LEXIKON_DELTERM
420
                             . "\" width=\"16\" height=\"16\"></a>&nbsp;";
421
        }
422
    }
423
    if ($entrytype != '1') {
424
        $srvlinks .= "<a TITLE=\""
425
                         . _MD_LEXIKON_PRINTTERM
426
                         . "\" href=\"print.php?entryID="
427
                         . $variable['id']
428
                         . "\" target=\"_blank\"><img src=\""
429
                         . $pathIcon16 . "/printer.png\"    border=\"0\" alt=\""
430
                         . _MD_LEXIKON_PRINTTERM
431
                         . "\" width=\"16\" height=\"16\"></a>&nbsp;<a TITLE=\""
432
                         . _MD_LEXIKON_SENDTOFRIEND
433
                         . "\" href=\"mailto:?subject="
434
                         . sprintf(_MD_LEXIKON_INTENTRY, $xoopsConfig['sitename'])
435
                         . '&amp;body='
436
                         . sprintf(_MD_LEXIKON_INTENTRYFOUND, $xoopsConfig['sitename'])
437
                         . ': '
438
                         . XOOPS_URL
439
                         . '/modules/'
440
                         . $xoopsModule->dirname()
441
                         . '/entry.php?entryID='
442
                         . $variable['id']
443
                         . " \" target=\"_blank\"><img src=\""
444
                         . $pathIcon16 . "/mail_replay.png\"   border=\"0\" alt=\""
445
                         . _MD_LEXIKON_SENDTOFRIEND
446
                         . "\" width=\"16\" height=\"16\"></a>&nbsp;";
447
        if (($xoopsModuleConfig['com_rule'] != 0)
448
                && (!empty($xoopsModuleConfig['com_anonpost'])
449
                    || is_object($xoopsUser))
450
            ) {
451
            $srvlinks .= "<a TITLE=\""
452
                             . _COMMENTS
453
                             . "?\" href=\"comment_new.php?com_itemid="
454
                             . $variable['id']
455
                             . "\" target=\"_parent\"><img src=\"assets/images/comments.gif\" border=\"0\" alt=\""
456
                             . _COMMENTS
457
                             . "?\" width=\"16\" height=\"16\"></a>&nbsp;";
458
        }
459
    }
460
461
    return $srvlinks;
462
}
463
464
    // entry footer
465
    /**
466
     * @param $variable
467
     * @return string
468
     */
469
public static function getServiceLinksNew($variable)
470
{
471
    global $xoopsUser, $xoopsDB, $xoopsModule, $xoopsModuleConfig, $xoopsConfig, $myts;
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...
472
    $srvlinks2 = "<a TITLE=\""
473
                     . _MD_LEXIKON_PRINTTERM
474
                     . "\" href=\"print.php?entryID="
475
                     . $variable['id']
476
                     . "\" target=\"_blank\"><img src=\"assets/images/print.gif\" border=\"0\" alt=\""
477
                     . _MD_LEXIKON_PRINTTERM
478
                     . "\" align=\"absmiddle\" width=\"16\" height=\"16\" hspace=\"2\" vspace=\"4\"> "
479
                     . _MD_LEXIKON_PRINTTERM2
480
                     . "</a>&nbsp; <a TITLE=\""
481
                     . _MD_LEXIKON_SENDTOFRIEND
482
                     . "\" href=\"mailto:?subject="
483
                     . sprintf(_MD_LEXIKON_INTENTRY, $xoopsConfig['sitename'])
484
                     . '&amp;body='
485
                     . sprintf(_MD_LEXIKON_INTENTRYFOUND, $xoopsConfig['sitename'])
486
                     . ': '
487
                     . $variable['term']
488
                     . ' '
489
                     . XOOPS_URL
490
                     . '/modules/'
491
                     . $xoopsModule->dirname()
492
                     . '/entry.php?entryID='
493
                     . $variable['id']
494
                     . " \" target=\"_blank\"><img src=\"assets/images/friend.gif\" border=\"0\" alt=\""
495
                     . _MD_LEXIKON_SENDTOFRIEND
496
                     . "\" align=\"absmiddle\" width=\"16\" height=\"16\" hspace=\"2\" vspace=\"4\"> "
497
                     . _MD_LEXIKON_SENDTOFRIEND2
498
                     . '</a>&nbsp;';
499
500
    return $srvlinks2;
501
}
502
503
    /**
504
     * @return string
505
     */
506
public static function showSearchForm()
507
{
508
    global $xoopsUser, $xoopsDB, $xoopsModule, $xoopsModuleConfig, $xoopsConfig;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

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

1. Pass all data via parameters

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

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

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

    public function myFunction() {
        // Do something
    }
}
Loading history...
509
    $gpermHandler = xoops_getHandler('groupperm');
510
    $groups       = is_object($xoopsUser) ? $xoopsUser->getGroups() : XOOPS_GROUP_ANONYMOUS;
511
512
    $searchform = "<table width=\"100%\">";
513
    $searchform .= "<form name=\"op\" id=\"op\" action=\"search.php\" method=\"post\">";
514
    $searchform .= "<tr><td style=\"text-align: right; line-height: 200%\" width=\"150\">";
515
    $searchform .= _MD_LEXIKON_LOOKON . "</td><td width=\"10\">&nbsp;</td><td style=\"text-align: left;\">";
516
    $searchform .= "<select name=\"type\"><option value=\"1\">" . _MD_LEXIKON_TERMS . "</option><option value=\"2\">" . _MD_LEXIKON_DEFINS . '</option>';
517
    $searchform .= "<option SELECTED value=\"3\">" . _MD_LEXIKON_TERMSDEFS . '</option></select></td></tr>';
518
519
    if ($xoopsModuleConfig['multicats'] == 1) {
520
        $searchform .= "<tr><td style=\"text-align: right; line-height: 200%\">" . _MD_LEXIKON_CATEGORY . '</td>';
521
        $searchform .= "<td>&nbsp;</td><td style=\"text-align: left;\">";
522
        $resultcat  = $xoopsDB->query('SELECT categoryID, name FROM ' . $xoopsDB->prefix('lxcategories') . ' ORDER BY categoryID');
523
        $searchform .= "<select name=\"categoryID\">";
524
        $searchform .= "<option value=\"0\">" . _MD_LEXIKON_ALLOFTHEM . '</option>';
525
526
        while (list($categoryID, $name) = $xoopsDB->fetchRow($resultcat)) {
527
            if ($gpermHandler->checkRight('lexikon_view', (int)$categoryID, $groups, $xoopsModule->getVar('mid'))) {
528
                $searchform .= "<option value=\"$categoryID\">$categoryID : $name</option>";
529
            }
530
        }
531
        $searchform .= '</select></td></tr>';
532
    }
533
534
    $searchform .= "<tr><td style=\"text-align: right; line-height: 200%\">";
535
    $searchform .= _MD_LEXIKON_TERM . "</td><td>&nbsp;</td><td style=\"text-align: left;\">";
536
    $searchform .= "<input type=\"text\" name=\"term\" class=\"searchBox\" /></td></tr><tr>";
537
    $searchform .= "<td>&nbsp;</td><td>&nbsp;</td><td><input type=\"submit\" class=\"btnDefault\" value=\"" . _MD_LEXIKON_SEARCH . "\" />";
538
    $searchform .= '</td></tr></form></table>';
539
540
    return $searchform;
541
}
542
543
    /**
544
     * @param $needle
545
     * @param $haystack
546
     * @param $hlS
547
     * @param $hlE
548
     * @return string
549
     */
550
public static function getHTMLHighlight($needle, $haystack, $hlS, $hlE)
551
{
552
    $parts = explode('>', $haystack);
553
    foreach ($parts as $key => $part) {
554
        $pL = '';
555
        $pR = '';
556
557
        if (($pos = strpos($part, '<')) === false) {
558
            $pL = $part;
559
        } elseif ($pos > 0) {
560
            $pL = substr($part, 0, $pos);
561
            $pR = substr($part, $pos, strlen($part));
562
        }
563
        if ($pL != '') {
564
            $parts[$key] = preg_replace('|(' . quotemeta($needle) . ')|iU', $hlS . '\\1' . $hlE, $pL) . $pR;
565
        }
566
    }
567
568
    return implode('>', $parts);
569
}
570
571
    /* *******************************************************************************
572
     * Most of the following functions are modified functions from Herve's News Module
573
     * other functions are from  AMS by Novasmart/Mithrandir
574
     * others from Red Mexico Soft Rmdp
575
     * others from Xhelp 0.78 thanks to ackbarr and eric_juden
576
     * *******************************************************************************
577
     */
578
579
    // Create the meta keywords based on content
580
    /**
581
     * @param $content
582
     */
583
public static function extractKeywords($content)
0 ignored issues
show
Coding Style introduced by
extractKeywords 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...
584
{
585
    global $xoopsTpl, $xoTheme, $xoopsModule, $xoopsModuleConfig;
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...
586
    include_once XOOPS_ROOT_PATH . '/modules/lexikon/include/common.inc.php';
587
    $keywords_count = $xoopsModuleConfig['metakeywordsnum'];
588
    $tmp            = array();
589
    if (isset($_SESSION['xoops_keywords_limit'])) {    // Search the "Minimum keyword length"
590
            $limit = $_SESSION['xoops_keywords_limit'];
591
    } else {
592
        $configHandler                    = xoops_getHandler('config');
593
        $xoopsConfigSearch                = $configHandler->getConfigsByCat(XOOPS_CONF_SEARCH);
594
        $limit                            = $xoopsConfigSearch['keyword_min'];
595
        $_SESSION['xoops_keywords_limit'] = $limit;
596
    }
597
    $myts            = MyTextSanitizer::getInstance();
598
    $content         = str_replace('<br>', ' ', $content);
599
    $content         = $myts->undoHtmlSpecialChars($content);
600
    $content         = strip_tags($content);
601
    $content         = strtolower($content);
602
    $search_pattern  = array(
603
            '&nbsp;',
604
            "\t",
605
            "\r\n",
606
            "\r",
607
            "\n",
608
            ',',
609
            '.',
610
            "'",
611
            ';',
612
            ':',
613
            ')',
614
            '(',
615
            '"',
616
            '?',
617
            '!',
618
            '{',
619
            '}',
620
            '[',
621
            ']',
622
            '<',
623
            '>',
624
            '/',
625
            '+',
626
            '-',
627
            '_',
628
            '\\',
629
            '*'
630
        );
631
    $replace_pattern = array(
632
            ' ',
633
            ' ',
634
            ' ',
635
            ' ',
636
            ' ',
637
            ' ',
638
            ' ',
639
            ' ',
640
            '',
641
            '',
642
            '',
643
            '',
644
            '',
645
            '',
646
            '',
647
            '',
648
            '',
649
            '',
650
            '',
651
            '',
652
            '',
653
            '',
654
            '',
655
            '',
656
            '',
657
            '',
658
            ''
659
        );
660
    $content         = str_replace($search_pattern, $replace_pattern, $content);
661
    $keywords        = explode(' ', $content);
662
    switch (META_KEYWORDS_ORDER) {
663
            case 1:    // Returns keywords in the same order that they were created in the text
664
                $keywords = array_unique($keywords);
665
                break;
666
667
            case 2:    // the keywords order is made according to the reverse keywords frequency (so the less frequent words appear in first in the list)
668
                $keywords = array_count_values($keywords);
669
                asort($keywords);
670
                $keywords = array_keys($keywords);
671
                break;
672
673
            case 3:    // Same as previous, the only difference is that the most frequent words will appear in first in the list
674
                $keywords = array_count_values($keywords);
675
                arsort($keywords);
676
                $keywords = array_keys($keywords);
677
                break;
678
        }
679
    foreach ($keywords as $keyword) {
680
        if (strlen($keyword) >= $limit && !is_numeric($keyword)) {
681
            $tmp[] = $keyword;
682
        }
683
    }
684
    $tmp = array_slice($tmp, 0, $keywords_count);
685
    if (count($tmp) > 0) {
686 View Code Duplication
        if (isset($xoTheme) && is_object($xoTheme)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
687
            $xoTheme->addMeta('meta', 'keywords', implode(',', $tmp));
688
        } else {    // Compatibility for old Xoops versions
689
                $xoopsTpl->assign('xoops_meta_keywords', implode(',', $tmp));
690
        }
691
    } else {
692
        if (!isset($configHandler) || !is_object($configHandler)) {
693
            $configHandler = xoops_getHandler('config');
694
        }
695
        $xoopsConfigMetaFooter = $configHandler->getConfigsByCat(XOOPS_CONF_METAFOOTER);
696
        if (isset($xoTheme) && is_object($xoTheme)) {
697
            $xoTheme->addMeta('meta', 'keywords', $xoopsConfigMetaFooter['meta_keywords']);
698
        } else {    // Compatibility for old Xoops versions
699
                $xoopsTpl->assign('xoops_meta_keywords', $xoopsConfigMetaFooter['meta_keywords']);
700
        }
701
    }
702
}
703
704
    // Create meta description based on content
705
    /**
706
     * @param $content
707
     */
708
public static function getMetaDescription($content)
709
{
710
    global $xoopsTpl, $xoTheme;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

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

1. Pass all data via parameters

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

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

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

    public function myFunction() {
        // Do something
    }
}
Loading history...
711
    $myts    = MyTextSanitizer::getInstance();
712
    $content = $myts->undoHtmlSpecialChars($myts->displayTarea($content));
713 View Code Duplication
    if (isset($xoTheme) && is_object($xoTheme)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
714
        $xoTheme->addMeta('meta', 'description', strip_tags($content));
715
    } else {  // Compatibility for old Xoops versions
716
            $xoopsTpl->assign('xoops_meta_description', strip_tags($content));
717
    }
718
}
719
720
    // Create pagetitles
721
    /**
722
     * @param string $article
723
     * @param string $topic
724
     */
725
public static function createPageTitle($article = '', $topic = '')
726
{
727
    global $xoopsModule, $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...
728
    $myts    = MyTextSanitizer::getInstance();
729
    $content = '';
730
    if (!empty($article)) {
731
        $content .= strip_tags($myts->displayTarea($article));
732
    }
733 View Code Duplication
    if (!empty($topic)) {
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...
734
        if (xoops_trim($content) != '') {
735
            $content .= ' - ' . strip_tags($myts->displayTarea($topic));
736
        } else {
737
            $content .= strip_tags($myts->displayTarea($topic));
738
        }
739
    }
740
    if (is_object($xoopsModule) && xoops_trim($xoopsModule->name()) != '') {
741 View Code Duplication
        if (xoops_trim($content) != '') {
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...
742
            $content .= ' - ' . strip_tags($myts->displayTarea($xoopsModule->name()));
743
        } else {
744
            $content .= strip_tags($myts->displayTarea($xoopsModule->name()));
745
        }
746
    }
747
    if ($content != '') {
748
        $xoopsTpl->assign('xoops_pagetitle', $content);
749
    }
750
}
751
752
    // clear descriptions
753
    /**
754
     * @param $document
755
     * @return mixed
756
     */
757
public static function convertHtml2text($document)
758
{
759
    // PHP Manual:: function preg_replace $document should contain an HTML document.
760
        // This will remove HTML tags, javascript sections and white space. It will also
761
        // convert some common HTML entities to their text equivalent.
762
763
        $search = array(
764
            "'<script[^>]*?>.*?</script>'si",  // Strip out javascript
765
            "'<[\/\!]*?[^<>]*?>'si",          // Strip out HTML tags
766
            "'([\r\n])[\s]+'",                // Strip out white space
767
            "'&(quot|#34);'i",                // Replace HTML entities
768
            "'&(amp|#38);'i",
769
            "'&(lt|#60);'i",
770
            "'&(gt|#62);'i",
771
            "'&(nbsp|#160);'i",
772
            "'&(iexcl|#161);'i",
773
            "'&(cent|#162);'i",
774
            "'&(pound|#163);'i",
775
            "'&(copy|#169);'i"
776
        );
777
778
    $replace = array(
779
            '',
780
            '',
781
            "\\1",
782
            "\"",
783
            '&',
784
            '<',
785
            '>',
786
            ' ',
787
            chr(161),
788
            chr(162),
789
            chr(163),
790
            chr(169)
791
        );
792
793
    $text = preg_replace($search, $replace, $document);
794
795
    $text = preg_replace_callback("&#(\d+)&", create_function('$matches', "return chr(\$matches[1]);"), $text);
0 ignored issues
show
Security Best Practice introduced by
The use of create_function is highly discouraged, better use a closure.

create_function can pose a great security vulnerability as it is similar to eval, and could be used for arbitrary code execution. We highly recommend to use a closure instead.

// Instead of
$function = create_function('$a, $b', 'return $a + $b');

// Better use
$function = function($a, $b) { return $a + $b; }
Loading history...
796
797
    return $text;
798
}
799
800
    //Retrieve moduleoptions equivalent to $Xoopsmoduleconfig
801
    /**
802
     * @param         $option
803
     * @param  string $repmodule
804
     * @return bool
805
     */
806
public static function getModuleOption($option, $repmodule = 'lexikon')
807
{
808
    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...
809
    static $tbloptions = array();
810
    if (is_array($tbloptions) && array_key_exists($option, $tbloptions)) {
811
        return $tbloptions[$option];
812
    }
813
814
    $retval = false;
815
    if (isset($xoopsModuleConfig)
816
            && (is_object($xoopsModule) && $xoopsModule->getVar('dirname') == $repmodule
817
                && $xoopsModule->getVar('isactive'))
818
        ) {
819
        if (isset($xoopsModuleConfig[$option])) {
820
            $retval = $xoopsModuleConfig[$option];
821
        }
822
    } else {
823
        /** @var XoopsModuleHandler $moduleHandler */
824
            $moduleHandler = xoops_getHandler('module');
825
        $module        = $moduleHandler->getByDirname($repmodule);
826
        $configHandler = xoops_getHandler('config');
827
        if ($module) {
828
            $moduleConfig = $configHandler->getConfigsByCat(0, $module->getVar('mid'));
829
            if (isset($moduleConfig[$option])) {
830
                $retval = $moduleConfig[$option];
831
            }
832
        }
833
    }
834
    $tbloptions[$option] = $retval;
835
836
    return $retval;
837
}
838
839
    /**
840
     * Is Xoops 2.3.x ?
841
     *
842
     * @return boolean need to say it ?
843
     */
844
public static function isX23()
845
{
846
    $x23 = false;
847
    $xv  = str_replace('XOOPS ', '', XOOPS_VERSION);
848
    if (substr($xv, 2, 1) >= '3') {
849
        $x23 = true;
850
    }
851
852
    return $x23;
853
}
854
855
    /**
856
     * Retreive an editor according to the module's option "form_options"
857
     * following function is from News modified by trabis
858
     * @param                                                                                                                                 $caption
859
     * @param                                                                                                                                 $name
860
     * @param  string                                                                                                                         $value
861
     * @param  string                                                                                                                         $width
862
     * @param  string                                                                                                                         $height
863
     * @param  string                                                                                                                         $supplemental
864
     * @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...
865
     */
866
public static function getWysiwygForm($caption, $name, $value = '', $width = '100%', $height = '400px', $supplemental = '')
867
{
868
    $editor_option            = strtolower(LexikonUtility::getModuleOption('form_options'));
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

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

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

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

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

Loading history...
869
    $editor                   = false;
870
    $editor_configs           = array();
871
    $editor_configs['name']   = $name;
872
    $editor_configs['value']  = $value;
873
    $editor_configs['rows']   = 35;
874
    $editor_configs['cols']   = 60;
875
    $editor_configs['width']  = '100%';
876
    $editor_configs['height'] = '350px';
877
    $editor_configs['editor'] = $editor_option;
878
879
    if (LexikonUtility::isX23()) {
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

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

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

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

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

Loading history...
880
        $editor = new XoopsFormEditor($caption, $name, $editor_configs);
881
882
        return $editor;
883
    }
884
885
        // Only for Xoops 2.0.x
886
        switch ($editor_option) {
887 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...
888
                if (is_readable(XOOPS_ROOT_PATH . '/class/fckeditor/formfckeditor.php')) {
889
                    require_once XOOPS_ROOT_PATH . '/class/fckeditor/formfckeditor.php';
890
                    $editor = new XoopsFormFckeditor($caption, $name, $value);
891
                }
892
                break;
893
894 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...
895
                if (is_readable(XOOPS_ROOT_PATH . '/class/htmlarea/formhtmlarea.php')) {
896
                    require_once XOOPS_ROOT_PATH . '/class/htmlarea/formhtmlarea.php';
897
                    $editor = new XoopsFormHtmlarea($caption, $name, $value);
898
                }
899
                break;
900
901
            case 'dhtmltextarea':
902
            case 'dhtml':
903
                $editor = new XoopsFormDhtmlTextArea($caption, $name, $value, 10, 50, $supplemental);
904
                break;
905
906
            case 'textarea':
907
                $editor = new XoopsFormTextArea($caption, $name, $value);
908
                break;
909
910
            case 'tinyeditor':
911
            case 'tinymce':
912
                if (is_readable(XOOPS_ROOT_PATH . '/class/xoopseditor/tinyeditor/formtinyeditortextarea.php')) {
913
                    require_once XOOPS_ROOT_PATH . '/class/xoopseditor/tinyeditor/formtinyeditortextarea.php';
914
                    $editor = new XoopsFormTinyeditorTextArea(array(
915
                                                                  'caption' => $caption,
916
                                                                  'name'    => $name,
917
                                                                  'value'   => $value,
918
                                                                  'width'   => '100%',
919
                                                                  'height'  => '400px'
920
                                                              ));
921
                }
922
                break;
923
924 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...
925
                if (is_readable(XOOPS_ROOT_PATH . '/class/wysiwyg/formwysiwygtextarea.php')) {
926
                    require_once XOOPS_ROOT_PATH . '/class/wysiwyg/formwysiwygtextarea.php';
927
                    $editor = new XoopsFormWysiwygTextArea($caption, $name, $value, $width, $height, '');
928
                }
929
                break;
930
        }
931
932
    return $editor;
933
}
934
935
    /**
936
     * linkterms: assign module header
937
     *
938
     * tooltips (c) dhtmlgoodies
939
     */
940
public static function getModuleHeader()
941
{
942
    global $xoopsTpl, $xoTheme, $xoopsModule, $xoopsModuleConfig, $lexikon_module_header;
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...
943
    if (isset($xoTheme) && is_object($xoTheme)) {
944
        $xoTheme->addStylesheet('modules/lexikon/assets/css/style.css');
945 View Code Duplication
        if ($xoopsModuleConfig['linkterms'] == 3) {
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...
946
            $xoTheme->addStylesheet('modules/lexikon/assets/css/linkterms.css');
947
            $xoTheme->addScript('/modules/lexikon/assets/js/tooltipscript2.js', array('type' => 'text/javascript'));
948
        }
949
        if ($xoopsModuleConfig['linkterms'] == 4) {
950
            $xoTheme->addScript('/modules/lexikon/assets/js/popup.js', array('type' => 'text/javascript'));
951
        }
952 View Code Duplication
        if ($xoopsModuleConfig['linkterms'] == 5) {
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...
953
            $xoTheme->addStylesheet('modules/lexikon/assets/css/linkterms.css');
954
            $xoTheme->addScript('/modules/lexikon/assets/js/balloontooltip.js', array('type' => 'text/javascript'));
955
        }
956 View Code Duplication
        if ($xoopsModuleConfig['linkterms'] == 6) {
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...
957
            $xoTheme->addStylesheet('modules/lexikon/assets/css/linkterms.css');
958
            $xoTheme->addScript('/modules/lexikon/assets/js/shadowtooltip.js', array('type' => 'text/javascript'));
959
        }
960
    } else {
961
        $lexikon_url = XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname');
962
        if ($xoopsModuleConfig['linkterms'] == 3) {
963
            $lexikon_module_header = '<link rel="stylesheet" type="text/css" href="assets/css/style.css" />
964
            <link rel="stylesheet" type="text/css" href="assets/css/linkterms.css" />
965
            <script src="' . $lexikon_url . '/assets/js/tooltipscript2.js" type="text/javascript"></script>';
966
        }
967
        if ($xoopsModuleConfig['linkterms'] == 4) {
968
            $lexikon_module_header = '<link rel="stylesheet" type="text/css" href="assets/css/style.css" />
969
            <link rel="stylesheet" type="text/css" href="assets/css/linkterms.css" />
970
            <script src="' . $lexikon_url . '/assets/js/popup.js" type="text/javascript"></script>';
971
        }
972
        if ($xoopsModuleConfig['linkterms'] == 5) {
973
            $lexikon_module_header = '<link rel="stylesheet" type="text/css" href="assets/css/style.css" />
974
            <link rel="stylesheet" type="text/css" href="assets/css/linkterms.css" />
975
            <script src="' . $lexikon_url . '/assets/js/balloontooltip.js" type="text/javascript"></script>';
976
        }
977
        if ($xoopsModuleConfig['linkterms'] == 6) {
978
            $lexikon_module_header = '<link rel="stylesheet" type="text/css" href="assets/css/style.css" />
979
            <link rel="stylesheet" type="text/css" href="assets/css/linkterms.css" />
980
            <script src="' . $lexikon_url . '/assets/js/shadowtooltip.js" type="text/javascript"></script>';
981
        }
982
    }
983
}
984
985
    /**
986
     * Validate userid
987
     * @param $uids
988
     * @return bool
989
     */
990
public static function getUserData($uids)
991
{
992
    global $xoopsDB, $xoopsUser, $xoopsUserIsAdmin;
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...
993
994
    if ($uids <= 0) {
995
        return false;
996
    }
997
    if ($uids > 0) {
998
        $memberHandler = xoops_getHandler('member');
999
        $user          = $memberHandler->getUser($uids);
1000
        if (!is_object($user)) {
1001
            return false;
1002
        }
1003
    }
1004
    $result = $xoopsDB->query('SELECT * FROM ' . $xoopsDB->prefix('users') . " WHERE uid='$uids'");
1005
    if ($xoopsDB->getRowsNum($result) <= 0) {
1006
        return false;
1007
    }
1008
    $row = $xoopsDB->fetchArray($result);
1009
1010
    return $row;
1011
}
1012
1013
    // Get all terms published by an author
1014
    /**
1015
     * @param $uid
1016
     */
1017
public static function getAuthorProfile($uid)
0 ignored issues
show
Coding Style introduced by
getAuthorProfile uses the super-global variable $_GET 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...
1018
{
1019
    include_once XOOPS_ROOT_PATH . '/class/pagenav.php';
1020
    global $authortermstotal, $xoopsTpl, $xoopsDB, $xoopsUser, $xoopsModuleConfig;
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...
1021
    $myts = MyTextSanitizer::getInstance();
0 ignored issues
show
Unused Code introduced by
$myts 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...
1022
        //permissions
1023
        $gpermHandler = xoops_getHandler('groupperm');
1024
    $groups       = is_object($xoopsUser) ? $xoopsUser->getGroups() : XOOPS_GROUP_ANONYMOUS;
1025
        /** @var XoopsModuleHandler $moduleHandler */
1026
        $moduleHandler = xoops_getHandler('module');
1027
    $module        = $moduleHandler->getByDirname('lexikon');
1028
    $module_id     = $module->getVar('mid');
1029
    $allowed_cats  = $gpermHandler->getItemIds('lexikon_view', $groups, $module_id);
1030
    $catids        = implode(',', $allowed_cats);
1031
    $catperms      = " AND categoryID IN ($catids) ";
1032
1033
    $start = isset($_GET['start']) ? (int)$_GET['start'] : 0;
1034
    $limit = $xoopsModuleConfig['indexperpage'];
1035
1036
    $sql = $xoopsDB->query('SELECT *
1037
                              FROM ' . $xoopsDB->prefix('lxentries') . "
1038
                              WHERE uid='" . (int)$uid . "' AND  offline = '0' AND submit = '0' AND request = '0' " . $catperms . "
1039
                              ORDER BY term
1040
                              LIMIT $start,$limit");
1041
1042
    while ($row = $xoopsDB->fetchArray($sql)) {
1043
        $xoopsTpl->append('entries', array(
1044
                'id'      => $row['entryID'],
1045
                'name'    => $row['term'],
1046
                'date'    => date($xoopsModuleConfig['dateformat'], $row['datesub']),
1047
                'counter' => $row['counter']
1048
            ));
1049
    }
1050
1051
    $navstring                = '';
1052
    $navstring                .= 'uid=' . $uid . '&start';
1053
    $pagenav                  = new XoopsPageNav($authortermstotal, $xoopsModuleConfig['indexperpage'], $start, $navstring);
1054
    $authortermsarr['navbar'] = '<span style="text-align:right;">' . $pagenav->renderNav(6) . '</span>';
0 ignored issues
show
Coding Style Comprehensibility introduced by
$authortermsarr was never initialized. Although not strictly required by PHP, it is generally a good practice to add $authortermsarr = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
1055
    $xoopsTpl->assign('authortermsarr', $authortermsarr);
1056
}
1057
1058
    // Returns the author's IDs for authorslist
1059
    /**
1060
     * @param  int $limit
1061
     * @param  int $start
1062
     * @return array
1063
     */
1064
public static function getAuthors($limit = 0, $start = 0)
0 ignored issues
show
Unused Code introduced by
The parameter $limit is not used and could be removed.

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

Loading history...
Unused Code introduced by
The parameter $start is not used and could be removed.

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

Loading history...
1065
{
1066
    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...
1067
1068
    $ret    = array();
1069
    $sql    = 'SELECT DISTINCT(uid) AS uid FROM ' . $xoopsDB->prefix('lxentries') . ' WHERE offline = 0 ';
1070
    $sql    .= ' ORDER BY uid';
1071
    $result = $xoopsDB->query($sql);
1072
    while ($myrow = $xoopsDB->fetchArray($result)) {
1073
        $ret[] = $myrow['uid'];
1074
    }
1075
1076
    return $ret;
1077
}
1078
1079
    // link to userprofile
1080
    /**
1081
     * @param $userid
1082
     * @return string
1083
     */
1084
public static function getLinkedProfileFromId($userid)
0 ignored issues
show
Unused Code introduced by
The parameter $userid is not used and could be removed.

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

Loading history...
Coding Style introduced by
getLinkedProfileFromId uses the super-global variable $GLOBALS which is generally not recommended.

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

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

// Better
class Router
{
    private $host;

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

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

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

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
1085
{
1086
    global $uid, $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...
1087
    $userid = (int)$uid;
1088
    if ($userid > 0) {
1089
        $memberHandler = xoops_getHandler('member');
1090
        $user          = $memberHandler->getUser($userid);
1091
        if (is_object($user)) {
1092
            $linkeduser = '<A TITLE="'
1093
                              . _MD_LEXIKON_AUTHORPROFILETEXT
1094
                              . '" HREF="'
1095
                              . XOOPS_URL
1096
                              . '/modules/'
1097
                              . $xoopsModule->dirname()
1098
                              . '/profile.php?uid='
1099
                              . $uid
1100
                              . '">'
1101
                              . $user->getVar('uname')
1102
                              . '</a>';
1103
                //$linkeduser = XoopsUserUtility::getUnameFromId ( $uid );
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...
1104
                //$linkeduser .= '<div style=\'position:relative; right: 4px; top: 2px;\'><A TITLE="'._MD_LEXIKON_AUTHORPROFILETEXT.'" HREF="'.XOOPS_URL.'/modules/'.$xoopsModule->dirname().'/profile.php?uid='.$uid.'">'._MD_LEXIKON_AUTHORPROFILETEXT.'</a></div>';
0 ignored issues
show
Unused Code Comprehensibility introduced by
40% 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...
1105
                return $linkeduser;
1106
        }
1107
    }
1108
1109
    return $GLOBALS['xoopsConfig']['anonymous'];
1110
}
1111
1112
    // functionset to assign terms with accentuated or umlaut initials to the adequate initial
1113
    /**
1114
     * @param $string
1115
     * @return mixed|string
1116
     */
1117
public static function removeAccents($string)
1118
{
1119
    $chars['in']  = chr(128)
0 ignored issues
show
Coding Style Comprehensibility introduced by
$chars was never initialized. Although not strictly required by PHP, it is generally a good practice to add $chars = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
1120
                        . chr(131)
1121
                        . chr(138)
1122
                        . chr(142)
1123
                        . chr(154)
1124
                        . chr(158)
1125
                        . chr(159)
1126
                        . chr(162)
1127
                        . chr(165)
1128
                        . chr(181)
1129
                        . chr(192)
1130
                        . chr(193)
1131
                        . chr(194)
1132
                        . chr(195)
1133
                        . chr(196)
1134
                        . chr(197)
1135
                        . chr(199)
1136
                        . chr(200)
1137
                        . chr(201)
1138
                        . chr(202)
1139
                        . chr(203)
1140
                        . chr(204)
1141
                        . chr(205)
1142
                        . chr(206)
1143
                        . chr(207)
1144
                        . chr(209)
1145
                        . chr(210)
1146
                        . chr(211)
1147
                        . chr(212)
1148
                        . chr(213)
1149
                        . chr(214)
1150
                        . chr(216)
1151
                        . chr(217)
1152
                        . chr(218)
1153
                        . chr(219)
1154
                        . chr(220)
1155
                        . chr(221)
1156
                        . chr(224)
1157
                        . chr(225)
1158
                        . chr(226)
1159
                        . chr(227)
1160
                        . chr(228)
1161
                        . chr(229)
1162
                        . chr(231)
1163
                        . chr(232)
1164
                        . chr(233)
1165
                        . chr(234)
1166
                        . chr(235)
1167
                        . chr(236)
1168
                        . chr(237)
1169
                        . chr(238)
1170
                        . chr(239)
1171
                        . chr(241)
1172
                        . chr(242)
1173
                        . chr(243)
1174
                        . chr(244)
1175
                        . chr(245)
1176
                        . chr(246)
1177
                        . chr(248)
1178
                        . chr(249)
1179
                        . chr(250)
1180
                        . chr(251)
1181
                        . chr(252)
1182
                        . chr(253)
1183
                        . chr(255);
1184
    $chars['out'] = 'EfSZszYcYuAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy';
1185
    if (LexikonUtility::isUtf8($string)) {
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

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

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

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

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

Loading history...
1186
        $invalid_latin_chars = array(
1187
                chr(197) . chr(146)            => 'OE',
1188
                chr(197) . chr(147)            => 'oe',
1189
                chr(197) . chr(160)            => 'S',
1190
                chr(197) . chr(189)            => 'Z',
1191
                chr(197) . chr(161)            => 's',
1192
                chr(197) . chr(190)            => 'z',
1193
                chr(226) . chr(130) . chr(172) => 'E'
1194
            );
1195
        $string              = utf8_decode(strtr($string, $invalid_latin_chars));
1196
    }
1197
    $string              = strtr($string, $chars['in'], $chars['out']);
1198
    $double_chars['in']  = array(
0 ignored issues
show
Coding Style Comprehensibility introduced by
$double_chars was never initialized. Although not strictly required by PHP, it is generally a good practice to add $double_chars = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
1199
            chr(140),
1200
            chr(156),
1201
            chr(198),
1202
            chr(208),
1203
            chr(222),
1204
            chr(223),
1205
            chr(230),
1206
            chr(240),
1207
            chr(254)
1208
        );
1209
    $double_chars['out'] = array('OE', 'oe', 'AE', 'DH', 'TH', 'ss', 'ae', 'dh', 'th');
1210
    $string              = str_replace($double_chars['in'], $double_chars['out'], $string);
1211
1212
    return $string;
1213
}
1214
1215
    /**
1216
     * @param $Str
1217
     * @return bool
1218
     */
1219
public static function isUtf8($Str)
1220
{ # by bmorel at ssi dot fr
1221
        for ($i = 0, $iMax = strlen($Str); $i < $iMax; ++$i) {
1222
            if (ord($Str[$i]) < 0x80) {
1223
                continue;
1224
            } # 0bbbbbbb
1225
            elseif ((ord($Str[$i]) & 0xE0) == 0xC0) {
1226
                $n = 1;
1227
            } # 110bbbbb
1228
            elseif ((ord($Str[$i]) & 0xF0) == 0xE0) {
1229
                $n = 2;
1230
            } # 1110bbbb
1231
            elseif ((ord($Str[$i]) & 0xF8) == 0xF0) {
1232
                $n = 3;
1233
            } # 11110bbb
1234
            elseif ((ord($Str[$i]) & 0xFC) == 0xF8) {
1235
                $n = 4;
1236
            } # 111110bb
1237
            elseif ((ord($Str[$i]) & 0xFE) == 0xFC) {
1238
                $n = 5;
1239
            } # 1111110b
1240
            else {
1241
                return false;
1242
            } # Does not match any model
1243
            for ($j = 0; $j < $n; ++$j) { # n bytes matching 10bbbbbb follow ?
1244
                if ((++$i == strlen($Str)) || ((ord($Str[$i]) & 0xC0) != 0x80)) {
1245
                    return false;
1246
                }
1247
            }
1248
        }
1249
1250
    return true;
1251
}
1252
1253
    /**
1254
     * @param $field
1255
     * @return mixed|string
1256
     */
1257
public static function sanitizeFieldName($field)
1258
{
1259
    $field = LexikonUtility::removeAccents($field);
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

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

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

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

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

Loading history...
1260
    $field = strtolower($field);
1261
    $field = preg_replace('/&.+?;/', '', $field); // kill entities
1262
        $field = preg_replace('/[^a-z0-9 _-]/', '', $field);
1263
    $field = preg_replace('/\s+/', ' ', $field);
1264
    $field = str_replace(' ', '-', $field);
1265
    $field = preg_replace('|-+|', '-', $field);
1266
    $field = trim($field, '-');
1267
1268
    return $field;
1269
}
1270
1271
    // Verify that a term does not exist for submissions and requests (both user frontend and admin backend)
1272
    /**
1273
     * @param $term
1274
     * @param $table
1275
     * @return mixed
1276
     */
1277
public static function isTermPresent($term, $table)
1278
{
1279
    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...
1280
    $sql    = sprintf('SELECT COUNT(*) FROM %s WHERE term = %s', $table, $xoopsDB->quoteString(addslashes($term)));
1281
    $result = $xoopsDB->query($sql);
1282
    list($count) = $xoopsDB->fetchRow($result);
1283
1284
    return $count;
1285
}
1286
1287
    // Static method to get author data block authors - from AMS
1288
    /**
1289
     * @param  int    $limit
1290
     * @param  string $sort
1291
     * @param  string $name
1292
     * @param  string $compute_method
1293
     * @return array|bool
1294
     */
1295
public static function getBlockAuthors($limit = 5, $sort = 'count', $name = 'uname', $compute_method = 'average')
1296
{
1297
    $limit = (int)$limit;
1298
    if ($name !== 'uname') {
1299
        $name = 'name';
1300
    } //making sure that there is not invalid information in field value
1301
        $ret = array();
1302
    $db  = XoopsDatabaseFactory::getDatabaseConnection();
1303
    if ($sort === 'count') {
1304
        $sql = 'SELECT u.' . $name . ' AS name, u.uid , count( n.entryID ) AS count
1305
              FROM ' . $db->prefix('users') . ' u, ' . $db->prefix('lxentries') . ' n
1306
              WHERE u.uid = n.uid
1307
              AND n.datesub > 0 AND n.datesub <= ' . time() . ' AND n.offline = 0 AND n.submit = 0
1308
              GROUP BY u.uid ORDER BY count DESC';
1309
    } elseif ($sort === 'read') {
1310
        if ($compute_method === 'average') {
1311
            $compute = 'sum( n.counter ) / count( n.entryID )';
1312
        } else {
1313
            $compute = 'sum( n.counter )';
1314
        }
1315
        $sql = 'SELECT u.' . $name . " AS name, u.uid , $compute AS count
1316
              FROM " . $db->prefix('users') . ' u, ' . $db->prefix('lxentries') . ' n
1317
              WHERE u.uid = n.uid
1318
              AND n.datesub > 0 AND n.datesub <= ' . time() . ' AND n.offline = 0 AND n.submit = 0
1319
              GROUP BY u.uid ORDER BY count DESC';
1320
    }
1321
    if (!$result = $db->query($sql, $limit)) {
0 ignored issues
show
Bug introduced by
The variable $sql does not seem to be defined for all execution paths leading up to this point.

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

Let’s take a look at an example:

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

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

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

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

Available Fixes

  1. Check for existence of the variable explicitly:

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

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

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
1322
        return false;
1323
    }
1324
1325
    while ($row = $db->fetchArray($result)) {
1326
        if ($name === 'name' && $row['name'] == '') {
1327
            $row['name'] = XoopsUser::getUnameFromId($row['uid']);
1328
        }
1329
        $row['count'] = round($row['count'], 0);
1330
        $ret[]        = $row;
1331
    }
1332
1333
    return $ret;
1334
}
1335
1336
    /**
1337
     * close all unclosed xhtml tags *Test*
1338
     *
1339
     * @param  string $html
1340
     * @return string
1341
     * @author Milian Wolff <mail -at- milianw.de>
1342
     */
1343
public static function closeTags2($html)
1344
{
1345
    // put all opened tags into an array
1346
        preg_match_all('#<([a-z]+)( .*)?(?!/)>#iU', $html, $result);
1347
    $openedtags = $result[1];
1348
1349
        // put all closed tags into an array
1350
        preg_match_all('#</([a-z]+)>#iU', $html, $result);
1351
    $closedtags = $result[1];
1352
    $len_opened = count($openedtags);
1353
        // all tags are closed
1354
        if (count($closedtags) == $len_opened) {
1355
            return $html;
1356
        }
1357
1358
    $openedtags = array_reverse($openedtags);
1359
        // close tags
1360
        for ($i = 0; $i < $len_opened; ++$i) {
1361
            if (!in_array($openedtags[$i], $closedtags)) {
1362
                $html .= '</' . $openedtags[$i] . '>';
1363
            } else {
1364
                unset($closedtags[array_search($openedtags[$i], $closedtags)]);
1365
            }
1366
        }
1367
1368
    return $html;
1369
}
1370
1371
    /**
1372
     * @author   Monte Ohrt <monte at ohrt dot com>, modified by Amos Robinson
1373
     *           <amos dot robinson at gmail dot com>
1374
     * @param $string
1375
     * @return string
1376
     */
1377
public static function closeTags($string)
1378
{
1379
    // match opened tags
1380
        if (preg_match_all('/<([a-z\:\-]+)[^\/]>/', $string, $start_tags)) {
1381
            $start_tags = $start_tags[1];
1382
            // match closed tags
1383
            if (preg_match_all('/<\/([a-z]+)>/', $string, $end_tags)) {
1384
                $complete_tags = array();
1385
                $end_tags      = $end_tags[1];
1386
1387
                foreach ($start_tags as $key => $val) {
1388
                    $posb = array_search($val, $end_tags);
1389
                    if (is_int($posb)) {
1390
                        unset($end_tags[$posb]);
1391
                    } else {
1392
                        $complete_tags[] = $val;
1393
                    }
1394
                }
1395
            } else {
1396
                $complete_tags = $start_tags;
1397
            }
1398
1399
            $complete_tags = array_reverse($complete_tags);
1400
            for ($i = 0, $iMax = count($complete_tags); $i < $iMax; ++$i) {
1401
                $string .= '</' . $complete_tags[$i] . '>';
1402
            }
1403
        }
1404
1405
    return $string;
1406
}
1407
1408
    /**
1409
     * Smarty plugin
1410
     * @package    Smarty
1411
     * @subpackage plugins
1412
     */
1413
    /**
1414
     * Smarty truncate_tagsafe modifier plugin
1415
     *
1416
     * Type:     modifier<br>
1417
     * Name:     truncate_tagsafe<br>
1418
     * Purpose:  Truncate a string to a certain length if necessary,
1419
     *           optionally splitting in the middle of a word, and
1420
     *           appending the $etc string or inserting $etc into the middle.
1421
     *           Makes sure no tags are left half-open or half-closed (e.g. "Banana in a <a...")
1422
     * @author   Monte Ohrt <monte at ohrt dot com>, modified by Amos Robinson
1423
     *           <amos dot robinson at gmail dot com>
1424
     * used in Block entries_scrolling.php
1425
     * @param               $string
1426
     * @param  int          $length
1427
     * @param  string       $etc
1428
     * @param  bool         $break_words
1429
     * @return mixed|string
1430
     */
1431
public static function truncateTagSafe($string, $length = 80, $etc = '...', $break_words = false)
1432
{
1433
    if ($length == 0) {
1434
        return '';
1435
    }
1436
    if (strlen($string) > $length) {
1437
        $length -= strlen($etc);
1438
        if (!$break_words) {
1439
            $string = preg_replace('/\s+?(\S+)?$/', '', substr($string, 0, $length + 1));
1440
            $string = preg_replace('/<[^>]*$/', '', $string);
1441
            $string = LexikonUtility::closeTags($string);
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

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

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

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

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

Loading history...
1442
        }
1443
1444
        return $string . $etc;
1445
    } else {
1446
        return $string;
1447
    }
1448
}
1449
1450
    /**
1451
     * @return array
1452
     */
1453
public static function getSummary()
1454
{
1455
    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...
1456
1457
    $summary = array();
1458
1459
    $result01 = $xoopsDB->query('SELECT COUNT(*)
1460
                                   FROM ' . $xoopsDB->prefix('lxcategories') . ' ');
1461
    list($totalcategories) = $xoopsDB->fetchRow($result01);
1462
1463
    $result02 = $xoopsDB->query('SELECT COUNT(*)
1464
                                   FROM ' . $xoopsDB->prefix('lxentries') . '
1465
                                   WHERE submit = 0');
1466
    list($totalpublished) = $xoopsDB->fetchRow($result02);
1467
1468
    $result03 = $xoopsDB->query('SELECT COUNT(*)
1469
                                   FROM ' . $xoopsDB->prefix('lxentries') . "
1470
                                   WHERE submit = '1' AND request = '0' ");
1471
    list($totalsubmitted) = $xoopsDB->fetchRow($result03);
1472
1473
    $result04 = $xoopsDB->query('SELECT COUNT(*)
1474
                                   FROM ' . $xoopsDB->prefix('lxentries') . "
1475
                                   WHERE submit = '1' AND request = '1' ");
1476
    list($totalrequested) = $xoopsDB->fetchRow($result04);
1477
1478
        // Recuperer les valeurs dans la base de donnees
1479
1480
        $summary['publishedEntries']    = $totalpublished ?: '0';
1481
    $summary['availableCategories'] = $totalcategories ?: '0';
1482
    $summary['submittedEntries']    = $totalsubmitted ?: '0';
1483
    $summary['requestedEntries']    = $totalrequested ?: '0';
1484
1485
        //print_r($summary);
1486
        return $summary;
1487
} // end function
1488
}
1489