Issues (167)

Security Analysis    not enabled

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

  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.
  Regex Injection
Regex Injection enables an attacker to execute arbitrary code in your PHP process.
  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.
  Response Splitting
Response Splitting can be used to send arbitrary responses.
  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.
  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.
  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.
  Code Injection
Code Injection enables an attacker to execute arbitrary code on the server.
  Variable Injection
Variable Injection enables an attacker to overwrite program variables with custom data, and can lead to further vulnerabilities.
  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.
  Other Vulnerability
This category comprises other attack vectors such as manipulating the PHP runtime, loading custom extensions, freezing the runtime, or similar.
  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.
  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.
  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.
  Header Injection
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/Common/SysUtility.php (4 issues)

1
<?php
2
3
declare(strict_types=1);
4
5
namespace XoopsModules\Tdmdownloads\Common;
6
7
/*
8
 Utility Class Definition
9
10
 You may not change or alter any portion of this comment or credits of
11
 supporting developers from this source code or any supporting source code
12
 which is considered copyrighted (c) material of the original comment or credit
13
 authors.
14
15
 This program is distributed in the hope that it will be useful, but
16
 WITHOUT ANY WARRANTY; without even the implied warranty of
17
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
18
 */
19
20
/**
21
 * @license      https://www.fsf.org/copyleft/gpl.html GNU public license
22
 * @copyright    https://xoops.org 2000-2020 &copy; XOOPS Project
23
 * @author       ZySpec <[email protected]>
24
 * @author       Mamba <[email protected]>
25
 */
26
27
use Xmf\Request;
28
use XoopsFormEditor;
29
use XoopsModules\Tdmdownloads\{
30
    Helper
31
};
32
33
/**
34
 * Class SysUtility
35
 */
36
class SysUtility
37
{
38
    use VersionChecks;    //checkVerXoops, checkVerPhp Traits
0 ignored issues
show
The trait XoopsModules\Tdmdownloads\Common\VersionChecks requires some properties which are not provided by XoopsModules\Tdmdownloads\Common\SysUtility: $tag_name, $prerelease
Loading history...
39
    use ServerStats;    // getServerStats Trait
40
    use FilesManagement;    // Files Management Trait
41
    //use ModuleStats;    // ModuleStats Trait
42
43
    //--------------- Common module methods -----------------------------
44
45
    /**
46
     * Access the only instance of this class
47
     */
48
    public static function getInstance(): self
49
    {
50
        static $instance;
51
        if (null === $instance) {
52
            $instance = new static();
53
        }
54
55
        return $instance;
56
    }
57
58
    public static function selectSorting(string $text, string $form_sort): string
59
    {
60
        global $start, $order, $sort;
61
62
        $selectView   = '';
0 ignored issues
show
The assignment to $selectView is dead and can be removed.
Loading history...
63
        $helper        = Helper::getInstance();
64
65
        //$pathModIcon16 = XOOPS_URL . '/modules/' . $moduleDirName . '/' . $helper->getConfig('modicons16');
66
        $pathModIcon16 = $helper->url($helper->getModule()->getInfo('modicons16'));
0 ignored issues
show
It seems like $helper->getModule()->getInfo('modicons16') can also be of type array; however, parameter $url of Xmf\Module\Helper\GenericHelper::url() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

66
        $pathModIcon16 = $helper->url(/** @scrutinizer ignore-type */ $helper->getModule()->getInfo('modicons16'));
Loading history...
67
68
        $selectView = '<form name="form_switch" id="form_switch" action="' . Request::getString('REQUEST_URI', '', 'SERVER') . '" method="post"><span style="font-weight: bold;">' . $text . '</span>';
69
        //$sorts =  $sort ==  'asc' ? 'desc' : 'asc';
70
        if ($form_sort == $sort) {
71
            $sel1 = 'asc' === $order ? 'selasc.png' : 'asc.png';
72
            $sel2 = 'desc' === $order ? 'seldesc.png' : 'desc.png';
73
        } else {
74
            $sel1 = 'asc.png';
75
            $sel2 = 'desc.png';
76
        }
77
        $selectView .= '  <a href="' . Request::getString('SCRIPT_NAME', '', 'SERVER') . '?start=' . $start . '&sort=' . $form_sort . '&order=asc"><img src="' . $pathModIcon16 . '/' . $sel1 . '" title="ASC" alt="ASC"></a>';
78
        $selectView .= '<a href="' . Request::getString('SCRIPT_NAME', '', 'SERVER') . '?start=' . $start . '&sort=' . $form_sort . '&order=desc"><img src="' . $pathModIcon16 . '/' . $sel2 . '" title="DESC" alt="DESC"></a>';
79
        $selectView .= '</form>';
80
81
        return $selectView;
82
    }
83
84
    /***************Blocks***************/
85
    public static function blockAddCatSelect(array $cats): string
86
    {
87
        $catSql = '';
88
        if (!empty($cats)) {
89
            $catSql = '(' . \current($cats);
90
            \array_shift($cats);
91
            foreach ($cats as $cat) {
92
                $catSql .= ',' . $cat;
93
            }
94
            $catSql .= ')';
95
        }
96
97
        return $catSql;
98
    }
99
100
    public static function metaKeywords(string $content): void
101
    {
102
        global $xoopsTpl, $xoTheme;
103
        $myts    = \MyTextSanitizer::getInstance();
104
        $content = $myts->undoHtmlSpecialChars($myts->displayTarea($content));
105
        if (\is_object($xoTheme)) {
106
            $xoTheme->addMeta('meta', 'keywords', \strip_tags($content));
107
        } else {    // Compatibility for old Xoops versions
108
            $xoopsTpl->assign('xoops_metaKeywords', \strip_tags($content));
109
        }
110
    }
111
112
    public static function metaDescription(string $content): void
113
    {
114
        global $xoopsTpl, $xoTheme;
115
        $myts    = \MyTextSanitizer::getInstance();
116
        $content = $myts->undoHtmlSpecialChars($myts->displayTarea($content));
117
        if (\is_object($xoTheme)) {
118
            $xoTheme->addMeta('meta', 'description', \strip_tags($content));
119
        } else {    // Compatibility for old Xoops versions
120
            $xoopsTpl->assign('xoops_metaDescription', \strip_tags($content));
121
        }
122
    }
123
124
    public static function enumerate(string $tableName, string $columnName): ?array
125
    {
126
        $table = $GLOBALS['xoopsDB']->prefix($tableName);
127
128
        //    $result = $GLOBALS['xoopsDB']->query("SELECT COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS
129
        //        WHERE TABLE_NAME = '" . $table . "' AND COLUMN_NAME = '" . $columnName . "'")
130
        //    || exit ($GLOBALS['xoopsDB']->error());
131
132
        $sql    = 'SELECT COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = "' . $table . '" AND COLUMN_NAME = "' . $columnName . '"';
133
        $result = $GLOBALS['xoopsDB']->query($sql);
134
        if (!$result instanceof \mysqli_result) {
135
            //            trigger_error($GLOBALS['xoopsDB']->error());
136
            $logger = \XoopsLogger::getInstance();
137
            $logger->handleError(\E_USER_WARNING, $sql, __FILE__, __LINE__);
138
            return null;
139
        }
140
141
        $row      = $GLOBALS['xoopsDB']->fetchBoth($result);
142
        $enumList = \explode(',', \str_replace("'", '', \mb_substr($row['COLUMN_TYPE'], 5, -6)));
143
        return $enumList;
144
    }
145
146
    /**
147
     * Clone a record in a dB
148
     *
149
     * @TODO need to exit more gracefully on error. Should throw/trigger error and then return false
150
     *
151
     * @param string $tableName name of dB table (without prefix)
152
     * @param string $idField   name of field (column) in dB table
153
     * @param int    $id        item id to clone
154
     */
155
    public static function cloneRecord(string $tableName, string $idField, int $id): ?int
156
    {
157
        $newId = null;
0 ignored issues
show
The assignment to $newId is dead and can be removed.
Loading history...
158
        $tempTable = '';
159
        $table = $GLOBALS['xoopsDB']->prefix($tableName);
160
        // copy content of the record you wish to clone
161
        $sql       = "SELECT * FROM $table WHERE $idField='" . $id . "' ";
162
        $result = $GLOBALS['xoopsDB']->query($sql);
163
        if ($result instanceof \mysqli_result) {
164
            $tempTable = $GLOBALS['xoopsDB']->fetchArray($result, \MYSQLI_ASSOC);
165
        }
166
167
         if (!$tempTable) {
168
            trigger_error($GLOBALS['xoopsDB']->error());
169
        }
170
        // set the auto-incremented id's value to blank.
171
        unset($tempTable[$idField]);
172
        // insert cloned copy of the original  record
173
        $sql    = "INSERT INTO $table (" . \implode(', ', \array_keys($tempTable)) . ") VALUES ('" . \implode("', '", $tempTable) . "')";
174
        $result = $GLOBALS['xoopsDB']->queryF($sql);
175
        if (!$result) {
176
            trigger_error($GLOBALS['xoopsDB']->error());
177
        }
178
        // Return the new id
179
        $newId = $GLOBALS['xoopsDB']->getInsertId();
180
        return $newId;
181
    }
182
183
    /**
184
     * truncateHtml can truncate a string up to a number of characters while preserving whole words and HTML tags
185
     * www.gsdesign.ro/blog/cut-html-string-without-breaking-the-tags
186
     * www.cakephp.org
187
     *
188
     * @TODO: Refactor to consider HTML5 & void (self-closing) elements
189
     * @TODO: Consider using https://github.com/jlgrall/truncateHTML/blob/master/truncateHTML.php
190
     *
191
     * @param string   $text         String to truncate.
192
     * @param int|null $length       Length of returned string, including ellipsis.
193
     * @param string   $ending       Ending to be appended to the trimmed string.
194
     * @param bool     $exact        If false, $text will not be cut mid-word
195
     * @param bool     $considerHtml If true, HTML tags would be handled correctly
196
     *
197
     * @return string Trimmed string.
198
     */
199
    public static function truncateHtml(
200
        string $text,
201
        ?int $length = 100,
202
        string $ending = '...',
203
        bool $exact = false,
204
        bool $considerHtml = true
205
    ): string {
206
        $openTags = [];
207
        if ($considerHtml) {
208
            // if the plain text is shorter than the maximum length, return the whole text
209
            if (\mb_strlen(\preg_replace('/<.*?' . '>/', '', $text)) <= $length) {
210
                return $text;
211
            }
212
            // splits all html-tags to scanable lines
213
            \preg_match_all('/(<.+?' . '>)?([^<>]*)/s', $text, $lines, \PREG_SET_ORDER);
214
            $totalLength = \mb_strlen($ending);
215
            //$openTags    = [];
216
            $truncate = '';
217
            foreach ($lines as $lineMatchings) {
218
                // if there is any html-tag in this line, handle it and add it (uncounted) to the output
219
                if (!empty($lineMatchings[1])) {
220
                    // if it's an "empty element" with or without xhtml-conform closing slash
221
                    if (\preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $lineMatchings[1])) {
222
                        // do nothing
223
                        // if tag is a closing tag
224
                    } elseif (\preg_match('/^<\s*\/(\S+?)\s*>$/s', $lineMatchings[1], $tagMatchings)) {
225
                        // delete tag from $openTags list
226
                        $pos = \array_search($tagMatchings[1], $openTags, true);
227
                        if (false !== $pos) {
228
                            unset($openTags[$pos]);
229
                        }
230
                        // if tag is an opening tag
231
                    } elseif (\preg_match('/^<\s*([^\s>!]+).*?' . '>$/s', $lineMatchings[1], $tagMatchings)) {
232
                        // add tag to the beginning of $openTags list
233
                        \array_unshift($openTags, \mb_strtolower($tagMatchings[1]));
234
                    }
235
                    // add html-tag to $truncate'd text
236
                    $truncate .= $lineMatchings[1];
237
                }
238
                // calculate the length of the plain text part of the line; handle entities as one character
239
                $contentLength = \mb_strlen(\preg_replace('/&[0-9a-z]{2,8};|&#\d{1,7};|[0-9a-f]{1,6};/i', ' ', $lineMatchings[2]));
240
                if ($totalLength + $contentLength > $length) {
241
                    // the number of characters which are left
242
                    $left            = $length - $totalLength;
243
                    $entitiesLength = 0;
244
                    // search for html entities
245
                    if (\preg_match_all('/&[0-9a-z]{2,8};|&#\d{1,7};|[0-9a-f]{1,6};/i', $lineMatchings[2], $entities, \PREG_OFFSET_CAPTURE)) {
246
                        // calculate the real length of all entities in the legal range
247
                        foreach ($entities[0] as $entity) {
248
                            if ($left >= $entity[1] + 1 - $entitiesLength) {
249
                                $left--;
250
                                $entitiesLength += \mb_strlen($entity[0]);
251
                            } else {
252
                                // no more characters left
253
                                break;
254
                            }
255
                        }
256
                    }
257
                    $truncate .= \mb_substr($lineMatchings[2], 0, $left + $entitiesLength);
258
                    // maximum length is reached, so get off the loop
259
                    break;
260
                }
261
                $truncate     .= $lineMatchings[2];
262
                $totalLength += $contentLength;
263
264
                // if the maximum length is reached, get off the loop
265
                if ($totalLength >= $length) {
266
                    break;
267
                }
268
            }
269
        } else {
270
            if (\mb_strlen($text) <= $length) {
271
                return $text;
272
            }
273
            $truncate = \mb_substr($text, 0, $length - \mb_strlen($ending));
274
        }
275
        // if the words shouldn't be cut in the middle...
276
        if (!$exact) {
277
            // ...search the last occurance of a space...
278
            $spacepos = \mb_strrpos($truncate, ' ');
279
            if (isset($spacepos)) {
280
                // ...and cut the text in this position
281
                $truncate = \mb_substr($truncate, 0, $spacepos);
282
            }
283
        }
284
        // add the defined ending to the text
285
        $truncate .= $ending;
286
        if ($considerHtml) {
287
            // close all unclosed html-tags
288
            foreach ($openTags as $tag) {
289
                $truncate .= '</' . $tag . '>';
290
            }
291
        }
292
293
        return $truncate;
294
    }
295
296
    /**
297
     * Get correct text editor based on user rights
298
     *
299
     * @return \XoopsFormDhtmlTextArea|\XoopsFormEditor
300
     */
301
    public static function getEditor(?\Xmf\Module\Helper $helper = null, ?array $options = null): ?\XoopsFormTextArea
302
    {
303
        $descEditor = null;
304
305
        /** @var Helper $helper */
306
        if (null === $options) {
307
            $options           = [];
308
            $options['name']   = 'Editor';
309
            $options['value']  = 'Editor';
310
            $options['rows']   = 10;
311
            $options['cols']   = '100%';
312
            $options['width']  = '100%';
313
            $options['height'] = '400px';
314
        }
315
316
        if (null === $helper) {
317
            $helper = Helper::getInstance();
318
        }
319
        $isAdmin = $helper->isUserAdmin();
320
321
        if (\class_exists('XoopsFormEditor')) {
322
            if ($isAdmin) {
323
                $descEditor = new \XoopsFormEditor(\ucfirst($options['name']), $helper->getConfig('editorAdmin'), $options, false, 'textarea');
324
            } else {
325
                $descEditor = new \XoopsFormEditor(\ucfirst($options['name']), $helper->getConfig('editorUser'), $options, false, 'textarea');
326
            }
327
        } else {
328
            $descEditor = new \XoopsFormDhtmlTextArea(\ucfirst($options['name']), $options['name'], $options['value']);
329
        }
330
331
        //        $form->addElement($descEditor);
332
333
        return $descEditor;
334
    }
335
336
    /**
337
     * Check if column in dB table exists
338
     *
339
     * @param string $fieldname name of dB table field
340
     * @param string $table     name of dB table (including prefix)
341
     *
342
     * @return bool true if table exists
343
     * @deprecated
344
     */
345
    public static function fieldExists(string $fieldname, string $table): bool
346
    {
347
        $trace = \debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, 1);
348
        \trigger_error(__METHOD__ . " is deprecated, use Xmf\Database\Tables instead - instantiated from {$trace[0]['file']} line {$trace[0]['line']},");
349
350
        $result = $GLOBALS['xoopsDB']->queryF("SHOW COLUMNS FROM   $table LIKE '$fieldname'");
351
        return ($GLOBALS['xoopsDB']->getRowsNum($result) > 0);
352
    }
353
354
    /**
355
     * Function responsible for checking if a directory exists, we can also write in and create an index.html file
356
     *
357
     * @param string $folder The full path of the directory to check
358
     */
359
    public static function prepareFolder(string $folder): void
360
    {
361
        try {
362
            if (!@\mkdir($folder) && !\is_dir($folder)) {
363
                throw new \RuntimeException(\sprintf('Unable to create the %s directory', $folder));
364
            }
365
            file_put_contents($folder . '/index.html', '<script>history.go(-1);</script>');
366
        } catch (\Exception $e) {
367
            echo 'Caught exception: ', $e->getMessage(), "\n", '<br>';
368
        }
369
    }
370
371
    /**
372
     * Check if dB table exists
373
     *
374
     * @param string $tablename dB tablename with prefix
375
     * @return bool true if table exists
376
     */
377
    public static function tableExists(string $tablename): bool
378
    {
379
        $trace = \debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, 1);
380
        \trigger_error(__FUNCTION__ . " is deprecated, called from {$trace[0]['file']} line {$trace[0]['line']}");
381
        $GLOBALS['xoopsLogger']->addDeprecated(
382
            \basename(\dirname(__DIR__, 2)) . ' Module: ' . __FUNCTION__ . ' function is deprecated, please use Xmf\Database\Tables method(s) instead.' . " Called from {$trace[0]['file']}line {$trace[0]['line']}"
383
        );
384
        $result = $GLOBALS['xoopsDB']->queryF("SHOW TABLES LIKE '$tablename'");
385
386
        return $GLOBALS['xoopsDB']->getRowsNum($result) > 0;
387
    }
388
389
    /**
390
     * Add a field to a mysql table
391
     *
392
     * @return bool|\mysqli_result
393
     */
394
    public static function addField(string $field, string $table)
395
    {
396
        global $xoopsDB;
397
        return $xoopsDB->queryF('ALTER TABLE ' . $table . " ADD $field;");
398
    }
399
}