Passed
Push — 1.11.x ( 401672...5ce8d4 )
by Julito
12:30
created

CoursesAndSessionsCatalog::getRequirements()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 27
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 18
nc 1
nop 4
dl 0
loc 27
rs 9.6666
c 0
b 0
f 0
1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
use Chamilo\CoreBundle\Entity\ExtraField;
6
use Doctrine\ORM\Query\Expr\Join;
7
use Chamilo\CoreBundle\Entity\Repository\SequenceResourceRepository;
8
use Chamilo\CoreBundle\Entity\SequenceResource;
9
use Chamilo\CoreBundle\Entity\SessionRelCourse;
10
use Chamilo\CoreBundle\Entity\Tag;
11
12
/**
13
 * @todo change class name
14
 */
15
class CoursesAndSessionsCatalog
16
{
17
    const PAGE_LENGTH = 12;
18
19
    /**
20
     * Check the configuration for the courses and sessions catalog.
21
     *
22
     * @global array $_configuration Configuration
23
     *
24
     * @param int $value The value to check
25
     *
26
     * @return bool Whether the configuration is $value
27
     */
28
    public static function is($value = CATALOG_COURSES)
29
    {
30
        $showCoursesSessions = (int) api_get_setting('catalog_show_courses_sessions');
31
        if ($showCoursesSessions == $value) {
32
            return true;
33
        }
34
35
        return false;
36
    }
37
38
    /**
39
     * Check whether to display the sessions list.
40
     *
41
     * @global array $_configuration Configuration
42
     *
43
     * @return bool whether to display
44
     */
45
    public static function showSessions()
46
    {
47
        $catalogShow = (int) api_get_setting('catalog_show_courses_sessions');
48
49
        if ($catalogShow == CATALOG_SESSIONS || $catalogShow == CATALOG_COURSES_SESSIONS) {
50
            return true;
51
        }
52
53
        return false;
54
    }
55
56
    /**
57
     * Check whether to display the courses list.
58
     *
59
     * @global array $_configuration Configuration
60
     *
61
     * @return bool whether to display
62
     */
63
    public static function showCourses()
64
    {
65
        $catalogShow = (int) api_get_setting('catalog_show_courses_sessions');
66
67
        if ($catalogShow == CATALOG_COURSES || $catalogShow == CATALOG_COURSES_SESSIONS) {
68
            return true;
69
        }
70
71
        return false;
72
    }
73
74
    /**
75
     * @return array
76
     */
77
    public static function getCoursesToAvoid()
78
    {
79
        $TABLE_COURSE_FIELD = Database::get_main_table(TABLE_EXTRA_FIELD);
80
        $TABLE_COURSE_FIELD_VALUE = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
81
82
        // Check special courses
83
        $courseListToAvoid = CourseManager::get_special_course_list();
84
85
        // Checks "hide_from_catalog" extra field
86
        $extraFieldType = ExtraField::COURSE_FIELD_TYPE;
87
88
        $sql = "SELECT item_id FROM $TABLE_COURSE_FIELD_VALUE tcfv
89
                INNER JOIN $TABLE_COURSE_FIELD tcf
90
                ON tcfv.field_id =  tcf.id
91
                WHERE
92
                    tcf.extra_field_type = $extraFieldType AND
93
                    tcf.variable = 'hide_from_catalog' AND
94
                    tcfv.value = 1
95
                ";
96
97
        $result = Database::query($sql);
98
        if (Database::num_rows($result) > 0) {
99
            while ($row = Database::fetch_array($result)) {
100
                $courseListToAvoid[] = $row['item_id'];
101
            }
102
        }
103
104
        return $courseListToAvoid;
105
    }
106
107
    /**
108
     * @return string
109
     */
110
    public static function getAvoidCourseCondition()
111
    {
112
        $courseListToAvoid = self::getCoursesToAvoid();
113
        $condition = '';
114
        if (!empty($courseListToAvoid)) {
115
            $courses = [];
116
            foreach ($courseListToAvoid as $courseId) {
117
                $courses[] = '"'.$courseId.'"';
118
            }
119
            $condition = ' AND course.id NOT IN ('.implode(',', $courses).')';
120
        }
121
122
        return $condition;
123
    }
124
125
    /**
126
     * Get available le courses count.
127
     *
128
     * @param int $accessUrlId (optional)
129
     *
130
     * @return int Number of courses
131
     */
132
    public static function countAvailableCoursesToShowInCatalog($accessUrlId = 1)
133
    {
134
        $tableCourse = Database::get_main_table(TABLE_MAIN_COURSE);
135
        $tableCourseRelAccessUrl = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
136
        $courseToAvoidCondition = self::getAvoidCourseCondition();
137
        $visibilityCondition = CourseManager::getCourseVisibilitySQLCondition('course', true);
138
139
        $accessUrlId = (int) $accessUrlId;
140
        if (empty($accessUrlId)) {
141
            $accessUrlId = 1;
142
        }
143
144
        $sql = "SELECT count(course.id)
145
                FROM $tableCourse course
146
                INNER JOIN $tableCourseRelAccessUrl u
147
                ON (course.id = u.c_id)
148
                WHERE
149
                    u.access_url_id = $accessUrlId AND
150
                    course.visibility != 0 AND
151
                    course.visibility != 4
152
                    $courseToAvoidCondition
153
                    $visibilityCondition
154
                ";
155
156
        $res = Database::query($sql);
157
        $row = Database::fetch_row($res);
158
159
        return $row[0];
160
    }
161
162
    public static function getCourseCategoriesTree()
163
    {
164
        $urlId = 1;
165
        if (api_is_multiple_url_enabled()) {
166
            $urlId = api_get_current_access_url_id();
167
        }
168
169
        $countCourses = self::countAvailableCoursesToShowInCatalog($urlId);
170
        $categories = [];
171
        $list = [];
172
173
        $categories['ALL'] = [
174
            'id' => 0,
175
            'name' => get_lang('DisplayAll'),
176
            'code' => 'ALL',
177
            'parent_id' => null,
178
            'tree_pos' => 0,
179
            'number_courses' => $countCourses,
180
            'level' => 0,
181
        ];
182
183
        $allCategories = CourseCategory::getAllCategories();
184
185
        foreach ($allCategories as $category) {
186
            if (empty($category['parent_id'])) {
187
                $list[$category['code']] = $category;
188
                $list[$category['code']]['level'] = 0;
189
                list($subList, $childrenCount) = self::buildCourseCategoryTree($allCategories, $category['code'], 0);
190
                foreach ($subList as $item) {
191
                    $list[$item['code']] = $item;
192
                }
193
                // Real course count
194
                $countCourses = CourseCategory::countCoursesInCategory($category['code']);
195
                $list[$category['code']]['number_courses'] = $childrenCount + $countCourses;
196
            }
197
        }
198
199
        // count courses that are in no category
200
        $countCourses = CourseCategory::countCoursesInCategory();
201
        $categories['NONE'] = [
202
            'id' => 0,
203
            'name' => get_lang('WithoutCategory'),
204
            'code' => 'NONE',
205
            'parent_id' => null,
206
            'tree_pos' => 0,
207
            'children_count' => 0,
208
            'auth_course_child' => true,
209
            'auth_cat_child' => true,
210
            'number_courses' => $countCourses,
211
            'level' => 0,
212
        ];
213
214
        return array_merge($list, $categories);
215
    }
216
217
    /**
218
     * @return array
219
     */
220
    public static function getCourseCategories()
221
    {
222
        $urlId = 1;
223
        if (api_is_multiple_url_enabled()) {
224
            $urlId = api_get_current_access_url_id();
225
        }
226
227
        $countCourses = self::countAvailableCoursesToShowInCatalog($urlId);
228
229
        $categories = [];
230
        $categories[0][0] = [
231
            'id' => 0,
232
            'name' => get_lang('DisplayAll'),
233
            'code' => 'ALL',
234
            'parent_id' => null,
235
            'tree_pos' => 0,
236
            'count_courses' => $countCourses,
237
        ];
238
239
        $categoriesFromDatabase = CourseCategory::getCategories();
240
241
        foreach ($categoriesFromDatabase as $row) {
242
            $countCourses = CourseCategory::countCoursesInCategory($row['code']);
243
            $row['count_courses'] = $countCourses;
244
            if (empty($row['parent_id'])) {
245
                $categories[0][$row['tree_pos']] = $row;
246
            } else {
247
                $categories[$row['parent_id']][$row['tree_pos']] = $row;
248
            }
249
        }
250
251
        // count courses that are in no category
252
        $countCourses = CourseCategory::countCoursesInCategory();
253
        $categories[0][count($categories[0]) + 1] = [
254
            'id' => 0,
255
            'name' => get_lang('None'),
256
            'code' => 'NONE',
257
            'parent_id' => null,
258
            'tree_pos' => $row['tree_pos'] + 1,
259
            'children_count' => 0,
260
            'auth_course_child' => true,
261
            'auth_cat_child' => true,
262
            'count_courses' => $countCourses,
263
        ];
264
265
        return $categories;
266
    }
267
268
    /**
269
     * Return LIMIT to filter SQL query.
270
     *
271
     * @param array $limit
272
     *
273
     * @return string
274
     */
275
    public static function getLimitFilterFromArray($limit)
276
    {
277
        $limitFilter = '';
278
        if (!empty($limit) && is_array($limit)) {
279
            $limitStart = isset($limit['start']) ? (int) $limit['start'] : 0;
280
            $limitLength = isset($limit['length']) ? (int) $limit['length'] : 12;
281
            $limitFilter = 'LIMIT '.$limitStart.', '.$limitLength;
282
        }
283
284
        return $limitFilter;
285
    }
286
287
    /**
288
     * @param string $category_code
289
     * @param int    $random_value
290
     * @param array  $limit         will be used if $random_value is not set.
291
     *                              This array should contains 'start' and 'length' keys
292
     *
293
     * @return array
294
     */
295
    public static function getCoursesInCategory($category_code, $random_value = null, $limit = [])
296
    {
297
        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
298
        $avoidCoursesCondition = self::getAvoidCourseCondition();
299
        $visibilityCondition = CourseManager::getCourseVisibilitySQLCondition('course', true);
300
301
        if (!empty($random_value)) {
302
            $random_value = (int) $random_value;
303
304
            $sql = "SELECT COUNT(*) FROM $tbl_course";
305
            $result = Database::query($sql);
306
            list($num_records) = Database::fetch_row($result);
307
308
            if (api_is_multiple_url_enabled()) {
309
                $urlId = api_get_current_access_url_id();
310
                $tbl_url_rel_course = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
311
312
                $urlCondition = ' access_url_id = '.$urlId.' ';
313
                $allowBaseCategories = api_get_configuration_value('allow_base_course_category');
314
                if ($allowBaseCategories) {
315
                    $urlCondition = ' (access_url_id = '.$urlId.' OR access_url_id = 1)  ';
316
                }
317
318
                $sql = "SELECT COUNT(*) FROM $tbl_course course
319
                        INNER JOIN $tbl_url_rel_course as url_rel_course
320
                        ON (url_rel_course.c_id = course.id)
321
                        WHERE access_url_id = '.$urlId.' ";
322
                $result = Database::query($sql);
323
                list($num_records) = Database::fetch_row($result);
324
325
                $sql = "SELECT course.id, course.id as real_id
326
                        FROM $tbl_course course
327
                        INNER JOIN $tbl_url_rel_course as url_rel_course
328
                        ON (url_rel_course.c_id = course.id)
329
                        WHERE
330
                            $urlCondition AND
331
                            RAND()*$num_records< $random_value
332
                            $avoidCoursesCondition
333
                            $visibilityCondition
334
                        ORDER BY RAND()
335
                        LIMIT 0, $random_value";
336
            } else {
337
                $sql = "SELECT id, id as real_id FROM $tbl_course course
338
                        WHERE
339
                            RAND()*$num_records< $random_value
340
                            $avoidCoursesCondition
341
                            $visibilityCondition
342
                        ORDER BY RAND()
343
                        LIMIT 0, $random_value";
344
            }
345
346
            $result = Database::query($sql);
347
            $id_in = null;
348
            while (list($id) = Database::fetch_row($result)) {
349
                if ($id_in) {
350
                    $id_in .= ",$id";
351
                } else {
352
                    $id_in = "$id";
353
                }
354
            }
355
            if ($id_in === null) {
356
                return [];
357
            }
358
            $sql = "SELECT *, id as real_id FROM $tbl_course WHERE id IN($id_in)";
359
        } else {
360
            $limitFilter = self::getLimitFilterFromArray($limit);
361
            $category_code = Database::escape_string($category_code);
362
            $listCode = self::childrenCategories($category_code);
363
            $conditionCode = ' ';
364
365
            if (empty($listCode)) {
366
                if ($category_code === 'NONE') {
367
                    $conditionCode .= " category_code='' ";
368
                } else {
369
                    $conditionCode .= " category_code='$category_code' ";
370
                }
371
            } else {
372
                foreach ($listCode as $code) {
373
                    $conditionCode .= " category_code='$code' OR ";
374
                }
375
                $conditionCode .= " category_code='$category_code' ";
376
            }
377
378
            if (empty($category_code) || $category_code == 'ALL') {
379
                $sql = "SELECT *, id as real_id
380
                        FROM $tbl_course course
381
                        WHERE
382
                          1=1
383
                          $avoidCoursesCondition
384
                          $visibilityCondition
385
                    ORDER BY title $limitFilter ";
386
            } else {
387
                $sql = "SELECT *, id as real_id FROM $tbl_course course
388
                        WHERE
389
                            $conditionCode
390
                            $avoidCoursesCondition
391
                            $visibilityCondition
392
                        ORDER BY title $limitFilter ";
393
            }
394
395
            // Showing only the courses of the current Chamilo access_url_id
396
            if (api_is_multiple_url_enabled()) {
397
                $urlId = api_get_current_access_url_id();
398
                $tbl_url_rel_course = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
399
400
                $urlCondition = ' access_url_id = '.$urlId.' ';
401
                if ($category_code != 'ALL') {
402
                    $sql = "SELECT *, course.id real_id FROM $tbl_course as course
403
                            INNER JOIN $tbl_url_rel_course as url_rel_course
404
                            ON (url_rel_course.c_id = course.id)
405
                            WHERE
406
                                $urlCondition AND
407
                                $conditionCode
408
                                $avoidCoursesCondition
409
                                $visibilityCondition
410
                            ORDER BY title $limitFilter";
411
                } else {
412
                    $sql = "SELECT *, course.id real_id FROM $tbl_course as course
413
                            INNER JOIN $tbl_url_rel_course as url_rel_course
414
                            ON (url_rel_course.c_id = course.id)
415
                            WHERE
416
                                $urlCondition
417
                                $avoidCoursesCondition
418
                                $visibilityCondition
419
                            ORDER BY title $limitFilter";
420
                }
421
            }
422
        }
423
424
        $result = Database::query($sql);
425
        $courses = [];
426
        while ($row = Database::fetch_array($result)) {
427
            $row['registration_code'] = !empty($row['registration_code']);
428
            $count_users = CourseManager::get_users_count_in_course($row['code']);
429
            $count_connections_last_month = Tracking::get_course_connections_count(
430
                $row['id'],
431
                0,
432
                api_get_utc_datetime(time() - (30 * 86400))
433
            );
434
435
            if ($row['tutor_name'] == '0') {
436
                $row['tutor_name'] = get_lang('NoManager');
437
            }
438
            $point_info = CourseManager::get_course_ranking($row['id'], 0);
439
            $courses[] = [
440
                'real_id' => $row['real_id'],
441
                'point_info' => $point_info,
442
                'code' => $row['code'],
443
                'directory' => $row['directory'],
444
                'visual_code' => $row['visual_code'],
445
                'title' => $row['title'],
446
                'tutor' => $row['tutor_name'],
447
                'subscribe' => $row['subscribe'],
448
                'unsubscribe' => $row['unsubscribe'],
449
                'registration_code' => $row['registration_code'],
450
                'creation_date' => $row['creation_date'],
451
                'visibility' => $row['visibility'],
452
                'category' => $row['category_code'],
453
                'count_users' => $count_users,
454
                'count_connections' => $count_connections_last_month,
455
            ];
456
        }
457
458
        return $courses;
459
    }
460
461
    /**
462
     * Search the courses database for a course that matches the search term.
463
     * The search is done on the code, title and tutor field of the course table.
464
     *
465
     * @param string $search_term The string that the user submitted, what we are looking for
466
     * @param array  $limit
467
     * @param bool   $justVisible search only on visible courses in the catalogue
468
     *
469
     * @return array an array containing a list of all the courses matching the the search term
470
     */
471
    public static function search_courses($search_term, $limit, $justVisible = false)
472
    {
473
        $courseTable = Database::get_main_table(TABLE_MAIN_COURSE);
474
        $limitFilter = self::getLimitFilterFromArray($limit);
475
        $avoidCoursesCondition = self::getAvoidCourseCondition();
476
        $visibilityCondition = $justVisible ? CourseManager::getCourseVisibilitySQLCondition('course', true) : '';
477
        $search_term_safe = Database::escape_string($search_term);
478
        $sql = "SELECT * FROM $courseTable course
479
                WHERE (
480
                        course.code LIKE '%".$search_term_safe."%' OR
481
                        course.title LIKE '%".$search_term_safe."%' OR
482
                        course.tutor_name LIKE '%".$search_term_safe."%'
483
                    )
484
                    $avoidCoursesCondition
485
                    $visibilityCondition
486
                ORDER BY title, visual_code ASC
487
                $limitFilter
488
                ";
489
490
        if (api_is_multiple_url_enabled()) {
491
            $urlId = api_get_current_access_url_id();
492
            if ($urlId != -1) {
493
                $tbl_url_rel_course = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
494
495
                $urlCondition = ' access_url_id = '.$urlId.' AND';
496
                $allowBaseCategories = api_get_configuration_value('allow_base_course_category');
497
                if ($allowBaseCategories) {
498
                    $urlCondition = ' (access_url_id = '.$urlId.' OR access_url_id = 1) AND ';
499
                }
500
501
                $sql = "SELECT course.*
502
                        FROM $courseTable as course
503
                        INNER JOIN $tbl_url_rel_course as url_rel_course
504
                        ON (url_rel_course.c_id = course.id)
505
                        WHERE
506
                            access_url_id = $urlId AND
507
                            (
508
                                code LIKE '%".$search_term_safe."%' OR
509
                                title LIKE '%".$search_term_safe."%' OR
510
                                tutor_name LIKE '%".$search_term_safe."%'
511
                            )
512
                            $avoidCoursesCondition
513
                            $visibilityCondition
514
                        ORDER BY title, visual_code ASC
515
                        $limitFilter
516
                       ";
517
            }
518
        }
519
        $result_find = Database::query($sql);
520
        $courses = [];
521
        while ($row = Database::fetch_array($result_find)) {
522
            $row['registration_code'] = !empty($row['registration_code']);
523
            $countUsers = CourseManager::get_user_list_from_course_code(
524
                $row['code'],
525
                0,
526
                null,
527
                null,
528
                null,
529
                true
530
            );
531
            $connectionsLastMonth = Tracking::get_course_connections_count(
532
                $row['id'],
533
                0,
534
                api_get_utc_datetime(time() - (30 * 86400))
535
            );
536
537
            $point_info = CourseManager::get_course_ranking($row['id'], 0);
538
539
            $courses[] = [
540
                'real_id' => $row['id'],
541
                'point_info' => $point_info,
542
                'code' => $row['code'],
543
                'directory' => $row['directory'],
544
                'visual_code' => $row['visual_code'],
545
                'title' => $row['title'],
546
                'tutor' => $row['tutor_name'],
547
                'subscribe' => $row['subscribe'],
548
                'unsubscribe' => $row['unsubscribe'],
549
                'registration_code' => $row['registration_code'],
550
                'creation_date' => $row['creation_date'],
551
                'visibility' => $row['visibility'],
552
                'count_users' => $countUsers,
553
                'count_connections' => $connectionsLastMonth,
554
            ];
555
        }
556
557
        return $courses;
558
    }
559
560
    /**
561
     * List the sessions.
562
     *
563
     * @param string $date
564
     * @param array  $limit
565
     * @param bool   $returnQueryBuilder
566
     * @param bool   $getCount
567
     *
568
     * @return array|\Doctrine\ORM\Query The session list
569
     */
570
    public static function browseSessions($date = null, $limit = [], $returnQueryBuilder = false, $getCount = false)
571
    {
572
        $urlId = api_get_current_access_url_id();
573
574
        /*$dql = "SELECT $select
575
                FROM ChamiloCoreBundle:Session s
576
                WHERE EXISTS
577
                    (
578
                        SELECT url.sessionId FROM ChamiloCoreBundle:AccessUrlRelSession url
579
                        WHERE url.sessionId = s.id AND url.accessUrlId = $urlId
580
                    ) AND
581
                    s.nbrCourses > 0
582
                ";
583
        if (!is_null($date)) {
584
            $date = Database::escape_string($date);
585
            $dql .= "
586
                AND (
587
                    (s.accessEndDate IS NULL)
588
                    OR
589
                    (
590
                    s.accessStartDate IS NOT NULL AND
591
                    s.accessEndDate IS NOT NULL AND
592
                    s.accessStartDate <= '$date' AND s.accessEndDate >= '$date')
593
                    OR
594
                    (
595
                        s.accessStartDate IS NULL AND
596
                        s.accessEndDate IS NOT NULL AND
597
                        s.accessEndDate >= '$date'
598
                    )
599
                )
600
            ";
601
        }*/
602
603
        $em = Database::getManager();
604
        $qb = $em->createQueryBuilder();
605
        $qb2 = $em->createQueryBuilder();
606
607
        $qb = $qb
608
            ->select('s')
609
            ->from('ChamiloCoreBundle:Session', 's')
610
            ->where(
611
                $qb->expr()->in(
612
                    's',
613
                    $qb2
614
                        ->select('s2')
615
                        ->from('ChamiloCoreBundle:AccessUrlRelSession', 'url')
616
                        ->join('ChamiloCoreBundle:Session', 's2')
617
                        ->where(
618
                            $qb->expr()->eq('url.sessionId ', 's2.id')
619
                        )->andWhere(
620
                            $qb->expr()->eq('url.accessUrlId ', $urlId))
621
                        ->getDQL()
622
                )
623
            )
624
            ->andWhere($qb->expr()->gt('s.nbrCourses', 0))
625
        ;
626
627
        if (!is_null($date)) {
628
            $qb->andWhere(
629
        $qb->expr()->orX(
630
                $qb->expr()->isNull('s.accessEndDate'),
631
                    $qb->expr()->andX(
632
                        $qb->expr()->isNotNull('s.accessStartDate'),
633
                        $qb->expr()->isNotNull('s.accessEndDate'),
634
                       $qb->expr()->lte('s.accessStartDate', $date),
635
                        $qb->expr()->gte('s.accessEndDate', $date)
636
                    ),
637
                    $qb->expr()->andX(
638
                        $qb->expr()->isNull('s.accessStartDate'),
639
                        $qb->expr()->isNotNull('s.accessEndDate'),
640
                        $qb->expr()->gte('s.accessEndDate', $date)
641
                    )
642
                )
643
            );
644
        }
645
646
        if ($getCount) {
647
            $qb->select('count(s)');
648
        }
649
650
        $qb = self::hideFromSessionCatalogCondition($qb);
651
652
        if (!empty($limit)) {
653
            $qb
654
                ->setFirstResult($limit['start'])
655
                ->setMaxResults($limit['length'])
656
            ;
657
        }
658
659
        $query = $qb->getQuery();
660
661
        if ($returnQueryBuilder) {
662
            return $query;
663
        }
664
665
        if ($getCount) {
666
            return $query->getSingleScalarResult();
667
        }
668
669
        return $query->getResult();
670
    }
671
672
    /**
673
     * @param \Doctrine\ORM\QueryBuilder $qb
674
     *
675
     * @return mixed
676
     */
677
    public static function hideFromSessionCatalogCondition($qb)
678
    {
679
        $em = Database::getManager();
680
        $qb3 = $em->createQueryBuilder();
681
682
        $extraField = new \ExtraField('session');
683
        $extraFieldInfo = $extraField->get_handler_field_info_by_field_variable('hide_from_catalog');
684
        if (!empty($extraFieldInfo)) {
685
            $qb->andWhere(
686
                $qb->expr()->notIn(
687
                    's',
688
                    $qb3
689
                        ->select('s3')
690
                        ->from('ChamiloCoreBundle:ExtraFieldValues', 'fv')
691
                        ->innerJoin('ChamiloCoreBundle:Session', 's3', Join::WITH, 'fv.itemId = s3.id')
692
                        ->where(
693
                            $qb->expr()->eq('fv.field', $extraFieldInfo['id'])
694
                        )->andWhere(
695
                            $qb->expr()->eq('fv.value ', 1)
696
                        )
697
                        ->getDQL()
698
                )
699
            );
700
        }
701
702
        return $qb;
703
    }
704
705
    /**
706
     * Search sessions by the tags in their courses.
707
     *
708
     * @param string $termTag Term for search in tags
709
     * @param array  $limit   Limit info
710
     *
711
     * @return array The sessions
712
     */
713
    public static function browseSessionsByTags($termTag, array $limit)
714
    {
715
        $em = Database::getManager();
716
        $qb = $em->createQueryBuilder();
717
718
        $urlId = api_get_current_access_url_id();
719
720
        $qb->select('s')
721
            ->distinct()
722
            ->from('ChamiloCoreBundle:Session', 's')
723
            ->innerJoin(
724
                'ChamiloCoreBundle:SessionRelCourse',
725
                'src',
726
                Join::WITH,
727
                's.id = src.session'
728
            )
729
            ->innerJoin(
730
                'ChamiloCoreBundle:AccessUrlRelSession',
731
                'url',
732
                Join::WITH,
733
                'url.sessionId = s.id'
734
            )
735
            ->innerJoin(
736
                'ChamiloCoreBundle:ExtraFieldRelTag',
737
                'frt',
738
                Join::WITH,
739
                'src.course = frt.itemId'
740
            )
741
            ->innerJoin(
742
                'ChamiloCoreBundle:Tag',
743
                't',
744
                Join::WITH,
745
                'frt.tagId = t.id'
746
            )
747
            ->innerJoin(
748
                'ChamiloCoreBundle:ExtraField',
749
                'f',
750
                Join::WITH,
751
                'frt.fieldId = f.id'
752
            )
753
            ->where(
754
                $qb->expr()->like('t.tag', ':tag')
755
            )
756
            ->andWhere(
757
                $qb->expr()->eq('f.extraFieldType', ExtraField::COURSE_FIELD_TYPE)
758
            )
759
            ->andWhere(
760
                $qb->expr()->gt('s.nbrCourses', 0)
761
            )
762
            ->andWhere(
763
                $qb->expr()->eq('url.accessUrlId', $urlId)
764
            )
765
            ->setFirstResult($limit['start'])
766
            ->setMaxResults($limit['length'])
767
            ->setParameter('tag', "$termTag%")
768
            ;
769
770
        $qb = self::hideFromSessionCatalogCondition($qb);
771
772
        return $qb->getQuery()->getResult();
773
    }
774
775
    /**
776
     * Search sessions by the title.
777
     *
778
     * @param string $keyword
779
     * @param array  $limit   Limit info
780
     *
781
     * @return array The sessions
782
     */
783
    public static function getSessionsByName($keyword, array $limit)
784
    {
785
        $em = Database::getManager();
786
        $qb = $em->createQueryBuilder();
787
788
        $urlId = api_get_current_access_url_id();
789
790
        $qb->select('s')
791
            ->distinct()
792
            ->from('ChamiloCoreBundle:Session', 's')
793
            ->innerJoin(
794
                'ChamiloCoreBundle:SessionRelCourse',
795
                'src',
796
                Join::WITH,
797
                's.id = src.session'
798
            )
799
            ->innerJoin(
800
                'ChamiloCoreBundle:AccessUrlRelSession',
801
                'url',
802
                Join::WITH,
803
                'url.sessionId = s.id'
804
            )
805
            ->andWhere(
806
                $qb->expr()->eq('url.accessUrlId', $urlId)
807
            )->andWhere(
808
                's.name LIKE :keyword'
809
            )
810
            ->andWhere(
811
                $qb->expr()->gt('s.nbrCourses', 0)
812
            )
813
            ->setFirstResult($limit['start'])
814
            ->setMaxResults($limit['length'])
815
            ->setParameter('keyword', "%$keyword%")
816
        ;
817
818
        $qb = self::hideFromSessionCatalogCondition($qb);
819
820
        return $qb->getQuery()->getResult();
821
    }
822
823
    /**
824
     * Build a recursive tree of course categories.
825
     *
826
     * @param array $categories
827
     * @param int   $parentId
828
     * @param int   $level
829
     *
830
     * @return array
831
     */
832
    public static function buildCourseCategoryTree($categories, $parentId = 0, $level = 0)
833
    {
834
        $list = [];
835
        $count = 0;
836
        $level++;
837
        foreach ($categories as $category) {
838
            if (empty($category['parent_id'])) {
839
                continue;
840
            }
841
            if ($category['parent_id'] == $parentId) {
842
                $list[$category['code']] = $category;
843
                $count += $category['number_courses'];
844
                $list[$category['code']]['level'] = $level;
845
                list($subList, $childrenCount) = self::buildCourseCategoryTree(
846
                    $categories,
847
                    $category['code'],
848
                    $level
849
                );
850
                $list[$category['code']]['number_courses'] += $childrenCount;
851
                foreach ($subList as $item) {
852
                    $list[$item['code']] = $item;
853
                }
854
                $count += $childrenCount;
855
            }
856
        }
857
858
        return [$list, $count];
859
    }
860
861
    /**
862
     * List Code Search Category.
863
     *
864
     * @param string $code
865
     *
866
     * @return array
867
     */
868
    public static function childrenCategories($code)
869
    {
870
        $allCategories = CourseCategory::getAllCategories();
871
        $list = [];
872
        $row = [];
873
874
        if ($code != 'ALL' and $code != 'NONE') {
875
            foreach ($allCategories as $category) {
876
                if ($category['code'] === $code) {
877
                    $list = self::buildCourseCategoryTree($allCategories, $category['code'], 0);
878
                }
879
            }
880
            foreach ($list[0] as $item) {
881
                $row[] = $item['code'];
882
            }
883
        }
884
885
        return $row;
886
    }
887
888
    public static function getOptionSelect($categories, $codeType)
889
    {
890
        $html = '';
891
        $html .= '<select name="category_code" onchange="submit();" class="selectpicker form-control">';
892
        foreach ($categories as $category) {
893
            $categoryCode = Security::remove_XSS($category['code']);
894
            $categoryName = Security::remove_XSS($category['name']);
895
            $countCourse = (int) $category['number_courses'];
896
            $level = $category['level'];
897
            if (empty($countCourse)) {
898
                continue;
899
            }
900
            if ($level > 0) {
901
                $separate = str_repeat('--', $level);
902
            } else {
903
                $separate = '';
904
            }
905
            $html .= '<option '.($categoryCode == $codeType ? 'selected="selected" ' : '')
906
                .' value="'.$categoryCode.'">'.$separate.' '.$categoryName.' ('.$countCourse.') </option>';
907
        }
908
        $html .= '</select>';
909
910
        return $html;
911
    }
912
913
    /**
914
     * Display the course catalog image of a course.
915
     *
916
     * @param array $course
917
     * @param bool  $registeredUser
918
     *
919
     * @return string HTML string
920
     */
921
    public static function returnThumbnail($course, $registeredUser)
922
    {
923
        $html = '';
924
        $title = cut($course['title'], 70);
925
        $linkCourse = api_get_path(WEB_PATH).'course/'.$course['real_id'].'/about';
926
        // course path
927
        $course_path = api_get_path(SYS_COURSE_PATH).$course['directory'];
928
929
        if (file_exists($course_path.'/course-pic.png')) {
930
            // redimensioned image 85x85
931
            $courseMediumImage = api_get_path(WEB_COURSE_PATH).$course['directory'].'/course-pic.png';
932
        } else {
933
            // without picture
934
            $courseMediumImage = Display::return_icon(
935
                'session_default.png',
936
                null,
937
                null,
938
                null,
939
                null,
940
                true
941
            );
942
        }
943
944
        $html .= '<div class="image">';
945
        $html .= '<a href="'.$linkCourse.'" title="'.$course['title'].'">'
946
            .'<img class="img-responsive" src="'.$courseMediumImage.'" '
947
            .'alt="'.api_htmlentities($title).'"/></a>';
948
949
        $categoryTitle = isset($course['category_title']) ? $course['category_title'] : '';
950
        if (!empty($categoryTitle)) {
951
            $html .= '<span class="category">'.$categoryTitle.'</span>';
952
            $html .= '<div class="cribbon"></div>';
953
        }
954
955
        $html .= '<div class="user-actions">';
956
        $html .= CourseManager::returnDescriptionButton($course);
957
        $html .= '</div></div>';
958
959
        return $html;
960
    }
961
962
    /**
963
     * @param array $courseInfo
964
     *
965
     * @return string
966
     */
967
    public static function return_teacher($courseInfo)
968
    {
969
        $teachers = CourseManager::getTeachersFromCourse($courseInfo['real_id']);
970
        $length = count($teachers);
971
972
        if (!$length) {
973
            return '';
974
        }
975
976
        $html = '<div class="block-author">';
977
        if ($length > 6) {
978
            $html .= '<a
979
            id="plist"
980
            data-trigger="focus"
981
            tabindex="0" role="button"
982
            class="btn btn-default panel_popover"
983
            data-toggle="popover"
984
            title="'.addslashes(get_lang('CourseTeachers')).'"
985
            data-html="true"
986
        >
987
            <i class="fa fa-graduation-cap" aria-hidden="true"></i>
988
        </a>';
989
            $html .= '<div id="popover-content-plist" class="hide">';
990
            foreach ($teachers as $value) {
991
                $name = $value['firstname'].' '.$value['lastname'];
992
                $html .= '<div class="popover-teacher">';
993
                $html .= '<a href="'.$value['url'].'" class="ajax" data-title="'.$name.'" title="'.$name.'">
994
                        <img src="'.$value['avatar'].'" title="'.$name.'" alt="'.get_lang('UserPicture').'"/></a>';
995
                $html .= '<div class="teachers-details"><h5>
996
                        <a href="'.$value['url'].'" class="ajax" data-title="'.$name.'" title="'.$name.'">'
997
                    .$name.'</a></h5></div>';
998
                $html .= '</div>';
999
            }
1000
            $html .= '</div>';
1001
        } else {
1002
            foreach ($teachers as $value) {
1003
                $name = $value['firstname'].' '.$value['lastname'];
1004
                if ($length > 2) {
1005
                    $html .= '<a href="'.$value['url'].'" class="ajax" data-title="'.$name.'" title="'.$name.'">
1006
                        <img src="'.$value['avatar'].'" title="'.$name.'" alt="'.get_lang('UserPicture').'"/></a>';
1007
                } else {
1008
                    $html .= '<a href="'.$value['url'].'" class="ajax" data-title="'.$name.'" title="'.$name.'">
1009
                        <img src="'.$value['avatar'].'" title="'.$name.'" alt="'.get_lang('UserPicture').'"/></a>';
1010
                    $html .= '<div class="teachers-details"><h5>
1011
                        <a href="'.$value['url'].'" class="ajax" data-title="'.$name.'">'
1012
                        .$name.'</a></h5><p>'.get_lang('Teacher').'</p></div>';
1013
                }
1014
            }
1015
        }
1016
        $html .= '</div>';
1017
1018
        return $html;
1019
    }
1020
1021
    /**
1022
     * Display the title of a course in course catalog.
1023
     *
1024
     * @param array $course
1025
     * @param bool  $registeredUser
1026
     *
1027
     * @return string HTML string
1028
     */
1029
    public static function return_title($course, $registeredUser)
1030
    {
1031
        //$linkCourse = api_get_course_url($course['code']);
1032
        $linkCourse = api_get_path(WEB_PATH).'course/'.$course['real_id'].'/about';
1033
        $html = '<div class="block-title"><h4 class="title">';
1034
        $html .= '<a title="'.$course['title'].'" href="'.$linkCourse.'">'.$course['title'].'</a>';
1035
        $html .= '</h4></div>';
1036
1037
        if (api_get_configuration_value('hide_course_rating') === false) {
1038
            $ajax_url = api_get_path(WEB_AJAX_PATH).'course.ajax.php?a=add_course_vote';
1039
            $rating = Display::return_rating_system(
1040
                'star_'.$course['real_id'],
1041
                $ajax_url.'&course_id='.$course['real_id'],
1042
                $course['point_info']
1043
            );
1044
            $html .= '<div class="ranking">'.$rating.'</div>';
1045
        }
1046
1047
        return $html;
1048
    }
1049
1050
    /**
1051
     * Display the already registerd text in a course in the course catalog.
1052
     *
1053
     * @param $in_status
1054
     *
1055
     * @return string HTML string
1056
     */
1057
    public static function return_already_registered_label($in_status)
1058
    {
1059
        $icon = '<em class="fa fa-check"></em>';
1060
        $title = get_lang('YouAreATeacherOfThisCourse');
1061
        if ($in_status == 'student') {
1062
            $icon = '<em class="fa fa-check"></em>';
1063
            $title = get_lang('AlreadySubscribed');
1064
        }
1065
1066
        $html = Display::tag(
1067
            'span',
1068
            $icon.' '.$title,
1069
            [
1070
                'id' => 'register',
1071
                'class' => 'label-subscribed text-success',
1072
                'title' => $title,
1073
                'aria-label' => $title,
1074
            ]
1075
        );
1076
1077
        return $html.PHP_EOL;
1078
    }
1079
1080
    /**
1081
     * Display the register button of a course in the course catalog.
1082
     *
1083
     * @param $course
1084
     * @param $stok
1085
     * @param $code
1086
     * @param $search_term
1087
     *
1088
     * @return string
1089
     */
1090
    public static function return_register_button($course, $stok, $code, $search_term)
1091
    {
1092
        $title = get_lang('Subscribe');
1093
        $action = 'subscribe_course';
1094
        if (!empty($course['registration_code'])) {
1095
            $action = 'subscribe_course_validation';
1096
        }
1097
1098
        return Display::url(
1099
            Display::returnFontAwesomeIcon('check').' '.$title,
1100
            api_get_self().'?action='.$action.'&sec_token='.$stok.
1101
            '&course_code='.$course['code'].'&search_term='.$search_term.'&category_code='.$code,
1102
            ['class' => 'btn btn-success btn-sm', 'title' => $title, 'aria-label' => $title]
1103
        );
1104
    }
1105
1106
    /**
1107
     * Display the unregister button of a course in the course catalog.
1108
     *
1109
     * @param $course
1110
     * @param $stok
1111
     * @param $search_term
1112
     * @param $code
1113
     *
1114
     * @return string
1115
     */
1116
    public static function return_unregister_button($course, $stok, $search_term, $code)
1117
    {
1118
        $title = get_lang('Unsubscription');
1119
1120
        return Display::url(
1121
            Display::returnFontAwesomeIcon('sign-in').' '.$title,
1122
            api_get_self().'?action=unsubscribe&sec_token='.$stok
1123
            .'&course_code='.$course['code'].'&search_term='.$search_term.'&category_code='.$code,
1124
            ['class' => 'btn btn-danger btn-sm', 'title' => $title, 'aria-label' => $title]
1125
        );
1126
    }
1127
1128
    /**
1129
     * Get a HTML button for subscribe to session.
1130
     *
1131
     * @param int    $sessionId         The session ID
1132
     * @param string $sessionName       The session name
1133
     * @param bool   $checkRequirements Optional.
1134
     *                                  Whether the session has requirement. Default is false
1135
     * @param bool   $includeText       Optional. Whether show the text in button
1136
     * @param bool   $btnBing
1137
     *
1138
     * @return string The button HTML
1139
     */
1140
    public static function getRegisteredInSessionButton(
1141
        $sessionId,
1142
        $sessionName,
1143
        $checkRequirements = false,
1144
        $includeText = false,
1145
        $btnBing = false
1146
    ) {
1147
        $sessionId = (int) $sessionId;
1148
1149
        if ($btnBing) {
1150
            $btnBing = 'btn-lg btn-block';
1151
        } else {
1152
            $btnBing = 'btn-sm';
1153
        }
1154
1155
        if ($checkRequirements) {
1156
            return self::getRequirements($sessionId, SequenceResource::SESSION_TYPE, $includeText, $btnBing);
1157
        }
1158
1159
        $catalogSessionAutoSubscriptionAllowed = false;
1160
        if (api_get_setting('catalog_allow_session_auto_subscription') === 'true') {
1161
            $catalogSessionAutoSubscriptionAllowed = true;
1162
        }
1163
1164
        $url = api_get_path(WEB_CODE_PATH);
1165
1166
        if ($catalogSessionAutoSubscriptionAllowed) {
1167
            $url .= 'auth/courses.php?';
1168
            $url .= http_build_query([
1169
                'action' => 'subscribe_to_session',
1170
                'session_id' => $sessionId,
1171
            ]);
1172
1173
            $result = Display::toolbarButton(
1174
                get_lang('Subscribe'),
1175
                $url,
1176
                'pencil',
1177
                'primary',
1178
                [
1179
                    'class' => $btnBing.' ajax',
1180
                    'data-title' => get_lang('AreYouSureToSubscribe'),
1181
                    'data-size' => 'md',
1182
                    'title' => get_lang('Subscribe'),
1183
                ],
1184
                $includeText
1185
            );
1186
        } else {
1187
            $url .= 'inc/email_editor.php?';
1188
            $url .= http_build_query([
1189
                'action' => 'subscribe_me_to_session',
1190
                'session' => Security::remove_XSS($sessionName),
1191
            ]);
1192
1193
            $result = Display::toolbarButton(
1194
                get_lang('SubscribeToSessionRequest'),
1195
                $url,
1196
                'pencil',
1197
                'primary',
1198
                ['class' => $btnBing],
1199
                $includeText
1200
            );
1201
        }
1202
1203
        $hook = HookResubscribe::create();
1204
        if (!empty($hook)) {
1205
            $hook->setEventData([
1206
                'session_id' => $sessionId,
1207
            ]);
1208
            try {
1209
                $hook->notifyResubscribe(HOOK_EVENT_TYPE_PRE);
1210
            } catch (Exception $exception) {
1211
                $result = $exception->getMessage();
1212
            }
1213
        }
1214
1215
        return $result;
1216
    }
1217
1218
    public static function getRequirements($id, $type, $includeText, $btnBing)
1219
    {
1220
        $id = (int) $id;
1221
        $type = (int) $type;
1222
1223
        $url = api_get_path(WEB_AJAX_PATH);
1224
        $url .= 'sequence.ajax.php?';
1225
        $url .= http_build_query(
1226
            [
1227
                'a' => 'get_requirements',
1228
                'id' => $id,
1229
                'type' => $type,
1230
            ]
1231
        );
1232
1233
        return Display::toolbarButton(
1234
            get_lang('CheckRequirements'),
1235
            $url,
1236
            'shield',
1237
            'info',
1238
            [
1239
                'class' => $btnBing.' ajax',
1240
                'data-title' => get_lang('CheckRequirements'),
1241
                'data-size' => 'md',
1242
                'title' => get_lang('CheckRequirements'),
1243
            ],
1244
            $includeText
1245
        );
1246
    }
1247
1248
    /**
1249
     * Generate a label if the user has been  registered in session.
1250
     *
1251
     * @return string The label
1252
     */
1253
    public static function getAlreadyRegisteredInSessionLabel()
1254
    {
1255
        $icon = '<em class="fa fa-graduation-cap"></em>';
1256
1257
        return Display::div(
1258
            $icon,
1259
            [
1260
                'class' => 'btn btn-default btn-sm registered',
1261
                'title' => get_lang("AlreadyRegisteredToSession"),
1262
            ]
1263
        );
1264
    }
1265
1266
    /**
1267
     * Get a icon for a session.
1268
     *
1269
     * @param string $sessionName The session name
1270
     *
1271
     * @return string The icon
1272
     */
1273
    public static function getSessionIcon($sessionName)
1274
    {
1275
        return Display::return_icon(
1276
            'window_list.png',
1277
            $sessionName,
1278
            null,
1279
            ICON_SIZE_MEDIUM
1280
        );
1281
    }
1282
1283
    /**
1284
     * Return Session catalog rendered view.
1285
     *
1286
     * @param array $limit
1287
     */
1288
    public static function sessionList($limit = [])
1289
    {
1290
        $date = isset($_POST['date']) ? $_POST['date'] : date('Y-m-d');
1291
        $hiddenLinks = isset($_GET['hidden_links']) ? $_GET['hidden_links'] == 1 : false;
1292
        $limit = isset($limit) ? $limit : self::getLimitArray();
1293
1294
        $countSessions = self::browseSessions($date, [], false, true);
1295
        $sessions = self::browseSessions($date, $limit);
1296
1297
        $pageTotal = ceil($countSessions / $limit['length']);
1298
        // Do NOT show pagination if only one page or less
1299
        $pagination = $pageTotal > 1 ? CourseCategory::getCatalogPagination($limit['current'], $limit['length'], $pageTotal) : '';
1300
        $sessionsBlocks = self::getFormattedSessionsBlock($sessions);
1301
1302
        // Get session search catalogue URL
1303
        $courseUrl = CourseCategory::getCourseCategoryUrl(
1304
            1,
1305
            $limit['length'],
1306
            null,
1307
            0,
1308
            'subscribe'
1309
        );
1310
1311
        $tpl = new Template();
1312
        $tpl->assign('actions', self::getTabList(2));
1313
        $tpl->assign('show_courses', self::showCourses());
1314
        $tpl->assign('show_sessions', self::showSessions());
1315
        $tpl->assign('show_tutor', api_get_setting('show_session_coach') === 'true');
1316
        $tpl->assign('course_url', $courseUrl);
1317
        $tpl->assign('catalog_pagination', $pagination);
1318
        $tpl->assign('hidden_links', $hiddenLinks);
1319
        $tpl->assign('search_token', Security::get_token());
1320
        $tpl->assign('search_date', $date);
1321
        $tpl->assign('web_session_courses_ajax_url', api_get_path(WEB_AJAX_PATH).'course.ajax.php');
1322
        $tpl->assign('sessions', $sessionsBlocks);
1323
        $tpl->assign('already_subscribed_label', self::getAlreadyRegisteredInSessionLabel());
1324
        $tpl->assign('catalog_settings', self::getCatalogSearchSettings());
1325
1326
        $contentTemplate = $tpl->get_template('auth/session_catalog.tpl');
1327
1328
        $tpl->display($contentTemplate);
1329
    }
1330
1331
    /**
1332
     * Show the Session Catalogue with filtered session by course tags.
1333
     *
1334
     * @param array $limit Limit info
1335
     */
1336
    public static function sessionsListByName(array $limit)
1337
    {
1338
        $keyword = isset($_POST['keyword']) ? $_POST['keyword'] : null;
1339
        $hiddenLinks = isset($_GET['hidden_links']) ? (int) $_GET['hidden_links'] == 1 : false;
1340
        $courseUrl = CourseCategory::getCourseCategoryUrl(
1341
            1,
1342
            $limit['length'],
1343
            null,
1344
            0,
1345
            'subscribe'
1346
        );
1347
1348
        $sessions = self::getSessionsByName($keyword, $limit);
1349
        $sessionsBlocks = self::getFormattedSessionsBlock($sessions);
1350
1351
        $tpl = new Template();
1352
        $tpl->assign('actions', self::getTabList(2));
1353
        $tpl->assign('show_courses', self::showCourses());
1354
        $tpl->assign('show_sessions', self::showSessions());
1355
        $tpl->assign('show_tutor', api_get_setting('show_session_coach') === 'true' ? true : false);
1356
        $tpl->assign('course_url', $courseUrl);
1357
        $tpl->assign('already_subscribed_label', self::getAlreadyRegisteredInSessionLabel());
1358
        $tpl->assign('hidden_links', $hiddenLinks);
1359
        $tpl->assign('search_token', Security::get_token());
1360
        $tpl->assign('keyword', Security::remove_XSS($keyword));
1361
        $tpl->assign('sessions', $sessionsBlocks);
1362
        $tpl->assign('catalog_settings', self::getCatalogSearchSettings());
1363
1364
        $contentTemplate = $tpl->get_template('auth/session_catalog.tpl');
1365
1366
        $tpl->display($contentTemplate);
1367
    }
1368
1369
    public static function getCatalogSearchSettings()
1370
    {
1371
        $settings = api_get_configuration_value('catalog_settings');
1372
        if (empty($settings)) {
1373
            // Default everything is visible
1374
            $settings = [
1375
                'sessions' => [
1376
                    'by_title' => true,
1377
                    'by_date' => true,
1378
                    'by_tag' => true,
1379
                    'show_session_info' => true,
1380
                    'show_session_date' => true,
1381
                ],
1382
            ];
1383
        }
1384
1385
        return $settings;
1386
    }
1387
1388
    /**
1389
     * @param int $active
1390
     *
1391
     * @return string
1392
     */
1393
    public static function getTabList($active = 1)
1394
    {
1395
        $pageLength = isset($_GET['pageLength']) ? (int) $_GET['pageLength'] : self::PAGE_LENGTH;
1396
1397
        $url = CourseCategory::getCourseCategoryUrl(1, $pageLength, null, 0, 'display_sessions');
1398
        $headers = [];
1399
        if (self::showCourses()) {
1400
            $headers[] = [
1401
                'url' => api_get_self(),
1402
                'content' => get_lang('CourseManagement'),
1403
            ];
1404
        }
1405
1406
        if (self::showSessions()) {
1407
            $headers[] = [
1408
                'url' => $url,
1409
                'content' => get_lang('SessionList'),
1410
            ];
1411
        }
1412
1413
        return Display::tabsOnlyLink($headers, $active);
1414
    }
1415
1416
    /**
1417
     * Show the Session Catalogue with filtered session by course tags.
1418
     *
1419
     * @param array $limit Limit info
1420
     */
1421
    public static function sessionsListByCoursesTag(array $limit)
1422
    {
1423
        $searchTag = isset($_POST['search_tag']) ? $_POST['search_tag'] : null;
1424
        $searchDate = isset($_POST['date']) ? $_POST['date'] : date('Y-m-d');
1425
        $hiddenLinks = isset($_GET['hidden_links']) ? (int) $_GET['hidden_links'] == 1 : false;
1426
        $courseUrl = CourseCategory::getCourseCategoryUrl(
1427
            1,
1428
            $limit['length'],
1429
            null,
1430
            0,
1431
            'subscribe'
1432
        );
1433
1434
        $sessions = self::browseSessionsByTags($searchTag, $limit);
1435
        $sessionsBlocks = self::getFormattedSessionsBlock($sessions);
1436
1437
        $tpl = new Template();
1438
        $tpl->assign('show_courses', self::showCourses());
1439
        $tpl->assign('show_sessions', self::showSessions());
1440
        $tpl->assign('show_tutor', api_get_setting('show_session_coach') === 'true' ? true : false);
1441
        $tpl->assign('course_url', $courseUrl);
1442
        $tpl->assign('already_subscribed_label', self::getAlreadyRegisteredInSessionLabel());
1443
        $tpl->assign('hidden_links', $hiddenLinks);
1444
        $tpl->assign('search_token', Security::get_token());
1445
        $tpl->assign('search_date', Security::remove_XSS($searchDate));
1446
        $tpl->assign('search_tag', Security::remove_XSS($searchTag));
1447
        $tpl->assign('sessions', $sessionsBlocks);
1448
1449
        $contentTemplate = $tpl->get_template('auth/session_catalog.tpl');
1450
1451
        $tpl->display($contentTemplate);
1452
    }
1453
1454
    /**
1455
     * @return array
1456
     */
1457
    public static function getLimitArray()
1458
    {
1459
        $pageCurrent = isset($_REQUEST['pageCurrent']) ? (int) $_GET['pageCurrent'] : 1;
1460
        $pageLength = isset($_REQUEST['pageLength']) ? (int) $_GET['pageLength'] : self::PAGE_LENGTH;
1461
1462
        return [
1463
            'start' => ($pageCurrent - 1) * $pageLength,
1464
            'current' => $pageCurrent,
1465
            'length' => $pageLength,
1466
        ];
1467
    }
1468
1469
    /**
1470
     * Get the formatted data for sessions block to be displayed on Session Catalog page.
1471
     *
1472
     * @param array $sessions The session list
1473
     *
1474
     * @return array
1475
     */
1476
    public static function getFormattedSessionsBlock(array $sessions)
1477
    {
1478
        $extraFieldValue = new ExtraFieldValue('session');
1479
        $userId = api_get_user_id();
1480
        $sessionsBlocks = [];
1481
        $entityManager = Database::getManager();
1482
        $sessionRelCourseRepo = $entityManager->getRepository('ChamiloCoreBundle:SessionRelCourse');
1483
        $extraFieldRepo = $entityManager->getRepository('ChamiloCoreBundle:ExtraField');
1484
        $extraFieldRelTagRepo = $entityManager->getRepository('ChamiloCoreBundle:ExtraFieldRelTag');
1485
1486
        $tagsField = $extraFieldRepo->findOneBy([
1487
            'extraFieldType' => Chamilo\CoreBundle\Entity\ExtraField::COURSE_FIELD_TYPE,
1488
            'variable' => 'tags',
1489
        ]);
1490
1491
        /** @var \Chamilo\CoreBundle\Entity\Session $session */
1492
        foreach ($sessions as $session) {
1493
            $sessionDates = SessionManager::parseSessionDates([
1494
                'display_start_date' => $session->getDisplayStartDate(),
1495
                'display_end_date' => $session->getDisplayEndDate(),
1496
                'access_start_date' => $session->getAccessStartDate(),
1497
                'access_end_date' => $session->getAccessEndDate(),
1498
                'coach_access_start_date' => $session->getCoachAccessStartDate(),
1499
                'coach_access_end_date' => $session->getCoachAccessEndDate(),
1500
            ]);
1501
1502
            $imageField = $extraFieldValue->get_values_by_handler_and_field_variable(
1503
                $session->getId(),
1504
                'image'
1505
            );
1506
            $sessionCourseTags = [];
1507
            if (!is_null($tagsField)) {
1508
                $sessionRelCourses = $sessionRelCourseRepo->findBy([
1509
                    'session' => $session,
1510
                ]);
1511
                /** @var SessionRelCourse $sessionRelCourse */
1512
                foreach ($sessionRelCourses as $sessionRelCourse) {
1513
                    $courseTags = $extraFieldRelTagRepo->getTags(
1514
                        $tagsField,
1515
                        $sessionRelCourse->getCourse()->getId()
1516
                    );
1517
                    /** @var Tag $tag */
1518
                    foreach ($courseTags as $tag) {
1519
                        $sessionCourseTags[] = $tag->getTag();
1520
                    }
1521
                }
1522
            }
1523
1524
            if (!empty($sessionCourseTags)) {
1525
                $sessionCourseTags = array_unique($sessionCourseTags);
1526
            }
1527
1528
            /** @var SequenceResourceRepository $repo */
1529
            $repo = $entityManager->getRepository('ChamiloCoreBundle:SequenceResource');
1530
            $sequences = $repo->getRequirementsAndDependenciesWithinSequences(
1531
                $session->getId(),
1532
                SequenceResource::SESSION_TYPE
1533
            );
1534
1535
            $hasRequirements = false;
1536
            foreach ($sequences as $sequence) {
1537
                if (count($sequence['requirements']) === 0) {
1538
                    continue;
1539
                }
1540
                $hasRequirements = true;
1541
                break;
1542
            }
1543
            $cat = $session->getCategory();
1544
            if (empty($cat)) {
1545
                $cat = null;
1546
                $catName = '';
1547
            } else {
1548
                $catName = $cat->getName();
1549
            }
1550
1551
            $generalCoach = $session->getGeneralCoach();
1552
            $coachId = $generalCoach ? $generalCoach->getId() : 0;
1553
            $coachName = $generalCoach ? UserManager::formatUserFullName($session->getGeneralCoach()) : '';
1554
1555
            $actions = null;
1556
            if (api_is_platform_admin()) {
1557
                $actions = api_get_path(WEB_CODE_PATH).'session/resume_session.php?id_session='.$session->getId();
1558
            }
1559
1560
            $plugin = \BuyCoursesPlugin::create();
1561
            $isThisSessionOnSale = $plugin->getBuyCoursePluginPrice($session);
1562
1563
            $sessionsBlock = [
1564
                'id' => $session->getId(),
1565
                'name' => $session->getName(),
1566
                'image' => isset($imageField['value']) ? $imageField['value'] : null,
1567
                'nbr_courses' => $session->getNbrCourses(),
1568
                'nbr_users' => $session->getNbrUsers(),
1569
                'coach_id' => $coachId,
1570
                'coach_url' => $generalCoach
1571
                    ? api_get_path(WEB_AJAX_PATH).'user_manager.ajax.php?a=get_user_popup&user_id='.$coachId
1572
                    : '',
1573
                'coach_name' => $coachName,
1574
                'coach_avatar' => UserManager::getUserPicture(
1575
                    $coachId,
1576
                    USER_IMAGE_SIZE_SMALL
1577
                ),
1578
                'is_subscribed' => SessionManager::isUserSubscribedAsStudent(
1579
                    $session->getId(),
1580
                    $userId
1581
                ),
1582
                'icon' => self::getSessionIcon($session->getName()),
1583
                'date' => $sessionDates['display'],
1584
                'price' => !empty($isThisSessionOnSale['html']) ? $isThisSessionOnSale['html'] : '',
1585
                'subscribe_button' => isset($isThisSessionOnSale['buy_button']) ? $isThisSessionOnSale['buy_button'] : self::getRegisteredInSessionButton(
1586
                    $session->getId(),
1587
                    $session->getName(),
1588
                    $hasRequirements
1589
                ),
1590
                'show_description' => $session->getShowDescription(),
1591
                'description' => $session->getDescription(),
1592
                'category' => $catName,
1593
                'tags' => $sessionCourseTags,
1594
                'edit_actions' => $actions,
1595
                'duration' => SessionManager::getDayLeftInSession(
1596
                    ['id' => $session->getId(), 'duration' => $session->getDuration()],
1597
                    $userId
1598
                ),
1599
            ];
1600
1601
            $sessionsBlocks[] = array_merge($sessionsBlock, $sequences);
1602
        }
1603
1604
        return $sessionsBlocks;
1605
    }
1606
1607
1608
}
1609