Passed
Pull Request — master (#4020)
by Yannick
09:55
created

CourseController::autoLaunch()   F

Complexity

Conditions 31
Paths 18192

Size

Total Lines 168
Code Lines 111

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 31
eloc 111
c 0
b 0
f 0
nc 18192
nop 0
dl 0
loc 168
rs 0

How to fix   Long Method    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
3
declare(strict_types=1);
4
5
/* For licensing terms, see /license.txt */
6
7
namespace Chamilo\CoreBundle\Controller;
8
9
use Chamilo\CoreBundle\Entity\Course;
10
use Chamilo\CoreBundle\Entity\ExtraField;
11
use Chamilo\CoreBundle\Entity\Tag;
12
use Chamilo\CoreBundle\Framework\Container;
13
use Chamilo\CoreBundle\Repository\ExtraFieldRelTagRepository;
14
use Chamilo\CoreBundle\Repository\LanguageRepository;
15
use Chamilo\CoreBundle\Repository\LegalRepository;
16
use Chamilo\CoreBundle\Repository\Node\IllustrationRepository;
17
use Chamilo\CoreBundle\Repository\TagRepository;
18
use Chamilo\CoreBundle\Security\Authorization\Voter\CourseVoter;
19
use Chamilo\CoreBundle\Tool\ToolChain;
20
use Chamilo\CourseBundle\Controller\ToolBaseController;
21
use Chamilo\CourseBundle\Entity\CCourseDescription;
22
use Chamilo\CourseBundle\Entity\CTool;
23
use Chamilo\CourseBundle\Repository\CCourseDescriptionRepository;
24
use Chamilo\CourseBundle\Repository\CShortcutRepository;
25
use Chamilo\CourseBundle\Repository\CToolRepository;
26
use Chamilo\CourseBundle\Settings\SettingsCourseManager;
27
use Chamilo\CourseBundle\Settings\SettingsFormFactory;
28
use CourseManager;
29
use Database;
30
use Display;
31
use Doctrine\ORM\EntityRepository;
32
use Event;
33
use Exercise;
34
use ExtraFieldValue;
35
use Fhaculty\Graph\Graph;
36
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Entity;
37
use Symfony\Component\HttpFoundation\RedirectResponse;
38
use Symfony\Component\HttpFoundation\Request;
39
use Symfony\Component\HttpFoundation\Response;
40
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
41
use Symfony\Component\Routing\Annotation\Route;
42
use Symfony\Component\Validator\Exception\ValidatorException;
43
use UnserializeApi;
44
use UserManager;
45
46
/**
47
 * @author Julio Montoya <[email protected]>
48
 */
49
#[Route('/course')]
50
class CourseController extends ToolBaseController
51
{
52
    #[Route('/{cid}/checkLegal.json', name: 'chamilo_core_course_check_legal_json')]
53
    public function checkTermsAndConditionJson(Request $request, LegalRepository $legalTermsRepo, LanguageRepository $languageRepository): Response
54
    {
55
        $user = $this->getUser();
56
        $course = $this->getCourse();
57
        $responseData = [
58
            'redirect' => false,
59
            'url' => '#',
60
        ];
61
62
        $termAndConditionStatus = $legalTermsRepo->checkTermCondition($user);
63
        if (false === $termAndConditionStatus) {
64
            $request->getSession()->set('term_and_condition', ['user_id' => $user->getId()]);
65
        } else {
66
            $request->getSession()->remove('term_and_condition');
67
        }
68
        $termsAndCondition = $request->getSession()->get('term_and_condition');
69
        if (null !== $termsAndCondition) {
70
            // user id
71
            $userId = $termsAndCondition['user_id'];
72
73
            // Update the terms & conditions
74
            $legalType = null;
75
76
            // Verify type of terms and conditions
77
            if (null !== $request->get('legal_info')) {
78
                $infoLegal = explode(':', $request->get('legal_info'));
79
                $legalId = (int) $infoLegal[0];
80
                $languageId = (int) $infoLegal[1];
81
                $legal = $legalTermsRepo->find($legalId);
82
                $language = $languageRepository->find($languageId);
83
                $legalType = $legalTermsRepo->getTypeOfTermsAndConditions($legal, $language);
84
            }
85
86
            $legalOption = (empty($legalType));
87
            // is necessary verify check
88
            if (1 === $legalType) {
89
                $legalOption = (null !== $request->get('legal_accept') && 1 === (int) $request->get('legal_accept'));
90
            }
91
92
            if (null !== $request->get('legal_accept_type') && true === $legalOption) {
93
                $condArray = explode(':', $request->get('legal_accept_type'));
94
                if (!empty($condArray[0]) && !empty($condArray[1])) {
95
                    $time = time();
96
                    $conditionToSave = intval($condArray[0]).':'.intval($condArray[1]).':'.$time;
97
                    UserManager::update_extra_field_value(
98
                        $userId,
99
                        'legal_accept',
100
                        $conditionToSave
101
                    );
102
                }
103
            }
104
105
            $redirect = true;
106
            $allow = api_get_configuration_value('allow_public_course_with_no_terms_conditions');
107
            if (true === $allow &&
108
                null !== $course->getVisibility() &&
109
                COURSE_VISIBILITY_OPEN_WORLD == $course->getVisibility()
110
            ) {
111
                $redirect = false;
112
            }
113
            if ($redirect && !$this->isGranted('ROLE_ADMIN')) {
114
                $url = '/main/auth/inscription.php';
115
                $responseData = [
116
                    'redirect' => $redirect,
117
                    'url' => $url,
118
                ];
119
            }
120
        }
121
122
        $json = $this->get('serializer')->serialize(
123
            $responseData,
124
            'json',
125
            [
126
                'groups' => ['course:read', 'ctool:read', 'tool:read', 'cshortcut:read'],
127
            ]
128
        );
129
130
        return new Response(
131
            $json,
132
            Response::HTTP_OK,
133
            [
134
                'Content-type' => 'application/json',
135
            ]
136
        );
137
    }
138
139
    #[Route('/{cid}/home.json', name: 'chamilo_core_course_home_json')]
140
    #[Entity('course', expr: 'repository.find(cid)')]
141
    public function indexJson(Request $request, CToolRepository $toolRepository, CShortcutRepository $shortcutRepository, ToolChain $toolChain): Response
142
    {
143
        $course = $this->getCourse();
144
        $sessionId = $this->getSessionId();
145
146
        if (null === $course) {
147
            throw $this->createAccessDeniedException();
148
        }
149
150
        if (empty($sessionId)) {
151
            $this->denyAccessUnlessGranted(CourseVoter::VIEW, $course);
152
        }
153
154
        $session = $request->getSession();
155
156
        $userId = 0;
157
        $user = $this->getUser();
158
        if (null !== $user) {
159
            $userId = $user->getId();
160
        }
161
162
        $courseCode = $course->getCode();
163
        $courseId = $course->getId();
164
165
        if ($user && $user->hasRole('ROLE_INVITEE')) {
166
            $isInASession = $sessionId > 0;
167
            $isSubscribed = CourseManager::is_user_subscribed_in_course(
168
                $userId,
169
                $courseCode,
170
                $isInASession,
171
                $sessionId
172
            );
173
174
            if (!$isSubscribed) {
175
                throw $this->createAccessDeniedException();
176
            }
177
        }
178
179
        $courseSession = $this->getCourseSession();
180
181
        $isSpecialCourse = CourseManager::isSpecialCourse($courseId);
182
183
        if ($user && $isSpecialCourse && (isset($_GET['autoreg']) && 1 === (int) $_GET['autoreg']) &&
184
            CourseManager::subscribeUser($userId, $courseId, STUDENT)
185
        ) {
186
            $session->set('is_allowed_in_course', true);
187
        }
188
189
        $logInfo = [
190
            'tool' => 'course-main',
191
        ];
192
        Event::registerLog($logInfo);
193
194
        $qb = $toolRepository->getResourcesByCourse($course, $this->getSession());
195
196
        $qb->addSelect('tool');
197
        $qb->innerJoin('resource.tool', 'tool');
198
199
        $result = $qb->getQuery()->getResult();
200
        $tools = [];
201
        $isCourseTeacher = $this->isGranted('ROLE_CURRENT_COURSE_TEACHER');
202
203
        $skipTools = ['course_tool', 'chat', 'notebook', 'wiki'];
204
205
        /** @var CTool $item */
206
        foreach ($result as $item) {
207
            if (\in_array($item->getName(), $skipTools, true)) {
208
                continue;
209
            }
210
            $toolModel = $toolChain->getToolFromName($item->getTool()->getName());
211
212
            if (!$isCourseTeacher && 'admin' === $toolModel->getCategory()) {
213
                continue;
214
            }
215
216
            $tools[$toolModel->getCategory()][] = [
217
                'ctool' => $item,
218
                'tool' => $toolModel,
219
            ];
220
        }
221
222
        // Get session-career diagram
223
        $diagram = '';
224
        /*$allow = api_get_configuration_value('allow_career_diagram');
225
        if (true === $allow) {
226
            $htmlHeadXtra[] = api_get_js('jsplumb2.js');
227
            $extra = new ExtraFieldValue('session');
228
            $value = $extra->get_values_by_handler_and_field_variable(
229
                api_get_session_id(),
230
                'external_career_id'
231
            );
232
233
            if (!empty($value) && isset($value['value'])) {
234
                $careerId = $value['value'];
235
                $extraFieldValue = new ExtraFieldValue('career');
236
                $item = $extraFieldValue->get_item_id_from_field_variable_and_field_value(
237
                    'external_career_id',
238
                    $careerId,
239
                    false,
240
                    false,
241
                    false
242
                );
243
244
                if (!empty($item) && isset($item['item_id'])) {
245
                    $careerId = $item['item_id'];
246
                    $career = new Career();
247
                    $careerInfo = $career->get($careerId);
248
                    if (!empty($careerInfo)) {
249
                        $extraFieldValue = new ExtraFieldValue('career');
250
                        $item = $extraFieldValue->get_values_by_handler_and_field_variable(
251
                            $careerId,
252
                            'career_diagram',
253
                            false,
254
                            false,
255
                            0
256
                        );
257
258
                        if (!empty($item) && isset($item['value']) && !empty($item['value'])) {
259
                            // @var Graph $graph
260
                            $graph = UnserializeApi::unserialize('career', $item['value']);
261
                            $diagram = Career::renderDiagram($careerInfo, $graph);
262
                        }
263
                    }
264
                }
265
            }
266
        }*/
267
268
        // Deleting the objects
269
        $session->remove('toolgroup');
270
        $session->remove('_gid');
271
        $session->remove('oLP');
272
        $session->remove('lpobject');
273
274
        api_remove_in_gradebook();
275
        Exercise::cleanSessionVariables();
276
277
        $shortcuts = [];
278
        if (null !== $user) {
279
            $shortcutQuery = $shortcutRepository->getResources($course->getResourceNode());
280
            $shortcuts = $shortcutQuery->getQuery()->getResult();
281
        }
282
        $responseData = [
283
            'course' => $course,
284
            'session' => $courseSession,
285
            'shortcuts' => $shortcuts,
286
            'diagram' => $diagram,
287
            'tools' => $tools,
288
        ];
289
290
        $json = $this->get('serializer')->serialize(
291
            $responseData,
292
            'json',
293
            [
294
                'groups' => ['course:read', 'ctool:read', 'tool:read', 'cshortcut:read'],
295
            ]
296
        );
297
298
        return new Response(
299
            $json,
300
            Response::HTTP_OK,
301
            [
302
                'Content-type' => 'application/json',
303
            ]
304
        );
305
    }
306
307
    /**
308
     * Redirects the page to a tool, following the tools settings.
309
     */
310
    #[Route('/{cid}/tool/{toolName}', name: 'chamilo_core_course_redirect_tool')]
311
    public function redirectTool(string $toolName, CToolRepository $repo, ToolChain $toolChain): RedirectResponse
312
    {
313
        /** @var CTool|null $tool */
314
        $tool = $repo->findOneBy([
315
            'name' => $toolName,
316
        ]);
317
318
        if (null === $tool) {
319
            throw new NotFoundHttpException($this->trans('Tool not found'));
320
        }
321
322
        $tool = $toolChain->getToolFromName($tool->getTool()->getName());
323
        $link = $tool->getLink();
324
325
        if (null === $this->getCourse()) {
326
            throw new NotFoundHttpException($this->trans('Course not found'));
327
        }
328
329
        if (strpos($link, 'nodeId')) {
330
            $nodeId = (string) $this->getCourse()->getResourceNode()->getId();
331
            $link = str_replace(':nodeId', $nodeId, $link);
332
        }
333
334
        $url = $link.'?'.$this->getCourseUrlQuery();
335
336
        return $this->redirect($url);
337
    }
338
339
    /*public function redirectToShortCut(string $toolName, CToolRepository $repo, ToolChain $toolChain): RedirectResponse
340
    {
341
        $tool = $repo->findOneBy([
342
            'name' => $toolName,
343
        ]);
344
345
        if (null === $tool) {
346
            throw new NotFoundHttpException($this->trans('Tool not found'));
347
        }
348
349
        $tool = $toolChain->getToolFromName($tool->getTool()->getName());
350
        $link = $tool->getLink();
351
352
        if (strpos($link, 'nodeId')) {
353
            $nodeId = (string) $this->getCourse()->getResourceNode()->getId();
354
            $link = str_replace(':nodeId', $nodeId, $link);
355
        }
356
357
        $url = $link.'?'.$this->getCourseUrlQuery();
358
359
        return $this->redirect($url);
360
    }*/
361
362
    /**
363
     * Edit configuration with given namespace.
364
     */
365
    #[Route('/{cid}/settings/{namespace}', name: 'chamilo_core_course_settings')]
366
    #[Entity('course', expr: 'repository.find(cid)')]
367
    public function updateSettings(Request $request, Course $course, string $namespace, SettingsCourseManager $manager, SettingsFormFactory $formFactory): Response
368
    {
369
        $this->denyAccessUnlessGranted(CourseVoter::VIEW, $course);
370
371
        $schemaAlias = $manager->convertNameSpaceToService($namespace);
372
        $settings = $manager->load($namespace);
373
374
        $form = $formFactory->create($schemaAlias);
375
376
        $form->setData($settings);
377
        $form->handleRequest($request);
378
379
        if ($form->isSubmitted() && $form->isValid()) {
380
            $messageType = 'success';
381
382
            try {
383
                $manager->setCourse($course);
384
                $manager->save($form->getData());
385
                $message = $this->trans('Update');
386
            } catch (ValidatorException $validatorException) {
387
                $message = $this->trans($validatorException->getMessage());
388
                $messageType = 'error';
389
            }
390
            $this->addFlash($messageType, $message);
391
392
            if ($request->headers->has('referer')) {
393
                return $this->redirect($request->headers->get('referer'));
394
            }
395
        }
396
397
        $schemas = $manager->getSchemas();
398
399
        return $this->render(
400
            '@ChamiloCore/Course/settings.html.twig',
401
            [
402
                'course' => $course,
403
                'schemas' => $schemas,
404
                'settings' => $settings,
405
                'form' => $form->createView(),
406
            ]
407
        );
408
    }
409
410
    #[Route('/{id}/about', name: 'chamilo_core_course_about')]
411
    public function about(Course $course, IllustrationRepository $illustrationRepository, CCourseDescriptionRepository $courseDescriptionRepository): Response
412
    {
413
        $courseId = $course->getId();
414
        $userId = $this->getUser()->getId();
415
        $em = $this->getDoctrine()->getManager();
416
417
        /** @var EntityRepository $fieldsRepo */
418
        $fieldsRepo = $em->getRepository(ExtraField::class);
419
        /** @var TagRepository $tagRepo */
420
        $tagRepo = $em->getRepository(Tag::class);
421
422
        $courseDescriptions = $courseDescriptionRepository->getResourcesByCourse($course)->getQuery()->getResult();
423
424
        $courseValues = new ExtraFieldValue('course');
425
426
        $urlCourse = api_get_path(WEB_PATH).sprintf('course/%s/about', $courseId);
427
        $courseTeachers = $course->getTeachers();
428
        $teachersData = [];
429
430
        foreach ($courseTeachers as $teacherSubscription) {
431
            $teacher = $teacherSubscription->getUser();
432
            $userData = [
433
                'complete_name' => UserManager::formatUserFullName($teacher),
434
                'image' => $illustrationRepository->getIllustrationUrl($teacher),
435
                'diploma' => $teacher->getDiplomas(),
436
                'openarea' => $teacher->getOpenarea(),
437
            ];
438
439
            $teachersData[] = $userData;
440
        }
441
        /** @var ExtraField $tagField */
442
        $tagField = $fieldsRepo->findOneBy([
443
            'extraFieldType' => ExtraField::COURSE_FIELD_TYPE,
444
            'variable' => 'tags',
445
        ]);
446
447
        $courseTags = [];
448
        if (null !== $tagField) {
449
            $courseTags = $tagRepo->getTagsByItem($tagField, $courseId);
450
        }
451
452
        $courseDescription = $courseObjectives = $courseTopics = $courseMethodology = '';
453
        $courseMaterial = $courseResources = $courseAssessment = '';
454
        $courseCustom = [];
455
        foreach ($courseDescriptions as $descriptionTool) {
456
            switch ($descriptionTool->getDescriptionType()) {
457
                case CCourseDescription::TYPE_DESCRIPTION:
458
                    $courseDescription = $descriptionTool->getContent();
459
460
                    break;
461
                case CCourseDescription::TYPE_OBJECTIVES:
462
                    $courseObjectives = $descriptionTool;
463
464
                    break;
465
                case CCourseDescription::TYPE_TOPICS:
466
                    $courseTopics = $descriptionTool;
467
468
                    break;
469
                case CCourseDescription::TYPE_METHODOLOGY:
470
                    $courseMethodology = $descriptionTool;
471
472
                    break;
473
                case CCourseDescription::TYPE_COURSE_MATERIAL:
474
                    $courseMaterial = $descriptionTool;
475
476
                    break;
477
                case CCourseDescription::TYPE_RESOURCES:
478
                    $courseResources = $descriptionTool;
479
480
                    break;
481
                case CCourseDescription::TYPE_ASSESSMENT:
482
                    $courseAssessment = $descriptionTool;
483
484
                    break;
485
                case CCourseDescription::TYPE_CUSTOM:
486
                    $courseCustom[] = $descriptionTool;
487
488
                    break;
489
            }
490
        }
491
492
        $topics = [
493
            'objectives' => $courseObjectives,
494
            'topics' => $courseTopics,
495
            'methodology' => $courseMethodology,
496
            'material' => $courseMaterial,
497
            'resources' => $courseResources,
498
            'assessment' => $courseAssessment,
499
            'custom' => array_reverse($courseCustom),
500
        ];
501
502
        $subscriptionUser = CourseManager::is_user_subscribed_in_course($userId, $course->getCode());
503
504
        /*$allowSubscribe = false;
505
        if ($course->getSubscribe() || api_is_platform_admin()) {
506
            $allowSubscribe = true;
507
        }
508
        $plugin = \BuyCoursesPlugin::create();
509
        $checker = $plugin->isEnabled();
510
        $courseIsPremium = null;
511
        if ($checker) {
512
            $courseIsPremium = $plugin->getItemByProduct(
513
                $courseId,
514
                \BuyCoursesPlugin::PRODUCT_TYPE_COURSE
515
            );
516
        }*/
517
518
        $image = Container::getIllustrationRepository()->getIllustrationUrl($course, 'course_picture_medium');
519
520
        $params = [
521
            'course' => $course,
522
            'description' => $courseDescription,
523
            'image' => $image,
524
            'syllabus' => $topics,
525
            'tags' => $courseTags,
526
            'teachers' => $teachersData,
527
            'extra_fields' => $courseValues->getAllValuesForAnItem(
528
                $course->getId(),
529
                null,
530
                true
531
            ),
532
            'subscription' => $subscriptionUser,
533
            'url' => '',
534
            'is_premium' => '',
535
            'token' => '',
536
        ];
537
538
        $metaInfo = '<meta property="og:url" content="'.$urlCourse.'" />';
539
        $metaInfo .= '<meta property="og:type" content="website" />';
540
        $metaInfo .= '<meta property="og:title" content="'.$course->getTitle().'" />';
541
        $metaInfo .= '<meta property="og:description" content="'.strip_tags($courseDescription).'" />';
542
        $metaInfo .= '<meta property="og:image" content="'.$image.'" />';
543
544
        $htmlHeadXtra[] = $metaInfo;
545
        $htmlHeadXtra[] = api_get_asset('readmore-js/readmore.js');
546
547
        return $this->render('@ChamiloCore/Course/about.html.twig', $params);
548
    }
549
550
    #[Route('/{id}/welcome', name: 'chamilo_core_course_welcome')]
551
    public function welcome(Course $course): Response
552
    {
553
        return $this->render('@ChamiloCore/Course/welcome.html.twig', [
554
            'course' => $course,
555
        ]);
556
    }
557
558
    private function autoLaunch(): void
559
    {
560
        $autoLaunchWarning = '';
561
        $showAutoLaunchLpWarning = false;
562
        $course_id = api_get_course_int_id();
563
        $lpAutoLaunch = api_get_course_setting('enable_lp_auto_launch');
564
        $session_id = api_get_session_id();
565
        $allowAutoLaunchForCourseAdmins =
566
            api_is_platform_admin() ||
567
            api_is_allowed_to_edit(true, true) ||
568
            api_is_coach();
569
570
        if (!empty($lpAutoLaunch)) {
571
            if (2 === $lpAutoLaunch) {
572
                // LP list
573
                if ($allowAutoLaunchForCourseAdmins) {
574
                    $showAutoLaunchLpWarning = true;
575
                } else {
576
                    $session_key = 'lp_autolaunch_'.$session_id.'_'.$course_id.'_'.api_get_user_id();
577
                    if (!isset($_SESSION[$session_key])) {
578
                        // Redirecting to the LP
579
                        $url = api_get_path(WEB_CODE_PATH).'lp/lp_controller.php?'.api_get_cidreq();
580
                        $_SESSION[$session_key] = true;
581
                        header(sprintf('Location: %s', $url));
582
                        exit;
583
                    }
584
                }
585
            } else {
586
                $lp_table = Database::get_course_table(TABLE_LP_MAIN);
587
                $condition = '';
588
                if (!empty($session_id)) {
589
                    $condition = api_get_session_condition($session_id);
590
                    $sql = "SELECT id FROM {$lp_table}
591
                            WHERE c_id = {$course_id} AND autolaunch = 1 {$condition}
592
                            LIMIT 1";
593
                    $result = Database::query($sql);
594
                    // If we found nothing in the session we just called the session_id =  0 autolaunch
595
                    if (0 === Database::num_rows($result)) {
596
                        $condition = '';
597
                    }
598
                }
599
600
                $sql = "SELECT iid FROM {$lp_table}
601
                        WHERE c_id = {$course_id} AND autolaunch = 1 {$condition}
602
                        LIMIT 1";
603
                $result = Database::query($sql);
604
                if (Database::num_rows($result) > 0) {
605
                    $lp_data = Database::fetch_array($result, 'ASSOC');
606
                    if (!empty($lp_data['iid'])) {
607
                        if ($allowAutoLaunchForCourseAdmins) {
608
                            $showAutoLaunchLpWarning = true;
609
                        } else {
610
                            $session_key = 'lp_autolaunch_'.$session_id.'_'.api_get_course_int_id().'_'.api_get_user_id();
611
                            if (!isset($_SESSION[$session_key])) {
612
                                // Redirecting to the LP
613
                                $url = api_get_path(WEB_CODE_PATH).
614
                                    'lp/lp_controller.php?'.api_get_cidreq().'&action=view&lp_id='.$lp_data['iid'];
615
616
                                $_SESSION[$session_key] = true;
617
                                header(sprintf('Location: %s', $url));
618
                                exit;
619
                            }
620
                        }
621
                    }
622
                }
623
            }
624
        }
625
626
        if ($showAutoLaunchLpWarning) {
627
            $autoLaunchWarning = get_lang(
628
                'The learning path auto-launch setting is ON. When learners enter this course, they will be automatically redirected to the learning path marked as auto-launch.'
629
            );
630
        }
631
632
        $forumAutoLaunch = (int) api_get_course_setting('enable_forum_auto_launch');
633
        if (1 === $forumAutoLaunch) {
634
            if ($allowAutoLaunchForCourseAdmins) {
635
                if (empty($autoLaunchWarning)) {
636
                    $autoLaunchWarning = get_lang(
637
                        "The forum's auto-launch setting is on. Students will be redirected to the forum tool when entering this course."
638
                    );
639
                }
640
            } else {
641
                $url = api_get_path(WEB_CODE_PATH).'forum/index.php?'.api_get_cidreq();
642
                header(sprintf('Location: %s', $url));
643
                exit;
644
            }
645
        }
646
647
        if (api_get_configuration_value('allow_exercise_auto_launch')) {
648
            $exerciseAutoLaunch = (int) api_get_course_setting('enable_exercise_auto_launch');
649
            if (2 === $exerciseAutoLaunch) {
650
                if ($allowAutoLaunchForCourseAdmins) {
651
                    if (empty($autoLaunchWarning)) {
652
                        $autoLaunchWarning = get_lang(
653
                            'TheExerciseAutoLaunchSettingIsONStudentsWillBeRedirectToTheExerciseList'
654
                        );
655
                    }
656
                } else {
657
                    // Redirecting to the document
658
                    $url = api_get_path(WEB_CODE_PATH).'exercise/exercise.php?'.api_get_cidreq();
659
                    header(sprintf('Location: %s', $url));
660
                    exit;
661
                }
662
            } elseif (1 === $exerciseAutoLaunch) {
663
                if ($allowAutoLaunchForCourseAdmins) {
664
                    if (empty($autoLaunchWarning)) {
665
                        $autoLaunchWarning = get_lang(
666
                            'TheExerciseAutoLaunchSettingIsONStudentsWillBeRedirectToAnSpecificExercise'
667
                        );
668
                    }
669
                } else {
670
                    // Redirecting to an exercise
671
                    $table = Database::get_course_table(TABLE_QUIZ_TEST);
672
                    $condition = '';
673
                    if (!empty($session_id)) {
674
                        $condition = api_get_session_condition($session_id);
675
                        $sql = "SELECT iid FROM {$table}
676
                                WHERE c_id = {$course_id} AND autolaunch = 1 {$condition}
677
                                LIMIT 1";
678
                        $result = Database::query($sql);
679
                        // If we found nothing in the session we just called the session_id = 0 autolaunch
680
                        if (0 === Database::num_rows($result)) {
681
                            $condition = '';
682
                        }
683
                    }
684
685
                    $sql = "SELECT iid FROM {$table}
686
                            WHERE c_id = {$course_id} AND autolaunch = 1 {$condition}
687
                            LIMIT 1";
688
                    $result = Database::query($sql);
689
                    if (Database::num_rows($result) > 0) {
690
                        $row = Database::fetch_array($result, 'ASSOC');
691
                        $exerciseId = $row['iid'];
692
                        $url = api_get_path(WEB_CODE_PATH).
693
                            'exercise/overview.php?exerciseId='.$exerciseId.'&'.api_get_cidreq();
694
                        header(sprintf('Location: %s', $url));
695
                        exit;
696
                    }
697
                }
698
            }
699
        }
700
701
        $documentAutoLaunch = (int) api_get_course_setting('enable_document_auto_launch');
702
        if (1 === $documentAutoLaunch) {
703
            if ($allowAutoLaunchForCourseAdmins) {
704
                if (empty($autoLaunchWarning)) {
705
                    $autoLaunchWarning = get_lang(
706
                        'The document auto-launch feature configuration is enabled. Learners will be automatically redirected to document tool.'
707
                    );
708
                }
709
            } else {
710
                // Redirecting to the document
711
                $url = api_get_path(WEB_CODE_PATH).'document/document.php?'.api_get_cidreq();
712
                header("Location: $url");
713
                exit;
714
            }
715
        }
716
717
        /*	SWITCH TO A DIFFERENT HOMEPAGE VIEW
718
         the setting homepage_view is adjustable through
719
         the platform administration section */
720
        if (!empty($autoLaunchWarning)) {
721
            $this->addFlash(
722
                'warning',
723
                Display::return_message(
724
                    $autoLaunchWarning,
725
                    'warning'
726
                )
727
            );
728
        }
729
    }
730
}
731