Code Duplication    Length = 796-816 lines in 2 locations

class/util.php 1 location

@@ 47-862 (lines=816) @@
44
/**
45
 * Class AdslightUtil
46
 */
47
class AdslightUtil
48
{
49
    public static function expireAd()
50
    {
51
        global $xoopsDB, $xoopsConfig, $xoopsModule, $myts, $meta, $moduleDirName, $main_lang;
52
53
        $datenow = time();
54
        $message = '';
55
56
        $result5
57
            = $xoopsDB->query('SELECT lid, title, expire, type, desctext, date, email, submitter, photo, valid, hits, comments, remind FROM ' . $xoopsDB->prefix('adslight_listing')
58
                              . " WHERE valid='Yes'");
59
60
        while (list($lids, $title, $expire, $type, $desctext, $dateann, $email, $submitter, $photo, $valid, $hits, $comments, $remind)
61
            = $xoopsDB->fetchRow($result5)) {
62
            $title     = $myts->htmlSpecialChars($title);
63
            $expire    = $myts->htmlSpecialChars($expire);
64
            $type      = $myts->htmlSpecialChars($type);
65
            $desctext  =& $myts->displayTarea($desctext, 1, 1, 1, 1, 1);
66
            $submitter = $myts->htmlSpecialChars($submitter);
67
            $remind    = $myts->htmlSpecialChars($remind);
68
            $supprdate = $dateann + ($expire * 86400);
69
            $almost    = $GLOBALS['xoopsModuleConfig']['adslight_almost'];
70
71
            // give warning that add is about to expire
72
73
            if ($almost > 0 && ($supprdate - $almost * 86400) < $datenow
74
                && $valid === 'Yes'
75
                && $remind == 0
76
            ) {
77
                $xoopsDB->queryF('UPDATE ' . $xoopsDB->prefix('adslight_listing') . " SET remind='1' WHERE lid=$lids");
78
79
                if ($email) {
80
                    $tags               = array();
81
                    $subject            = '' . _ADSLIGHT_ALMOST . '';
82
                    $tags['TITLE']      = $title;
83
                    $tags['HELLO']      = '' . _ADSLIGHT_HELLO . '';
84
                    $tags['YOUR_AD_ON'] = '' . _ADSLIGHT_YOUR_AD_ON . '';
85
                    $tags['VEDIT_AD']   = '' . _ADSLIGHT_VEDIT_AD . '';
86
                    $tags['YOUR_AD']    = '' . _ADSLIGHT_YOUR_AD . '';
87
                    $tags['SOON']       = '' . _ADSLIGHT_SOON . '';
88
                    $tags['VIEWED']     = '' . _ADSLIGHT_VU . '';
89
                    $tags['TIMES']      = '' . _ADSLIGHT_TIMES . '';
90
                    $tags['WEBMASTER']  = '' . _ADSLIGHT_WEBMASTER . '';
91
                    $tags['THANKS']     = '' . _ADSLIGHT_THANKS . '';
92
                    $tags['TYPE']       = static::getNameType($type);
93
                    $tags['DESCTEXT']   = $desctext;
94
                    $tags['HITS']       = $hits;
95
                    $tags['META_TITLE'] = $meta['title'];
96
                    $tags['SUBMITTER']  = $submitter;
97
                    $tags['DURATION']   = $expire;
98
                    $tags['LINK_URL']   = XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname') . '/viewads.php?' . '&lid=' . $lids;
99
                    $mail               =& getMailer();
100
                    $mail->setTemplateDir(XOOPS_ROOT_PATH . '/modules/' . $xoopsModule->getVar('dirname') . '/language/' . $xoopsConfig['language'] . '/mail_template/');
101
                    $mail->setTemplate('listing_expires.tpl');
102
                    $mail->useMail();
103
                    $mail->multimailer->isHTML(true);
104
                    $mail->setFromName($meta['title']);
105
                    $mail->setFromEmail($xoopsConfig['adminmail']);
106
                    $mail->setToEmails($email);
107
                    $mail->setSubject($subject);
108
                    $mail->assign($tags);
109
                    $mail->send();
110
                    echo $mail->getErrors();
111
                }
112
            }
113
114
            // expire ad
115
116
            if ($supprdate < $datenow) {
117
                if ($photo != 0) {
118
                    $result2 = $xoopsDB->query('SELECT url FROM ' . $xoopsDB->prefix('adslight_pictures') . ' WHERE lid=' . $xoopsDB->escape($lids));
119
120
                    while (list($url) = $xoopsDB->fetchRow($result2)) {
121
                        $destination  = XOOPS_ROOT_PATH . '/uploads/AdsLight';
122
                        $destination2 = XOOPS_ROOT_PATH . '/uploads/AdsLight/thumbs';
123
                        $destination3 = XOOPS_ROOT_PATH . '/uploads/AdsLight/midsize';
124
                        if (file_exists("$destination/$url")) {
125
                            unlink("$destination/$url");
126
                        }
127
                        if (file_exists("$destination2/thumb_$url")) {
128
                            unlink("$destination2/thumb_$url");
129
                        }
130
                        if (file_exists("$destination3/resized_$url")) {
131
                            unlink("$destination3/resized_$url");
132
                        }
133
                    }
134
                }
135
136
                $xoopsDB->queryF('DELETE FROM ' . $xoopsDB->prefix('adslight_listing') . ' WHERE lid=' . $xoopsDB->escape($lids));
137
138
                //  Specification for Japan:
139
                //  $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."";
140
                if ($email) {
141
                    $tags               = array();
142
                    $subject            = '' . _ADSLIGHT_STOP . '';
143
                    $tags['TITLE']      = $title;
144
                    $tags['HELLO']      = '' . _ADSLIGHT_HELLO . '';
145
                    $tags['TYPE']       = static::getNameType($type);
146
                    $tags['DESCTEXT']   = $desctext;
147
                    $tags['HITS']       = $hits;
148
                    $tags['META_TITLE'] = $meta['title'];
149
                    $tags['SUBMITTER']  = $submitter;
150
                    $tags['YOUR_AD_ON'] = '' . _ADSLIGHT_YOUR_AD_ON . '';
151
                    $tags['EXPIRED']    = '' . _ADSLIGHT_EXPIRED . '';
152
                    $tags['MESSTEXT']   = stripslashes($message);
153
                    $tags['OTHER']      = '' . _ADSLIGHT_OTHER . '';
154
                    $tags['WEBMASTER']  = '' . _ADSLIGHT_WEBMASTER . '';
155
                    $tags['THANKS']     = '' . _ADSLIGHT_THANKS . '';
156
                    $tags['VIEWED']     = '' . _ADSLIGHT_VU . '';
157
                    $tags['TIMES']      = '' . _ADSLIGHT_TIMES . '';
158
                    $tags['TEAM']       = '' . _ADSLIGHT_TEAM . '';
159
                    $tags['DURATION']   = $expire;
160
                    $tags['LINK_URL']   = XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname') . '/viewads.php?' . '&lid=' . $lids;
161
                    $mail               =& getMailer();
162
                    $mail->setTemplateDir(XOOPS_ROOT_PATH . '/modules/' . $xoopsModule->getVar('dirname') . '/language/' . $xoopsConfig['language'] . '/mail_template/');
163
                    $mail->setTemplate('listing_expired.tpl');
164
                    $mail->useMail();
165
                    $mail->multimailer->isHTML(true);
166
                    $mail->setFromName($meta['title']);
167
                    $mail->setFromEmail($xoopsConfig['adminmail']);
168
                    $mail->setToEmails($email);
169
                    $mail->setSubject($subject);
170
                    $mail->assign($tags);
171
                    $mail->send();
172
                    echo $mail->getErrors();
173
                }
174
            }
175
        }
176
    }
177
178
    //updates rating data in itemtable for a given user
179
180
    /**
181
     * @param $sel_id
182
     */
183
    public static function updateUserRating($sel_id)
184
    {
185
        global $xoopsDB, $moduleDirName, $main_lang;
186
187
        $usid = Request::getInt('usid', 0, 'GET');
188
189
        $query = 'SELECT rating FROM ' . $xoopsDB->prefix('adslight_user_votedata') . ' WHERE usid=' . $xoopsDB->escape($sel_id) . '';
190
        //echo $query;
191
        $voteresult  = $xoopsDB->query($query);
192
        $votesDB     = $xoopsDB->getRowsNum($voteresult);
193
        $totalrating = 0;
194
        while (list($rating) = $xoopsDB->fetchRow($voteresult)) {
195
            $totalrating += $rating;
196
        }
197
        $finalrating = $totalrating / $votesDB;
198
        $finalrating = number_format($finalrating, 4);
199
        $query       = 'UPDATE ' . $xoopsDB->prefix('adslight_listing') . " SET user_rating=$finalrating, user_votes=$votesDB WHERE usid=" . $xoopsDB->escape($sel_id) . '';
200
        //echo $query;
201
        $xoopsDB->query($query) || exit();
202
    }
203
204
    //updates rating data in itemtable for a given item
205
206
    /**
207
     * @param $sel_id
208
     */
209
    public static function updateItemRating($sel_id)
210
    {
211
        global $xoopsDB, $moduleDirName, $main_lang;
212
213
        $lid = Request::getInt('lid', 0, 'GET');
214
215
        $query = 'SELECT rating FROM ' . $xoopsDB->prefix('adslight_item_votedata') . ' WHERE lid=' . $xoopsDB->escape($sel_id) . '';
216
        //echo $query;
217
        $voteresult  = $xoopsDB->query($query);
218
        $votesDB     = $xoopsDB->getRowsNum($voteresult);
219
        $totalrating = 0;
220
        while (list($rating) = $xoopsDB->fetchRow($voteresult)) {
221
            $totalrating += $rating;
222
        }
223
        $finalrating = $totalrating / $votesDB;
224
        $finalrating = number_format($finalrating, 4);
225
        $query       = 'UPDATE ' . $xoopsDB->prefix('adslight_listing') . " SET item_rating=$finalrating, item_votes=$votesDB WHERE lid=" . $xoopsDB->escape($sel_id) . '';
226
        //echo $query;
227
        $xoopsDB->query($query) || exit();
228
    }
229
230
    /**
231
     * @param        $sel_id
232
     * @param string $status
233
     *
234
     * @return int
235
     */
236
    public static function getTotalItems($sel_id, $status = '')
237
    {
238
        global $xoopsDB, $mytree, $moduleDirName;
239
        $categories = AdslightUtil::getMyItemIds('adslight_view');
240
        $count      = 0;
241
        $arr        = array();
242
        if (in_array($sel_id, $categories)) {
243
            $query = 'SELECT SQL_CACHE count(*) FROM ' . $xoopsDB->prefix('adslight_listing') . ' WHERE cid=' . (int)$sel_id . " and valid='Yes' AND status!='1'";
244
245
            $result = $xoopsDB->query($query);
246
            list($thing) = $xoopsDB->fetchRow($result);
247
            $count = $thing;
248
            $arr   = $mytree->getAllChildId($sel_id);
249
            $size  = count($arr);
250
            for ($i = 0; $i < $size; ++$i) {
251
                if (in_array($arr[$i], $categories)) {
252
                    $query2 = 'SELECT SQL_CACHE count(*) FROM ' . $xoopsDB->prefix('adslight_listing') . ' WHERE cid=' . (int)$arr[$i] . " and valid='Yes' AND status!='1'";
253
254
                    $result2 = $xoopsDB->query($query2);
255
                    list($thing) = $xoopsDB->fetchRow($result2);
256
                    $count += $thing;
257
                }
258
            }
259
        }
260
261
        return $count;
262
    }
263
264
    /**
265
     * @param $permtype
266
     *
267
     * @return mixed
268
     */
269
    public static function getMyItemIds($permtype)
270
    {
271
        global $moduleDirName;
272
        static $permissions = array();
273
        if (is_array($permissions)
274
            && array_key_exists($permtype, $permissions)
275
        ) {
276
            return $permissions[$permtype];
277
        }
278
279
        /** @var XoopsModuleHandler $moduleHandler */
280
        $moduleHandler = xoops_getHandler('module');
281
        $myModule      = $moduleHandler->getByDirname('adslight');
282
        $groups
283
                       = is_object($GLOBALS['xoopsUser']) ? $GLOBALS['xoopsUser']->getGroups() : XOOPS_GROUP_ANONYMOUS;
284
        /** @var XoopsGroupPermHandler $gpermHandler */
285
        $gpermHandler           = xoops_getHandler('groupperm');
286
        $categories             = $gpermHandler->getItemIds($permtype, $groups, $myModule->getVar('mid'));
287
        $permissions[$permtype] = $categories;
288
289
        return $categories;
290
    }
291
292
    /**
293
     * Returns a module's option
294
     * @param        $option module option's name
295
     * @param string $repmodule
296
     *
297
     * @return option's value
298
     */
299
    public static function getModuleOption($option, $repmodule = 'adslight')
300
    {
301
        global $xoopsModule;
302
        static $tbloptions = array();
303
        if (is_array($tbloptions) && array_key_exists($option, $tbloptions)) {
304
            return $tbloptions[$option];
305
        }
306
307
        $retval = false;
308
        if (isset($GLOBALS['xoopsModuleConfig'])
309
            && (is_object($xoopsModule)
310
                && $xoopsModule->getVar('dirname') == $repmodule
311
                && $xoopsModule->getVar('isactive'))
312
        ) {
313
            if (isset($GLOBALS['xoopsModuleConfig'][$option])) {
314
                $retval = $GLOBALS['xoopsModuleConfig'][$option];
315
            }
316
        } else {
317
            /** @var XoopsModuleHandler $moduleHandler */
318
            $moduleHandler = xoops_getHandler('module');
319
            $module        = $moduleHandler->getByDirname($repmodule);
320
            /** @var XoopsConfigHandler $configHandler */
321
            $configHandler = xoops_getHandler('config');
322
            if ($module) {
323
                $moduleConfig =& $configHandler->getConfigsByCat(0, $GLOBALS['xoopsModule']->getVar('mid'));
324
                if (isset($moduleConfig[$option])) {
325
                    $retval = $moduleConfig[$option];
326
                }
327
            }
328
        }
329
        $tbloptions[$option] = $retval;
330
331
        return $retval;
332
    }
333
334
    public static function showImage()
335
    {
336
        global $moduleDirName;
337
        echo "<script type=\"text/javascript\">\n";
338
        echo "<!--\n\n";
339
        echo "function showimage() {\n";
340
        echo "if (!document.images)\n";
341
        echo "return\n";
342
        echo "document.images.avatar.src=\n";
343
        echo "'" . XOOPS_URL . "/modules/adslight/assets/images/img_cat/' + document.imcat.img.options[document.imcat.img.selectedIndex].value\n";
344
        echo "}\n\n";
345
        echo "//-->\n";
346
        echo "</script>\n";
347
    }
348
349
    //Reusable Link Sorting Functions
350
351
    /**
352
     * @param $orderby
353
     *
354
     * @return string
355
     */
356
    public static function convertOrderByIn($orderby)
357
    {
358
        switch (trim($orderby)) {
359
            case 'titleA':
360
                $orderby = 'title ASC';
361
                break;
362
            case 'dateA':
363
                $orderby = 'date ASC';
364
                break;
365
            case 'hitsA':
366
                $orderby = 'hits ASC';
367
                break;
368
            case 'priceA':
369
                $orderby = 'price ASC';
370
                break;
371
            case 'titleD':
372
                $orderby = 'title DESC';
373
                break;
374
            case 'hitsD':
375
                $orderby = 'hits DESC';
376
                break;
377
            case 'priceD':
378
                $orderby = 'price DESC';
379
                break;
380
            case'dateD':
381
            default:
382
                $orderby = 'date DESC';
383
                break;
384
        }
385
386
        return $orderby;
387
    }
388
389
    /**
390
     * @param $orderby
391
     *
392
     * @return string
393
     */
394
    public static function convertOrderByTrans($orderby)
395
    {
396
        global $main_lang;
397
        $orderbyTrans = '';
398
        if ($orderby === 'hits ASC') {
399
            $orderbyTrans = '' . _ADSLIGHT_POPULARITYLTOM . '';
400
        }
401
        if ($orderby === 'hits DESC') {
402
            $orderbyTrans = '' . _ADSLIGHT_POPULARITYMTOL . '';
403
        }
404
        if ($orderby === 'title ASC') {
405
            $orderbyTrans = '' . _ADSLIGHT_TITLEATOZ . '';
406
        }
407
        if ($orderby === 'title DESC') {
408
            $orderbyTrans = '' . _ADSLIGHT_TITLEZTOA . '';
409
        }
410
        if ($orderby === 'date ASC') {
411
            $orderbyTrans = '' . _ADSLIGHT_DATEOLD . '';
412
        }
413
        if ($orderby === 'date DESC') {
414
            $orderbyTrans = '' . _ADSLIGHT_DATENEW . '';
415
        }
416
        if ($orderby === 'price ASC') {
417
            $orderbyTrans = _ADSLIGHT_PRICELTOH;
418
        }
419
        if ($orderby === 'price DESC') {
420
            $orderbyTrans = '' . _ADSLIGHT_PRICEHTOL . '';
421
        }
422
423
        return $orderbyTrans;
424
    }
425
426
    /**
427
     * @param $orderby
428
     *
429
     * @return string
430
     */
431
    public static function convertOrderByOut($orderby)
432
    {
433
        if ($orderby === 'title ASC') {
434
            $orderby = 'titleA';
435
        }
436
        if ($orderby === 'date ASC') {
437
            $orderby = 'dateA';
438
        }
439
        if ($orderby === 'hits ASC') {
440
            $orderby = 'hitsA';
441
        }
442
        if ($orderby === 'price ASC') {
443
            $orderby = 'priceA';
444
        }
445
        if ($orderby === 'title DESC') {
446
            $orderby = 'titleD';
447
        }
448
        if ($orderby === 'date DESC') {
449
            $orderby = 'dateD';
450
        }
451
        if ($orderby === 'hits DESC') {
452
            $orderby = 'hitsD';
453
        }
454
        if ($orderby === 'price DESC') {
455
            $orderby = 'priceD';
456
        }
457
458
        return $orderby;
459
    }
460
461
    /**
462
     * @param string $caption
463
     * @param string $name
464
     * @param string $value
465
     * @param string $width
466
     * @param string $height
467
     * @param string $supplemental
468
     *
469
     * @return XoopsFormDhtmlTextArea|XoopsFormEditor
470
     */
471
    public static function getEditor($caption, $name, $value = '', $width = '100%', $height = '300px', $supplemental = '')
472
    {
473
        global $xoopsModule;
474
        $options = array();
475
        $isAdmin = $GLOBALS['xoopsUser']->isAdmin($xoopsModule->getVar('mid'));
476
477
        if (class_exists('XoopsFormEditor')) {
478
            $options['name']   = $name;
479
            $options['value']  = $value;
480
            $options['rows']   = 20;
481
            $options['cols']   = '100%';
482
            $options['width']  = $width;
483
            $options['height'] = $height;
484
            if ($isAdmin) {
485
                $myEditor = new XoopsFormEditor(ucfirst($name), $GLOBALS['xoopsModuleConfig']['adslightAdminUser'], $options, $nohtml = false, $onfailure = 'textarea');
486
            } else {
487
                $myEditor = new XoopsFormEditor(ucfirst($name), $GLOBALS['xoopsModuleConfig']['adslightEditorUser'], $options, $nohtml = false, $onfailure = 'textarea');
488
            }
489
        } else {
490
            $myEditor = new XoopsFormDhtmlTextArea(ucfirst($name), $name, $value, '100%', '100%');
491
        }
492
493
        //        $form->addElement($descEditor);
494
495
        return $myEditor;
496
    }
497
498
    /**
499
     * @param $tablename
500
     *
501
     * @return bool
502
     */
503
    public static function checkTableExists($tablename)
504
    {
505
        global $xoopsDB;
506
        $result = $xoopsDB->queryF("SHOW TABLES LIKE '$tablename'");
507
508
        return ($xoopsDB->getRowsNum($result) > 0);
509
    }
510
511
    /**
512
     * @param $fieldname
513
     * @param $table
514
     *
515
     * @return bool
516
     */
517
    public static function checkFieldExists($fieldname, $table)
518
    {
519
        global $xoopsDB;
520
        $result
521
            = $xoopsDB->queryF("SHOW COLUMNS FROM $table LIKE '$fieldname'");
522
523
        return ($xoopsDB->getRowsNum($result) > 0);
524
    }
525
526
    /**
527
     * @param $field
528
     * @param $table
529
     *
530
     * @return mixed
531
     */
532
    public static function addField($field, $table)
533
    {
534
        global $xoopsDB;
535
        $result = $xoopsDB->queryF('ALTER TABLE ' . $table . " ADD $field;");
536
537
        return $result;
538
    }
539
540
    /**
541
     * @param $cid
542
     *
543
     * @return bool
544
     */
545
    public static function getCatNameFromId($cid)
546
    {
547
        global $xoopsDB, $xoopsConfig, $myts, $moduleDirName;
548
549
        $sql = 'SELECT SQL_CACHE title FROM ' . $xoopsDB->prefix('adslight_categories') . " WHERE cid = '$cid'";
550
551
        if (!$result = $xoopsDB->query($sql)) {
552
            return false;
553
        }
554
555
        if (!$arr = $xoopsDB->fetchArray($result)) {
556
            return false;
557
        }
558
559
        $title = $arr['title'];
560
561
        return $title;
562
    }
563
564
    /**
565
     * @return mixed
566
     */
567
    public static function goCategory()
568
    {
569
        global $xoopsDB;
570
571
        $xt   = new XoopsTree($xoopsDB->prefix('adslight_categories'), 'cid', 'pid');
572
        $jump = XOOPS_URL . '/modules/adslight/viewcats.php?cid=';
573
        ob_start();
574
        $xt->makeMySelBox('title', 'title', 0, 1, 'pid', "location=\"" . $jump . "\"+this.options[this.selectedIndex].value");
575
        $block['selectbox'] = ob_get_contents();
576
        ob_end_clean();
577
578
        return $block;
579
    }
580
581
    // ADSLIGHT Version 2 //
582
    // Fonction rss.php RSS par categories
583
    /**
584
     * @return array
585
     */
586
    public static function returnAllAdsRss()
587
    {
588
        global $xoopsDB;
589
590
        $cid = Request::getInt('cid', null, 'GET');
591
592
        $result = array();
593
594
        $sql = 'SELECT lid, title, price, date, town FROM ' . $xoopsDB->prefix('adslight_listing') . " WHERE valid='yes' AND cid=" . $xoopsDB->escape($cid) . ' ORDER BY date DESC';
595
596
        $resultValues = $xoopsDB->query($sql);
597
        while (($resultTemp = $xoopsDB->fetchBoth($resultValues)) !== false) {
598
            array_push($result, $resultTemp);
599
        }
600
601
        return $result;
602
    }
603
604
    // Fonction fluxrss.php RSS Global
605
606
    /**
607
     * @return array
608
     */
609
    public static function returnAllAdsFluxRss()
610
    {
611
        global $xoopsDB;
612
613
        $result = array();
614
615
        $sql = 'SELECT lid, title, price, desctext, date, town FROM ' . $xoopsDB->prefix('adslight_listing') . " WHERE valid='yes' ORDER BY date DESC LIMIT 0,15";
616
617
        $resultValues = $xoopsDB->query($sql);
618
        while (($resultTemp = $xoopsDB->fetchBoth($resultValues)) !== false) {
619
            array_push($result, $resultTemp);
620
        }
621
622
        return $result;
623
    }
624
625
    /**
626
     * @param $type
627
     *
628
     * @return mixed
629
     */
630
    public static function getNameType($type)
631
    {
632
        global $xoopsDB;
633
        $sql = $xoopsDB->query('SELECT nom_type FROM ' . $xoopsDB->prefix('adslight_type') . " WHERE id_type='" . $xoopsDB->escape($type) . "'");
634
        list($nom_type) = $xoopsDB->fetchRow($sql);
635
636
        return $nom_type;
637
    }
638
639
    /**
640
     * @param $format
641
     * @param $number
642
     *
643
     * @return mixed
644
     */
645
    public static function getMoneyFormat($format, $number)
646
    {
647
        $regex = '/%((?:[\^!\-]|\+|\(|\=.)*)([0-9]+)?' . '(?:#([0-9]+))?(?:\.([0-9]+))?([in%])/';
648
        if (setlocale(LC_MONETARY, 0) === 'C') {
649
            setlocale(LC_MONETARY, '');
650
        }
651
652
        setlocale(LC_ALL, 'en_US');
653
        //        setlocale(LC_ALL, 'fr_FR');
654
655
        $locale = localeconv();
656
        preg_match_all($regex, $format, $matches, PREG_SET_ORDER);
657
        foreach ($matches as $fmatch) {
658
            $value      = (float)$number;
659
            $flags      = array(
660
                'fillchar'  => preg_match('/\=(.)/', $fmatch[1], $match) ? $match[1] : ' ',
661
                'nogroup'   => preg_match('/\^/', $fmatch[1]) > 0,
662
                'usesignal' => preg_match('/\+|\(/', $fmatch[1], $match) ? $match[0] : '+',
663
                'nosimbol'  => preg_match('/\!/', $fmatch[1]) > 0,
664
                'isleft'    => preg_match('/\-/', $fmatch[1]) > 0
665
            );
666
            $width      = trim($fmatch[2]) ? (int)$fmatch[2] : 0;
667
            $left       = trim($fmatch[3]) ? (int)$fmatch[3] : 0;
668
            $right
669
                        = trim($fmatch[4]) ? (int)$fmatch[4] : $locale['int_frac_digits'];
670
            $conversion = $fmatch[5];
671
672
            $positive = true;
673
            if ($value < 0) {
674
                $positive = false;
675
                $value    *= -1;
676
            }
677
            $letter = $positive ? 'p' : 'n';
678
679
            $prefix = $suffix = $cprefix = $csuffix = $signal = '';
680
681
            $signal
682
                = $positive ? $locale['positive_sign'] : $locale['negative_sign'];
683
            switch (true) {
684
                case $locale["{$letter}_sign_posn"] == 1
685
                     && $flags['usesignal'] == '+':
686
                    $prefix = $signal;
687
                    break;
688
                case $locale["{$letter}_sign_posn"] == 2
689
                     && $flags['usesignal'] == '+':
690
                    $suffix = $signal;
691
                    break;
692
                case $locale["{$letter}_sign_posn"] == 3
693
                     && $flags['usesignal'] == '+':
694
                    $cprefix = $signal;
695
                    break;
696
                case $locale["{$letter}_sign_posn"] == 4
697
                     && $flags['usesignal'] == '+':
698
                    $csuffix = $signal;
699
                    break;
700
                case $flags['usesignal'] === '(':
701
                case $locale["{$letter}_sign_posn"] == 0:
702
                    $prefix = '(';
703
                    $suffix = ')';
704
                    break;
705
            }
706
            if (!$flags['nosimbol']) {
707
                $currency = $cprefix . ($conversion === 'i' ? $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 = strlen($prefix) + strlen($currency) + 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
     * Function responsible for checking if a directory exists, we can also write in and create an index.html file
738
     *
739
     * @param string $folder The full path of the directory to check
740
     *
741
     * @return void
742
     */
743
    public static function createFolder($folder)
744
    {
745
        try {
746
            if (!@mkdir($folder) && !is_dir($folder)) {
747
                throw new \RuntimeException(sprintf('Unable to create the %s directory', $folder));
748
            } else {
749
                file_put_contents($folder . '/index.html', '<script>history.go(-1);</script>');
750
            }
751
        } catch (Exception $e) {
752
            echo 'Caught exception: ', $e->getMessage(), "\n", '<br/>';
753
        }
754
    }
755
756
    /**
757
     * @param $file
758
     * @param $folder
759
     * @return bool
760
     */
761
    public static function copyFile($file, $folder)
762
    {
763
        return copy($file, $folder);
764
        //        try {
765
        //            if (!is_dir($folder)) {
766
        //                throw new \RuntimeException(sprintf('Unable to copy file as: %s ', $folder));
767
        //            } else {
768
        //                return copy($file, $folder);
769
        //            }
770
        //        } catch (Exception $e) {
771
        //            echo 'Caught exception: ', $e->getMessage(), "\n", "<br/>";
772
        //        }
773
        //        return false;
774
    }
775
776
    /**
777
     * @param $src
778
     * @param $dst
779
     */
780
    public static function recurseCopy($src, $dst)
781
    {
782
        $dir = opendir($src);
783
        //    @mkdir($dst);
784
        while (false !== ($file = readdir($dir))) {
785
            if (($file !== '.') && ($file !== '..')) {
786
                if (is_dir($src . '/' . $file)) {
787
                    self::recurseCopy($src . '/' . $file, $dst . '/' . $file);
788
                } else {
789
                    copy($src . '/' . $file, $dst . '/' . $file);
790
                }
791
            }
792
        }
793
        closedir($dir);
794
    }
795
796
    /**
797
     *
798
     * Verifies XOOPS version meets minimum requirements for this module
799
     * @static
800
     * @param XoopsModule $module
801
     *
802
     * @return bool true if meets requirements, false if not
803
     */
804
    public static function checkXoopsVer(XoopsModule $module)
805
    {
806
        xoops_loadLanguage('admin', $module->dirname());
807
        //check for minimum XOOPS version
808
        $currentVer  = substr(XOOPS_VERSION, 6); // get the numeric part of string
809
        $currArray   = explode('.', $currentVer);
810
        $requiredVer = '' . $module->getInfo('min_xoops'); //making sure it's a string
811
        $reqArray    = explode('.', $requiredVer);
812
        $success     = true;
813
        foreach ($reqArray as $k => $v) {
814
            if (isset($currArray[$k])) {
815
                if ($currArray[$k] > $v) {
816
                    break;
817
                } elseif ($currArray[$k] == $v) {
818
                    continue;
819
                } else {
820
                    $success = false;
821
                    break;
822
                }
823
            } else {
824
                if ((int)$v > 0) { // handles things like x.x.x.0_RC2
825
                    $success = false;
826
                    break;
827
                }
828
            }
829
        }
830
831
        if (!$success) {
832
            $module->setErrors(sprintf(_AM_ADSLIGHT_ERROR_BAD_XOOPS, $requiredVer, $currentVer));
833
        }
834
835
        return $success;
836
    }
837
838
    /**
839
     *
840
     * Verifies PHP version meets minimum requirements for this module
841
     * @static
842
     * @param XoopsModule $module
843
     *
844
     * @return bool true if meets requirements, false if not
845
     */
846
    public static function checkPhpVer(XoopsModule $module)
847
    {
848
        xoops_loadLanguage('admin', $module->dirname());
849
        // check for minimum PHP version
850
        $success = true;
851
        $verNum  = phpversion();
852
        $reqVer  =& $module->getInfo('min_php');
853
        if (false !== $reqVer && '' !== $reqVer) {
854
            if (version_compare($verNum, $reqVer, '<')) {
855
                $module->setErrors(sprintf(_AM_ADSLIGHT_ERROR_BAD_PHP, $reqVer, $verNum));
856
                $success = false;
857
            }
858
        }
859
860
        return $success;
861
    }
862
}
863

class/utilities.php 1 location

@@ 47-842 (lines=796) @@
44
/**
45
 * Class AdslightUtilities
46
 */
47
class AdslightUtilities
48
{
49
    public static function expireAd()
50
    {
51
        global $xoopsDB, $xoopsConfig, $xoopsModule, $myts, $meta, $moduleDirName, $main_lang;
52
53
        $datenow = time();
54
        $message = '';
55
56
        $result5 = $xoopsDB->query('SELECT lid, title, expire, type, desctext, date, email, submitter, photo, valid, hits, comments, remind FROM '
57
                                   . $xoopsDB->prefix('adslight_listing')
58
                                   . " WHERE valid='Yes'");
59
60
        while (list($lids, $title, $expire, $type, $desctext, $dateann, $email, $submitter, $photo, $valid, $hits, $comments, $remind) = $xoopsDB->fetchRow($result5)) {
61
            $title     = $myts->htmlSpecialChars($title);
62
            $expire    = $myts->htmlSpecialChars($expire);
63
            $type      = $myts->htmlSpecialChars($type);
64
            $desctext  =& $myts->displayTarea($desctext, 1, 1, 1, 1, 1);
65
            $submitter = $myts->htmlSpecialChars($submitter);
66
            $remind    = $myts->htmlSpecialChars($remind);
67
            $supprdate = $dateann + ($expire * 86400);
68
            $almost    = $GLOBALS['xoopsModuleConfig']['adslight_almost'];
69
70
            // give warning that add is about to expire
71
72
            if ($almost > 0 && ($supprdate - $almost * 86400) < $datenow && $valid === 'Yes' && $remind == 0) {
73
                $xoopsDB->queryF('UPDATE ' . $xoopsDB->prefix('adslight_listing') . " SET remind='1' WHERE lid=$lids");
74
75
                if ($email) {
76
                    $tags               = array();
77
                    $subject            = '' . _ADSLIGHT_ALMOST . '';
78
                    $tags['TITLE']      = $title;
79
                    $tags['HELLO']      = '' . _ADSLIGHT_HELLO . '';
80
                    $tags['YOUR_AD_ON'] = '' . _ADSLIGHT_YOUR_AD_ON . '';
81
                    $tags['VEDIT_AD']   = '' . _ADSLIGHT_VEDIT_AD . '';
82
                    $tags['YOUR_AD']    = '' . _ADSLIGHT_YOUR_AD . '';
83
                    $tags['SOON']       = '' . _ADSLIGHT_SOON . '';
84
                    $tags['VIEWED']     = '' . _ADSLIGHT_VU . '';
85
                    $tags['TIMES']      = '' . _ADSLIGHT_TIMES . '';
86
                    $tags['WEBMASTER']  = '' . _ADSLIGHT_WEBMASTER . '';
87
                    $tags['THANKS']     = '' . _ADSLIGHT_THANKS . '';
88
                    $tags['TYPE']       = static::getNameType($type);
89
                    $tags['DESCTEXT']   = $desctext;
90
                    $tags['HITS']       = $hits;
91
                    $tags['META_TITLE'] = $meta['title'];
92
                    $tags['SUBMITTER']  = $submitter;
93
                    $tags['DURATION']   = $expire;
94
                    $tags['LINK_URL']   = XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname') . '/viewads.php?' . '&lid=' . $lids;
95
                    $mail               =& getMailer();
96
                    $mail->setTemplateDir(XOOPS_ROOT_PATH . '/modules/' . $xoopsModule->getVar('dirname') . '/language/' . $xoopsConfig['language'] . '/mail_template/');
97
                    $mail->setTemplate('listing_expires.tpl');
98
                    $mail->useMail();
99
                    $mail->multimailer->isHTML(true);
100
                    $mail->setFromName($meta['title']);
101
                    $mail->setFromEmail($xoopsConfig['adminmail']);
102
                    $mail->setToEmails($email);
103
                    $mail->setSubject($subject);
104
                    $mail->assign($tags);
105
                    $mail->send();
106
                    echo $mail->getErrors();
107
                }
108
            }
109
110
            // expire ad
111
112
            if ($supprdate < $datenow) {
113
                if ($photo != 0) {
114
                    $result2 = $xoopsDB->query('SELECT url FROM ' . $xoopsDB->prefix('adslight_pictures') . ' WHERE lid=' . $xoopsDB->escape($lids));
115
116
                    while (list($url) = $xoopsDB->fetchRow($result2)) {
117
                        $destination  = XOOPS_ROOT_PATH . '/uploads/AdsLight';
118
                        $destination2 = XOOPS_ROOT_PATH . '/uploads/AdsLight/thumbs';
119
                        $destination3 = XOOPS_ROOT_PATH . '/uploads/AdsLight/midsize';
120
                        if (file_exists("$destination/$url")) {
121
                            unlink("$destination/$url");
122
                        }
123
                        if (file_exists("$destination2/thumb_$url")) {
124
                            unlink("$destination2/thumb_$url");
125
                        }
126
                        if (file_exists("$destination3/resized_$url")) {
127
                            unlink("$destination3/resized_$url");
128
                        }
129
                    }
130
                }
131
132
                $xoopsDB->queryF('DELETE FROM ' . $xoopsDB->prefix('adslight_listing') . ' WHERE lid=' . $xoopsDB->escape($lids));
133
134
                //  Specification for Japan:
135
                //  $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."";
136
                if ($email) {
137
                    $tags               = array();
138
                    $subject            = '' . _ADSLIGHT_STOP . '';
139
                    $tags['TITLE']      = $title;
140
                    $tags['HELLO']      = '' . _ADSLIGHT_HELLO . '';
141
                    $tags['TYPE']       = static::getNameType($type);
142
                    $tags['DESCTEXT']   = $desctext;
143
                    $tags['HITS']       = $hits;
144
                    $tags['META_TITLE'] = $meta['title'];
145
                    $tags['SUBMITTER']  = $submitter;
146
                    $tags['YOUR_AD_ON'] = '' . _ADSLIGHT_YOUR_AD_ON . '';
147
                    $tags['EXPIRED']    = '' . _ADSLIGHT_EXPIRED . '';
148
                    $tags['MESSTEXT']   = stripslashes($message);
149
                    $tags['OTHER']      = '' . _ADSLIGHT_OTHER . '';
150
                    $tags['WEBMASTER']  = '' . _ADSLIGHT_WEBMASTER . '';
151
                    $tags['THANKS']     = '' . _ADSLIGHT_THANKS . '';
152
                    $tags['VIEWED']     = '' . _ADSLIGHT_VU . '';
153
                    $tags['TIMES']      = '' . _ADSLIGHT_TIMES . '';
154
                    $tags['TEAM']       = '' . _ADSLIGHT_TEAM . '';
155
                    $tags['DURATION']   = $expire;
156
                    $tags['LINK_URL']   = XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname') . '/viewads.php?' . '&lid=' . $lids;
157
                    $mail               =& getMailer();
158
                    $mail->setTemplateDir(XOOPS_ROOT_PATH . '/modules/' . $xoopsModule->getVar('dirname') . '/language/' . $xoopsConfig['language'] . '/mail_template/');
159
                    $mail->setTemplate('listing_expired.tpl');
160
                    $mail->useMail();
161
                    $mail->multimailer->isHTML(true);
162
                    $mail->setFromName($meta['title']);
163
                    $mail->setFromEmail($xoopsConfig['adminmail']);
164
                    $mail->setToEmails($email);
165
                    $mail->setSubject($subject);
166
                    $mail->assign($tags);
167
                    $mail->send();
168
                    echo $mail->getErrors();
169
                }
170
            }
171
        }
172
    }
173
174
    //updates rating data in itemtable for a given user
175
    /**
176
     * @param $sel_id
177
     */
178
    public static function updateUserRating($sel_id)
179
    {
180
        global $xoopsDB, $moduleDirName, $main_lang;
181
182
        $usid      = Request::getInt('usid', 0, 'GET');
183
184
        $query = 'SELECT rating FROM ' . $xoopsDB->prefix('adslight_user_votedata') . ' WHERE usid=' . $xoopsDB->escape($sel_id) . '';
185
        //echo $query;
186
        $voteresult  = $xoopsDB->query($query);
187
        $votesDB     = $xoopsDB->getRowsNum($voteresult);
188
        $totalrating = 0;
189
        while (list($rating) = $xoopsDB->fetchRow($voteresult)) {
190
            $totalrating += $rating;
191
        }
192
        $finalrating = $totalrating / $votesDB;
193
        $finalrating = number_format($finalrating, 4);
194
        $query       = 'UPDATE ' . $xoopsDB->prefix('adslight_listing') . " SET user_rating=$finalrating, user_votes=$votesDB WHERE usid=" . $xoopsDB->escape($sel_id) . '';
195
        //echo $query;
196
        $xoopsDB->query($query) || exit();
197
    }
198
199
    //updates rating data in itemtable for a given item
200
    /**
201
     * @param $sel_id
202
     */
203
    public static function updateItemRating($sel_id)
204
    {
205
        global $xoopsDB, $moduleDirName, $main_lang;
206
207
        $lid      = Request::getInt('lid', 0, 'GET');
208
209
        $query = 'SELECT rating FROM ' . $xoopsDB->prefix('adslight_item_votedata') . ' WHERE lid=' . $xoopsDB->escape($sel_id) . '';
210
        //echo $query;
211
        $voteresult  = $xoopsDB->query($query);
212
        $votesDB     = $xoopsDB->getRowsNum($voteresult);
213
        $totalrating = 0;
214
        while (list($rating) = $xoopsDB->fetchRow($voteresult)) {
215
            $totalrating += $rating;
216
        }
217
        $finalrating = $totalrating / $votesDB;
218
        $finalrating = number_format($finalrating, 4);
219
        $query       = 'UPDATE ' . $xoopsDB->prefix('adslight_listing') . " SET item_rating=$finalrating, item_votes=$votesDB WHERE lid=" . $xoopsDB->escape($sel_id) . '';
220
        //echo $query;
221
        $xoopsDB->query($query) || exit();
222
    }
223
224
    /**
225
     * @param        $sel_id
226
     * @param string $status
227
     *
228
     * @return int
229
     */
230
    public static function getTotalItems($sel_id, $status = '')
231
    {
232
        global $xoopsDB, $mytree, $moduleDirName;
233
        $categories = AdslightUtilities::getMyItemIds('adslight_view');
234
        $count      = 0;
235
        $arr        = array();
236
        if (in_array($sel_id, $categories)) {
237
            $query = 'SELECT SQL_CACHE count(*) FROM ' . $xoopsDB->prefix('adslight_listing') . ' WHERE cid=' . (int)$sel_id . " and valid='Yes' AND status!='1'";
238
239
            $result = $xoopsDB->query($query);
240
            list($thing) = $xoopsDB->fetchRow($result);
241
            $count = $thing;
242
            $arr   = $mytree->getAllChildId($sel_id);
243
            $size  = count($arr);
244
            for ($i = 0; $i < $size; ++$i) {
245
                if (in_array($arr[$i], $categories)) {
246
                    $query2 = 'SELECT SQL_CACHE count(*) FROM ' . $xoopsDB->prefix('adslight_listing') . ' WHERE cid=' . (int)$arr[$i] . " and valid='Yes' AND status!='1'";
247
248
                    $result2 = $xoopsDB->query($query2);
249
                    list($thing) = $xoopsDB->fetchRow($result2);
250
                    $count += $thing;
251
                }
252
            }
253
        }
254
255
        return $count;
256
    }
257
258
    /**
259
     * @param $permtype
260
     *
261
     * @return mixed
262
     */
263
    public static function getMyItemIds($permtype)
264
    {
265
        global $moduleDirName;
266
        static $permissions = array();
267
        if (is_array($permissions) && array_key_exists($permtype, $permissions)) {
268
            return $permissions[$permtype];
269
        }
270
271
        /** @var XoopsModuleHandler $moduleHandler */
272
        $moduleHandler          = xoops_getHandler('module');
273
        $myModule               = $moduleHandler->getByDirname('adslight');
274
        $groups                 = is_object($GLOBALS['xoopsUser']) ? $GLOBALS['xoopsUser']->getGroups() : XOOPS_GROUP_ANONYMOUS;
275
        /** @var XoopsGroupPermHandler $gpermHandler */
276
        $gpermHandler           = xoops_getHandler('groupperm');
277
        $categories             = $gpermHandler->getItemIds($permtype, $groups, $myModule->getVar('mid'));
278
        $permissions[$permtype] = $categories;
279
280
        return $categories;
281
    }
282
283
    /**
284
     * @param        $option
285
     * @param string $repmodule
286
     *
287
     * @return bool
288
     */
289
    public static function getModuleOption($option, $repmodule = 'adslight')
290
    {
291
        global $xoopsModule;
292
        static $tbloptions = array();
293
        if (is_array($tbloptions) && array_key_exists($option, $tbloptions)) {
294
            return $tbloptions[$option];
295
        }
296
297
        $retval = false;
298
        if (isset($GLOBALS['xoopsModuleConfig'])
299
            && (is_object($xoopsModule) && $xoopsModule->getVar('dirname') == $repmodule
300
                && $xoopsModule->getVar('isactive'))
301
        ) {
302
            if (isset($GLOBALS['xoopsModuleConfig'][$option])) {
303
                $retval = $GLOBALS['xoopsModuleConfig'][$option];
304
            }
305
        } else {
306
            /** @var XoopsModuleHandler $moduleHandler */
307
            $moduleHandler  = xoops_getHandler('module');
308
            $module         = $moduleHandler->getByDirname($repmodule);
309
            /** @var XoopsConfigHandler $configHandler */
310
            $configHandler = xoops_getHandler('config');
311
            if ($module) {
312
                $moduleConfig =& $configHandler->getConfigsByCat(0, $GLOBALS['xoopsModule']->getVar('mid'));
313
                if (isset($moduleConfig[$option])) {
314
                    $retval = $moduleConfig[$option];
315
                }
316
            }
317
        }
318
        $tbloptions[$option] = $retval;
319
320
        return $retval;
321
    }
322
323
    public static function showImage()
324
    {
325
        global $moduleDirName;
326
        echo "<script type=\"text/javascript\">\n";
327
        echo "<!--\n\n";
328
        echo "function showimage() {\n";
329
        echo "if (!document.images)\n";
330
        echo "return\n";
331
        echo "document.images.avatar.src=\n";
332
        echo "'" . XOOPS_URL . "/modules/adslight/assets/images/img_cat/' + document.imcat.img.options[document.imcat.img.selectedIndex].value\n";
333
        echo "}\n\n";
334
        echo "//-->\n";
335
        echo "</script>\n";
336
    }
337
338
    //Reusable Link Sorting Functions
339
    /**
340
     * @param $orderby
341
     *
342
     * @return string
343
     */
344
    public static function convertOrderByIn($orderby)
345
    {
346
        switch (trim($orderby)) {
347
            case 'titleA':
348
                $orderby = 'title ASC';
349
                break;
350
            case 'dateA':
351
                $orderby = 'date ASC';
352
                break;
353
            case 'hitsA':
354
                $orderby = 'hits ASC';
355
                break;
356
            case 'priceA':
357
                $orderby = 'price ASC';
358
                break;
359
            case 'titleD':
360
                $orderby = 'title DESC';
361
                break;
362
            case 'hitsD':
363
                $orderby = 'hits DESC';
364
                break;
365
            case 'priceD':
366
                $orderby = 'price DESC';
367
                break;
368
            case'dateD':
369
            default:
370
                $orderby = 'date DESC';
371
                break;
372
        }
373
374
        return $orderby;
375
    }
376
377
    /**
378
     * @param $orderby
379
     *
380
     * @return string
381
     */
382
    public static function convertOrderByTrans($orderby)
383
    {
384
        global $main_lang;
385
        $orderbyTrans = '';
386
        if ($orderby === 'hits ASC') {
387
            $orderbyTrans = '' . _ADSLIGHT_POPULARITYLTOM . '';
388
        }
389
        if ($orderby === 'hits DESC') {
390
            $orderbyTrans = '' . _ADSLIGHT_POPULARITYMTOL . '';
391
        }
392
        if ($orderby === 'title ASC') {
393
            $orderbyTrans = '' . _ADSLIGHT_TITLEATOZ . '';
394
        }
395
        if ($orderby === 'title DESC') {
396
            $orderbyTrans = '' . _ADSLIGHT_TITLEZTOA . '';
397
        }
398
        if ($orderby === 'date ASC') {
399
            $orderbyTrans = '' . _ADSLIGHT_DATEOLD . '';
400
        }
401
        if ($orderby === 'date DESC') {
402
            $orderbyTrans = '' . _ADSLIGHT_DATENEW . '';
403
        }
404
        if ($orderby === 'price ASC') {
405
            $orderbyTrans = _ADSLIGHT_PRICELTOH;
406
        }
407
        if ($orderby === 'price DESC') {
408
            $orderbyTrans = '' . _ADSLIGHT_PRICEHTOL . '';
409
        }
410
411
        return $orderbyTrans;
412
    }
413
414
    /**
415
     * @param $orderby
416
     *
417
     * @return string
418
     */
419
    public static function convertOrderByOut($orderby)
420
    {
421
        if ($orderby === 'title ASC') {
422
            $orderby = 'titleA';
423
        }
424
        if ($orderby === 'date ASC') {
425
            $orderby = 'dateA';
426
        }
427
        if ($orderby === 'hits ASC') {
428
            $orderby = 'hitsA';
429
        }
430
        if ($orderby === 'price ASC') {
431
            $orderby = 'priceA';
432
        }
433
        if ($orderby === 'title DESC') {
434
            $orderby = 'titleD';
435
        }
436
        if ($orderby === 'date DESC') {
437
            $orderby = 'dateD';
438
        }
439
        if ($orderby === 'hits DESC') {
440
            $orderby = 'hitsD';
441
        }
442
        if ($orderby === 'price DESC') {
443
            $orderby = 'priceD';
444
        }
445
446
        return $orderby;
447
    }
448
449
    /**
450
     * @param string $caption
451
     * @param string $name
452
     * @param string $value
453
     * @param string $width
454
     * @param string $height
455
     * @param string $supplemental
456
     *
457
     * @return XoopsFormDhtmlTextArea|XoopsFormEditor
458
     */
459
    public static function getEditor($caption, $name, $value = '', $width = '100%', $height = '300px', $supplemental = '')
460
    {
461
462
        global $xoopsModule;
463
        $options = array();
464
        $isAdmin = $GLOBALS['xoopsUser']->isAdmin($xoopsModule->getVar('mid'));
465
466
        if (class_exists('XoopsFormEditor')) {
467
            $options['name']   = $name;
468
            $options['value']  = $value;
469
            $options['rows']   = 20;
470
            $options['cols']   = '100%';
471
            $options['width']  = $width;
472
            $options['height'] = $height;
473
            if ($isAdmin) {
474
                $myEditor = new XoopsFormEditor(ucfirst($name), $GLOBALS['xoopsModuleConfig']['adslightAdminUser'], $options, $nohtml = false, $onfailure = 'textarea');
475
            } else {
476
                $myEditor = new XoopsFormEditor(ucfirst($name), $GLOBALS['xoopsModuleConfig']['adslightEditorUser'], $options, $nohtml = false, $onfailure = 'textarea');
477
            }
478
        } else {
479
            $myEditor = new XoopsFormDhtmlTextArea(ucfirst($name), $name, $value, '100%', '100%');
480
        }
481
482
        //        $form->addElement($descEditor);
483
484
        return $myEditor;
485
    }
486
487
    /**
488
     * @param $tablename
489
     *
490
     * @return bool
491
     */
492
    public static function checkTableExists($tablename)
493
    {
494
        global $xoopsDB;
495
        $result = $xoopsDB->queryF("SHOW TABLES LIKE '$tablename'");
496
497
        return ($xoopsDB->getRowsNum($result) > 0);
498
    }
499
500
    /**
501
     * @param $fieldname
502
     * @param $table
503
     *
504
     * @return bool
505
     */
506
    public static function checkFieldExists($fieldname, $table)
507
    {
508
        global $xoopsDB;
509
        $result = $xoopsDB->queryF("SHOW COLUMNS FROM $table LIKE '$fieldname'");
510
511
        return ($xoopsDB->getRowsNum($result) > 0);
512
    }
513
514
    /**
515
     * @param $field
516
     * @param $table
517
     *
518
     * @return mixed
519
     */
520
    public static function addField($field, $table)
521
    {
522
        global $xoopsDB;
523
        $result = $xoopsDB->queryF('ALTER TABLE ' . $table . " ADD $field;");
524
525
        return $result;
526
    }
527
528
    /**
529
     * @param $cid
530
     *
531
     * @return bool
532
     */
533
    public static function getCatNameFromId($cid)
534
    {
535
        global $xoopsDB, $xoopsConfig, $myts, $moduleDirName;
536
537
        $sql = 'SELECT SQL_CACHE title FROM ' . $xoopsDB->prefix('adslight_categories') . " WHERE cid = '$cid'";
538
539
        if (!$result = $xoopsDB->query($sql)) {
540
            return false;
541
        }
542
543
        if (!$arr = $xoopsDB->fetchArray($result)) {
544
            return false;
545
        }
546
547
        $title = $arr['title'];
548
549
        return $title;
550
    }
551
552
    /**
553
     * @return mixed
554
     */
555
    public static function goCategory()
556
    {
557
        global $xoopsDB;
558
559
        $xt   = new XoopsTree($xoopsDB->prefix('adslight_categories'), 'cid', 'pid');
560
        $jump = XOOPS_URL . '/modules/adslight/viewcats.php?cid=';
561
        ob_start();
562
        $xt->makeMySelBox('title', 'title', 0, 1, 'pid', "location=\"" . $jump . "\"+this.options[this.selectedIndex].value");
563
        $block['selectbox'] = ob_get_contents();
564
        ob_end_clean();
565
566
        return $block;
567
    }
568
569
    // ADSLIGHT Version 2 //
570
    // Fonction rss.php RSS par categories
571
    /**
572
     * @return array
573
     */
574
    public static function returnAllAdsRss()
575
    {
576
        global $xoopsDB;
577
578
        $cid      = Request::getInt('cid', null, 'GET');
579
580
        $result = array();
581
582
        $sql = 'SELECT lid, title, price, date, town FROM ' . $xoopsDB->prefix('adslight_listing') . " WHERE valid='yes' AND cid=" . $xoopsDB->escape($cid) . ' ORDER BY date DESC';
583
584
        $resultValues = $xoopsDB->query($sql);
585
        while (($resultTemp = $xoopsDB->fetchBoth($resultValues)) !== false) {
586
            array_push($result, $resultTemp);
587
        }
588
589
        return $result;
590
    }
591
592
    // Fonction fluxrss.php RSS Global
593
    /**
594
     * @return array
595
     */
596
    public static function returnAllAdsFluxRss()
597
    {
598
        global $xoopsDB;
599
600
        $result = array();
601
602
        $sql = 'SELECT lid, title, price, desctext, date, town FROM ' . $xoopsDB->prefix('adslight_listing') . " WHERE valid='yes' ORDER BY date DESC LIMIT 0,15";
603
604
        $resultValues = $xoopsDB->query($sql);
605
        while (($resultTemp = $xoopsDB->fetchBoth($resultValues)) !== false) {
606
            array_push($result, $resultTemp);
607
        }
608
609
        return $result;
610
    }
611
612
    /**
613
     * @param $type
614
     *
615
     * @return mixed
616
     */
617
    public static function getNameType($type)
618
    {
619
        global $xoopsDB;
620
        $sql = $xoopsDB->query('SELECT nom_type FROM ' . $xoopsDB->prefix('adslight_type') . " WHERE id_type='" . $xoopsDB->escape($type) . "'");
621
        list($nom_type) = $xoopsDB->fetchRow($sql);
622
623
        return $nom_type;
624
    }
625
626
    /**
627
     * @param $format
628
     * @param $number
629
     *
630
     * @return mixed
631
     */
632
    public static function getMoneyFormat($format, $number)
633
    {
634
        $regex = '/%((?:[\^!\-]|\+|\(|\=.)*)([0-9]+)?' . '(?:#([0-9]+))?(?:\.([0-9]+))?([in%])/';
635
        if (setlocale(LC_MONETARY, 0) === 'C') {
636
            setlocale(LC_MONETARY, '');
637
        }
638
639
        setlocale(LC_ALL, 'en_US');
640
        $locale = localeconv();
641
        preg_match_all($regex, $format, $matches, PREG_SET_ORDER);
642
        foreach ($matches as $fmatch) {
643
            $value      = (float)$number;
644
            $flags      = array(
645
                'fillchar'  => preg_match('/\=(.)/', $fmatch[1], $match) ? $match[1] : ' ',
646
                'nogroup'   => preg_match('/\^/', $fmatch[1]) > 0,
647
                'usesignal' => preg_match('/\+|\(/', $fmatch[1], $match) ? $match[0] : '+',
648
                'nosimbol'  => preg_match('/\!/', $fmatch[1]) > 0,
649
                'isleft'    => preg_match('/\-/', $fmatch[1]) > 0
650
            );
651
            $width      = trim($fmatch[2]) ? (int)$fmatch[2] : 0;
652
            $left       = trim($fmatch[3]) ? (int)$fmatch[3] : 0;
653
            $right      = trim($fmatch[4]) ? (int)$fmatch[4] : $locale['int_frac_digits'];
654
            $conversion = $fmatch[5];
655
656
            $positive = true;
657
            if ($value < 0) {
658
                $positive = false;
659
                $value *= -1;
660
            }
661
            $letter = $positive ? 'p' : 'n';
662
663
            $prefix = $suffix = $cprefix = $csuffix = $signal = '';
664
665
            $signal = $positive ? $locale['positive_sign'] : $locale['negative_sign'];
666
            switch (true) {
667
                case $locale["{$letter}_sign_posn"] == 1 && $flags['usesignal'] == '+':
668
                    $prefix = $signal;
669
                    break;
670
                case $locale["{$letter}_sign_posn"] == 2 && $flags['usesignal'] == '+':
671
                    $suffix = $signal;
672
                    break;
673
                case $locale["{$letter}_sign_posn"] == 3 && $flags['usesignal'] == '+':
674
                    $cprefix = $signal;
675
                    break;
676
                case $locale["{$letter}_sign_posn"] == 4 && $flags['usesignal'] == '+':
677
                    $csuffix = $signal;
678
                    break;
679
                case $flags['usesignal'] === '(':
680
                case $locale["{$letter}_sign_posn"] == 0:
681
                    $prefix = '(';
682
                    $suffix = ')';
683
                    break;
684
            }
685
            if (!$flags['nosimbol']) {
686
                $currency = $cprefix . ($conversion === 'i' ? $locale['int_curr_symbol'] : $locale['currency_symbol']) . $csuffix;
687
            } else {
688
                $currency = '';
689
            }
690
            $space = $locale["{$letter}_sep_by_space"] ? ' ' : '';
691
692
            $value = number_format($value, $right, $locale['mon_decimal_point'], $flags['nogroup'] ? '' : $locale['mon_thousands_sep']);
693
            $value = @explode($locale['mon_decimal_point'], $value);
694
695
            $n = strlen($prefix) + strlen($currency) + strlen($value[0]);
696
            if ($left > 0 && $left > $n) {
697
                $value[0] = str_repeat($flags['fillchar'], $left - $n) . $value[0];
698
            }
699
            $value = implode($locale['mon_decimal_point'], $value);
700
            if ($locale["{$letter}_cs_precedes"]) {
701
                $value = $prefix . $currency . $space . $value . $suffix;
702
            } else {
703
                $value = $prefix . $value . $space . $currency . $suffix;
704
            }
705
            if ($width > 0) {
706
                $value = str_pad($value, $width, $flags['fillchar'], $flags['isleft'] ? STR_PAD_RIGHT : STR_PAD_LEFT);
707
            }
708
709
            $format = str_replace($fmatch[0], $value, $format);
710
        }
711
712
        return $format;
713
    }
714
715
    /**
716
     * Function responsible for checking if a directory exists, we can also write in and create an index.html file
717
     *
718
     * @param string $folder The full path of the directory to check
719
     *
720
     * @return void
721
     */
722
    public static function createFolder($folder)
723
    {
724
        try {
725
            if (!@mkdir($folder) && !is_dir($folder)) {
726
                throw new \RuntimeException(sprintf('Unable to create the %s directory', $folder));
727
            } else {
728
                file_put_contents($folder . '/index.html', '<script>history.go(-1);</script>');
729
            }
730
        }
731
        catch (Exception $e) {
732
            echo 'Caught exception: ', $e->getMessage(), "\n", '<br/>';
733
        }
734
    }
735
736
    /**
737
     * @param $file
738
     * @param $folder
739
     * @return bool
740
     */
741
    public static function copyFile($file, $folder)
742
    {
743
        return copy($file, $folder);
744
        //        try {
745
        //            if (!is_dir($folder)) {
746
        //                throw new \RuntimeException(sprintf('Unable to copy file as: %s ', $folder));
747
        //            } else {
748
        //                return copy($file, $folder);
749
        //            }
750
        //        } catch (Exception $e) {
751
        //            echo 'Caught exception: ', $e->getMessage(), "\n", "<br/>";
752
        //        }
753
        //        return false;
754
    }
755
756
    /**
757
     * @param $src
758
     * @param $dst
759
     */
760
    public static function recurseCopy($src, $dst)
761
    {
762
        $dir = opendir($src);
763
        //    @mkdir($dst);
764
        while (false !== ($file = readdir($dir))) {
765
            if (($file !== '.') && ($file !== '..')) {
766
                if (is_dir($src . '/' . $file)) {
767
                    self::recurseCopy($src . '/' . $file, $dst . '/' . $file);
768
                } else {
769
                    copy($src . '/' . $file, $dst . '/' . $file);
770
                }
771
            }
772
        }
773
        closedir($dir);
774
    }
775
776
    /**
777
     *
778
     * Verifies XOOPS version meets minimum requirements for this module
779
     * @static
780
     * @param XoopsModule $module
781
     *
782
     * @return bool true if meets requirements, false if not
783
     */
784
    public static function checkXoopsVer(XoopsModule $module)
785
    {
786
        xoops_loadLanguage('admin', $module->dirname());
787
        //check for minimum XOOPS version
788
        $currentVer  = substr(XOOPS_VERSION, 6); // get the numeric part of string
789
        $currArray   = explode('.', $currentVer);
790
        $requiredVer = '' . $module->getInfo('min_xoops'); //making sure it's a string
791
        $reqArray    = explode('.', $requiredVer);
792
        $success     = true;
793
        foreach ($reqArray as $k => $v) {
794
            if (isset($currArray[$k])) {
795
                if ($currArray[$k] > $v) {
796
                    break;
797
                } elseif ($currArray[$k] == $v) {
798
                    continue;
799
                } else {
800
                    $success = false;
801
                    break;
802
                }
803
            } else {
804
                if ((int)$v > 0) { // handles things like x.x.x.0_RC2
805
                    $success = false;
806
                    break;
807
                }
808
            }
809
        }
810
811
        if (!$success) {
812
            $module->setErrors(sprintf(_AM_ADSLIGHT_ERROR_BAD_XOOPS, $requiredVer, $currentVer));
813
        }
814
815
        return $success;
816
    }
817
818
    /**
819
     *
820
     * Verifies PHP version meets minimum requirements for this module
821
     * @static
822
     * @param XoopsModule $module
823
     *
824
     * @return bool true if meets requirements, false if not
825
     */
826
    public static function checkPhpVer(XoopsModule $module)
827
    {
828
        xoops_loadLanguage('admin', $module->dirname());
829
        // check for minimum PHP version
830
        $success = true;
831
        $verNum  = phpversion();
832
        $reqVer  =& $module->getInfo('min_php');
833
        if (false !== $reqVer && '' !== $reqVer) {
834
            if (version_compare($verNum, $reqVer, '<')) {
835
                $module->setErrors(sprintf(_AM_ADSLIGHT_ERROR_BAD_PHP, $reqVer, $verNum));
836
                $success = false;
837
            }
838
        }
839
840
        return $success;
841
    }
842
}
843