Test Setup Failed
Push — master ( 4dd98a...0dd2b0 )
by Yannick
519:15 queued 457:26
created

CourseCategoryManager::getCourseCategoryUrl()   D

Complexity

Conditions 11
Paths 768

Size

Total Lines 60
Code Lines 46

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
c 1
b 1
f 0
dl 0
loc 60
rs 4.1176
cc 11
eloc 46
nc 768
nop 5

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/* For licensing terms, see /license.txt */
3
4
/**
5
 * Class CourseCategoryManager
6
 */
7
class CourseCategoryManager
8
{
9
    /**
10
     * Returns whether we are in a mode where multiple URLs are configured to work
11
     * with course categories
12
     * @return bool
13
     */
14
    function isMultipleUrlSupport()
15
    {
16
        return api_get_configuration_value(
17
            'enable_multiple_url_support_for_course_category'
18
        );
19
    }
20
21
    /**
22
     * Returns the category fields from the database from an int ID
23
     * @param int $categoryId The category ID
24
     * @return array
25
     */
26
    function getCategoryById($categoryId)
27
    {
28
        $tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
29
        $categoryId = intval($categoryId);
30
        $sql = "SELECT * FROM $tbl_category WHERE id = $categoryId";
31
        $result = Database::query($sql);
32
        if (Database::num_rows($result)) {
33
            return Database::fetch_array($result, 'ASSOC');
34
        }
35
36
        return array();
37
    }
38
39
    /**
40
     * Get category details from a simple category code
41
     * @param string $category The literal category code
42
     * @return array
43
     */
44
    function getCategory($category)
45
    {
46
        $tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
47
        $category = Database::escape_string($category);
48
        $sql = "SELECT * FROM $tbl_category WHERE code ='$category'";
49
        $result = Database::query($sql);
50
        if (Database::num_rows($result)) {
51
            return Database::fetch_array($result, 'ASSOC');
52
        }
53
54
        return array();
55
    }
56
57
    /**
58
     * @param string $category
59
     *
60
     * @return array
61
     */
62
    function getCategories($category)
63
    {
64
        $tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
65
        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
66
        $category = Database::escape_string($category);
67
        $conditions = null;
68
        $whereCondition = '';
69
70 View Code Duplication
        if (self::isMultipleUrlSupport()) {
71
            $table = Database::get_main_table(
72
                TABLE_MAIN_ACCESS_URL_REL_COURSE_CATEGORY
73
            );
74
            $conditions = " INNER JOIN $table a ON (t1.id = a.course_category_id)";
75
            $whereCondition = " AND a.access_url_id = ".api_get_current_access_url_id(
76
                );
77
        }
78
79
        $parentIdCondition = " AND (t1.parent_id IS NULL OR t1.parent_id = '' )";
80
        if (!empty($category)) {
81
            $parentIdCondition = " AND t1.parent_id  = '$category' ";
82
        }
83
84
        $sql = "SELECT
85
                    t1.name,
86
                    t1.code,
87
                    t1.parent_id,
88
                    t1.tree_pos,
89
                    t1.children_count,
90
                    COUNT(DISTINCT t3.code) AS nbr_courses
91
                    FROM $tbl_category t1
92
                    $conditions
93
                    LEFT JOIN $tbl_category t2
94
                    ON t1.code = t2.parent_id
95
                    LEFT JOIN $tbl_course t3
96
                    ON t3.category_code=t1.code
97
                    WHERE
98
                        1 = 1
99
                        $parentIdCondition
100
                        $whereCondition
101
                    GROUP BY t1.name,
102
                             t1.code,
103
                             t1.parent_id,
104
                             t1.tree_pos,
105
                             t1.children_count
106
                    ORDER BY t1.tree_pos";
107
108
        $result = Database::query($sql);
109
110
        $categories = Database::store_result($result);
111
        foreach ($categories as $category) {
112
            $category['nbr_courses'] = 1;
113
        }
114
115
        return $categories;
116
    }
117
118
    /**
119
     * @param string $code
120
     * @param string $name
121
     * @param string $canHaveCourses
122
     * @param int $parent_id
123
     *
124
     * @return bool
125
     */
126
    function addNode($code, $name, $canHaveCourses, $parent_id)
127
    {
128
        $tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
129
        $code = trim($code);
130
        $name = trim($name);
131
        $parent_id = trim($parent_id);
132
133
        $code = CourseManager::generate_course_code($code);
134
        $sql = "SELECT 1 FROM $tbl_category
135
                WHERE code = '".Database::escape_string($code)."'";
136
        $result = Database::query($sql);
137
        if (Database::num_rows($result)) {
138
            return false;
139
        }
140
        $result = Database::query(
141
            "SELECT MAX(tree_pos) AS maxTreePos FROM $tbl_category"
142
        );
143
        $row = Database::fetch_array($result);
144
        $tree_pos = $row['maxTreePos'] + 1;
145
146
        $params = [
147
            'name' => $name,
148
            'code' => $code,
149
            'parent_id' => empty($parent_id) ? null : $parent_id,
150
            'tree_pos' => $tree_pos,
151
            'children_count' => 0,
152
            'auth_course_child' => $canHaveCourses,
153
            'auth_cat_child' => 'TRUE'
154
        ];
155
156
        $categoryId = Database::insert($tbl_category, $params);
157
158
        self::updateParentCategoryChildrenCount($parent_id, 1);
159
160
        if (self::isMultipleUrlSupport()) {
161
            self::addToUrl($categoryId);
162
        }
163
164
        return $categoryId;
165
    }
166
167
    /**
168
     * Recursive function that updates the count of children in the parent
169
     * @param string $categoryId Category ID
170
     * @param    int $delta The number to add or delete (1 to add one, -1 to remove one)
171
     */
172
    function updateParentCategoryChildrenCount($categoryId, $delta = 1)
173
    {
174
        $tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
175
        $categoryId = Database::escape_string($categoryId);
176
        $delta = intval($delta);
177
        // First get to the highest level possible in the tree
178
        $result = Database::query(
179
            "SELECT parent_id FROM $tbl_category WHERE code = '$categoryId'"
180
        );
181
        $row = Database::fetch_array($result);
182
        if ($row !== false and $row['parent_id'] != 0) {
183
            // if a parent was found, enter there to see if he's got one more parent
184
            self::updateParentCategoryChildrenCount($row['parent_id'], $delta);
185
        }
186
        // Now we're at the top, get back down to update each child
187
        //$children_count = courseCategoryChildrenCount($categoryId);
188
        if ($delta >= 0) {
189
            $sql = "UPDATE $tbl_category SET children_count = (children_count + $delta)
190
                    WHERE code = '$categoryId'";
191
        } else {
192
            $sql = "UPDATE $tbl_category SET children_count = (children_count - ".abs(
193
                    $delta
194
                ).")
195
                    WHERE code = '$categoryId'";
196
        }
197
        Database::query($sql);
198
    }
199
200
    /**
201
     * @param string $node
202
     */
203
    function deleteNode($node)
204
    {
205
        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
206
        $tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
207
208
        $node = Database::escape_string($node);
209
210
        $result = Database::query(
211
            "SELECT parent_id, tree_pos FROM $tbl_category WHERE code='$node'"
212
        );
213
214
        if ($row = Database::fetch_array($result)) {
215
            if (!empty($row['parent_id'])) {
216
                Database::query(
217
                    "UPDATE $tbl_course SET category_code = '".$row['parent_id']."' WHERE category_code='$node'"
218
                );
219
                Database::query(
220
                    "UPDATE $tbl_category SET parent_id='".$row['parent_id']."' WHERE parent_id='$node'"
221
                );
222
            } else {
223
                Database::query(
224
                    "UPDATE $tbl_course SET category_code='' WHERE category_code='$node'"
225
                );
226
                Database::query(
227
                    "UPDATE $tbl_category SET parent_id=NULL WHERE parent_id='$node'"
228
                );
229
            }
230
231
            Database::query(
232
                "UPDATE $tbl_category SET tree_pos=tree_pos-1 WHERE tree_pos > '".$row['tree_pos']."'"
233
            );
234
            Database::query("DELETE FROM $tbl_category WHERE code='$node'");
235
236
            if (!empty($row['parent_id'])) {
237
                updateParentCategoryChildrenCount($row['parent_id'], -1);
238
            }
239
        }
240
    }
241
242
    /**
243
     * @param string $code
244
     * @param string $name
245
     * @param string $canHaveCourses
246
     * @param string $old_code
247
     * @return bool
248
     */
249
    function editNode($code, $name, $canHaveCourses, $old_code)
250
    {
251
        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
252
        $tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
253
254
        $code = trim(Database::escape_string($code));
255
        $name = trim(Database::escape_string($name));
256
        $old_code = Database::escape_string($old_code);
257
        $canHaveCourses = Database::escape_string($canHaveCourses);
258
259
        $code = CourseManager::generate_course_code($code);
260
        // Updating category
261
        $sql = "UPDATE $tbl_category SET name='$name', code='$code', auth_course_child = '$canHaveCourses'
262
                WHERE code = '$old_code'";
263
        Database::query($sql);
264
265
        // Updating children
266
        $sql = "UPDATE $tbl_category SET parent_id = '$code'
267
                WHERE parent_id = '$old_code'";
268
        Database::query($sql);
269
270
        // Updating course category
271
        $sql = "UPDATE $tbl_course SET category_code = '$code'
272
                WHERE category_code = '$old_code' ";
273
        Database::query($sql);
274
275
        return true;
276
    }
277
278
    /**
279
     * Move a node up on display
280
     * @param string $code
281
     * @param int $tree_pos
282
     * @param string $parent_id
283
     *
284
     * @return bool
285
     */
286
    function moveNodeUp($code, $tree_pos, $parent_id)
287
    {
288
        $tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
289
        $code = Database::escape_string($code);
290
        $tree_pos = intval($tree_pos);
291
        $parent_id = Database::escape_string($parent_id);
292
293
        $parentIdCondition = " AND (parent_id IS NULL OR parent_id = '' )";
294
        if (!empty($parent_id)) {
295
            $parentIdCondition = " AND parent_id = '$parent_id' ";
296
        }
297
298
        $sql = "SELECT code,tree_pos
299
                FROM $tbl_category
300
                WHERE
301
                    tree_pos < $tree_pos
302
                    $parentIdCondition
303
                ORDER BY tree_pos DESC
304
                LIMIT 0,1";
305
306
        $result = Database::query($sql);
307
        if (!$row = Database::fetch_array($result)) {
308
            $sql = "SELECT code, tree_pos
309
                    FROM $tbl_category
310
                    WHERE
311
                        tree_pos > $tree_pos
312
                        $parentIdCondition
313
                    ORDER BY tree_pos DESC
314
                    LIMIT 0,1";
315
            $result2 = Database::query($sql);
316
            if (!$row = Database::fetch_array($result2)) {
317
                return false;
318
            }
319
        }
320
321
        $sql = "UPDATE $tbl_category
322
                SET tree_pos ='".$row['tree_pos']."'
323
                WHERE code='$code'";
324
        Database::query($sql);
325
326
        $sql = "UPDATE $tbl_category
327
                SET tree_pos = '$tree_pos'
328
                WHERE code= '".$row['code']."'";
329
        Database::query($sql);
330
331
        return true;
332
    }
333
334
    /**
335
     * Counts the number of children categories a category has
336
     * @param int $categoryId The ID of the category of which we want to count the children
337
     * @param int $count The number of subcategories we counted this far
0 ignored issues
show
Bug introduced by
There is no parameter named $count. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
338
     * @return mixed The number of subcategories this category has
339
     */
340
    function courseCategoryChildrenCount($categoryId)
341
    {
342
        $tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
343
        $categoryId = intval($categoryId);
344
        $count = 0;
345
        if (empty($categoryId)) {
346
            return 0;
347
        }
348
        $sql = "SELECT id, code FROM $tbl_category WHERE parent_id = $categoryId";
349
        $result = Database::query($sql);
350
        while ($row = Database::fetch_array($result)) {
351
            $count += self::courseCategoryChildrenCount($row['id']);
352
        }
353
        $sql = "UPDATE $tbl_category SET children_count = $count WHERE id = $categoryId";
354
        Database::query($sql);
355
356
        return $count + 1;
357
    }
358
359
    /**
360
     * @param string $categoryCode
361
     *
362
     * @return array
363
     */
364 View Code Duplication
    function getChildren($categoryCode)
365
    {
366
        $tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
367
        $categoryCode = Database::escape_string($categoryCode);
368
        $result = Database::query(
369
            "SELECT code, id FROM $tbl_category WHERE parent_id = '$categoryCode'"
370
        );
371
        $children = array();
372
        while ($row = Database::fetch_array($result, 'ASSOC')) {
373
            $children[] = $row;
374
            $subChildren = self::getChildren($row['code']);
375
            $children = array_merge($children, $subChildren);
376
        }
377
378
        return $children;
379
    }
380
381
    /**
382
     * @param string $categoryCode
383
     *
384
     * @return array
385
     */
386
    function getParents($categoryCode)
387
    {
388
        if (empty($categoryCode)) {
389
            return array();
390
        }
391
392
        $tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
393
        $categoryCode = Database::escape_string($categoryCode);
394
        $sql = "SELECT code, parent_id FROM $tbl_category
395
                WHERE code = '$categoryCode'";
396
397
        $result = Database::query($sql);
398
        $children = array();
399
        while ($row = Database::fetch_array($result, 'ASSOC')) {
400
            $parent = self::getCategory($row['parent_id']);
401
            $children[] = $row;
402
            $subChildren = self::getParents($parent['code']);
403
            $children = array_merge($children, $subChildren);
404
        }
405
406
        return $children;
407
    }
408
409
    /**
410
     * @param string $categoryCode
411
     * @return null|string
412
     */
413
    function getParentsToString($categoryCode)
414
    {
415
        $parents = self::getParents($categoryCode);
416
417
        if (!empty($parents)) {
418
            $parents = array_reverse($parents);
419
            $categories = array();
420
            foreach ($parents as $category) {
421
                $categories[] = $category['code'];
422
            }
423
            $categoriesInString = implode(' > ', $categories).' > ';
424
425
            return $categoriesInString;
426
        }
427
428
        return null;
429
    }
430
431
    /**
432
     * @param string $categorySource
433
     *
434
     * @return string
435
     */
436
    function listCategories($categorySource)
437
    {
438
        $categorySource = isset($categorySource) ? $categorySource : null;
439
        $categories = self::getCategories($categorySource);
440
441
        if (count($categories) > 0) {
442
            $table = new HTML_Table(array('class' => 'data_table'));
443
            $column = 0;
444
            $row = 0;
445
            $headers = array(
446
                get_lang('Category'),
447
                get_lang('CategoriesNumber'),
448
                get_lang('Courses'),
449
                get_lang('Actions')
450
            );
451
            foreach ($headers as $header) {
452
                $table->setHeaderContents($row, $column, $header);
453
                $column++;
454
            }
455
            $row++;
456
            $mainUrl = api_get_path(
457
                    WEB_CODE_PATH
458
                ).'admin/course_category.php?category='.$categorySource;
459
460
            $editIcon = Display::return_icon(
461
                'edit.png',
462
                get_lang('EditNode'),
463
                null,
464
                ICON_SIZE_SMALL
465
            );
466
            $deleteIcon = Display::return_icon(
467
                'delete.png',
468
                get_lang('DeleteNode'),
469
                null,
470
                ICON_SIZE_SMALL
471
            );
472
            $moveIcon = Display::return_icon(
473
                'up.png',
474
                get_lang('UpInSameLevel'),
475
                null,
476
                ICON_SIZE_SMALL
477
            );
478
479
            foreach ($categories as $category) {
480
481
                $editUrl = $mainUrl.'&id='.$category['code'].'&action=edit';
482
                $moveUrl = $mainUrl.'&id='.$category['code'].'&action=moveUp&tree_pos='.$category['tree_pos'];
483
                $deleteUrl = $mainUrl.'&id='.$category['code'].'&action=delete';
484
485
                $actions = Display::url($editIcon, $editUrl).Display::url(
486
                        $moveIcon,
487
                        $moveUrl
488
                    ).Display::url($deleteIcon, $deleteUrl);
489
                $url = api_get_path(
490
                        WEB_CODE_PATH
491
                    ).'admin/course_category.php?category='.$category['code'];
492
                $title = Display::url(
493
                    Display::return_icon(
494
                        'folder_document.gif',
495
                        get_lang('OpenNode'),
496
                        null,
497
                        ICON_SIZE_SMALL
498
                    ).' '.$category['name'],
499
                    $url
500
                );
501
                $content = array(
502
                    $title,
503
                    $category['children_count'],
504
                    $category['nbr_courses'],
505
                    $actions
506
                );
507
                $column = 0;
508
                foreach ($content as $value) {
509
                    $table->setCellContents($row, $column, $value);
510
                    $column++;
511
                }
512
                $row++;
513
            }
514
515
            return $table->toHtml();
516
        } else {
517
            return Display::return_message(get_lang("NoCategories"), 'warning');
518
        }
519
    }
520
521
    /**
522
     * @return array
523
     */
524
    function getCategoriesToDisplayInHomePage()
525
    {
526
        $tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
527
        $sql = "SELECT name FROM $tbl_category
528
                WHERE parent_id IS NULL
529
                ORDER BY tree_pos";
530
531
        return Database::store_result(Database::query($sql));
0 ignored issues
show
Bug introduced by
It seems like \Database::query($sql) can be null; however, store_result() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
532
    }
533
534
    /**
535
     * @param int $id
536
     *
537
     * @return bool
538
     */
539
    function addToUrl($id)
540
    {
541
        if (!self::isMultipleUrlSupport()) {
542
            return false;
543
        }
544
545
        UrlManager::addCourseCategoryListToUrl(
546
            array($id),
547
            array(api_get_current_access_url_id())
548
        );
549
    }
550
551
    /**
552
     * @param string $categoryCode
553
     *
554
     * @return array
555
     */
556
    function getCategoriesCanBeAddedInCourse($categoryCode)
557
    {
558
        $conditions = null;
559
        $whereCondition = null;
560 View Code Duplication
        if (self::isMultipleUrlSupport()) {
561
            $table = Database::get_main_table(
562
                TABLE_MAIN_ACCESS_URL_REL_COURSE_CATEGORY
563
            );
564
            $conditions = " INNER JOIN $table a ON (c.id = a.course_category_id)";
565
            $whereCondition = " AND a.access_url_id = ".api_get_current_access_url_id();
566
        }
567
568
        $tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
569
        $sql = "SELECT code, name
570
                FROM $tbl_category c
571
                $conditions
572
                WHERE (auth_course_child = 'TRUE' OR code = '".Database::escape_string(
573
                $categoryCode
574
            )."')
575
                       $whereCondition
576
                ORDER BY tree_pos";
577
        $res = Database::query($sql);
578
579
        $categories[''] = '-';
580
        while ($cat = Database::fetch_array($res)) {
581
            $categories[$cat['code']] = '('.$cat['code'].') '.$cat['name'];
582
            ksort($categories);
583
        }
584
585
        return $categories;
586
    }
587
588
    /**
589
     * @return array
590
     */
591
    function browseCourseCategories()
592
    {
593
        $tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
594
        $conditions = null;
595
        $whereCondition = null;
596
597 View Code Duplication
        if (self::isMultipleUrlSupport()) {
598
            $table = Database::get_main_table(
599
                TABLE_MAIN_ACCESS_URL_REL_COURSE_CATEGORY
600
            );
601
            $conditions = " INNER JOIN $table a ON (c.id = a.course_category_id)";
602
            $whereCondition = " WHERE a.access_url_id = ".api_get_current_access_url_id(
603
                );
604
        }
605
        $sql = "SELECT c.* FROM $tbl_category c
606
                $conditions
607
                $whereCondition
608
                ORDER BY tree_pos ASC";
609
        $result = Database::query($sql);
610
        $url_access_id = 1;
611
        if (api_is_multiple_url_enabled()) {
612
            $url_access_id = api_get_current_access_url_id();
613
        }
614
        $countCourses = CourseManager:: countAvailableCourses($url_access_id);
615
616
        $categories = array();
617
        $categories[0][0] = array(
618
            'id' => 0,
619
            'name' => get_lang('DisplayAll'),
620
            'code' => 'ALL',
621
            'parent_id' => null,
622
            'tree_pos' => 0,
623
            'count_courses' => $countCourses
624
625
        );
626
        while ($row = Database::fetch_array($result)) {
627
            $count_courses = self::countCoursesInCategory($row['code']);
628
            $row['count_courses'] = $count_courses;
629
            if (!isset($row['parent_id'])) {
630
                $categories[0][$row['tree_pos']] = $row;
631
            } else {
632
                $categories[$row['parent_id']][$row['tree_pos']] = $row;
633
            }
634
        }
635
636
        $count_courses = self::countCoursesInCategory();
637
638
        $categories[0][count($categories[0]) + 1] = array(
639
            'id' => 0,
640
            'name' => get_lang('None'),
641
            'code' => 'NONE',
642
            'parent_id' => null,
643
            'tree_pos' => $row['tree_pos'] + 1,
644
            'children_count' => 0,
645
            'auth_course_child' => true,
646
            'auth_cat_child' => true,
647
            'count_courses' => $count_courses
648
        );
649
650
        return $categories;
651
    }
652
653
    /**
654
     * @param string $category_code
655
     * @param string $searchTerm
656
     * @return int
657
     */
658
    function countCoursesInCategory($category_code = "", $searchTerm = '')
659
    {
660
        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
661
        $categoryCode = Database::escape_string($category_code);
662
        $searchTerm = Database::escape_string($searchTerm);
663
        $categoryFilter = '';
664
        $searchFilter = '';
665
666
        $specialCourseList = CourseManager::get_special_course_list();
667
668
        $without_special_courses = '';
669
        if (!empty($specialCourseList)) {
670
            $without_special_courses = ' AND course.code NOT IN ('.implode(
671
                    ',',
672
                    $specialCourseList
673
                ).')';
674
        }
675
676
        $visibilityCondition = null;
677
        $hidePrivate = api_get_setting('platform.course_catalog_hide_private');
678 View Code Duplication
        if ($hidePrivate === 'true') {
679
            $courseInfo = api_get_course_info();
680
            $courseVisibility = $courseInfo['visibility'];
681
            $visibilityCondition = ' AND course.visibility <> 1';
682
        }
683
684
        if ($categoryCode == 'ALL') {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
685
            // Nothing to do
686
        } elseif ($categoryCode == 'NONE') {
687
            $categoryFilter = ' AND category_code = "" ';
688
        } else {
689
            $categoryFilter = ' AND category_code = "'.$categoryCode.'" ';
690
        }
691
692
        if (!empty($searchTerm)) {
693
            $searchFilter = ' AND (code LIKE "%'.$searchTerm.'%"
694
                OR title LIKE "%'.$searchTerm.'%"
695
                OR tutor_name LIKE "%'.$searchTerm.'%") ';
696
        }
697
698
        $sql = "SELECT * FROM $tbl_course
699
                WHERE
700
                    visibility != '0' AND
701
                    visibility != '4'
702
                    $categoryFilter
703
                    $searchFilter
704
                    $without_special_courses
705
                    $visibilityCondition
706
                ";
707
        // Showing only the courses of the current portal access_url_id.
708
709
        if (api_is_multiple_url_enabled()) {
710
            $url_access_id = api_get_current_access_url_id();
711
            if ($url_access_id != -1) {
712
                $tbl_url_rel_course = Database::get_main_table(
713
                    TABLE_MAIN_ACCESS_URL_REL_COURSE
714
                );
715
                $sql = "SELECT * FROM $tbl_course as course
716
                        INNER JOIN $tbl_url_rel_course as url_rel_course
717
                        ON (url_rel_course.c_id = course.id)
718
                        WHERE
719
                            access_url_id = $url_access_id AND
720
                            course.visibility != '0' AND
721
                            course.visibility != '4' AND
722
                            category_code = '$category_code'
723
                            $searchTerm
724
                            $without_special_courses
725
                            $visibilityCondition
726
                        ";
727
            }
728
        }
729
730
        return Database::num_rows(Database::query($sql));
0 ignored issues
show
Bug introduced by
It seems like \Database::query($sql) can be null; however, num_rows() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
731
    }
732
733
    /**
734
     * @param string $category_code
735
     * @param int $random_value
736
     * @param array $limit will be used if $random_value is not set.
737
     * This array should contains 'start' and 'length' keys
738
     * @return array
739
     */
740
    function browseCoursesInCategory(
741
        $category_code,
742
        $random_value = null,
743
        $limit = array()
744
    ) {
745
        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
746
747
        $specialCourseList = CourseManager::get_special_course_list();
748
749
        $without_special_courses = '';
750
        if (!empty($specialCourseList)) {
751
            $without_special_courses = ' AND course.code NOT IN ('.implode(
752
                    ',',
753
                    $specialCourseList
754
                ).')';
755
        }
756
        $visibilityCondition = null;
757
        $hidePrivate = api_get_setting('platform.course_catalog_hide_private');
758 View Code Duplication
        if ($hidePrivate === 'true') {
759
            $courseInfo = api_get_course_info();
760
            $courseVisibility = $courseInfo['visibility'];
761
            $visibilityCondition = ' AND course.visibility <> 1';
762
        }
763
        if (!empty($random_value)) {
764
            $random_value = intval($random_value);
765
766
            $sql = "SELECT COUNT(*) FROM $tbl_course";
767
            $result = Database::query($sql);
768
            list($num_records) = Database::fetch_row($result);
0 ignored issues
show
Bug introduced by
It seems like $result can be null; however, fetch_row() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
769
770
            if (api_is_multiple_url_enabled()) {
771
772
                $url_access_id = api_get_current_access_url_id();
773
                $tbl_url_rel_course = Database::get_main_table(
774
                    TABLE_MAIN_ACCESS_URL_REL_COURSE
775
                );
776
777
                $sql = "SELECT COUNT(*) FROM $tbl_course course
778
                        INNER JOIN $tbl_url_rel_course as url_rel_course
779
                        ON (url_rel_course.c_id = course.id)
780
                        WHERE access_url_id = $url_access_id ";
781
                $result = Database::query($sql);
782
                list($num_records) = Database::fetch_row($result);
0 ignored issues
show
Bug introduced by
It seems like $result can be null; however, fetch_row() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
783
784
                $sql = "SELECT course.id FROM $tbl_course course
785
                        INNER JOIN $tbl_url_rel_course as url_rel_course
786
                        ON (url_rel_course.c_id = course.id)
787
                        WHERE
788
                            access_url_id = $url_access_id AND
789
                            RAND()*$num_records< $random_value
790
                            $without_special_courses $visibilityCondition
791
                        ORDER BY RAND()
792
                        LIMIT 0, $random_value";
793
            } else {
794
                $sql = "SELECT id FROM $tbl_course course
795
                        WHERE RAND()*$num_records< $random_value $without_special_courses $visibilityCondition
796
                        ORDER BY RAND()
797
                        LIMIT 0, $random_value";
798
            }
799
800
            $result = Database::query($sql);
801
            $id_in = null;
802
            while (list($id) = Database::fetch_row($result)) {
0 ignored issues
show
Bug introduced by
It seems like $result can be null; however, fetch_row() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
803
                if ($id_in) {
804
                    $id_in .= ",$id";
805
                } else {
806
                    $id_in = "$id";
807
                }
808
            }
809
            if ($id_in === null) {
810
                return array();
811
            }
812
            $sql = "SELECT * FROM $tbl_course WHERE id IN($id_in)";
813
        } else {
814
            $limitFilter = self::getLimitFilterFromArray($limit);
815
            $category_code = Database::escape_string($category_code);
816
            if (empty($category_code) || $category_code == "ALL") {
817
                $sql = "SELECT * FROM $tbl_course
818
                        WHERE
819
                            1=1
820
                            $without_special_courses
821
                            $visibilityCondition
822
                        ORDER BY title $limitFilter ";
823
            } else {
824
                if ($category_code == 'NONE') {
825
                    $category_code = '';
826
                }
827
                $sql = "SELECT * FROM $tbl_course
828
                        WHERE
829
                            category_code='$category_code'
830
                            $without_special_courses
831
                            $visibilityCondition
832
                        ORDER BY title $limitFilter ";
833
            }
834
835
            //showing only the courses of the current Chamilo access_url_id
836 View Code Duplication
            if (api_is_multiple_url_enabled()) {
837
                $url_access_id = api_get_current_access_url_id();
838
                $tbl_url_rel_course = Database::get_main_table(
839
                    TABLE_MAIN_ACCESS_URL_REL_COURSE
840
                );
841
                if ($category_code != "ALL") {
842
                    $sql = "SELECT * FROM $tbl_course as course
843
                            INNER JOIN $tbl_url_rel_course as url_rel_course
844
                            ON (url_rel_course.c_id = course.id)
845
                            WHERE
846
                                access_url_id = $url_access_id AND
847
                                category_code='$category_code'
848
                                $without_special_courses
849
                                $visibilityCondition
850
                            ORDER BY title $limitFilter";
851
                } else {
852
                    $sql = "SELECT * FROM $tbl_course as course
853
                            INNER JOIN $tbl_url_rel_course as url_rel_course
854
                            ON (url_rel_course.c_id = course.id)
855
                            WHERE
856
                                access_url_id = $url_access_id
857
                                $without_special_courses
858
                                $visibilityCondition
859
                            ORDER BY title $limitFilter";
860
                }
861
            }
862
        }
863
864
        $result = Database::query($sql);
865
        $courses = array();
866
        while ($row = Database::fetch_array($result)) {
867
            $row['registration_code'] = !empty($row['registration_code']);
868
            $count_users = CourseManager::get_users_count_in_course(
869
                $row['code']
870
            );
871
            $count_connections_last_month = Tracking::get_course_connections_count(
872
                $row['id'],
873
                0,
874
                api_get_utc_datetime(time() - (30 * 86400))
875
            );
876
877
            if ($row['tutor_name'] == '0') {
878
                $row['tutor_name'] = get_lang('NoManager');
879
            }
880
            $point_info = CourseManager::get_course_ranking($row['id'], 0);
881
            $courses[] = array(
882
                'real_id' => $row['id'],
883
                'point_info' => $point_info,
884
                'code' => $row['code'],
885
                'directory' => $row['directory'],
886
                'visual_code' => $row['visual_code'],
887
                'title' => $row['title'],
888
                'tutor' => $row['tutor_name'],
889
                'subscribe' => $row['subscribe'],
890
                'unsubscribe' => $row['unsubscribe'],
891
                'registration_code' => $row['registration_code'],
892
                'creation_date' => $row['creation_date'],
893
                'visibility' => $row['visibility'],
894
                'count_users' => $count_users,
895
                'count_connections' => $count_connections_last_month
896
            );
897
        }
898
899
        return $courses;
900
    }
901
902
    /**
903
     * create recursively all categories as option of the select passed in parameter.
904
     *
905
     * @param HTML_QuickForm_Element $element
906
     * @param string $defaultCode the option value to select by default (used mainly for edition of courses)
907
     * @param string $parentCode the parent category of the categories added (default=null for root category)
908
     * @param string $padding the indent param (you shouldn't indicate something here)
909
     */
910
    function setCategoriesInForm(
911
        $element,
912
        $defaultCode = null,
913
        $parentCode = null,
914
        $padding = null
915
    ) {
916
        $tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
917
        $conditions = null;
918
        $whereCondition = null;
919 View Code Duplication
        if (self::isMultipleUrlSupport()) {
920
            $table = Database::get_main_table(
921
                TABLE_MAIN_ACCESS_URL_REL_COURSE_CATEGORY
922
            );
923
            $conditions = " INNER JOIN $table a ON (c.id = a.course_category_id)";
924
            $whereCondition = " AND a.access_url_id = ".api_get_current_access_url_id(
925
                );
926
        }
927
928
        $sql = "SELECT code, name, auth_course_child, auth_cat_child
929
                FROM ".$tbl_category." c
930
                $conditions
931
                WHERE parent_id ".(empty($parentCode) ? "IS NULL" : "='".Database::escape_string(
932
                    $parentCode
933
                )."'")."
934
                $whereCondition
935
                ORDER BY name,  code";
936
        $res = Database::query($sql);
937
938
        while ($cat = Database::fetch_array($res, 'ASSOC')) {
939
            $params = $cat['auth_course_child'] == 'TRUE' ? '' : 'disabled';
940
            $params .= ($cat['code'] == $defaultCode) ? ' selected' : '';
941
            $option = $padding.' '.$cat['name'].' ('.$cat['code'].')';
942
943
            $element->addOption($option, $cat['code'], $params);
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class HTML_QuickForm_element as the method addOption() does only exist in the following sub-classes of HTML_QuickForm_element: HTML_QuickForm_advmultiselect, HTML_QuickForm_hiddenselect, HTML_QuickForm_select, SelectAjax, SelectLanguage, SelectTheme. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
944
            if ($cat['auth_cat_child'] == 'TRUE') {
945
                self::setCategoriesInForm(
946
                    $element,
947
                    $defaultCode,
948
                    $cat['code'],
949
                    $padding.' - '
950
                );
951
            }
952
        }
953
    }
954
955
    /**
956
     * @param array $list
957
     * @return array
958
     */
959
    function getCourseCategoryNotInList($list)
960
    {
961
        $table = Database::get_main_table(TABLE_MAIN_CATEGORY);
962
        if (empty($list)) {
963
            return array();
964
        }
965
966
        $list = array_map('intval', $list);
967
        $listToString = implode("','", $list);
968
969
        $sql = "SELECT * FROM $table
970
                WHERE id NOT IN ('$listToString') AND (parent_id IS NULL) ";
971
        $result = Database::query($sql);
972
973
        return Database::store_result($result, 'ASSOC');
974
    }
975
976
    /**
977
     * @param string $keyword
978
     * @return array|null
979
     */
980
    function searchCategoryByKeyword($keyword)
981
    {
982
        if (empty($keyword)) {
983
            return null;
984
        }
985
986
        $tableCategory = Database::get_main_table(TABLE_MAIN_CATEGORY);
987
        $conditions = null;
988
        $whereCondition = null;
989 View Code Duplication
        if (self::isMultipleUrlSupport()) {
990
            $table = Database::get_main_table(
991
                TABLE_MAIN_ACCESS_URL_REL_COURSE_CATEGORY
992
            );
993
            $conditions = " INNER JOIN $table a ON (c.id = a.course_category_id)";
994
            $whereCondition = " AND a.access_url_id = ".api_get_current_access_url_id(
995
                );
996
        }
997
998
        $keyword = Database::escape_string($keyword);
999
1000
        $sql = "SELECT c.*, c.name as text
1001
                FROM $tableCategory c $conditions
1002
                WHERE
1003
                    (
1004
                        c.code LIKE '%$keyword%' OR name LIKE '%$keyword%'
1005
                    ) AND
1006
                    auth_course_child = 'TRUE'
1007
                    $whereCondition ";
1008
        $result = Database::query($sql);
1009
1010
        return Database::store_result($result, 'ASSOC');
1011
    }
1012
1013
    /**
1014
     * @param array $list
1015
     * @return array
1016
     */
1017
    function searchCategoryById($list)
1018
    {
1019
        if (empty($list)) {
1020
            return array();
1021
        } else {
1022
            $list = array_map('intval', $list);
1023
            $list = implode("','", $list);
1024
        }
1025
1026
        $tableCategory = Database::get_main_table(TABLE_MAIN_CATEGORY);
1027
        $conditions = null;
1028
        $whereCondition = null;
1029 View Code Duplication
        if (self::isMultipleUrlSupport()) {
1030
            $table = Database::get_main_table(
1031
                TABLE_MAIN_ACCESS_URL_REL_COURSE_CATEGORY
1032
            );
1033
            $conditions = " INNER JOIN $table a ON (c.id = a.course_category_id)";
1034
            $whereCondition = " AND a.access_url_id = ".api_get_current_access_url_id(
1035
                );
1036
        }
1037
1038
        $sql = "SELECT c.*, c.name as text FROM $tableCategory c $conditions
1039
                WHERE c.id IN $list $whereCondition";
1040
        $result = Database::query($sql);
1041
1042
        return Database::store_result($result, 'ASSOC');
1043
    }
1044
1045
    /**
1046
     * @return array
1047
     */
1048
    function getLimitArray()
1049
    {
1050
        $pageCurrent = isset($_REQUEST['pageCurrent']) ?
1051
            intval($_GET['pageCurrent']) :
1052
            1;
1053
        $pageLength = isset($_REQUEST['pageLength']) ?
1054
            intval($_GET['pageLength']) :
1055
            10;
1056
1057
        return array(
1058
            'start' => ($pageCurrent - 1) * $pageLength,
1059
            'current' => $pageCurrent,
1060
            'length' => $pageLength,
1061
        );
1062
    }
1063
1064
    /**
1065
     * Return LIMIT to filter SQL query
1066
     * @param array $limit
1067
     * @return string
1068
     */
1069
    function getLimitFilterFromArray($limit)
1070
    {
1071
        $limitFilter = '';
1072
        if (!empty($limit) && is_array($limit)) {
1073
            $limitStart = isset($limit['start']) ? $limit['start'] : 0;
1074
            $limitLength = isset($limit['length']) ? $limit['length'] : 10;
1075
            $limitFilter = 'LIMIT '.$limitStart.', '.$limitLength;
1076
        }
1077
1078
        return $limitFilter;
1079
    }
1080
1081
    /**
1082
     * Get Pagination HTML div
1083
     * @param $pageCurrent
1084
     * @param $pageLength
1085
     * @param $pageTotal
1086
     * @return string
1087
     */
1088
    function getCatalogPagination($pageCurrent, $pageLength, $pageTotal)
1089
    {
1090
        // Start empty html
1091
        $pageDiv = '';
1092
        $html = '';
1093
        $pageBottom = max(1, $pageCurrent - 3);
1094
        $pageTop = min($pageTotal, $pageCurrent + 3);
1095
1096
        if ($pageBottom > 1) {
1097
            $pageDiv .= self::getPageNumberItem(1, $pageLength);
1098
            if ($pageBottom > 2) {
1099
                $pageDiv .= self::getPageNumberItem(
1100
                    $pageBottom - 1,
1101
                    $pageLength,
1102
                    null,
1103
                    '...'
1104
                );
1105
            }
1106
        } else {
0 ignored issues
show
Unused Code introduced by
This else statement is empty and can be removed.

This check looks for the else branches of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These else branches can be removed.

if (rand(1, 6) > 3) {
print "Check failed";
} else {
    //print "Check succeeded";
}

could be turned into

if (rand(1, 6) > 3) {
    print "Check failed";
}

This is much more concise to read.

Loading history...
1107
            // Nothing to do
1108
        }
1109
1110
        // For each page add its page button to html
1111
        for (
1112
            $i = $pageBottom;
1113
            $i <= $pageTop;
1114
            $i++
1115
        ) {
1116
            if ($i === $pageCurrent) {
1117
                $pageItemAttributes = array('class' => 'active');
1118
            } else {
1119
                $pageItemAttributes = array();
1120
            }
1121
            $pageDiv .= self::getPageNumberItem($i, $pageLength, $pageItemAttributes);
1122
1123
        }
1124
        // Check if current page is the last page
1125
1126
        if ($pageTop < $pageTotal) {
1127
            if ($pageTop < ($pageTotal - 1)) {
1128
                $pageDiv .= self::getPageNumberItem(
1129
                    $pageTop + 1,
1130
                    $pageLength,
1131
                    null,
1132
                    '...'
1133
                );
1134
            }
1135
            $pageDiv .= self::getPageNumberItem($pageTotal, $pageLength);
1136
        }
1137
1138
        // Complete pagination html
1139
        $pageDiv = Display::tag('ul', $pageDiv, array('class' => 'pagination'));
1140
1141
1142
        $html .= '<nav>'.$pageDiv.'</nav>';
1143
1144
        return $html;
1145
    }
1146
1147
    /**
1148
     * Return URL to course catalog
1149
     * @param int $pageCurrent
1150
     * @param int $pageLength
1151
     * @param string $categoryCode
1152
     * @param int $hiddenLinks
1153
     * @param string $action
1154
     * @return string
1155
     */
1156
    function getCourseCategoryUrl(
1157
        $pageCurrent,
1158
        $pageLength,
1159
        $categoryCode = null,
1160
        $hiddenLinks = null,
1161
        $action = null
1162
    ) {
1163
        $requestAction = isset($_REQUEST['action']) ? Security::remove_XSS(
1164
            $_REQUEST['action']
1165
        ) : null;
1166
        $action = isset($action) ? Security::remove_XSS(
1167
            $action
1168
        ) : $requestAction;
1169
        $searchTerm = isset($_REQUEST['search_term']) ? Security::remove_XSS(
1170
            $_REQUEST['search_term']
1171
        ) : null;
1172
1173
        if ($action === 'subscribe_user_with_password') {
1174
            $action = 'subscribe';
1175
        }
1176
1177
        $categoryCodeRequest = isset($_REQUEST['category_code']) ? Security::remove_XSS(
1178
            $_REQUEST['category_code']
1179
        ) : null;
1180
        $categoryCode = isset($categoryCode) ? Security::remove_XSS(
1181
            $categoryCode
1182
        ) : $categoryCodeRequest;
1183
1184
        $hiddenLinksRequest = isset($_REQUEST['hidden_links']) ? Security::remove_XSS(
1185
            $_REQUEST['hidden_links']
1186
        ) : null;
1187
        $hiddenLinks = isset($hiddenLinks) ? Security::remove_XSS(
1188
            $hiddenLinksRequest
1189
        ) : $categoryCodeRequest;
1190
1191
        // Start URL with params
1192
        $pageUrl = api_get_self().
1193
            '?action='.$action.
1194
            '&category_code='.$categoryCode.
1195
            '&hidden_links='.$hiddenLinks.
1196
            '&pageCurrent='.$pageCurrent.
1197
            '&pageLength='.$pageLength;
1198
1199
        switch ($action) {
1200
            case 'subscribe' :
1201
                // for search
1202
                $pageUrl .=
1203
                    '&search_term='.$searchTerm.
1204
                    '&search_course=1'.
1205
                    '&sec_token='.$_SESSION['sec_token'];
1206
                break;
1207
            case 'display_courses' :
1208
                // No break
1209
            default :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a DEFAULT statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in the default statement.

switch ($expr) {
    default : //wrong
        doSomething();
        break;
}

switch ($expr) {
    default: //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
1210
                break;
1211
1212
        }
1213
1214
        return $pageUrl;
1215
    }
1216
1217
    /**
1218
     * Get li HTML of page number
1219
     * @param $pageNumber
1220
     * @param $pageLength
1221
     * @param array $liAttributes
1222
     * @param string $content
1223
     * @return string
1224
     */
1225
    function getPageNumberItem(
1226
        $pageNumber,
1227
        $pageLength,
1228
        $liAttributes = array(),
1229
        $content = ''
1230
    ) {
1231
        // Get page URL
1232
        $url = self::getCourseCategoryUrl(
1233
            $pageNumber,
1234
            $pageLength
1235
        );
1236
1237
        // If is current page ('active' class) clear URL
1238
        if (isset($liAttributes) && is_array(
1239
                $liAttributes
1240
            ) && isset($liAttributes['class'])
1241
        ) {
1242
            if (strpos('active', $liAttributes['class']) !== false) {
1243
                $url = '';
1244
            }
1245
        }
1246
1247
        $content = !empty($content) ? $content : $pageNumber;
1248
1249
        return Display::tag(
1250
            'li',
1251
            Display::url(
1252
                $content,
1253
                $url
1254
            ),
1255
            $liAttributes
0 ignored issues
show
Bug introduced by
It seems like $liAttributes can also be of type null; however, Display::tag() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
1256
        );
1257
    }
1258
1259
    /**
1260
     * Return the name tool by action
1261
     * @param string $action
1262
     * @return string
1263
     */
1264
    function getCourseCatalogNameTools($action)
1265
    {
1266
        $nameTools = get_lang('SortMyCourses');
1267
        if (empty($action)) {
1268
            return $nameTools; //should never happen
1269
        }
1270
1271
        switch ($action) {
1272
            case 'createcoursecategory':
1273
                $nameTools = get_lang('CreateCourseCategory');
1274
                break;
1275
            case 'subscribe':
1276
                $nameTools = get_lang('CourseManagement');
1277
                break;
1278
            case 'subscribe_user_with_password':
1279
                $nameTools = get_lang('CourseManagement');
1280
                break;
1281
            case 'display_random_courses':
1282
                // No break
1283
            case 'display_courses':
1284
                $nameTools = get_lang('CourseManagement');
1285
                break;
1286
            case 'display_sessions':
1287
                $nameTools = get_lang('Sessions');
1288
                break;
1289
            default :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a DEFAULT statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in the default statement.

switch ($expr) {
    default : //wrong
        doSomething();
        break;
}

switch ($expr) {
    default: //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
1290
                // Nothing to do
1291
                break;
1292
        }
1293
1294
        return $nameTools;
1295
    }
1296
1297
    /**
1298
     * CREATE TABLE IF NOT EXISTS access_url_rel_course_category (access_url_id int unsigned NOT NULL, course_category_id int unsigned NOT NULL, PRIMARY KEY (access_url_id, course_category_id));
1299
     */
1300
}
1301