Passed
Push — master ( f5688d...87bc65 )
by Julito
09:49
created

IndexManager::returnClassesBlock()   B

Complexity

Conditions 7
Paths 7

Size

Total Lines 41
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 7
eloc 25
nc 7
nop 0
dl 0
loc 41
rs 8.5866
c 1
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_configuration_value('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
        return $items;
892
    }
893
894
    /**
895
     * @return array
896
     */
897
    public function return_navigation_links()
898
    {
899
        $items = [];
900
        // Deleting the myprofile link.
901
        if (api_get_setting('allow_social_tool') == 'true') {
902
            unset($this->tpl->menu_navigation['myprofile']);
903
        }
904
905
        $hideMenu = api_get_configuration_value('hide_main_navigation_menu');
906
        if ($hideMenu === true) {
907
            return '';
908
        }
909
910
        // Main navigation section.
911
        // Tabs that are deactivated are added here.
912
        if (!empty($this->tpl->menu_navigation)) {
913
            foreach ($this->tpl->menu_navigation as $section => $navigation_info) {
914
                $items[] = [
915
                    'icon' => null,
916
                    'link' => $navigation_info['url'],
917
                    'title' => $navigation_info['title'],
918
                ];
919
            }
920
        }
921
922
        return $items;
923
    }
924
925
    /**
926
     * @return array
927
     */
928
    public function return_course_block()
929
    {
930
        $isHrm = api_is_drh();
931
        $show_create_link = false;
932
        $show_course_link = false;
933
        if (api_is_allowed_to_create_course()) {
934
            $show_create_link = true;
935
        }
936
937
        if (api_get_setting('allow_students_to_browse_courses') === 'true') {
938
            $show_course_link = true;
939
        }
940
941
        $items = [];
942
943
        // My account section
944
        if ($show_create_link) {
945
            if (api_get_setting('course_validation') == 'true' && !api_is_platform_admin()) {
946
                $items[] = [
947
                    'class' => 'add-course',
948
                    'icon' => Display::return_icon('new-course.png', get_lang('CreateCourseRequest')),
949
                    'link' => 'main/create_course/add_course.php',
950
                    'title' => get_lang('CreateCourseRequest'),
951
                ];
952
            } else {
953
                $items[] = [
954
                    'class' => 'add-course',
955
                    'icon' => Display::return_icon('new-course.png', get_lang('CourseCreate')),
956
                    'link' => 'main/create_course/add_course.php',
957
                    'title' => get_lang('CourseCreate'),
958
                ];
959
            }
960
961
            if (SessionManager::allowToManageSessions()) {
962
                $items[] = [
963
                    'class' => 'add-session',
964
                    'icon' => Display::return_icon('session.png', get_lang('AddSession')),
965
                    'link' => 'main/session/session_add.php',
966
                    'title' => get_lang('AddSession'),
967
                ];
968
            }
969
        }
970
971
        // Sort courses
972
        $items[] = [
973
            'class' => 'order-course',
974
            'icon' => Display::return_icon('order-course.png', get_lang('SortMyCourses')),
975
            'link' => api_get_path(WEB_CODE_PATH).'auth/courses.php?action=sortmycourses',
976
            'title' => get_lang('SortMyCourses'),
977
        ];
978
979
        // Session history
980
        if (isset($_GET['history']) && intval($_GET['history']) == 1) {
981
            $items[] = [
982
                'class' => 'history-course',
983
                'icon' => Display::return_icon('history-course.png', get_lang('DisplayTrainingList')),
984
                'link' => 'user_portal.php',
985
                'title' => get_lang('DisplayTrainingList'),
986
            ];
987
        } else {
988
            $items[] = [
989
                'class' => 'history-course',
990
                'icon' => Display::return_icon('history-course.png', get_lang('HistoryTrainingSessions')),
991
                'link' => 'user_portal.php?history=1',
992
                'title' => get_lang('HistoryTrainingSessions'),
993
            ];
994
        }
995
996
        if ($isHrm) {
997
            $items[] = [
998
                'link' => api_get_path(WEB_CODE_PATH).'auth/hrm_courses.php',
999
                'title' => get_lang('HrmAssignedUsersCourseList'),
1000
            ];
1001
        }
1002
1003
        // Course catalog
1004
        if ($show_course_link) {
1005
            if (!api_is_drh()) {
1006
                $items[] = [
1007
                    'class' => 'list-course',
1008
                    'icon' => Display::return_icon('catalog-course.png', get_lang('CourseCatalog')),
1009
                    'link' => 'main/auth/courses.php',
1010
                    'title' => get_lang('CourseCatalog'),
1011
                ];
1012
            } else {
1013
                $items[] = [
1014
                    'link' => 'main/dashboard/index.php',
1015
                    'title' => get_lang('Dashboard'),
1016
                ];
1017
            }
1018
        }
1019
1020
        return $items;
1021
    }
1022
1023
    /**
1024
     * Prints the session and course list (user_portal.php).
1025
     *
1026
     * @param int    $user_id
1027
     * @param bool   $showSessions
1028
     * @param string $categoryCodeFilter
1029
     * @param bool   $useUserLanguageFilterIfAvailable
1030
     * @param bool   $loadHistory
1031
     *
1032
     * @return array
1033
     */
1034
    public function returnCoursesAndSessions(
1035
        $user_id,
1036
        $showSessions = true,
1037
        $categoryCodeFilter = '',
1038
        $useUserLanguageFilterIfAvailable = true,
1039
        $loadHistory = false
1040
    ) {
1041
        $gameModeIsActive = api_get_setting('gamification_mode');
1042
        $viewGridCourses = api_get_configuration_value('view_grid_courses') === true;
1043
        $showSimpleSessionInfo = api_get_configuration_value('show_simple_session_info');
1044
        $coursesWithoutCategoryTemplate = '/user_portal/classic_courses_without_category.tpl';
1045
        $coursesWithCategoryTemplate = '/user_portal/classic_courses_with_category.tpl';
1046
        $showAllSessions = api_get_configuration_value('show_all_sessions_on_my_course_page') === true;
1047
1048
        if ($loadHistory) {
1049
            // Load sessions in category in *history*
1050
            $session_categories = UserManager::get_sessions_by_category($user_id, true);
1051
        } else {
1052
            // Load sessions in category
1053
            $session_categories = UserManager::get_sessions_by_category($user_id, false);
1054
        }
1055
1056
        $sessionCount = 0;
1057
        $courseCount = 0;
1058
1059
        // Student info code check (shows student progress information on
1060
        // courses list
1061
        $studentInfo = api_get_configuration_value('course_student_info');
1062
        $viewGrid = api_get_configuration_value('view_grid_courses');
1063
1064
        $studentInfoProgress = !empty($studentInfo['progress']) && $studentInfo['progress'] === true;
1065
        $studentInfoScore = !empty($studentInfo['score']) && $studentInfo['score'] === true;
1066
        $studentInfoCertificate = !empty($studentInfo['certificate']) && $studentInfo['certificate'] === true;
1067
        $courseCompleteList = [];
1068
        $coursesInCategoryCount = 0;
1069
        $coursesNotInCategoryCount = 0;
1070
        $listCourse = '';
1071
        $specialCourseList = '';
1072
1073
        // If we're not in the history view...
1074
        if ($loadHistory == false) {
1075
            // Display special courses.
1076
            $specialCourses = CourseManager::returnSpecialCourses(
1077
                $user_id,
1078
                $this->load_directories_preview,
1079
                $useUserLanguageFilterIfAvailable
1080
            );
1081
1082
            // Display courses.
1083
            $courses = CourseManager::returnCourses(
1084
                $user_id,
1085
                $this->load_directories_preview,
1086
                $useUserLanguageFilterIfAvailable
1087
            );
1088
1089
            // Course option (show student progress)
1090
            // This code will add new variables (Progress, Score, Certificate)
1091
            if ($studentInfoProgress || $studentInfoScore || $studentInfoCertificate) {
1092
                if (!empty($specialCourses)) {
1093
                    foreach ($specialCourses as $key => $specialCourseInfo) {
1094
                        if ($studentInfoProgress) {
1095
                            $progress = Tracking::get_avg_student_progress(
1096
                                $user_id,
1097
                                $specialCourseInfo['course_code']
1098
                            );
1099
                            $specialCourses[$key]['student_info']['progress'] = $progress === false ? null : $progress;
1100
                        }
1101
1102
                        if ($studentInfoScore) {
1103
                            $percentage_score = Tracking::get_avg_student_score(
1104
                                $user_id,
1105
                                $specialCourseInfo['course_code'],
1106
                                []
1107
                            );
1108
                            $specialCourses[$key]['student_info']['score'] = $percentage_score;
1109
                        }
1110
1111
                        if ($studentInfoCertificate) {
1112
                            $category = Category::load(
1113
                                null,
1114
                                null,
1115
                                $specialCourseInfo['course_code'],
1116
                                null,
1117
                                null,
1118
                                null
1119
                            );
1120
                            $specialCourses[$key]['student_info']['certificate'] = null;
1121
                            if (isset($category[0])) {
1122
                                if ($category[0]->is_certificate_available($user_id)) {
1123
                                    $specialCourses[$key]['student_info']['certificate'] = Display::label(
1124
                                        get_lang('Yes'),
1125
                                        'success'
1126
                                    );
1127
                                } else {
1128
                                    $specialCourses[$key]['student_info']['certificate'] = Display::label(
1129
                                        get_lang('No'),
1130
                                        'danger'
1131
                                    );
1132
                                }
1133
                            }
1134
                        }
1135
                    }
1136
                }
1137
1138
                if (isset($courses['in_category'])) {
1139
                    foreach ($courses['in_category'] as $key1 => $value) {
1140
                        if (isset($courses['in_category'][$key1]['courses'])) {
1141
                            foreach ($courses['in_category'][$key1]['courses'] as $key2 => $courseInCatInfo) {
1142
                                if ($studentInfoProgress) {
1143
                                    $progress = Tracking::get_avg_student_progress(
1144
                                        $user_id,
1145
                                        $courseInCatInfo['course_code']
1146
                                    );
1147
                                    $courses['in_category'][$key1]['courses'][$key2]['student_info']['progress'] = $progress === false ? null : $progress;
1148
                                }
1149
1150
                                if ($studentInfoScore) {
1151
                                    $percentage_score = Tracking::get_avg_student_score(
1152
                                        $user_id,
1153
                                        $specialCourseInfo['course_code'],
1154
                                        []
1155
                                    );
1156
                                    $courses['in_category'][$key1]['courses'][$key2]['student_info']['score'] = $percentage_score;
1157
                                }
1158
1159
                                if ($studentInfoCertificate) {
1160
                                    $category = Category::load(
1161
                                        null,
1162
                                        null,
1163
                                        $courseInCatInfo['course_code'],
1164
                                        null,
1165
                                        null,
1166
                                        null
1167
                                    );
1168
                                    $courses['in_category'][$key1]['student_info']['certificate'] = null;
1169
                                    $isCertificateAvailable = $category[0]->is_certificate_available($user_id);
1170
                                    if (isset($category[0])) {
1171
                                        if ($viewGrid) {
1172
                                            if ($isCertificateAvailable) {
1173
                                                $courses['in_category'][$key1]['student_info']['certificate'] = get_lang(
1174
                                                    'Yes'
1175
                                                );
1176
                                            } else {
1177
                                                $courses['in_category'][$key1]['student_info']['certificate'] = get_lang(
1178
                                                    'No'
1179
                                                );
1180
                                            }
1181
                                        } else {
1182
                                            if ($isCertificateAvailable) {
1183
                                                $courses['in_category'][$key1]['student_info']['certificate'] = Display::label(
1184
                                                    get_lang('Yes'),
1185
                                                    'success'
1186
                                                );
1187
                                            } else {
1188
                                                $courses['in_category'][$key1]['student_info']['certificate'] = Display::label(
1189
                                                    get_lang('No'),
1190
                                                    'danger'
1191
                                                );
1192
                                            }
1193
                                        }
1194
                                    }
1195
                                }
1196
                            }
1197
                        }
1198
                    }
1199
                }
1200
1201
                if (isset($courses['not_category'])) {
1202
                    foreach ($courses['not_category'] as $key => $courseNotInCatInfo) {
1203
                        if ($studentInfoProgress) {
1204
                            $progress = Tracking::get_avg_student_progress(
1205
                                $user_id,
1206
                                $courseNotInCatInfo['course_code']
1207
                            );
1208
                            $courses['not_category'][$key]['student_info']['progress'] = $progress === false ? null : $progress;
1209
                        }
1210
1211
                        if ($studentInfoScore) {
1212
                            $percentage_score = Tracking::get_avg_student_score(
1213
                                $user_id,
1214
                                $courseNotInCatInfo['course_code'],
1215
                                []
1216
                            );
1217
                            $courses['not_category'][$key]['student_info']['score'] = $percentage_score;
1218
                        }
1219
1220
                        if ($studentInfoCertificate) {
1221
                            $category = Category::load(
1222
                                null,
1223
                                null,
1224
                                $courseNotInCatInfo['course_code'],
1225
                                null,
1226
                                null,
1227
                                null
1228
                            );
1229
                            $courses['not_category'][$key]['student_info']['certificate'] = null;
1230
1231
                            if (isset($category[0])) {
1232
                                $certificateAvailable = $category[0]->is_certificate_available($user_id);
1233
                                if ($viewGrid) {
1234
                                    if ($certificateAvailable) {
1235
                                        $courses['not_category'][$key]['student_info']['certificate'] = get_lang('Yes');
1236
                                    } else {
1237
                                        $courses['not_category'][$key]['student_info']['certificate'] = get_lang('No');
1238
                                    }
1239
                                } else {
1240
                                    if ($certificateAvailable) {
1241
                                        $courses['not_category'][$key]['student_info']['certificate'] = Display::label(
1242
                                            get_lang('Yes'),
1243
                                            'success'
1244
                                        );
1245
                                    } else {
1246
                                        $courses['not_category'][$key]['student_info']['certificate'] = Display::label(
1247
                                            get_lang('No'),
1248
                                            'danger'
1249
                                        );
1250
                                    }
1251
                                }
1252
                            }
1253
                        }
1254
                    }
1255
                }
1256
            }
1257
1258
            if ($viewGridCourses) {
1259
                $coursesWithoutCategoryTemplate = '/user_portal/grid_courses_without_category.tpl';
1260
                $coursesWithCategoryTemplate = '/user_portal/grid_courses_with_category.tpl';
1261
            }
1262
1263
            if ($specialCourses) {
1264
                if ($categoryCodeFilter) {
1265
                    $specialCourses = self::filterByCategory(
1266
                        $specialCourses,
1267
                        $categoryCodeFilter
1268
                    );
1269
                }
1270
                $this->tpl->assign('courses', $specialCourses);
1271
                $specialCourseList = $this->tpl->fetch(
1272
                    $this->tpl->get_template($coursesWithoutCategoryTemplate)
1273
                );
1274
                $courseCompleteList = array_merge($courseCompleteList, $specialCourses);
1275
            }
1276
1277
            if ($courses['in_category'] || $courses['not_category']) {
1278
                foreach ($courses['in_category'] as $courseData) {
1279
                    if (!empty($courseData['courses'])) {
1280
                        $coursesInCategoryCount += count($courseData['courses']);
1281
                        $courseCompleteList = array_merge($courseCompleteList, $courseData['courses']);
1282
                    }
1283
                }
1284
1285
                $coursesNotInCategoryCount += count($courses['not_category']);
1286
                $courseCompleteList = array_merge($courseCompleteList, $courses['not_category']);
1287
1288
                if ($categoryCodeFilter) {
1289
                    $courses['in_category'] = self::filterByCategory(
1290
                        $courses['in_category'],
1291
                        $categoryCodeFilter
1292
                    );
1293
                    $courses['not_category'] = self::filterByCategory(
1294
                        $courses['not_category'],
1295
                        $categoryCodeFilter
1296
                    );
1297
                }
1298
1299
                $this->tpl->assign('courses', $courses['not_category']);
1300
                $this->tpl->assign('categories', $courses['in_category']);
1301
1302
                $listCourse = $this->tpl->fetch($this->tpl->get_template($coursesWithCategoryTemplate));
1303
                $listCourse .= $this->tpl->fetch($this->tpl->get_template($coursesWithoutCategoryTemplate));
1304
            }
1305
1306
            $courseCount = count($specialCourses) + $coursesInCategoryCount + $coursesNotInCategoryCount;
1307
        }
1308
1309
        $sessions_with_category = '';
1310
        $sessions_with_no_category = '';
1311
        if ($showSessions) {
1312
            $coursesListSessionStyle = api_get_configuration_value('courses_list_session_title_link');
1313
            $coursesListSessionStyle = $coursesListSessionStyle === false ? 1 : $coursesListSessionStyle;
1314
            if (api_is_drh()) {
1315
                $coursesListSessionStyle = 1;
1316
            }
1317
1318
            $portalShowDescription = api_get_setting('show_session_description') === 'true';
1319
1320
            // Declared listSession variable
1321
            $listSession = [];
1322
            // Get timestamp in UTC to compare to DB values (in UTC by convention)
1323
            $session_now = strtotime(api_get_utc_datetime(time()));
1324
            if (is_array($session_categories)) {
1325
                foreach ($session_categories as $session_category) {
1326
                    $session_category_id = $session_category['session_category']['id'];
1327
                    // Sessions and courses that are not in a session category
1328
                    if (empty($session_category_id) &&
1329
                        isset($session_category['sessions'])
1330
                    ) {
1331
                        // Independent sessions
1332
                        foreach ($session_category['sessions'] as $session) {
1333
                            $session_id = $session['session_id'];
1334
1335
                            // Don't show empty sessions.
1336
                            if (count($session['courses']) < 1) {
1337
                                continue;
1338
                            }
1339
1340
                            // Courses inside the current session.
1341
                            $date_session_start = $session['access_start_date'];
1342
                            $date_session_end = $session['access_end_date'];
1343
                            $coachAccessStartDate = $session['coach_access_start_date'];
1344
                            $coachAccessEndDate = $session['coach_access_end_date'];
1345
                            $count_courses_session = 0;
1346
1347
                            // Loop course content
1348
                            $html_courses_session = [];
1349
                            $atLeastOneCourseIsVisible = false;
1350
                            $markAsOld = false;
1351
                            $markAsFuture = false;
1352
1353
                            foreach ($session['courses'] as $course) {
1354
                                $is_coach_course = api_is_coach($session_id, $course['real_id']);
1355
                                $allowed_time = 0;
1356
                                $allowedEndTime = true;
1357
1358
                                if (!empty($date_session_start)) {
1359
                                    if ($is_coach_course) {
1360
                                        $allowed_time = api_strtotime($coachAccessStartDate);
1361
                                    } else {
1362
                                        $allowed_time = api_strtotime($date_session_start);
1363
                                    }
1364
1365
                                    $endSessionToTms = null;
1366
                                    if (!isset($_GET['history'])) {
1367
                                        if (!empty($date_session_end)) {
1368
                                            if ($is_coach_course) {
1369
                                                // if coach end date is empty we use the default end date
1370
                                                if (empty($coachAccessEndDate)) {
1371
                                                    $endSessionToTms = api_strtotime($date_session_end);
1372
                                                    if ($session_now > $endSessionToTms) {
1373
                                                        $allowedEndTime = false;
1374
                                                    }
1375
                                                } else {
1376
                                                    $endSessionToTms = api_strtotime($coachAccessEndDate);
1377
                                                    if ($session_now > $endSessionToTms) {
1378
                                                        $allowedEndTime = false;
1379
                                                    }
1380
                                                }
1381
                                            } else {
1382
                                                $endSessionToTms = api_strtotime($date_session_end);
1383
                                                if ($session_now > $endSessionToTms) {
1384
                                                    $allowedEndTime = false;
1385
                                                }
1386
                                            }
1387
                                        }
1388
                                    }
1389
                                }
1390
1391
                                if ($showAllSessions) {
1392
                                    if ($allowed_time < $session_now && $allowedEndTime === false) {
1393
                                        $markAsOld = true;
1394
                                    }
1395
                                    if ($allowed_time > $session_now && $endSessionToTms > $session_now) {
1396
                                        $markAsFuture = true;
1397
                                    }
1398
                                    $allowedEndTime = true;
1399
                                    $allowed_time = 0;
1400
                                }
1401
1402
                                if ($session_now >= $allowed_time && $allowedEndTime) {
1403
                                    // Read only and accessible.
1404
                                    $atLeastOneCourseIsVisible = true;
1405
                                    if (api_get_setting('hide_courses_in_sessions') === 'false') {
1406
                                        $courseUserHtml = CourseManager::get_logged_user_course_html(
1407
                                            $course,
1408
                                            $session_id,
1409
                                            'session_course_item',
1410
                                            true,
1411
                                            $this->load_directories_preview
1412
                                        );
1413
                                        if (isset($courseUserHtml[1])) {
1414
                                            $course_session = $courseUserHtml[1];
1415
                                            $course_session['skill'] = isset($courseUserHtml['skill']) ? $courseUserHtml['skill'] : '';
1416
1417
                                            // Course option (show student progress)
1418
                                            // This code will add new variables (Progress, Score, Certificate)
1419
                                            if ($studentInfoProgress || $studentInfoScore || $studentInfoCertificate) {
1420
                                                if ($studentInfoProgress) {
1421
                                                    $progress = Tracking::get_avg_student_progress(
1422
                                                        $user_id,
1423
                                                        $course['course_code'],
1424
                                                        [],
1425
                                                        $session_id
1426
                                                    );
1427
                                                    $course_session['student_info']['progress'] = $progress === false ? null : $progress;
1428
                                                }
1429
1430
                                                if ($studentInfoScore) {
1431
                                                    $percentage_score = Tracking::get_avg_student_score(
1432
                                                        $user_id,
1433
                                                        $course['course_code'],
1434
                                                        [],
1435
                                                        $session_id
1436
                                                    );
1437
                                                    $course_session['student_info']['score'] = $percentage_score;
1438
                                                }
1439
1440
                                                if ($studentInfoCertificate) {
1441
                                                    $category = Category::load(
1442
                                                        null,
1443
                                                        null,
1444
                                                        $course['course_code'],
1445
                                                        null,
1446
                                                        null,
1447
                                                        $session_id
1448
                                                    );
1449
                                                    $course_session['student_info']['certificate'] = null;
1450
                                                    if (isset($category[0])) {
1451
                                                        if ($category[0]->is_certificate_available($user_id)) {
1452
                                                            $course_session['student_info']['certificate'] = Display::label(
1453
                                                                get_lang('Yes'),
1454
                                                                'success'
1455
                                                            );
1456
                                                        } else {
1457
                                                            $course_session['student_info']['certificate'] = Display::label(
1458
                                                                get_lang('No')
1459
                                                            );
1460
                                                        }
1461
                                                    }
1462
                                                }
1463
                                            }
1464
                                            $html_courses_session[] = $course_session;
1465
                                        }
1466
                                    }
1467
                                    $count_courses_session++;
1468
                                }
1469
                            }
1470
1471
                            // No courses to show.
1472
                            if ($atLeastOneCourseIsVisible === false) {
1473
                                if (empty($html_courses_session)) {
1474
                                    continue;
1475
                                }
1476
                            }
1477
1478
                            if ($count_courses_session > 0) {
1479
                                $params = [
1480
                                    'id' => $session_id,
1481
                                ];
1482
                                $session_box = Display::getSessionTitleBox($session_id);
1483
                                $coachId = $session_box['id_coach'];
1484
                                $extraFieldValue = new ExtraFieldValue('session');
1485
                                $imageField = $extraFieldValue->get_values_by_handler_and_field_variable(
1486
                                    $session_id,
1487
                                    'image'
1488
                                );
1489
1490
                                $params['category_id'] = $session_box['category_id'];
1491
                                $params['title'] = $session_box['title'];
1492
                                $params['id_coach'] = $coachId;
1493
                                $params['coach_url'] = api_get_path(
1494
                                        WEB_AJAX_PATH
1495
                                    ).'user_manager.ajax.php?a=get_user_popup&user_id='.$coachId;
1496
                                $params['coach_name'] = !empty($session_box['coach']) ? $session_box['coach'] : null;
1497
                                $params['coach_avatar'] = UserManager::getUserPicture(
1498
                                    $coachId,
1499
                                    USER_IMAGE_SIZE_SMALL
1500
                                );
1501
                                $params['date'] = $session_box['dates'];
1502
                                $params['image'] = isset($imageField['value']) ? $imageField['value'] : null;
1503
                                $params['duration'] = isset($session_box['duration']) ? ' '.$session_box['duration'] : null;
1504
                                $params['show_actions'] = SessionManager::cantEditSession($session_id);
1505
                                $params['show_description'] = $session_box['show_description'] == 1 && $portalShowDescription;
1506
                                $params['description'] = $session_box['description'];
1507
                                $params['visibility'] = $session_box['visibility'];
1508
                                $params['show_simple_session_info'] = $showSimpleSessionInfo;
1509
                                $params['course_list_session_style'] = $coursesListSessionStyle;
1510
                                $params['num_users'] = $session_box['num_users'];
1511
                                $params['num_courses'] = $session_box['num_courses'];
1512
                                $params['course_categories'] = CourseManager::getCourseCategoriesFromCourseList(
1513
                                    $html_courses_session
1514
                                );
1515
                                $params['courses'] = $html_courses_session;
1516
                                $params['is_old'] = $markAsOld;
1517
                                $params['is_future'] = $markAsFuture;
1518
1519
                                if ($showSimpleSessionInfo) {
1520
                                    $params['subtitle'] = self::getSimpleSessionDetails(
1521
                                        $session_box['coach'],
1522
                                        $session_box['dates'],
1523
                                        isset($session_box['duration']) ? $session_box['duration'] : null
1524
                                    );
1525
                                }
1526
1527
                                if ($gameModeIsActive) {
1528
                                    $params['stars'] = GamificationUtils::getSessionStars(
1529
                                        $params['id'],
1530
                                        $this->user_id
1531
                                    );
1532
                                    $params['progress'] = GamificationUtils::getSessionProgress(
1533
                                        $params['id'],
1534
                                        $this->user_id
1535
                                    );
1536
                                    $params['points'] = GamificationUtils::getSessionPoints(
1537
                                        $params['id'],
1538
                                        $this->user_id
1539
                                    );
1540
                                }
1541
                                $listSession[] = $params;
1542
                                $sessionCount++;
1543
                            }
1544
                        }
1545
                    } else {
1546
                        // All sessions included in
1547
                        $count_courses_session = 0;
1548
                        $html_sessions = '';
1549
                        if (isset($session_category['sessions'])) {
1550
                            foreach ($session_category['sessions'] as $session) {
1551
                                $session_id = $session['session_id'];
1552
1553
                                // Don't show empty sessions.
1554
                                if (count($session['courses']) < 1) {
1555
                                    continue;
1556
                                }
1557
1558
                                $date_session_start = $session['access_start_date'];
1559
                                $date_session_end = $session['access_end_date'];
1560
                                $coachAccessStartDate = $session['coach_access_start_date'];
1561
                                $coachAccessEndDate = $session['coach_access_end_date'];
1562
                                $html_courses_session = [];
1563
                                $count = 0;
1564
                                $markAsOld = false;
1565
                                $markAsFuture = false;
1566
1567
                                foreach ($session['courses'] as $course) {
1568
                                    $is_coach_course = api_is_coach($session_id, $course['real_id']);
1569
                                    $allowed_time = 0;
1570
                                    $allowedEndTime = true;
1571
1572
                                    if (!empty($date_session_start)) {
1573
                                        if ($is_coach_course) {
1574
                                            $allowed_time = api_strtotime($coachAccessStartDate);
1575
                                        } else {
1576
                                            $allowed_time = api_strtotime($date_session_start);
1577
                                        }
1578
1579
                                        if (!isset($_GET['history'])) {
1580
                                            if (!empty($date_session_end)) {
1581
                                                if ($is_coach_course) {
1582
                                                    // if coach end date is empty we use the default end date
1583
                                                    if (empty($coachAccessEndDate)) {
1584
                                                        $endSessionToTms = api_strtotime($date_session_end);
1585
                                                        if ($session_now > $endSessionToTms) {
1586
                                                            $allowedEndTime = false;
1587
                                                        }
1588
                                                    } else {
1589
                                                        $endSessionToTms = api_strtotime($coachAccessEndDate);
1590
                                                        if ($session_now > $endSessionToTms) {
1591
                                                            $allowedEndTime = false;
1592
                                                        }
1593
                                                    }
1594
                                                } else {
1595
                                                    $endSessionToTms = api_strtotime($date_session_end);
1596
                                                    if ($session_now > $endSessionToTms) {
1597
                                                        $allowedEndTime = false;
1598
                                                    }
1599
                                                }
1600
                                            }
1601
                                        }
1602
                                    }
1603
1604
                                    if ($showAllSessions) {
1605
                                        if ($allowed_time < $session_now && $allowedEndTime == false) {
1606
                                            $markAsOld = true;
1607
                                        }
1608
                                        if ($allowed_time > $session_now && $endSessionToTms > $session_now) {
1609
                                            $markAsFuture = true;
1610
                                        }
1611
                                        $allowedEndTime = true;
1612
                                        $allowed_time = 0;
1613
                                    }
1614
1615
                                    if ($session_now >= $allowed_time && $allowedEndTime) {
1616
                                        if (api_get_setting('hide_courses_in_sessions') === 'false') {
1617
                                            $c = CourseManager::get_logged_user_course_html(
1618
                                                $course,
1619
                                                $session_id,
1620
                                                'session_course_item'
1621
                                            );
1622
                                            if (isset($c[1])) {
1623
                                                $html_courses_session[] = $c[1];
1624
                                            }
1625
                                        }
1626
                                        $count_courses_session++;
1627
                                        $count++;
1628
                                    }
1629
                                }
1630
1631
                                $sessionParams = [];
1632
                                // Category
1633
                                if ($count > 0) {
1634
                                    $session_box = Display::getSessionTitleBox($session_id);
1635
                                    $sessionParams[0]['id'] = $session_id;
1636
                                    $sessionParams[0]['date'] = $session_box['dates'];
1637
                                    $sessionParams[0]['duration'] = isset($session_box['duration']) ? ' '.$session_box['duration'] : null;
1638
                                    $sessionParams[0]['course_list_session_style'] = $coursesListSessionStyle;
1639
                                    $sessionParams[0]['title'] = $session_box['title'];
1640
                                    $sessionParams[0]['subtitle'] = (!empty($session_box['coach']) ? $session_box['coach'].' | ' : '').$session_box['dates'];
1641
                                    $sessionParams[0]['show_actions'] = SessionManager::cantEditSession($session_id);
1642
                                    $sessionParams[0]['courses'] = $html_courses_session;
1643
                                    $sessionParams[0]['show_simple_session_info'] = $showSimpleSessionInfo;
1644
                                    $sessionParams[0]['coach_name'] = !empty($session_box['coach']) ? $session_box['coach'] : null;
1645
                                    $sessionParams[0]['is_old'] = $markAsOld;
1646
                                    $sessionParams[0]['is_future'] = $markAsFuture;
1647
1648
                                    if ($showSimpleSessionInfo) {
1649
                                        $sessionParams[0]['subtitle'] = self::getSimpleSessionDetails(
1650
                                            $session_box['coach'],
1651
                                            $session_box['dates'],
1652
                                            isset($session_box['duration']) ? $session_box['duration'] : null
1653
                                        );
1654
                                    }
1655
1656
                                    $this->tpl->assign('session', $sessionParams);
1657
1658
                                    if ($viewGridCourses) {
1659
                                        $html_sessions .= $this->tpl->fetch(
1660
                                            $this->tpl->get_template('/user_portal/grid_session.tpl')
1661
                                        );
1662
                                    } else {
1663
                                        $html_sessions .= $this->tpl->fetch(
1664
                                            $this->tpl->get_template('user_portal/classic_session.tpl')
1665
                                        );
1666
                                    }
1667
                                    $sessionCount++;
1668
                                }
1669
                            }
1670
                        }
1671
1672
                        if ($count_courses_session > 0) {
1673
                            $categoryParams = [
1674
                                'id' => $session_category['session_category']['id'],
1675
                                'title' => $session_category['session_category']['name'],
1676
                                'show_actions' => api_is_platform_admin(),
1677
                                'subtitle' => '',
1678
                                'sessions' => $html_sessions,
1679
                            ];
1680
1681
                            $session_category_start_date = $session_category['session_category']['date_start'];
1682
                            $session_category_end_date = $session_category['session_category']['date_end'];
1683
                            if ($session_category_start_date == '0000-00-00') {
1684
                                $session_category_start_date = '';
1685
                            }
1686
1687
                            if ($session_category_end_date == '0000-00-00') {
1688
                                $session_category_end_date = '';
1689
                            }
1690
1691
                            if (!empty($session_category_start_date) &&
1692
                                !empty($session_category_end_date)
1693
                            ) {
1694
                                $categoryParams['subtitle'] = sprintf(
1695
                                    get_lang('FromDateXToDateY'),
1696
                                    $session_category_start_date,
1697
                                    $session_category_end_date
1698
                                );
1699
                            } else {
1700
                                if (!empty($session_category_start_date)) {
1701
                                    $categoryParams['subtitle'] = get_lang('From').' '.$session_category_start_date;
1702
                                }
1703
1704
                                if (!empty($session_category_end_date)) {
1705
                                    $categoryParams['subtitle'] = get_lang('Until').' '.$session_category_end_date;
1706
                                }
1707
                            }
1708
1709
                            $this->tpl->assign('session_category', $categoryParams);
1710
                            $sessions_with_category .= $this->tpl->fetch(
1711
                                $this->tpl->get_template('user_portal/session_category.tpl')
1712
                            );
1713
                        }
1714
                    }
1715
                }
1716
1717
                $allCoursesInSessions = [];
1718
                foreach ($listSession as $currentSession) {
1719
                    $coursesInSessions = $currentSession['courses'];
1720
                    unset($currentSession['courses']);
1721
                    foreach ($coursesInSessions as $coursesInSession) {
1722
                        $coursesInSession['session'] = $currentSession;
1723
                        $allCoursesInSessions[] = $coursesInSession;
1724
                    }
1725
                }
1726
1727
                $this->tpl->assign('all_courses', $allCoursesInSessions);
1728
                $this->tpl->assign('session', $listSession);
1729
                $this->tpl->assign('show_tutor', (api_get_setting('show_session_coach') === 'true' ? true : false));
1730
                $this->tpl->assign('gamification_mode', $gameModeIsActive);
1731
                $this->tpl->assign('remove_session_url', api_get_setting('session.remove_session_url'));
1732
1733
                if ($viewGridCourses) {
1734
                    $sessions_with_no_category = $this->tpl->fetch(
1735
                        $this->tpl->get_template('/user_portal/grid_session.tpl')
1736
                    );
1737
                } else {
1738
                    $sessions_with_no_category = $this->tpl->fetch(
1739
                        $this->tpl->get_template('user_portal/classic_session.tpl')
1740
                    );
1741
                }
1742
            }
1743
        }
1744
1745
        return [
1746
            'courses' => $courseCompleteList,
1747
            'sessions' => $session_categories,
1748
            'html' => trim($specialCourseList.$sessions_with_category.$sessions_with_no_category.$listCourse),
1749
            'session_count' => $sessionCount,
1750
            'course_count' => $courseCount,
1751
        ];
1752
    }
1753
1754
    /**
1755
     * Shows a welcome message when the user doesn't have any content in the course list.
1756
     */
1757
    public function return_welcome_to_course_block()
1758
    {
1759
        $count_courses = CourseManager::count_courses();
1760
        $tpl = $this->tpl->get_template('layout/welcome_to_course.tpl');
1761
1762
        $course_catalog_url = api_get_path(WEB_CODE_PATH).'auth/courses.php';
1763
        $course_list_url = api_get_path(WEB_PATH).'user_portal.php';
1764
1765
        $this->tpl->assign('course_catalog_url', $course_catalog_url);
1766
        $this->tpl->assign('course_list_url', $course_list_url);
1767
        $this->tpl->assign('course_catalog_link', Display::url(get_lang('Here'), $course_catalog_url));
1768
        $this->tpl->assign('course_list_link', Display::url(get_lang('Here'), $course_list_url));
1769
        $this->tpl->assign('count_courses', $count_courses);
1770
1771
        return $this->tpl->fetch($tpl);
1772
    }
1773
1774
    /**
1775
     * @return array
1776
     */
1777
    public function return_hot_courses()
1778
    {
1779
        return CourseManager::return_hot_courses(30, 6);
1780
    }
1781
1782
    /**
1783
     * UserPortal view for session, return the HTML of the course list.
1784
     *
1785
     * @param $user_id
1786
     *
1787
     * @return string
1788
     */
1789
    public function returnCoursesAndSessionsViewBySession($user_id)
1790
    {
1791
        $sessionCount = 0;
1792
        $courseCount = 0;
1793
        $load_history = (isset($_GET['history']) && intval($_GET['history']) == 1) ? true : false;
1794
1795
        if ($load_history) {
1796
            // Load sessions in category in *history*
1797
            $session_categories = UserManager::get_sessions_by_category($user_id, true);
1798
        } else {
1799
            // Load sessions in category
1800
            $session_categories = UserManager::get_sessions_by_category($user_id, false);
1801
        }
1802
1803
        $html = '';
1804
        $loadDirs = $this->load_directories_preview;
1805
1806
        // If we're not in the history view...
1807
        $listCoursesInfo = [];
1808
        if (!isset($_GET['history'])) {
1809
            // Display special courses
1810
            $specialCoursesResult = CourseManager::returnSpecialCourses(
1811
                $user_id,
1812
                $loadDirs
1813
            );
1814
            $specialCourses = $specialCoursesResult;
1815
1816
            if ($specialCourses) {
1817
                $this->tpl->assign('courses', $specialCourses);
1818
                $html = $this->tpl->fetch(
1819
                    $this->tpl->get_template('/user_portal/classic_courses_without_category.tpl')
1820
                );
1821
            }
1822
1823
            // Display courses
1824
            // [code=>xxx, real_id=>000]
1825
            $listCourses = CourseManager::get_courses_list_by_user_id(
1826
                $user_id,
1827
                false
1828
            );
1829
1830
            foreach ($listCourses as $i => $listCourseCodeId) {
1831
                if (isset($listCourseCodeId['special_course'])) {
1832
                    continue;
1833
                }
1834
                $courseCategory = CourseManager::getUserCourseCategoryForCourse(
1835
                    $user_id,
1836
                    $listCourseCodeId['real_id']
1837
                );
1838
1839
                $userCatTitle = '';
1840
                $userCategoryId = 0;
1841
                if ($courseCategory) {
1842
                    $userCategoryId = $courseCategory['user_course_cat'];
1843
                    $userCatTitle = $courseCategory['title'];
1844
                }
1845
1846
                $listCourse = api_get_course_info_by_id($listCourseCodeId['real_id']);
1847
                $listCoursesInfo[] = [
1848
                    'course' => $listCourse,
1849
                    'code' => $listCourseCodeId['code'],
1850
                    'id' => $listCourseCodeId['real_id'],
1851
                    'title' => $listCourse['title'],
1852
                    'userCatId' => $userCategoryId,
1853
                    'userCatTitle' => $userCatTitle,
1854
                ];
1855
                $courseCount++;
1856
            }
1857
            usort($listCoursesInfo, 'self::compareByCourse');
1858
        }
1859
1860
        $listCoursesInSession = [];
1861
        if (is_array($session_categories)) {
1862
            // all courses that are in a session
1863
            $listCoursesInSession = SessionManager::getNamedSessionCourseForCoach($user_id);
1864
        }
1865
1866
        // we got all courses
1867
        // for each user category, sorted alphabetically, display courses
1868
        $listUserCategories = CourseManager::get_user_course_categories($user_id);
1869
        $listCoursesAlreadyDisplayed = [];
1870
        uasort($listUserCategories, "self::compareListUserCategory");
1871
        $listUserCategories[0] = '';
1872
1873
        $html .= '<div class="session-view-block">';
1874
        foreach ($listUserCategories as $userCategoryId => $userCat) {
1875
            // add user category
1876
            $userCategoryHtml = '';
1877
            if ($userCategoryId != 0) {
1878
                $userCategoryHtml = '<div class="session-view-well ">';
1879
                $userCategoryHtml .= self::getHtmlForUserCategory($userCategoryId, $userCat['title']);
1880
            }
1881
            // look for course in this userCat in session courses : $listCoursesInSession
1882
            $htmlCategory = '';
1883
            if (isset($listCoursesInSession[$userCategoryId])) {
1884
                // list of courses in this user cat
1885
                foreach ($listCoursesInSession[$userCategoryId]['courseInUserCatList'] as $i => $listCourse) {
1886
                    // add course
1887
                    $listCoursesAlreadyDisplayed[$listCourse['courseId']] = 1;
1888
                    $coursesInfo = $listCourse['course'];
1889
                    $htmlCategory .= self::getHtmlForCourse(
1890
                        $coursesInfo,
1891
                        $userCategoryId,
1892
                        1,
1893
                        $loadDirs
1894
                    );
1895
                    // list of session category
1896
                    $htmlSessionCategory = '<div class="session-view-row" style="display:none;" id="courseblock-'.$coursesInfo['real_id'].'">';
1897
                    foreach ($listCourse['sessionCatList'] as $listCategorySession) {
1898
                        // add session category
1899
                        $htmlSessionCategory .= self::getHtmlSessionCategory(
1900
                            $listCategorySession['catSessionId'],
1901
                            $listCategorySession['catSessionName']
1902
                        );
1903
                        // list of session
1904
                        $htmlSession = ''; // start
1905
                        foreach ($listCategorySession['sessionList'] as $listSession) {
1906
                            // add session
1907
                            $htmlSession .= '<div class="session-view-row">';
1908
                            $htmlSession .= self::getHtmlForSession(
1909
                                $listSession['sessionId'],
1910
                                $listSession['sessionName'],
1911
                                $listCategorySession['catSessionId'],
1912
                                $coursesInfo
1913
                            );
1914
                            $htmlSession .= '</div>';
1915
                            $sessionCount++;
1916
                        }
1917
                        $htmlSession .= ''; // end session block
1918
                        $htmlSessionCategory .= $htmlSession;
1919
                    }
1920
                    $htmlSessionCategory .= '</div>'; // end session cat block
1921
                    $htmlCategory .= Display::panel($htmlSessionCategory, '');
1922
                }
1923
                $userCategoryHtml .= $htmlCategory;
1924
            }
1925
1926
            // look for courses in this userCat in not in session courses : $listCoursesInfo
1927
            // if course not already added
1928
            $htmlCategory = '';
1929
            foreach ($listCoursesInfo as $i => $listCourse) {
1930
                if ($listCourse['userCatId'] == $userCategoryId &&
1931
                    !isset($listCoursesAlreadyDisplayed[$listCourse['id']])
1932
                ) {
1933
                    $body = self::getHtmlForCourse(
1934
                        $listCourse['course'],
1935
                        $userCategoryId,
1936
                        0,
1937
                        $loadDirs
1938
                    );
1939
                    $htmlCategory .= Display::panel($body, '');
1940
                }
1941
            }
1942
            $htmlCategory .= '';
1943
            $userCategoryHtml .= $htmlCategory; // end user cat block
1944
            if ($userCategoryId != 0) {
1945
                $userCategoryHtml .= '</div>';
1946
            }
1947
            $html .= $userCategoryHtml;
1948
        }
1949
        $html .= '</div>';
1950
1951
        return [
1952
            'html' => $html,
1953
            'sessions' => $session_categories,
1954
            'courses' => $listCoursesInfo,
1955
            'session_count' => $sessionCount,
1956
            'course_count' => $courseCount,
1957
        ];
1958
    }
1959
1960
    /**
1961
     * @param $listA
1962
     * @param $listB
1963
     *
1964
     * @return int
1965
     */
1966
    public static function compareListUserCategory($listA, $listB)
1967
    {
1968
        if ($listA['title'] == $listB['title']) {
1969
            return 0;
1970
        }
1971
1972
        if ($listA['title'] > $listB['title']) {
1973
            return 1;
1974
        }
1975
1976
        return -1;
1977
    }
1978
1979
    /**
1980
     * @param $view
1981
     * @param $userId
1982
     */
1983
    public static function setDefaultMyCourseView($view, $userId)
1984
    {
1985
        //setcookie('defaultMyCourseView'.$userId, $view);
1986
    }
1987
1988
    /**
1989
     * @param int $userId
1990
     *
1991
     * @return array
1992
     */
1993
    public function returnCourseCategoryListFromUser($userId)
1994
    {
1995
        $sessionCount = 0;
1996
        $courseList = CourseManager::get_courses_list_by_user_id($userId);
1997
        $categoryCodes = CourseManager::getCourseCategoriesFromCourseList($courseList);
1998
        $categories = [];
1999
        foreach ($categoryCodes as $categoryCode) {
2000
            $categories[] = CourseCategory::getCategory($categoryCode);
2001
        }
2002
2003
        $template = new Template('', false, false, false, true, false, false);
2004
        $layout = $template->get_template('user_portal/course_categories.tpl');
2005
        $template->assign('course_categories', $categories);
2006
2007
        return [
2008
            'courses' => $courseList,
2009
            'html' => $template->fetch($layout),
2010
            'course_count' => count($courseList),
2011
            'session_count' => $sessionCount,
2012
        ];
2013
    }
2014
2015
    /**
2016
     * Set grade book dependency progress bar see BT#13099.
2017
     *
2018
     * @param $userId
2019
     *
2020
     * @return bool
2021
     */
2022
    public function setGradeBookDependencyBar($userId)
2023
    {
2024
        $allow = api_get_configuration_value('gradebook_dependency');
2025
2026
        if (api_is_anonymous()) {
2027
            return false;
2028
        }
2029
2030
        if ($allow) {
2031
            $courseAndSessions = $this->returnCoursesAndSessions(
2032
                $userId,
2033
                false,
2034
                '',
2035
                false,
2036
                false
2037
            );
2038
2039
            $courseList = api_get_configuration_value('gradebook_dependency_mandatory_courses');
2040
            $courseList = isset($courseList['courses']) ? $courseList['courses'] : [];
2041
            $mandatoryCourse = [];
2042
            if (!empty($courseList)) {
2043
                foreach ($courseList as $courseId) {
2044
                    $courseInfo = api_get_course_info_by_id($courseId);
2045
                    $mandatoryCourse[] = $courseInfo['code'];
2046
                }
2047
            }
2048
2049
            // @todo improve calls of course info
2050
            $subscribedCourses = !empty($courseAndSessions['courses']) ? $courseAndSessions['courses'] : [];
2051
            $mainCategoryList = [];
2052
            foreach ($subscribedCourses as $courseInfo) {
2053
                $courseCode = $courseInfo['code'];
2054
                $categories = Category::load(null, null, $courseCode);
2055
                /** @var Category $category */
2056
                $category = !empty($categories[0]) ? $categories[0] : [];
2057
                if (!empty($category)) {
2058
                    $mainCategoryList[] = $category;
2059
                }
2060
            }
2061
2062
            $result20 = 0;
2063
            $result80 = 0;
2064
            $countCoursesPassedNoDependency = 0;
2065
            /** @var Category $category */
2066
            foreach ($mainCategoryList as $category) {
2067
                $userFinished = Category::userFinishedCourse(
2068
                    $userId,
2069
                    $category,
2070
                    true
2071
                );
2072
2073
                if ($userFinished) {
2074
                    if (in_array($category->get_course_code(), $mandatoryCourse)) {
2075
                        if ($result20 < 20) {
2076
                            $result20 += 10;
2077
                        }
2078
                    } else {
2079
                        $countCoursesPassedNoDependency++;
2080
                        if ($result80 < 80) {
2081
                            $result80 += 10;
2082
                        }
2083
                    }
2084
                }
2085
            }
2086
2087
            $finalResult = $result20 + $result80;
2088
2089
            $gradeBookList = api_get_configuration_value('gradebook_badge_sidebar');
2090
            $gradeBookList = isset($gradeBookList['gradebooks']) ? $gradeBookList['gradebooks'] : [];
2091
            $badgeList = [];
2092
            foreach ($gradeBookList as $id) {
2093
                $categories = Category::load($id);
2094
                /** @var Category $category */
2095
                $category = !empty($categories[0]) ? $categories[0] : [];
2096
                $badgeList[$id]['name'] = $category->get_name();
2097
                $badgeList[$id]['finished'] = false;
2098
                $badgeList[$id]['skills'] = [];
2099
                if (!empty($category)) {
2100
                    $minToValidate = $category->getMinimumToValidate();
2101
                    $dependencies = $category->getCourseListDependency();
2102
                    $gradeBooksToValidateInDependence = $category->getGradeBooksToValidateInDependence();
2103
                    $countDependenciesPassed = 0;
2104
                    foreach ($dependencies as $courseId) {
2105
                        $courseInfo = api_get_course_info_by_id($courseId);
2106
                        $courseCode = $courseInfo['code'];
2107
                        $categories = Category::load(null, null, $courseCode);
2108
                        $subCategory = !empty($categories[0]) ? $categories[0] : null;
2109
                        if (!empty($subCategory)) {
2110
                            $score = Category::userFinishedCourse(
2111
                                $userId,
2112
                                $subCategory,
2113
                                true
2114
                            );
2115
                            if ($score) {
2116
                                $countDependenciesPassed++;
2117
                            }
2118
                        }
2119
                    }
2120
2121
                    $userFinished =
2122
                        $countDependenciesPassed >= $gradeBooksToValidateInDependence &&
2123
                        $countCoursesPassedNoDependency >= $minToValidate;
2124
2125
                    if ($userFinished) {
2126
                        $badgeList[$id]['finished'] = true;
2127
                    }
2128
2129
                    $objSkill = new Skill();
2130
                    $skills = $category->get_skills();
2131
                    $skillList = [];
2132
                    foreach ($skills as $skill) {
2133
                        $skillList[] = $objSkill->get($skill['id']);
2134
                    }
2135
                    $badgeList[$id]['skills'] = $skillList;
2136
                }
2137
            }
2138
2139
            $this->tpl->assign(
2140
                'grade_book_sidebar',
2141
                true
2142
            );
2143
2144
            $this->tpl->assign(
2145
                'grade_book_progress',
2146
                $finalResult
2147
            );
2148
            $this->tpl->assign('grade_book_badge_list', $badgeList);
2149
2150
            return true;
2151
        }
2152
2153
        return false;
2154
    }
2155
2156
    /**
2157
     * Generate the HTML code for items when displaying the right-side blocks.
2158
     *
2159
     * @param array $items
2160
     *
2161
     * @return string
2162
     */
2163
    private static function returnRightBlockItems(array $items)
2164
    {
2165
        $my_account_content = '';
2166
        foreach ($items as $item) {
2167
            if (empty($item['link']) && empty($item['title'])) {
2168
                continue;
2169
            }
2170
2171
            $my_account_content .= '<li class="list-group-item '.(empty($item['class']) ? '' : $item['class']).'">'
2172
                .(empty($item['icon']) ? '' : '<span class="item-icon">'.$item['icon'].'</span>')
2173
                .'<a href="'.$item['link'].'">'.$item['title'].'</a>'
2174
                .'</li>';
2175
        }
2176
2177
        return '<ul class="list-group">'.$my_account_content.'</ul>';
2178
    }
2179
2180
    /**
2181
     * Return HTML code for personal user course category.
2182
     *
2183
     * @param $id
2184
     * @param $title
2185
     *
2186
     * @return string
2187
     */
2188
    private static function getHtmlForUserCategory($id, $title)
2189
    {
2190
        if ($id == 0) {
2191
            return '';
2192
        }
2193
        $icon = Display::return_icon(
2194
            'folder_yellow.png',
2195
            $title,
2196
            ['class' => 'sessionView'],
2197
            ICON_SIZE_LARGE
2198
        );
2199
2200
        return "<div class='session-view-user-category'>$icon<span>$title</span></div>";
2201
    }
2202
2203
    /**
2204
     * return HTML code for course display in session view.
2205
     *
2206
     * @param array $courseInfo
2207
     * @param $userCategoryId
2208
     * @param bool $displayButton
2209
     * @param $loadDirs
2210
     *
2211
     * @return string
2212
     */
2213
    private static function getHtmlForCourse(
2214
        $courseInfo,
2215
        $userCategoryId,
2216
        $displayButton = false,
2217
        $loadDirs
2218
    ) {
2219
        if (empty($courseInfo)) {
2220
            return '';
2221
        }
2222
2223
        $id = $courseInfo['real_id'];
2224
        $title = $courseInfo['title'];
2225
        $code = $courseInfo['code'];
2226
2227
        $class = 'session-view-lvl-6';
2228
        if ($userCategoryId != 0 && !$displayButton) {
2229
            $class = 'session-view-lvl-7';
2230
        }
2231
2232
        $class2 = 'session-view-lvl-6';
2233
        if ($displayButton || $userCategoryId != 0) {
2234
            $class2 = 'session-view-lvl-7';
2235
        }
2236
2237
        $button = '';
2238
        if ($displayButton) {
2239
            $button = '<input id="session-view-button-'.intval(
2240
                    $id
2241
                ).'" class="btn btn-default btn-sm" type="button" onclick="hideUnhide(\'courseblock-'.intval(
2242
                    $id
2243
                ).'\', \'session-view-button-'.intval($id).'\', \'+\', \'-\')" value="+" />';
2244
        }
2245
2246
        $icon = Display::return_icon(
2247
            'blackboard.png',
2248
            $title,
2249
            ['class' => 'sessionView'],
2250
            ICON_SIZE_LARGE
2251
        );
2252
2253
        $courseLink = $courseInfo['course_public_url'].'?id_session=0';
2254
2255
        // get html course params
2256
        $courseParams = CourseManager::getCourseParamsForDisplay($id, $loadDirs);
2257
        $teachers = '';
2258
        $rightActions = '';
2259
2260
        // teacher list
2261
        if (!empty($courseParams['teachers'])) {
2262
            $teachers = '<p class="'.$class2.' view-by-session-teachers">'.$courseParams['teachers'].'</p>';
2263
        }
2264
2265
        // notification
2266
        if (!empty($courseParams['right_actions'])) {
2267
            $rightActions = '<div class="pull-right">'.$courseParams['right_actions'].'</div>';
2268
        }
2269
2270
        $notifications = isset($courseParams['notifications']) ? $courseParams['notifications'] : '';
2271
2272
        return "<div>
2273
                    $button
2274
                    <span class='$class'>$icon
2275
                        <a class='sessionView' href='$courseLink'>$title</a>
2276
                    </span> 
2277
                    $notifications 
2278
                    $rightActions 
2279
                </div>
2280
                $teachers";
2281
    }
2282
2283
    /**
2284
     * return HTML code for session category.
2285
     *
2286
     * @param $id
2287
     * @param $title
2288
     *
2289
     * @return string
2290
     */
2291
    private static function getHtmlSessionCategory($id, $title)
2292
    {
2293
        if ($id == 0) {
2294
            return '';
2295
        }
2296
2297
        $icon = Display::return_icon(
2298
            'folder_blue.png',
2299
            $title,
2300
            ['class' => 'sessionView'],
2301
            ICON_SIZE_LARGE
2302
        );
2303
2304
        return "<div class='session-view-session-category'>
2305
                <span class='session-view-lvl-2'>
2306
                    $icon
2307
                    <span>$title</span>
2308
                </span>
2309
                </div>";
2310
    }
2311
2312
    /**
2313
     * return HTML code for session.
2314
     *
2315
     * @param int    $id                session id
2316
     * @param string $title             session title
2317
     * @param int    $categorySessionId
2318
     * @param array  $courseInfo
2319
     *
2320
     * @return string
2321
     */
2322
    private static function getHtmlForSession($id, $title, $categorySessionId, $courseInfo)
2323
    {
2324
        $html = '';
2325
        if ($categorySessionId == 0) {
2326
            $class1 = 'session-view-lvl-2'; // session
2327
            $class2 = 'session-view-lvl-4'; // got to course in session link
2328
        } else {
2329
            $class1 = 'session-view-lvl-3'; // session
2330
            $class2 = 'session-view-lvl-5'; // got to course in session link
2331
        }
2332
2333
        $icon = Display::return_icon(
2334
            'blackboard_blue.png',
2335
            $title,
2336
            ['class' => 'sessionView'],
2337
            ICON_SIZE_LARGE
2338
        );
2339
        $courseLink = $courseInfo['course_public_url'].'?id_session='.intval($id);
2340
2341
        $html .= "<span class='$class1 session-view-session'>$icon$title</span>";
2342
        $html .= '<div class="'.$class2.' session-view-session-go-to-course-in-session">
2343
                  <a class="" href="'.$courseLink.'">'.get_lang('GoToCourseInsideSession').'</a></div>';
2344
2345
        return '<div>'.$html.'</div>';
2346
    }
2347
2348
    /**
2349
     * @param $listA
2350
     * @param $listB
2351
     *
2352
     * @return int
2353
     */
2354
    private static function compareByCourse($listA, $listB)
2355
    {
2356
        if ($listA['userCatTitle'] == $listB['userCatTitle']) {
2357
            if ($listA['title'] == $listB['title']) {
2358
                return 0;
2359
            }
2360
2361
            if ($listA['title'] > $listB['title']) {
2362
                return 1;
2363
            }
2364
2365
            return -1;
2366
        }
2367
2368
        if ($listA['userCatTitle'] > $listB['userCatTitle']) {
2369
            return 1;
2370
        }
2371
2372
        return -1;
2373
    }
2374
2375
    /**
2376
     * Get the session coach name, duration or dates
2377
     * when $_configuration['show_simple_session_info'] is enabled.
2378
     *
2379
     * @param string      $coachName
2380
     * @param string      $dates
2381
     * @param string|null $duration  Optional
2382
     *
2383
     * @return string
2384
     */
2385
    private static function getSimpleSessionDetails($coachName, $dates, $duration = null)
2386
    {
2387
        $strDetails = [];
2388
        if (!empty($coachName)) {
2389
            $strDetails[] = $coachName;
2390
        }
2391
2392
        $strDetails[] = !empty($duration) ? $duration : $dates;
2393
2394
        return implode(' | ', $strDetails);
2395
    }
2396
2397
    /**
2398
     * Filter the course list by category code.
2399
     *
2400
     * @param array  $courseList   course list
2401
     * @param string $categoryCode
2402
     *
2403
     * @return array
2404
     */
2405
    private static function filterByCategory($courseList, $categoryCode)
2406
    {
2407
        return array_filter(
2408
            $courseList,
2409
            function ($courseInfo) use ($categoryCode) {
2410
                if (isset($courseInfo['category_code']) &&
2411
                    $courseInfo['category_code'] === $categoryCode
2412
                ) {
2413
                    return true;
2414
                }
2415
2416
                return false;
2417
            }
2418
        );
2419
    }
2420
}
2421