Passed
Push — master ( 81ba93...c6c854 )
by Michael
03:30
created

class/Utility.php (3 issues)

Labels
1
<?php
2
3
namespace XoopsModules\Smartfaq;
4
5
use XoopsModules\Smartfaq;
6
7
/**
8
 * Class Utility
9
 */
10
class Utility
11
{
12
    use Common\VersionChecks; //checkVerXoops, checkVerPhp Traits
0 ignored issues
show
The trait XoopsModules\Smartfaq\Common\VersionChecks requires some properties which are not provided by XoopsModules\Smartfaq\Utility: $tag_name, $prerelease
Loading history...
13
14
    use Common\ServerStats; // getServerStats Trait
15
16
    use Common\FilesManagement; // Files Management Trait
17
18
    //--------------- Custom module methods -----------------------------
19
20
    /**
21
     * @return mixed|null
22
     */
23
    public static function getModuleInfo()
24
    {
25
        static $smartModule;
26
        if (null === $smartModule) {
27
            global $xoopsModule;
28
            if (null !== $xoopsModule && is_object($xoopsModule) && 'smartfaq' === $xoopsModule->getVar('dirname')) {
29
                $smartModule = $xoopsModule;
30
            } else {
31
                $moduleHandler = xoops_getHandler('module');
32
                $smartModule   = $moduleHandler->getByDirname('smartfaq');
0 ignored issues
show
The method getByDirname() does not exist on XoopsObjectHandler. It seems like you code against a sub-type of XoopsObjectHandler such as XoopsModuleHandler or XoopsPersistableObjectHandler. ( Ignorable by Annotation )

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

32
                /** @scrutinizer ignore-call */ 
33
                $smartModule   = $moduleHandler->getByDirname('smartfaq');
Loading history...
33
            }
34
        }
35
36
        return $smartModule;
37
    }
38
39
    /**
40
     * @return mixed
41
     */
42
    public static function getModuleConfig()
43
    {
44
        static $smartConfig;
45
        if (!$smartConfig) {
46
            global $xoopsModule;
47
            if (null !== $xoopsModule && is_object($xoopsModule) && 'smartfaq' === $xoopsModule->getVar('dirname')) {
48
                global $xoopsModuleConfig;
49
                $smartConfig = $xoopsModuleConfig;
50
            } else {
51
                $smartModule = self::getModuleInfo();
52
                $hModConfig  = xoops_getHandler('config');
53
                $smartConfig = $hModConfig->getConfigsByCat(0, $smartModule->getVar('mid'));
54
            }
55
        }
56
57
        return $smartConfig;
58
    }
59
60
    /**
61
     * @return string
62
     */
63
    public static function getHelpPath()
64
    {
65
        $smartConfig = self::getModuleConfig();
66
        switch ($smartConfig['helppath_select']) {
67
            case 'docs.xoops.org':
68
                return 'http://docs.xoops.org/help/sfaqh/index.htm';
69
                break;
70
            case 'inside':
71
                return XOOPS_URL . '/modules/smartfaq/doc/';
72
                break;
73
            case 'custom':
74
                return $smartConfig['helppath_custom'];
75
                break;
76
        }
77
    }
78
79
    /**
80
     * @param  array $errors
81
     * @return string
82
     */
83
    public static function formatErrors($errors = [])
84
    {
85
        $ret = '';
86
        foreach ($errors as $key => $value) {
87
            $ret .= '<br> - ' . $value;
88
        }
89
90
        return $ret;
91
    }
92
93
    /**
94
     * @param         $categoryObj
95
     * @param  int    $selectedid
96
     * @param  int    $level
97
     * @param  string $ret
98
     * @return string
99
     */
100
    public static function addCategoryOption($categoryObj, $selectedid = 0, $level = 0, $ret = '')
101
    {
102
        // Creating the category handler object
103
        /** @var Smartfaq\CategoryHandler $categoryHandler */
104
        $categoryHandler = Smartfaq\Helper::getInstance()->getHandler('Category');
105
106
        $spaces = '';
107
        for ($j = 0; $j < $level; ++$j) {
108
            $spaces .= '--';
109
        }
110
111
        $ret .= "<option value='" . $categoryObj->categoryid() . "'";
112
        if ($selectedid == $categoryObj->categoryid()) {
113
            $ret .= ' selected';
114
        }
115
        $ret .= '>' . $spaces . $categoryObj->name() . "</option>\n";
116
117
        $subCategoriesObj = &$categoryHandler->getCategories(0, 0, $categoryObj->categoryid());
118
        if (count($subCategoriesObj) > 0) {
119
            ++$level;
120
            foreach ($subCategoriesObj as $catID => $subCategoryObj) {
121
                $ret .= self::addCategoryOption($subCategoryObj, $selectedid, $level);
122
            }
123
        }
124
125
        return $ret;
126
    }
127
128
    /**
129
     * @param  int  $selectedid
130
     * @param  int  $parentcategory
131
     * @param  bool $allCatOption
132
     * @return string
133
     */
134
    public static function createCategorySelect($selectedid = 0, $parentcategory = 0, $allCatOption = true)
135
    {
136
        $ret = '' . _MB_SF_SELECTCAT . "&nbsp;<select name='options[]'>";
137
        if ($allCatOption) {
138
            $ret .= "<option value='0'";
139
            $ret .= '>' . _MB_SF_ALLCAT . "</option>\n";
140
        }
141
142
        // Creating the category handler object
143
        $categoryHandler = Smartfaq\Helper::getInstance()->getHandler('Category');
144
145
        // Creating category objects
146
        $categoriesObj = $categoryHandler->getCategories(0, 0, $parentcategory);
147
148
        if (count($categoriesObj) > 0) {
149
            foreach ($categoriesObj as $catID => $categoryObj) {
150
                $ret .= self::addCategoryOption($categoryObj, $selectedid);
151
            }
152
        }
153
        $ret .= "</select>\n";
154
155
        return $ret;
156
    }
157
158
    /**
159
     * @return array
160
     */
161
    public static function getStatusArray()
162
    {
163
        $result = [
164
            '1' => _AM_SF_STATUS1,
165
            '2' => _AM_SF_STATUS2,
166
            '3' => _AM_SF_STATUS3,
167
            '4' => _AM_SF_STATUS4,
168
            '5' => _AM_SF_STATUS5,
169
            '6' => _AM_SF_STATUS6,
170
            '7' => _AM_SF_STATUS7,
171
            '8' => _AM_SF_STATUS8,
172
        ];
173
174
        return $result;
175
    }
176
177
    /**
178
     * @return bool
179
     */
180
    public static function hasModerator()
181
    {
182
        global $xoopsUser;
183
184
        if (!$xoopsUser) {
185
            $result = false;
186
        } else {
187
            /** @var Smartfaq\PermissionHandler $smartPermHandler */
188
            $smartPermHandler = Smartfaq\Helper::getInstance()->getHandler('Permission');
189
190
            $categories = $smartPermHandler->getPermissions('moderation');
191
            if (0 == count($categories)) {
192
                $result = false;
193
            } else {
194
                $result = true;
195
            }
196
        }
197
198
        return $result;
199
    }
200
201
    /**
202
     * @return string
203
     */
204
    public static function modFooter()
205
    {
206
        $smartModule = self::getModuleInfo();
207
208
        $modfootertxt = 'Module ' . $smartModule->getInfo('name') . ' - Version ' . $smartModule->getInfo('version') . '';
209
210
        $modfooter = "<a href='" . $smartModule->getInfo('support_site_url') . "' target='_blank'><img src='" . XOOPS_URL . "/modules/smartfaq/assets/images/sfcssbutton.gif' title='" . $modfootertxt . "' alt='" . $modfootertxt . "'></a>";
211
212
        return $modfooter;
213
    }
214
215
    /**
216
     * Checks if a user is admin of Smartfaq
217
     *
218
     * self::userIsAdmin()
219
     *
220
     * @return bool : array with userids and uname
221
     */
222
    public static function userIsAdmin()
223
    {
224
        global $xoopsUser;
225
226
        $result = false;
227
228
        $smartModule = self::getModuleInfo();
229
        $module_id   = $smartModule->getVar('mid');
230
231
        if (!empty($xoopsUser)) {
232
            $groups = &$xoopsUser->getGroups();
233
            $result = in_array(XOOPS_GROUP_ADMIN, $groups) || $xoopsUser->isAdmin($module_id);
234
        }
235
236
        return $result;
237
    }
238
239
    /**
240
     * Checks if a user has access to a selected faq. If no item permissions are
241
     * set, access permission is denied. The user needs to have necessary category
242
     * permission as well.
243
     *
244
     * self::faqAccessGranted()
245
     *
246
     * @param $faqObj
247
     * @return int : -1 if no access, 0 if partialview and 1 if full access
248
     * @internal param int $faqid : faqid on which we are setting permissions
249
     * @internal param $integer $ categoryid : categoryid of the faq
250
     */
251
252
    // TODO : Move this function to Smartfaq\Faq class
253
    public static function faqAccessGranted($faqObj)
254
    {
255
        global $xoopsUser;
256
257
        if (self::userIsAdmin()) {
258
            $result = 1;
259
        } else {
260
            $result = -1;
261
262
            $groups = $xoopsUser ? $xoopsUser->getGroups() : XOOPS_GROUP_ANONYMOUS;
263
264
            $grouppermHandler = xoops_getHandler('groupperm');
265
            $smartModule      = self::getModuleInfo();
266
            $module_id        = $smartModule->getVar('mid');
267
268
            // Do we have access to the parent category
269
            if ($grouppermHandler->checkRight('category_read', $faqObj->categoryid(), $groups, $module_id)) {
270
                // Do we have access to the faq?
271
                if ($grouppermHandler->checkRight('item_read', $faqObj->faqid(), $groups, $module_id)) {
272
                    $result = 1;
273
                } else { // No we don't !
274
                    // Check to see if we have partial view access
275
                    if (!is_object($xoopsUser) && $faqObj->partialView()) {
276
                        return 0;
277
                    }
278
                }
279
            } else { // No we don't !
280
                $result = false;
281
            }
282
        }
283
284
        return $result;
285
    }
286
287
    /**
288
     * Override FAQs permissions of a category by the category read permissions
289
     *
290
     *   self::overrideFaqsPermissions()
291
     *
292
     * @param  array $groups     : group with granted permission
293
     * @param  int   $categoryid :
294
     * @return bool|array : TRUE if the no errors occured
295
     */
296
    public static function overrideFaqsPermissions($groups, $categoryid)
297
    {
298
        global $xoopsDB;
299
300
        $result      = true;
301
        $smartModule = self::getModuleInfo();
302
        $module_id   = $smartModule->getVar('mid');
303
304
        $grouppermHandler = xoops_getHandler('groupperm');
305
306
        $sql    = 'SELECT faqid FROM ' . $xoopsDB->prefix('smartfaq_faq') . " WHERE categoryid = '$categoryid' ";
307
        $result = $xoopsDB->queryF($sql);
308
309
        if ($GLOBALS['xoopsDB']->getRowsNum($result) > 0) {
310
            while (list($faqid) = $xoopsDB->fetchRow($result)) {
311
                // First, if the permissions are already there, delete them
312
                $grouppermHandler->deleteByModule($module_id, 'item_read', $faqid);
313
                // Save the new permissions
314
                if (count($groups) > 0) {
315
                    foreach ($groups as $group_id) {
316
                        $grouppermHandler->addRight('item_read', $faqid, $group_id, $module_id);
317
                    }
318
                }
319
            }
320
        }
321
322
        return $result;
323
    }
324
325
    /**
326
     * Saves permissions for the selected faq
327
     *
328
     *   self::saveItemPermissions()
329
     *
330
     * @param  array $groups : group with granted permission
331
     * @param  int   $itemID : faqid on which we are setting permissions
332
     * @return bool : TRUE if the no errors occured
333
     */
334
    public static function saveItemPermissions($groups, $itemID)
335
    {
336
        $result      = true;
337
        $smartModule = self::getModuleInfo();
338
        $module_id   = $smartModule->getVar('mid');
339
340
        $grouppermHandler = xoops_getHandler('groupperm');
341
        // First, if the permissions are already there, delete them
342
        $grouppermHandler->deleteByModule($module_id, 'item_read', $itemID);
343
        // Save the new permissions
344
        if (count($groups) > 0) {
345
            foreach ($groups as $group_id) {
346
                $grouppermHandler->addRight('item_read', $itemID, $group_id, $module_id);
347
            }
348
        }
349
350
        return $result;
351
    }
352
353
    /**
354
     * Saves permissions for the selected category
355
     *
356
     *   self::saveCategoryPermissions()
357
     *
358
     * @param  array  $groups     : group with granted permission
359
     * @param  int    $categoryid : categoryid on which we are setting permissions
360
     * @param  string $perm_name  : name of the permission
361
     * @return bool : TRUE if the no errors occured
362
     */
363
    public static function saveCategoryPermissions($groups, $categoryid, $perm_name)
364
    {
365
        $result      = true;
366
        $smartModule = self::getModuleInfo();
367
        $module_id   = $smartModule->getVar('mid');
368
369
        $grouppermHandler = xoops_getHandler('groupperm');
370
        // First, if the permissions are already there, delete them
371
        $grouppermHandler->deleteByModule($module_id, $perm_name, $categoryid);
372
        // Save the new permissions
373
        if (count($groups) > 0) {
374
            foreach ($groups as $group_id) {
375
                $grouppermHandler->addRight($perm_name, $categoryid, $group_id, $module_id);
376
            }
377
        }
378
379
        return $result;
380
    }
381
382
    /**
383
     * Saves permissions for the selected category
384
     *
385
     *   self::saveModerators()
386
     *
387
     * @param  array $moderators : moderators uids
388
     * @param  int   $categoryid : categoryid on which we are setting permissions
389
     * @return bool : TRUE if the no errors occured
390
     */
391
    public static function saveModerators($moderators, $categoryid)
392
    {
393
        $result      = true;
394
        $smartModule = self::getModuleInfo();
395
        $module_id   = $smartModule->getVar('mid');
396
397
        $grouppermHandler = xoops_getHandler('groupperm');
398
        // First, if the permissions are already there, delete them
399
        $grouppermHandler->deleteByModule($module_id, 'category_moderation', $categoryid);
400
        // Save the new permissions
401
        if (count($moderators) > 0) {
402
            foreach ($moderators as $uid) {
403
                $grouppermHandler->addRight('category_moderation', $categoryid, $uid, $module_id);
404
            }
405
        }
406
407
        return $result;
408
    }
409
410
    /**
411
     * @param  int $faqid
412
     * @return array
413
     */
414
    public static function retrieveFaqByID($faqid = 0)
415
    {
416
        $ret = [];
417
        global $xoopsDB;
418
419
        $result = $xoopsDB->queryF('SELECT * FROM ' . $xoopsDB->prefix('smartfaq_faq') . " WHERE faqid = '$faqid'");
420
        $ret    = $xoopsDB->fetchArray($result);
421
422
        return $ret;
423
    }
424
425
    /**
426
     * self::getAdminLinks()
427
     *
428
     * @param  int  $faqid
429
     * @param  bool $open
430
     * @return string
431
     */
432
433
    // TODO : Move this to the Smartfaq\Faq class
434
    public static function getAdminLinks($faqid = 0, $open = false)
435
    {
436
        global $xoopsUser, $xoopsModule, $xoopsConfig;
437
        /** @var Smartfaq\Helper $helper */
438
        $helper = Smartfaq\Helper::getInstance();
439
440
        $adminLinks = '';
441
        $modulePath = XOOPS_URL . '/modules/' . $xoopsModule->dirname() . '/';
442
        $page       = $open ? 'question.php' : 'faq.php';
443
        if ($xoopsUser && $xoopsUser->isAdmin($xoopsModule->getVar('mid'))) {
444
            // Edit button
445
            $adminLinks .= "<a href='" . $modulePath . "admin/$page?op=mod&amp;faqid=" . $faqid . "'><img src='" . $modulePath . "assets/images/links/edit.gif'" . " title='" . _MD_SF_EDIT . "' alt='" . _MD_SF_EDIT . "'></a>";
446
            $adminLinks .= ' ';
447
            // Delete button
448
            $adminLinks .= "<a href='" . $modulePath . "admin/$page?op=del&amp;faqid=" . $faqid . "'><img src='" . $modulePath . "assets/images/links/delete.gif'" . " title='" . _MD_SF_DELETE . "' alt='" . _MD_SF_DELETE . "'></a>";
449
            $adminLinks .= ' ';
450
        }
451
        // Print button
452
        $adminLinks .= "<a href='" . $modulePath . 'print.php?faqid=' . $faqid . "'><img src='" . $modulePath . "assets/images/links/print.gif' title='" . _MD_SF_PRINT . "' alt='" . _MD_SF_PRINT . "'></a>";
453
        $adminLinks .= ' ';
454
        // Email button
455
        $maillink   = 'mailto:?subject=' . sprintf(_MD_SF_INTARTICLE, $xoopsConfig['sitename']) . '&amp;body=' . sprintf(_MD_SF_INTARTFOUND, $xoopsConfig['sitename']) . ':  ' . $modulePath . 'faq.php?faqid=' . $faqid;
456
        $adminLinks .= '<a href="' . $maillink . "\"><img src='" . $modulePath . "assets/images/links/friend.gif' title='" . _MD_SF_MAIL . "' alt='" . _MD_SF_MAIL . "'></a>";
457
        $adminLinks .= ' ';
458
        // Submit New Answer button
459
        if ($helper->getConfig('allownewanswer') && (is_object($xoopsUser) || $helper->getConfig('anonpost'))) {
460
            $adminLinks .= "<a href='" . $modulePath . 'answer.php?faqid=' . $faqid . "'><img src='" . $modulePath . "assets/images/links/newanswer.gif' title='" . _MD_SF_SUBMITANSWER . "' alt='" . _MD_SF_SUBMITANSWER . "'></a>";
461
            $adminLinks .= ' ';
462
        }
463
464
        return $adminLinks;
465
    }
466
467
    /**
468
     * self::getLinkedUnameFromId()
469
     *
470
     * @param  int   $userid Userid of poster etc
471
     * @param  int   $name   :  0 Use Usenamer 1 Use realname
472
     * @param  array $users
473
     * @return string
474
     */
475
    public static function getLinkedUnameFromId($userid = 0, $name = 0, $users = [])
476
    {
477
        if (!is_numeric($userid)) {
0 ignored issues
show
The condition is_numeric($userid) is always true.
Loading history...
478
            return $userid;
479
        }
480
481
        $userid = (int)$userid;
482
        if ($userid > 0) {
483
            if ($users == []) {
484
                //fetching users
485
                $memberHandler = xoops_getHandler('member');
486
                $user          = $memberHandler->getUser($userid);
487
            } else {
488
                if (!isset($users[$userid])) {
489
                    return $GLOBALS['xoopsConfig']['anonymous'];
490
                }
491
                $user = &$users[$userid];
492
            }
493
494
            if (is_object($user)) {
495
                $ts       = \MyTextSanitizer::getInstance();
496
                $username = $user->getVar('uname');
497
                $fullname = '';
498
499
                $fullname2 = $user->getVar('name');
500
501
                if ($name && !empty($fullname2)) {
502
                    $fullname = $user->getVar('name');
503
                }
504
                if (!empty($fullname)) {
505
                    $linkeduser = "$fullname [<a href='" . XOOPS_URL . '/userinfo.php?uid=' . $userid . "'>" . $ts->htmlSpecialChars($username) . '</a>]';
506
                } else {
507
                    $linkeduser = "<a href='" . XOOPS_URL . '/userinfo.php?uid=' . $userid . "'>" . ucwords($ts->htmlSpecialChars($username)) . '</a>';
508
                }
509
510
                return $linkeduser;
511
            }
512
        }
513
514
        return $GLOBALS['xoopsConfig']['anonymous'];
515
    }
516
517
    /**
518
     * @param  string $url
519
     * @return mixed|string
520
     */
521
    public static function getXoopslink($url = '')
522
    {
523
        $xurl = $url;
524
        if (mb_strlen($xurl) > 0) {
525
            if ($xurl[0] = '/') {
526
                $xurl = str_replace('/', '', $xurl);
527
            }
528
            $xurl = str_replace('{SITE_URL}', XOOPS_URL, $xurl);
529
        }
530
531
        //        $xurl = $url;
532
533
        return $xurl;
534
    }
535
536
    /**
537
     * @param string $tablename
538
     * @param string $iconname
539
     */
540
    public static function collapsableBar($tablename = '', $iconname = '')
541
    {
542
        ?>
543
        <script type="text/javascript"><!--
544
            function goto_URL(object) {
545
                window.location.href = object.options[object.selectedIndex].value;
546
            }
547
548
            function toggle(id) {
549
                if (document.getElementById) {
550
                    obj = document.getElementById(id);
551
                }
552
                if (document.all) {
553
                    obj = document.all[id];
554
                }
555
                if (document.layers) {
556
                    obj = document.layers[id];
557
                }
558
                if (obj) {
559
                    if (obj.style.display === "none") {
560
                        obj.style.display = "";
561
                    } else {
562
                        obj.style.display = "none";
563
                    }
564
                }
565
566
                return false;
567
            }
568
569
            var iconClose = new Image();
570
            iconClose.src = '../assets/images/icon/close12.gif';
571
            var iconOpen = new Image();
572
            iconOpen.src = '../assets/images/icon/open12.gif';
573
574
            function toggleIcon(iconName) {
575
                if (document.images[iconName].src == window.iconOpen.src) {
576
                    document.images[iconName].src = window.iconClose.src;
577
                }
578
                elseif(document.images[iconName].src == window.iconClose.src)
579
                {
580
                    document.images[iconName].src = window.iconOpen.src;
581
                }
582
583
                return;
584
            }
585
586
            //-->
587
        </script>
588
        <?php
589
        echo "<h3 style=\"color: #2F5376; margin: 6px 0 0 0; \"><a href='#' onClick=\"toggle('" . $tablename . "'); toggleIcon('" . $iconname . "');\">";
590
    }
591
}
592