Passed
Push — 1.11.x ( 156807...e5ebc9 )
by Julito
09:43
created

CourseCategory::getCoursesInCategory()   B

Complexity

Conditions 9
Paths 96

Size

Total Lines 72
Code Lines 47

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
eloc 47
nc 96
nop 5
dl 0
loc 72
rs 7.6008
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 $categoryCode The literal category code
34
     *
35
     * @return array
36
     */
37
    public static function getCategory($categoryCode)
38
    {
39
        $table = Database::get_main_table(TABLE_MAIN_CATEGORY);
40
        $categoryCode = Database::escape_string($categoryCode);
41
        $sql = "SELECT * FROM $table WHERE code ='$categoryCode'";
42
        $result = Database::query($sql);
43
        if (Database::num_rows($result)) {
44
            $category = Database::fetch_array($result, 'ASSOC');
45
            if ($category) {
46
                // Get access url id
47
                $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE_CATEGORY);
48
                $sql = "SELECT * FROM $table WHERE course_category_id = ".$category['id'];
49
                $result = Database::query($sql);
50
                $result = Database::fetch_array($result);
51
                if ($result) {
52
                    $category['access_url_id'] = $result['access_url_id'];
53
                }
54
55
                return $category;
56
            }
57
        }
58
59
        return [];
60
    }
61
62
    /**
63
     * @param string $category Optional. Parent category code
64
     *
65
     * @return array
66
     */
67
    public static function getCategories($category = '')
68
    {
69
        $tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
70
        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
71
        $category = Database::escape_string($category);
72
73
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE_CATEGORY);
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
        $allowBaseCategories = api_get_configuration_value('allow_base_course_category');
77
        if ($allowBaseCategories) {
78
            $whereCondition = " AND (a.access_url_id = ".api_get_current_access_url_id()." OR a.access_url_id = 1) ";
79
        }
80
81
        $parentIdCondition = " AND (t1.parent_id IS NULL OR t1.parent_id = '' )";
82
        if (!empty($category)) {
83
            $parentIdCondition = " AND t1.parent_id = '$category' ";
84
        }
85
86
        $sql = "SELECT
87
                t1.name,
88
                t1.code,
89
                t1.parent_id,
90
                t1.tree_pos,
91
                t1.children_count,
92
                COUNT(DISTINCT t3.code) AS nbr_courses,
93
                a.access_url_id
94
                FROM $tbl_category t1
95
                $conditions
96
                LEFT JOIN $tbl_category t2
97
                ON t1.code = t2.parent_id
98
                LEFT JOIN $tbl_course t3
99
                ON t3.category_code=t1.code
100
                WHERE
101
                    1 = 1
102
                    $parentIdCondition
103
                    $whereCondition
104
                GROUP BY t1.name,
105
                         t1.code,
106
                         t1.parent_id,
107
                         t1.tree_pos,
108
                         t1.children_count
109
                ORDER BY t1.tree_pos";
110
111
        $result = Database::query($sql);
112
113
        return Database::store_result($result, 'ASSOC');
114
    }
115
116
    /**
117
     * Returns a flat list of all course categories in this URL. If the
118
     * allow_base_course_category option is true, then also show the
119
     * course categories of the base URL.
120
     *
121
     * @return array [id, name, code, parent_id, tree_pos, children_count, number_courses]
122
     */
123
    public static function getAllCategories()
124
    {
125
        $tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
126
        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
127
128
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE_CATEGORY);
129
        $conditions = " INNER JOIN $table a ON (t1.id = a.course_category_id)";
130
        $whereCondition = " AND a.access_url_id = ".api_get_current_access_url_id();
131
        $allowBaseCategories = api_get_configuration_value('allow_base_course_category');
132
        if ($allowBaseCategories) {
133
            $whereCondition = " AND (a.access_url_id = ".api_get_current_access_url_id()." OR a.access_url_id = 1) ";
134
        }
135
136
        $sql = "SELECT
137
                t1.id,
138
                t1.name,
139
                t1.code,
140
                t1.parent_id,
141
                t1.tree_pos,
142
                t1.children_count,
143
                COUNT(DISTINCT t3.code) AS number_courses
144
                FROM $tbl_category t1
145
                $conditions
146
                LEFT JOIN $tbl_course t3
147
                ON t3.category_code=t1.code
148
                WHERE 1=1
149
                    $whereCondition
150
                GROUP BY
151
                    t1.name,
152
                    t1.code,
153
                    t1.parent_id,
154
                    t1.tree_pos,
155
                    t1.children_count
156
                ORDER BY t1.parent_id, t1.tree_pos";
157
158
        $result = Database::query($sql);
159
160
        return Database::store_result($result, 'ASSOC');
161
    }
162
163
    /**
164
     * @param string $code
165
     * @param string $name
166
     * @param string $canHaveCourses
167
     * @param int    $parent_id
168
     *
169
     * @return bool
170
     */
171
    public static function addNode($code, $name, $canHaveCourses, $parent_id)
172
    {
173
        $table = Database::get_main_table(TABLE_MAIN_CATEGORY);
174
        $code = trim($code);
175
        $name = trim($name);
176
        $parent_id = trim($parent_id);
177
178
        $code = CourseManager::generate_course_code($code);
179
        $sql = "SELECT 1 FROM $table
180
                WHERE code = '".Database::escape_string($code)."'";
181
        $result = Database::query($sql);
182
        if (Database::num_rows($result)) {
183
            return false;
184
        }
185
        $result = Database::query("SELECT MAX(tree_pos) AS maxTreePos FROM $table");
186
        $row = Database::fetch_array($result);
187
        $tree_pos = $row['maxTreePos'] + 1;
188
189
        $params = [
190
            'name' => $name,
191
            'code' => $code,
192
            'parent_id' => empty($parent_id) ? null : $parent_id,
193
            'tree_pos' => $tree_pos,
194
            'children_count' => 0,
195
            'auth_course_child' => $canHaveCourses,
196
            'auth_cat_child' => 'TRUE',
197
        ];
198
199
        $categoryId = Database::insert($table, $params);
200
        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...
201
            self::updateParentCategoryChildrenCount($parent_id, 1);
202
            UrlManager::addCourseCategoryListToUrl(
203
                [$categoryId],
204
                [api_get_current_access_url_id()]
205
            );
206
207
            return $categoryId;
208
        }
209
210
        return false;
211
    }
212
213
    /**
214
     * Recursive function that updates the count of children in the parent.
215
     *
216
     * @param string $categoryId Category ID
217
     * @param int    $delta      The number to add or delete (1 to add one, -1 to remove one)
218
     */
219
    public static function updateParentCategoryChildrenCount($categoryId, $delta = 1)
220
    {
221
        $table = Database::get_main_table(TABLE_MAIN_CATEGORY);
222
        $categoryId = Database::escape_string($categoryId);
223
        $delta = (int) $delta;
224
        // First get to the highest level possible in the tree
225
        $result = Database::query("SELECT parent_id FROM $table WHERE code = '$categoryId'");
226
        $row = Database::fetch_array($result);
227
        if ($row !== false and $row['parent_id'] != 0) {
228
            // if a parent was found, enter there to see if he's got one more parent
229
            self::updateParentCategoryChildrenCount($row['parent_id'], $delta);
230
        }
231
        // Now we're at the top, get back down to update each child
232
        $sql = "UPDATE $table SET children_count = (children_count - ".abs($delta).") WHERE code = '$categoryId'";
233
        if ($delta >= 0) {
234
            $sql = "UPDATE $table SET children_count = (children_count + $delta) WHERE code = '$categoryId'";
235
        }
236
        Database::query($sql);
237
    }
238
239
    /**
240
     * @param string $node
241
     *
242
     * @return bool
243
     */
244
    public static function deleteNode($node)
245
    {
246
        $category = self::getCategory($node);
247
248
        if (empty($category)) {
249
            return false;
250
        }
251
252
        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
253
        $tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
254
        $node = Database::escape_string($node);
255
        $result = Database::query("SELECT parent_id, tree_pos FROM $tbl_category WHERE code='$node'");
256
257
        if ($row = Database::fetch_array($result)) {
258
            if (!empty($row['parent_id'])) {
259
                Database::query(
260
                    "UPDATE $tbl_course SET category_code = '".$row['parent_id']."' WHERE category_code='$node'"
261
                );
262
                Database::query("UPDATE $tbl_category SET parent_id='".$row['parent_id']."' WHERE parent_id='$node'");
263
            } else {
264
                Database::query("UPDATE $tbl_course SET category_code='' WHERE category_code='$node'");
265
                Database::query("UPDATE $tbl_category SET parent_id=NULL WHERE parent_id='$node'");
266
            }
267
268
            $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE_CATEGORY);
269
            $sql = "DELETE FROM $table WHERE course_category_id = ".$category['id'];
270
271
            Database::query($sql);
272
            Database::query("UPDATE $tbl_category SET tree_pos=tree_pos-1 WHERE tree_pos > '".$row['tree_pos']."'");
273
            Database::query("DELETE FROM $tbl_category WHERE code='$node'");
274
275
            if (!empty($row['parent_id'])) {
276
                self::updateParentCategoryChildrenCount($row['parent_id'], -1);
277
            }
278
279
            return true;
280
        }
281
    }
282
283
    /**
284
     * @param string $code
285
     * @param string $name
286
     * @param string $canHaveCourses
287
     * @param string $old_code
288
     *
289
     * @return bool
290
     */
291
    public static function editNode($code, $name, $canHaveCourses, $old_code)
292
    {
293
        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
294
        $tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
295
296
        $code = trim(Database::escape_string($code));
297
        $name = trim(Database::escape_string($name));
298
        $old_code = Database::escape_string($old_code);
299
        $canHaveCourses = Database::escape_string($canHaveCourses);
300
301
        $code = CourseManager::generate_course_code($code);
302
        // Updating category
303
        $sql = "UPDATE $tbl_category SET
304
                    name='$name',
305
                    code='$code',
306
                    auth_course_child = '$canHaveCourses'
307
                WHERE code = '$old_code'";
308
        Database::query($sql);
309
310
        // Updating children
311
        $sql = "UPDATE $tbl_category SET parent_id = '$code'
312
            WHERE parent_id = '$old_code'";
313
        Database::query($sql);
314
315
        // Updating course category
316
        $sql = "UPDATE $tbl_course SET category_code = '$code'
317
            WHERE category_code = '$old_code' ";
318
        Database::query($sql);
319
320
        return true;
321
    }
322
323
    /**
324
     * Move a node up on display.
325
     *
326
     * @param string $code
327
     * @param int    $tree_pos
328
     * @param string $parent_id
329
     *
330
     * @return bool
331
     */
332
    public static function moveNodeUp($code, $tree_pos, $parent_id)
333
    {
334
        $table = Database::get_main_table(TABLE_MAIN_CATEGORY);
335
        $code = Database::escape_string($code);
336
        $tree_pos = (int) $tree_pos;
337
        $parent_id = Database::escape_string($parent_id);
338
339
        $parentIdCondition = " AND (parent_id IS NULL OR parent_id = '' )";
340
        if (!empty($parent_id)) {
341
            $parentIdCondition = " AND parent_id = '$parent_id' ";
342
        }
343
344
        $sql = "SELECT code,tree_pos
345
                FROM $table
346
                WHERE
347
                    tree_pos < $tree_pos
348
                    $parentIdCondition
349
                ORDER BY tree_pos DESC
350
                LIMIT 0,1";
351
352
        $result = Database::query($sql);
353
        if (!$row = Database::fetch_array($result)) {
354
            $sql = "SELECT code, tree_pos
355
                    FROM $table
356
                    WHERE
357
                        tree_pos > $tree_pos
358
                        $parentIdCondition
359
                    ORDER BY tree_pos DESC
360
                    LIMIT 0,1";
361
            $result2 = Database::query($sql);
362
            if (!$row = Database::fetch_array($result2)) {
363
                return false;
364
            }
365
        }
366
367
        $sql = "UPDATE $table
368
                SET tree_pos ='".$row['tree_pos']."'
369
                WHERE code='$code'";
370
        Database::query($sql);
371
372
        $sql = "UPDATE $table
373
                SET tree_pos = '$tree_pos'
374
                WHERE code= '".$row['code']."'";
375
        Database::query($sql);
376
377
        return true;
378
    }
379
380
    /**
381
     * @param string $categoryCode
382
     *
383
     * @return array
384
     */
385
    public static function getChildren($categoryCode)
386
    {
387
        $table = Database::get_main_table(TABLE_MAIN_CATEGORY);
388
        $categoryCode = Database::escape_string($categoryCode);
389
        $sql = "SELECT code, id FROM $table
390
                WHERE parent_id = '$categoryCode'";
391
        $result = Database::query($sql);
392
        $children = [];
393
        while ($row = Database::fetch_array($result, 'ASSOC')) {
394
            $children[] = $row;
395
            $subChildren = self::getChildren($row['code']);
396
            $children = array_merge($children, $subChildren);
397
        }
398
399
        return $children;
400
    }
401
402
    /**
403
     * @param string $categoryCode
404
     *
405
     * @return array
406
     */
407
    public static function getParents($categoryCode)
408
    {
409
        if (empty($categoryCode)) {
410
            return [];
411
        }
412
413
        $table = Database::get_main_table(TABLE_MAIN_CATEGORY);
414
        $categoryCode = Database::escape_string($categoryCode);
415
        $sql = "SELECT code, parent_id
416
                FROM $table
417
                WHERE code = '$categoryCode'";
418
419
        $result = Database::query($sql);
420
        $children = [];
421
        while ($row = Database::fetch_array($result, 'ASSOC')) {
422
            $parent = self::getCategory($row['parent_id']);
423
            $children[] = $row;
424
            $subChildren = self::getParents($parent ? $parent['code'] : null);
425
            $children = array_merge($children, $subChildren);
426
        }
427
428
        return $children;
429
    }
430
431
    /**
432
     * @param string $categoryCode
433
     *
434
     * @return string|null
435
     */
436
    public static function getParentsToString($categoryCode)
437
    {
438
        $parents = self::getParents($categoryCode);
439
440
        if (!empty($parents)) {
441
            $parents = array_reverse($parents);
442
            $categories = [];
443
            foreach ($parents as $category) {
444
                $categories[] = $category['code'];
445
            }
446
447
            return implode(' > ', $categories).' > ';
448
        }
449
450
        return null;
451
    }
452
453
    /**
454
     * @param string $categorySource
455
     *
456
     * @return string
457
     */
458
    public static function listCategories($categorySource)
459
    {
460
        $categories = self::getCategories($categorySource);
461
        $categorySource = Security::remove_XSS($categorySource);
462
463
        if (count($categories) > 0) {
464
            $table = new HTML_Table(['class' => 'table table-hover table-striped data_table']);
465
            $column = 0;
466
            $row = 0;
467
            $headers = [
468
                get_lang('Category'),
469
                get_lang('SubCat'),
470
                get_lang('Courses'),
471
                get_lang('Actions'),
472
            ];
473
            foreach ($headers as $header) {
474
                $table->setHeaderContents($row, $column, $header);
475
                $column++;
476
            }
477
            $row++;
478
            $mainUrl = api_get_path(WEB_CODE_PATH).'admin/course_category.php?category='.$categorySource;
479
480
            $editIcon = Display::return_icon(
481
                'edit.png',
482
                get_lang('EditNode'),
483
                null,
484
                ICON_SIZE_SMALL
485
            );
486
            $deleteIcon = Display::return_icon(
487
                'delete.png',
488
                get_lang('DeleteNode'),
489
                null,
490
                ICON_SIZE_SMALL
491
            );
492
            $moveIcon = Display::return_icon(
493
                'up.png',
494
                get_lang('UpInSameLevel'),
495
                null,
496
                ICON_SIZE_SMALL
497
            );
498
499
            $urlId = api_get_current_access_url_id();
500
            foreach ($categories as $category) {
501
                $editUrl = $mainUrl.'&id='.$category['code'].'&action=edit';
502
                $moveUrl = $mainUrl.'&id='.$category['code'].'&action=moveUp&tree_pos='.$category['tree_pos'];
503
                $deleteUrl = $mainUrl.'&id='.$category['code'].'&action=delete';
504
505
                $actions = [];
506
507
                if ($urlId == $category['access_url_id']) {
508
                    $actions[] = Display::url($editIcon, $editUrl);
509
                    $actions[] = Display::url($moveIcon, $moveUrl);
510
                    $actions[] = Display::url($deleteIcon, $deleteUrl);
511
                }
512
513
                $url = api_get_path(WEB_CODE_PATH).'admin/course_category.php?category='.$category['code'];
514
                $title = Display::url(
515
                    Display::return_icon(
516
                        'folder_document.gif',
517
                        get_lang('OpenNode'),
518
                        null,
519
                        ICON_SIZE_SMALL
520
                    ).' '.$category['name'].' ('.$category['code'].')',
521
                    $url
522
                );
523
524
                $countCourses = self::countCoursesInCategory($category['code'], null, false);
525
526
                $content = [
527
                    $title,
528
                    $category['children_count'],
529
                    $countCourses,
530
                    implode('', $actions),
531
                ];
532
                $column = 0;
533
                foreach ($content as $value) {
534
                    $table->setCellContents($row, $column, $value);
535
                    $column++;
536
                }
537
                $row++;
538
            }
539
540
            return $table->toHtml();
541
        }
542
543
        return Display::return_message(get_lang('NoCategories'), 'warning');
544
    }
545
546
    /**
547
     * @return array
548
     */
549
    public static function getCategoriesToDisplayInHomePage()
550
    {
551
        $table = Database::get_main_table(TABLE_MAIN_CATEGORY);
552
        $sql = "SELECT name FROM $table
553
                WHERE parent_id IS NULL
554
                ORDER BY tree_pos";
555
556
        return Database::store_result(Database::query($sql));
557
    }
558
559
    /**
560
     * @param string $categoryCode
561
     *
562
     * @return array
563
     */
564
    public static function getCategoriesCanBeAddedInCourse($categoryCode)
565
    {
566
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE_CATEGORY);
567
        $conditions = " INNER JOIN $table a ON (c.id = a.course_category_id)";
568
        $whereCondition = ' AND a.access_url_id = '.api_get_current_access_url_id();
569
570
        $tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
571
        $sql = "SELECT code, name
572
                FROM $tbl_category c
573
                $conditions
574
                WHERE (auth_course_child = 'TRUE' OR code = '".Database::escape_string($categoryCode)."')
575
                $whereCondition
576
                ORDER BY tree_pos";
577
        $res = Database::query($sql);
578
579
        $categoryToAvoid = '';
580
        if (!api_is_platform_admin()) {
581
            $categoryToAvoid = api_get_configuration_value('course_category_code_to_use_as_model');
582
        }
583
584
        $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...
585
        while ($cat = Database::fetch_array($res)) {
586
            $categoryCode = $cat['code'];
587
            if (!empty($categoryToAvoid) && $categoryToAvoid == $categoryCode) {
588
                continue;
589
            }
590
            $categories[$categoryCode] = '('.$categoryCode.') '.$cat['name'];
591
            ksort($categories);
592
        }
593
594
        return $categories;
595
    }
596
597
    /**
598
     * @param string $category_code
599
     * @param string $keyword
600
     * @paran bool  $avoidCourses
601
     * @paran array $conditions
602
     *
603
     * @return int
604
     */
605
    public static function countCoursesInCategory(
606
        $category_code = '',
607
        $keyword = '',
608
        $avoidCourses = true,
609
        $conditions = []
610
    ) {
611
        return self::getCoursesInCategory($category_code, $keyword, $avoidCourses, $conditions, true);
612
    }
613
614
    public static function getCoursesInCategory($category_code = '', $keyword = '', $avoidCourses = true, $conditions = [], $getCount = false)
615
    {
616
        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
617
        $categoryCode = Database::escape_string($category_code);
618
        $keyword = Database::escape_string($keyword);
619
620
        $avoidCoursesCondition = '';
621
        if ($avoidCourses) {
622
            $avoidCoursesCondition = CoursesAndSessionsCatalog::getAvoidCourseCondition();
623
        }
624
625
        $visibilityCondition = CourseManager::getCourseVisibilitySQLCondition('course', true);
626
627
        $sqlInjectJoins = '';
628
        $where = ' AND 1 = 1 ';
629
        $sqlInjectWhere = '';
630
        if (!empty($conditions)) {
631
            $sqlInjectJoins = $conditions['inject_joins'];
632
            $where = $conditions['where'];
633
            $sqlInjectWhere = $conditions['inject_where'];
634
        }
635
636
        $categoryFilter = '';
637
        if ($categoryCode === 'ALL' || empty($categoryCode)) {
638
            // Nothing to do
639
        } elseif ($categoryCode === 'NONE') {
640
            $categoryFilter = ' AND category_code = "" ';
641
        } else {
642
            $categoryFilter = ' AND category_code = "'.$categoryCode.'" ';
643
        }
644
645
        $searchFilter = '';
646
        if (!empty($keyword)) {
647
            $searchFilter = ' AND (
648
                code LIKE "%'.$keyword.'%" OR
649
                title LIKE "%'.$keyword.'%" OR
650
                tutor_name LIKE "%'.$keyword.'%"
651
            ) ';
652
        }
653
654
        $urlCondition = ' access_url_id = '.api_get_current_access_url_id().' AND';
655
        $tbl_url_rel_course = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
656
        $select = " DISTINCT course.id, course.code, course.title, course.category_code ";
657
        if ($getCount) {
658
            $select = "count(DISTINCT course.id) as count";
659
        }
660
        $sql = "SELECT $select
661
                FROM $tbl_course as course
662
                INNER JOIN $tbl_url_rel_course as url_rel_course
663
                ON (url_rel_course.c_id = course.id)
664
                $sqlInjectJoins
665
                WHERE
666
                    $urlCondition
667
                    course.visibility != '0' AND
668
                    course.visibility != '4'
669
                    $categoryFilter
670
                    $searchFilter
671
                    $avoidCoursesCondition
672
                    $visibilityCondition
673
                    $where
674
                    $sqlInjectWhere
675
            ";
676
677
        $result = Database::query($sql);
678
679
        if ($getCount) {
680
            $row = Database::fetch_array($result);
681
682
            return (int) $row['count'];
683
        }
684
685
        return Database::store_result($result, 'ASSOC');
686
    }
687
688
    /**
689
     * @param array $list
690
     *
691
     * @return array
692
     */
693
    public static function getCourseCategoryNotInList($list)
694
    {
695
        $table = Database::get_main_table(TABLE_MAIN_CATEGORY);
696
697
        if (empty($list)) {
698
            $sql = "SELECT * FROM $table
699
                    WHERE (parent_id IS NULL) ";
700
            $result = Database::query($sql);
701
702
            return Database::store_result($result, 'ASSOC');
703
        }
704
705
        $list = array_map('intval', $list);
706
        $listToString = implode("','", $list);
707
708
        $sql = "SELECT * FROM $table
709
                WHERE id NOT IN ('$listToString') AND (parent_id IS NULL) ";
710
        $result = Database::query($sql);
711
712
        return Database::store_result($result, 'ASSOC');
713
    }
714
715
    /**
716
     * @param string $keyword
717
     *
718
     * @return array|null
719
     */
720
    public static function searchCategoryByKeyword($keyword)
721
    {
722
        if (empty($keyword)) {
723
            return null;
724
        }
725
726
        $tableCategory = Database::get_main_table(TABLE_MAIN_CATEGORY);
727
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE_CATEGORY);
728
        $conditions = " INNER JOIN $table a ON (c.id = a.course_category_id)";
729
        $whereCondition = " AND a.access_url_id = ".api_get_current_access_url_id();
730
731
        $allowBaseCategories = api_get_configuration_value('allow_base_course_category');
732
        if ($allowBaseCategories) {
733
            $whereCondition = " AND (a.access_url_id = ".api_get_current_access_url_id()." OR a.access_url_id = 1) ";
734
        }
735
736
        $keyword = Database::escape_string($keyword);
737
738
        $sql = "SELECT c.*, c.name as text
739
                FROM $tableCategory c $conditions
740
                WHERE
741
                (
742
                    c.code LIKE '%$keyword%' OR name LIKE '%$keyword%'
743
                ) AND auth_course_child = 'TRUE'
744
                $whereCondition ";
745
        $result = Database::query($sql);
746
747
        return Database::store_result($result, 'ASSOC');
748
    }
749
750
    /**
751
     * Return the name tool by action.
752
     *
753
     * @param string $action
754
     *
755
     * @return string
756
     */
757
    public static function getCourseCatalogNameTools($action)
758
    {
759
        $nameTools = get_lang('MyCourses');
760
        if (empty($action)) {
761
            return $nameTools; //should never happen
762
        }
763
764
        switch ($action) {
765
            case 'subscribe':
766
            case 'subscribe_user_with_password':
767
            case 'display_random_courses':
768
            case 'display_courses':
769
                $nameTools = get_lang('CourseManagement');
770
                break;
771
            case 'display_sessions':
772
                $nameTools = get_lang('Sessions');
773
                break;
774
            default:
775
                // Nothing to do
776
                break;
777
        }
778
779
        return $nameTools;
780
    }
781
782
    /**
783
     * Save image for a course category.
784
     *
785
     * @param int   $categoryId Course category ID
786
     * @param array $fileData   File data from $_FILES
787
     */
788
    public static function saveImage($categoryId, $fileData)
789
    {
790
        $categoryInfo = self::getCategoryById($categoryId);
791
        if (empty($categoryInfo)) {
792
            return;
793
        }
794
795
        if (!empty($fileData['error'])) {
796
            return;
797
        }
798
799
        $extension = getextension($fileData['name']);
800
        $dirName = 'course_category/';
801
        $fileDir = api_get_path(SYS_UPLOAD_PATH).$dirName;
802
        $fileName = "cc_$categoryId.{$extension[0]}";
803
804
        if (!file_exists($fileDir)) {
805
            mkdir($fileDir, api_get_permissions_for_new_directories(), true);
806
        }
807
808
        $image = new Image($fileData['tmp_name']);
809
        $image->send_image($fileDir.$fileName);
810
811
        $table = Database::get_main_table(TABLE_MAIN_CATEGORY);
812
        Database::update(
813
            $table,
814
            ['image' => $dirName.$fileName],
815
            ['id = ?' => $categoryId]
816
        );
817
    }
818
819
    /**
820
     * @param $categoryId
821
     * @param string $description
822
     *
823
     * @return string
824
     */
825
    public static function saveDescription($categoryId, $description)
826
    {
827
        $categoryInfo = self::getCategoryById($categoryId);
828
        if (empty($categoryInfo)) {
829
            return false;
830
        }
831
        $table = Database::get_main_table(TABLE_MAIN_CATEGORY);
832
        Database::update(
833
            $table,
834
            ['description' => $description],
835
            ['id = ?' => $categoryId]
836
        );
837
838
        return true;
839
    }
840
}
841