Passed
Push — master ( df5caf...cd5737 )
by Michael
02:02
created

Utility::convertOrderByTrans()   F

Complexity

Conditions 9
Paths 256

Size

Total Lines 30
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 30
rs 3
cc 9
eloc 19
nc 256
nop 1
1
<?php namespace XoopsModules\Adslight;
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 49 and the first side effect is on line 39.

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
-------------------------------------------------------------------------
5
                     ADSLIGHT 2 : Module for Xoops
6
7
        Redesigned and ameliorate By Luc Bizet user at www.frxoops.org
8
        Started with the Classifieds module and made MANY changes
9
        Website : http://www.luc-bizet.fr
10
        Contact : [email protected]
11
-------------------------------------------------------------------------
12
             Original credits below Version History
13
##########################################################################
14
#                    Classified Module for Xoops                         #
15
#  By John Mordo user jlm69 at www.xoops.org and www.jlmzone.com         #
16
#      Started with the MyAds module and made MANY changes               #
17
##########################################################################
18
 Original Author: Pascal Le Boustouller
19
 Author Website : [email protected]
20
 Licence Type   : GPL
21
-------------------------------------------------------------------------
22
*/
23
24
/**
25
 * AdslightUtil Class
26
 *
27
 * @copyright   XOOPS Project (https://xoops.org)
28
 * @license     http://www.fsf.org/copyleft/gpl.html GNU public license
29
 * @author      XOOPS Development Team
30
 * @package     AdsLight
31
 * @since       1.03
32
 *
33
 */
34
35
use Xmf\Request;
0 ignored issues
show
Bug introduced by
The type Xmf\Request was not found. Maybe you did not declare it correctly or list all dependencies?

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

filter:
    dependency_paths: ["lib/*"]

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

Loading history...
36
use XoopsModules\Adslight;
37
use XoopsModules\Adslight\Common;
38
39
$moduleDirName = basename(dirname(__DIR__));
40
$main_lang     = '_' . strtoupper($moduleDirName);
41
//require_once XOOPS_ROOT_PATH . '/modules/adslight/include/gtickets.php';
0 ignored issues
show
Unused Code Comprehensibility introduced by
38% 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...
42
require_once XOOPS_ROOT_PATH . '/class/xoopstree.php';
0 ignored issues
show
Bug introduced by
The constant XoopsModules\Adslight\XOOPS_ROOT_PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
43
$myts = \MyTextSanitizer::getInstance();
0 ignored issues
show
Bug introduced by
The type MyTextSanitizer was not found. Maybe you did not declare it correctly or list all dependencies?

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

filter:
    dependency_paths: ["lib/*"]

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

Loading history...
44
45
46
/**
47
 * Class Utility
48
 */
49
class Utility
50
{
51
    use Common\VersionChecks; //checkVerXoops, checkVerPhp Traits
52
53
    use Common\ServerStats; // getServerStats Trait
54
55
    use Common\FilesManagement; // Files Management Trait
56
57
    //--------------- Custom module methods -----------------------------
58
59
60
    public static function expireAd()
61
    {
62
        global $xoopsDB, $xoopsConfig, $xoopsModule, $myts, $meta, $moduleDirName, $main_lang;
63
64
        $datenow = time();
65
        $message = '';
66
67
        $result5 = $xoopsDB->query('SELECT lid, title, expire, type, desctext, date, email, submitter, photo, valid, hits, comments, remind FROM ' . $xoopsDB->prefix('adslight_listing') . " WHERE valid='Yes'");
68
69
        while (list($lids, $title, $expire, $type, $desctext, $dateann, $email, $submitter, $photo, $valid, $hits, $comments, $remind) = $xoopsDB->fetchRow($result5)) {
70
            $title     = $myts->htmlSpecialChars($title);
71
            $expire    = $myts->htmlSpecialChars($expire);
72
            $type      = $myts->htmlSpecialChars($type);
73
            $desctext  =& $myts->displayTarea($desctext, 1, 1, 1, 1, 1);
74
            $submitter = $myts->htmlSpecialChars($submitter);
75
            $remind    = $myts->htmlSpecialChars($remind);
76
            $supprdate = $dateann + ($expire * 86400);
77
            $almost    = $GLOBALS['xoopsModuleConfig']['adslight_almost'];
78
79
            // give warning that add is about to expire
80
81
            if ($almost > 0 && ($supprdate - $almost * 86400) < $datenow
82
                && 'Yes' === $valid
83
                && 0 == $remind) {
84
                $xoopsDB->queryF('UPDATE ' . $xoopsDB->prefix('adslight_listing') . " SET remind='1' WHERE lid=$lids");
85
86
                if ($email) {
87
                    $tags               = [];
88
                    $subject            = '' . _ADSLIGHT_ALMOST . '';
89
                    $tags['TITLE']      = $title;
90
                    $tags['HELLO']      = '' . _ADSLIGHT_HELLO . '';
91
                    $tags['YOUR_AD_ON'] = '' . _ADSLIGHT_YOUR_AD_ON . '';
92
                    $tags['VEDIT_AD']   = '' . _ADSLIGHT_VEDIT_AD . '';
93
                    $tags['YOUR_AD']    = '' . _ADSLIGHT_YOUR_AD . '';
94
                    $tags['SOON']       = '' . _ADSLIGHT_SOON . '';
95
                    $tags['VIEWED']     = '' . _ADSLIGHT_VU . '';
96
                    $tags['TIMES']      = '' . _ADSLIGHT_TIMES . '';
97
                    $tags['WEBMASTER']  = '' . _ADSLIGHT_WEBMASTER . '';
98
                    $tags['THANKS']     = '' . _ADSLIGHT_THANKS . '';
99
                    $tags['TYPE']       = static::getNameType($type);
100
                    $tags['DESCTEXT']   = $desctext;
101
                    $tags['HITS']       = $hits;
102
                    $tags['META_TITLE'] = $meta['title'];
103
                    $tags['SUBMITTER']  = $submitter;
104
                    $tags['DURATION']   = $expire;
105
                    $tags['LINK_URL']   = XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname') . '/viewads.php?' . '&lid=' . $lids;
0 ignored issues
show
Bug introduced by
The constant XoopsModules\Adslight\XOOPS_URL was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
106
                    $mail               =& getMailer();
0 ignored issues
show
Bug introduced by
The function getMailer was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

106
                    $mail               =& /** @scrutinizer ignore-call */ getMailer();
Loading history...
107
                    $mail->setTemplateDir(XOOPS_ROOT_PATH . '/modules/' . $xoopsModule->getVar('dirname') . '/language/' . $xoopsConfig['language'] . '/mail_template/');
0 ignored issues
show
Bug introduced by
The constant XoopsModules\Adslight\XOOPS_ROOT_PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
108
                    $mail->setTemplate('listing_expires.tpl');
109
                    $mail->useMail();
110
                    $mail->multimailer->isHTML(true);
111
                    $mail->setFromName($meta['title']);
112
                    $mail->setFromEmail($xoopsConfig['adminmail']);
113
                    $mail->setToEmails($email);
114
                    $mail->setSubject($subject);
115
                    $mail->assign($tags);
116
                    $mail->send();
117
                    echo $mail->getErrors();
118
                }
119
            }
120
121
            // expire ad
122
123
            if ($supprdate < $datenow) {
124
                if (0 != $photo) {
125
                    $result2 = $xoopsDB->query('SELECT url FROM ' . $xoopsDB->prefix('adslight_pictures') . ' WHERE lid=' . $xoopsDB->escape($lids));
126
127
                    while (list($url) = $xoopsDB->fetchRow($result2)) {
128
                        $destination  = XOOPS_ROOT_PATH . '/uploads/AdsLight';
129
                        $destination2 = XOOPS_ROOT_PATH . '/uploads/AdsLight/thumbs';
130
                        $destination3 = XOOPS_ROOT_PATH . '/uploads/AdsLight/midsize';
131
                        if (file_exists("$destination/$url")) {
132
                            unlink("$destination/$url");
133
                        }
134
                        if (file_exists("$destination2/thumb_$url")) {
135
                            unlink("$destination2/thumb_$url");
136
                        }
137
                        if (file_exists("$destination3/resized_$url")) {
138
                            unlink("$destination3/resized_$url");
139
                        }
140
                    }
141
                }
142
143
                $xoopsDB->queryF('DELETE FROM ' . $xoopsDB->prefix('adslight_listing') . ' WHERE lid=' . $xoopsDB->escape($lids));
144
145
                //  Specification for Japan:
146
                //  $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."";
147
                if ($email) {
148
                    $tags               = [];
149
                    $subject            = '' . _ADSLIGHT_STOP . '';
150
                    $tags['TITLE']      = $title;
151
                    $tags['HELLO']      = '' . _ADSLIGHT_HELLO . '';
152
                    $tags['TYPE']       = static::getNameType($type);
153
                    $tags['DESCTEXT']   = $desctext;
154
                    $tags['HITS']       = $hits;
155
                    $tags['META_TITLE'] = $meta['title'];
156
                    $tags['SUBMITTER']  = $submitter;
157
                    $tags['YOUR_AD_ON'] = '' . _ADSLIGHT_YOUR_AD_ON . '';
158
                    $tags['EXPIRED']    = '' . _ADSLIGHT_EXPIRED . '';
159
                    $tags['MESSTEXT']   = stripslashes($message);
160
                    $tags['OTHER']      = '' . _ADSLIGHT_OTHER . '';
161
                    $tags['WEBMASTER']  = '' . _ADSLIGHT_WEBMASTER . '';
162
                    $tags['THANKS']     = '' . _ADSLIGHT_THANKS . '';
163
                    $tags['VIEWED']     = '' . _ADSLIGHT_VU . '';
164
                    $tags['TIMES']      = '' . _ADSLIGHT_TIMES . '';
165
                    $tags['TEAM']       = '' . _ADSLIGHT_TEAM . '';
166
                    $tags['DURATION']   = $expire;
167
                    $tags['LINK_URL']   = XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname') . '/viewads.php?' . '&lid=' . $lids;
168
                    $mail               =& getMailer();
169
                    $mail->setTemplateDir(XOOPS_ROOT_PATH . '/modules/' . $xoopsModule->getVar('dirname') . '/language/' . $xoopsConfig['language'] . '/mail_template/');
170
                    $mail->setTemplate('listing_expired.tpl');
171
                    $mail->useMail();
172
                    $mail->multimailer->isHTML(true);
173
                    $mail->setFromName($meta['title']);
174
                    $mail->setFromEmail($xoopsConfig['adminmail']);
175
                    $mail->setToEmails($email);
176
                    $mail->setSubject($subject);
177
                    $mail->assign($tags);
178
                    $mail->send();
179
                    echo $mail->getErrors();
180
                }
181
            }
182
        }
183
    }
184
185
    //updates rating data in itemtable for a given user
186
187
    /**
188
     * @param $sel_id
189
     */
190
    public static function updateUserRating($sel_id)
191
    {
192
        global $xoopsDB, $moduleDirName, $main_lang;
193
194
        $usid = Request::getInt('usid', 0, 'GET');
0 ignored issues
show
Unused Code introduced by
The assignment to $usid is dead and can be removed.
Loading history...
195
196
        $query = 'SELECT rating FROM ' . $xoopsDB->prefix('adslight_user_votedata') . ' WHERE usid=' . $xoopsDB->escape($sel_id) . ' ';
197
        //echo $query;
198
        $voteresult  = $xoopsDB->query($query);
199
        $votesDB     = $xoopsDB->getRowsNum($voteresult);
200
        $totalrating = 0;
201
        while (list($rating) = $xoopsDB->fetchRow($voteresult)) {
202
            $totalrating += $rating;
203
        }
204
        $finalrating = $totalrating / $votesDB;
205
        $finalrating = number_format($finalrating, 4);
206
        $query       = 'UPDATE ' . $xoopsDB->prefix('adslight_listing') . " SET user_rating=$finalrating, user_votes=$votesDB WHERE usid=" . $xoopsDB->escape($sel_id) . '';
207
        //echo $query;
208
        $xoopsDB->query($query) || exit();
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
209
    }
210
211
    //updates rating data in itemtable for a given item
212
213
    /**
214
     * @param $sel_id
215
     */
216
    public static function updateItemRating($sel_id)
217
    {
218
        global $xoopsDB, $moduleDirName, $main_lang;
219
220
        $lid = Request::getInt('lid', 0, 'GET');
0 ignored issues
show
Unused Code introduced by
The assignment to $lid is dead and can be removed.
Loading history...
221
222
        $query = 'SELECT rating FROM ' . $xoopsDB->prefix('adslight_item_votedata') . ' WHERE lid=' . $xoopsDB->escape($sel_id) . ' ';
223
        //echo $query;
224
        $voteresult  = $xoopsDB->query($query);
225
        $votesDB     = $xoopsDB->getRowsNum($voteresult);
226
        $totalrating = 0;
227
        while (list($rating) = $xoopsDB->fetchRow($voteresult)) {
228
            $totalrating += $rating;
229
        }
230
        $finalrating = $totalrating / $votesDB;
231
        $finalrating = number_format($finalrating, 4);
232
        $query       = 'UPDATE ' . $xoopsDB->prefix('adslight_listing') . " SET item_rating=$finalrating, item_votes=$votesDB WHERE lid=" . $xoopsDB->escape($sel_id) . '';
233
        //echo $query;
234
        $xoopsDB->query($query) || exit();
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
235
    }
236
237
    /**
238
     * @param        $sel_id
239
     * @param string $status
240
     *
241
     * @return int
242
     */
243
    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. ( Ignorable by Annotation )

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

243
    public static function getTotalItems($sel_id, /** @scrutinizer ignore-unused */ $status = '')

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

Loading history...
244
    {
245
        global $xoopsDB, $mytree, $moduleDirName;
246
        $categories = Adslight\Utility::getMyItemIds('adslight_view');
247
        $count      = 0;
248
        $arr        = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $arr is dead and can be removed.
Loading history...
249
        if (in_array($sel_id, $categories)) {
250
            $query = 'SELECT SQL_CACHE count(*) FROM ' . $xoopsDB->prefix('adslight_listing') . ' WHERE cid=' . (int)$sel_id . " AND valid='Yes' AND status!='1'";
251
252
            $result = $xoopsDB->query($query);
253
            list($thing) = $xoopsDB->fetchRow($result);
254
            $count = $thing;
255
            $arr   = $mytree->getAllChildId($sel_id);
256
            $size  = count($arr);
257
            for ($i = 0; $i < $size; ++$i) {
258
                if (in_array($arr[$i], $categories)) {
259
                    $query2 = 'SELECT SQL_CACHE count(*) FROM ' . $xoopsDB->prefix('adslight_listing') . ' WHERE cid=' . (int)$arr[$i] . " AND valid='Yes' AND status!='1'";
260
261
                    $result2 = $xoopsDB->query($query2);
262
                    list($thing) = $xoopsDB->fetchRow($result2);
263
                    $count += $thing;
264
                }
265
            }
266
        }
267
268
        return $count;
269
    }
270
271
    /**
272
     * @param $permtype
273
     *
274
     * @return mixed
275
     */
276
    public static function getMyItemIds($permtype)
277
    {
278
        global $moduleDirName;
279
        static $permissions = [];
280
        if (is_array($permissions)
281
            && array_key_exists($permtype, $permissions)) {
282
            return $permissions[$permtype];
283
        }
284
285
        /** @var XoopsModuleHandler $moduleHandler */
286
        $moduleHandler = xoops_getHandler('module');
0 ignored issues
show
Bug introduced by
The function xoops_getHandler was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

286
        $moduleHandler = /** @scrutinizer ignore-call */ xoops_getHandler('module');
Loading history...
287
        $myModule      = $moduleHandler->getByDirname('adslight');
288
        $groups        = is_object($GLOBALS['xoopsUser']) ? $GLOBALS['xoopsUser']->getGroups() : XOOPS_GROUP_ANONYMOUS;
0 ignored issues
show
Bug introduced by
The constant XoopsModules\Adslight\XOOPS_GROUP_ANONYMOUS was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
289
        /** @var XoopsGroupPermHandler $gpermHandler */
290
        $gpermHandler           = xoops_getHandler('groupperm');
291
        $categories             = $gpermHandler->getItemIds($permtype, $groups, $myModule->getVar('mid'));
292
        $permissions[$permtype] = $categories;
293
294
        return $categories;
295
    }
296
297
    /**
298
     * Returns a module's option
0 ignored issues
show
Bug introduced by
The type XoopsModules\Adslight\module was not found. Maybe you did not declare it correctly or list all dependencies?

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

filter:
    dependency_paths: ["lib/*"]

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

Loading history...
299
     * @param        $option module option's name
300
     * @param string $repmodule
301
     *
302
     * @return option's value
303
     */
0 ignored issues
show
Documentation Bug introduced by
The doc comment option's at position 0 could not be parsed: Unknown type name 'option's' at position 0 in option's.
Loading history...
304
    public static function getModuleOption($option, $repmodule = 'adslight')
305
    {
306
        global $xoopsModule;
307
        static $tbloptions = [];
308
        if (is_array($tbloptions) && array_key_exists($option, $tbloptions)) {
309
            return $tbloptions[$option];
310
        }
311
312
        $retval = false;
313
        if (isset($GLOBALS['xoopsModuleConfig'])
314
            && (is_object($xoopsModule)
315
                && $xoopsModule->getVar('dirname') == $repmodule
316
                && $xoopsModule->getVar('isactive'))) {
317
            if (isset($GLOBALS['xoopsModuleConfig'][$option])) {
318
                $retval = $GLOBALS['xoopsModuleConfig'][$option];
319
            }
320
        } else {
321
            /** @var XoopsModuleHandler $moduleHandler */
322
            $moduleHandler = xoops_getHandler('module');
0 ignored issues
show
Bug introduced by
The function xoops_getHandler was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

322
            $moduleHandler = /** @scrutinizer ignore-call */ xoops_getHandler('module');
Loading history...
323
            $module        = $moduleHandler->getByDirname($repmodule);
324
            /** @var XoopsModuleHandler $moduleHandler */
325
            $configHandler = xoops_getHandler('config');
326
            if ($module) {
327
                $moduleConfig = $configHandler->getConfigsByCat(0, $GLOBALS['xoopsModule']->getVar('mid'));
0 ignored issues
show
Unused Code introduced by
The assignment to $moduleConfig is dead and can be removed.
Loading history...
328
                if (null !== ($helper->getConfig($option))) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $helper seems to be never defined.
Loading history...
329
                    $retval = $helper->getConfig($option);
330
                }
331
            }
332
        }
333
        $tbloptions[$option] = $retval;
334
335
        return $retval;
336
    }
337
338
    public static function showImage()
339
    {
340
        global $moduleDirName;
341
        echo "<script type=\"text/javascript\">\n";
342
        echo "<!--\n\n";
343
        echo "function showimage() {\n";
344
        echo "if (!document.images)\n";
345
        echo "return\n";
346
        echo "document.images.avatar.src=\n";
347
        echo "'" . XOOPS_URL . "/modules/adslight/assets/images/img_cat/' + document.imcat.img.options[document.imcat.img.selectedIndex].value\n";
0 ignored issues
show
Bug introduced by
The constant XoopsModules\Adslight\XOOPS_URL was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
348
        echo "}\n\n";
349
        echo "//-->\n";
350
        echo "</script>\n";
351
    }
352
353
    //Reusable Link Sorting Functions
354
355
    /**
356
     * @param $orderby
357
     *
358
     * @return string
359
     */
360
    public static function convertOrderByIn($orderby)
361
    {
362
        switch (trim($orderby)) {
363
            case 'titleA':
364
                $orderby = 'title ASC';
365
                break;
366
            case 'dateA':
367
                $orderby = 'date ASC';
368
                break;
369
            case 'hitsA':
370
                $orderby = 'hits ASC';
371
                break;
372
            case 'priceA':
373
                $orderby = 'price ASC';
374
                break;
375
            case 'titleD':
376
                $orderby = 'title DESC';
377
                break;
378
            case 'hitsD':
379
                $orderby = 'hits DESC';
380
                break;
381
            case 'priceD':
382
                $orderby = 'price DESC';
383
                break;
384
            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...
385
            default:
386
                $orderby = 'date DESC';
387
                break;
388
        }
389
390
        return $orderby;
391
    }
392
393
    /**
394
     * @param $orderby
395
     *
396
     * @return string
397
     */
398
    public static function convertOrderByTrans($orderby)
399
    {
400
        global $main_lang;
401
        $orderbyTrans = '';
402
        if ('hits ASC' === $orderby) {
403
            $orderbyTrans = '' . _ADSLIGHT_POPULARITYLTOM . '';
404
        }
405
        if ('hits DESC' === $orderby) {
406
            $orderbyTrans = '' . _ADSLIGHT_POPULARITYMTOL . '';
407
        }
408
        if ('title ASC' === $orderby) {
409
            $orderbyTrans = '' . _ADSLIGHT_TITLEATOZ . '';
410
        }
411
        if ('title DESC' === $orderby) {
412
            $orderbyTrans = '' . _ADSLIGHT_TITLEZTOA . '';
413
        }
414
        if ('date ASC' === $orderby) {
415
            $orderbyTrans = '' . _ADSLIGHT_DATEOLD . '';
416
        }
417
        if ('date DESC' === $orderby) {
418
            $orderbyTrans = '' . _ADSLIGHT_DATENEW . '';
419
        }
420
        if ('price ASC' === $orderby) {
421
            $orderbyTrans = _ADSLIGHT_PRICELTOH;
422
        }
423
        if ('price DESC' === $orderby) {
424
            $orderbyTrans = '' . _ADSLIGHT_PRICEHTOL . '';
425
        }
426
427
        return $orderbyTrans;
428
    }
429
430
    /**
431
     * @param $orderby
432
     *
433
     * @return string
434
     */
435
    public static function convertOrderByOut($orderby)
436
    {
437
        if ('title ASC' === $orderby) {
438
            $orderby = 'titleA';
439
        }
440
        if ('date ASC' === $orderby) {
441
            $orderby = 'dateA';
442
        }
443
        if ('hits ASC' === $orderby) {
444
            $orderby = 'hitsA';
445
        }
446
        if ('price ASC' === $orderby) {
447
            $orderby = 'priceA';
448
        }
449
        if ('title DESC' === $orderby) {
450
            $orderby = 'titleD';
451
        }
452
        if ('date DESC' === $orderby) {
453
            $orderby = 'dateD';
454
        }
455
        if ('hits DESC' === $orderby) {
456
            $orderby = 'hitsD';
457
        }
458
        if ('price DESC' === $orderby) {
459
            $orderby = 'priceD';
460
        }
461
462
        return $orderby;
463
    }
464
465
    /**
466
     * @param string $caption
467
     * @param string $name
468
     * @param string $value
469
     * @param string $width
470
     * @param string $height
471
     * @param string $supplemental
472
     *
473
     * @return XoopsFormDhtmlTextArea|\XoopsFormEditor
0 ignored issues
show
Bug introduced by
The type XoopsModules\Adslight\XoopsFormDhtmlTextArea was not found. Maybe you did not declare it correctly or list all dependencies?

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

filter:
    dependency_paths: ["lib/*"]

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

Loading history...
474
     */
475
    public static function getEditor($caption, $name, $value = '', $width = '100%', $height = '300px', $supplemental = '')
0 ignored issues
show
Unused Code introduced by
The parameter $supplemental is not used and could be removed. ( Ignorable by Annotation )

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

475
    public static function getEditor($caption, $name, $value = '', $width = '100%', $height = '300px', /** @scrutinizer ignore-unused */ $supplemental = '')

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

Loading history...
Unused Code introduced by
The parameter $caption is not used and could be removed. ( Ignorable by Annotation )

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

475
    public static function getEditor(/** @scrutinizer ignore-unused */ $caption, $name, $value = '', $width = '100%', $height = '300px', $supplemental = '')

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

Loading history...
476
    {
477
        global $xoopsModule;
478
        $options = [];
479
        $isAdmin = $GLOBALS['xoopsUser']->isAdmin($xoopsModule->getVar('mid'));
480
481
        if (class_exists('XoopsFormEditor')) {
482
            $options['name']   = $name;
483
            $options['value']  = $value;
484
            $options['rows']   = 20;
485
            $options['cols']   = '100%';
486
            $options['width']  = $width;
487
            $options['height'] = $height;
488
            if ($isAdmin) {
489
                $myEditor = new \XoopsFormEditor(ucfirst($name), $GLOBALS['xoopsModuleConfig']['adslightAdminUser'], $options, $nohtml = false, $onfailure = 'textarea');
0 ignored issues
show
Bug introduced by
The type XoopsFormEditor was not found. Maybe you did not declare it correctly or list all dependencies?

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

filter:
    dependency_paths: ["lib/*"]

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

Loading history...
490
            } else {
491
                $myEditor = new \XoopsFormEditor(ucfirst($name), $GLOBALS['xoopsModuleConfig']['adslightEditorUser'], $options, $nohtml = false, $onfailure = 'textarea');
492
            }
493
        } else {
494
            $myEditor = new \XoopsFormDhtmlTextArea(ucfirst($name), $name, $value, '100%', '100%');
0 ignored issues
show
Bug introduced by
The type XoopsFormDhtmlTextArea was not found. Maybe you did not declare it correctly or list all dependencies?

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

filter:
    dependency_paths: ["lib/*"]

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

Loading history...
495
        }
496
497
        //        $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...
498
499
        return $myEditor;
500
    }
501
502
    /**
503
     * @param $tablename
504
     *
505
     * @return bool
506
     */
507
    public static function checkTableExists($tablename)
508
    {
509
        global $xoopsDB;
510
        $result = $xoopsDB->queryF("SHOW TABLES LIKE '$tablename'");
511
512
        return ($xoopsDB->getRowsNum($result) > 0);
513
    }
514
515
    /**
516
     * @param $fieldname
517
     * @param $table
518
     *
519
     * @return bool
520
     */
521
    public static function checkFieldExists($fieldname, $table)
522
    {
523
        global $xoopsDB;
524
        $result = $xoopsDB->queryF("SHOW COLUMNS FROM $table LIKE '$fieldname'");
525
526
        return ($xoopsDB->getRowsNum($result) > 0);
527
    }
528
529
    /**
530
     * @param $field
531
     * @param $table
532
     *
533
     * @return mixed
534
     */
535
    public static function addField($field, $table)
536
    {
537
        global $xoopsDB;
538
        $result = $xoopsDB->queryF('ALTER TABLE ' . $table . " ADD $field;");
539
540
        return $result;
541
    }
542
543
    /**
544
     * @param $cid
545
     *
546
     * @return bool
547
     */
548
    public static function getCatNameFromId($cid)
549
    {
550
        global $xoopsDB, $xoopsConfig, $myts, $moduleDirName;
551
552
        $sql = 'SELECT SQL_CACHE title FROM ' . $xoopsDB->prefix('adslight_categories') . " WHERE cid = '$cid'";
553
554
        if (!$result = $xoopsDB->query($sql)) {
555
            return false;
556
        }
557
558
        if (!$arr = $xoopsDB->fetchArray($result)) {
559
            return false;
560
        }
561
562
        $title = $arr['title'];
563
564
        return $title;
565
    }
566
567
    /**
568
     * @return mixed
569
     */
570
    public static function goCategory()
571
    {
572
        global $xoopsDB;
573
574
        $xt   = new \XoopsTree($xoopsDB->prefix('adslight_categories'), 'cid', 'pid');
0 ignored issues
show
Bug introduced by
The type XoopsTree was not found. Maybe you did not declare it correctly or list all dependencies?

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

filter:
    dependency_paths: ["lib/*"]

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

Loading history...
575
        $jump = XOOPS_URL . '/modules/adslight/viewcats.php?cid=';
0 ignored issues
show
Bug introduced by
The constant XoopsModules\Adslight\XOOPS_URL was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
576
        ob_start();
577
        $xt->makeMySelBox('title', 'title', 0, 1, 'pid', 'location="' . $jump . '"+this.options[this.selectedIndex].value');
578
        $block['selectbox'] = ob_get_contents();
0 ignored issues
show
Comprehensibility Best Practice introduced by
$block was never initialized. Although not strictly required by PHP, it is generally a good practice to add $block = array(); before regardless.
Loading history...
579
        ob_end_clean();
580
581
        return $block;
582
    }
583
584
    // ADSLIGHT Version 2 //
585
    // Fonction rss.php RSS par categories
586
    /**
587
     * @return array
588
     */
589
    public static function returnAllAdsRss()
590
    {
591
        global $xoopsDB;
592
593
        $cid = Request::getInt('cid', null, 'GET');
594
595
        $result = [];
596
597
        $sql = 'SELECT lid, title, price, date, town FROM ' . $xoopsDB->prefix('adslight_listing') . " WHERE valid='yes' AND cid=" . $xoopsDB->escape($cid) . ' ORDER BY date DESC';
598
599
        $resultValues = $xoopsDB->query($sql);
600
        while (false !== ($resultTemp = $xoopsDB->fetchBoth($resultValues))) {
601
            array_push($result, $resultTemp);
602
        }
603
604
        return $result;
605
    }
606
607
    // Fonction fluxrss.php RSS Global
608
609
    /**
610
     * @return array
611
     */
612
    public static function returnAllAdsFluxRss()
613
    {
614
        global $xoopsDB;
615
616
        $result = [];
617
618
        $sql = 'SELECT lid, title, price, desctext, date, town FROM ' . $xoopsDB->prefix('adslight_listing') . " WHERE valid='yes' ORDER BY date DESC LIMIT 0,15";
619
620
        $resultValues = $xoopsDB->query($sql);
621
        while (false !== ($resultTemp = $xoopsDB->fetchBoth($resultValues))) {
622
            array_push($result, $resultTemp);
623
        }
624
625
        return $result;
626
    }
627
628
    /**
629
     * @param $type
630
     *
631
     * @return mixed
632
     */
633
    public static function getNameType($type)
634
    {
635
        global $xoopsDB;
636
        $sql = $xoopsDB->query('SELECT nom_type FROM ' . $xoopsDB->prefix('adslight_type') . " WHERE id_type='" . $xoopsDB->escape($type) . "'");
637
        list($nom_type) = $xoopsDB->fetchRow($sql);
638
639
        return $nom_type;
640
    }
641
642
    /**
643
     * @param $format
644
     * @param $number
645
     *
646
     * @return mixed
647
     */
648
    public static function getMoneyFormat($format, $number)
649
    {
650
        $regex = '/%((?:[\^!\-]|\+|\(|\=.)*)([0-9]+)?' . '(?:#([0-9]+))?(?:\.([0-9]+))?([in%])/';
651
        if ('C' === setlocale(LC_MONETARY, 0)) {
652
            setlocale(LC_MONETARY, '');
653
        }
654
655
        setlocale(LC_ALL, 'en_US');
656
        //        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...
657
658
        $locale = localeconv();
659
        preg_match_all($regex, $format, $matches, PREG_SET_ORDER);
660
        foreach ($matches as $fmatch) {
661
            $value      = (float)$number;
662
            $flags      = [
663
                'fillchar'  => preg_match('/\=(.)/', $fmatch[1], $match) ? $match[1] : ' ',
664
                'nogroup'   => preg_match('/\^/', $fmatch[1]) > 0,
665
                'usesignal' => preg_match('/\+|\(/', $fmatch[1], $match) ? $match[0] : '+',
666
                'nosimbol'  => preg_match('/\!/', $fmatch[1]) > 0,
667
                'isleft'    => preg_match('/\-/', $fmatch[1]) > 0
668
            ];
669
            $width      = trim($fmatch[2]) ? (int)$fmatch[2] : 0;
670
            $left       = trim($fmatch[3]) ? (int)$fmatch[3] : 0;
671
            $right      = trim($fmatch[4]) ? (int)$fmatch[4] : $locale['int_frac_digits'];
672
            $conversion = $fmatch[5];
673
674
            $positive = true;
675
            if ($value < 0) {
676
                $positive = false;
677
                $value    *= -1;
678
            }
679
            $letter = $positive ? 'p' : 'n';
680
681
            $prefix = $suffix = $cprefix = $csuffix = $signal = '';
0 ignored issues
show
Unused Code introduced by
The assignment to $signal is dead and can be removed.
Loading history...
682
683
            $signal = $positive ? $locale['positive_sign'] : $locale['negative_sign'];
684
            switch (true) {
685
                case 1 == $locale["{$letter}_sign_posn"]
686
                     && '+' == $flags['usesignal']:
687
                    $prefix = $signal;
688
                    break;
689
                case 2 == $locale["{$letter}_sign_posn"]
690
                     && '+' == $flags['usesignal']:
691
                    $suffix = $signal;
692
                    break;
693
                case 3 == $locale["{$letter}_sign_posn"]
694
                     && '+' == $flags['usesignal']:
695
                    $cprefix = $signal;
696
                    break;
697
                case 4 == $locale["{$letter}_sign_posn"]
698
                     && '+' == $flags['usesignal']:
699
                    $csuffix = $signal;
700
                    break;
701
                case '(' === $flags['usesignal']:
702
                case 0 == $locale["{$letter}_sign_posn"]:
703
                    $prefix = '(';
704
                    $suffix = ')';
705
                    break;
706
            }
707
            if (!$flags['nosimbol']) {
708
                $currency = $cprefix . ('i' === $conversion ? $locale['int_curr_symbol'] : $locale['currency_symbol']) . $csuffix;
709
            } else {
710
                $currency = '';
711
            }
712
            $space = $locale["{$letter}_sep_by_space"] ? ' ' : '';
713
714
            $value = number_format($value, $right, $locale['mon_decimal_point'], $flags['nogroup'] ? '' : $locale['mon_thousands_sep']);
715
            $value = @explode($locale['mon_decimal_point'], $value);
716
717
            $n = strlen($prefix) + strlen($currency) + strlen($value[0]);
718
            if ($left > 0 && $left > $n) {
719
                $value[0] = str_repeat($flags['fillchar'], $left - $n) . $value[0];
720
            }
721
            $value = implode($locale['mon_decimal_point'], $value);
722
            if ($locale["{$letter}_cs_precedes"]) {
723
                $value = $prefix . $currency . $space . $value . $suffix;
724
            } else {
725
                $value = $prefix . $value . $space . $currency . $suffix;
726
            }
727
            if ($width > 0) {
728
                $value = str_pad($value, $width, $flags['fillchar'], $flags['isleft'] ? STR_PAD_RIGHT : STR_PAD_LEFT);
729
            }
730
731
            $format = str_replace($fmatch[0], $value, $format);
732
        }
733
734
        return $format;
735
    }
736
737
    /**
738
     * Saves permissions for the selected category
739
     *
740
     *   saveCategory_Permissions()
741
     *
742
     * @param  array   $groups     : group with granted permission
743
     * @param  integer $categoryid : categoryid on which we are setting permissions
744
     * @param  string  $perm_name  : name of the permission
745
     * @return boolean : TRUE if the no errors occured
746
     */
747
748
    public static function saveCategoryPermissions($groups, $categoryId, $permName)
749
    {
750
        global $xoopsModule;
751
752
        $moduleDirName = basename(dirname(__DIR__));
753
754
        if (false !== ($helper = Helper::getHelper($moduleDirName))) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
755
        } else {
756
            $helper = Helper::getHelper('system');
757
        }
758
759
        $result = true;
760
        //        $xoopsModule = sf_getModuleInfo();
0 ignored issues
show
Unused Code Comprehensibility introduced by
45% 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...
761
        $moduleId = $helper->getModule()->getVar('mid');
762
763
        $gpermHandler = xoops_getHandler('groupperm');
0 ignored issues
show
Bug introduced by
The function xoops_getHandler was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

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

763
        $gpermHandler = /** @scrutinizer ignore-call */ xoops_getHandler('groupperm');
Loading history...
764
        // First, if the permissions are already there, delete them
765
        $gpermHandler->deleteByModule($moduleId, $permName, $categoryId);
766
        // Save the new permissions
767
        if (count($groups) > 0) {
768
            foreach ($groups as $groupId) {
769
                $gpermHandler->addRight($permName, $categoryId, $groupId, $moduleId);
770
            }
771
        }
772
773
        return $result;
774
    }
775
}
776