Passed
Push — master ( d50017...68c32a )
by Michael
02:26
created

Utility::cloneRecord()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 8
dl 0
loc 16
rs 10
c 0
b 0
f 0
cc 4
nc 8
nop 3
1
<?php
2
3
namespace XoopsModules\Adslight;
4
5
/*
6
-------------------------------------------------------------------------
7
                     ADSLIGHT 2 : Module for Xoops
8
9
        Redesigned and ameliorate By Luc Bizet user at www.frxoops.org
10
        Started with the Classifieds module and made MANY changes
11
        Website : http://www.luc-bizet.fr
12
        Contact : [email protected]
13
-------------------------------------------------------------------------
14
             Original credits below Version History
15
##########################################################################
16
#                    Classified Module for Xoops                         #
17
#  By John Mordo user jlm69 at www.xoops.org and www.jlmzone.com         #
18
#      Started with the MyAds module and made MANY changes               #
19
##########################################################################
20
 Original Author: Pascal Le Boustouller
21
 Author Website : [email protected]
22
 Licence Type   : GPL
23
-------------------------------------------------------------------------
24
*/
25
26
/**
27
 * AdslightUtil Class
28
 *
29
 * @copyright   XOOPS Project (https://xoops.org)
30
 * @license     http://www.fsf.org/copyleft/gpl.html GNU public license
31
 * @author      XOOPS Development Team
32
 * @package     AdsLight
33
 * @since       1.03
34
 */
35
36
use Xmf\Request;
37
use XoopsModules\Adslight;
38
use XoopsModules\Adslight\Common;
39
40
require_once XOOPS_ROOT_PATH . '/class/xoopstree.php';
41
$myts = \MyTextSanitizer::getInstance();
42
43
/**
44
 * Class Utility
45
 */
46
class Utility
47
{
48
    use Common\VersionChecks; //checkVerXoops, checkVerPhp Traits
0 ignored issues
show
introduced by
The trait XoopsModules\Adslight\Common\VersionChecks requires some properties which are not provided by XoopsModules\Adslight\Utility: $tag_name, $prerelease
Loading history...
49
50
    use Common\ServerStats; // getServerStats Trait
51
52
    use Common\FilesManagement; // Files Management Trait
53
54
    //--------------- Custom module methods -----------------------------
55
56
    public static function expireAd()
57
    {
58
        global $xoopsDB, $xoopsConfig, $xoopsModule, $myts, $meta;
59
60
        $datenow = time();
61
        $message = '';
62
63
        $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'");
64
65
        while (false !== (list($lids, $title, $expire, $type, $desctext, $dateann, $email, $submitter, $photo, $valid, $hits, $comments, $remind) = $xoopsDB->fetchRow($result5))) {
66
            $title     = $myts->htmlSpecialChars($title);
67
            $expire    = $myts->htmlSpecialChars($expire);
68
            $type      = $myts->htmlSpecialChars($type);
69
            $desctext  = &$myts->displayTarea($desctext, 1, 1, 1, 1, 1);
70
            $submitter = $myts->htmlSpecialChars($submitter);
71
            $remind    = $myts->htmlSpecialChars($remind);
72
            $supprdate = $dateann + ($expire * 86400);
73
            $almost    = $GLOBALS['xoopsModuleConfig']['adslight_almost'];
74
75
            // give warning that add is about to expire
76
77
            if ($almost > 0 && ($supprdate - $almost * 86400) < $datenow
78
                && 'Yes' === $valid
79
                && 0 == $remind) {
80
                $xoopsDB->queryF('UPDATE ' . $xoopsDB->prefix('adslight_listing') . " SET remind='1' WHERE lid=$lids");
81
82
                if ($email) {
83
                    $tags               = [];
84
                    $subject            = '' . _ADSLIGHT_ALMOST . '';
85
                    $tags['TITLE']      = $title;
86
                    $tags['HELLO']      = '' . _ADSLIGHT_HELLO . '';
87
                    $tags['YOUR_AD_ON'] = '' . _ADSLIGHT_YOUR_AD_ON . '';
88
                    $tags['VEDIT_AD']   = '' . _ADSLIGHT_VEDIT_AD . '';
89
                    $tags['YOUR_AD']    = '' . _ADSLIGHT_YOUR_AD . '';
90
                    $tags['SOON']       = '' . _ADSLIGHT_SOON . '';
91
                    $tags['VIEWED']     = '' . _ADSLIGHT_VU . '';
92
                    $tags['TIMES']      = '' . _ADSLIGHT_TIMES . '';
93
                    $tags['WEBMASTER']  = '' . _ADSLIGHT_WEBMASTER . '';
94
                    $tags['THANKS']     = '' . _ADSLIGHT_THANKS . '';
95
                    $tags['TYPE']       = static::getNameType($type);
96
                    $tags['DESCTEXT']   = $desctext;
97
                    $tags['HITS']       = $hits;
98
                    $tags['META_TITLE'] = $meta['title'];
99
                    $tags['SUBMITTER']  = $submitter;
100
                    $tags['DURATION']   = $expire;
101
                    $tags['LINK_URL']   = XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname') . '/viewads.php?' . '&lid=' . $lids;
102
                    $mail               = &getMailer();
103
                    $mail->setTemplateDir(XOOPS_ROOT_PATH . '/modules/' . $xoopsModule->getVar('dirname') . '/language/' . $xoopsConfig['language'] . '/mail_template/');
104
                    $mail->setTemplate('listing_expires.tpl');
105
                    $mail->useMail();
106
                    $mail->multimailer->isHTML(true);
107
                    $mail->setFromName($meta['title']);
108
                    $mail->setFromEmail($xoopsConfig['adminmail']);
109
                    $mail->setToEmails($email);
110
                    $mail->setSubject($subject);
111
                    $mail->assign($tags);
112
                    $mail->send();
113
                    echo $mail->getErrors();
114
                }
115
            }
116
117
            // expire ad
118
119
            if ($supprdate < $datenow) {
120
                if (0 != $photo) {
121
                    $result2 = $xoopsDB->query('SELECT url FROM ' . $xoopsDB->prefix('adslight_pictures') . ' WHERE lid=' . $xoopsDB->escape($lids));
122
123
                    while (false !== (list($url) = $xoopsDB->fetchRow($result2))) {
124
                        $destination  = XOOPS_ROOT_PATH . '/uploads/adslight';
125
                        $destination2 = XOOPS_ROOT_PATH . '/uploads/adslight/thumbs';
126
                        $destination3 = XOOPS_ROOT_PATH . '/uploads/adslight/midsize';
127
                        if (file_exists("$destination/$url")) {
128
                            unlink("$destination/$url");
129
                        }
130
                        if (file_exists("$destination2/thumb_$url")) {
131
                            unlink("$destination2/thumb_$url");
132
                        }
133
                        if (file_exists("$destination3/resized_$url")) {
134
                            unlink("$destination3/resized_$url");
135
                        }
136
                    }
137
                }
138
139
                $xoopsDB->queryF('DELETE FROM ' . $xoopsDB->prefix('adslight_listing') . ' WHERE lid=' . $xoopsDB->escape($lids));
140
141
                //  Specification for Japan:
142
                //  $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."";
143
                if ($email) {
144
                    $tags               = [];
145
                    $subject            = '' . _ADSLIGHT_STOP . '';
146
                    $tags['TITLE']      = $title;
147
                    $tags['HELLO']      = '' . _ADSLIGHT_HELLO . '';
148
                    $tags['TYPE']       = static::getNameType($type);
149
                    $tags['DESCTEXT']   = $desctext;
150
                    $tags['HITS']       = $hits;
151
                    $tags['META_TITLE'] = $meta['title'];
152
                    $tags['SUBMITTER']  = $submitter;
153
                    $tags['YOUR_AD_ON'] = '' . _ADSLIGHT_YOUR_AD_ON . '';
154
                    $tags['EXPIRED']    = '' . _ADSLIGHT_EXPIRED . '';
155
                    $tags['MESSTEXT']   = stripslashes($message);
156
                    $tags['OTHER']      = '' . _ADSLIGHT_OTHER . '';
157
                    $tags['WEBMASTER']  = '' . _ADSLIGHT_WEBMASTER . '';
158
                    $tags['THANKS']     = '' . _ADSLIGHT_THANKS . '';
159
                    $tags['VIEWED']     = '' . _ADSLIGHT_VU . '';
160
                    $tags['TIMES']      = '' . _ADSLIGHT_TIMES . '';
161
                    $tags['TEAM']       = '' . _ADSLIGHT_TEAM . '';
162
                    $tags['DURATION']   = $expire;
163
                    $tags['LINK_URL']   = XOOPS_URL . '/modules/' . $xoopsModule->getVar('dirname') . '/viewads.php?' . '&lid=' . $lids;
164
                    $mail               = &getMailer();
165
                    $mail->setTemplateDir(XOOPS_ROOT_PATH . '/modules/' . $xoopsModule->getVar('dirname') . '/language/' . $xoopsConfig['language'] . '/mail_template/');
166
                    $mail->setTemplate('listing_expired.tpl');
167
                    $mail->useMail();
168
                    $mail->multimailer->isHTML(true);
169
                    $mail->setFromName($meta['title']);
170
                    $mail->setFromEmail($xoopsConfig['adminmail']);
171
                    $mail->setToEmails($email);
172
                    $mail->setSubject($subject);
173
                    $mail->assign($tags);
174
                    $mail->send();
175
                    echo $mail->getErrors();
176
                }
177
            }
178
        }
179
    }
180
181
    //updates rating data in itemtable for a given user
182
183
    /**
184
     * @param $sel_id
185
     */
186
    public static function updateUserRating($sel_id)
187
    {
188
        global $xoopsDB;
189
190
        $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...
191
192
        $query = 'SELECT rating FROM ' . $xoopsDB->prefix('adslight_user_votedata') . ' WHERE usid=' . $xoopsDB->escape($sel_id) . ' ';
193
        //echo $query;
194
        $voteresult  = $xoopsDB->query($query);
195
        $votesDB     = $xoopsDB->getRowsNum($voteresult);
196
        $totalrating = 0;
197
        while (false !== (list($rating) = $xoopsDB->fetchRow($voteresult))) {
198
            $totalrating += $rating;
199
        }
200
        $finalrating = $totalrating / $votesDB;
201
        $finalrating = number_format($finalrating, 4);
202
        $query       = 'UPDATE ' . $xoopsDB->prefix('adslight_listing') . " SET user_rating=$finalrating, user_votes=$votesDB WHERE usid=" . $xoopsDB->escape($sel_id) . '';
203
        //echo $query;
204
        $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...
205
    }
206
207
    //updates rating data in itemtable for a given item
208
209
    /**
210
     * @param $sel_id
211
     */
212
    public static function updateItemRating($sel_id)
213
    {
214
        global $xoopsDB;
215
216
        $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...
217
218
        $query = 'SELECT rating FROM ' . $xoopsDB->prefix('adslight_item_votedata') . ' WHERE lid=' . $xoopsDB->escape($sel_id) . ' ';
219
        //echo $query;
220
        $voteresult  = $xoopsDB->query($query);
221
        $votesDB     = $xoopsDB->getRowsNum($voteresult);
222
        $totalrating = 0;
223
        while (false !== (list($rating) = $xoopsDB->fetchRow($voteresult))) {
224
            $totalrating += $rating;
225
        }
226
        $finalrating = $totalrating / $votesDB;
227
        $finalrating = number_format($finalrating, 4);
228
        $query       = 'UPDATE ' . $xoopsDB->prefix('adslight_listing') . " SET item_rating=$finalrating, item_votes=$votesDB WHERE lid=" . $xoopsDB->escape($sel_id) . '';
229
        //echo $query;
230
        $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...
231
    }
232
233
    /**
234
     * @param        $sel_id
235
     * @param string $status
236
     *
237
     * @return int
238
     */
239
    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

239
    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...
240
    {
241
        global $xoopsDB, $mytree;
242
        $categories = self::getMyItemIds('adslight_view');
243
        $count      = 0;
244
        $arr        = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $arr is dead and can be removed.
Loading history...
245
        if (in_array($sel_id, $categories)) {
246
            $query = 'SELECT SQL_CACHE count(*) FROM ' . $xoopsDB->prefix('adslight_listing') . ' WHERE cid=' . (int)$sel_id . " AND valid='Yes' AND status!='1'";
247
248
            $result = $xoopsDB->query($query);
249
            list($thing) = $xoopsDB->fetchRow($result);
250
            $count = $thing;
251
            $arr   = $mytree->getAllChildId($sel_id);
252
            foreach ($arr as $iValue) {
253
                if (in_array($iValue, $categories)) {
254
                    $query2 = 'SELECT SQL_CACHE count(*) FROM ' . $xoopsDB->prefix('adslight_listing') . ' WHERE cid=' . (int)$iValue . " AND valid='Yes' AND status!='1'";
255
256
                    $result2 = $xoopsDB->query($query2);
257
                    list($thing) = $xoopsDB->fetchRow($result2);
258
                    $count += $thing;
259
                }
260
            }
261
        }
262
263
        return $count;
264
    }
265
266
    /**
267
     * @param $permtype
268
     *
269
     * @return mixed
270
     */
271
    public static function getMyItemIds($permtype)
272
    {
273
        static $permissions = [];
274
        if (is_array($permissions)
275
            && array_key_exists($permtype, $permissions)) {
276
            return $permissions[$permtype];
277
        }
278
279
        /** @var \XoopsModuleHandler $moduleHandler */
280
        $moduleHandler = xoops_getHandler('module');
281
        $myModule      = $moduleHandler->getByDirname('adslight');
282
        $groups        = is_object($GLOBALS['xoopsUser']) ? $GLOBALS['xoopsUser']->getGroups() : XOOPS_GROUP_ANONYMOUS;
283
        /** @var \XoopsGroupPermHandler $grouppermHandler */
284
        $grouppermHandler       = xoops_getHandler('groupperm');
285
        $categories             = $grouppermHandler->getItemIds($permtype, $groups, $myModule->getVar('mid'));
286
        $permissions[$permtype] = $categories;
287
288
        return $categories;
289
    }
290
291
    /**
292
     * Returns a module's option
293
     * @param string $option module option's name
294
     * @param string $repmodule
295
     *
296
     * @return bool|mixed option's value
297
     */
298
    public static function getModuleOption($option, $repmodule = 'adslight')
299
    {
300
        global $xoopsModule;
301
        /** @var \XoopsModules\Adslight\Helper $helper */
302
        $helper = \XoopsModules\Adslight\Helper::getInstance();
303
        static $tbloptions = [];
304
        if (is_array($tbloptions) && array_key_exists($option, $tbloptions)) {
305
            return $tbloptions[$option];
306
        }
307
308
        $retval = false;
309
        if (isset($GLOBALS['xoopsModuleConfig'])
310
            && (is_object($xoopsModule)
311
                && $xoopsModule->getVar('dirname') == $repmodule
312
                && $xoopsModule->getVar('isactive'))) {
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'));
0 ignored issues
show
Unused Code introduced by
The assignment to $moduleConfig is dead and can be removed.
Loading history...
324
                if (null !== $helper->getConfig($option)) {
325
                    $retval = $helper->getConfig($option);
326
                }
327
            }
328
        }
329
        $tbloptions[$option] = $retval;
330
331
        return $retval;
332
    }
333
334
    public static function showImage()
335
    {
336
        echo "<script type=\"text/javascript\">\n";
337
        echo "<!--\n\n";
338
        echo "function showimage() {\n";
339
        echo "if (!document.images)\n";
340
        echo "return\n";
341
        echo "document.images.avatar.src=\n";
342
        echo "'" . XOOPS_URL . "/modules/adslight/assets/images/img_cat/' + document.imcat.img.options[document.imcat.img.selectedIndex].value\n";
343
        echo "}\n\n";
344
        echo "//-->\n";
345
        echo "</script>\n";
346
    }
347
348
    //Reusable Link Sorting Functions
349
350
    /**
351
     * @param $orderby
352
     *
353
     * @return string
354
     */
355
    public static function convertOrderByIn($orderby)
356
    {
357
        switch (trim($orderby)) {
358
            case 'titleA':
359
                $orderby = 'title ASC';
360
                break;
361
            case 'dateA':
362
                $orderby = 'date ASC';
363
                break;
364
            case 'hitsA':
365
                $orderby = 'hits ASC';
366
                break;
367
            case 'priceA':
368
                $orderby = 'price ASC';
369
                break;
370
            case 'titleD':
371
                $orderby = 'title DESC';
372
                break;
373
            case 'hitsD':
374
                $orderby = 'hits DESC';
375
                break;
376
            case 'priceD':
377
                $orderby = 'price DESC';
378
                break;
379
            case'dateD':
380
            default:
381
                $orderby = 'date DESC';
382
                break;
383
        }
384
385
        return $orderby;
386
    }
387
388
    /**
389
     * @param $orderby
390
     *
391
     * @return string
392
     */
393
    public static function convertOrderByTrans($orderby)
394
    {
395
        $orderbyTrans = '';
396
        if ('hits ASC' === $orderby) {
397
            $orderbyTrans = '' . _ADSLIGHT_POPULARITYLTOM . '';
398
        }
399
        if ('hits DESC' === $orderby) {
400
            $orderbyTrans = '' . _ADSLIGHT_POPULARITYMTOL . '';
401
        }
402
        if ('title ASC' === $orderby) {
403
            $orderbyTrans = '' . _ADSLIGHT_TITLEATOZ . '';
404
        }
405
        if ('title DESC' === $orderby) {
406
            $orderbyTrans = '' . _ADSLIGHT_TITLEZTOA . '';
407
        }
408
        if ('date ASC' === $orderby) {
409
            $orderbyTrans = '' . _ADSLIGHT_DATEOLD . '';
410
        }
411
        if ('date DESC' === $orderby) {
412
            $orderbyTrans = '' . _ADSLIGHT_DATENEW . '';
413
        }
414
        if ('price ASC' === $orderby) {
415
            $orderbyTrans = _ADSLIGHT_PRICELTOH;
416
        }
417
        if ('price DESC' === $orderby) {
418
            $orderbyTrans = '' . _ADSLIGHT_PRICEHTOL . '';
419
        }
420
421
        return $orderbyTrans;
422
    }
423
424
    /**
425
     * @param $orderby
426
     *
427
     * @return string
428
     */
429
    public static function convertOrderByOut($orderby)
430
    {
431
        if ('title ASC' === $orderby) {
432
            $orderby = 'titleA';
433
        }
434
        if ('date ASC' === $orderby) {
435
            $orderby = 'dateA';
436
        }
437
        if ('hits ASC' === $orderby) {
438
            $orderby = 'hitsA';
439
        }
440
        if ('price ASC' === $orderby) {
441
            $orderby = 'priceA';
442
        }
443
        if ('title DESC' === $orderby) {
444
            $orderby = 'titleD';
445
        }
446
        if ('date DESC' === $orderby) {
447
            $orderby = 'dateD';
448
        }
449
        if ('hits DESC' === $orderby) {
450
            $orderby = 'hitsD';
451
        }
452
        if ('price DESC' === $orderby) {
453
            $orderby = 'priceD';
454
        }
455
456
        return $orderby;
457
    }
458
459
    /**
460
     * @param string $caption
461
     * @param string $name
462
     * @param string $value
463
     * @param string $width
464
     * @param string $height
465
     * @param string $supplemental
466
     *
467
     * @return \XoopsFormDhtmlTextArea|\XoopsFormEditor
468
     */
469
    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. ( Ignorable by Annotation )

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

469
    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...
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

469
    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...
470
    {
471
        global $xoopsModule;
472
        $options = [];
473
        $isAdmin = $GLOBALS['xoopsUser']->isAdmin($xoopsModule->getVar('mid'));
474
475
        if (class_exists('XoopsFormEditor')) {
476
            $options['name']   = $name;
477
            $options['value']  = $value;
478
            $options['rows']   = 20;
479
            $options['cols']   = '100%';
480
            $options['width']  = $width;
481
            $options['height'] = $height;
482
            if ($isAdmin) {
483
                $myEditor = new \XoopsFormEditor(ucfirst($name), $GLOBALS['xoopsModuleConfig']['adslightAdminUser'], $options, $nohtml = false, $onfailure = 'textarea');
484
            } else {
485
                $myEditor = new \XoopsFormEditor(ucfirst($name), $GLOBALS['xoopsModuleConfig']['adslightEditorUser'], $options, $nohtml = false, $onfailure = 'textarea');
486
            }
487
        } else {
488
            $myEditor = new \XoopsFormDhtmlTextArea(ucfirst($name), $name, $value, '100%', '100%');
0 ignored issues
show
Bug introduced by
'100%' of type string is incompatible with the type integer expected by parameter $rows of XoopsFormDhtmlTextArea::__construct(). ( Ignorable by Annotation )

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

488
            $myEditor = new \XoopsFormDhtmlTextArea(ucfirst($name), $name, $value, /** @scrutinizer ignore-type */ '100%', '100%');
Loading history...
Bug introduced by
'100%' of type string is incompatible with the type integer expected by parameter $cols of XoopsFormDhtmlTextArea::__construct(). ( Ignorable by Annotation )

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

488
            $myEditor = new \XoopsFormDhtmlTextArea(ucfirst($name), $name, $value, '100%', /** @scrutinizer ignore-type */ '100%');
Loading history...
489
        }
490
491
        //        $form->addElement($descEditor);
492
493
        return $myEditor;
494
    }
495
496
    /**
497
     * @param $tablename
498
     *
499
     * @return bool
500
     */
501
    public static function checkTableExists($tablename)
502
    {
503
        global $xoopsDB;
504
        $result = $xoopsDB->queryF("SHOW TABLES LIKE '$tablename'");
505
506
        return ($xoopsDB->getRowsNum($result) > 0);
507
    }
508
509
    /**
510
     * @param $fieldname
511
     * @param $table
512
     *
513
     * @return bool
514
     */
515
    public static function checkFieldExists($fieldname, $table)
516
    {
517
        global $xoopsDB;
518
        $result = $xoopsDB->queryF("SHOW COLUMNS FROM $table LIKE '$fieldname'");
519
520
        return ($xoopsDB->getRowsNum($result) > 0);
521
    }
522
523
    /**
524
     * @param $field
525
     * @param $table
526
     *
527
     * @return mixed
528
     */
529
    public static function addField($field, $table)
530
    {
531
        global $xoopsDB;
532
        $result = $xoopsDB->queryF('ALTER TABLE ' . $table . " ADD $field;");
533
534
        return $result;
535
    }
536
537
    /**
538
     * @param $cid
539
     *
540
     * @return bool
541
     */
542
    public static function getCatNameFromId($cid)
543
    {
544
        global $xoopsDB, $myts;
545
546
        $sql = 'SELECT SQL_CACHE title FROM ' . $xoopsDB->prefix('adslight_categories') . " WHERE cid = '$cid'";
547
548
        if (!$result = $xoopsDB->query($sql)) {
549
            return false;
550
        }
551
552
        if (!$arr = $xoopsDB->fetchArray($result)) {
553
            return false;
554
        }
555
556
        $title = $arr['title'];
557
558
        return $title;
559
    }
560
561
    /**
562
     * @return mixed
563
     */
564
    public static function goCategory()
565
    {
566
        global $xoopsDB;
567
568
        $xoopsTree   = new \XoopsTree($xoopsDB->prefix('adslight_categories'), 'cid', 'pid');
569
        $jump = XOOPS_URL . '/modules/adslight/viewcats.php?cid=';
570
        ob_start();
571
        $xoopsTree->makeMySelBox('title', 'title', 0, 1, 'pid', 'location="' . $jump . '"+this.options[this.selectedIndex].value');
572
        $block['selectbox'] = ob_get_clean();
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...
573
574
        return $block;
575
    }
576
577
    // ADSLIGHT Version 2 //
578
    // Fonction rss.php RSS par categories
579
580
    /**
581
     * @return array
582
     */
583
    public static function returnAllAdsRss()
584
    {
585
        global $xoopsDB;
586
587
        $cid = Request::getInt('cid', null, 'GET');
588
589
        $result = [];
590
591
        $sql = 'SELECT lid, title, price, date, town FROM ' . $xoopsDB->prefix('adslight_listing') . " WHERE valid='yes' AND cid=" . $xoopsDB->escape($cid) . ' ORDER BY date DESC';
592
593
        $resultValues = $xoopsDB->query($sql);
594
        while (false !== ($resultTemp = $xoopsDB->fetchBoth($resultValues))) {
595
            $result[] = $resultTemp;
596
        }
597
598
        return $result;
599
    }
600
601
    // Fonction fluxrss.php RSS Global
602
603
    /**
604
     * @return array
605
     */
606
    public static function returnAllAdsFluxRss()
607
    {
608
        global $xoopsDB;
609
610
        $result = [];
611
612
        $sql = 'SELECT lid, title, price, desctext, date, town FROM ' . $xoopsDB->prefix('adslight_listing') . " WHERE valid='yes' ORDER BY date DESC LIMIT 0,15";
613
614
        $resultValues = $xoopsDB->query($sql);
615
        while (false !== ($resultTemp = $xoopsDB->fetchBoth($resultValues))) {
616
            $result[] = $resultTemp;
617
        }
618
619
        return $result;
620
    }
621
622
    /**
623
     * @param $type
624
     *
625
     * @return mixed
626
     */
627
    public static function getNameType($type)
628
    {
629
        global $xoopsDB;
630
        $sql = $xoopsDB->query('SELECT nom_type FROM ' . $xoopsDB->prefix('adslight_type') . " WHERE id_type='" . $xoopsDB->escape($type) . "'");
631
        list($nom_type) = $xoopsDB->fetchRow($sql);
632
633
        return $nom_type;
634
    }
635
636
    /**
637
     * @param $format
638
     * @param $number
639
     *
640
     * @return mixed
641
     */
642
    public static function getMoneyFormat($format, $number)
643
    {
644
        $regex = '/%((?:[\^!\-]|\+|\(|\=.)*)([0-9]+)?' . '(?:#([0-9]+))?(?:\.([0-9]+))?([in%])/';
645
        if ('C' === setlocale(LC_MONETARY, 0)) {
646
            setlocale(LC_MONETARY, '');
647
        }
648
649
        setlocale(LC_ALL, 'en_US');
650
        //        setlocale(LC_ALL, 'fr_FR');
651
652
        $locale = localeconv();
653
        preg_match_all($regex, $format, $matches, PREG_SET_ORDER);
654
        foreach ($matches as $fmatch) {
655
            $value      = (float)$number;
656
            $flags      = [
657
                'fillchar'  => preg_match('/\=(.)/', $fmatch[1], $match) ? $match[1] : ' ',
658
                'nogroup'   => preg_match('/\^/', $fmatch[1]) > 0,
659
                'usesignal' => preg_match('/\+|\(/', $fmatch[1], $match) ? $match[0] : '+',
660
                'nosimbol'  => preg_match('/\!/', $fmatch[1]) > 0,
661
                'isleft'    => preg_match('/\-/', $fmatch[1]) > 0,
662
            ];
663
            $width      = trim($fmatch[2]) ? (int)$fmatch[2] : 0;
664
            $left       = trim($fmatch[3]) ? (int)$fmatch[3] : 0;
665
            $right      = trim($fmatch[4]) ? (int)$fmatch[4] : $locale['int_frac_digits'];
666
            $conversion = $fmatch[5];
667
668
            $positive = true;
669
            if ($value < 0) {
670
                $positive = false;
671
                $value    *= -1;
672
            }
673
            $letter = $positive ? 'p' : 'n';
674
675
            $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...
676
677
            $signal = $positive ? $locale['positive_sign'] : $locale['negative_sign'];
678
            switch (true) {
679
                case 1 == $locale["{$letter}_sign_posn"]
680
                     && '+' == $flags['usesignal']:
681
                    $prefix = $signal;
682
                    break;
683
                case 2 == $locale["{$letter}_sign_posn"]
684
                     && '+' == $flags['usesignal']:
685
                    $suffix = $signal;
686
                    break;
687
                case 3 == $locale["{$letter}_sign_posn"]
688
                     && '+' == $flags['usesignal']:
689
                    $cprefix = $signal;
690
                    break;
691
                case 4 == $locale["{$letter}_sign_posn"]
692
                     && '+' == $flags['usesignal']:
693
                    $csuffix = $signal;
694
                    break;
695
                case '(' === $flags['usesignal']:
696
                case 0 == $locale["{$letter}_sign_posn"]:
697
                    $prefix = '(';
698
                    $suffix = ')';
699
                    break;
700
            }
701
            if (!$flags['nosimbol']) {
702
                $currency = $cprefix . ('i' === $conversion ? $locale['int_curr_symbol'] : $locale['currency_symbol']) . $csuffix;
703
            } else {
704
                $currency = '';
705
            }
706
            $space = $locale["{$letter}_sep_by_space"] ? ' ' : '';
707
708
            $value = number_format($value, $right, $locale['mon_decimal_point'], $flags['nogroup'] ? '' : $locale['mon_thousands_sep']);
709
            $value = @explode($locale['mon_decimal_point'], $value);
710
711
            $n = mb_strlen($prefix) + mb_strlen($currency) + mb_strlen($value[0]);
712
            if ($left > 0 && $left > $n) {
713
                $value[0] = str_repeat($flags['fillchar'], $left - $n) . $value[0];
714
            }
715
            $value = implode($locale['mon_decimal_point'], $value);
716
            if ($locale["{$letter}_cs_precedes"]) {
717
                $value = $prefix . $currency . $space . $value . $suffix;
718
            } else {
719
                $value = $prefix . $value . $space . $currency . $suffix;
720
            }
721
            if ($width > 0) {
722
                $value = str_pad($value, $width, $flags['fillchar'], $flags['isleft'] ? STR_PAD_RIGHT : STR_PAD_LEFT);
723
            }
724
725
            $format = str_replace($fmatch[0], $value, $format);
726
        }
727
728
        return $format;
729
    }
730
731
    /**
732
     * Saves permissions for the selected category
733
     *
734
     *   saveCategory_Permissions()
735
     *
736
     * @param array  $groups : group with granted permission
737
     * @param        $categoryId
738
     * @param        $permName
739
     * @return bool : TRUE if the no errors occured
740
     */
741
    public static function saveCategoryPermissions($groups, $categoryId, $permName)
742
    {
743
        global $xoopsModule;
744
        /** @var \XoopsModules\Adslight\Helper $helper */
745
        $helper = \XoopsModules\Adslight\Helper::getInstance();
0 ignored issues
show
Unused Code introduced by
The assignment to $helper is dead and can be removed.
Loading history...
746
747
        $result = true;
748
        //        $xoopsModule = sf_getModuleInfo();
749
//        $moduleId = $helper->getModule()->getVar('mid');
750
        $moduleId = $xoopsModule->getVar('mid');
751
752
        $grouppermHandler = xoops_getHandler('groupperm');
753
        // First, if the permissions are already there, delete them
754
        /** @var \XoopsGroupPermHandler $grouppermHandler */
755
        $grouppermHandler->deleteByModule($moduleId, $permName, $categoryId);
756
        // Save the new permissions
757
        if (count($groups) > 0) {
758
            foreach ($groups as $groupId) {
759
                $grouppermHandler->addRight($permName, $categoryId, $groupId, $moduleId);
760
            }
761
        }
762
763
        return $result;
764
    }
765
766
767
    //======================= NEW ========================
768
    //--------------- Custom module methods -----------------------------
769
770
    /**
771
     * @param $text
772
     * @param $form_sort
773
     * @return string
774
     */
775
    public static function selectSorting($text, $form_sort)
776
    {
777
        global $start, $order, $file_cat, $sort, $xoopsModule;
778
779
        $select_view   = '';
0 ignored issues
show
Unused Code introduced by
The assignment to $select_view is dead and can be removed.
Loading history...
780
        $moduleDirName = basename(dirname(__DIR__));
781
        /** @var Adslight\Helper $helper */
782
        $helper = Adslight\Helper::getInstance();
783
784
        $pathModIcon16 = XOOPS_URL . '/modules/' . $moduleDirName . '/' . $helper->getModule()->getInfo('modicons16');
0 ignored issues
show
Bug introduced by
Are you sure $helper->getModule()->getInfo('modicons16') of type array|string can be used in concatenation? ( Ignorable by Annotation )

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

784
        $pathModIcon16 = XOOPS_URL . '/modules/' . $moduleDirName . '/' . /** @scrutinizer ignore-type */ $helper->getModule()->getInfo('modicons16');
Loading history...
785
786
        $select_view = '<form name="form_switch" id="form_switch" action="' . Request::getString('REQUEST_URI', '', 'SERVER') . '" method="post"><span style="font-weight: bold;">' . $text . '</span>';
787
        //$sorts =  $sort ==  'asc' ? 'desc' : 'asc';
788
        if ($form_sort == $sort) {
789
            $sel1 = 'asc' === $order ? 'selasc.png' : 'asc.png';
790
            $sel2 = 'desc' === $order ? 'seldesc.png' : 'desc.png';
791
        } else {
792
            $sel1 = 'asc.png';
793
            $sel2 = 'desc.png';
794
        }
795
        $select_view .= '  <a href="' . Request::getString('PHP_SELF', '', 'SERVER') . '?start=' . $start . '&sort=' . $form_sort . '&order=asc"><img src="' . $pathModIcon16 . '/' . $sel1 . '" title="ASC" alt="ASC"></a>';
796
        $select_view .= '<a href="' . Request::getString('PHP_SELF', '', 'SERVER') . '?start=' . $start . '&sort=' . $form_sort . '&order=desc"><img src="' . $pathModIcon16 . '/' . $sel2 . '" title="DESC" alt="DESC"></a>';
797
        $select_view .= '</form>';
798
799
        return $select_view;
800
    }
801
802
    /***************Blocks***************/
803
    /**
804
     * @param array $cats
805
     * @return string
806
     */
807
    public static function blockAddCatSelect($cats)
808
    {
809
        $cat_sql = '';
810
        if (is_array($cats)) {
0 ignored issues
show
introduced by
The condition is_array($cats) is always true.
Loading history...
811
            $cat_sql = '(' . current($cats);
812
            array_shift($cats);
813
            foreach ($cats as $cat) {
814
                $cat_sql .= ',' . $cat;
815
            }
816
            $cat_sql .= ')';
817
        }
818
819
        return $cat_sql;
820
    }
821
822
    /**
823
     * @param $content
824
     */
825
    public static function metaKeywords($content)
826
    {
827
        global $xoopsTpl, $xoTheme;
828
        $myts    = \MyTextSanitizer::getInstance();
829
        $content = $myts->undoHtmlSpecialChars($myts->displayTarea($content));
830
        if (null !== $xoTheme && is_object($xoTheme)) {
831
            $xoTheme->addMeta('meta', 'keywords', strip_tags($content));
832
        } else {    // Compatibility for old Xoops versions
833
            $xoopsTpl->assign('xoops_metaKeywords', strip_tags($content));
834
        }
835
    }
836
837
    /**
838
     * @param $content
839
     */
840
    public static function metaDescription($content)
841
    {
842
        global $xoopsTpl, $xoTheme;
843
        $myts    = \MyTextSanitizer::getInstance();
844
        $content = $myts->undoHtmlSpecialChars($myts->displayTarea($content));
845
        if (null !== $xoTheme && is_object($xoTheme)) {
846
            $xoTheme->addMeta('meta', 'description', strip_tags($content));
847
        } else {    // Compatibility for old Xoops versions
848
            $xoopsTpl->assign('xoops_metaDescription', strip_tags($content));
849
        }
850
    }
851
852
    /**
853
     * @param $tableName
854
     * @param $columnName
855
     *
856
     * @return array
857
     */
858
    public static function enumerate($tableName, $columnName)
859
    {
860
        $table = $GLOBALS['xoopsDB']->prefix($tableName);
861
862
        //    $result = $GLOBALS['xoopsDB']->query("SELECT COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS
863
        //        WHERE TABLE_NAME = '" . $table . "' AND COLUMN_NAME = '" . $columnName . "'")
864
        //    || exit ($GLOBALS['xoopsDB']->error());
865
866
        $sql    = 'SELECT COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = "' . $table . '" AND COLUMN_NAME = "' . $columnName . '"';
867
        $result = $GLOBALS['xoopsDB']->query($sql);
868
        if (!$result) {
869
            exit($GLOBALS['xoopsDB']->error());
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...
870
        }
871
872
        $row      = $GLOBALS['xoopsDB']->fetchBoth($result);
873
        $enumList = explode(',', str_replace("'", '', substr($row['COLUMN_TYPE'], 5, - 6)));
874
        return $enumList;
875
    }
876
877
    /**
878
     * @param array|string $tableName
879
     * @param int          $id_field
880
     * @param int          $id
881
     *
882
     * @return mixed
883
     */
884
    public static function cloneRecord($tableName, $id_field, $id)
885
    {
886
        $new_id = false;
887
        $table  = $GLOBALS['xoopsDB']->prefix($tableName);
888
        // copy content of the record you wish to clone 
889
        $tempTable = $GLOBALS['xoopsDB']->fetchArray($GLOBALS['xoopsDB']->query("SELECT * FROM $table WHERE $id_field='$id' "), MYSQLI_ASSOC) or exit('Could not select record');
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...
890
        // set the auto-incremented id's value to blank.
891
        unset($tempTable[$id_field]);
892
        // insert cloned copy of the original  record 
893
        $result = $GLOBALS['xoopsDB']->queryF("INSERT INTO $table (" . implode(', ', array_keys($tempTable)) . ") VALUES ('" . implode("', '", array_values($tempTable)) . "')") or exit($GLOBALS['xoopsDB']->error());
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...
894
895
        if ($result) {
896
            // Return the new id
897
            $new_id = $GLOBALS['xoopsDB']->getInsertId();
898
        }
899
        return $new_id;
900
    }
901
902
903
    /**
904
     * truncateHtml can truncate a string up to a number of characters while preserving whole words and HTML tags
905
     * www.gsdesign.ro/blog/cut-html-string-without-breaking-the-tags
906
     * www.cakephp.org
907
     *
908
     * @param string  $text         String to truncate.
909
     * @param integer $length       Length of returned string, including ellipsis.
910
     * @param string  $ending       Ending to be appended to the trimmed string.
911
     * @param boolean $exact        If false, $text will not be cut mid-word
912
     * @param boolean $considerHtml If true, HTML tags would be handled correctly
913
     *
914
     * @return string Trimmed string.
915
     */
916
    public static function truncateHtml($text, $length = 100, $ending = '...', $exact = false, $considerHtml = true)
917
    {
918
        if ($considerHtml) {
919
            // if the plain text is shorter than the maximum length, return the whole text
920
            if (strlen(preg_replace('/<.*?' . '>/', '', $text)) <= $length) {
921
                return $text;
922
            }
923
            // splits all html-tags to scanable lines
924
            preg_match_all('/(<.+?' . '>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
925
            $total_length = strlen($ending);
926
            $openTags    = [];
927
            $truncate     = '';
928
            foreach ($lines as $line_matchings) {
929
                // if there is any html-tag in this line, handle it and add it (uncounted) to the output
930
                if (!empty($line_matchings[1])) {
931
                    // if it's an "empty element" with or without xhtml-conform closing slash
932
                    if (preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $line_matchings[1])) {
933
                        // do nothing
934
                        // if tag is a closing tag
935
                    } elseif (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $line_matchings[1], $tag_matchings)) {
936
                        // delete tag from $openTags list
937
                        $pos = array_search($tag_matchings[1], $openTags);
938
                        if (false !== $pos) {
939
                            unset($openTags[$pos]);
940
                        }
941
                        // if tag is an opening tag
942
                    } elseif (preg_match('/^<\s*([^\s>!]+).*?' . '>$/s', $line_matchings[1], $tag_matchings)) {
943
                        // add tag to the beginning of $openTags list
944
                        array_unshift($openTags, strtolower($tag_matchings[1]));
945
                    }
946
                    // add html-tag to $truncate'd text
947
                    $truncate .= $line_matchings[1];
948
                }
949
                // calculate the length of the plain text part of the line; handle entities as one character
950
                $content_length = strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', ' ', $line_matchings[2]));
951
                if ($total_length + $content_length > $length) {
952
                    // the number of characters which are left
953
                    $left            = $length - $total_length;
954
                    $entities_length = 0;
955
                    // search for html entities
956
                    if (preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', $line_matchings[2], $entities, PREG_OFFSET_CAPTURE)) {
957
                        // calculate the real length of all entities in the legal range
958
                        foreach ($entities[0] as $entity) {
959
                            if ($entity[1] + 1 - $entities_length <= $left) {
960
                                $left--;
961
                                $entities_length += strlen($entity[0]);
962
                            } else {
963
                                // no more characters left
964
                                break;
965
                            }
966
                        }
967
                    }
968
                    $truncate .= substr($line_matchings[2], 0, $left + $entities_length);
969
                    // maximum lenght is reached, so get off the loop
970
                    break;
971
                } else {
972
                    $truncate     .= $line_matchings[2];
973
                    $total_length += $content_length;
974
                }
975
                // if the maximum length is reached, get off the loop
976
                if ($total_length >= $length) {
977
                    break;
978
                }
979
            }
980
        } else {
981
            if (strlen($text) <= $length) {
982
                return $text;
983
            } else {
984
                $truncate = substr($text, 0, $length - strlen($ending));
985
            }
986
        }
987
        // if the words shouldn't be cut in the middle...
988
        if (!$exact) {
989
            // ...search the last occurance of a space...
990
            $spacepos = strrpos($truncate, ' ');
991
            if (isset($spacepos)) {
992
                // ...and cut the text in this position
993
                $truncate = substr($truncate, 0, $spacepos);
994
            }
995
        }
996
        // add the defined ending to the text
997
        $truncate .= $ending;
998
        if ($considerHtml) {
999
            // close all unclosed html-tags
1000
            foreach ($openTags as $tag) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $openTags does not seem to be defined for all execution paths leading up to this point.
Loading history...
1001
                $truncate .= '</' . $tag . '>';
1002
            }
1003
        }
1004
1005
        return $truncate;
1006
    }
1007
1008
}
1009