SysUtility::getEditor()   A
last analyzed

Complexity

Conditions 5
Paths 12

Size

Total Lines 34
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 20
c 1
b 0
f 0
nc 12
nop 2
dl 0
loc 34
rs 9.2888
1
<?php declare(strict_types=1);
2
3
namespace XoopsModules\Xoopsfaq\Common;
4
5
/*
6
 Utility Class Definition
7
8
 You may not change or alter any portion of this comment or credits of
9
 supporting developers from this source code or any supporting source code
10
 which is considered copyrighted (c) material of the original comment or credit
11
 authors.
12
13
 This program is distributed in the hope that it will be useful, but
14
 WITHOUT ANY WARRANTY; without even the implied warranty of
15
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
16
 */
17
18
/**
19
 * @license      GNU GPL 2.0 or later (https://www.gnu.org/licenses/gpl-2.0.html)
20
 * @copyright    https://xoops.org 2000-2020 &copy; XOOPS Project
21
 * @author       ZySpec <[email protected]>
22
 * @author       Mamba <[email protected]>
23
 */
24
25
use Xmf\Request;
26
use XoopsModules\Xoopsfaq\{
27
    Helper
28
};
29
30
/**
31
 * Class SysUtility
32
 */
33
class SysUtility
34
{
35
    use VersionChecks;
0 ignored issues
show
introduced by
The trait XoopsModules\Xoopsfaq\Common\VersionChecks requires some properties which are not provided by XoopsModules\Xoopsfaq\Common\SysUtility: $tag_name, $prerelease
Loading history...
36
37
    //checkVerXoops, checkVerPhp Traits
38
39
    use ServerStats;
40
41
    // getServerStats Trait
42
43
    use FilesManagement;
44
45
    // Files Management Trait
46
    //use ModuleStats;    // ModuleStats Trait
47
48
    //--------------- Common module methods -----------------------------
49
50
    /**
51
     * Access the only instance of this class
52
     */
53
    public static function getInstance(): self
54
    {
55
        static $instance;
56
        if (null === $instance) {
57
            $instance = new static();
58
        }
59
60
        return $instance;
61
    }
62
63
    public static function selectSorting(string $text, string $form_sort): string
64
    {
65
        global $start, $order, $sort;
66
67
        $selectView = '';
0 ignored issues
show
Unused Code introduced by
The assignment to $selectView is dead and can be removed.
Loading history...
68
        $helper     = Helper::getInstance();
69
70
        //$pathModIcon16 = XOOPS_URL . '/modules/' . $moduleDirName . '/' . $helper->getConfig('modicons16');
71
        $pathModIcon16 = $helper->url(
72
            $helper->getModule()
0 ignored issues
show
Bug introduced by
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

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