Passed
Push — master ( 3d3d69...b10d98 )
by Julito
21:59
created

CourseHomeController::updateSettingsAction()   A

Complexity

Conditions 5
Paths 9

Size

Total Lines 37
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 24
c 0
b 0
f 0
nc 9
nop 5
dl 0
loc 37
rs 9.2248
1
<?php
2
3
declare(strict_types=1);
4
5
/* For licensing terms, see /license.txt */
6
7
namespace Chamilo\CoreBundle\Controller;
8
9
use Chamilo\CoreBundle\Entity\Course;
10
use Chamilo\CoreBundle\Security\Authorization\Voter\CourseVoter;
11
use Chamilo\CoreBundle\Tool\ToolChain;
12
use Chamilo\CourseBundle\Controller\ToolBaseController;
13
use Chamilo\CourseBundle\Entity\CTool;
14
use Chamilo\CourseBundle\Repository\CShortcutRepository;
15
use Chamilo\CourseBundle\Repository\CToolRepository;
16
use Chamilo\CourseBundle\Settings\SettingsCourseManager;
17
use Chamilo\CourseBundle\Settings\SettingsFormFactory;
18
use CourseManager;
19
use Database;
20
use Display;
21
use Event;
22
use Exercise;
23
use ExtraFieldValue;
24
use Fhaculty\Graph\Graph;
25
use Security;
26
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Entity;
27
use Symfony\Component\HttpFoundation\RedirectResponse;
28
use Symfony\Component\HttpFoundation\Request;
29
use Symfony\Component\HttpFoundation\Response;
30
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
31
use Symfony\Component\Routing\Annotation\Route;
32
use Symfony\Component\Validator\Exception\ValidatorException;
33
use UnserializeApi;
34
35
/**
36
 * @author Julio Montoya <[email protected]>
37
 */
38
#[Route('/course')]
39
class CourseHomeController extends ToolBaseController
40
{
41
    /**
42
     * @Route("/{cid}/home.json", name="chamilo_core_course_home_json")
43
     *
44
     * @Entity("course", expr="repository.find(cid)")
45
     */
46
    public function indexJsonAction(Request $request, CToolRepository $toolRepository, CShortcutRepository $shortcutRepository, ToolChain $toolChain): Response
47
    {
48
        $course = $this->getCourse();
49
50
        if (null === $course) {
51
            throw $this->createAccessDeniedException();
52
        }
53
54
        $this->denyAccessUnlessGranted(CourseVoter::VIEW, $course);
55
56
        $session = $request->getSession();
57
58
        $userId = 0;
59
        $user = $this->getUser();
60
        if (null !== $user) {
61
            $userId = $user->getId();
62
        }
63
64
        $courseCode = $course->getCode();
65
        $courseId = $course->getId();
66
        $sessionId = $this->getSessionId();
67
68
        if ($user && $user->hasRole('ROLE_INVITEE')) {
69
            $isInASession = $sessionId > 0;
70
            $isSubscribed = CourseManager::is_user_subscribed_in_course(
71
                $userId,
72
                $courseCode,
73
                $isInASession,
74
                $sessionId
75
            );
76
77
            if (!$isSubscribed) {
78
                throw $this->createAccessDeniedException();
79
            }
80
        }
81
82
        $isSpecialCourse = CourseManager::isSpecialCourse($courseId);
83
84
        if ($user && $isSpecialCourse && (isset($_GET['autoreg']) && 1 === (int) $_GET['autoreg']) &&
85
            CourseManager::subscribeUser($userId, $courseId, STUDENT)
86
        ) {
87
            $session->set('is_allowed_in_course', true);
88
        }
89
90
        /*$action = empty($_GET['action']) ? '' : Security::remove_XSS($_GET['action']);
91
        if ('subscribe' === $action && Security::check_token('get')) {
92
            Security::clear_token();
93
            $result = CourseManager::autoSubscribeToCourse($courseCode);
94
            if ($result && CourseManager::is_user_subscribed_in_course($userId, $courseCode)) {
95
                $session->set('is_allowed_in_course', true);
96
            }
97
            header('Location: '.api_get_self());
98
            exit;
99
        }
100
101
        $logInfo = [
102
            'tool' => 'course-main',
103
            'action' => $action,
104
        ];
105
        Event::registerLog($logInfo);*/
106
        $logInfo = [
107
            'tool' => 'course-main',
108
        ];
109
        Event::registerLog($logInfo);
110
111
        $qb = $toolRepository->getResourcesByCourse($course, $this->getSession());
112
113
        $qb->addSelect('tool');
114
        $qb->innerJoin('resource.tool', 'tool');
115
116
        $result = $qb->getQuery()->getResult();
117
        $tools = [];
118
        $isCourseTeacher = $this->isGranted('ROLE_CURRENT_COURSE_TEACHER');
119
120
        /** @var CTool $item */
121
        foreach ($result as $item) {
122
            if ('course_tool' === $item->getName()) {
123
                continue;
124
            }
125
            $toolModel = $toolChain->getToolFromName($item->getTool()->getName());
126
127
            if (!$isCourseTeacher && 'admin' === $toolModel->getCategory()) {
128
                continue;
129
            }
130
131
            $tools[$toolModel->getCategory()][] = [
132
                'ctool' => $item,
133
                'tool' => $toolModel,
134
            ];
135
        }
136
137
        // Get session-career diagram
138
        $diagram = '';
139
        /*$allow = api_get_configuration_value('allow_career_diagram');
140
        if (true === $allow) {
141
            $htmlHeadXtra[] = api_get_js('jsplumb2.js');
142
            $extra = new ExtraFieldValue('session');
143
            $value = $extra->get_values_by_handler_and_field_variable(
144
                api_get_session_id(),
145
                'external_career_id'
146
            );
147
148
            if (!empty($value) && isset($value['value'])) {
149
                $careerId = $value['value'];
150
                $extraFieldValue = new ExtraFieldValue('career');
151
                $item = $extraFieldValue->get_item_id_from_field_variable_and_field_value(
152
                    'external_career_id',
153
                    $careerId,
154
                    false,
155
                    false,
156
                    false
157
                );
158
159
                if (!empty($item) && isset($item['item_id'])) {
160
                    $careerId = $item['item_id'];
161
                    $career = new Career();
162
                    $careerInfo = $career->get($careerId);
163
                    if (!empty($careerInfo)) {
164
                        $extraFieldValue = new ExtraFieldValue('career');
165
                        $item = $extraFieldValue->get_values_by_handler_and_field_variable(
166
                            $careerId,
167
                            'career_diagram',
168
                            false,
169
                            false,
170
                            0
171
                        );
172
173
                        if (!empty($item) && isset($item['value']) && !empty($item['value'])) {
174
                            // @var Graph $graph
175
                            $graph = UnserializeApi::unserialize('career', $item['value']);
176
                            $diagram = Career::renderDiagram($careerInfo, $graph);
177
                        }
178
                    }
179
                }
180
            }
181
        }*/
182
183
        // Deleting the objects
184
        $session->remove('toolgroup');
185
        $session->remove('_gid');
186
        $session->remove('oLP');
187
        $session->remove('lpobject');
188
189
        api_remove_in_gradebook();
190
        Exercise::cleanSessionVariables();
191
192
        $shortcuts = [];
193
        if (null !== $user) {
194
            $shortcutQuery = $shortcutRepository->getResources($course->getResourceNode());
195
            $shortcuts = $shortcutQuery->getQuery()->getResult();
196
        }
197
        $responseData = [
198
            'course' => $course,
199
            'shortcuts' => $shortcuts,
200
            'diagram' => $diagram,
201
            'tools' => $tools,
202
        ];
203
204
        $json = $this->get('serializer')->serialize(
205
            $responseData,
206
            'json',
207
            [
208
                'groups' => ['course:read', 'ctool:read', 'tool:read', 'cshortcut:read'],
209
            ]
210
        );
211
212
        return new Response(
213
            $json,
214
            Response::HTTP_OK,
215
            [
216
                'Content-type' => 'application/json',
217
            ]
218
        );
219
        /*return $this->render(
220
            '@ChamiloCore/Course/home.html.twig',
221
            [
222
                'course' => $course,
223
                'shortcuts' => $shortcuts,
224
                'diagram' => $diagram,
225
                'tools' => $tools,
226
            ]
227
        );*/
228
    }
229
230
    /**
231
     * Redirects the page to a tool, following the tools.yml settings.
232
     *
233
     * @Route("/{cid}/tool/{toolName}", name="chamilo_core_course_redirect_tool")
234
     */
235
    public function redirectTool(string $toolName, CToolRepository $repo, ToolChain $toolChain): RedirectResponse
236
    {
237
        /** @var CTool|null $tool */
238
        $tool = $repo->findOneBy([
239
            'name' => $toolName,
240
        ]);
241
242
        if (null === $tool) {
243
            throw new NotFoundHttpException($this->trans('Tool not found'));
244
        }
245
246
        $tool = $toolChain->getToolFromName($tool->getTool()->getName());
247
        $link = $tool->getLink();
248
249
        if (null === $this->getCourse()) {
250
            throw new NotFoundHttpException($this->trans('Course not found'));
251
        }
252
253
        if (strpos($link, 'nodeId')) {
254
            $nodeId = (string) $this->getCourse()->getResourceNode()->getId();
255
            $link = str_replace(':nodeId', $nodeId, $link);
256
        }
257
258
        $url = $link.'?'.$this->getCourseUrlQuery();
259
260
        return $this->redirect($url);
261
    }
262
263
    public function redirectToShortCut(string $toolName, CToolRepository $repo, ToolChain $toolChain): RedirectResponse
264
    {
265
        /** @var CTool|null $tool */
266
        $tool = $repo->findOneBy([
267
            'name' => $toolName,
268
        ]);
269
270
        if (null === $tool) {
271
            throw new NotFoundHttpException($this->trans('Tool not found'));
272
        }
273
274
        $tool = $toolChain->getToolFromName($tool->getTool()->getName());
275
        $link = $tool->getLink();
276
277
        if (strpos($link, 'nodeId')) {
278
            $nodeId = (string) $this->getCourse()->getResourceNode()->getId();
279
            $link = str_replace(':nodeId', $nodeId, $link);
280
        }
281
282
        $url = $link.'?'.$this->getCourseUrlQuery();
283
284
        return $this->redirect($url);
285
    }
286
287
    /**
288
     * Edit configuration with given namespace.
289
     *
290
     * @Route("/{cid}/settings/{namespace}", name="chamilo_core_course_settings")
291
     *
292
     * @Entity("course", expr="repository.find(cid)")
293
     */
294
    public function updateSettings(Request $request, Course $course, string $namespace, SettingsCourseManager $manager, SettingsFormFactory $formFactory): Response
295
    {
296
        $this->denyAccessUnlessGranted(CourseVoter::VIEW, $course);
297
298
        $schemaAlias = $manager->convertNameSpaceToService($namespace);
299
        $settings = $manager->load($namespace);
300
301
        $form = $formFactory->create($schemaAlias);
302
303
        $form->setData($settings);
304
        $form->handleRequest($request);
305
306
        if ($form->isSubmitted() && $form->isValid()) {
307
            $messageType = 'success';
308
309
            try {
310
                $manager->setCourse($course);
311
                $manager->save($form->getData());
312
                $message = $this->trans('Update');
313
            } catch (ValidatorException $validatorException) {
314
                $message = $this->trans($validatorException->getMessage());
315
                $messageType = 'error';
316
            }
317
            $this->addFlash($messageType, $message);
318
319
            if ($request->headers->has('referer')) {
320
                return $this->redirect($request->headers->get('referer'));
321
            }
322
        }
323
324
        $schemas = $manager->getSchemas();
325
326
        return $this->render(
327
            '@ChamiloCore/Course/settings.html.twig',
328
            [
329
                'course' => $course,
330
                'schemas' => $schemas,
331
                'settings' => $settings,
332
                'form' => $form->createView(),
333
            ]
334
        );
335
    }
336
337
    private function autoLaunch(): void
338
    {
339
        $autoLaunchWarning = '';
340
        $showAutoLaunchLpWarning = false;
341
        $course_id = api_get_course_int_id();
342
        $lpAutoLaunch = api_get_course_setting('enable_lp_auto_launch');
343
        $session_id = api_get_session_id();
344
        $allowAutoLaunchForCourseAdmins =
345
            api_is_platform_admin() ||
346
            api_is_allowed_to_edit(true, true) ||
347
            api_is_coach();
348
349
        if (!empty($lpAutoLaunch)) {
350
            if (2 === $lpAutoLaunch) {
351
                // LP list
352
                if ($allowAutoLaunchForCourseAdmins) {
353
                    $showAutoLaunchLpWarning = true;
354
                } else {
355
                    $session_key = 'lp_autolaunch_'.$session_id.'_'.$course_id.'_'.api_get_user_id();
356
                    if (!isset($_SESSION[$session_key])) {
357
                        // Redirecting to the LP
358
                        $url = api_get_path(WEB_CODE_PATH).'lp/lp_controller.php?'.api_get_cidreq();
359
                        $_SESSION[$session_key] = true;
360
                        header(sprintf('Location: %s', $url));
361
                        exit;
362
                    }
363
                }
364
            } else {
365
                $lp_table = Database::get_course_table(TABLE_LP_MAIN);
366
                $condition = '';
367
                if (!empty($session_id)) {
368
                    $condition = api_get_session_condition($session_id);
369
                    $sql = "SELECT id FROM {$lp_table}
370
                            WHERE c_id = {$course_id} AND autolaunch = 1 {$condition}
371
                            LIMIT 1";
372
                    $result = Database::query($sql);
373
                    // If we found nothing in the session we just called the session_id =  0 autolaunch
374
                    if (0 === Database::num_rows($result)) {
375
                        $condition = '';
376
                    }
377
                }
378
379
                $sql = "SELECT iid FROM {$lp_table}
380
                        WHERE c_id = {$course_id} AND autolaunch = 1 {$condition}
381
                        LIMIT 1";
382
                $result = Database::query($sql);
383
                if (Database::num_rows($result) > 0) {
384
                    $lp_data = Database::fetch_array($result, 'ASSOC');
385
                    if (!empty($lp_data['iid'])) {
386
                        if ($allowAutoLaunchForCourseAdmins) {
387
                            $showAutoLaunchLpWarning = true;
388
                        } else {
389
                            $session_key = 'lp_autolaunch_'.$session_id.'_'.api_get_course_int_id().'_'.api_get_user_id();
390
                            if (!isset($_SESSION[$session_key])) {
391
                                // Redirecting to the LP
392
                                $url = api_get_path(WEB_CODE_PATH).
393
                                    'lp/lp_controller.php?'.api_get_cidreq().'&action=view&lp_id='.$lp_data['iid'];
394
395
                                $_SESSION[$session_key] = true;
396
                                header(sprintf('Location: %s', $url));
397
                                exit;
398
                            }
399
                        }
400
                    }
401
                }
402
            }
403
        }
404
405
        if ($showAutoLaunchLpWarning) {
406
            $autoLaunchWarning = get_lang(
407
                '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.'
408
            );
409
        }
410
411
        $forumAutoLaunch = (int) api_get_course_setting('enable_forum_auto_launch');
412
        if (1 === $forumAutoLaunch) {
413
            if ($allowAutoLaunchForCourseAdmins) {
414
                if (empty($autoLaunchWarning)) {
415
                    $autoLaunchWarning = get_lang(
416
                        "The forum's auto-launch setting is on. Students will be redirected to the forum tool when entering this course."
417
                    );
418
                }
419
            } else {
420
                $url = api_get_path(WEB_CODE_PATH).'forum/index.php?'.api_get_cidreq();
421
                header(sprintf('Location: %s', $url));
422
                exit;
423
            }
424
        }
425
426
        if (api_get_configuration_value('allow_exercise_auto_launch')) {
427
            $exerciseAutoLaunch = (int) api_get_course_setting('enable_exercise_auto_launch');
428
            if (2 === $exerciseAutoLaunch) {
429
                if ($allowAutoLaunchForCourseAdmins) {
430
                    if (empty($autoLaunchWarning)) {
431
                        $autoLaunchWarning = get_lang(
432
                            'TheExerciseAutoLaunchSettingIsONStudentsWillBeRedirectToTheExerciseList'
433
                        );
434
                    }
435
                } else {
436
                    // Redirecting to the document
437
                    $url = api_get_path(WEB_CODE_PATH).'exercise/exercise.php?'.api_get_cidreq();
438
                    header(sprintf('Location: %s', $url));
439
                    exit;
440
                }
441
            } elseif (1 === $exerciseAutoLaunch) {
442
                if ($allowAutoLaunchForCourseAdmins) {
443
                    if (empty($autoLaunchWarning)) {
444
                        $autoLaunchWarning = get_lang(
445
                            'TheExerciseAutoLaunchSettingIsONStudentsWillBeRedirectToAnSpecificExercise'
446
                        );
447
                    }
448
                } else {
449
                    // Redirecting to an exercise
450
                    $table = Database::get_course_table(TABLE_QUIZ_TEST);
451
                    $condition = '';
452
                    if (!empty($session_id)) {
453
                        $condition = api_get_session_condition($session_id);
454
                        $sql = "SELECT iid FROM {$table}
455
                                WHERE c_id = {$course_id} AND autolaunch = 1 {$condition}
456
                                LIMIT 1";
457
                        $result = Database::query($sql);
458
                        // If we found nothing in the session we just called the session_id = 0 autolaunch
459
                        if (0 === Database::num_rows($result)) {
460
                            $condition = '';
461
                        }
462
                    }
463
464
                    $sql = "SELECT iid FROM {$table}
465
                            WHERE c_id = {$course_id} AND autolaunch = 1 {$condition}
466
                            LIMIT 1";
467
                    $result = Database::query($sql);
468
                    if (Database::num_rows($result) > 0) {
469
                        $row = Database::fetch_array($result, 'ASSOC');
470
                        $exerciseId = $row['iid'];
471
                        $url = api_get_path(WEB_CODE_PATH).
472
                            'exercise/overview.php?exerciseId='.$exerciseId.'&'.api_get_cidreq();
473
                        header(sprintf('Location: %s', $url));
474
                        exit;
475
                    }
476
                }
477
            }
478
        }
479
480
        $documentAutoLaunch = (int) api_get_course_setting('enable_document_auto_launch');
481
        if (1 === $documentAutoLaunch) {
482
            if ($allowAutoLaunchForCourseAdmins) {
483
                if (empty($autoLaunchWarning)) {
484
                    $autoLaunchWarning = get_lang(
485
                        'The document auto-launch feature configuration is enabled. Learners will be automatically redirected to document tool.'
486
                    );
487
                }
488
            } else {
489
                // Redirecting to the document
490
                $url = api_get_path(WEB_CODE_PATH).'document/document.php?'.api_get_cidreq();
491
                header("Location: $url");
492
                exit;
493
            }
494
        }
495
496
        /*	SWITCH TO A DIFFERENT HOMEPAGE VIEW
497
         the setting homepage_view is adjustable through
498
         the platform administration section */
499
        if (!empty($autoLaunchWarning)) {
500
            $this->addFlash(
501
                'warning',
502
                Display::return_message(
503
                    $autoLaunchWarning,
504
                    'warning'
505
                )
506
            );
507
        }
508
    }
509
}
510