SysUtility::cloneRecord()   A
last analyzed

Complexity

Conditions 4
Paths 5

Size

Total Lines 44
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 18
nc 5
nop 3
dl 0
loc 44
rs 9.6666
c 1
b 0
f 0
1
<?php declare(strict_types=1);
2
3
namespace XoopsModules\Xoopsheadline\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-2020 &copy; XOOPS Project
21
 * @author       ZySpec <[email protected]>
22
 * @author       Mamba <[email protected]>
23
 */
24
25
use Xmf\Request;
26
use XoopsModules\Xoopsheadline\{
27
    Helper
28
};
29
30
/**
31
 * Class SysUtility
32
 */
33
class SysUtility
34
{
35
    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...
36
    use ServerStats;    // getServerStats Trait
37
    use FilesManagement;    // Files Management Trait
38
    //    use ModuleStats;    // ModuleStats Trait
39
40
    //--------------- Common module methods -----------------------------
41
42
    /**
43
     * Access the only instance of this class
44
     */
45
    public static function getInstance(): self
46
    {
47
        static $instance;
48
        if (null === $instance) {
49
            $instance = new static();
50
        }
51
52
        return $instance;
53
    }
54
55
    public static function selectSorting(string $text, string $form_sort): string
56
    {
57
        global $start, $order, $sort;
58
59
        $helper = Helper::getInstance();
60
61
        //$pathModIcon16 = XOOPS_URL . '/modules/' . $moduleDirName . '/' . $helper->getConfig('modicons16');
62
        $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

62
        $pathModIcon16 = $helper->url(/** @scrutinizer ignore-type */ $helper->getModule()->getInfo('modicons16'));
Loading history...
63
64
        $selectView = '<form name="form_switch" id="form_switch" action="' . Request::getString('REQUEST_URI', '', 'SERVER') . '" method="post"><span style="font-weight: bold;">' . $text . '</span>';
65
        //$sorts =  $sort ==  'asc' ? 'desc' : 'asc';
66
        if ($form_sort == $sort) {
67
            $sel1 = 'asc' === $order ? 'selasc.png' : 'asc.png';
68
            $sel2 = 'desc' === $order ? 'seldesc.png' : 'desc.png';
69
        } else {
70
            $sel1 = 'asc.png';
71
            $sel2 = 'desc.png';
72
        }
73
        $selectView .= '  <a href="' . Request::getString('SCRIPT_NAME', '', 'SERVER') . '?start=' . $start . '&sort=' . $form_sort . '&order=asc"><img src="' . $pathModIcon16 . '/' . $sel1 . '" title="ASC" alt="ASC"></a>';
74
        $selectView .= '<a href="' . Request::getString('SCRIPT_NAME', '', 'SERVER') . '?start=' . $start . '&sort=' . $form_sort . '&order=desc"><img src="' . $pathModIcon16 . '/' . $sel2 . '" title="DESC" alt="DESC"></a>';
75
        $selectView .= '</form>';
76
77
        return $selectView;
78
    }
79
80
    /***************Blocks***************/
81
82
    public static function blockAddCatSelect(array $cats): string
83
    {
84
        $catSql = '';
85
        if (!empty($cats)) {
86
            $catSql = '(' . \current($cats);
87
            \array_shift($cats);
88
            //            foreach ($cats as $cat) {
89
            //                $catSql .= ',' . $cat;
90
            //            }
91
            $catSql .= implode(',', $cats);
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;
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
        } else {
166
            //            trigger_error("Query Failed! SQL: $sql- Error: " . $GLOBALS['xoopsDB']->error(), E_USER_ERROR);
167
            $logger = \XoopsLogger::getInstance();
168
            $logger->handleError(\E_USER_WARNING, $sql, __FILE__, __LINE__);
169
170
            return null;
171
        }
172
173
        //        $result = $GLOBALS['xoopsDB']->query($sql);
174
        //        if ($result instanceof \mysqli_result) {
175
        //            $result_array = $GLOBALS['xoopsDB']->fetchArray($result);
176
        //        } else {
177
        //            trigger_error("Query Failed! SQL: $sql- Error: " . $GLOBALS['xoopsDB']->error(), E_USER_ERROR);
178
        //            $logger = \XoopsLogger::getInstance();
179
        //            $logger->handleError(\E_USER_WARNING, $sql, __FILE__, __LINE__);
180
        //            return null;
181
        //        }
182
183
        if (!$tempTable) {
184
            \trigger_error($GLOBALS['xoopsDB']->error());
185
        }
186
        // set the auto-incremented id's value to blank.
187
        unset($tempTable[$idField]);
188
189
        // insert cloned copy of the original  record
190
        $sql    = "INSERT INTO $table (" . \implode(', ', \array_keys($tempTable)) . ") VALUES ('" . \implode("', '", $tempTable) . "')";
191
        $result = $GLOBALS['xoopsDB']->queryF($sql);
192
        if (!$result) {
193
            \trigger_error($GLOBALS['xoopsDB']->error());
194
        }
195
        // Return the new id
196
        $newId = $GLOBALS['xoopsDB']->getInsertId();
197
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
371
        return ($GLOBALS['xoopsDB']->getRowsNum($result) > 0);
372
    }
373
374
    /**
375
     * Function responsible for checking if a directory exists, we can also write in and create an index.html file
376
     *
377
     * @param string $folder The full path of the directory to check
378
     */
379
    public static function prepareFolder(string $folder): void
380
    {
381
        try {
382
            if (!@\mkdir($folder) && !\is_dir($folder)) {
383
                throw new \RuntimeException(\sprintf('Unable to create the %s directory', $folder));
384
            }
385
            file_put_contents($folder . '/index.html', '<script>history.go(-1);</script>');
386
        } catch (\Exception $e) {
387
            echo 'Caught exception: ', $e->getMessage(), "\n", '<br>';
388
        }
389
    }
390
391
    /**
392
     * Check if dB table exists
393
     *
394
     * @param string $tablename dB tablename with prefix
395
     * @return bool true if table exists
396
     */
397
    public static function tableExists(string $tablename): bool
398
    {
399
        $trace = \debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS, 1);
400
        \trigger_error(__FUNCTION__ . " is deprecated, called from {$trace[0]['file']} line {$trace[0]['line']}");
401
        $GLOBALS['xoopsLogger']->addDeprecated(
402
            \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']}"
403
        );
404
        $result = $GLOBALS['xoopsDB']->queryF("SHOW TABLES LIKE '$tablename'");
405
406
        return $GLOBALS['xoopsDB']->getRowsNum($result) > 0;
407
    }
408
409
    /**
410
     * Add a field to a mysql table
411
     *
412
     * @return bool|\mysqli_result
413
     */
414
    public static function addField(string $field, string $table)
415
    {
416
        return $GLOBALS['xoopsDB']->queryF('ALTER TABLE ' . $table . " ADD $field;");
417
    }
418
}
419