SysUtility::metaDescription()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 7
nc 2
nop 1
dl 0
loc 12
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace XoopsModules\Chess\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 XoopsModules\Chess\Helper;
26
27
/**
28
 * Class Utility
29
 */
30
class SysUtility
31
{
32
    use VersionChecks;
0 ignored issues
show
introduced by
The trait XoopsModules\Chess\Common\VersionChecks requires some properties which are not provided by XoopsModules\Chess\Common\SysUtility: $tag_name, $prerelease
Loading history...
33
34
    //checkVerXoops, checkVerPhp Traits
35
36
    use ServerStats;
37
38
    // getServerStats Trait
39
40
    use FilesManagement;
41
42
    // Files Management Trait
43
44
    /**
45
     * Access the only instance of this class
46
     *
47
     * @return object
48
     */
49
    public static function getInstance()
50
    {
51
        static $instance;
52
53
        if (null === $instance) {
54
            $instance = new static();
55
        }
56
57
        return $instance;
58
    }
59
60
    /**
61
     * @param array|string $tableName
62
     * @param int          $id_field
63
     * @param int          $id
64
     *
65
     * @return mixed
66
     */
67
    public static function cloneRecord($tableName, $id_field, $id)
68
    {
69
        $new_id = false;
0 ignored issues
show
Unused Code introduced by
The assignment to $new_id is dead and can be removed.
Loading history...
70
71
        $table = $GLOBALS['xoopsDB']->prefix($tableName);
72
73
        // copy content of the record you wish to clone
74
75
        $sql = "SELECT * FROM $table WHERE $id_field='$id' ";
76
77
        $tempTable = $GLOBALS['xoopsDB']->fetchArray($GLOBALS['xoopsDB']->query($sql), \MYSQLI_ASSOC);
78
79
        if (!$tempTable) {
80
            exit($GLOBALS['xoopsDB']->error());
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
81
        }
82
83
        // set the auto-incremented id's value to blank.
84
85
        unset($tempTable[$id_field]);
86
87
        // insert cloned copy of the original  record
88
89
        $sql = "INSERT INTO $table (" . \implode(', ', \array_keys($tempTable)) . ") VALUES ('" . \implode("', '", \array_values($tempTable)) . "')";
90
91
        $result = $GLOBALS['xoopsDB']->queryF($sql);
92
93
        if (!$result) {
94
            exit($GLOBALS['xoopsDB']->error());
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
95
        }
96
97
        // Return the new id
98
99
        $new_id = $GLOBALS['xoopsDB']->getInsertId();
100
101
        return $new_id;
102
    }
103
104
    /**
105
     * @param $content
106
     */
107
    public static function metaKeywords($content)
108
    {
109
        global $xoopsTpl, $xoTheme;
110
111
        $myts = \MyTextSanitizer::getInstance();
112
113
        $content = $myts->undoHtmlSpecialChars($myts->displayTarea($content));
114
115
        if (null !== $xoTheme && \is_object($xoTheme)) {
116
            $xoTheme->addMeta('meta', 'keywords', \strip_tags($content));
117
        } else {    // Compatibility for old Xoops versions
118
            $xoopsTpl->assign('xoops_metaKeywords', \strip_tags($content));
119
        }
120
    }
121
122
    /**
123
     * @param $content
124
     */
125
    public static function metaDescription($content)
126
    {
127
        global $xoopsTpl, $xoTheme;
128
129
        $myts = \MyTextSanitizer::getInstance();
130
131
        $content = $myts->undoHtmlSpecialChars($myts->displayTarea($content));
132
133
        if (null !== $xoTheme && \is_object($xoTheme)) {
134
            $xoTheme->addMeta('meta', 'description', \strip_tags($content));
135
        } else {    // Compatibility for old Xoops versions
136
            $xoopsTpl->assign('xoops_metaDescription', \strip_tags($content));
137
        }
138
    }
139
140
    /**
141
     * @param $tableName
142
     * @param $columnName
143
     *
144
     * @return array
145
     */
146
    public static function enumerate($tableName, $columnName)
147
    {
148
        $table = $GLOBALS['xoopsDB']->prefix($tableName);
149
150
        //    $result = $GLOBALS['xoopsDB']->query("SELECT COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS
151
152
        //        WHERE TABLE_NAME = '" . $table . "' AND COLUMN_NAME = '" . $columnName . "'")
153
154
        //    || exit ($GLOBALS['xoopsDB']->error());
155
156
        $sql = 'SELECT COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = "' . $table . '" AND COLUMN_NAME = "' . $columnName . '"';
157
158
        $result = $GLOBALS['xoopsDB']->query($sql);
159
160
        if (!$result) {
161
            exit($GLOBALS['xoopsDB']->error());
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
162
        }
163
164
        $row = $GLOBALS['xoopsDB']->fetchBoth($result);
165
166
        return \explode(',', \str_replace("'", '', \mb_substr($row['COLUMN_TYPE'], 5, -6)));
167
    }
168
169
    /**
170
     * truncateHtml can truncate a string up to a number of characters while preserving whole words and HTML tags
171
     * www.gsdesign.ro/blog/cut-html-string-without-breaking-the-tags
172
     * www.cakephp.org
173
     *
174
     * @param string $text         String to truncate.
175
     * @param int    $length       Length of returned string, including ellipsis.
176
     * @param string $ending       Ending to be appended to the trimmed string.
177
     * @param bool   $exact        If false, $text will not be cut mid-word
178
     * @param bool   $considerHtml If true, HTML tags would be handled correctly
179
     *
180
     * @return string Trimmed string.
181
     */
182
    public static function truncateHtml($text, $length = 100, $ending = '...', $exact = false, $considerHtml = true)
183
    {
184
        if ($considerHtml) {
185
            // if the plain text is shorter than the maximum length, return the whole text
186
187
            if (mb_strlen(\preg_replace('/<.*?' . '>/', '', $text)) <= $length) {
188
                return $text;
189
            }
190
191
            // splits all html-tags to scanable lines
192
193
            \preg_match_all('/(<.+?' . '>)?([^<>]*)/s', $text, $lines, \PREG_SET_ORDER);
194
195
            $total_length = mb_strlen($ending);
196
197
            $open_tags = [];
198
199
            $truncate = '';
200
201
            foreach ($lines as $line_matchings) {
202
                // if there is any html-tag in this line, handle it and add it (uncounted) to the output
203
204
                if (!empty($line_matchings[1])) {
205
                    // if it's an "empty element" with or without xhtml-conform closing slash
206
207
                    if (\preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $line_matchings[1])) {
208
                        // do nothing
209
                        // if tag is a closing tag
210
                    } elseif (\preg_match('/^<\s*\/([\S]+?)\s*>$/s', $line_matchings[1], $tag_matchings)) {
211
                        // delete tag from $open_tags list
212
213
                        $pos = \array_search($tag_matchings[1], $open_tags, true);
214
215
                        if (false !== $pos) {
216
                            unset($open_tags[$pos]);
217
                        }
218
                        // if tag is an opening tag
219
                    } elseif (\preg_match('/^<\s*([^\s>!]+).*?' . '>$/s', $line_matchings[1], $tag_matchings)) {
220
                        // add tag to the beginning of $open_tags list
221
222
                        \array_unshift($open_tags, mb_strtolower($tag_matchings[1]));
223
                    }
224
225
                    // add html-tag to $truncate'd text
226
227
                    $truncate .= $line_matchings[1];
228
                }
229
230
                // calculate the length of the plain text part of the line; handle entities as one character
231
232
                $content_length = mb_strlen(\preg_replace('/&[0-9a-z]{2,8};|&#\d{1,7};|[0-9a-f]{1,6};/i', ' ', $line_matchings[2]));
233
234
                if ($total_length + $content_length > $length) {
235
                    // the number of characters which are left
236
237
                    $left = $length - $total_length;
238
239
                    $entities_length = 0;
240
241
                    // search for html entities
242
243
                    if (\preg_match_all('/&[0-9a-z]{2,8};|&#\d{1,7};|[0-9a-f]{1,6};/i', $line_matchings[2], $entities, \PREG_OFFSET_CAPTURE)) {
244
                        // calculate the real length of all entities in the legal range
245
246
                        foreach ($entities[0] as $entity) {
247
                            if ($left >= $entity[1] + 1 - $entities_length) {
248
                                $left--;
249
250
                                $entities_length += mb_strlen($entity[0]);
251
                            } else {
252
                                // no more characters left
253
254
                                break;
255
                            }
256
                        }
257
                    }
258
259
                    $truncate .= mb_substr($line_matchings[2], 0, $left + $entities_length);
260
261
                    // maximum lenght is reached, so get off the loop
262
263
                    break;
264
                }
265
266
                $truncate .= $line_matchings[2];
267
268
                $total_length += $content_length;
269
270
                // if the maximum length is reached, get off the loop
271
272
                if ($total_length >= $length) {
273
                    break;
274
                }
275
            }
276
        } else {
277
            if (mb_strlen($text) <= $length) {
278
                return $text;
279
            }
280
281
            $truncate = mb_substr($text, 0, $length - mb_strlen($ending));
282
        }
283
284
        // if the words shouldn't be cut in the middle...
285
286
        if (!$exact) {
287
            // ...search the last occurance of a space...
288
289
            $spacepos = mb_strrpos($truncate, ' ');
290
291
            if (isset($spacepos)) {
292
                // ...and cut the text in this position
293
294
                $truncate = mb_substr($truncate, 0, $spacepos);
295
            }
296
        }
297
298
        // add the defined ending to the text
299
300
        $truncate .= $ending;
301
302
        if ($considerHtml) {
303
            // close all unclosed html-tags
304
305
            foreach ($open_tags as $tag) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $open_tags does not seem to be defined for all execution paths leading up to this point.
Loading history...
306
                $truncate .= '</' . $tag . '>';
307
            }
308
        }
309
310
        return $truncate;
311
    }
312
313
    /**
314
     * @param \Xmf\Module\Helper $helper
315
     * @param array|null         $options
316
     * @return \XoopsFormDhtmlTextArea|\XoopsFormEditor
317
     */
318
    public static function getEditor($helper = null, $options = null)
319
    {
320
        /** @var Helper $helper */
321
322
        if (null === $options) {
323
            $options = [];
324
325
            $options['name'] = 'Editor';
326
327
            $options['value'] = 'Editor';
328
329
            $options['rows'] = 10;
330
331
            $options['cols'] = '100%';
332
333
            $options['width'] = '100%';
334
335
            $options['height'] = '400px';
336
        }
337
338
        if (null === $helper) {
339
            $helper = Helper::getInstance();
340
        }
341
342
        $isAdmin = $helper->isUserAdmin();
343
344
        if (\class_exists('XoopsFormEditor')) {
345
            if ($isAdmin) {
346
                $descEditor = new \XoopsFormEditor(\ucfirst($options['name']), $helper->getConfig('editorAdmin'), $options, $nohtml = false, $onfailure = 'textarea');
347
            } else {
348
                $descEditor = new \XoopsFormEditor(\ucfirst($options['name']), $helper->getConfig('editorUser'), $options, $nohtml = false, $onfailure = 'textarea');
349
            }
350
        } else {
351
            $descEditor = new \XoopsFormDhtmlTextArea(\ucfirst($options['name']), $options['name'], $options['value'], '100%', '100%');
0 ignored issues
show
Bug introduced by
'100%' of type string is incompatible with the type integer expected by parameter $rows of XoopsFormDhtmlTextArea::__construct(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

351
            $descEditor = new \XoopsFormDhtmlTextArea(\ucfirst($options['name']), $options['name'], $options['value'], /** @scrutinizer ignore-type */ '100%', '100%');
Loading history...
Bug introduced by
'100%' of type string is incompatible with the type integer expected by parameter $cols of XoopsFormDhtmlTextArea::__construct(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

351
            $descEditor = new \XoopsFormDhtmlTextArea(\ucfirst($options['name']), $options['name'], $options['value'], '100%', /** @scrutinizer ignore-type */ '100%');
Loading history...
352
        }
353
354
        //        $form->addElement($descEditor);
355
356
        return $descEditor;
357
    }
358
359
    /**
360
     * @param $fieldname
361
     * @param $table
362
     *
363
     * @return bool
364
     */
365
    public function fieldExists($fieldname, $table)
366
    {
367
        global $xoopsDB;
368
369
        $result = $xoopsDB->queryF("SHOW COLUMNS FROM   $table LIKE '$fieldname'");
370
371
        return $xoopsDB->getRowsNum($result) > 0;
372
    }
373
}
374