Passed
Push — 1.11.x ( 47505b...220ec2 )
by Angel Fernando Quiroz
09:45 queued 11s
created

generateRedirectUrlAfterSubscription()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 15
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 7
c 0
b 0
f 0
nc 4
nop 2
dl 0
loc 15
rs 9.6111
1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
use Chamilo\CoreBundle\Entity\SequenceResource;
6
7
// Delete the globals['_cid'], we don't need it here.
8
$cidReset = true;
9
10
require_once __DIR__.'/../inc/global.inc.php';
11
12
$ctok = Security::get_existing_token();
13
14
// Get Limit data
15
$limit = CoursesAndSessionsCatalog::getLimitArray();
16
17
// Section for the tabs.
18
$this_section = SECTION_CATALOG;
19
20
if ('true' !== api_get_setting('course_catalog_published')) {
21
    // Access rights: anonymous users can't do anything useful here.
22
    api_block_anonymous_users();
23
}
24
25
$allowExtraFields = api_get_configuration_value('allow_course_extra_field_in_catalog');
26
27
// For students
28
$userCanViewPage = true;
29
if ('false' === api_get_setting('allow_students_to_browse_courses')) {
30
    $userCanViewPage = false;
31
}
32
33
//For teachers/admins
34
if (api_is_platform_admin() || api_is_course_admin() || api_is_allowed_to_create_course()) {
35
    $userCanViewPage = true;
36
}
37
38
$defaultAction = CoursesAndSessionsCatalog::is(CATALOG_SESSIONS) ? 'display_sessions' : 'display_courses';
39
$action = isset($_REQUEST['action']) ? Security::remove_XSS($_REQUEST['action']) : $defaultAction;
40
$categoryCode = isset($_REQUEST['category_code']) ? Security::remove_XSS($_REQUEST['category_code']) : '';
41
$searchTerm = isset($_REQUEST['search_term']) ? Security::remove_XSS($_REQUEST['search_term']) : '';
42
43
$nameTools = CourseCategory::getCourseCatalogNameTools($action);
44
if (empty($nameTools)) {
45
    $nameTools = get_lang('CourseManagement');
46
} else {
47
    if (!in_array(
48
        $action,
49
        ['display_random_courses', 'display_courses', 'subscribe']
50
    )) {
51
        $interbreadcrumb[] = [
52
            'url' => api_get_path(WEB_CODE_PATH).'auth/courses.php',
53
            'name' => get_lang('CourseManagement'),
54
        ];
55
    }
56
    $interbreadcrumb[] = ['url' => '#', 'name' => $nameTools];
57
}
58
59
$auth = new Auth();
60
$userId = api_get_user_id();
61
$currentUrl = api_get_path(WEB_CODE_PATH).'auth/courses.php?category_code='.$categoryCode.'&search_term='.$searchTerm;
62
$content = '';
63
$toolTitle = get_lang('CourseCatalog');
64
65
$courseCatalogSettings = [
66
    'info_url' => 'course_description_popup',
67
    'title_url' => 'course_home',
68
    'image_url' => 'course_about',
69
];
70
71
$redirectAfterSubscription = 'course_home';
72
$settings = api_get_configuration_value('course_catalog_settings');
73
// By default all extra fields are shown (visible and filterable)
74
$extraFieldsInSearchForm = [];
75
$extraFieldsInCourseBlock = [];
76
if (!empty($settings)) {
77
    if (isset($settings['link_settings'])) {
78
        $courseCatalogSettings = $settings['link_settings'];
79
    }
80
    if (isset($settings['redirect_after_subscription'])) {
81
        $redirectAfterSubscription = $settings['redirect_after_subscription'];
82
    }
83
84
    if (isset($settings['extra_fields_in_search_form'])) {
85
        $extraFieldsInSearchForm = $settings['extra_fields_in_search_form'];
86
    }
87
88
    if (isset($settings['extra_fields_in_course_block'])) {
89
        $extraFieldsInCourseBlock = $settings['extra_fields_in_course_block'];
90
    }
91
}
92
93
function generateRedirectUrlAfterSubscription($redirectAfterSubscription, $coursePublicUrl): string
94
{
95
    if ('course_home' !== $redirectAfterSubscription) {
96
        return api_get_self();
97
    }
98
99
    if (api_get_configuration_value('catalog_course_subscription_in_user_s_session')) {
100
        $user = api_get_user_entity(api_get_user_id());
101
102
        if ($user && $accesibleSessions = $user->getCurrentlyAccessibleSessions()) {
103
            return $coursePublicUrl.'?id_session='.$accesibleSessions[0]->getId();
104
        }
105
    }
106
107
    return $coursePublicUrl;
108
}
109
110
switch ($action) {
111
    case 'unsubscribe':
112
        // We are unsubscribing from a course (=Unsubscribe from course).
113
        if (!empty($_GET['sec_token']) && $ctok == $_GET['sec_token']) {
114
            $result = $auth->remove_user_from_course($_GET['unsubscribe']);
115
            if ($result) {
116
                Display::addFlash(
117
                    Display::return_message(get_lang('YouAreNowUnsubscribed'), 'success')
118
                );
119
            }
120
        }
121
122
        header('Location: '.$currentUrl);
123
        exit;
124
        break;
125
    case 'subscribe_course':
126
        $courseCodeToSubscribe = isset($_GET['course_code']) ? Security::remove_XSS($_GET['course_code']) : '';
127
        if (api_is_anonymous()) {
128
            header('Location: '.api_get_path(WEB_CODE_PATH).'auth/inscription.php?c='.$courseCodeToSubscribe);
129
            exit;
130
        }
131
        if (Security::check_token('get')) {
132
            $courseInfo = api_get_course_info($courseCodeToSubscribe);
133
            CourseManager::autoSubscribeToCourse($courseCodeToSubscribe);
134
            $redirectionTarget = generateRedirectUrlAfterSubscription(
135
                $redirectAfterSubscription,
136
                $courseInfo['course_public_url']
137
            );
138
139
            header("Location: $redirectionTarget");
140
            exit;
141
        }
142
        break;
143
    case 'subscribe_course_validation':
144
        $toolTitle = get_lang('Subscribe');
145
        $courseCodeToSubscribe = isset($_GET['course_code']) ? Security::remove_XSS($_GET['course_code']) : '';
146
        $courseInfo = api_get_course_info($courseCodeToSubscribe);
147
        if (empty($courseInfo)) {
148
            header('Location: '.api_get_self());
149
            exit;
150
        }
151
        $message = get_lang('CourseRequiresPassword').' ';
152
        $message .= $courseInfo['title'].' ('.$courseInfo['visual_code'].') ';
153
154
        $action = api_get_self().'?action=subscribe_course_validation&sec_token='.
155
            Security::getTokenFromSession().'&course_code='.$courseInfo['code'];
156
        $form = new FormValidator(
157
            'subscribe_user_with_password',
158
            'post',
159
            $action
160
        );
161
        $form->addHeader($message);
162
        $form->addElement('hidden', 'sec_token', Security::getTokenFromSession());
163
        $form->addElement('hidden', 'subscribe_user_with_password', $courseInfo['code']);
164
        $form->addElement('text', 'course_registration_code');
165
        $form->addButtonSave(get_lang('SubmitRegistrationCode'));
166
        $content = $form->returnForm();
167
168
        if ($form->validate()) {
169
            if (sha1($_POST['course_registration_code']) === $courseInfo['registration_code']) {
170
                CourseManager::autoSubscribeToCourse($_POST['subscribe_user_with_password']);
171
172
                $redirectionTarget = generateRedirectUrlAfterSubscription(
173
                    $redirectAfterSubscription,
174
                    $courseInfo['course_public_url']
175
                );
176
177
                header("Location: $redirectionTarget");
178
            } else {
179
                Display::addFlash(Display::return_message(get_lang('CourseRegistrationCodeIncorrect'), 'warning'));
180
                header('Location: '.$action);
181
            }
182
            exit;
183
        }
184
185
        break;
186
    case 'subscribe':
187
        if (!$userCanViewPage) {
188
            api_not_allowed(true);
189
        }
190
        header('Location: '.api_get_self());
191
        exit;
192
        break;
193
    case 'display_random_courses':
194
    case 'display_courses':
195
    case 'search_course':
196
        if (!$userCanViewPage) {
197
            api_not_allowed(true);
198
        }
199
200
        $settings = CoursesAndSessionsCatalog::getCatalogSearchSettings();
201
        $form = new FormValidator('search', 'get', '', null, null, FormValidator::LAYOUT_GRID);
202
        $form->addHidden('action', 'search_course');
203
        if (isset($settings['courses']) && true === $settings['courses']['by_title']) {
204
            $form->addText('search_term', get_lang('Title'));
205
        }
206
207
        $select = $form->addSelect(
208
            'category_code',
209
            get_lang('CourseCategories'),
210
            [],
211
            ['placeholder' => get_lang('SelectAnOption')]
212
        );
213
214
        $defaults = [];
215
        $listCategories = CoursesAndSessionsCatalog::getCourseCategoriesTree();
216
        foreach ($listCategories as $category) {
217
            $countCourse = (int) $category['number_courses'];
218
            if (empty($countCourse)) {
219
                continue;
220
            }
221
222
            $categoryCodeItem = Security::remove_XSS($category['code']);
223
            $categoryName = Security::remove_XSS($category['name']);
224
            $level = $category['level'];
225
            $separate = '';
226
            if ($level > 0) {
227
                $separate = str_repeat('--', $level);
228
            }
229
            $select->addOption($separate.' '.$categoryName.' ('.$countCourse.')', $categoryCodeItem);
230
        }
231
232
        $jqueryReadyContent = '';
233
        if ($allowExtraFields) {
234
            $extraField = new ExtraField('course');
235
            $onlyFields = [];
236
            $returnParams = $extraField->addElements($form, null, [], true, false, $extraFieldsInSearchForm);
237
            $jqueryReadyContent = $returnParams['jquery_ready_content'];
238
        }
239
240
        $sortKeySelect = $form->addSelect(
241
            'sortKeys',
242
            get_lang('SortKeys'),
243
            CoursesAndSessionsCatalog::courseSortOptions(),
244
            ['multiple' => true]
245
        );
246
247
        $sortKeys = isset($_REQUEST['sortKeys']) ? Security::remove_XSS($_REQUEST['sortKeys']) : '';
248
        $defaults['sortKeys'] = $sortKeys;
249
        $defaults['search_term'] = $searchTerm;
250
        $defaults['category_code'] = $categoryCode;
251
252
        $conditions = [];
253
        $fields = [];
254
        if ('display_random_courses' === $action) {
255
            // Random value is used instead limit filter
256
            $courses = CoursesAndSessionsCatalog::getCoursesInCategory(null, 12);
257
            $countCoursesInCategory = count($courses);
258
        } else {
259
            $values = $_REQUEST;
260
            if ($allowExtraFields) {
261
                $extraResult = $extraField->processExtraFieldSearch($values, $form, 'course', 'AND');
262
                $conditions = $extraResult['condition'];
263
                $fields = $extraResult['fields'];
264
                $defaults = $extraResult['defaults'];
265
266
                $defaults['sortKeys'] = $sortKeys;
267
                $defaults['search_term'] = $searchTerm;
268
                $defaults['category_code'] = $categoryCode;
269
            }
270
271
            $courses = CoursesAndSessionsCatalog::searchAndSortCourses(
272
                $categoryCode,
273
                $searchTerm,
274
                $limit,
275
                true,
276
                $conditions,
277
                $sortKeySelect->getValue()
278
            );
279
            $countCoursesInCategory = CourseCategory::countCoursesInCategory(
280
                $categoryCode,
281
                $searchTerm,
282
                true,
283
                true,
284
                $conditions
285
            );
286
        }
287
        $showCourses = CoursesAndSessionsCatalog::showCourses();
288
        $showSessions = CoursesAndSessionsCatalog::showSessions();
289
        $pageCurrent = isset($_GET['pageCurrent']) ? (int) $_GET['pageCurrent'] : 1;
290
        $pageLength = isset($_GET['pageLength']) ? (int) $_GET['pageLength'] : CoursesAndSessionsCatalog::PAGE_LENGTH;
291
        $pageTotal = (int) ceil($countCoursesInCategory / $pageLength);
292
293
        $url = CoursesAndSessionsCatalog::getCatalogUrl(1, $pageLength, 'ALL', 'search_course', $fields);
294
        $urlNoExtraFields = CoursesAndSessionsCatalog::getCatalogUrl(1, $pageLength, 'ALL', 'search_course');
295
        $urlNoCategory = CoursesAndSessionsCatalog::getCatalogUrl(1, $pageLength, '', 'search_course', $fields);
296
        $urlNoCategory = str_replace('&category_code=ALL', '', $urlNoCategory);
297
298
        $form->setAttribute('action', $url);
299
300
        // getting all the courses to which the user is subscribed to
301
        $user_courses = CourseManager::getCoursesByUserCourseCategory($userId);
302
        $user_coursecodes = [];
303
        // we need only the course codes as these will be used to match against the courses of the category
304
        if ('' != $user_courses) {
305
            foreach ($user_courses as $key => $value) {
306
                $user_coursecodes[] = $value['code'];
307
            }
308
        }
309
310
        if (api_is_drh()) {
311
            $coursesDrh = CourseManager::get_courses_followed_by_drh($userId);
312
            foreach ($coursesDrh as $course) {
313
                $user_coursecodes[] = $course['code'];
314
            }
315
        }
316
317
        $catalogShowCoursesSessions = 0;
318
        $showCoursesSessions = (int) api_get_setting('catalog_show_courses_sessions');
319
        if ($showCoursesSessions > 0) {
320
            $catalogShowCoursesSessions = $showCoursesSessions;
321
        }
322
323
        $catalogPagination = '';
324
        if ($pageTotal > 1) {
325
            $catalogPagination = CoursesAndSessionsCatalog::getCatalogPagination(
326
                $pageCurrent,
327
                $pageLength,
328
                $pageTotal,
329
                $categoryCode,
330
                $action,
331
                $fields,
332
                $sortKeySelect->getValue()
333
            );
334
        }
335
336
        $userInfo = api_get_user_info();
337
        $extraDate = '';
338
        if ($showSessions) {
339
            $extraDate = "
340
            $('#date').datepicker({
341
                dateFormat: 'yy-mm-dd'
342
            });";
343
        }
344
345
        $htmlHeadXtra[] = "
346
        <script>
347
            $(function() {
348
                $(\".selectpicker\").selectpicker({
349
                    \"width\": \"500px\",
350
                });
351
                $('.star-rating li a').on('click', function(event) {
352
                    var id = $(this).parents('ul').attr('id');
353
                    $('#vote_label2_' + id).html('".get_lang('Loading')."');
354
                    $.ajax({
355
                        url: $(this).attr('data-link'),
356
                        success: function(data) {
357
                            $('#rating_wrapper_'+id).html(data);
358
                        }
359
                    });
360
                });
361
362
                var getSessionId = function (el) {
363
                    var parts = el.id.split('_');
364
365
                    return parseInt(parts[1], 10);
366
                };
367
                $extraDate
368
            });
369
        </script>";
370
371
        $stok = Security::get_token();
372
        $content = CoursesAndSessionsCatalog::getTabList(1);
373
        $content .= '<div class="row">
374
        <div class="col-md-12">
375
            <div class="search-courses">
376
             ';
377
378
        if ($showCourses) {
379
            $htmlHeadXtra[] = '<script>
380
            $(function () {
381
                '.$jqueryReadyContent.'
382
            });
383
            </script>';
384
            $form->addButtonSearch(get_lang('Search'));
385
            $form->setDefaults($defaults);
386
387
            $content .= $form->returnForm();
388
        }
389
390
        $content .= '</div></div></div>';
391
392
        if ($showCourses) {
393
            $showTeacher = 'true' === api_get_setting('display_teacher_in_courselist');
394
            $ajax_url = api_get_path(WEB_AJAX_PATH).'course.ajax.php?a=add_course_vote';
395
            $user_id = api_get_user_id();
396
            $categoryListFromDatabase = CourseCategory::getAllCategories();
397
398
            $categoryList = [];
399
            if (!empty($categoryListFromDatabase)) {
400
                foreach ($categoryListFromDatabase as $categoryItem) {
401
                    $categoryList[$categoryItem['code']] = $categoryItem['name'];
402
                }
403
            }
404
405
            if ($allowExtraFields) {
406
                $extraFieldValues = new ExtraFieldValue('course');
407
                $em = Database::getManager();
408
                $fieldsRepo = $em->getRepository('ChamiloCoreBundle:ExtraField');
409
                $fieldTagsRepo = $em->getRepository('ChamiloCoreBundle:ExtraFieldRelTag');
410
            }
411
412
            $courseUrl = api_get_path(WEB_COURSE_PATH);
413
            $hideRating = api_get_configuration_value('hide_course_rating');
414
415
            if (!empty($courses)) {
416
                foreach ($courses as &$course) {
417
                    $courseId = $course['real_id'];
418
                    if (COURSE_VISIBILITY_HIDDEN == $course['visibility']) {
419
                        continue;
420
                    }
421
422
                    $aboutPage = api_get_path(WEB_PATH).'course/'.$course['real_id'].'/about';
423
                    $settingsUrl = [
424
                        'course_description_popup' => api_get_path(WEB_CODE_PATH).'inc/ajax/course_home.ajax.php?a=show_course_information&code='.$course['code'],
425
                        'course_about' => $aboutPage,
426
                        'course_home' => $courseUrl.$course['directory'].'/index.php?id_session=0',
427
                    ];
428
429
                    $infoUrl = $settingsUrl[$courseCatalogSettings['info_url']];
430
                    $course['title_url'] = $settingsUrl[$courseCatalogSettings['title_url']];
431
                    $course['image_url'] = $settingsUrl[$courseCatalogSettings['image_url']];
432
433
                    $userRegisteredInCourse = CourseManager::is_user_subscribed_in_course($user_id, $course['code']);
434
                    $userRegisteredInCourseAsTeacher = CourseManager::is_course_teacher($user_id, $course['code']);
435
                    $userRegistered = $userRegisteredInCourse && $userRegisteredInCourseAsTeacher;
436
437
                    $course_public = COURSE_VISIBILITY_OPEN_WORLD == $course['visibility'];
438
                    $course_open = COURSE_VISIBILITY_OPEN_PLATFORM == $course['visibility'];
439
                    $course_private = COURSE_VISIBILITY_REGISTERED == $course['visibility'];
440
                    $courseClosed = COURSE_VISIBILITY_CLOSED == $course['visibility'];
441
                    $course_subscribe_allowed = 1 == $course['subscribe'];
442
                    $course_unsubscribe_allowed = 1 == $course['unsubscribe'];
443
                    $count_connections = $course['count_connections'];
444
                    $creation_date = substr($course['creation_date'], 0, 10);
445
446
                    // display the course bloc
447
                    $course['category_title'] = '';
448
                    if (!empty($course['category_code'])) {
449
                        $course['category_title'] = isset($categoryList[$course['category_code']]) ? $categoryList[$course['category_code']] : '';
450
                        $course['category_code_link'] = $urlNoCategory.'&category_code='.$course['category_code'];
451
                    }
452
453
                    // Display thumbnail
454
                    $course['thumbnail'] = CoursesAndSessionsCatalog::returnThumbnail($course);
455
                    $course['description_button'] = CourseManager::returnDescriptionButton($course, $infoUrl);
456
                    $subscribeButton = CoursesAndSessionsCatalog::return_register_button(
457
                        $course,
458
                        $stok,
459
                        $categoryCode,
460
                        $searchTerm
461
                    );
462
463
                    // Start buy course validation
464
                    // display the course price and buy button if the buycourses plugin is enabled and this course is configured
465
                    $plugin = BuyCoursesPlugin::create();
466
                    $isThisCourseInSale = $plugin->buyCoursesForGridCatalogValidator(
467
                        $courseId,
468
                        BuyCoursesPlugin::PRODUCT_TYPE_COURSE
469
                    );
470
471
                    $separator = '';
472
                    if ($isThisCourseInSale) {
473
                        // set the Price label
474
                        $separator = $isThisCourseInSale['html'];
475
                        // set the Buy button instead register.
476
                        if ($isThisCourseInSale['verificator']) {
477
                            $subscribeButton = $plugin->returnBuyCourseButton(
478
                                $courseId,
479
                                BuyCoursesPlugin::PRODUCT_TYPE_COURSE
480
                            );
481
                        }
482
                    }
483
484
                    $course['rating'] = '';
485
                    if ($hideRating === false) {
486
                        $ajax_url = api_get_path(WEB_AJAX_PATH).'course.ajax.php?a=add_course_vote';
487
                        $rating = Display::return_rating_system(
488
                            'star_'.$course['real_id'],
489
                            $ajax_url.'&course_id='.$course['real_id'],
490
                            $course['point_info']
491
                        );
492
                        $course['rating'] = '<div class="ranking">'.$rating.'</div>';
493
                    }
494
495
                    if ($showTeacher) {
496
                        $course['teacher_info'] = CoursesAndSessionsCatalog::return_teacher($course);
497
                    }
498
499
                    // display button line
500
                    $course['buy_course'] = $separator;
501
                    $course['extra_data'] = '';
502
                    if ($allowExtraFields) {
503
                        $course['extra_data'] = $extraField->getDataAndFormattedValues(
504
                            $courseId,
505
                            true,
506
                            $extraFieldsInCourseBlock
507
                        );
508
                    }
509
510
                    // if user registered as student
511
                    if ($userRegisteredInCourse) {
512
                        $course['already_registered_formatted'] = Display::url(
513
                            Display::returnFontAwesomeIcon('external-link').'&nbsp;'.
514
                            get_lang('GoToCourse'),
515
                            $courseUrl.$course['directory'].'/index.php?id_session=0',
516
                            ['class' => 'btn btn-primary']
517
                        );
518
                        if (!$courseClosed && $course_unsubscribe_allowed &&
519
                            false === $userRegisteredInCourseAsTeacher
520
                        ) {
521
                            $course['unregister_formatted'] = CoursesAndSessionsCatalog::return_unregister_button(
522
                                $course,
523
                                $stok,
524
                                $searchTerm,
525
                                $categoryCode
526
                            );
527
                        }
528
                    } elseif ($userRegisteredInCourseAsTeacher) {
529
                        // if user registered as teacher
530
                        // Updated teacher cannot unregister himself.
531
                        /*if ($course_unsubscribe_allowed) {
532
                            $course['unregister_formatted'] = CoursesAndSessionsCatalog::return_unregister_button(
533
                                $course,
534
                                $stok,
535
                                $searchTerm,
536
                                $categoryCode
537
                            );
538
                        }*/
539
                    } else {
540
                        // if user not registered in the course
541
                        if (!$courseClosed) {
542
                            if (!$course_private) {
543
                                if ($course_subscribe_allowed) {
544
                                    $course['subscribe_formatted'] = $subscribeButton;
545
                                }
546
                            }
547
                        }
548
                    }
549
                }
550
            } else {
551
                if (!isset($_REQUEST['subscribe_user_with_password']) &&
552
                    !isset($_REQUEST['subscribe_course'])
553
                ) {
554
                    Display::addFlash(Display::return_message(get_lang('NoResults'), 'warning'));
555
                }
556
            }
557
        }
558
559
        if (api_is_course_admin()) {
560
            foreach ($courses as &$course) {
561
                $course['admin_url'] = api_get_path(WEB_CODE_PATH).'/admin/course_list.php?keyword='.$course['code'];
562
            }
563
        }
564
565
        $template = new Template($toolTitle, true, true, false, false, false);
566
        $template->assign('content', $content);
567
        $template->assign('courses', $courses);
568
        $template->assign(
569
            'total_number_of_courses',
570
            CoursesAndSessionsCatalog::countAvailableCoursesToShowInCatalog(
571
                api_get_current_access_url_id()
572
            )
573
        );
574
        $template->assign('total_number_of_matching_courses', $countCoursesInCategory);
575
        $template->assign('catalog_url_no_extra_fields', $urlNoExtraFields);
576
        $template->assign('pagination', $catalogPagination);
577
578
        $template->display($template->get_template('catalog/course_catalog.tpl'));
579
        exit;
580
        break;
581
    case 'display_sessions':
582
        if (!$userCanViewPage) {
583
            api_not_allowed(true);
584
        }
585
586
        CoursesAndSessionsCatalog::sessionList($limit);
587
        exit;
588
        break;
589
    case 'subscribe_to_session':
590
        if (!$userCanViewPage) {
591
            api_not_allowed(true);
592
        }
593
594
        $userId = api_get_user_id();
595
        $confirmed = isset($_GET['confirm']);
596
        $sessionId = (int) $_GET['session_id'];
597
598
        if (empty($userId)) {
599
            api_not_allowed();
600
            exit;
601
        }
602
603
        if (!$confirmed) {
604
            $template = new Template(null, false, false, false, false, false);
605
            $template->assign('session_id', $sessionId);
606
            $layout = $template->get_template('auth/confirm_session_subscription.tpl');
607
            echo $template->fetch($layout);
608
            exit;
609
        }
610
611
        $registrationAllowed = api_get_setting('catalog_allow_session_auto_subscription');
612
        if ('true' === $registrationAllowed) {
613
            $entityManager = Database::getManager();
614
            $repository = $entityManager->getRepository('ChamiloCoreBundle:SequenceResource');
615
            $sequences = $repository->getRequirements(
616
                $sessionId,
617
                SequenceResource::SESSION_TYPE
618
            );
619
620
            if (count($sequences) > 0) {
621
                $requirementsData = $repository->checkRequirementsForUser(
622
                    $sequences,
623
                    SequenceResource::SESSION_TYPE,
624
                    $userId,
625
                    $sessionId
626
                );
627
628
                $continueWithSubscription = $repository->checkSequenceAreCompleted($requirementsData);
629
630
                if (!$continueWithSubscription) {
631
                    header('Location: '.api_get_path(WEB_CODE_PATH).'auth/courses.php');
632
                    exit;
633
                }
634
            }
635
636
            SessionManager::subscribeUsersToSession(
637
                $sessionId,
638
                [$userId],
639
                SESSION_VISIBLE_READ_ONLY,
640
                false
641
            );
642
643
            $coursesList = SessionManager::get_course_list_by_session_id($sessionId);
644
            $count = count($coursesList);
645
            $url = '';
646
647
            if ($count <= 0) {
648
                // no course in session -> return to catalog
649
                $url = api_get_path(WEB_CODE_PATH).'auth/courses.php';
650
            } elseif (1 == $count) {
651
                // only one course, so redirect directly to this course
652
                foreach ($coursesList as $course) {
653
                    $url = api_get_path(WEB_COURSE_PATH).$course['directory'].'/index.php?id_session='.$sessionId;
654
                }
655
            } else {
656
                $url = api_get_path(WEB_CODE_PATH).'session/index.php?session_id='.$sessionId;
657
            }
658
            header('Location: '.$url);
659
            exit;
660
        }
661
        break;
662
    case 'search_tag':
663
        if (!$userCanViewPage) {
664
            api_not_allowed(true);
665
        }
666
667
        CoursesAndSessionsCatalog::sessionsListByCoursesTag($limit);
668
        exit;
669
        break;
670
    case 'search_session_title':
671
        if (!$userCanViewPage) {
672
            api_not_allowed(true);
673
        }
674
675
        CoursesAndSessionsCatalog::sessionsListByName($limit);
676
        exit;
677
        break;
678
}
679
680
$template = new Template($toolTitle, true, true, false, false, false);
681
$template->assign('content', $content);
682
$template->display_one_col_template();
683