Passed
Push — master ( 05cb95...eed2c7 )
by Michael
02:06
created

class/Utility.php (3 issues)

1
<?php
2
3
namespace XoopsModules\Adslight;
4
5
/*
6
-------------------------------------------------------------------------
7
                     ADSLIGHT 2 : Module for Xoops
8
9
        Redesigned and ameliorate By Luc Bizet user at www.frxoops.org
10
        Started with the Classifieds module and made MANY changes
11
        Website : http://www.luc-bizet.fr
12
        Contact : [email protected]
13
-------------------------------------------------------------------------
14
             Original credits below Version History
15
##########################################################################
16
#                    Classified Module for Xoops                         #
17
#  By John Mordo user jlm69 at www.xoops.org and www.jlmzone.com         #
18
#      Started with the MyAds module and made MANY changes               #
19
##########################################################################
20
 Original Author: Pascal Le Boustouller
21
 Author Website : [email protected]
22
 Licence Type   : GPL
23
-------------------------------------------------------------------------
24
*/
25
26
/**
27
 * AdslightUtil Class
28
 *
29
 * @copyright   XOOPS Project (https://xoops.org)
30
 * @license     http://www.fsf.org/copyleft/gpl.html GNU public license
31
 * @author      XOOPS Development Team
32
 * @package     AdsLight
33
 * @since       1.03
34
 */
35
36
use Xmf\Request;
37
use XoopsModules\Adslight;
38
39
$moduleDirName = basename(dirname(__DIR__));
40
$main_lang     = '_' . mb_strtoupper($moduleDirName);
41
//require_once XOOPS_ROOT_PATH . '/modules/adslight/include/gtickets.php';
42
require_once XOOPS_ROOT_PATH . '/class/xoopstree.php';
43
$myts = \MyTextSanitizer::getInstance();
44
45
/**
46
 * Class Utility
47
 */
48
class Utility
49
{
50
    use Common\VersionChecks; //checkVerXoops, checkVerPhp Traits
51
52
    use Common\ServerStats; // getServerStats Trait
53
54
    use Common\FilesManagement; // Files Management Trait
55
56
    //--------------- Custom module methods -----------------------------
57
58
    public static function expireAd()
59
    {
60
        global $xoopsDB, $xoopsConfig, $xoopsModule, $myts, $meta, $moduleDirName, $main_lang;
61
62
        $datenow = time();
63
        $message = '';
64
65
        $result5 = $xoopsDB->query('SELECT lid, title, expire, type, desctext, date, email, submitter, photo, valid, hits, comments, remind FROM ' . $xoopsDB->prefix('adslight_listing') . " WHERE valid='Yes'");
66
67
        while (false !== (list($lids, $title, $expire, $type, $desctext, $dateann, $email, $submitter, $photo, $valid, $hits, $comments, $remind) = $xoopsDB->fetchRow($result5))) {
68
            $title     = $myts->htmlSpecialChars($title);
69
            $expire    = $myts->htmlSpecialChars($expire);
70
            $type      = $myts->htmlSpecialChars($type);
71
            $desctext  = &$myts->displayTarea($desctext, 1, 1, 1, 1, 1);
72
            $submitter = $myts->htmlSpecialChars($submitter);
73
            $remind    = $myts->htmlSpecialChars($remind);
74
            $supprdate = $dateann + ($expire * 86400);
75
            $almost    = $GLOBALS['xoopsModuleConfig']['adslight_almost'];
76
77
            // give warning that add is about to expire
78
79
            if ($almost > 0 && ($supprdate - $almost * 86400) < $datenow
80
                && 'Yes' === $valid
81
                && 0 == $remind) {
82
                $xoopsDB->queryF('UPDATE ' . $xoopsDB->prefix('adslight_listing') . " SET remind='1' WHERE lid=$lids");
83
84
                if ($email) {
85
                    $tags               = [];
86
                    $subject            = '' . _ADSLIGHT_ALMOST . '';
87
                    $tags['TITLE']      = $title;
88
                    $tags['HELLO']      = '' . _ADSLIGHT_HELLO . '';
89
                    $tags['YOUR_AD_ON'] = '' . _ADSLIGHT_YOUR_AD_ON . '';
90
                    $tags['VEDIT_AD']   = '' . _ADSLIGHT_VEDIT_AD . '';
91
                    $tags['YOUR_AD']    = '' . _ADSLIGHT_YOUR_AD . '';
92
                    $tags['SOON']       = '' . _ADSLIGHT_SOON . '';
93
                    $tags['VIEWED']     = '' . _ADSLIGHT_VU . '';
94
                    $tags['TIMES']      = '' . _ADSLIGHT_TIMES . '';
95
                    $tags['WEBMASTER']  = '' . _ADSLIGHT_WEBMASTER . '';
96
                    $tags['THANKS']     = '' . _ADSLIGHT_THANKS . '';
97
                    $tags['TYPE']       = static::getNameType($type);
98
                    $tags['DESCTEXT']   = $desctext;
99
                    $tags['HITS']       = $hits;
100
                    $tags['META_TITLE'] = $meta['title'];
101
                    $tags['SUBMITTER']  = $submitter;
102
                    $tags['DURATION']   = $expire;
103
                    $tags['LINK_URL']   = XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname') . '/viewads.php?' . '&lid=' . $lids;
104
                    $mail               = &getMailer();
105
                    $mail->setTemplateDir(XOOPS_ROOT_PATH . '/modules/' . $xoopsModule->getVar('dirname') . '/language/' . $xoopsConfig['language'] . '/mail_template/');
106
                    $mail->setTemplate('listing_expires.tpl');
107
                    $mail->useMail();
108
                    $mail->multimailer->isHTML(true);
109
                    $mail->setFromName($meta['title']);
110
                    $mail->setFromEmail($xoopsConfig['adminmail']);
111
                    $mail->setToEmails($email);
112
                    $mail->setSubject($subject);
113
                    $mail->assign($tags);
114
                    $mail->send();
115
                    echo $mail->getErrors();
116
                }
117
            }
118
119
            // expire ad
120
121
            if ($supprdate < $datenow) {
122
                if (0 != $photo) {
123
                    $result2 = $xoopsDB->query('SELECT url FROM ' . $xoopsDB->prefix('adslight_pictures') . ' WHERE lid=' . $xoopsDB->escape($lids));
124
125
                    while (false !== (list($url) = $xoopsDB->fetchRow($result2))) {
126
                        $destination  = XOOPS_ROOT_PATH . '/uploads/AdsLight';
127
                        $destination2 = XOOPS_ROOT_PATH . '/uploads/AdsLight/thumbs';
128
                        $destination3 = XOOPS_ROOT_PATH . '/uploads/AdsLight/midsize';
129
                        if (file_exists("$destination/$url")) {
130
                            unlink("$destination/$url");
131
                        }
132
                        if (file_exists("$destination2/thumb_$url")) {
133
                            unlink("$destination2/thumb_$url");
134
                        }
135
                        if (file_exists("$destination3/resized_$url")) {
136
                            unlink("$destination3/resized_$url");
137
                        }
138
                    }
139
                }
140
141
                $xoopsDB->queryF('DELETE FROM ' . $xoopsDB->prefix('adslight_listing') . ' WHERE lid=' . $xoopsDB->escape($lids));
142
143
                //  Specification for Japan:
144
                //  $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."";
145
                if ($email) {
146
                    $tags               = [];
147
                    $subject            = '' . _ADSLIGHT_STOP . '';
148
                    $tags['TITLE']      = $title;
149
                    $tags['HELLO']      = '' . _ADSLIGHT_HELLO . '';
150
                    $tags['TYPE']       = static::getNameType($type);
151
                    $tags['DESCTEXT']   = $desctext;
152
                    $tags['HITS']       = $hits;
153
                    $tags['META_TITLE'] = $meta['title'];
154
                    $tags['SUBMITTER']  = $submitter;
155
                    $tags['YOUR_AD_ON'] = '' . _ADSLIGHT_YOUR_AD_ON . '';
156
                    $tags['EXPIRED']    = '' . _ADSLIGHT_EXPIRED . '';
157
                    $tags['MESSTEXT']   = stripslashes($message);
158
                    $tags['OTHER']      = '' . _ADSLIGHT_OTHER . '';
159
                    $tags['WEBMASTER']  = '' . _ADSLIGHT_WEBMASTER . '';
160
                    $tags['THANKS']     = '' . _ADSLIGHT_THANKS . '';
161
                    $tags['VIEWED']     = '' . _ADSLIGHT_VU . '';
162
                    $tags['TIMES']      = '' . _ADSLIGHT_TIMES . '';
163
                    $tags['TEAM']       = '' . _ADSLIGHT_TEAM . '';
164
                    $tags['DURATION']   = $expire;
165
                    $tags['LINK_URL']   = XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname') . '/viewads.php?' . '&lid=' . $lids;
166
                    $mail               = &getMailer();
167
                    $mail->setTemplateDir(XOOPS_ROOT_PATH . '/modules/' . $xoopsModule->getVar('dirname') . '/language/' . $xoopsConfig['language'] . '/mail_template/');
168
                    $mail->setTemplate('listing_expired.tpl');
169
                    $mail->useMail();
170
                    $mail->multimailer->isHTML(true);
171
                    $mail->setFromName($meta['title']);
172
                    $mail->setFromEmail($xoopsConfig['adminmail']);
173
                    $mail->setToEmails($email);
174
                    $mail->setSubject($subject);
175
                    $mail->assign($tags);
176
                    $mail->send();
177
                    echo $mail->getErrors();
178
                }
179
            }
180
        }
181
    }
182
183
    //updates rating data in itemtable for a given user
184
185
    /**
186
     * @param $sel_id
187
     */
188
    public static function updateUserRating($sel_id)
189
    {
190
        global $xoopsDB, $moduleDirName, $main_lang;
191
192
        $usid = Request::getInt('usid', 0, 'GET');
193
194
        $query = 'SELECT rating FROM ' . $xoopsDB->prefix('adslight_user_votedata') . ' WHERE usid=' . $xoopsDB->escape($sel_id) . ' ';
195
        //echo $query;
196
        $voteresult  = $xoopsDB->query($query);
197
        $votesDB     = $xoopsDB->getRowsNum($voteresult);
198
        $totalrating = 0;
199
        while (false !== (list($rating) = $xoopsDB->fetchRow($voteresult))) {
200
            $totalrating += $rating;
201
        }
202
        $finalrating = $totalrating / $votesDB;
203
        $finalrating = number_format($finalrating, 4);
204
        $query       = 'UPDATE ' . $xoopsDB->prefix('adslight_listing') . " SET user_rating=$finalrating, user_votes=$votesDB WHERE usid=" . $xoopsDB->escape($sel_id) . '';
205
        //echo $query;
206
        $xoopsDB->query($query) || exit();
207
    }
208
209
    //updates rating data in itemtable for a given item
210
211
    /**
212
     * @param $sel_id
213
     */
214
    public static function updateItemRating($sel_id)
215
    {
216
        global $xoopsDB, $moduleDirName, $main_lang;
217
218
        $lid = Request::getInt('lid', 0, 'GET');
219
220
        $query = 'SELECT rating FROM ' . $xoopsDB->prefix('adslight_item_votedata') . ' WHERE lid=' . $xoopsDB->escape($sel_id) . ' ';
221
        //echo $query;
222
        $voteresult  = $xoopsDB->query($query);
223
        $votesDB     = $xoopsDB->getRowsNum($voteresult);
224
        $totalrating = 0;
225
        while (false !== (list($rating) = $xoopsDB->fetchRow($voteresult))) {
226
            $totalrating += $rating;
227
        }
228
        $finalrating = $totalrating / $votesDB;
229
        $finalrating = number_format($finalrating, 4);
230
        $query       = 'UPDATE ' . $xoopsDB->prefix('adslight_listing') . " SET item_rating=$finalrating, item_votes=$votesDB WHERE lid=" . $xoopsDB->escape($sel_id) . '';
231
        //echo $query;
232
        $xoopsDB->query($query) || exit();
233
    }
234
235
    /**
236
     * @param        $sel_id
237
     * @param string $status
238
     *
239
     * @return int
240
     */
241
    public static function getTotalItems($sel_id, $status = '')
242
    {
243
        global $xoopsDB, $mytree, $moduleDirName;
244
        $categories = self::getMyItemIds('adslight_view');
245
        $count      = 0;
246
        $arr        = [];
247
        if (in_array($sel_id, $categories, true)) {
248
            $query = 'SELECT SQL_CACHE count(*) FROM ' . $xoopsDB->prefix('adslight_listing') . ' WHERE cid=' . (int)$sel_id . " AND valid='Yes' AND status!='1'";
249
250
            $result = $xoopsDB->query($query);
251
            list($thing) = $xoopsDB->fetchRow($result);
252
            $count = $thing;
253
            $arr   = $mytree->getAllChildId($sel_id);
254
            $size  = count($arr);
255
            for ($i = 0; $i < $size; ++$i) {
256
                if (in_array($arr[$i], $categories, true)) {
257
                    $query2 = 'SELECT SQL_CACHE count(*) FROM ' . $xoopsDB->prefix('adslight_listing') . ' WHERE cid=' . (int)$arr[$i] . " AND valid='Yes' AND status!='1'";
258
259
                    $result2 = $xoopsDB->query($query2);
260
                    list($thing) = $xoopsDB->fetchRow($result2);
261
                    $count += $thing;
262
                }
263
            }
264
        }
265
266
        return $count;
267
    }
268
269
    /**
270
     * @param $permtype
271
     *
272
     * @return mixed
273
     */
274
    public static function getMyItemIds($permtype)
275
    {
276
        global $moduleDirName;
277
        static $permissions = [];
278
        if (is_array($permissions)
279
            && array_key_exists($permtype, $permissions)) {
280
            return $permissions[$permtype];
281
        }
282
283
        /** @var \XoopsModuleHandler $moduleHandler */
284
        $moduleHandler = xoops_getHandler('module');
285
        $myModule      = $moduleHandler->getByDirname('adslight');
286
        $groups        = is_object($GLOBALS['xoopsUser']) ? $GLOBALS['xoopsUser']->getGroups() : XOOPS_GROUP_ANONYMOUS;
287
        /** @var \XoopsGroupPermHandler $grouppermHandler */
288
        $grouppermHandler       = xoops_getHandler('groupperm');
289
        $categories             = $grouppermHandler->getItemIds($permtype, $groups, $myModule->getVar('mid'));
290
        $permissions[$permtype] = $categories;
291
292
        return $categories;
293
    }
294
295
    /**
296
     * Returns a module's option
297
     * @param        $option module option's name
0 ignored issues
show
The type XoopsModules\Adslight\module was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
298
     * @param string $repmodule
299
     *
300
     * @return bool|mixed option's value
301
     */
302
    public static function getModuleOption($option, $repmodule = 'adslight')
303
    {
304
        global $xoopsModule;
305
        static $tbloptions = [];
306
        if (is_array($tbloptions) && array_key_exists($option, $tbloptions)) {
307
            return $tbloptions[$option];
308
        }
309
310
        $retval = false;
311
        if (isset($GLOBALS['xoopsModuleConfig'])
312
            && (is_object($xoopsModule)
313
                && $xoopsModule->getVar('dirname') == $repmodule
314
                && $xoopsModule->getVar('isactive'))) {
315
            if (isset($GLOBALS['xoopsModuleConfig'][$option])) {
316
                $retval = $GLOBALS['xoopsModuleConfig'][$option];
317
            }
318
        } else {
319
            /** @var \XoopsModuleHandler $moduleHandler */
320
            $moduleHandler = xoops_getHandler('module');
321
            $module        = $moduleHandler->getByDirname($repmodule);
322
            /** @var \XoopsModuleHandler $moduleHandler */
323
            $configHandler = xoops_getHandler('config');
324
            if ($module) {
325
                $moduleConfig = $configHandler->getConfigsByCat(0, $GLOBALS['xoopsModule']->getVar('mid'));
326
                if (null !== $helper->getConfig($option)) {
327
                    $retval = $helper->getConfig($option);
328
                }
329
            }
330
        }
331
        $tbloptions[$option] = $retval;
332
333
        return $retval;
334
    }
335
336
    public static function showImage()
337
    {
338
        global $moduleDirName;
339
        echo "<script type=\"text/javascript\">\n";
340
        echo "<!--\n\n";
341
        echo "function showimage() {\n";
342
        echo "if (!document.images)\n";
343
        echo "return\n";
344
        echo "document.images.avatar.src=\n";
345
        echo "'" . XOOPS_URL . "/modules/adslight/assets/images/img_cat/' + document.imcat.img.options[document.imcat.img.selectedIndex].value\n";
346
        echo "}\n\n";
347
        echo "//-->\n";
348
        echo "</script>\n";
349
    }
350
351
    //Reusable Link Sorting Functions
352
353
    /**
354
     * @param $orderby
355
     *
356
     * @return string
357
     */
358
    public static function convertOrderByIn($orderby)
359
    {
360
        switch (trim($orderby)) {
361
            case 'titleA':
362
                $orderby = 'title ASC';
363
                break;
364
            case 'dateA':
365
                $orderby = 'date ASC';
366
                break;
367
            case 'hitsA':
368
                $orderby = 'hits ASC';
369
                break;
370
            case 'priceA':
371
                $orderby = 'price ASC';
372
                break;
373
            case 'titleD':
374
                $orderby = 'title DESC';
375
                break;
376
            case 'hitsD':
377
                $orderby = 'hits DESC';
378
                break;
379
            case 'priceD':
380
                $orderby = 'price DESC';
381
                break;
382
            case'dateD':
383
            default:
384
                $orderby = 'date DESC';
385
                break;
386
        }
387
388
        return $orderby;
389
    }
390
391
    /**
392
     * @param $orderby
393
     *
394
     * @return string
395
     */
396
    public static function convertOrderByTrans($orderby)
397
    {
398
        global $main_lang;
399
        $orderbyTrans = '';
400
        if ('hits ASC' === $orderby) {
401
            $orderbyTrans = '' . _ADSLIGHT_POPULARITYLTOM . '';
402
        }
403
        if ('hits DESC' === $orderby) {
404
            $orderbyTrans = '' . _ADSLIGHT_POPULARITYMTOL . '';
405
        }
406
        if ('title ASC' === $orderby) {
407
            $orderbyTrans = '' . _ADSLIGHT_TITLEATOZ . '';
408
        }
409
        if ('title DESC' === $orderby) {
410
            $orderbyTrans = '' . _ADSLIGHT_TITLEZTOA . '';
411
        }
412
        if ('date ASC' === $orderby) {
413
            $orderbyTrans = '' . _ADSLIGHT_DATEOLD . '';
414
        }
415
        if ('date DESC' === $orderby) {
416
            $orderbyTrans = '' . _ADSLIGHT_DATENEW . '';
417
        }
418
        if ('price ASC' === $orderby) {
419
            $orderbyTrans = _ADSLIGHT_PRICELTOH;
420
        }
421
        if ('price DESC' === $orderby) {
422
            $orderbyTrans = '' . _ADSLIGHT_PRICEHTOL . '';
423
        }
424
425
        return $orderbyTrans;
426
    }
427
428
    /**
429
     * @param $orderby
430
     *
431
     * @return string
432
     */
433
    public static function convertOrderByOut($orderby)
434
    {
435
        if ('title ASC' === $orderby) {
436
            $orderby = 'titleA';
437
        }
438
        if ('date ASC' === $orderby) {
439
            $orderby = 'dateA';
440
        }
441
        if ('hits ASC' === $orderby) {
442
            $orderby = 'hitsA';
443
        }
444
        if ('price ASC' === $orderby) {
445
            $orderby = 'priceA';
446
        }
447
        if ('title DESC' === $orderby) {
448
            $orderby = 'titleD';
449
        }
450
        if ('date DESC' === $orderby) {
451
            $orderby = 'dateD';
452
        }
453
        if ('hits DESC' === $orderby) {
454
            $orderby = 'hitsD';
455
        }
456
        if ('price DESC' === $orderby) {
457
            $orderby = 'priceD';
458
        }
459
460
        return $orderby;
461
    }
462
463
    /**
464
     * @param string $caption
465
     * @param string $name
466
     * @param string $value
467
     * @param string $width
468
     * @param string $height
469
     * @param string $supplemental
470
     *
471
     * @return XoopsFormDhtmlTextArea|\XoopsFormEditor
0 ignored issues
show
The type XoopsModules\Adslight\XoopsFormDhtmlTextArea was not found. Did you mean XoopsFormDhtmlTextArea? If so, make sure to prefix the type with \.
Loading history...
472
     */
473
    public static function getEditor($caption, $name, $value = '', $width = '100%', $height = '300px', $supplemental = '')
474
    {
475
        global $xoopsModule;
476
        $options = [];
477
        $isAdmin = $GLOBALS['xoopsUser']->isAdmin($xoopsModule->getVar('mid'));
478
479
        if (class_exists('XoopsFormEditor')) {
480
            $options['name']   = $name;
481
            $options['value']  = $value;
482
            $options['rows']   = 20;
483
            $options['cols']   = '100%';
484
            $options['width']  = $width;
485
            $options['height'] = $height;
486
            if ($isAdmin) {
487
                $myEditor = new \XoopsFormEditor(ucfirst($name), $GLOBALS['xoopsModuleConfig']['adslightAdminUser'], $options, $nohtml = false, $onfailure = 'textarea');
488
            } else {
489
                $myEditor = new \XoopsFormEditor(ucfirst($name), $GLOBALS['xoopsModuleConfig']['adslightEditorUser'], $options, $nohtml = false, $onfailure = 'textarea');
490
            }
491
        } else {
492
            $myEditor = new \XoopsFormDhtmlTextArea(ucfirst($name), $name, $value, '100%', '100%');
493
        }
494
495
        //        $form->addElement($descEditor);
496
497
        return $myEditor;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $myEditor also could return the type XoopsFormDhtmlTextArea which is incompatible with the documented return type XoopsFormEditor|XoopsMod...\XoopsFormDhtmlTextArea.
Loading history...
498
    }
499
500
    /**
501
     * @param $tablename
502
     *
503
     * @return bool
504
     */
505
    public static function checkTableExists($tablename)
506
    {
507
        global $xoopsDB;
508
        $result = $xoopsDB->queryF("SHOW TABLES LIKE '$tablename'");
509
510
        return ($xoopsDB->getRowsNum($result) > 0);
511
    }
512
513
    /**
514
     * @param $fieldname
515
     * @param $table
516
     *
517
     * @return bool
518
     */
519
    public static function checkFieldExists($fieldname, $table)
520
    {
521
        global $xoopsDB;
522
        $result = $xoopsDB->queryF("SHOW COLUMNS FROM $table LIKE '$fieldname'");
523
524
        return ($xoopsDB->getRowsNum($result) > 0);
525
    }
526
527
    /**
528
     * @param $field
529
     * @param $table
530
     *
531
     * @return mixed
532
     */
533
    public static function addField($field, $table)
534
    {
535
        global $xoopsDB;
536
        $result = $xoopsDB->queryF('ALTER TABLE ' . $table . " ADD $field;");
537
538
        return $result;
539
    }
540
541
    /**
542
     * @param $cid
543
     *
544
     * @return bool
545
     */
546
    public static function getCatNameFromId($cid)
547
    {
548
        global $xoopsDB, $xoopsConfig, $myts, $moduleDirName;
549
550
        $sql = 'SELECT SQL_CACHE title FROM ' . $xoopsDB->prefix('adslight_categories') . " WHERE cid = '$cid'";
551
552
        if (!$result = $xoopsDB->query($sql)) {
553
            return false;
554
        }
555
556
        if (!$arr = $xoopsDB->fetchArray($result)) {
557
            return false;
558
        }
559
560
        $title = $arr['title'];
561
562
        return $title;
563
    }
564
565
    /**
566
     * @return mixed
567
     */
568
    public static function goCategory()
569
    {
570
        global $xoopsDB;
571
572
        $xt   = new \XoopsTree($xoopsDB->prefix('adslight_categories'), 'cid', 'pid');
573
        $jump = XOOPS_URL . '/modules/adslight/viewcats.php?cid=';
574
        ob_start();
575
        $xt->makeMySelBox('title', 'title', 0, 1, 'pid', 'location="' . $jump . '"+this.options[this.selectedIndex].value');
576
        $block['selectbox'] = ob_get_contents();
577
        ob_end_clean();
578
579
        return $block;
580
    }
581
582
    // ADSLIGHT Version 2 //
583
    // Fonction rss.php RSS par categories
584
585
    /**
586
     * @return array
587
     */
588
    public static function returnAllAdsRss()
589
    {
590
        global $xoopsDB;
591
592
        $cid = Request::getInt('cid', null, 'GET');
593
594
        $result = [];
595
596
        $sql = 'SELECT lid, title, price, date, town FROM ' . $xoopsDB->prefix('adslight_listing') . " WHERE valid='yes' AND cid=" . $xoopsDB->escape($cid) . ' ORDER BY date DESC';
597
598
        $resultValues = $xoopsDB->query($sql);
599
        while (false !== ($resultTemp = $xoopsDB->fetchBoth($resultValues))) {
600
            array_push($result, $resultTemp);
601
        }
602
603
        return $result;
604
    }
605
606
    // Fonction fluxrss.php RSS Global
607
608
    /**
609
     * @return array
610
     */
611
    public static function returnAllAdsFluxRss()
612
    {
613
        global $xoopsDB;
614
615
        $result = [];
616
617
        $sql = 'SELECT lid, title, price, desctext, date, town FROM ' . $xoopsDB->prefix('adslight_listing') . " WHERE valid='yes' ORDER BY date DESC LIMIT 0,15";
618
619
        $resultValues = $xoopsDB->query($sql);
620
        while (false !== ($resultTemp = $xoopsDB->fetchBoth($resultValues))) {
621
            array_push($result, $resultTemp);
622
        }
623
624
        return $result;
625
    }
626
627
    /**
628
     * @param $type
629
     *
630
     * @return mixed
631
     */
632
    public static function getNameType($type)
633
    {
634
        global $xoopsDB;
635
        $sql = $xoopsDB->query('SELECT nom_type FROM ' . $xoopsDB->prefix('adslight_type') . " WHERE id_type='" . $xoopsDB->escape($type) . "'");
636
        list($nom_type) = $xoopsDB->fetchRow($sql);
637
638
        return $nom_type;
639
    }
640
641
    /**
642
     * @param $format
643
     * @param $number
644
     *
645
     * @return mixed
646
     */
647
    public static function getMoneyFormat($format, $number)
648
    {
649
        $regex = '/%((?:[\^!\-]|\+|\(|\=.)*)([0-9]+)?' . '(?:#([0-9]+))?(?:\.([0-9]+))?([in%])/';
650
        if ('C' === setlocale(LC_MONETARY, 0)) {
651
            setlocale(LC_MONETARY, '');
652
        }
653
654
        setlocale(LC_ALL, 'en_US');
655
        //        setlocale(LC_ALL, 'fr_FR');
656
657
        $locale = localeconv();
658
        preg_match_all($regex, $format, $matches, PREG_SET_ORDER);
659
        foreach ($matches as $fmatch) {
660
            $value      = (float)$number;
661
            $flags      = [
662
                'fillchar'  => preg_match('/\=(.)/', $fmatch[1], $match) ? $match[1] : ' ',
663
                'nogroup'   => preg_match('/\^/', $fmatch[1]) > 0,
664
                'usesignal' => preg_match('/\+|\(/', $fmatch[1], $match) ? $match[0] : '+',
665
                'nosimbol'  => preg_match('/\!/', $fmatch[1]) > 0,
666
                'isleft'    => preg_match('/\-/', $fmatch[1]) > 0,
667
            ];
668
            $width      = trim($fmatch[2]) ? (int)$fmatch[2] : 0;
669
            $left       = trim($fmatch[3]) ? (int)$fmatch[3] : 0;
670
            $right      = trim($fmatch[4]) ? (int)$fmatch[4] : $locale['int_frac_digits'];
671
            $conversion = $fmatch[5];
672
673
            $positive = true;
674
            if ($value < 0) {
675
                $positive = false;
676
                $value    *= -1;
677
            }
678
            $letter = $positive ? 'p' : 'n';
679
680
            $prefix = $suffix = $cprefix = $csuffix = $signal = '';
681
682
            $signal = $positive ? $locale['positive_sign'] : $locale['negative_sign'];
683
            switch (true) {
684
                case 1 == $locale["{$letter}_sign_posn"]
685
                     && '+' == $flags['usesignal']:
686
                    $prefix = $signal;
687
                    break;
688
                case 2 == $locale["{$letter}_sign_posn"]
689
                     && '+' == $flags['usesignal']:
690
                    $suffix = $signal;
691
                    break;
692
                case 3 == $locale["{$letter}_sign_posn"]
693
                     && '+' == $flags['usesignal']:
694
                    $cprefix = $signal;
695
                    break;
696
                case 4 == $locale["{$letter}_sign_posn"]
697
                     && '+' == $flags['usesignal']:
698
                    $csuffix = $signal;
699
                    break;
700
                case '(' === $flags['usesignal']:
701
                case 0 == $locale["{$letter}_sign_posn"]:
702
                    $prefix = '(';
703
                    $suffix = ')';
704
                    break;
705
            }
706
            if (!$flags['nosimbol']) {
707
                $currency = $cprefix . ('i' === $conversion ? $locale['int_curr_symbol'] : $locale['currency_symbol']) . $csuffix;
708
            } else {
709
                $currency = '';
710
            }
711
            $space = $locale["{$letter}_sep_by_space"] ? ' ' : '';
712
713
            $value = number_format($value, $right, $locale['mon_decimal_point'], $flags['nogroup'] ? '' : $locale['mon_thousands_sep']);
714
            $value = @explode($locale['mon_decimal_point'], $value);
715
716
            $n = mb_strlen($prefix) + mb_strlen($currency) + mb_strlen($value[0]);
717
            if ($left > 0 && $left > $n) {
718
                $value[0] = str_repeat($flags['fillchar'], $left - $n) . $value[0];
719
            }
720
            $value = implode($locale['mon_decimal_point'], $value);
721
            if ($locale["{$letter}_cs_precedes"]) {
722
                $value = $prefix . $currency . $space . $value . $suffix;
723
            } else {
724
                $value = $prefix . $value . $space . $currency . $suffix;
725
            }
726
            if ($width > 0) {
727
                $value = str_pad($value, $width, $flags['fillchar'], $flags['isleft'] ? STR_PAD_RIGHT : STR_PAD_LEFT);
728
            }
729
730
            $format = str_replace($fmatch[0], $value, $format);
731
        }
732
733
        return $format;
734
    }
735
736
    /**
737
     * Saves permissions for the selected category
738
     *
739
     *   saveCategory_Permissions()
740
     *
741
     * @param  array $groups : group with granted permission
742
     * @param        $categoryId
743
     * @param        $permName
744
     * @return bool : TRUE if the no errors occured
745
     */
746
    public static function saveCategoryPermissions($groups, $categoryId, $permName)
747
    {
748
        global $xoopsModule;
749
750
        $moduleDirName = basename(dirname(__DIR__));
751
752
        if (false !== ($helper = Helper::getHelper($moduleDirName))) {
753
        } else {
754
            $helper = \Xmf\Module\Helper::getHelper('system');
755
        }
756
757
        $result = true;
758
        //        $xoopsModule = sf_getModuleInfo();
759
        $moduleId = $helper->getModule()->getVar('mid');
760
761
        $grouppermHandler = xoops_getHandler('groupperm');
762
        // First, if the permissions are already there, delete them
763
        $grouppermHandler->deleteByModule($moduleId, $permName, $categoryId);
764
        // Save the new permissions
765
        if (count($groups) > 0) {
766
            foreach ($groups as $groupId) {
767
                $grouppermHandler->addRight($permName, $categoryId, $groupId, $moduleId);
768
            }
769
        }
770
771
        return $result;
772
    }
773
}
774