GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — 2.9 ( 57324c...7343d3 )
by Thorsten
13:59
created

PMF_Category::numParent()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 15
Code Lines 6

Duplication

Lines 15
Ratio 100 %
Metric Value
dl 15
loc 15
rs 9.4286
cc 1
eloc 6
nc 1
nop 1
1
<?php
2
3
/**
4
 * The main category class.
5
 *
6
 * PHP Version 5.5
7
 *
8
 * This Source Code Form is subject to the terms of the Mozilla Public License,
9
 * v. 2.0. If a copy of the MPL was not distributed with this file, You can
10
 * obtain one at http://mozilla.org/MPL/2.0/.
11
 *
12
 * @category  phpMyFAQ
13
 *
14
 * @author    Thorsten Rinne <[email protected]>
15
 * @author    Lars Tiedemann <[email protected]>
16
 * @author    Matteo Scaramuccia <[email protected]>
17
 * @author    Rudi Ferrari <[email protected]>
18
 * @copyright 2004-2015 phpMyFAQ Team
19
 * @license   http://www.mozilla.org/MPL/2.0/ Mozilla Public License Version 2.0
20
 *
21
 * @link      http://www.phpmyfaq.de
22
 * @since     2004-02-16
23
 */
24
if (!defined('IS_VALID_PHPMYFAQ')) {
25
    exit();
26
}
27
28
/**
29
 * Category.
30
 *
31
 * @category  phpMyFAQ
32
 *
33
 * @author    Thorsten Rinne <[email protected]>
34
 * @author    Lars Tiedemann <[email protected]>
35
 * @author    Matteo Scaramuccia <[email protected]>
36
 * @author    Rudi Ferrari <[email protected]>
37
 * @copyright 2004-2015 phpMyFAQ Team
38
 * @license   http://www.mozilla.org/MPL/2.0/ Mozilla Public License Version 2.0
39
 *
40
 * @link      http://www.phpmyfaq.de
41
 * @since     2004-02-16
42
 */
43
class PMF_Category
44
{
45
    /**
46
     * @var PMF_Configuration
47
     */
48
    private $_config = null;
49
50
    /**
51
     * User ID.
52
     *
53
     * @var int
54
     */
55
    private $user = -1;
56
57
    /**
58
     * Groupd.
59
     *
60
     * @var array
61
     */
62
    private $groups = array(-1);
63
64
    /**
65
     * The categories as an array.
66
     *
67
     * @var array
68
     */
69
    public $categories = [];
70
71
    /**
72
     * The category names as an array.
73
     *
74
     * @var array
75
     */
76
    public $categoryName = [];
77
78
    /**
79
     * The category tree.
80
     *
81
     * @var array
82
     */
83
    public $catTree = [];
84
85
    /**
86
     * The children nodes.
87
     *
88
     * @var array
89
     */
90
    private $children = [];
91
92
    /**
93
     * The current language.
94
     *
95
     * @var string
96
     */
97
    private $language = null;
98
99
    /**
100
     * The lines of tabs.
101
     *
102
     * @var array
103
     */
104
    private $lineTab = [];
105
106
    /**
107
     * The tree with the tabs.
108
     *
109
     * @var array
110
     */
111
    public $treeTab = [];
112
113
    /**
114
     * Symbol for each item
115
     * NOTE: We do not use this currently.
116
     *
117
     * @var array
118
     */
119
    private $symbols = array(
120
        'vertical' => '|',
121
        'plus' => '+',
122
        'minus' => '-',
123
        'space' => '&nbsp;',
124
        'angle' => '-',
125
        'medium' => '|-', );
126
127
    /**
128
     * Constructor.
129
     *
130
     * @param PMF_Configuration $config   Configuration object
131
     * @param array             $groups   Array with group IDs
132
     * @param bool              $withperm With or without permission check
133
     */
134
    public function __construct(PMF_Configuration $config, $groups = [], $withperm = true)
135
    {
136
        $this->_config = $config;
137
138
        $this->setGroups($groups);
139
        $this->setLanguage($this->_config->getLanguage()->getLanguage());
140
141
        $this->lineTab = $this->getOrderedCategories($withperm);
142
        foreach (array_keys($this->lineTab) as $i) {
143
            $this->lineTab[$i]['level'] = $this->levelOf($this->lineTab[$i]['id']);
144
        }
145
    }
146
147
    /**
148
     * @param int $userId
149
     */
150
    public function setUser($userId = -1)
151
    {
152
        $this->user = $userId;
153
    }
154
155
    /**
156
     * @param array $groups
157
     */
158
    public function setGroups(Array $groups)
159
    {
160
        if (0 === count($groups)) {
161
            $groups = array(-1);
162
        }
163
        $this->groups = $groups;
164
    }
165
166
    /**
167
     * Returns all categories with ordered category IDs according to the user
168
     * and group permissions.
169
     *
170
     * @param bool $withperm With or without permission check
171
     *
172
     * @return array
173
     */
174
    private function getOrderedCategories($withperm = true)
175
    {
176
        $where = '';
177
178 View Code Duplication
        if ($withperm) {
179
            $where = sprintf('
180
                WHERE
181
                    ( fg.group_id IN (%s)
182
                OR
183
                    (fu.user_id = %d AND fg.group_id IN (%s)))',
184
                implode(', ', $this->groups),
185
                $this->user,
186
                implode(', ', $this->groups)
187
            );
188
        }
189
190
        if (isset($this->language) && preg_match("/^[a-z\-]{2,}$/", $this->language)) {
191
            $where .= empty($where) ? '
192
            WHERE' : '
193
            AND';
194
            $where .= "
195
                fc.lang = '".$this->language."'";
196
        }
197
198
        $query = sprintf('
199
            SELECT
200
                fc.id AS id,
201
                fc.lang AS lang,
202
                fc.parent_id AS parent_id,
203
                fc.name AS name,
204
                fc.description AS description,
205
                fc.user_id AS user_id,
206
                fc.group_id AS group_id,
207
                fc.active AS active
208
            FROM
209
                %sfaqcategories fc
210
            LEFT JOIN
211
                %sfaqcategory_group fg
212
            ON
213
                fc.id = fg.category_id
214
            LEFT JOIN
215
                %sfaqcategory_user fu
216
            ON
217
                fc.id = fu.category_id
218
            %s
219
            GROUP BY
220
                fc.id, fc.lang, fc.parent_id, fc.name, fc.description, fc.user_id
221
            ORDER BY
222
                fc.parent_id, fc.id',
223
            PMF_Db::getTablePrefix(),
224
            PMF_Db::getTablePrefix(),
225
            PMF_Db::getTablePrefix(),
226
            $where
227
        );
228
229
        $result = $this->_config->getDb()->query($query);
230
231
        if ($result) {
232 View Code Duplication
            while ($row = $this->_config->getDb()->fetchArray($result)) {
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...
233
                $this->categoryName[$row['id']] = $row;
234
                $this->categories[$row['id']] = &$this->categoryName[$row['id']];
235
                $this->children[$row['parent_id']][$row['id']] = &$this->categoryName[$row['id']];
236
            }
237
        }
238
239
        return $this->categories;
240
    }
241
242
    /**
243
     * Gets the main categories and write them in an array.
244
     *
245
     * @param string $categories Array of parent category ids
246
     * @param bool   $parentId  Only top level categories?
247
     *
248
     * @return array
249
     */
250
    public function getCategories($categories, $parentId = true)
251
    {
252
        $_query = '';
253
        $query = sprintf('
254
            SELECT
255
                id, lang, parent_id, name, description, user_id, group_id, active
256
            FROM
257
                %sfaqcategories
258
            WHERE ',
259
            PMF_Db::getTablePrefix());
260
261
        if (true === $parentId) {
262
            $query .= 'parent_id = 0';
263
        }
264
        foreach (explode(',', $categories) as $cats) {
265
            $_query .= ' OR parent_id = '.$cats;
266
        }
267
        if (false === $parentId && 0 < PMF_String::strlen($_query)) {
268
            $query .= PMF_String::substr($_query, 4);
269
        }
270 View Code Duplication
        if (isset($this->language) && preg_match("/^[a-z\-]{2,}$/", $this->language)) {
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...
271
            $query .= " AND lang = '".$this->language."'";
272
        }
273
        $query .= ' ORDER BY id';
274
        $result = $this->_config->getDb()->query($query);
275 View Code Duplication
        while ($row = $this->_config->getDb()->fetchArray($result)) {
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...
276
            $this->categories[$row['id']] = $row;
277
        }
278
279
        return $this->categories;
280
    }
281
282
    /**
283
     * Gets all categories and write them in an array.
284
     *
285
     * @return array
286
     */
287
    public function getAllCategories()
288
    {
289
        $query = sprintf('
290
            SELECT
291
                id, lang, parent_id, name, description, user_id, group_id, active
292
            FROM
293
                %sfaqcategories',
294
            PMF_Db::getTablePrefix());
295 View Code Duplication
        if (isset($this->language) && preg_match("/^[a-z\-]{2,}$/", $this->language)) {
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...
296
            $query .= " WHERE lang = '".$this->language."'";
297
        }
298
        $result = $this->_config->getDb()->query($query);
299 View Code Duplication
        while ($row = $this->_config->getDb()->fetchArray($result)) {
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...
300
            $this->categories[$row['id']] = $row;
301
        }
302
303
        return $this->categories;
304
    }
305
306
    /**
307
     * Gets all category IDs
308
     *
309
     * @return array
310
     */
311
    public function getAllCategoryIds()
312
    {
313
        $categories = [];
314
315
        $query = sprintf('
316
            SELECT
317
                id
318
            FROM
319
                %sfaqcategories',
320
            PMF_Db::getTablePrefix()
321
        );
322
323 View Code Duplication
        if (isset($this->language) && preg_match("/^[a-z\-]{2,}$/", $this->language)) {
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...
324
            $query .= sprintf(" WHERE lang = '%s'", $this->language);
325
        }
326
327
        $result = $this->_config->getDb()->query($query);
328
329
        while ($row = $this->_config->getDb()->fetchArray($result)) {
330
            $categories[] = (int) $row['id'];
331
        }
332
333
        return $categories;
334
    }
335
336
    /**
337
     * Builds the category tree.
338
     *
339
     * @param int $id_parent Parent id
340
     * @param int $indent    Indention
341
     */
342
    public function buildTree($id_parent = 0, $indent = 0)
343
    {
344
        $tt = [];
345
        $x = $loop = 0;
346
347
        foreach ($this->categories as $category_id => $n) {
348
            if (isset($n['parent_id']) && $n['parent_id'] == $id_parent) {
349
                $tt[$x++] = $category_id;
350
            }
351
            ++$loop;
352
        }
353
354
        if ($x != 0) {
355
            foreach ($tt as $d) {
356
                $tmp = [];
357
                if (isset($this->categories[$d])) {
358
                    foreach ($this->categories[$d] as $key => $value) {
359
                        $tmp[$key] = $value;
360
                    }
361
                    $tmp['indent'] = $indent;
362
                    $this->catTree[] = $tmp;
363
                    $this->buildTree($tmp['id'], $indent + 1);
364
                }
365
            }
366
        }
367
    }
368
369
    /**
370
     * Get the level of the item id.
371
     *
372
     * @param int $id Category id
373
     *
374
     * @return int
375
     */
376
    private function levelOf($id)
377
    {
378
        $alreadies = array($id);
379
        $ret = 0;
380
        while ((isset($this->categoryName[$id]['parent_id'])) && ($this->categoryName[$id]['parent_id'] != 0)) {
381
            ++$ret;
382
            $id = $this->categoryName[$id]['parent_id'];
383
384
            if (in_array($id, $alreadies)) {
385
                break;
386
            } else {
387
                array_push($alreadies, $id);
388
            }
389
        }
390
391
        return $ret;
392
    }
393
394
    /**
395
     * Transforms the linear array in a 1D array in the order of the tree, with
396
     * the info.
397
     *
398
     * @param int $id Category id
399
     */
400
    public function transform($id)
401
    {
402
        $parentId = $level = 0;
403
        $tree = [];
404
        $tabs = isset($this->children[$id]) ? array_keys($this->children[$id]) : [];
405
        $num = count($tabs);
406
        $symbol = 'minus';
407
        $name = $description = '';
408
        $active = true;
409
410
        if ($id > 0) {
411
            $active = $this->categoryName[$id]['active'];
412
            $description = $this->categoryName[$id]['description'];
413
            $level = $this->categoryName[$id]['level'];
414
            $name = $this->categoryName[$id]['name'];
415
            $parentId = $this->categoryName[$id]['parent_id'];
416
        }
417
418
        if ($num < 0) {
419
            $temp = isset($this->children[$parentId]) ? array_keys($this->children[$parentId]) : [];
420
            if (isset($temp[count($temp) - 1])) {
421
                $symbol = ($id == $temp[count($temp) - 1]) ? 'angle' : 'medium';
422
            }
423
        }
424
425
        $ascendants = $this->getNodes($id);
426
        $numAscendants = count($ascendants);
427
428
        if ($id > 0) {
429
            for ($i = 0; $i < $numAscendants; ++$i) {
430
                $brothers = $this->getBrothers($ascendants[$i]);
431
                $tree[$i] = ($ascendants[$i] == $brothers[count($brothers) - 1]) ? 'space' : 'vertical';
432
            }
433
        }
434
435
        if ($id > 0) {
436
            $this->treeTab[] = array(
437
                'id' => $id,
438
                'symbol' => $symbol,
439
                'name' => $name,
440
                'numChilds' => count($tabs),
441
                'level' => $level,
442
                'parent_id' => $parentId,
443
                'childs' => $tabs,
444
                'tree' => $tree,
445
                'description' => $description,
446
                'active' => $active,
447
            );
448
        }
449
450
        foreach ($tabs as $i) {
451
            $this->transform($i);
452
        }
453
    }
454
455
    /**
456
     * Get the line number where to find the node $id in the category tree.
457
     *
458
     * @param int $id Category id
459
     *
460
     * @return int
461
     */
462
    private function getLineCategory($id)
463
    {
464
        $num = count($this->treeTab);
465
        for ($i = 0; $i < $num; ++$i) {
466
            if (isset($this->treeTab[$i]['id']) && $this->treeTab[$i]['id'] == $id) {
467
                return $i;
468
            }
469
        }
470
    }
471
472
    //
473
    /**
474
     * List in a array of the $id of the child.
475
     *
476
     * @param int $id Category id
477
     *
478
     * @return array
479
     *
480
     * @author Thorsten Rinne <[email protected]>
481
     */
482
    public function getChildren($id)
483
    {
484
        return isset($this->children[$id]) ? array_keys($this->children[$id]) : [];
485
    }
486
487
    /**
488
     * list in a array of the $id of the child.
489
     *
490
     * @param int $id Category id
491
     *
492
     * @return array
493
     */
494
    public function getChildNodes($id)
495
    {
496
        $childs = [];
497
498
        if (isset($this->children[$id])) {
499
            foreach (array_keys($this->children[$id]) as $childId) {
500
                $childs = array_merge($childs, array($childId));
501
                $childs = array_merge($childs, $this->getChildNodes($childId));
502
            }
503
        }
504
505
        return $childs;
506
    }
507
508
    /**
509
     * List in array the root, super-root, ... of the $id.
510
     *
511
     * @param int $id Category id
512
     *
513
     * @return array
514
     */
515
    private function getNodes($id)
516
    {
517
        if (($id > 0) && (isset($this->categoryName[$id]['level']))) {
518
            $thisLevel = $this->categoryName[$id]['level'];
519
            $temp = [];
520
            for ($i = $thisLevel; $i > 0; --$i) {
521
                $id = $this->categoryName[$id]['parent_id'];
522
                array_unshift($temp, $id);
523
            }
524
525
            return $temp;
526
        }
527
    }
528
529
    /**
530
     * Collapse the complete category tree.
531
     */
532 View Code Duplication
    public function collapseAll()
533
    {
534
        $numTreeTab = count($this->treeTab);
535
        for ($i = 0; $i < $numTreeTab; ++$i) {
536
            if ($this->treeTab[$i]['symbol'] == 'minus') {
537
                $this->treeTab[$i]['symbol'] = 'plus';
538
            }
539
        }
540
    }
541
542
    /**
543
     * expand the node $id.
544
     *
545
     * @param int $id Category id
546
     */
547
    public function expand($id)
548
    {
549
        $this->treeTab[$this->getLineCategory($id)]['symbol'] = 'minus';
550
    }
551
552
    /**
553
     * Try to expand from the parent_id to the node $id
554
     *
555
     * @param int $id
556
     *
557
     * @return void
558
     */
559
    public function expandTo($id)
560
    {
561
        $this->collapseAll();
562
        $ascendants = $this->getNodes($id);
563
        $ascendants[] = $id;
564
        $numAscendants = count($ascendants);
565
        for ($i = 0; $i < $numAscendants; ++$i) {
566
            if (isset($this->treeTab[$this->getLineCategory($ascendants[$i])]['numChilds'])) {
567
                $numChilds = $this->treeTab[$this->getLineCategory($ascendants[$i])]['numChilds'];
568
                if ($numChilds > 0) {
569
                    $this->expand($ascendants[$i]);
570
                } else {
571
                    $i = count($ascendants);
572
                }
573
            }
574
        }
575
    }
576
577
    /**
578
     * Expand the entire tree
579
     *
580
     * @return void
581
     */
582 View Code Duplication
    public function expandAll()
583
    {
584
        $numTreeTab = count($this->treeTab);
585
        for ($i = 0; $i < $numTreeTab; ++$i) {
586
            if ($this->treeTab[$i]['symbol'] == 'plus') {
587
                $this->treeTab[$i]['symbol'] = 'minus';
588
            }
589
        }
590
    }
591
592
    /**
593
     * Total height of the expanded tree.
594
     *
595
     * @return int
596
     */
597
    public function height()
598
    {
599
        return count($this->treeTab);
600
    }
601
602
    /**
603
     * print the static tree with the number of records.
604
     *
605
     * @return string
606
     */
607
    public function viewTree()
608
    {
609
        global $sids, $plr;
610
611
        $totFaqRecords = 0;
612
        $number = [];
613
614
        $query = sprintf('
615
            SELECT
616
                fcr.category_id AS category_id,
617
                count(fcr.category_id) AS number
618
            FROM
619
                %sfaqcategoryrelations fcr,
620
                %sfaqdata fd
621
            WHERE
622
                fcr.record_id = fd.id
623
            AND
624
                fcr.record_lang = fd.lang',
625
            PMF_Db::getTablePrefix(),
626
            PMF_Db::getTablePrefix());
627
628
        if (strlen($this->language) > 0) {
629
            $query .= sprintf(" AND fd.lang = '%s'",
630
                $this->language);
631
        }
632
633
        $query .= sprintf("
634
            AND
635
                fd.active = 'yes'
636
            GROUP BY
637
                fcr.category_id",
638
            PMF_Db::getTablePrefix(),
639
            PMF_Db::getTablePrefix());
640
        $result = $this->_config->getDb()->query($query);
641
642
        if ($this->_config->getDb()->numRows($result) > 0) {
643
            while ($row = $this->_config->getDb()->fetchObject($result)) {
644
                $number[$row->category_id] = $row->number;
645
            }
646
        }
647
648
        $output = "<ul>\n";
649
        $open = 0;
650
        $this->expandAll();
651
652
        for ($y = 0;$y < $this->height(); $y = $this->getNextLineTree($y)) {
653
            list($hasChild, $categoryName, $parent, $description) = $this->getLineDisplay($y);
654
            $level = $this->treeTab[$y]['level'];
655
            $leveldiff = $open - $level;
656
657
            if (!isset($number[$parent])) {
658
                $number[$parent] = 0;
659
            }
660
661 View Code Duplication
            if ($this->_config->get('records.hideEmptyCategories') && 0 === $number[$parent] && '-' === $hasChild) {
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...
662
                continue;
663
            }
664
665 View Code Duplication
            if ($leveldiff > 1) {
666
                $output .= '</li>';
667
                for ($i = $leveldiff; $i > 1; --$i) {
668
                    $output .= sprintf("\n%s</ul>\n%s</li>\n",
669
                        str_repeat("\t", $level + $i + 1),
670
                        str_repeat("\t", $level + $i));
671
                }
672
            }
673
674 View Code Duplication
            if ($level < $open) {
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...
675
                if (($level - $open) == -1) {
676
                    $output .= '</li>';
677
                }
678
                $output .= sprintf("\n%s</ul>\n%s</li>\n",
679
                    str_repeat("\t", $level + 2),
680
                    str_repeat("\t", $level + 1));
681
            } elseif ($level == $open && $y != 0) {
682
                $output .= "</li>\n";
683
            }
684
685
            if ($level > $open) {
686
                $output .= sprintf("\n%s<ul>\n%s<li>",
687
                    str_repeat("\t", $level + 1),
688
                    str_repeat("\t", $level + 1));
689
            } else {
690
                $output .= str_repeat("\t", $level + 1).'<li>';
691
            }
692
693
            if (0 === $number[$parent] && 0 === $level) {
694
                $numFaqs = '';
695
            } else {
696
                $totFaqRecords += $number[$parent];
697
                $numFaqs = '<span class="rssCategoryLink"> ('.$plr->GetMsg('plmsgEntries', $number[$parent]);
698
                if ($this->_config->get('main.enableRssFeeds')) {
699
                    $numFaqs .= sprintf(
700
                        ' <a href="feed/category/rss.php?category_id=%d&category_lang=%s" target="_blank"><i class="fa fa-rss"></i></a>',
701
                        $parent,
702
                        $this->language,
703
                        $parent
704
                    );
705
                }
706
                $numFaqs .= ')</span>';
707
            }
708
709
            $url = sprintf(
710
                '%s?%saction=show&amp;cat=%d',
711
                PMF_Link::getSystemRelativeUri(),
712
                $sids,
713
                $parent
714
            );
715
            $oLink = new PMF_Link($url, $this->_config);
716
            $oLink->itemTitle = $categoryName;
717
            $oLink->text = $categoryName;
718
            $oLink->tooltip = $description;
719
720
            $output .= $oLink->toHtmlAnchor().$numFaqs;
721
            $open = $level;
722
        }
723
724
        if (isset($level) && $level > 0) {
725
            $output .= str_repeat("</li>\n\t</ul>\n\t", $level);
726
        }
727
728
        $output .= "\t</li>\n";
729
        $output .= "\t</ul>\n";
730
        $output .= '<span id="totFaqRecords" style="display: none;">'.$totFaqRecords."</span>\n";
731
732
        return $output;
733
    }
734
735
    /**
736
     * Returns the three parts of a line to display: category name, the ID of
737
     * the root node and the description.
738
     *
739
     * @param int $y ID
740
     *
741
     * @return array
742
     */
743
    public function getLineDisplay($y)
744
    {
745
        $ret[0] = $this->symbols[$this->treeTab[$y]['symbol']];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$ret was never initialized. Although not strictly required by PHP, it is generally a good practice to add $ret = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
746
        $ret[1] = $this->treeTab[$y]['name'];
747
        $ret[2] = $this->treeTab[$y]['id'];
748
        $ret[3] = $this->treeTab[$y]['description'];
749
        $ret[4] = $this->treeTab[$y]['active'];
750
751
        return $ret;
752
    }
753
754
    /**
755
     * Gets the next line in the array treeTab, depending of the
756
     * collapse/expand node.
757
     *
758
     * @param int $l Current line
759
     *
760
     * @return int
761
     */
762
    public function getNextLineTree($l)
763
    {
764
        if ($this->treeTab[$l]['symbol'] != 'plus') {
765
            return $l + 1;
766
        } else {
767
            for ($i = $l + 1; $i < $this->height(); ++$i) {
768
                if ($this->treeTab[$i]['level'] <= $this->treeTab[$l]['level']) {
769
                    return $i;
770
                }
771
            }
772
        }
773
774
        return $this->height();
775
    }
776
777
    /**
778
     * Gets the list of the brothers of $id (include $id).
779
     *
780
     * @param int $id Brothers
781
     *
782
     * @return array
783
     */
784
    private function getBrothers($id)
785
    {
786
        return $this->getChildren($this->categoryName[$id]['parent_id']);
787
    }
788
789
    /**
790
     * Creates a category link.
791
     *
792
     * @param string $sids         Session id
793
     * @param int    $categoryId   Parent category
794
     * @param string $categoryName Category name
795
     * @param string $description  Description
796
     * @param bool   $hasChildren  Child categories available
797
     * @param bool   $isActive     Sets a link active via CSS
798
     *
799
     * @return string
800
     */
801
    public function addCategoryLink($sids, $categoryId, $categoryName, $description, $hasChildren = false, $isActive = false)
802
    {
803
        $url = sprintf(
804
            '%s?%saction=show&amp;cat=%d',
805
            PMF_Link::getSystemRelativeUri(),
806
            $sids,
807
            $categoryId
808
        );
809
810
        $oLink = new PMF_Link($url, $this->_config);
811
        $oLink->id = 'category_'.$categoryId;
812
        $oLink->itemTitle = $categoryName;
813
        $oLink->text = $categoryName;
814
815
        if ($hasChildren) {
816
            $oLink->text .= sprintf(
817
                '<i class="fa fa-caret-right"></i>',
818
                $categoryName);
819
        }
820
821
        if ($isActive) {
822
            $oLink->class = 'active';
823
        }
824
825
        $oLink->tooltip = $description;
826
827
        return $oLink->toHtmlAnchor();
828
    }
829
830
    /**
831
     * Gets the path from root to child as breadcrumbs.
832
     *
833
     * @param int    $id                Category ID
834
     * @param string $separator         Path separator
835
     * @param bool   $renderAsMicroData Renders breadcrumbs as HTML5 microdata
836
     * @param string $useCssClass       Use CSS class "breadcrumb"
837
     *
838
     * @return string
839
     */
840
    public function getPath($id, $separator = ' / ', $renderAsMicroData = false, $useCssClass = 'breadcrumb')
841
    {
842
        global $sids;
843
844
        $ids = $this->getNodes($id);
845
        $num = count($ids);
846
847
        $temp = $catid = $desc = $breadcrumb = [];
848
849
        for ($i = 0; $i < $num; ++$i) {
850
            $t = $this->getLineCategory($ids[$i]);
851
            if (array_key_exists($t, $this->treeTab)) {
852
                $temp[] = $this->treeTab[$this->getLineCategory($ids[$i])]['name'];
853
                $catid[] = $this->treeTab[$this->getLineCategory($ids[$i])]['id'];
854
                $desc[] = $this->treeTab[$this->getLineCategory($ids[$i])]['description'];
855
            }
856
        }
857
        if (isset($this->treeTab[$this->getLineCategory($id)]['name'])) {
858
            $temp[] = $this->treeTab[$this->getLineCategory($id)]['name'];
859
            $catid[] = $this->treeTab[$this->getLineCategory($id)]['id'];
860
            $desc[] = $this->treeTab[$this->getLineCategory($id)]['description'];
861
        }
862
863
        // @todo Maybe this should be done somewhere else ...
864
        if ($renderAsMicroData) {
865
            foreach ($temp as $k => $category) {
866
                $url = sprintf(
867
                    '%s?%saction=show&amp;cat=%d',
868
                    PMF_Link::getSystemRelativeUri(),
869
                    $sids,
870
                    $catid[$k]
871
                );
872
                $oLink = new PMF_Link($url, $this->_config);
873
                $oLink->text = sprintf('<span itemprop="title">%s</span>', $category);
874
                $oLink->itemTitle = $category;
875
                $oLink->tooltip = $desc[$k];
876
                $oLink->setItemProperty('url');
877
                if (0 == $k) {
878
                    $oLink->setRelation('index');
879
                }
880
881
                $breadcrumb[] = sprintf(
882
                    '<li itemscope itemtype="http://data-vocabulary.org/Breadcrumb">%s</li>',
883
                    $oLink->toHtmlAnchor()
884
                );
885
            }
886
887
            $temp = $breadcrumb;
888
889
            return sprintf(
890
                '<ul class="%s">%s</ul>',
891
                $useCssClass,
892
                implode('', $temp)
893
            );
894
        } else {
895
            return implode($separator, $temp);
896
        }
897
    }
898
899
    /**
900
     * Returns the categories from a record id and language.
901
     *
902
     * @param int $record_id   record id
903
     * @param int $record_lang record language
904
     *
905
     * @return array
906
     */
907 View Code Duplication
    public function getCategoryRelationsFromArticle($record_id, $record_lang)
908
    {
909
        $categories = [];
910
911
        $query = sprintf("
912
            SELECT
913
                category_id, category_lang
914
            FROM
915
                %sfaqcategoryrelations
916
            WHERE
917
                record_id = %d
918
            AND
919
                record_lang = '%s'",
920
            PMF_Db::getTablePrefix(),
921
            $record_id,
922
            $record_lang);
923
924
        $result = $this->_config->getDb()->query($query);
925
        while ($row = $this->_config->getDb()->fetchObject($result)) {
926
            $categories[$row->category_id] = array(
927
                'category_id' => $row->category_id,
928
                'category_lang' => $row->category_lang, );
929
        }
930
931
        return $categories;
932
    }
933
934
    /**
935
     * Returns all categories that are related to the given article-id and
936
     * the current language $this->language in an unsorted array which consists
937
     * of associative arrays with the keys 'name', 'id', 'lang',
938
     * 'parent_id' and 'description'.
939
     *
940
     * @param int $articleId Record id
941
     *
942
     * @return array
943
     */
944
    public function getCategoriesFromArticle($articleId)
945
    {
946
        $query = sprintf("
947
            SELECT
948
                fc.id AS id,
949
                fc.lang AS lang,
950
                fc.parent_id AS parent_id,
951
                fc.name AS name,
952
                fc.description AS description
953
            FROM
954
                %sfaqcategoryrelations fcr,
955
                %sfaqcategories fc
956
            WHERE
957
                fc.id = fcr.category_id
958
            AND
959
                fcr.record_id = %d
960
            AND
961
                fcr.category_lang = '%s'
962
            AND
963
                fc.lang = '%s'",
964
            PMF_Db::getTablePrefix(),
965
            PMF_Db::getTablePrefix(),
966
            $articleId,
967
            $this->language,
968
            $this->language);
969
970
        $result = $this->_config->getDb()->query($query);
971
        $num = $this->_config->getDb()->numRows($result);
972
        $this->categories = [];
973
        if ($num > 0) {
974 View Code Duplication
            while ($row = $this->_config->getDb()->fetchArray($result)) {
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...
975
                $this->categories[intval($row['id'])] = $row;
976
            }
977
        }
978
979
        return $this->categories;
980
    }
981
982
    /**
983
     * Returns the ID of a category that associated with the given article.
984
     *
985
     * @param int $article_id Record id
986
     *
987
     * @return int
988
     */
989
    public function getCategoryIdFromArticle($article_id)
990
    {
991
        $cats = $this->getCategoryIdsFromArticle($article_id);
992
        if (isset($cats[0])) {
993
            return $cats[0];
994
        } else {
995
            return 0;
996
        }
997
    }
998
999
    /**
1000
     * Returns an array with the IDs of all categories that are associated with
1001
     * the given article.
1002
     *
1003
     * @param int $article_id Record id
1004
     *
1005
     * @return array
1006
     */
1007
    public function getCategoryIdsFromArticle($article_id)
1008
    {
1009
        $cats = $this->getCategoriesFromArticle($article_id);
1010
        $arr = [];
1011
        foreach ($cats as $cat) {
1012
            $arr[] = $cat['id'];
1013
        }
1014
1015
        return $arr;
1016
    }
1017
1018
    /**
1019
     * Returns the admin user of the given category.
1020
     *
1021
     * @param int $categoryId
1022
     *
1023
     * @return int
1024
     */
1025
    public function getCategoryUser($categoryId)
1026
    {
1027
        return $this->categories[$categoryId]['user_id'];
1028
    }
1029
1030
    /**
1031
     * Returns the moderator group ID of the given category.
1032
     *
1033
     * @param int $categoryId
1034
     *
1035
     * @return int
1036
     */
1037
    public function getModeratorGroupId($categoryId)
1038
    {
1039
        return $this->categories[$categoryId]['group_id'];
1040
    }
1041
1042
    /**
1043
     * Adds a new category entry.
1044
     *
1045
     * @param array $categoryData Array of category data
1046
     * @param int   $parentId     Parent id
1047
     * @param int   $id           Category id
1048
     *
1049
     * @return int
1050
     */
1051
    public function addCategory(Array $categoryData, $parentId = 0, $id = null)
1052
    {
1053
        // If we only need a new language, we don't need a new category id
1054
        if (is_null($id)) {
1055
            $id = $this->_config->getDb()->nextId(PMF_Db::getTablePrefix().'faqcategories', 'id');
1056
        }
1057
1058
        $query = sprintf("
1059
            INSERT INTO
1060
                %sfaqcategories
1061
            (id, lang, parent_id, name, description, user_id, group_id, active)
1062
                VALUES
1063
            (%d, '%s', %d, '%s', '%s', %d, %d, %d)",
1064
            PMF_Db::getTablePrefix(),
1065
            $id,
1066
            $categoryData['lang'],
1067
            $parentId,
1068
            $categoryData['name'],
1069
            $categoryData['description'],
1070
            $categoryData['user_id'],
1071
            $categoryData['group_id'],
1072
            $categoryData['active']
1073
        );
1074
        $this->_config->getDb()->query($query);
1075
1076
        return $id;
1077
    }
1078
1079
    /**
1080
     * Updates an existent category entry.
1081
     *
1082
     * @param array $categoryData Array of category data
1083
     *
1084
     * @return bool
1085
     */
1086
    public function updateCategory(Array $categoryData)
1087
    {
1088
        $query = sprintf("
1089
            UPDATE
1090
                %sfaqcategories
1091
            SET
1092
                name = '%s',
1093
                description = '%s',
1094
                user_id = %d,
1095
                group_id = %d,
1096
                active = %d
1097
            WHERE
1098
                id = %d
1099
            AND
1100
                lang = '%s'",
1101
            PMF_Db::getTablePrefix(),
1102
            $categoryData['name'],
1103
            $categoryData['description'],
1104
            $categoryData['user_id'],
1105
            $categoryData['group_id'],
1106
            $categoryData['active'],
1107
            $categoryData['id'],
1108
            $categoryData['lang']
1109
        );
1110
        $this->_config->getDb()->query($query);
1111
1112
        return true;
1113
    }
1114
1115
    /**
1116
     * Returns the data of the given category.
1117
     *
1118
     * @param int $categoryId
1119
     *
1120
     * @return PMF_Entity_Category
1121
     */
1122
    public function getCategoryData($categoryId)
1123
    {
1124
        $entity = new PMF_Entity_Category();
1125
1126
        $query = sprintf(
1127
            "SELECT * FROM %sfaqcategories WHERE id = %d AND lang = '%s'",
1128
            PMF_Db::getTablePrefix(),
1129
            $categoryId,
1130
            $this->language
1131
        );
1132
1133
        $result = $this->_config->getDb()->query($query);
1134
1135
        if ($row = $this->_config->getDb()->fetchObject($result)) {
1136
            $entity->setId($row->id)
1137
                ->setLang($row->lang)
1138
                ->setParentId($row->parent_id)
1139
                ->setName($row->name)
1140
                ->setDescription($row->description)
1141
                ->setUserId($row->user_id)
1142
                ->setGroupId($row->group_id)
1143
                ->setActive($row->active);
1144
        }
1145
1146
        return $entity;
1147
    }
1148
1149
    /**
1150
     * Move the categories ownership for users.
1151
     *
1152
     * @param int $from Old user id
1153
     * @param int $to   New user id
1154
     *
1155
     * @return bool
1156
     */
1157
    public function moveOwnership($from, $to)
1158
    {
1159
        if (!is_numeric($from) || !is_numeric($to)) {
1160
            return false;
1161
        }
1162
1163
        $query = sprintf('
1164
            UPDATE
1165
                %sfaqcategories
1166
            SET
1167
                user_id = %d
1168
            WHERE
1169
                user_id = %d',
1170
            PMF_Db::getTablePrefix(),
1171
            $to,
1172
            $from
1173
        );
1174
        $this->_config->getDb()->query($query);
1175
1176
        return true;
1177
    }
1178
1179
    /**
1180
     * Checks if a language is already defined for a category id.
1181
     *
1182
     * @param int    $category_id   Category id
1183
     * @param string $category_lang Category language
1184
     *
1185
     * @return bool
1186
     */
1187
    public function checkLanguage($category_id, $category_lang)
1188
    {
1189
        $query = sprintf("
1190
            SELECT
1191
                lang
1192
            FROM
1193
                %sfaqcategories
1194
            WHERE
1195
                id = %d
1196
            AND
1197
                lang = '%s'",
1198
            PMF_Db::getTablePrefix(),
1199
            $category_id,
1200
            $category_lang);
1201
1202
        $result = $this->_config->getDb()->query($query);
1203
1204
        return $this->_config->getDb()->numRows($result);
1205
    }
1206
1207
    /**
1208
     * Swaps two categories.
1209
     *
1210
     * @param int $category_id_1 First category
1211
     * @param int $category_id_2 Second category
1212
     *
1213
     * @return bool
1214
     */
1215
    public function swapCategories($category_id_1, $category_id_2)
1216
    {
1217
        $temp_cat = rand(200000, 400000);
1218
1219
        $tables = array(
1220
            array('faqcategories' => 'id'),
1221
            array('faqcategories' => 'parent_id'),
1222
            array('faqcategoryrelations' => 'category_id'),
1223
            array('faqcategory_group' => 'category_id'),
1224
            array('faqcategory_user' => 'category_id'), );
1225
1226
        $result = true;
1227 View Code Duplication
        foreach ($tables as $pair) {
1228
            foreach ($pair as $_table => $_field) {
1229
                $result = $result && $this->_config->getDb()->query(sprintf('UPDATE %s SET %s = %d WHERE %s = %d',
1230
                    PMF_Db::getTablePrefix().$_table,
1231
                    $_field,
1232
                    $temp_cat,
1233
                    $_field,
1234
                    $category_id_2));
1235
                $result = $result && $this->_config->getDb()->query(sprintf('UPDATE %s SET %s = %d WHERE %s = %d',
1236
                    PMF_Db::getTablePrefix().$_table,
1237
                    $_field,
1238
                    $category_id_2,
1239
                    $_field,
1240
                    $category_id_1));
1241
                $result = $result && $this->_config->getDb()->query(sprintf('UPDATE %s SET %s = %d WHERE %s = %d',
1242
                    PMF_Db::getTablePrefix().$_table,
1243
                    $_field,
1244
                    $category_id_1,
1245
                    $_field,
1246
                    $temp_cat));
1247
            }
1248
        }
1249
1250
        $tables2 = array(array('faqquestions' => 'category_id'));
1251
1252 View Code Duplication
        foreach ($tables2 as $pair) {
1253
            foreach ($pair as $_table => $_field) {
1254
                $result = $result && $this->_config->getDb()->query(sprintf("UPDATE %s SET %s = '%d' WHERE %s = '%d'",
1255
                    PMF_Db::getTablePrefix().$_table,
1256
                    $_field,
1257
                    $temp_cat,
1258
                    $_field,
1259
                    $category_id_2));
1260
                $result = $result && $this->_config->getDb()->query(sprintf("UPDATE %s SET %s = '%d' WHERE %s = '%d'",
1261
                    PMF_Db::getTablePrefix().$_table,
1262
                    $_field,
1263
                    $category_id_2,
1264
                    $_field,
1265
                    $category_id_1));
1266
                $result = $result && $this->_config->getDb()->query(sprintf("UPDATE %s SET %s = '%d' WHERE %s = '%d'",
1267
                    PMF_Db::getTablePrefix().$_table,
1268
                    $_field,
1269
                    $category_id_1,
1270
                    $_field,
1271
                    $temp_cat));
1272
            }
1273
        }
1274
1275
        return $result;
1276
    }
1277
1278
    /**
1279
     * Updates the parent category.
1280
     *
1281
     * @param int $category_id Category id
1282
     * @param int $parent_id   Parent category id
1283
     *
1284
     * @return bool
1285
     */
1286
    public function updateParentCategory($category_id, $parent_id)
1287
    {
1288
        if ((!is_numeric($category_id) || !is_numeric($parent_id)) && $category_id != $parent_id) {
1289
            return false;
1290
        }
1291
1292
        $query = sprintf('
1293
            UPDATE
1294
                %sfaqcategories
1295
            SET
1296
                parent_id = %d
1297
            WHERE
1298
                id = %d',
1299
            PMF_Db::getTablePrefix(),
1300
            $parent_id,
1301
            $category_id);
1302
        $this->_config->getDb()->query($query);
1303
1304
        return true;
1305
    }
1306
1307
    /**
1308
     * Deletes a category.
1309
     *
1310
     * @param int    $category_id   Category id
1311
     * @param string $category_lang Categiry language
1312
     * @param bool   $delete_all    Delete all languages?
1313
     *
1314
     * @return bool
1315
     */
1316 View Code Duplication
    public function deleteCategory($category_id, $category_lang, $delete_all = false)
1317
    {
1318
        $query = sprintf('
1319
            DELETE FROM
1320
                %sfaqcategories
1321
            WHERE
1322
                id = %d',
1323
            PMF_Db::getTablePrefix(),
1324
            $category_id);
1325
        if (!$delete_all) {
1326
            $query .= " AND lang = '".$category_lang."'";
1327
        }
1328
        $this->_config->getDb()->query($query);
1329
1330
        return true;
1331
    }
1332
    /**
1333
     * Deletes a category relation.
1334
     *
1335
     * @param int    $category_id   Category id
1336
     * @param string $category_lang Categiry language
1337
     * @param bool   $delete_all    Delete all languages?
1338
     *
1339
     * @return bool
1340
     */
1341 View Code Duplication
    public function deleteCategoryRelation($category_id, $category_lang, $delete_all = false)
1342
    {
1343
        $query = sprintf('
1344
            DELETE FROM
1345
                %sfaqcategoryrelations
1346
            WHERE
1347
                category_id = %d',
1348
            PMF_Db::getTablePrefix(),
1349
            $category_id);
1350
        if (!$delete_all) {
1351
            $query .= " AND category_lang = '".$category_lang."'";
1352
        }
1353
        $this->_config->getDb()->query($query);
1354
1355
        return true;
1356
    }
1357
1358
    /**
1359
     * Create array with translated categories.
1360
     *
1361
     * @param int $category_id
1362
     *
1363
     * @return array
1364
     *
1365
     * @since   2006-09-10
1366
     *
1367
     * @author  Rudi Ferrari <[email protected]>
1368
     */
1369
    public function getCategoryLanguagesTranslated($category_id)
1370
    {
1371
        global $languageCodes;
1372
1373
        $existcatlang = $this->_config->getLanguage()->languageAvailable($category_id, 'faqcategories');
1374
        $translated = [];
1375
1376
        foreach ($existcatlang as $language) {
1377
            $query = sprintf("
1378
               SELECT
1379
                  name, description
1380
               FROM
1381
                   %sfaqcategories
1382
               WHERE
1383
                   id = %d
1384
               AND
1385
                   lang = '%s'",
1386
               PMF_Db::getTablePrefix(),
1387
               $category_id,
1388
               $language);
1389
            $result = $this->_config->getDb()->query($query);
1390
            if ($row = $this->_config->getDb()->fetchArray($result)) {
1391
                $translated[$languageCodes[strtoupper($language)]] = $row['name'].('' == $row['description'] ? '' : '  ('.$row['description'].')');
1392
            }
1393
        }
1394
        ksort($translated);
1395
1396
        return $translated;
1397
    }
1398
1399
    /**
1400
     * Create all languages which can be used for translation as <option>.
1401
     *
1402
     * @param int    $category_id   Category id
1403
     * @param string $selected_lang Selected language
1404
     *
1405
     * @return string
1406
     */
1407
    public function getCategoryLanguagesToTranslate($category_id, $selected_lang)
1408
    {
1409
        $output = '';
1410
        $existcatlang = $this->_config->getLanguage()->languageAvailable($category_id, 'faqcategories');
1411
1412
        foreach (PMF_Language::getAvailableLanguages() as $lang => $langname) {
1413
            if (!in_array(strtolower($lang), $existcatlang)) {
1414
                $output .= "\t<option value=\"".strtolower($lang).'"';
1415
                if ($lang == $selected_lang) {
1416
                    $output .= ' selected="selected"';
1417
                }
1418
                $output .=  '>'.$langname."</option>\n";
1419
            }
1420
        }
1421
1422
        return $output;
1423
    }
1424
1425
    /**
1426
     * Gets all categories which are not translated in actual language
1427
     * to add in this->categories (used in admin section).
1428
     */
1429
    public function getMissingCategories()
1430
    {
1431
        $query = sprintf('
1432
            SELECT
1433
                id, lang, parent_id, name, description, user_id
1434
            FROM
1435
                %sfaqcategories',
1436
            PMF_Db::getTablePrefix());
1437 View Code Duplication
        if (isset($this->language) && preg_match("/^[a-z\-]{2,}$/", $this->language)) {
1438
            $query .= " WHERE lang != '".$this->language."'";
1439
        }
1440
        $query .= ' ORDER BY id';
1441
        $result = $this->_config->getDb()->query($query);
1442 View Code Duplication
        while ($row = $this->_config->getDb()->fetchArray($result)) {
1443
            if (!array_key_exists($row['id'], $this->categoryName)) {
1444
                $this->categoryName[$row['id']] = $row;
1445
                $this->categories[$row['id']] = &$this->categoryName[$row['id']];
1446
                $this->children[$row['parent_id']][$row['id']] = &$this->categoryName[$row['id']];
1447
            }
1448
        }
1449
    }
1450
1451
    /**
1452
     * Get number of nodes at the same parent_id level.
1453
     *
1454
     * @param int $parent_id Parent id
1455
     *
1456
     * @return int
1457
     */
1458 View Code Duplication
    public function numParent($parent_id)
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...
1459
    {
1460
        $query = sprintf('
1461
            SELECT distinct
1462
                id
1463
            FROM
1464
                %sfaqcategories
1465
            WHERE
1466
                parent_id = %d',
1467
            PMF_Db::getTablePrefix(),
1468
            $parent_id);
1469
        $result = $this->_config->getDb()->query($query);
1470
1471
        return $this->_config->getDb()->numRows($result);
1472
    }
1473
1474
    /**
1475
     * Adds the category permissions for users and groups.
1476
     *
1477
     * @param string $mode       'group' or 'user'
1478
     * @param array  $categories ID of the current category
1479
     * @param array  $ids        Array of group or user IDs
1480
     *
1481
     * @return bool
1482
     */
1483
    public function addPermission($mode, Array $categories, Array $ids)
1484
    {
1485
        if ('user' !== $mode && 'group' !== $mode) {
1486
            return false;
1487
        }
1488
1489
        foreach ($categories as $categoryId) {
1490
            foreach ($ids as $id) {
1491
                $query = sprintf(
1492
                    'SELECT * FROM %sfaqcategory_%s WHERE category_id = %d AND %s_id = %d',
1493
                    PMF_Db::getTablePrefix(),
1494
                    $mode,
1495
                    $categoryId,
1496
                    $mode,
1497
                    $id
1498
                );
1499
1500
                if ($this->_config->getDb()->numRows($this->_config->getDb()->query($query))) {
1501
                    continue;
1502
                }
1503
1504
                $query = sprintf(
1505
                    'INSERT INTO %sfaqcategory_%s (category_id, %s_id) VALUES (%d, %d)',
1506
                    PMF_Db::getTablePrefix(),
1507
                    $mode,
1508
                    $mode,
1509
                    $categoryId,
1510
                    $id
1511
                );
1512
1513
                $this->_config->getDb()->query($query);
1514
            }
1515
        }
1516
1517
        return true;
1518
    }
1519
1520
    /**
1521
     * Deletes the category permissions for users and groups.
1522
     *
1523
     * @param string $mode       'group' or 'user'
1524
     * @param array  $categories ID of the current category
1525
     *
1526
     * @return bool
1527
     */
1528 View Code Duplication
    public function deletePermission($mode, $categories)
1529
    {
1530
        if (!($mode == 'user' || $mode == 'group')) {
1531
            return false;
1532
        }
1533
        if (!is_array($categories)) {
1534
            return false;
1535
        }
1536
1537
        foreach ($categories as $category_id) {
1538
            $query = sprintf('
1539
                DELETE FROM
1540
                    %sfaqcategory_%s
1541
                WHERE
1542
                    category_id = %d',
1543
                PMF_Db::getTablePrefix(),
1544
                $mode,
1545
                $category_id);
1546
            $this->_config->getDb()->query($query);
1547
        }
1548
1549
        return true;
1550
    }
1551
1552
    /**
1553
     * Returns the category permissions for users and groups.
1554
     *
1555
     * @param string $mode       'group' or 'user'
1556
     * @param array  $categories Array of category ids
1557
     *
1558
     * @return array
1559
     */
1560
    public function getPermissions($mode, Array $categories)
1561
    {
1562
        $permissions = [];
1563
        if (!($mode === 'user' || $mode === 'group')) {
1564
            return $permissions;
1565
        }
1566
        if (!is_array($categories)) {
1567
            return $permissions;
1568
        }
1569
1570
        $query = sprintf('
1571
            SELECT
1572
                %s_id AS permission
1573
            FROM
1574
                %sfaqcategory_%s
1575
            WHERE
1576
                category_id IN (%s)',
1577
            $mode,
1578
            PMF_Db::getTablePrefix(),
1579
            $mode,
1580
            implode(', ', $categories));
1581
1582
        $result = $this->_config->getDb()->query($query);
1583
        while ($row = $this->_config->getDb()->fetchObject($result)) {
1584
            $permissions[] = $row->permission;
1585
        }
1586
1587
        return $permissions;
1588
    }
1589
1590
    /**
1591
     * Returns the number of records in each category.
1592
     *
1593
     * @return array
1594
     */
1595
    public function getNumberOfRecordsOfCategory()
1596
    {
1597
        $numRecordsByCat = [];
1598
1599
        $query = sprintf('
1600
            SELECT
1601
                fcr.category_id AS category_id,
1602
                COUNT(fcr.record_id) AS number
1603
            FROM
1604
                %sfaqcategoryrelations fcr, %sfaqdata fd
1605
            WHERE
1606
                fcr.record_id = fd.id
1607
            AND
1608
                fcr.record_lang = fd.lang
1609
            GROUP BY fcr.category_id',
1610
            PMF_Db::getTablePrefix(),
1611
            PMF_Db::getTablePrefix());
1612
1613
        $result = $this->_config->getDb()->query($query);
1614
1615
        if ($this->_config->getDb()->numRows($result) > 0) {
1616
            while ($row = $this->_config->getDb()->fetchObject($result)) {
1617
                $numRecordsByCat[$row->category_id] = $row->number;
1618
            }
1619
        }
1620
1621
        return $numRecordsByCat;
1622
    }
1623
1624
    /**
1625
     * Create a matrix for representing categories and faq records.
1626
     *
1627
     * @return array
1628
     */
1629
    public function getCategoryRecordsMatrix()
1630
    {
1631
        $matrix = [];
1632
1633
        $query = sprintf('
1634
            SELECT
1635
                fcr.category_id AS id_cat,
1636
                fd.id AS id
1637
            FROM
1638
                %sfaqdata fd
1639
            INNER JOIN
1640
                %sfaqcategoryrelations fcr
1641
            ON
1642
                fd.id = fcr.record_id
1643
            AND
1644
                fd.lang = fcr.category_lang
1645
            ORDER BY
1646
                fcr.category_id, fd.id',
1647
             PMF_Db::getTablePrefix(),
1648
             PMF_Db::getTablePrefix());
1649
        $result = $this->_config->getDb()->query($query);
1650
1651
        if ($this->_config->getDb()->numRows($result) > 0) {
1652
            while ($row = $this->_config->getDb()->fetchObject($result)) {
1653
                $matrix[$row->id_cat][$row->id] = true;
1654
            }
1655
        }
1656
1657
        return $matrix;
1658
    }
1659
1660
    /**
1661
     * Sets language.
1662
     *
1663
     * @param string $language
1664
     */
1665
    public function setLanguage($language)
1666
    {
1667
        $this->language = $language;
1668
    }
1669
}
1670