Passed
Pull Request — master (#5063)
by Angel Fernando Quiroz
06:57
created

CourseController::addToolIntro()   A

Complexity

Conditions 5
Paths 6

Size

Total Lines 51
Code Lines 37

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 37
nc 6
nop 3
dl 0
loc 51
rs 9.0168
c 0
b 0
f 0

How to fix   Long Method   

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
/* For licensing terms, see /license.txt */
4
5
declare(strict_types=1);
6
7
namespace Chamilo\CoreBundle\Controller;
8
9
use Chamilo\CoreBundle\Entity\Course;
10
use Chamilo\CoreBundle\Entity\CourseRelUser;
11
use Chamilo\CoreBundle\Entity\ExtraField;
12
use Chamilo\CoreBundle\Entity\Session;
13
use Chamilo\CoreBundle\Entity\SessionRelUser;
14
use Chamilo\CoreBundle\Entity\Tag;
15
use Chamilo\CoreBundle\Entity\Tool;
16
use Chamilo\CoreBundle\Entity\User;
17
use Chamilo\CoreBundle\Framework\Container;
18
use Chamilo\CoreBundle\Repository\ExtraFieldValuesRepository;
19
use Chamilo\CoreBundle\Repository\LanguageRepository;
20
use Chamilo\CoreBundle\Repository\LegalRepository;
21
use Chamilo\CoreBundle\Repository\Node\IllustrationRepository;
22
use Chamilo\CoreBundle\Repository\TagRepository;
23
use Chamilo\CoreBundle\Security\Authorization\Voter\CourseVoter;
24
use Chamilo\CoreBundle\Settings\SettingsManager;
25
use Chamilo\CoreBundle\Tool\AbstractTool;
26
use Chamilo\CoreBundle\Tool\ToolChain;
27
use Chamilo\CourseBundle\Controller\ToolBaseController;
28
use Chamilo\CourseBundle\Entity\CCourseDescription;
29
use Chamilo\CourseBundle\Entity\CTool;
30
use Chamilo\CourseBundle\Entity\CToolIntro;
31
use Chamilo\CourseBundle\Repository\CCourseDescriptionRepository;
32
use Chamilo\CourseBundle\Repository\CShortcutRepository;
33
use Chamilo\CourseBundle\Repository\CToolRepository;
34
use Chamilo\CourseBundle\Settings\SettingsCourseManager;
35
use Chamilo\CourseBundle\Settings\SettingsFormFactory;
36
use CourseManager;
37
use Database;
38
use Display;
39
use Doctrine\ORM\EntityManagerInterface;
40
use Event;
41
use Exercise;
42
use ExtraFieldValue;
43
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Entity;
44
use Symfony\Component\HttpFoundation\JsonResponse;
45
use Symfony\Component\HttpFoundation\RedirectResponse;
46
use Symfony\Component\HttpFoundation\Request;
47
use Symfony\Component\HttpFoundation\Response;
48
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
49
use Symfony\Component\Routing\Annotation\Route;
50
use Symfony\Component\Serializer\SerializerInterface;
51
use Symfony\Component\Validator\Exception\ValidatorException;
52
use UserManager;
53
54
/**
55
 * @author Julio Montoya <[email protected]>
56
 */
57
#[Route('/course')]
58
class CourseController extends ToolBaseController
59
{
60
    public function __construct(
61
        private readonly EntityManagerInterface $em,
62
        private readonly SerializerInterface $serializer
63
    ) {}
64
65
    #[Route('/{cid}/checkLegal.json', name: 'chamilo_core_course_check_legal_json')]
66
    public function checkTermsAndConditionJson(
67
        Request $request,
68
        LegalRepository $legalTermsRepo,
69
        LanguageRepository $languageRepository,
70
        ExtraFieldValuesRepository $extraFieldValuesRepository,
71
        SettingsManager $settingsManager
72
    ): Response {
73
        /** @var User $user */
74
        $user = $this->getUser();
75
        $course = $this->getCourse();
76
        $responseData = [
77
            'redirect' => false,
78
            'url' => '#',
79
        ];
80
81
        if ($user && $user->hasRole('ROLE_STUDENT')
82
            && 'true' === $settingsManager->getSetting('allow_terms_conditions')
83
            && 'course' === $settingsManager->getSetting('load_term_conditions_section')
84
        ) {
85
            $termAndConditionStatus = false;
86
            $extraValue = $extraFieldValuesRepository->findLegalAcceptByItemId($user->getId());
87
            if (!empty($extraValue['value'])) {
88
                $result = $extraValue['value'];
89
                $userConditions = explode(':', $result);
90
                $version = $userConditions[0];
91
                $langId = (int) $userConditions[1];
92
                $realVersion = $legalTermsRepo->getLastVersion($langId);
93
                $termAndConditionStatus = ($version >= $realVersion);
94
            }
95
96
            if (false === $termAndConditionStatus) {
97
                $request->getSession()->set('term_and_condition', ['user_id' => $user->getId()]);
98
            } else {
99
                $request->getSession()->remove('term_and_condition');
100
            }
101
102
            $termsAndCondition = $request->getSession()->get('term_and_condition');
103
            if (null !== $termsAndCondition) {
104
                $redirect = true;
105
                $allow = 'true' === Container::getSettingsManager()
106
                    ->getSetting('course.allow_public_course_with_no_terms_conditions')
107
                ;
108
109
                if (true === $allow
110
                    && null !== $course->getVisibility()
111
                    && Course::OPEN_WORLD === $course->getVisibility()
112
                ) {
113
                    $redirect = false;
114
                }
115
                if ($redirect && !$this->isGranted('ROLE_ADMIN')) {
116
                    $url = '/main/auth/inscription.php';
117
                    $responseData = [
118
                        'redirect' => true,
119
                        'url' => $url,
120
                    ];
121
                }
122
            }
123
        }
124
125
        return new JsonResponse($responseData);
126
    }
127
128
    #[Route('/{cid}/home.json', name: 'chamilo_core_course_home_json')]
129
    #[Entity('course', expr: 'repository.find(cid)')]
130
    public function indexJson(
131
        Request $request,
132
        CToolRepository $toolRepository,
133
        CShortcutRepository $shortcutRepository,
134
        ToolChain $toolChain,
135
        EntityManagerInterface $em,
136
    ): Response {
137
        $requestData = json_decode($request->getContent(), true);
138
        // Sort behaviour
139
        if (!empty($requestData) && isset($requestData['toolItem'])) {
140
            $index = $requestData['index'];
141
            $toolItem = $requestData['toolItem'];
142
            $toolId = (int) $toolItem['iid'];
143
144
            /** @var CTool $cTool */
145
            $cTool = $em->find(CTool::class, $toolId);
146
147
            if ($cTool) {
148
                $cTool->setPosition($index + 1);
149
                $em->persist($cTool);
150
                $em->flush();
151
            }
152
        }
153
154
        $course = $this->getCourse();
155
        $sessionId = $this->getSessionId();
156
        $isInASession = $sessionId > 0;
157
158
        if (null === $course) {
159
            throw $this->createAccessDeniedException();
160
        }
161
162
        if (empty($sessionId)) {
163
            $this->denyAccessUnlessGranted(CourseVoter::VIEW, $course);
164
        }
165
166
        $sessionHandler = $request->getSession();
167
168
        $userId = 0;
169
170
        /** @var ?User $user */
171
        $user = $this->getUser();
172
        if (null !== $user) {
173
            $userId = $user->getId();
174
        }
175
176
        $courseCode = $course->getCode();
177
        $courseId = $course->getId();
178
179
        if ($user && $user->hasRole('ROLE_INVITEE')) {
180
            $isSubscribed = CourseManager::is_user_subscribed_in_course(
181
                $userId,
182
                $courseCode,
183
                $isInASession,
184
                $sessionId
185
            );
186
187
            if (!$isSubscribed) {
188
                throw $this->createAccessDeniedException();
189
            }
190
        }
191
192
        $isSpecialCourse = CourseManager::isSpecialCourse($courseId);
193
194
        if ($user && $isSpecialCourse && (isset($_GET['autoreg']) && 1 === (int) $_GET['autoreg'])
195
            && CourseManager::subscribeUser($userId, $courseId, STUDENT)
196
        ) {
197
            $sessionHandler->set('is_allowed_in_course', true);
198
        }
199
200
        $logInfo = [
201
            'tool' => 'course-main',
202
        ];
203
        Event::registerLog($logInfo);
204
205
        // Deleting the objects
206
        $sessionHandler->remove('toolgroup');
207
        $sessionHandler->remove('_gid');
208
        $sessionHandler->remove('oLP');
209
        $sessionHandler->remove('lpobject');
210
211
        api_remove_in_gradebook();
212
        Exercise::cleanSessionVariables();
213
214
        $shortcuts = [];
215
        if (null !== $user) {
216
            $shortcutQuery = $shortcutRepository->getResources($course->getResourceNode());
217
            $shortcuts = $shortcutQuery->getQuery()->getResult();
218
        }
219
        $responseData = [
220
            'shortcuts' => $shortcuts,
221
            'diagram' => '',
222
        ];
223
224
        $json = $this->serializer->serialize(
225
            $responseData,
226
            'json',
227
            [
228
                'groups' => ['course:read', 'ctool:read', 'tool:read', 'cshortcut:read'],
229
            ]
230
        );
231
232
        return new Response(
233
            $json,
234
            Response::HTTP_OK,
235
            [
236
                'Content-type' => 'application/json',
237
            ]
238
        );
239
    }
240
241
    /**
242
     * Redirects the page to a tool, following the tools settings.
243
     */
244
    #[Route('/{cid}/tool/{toolName}', name: 'chamilo_core_course_redirect_tool')]
245
    public function redirectTool(string $toolName, CToolRepository $repo, ToolChain $toolChain): RedirectResponse
246
    {
247
        /** @var CTool|null $tool */
248
        $tool = $repo->findOneBy([
249
            'name' => $toolName,
250
        ]);
251
252
        if (null === $tool) {
253
            throw new NotFoundHttpException($this->trans('Tool not found'));
254
        }
255
256
        $tool = $toolChain->getToolFromName($tool->getTool()->getName());
257
        $link = $tool->getLink();
258
259
        if (null === $this->getCourse()) {
260
            throw new NotFoundHttpException($this->trans('Course not found'));
261
        }
262
263
        if (strpos($link, 'nodeId')) {
264
            $nodeId = (string) $this->getCourse()->getResourceNode()->getId();
265
            $link = str_replace(':nodeId', $nodeId, $link);
266
        }
267
268
        $url = $link.'?'.$this->getCourseUrlQuery();
269
270
        return $this->redirect($url);
271
    }
272
273
    /*public function redirectToShortCut(string $toolName, CToolRepository $repo, ToolChain $toolChain): RedirectResponse
274
    {
275
        $tool = $repo->findOneBy([
276
            'name' => $toolName,
277
        ]);
278
279
        if (null === $tool) {
280
            throw new NotFoundHttpException($this->trans('Tool not found'));
281
        }
282
283
        $tool = $toolChain->getToolFromName($tool->getTool()->getName());
284
        $link = $tool->getLink();
285
286
        if (strpos($link, 'nodeId')) {
287
            $nodeId = (string) $this->getCourse()->getResourceNode()->getId();
288
            $link = str_replace(':nodeId', $nodeId, $link);
289
        }
290
291
        $url = $link.'?'.$this->getCourseUrlQuery();
292
293
        return $this->redirect($url);
294
    }*/
295
296
    /**
297
     * Edit configuration with given namespace.
298
     */
299
    #[Route('/{cid}/settings/{namespace}', name: 'chamilo_core_course_settings')]
300
    #[Entity('course', expr: 'repository.find(cid)')]
301
    public function updateSettings(
302
        Request $request,
303
        Course $course,
304
        string $namespace,
305
        SettingsCourseManager $manager,
306
        SettingsFormFactory $formFactory
307
    ): Response {
308
        $this->denyAccessUnlessGranted(CourseVoter::VIEW, $course);
309
310
        $schemaAlias = $manager->convertNameSpaceToService($namespace);
311
        $settings = $manager->load($namespace);
312
313
        $form = $formFactory->create($schemaAlias);
314
315
        $form->setData($settings);
316
        $form->handleRequest($request);
317
318
        if ($form->isSubmitted() && $form->isValid()) {
319
            $messageType = 'success';
320
321
            try {
322
                $manager->setCourse($course);
323
                $manager->save($form->getData());
324
                $message = $this->trans('Update');
325
            } catch (ValidatorException $validatorException) {
326
                $message = $this->trans($validatorException->getMessage());
327
                $messageType = 'error';
328
            }
329
            $this->addFlash($messageType, $message);
330
331
            if ($request->headers->has('referer')) {
332
                return $this->redirect($request->headers->get('referer'));
333
            }
334
        }
335
336
        $schemas = $manager->getSchemas();
337
338
        return $this->render(
339
            '@ChamiloCore/Course/settings.html.twig',
340
            [
341
                'course' => $course,
342
                'schemas' => $schemas,
343
                'settings' => $settings,
344
                'form' => $form->createView(),
345
            ]
346
        );
347
    }
348
349
    #[Route('/{id}/about', name: 'chamilo_core_course_about')]
350
    public function about(
351
        Course $course,
352
        IllustrationRepository $illustrationRepository,
353
        CCourseDescriptionRepository $courseDescriptionRepository,
354
        EntityManagerInterface $em
355
    ): Response {
356
        $courseId = $course->getId();
357
358
        /** @var ?User $user */
359
        $user = $this->getUser();
360
361
        $fieldsRepo = $em->getRepository(ExtraField::class);
362
363
        /** @var TagRepository $tagRepo */
364
        $tagRepo = $em->getRepository(Tag::class);
365
366
        $courseDescriptions = $courseDescriptionRepository->getResourcesByCourse($course)->getQuery()->getResult();
367
368
        $courseValues = new ExtraFieldValue('course');
369
370
        $urlCourse = api_get_path(WEB_PATH).sprintf('course/%s/about', $courseId);
371
        $courseTeachers = $course->getTeachersSubscriptions();
372
        $teachersData = [];
373
374
        foreach ($courseTeachers as $teacherSubscription) {
375
            $teacher = $teacherSubscription->getUser();
376
            $userData = [
377
                'complete_name' => UserManager::formatUserFullName($teacher),
378
                'image' => $illustrationRepository->getIllustrationUrl($teacher),
379
                'diploma' => $teacher->getDiplomas(),
380
                'openarea' => $teacher->getOpenarea(),
381
            ];
382
383
            $teachersData[] = $userData;
384
        }
385
386
        /** @var ExtraField $tagField */
387
        $tagField = $fieldsRepo->findOneBy([
388
            'itemType' => ExtraField::COURSE_FIELD_TYPE,
389
            'variable' => 'tags',
390
        ]);
391
392
        $courseTags = [];
393
        if (null !== $tagField) {
394
            $courseTags = $tagRepo->getTagsByItem($tagField, $courseId);
395
        }
396
397
        $courseDescription = $courseObjectives = $courseTopics = $courseMethodology = '';
398
        $courseMaterial = $courseResources = $courseAssessment = '';
399
        $courseCustom = [];
400
        foreach ($courseDescriptions as $descriptionTool) {
401
            switch ($descriptionTool->getDescriptionType()) {
402
                case CCourseDescription::TYPE_DESCRIPTION:
403
                    $courseDescription = $descriptionTool->getContent();
404
405
                    break;
406
407
                case CCourseDescription::TYPE_OBJECTIVES:
408
                    $courseObjectives = $descriptionTool;
409
410
                    break;
411
412
                case CCourseDescription::TYPE_TOPICS:
413
                    $courseTopics = $descriptionTool;
414
415
                    break;
416
417
                case CCourseDescription::TYPE_METHODOLOGY:
418
                    $courseMethodology = $descriptionTool;
419
420
                    break;
421
422
                case CCourseDescription::TYPE_COURSE_MATERIAL:
423
                    $courseMaterial = $descriptionTool;
424
425
                    break;
426
427
                case CCourseDescription::TYPE_RESOURCES:
428
                    $courseResources = $descriptionTool;
429
430
                    break;
431
432
                case CCourseDescription::TYPE_ASSESSMENT:
433
                    $courseAssessment = $descriptionTool;
434
435
                    break;
436
437
                case CCourseDescription::TYPE_CUSTOM:
438
                    $courseCustom[] = $descriptionTool;
439
440
                    break;
441
            }
442
        }
443
444
        $topics = [
445
            'objectives' => $courseObjectives,
446
            'topics' => $courseTopics,
447
            'methodology' => $courseMethodology,
448
            'material' => $courseMaterial,
449
            'resources' => $courseResources,
450
            'assessment' => $courseAssessment,
451
            'custom' => array_reverse($courseCustom),
452
        ];
453
454
        $subscriptionUser = false;
455
456
        if ($user) {
457
            $subscriptionUser = CourseManager::is_user_subscribed_in_course($user->getId(), $course->getCode());
458
        }
459
460
        /*$allowSubscribe = false;
461
        if ($course->getSubscribe() || api_is_platform_admin()) {
462
            $allowSubscribe = true;
463
        }
464
        $plugin = \BuyCoursesPlugin::create();
465
        $checker = $plugin->isEnabled();
466
        $courseIsPremium = null;
467
        if ($checker) {
468
            $courseIsPremium = $plugin->getItemByProduct(
469
                $courseId,
470
                \BuyCoursesPlugin::PRODUCT_TYPE_COURSE
471
            );
472
        }*/
473
474
        $image = Container::getIllustrationRepository()->getIllustrationUrl($course, 'course_picture_medium');
475
476
        $params = [
477
            'course' => $course,
478
            'description' => $courseDescription,
479
            'image' => $image,
480
            'syllabus' => $topics,
481
            'tags' => $courseTags,
482
            'teachers' => $teachersData,
483
            'extra_fields' => $courseValues->getAllValuesForAnItem(
484
                $course->getId(),
485
                null,
486
                true
487
            ),
488
            'subscription' => $subscriptionUser,
489
            'url' => '',
490
            'is_premium' => '',
491
            'token' => '',
492
        ];
493
494
        $metaInfo = '<meta property="og:url" content="'.$urlCourse.'" />';
495
        $metaInfo .= '<meta property="og:type" content="website" />';
496
        $metaInfo .= '<meta property="og:title" content="'.$course->getTitle().'" />';
497
        $metaInfo .= '<meta property="og:description" content="'.strip_tags($courseDescription).'" />';
498
        $metaInfo .= '<meta property="og:image" content="'.$image.'" />';
499
500
        $htmlHeadXtra[] = $metaInfo;
501
        $htmlHeadXtra[] = api_get_asset('readmore-js/readmore.js');
502
503
        return $this->render('@ChamiloCore/Course/about.html.twig', $params);
504
    }
505
506
    #[Route('/{id}/welcome', name: 'chamilo_core_course_welcome')]
507
    public function welcome(Course $course): Response
508
    {
509
        return $this->render('@ChamiloCore/Course/welcome.html.twig', [
510
            'course' => $course,
511
        ]);
512
    }
513
514
    private function findIntroOfCourse(Course $course)
515
    {
516
        $qb = $this->em->createQueryBuilder();
517
518
        $query = $qb->select('ct')
519
            ->from(CTool::class, 'ct')
520
            ->where('ct.course = :c_id')
521
            ->andWhere('ct.name = :name')
522
            ->andWhere(
523
                $qb->expr()->orX(
524
                    $qb->expr()->eq('ct.session', ':session_id'),
525
                    $qb->expr()->isNull('ct.session')
526
                )
527
            )
528
            ->setParameters([
529
                'c_id' => $course->getId(),
530
                'name' => 'course_homepage',
531
                'session_id' => 0,
532
            ])
533
            ->getQuery()
534
        ;
535
536
        return $query->getOneOrNullResult();
537
    }
538
539
    #[Route('/{id}/getToolIntro', name: 'chamilo_core_course_gettoolintro')]
540
    public function getToolIntro(Request $request, Course $course, EntityManagerInterface $em): Response
541
    {
542
        $sessionId = (int) $request->get('sid');
543
544
        // $session = $this->getSession();
545
        $responseData = [];
546
        $ctoolRepo = $em->getRepository(CTool::class);
547
        $sessionRepo = $em->getRepository(Session::class);
548
        $createInSession = false;
549
550
        $session = null;
551
552
        if (!empty($sessionId)) {
553
            $session = $sessionRepo->find($sessionId);
554
        }
555
556
        $ctool = $this->findIntroOfCourse($course);
557
558
        if ($session) {
559
            $ctoolSession = $ctoolRepo->findOneBy(['name' => 'course_homepage', 'course' => $course, 'session' => $session]);
560
561
            if (!$ctoolSession) {
562
                $createInSession = true;
563
            } else {
564
                $ctool = $ctoolSession;
565
            }
566
        }
567
568
        if ($ctool) {
569
            $ctoolintroRepo = $em->getRepository(CToolIntro::class);
570
571
            /** @var CToolIntro $ctoolintro */
572
            $ctoolintro = $ctoolintroRepo->findOneBy(['courseTool' => $ctool]);
573
            if ($ctoolintro) {
574
                $responseData = [
575
                    'iid' => $ctoolintro->getIid(),
576
                    'introText' => $ctoolintro->getIntroText(),
577
                    'createInSession' => $createInSession,
578
                    'cToolId' => $ctool->getIid(),
579
                ];
580
            }
581
            $responseData['c_tool'] = [
582
                'iid' => $ctool->getIid(),
583
                'name' => $ctool->getName(),
584
            ];
585
        }
586
587
        return new JsonResponse($responseData);
588
    }
589
590
    #[Route('/{id}/addToolIntro', name: 'chamilo_core_course_addtoolintro')]
591
    public function addToolIntro(Request $request, Course $course, EntityManagerInterface $em): Response
592
    {
593
        $data = $request->getContent();
594
        $data = json_decode($data);
595
        $ctoolintroId = $data->iid;
596
        $sessionId = $data->sid ?? 0;
597
598
        $sessionRepo = $em->getRepository(Session::class);
599
        $session = null;
600
        if (!empty($sessionId)) {
601
            $session = $sessionRepo->find($sessionId);
602
        }
603
604
        $ctool = $em->getRepository(CTool::class);
605
        $check = $ctool->findOneBy(['name' => 'course_homepage', 'course' => $course, 'session' => $session]);
606
        if (!$check) {
607
            $toolRepo = $em->getRepository(Tool::class);
608
            $toolEntity = $toolRepo->findOneBy(['name' => 'course_homepage']);
609
            $courseTool = (new CTool())
610
                ->setTool($toolEntity)
611
                ->setName('course_homepage')
612
                ->setCourse($course)
613
                ->setPosition(1)
614
                ->setVisibility(true)
615
                ->setParent($course)
616
                ->setCreator($course->getCreator())
617
                ->setSession($session)
618
                ->addCourseLink($course)
619
            ;
620
            $em->persist($courseTool);
621
            $em->flush();
622
            if ($courseTool && !empty($ctoolintroId)) {
623
                $ctoolintroRepo = Container::getToolIntroRepository();
624
625
                /** @var CToolIntro $ctoolintro */
626
                $ctoolintro = $ctoolintroRepo->find($ctoolintroId);
627
                $ctoolintro->setCourseTool($courseTool);
628
                $ctoolintroRepo->update($ctoolintro);
629
            }
630
        }
631
        $responseData = [];
632
        $json = $this->serializer->serialize(
633
            $responseData,
634
            'json',
635
            [
636
                'groups' => ['course:read', 'ctool:read', 'tool:read', 'cshortcut:read'],
637
            ]
638
        );
639
640
        return new JsonResponse($responseData);
641
    }
642
643
    #[Route('/check-enrollments', name: 'chamilo_core_check_enrollments', methods: ['GET'])]
644
    public function checkEnrollments(EntityManagerInterface $em, SettingsManager $settingsManager): JsonResponse
645
    {
646
        /** @var User|null $user */
647
        $user = $this->getUser();
648
649
        if (!$user) {
650
            return new JsonResponse(['error' => 'User not found'], Response::HTTP_UNAUTHORIZED);
651
        }
652
653
        $isEnrolledInCourses = $this->isUserEnrolledInAnyCourse($user, $em);
654
        $isEnrolledInSessions = $this->isUserEnrolledInAnySession($user, $em);
655
656
        if (!$isEnrolledInCourses && !$isEnrolledInSessions) {
657
            $defaultMenuEntry = $settingsManager->getSetting('platform.default_menu_entry_for_course_or_session');
658
            $isEnrolledInCourses = 'my_courses' === $defaultMenuEntry;
659
            $isEnrolledInSessions = 'my_sessions' === $defaultMenuEntry;
660
        }
661
662
        return new JsonResponse([
663
            'isEnrolledInCourses' => $isEnrolledInCourses,
664
            'isEnrolledInSessions' => $isEnrolledInSessions,
665
        ]);
666
    }
667
668
    private function autoLaunch(): void
669
    {
670
        $autoLaunchWarning = '';
671
        $showAutoLaunchLpWarning = false;
672
        $course_id = api_get_course_int_id();
673
        $lpAutoLaunch = api_get_course_setting('enable_lp_auto_launch');
674
        $session_id = api_get_session_id();
675
        $allowAutoLaunchForCourseAdmins =
676
            api_is_platform_admin()
677
            || api_is_allowed_to_edit(true, true)
678
            || api_is_coach();
679
680
        if (!empty($lpAutoLaunch)) {
681
            if (2 === $lpAutoLaunch) {
682
                // LP list
683
                if ($allowAutoLaunchForCourseAdmins) {
684
                    $showAutoLaunchLpWarning = true;
685
                } else {
686
                    $session_key = 'lp_autolaunch_'.$session_id.'_'.$course_id.'_'.api_get_user_id();
687
                    if (!isset($_SESSION[$session_key])) {
688
                        // Redirecting to the LP
689
                        $url = api_get_path(WEB_CODE_PATH).'lp/lp_controller.php?'.api_get_cidreq();
690
                        $_SESSION[$session_key] = true;
691
                        header(sprintf('Location: %s', $url));
692
693
                        exit;
694
                    }
695
                }
696
            } else {
697
                $lp_table = Database::get_course_table(TABLE_LP_MAIN);
698
                $condition = '';
699
                if (!empty($session_id)) {
700
                    $condition = api_get_session_condition($session_id);
701
                    $sql = "SELECT id FROM {$lp_table}
702
                            WHERE c_id = {$course_id} AND autolaunch = 1 {$condition}
703
                            LIMIT 1";
704
                    $result = Database::query($sql);
705
                    // If we found nothing in the session we just called the session_id =  0 autolaunch
706
                    if (0 === Database::num_rows($result)) {
707
                        $condition = '';
708
                    }
709
                }
710
711
                $sql = "SELECT iid FROM {$lp_table}
712
                        WHERE c_id = {$course_id} AND autolaunch = 1 {$condition}
713
                        LIMIT 1";
714
                $result = Database::query($sql);
715
                if (Database::num_rows($result) > 0) {
716
                    $lp_data = Database::fetch_array($result);
717
                    if (!empty($lp_data['iid'])) {
718
                        if ($allowAutoLaunchForCourseAdmins) {
719
                            $showAutoLaunchLpWarning = true;
720
                        } else {
721
                            $session_key = 'lp_autolaunch_'.$session_id.'_'.api_get_course_int_id().'_'.api_get_user_id();
722
                            if (!isset($_SESSION[$session_key])) {
723
                                // Redirecting to the LP
724
                                $url = api_get_path(WEB_CODE_PATH).
725
                                    'lp/lp_controller.php?'.api_get_cidreq().'&action=view&lp_id='.$lp_data['iid'];
726
727
                                $_SESSION[$session_key] = true;
728
                                header(sprintf('Location: %s', $url));
729
730
                                exit;
731
                            }
732
                        }
733
                    }
734
                }
735
            }
736
        }
737
738
        if ($showAutoLaunchLpWarning) {
739
            $autoLaunchWarning = get_lang(
740
                '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.'
741
            );
742
        }
743
744
        $forumAutoLaunch = (int) api_get_course_setting('enable_forum_auto_launch');
745
        if (1 === $forumAutoLaunch) {
746
            if ($allowAutoLaunchForCourseAdmins) {
747
                if (empty($autoLaunchWarning)) {
748
                    $autoLaunchWarning = get_lang(
749
                        "The forum's auto-launch setting is on. Students will be redirected to the forum tool when entering this course."
750
                    );
751
                }
752
            } else {
753
                $url = api_get_path(WEB_CODE_PATH).'forum/index.php?'.api_get_cidreq();
754
                header(sprintf('Location: %s', $url));
755
756
                exit;
757
            }
758
        }
759
760
        if ('true' === api_get_setting('exercise.allow_exercise_auto_launch')) {
761
            $exerciseAutoLaunch = (int) api_get_course_setting('enable_exercise_auto_launch');
762
            if (2 === $exerciseAutoLaunch) {
763
                if ($allowAutoLaunchForCourseAdmins) {
764
                    if (empty($autoLaunchWarning)) {
765
                        $autoLaunchWarning = get_lang(
766
                            'TheExerciseAutoLaunchSettingIsONStudentsWillBeRedirectToTheExerciseList'
767
                        );
768
                    }
769
                } else {
770
                    // Redirecting to the document
771
                    $url = api_get_path(WEB_CODE_PATH).'exercise/exercise.php?'.api_get_cidreq();
772
                    header(sprintf('Location: %s', $url));
773
774
                    exit;
775
                }
776
            } elseif (1 === $exerciseAutoLaunch) {
777
                if ($allowAutoLaunchForCourseAdmins) {
778
                    if (empty($autoLaunchWarning)) {
779
                        $autoLaunchWarning = get_lang(
780
                            'TheExerciseAutoLaunchSettingIsONStudentsWillBeRedirectToAnSpecificExercise'
781
                        );
782
                    }
783
                } else {
784
                    // Redirecting to an exercise
785
                    $table = Database::get_course_table(TABLE_QUIZ_TEST);
786
                    $condition = '';
787
                    if (!empty($session_id)) {
788
                        $condition = api_get_session_condition($session_id);
789
                        $sql = "SELECT iid FROM {$table}
790
                                WHERE c_id = {$course_id} AND autolaunch = 1 {$condition}
791
                                LIMIT 1";
792
                        $result = Database::query($sql);
793
                        // If we found nothing in the session we just called the session_id = 0 autolaunch
794
                        if (0 === Database::num_rows($result)) {
795
                            $condition = '';
796
                        }
797
                    }
798
799
                    $sql = "SELECT iid FROM {$table}
800
                            WHERE c_id = {$course_id} AND autolaunch = 1 {$condition}
801
                            LIMIT 1";
802
                    $result = Database::query($sql);
803
                    if (Database::num_rows($result) > 0) {
804
                        $row = Database::fetch_array($result);
805
                        $exerciseId = $row['iid'];
806
                        $url = api_get_path(WEB_CODE_PATH).
807
                            'exercise/overview.php?exerciseId='.$exerciseId.'&'.api_get_cidreq();
808
                        header(sprintf('Location: %s', $url));
809
810
                        exit;
811
                    }
812
                }
813
            }
814
        }
815
816
        $documentAutoLaunch = (int) api_get_course_setting('enable_document_auto_launch');
817
        if (1 === $documentAutoLaunch) {
818
            if ($allowAutoLaunchForCourseAdmins) {
819
                if (empty($autoLaunchWarning)) {
820
                    $autoLaunchWarning = get_lang(
821
                        'The document auto-launch feature configuration is enabled. Learners will be automatically redirected to document tool.'
822
                    );
823
                }
824
            } else {
825
                // Redirecting to the document
826
                $url = api_get_path(WEB_CODE_PATH).'document/document.php?'.api_get_cidreq();
827
                header("Location: $url");
828
829
                exit;
830
            }
831
        }
832
833
        /*  SWITCH TO A DIFFERENT HOMEPAGE VIEW
834
         the setting homepage_view is adjustable through
835
         the platform administration section */
836
        if (!empty($autoLaunchWarning)) {
837
            $this->addFlash(
838
                'warning',
839
                Display::return_message(
840
                    $autoLaunchWarning,
841
                    'warning'
842
                )
843
            );
844
        }
845
    }
846
847
    private function generateToolUrl(AbstractTool $tool): string
848
    {
849
        $link = $tool->getLink();
850
        $course = $this->getCourse();
851
852
        if (strpos($link, 'nodeId')) {
853
            $nodeId = (string) $course->getResourceNode()->getId();
854
            $link = str_replace(':nodeId', $nodeId, $link);
855
        }
856
857
        return $link.'?'.$this->getCourseUrlQuery();
858
    }
859
860
    // Implement the real logic to check course enrollment
861
    private function isUserEnrolledInAnyCourse(User $user, EntityManagerInterface $em): bool
862
    {
863
        $enrollmentCount = $em
864
            ->getRepository(CourseRelUser::class)
865
            ->count(['user' => $user])
866
        ;
867
868
        return $enrollmentCount > 0;
869
    }
870
871
    // Implement the real logic to check session enrollment
872
    private function isUserEnrolledInAnySession(User $user, EntityManagerInterface $em): bool
873
    {
874
        $enrollmentCount = $em->getRepository(SessionRelUser::class)
875
            ->count(['user' => $user])
876
        ;
877
878
        return $enrollmentCount > 0;
879
    }
880
}
881