Completed
Push — master ( f87886...b3b862 )
by Michael
02:18
created

ExtgalleryCatHandler::_getPermHandler()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 26 and the first side effect is on line 20.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
/**
3
 * ExtGallery Class Manager
4
 *
5
 * You may not change or alter any portion of this comment or credits
6
 * of supporting developers from this source code or any supporting source code
7
 * which is considered copyrighted (c) material of the original comment or credit authors.
8
 * This program is distributed in the hope that it will be useful,
9
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
11
 *
12
 * @copyright   {@link https://xoops.org/ XOOPS Project}
13
 * @license     GNU GPL 2 (http://www.gnu.org/licenses/old-licenses/gpl-2.0.html)
14
 * @author      Zoullou (http://www.zoullou.net)
15
 * @package     ExtGallery
16
 */
17
18
// defined('XOOPS_ROOT_PATH') || exit('XOOPS root path not defined');
0 ignored issues
show
Unused Code Comprehensibility introduced by
70% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
19
20
require_once __DIR__ . '/publicPerm.php';
21
require_once __DIR__ . '/ExtgalleryPersistableObjectHandler.php';
22
23
/**
24
 * Class ExtgalleryCat
25
 */
26
class ExtgalleryCat extends XoopsObject
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
27
{
28
    public $externalKey = array();
29
30
    /**
31
     * ExtgalleryCat constructor.
32
     */
33
    public function __construct()
34
    {
35
        parent::__construct();
36
        $this->initVar('cat_id', XOBJ_DTYPE_INT, 0, false);
37
        $this->initVar('cat_pid', XOBJ_DTYPE_INT, 0, false);
38
        $this->initVar('nleft', XOBJ_DTYPE_INT, 0, false);
39
        $this->initVar('nright', XOBJ_DTYPE_INT, 0, false);
40
        $this->initVar('nlevel', XOBJ_DTYPE_INT, 0, false);
41
        $this->initVar('cat_name', XOBJ_DTYPE_TXTBOX, '', true, 255);
42
        $this->initVar('cat_desc', XOBJ_DTYPE_TXTAREA, '', false);
43
        $this->initVar('cat_date', XOBJ_DTYPE_INT, 0, true);
44
        $this->initVar('cat_isalbum', XOBJ_DTYPE_INT, 0, false);
45
        $this->initVar('cat_weight', XOBJ_DTYPE_INT, 0, false);
46
        $this->initVar('cat_nb_album', XOBJ_DTYPE_INT, 0, false);
47
        $this->initVar('cat_nb_photo', XOBJ_DTYPE_INT, 0, false);
48
        $this->initVar('cat_imgurl', XOBJ_DTYPE_URL, '', false, 150);
49
        $this->initVar('photo_id', XOBJ_DTYPE_INT, 0, false);
50
51
        $this->externalKey['photo_id'] = array(
52
            'className'      => 'publicphoto',
53
            'getMethodeName' => 'getPhoto',
54
            'keyName'        => 'photo',
55
            'core'           => false
56
        );
57
    }
58
59
    /**
60
     * @param $key
61
     *
62
     * @return mixed
63
     */
64
    public function getExternalKey($key)
65
    {
66
        return $this->externalKey[$key];
67
    }
68
}
69
70
/**
71
 * Class ExtgalleryCatHandler
72
 */
73
class ExtgalleryCatHandler extends ExtgalleryPersistableObjectHandler
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
74
{
75
    //var $_nestedTree;
76
    public $_photoHandler;
77
78
    /**
79
     * @param $db
80
     * @param $type
81
     */
82
    public function __construct(XoopsDatabase $db, $type)
83
    {
84
        parent::__construct($db, 'extgallery_' . $type . 'cat', 'Extgallery' . ucfirst($type) . 'Cat', 'cat_id');
85
        //$this->_nestedTree = new NestedTree($db, 'extgallery_'.$type.'cat', 'cat_id', 'cat_pid', 'cat_id');
0 ignored issues
show
Unused Code Comprehensibility introduced by
59% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
86
        $this->_photoHandler = xoops_getModuleHandler($type . 'photo', 'extgallery');
87
    }
88
89
    /**
90
     * @param $data
91
     *
92
     * @return bool
93
     */
94
    public function createCat($data)
95
    {
96
        $cat = $this->create();
97
        $cat->setVars($data);
98
99
        if (!$this->_haveValidParent($cat)) {
100
            return false;
101
        }
102
103
        $this->insert($cat, true);
104
        $this->rebuild();
105
106
        return true;
107
    }
108
109
    /**
110
     * @param $data
111
     *
112
     * @return bool
0 ignored issues
show
Documentation introduced by
Should the return type not be false|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
113
     */
114
    public function modifyCat($data)
115
    {
116
        $cat = $this->get($data['cat_id']);
117
        $cat->setVars($data);
118
119
        if (!$this->_haveValidParent($cat)) {
120
            return false;
121
        }
122
        $this->insert($cat, true);
123
124
        // Rebluid the tree only if the structure is modified
125
        if (isset($data['cat_pid']) || isset($data['nlevel']) || isset($data['nright']) || isset($data['nleft'])) {
126
            $this->rebuild();
127
        }
128
    }
129
130
    /**
131
     * @param int $catId
132
     */
133
    public function deleteCat($catId)
134
    {
135
        $children = $this->getDescendants($catId, false, true);
136
        foreach ($children as $child) {
137
            $this->_photoHandler->deletePhotoByCat($child->getVar('cat_id'));
138
            $this->deleteCat($child->getVar('cat_id'));
139
        }
140
        $this->_photoHandler->deletePhotoByCat($catId);
141
        $this->deleteById($catId);
142
    }
143
144
    /**
145
     * @param int    $id
146
     * @param bool   $includeSelf
147
     * @param bool   $childrenOnly
148
     * @param bool   $withRestrict
149
     * @param string $permType
150
     *
151
     * @return array
152
     */
153
    public function getDescendants(
154
        $id = 0,
155
        $includeSelf = false,
156
        $childrenOnly = false,
157
        $withRestrict = true,
158
        $permType = 'public_access'
159
    ) {
160
        $cat = $this->get($id);
161
162
        $nleft     = $cat->getVar('nleft');
163
        $nright    = $cat->getVar('nright');
164
        $parent_id = $cat->getVar('cat_id');
165
166
        $criteria = new CriteriaCompo();
167
168
        if ($childrenOnly) {
169
            $criteria->add(new Criteria('cat_pid', $parent_id), 'OR');
170
            if ($includeSelf) {
171
                $criteria->add(new Criteria('cat_id', $parent_id));
172
                //$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);
0 ignored issues
show
Unused Code Comprehensibility introduced by
67% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
173
            }/* else {
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
174
                //$query = sprintf('select * from %s where %s = %d order by nleft', $this->table, $this->fields['parent'], $parent_id);
175
            }*/
176
        } else {
177
            if ($nleft > 0 && $includeSelf) {
178
                $criteria->add(new Criteria('nleft', $nleft, '>='));
179
                $criteria->add(new Criteria('nright', $nright, '<='));
180
                //$query = sprintf('select * from %s where nleft >= %d and nright <= %d order by nleft', $this->table, $nleft, $nright);
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
181 View Code Duplication
            } else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
182
                if ($nleft > 0) {
183
                    $criteria->add(new Criteria('nleft', $nleft, '>'));
184
                    $criteria->add(new Criteria('nright', $nright, '<'));
185
                    //$query = sprintf('select * from %s where nleft > %d and nright < %d order by nleft', $this->table, $nleft, $nright);
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
186
                }/* else {
0 ignored issues
show
Unused Code Comprehensibility introduced by
53% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
187
                $query = sprintf('select * from %s order by nleft', $this->table);
188
                }*/
189
            }
190
        }
191
        if ($withRestrict) {
192
            $criteria->add($this->getCatRestrictCriteria($permType));
193
            $criteria->add($this->getCatRestrictCriteria('public_displayed'));
194
        }
195
        $criteria->setSort('nleft');
196
197
        return $this->getObjects($criteria);
198
    }
199
200
    /**
201
     * @param int $id
202
     *
203
     * @return null
204
     */
205 View Code Duplication
    public function getCat($id = 0)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
206
    {
207
        $criteria = new CriteriaCompo();
208
        $criteria->add($this->getCatRestrictCriteria('public_displayed'));
209
        $criteria->add(new Criteria('cat_id', $id));
210
        $ret = $this->getObjects($criteria);
211
212
        if (count($ret) > 0) {
213
            return $ret[0];
214
        } else {
215
            return null;
216
        }
217
    }
218
219
    public function _haveValidParent()
220
    {
221
        exit('_haveValidParent() method must be defined on sub classes');
0 ignored issues
show
Coding Style Compatibility introduced by
The method _haveValidParent() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
222
    }
223
224
    /**
225
     * @param $cat
226
     *
227
     * @return bool
228
     */
229
    public function _isAlbum($cat)
230
    {
231
        $nbPhoto = $this->nbPhoto($cat);
232
233
        return $nbPhoto != 0;
234
    }
235
236
    /**
237
     * @param ExtgalleryCat $cat
238
     *
239
     * @return mixed
240
     */
241
    public function nbPhoto(&$cat)
242
    {
243
        /** @var ExtgalleryPublicPhotoHandler $this ->_photoHandler */
244
        return $this->_photoHandler->nbPhoto($cat);
245
    }
246
247
    /**
248
     * @param int  $id
249
     * @param bool $includeSelf
250
     *
251
     * @return array
252
     */
253
    public function getPath($id = 0, $includeSelf = false)
254
    {
255
        $cat = $this->get($id);
256
        if (null === $cat) {
257
            return array();
258
        }
259
260
        $criteria = new CriteriaCompo();
261
        if ($includeSelf) {
262
            $criteria->add(new Criteria('nleft', $cat->getVar('nleft'), '<='));
263
            $criteria->add(new Criteria('nright', $cat->getVar('nright'), '>='));
264
            //$query = sprintf('select * from %s where nleft <= %d and nright >= %d order by nlevel', $this->table, $node['nleft'], $node['nright']);
0 ignored issues
show
Unused Code Comprehensibility introduced by
70% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
265 View Code Duplication
        } else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
266
            $criteria->add(new Criteria('nleft', $cat->getVar('nleft'), '<'));
267
            $criteria->add(new Criteria('nright', $cat->getVar('nright'), '>'));
268
            //$query = sprintf('select * from %s where nleft < %d and nright > %d order by nlevel', $this->table, $node['nleft'], $node['nright']);
0 ignored issues
show
Unused Code Comprehensibility introduced by
70% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
269
        }
270
        $criteria->add($this->getCatRestrictCriteria());
271
        $criteria->add($this->getCatRestrictCriteria('public_displayed'));
272
        $criteria->setSort('nlevel');
273
274
        return $this->getObjects($criteria);
275
    }
276
277
    /**
278
     * @return array
279
     */
280
    public function getTree()
281
    {
282
        return $this->getDescendants(0, false, false, false);
283
    }
284
285
    /**
286
     * @param int  $id
287
     * @param bool $includeSelf
288
     *
289
     * @return array
290
     */
291
    public function getChildren($id = 0, $includeSelf = false)
292
    {
293
        return $this->getDescendants($id, $includeSelf, true);
294
    }
295
296
    /**
297
     * @param int $id
298
     *
299
     * @return int
300
     */
301
    public function nbAlbum($id = 0)
302
    {
303
        $criteria = new CriteriaCompo(new Criteria('nright - nleft', 1));
304
        //$query = sprintf('select count(*) as num_leef from %s where nright - nleft = 1', $this->table);
0 ignored issues
show
Unused Code Comprehensibility introduced by
58% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
305
        if ($id != 0) {
306
            $cat = $this->get($id);
307
            $criteria->add(new Criteria('nleft', $cat->getVar('nleft'), '>'));
308
            $criteria->add(new Criteria('nright', $cat->getVar('nright'), '<'));
309
            //$query .= sprintf(' AND nleft > %d AND nright < %d', $node['nleft'], $node['nright']);
0 ignored issues
show
Unused Code Comprehensibility introduced by
69% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
310
        }
311
312
        return $this->getCount($criteria);
313
    }
314
315
    /**
316
     * @param        $name
317
     * @param        $selectMode
318
     * @param bool   $addEmpty
319
     * @param int    $selected
320
     * @param string $extra
321
     * @param bool   $displayWeight
322
     * @param string $permType
323
     *
324
     * @return string
325
     */
326
    public function getSelect(
327
        $name,
328
        $selectMode,
329
        $addEmpty = false,
330
        $selected = 0,
331
        $extra = '',
332
        $displayWeight = false,
333
        $permType = 'public_access'
334
    ) {
335
        $cats = $this->getDescendants(0, false, false, true, $permType);
336
337
        return $this->makeSelect($cats, $name, $selectMode, $addEmpty, $selected, $extra, $displayWeight);
338
    }
339
340
    /**
341
     * @param        $name
342
     * @param bool   $addEmpty
343
     * @param int    $selected
344
     * @param string $extra
345
     * @param string $permType
346
     *
347
     * @return string
348
     */
349
    public function getLeafSelect($name, $addEmpty = false, $selected = 0, $extra = '', $permType = 'public_access')
350
    {
351
        return $this->getSelect($name, 'node', $addEmpty, $selected, $extra, false, $permType);
352
    }
353
354
    /**
355
     * @param        $name
356
     * @param bool   $addEmpty
357
     * @param int    $selected
358
     * @param string $extra
359
     *
360
     * @return string
361
     */
362
    public function getNodeSelect($name, $addEmpty = false, $selected = 0, $extra = '')
363
    {
364
        return $this->getSelect($name, 'leaf', $addEmpty, $selected, $extra);
365
    }
366
367
    /**
368
     * @param array  $cats
369
     * @param string $name
370
     * @param string $selectMode
371
     * @param        $addEmpty
372
     * @param        $selected
373
     * @param        $extra
374
     * @param        $displayWeight
375
     *
376
     * @return string
377
     */
378
    public function makeSelect($cats, $name, $selectMode, $addEmpty, $selected, $extra, $displayWeight)
0 ignored issues
show
Coding Style introduced by
makeSelect uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
379
    {
380
        $ret = '<select name="' . $name . '" id="' . $name . '"' . $extra . '>';
381
        if ($addEmpty) {
382
            $ret .= '<option value="0">-----</option>';
383
        }
384
        /** @var ExtgalleryCat $cat */
385
        foreach ($cats as $cat) {
386
            $disableOption = '';
387
            if ($selectMode === 'node' && ($cat->getVar('nright') - $cat->getVar('nleft') != 1)) {
388
                // If the brownser is IE the parent cat isn't displayed
389
                //                if (preg_match('`MSIE`', $_SERVER['HTTP_USER_AGENT'])) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
71% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
390
                if (false !== strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE')) {
391
                    continue;
392
                }
393
                $disableOption = ' disabled="disabled"';
394
            } elseif ($selectMode === 'leaf' && ($cat->getVar('cat_isalbum') == 1)) {
395
                continue;
396
            }
397
398
            $selectedOption = '';
399
            if ($cat->getVar('cat_id') == $selected) {
400
                $selectedOption = ' selected';
401
            }
402
403
            $prefix = '';
404 View Code Duplication
            for ($i = 0; $i < $cat->getVar('nlevel') - 1; ++$i) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
405
                $prefix .= '--';
406
            }
407
            $catName = $prefix . ' ' . $cat->getVar('cat_name');
408
            if ($displayWeight) {
409
                $catName .= ' [' . $cat->getVar('cat_weight') . ']';
410
            }
411
412
            $ret .= '<option value="' . $cat->getVar('cat_id') . '"' . $selectedOption . '' . $disableOption . '>' . $catName . '</option>';
413
        }
414
        $ret .= '</select>';
415
416
        return $ret;
417
    }
418
419
    /**
420
     * @param array $selected
421
     *
422
     * @return string
423
     */
424
    public function getBlockSelect($selected = array())
425
    {
426
        $cats           = $this->getDescendants();
427
        $ret            = '<select name="options[]" multiple="multiple">';
428
        $selectedOption = '';
429
        if ($allCat = in_array(0, $selected)) {
430
            $selectedOption = ' selected';
431
        }
432
        $ret .= '<option value="0"' . $selectedOption . '>' . _MB_EXTGALLERY_ALL_CATEGORIES . '</option>';
433
        foreach ($cats as $cat) {
434
            $prefix = '';
435 View Code Duplication
            for ($i = 0; $i < $cat->getVar('nlevel') - 1; ++$i) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
436
                $prefix .= '-';
437
            }
438
            $selectedOption = '';
439
            $disableOption  = '';
440
441
            if (!$allCat && in_array($cat->getVar('cat_id'), $selected)) {
442
                $selectedOption = ' selected';
443
            }
444
445
            if ($cat->getVar('nright') - $cat->getVar('nleft') != 1) {
446
                $disableOption = ' disabled="disabled"';
447
            }
448
449
            $ret .= '<option value="' . $cat->getVar('cat_id') . '"' . $selectedOption . '' . $disableOption . '>' . $prefix . ' ' . $cat->getVar('cat_name') . '</option>';
450
        }
451
        $ret .= '</select>';
452
453
        return $ret;
454
    }
455
456
    /**
457
     * @return array
458
     */
459
    public function getTreeWithChildren()
460
    {
461
        $criteria = new CriteriaCompo();
462
        $criteria->setSort('cat_weight, cat_name');
463
        //$query = sprintf('select * from %s order by %s', $this->table, $this->fields['sort']);
0 ignored issues
show
Unused Code Comprehensibility introduced by
64% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
464
465
        //$result = $this->db->query($query);
0 ignored issues
show
Unused Code Comprehensibility introduced by
62% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
466
        $categories = $this->getObjects($criteria, false, false);
467
468
        // create a root node to hold child data about first level items
469
        $root             = array();
470
        $root['cat_id']   = 0;
471
        $root['children'] = array();
472
473
        $arr = array(
474
            $root
475
        );
476
477
        // populate the array and create an empty children array
478
        /*while ($row = $this->db->fetchArray($result)) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
70% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
479
            $arr[$row[$this->fields['id']]] = $row;
480
            $arr[$row[$this->fields['id']]]['children'] = array ();
481
        }*/
482
        foreach ($categories as $row) {
483
            $arr[$row['cat_id']]             = $row;
484
            $arr[$row['cat_id']]['children'] = array();
485
        }
486
487
        // now process the array and build the child data
488
        foreach ($arr as $id => $row) {
489
            if (isset($row['cat_pid'])) {
490
                $arr[$row['cat_pid']]['children'][$id] = $id;
491
            }
492
        }
493
494
        return $arr;
495
    }
496
497
    /**
498
     * Rebuilds the tree data and saves it to the database
499
     */
500
    public function rebuild()
501
    {
502
        $data = $this->getTreeWithChildren();
503
504
        $n     = 0; // need a variable to hold the running n tally
505
        $level = 0; // need a variable to hold the running level tally
0 ignored issues
show
Unused Code introduced by
$level is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
506
507
        // invoke the recursive function. Start it processing
508
        // on the fake "root node" generated in getTreeWithChildren().
509
        // because this node doesn't really exist in the database, we
510
        // give it an initial nleft value of 0 and an nlevel of 0.
511
        $this->_generateTreeData($data, 0, 0, $n);
512
        //echo "<pre>";print_r($data);echo "</pre>";
0 ignored issues
show
Unused Code Comprehensibility introduced by
77% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
513
        // at this point the the root node will have nleft of 0, nlevel of 0
514
        // and nright of (tree size * 2 + 1)
515
516
        // Errase category and photo counter
517
        $query = sprintf('UPDATE "%s" SET cat_nb_album = 0, cat_nb_photo = 0;', $this->table);
518
        $this->db->queryF($query);
519
520
        foreach ($data as $id => $row) {
521
522
            // skip the root node
523
            if ($id == 0) {
524
                continue;
525
            }
526
527
            // Update the photo number
528
            if ($row['nright'] - $row['nleft'] == 1) {
529
                // Get the number of photo in this album
530
                $criteria = new CriteriaCompo();
531
                $criteria->add(new Criteria('cat_id', $id));
532
                $criteria->add(new Criteria('photo_approved', 1));
533
                /** @var ExtgalleryPublicPhotoHandler $this ->_photoHandler */
534
                $nbPhoto = $this->_photoHandler->getCount($criteria);
535
536
                // Update all parent of this album
537
                $upNbAlbum = '';
538
                if ($nbPhoto != 0) {
539
                    $upNbAlbum = 'cat_nb_album = cat_nb_album + 1, ';
540
                }
541
                $sql   = 'UPDATE "%s" SET ' . $upNbAlbum . 'cat_nb_photo = cat_nb_photo + "%d" WHERE nleft < "%d" AND nright > "%d";';
542
                $query = sprintf($sql, $this->table, $nbPhoto, $row['nleft'], $row['nright']);
543
                $this->db->queryF($query);
544
545
                // Update this album if needed
546
                if ($nbPhoto != 0) {
547
                    $sql   = 'UPDATE %s SET cat_nb_photo = %d WHERE %s = %d';
548
                    $query = sprintf($sql, $this->table, $nbPhoto, $this->keyName, $id);
549
                    $this->db->queryF($query);
550
                }
551
            }
552
553
            $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);
554
            $this->db->queryF($query);
555
        }
556
    }
557
558
    /**
559
     * Generate the tree data. A single call to this generates the n-values for
560
     * 1 node in the tree. This function assigns the passed in n value as the
561
     * node's nleft value. It then processes all the node's children (which
562
     * in turn recursively processes that node's children and so on), and when
563
     * it is finally done, it takes the update n-value and assigns it as its
564
     * nright value. Because it is passed as a reference, the subsequent changes
565
     * in subrequests are held over to when control is returned so the nright
566
     * can be assigned.
567
     *
568
     * @param array &$arr  A reference to the data array, since we need to
569
     *                     be able to update the data in it
570
     * @param int   $id    The ID of the current node to process
571
     * @param int   $level The nlevel to assign to the current node
572
     * @param int   &$n    A reference to the running tally for the n-value
573
     */
574 View Code Duplication
    public function _generateTreeData(&$arr, $id, $level, &$n)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
575
    {
576
        $arr[$id]['nlevel'] = $level;
577
        $arr[$id]['nleft']  = ++$n;
578
579
        // loop over the node's children and process their data
580
        // before assigning the nright value
581
        foreach ($arr[$id]['children'] as $child_id) {
582
            $this->_generateTreeData($arr, $child_id, $level + 1, $n);
583
        }
584
        $arr[$id]['nright'] = ++$n;
585
    }
586
587
    /**
588
     * @param string $permType
589
     *
590
     * @return Criteria
0 ignored issues
show
Documentation introduced by
Should the return type not be Criteria|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
591
     */
592
    public function getCatRestrictCriteria($permType = 'public_access')
0 ignored issues
show
Coding Style introduced by
getCatRestrictCriteria uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
593
    {
594
        if (null !== $GLOBALS['xoopsUser'] && is_object($GLOBALS['xoopsUser'])) {
595
            $permHandler       = $this->_getPermHandler();
596
            $allowedCategories = $permHandler->getAuthorizedPublicCat($GLOBALS['xoopsUser'], $permType);
597
598
            $count = count($allowedCategories);
599 View Code Duplication
            if ($count > 0) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
600
                $in = '(' . $allowedCategories[0];
601
                array_shift($allowedCategories);
602
                foreach ($allowedCategories as $allowedCategory) {
603
                    $in .= ',' . $allowedCategory;
604
                }
605
                $in       .= ')';
606
                $criteria = new Criteria('cat_id', $in, 'IN');
607
            } else {
608
                $criteria = new Criteria('cat_id', '(0)', 'IN');
609
            }
610
611
            return $criteria;
612
        }
613
    }
614
    /**
615
     * @return ExtgalleryPublicPermHandler
616
     */
617
    public function _getPermHandler()
618
    {
619
        return ExtgalleryPublicPermHandler::getInstance();
620
    }
621
}
622