IndexManager   F
last analyzed

Complexity

Total Complexity 419

Size/Duplication

Total Lines 2668
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 419
eloc 1489
dl 0
loc 2668
rs 0.8
c 0
b 0
f 0

38 Methods

Rating   Name   Duplication   Size   Complexity  
B returnClassesBlock() 0 41 7
A return_user_image_block() 0 24 3
A setDefaultMyCourseView() 0 3 1
A compareListUserCategory() 0 11 3
A __construct() 0 24 2
A return_exercise_block() 0 34 5
A set_login_form() 0 4 1
A logout() 0 4 1
B return_announcements() 0 38 8
A studentPublicationBlock() 0 18 3
A return_help() 0 18 3
A handle_login_failed() 0 3 1
F return_courses_in_categories() 0 271 63
B category_has_open_courses() 0 22 7
A return_notice() 0 13 3
A display_login_form() 0 3 1
C return_home_page() 0 50 14
A showRightBlock() 0 32 4
B returnSkillLinks() 0 56 9
A return_search_block() 0 15 2
A return_hot_courses() 0 3 1
A getSimpleSessionDetails() 0 10 3
A returnRightBlockItems() 0 15 6
F returnCoursesAndSessionsViewBySession() 0 194 24
A return_navigation_links() 0 28 6
A getHtmlForUserCategory() 0 13 2
A getHtmlForSession() 0 24 2
F setGradeBookDependencyBar() 0 132 26
A compareByCourse() 0 19 5
A returnCourseCategoryListFromUser() 0 19 2
A filterByCategory() 0 12 3
F return_profile_block() 0 151 17
B getHtmlForCourse() 0 68 10
A getHtmlSessionCategory() 0 17 2
A return_welcome_to_course_block() 0 15 1
F returnCoursesAndSessions() 0 814 150
A returnPopularCoursesHandPicked() 0 3 1
F return_course_block() 0 133 17

How to fix   Complexity   

Complex Class

Complex classes like IndexManager often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use IndexManager, and based on these observations, apply Extract Interface, too.

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