Passed
Branch master (1b1cd9)
by Michael
03:24
created

SysUtility::cloneRecord()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 8
c 0
b 0
f 0
nc 8
nop 3
dl 0
loc 16
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace XoopsModules\Publisher\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
 * @license      https://www.fsf.org/copyleft/gpl.html GNU public license
22
 * @copyright    https://xoops.org 2000-2020 &copy; XOOPS Project
23
 * @author       ZySpec <[email protected]>
24
 * @author       Mamba <[email protected]>
25
 */
26
27
use MyTextSanitizer;
28
use XoopsFormDhtmlTextArea;
29
use XoopsFormTextArea;
30
use XoopsModules\Publisher;
31
use XoopsModules\Publisher\Helper;
32
33
/**
34
 * Class SysUtility
35
 */
36
class SysUtility
37
{
38
    use VersionChecks;
0 ignored issues
show
introduced by
The trait XoopsModules\Publisher\Common\VersionChecks requires some properties which are not provided by XoopsModules\Publisher\Common\SysUtility: $tag_name, $prerelease
Loading history...
39
40
    //checkVerXoops, checkVerPhp Traits
41
42
    use ServerStats;
43
44
    // getServerStats Trait
45
46
    use FilesManagement;
47
48
    // Files Management Trait
49
50
    use ModuleStats;
0 ignored issues
show
Bug introduced by
The trait XoopsModules\Publisher\Common\ModuleStats requires the property $moduleStats which is not provided by XoopsModules\Publisher\Common\SysUtility.
Loading history...
51
52
    // ModuleStats Trait
53
54
    /**
55
     * truncateHtml can truncate a string up to a number of characters while preserving whole words and HTML tags
56
     * www.gsdesign.ro/blog/cut-html-string-without-breaking-the-tags
57
     * www.cakephp.org
58
     *
59
     * @param string $text         String to truncate.
60
     * @param int    $length       Length of returned string, including ellipsis.
61
     * @param string $ending       Ending to be appended to the trimmed string.
62
     * @param bool   $exact        If false, $text will not be cut mid-word
63
     * @param bool   $considerHtml If true, HTML tags would be handled correctly
64
     *
65
     * @return string Trimmed string.
66
     */
67
    public static function truncateHtml($text, $length = 100, $ending = '...', $exact = false, $considerHtml = true)
68
    {
69
        if ($considerHtml) {
70
            // if the plain text is shorter than the maximum length, return the whole text
71
            if (mb_strlen(\preg_replace('/<.*?' . '>/', '', $text)) <= $length) {
72
                return $text;
73
            }
74
            // splits all html-tags to scanable lines
75
            \preg_match_all('/(<.+?' . '>)?([^<>]*)/s', $text, $lines, \PREG_SET_ORDER);
76
            $totalLength = mb_strlen($ending);
77
            $openTags    = [];
78
            $truncate    = '';
79
            foreach ($lines as $lineMatchings) {
80
                // if there is any html-tag in this line, handle it and add it (uncounted) to the output
81
                if (!empty($lineMatchings[1])) {
82
                    // if it's an "empty element" with or without xhtml-conform closing slash
83
                    if (\preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $lineMatchings[1])) {
84
                        // do nothing
85
                        // if tag is a closing tag
86
                    } elseif (\preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $lineMatchings[1], $tagMatchings)) {
87
                        // delete tag from $openTags list
88
                        $pos = \array_search($tagMatchings[1], $openTags, true);
89
                        if (false !== $pos) {
90
                            unset($openTags[$pos]);
91
                        }
92
                        // if tag is an opening tag
93
                    } elseif (\preg_match('/^<\s*([^\s>!]+).*?' . '>$/s', $lineMatchings[1], $tagMatchings)) {
94
                        // add tag to the beginning of $openTags list
95
                        \array_unshift($openTags, mb_strtolower($tagMatchings[1]));
96
                    }
97
                    // add html-tag to $truncate'd text
98
                    $truncate .= $lineMatchings[1];
99
                }
100
                // calculate the length of the plain text part of the line; handle entities as one character
101
                $content_length = mb_strlen(\preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', ' ', $lineMatchings[2]));
102
                if ($totalLength + $content_length > $length) {
103
                    // the number of characters which are left
104
                    $left           = $length - $totalLength;
105
                    $entitiesLength = 0;
106
                    // search for html entities
107
                    if (\preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', $lineMatchings[2], $entities, \PREG_OFFSET_CAPTURE)) {
108
                        // calculate the real length of all entities in the legal range
109
                        foreach ($entities[0] as $entity) {
110
                            if ($left >= $entity[1] + 1 - $entitiesLength) {
111
                                $left--;
112
                                $entitiesLength += mb_strlen($entity[0]);
113
                            } else {
114
                                // no more characters left
115
                                break;
116
                            }
117
                        }
118
                    }
119
                    $truncate .= mb_substr($lineMatchings[2], 0, $left + $entitiesLength);
120
                    // maximum lenght is reached, so get off the loop
121
                    break;
122
                }
123
                $truncate    .= $lineMatchings[2];
124
                $totalLength += $content_length;
125
126
                // if the maximum length is reached, get off the loop
127
                if ($totalLength >= $length) {
128
                    break;
129
                }
130
            }
131
        } else {
132
            if (mb_strlen($text) <= $length) {
133
                return $text;
134
            }
135
            $truncate = mb_substr($text, 0, $length - mb_strlen($ending));
136
        }
137
        // if the words shouldn't be cut in the middle...
138
        if (!$exact) {
139
            // ...search the last occurance of a space...
140
            $spacepos = mb_strrpos($truncate, ' ');
141
            if (isset($spacepos)) {
142
                // ...and cut the text in this position
143
                $truncate = mb_substr($truncate, 0, $spacepos);
144
            }
145
        }
146
        // add the defined ending to the text
147
        $truncate .= $ending;
148
        if ($considerHtml) {
149
            // close all unclosed html-tags
150
            foreach ($openTags as $tag) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $openTags does not seem to be defined for all execution paths leading up to this point.
Loading history...
151
                $truncate .= '</' . $tag . '>';
152
            }
153
        }
154
155
        return $truncate;
156
    }
157
158
    /**
159
     * @param null|\Helper $helper
0 ignored issues
show
Bug introduced by
The type Helper was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
160
     * @param array|null   $options
161
     * @return \XoopsFormDhtmlTextArea|\XoopsFormEditor
162
     */
163
    public static function getEditor($helper = null, $options = null)
164
    {
165
        /** @var Helper $helper */
166
        if (null === $options) {
167
            $options           = [];
168
            $options['name']   = 'Editor';
169
            $options['value']  = 'Editor';
170
            $options['rows']   = 10;
171
            $options['cols']   = '100%';
172
            $options['width']  = '100%';
173
            $options['height'] = '400px';
174
        }
175
176
        if (null === $helper) {
177
            $helper = Helper::getInstance();
178
        }
179
180
        $isAdmin = $helper->isUserAdmin();
181
182
        if (\class_exists('XoopsFormEditor')) {
183
            if ($isAdmin) {
184
                $descEditor = new \XoopsFormEditor(\ucfirst($options['name']), $helper->getConfig('editorAdmin'), $options, $nohtml = false, $onfailure = 'textarea');
185
            } else {
186
                $descEditor = new \XoopsFormEditor(\ucfirst($options['name']), $helper->getConfig('editorUser'), $options, $nohtml = false, $onfailure = 'textarea');
187
            }
188
        } else {
189
            $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

189
            $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

189
            $descEditor = new \XoopsFormDhtmlTextArea(\ucfirst($options['name']), $options['name'], $options['value'], '100%', /** @scrutinizer ignore-type */ '100%');
Loading history...
190
        }
191
192
        //        $form->addElement($descEditor);
193
194
        return $descEditor;
195
    }
196
197
    /**
198
     * @param $fieldname
199
     * @param $table
200
     *
201
     * @return bool
202
     */
203
    public function fieldExists($fieldname, $table)
204
    {
205
        global $xoopsDB;
206
        $result = $xoopsDB->queryF("SHOW COLUMNS FROM   $table LIKE '$fieldname'");
207
208
        return ($xoopsDB->getRowsNum($result) > 0);
209
    }
210
211
    /**
212
     * @param array|string $tableName
213
     * @param int          $id_field
214
     * @param int          $id
215
     *
216
     * @return mixed
217
     */
218
    public static function cloneRecord($tableName, $id_field, $id)
219
    {
220
        $new_id = false;
221
        $table  = $GLOBALS['xoopsDB']->prefix($tableName);
222
        // copy content of the record you wish to clone
223
        $tempTable = $GLOBALS['xoopsDB']->fetchArray($GLOBALS['xoopsDB']->query("SELECT * FROM $table WHERE $id_field='$id' "), MYSQLI_ASSOC) or exit('Could not select record');
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...
224
        // set the auto-incremented id's value to blank.
225
        unset($tempTable[$id_field]);
226
        // insert cloned copy of the original  record
227
        $result = $GLOBALS['xoopsDB']->queryF("INSERT INTO $table (" . implode(', ', array_keys($tempTable)) . ") VALUES ('" . implode("', '", array_values($tempTable)) . "')") or 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...
228
229
        if ($result) {
230
            // Return the new id
231
            $new_id = $GLOBALS['xoopsDB']->getInsertId();
232
        }
233
        return $new_id;
234
    }
235
}
236