Passed
Push — master ( df064e...3f6262 )
by Angel Fernando Quiroz
07:57 queued 39s
created

CourseController::generateToolUrl()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

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