CategoryHandler::getTreeWithChildren()   A
last analyzed

Complexity

Conditions 4
Paths 6

Size

Total Lines 36
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 15
nc 6
nop 0
dl 0
loc 36
rs 9.7666
c 0
b 0
f 0
1
<?php
2
3
namespace XoopsModules\Extgallery;
4
5
/**
6
 * ExtGallery Class Manager
7
 *
8
 * You may not change or alter any portion of this comment or credits
9
 * of supporting developers from this source code or any supporting source code
10
 * which is considered copyrighted (c) material of the original comment or credit authors.
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
14
 *
15
 * @copyright   {@link https://xoops.org/ XOOPS Project}
16
 * @license     GNU GPL 2 (https://www.gnu.org/licenses/old-licenses/gpl-2.0.html)
17
 * @author      Zoullou (http://www.zoullou.net)
18
 * @package     ExtGallery
19
 */
20
21
use XoopsModules\Extgallery;
22
23
/**
24
 * Class Extgallery\CategoryHandler
25
 */
26
class CategoryHandler extends Extgallery\PersistableObjectHandler
27
{
28
    //var $_nestedTree;
29
    public $_photoHandler;
30
31
    /**
32
     * @param \XoopsDatabase|null $db
33
     * @param                     $type
34
     */
35
    public function __construct(\XoopsDatabase $db, $type)
36
    {
37
        parent::__construct($db, 'extgallery_' . $type . 'cat', \ucfirst($type) . 'Category', 'cat_id');
38
        //$this->_nestedTree = new NestedTree($db, 'extgallery_'.$type.'cat', 'cat_id', 'cat_pid', 'cat_id');
39
        $this->_photoHandler = Extgallery\Helper::getInstance()->getHandler(\ucfirst($type) . 'Photo');
40
    }
41
42
    /**
43
     * @param $data
44
     *
45
     * @return bool
46
     */
47
    public function createCat($data)
48
    {
49
        $cat = $this->create();
50
        $cat->setVars($data);
51
52
        if (!$this->hasValidParent($cat)) {
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->hasValidParent($cat) targeting XoopsModules\Extgallery\...ndler::hasValidParent() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
Unused Code introduced by
The call to XoopsModules\Extgallery\...ndler::hasValidParent() has too many arguments starting with $cat. ( Ignorable by Annotation )

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

52
        if (!$this->/** @scrutinizer ignore-call */ hasValidParent($cat)) {

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
53
            return false;
54
        }
55
56
        $this->insert($cat, true);
57
        $this->rebuild();
58
59
        return true;
60
    }
61
62
    /**
63
     * @param $data
64
     *
65
     * @return bool
66
     */
67
    public function modifyCat($data)
68
    {
69
        $cat = $this->get($data['cat_id']);
70
        $cat->setVars($data);
71
72
        if (!$this->hasValidParent($cat)) {
0 ignored issues
show
Bug introduced by
Are you sure the usage of $this->hasValidParent($cat) targeting XoopsModules\Extgallery\...ndler::hasValidParent() seems to always return null.

This check looks for function or method calls that always return null and whose return value is used.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
if ($a->getObject()) {

The method getObject() can return nothing but null, so it makes no sense to use the return value.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
Unused Code introduced by
The call to XoopsModules\Extgallery\...ndler::hasValidParent() has too many arguments starting with $cat. ( Ignorable by Annotation )

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

72
        if (!$this->/** @scrutinizer ignore-call */ hasValidParent($cat)) {

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
73
            return false;
74
        }
75
        $this->insert($cat, true);
76
77
        // Rebluid the tree only if the structure is modified
78
        if (isset($data['cat_pid']) || isset($data['nlevel']) || isset($data['nright']) || isset($data['nleft'])) {
79
            $this->rebuild();
80
        }
81
82
        return '';
83
    }
84
85
    /**
86
     * @param int $catId
87
     */
88
    public function deleteCat($catId)
89
    {
90
        $children = $this->getDescendants($catId, false, true);
91
        foreach ($children as $child) {
92
            $this->_photoHandler->deletePhotoByCat($child->getVar('cat_id'));
0 ignored issues
show
Bug introduced by
The method deletePhotoByCat() does not exist on XoopsObjectHandler. Did you maybe mean delete()? ( Ignorable by Annotation )

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

92
            $this->_photoHandler->/** @scrutinizer ignore-call */ 
93
                                  deletePhotoByCat($child->getVar('cat_id'));

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
93
            $this->deleteCat($child->getVar('cat_id'));
94
        }
95
        $this->_photoHandler->deletePhotoByCat($catId);
96
        $this->deleteById($catId);
97
    }
98
99
    /**
100
     * @param int    $id
101
     * @param bool   $includeSelf
102
     * @param bool   $childrenOnly
103
     * @param bool   $withRestrict
104
     * @param string $permType
105
     *
106
     * @return array
107
     */
108
    public function getDescendants(
109
        $id = 0,
110
        $includeSelf = false,
111
        $childrenOnly = false,
112
        $withRestrict = true,
113
        $permType = 'public_access'
114
    ) {
115
        $cat = $this->get($id);
116
117
        $nleft     = $cat->getVar('nleft');
118
        $nright    = $cat->getVar('nright');
119
        $parent_id = $cat->getVar('cat_id');
120
121
        $criteria = new \CriteriaCompo();
122
123
        if ($childrenOnly) {
124
            $criteria->add(new \Criteria('cat_pid', $parent_id), 'OR');
0 ignored issues
show
Bug introduced by
It seems like $parent_id can also be of type array and array; however, parameter $value of Criteria::__construct() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

124
            $criteria->add(new \Criteria('cat_pid', /** @scrutinizer ignore-type */ $parent_id), 'OR');
Loading history...
125
            if ($includeSelf) {
126
                $criteria->add(new \Criteria('cat_id', $parent_id));
127
                //$query = sprintf('select * from %s where %s = %d or %s = %d order by nleft', $this->table, $this->fields['id'], $parent_id, $this->fields['parent'], $parent_id);
128
            }/* else {
129
                //$query = sprintf('select * from %s where %s = %d order by nleft', $this->table, $this->fields['parent'], $parent_id);
130
            }*/
131
        } else {
132
            if ($nleft > 0 && $includeSelf) {
133
                $criteria->add(new \Criteria('nleft', $nleft, '>='));
134
                $criteria->add(new \Criteria('nright', $nright, '<='));
135
                //$query = sprintf('select * from %s where nleft >= %d and nright <= %d order by nleft', $this->table, $nleft, $nright);
136
            } else {
137
                if ($nleft > 0) {
138
                    $criteria->add(new \Criteria('nleft', $nleft, '>'));
139
                    $criteria->add(new \Criteria('nright', $nright, '<'));
140
                    //$query = sprintf('select * from %s where nleft > %d and nright < %d order by nleft', $this->table, $nleft, $nright);
141
                }/* else {
142
                $query = sprintf('select * from %s order by nleft', $this->table);
143
                }*/
144
            }
145
        }
146
        if ($withRestrict) {
147
            $temp = $this->getCatRestrictCriteria($permType);
148
            if (false !== $temp) {
149
                $criteria->add($temp);
150
            }
151
            $temp = $this->getCatRestrictCriteria('public_displayed');
152
            if (false !== $temp) {
153
                $criteria->add($temp);
154
            }
155
        }
156
        $criteria->setSort('nleft');
157
158
        return $this->getObjects($criteria);
159
    }
160
161
    /**
162
     * @param int $id
163
     * @return mixed|null
164
     */
165
    public function getCat($id = 0)
166
    {
167
        $criteria = new \CriteriaCompo();
168
        $temp     = $this->getCatRestrictCriteria('public_displayed');
169
        if (false !== $temp) {
170
            $criteria->add($temp);
171
        }
172
173
        $criteria->add(new \Criteria('cat_id', $id));
174
        $ret = $this->getObjects($criteria);
175
176
        if (\count($ret) > 0) {
177
            return $ret[0];
178
        }
179
180
        return null;
181
    }
182
183
    public function hasValidParent()
184
    {
185
        exit('hasValidParent() method must be defined on sub classes');
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...
186
    }
187
188
    /**
189
     * @param $cat
190
     *
191
     * @return bool
192
     */
193
    public function _isAlbum($cat)
194
    {
195
        $nbPhoto = $this->nbPhoto($cat);
196
197
        return 0 != $nbPhoto;
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing $nbPhoto of type mixed|null to 0; this is ambiguous as not only 0 == 0 is true, but null == 0 is true, too. Consider using a strict comparison ===.
Loading history...
198
    }
199
200
    /**
201
     * @param Extgallery\Category $cat
202
     *
203
     * @return mixed
204
     */
205
    public function nbPhoto(&$cat)
206
    {
207
        /** @var Extgallery\CategoryHandler $this ->_photoHandler */
208
        return $this->_photoHandler->nbPhoto($cat);
0 ignored issues
show
Bug introduced by
The method nbPhoto() does not exist on XoopsObjectHandler. It seems like you code against a sub-type of XoopsObjectHandler such as XoopsPersistableObjectHandler. ( Ignorable by Annotation )

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

208
        return $this->_photoHandler->/** @scrutinizer ignore-call */ nbPhoto($cat);
Loading history...
209
    }
210
211
    /**
212
     * @param int  $id
213
     * @param bool $includeSelf
214
     *
215
     * @return array
216
     */
217
    public function getPath($id = 0, $includeSelf = false)
218
    {
219
        $cat = $this->get($id);
220
        if (null === $cat) {
221
            return [];
222
        }
223
224
        $criteria = new \CriteriaCompo();
225
        if ($includeSelf) {
226
            $criteria->add(new \Criteria('nleft', $cat->getVar('nleft'), '<='));
0 ignored issues
show
Bug introduced by
It seems like $cat->getVar('nleft') can also be of type array and array; however, parameter $value of Criteria::__construct() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

226
            $criteria->add(new \Criteria('nleft', /** @scrutinizer ignore-type */ $cat->getVar('nleft'), '<='));
Loading history...
227
            $criteria->add(new \Criteria('nright', $cat->getVar('nright'), '>='));
228
            //$query = sprintf('select * from %s where nleft <= %d and nright >= %d order by nlevel', $this->table, $node['nleft'], $node['nright']);
229
        } else {
230
            $criteria->add(new \Criteria('nleft', $cat->getVar('nleft'), '<'));
231
            $criteria->add(new \Criteria('nright', $cat->getVar('nright'), '>'));
232
            //$query = sprintf('select * from %s where nleft < %d and nright > %d order by nlevel', $this->table, $node['nleft'], $node['nright']);
233
        }
234
        $temp = $this->getCatRestrictCriteria();
235
        if (\is_object($temp)) {
236
            $criteria->add($temp);
237
        }
238
        $temp2 = $this->getCatRestrictCriteria('public_displayed');
239
        if (\is_object($temp2)) {
240
            $criteria->add($temp2);
241
        }
242
        $criteria->setSort('nlevel');
243
244
        return $this->getObjects($criteria);
245
    }
246
247
    /**
248
     * @return array
249
     */
250
    public function getTree()
251
    {
252
        return $this->getDescendants(0, false, false, false);
253
    }
254
255
    /**
256
     * @param int  $id
257
     * @param bool $includeSelf
258
     *
259
     * @return array
260
     */
261
    public function getChildren($id = 0, $includeSelf = false)
262
    {
263
        return $this->getDescendants($id, $includeSelf, true);
264
    }
265
266
    /**
267
     * @param int $id
268
     *
269
     * @return int
270
     */
271
    public function nbAlbum($id = 0)
272
    {
273
        $criteria = new \CriteriaCompo(new \Criteria('nright - nleft', 1));
274
        //$query = sprintf('select count(*) as num_leef from %s where nright - nleft = 1', $this->table);
275
        if (0 != $id) {
276
            $cat = $this->get($id);
277
            $criteria->add(new \Criteria('nleft', $cat->getVar('nleft'), '>'));
0 ignored issues
show
Bug introduced by
It seems like $cat->getVar('nleft') can also be of type array and array; however, parameter $value of Criteria::__construct() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

277
            $criteria->add(new \Criteria('nleft', /** @scrutinizer ignore-type */ $cat->getVar('nleft'), '>'));
Loading history...
278
            $criteria->add(new \Criteria('nright', $cat->getVar('nright'), '<'));
279
            //$query .= sprintf(' AND nleft > %d AND nright < %d', $node['nleft'], $node['nright']);
280
        }
281
282
        return $this->getCount($criteria);
283
    }
284
285
    /**
286
     * @param        $name
287
     * @param        $selectMode
288
     * @param bool   $addEmpty
289
     * @param int    $selected
290
     * @param string $extra
291
     * @param bool   $displayWeight
292
     * @param string $permType
293
     *
294
     * @return string
295
     */
296
    public function getSelect(
297
        $name,
298
        $selectMode,
299
        $addEmpty = false,
300
        $selected = 0,
301
        $extra = '',
302
        $displayWeight = false,
303
        $permType = 'public_access'
304
    ) {
305
        $cats = $this->getDescendants(0, false, false, true, $permType);
306
307
        return $this->makeSelect($cats, $name, $selectMode, $addEmpty, $selected, $extra, $displayWeight);
308
    }
309
310
    /**
311
     * @param        $name
312
     * @param bool   $addEmpty
313
     * @param int    $selected
314
     * @param string $extra
315
     * @param string $permType
316
     *
317
     * @return string
318
     */
319
    public function getLeafSelect($name, $addEmpty = false, $selected = 0, $extra = '', $permType = 'public_access')
320
    {
321
        return $this->getSelect($name, 'node', $addEmpty, $selected, $extra, false, $permType);
322
    }
323
324
    /**
325
     * @param        $name
326
     * @param bool   $addEmpty
327
     * @param int    $selected
328
     * @param string $extra
329
     *
330
     * @return string
331
     */
332
    public function getNodeSelect($name, $addEmpty = false, $selected = 0, $extra = '')
333
    {
334
        return $this->getSelect($name, 'leaf', $addEmpty, $selected, $extra);
335
    }
336
337
    /**
338
     * @param array  $cats
339
     * @param string $name
340
     * @param string $selectMode
341
     * @param        $addEmpty
342
     * @param        $selected
343
     * @param        $extra
344
     * @param        $displayWeight
345
     *
346
     * @return string
347
     */
348
    public function makeSelect($cats, $name, $selectMode, $addEmpty, $selected, $extra, $displayWeight)
349
    {
350
        $ret = '<select name="' . $name . '" id="' . $name . '"' . $extra . '>';
351
        if ($addEmpty) {
352
            $ret .= '<option value="0">-----</option>';
353
        }
354
        /** @var Extgallery\Category $cat */
355
        foreach ($cats as $cat) {
356
            $disableOption = '';
357
            if ('node' === $selectMode && (1 != $cat->getVar('nright') - $cat->getVar('nleft'))) {
358
                // If the brownser is IE the parent cat isn't displayed
359
                //                if (preg_match('`MSIE`', $_SERVER['HTTP_USER_AGENT'])) {
360
                if (false !== mb_strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE')) {
361
                    continue;
362
                }
363
                $disableOption = ' disabled="disabled"';
364
            } elseif ('leaf' === $selectMode && (1 == $cat->getVar('cat_isalbum'))) {
365
                continue;
366
            }
367
368
            $selectedOption = '';
369
            if ($cat->getVar('cat_id') == $selected) {
370
                $selectedOption = ' selected';
371
            }
372
373
            $prefix = '';
374
            for ($i = 0; $i < $cat->getVar('nlevel') - 1; ++$i) {
375
                $prefix .= '--';
376
            }
377
            $catName = $prefix . ' ' . $cat->getVar('cat_name');
378
            if ($displayWeight) {
379
                $catName .= ' [' . $cat->getVar('cat_weight') . ']';
380
            }
381
382
            $ret .= '<option value="' . $cat->getVar('cat_id') . '"' . $selectedOption . '' . $disableOption . '>' . $catName . '</option>';
383
        }
384
        $ret .= '</select>';
385
386
        return $ret;
387
    }
388
389
    /**
390
     * @param array $selected
391
     *
392
     * @return string
393
     */
394
    public function getBlockSelect($selected = [])
395
    {
396
        $cats           = $this->getDescendants();
397
        $ret            = '<select name="options[]" multiple="multiple">';
398
        $selectedOption = '';
399
        $allCat         = \in_array(0, $selected);
400
        if ($allCat) {
401
            $selectedOption = ' selected';
402
        }
403
        $ret .= '<option value="0"' . $selectedOption . '>' . \_MB_EXTGALLERY_ALL_CATEGORIES . '</option>';
404
        foreach ($cats as $cat) {
405
            $prefix = '';
406
            for ($i = 0; $i < $cat->getVar('nlevel') - 1; ++$i) {
407
                $prefix .= '-';
408
            }
409
            $selectedOption = '';
410
            $disableOption  = '';
411
412
            if (!$allCat && \in_array($cat->getVar('cat_id'), $selected)) {
413
                $selectedOption = ' selected';
414
            }
415
416
            if (1 != $cat->getVar('nright') - $cat->getVar('nleft')) {
417
                $disableOption = ' disabled="disabled"';
418
            }
419
420
            $ret .= '<option value="' . $cat->getVar('cat_id') . '"' . $selectedOption . '' . $disableOption . '>' . $prefix . ' ' . $cat->getVar('cat_name') . '</option>';
421
        }
422
        $ret .= '</select>';
423
424
        return $ret;
425
    }
426
427
    /**
428
     * @return array
429
     */
430
    public function getTreeWithChildren()
431
    {
432
        $criteria = new \CriteriaCompo();
433
        $criteria->setSort('cat_weight, cat_name');
434
        //$query = sprintf('select * from %s order by %s', $this->table, $this->fields['sort']);
435
436
        //$result = $this->db->query($query);
437
        $categories = $this->getObjects($criteria, false, false);
438
439
        // create a root node to hold child data about first level items
440
        $root             = [];
441
        $root['cat_id']   = 0;
442
        $root['children'] = [];
443
444
        $arr = [
445
            $root,
446
        ];
447
448
        // populate the array and create an empty children array
449
        /*while (false !== ($row = $this->db->fetchArray($result))) {
450
            $arr[$row[$this->fields['id']]] = $row;
451
            $arr[$row[$this->fields['id']]]['children'] = array ();
452
        }*/
453
        foreach ($categories as $row) {
454
            $arr[$row['cat_id']]             = $row;
455
            $arr[$row['cat_id']]['children'] = [];
456
        }
457
458
        // now process the array and build the child data
459
        foreach ($arr as $id => $row) {
460
            if (isset($row['cat_pid'])) {
461
                $arr[$row['cat_pid']]['children'][$id] = $id;
462
            }
463
        }
464
465
        return $arr;
466
    }
467
468
    /**
469
     * Rebuilds the tree data and saves it to the database
470
     */
471
    public function rebuild()
472
    {
473
        $data = $this->getTreeWithChildren();
474
475
        $n     = 0; // need a variable to hold the running n tally
476
        $level = 0; // need a variable to hold the running level tally
0 ignored issues
show
Unused Code introduced by
The assignment to $level is dead and can be removed.
Loading history...
477
478
        // invoke the recursive function. Start it processing
479
        // on the fake "root node" generated in getTreeWithChildren().
480
        // because this node doesn't really exist in the database, we
481
        // give it an initial nleft value of 0 and an nlevel of 0.
482
        $this->_generateTreeData($data, 0, 0, $n);
483
        //echo "<pre>";print_r($data);echo "</pre>";
484
        // at this point the root node will have nleft of 0, nlevel of 0
485
        // and nright of (tree size * 2 + 1)
486
487
        // Errase category and photo counter
488
        $query = \sprintf('UPDATE `%s` SET cat_nb_album = 0, cat_nb_photo = 0;', $this->table);
489
        $this->db->queryF($query);
490
491
        foreach ($data as $id => $row) {
492
            // skip the root node
493
            if (0 == $id) {
494
                continue;
495
            }
496
497
            // Update the photo number
498
            if (1 == $row['nright'] - $row['nleft']) {
499
                // Get the number of photo in this album
500
                $criteria = new \CriteriaCompo();
501
                $criteria->add(new \Criteria('cat_id', $id));
502
                $criteria->add(new \Criteria('photo_approved', 1));
503
                /** @var Extgallery\CategoryHandler $this ->_photoHandler */
504
                $nbPhoto = $this->_photoHandler->getCount($criteria);
0 ignored issues
show
Bug introduced by
The method getCount() does not exist on XoopsObjectHandler. It seems like you code against a sub-type of said class. However, the method does not exist in XoopsGroupHandler or XoopsConfigCategoryHandler or XoopsRankHandler or XoopsConfigOptionHandler or XoopsBlockHandler or XoopsImageSetHandler. Are you sure you never get one of those? ( Ignorable by Annotation )

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

504
                /** @scrutinizer ignore-call */ 
505
                $nbPhoto = $this->_photoHandler->getCount($criteria);
Loading history...
505
506
                // Update all parent of this album
507
                $upNbAlbum = '';
508
                if (0 != $nbPhoto) {
509
                    $upNbAlbum = 'cat_nb_album = cat_nb_album + 1, ';
510
                }
511
                $sql   = 'UPDATE `%s` SET ' . $upNbAlbum . 'cat_nb_photo = cat_nb_photo + %d WHERE nleft < %d AND nright > %d;';
512
                $query = \sprintf($sql, $this->table, $nbPhoto, $row['nleft'], $row['nright']);
513
                $this->db->queryF($query);
514
515
                // Update this album if needed
516
                if (0 != $nbPhoto) {
517
                    $sql   = 'UPDATE `%s`SET cat_nb_photo = %d WHERE `%s` = %d';
518
                    $query = \sprintf($sql, $this->table, $nbPhoto, $this->keyName, $id);
519
                    $this->db->queryF($query);
520
                }
521
            }
522
523
            $query = \sprintf('UPDATE `%s`SET nlevel = %d, nleft = %d, nright = %d WHERE `%s` = %d;', $this->table, $row['nlevel'], $row['nleft'], $row['nright'], $this->keyName, $id);
524
            $this->db->queryF($query);
525
        }
526
    }
527
528
    /**
529
     * Generate the tree data. A single call to this generates the n-values for
530
     * 1 node in the tree. This function assigns the passed in n value as the
531
     * node's nleft value. It then processes all the node's children (which
532
     * in turn recursively processes that node's children and so on), and when
533
     * it is finally done, it takes the update n-value and assigns it as its
534
     * nright value. Because it is passed as a reference, the subsequent changes
535
     * in subrequests are held over to when control is returned so the nright
536
     * can be assigned.
537
     *
538
     * @param array &$arr   A reference to the data array, since we need to
539
     *                      be able to update the data in it
540
     * @param int    $id    The ID of the current node to process
541
     * @param int    $level The nlevel to assign to the current node
542
     * @param int   &$n     A reference to the running tally for the n-value
543
     */
544
    public function _generateTreeData(&$arr, $id, $level, &$n)
545
    {
546
        $arr[$id]['nlevel'] = $level;
547
        $arr[$id]['nleft']  = ++$n;
548
549
        // loop over the node's children and process their data
550
        // before assigning the nright value
551
        foreach ($arr[$id]['children'] as $child_id) {
552
            $this->_generateTreeData($arr, $child_id, $level + 1, $n);
553
        }
554
        $arr[$id]['nright'] = ++$n;
555
    }
556
557
    /**
558
     * @param string $permType
559
     *
560
     * @return bool|\Criteria
561
     */
562
    public function getCatRestrictCriteria($permType = 'public_access')
563
    {
564
        if (null !== $GLOBALS['xoopsUser'] && \is_object($GLOBALS['xoopsUser'])) {
565
            $permHandler       = $this->getPermHandler();
566
            $allowedCategories = $permHandler->getAuthorizedPublicCat($GLOBALS['xoopsUser'], $permType);
567
568
            $count = \count($allowedCategories);
569
            if ($count > 0) {
570
                $in = '(' . $allowedCategories[0];
571
                \array_shift($allowedCategories);
572
                foreach ($allowedCategories as $allowedCategory) {
573
                    $in .= ',' . $allowedCategory;
574
                }
575
                $in       .= ')';
576
                $criteria = new \Criteria('cat_id', $in, 'IN');
577
            } else {
578
                $criteria = new \Criteria('cat_id', '(0)', 'IN');
579
            }
580
581
            return $criteria;
582
        }
583
584
        return false;
585
    }
586
587
    /**
588
     * @return Extgallery\PublicPermHandler
589
     */
590
    public function getPermHandler()
591
    {
592
        return Extgallery\PublicPermHandler::getInstance();
593
    }
594
}
595