Passed
Push — master ( d886e7...d787f3 )
by Julito
10:03
created

CourseHomeController   F

Complexity

Total Complexity 68

Size/Duplication

Total Lines 411
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 240
c 0
b 0
f 0
dl 0
loc 411
rs 2.96
wmc 68

4 Methods

Rating   Name   Duplication   Size   Complexity  
F autoLaunch() 0 166 31
F indexAction() 0 154 29
A redirectTool() 0 22 3
A updateSettingsAction() 0 37 5

How to fix   Complexity   

Complex Class

Complex classes like CourseHomeController 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 CourseHomeController, and based on these observations, apply Extract Interface, too.

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", name="chamilo_core_course_home")
45
     *
46
     * @Entity("course", expr="repository.find(cid)")
47
     */
48
    public function indexAction(Request $request, CToolRepository $toolRepository, CShortcutRepository $shortcutRepository, ToolChain $toolChain)
49
    {
50
        $this->autoLaunch();
51
        $course = $this->getCourse();
52
        $session = $request->getSession();
53
54
        $js = '<script>'.api_get_language_translate_html().'</script>';
55
        $htmlHeadXtra[] = $js;
0 ignored issues
show
Comprehensibility Best Practice introduced by
$htmlHeadXtra was never initialized. Although not strictly required by PHP, it is generally a good practice to add $htmlHeadXtra = array(); before regardless.
Loading history...
56
57
        $userId = 0;
58
        $user = $this->getUser();
59
        if ($user) {
60
            $userId = $this->getUser()->getId();
61
        }
62
63
        $courseCode = $course->getCode();
64
        $courseId = $course->getId();
65
        $sessionId = $this->getSessionId();
66
67
        if ($user && api_is_invitee()) {
68
            $isInASession = $sessionId > 0;
69
            $isSubscribed = CourseManager::is_user_subscribed_in_course(
70
                $userId,
71
                $courseCode,
72
                $isInASession,
73
                $sessionId
74
            );
75
76
            if (!$isSubscribed) {
77
                api_not_allowed(true);
78
            }
79
        }
80
81
        $isSpecialCourse = CourseManager::isSpecialCourse($courseId);
82
83
        if ($user && $isSpecialCourse && (isset($_GET['autoreg']) && 1 === (int) $_GET['autoreg'])) {
84
            if (CourseManager::subscribeUser($userId, $courseCode, STUDENT)) {
85
                $session->set('is_allowed_in_course', true);
86
            }
87
        }
88
89
        $action = empty($_GET['action']) ? '' : Security::remove_XSS($_GET['action']);
90
        if ('subscribe' === $action && Security::check_token('get')) {
91
            Security::clear_token();
92
            $result = CourseManager::autoSubscribeToCourse($courseCode);
93
            if ($result && CourseManager::is_user_subscribed_in_course($userId, $courseCode)) {
94
                $session->set('is_allowed_in_course', true);
95
            }
96
            header('Location: '.api_get_self());
97
            exit;
98
        }
99
100
        $logInfo = [
101
            'tool' => 'course-main',
102
            'action' => $action,
103
        ];
104
        Event::registerLog($logInfo);
105
106
        /*	Introduction section (editable by course admins) */
107
        /*$introduction = Display::return_introduction_section(
108
            TOOL_COURSE_HOMEPAGE,
109
            [
110
                'CreateDocumentWebDir' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/',
111
                'CreateDocumentDir' => 'document/',
112
                'BaseHref' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/',
113
            ]
114
        );*/
115
116
        $qb = $toolRepository->getResourcesByCourse($course, $this->getSession());
117
        $qb->addSelect('tool');
118
        $qb->innerJoin('resource.tool', 'tool');
119
        $result = $qb->getQuery()->getResult();
120
        $tools = [];
121
        /** @var CTool $item */
122
        foreach ($result as $item) {
123
            if ('course_tool' === $item->getName()) {
124
                continue;
125
            }
126
            $toolModel = $toolChain->getToolFromName($item->getTool()->getName());
127
128
            if ('admin' === $toolModel->getCategory() && !$this->isGranted('ROLE_CURRENT_COURSE_TEACHER')) {
129
                continue;
130
            }
131
            $tools[$toolModel->getCategory()][] = $item;
132
        }
133
134
        // Get session-career diagram
135
        $diagram = '';
136
        $allow = api_get_configuration_value('allow_career_diagram');
137
        if (true === $allow) {
138
            $htmlHeadXtra[] = api_get_js('jsplumb2.js');
139
            $extra = new ExtraFieldValue('session');
140
            $value = $extra->get_values_by_handler_and_field_variable(
141
                api_get_session_id(),
142
                'external_career_id'
143
            );
144
145
            if (!empty($value) && isset($value['value'])) {
146
                $careerId = $value['value'];
147
                $extraFieldValue = new ExtraFieldValue('career');
148
                $item = $extraFieldValue->get_item_id_from_field_variable_and_field_value(
149
                    'external_career_id',
150
                    $careerId,
151
                    false,
152
                    false,
153
                    false
154
                );
155
156
                if (!empty($item) && isset($item['item_id'])) {
157
                    $careerId = $item['item_id'];
158
                    $career = new Career();
159
                    $careerInfo = $career->get($careerId);
160
                    if (!empty($careerInfo)) {
161
                        $extraFieldValue = new ExtraFieldValue('career');
162
                        $item = $extraFieldValue->get_values_by_handler_and_field_variable(
163
                            $careerId,
164
                            'career_diagram',
165
                            false,
166
                            false,
167
                            0
168
                        );
169
170
                        if (!empty($item) && isset($item['value']) && !empty($item['value'])) {
171
                            /** @var Graph $graph */
172
                            $graph = UnserializeApi::unserialize('career', $item['value']);
173
                            $diagram = Career::renderDiagram($careerInfo, $graph);
174
                        }
175
                    }
176
                }
177
            }
178
        }
179
180
        // Deleting the objects
181
        $session->remove('toolgroup');
182
        $session->remove('_gid');
183
        $session->remove('oLP');
184
        $session->remove('lpobject');
185
186
        api_remove_in_gradebook();
187
        Exercise::cleanSessionVariables();
188
189
        $shortcuts = [];
190
        if ($user) {
191
            $shortcutQuery = $shortcutRepository->getResources($user, $course->getResourceNode(), $course);
192
            $shortcuts = $shortcutQuery->getQuery()->getResult();
193
        }
194
195
        return $this->render(
196
            '@ChamiloCore/Course/home.html.twig',
197
            [
198
                'course' => $course,
199
                'shortcuts' => $shortcuts,
200
                'diagram' => $diagram,
201
                'tools' => $tools,
202
            ]
203
        );
204
    }
205
206
    /**
207
     * Redirects the page to a tool, following the tools.yml settings.
208
     *
209
     * @Route("/{cid}/tool/{toolName}", name="chamilo_core_course_redirect_tool")
210
     */
211
    public function redirectTool(string $toolName, CToolRepository $repo, ToolChain $toolChain)
212
    {
213
        /** @var null|CTool $tool */
214
        $tool = $repo->findOneBy([
215
            'name' => $toolName,
216
        ]);
217
218
        if (null === $tool) {
219
            throw new NotFoundHttpException($this->trans('Tool not found'));
220
        }
221
222
        $tool = $toolChain->getToolFromName($tool->getTool()->getName());
223
        $link = $tool->getLink();
224
225
        if (strpos($link, 'nodeId')) {
226
            $nodeId = (string) $this->getCourse()->getResourceNode()->getId();
227
            $link = str_replace(':nodeId', $nodeId, $link);
228
        }
229
230
        $url = $link.'?'.$this->getCourseUrlQuery();
231
232
        return $this->redirect($url);
233
    }
234
235
    /**
236
     * Edit configuration with given namespace.
237
     *
238
     * @param string $namespace
239
     * @Route("/{cid}/settings/{namespace}", name="chamilo_core_course_settings")
240
     *
241
     * @Entity("course", expr="repository.find(cid)")
242
     *
243
     * @return Response
244
     */
245
    public function updateSettingsAction(Request $request, Course $course, $namespace, SettingsCourseManager $manager, SettingsFormFactory $formFactory)
246
    {
247
        $schemaAlias = $manager->convertNameSpaceToService($namespace);
248
        $settings = $manager->load($namespace);
249
250
        $form = $formFactory->create($schemaAlias);
251
252
        $form->setData($settings);
253
        $form->handleRequest($request);
254
255
        if ($form->isSubmitted() && $form->isValid()) {
256
            $messageType = 'success';
257
258
            try {
259
                $manager->setCourse($course);
260
                $manager->save($form->getData());
261
                $message = $this->trans('Update');
262
            } catch (ValidatorException $exception) {
263
                $message = $this->trans($exception->getMessage());
264
                $messageType = 'error';
265
            }
266
            $this->addFlash($messageType, $message);
267
268
            if ($request->headers->has('referer')) {
269
                return $this->redirect($request->headers->get('referer'));
270
            }
271
        }
272
273
        $schemas = $manager->getSchemas();
274
275
        return $this->render(
276
            '@ChamiloCore/Course/settings.html.twig',
277
            [
278
                'course' => $course,
279
                'schemas' => $schemas,
280
                'settings' => $settings,
281
                'form' => $form->createView(),
282
            ]
283
        );
284
    }
285
286
    private function autoLaunch(): void
287
    {
288
        /* Auto launch code */
289
        $autoLaunchWarning = '';
290
        $showAutoLaunchLpWarning = false;
291
        $course_id = api_get_course_int_id();
292
        $lpAutoLaunch = api_get_course_setting('enable_lp_auto_launch');
293
        $session_id = api_get_session_id();
294
        $allowAutoLaunchForCourseAdmins = api_is_platform_admin() || api_is_allowed_to_edit(true, true) || api_is_coach();
295
296
        if (!empty($lpAutoLaunch)) {
297
            if (2 === $lpAutoLaunch) {
298
                // LP list
299
                if ($allowAutoLaunchForCourseAdmins) {
300
                    $showAutoLaunchLpWarning = true;
301
                } else {
302
                    $session_key = 'lp_autolaunch_'.$session_id.'_'.api_get_course_int_id().'_'.api_get_user_id();
303
                    if (!isset($_SESSION[$session_key])) {
304
                        // Redirecting to the LP
305
                        $url = api_get_path(WEB_CODE_PATH).'lp/lp_controller.php?'.api_get_cidreq();
306
                        $_SESSION[$session_key] = true;
307
                        header("Location: {$url}");
308
                        exit;
309
                    }
310
                }
311
            } else {
312
                $lp_table = Database::get_course_table(TABLE_LP_MAIN);
313
                $condition = '';
314
                if (!empty($session_id)) {
315
                    $condition = api_get_session_condition($session_id);
316
                    $sql = "SELECT id FROM {$lp_table}
317
                            WHERE c_id = {$course_id} AND autolaunch = 1 {$condition}
318
                            LIMIT 1";
319
                    $result = Database::query($sql);
320
                    // If we found nothing in the session we just called the session_id =  0 autolaunch
321
                    if (0 === Database::num_rows($result)) {
322
                        $condition = '';
323
                    }
324
                }
325
326
                $sql = "SELECT iid FROM {$lp_table}
327
                        WHERE c_id = {$course_id} AND autolaunch = 1 {$condition}
328
                        LIMIT 1";
329
                $result = Database::query($sql);
330
                if (Database::num_rows($result) > 0) {
331
                    $lp_data = Database::fetch_array($result, 'ASSOC');
332
                    if (!empty($lp_data['iid'])) {
333
                        if ($allowAutoLaunchForCourseAdmins) {
334
                            $showAutoLaunchLpWarning = true;
335
                        } else {
336
                            $session_key = 'lp_autolaunch_'.$session_id.'_'.api_get_course_int_id().'_'.api_get_user_id();
337
                            if (!isset($_SESSION[$session_key])) {
338
                                // Redirecting to the LP
339
                                $url = api_get_path(WEB_CODE_PATH).
340
                                    'lp/lp_controller.php?'.api_get_cidreq().'&action=view&lp_id='.$lp_data['iid'];
341
342
                                $_SESSION[$session_key] = true;
343
                                header("Location: {$url}");
344
                                exit;
345
                            }
346
                        }
347
                    }
348
                }
349
            }
350
        }
351
352
        if ($showAutoLaunchLpWarning) {
353
            $autoLaunchWarning = get_lang(
354
                '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.'
355
            );
356
        }
357
358
        $forumAutoLaunch = (int) api_get_course_setting('enable_forum_auto_launch');
359
        if (1 === $forumAutoLaunch) {
360
            if ($allowAutoLaunchForCourseAdmins) {
361
                if (empty($autoLaunchWarning)) {
362
                    $autoLaunchWarning = get_lang(
363
                        'The forum\'s auto-launch setting is on. Students will be redirected to the forum tool when entering this course.'
364
                    );
365
                }
366
            } else {
367
                $url = api_get_path(WEB_CODE_PATH).'forum/index.php?'.api_get_cidreq();
368
                header("Location: {$url}");
369
                exit;
370
            }
371
        }
372
373
        if (api_get_configuration_value('allow_exercise_auto_launch')) {
374
            $exerciseAutoLaunch = (int) api_get_course_setting('enable_exercise_auto_launch');
375
            if (2 === $exerciseAutoLaunch) {
376
                if ($allowAutoLaunchForCourseAdmins) {
377
                    if (empty($autoLaunchWarning)) {
378
                        $autoLaunchWarning = get_lang(
379
                            'TheExerciseAutoLaunchSettingIsONStudentsWillBeRedirectToTheExerciseList'
380
                        );
381
                    }
382
                } else {
383
                    // Redirecting to the document
384
                    $url = api_get_path(WEB_CODE_PATH).'exercise/exercise.php?'.api_get_cidreq();
385
                    header("Location: {$url}");
386
                    exit;
387
                }
388
            } elseif (1 === $exerciseAutoLaunch) {
389
                if ($allowAutoLaunchForCourseAdmins) {
390
                    if (empty($autoLaunchWarning)) {
391
                        $autoLaunchWarning = get_lang(
392
                            'TheExerciseAutoLaunchSettingIsONStudentsWillBeRedirectToAnSpecificExercise'
393
                        );
394
                    }
395
                } else {
396
                    // Redirecting to an exercise
397
                    $table = Database::get_course_table(TABLE_QUIZ_TEST);
398
                    $condition = '';
399
                    if (!empty($session_id)) {
400
                        $condition = api_get_session_condition($session_id);
401
                        $sql = "SELECT iid FROM {$table}
402
                                WHERE c_id = {$course_id} AND autolaunch = 1 {$condition}
403
                                LIMIT 1";
404
                        $result = Database::query($sql);
405
                        // If we found nothing in the session we just called the session_id = 0 autolaunch
406
                        if (0 === Database::num_rows($result)) {
407
                            $condition = '';
408
                        }
409
                    }
410
411
                    $sql = "SELECT iid FROM {$table}
412
                            WHERE c_id = {$course_id} AND autolaunch = 1 {$condition}
413
                            LIMIT 1";
414
                    $result = Database::query($sql);
415
                    if (Database::num_rows($result) > 0) {
416
                        $row = Database::fetch_array($result, 'ASSOC');
417
                        $exerciseId = $row['iid'];
418
                        $url = api_get_path(WEB_CODE_PATH).
419
                            'exercise/overview.php?exerciseId='.$exerciseId.'&'.api_get_cidreq();
420
                        header("Location: {$url}");
421
                        exit;
422
                    }
423
                }
424
            }
425
        }
426
427
        $documentAutoLaunch = (int) api_get_course_setting('enable_document_auto_launch');
428
        if (1 === $documentAutoLaunch) {
429
            if ($allowAutoLaunchForCourseAdmins) {
430
                if (empty($autoLaunchWarning)) {
431
                    $autoLaunchWarning = get_lang(
432
                        'The document auto-launch feature configuration is enabled. Learners will be automatically redirected to document tool.'
433
                    );
434
                }
435
            } else {
436
                // Redirecting to the document
437
                $url = api_get_path(WEB_CODE_PATH).'document/document.php?'.api_get_cidreq();
438
                header("Location: {$url}");
439
                exit;
440
            }
441
        }
442
443
        /*	SWITCH TO A DIFFERENT HOMEPAGE VIEW
444
         the setting homepage_view is adjustable through
445
         the platform administration section */
446
        if (!empty($autoLaunchWarning)) {
447
            $this->addFlash(
448
                'warning',
449
                Display::return_message(
450
                    $autoLaunchWarning,
451
                    'warning'
452
                )
453
            );
454
        }
455
    }
456
}
457