Passed
Push — master ( a02707...7dc539 )
by Julito
12:00
created

CourseCategory::getCoursesInCategory()   B

Complexity

Conditions 6
Paths 24

Size

Total Lines 59
Code Lines 38

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 38
nc 24
nop 5
dl 0
loc 59
rs 8.6897
c 0
b 0
f 0

How to fix   Long Method   

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
3
/* For licensing terms, see /license.txt */
4
5
/**
6
 * Class CourseCategory.
7
 */
8
class CourseCategory
9
{
10
    /**
11
     * Returns the category fields from the database from an int ID.
12
     *
13
     * @param int $categoryId The category ID
14
     *
15
     * @return array
16
     */
17
    public static function getCategoryById($categoryId)
18
    {
19
        $table = Database::get_main_table(TABLE_MAIN_CATEGORY);
20
        $categoryId = (int) $categoryId;
21
        $sql = "SELECT * FROM $table WHERE id = $categoryId";
22
        $result = Database::query($sql);
23
        if (Database::num_rows($result)) {
24
            return Database::fetch_array($result, 'ASSOC');
25
        }
26
27
        return [];
28
    }
29
30
    /**
31
     * Get category details from a simple category code.
32
     *
33
     * @param string|null $categoryCode The literal category code
34
     *
35
     * @return array
36
     */
37
    public static function getCategory(string $categoryCode = null)
38
    {
39
        if (!empty($categoryCode)) {
40
            $table = Database::get_main_table(TABLE_MAIN_CATEGORY);
41
            $categoryCode = Database::escape_string($categoryCode);
42
            $sql = "SELECT * FROM $table WHERE code ='$categoryCode'";
43
            $result = Database::query($sql);
44
45
            if (Database::num_rows($result)) {
46
                $category = Database::fetch_array($result, 'ASSOC');
47
                if ($category) {
48
                    // Get access url id
49
                    $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE_CATEGORY);
50
                    $sql = "SELECT * FROM $table WHERE course_category_id = ".$category['id'];
51
                    $result = Database::query($sql);
52
                    $result = Database::fetch_array($result);
53
                    if ($result) {
54
                        $category['access_url_id'] = $result['access_url_id'];
55
                    }
56
57
                    return $category;
58
                }
59
            }
60
        }
61
62
        return [];
63
    }
64
65
    /**
66
     * @param int|null $category Optional. Parent category ID.
67
     *
68
     * @return array
69
     */
70
    public static function getCategories($category = null)
71
    {
72
        $tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
73
        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
74
        $tbl_course_rel_category = Database::get_main_table(TABLE_MAIN_COURSE_REL_CATEGORY);
75
        $category = (int) $category;
76
        $conditions = null;
77
78
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE_CATEGORY);
79
        $conditions = " INNER JOIN $table a ON (t1.id = a.course_category_id)";
80
        $whereCondition = " AND a.access_url_id = ".api_get_current_access_url_id();
81
        $allowBaseCategories = api_get_configuration_value('allow_base_course_category');
82
        if ($allowBaseCategories) {
83
            $whereCondition = " AND (a.access_url_id = ".api_get_current_access_url_id()." OR a.access_url_id = 1) ";
84
        }
85
86
        $parentIdCondition = " AND (t1.parent_id IS NULL OR t1.parent_id = '' )";
87
88
        if ($category) {
89
            $parentIdCondition = " AND t1.parent_id = $category ";
90
        }
91
92
        $sql = "SELECT
93
                t1.name,
94
                t1.code,
95
                t1.parent_id,
96
                t1.tree_pos,
97
                t1.children_count,
98
                COUNT(DISTINCT t4.code) AS nbr_courses,
99
                a.access_url_id
100
                FROM $tbl_category t1
101
                $conditions
102
                LEFT JOIN $tbl_category t2
103
                ON t1.id = t2.parent_id
104
                LEFT JOIN $tbl_course_rel_category t3
105
                ON t1.id = t3.course_category_id
106
                LEFT JOIN $tbl_course t4
107
                ON t3.course_id = t4.id
108
                WHERE
109
                    1 = 1
110
                    $parentIdCondition
111
                    $whereCondition
112
                GROUP BY t1.name,
113
                         t1.code,
114
                         t1.parent_id,
115
                         t1.tree_pos,
116
                         t1.children_count
117
                ORDER BY t1.tree_pos
118
        ";
119
120
        $result = Database::query($sql);
121
122
        return Database::store_result($result, 'ASSOC');
123
    }
124
125
    /**
126
     * Returns a flat list of all course categories in this URL. If the
127
     * allow_base_course_category option is true, then also show the
128
     * course categories of the base URL.
129
     *
130
     * @return array [id, name, code, parent_id, tree_pos, children_count, number_courses]
131
     */
132
    public static function getAllCategories()
133
    {
134
        $tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
135
        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
136
137
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE_CATEGORY);
138
        $conditions = " INNER JOIN $table a ON (t1.id = a.course_category_id)";
139
        $whereCondition = " AND a.access_url_id = ".api_get_current_access_url_id();
140
        $allowBaseCategories = api_get_configuration_value('allow_base_course_category');
141
        if ($allowBaseCategories) {
142
            $whereCondition = " AND (a.access_url_id = ".api_get_current_access_url_id()." OR a.access_url_id = 1) ";
143
        }
144
145
        $sql = "SELECT
146
                t1.id,
147
                t1.name,
148
                t1.code,
149
                t1.parent_id,
150
                t1.tree_pos,
151
                t1.children_count,
152
                COUNT(DISTINCT t3.code) AS number_courses
153
                FROM $tbl_category t1
154
                $conditions
155
                LEFT JOIN $tbl_course t3
156
                ON t3.category_id=t1.id
157
                WHERE 1=1
158
                    $whereCondition
159
                GROUP BY
160
                    t1.name,
161
                    t1.code,
162
                    t1.parent_id,
163
                    t1.tree_pos,
164
                    t1.children_count
165
                ORDER BY t1.parent_id, t1.tree_pos";
166
167
        $result = Database::query($sql);
168
169
        return Database::store_result($result, 'ASSOC');
170
    }
171
172
    /**
173
     * @param string $code
174
     * @param string $name
175
     * @param string $canHaveCourses
176
     * @param int    $parent_id
177
     *
178
     * @return bool
179
     */
180
    public static function addNode($code, $name, $canHaveCourses, $parent_id)
181
    {
182
        $table = Database::get_main_table(TABLE_MAIN_CATEGORY);
183
        $code = trim($code);
184
        $name = trim($name);
185
        $parent_id = (int) $parent_id;
186
187
        $code = CourseManager::generate_course_code($code);
188
        $sql = "SELECT 1 FROM $table
189
                WHERE code = '".Database::escape_string($code)."'";
190
        $result = Database::query($sql);
191
        if (Database::num_rows($result)) {
192
            return false;
193
        }
194
        $result = Database::query("SELECT MAX(tree_pos) AS maxTreePos FROM $table");
195
        $row = Database::fetch_array($result);
196
        $tree_pos = $row['maxTreePos'] + 1;
197
198
        $params = [
199
            'name' => $name,
200
            'code' => $code,
201
            'parent_id' => empty($parent_id) ? null : $parent_id,
202
            'tree_pos' => $tree_pos,
203
            'children_count' => 0,
204
            'auth_course_child' => $canHaveCourses,
205
            'auth_cat_child' => 'TRUE',
206
        ];
207
208
        $categoryId = Database::insert($table, $params);
209
        if ($categoryId) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $categoryId of type false|integer is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
210
            self::updateParentCategoryChildrenCount($parent_id, 1);
211
            UrlManager::addCourseCategoryListToUrl(
212
                [$categoryId],
213
                [api_get_current_access_url_id()]
214
            );
215
216
            return $categoryId;
217
        }
218
219
        return false;
220
    }
221
222
    /**
223
     * Recursive function that updates the count of children in the parent.
224
     *
225
     * @param string $categoryId Category ID
226
     * @param int    $delta      The number to add or delete (1 to add one, -1 to remove one)
227
     */
228
    public static function updateParentCategoryChildrenCount($categoryId, $delta = 1)
229
    {
230
        $table = Database::get_main_table(TABLE_MAIN_CATEGORY);
231
        $categoryId = Database::escape_string($categoryId);
232
        $delta = (int) $delta;
233
        // First get to the highest level possible in the tree
234
        $result = Database::query("SELECT parent_id FROM $table WHERE id = '$categoryId'");
235
        $row = Database::fetch_array($result);
236
        if (false !== $row && 0 != $row['parent_id']) {
237
            // if a parent was found, enter there to see if he's got one more parent
238
            self::updateParentCategoryChildrenCount($row['parent_id'], $delta);
239
        }
240
        // Now we're at the top, get back down to update each child
241
        $sql = "UPDATE $table SET children_count = (children_count - ".abs($delta).") WHERE id = '$categoryId'";
242
        if ($delta >= 0) {
243
            $sql = "UPDATE $table SET children_count = (children_count + $delta) WHERE id = '$categoryId'";
244
        }
245
        Database::query($sql);
246
    }
247
248
    /**
249
     * @param string $node
250
     *
251
     * @return bool
252
     */
253
    public static function deleteNode($node)
254
    {
255
        $category = self::getCategory($node);
256
257
        if (empty($category)) {
258
            return false;
259
        }
260
261
        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
262
        $tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
263
        $node = Database::escape_string($node);
264
        $result = Database::query("SELECT parent_id, tree_pos FROM $tbl_category WHERE code='$node'");
265
266
        if ($row = Database::fetch_array($result)) {
267
            if (!empty($row['parent_id'])) {
268
                Database::query(
269
                    "UPDATE $tbl_course SET category_id = '".$row['parent_id']."' WHERE category_id = {$category['id']}"
270
                );
271
                Database::query("UPDATE $tbl_category SET parent_id='".$row['parent_id']."' WHERE parent_id='$node'");
272
            } else {
273
                Database::query("UPDATE $tbl_course SET category_id = NULL WHERE category_id = ".$category['id']);
274
                Database::query("UPDATE $tbl_category SET parent_id=NULL WHERE parent_id='$node'");
275
            }
276
277
            $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE_CATEGORY);
278
            $sql = "DELETE FROM $table WHERE course_category_id = ".$category['id'];
279
280
            Database::query($sql);
281
            Database::query("UPDATE $tbl_category SET tree_pos=tree_pos-1 WHERE tree_pos > '".$row['tree_pos']."'");
282
            Database::query("DELETE FROM $tbl_category WHERE code='$node'");
283
284
            if (!empty($row['parent_id'])) {
285
                self::updateParentCategoryChildrenCount($row['parent_id'], -1);
286
            }
287
288
            return true;
289
        }
290
    }
291
292
    /**
293
     * @param string $code
294
     * @param string $name
295
     * @param string $canHaveCourses
296
     * @param string $old_code
297
     *
298
     * @return bool
299
     */
300
    public static function editNode($code, $name, $canHaveCourses, $old_code)
301
    {
302
        $tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
303
304
        $code = trim(Database::escape_string($code));
305
        $name = trim(Database::escape_string($name));
306
        $old_code = Database::escape_string($old_code);
307
        $canHaveCourses = Database::escape_string($canHaveCourses);
308
309
        $code = CourseManager::generate_course_code($code);
310
        // Updating category
311
        $sql = "UPDATE $tbl_category SET
312
                    name='$name',
313
                    code='$code',
314
                    auth_course_child = '$canHaveCourses'
315
                WHERE code = '$old_code'";
316
        Database::query($sql);
317
318
        // Updating children
319
        $sql = "UPDATE $tbl_category SET parent_id = '$code'
320
            WHERE parent_id = '$old_code'";
321
        Database::query($sql);
322
323
        return true;
324
    }
325
326
    /**
327
     * Move a node up on display.
328
     *
329
     * @param string $code
330
     * @param int    $tree_pos
331
     * @param string $parent_id
332
     *
333
     * @return bool
334
     */
335
    public static function moveNodeUp($code, $tree_pos, $parent_id)
336
    {
337
        $table = Database::get_main_table(TABLE_MAIN_CATEGORY);
338
        $code = Database::escape_string($code);
339
        $tree_pos = (int) $tree_pos;
340
        $parent_id = Database::escape_string($parent_id);
341
342
        $parentIdCondition = " AND (parent_id IS NULL OR parent_id = '' )";
343
        if (!empty($parent_id)) {
344
            $parentIdCondition = " AND parent_id = '$parent_id' ";
345
        }
346
347
        $sql = "SELECT code,tree_pos
348
                FROM $table
349
                WHERE
350
                    tree_pos < $tree_pos
351
                    $parentIdCondition
352
                ORDER BY tree_pos DESC
353
                LIMIT 0,1";
354
355
        $result = Database::query($sql);
356
        if (!$row = Database::fetch_array($result)) {
357
            $sql = "SELECT code, tree_pos
358
                    FROM $table
359
                    WHERE
360
                        tree_pos > $tree_pos
361
                        $parentIdCondition
362
                    ORDER BY tree_pos DESC
363
                    LIMIT 0,1";
364
            $result2 = Database::query($sql);
365
            if (!$row = Database::fetch_array($result2)) {
366
                return false;
367
            }
368
        }
369
370
        $sql = "UPDATE $table
371
                SET tree_pos ='".$row['tree_pos']."'
372
                WHERE code='$code'";
373
        Database::query($sql);
374
375
        $sql = "UPDATE $table
376
                SET tree_pos = '$tree_pos'
377
                WHERE code= '".$row['code']."'";
378
        Database::query($sql);
379
380
        return true;
381
    }
382
383
    /**
384
     * Counts the number of children categories a category has.
385
     *
386
     * @param int $categoryId The ID of the category of which we want to count the children
387
     *
388
     * @return mixed The number of subcategories this category has
389
     */
390
    public static function courseCategoryChildrenCount($categoryId)
391
    {
392
        $table = Database::get_main_table(TABLE_MAIN_CATEGORY);
393
        $categoryId = (int) $categoryId;
394
        $count = 0;
395
        if (empty($categoryId)) {
396
            return 0;
397
        }
398
        $sql = "SELECT id, code FROM $table
399
                WHERE parent_id = $categoryId";
400
        $result = Database::query($sql);
401
        while ($row = Database::fetch_array($result)) {
402
            $count += self::courseCategoryChildrenCount($row['id']);
403
        }
404
        $sql = "UPDATE $table SET
405
                    children_count = $count
406
                WHERE id = $categoryId";
407
        Database::query($sql);
408
409
        return $count + 1;
410
    }
411
412
    /**
413
     * @param string $categoryCode
414
     *
415
     * @return array
416
     */
417
    public static function getChildren($categoryCode)
418
    {
419
        $table = Database::get_main_table(TABLE_MAIN_CATEGORY);
420
        $categoryCode = Database::escape_string($categoryCode);
421
        $sql = "SELECT code, id FROM $table
422
                WHERE parent_id = '$categoryCode'";
423
        $result = Database::query($sql);
424
        $children = [];
425
        while ($row = Database::fetch_array($result, 'ASSOC')) {
426
            $children[] = $row;
427
            $subChildren = self::getChildren($row['code']);
428
            $children = array_merge($children, $subChildren);
429
        }
430
431
        return $children;
432
    }
433
434
    /**
435
     * @param string $categoryCode
436
     *
437
     * @return array
438
     */
439
    public static function getParents($categoryCode)
440
    {
441
        if (empty($categoryCode)) {
442
            return [];
443
        }
444
445
        $table = Database::get_main_table(TABLE_MAIN_CATEGORY);
446
        $categoryCode = Database::escape_string($categoryCode);
447
        $sql = "SELECT code, parent_id
448
                FROM $table
449
                WHERE code = '$categoryCode'";
450
451
        $result = Database::query($sql);
452
        $children = [];
453
        while ($row = Database::fetch_array($result, 'ASSOC')) {
454
            $parent = self::getCategory($row['parent_id']);
455
            $children[] = $row;
456
            $subChildren = self::getParents($parent ? $parent['code'] : null);
457
            $children = array_merge($children, $subChildren);
458
        }
459
460
        return $children;
461
    }
462
463
    /**
464
     * @param string $categoryCode
465
     *
466
     * @return string|null
467
     */
468
    public static function getParentsToString($categoryCode)
469
    {
470
        $parents = self::getParents($categoryCode);
471
472
        if (!empty($parents)) {
473
            $parents = array_reverse($parents);
474
            $categories = [];
475
            foreach ($parents as $category) {
476
                $categories[] = $category['code'];
477
            }
478
479
            return implode(' > ', $categories).' > ';
480
        }
481
482
        return null;
483
    }
484
485
    /**
486
     * @param array
487
     *
488
     * @return string
489
     */
490
    public static function listCategories(array $categorySource = [])
491
    {
492
        $categories = self::getCategories($categorySource ? $categorySource['id'] : null);
493
        $categoryCode = $categorySource ? Security::remove_XSS($categorySource['code']) : '';
494
495
        if (count($categories) > 0) {
496
            $table = new HTML_Table(['class' => 'data_table']);
497
            $column = 0;
498
            $row = 0;
499
            $headers = [
500
                get_lang('Category'),
501
                get_lang('Sub-categories'),
502
                get_lang('Courses'),
503
                get_lang('Detail'),
504
            ];
505
            foreach ($headers as $header) {
506
                $table->setHeaderContents($row, $column, $header);
507
                $column++;
508
            }
509
            $row++;
510
            $mainUrl = api_get_path(WEB_CODE_PATH).'admin/course_category.php?category='.$categoryCode;
511
512
            $editIcon = Display::return_icon(
513
                'edit.png',
514
                get_lang('Edit this category'),
515
                null,
516
                ICON_SIZE_SMALL
517
            );
518
            $deleteIcon = Display::return_icon(
519
                'delete.png',
520
                get_lang('Delete this category'),
521
                null,
522
                ICON_SIZE_SMALL
523
            );
524
            $moveIcon = Display::return_icon(
525
                'up.png',
526
                get_lang('Up in same level'),
527
                null,
528
                ICON_SIZE_SMALL
529
            );
530
531
            $urlId = api_get_current_access_url_id();
532
            foreach ($categories as $category) {
533
                $editUrl = $mainUrl.'&id='.$category['code'].'&action=edit';
534
                $moveUrl = $mainUrl.'&id='.$category['code'].'&action=moveUp&tree_pos='.$category['tree_pos'];
535
                $deleteUrl = $mainUrl.'&id='.$category['code'].'&action=delete';
536
537
                $actions = [];
538
539
                if ($urlId == $category['access_url_id']) {
540
                    $actions[] = Display::url($editIcon, $editUrl);
541
                    $actions[] = Display::url($moveIcon, $moveUrl);
542
                    $actions[] = Display::url($deleteIcon, $deleteUrl);
543
                }
544
545
                $url = api_get_path(WEB_CODE_PATH).'admin/course_category.php?category='.$category['code'];
546
                $title = Display::url(
547
                    Display::return_icon(
548
                        'folder_document.gif',
549
                        get_lang('Open this category'),
550
                        null,
551
                        ICON_SIZE_SMALL
552
                    ).' '.$category['name'].' ('.$category['code'].')',
553
                    $url
554
                );
555
                $countCourses = self::countCoursesInCategory($category['code'], null, false);
0 ignored issues
show
Bug introduced by
The method countCoursesInCategory() does not exist on CourseCategory. ( Ignorable by Annotation )

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

555
                /** @scrutinizer ignore-call */ 
556
                $countCourses = self::countCoursesInCategory($category['code'], null, false);

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

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

Loading history...
556
                $content = [
557
                    $title,
558
                    $category['children_count'],
559
                    $countCourses,
560
                    implode('', $actions),
561
                ];
562
                $column = 0;
563
                foreach ($content as $value) {
564
                    $table->setCellContents($row, $column, $value);
565
                    $column++;
566
                }
567
                $row++;
568
            }
569
570
            return $table->toHtml();
571
        }
572
        return Display::return_message(get_lang('NoCategories'), 'warning');
573
    }
574
575
    /**
576
     * @return array
577
     */
578
    public static function getCategoriesToDisplayInHomePage()
579
    {
580
        $table = Database::get_main_table(TABLE_MAIN_CATEGORY);
581
        $sql = "SELECT name FROM $table
582
                WHERE parent_id IS NULL
583
                ORDER BY tree_pos";
584
585
        return Database::store_result(Database::query($sql));
586
    }
587
588
    /**
589
     * @param string $categoryCode
590
     *
591
     * @return array
592
     */
593
    public static function getCategoriesCanBeAddedInCourse($categoryCode)
594
    {
595
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE_CATEGORY);
596
        $conditions = " INNER JOIN $table a ON (c.id = a.course_category_id)";
597
        $whereCondition = ' AND a.access_url_id = '.api_get_current_access_url_id();
598
599
        $tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
600
        $sql = "SELECT c.id, c.code, name
601
                FROM $tbl_category c
602
                $conditions
603
                WHERE (auth_course_child = 'TRUE' OR code = '".Database::escape_string($categoryCode)."')
604
                $whereCondition
605
                ORDER BY tree_pos";
606
        $res = Database::query($sql);
607
608
        $categoryToAvoid = '';
609
        if (!api_is_platform_admin()) {
610
            $categoryToAvoid = api_get_configuration_value('course_category_code_to_use_as_model');
611
        }
612
        $categories[''] = '-';
0 ignored issues
show
Comprehensibility Best Practice introduced by
$categories was never initialized. Although not strictly required by PHP, it is generally a good practice to add $categories = array(); before regardless.
Loading history...
613
        while ($cat = Database::fetch_array($res)) {
614
            $categoryCode = $cat['code'];
615
            if (!empty($categoryToAvoid) && $categoryToAvoid == $categoryCode) {
616
                continue;
617
            }
618
            $categories[$cat['id']] = '('.$cat['code'].') '.$cat['name'];
619
            ksort($categories);
620
        }
621
622
        return $categories;
623
    }
624
625
    public static function getCoursesInCategory($category_code = '', $searchTerm = '', $avoidCourses = true, $conditions = [], $getCount = false)
626
{
627
        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
628
        $tblCourseCategory = Database::get_main_table(TABLE_MAIN_CATEGORY);
629
        $avoidCoursesCondition = '';
630
        if ($avoidCourses) {
631
            $avoidCoursesCondition = CoursesAndSessionsCatalog::getAvoidCourseCondition();
632
        }
633
634
        $categoryCode = Database::escape_string($category_code);
635
        $searchTerm = Database::escape_string($searchTerm);
636
637
        $visibilityCondition = CourseManager::getCourseVisibilitySQLCondition('course', true);
638
639
        $categoryJoin = '';
640
        $categoryFilter = '';
641
        if ('ALL' === $categoryCode) {
642
            // Nothing to do
643
        } elseif ('NONE' === $categoryCode) {
644
            $categoryFilter = ' AND course.category_id IS NULL ';
645
        } else {
646
            $categoryJoin = " INNER JOIN $tblCourseCategory cat ON course.category_id = cat.id ";
647
            $categoryFilter = ' AND cat.code = "'.$categoryCode.'" ';
648
        }
649
650
        $searchFilter = '';
651
        if (!empty($searchTerm)) {
652
            $searchFilter = ' AND (
653
                course.code LIKE "%'.$searchTerm.'%" OR
654
                course.title LIKE "%'.$searchTerm.'%" OR
655
                course.tutor_name LIKE "%'.$searchTerm.'%"
656
            ) ';
657
        }
658
659
        $urlCondition = ' url_rel_course.access_url_id = '.api_get_current_access_url_id().' AND';
660
        $tbl_url_rel_course = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
661
        $sql = "SELECT count(course.id) as count
662
                FROM $tbl_course as course
663
                INNER JOIN $tbl_url_rel_course as url_rel_course
664
                ON (url_rel_course.c_id = course.id)
665
                $categoryJoin
666
                WHERE
667
                    $urlCondition
668
                    course.visibility != '0' AND
669
                    course.visibility != '4'
670
                    $categoryFilter
671
                    $searchFilter
672
                    $avoidCoursesCondition
673
                    $visibilityCondition
674
            ";
675
676
        $result = Database::query($sql);
677
        if ($getCount) {
678
            $row = Database::fetch_array($result);
679
680
            return (int) $row['count'];
681
        }
682
683
        return Database::store_result($result, 'ASSOC');
684
    }
685
686
    /**
687
     * @param array $list
688
     *
689
     * @return array
690
     */
691
    public static function getCourseCategoryNotInList($list)
692
    {
693
        $table = Database::get_main_table(TABLE_MAIN_CATEGORY);
694
695
        if (empty($list)) {
696
            $sql = "SELECT * FROM $table
697
                    WHERE (parent_id IS NULL) ";
698
            $result = Database::query($sql);
699
700
            return Database::store_result($result, 'ASSOC');
701
        }
702
703
        $list = array_map('intval', $list);
704
        $listToString = implode("','", $list);
705
706
        $sql = "SELECT * FROM $table
707
                WHERE id NOT IN ('$listToString') AND (parent_id IS NULL) ";
708
        $result = Database::query($sql);
709
710
        return Database::store_result($result, 'ASSOC');
711
    }
712
713
    /**
714
     * @param string $keyword
715
     *
716
     * @return array|null
717
     */
718
    public static function searchCategoryByKeyword($keyword)
719
    {
720
        if (empty($keyword)) {
721
            return null;
722
        }
723
724
        $tableCategory = Database::get_main_table(TABLE_MAIN_CATEGORY);
725
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE_CATEGORY);
726
        $conditions = " INNER JOIN $table a ON (c.id = a.course_category_id)";
727
        $whereCondition = " AND a.access_url_id = ".api_get_current_access_url_id();
728
729
        $allowBaseCategories = api_get_configuration_value('allow_base_course_category');
730
        if ($allowBaseCategories) {
731
            $whereCondition = " AND (a.access_url_id = ".api_get_current_access_url_id()." OR a.access_url_id = 1) ";
732
        }
733
734
        $keyword = Database::escape_string($keyword);
735
736
        $sql = "SELECT c.*, c.name as text
737
                FROM $tableCategory c $conditions
738
                WHERE
739
                (
740
                    c.code LIKE '%$keyword%' OR name LIKE '%$keyword%'
741
                ) AND auth_course_child = 'TRUE'
742
                $whereCondition ";
743
        $result = Database::query($sql);
744
745
        return Database::store_result($result, 'ASSOC');
746
    }
747
748
    /**
749
     * Get Pagination HTML div.
750
     *
751
     * @param $pageCurrent
752
     * @param $pageLength
753
     * @param $pageTotal
754
     *
755
     * @return string
756
     */
757
    public static function getCatalogPagination($pageCurrent, $pageLength, $pageTotal)
758
    {
759
        // Start empty html
760
        $pageDiv = '';
761
        $html = '';
762
        $pageBottom = max(1, $pageCurrent - 3);
763
        $pageTop = min($pageTotal, $pageCurrent + 3);
764
765
        if ($pageBottom > 1) {
766
            $pageDiv .= self::getPageNumberItem(1, $pageLength);
767
            if ($pageBottom > 2) {
768
                $pageDiv .= self::getPageNumberItem(
769
                    $pageBottom - 1,
770
                    $pageLength,
771
                    null,
772
                    '...'
773
                );
774
            }
775
        }
776
777
        // For each page add its page button to html
778
        for ($i = $pageBottom; $i <= $pageTop; $i++) {
779
            if ($i === $pageCurrent) {
780
                $pageItemAttributes = ['class' => 'page-item active'];
781
            } else {
782
                $pageItemAttributes = ['class' => 'page-item'];
783
            }
784
            $pageDiv .= self::getPageNumberItem(
785
                $i,
786
                $pageLength,
787
                $pageItemAttributes
788
            );
789
        }
790
791
        // Check if current page is the last page
792
        if ($pageTop < $pageTotal) {
793
            if ($pageTop < ($pageTotal - 1)) {
794
                $pageDiv .= self::getPageNumberItem(
795
                    $pageTop + 1,
796
                    $pageLength,
797
                    null,
798
                    '...'
799
                );
800
            }
801
            $pageDiv .= self::getPageNumberItem($pageTotal, $pageLength);
802
        }
803
804
        // Complete pagination html
805
        $pageDiv = Display::tag('ul', $pageDiv, ['class' => 'pagination']);
806
        $html .= '<nav>'.$pageDiv.'</nav>';
807
808
        return $html;
809
    }
810
811
    /**
812
     * Return URL to course catalog.
813
     *
814
     * @param int    $pageCurrent
815
     * @param int    $pageLength
816
     * @param string $categoryCode
817
     * @param int    $hiddenLinks
818
     * @param string $action
819
     *
820
     * @return string
821
     */
822
    public static function getCourseCategoryUrl(
823
        $pageCurrent,
824
        $pageLength,
825
        $categoryCode = null,
826
        $hiddenLinks = null,
827
        $action = null
828
    ) {
829
        $requestAction = isset($_REQUEST['action']) ? Security::remove_XSS($_REQUEST['action']) : null;
830
        $action = isset($action) ? Security::remove_XSS($action) : $requestAction;
831
        $searchTerm = isset($_REQUEST['search_term']) ? Security::remove_XSS($_REQUEST['search_term']) : null;
832
833
        if ('subscribe_user_with_password' === $action) {
834
            $action = 'subscribe';
835
        }
836
837
        $categoryCodeRequest = isset($_REQUEST['category_code']) ? Security::remove_XSS($_REQUEST['category_code']) : null;
838
        $categoryCode = isset($categoryCode) ? Security::remove_XSS($categoryCode) : $categoryCodeRequest;
839
        $hiddenLinksRequest = isset($_REQUEST['hidden_links']) ? Security::remove_XSS($_REQUEST['hidden_links']) : null;
840
        $hiddenLinks = isset($hiddenLinks) ? Security::remove_XSS($hiddenLinksRequest) : $categoryCodeRequest;
841
842
        // Start URL with params
843
        $pageUrl = api_get_self().
844
            '?action='.$action.
845
            '&category_code='.$categoryCode.
846
            '&hidden_links='.$hiddenLinks.
847
            '&pageCurrent='.$pageCurrent.
848
            '&pageLength='.$pageLength;
849
850
        switch ($action) {
851
            case 'subscribe':
852
                // for search
853
                $pageUrl .=
854
                    '&search_term='.$searchTerm.
855
                    '&search_course=1'.
856
                    '&sec_token='.Security::getTokenFromSession();
857
                break;
858
            case 'display_courses':
859
            default:
860
                break;
861
        }
862
863
        return $pageUrl;
864
    }
865
866
    /**
867
     * Get li HTML of page number.
868
     *
869
     * @param $pageNumber
870
     * @param $pageLength
871
     * @param array  $liAttributes
872
     * @param string $content
873
     *
874
     * @return string
875
     */
876
    public static function getPageNumberItem(
877
        $pageNumber,
878
        $pageLength,
879
        $liAttributes = [],
880
        $content = ''
881
    ) {
882
        // Get page URL
883
        $url = self::getCourseCategoryUrl(
884
            $pageNumber,
885
            $pageLength
886
        );
887
888
        // If is current page ('active' class) clear URL
889
        if (isset($liAttributes) && is_array($liAttributes) && isset($liAttributes['class'])) {
890
            if (false !== strpos('active', $liAttributes['class'])) {
891
                $url = '';
892
            }
893
        }
894
895
        $content = !empty($content) ? $content : $pageNumber;
896
897
        return Display::tag(
898
            'li',
899
            Display::url(
900
                $content,
901
                $url,
902
                ['class' => 'page-link']
903
            ),
904
            $liAttributes
905
        );
906
    }
907
908
    /**
909
     * Return the name tool by action.
910
     *
911
     * @param string $action
912
     *
913
     * @return string
914
     */
915
    public static function getCourseCatalogNameTools($action)
916
    {
917
        $nameTools = get_lang('My courses');
918
        if (empty($action)) {
919
            return $nameTools; //should never happen
920
        }
921
922
        switch ($action) {
923
            case 'subscribe':
924
            case 'subscribe_user_with_password':
925
            case 'display_random_courses':
926
            case 'display_courses':
927
                $nameTools = get_lang('Courses catalog');
928
                break;
929
            case 'display_sessions':
930
                $nameTools = get_lang('Course sessions');
931
                break;
932
            default:
933
                // Nothing to do
934
                break;
935
        }
936
937
        return $nameTools;
938
    }
939
940
    /**
941
     * Save image for a course category.
942
     *
943
     * @param int   $categoryId Course category ID
944
     * @param array $fileData   File data from $_FILES
945
     */
946
    public static function saveImage($categoryId, $fileData)
947
    {
948
        $categoryInfo = self::getCategoryById($categoryId);
949
        if (empty($categoryInfo)) {
950
            return;
951
        }
952
953
        if (!empty($fileData['error'])) {
954
            return;
955
        }
956
957
        $extension = getextension($fileData['name']);
958
        $dirName = 'course_category/';
959
        $fileDir = api_get_path(SYS_UPLOAD_PATH).$dirName;
960
        $fileName = "cc_$categoryId.{$extension[0]}";
961
962
        if (!file_exists($fileDir)) {
963
            mkdir($fileDir, api_get_permissions_for_new_directories(), true);
964
        }
965
966
        $image = new Image($fileData['tmp_name']);
0 ignored issues
show
Deprecated Code introduced by
The class Image has been deprecated. ( Ignorable by Annotation )

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

966
        $image = /** @scrutinizer ignore-deprecated */ new Image($fileData['tmp_name']);
Loading history...
967
        $image->send_image($fileDir.$fileName);
968
969
        $table = Database::get_main_table(TABLE_MAIN_CATEGORY);
970
        Database::update(
971
            $table,
972
            ['image' => $dirName.$fileName],
973
            ['id = ?' => $categoryId]
974
        );
975
    }
976
977
    /**
978
     * @param $categoryId
979
     * @param string $description
980
     *
981
     * @return string
982
     */
983
    public static function saveDescription($categoryId, $description)
984
    {
985
        $categoryInfo = self::getCategoryById($categoryId);
986
        if (empty($categoryInfo)) {
987
            return false;
988
        }
989
        $table = Database::get_main_table(TABLE_MAIN_CATEGORY);
990
        Database::update(
991
            $table,
992
            ['description' => $description],
993
            ['id = ?' => $categoryId]
994
        );
995
996
        return true;
997
    }
998
}
999