Utility   A
last analyzed

Complexity

Total Complexity 38

Size/Duplication

Total Lines 235
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 107
dl 0
loc 235
rs 9.36
c 0
b 0
f 0
wmc 38

7 Methods

Rating   Name   Duplication   Size   Complexity  
F truncateHtml() 0 90 19
A metaKeywords() 0 9 3
A selectSorting() 0 22 4
A cloneRecord() 0 16 4
A blockAddCatSelect() 0 13 3
A metaDescription() 0 9 3
A enumerate() 0 12 2
1
<?php namespace XoopsModules\Cardealer;
2
3
/*
4
 You may not change or alter any portion of this comment or credits
5
 of supporting developers from this source code or any supporting source code
6
 which is considered copyrighted (c) material of the original comment or credit authors.
7
8
 This program is distributed in the hope that it will be useful,
9
 but WITHOUT ANY WARRANTY; without even the implied warranty of
10
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
11
*/
12
13
/**
14
 * Module: cardealer
15
 *
16
 * @category        Module
17
 * @package         cardealer
18
 * @author          XOOPS Development Team <[email protected]> - <https://xoops.org>
19
 * @copyright       {@link https://xoops.org/ XOOPS Project}
20
 * @license         GPL 2.0 or later
21
 * @link            https://xoops.org/
22
 * @since           1.0.0
23
 */
24
25
use Xmf\Request;
26
use XoopsModules\Cardealer;
27
use XoopsModules\Cardealer\Common;
28
29
/**
30
 * Class Utility
31
 */
32
class Utility
33
{
34
    use Common\VersionChecks; //checkVerXoops, checkVerPhp Traits
35
    use Common\ServerStats; // getServerStats Trait
36
    use Common\FilesManagement; // Files Management Trait
37
38
    //--------------- Custom module methods -----------------------------
39
40
    /**
41
     * @param $text
42
     * @param $form_sort
43
     * @return string
44
     */
45
    public static function selectSorting($text, $form_sort)
46
    {
47
        global $start, $order, $file_cat, $sort, $xoopsModule;
48
49
        $select_view   = '';
0 ignored issues
show
Unused Code introduced by
The assignment to $select_view is dead and can be removed.
Loading history...
50
        $moduleDirName = basename(dirname(__DIR__));
51
        $helper = Cardealer\Helper::getInstance();
52
        $pathModIcon16 = XOOPS_URL . '/modules/' . $moduleDirName . '/' . $helper->getModule()->getInfo('modicons16');
0 ignored issues
show
Bug introduced by
Are you sure $helper->getModule()->getInfo('modicons16') of type array|string can be used in concatenation? ( Ignorable by Annotation )

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

52
        $pathModIcon16 = XOOPS_URL . '/modules/' . $moduleDirName . '/' . /** @scrutinizer ignore-type */ $helper->getModule()->getInfo('modicons16');
Loading history...
53
54
        $select_view = '<form name="form_switch" id="form_switch" action="' . Request::getString('REQUEST_URI', '', 'SERVER') . '" method="post"><span style="font-weight: bold;">' . $text . '</span>';
55
        if ($form_sort == $sort) {
56
            $sel1 = 'asc' === $order ? 'selasc.png' : 'asc.png';
57
            $sel2 = 'desc' === $order ? 'seldesc.png' : 'desc.png';
58
        } else {
59
            $sel1 = 'asc.png';
60
            $sel2 = 'desc.png';
61
        }
62
        $select_view .= '  <a href="' . Request::getString('PHP_SELF', '', 'SERVER') . '?start=' . $start . '&sort=' . $form_sort . '&order=asc" /><img src="' . $pathModIcon16 . '/' . $sel1 . '" title="ASC" alt="ASC"></a>';
63
        $select_view .= '<a href="' . Request::getString('PHP_SELF', '', 'SERVER') . '?start=' . $start . '&sort=' . $form_sort . '&order=desc" /><img src="' . $pathModIcon16 . '/' . $sel2 . '" title="DESC" alt="DESC"></a>';
64
        $select_view .= '</form>';
65
66
        return $select_view;
67
    }
68
69
    /***************Blocks***************/
70
    /**
71
     * @param array $cats
72
     * @return string
73
     */
74
    public static function blockAddCatSelect($cats)
75
    {
76
        $cat_sql = '';
77
        if (is_array($cats)) {
0 ignored issues
show
introduced by
The condition is_array($cats) is always true.
Loading history...
78
            $cat_sql = '(' . current($cats);
79
            array_shift($cats);
80
            foreach ($cats as $cat) {
81
                $cat_sql .= ',' . $cat;
82
            }
83
            $cat_sql .= ')';
84
        }
85
86
        return $cat_sql;
87
    }
88
89
    /**
90
     * @param $content
91
     */
92
    public static function metaKeywords($content)
93
    {
94
        global $xoopsTpl, $xoTheme;
95
        $myts    = \MyTextSanitizer::getInstance();
96
        $content = $myts->undoHtmlSpecialChars($myts->displayTarea($content));
97
        if (null !== $xoTheme && is_object($xoTheme)) {
98
            $xoTheme->addMeta('meta', 'keywords', strip_tags($content));
99
        } else {    // Compatibility for old Xoops versions
100
            $xoopsTpl->assign('xoops_metaKeywords', strip_tags($content));
101
        }
102
    }
103
104
    /**
105
     * @param $content
106
     */
107
    public static function metaDescription($content)
108
    {
109
        global $xoopsTpl, $xoTheme;
110
        $myts    = \MyTextSanitizer::getInstance();
111
        $content = $myts->undoHtmlSpecialChars($myts->displayTarea($content));
112
        if (null !== $xoTheme && is_object($xoTheme)) {
113
            $xoTheme->addMeta('meta', 'description', strip_tags($content));
114
        } else {    // Compatibility for old Xoops versions
115
            $xoopsTpl->assign('xoops_metaDescription', strip_tags($content));
116
        }
117
    }
118
119
    /**
120
     * @param $tableName
121
     * @param $columnName
122
     *
123
     * @return array
124
     */
125
    public static function enumerate($tableName, $columnName)
126
    {
127
        $table = $GLOBALS['xoopsDB']->prefix($tableName);
128
        $sql    = 'SELECT COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = "' . $table . '" AND COLUMN_NAME = "' . $columnName . '"';
129
        $result = $GLOBALS['xoopsDB']->query($sql);
130
        if (!$result) {
131
            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...
132
        }
133
134
        $row      = $GLOBALS['xoopsDB']->fetchBoth($result);
135
        $enumList = explode(',', str_replace("'", '', substr($row['COLUMN_TYPE'], 5, -6)));
136
        return $enumList;
137
    }
138
139
    /**
140
     * @param array|string $tableName
141
     * @param int          $id_field
142
     * @param int          $id
143
     *
144
     * @return mixed
145
     */
146
    public static function cloneRecord($tableName, $id_field, $id)
147
    {
148
        $new_id = false;
149
        $table  = $GLOBALS['xoopsDB']->prefix($tableName);
150
        // copy content of the record you wish to clone 
151
        $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...
152
        // set the auto-incremented id's value to blank.
153
        unset($tempTable[$id_field]);
154
        // insert cloned copy of the original  record 
155
        $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...
156
157
        if ($result) {
158
            // Return the new id
159
            $new_id = $GLOBALS['xoopsDB']->getInsertId();
160
        }
161
        return $new_id;
162
    }
163
164
    /**
165
     * truncateHtml can truncate a string up to a number of characters while preserving whole words and HTML tags
166
     * www.gsdesign.ro/blog/cut-html-string-without-breaking-the-tags
167
     * www.cakephp.org
168
     *
169
     * @param string  $text         String to truncate.
170
     * @param integer $length       Length of returned string, including ellipsis.
171
     * @param string  $ending       Ending to be appended to the trimmed string.
172
     * @param boolean $exact        If false, $text will not be cut mid-word
173
     * @param boolean $considerHtml If true, HTML tags would be handled correctly
174
     *
175
     * @return string Trimmed string.
176
     */
177
    public static function truncateHtml($text, $length = 100, $ending = '...', $exact = false, $considerHtml = true)
178
    {
179
        if ($considerHtml) {
180
            // if the plain text is shorter than the maximum length, return the whole text
181
            if (strlen(preg_replace('/<.*?' . '>/', '', $text)) <= $length) {
182
                return $text;
183
            }
184
            // splits all html-tags to scanable lines
185
            preg_match_all('/(<.+?' . '>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
186
            $total_length = strlen($ending);
187
            $openTags     = [];
188
            $truncate     = '';
189
            foreach ($lines as $line_matchings) {
190
                // if there is any html-tag in this line, handle it and add it (uncounted) to the output
191
                if (!empty($line_matchings[1])) {
192
                    // if it's an "empty element" with or without xhtml-conform closing slash
193
                    if (preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $line_matchings[1])) {
194
                        // do nothing
195
                        // if tag is a closing tag
196
                    } elseif (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $line_matchings[1], $tag_matchings)) {
197
                        // delete tag from $openTags list
198
                        $pos = array_search($tag_matchings[1], $openTags);
199
                        if (false !== $pos) {
200
                            unset($openTags[$pos]);
201
                        }
202
                        // if tag is an opening tag
203
                    } elseif (preg_match('/^<\s*([^\s>!]+).*?' . '>$/s', $line_matchings[1], $tag_matchings)) {
204
                        // add tag to the beginning of $openTags list
205
                        array_unshift($openTags, strtolower($tag_matchings[1]));
206
                    }
207
                    // add html-tag to $truncate'd text
208
                    $truncate .= $line_matchings[1];
209
                }
210
                // calculate the length of the plain text part of the line; handle entities as one character
211
                $content_length = strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', ' ', $line_matchings[2]));
212
                if ($total_length + $content_length > $length) {
213
                    // the number of characters which are left
214
                    $left            = $length - $total_length;
215
                    $entities_length = 0;
216
                    // search for html entities
217
                    if (preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', $line_matchings[2], $entities, PREG_OFFSET_CAPTURE)) {
218
                        // calculate the real length of all entities in the legal range
219
                        foreach ($entities[0] as $entity) {
220
                            if ($entity[1] + 1 - $entities_length <= $left) {
221
                                $left--;
222
                                $entities_length += strlen($entity[0]);
223
                            } else {
224
                                // no more characters left
225
                                break;
226
                            }
227
                        }
228
                    }
229
                    $truncate .= substr($line_matchings[2], 0, $left + $entities_length);
230
                    // maximum lenght is reached, so get off the loop
231
                    break;
232
                } else {
233
                    $truncate     .= $line_matchings[2];
234
                    $total_length += $content_length;
235
                }
236
                // if the maximum length is reached, get off the loop
237
                if ($total_length >= $length) {
238
                    break;
239
                }
240
            }
241
        } else {
242
            if (strlen($text) <= $length) {
243
                return $text;
244
            } else {
245
                $truncate = substr($text, 0, $length - strlen($ending));
246
            }
247
        }
248
        // if the words shouldn't be cut in the middle...
249
        if (!$exact) {
250
            // ...search the last occurance of a space...
251
            $spacepos = strrpos($truncate, ' ');
252
            if (isset($spacepos)) {
253
                // ...and cut the text in this position
254
                $truncate = substr($truncate, 0, $spacepos);
255
            }
256
        }
257
        // add the defined ending to the text
258
        $truncate .= $ending;
259
        if ($considerHtml) {
260
            // close all unclosed html-tags
261
            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...
262
                $truncate .= '</' . $tag . '>';
263
            }
264
        }
265
266
        return $truncate;
267
    }
268
269
}
270