Passed
Push — master ( ad6b2a...ec8fd5 )
by Julito
28:29 queued 12s
created

CourseHomeController::indexJsonAction()   F

Complexity

Conditions 30
Paths 1201

Size

Total Lines 170
Code Lines 104

Duplication

Lines 0
Ratio 0 %

Importance

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