Passed
Push — master ( f437d8...92f70a )
by Julito
10:14
created

CoursesAndSessionsCatalog::is()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 1
dl 0
loc 8
rs 10
c 0
b 0
f 0
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
use Chamilo\CoreBundle\Entity\ExtraField;
5
use Doctrine\Common\Collections\Criteria;
6
use Doctrine\ORM\Query\Expr\Join;
7
8
/**
9
 * @todo change class name
10
 * Class CoursesAndSessionsCatalog
11
 */
12
class CoursesAndSessionsCatalog
13
{
14
    const PAGE_LENGTH = 12;
15
16
    /**
17
     * Check the configuration for the courses and sessions catalog.
18
     *
19
     * @global array $_configuration Configuration
20
     *
21
     * @param int $value The value to check
22
     *
23
     * @return bool Whether the configuration is $value
24
     */
25
    public static function is($value = CATALOG_COURSES)
26
    {
27
        $showCoursesSessions = (int) api_get_setting('catalog_show_courses_sessions');
28
        if ($showCoursesSessions == $value) {
29
            return true;
30
        }
31
32
        return false;
33
    }
34
35
    /**
36
     * Check whether to display the sessions list.
37
     *
38
     * @global array $_configuration Configuration
39
     *
40
     * @return bool whether to display
41
     */
42
    public static function showSessions()
43
    {
44
        $catalogShow = (int) api_get_setting('catalog_show_courses_sessions');
45
46
        if ($catalogShow == CATALOG_SESSIONS || $catalogShow == CATALOG_COURSES_SESSIONS) {
47
            return true;
48
        }
49
50
        return false;
51
    }
52
53
    /**
54
     * Check whether to display the courses list.
55
     *
56
     * @global array $_configuration Configuration
57
     *
58
     * @return bool whether to display
59
     */
60
    public static function showCourses()
61
    {
62
        $catalogShow = (int) api_get_setting('catalog_show_courses_sessions');
63
64
        if ($catalogShow == CATALOG_COURSES || $catalogShow == CATALOG_COURSES_SESSIONS) {
65
            return true;
66
        }
67
68
        return false;
69
    }
70
71
    /**
72
     * @return array
73
     */
74
    public static function getCoursesToAvoid()
75
    {
76
        $TABLE_COURSE_FIELD = Database::get_main_table(TABLE_EXTRA_FIELD);
77
        $TABLE_COURSE_FIELD_VALUE = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
78
79
        // Check special courses
80
        $courseListToAvoid = CourseManager::get_special_course_list();
81
82
        // Checks "hide_from_catalog" extra field
83
        $extraFieldType = ExtraField::COURSE_FIELD_TYPE;
84
85
        $sql = "SELECT item_id FROM $TABLE_COURSE_FIELD_VALUE tcfv
86
                INNER JOIN $TABLE_COURSE_FIELD tcf
87
                ON tcfv.field_id =  tcf.id
88
                WHERE
89
                    tcf.extra_field_type = $extraFieldType AND
90
                    tcf.variable = 'hide_from_catalog' AND
91
                    tcfv.value = 1
92
                ";
93
94
        $result = Database::query($sql);
95
        if (Database::num_rows($result) > 0) {
96
            while ($row = Database::fetch_array($result)) {
97
                $courseListToAvoid[] = $row['item_id'];
98
            }
99
        }
100
101
        return $courseListToAvoid;
102
    }
103
104
    /**
105
     * @return string
106
     */
107
    public static function getAvoidCourseCondition()
108
    {
109
        $courseListToAvoid = self::getCoursesToAvoid();
110
        $condition = '';
111
        if (!empty($courseListToAvoid)) {
112
            $courses = [];
113
            foreach ($courseListToAvoid as $courseId) {
114
                $courses[] = '"'.$courseId.'"';
115
            }
116
            $condition = ' AND course.id NOT IN ('.implode(',', $courses).')';
117
        }
118
119
        return $condition;
120
    }
121
122
    /**
123
     * Get available le courses count.
124
     *
125
     * @param int $accessUrlId (optional)
126
     *
127
     * @return int Number of courses
128
     */
129
    public static function countAvailableCoursesToShowInCatalog($accessUrlId = 1)
130
    {
131
        $tableCourse = Database::get_main_table(TABLE_MAIN_COURSE);
132
        $tableCourseRelAccessUrl = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
133
        $courseToAvoidCondition = self::getAvoidCourseCondition();
134
        $visibilityCondition = CourseManager::getCourseVisibilitySQLCondition('course', true);
135
136
        $accessUrlId = (int) $accessUrlId;
137
        if (empty($accessUrlId)) {
138
            $accessUrlId = 1;
139
        }
140
141
        $sql = "SELECT count(course.id) 
142
                FROM $tableCourse course
143
                INNER JOIN $tableCourseRelAccessUrl u
144
                ON (course.id = u.c_id)
145
                WHERE
146
                    u.access_url_id = $accessUrlId AND
147
                    course.visibility != 0 AND
148
                    course.visibility != 4
149
                    $courseToAvoidCondition
150
                    $visibilityCondition
151
                ";
152
153
        $res = Database::query($sql);
154
        $row = Database::fetch_row($res);
155
156
        return $row[0];
157
    }
158
159
    public static function getCourseCategoriesTree()
160
    {
161
        $urlId = 1;
162
        if (api_is_multiple_url_enabled()) {
163
            $urlId = api_get_current_access_url_id();
164
        }
165
166
        $countCourses = self::countAvailableCoursesToShowInCatalog($urlId);
167
        $categories = [];
168
        $list = [];
169
170
        $categories['ALL'] = [
171
            'id' => 0,
172
            'name' => get_lang('DisplayAll'),
173
            'code' => 'ALL',
174
            'parent_id' => null,
175
            'tree_pos' => 0,
176
            'number_courses' => $countCourses,
177
            'level' => 0,
178
        ];
179
180
        $allCategories = CourseCategory::getAllCategories();
181
182
        foreach ($allCategories as $category) {
183
            if (empty($category['parent_id'])) {
184
                $list[$category['code']] = $category;
185
                $list[$category['code']]['level'] = 0;
186
                list($subList, $childrenCount) = self::buildCourseCategoryTree($allCategories, $category['code'], 0);
187
                foreach ($subList as $item) {
188
                    $list[$item['code']] = $item;
189
                }
190
                // Real course count
191
                $countCourses = CourseCategory::countCoursesInCategory($category['code']);
192
                $list[$category['code']]['number_courses'] = $childrenCount + $countCourses;
193
            }
194
        }
195
196
        // count courses that are in no category
197
        $countCourses = CourseCategory::countCoursesInCategory();
198
        $categories['NONE'] = [
199
            'id' => 0,
200
            'name' => get_lang('WithoutCategory'),
201
            'code' => 'NONE',
202
            'parent_id' => null,
203
            'tree_pos' => 0,
204
            'children_count' => 0,
205
            'auth_course_child' => true,
206
            'auth_cat_child' => true,
207
            'number_courses' => $countCourses,
208
            'level' => 0,
209
        ];
210
211
        $result = array_merge($list, $categories);
212
213
        return $result;
214
    }
215
216
    /**
217
     * @return array
218
     */
219
    public static function getCourseCategories()
220
    {
221
        $urlId = 1;
222
        if (api_is_multiple_url_enabled()) {
223
            $urlId = api_get_current_access_url_id();
224
        }
225
226
        $countCourses = self::countAvailableCoursesToShowInCatalog($urlId);
227
228
        $categories = [];
229
        $categories[0][0] = [
230
            'id' => 0,
231
            'name' => get_lang('DisplayAll'),
232
            'code' => 'ALL',
233
            'parent_id' => null,
234
            'tree_pos' => 0,
235
            'count_courses' => $countCourses,
236
        ];
237
238
        $categoriesFromDatabase = CourseCategory::getCategories();
239
240
        foreach ($categoriesFromDatabase as $row) {
241
            $countCourses = CourseCategory::countCoursesInCategory($row['code']);
242
            $row['count_courses'] = $countCourses;
243
            if (empty($row['parent_id'])) {
244
                $categories[0][$row['tree_pos']] = $row;
245
            } else {
246
                $categories[$row['parent_id']][$row['tree_pos']] = $row;
247
            }
248
        }
249
250
        // count courses that are in no category
251
        $countCourses = CourseCategory::countCoursesInCategory();
252
        $categories[0][count($categories[0]) + 1] = [
253
            'id' => 0,
254
            'name' => get_lang('None'),
255
            'code' => 'NONE',
256
            'parent_id' => null,
257
            'tree_pos' => $row['tree_pos'] + 1,
258
            'children_count' => 0,
259
            'auth_course_child' => true,
260
            'auth_cat_child' => true,
261
            'count_courses' => $countCourses,
262
        ];
263
264
        return $categories;
265
    }
266
267
    /**
268
     * Return LIMIT to filter SQL query.
269
     *
270
     * @param array $limit
271
     *
272
     * @return string
273
     */
274
    public static function getLimitFilterFromArray($limit)
275
    {
276
        $limitFilter = '';
277
        if (!empty($limit) && is_array($limit)) {
278
            $limitStart = isset($limit['start']) ? (int) $limit['start'] : 0;
279
            $limitLength = isset($limit['length']) ? (int) $limit['length'] : 12;
280
            $limitFilter = 'LIMIT '.$limitStart.', '.$limitLength;
281
        }
282
283
        return $limitFilter;
284
    }
285
286
    /**
287
     * @param string $category_code
288
     * @param int    $random_value
289
     * @param array  $limit         will be used if $random_value is not set.
290
     *                              This array should contains 'start' and 'length' keys
291
     *
292
     * @return array
293
     */
294
    public static function getCoursesInCategory($category_code, $random_value = null, $limit = [])
295
    {
296
        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
297
        $avoidCoursesCondition = self::getAvoidCourseCondition();
298
        $visibilityCondition = CourseManager::getCourseVisibilitySQLCondition('course', true);
299
300
        if (!empty($random_value)) {
301
            $random_value = (int) $random_value;
302
303
            $sql = "SELECT COUNT(*) FROM $tbl_course";
304
            $result = Database::query($sql);
305
            list($num_records) = Database::fetch_row($result);
306
307
            if (api_is_multiple_url_enabled()) {
308
                $urlId = api_get_current_access_url_id();
309
                $tbl_url_rel_course = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
310
311
                $urlCondition = ' access_url_id = '.$urlId.' ';
312
                $allowBaseCategories = api_get_configuration_value('allow_base_course_category');
313
                if ($allowBaseCategories) {
314
                    $urlCondition = ' (access_url_id = '.$urlId.' OR access_url_id = 1)  ';
315
                }
316
317
                $sql = "SELECT COUNT(*) FROM $tbl_course course
318
                        INNER JOIN $tbl_url_rel_course as url_rel_course
319
                        ON (url_rel_course.c_id = course.id)
320
                        WHERE access_url_id = '.$urlId.' ";
321
                $result = Database::query($sql);
322
                list($num_records) = Database::fetch_row($result);
323
324
                $sql = "SELECT course.id, course.id as real_id 
325
                        FROM $tbl_course course
326
                        INNER JOIN $tbl_url_rel_course as url_rel_course
327
                        ON (url_rel_course.c_id = course.id)
328
                        WHERE
329
                            $urlCondition AND
330
                            RAND()*$num_records< $random_value
331
                            $avoidCoursesCondition 
332
                            $visibilityCondition
333
                        ORDER BY RAND()
334
                        LIMIT 0, $random_value";
335
            } else {
336
                $sql = "SELECT id, id as real_id FROM $tbl_course course
337
                        WHERE 
338
                            RAND()*$num_records< $random_value 
339
                            $avoidCoursesCondition 
340
                            $visibilityCondition
341
                        ORDER BY RAND()
342
                        LIMIT 0, $random_value";
343
            }
344
345
            $result = Database::query($sql);
346
            $id_in = null;
347
            while (list($id) = Database::fetch_row($result)) {
348
                if ($id_in) {
349
                    $id_in .= ",$id";
350
                } else {
351
                    $id_in = "$id";
352
                }
353
            }
354
            if ($id_in === null) {
355
                return [];
356
            }
357
            $sql = "SELECT *, id as real_id FROM $tbl_course WHERE id IN($id_in)";
358
        } else {
359
            $limitFilter = self::getLimitFilterFromArray($limit);
360
            $category_code = Database::escape_string($category_code);
361
            $listCode = self::childrenCategories($category_code);
362
            $conditionCode = ' ';
363
364
            if (empty($listCode)) {
365
                if ($category_code === 'NONE') {
366
                    $conditionCode .= " category_code='' ";
367
                } else {
368
                    $conditionCode .= " category_code='$category_code' ";
369
                }
370
            } else {
371
                foreach ($listCode as $code) {
372
                    $conditionCode .= " category_code='$code' OR ";
373
                }
374
                $conditionCode .= " category_code='$category_code' ";
375
            }
376
377
            if (empty($category_code) || $category_code == 'ALL') {
378
                $sql = "SELECT *, id as real_id 
379
                        FROM $tbl_course course
380
                        WHERE
381
                          1=1
382
                          $avoidCoursesCondition
383
                          $visibilityCondition
384
                    ORDER BY title $limitFilter ";
385
            } else {
386
                $sql = "SELECT *, id as real_id FROM $tbl_course course
387
                        WHERE
388
                            $conditionCode 
389
                            $avoidCoursesCondition
390
                            $visibilityCondition
391
                        ORDER BY title $limitFilter ";
392
            }
393
394
            // Showing only the courses of the current Chamilo access_url_id
395
            if (api_is_multiple_url_enabled()) {
396
                $urlId = api_get_current_access_url_id();
397
                $tbl_url_rel_course = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
398
399
                $urlCondition = ' access_url_id = '.$urlId.' ';
400
                if ($category_code != 'ALL') {
401
                    $sql = "SELECT *, course.id real_id FROM $tbl_course as course
402
                            INNER JOIN $tbl_url_rel_course as url_rel_course
403
                            ON (url_rel_course.c_id = course.id)
404
                            WHERE
405
                                $urlCondition AND
406
                                $conditionCode
407
                                $avoidCoursesCondition
408
                                $visibilityCondition
409
                            ORDER BY title $limitFilter";
410
                } else {
411
                    $sql = "SELECT *, course.id real_id FROM $tbl_course as course
412
                            INNER JOIN $tbl_url_rel_course as url_rel_course
413
                            ON (url_rel_course.c_id = course.id)
414
                            WHERE
415
                                $urlCondition
416
                                $avoidCoursesCondition
417
                                $visibilityCondition
418
                            ORDER BY title $limitFilter";
419
                }
420
            }
421
        }
422
423
        $result = Database::query($sql);
424
        $courses = [];
425
        while ($row = Database::fetch_array($result)) {
426
            $row['registration_code'] = !empty($row['registration_code']);
427
            $count_users = CourseManager::get_users_count_in_course($row['code']);
428
            $count_connections_last_month = Tracking::get_course_connections_count(
429
                $row['id'],
430
                0,
431
                api_get_utc_datetime(time() - (30 * 86400))
432
            );
433
434
            if ($row['tutor_name'] == '0') {
435
                $row['tutor_name'] = get_lang('NoManager');
436
            }
437
            $point_info = CourseManager::get_course_ranking($row['id'], 0);
438
            $courses[] = [
439
                'real_id' => $row['real_id'],
440
                'point_info' => $point_info,
441
                'code' => $row['code'],
442
                'directory' => $row['directory'],
443
                'visual_code' => $row['visual_code'],
444
                'title' => $row['title'],
445
                'tutor' => $row['tutor_name'],
446
                'subscribe' => $row['subscribe'],
447
                'unsubscribe' => $row['unsubscribe'],
448
                'registration_code' => $row['registration_code'],
449
                'creation_date' => $row['creation_date'],
450
                'visibility' => $row['visibility'],
451
                'category' => $row['category_code'],
452
                'count_users' => $count_users,
453
                'count_connections' => $count_connections_last_month,
454
            ];
455
        }
456
457
        return $courses;
458
    }
459
460
    /**
461
     * Search the courses database for a course that matches the search term.
462
     * The search is done on the code, title and tutor field of the course table.
463
     *
464
     * @param string $search_term The string that the user submitted, what we are looking for
465
     * @param array  $limit
466
     * @param bool   $justVisible search only on visible courses in the catalogue
467
     *
468
     * @return array an array containing a list of all the courses matching the the search term
469
     */
470
    public static function search_courses($search_term, $limit, $justVisible = false)
471
    {
472
        $courseTable = Database::get_main_table(TABLE_MAIN_COURSE);
473
        $limitFilter = self::getLimitFilterFromArray($limit);
474
        $avoidCoursesCondition = self::getAvoidCourseCondition();
475
        $visibilityCondition = $justVisible ? CourseManager::getCourseVisibilitySQLCondition('course', true) : '';
476
        $search_term_safe = Database::escape_string($search_term);
477
        $sql = "SELECT * FROM $courseTable course
478
                WHERE (
479
                        course.code LIKE '%".$search_term_safe."%' OR
480
                        course.title LIKE '%".$search_term_safe."%' OR
481
                        course.tutor_name LIKE '%".$search_term_safe."%'
482
                    )
483
                    $avoidCoursesCondition
484
                    $visibilityCondition
485
                ORDER BY title, visual_code ASC
486
                $limitFilter
487
                ";
488
489
        if (api_is_multiple_url_enabled()) {
490
            $urlId = api_get_current_access_url_id();
491
            if ($urlId != -1) {
492
                $tbl_url_rel_course = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
493
494
                $urlCondition = ' access_url_id = '.$urlId.' AND';
495
                $allowBaseCategories = api_get_configuration_value('allow_base_course_category');
496
                if ($allowBaseCategories) {
497
                    $urlCondition = ' (access_url_id = '.$urlId.' OR access_url_id = 1) AND ';
498
                }
499
500
                $sql = "SELECT *
501
                            FROM $courseTable as course
502
                            INNER JOIN $tbl_url_rel_course as url_rel_course
503
                            ON (url_rel_course.c_id = course.id)
504
                            WHERE
505
                                access_url_id = $urlId AND 
506
                                (
507
                                    code LIKE '%".$search_term_safe."%' OR
508
                                    title LIKE '%".$search_term_safe."%' OR
509
                                    tutor_name LIKE '%".$search_term_safe."%'
510
                                )
511
                                $avoidCoursesCondition
512
                                $visibilityCondition
513
                            ORDER BY title, visual_code ASC
514
                            $limitFilter
515
                            ";
516
            }
517
        }
518
        $result_find = Database::query($sql);
519
        $courses = [];
520
        while ($row = Database::fetch_array($result_find)) {
521
            $row['registration_code'] = !empty($row['registration_code']);
522
            $count_users = count(CourseManager::get_user_list_from_course_code($row['code']));
523
            $count_connections_last_month = Tracking::get_course_connections_count(
524
                $row['id'],
525
                0,
526
                api_get_utc_datetime(time() - (30 * 86400))
527
            );
528
529
            $point_info = CourseManager::get_course_ranking($row['id'], 0);
530
531
            $courses[] = [
532
                'real_id' => $row['id'],
533
                'point_info' => $point_info,
534
                'code' => $row['code'],
535
                'directory' => $row['directory'],
536
                'visual_code' => $row['visual_code'],
537
                'title' => $row['title'],
538
                'tutor' => $row['tutor_name'],
539
                'subscribe' => $row['subscribe'],
540
                'unsubscribe' => $row['unsubscribe'],
541
                'registration_code' => $row['registration_code'],
542
                'creation_date' => $row['creation_date'],
543
                'visibility' => $row['visibility'],
544
                'count_users' => $count_users,
545
                'count_connections' => $count_connections_last_month,
546
            ];
547
        }
548
549
        return $courses;
550
    }
551
552
    /**
553
     * List the sessions.
554
     *
555
     * @param string $date  (optional) The date of sessions
556
     * @param array  $limit
557
     *
558
     * @throws Exception
559
     *
560
     * @return array The session list
561
     */
562
    public static function browseSessions($date = null, $limit = [])
563
    {
564
        $em = Database::getManager();
565
        $urlId = api_get_current_access_url_id();
566
567
        $sql = "SELECT s.id FROM session s ";
568
        $sql .= "
569
            INNER JOIN access_url_rel_session ars
570
            ON s.id = ars.session_id
571
        ";
572
573
        $sql .= "
574
            WHERE s.nbr_courses > 0
575
                AND ars.access_url_id = $urlId
576
        ";
577
578
        if (!is_null($date)) {
579
            $date = Database::escape_string($date);
580
            $sql .= "
581
                AND (
582
                    ('$date' BETWEEN DATE(s.access_start_date) AND DATE(s.access_end_date))
583
                    OR (s.access_end_date IS NULL)
584
                    OR (
585
                        s.access_start_date IS NULL
586
                        AND s.access_end_date IS NOT NULL
587
                        AND DATE(s.access_end_date) >= '$date'
588
                    )
589
                )
590
            ";
591
        }
592
593
        if (!empty($limit)) {
594
            $limit['start'] = (int) $limit['start'];
595
            $limit['length'] = (int) $limit['length'];
596
            $sql .= "LIMIT {$limit['start']}, {$limit['length']} ";
597
        }
598
599
        $list = Database::store_result(Database::query($sql), 'ASSOC');
600
        $sessions = [];
601
        foreach ($list as $sessionData) {
602
            $id = $sessionData['id'];
603
            $sessions[] = $em->find('ChamiloCoreBundle:Session', $id);
604
        }
605
606
        return $sessions;
607
    }
608
609
    /**
610
     * Search sessions by searched term by session name.
611
     *
612
     * @param string $queryTerm Term for search
613
     * @param array  $limit     Limit info
614
     *
615
     * @return array The sessions
616
     */
617
    public static function browseSessionsBySearch($queryTerm, array $limit)
618
    {
619
        $sessionsToBrowse = [];
620
621
        $criteria = Criteria::create()
622
            ->where(
623
                Criteria::expr()->contains('name', $queryTerm)
624
            )
625
            ->setFirstResult($limit['start'])
626
            ->setMaxResults($limit['length']);
627
628
        $sessions = Database::getManager()
629
            ->getRepository('ChamiloCoreBundle:Session')
630
            ->matching($criteria);
631
632
        foreach ($sessions as $session) {
633
            if ($session->getNbrCourses() === 0) {
634
                continue;
635
            }
636
637
            $sessionsToBrowse[] = $session;
638
        }
639
640
        return $sessionsToBrowse;
641
    }
642
643
    /**
644
     * Search sessions by the tags in their courses.
645
     *
646
     * @param string $termTag Term for search in tags
647
     * @param array  $limit   Limit info
648
     *
649
     * @return array The sessions
650
     */
651
    public static function browseSessionsByTags($termTag, array $limit)
652
    {
653
        $em = Database::getManager();
654
        $qb = $em->createQueryBuilder();
655
656
        $sessions = $qb->select('s')
657
            ->distinct(true)
658
            ->from('ChamiloCoreBundle:Session', 's')
659
            ->innerJoin(
660
                'ChamiloCoreBundle:SessionRelCourse',
661
                'src',
662
                Join::WITH,
663
                's.id = src.session'
664
            )
665
            ->innerJoin(
666
                'ChamiloCoreBundle:ExtraFieldRelTag',
667
                'frt',
668
                Join::WITH,
669
                'src.course = frt.itemId'
670
            )
671
            ->innerJoin(
672
                'ChamiloCoreBundle:Tag',
673
                't',
674
                Join::WITH,
675
                'frt.tagId = t.id'
676
            )
677
            ->innerJoin(
678
                'ChamiloCoreBundle:ExtraField',
679
                'f',
680
                Join::WITH,
681
                'frt.fieldId = f.id'
682
            )
683
            ->where(
684
                $qb->expr()->like('t.tag', ":tag")
685
            )
686
            ->andWhere(
687
                $qb->expr()->eq('f.extraFieldType', ExtraField::COURSE_FIELD_TYPE)
688
            )
689
            ->setFirstResult($limit['start'])
690
            ->setMaxResults($limit['length'])
691
            ->setParameter('tag', "$termTag%")
692
            ->getQuery()
693
            ->getResult();
694
695
        $sessionsToBrowse = [];
696
        foreach ($sessions as $session) {
697
            if ($session->getNbrCourses() === 0) {
698
                continue;
699
            }
700
            $sessionsToBrowse[] = $session;
701
        }
702
703
        return $sessionsToBrowse;
704
    }
705
706
    /**
707
     * Build a recursive tree of course categories.
708
     *
709
     * @param $categories
710
     * @param $parentId
711
     *
712
     * @return array
713
     */
714
    public static function buildCourseCategoryTree($categories, $parentId = 0, $level = 0)
715
    {
716
        $list = [];
717
        $count = 0;
718
        $level++;
719
        foreach ($categories as $category) {
720
            if (empty($category['parent_id'])) {
721
                continue;
722
            }
723
            if ($category['parent_id'] == $parentId) {
724
                $list[$category['code']] = $category;
725
                $count += $category['number_courses'];
726
                $list[$category['code']]['level'] = $level;
727
                list($subList, $childrenCount) = self::buildCourseCategoryTree(
728
                    $categories,
729
                    $category['code'],
730
                    $level
731
                );
732
                $list[$category['code']]['number_courses'] += $childrenCount;
733
                foreach ($subList as $item) {
734
                    $list[$item['code']] = $item;
735
                }
736
                $count += $childrenCount;
737
            }
738
        }
739
740
        return [$list, $count];
741
    }
742
743
    /**
744
     * List Code Search Category.
745
     *
746
     * @param $code
747
     *
748
     * @return array
749
     */
750
    public static function childrenCategories($code)
751
    {
752
        $allCategories = CourseCategory::getAllCategories();
753
        $list = [];
754
        $row = [];
755
756
        if ($code != 'ALL' and $code != 'NONE') {
757
            foreach ($allCategories as $category) {
758
                if ($category['code'] === $code) {
759
                    $list = self::buildCourseCategoryTree($allCategories, $category['code'], 0);
760
                }
761
            }
762
            foreach ($list[0] as $item) {
763
                $row[] = $item['code'];
764
            }
765
        }
766
767
        return $row;
768
    }
769
}
770