Passed
Pull Request — master (#29)
by Michael
05:21 queued 02:44
created

SysUtility::addField()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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

64
        $pathModIcon16 = $helper->url(/** @scrutinizer ignore-type */ $helper->getModule()->getInfo('modicons16'));
Loading history...
65
66
        $selectView = '<form name="form_switch" id="form_switch" action="' . Request::getString('REQUEST_URI', '', 'SERVER') . '" method="post"><span style="font-weight: bold;">' . $text . '</span>';
67
        //$sorts =  $sort ==  'asc' ? 'desc' : 'asc';
68
        if ($form_sort == $sort) {
69
            $sel1 = 'asc' === $order ? 'selasc.png' : 'asc.png';
70
            $sel2 = 'desc' === $order ? 'seldesc.png' : 'desc.png';
71
        } else {
72
            $sel1 = 'asc.png';
73
            $sel2 = 'desc.png';
74
        }
75
        $selectView .= '  <a href="' . Request::getString('SCRIPT_NAME', '', 'SERVER') . '?start=' . $start . '&sort=' . $form_sort . '&order=asc"><img src="' . $pathModIcon16 . '/' . $sel1 . '" title="ASC" alt="ASC"></a>';
76
        $selectView .= '<a href="' . Request::getString('SCRIPT_NAME', '', 'SERVER') . '?start=' . $start . '&sort=' . $form_sort . '&order=desc"><img src="' . $pathModIcon16 . '/' . $sel2 . '" title="DESC" alt="DESC"></a>';
77
        $selectView .= '</form>';
78
79
        return $selectView;
80
    }
81
82
    /***************Blocks***************/
83
    public static function blockAddCatSelect(array $cats): string
84
    {
85
        $catSql = '';
86
        if (!empty($cats)) {
87
            $catSql = '(' . \current($cats);
88
            \array_shift($cats);
89
            foreach ($cats as $cat) {
90
                $catSql .= ',' . $cat;
91
            }
92
            $catSql .= ')';
93
        }
94
95
        return $catSql;
96
    }
97
98
    public static function metaKeywords(string $content): void
99
    {
100
        global $xoopsTpl, $xoTheme;
101
        $myts    = \MyTextSanitizer::getInstance();
102
        $content = $myts->undoHtmlSpecialChars($myts->displayTarea($content));
103
        if (\is_object($xoTheme)) {
104
            $xoTheme->addMeta('meta', 'keywords', \strip_tags($content));
105
        } else {    // Compatibility for old Xoops versions
106
            $xoopsTpl->assign('xoops_metaKeywords', \strip_tags($content));
107
        }
108
    }
109
110
    public static function metaDescription(string $content): void
111
    {
112
        global $xoopsTpl, $xoTheme;
113
        $myts    = \MyTextSanitizer::getInstance();
114
        $content = $myts->undoHtmlSpecialChars($myts->displayTarea($content));
115
        if (\is_object($xoTheme)) {
116
            $xoTheme->addMeta('meta', 'description', \strip_tags($content));
117
        } else {    // Compatibility for old Xoops versions
118
            $xoopsTpl->assign('xoops_metaDescription', \strip_tags($content));
119
        }
120
    }
121
122
    public static function enumerate(string $tableName, string $columnName): ?array
123
    {
124
        $table = $GLOBALS['xoopsDB']->prefix($tableName);
125
126
        //    $result = $GLOBALS['xoopsDB']->query("SELECT COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS
127
        //        WHERE TABLE_NAME = '" . $table . "' AND COLUMN_NAME = '" . $columnName . "'")
128
        //    || exit ($GLOBALS['xoopsDB']->error());
129
130
        $sql    = 'SELECT COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = "' . $table . '" AND COLUMN_NAME = "' . $columnName . '"';
131
        $result = $GLOBALS['xoopsDB']->query($sql);
132
        if (!$result instanceof \mysqli_result) {
133
            //            trigger_error($GLOBALS['xoopsDB']->error());
134
            $logger = \XoopsLogger::getInstance();
135
            $logger->handleError(\E_USER_WARNING, $sql, __FILE__, __LINE__);
136
137
            return null;
138
        }
139
140
        $row      = $GLOBALS['xoopsDB']->fetchBoth($result);
141
        $enumList = \explode(',', \str_replace("'", '', \mb_substr($row['COLUMN_TYPE'], 5, -6)));
142
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
Unused Code introduced by
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
        if (!$tempTable) {
167
            \trigger_error($GLOBALS['xoopsDB']->error());
168
        }
169
        // set the auto-incremented id's value to blank.
170
        unset($tempTable[$idField]);
171
        // insert cloned copy of the original  record
172
        $sql    = "INSERT INTO $table (" . \implode(', ', \array_keys($tempTable)) . ") VALUES ('" . \implode("', '", $tempTable) . "')";
173
        $result = $GLOBALS['xoopsDB']->queryF($sql);
174
        if (!$result) {
175
            \trigger_error($GLOBALS['xoopsDB']->error());
176
        }
177
        // Return the new id
178
        $newId = $GLOBALS['xoopsDB']->getInsertId();
179
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
320
        $isAdmin = $helper->isUserAdmin();
321
322
        if (\class_exists('XoopsFormEditor')) {
323
            if ($isAdmin) {
324
                $descEditor = new \XoopsFormEditor(\ucfirst($options['name']), $helper->getConfig('editorAdmin'), $options, false, 'textarea');
325
            } else {
326
                $descEditor = new \XoopsFormEditor(\ucfirst($options['name']), $helper->getConfig('editorUser'), $options, false, 'textarea');
327
            }
328
        } else {
329
            $descEditor = new \XoopsFormDhtmlTextArea(\ucfirst($options['name']), $options['name'], $options['value']);
330
        }
331
332
        //        $form->addElement($descEditor);
333
334
        return $descEditor;
335
    }
336
337
    /**
338
     * Check if column in dB table exists
339
     *
340
     * @param string $fieldname name of dB table field
341
     * @param string $table     name of dB table (including prefix)
342
     *
343
     * @return bool true if table exists
344
     * @deprecated
345
     */
346
    public static function fieldExists(string $fieldname, string $table): bool
347
    {
348
        $trace = \debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, 1);
349
        \trigger_error(__METHOD__ . " is deprecated, use Xmf\Database\Tables instead - instantiated from {$trace[0]['file']} line {$trace[0]['line']},");
350
351
        $result = $GLOBALS['xoopsDB']->queryF("SHOW COLUMNS FROM   $table LIKE '$fieldname'");
352
353
        return ($GLOBALS['xoopsDB']->getRowsNum($result) > 0);
354
    }
355
356
    /**
357
     * Function responsible for checking if a directory exists, we can also write in and create an index.html file
358
     *
359
     * @param string $folder The full path of the directory to check
360
     */
361
    public static function prepareFolder(string $folder): void
362
    {
363
        try {
364
            if (!@\mkdir($folder) && !\is_dir($folder)) {
365
                throw new \RuntimeException(\sprintf('Unable to create the %s directory', $folder));
366
            }
367
            file_put_contents($folder . '/index.html', '<script>history.go(-1);</script>');
368
        } catch (\Throwable $e) {
369
            echo 'Caught exception: ', $e->getMessage(), "\n", '<br>';
370
        }
371
    }
372
373
    /**
374
     * Check if dB table exists
375
     *
376
     * @param string $tablename dB tablename with prefix
377
     * @return bool true if table exists
378
     */
379
    public static function tableExists(string $tablename): bool
380
    {
381
        $trace = \debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, 1);
382
        \trigger_error(__FUNCTION__ . " is deprecated, called from {$trace[0]['file']} line {$trace[0]['line']}");
383
        $GLOBALS['xoopsLogger']->addDeprecated(
384
            \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']}"
385
        );
386
        $result = $GLOBALS['xoopsDB']->queryF("SHOW TABLES LIKE '$tablename'");
387
388
        return $GLOBALS['xoopsDB']->getRowsNum($result) > 0;
389
    }
390
391
    /**
392
     * Add a field to a mysql table
393
     *
394
     * @return bool|\mysqli_result
395
     */
396
    public static function addField(string $field, string $table)
397
    {
398
        global $xoopsDB;
399
400
        return $xoopsDB->queryF('ALTER TABLE ' . $table . " ADD $field;");
401
    }
402
}
403