SysUtility::fieldExists()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 4
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 8
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;
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
38
    //checkVerXoops, checkVerPhp Traits
39
40
    use ServerStats;
41
42
    // getServerStats Trait
43
44
    use FilesManagement;
45
46
    // Files Management Trait
47
    //    use ModuleStats;    // ModuleStats Trait
48
49
    //--------------- Common module methods -----------------------------
50
51
    /**
52
     * Access the only instance of this class
53
     */
54
    public static function getInstance(): self
55
    {
56
        static $instance;
57
        if (null === $instance) {
58
            $instance = new static();
59
        }
60
61
        return $instance;
62
    }
63
64
    public static function selectSorting(string $text, string $form_sort): string
65
    {
66
        global $start, $order, $sort;
67
68
        $selectView = '';
0 ignored issues
show
Unused Code introduced by
The assignment to $selectView is dead and can be removed.
Loading history...
69
        $helper     = Helper::getInstance();
70
71
        //$pathModIcon16 = XOOPS_URL . '/modules/' . $moduleDirName . '/' . $helper->getConfig('modicons16');
72
        $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

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