Passed
Push — master ( 919ce4...d1101e )
by Michael
03:15 queued 11s
created

Utility::getMoneyFormat()   F

Complexity

Conditions 30
Paths > 20000

Size

Total Lines 85
Code Lines 70

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 70
dl 0
loc 85
rs 0
c 1
b 0
f 0
cc 30
nc 172034
nop 2

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
namespace XoopsModules\Adslight;
6
7
/*
8
 * You may not change or alter any portion of this comment or credits
9
 * of supporting developers from this source code or any supporting source code
10
 * which is considered copyrighted (c) material of the original comment or credit authors.
11
 *
12
 * This program is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
15
 */
16
17
/**
18
 * @copyright    XOOPS Project (https://xoops.org)
19
 * @license      GNU GPL 2 or later (https://www.gnu.org/licenses/gpl-2.0.html)
20
 * @author       XOOPS Development Team
21
 * @author       Pascal Le Boustouller: original author ([email protected])
22
 * @author       Luc Bizet (www.frxoops.org)
23
 * @author       jlm69 (www.jlmzone.com)
24
 * @author       mamba (www.xoops.org)
25
 */
26
27
use Xmf\Request;
28
use XoopsModules\Adslight\{
29
    Common
30
};
31
32
33
/**
34
 * Class Utility
35
 */
36
class Utility extends Common\SysUtility
37
{
38
    //--------------- Custom module methods -----------------------------
39
40
    public static function expireAd(): void
41
    {
42
        global $xoopsDB, $xoopsConfig, $xoopsModule, $myts, $meta;
43
44
        $datenow = \time();
45
        $message = '';
46
47
        $result5 = $xoopsDB->query('SELECT lid, title, expire, type, desctext, date_created, email, submitter, photo, valid, hits, comments, remind FROM ' . $xoopsDB->prefix('adslight_listing') . " WHERE valid='Yes'");
48
49
        while (false !== [$lids, $title, $expire, $type, $desctext, $dateann, $email, $submitter, $photo, $valid, $hits, $comments, $remind] = $xoopsDB->fetchRow($result5)) {
50
            $title     = \htmlspecialchars($title, \ENT_QUOTES | \ENT_HTML5);
51
            $expire    = \htmlspecialchars($expire, \ENT_QUOTES | \ENT_HTML5);
52
            $type      = \htmlspecialchars($type, \ENT_QUOTES | \ENT_HTML5);
53
            $desctext  = &$myts->displayTarea($desctext, 1, 1, 1, 1, 1);
54
            $submitter = \htmlspecialchars($submitter, \ENT_QUOTES | \ENT_HTML5);
55
            $remind    = \htmlspecialchars($remind, \ENT_QUOTES | \ENT_HTML5);
56
            $supprdate = $dateann + ($expire * 86400);
57
            $almost    = $GLOBALS['xoopsModuleConfig']['adslight_almost'];
58
59
            // give warning that add is about to expire
60
61
            if ($almost > 0 && ($supprdate - $almost * 86400) < $datenow
62
                && 'Yes' === $valid
63
                && 0 === $remind) {
64
                $xoopsDB->queryF('UPDATE ' . $xoopsDB->prefix('adslight_listing') . " SET remind='1' WHERE lid=${lids}");
65
66
                if ($email) {
67
                    $tags               = [];
68
                    $subject            = '' . \_ADSLIGHT_ALMOST . '';
69
                    $tags['TITLE']      = $title;
70
                    $tags['HELLO']      = '' . \_ADSLIGHT_HELLO . '';
71
                    $tags['YOUR_AD_ON'] = '' . \_ADSLIGHT_YOUR_AD_ON . '';
72
                    $tags['VEDIT_AD']   = '' . \_ADSLIGHT_VEDIT_AD . '';
73
                    $tags['YOUR_AD']    = '' . \_ADSLIGHT_YOUR_AD . '';
74
                    $tags['SOON']       = '' . \_ADSLIGHT_SOON . '';
75
                    $tags['VIEWED']     = '' . \_ADSLIGHT_VU . '';
76
                    $tags['TIMES']      = '' . \_ADSLIGHT_TIMES . '';
77
                    $tags['WEBMASTER']  = '' . \_ADSLIGHT_WEBMASTER . '';
78
                    $tags['THANKS']     = '' . \_ADSLIGHT_THANKS . '';
79
                    $tags['TYPE']       = static::getNameType($type);
80
                    $tags['DESCTEXT']   = $desctext;
81
                    $tags['HITS']       = $hits;
82
                    $tags['META_TITLE'] = $meta['title'];
83
                    $tags['SUBMITTER']  = $submitter;
84
                    $tags['DURATION']   = $expire;
85
                    $tags['LINK_URL']   = XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname') . '/viewads.php?' . '&lid=' . $lids;
86
                    $mail               = \getMailer();
87
                    $mail->setTemplateDir(XOOPS_ROOT_PATH . '/modules/' . $xoopsModule->getVar('dirname') . '/language/' . $xoopsConfig['language'] . '/mail_template/');
88
                    $mail->setTemplate('listing_expires.tpl');
89
                    $mail->useMail();
90
                    $mail->multimailer->isHTML(true);
91
                    $mail->setFromName($meta['title']);
92
                    $mail->setFromEmail($xoopsConfig['adminmail']);
93
                    $mail->setToEmails($email);
94
                    $mail->setSubject($subject);
95
                    $mail->assign($tags);
96
                    $mail->send();
97
                    echo $mail->getErrors();
98
                }
99
            }
100
101
            // expire ad
102
103
            if ($supprdate < $datenow) {
104
                if (0 !== $photo) {
105
                    $result2 = $xoopsDB->query('SELECT url FROM ' . $xoopsDB->prefix('adslight_pictures') . ' WHERE lid=' . $xoopsDB->escape($lids));
106
107
                    while (false !== [$url] = $xoopsDB->fetchRow($result2)) {
108
                        $destination  = XOOPS_ROOT_PATH . '/uploads/adslight';
109
                        $destination2 = XOOPS_ROOT_PATH . '/uploads/adslight/thumbs';
110
                        $destination3 = XOOPS_ROOT_PATH . '/uploads/adslight/midsize';
111
                        if (\is_file("${destination}/${url}")) {
112
                            \unlink("${destination}/${url}");
113
                        }
114
                        if (\is_file("${destination2}/thumb_${url}")) {
115
                            \unlink("${destination2}/thumb_${url}");
116
                        }
117
                        if (\is_file("${destination3}/resized_${url}")) {
118
                            \unlink("${destination3}/resized_${url}");
119
                        }
120
                    }
121
                }
122
123
                $xoopsDB->queryF('DELETE FROM ' . $xoopsDB->prefix('adslight_listing') . ' WHERE lid=' . $xoopsDB->escape($lids));
124
125
                //  Specification for Japan:
126
                //  $message = ""._ADS_HELLO." $submitter,\n\n"._ADS_STOP2."\n $type : $title\n $desctext\n"._ADS_STOP3."\n\n"._ADS_VU." $lu "._ADS_VU2."\n\n"._ADS_OTHER." ".XOOPS_URL."/modules/myAds\n\n"._ADS_THANK."\n\n"._ADS_TEAM." ".$meta['title']."\n".XOOPS_URL."";
127
                if ($email) {
128
                    $tags               = [];
129
                    $subject            = '' . \_ADSLIGHT_STOP . '';
130
                    $tags['TITLE']      = $title;
131
                    $tags['HELLO']      = '' . \_ADSLIGHT_HELLO . '';
132
                    $tags['TYPE']       = static::getNameType($type);
133
                    $tags['DESCTEXT']   = $desctext;
134
                    $tags['HITS']       = $hits;
135
                    $tags['META_TITLE'] = $meta['title'] ?? '';
136
                    $tags['SUBMITTER']  = $submitter;
137
                    $tags['YOUR_AD_ON'] = '' . \_ADSLIGHT_YOUR_AD_ON . '';
138
                    $tags['EXPIRED']    = '' . \_ADSLIGHT_EXPIRED . '';
139
                    $tags['MESSTEXT']   = \stripslashes($message);
140
                    $tags['OTHER']      = '' . \_ADSLIGHT_OTHER . '';
141
                    $tags['WEBMASTER']  = '' . \_ADSLIGHT_WEBMASTER . '';
142
                    $tags['THANKS']     = '' . \_ADSLIGHT_THANKS . '';
143
                    $tags['VIEWED']     = '' . \_ADSLIGHT_VU . '';
144
                    $tags['TIMES']      = '' . \_ADSLIGHT_TIMES . '';
145
                    $tags['TEAM']       = '' . \_ADSLIGHT_TEAM . '';
146
                    $tags['DURATION']   = $expire;
147
                    $tags['LINK_URL']   = XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname') . '/viewads.php?' . '&lid=' . $lids;
148
                    $mail               = \getMailer();
149
                    $mail->setTemplateDir(XOOPS_ROOT_PATH . '/modules/' . $xoopsModule->getVar('dirname') . '/language/' . $xoopsConfig['language'] . '/mail_template/');
150
                    $mail->setTemplate('listing_expired.tpl');
151
                    $mail->useMail();
152
                    $mail->multimailer->isHTML(true);
153
                    $mail->setFromName($meta['title']);
154
                    $mail->setFromEmail($xoopsConfig['adminmail']);
155
                    $mail->setToEmails($email);
156
                    $mail->setSubject($subject);
157
                    $mail->assign($tags);
158
                    $mail->send();
159
                    echo $mail->getErrors();
160
                }
161
            }
162
        }
163
    }
164
165
    //updates rating data in itemtable for a given user
166
167
    /**
168
     * @param $sel_id
169
     */
170
    public static function updateUserRating($sel_id): void
171
    {
172
        global $xoopsDB;
173
174
        $usid = Request::getInt('usid', 0, 'GET');
0 ignored issues
show
Unused Code introduced by
The assignment to $usid is dead and can be removed.
Loading history...
175
176
        $query = 'SELECT rating FROM ' . $xoopsDB->prefix('adslight_user_votedata') . ' WHERE usid=' . $xoopsDB->escape($sel_id) . ' ';
177
        //echo $query;
178
        $voteresult  = $xoopsDB->query($query);
179
        $votesDB     = $xoopsDB->getRowsNum($voteresult);
180
        $totalrating = 0;
181
        while (false !== [$rating] = $xoopsDB->fetchRow($voteresult)) {
182
            $totalrating += $rating;
183
        }
184
        $finalrating = $totalrating / $votesDB;
185
        $finalrating = \number_format($finalrating, 4);
186
        $query = 'UPDATE ' . $xoopsDB->prefix('adslight_listing') . " SET user_rating=${finalrating}, user_votes=${votesDB} WHERE usid=" . $xoopsDB->escape($sel_id) . '';
187
        //echo $query;
188
        $xoopsDB->query($query) || exit();
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...
189
    }
190
191
    //updates rating data in itemtable for a given item
192
193
    /**
194
     * @param $sel_id
195
     */
196
    public static function updateItemRating($sel_id): void
197
    {
198
        global $xoopsDB;
199
200
        $lid = Request::getInt('lid', 0, 'GET');
0 ignored issues
show
Unused Code introduced by
The assignment to $lid is dead and can be removed.
Loading history...
201
202
        $query = 'SELECT rating FROM ' . $xoopsDB->prefix('adslight_item_votedata') . ' WHERE lid=' . $xoopsDB->escape($sel_id) . ' ';
203
        //echo $query;
204
        $voteresult  = $xoopsDB->query($query);
205
        $votesDB     = $xoopsDB->getRowsNum($voteresult);
206
        $totalrating = 0;
207
        while (false !== [$rating] = $xoopsDB->fetchRow($voteresult)) {
208
            $totalrating += $rating;
209
        }
210
        $finalrating = $totalrating / $votesDB;
211
        $finalrating = \number_format($finalrating, 4);
212
        $query = 'UPDATE ' . $xoopsDB->prefix('adslight_listing') . " SET item_rating=${finalrating}, item_votes=${votesDB} WHERE lid=" . $xoopsDB->escape($sel_id) . '';
213
        //echo $query;
214
        $xoopsDB->query($query) || exit();
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...
215
    }
216
217
    /**
218
     * @param        $sel_id
219
     * @param string $status
220
     */
221
    public static function getTotalItems($sel_id, $status = ''): int
0 ignored issues
show
Unused Code introduced by
The parameter $status is not used and could be removed. ( Ignorable by Annotation )

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

221
    public static function getTotalItems($sel_id, /** @scrutinizer ignore-unused */ $status = ''): int

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
222
    {
223
        global $xoopsDB, $mytree;
224
        $categories = self::getMyItemIds('adslight_view');
225
        $count      = 0;
226
        $arr        = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $arr is dead and can be removed.
Loading history...
227
        if (\in_array($sel_id, $categories, true)) {
228
            $query = 'SELECT SQL_CACHE count(*) FROM ' . $xoopsDB->prefix('adslight_listing') . ' WHERE cid=' . (int)$sel_id . " AND valid='Yes' AND status!='1'";
229
230
            $result = $xoopsDB->query($query);
231
            [$thing] = $xoopsDB->fetchRow($result);
232
            $count = $thing;
233
            $arr   = $mytree->getAllChildId($sel_id);
234
            foreach ($arr as $iValue) {
235
                if (\in_array($iValue, $categories, true)) {
236
                    $query2 = 'SELECT SQL_CACHE count(*) FROM ' . $xoopsDB->prefix('adslight_listing') . ' WHERE cid=' . (int)$iValue . " AND valid='Yes' AND status!='1'";
237
238
                    $result2 = $xoopsDB->query($query2);
239
                    [$thing] = $xoopsDB->fetchRow($result2);
240
                    $count += $thing;
241
                }
242
            }
243
        }
244
245
        return (int)$count;
246
    }
247
248
    /**
249
     * @param $permtype
250
     */
251
    public static function getMyItemIds($permtype)
252
    {
253
        static $permissions = [];
254
        if (\is_array($permissions)
255
            && \array_key_exists($permtype, $permissions)) {
256
            return $permissions[$permtype];
257
        }
258
259
        /** @var \XoopsModuleHandler $moduleHandler */
260
        $moduleHandler = \xoops_getHandler('module');
261
        $myModule      = $moduleHandler->getByDirname('adslight');
262
        $groups        = \is_object($GLOBALS['xoopsUser']) ? $GLOBALS['xoopsUser']->getGroups() : XOOPS_GROUP_ANONYMOUS;
263
        /** @var \XoopsGroupPermHandler $grouppermHandler */
264
        $grouppermHandler       = \xoops_getHandler('groupperm');
265
        $categories             = $grouppermHandler->getItemIds($permtype, $groups, $myModule->getVar('mid'));
266
        $permissions[$permtype] = $categories;
267
268
        return $categories;
269
    }
270
271
    /**
272
     * Returns a module's option
273
     * @param string $option module option's name
274
     * @param string $repmodule
275
     *
276
     * @return bool|mixed option's value
277
     */
278
    public static function getModuleOption($option, $repmodule = 'adslight')
279
    {
280
        global $xoopsModule;
281
        $helper = \XoopsModules\Adslight\Helper::getInstance();
282
        static $tbloptions = [];
283
        if (\is_array($tbloptions) && \array_key_exists($option, $tbloptions)) {
284
            return $tbloptions[$option];
285
        }
286
287
        $retval = false;
288
        if (isset($GLOBALS['xoopsModuleConfig'])
289
            && (\is_object($xoopsModule)
290
                && $xoopsModule->getVar('dirname') === $repmodule
291
                && $xoopsModule->getVar('isactive'))) {
292
            if (isset($GLOBALS['xoopsModuleConfig'][$option])) {
293
                $retval = $GLOBALS['xoopsModuleConfig'][$option];
294
            }
295
        } else {
296
            /** @var \XoopsModuleHandler $moduleHandler */
297
            $moduleHandler = \xoops_getHandler('module');
298
            $module        = $moduleHandler->getByDirname($repmodule);
299
            /** @var \XoopsConfigHandler $configHandler */
300
            $configHandler = \xoops_getHandler('config');
301
            if ($module) {
302
                $moduleConfig = $configHandler->getConfigsByCat(0, $GLOBALS['xoopsModule']->getVar('mid'));
0 ignored issues
show
Unused Code introduced by
The assignment to $moduleConfig is dead and can be removed.
Loading history...
303
                if (null !== $helper->getConfig($option)) {
304
                    $retval = $helper->getConfig($option);
305
                }
306
            }
307
        }
308
        $tbloptions[$option] = $retval;
309
310
        return $retval;
311
    }
312
313
    public static function showImage(): void
314
    {
315
        echo "<script type=\"text/javascript\">\n";
316
        echo "<!--\n\n";
317
        echo "function showimage() {\n";
318
        echo "if (!document.images)\n";
319
        echo "return\n";
320
        echo "document.images.avatar.src=\n";
321
        echo "'" . XOOPS_URL . "/modules/adslight/assets/images/img_cat/' + document.imcat.img.options[document.imcat.img.selectedIndex].value\n";
322
        echo "}\n\n";
323
        echo "//-->\n";
324
        echo "</script>\n";
325
    }
326
327
    //Reusable Link Sorting Functions
328
329
    /**
330
     * @param $orderby
331
     */
332
    public static function convertOrderByIn($orderby): string
333
    {
334
        switch (\trim($orderby)) {
335
            case 'titleA':
336
                $orderby = 'title ASC';
337
                break;
338
            case 'dateA':
339
                $orderby = 'date_created ASC';
340
                break;
341
            case 'hitsA':
342
                $orderby = 'hits ASC';
343
                break;
344
            case 'priceA':
345
                $orderby = 'price ASC';
346
                break;
347
            case 'titleD':
348
                $orderby = 'title DESC';
349
                break;
350
            case 'hitsD':
351
                $orderby = 'hits DESC';
352
                break;
353
            case 'priceD':
354
                $orderby = 'price DESC';
355
                break;
356
            case'dateD':
357
            default:
358
                $orderby = 'date_created DESC';
359
                break;
360
        }
361
362
        return $orderby;
363
    }
364
365
    /**
366
     * @param $orderby
367
     */
368
    public static function convertOrderByTrans($orderby): string
369
    {
370
        $orderbyTrans = '';
371
        if ('hits ASC' === $orderby) {
372
            $orderbyTrans = '' . \_ADSLIGHT_POPULARITYLTOM . '';
373
        }
374
        if ('hits DESC' === $orderby) {
375
            $orderbyTrans = '' . \_ADSLIGHT_POPULARITYMTOL . '';
376
        }
377
        if ('title ASC' === $orderby) {
378
            $orderbyTrans = '' . \_ADSLIGHT_TITLEATOZ . '';
379
        }
380
        if ('title DESC' === $orderby) {
381
            $orderbyTrans = '' . \_ADSLIGHT_TITLEZTOA . '';
382
        }
383
        if ('date_created ASC' === $orderby) {
384
            $orderbyTrans = '' . \_ADSLIGHT_DATEOLD . '';
385
        }
386
        if ('date_created DESC' === $orderby) {
387
            $orderbyTrans = '' . \_ADSLIGHT_DATENEW . '';
388
        }
389
        if ('price ASC' === $orderby) {
390
            $orderbyTrans = \_ADSLIGHT_PRICELTOH;
391
        }
392
        if ('price DESC' === $orderby) {
393
            $orderbyTrans = '' . \_ADSLIGHT_PRICEHTOL . '';
394
        }
395
396
        return $orderbyTrans;
397
    }
398
399
    /**
400
     * @param $orderby
401
     */
402
    public static function convertOrderByOut($orderby): string
403
    {
404
        if ('title ASC' === $orderby) {
405
            $orderby = 'titleA';
406
        }
407
        if ('date_created ASC' === $orderby) {
408
            $orderby = 'dateA';
409
        }
410
        if ('hits ASC' === $orderby) {
411
            $orderby = 'hitsA';
412
        }
413
        if ('price ASC' === $orderby) {
414
            $orderby = 'priceA';
415
        }
416
        if ('title DESC' === $orderby) {
417
            $orderby = 'titleD';
418
        }
419
        if ('date_created DESC' === $orderby) {
420
            $orderby = 'dateD';
421
        }
422
        if ('hits DESC' === $orderby) {
423
            $orderby = 'hitsD';
424
        }
425
        if ('price DESC' === $orderby) {
426
            $orderby = 'priceD';
427
        }
428
429
        return $orderby;
430
    }
431
432
    /**
433
     * @param $tablename
434
     */
435
    public static function checkTableExists($tablename): bool
436
    {
437
        global $xoopsDB;
438
        $result = $xoopsDB->queryF("SHOW TABLES LIKE '${tablename}'");
439
440
        return $xoopsDB->getRowsNum($result) > 0;
441
    }
442
443
    /**
444
     * @param $fieldname
445
     * @param $table
446
     */
447
    public static function checkFieldExists($fieldname, $table): bool
448
    {
449
        global $xoopsDB;
450
        $result = $xoopsDB->queryF("SHOW COLUMNS FROM ${table} LIKE '${fieldname}'");
451
452
        return $xoopsDB->getRowsNum($result) > 0;
453
    }
454
455
    /**
456
     * @param $cid
457
     */
458
    public static function getCatNameFromId($cid): bool
459
    {
460
        global $xoopsDB, $myts;
461
462
        $sql = 'SELECT SQL_CACHE title FROM ' . $xoopsDB->prefix('adslight_categories') . " WHERE cid = '${cid}'";
463
464
        if (!$result = $xoopsDB->query($sql)) {
465
            return false;
466
        }
467
468
        if (!$arr = $xoopsDB->fetchArray($result)) {
469
            return false;
470
        }
471
472
        return $arr['title'];
473
    }
474
475
476
    public static function goCategory(): array
477
    {
478
        global $xoopsDB;
479
480
        $xoopsTree = new \XoopsTree($xoopsDB->prefix('adslight_categories'), 'cid', 'pid');
481
        $jump      = XOOPS_URL . '/modules/adslight/viewcats.php?cid=';
482
        \ob_start();
483
        $xoopsTree->makeMySelBox('title', 'title', 0, 1, 'pid', 'location="' . $jump . '"+this.options[this.selectedIndex].value');
484
        $block['selectbox'] = \ob_get_clean();
0 ignored issues
show
Comprehensibility Best Practice introduced by
$block was never initialized. Although not strictly required by PHP, it is generally a good practice to add $block = array(); before regardless.
Loading history...
485
486
        return $block;
487
    }
488
489
    // ADSLIGHT Version 2 //
490
    // Fonction rss.php RSS par categories
491
492
493
    public static function returnAllAdsRss(): array
494
    {
495
        global $xoopsDB;
496
497
        $cid = Request::getInt('cid', null, 'GET');
498
499
        $result = [];
500
501
        $sql = 'SELECT lid, title, price, date_created, town FROM ' . $xoopsDB->prefix('adslight_listing') . " WHERE valid='yes' AND cid=" . $xoopsDB->escape($cid) . ' ORDER BY date_created DESC';
502
503
        $resultValues = $xoopsDB->query($sql);
504
        while (false !== ($resultTemp = $xoopsDB->fetchBoth($resultValues))) {
505
            $result[] = $resultTemp;
506
        }
507
508
        return $result;
509
    }
510
511
    // Fonction fluxrss.php RSS Global
512
513
514
    public static function returnAllAdsFluxRss(): array
515
    {
516
        global $xoopsDB;
517
518
        $result = [];
519
520
        $sql = 'SELECT lid, title, price, desctext, date_created, town FROM ' . $xoopsDB->prefix('adslight_listing') . " WHERE valid='yes' ORDER BY date_created DESC LIMIT 0,15";
521
522
        $resultValues = $xoopsDB->query($sql);
523
        while (false !== ($resultTemp = $xoopsDB->fetchBoth($resultValues))) {
524
            $result[] = $resultTemp;
525
        }
526
527
        return $result;
528
    }
529
530
    /**
531
     * @param $type
532
     */
533
    public static function getNameType($type)
534
    {
535
        global $xoopsDB;
536
        $sql = $xoopsDB->query('SELECT nom_type FROM ' . $xoopsDB->prefix('adslight_type') . " WHERE id_type='" . $xoopsDB->escape($type) . "'");
537
        [$nom_type] = $xoopsDB->fetchRow($sql);
538
539
        return $nom_type;
540
    }
541
542
    /**
543
     * @param $format
544
     * @param $number
545
     */
546
    public static function getMoneyFormat(
547
        $format,
548
        $number
549
    ) {
550
        $regex = '/%((?:[\^!\-]|\+|\(|\=.)*)(\d+)?' . '(?:#(\d+))?(?:\.(\d+))?([in%])/';
551
        if ('C' === \setlocale(\LC_MONETARY, 0)) {
552
            \setlocale(\LC_MONETARY, '');
553
        }
554
        \setlocale(\LC_ALL, 'en_US');
555
        //        setlocale(LC_ALL, 'fr_FR');
556
        $locale = \localeconv();
557
        \preg_match_all($regex, $format, $matches, \PREG_SET_ORDER);
558
        foreach ($matches as $fmatch) {
559
            $value      = (float)$number;
560
            $flags      = [
561
                'fillchar'  => \preg_match('#\=(.)#', $fmatch[1], $match) ? $match[1] : ' ',
562
                'nogroup'   => \preg_match('#\^#', $fmatch[1]) > 0,
563
                'usesignal' => \preg_match('/\+|\(/', $fmatch[1], $match) ? $match[0] : '+',
564
                'nosimbol'  => \preg_match('#\!#', $fmatch[1]) > 0,
565
                'isleft'    => \preg_match('#\-#', $fmatch[1]) > 0,
566
            ];
567
            $width      = \trim($fmatch[2]) ? (int)$fmatch[2] : 0;
568
            $left       = \trim($fmatch[3]) ? (int)$fmatch[3] : 0;
569
            $right      = \trim($fmatch[4]) ? (int)$fmatch[4] : $locale['int_frac_digits'];
570
            $conversion = $fmatch[5];
571
            $positive   = true;
572
            if ($value < 0) {
573
                $positive = false;
574
                $value    *= -1;
575
            }
576
            $letter = $positive ? 'p' : 'n';
577
            $prefix = $suffix = $cprefix = $csuffix = $signal = '';
0 ignored issues
show
Unused Code introduced by
The assignment to $signal is dead and can be removed.
Loading history...
578
            $signal = $positive ? $locale['positive_sign'] : $locale['negative_sign'];
579
            switch (true) {
580
                case 1 === $locale["{$letter}_sign_posn"]
581
                     && '+' === $flags['usesignal']:
582
                    $prefix = $signal;
583
                    break;
584
                case 2 === $locale["{$letter}_sign_posn"]
585
                     && '+' === $flags['usesignal']:
586
                    $suffix = $signal;
587
                    break;
588
                case 3 === $locale["{$letter}_sign_posn"]
589
                     && '+' === $flags['usesignal']:
590
                    $cprefix = $signal;
591
                    break;
592
                case 4 === $locale["{$letter}_sign_posn"]
593
                     && '+' === $flags['usesignal']:
594
                    $csuffix = $signal;
595
                    break;
596
                case '(' === $flags['usesignal']:
597
                case 0 === $locale["{$letter}_sign_posn"]:
598
                    $prefix = '(';
599
                    $suffix = ')';
600
                    break;
601
            }
602
            if ($flags['nosimbol']) {
603
                $currency = '';
604
            } else {
605
                $currency = $cprefix . ('i' === $conversion ? $locale['int_curr_symbol'] : $locale['currency_symbol']) . $csuffix;
606
            }
607
            $space = $locale["{$letter}_sep_by_space"] ? ' ' : '';
608
            $value = \number_format(
609
                $value,
610
                $right,
611
                $locale['mon_decimal_point'],
612
                $flags['nogroup'] ? '' : $locale['mon_thousands_sep']
613
            );
614
            $value = @\explode($locale['mon_decimal_point'], $value);
615
            $n     = \mb_strlen($prefix) + \mb_strlen($currency) + \mb_strlen($value[0]);
616
            if ($left > 0 && $left > $n) {
617
                $value[0] = \str_repeat($flags['fillchar'], $left - $n) . $value[0];
618
            }
619
            $value = \implode($locale['mon_decimal_point'], $value);
620
            if ($locale["{$letter}_cs_precedes"]) {
621
                $value = $prefix . $currency . $space . $value . $suffix;
622
            } else {
623
                $value = $prefix . $value . $space . $currency . $suffix;
624
            }
625
            if ($width > 0) {
626
                $value = \str_pad($value, $width, $flags['fillchar'], $flags['isleft'] ? \STR_PAD_RIGHT : \STR_PAD_LEFT);
627
            }
628
            $format = \str_replace($fmatch[0], $value, $format);
629
        }
630
        return $format;
631
    }
632
633
    /**
634
     * Saves permissions for the selected category
635
     *
636
     *   saveCategory_Permissions()
637
     *
638
     * @param array  $groups : group with granted permission
639
     * @param        $categoryId
640
     * @param        $permName
641
     * @return bool : TRUE if the no errors occured
642
     */
643
    public static function saveCategoryPermissions($groups, $categoryId, $permName): bool
644
    {
645
        global $xoopsModule;
646
        $helper = \XoopsModules\Adslight\Helper::getInstance();
0 ignored issues
show
Unused Code introduced by
The assignment to $helper is dead and can be removed.
Loading history...
647
648
        $result = true;
649
        //        $xoopsModule = sf_getModuleInfo();
650
        //        $moduleId = $helper->getModule()->getVar('mid');
651
        $moduleId = $xoopsModule->getVar('mid');
652
653
        $grouppermHandler = \xoops_getHandler('groupperm');
654
        // First, if the permissions are already there, delete them
655
        /** @var \XoopsGroupPermHandler $grouppermHandler */
656
        $grouppermHandler->deleteByModule($moduleId, $permName, $categoryId);
657
        // Save the new permissions
658
        if (\count($groups) > 0) {
659
            foreach ($groups as $groupId) {
660
                $grouppermHandler->addRight($permName, $categoryId, $groupId, $moduleId);
661
            }
662
        }
663
664
        return $result;
665
    }
666
667
    /***********************************************************************
668
     * $fldVersion : dossier version de fancybox
669
     ***********************************************************************/
670
    public static function load_lib_js(): void
671
    {
672
        global $xoTheme, $xoopsModuleConfig;
673
674
        $fld = XOOPS_URL . '/modules/adslight/' . 'assets/';
675
676
        if (1 === $GLOBALS['xoopsModuleConfig']['adslight_lightbox']) {
677
            // $xoTheme->addScript(XOOPS_URL . '/browse.php?Frameworks/jquery/plugins/jquery.lightbox.js');
678
            // $xoTheme->addStyleSheet(XOOPS_URL . '/browse.php?Frameworks/jquery/plugins/jquery.lightbox.js');
679
680
            $xoTheme->addScript($fld . '/js/lightbox/js/lightbox.js');
681
            $xoTheme->addStyleSheet($fld . '/js/lightbox/css/lightbox.css');
682
        }
683
            //$xoTheme->addStyleSheet($fld . "/css/galery.css" type="text/css" media="screen");
684
685
686
        /*
687
                    if (1 == $GLOBALS['xoopsModuleConfig']['adslight_lightbox']) {
688
                        $header_lightbox = '<link rel="stylesheet" href="' . XOOPS_URL . '/modules/adslight/assets/css/adslight.css" type="text/css" media="all" >
689
        <script type="text/javascript" src="assets/lightbox/js/jquery-1.7.2.min.js"></script>
690
        <script type="text/javascript" src="assets/lightbox/js/jquery-ui-1.8.18.custom.min"></script>
691
        <script type="text/javascript" src="assets/lightbox/js/jquery.smooth-scroll.min.js"></script>
692
        <script type="text/javascript" src="assets/lightbox/js/lightbox.js"></script>
693
694
        <link rel="stylesheet" href="assets/css/galery.css" type="text/css" media="screen" >
695
        <link rel="stylesheet" type="text/css" media="screen" href="assets/lightbox/css/lightbox.css"></link>';
696
                    } else {
697
                        $header_lightbox = '<link rel="stylesheet" href="' . XOOPS_URL . '/modules/adslight/assets/css/adslight.css" type="text/css" media="all" >
698
        <link rel="stylesheet" href="assets/css/galery.css" type="text/css" media="screen" >';
699
                    }
700
701
702
          $fldVersion = "fancybox_215";
703
          $fbFolder =  XOOPS_URL . "/Frameworks/" . $fldVersion;
704
          //$modFolder = "modules/" . $module_dirname;
705
          $modFolder = "modules/" . 'mediatheque';
706
707
            //$xoTheme->addStyleSheet($fModule . '/css/style.css');
708
            $xoTheme->addScript(XOOPS_URL . '/browse.php?Frameworks/jquery/jquery.js');
709
710
          //to-do : a remplacer par  jquery.mousewheel-3.0.6.pack.js
711
          $xoTheme->addScript($fbFolder . "/jquery.mousewheel-3.0.4.pack.js");
712
713
            $xoTheme->addStyleSheet($fbFolder . "/jquery.fancybox.css?v=2.1.5");
714
            $xoTheme->addScript($fbFolder . "/jquery.fancybox.js?v=2.1.5");
715
716
        //-----------------------------------------
717
        //  OPTIONAL
718
            $xoTheme->addStyleSheet($fbFolder . "/helpers/jquery.fancybox-buttons.css?v=1.0.5");
719
            $xoTheme->addScript($fbFolder . "/helpers/jquery.fancybox-buttons.js?v=1.0.5");
720
721
            $xoTheme->addStyleSheet($fbFolder . "/helpers/jquery.fancybox-thumbs.css?v=1.0.7");
722
            $xoTheme->addScript($fbFolder . "/helpers/jquery.fancybox-thumbs.js?v=1.0.7");
723
724
            $xoTheme->addScript($fbFolder . "/helpers/jquery.fancybox-media.js?v=1.0.6");
725
726
        //-----------------------------------------
727
728
729
730
            $xoTheme->addScript($modFolder . "/js/media.fancybox.js");
731
732
        */
733
    }
734
735
    /**
736
     * Currency Format
737
     *
738
     * @param float  $number
739
     * @param string $currency   The 3-letter ISO 4217 currency code indicating the currency to use.
740
     * @param string $localeCode (local language code, e.g. en_US)
741
     * @return string formatted currency value
742
     */
743
    public static function formatCurrency($number, $currency = 'USD', $localeCode = ''): ?string
744
    {
745
        $localeCode ?? \locale_get_default();
746
        $fmt = new \NumberFormatter($localeCode, \NumberFormatter::CURRENCY);
747
        return $fmt->formatCurrency($number, $currency);
748
    }
749
750
    /**
751
     * Currency Format (temporary)
752
     *
753
     * @param float  $number
754
     * @param string $currency The 3-letter ISO 4217 currency code indicating the currency to use.
755
     * @param string $currencySymbol
756
     * @param int    $currencyPosition
757
     * @return string formatted currency value
758
     */
759
    public static function formatCurrencyTemp($number, $currency = 'USD', $currencySymbol = '$', $currencyPosition = 0): string
0 ignored issues
show
Unused Code introduced by
The parameter $currency is not used and could be removed. ( Ignorable by Annotation )

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

759
    public static function formatCurrencyTemp($number, /** @scrutinizer ignore-unused */ $currency = 'USD', $currencySymbol = '$', $currencyPosition = 0): string

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
760
    {
761
        $currentDefault  = \locale_get_default();
762
        $fmt             = new \NumberFormatter($currentDefault, \NumberFormatter::DECIMAL);
763
        $formattedNumber = $fmt->format($number);
764
        return 1 === $currencyPosition ? $currencySymbol . $formattedNumber : $formattedNumber . ' ' . $currencySymbol;
765
    }
766
}
767