Passed
Pull Request — master (#9)
by Michael
03:24
created

Utility::toolbar()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 7
dl 0
loc 13
rs 10
c 0
b 0
f 0
cc 4
nc 2
nop 0
1
<?php
2
3
namespace XoopsModules\Mylinks;
4
5
/**
6
 *  mylinks Utility Class Elements
7
 *
8
 * @copyright ::  ZySpec Incorporated
9
 * @license   ::    {@link https://www.gnu.org/licenses/gpl-2.0.html GNU Public License}
10
 * @package   ::    mylinks
11
 * @subpackage:: class
12
 * @author    ::     zyspec ([email protected])
13
 * @since     ::     File available since Release 3.11
14
 */
15
16
17
18
use XoopsModules\Mylinks;
19
use XoopsModules\Mylinks\Common;
20
use XoopsModules\Mylinks\Constants;
21
22
/**
23
 * Class Utility
24
 */
25
class Utility extends Common\SysUtility
26
{
27
    //--------------- Custom module methods -----------------------------
28
    /**
29
     * Sanitize input variables
30
     * @param string              $global  the input array ($_REQUEST, $_GET, $_POST)
31
     * @param unknown_type        $key     the array key for variable to clean
0 ignored issues
show
Bug introduced by
The type XoopsModules\Mylinks\unknown_type 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...
32
     * @param string|unknown_type $default the default value to use if filter fails
33
     * @param string              $type    the variable type (string, email, url, int)
34
     * @param array               $limit   'min' 'max' keys - the lower/upper limit for integer values
35
     * @return Ambigous|number     <boolean, unknown>
0 ignored issues
show
Bug introduced by
The type XoopsModules\Mylinks\Ambigous 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
     */
37
    public static function cleanVars($global, $key, $default = '', $type = 'int', $limit = null)
38
    {
39
        switch ($type) {
40
            case 'string':
41
                if (defined('FILTER_SANITIZE_ADD_SLASHES')) {
42
                    $ret = isset($global[$key]) ? filter_var($global[$key], FILTER_SANITIZE_ADD_SLASHES) : $default;
43
                } else {
44
                    $ret = isset($global[$key]) ? filter_var($global[$key], FILTER_SANITIZE_MAGIC_QUOTES) : $default;
45
                }
46
                break;
47
            case 'email':
48
                $ret = isset($global[$key]) ? filter_var($global[$key], FILTER_SANITIZE_EMAIL) : $default;
49
                break;
50
            case 'url':
51
                $ret = isset($global[$key]) ? filter_var($global[$key], FILTER_SANITIZE_URL) : $default;
52
                break;
53
            case 'int':
54
            default:
55
                $default = (int)$default;
56
                $ret     = isset($global[$key]) ? filter_var($global[$key], FILTER_SANITIZE_NUMBER_INT) : false;
57
                if (isset($limit) && is_array($limit) && (false !== $ret)) {
58
                    if (array_key_exists('min', $limit)) {
59
                        $ret = ($ret >= $limit['min']) ? $ret : false;
60
                    }
61
                    if (array_key_exists('max', $limit)) {
62
                        $ret = ($ret <= $limit['max']) ? $ret : false;
63
                    }
64
                }
65
                break;
66
        }
67
        $ret = (false === $ret) ? $default : $ret;
68
69
        return $ret;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $ret also could return the type string which is incompatible with the documented return type XoopsModules\Mylinks\Ambigous|double|integer.
Loading history...
70
    }
71
72
    /**
73
     * Temporary patch for error_handler processing
74
     * @param string $msg   message to display
75
     * @param int    $pages number of pages to jump back for link
76
     * @param string $type  error||info to add errorMsg CSS to display
77
     * @deprecated
78
     */
79
    public static function show_message($msg, $pages = 1, $type = 'error')
80
    {
81
        switch (mb_strtolower($type)) {
82
            case 'error':
83
                $div_class = "class='errorMsg'";
84
                break;
85
            case 'info':
86
                $div_class = '';
87
                break;
88
        }
89
        require_once XOOPS_ROOT_PATH . '/header.php';
90
        echo "<div{$div_class}><strong>{$xoopsConfig['sitename']} Error</strong><br><br>\n" . "Error Code: {$e_code}<br><br><br>\n" . "<strong>ERROR:</strong> {$msg}<br>\n";
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $div_class does not seem to be defined for all execution paths leading up to this point.
Loading history...
Comprehensibility Best Practice introduced by
The variable $xoopsConfig seems to be never defined.
Loading history...
Comprehensibility Best Practice introduced by
The variable $e_code seems to be never defined.
Loading history...
91
        $pages = (int)$pages;
92
        if (0 != $pages) {
93
            $pages = '-' . abs($pages);
94
            echo "<br><br>\n" . "[ <a href='javascript:history.go({$pages})'>" . _BACK . '</a> ]</div>';
95
        }
96
        require_once XOOPS_ROOT_PATH . '/footer.php';
97
    }
98
99
100
    /**
101
     * @param $time
102
     * @param $status
103
     * @return string
104
     */
105
    public static function newLinkGraphic($time, $status)
106
    {
107
        $count     = 7;
108
        $new       = '';
109
        $startdate = (time() - (86400 * $count));
110
111
        if ($startdate < $time) {
112
            if (1 == $status) {
113
                $new = "&nbsp;<img src='" . self::getIconURL('newred.gif') . "' alt='" . _MD_MYLINKS_NEWTHISWEEK . "'>";
114
            } elseif (2 == $status) {
115
                $new = "&nbsp;<img src='" . self::getIconURL('update.gif') . "' alt='" . _MD_MYLINKS_UPTHISWEEK . "'>";
116
            }
117
        }
118
119
        return $new;
120
    }
121
122
    /**
123
     * @param $hits
124
     * @return string
125
     */
126
    public static function popGraphic($hits)
127
    {
128
        /** @var Mylinks\Helper $helper */
129
        $helper = Mylinks\Helper::getInstance();
130
        $retVal = '';
131
132
        if (isset($hits) && ($hits >= $helper->getConfig('popular'))) {
133
            $retVal = "&nbsp;<img src='" . self::getIconURL('pop.gif') . "' alt='" . _MD_MYLINKS_POPULAR . "'>";
134
        }
135
136
        return $retVal;
137
    }
138
139
    /*
140
     * Reusable Link Sorting Functions
141
     *
142
     * @param string orderby is a shortened string for sorting
143
     * @return string returns a dB 'ready' ORDER BY string for dB query
144
     */
145
    /**
146
     * @param $orderby
147
     * @return string
148
     */
149
    public static function convertorderbyin($orderby)
150
    {
151
        $orderby = (isset($orderby) && ('' != trim($orderby))) ? trim($orderby) : '';
152
        switch ($orderby) {
153
            case 'titleA':
154
                $orderby = 'title ASC';
155
                break;
156
            case 'hitsA':
157
                $orderby = 'hits ASC';
158
                break;
159
            case 'ratingA':
160
                $orderby = 'rating ASC';
161
                break;
162
            case 'dateA':
163
                $orderby = 'date ASC';
164
                break;
165
            case 'titleD':
166
                $orderby = 'title DESC';
167
                break;
168
            case 'hitsD':
169
                $orderby = 'hits DESC';
170
                break;
171
            case 'ratingD':
172
                $orderby = 'rating DESC';
173
                break;
174
            case 'dateD':
175
            default:
176
                $orderby = 'date DESC';
177
                break;
178
        }
179
180
        return $orderby;
181
    }
182
183
    /**
184
     * @param $orderby
185
     * @return string
186
     */
187
    public static function convertorderbytrans($orderby)
188
    {
189
        $orderby = (isset($orderby) && ('' != trim($orderby))) ? trim($orderby) : '';
190
        switch ($orderby) {
191
            case 'title ASC':
192
                $orderbyTrans = '' . _MD_MYLINKS_TITLEATOZ . '';
193
                break;
194
            case 'hits ASC':
195
                $orderbyTrans = '' . _MD_MYLINKS_POPULARITYLTOM . '';
196
                break;
197
            case 'rating ASC':
198
                $orderbyTrans = '' . _MD_MYLINKS_RATINGLTOH . '';
199
                break;
200
            case 'date ASC':
201
                $orderbyTrans = '' . _MD_MYLINKS_DATEOLD . '';
202
                break;
203
            case 'title DESC':
204
                $orderbyTrans = '' . _MD_MYLINKS_TITLEZTOA . '';
205
                break;
206
            case 'hits DESC':
207
                $orderbyTrans = '' . _MD_MYLINKS_POPULARITYMTOL . '';
208
                break;
209
            case 'rating DESC':
210
                $orderbyTrans = '' . _MD_MYLINKS_RATINGHTOL . '';
211
                break;
212
            case 'date DESC':
213
            default:
214
                $orderbyTrans = '' . _MD_MYLINKS_DATENEW . '';
215
                break;
216
        }
217
218
        return $orderbyTrans;
219
    }
220
221
    /**
222
     * @param $orderby
223
     * @return string
224
     */
225
    public static function convertorderbyout($orderby)
226
    {
227
        $orderby = (isset($orderby) && ('' != trim($orderby))) ? trim($orderby) : '';
228
        switch ($orderby) {
229
            case 'title ASC':
230
                $orderby = 'titleA';
231
                break;
232
            case 'hits ASC':
233
                $orderby = 'hitsA';
234
                break;
235
            case 'rating ASC':
236
                $orderby = 'ratingA';
237
                break;
238
            case 'date ASC':
239
                $orderby = 'dateA';
240
                break;
241
            case 'title DESC':
242
                $orderby = 'titleD';
243
                break;
244
            case 'hits DESC':
245
                $orderby = 'hitsD';
246
                break;
247
            case 'rating DESC':
248
                $orderby = 'ratingD';
249
                break;
250
            case 'date DESC':
251
            default:
252
                $orderby = 'dateD';
253
                break;
254
        }
255
256
        return $orderby;
257
    }
258
259
    /**
260
     * Update rating data for a link in dB link table to keep in sync
261
     * with the vote dB table contents
262
     * @param int $sel_id Listing ID to update
263
     */
264
    public static function updaterating($sel_id)
265
    {
266
        global $xoopsDB;
267
        $sel_id     = (int)$sel_id;
268
        $sql        = 'SELECT COUNT(*), FORMAT(AVG(rating),4) FROM ' . $xoopsDB->prefix('mylinks_votedata') . " WHERE lid={$sel_id}";
269
        $voteResult = $xoopsDB->query($sql);
270
        if ($voteResult) {
271
            list($votesDB, $finalrating) = $xoopsDB->fetchRow($voteResult);
272
            /*
273
                $query = "SELECT rating FROM " . $xoopsDB->prefix("mylinks_votedata") . " WHERE lid={$sel_id}";
274
                $voteresult = $xoopsDB->query($query);
275
                $votesDB = $xoopsDB->getRowsNum($voteresult);
276
                $totalrating = 0;
277
                while (list($rating)=$xoopsDB->fetchRow($voteresult)) {
278
                    $totalrating += $rating;
279
                }
280
                $finalrating = $totalrating/$votesDB;
281
                $finalrating = number_format($finalrating, 4);
282
            */
283
            $query = 'UPDATE ' . $xoopsDB->prefix('mylinks_links') . " SET rating={$finalrating}, votes={$votesDB} WHERE lid = {$sel_id}";
284
            $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...
285
        }
286
    }
287
288
    //returns the total number of items in items table that are accociated with a given table $table id
289
    /**
290
     * @param null   $sel_id
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $sel_id is correct as it would always require null to be passed?
Loading history...
291
     * @param string $status
292
     * @param string $oper
293
     * @return mixed
294
     */
295
    public static function getTotalItems($sel_id = null, $status = '', $oper = '>')
296
    {
297
        $sel_id = filter_var($sel_id, FILTER_VALIDATE_INT, ['options' => ['default' => 0, 'min_range' => 0]]);
298
        $count  = 0;
0 ignored issues
show
Unused Code introduced by
The assignment to $count is dead and can be removed.
Loading history...
299
        $arr    = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $arr is dead and can be removed.
Loading history...
300
301
        /** @var \XoopsModules\Mylinks\Helper $helper */
302
        $helper = \XoopsModules\Mylinks\Helper::getInstance();
303
304
        // get XoopsObjectTree for categories
305
        $categoryHandler = $helper->getHandler('Category');
306
        $catFields         = ['cid', 'pid'];
307
        $catObjs           = $categoryHandler->getAll(null, $catFields);
308
        $myCatTree         = new \XoopsObjectTree($catObjs, 'cid', 'pid');
309
310
        /* new count routine */
311
        $childObjArray = $myCatTree->getAllChild($sel_id);
312
        //    $whereClause = "`cid`=0";
313
        $whereClause = "`cid`={$sel_id}";
314
        if (!empty($childObjArray)) {
315
            $whereClause = "`cid` IN ({$sel_id}";
316
            foreach ($childObjArray as $childObj) {
317
                $whereClause .= ',' . $childObj->getVar('cid');
318
            }
319
            $whereClause .= ')';
320
        }
321
        $query = 'SELECT COUNT(*) FROM ' . $GLOBALS['xoopsDB']->prefix('mylinks_links') . " WHERE {$whereClause}";
322
        if ('' !== $status) {
323
            $status = (int)$status;
324
            if (preg_match('/^[!]*[<=>]{1}[=>]*$/', $oper, $match)) {
325
                $oper = $match[0];
326
            } else {
327
                $oper = '>';
328
            }
329
            //        $oper   = (0 == (int)($status)) ? '=': '>';
330
            $query .= " AND status{$oper}{$status}";
331
        }
332
        $result = $GLOBALS['xoopsDB']->query($query);
333
        list($linkCount) = $GLOBALS['xoopsDB']->fetchRow($result);
334
335
        return $linkCount;
336
    }
337
338
    /*
339
    public static function getTotalItems($sel_id=NULL, $status='', $oper='>')
340
    {
341
        global $xoopsDB, $xoopsModule;
342
    
343
        $sel_id = filter_var($sel_id, FILTER_VALIDATE_INT, array( 'options' => array( 'default' => 0, 'min_range' => 0)));
344
        $count = 0;
345
        $arr = [];
346
    
347
        // get XoopsObjectTree for categories
348
        $categoryHandler = $helper->getHandler('category', $xoopsModule->getVar('dirname'));
349
        $catObjs = $categoryHandler->getAll();
350
        $myCatTree = new \XoopsObjectTree($catObjs, 'cid', 'pid');
351
    
352
        // new count routine
353
        $childObjArray = $myCatTree->getAllChild($sel_id);
354
        $catIds = "({$sel_id}";
355
        foreach ($childObjArray as $childObj) {
356
            $catIds .= ',' . $childObj->getVar('cid');
357
        }
358
        $catIds .= ')';
359
        $query = "SELECT COUNT(*) FROM " . $xoopsDB->prefix("mylinks_links") . " WHERE `cid` IN {$catIds}";
360
        if ('' !== $status) {
361
            $status = (int)($status);
362
            if ( preg_match($oper, "~^[!]?[<=>]{1}[=>]*$~", $match) ) {
363
                $oper = $match[0];
364
            } else {
365
                $oper = '>';
366
            }
367
    //        $oper   = (0 == (int)($status)) ? '=': '>';
368
            $query .= " AND status{$oper}{$status}";
369
        }
370
        $result = $xoopsDB->query($query);
371
        list($linkCount) = $xoopsDB->fetchRow($result);
372
    
373
        return $linkCount;
374
    }
375
    */
376
    //wanikoo
377
    /**
378
     * @param $aFile
379
     * @return string
380
     */
381
    public static function getStyleURL($aFile)
382
    {
383
        global $mylinks_theme;
384
        $StyleURL = XOOPSMYLINKINCURL . "/{$mylinks_theme}/icons/{$aFile}";
385
386
        if (file_exists(XOOPSMYLINKINCPATH . "/{$mylinks_theme}/icons/{$aFile}")) {
387
            return $StyleURL;
388
        }
389
390
        return XOOPSMYLINKINCURL . "/icons/{$aFile}";
391
    }
392
393
    /**
394
     * @param $aFile
395
     * @return string
396
     */
397
    public static function getIconURL($aFile)
398
    {
399
        global $mylinks_theme;
400
401
        if (file_exists(XOOPSMYLINKIMGPATH . "/{$mylinks_theme}/icons/{$aFile}")) {
402
            return XOOPSMYLINKIMGURL . "/{$mylinks_theme}/icons/{$aFile}";
403
        }
404
405
        return XOOPSMYLINKIMGURL . "/icons/{$aFile}";
406
    }
407
408
    /**
409
     * @param         $aFile
410
     * @param string  $subPath
411
     * @param bool    $relPath
412
     * @return string
413
     */
414
    public static function getStylePath($aFile, $subPath = '', $relPath = true)
0 ignored issues
show
Unused Code introduced by
The parameter $relPath 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

414
    public static function getStylePath($aFile, $subPath = '', /** @scrutinizer ignore-unused */ $relPath = true)

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...
415
    {
416
        global $mylinks_theme, $xoopsModule;
417
        //sanitize subPath to make sure it's only contains valid path chars
418
        $subPath = (!preg_match('/^(\D+)(\d*)$/', $subPath, $regs)) ? '' : $subPath;
419
420
        $path = $subPath ? 'modules/' . $xoopsModule->getVar('dirname') : XOOPSMYLINKPATH . '/modules/' . $xoopsModule->getVar('dirname') . '/';
421
422
        $subPath   = !empty($subPath) ? "/{$subPath}" : '';
423
        $stylePath = "{$path}{$subPath}/{$mylinks_theme}/{$aFile}";
424
425
        return file_exists($stylePath) ? $stylePath : "{$path}{$subPath}/{$aFile}";
426
    }
427
428
    /**
429
     * @return string
430
     */
431
    public static function letters()
432
    {
433
        global $xoopsDB, $xoopsModule;
434
435
        xoops_loadLanguage('main', $xoopsModule->getVar('dirname'));
436
        $alphabet = explode(',', _MD_MYLINKS_LTRCHARS);
437
438
        $result      = $xoopsDB->query('SELECT COUNT(*), LEFT(title, 1) AS sletter FROM ' . $xoopsDB->prefix('mylinks_links') . ' WHERE status>0 GROUP BY sletter');
439
        $letterArray = [];
440
        while (list($count, $sletter) = $xoopsDB->fetchRow($result)) {
441
            $sletter               = mb_strtoupper($sletter);
442
            $letterArray[$sletter] = $count;
443
        }
444
445
        $letterchoice = "<div class='browsebyletter'>" . _MD_MYLINKS_BROWSETOTOPIC . '</div>';
446
        $letterchoice .= '[  ';
447
        $num          = count($alphabet) - 1;
448
        $halfNum      = round($num / 2);
449
        $counter      = 0;
450
        foreach ($alphabet as $key => $ltr) {
451
            if (array_key_exists($ltr, $letterArray)) {
452
                $letterchoice .= "<a class='browsebyletter' href='" . XOOPSMYLINKURL . "/viewcat.php?list={$ltr}'>{$ltr}</a>";
453
            } else {
454
                $letterchoice .= $ltr;
455
            }
456
            if ($counter == $halfNum) {
457
                $letterchoice .= ' ]<br>[ ';
458
            } elseif ($counter != $num) {
459
                $letterchoice .= '&nbsp;|&nbsp;';
460
            }
461
            ++$counter;
462
        }
463
        $letterchoice .= ' ]';
464
465
        return $letterchoice;
466
    }
467
468
    /**
469
     * @return string
470
     */
471
    public static function toolbar()
472
    {
473
        global $xoopsUser;
474
        /** @var Mylinks\Helper $helper */
475
        $helper = Mylinks\Helper::getInstance();
476
477
        $toolbar = "[ <a href='index.php' class='toolbar'>" . _MD_MYLINKS_MAIN . '</a> | ';
478
        if (is_object($xoopsUser) || (!is_object($xoopsUser) && $helper->getConfig('anonpost'))) {
479
            $toolbar .= "<a href='submit.php' class='toolbar'>" . _MI_MYLINKS_SMNAME1 . '</a> | ';
480
        }
481
        $toolbar .= "<a href='topten.php?sort=2' class='toolbar'>" . _MI_MYLINKS_SMNAME2 . "</a> | <a href='topten.php?sort=1' class='toolbar'>" . _MI_MYLINKS_SMNAME3 . "</a> | <a href='topten.php?sort=3' class='toolbar'>" . _MI_MYLINKS_SMNAME4 . '</a> ]';
482
483
        return $toolbar;
484
    }
485
486
}
487