Passed
Push — master ( 0c074a...115052 )
by Julito
10:13 queued 12s
created

IndexManager::get_courses_of_user()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 45
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 23
nc 2
nop 1
dl 0
loc 45
rs 9.552
c 0
b 0
f 0
1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
/**
6
 * Class IndexManager.
7
 */
8
class IndexManager
9
{
10
    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 ('true' === api_get_setting('show_documents_preview')) {
49
            $this->load_directories_preview = true;
50
        }
51
    }
52
53
    /**
54
     * @param array $personal_course_list
55
     */
56
    public function return_exercise_block($personal_course_list)
57
    {
58
        throw new Exception('return_exercise_block');
59
        /*$exercise_list = [];
60
        if (!empty($personal_course_list)) {
61
            foreach ($personal_course_list as $course_item) {
62
                $course_code = $course_item['c'];
63
                $session_id = $course_item['id_session'];
64
65
                $exercises = ExerciseLib::get_exercises_to_be_taken(
66
                    $course_code,
67
                    $session_id
68
                );
69
70
                foreach ($exercises as $exercise_item) {
71
                    $exercise_item['course_code'] = $course_code;
72
                    $exercise_item['session_id'] = $session_id;
73
                    $exercise_item['tms'] = api_strtotime($exercise_item['end_time'], 'UTC');
74
75
                    $exercise_list[] = $exercise_item;
76
                }
77
            }
78
            if (!empty($exercise_list)) {
79
                $exercise_list = msort($exercise_list, 'tms');
80
                $my_exercise = $exercise_list[0];
81
                $url = Display::url(
82
                    $my_exercise['title'],
83
                    api_get_path(
84
                        WEB_CODE_PATH
85
                    ).'exercise/overview.php?exerciseId='.$my_exercise['id'].'&cid='.$my_exercise['course_code'].'&sid='.$my_exercise['session_id']
86
                );
87
                $this->tpl->assign('exercise_url', $url);
88
                $this->tpl->assign(
89
                    'exercise_end_date',
90
                    api_convert_and_format_date($my_exercise['end_time'], DATE_FORMAT_SHORT)
91
                );
92
            }
93
        }*/
94
    }
95
96
    /**
97
     * Alias for the online_logout() function.
98
     *
99
     * @param bool  $redirect   Whether to ask online_logout to redirect to index.php or not
100
     * @param array $logoutInfo Information stored by local.inc.php before new context ['uid'=> x, 'cid'=>y, 'sid'=>z]
101
     */
102
    public function logout($redirect = true, $logoutInfo = [])
103
    {
104
        online_logout($this->user_id, true);
105
        Event::courseLogout($logoutInfo);
106
    }
107
108
    /**
109
     * This function checks if there are courses that are open to the world in the platform course categories (=faculties).
110
     *
111
     * @param string $category
112
     *
113
     * @return bool
114
     */
115
    public function category_has_open_courses($category)
116
    {
117
        $setting_show_also_closed_courses = 'true' == api_get_setting('show_closed_courses');
118
        $main_course_table = Database::get_main_table(TABLE_MAIN_COURSE);
119
        $tblCourseCategory = Database::get_main_table(TABLE_MAIN_CATEGORY);
120
        $category = Database::escape_string($category);
121
        $sql_query = "SELECT course.*, course_category.code AS category_code
122
            FROM $main_course_table course
123
            INNER JOIN $tblCourseCategory course_category ON course.category_id = course_category.id
124
            WHERE course_category.code ='$category'";
125
        $sql_result = Database::query($sql_query);
126
        while ($course = Database::fetch_array($sql_result)) {
127
            if (!$setting_show_also_closed_courses) {
128
                if ((api_get_user_id() > 0 && COURSE_VISIBILITY_OPEN_PLATFORM == $course['visibility']) ||
129
                    (COURSE_VISIBILITY_OPEN_WORLD == $course['visibility'])
130
                ) {
131
                    return true; //at least one open course
132
                }
133
            } else {
134
                if (isset($course['visibility'])) {
135
                    return true; // At least one course (it does not matter weither it's open or not because $setting_show_also_closed_courses = true).
136
                }
137
            }
138
        }
139
140
        return false;
141
    }
142
143
    /**
144
     * Includes a created page.
145
     *
146
     * @param bool $getIncludedFile Whether to include a file as provided in URL GET or simply the homepage
147
     *
148
     * @return string
149
     */
150
    public function return_home_page($getIncludedFile = false)
151
    {
152
        return '';
153
        $userId = api_get_user_id();
0 ignored issues
show
Unused Code introduced by
$userId = api_get_user_id() is not reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

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