Passed
Push — master ( e5e421...58a83e )
by Julito
12:06
created

IndexManager::return_help()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 18
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

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