Passed
Push — 1.11.x ( 340c2f...932035 )
by Julito
10:42
created

IndexManager::compareListUserCategory()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 5
nc 3
nop 2
dl 0
loc 11
rs 10
c 0
b 0
f 0
1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
/**
6
 * Class IndexManager.
7
 */
8
class IndexManager
9
{
10
    const VIEW_BY_DEFAULT = 0;
11
    const VIEW_BY_SESSION = 1;
12
13
    // An instance of the template engine
14
    // No need to initialize because IndexManager is not static,
15
    // and the constructor immediately instantiates a Template
16
    public $tpl;
17
    public $name = '';
18
    public $home = '';
19
    public $default_home = 'home/';
20
21
    /**
22
     * Construct.
23
     *
24
     * @param string $title
25
     */
26
    public function __construct($title)
27
    {
28
        $this->tpl = new Template($title);
29
        $this->home = api_get_home_path();
30
        $this->user_id = api_get_user_id();
31
        $this->load_directories_preview = false;
32
33
        // Load footer plugins systematically
34
        /*$config = api_get_settings_params(array('subkey = ? ' => 'customfooter', ' AND category = ? ' => 'Plugins'));
35
        if (!empty($config)) {
36
            foreach ($config as $fooid => $configrecord) {
37
                $canonic = preg_replace('/^customfooter_/', '', $configrecord['variable']);
38
                $footerconfig->$canonic = $configrecord['selected_value'];
39
            }
40
            if (!empty($footerconfig->footer_left)) {
41
                $this->tpl->assign('plugin_footer_left', $footerconfig->footer_left);
42
            }
43
            if (!empty($footerconfig->footer_right)) {
44
                $this->tpl->assign('plugin_footer_right', $footerconfig->footer_right);
45
            }
46
        }*/
47
48
        if (api_get_setting('show_documents_preview') === 'true') {
49
            $this->load_directories_preview = true;
50
        }
51
    }
52
53
    /**
54
     * @param $listA
55
     * @param $listB
56
     *
57
     * @return int
58
     */
59
    public static function compareListUserCategory($listA, $listB)
60
    {
61
        if ($listA['title'] == $listB['title']) {
62
            return 0;
63
        }
64
65
        if ($listA['title'] > $listB['title']) {
66
            return 1;
67
        }
68
69
        return -1;
70
    }
71
72
    /**
73
     * @param $view
74
     * @param $userId
75
     */
76
    public static function setDefaultMyCourseView($view, $userId)
77
    {
78
        setcookie('defaultMyCourseView'.$userId, $view);
79
    }
80
81
    /**
82
     * @param bool $setLoginForm
83
     */
84
    public function set_login_form($setLoginForm = true)
85
    {
86
        global $loginFailed;
87
        $this->tpl->setLoginForm($setLoginForm);
88
    }
89
90
    /**
91
     * @param array $personal_course_list
92
     */
93
    public function return_exercise_block($personal_course_list)
94
    {
95
        $exercise_list = [];
96
        if (!empty($personal_course_list)) {
97
            foreach ($personal_course_list as $course_item) {
98
                $course_code = $course_item['c'];
99
                $session_id = $course_item['id_session'];
100
101
                $exercises = ExerciseLib::get_exercises_to_be_taken(
102
                    $course_code,
103
                    $session_id
104
                );
105
106
                foreach ($exercises as $exercise_item) {
107
                    $exercise_item['course_code'] = $course_code;
108
                    $exercise_item['session_id'] = $session_id;
109
                    $exercise_item['tms'] = api_strtotime($exercise_item['end_time'], 'UTC');
110
111
                    $exercise_list[] = $exercise_item;
112
                }
113
            }
114
            if (!empty($exercise_list)) {
115
                $exercise_list = msort($exercise_list, 'tms');
116
                $my_exercise = $exercise_list[0];
117
                $url = Display::url(
118
                    $my_exercise['title'],
119
                    api_get_path(
120
                        WEB_CODE_PATH
121
                    ).'exercise/overview.php?exerciseId='.$my_exercise['id'].'&cidReq='.$my_exercise['course_code'].'&id_session='.$my_exercise['session_id']
122
                );
123
                $this->tpl->assign('exercise_url', $url);
124
                $this->tpl->assign(
125
                    'exercise_end_date',
126
                    api_convert_and_format_date($my_exercise['end_time'], DATE_FORMAT_SHORT)
127
                );
128
            }
129
        }
130
    }
131
132
    /**
133
     * @param bool $show_slide
134
     *
135
     * @return string|null
136
     */
137
    public function return_announcements($show_slide = true)
138
    {
139
        $hideAnnouncements = api_get_setting('hide_global_announcements_when_not_connected');
140
        $currentUserId = api_get_user_id();
141
        if ($hideAnnouncements === 'true' && empty($currentUserId)) {
142
            return null;
143
        }
144
        $announcement = isset($_GET['announcement']) ? $_GET['announcement'] : null;
145
        $announcement = (int) $announcement;
146
147
        if (!api_is_anonymous() && $this->user_id) {
148
            $visibility = SystemAnnouncementManager::getCurrentUserVisibility();
149
            if ($show_slide) {
150
                $announcements = SystemAnnouncementManager::displayAnnouncementsSlider(
151
                    $visibility,
152
                    $announcement
153
                );
154
            } else {
155
                $announcements = SystemAnnouncementManager::displayAllAnnouncements(
156
                    $visibility,
157
                    $announcement
158
                );
159
            }
160
        } else {
161
            if ($show_slide) {
162
                $announcements = SystemAnnouncementManager::displayAnnouncementsSlider(
163
                    SystemAnnouncementManager::VISIBLE_GUEST,
164
                    $announcement
165
                );
166
            } else {
167
                $announcements = SystemAnnouncementManager::displayAllAnnouncements(
168
                    SystemAnnouncementManager::VISIBLE_GUEST,
169
                    $announcement
170
                );
171
            }
172
        }
173
174
        return $announcements;
175
    }
176
177
    /**
178
     * Alias for the online_logout() function.
179
     *
180
     * @param bool  $redirect   Whether to ask online_logout to redirect to index.php or not
181
     * @param array $logoutInfo Information stored by local.inc.php before new context ['uid'=> x, 'cid'=>y, 'sid'=>z]
182
     */
183
    public function logout($redirect = true, $logoutInfo = [])
184
    {
185
        online_logout($this->user_id, true);
186
        Event::courseLogout($logoutInfo);
187
    }
188
189
    /**
190
     * Includes a created page.
191
     *
192
     * @param bool $getIncludedFile Whether to include a file as provided in URL GET or simply the homepage
193
     *
194
     * @return string
195
     */
196
    public function return_home_page($getIncludedFile = false)
197
    {
198
        $userId = api_get_user_id();
199
        // Including the page for the news
200
        $html = '';
201
        if ($getIncludedFile === true) {
202
            if (!empty($_GET['include']) && preg_match('/^[a-zA-Z0-9_-]*\.html$/', $_GET['include'])) {
203
                $open = @(string) file_get_contents($this->home.$_GET['include']);
204
                $html = api_to_system_encoding($open, api_detect_encoding(strip_tags($open)));
205
            }
206
        } else {
207
            // Hiding home top when user not connected.
208
            $hideTop = api_get_setting('hide_home_top_when_connected');
209
            if ($hideTop == 'true' && !empty($userId)) {
210
                return $html;
211
            }
212
213
            if (!empty($_SESSION['user_language_choice'])) {
214
                $user_selected_language = $_SESSION['user_language_choice'];
215
            } elseif (!empty($_SESSION['_user']['language'])) {
216
                $user_selected_language = $_SESSION['_user']['language'];
217
            } else {
218
                $user_selected_language = api_get_setting('platformLanguage');
219
            }
220
221
            $home_top_temp = '';
222
            // Try language specific home
223
            if (file_exists($this->home.'home_top_'.$user_selected_language.'.html')) {
224
                $home_top_temp = file_get_contents($this->home.'home_top_'.$user_selected_language.'.html');
225
            }
226
227
            // Try default language home
228
            if (empty($home_top_temp)) {
229
                if (file_exists($this->home.'home_top.html')) {
230
                    $home_top_temp = file_get_contents($this->home.'home_top.html');
231
                } else {
232
                    if (file_exists($this->default_home.'home_top.html')) {
233
                        $home_top_temp = file_get_contents($this->default_home.'home_top.html');
234
                    }
235
                }
236
            }
237
238
            if (trim($home_top_temp) == '' && api_is_platform_admin()) {
239
                $home_top_temp = get_lang('PortalHomepageDefaultIntroduction');
240
            } else {
241
                $home_top_temp;
242
            }
243
            $open = str_replace('{rel_path}', api_get_path(REL_PATH), $home_top_temp);
244
            $html = api_to_system_encoding($open, api_detect_encoding(strip_tags($open)));
245
        }
246
247
        return $html;
248
    }
249
250
    /**
251
     * @return string
252
     */
253
    public function return_notice()
254
    {
255
        $user_selected_language = api_get_interface_language();
256
        // Notice
257
        $home_notice = @(string) file_get_contents($this->home.'home_notice_'.$user_selected_language.'.html');
258
        if (empty($home_notice)) {
259
            $home_notice = @(string) file_get_contents($this->home.'home_notice.html');
260
        }
261
        if (!empty($home_notice)) {
262
            $home_notice = api_to_system_encoding($home_notice, api_detect_encoding(strip_tags($home_notice)));
263
        }
264
265
        return $home_notice;
266
    }
267
268
    /**
269
     * @return string
270
     */
271
    public function return_help()
272
    {
273
        $user_selected_language = api_get_interface_language();
274
        $platformLanguage = api_get_setting('platformLanguage');
275
276
        // Help section.
277
        /* Hide right menu "general" and other parts on anonymous right menu. */
278
        if (!isset($user_selected_language)) {
279
            $user_selected_language = $platformLanguage;
280
        }
281
282
        $html = '';
283
        $home_menu = @(string) file_get_contents($this->home.'home_menu_'.$user_selected_language.'.html');
284
        if (!empty($home_menu)) {
285
            $html = api_to_system_encoding($home_menu, api_detect_encoding(strip_tags($home_menu)));
286
        }
287
288
        return $html;
289
    }
290
291
    /**
292
     * Generate the block for show a panel with links to My Certificates and Certificates Search pages.
293
     *
294
     * @return array The HTML code for the panel
295
     */
296
    public function returnSkillLinks()
297
    {
298
        $items = [];
299
300
        if (!api_is_anonymous() &&
301
            api_get_configuration_value('hide_my_certificate_link') === false
302
        ) {
303
            $items[] = [
304
                'icon' => Display::return_icon('graduation.png', get_lang('MyCertificates')),
305
                'link' => api_get_path(WEB_CODE_PATH).'gradebook/my_certificates.php',
306
                'title' => get_lang('MyCertificates'),
307
            ];
308
        }
309
        if (api_get_setting('allow_public_certificates') === 'true') {
310
            $items[] = [
311
                'icon' => Display::return_icon('search_graduation.png', get_lang('Search')),
312
                'link' => api_get_path(WEB_CODE_PATH).'gradebook/search.php',
313
                'title' => get_lang('Search'),
314
            ];
315
        }
316
317
        $myCertificate = GradebookUtils::get_certificate_by_user_id(
318
            +0,
319
            $this->user_id
320
        );
321
322
        if ($myCertificate) {
0 ignored issues
show
introduced by
$myCertificate is of type Datetime, thus it always evaluated to true.
Loading history...
323
            $items[] = [
324
                'icon' => Display::return_icon(
325
                    'skill-badges.png',
326
                    get_lang('MyGeneralCertificate'),
327
                    null,
328
                    ICON_SIZE_SMALL
329
                ),
330
                'link' => api_get_path(WEB_CODE_PATH).'social/my_skills_report.php?a=generate_custom_skill',
331
                'title' => get_lang('MyGeneralCertificate'),
332
            ];
333
        }
334
335
        if (Skill::isAllowed(api_get_user_id(), false)) {
336
            $items[] = [
337
                'icon' => Display::return_icon('skill-badges.png', get_lang('MySkills')),
338
                'link' => api_get_path(WEB_CODE_PATH).'social/my_skills_report.php',
339
                'title' => get_lang('MySkills'),
340
            ];
341
            $allowSkillsManagement = api_get_setting('allow_hr_skills_management') == 'true';
342
            if (($allowSkillsManagement && api_is_drh()) || api_is_platform_admin()) {
343
                $items[] = [
344
                    'icon' => Display::return_icon('edit-skill.png', get_lang('MySkills')),
345
                    'link' => api_get_path(WEB_CODE_PATH).'admin/skills_wheel.php',
346
                    'title' => get_lang('ManageSkills'),
347
                ];
348
            }
349
        }
350
351
        return $items;
352
    }
353
354
    public static function studentPublicationBlock()
355
    {
356
        $items[] = [
357
            'icon' => Display::return_icon('lp_student_publication.png', get_lang('StudentPublication')),
358
            'link' => api_get_path(WEB_CODE_PATH).'work/publications.php',
359
            'title' => get_lang('MyStudentPublications'),
360
        ];
361
362
        return $items;
363
    }
364
365
    /**
366
     * Reacts on a failed login:
367
     * Displays an explanation with a link to the registration form.
368
     *
369
     * @version 1.0.1
370
     */
371
    public function handle_login_failed()
372
    {
373
        return $this->tpl->handleLoginFailed();
374
    }
375
376
    /**
377
     * Display list of courses in a category.
378
     * (for anonymous users).
379
     *
380
     * @version 1.1
381
     *
382
     * @author  Patrick Cool <[email protected]>, Ghent University - refactoring and code cleaning
383
     * @author  Julio Montoya <[email protected]>, Beeznest template modifs
384
     */
385
    public function return_courses_in_categories()
386
    {
387
        $result = '';
388
        $stok = Security::get_token();
389
390
        // Initialization.
391
        $user_identified = (api_get_user_id() > 0 && !api_is_anonymous());
392
        $web_course_path = api_get_path(WEB_COURSE_PATH);
393
        $category = isset($_GET['category']) ? Database::escape_string($_GET['category']) : '';
394
        $setting_show_also_closed_courses = api_get_setting('show_closed_courses') == 'true';
395
396
        // Database table definitions.
397
        $main_course_table = Database::get_main_table(TABLE_MAIN_COURSE);
398
        $main_category_table = Database::get_main_table(TABLE_MAIN_CATEGORY);
399
400
        // Get list of courses in category $category.
401
        $sql = "SELECT * FROM $main_course_table cours
402
                WHERE category_code = '".$category."'
403
                ORDER BY title, UPPER(visual_code)";
404
405
        // Showing only the courses of the current access_url_id.
406
        if (api_is_multiple_url_enabled()) {
407
            $url_access_id = api_get_current_access_url_id();
408
            if ($url_access_id != -1) {
409
                $tbl_url_rel_course = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
410
                $sql = "SELECT * FROM $main_course_table 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
                            access_url_id = $url_access_id AND
415
                            category_code = '".$category."'
416
                        ORDER BY title, UPPER(visual_code)";
417
            }
418
        }
419
420
        // Removed: AND cours.visibility='".COURSE_VISIBILITY_OPEN_WORLD."'
421
        $queryResult = Database::query($sql);
422
        while ($course_result = Database::fetch_array($queryResult)) {
423
            $course_list[] = $course_result;
424
        }
425
        $numRows = Database::num_rows($queryResult);
426
427
        // $setting_show_also_closed_courses
428
        if ($user_identified) {
429
            if ($setting_show_also_closed_courses) {
430
                $platform_visible_courses = '';
431
            } else {
432
                $platform_visible_courses = "  AND (t3.visibility='".COURSE_VISIBILITY_OPEN_WORLD."' OR t3.visibility='".COURSE_VISIBILITY_OPEN_PLATFORM."' )";
433
            }
434
        } else {
435
            if ($setting_show_also_closed_courses) {
436
                $platform_visible_courses = '';
437
            } else {
438
                $platform_visible_courses = "  AND (t3.visibility='".COURSE_VISIBILITY_OPEN_WORLD."' )";
439
            }
440
        }
441
        $sqlGetSubCatList = "
442
                    SELECT  t1.name,
443
                            t1.code,
444
                            t1.parent_id,
445
                            t1.children_count,COUNT(DISTINCT t3.code) AS nbCourse
446
                    FROM $main_category_table t1
447
                    LEFT JOIN $main_category_table t2
448
                    ON t1.code=t2.parent_id
449
                    LEFT JOIN $main_course_table t3
450
                    ON (t3.category_code = t1.code $platform_visible_courses)
451
                    WHERE t1.parent_id ".(empty($category) ? "IS NULL" : "='$category'")."
452
                    GROUP BY t1.name,t1.code,t1.parent_id,t1.children_count
453
                    ORDER BY t1.tree_pos, t1.name";
454
455
        // Showing only the category of courses of the current access_url_id
456
        if (api_is_multiple_url_enabled()) {
457
            $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE_CATEGORY);
458
            $courseCategoryCondition = " INNER JOIN $table a ON (t1.id = a.course_category_id)";
459
460
            $url_access_id = api_get_current_access_url_id();
461
            if ($url_access_id != -1) {
462
                $tbl_url_rel_course = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
463
                $sqlGetSubCatList = "
464
                    SELECT t1.name,
465
                            t1.code,
466
                            t1.parent_id,
467
                            t1.children_count,
468
                            COUNT(DISTINCT t3.code) AS nbCourse
469
                    FROM $main_category_table t1
470
                    $courseCategoryCondition
471
                    LEFT JOIN $main_category_table t2 ON t1.code = t2.parent_id
472
                    LEFT JOIN $main_course_table t3 ON (t3.category_code = t1.code $platform_visible_courses)
473
                    INNER JOIN $tbl_url_rel_course as url_rel_course
474
                    ON (url_rel_course.c_id = t3.id)
475
                    WHERE
476
                        url_rel_course.access_url_id = $url_access_id AND
477
                        t1.parent_id ".(empty($category) ? "IS NULL" : "='$category'")."
478
                    GROUP BY t1.name,t1.code,t1.parent_id,t1.children_count
479
                    ORDER BY t1.tree_pos, t1.name";
480
            }
481
        }
482
483
        $resCats = Database::query($sqlGetSubCatList);
484
        $thereIsSubCat = false;
485
486
        $htmlTitre = '';
487
        $htmlListCat = '';
488
        if (Database::num_rows($resCats) > 0) {
489
            $htmlListCat = Display::page_header(get_lang('CatList'));
490
            $htmlListCat .= '<ul>';
491
            while ($catLine = Database::fetch_array($resCats)) {
492
                $category_has_open_courses = self::category_has_open_courses($catLine['code']);
493
                if ($category_has_open_courses) {
494
                    // The category contains courses accessible to anonymous visitors.
495
                    $htmlListCat .= '<li>';
496
                    $htmlListCat .= '<a href="'.api_get_self(
497
                        ).'?category='.$catLine['code'].'">'.$catLine['name'].'</a>';
498
                    if (api_get_setting('show_number_of_courses') == 'true') {
499
                        $htmlListCat .= ' ('.$catLine['nbCourse'].' '.get_lang('Courses').')';
500
                    }
501
                    $htmlListCat .= "</li>";
502
                    $thereIsSubCat = true;
503
                } elseif ($catLine['children_count'] > 0) {
504
                    // The category has children, subcategories.
505
                    $htmlListCat .= '<li>';
506
                    $htmlListCat .= '<a href="'.api_get_self(
507
                        ).'?category='.$catLine['code'].'">'.$catLine['name'].'</a>';
508
                    $htmlListCat .= "</li>";
509
                    $thereIsSubCat = true;
510
                } elseif (api_get_setting('show_empty_course_categories') == 'true') {
511
                    /* End changed code to eliminate the (0 courses) after empty categories. */
512
                    $htmlListCat .= '<li>';
513
                    $htmlListCat .= $catLine['name'];
514
                    $htmlListCat .= "</li>";
515
                    $thereIsSubCat = true;
516
                } // Else don't set thereIsSubCat to true to avoid printing things if not requested.
517
                // TODO: deprecate this useless feature - this includes removing system variable
518
                if (empty($htmlTitre)) {
519
                    $htmlTitre = '<p>';
520
                    if (api_get_setting('show_back_link_on_top_of_tree') == 'true') {
521
                        $htmlTitre .= '<a href="'.api_get_self().'">&lt;&lt; '.get_lang('BackToHomePage').'</a>';
522
                    }
523
                    $htmlTitre .= "</p>";
524
                }
525
            }
526
            $htmlListCat .= "</ul>";
527
        }
528
        $result .= $htmlTitre;
529
        if ($thereIsSubCat) {
530
            $result .= $htmlListCat;
531
        }
532
        while ($categoryName = Database::fetch_array($resCats)) {
533
            $result .= '<h3>'.$categoryName['name']."</h3>\n";
534
        }
535
536
        $courses_list_string = '';
537
        $courses_shown = 0;
538
        if ($numRows > 0) {
539
            $courses_list_string .= Display::page_header(get_lang('CourseList'));
540
            $courses_list_string .= "<ul>";
541
            if (api_get_user_id()) {
542
                $courses_of_user = [];
543
                $coursesByUserCategory = CourseManager::getCoursesByUserCourseCategory(api_get_user_id());
544
                if (!empty($coursesByUserCategory)) {
545
                    foreach ($coursesByUserCategory as $courseItem) {
546
                        $courses_of_user[$courseItem['code']] = $courseItem;
547
                    }
548
                }
549
            }
550
            foreach ($course_list as $course) {
551
                // $setting_show_also_closed_courses
552
                if ($course['visibility'] == COURSE_VISIBILITY_HIDDEN) {
553
                    continue;
554
                }
555
                if (!$setting_show_also_closed_courses) {
556
                    // If we do not show the closed courses
557
                    // we only show the courses that are open to the world (to everybody)
558
                    // and the courses that are open to the platform (if the current user is a registered user.
559
                    if (($user_identified && $course['visibility'] == COURSE_VISIBILITY_OPEN_PLATFORM) ||
560
                        ($course['visibility'] == COURSE_VISIBILITY_OPEN_WORLD)
561
                    ) {
562
                        $courses_shown++;
563
                        $courses_list_string .= "<li>";
564
                        $courses_list_string .= '<a href="'.$web_course_path.$course['directory'].'/">'.$course['title'].'</a><br />';
565
                        $course_details = [];
566
                        if (api_get_setting('display_coursecode_in_courselist') === 'true') {
567
                            $course_details[] = '('.$course['visual_code'].')';
568
                        }
569
                        if (api_get_setting('display_teacher_in_courselist') === 'true') {
570
                            $course_details[] = CourseManager::getTeacherListFromCourseCodeToString($course['code']);
571
                        }
572
                        if (api_get_setting('show_different_course_language') === 'true' &&
573
                            $course['course_language'] != api_get_setting('platformLanguage')
574
                        ) {
575
                            $course_details[] = $course['course_language'];
576
                        }
577
                        $courses_list_string .= implode(' - ', $course_details);
578
                        $courses_list_string .= "</li>";
579
                    }
580
                } else {
581
                    // We DO show the closed courses.
582
                    // The course is accessible if (link to the course homepage):
583
                    // 1. the course is open to the world (doesn't matter if the user is logged in or not): $course['visibility'] == COURSE_VISIBILITY_OPEN_WORLD);
584
                    // 2. the user is logged in and the course is open to the world or open to the platform: ($user_identified && $course['visibility'] == COURSE_VISIBILITY_OPEN_PLATFORM);
585
                    // 3. the user is logged in and the user is subscribed to the course and the course visibility is not COURSE_VISIBILITY_CLOSED;
586
                    // 4. the user is logged in and the user is course admin of te course (regardless of the course visibility setting);
587
                    // 5. the user is the platform admin api_is_platform_admin().
588
589
                    $courses_shown++;
590
                    $courses_list_string .= "<li>";
591
                    if ($course['visibility'] == COURSE_VISIBILITY_OPEN_WORLD
592
                        || ($user_identified && $course['visibility'] == COURSE_VISIBILITY_OPEN_PLATFORM)
593
                        || ($user_identified && array_key_exists($course['code'], $courses_of_user)
594
                            && $course['visibility'] != COURSE_VISIBILITY_CLOSED)
595
                        || $courses_of_user[$course['code']]['status'] == '1'
596
                        || api_is_platform_admin()
597
                    ) {
598
                        $courses_list_string .= '<a href="'.$web_course_path.$course['directory'].'/">';
599
                    }
600
                    $courses_list_string .= $course['title'];
601
                    if ($course['visibility'] == COURSE_VISIBILITY_OPEN_WORLD
602
                        || ($user_identified && $course['visibility'] == COURSE_VISIBILITY_OPEN_PLATFORM)
603
                        || ($user_identified && array_key_exists($course['code'], $courses_of_user)
604
                            && $course['visibility'] != COURSE_VISIBILITY_CLOSED)
605
                        || $courses_of_user[$course['code']]['status'] == '1'
606
                        || api_is_platform_admin()
607
                    ) {
608
                        $courses_list_string .= '</a><br />';
609
                    }
610
                    $course_details = [];
611
                    if (api_get_setting('display_coursecode_in_courselist') === 'true') {
612
                        $course_details[] = '('.$course['visual_code'].')';
613
                    }
614
                    if (api_get_setting('display_teacher_in_courselist') === 'true') {
615
                        if (!empty($course['tutor_name'])) {
616
                            $course_details[] = $course['tutor_name'];
617
                        }
618
                    }
619
                    if (api_get_setting('show_different_course_language') == 'true' &&
620
                        $course['course_language'] != api_get_setting('platformLanguage')
621
                    ) {
622
                        $course_details[] = $course['course_language'];
623
                    }
624
625
                    $courses_list_string .= implode(' - ', $course_details);
626
                    // We display a subscription link if:
627
                    // 1. it is allowed to register for the course and if the course is not already in
628
                    // the courselist of the user and if the user is identified
629
                    // 2.
630
                    if ($user_identified && !array_key_exists($course['code'], $courses_of_user)) {
631
                        if ($course['subscribe'] == '1') {
632
                            $courses_list_string .= '&nbsp;<a class="btn btn-primary" href="main/auth/courses.php?action=subscribe_course&sec_token='.$stok.'&course_code='.$course['code'].'&category_code='.Security::remove_XSS(
633
                                    $_GET['category']
634
                                ).'">'.get_lang('Subscribe').'</a><br />';
635
                        } else {
636
                            $courses_list_string .= '<br />'.get_lang('SubscribingNotAllowed');
637
                        }
638
                    }
639
                    $courses_list_string .= "</li>";
640
                } //end else
641
            } // end foreach
642
            $courses_list_string .= "</ul>";
643
        }
644
        if ($courses_shown > 0) {
645
            // Only display the list of courses and categories if there was more than
646
            // 0 courses visible to the world (we're in the anonymous list here).
647
            $result .= $courses_list_string;
648
        }
649
        if ($category != '') {
650
            $result .= '<p><a href="'.api_get_self().'">'
651
                .Display:: return_icon('back.png', get_lang('BackToHomePage'))
652
                .get_lang('BackToHomePage').'</a></p>';
653
        }
654
655
        return $result;
656
    }
657
658
    /**
659
     * This function checks if there are courses that are open to the world in the platform course categories
660
     * (=faculties).
661
     *
662
     * @param string $category
663
     *
664
     * @return bool
665
     */
666
    public function category_has_open_courses($category)
667
    {
668
        $setting_show_also_closed_courses = api_get_setting('show_closed_courses') == 'true';
669
        $main_course_table = Database::get_main_table(TABLE_MAIN_COURSE);
670
        $category = Database::escape_string($category);
671
        $sql_query = "SELECT * FROM $main_course_table WHERE category_code='$category'";
672
        $sql_result = Database::query($sql_query);
673
        while ($course = Database::fetch_array($sql_result)) {
674
            if (!$setting_show_also_closed_courses) {
675
                if ((api_get_user_id() > 0 && $course['visibility'] == COURSE_VISIBILITY_OPEN_PLATFORM) ||
676
                    ($course['visibility'] == COURSE_VISIBILITY_OPEN_WORLD)
677
                ) {
678
                    return true; //at least one open course
679
                }
680
            } else {
681
                if (isset($course['visibility'])) {
682
                    return true; // At least one course (it does not matter weither it's open or not because $setting_show_also_closed_courses = true).
683
                }
684
            }
685
        }
686
687
        return false;
688
    }
689
690
    /**
691
     * Adds a form to let users login.
692
     *
693
     * @version 1.1
694
     */
695
    public function display_login_form()
696
    {
697
        return $this->tpl->displayLoginForm();
698
    }
699
700
    /**
701
     * @return string
702
     *
703
     * @todo use FormValidator
704
     */
705
    public function return_search_block()
706
    {
707
        $html = '';
708
        if (api_get_setting('search_enabled') == 'true') {
709
            $search_btn = get_lang('Search');
710
            $search_content = '<form action="main/search/" method="post">
711
                <div class="form-group">
712
                <input type="text" id="query" class="form-control" name="query" value="" />
713
                <button class="btn btn-default" type="submit" name="submit" value="'.$search_btn.'" />'.
714
                $search_btn.' </button>
715
                </div></form>';
716
            $html .= $this->showRightBlock(get_lang('Search'), $search_content, 'search_block');
717
        }
718
719
        return $html;
720
    }
721
722
    /**
723
     * @param        $title
724
     * @param        $content
725
     * @param string $id
726
     * @param array  $params
727
     * @param string $idAccordion
728
     * @param string $idCollapse
729
     *
730
     * @return string
731
     *
732
     * @todo use the template system
733
     */
734
    public function showRightBlock(
735
        $title,
736
        $content,
737
        $id = '',
738
        $params = [],
739
        $idAccordion = '',
740
        $idCollapse = ''
741
    ) {
742
        $html = '';
743
        if (!empty($idAccordion)) {
744
            $html .= '<div class="panel-group" id="'.$idAccordion.'" role="tablist" aria-multiselectable="true">';
745
            $html .= '<div class="panel panel-default" id="'.$id.'">';
746
            $html .= '<div class="panel-heading" role="tab"><h4 class="panel-title">';
747
            $html .= '<a role="button" data-toggle="collapse" data-parent="#'.$idAccordion.'" href="#'.$idCollapse.'" aria-expanded="true" aria-controls="'.$idCollapse.'">'.$title.'</a>';
748
            $html .= '</h4></div>';
749
            $html .= '<div id="'.$idCollapse.'" class="panel-collapse collapse in" role="tabpanel">';
750
            $html .= '<div class="panel-body">'.$content.'</div>';
751
            $html .= '</div></div></div>';
752
        } else {
753
            if (!empty($id)) {
754
                $params['id'] = $id;
755
            }
756
            $params['class'] = 'panel panel-default';
757
            $html = null;
758
            if (!empty($title)) {
759
                $html .= '<div class="panel-heading">'.$title.'</div>';
760
            }
761
            $html .= '<div class="panel-body">'.$content.'</div>';
762
            $html = Display::div($html, $params);
763
        }
764
765
        return $html;
766
    }
767
768
    /**
769
     * @return string
770
     */
771
    public function returnClassesBlock()
772
    {
773
        if (api_get_setting('show_groups_to_users') !== 'true') {
774
            return '';
775
        }
776
777
        $items = [];
778
779
        $usergroup = new UserGroup();
780
        if (api_is_platform_admin()) {
781
            $items[] = [
782
                'link' => api_get_path(WEB_CODE_PATH).'admin/usergroups.php?action=add',
783
                'title' => get_lang('AddClasses'),
784
            ];
785
        } else {
786
            if (api_is_teacher() && $usergroup->allowTeachers()) {
787
                $items[] = [
788
                    'link' => api_get_path(WEB_CODE_PATH).'admin/usergroups.php',
789
                    'title' => get_lang('ClassList'),
790
                ];
791
            }
792
        }
793
794
        $usergroup_list = $usergroup->get_usergroup_by_user(api_get_user_id());
795
        if (!empty($usergroup_list)) {
796
            foreach ($usergroup_list as $group_id) {
797
                $data = $usergroup->get($group_id);
798
                $items[] = [
799
                    'link' => api_get_path(WEB_CODE_PATH).'user/classes.php?id='.$data['id'],
800
                    'title' => $data['name'],
801
                ];
802
            }
803
        }
804
805
        $html = $this->showRightBlock(
806
            get_lang('Classes'),
807
            self::returnRightBlockItems($items),
808
            'classes_block'
809
        );
810
811
        return $html;
812
    }
813
814
    /**
815
     * @return string
816
     */
817
    public function return_user_image_block()
818
    {
819
        $html = '';
820
        if (!api_is_anonymous()) {
821
            $userPicture = UserManager::getUserPicture(api_get_user_id(), USER_IMAGE_SIZE_ORIGINAL);
822
            $content = null;
823
824
            if (api_get_setting('allow_social_tool') == 'true') {
825
                $content .= '<a style="text-align:center" href="'.api_get_path(WEB_CODE_PATH).'social/home.php">
826
                <img class="img-circle" src="'.$userPicture.'"></a>';
827
            } else {
828
                $content .= '<a style="text-align:center" href="'.api_get_path(WEB_CODE_PATH).'auth/profile.php">
829
                <img class="img-circle" title="'.get_lang('EditProfile').'" src="'.$userPicture.'"></a>';
830
            }
831
832
            $html = $this->showRightBlock(
833
                null,
834
                $content,
835
                'user_image_block',
836
                ['style' => 'text-align:center;']
837
            );
838
        }
839
840
        return $html;
841
    }
842
843
    /**
844
     * @return array
845
     */
846
    public function return_profile_block()
847
    {
848
        $userInfo = api_get_user_info();
849
        $userId = api_get_user_id();
850
        if (empty($userId)) {
851
            return;
852
        }
853
854
        $items = [];
855
        $userGroup = new UserGroup();
856
        //  @todo Add a platform setting to add the user image.
857
        if (api_get_setting('allow_message_tool') === 'true') {
858
            // New messages.
859
            $number_of_new_messages = MessageManager::getCountNewMessages();
860
            // New contact invitations.
861
            $number_of_new_messages_of_friend = SocialManager::get_message_number_invitation_by_user_id(
862
                $userId
863
            );
864
865
            // New group invitations sent by a moderator.
866
            $group_pending_invitations = $userGroup->get_groups_by_user(
867
                $userId,
868
                GROUP_USER_PERMISSION_PENDING_INVITATION,
869
                false
870
            );
871
            $group_pending_invitations = count($group_pending_invitations);
872
            $total_invitations = $number_of_new_messages_of_friend + $group_pending_invitations;
873
            $cant_msg = Display::badge($number_of_new_messages);
874
875
            $items[] = [
876
                'class' => 'inbox-message-social',
877
                'icon' => Display::return_icon('inbox.png', get_lang('Inbox')),
878
                'link' => api_get_path(WEB_CODE_PATH).'messages/inbox.php',
879
                'title' => get_lang('Inbox').$cant_msg,
880
            ];
881
882
            $items[] = [
883
                'class' => 'new-message-social',
884
                'icon' => Display::return_icon('new-message.png', get_lang('Compose')),
885
                'link' => api_get_path(WEB_CODE_PATH).'messages/new_message.php',
886
                'title' => get_lang('Compose'),
887
            ];
888
889
            if (api_get_setting('allow_social_tool') == 'true') {
890
                $total_invitations = Display::badge($total_invitations);
891
                $items[] = [
892
                    'class' => 'invitations-social',
893
                    'icon' => Display::return_icon('invitations.png', get_lang('PendingInvitations')),
894
                    'link' => api_get_path(WEB_CODE_PATH).'social/invitations.php',
895
                    'title' => get_lang('PendingInvitations').$total_invitations,
896
                ];
897
            }
898
        }
899
900
        $items[] = [
901
            'class' => 'personal-data',
902
            'icon' => Display::return_icon('database.png', get_lang('PersonalDataReport')),
903
            'link' => api_get_path(WEB_CODE_PATH).'social/personal_data.php',
904
            'title' => get_lang('PersonalDataReport'),
905
        ];
906
907
        if (api_get_configuration_value('allow_my_files_link_in_homepage')) {
908
            if (api_get_setting('allow_my_files') !== 'false') {
909
                $items[] = [
910
                    'class' => 'myfiles-social',
911
                    'icon' => Display::return_icon('sn-files.png', get_lang('Files')),
912
                    'link' => api_get_path(WEB_CODE_PATH).'social/myfiles.php',
913
                    'title' => get_lang('MyFiles'),
914
                ];
915
            }
916
        }
917
918
        $items[] = [
919
            'class' => 'profile-social',
920
            'icon' => Display::return_icon('edit-profile.png', get_lang('EditProfile')),
921
            'link' => Display::getProfileEditionLink($userId),
922
            'title' => get_lang('EditProfile'),
923
        ];
924
925
        if (api_get_configuration_value('show_link_request_hrm_user') &&
926
            api_is_drh()
927
        ) {
928
            $label = get_lang('RequestLinkingToUser');
929
            $items[] = [
930
                'icon' => Display::return_icon('new_group.png', $label),
931
                'link' => api_get_path(WEB_CODE_PATH).'social/require_user_linking.php',
932
                'title' => $label,
933
            ];
934
        }
935
936
        if (bbb::showGlobalConferenceLink($userInfo)) {
937
            $bbb = new bbb('', '', true, api_get_user_id());
938
            $url = $bbb->getListingUrl();
939
            $items[] = [
940
                'class' => 'video-conference',
941
                'icon' => Display::return_icon(
942
                    'bbb.png',
943
                    get_lang('VideoConference')
944
                ),
945
                'link' => $url,
946
                'title' => get_lang('VideoConference'),
947
            ];
948
        }
949
950
        if (true === api_get_configuration_value('whispeak_auth_enabled')) {
951
            $itemTitle = WhispeakAuthPlugin::create()->get_title();
952
953
            $items[] = [
954
                'class' => 'whispeak-enrollment',
955
                'icon' => Display::return_icon('addworkuser.png', $itemTitle),
956
                'link' => WhispeakAuthPlugin::getEnrollmentUrl(),
957
                'title' => $itemTitle,
958
            ];
959
        }
960
961
        return $items;
962
    }
963
964
    /**
965
     * @return array
966
     */
967
    public function return_navigation_links()
968
    {
969
        $items = [];
970
        // Deleting the myprofile link.
971
        if (api_get_setting('allow_social_tool') == 'true') {
972
            unset($this->tpl->menu_navigation['myprofile']);
973
        }
974
975
        $hideMenu = api_get_configuration_value('hide_main_navigation_menu');
976
        if ($hideMenu === true) {
977
            return '';
978
        }
979
980
        // Main navigation section.
981
        // Tabs that are deactivated are added here.
982
        if (!empty($this->tpl->menu_navigation)) {
983
            foreach ($this->tpl->menu_navigation as $section => $navigation_info) {
984
                $items[] = [
985
                    'icon' => null,
986
                    'link' => $navigation_info['url'],
987
                    'title' => $navigation_info['title'],
988
                ];
989
            }
990
        }
991
992
        return $items;
993
    }
994
995
    /**
996
     * @return array
997
     */
998
    public function return_course_block()
999
    {
1000
        if (api_get_configuration_value('hide_course_sidebar')) {
1001
            return '';
1002
        }
1003
        $isHrm = api_is_drh();
1004
        $show_create_link = false;
1005
        $show_course_link = false;
1006
        if (api_is_allowed_to_create_course()) {
1007
            $show_create_link = true;
1008
        }
1009
1010
        if (api_get_setting('allow_students_to_browse_courses') === 'true') {
1011
            $show_course_link = true;
1012
        }
1013
1014
        $items = [];
1015
1016
        // My account section
1017
        if ($show_create_link) {
1018
            if (api_get_setting('course_validation') == 'true' && !api_is_platform_admin()) {
1019
                $items[] = [
1020
                    'class' => 'add-course',
1021
                    'icon' => Display::return_icon('new-course.png', get_lang('CreateCourseRequest')),
1022
                    'link' => api_get_path(WEB_CODE_PATH).'create_course/add_course.php',
1023
                    'title' => get_lang('CreateCourseRequest'),
1024
                ];
1025
            } else {
1026
                $items[] = [
1027
                    'class' => 'add-course',
1028
                    'icon' => Display::return_icon('new-course.png', get_lang('CourseCreate')),
1029
                    'link' => api_get_path(WEB_CODE_PATH).'create_course/add_course.php',
1030
                    'title' => get_lang('CourseCreate'),
1031
                ];
1032
            }
1033
1034
            if (SessionManager::allowToManageSessions()) {
1035
                $items[] = [
1036
                    'class' => 'add-session',
1037
                    'icon' => Display::return_icon('session.png', get_lang('AddSession')),
1038
                    'link' => api_get_path(WEB_CODE_PATH).'session/session_add.php',
1039
                    'title' => get_lang('AddSession'),
1040
                ];
1041
            }
1042
        }
1043
1044
        // Sort courses
1045
        if (api_get_configuration_value('view_grid_courses') != true) {
1046
            $items[] = [
1047
                'class' => 'order-course',
1048
                'icon' => Display::return_icon('order-course.png', get_lang('SortMyCourses')),
1049
                'link' => api_get_path(WEB_CODE_PATH).'auth/sort_my_courses.php',
1050
                'title' => get_lang('SortMyCourses'),
1051
            ];
1052
        }
1053
1054
        // Session history
1055
        if (isset($_GET['history']) && intval($_GET['history']) == 1) {
1056
            $items[] = [
1057
                'class' => 'history-course',
1058
                'icon' => Display::return_icon('history-course.png', get_lang('DisplayTrainingList')),
1059
                'link' => api_get_path(WEB_PATH).'user_portal.php',
1060
                'title' => get_lang('DisplayTrainingList'),
1061
            ];
1062
        } else {
1063
            $items[] = [
1064
                'class' => 'history-course',
1065
                'icon' => Display::return_icon('history-course.png', get_lang('HistoryTrainingSessions')),
1066
                'link' => api_get_path(WEB_PATH).'user_portal.php?history=1',
1067
                'title' => get_lang('HistoryTrainingSessions'),
1068
            ];
1069
        }
1070
1071
        if ($isHrm) {
1072
            $items[] = [
1073
                'link' => api_get_path(WEB_CODE_PATH).'auth/hrm_courses.php',
1074
                'title' => get_lang('HrmAssignedUsersCourseList'),
1075
            ];
1076
        }
1077
1078
        // Course catalog
1079
        if ($show_course_link) {
1080
            if (!api_is_drh()) {
1081
                $items[] = [
1082
                    'class' => 'list-course',
1083
                    'icon' => Display::return_icon('catalog-course.png', get_lang('CourseCatalog')),
1084
                    'link' => api_get_path(WEB_CODE_PATH).'auth/courses.php',
1085
                    'title' => get_lang('CourseCatalog'),
1086
                ];
1087
            } else {
1088
                $items[] = [
1089
                    'link' => api_get_path(WEB_CODE_PATH).'dashboard/index.php',
1090
                    'title' => get_lang('Dashboard'),
1091
                ];
1092
            }
1093
        }
1094
1095
        return $items;
1096
    }
1097
1098
    /**
1099
     * Shows a welcome message when the user doesn't have any content in the course list.
1100
     */
1101
    public function return_welcome_to_course_block()
1102
    {
1103
        $count_courses = CourseManager::count_courses();
1104
        $tpl = $this->tpl->get_template('layout/welcome_to_course.tpl');
1105
1106
        $course_catalog_url = api_get_path(WEB_CODE_PATH).'auth/courses.php';
1107
        $course_list_url = api_get_path(WEB_PATH).'user_portal.php';
1108
1109
        $this->tpl->assign('course_catalog_url', $course_catalog_url);
1110
        $this->tpl->assign('course_list_url', $course_list_url);
1111
        $this->tpl->assign('course_catalog_link', Display::url(get_lang('Here'), $course_catalog_url));
1112
        $this->tpl->assign('course_list_link', Display::url(get_lang('Here'), $course_list_url));
1113
        $this->tpl->assign('count_courses', $count_courses);
1114
1115
        return $this->tpl->fetch($tpl);
1116
    }
1117
1118
    /**
1119
     * @return array
1120
     */
1121
    public function return_hot_courses()
1122
    {
1123
        return CourseManager::return_hot_courses(30, 6);
1124
    }
1125
1126
    /**
1127
     * UserPortal view for session, return the HTML of the course list.
1128
     *
1129
     * @param $user_id
1130
     *
1131
     * @return string
1132
     */
1133
    public function returnCoursesAndSessionsViewBySession($user_id)
1134
    {
1135
        $sessionCount = 0;
1136
        $courseCount = 0;
1137
        $load_history = (isset($_GET['history']) && intval($_GET['history']) == 1) ? true : false;
1138
1139
        if ($load_history) {
1140
            // Load sessions in category in *history*
1141
            $session_categories = UserManager::get_sessions_by_category($user_id, true);
1142
        } else {
1143
            // Load sessions in category
1144
            $session_categories = UserManager::get_sessions_by_category($user_id, false);
1145
        }
1146
1147
        $html = '';
1148
        $loadDirs = $this->load_directories_preview;
1149
1150
        // If we're not in the history view...
1151
        $listCoursesInfo = [];
1152
        if (!isset($_GET['history'])) {
1153
            // Display special courses
1154
            $specialCoursesResult = CourseManager::returnSpecialCourses(
1155
                $user_id,
1156
                $loadDirs
1157
            );
1158
            $specialCourses = $specialCoursesResult;
1159
1160
            if ($specialCourses) {
1161
                $this->tpl->assign('courses', $specialCourses);
1162
                $html = $this->tpl->fetch(
1163
                    $this->tpl->get_template('/user_portal/classic_courses_without_category.tpl')
1164
                );
1165
            }
1166
1167
            // Display courses
1168
            // [code=>xxx, real_id=>000]
1169
            $listCourses = CourseManager::get_courses_list_by_user_id(
1170
                $user_id,
1171
                false
1172
            );
1173
1174
            foreach ($listCourses as $i => $listCourseCodeId) {
1175
                if (isset($listCourseCodeId['special_course'])) {
1176
                    continue;
1177
                }
1178
                $courseCategory = CourseManager::getUserCourseCategoryForCourse(
1179
                    $user_id,
1180
                    $listCourseCodeId['real_id']
1181
                );
1182
1183
                $userCatTitle = '';
1184
                $userCategoryId = 0;
1185
                if ($courseCategory) {
1186
                    $userCategoryId = $courseCategory['user_course_cat'];
1187
                    $userCatTitle = $courseCategory['title'];
1188
                }
1189
1190
                $listCourse = api_get_course_info_by_id($listCourseCodeId['real_id']);
1191
                $listCoursesInfo[] = [
1192
                    'course' => $listCourse,
1193
                    'code' => $listCourseCodeId['code'],
1194
                    'id' => $listCourseCodeId['real_id'],
1195
                    'title' => $listCourse['title'],
1196
                    'userCatId' => $userCategoryId,
1197
                    'userCatTitle' => $userCatTitle,
1198
                ];
1199
                $courseCount++;
1200
            }
1201
            usort($listCoursesInfo, 'self::compareByCourse');
1202
        }
1203
1204
        $listCoursesInSession = [];
1205
        if (is_array($session_categories)) {
1206
            // all courses that are in a session
1207
            $listCoursesInSession = SessionManager::getNamedSessionCourseForCoach($user_id);
1208
        }
1209
1210
        // we got all courses
1211
        // for each user category, sorted alphabetically, display courses
1212
        $listUserCategories = CourseManager::get_user_course_categories($user_id);
1213
        $listCoursesAlreadyDisplayed = [];
1214
        uasort($listUserCategories, "self::compareListUserCategory");
1215
        $listUserCategories[0] = '';
1216
1217
        $html .= '<div class="session-view-block">';
1218
        foreach ($listUserCategories as $userCategoryId => $userCat) {
1219
            // add user category
1220
            $userCategoryHtml = '';
1221
            if ($userCategoryId != 0) {
1222
                $userCategoryHtml = '<div class="session-view-well ">';
1223
                $userCategoryHtml .= self::getHtmlForUserCategory($userCategoryId, $userCat['title']);
1224
            }
1225
            // look for course in this userCat in session courses : $listCoursesInSession
1226
            $htmlCategory = '';
1227
            if (isset($listCoursesInSession[$userCategoryId])) {
1228
                // list of courses in this user cat
1229
                foreach ($listCoursesInSession[$userCategoryId]['courseInUserCatList'] as $i => $listCourse) {
1230
                    // add course
1231
                    $listCoursesAlreadyDisplayed[$listCourse['courseId']] = 1;
1232
                    if ($userCategoryId == 0) {
1233
                        $htmlCategory .= '<div class="panel panel-default">';
1234
                    } else {
1235
                        $htmlCategory .= '<div class="panel panel-default">';
1236
                    }
1237
                    $htmlCategory .= '<div class="panel-body">';
1238
                    $coursesInfo = $listCourse['course'];
1239
1240
                    $htmlCategory .= self::getHtmlForCourse(
1241
                        $coursesInfo,
1242
                        $userCategoryId,
1243
                        1,
1244
                        $loadDirs
1245
                    );
1246
                    // list of session category
1247
                    $htmlSessionCategory = '<div
1248
                        class="session-view-row"
1249
                        style="display:none;"
1250
                        id="courseblock-'.$coursesInfo['real_id'].'"
1251
                        >';
1252
                    foreach ($listCourse['sessionCatList'] as $listCategorySession) {
1253
                        $catSessionId = null;
1254
                        if (isset($listCategorySession['catSessionId'])) {
1255
                            $catSessionId = $listCategorySession['catSessionId'];
1256
                        }
1257
                        // add session category
1258
                        if ($catSessionId) {
1259
                            $htmlSessionCategory .= self::getHtmlSessionCategory(
1260
                                $listCategorySession['catSessionId'],
1261
                                $listCategorySession['catSessionName']
1262
                            );
1263
                        }
1264
1265
                        // list of session
1266
                        $htmlSession = ''; // start
1267
                        foreach ($listCategorySession['sessionList'] as $listSession) {
1268
                            // add session
1269
                            $htmlSession .= '<div class="session-view-row">';
1270
                            $htmlSession .= self::getHtmlForSession(
1271
                                $listSession['sessionId'],
1272
                                $listSession['sessionName'],
1273
                                $catSessionId,
1274
                                $coursesInfo
1275
                            );
1276
                            $htmlSession .= '</div>';
1277
                            $sessionCount++;
1278
                        }
1279
                        $htmlSession .= ''; // end session block
1280
                        $htmlSessionCategory .= $htmlSession;
1281
                    }
1282
                    $htmlSessionCategory .= '</div>'; // end session cat block
1283
                    $htmlCategory .= $htmlSessionCategory.'</div></div>';
1284
                    $htmlCategory .= ''; // end course block
1285
                }
1286
                $userCategoryHtml .= $htmlCategory;
1287
            }
1288
1289
            // look for courses in this userCat in not in session courses : $listCoursesInfo
1290
            // if course not already added
1291
            $htmlCategory = '';
1292
            foreach ($listCoursesInfo as $i => $listCourse) {
1293
                if ($listCourse['userCatId'] == $userCategoryId &&
1294
                    !isset($listCoursesAlreadyDisplayed[$listCourse['id']])
1295
                ) {
1296
                    if ($userCategoryId != 0) {
1297
                        $htmlCategory .= '<div class="panel panel-default">';
1298
                    } else {
1299
                        $htmlCategory .= '<div class="panel panel-default">';
1300
                    }
1301
1302
                    $htmlCategory .= '<div class="panel-body">';
1303
                    $htmlCategory .= self::getHtmlForCourse(
1304
                        $listCourse['course'],
1305
                        $userCategoryId,
1306
                        0,
1307
                        $loadDirs
1308
                    );
1309
                    $htmlCategory .= '</div></div>';
1310
                }
1311
            }
1312
            $htmlCategory .= '';
1313
            $userCategoryHtml .= $htmlCategory; // end user cat block
1314
            if ($userCategoryId != 0) {
1315
                $userCategoryHtml .= '</div>';
1316
            }
1317
            $html .= $userCategoryHtml;
1318
        }
1319
        $html .= '</div>';
1320
1321
        return [
1322
            'html' => $html,
1323
            'sessions' => $session_categories,
1324
            'courses' => $listCoursesInfo,
1325
            'session_count' => $sessionCount,
1326
            'course_count' => $courseCount,
1327
        ];
1328
    }
1329
1330
    /**
1331
     * @param int $userId
1332
     *
1333
     * @return array
1334
     */
1335
    public function returnCourseCategoryListFromUser($userId)
1336
    {
1337
        $sessionCount = 0;
1338
        $courseList = CourseManager::get_courses_list_by_user_id($userId);
1339
        $categoryCodes = CourseManager::getCourseCategoriesFromCourseList($courseList);
1340
        $categories = [];
1341
        foreach ($categoryCodes as $categoryCode) {
1342
            $categories[] = CourseCategory::getCategory($categoryCode);
1343
        }
1344
1345
        $template = new Template('', false, false, false, true, false, false);
1346
        $layout = $template->get_template('user_portal/course_categories.tpl');
1347
        $template->assign('course_categories', $categories);
1348
1349
        return [
1350
            'courses' => $courseList,
1351
            'html' => $template->fetch($layout),
1352
            'course_count' => count($courseList),
1353
            'session_count' => $sessionCount,
1354
        ];
1355
    }
1356
1357
    /**
1358
     * Set grade book dependency progress bar see BT#13099.
1359
     *
1360
     * @param $userId
1361
     *
1362
     * @return bool
1363
     */
1364
    public function setGradeBookDependencyBar($userId)
1365
    {
1366
        $allow = api_get_configuration_value('gradebook_dependency');
1367
1368
        if (api_is_anonymous()) {
1369
            return false;
1370
        }
1371
1372
        if ($allow) {
1373
            $courseAndSessions = $this->returnCoursesAndSessions(
1374
                $userId,
1375
                false,
1376
                '',
1377
                false,
1378
                false
1379
            );
1380
1381
            $courseList = api_get_configuration_value('gradebook_dependency_mandatory_courses');
1382
            $courseList = isset($courseList['courses']) ? $courseList['courses'] : [];
1383
            $mandatoryCourse = [];
1384
            if (!empty($courseList)) {
1385
                foreach ($courseList as $courseId) {
1386
                    $courseInfo = api_get_course_info_by_id($courseId);
1387
                    $mandatoryCourse[] = $courseInfo['code'];
1388
                }
1389
            }
1390
1391
            // @todo improve calls of course info
1392
            $subscribedCourses = !empty($courseAndSessions['courses']) ? $courseAndSessions['courses'] : [];
1393
            $mainCategoryList = [];
1394
            foreach ($subscribedCourses as $courseInfo) {
1395
                $courseCode = $courseInfo['code'];
1396
                $categories = Category::load(null, null, $courseCode);
1397
                /** @var Category $category */
1398
                $category = !empty($categories[0]) ? $categories[0] : [];
1399
                if (!empty($category)) {
1400
                    $mainCategoryList[] = $category;
1401
                }
1402
            }
1403
1404
            $result20 = 0;
1405
            $result80 = 0;
1406
            $countCoursesPassedNoDependency = 0;
1407
            /** @var Category $category */
1408
            foreach ($mainCategoryList as $category) {
1409
                $userFinished = Category::userFinishedCourse(
1410
                    $userId,
1411
                    $category,
1412
                    true
1413
                );
1414
1415
                if ($userFinished) {
1416
                    if (in_array($category->get_course_code(), $mandatoryCourse)) {
1417
                        if ($result20 < 20) {
1418
                            $result20 += 10;
1419
                        }
1420
                    } else {
1421
                        $countCoursesPassedNoDependency++;
1422
                        if ($result80 < 80) {
1423
                            $result80 += 10;
1424
                        }
1425
                    }
1426
                }
1427
            }
1428
1429
            $finalResult = $result20 + $result80;
1430
1431
            $gradeBookList = api_get_configuration_value('gradebook_badge_sidebar');
1432
            $gradeBookList = isset($gradeBookList['gradebooks']) ? $gradeBookList['gradebooks'] : [];
1433
            $badgeList = [];
1434
            foreach ($gradeBookList as $id) {
1435
                $categories = Category::load($id);
1436
                /** @var Category $category */
1437
                $category = !empty($categories[0]) ? $categories[0] : [];
1438
                $badgeList[$id]['name'] = $category->get_name();
1439
                $badgeList[$id]['finished'] = false;
1440
                $badgeList[$id]['skills'] = [];
1441
                if (!empty($category)) {
1442
                    $minToValidate = $category->getMinimumToValidate();
1443
                    $dependencies = $category->getCourseListDependency();
1444
                    $gradeBooksToValidateInDependence = $category->getGradeBooksToValidateInDependence();
1445
                    $countDependenciesPassed = 0;
1446
                    foreach ($dependencies as $courseId) {
1447
                        $courseInfo = api_get_course_info_by_id($courseId);
1448
                        $courseCode = $courseInfo['code'];
1449
                        $categories = Category::load(null, null, $courseCode);
1450
                        $subCategory = !empty($categories[0]) ? $categories[0] : null;
1451
                        if (!empty($subCategory)) {
1452
                            $score = Category::userFinishedCourse(
1453
                                $userId,
1454
                                $subCategory,
1455
                                true
1456
                            );
1457
                            if ($score) {
1458
                                $countDependenciesPassed++;
1459
                            }
1460
                        }
1461
                    }
1462
1463
                    $userFinished =
1464
                        $countDependenciesPassed >= $gradeBooksToValidateInDependence &&
1465
                        $countCoursesPassedNoDependency >= $minToValidate;
1466
1467
                    if ($userFinished) {
1468
                        $badgeList[$id]['finished'] = true;
1469
                    }
1470
1471
                    $objSkill = new Skill();
1472
                    $skills = $category->get_skills();
1473
                    $skillList = [];
1474
                    foreach ($skills as $skill) {
1475
                        $skillList[] = $objSkill->get($skill['id']);
1476
                    }
1477
                    $badgeList[$id]['skills'] = $skillList;
1478
                }
1479
            }
1480
1481
            $this->tpl->assign(
1482
                'grade_book_sidebar',
1483
                true
1484
            );
1485
1486
            $this->tpl->assign(
1487
                'grade_book_progress',
1488
                $finalResult
1489
            );
1490
            $this->tpl->assign('grade_book_badge_list', $badgeList);
1491
1492
            return true;
1493
        }
1494
1495
        return false;
1496
    }
1497
1498
    /**
1499
     * Prints the session and course list (user_portal.php).
1500
     *
1501
     * @param int    $user_id
1502
     * @param bool   $showSessions
1503
     * @param string $categoryCodeFilter
1504
     * @param bool   $useUserLanguageFilterIfAvailable
1505
     * @param bool   $loadHistory
1506
     *
1507
     * @return array
1508
     */
1509
    public function returnCoursesAndSessions(
1510
        $user_id,
1511
        $showSessions = true,
1512
        $categoryCodeFilter = '',
1513
        $useUserLanguageFilterIfAvailable = true,
1514
        $loadHistory = false
1515
    ) {
1516
        $gameModeIsActive = api_get_setting('gamification_mode');
1517
        $viewGridCourses = api_get_configuration_value('view_grid_courses');
1518
        $showSimpleSessionInfo = api_get_configuration_value('show_simple_session_info');
1519
        $coursesWithoutCategoryTemplate = '/user_portal/classic_courses_without_category.tpl';
1520
        $coursesWithCategoryTemplate = '/user_portal/classic_courses_with_category.tpl';
1521
        $showAllSessions = api_get_configuration_value('show_all_sessions_on_my_course_page') === true;
1522
1523
        if ($loadHistory) {
1524
            // Load sessions in category in *history*
1525
            $session_categories = UserManager::get_sessions_by_category($user_id, true);
1526
        } else {
1527
            // Load sessions in category
1528
            $session_categories = UserManager::get_sessions_by_category($user_id, false);
1529
        }
1530
1531
        $sessionCount = 0;
1532
        $courseCount = 0;
1533
1534
        // Student info code check (shows student progress information on
1535
        // courses list
1536
        $studentInfo = api_get_configuration_value('course_student_info');
1537
1538
        $studentInfoProgress = !empty($studentInfo['progress']) && $studentInfo['progress'] === true;
1539
        $studentInfoScore = !empty($studentInfo['score']) && $studentInfo['score'] === true;
1540
        $studentInfoCertificate = !empty($studentInfo['certificate']) && $studentInfo['certificate'] === true;
1541
        $courseCompleteList = [];
1542
        $coursesInCategoryCount = 0;
1543
        $coursesNotInCategoryCount = 0;
1544
        $listCourse = '';
1545
        $specialCourseList = '';
1546
1547
        // If we're not in the history view...
1548
        if ($loadHistory === false) {
1549
            // Display special courses.
1550
            $specialCourses = CourseManager::returnSpecialCourses(
1551
                $user_id,
1552
                $this->load_directories_preview,
1553
                $useUserLanguageFilterIfAvailable
1554
            );
1555
1556
            // Display courses.
1557
            $courses = CourseManager::returnCourses(
1558
                $user_id,
1559
                $this->load_directories_preview,
1560
                $useUserLanguageFilterIfAvailable
1561
            );
1562
1563
            // Course option (show student progress)
1564
            // This code will add new variables (Progress, Score, Certificate)
1565
            if ($studentInfoProgress || $studentInfoScore || $studentInfoCertificate) {
1566
                if (!empty($specialCourses)) {
1567
                    foreach ($specialCourses as $key => $specialCourseInfo) {
1568
                        if ($studentInfoProgress) {
1569
                            $progress = Tracking::get_avg_student_progress(
1570
                                $user_id,
1571
                                $specialCourseInfo['course_code']
1572
                            );
1573
                            $specialCourses[$key]['student_info']['progress'] = $progress === false ? null : $progress;
1574
                        }
1575
1576
                        if ($studentInfoScore) {
1577
                            $percentage_score = Tracking::get_avg_student_score(
1578
                                $user_id,
1579
                                $specialCourseInfo['course_code'],
1580
                                []
1581
                            );
1582
                            $specialCourses[$key]['student_info']['score'] = $percentage_score;
1583
                        }
1584
1585
                        if ($studentInfoCertificate) {
1586
                            $category = Category::load(
1587
                                null,
1588
                                null,
1589
                                $specialCourseInfo['course_code'],
1590
                                null,
1591
                                null,
1592
                                null
1593
                            );
1594
                            $specialCourses[$key]['student_info']['certificate'] = null;
1595
                            if (isset($category[0])) {
1596
                                if ($category[0]->is_certificate_available($user_id)) {
1597
                                    $specialCourses[$key]['student_info']['certificate'] = Display::label(
1598
                                        get_lang('Yes'),
1599
                                        'success'
1600
                                    );
1601
                                } else {
1602
                                    $specialCourses[$key]['student_info']['certificate'] = Display::label(
1603
                                        get_lang('No'),
1604
                                        'danger'
1605
                                    );
1606
                                }
1607
                            }
1608
                        }
1609
                    }
1610
                }
1611
1612
                if (isset($courses['in_category'])) {
1613
                    foreach ($courses['in_category'] as $key1 => $value) {
1614
                        if (isset($courses['in_category'][$key1]['courses'])) {
1615
                            foreach ($courses['in_category'][$key1]['courses'] as $key2 => $courseInCatInfo) {
1616
                                $courseCode = $courseInCatInfo['course_code'];
1617
                                if ($studentInfoProgress) {
1618
                                    $progress = Tracking::get_avg_student_progress(
1619
                                        $user_id,
1620
                                        $courseCode
1621
                                    );
1622
                                    $courses['in_category'][$key1]['courses'][$key2]['student_info']['progress'] = $progress === false ? null : $progress;
1623
                                }
1624
1625
                                if ($studentInfoScore) {
1626
                                    $percentage_score = Tracking::get_avg_student_score(
1627
                                        $user_id,
1628
                                        $courseCode,
1629
                                        []
1630
                                    );
1631
                                    $courses['in_category'][$key1]['courses'][$key2]['student_info']['score'] = $percentage_score;
1632
                                }
1633
1634
                                if ($studentInfoCertificate) {
1635
                                    $category = Category::load(
1636
                                        null,
1637
                                        null,
1638
                                        $courseCode,
1639
                                        null,
1640
                                        null,
1641
                                        null
1642
                                    );
1643
                                    $courses['in_category'][$key1]['student_info']['certificate'] = null;
1644
                                    $isCertificateAvailable = $category[0]->is_certificate_available($user_id);
1645
                                    if (isset($category[0])) {
1646
                                        if ($viewGridCourses) {
1647
                                            if ($isCertificateAvailable) {
1648
                                                $courses['in_category'][$key1]['student_info']['certificate'] = get_lang(
1649
                                                    'Yes'
1650
                                                );
1651
                                            } else {
1652
                                                $courses['in_category'][$key1]['student_info']['certificate'] = get_lang(
1653
                                                    'No'
1654
                                                );
1655
                                            }
1656
                                        } else {
1657
                                            if ($isCertificateAvailable) {
1658
                                                $courses['in_category'][$key1]['student_info']['certificate'] = Display::label(
1659
                                                    get_lang('Yes'),
1660
                                                    'success'
1661
                                                );
1662
                                            } else {
1663
                                                $courses['in_category'][$key1]['student_info']['certificate'] = Display::label(
1664
                                                    get_lang('No'),
1665
                                                    'danger'
1666
                                                );
1667
                                            }
1668
                                        }
1669
                                    }
1670
                                }
1671
                            }
1672
                        }
1673
                    }
1674
                }
1675
1676
                if (isset($courses['not_category'])) {
1677
                    foreach ($courses['not_category'] as $key => $courseNotInCatInfo) {
1678
                        $courseCode = $courseNotInCatInfo['course_code'];
1679
                        if ($studentInfoProgress) {
1680
                            $progress = Tracking::get_avg_student_progress(
1681
                                $user_id,
1682
                                $courseCode
1683
                            );
1684
                            $courses['not_category'][$key]['student_info']['progress'] = $progress === false ? null : $progress;
1685
                        }
1686
1687
                        if ($studentInfoScore) {
1688
                            $percentage_score = Tracking::get_avg_student_score(
1689
                                $user_id,
1690
                                $courseCode,
1691
                                []
1692
                            );
1693
                            $courses['not_category'][$key]['student_info']['score'] = $percentage_score;
1694
                        }
1695
1696
                        if ($studentInfoCertificate) {
1697
                            $category = Category::load(
1698
                                null,
1699
                                null,
1700
                                $courseCode,
1701
                                null,
1702
                                null,
1703
                                null
1704
                            );
1705
                            $courses['not_category'][$key]['student_info']['certificate'] = null;
1706
1707
                            if (isset($category[0])) {
1708
                                $certificateAvailable = $category[0]->is_certificate_available($user_id);
1709
                                if ($viewGridCourses) {
1710
                                    if ($certificateAvailable) {
1711
                                        $courses['not_category'][$key]['student_info']['certificate'] = get_lang('Yes');
1712
                                    } else {
1713
                                        $courses['not_category'][$key]['student_info']['certificate'] = get_lang('No');
1714
                                    }
1715
                                } else {
1716
                                    if ($certificateAvailable) {
1717
                                        $courses['not_category'][$key]['student_info']['certificate'] = Display::label(
1718
                                            get_lang('Yes'),
1719
                                            'success'
1720
                                        );
1721
                                    } else {
1722
                                        $courses['not_category'][$key]['student_info']['certificate'] = Display::label(
1723
                                            get_lang('No'),
1724
                                            'danger'
1725
                                        );
1726
                                    }
1727
                                }
1728
                            }
1729
                        }
1730
                    }
1731
                }
1732
            }
1733
1734
            if ($viewGridCourses) {
1735
                $coursesWithoutCategoryTemplate = '/user_portal/grid_courses_without_category.tpl';
1736
                $coursesWithCategoryTemplate = '/user_portal/grid_courses_with_category.tpl';
1737
            }
1738
1739
            if ($specialCourses) {
1740
                if ($categoryCodeFilter) {
1741
                    $specialCourses = self::filterByCategory($specialCourses, $categoryCodeFilter);
1742
                }
1743
                $this->tpl->assign('courses', $specialCourses);
1744
                $specialCourseList = $this->tpl->fetch($this->tpl->get_template($coursesWithoutCategoryTemplate));
1745
                $courseCompleteList = array_merge($courseCompleteList, $specialCourses);
1746
            }
1747
1748
            if ($courses['in_category'] || $courses['not_category']) {
1749
                foreach ($courses['in_category'] as $courseData) {
1750
                    if (!empty($courseData['courses'])) {
1751
                        $coursesInCategoryCount += count($courseData['courses']);
1752
                        $courseCompleteList = array_merge($courseCompleteList, $courseData['courses']);
1753
                    }
1754
                }
1755
1756
                $coursesNotInCategoryCount += count($courses['not_category']);
1757
                $courseCompleteList = array_merge($courseCompleteList, $courses['not_category']);
1758
1759
                if ($categoryCodeFilter) {
1760
                    $courses['in_category'] = self::filterByCategory(
1761
                        $courses['in_category'],
1762
                        $categoryCodeFilter
1763
                    );
1764
                    $courses['not_category'] = self::filterByCategory(
1765
                        $courses['not_category'],
1766
                        $categoryCodeFilter
1767
                    );
1768
                }
1769
1770
                $this->tpl->assign('courses', $courses['not_category']);
1771
                $this->tpl->assign('categories', $courses['in_category']);
1772
1773
                $listCourse = $this->tpl->fetch($this->tpl->get_template($coursesWithCategoryTemplate));
1774
                $listCourse .= $this->tpl->fetch($this->tpl->get_template($coursesWithoutCategoryTemplate));
1775
            }
1776
1777
            $courseCount = count($specialCourses) + $coursesInCategoryCount + $coursesNotInCategoryCount;
1778
        }
1779
1780
        $sessions_with_category = '';
1781
        $sessions_with_no_category = '';
1782
        $collapsable = api_get_configuration_value('allow_user_session_collapsable');
1783
        $collapsableLink = '';
1784
        if ($collapsable) {
1785
            $collapsableLink = api_get_path(WEB_PATH).'user_portal.php?action=collapse_session';
1786
        }
1787
1788
        $extraFieldValue = new ExtraFieldValue('session');
1789
        if ($showSessions) {
1790
            $coursesListSessionStyle = api_get_configuration_value('courses_list_session_title_link');
1791
            $coursesListSessionStyle = $coursesListSessionStyle === false ? 1 : $coursesListSessionStyle;
1792
            if (api_is_drh()) {
1793
                $coursesListSessionStyle = 1;
1794
            }
1795
1796
            $portalShowDescription = api_get_setting('show_session_description') === 'true';
1797
1798
            // Declared listSession variable
1799
            $listSession = [];
1800
            // Get timestamp in UTC to compare to DB values (in UTC by convention)
1801
            $session_now = strtotime(api_get_utc_datetime(time()));
1802
            if (is_array($session_categories)) {
1803
                foreach ($session_categories as $session_category) {
1804
                    $session_category_id = $session_category['session_category']['id'];
1805
                    // Sessions and courses that are not in a session category
1806
                    if (empty($session_category_id) &&
1807
                        isset($session_category['sessions'])
1808
                    ) {
1809
                        // Independent sessions
1810
                        foreach ($session_category['sessions'] as $session) {
1811
                            $session_id = $session['session_id'];
1812
1813
                            // Don't show empty sessions.
1814
                            if (count($session['courses']) < 1) {
1815
                                continue;
1816
                            }
1817
1818
                            // Courses inside the current session.
1819
                            $date_session_start = $session['access_start_date'];
1820
                            $date_session_end = $session['access_end_date'];
1821
                            $coachAccessStartDate = $session['coach_access_start_date'];
1822
                            $coachAccessEndDate = $session['coach_access_end_date'];
1823
                            $count_courses_session = 0;
1824
1825
                            // Loop course content
1826
                            $html_courses_session = [];
1827
                            $atLeastOneCourseIsVisible = false;
1828
                            $markAsOld = false;
1829
                            $markAsFuture = false;
1830
1831
                            foreach ($session['courses'] as $course) {
1832
                                $is_coach_course = api_is_coach($session_id, $course['real_id']);
1833
                                $allowed_time = 0;
1834
                                $allowedEndTime = true;
1835
1836
                                if (!empty($date_session_start)) {
1837
                                    if ($is_coach_course) {
1838
                                        $allowed_time = api_strtotime($coachAccessStartDate);
1839
                                    } else {
1840
                                        $allowed_time = api_strtotime($date_session_start);
1841
                                    }
1842
1843
                                    $endSessionToTms = null;
1844
                                    if (!isset($_GET['history'])) {
1845
                                        if (!empty($date_session_end)) {
1846
                                            if ($is_coach_course) {
1847
                                                // if coach end date is empty we use the default end date
1848
                                                if (empty($coachAccessEndDate)) {
1849
                                                    $endSessionToTms = api_strtotime($date_session_end);
1850
                                                    if ($session_now > $endSessionToTms) {
1851
                                                        $allowedEndTime = false;
1852
                                                    }
1853
                                                } else {
1854
                                                    $endSessionToTms = api_strtotime($coachAccessEndDate);
1855
                                                    if ($session_now > $endSessionToTms) {
1856
                                                        $allowedEndTime = false;
1857
                                                    }
1858
                                                }
1859
                                            } else {
1860
                                                $endSessionToTms = api_strtotime($date_session_end);
1861
                                                if ($session_now > $endSessionToTms) {
1862
                                                    $allowedEndTime = false;
1863
                                                }
1864
                                            }
1865
                                        }
1866
                                    }
1867
                                }
1868
1869
                                if ($showAllSessions) {
1870
                                    if ($allowed_time < $session_now && $allowedEndTime === false) {
1871
                                        $markAsOld = true;
1872
                                    }
1873
                                    if ($allowed_time > $session_now && $endSessionToTms > $session_now) {
1874
                                        $markAsFuture = true;
1875
                                    }
1876
                                    $allowedEndTime = true;
1877
                                    $allowed_time = 0;
1878
                                }
1879
1880
                                if ($session_now >= $allowed_time && $allowedEndTime) {
1881
                                    // Read only and accessible.
1882
                                    $atLeastOneCourseIsVisible = true;
1883
                                    if (api_get_setting('hide_courses_in_sessions') === 'false') {
1884
                                        $courseUserHtml = CourseManager::get_logged_user_course_html(
1885
                                            $course,
1886
                                            $session_id,
1887
                                            'session_course_item',
1888
                                            true,
1889
                                            $this->load_directories_preview
1890
                                        );
1891
                                        if (isset($courseUserHtml[1])) {
1892
                                            $course_session = $courseUserHtml[1];
1893
                                            $course_session['skill'] = isset($courseUserHtml['skill']) ? $courseUserHtml['skill'] : '';
1894
1895
                                            // Course option (show student progress)
1896
                                            // This code will add new variables (Progress, Score, Certificate)
1897
                                            if ($studentInfoProgress || $studentInfoScore || $studentInfoCertificate) {
1898
                                                if ($studentInfoProgress) {
1899
                                                    $progress = Tracking::get_avg_student_progress(
1900
                                                        $user_id,
1901
                                                        $course['course_code'],
1902
                                                        [],
1903
                                                        $session_id
1904
                                                    );
1905
                                                    $course_session['student_info']['progress'] = $progress === false ? null : $progress;
1906
                                                }
1907
1908
                                                if ($studentInfoScore) {
1909
                                                    $percentage_score = Tracking::get_avg_student_score(
1910
                                                        $user_id,
1911
                                                        $course['course_code'],
1912
                                                        [],
1913
                                                        $session_id
1914
                                                    );
1915
                                                    $course_session['student_info']['score'] = $percentage_score;
1916
                                                }
1917
1918
                                                if ($studentInfoCertificate) {
1919
                                                    $category = Category::load(
1920
                                                        null,
1921
                                                        null,
1922
                                                        $course['course_code'],
1923
                                                        null,
1924
                                                        null,
1925
                                                        $session_id
1926
                                                    );
1927
                                                    $course_session['student_info']['certificate'] = null;
1928
                                                    if (isset($category[0])) {
1929
                                                        if ($category[0]->is_certificate_available($user_id)) {
1930
                                                            $course_session['student_info']['certificate'] = Display::label(
1931
                                                                get_lang('Yes'),
1932
                                                                'success'
1933
                                                            );
1934
                                                        } else {
1935
                                                            $course_session['student_info']['certificate'] = Display::label(
1936
                                                                get_lang('No')
1937
                                                            );
1938
                                                        }
1939
                                                    }
1940
                                                }
1941
                                            }
1942
1943
                                            $course_session['extrafields'] = CourseManager::getExtraFieldsToBePresented($course['real_id']);
1944
1945
                                            if (api_get_configuration_value(
1946
                                                'enable_unsubscribe_button_on_my_course_page'
1947
                                                )
1948
                                                && '1' === $course['unsubscribe']
1949
                                            ) {
1950
                                                $course_session['unregister_button'] =
1951
                                                    CoursesAndSessionsCatalog::return_unregister_button(
1952
                                                        ['code' => $course['course_code']],
1953
                                                        Security::get_existing_token(),
1954
                                                        '',
1955
                                                        ''
1956
                                                    );
1957
                                            }
1958
1959
                                            $html_courses_session[] = $course_session;
1960
                                        }
1961
                                    }
1962
                                    $count_courses_session++;
1963
                                }
1964
                            }
1965
1966
                            // No courses to show.
1967
                            if ($atLeastOneCourseIsVisible === false) {
1968
                                if (empty($html_courses_session)) {
1969
                                    continue;
1970
                                }
1971
                            }
1972
1973
                            if ($count_courses_session > 0) {
1974
                                $params = [
1975
                                    'id' => $session_id,
1976
                                ];
1977
                                $session_box = Display::getSessionTitleBox($session_id);
1978
                                $coachId = $session_box['id_coach'];
1979
                                $imageField = $extraFieldValue->get_values_by_handler_and_field_variable(
1980
                                    $session_id,
1981
                                    'image'
1982
                                );
1983
1984
                                $params['category_id'] = $session_box['category_id'];
1985
                                $params['title'] = $session_box['title'];
1986
                                $params['id_coach'] = $coachId;
1987
                                $params['coach_url'] = api_get_path(WEB_AJAX_PATH).
1988
                                    'user_manager.ajax.php?a=get_user_popup&user_id='.$coachId;
1989
                                $params['coach_name'] = !empty($session_box['coach']) ? $session_box['coach'] : null;
1990
                                $params['coach_avatar'] = UserManager::getUserPicture(
1991
                                    $coachId,
1992
                                    USER_IMAGE_SIZE_SMALL
1993
                                );
1994
                                $params['date'] = $session_box['dates'];
1995
                                $params['image'] = isset($imageField['value']) ? $imageField['value'] : null;
1996
                                $params['duration'] = isset($session_box['duration']) ? ' '.$session_box['duration'] : null;
1997
                                $params['show_actions'] = SessionManager::cantEditSession($session_id);
1998
1999
                                if ($collapsable) {
2000
                                    $collapsableData = SessionManager::getCollapsableData(
2001
                                        $user_id,
2002
                                        $session_id,
2003
                                        $extraFieldValue,
2004
                                        $collapsableLink
2005
                                    );
2006
                                    $params['collapsed'] = $collapsableData['collapsed'];
2007
                                    $params['collapsable_link'] = $collapsableData['collapsable_link'];
2008
                                }
2009
2010
                                $params['show_description'] = $session_box['show_description'] == 1 && $portalShowDescription;
2011
                                $params['description'] = $session_box['description'];
2012
                                $params['visibility'] = $session_box['visibility'];
2013
                                $params['show_simple_session_info'] = $showSimpleSessionInfo;
2014
                                $params['course_list_session_style'] = $coursesListSessionStyle;
2015
                                $params['num_users'] = $session_box['num_users'];
2016
                                $params['num_courses'] = $session_box['num_courses'];
2017
                                $params['course_categories'] = CourseManager::getCourseCategoriesFromCourseList(
2018
                                    $html_courses_session
2019
                                );
2020
                                $params['courses'] = $html_courses_session;
2021
                                $params['is_old'] = $markAsOld;
2022
                                $params['is_future'] = $markAsFuture;
2023
2024
                                if ($showSimpleSessionInfo) {
2025
                                    $params['subtitle'] = self::getSimpleSessionDetails(
2026
                                        $session_box['coach'],
2027
                                        $session_box['dates'],
2028
                                        isset($session_box['duration']) ? $session_box['duration'] : null
2029
                                    );
2030
                                }
2031
2032
                                if ($gameModeIsActive) {
2033
                                    $params['stars'] = GamificationUtils::getSessionStars(
2034
                                        $params['id'],
2035
                                        $this->user_id
2036
                                    );
2037
                                    $params['progress'] = GamificationUtils::getSessionProgress(
2038
                                        $params['id'],
2039
                                        $this->user_id
2040
                                    );
2041
                                    $params['points'] = GamificationUtils::getSessionPoints(
2042
                                        $params['id'],
2043
                                        $this->user_id
2044
                                    );
2045
                                }
2046
                                $listSession[] = $params;
2047
                                $sessionCount++;
2048
                            }
2049
                        }
2050
                    } else {
2051
                        // All sessions included in
2052
                        $count_courses_session = 0;
2053
                        $html_sessions = '';
2054
                        if (isset($session_category['sessions'])) {
2055
                            foreach ($session_category['sessions'] as $session) {
2056
                                $session_id = $session['session_id'];
2057
2058
                                // Don't show empty sessions.
2059
                                if (count($session['courses']) < 1) {
2060
                                    continue;
2061
                                }
2062
2063
                                $date_session_start = $session['access_start_date'];
2064
                                $date_session_end = $session['access_end_date'];
2065
                                $coachAccessStartDate = $session['coach_access_start_date'];
2066
                                $coachAccessEndDate = $session['coach_access_end_date'];
2067
                                $html_courses_session = [];
2068
                                $count = 0;
2069
                                $markAsOld = false;
2070
                                $markAsFuture = false;
2071
2072
                                foreach ($session['courses'] as $course) {
2073
                                    $is_coach_course = api_is_coach($session_id, $course['real_id']);
2074
                                    $allowed_time = 0;
2075
                                    $allowedEndTime = true;
2076
2077
                                    if (!empty($date_session_start)) {
2078
                                        if ($is_coach_course) {
2079
                                            $allowed_time = api_strtotime($coachAccessStartDate);
2080
                                        } else {
2081
                                            $allowed_time = api_strtotime($date_session_start);
2082
                                        }
2083
2084
                                        if (!isset($_GET['history'])) {
2085
                                            if (!empty($date_session_end)) {
2086
                                                if ($is_coach_course) {
2087
                                                    // if coach end date is empty we use the default end date
2088
                                                    if (empty($coachAccessEndDate)) {
2089
                                                        $endSessionToTms = api_strtotime($date_session_end);
2090
                                                        if ($session_now > $endSessionToTms) {
2091
                                                            $allowedEndTime = false;
2092
                                                        }
2093
                                                    } else {
2094
                                                        $endSessionToTms = api_strtotime($coachAccessEndDate);
2095
                                                        if ($session_now > $endSessionToTms) {
2096
                                                            $allowedEndTime = false;
2097
                                                        }
2098
                                                    }
2099
                                                } else {
2100
                                                    $endSessionToTms = api_strtotime($date_session_end);
2101
                                                    if ($session_now > $endSessionToTms) {
2102
                                                        $allowedEndTime = false;
2103
                                                    }
2104
                                                }
2105
                                            }
2106
                                        }
2107
                                    }
2108
2109
                                    if ($showAllSessions) {
2110
                                        if ($allowed_time < $session_now && $allowedEndTime == false) {
2111
                                            $markAsOld = true;
2112
                                        }
2113
                                        if ($allowed_time > $session_now && $endSessionToTms > $session_now) {
2114
                                            $markAsFuture = true;
2115
                                        }
2116
                                        $allowedEndTime = true;
2117
                                        $allowed_time = 0;
2118
                                    }
2119
2120
                                    if ($session_now >= $allowed_time && $allowedEndTime) {
2121
                                        if (api_get_setting('hide_courses_in_sessions') === 'false') {
2122
                                            $c = CourseManager::get_logged_user_course_html(
2123
                                                $course,
2124
                                                $session_id,
2125
                                                'session_course_item'
2126
                                            );
2127
                                            if (isset($c[1])) {
2128
                                                $html_courses_session[] = $c[1];
2129
                                            }
2130
                                        }
2131
                                        $count_courses_session++;
2132
                                        $count++;
2133
                                    }
2134
                                }
2135
2136
                                $sessionParams = [];
2137
                                // Category
2138
                                if ($count > 0) {
2139
                                    $session_box = Display::getSessionTitleBox($session_id);
2140
                                    $sessionParams[0]['id'] = $session_id;
2141
                                    $sessionParams[0]['date'] = $session_box['dates'];
2142
                                    $sessionParams[0]['duration'] = isset($session_box['duration']) ? ' '.$session_box['duration'] : null;
2143
                                    $sessionParams[0]['course_list_session_style'] = $coursesListSessionStyle;
2144
                                    $sessionParams[0]['title'] = $session_box['title'];
2145
                                    $sessionParams[0]['subtitle'] = (!empty($session_box['coach']) ? $session_box['coach'].' | ' : '').$session_box['dates'];
2146
                                    $sessionParams[0]['show_actions'] = SessionManager::cantEditSession($session_id);
2147
                                    $sessionParams[0]['courses'] = $html_courses_session;
2148
                                    $sessionParams[0]['show_simple_session_info'] = $showSimpleSessionInfo;
2149
                                    $sessionParams[0]['coach_name'] = !empty($session_box['coach']) ? $session_box['coach'] : null;
2150
                                    $sessionParams[0]['is_old'] = $markAsOld;
2151
                                    $sessionParams[0]['is_future'] = $markAsFuture;
2152
2153
                                    if ($collapsable) {
2154
                                        $collapsableData = SessionManager::getCollapsableData(
2155
                                            $user_id,
2156
                                            $session_id,
2157
                                            $extraFieldValue,
2158
                                            $collapsableLink
2159
                                        );
2160
                                        $sessionParams[0]['collapsable_link'] = $collapsableData['collapsable_link'];
2161
                                        $sessionParams[0]['collapsed'] = $collapsableData['collapsed'];
2162
                                    }
2163
2164
                                    if ($showSimpleSessionInfo) {
2165
                                        $sessionParams[0]['subtitle'] = self::getSimpleSessionDetails(
2166
                                            $session_box['coach'],
2167
                                            $session_box['dates'],
2168
                                            isset($session_box['duration']) ? $session_box['duration'] : null
2169
                                        );
2170
                                    }
2171
2172
                                    $this->tpl->assign('session', $sessionParams);
2173
                                    $this->tpl->assign('show_tutor', api_get_setting('show_session_coach') === 'true');
2174
                                    $this->tpl->assign('gamification_mode', $gameModeIsActive);
2175
                                    $this->tpl->assign(
2176
                                        'remove_session_url',
2177
                                        api_get_configuration_value('remove_session_url')
2178
                                    );
2179
                                    $this->tpl->assign(
2180
                                        'hide_session_dates_in_user_portal',
2181
                                        api_get_configuration_value('hide_session_dates_in_user_portal')
2182
                                    );
2183
2184
                                    if ($viewGridCourses) {
2185
                                        $html_sessions .= $this->tpl->fetch(
2186
                                            $this->tpl->get_template('/user_portal/grid_session.tpl')
2187
                                        );
2188
                                    } else {
2189
                                        $html_sessions .= $this->tpl->fetch(
2190
                                            $this->tpl->get_template('user_portal/classic_session.tpl')
2191
                                        );
2192
                                    }
2193
                                    $sessionCount++;
2194
                                }
2195
                            }
2196
                        }
2197
2198
                        if ($count_courses_session > 0) {
2199
                            $categoryParams = [
2200
                                'id' => $session_category['session_category']['id'],
2201
                                'title' => $session_category['session_category']['name'],
2202
                                'show_actions' => api_is_platform_admin(),
2203
                                'subtitle' => '',
2204
                                'sessions' => $html_sessions,
2205
                            ];
2206
2207
                            $session_category_start_date = $session_category['session_category']['date_start'];
2208
                            $session_category_end_date = $session_category['session_category']['date_end'];
2209
                            if ($session_category_start_date == '0000-00-00') {
2210
                                $session_category_start_date = '';
2211
                            }
2212
2213
                            if ($session_category_end_date == '0000-00-00') {
2214
                                $session_category_end_date = '';
2215
                            }
2216
2217
                            if (!empty($session_category_start_date) &&
2218
                                !empty($session_category_end_date)
2219
                            ) {
2220
                                $categoryParams['subtitle'] = sprintf(
2221
                                    get_lang('FromDateXToDateY'),
2222
                                    $session_category_start_date,
2223
                                    $session_category_end_date
2224
                                );
2225
                            } else {
2226
                                if (!empty($session_category_start_date)) {
2227
                                    $categoryParams['subtitle'] = get_lang('From').' '.$session_category_start_date;
2228
                                }
2229
2230
                                if (!empty($session_category_end_date)) {
2231
                                    $categoryParams['subtitle'] = get_lang('Until').' '.$session_category_end_date;
2232
                                }
2233
                            }
2234
2235
                            $this->tpl->assign('session_category', $categoryParams);
2236
                            $sessions_with_category .= $this->tpl->fetch(
2237
                                $this->tpl->get_template('user_portal/session_category.tpl')
2238
                            );
2239
                        }
2240
                    }
2241
                }
2242
2243
                $allCoursesInSessions = [];
2244
                foreach ($listSession as $currentSession) {
2245
                    $coursesInSessions = $currentSession['courses'];
2246
                    unset($currentSession['courses']);
2247
                    foreach ($coursesInSessions as $coursesInSession) {
2248
                        $coursesInSession['session'] = $currentSession;
2249
                        $allCoursesInSessions[] = $coursesInSession;
2250
                    }
2251
                }
2252
2253
                $this->tpl->assign('all_courses', $allCoursesInSessions);
2254
                $this->tpl->assign('session', $listSession);
2255
                $this->tpl->assign('show_tutor', (api_get_setting('show_session_coach') === 'true' ? true : false));
2256
                $this->tpl->assign('gamification_mode', $gameModeIsActive);
2257
                $this->tpl->assign('remove_session_url', api_get_configuration_value('remove_session_url'));
2258
                $this->tpl->assign(
2259
                    'hide_session_dates_in_user_portal',
2260
                    api_get_configuration_value('hide_session_dates_in_user_portal')
2261
                );
2262
2263
                if ($viewGridCourses) {
2264
                    $sessions_with_no_category = $this->tpl->fetch(
2265
                        $this->tpl->get_template('/user_portal/grid_session.tpl')
2266
                    );
2267
                } else {
2268
                    $sessions_with_no_category = $this->tpl->fetch(
2269
                        $this->tpl->get_template('user_portal/classic_session.tpl')
2270
                    );
2271
                }
2272
            }
2273
        }
2274
2275
        return [
2276
            'courses' => $courseCompleteList,
2277
            'sessions' => $session_categories,
2278
            'html' => trim($specialCourseList.$sessions_with_category.$sessions_with_no_category.$listCourse),
2279
            'session_count' => $sessionCount,
2280
            'course_count' => $courseCount,
2281
        ];
2282
    }
2283
2284
    /**
2285
     * @param $listA
2286
     * @param $listB
2287
     *
2288
     * @return int
2289
     */
2290
    private static function compareByCourse($listA, $listB)
2291
    {
2292
        if ($listA['userCatTitle'] == $listB['userCatTitle']) {
2293
            if ($listA['title'] == $listB['title']) {
2294
                return 0;
2295
            }
2296
2297
            if ($listA['title'] > $listB['title']) {
2298
                return 1;
2299
            }
2300
2301
            return -1;
2302
        }
2303
2304
        if ($listA['userCatTitle'] > $listB['userCatTitle']) {
2305
            return 1;
2306
        }
2307
2308
        return -1;
2309
    }
2310
2311
    /**
2312
     * Generate the HTML code for items when displaying the right-side blocks.
2313
     *
2314
     * @return string
2315
     */
2316
    private static function returnRightBlockItems(array $items)
2317
    {
2318
        $my_account_content = '';
2319
        foreach ($items as $item) {
2320
            if (empty($item['link']) && empty($item['title'])) {
2321
                continue;
2322
            }
2323
2324
            $my_account_content .= '<li class="list-group-item '.(empty($item['class']) ? '' : $item['class']).'">'
2325
                .(empty($item['icon']) ? '' : '<span class="item-icon">'.$item['icon'].'</span>')
2326
                .'<a href="'.$item['link'].'">'.$item['title'].'</a>'
2327
                .'</li>';
2328
        }
2329
2330
        return '<ul class="list-group">'.$my_account_content.'</ul>';
2331
    }
2332
2333
    /**
2334
     * Return HTML code for personal user course category.
2335
     *
2336
     * @param $id
2337
     * @param $title
2338
     *
2339
     * @return string
2340
     */
2341
    private static function getHtmlForUserCategory($id, $title)
2342
    {
2343
        if ($id == 0) {
2344
            return '';
2345
        }
2346
        $icon = Display::return_icon(
2347
            'folder_yellow.png',
2348
            $title,
2349
            ['class' => 'sessionView'],
2350
            ICON_SIZE_LARGE
2351
        );
2352
2353
        return "<div class='session-view-user-category'>$icon<span>$title</span></div>";
2354
    }
2355
2356
    /**
2357
     * return HTML code for course display in session view.
2358
     *
2359
     * @param array $courseInfo
2360
     * @param       $userCategoryId
2361
     * @param bool  $displayButton
2362
     * @param       $loadDirs
2363
     *
2364
     * @return string
2365
     */
2366
    private static function getHtmlForCourse(
2367
        $courseInfo,
2368
        $userCategoryId,
2369
        $displayButton = false,
2370
        $loadDirs
2371
    ) {
2372
        if (empty($courseInfo)) {
2373
            return '';
2374
        }
2375
2376
        $id = $courseInfo['real_id'];
2377
        $title = $courseInfo['title'];
2378
        $code = $courseInfo['code'];
2379
2380
        $class = 'session-view-lvl-6';
2381
        if ($userCategoryId != 0 && !$displayButton) {
2382
            $class = 'session-view-lvl-7';
2383
        }
2384
2385
        $class2 = 'session-view-lvl-6';
2386
        if ($displayButton || $userCategoryId != 0) {
2387
            $class2 = 'session-view-lvl-7';
2388
        }
2389
2390
        $button = '';
2391
        if ($displayButton) {
2392
            $button = '<input id="session-view-button-'.intval(
2393
                    $id
2394
                ).'" class="btn btn-default btn-sm" type="button" onclick="hideUnhide(\'courseblock-'.intval(
2395
                    $id
2396
                ).'\', \'session-view-button-'.intval($id).'\', \'+\', \'-\')" value="+" />';
2397
        }
2398
2399
        $icon = Display::return_icon(
2400
            'blackboard.png',
2401
            $title,
2402
            ['class' => 'sessionView'],
2403
            ICON_SIZE_LARGE
2404
        );
2405
2406
        $courseLink = $courseInfo['course_public_url'].'?id_session=0';
2407
2408
        // get html course params
2409
        $courseParams = CourseManager::getCourseParamsForDisplay($id, $loadDirs);
2410
        $teachers = '';
2411
        $rightActions = '';
2412
2413
        // teacher list
2414
        if (!empty($courseParams['teachers'])) {
2415
            $teachers = '<p class="'.$class2.' view-by-session-teachers">'.$courseParams['teachers'].'</p>';
2416
        }
2417
2418
        // notification
2419
        if (!empty($courseParams['right_actions'])) {
2420
            $rightActions = '<div class="pull-right">'.$courseParams['right_actions'].'</div>';
2421
        }
2422
2423
        $notifications = isset($courseParams['notifications']) ? $courseParams['notifications'] : '';
2424
2425
        return "<div>
2426
                    $button
2427
                    <span class='$class'>$icon
2428
                        <a class='sessionView' href='$courseLink'>$title</a>
2429
                    </span>
2430
                    $notifications
2431
                    $rightActions
2432
                </div>
2433
                $teachers";
2434
    }
2435
2436
    /**
2437
     * return HTML code for session category.
2438
     *
2439
     * @param $id
2440
     * @param $title
2441
     *
2442
     * @return string
2443
     */
2444
    private static function getHtmlSessionCategory($id, $title)
2445
    {
2446
        if ($id == 0) {
2447
            return '';
2448
        }
2449
2450
        $icon = Display::return_icon(
2451
            'folder_blue.png',
2452
            $title,
2453
            ['class' => 'sessionView'],
2454
            ICON_SIZE_LARGE
2455
        );
2456
2457
        return "<div class='session-view-session-category'>
2458
                <span class='session-view-lvl-2'>
2459
                    $icon
2460
                    <span>$title</span>
2461
                </span>
2462
                </div>";
2463
    }
2464
2465
    /**
2466
     * return HTML code for session.
2467
     *
2468
     * @param int    $id                session id
2469
     * @param string $title             session title
2470
     * @param int    $categorySessionId
2471
     * @param array  $courseInfo
2472
     *
2473
     * @return string
2474
     */
2475
    private static function getHtmlForSession($id, $title, $categorySessionId, $courseInfo)
2476
    {
2477
        $html = '';
2478
        if ($categorySessionId == 0) {
2479
            $class1 = 'session-view-lvl-2'; // session
2480
            $class2 = 'session-view-lvl-4'; // got to course in session link
2481
        } else {
2482
            $class1 = 'session-view-lvl-3'; // session
2483
            $class2 = 'session-view-lvl-5'; // got to course in session link
2484
        }
2485
2486
        $icon = Display::return_icon(
2487
            'session.png',
2488
            $title,
2489
            ['class' => 'sessionView'],
2490
            ICON_SIZE_LARGE
2491
        );
2492
        $courseLink = $courseInfo['course_public_url'].'?id_session='.intval($id);
2493
2494
        $html .= "<span class='$class1 session-view-session'>$icon$title</span>";
2495
        $html .= '<div class="'.$class2.' session-view-session-go-to-course-in-session">
2496
                  <a class="" href="'.$courseLink.'">'.get_lang('GoToCourseInsideSession').'</a></div>';
2497
2498
        return '<div>'.$html.'</div>';
2499
    }
2500
2501
    /**
2502
     * Filter the course list by category code.
2503
     *
2504
     * @param array  $courseList   course list
2505
     * @param string $categoryCode
2506
     *
2507
     * @return array
2508
     */
2509
    private static function filterByCategory($courseList, $categoryCode)
2510
    {
2511
        return array_filter(
2512
            $courseList,
2513
            function ($courseInfo) use ($categoryCode) {
2514
                if (isset($courseInfo['category_code']) &&
2515
                    $courseInfo['category_code'] === $categoryCode
2516
                ) {
2517
                    return true;
2518
                }
2519
2520
                return false;
2521
            }
2522
        );
2523
    }
2524
2525
    /**
2526
     * Get the session coach name, duration or dates
2527
     * when $_configuration['show_simple_session_info'] is enabled.
2528
     *
2529
     * @param string      $coachName
2530
     * @param string      $dates
2531
     * @param string|null $duration  Optional
2532
     *
2533
     * @return string
2534
     */
2535
    private static function getSimpleSessionDetails($coachName, $dates, $duration = null)
2536
    {
2537
        $strDetails = [];
2538
        if (!empty($coachName)) {
2539
            $strDetails[] = $coachName;
2540
        }
2541
2542
        $strDetails[] = !empty($duration) ? $duration : $dates;
2543
2544
        return implode(' | ', $strDetails);
2545
    }
2546
}
2547