returnNotificationMenu()   C
last analyzed

Complexity

Conditions 16
Paths 64

Size

Total Lines 50
Code Lines 33

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 16
eloc 33
nc 64
nop 0
dl 0
loc 50
rs 5.5666
c 0
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/* For licensing terms, see /license.txt */
3
4
use Chamilo\CoreBundle\Component\Utils\ChamiloApi;
5
use ChamiloSession as Session;
6
7
/**
8
 * Code.
9
 *
10
 * @todo use globals or parameters or add this file in the template
11
 *
12
 * @package chamilo.include
13
 */
14
15
/**
16
 * Determines the possible tabs (=sections) that are available.
17
 * This function is used when creating the tabs in the third header line and
18
 * all the sections that do not appear there (as determined by the
19
 * platform admin on the Dokeos configuration settings page)
20
 * will appear in the right hand menu that appears on several other pages.
21
 *
22
 * @return array containing all the possible tabs
23
 *
24
 * @author Patrick Cool <[email protected]>, Ghent University
25
 */
26
function get_tabs($courseId = null)
27
{
28
    $courseInfo = api_get_course_info($courseId);
29
30
    $navigation = [];
31
32
    // Campus Homepage
33
    $navigation[SECTION_CAMPUS]['url'] = api_get_path(WEB_PATH).'index.php';
34
    $navigation[SECTION_CAMPUS]['title'] = get_lang('CampusHomepage');
35
    $navigation[SECTION_CAMPUS]['key'] = 'homepage';
36
    $navigation[SECTION_CAMPUS]['icon'] = 'homepage.png';
37
38
    $navigation[SECTION_CATALOG]['url'] = api_get_path(WEB_PATH).'main/auth/courses.php';
39
    $navigation[SECTION_CATALOG]['title'] = get_lang('Courses');
40
    $navigation[SECTION_CATALOG]['key'] = 'catalog';
41
    $navigation[SECTION_CATALOG]['icon'] = 'catalog.png';
42
43
    // My Courses
44
    if (api_is_allowed_to_create_course()) {
45
        // Link to my courses for teachers
46
        $navigation['mycourses']['url'] = api_get_path(WEB_PATH).'user_portal.php?nosession=true';
47
    } else {
48
        // Link to my courses for students
49
        $navigation['mycourses']['url'] = api_get_path(WEB_PATH).'user_portal.php';
50
    }
51
    $navigation['mycourses']['title'] = get_lang('MyCourses');
52
    $navigation['mycourses']['key'] = 'my-course';
53
    $navigation['mycourses']['icon'] = 'my-course.png';
54
55
    // My Profile
56
    $navigation['myprofile']['url'] = api_get_path(WEB_CODE_PATH).'auth/profile.php'
57
        .(!empty($courseInfo['path']) ? '?coursePath='.$courseInfo['path'].'&amp;courseCode='.$courseInfo['official_code'] : '');
58
    $navigation['myprofile']['title'] = get_lang('ModifyProfile');
59
    $navigation['myprofile']['key'] = 'profile';
60
    $navigation['myprofile']['icon'] = 'profile.png';
61
    // Link to my agenda
62
    $navigation['myagenda']['url'] = api_get_path(WEB_CODE_PATH).'calendar/agenda_js.php?type=personal';
63
    $navigation['myagenda']['title'] = get_lang('MyAgenda');
64
    $navigation['myagenda']['key'] = 'agenda';
65
    $navigation['myagenda']['icon'] = 'agenda.png';
66
67
    // Gradebook
68
    if (api_get_setting('gradebook_enable') == 'true') {
69
        $navigation['mygradebook']['url'] = api_get_path(WEB_CODE_PATH)
70
            .'gradebook/gradebook.php'
71
            .(!empty($courseInfo['path']) ? '?coursePath='.$courseInfo['path'].'&amp;courseCode='.$courseInfo['official_code'] : '');
72
        $navigation['mygradebook']['title'] = get_lang('MyGradebook');
73
        $navigation['mygradebook']['key'] = 'gradebook';
74
        $navigation['mygradebook']['icon'] = 'gradebook.png';
75
    }
76
77
    // Reporting
78
    if (api_is_teacher() || api_is_drh() || api_is_session_admin()) {
79
        // Link to my space
80
        $navigation['session_my_space']['url'] = api_get_path(WEB_CODE_PATH).'mySpace/'
81
            .(api_is_drh() ? 'session.php' : '');
82
        $navigation['session_my_space']['title'] = get_lang('MySpace');
83
        $navigation['session_my_space']['key'] = 'my-space';
84
        $navigation['session_my_space']['icon'] = 'my-space.png';
85
    } else {
86
        if (api_is_student_boss()) {
87
            $navigation['session_my_space']['url'] = api_get_path(WEB_CODE_PATH).'mySpace/student.php';
88
            $navigation['session_my_space']['title'] = get_lang('MySpace');
89
            $navigation['session_my_space']['key'] = 'my-space';
90
            $navigation['session_my_space']['icon'] = 'my-space.png';
91
        } else {
92
            $hideMyProgressTab = api_get_configuration_value('hide_my_progress_tab');
93
            if (true !== $hideMyProgressTab) {
94
                $navigation['session_my_progress']['url'] = api_get_path(WEB_CODE_PATH);
95
                // Link to my progress
96
                switch (api_get_setting('gamification_mode')) {
97
                    case 1:
98
                        $navigation['session_my_progress']['url'] .= 'gamification/my_progress.php';
99
                        break;
100
                    default:
101
                        $navigation['session_my_progress']['url'] .= 'auth/my_progress.php';
102
                }
103
104
                $navigation['session_my_progress']['title'] = get_lang('MyProgress');
105
                $navigation['session_my_progress']['key'] = 'my-progress';
106
                $navigation['session_my_progress']['icon'] = 'my-progress.png';
107
            }
108
        }
109
    }
110
111
    // Social
112
    if (api_get_setting('allow_social_tool') == 'true') {
113
        $navigation['social']['url'] = api_get_path(WEB_CODE_PATH).'social/home.php';
114
        $navigation['social']['title'] = get_lang('SocialNetwork');
115
        $navigation['social']['key'] = 'social-network';
116
        $navigation['social']['icon'] = 'social-network.png';
117
    }
118
119
    // Dashboard
120
    if (api_is_platform_admin() || api_is_drh() || api_is_session_admin()) {
121
        $navigation['dashboard']['url'] = api_get_path(WEB_CODE_PATH).'dashboard/index.php';
122
        $navigation['dashboard']['title'] = get_lang('Dashboard');
123
        $navigation['dashboard']['key'] = 'dashboard';
124
        $navigation['dashboard']['icon'] = 'dashboard.png';
125
    }
126
127
    // Custom Tabs See BT#7180
128
    $customTabs = getCustomTabs();
129
    if (!empty($customTabs)) {
130
        foreach ($customTabs as $tab) {
131
            if (api_get_setting($tab['variable'], $tab['subkey']) == 'true') {
132
                if (!empty($tab['comment']) && $tab['comment'] !== 'ShowTabsComment') {
133
                    $navigation[$tab['subkey']]['url'] = $tab['comment'];
134
                    // $tab['title'] value must be included in trad4all.inc.php
135
                    $navigation[$tab['subkey']]['title'] = get_lang($tab['title']);
136
                    $navigation[$tab['subkey']]['key'] = $tab['subkey'];
137
                }
138
            }
139
        }
140
    }
141
    // End Custom Tabs
142
143
    // Platform administration
144
    if (api_is_platform_admin(true)) {
145
        $navigation['platform_admin']['url'] = api_get_path(WEB_CODE_PATH).'admin/';
146
        $navigation['platform_admin']['title'] = get_lang('PlatformAdmin');
147
        $navigation['platform_admin']['key'] = 'admin';
148
        $navigation['platform_admin']['icon'] = 'admin.png';
149
    }
150
151
    return $navigation;
152
}
153
154
/**
155
 * This function returns the custom tabs.
156
 *
157
 * @return array
158
 */
159
function getCustomTabs()
160
{
161
    static $customTabs = null;
162
163
    if ($customTabs !== null) {
164
        return $customTabs;
165
    }
166
167
    $urlId = api_get_current_access_url_id();
168
    $isStudent = api_is_student();
169
    $cacheAvailable = api_get_configuration_value('apc');
170
    if ($cacheAvailable === true) {
171
        $apcVar = api_get_configuration_value('apc_prefix').'custom_tabs_url_student_'.($isStudent ? '1' : '0');
172
        if (apcu_exists($apcVar)) {
173
            return apcu_fetch($apcVar);
174
        }
175
    }
176
    $tableSettingsCurrent = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
177
    $sql = "SELECT * FROM $tableSettingsCurrent
178
            WHERE
179
                variable = 'show_tabs' AND
180
                subkey LIKE 'custom_tab_%' AND access_url = $urlId ";
181
    $result = Database::query($sql);
182
    $customTabs = [];
183
    while ($row = Database::fetch_assoc($result)) {
184
        $shouldAdd = true;
185
        if (strpos($row['subkey'], Plugin::TAB_FILTER_NO_STUDENT) !== false && $isStudent) {
186
            $shouldAdd = false;
187
        } elseif (strpos($row['subkey'], Plugin::TAB_FILTER_ONLY_STUDENT) !== false && !$isStudent) {
188
            $shouldAdd = false;
189
        }
190
191
        if ($shouldAdd) {
192
            $customTabs[] = $row;
193
        }
194
    }
195
    if ($cacheAvailable === true) {
196
        $apcVar = api_get_configuration_value('apc_prefix').'custom_tabs_url_'.$urlId.'_student_'.($isStudent ? '1' : '0');
197
        apcu_store($apcVar, $customTabs, 15);
198
    }
199
200
    return $customTabs;
201
}
202
203
/**
204
 * Return the active logo of the portal, based on a series of settings.
205
 *
206
 * @param string $theme      The name of the theme folder from web/css/themes/
207
 * @param bool   $responsive add class img-responsive
208
 *
209
 * @return string HTML string with logo as an HTML element
210
 */
211
function return_logo($theme = '', $responsive = true)
212
{
213
    $siteName = api_get_setting('siteName');
214
    $class = 'img-responsive';
215
    if (!$responsive) {
216
        $class = '';
217
    }
218
219
    if (api_get_configuration_value('mail_header_from_custom_course_logo') == true) {
220
        // check if current page is a course page
221
        $courseCode = api_get_course_id();
222
223
        if (!empty($courseCode)) {
224
            $course = api_get_course_info($courseCode);
225
            if (!empty($course) && !empty($course['course_email_image_large'])) {
226
                $image = \Display::img(
227
                    $course['course_email_image_large'],
228
                    $course['name'],
229
                    [
230
                        'title' => $course['name'],
231
                        'class' => $class,
232
                        'id' => 'header-logo',
233
                    ]
234
                );
235
236
                return \Display::url($image, $course['course_public_url']);
237
            }
238
        }
239
    }
240
241
    return ChamiloApi::getPlatformLogo(
242
        $theme,
243
        [
244
            'title' => $siteName,
245
            'class' => $class,
246
            'id' => 'header-logo',
247
        ]
248
    );
249
}
250
251
/**
252
 * Check if user have access to "who is online" page.
253
 *
254
 * @param int $userId   The user for whom we want to check
255
 * @param int $courseId The course ID for if we want the number of users in the course. Set to 0 for "out of a course context". Leave empty if you want the PHP session info to be used.
256
 *
257
 * @return bool
258
 */
259
function accessToWhoIsOnline($userId = null, $courseId = null)
260
{
261
    if (empty($userId)) {
262
        $userId = api_get_user_id();
263
    }
264
    // If we received 0, treat it as "no course" instead of searching again
265
    if ($courseId === null) {
266
        $courseId = api_get_course_int_id();
267
    }
268
    $access = false;
269
270
    if (true === api_get_configuration_value('whoisonline_only_for_admin') && !api_is_platform_admin()) {
271
        return false;
272
    }
273
274
    if ((api_get_setting('showonline', 'world') == 'true' && !$userId) ||
275
        (api_get_setting('showonline', 'users') == 'true' && $userId) ||
276
        (api_get_setting('showonline', 'course') == 'true' && $userId && $courseId)
277
    ) {
278
        $access = true;
279
        $profileList = api_get_configuration_value('allow_online_users_by_status');
280
        if (!empty($profileList) && isset($profileList['status'])) {
281
            $userInfo = api_get_user_info($userId);
282
            if ($userInfo['is_admin']) {
283
                $userInfo['status'] = PLATFORM_ADMIN;
284
            }
285
            $profileList = $profileList['status'];
286
            $access = false;
287
            if (in_array($userInfo['status'], $profileList)) {
288
                $access = true;
289
            }
290
        }
291
    }
292
293
    return $access;
294
}
295
296
/**
297
 * Return HTML string of a list as <li> items.
298
 *
299
 * @return string
300
 */
301
function returnNotificationMenu()
302
{
303
    $html = '';
304
305
    $user_id = api_get_user_id();
306
    $courseInfo = api_get_course_info();
307
    if (accessToWhoIsOnline($user_id, (!empty($courseInfo['real_id']) ?: 0))) {
308
        // Display the who's online of the platform
309
        if ((api_get_setting('showonline', 'world') == 'true' && !$user_id) ||
310
            (api_get_setting('showonline', 'users') == 'true' && $user_id)
311
        ) {
312
            $number = getOnlineUsersCount();
313
            if ($number) {
314
                $html .= '<li class="user-online"><a href="'.api_get_path(WEB_PATH).'whoisonline.php" target="_self" title="'
315
                    .get_lang('UsersOnline').'" >'
316
                    .Display::return_icon('user.png', get_lang('UsersOnline'), [], ICON_SIZE_TINY)
317
                    .' '.$number.'</a></li>';
318
            }
319
        }
320
321
        // Display the who's online for the course
322
        if (
323
            is_array($courseInfo) &&
324
            api_get_setting('showonline', 'course') == 'true' && isset($courseInfo['sysCode'])
325
        ) {
326
            $number_online_in_course = getOnlineUsersInCourseCount($user_id, $courseInfo);
327
            if ($number_online_in_course) {
328
                $html .= '<li class="user-online-course"><a href="'.api_get_path(WEB_PATH).'whoisonline.php?cidReq='.$courseInfo['sysCode']
329
                    .'" target="_self">'
330
                    .Display::return_icon('course.png', get_lang('UsersOnline').' '.get_lang('InThisCourse'), [], ICON_SIZE_TINY)
331
                    .' '.$number_online_in_course.' </a></li>';
332
            }
333
        }
334
335
        $sessionId = api_get_session_id();
336
        if (!empty($sessionId)) {
337
            $allow = api_is_platform_admin(true) ||
338
                api_is_coach($sessionId, null, false) ||
339
                SessionManager::isUserSubscribedAsStudent($sessionId, api_get_user_id());
340
            if ($allow) {
341
                $numberOnlineInSession = getOnlineUsersInSessionCount($sessionId);
342
                $html .= '<li class="user-online-session">
343
                            <a href="'.api_get_path(WEB_PATH).'whoisonlinesession.php" target="_self">'
344
                            .Display::return_icon('session.png', get_lang('UsersConnectedToMySessions'), [], ICON_SIZE_TINY)
345
                            .' '.$numberOnlineInSession.'</a></li>';
346
            }
347
        }
348
    }
349
350
    return $html;
351
}
352
353
/**
354
 * Return an array with different navigation mennu elements.
355
 *
356
 * @return array [menu_navigation[], navigation[], possible_tabs[]]
357
 */
358
function return_navigation_array()
359
{
360
    $navigation = [];
361
    $menu_navigation = [];
362
    $possible_tabs = get_tabs();
363
364
    // Campus Homepage
365
    if (api_get_setting('show_tabs', 'campus_homepage') == 'true') {
366
        $navigation[SECTION_CAMPUS] = $possible_tabs[SECTION_CAMPUS];
367
    } else {
368
        $menu_navigation[SECTION_CAMPUS] = $possible_tabs[SECTION_CAMPUS];
369
    }
370
371
    if (api_get_setting('course_catalog_published') == 'true' && api_is_anonymous()) {
372
        if (true !== api_get_configuration_value('catalog_hide_public_link')) {
373
            $navigation[SECTION_CATALOG] = $possible_tabs[SECTION_CATALOG];
374
        }
375
    }
376
377
    if (api_get_user_id() && !api_is_anonymous()) {
378
        // My Courses
379
        if (api_get_setting('show_tabs', 'my_courses') == 'true') {
380
            $navigation['mycourses'] = $possible_tabs['mycourses'];
381
        } else {
382
            $menu_navigation['mycourses'] = $possible_tabs['mycourses'];
383
        }
384
385
        // My Profile
386
        if (api_get_setting('show_tabs', 'my_profile') == 'true' &&
387
            api_get_setting('allow_social_tool') != 'true'
388
        ) {
389
            $navigation['myprofile'] = $possible_tabs['myprofile'];
390
        } else {
391
            $menu_navigation['myprofile'] = $possible_tabs['myprofile'];
392
        }
393
394
        // My Agenda
395
        if (api_get_setting('show_tabs', 'my_agenda') == 'true') {
396
            $navigation['myagenda'] = $possible_tabs['myagenda'];
397
        } else {
398
            $menu_navigation['myagenda'] = $possible_tabs['myagenda'];
399
        }
400
401
        // Gradebook
402
        if (api_get_setting('gradebook_enable') == 'true') {
403
            if (api_get_setting('show_tabs', 'my_gradebook') == 'true') {
404
                $navigation['mygradebook'] = $possible_tabs['mygradebook'];
405
            } else {
406
                $menu_navigation['mygradebook'] = $possible_tabs['mygradebook'];
407
            }
408
        }
409
410
        // Reporting
411
        if (api_get_setting('show_tabs', 'reporting') == 'true') {
412
            if (api_is_teacher() || api_is_drh() || api_is_session_admin() || api_is_student_boss()) {
413
                $navigation['session_my_space'] = $possible_tabs['session_my_space'];
414
            } else {
415
                $navigation['session_my_space'] = $possible_tabs['session_my_progress'];
416
            }
417
        } else {
418
            if (api_is_teacher() || api_is_drh() || api_is_session_admin() || api_is_student_boss()) {
419
                $menu_navigation['session_my_space'] = $possible_tabs['session_my_space'];
420
            } else {
421
                $menu_navigation['session_my_space'] = $possible_tabs['session_my_progress'];
422
            }
423
        }
424
425
        // Social Networking
426
        if (api_get_setting('show_tabs', 'social') == 'true') {
427
            if (api_get_setting('allow_social_tool') == 'true') {
428
                $navigation['social'] = isset($possible_tabs['social']) ? $possible_tabs['social'] : null;
429
            }
430
        } else {
431
            $menu_navigation['social'] = isset($possible_tabs['social']) ? $possible_tabs['social'] : null;
432
        }
433
434
        // Dashboard
435
        if (api_get_setting('show_tabs', 'dashboard') == 'true') {
436
            if (api_is_platform_admin() || api_is_drh() || api_is_session_admin()) {
437
                $navigation['dashboard'] = isset($possible_tabs['dashboard']) ? $possible_tabs['dashboard'] : null;
438
            }
439
        } else {
440
            $menu_navigation['dashboard'] = isset($possible_tabs['dashboard']) ? $possible_tabs['dashboard'] : null;
441
        }
442
443
        $installed = AppPlugin::getInstance()->isInstalled('studentfollowup');
444
        if ($installed) {
445
            $plugin = StudentFollowUpPlugin::create();
446
            // Students
447
            $url = api_get_path(WEB_PLUGIN_PATH).'studentfollowup/posts.php';
448
            if (api_is_platform_admin() || api_is_drh() || api_is_teacher()) {
449
                $url = api_get_path(WEB_PLUGIN_PATH).'studentfollowup/my_students.php';
450
            }
451
            $navigation['follow_up']['url'] = $url;
452
            $navigation['follow_up']['title'] = $plugin->get_lang('CareDetailView');
453
            $navigation['follow_up']['key'] = 'homepage';
454
            $navigation['follow_up']['icon'] = 'homepage.png';
455
        }
456
457
        // Administration
458
        if (api_is_platform_admin(true)) {
459
            if (api_get_setting('show_tabs', 'platform_administration') == 'true') {
460
                $navigation['platform_admin'] = $possible_tabs['platform_admin'];
461
            } else {
462
                $menu_navigation['platform_admin'] = $possible_tabs['platform_admin'];
463
            }
464
        }
465
466
        // Custom tabs
467
        $customTabs = getCustomTabs();
468
        if (!empty($customTabs)) {
469
            foreach ($customTabs as $tab) {
470
                if (api_get_setting($tab['variable'], $tab['subkey']) == 'true' &&
471
                    isset($possible_tabs[$tab['subkey']])
472
                ) {
473
                    $possible_tabs[$tab['subkey']]['url'] = api_get_path(WEB_PATH).$possible_tabs[$tab['subkey']]['url'];
474
                    $navigation[$tab['subkey']] = $possible_tabs[$tab['subkey']];
475
                } else {
476
                    if (isset($possible_tabs[$tab['subkey']])) {
477
                        $possible_tabs[$tab['subkey']]['url'] = api_get_path(WEB_PATH).$possible_tabs[$tab['subkey']]['url'];
478
                        $menu_navigation[$tab['subkey']] = $possible_tabs[$tab['subkey']];
479
                    }
480
                }
481
            }
482
        }
483
    } else {
484
        // Show custom tabs that are specifically marked as public
485
        $customTabs = getCustomTabs();
486
        if (!empty($customTabs)) {
487
            foreach ($customTabs as $tab) {
488
                if (api_get_setting($tab['variable'], $tab['subkey']) == 'true' &&
489
                    isset($possible_tabs[$tab['subkey']]) &&
490
                    api_get_plugin_setting(strtolower(str_replace('Tabs', '', $tab['subkeytext'])), 'public_main_menu_tab') == 'true'
491
                ) {
492
                    $possible_tabs[$tab['subkey']]['url'] = api_get_path(WEB_PATH).$possible_tabs[$tab['subkey']]['url'];
493
                    $navigation[$tab['subkey']] = $possible_tabs[$tab['subkey']];
494
                } else {
495
                    if (isset($possible_tabs[$tab['subkey']])) {
496
                        $possible_tabs[$tab['subkey']]['url'] = api_get_path(WEB_PATH).$possible_tabs[$tab['subkey']]['url'];
497
                        $menu_navigation[$tab['subkey']] = $possible_tabs[$tab['subkey']];
498
                    }
499
                }
500
            }
501
        }
502
    }
503
504
    return [
505
        'menu_navigation' => $menu_navigation,
506
        'navigation' => $navigation,
507
        'possible_tabs' => $possible_tabs,
508
    ];
509
}
510
511
function getCourseCategoriesAsMenuItems()
512
{
513
514
}
515
516
/**
517
 * Return the navigation menu elements as a flat array.
518
 *
519
 * @return array
520
 */
521
function menuArray()
522
{
523
    $mainNavigation = return_navigation_array();
524
    unset($mainNavigation['possible_tabs']);
525
    unset($mainNavigation['menu_navigation']);
526
    //$navigation = $navigation['navigation'];
527
    // Get active language
528
    $lang = api_get_setting('platformLanguage');
529
    if (!empty($_SESSION['user_language_choice'])) {
530
        $lang = $_SESSION['user_language_choice'];
531
    } elseif (!empty($_SESSION['_user']['language'])) {
532
        $lang = $_SESSION['_user']['language'];
533
    }
534
535
    if (api_get_configuration_value('display_menu_use_course_categories')
536
        && 'true' === api_get_setting('course_catalog_published')
537
    ) {
538
        $baseCategoryUrl = api_get_path(WEB_CODE_PATH).'auth/courses.php?';
539
        $commonParams = [
540
            'search_term' => '',
541
            'submit' => '_qf__s',
542
        ];
543
544
        $buildCategoryTree = function ($parentCode = 0, $depth = 0) use ($baseCategoryUrl, &$buildCategoryTree, &$commonParams) {
545
            if ($depth > 2) {
546
                return [];
547
            }
548
549
            $items = [];
550
551
            foreach (CourseCategory::getChildren($parentCode, false) as $category) {
552
                $commonParams['category_code'] = $category['code'];
553
554
                $categoryItem = [
555
                    'title' => $category['name'],
556
                    'key' => 'category_'.$category['code'],
557
                    'url' => $baseCategoryUrl.http_build_query($commonParams),
558
                ];
559
560
                $children = $buildCategoryTree($category['code'], $depth + 1);
561
562
                if (!empty($children)) {
563
                    $categoryItem['items'] = $children;
564
                    $categoryItem['url'] = '#';
565
                }
566
567
                $items[] = $categoryItem;
568
            }
569
570
            return $items;
571
        };
572
573
        foreach (CourseCategory::getCategoriesToDisplayInHomePage() as $category) {
574
            $key = 'category_'.$category['code'];
575
            $mainNavigation['navigation'][$key] = [
576
                'url' => '#',
577
                'title' => $category['name'],
578
                'key' => $key,
579
                'items' => $buildCategoryTree($category['code']),
580
            ];
581
        }
582
    }
583
584
    // Preparing home folder for multiple urls
585
    if (api_get_multiple_access_url()) {
586
        $access_url_id = api_get_current_access_url_id();
587
        if ($access_url_id != -1) {
588
            // If not a dead URL
589
            $urlInfo = api_get_access_url($access_url_id);
590
            $url = api_remove_trailing_slash(preg_replace('/https?:\/\//i', '', $urlInfo['url']));
591
            $cleanUrl = api_replace_dangerous_char($url);
592
            $cleanUrl = str_replace('/', '-', $cleanUrl);
593
            $cleanUrl .= '/';
594
            $homepath = api_get_path(SYS_HOME_PATH).$cleanUrl; //homep for Home Path
595
596
            //we create the new dir for the new sites
597
            if (!is_dir($homepath)) {
598
                mkdir($homepath, api_get_permissions_for_new_directories());
599
            }
600
        }
601
    } else {
602
        $homepath = api_get_path(SYS_HOME_PATH);
603
    }
604
    $ext = '.html';
605
    $menuTabs = 'home_tabs';
606
    $menuTabsLoggedIn = 'home_tabs_logged_in';
607
    $pageContent = '';
608
    // Get the extra page content, containing the links to add to the tabs
609
    if (is_file($homepath.$menuTabs.'_'.$lang.$ext) && is_readable($homepath.$menuTabs.'_'.$lang.$ext)) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $homepath does not seem to be defined for all execution paths leading up to this point.
Loading history...
610
        $pageContent = @(string) file_get_contents($homepath.$menuTabs.'_'.$lang.$ext);
611
    } elseif (is_file($homepath.$menuTabs.$lang.$ext) && is_readable($homepath.$menuTabs.$lang.$ext)) {
612
        $pageContent = @(string) file_get_contents($homepath.$menuTabs.$lang.$ext);
613
    }
614
    // Sanitize page content
615
    $pageContent = api_to_system_encoding($pageContent, api_detect_encoding(strip_tags($pageContent)));
616
    $open = str_replace('{rel_path}', api_get_path(REL_PATH), $pageContent);
617
    $open = api_to_system_encoding($open, api_detect_encoding(strip_tags($open)));
618
    // Get the extra page content, containing the links to add to the tabs
619
    //  that are only for users already logged in
620
    $openMenuTabsLoggedIn = '';
621
    if (api_get_user_id() && !api_is_anonymous()) {
622
        if (is_file($homepath.$menuTabsLoggedIn.'_'.$lang.$ext) && is_readable(
623
                $homepath.$menuTabsLoggedIn.'_'.$lang.$ext
624
            )
625
        ) {
626
            $pageContent = @(string) file_get_contents($homepath.$menuTabsLoggedIn.'_'.$lang.$ext);
627
            $pageContent = str_replace('::private', '', $pageContent);
628
        } elseif (is_file($homepath.$menuTabsLoggedIn.$lang.$ext) && is_readable(
629
                $homepath.$menuTabsLoggedIn.$lang.$ext
630
            )
631
        ) {
632
            $pageContent = @(string) file_get_contents($homepath.$menuTabsLoggedIn.$lang.$ext);
633
            $pageContent = str_replace('::private', '', $pageContent);
634
        }
635
636
        $pageContent = api_to_system_encoding($pageContent, api_detect_encoding(strip_tags($pageContent)));
637
        $openMenuTabsLoggedIn = str_replace('{rel_path}', api_get_path(REL_PATH), $pageContent);
638
        $openMenuTabsLoggedIn = api_to_system_encoding(
639
            $openMenuTabsLoggedIn,
640
            api_detect_encoding(strip_tags($openMenuTabsLoggedIn))
641
        );
642
    }
643
    if (!empty($open) || !empty($openMenuTabsLoggedIn)) {
644
        if (strpos($open.$openMenuTabsLoggedIn, 'show_menu') !== false) {
645
            $list = explode("\n", api_get_user_id() && !api_is_anonymous() ? $openMenuTabsLoggedIn : $open);
646
647
            foreach ($list as $link) {
648
                if (strpos($link, 'class="hide_menu"') !== false) {
649
                    continue;
650
                }
651
652
                $matches = [];
653
                $match = preg_match('$href="([^"]*)" target="([^"]*)">([^<]*)</a>$', $link, $matches);
654
655
                if (!$match) {
656
                    continue;
657
                }
658
659
                $mainNavigation['navigation'][$matches[3]] = [
660
                    'url' => $matches[1],
661
                    'target' => $matches[2],
662
                    'title' => $matches[3],
663
                    'key' => 'page-'.str_replace(' ', '-', strtolower($matches[3])),
664
                ];
665
            }
666
        }
667
    }
668
669
    if (count($mainNavigation['navigation']) > 0) {
670
        //$pre_lis = '';
671
        $activeSection = '';
672
        foreach ($mainNavigation['navigation'] as $section => $navigation_info) {
673
            $key = (!empty($navigation_info['key']) ? 'tab-'.$navigation_info['key'] : '');
674
675
            if (isset($GLOBALS['this_section'])) {
676
                $tempSection = $section;
677
                if ($section == 'social') {
678
                    $tempSection = 'social-network';
679
                }
680
                if ($tempSection == $GLOBALS['this_section']) {
681
                    $activeSection = $section;
682
                }
683
                // If we're on the index page and a specific extra link has been
684
                // loaded
685
                if ($GLOBALS['this_section'] == SECTION_CAMPUS) {
686
                    if (!empty($_GET['include'])) {
687
                        $name = str_replace(' ', '-', strtolower($navigation_info['title'])).'_'.$lang.$ext;
688
                        if (strtolower($_GET['include']) == $name) {
689
                            $activeSection = $section;
690
                        }
691
                    }
692
                }
693
            } else {
694
                $current = '';
695
            }
696
            $mainNavigation['navigation'][$section]['current'] = '';
697
        }
698
        if (!empty($activeSection)) {
699
            $mainNavigation['navigation'][$activeSection]['current'] = 'active';
700
        }
701
    }
702
    unset($mainNavigation['navigation']['myprofile']);
703
704
    return $mainNavigation['navigation'];
705
}
706
707
/**
708
 * Return the breadcrumb menu elements as an array of <li> items.
709
 *
710
 * @param array  $interbreadcrumb The elements to add to the breadcrumb
711
 * @param string $language_file   Deprecated
712
 * @param string $nameTools       The name of the current tool (not linked)
713
 *
714
 * @return string HTML string of <li> items
715
 */
716
function return_breadcrumb($interbreadcrumb, $language_file, $nameTools)
717
{
718
    // This configuration option allows you to completely hide the breadcrumb
719
    if (api_get_configuration_value('breadcrumb_hide') == true) {
720
        return '';
721
    }
722
    $courseInfo = api_get_course_info();
723
    $user_id = api_get_user_id();
724
    $additionalBlocks = '';
725
726
    /*  Plugins for banner section */
727
    $web_course_path = api_get_path(WEB_COURSE_PATH);
728
729
    /* If the user is a coach he can see the users who are logged in its session */
730
    $navigation = [];
731
732
    $sessionId = api_get_session_id();
733
    // part 1: Course Homepage. If we are in a course then the first breadcrumb
734
    // is a link to the course homepage
735
    if (!empty($courseInfo) && !isset($_GET['hide_course_breadcrumb'])) {
736
        $sessionName = '';
737
        if (!empty($sessionId)) {
738
            /** @var \Chamilo\CoreBundle\Entity\Session $session */
739
            $session = Database::getManager()->find('ChamiloCoreBundle:Session', $sessionId);
740
            $sessionName = $session ? ' ('.cut(Security::remove_XSS($session->getName()), MAX_LENGTH_BREADCRUMB).')' : '';
0 ignored issues
show
introduced by
$session is of type Chamilo\CoreBundle\Entity\Session, thus it always evaluated to true.
Loading history...
741
        }
742
743
        $courseInfo['name'] = api_htmlentities($courseInfo['name']);
744
        $course_title = cut($courseInfo['name'], MAX_LENGTH_BREADCRUMB);
745
746
        switch (api_get_setting('breadcrumbs_course_homepage')) {
747
            case 'get_lang':
748
                $itemTitle = Display::return_icon(
749
                    'home.png',
750
                    get_lang('CourseHomepageLink'),
751
                    [],
752
                    ICON_SIZE_TINY
753
                );
754
                break;
755
            case 'course_code':
756
                $itemTitle = Display::return_icon(
757
                    'home.png',
758
                    $courseInfo['official_code'],
759
                    [],
760
                    ICON_SIZE_TINY
761
                )
762
                .' '.$courseInfo['official_code'];
763
                break;
764
            case 'session_name_and_course_title':
765
            default:
766
                $itemTitle = Display::return_icon(
767
                    'home.png',
768
                    $courseInfo['name'].$sessionName,
769
                    [],
770
                    ICON_SIZE_TINY
771
                )
772
                .' '.$course_title.$sessionName;
773
774
                if (!empty($sessionId) && ($session->getDuration() && !api_is_allowed_to_edit())) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $session does not seem to be defined for all execution paths leading up to this point.
Loading history...
775
                    $daysLeft = SessionManager::getDayLeftInSession(
776
                        ['id' => $session->getId(), 'duration' => $session->getDuration()],
777
                        $user_id
778
                    );
779
780
                    if ($daysLeft >= 0) {
781
                        $additionalBlocks .= Display::return_message(
782
                            sprintf(get_lang('SessionDurationXDaysLeft'), $daysLeft),
783
                            'information'
784
                        );
785
                    } else {
786
                        $additionalBlocks .= Display::return_message(
787
                            get_lang('YourSessionTimeHasExpired'),
788
                            'warning'
789
                        );
790
                    }
791
                }
792
                break;
793
        }
794
795
        /**
796
         * @todo could be useful adding the My courses in the breadcrumb
797
         * $navigation_item_my_courses['title'] = get_lang('MyCourses');
798
         * $navigation_item_my_courses['url'] = api_get_path(WEB_PATH).'user_portal.php';
799
         * $navigation[] = $navigation_item_my_courses;
800
         */
801
        $navigation[] = [
802
            'url' => $web_course_path.$courseInfo['path'].'/index.php?id_session='.$sessionId,
803
            'title' => $itemTitle,
804
        ];
805
    }
806
807
    /* part 2: Interbreadcrumbs. If there is an array $interbreadcrumb
808
    defined then these have to appear before the last breadcrumb
809
    (which is the tool itself)*/
810
    if (isset($interbreadcrumb) && is_array($interbreadcrumb)) {
811
        foreach ($interbreadcrumb as $breadcrumb_step) {
812
            if (isset($breadcrumb_step['type']) && $breadcrumb_step['type'] == 'right') {
813
                continue;
814
            }
815
            if ($breadcrumb_step['url'] != '#') {
816
                $sep = strrchr($breadcrumb_step['url'], '?') ? '&' : '?';
817
                $courseParams = strpos($breadcrumb_step['url'], 'cidReq') === false ? api_get_cidreq() : '';
818
                $navigation_item['url'] = $breadcrumb_step['url'].$sep.$courseParams;
819
            } else {
820
                $navigation_item['url'] = '#';
821
            }
822
            $navigation_item['title'] = $breadcrumb_step['name'];
823
            // titles for shared folders
824
            if ($breadcrumb_step['name'] == 'shared_folder') {
825
                $navigation_item['title'] = get_lang('UserFolders');
826
            } elseif (strstr($breadcrumb_step['name'], 'shared_folder_session_')) {
827
                $navigation_item['title'] = get_lang('UserFolders');
828
            } elseif (strstr($breadcrumb_step['name'], 'sf_user_')) {
829
                $userinfo = api_get_user_info(substr($breadcrumb_step['name'], 8));
830
                $navigation_item['title'] = $userinfo['complete_name'];
831
            } elseif ($breadcrumb_step['name'] == 'chat_files') {
832
                $navigation_item['title'] = get_lang('ChatFiles');
833
            } elseif ($breadcrumb_step['name'] == 'images') {
834
                $navigation_item['title'] = get_lang('Images');
835
            } elseif ($breadcrumb_step['name'] == 'video') {
836
                $navigation_item['title'] = get_lang('Video');
837
            } elseif ($breadcrumb_step['name'] == 'audio') {
838
                $navigation_item['title'] = get_lang('Audio');
839
            } elseif ($breadcrumb_step['name'] == 'flash') {
840
                $navigation_item['title'] = get_lang('Flash');
841
            } elseif ($breadcrumb_step['name'] == 'gallery') {
842
                $navigation_item['title'] = get_lang('Gallery');
843
            }
844
            // Fixes breadcrumb title now we applied the Security::remove_XSS and
845
            // we cut the string depending of the MAX_LENGTH_BREADCRUMB value
846
            $navigation_item['title'] = cut($navigation_item['title'], MAX_LENGTH_BREADCRUMB);
847
            $navigation_item['title'] = Security::remove_XSS($navigation_item['title']);
848
849
            $navigation[] = $navigation_item;
850
        }
851
    }
852
853
    $navigation_right = [];
854
    if (isset($interbreadcrumb) && is_array($interbreadcrumb)) {
855
        foreach ($interbreadcrumb as $breadcrumb_step) {
856
            if (isset($breadcrumb_step['type']) && $breadcrumb_step['type'] == 'right') {
857
                if ($breadcrumb_step['url'] != '#') {
858
                    $sep = (strrchr($breadcrumb_step['url'], '?') ? '&amp;' : '?');
859
                    $navigation_item['url'] = $breadcrumb_step['url'].$sep.api_get_cidreq();
860
                } else {
861
                    $navigation_item['url'] = '#';
862
                }
863
                $breadcrumb_step['title'] = cut($navigation_item['title'], MAX_LENGTH_BREADCRUMB);
864
                $breadcrumb_step['title'] = Security::remove_XSS($navigation_item['title']);
865
                $navigation_right[] = $breadcrumb_step;
866
            }
867
        }
868
    }
869
870
    // part 3: The tool itself. If we are on the course homepage we do not want
871
    // to display the title of the course because this
872
    // is the same as the first part of the breadcrumbs (see part 1)
873
    if (isset($nameTools)) {
874
        $navigation_item['url'] = '#';
875
        $navigation_item['title'] = $nameTools;
876
        $navigation[] = $navigation_item;
877
    }
878
879
    $final_navigation = [];
880
    $counter = 0;
881
    foreach ($navigation as $index => $navigation_info) {
882
        if (!empty($navigation_info['title'])) {
883
            if ($navigation_info['url'] == '#') {
884
                $final_navigation[$index] = $navigation_info['title'];
885
            } else {
886
                $final_navigation[$index] = '<a href="'.$navigation_info['url'].'" target="_self">'.$navigation_info['title'].'</a>';
887
            }
888
            $counter++;
889
        }
890
    }
891
892
    $html = '';
893
894
    /* Part 4 . Show the teacher view/student view button at the right of the breadcrumb */
895
    $view_as_student_link = null;
896
    if ($user_id && !empty($courseInfo)) {
897
        if ((
898
                api_is_course_admin() ||
899
                api_is_platform_admin() ||
900
                api_is_coach(null, null, false)
901
            ) &&
902
            api_get_setting('student_view_enabled') === 'true' && api_get_course_info()
903
        ) {
904
            $view_as_student_link = api_display_tool_view_option();
905
906
            // Only show link if LP can be editable
907
            /** @var learnpath $learnPath */
908
            $learnPath = Session::read('oLP');
909
            if (!empty($learnPath) && !empty($view_as_student_link)) {
910
                if ((int) $learnPath->get_lp_session_id() != (int) api_get_session_id()) {
911
                    $view_as_student_link = '';
912
                }
913
            }
914
        }
915
    }
916
917
    if (!empty($final_navigation)) {
918
        $lis = '';
919
        $i = 0;
920
        $final_navigation_count = count($final_navigation);
921
        if (!empty($final_navigation)) {
922
            if (!empty($home_link)) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $home_link seems to never exist and therefore empty should always be true.
Loading history...
923
                $lis .= Display::tag('li', $home_link);
924
            }
925
926
            foreach ($final_navigation as $bread) {
927
                $bread_check = trim(strip_tags($bread));
928
                if (!empty($bread_check)) {
929
                    if ($final_navigation_count - 1 > $i) {
930
                        $bread .= '';
931
                    }
932
                    $lis .= Display::tag('li', $bread, ['class' => 'active']);
933
                    $i++;
934
                }
935
            }
936
        } else {
937
            if (!empty($home_link)) {
938
                $lis .= Display::tag('li', $home_link);
939
            }
940
        }
941
942
        // View as student/teacher link
943
        if (!empty($view_as_student_link)) {
944
            $html .= Display::tag('div', $view_as_student_link, ['id' => 'view_as_link', 'class' => 'pull-right']);
945
        }
946
947
        if ($sessionId && !empty($courseInfo) &&
948
            (
949
                api_is_platform_admin()
950
                || (CourseManager::is_course_teacher($user_id, $courseInfo['code']))
951
            )
952
        ) {
953
            $url = Display::url(
954
                Display::return_icon('course.png', get_lang('Course')),
955
                $courseInfo['course_public_url'].'?id_session=0',
956
                ['class' => 'btn btn-default btn-sm', 'target' => '_blank']
957
            );
958
            $button = Display::tag('div', $url, ['class' => 'view-options']);
959
            $html .= Display::tag('div', $button, ['id' => 'view_as_link', 'class' => 'pull-right']);
960
        }
961
962
        if (!empty($navigation_right)) {
963
            foreach ($navigation_right as $item) {
964
                $extra_class = isset($item['class']) ? $item['class'] : null;
965
                $lis .= Display::tag(
966
                    'li',
967
                    $item['title'],
968
                    ['class' => $extra_class.' pull-right']
969
                );
970
            }
971
        }
972
973
        if (!empty($lis)) {
974
            $html .= Display::tag('ul', $lis, ['class' => 'breadcrumb']);
975
        }
976
    }
977
978
    return $html.$additionalBlocks;
979
}
980
981
/**
982
 * Helper function to get the number of users online, using cache if available.
983
 *
984
 * @param int $minutes Number of minutes (how many users were active in those last X minutes?)
985
 *
986
 * @return int The number of users currently online
987
 */
988
function getOnlineUsersCount($minutes = null)
989
{
990
    $number = 0;
991
    $limit = !empty($minutes) ? intval($minutes) : api_get_setting('time_limit_whosonline');
992
    $cacheAvailable = api_get_configuration_value('apc');
993
    if ($cacheAvailable === true) {
994
        $apcVar = api_get_configuration_value('apc_prefix').'my_campus_whoisonline_count_simple_'.$minutes;
995
        if (apcu_exists($apcVar)) {
996
            $number = apcu_fetch($apcVar);
997
        } else {
998
            $number = who_is_online_count($limit);
999
            apcu_store($apcVar, $number, 15);
1000
        }
1001
    } else {
1002
        $number = who_is_online_count($limit);
1003
    }
1004
1005
    return $number;
1006
}
1007
1008
/**
1009
 * Helper function to get the number of users online in a course, using cache if available.
1010
 *
1011
 * @param int   $userId     The user ID
1012
 * @param array $courseInfo The course details
1013
 *
1014
 * @return int The number of users currently online
1015
 */
1016
function getOnlineUsersInCourseCount($userId, $courseInfo)
1017
{
1018
    $cacheAvailable = api_get_configuration_value('apc');
1019
    $numberOnlineInCourse = 0;
1020
    if (!empty($courseInfo['id'])) {
1021
        if ($cacheAvailable === true) {
1022
            $apcVar = api_get_configuration_value('apc_prefix').'my_campus_whoisonline_count_simple_'.$courseInfo['id'];
1023
            if (apcu_exists($apcVar)) {
1024
                $numberOnlineInCourse = apcu_fetch($apcVar);
1025
            } else {
1026
                $numberOnlineInCourse = who_is_online_in_this_course_count(
1027
                    $userId,
1028
                    api_get_setting('time_limit_whosonline'),
1029
                    $courseInfo['id']
1030
                );
1031
                apcu_store(
1032
                    $apcVar,
1033
                    $numberOnlineInCourse,
1034
                    15
1035
                );
1036
            }
1037
        } else {
1038
            $numberOnlineInCourse = who_is_online_in_this_course_count(
1039
                $userId,
1040
                api_get_setting('time_limit_whosonline'),
1041
                $courseInfo['id']
1042
            );
1043
        }
1044
    }
1045
1046
    return $numberOnlineInCourse;
1047
}
1048
1049
/**
1050
 * Helper function to get the number of users online in a session, using cache if available.
1051
 *
1052
 * @param int $sessionId The session ID
1053
 *
1054
 * @return int The number of users currently online
1055
 */
1056
function getOnlineUsersInSessionCount($sessionId)
1057
{
1058
    $cacheAvailable = api_get_configuration_value('apc');
1059
1060
    if (!$sessionId) {
1061
        return 0;
1062
    }
1063
1064
    if ($cacheAvailable === true) {
1065
        $apcVar = api_get_configuration_value('apc_prefix').'my_campus_whoisonline_session_count_simple_'.$sessionId;
1066
1067
        if (apcu_exists($apcVar)) {
1068
            return apcu_fetch($apcVar);
1069
        }
1070
1071
        $numberOnlineInCourse = whoIsOnlineInThisSessionCount(
1072
            api_get_setting('time_limit_whosonline'),
1073
            $sessionId
1074
        );
1075
        apcu_store($apcVar, $numberOnlineInCourse, 15);
1076
1077
        return $numberOnlineInCourse;
1078
    }
1079
1080
    return whoIsOnlineInThisSessionCount(
1081
        api_get_setting('time_limit_whosonline'),
1082
        $sessionId
1083
    );
1084
}
1085