Completed
Push — master ( ae5621...ef667c )
by Julito
13:23
created

CourseCategory::getCourseCategoryNotInList()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 20
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 11
nc 2
nop 1
dl 0
loc 20
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
/**
5
 * Class CourseCategory.
6
 */
7
class CourseCategory
8
{
9
    /**
10
     * Returns the category fields from the database from an int ID.
11
     *
12
     * @param int $categoryId The category ID
13
     *
14
     * @return array
15
     */
16
    public static function getCategoryById($categoryId)
17
    {
18
        $table = Database::get_main_table(TABLE_MAIN_CATEGORY);
19
        $categoryId = intval($categoryId);
20
        $sql = "SELECT * FROM $table WHERE id = $categoryId";
21
        $result = Database::query($sql);
22
        if (Database::num_rows($result)) {
23
            return Database::fetch_array($result, 'ASSOC');
24
        }
25
26
        return [];
27
    }
28
29
    /**
30
     * Get category details from a simple category code.
31
     *
32
     * @param string $category The literal category code
33
     *
34
     * @return array
35
     */
36
    public static function getCategory($category)
37
    {
38
        $table = Database::get_main_table(TABLE_MAIN_CATEGORY);
39
        $category = Database::escape_string($category);
40
        $sql = "SELECT * FROM $table WHERE code ='$category'";
41
        $result = Database::query($sql);
42
        if (Database::num_rows($result)) {
43
            $category = Database::fetch_array($result, 'ASSOC');
44
            // Get access url id
45
            $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE_CATEGORY);
46
            $sql = "SELECT * FROM $table WHERE course_category_id = ".$category['id'];
47
            $result = Database::query($sql);
48
            $result = Database::fetch_array($result);
49
            if ($result) {
50
                $category['access_url_id'] = $result['access_url_id'];
51
            }
52
53
            return $category;
54
        }
55
56
        return [];
57
    }
58
59
    /**
60
     * @param string $category Optional. Parent category code
61
     *
62
     * @return array
63
     */
64
    public static function getCategories($category = '')
65
    {
66
        $tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
67
        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
68
        $category = Database::escape_string($category);
69
        $conditions = null;
70
71
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE_CATEGORY);
72
73
        $conditions = " INNER JOIN $table a ON (t1.id = a.course_category_id)";
74
        $whereCondition = " AND a.access_url_id = ".api_get_current_access_url_id();
75
        $allowBaseCategories = api_get_configuration_value('allow_base_course_category');
76
        if ($allowBaseCategories) {
77
            $whereCondition = " AND (a.access_url_id = ".api_get_current_access_url_id()." OR a.access_url_id = 1) ";
78
        }
79
80
        $parentIdCondition = " AND (t1.parent_id IS NULL OR t1.parent_id = '' )";
81
        if (!empty($category)) {
82
            $parentIdCondition = " AND t1.parent_id = '$category' ";
83
        }
84
85
        $sql = "SELECT
86
                t1.name,
87
                t1.code,
88
                t1.parent_id,
89
                t1.tree_pos,
90
                t1.children_count,
91
                COUNT(DISTINCT t3.code) AS nbr_courses,
92
                a.access_url_id
93
                FROM $tbl_category t1
94
                $conditions
95
                LEFT JOIN $tbl_category t2
96
                ON t1.code = t2.parent_id
97
                LEFT JOIN $tbl_course t3
98
                ON t3.category_code=t1.code
99
                WHERE
100
                    1 = 1
101
                    $parentIdCondition
102
                    $whereCondition
103
                GROUP BY t1.name,
104
                         t1.code,
105
                         t1.parent_id,
106
                         t1.tree_pos,
107
                         t1.children_count
108
                ORDER BY t1.tree_pos";
109
110
        $result = Database::query($sql);
111
        $categories = Database::store_result($result, 'ASSOC');
112
113
        return $categories;
114
    }
115
116
    /**
117
     * @param string $code
118
     * @param string $name
119
     * @param string $canHaveCourses
120
     * @param int    $parent_id
121
     *
122
     * @return bool
123
     */
124
    public static function addNode($code, $name, $canHaveCourses, $parent_id)
125
    {
126
        $table = Database::get_main_table(TABLE_MAIN_CATEGORY);
127
        $code = trim($code);
128
        $name = trim($name);
129
        $parent_id = trim($parent_id);
130
131
        $code = CourseManager::generate_course_code($code);
132
        $sql = "SELECT 1 FROM $table
133
                WHERE code = '".Database::escape_string($code)."'";
134
        $result = Database::query($sql);
135
        if (Database::num_rows($result)) {
136
            return false;
137
        }
138
        $result = Database::query("SELECT MAX(tree_pos) AS maxTreePos FROM $table");
139
        $row = Database::fetch_array($result);
140
        $tree_pos = $row['maxTreePos'] + 1;
141
142
        $params = [
143
            'name' => $name,
144
            'code' => $code,
145
            'parent_id' => empty($parent_id) ? null : $parent_id,
146
            'tree_pos' => $tree_pos,
147
            'children_count' => 0,
148
            'auth_course_child' => $canHaveCourses,
149
            'auth_cat_child' => 'TRUE',
150
        ];
151
152
        $categoryId = Database::insert($table, $params);
153
154
        self::updateParentCategoryChildrenCount($parent_id, 1);
155
        self::addToUrl($categoryId);
0 ignored issues
show
Bug introduced by
It seems like $categoryId can also be of type false; however, parameter $id of CourseCategory::addToUrl() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

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

155
        self::addToUrl(/** @scrutinizer ignore-type */ $categoryId);
Loading history...
156
157
        return $categoryId;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $categoryId also could return the type integer which is incompatible with the documented return type boolean.
Loading history...
158
    }
159
160
    /**
161
     * Recursive function that updates the count of children in the parent.
162
     *
163
     * @param string $categoryId Category ID
164
     * @param int    $delta      The number to add or delete (1 to add one, -1 to remove one)
165
     */
166
    public static function updateParentCategoryChildrenCount($categoryId, $delta = 1)
167
    {
168
        $table = Database::get_main_table(TABLE_MAIN_CATEGORY);
169
        $categoryId = Database::escape_string($categoryId);
170
        $delta = intval($delta);
171
        // First get to the highest level possible in the tree
172
        $result = Database::query("SELECT parent_id FROM $table WHERE code = '$categoryId'");
173
        $row = Database::fetch_array($result);
174
        if ($row !== false and $row['parent_id'] != 0) {
175
            // if a parent was found, enter there to see if he's got one more parent
176
            self::updateParentCategoryChildrenCount($row['parent_id'], $delta);
177
        }
178
        // Now we're at the top, get back down to update each child
179
        //$children_count = courseCategoryChildrenCount($categoryId);
180
        $sql = "UPDATE $table SET children_count = (children_count - ".abs($delta).") WHERE code = '$categoryId'";
181
        if ($delta >= 0) {
182
            $sql = "UPDATE $table SET children_count = (children_count + $delta) WHERE code = '$categoryId'";
183
        }
184
        Database::query($sql);
185
    }
186
187
    /**
188
     * @param string $node
189
     *
190
     * @return bool
191
     */
192
    public static function deleteNode($node)
193
    {
194
        $category = self::getCategory($node);
195
196
        if (empty($category)) {
197
            return false;
198
        }
199
200
        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
201
        $tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
202
        $node = Database::escape_string($node);
203
        $result = Database::query("SELECT parent_id, tree_pos FROM $tbl_category WHERE code='$node'");
204
205
        if ($row = Database::fetch_array($result)) {
206
            if (!empty($row['parent_id'])) {
207
                Database::query(
208
                    "UPDATE $tbl_course SET category_code = '".$row['parent_id']."' WHERE category_code='$node'"
209
                );
210
                Database::query("UPDATE $tbl_category SET parent_id='".$row['parent_id']."' WHERE parent_id='$node'");
211
            } else {
212
                Database::query("UPDATE $tbl_course SET category_code='' WHERE category_code='$node'");
213
                Database::query("UPDATE $tbl_category SET parent_id=NULL WHERE parent_id='$node'");
214
            }
215
216
            $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE_CATEGORY);
217
            $sql = "DELETE FROM $table WHERE course_category_id = ".$category['id'];
218
219
            Database::query($sql);
220
            Database::query("UPDATE $tbl_category SET tree_pos=tree_pos-1 WHERE tree_pos > '".$row['tree_pos']."'");
221
            Database::query("DELETE FROM $tbl_category WHERE code='$node'");
222
223
            if (!empty($row['parent_id'])) {
224
                self::updateParentCategoryChildrenCount($row['parent_id'], -1);
225
            }
226
227
            return true;
228
        }
229
    }
230
231
    /**
232
     * @param string $code
233
     * @param string $name
234
     * @param string $canHaveCourses
235
     * @param string $old_code
236
     *
237
     * @return bool
238
     */
239
    public static function editNode($code, $name, $canHaveCourses, $old_code)
240
    {
241
        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
242
        $tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
243
244
        $code = trim(Database::escape_string($code));
245
        $name = trim(Database::escape_string($name));
246
        $old_code = Database::escape_string($old_code);
247
        $canHaveCourses = Database::escape_string($canHaveCourses);
248
249
        $code = CourseManager::generate_course_code($code);
250
        // Updating category
251
        $sql = "UPDATE $tbl_category SET 
252
                    name='$name', 
253
                    code='$code', 
254
                    auth_course_child = '$canHaveCourses'
255
                WHERE code = '$old_code'";
256
        Database::query($sql);
257
258
        // Updating children
259
        $sql = "UPDATE $tbl_category SET parent_id = '$code'
260
            WHERE parent_id = '$old_code'";
261
        Database::query($sql);
262
263
        // Updating course category
264
        $sql = "UPDATE $tbl_course SET category_code = '$code'
265
            WHERE category_code = '$old_code' ";
266
        Database::query($sql);
267
268
        return true;
269
    }
270
271
    /**
272
     * Move a node up on display.
273
     *
274
     * @param string $code
275
     * @param int    $tree_pos
276
     * @param string $parent_id
277
     *
278
     * @return bool
279
     */
280
    public static function moveNodeUp($code, $tree_pos, $parent_id)
281
    {
282
        $table = Database::get_main_table(TABLE_MAIN_CATEGORY);
283
        $code = Database::escape_string($code);
284
        $tree_pos = intval($tree_pos);
285
        $parent_id = Database::escape_string($parent_id);
286
287
        $parentIdCondition = " AND (parent_id IS NULL OR parent_id = '' )";
288
        if (!empty($parent_id)) {
289
            $parentIdCondition = " AND parent_id = '$parent_id' ";
290
        }
291
292
        $sql = "SELECT code,tree_pos
293
                FROM $table
294
                WHERE
295
                    tree_pos < $tree_pos
296
                    $parentIdCondition
297
                ORDER BY tree_pos DESC
298
                LIMIT 0,1";
299
300
        $result = Database::query($sql);
301
        if (!$row = Database::fetch_array($result)) {
302
            $sql = "SELECT code, tree_pos
303
                    FROM $table
304
                    WHERE
305
                        tree_pos > $tree_pos
306
                        $parentIdCondition
307
                    ORDER BY tree_pos DESC
308
                    LIMIT 0,1";
309
            $result2 = Database::query($sql);
310
            if (!$row = Database::fetch_array($result2)) {
311
                return false;
312
            }
313
        }
314
315
        $sql = "UPDATE $table
316
                SET tree_pos ='".$row['tree_pos']."'
317
                WHERE code='$code'";
318
        Database::query($sql);
319
320
        $sql = "UPDATE $table
321
                SET tree_pos = '$tree_pos'
322
                WHERE code= '".$row['code']."'";
323
        Database::query($sql);
324
325
        return true;
326
    }
327
328
    /**
329
     * Counts the number of children categories a category has.
330
     *
331
     * @param int $categoryId The ID of the category of which we want to count the children
332
     *
333
     * @return mixed The number of subcategories this category has
334
     */
335
    public static function courseCategoryChildrenCount($categoryId)
336
    {
337
        $table = Database::get_main_table(TABLE_MAIN_CATEGORY);
338
        $categoryId = intval($categoryId);
339
        $count = 0;
340
        if (empty($categoryId)) {
341
            return 0;
342
        }
343
        $sql = "SELECT id, code FROM $table 
344
                WHERE parent_id = $categoryId";
345
        $result = Database::query($sql);
346
        while ($row = Database::fetch_array($result)) {
347
            $count += self::courseCategoryChildrenCount($row['id']);
348
        }
349
        $sql = "UPDATE $table SET 
350
                    children_count = $count 
351
                WHERE id = $categoryId";
352
        Database::query($sql);
353
354
        return $count + 1;
355
    }
356
357
    /**
358
     * @param string $categoryCode
359
     *
360
     * @return array
361
     */
362
    public static function getChildren($categoryCode)
363
    {
364
        $table = Database::get_main_table(TABLE_MAIN_CATEGORY);
365
        $categoryCode = Database::escape_string($categoryCode);
366
        $sql = "SELECT code, id FROM $table 
367
                WHERE parent_id = '$categoryCode'";
368
        $result = Database::query($sql);
369
        $children = [];
370
        while ($row = Database::fetch_array($result, 'ASSOC')) {
371
            $children[] = $row;
372
            $subChildren = self::getChildren($row['code']);
373
            $children = array_merge($children, $subChildren);
374
        }
375
376
        return $children;
377
    }
378
379
    /**
380
     * @param string $categoryCode
381
     *
382
     * @return array
383
     */
384
    public static function getParents($categoryCode)
385
    {
386
        if (empty($categoryCode)) {
387
            return [];
388
        }
389
390
        $table = Database::get_main_table(TABLE_MAIN_CATEGORY);
391
        $categoryCode = Database::escape_string($categoryCode);
392
        $sql = "SELECT code, parent_id 
393
                FROM $table
394
                WHERE code = '$categoryCode'";
395
396
        $result = Database::query($sql);
397
        $children = [];
398
        while ($row = Database::fetch_array($result, 'ASSOC')) {
399
            $parent = self::getCategory($row['parent_id']);
400
            $children[] = $row;
401
            $subChildren = self::getParents($parent ? $parent['code'] : null);
402
            $children = array_merge($children, $subChildren);
403
        }
404
405
        return $children;
406
    }
407
408
    /**
409
     * @param string $categoryCode
410
     *
411
     * @return null|string
412
     */
413
    public static function getParentsToString($categoryCode)
414
    {
415
        $parents = self::getParents($categoryCode);
416
417
        if (!empty($parents)) {
418
            $parents = array_reverse($parents);
419
            $categories = [];
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
    public static 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(['class' => 'data_table']);
443
            $column = 0;
444
            $row = 0;
445
            $headers = [
446
                get_lang('Category'),
447
                get_lang('SubCat'),
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(WEB_CODE_PATH).'admin/course_category.php?category='.$categorySource;
457
458
            $editIcon = Display::return_icon(
459
                'edit.png',
460
                get_lang('EditNode'),
461
                null,
462
                ICON_SIZE_SMALL
463
            );
464
            $deleteIcon = Display::return_icon(
465
                'delete.png',
466
                get_lang('DeleteNode'),
467
                null,
468
                ICON_SIZE_SMALL
469
            );
470
            $moveIcon = Display::return_icon(
471
                'up.png',
472
                get_lang('UpInSameLevel'),
473
                null,
474
                ICON_SIZE_SMALL
475
            );
476
477
            $urlId = api_get_current_access_url_id();
478
            foreach ($categories as $category) {
479
                $editUrl = $mainUrl.'&id='.$category['code'].'&action=edit';
480
                $moveUrl = $mainUrl.'&id='.$category['code'].'&action=moveUp&tree_pos='.$category['tree_pos'];
481
                $deleteUrl = $mainUrl.'&id='.$category['code'].'&action=delete';
482
483
                $actions = [];
484
485
                if ($urlId == $category['access_url_id']) {
486
                    $actions[] = Display::url($editIcon, $editUrl);
487
                    $actions[] = Display::url($moveIcon, $moveUrl);
488
                    $actions[] = Display::url($deleteIcon, $deleteUrl);
489
                }
490
491
                $url = api_get_path(WEB_CODE_PATH).'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'].' ('.$category['code'].')',
499
                    $url
500
                );
501
                $content = [
502
                    $title,
503
                    $category['children_count'],
504
                    $category['nbr_courses'],
505
                    implode('', $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
    public static function getCategoriesToDisplayInHomePage()
525
    {
526
        $table = Database::get_main_table(TABLE_MAIN_CATEGORY);
527
        $sql = "SELECT name FROM $table
528
                WHERE parent_id IS NULL
529
                ORDER BY tree_pos";
530
531
        return Database::store_result(Database::query($sql));
532
    }
533
534
    /**
535
     * @param int $id
536
     *
537
     * @return bool
538
     */
539
    public static function addToUrl($id)
540
    {
541
        UrlManager::addCourseCategoryListToUrl(
542
            [$id],
543
            [api_get_current_access_url_id()]
544
        );
545
    }
546
547
    /**
548
     * @param string $categoryCode
549
     *
550
     * @return array
551
     */
552
    public static function getCategoriesCanBeAddedInCourse($categoryCode)
553
    {
554
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE_CATEGORY);
555
        $conditions = " INNER JOIN $table a ON (c.id = a.course_category_id)";
556
        $whereCondition = " AND a.access_url_id = ".api_get_current_access_url_id();
557
558
        $tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
559
        $sql = "SELECT code, name
560
                FROM $tbl_category c
561
                $conditions
562
                WHERE (auth_course_child = 'TRUE' OR code = '".Database::escape_string($categoryCode)."')
563
                $whereCondition
564
                ORDER BY tree_pos";
565
        $res = Database::query($sql);
566
567
        $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...
568
        while ($cat = Database::fetch_array($res)) {
569
            $categories[$cat['code']] = '('.$cat['code'].') '.$cat['name'];
570
            ksort($categories);
571
        }
572
573
        return $categories;
574
    }
575
576
    /**
577
     * @param string $category_code
578
     * @param string $searchTerm
579
     *
580
     * @return int
581
     */
582
    public static function countCoursesInCategory($category_code = '', $searchTerm = '')
583
    {
584
        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
585
        $categoryCode = Database::escape_string($category_code);
586
        $searchTerm = Database::escape_string($searchTerm);
587
        $avoidCoursesCondition = CoursesAndSessionsCatalog::getAvoidCourseCondition();
588
        $visibilityCondition = CourseManager::getCourseVisibilitySQLCondition(
589
            'course',
590
            true
591
        );
592
593
        $categoryFilter = '';
594
        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...
595
            // Nothing to do
596
        } elseif ($categoryCode === 'NONE') {
597
            $categoryFilter = ' AND category_code = "" ';
598
        } else {
599
            $categoryFilter = ' AND category_code = "'.$categoryCode.'" ';
600
        }
601
602
        $searchFilter = '';
603
        if (!empty($searchTerm)) {
604
            $searchFilter = ' AND (
605
                code LIKE "%'.$searchTerm.'%" OR 
606
                title LIKE "%'.$searchTerm.'%" OR 
607
                tutor_name LIKE "%'.$searchTerm.'%"
608
            ) ';
609
        }
610
611
        $url_access_id = api_get_current_access_url_id();
612
        $tbl_url_rel_course = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
613
        $sql = "SELECT * 
614
                FROM $tbl_course as course
615
                INNER JOIN $tbl_url_rel_course as url_rel_course
616
                ON (url_rel_course.c_id = course.id)
617
                WHERE
618
                    access_url_id = $url_access_id AND
619
                    course.visibility != '0' AND
620
                    course.visibility != '4'
621
                    $categoryFilter
622
                    $searchFilter
623
                    $avoidCoursesCondition
624
                    $visibilityCondition
625
            ";
626
627
        return Database::num_rows(Database::query($sql));
628
    }
629
630
    /**
631
     * create recursively all categories as option of the select passed in parameter.
632
     *
633
     * @param HTML_QuickForm_Element $element
634
     * @param string                 $defaultCode the option value to select by default (used mainly for edition of courses)
635
     * @param string                 $parentCode  the parent category of the categories added (default=null for root category)
636
     * @param string                 $padding     the indent param (you shouldn't indicate something here)
637
     */
638
    public static function setCategoriesInForm(
639
        $element,
640
        $defaultCode = null,
641
        $parentCode = null,
642
        $padding = null
643
    ) {
644
        $tbl_category = Database::get_main_table(TABLE_MAIN_CATEGORY);
645
646
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE_CATEGORY);
647
        $conditions = " INNER JOIN $table a ON (c.id = a.course_category_id)";
648
        $whereCondition = " AND a.access_url_id = ".api_get_current_access_url_id();
649
650
        $sql = "SELECT code, name, auth_course_child, auth_cat_child
651
                FROM $tbl_category c
652
                $conditions
653
                WHERE parent_id ".(empty($parentCode) ? "IS NULL" : "='".Database::escape_string($parentCode)."'")."
654
                $whereCondition
655
                ORDER BY name,  code";
656
        $res = Database::query($sql);
657
658
        while ($cat = Database::fetch_array($res, 'ASSOC')) {
659
            $params = $cat['auth_course_child'] == 'TRUE' ? '' : 'disabled';
660
            $params .= ($cat['code'] == $defaultCode) ? ' selected' : '';
661
            $option = $padding.' '.$cat['name'].' ('.$cat['code'].')';
662
663
            $element->addOption($option, $cat['code'], $params);
664
            if ($cat['auth_cat_child'] == 'TRUE') {
665
                self::setCategoriesInForm(
666
                    $element,
667
                    $defaultCode,
668
                    $cat['code'],
669
                    $padding.' - '
670
                );
671
            }
672
        }
673
    }
674
675
    /**
676
     * @param array $list
677
     *
678
     * @return array
679
     */
680
    public static function getCourseCategoryNotInList($list)
681
    {
682
        $table = Database::get_main_table(TABLE_MAIN_CATEGORY);
683
684
        if (empty($list)) {
685
            $sql = "SELECT * FROM $table
686
                    WHERE (parent_id IS NULL) ";
687
            $result = Database::query($sql);
688
689
            return Database::store_result($result, 'ASSOC');
690
        }
691
692
        $list = array_map('intval', $list);
693
        $listToString = implode("','", $list);
694
695
        $sql = "SELECT * FROM $table
696
                WHERE id NOT IN ('$listToString') AND (parent_id IS NULL) ";
697
        $result = Database::query($sql);
698
699
        return Database::store_result($result, 'ASSOC');
700
    }
701
702
    /**
703
     * @param string $keyword
704
     *
705
     * @return array|null
706
     */
707
    public static function searchCategoryByKeyword($keyword)
708
    {
709
        if (empty($keyword)) {
710
            return null;
711
        }
712
713
        $tableCategory = Database::get_main_table(TABLE_MAIN_CATEGORY);
714
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE_CATEGORY);
715
        $conditions = " INNER JOIN $table a ON (c.id = a.course_category_id)";
716
        $whereCondition = " AND a.access_url_id = ".api_get_current_access_url_id();
717
718
        $keyword = Database::escape_string($keyword);
719
720
        $sql = "SELECT c.*, c.name as text
721
                FROM $tableCategory c $conditions
722
                WHERE
723
                (
724
                    c.code LIKE '%$keyword%' OR name LIKE '%$keyword%'
725
                ) AND auth_course_child = 'TRUE'
726
                $whereCondition ";
727
        $result = Database::query($sql);
728
729
        return Database::store_result($result, 'ASSOC');
730
    }
731
732
    /**
733
     * @param array $list
734
     *
735
     * @return array
736
     */
737
    public static function searchCategoryById($list)
738
    {
739
        if (empty($list)) {
740
            return [];
741
        } else {
742
            $list = array_map('intval', $list);
743
            $list = implode("','", $list);
744
        }
745
746
        $tableCategory = Database::get_main_table(TABLE_MAIN_CATEGORY);
747
748
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE_CATEGORY);
749
        $conditions = " INNER JOIN $table a ON (c.id = a.course_category_id)";
750
        $whereCondition = " AND a.access_url_id = ".api_get_current_access_url_id();
751
752
        $sql = "SELECT c.*, c.name as text FROM $tableCategory c $conditions
753
                WHERE c.id IN $list $whereCondition";
754
        $result = Database::query($sql);
755
756
        return Database::store_result($result, 'ASSOC');
757
    }
758
759
    /**
760
     * Get Pagination HTML div.
761
     *
762
     * @param $pageCurrent
763
     * @param $pageLength
764
     * @param $pageTotal
765
     *
766
     * @return string
767
     */
768
    public static function getCatalogPagination($pageCurrent, $pageLength, $pageTotal)
769
    {
770
        // Start empty html
771
        $pageDiv = '';
772
        $html = '';
773
        $pageBottom = max(1, $pageCurrent - 3);
774
        $pageTop = min($pageTotal, $pageCurrent + 3);
775
776
        if ($pageBottom > 1) {
777
            $pageDiv .= self::getPageNumberItem(1, $pageLength);
778
            if ($pageBottom > 2) {
779
                $pageDiv .= self::getPageNumberItem(
780
                    $pageBottom - 1,
781
                    $pageLength,
782
                    null,
783
                    '...'
784
                );
785
            }
786
        }
787
788
        // For each page add its page button to html
789
        for ($i = $pageBottom; $i <= $pageTop; $i++) {
790
            if ($i === $pageCurrent) {
791
                $pageItemAttributes = ['class' => 'active'];
792
            } else {
793
                $pageItemAttributes = [];
794
            }
795
            $pageDiv .= self::getPageNumberItem(
796
                $i,
797
                $pageLength,
798
                $pageItemAttributes
799
            );
800
        }
801
802
        // Check if current page is the last page
803
        if ($pageTop < $pageTotal) {
804
            if ($pageTop < ($pageTotal - 1)) {
805
                $pageDiv .= self::getPageNumberItem(
806
                    $pageTop + 1,
807
                    $pageLength,
808
                    null,
809
                    '...'
810
                );
811
            }
812
            $pageDiv .= self::getPageNumberItem($pageTotal, $pageLength);
813
        }
814
815
        // Complete pagination html
816
        $pageDiv = Display::tag('ul', $pageDiv, ['class' => 'pagination']);
817
        $html .= '<nav>'.$pageDiv.'</nav>';
818
819
        return $html;
820
    }
821
822
    /**
823
     * Return URL to course catalog.
824
     *
825
     * @param int    $pageCurrent
826
     * @param int    $pageLength
827
     * @param string $categoryCode
828
     * @param int    $hiddenLinks
829
     * @param string $action
830
     *
831
     * @return string
832
     */
833
    public static function getCourseCategoryUrl(
834
        $pageCurrent,
835
        $pageLength,
836
        $categoryCode = null,
837
        $hiddenLinks = null,
838
        $action = null
839
    ) {
840
        $requestAction = isset($_REQUEST['action']) ? Security::remove_XSS($_REQUEST['action']) : null;
841
        $action = isset($action) ? Security::remove_XSS($action) : $requestAction;
842
        $searchTerm = isset($_REQUEST['search_term']) ? Security::remove_XSS($_REQUEST['search_term']) : null;
843
844
        if ($action === 'subscribe_user_with_password') {
845
            $action = 'subscribe';
846
        }
847
848
        $categoryCodeRequest = isset($_REQUEST['category_code']) ? Security::remove_XSS($_REQUEST['category_code']) : null;
849
        $categoryCode = isset($categoryCode) ? Security::remove_XSS($categoryCode) : $categoryCodeRequest;
850
        $hiddenLinksRequest = isset($_REQUEST['hidden_links']) ? Security::remove_XSS($_REQUEST['hidden_links']) : null;
851
        $hiddenLinks = isset($hiddenLinks) ? Security::remove_XSS($hiddenLinksRequest) : $categoryCodeRequest;
852
853
        // Start URL with params
854
        $pageUrl = api_get_self().
855
            '?action='.$action.
856
            '&category_code='.$categoryCode.
857
            '&hidden_links='.$hiddenLinks.
858
            '&pageCurrent='.$pageCurrent.
859
            '&pageLength='.$pageLength;
860
861
        switch ($action) {
862
            case 'subscribe':
863
                // for search
864
                $pageUrl .=
865
                    '&search_term='.$searchTerm.
866
                    '&search_course=1'.
867
                    '&sec_token='.Security::getTokenFromSession();
868
                break;
869
            case 'display_courses':
870
            default:
871
                break;
872
        }
873
874
        return $pageUrl;
875
    }
876
877
    /**
878
     * Get li HTML of page number.
879
     *
880
     * @param $pageNumber
881
     * @param $pageLength
882
     * @param array  $liAttributes
883
     * @param string $content
884
     *
885
     * @return string
886
     */
887
    public static function getPageNumberItem(
888
        $pageNumber,
889
        $pageLength,
890
        $liAttributes = [],
891
        $content = ''
892
    ) {
893
        // Get page URL
894
        $url = self::getCourseCategoryUrl(
895
            $pageNumber,
896
            $pageLength
897
        );
898
899
        // If is current page ('active' class) clear URL
900
        if (isset($liAttributes) && is_array($liAttributes) && isset($liAttributes['class'])) {
901
            if (strpos('active', $liAttributes['class']) !== false) {
902
                $url = '';
903
            }
904
        }
905
906
        $content = !empty($content) ? $content : $pageNumber;
907
908
        return Display::tag(
909
            'li',
910
            Display::url(
911
                $content,
912
                $url
913
            ),
914
            $liAttributes
915
        );
916
    }
917
918
    /**
919
     * Return the name tool by action.
920
     *
921
     * @param string $action
922
     *
923
     * @return string
924
     */
925
    public static function getCourseCatalogNameTools($action)
926
    {
927
        $nameTools = get_lang('SortMyCourses');
928
        if (empty($action)) {
929
            return $nameTools; //should never happen
930
        }
931
932
        switch ($action) {
933
            case 'createcoursecategory':
934
                $nameTools = get_lang('CreateCourseCategory');
935
                break;
936
            case 'subscribe':
937
                $nameTools = get_lang('CourseManagement');
938
                break;
939
            case 'subscribe_user_with_password':
940
                $nameTools = get_lang('CourseManagement');
941
                break;
942
            case 'display_random_courses':
943
            case 'display_courses':
944
                $nameTools = get_lang('CourseManagement');
945
                break;
946
            case 'display_sessions':
947
                $nameTools = get_lang('Sessions');
948
                break;
949
            default:
950
                // Nothing to do
951
                break;
952
        }
953
954
        return $nameTools;
955
    }
956
957
    /**
958
     * Save image for a course category.
959
     *
960
     * @param int   $categoryId Course category ID
961
     * @param array $fileData   File data from $_FILES
962
     */
963
    public static function saveImage($categoryId, $fileData)
964
    {
965
        $categoryInfo = self::getCategoryById($categoryId);
966
        if (empty($categoryInfo)) {
967
            return;
968
        }
969
970
        if (!empty($fileData['error'])) {
971
            return;
972
        }
973
974
        $extension = getextension($fileData['name']);
975
        $dirName = 'course_category/';
976
        $fileDir = api_get_path(SYS_UPLOAD_PATH).$dirName;
977
        $fileName = "cc_$categoryId.{$extension[0]}";
978
979
        if (!file_exists($fileDir)) {
980
            mkdir($fileDir, api_get_permissions_for_new_directories(), true);
981
        }
982
983
        $image = new Image($fileData['tmp_name']);
984
        $image->send_image($fileDir.$fileName);
985
986
        $table = Database::get_main_table(TABLE_MAIN_CATEGORY);
987
        Database::update(
988
            $table,
989
            ['image' => $dirName.$fileName],
990
            ['id = ?' => $categoryId]
991
        );
992
    }
993
994
    /**
995
     * @param $categoryId
996
     * @param string $description
997
     *
998
     * @return string
999
     */
1000
    public static function saveDescription($categoryId, $description)
1001
    {
1002
        $categoryInfo = self::getCategoryById($categoryId);
1003
        if (empty($categoryInfo)) {
1004
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type string.
Loading history...
1005
        }
1006
        $table = Database::get_main_table(TABLE_MAIN_CATEGORY);
1007
        Database::update(
1008
            $table,
1009
            ['description' => $description],
1010
            ['id = ?' => $categoryId]
1011
        );
1012
1013
        return true;
0 ignored issues
show
Bug Best Practice introduced by
The expression return true returns the type true which is incompatible with the documented return type string.
Loading history...
1014
    }
1015
}
1016