Passed
Push — 1.11.x ( 89194e...983a7c )
by Julito
09:11
created

CoursesAndSessionsCatalog::getCoursesToAvoid()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 28
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

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