Passed
Push — master ( 6ca194...4db669 )
by Yannick
12:38
created

CourseController   F

Complexity

Total Complexity 72

Size/Duplication

Total Lines 609
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 324
c 0
b 0
f 0
dl 0
loc 609
rs 2.64
wmc 72

7 Methods

Rating   Name   Duplication   Size   Complexity  
F autoLaunch() 0 168 31
A welcome() 0 5 1
C indexJsonAction() 0 173 16
A redirectTool() 0 27 4
C about() 0 138 12
A redirectToShortCut() 0 22 3
A updateSettings() 0 41 5

How to fix   Complexity   

Complex Class

Complex classes like CourseController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use CourseController, and based on these observations, apply Extract Interface, too.

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