Completed
Push — master ( 27e209...a08afa )
by Julito
186:04 queued 150:53
created

IndexManager::return_help()   B

Complexity

Conditions 3
Paths 4

Size

Total Lines 28
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 18
nc 4
nop 0
dl 0
loc 28
rs 8.8571
c 0
b 0
f 0
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
/**
5
 * Class IndexManager
6
 */
7
class IndexManager
8
{
9
    const VIEW_BY_DEFAULT = 0;
10
    const VIEW_BY_SESSION = 1;
11
12
    // An instance of the template engine
13
    // No need to initialize because IndexManager is not static,
14
    // and the constructor immediately instantiates a Template
15
    public $tpl;
16
    public $name = '';
17
    public $home = '';
18
    public $default_home = 'home/';
19
20
    /**
21
     * Construct
22
     * @param string $title
23
     */
24
    public function __construct($title)
25
    {
26
        $this->tpl = new Template($title);
27
        $this->home = api_get_home_path();
28
        $this->user_id = api_get_user_id();
0 ignored issues
show
Bug Best Practice introduced by
The property user_id does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
29
        $this->load_directories_preview = false;
0 ignored issues
show
Bug Best Practice introduced by
The property load_directories_preview does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
30
31
        // Load footer plugins systematically
32
        /*$config = api_get_settings_params(array('subkey = ? ' => 'customfooter', ' AND category = ? ' => 'Plugins'));
33
        if (!empty($config)) {
34
            foreach ($config as $fooid => $configrecord) {
35
                $canonic = preg_replace('/^customfooter_/', '', $configrecord['variable']);
36
                $footerconfig->$canonic = $configrecord['selected_value'];
37
            }
38
            if (!empty($footerconfig->footer_left)) {
39
                $this->tpl->assign('plugin_footer_left', $footerconfig->footer_left);
40
            }
41
            if (!empty($footerconfig->footer_right)) {
42
                $this->tpl->assign('plugin_footer_right', $footerconfig->footer_right);
43
            }
44
        }*/
45
46
        if (api_get_setting('show_documents_preview') === 'true') {
47
            $this->load_directories_preview = true;
48
        }
49
    }
50
51
    /**
52
     * @param bool $setLoginForm
53
     */
54
    public function set_login_form($setLoginForm = true)
55
    {
56
        global $loginFailed;
57
        $this->tpl->setLoginForm($setLoginForm);
58
    }
59
60
    /**
61
     * @param array $personal_course_list
62
     */
63
    public function return_exercise_block($personal_course_list)
64
    {
65
        $exercise_list = [];
66
        if (!empty($personal_course_list)) {
67
            foreach ($personal_course_list as $course_item) {
68
                $course_code = $course_item['c'];
69
                $session_id = $course_item['id_session'];
70
71
                $exercises = ExerciseLib::get_exercises_to_be_taken(
72
                    $course_code,
73
                    $session_id
74
                );
75
76
                foreach ($exercises as $exercise_item) {
77
                    $exercise_item['course_code'] = $course_code;
78
                    $exercise_item['session_id'] = $session_id;
79
                    $exercise_item['tms'] = api_strtotime($exercise_item['end_time'], 'UTC');
80
81
                    $exercise_list[] = $exercise_item;
82
                }
83
            }
84
            if (!empty($exercise_list)) {
85
                $exercise_list = msort($exercise_list, 'tms');
86
                $my_exercise = $exercise_list[0];
87
                $url = Display::url(
88
                    $my_exercise['title'],
89
                    api_get_path(WEB_CODE_PATH).'exercise/overview.php?exerciseId='.$my_exercise['id'].'&cidReq='.$my_exercise['course_code'].'&id_session='.$my_exercise['session_id']
90
                );
91
                $this->tpl->assign('exercise_url', $url);
92
                $this->tpl->assign(
93
                    'exercise_end_date',
94
                    api_convert_and_format_date($my_exercise['end_time'], DATE_FORMAT_SHORT)
95
                );
96
            }
97
        }
98
    }
99
100
    /**
101
     * @param bool $show_slide
102
     * @return null|string
103
     */
104
    public function return_announcements($show_slide = true)
105
    {
106
        $hideAnnouncements = api_get_setting('hide_global_announcements_when_not_connected');
107
        $currentUserId = api_get_user_id();
108
        if ($hideAnnouncements == 'true' && empty($currentUserId)) {
109
            return null;
110
        }
111
        $announcement = isset($_GET['announcement']) ? $_GET['announcement'] : null;
112
        $announcement = intval($announcement);
113
114
        if (!api_is_anonymous() && $this->user_id) {
115
            $visibility = SystemAnnouncementManager::getCurrentUserVisibility();
116
            if ($show_slide) {
117
                $announcements = SystemAnnouncementManager::displayAnnouncementsSlider(
118
                    $visibility,
119
                    $announcement
120
                );
121
            } else {
122
                $announcements = SystemAnnouncementManager::displayAllAnnouncements(
123
                    $visibility,
124
                    $announcement
125
                );
126
            }
127
        } else {
128
            if ($show_slide) {
129
                $announcements = SystemAnnouncementManager::displayAnnouncementsSlider(
130
                    SystemAnnouncementManager::VISIBLE_GUEST,
131
                    $announcement
132
                );
133
            } else {
134
                $announcements = SystemAnnouncementManager::displayAllAnnouncements(
135
                    SystemAnnouncementManager::VISIBLE_GUEST,
136
                    $announcement
137
                );
138
            }
139
        }
140
141
        return $announcements;
142
    }
143
144
    /**
145
     * Alias for the online_logout() function
146
     * @param bool $redirect Whether to ask online_logout to redirect to index.php or not
147
     * @param array $logoutInfo Information stored by local.inc.php before new context ['uid'=> x, 'cid'=>y, 'sid'=>z]
148
     */
149
    public function logout($redirect = true, $logoutInfo = [])
0 ignored issues
show
Unused Code introduced by
The parameter $redirect is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

149
    public function logout(/** @scrutinizer ignore-unused */ $redirect = true, $logoutInfo = [])

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
150
    {
151
        online_logout($this->user_id, true);
152
        Event::courseLogout($logoutInfo);
153
    }
154
155
    /**
156
     * This function checks if there are courses that are open to the world in the platform course categories (=faculties)
157
     *
158
     * @param string $category
159
     * @return boolean
160
     */
161
    public function category_has_open_courses($category)
162
    {
163
        $setting_show_also_closed_courses = api_get_setting('show_closed_courses') == 'true';
164
        $main_course_table = Database::get_main_table(TABLE_MAIN_COURSE);
165
        $category = Database::escape_string($category);
166
        $sql_query = "SELECT * FROM $main_course_table WHERE category_code='$category'";
167
        $sql_result = Database::query($sql_query);
168
        while ($course = Database::fetch_array($sql_result)) {
169
            if (!$setting_show_also_closed_courses) {
170
                if ((api_get_user_id() > 0 && $course['visibility'] == COURSE_VISIBILITY_OPEN_PLATFORM) ||
171
                    ($course['visibility'] == COURSE_VISIBILITY_OPEN_WORLD)
172
                ) {
173
                    return true; //at least one open course
174
                }
175
            } else {
176
                if (isset($course['visibility'])) {
177
                    return true; // At least one course (it does not matter weither it's open or not because $setting_show_also_closed_courses = true).
178
                }
179
            }
180
        }
181
182
        return false;
183
    }
184
185
    /**
186
     * @return null|string
187
     */
188
    public function return_teacher_link()
189
    {
190
        $html = '';
191
        $show_menu = false;
192
        if (!empty($this->user_id)) {
193
            // tabs that are deactivated are added here
194
195
            $show_menu = false;
196
            $show_create_link = false;
197
            $show_course_link = false;
198
199
            if (api_is_allowed_to_create_course()) {
200
                $show_menu = true;
201
                $show_course_link = true;
202
                $show_create_link = true;
203
            } else {
204
                if (api_get_setting('allow_students_to_browse_courses') === 'true') {
205
                    $show_menu = true;
206
                    $show_course_link = true;
207
                }
208
209
                if (api_is_allowed_to_create_course()) {
210
                    $show_create_link = true;
211
                }
212
            }
213
214
            if ($show_menu && ($show_create_link || $show_course_link)) {
215
                $show_menu = true;
216
            } else {
217
                $show_menu = false;
218
            }
219
        }
220
221
        // My Account section
222
        if ($show_menu) {
223
            $html .= '<ul class="nav nav-pills nav-stacked">';
224
            if ($show_create_link) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $show_create_link does not seem to be defined for all execution paths leading up to this point.
Loading history...
225
                $html .= '<li class="add-course"><a href="'.api_get_path(WEB_CODE_PATH).'create_course/add_course.php">'
226
                    .Display::return_icon('new-course.png', get_lang('CourseCreate'))
227
                    .(api_get_setting('course_validation') == 'true' ? get_lang('CreateCourseRequest') : get_lang('CourseCreate'))
228
                    .'</a></li>';
229
            }
230
231
            if ($show_course_link) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $show_course_link does not seem to be defined for all execution paths leading up to this point.
Loading history...
232
                if (!api_is_drh() && !api_is_session_admin()) {
233
                    $html .= '<li class="list-course"><a href="'.api_get_path(WEB_CODE_PATH).'auth/courses.php">'
234
                        .Display::return_icon('catalog-course.png', get_lang('CourseCatalog'))
235
                        .get_lang('CourseCatalog')
236
                        .'</a></li>';
237
                } else {
238
                    $html .= '<li><a href="'.api_get_path(WEB_CODE_PATH).'dashboard/index.php">'.get_lang('Dashboard').'</a></li>';
239
                }
240
            }
241
            $html .= '</ul>';
242
        }
243
244
        if (!empty($html)) {
245
            $html = self::show_right_block(
246
                get_lang('Courses'),
247
                $html,
248
                'teacher_block',
249
                null,
250
                'teachers',
251
                'teachersCollapse'
252
            );
253
        }
254
255
        return $html;
256
    }
257
258
    /**
259
     * Includes a created page
260
     * @return string
261
     */
262
    public function return_home_page()
263
    {
264
        $userId = api_get_user_id();
265
        // Including the page for the news
266
        $html = '';
267
        if (!empty($_GET['include']) && preg_match('/^[a-zA-Z0-9_-]*\.html$/', $_GET['include'])) {
268
            $open = @(string) file_get_contents($this->home.$_GET['include']);
269
            $html = api_to_system_encoding($open, api_detect_encoding(strip_tags($open)));
270
        } else {
271
            // Hiding home top when user not connected.
272
            $hideTop = api_get_setting('hide_home_top_when_connected');
273
            if ($hideTop == 'true' && !empty($userId)) {
274
                return $html;
275
            }
276
277
            if (!empty($_SESSION['user_language_choice'])) {
278
                $user_selected_language = $_SESSION['user_language_choice'];
279
            } elseif (!empty($_SESSION['_user']['language'])) {
280
                $user_selected_language = $_SESSION['_user']['language'];
281
            } else {
282
                $user_selected_language = api_get_setting('platformLanguage');
283
            }
284
285
            $home_top_temp = '';
286
            // Try language specific home
287
            if (file_exists($this->home.'home_top_'.$user_selected_language.'.html')) {
288
                $home_top_temp = file_get_contents($this->home.'home_top_'.$user_selected_language.'.html');
289
            }
290
291
            // Try default language home
292
            if (empty($home_top_temp)) {
293
                if (file_exists($this->home.'home_top.html')) {
294
                    $home_top_temp = file_get_contents($this->home.'home_top.html');
295
                } else {
296
                    if (file_exists($this->default_home.'home_top.html')) {
297
                        $home_top_temp = file_get_contents($this->default_home.'home_top.html');
298
                    }
299
                }
300
            }
301
302
            if (trim($home_top_temp) == '' && api_is_platform_admin()) {
303
                $home_top_temp = '<div class="welcome-mascot">'.get_lang('PortalHomepageDefaultIntroduction').'</div>';
304
            } else {
305
                $home_top_temp = '<div class="welcome-home-top-temp">'.$home_top_temp.'</div>';
306
            }
307
            $open = str_replace('{rel_path}', api_get_path(REL_PATH), $home_top_temp);
308
            $html = api_to_system_encoding($open, api_detect_encoding(strip_tags($open)));
309
        }
310
311
        return $html;
312
    }
313
314
    /**
315
     * @return string
316
     */
317
    public function return_notice()
318
    {
319
        $user_selected_language = api_get_interface_language();
320
        $html = '';
321
        // Notice
322
        $home_notice = @(string) file_get_contents($this->home.'home_notice_'.$user_selected_language.'.html');
323
        if (empty($home_notice)) {
324
            $home_notice = @(string) file_get_contents($this->home.'home_notice.html');
325
        }
326
        if (!empty($home_notice)) {
327
            $home_notice = api_to_system_encoding($home_notice, api_detect_encoding(strip_tags($home_notice)));
328
            $html = self::show_right_block(
0 ignored issues
show
Bug Best Practice introduced by
The method IndexManager::show_right_block() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

328
            /** @scrutinizer ignore-call */ 
329
            $html = self::show_right_block(
Loading history...
329
                get_lang('Notice'),
330
                $home_notice,
331
                'notice_block',
332
                null,
333
                'notices',
334
                'noticesCollapse'
335
            );
336
        }
337
        return $html;
338
    }
339
340
    /**
341
     * @return string
342
     */
343
    public function return_help()
344
    {
345
        $user_selected_language = api_get_interface_language();
346
        $platformLanguage = api_get_setting('platformLanguage');
347
348
        // Help section.
349
        /* Hide right menu "general" and other parts on anonymous right menu. */
350
        if (!isset($user_selected_language)) {
351
            $user_selected_language = $platformLanguage;
352
        }
353
354
        $html = '';
355
        $home_menu = @(string) file_get_contents($this->home.'home_menu_'.$user_selected_language.'.html');
356
        if (!empty($home_menu)) {
357
            $home_menu_content = '<ul class="nav nav-pills nav-stacked">';
358
            $home_menu_content .= api_to_system_encoding($home_menu, api_detect_encoding(strip_tags($home_menu)));
359
            $home_menu_content .= '</ul>';
360
            $html .= self::show_right_block(
0 ignored issues
show
Bug Best Practice introduced by
The method IndexManager::show_right_block() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

360
            $html .= self::/** @scrutinizer ignore-call */ show_right_block(
Loading history...
361
                get_lang('MenuGeneral'),
362
                $home_menu_content,
363
                'help_block',
364
                null,
365
                'helps',
366
                'helpsCollapse'
367
            );
368
        }
369
370
        return $html;
371
    }
372
373
    /**
374
     * Generate the block for show a panel with links to My Certificates and Certificates Search pages
375
     * @return array The HTML code for the panel
376
     */
377
    public function returnSkillLinks()
378
    {
379
        $items = [];
380
381
        if (!api_is_anonymous() &&
382
            api_get_configuration_value('hide_my_certificate_link') === false
383
        ) {
384
            $items[] = [
385
                'icon' => Display::return_icon('graduation.png', get_lang('MyCertificates')),
386
                'link' => api_get_path(WEB_CODE_PATH).'gradebook/my_certificates.php',
387
                'title' => get_lang('MyCertificates')
388
            ];
389
        }
390
        if (api_get_setting('allow_public_certificates') == 'true') {
391
            $items[] = [
392
                'icon' => Display::return_icon('search_graduation.png', get_lang('Search')),
393
                'link' => api_get_path(WEB_CODE_PATH).'gradebook/search.php',
394
                'title' => get_lang('Search')
395
            ];
396
        }
397
398
        $myCertificate = GradebookUtils::get_certificate_by_user_id(
399
            +0,
400
            $this->user_id
401
        );
402
403
        if ($myCertificate) {
404
            $items[] = [
405
                'icon' => Display::return_icon(
406
                    'skill-badges.png',
407
                    get_lang('MyGeneralCertificate'),
408
                    null,
409
                    ICON_SIZE_SMALL
410
                ),
411
                'link' => api_get_path(WEB_CODE_PATH).'social/my_skills_report.php?a=generate_custom_skill',
412
                'title' => get_lang('MyGeneralCertificate')
413
            ];
414
        }
415
416
        if (Skill::isAllowed(api_get_user_id(), false)) {
417
            $items[] = [
418
                'icon' => Display::return_icon('skill-badges.png', get_lang('MySkills')),
419
                'link' => api_get_path(WEB_CODE_PATH).'social/my_skills_report.php',
420
                'title' => get_lang('MySkills')
421
            ];
422
            $allowSkillsManagement = api_get_setting('allow_hr_skills_management') == 'true';
423
            if (($allowSkillsManagement && api_is_drh()) || api_is_platform_admin()) {
424
                $items[] = [
425
                    'icon' => Display::return_icon('edit-skill.png', get_lang('MySkills')),
426
                    'link' => api_get_path(WEB_CODE_PATH).'admin/skills_wheel.php',
427
                    'title' => get_lang('ManageSkills')
428
                ];
429
            }
430
        }
431
432
        return $items;
433
    }
434
435
    /**
436
     * Reacts on a failed login:
437
     * Displays an explanation with a link to the registration form.
438
     *
439
     * @version 1.0.1
440
     */
441
    public function handle_login_failed()
442
    {
443
        return $this->tpl->handleLoginFailed();
444
    }
445
446
    /**
447
     * Display list of courses in a category.
448
     * (for anonymous users)
449
     *
450
     * @version 1.1
451
     * @author Patrick Cool <[email protected]>, Ghent University - refactoring and code cleaning
452
     * @author Julio Montoya <[email protected]>, Beeznest template modifs
453
     */
454
    public function return_courses_in_categories()
455
    {
456
        $result = '';
457
        $stok = Security::get_token();
458
459
        // Initialization.
460
        $user_identified = (api_get_user_id() > 0 && !api_is_anonymous());
461
        $web_course_path = api_get_path(WEB_COURSE_PATH);
462
        $category = isset($_GET['category']) ? Database::escape_string($_GET['category']) : '';
463
        $setting_show_also_closed_courses = api_get_setting('show_closed_courses') == 'true';
464
465
        // Database table definitions.
466
        $main_course_table = Database::get_main_table(TABLE_MAIN_COURSE);
467
        $main_category_table = Database::get_main_table(TABLE_MAIN_CATEGORY);
468
469
        // Get list of courses in category $category.
470
        $sql = "SELECT * FROM $main_course_table cours
471
                WHERE category_code = '".$category."'
472
                ORDER BY title, UPPER(visual_code)";
473
474
        // Showing only the courses of the current access_url_id.
475
        if (api_is_multiple_url_enabled()) {
476
            $url_access_id = api_get_current_access_url_id();
477
            if ($url_access_id != -1) {
478
                $tbl_url_rel_course = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
479
                $sql = "SELECT * FROM $main_course_table as course
480
                        INNER JOIN $tbl_url_rel_course as url_rel_course
481
                        ON (url_rel_course.c_id = course.id)
482
                        WHERE
483
                            access_url_id = $url_access_id AND
484
                            category_code = '".$category."'
485
                        ORDER BY title, UPPER(visual_code)";
486
            }
487
        }
488
489
        // Removed: AND cours.visibility='".COURSE_VISIBILITY_OPEN_WORLD."'
490
        $queryResult = Database::query($sql);
491
        while ($course_result = Database::fetch_array($queryResult)) {
492
            $course_list[] = $course_result;
493
        }
494
        $numRows = Database::num_rows($queryResult);
495
496
        // $setting_show_also_closed_courses
497
        if ($user_identified) {
498
            if ($setting_show_also_closed_courses) {
499
                $platform_visible_courses = '';
500
            } else {
501
                $platform_visible_courses = "  AND (t3.visibility='".COURSE_VISIBILITY_OPEN_WORLD."' OR t3.visibility='".COURSE_VISIBILITY_OPEN_PLATFORM."' )";
502
            }
503
        } else {
504
            if ($setting_show_also_closed_courses) {
505
                $platform_visible_courses = '';
506
            } else {
507
                $platform_visible_courses = "  AND (t3.visibility='".COURSE_VISIBILITY_OPEN_WORLD."' )";
508
            }
509
        }
510
        $sqlGetSubCatList = "
511
                    SELECT  t1.name,
512
                            t1.code,
513
                            t1.parent_id,
514
                            t1.children_count,COUNT(DISTINCT t3.code) AS nbCourse
515
                    FROM $main_category_table t1
516
                    LEFT JOIN $main_category_table t2 
517
                    ON t1.code=t2.parent_id
518
                    LEFT JOIN $main_course_table t3 
519
                    ON (t3.category_code = t1.code $platform_visible_courses)
520
                    WHERE t1.parent_id ".(empty($category) ? "IS NULL" : "='$category'")."
521
                    GROUP BY t1.name,t1.code,t1.parent_id,t1.children_count 
522
                    ORDER BY t1.tree_pos, t1.name";
523
524
        // Showing only the category of courses of the current access_url_id
525
        if (api_is_multiple_url_enabled()) {
526
            $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE_CATEGORY);
527
            $courseCategoryCondition = " INNER JOIN $table a ON (t1.id = a.course_category_id)";
528
529
            $url_access_id = api_get_current_access_url_id();
530
            if ($url_access_id != -1) {
531
                $tbl_url_rel_course = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
532
                $sqlGetSubCatList = "
533
                    SELECT t1.name,
534
                            t1.code,
535
                            t1.parent_id,
536
                            t1.children_count,
537
                            COUNT(DISTINCT t3.code) AS nbCourse
538
                    FROM $main_category_table t1
539
                    $courseCategoryCondition
540
                    LEFT JOIN $main_category_table t2 ON t1.code = t2.parent_id
541
                    LEFT JOIN $main_course_table t3 ON (t3.category_code = t1.code $platform_visible_courses)
542
                    INNER JOIN $tbl_url_rel_course as url_rel_course
543
                    ON (url_rel_course.c_id = t3.id)
544
                    WHERE
545
                        url_rel_course.access_url_id = $url_access_id AND
546
                        t1.parent_id ".(empty($category) ? "IS NULL" : "='$category'")."
547
                    GROUP BY t1.name,t1.code,t1.parent_id,t1.children_count
548
                    ORDER BY t1.tree_pos, t1.name";
549
            }
550
        }
551
552
        $resCats = Database::query($sqlGetSubCatList);
553
        $thereIsSubCat = false;
554
        if (Database::num_rows($resCats) > 0) {
555
            $htmlListCat = Display::page_header(get_lang('CatList'));
556
            $htmlListCat .= '<ul>';
557
            $htmlTitre = '';
558
            while ($catLine = Database::fetch_array($resCats)) {
559
                $category_has_open_courses = self::category_has_open_courses($catLine['code']);
0 ignored issues
show
Bug Best Practice introduced by
The method IndexManager::category_has_open_courses() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

559
                /** @scrutinizer ignore-call */ 
560
                $category_has_open_courses = self::category_has_open_courses($catLine['code']);
Loading history...
560
                if ($category_has_open_courses) {
561
                    // The category contains courses accessible to anonymous visitors.
562
                    $htmlListCat .= '<li>';
563
                    $htmlListCat .= '<a href="'.api_get_self().'?category='.$catLine['code'].'">'.$catLine['name'].'</a>';
564
                    if (api_get_setting('show_number_of_courses') == 'true') {
565
                        $htmlListCat .= ' ('.$catLine['nbCourse'].' '.get_lang('Courses').')';
566
                    }
567
                    $htmlListCat .= "</li>";
568
                    $thereIsSubCat = true;
569
                } elseif ($catLine['children_count'] > 0) {
570
                    // The category has children, subcategories.
571
                    $htmlListCat .= '<li>';
572
                    $htmlListCat .= '<a href="'.api_get_self().'?category='.$catLine['code'].'">'.$catLine['name'].'</a>';
573
                    $htmlListCat .= "</li>";
574
                    $thereIsSubCat = true;
575
                } elseif (api_get_setting('show_empty_course_categories') == 'true') {
576
                    /* End changed code to eliminate the (0 courses) after empty categories. */
577
                    $htmlListCat .= '<li>';
578
                    $htmlListCat .= $catLine['name'];
579
                    $htmlListCat .= "</li>";
580
                    $thereIsSubCat = true;
581
                } // Else don't set thereIsSubCat to true to avoid printing things if not requested.
582
                // TODO: deprecate this useless feature - this includes removing system variable
583
                if (empty($htmlTitre)) {
584
                    $htmlTitre = '<p>';
585
                    if (api_get_setting('show_back_link_on_top_of_tree') == 'true') {
586
                        $htmlTitre .= '<a href="'.api_get_self().'">&lt;&lt; '.get_lang('BackToHomePage').'</a>';
587
                    }
588
                    $htmlTitre .= "</p>";
589
                }
590
            }
591
            $htmlListCat .= "</ul>";
592
        }
593
        $result .= $htmlTitre;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $htmlTitre does not seem to be defined for all execution paths leading up to this point.
Loading history...
594
        if ($thereIsSubCat) {
595
            $result .= $htmlListCat;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $htmlListCat does not seem to be defined for all execution paths leading up to this point.
Loading history...
596
        }
597
        while ($categoryName = Database::fetch_array($resCats)) {
598
            $result .= '<h3>'.$categoryName['name']."</h3>\n";
599
        }
600
601
        $courses_list_string = '';
602
        $courses_shown = 0;
603
        if ($numRows > 0) {
604
            $courses_list_string .= Display::page_header(get_lang('CourseList'));
605
            $courses_list_string .= "<ul>";
606
            if (api_get_user_id()) {
607
                $courses_of_user = self::get_courses_of_user(api_get_user_id());
0 ignored issues
show
Bug Best Practice introduced by
The method IndexManager::get_courses_of_user() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

607
                /** @scrutinizer ignore-call */ 
608
                $courses_of_user = self::get_courses_of_user(api_get_user_id());
Loading history...
608
            }
609
            foreach ($course_list as $course) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $course_list does not seem to be defined for all execution paths leading up to this point.
Loading history...
610
                // $setting_show_also_closed_courses
611
                if ($course['visibility'] == COURSE_VISIBILITY_HIDDEN) {
612
                    continue;
613
                }
614
                if (!$setting_show_also_closed_courses) {
615
                    // If we do not show the closed courses
616
                    // we only show the courses that are open to the world (to everybody)
617
                    // and the courses that are open to the platform (if the current user is a registered user.
618
                    if (($user_identified && $course['visibility'] == COURSE_VISIBILITY_OPEN_PLATFORM) ||
619
                        ($course['visibility'] == COURSE_VISIBILITY_OPEN_WORLD)
620
                    ) {
621
                        $courses_shown++;
622
                        $courses_list_string .= "<li>";
623
                        $courses_list_string .= '<a href="'.$web_course_path.$course['directory'].'/">'.$course['title'].'</a><br />';
624
                        $course_details = [];
625
                        if (api_get_setting('display_coursecode_in_courselist') === 'true') {
626
                            $course_details[] = $course['visual_code'];
627
                        }
628
                        if (api_get_setting('display_teacher_in_courselist') === 'true') {
629
                            $course_details[] = CourseManager::getTeacherListFromCourseCodeToString($course['code']);
630
                        }
631
                        if (api_get_setting('show_different_course_language') === 'true' &&
632
                            $course['course_language'] != api_get_setting('platformLanguage')
633
                        ) {
634
                            $course_details[] = $course['course_language'];
635
                        }
636
                        $courses_list_string .= implode(' - ', $course_details);
637
                        $courses_list_string .= "</li>";
638
                    }
639
                } else {
640
                    // We DO show the closed courses.
641
                    // The course is accessible if (link to the course homepage):
642
                    // 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);
643
                    // 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);
644
                    // 3. the user is logged in and the user is subscribed to the course and the course visibility is not COURSE_VISIBILITY_CLOSED;
645
                    // 4. the user is logged in and the user is course admin of te course (regardless of the course visibility setting);
646
                    // 5. the user is the platform admin api_is_platform_admin().
647
648
                    $courses_shown++;
649
                    $courses_list_string .= "<li>";
650
                    if ($course['visibility'] == COURSE_VISIBILITY_OPEN_WORLD
651
                        || ($user_identified && $course['visibility'] == COURSE_VISIBILITY_OPEN_PLATFORM)
652
                        || ($user_identified && array_key_exists($course['code'], $courses_of_user)
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $courses_of_user does not seem to be defined for all execution paths leading up to this point.
Loading history...
653
                            && $course['visibility'] != COURSE_VISIBILITY_CLOSED)
654
                        || $courses_of_user[$course['code']]['status'] == '1'
655
                        || api_is_platform_admin()
656
                    ) {
657
                        $courses_list_string .= '<a href="'.$web_course_path.$course['directory'].'/">';
658
                    }
659
                    $courses_list_string .= $course['title'];
660
                    if ($course['visibility'] == COURSE_VISIBILITY_OPEN_WORLD
661
                        || ($user_identified && $course['visibility'] == COURSE_VISIBILITY_OPEN_PLATFORM)
662
                        || ($user_identified && array_key_exists($course['code'], $courses_of_user)
663
                            && $course['visibility'] != COURSE_VISIBILITY_CLOSED)
664
                        || $courses_of_user[$course['code']]['status'] == '1'
665
                        || api_is_platform_admin()
666
                    ) {
667
                        $courses_list_string .= '</a><br />';
668
                    }
669
                    $course_details = [];
670
                    if (api_get_setting('display_coursecode_in_courselist') == 'true') {
671
                        $course_details[] = $course['visual_code'];
672
                    }
673
                    if (api_get_setting('display_teacher_in_courselist') === 'true') {
674
                        if (!empty($course['tutor_name'])) {
675
                            $course_details[] = $course['tutor_name'];
676
                        }
677
                    }
678
                    if (api_get_setting('show_different_course_language') == 'true' &&
679
                        $course['course_language'] != api_get_setting('platformLanguage')
680
                    ) {
681
                        $course_details[] = $course['course_language'];
682
                    }
683
684
                    $courses_list_string .= implode(' - ', $course_details);
685
                    // We display a subscription link if:
686
                    // 1. it is allowed to register for the course and if the course is not already in
687
                    // the courselist of the user and if the user is identified
688
                    // 2.
689
                    if ($user_identified && !array_key_exists($course['code'], $courses_of_user)) {
690
                        if ($course['subscribe'] == '1') {
691
                            $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($_GET['category']).'">'.get_lang('Subscribe').'</a><br />';
692
                        } else {
693
                            $courses_list_string .= '<br />'.get_lang('SubscribingNotAllowed');
694
                        }
695
                    }
696
                    $courses_list_string .= "</li>";
697
                } //end else
698
            } // end foreach
699
            $courses_list_string .= "</ul>";
700
        }
701
        if ($courses_shown > 0) {
702
            // Only display the list of courses and categories if there was more than
703
            // 0 courses visible to the world (we're in the anonymous list here).
704
            $result .= $courses_list_string;
705
        }
706
        if ($category != '') {
707
            $result .= '<p><a href="'.api_get_self().'">'
708
                .Display:: return_icon('back.png', get_lang('BackToHomePage'))
709
                .get_lang('BackToHomePage').'</a></p>';
710
        }
711
712
        return $result;
713
    }
714
715
    /**
716
     * retrieves all the courses that the user has already subscribed to
717
     * @author Patrick Cool <[email protected]>, Ghent University, Belgium
718
     * @param int $user_id : the id of the user
719
     * @return array an array containing all the information of the courses of the given user
720
     */
721
    public function get_courses_of_user($user_id)
722
    {
723
        $table_course = Database::get_main_table(TABLE_MAIN_COURSE);
724
        $table_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
725
        // Secondly we select the courses that are in a category (user_course_cat <> 0)
726
        // and sort these according to the sort of the category
727
        $user_id = intval($user_id);
728
        $sql = "SELECT
729
                    course.code k,
730
                    course.visual_code vc,
731
                    course.subscribe subscr,
732
                    course.unsubscribe unsubscr,
733
                    course.title i,
734
                    course.tutor_name t,
735
                    course.directory dir,
736
                    course_rel_user.status status,
737
                    course_rel_user.sort sort,
738
                    course_rel_user.user_course_cat user_course_cat
739
                FROM
740
                    $table_course course,
741
                    $table_course_user course_rel_user
742
                WHERE
743
                    course.id = course_rel_user.c_id AND
744
                    course_rel_user.user_id = '".$user_id."' AND
745
                    course_rel_user.relation_type <> ".COURSE_RELATION_TYPE_RRHH."
746
                ORDER BY course_rel_user.sort ASC";
747
        $result = Database::query($sql);
748
        $courses = [];
749
        while ($row = Database::fetch_array($result)) {
750
            // We only need the database name of the course.
751
            $courses[$row['k']] = [
752
                'code' => $row['k'],
753
                'visual_code' => $row['vc'],
754
                'title' => $row['i'],
755
                'directory' => $row['dir'],
756
                'status' => $row['status'],
757
                'tutor' => $row['t'],
758
                'subscribe' => $row['subscr'],
759
                'unsubscribe' => $row['unsubscr'],
760
                'sort' => $row['sort'],
761
                'user_course_category' => $row['user_course_cat']
762
            ];
763
        }
764
765
        return $courses;
766
    }
767
768
    /**
769
     * @todo use the template system
770
     * @param $title
771
     * @param $content
772
     * @param string $id
773
     * @param array $params
774
     * @param string $idAccordion
775
     * @param string $idCollapse
776
     * @return string
777
     */
778
    public function show_right_block(
779
        $title,
780
        $content,
781
        $id = '',
782
        $params = [],
783
        $idAccordion = '',
784
        $idCollapse = ''
785
    ) {
786
        $html = '';
787
        if (!empty($idAccordion)) {
788
            $html .= '<div class="panel-group" id="'.$idAccordion.'" role="tablist" aria-multiselectable="true">';
789
            $html .= '<div class="panel panel-default" id="'.$id.'">';
790
            $html .= '<div class="panel-heading" role="tab"><h4 class="panel-title">';
791
            $html .= '<a role="button" data-toggle="collapse" data-parent="#'.$idAccordion.'" href="#'.$idCollapse.'" aria-expanded="true" aria-controls="'.$idCollapse.'">'.$title.'</a>';
792
            $html .= '</h4></div>';
793
            $html .= '<div id="'.$idCollapse.'" class="panel-collapse collapse in" role="tabpanel">';
794
            $html .= '<div class="panel-body">'.$content.'</div>';
795
            $html .= '</div></div></div>';
796
        } else {
797
            if (!empty($id)) {
798
                $params['id'] = $id;
799
            }
800
            $params['class'] = 'panel panel-default';
801
            $html = null;
802
            if (!empty($title)) {
803
                $html .= '<div class="panel-heading">'.$title.'</div>';
804
            }
805
            $html .= '<div class="panel-body">'.$content.'</div>';
806
            $html = Display::div($html, $params);
807
        }
808
809
        return $html;
810
    }
811
812
    /**
813
     * Adds a form to let users login
814
     * @version 1.1
815
     */
816
    public function display_login_form()
817
    {
818
        return $this->tpl->displayLoginForm();
819
    }
820
821
    /**
822
     * @todo use FormValidator
823
     * @return string
824
     */
825
    public function return_search_block()
826
    {
827
        $html = '';
828
        if (api_get_setting('search_enabled') == 'true') {
829
            $search_btn = get_lang('Search');
830
            $search_content = '<form action="main/search/" method="post">
831
                <div class="form-group">
832
                <input type="text" id="query" class="form-control" name="query" value="" />
833
                <button class="btn btn-default" type="submit" name="submit" value="'.$search_btn.'" />'.
834
                $search_btn.' </button>
835
                </div></form>';
836
            $html .= self::show_right_block(get_lang('Search'), $search_content, 'search_block');
0 ignored issues
show
Bug Best Practice introduced by
The method IndexManager::show_right_block() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

836
            $html .= self::/** @scrutinizer ignore-call */ show_right_block(get_lang('Search'), $search_content, 'search_block');
Loading history...
837
        }
838
839
        return $html;
840
    }
841
842
    /**
843
     * @return string
844
     */
845
    public function return_classes_block()
846
    {
847
        if (api_get_setting('show_groups_to_users') !== 'true') {
848
            return '';
849
        }
850
851
        $usergroup = new UserGroup();
852
        $usergroup_list = $usergroup->get_usergroup_by_user(api_get_user_id());
853
        $items = [];
854
        if (!empty($usergroup_list)) {
855
            foreach ($usergroup_list as $group_id) {
856
                $data = $usergroup->get($group_id);
857
                $items[] = [
858
                    'link' => api_get_path(WEB_CODE_PATH).'user/classes.php?id='.$data['id'],
859
                    'title' => $data['name']
860
                ];
861
            }
862
        }
863
        if (api_is_platform_admin()) {
864
            $items[] = [
865
                'link' => api_get_path(WEB_CODE_PATH).'admin/usergroups.php?action=add',
866
                'title' => get_lang('AddClasses')
867
            ];
868
        }
869
870
        $html = self::show_right_block(
0 ignored issues
show
Bug Best Practice introduced by
The method IndexManager::show_right_block() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

870
        /** @scrutinizer ignore-call */ 
871
        $html = self::show_right_block(
Loading history...
871
            get_lang('Classes'),
872
            self::returnRightBlockItems($items),
873
            'classes_block'
874
        );
875
876
        return $html;
877
    }
878
879
    /**
880
     * @return string
881
     */
882
    public function return_user_image_block()
883
    {
884
        $html = '';
885
        if (!api_is_anonymous()) {
886
            $userPicture = UserManager::getUserPicture(api_get_user_id(), USER_IMAGE_SIZE_ORIGINAL);
887
            $content = null;
888
889
            if (api_get_setting('allow_social_tool') == 'true') {
890
                $content .= '<a style="text-align:center" href="'.api_get_path(WEB_PATH).'main/social/home.php">
891
                <img class="img-circle" src="'.$userPicture.'"></a>';
892
            } else {
893
                $content .= '<a style="text-align:center" href="'.api_get_path(WEB_PATH).'main/auth/profile.php">
894
                <img class="img-circle" title="'.get_lang('EditProfile').'" src="'.$userPicture.'"></a>';
895
            }
896
897
            $html = self::show_right_block(
0 ignored issues
show
Bug Best Practice introduced by
The method IndexManager::show_right_block() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

897
            /** @scrutinizer ignore-call */ 
898
            $html = self::show_right_block(
Loading history...
898
                null,
899
                $content,
900
                'user_image_block',
901
                ['style' => 'text-align:center;']
902
            );
903
        }
904
905
        return $html;
906
    }
907
908
    /**
909
     * @return array
910
     */
911
    public function return_profile_block()
912
    {
913
        $userInfo = api_get_user_info();
914
        $userId = api_get_user_id();
915
        if (empty($userId)) {
916
            return;
917
        }
918
919
        $items = [];
920
        $userGroup = new UserGroup();
921
        //  @todo Add a platform setting to add the user image.
922
        if (api_get_setting('allow_message_tool') == 'true') {
923
            // New messages.
924
            $number_of_new_messages = MessageManager::getCountNewMessages();
925
            // New contact invitations.
926
            $number_of_new_messages_of_friend = SocialManager::get_message_number_invitation_by_user_id(
927
                $userId
928
            );
929
930
            // New group invitations sent by a moderator.
931
            $group_pending_invitations = $userGroup->get_groups_by_user(
932
                $userId,
933
                GROUP_USER_PERMISSION_PENDING_INVITATION,
934
                false
935
            );
936
            $group_pending_invitations = count($group_pending_invitations);
937
            $total_invitations = $number_of_new_messages_of_friend + $group_pending_invitations;
938
            $cant_msg = Display::badge($number_of_new_messages);
939
940
            $items[] = [
941
                'class' => 'inbox-message-social',
942
                'icon' => Display::return_icon('inbox.png', get_lang('Inbox')),
943
                'link' => api_get_path(WEB_PATH).'main/messages/inbox.php',
944
                'title' => get_lang('Inbox').$cant_msg
945
            ];
946
            $items[] = [
947
                'class' => 'new-message-social',
948
                'icon' => Display::return_icon('new-message.png', get_lang('Compose')),
949
                'link' => api_get_path(WEB_PATH).'main/messages/new_message.php',
950
                'title' => get_lang('Compose')
951
            ];
952
953
            if (api_get_setting('allow_social_tool') == 'true') {
954
                $total_invitations = Display::badge($total_invitations);
955
                $items[] = [
956
                    'class' => 'invitations-social',
957
                    'icon' => Display::return_icon('invitations.png', get_lang('PendingInvitations')),
958
                    'link' => api_get_path(WEB_PATH).'main/social/invitations.php',
959
                    'title' => get_lang('PendingInvitations').$total_invitations
960
                ];
961
            }
962
963
            if (api_get_configuration_value('allow_my_files_link_in_homepage')) {
964
                if (api_get_setting('allow_my_files') !== 'false') {
965
                    $items[] = [
966
                        'class' => 'myfiles-social',
967
                        'icon' => Display::return_icon('sn-files.png', get_lang('Files')),
968
                        'link' => api_get_path(WEB_PATH).'main/social/myfiles.php',
969
                        'title' => get_lang('MyFiles')
970
                    ];
971
                }
972
            }
973
        }
974
975
        $items[] = [
976
            'class' => 'profile-social',
977
            'icon' => Display::return_icon('edit-profile.png', get_lang('EditProfile')),
978
            'link' => Display::getProfileEditionLink($userId),
979
            'title' => get_lang('EditProfile')
980
        ];
981
982
        if (api_get_configuration_value('show_link_request_hrm_user') &&
983
            api_is_drh()
984
        ) {
985
            $label = get_lang('RequestLinkingToUser');
986
            $items[] = [
987
                'icon' => Display::return_icon('new_group.png', $label),
988
                'link' => api_get_path(WEB_CODE_PATH).'social/require_user_linking.php',
989
                'title' => $label
990
            ];
991
        }
992
993
        if (bbb::showGlobalConferenceLink($userInfo)) {
994
            $bbb = new bbb('', '', true, api_get_user_id());
995
            $url = $bbb->getListingUrl();
996
            $items[] = [
997
                'class' => 'video-conference',
998
                'icon' => Display::return_icon(
999
                    'bbb.png',
1000
                    get_lang('VideoConference')
1001
                ),
1002
                'link' => $url,
1003
                'title' => get_lang('VideoConference')
1004
            ];
1005
        }
1006
1007
        return $items;
1008
    }
1009
1010
    /**
1011
     * @return array
1012
     */
1013
    public function return_navigation_links()
1014
    {
1015
        $items = [];
1016
        // Deleting the myprofile link.
1017
        if (api_get_setting('allow_social_tool') == 'true') {
1018
            unset($this->tpl->menu_navigation['myprofile']);
1019
        }
1020
1021
        $hideMenu = api_get_configuration_value('hide_main_navigation_menu');
1022
        if ($hideMenu === true) {
1023
            return '';
0 ignored issues
show
Bug Best Practice introduced by
The expression return '' returns the type string which is incompatible with the documented return type array.
Loading history...
1024
        }
1025
1026
        // Main navigation section.
1027
        // Tabs that are deactivated are added here.
1028
        if (!empty($this->tpl->menu_navigation)) {
1029
            foreach ($this->tpl->menu_navigation as $section => $navigation_info) {
1030
                $items [] = [
1031
                    'icon' => null,
1032
                    'link' => $navigation_info['url'],
1033
                    'title' => $navigation_info['title']
1034
                ];
1035
            }
1036
        }
1037
1038
        return $items;
1039
    }
1040
1041
    /**
1042
     * @return array
1043
     */
1044
    public function return_course_block()
1045
    {
1046
        $isHrm = api_is_drh();
1047
        $show_create_link = false;
1048
        $show_course_link = false;
1049
        if (api_is_allowed_to_create_course()) {
1050
            $show_create_link = true;
1051
        }
1052
1053
        if (api_get_setting('allow_students_to_browse_courses') === 'true') {
1054
            $show_course_link = true;
1055
        }
1056
1057
        $items = [];
1058
1059
        // My account section
1060
        if ($show_create_link) {
1061
            if (api_get_setting('course_validation') == 'true' && !api_is_platform_admin()) {
1062
                $items[] = [
1063
                    'class' => 'add-course',
1064
                    'icon' => Display::return_icon('new-course.png', get_lang('CreateCourseRequest')),
1065
                    'link' => 'main/create_course/add_course.php',
1066
                    'title' => get_lang('CreateCourseRequest')
1067
                ];
1068
            } else {
1069
                $items[] = [
1070
                    'class' => 'add-course',
1071
                    'icon' => Display::return_icon('new-course.png', get_lang('CourseCreate')),
1072
                    'link' => 'main/create_course/add_course.php',
1073
                    'title' => get_lang('CourseCreate')
1074
                ];
1075
            }
1076
1077
            if (SessionManager::allowToManageSessions()) {
1078
                $items[] = [
1079
                    'class' => 'add-course',
1080
                    'icon' => Display::return_icon('session.png', get_lang('AddSession')),
1081
                    'link' => 'main/session/session_add.php',
1082
                    'title' => get_lang('AddSession')
1083
                ];
1084
            }
1085
        }
1086
1087
        // Sort courses
1088
        $items[] = [
1089
            'class' => 'order-course',
1090
            'icon' => Display::return_icon('order-course.png', get_lang('SortMyCourses')),
1091
            'link' => api_get_path(WEB_CODE_PATH).'auth/courses.php?action=sortmycourses',
1092
            'title' => get_lang('SortMyCourses')
1093
        ];
1094
1095
        // Session history
1096
        if (isset($_GET['history']) && intval($_GET['history']) == 1) {
1097
            $items[] = [
1098
                'class' => 'history-course',
1099
                'icon' => Display::return_icon('history-course.png', get_lang('DisplayTrainingList')),
1100
                'link' => 'user_portal.php',
1101
                'title' => get_lang('DisplayTrainingList')
1102
            ];
1103
        } else {
1104
            $items[] = [
1105
                'class' => 'history-course',
1106
                'icon' => Display::return_icon('history-course.png', get_lang('HistoryTrainingSessions')),
1107
                'link' => 'user_portal.php?history=1',
1108
                'title' => get_lang('HistoryTrainingSessions')
1109
            ];
1110
        }
1111
1112
        if ($isHrm) {
1113
            $items[] = [
1114
                'link' => api_get_path(WEB_CODE_PATH).'auth/hrm_courses.php',
1115
                'title' => get_lang('HrmAssignedUsersCourseList')
1116
            ];
1117
        }
1118
1119
        // Course catalog
1120
        if ($show_course_link) {
1121
            if (!api_is_drh()) {
1122
                $items[] = [
1123
                    'class' => 'list-course',
1124
                    'icon' => Display::return_icon('catalog-course.png', get_lang('CourseCatalog')),
1125
                    'link' => 'main/auth/courses.php',
1126
                    'title' => get_lang('CourseCatalog')
1127
                ];
1128
            } else {
1129
                $items[] = [
1130
                    'link' => 'main/dashboard/index.php',
1131
                    'title' => get_lang('Dashboard')
1132
                ];
1133
            }
1134
        }
1135
1136
        return $items;
1137
    }
1138
1139
    /**
1140
     * Generate the HTML code for items when displaying the right-side blocks
1141
     * @param array $items
1142
     * @return string
1143
     */
1144
    private static function returnRightBlockItems(array $items)
1145
    {
1146
        $my_account_content = '';
1147
        foreach ($items as $item) {
1148
            if (empty($item['link']) && empty($item['title'])) {
1149
                continue;
1150
            }
1151
1152
            $my_account_content .= '<li class="list-group-item '.(empty($item['class']) ? '' : $item['class']).'">'
1153
                .(empty($item['icon']) ? '' : '<span class="item-icon">'.$item['icon'].'</span>')
1154
                .'<a href="'.$item['link'].'">'.$item['title'].'</a>'
1155
                .'</li>';
1156
        }
1157
1158
        return '<ul class="list-group">'.$my_account_content.'</ul>';
1159
    }
1160
1161
    /**
1162
     * Prints the session and course list (user_portal.php)
1163
     * @param int $user_id
1164
     * @param bool $showSessions
1165
     * @param string $categoryCodeFilter
1166
     * @param bool $useUserLanguageFilterIfAvailable
1167
     * @param bool $loadHistory
1168
     * @return array
1169
     */
1170
    public function returnCoursesAndSessions(
1171
        $user_id,
1172
        $showSessions = true,
1173
        $categoryCodeFilter = '',
1174
        $useUserLanguageFilterIfAvailable = true,
1175
        $loadHistory = false
1176
    ) {
1177
        $gameModeIsActive = api_get_setting('gamification_mode');
1178
        $listCourse = '';
1179
        $specialCourseList = '';
1180
        $viewGridCourses = api_get_configuration_value('view_grid_courses') === true;
1181
        $showSimpleSessionInfo = api_get_configuration_value('show_simple_session_info');
1182
1183
        $coursesWithoutCategoryTemplate = '/user_portal/classic_courses_without_category.tpl';
1184
        $coursesWithCategoryTemplate = '/user_portal/classic_courses_with_category.tpl';
1185
        $showAllSessions = api_get_configuration_value('show_all_sessions_on_my_course_page') === true;
1186
1187
        if ($loadHistory) {
1188
            // Load sessions in category in *history*
1189
            $session_categories = UserManager::get_sessions_by_category($user_id, true);
1190
        } else {
1191
            // Load sessions in category
1192
            $session_categories = UserManager::get_sessions_by_category($user_id, false);
1193
        }
1194
1195
        $sessionCount = 0;
1196
        $courseCount = 0;
1197
1198
        // Student info code check (shows student progress information on
1199
        // courses list
1200
        $studentInfo = api_get_configuration_value('course_student_info');
1201
        $viewGrid = api_get_configuration_value('view_grid_courses');
1202
1203
        $studentInfoProgress = !empty($studentInfo['progress']) && $studentInfo['progress'] === true;
1204
        $studentInfoScore = !empty($studentInfo['score']) && $studentInfo['score'] === true;
1205
        $studentInfoCertificate = !empty($studentInfo['certificate']) && $studentInfo['certificate'] === true;
1206
        $courseCompleteList = [];
1207
        $coursesInCategoryCount = 0;
1208
        $coursesNotInCategoryCount = 0;
1209
1210
        // If we're not in the history view...
1211
        if ($loadHistory == false) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
1212
            // Display special courses.
1213
            $specialCourses = CourseManager::returnSpecialCourses(
1214
                $user_id,
1215
                $this->load_directories_preview,
1216
                $useUserLanguageFilterIfAvailable
1217
            );
1218
1219
            // Display courses.
1220
            $courses = CourseManager::returnCourses(
1221
                $user_id,
1222
                $this->load_directories_preview,
1223
                $useUserLanguageFilterIfAvailable
1224
            );
1225
1226
            // Course option (show student progress)
1227
            // This code will add new variables (Progress, Score, Certificate)
1228
            if ($studentInfoProgress || $studentInfoScore || $studentInfoCertificate) {
1229
                if (!empty($specialCourses)) {
1230
                    foreach ($specialCourses as $key => $specialCourseInfo) {
1231
                        if ($studentInfoProgress) {
1232
                            $progress = Tracking::get_avg_student_progress(
1233
                                $user_id,
1234
                                $specialCourseInfo['course_code']
1235
                            );
1236
                            $specialCourses[$key]['student_info']['progress'] = $progress === false ? null : $progress;
1237
                        }
1238
1239
                        if ($studentInfoScore) {
1240
                            $percentage_score = Tracking::get_avg_student_score(
1241
                                $user_id,
1242
                                $specialCourseInfo['course_code'],
1243
                                []
1244
                            );
1245
                            $specialCourses[$key]['student_info']['score'] = $percentage_score;
1246
                        }
1247
1248
                        if ($studentInfoCertificate) {
1249
                            $category = Category::load(
1250
                                null,
1251
                                null,
1252
                                $specialCourseInfo['course_code'],
1253
                                null,
1254
                                null,
1255
                                null
1256
                            );
1257
                            $specialCourses[$key]['student_info']['certificate'] = null;
1258
                            if (isset($category[0])) {
1259
                                if ($category[0]->is_certificate_available($user_id)) {
1260
                                    $specialCourses[$key]['student_info']['certificate'] = Display::label(
1261
                                        get_lang('Yes'),
1262
                                        'success'
1263
                                    );
1264
                                } else {
1265
                                    $specialCourses[$key]['student_info']['certificate'] = Display::label(
1266
                                        get_lang('No'),
1267
                                        'danger'
1268
                                    );
1269
                                }
1270
                            }
1271
                        }
1272
                    }
1273
                }
1274
1275
                if (isset($courses['in_category'])) {
1276
                    foreach ($courses['in_category'] as $key1 => $value) {
1277
                        if (isset($courses['in_category'][$key1]['courses'])) {
1278
                            foreach ($courses['in_category'][$key1]['courses'] as $key2 => $courseInCatInfo) {
1279
                                if ($studentInfoProgress) {
1280
                                    $progress = Tracking::get_avg_student_progress(
1281
                                        $user_id,
1282
                                        $courseInCatInfo['course_code']
1283
                                    );
1284
                                    $courses['in_category'][$key1]['courses'][$key2]['student_info']['progress'] = $progress === false ? null : $progress;
1285
                                }
1286
1287
                                if ($studentInfoScore) {
1288
                                    $percentage_score = Tracking::get_avg_student_score(
1289
                                        $user_id,
1290
                                        $specialCourseInfo['course_code'],
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $specialCourseInfo does not seem to be defined for all execution paths leading up to this point.
Loading history...
1291
                                        []
1292
                                    );
1293
                                    $courses['in_category'][$key1]['courses'][$key2]['student_info']['score'] = $percentage_score;
1294
                                }
1295
1296
                                if ($studentInfoCertificate) {
1297
                                    $category = Category::load(
1298
                                        null,
1299
                                        null,
1300
                                        $courseInCatInfo['course_code'],
1301
                                        null,
1302
                                        null,
1303
                                        null
1304
                                    );
1305
                                    $courses['in_category'][$key1]['student_info']['certificate'] = null;
1306
                                    $isCertificateAvailable = $category[0]->is_certificate_available($user_id);
1307
                                    if (isset($category[0])) {
1308
                                        if ($viewGrid) {
1309
                                            if ($isCertificateAvailable) {
1310
                                                $courses['in_category'][$key1]['student_info']['certificate'] = get_lang('Yes');
1311
                                            } else {
1312
                                                $courses['in_category'][$key1]['student_info']['certificate'] = get_lang('No');
1313
                                            }
1314
                                        } else {
1315
                                            if ($isCertificateAvailable) {
1316
                                                $courses['in_category'][$key1]['student_info']['certificate'] = Display::label(
1317
                                                    get_lang('Yes'),
1318
                                                    'success'
1319
                                                );
1320
                                            } else {
1321
                                                $courses['in_category'][$key1]['student_info']['certificate'] = Display::label(
1322
                                                    get_lang('No'),
1323
                                                    'danger'
1324
                                                );
1325
                                            }
1326
                                        }
1327
                                    }
1328
                                }
1329
                            }
1330
                        }
1331
                    }
1332
                }
1333
1334
                if (isset($courses['not_category'])) {
1335
                    foreach ($courses['not_category'] as $key => $courseNotInCatInfo) {
1336
                        if ($studentInfoProgress) {
1337
                            $progress = Tracking::get_avg_student_progress(
1338
                                $user_id,
1339
                                $courseNotInCatInfo['course_code']
1340
                            );
1341
                            $courses['not_category'][$key]['student_info']['progress'] = $progress === false ? null : $progress;
1342
                        }
1343
1344
                        if ($studentInfoScore) {
1345
                            $percentage_score = Tracking::get_avg_student_score(
1346
                                $user_id,
1347
                                $courseNotInCatInfo['course_code'],
1348
                                []
1349
                            );
1350
                            $courses['not_category'][$key]['student_info']['score'] = $percentage_score;
1351
                        }
1352
1353
                        if ($studentInfoCertificate) {
1354
                            $category = Category::load(
1355
                                null,
1356
                                null,
1357
                                $courseNotInCatInfo['course_code'],
1358
                                null,
1359
                                null,
1360
                                null
1361
                            );
1362
                            $courses['not_category'][$key]['student_info']['certificate'] = null;
1363
1364
                            if (isset($category[0])) {
1365
                                $certificateAvailable = $category[0]->is_certificate_available($user_id);
1366
                                if ($viewGrid) {
1367
                                    if ($certificateAvailable) {
1368
                                        $courses['not_category'][$key]['student_info']['certificate'] = get_lang('Yes');
1369
                                    } else {
1370
                                        $courses['not_category'][$key]['student_info']['certificate'] = get_lang('No');
1371
                                    }
1372
                                } else {
1373
                                    if ($certificateAvailable) {
1374
                                        $courses['not_category'][$key]['student_info']['certificate'] = Display::label(
1375
                                            get_lang('Yes'),
1376
                                            'success'
1377
                                        );
1378
                                    } else {
1379
                                        $courses['not_category'][$key]['student_info']['certificate'] = Display::label(
1380
                                            get_lang('No'),
1381
                                            'danger'
1382
                                        );
1383
                                    }
1384
                                }
1385
                            }
1386
                        }
1387
                    }
1388
                }
1389
            }
1390
1391
            if ($viewGridCourses) {
1392
                $coursesWithoutCategoryTemplate = '/user_portal/grid_courses_without_category.tpl';
1393
                $coursesWithCategoryTemplate = '/user_portal/grid_courses_with_category.tpl';
1394
            }
1395
1396
            if ($specialCourses) {
1397
                if ($categoryCodeFilter) {
1398
                    $specialCourses = self::filterByCategory(
1399
                        $specialCourses,
1400
                        $categoryCodeFilter
1401
                    );
1402
                }
1403
                $this->tpl->assign('courses', $specialCourses);
1404
                $specialCourseList = $this->tpl->fetch(
1405
                    $this->tpl->get_template($coursesWithoutCategoryTemplate)
1406
                );
1407
                $courseCompleteList = array_merge($courseCompleteList, $specialCourses);
1408
            }
1409
            if ($courses['in_category'] || $courses['not_category']) {
1410
                foreach ($courses['in_category'] as $courseData) {
1411
                    if (!empty($courseData['courses'])) {
1412
                        $coursesInCategoryCount += count($courseData['courses']);
1413
                        $courseCompleteList = array_merge($courseCompleteList, $courseData['courses']);
1414
                    }
1415
                }
1416
1417
                $coursesNotInCategoryCount += count($courses['not_category']);
1418
                $courseCompleteList = array_merge($courseCompleteList, $courses['not_category']);
1419
1420
                if ($categoryCodeFilter) {
1421
                    $courses['in_category'] = self::filterByCategory(
1422
                        $courses['in_category'],
1423
                        $categoryCodeFilter
1424
                    );
1425
                    $courses['not_category'] = self::filterByCategory(
1426
                        $courses['not_category'],
1427
                        $categoryCodeFilter
1428
                    );
1429
                }
1430
1431
                $this->tpl->assign('courses', $courses['not_category']);
1432
                $this->tpl->assign('categories', $courses['in_category']);
1433
1434
                $listCourse = $this->tpl->fetch($this->tpl->get_template($coursesWithCategoryTemplate));
1435
                $listCourse .= $this->tpl->fetch($this->tpl->get_template($coursesWithoutCategoryTemplate));
1436
            }
1437
1438
            $courseCount = count($specialCourses) + $coursesInCategoryCount + $coursesNotInCategoryCount;
1439
        }
1440
1441
        $sessions_with_category = '';
1442
        $sessions_with_no_category = '';
1443
        if ($showSessions) {
1444
            $coursesListSessionStyle = api_get_configuration_value('courses_list_session_title_link');
1445
            $coursesListSessionStyle = $coursesListSessionStyle === false ? 1 : $coursesListSessionStyle;
1446
            if (api_is_drh()) {
1447
                $coursesListSessionStyle = 1;
1448
            }
1449
1450
            $portalShowDescription = api_get_setting('show_session_description') === 'true';
1451
1452
            // Declared listSession variable
1453
            $listSession = [];
1454
            // Get timestamp in UTC to compare to DB values (in UTC by convention)
1455
            $session_now = strtotime(api_get_utc_datetime(time()));
1456
            if (is_array($session_categories)) {
1457
                foreach ($session_categories as $session_category) {
1458
                    $session_category_id = $session_category['session_category']['id'];
1459
                    // Sessions and courses that are not in a session category
1460
                    if (empty($session_category_id) &&
1461
                        isset($session_category['sessions'])
1462
                    ) {
1463
                        // Independent sessions
1464
                        foreach ($session_category['sessions'] as $session) {
1465
                            $session_id = $session['session_id'];
1466
1467
                            // Don't show empty sessions.
1468
                            if (count($session['courses']) < 1) {
1469
                                continue;
1470
                            }
1471
1472
                            // Courses inside the current session.
1473
                            $date_session_start = $session['access_start_date'];
1474
                            $date_session_end = $session['access_end_date'];
1475
                            $coachAccessStartDate = $session['coach_access_start_date'];
1476
                            $coachAccessEndDate = $session['coach_access_end_date'];
1477
                            $count_courses_session = 0;
1478
1479
                            // Loop course content
1480
                            $html_courses_session = [];
1481
                            $atLeastOneCourseIsVisible = false;
1482
                            $markAsOld = false;
1483
                            $markAsFuture = false;
1484
1485
                            foreach ($session['courses'] as $course) {
1486
                                $is_coach_course = api_is_coach($session_id, $course['real_id']);
1487
                                $allowed_time = 0;
1488
                                $allowedEndTime = true;
1489
1490
                                if (!empty($date_session_start)) {
1491
                                    if ($is_coach_course) {
1492
                                        $allowed_time = api_strtotime($coachAccessStartDate);
1493
                                    } else {
1494
                                        $allowed_time = api_strtotime($date_session_start);
1495
                                    }
1496
1497
                                    $endSessionToTms = null;
1498
                                    if (!isset($_GET['history'])) {
1499
                                        if (!empty($date_session_end)) {
1500
                                            if ($is_coach_course) {
1501
                                                // if coach end date is empty we use the default end date
1502
                                                if (empty($coachAccessEndDate)) {
1503
                                                    $endSessionToTms = api_strtotime($date_session_end);
1504
                                                    if ($session_now > $endSessionToTms) {
1505
                                                        $allowedEndTime = false;
1506
                                                    }
1507
                                                } else {
1508
                                                    $endSessionToTms = api_strtotime($coachAccessEndDate);
1509
                                                    if ($session_now > $endSessionToTms) {
1510
                                                        $allowedEndTime = false;
1511
                                                    }
1512
                                                }
1513
                                            } else {
1514
                                                $endSessionToTms = api_strtotime($date_session_end);
1515
                                                if ($session_now > $endSessionToTms) {
1516
                                                    $allowedEndTime = false;
1517
                                                }
1518
                                            }
1519
                                        }
1520
                                    }
1521
                                }
1522
1523
                                if ($showAllSessions) {
1524
                                    if ($allowed_time < $session_now && $allowedEndTime == false) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
1525
                                        $markAsOld = true;
1526
                                    }
1527
                                    if ($allowed_time > $session_now && $endSessionToTms > $session_now) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $endSessionToTms does not seem to be defined for all execution paths leading up to this point.
Loading history...
1528
                                        $markAsFuture = true;
1529
                                    }
1530
                                    $allowedEndTime = true;
1531
                                    $allowed_time = 0;
1532
                                }
1533
1534
                                if ($session_now >= $allowed_time && $allowedEndTime) {
1535
                                    // Read only and accessible.
1536
                                    $atLeastOneCourseIsVisible = true;
1537
1538
                                    if (api_get_setting('hide_courses_in_sessions') == 'false') {
1539
                                        $courseUserHtml = CourseManager::get_logged_user_course_html(
1540
                                            $course,
1541
                                            $session_id,
1542
                                            'session_course_item',
1543
                                            true,
1544
                                            $this->load_directories_preview
1545
                                        );
1546
                                        if (isset($courseUserHtml[1])) {
1547
                                            $course_session = $courseUserHtml[1];
1548
                                            $course_session['skill'] = isset($courseUserHtml['skill']) ? $courseUserHtml['skill'] : '';
1549
1550
                                            // Course option (show student progress)
1551
                                            // This code will add new variables (Progress, Score, Certificate)
1552
                                            if ($studentInfoProgress || $studentInfoScore || $studentInfoCertificate) {
1553
                                                if ($studentInfoProgress) {
1554
                                                    $progress = Tracking::get_avg_student_progress(
1555
                                                        $user_id,
1556
                                                        $course['course_code'],
1557
                                                        [],
1558
                                                        $session_id
1559
                                                    );
1560
                                                    $course_session['student_info']['progress'] = $progress === false ? null : $progress;
1561
                                                }
1562
1563
                                                if ($studentInfoScore) {
1564
                                                    $percentage_score = Tracking::get_avg_student_score(
1565
                                                        $user_id,
1566
                                                        $course['course_code'],
1567
                                                        [],
1568
                                                        $session_id
1569
                                                    );
1570
                                                    $course_session['student_info']['score'] = $percentage_score;
1571
                                                }
1572
1573
                                                if ($studentInfoCertificate) {
1574
                                                    $category = Category::load(
1575
                                                        null,
1576
                                                        null,
1577
                                                        $course['course_code'],
1578
                                                        null,
1579
                                                        null,
1580
                                                        $session_id
1581
                                                    );
1582
                                                    $course_session['student_info']['certificate'] = null;
1583
                                                    if (isset($category[0])) {
1584
                                                        if ($category[0]->is_certificate_available($user_id)) {
1585
                                                            $course_session['student_info']['certificate'] = Display::label(get_lang('Yes'), 'success');
1586
                                                        } else {
1587
                                                            $course_session['student_info']['certificate'] = Display::label(get_lang('No'));
1588
                                                        }
1589
                                                    }
1590
                                                }
1591
                                            }
1592
                                            $html_courses_session[] = $course_session;
1593
                                        }
1594
                                    }
1595
                                    $count_courses_session++;
1596
                                }
1597
                            }
1598
1599
                            // No courses to show.
1600
                            if ($atLeastOneCourseIsVisible == false) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
1601
                                if (empty($html_courses_session)) {
1602
                                    continue;
1603
                                }
1604
                            }
1605
1606
                            if ($count_courses_session > 0) {
1607
                                $params = [
1608
                                    'id' => $session_id
1609
                                ];
1610
                                $session_box = Display::get_session_title_box($session_id);
1611
                                $actions = api_get_path(WEB_CODE_PATH).'session/resume_session.php?id_session='.$session_id;
1612
                                $coachId = $session_box['id_coach'];
1613
                                $extraFieldValue = new ExtraFieldValue('session');
1614
                                $imageField = $extraFieldValue->get_values_by_handler_and_field_variable(
1615
                                    $session_id,
1616
                                    'image'
1617
                                );
1618
1619
                                $params['category_id'] = $session_box['category_id'];
1620
                                $params['title'] = $session_box['title'];
1621
                                $params['id_coach'] = $coachId;
1622
                                $params['coach_url'] = api_get_path(WEB_AJAX_PATH).'user_manager.ajax.php?a=get_user_popup&user_id='.$coachId;
1623
                                $params['coach_name'] = !empty($session_box['coach']) ? $session_box['coach'] : null;
1624
                                $params['coach_avatar'] = UserManager::getUserPicture(
1625
                                    $coachId,
1626
                                    USER_IMAGE_SIZE_SMALL
1627
                                );
1628
                                $params['date'] = $session_box['dates'];
1629
                                $params['image'] = isset($imageField['value']) ? $imageField['value'] : null;
1630
                                $params['duration'] = isset($session_box['duration']) ? ' '.$session_box['duration'] : null;
1631
                                $params['edit_actions'] = $actions;
1632
                                $params['show_description'] = $session_box['show_description'] == 1 && $portalShowDescription;
1633
                                $params['description'] = $session_box['description'];
1634
                                $params['visibility'] = $session_box['visibility'];
1635
                                $params['show_simple_session_info'] = $showSimpleSessionInfo;
1636
                                $params['course_list_session_style'] = $coursesListSessionStyle;
1637
                                $params['num_users'] = $session_box['num_users'];
1638
                                $params['num_courses'] = $session_box['num_courses'];
1639
                                $params['course_categories'] = CourseManager::getCourseCategoriesFromCourseList(
1640
                                    $html_courses_session
1641
                                );
1642
                                $params['courses'] = $html_courses_session;
1643
                                $params['is_old'] = $markAsOld;
1644
                                $params['is_future'] = $markAsFuture;
1645
1646
                                if ($showSimpleSessionInfo) {
1647
                                    $params['subtitle'] = self::getSimpleSessionDetails(
1648
                                        $session_box['coach'],
1649
                                        $session_box['dates'],
1650
                                        isset($session_box['duration']) ? $session_box['duration'] : null
1651
                                    );
1652
                                }
1653
1654
                                if ($gameModeIsActive) {
1655
                                    $params['stars'] =
1656
                                        GamificationUtils::getSessionStars($params['id'], $this->user_id);
1657
                                    $params['progress'] = GamificationUtils::getSessionProgress(
1658
                                        $params['id'],
1659
                                        $this->user_id
1660
                                    );
1661
                                    $params['points'] =
1662
                                        GamificationUtils::getSessionPoints($params['id'], $this->user_id);
1663
                                }
1664
                                $listSession[] = $params;
1665
                                $sessionCount++;
1666
                            }
1667
                        }
1668
                    } else {
1669
                        // All sessions included in
1670
                        $count_courses_session = 0;
1671
                        $html_sessions = '';
1672
                        if (isset($session_category['sessions'])) {
1673
                            foreach ($session_category['sessions'] as $session) {
1674
                                $session_id = $session['session_id'];
1675
1676
                                // Don't show empty sessions.
1677
                                if (count($session['courses']) < 1) {
1678
                                    continue;
1679
                                }
1680
1681
                                $date_session_start = $session['access_start_date'];
1682
                                $date_session_end = $session['access_end_date'];
1683
                                $coachAccessStartDate = $session['coach_access_start_date'];
1684
                                $coachAccessEndDate = $session['coach_access_end_date'];
1685
                                $html_courses_session = [];
1686
                                $count = 0;
1687
                                $markAsOld = false;
1688
                                $markAsFuture = false;
1689
1690
                                foreach ($session['courses'] as $course) {
1691
                                    $is_coach_course = api_is_coach($session_id, $course['real_id']);
1692
                                    $allowed_time = 0;
1693
                                    $allowedEndTime = true;
1694
1695
                                    if (!empty($date_session_start)) {
1696
                                        if ($is_coach_course) {
1697
                                            $allowed_time = api_strtotime($coachAccessStartDate);
1698
                                        } else {
1699
                                            $allowed_time = api_strtotime($date_session_start);
1700
                                        }
1701
1702
                                        if (!isset($_GET['history'])) {
1703
                                            if (!empty($date_session_end)) {
1704
                                                if ($is_coach_course) {
1705
                                                    // if coach end date is empty we use the default end date
1706
                                                    if (empty($coachAccessEndDate)) {
1707
                                                        $endSessionToTms = api_strtotime($date_session_end);
1708
                                                        if ($session_now > $endSessionToTms) {
1709
                                                            $allowedEndTime = false;
1710
                                                        }
1711
                                                    } else {
1712
                                                        $endSessionToTms = api_strtotime($coachAccessEndDate);
1713
                                                        if ($session_now > $endSessionToTms) {
1714
                                                            $allowedEndTime = false;
1715
                                                        }
1716
                                                    }
1717
                                                } else {
1718
                                                    $endSessionToTms = api_strtotime($date_session_end);
1719
                                                    if ($session_now > $endSessionToTms) {
1720
                                                        $allowedEndTime = false;
1721
                                                    }
1722
                                                }
1723
                                            }
1724
                                        }
1725
                                    }
1726
1727
                                    if ($showAllSessions) {
1728
                                        if ($allowed_time < $session_now && $allowedEndTime == false) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
1729
                                            $markAsOld = true;
1730
                                        }
1731
                                        if ($allowed_time > $session_now && $endSessionToTms > $session_now) {
1732
                                            $markAsFuture = true;
1733
                                        }
1734
                                        $allowedEndTime = true;
1735
                                        $allowed_time = 0;
1736
                                    }
1737
1738
                                    if ($session_now >= $allowed_time && $allowedEndTime) {
1739
                                        if (api_get_setting('hide_courses_in_sessions') === 'false') {
1740
                                            $c = CourseManager::get_logged_user_course_html(
1741
                                                $course,
1742
                                                $session_id,
1743
                                                'session_course_item'
1744
                                            );
1745
                                            $html_courses_session[] = $c[1];
1746
                                        }
1747
                                        $count_courses_session++;
1748
                                        $count++;
1749
                                    }
1750
                                }
1751
1752
                                $sessionParams = [];
1753
                                // Category
1754
                                if ($count > 0) {
1755
                                    $session_box = Display::get_session_title_box($session_id);
1756
                                    $sessionParams[0]['id'] = $session_id;
1757
                                    $sessionParams[0]['date'] = $session_box['dates'];
1758
                                    $sessionParams[0]['duration'] = isset($session_box['duration']) ? ' '.$session_box['duration'] : null;
1759
                                    $sessionParams[0]['course_list_session_style'] = $coursesListSessionStyle;
1760
                                    $sessionParams[0]['title'] = $session_box['title'];
1761
                                    $sessionParams[0]['subtitle'] = (!empty($session_box['coach']) ? $session_box['coach'].' | ' : '').$session_box['dates'];
1762
                                    $sessionParams[0]['show_actions'] = api_is_platform_admin();
1763
                                    $sessionParams[0]['courses'] = $html_courses_session;
1764
                                    $sessionParams[0]['show_simple_session_info'] = $showSimpleSessionInfo;
1765
                                    $sessionParams[0]['coach_name'] = !empty($session_box['coach']) ? $session_box['coach'] : null;
1766
                                    $sessionParams[0]['is_old'] = $markAsOld;
1767
                                    $sessionParams[0]['is_future'] = $markAsFuture;
1768
1769
                                    if ($showSimpleSessionInfo) {
1770
                                        $sessionParams[0]['subtitle'] = self::getSimpleSessionDetails(
1771
                                            $session_box['coach'],
1772
                                            $session_box['dates'],
1773
                                            isset($session_box['duration']) ? $session_box['duration'] : null
1774
                                        );
1775
                                    }
1776
1777
                                    $this->tpl->assign('session', $sessionParams);
1778
1779
                                    if ($viewGridCourses) {
1780
                                        $html_sessions .= $this->tpl->fetch(
1781
                                            $this->tpl->get_template('/user_portal/grid_session.tpl')
1782
                                        );
1783
                                    } else {
1784
                                        $html_sessions .= $this->tpl->fetch(
1785
                                            $this->tpl->get_template('user_portal/classic_session.tpl')
1786
                                        );
1787
                                    }
1788
                                    $sessionCount++;
1789
                                }
1790
                            }
1791
                        }
1792
1793
                        if ($count_courses_session > 0) {
1794
                            $categoryParams = [
1795
                                'id' => $session_category['session_category']['id'],
1796
                                'title' => $session_category['session_category']['name'],
1797
                                'show_actions' => api_is_platform_admin(),
1798
                                'subtitle' => '',
1799
                                'sessions' => $html_sessions
1800
                            ];
1801
1802
                            $session_category_start_date = $session_category['session_category']['date_start'];
1803
                            $session_category_end_date = $session_category['session_category']['date_end'];
1804
                            if ($session_category_start_date == '0000-00-00') {
1805
                                $session_category_start_date = '';
1806
                            }
1807
1808
                            if ($session_category_end_date == '0000-00-00') {
1809
                                $session_category_end_date = '';
1810
                            }
1811
1812
                            if (!empty($session_category_start_date) &&
1813
                                !empty($session_category_end_date)
1814
                            ) {
1815
                                $categoryParams['subtitle'] = sprintf(
1816
                                    get_lang('FromDateXToDateY'),
1817
                                    $session_category_start_date,
1818
                                    $session_category_end_date
1819
                                );
1820
                            } else {
1821
                                if (!empty($session_category_start_date)) {
1822
                                    $categoryParams['subtitle'] = get_lang('From').' '.$session_category_start_date;
1823
                                }
1824
1825
                                if (!empty($session_category_end_date)) {
1826
                                    $categoryParams['subtitle'] = get_lang('Until').' '.$session_category_end_date;
1827
                                }
1828
                            }
1829
1830
                            $this->tpl->assign('session_category', $categoryParams);
1831
                            $sessions_with_category .= $this->tpl->fetch(
1832
                                "{$this->tpl->templateFolder}/user_portal/session_category.tpl"
1833
                            );
1834
                        }
1835
                    }
1836
                }
1837
1838
                $allCoursesInSessions = [];
1839
                foreach ($listSession as $currentSession) {
1840
                    $coursesInSessions = $currentSession['courses'];
1841
                    unset($currentSession['courses']);
1842
                    foreach ($coursesInSessions as $coursesInSession) {
1843
                        $coursesInSession['session'] = $currentSession;
1844
                        $allCoursesInSessions[] = $coursesInSession;
1845
                    }
1846
                }
1847
1848
                $this->tpl->assign('all_courses', $allCoursesInSessions);
1849
                $this->tpl->assign('session', $listSession);
1850
                $this->tpl->assign('show_tutor', (api_get_setting('show_session_coach') === 'true' ? true : false));
1851
                $this->tpl->assign('gamification_mode', $gameModeIsActive);
1852
                $this->tpl->assign('remove_session_url', api_get_configuration_value('remove_session_url'));
1853
1854
                if ($viewGridCourses) {
1855
                    $sessions_with_no_category = $this->tpl->fetch(
1856
                        $this->tpl->get_template('/user_portal/grid_session.tpl')
1857
                    );
1858
                } else {
1859
                    $sessions_with_no_category = $this->tpl->fetch(
1860
                        $this->tpl->get_template('user_portal/classic_session.tpl')
1861
                    );
1862
                }
1863
            }
1864
        }
1865
1866
        return [
1867
            'courses' => $courseCompleteList,
1868
            'sessions' => $session_categories,
1869
            'html' => trim($specialCourseList.$sessions_with_category.$sessions_with_no_category.$listCourse),
1870
            'session_count' => $sessionCount,
1871
            'course_count' => $courseCount
1872
        ];
1873
    }
1874
1875
    /**
1876
     * Shows a welcome message when the user doesn't have any content in the course list
1877
     */
1878
    public function return_welcome_to_course_block()
1879
    {
1880
        $count_courses = CourseManager::count_courses();
1881
        $tpl = $this->tpl->get_template('layout/welcome_to_course.tpl');
1882
1883
        $course_catalog_url = api_get_path(WEB_CODE_PATH).'auth/courses.php';
1884
        $course_list_url = api_get_path(WEB_PATH).'user_portal.php';
1885
1886
        $this->tpl->assign('course_catalog_url', $course_catalog_url);
1887
        $this->tpl->assign('course_list_url', $course_list_url);
1888
        $this->tpl->assign('course_catalog_link', Display::url(get_lang('Here'), $course_catalog_url));
1889
        $this->tpl->assign('course_list_link', Display::url(get_lang('Here'), $course_list_url));
1890
        $this->tpl->assign('count_courses', $count_courses);
1891
1892
        return $this->tpl->fetch($tpl);
1893
    }
1894
1895
    /**
1896
     * @return array
1897
     */
1898
    public function return_hot_courses()
1899
    {
1900
        return CourseManager::return_hot_courses(30, 6);
1901
    }
1902
1903
    /**
1904
     * UserPortal view for session, return the HTML of the course list
1905
     * @param $user_id
1906
     * @return string
1907
     */
1908
    public function returnCoursesAndSessionsViewBySession($user_id)
1909
    {
1910
        $sessionCount = 0;
1911
        $courseCount = 0;
1912
        $load_history = (isset($_GET['history']) && intval($_GET['history']) == 1) ? true : false;
1913
1914
        if ($load_history) {
1915
            // Load sessions in category in *history*
1916
            $session_categories = UserManager::get_sessions_by_category($user_id, true);
1917
        } else {
1918
            // Load sessions in category
1919
            $session_categories = UserManager::get_sessions_by_category($user_id, false);
1920
        }
1921
1922
        $html = '';
1923
        $loadDirs = $this->load_directories_preview;
1924
1925
        // If we're not in the history view...
1926
        $listCoursesInfo = [];
1927
        if (!isset($_GET['history'])) {
1928
            // Display special courses
1929
            $specialCoursesResult = CourseManager::returnSpecialCourses(
1930
                $user_id,
1931
                $loadDirs
1932
            );
1933
            $specialCourses = $specialCoursesResult;
1934
1935
            if ($specialCourses) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $specialCourses of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
1936
                $this->tpl->assign('courses', $specialCourses);
1937
                $html = $this->tpl->fetch(
1938
                    $this->tpl->get_template('/user_portal/classic_courses_without_category.tpl')
1939
                );
1940
            }
1941
1942
            // Display courses
1943
            // [code=>xxx, real_id=>000]
1944
            $listCourses = CourseManager::get_courses_list_by_user_id(
1945
                $user_id,
1946
                false
1947
            );
1948
1949
            foreach ($listCourses as $i => $listCourseCodeId) {
1950
                if (isset($listCourseCodeId['special_course'])) {
1951
                    continue;
1952
                }
1953
                $courseCategory = CourseManager::getUserCourseCategoryForCourse(
1954
                    $user_id,
1955
                    $listCourseCodeId['real_id']
1956
                );
1957
1958
                $userCatTitle = '';
1959
                $userCategoryId = 0;
1960
                if ($courseCategory) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $courseCategory of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
1961
                    $userCategoryId = $courseCategory['user_course_cat'];
1962
                    $userCatTitle = $courseCategory['title'];
1963
                }
1964
1965
                $listCourse = api_get_course_info_by_id($listCourseCodeId['real_id']);
1966
                $listCoursesInfo[] = [
1967
                    'course' => $listCourse,
1968
                    'code' => $listCourseCodeId['code'],
1969
                    'id' => $listCourseCodeId['real_id'],
1970
                    'title' => $listCourse['title'],
1971
                    'userCatId' => $userCategoryId,
1972
                    'userCatTitle' => $userCatTitle
1973
                ];
1974
                $courseCount++;
1975
            }
1976
            usort($listCoursesInfo, 'self::compareByCourse');
1977
        }
1978
1979
        if (is_array($session_categories)) {
1980
            // all courses that are in a session
1981
            $listCoursesInSession = SessionManager::getNamedSessionCourseForCoach($user_id);
1982
        }
1983
1984
        // we got all courses
1985
        // for each user category, sorted alphabetically, display courses
1986
        $listUserCategories = CourseManager::get_user_course_categories($user_id);
1987
        $listCoursesAlreadyDisplayed = [];
1988
        uasort($listUserCategories, "self::compareListUserCategory");
1989
        $listUserCategories[0] = '';
1990
1991
        $html .= '<div class="session-view-block">';
1992
        foreach ($listUserCategories as $userCategoryId => $userCat) {
1993
            // add user category
1994
            $userCategoryHtml = '';
1995
            if ($userCategoryId != 0) {
1996
                $userCategoryHtml = '<div class="session-view-well ">';
1997
                $userCategoryHtml .= self::getHtmlForUserCategory($userCategoryId, $userCat['title']);
1998
            }
1999
            // look for course in this userCat in session courses : $listCoursesInSession
2000
            $htmlCategory = '';
2001
            if (isset($listCoursesInSession[$userCategoryId])) {
2002
                // list of courses in this user cat
2003
                foreach ($listCoursesInSession[$userCategoryId]['courseInUserCatList'] as $i => $listCourse) {
2004
                    // add course
2005
                    $listCoursesAlreadyDisplayed[$listCourse['courseId']] = 1;
2006
                    if ($userCategoryId == 0) {
2007
                        $htmlCategory .= '<div class="panel panel-default">';
2008
                    } else {
2009
                        $htmlCategory .= '<div class="panel panel-default">';
2010
                    }
2011
                    $htmlCategory .= '<div class="panel-body">';
2012
                    $coursesInfo = $listCourse['course'];
2013
2014
                    $htmlCategory .= self::getHtmlForCourse(
2015
                        $coursesInfo,
2016
                        $userCategoryId,
2017
                        1,
2018
                        $loadDirs
2019
                    );
2020
                    // list of session category
2021
                    $htmlSessionCategory = '<div class="session-view-row" style="display:none;" id="courseblock-'.$coursesInfo['real_id'].'">';
2022
                    foreach ($listCourse['sessionCatList'] as $j => $listCategorySession) {
2023
                        // add session category
2024
                        $htmlSessionCategory .= self::getHtmlSessionCategory(
2025
                            $listCategorySession['catSessionId'],
2026
                            $listCategorySession['catSessionName']
2027
                        );
2028
                        // list of session
2029
                        $htmlSession = ''; // start
2030
                        foreach ($listCategorySession['sessionList'] as $k => $listSession) {
2031
                            // add session
2032
                            $htmlSession .= '<div class="session-view-row">';
2033
                            $htmlSession .= self::getHtmlForSession(
2034
                                $listSession['sessionId'],
2035
                                $listSession['sessionName'],
2036
                                $listCategorySession['catSessionId'],
2037
                                $coursesInfo
2038
                            );
2039
                            $htmlSession .= '</div>';
2040
                            $sessionCount++;
2041
                        }
2042
                        $htmlSession .= ''; // end session block
2043
                        $htmlSessionCategory .= $htmlSession;
2044
                    }
2045
                    $htmlSessionCategory .= '</div>'; // end session cat block
2046
                    $htmlCategory .= $htmlSessionCategory.'</div></div>';
2047
                    $htmlCategory .= ''; // end course block
2048
                }
2049
                $userCategoryHtml .= $htmlCategory;
2050
            }
2051
2052
            // look for courses in this userCat in not in session courses : $listCoursesInfo
2053
            // if course not already added
2054
            $htmlCategory = '';
2055
            foreach ($listCoursesInfo as $i => $listCourse) {
2056
                if ($listCourse['userCatId'] == $userCategoryId && !isset($listCoursesAlreadyDisplayed[$listCourse['id']])) {
2057
                    if ($userCategoryId != 0) {
2058
                        $htmlCategory .= '<div class="panel panel-default">';
2059
                    } else {
2060
                        $htmlCategory .= '<div class="panel panel-default">';
2061
                    }
2062
2063
                    $htmlCategory .= '<div class="panel-body">';
2064
                    $htmlCategory .= self::getHtmlForCourse(
2065
                        $listCourse['course'],
2066
                        $userCategoryId,
2067
                        0,
2068
                        $loadDirs
2069
                    );
2070
                    $htmlCategory .= '</div></div>';
2071
                }
2072
            }
2073
            $htmlCategory .= '';
2074
            $userCategoryHtml .= $htmlCategory; // end user cat block
2075
            if ($userCategoryId != 0) {
2076
                $userCategoryHtml .= '</div>';
2077
            }
2078
            $html .= $userCategoryHtml; //
2079
        }
2080
        $html .= '</div>';
2081
2082
        return [
2083
            'html' => $html,
2084
            'sessions' => $session_categories,
2085
            'courses' => $listCoursesInfo,
2086
            'session_count' => $sessionCount,
2087
            'course_count' => $courseCount
2088
        ];
2089
    }
2090
2091
    /**
2092
     * Return HTML code for personal user course category
2093
     * @param $id
2094
     * @param $title
2095
     * @return string
2096
     */
2097
    private static function getHtmlForUserCategory($id, $title)
2098
    {
2099
        if ($id == 0) {
2100
            return '';
2101
        }
2102
        $icon = Display::return_icon(
2103
            'folder_yellow.png',
2104
            $title,
2105
            ['class' => 'sessionView'],
2106
            ICON_SIZE_LARGE
2107
        );
2108
2109
        return "<div class='session-view-user-category'>$icon<span>$title</span></div>";
2110
    }
2111
2112
    /**
2113
     * return HTML code for course display in session view
2114
     * @param array $courseInfo
2115
     * @param $userCategoryId
2116
     * @param bool $displayButton
2117
     * @param $loadDirs
2118
     * @return string
2119
     */
2120
    private static function getHtmlForCourse(
2121
        $courseInfo,
2122
        $userCategoryId,
2123
        $displayButton = false,
2124
        $loadDirs
2125
    ) {
2126
        if (empty($courseInfo)) {
2127
            return '';
2128
        }
2129
2130
        $id = $courseInfo['real_id'];
2131
        $title = $courseInfo['title'];
2132
        $code = $courseInfo['code'];
2133
2134
        $class = 'session-view-lvl-6';
2135
        if ($userCategoryId != 0 && !$displayButton) {
2136
            $class = 'session-view-lvl-7';
2137
        }
2138
2139
        $class2 = 'session-view-lvl-6';
2140
        if ($displayButton || $userCategoryId != 0) {
2141
            $class2 = 'session-view-lvl-7';
2142
        }
2143
2144
        $button = '';
2145
        if ($displayButton) {
2146
            $button = '<input id="session-view-button-'.intval($id).'" class="btn btn-default btn-sm" type="button" onclick="hideUnhide(\'courseblock-'.intval($id).'\', \'session-view-button-'.intval($id).'\', \'+\', \'-\')" value="+" />';
2147
        }
2148
2149
        $icon = Display::return_icon(
2150
            'blackboard.png',
2151
            $title,
2152
            ['class' => 'sessionView'],
2153
            ICON_SIZE_LARGE
2154
        );
2155
2156
        $courseLink = $courseInfo['course_public_url'].'?id_session=0';
2157
2158
        // get html course params
2159
        $courseParams = CourseManager::getCourseParamsForDisplay($id, $loadDirs);
2160
        $teachers = '';
2161
        $rightActions = '';
2162
2163
        // teacher list
2164
        if (!empty($courseParams['teachers'])) {
2165
            $teachers = '<p class="'.$class2.' view-by-session-teachers">'.$courseParams['teachers'].'</p>';
2166
        }
2167
2168
        // notification
2169
        if (!empty($courseParams['right_actions'])) {
2170
            $rightActions = '<div class="pull-right">'.$courseParams['right_actions'].'</div>';
2171
        }
2172
2173
        $notifications = isset($courseParams['notifications']) ? $courseParams['notifications'] : '';
2174
2175
        return "<div>
2176
                    $button
2177
                    <span class='$class'>$icon
2178
                        <a class='sessionView' href='$courseLink'>$title</a>
2179
                    </span> 
2180
                    $notifications 
2181
                    $rightActions 
2182
                </div>
2183
                $teachers";
2184
    }
2185
2186
    /**
2187
     * return HTML code for session category
2188
     * @param $id
2189
     * @param $title
2190
     * @return string
2191
     */
2192
    private static function getHtmlSessionCategory($id, $title)
2193
    {
2194
        if ($id == 0) {
2195
            return '';
2196
        }
2197
2198
        $icon = Display::return_icon(
2199
            'folder_blue.png',
2200
            $title,
2201
            ['class' => 'sessionView'],
2202
            ICON_SIZE_LARGE
2203
        );
2204
2205
        return "<div class='session-view-session-category'>
2206
                <span class='session-view-lvl-2'>
2207
                    $icon
2208
                    <span>$title</span>
2209
                </span>
2210
                </div>";
2211
    }
2212
2213
    /**
2214
     * return HTML code for session
2215
     * @param int $id session id
2216
     * @param string $title session title
2217
     * @param int $categorySessionId
2218
     * @param array $courseInfo
2219
     *
2220
     * @return string
2221
     */
2222
    private static function getHtmlForSession($id, $title, $categorySessionId, $courseInfo)
2223
    {
2224
        $html = '';
2225
        if ($categorySessionId == 0) {
2226
            $class1 = 'session-view-lvl-2'; // session
2227
            $class2 = 'session-view-lvl-4'; // got to course in session link
2228
        } else {
2229
            $class1 = 'session-view-lvl-3'; // session
2230
            $class2 = 'session-view-lvl-5'; // got to course in session link
2231
        }
2232
2233
        $icon = Display::return_icon(
2234
            'blackboard_blue.png',
2235
            $title,
2236
            ['class' => 'sessionView'],
2237
            ICON_SIZE_LARGE
2238
        );
2239
        $courseLink = $courseInfo['course_public_url'].'?id_session='.intval($id);
2240
2241
        $html .= "<span class='$class1 session-view-session'>$icon$title</span>";
2242
        $html .= '<div class="'.$class2.' session-view-session-go-to-course-in-session">
2243
                  <a class="" href="'.$courseLink.'">'.get_lang('GoToCourseInsideSession').'</a></div>';
2244
2245
        return '<div>'.$html.'</div>';
2246
    }
2247
2248
    /**
2249
     * @param $listA
2250
     * @param $listB
2251
     * @return int
2252
     */
2253
    private static function compareByCourse($listA, $listB)
2254
    {
2255
        if ($listA['userCatTitle'] == $listB['userCatTitle']) {
2256
            if ($listA['title'] == $listB['title']) {
2257
                return 0;
2258
            }
2259
2260
            if ($listA['title'] > $listB['title']) {
2261
                return 1;
2262
            }
2263
2264
            return -1;
2265
        }
2266
2267
        if ($listA['userCatTitle'] > $listB['userCatTitle']) {
2268
            return 1;
2269
        }
2270
2271
        return -1;
2272
    }
2273
2274
    /**
2275
     * @param $listA
2276
     * @param $listB
2277
     * @return int
2278
     */
2279
    public static function compareListUserCategory($listA, $listB)
2280
    {
2281
        if ($listA['title'] == $listB['title']) {
2282
            return 0;
2283
        }
2284
2285
        if ($listA['title'] > $listB['title']) {
2286
            return 1;
2287
        }
2288
2289
        return -1;
2290
    }
2291
2292
    /**
2293
     * @param $view
2294
     * @param $userId
2295
     */
2296
    public static function setDefaultMyCourseView($view, $userId)
2297
    {
2298
        setcookie('defaultMyCourseView'.$userId, $view);
2299
    }
2300
2301
    /**
2302
     * Get the session coach name, duration or dates
2303
     * when $_configuration['show_simple_session_info'] is enabled
2304
     * @param string $coachName
2305
     * @param string $dates
2306
     * @param string|null $duration Optional
2307
     * @return string
2308
     */
2309
    private static function getSimpleSessionDetails($coachName, $dates, $duration = null)
2310
    {
2311
        $strDetails = [];
2312
        if (!empty($coachName)) {
2313
            $strDetails[] = $coachName;
2314
        }
2315
2316
        $strDetails[] = !empty($duration) ? $duration : $dates;
2317
2318
        return implode(' | ', $strDetails);
2319
    }
2320
2321
    /**
2322
     * @param int $userId
2323
     * @return array
2324
     */
2325
    public function returnCourseCategoryListFromUser($userId)
2326
    {
2327
        $sessionCount = 0;
2328
        $courseList = CourseManager::get_courses_list_by_user_id($userId);
2329
        $categoryCodes = CourseManager::getCourseCategoriesFromCourseList($courseList);
2330
        $categories = [];
2331
        foreach ($categoryCodes as $categoryCode) {
2332
            $categories[] = CourseCategory::getCategory($categoryCode);
2333
        }
2334
2335
        $template = new Template('', false, false, false, true, false, false);
2336
        $layout = $template->get_template('user_portal/course_categories.tpl');
2337
        $template->assign('course_categories', $categories);
2338
2339
        return [
2340
            'courses' => $courseList,
2341
            'html' => $template->fetch($layout),
2342
            'course_count' => count($courseList),
2343
            'session_count' => $sessionCount
2344
        ];
2345
    }
2346
2347
    /**
2348
     * Filter the course list by category code
2349
     * @param array $courseList course list
2350
     * @param string $categoryCode
2351
     * @return array
2352
     */
2353
    private static function filterByCategory($courseList, $categoryCode)
2354
    {
2355
        return array_filter($courseList, function ($courseInfo) use ($categoryCode) {
2356
            if (isset($courseInfo['category_code']) &&
2357
                $courseInfo['category_code'] === $categoryCode
2358
            ) {
2359
                return true;
2360
            }
2361
2362
            return false;
2363
        });
2364
    }
2365
2366
    /**
2367
     * Set grade book dependency progress bar see BT#13099
2368
     * @param $userId
2369
     *
2370
     * @return bool
2371
     */
2372
    public function setGradeBookDependencyBar($userId)
2373
    {
2374
        $allow = api_get_configuration_value('gradebook_dependency');
2375
2376
        if (api_is_anonymous()) {
2377
            return false;
2378
        }
2379
2380
        if ($allow) {
2381
            $courseAndSessions = $this->returnCoursesAndSessions(
2382
                $userId,
2383
                false,
2384
                '',
2385
                false,
2386
                false
2387
            );
2388
2389
            $courseList = api_get_configuration_value('gradebook_dependency_mandatory_courses');
2390
            $courseList = isset($courseList['courses']) ? $courseList['courses'] : [];
2391
            $mandatoryCourse = [];
2392
            if (!empty($courseList)) {
2393
                foreach ($courseList as $courseId) {
2394
                    $courseInfo = api_get_course_info_by_id($courseId);
2395
                    $mandatoryCourse[] = $courseInfo['code'];
2396
                }
2397
            }
2398
2399
            // @todo improve calls of course info
2400
            $subscribedCourses = !empty($courseAndSessions['courses']) ? $courseAndSessions['courses'] : [];
2401
            $mainCategoryList = [];
2402
            foreach ($subscribedCourses as $courseInfo) {
2403
                $courseCode = $courseInfo['code'];
2404
                $categories = Category::load(null, null, $courseCode);
2405
                /** @var Category $category */
2406
                $category = !empty($categories[0]) ? $categories[0] : [];
2407
                if (!empty($category)) {
2408
                    $mainCategoryList[] = $category;
2409
                }
2410
            }
2411
2412
            $result20 = 0;
2413
            $result80 = 0;
2414
            $countCoursesPassedNoDependency = 0;
2415
            /** @var Category $category */
2416
            foreach ($mainCategoryList as $category) {
2417
                $userFinished = Category::userFinishedCourse(
2418
                    $userId,
2419
                    $category,
2420
                    true
2421
                );
2422
2423
                if ($userFinished) {
2424
                    if (in_array($category->get_course_code(), $mandatoryCourse)) {
2425
                        if ($result20 < 20) {
2426
                            $result20 += 10;
2427
                        }
2428
                    } else {
2429
                        $countCoursesPassedNoDependency++;
2430
                        if ($result80 < 80) {
2431
                            $result80 += 10;
2432
                        }
2433
                    }
2434
                }
2435
            }
2436
2437
            $finalResult = $result20 + $result80;
2438
2439
            $gradeBookList = api_get_configuration_value('gradebook_badge_sidebar');
2440
            $gradeBookList = isset($gradeBookList['gradebooks']) ? $gradeBookList['gradebooks'] : [];
2441
            $badgeList = [];
2442
            foreach ($gradeBookList as $id) {
2443
                $categories = Category::load($id);
2444
                /** @var Category $category */
2445
                $category = !empty($categories[0]) ? $categories[0] : [];
2446
                $badgeList[$id]['name'] = $category->get_name();
2447
                $badgeList[$id]['finished'] = false;
2448
                $badgeList[$id]['skills'] = [];
2449
                if (!empty($category)) {
2450
                    $minToValidate = $category->getMinimumToValidate();
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $minToValidate is correct as $category->getMinimumToValidate() targeting Category::getMinimumToValidate() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
2451
                    $dependencies = $category->getCourseListDependency();
2452
                    $gradeBooksToValidateInDependence = $category->getGradeBooksToValidateInDependence();
2453
                    $countDependenciesPassed = 0;
2454
                    foreach ($dependencies as $courseId) {
2455
                        $courseInfo = api_get_course_info_by_id($courseId);
2456
                        $courseCode = $courseInfo['code'];
2457
                        $categories = Category::load(null, null, $courseCode);
2458
                        $subCategory = !empty($categories[0]) ? $categories[0] : null;
2459
                        if (!empty($subCategory)) {
2460
                            $score = Category::userFinishedCourse(
2461
                                $userId,
2462
                                $subCategory,
2463
                                true
2464
                            );
2465
                            if ($score) {
2466
                                $countDependenciesPassed++;
2467
                            }
2468
                        }
2469
                    }
2470
2471
                    $userFinished =
2472
                        $countDependenciesPassed >= $gradeBooksToValidateInDependence &&
2473
                        $countCoursesPassedNoDependency >= $minToValidate
2474
                    ;
2475
2476
                    if ($userFinished) {
2477
                        $badgeList[$id]['finished'] = true;
2478
                    }
2479
2480
                    $objSkill = new Skill();
2481
                    $skills = $category->get_skills();
2482
                    $skillList = [];
2483
                    foreach ($skills as $skill) {
2484
                        $skillList[] = $objSkill->get($skill['id']);
2485
                    }
2486
                    $badgeList[$id]['skills'] = $skillList;
2487
                }
2488
            }
2489
2490
            $this->tpl->assign(
2491
                'grade_book_sidebar',
2492
                true
2493
            );
2494
2495
            $this->tpl->assign(
2496
                'grade_book_progress',
2497
                $finalResult
2498
            );
2499
            $this->tpl->assign('grade_book_badge_list', $badgeList);
2500
2501
            return true;
2502
        }
2503
2504
        return false;
2505
    }
2506
}
2507