Completed
Push — master ( 792ce7...e487ad )
by Julito
21:06 queued 10s
created

CourseHomeController   F

Complexity

Total Complexity 62

Size/Duplication

Total Lines 416
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 241
c 2
b 0
f 0
dl 0
loc 416
rs 3.44
wmc 62

4 Methods

Rating   Name   Duplication   Size   Complexity  
A updateAction() 0 49 4
F indexAction() 0 161 25
A redirectTool() 0 14 2
F autoLaunch() 0 158 31

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
/* For licensing terms, see /license.txt */
3
4
namespace Chamilo\CoreBundle\Controller;
5
6
use Chamilo\CoreBundle\Entity\Course;
7
use Chamilo\CoreBundle\ToolChain;
8
use Chamilo\CourseBundle\Controller\ToolBaseController;
9
use Chamilo\CourseBundle\Entity\CTool;
10
use Chamilo\CourseBundle\Manager\SettingsManager;
11
use Chamilo\CourseBundle\Repository\CToolRepository;
12
use Chamilosession as Session;
13
use CourseManager;
14
use Database;
15
use Display;
16
use Event;
17
use ExtraFieldValue;
18
use Security;
19
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Entity;
20
use Sylius\Bundle\SettingsBundle\Form\Factory\SettingsFormFactory;
21
use Symfony\Component\HttpFoundation\Request;
22
use Symfony\Component\HttpFoundation\Response;
23
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
24
use Symfony\Component\Routing\Annotation\Route;
25
use Symfony\Component\Validator\Exception\ValidatorException;
26
27
/**
28
 * Class CourseHomeController.
29
 *
30
 * @author Julio Montoya <[email protected]>
31
 *
32
 * @Route("/course")
33
 */
34
class CourseHomeController extends ToolBaseController
35
{
36
    /**
37
     * @Route("/{cid}/home", name="chamilo_core_course_home")
38
     *
39
     * @Entity("course", expr="repository.find(cid)")
40
     */
41
    public function indexAction(Request $request, CToolRepository $toolRepository, ToolChain $toolChain)
42
    {
43
        $this->autoLaunch();
44
        $course = $this->getCourse();
45
46
        $js = '<script>'.api_get_language_translate_html().'</script>';
47
        $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...
48
49
        $userId = $this->getUser()->getId();
50
        $courseCode = $course->getCode();
51
        $courseId = $course->getId();
52
        $sessionId = $this->getSessionId();
53
54
        if (api_is_invitee()) {
55
            $isInASession = $sessionId > 0;
56
            $isSubscribed = CourseManager::is_user_subscribed_in_course(
57
                $userId,
58
                $courseCode,
59
                $isInASession,
60
                $sessionId
61
            );
62
63
            if (!$isSubscribed) {
64
                api_not_allowed(true);
65
            }
66
        }
67
68
        // Deleting group session
69
        Session::erase('toolgroup');
70
        Session::erase('_gid');
71
72
        $isSpecialCourse = CourseManager::isSpecialCourse($courseId);
73
74
        if ($isSpecialCourse) {
75
            if (isset($_GET['autoreg']) && $_GET['autoreg'] == 1) {
76
                if (CourseManager::subscribeUser($userId, $courseCode, STUDENT)) {
77
                    Session::write('is_allowed_in_course', true);
78
                }
79
            }
80
        }
81
82
        $action = !empty($_GET['action']) ? Security::remove_XSS($_GET['action']) : '';
83
        if ($action == 'subscribe') {
84
            if (Security::check_token('get')) {
85
                Security::clear_token();
86
                $result = CourseManager::autoSubscribeToCourse($courseCode);
87
                if ($result) {
88
                    if (CourseManager::is_user_subscribed_in_course($userId, $courseCode)) {
89
                        Session::write('is_allowed_in_course', true);
90
                    }
91
                }
92
                header('Location: '.api_get_self());
93
                exit;
94
            }
95
        }
96
97
        /*  STATISTICS */
98
        if (!isset($coursesAlreadyVisited[$courseCode])) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $coursesAlreadyVisited does not exist. Did you maybe mean $course?
Loading history...
99
            Event::accessCourse();
100
            $coursesAlreadyVisited[$courseCode] = 1;
0 ignored issues
show
Comprehensibility Best Practice introduced by
$coursesAlreadyVisited was never initialized. Although not strictly required by PHP, it is generally a good practice to add $coursesAlreadyVisited = array(); before regardless.
Loading history...
101
            Session::write('coursesAlreadyVisited', $coursesAlreadyVisited);
102
        }
103
104
        $logInfo = [
105
            'tool' => 'course-main',
106
            'action' => $action,
107
        ];
108
        Event::registerLog($logInfo);
109
110
        /*	Introduction section (editable by course admins) */
111
        /*$introduction = Display::return_introduction_section(
112
            TOOL_COURSE_HOMEPAGE,
113
            [
114
                'CreateDocumentWebDir' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/',
115
                'CreateDocumentDir' => 'document/',
116
                'BaseHref' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/',
117
            ]
118
        );*/
119
120
        $qb = $toolRepository->getResourcesByCourse($course, $this->getSession());
121
        $result = $qb->getQuery()->getResult();
122
123
        $tools = [];
124
        /** @var CTool $item */
125
        foreach ($result as $item) {
126
            $toolModel = $toolChain->getToolFromName($item->getTool()->getName());
127
128
            if ($toolModel->getCategory() === 'admin' && !$this->isGranted('ROLE_CURRENT_COURSE_TEACHER')) {
129
                continue;
130
            }
131
            $tools[$item->getCategory()][] = $item;
132
        }
133
134
        // Get session-career diagram
135
        $diagram = '';
136
        $allow = api_get_configuration_value('allow_career_diagram');
137
        if ($allow === true) {
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();
0 ignored issues
show
Bug introduced by
The type Chamilo\CoreBundle\Controller\Career was not found. Did you mean Career? If so, make sure to prefix the type with \.
Loading history...
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
                            false
168
                        );
169
170
                        if (!empty($item) && isset($item['value']) && !empty($item['value'])) {
171
                            /** @var Graph $graph */
172
                            $graph = UnserializeApi::unserialize(
0 ignored issues
show
Bug introduced by
The type Chamilo\CoreBundle\Controller\UnserializeApi was not found. Did you mean UnserializeApi? If so, make sure to prefix the type with \.
Loading history...
173
                                'career',
174
                                $item['value']
175
                            );
176
                            $diagram = Career::renderDiagram($careerInfo, $graph);
177
                        }
178
                    }
179
                }
180
            }
181
        }
182
183
        // Deleting the objects
184
        Session::erase('_gid');
185
        Session::erase('oLP');
186
        Session::erase('lpobject');
187
        api_remove_in_gradebook();
188
        \Exercise::cleanSessionVariables();
189
        \DocumentManager::removeGeneratedAudioTempFile();
190
191
        return $this->render(
192
            '@ChamiloTheme/Course/home.html.twig',
193
            [
194
                'course' => $course,
195
                'diagram' => $diagram,
196
               // 'session_info' => $sessionInfo,
197
                'tools' => $tools,
198
                //'edit_icons' => $editIcons,
199
                //'introduction_text' => $introduction,
200
                'exercise_warning' => null,
201
                'lp_warning' => null,
202
            ]
203
        );
204
    }
205
206
    /**
207
     * @Route("/{cid}/tool/{toolId}", name="chamilo_core_course_redirect_tool")
208
     */
209
    public function redirectTool($toolId, ToolChain $toolChain)
210
    {
211
        $criteria = ['id' => $toolId];
212
        /** @var CTool $tool */
213
        $tool = $this->getDoctrine()->getRepository('Chamilo\CourseBundle\Entity\CTool')->findOneBy($criteria);
214
215
        if (null === $tool) {
216
            throw new NotFoundHttpException($this->trans('Tool not found'));
217
        }
218
219
        $tool = $toolChain->getToolFromName($tool->getTool()->getName());
220
        $url = $tool->getLink().'?'.$this->getCourseUrlQuery();
221
222
        return $this->redirect($url);
223
    }
224
225
    /**
226
     * @return array
227
     */
228
    private function autoLaunch()
229
    {
230
        /* Auto launch code */
231
        $autoLaunchWarning = '';
232
        $showAutoLaunchLpWarning = false;
233
        $course_id = api_get_course_int_id();
234
        $lpAutoLaunch = api_get_course_setting('enable_lp_auto_launch');
235
        $session_id = api_get_session_id();
236
        $allowAutoLaunchForCourseAdmins = api_is_platform_admin() || api_is_allowed_to_edit(true, true) || api_is_coach();
237
238
        if (!empty($lpAutoLaunch)) {
239
            if ($lpAutoLaunch == 2) {
240
                // LP list
241
                if ($allowAutoLaunchForCourseAdmins) {
242
                    $showAutoLaunchLpWarning = true;
243
                } else {
244
                    $session_key = 'lp_autolaunch_'.$session_id.'_'.api_get_course_int_id().'_'.api_get_user_id();
245
                    if (!isset($_SESSION[$session_key])) {
246
                        // Redirecting to the LP
247
                        $url = api_get_path(WEB_CODE_PATH).'lp/lp_controller.php?'.api_get_cidreq();
248
                        $_SESSION[$session_key] = true;
249
                        header("Location: $url");
250
                        exit;
251
                    }
252
                }
253
            } else {
254
                $lp_table = Database::get_course_table(TABLE_LP_MAIN);
255
                $condition = '';
256
                if (!empty($session_id)) {
257
                    $condition = api_get_session_condition($session_id);
258
                    $sql = "SELECT id FROM $lp_table
259
                            WHERE c_id = $course_id AND autolaunch = 1 $condition
260
                            LIMIT 1";
261
                    $result = Database::query($sql);
262
                    // If we found nothing in the session we just called the session_id =  0 autolaunch
263
                    if (Database::num_rows($result) == 0) {
264
                        $condition = '';
265
                    }
266
                }
267
268
                $sql = "SELECT id FROM $lp_table
269
                        WHERE c_id = $course_id AND autolaunch = 1 $condition
270
                        LIMIT 1";
271
                $result = Database::query($sql);
272
                if (Database::num_rows($result) > 0) {
273
                    $lp_data = Database::fetch_array($result, 'ASSOC');
274
                    if (!empty($lp_data['id'])) {
275
                        if ($allowAutoLaunchForCourseAdmins) {
276
                            $showAutoLaunchLpWarning = true;
277
                        } else {
278
                            $session_key = 'lp_autolaunch_'.$session_id.'_'.api_get_course_int_id().'_'.api_get_user_id();
279
                            if (!isset($_SESSION[$session_key])) {
280
                                // Redirecting to the LP
281
                                $url = api_get_path(WEB_CODE_PATH).'lp/lp_controller.php?'.api_get_cidreq().'&action=view&lp_id='.$lp_data['id'];
282
283
                                $_SESSION[$session_key] = true;
284
                                header("Location: $url");
285
                                exit;
286
                            }
287
                        }
288
                    }
289
                }
290
            }
291
        }
292
293
        if ($showAutoLaunchLpWarning) {
294
            $autoLaunchWarning = get_lang('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.');
295
        }
296
297
        $forumAutoLaunch = api_get_course_setting('enable_forum_auto_launch');
298
        if ($forumAutoLaunch == 1) {
299
            if ($allowAutoLaunchForCourseAdmins) {
300
                if (empty($autoLaunchWarning)) {
301
                    $autoLaunchWarning = get_lang('The forum\'s auto-launch setting is on. Students will be redirected to the forum tool when entering this course.');
302
                }
303
            } else {
304
                $url = api_get_path(WEB_CODE_PATH).'forum/index.php?'.api_get_cidreq();
305
                header("Location: $url");
306
                exit;
307
            }
308
        }
309
310
        if (api_get_configuration_value('allow_exercise_auto_launch')) {
311
            $exerciseAutoLaunch = (int) api_get_course_setting('enable_exercise_auto_launch');
312
            if ($exerciseAutoLaunch == 2) {
313
                if ($allowAutoLaunchForCourseAdmins) {
314
                    if (empty($autoLaunchWarning)) {
315
                        $autoLaunchWarning = get_lang(
316
                            'TheExerciseAutoLaunchSettingIsONStudentsWillBeRedirectToTheExerciseList'
317
                        );
318
                    }
319
                } else {
320
                    // Redirecting to the document
321
                    $url = api_get_path(WEB_CODE_PATH).'exercise/exercise.php?'.api_get_cidreq();
322
                    header("Location: $url");
323
                    exit;
324
                }
325
            } elseif ($exerciseAutoLaunch == 1) {
326
                if ($allowAutoLaunchForCourseAdmins) {
327
                    if (empty($autoLaunchWarning)) {
328
                        $autoLaunchWarning = get_lang(
329
                            'TheExerciseAutoLaunchSettingIsONStudentsWillBeRedirectToAnSpecificExercise'
330
                        );
331
                    }
332
                } else {
333
                    // Redirecting to an exercise
334
                    $table = Database::get_course_table(TABLE_QUIZ_TEST);
335
                    $condition = '';
336
                    if (!empty($session_id)) {
337
                        $condition = api_get_session_condition($session_id);
338
                        $sql = "SELECT iid FROM $table
339
                        WHERE c_id = $course_id AND autolaunch = 1 $condition
340
                        LIMIT 1";
341
                        $result = Database::query($sql);
342
                        // If we found nothing in the session we just called the session_id = 0 autolaunch
343
                        if (Database::num_rows($result) == 0) {
344
                            $condition = '';
345
                        }
346
                    }
347
348
                    $sql = "SELECT iid FROM $table
349
                    WHERE c_id = $course_id AND autolaunch = 1 $condition
350
                    LIMIT 1";
351
                    $result = Database::query($sql);
352
                    if (Database::num_rows($result) > 0) {
353
                        $row = Database::fetch_array($result, 'ASSOC');
354
                        $exerciseId = $row['iid'];
355
                        $url = api_get_path(WEB_CODE_PATH).
356
                            'exercise/overview.php?exerciseId='.$exerciseId.'&'.api_get_cidreq();
357
                        header("Location: $url");
358
                        exit;
359
                    }
360
                }
361
            }
362
        }
363
364
        $documentAutoLaunch = api_get_course_setting('enable_document_auto_launch');
365
        if ($documentAutoLaunch == 1) {
366
            if ($allowAutoLaunchForCourseAdmins) {
367
                if (empty($autoLaunchWarning)) {
368
                    $autoLaunchWarning = get_lang('The document auto-launch feature configuration is enabled. Learners will be automatically redirected to document tool.');
369
                }
370
            } else {
371
                // Redirecting to the document
372
                $url = api_get_path(WEB_CODE_PATH).'document/document.php?'.api_get_cidreq();
373
                header("Location: $url");
374
                exit;
375
            }
376
        }
377
378
        /*	SWITCH TO A DIFFERENT HOMEPAGE VIEW
379
         the setting homepage_view is adjustable through
380
         the platform administration section */
381
        if (!empty($autoLaunchWarning)) {
382
            $this->addFlash(
383
            Display::return_message(
384
                $autoLaunchWarning,
385
                'warning'
386
            ));
387
        }
388
    }
389
390
    /**
391
     * Edit configuration with given namespace.
392
     *
393
     * @param string $namespace
394
     * @Route("/{cid}/settings/{namespace}", name="chamilo_core_course_settings")
395
396
     * @Entity("course", expr="repository.find(cid)")
397
     *
398
     *
399
     * @return Response
400
     */
401
    public function updateAction(Request $request, Course $course, $namespace, SettingsManager $manager, SettingsFormFactory $formFactory)
402
    {
403
        $schemaAlias = $manager->convertNameSpaceToService($namespace);
404
        $settings = $manager->load($namespace);
405
        $form = $formFactory->create($schemaAlias);
406
407
        $form->setData($settings);
408
409
        if ($form->handleRequest($request)->isValid()) {
410
            $messageType = 'success';
411
            try {
412
                $manager->setCourse($course);
413
                $manager->saveSettings($namespace, $form->getData());
414
                $message = $this->trans(
415
                    'sylius.settings.update',
416
                    [],
417
                    'flashes'
418
                );
419
            } catch (ValidatorException $exception) {
420
                $message = $this->trans(
421
                    $exception->getMessage(),
422
                    [],
423
                    'validators'
424
                );
425
                $messageType = 'error';
426
            }
427
            $request->getSession()->getBag('flashes')->add(
428
                $messageType,
429
                $message
430
            );
431
432
            if ($request->headers->has('referer')) {
433
                return $this->redirect($request->headers->get('referer'));
434
            }
435
        }
436
        $schemas = $manager->getSchemas();
437
438
        return $this->render(
439
            $request->attributes->get(
440
                'template',
441
                'ChamiloCourseBundle:Settings:update.html.twig'
442
            ),
443
            [
444
                'course' => $course,
445
                'schemas' => $schemas,
446
                'settings' => $settings,
447
                'form' => $form->createView(),
448
                'keyword' => '',
449
                'search_form' => '',
450
            ]
451
        );
452
    }
453
454
455
}
456