Passed
Pull Request — master (#6039)
by
unknown
07:39
created

CourseController::indexJson()   D

Complexity

Conditions 19
Paths 111

Size

Total Lines 122
Code Lines 71

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 19
eloc 71
nc 111
nop 4
dl 0
loc 122
rs 4.425
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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