Completed
Push — master ( 5dd679...2a7c05 )
by Michael
02:39
created

AdslightUtil::getEditor()   B

Complexity

Conditions 3
Paths 3

Size

Total Lines 26
Code Lines 18

Duplication

Lines 26
Ratio 100 %

Importance

Changes 0
Metric Value
cc 3
eloc 18
nc 3
nop 6
dl 26
loc 26
rs 8.8571
c 0
b 0
f 0
1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 47 and the first side effect is on line 38.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
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
use Xmf\Request;
24
25
/**
26
 * AdslightUtil Class
27
 *
28
 * @copyright   XOOPS Project (http://xoops.org)
29
 * @license     http://www.fsf.org/copyleft/gpl.html GNU public license
30
 * @author      XOOPS Development Team
31
 * @package     AdsLight
32
 * @since       1.03
33
 *
34
 */
35
36
//namespace Xoopsmodules/Adslight;
37
38
$moduleDirName = basename(dirname(__DIR__));
39
$main_lang     = '_' . strtoupper($moduleDirName);
40
require_once XOOPS_ROOT_PATH . '/modules/adslight/include/gtickets.php';
41
include_once XOOPS_ROOT_PATH . '/class/xoopstree.php';
42
$myts = MyTextSanitizer::getInstance();
43
44
/**
45
 * Class AdslightUtil
46
 */
47 View Code Duplication
class AdslightUtil
0 ignored issues
show
Duplication introduced by
This class seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
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)
0 ignored issues
show
Unused Code introduced by
The assignment to $comments is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
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');
0 ignored issues
show
Unused Code introduced by
$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...
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();
0 ignored issues
show
Coding Style Compatibility introduced by
The method updateUserRating() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
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');
0 ignored issues
show
Unused Code introduced by
$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...
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();
0 ignored issues
show
Coding Style Compatibility introduced by
The method updateItemRating() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
228
    }
229
230
    /**
231
     * @param        $sel_id
232
     * @param string $status
233
     *
234
     * @return int
235
     */
236
    public static function getTotalItems($sel_id, $status = '')
0 ignored issues
show
Unused Code introduced by
The parameter $status is not used and could be removed.

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

Loading history...
237
    {
238
        global $xoopsDB, $mytree, $moduleDirName;
239
        $categories = AdslightUtil::getMyItemIds('adslight_view');
0 ignored issues
show
Coding Style introduced by
As per coding style, self should be used for accessing local static members.

This check looks for accesses to local static members using the fully qualified name instead of self::.

<?php

class Certificate {
    const TRIPLEDES_CBC = 'ASDFGHJKL';

    private $key;

    public function __construct()
    {
        $this->key = Certificate::TRIPLEDES_CBC;
    }
}

While this is perfectly valid, the fully qualified name of Certificate::TRIPLEDES_CBC could just as well be replaced by self::TRIPLEDES_CBC. Referencing local members with self:: assured the access will still work when the class is renamed, makes it perfectly clear that the member is in fact local and will usually be shorter.

Loading history...
240
        $count      = 0;
241
        $arr        = array();
0 ignored issues
show
Unused Code introduced by
$arr 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...
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
0 ignored issues
show
Documentation introduced by
The doc-type option's could not be parsed: Unknown type name "option's" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
298
     */
299
    public static function getModuleOption($option, $repmodule = 'adslight')
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
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':
0 ignored issues
show
Coding Style introduced by
As per coding-style, case should be followed by a single space.

As per the PSR-2 coding standard, there must be a space after the case keyword, instead of the test immediately following it.

switch (true) {
    case!isset($a):  //wrong
        doSomething();
        break;
    case !isset($b):  //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
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 = '')
0 ignored issues
show
Unused Code introduced by
The parameter $caption is not used and could be removed.

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

Loading history...
Unused Code introduced by
The parameter $supplemental is not used and could be removed.

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

Loading history...
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);
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
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();
0 ignored issues
show
Coding Style Comprehensibility introduced by
$block was never initialized. Although not strictly required by PHP, it is generally a good practice to add $block = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
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');
0 ignored issues
show
Unused Code Comprehensibility introduced by
56% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
654
655
        $locale = localeconv();
656
        preg_match_all($regex, $format, $matches, PREG_SET_ORDER);
657
        foreach ($matches as $fmatch) {
0 ignored issues
show
Bug introduced by
The expression $matches of type null|array<integer,array<integer,string>> is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
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 = '';
0 ignored issues
show
Unused Code introduced by
$signal 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...
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)) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
766
        //                throw new \RuntimeException(sprintf('Unable to copy file as: %s ', $folder));
0 ignored issues
show
Unused Code Comprehensibility introduced by
63% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
767
        //            } else {
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
768
        //                return copy($file, $folder);
0 ignored issues
show
Unused Code Comprehensibility introduced by
64% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
769
        //            }
770
        //        } catch (Exception $e) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
771
        //            echo 'Caught exception: ', $e->getMessage(), "\n", "<br/>";
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
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