Passed
Pull Request — master (#88)
by Michael
08:00 queued 04:03
created

Utility::StringSizeConvert()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 19
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 16
nc 5
nop 1
dl 0
loc 19
rs 9.4222
c 0
b 0
f 0
1
<?php declare(strict_types=1);
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
/**
19
 * Class Utility
20
 */
21
class Utility extends Common\SysUtility
22
{
23
    //--------------- Custom module methods -----------------------------
24
    /**
25
     * @param $permtype
26
     * @param $dirname
27
     * @return mixed
28
     */
29
    public function getItemIds($permtype, $dirname)
30
    {
31
        global $xoopsUser;
32
33
        static $permissions = [];
34
35
        if (\is_array($permissions) && \array_key_exists($permtype, $permissions)) {
36
            return $permissions[$permtype];
37
        }
38
39
        /** @var \XoopsModuleHandler $moduleHandler */
40
41
        $moduleHandler = \xoops_getHandler('module');
42
43
        $tdmModule = $moduleHandler->getByDirname($dirname);
44
45
        $groups = \is_object($xoopsUser) ? $xoopsUser->getGroups() : XOOPS_GROUP_ANONYMOUS;
46
47
        /** @var \XoopsGroupPermHandler $grouppermHandler */
48
        $grouppermHandler = \xoops_getHandler('groupperm');
49
50
        return $grouppermHandler->getItemIds($permtype, $groups, $tdmModule->getVar('mid'));
51
    }
52
53
    /**
54
     * retourne le nombre de téléchargements dans le catégories enfants d'une catégorie
55
     * @param \XoopsModules\Tdmdownloads\Tree        $mytree
56
     * @param                                        $categories
57
     * @param                                        $entries
58
     * @param                                        $cid
59
     * @return int
60
     */
61
    public function getNumbersOfEntries($mytree, $categories, $entries, $cid)
62
    {
63
        $count = 0;
64
65
        $child_arr = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $child_arr is dead and can be removed.
Loading history...
66
67
        if (\in_array($cid, $categories)) {
68
            $child = $mytree->getAllChild($cid);
69
70
            foreach (\array_keys($entries) as $i) {
71
                /** @var \XoopsModules\Tdmdownloads\Downloads[] $entries */
72
73
                if ($entries[$i]->getVar('cid') == $cid) {
74
                    $count++;
75
                }
76
77
                foreach (\array_keys($child) as $j) {
78
                    if ($entries[$i]->getVar('cid') == $j) {
79
                        $count++;
80
                    }
81
                }
82
            }
83
        }
84
85
        return $count;
86
    }
87
88
    /**
89
     * retourne une image "nouveau" ou "mise à jour"
90
     * @param $time
91
     * @param $status
92
     * @return string
93
     */
94
    public function getStatusImage($time, $status)
95
    {
96
        global $xoopsModuleConfig;
97
98
        $moduleDirName = basename(dirname(__DIR__));
99
        $helper = Helper::getInstance();
0 ignored issues
show
Unused Code introduced by
The assignment to $helper is dead and can be removed.
Loading history...
100
101
        $count = 7;
102
103
        $new = '';
104
105
        $startdate = \time() - (86400 * $count);
106
107
        if (1 == $xoopsModuleConfig['showupdated']) {
108
            if ($startdate < $time) {
109
                $language = $GLOBALS['xoopsConfig']['language'];
110
111
                if (!\is_dir(XOOPS_ROOT_PATH . '/modules/' . $moduleDirName . '/language/' . $language . '/')) {
112
                    $language = 'english';
113
                }
114
115
                $img_path = XOOPS_ROOT_PATH . '/modules/' . $moduleDirName . '/language/' . $language . '/';
116
117
                $img_url = XOOPS_URL . '/modules/' . $moduleDirName . '/language/' . $language . '/';
118
119
                if (1 == $status) {
120
                    if (\is_readable($img_path . 'new.png')) {
121
                        $new = '&nbsp;<img src="' . $img_url . 'new.png" alt="' . _MD_TDMDOWNLOADS_INDEX_NEWTHISWEEK . '" title="' . _MD_TDMDOWNLOADS_INDEX_NEWTHISWEEK . '">';
122
                    } else {
123
                        $new = '&nbsp;<img src="' . XOOPS_URL . '/modules/' . $moduleDirName . '/language/english/new.png" alt="' . _MD_TDMDOWNLOADS_INDEX_NEWTHISWEEK . '" title="' . _MD_TDMDOWNLOADS_INDEX_NEWTHISWEEK . '">';
124
                    }
125
                } elseif (2 == $status) {
126
                    if (\is_readable($img_path . 'updated.png')) {
127
                        $new = '&nbsp;<img src="' . $img_url . 'updated.png" alt="' . _MD_TDMDOWNLOADS_INDEX_UPTHISWEEK . '" title="' . _MD_TDMDOWNLOADS_INDEX_UPTHISWEEK . '">';
128
                    } else {
129
                        $new = '&nbsp;<img src="' . XOOPS_URL . '/modules/' . $moduleDirName . '/language/english/updated.png" alt="' . _MD_TDMDOWNLOADS_INDEX_UPTHISWEEK . '" title="' . _MD_TDMDOWNLOADS_INDEX_UPTHISWEEK . '">';
130
                    }
131
                }
132
            }
133
        }
134
135
        return $new;
136
    }
137
138
    /**
139
     * retourne une image "populaire"
140
     * @param $hits
141
     * @return string
142
     */
143
    public function getPopularImage($hits)
144
    {
145
        global $xoopsModuleConfig;
146
        $moduleDirName = basename(dirname(__DIR__));
147
148
        $pop = '';
149
150
        if ($hits >= $xoopsModuleConfig['popular']) {
151
            $language = $GLOBALS['xoopsConfig']['language'];
152
153
            if (!\is_dir(XOOPS_ROOT_PATH . '/modules/' . $moduleDirName . '/language/' . $language . '/')) {
154
                $language = 'english';
155
            }
156
157
            $img_path = XOOPS_ROOT_PATH . '/modules/' . $moduleDirName . '/language/' . $language . '/';
158
159
            $img_url = XOOPS_URL . '/modules/' . $moduleDirName . '/language/' . $language . '/';
160
161
            if (\is_readable($img_path . 'popular.png')) {
162
                $pop = '&nbsp;<img src="' . $img_url . 'popular.png" alt="' . _MD_TDMDOWNLOADS_INDEX_POPULAR . '" title="' . _MD_TDMDOWNLOADS_INDEX_POPULAR . '">';
163
            } else {
164
                $pop = '&nbsp;<img src ="' . XOOPS_URL . '/modules/' . $moduleDirName . '/language/english/popular.png" alt="' . _MD_TDMDOWNLOADS_INDEX_POPULAR . '" title="' . _MD_TDMDOWNLOADS_INDEX_POPULAR . '">';
165
            }
166
        }
167
168
        return $pop;
169
    }
170
171
    /**
172
     * @param int $size
173
     * @return string
174
     */
175
    public static function prettifyBytes($size)
176
    {
177
        if ($size > 0) {
178
            $mb = 1024 * 1024;
179
180
            if ($size > $mb) {
181
                $mysize = \sprintf('%01.2f', $size / $mb) . ' MB';
182
            } elseif ($size >= 1024) {
183
                $mysize = \sprintf('%01.2f', $size / 1024) . ' KB';
184
            } else {
185
                $mysize = \sprintf(_AM_TDMDOWNLOADS_NUMBYTES, $size);
186
            }
187
188
            return $mysize;
189
        }
190
191
        return '';
192
    }
193
194
    /**
195
     * @param        $global
196
     * @param        $key
197
     * @param string $default
198
     * @param string $type
199
     * @return mixed|string
200
     */
201
    public static function cleanVars($global, $key, $default = '', $type = 'int')
202
    {
203
        switch ($type) {
204
            case 'string':
205
                $ret = isset($global[$key]) ? \filter_var($global[$key], \FILTER_SANITIZE_MAGIC_QUOTES) : $default;
0 ignored issues
show
introduced by
The constant FILTER_SANITIZE_MAGIC_QUOTES has been deprecated: 7.4 ( Ignorable by Annotation )

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

205
                $ret = isset($global[$key]) ? \filter_var($global[$key], /** @scrutinizer ignore-deprecated */ \FILTER_SANITIZE_MAGIC_QUOTES) : $default;
Loading history...
206
                break;
207
            case 'int':
208
            default:
209
                $ret = isset($global[$key]) ? \filter_var($global[$key], \FILTER_SANITIZE_NUMBER_INT) : $default;
210
                break;
211
        }
212
213
        if (false === $ret) {
214
            return $default;
215
        }
216
217
        return $ret;
218
    }
219
220
    /**
221
     * @param        $mytree
222
     * @param        $key
223
     * @param        $category_array
224
     * @param        $title
225
     * @param string $prefix
226
     * @return string
227
     */
228
    public static function getPathTree($mytree, $key, $category_array, $title, $prefix = '')
229
    {
230
        /** @var \XoopsObjectTree $mytree */
231
232
        $categoryParent = $mytree->getAllParent($key);
233
234
        $categoryParent = \array_reverse($categoryParent);
235
236
        $path = '';
237
238
        foreach (\array_keys($categoryParent) as $j) {
239
            /** @var \XoopsModules\Tdmdownloads\Category[] $categoryParent */
240
241
            $path .= $categoryParent[$j]->getVar($title) . $prefix;
242
        }
243
244
        if (\array_key_exists($key, $category_array)) {
245
            /** @var \XoopsModules\Tdmdownloads\Category[] $category_array */
246
247
            $firstCategory = $category_array[$key]->getVar($title);
248
        } else {
249
            $firstCategory = '';
250
        }
251
252
        $path .= $firstCategory;
253
254
        return $path;
255
    }
256
257
    /**
258
     * @param \XoopsModules\Tdmdownloads\Tree $mytree
259
     * @param                                 $key
260
     * @param                                 $category_array
261
     * @param                                 $title
262
     * @param string                          $prefix
263
     * @param bool                            $link
264
     * @param string                          $order
265
     * @param bool                            $lasturl
266
     * @return string
267
     */
268
    public static function getPathTreeUrl($mytree, $key, $category_array, $title, $prefix = '', $link = false, $order = 'ASC', $lasturl = false)
269
    {
270
        global $xoopsModule;
271
272
        $categoryParent = $mytree->getAllParent($key);
273
274
        if ('ASC' === $order) {
275
            $categoryParent = \array_reverse($categoryParent);
276
277
            if ($link) {
278
                $path = '<a href="index.php">' . $xoopsModule->name() . '</a>' . $prefix;
279
            } else {
280
                $path = $xoopsModule->name() . $prefix;
281
            }
282
        } else {
283
            if (\array_key_exists($key, $category_array)) {
284
                /** @var \XoopsModules\Tdmdownloads\Category[] $category_array */
285
286
                $firstCategory = $category_array[$key]->getVar($title);
287
            } else {
288
                $firstCategory = '';
289
            }
290
291
            $path = $firstCategory . $prefix;
292
        }
293
294
        foreach (\array_keys($categoryParent) as $j) {
295
            /** @var \XoopsModules\Tdmdownloads\Category[] $categoryParent */
296
297
            if ($link) {
298
                $path .= '<a href="viewcat.php?cid=' . $categoryParent[$j]->getVar('cat_cid') . '">' . $categoryParent[$j]->getVar($title) . '</a>' . $prefix;
299
            } else {
300
                $path .= $categoryParent[$j]->getVar($title) . $prefix;
301
            }
302
        }
303
304
        if ('ASC' === $order) {
305
            if (\array_key_exists($key, $category_array)) {
306
                if ($lasturl) {
307
                    $firstCategory = '<a href="viewcat.php?cid=' . $category_array[$key]->getVar('cat_cid') . '">' . $category_array[$key]->getVar($title) . '</a>';
308
                } else {
309
                    $firstCategory = $category_array[$key]->getVar($title);
310
                }
311
            } else {
312
                $firstCategory = '';
313
            }
314
315
            $path .= $firstCategory;
316
        } else {
317
            if ($link) {
318
                $path .= '<a href="index.php">' . $xoopsModule->name() . '</a>';
319
            } else {
320
                $path .= $xoopsModule->name();
321
            }
322
        }
323
324
        return $path;
325
    }
326
327
    /**
328
     * Utility::convertStringToSize()
329
     *
330
     * @param mixed $stringSize
331
     * @return mixed|int
332
     */
333
    public static function convertStringToSize($stringSize)
334
    {
335
        if ('' != $stringSize) {
336
            $kb = 1024;
337
338
            $mb = 1024 * 1024;
339
340
            $gb = 1024 * 1024 * 1024;
341
342
            $size_value_arr = \explode(' ', $stringSize);
343
344
            if ('B' == $size_value_arr[1]) {
345
                $mysize = $size_value_arr[0];
346
            } elseif ('K' == $size_value_arr[1]) {
347
                $mysize = $size_value_arr[0] * $kb;
348
            } elseif ('M' == $size_value_arr[1]) {
349
                $mysize = $size_value_arr[0] * $mb;
350
            } else {
351
                $mysize = $size_value_arr[0] * $gb;
352
            }
353
354
            return $mysize;
355
        }
356
357
        return 0;
358
    }
359
360
    /**
361
     * Utility::convertSizeToString()
362
     *
363
     * @param mixed $sizeString
364
     * @return mixed|string
365
     */
366
    public static function convertSizeToString($sizeString)
367
    {
368
        $mysizeString = '';
369
370
        if ('' != $sizeString) {
371
            $size_value_arr = \explode(' ', $sizeString);
372
373
            if (\array_key_exists(0, $size_value_arr) && \array_key_exists(1, $size_value_arr)) {
374
                if ('' != $size_value_arr[0]) {
375
                    $mysizeString = '';
376
377
                    switch ($size_value_arr[1]) {
378
                        case 'B':
379
                            $mysizeString = $size_value_arr[0] . ' ' . _AM_TDMDOWNLOADS_BYTES;
380
                            break;
381
                        case 'K':
382
                            $mysizeString = $size_value_arr[0] . ' ' . _AM_TDMDOWNLOADS_KBYTES;
383
                            break;
384
                        case 'M':
385
                            $mysizeString = $size_value_arr[0] . ' ' . _AM_TDMDOWNLOADS_MBYTES;
386
                            break;
387
                        case 'G':
388
                            $mysizeString = $size_value_arr[0] . ' ' . _AM_TDMDOWNLOADS_GBYTES;
389
                            break;
390
                        case 'T':
391
                            $mysizeString = $size_value_arr[0] . ' ' . _AM_TDMDOWNLOADS_TBYTES;
392
                            break;
393
                    }
394
395
                    return $mysizeString;
396
                }
397
            }
398
        }
399
400
        return $mysizeString;
401
    }
402
403
    /**
404
     * Utility::getFileSize()
405
     *
406
     * @param mixed $url
407
     * @return mixed|string
408
     */
409
    public static function getFileSize($url)
410
    {
411
        if (\function_exists('curl_init') && false !== ($curlHandle = \curl_init($url))) {
412
            \curl_setopt($curlHandle, \CURLOPT_RETURNTRANSFER, true);
413
414
            \curl_setopt($curlHandle, \CURLOPT_HEADER, true);
415
416
            \curl_setopt($curlHandle, \CURLOPT_NOBODY, true);
417
418
            \curl_setopt($curlHandle, \CURLOPT_SSL_VERIFYPEER, true); //TODO: how to avoid an error when 'Peer's Certificate issuer is not recognized'
419
420
            $curlReturn = \curl_exec($curlHandle);
421
422
            if (false === $curlReturn) {
423
                \trigger_error(\curl_error($curlHandle));
424
425
                $size = 0;
426
            } else {
427
                $size = \curl_getinfo($curlHandle, \CURLINFO_CONTENT_LENGTH_DOWNLOAD);
428
            }
429
430
            \curl_close($curlHandle);
431
432
            if ($size <= 0) {
433
                return 0;
434
            }
435
436
            return self::convertFileSize($size);
437
        }
438
439
        return 0;
440
    }
441
442
    /**
443
     * Utility::convertFileSize()
444
     *
445
     * @param mixed $size
446
     * @return mixed|string
447
     */
448
    public static function convertFileSize($size)
449
    {
450
        if ($size > 0) {
451
            $kb = 1024;
452
453
            $mb = 1024 * 1024;
454
455
            $gb = 1024 * 1024 * 1024;
456
457
            if ($size >= $gb) {
458
                $mysize = \sprintf('%01.2f', $size / $gb) . ' ' . 'G';
459
            } elseif ($size >= $mb) {
460
                $mysize = \sprintf('%01.2f', $size / $mb) . ' ' . 'M';
461
            } elseif ($size >= $kb) {
462
                $mysize = \sprintf('%01.2f', $size / $kb) . ' ' . 'K';
463
            } else {
464
                $mysize = \sprintf('%01.2f', $size) . ' ' . 'B';
465
            }
466
467
            return $mysize;
468
        }
469
470
        return '';
471
    }
472
473
    /**
474
     * @param $val
475
     * @return float|int
476
     */
477
    public static function returnBytes($val)
478
    {
479
        switch (\mb_substr($val, -1)) {
480
            case 'K':
481
            case 'k':
482
                return (int)$val * 1024;
483
            case 'M':
484
            case 'm':
485
                return (int)$val * 1048576;
486
            case 'G':
487
            case 'g':
488
                return (int)$val * 1073741824;
489
            default:
490
                return $val;
491
        }
492
    }
493
}
494