Passed
Pull Request — master (#5)
by Michael
02:50
created

Utility::cleanVars()   A

Complexity

Conditions 6
Paths 12

Size

Total Lines 16
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 11
nc 12
nop 4
dl 0
loc 16
rs 9.2222
c 0
b 0
f 0
1
<?php
2
3
namespace XoopsModules\Tdmdownloads;
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
use Xmf\Request;
19
use XoopsModules\Tdmdownloads;
20
use XoopsModules\Tdmdownloads\Common;
21
22
/**
23
 * Class Utility
24
 */
25
class Utility
26
{
27
    use Common\VersionChecks; //checkVerXoops, checkVerPhp Traits
28
29
    use Common\ServerStats; // getServerStats Trait
30
31
    use Common\FilesManagement; // Files Management Trait
32
33
    /**
34
     * truncateHtml can truncate a string up to a number of characters while preserving whole words and HTML tags
35
     * www.gsdesign.ro/blog/cut-html-string-without-breaking-the-tags
36
     * www.cakephp.org
37
     *
38
     * @param string $text         String to truncate.
39
     * @param int    $length       Length of returned string, including ellipsis.
40
     * @param string $ending       Ending to be appended to the trimmed string.
41
     * @param bool   $exact        If false, $text will not be cut mid-word
42
     * @param bool   $considerHtml If true, HTML tags would be handled correctly
43
     *
44
     * @return string Trimmed string.
45
     */
46
    public static function truncateHtml($text, $length = 100, $ending = '...', $exact = false, $considerHtml = true)
47
    {
48
        if ($considerHtml) {
49
            // if the plain text is shorter than the maximum length, return the whole text
50
            if (mb_strlen(preg_replace('/<.*?' . '>/', '', $text)) <= $length) {
51
                return $text;
52
            }
53
            // splits all html-tags to scanable lines
54
            preg_match_all('/(<.+?' . '>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
55
            $total_length = mb_strlen($ending);
56
            $open_tags    = [];
57
            $truncate     = '';
58
            foreach ($lines as $line_matchings) {
59
                // if there is any html-tag in this line, handle it and add it (uncounted) to the output
60
                if (!empty($line_matchings[1])) {
61
                    // if it's an "empty element" with or without xhtml-conform closing slash
62
                    if (preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $line_matchings[1])) {
63
                        // do nothing
64
                        // if tag is a closing tag
65
                    } elseif (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $line_matchings[1], $tag_matchings)) {
66
                        // delete tag from $open_tags list
67
                        $pos = array_search($tag_matchings[1], $open_tags, true);
68
                        if (false !== $pos) {
69
                            unset($open_tags[$pos]);
70
                        }
71
                        // if tag is an opening tag
72
                    } elseif (preg_match('/^<\s*([^\s>!]+).*?' . '>$/s', $line_matchings[1], $tag_matchings)) {
73
                        // add tag to the beginning of $open_tags list
74
                        array_unshift($open_tags, mb_strtolower($tag_matchings[1]));
75
                    }
76
                    // add html-tag to $truncate'd text
77
                    $truncate .= $line_matchings[1];
78
                }
79
                // calculate the length of the plain text part of the line; handle entities as one character
80
                $content_length = mb_strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', ' ', $line_matchings[2]));
81
                if ($total_length + $content_length > $length) {
82
                    // the number of characters which are left
83
                    $left            = $length - $total_length;
84
                    $entities_length = 0;
85
                    // search for html entities
86
                    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)) {
87
                        // calculate the real length of all entities in the legal range
88
                        foreach ($entities[0] as $entity) {
89
                            if ($left >= $entity[1] + 1 - $entities_length) {
90
                                $left--;
91
                                $entities_length += mb_strlen($entity[0]);
92
                            } else {
93
                                // no more characters left
94
                                break;
95
                            }
96
                        }
97
                    }
98
                    $truncate .= mb_substr($line_matchings[2], 0, $left + $entities_length);
99
                    // maximum lenght is reached, so get off the loop
100
                    break;
101
                }
102
                $truncate     .= $line_matchings[2];
103
                $total_length += $content_length;
104
105
                // if the maximum length is reached, get off the loop
106
                if ($total_length >= $length) {
107
                    break;
108
                }
109
            }
110
        } else {
111
            if (mb_strlen($text) <= $length) {
112
                return $text;
113
            }
114
            $truncate = mb_substr($text, 0, $length - mb_strlen($ending));
115
        }
116
        // if the words shouldn't be cut in the middle...
117
        if (!$exact) {
118
            // ...search the last occurance of a space...
119
            $spacepos = mb_strrpos($truncate, ' ');
120
            if (isset($spacepos)) {
121
                // ...and cut the text in this position
122
                $truncate = mb_substr($truncate, 0, $spacepos);
123
            }
124
        }
125
        // add the defined ending to the text
126
        $truncate .= $ending;
127
        if ($considerHtml) {
128
            // close all unclosed html-tags
129
            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...
130
                $truncate .= '</' . $tag . '>';
131
            }
132
        }
133
134
        return $truncate;
135
    }
136
137
    /**
138
     * @param \Xmf\Module\Helper $helper
139
     * @param array|null         $options
140
     * @return \XoopsFormDhtmlTextArea|\XoopsFormEditor
141
     */
142
    public static function getEditor($helper = null, $options = null)
143
    {
144
        /** @var \XoopsModules\Tdmdownloads\Helper $helper */
145
        if (null === $options) {
146
            $options           = [];
147
            $options['name']   = 'Editor';
148
            $options['value']  = 'Editor';
149
            $options['rows']   = 10;
150
            $options['cols']   = '100%';
151
            $options['width']  = '100%';
152
            $options['height'] = '400px';
153
        }
154
155
        $isAdmin = $helper->isUserAdmin();
156
157
        if (class_exists('XoopsFormEditor')) {
158
            if ($isAdmin) {
159
                $descEditor = new \XoopsFormEditor(ucfirst($options['name']), $helper->getConfig('editorAdmin'), $options, $nohtml = false, $onfailure = 'textarea');
160
            } else {
161
                $descEditor = new \XoopsFormEditor(ucfirst($options['name']), $helper->getConfig('editorUser'), $options, $nohtml = false, $onfailure = 'textarea');
162
            }
163
        } else {
164
            $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 $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

164
            $descEditor = new \XoopsFormDhtmlTextArea(ucfirst($options['name']), $options['name'], $options['value'], '100%', /** @scrutinizer ignore-type */ '100%');
Loading history...
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

164
            $descEditor = new \XoopsFormDhtmlTextArea(ucfirst($options['name']), $options['name'], $options['value'], /** @scrutinizer ignore-type */ '100%', '100%');
Loading history...
165
        }
166
167
        //        $form->addElement($descEditor);
168
169
        return $descEditor;
170
    }
171
172
    //--------------- Custom module methods -----------------------------
173
174
    /**
175
     * @param $permtype
176
     * @param $dirname
177
     * @return mixed
178
     */
179
    public function getItemIds($permtype, $dirname)
180
    {
181
        global $xoopsUser;
182
        static $permissions = [];
183
        if (is_array($permissions) && array_key_exists($permtype, $permissions)) {
184
            return $permissions[$permtype];
185
        }
186
        /** @var \XoopsModuleHandler $moduleHandler */
187
        $moduleHandler = xoops_getHandler('module');
188
        $tdmModule     = $moduleHandler->getByDirname($dirname);
189
        $groups        = is_object($xoopsUser) ? $xoopsUser->getGroups() : XOOPS_GROUP_ANONYMOUS;
190
191
        /** @var \XoopsGroupPermHandler $grouppermHandler */
192
        $grouppermHandler = xoops_getHandler('groupperm');
193
        $categories       = $grouppermHandler->getItemIds($permtype, $groups, $tdmModule->getVar('mid'));
194
195
        return $categories;
196
    }
197
198
    /**
199
     * retourne le nombre de téléchargements dans le catégories enfants d'une catégorie
200
     * @param $mytree
201
     * @param $categories
202
     * @param $entries
203
     * @param $cid
204
     * @return int
205
     */
206
    public function getNumbersOfEntries($mytree, $categories, $entries, $cid)
207
    {
208
        $count     = 0;
209
        $child_arr = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $child_arr is dead and can be removed.
Loading history...
210
        if (in_array($cid, $categories, true)) {
211
            $child = $mytree->getAllChild($cid);
212
            foreach (array_keys($entries) as $i) {
213
                if ($entries[$i]->getVar('cid') == $cid) {
214
                    $count++;
215
                }
216
                foreach (array_keys($child) as $j) {
217
                    if ($entries[$i]->getVar('cid') == $j) {
218
                        $count++;
219
                    }
220
                }
221
            }
222
        }
223
224
        return $count;
225
    }
226
227
    /**
228
     * retourne une image "nouveau" ou "mise à jour"
229
     * @param $time
230
     * @param $status
231
     * @return string
232
     */
233
    public function getStatusImage($time, $status)
234
    {
235
        global $xoopsModuleConfig;
236
        $count     = 7;
237
        $new       = '';
238
        $startdate = (time() - (86400 * $count));
239
        if (1 == $xoopsModuleConfig['showupdated']) {
240
            if ($startdate < $time) {
241
                $language = $GLOBALS['xoopsConfig']['language'];
242
                if (!is_dir(XOOPS_ROOT_PATH . '/modules/tdmdownloads/language/' . $language . '/')) {
243
                    $language = 'english';
244
                }
245
                $img_path = XOOPS_ROOT_PATH . '/modules/tdmdownloads/language/' . $language . '/';
246
                $img_url  = XOOPS_URL . '/modules/tdmdownloads/language/' . $language . '/';
247
                if (1 == $status) {
248
                    if (is_readable($img_path . 'new.png')) {
249
                        $new = '&nbsp;<img src="' . $img_url . 'new.png" alt="' . _MD_TDMDOWNLOADS_INDEX_NEWTHISWEEK . '" title="' . _MD_TDMDOWNLOADS_INDEX_NEWTHISWEEK . '">';
250
                    } else {
251
                        $new = '&nbsp;<img src="' . XOOPS_URL . '/modules/tdmdownloads/language/english/new.png" alt="' . _MD_TDMDOWNLOADS_INDEX_NEWTHISWEEK . '" title="' . _MD_TDMDOWNLOADS_INDEX_NEWTHISWEEK . '">';
252
                    }
253
                } elseif (2 == $status) {
254
                    if (is_readable($img_path . 'updated.png')) {
255
                        $new = '&nbsp;<img src="' . $img_url . 'updated.png" alt="' . _MD_TDMDOWNLOADS_INDEX_UPTHISWEEK . '" title="' . _MD_TDMDOWNLOADS_INDEX_UPTHISWEEK . '">';
256
                    } else {
257
                        $new = '&nbsp;<img src="' . XOOPS_URL . '/modules/tdmdownloads/language/english/updated.png" alt="' . _MD_TDMDOWNLOADS_INDEX_UPTHISWEEK . '" title="' . _MD_TDMDOWNLOADS_INDEX_UPTHISWEEK . '">';
258
                    }
259
                }
260
            }
261
        }
262
263
        return $new;
264
    }
265
266
    /**
267
     * retourne une image "populaire"
268
     * @param $hits
269
     * @return string
270
     */
271
    public function getPopularImage($hits)
272
    {
273
        global $xoopsModuleConfig;
274
        $pop = '';
275
        if ($hits >= $xoopsModuleConfig['popular']) {
276
            $language = $GLOBALS['xoopsConfig']['language'];
277
            if (!is_dir(XOOPS_ROOT_PATH . '/modules/tdmdownloads/language/' . $language . '/')) {
278
                $language = 'english';
279
            }
280
            $img_path = XOOPS_ROOT_PATH . '/modules/tdmdownloads/language/' . $language . '/';
281
            $img_url  = XOOPS_URL . '/modules/tdmdownloads/language/' . $language . '/';
282
            if (is_readable($img_path . 'popular.png')) {
283
                $pop = '&nbsp;<img src="' . $img_url . 'popular.png" alt="' . _MD_TDMDOWNLOADS_INDEX_POPULAR . '" title="' . _MD_TDMDOWNLOADS_INDEX_POPULAR . '">';
284
            } else {
285
                $pop = '&nbsp;<img src ="' . XOOPS_URL . '/modules/tdmdownloads/language/english/popular.png" alt="' . _MD_TDMDOWNLOADS_INDEX_POPULAR . '" title="' . _MD_TDMDOWNLOADS_INDEX_POPULAR . '">';
286
            }
287
        }
288
289
        return $pop;
290
    }
291
292
    /**
293
     * @param $size
294
     * @return string
295
     */
296
    public static function trans_size($size)
297
    {
298
        if ($size > 0) {
299
            $mb = 1024 * 1024;
300
            if ($size > $mb) {
301
                $mysize = sprintf('%01.2f', $size / $mb) . ' MB';
302
            } elseif ($size >= 1024) {
303
                $mysize = sprintf('%01.2f', $size / 1024) . ' KB';
304
            } else {
305
                $mysize = sprintf(_AM_TDMDOWNLOADS_NUMBYTES, $size);
306
            }
307
308
            return $mysize;
309
        }
310
311
        return '';
312
    }
313
314
    /**
315
     * @param        $global
316
     * @param        $key
317
     * @param string $default
318
     * @param string $type
319
     * @return mixed|string
320
     */
321
    public static function cleanVars(&$global, $key, $default = '', $type = 'int')
322
    {
323
        switch ($type) {
324
            case 'string':
325
                $ret = isset($global[$key]) ? filter_var($global[$key], FILTER_SANITIZE_MAGIC_QUOTES) : $default;
326
                break;
327
            case 'int':
328
            default:
329
                $ret = isset($global[$key]) ? filter_var($global[$key], FILTER_SANITIZE_NUMBER_INT) : $default;
330
                break;
331
        }
332
        if (false === $ret) {
333
            return $default;
334
        }
335
336
        return $ret;
337
    }
338
339
    /**
340
     * @param        $mytree
341
     * @param        $key
342
     * @param        $category_array
343
     * @param        $title
344
     * @param string $prefix
345
     * @return string
346
     */
347
    public function getPathTree($mytree, $key, $category_array, $title, $prefix = '')
348
    {
349
        $category_parent = $mytree->getAllParent($key);
350
        $category_parent = array_reverse($category_parent);
351
        $Path            = '';
352
        foreach (array_keys($category_parent) as $j) {
353
            $Path .= $category_parent[$j]->getVar($title) . $prefix;
354
        }
355
        if (array_key_exists($key, $category_array)) {
356
            $first_category = $category_array[$key]->getVar($title);
357
        } else {
358
            $first_category = '';
359
        }
360
        $Path .= $first_category;
361
362
        return $Path;
363
    }
364
365
    /**
366
     * @param        $mytree
367
     * @param        $key
368
     * @param        $category_array
369
     * @param        $title
370
     * @param string $prefix
371
     * @param bool   $link
372
     * @param string $order
373
     * @param bool   $lasturl
374
     * @return string
375
     */
376
    public function getPathTreeUrl($mytree, $key, $category_array, $title, $prefix = '', $link = false, $order = 'ASC', $lasturl = false)
377
    {
378
        global $xoopsModule;
379
        $category_parent = $mytree->getAllParent($key);
380
        if ('ASC' === $order) {
381
            $category_parent = array_reverse($category_parent);
382
            if (true === $link) {
383
                $Path = '<a href="index.php">' . $xoopsModule->name() . '</a>' . $prefix;
384
            } else {
385
                $Path = $xoopsModule->name() . $prefix;
386
            }
387
        } else {
388
            if (array_key_exists($key, $category_array)) {
389
                $first_category = $category_array[$key]->getVar($title);
390
            } else {
391
                $first_category = '';
392
            }
393
            $Path = $first_category . $prefix;
394
        }
395
        foreach (array_keys($category_parent) as $j) {
396
            if (true === $link) {
397
                $Path .= '<a href="viewcat.php?cid=' . $category_parent[$j]->getVar('cat_cid') . '">' . $category_parent[$j]->getVar($title) . '</a>' . $prefix;
398
            } else {
399
                $Path .= $category_parent[$j]->getVar($title) . $prefix;
400
            }
401
        }
402
        if ('ASC' === $order) {
403
            if (array_key_exists($key, $category_array)) {
404
                if (true === $lasturl) {
405
                    $first_category = '<a href="viewcat.php?cid=' . $category_array[$key]->getVar('cat_cid') . '">' . $category_array[$key]->getVar($title) . '</a>';
406
                } else {
407
                    $first_category = $category_array[$key]->getVar($title);
408
                }
409
            } else {
410
                $first_category = '';
411
            }
412
            $Path .= $first_category;
413
        } else {
414
            if (true === $link) {
415
                $Path .= '<a href="index.php">' . $xoopsModule->name() . '</a>';
416
            } else {
417
                $Path .= $xoopsModule->name();
418
            }
419
        }
420
421
        return $Path;
422
    }
423
}
424