Completed
Push — master ( 0c8670...7c9763 )
by Julito
14:22
created

CourseHomeController::indexAction()   F

Complexity

Conditions 26
Paths 2376

Size

Total Lines 165
Code Lines 99

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 26
eloc 99
c 0
b 0
f 0
nc 2376
nop 3
dl 0
loc 165
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
/* For licensing terms, see /license.txt */
3
4
namespace Chamilo\CoreBundle\Controller;
5
6
use Chamilo\CoreBundle\ToolChain;
7
use Chamilo\CourseBundle\Controller\ToolBaseController;
8
use Chamilo\CourseBundle\Entity\CTool;
9
use Chamilo\CourseBundle\Repository\CToolRepository;
10
use Chamilosession as Session;
11
use CourseManager;
12
use Database;
13
use Display;
14
use Event;
15
use ExtraFieldValue;
16
use Security;
17
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Entity;
18
use Symfony\Component\HttpFoundation\Request;
19
use Symfony\Component\Routing\Annotation\Route;
20
21
/**
22
 * Class CourseHomeController.
23
 *
24
 * @author Julio Montoya <[email protected]>
25
 *
26
 * @Route("/courses")
27
 */
28
class CourseHomeController extends ToolBaseController
29
{
30
    /**
31
     * @Route("/{cid}/home", name="chamilo_core_course_home")
32
     *
33
     * @Entity("course", expr="repository.find(cid)")
34
     */
35
    public function indexAction(Request $request, CToolRepository $toolRepository, ToolChain $toolChain)
36
    {
37
        $this->autoLaunch();
38
        $course = $this->getCourse();
39
40
        $js = '<script>'.api_get_language_translate_html().'</script>';
41
        $htmlHeadXtra[] = $js;
0 ignored issues
show
Comprehensibility Best Practice introduced by
$htmlHeadXtra was never initialized. Although not strictly required by PHP, it is generally a good practice to add $htmlHeadXtra = array(); before regardless.
Loading history...
42
43
        $userId = $this->getUser()->getId();
44
        $courseCode = $course->getCode();
45
        $courseId = $course->getId();
46
        $sessionId = $this->getSessionId();
47
48
        if (api_is_invitee()) {
49
            $isInASession = $sessionId > 0;
50
            $isSubscribed = CourseManager::is_user_subscribed_in_course(
51
                $userId,
52
                $courseCode,
53
                $isInASession,
54
                $sessionId
55
            );
56
57
            if (!$isSubscribed) {
58
                api_not_allowed(true);
59
            }
60
        }
61
62
        // Deleting group session
63
        Session::erase('toolgroup');
64
        Session::erase('_gid');
65
66
        $isSpecialCourse = CourseManager::isSpecialCourse($courseId);
67
68
        if ($isSpecialCourse) {
69
            if (isset($_GET['autoreg']) && $_GET['autoreg'] == 1) {
70
                if (CourseManager::subscribeUser($userId, $courseCode, STUDENT)) {
71
                    Session::write('is_allowed_in_course', true);
72
                }
73
            }
74
        }
75
76
        $action = !empty($_GET['action']) ? Security::remove_XSS($_GET['action']) : '';
77
        if ($action == 'subscribe') {
78
            if (Security::check_token('get')) {
79
                Security::clear_token();
80
                $result = CourseManager::autoSubscribeToCourse($courseCode);
81
                if ($result) {
82
                    if (CourseManager::is_user_subscribed_in_course($userId, $courseCode)) {
83
                        Session::write('is_allowed_in_course', true);
84
                    }
85
                }
86
                header('Location: '.api_get_self());
87
                exit;
88
            }
89
        }
90
91
        /*  STATISTICS */
92
        if (!isset($coursesAlreadyVisited[$courseCode])) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $coursesAlreadyVisited does not exist. Did you maybe mean $course?
Loading history...
93
            Event::accessCourse();
94
            $coursesAlreadyVisited[$courseCode] = 1;
0 ignored issues
show
Comprehensibility Best Practice introduced by
$coursesAlreadyVisited was never initialized. Although not strictly required by PHP, it is generally a good practice to add $coursesAlreadyVisited = array(); before regardless.
Loading history...
95
            Session::write('coursesAlreadyVisited', $coursesAlreadyVisited);
96
        }
97
98
        $logInfo = [
99
            'tool' => 'course-main',
100
            'action' => $action,
101
        ];
102
        Event::registerLog($logInfo);
103
104
        /*	Introduction section (editable by course admins) */
105
        /*$introduction = Display::return_introduction_section(
106
            TOOL_COURSE_HOMEPAGE,
107
            [
108
                'CreateDocumentWebDir' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/',
109
                'CreateDocumentDir' => 'document/',
110
                'BaseHref' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/',
111
            ]
112
        );*/
113
114
        $qb = $toolRepository->getResourcesByCourse($course, $this->getSession());
115
        $result = $qb->getQuery()->getResult();
116
117
        $tools = [];
118
        /** @var CTool $item */
119
        foreach ($result as $item) {
120
            $toolModel = $toolChain->getToolFromName($item->getTool()->getName());
121
            // Dont show admin links.
122
            if ($toolModel->getAdmin()) {
123
                continue;
124
            }
125
126
            if ($toolModel->getCategory() === 'admin' && !$this->isGranted('ROLE_CURRENT_COURSE_TEACHER')) {
127
                continue;
128
            }
129
            $tools[$item->getCategory()][] = $item;
130
        }
131
132
        // Get session-career diagram
133
        $diagram = '';
134
        $allow = api_get_configuration_value('allow_career_diagram');
135
        if ($allow === true) {
136
            $htmlHeadXtra[] = api_get_js('jsplumb2.js');
137
            $extra = new ExtraFieldValue('session');
138
            $value = $extra->get_values_by_handler_and_field_variable(
139
                api_get_session_id(),
140
                'external_career_id'
141
            );
142
143
            if (!empty($value) && isset($value['value'])) {
144
                $careerId = $value['value'];
145
                $extraFieldValue = new ExtraFieldValue('career');
146
                $item = $extraFieldValue->get_item_id_from_field_variable_and_field_value(
147
                    'external_career_id',
148
                    $careerId,
149
                    false,
150
                    false,
151
                    false
152
                );
153
154
                if (!empty($item) && isset($item['item_id'])) {
155
                    $careerId = $item['item_id'];
156
                    $career = new Career();
0 ignored issues
show
Bug introduced by
The type Chamilo\CoreBundle\Controller\Career was not found. Did you mean Career? If so, make sure to prefix the type with \.
Loading history...
157
                    $careerInfo = $career->get($careerId);
158
                    if (!empty($careerInfo)) {
159
                        $extraFieldValue = new ExtraFieldValue('career');
160
                        $item = $extraFieldValue->get_values_by_handler_and_field_variable(
161
                            $careerId,
162
                            'career_diagram',
163
                            false,
164
                            false,
165
                            false
166
                        );
167
168
                        if (!empty($item) && isset($item['value']) && !empty($item['value'])) {
169
                            /** @var Graph $graph */
170
                            $graph = UnserializeApi::unserialize(
0 ignored issues
show
Bug introduced by
The type Chamilo\CoreBundle\Controller\UnserializeApi was not found. Did you mean UnserializeApi? If so, make sure to prefix the type with \.
Loading history...
171
                                'career',
172
                                $item['value']
173
                            );
174
                            $diagram = Career::renderDiagram($careerInfo, $graph);
175
                        }
176
                    }
177
                }
178
            }
179
        }
180
181
        // Deleting the objects
182
        Session::erase('_gid');
183
        Session::erase('oLP');
184
        Session::erase('lpobject');
185
        api_remove_in_gradebook();
186
        \Exercise::cleanSessionVariables();
187
        \DocumentManager::removeGeneratedAudioTempFile();
188
189
        return $this->render(
190
            '@ChamiloTheme/Course/home.html.twig',
191
            [
192
                'course' => $course,
193
                'diagram' => $diagram,
194
               // 'session_info' => $sessionInfo,
195
                'tools' => $tools,
196
                //'edit_icons' => $editIcons,
197
                //'introduction_text' => $introduction,
198
                'exercise_warning' => null,
199
                'lp_warning' => null,
200
            ]
201
        );
202
    }
203
204
    /**
205
     * @Route("/{cid}/tool/{toolId}", name="chamilo_core_course_redirect_tool")
206
     *
207
     * @Entity("course", expr="repository.find(cid)")
208
     */
209
    public function redirectTool(Request $request, $toolId, ToolChain $toolChain)
210
    {
211
        $criteria = ['id' => $toolId];
212
        /** @var CTool $tool */
213
        $tool = $this->getDoctrine()->getRepository('Chamilo\CourseBundle\Entity\CTool')->findOneBy($criteria);
214
        $tool = $toolChain->getToolFromName($tool->getTool()->getName());
215
        $url = $tool->getLink().'?'.$this->getCourseUrlQuery();
216
217
        return $this->redirect($url);
218
    }
219
220
    /**
221
     * @Route("/show/{iconId}", methods={"GET"})
222
     *
223
     * @param $iconId
224
     *
225
     * @return string|null
226
     */
227
    public function showIconAction($iconId)
228
    {
229
        $entityManager = $this->getDoctrine()->getManager();
230
        $criteria = ['cId' => api_get_course_int_id(), 'id' => $iconId];
231
        $tool = $this->getRepository('Chamilo\CourseBundle\Entity\CTool')->findOneBy($criteria);
232
        if ($tool) {
233
            $tool->setVisibility(1);
234
        }
235
        $entityManager->persist($tool);
236
        //$entityManager->flush();
237
        return Display::return_message(get_lang('Visible'), 'confirmation');
238
    }
239
240
    /**
241
     * @Route("/hide/{iconId}", methods={"GET"})
242
     *
243
     * @param $iconId
244
     *
245
     * @return string|null
246
     */
247
    public function hideIconAction($iconId)
248
    {
249
        if (!$this->isCourseTeacher()) {
250
            return $this->abort(404);
251
        }
252
253
        $entityManager = $this->getDoctrine()->getManager();
254
        $criteria = ['cId' => api_get_course_int_id(), 'id' => $iconId];
255
        $tool = $this->getRepository(
256
            'Chamilo\CourseBundle\Entity\CTool'
257
        )->findOneBy($criteria);
258
        if ($tool) {
259
            $tool->setVisibility(0);
260
        }
261
        $entityManager->persist($tool);
262
        //$entityManager->flush();
263
        return Display::return_message(get_lang('The tool is now invisible.'), 'confirmation');
264
    }
265
266
    /**
267
     * @Route("/delete/{iconId}", methods={"GET"})
268
     *
269
     * @param $iconId
270
     *
271
     * @return string|null
272
     */
273
    public function deleteIcon($iconId)
274
    {
275
        if (!$this->isCourseTeacher()) {
276
            return $this->abort(404);
277
        }
278
279
        $entityManager = $this->getDoctrine()->getManager();
280
        $criteria = ['cId' => api_get_course_int_id(), 'id' => $iconId, 'added_tool' => 1];
281
        $tool = $this->getRepository(
282
            'Chamilo\CourseBundle\Entity\CTool'
283
        )->findOneBy($criteria);
284
        $entityManager->remove($tool);
285
        //$entityManager->flush();
286
        return Display::return_message(get_lang('Deleted'), 'confirmation');
287
    }
288
289
    /**
290
     * @Route("/icon_list", methods={"GET"})
291
     */
292
    public function iconListAction(Request $request)
293
    {
294
        $em = $this->getDoctrine()->getManager();
295
        $repo = $this->getDoctrine()->getRepository('ChamiloCourseBundle:CTool');
296
297
        $sessionId = (int) $request->get('id_session');
298
        $itemsFromSession = [];
299
        if (!empty($sessionId)) {
300
            $query = $repo->createQueryBuilder('a');
301
            $query->select('s');
302
            $query->from('Chamilo\CourseBundle\Entity\CTool', 's');
303
            $query->where('s.cId  = :courseId AND s.sessionId = :sessionId')
304
                ->setParameters(
305
                    [
306
                        'course' => $this->getCourse()->getId(),
307
                        'sessionId' => $sessionId,
308
                    ]
309
                );
310
            $itemsFromSession = $query->getQuery()->getResult();
311
312
            $itemNameList = [];
313
            foreach ($itemsFromSession as $item) {
314
                $itemNameList[] = $item->getName();
315
            }
316
317
            //$itemsFromSession = $this->getRepository()->findBy($criteria);
318
            $query = $repo->createQueryBuilder('a');
319
            $query->select('s');
320
            $query->from('Chamilo\CourseBundle\Entity\CTool', 's');
321
            $query->where('s.cId  = :courseId AND s.sessionId = 0')
322
                ->setParameters(
323
                    [
324
                        'courseId' => $this->getCourse()->getId(),
325
                    ]
326
                );
327
            if (!empty($itemNameList)) {
328
                $query->andWhere($query->expr()->notIn('s.name', $itemNameList));
329
            }
330
            $itemsFromCourse = $query->getQuery()->getResult();
331
        } else {
332
            $criteria = ['cId' => $this->getCourse()->getId(), 'sessionId' => 0];
333
            $itemsFromCourse = $repo->findBy($criteria);
334
        }
335
336
        return $this->render(
337
            '@ChamiloCourse/Home/list.html.twig',
338
            [
339
                'items_from_course' => $itemsFromCourse,
340
                'items_from_session' => $itemsFromSession,
341
                'links' => '',
342
            ]
343
        );
344
    }
345
346
    /**
347
     * @Route("/{itemName}/add", methods={"GET", "POST"})
348
     *
349
     * @param $itemName
350
     *
351
     * @return mixed
352
     */
353
    public function addIconAction($itemName)
354
    {
355
        if (!$this->isCourseTeacher()) {
356
            return $this->abort(404);
357
        }
358
359
        $sessionId = intval($this->getRequest()->get('id_session'));
360
361
        if (empty($sessionId)) {
362
            return $this->abort(500);
363
        }
364
365
        $criteria = ['cId' => $this->getCourse()->getId(), 'sessionId' => 0, 'name' => $itemName];
366
        $itemFromDatabase = $this->getRepository()->findOneBy($criteria);
367
368
        if (!$itemFromDatabase) {
369
            $this->createNotFoundException();
370
        }
371
        /** @var CTool $item */
372
        $item = clone $itemFromDatabase;
373
        $item->setId(null);
374
        $item->setSessionId($sessionId);
0 ignored issues
show
Bug introduced by
The method setSessionId() does not exist on Chamilo\CourseBundle\Entity\CTool. Did you maybe mean setSession()? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

374
        $item->/** @scrutinizer ignore-call */ 
375
               setSessionId($sessionId);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
375
        $form = $this->createForm($this->getFormType(), $item);
376
377
        $form->handleRequest($this->getRequest());
378
379
        if ($form->isSubmitted() && $form->isValid()) {
380
            $query = $this->getDoctrine()->getManager()->createQueryBuilder('a');
381
            $query->select('MAX(s.id) as id');
382
            $query->from('Chamilo\CourseBundle\Entity\CTool', 's');
383
            $query->where('s.cId  = :courseId')->setParameter('courseId', $this->getCourse()->getId());
384
            $result = $query->getQuery()->getArrayResult();
385
            $maxId = $result[0]['id'] + 1;
386
            $item->setId($maxId);
387
388
            $entityManager = $this->getDoctrine()->getManager();
389
            $entityManager->persist($item);
390
            $entityManager->flush();
391
            $customIcon = $item->getCustomIcon();
0 ignored issues
show
Bug introduced by
The method getCustomIcon() does not exist on Chamilo\CourseBundle\Entity\CTool. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

391
            /** @scrutinizer ignore-call */ 
392
            $customIcon = $item->getCustomIcon();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
392
            if (!empty($customIcon)) {
393
                $item->createGrayIcon($this->get('imagine'));
0 ignored issues
show
Bug introduced by
The method createGrayIcon() does not exist on Chamilo\CourseBundle\Entity\CTool. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

393
                $item->/** @scrutinizer ignore-call */ 
394
                       createGrayIcon($this->get('imagine'));

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
394
            }
395
396
            $this->get('session')->getFlashBag()->add('success', "Added");
397
            $url = $this->generateUrl('course_home.controller:iconListAction', ['id_session' => $sessionId]);
398
399
            return $this->redirect($url);
400
        }
401
402
        $this->getTemplate()->assign('item', $item);
403
        $this->getTemplate()->assign('form', $form->createView());
404
        $this->getTemplate()->assign('links', $this->generateLinks());
405
406
        return $this->render('@ChamiloCourse/Home/add.html.twig');
407
    }
408
409
    /**
410
     * @Route("/{itemId}/edit", methods={"GET"})
411
     */
412
    public function editIconAction($itemId)
413
    {
414
        if (!$this->isCourseTeacher()) {
415
            return $this->abort(404);
416
        }
417
418
        $sessionId = intval($this->getRequest()->get('id_session'));
419
420
        $criteria = ['cId' => $this->getCourse()->getId(), 'id' => $itemId];
421
        /** @var CTool $item */
422
        $item = $this->getRepository()->findOneBy($criteria);
423
424
        $form = $this->createForm($this->getFormType(), $item);
425
        $form->handleRequest($this->getRequest());
426
427
        if ($form->isValid()) {
428
            $entityManager = $this->getDoctrine()->getManager();
429
            $entityManager->persist($item);
430
            $entityManager->flush();
431
432
            $customIcon = $item->getCustomIcon();
433
            if (!empty($customIcon)) {
434
                $item->createGrayIcon($this->get('imagine'));
435
            }
436
437
            $this->get('session')->getFlashBag()->add('success', "Updated");
438
            $url = $this->generateUrl('course_home.controller:iconListAction', ['id_session' => $sessionId]);
439
440
            return $this->redirect($url);
441
        }
442
443
        $this->getTemplate()->assign('item', $item);
444
        $this->getTemplate()->assign('form', $form->createView());
445
        $this->getTemplate()->assign('links', $this->generateLinks());
446
447
        return $this->render('@ChamiloCourse/Home/edit.html.twig');
448
    }
449
450
    /**
451
     * @Route("/{itemId}/delete", methods={"GET"})
452
     */
453
    public function deleteIconAction($itemId)
454
    {
455
        if (!$this->isCourseTeacher()) {
456
            return $this->abort(404);
457
        }
458
459
        $criteria = ['cId' => $this->getCourse()->getId(), 'id' => $itemId];
460
461
        /** @var CTool $item */
462
        $item = $this->getRepository()->findOneBy($criteria);
463
        $entityManager = $this->getDoctrine()->getManager();
464
        $sessionId = $item->getSessionId();
0 ignored issues
show
Bug introduced by
The method getSessionId() does not exist on Chamilo\CourseBundle\Entity\CTool. Did you maybe mean getSession()? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

464
        /** @scrutinizer ignore-call */ 
465
        $sessionId = $item->getSessionId();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
465
        if (!empty($sessionId)) {
466
            $entityManager->remove($item);
467
        } else {
468
            $item->setCustomIcon(null);
0 ignored issues
show
Bug introduced by
The method setCustomIcon() does not exist on Chamilo\CourseBundle\Entity\CTool. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

468
            $item->/** @scrutinizer ignore-call */ 
469
                   setCustomIcon(null);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
469
            $entityManager->persist($item);
470
        }
471
        $entityManager->flush();
472
        $this->get('session')->getFlashBag()->add('success', "Deleted");
473
474
        $this->getTemplate()->assign('links', $this->generateLinks());
475
        $url = $this->generateUrl('course_home.controller:iconListAction');
476
477
        return $this->redirect($url);
478
    }
479
480
    /**
481
     * @return array
482
     */
483
    private function autoLaunch()
484
    {
485
        /* Auto launch code */
486
        $autoLaunchWarning = '';
487
        $showAutoLaunchLpWarning = false;
488
        $course_id = api_get_course_int_id();
489
        $lpAutoLaunch = api_get_course_setting('enable_lp_auto_launch');
490
        $session_id = api_get_session_id();
491
        $allowAutoLaunchForCourseAdmins = api_is_platform_admin() || api_is_allowed_to_edit(true, true) || api_is_coach();
492
493
        if (!empty($lpAutoLaunch)) {
494
            if ($lpAutoLaunch == 2) {
495
                // LP list
496
                if ($allowAutoLaunchForCourseAdmins) {
497
                    $showAutoLaunchLpWarning = true;
498
                } else {
499
                    $session_key = 'lp_autolaunch_'.$session_id.'_'.api_get_course_int_id().'_'.api_get_user_id();
500
                    if (!isset($_SESSION[$session_key])) {
501
                        // Redirecting to the LP
502
                        $url = api_get_path(WEB_CODE_PATH).'lp/lp_controller.php?'.api_get_cidreq();
503
                        $_SESSION[$session_key] = true;
504
                        header("Location: $url");
505
                        exit;
506
                    }
507
                }
508
            } else {
509
                $lp_table = Database::get_course_table(TABLE_LP_MAIN);
510
                $condition = '';
511
                if (!empty($session_id)) {
512
                    $condition = api_get_session_condition($session_id);
513
                    $sql = "SELECT id FROM $lp_table
514
                            WHERE c_id = $course_id AND autolaunch = 1 $condition
515
                            LIMIT 1";
516
                    $result = Database::query($sql);
517
                    // If we found nothing in the session we just called the session_id =  0 autolaunch
518
                    if (Database::num_rows($result) == 0) {
519
                        $condition = '';
520
                    }
521
                }
522
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 (Database::num_rows($result) > 0) {
528
                    $lp_data = Database::fetch_array($result, 'ASSOC');
529
                    if (!empty($lp_data['id'])) {
530
                        if ($allowAutoLaunchForCourseAdmins) {
531
                            $showAutoLaunchLpWarning = true;
532
                        } else {
533
                            $session_key = 'lp_autolaunch_'.$session_id.'_'.api_get_course_int_id().'_'.api_get_user_id();
534
                            if (!isset($_SESSION[$session_key])) {
535
                                // Redirecting to the LP
536
                                $url = api_get_path(WEB_CODE_PATH).'lp/lp_controller.php?'.api_get_cidreq().'&action=view&lp_id='.$lp_data['id'];
537
538
                                $_SESSION[$session_key] = true;
539
                                header("Location: $url");
540
                                exit;
541
                            }
542
                        }
543
                    }
544
                }
545
            }
546
        }
547
548
        if ($showAutoLaunchLpWarning) {
549
            $autoLaunchWarning = get_lang('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.');
550
        }
551
552
        $forumAutoLaunch = api_get_course_setting('enable_forum_auto_launch');
553
        if ($forumAutoLaunch == 1) {
554
            if ($allowAutoLaunchForCourseAdmins) {
555
                if (empty($autoLaunchWarning)) {
556
                    $autoLaunchWarning = get_lang('The forum\'s auto-launch setting is on. Students will be redirected to the forum tool when entering this course.');
557
                }
558
            } else {
559
                $url = api_get_path(WEB_CODE_PATH).'forum/index.php?'.api_get_cidreq();
560
                header("Location: $url");
561
                exit;
562
            }
563
        }
564
565
        if (api_get_configuration_value('allow_exercise_auto_launch')) {
566
            $exerciseAutoLaunch = (int) api_get_course_setting('enable_exercise_auto_launch');
567
            if ($exerciseAutoLaunch == 2) {
568
                if ($allowAutoLaunchForCourseAdmins) {
569
                    if (empty($autoLaunchWarning)) {
570
                        $autoLaunchWarning = get_lang(
571
                            'TheExerciseAutoLaunchSettingIsONStudentsWillBeRedirectToTheExerciseList'
572
                        );
573
                    }
574
                } else {
575
                    // Redirecting to the document
576
                    $url = api_get_path(WEB_CODE_PATH).'exercise/exercise.php?'.api_get_cidreq();
577
                    header("Location: $url");
578
                    exit;
579
                }
580
            } elseif ($exerciseAutoLaunch == 1) {
581
                if ($allowAutoLaunchForCourseAdmins) {
582
                    if (empty($autoLaunchWarning)) {
583
                        $autoLaunchWarning = get_lang(
584
                            'TheExerciseAutoLaunchSettingIsONStudentsWillBeRedirectToAnSpecificExercise'
585
                        );
586
                    }
587
                } else {
588
                    // Redirecting to an exercise
589
                    $table = Database::get_course_table(TABLE_QUIZ_TEST);
590
                    $condition = '';
591
                    if (!empty($session_id)) {
592
                        $condition = api_get_session_condition($session_id);
593
                        $sql = "SELECT iid FROM $table
594
                        WHERE c_id = $course_id AND autolaunch = 1 $condition
595
                        LIMIT 1";
596
                        $result = Database::query($sql);
597
                        // If we found nothing in the session we just called the session_id = 0 autolaunch
598
                        if (Database::num_rows($result) == 0) {
599
                            $condition = '';
600
                        }
601
                    }
602
603
                    $sql = "SELECT iid FROM $table
604
                    WHERE c_id = $course_id AND autolaunch = 1 $condition
605
                    LIMIT 1";
606
                    $result = Database::query($sql);
607
                    if (Database::num_rows($result) > 0) {
608
                        $row = Database::fetch_array($result, 'ASSOC');
609
                        $exerciseId = $row['iid'];
610
                        $url = api_get_path(WEB_CODE_PATH).
611
                            'exercise/overview.php?exerciseId='.$exerciseId.'&'.api_get_cidreq();
612
                        header("Location: $url");
613
                        exit;
614
                    }
615
                }
616
            }
617
        }
618
619
        $documentAutoLaunch = api_get_course_setting('enable_document_auto_launch');
620
        if ($documentAutoLaunch == 1) {
621
            if ($allowAutoLaunchForCourseAdmins) {
622
                if (empty($autoLaunchWarning)) {
623
                    $autoLaunchWarning = get_lang('The document auto-launch feature configuration is enabled. Learners will be automatically redirected to document tool.');
624
                }
625
            } else {
626
                // Redirecting to the document
627
                $url = api_get_path(WEB_CODE_PATH).'document/document.php?'.api_get_cidreq();
628
                header("Location: $url");
629
                exit;
630
            }
631
        }
632
633
        /*	SWITCH TO A DIFFERENT HOMEPAGE VIEW
634
         the setting homepage_view is adjustable through
635
         the platform administration section */
636
        if (!empty($autoLaunchWarning)) {
637
            $this->addFlash(
638
            Display::return_message(
639
                $autoLaunchWarning,
640
                'warning'
641
            ));
642
        }
643
    }
644
}
645