Issues (102)

Security Analysis    no request data  

This project does not seem to handle request data directly as such no vulnerable execution paths were found.

  Cross-Site Scripting
Cross-Site Scripting enables an attacker to inject code into the response of a web-request that is viewed by other users. It can for example be used to bypass access controls, or even to take over other users' accounts.
  File Exposure
File Exposure allows an attacker to gain access to local files that he should not be able to access. These files can for example include database credentials, or other configuration files.
  File Manipulation
File Manipulation enables an attacker to write custom data to files. This potentially leads to injection of arbitrary code on the server.
  Object Injection
Object Injection enables an attacker to inject an object into PHP code, and can lead to arbitrary code execution, file exposure, or file manipulation attacks.
  Code Injection
Code Injection enables an attacker to execute arbitrary code on the server.
  Response Splitting
Response Splitting can be used to send arbitrary responses.
  File Inclusion
File Inclusion enables an attacker to inject custom files into PHP's file loading mechanism, either explicitly passed to include, or for example via PHP's auto-loading mechanism.
  Command Injection
Command Injection enables an attacker to inject a shell command that is execute with the privileges of the web-server. This can be used to expose sensitive data, or gain access of your server.
  SQL Injection
SQL Injection enables an attacker to execute arbitrary SQL code on your database server gaining access to user data, or manipulating user data.
  XPath Injection
XPath Injection enables an attacker to modify the parts of XML document that are read. If that XML document is for example used for authentication, this can lead to further vulnerabilities similar to SQL Injection.
  LDAP Injection
LDAP Injection enables an attacker to inject LDAP statements potentially granting permission to run unauthorized queries, or modify content inside the LDAP tree.
  Header Injection
  Other Vulnerability
This category comprises other attack vectors such as manipulating the PHP runtime, loading custom extensions, freezing the runtime, or similar.
  Regex Injection
Regex Injection enables an attacker to execute arbitrary code in your PHP process.
  XML Injection
XML Injection enables an attacker to read files on your local filesystem including configuration files, or can be abused to freeze your web-server process.
  Variable Injection
Variable Injection enables an attacker to overwrite program variables with custom data, and can lead to further vulnerabilities.
Unfortunately, the security analysis is currently not available for your project. If you are a non-commercial open-source project, please contact support to gain access.

class/utility.php (6 issues)

Upgrade to new PHP Analysis Engine

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

1
<?php namespace Xoopsmodules\randomquote;
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
 * Module: randomquote
14
 *
15
 * @category        Module
16
 * @package         randomquote
17
 * @author          XOOPS Development Team <[email protected]> - <https://xoops.org>
18
 * @copyright       {@link https://xoops.org/ XOOPS Project}
19
 * @license         GPL 2.0 or later
20
 * @link            https://xoops.org/
21
 * @since           1.0.0
22
 */
23
24
use Xmf\Request;
25
use Xoopsmodules\randomquote;
26
use Xoopsmodules\randomquote\common;
27
28
/**
29
 * Class Utility
30
 */
31
class Utility
32
{
33
34
    use common\VersionChecks; //checkVerXoops, checkVerPhp Traits
35
36
    use common\ServerStats; // getServerStats Trait
37
38
    use common\FilesManagement; // Files Management Trait
39
40
    //--------------- Custom module methods -----------------------------
41
42
    /**
43
     * @param $text
44
     * @param $form_sort
45
     * @return string
46
     */
47
    public static function selectSorting($text, $form_sort)
48
    {
49
        global $start, $order, $file_cat, $sort, $xoopsModule;
50
51
        $select_view   = '';
0 ignored issues
show
$select_view 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...
52
        $moduleDirName = basename(dirname(__DIR__));
53
54
        //        if (false !== ($helper = Xmf\Module\Helper::getHelper($moduleDirName))) {
55
        //        } else {
56
        //            $helper = Xmf\Module\Helper::getHelper('system');
57
        //        }
58
        $helper = randomquote\Helper::getInstance();
59
60
        $pathModIcon16 = XOOPS_URL . '/modules/' . $moduleDirName . '/' . $helper->getModule()->getInfo('modicons16');
61
62
        $select_view = '<form name="form_switch" id="form_switch" action="' . Request::getString('REQUEST_URI', '', 'SERVER') . '" method="post"><span style="font-weight: bold;">' . $text . '</span>';
63
        //$sorts =  $sort ==  'asc' ? 'desc' : 'asc';
64
        if ($form_sort == $sort) {
65
            $sel1 = 'asc' === $order ? 'selasc.png' : 'asc.png';
66
            $sel2 = 'desc' === $order ? 'seldesc.png' : 'desc.png';
67
        } else {
68
            $sel1 = 'asc.png';
69
            $sel2 = 'desc.png';
70
        }
71
        $select_view .= '  <a href="' . Request::getString('PHP_SELF', '', 'SERVER') . '?start=' . $start . '&sort=' . $form_sort . '&order=asc" /><img src="' . $pathModIcon16 . '/' . $sel1 . '" title="ASC" alt="ASC"></a>';
72
        $select_view .= '<a href="' . Request::getString('PHP_SELF', '', 'SERVER') . '?start=' . $start . '&sort=' . $form_sort . '&order=desc" /><img src="' . $pathModIcon16 . '/' . $sel2 . '" title="DESC" alt="DESC"></a>';
73
        $select_view .= '</form>';
74
75
        return $select_view;
76
    }
77
78
    /***************Blocks***************/
79
    /**
80
     * @param array $cats
81
     * @return string
82
     */
83
    public static function block_addCatSelect($cats)
84
    {
85
        $cat_sql = '';
86
        if (is_array($cats)) {
87
            $cat_sql = '(' . current($cats);
88
            array_shift($cats);
89
            foreach ($cats as $cat) {
90
                $cat_sql .= ',' . $cat;
91
            }
92
            $cat_sql .= ')';
93
        }
94
95
        return $cat_sql;
96
    }
97
98
    /**
99
     * @param $content
100
     */
101 View Code Duplication
    public static function meta_keywords($content)
0 ignored issues
show
This method seems to be duplicated in your project.

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

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

Loading history...
102
    {
103
        global $xoopsTpl, $xoTheme;
104
        $myts    = \MyTextSanitizer::getInstance();
105
        $content = $myts->undoHtmlSpecialChars($myts->displayTarea($content));
106
        if (null !== $xoTheme && is_object($xoTheme)) {
107
            $xoTheme->addMeta('meta', 'keywords', strip_tags($content));
108
        } else {    // Compatibility for old Xoops versions
109
            $xoopsTpl->assign('xoops_meta_keywords', strip_tags($content));
110
        }
111
    }
112
113
    /**
114
     * @param $content
115
     */
116 View Code Duplication
    public static function meta_description($content)
0 ignored issues
show
This method seems to be duplicated in your project.

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

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

Loading history...
117
    {
118
        global $xoopsTpl, $xoTheme;
119
        $myts    = \MyTextSanitizer::getInstance();
120
        $content = $myts->undoHtmlSpecialChars($myts->displayTarea($content));
121
        if (null !== $xoTheme && is_object($xoTheme)) {
122
            $xoTheme->addMeta('meta', 'description', strip_tags($content));
123
        } else {    // Compatibility for old Xoops versions
124
            $xoopsTpl->assign('xoops_meta_description', strip_tags($content));
125
        }
126
    }
127
128
    /**
129
     * @param $tableName
130
     * @param $columnName
131
     *
132
     * @return array
0 ignored issues
show
Should the return type not be null|array?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
133
     */
134
    public static function enumerate($tableName, $columnName)
135
    {
136
        $table = $GLOBALS['xoopsDB']->prefix($tableName);
137
138
        //    $result = $GLOBALS['xoopsDB']->query("SELECT COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS
139
        //        WHERE TABLE_NAME = '" . $table . "' AND COLUMN_NAME = '" . $columnName . "'")
140
        //    || exit ($GLOBALS['xoopsDB']->error());
141
142
        $sql    = 'SELECT COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = "' . $table . '" AND COLUMN_NAME = "' . $columnName . '"';
143
        $result = $GLOBALS['xoopsDB']->query($sql);
144
        if (!$result) {
145
            exit ($GLOBALS['xoopsDB']->error());
146
        }
147
148
        $row      = $GLOBALS['xoopsDB']->fetchBoth($result);
149
        $enumList = explode(',', str_replace("'", '', substr($row['COLUMN_TYPE'], 5, -6)));
150
        return $enumList;
151
    }
152
153
    /**
154
     * @param array|string $tableName
155
     * @param int          $id_field
156
     * @param int          $id
157
     *
158
     * @return mixed
159
     */
160
    public static function cloneRecord($tableName, $id_field, $id)
161
    {
162
        $new_id = false;
163
        $table  = $GLOBALS['xoopsDB']->prefix($tableName);
164
        // copy content of the record you wish to clone 
165
        $tempTable = $GLOBALS['xoopsDB']->fetchArray($GLOBALS['xoopsDB']->query("SELECT * FROM $table WHERE $id_field='$id' "), MYSQLI_ASSOC) or exit('Could not select record');
166
        // set the auto-incremented id's value to blank.
167
        unset($tempTable[$id_field]);
168
        // insert cloned copy of the original  record 
169
        $result = $GLOBALS['xoopsDB']->queryF("INSERT INTO $table (" . implode(', ', array_keys($tempTable)) . ") VALUES ('" . implode("', '", array_values($tempTable)) . "')") or exit ($GLOBALS['xoopsDB']->error());
170
171
        if ($result) {
172
            // Return the new id
173
            $new_id = $GLOBALS['xoopsDB']->getInsertId();
174
        }
175
        return $new_id;
176
    }
177
178
    /**
179
     * truncateHtml can truncate a string up to a number of characters while preserving whole words and HTML tags
180
     * www.gsdesign.ro/blog/cut-html-string-without-breaking-the-tags
181
     * www.cakephp.org
182
     *
183
     * @param string  $text         String to truncate.
184
     * @param integer $length       Length of returned string, including ellipsis.
185
     * @param string  $ending       Ending to be appended to the trimmed string.
186
     * @param boolean $exact        If false, $text will not be cut mid-word
187
     * @param boolean $considerHtml If true, HTML tags would be handled correctly
188
     *
189
     * @return string Trimmed string.
190
     */
191
    public static function truncateHtml($text, $length = 100, $ending = '...', $exact = false, $considerHtml = true)
192
    {
193
        if ($considerHtml) {
194
            // if the plain text is shorter than the maximum length, return the whole text
195
            if (strlen(preg_replace('/<.*?' . '>/', '', $text)) <= $length) {
196
                return $text;
197
            }
198
            // splits all html-tags to scanable lines
199
            preg_match_all('/(<.+?' . '>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
200
            $total_length = strlen($ending);
201
            $open_tags    = [];
202
            $truncate     = '';
203
            foreach ($lines as $line_matchings) {
0 ignored issues
show
The expression $lines of type null|array<integer,array<integer,string>> is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
204
                // if there is any html-tag in this line, handle it and add it (uncounted) to the output
205
                if (!empty($line_matchings[1])) {
206
                    // if it's an "empty element" with or without xhtml-conform closing slash
207
                    if (preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $line_matchings[1])) {
208
                        // do nothing
209
                        // if tag is a closing tag
210
                    } elseif (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $line_matchings[1], $tag_matchings)) {
211
                        // delete tag from $open_tags list
212
                        $pos = array_search($tag_matchings[1], $open_tags);
213
                        if (false !== $pos) {
214
                            unset($open_tags[$pos]);
215
                        }
216
                        // if tag is an opening tag
217
                    } elseif (preg_match('/^<\s*([^\s>!]+).*?' . '>$/s', $line_matchings[1], $tag_matchings)) {
218
                        // add tag to the beginning of $open_tags list
219
                        array_unshift($open_tags, strtolower($tag_matchings[1]));
220
                    }
221
                    // add html-tag to $truncate'd text
222
                    $truncate .= $line_matchings[1];
223
                }
224
                // calculate the length of the plain text part of the line; handle entities as one character
225
                $content_length = strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', ' ', $line_matchings[2]));
226
                if ($total_length + $content_length > $length) {
227
                    // the number of characters which are left
228
                    $left            = $length - $total_length;
229
                    $entities_length = 0;
230
                    // search for html entities
231
                    if (preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', $line_matchings[2], $entities, PREG_OFFSET_CAPTURE)) {
232
                        // calculate the real length of all entities in the legal range
233
                        foreach ($entities[0] as $entity) {
234
                            if ($entity[1] + 1 - $entities_length <= $left) {
235
                                $left--;
236
                                $entities_length += strlen($entity[0]);
237
                            } else {
238
                                // no more characters left
239
                                break;
240
                            }
241
                        }
242
                    }
243
                    $truncate .= substr($line_matchings[2], 0, $left + $entities_length);
244
                    // maximum lenght is reached, so get off the loop
245
                    break;
246
                } else {
247
                    $truncate     .= $line_matchings[2];
248
                    $total_length += $content_length;
249
                }
250
                // if the maximum length is reached, get off the loop
251
                if ($total_length >= $length) {
252
                    break;
253
                }
254
            }
255
        } else {
256
            if (strlen($text) <= $length) {
257
                return $text;
258
            } else {
259
                $truncate = substr($text, 0, $length - strlen($ending));
260
            }
261
        }
262
        // if the words shouldn't be cut in the middle...
263
        if (!$exact) {
264
            // ...search the last occurance of a space...
265
            $spacepos = strrpos($truncate, ' ');
266
            if (isset($spacepos)) {
267
                // ...and cut the text in this position
268
                $truncate = substr($truncate, 0, $spacepos);
269
            }
270
        }
271
        // add the defined ending to the text
272
        $truncate .= $ending;
273
        if ($considerHtml) {
274
            // close all unclosed html-tags
275
            foreach ($open_tags as $tag) {
0 ignored issues
show
The variable $open_tags 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...
276
                $truncate .= '</' . $tag . '>';
277
            }
278
        }
279
280
        return $truncate;
281
    }
282
}
283