Total Complexity | 115 |
Total Lines | 924 |
Duplicated Lines | 0 % |
Changes | 2 | ||
Bugs | 0 | Features | 0 |
Complex classes like CourseController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use CourseController, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
65 | #[Route('/course')] |
||
66 | class CourseController extends ToolBaseController |
||
67 | { |
||
68 | public function __construct( |
||
69 | private readonly EntityManagerInterface $em, |
||
70 | private readonly SerializerInterface $serializer, |
||
71 | private readonly UserHelper $userHelper, |
||
72 | ) {} |
||
73 | |||
74 | #[Route('/cidReset', methods: ['GET'])] |
||
75 | public function cidReset( |
||
76 | Request $request, |
||
77 | TokenStorageInterface $tokenStorage, |
||
78 | ): Response { |
||
79 | CidReqListener::cleanSessionHandler( |
||
80 | $request, |
||
81 | $tokenStorage->getToken() |
||
82 | ); |
||
83 | |||
84 | return new Response('', Response::HTTP_NO_CONTENT); |
||
85 | } |
||
86 | |||
87 | #[Route('/{cid}/checkLegal.json', name: 'chamilo_core_course_check_legal_json')] |
||
88 | public function checkTermsAndConditionJson( |
||
89 | Request $request, |
||
90 | LegalRepository $legalTermsRepo, |
||
91 | LanguageRepository $languageRepository, |
||
92 | ExtraFieldValuesRepository $extraFieldValuesRepository, |
||
93 | SettingsManager $settingsManager |
||
94 | ): Response { |
||
95 | $user = $this->userHelper->getCurrent(); |
||
96 | $course = $this->getCourse(); |
||
97 | $responseData = [ |
||
98 | 'redirect' => false, |
||
99 | 'url' => '#', |
||
100 | ]; |
||
101 | |||
102 | if ($user && $user->hasRole('ROLE_STUDENT') |
||
103 | && 'true' === $settingsManager->getSetting('allow_terms_conditions') |
||
104 | && 'course' === $settingsManager->getSetting('load_term_conditions_section') |
||
105 | ) { |
||
106 | $termAndConditionStatus = false; |
||
107 | $extraValue = $extraFieldValuesRepository->findLegalAcceptByItemId($user->getId()); |
||
108 | if (!empty($extraValue['value'])) { |
||
109 | $result = $extraValue['value']; |
||
110 | $userConditions = explode(':', $result); |
||
111 | $version = $userConditions[0]; |
||
112 | $langId = (int) $userConditions[1]; |
||
113 | $realVersion = $legalTermsRepo->getLastVersion($langId); |
||
114 | $termAndConditionStatus = ($version >= $realVersion); |
||
115 | } |
||
116 | |||
117 | if (false === $termAndConditionStatus) { |
||
118 | $request->getSession()->set('term_and_condition', ['user_id' => $user->getId()]); |
||
119 | } else { |
||
120 | $request->getSession()->remove('term_and_condition'); |
||
121 | } |
||
122 | |||
123 | $termsAndCondition = $request->getSession()->get('term_and_condition'); |
||
124 | if (null !== $termsAndCondition) { |
||
125 | $redirect = true; |
||
126 | $allow = 'true' === Container::getSettingsManager() |
||
127 | ->getSetting('course.allow_public_course_with_no_terms_conditions') |
||
128 | ; |
||
129 | |||
130 | if (true === $allow |
||
131 | && null !== $course->getVisibility() |
||
132 | && Course::OPEN_WORLD === $course->getVisibility() |
||
133 | ) { |
||
134 | $redirect = false; |
||
135 | } |
||
136 | if ($redirect && !$this->isGranted('ROLE_ADMIN')) { |
||
137 | $url = '/main/auth/inscription.php'; |
||
138 | $responseData = [ |
||
139 | 'redirect' => true, |
||
140 | 'url' => $url, |
||
141 | ]; |
||
142 | } |
||
143 | } |
||
144 | } |
||
145 | |||
146 | return new JsonResponse($responseData); |
||
147 | } |
||
148 | |||
149 | #[Route('/{cid}/home.json', name: 'chamilo_core_course_home_json')] |
||
150 | public function indexJson( |
||
151 | Request $request, |
||
152 | CShortcutRepository $shortcutRepository, |
||
153 | EntityManagerInterface $em, |
||
154 | ): Response { |
||
155 | $requestData = json_decode($request->getContent(), true); |
||
156 | // Sort behaviour |
||
157 | if (!empty($requestData) && isset($requestData['toolItem'])) { |
||
158 | $index = $requestData['index']; |
||
159 | $toolItem = $requestData['toolItem']; |
||
160 | $toolId = (int) $toolItem['iid']; |
||
161 | |||
162 | /** @var CTool $cTool */ |
||
163 | $cTool = $em->find(CTool::class, $toolId); |
||
164 | |||
165 | if ($cTool) { |
||
166 | $cTool->setPosition($index + 1); |
||
167 | $em->persist($cTool); |
||
168 | $em->flush(); |
||
169 | } |
||
170 | } |
||
171 | |||
172 | $course = $this->getCourse(); |
||
173 | $sessionId = $this->getSessionId(); |
||
174 | $isInASession = $sessionId > 0; |
||
175 | |||
176 | if (null === $course) { |
||
177 | throw $this->createAccessDeniedException(); |
||
178 | } |
||
179 | |||
180 | if (empty($sessionId)) { |
||
181 | $this->denyAccessUnlessGranted(CourseVoter::VIEW, $course); |
||
182 | } |
||
183 | |||
184 | $sessionHandler = $request->getSession(); |
||
185 | |||
186 | $userId = 0; |
||
187 | |||
188 | $user = $this->userHelper->getCurrent(); |
||
189 | if (null !== $user) { |
||
190 | $userId = $user->getId(); |
||
191 | } |
||
192 | |||
193 | $courseCode = $course->getCode(); |
||
194 | $courseId = $course->getId(); |
||
195 | |||
196 | if ($user && $user->hasRole('ROLE_INVITEE')) { |
||
197 | $isSubscribed = CourseManager::is_user_subscribed_in_course( |
||
198 | $userId, |
||
199 | $courseCode, |
||
200 | $isInASession, |
||
201 | $sessionId |
||
202 | ); |
||
203 | |||
204 | if (!$isSubscribed) { |
||
205 | throw $this->createAccessDeniedException(); |
||
206 | } |
||
207 | } |
||
208 | |||
209 | $isSpecialCourse = CourseManager::isSpecialCourse($courseId); |
||
210 | |||
211 | if ($user && $isSpecialCourse && (isset($_GET['autoreg']) && 1 === (int) $_GET['autoreg']) |
||
212 | && CourseManager::subscribeUser($userId, $courseId, STUDENT) |
||
213 | ) { |
||
214 | $sessionHandler->set('is_allowed_in_course', true); |
||
215 | } |
||
216 | |||
217 | $logInfo = [ |
||
218 | 'tool' => 'course-main', |
||
219 | ]; |
||
220 | Event::registerLog($logInfo); |
||
221 | |||
222 | // Deleting the objects |
||
223 | $sessionHandler->remove('toolgroup'); |
||
224 | $sessionHandler->remove('_gid'); |
||
225 | $sessionHandler->remove('oLP'); |
||
226 | $sessionHandler->remove('lpobject'); |
||
227 | |||
228 | api_remove_in_gradebook(); |
||
229 | Exercise::cleanSessionVariables(); |
||
230 | |||
231 | $shortcuts = []; |
||
232 | if (null !== $user) { |
||
233 | $shortcutQuery = $shortcutRepository->getResources($course->getResourceNode()); |
||
234 | $shortcuts = $shortcutQuery->getQuery()->getResult(); |
||
235 | } |
||
236 | $responseData = [ |
||
237 | 'shortcuts' => $shortcuts, |
||
238 | 'diagram' => '', |
||
239 | ]; |
||
240 | |||
241 | $json = $this->serializer->serialize( |
||
242 | $responseData, |
||
243 | 'json', |
||
244 | [ |
||
245 | 'groups' => ['course:read', 'ctool:read', 'tool:read', 'cshortcut:read'], |
||
246 | ] |
||
247 | ); |
||
248 | |||
249 | return new Response( |
||
250 | $json, |
||
251 | Response::HTTP_OK, |
||
252 | [ |
||
253 | 'Content-type' => 'application/json', |
||
254 | ] |
||
255 | ); |
||
256 | } |
||
257 | |||
258 | /** |
||
259 | * Redirects the page to a tool, following the tools settings. |
||
260 | */ |
||
261 | #[Route('/{cid}/tool/{toolName}', name: 'chamilo_core_course_redirect_tool')] |
||
262 | public function redirectTool( |
||
263 | Request $request, |
||
264 | string $toolName, |
||
265 | CToolRepository $repo, |
||
266 | ToolChain $toolChain |
||
267 | ): RedirectResponse { |
||
268 | /** @var CTool|null $tool */ |
||
269 | $tool = $repo->findOneBy([ |
||
270 | 'title' => $toolName, |
||
271 | ]); |
||
272 | |||
273 | if (null === $tool) { |
||
274 | throw new NotFoundHttpException($this->trans('Tool not found')); |
||
275 | } |
||
276 | |||
277 | $tool = $toolChain->getToolFromName($tool->getTool()->getTitle()); |
||
278 | $link = $tool->getLink(); |
||
279 | |||
280 | if (null === $this->getCourse()) { |
||
281 | throw new NotFoundHttpException($this->trans('Course not found')); |
||
282 | } |
||
283 | $optionalParams = ''; |
||
284 | |||
285 | $optionalParams = $request->query->get('cert') ? '&cert='.$request->query->get('cert') : ''; |
||
286 | |||
287 | if (strpos($link, 'nodeId')) { |
||
288 | $nodeId = (string) $this->getCourse()->getResourceNode()->getId(); |
||
289 | $link = str_replace(':nodeId', $nodeId, $link); |
||
290 | } |
||
291 | |||
292 | $url = $link.'?'.$this->getCourseUrlQuery().$optionalParams; |
||
293 | |||
294 | return $this->redirect($url); |
||
295 | } |
||
296 | |||
297 | /*public function redirectToShortCut(string $toolName, CToolRepository $repo, ToolChain $toolChain): RedirectResponse |
||
298 | { |
||
299 | $tool = $repo->findOneBy([ |
||
300 | 'name' => $toolName, |
||
301 | ]); |
||
302 | |||
303 | if (null === $tool) { |
||
304 | throw new NotFoundHttpException($this->trans('Tool not found')); |
||
305 | } |
||
306 | |||
307 | $tool = $toolChain->getToolFromName($tool->getTool()->getTitle()); |
||
308 | $link = $tool->getLink(); |
||
309 | |||
310 | if (strpos($link, 'nodeId')) { |
||
311 | $nodeId = (string) $this->getCourse()->getResourceNode()->getId(); |
||
312 | $link = str_replace(':nodeId', $nodeId, $link); |
||
313 | } |
||
314 | |||
315 | $url = $link.'?'.$this->getCourseUrlQuery(); |
||
316 | |||
317 | return $this->redirect($url); |
||
318 | }*/ |
||
319 | |||
320 | /** |
||
321 | * Edit configuration with given namespace. |
||
322 | */ |
||
323 | #[Route('/{course}/settings/{namespace}', name: 'chamilo_core_course_settings')] |
||
324 | public function updateSettings( |
||
325 | Request $request, |
||
326 | #[MapEntity(expr: 'repository.find(cid)')] |
||
327 | Course $course, |
||
328 | string $namespace, |
||
329 | SettingsCourseManager $manager, |
||
330 | SettingsFormFactory $formFactory |
||
331 | ): Response { |
||
332 | $this->denyAccessUnlessGranted(CourseVoter::VIEW, $course); |
||
333 | |||
334 | $schemaAlias = $manager->convertNameSpaceToService($namespace); |
||
335 | $settings = $manager->load($namespace); |
||
336 | |||
337 | $form = $formFactory->create($schemaAlias); |
||
338 | |||
339 | $form->setData($settings); |
||
340 | $form->handleRequest($request); |
||
341 | |||
342 | if ($form->isSubmitted() && $form->isValid()) { |
||
343 | $messageType = 'success'; |
||
344 | |||
345 | try { |
||
346 | $manager->setCourse($course); |
||
347 | $manager->save($form->getData()); |
||
348 | $message = $this->trans('Update'); |
||
349 | } catch (ValidatorException $validatorException) { |
||
350 | $message = $this->trans($validatorException->getMessage()); |
||
351 | $messageType = 'error'; |
||
352 | } |
||
353 | $this->addFlash($messageType, $message); |
||
354 | |||
355 | if ($request->headers->has('referer')) { |
||
356 | return $this->redirect($request->headers->get('referer')); |
||
357 | } |
||
358 | } |
||
359 | |||
360 | $schemas = $manager->getSchemas(); |
||
361 | |||
362 | return $this->render( |
||
363 | '@ChamiloCore/Course/settings.html.twig', |
||
364 | [ |
||
365 | 'course' => $course, |
||
366 | 'schemas' => $schemas, |
||
367 | 'settings' => $settings, |
||
368 | 'form' => $form, |
||
369 | ] |
||
370 | ); |
||
371 | } |
||
372 | |||
373 | #[Route('/{id}/about', name: 'chamilo_core_course_about')] |
||
374 | public function about( |
||
375 | Course $course, |
||
376 | IllustrationRepository $illustrationRepository, |
||
377 | CCourseDescriptionRepository $courseDescriptionRepository, |
||
378 | EntityManagerInterface $em |
||
379 | ): Response { |
||
380 | $courseId = $course->getId(); |
||
381 | |||
382 | $user = $this->userHelper->getCurrent(); |
||
383 | |||
384 | $fieldsRepo = $em->getRepository(ExtraField::class); |
||
385 | |||
386 | /** @var TagRepository $tagRepo */ |
||
387 | $tagRepo = $em->getRepository(Tag::class); |
||
388 | |||
389 | $courseDescriptions = $courseDescriptionRepository->getResourcesByCourse($course)->getQuery()->getResult(); |
||
390 | |||
391 | $courseValues = new ExtraFieldValue('course'); |
||
392 | |||
393 | $urlCourse = api_get_path(WEB_PATH).sprintf('course/%s/about', $courseId); |
||
394 | $courseTeachers = $course->getTeachersSubscriptions(); |
||
395 | $teachersData = []; |
||
396 | |||
397 | foreach ($courseTeachers as $teacherSubscription) { |
||
398 | $teacher = $teacherSubscription->getUser(); |
||
399 | $userData = [ |
||
400 | 'complete_name' => UserManager::formatUserFullName($teacher), |
||
401 | 'image' => $illustrationRepository->getIllustrationUrl($teacher), |
||
402 | 'diploma' => $teacher->getDiplomas(), |
||
403 | 'openarea' => $teacher->getOpenarea(), |
||
404 | ]; |
||
405 | |||
406 | $teachersData[] = $userData; |
||
407 | } |
||
408 | |||
409 | /** @var ExtraField $tagField */ |
||
410 | $tagField = $fieldsRepo->findOneBy([ |
||
411 | 'itemType' => ExtraField::COURSE_FIELD_TYPE, |
||
412 | 'variable' => 'tags', |
||
413 | ]); |
||
414 | |||
415 | $courseTags = []; |
||
416 | if (null !== $tagField) { |
||
417 | $courseTags = $tagRepo->getTagsByItem($tagField, $courseId); |
||
418 | } |
||
419 | |||
420 | $courseDescription = $courseObjectives = $courseTopics = $courseMethodology = ''; |
||
421 | $courseMaterial = $courseResources = $courseAssessment = ''; |
||
422 | $courseCustom = []; |
||
423 | foreach ($courseDescriptions as $descriptionTool) { |
||
424 | switch ($descriptionTool->getDescriptionType()) { |
||
425 | case CCourseDescription::TYPE_DESCRIPTION: |
||
426 | $courseDescription = $descriptionTool->getContent(); |
||
427 | |||
428 | break; |
||
429 | |||
430 | case CCourseDescription::TYPE_OBJECTIVES: |
||
431 | $courseObjectives = $descriptionTool; |
||
432 | |||
433 | break; |
||
434 | |||
435 | case CCourseDescription::TYPE_TOPICS: |
||
436 | $courseTopics = $descriptionTool; |
||
437 | |||
438 | break; |
||
439 | |||
440 | case CCourseDescription::TYPE_METHODOLOGY: |
||
441 | $courseMethodology = $descriptionTool; |
||
442 | |||
443 | break; |
||
444 | |||
445 | case CCourseDescription::TYPE_COURSE_MATERIAL: |
||
446 | $courseMaterial = $descriptionTool; |
||
447 | |||
448 | break; |
||
449 | |||
450 | case CCourseDescription::TYPE_RESOURCES: |
||
451 | $courseResources = $descriptionTool; |
||
452 | |||
453 | break; |
||
454 | |||
455 | case CCourseDescription::TYPE_ASSESSMENT: |
||
456 | $courseAssessment = $descriptionTool; |
||
457 | |||
458 | break; |
||
459 | |||
460 | case CCourseDescription::TYPE_CUSTOM: |
||
461 | $courseCustom[] = $descriptionTool; |
||
462 | |||
463 | break; |
||
464 | } |
||
465 | } |
||
466 | |||
467 | $topics = [ |
||
468 | 'objectives' => $courseObjectives, |
||
469 | 'topics' => $courseTopics, |
||
470 | 'methodology' => $courseMethodology, |
||
471 | 'material' => $courseMaterial, |
||
472 | 'resources' => $courseResources, |
||
473 | 'assessment' => $courseAssessment, |
||
474 | 'custom' => array_reverse($courseCustom), |
||
475 | ]; |
||
476 | |||
477 | $subscriptionUser = false; |
||
478 | |||
479 | if ($user) { |
||
480 | $subscriptionUser = CourseManager::is_user_subscribed_in_course($user->getId(), $course->getCode()); |
||
481 | } |
||
482 | |||
483 | /*$allowSubscribe = false; |
||
484 | if ($course->getSubscribe() || api_is_platform_admin()) { |
||
485 | $allowSubscribe = true; |
||
486 | } |
||
487 | $plugin = \BuyCoursesPlugin::create(); |
||
488 | $checker = $plugin->isEnabled(); |
||
489 | $courseIsPremium = null; |
||
490 | if ($checker) { |
||
491 | $courseIsPremium = $plugin->getItemByProduct( |
||
492 | $courseId, |
||
493 | \BuyCoursesPlugin::PRODUCT_TYPE_COURSE |
||
494 | ); |
||
495 | }*/ |
||
496 | |||
497 | $image = Container::getIllustrationRepository()->getIllustrationUrl($course, 'course_picture_medium'); |
||
498 | |||
499 | $params = [ |
||
500 | 'course' => $course, |
||
501 | 'description' => $courseDescription, |
||
502 | 'image' => $image, |
||
503 | 'syllabus' => $topics, |
||
504 | 'tags' => $courseTags, |
||
505 | 'teachers' => $teachersData, |
||
506 | 'extra_fields' => $courseValues->getAllValuesForAnItem( |
||
507 | $course->getId(), |
||
508 | null, |
||
509 | true |
||
510 | ), |
||
511 | 'subscription' => $subscriptionUser, |
||
512 | 'url' => '', |
||
513 | 'is_premium' => '', |
||
514 | 'token' => '', |
||
515 | ]; |
||
516 | |||
517 | $metaInfo = '<meta property="og:url" content="'.$urlCourse.'" />'; |
||
518 | $metaInfo .= '<meta property="og:type" content="website" />'; |
||
519 | $metaInfo .= '<meta property="og:title" content="'.$course->getTitle().'" />'; |
||
520 | $metaInfo .= '<meta property="og:description" content="'.strip_tags($courseDescription).'" />'; |
||
521 | $metaInfo .= '<meta property="og:image" content="'.$image.'" />'; |
||
522 | |||
523 | $htmlHeadXtra[] = $metaInfo; |
||
524 | $htmlHeadXtra[] = api_get_asset('readmore-js/readmore.js'); |
||
525 | |||
526 | return $this->render('@ChamiloCore/Course/about.html.twig', $params); |
||
527 | } |
||
528 | |||
529 | #[Route('/{id}/welcome', name: 'chamilo_core_course_welcome')] |
||
530 | public function welcome(Course $course): Response |
||
531 | { |
||
532 | return $this->render('@ChamiloCore/Course/welcome.html.twig', [ |
||
533 | 'course' => $course, |
||
534 | ]); |
||
535 | } |
||
536 | |||
537 | private function findIntroOfCourse(Course $course): ?CTool |
||
538 | { |
||
539 | $qb = $this->em->createQueryBuilder(); |
||
540 | |||
541 | $query = $qb->select('ct') |
||
542 | ->from(CTool::class, 'ct') |
||
543 | ->where('ct.course = :c_id') |
||
544 | ->andWhere('ct.title = :title') |
||
545 | ->andWhere( |
||
546 | $qb->expr()->orX( |
||
547 | $qb->expr()->eq('ct.session', ':session_id'), |
||
548 | $qb->expr()->isNull('ct.session') |
||
549 | ) |
||
550 | ) |
||
551 | ->setParameters([ |
||
552 | 'c_id' => $course->getId(), |
||
553 | 'title' => 'course_homepage', |
||
554 | 'session_id' => 0, |
||
555 | ]) |
||
556 | ->getQuery() |
||
557 | ; |
||
558 | |||
559 | return $query->getOneOrNullResult(); |
||
560 | } |
||
561 | |||
562 | #[Route('/{id}/getToolIntro', name: 'chamilo_core_course_gettoolintro')] |
||
563 | public function getToolIntro(Request $request, Course $course, EntityManagerInterface $em): Response |
||
564 | { |
||
565 | $sessionId = (int) $request->get('sid'); |
||
566 | |||
567 | // $session = $this->getSession(); |
||
568 | $responseData = []; |
||
569 | $ctoolRepo = $em->getRepository(CTool::class); |
||
570 | $sessionRepo = $em->getRepository(Session::class); |
||
571 | $createInSession = false; |
||
572 | |||
573 | $session = null; |
||
574 | |||
575 | if (!empty($sessionId)) { |
||
576 | $session = $sessionRepo->find($sessionId); |
||
577 | } |
||
578 | |||
579 | $ctool = $this->findIntroOfCourse($course); |
||
580 | |||
581 | if ($session) { |
||
582 | $ctoolSession = $ctoolRepo->findOneBy(['title' => 'course_homepage', 'course' => $course, 'session' => $session]); |
||
583 | |||
584 | if (!$ctoolSession) { |
||
585 | $createInSession = true; |
||
586 | } else { |
||
587 | $ctool = $ctoolSession; |
||
588 | } |
||
589 | } |
||
590 | |||
591 | if ($ctool) { |
||
592 | $ctoolintroRepo = $em->getRepository(CToolIntro::class); |
||
593 | |||
594 | /** @var CToolIntro $ctoolintro */ |
||
595 | $ctoolintro = $ctoolintroRepo->findOneBy(['courseTool' => $ctool]); |
||
596 | if ($ctoolintro) { |
||
597 | $responseData = [ |
||
598 | 'iid' => $ctoolintro->getIid(), |
||
599 | 'introText' => $ctoolintro->getIntroText(), |
||
600 | 'createInSession' => $createInSession, |
||
601 | 'cToolId' => $ctool->getIid(), |
||
602 | ]; |
||
603 | } |
||
604 | $responseData['c_tool'] = [ |
||
605 | 'iid' => $ctool->getIid(), |
||
606 | 'title' => $ctool->getTitle(), |
||
607 | ]; |
||
608 | } |
||
609 | |||
610 | return new JsonResponse($responseData); |
||
611 | } |
||
612 | |||
613 | #[Route('/{id}/addToolIntro', name: 'chamilo_core_course_addtoolintro')] |
||
614 | public function addToolIntro(Request $request, Course $course, EntityManagerInterface $em): Response |
||
615 | { |
||
616 | $data = $request->getContent(); |
||
617 | $data = json_decode($data); |
||
618 | $ctoolintroId = $data->iid; |
||
619 | $sessionId = $data->sid ?? 0; |
||
620 | |||
621 | $sessionRepo = $em->getRepository(Session::class); |
||
622 | $session = null; |
||
623 | if (!empty($sessionId)) { |
||
624 | $session = $sessionRepo->find($sessionId); |
||
625 | } |
||
626 | |||
627 | $ctool = $em->getRepository(CTool::class); |
||
628 | $check = $ctool->findOneBy(['title' => 'course_homepage', 'course' => $course, 'session' => $session]); |
||
629 | if (!$check) { |
||
630 | $toolRepo = $em->getRepository(Tool::class); |
||
631 | $toolEntity = $toolRepo->findOneBy(['title' => 'course_homepage']); |
||
632 | $courseTool = (new CTool()) |
||
633 | ->setTool($toolEntity) |
||
634 | ->setTitle('course_homepage') |
||
635 | ->setCourse($course) |
||
636 | ->setPosition(1) |
||
637 | ->setVisibility(true) |
||
638 | ->setParent($course) |
||
639 | ->setCreator($course->getCreator()) |
||
640 | ->setSession($session) |
||
641 | ->addCourseLink($course) |
||
642 | ; |
||
643 | $em->persist($courseTool); |
||
644 | $em->flush(); |
||
645 | if ($courseTool && !empty($ctoolintroId)) { |
||
646 | $ctoolintroRepo = Container::getToolIntroRepository(); |
||
647 | |||
648 | /** @var CToolIntro $ctoolintro */ |
||
649 | $ctoolintro = $ctoolintroRepo->find($ctoolintroId); |
||
650 | $ctoolintro->setCourseTool($courseTool); |
||
651 | $ctoolintroRepo->update($ctoolintro); |
||
652 | } |
||
653 | } |
||
654 | $responseData = []; |
||
655 | $json = $this->serializer->serialize( |
||
656 | $responseData, |
||
657 | 'json', |
||
658 | [ |
||
659 | 'groups' => ['course:read', 'ctool:read', 'tool:read', 'cshortcut:read'], |
||
660 | ] |
||
661 | ); |
||
662 | |||
663 | return new JsonResponse($responseData); |
||
664 | } |
||
665 | |||
666 | #[Route('/check-enrollments', name: 'chamilo_core_check_enrollments', methods: ['GET'])] |
||
667 | public function checkEnrollments(EntityManagerInterface $em, SettingsManager $settingsManager): JsonResponse |
||
668 | { |
||
669 | $user = $this->userHelper->getCurrent(); |
||
670 | |||
671 | if (!$user) { |
||
672 | return new JsonResponse(['error' => 'User not found'], Response::HTTP_UNAUTHORIZED); |
||
673 | } |
||
674 | |||
675 | $isEnrolledInCourses = $this->isUserEnrolledInAnyCourse($user, $em); |
||
676 | $isEnrolledInSessions = $this->isUserEnrolledInAnySession($user, $em); |
||
677 | |||
678 | if (!$isEnrolledInCourses && !$isEnrolledInSessions) { |
||
679 | $defaultMenuEntry = $settingsManager->getSetting('platform.default_menu_entry_for_course_or_session'); |
||
680 | $isEnrolledInCourses = 'my_courses' === $defaultMenuEntry; |
||
681 | $isEnrolledInSessions = 'my_sessions' === $defaultMenuEntry; |
||
682 | } |
||
683 | |||
684 | return new JsonResponse([ |
||
685 | 'isEnrolledInCourses' => $isEnrolledInCourses, |
||
686 | 'isEnrolledInSessions' => $isEnrolledInSessions, |
||
687 | ]); |
||
688 | } |
||
689 | |||
690 | #[Route('/categories', name: 'chamilo_core_course_form_lists')] |
||
691 | public function getCategories( |
||
692 | SettingsManager $settingsManager, |
||
693 | AccessUrlHelper $accessUrlHelper, |
||
694 | CourseCategoryRepository $courseCategoriesRepo |
||
695 | ): JsonResponse { |
||
696 | $allowBaseCourseCategory = 'true' === $settingsManager->getSetting('course.allow_base_course_category'); |
||
697 | $accessUrlId = $accessUrlHelper->getCurrent()->getId(); |
||
698 | |||
699 | $categories = $courseCategoriesRepo->findAllInAccessUrl( |
||
700 | $accessUrlId, |
||
701 | $allowBaseCourseCategory |
||
702 | ); |
||
703 | |||
704 | $data = []; |
||
705 | $categoryToAvoid = ''; |
||
706 | if (!$this->isGranted('ROLE_ADMIN')) { |
||
707 | $categoryToAvoid = $settingsManager->getSetting('course.course_category_code_to_use_as_model'); |
||
708 | } |
||
709 | |||
710 | foreach ($categories as $category) { |
||
711 | $categoryCode = $category->getCode(); |
||
712 | if (!empty($categoryToAvoid) && $categoryToAvoid == $categoryCode) { |
||
713 | continue; |
||
714 | } |
||
715 | $data[] = ['id' => $category->getId(), 'name' => $category->__toString()]; |
||
716 | } |
||
717 | |||
718 | return new JsonResponse($data); |
||
719 | } |
||
720 | |||
721 | #[Route('/search_templates', name: 'chamilo_core_course_search_templates')] |
||
722 | public function searchCourseTemplates( |
||
723 | Request $request, |
||
724 | AccessUrlHelper $accessUrlHelper, |
||
725 | CourseRepository $courseRepository |
||
726 | ): JsonResponse { |
||
727 | $searchTerm = $request->query->get('search', ''); |
||
728 | $accessUrl = $accessUrlHelper->getCurrent(); |
||
729 | |||
730 | $user = $this->userHelper->getCurrent(); |
||
731 | |||
732 | $courseList = $courseRepository->getCoursesInfoByUser($user, $accessUrl, 1, $searchTerm); |
||
733 | $results = ['items' => []]; |
||
734 | foreach ($courseList as $course) { |
||
735 | $title = $course['title']; |
||
736 | $results['items'][] = [ |
||
737 | 'id' => $course['id'], |
||
738 | 'name' => $title.' ('.$course['code'].') ', |
||
739 | ]; |
||
740 | } |
||
741 | |||
742 | return new JsonResponse($results); |
||
743 | } |
||
744 | |||
745 | #[Route('/create', name: 'chamilo_core_course_create')] |
||
746 | public function createCourse( |
||
747 | Request $request, |
||
748 | TranslatorInterface $translator, |
||
749 | CourseService $courseService |
||
750 | ): JsonResponse { |
||
751 | $courseData = json_decode($request->getContent(), true); |
||
752 | |||
753 | $title = $courseData['name'] ?? null; |
||
754 | $wantedCode = $courseData['code'] ?? null; |
||
755 | $courseLanguage = $courseData['language']['id'] ?? null; |
||
756 | $categoryCode = $courseData['category'] ?? null; |
||
757 | $exemplaryContent = $courseData['fillDemoContent'] ?? false; |
||
758 | $template = $courseData['template'] ?? ''; |
||
759 | |||
760 | $params = [ |
||
761 | 'title' => $title, |
||
762 | 'wanted_code' => $wantedCode, |
||
763 | 'course_language' => $courseLanguage, |
||
764 | 'exemplary_content' => $exemplaryContent, |
||
765 | 'course_template' => $template, |
||
766 | ]; |
||
767 | |||
768 | if ($categoryCode) { |
||
769 | $params['course_categories'] = $categoryCode; |
||
770 | } |
||
771 | |||
772 | try { |
||
773 | $course = $courseService->createCourse($params); |
||
774 | if ($course) { |
||
775 | return new JsonResponse([ |
||
776 | 'success' => true, |
||
777 | 'message' => $translator->trans('Course created successfully.'), |
||
778 | 'courseId' => $course->getId(), |
||
779 | ]); |
||
780 | } |
||
781 | } catch (Exception $e) { |
||
782 | return new JsonResponse([ |
||
783 | 'success' => false, |
||
784 | 'message' => $translator->trans($e->getMessage()), |
||
785 | ], Response::HTTP_BAD_REQUEST); |
||
786 | } |
||
787 | |||
788 | return new JsonResponse(['success' => false, 'message' => $translator->trans('An error occurred while creating the course.')]); |
||
789 | } |
||
790 | |||
791 | private function autoLaunch(): void |
||
965 | ) |
||
966 | ); |
||
967 | } |
||
968 | } |
||
969 | |||
970 | // Implement the real logic to check course enrollment |
||
971 | private function isUserEnrolledInAnyCourse(User $user, EntityManagerInterface $em): bool |
||
972 | { |
||
973 | $enrollmentCount = $em |
||
974 | ->getRepository(CourseRelUser::class) |
||
975 | ->count(['user' => $user]) |
||
976 | ; |
||
977 | |||
978 | return $enrollmentCount > 0; |
||
979 | } |
||
980 | |||
981 | // Implement the real logic to check session enrollment |
||
982 | private function isUserEnrolledInAnySession(User $user, EntityManagerInterface $em): bool |
||
989 | } |
||
990 | } |
||
991 |