Passed
Pull Request — 1.11.x (#6364)
by Angel Fernando Quiroz
09:37
created

buildCategoryTreeInternal()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 30
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 16
nc 3
nop 1
dl 0
loc 30
rs 9.7333
c 0
b 0
f 0
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 buildCategoryTreeInternal($parentCode = 0): array
512
{
513
    $baseCategoryUrl = api_get_path(WEB_CODE_PATH).'auth/courses.php?';
514
515
    $commonParams = [
516
        'search_term' => '',
517
        'submit' => '_qf__s',
518
    ];
519
520
    $items = [];
521
522
    foreach (CourseCategory::getChildren($parentCode, false) as $category) {
523
        $commonParams['category_code'] = $category['code'];
524
525
        $categoryItem = [
526
            'title' => $category['name'],
527
            'key' => 'category_'.$category['code'],
528
            'url' => $baseCategoryUrl.http_build_query($commonParams),
529
        ];
530
531
        $children = buildCategoryTreeInternal($category['code']);
532
533
        if (!empty($children)) {
534
            $categoryItem['items'] = $children;
535
        }
536
537
        $items[] = $categoryItem;
538
    }
539
540
    return $items;
541
}
542
543
/**
544
 * Return the navigation menu elements as a flat array.
545
 *
546
 * @return array
547
 */
548
function menuArray()
549
{
550
    $mainNavigation = return_navigation_array();
551
    unset($mainNavigation['possible_tabs']);
552
    unset($mainNavigation['menu_navigation']);
553
    //$navigation = $navigation['navigation'];
554
    // Get active language
555
    $lang = api_get_setting('platformLanguage');
556
    if (!empty($_SESSION['user_language_choice'])) {
557
        $lang = $_SESSION['user_language_choice'];
558
    } elseif (!empty($_SESSION['_user']['language'])) {
559
        $lang = $_SESSION['_user']['language'];
560
    }
561
562
    if (api_get_configuration_value('display_menu_use_course_categories')
563
        && 'true' === api_get_setting('course_catalog_published')
564
    ) {
565
        foreach (CourseCategory::getCategoriesToDisplayInHomePage() as $category) {
566
            $key = 'category_'.$category['code'];
567
            $mainNavigation['navigation'][$key] = [
568
                'url' => '#',
569
                'title' => $category['name'],
570
                'key' => $key,
571
                'items' => buildCategoryTreeInternal($category['code']),
572
            ];
573
        }
574
    }
575
576
    // Preparing home folder for multiple urls
577
    if (api_get_multiple_access_url()) {
578
        $access_url_id = api_get_current_access_url_id();
579
        if ($access_url_id != -1) {
580
            // If not a dead URL
581
            $urlInfo = api_get_access_url($access_url_id);
582
            $url = api_remove_trailing_slash(preg_replace('/https?:\/\//i', '', $urlInfo['url']));
583
            $cleanUrl = api_replace_dangerous_char($url);
584
            $cleanUrl = str_replace('/', '-', $cleanUrl);
585
            $cleanUrl .= '/';
586
            $homepath = api_get_path(SYS_HOME_PATH).$cleanUrl; //homep for Home Path
587
588
            //we create the new dir for the new sites
589
            if (!is_dir($homepath)) {
590
                mkdir($homepath, api_get_permissions_for_new_directories());
591
            }
592
        }
593
    } else {
594
        $homepath = api_get_path(SYS_HOME_PATH);
595
    }
596
    $ext = '.html';
597
    $menuTabs = 'home_tabs';
598
    $menuTabsLoggedIn = 'home_tabs_logged_in';
599
    $pageContent = '';
600
    // Get the extra page content, containing the links to add to the tabs
601
    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...
602
        $pageContent = @(string) file_get_contents($homepath.$menuTabs.'_'.$lang.$ext);
603
    } elseif (is_file($homepath.$menuTabs.$lang.$ext) && is_readable($homepath.$menuTabs.$lang.$ext)) {
604
        $pageContent = @(string) file_get_contents($homepath.$menuTabs.$lang.$ext);
605
    }
606
    // Sanitize page content
607
    $pageContent = api_to_system_encoding($pageContent, api_detect_encoding(strip_tags($pageContent)));
608
    $open = str_replace('{rel_path}', api_get_path(REL_PATH), $pageContent);
609
    $open = api_to_system_encoding($open, api_detect_encoding(strip_tags($open)));
610
    // Get the extra page content, containing the links to add to the tabs
611
    //  that are only for users already logged in
612
    $openMenuTabsLoggedIn = '';
613
    if (api_get_user_id() && !api_is_anonymous()) {
614
        if (is_file($homepath.$menuTabsLoggedIn.'_'.$lang.$ext) && is_readable(
615
                $homepath.$menuTabsLoggedIn.'_'.$lang.$ext
616
            )
617
        ) {
618
            $pageContent = @(string) file_get_contents($homepath.$menuTabsLoggedIn.'_'.$lang.$ext);
619
            $pageContent = str_replace('::private', '', $pageContent);
620
        } elseif (is_file($homepath.$menuTabsLoggedIn.$lang.$ext) && is_readable(
621
                $homepath.$menuTabsLoggedIn.$lang.$ext
622
            )
623
        ) {
624
            $pageContent = @(string) file_get_contents($homepath.$menuTabsLoggedIn.$lang.$ext);
625
            $pageContent = str_replace('::private', '', $pageContent);
626
        }
627
628
        $pageContent = api_to_system_encoding($pageContent, api_detect_encoding(strip_tags($pageContent)));
629
        $openMenuTabsLoggedIn = str_replace('{rel_path}', api_get_path(REL_PATH), $pageContent);
630
        $openMenuTabsLoggedIn = api_to_system_encoding(
631
            $openMenuTabsLoggedIn,
632
            api_detect_encoding(strip_tags($openMenuTabsLoggedIn))
633
        );
634
    }
635
    if (!empty($open) || !empty($openMenuTabsLoggedIn)) {
636
        if (strpos($open.$openMenuTabsLoggedIn, 'show_menu') !== false) {
637
            $list = explode("\n", api_get_user_id() && !api_is_anonymous() ? $openMenuTabsLoggedIn : $open);
638
639
            foreach ($list as $link) {
640
                if (strpos($link, 'class="hide_menu"') !== false) {
641
                    continue;
642
                }
643
644
                $matches = [];
645
                $match = preg_match('$href="([^"]*)" target="([^"]*)">([^<]*)</a>$', $link, $matches);
646
647
                if (!$match) {
648
                    continue;
649
                }
650
651
                $mainNavigation['navigation'][$matches[3]] = [
652
                    'url' => $matches[1],
653
                    'target' => $matches[2],
654
                    'title' => $matches[3],
655
                    'key' => 'page-'.str_replace(' ', '-', strtolower($matches[3])),
656
                ];
657
            }
658
        }
659
    }
660
661
    if (count($mainNavigation['navigation']) > 0) {
662
        //$pre_lis = '';
663
        $activeSection = '';
664
        foreach ($mainNavigation['navigation'] as $section => $navigation_info) {
665
            $key = (!empty($navigation_info['key']) ? 'tab-'.$navigation_info['key'] : '');
666
667
            if (isset($GLOBALS['this_section'])) {
668
                $tempSection = $section;
669
                if ($section == 'social') {
670
                    $tempSection = 'social-network';
671
                }
672
                if ($tempSection == $GLOBALS['this_section']) {
673
                    $activeSection = $section;
674
                }
675
                // If we're on the index page and a specific extra link has been
676
                // loaded
677
                if ($GLOBALS['this_section'] == SECTION_CAMPUS) {
678
                    if (!empty($_GET['include'])) {
679
                        $name = str_replace(' ', '-', strtolower($navigation_info['title'])).'_'.$lang.$ext;
680
                        if (strtolower($_GET['include']) == $name) {
681
                            $activeSection = $section;
682
                        }
683
                    }
684
                }
685
            } else {
686
                $current = '';
687
            }
688
            $mainNavigation['navigation'][$section]['current'] = '';
689
        }
690
        if (!empty($activeSection)) {
691
            $mainNavigation['navigation'][$activeSection]['current'] = 'active';
692
        }
693
    }
694
    unset($mainNavigation['navigation']['myprofile']);
695
696
    return $mainNavigation['navigation'];
697
}
698
699
/**
700
 * Return the breadcrumb menu elements as an array of <li> items.
701
 *
702
 * @param array  $interbreadcrumb The elements to add to the breadcrumb
703
 * @param string $language_file   Deprecated
704
 * @param string $nameTools       The name of the current tool (not linked)
705
 *
706
 * @return string HTML string of <li> items
707
 */
708
function return_breadcrumb($interbreadcrumb, $language_file, $nameTools)
709
{
710
    // This configuration option allows you to completely hide the breadcrumb
711
    if (api_get_configuration_value('breadcrumb_hide') == true) {
712
        return '';
713
    }
714
    $courseInfo = api_get_course_info();
715
    $user_id = api_get_user_id();
716
    $additionalBlocks = '';
717
718
    /*  Plugins for banner section */
719
    $web_course_path = api_get_path(WEB_COURSE_PATH);
720
721
    /* If the user is a coach he can see the users who are logged in its session */
722
    $navigation = [];
723
724
    $sessionId = api_get_session_id();
725
    // part 1: Course Homepage. If we are in a course then the first breadcrumb
726
    // is a link to the course homepage
727
    if (!empty($courseInfo) && !isset($_GET['hide_course_breadcrumb'])) {
728
        $sessionName = '';
729
        if (!empty($sessionId)) {
730
            /** @var \Chamilo\CoreBundle\Entity\Session $session */
731
            $session = Database::getManager()->find('ChamiloCoreBundle:Session', $sessionId);
732
            $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...
733
        }
734
735
        $courseInfo['name'] = api_htmlentities($courseInfo['name']);
736
        $course_title = cut($courseInfo['name'], MAX_LENGTH_BREADCRUMB);
737
738
        switch (api_get_setting('breadcrumbs_course_homepage')) {
739
            case 'get_lang':
740
                $itemTitle = Display::return_icon(
741
                    'home.png',
742
                    get_lang('CourseHomepageLink'),
743
                    [],
744
                    ICON_SIZE_TINY
745
                );
746
                break;
747
            case 'course_code':
748
                $itemTitle = Display::return_icon(
749
                    'home.png',
750
                    $courseInfo['official_code'],
751
                    [],
752
                    ICON_SIZE_TINY
753
                )
754
                .' '.$courseInfo['official_code'];
755
                break;
756
            case 'session_name_and_course_title':
757
            default:
758
                $itemTitle = Display::return_icon(
759
                    'home.png',
760
                    $courseInfo['name'].$sessionName,
761
                    [],
762
                    ICON_SIZE_TINY
763
                )
764
                .' '.$course_title.$sessionName;
765
766
                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...
767
                    $daysLeft = SessionManager::getDayLeftInSession(
768
                        ['id' => $session->getId(), 'duration' => $session->getDuration()],
769
                        $user_id
770
                    );
771
772
                    if ($daysLeft >= 0) {
773
                        $additionalBlocks .= Display::return_message(
774
                            sprintf(get_lang('SessionDurationXDaysLeft'), $daysLeft),
775
                            'information'
776
                        );
777
                    } else {
778
                        $additionalBlocks .= Display::return_message(
779
                            get_lang('YourSessionTimeHasExpired'),
780
                            'warning'
781
                        );
782
                    }
783
                }
784
                break;
785
        }
786
787
        /**
788
         * @todo could be useful adding the My courses in the breadcrumb
789
         * $navigation_item_my_courses['title'] = get_lang('MyCourses');
790
         * $navigation_item_my_courses['url'] = api_get_path(WEB_PATH).'user_portal.php';
791
         * $navigation[] = $navigation_item_my_courses;
792
         */
793
        $navigation[] = [
794
            'url' => $web_course_path.$courseInfo['path'].'/index.php?id_session='.$sessionId,
795
            'title' => $itemTitle,
796
        ];
797
    }
798
799
    /* part 2: Interbreadcrumbs. If there is an array $interbreadcrumb
800
    defined then these have to appear before the last breadcrumb
801
    (which is the tool itself)*/
802
    if (isset($interbreadcrumb) && is_array($interbreadcrumb)) {
803
        foreach ($interbreadcrumb as $breadcrumb_step) {
804
            if (isset($breadcrumb_step['type']) && $breadcrumb_step['type'] == 'right') {
805
                continue;
806
            }
807
            if ($breadcrumb_step['url'] != '#') {
808
                $sep = strrchr($breadcrumb_step['url'], '?') ? '&' : '?';
809
                $courseParams = strpos($breadcrumb_step['url'], 'cidReq') === false ? api_get_cidreq() : '';
810
                $navigation_item['url'] = $breadcrumb_step['url'].$sep.$courseParams;
811
            } else {
812
                $navigation_item['url'] = '#';
813
            }
814
            $navigation_item['title'] = $breadcrumb_step['name'];
815
            // titles for shared folders
816
            if ($breadcrumb_step['name'] == 'shared_folder') {
817
                $navigation_item['title'] = get_lang('UserFolders');
818
            } elseif (strstr($breadcrumb_step['name'], 'shared_folder_session_')) {
819
                $navigation_item['title'] = get_lang('UserFolders');
820
            } elseif (strstr($breadcrumb_step['name'], 'sf_user_')) {
821
                $userinfo = api_get_user_info(substr($breadcrumb_step['name'], 8));
822
                $navigation_item['title'] = $userinfo['complete_name'];
823
            } elseif ($breadcrumb_step['name'] == 'chat_files') {
824
                $navigation_item['title'] = get_lang('ChatFiles');
825
            } elseif ($breadcrumb_step['name'] == 'images') {
826
                $navigation_item['title'] = get_lang('Images');
827
            } elseif ($breadcrumb_step['name'] == 'video') {
828
                $navigation_item['title'] = get_lang('Video');
829
            } elseif ($breadcrumb_step['name'] == 'audio') {
830
                $navigation_item['title'] = get_lang('Audio');
831
            } elseif ($breadcrumb_step['name'] == 'flash') {
832
                $navigation_item['title'] = get_lang('Flash');
833
            } elseif ($breadcrumb_step['name'] == 'gallery') {
834
                $navigation_item['title'] = get_lang('Gallery');
835
            }
836
            // Fixes breadcrumb title now we applied the Security::remove_XSS and
837
            // we cut the string depending of the MAX_LENGTH_BREADCRUMB value
838
            $navigation_item['title'] = cut($navigation_item['title'], MAX_LENGTH_BREADCRUMB);
839
            $navigation_item['title'] = Security::remove_XSS($navigation_item['title']);
840
841
            $navigation[] = $navigation_item;
842
        }
843
    }
844
845
    $navigation_right = [];
846
    if (isset($interbreadcrumb) && is_array($interbreadcrumb)) {
847
        foreach ($interbreadcrumb as $breadcrumb_step) {
848
            if (isset($breadcrumb_step['type']) && $breadcrumb_step['type'] == 'right') {
849
                if ($breadcrumb_step['url'] != '#') {
850
                    $sep = (strrchr($breadcrumb_step['url'], '?') ? '&amp;' : '?');
851
                    $navigation_item['url'] = $breadcrumb_step['url'].$sep.api_get_cidreq();
852
                } else {
853
                    $navigation_item['url'] = '#';
854
                }
855
                $breadcrumb_step['title'] = cut($navigation_item['title'], MAX_LENGTH_BREADCRUMB);
856
                $breadcrumb_step['title'] = Security::remove_XSS($navigation_item['title']);
857
                $navigation_right[] = $breadcrumb_step;
858
            }
859
        }
860
    }
861
862
    // part 3: The tool itself. If we are on the course homepage we do not want
863
    // to display the title of the course because this
864
    // is the same as the first part of the breadcrumbs (see part 1)
865
    if (isset($nameTools)) {
866
        $navigation_item['url'] = '#';
867
        $navigation_item['title'] = $nameTools;
868
        $navigation[] = $navigation_item;
869
    }
870
871
    $final_navigation = [];
872
    $counter = 0;
873
    foreach ($navigation as $index => $navigation_info) {
874
        if (!empty($navigation_info['title'])) {
875
            if ($navigation_info['url'] == '#') {
876
                $final_navigation[$index] = $navigation_info['title'];
877
            } else {
878
                $final_navigation[$index] = '<a href="'.$navigation_info['url'].'" target="_self">'.$navigation_info['title'].'</a>';
879
            }
880
            $counter++;
881
        }
882
    }
883
884
    $html = '';
885
886
    /* Part 4 . Show the teacher view/student view button at the right of the breadcrumb */
887
    $view_as_student_link = null;
888
    if ($user_id && !empty($courseInfo)) {
889
        if ((
890
                api_is_course_admin() ||
891
                api_is_platform_admin() ||
892
                api_is_coach(null, null, false)
893
            ) &&
894
            api_get_setting('student_view_enabled') === 'true' && api_get_course_info()
895
        ) {
896
            $view_as_student_link = api_display_tool_view_option();
897
898
            // Only show link if LP can be editable
899
            /** @var learnpath $learnPath */
900
            $learnPath = Session::read('oLP');
901
            if (!empty($learnPath) && !empty($view_as_student_link)) {
902
                if ((int) $learnPath->get_lp_session_id() != (int) api_get_session_id()) {
903
                    $view_as_student_link = '';
904
                }
905
            }
906
        }
907
    }
908
909
    if (!empty($final_navigation)) {
910
        $lis = '';
911
        $i = 0;
912
        $final_navigation_count = count($final_navigation);
913
        if (!empty($final_navigation)) {
914
            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...
915
                $lis .= Display::tag('li', $home_link);
916
            }
917
918
            foreach ($final_navigation as $bread) {
919
                $bread_check = trim(strip_tags($bread));
920
                if (!empty($bread_check)) {
921
                    if ($final_navigation_count - 1 > $i) {
922
                        $bread .= '';
923
                    }
924
                    $lis .= Display::tag('li', $bread, ['class' => 'active']);
925
                    $i++;
926
                }
927
            }
928
        } else {
929
            if (!empty($home_link)) {
930
                $lis .= Display::tag('li', $home_link);
931
            }
932
        }
933
934
        // View as student/teacher link
935
        if (!empty($view_as_student_link)) {
936
            $html .= Display::tag('div', $view_as_student_link, ['id' => 'view_as_link', 'class' => 'pull-right']);
937
        }
938
939
        if ($sessionId && !empty($courseInfo) &&
940
            (
941
                api_is_platform_admin()
942
                || (CourseManager::is_course_teacher($user_id, $courseInfo['code']))
943
            )
944
        ) {
945
            $url = Display::url(
946
                Display::return_icon('course.png', get_lang('Course')),
947
                $courseInfo['course_public_url'].'?id_session=0',
948
                ['class' => 'btn btn-default btn-sm', 'target' => '_blank']
949
            );
950
            $button = Display::tag('div', $url, ['class' => 'view-options']);
951
            $html .= Display::tag('div', $button, ['id' => 'view_as_link', 'class' => 'pull-right']);
952
        }
953
954
        if (!empty($navigation_right)) {
955
            foreach ($navigation_right as $item) {
956
                $extra_class = isset($item['class']) ? $item['class'] : null;
957
                $lis .= Display::tag(
958
                    'li',
959
                    $item['title'],
960
                    ['class' => $extra_class.' pull-right']
961
                );
962
            }
963
        }
964
965
        if (!empty($lis)) {
966
            $html .= Display::tag('ul', $lis, ['class' => 'breadcrumb']);
967
        }
968
    }
969
970
    return $html.$additionalBlocks;
971
}
972
973
/**
974
 * Helper function to get the number of users online, using cache if available.
975
 *
976
 * @param int $minutes Number of minutes (how many users were active in those last X minutes?)
977
 *
978
 * @return int The number of users currently online
979
 */
980
function getOnlineUsersCount($minutes = null)
981
{
982
    $number = 0;
983
    $limit = !empty($minutes) ? intval($minutes) : api_get_setting('time_limit_whosonline');
984
    $cacheAvailable = api_get_configuration_value('apc');
985
    if ($cacheAvailable === true) {
986
        $apcVar = api_get_configuration_value('apc_prefix').'my_campus_whoisonline_count_simple_'.$minutes;
987
        if (apcu_exists($apcVar)) {
988
            $number = apcu_fetch($apcVar);
989
        } else {
990
            $number = who_is_online_count($limit);
991
            apcu_store($apcVar, $number, 15);
992
        }
993
    } else {
994
        $number = who_is_online_count($limit);
995
    }
996
997
    return $number;
998
}
999
1000
/**
1001
 * Helper function to get the number of users online in a course, using cache if available.
1002
 *
1003
 * @param int   $userId     The user ID
1004
 * @param array $courseInfo The course details
1005
 *
1006
 * @return int The number of users currently online
1007
 */
1008
function getOnlineUsersInCourseCount($userId, $courseInfo)
1009
{
1010
    $cacheAvailable = api_get_configuration_value('apc');
1011
    $numberOnlineInCourse = 0;
1012
    if (!empty($courseInfo['id'])) {
1013
        if ($cacheAvailable === true) {
1014
            $apcVar = api_get_configuration_value('apc_prefix').'my_campus_whoisonline_count_simple_'.$courseInfo['id'];
1015
            if (apcu_exists($apcVar)) {
1016
                $numberOnlineInCourse = apcu_fetch($apcVar);
1017
            } else {
1018
                $numberOnlineInCourse = who_is_online_in_this_course_count(
1019
                    $userId,
1020
                    api_get_setting('time_limit_whosonline'),
1021
                    $courseInfo['id']
1022
                );
1023
                apcu_store(
1024
                    $apcVar,
1025
                    $numberOnlineInCourse,
1026
                    15
1027
                );
1028
            }
1029
        } else {
1030
            $numberOnlineInCourse = who_is_online_in_this_course_count(
1031
                $userId,
1032
                api_get_setting('time_limit_whosonline'),
1033
                $courseInfo['id']
1034
            );
1035
        }
1036
    }
1037
1038
    return $numberOnlineInCourse;
1039
}
1040
1041
/**
1042
 * Helper function to get the number of users online in a session, using cache if available.
1043
 *
1044
 * @param int $sessionId The session ID
1045
 *
1046
 * @return int The number of users currently online
1047
 */
1048
function getOnlineUsersInSessionCount($sessionId)
1049
{
1050
    $cacheAvailable = api_get_configuration_value('apc');
1051
1052
    if (!$sessionId) {
1053
        return 0;
1054
    }
1055
1056
    if ($cacheAvailable === true) {
1057
        $apcVar = api_get_configuration_value('apc_prefix').'my_campus_whoisonline_session_count_simple_'.$sessionId;
1058
1059
        if (apcu_exists($apcVar)) {
1060
            return apcu_fetch($apcVar);
1061
        }
1062
1063
        $numberOnlineInCourse = whoIsOnlineInThisSessionCount(
1064
            api_get_setting('time_limit_whosonline'),
1065
            $sessionId
1066
        );
1067
        apcu_store($apcVar, $numberOnlineInCourse, 15);
1068
1069
        return $numberOnlineInCourse;
1070
    }
1071
1072
    return whoIsOnlineInThisSessionCount(
1073
        api_get_setting('time_limit_whosonline'),
1074
        $sessionId
1075
    );
1076
}
1077