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