Completed
Push — master ( a25b3b...67bb37 )
by Michael
02:44
created

class/utilities.php (2 issues)

Severity

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
/*
3
-------------------------------------------------------------------------
4
                     ADSLIGHT 2 : Module for Xoops
5
6
        Redesigned and ameliorate By Luc Bizet user at www.frxoops.org
7
        Started with the Classifieds module and made MANY changes
8
        Website : http://www.luc-bizet.fr
9
        Contact : [email protected]
10
-------------------------------------------------------------------------
11
             Original credits below Version History
12
##########################################################################
13
#                    Classified Module for Xoops                         #
14
#  By John Mordo user jlm69 at www.xoops.org and www.jlmzone.com         #
15
#      Started with the MyAds module and made MANY changes               #
16
##########################################################################
17
 Original Author: Pascal Le Boustouller
18
 Author Website : [email protected]
19
 Licence Type   : GPL
20
-------------------------------------------------------------------------
21
*/
22
23
/**
24
 * AdslightUtilities Class
25
 *
26
 * @copyright   XOOPS Project (http://xoops.org)
27
 * @license     http://www.fsf.org/copyleft/gpl.html GNU public license
28
 * @author      XOOPS Development Team
29
 * @package     AdsLight
30
 * @since       1.03
31
 *
32
 */
33
34
//namespace Xoopsmodules/Adslight;
35
36
$moduleDirName = basename(dirname(__DIR__));
37
$main_lang     = '_' . strtoupper($moduleDirName);
38
require_once XOOPS_ROOT_PATH . '/modules/adslight/include/gtickets.php';
39
include_once XOOPS_ROOT_PATH . '/class/xoopstree.php';
40
$myts = MyTextSanitizer::getInstance();
41
42
/**
43
 * Class AdslightUtilities
44
 */
45
class AdslightUtilities
46
{
47
    public static function expireAd()
48
    {
49
        global $xoopsDB, $xoopsConfig, $xoopsModule, $myts, $meta, $moduleDirName, $main_lang;
50
51
        $datenow = time();
52
53
        $result5 = $xoopsDB->query('SELECT lid, title, expire, type, desctext, date, email, submitter, photo, valid, hits, comments, remind FROM '
54
                                   . $xoopsDB->prefix('adslight_listing')
55
                                   . " WHERE valid='Yes'");
56
57
        while (list($lids, $title, $expire, $type, $desctext, $dateann, $email, $submitter, $photo, $valid, $hits, $comments, $remind) = $xoopsDB->fetchRow($result5)) {
58
            $title     = $myts->htmlSpecialChars($title);
59
            $expire    = $myts->htmlSpecialChars($expire);
60
            $type      = $myts->htmlSpecialChars($type);
61
            $desctext  =& $myts->displayTarea($desctext, 1, 1, 1, 1, 1);
62
            $submitter = $myts->htmlSpecialChars($submitter);
63
            $remind    = $myts->htmlSpecialChars($remind);
64
            $supprdate = $dateann + ($expire * 86400);
65
            $almost    = $GLOBALS['xoopsModuleConfig']['adslight_almost'];
66
67
            // give warning that add is about to expire
68
69
            if ($almost > 0 && ($supprdate - $almost * 86400) < $datenow && $valid === 'Yes' && $remind == 0) {
70
                $xoopsDB->queryF('UPDATE ' . $xoopsDB->prefix('adslight_listing') . " SET remind='1' WHERE lid=$lids");
71
72 View Code Duplication
                if ($email) {
73
                    $tags               = array();
74
                    $subject            = '' . _ADSLIGHT_ALMOST . '';
75
                    $tags['TITLE']      = $title;
76
                    $tags['HELLO']      = '' . _ADSLIGHT_HELLO . '';
77
                    $tags['YOUR_AD_ON'] = '' . _ADSLIGHT_YOUR_AD_ON . '';
78
                    $tags['VEDIT_AD']   = '' . _ADSLIGHT_VEDIT_AD . '';
79
                    $tags['YOUR_AD']    = '' . _ADSLIGHT_YOUR_AD . '';
80
                    $tags['SOON']       = '' . _ADSLIGHT_SOON . '';
81
                    $tags['VIEWED']     = '' . _ADSLIGHT_VU . '';
82
                    $tags['TIMES']      = '' . _ADSLIGHT_TIMES . '';
83
                    $tags['WEBMASTER']  = '' . _ADSLIGHT_WEBMASTER . '';
84
                    $tags['THANKS']     = '' . _ADSLIGHT_THANKS . '';
85
                    $tags['TYPE']       = static::getNameType($type);
86
                    $tags['DESCTEXT']   = $desctext;
87
                    $tags['HITS']       = $hits;
88
                    $tags['META_TITLE'] = $meta['title'];
89
                    $tags['SUBMITTER']  = $submitter;
90
                    $tags['DURATION']   = $expire;
91
                    $tags['LINK_URL']   = XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname') . '/viewads.php?' . '&lid=' . $lids;
92
                    $mail               =& getMailer();
93
                    $mail->setTemplateDir(XOOPS_ROOT_PATH . '/modules/' . $xoopsModule->getVar('dirname') . '/language/' . $xoopsConfig['language'] . '/mail_template/');
94
                    $mail->setTemplate('listing_expires.tpl');
95
                    $mail->useMail();
96
                    $mail->multimailer->isHTML(true);
97
                    $mail->setFromName($meta['title']);
98
                    $mail->setFromEmail($xoopsConfig['adminmail']);
99
                    $mail->setToEmails($email);
100
                    $mail->setSubject($subject);
101
                    $mail->assign($tags);
102
                    $mail->send();
103
                    echo $mail->getErrors();
104
                }
105
            }
106
107
            // expire ad
108
109
            if ($supprdate < $datenow) {
110
                if ($photo != 0) {
111
                    $result2 = $xoopsDB->query('SELECT url FROM ' . $xoopsDB->prefix('adslight_pictures') . ' WHERE lid=' . $xoopsDB->escape($lids));
112
113
                    while (list($url) = $xoopsDB->fetchRow($result2)) {
114
                        $destination  = XOOPS_ROOT_PATH . '/uploads/AdsLight';
115
                        $destination2 = XOOPS_ROOT_PATH . '/uploads/AdsLight/thumbs';
116
                        $destination3 = XOOPS_ROOT_PATH . '/uploads/AdsLight/midsize';
117
                        if (file_exists("$destination/$url")) {
118
                            unlink("$destination/$url");
119
                        }
120
                        if (file_exists("$destination2/thumb_$url")) {
121
                            unlink("$destination2/thumb_$url");
122
                        }
123
                        if (file_exists("$destination3/resized_$url")) {
124
                            unlink("$destination3/resized_$url");
125
                        }
126
                    }
127
                }
128
129
                $xoopsDB->queryF('DELETE FROM ' . $xoopsDB->prefix('adslight_listing') . ' WHERE lid=' . $xoopsDB->escape($lids));
130
131
                //  Specification for Japan:
132
                //  $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."";
133 View Code Duplication
                if ($email) {
134
                    $tags               = array();
135
                    $subject            = '' . _ADSLIGHT_STOP . '';
136
                    $tags['TITLE']      = $title;
137
                    $tags['HELLO']      = '' . _ADSLIGHT_HELLO . '';
138
                    $tags['TYPE']       = static::getNameType($type);
139
                    $tags['DESCTEXT']   = $desctext;
140
                    $tags['HITS']       = $hits;
141
                    $tags['META_TITLE'] = $meta['title'];
142
                    $tags['SUBMITTER']  = $submitter;
143
                    $tags['YOUR_AD_ON'] = '' . _ADSLIGHT_YOUR_AD_ON . '';
144
                    $tags['EXPIRED']    = '' . _ADSLIGHT_EXPIRED . '';
145
                    $tags['MESSTEXT']   = stripslashes($message);
146
                    $tags['OTHER']      = '' . _ADSLIGHT_OTHER . '';
147
                    $tags['WEBMASTER']  = '' . _ADSLIGHT_WEBMASTER . '';
148
                    $tags['THANKS']     = '' . _ADSLIGHT_THANKS . '';
149
                    $tags['VIEWED']     = '' . _ADSLIGHT_VU . '';
150
                    $tags['TIMES']      = '' . _ADSLIGHT_TIMES . '';
151
                    $tags['TEAM']       = '' . _ADSLIGHT_TEAM . '';
152
                    $tags['DURATION']   = $expire;
153
                    $tags['LINK_URL']   = XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname') . '/viewads.php?' . '&lid=' . $lids;
154
                    $mail               =& getMailer();
155
                    $mail->setTemplateDir(XOOPS_ROOT_PATH . '/modules/' . $xoopsModule->getVar('dirname') . '/language/' . $xoopsConfig['language'] . '/mail_template/');
156
                    $mail->setTemplate('listing_expired.tpl');
157
                    $mail->useMail();
158
                    $mail->multimailer->isHTML(true);
159
                    $mail->setFromName($meta['title']);
160
                    $mail->setFromEmail($xoopsConfig['adminmail']);
161
                    $mail->setToEmails($email);
162
                    $mail->setSubject($subject);
163
                    $mail->assign($tags);
164
                    $mail->send();
165
                    echo $mail->getErrors();
166
                }
167
            }
168
        }
169
    }
170
171
    //updates rating data in itemtable for a given user
172
    /**
173
     * @param $sel_id
174
     */
175 View Code Duplication
    public static function updateUserRating($sel_id)
176
    {
177
        global $xoopsDB, $moduleDirName, $main_lang;
178
179
        $usid      = XoopsRequest::getInt('usid', 0, 'GET');
0 ignored issues
show
$usid is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
180
181
        $query = 'SELECT rating FROM ' . $xoopsDB->prefix('adslight_user_votedata') . ' WHERE usid=' . $xoopsDB->escape($sel_id) . '';
182
        //echo $query;
183
        $voteresult  = $xoopsDB->query($query);
184
        $votesDB     = $xoopsDB->getRowsNum($voteresult);
185
        $totalrating = 0;
186
        while (list($rating) = $xoopsDB->fetchRow($voteresult)) {
187
            $totalrating += $rating;
188
        }
189
        $finalrating = $totalrating / $votesDB;
190
        $finalrating = number_format($finalrating, 4);
191
        $query       = 'UPDATE ' . $xoopsDB->prefix('adslight_listing') . " SET user_rating=$finalrating, user_votes=$votesDB WHERE usid=" . $xoopsDB->escape($sel_id) . '';
192
        //echo $query;
193
        $xoopsDB->query($query) || exit();
194
    }
195
196
    //updates rating data in itemtable for a given item
197
    /**
198
     * @param $sel_id
199
     */
200 View Code Duplication
    public static function updateItemRating($sel_id)
201
    {
202
        global $xoopsDB, $moduleDirName, $main_lang;
203
204
        $lid      = XoopsRequest::getInt('lid', 0, 'GET');
0 ignored issues
show
$lid is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
205
206
        $query = 'SELECT rating FROM ' . $xoopsDB->prefix('adslight_item_votedata') . ' WHERE lid=' . $xoopsDB->escape($sel_id) . '';
207
        //echo $query;
208
        $voteresult  = $xoopsDB->query($query);
209
        $votesDB     = $xoopsDB->getRowsNum($voteresult);
210
        $totalrating = 0;
211
        while (list($rating) = $xoopsDB->fetchRow($voteresult)) {
212
            $totalrating += $rating;
213
        }
214
        $finalrating = $totalrating / $votesDB;
215
        $finalrating = number_format($finalrating, 4);
216
        $query       = 'UPDATE ' . $xoopsDB->prefix('adslight_listing') . " SET item_rating=$finalrating, item_votes=$votesDB WHERE lid=" . $xoopsDB->escape($sel_id) . '';
217
        //echo $query;
218
        $xoopsDB->query($query) || exit();
219
    }
220
221
    /**
222
     * @param        $sel_id
223
     * @param string $status
224
     *
225
     * @return int
226
     */
227
    public static function getTotalItems($sel_id, $status = '')
228
    {
229
        global $xoopsDB, $mytree, $moduleDirName;
230
        $categories = AdslightUtilities::getMyItemIds('adslight_view');
231
        $count      = 0;
232
        $arr        = array();
233
        if (in_array($sel_id, $categories)) {
234
            $query = 'SELECT SQL_CACHE count(*) FROM ' . $xoopsDB->prefix('adslight_listing') . ' WHERE cid=' . (int)$sel_id . " and valid='Yes' AND status!='1'";
235
236
            $result = $xoopsDB->query($query);
237
            list($thing) = $xoopsDB->fetchRow($result);
238
            $count = $thing;
239
            $arr   = $mytree->getAllChildId($sel_id);
240
            $size  = count($arr);
241
            for ($i = 0; $i < $size; ++$i) {
242
                if (in_array($arr[$i], $categories)) {
243
                    $query2 = 'SELECT SQL_CACHE count(*) FROM ' . $xoopsDB->prefix('adslight_listing') . ' WHERE cid=' . (int)$arr[$i] . " and valid='Yes' AND status!='1'";
244
245
                    $result2 = $xoopsDB->query($query2);
246
                    list($thing) = $xoopsDB->fetchRow($result2);
247
                    $count += $thing;
248
                }
249
            }
250
        }
251
252
        return $count;
253
    }
254
255
    /**
256
     * @param $permtype
257
     *
258
     * @return mixed
259
     */
260
    public static function getMyItemIds($permtype)
261
    {
262
        global $moduleDirName;
263
        static $permissions = array();
264
        if (is_array($permissions) && array_key_exists($permtype, $permissions)) {
265
            return $permissions[$permtype];
266
        }
267
268
        /** @var XoopsModuleHandler $moduleHandler */
269
        $moduleHandler          = xoops_getHandler('module');
270
        $myModule               = $moduleHandler->getByDirname('adslight');
271
        $groups                 = is_object($GLOBALS['xoopsUser']) ? $GLOBALS['xoopsUser']->getGroups() : XOOPS_GROUP_ANONYMOUS;
272
        $gpermHandler           = xoops_getHandler('groupperm');
273
        $categories             = $gpermHandler->getItemIds($permtype, $groups, $myModule->getVar('mid'));
274
        $permissions[$permtype] = $categories;
275
276
        return $categories;
277
    }
278
279
    /**
280
     * @param        $option
281
     * @param string $repmodule
282
     *
283
     * @return bool
284
     */
285
    public static function getModuleOption($option, $repmodule = 'adslight')
286
    {
287
        global $xoopsModule;
288
        static $tbloptions = array();
289
        if (is_array($tbloptions) && array_key_exists($option, $tbloptions)) {
290
            return $tbloptions[$option];
291
        }
292
293
        $retval = false;
294
        if (isset($GLOBALS['xoopsModuleConfig'])
295
            && (is_object($xoopsModule) && $xoopsModule->getVar('dirname') == $repmodule
296
                && $xoopsModule->getVar('isactive'))
297
        ) {
298
            if (isset($GLOBALS['xoopsModuleConfig'][$option])) {
299
                $retval = $GLOBALS['xoopsModuleConfig'][$option];
300
            }
301
        } else {
302
            /** @var XoopsModuleHandler $moduleHandler */
303
            $moduleHandler  = xoops_getHandler('module');
304
            $module         = $moduleHandler->getByDirname($repmodule);
305
            $config_handler = xoops_getHandler('config');
306
            if ($module) {
307
                $moduleConfig =& $config_handler->getConfigsByCat(0, $GLOBALS['xoopsModule']->getVar('mid'));
308
                if (isset($moduleConfig[$option])) {
309
                    $retval = $moduleConfig[$option];
310
                }
311
            }
312
        }
313
        $tbloptions[$option] = $retval;
314
315
        return $retval;
316
    }
317
318
    public static function showImage()
319
    {
320
        global $moduleDirName;
321
        echo "<script type=\"text/javascript\">\n";
322
        echo "<!--\n\n";
323
        echo "function showimage() {\n";
324
        echo "if (!document.images)\n";
325
        echo "return\n";
326
        echo "document.images.avatar.src=\n";
327
        echo "'" . XOOPS_URL . "/modules/adslight/assets/images/img_cat/' + document.imcat.img.options[document.imcat.img.selectedIndex].value\n";
328
        echo "}\n\n";
329
        echo "//-->\n";
330
        echo "</script>\n";
331
    }
332
333
    //Reusable Link Sorting Functions
334
    /**
335
     * @param $orderby
336
     *
337
     * @return string
338
     */
339
    public static function convertOrderByIn($orderby)
340
    {
341
        switch (trim($orderby)) {
342
            case 'titleA':
343
                $orderby = 'title ASC';
344
                break;
345
            case 'dateA':
346
                $orderby = 'date ASC';
347
                break;
348
            case 'hitsA':
349
                $orderby = 'hits ASC';
350
                break;
351
            case 'priceA':
352
                $orderby = 'price ASC';
353
                break;
354
            case 'titleD':
355
                $orderby = 'title DESC';
356
                break;
357
            case 'hitsD':
358
                $orderby = 'hits DESC';
359
                break;
360
            case 'priceD':
361
                $orderby = 'price DESC';
362
                break;
363
            case'dateD':
364
            default:
365
                $orderby = 'date DESC';
366
                break;
367
        }
368
369
        return $orderby;
370
    }
371
372
    /**
373
     * @param $orderby
374
     *
375
     * @return string
376
     */
377
    public static function convertOrderByTrans($orderby)
378
    {
379
        global $main_lang;
380
381
        if ($orderby === 'hits ASC') {
382
            $orderbyTrans = '' . _ADSLIGHT_POPULARITYLTOM . '';
383
        }
384
        if ($orderby === 'hits DESC') {
385
            $orderbyTrans = '' . _ADSLIGHT_POPULARITYMTOL . '';
386
        }
387
        if ($orderby === 'title ASC') {
388
            $orderbyTrans = '' . _ADSLIGHT_TITLEATOZ . '';
389
        }
390
        if ($orderby === 'title DESC') {
391
            $orderbyTrans = '' . _ADSLIGHT_TITLEZTOA . '';
392
        }
393
        if ($orderby === 'date ASC') {
394
            $orderbyTrans = '' . _ADSLIGHT_DATEOLD . '';
395
        }
396
        if ($orderby === 'date DESC') {
397
            $orderbyTrans = '' . _ADSLIGHT_DATENEW . '';
398
        }
399
        if ($orderby === 'price ASC') {
400
            $orderbyTrans = _ADSLIGHT_PRICELTOH;
401
        }
402
        if ($orderby === 'price DESC') {
403
            $orderbyTrans = '' . _ADSLIGHT_PRICEHTOL . '';
404
        }
405
406
        return $orderbyTrans;
407
    }
408
409
    /**
410
     * @param $orderby
411
     *
412
     * @return string
413
     */
414
    public static function convertOrderByOut($orderby)
415
    {
416
        if ($orderby === 'title ASC') {
417
            $orderby = 'titleA';
418
        }
419
        if ($orderby === 'date ASC') {
420
            $orderby = 'dateA';
421
        }
422
        if ($orderby === 'hits ASC') {
423
            $orderby = 'hitsA';
424
        }
425
        if ($orderby === 'price ASC') {
426
            $orderby = 'priceA';
427
        }
428
        if ($orderby === 'title DESC') {
429
            $orderby = 'titleD';
430
        }
431
        if ($orderby === 'date DESC') {
432
            $orderby = 'dateD';
433
        }
434
        if ($orderby === 'hits DESC') {
435
            $orderby = 'hitsD';
436
        }
437
        if ($orderby === 'price DESC') {
438
            $orderby = 'priceD';
439
        }
440
441
        return $orderby;
442
    }
443
444
    /**
445
     * @param string $caption
446
     * @param string $name
447
     * @param string $value
448
     * @param string $width
449
     * @param string $height
450
     * @param string $supplemental
451
     *
452
     * @return XoopsFormDhtmlTextArea|XoopsFormEditor
453
     */
454
    public static function getEditor($caption, $name, $value = '', $width = '100%', $height = '300px', $supplemental = '')
455
    {
456
457
        global $xoopsModule;
458
        $options = array();
459
        $isAdmin = $GLOBALS['xoopsUser']->isAdmin($xoopsModule->getVar('mid'));
460
461
        if (class_exists('XoopsFormEditor')) {
462
            $options['name']   = $name;
463
            $options['value']  = $value;
464
            $options['rows']   = 20;
465
            $options['cols']   = '100%';
466
            $options['width']  = $width;
467
            $options['height'] = $height;
468
            if ($isAdmin) {
469
                $myEditor = new XoopsFormEditor(ucfirst($name), $GLOBALS['xoopsModuleConfig']['adslightAdminUser'], $options, $nohtml = false, $onfailure = 'textarea');
470
            } else {
471
                $myEditor = new XoopsFormEditor(ucfirst($name), $GLOBALS['xoopsModuleConfig']['adslightEditorUser'], $options, $nohtml = false, $onfailure = 'textarea');
472
            }
473
        } else {
474
            $myEditor = new XoopsFormDhtmlTextArea(ucfirst($name), $name, $value, '100%', '100%');
475
        }
476
477
        //        $form->addElement($descEditor);
478
479
        return $myEditor;
480
    }
481
482
    /**
483
     * @param $tablename
484
     *
485
     * @return bool
486
     */
487
    public static function checkTableExists($tablename)
488
    {
489
        global $xoopsDB;
490
        $result = $xoopsDB->queryF("SHOW TABLES LIKE '$tablename'");
491
492
        return ($xoopsDB->getRowsNum($result) > 0);
493
    }
494
495
    /**
496
     * @param $fieldname
497
     * @param $table
498
     *
499
     * @return bool
500
     */
501
    public static function checkFieldExists($fieldname, $table)
502
    {
503
        global $xoopsDB;
504
        $result = $xoopsDB->queryF("SHOW COLUMNS FROM $table LIKE '$fieldname'");
505
506
        return ($xoopsDB->getRowsNum($result) > 0);
507
    }
508
509
    /**
510
     * @param $field
511
     * @param $table
512
     *
513
     * @return mixed
514
     */
515
    public static function addField($field, $table)
516
    {
517
        global $xoopsDB;
518
        $result = $xoopsDB->queryF('ALTER TABLE ' . $table . " ADD $field;");
519
520
        return $result;
521
    }
522
523
    /**
524
     * @param $cid
525
     *
526
     * @return bool
527
     */
528
    public static function getCatNameFromId($cid)
529
    {
530
        global $xoopsDB, $xoopsConfig, $myts, $moduleDirName;
531
532
        $sql = 'SELECT SQL_CACHE title FROM ' . $xoopsDB->prefix('adslight_categories') . " WHERE cid = '$cid'";
533
534
        if (!$result = $xoopsDB->query($sql)) {
535
            return false;
536
        }
537
538
        if (!$arr = $xoopsDB->fetchArray($result)) {
539
            return false;
540
        }
541
542
        $title = $arr['title'];
543
544
        return $title;
545
    }
546
547
    /**
548
     * @return mixed
549
     */
550
    public static function goCategory()
551
    {
552
        global $xoopsDB;
553
554
        $xt   = new XoopsTree($xoopsDB->prefix('adslight_categories'), 'cid', 'pid');
555
        $jump = XOOPS_URL . '/modules/adslight/viewcats.php?cid=';
556
        ob_start();
557
        $xt->makeMySelBox('title', 'title', 0, 1, 'pid', "location=\"" . $jump . "\"+this.options[this.selectedIndex].value");
558
        $block['selectbox'] = ob_get_contents();
559
        ob_end_clean();
560
561
        return $block;
562
    }
563
564
    // ADSLIGHT Version 2 //
565
    // Fonction rss.php RSS par categories
566
    /**
567
     * @return array
568
     */
569
    public static function returnAllAdsRss()
570
    {
571
        global $xoopsDB;
572
573
        $cid      = XoopsRequest::getInt('cid', null, 'GET');
574
575
        $result = array();
576
577
        $sql = 'SELECT lid, title, price, date, town FROM ' . $xoopsDB->prefix('adslight_listing') . " WHERE valid='yes' AND cid=" . $xoopsDB->escape($cid) . ' ORDER BY date DESC';
578
579
        $resultValues = $xoopsDB->query($sql);
580
        while (($resultTemp = $xoopsDB->fetchBoth($resultValues)) !== false) {
581
            array_push($result, $resultTemp);
582
        }
583
584
        return $result;
585
    }
586
587
    // Fonction fluxrss.php RSS Global
588
    /**
589
     * @return array
590
     */
591
    public static function returnAllAdsFluxRss()
592
    {
593
        global $xoopsDB;
594
595
        $result = array();
596
597
        $sql = 'SELECT lid, title, price, desctext, date, town FROM ' . $xoopsDB->prefix('adslight_listing') . " WHERE valid='yes' ORDER BY date DESC LIMIT 0,15";
598
599
        $resultValues = $xoopsDB->query($sql);
600
        while (($resultTemp = $xoopsDB->fetchBoth($resultValues)) !== false) {
601
            array_push($result, $resultTemp);
602
        }
603
604
        return $result;
605
    }
606
607
    /**
608
     * @param $type
609
     *
610
     * @return mixed
611
     */
612
    public static function getNameType($type)
613
    {
614
        global $xoopsDB;
615
        $sql = $xoopsDB->query('SELECT nom_type FROM ' . $xoopsDB->prefix('adslight_type') . " WHERE id_type='" . $xoopsDB->escape($type) . "'");
616
        list($nom_type) = $xoopsDB->fetchRow($sql);
617
618
        return $nom_type;
619
    }
620
621
    /**
622
     * @param $format
623
     * @param $number
624
     *
625
     * @return mixed
626
     */
627
    public static function getMoneyFormat($format, $number)
628
    {
629
        $regex = '/%((?:[\^!\-]|\+|\(|\=.)*)([0-9]+)?' . '(?:#([0-9]+))?(?:\.([0-9]+))?([in%])/';
630
        if (setlocale(LC_MONETARY, 0) === 'C') {
631
            setlocale(LC_MONETARY, '');
632
        }
633
634
        setlocale(LC_ALL, 'en_US');
635
        $locale = localeconv();
636
        preg_match_all($regex, $format, $matches, PREG_SET_ORDER);
637
        foreach ($matches as $fmatch) {
638
            $value      = (float)$number;
639
            $flags      = array(
640
                'fillchar'  => preg_match('/\=(.)/', $fmatch[1], $match) ? $match[1] : ' ',
641
                'nogroup'   => preg_match('/\^/', $fmatch[1]) > 0,
642
                'usesignal' => preg_match('/\+|\(/', $fmatch[1], $match) ? $match[0] : '+',
643
                'nosimbol'  => preg_match('/\!/', $fmatch[1]) > 0,
644
                'isleft'    => preg_match('/\-/', $fmatch[1]) > 0
645
            );
646
            $width      = trim($fmatch[2]) ? (int)$fmatch[2] : 0;
647
            $left       = trim($fmatch[3]) ? (int)$fmatch[3] : 0;
648
            $right      = trim($fmatch[4]) ? (int)$fmatch[4] : $locale['int_frac_digits'];
649
            $conversion = $fmatch[5];
650
651
            $positive = true;
652
            if ($value < 0) {
653
                $positive = false;
654
                $value *= -1;
655
            }
656
            $letter = $positive ? 'p' : 'n';
657
658
            $prefix = $suffix = $cprefix = $csuffix = $signal = '';
659
660
            $signal = $positive ? $locale['positive_sign'] : $locale['negative_sign'];
661
            switch (true) {
662 View Code Duplication
                case $locale["{$letter}_sign_posn"] == 1 && $flags['usesignal'] == '+':
663
                    $prefix = $signal;
664
                    break;
665 View Code Duplication
                case $locale["{$letter}_sign_posn"] == 2 && $flags['usesignal'] == '+':
666
                    $suffix = $signal;
667
                    break;
668 View Code Duplication
                case $locale["{$letter}_sign_posn"] == 3 && $flags['usesignal'] == '+':
669
                    $cprefix = $signal;
670
                    break;
671 View Code Duplication
                case $locale["{$letter}_sign_posn"] == 4 && $flags['usesignal'] == '+':
672
                    $csuffix = $signal;
673
                    break;
674
                case $flags['usesignal'] === '(':
675
                case $locale["{$letter}_sign_posn"] == 0:
676
                    $prefix = '(';
677
                    $suffix = ')';
678
                    break;
679
            }
680
            if (!$flags['nosimbol']) {
681
                $currency = $cprefix . ($conversion === 'i' ? $locale['int_curr_symbol'] : $locale['currency_symbol']) . $csuffix;
682
            } else {
683
                $currency = '';
684
            }
685
            $space = $locale["{$letter}_sep_by_space"] ? ' ' : '';
686
687
            $value = number_format($value, $right, $locale['mon_decimal_point'], $flags['nogroup'] ? '' : $locale['mon_thousands_sep']);
688
            $value = @explode($locale['mon_decimal_point'], $value);
689
690
            $n = strlen($prefix) + strlen($currency) + strlen($value[0]);
691
            if ($left > 0 && $left > $n) {
692
                $value[0] = str_repeat($flags['fillchar'], $left - $n) . $value[0];
693
            }
694
            $value = implode($locale['mon_decimal_point'], $value);
695
            if ($locale["{$letter}_cs_precedes"]) {
696
                $value = $prefix . $currency . $space . $value . $suffix;
697
            } else {
698
                $value = $prefix . $value . $space . $currency . $suffix;
699
            }
700
            if ($width > 0) {
701
                $value = str_pad($value, $width, $flags['fillchar'], $flags['isleft'] ? STR_PAD_RIGHT : STR_PAD_LEFT);
702
            }
703
704
            $format = str_replace($fmatch[0], $value, $format);
705
        }
706
707
        return $format;
708
    }
709
710
    /**
711
     * Function responsible for checking if a directory exists, we can also write in and create an index.html file
712
     *
713
     * @param string $folder The full path of the directory to check
714
     *
715
     * @return void
716
     */
717
    public static function createFolder($folder)
718
    {
719
        try {
720
            if (!@mkdir($folder) && !is_dir($folder)) {
721
                throw new \RuntimeException(sprintf('Unable to create the %s directory', $folder));
722
            } else {
723
                file_put_contents($folder . '/index.html', '<script>history.go(-1);</script>');
724
            }
725
        }
726
        catch (Exception $e) {
727
            echo 'Caught exception: ', $e->getMessage(), "\n", '<br/>';
728
        }
729
    }
730
731
    /**
732
     * @param $file
733
     * @param $folder
734
     * @return bool
735
     */
736
    public static function copyFile($file, $folder)
737
    {
738
        return copy($file, $folder);
739
        //        try {
740
        //            if (!is_dir($folder)) {
741
        //                throw new \RuntimeException(sprintf('Unable to copy file as: %s ', $folder));
742
        //            } else {
743
        //                return copy($file, $folder);
744
        //            }
745
        //        } catch (Exception $e) {
746
        //            echo 'Caught exception: ', $e->getMessage(), "\n", "<br/>";
747
        //        }
748
        //        return false;
749
    }
750
751
    /**
752
     * @param $src
753
     * @param $dst
754
     */
755
    public static function recurseCopy($src, $dst)
756
    {
757
        $dir = opendir($src);
758
        //    @mkdir($dst);
759
        while (false !== ($file = readdir($dir))) {
760
            if (($file !== '.') && ($file !== '..')) {
761
                if (is_dir($src . '/' . $file)) {
762
                    self::recurseCopy($src . '/' . $file, $dst . '/' . $file);
763
                } else {
764
                    copy($src . '/' . $file, $dst . '/' . $file);
765
                }
766
            }
767
        }
768
        closedir($dir);
769
    }
770
771
    /**
772
     *
773
     * Verifies XOOPS version meets minimum requirements for this module
774
     * @static
775
     * @param XoopsModule $module
776
     *
777
     * @return bool true if meets requirements, false if not
778
     */
779
    public static function checkXoopsVer(XoopsModule $module)
780
    {
781
        xoops_loadLanguage('admin', $module->dirname());
782
        //check for minimum XOOPS version
783
        $currentVer  = substr(XOOPS_VERSION, 6); // get the numeric part of string
784
        $currArray   = explode('.', $currentVer);
785
        $requiredVer = '' . $module->getInfo('min_xoops'); //making sure it's a string
786
        $reqArray    = explode('.', $requiredVer);
787
        $success     = true;
788
        foreach ($reqArray as $k => $v) {
789
            if (isset($currArray[$k])) {
790
                if ($currArray[$k] > $v) {
791
                    break;
792
                } elseif ($currArray[$k] == $v) {
793
                    continue;
794
                } else {
795
                    $success = false;
796
                    break;
797
                }
798
            } else {
799
                if ((int)$v > 0) { // handles things like x.x.x.0_RC2
800
                    $success = false;
801
                    break;
802
                }
803
            }
804
        }
805
806
        if (!$success) {
807
            $module->setErrors(sprintf(_AM_ADSLIGHT_ERROR_BAD_XOOPS, $requiredVer, $currentVer));
808
        }
809
810
        return $success;
811
    }
812
813
    /**
814
     *
815
     * Verifies PHP version meets minimum requirements for this module
816
     * @static
817
     * @param XoopsModule $module
818
     *
819
     * @return bool true if meets requirements, false if not
820
     */
821
    public static function checkPhpVer(XoopsModule $module)
822
    {
823
        xoops_loadLanguage('admin', $module->dirname());
824
        // check for minimum PHP version
825
        $success = true;
826
        $verNum  = phpversion();
827
        $reqVer  =& $module->getInfo('min_php');
828
        if (false !== $reqVer && '' !== $reqVer) {
829
            if (version_compare($verNum, $reqVer, '<')) {
830
                $module->setErrors(sprintf(_AM_ADSLIGHT_ERROR_BAD_PHP, $reqVer, $verNum));
831
                $success = false;
832
            }
833
        }
834
835
        return $success;
836
    }
837
}
838