Passed
Push — master ( eec3d3...7b6eed )
by Michael
02:45
created

SysUtility::selectSorting()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 24
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 15
nc 5
nop 2
dl 0
loc 24
rs 9.7666
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace XoopsModules\Xoopsheadline\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
 *
22
 * @license      https://www.fsf.org/copyleft/gpl.html GNU public license
23
 * @copyright    https://xoops.org 2000-2020 &copy; XOOPS Project
24
 * @author       ZySpec <[email protected]>
25
 * @author       Mamba <[email protected]>
26
 */
27
28
use Xmf\Request;
29
use XoopsFormEditor;
30
use XoopsModules\Xoopsheadline\{
31
    Helper
32
};
33
34
/**
35
 * Class SysUtility
36
 */
37
class SysUtility
38
{
39
    use VersionChecks;    //checkVerXoops, checkVerPhp Traits
0 ignored issues
show
introduced by
The trait XoopsModules\Xoopsheadline\Common\VersionChecks requires some properties which are not provided by XoopsModules\Xoopsheadline\Common\SysUtility: $tag_name, $prerelease
Loading history...
40
    use ServerStats;    // getServerStats Trait
41
    use FilesManagement;    // Files Management Trait
42
    //    use ModuleStats;    // ModuleStats Trait
43
44
    //--------------- Common module methods -----------------------------
45
46
    /**
47
     * Access the only instance of this class
48
     */
49
    public static function getInstance(): self
50
    {
51
        static $instance;
52
        if (null === $instance) {
53
            $instance = new static();
54
        }
55
56
        return $instance;
57
    }
58
59
    public static function selectSorting(string $text, string $form_sort): string
60
    {
61
        global $start, $order, $sort;
62
63
        $selectView   = '';
0 ignored issues
show
Unused Code introduced by
The assignment to $selectView is dead and can be removed.
Loading history...
64
        $helper        = Helper::getInstance();
65
66
        //$pathModIcon16 = XOOPS_URL . '/modules/' . $moduleDirName . '/' . $helper->getConfig('modicons16');
67
        $pathModIcon16 = $helper->url($helper->getModule()->getInfo('modicons16'));
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

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