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

IndexManager::get_courses_of_user()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 45
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

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