Completed
Push — master ( 0614a5...805611 )
by Julito
14:30
created

CourseHomeController   F

Complexity

Total Complexity 133

Size/Duplication

Total Lines 953
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 541
c 0
b 0
f 0
dl 0
loc 953
rs 2
wmc 133

11 Methods

Rating   Name   Duplication   Size   Complexity  
F indexAction() 0 372 64
B addIconAction() 0 54 6
A return_block() 0 10 1
A deleteIcon() 0 14 2
A iconListAction() 0 50 4
A hideIconAction() 0 17 3
D renderActivityView() 0 148 19
D autoLaunch() 0 132 25
A showIconAction() 0 13 2
A deleteIconAction() 0 25 3
A editIconAction() 0 36 4

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\CourseBundle\Controller\ToolBaseController;
7
use Chamilo\CourseBundle\Entity\CTool;
8
use Chamilosession as Session;
9
use CourseHome;
10
use CourseManager;
11
use Database;
12
use Display;
13
use Event;
14
use ExtraFieldValue;
15
use Security;
16
use Symfony\Component\HttpFoundation\Request;
17
use Symfony\Component\HttpFoundation\Response;
18
use Symfony\Component\Routing\Annotation\Route;
19
20
/**
21
 * Class CourseHomeController.
22
 *
23
 * @author Julio Montoya <[email protected]>
24
 *
25
 * @Route("/sad")
26
 */
27
class CourseHomeController extends ToolBaseController
28
{
29
    /**
30
     * Route("/", name="course_home")
31
     * Route("/index.php", methods={"GET"})
32
     *
33
     * @return Response
34
     */
35
    public function indexAction(Request $request)
36
    {
37
        $course = $this->getCourse();
38
        $result = $this->autoLaunch();
39
        $js = '<script>'.api_get_language_translate_html().'</script>';
40
        $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...
41
42
        $user_id = api_get_user_id();
43
        $courseCode = $course->getCode();
44
        $courseId = $course->getId();
45
        $sessionId = $this->getSessionId();
46
        $show_message = '';
47
48
        if (api_is_invitee()) {
49
            $isInASession = $sessionId > 0;
50
            $isSubscribed = CourseManager::is_user_subscribed_in_course(
51
                $user_id,
52
                $courseCode,
53
                $isInASession,
54
                $sessionId
55
            );
56
57
            if (!$isSubscribed) {
58
                api_not_allowed(true);
59
            }
60
        }
61
62
        // Deleting group session
63
        Session::erase('toolgroup');
64
        Session::erase('_gid');
65
66
        $isSpecialCourse = CourseManager::isSpecialCourse($courseId);
67
68
        if ($isSpecialCourse) {
69
            if (isset($_GET['autoreg']) && $_GET['autoreg'] == 1) {
70
                if (CourseManager::subscribeUser($user_id, $courseCode, STUDENT)) {
71
                    Session::write('is_allowed_in_course', true);
72
                }
73
            }
74
        }
75
76
        $action = !empty($_GET['action']) ? Security::remove_XSS($_GET['action']) : '';
77
78
        if ($action == 'subscribe') {
79
            if (Security::check_token('get')) {
80
                Security::clear_token();
81
                $result = CourseManager::autoSubscribeToCourse($courseCode);
82
                if ($result) {
83
                    if (CourseManager::is_user_subscribed_in_course($user_id, $courseCode)) {
84
                        Session::write('is_allowed_in_course', true);
85
                    }
86
                }
87
                header('Location: '.api_get_self());
88
                exit;
89
            }
90
        }
91
92
        /*	Is the user allowed here? */
93
        api_protect_course_script(true);
94
95
        /*  STATISTICS */
96
        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...
97
            Event::accessCourse();
98
            $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...
99
            Session::write('coursesAlreadyVisited', $coursesAlreadyVisited);
100
        }
101
102
        $logInfo = [
103
            'tool' => 'course-main',
104
            'action' => $action,
105
        ];
106
        Event::registerLog($logInfo);
107
108
        /* Auto launch code */
109
        $autoLaunchWarning = '';
110
        $showAutoLaunchLpWarning = false;
111
        $course_id = api_get_course_int_id();
112
        $lpAutoLaunch = api_get_course_setting('enable_lp_auto_launch');
113
        $session_id = api_get_session_id();
114
        $allowAutoLaunchForCourseAdmins = api_is_platform_admin() || api_is_allowed_to_edit(true, true) || api_is_coach();
115
116
        if (!empty($lpAutoLaunch)) {
117
            if ($lpAutoLaunch == 2) {
118
                // LP list
119
                if ($allowAutoLaunchForCourseAdmins) {
120
                    $showAutoLaunchLpWarning = true;
121
                } else {
122
                    $session_key = 'lp_autolaunch_'.$session_id.'_'.api_get_course_int_id().'_'.api_get_user_id();
123
                    if (!isset($_SESSION[$session_key])) {
124
                        // Redirecting to the LP
125
                        $url = api_get_path(WEB_CODE_PATH).'lp/lp_controller.php?'.api_get_cidreq();
126
                        $_SESSION[$session_key] = true;
127
                        header("Location: $url");
128
                        exit;
129
                    }
130
                }
131
            } else {
132
                $lp_table = Database::get_course_table(TABLE_LP_MAIN);
133
                $condition = '';
134
                if (!empty($session_id)) {
135
                    $condition = api_get_session_condition($session_id);
136
                    $sql = "SELECT id FROM $lp_table
137
                    WHERE c_id = $course_id AND autolaunch = 1 $condition
138
                    LIMIT 1";
139
                    $result = Database::query($sql);
140
                    // If we found nothing in the session we just called the session_id =  0 autolaunch
141
                    if (Database::num_rows($result) == 0) {
142
                        $condition = '';
143
                    }
144
                }
145
146
                $sql = "SELECT id FROM $lp_table
147
                WHERE c_id = $course_id AND autolaunch = 1 $condition
148
                LIMIT 1";
149
                $result = Database::query($sql);
150
                if (Database::num_rows($result) > 0) {
151
                    $lp_data = Database::fetch_array($result, 'ASSOC');
152
                    if (!empty($lp_data['id'])) {
153
                        if ($allowAutoLaunchForCourseAdmins) {
154
                            $showAutoLaunchLpWarning = true;
155
                        } else {
156
                            $session_key = 'lp_autolaunch_'.$session_id.'_'.api_get_course_int_id().'_'.api_get_user_id();
157
                            if (!isset($_SESSION[$session_key])) {
158
                                // Redirecting to the LP
159
                                $url = api_get_path(WEB_CODE_PATH).'lp/lp_controller.php?'.api_get_cidreq().'&action=view&lp_id='.$lp_data['id'];
160
161
                                $_SESSION[$session_key] = true;
162
                                header("Location: $url");
163
                                exit;
164
                            }
165
                        }
166
                    }
167
                }
168
            }
169
        }
170
171
        if ($showAutoLaunchLpWarning) {
172
            $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.');
173
        }
174
175
        $forumAutoLaunch = api_get_course_setting('enable_forum_auto_launch');
176
        if ($forumAutoLaunch == 1) {
177
            if ($allowAutoLaunchForCourseAdmins) {
178
                if (empty($autoLaunchWarning)) {
179
                    $autoLaunchWarning = get_lang('The forum\'s auto-launch setting is on. Students will be redirected to the forum tool when entering this course.');
180
                }
181
            } else {
182
                $url = api_get_path(WEB_CODE_PATH).'forum/index.php?'.api_get_cidreq();
183
                header("Location: $url");
184
                exit;
185
            }
186
        }
187
188
        if (api_get_configuration_value('allow_exercise_auto_launch')) {
189
            $exerciseAutoLaunch = (int) api_get_course_setting('enable_exercise_auto_launch');
190
            if ($exerciseAutoLaunch == 2) {
191
                if ($allowAutoLaunchForCourseAdmins) {
192
                    if (empty($autoLaunchWarning)) {
193
                        $autoLaunchWarning = get_lang(
194
                            'TheExerciseAutoLaunchSettingIsONStudentsWillBeRedirectToTheExerciseList'
195
                        );
196
                    }
197
                } else {
198
                    // Redirecting to the document
199
                    $url = api_get_path(WEB_CODE_PATH).'exercise/exercise.php?'.api_get_cidreq();
200
                    header("Location: $url");
201
                    exit;
202
                }
203
            } elseif ($exerciseAutoLaunch == 1) {
204
                if ($allowAutoLaunchForCourseAdmins) {
205
                    if (empty($autoLaunchWarning)) {
206
                        $autoLaunchWarning = get_lang(
207
                            'TheExerciseAutoLaunchSettingIsONStudentsWillBeRedirectToAnSpecificExercise'
208
                        );
209
                    }
210
                } else {
211
                    // Redirecting to an exercise
212
                    $table = Database::get_course_table(TABLE_QUIZ_TEST);
213
                    $condition = '';
214
                    if (!empty($session_id)) {
215
                        $condition = api_get_session_condition($session_id);
216
                        $sql = "SELECT iid FROM $table
217
                        WHERE c_id = $course_id AND autolaunch = 1 $condition
218
                        LIMIT 1";
219
                        $result = Database::query($sql);
220
                        // If we found nothing in the session we just called the session_id = 0 autolaunch
221
                        if (Database::num_rows($result) == 0) {
222
                            $condition = '';
223
                        }
224
                    }
225
226
                    $sql = "SELECT iid FROM $table
227
                    WHERE c_id = $course_id AND autolaunch = 1 $condition
228
                    LIMIT 1";
229
                    $result = Database::query($sql);
230
                    if (Database::num_rows($result) > 0) {
231
                        $row = Database::fetch_array($result, 'ASSOC');
232
                        $exerciseId = $row['iid'];
233
                        $url = api_get_path(WEB_CODE_PATH).
234
                            'exercise/overview.php?exerciseId='.$exerciseId.'&'.api_get_cidreq();
235
                        header("Location: $url");
236
                        exit;
237
                    }
238
                }
239
            }
240
        }
241
242
        $documentAutoLaunch = api_get_course_setting('enable_document_auto_launch');
243
        if ($documentAutoLaunch == 1) {
244
            if ($allowAutoLaunchForCourseAdmins) {
245
                if (empty($autoLaunchWarning)) {
246
                    $autoLaunchWarning = get_lang('The document auto-launch feature configuration is enabled. Learners will be automatically redirected to document tool.');
247
                }
248
            } else {
249
                // Redirecting to the document
250
                $url = api_get_path(WEB_CODE_PATH).'document/document.php?'.api_get_cidreq();
251
                header("Location: $url");
252
                exit;
253
            }
254
        }
255
256
        // Used in different pages
257
        $tool_table = Database::get_course_table(TABLE_TOOL_LIST);
258
259
        /*	Introduction section (editable by course admins) */
260
        $content = Display::return_introduction_section(
261
            TOOL_COURSE_HOMEPAGE,
262
            [
263
                'CreateDocumentWebDir' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/',
264
                'CreateDocumentDir' => 'document/',
265
                'BaseHref' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/',
266
            ]
267
        );
268
269
        /*	SWITCH TO A DIFFERENT HOMEPAGE VIEW
270
            the setting homepage_view is adjustable through
271
            the platform administration section */
272
        if (!empty($autoLaunchWarning)) {
273
            $show_message .= Display::return_message(
274
                $autoLaunchWarning,
275
                'warning'
276
            );
277
        }
278
279
        //require 'activity.php';
280
        // Activity start
281
        $id = isset($_GET['id']) ? (int) $_GET['id'] : null;
282
        $course_id = api_get_course_int_id();
283
        $session_id = api_get_session_id();
284
285
        // Work with data post askable by admin of course
286
        if (api_is_platform_admin()) {
287
            // Show message to confirm that a tool it to be hidden from available tools
288
            // visibility 0,1->2
289
            if (!empty($_GET['askDelete'])) {
290
                $content .= '<div id="toolhide">'.get_lang('Do you really want to delete this link?').'<br />&nbsp;&nbsp;&nbsp;
291
            <a href="'.api_get_self().'">'.get_lang('No').'</a>&nbsp;|&nbsp;
292
            <a href="'.api_get_self().'?delete=yes&id='.$id.'">'.get_lang('Yes').'</a>
293
        </div>';
294
            } elseif (isset($_GET['delete']) && $_GET['delete']) {
295
                /*
296
                * Process hiding a tools from available tools.
297
                */
298
                Database::query("DELETE FROM $tool_table WHERE c_id = $course_id AND id='$id' AND added_tool=1");
299
            }
300
        }
301
302
        // Course legal
303
        $enabled = api_get_plugin_setting('courselegal', 'tool_enable');
304
        $pluginExtra = null;
305
        if ($enabled === 'true') {
306
            require_once api_get_path(SYS_PLUGIN_PATH).'courselegal/config.php';
307
            $plugin = \CourseLegalPlugin::create();
308
            $pluginExtra = $plugin->getTeacherLink();
309
        }
310
311
        // Start of tools for CourseAdmins (teachers/tutors)
312
        if ($session_id === 0 && api_is_course_admin() && api_is_allowed_to_edit(null, true)) {
313
            $content .= '<div class="alert alert-success" style="border:0px; margin-top: 0px;padding:0px;">
314
		<div class="normal-message" id="id_normal_message" style="display:none">';
315
            $content .= '<img src="'.api_get_path(WEB_PATH).'main/inc/lib/javascript/indicator.gif"/>&nbsp;&nbsp;';
316
            $content .= get_lang('Please stand by...');
317
            $content .= '</div>
318
		<div class="alert alert-success" id="id_confirmation_message" style="display:none"></div>
319
	</div>';
320
            $content .= $pluginExtra;
321
        } elseif (api_is_coach()) {
322
            $content .= $pluginExtra;
323
            if (api_get_setting('show_session_data') === 'true' && $session_id > 0) {
324
                $content .= '<div class="row">
325
            <div class="col-xs-12 col-md-12">
326
			<span class="viewcaption">'.get_lang('Session\'s data').'</span>
327
			<table class="course_activity_home">';
328
                $content .= CourseHome::show_session_data($session_id);
329
                $content .= '</table></div></div>';
330
            }
331
        }
332
333
        $blocks = CourseHome::getUserBlocks();
334
        // Activity end
335
336
        // Get session-career diagram
337
        $diagram = '';
338
        $allow = api_get_configuration_value('allow_career_diagram');
339
        if ($allow === true) {
340
            $htmlHeadXtra[] = api_get_js('jsplumb2.js');
341
            $extra = new ExtraFieldValue('session');
342
            $value = $extra->get_values_by_handler_and_field_variable(
343
                api_get_session_id(),
344
                'external_career_id'
345
            );
346
347
            if (!empty($value) && isset($value['value'])) {
348
                $careerId = $value['value'];
349
                $extraFieldValue = new ExtraFieldValue('career');
350
                $item = $extraFieldValue->get_item_id_from_field_variable_and_field_value(
351
                    'external_career_id',
352
                    $careerId,
353
                    false,
354
                    false,
355
                    false
356
                );
357
358
                if (!empty($item) && isset($item['item_id'])) {
359
                    $careerId = $item['item_id'];
360
                    $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...
361
                    $careerInfo = $career->get($careerId);
362
                    if (!empty($careerInfo)) {
363
                        $extraFieldValue = new ExtraFieldValue('career');
364
                        $item = $extraFieldValue->get_values_by_handler_and_field_variable(
365
                            $careerId,
366
                            'career_diagram',
367
                            false,
368
                            false,
369
                            false
370
                        );
371
372
                        if (!empty($item) && isset($item['value']) && !empty($item['value'])) {
373
                            /** @var Graph $graph */
374
                            $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...
375
                                'career',
376
                                $item['value']
377
                            );
378
                            $diagram = Career::renderDiagram($careerInfo, $graph);
379
                        }
380
                    }
381
                }
382
            }
383
        }
384
385
        $content = '<div id="course_tools">'.$diagram.$content.'</div>';
386
387
        // Deleting the objects
388
        Session::erase('_gid');
389
        Session::erase('oLP');
390
        Session::erase('lpobject');
391
        api_remove_in_gradebook();
392
        \Exercise::cleanSessionVariables();
393
        \DocumentManager::removeGeneratedAudioTempFile();
394
395
        return $this->render(
396
            '@ChamiloTheme/Course/home.html.twig',
397
            [
398
                'course' => $course,
399
                'diagram' => $diagram,
400
               // 'session_info' => $sessionInfo,
401
                'icons' => $result['content'],
402
                'blocks' => $blocks,
403
                //'edit_icons' => $editIcons,
404
                //'introduction_text' => $introduction,
405
                'exercise_warning' => null,
406
                'lp_warning' => null,
407
            ]
408
        );
409
    }
410
411
    /**
412
     * @Route("/show/{iconId}", methods={"GET"})
413
     *
414
     * @param $iconId
415
     *
416
     * @return string|null
417
     */
418
    public function showIconAction($iconId)
419
    {
420
        $entityManager = $this->getDoctrine()->getManager();
421
        $criteria = ['cId' => api_get_course_int_id(), 'id' => $iconId];
422
        $tool = $this->getRepository(
423
            'Chamilo\CourseBundle\Entity\CTool'
424
        )->findOneBy($criteria);
425
        if ($tool) {
426
            $tool->setVisibility(1);
427
        }
428
        $entityManager->persist($tool);
429
        //$entityManager->flush();
430
        return Display::return_message(get_lang('Visible'), 'confirmation');
431
    }
432
433
    /**
434
     * @Route("/hide/{iconId}", methods={"GET"})
435
     *
436
     * @param $iconId
437
     *
438
     * @return string|null
439
     */
440
    public function hideIconAction($iconId)
441
    {
442
        if (!$this->isCourseTeacher()) {
443
            return $this->abort(404);
444
        }
445
446
        $entityManager = $this->getDoctrine()->getManager();
447
        $criteria = ['cId' => api_get_course_int_id(), 'id' => $iconId];
448
        $tool = $this->getRepository(
449
            'Chamilo\CourseBundle\Entity\CTool'
450
        )->findOneBy($criteria);
451
        if ($tool) {
452
            $tool->setVisibility(0);
453
        }
454
        $entityManager->persist($tool);
455
        //$entityManager->flush();
456
        return Display::return_message(get_lang('The tool is now invisible.'), 'confirmation');
457
    }
458
459
    /**
460
     * @Route("/delete/{iconId}", methods={"GET"})
461
     *
462
     * @param $iconId
463
     *
464
     * @return string|null
465
     */
466
    public function deleteIcon($iconId)
467
    {
468
        if (!$this->isCourseTeacher()) {
469
            return $this->abort(404);
470
        }
471
472
        $entityManager = $this->getDoctrine()->getManager();
473
        $criteria = ['cId' => api_get_course_int_id(), 'id' => $iconId, 'added_tool' => 1];
474
        $tool = $this->getRepository(
475
            'Chamilo\CourseBundle\Entity\CTool'
476
        )->findOneBy($criteria);
477
        $entityManager->remove($tool);
478
        //$entityManager->flush();
479
        return Display::return_message(get_lang('Deleted'), 'confirmation');
480
    }
481
482
    /**
483
     * @Route("/icon_list", methods={"GET"})
484
     */
485
    public function iconListAction(Request $request)
486
    {
487
        $em = $this->getDoctrine()->getManager();
488
        $repo = $this->getDoctrine()->getRepository('ChamiloCourseBundle:CTool');
489
490
        $sessionId = intval($request->get('id_session'));
491
        $itemsFromSession = [];
492
        if (!empty($sessionId)) {
493
            $query = $repo->createQueryBuilder('a');
494
            $query->select('s');
495
            $query->from('Chamilo\CourseBundle\Entity\CTool', 's');
496
            $query->where('s.cId  = :courseId AND s.sessionId = :sessionId')
497
                ->setParameters(
498
                    [
499
                        'course' => $this->getCourse()->getId(),
500
                        'sessionId' => $sessionId,
501
                    ]
502
                );
503
            $itemsFromSession = $query->getQuery()->getResult();
504
505
            $itemNameList = [];
506
            foreach ($itemsFromSession as $item) {
507
                $itemNameList[] = $item->getName();
508
            }
509
510
            //$itemsFromSession = $this->getRepository()->findBy($criteria);
511
            $query = $repo->createQueryBuilder('a');
512
            $query->select('s');
513
            $query->from('Chamilo\CourseBundle\Entity\CTool', 's');
514
            $query->where('s.cId  = :courseId AND s.sessionId = 0')
515
                ->setParameters(
516
                    [
517
                        'courseId' => $this->getCourse()->getId(),
518
                    ]
519
                );
520
            if (!empty($itemNameList)) {
521
                $query->andWhere($query->expr()->notIn('s.name', $itemNameList));
522
            }
523
            $itemsFromCourse = $query->getQuery()->getResult();
524
        } else {
525
            $criteria = ['cId' => $this->getCourse()->getId(), 'sessionId' => 0];
526
            $itemsFromCourse = $repo->findBy($criteria);
527
        }
528
529
        return $this->render(
530
            '@ChamiloCourse/Home/list.html.twig',
531
            [
532
                'items_from_course' => $itemsFromCourse,
533
                'items_from_session' => $itemsFromSession,
534
                'links' => '',
535
            ]
536
        );
537
    }
538
539
    /**
540
     * @Route("/{itemName}/add", methods={"GET", "POST"})
541
     *
542
     * @param $itemName
543
     *
544
     * @return mixed
545
     */
546
    public function addIconAction($itemName)
547
    {
548
        if (!$this->isCourseTeacher()) {
549
            return $this->abort(404);
550
        }
551
552
        $sessionId = intval($this->getRequest()->get('id_session'));
553
554
        if (empty($sessionId)) {
555
            return $this->abort(500);
556
        }
557
558
        $criteria = ['cId' => $this->getCourse()->getId(), 'sessionId' => 0, 'name' => $itemName];
559
        $itemFromDatabase = $this->getRepository()->findOneBy($criteria);
560
561
        if (!$itemFromDatabase) {
562
            $this->createNotFoundException();
563
        }
564
        /** @var CTool $item */
565
        $item = clone $itemFromDatabase;
566
        $item->setId(null);
567
        $item->setSessionId($sessionId);
568
        $form = $this->createForm($this->getFormType(), $item);
569
570
        $form->handleRequest($this->getRequest());
571
572
        if ($form->isValid()) {
573
            $query = $this->getDoctrine()->getManager()->createQueryBuilder('a');
574
            $query->select('MAX(s.id) as id');
575
            $query->from('Chamilo\CourseBundle\Entity\CTool', 's');
576
            $query->where('s.cId  = :courseId')->setParameter('courseId', $this->getCourse()->getId());
577
            $result = $query->getQuery()->getArrayResult();
578
            $maxId = $result[0]['id'] + 1;
579
            $item->setId($maxId);
580
581
            $entityManager = $this->getDoctrine()->getManager();
582
            $entityManager->persist($item);
583
            $entityManager->flush();
584
            $customIcon = $item->getCustomIcon();
585
            if (!empty($customIcon)) {
586
                $item->createGrayIcon($this->get('imagine'));
0 ignored issues
show
Bug introduced by
The method createGrayIcon() does not exist on Chamilo\CourseBundle\Entity\CTool. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

586
                $item->/** @scrutinizer ignore-call */ 
587
                       createGrayIcon($this->get('imagine'));

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
587
            }
588
589
            $this->get('session')->getFlashBag()->add('success', "Added");
590
            $url = $this->generateUrl('course_home.controller:iconListAction', ['id_session' => $sessionId]);
591
592
            return $this->redirect($url);
593
        }
594
595
        $this->getTemplate()->assign('item', $item);
596
        $this->getTemplate()->assign('form', $form->createView());
597
        $this->getTemplate()->assign('links', $this->generateLinks());
598
599
        return $this->render('@ChamiloCourse/Home/add.html.twig');
600
    }
601
602
    /**
603
     * @Route("/{itemId}/edit", methods={"GET"})
604
     */
605
    public function editIconAction($itemId)
606
    {
607
        if (!$this->isCourseTeacher()) {
608
            return $this->abort(404);
609
        }
610
611
        $sessionId = intval($this->getRequest()->get('id_session'));
612
613
        $criteria = ['cId' => $this->getCourse()->getId(), 'id' => $itemId];
614
        /** @var CTool $item */
615
        $item = $this->getRepository()->findOneBy($criteria);
616
617
        $form = $this->createForm($this->getFormType(), $item);
618
        $form->handleRequest($this->getRequest());
619
620
        if ($form->isValid()) {
621
            $entityManager = $this->getDoctrine()->getManager();
622
            $entityManager->persist($item);
623
            $entityManager->flush();
624
625
            $customIcon = $item->getCustomIcon();
626
            if (!empty($customIcon)) {
627
                $item->createGrayIcon($this->get('imagine'));
628
            }
629
630
            $this->get('session')->getFlashBag()->add('success', "Updated");
631
            $url = $this->generateUrl('course_home.controller:iconListAction', ['id_session' => $sessionId]);
632
633
            return $this->redirect($url);
634
        }
635
636
        $this->getTemplate()->assign('item', $item);
637
        $this->getTemplate()->assign('form', $form->createView());
638
        $this->getTemplate()->assign('links', $this->generateLinks());
639
640
        return $this->render('@ChamiloCourse/Home/edit.html.twig');
641
    }
642
643
    /**
644
     * @Route("/{itemId}/delete", methods={"GET"})
645
     */
646
    public function deleteIconAction($itemId)
647
    {
648
        if (!$this->isCourseTeacher()) {
649
            return $this->abort(404);
650
        }
651
652
        $criteria = ['cId' => $this->getCourse()->getId(), 'id' => $itemId];
653
654
        /** @var CTool $item */
655
        $item = $this->getRepository()->findOneBy($criteria);
656
        $entityManager = $this->getDoctrine()->getManager();
657
        $sessionId = $item->getSessionId();
658
        if (!empty($sessionId)) {
659
            $entityManager->remove($item);
660
        } else {
661
            $item->setCustomIcon(null);
662
            $entityManager->persist($item);
663
        }
664
        $entityManager->flush();
665
        $this->get('session')->getFlashBag()->add('success', "Deleted");
666
667
        $this->getTemplate()->assign('links', $this->generateLinks());
668
        $url = $this->generateUrl('course_home.controller:iconListAction');
669
670
        return $this->redirect($url);
671
    }
672
673
    /**
674
     * @param string $title
675
     * @param string $content
676
     * @param string $class
677
     *
678
     * @return string
679
     */
680
    private function return_block($title, $content, $class = null)
0 ignored issues
show
Unused Code introduced by
The method return_block() is not used, and could be removed.

This check looks for private methods that have been defined, but are not used inside the class.

Loading history...
681
    {
682
        $html = '<div class="row">
683
                <div class="col-xs-12 col-md-12">
684
                    <div class="title-tools">'.$title.'</div>
685
                </div>
686
            </div>
687
            <div class="row '.$class.'">'.$content.'</div>';
688
689
        return $html;
690
    }
691
692
    /**
693
     * @return array
694
     */
695
    private function renderActivityView()
0 ignored issues
show
Unused Code introduced by
The method renderActivityView() is not used, and could be removed.

This check looks for private methods that have been defined, but are not used inside the class.

Loading history...
696
    {
697
        $session_id = api_get_session_id();
698
        $urlGenerator = $this->get('router');
699
        $content = '';
700
701
        $enabled = api_get_plugin_setting('courselegal', 'tool_enable');
702
        $pluginExtra = null;
703
        if ($enabled === 'true') {
704
            /*require_once api_get_path(SYS_PLUGIN_PATH).'courselegal/config.php';
705
            $plugin = CourseLegalPlugin::create();
706
            $pluginExtra = $plugin->getTeacherLink();*/
707
        }
708
709
        // Start of tools for CourseAdmins (teachers/tutors)
710
        $totalList = [];
711
712
        // Start of tools for CourseAdmins (teachers/tutors)
713
        if ($session_id === 0 && api_is_course_admin() && api_is_allowed_to_edit(null, true)) {
714
            $content .= '<div class="alert alert-success" style="border:0px; margin-top: 0px;padding:0px;">
715
                <div class="normal-message" id="id_normal_message" style="display:none">';
716
            $content .= '<img src="'.api_get_path(WEB_PATH).'main/inc/lib/javascript/indicator.gif"/>&nbsp;&nbsp;';
717
            $content .= get_lang('Please stand by...');
718
            $content .= '</div>
719
                <div class="alert alert-success" id="id_confirmation_message" style="display:none"></div>
720
            </div>';
721
722
            $content .= $pluginExtra;
723
724
            if (api_get_setting('show_session_data') == 'true' && $session_id > 0) {
725
                $content .= '
726
                <div class="row">
727
                    <div class="col-xs-12 col-md-12">
728
                        <span class="viewcaption">'.get_lang('Session\'s data').'</span>
729
                        <table class="course_activity_home">'.
730
                            CourseHome::show_session_data($session_id).'
731
                        </table>
732
                    </div>
733
                </div>';
734
            }
735
736
            $my_list = CourseHome::get_tools_category(TOOL_AUTHORING);
737
738
            $blocks[] = [
0 ignored issues
show
Comprehensibility Best Practice introduced by
$blocks was never initialized. Although not strictly required by PHP, it is generally a good practice to add $blocks = array(); before regardless.
Loading history...
739
                'title' => get_lang('Authoring'),
740
                'class' => 'course-tools-author',
741
                'content' => CourseHome::show_tools_category($my_list),
742
            ];
743
744
            $list1 = CourseHome::get_tools_category(TOOL_INTERACTION);
745
            $list2 = CourseHome::get_tools_category(TOOL_COURSE_PLUGIN);
746
            $my_list = array_merge($list1, $list2);
747
748
            $blocks[] = [
749
                'title' => get_lang('Interaction'),
750
                'class' => 'course-tools-interaction',
751
                'content' => CourseHome::show_tools_category($my_list),
752
            ];
753
754
            $my_list = CourseHome::get_tools_category(TOOL_ADMIN_PLATFORM);
755
756
            $blocks[] = [
757
                'title' => get_lang('Administration'),
758
                'class' => 'course-tools-administration',
759
                'content' => CourseHome::show_tools_category($my_list),
760
            ];
761
        } elseif (api_is_coach()) {
762
            $content .= $pluginExtra;
763
            if (api_get_setting('show_session_data') === 'true' && $session_id > 0) {
764
                $content .= '<div class="row">
765
                    <div class="col-xs-12 col-md-12">
766
                    <span class="viewcaption">'.get_lang('Session\'s data').'</span>
767
                    <table class="course_activity_home">';
768
                $content .= CourseHome::show_session_data($session_id);
769
                $content .= '</table></div></div>';
770
            }
771
772
            $my_list = CourseHome::get_tools_category(TOOL_STUDENT_VIEW);
773
774
            $blocks[] = [
775
                'content' => CourseHome::show_tools_category($my_list),
776
            ];
777
778
            $sessionsCopy = api_get_setting('allow_session_course_copy_for_teachers');
779
            if ($sessionsCopy === 'true') {
780
                // Adding only maintenance for coaches.
781
                $myList = CourseHome::get_tools_category(TOOL_ADMIN_PLATFORM);
782
                $onlyMaintenanceList = [];
783
784
                foreach ($myList as $item) {
785
                    if ($item['name'] === 'course_maintenance') {
786
                        $item['link'] = 'course_info/maintenance_coach.php';
787
788
                        $onlyMaintenanceList[] = $item;
789
                    }
790
                }
791
792
                $blocks[] = [
793
                    'title' => get_lang('Administration'),
794
                    'content' => CourseHome::show_tools_category($onlyMaintenanceList),
795
                ];
796
            }
797
        } else {
798
            $tools = CourseHome::get_tools_category(TOOL_STUDENT_VIEW);
799
800
            $isDrhOfCourse = \CourseManager::isUserSubscribedInCourseAsDrh(
801
                api_get_user_id(),
802
                api_get_course_info()
803
            );
804
805
            // Force user icon for DRH
806
            if ($isDrhOfCourse) {
807
                $addUserTool = true;
808
                foreach ($tools as $tool) {
809
                    if ($tool['name'] === 'user') {
810
                        $addUserTool = false;
811
                        break;
812
                    }
813
                }
814
815
                if ($addUserTool) {
816
                    $tools[] = [
817
                        'c_id' => api_get_course_int_id(),
818
                        'name' => 'user',
819
                        'link' => 'user/user.php',
820
                        'image' => 'members.gif',
821
                        'visibility' => '1',
822
                        'admin' => '0',
823
                        'address' => 'squaregrey.gif',
824
                        'added_tool' => '0',
825
                        'target' => '_self',
826
                        'category' => 'interaction',
827
                        'session_id' => api_get_session_id(),
828
                    ];
829
                }
830
            }
831
832
            if (count($tools) > 0) {
833
                $blocks[] = ['content' => CourseHome::show_tools_category($tools)];
834
            }
835
836
            if ($isDrhOfCourse) {
837
                $drhTool = CourseHome::get_tools_category(TOOL_DRH);
838
                $blocks[] = ['content' => CourseHome::show_tools_category($drhTool)];
839
            }
840
        }
841
842
        return $blocks;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $blocks does not seem to be defined for all execution paths leading up to this point.
Loading history...
843
    }
844
845
    /**
846
     * @return array
847
     */
848
    private function autoLaunch()
849
    {
850
        return;
851
        $showAutoLaunchExerciseWarning = false;
0 ignored issues
show
Unused Code introduced by
$showAutoLaunchExerciseWarning = false is not reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
852
853
        // Exercise auto-launch
854
        $auto_launch = api_get_course_setting('enable_exercise_auto_launch');
855
856
        if (!empty($auto_launch)) {
857
            $session_id = api_get_session_id();
858
            //Exercise list
859
            if ($auto_launch == 2) {
860
                if (api_is_platform_admin() || api_is_allowed_to_edit()) {
861
                    $showAutoLaunchExerciseWarning = true;
862
                } else {
863
                    $session_key = 'exercise_autolunch_'.$session_id.'_'.api_get_course_int_id().'_'.api_get_user_id();
864
                    $sessionData = Session::read($session_key);
865
                    if (!isset($sessionData)) {
866
                        //redirecting to the Exercise
867
                        $url = api_get_path(WEB_CODE_PATH).'exercise/exercise.php?'.api_get_cidreq();
868
                        $_SESSION[$session_key] = true;
869
870
                        header("Location: $url");
871
                        exit;
872
                    }
873
                }
874
            } else {
875
                $table = \Database::get_course_table(TABLE_QUIZ_TEST);
876
                $course_id = api_get_course_int_id();
877
                $condition = '';
878
                if (!empty($session_id)) {
879
                    $condition = api_get_session_condition($session_id);
880
                    $sql = "SELECT iid FROM $table
881
                            WHERE c_id = $course_id AND autolaunch = 1 $condition
882
                            LIMIT 1";
883
                    $result = \Database::query($sql);
884
                    //If we found nothing in the session we just called the session_id =  0 autolaunch
885
                    if (\Database::num_rows($result) == 0) {
886
                        $condition = '';
887
                    } else {
888
                        //great, there is an specific auto lunch for this session we leave the $condition
889
                    }
890
                }
891
892
                $sql = "SELECT iid FROM $table
893
                        WHERE c_id = $course_id AND autolaunch = 1 $condition
894
                        LIMIT 1";
895
                $result = \Database::query($sql);
896
                if (\Database::num_rows($result) > 0) {
897
                    $data = \Database::fetch_array($result, 'ASSOC');
898
                    if (!empty($data['iid'])) {
899
                        if (api_is_platform_admin() || api_is_allowed_to_edit()) {
900
                            $showAutoLaunchExerciseWarning = true;
901
                        } else {
902
                            $session_key = 'exercise_autolunch_'.$session_id.'_'.api_get_course_int_id().'_'.api_get_user_id();
903
                            if (!isset($_SESSION[$session_key])) {
904
                                //redirecting to the LP
905
                                $url = api_get_path(WEB_CODE_PATH).'exercise/overview.php?'.api_get_cidreq().'&exerciseId='.$data['iid'];
906
907
                                $_SESSION[$session_key] = true;
908
                                header("Location: $url");
909
                                exit;
910
                            }
911
                        }
912
                    }
913
                }
914
            }
915
        }
916
917
        /* Auto launch code */
918
        $showAutoLaunchLpWarning = false;
919
        $auto_launch = api_get_course_setting('enable_lp_auto_launch');
920
        if (!empty($auto_launch)) {
921
            $session_id = api_get_session_id();
922
            //LP list
923
            if ($auto_launch == 2) {
924
                if (api_is_platform_admin() || api_is_allowed_to_edit()) {
925
                    $showAutoLaunchLpWarning = true;
926
                } else {
927
                    $session_key = 'lp_autolunch_'.$session_id.'_'.api_get_course_int_id().'_'.api_get_user_id();
928
                    if (!isset($_SESSION[$session_key])) {
929
                        //redirecting to the LP
930
                        $url = api_get_path(WEB_CODE_PATH).'lp/lp_controller.php?'.api_get_cidreq();
931
                        $_SESSION[$session_key] = true;
932
                        header("Location: $url");
933
                        exit;
934
                    }
935
                }
936
            } else {
937
                $lp_table = \Database::get_course_table(TABLE_LP_MAIN);
938
                $course_id = api_get_course_int_id();
939
                $condition = '';
940
                if (!empty($session_id)) {
941
                    $condition = api_get_session_condition($session_id);
942
                    $sql = "SELECT id FROM $lp_table WHERE c_id = $course_id AND autolunch = 1 $condition LIMIT 1";
943
                    $result = \Database::query($sql);
944
                    //If we found nothing in the session we just called the session_id =  0 autolunch
945
                    if (\Database::num_rows($result) == 0) {
946
                        $condition = '';
947
                    } else {
948
                        //great, there is an specific auto lunch for this session we leave the $condition
949
                    }
950
                }
951
952
                $sql = "SELECT id FROM $lp_table
953
                        WHERE c_id = $course_id AND autolunch = 1 $condition
954
                        LIMIT 1";
955
                $result = \Database::query($sql);
956
                if (\Database::num_rows($result) > 0) {
957
                    $lp_data = \Database::fetch_array($result, 'ASSOC');
958
                    if (!empty($lp_data['id'])) {
959
                        if (api_is_platform_admin() || api_is_allowed_to_edit()) {
960
                            $showAutoLaunchLpWarning = true;
961
                        } else {
962
                            $session_key = 'lp_autolunch_'.$session_id.'_'.api_get_course_int_id().'_'.api_get_user_id();
963
                            if (!isset($_SESSION[$session_key])) {
964
                                //redirecting to the LP
965
                                $url = api_get_path(WEB_CODE_PATH).'lp/lp_controller.php?'.api_get_cidreq().'&action=view&lp_id='.$lp_data['id'];
966
967
                                $_SESSION[$session_key] = true;
968
                                header("Location: $url");
969
                                exit;
970
                            }
971
                        }
972
                    }
973
                }
974
            }
975
        }
976
977
        return [
978
            'show_autolaunch_exercise_warning' => $showAutoLaunchExerciseWarning,
979
            'show_autolaunch_lp_warning' => $showAutoLaunchLpWarning,
980
        ];
981
    }
982
}
983