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