Passed
Push — master ( 6af1fb...f5fe55 )
by Michael
02:53 queued 10s
created

Utility::formatCurrency()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 3
c 0
b 0
f 0
dl 0
loc 5
rs 10
cc 1
nc 1
nop 3
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
    Categories,
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, XoopsModules\Adslight\Categories. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
31
    CategoriesHandler
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, XoopsModules\Adslight\CategoriesHandler. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
32
};
33
34
35
/**
36
 * Class Utility
37
 */
38
class Utility extends Common\SysUtility
39
{
40
    //--------------- Custom module methods -----------------------------
41
42
    public static function expireAd(): void
43
    {
44
        global $xoopsDB, $xoopsConfig, $xoopsModule, $myts, $meta;
45
46
        $datenow = \time();
47
        $message = '';
48
49
        $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'");
50
51
        while (false !== [$lids, $title, $expire, $type, $desctext, $dateann, $email, $submitter, $photo, $valid, $hits, $comments, $remind] = $xoopsDB->fetchRow($result5)) {
52
            $title     = \htmlspecialchars($title, \ENT_QUOTES | \ENT_HTML5);
53
            $expire    = \htmlspecialchars($expire, \ENT_QUOTES | \ENT_HTML5);
54
            $type      = \htmlspecialchars($type, \ENT_QUOTES | \ENT_HTML5);
55
            $desctext  = &$myts->displayTarea($desctext, 1, 1, 1, 1, 1);
56
            $submitter = \htmlspecialchars($submitter, \ENT_QUOTES | \ENT_HTML5);
57
            $remind    = \htmlspecialchars($remind, \ENT_QUOTES | \ENT_HTML5);
58
            $supprdate = $dateann + ($expire * 86400);
59
            $almost    = $GLOBALS['xoopsModuleConfig']['adslight_almost'];
60
61
            // give warning that add is about to expire
62
63
            if ($almost > 0 && ($supprdate - $almost * 86400) < $datenow
64
                && 'Yes' === $valid
65
                && 0 === $remind) {
66
                $xoopsDB->queryF('UPDATE ' . $xoopsDB->prefix('adslight_listing') . " SET remind='1' WHERE lid=${lids}");
67
68
                if ($email) {
69
                    $tags               = [];
70
                    $subject            = '' . \_ADSLIGHT_ALMOST . '';
71
                    $tags['TITLE']      = $title;
72
                    $tags['HELLO']      = '' . \_ADSLIGHT_HELLO . '';
73
                    $tags['YOUR_AD_ON'] = '' . \_ADSLIGHT_YOUR_AD_ON . '';
74
                    $tags['VEDIT_AD']   = '' . \_ADSLIGHT_VEDIT_AD . '';
75
                    $tags['YOUR_AD']    = '' . \_ADSLIGHT_YOUR_AD . '';
76
                    $tags['SOON']       = '' . \_ADSLIGHT_SOON . '';
77
                    $tags['VIEWED']     = '' . \_ADSLIGHT_VU . '';
78
                    $tags['TIMES']      = '' . \_ADSLIGHT_TIMES . '';
79
                    $tags['WEBMASTER']  = '' . \_ADSLIGHT_WEBMASTER . '';
80
                    $tags['THANKS']     = '' . \_ADSLIGHT_THANKS . '';
81
                    $tags['TYPE']       = static::getNameType($type);
82
                    $tags['DESCTEXT']   = $desctext;
83
                    $tags['HITS']       = $hits;
84
                    $tags['META_TITLE'] = $meta['title'];
85
                    $tags['SUBMITTER']  = $submitter;
86
                    $tags['DURATION']   = $expire;
87
                    $tags['LINK_URL']   = XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname') . '/viewads.php?' . '&lid=' . $lids;
88
                    $mail               = \getMailer();
89
                    $mail->setTemplateDir(XOOPS_ROOT_PATH . '/modules/' . $xoopsModule->getVar('dirname') . '/language/' . $xoopsConfig['language'] . '/mail_template/');
90
                    $mail->setTemplate('listing_expires.tpl');
91
                    $mail->useMail();
92
                    $mail->multimailer->isHTML(true);
93
                    $mail->setFromName($meta['title']);
94
                    $mail->setFromEmail($xoopsConfig['adminmail']);
95
                    $mail->setToEmails($email);
96
                    $mail->setSubject($subject);
97
                    $mail->assign($tags);
98
                    $mail->send();
99
                    echo $mail->getErrors();
100
                }
101
            }
102
103
            // expire ad
104
105
            if ($supprdate < $datenow) {
106
                if (0 !== $photo) {
107
                    $result2 = $xoopsDB->query('SELECT url FROM ' . $xoopsDB->prefix('adslight_pictures') . ' WHERE lid=' . $xoopsDB->escape($lids));
108
109
                    while (false !== [$url] = $xoopsDB->fetchRow($result2)) {
110
                        $destination  = XOOPS_ROOT_PATH . '/uploads/adslight';
111
                        $destination2 = XOOPS_ROOT_PATH . '/uploads/adslight/thumbs';
112
                        $destination3 = XOOPS_ROOT_PATH . '/uploads/adslight/midsize';
113
                        if (\is_file("${destination}/${url}")) {
114
                            \unlink("${destination}/${url}");
115
                        }
116
                        if (\is_file("${destination2}/thumb_${url}")) {
117
                            \unlink("${destination2}/thumb_${url}");
118
                        }
119
                        if (\is_file("${destination3}/resized_${url}")) {
120
                            \unlink("${destination3}/resized_${url}");
121
                        }
122
                    }
123
                }
124
125
                $xoopsDB->queryF('DELETE FROM ' . $xoopsDB->prefix('adslight_listing') . ' WHERE lid=' . $xoopsDB->escape($lids));
126
127
                //  Specification for Japan:
128
                //  $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."";
129
                if ($email) {
130
                    $tags               = [];
131
                    $subject            = '' . \_ADSLIGHT_STOP . '';
132
                    $tags['TITLE']      = $title;
133
                    $tags['HELLO']      = '' . \_ADSLIGHT_HELLO . '';
134
                    $tags['TYPE']       = static::getNameType($type);
135
                    $tags['DESCTEXT']   = $desctext;
136
                    $tags['HITS']       = $hits;
137
                    $tags['META_TITLE'] = $meta['title'] ?? '';
138
                    $tags['SUBMITTER']  = $submitter;
139
                    $tags['YOUR_AD_ON'] = '' . \_ADSLIGHT_YOUR_AD_ON . '';
140
                    $tags['EXPIRED']    = '' . \_ADSLIGHT_EXPIRED . '';
141
                    $tags['MESSTEXT']   = \stripslashes($message);
142
                    $tags['OTHER']      = '' . \_ADSLIGHT_OTHER . '';
143
                    $tags['WEBMASTER']  = '' . \_ADSLIGHT_WEBMASTER . '';
144
                    $tags['THANKS']     = '' . \_ADSLIGHT_THANKS . '';
145
                    $tags['VIEWED']     = '' . \_ADSLIGHT_VU . '';
146
                    $tags['TIMES']      = '' . \_ADSLIGHT_TIMES . '';
147
                    $tags['TEAM']       = '' . \_ADSLIGHT_TEAM . '';
148
                    $tags['DURATION']   = $expire;
149
                    $tags['LINK_URL']   = XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname') . '/viewads.php?' . '&lid=' . $lids;
150
                    $mail               = \getMailer();
151
                    $mail->setTemplateDir(XOOPS_ROOT_PATH . '/modules/' . $xoopsModule->getVar('dirname') . '/language/' . $xoopsConfig['language'] . '/mail_template/');
152
                    $mail->setTemplate('listing_expired.tpl');
153
                    $mail->useMail();
154
                    $mail->multimailer->isHTML(true);
155
                    $mail->setFromName($meta['title']);
156
                    $mail->setFromEmail($xoopsConfig['adminmail']);
157
                    $mail->setToEmails($email);
158
                    $mail->setSubject($subject);
159
                    $mail->assign($tags);
160
                    $mail->send();
161
                    echo $mail->getErrors();
162
                }
163
            }
164
        }
165
    }
166
167
    //updates rating data in itemtable for a given user
168
169
    /**
170
     * @param $sel_id
171
     */
172
    public static function updateUserRating($sel_id): void
173
    {
174
        global $xoopsDB;
175
176
        $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...
177
178
        $query = 'SELECT rating FROM ' . $xoopsDB->prefix('adslight_user_votedata') . ' WHERE usid=' . $xoopsDB->escape($sel_id) . ' ';
179
        //echo $query;
180
        $voteresult  = $xoopsDB->query($query);
181
        $votesDB     = $xoopsDB->getRowsNum($voteresult);
182
        $totalrating = 0;
183
        while (false !== [$rating] = $xoopsDB->fetchRow($voteresult)) {
184
            $totalrating += $rating;
185
        }
186
        $finalrating = $totalrating / $votesDB;
187
        $finalrating = \number_format($finalrating, 4);
188
        $query = 'UPDATE ' . $xoopsDB->prefix('adslight_listing') . " SET user_rating=${finalrating}, user_votes=${votesDB} WHERE usid=" . $xoopsDB->escape($sel_id) . '';
189
        //echo $query;
190
        $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...
191
    }
192
193
    //updates rating data in itemtable for a given item
194
195
    /**
196
     * @param $sel_id
197
     */
198
    public static function updateItemRating($sel_id): void
199
    {
200
        global $xoopsDB;
201
202
        $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...
203
204
        $query = 'SELECT rating FROM ' . $xoopsDB->prefix('adslight_item_votedata') . ' WHERE lid=' . $xoopsDB->escape($sel_id) . ' ';
205
        //echo $query;
206
        $voteresult  = $xoopsDB->query($query);
207
        $votesDB     = $xoopsDB->getRowsNum($voteresult);
208
        $totalrating = 0;
209
        while (false !== [$rating] = $xoopsDB->fetchRow($voteresult)) {
210
            $totalrating += $rating;
211
        }
212
        $finalrating = $totalrating / $votesDB;
213
        $finalrating = \number_format($finalrating, 4);
214
        $query = 'UPDATE ' . $xoopsDB->prefix('adslight_listing') . " SET item_rating=${finalrating}, item_votes=${votesDB} WHERE lid=" . $xoopsDB->escape($sel_id) . '';
215
        //echo $query;
216
        $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...
217
    }
218
219
    /**
220
     * @param        $sel_id
221
     * @param string $status
222
     */
223
    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

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

761
    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...
762
    {
763
        $currentDefault  = \locale_get_default();
764
        $fmt             = new \NumberFormatter($currentDefault, \NumberFormatter::DECIMAL);
765
        $formattedNumber = $fmt->format((float)$number);
766
        return 1 === $currencyPosition ? $currencySymbol . $formattedNumber : $formattedNumber . ' ' . $currencySymbol;
767
    }
768
769
770
    /**
771
     * @param Categories $categoryObj
772
     * @param int      $level
773
     */
774
    public static function displayCategory(Categories $categoryObj, $level = 0)
775
    {
776
        $helper = Helper::getInstance();
777
        $configurator = new Common\Configurator();
778
        $icons = $configurator->icons;
779
780
        $description = $categoryObj->cat_desc;
0 ignored issues
show
Bug introduced by
The property cat_desc does not seem to exist on XoopsModules\Adslight\Categories.
Loading history...
781
        if (!XOOPS_USE_MULTIBYTES && !empty($description)) {
782
            if (\mb_strlen($description) >= 100) {
783
                $description = \mb_substr($description, 0, 100 - 1) . '...';
0 ignored issues
show
Unused Code introduced by
The assignment to $description is dead and can be removed.
Loading history...
784
            }
785
        }
786
        $modify = "<a href='category.php?op=mod&amp;cid=" . $categoryObj->cid() . '&amp;pid=' . $categoryObj->pid() . "'>" . $icons['edit'] . '</a>';
0 ignored issues
show
Bug introduced by
The method cid() does not exist on XoopsModules\Adslight\Categories. ( Ignorable by Annotation )

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

786
        $modify = "<a href='category.php?op=mod&amp;cid=" . $categoryObj->/** @scrutinizer ignore-call */ cid() . '&amp;pid=' . $categoryObj->pid() . "'>" . $icons['edit'] . '</a>';

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
Bug introduced by
The method pid() does not exist on XoopsModules\Adslight\Categories. ( Ignorable by Annotation )

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

786
        $modify = "<a href='category.php?op=mod&amp;cid=" . $categoryObj->cid() . '&amp;pid=' . $categoryObj->/** @scrutinizer ignore-call */ pid() . "'>" . $icons['edit'] . '</a>';

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
787
        $delete = "<a href='category.php?op=del&amp;cid=" . $categoryObj->cid() . "'>" . $icons['delete'] . '</a>';
788
        $spaces = \str_repeat('&nbsp;', ($level * 3));
789
        /*
790
        $spaces = '';
791
        for ($j = 0; $j < $level; ++$j) {
792
            $spaces .= '&nbsp;&nbsp;&nbsp;';
793
        }
794
        */
795
        echo "<tr>\n"
796
             . "<td class='even center'>"
797
             . $categoryObj->cid()
798
             . "</td>\n"
799
             . "<td class='even left'>"
800
             . $spaces
801
             . "<a href='" . $helper->url() . 'category.php?cid=' . $categoryObj->cid()
802
             . "'><img src='" . $helper->url() . "assets/images/links/subcat.gif' alt=''>&nbsp;"
803
             . $categoryObj->name()
0 ignored issues
show
Bug introduced by
The method name() does not exist on XoopsModules\Adslight\Categories. ( Ignorable by Annotation )

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

803
             . $categoryObj->/** @scrutinizer ignore-call */ name()

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
804
             . "</a></td>\n"
805
             . "<td class='even center'>"
806
             . $categoryObj->weight()
0 ignored issues
show
Bug introduced by
The method weight() does not exist on XoopsModules\Adslight\Categories. ( Ignorable by Annotation )

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

806
             . $categoryObj->/** @scrutinizer ignore-call */ weight()

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
807
             . "</td>\n"
808
             . "<td class='even center'> {$modify} {$delete} </td>\n"
809
             . "</tr>\n";
810
        $subCategoriesObj = $helper->getHandler('Categories')->getCategories(0, 0, $categoryObj->cid());
0 ignored issues
show
Bug introduced by
The method getCategories() does not exist on XoopsModules\Adslight\CategoriesHandler. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

810
        $subCategoriesObj = $helper->getHandler('Categories')->/** @scrutinizer ignore-call */ getCategories(0, 0, $categoryObj->cid());
Loading history...
811
        if (\count($subCategoriesObj) > 0) {
0 ignored issues
show
Bug introduced by
It seems like $subCategoriesObj can also be of type null; however, parameter $value of count() does only seem to accept Countable|array, maybe add an additional type check? ( Ignorable by Annotation )

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

811
        if (\count(/** @scrutinizer ignore-type */ $subCategoriesObj) > 0) {
Loading history...
812
            ++$level;
813
            foreach ($subCategoriesObj as $thiscat) {
814
                self::displayCategory($thiscat, $level);
815
            }
816
            unset($key);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $key seems to be never defined.
Loading history...
817
        }
818
        //        unset($categoryObj);
819
    }
820
}
821