Completed
Push — master ( a34f18...c6c5e0 )
by Julito
15:01
created

CourseHomeController::renderActivityView()   D

Complexity

Conditions 19
Paths 68

Size

Total Lines 148
Code Lines 85

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 19
eloc 85
c 0
b 0
f 0
nc 68
nop 0
dl 0
loc 148
rs 4.5166

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
/* For licensing terms, see /license.txt */
3
4
namespace Chamilo\CoreBundle\Controller;
5
6
use Chamilo\CoreBundle\ToolChain;
7
use Chamilo\CourseBundle\Controller\ToolBaseController;
8
use Chamilo\CourseBundle\Entity\CTool;
9
use Chamilosession as Session;
10
use CourseHome;
11
use CourseManager;
12
use Database;
13
use Display;
14
use Event;
15
use ExtraFieldValue;
16
use Security;
17
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Entity;
18
use Symfony\Component\HttpFoundation\Request;
19
use Symfony\Component\Routing\Annotation\Route;
20
21
/**
22
 * Class CourseHomeController.
23
 *
24
 * @author Julio Montoya <[email protected]>
25
 *
26
 * @Route("/courses")
27
 */
28
class CourseHomeController extends ToolBaseController
29
{
30
    /**
31
     * @Route("/{cid}/home", name="chamilo_core_course_home")
32
     *
33
     * @Entity("course", expr="repository.find(cid)")
34
     */
35
    public function indexAction(Request $request, ToolChain $toolChain)
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
        $userId = $this->getUser()->getId();
43
        $courseCode = $course->getCode();
44
        $courseId = $course->getId();
45
        $sessionId = $this->getSessionId();
46
        $showMessage = '';
47
48
        if (api_is_invitee()) {
49
            $isInASession = $sessionId > 0;
50
            $isSubscribed = CourseManager::is_user_subscribed_in_course(
51
                $userId,
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($userId, $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($userId, $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
            $showMessage .= Display::return_message(
274
                $autoLaunchWarning,
275
                'warning'
276
            );
277
        }
278
279
        // Activity start
280
        $id = isset($_GET['id']) ? (int) $_GET['id'] : null;
281
        $course_id = api_get_course_int_id();
282
        $session_id = api_get_session_id();
283
284
        // Work with data post askable by admin of course
285
        if (api_is_platform_admin()) {
286
            // Show message to confirm that a tool it to be hidden from available tools
287
            // visibility 0,1->2
288
            if (!empty($_GET['askDelete'])) {
289
                $content .= '<div id="toolhide">'.get_lang('Do you really want to delete this link?').'<br />&nbsp;&nbsp;&nbsp;
290
                    <a href="'.api_get_self().'">'.get_lang('No').'</a>&nbsp;|&nbsp;
291
                    <a href="'.api_get_self().'?delete=yes&id='.$id.'">'.get_lang('Yes').'</a>
292
                </div>';
293
            } elseif (isset($_GET['delete']) && $_GET['delete']) {
294
                /*
295
                * Process hiding a tools from available tools.
296
                */
297
                Database::query("DELETE FROM $tool_table WHERE c_id = $course_id AND id='$id' AND added_tool=1");
298
            }
299
        }
300
301
        // Course legal
302
        $enabled = api_get_plugin_setting('courselegal', 'tool_enable');
303
        $pluginExtra = null;
304
        if ($enabled === 'true') {
305
            require_once api_get_path(SYS_PLUGIN_PATH).'courselegal/config.php';
306
            $plugin = \CourseLegalPlugin::create();
307
            $pluginExtra = $plugin->getTeacherLink();
308
        }
309
310
        // Start of tools for CourseAdmins (teachers/tutors)
311
        if ($session_id === 0 && api_is_course_admin() && api_is_allowed_to_edit(null, true)) {
312
            $content .= '<div class="alert alert-success" style="border:0px; margin-top: 0px;padding:0px;">
313
		<div class="normal-message" id="id_normal_message" style="display:none">';
314
            $content .= '<img src="'.api_get_path(WEB_PATH).'main/inc/lib/javascript/indicator.gif"/>&nbsp;&nbsp;';
315
            $content .= get_lang('Please stand by...');
316
            $content .= '</div>
317
		<div class="alert alert-success" id="id_confirmation_message" style="display:none"></div>
318
	</div>';
319
            $content .= $pluginExtra;
320
        } elseif (api_is_coach()) {
321
            $content .= $pluginExtra;
322
            if (api_get_setting('show_session_data') === 'true' && $session_id > 0) {
323
                $content .= '<div class="row">
324
            <div class="col-xs-12 col-md-12">
325
			<span class="viewcaption">'.get_lang('Session\'s data').'</span>
326
			<table class="course_activity_home">';
327
                $content .= CourseHome::show_session_data($session_id);
328
                $content .= '</table></div></div>';
329
            }
330
        }
331
332
        $blocks = CourseHome::getUserBlocks($toolChain);
333
334
        // Get session-career diagram
335
        $diagram = '';
336
        $allow = api_get_configuration_value('allow_career_diagram');
337
        if ($allow === true) {
338
            $htmlHeadXtra[] = api_get_js('jsplumb2.js');
339
            $extra = new ExtraFieldValue('session');
340
            $value = $extra->get_values_by_handler_and_field_variable(
341
                api_get_session_id(),
342
                'external_career_id'
343
            );
344
345
            if (!empty($value) && isset($value['value'])) {
346
                $careerId = $value['value'];
347
                $extraFieldValue = new ExtraFieldValue('career');
348
                $item = $extraFieldValue->get_item_id_from_field_variable_and_field_value(
349
                    'external_career_id',
350
                    $careerId,
351
                    false,
352
                    false,
353
                    false
354
                );
355
356
                if (!empty($item) && isset($item['item_id'])) {
357
                    $careerId = $item['item_id'];
358
                    $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...
359
                    $careerInfo = $career->get($careerId);
360
                    if (!empty($careerInfo)) {
361
                        $extraFieldValue = new ExtraFieldValue('career');
362
                        $item = $extraFieldValue->get_values_by_handler_and_field_variable(
363
                            $careerId,
364
                            'career_diagram',
365
                            false,
366
                            false,
367
                            false
368
                        );
369
370
                        if (!empty($item) && isset($item['value']) && !empty($item['value'])) {
371
                            /** @var Graph $graph */
372
                            $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...
373
                                'career',
374
                                $item['value']
375
                            );
376
                            $diagram = Career::renderDiagram($careerInfo, $graph);
377
                        }
378
                    }
379
                }
380
            }
381
        }
382
383
        $content = '<div id="course_tools">'.$diagram.$content.'</div>';
384
385
        // Deleting the objects
386
        Session::erase('_gid');
387
        Session::erase('oLP');
388
        Session::erase('lpobject');
389
        api_remove_in_gradebook();
390
        \Exercise::cleanSessionVariables();
391
        \DocumentManager::removeGeneratedAudioTempFile();
392
393
        return $this->render(
394
            '@ChamiloTheme/Course/home.html.twig',
395
            [
396
                'course' => $course,
397
                'diagram' => $diagram,
398
               // 'session_info' => $sessionInfo,
399
                'icons' => $result['content'],
400
                'blocks' => $blocks,
401
                //'edit_icons' => $editIcons,
402
                //'introduction_text' => $introduction,
403
                'exercise_warning' => null,
404
                'lp_warning' => null,
405
            ]
406
        );
407
    }
408
409
    /**
410
     * @Route("/show/{iconId}", methods={"GET"})
411
     *
412
     * @param $iconId
413
     *
414
     * @return string|null
415
     */
416
    public function showIconAction($iconId)
417
    {
418
        $entityManager = $this->getDoctrine()->getManager();
419
        $criteria = ['cId' => api_get_course_int_id(), 'id' => $iconId];
420
        $tool = $this->getRepository(
421
            'Chamilo\CourseBundle\Entity\CTool'
422
        )->findOneBy($criteria);
423
        if ($tool) {
424
            $tool->setVisibility(1);
425
        }
426
        $entityManager->persist($tool);
427
        //$entityManager->flush();
428
        return Display::return_message(get_lang('Visible'), 'confirmation');
429
    }
430
431
    /**
432
     * @Route("/hide/{iconId}", methods={"GET"})
433
     *
434
     * @param $iconId
435
     *
436
     * @return string|null
437
     */
438
    public function hideIconAction($iconId)
439
    {
440
        if (!$this->isCourseTeacher()) {
441
            return $this->abort(404);
442
        }
443
444
        $entityManager = $this->getDoctrine()->getManager();
445
        $criteria = ['cId' => api_get_course_int_id(), 'id' => $iconId];
446
        $tool = $this->getRepository(
447
            'Chamilo\CourseBundle\Entity\CTool'
448
        )->findOneBy($criteria);
449
        if ($tool) {
450
            $tool->setVisibility(0);
451
        }
452
        $entityManager->persist($tool);
453
        //$entityManager->flush();
454
        return Display::return_message(get_lang('The tool is now invisible.'), 'confirmation');
455
    }
456
457
    /**
458
     * @Route("/delete/{iconId}", methods={"GET"})
459
     *
460
     * @param $iconId
461
     *
462
     * @return string|null
463
     */
464
    public function deleteIcon($iconId)
465
    {
466
        if (!$this->isCourseTeacher()) {
467
            return $this->abort(404);
468
        }
469
470
        $entityManager = $this->getDoctrine()->getManager();
471
        $criteria = ['cId' => api_get_course_int_id(), 'id' => $iconId, 'added_tool' => 1];
472
        $tool = $this->getRepository(
473
            'Chamilo\CourseBundle\Entity\CTool'
474
        )->findOneBy($criteria);
475
        $entityManager->remove($tool);
476
        //$entityManager->flush();
477
        return Display::return_message(get_lang('Deleted'), 'confirmation');
478
    }
479
480
    /**
481
     * @Route("/icon_list", methods={"GET"})
482
     */
483
    public function iconListAction(Request $request)
484
    {
485
        $em = $this->getDoctrine()->getManager();
486
        $repo = $this->getDoctrine()->getRepository('ChamiloCourseBundle:CTool');
487
488
        $sessionId = (int) $request->get('id_session');
489
        $itemsFromSession = [];
490
        if (!empty($sessionId)) {
491
            $query = $repo->createQueryBuilder('a');
492
            $query->select('s');
493
            $query->from('Chamilo\CourseBundle\Entity\CTool', 's');
494
            $query->where('s.cId  = :courseId AND s.sessionId = :sessionId')
495
                ->setParameters(
496
                    [
497
                        'course' => $this->getCourse()->getId(),
498
                        'sessionId' => $sessionId,
499
                    ]
500
                );
501
            $itemsFromSession = $query->getQuery()->getResult();
502
503
            $itemNameList = [];
504
            foreach ($itemsFromSession as $item) {
505
                $itemNameList[] = $item->getName();
506
            }
507
508
            //$itemsFromSession = $this->getRepository()->findBy($criteria);
509
            $query = $repo->createQueryBuilder('a');
510
            $query->select('s');
511
            $query->from('Chamilo\CourseBundle\Entity\CTool', 's');
512
            $query->where('s.cId  = :courseId AND s.sessionId = 0')
513
                ->setParameters(
514
                    [
515
                        'courseId' => $this->getCourse()->getId(),
516
                    ]
517
                );
518
            if (!empty($itemNameList)) {
519
                $query->andWhere($query->expr()->notIn('s.name', $itemNameList));
520
            }
521
            $itemsFromCourse = $query->getQuery()->getResult();
522
        } else {
523
            $criteria = ['cId' => $this->getCourse()->getId(), 'sessionId' => 0];
524
            $itemsFromCourse = $repo->findBy($criteria);
525
        }
526
527
        return $this->render(
528
            '@ChamiloCourse/Home/list.html.twig',
529
            [
530
                'items_from_course' => $itemsFromCourse,
531
                'items_from_session' => $itemsFromSession,
532
                'links' => '',
533
            ]
534
        );
535
    }
536
537
    /**
538
     * @Route("/{itemName}/add", methods={"GET", "POST"})
539
     *
540
     * @param $itemName
541
     *
542
     * @return mixed
543
     */
544
    public function addIconAction($itemName)
545
    {
546
        if (!$this->isCourseTeacher()) {
547
            return $this->abort(404);
548
        }
549
550
        $sessionId = intval($this->getRequest()->get('id_session'));
551
552
        if (empty($sessionId)) {
553
            return $this->abort(500);
554
        }
555
556
        $criteria = ['cId' => $this->getCourse()->getId(), 'sessionId' => 0, 'name' => $itemName];
557
        $itemFromDatabase = $this->getRepository()->findOneBy($criteria);
558
559
        if (!$itemFromDatabase) {
560
            $this->createNotFoundException();
561
        }
562
        /** @var CTool $item */
563
        $item = clone $itemFromDatabase;
564
        $item->setId(null);
565
        $item->setSessionId($sessionId);
0 ignored issues
show
Bug introduced by
The method setSessionId() does not exist on Chamilo\CourseBundle\Entity\CTool. Did you maybe mean setSession()? ( Ignorable by Annotation )

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

565
        $item->/** @scrutinizer ignore-call */ 
566
               setSessionId($sessionId);

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...
566
        $form = $this->createForm($this->getFormType(), $item);
567
568
        $form->handleRequest($this->getRequest());
569
570
        if ($form->isSubmitted() && $form->isValid()) {
571
            $query = $this->getDoctrine()->getManager()->createQueryBuilder('a');
572
            $query->select('MAX(s.id) as id');
573
            $query->from('Chamilo\CourseBundle\Entity\CTool', 's');
574
            $query->where('s.cId  = :courseId')->setParameter('courseId', $this->getCourse()->getId());
575
            $result = $query->getQuery()->getArrayResult();
576
            $maxId = $result[0]['id'] + 1;
577
            $item->setId($maxId);
578
579
            $entityManager = $this->getDoctrine()->getManager();
580
            $entityManager->persist($item);
581
            $entityManager->flush();
582
            $customIcon = $item->getCustomIcon();
583
            if (!empty($customIcon)) {
584
                $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

584
                $item->/** @scrutinizer ignore-call */ 
585
                       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...
585
            }
586
587
            $this->get('session')->getFlashBag()->add('success', "Added");
588
            $url = $this->generateUrl('course_home.controller:iconListAction', ['id_session' => $sessionId]);
589
590
            return $this->redirect($url);
591
        }
592
593
        $this->getTemplate()->assign('item', $item);
594
        $this->getTemplate()->assign('form', $form->createView());
595
        $this->getTemplate()->assign('links', $this->generateLinks());
596
597
        return $this->render('@ChamiloCourse/Home/add.html.twig');
598
    }
599
600
    /**
601
     * @Route("/{itemId}/edit", methods={"GET"})
602
     */
603
    public function editIconAction($itemId)
604
    {
605
        if (!$this->isCourseTeacher()) {
606
            return $this->abort(404);
607
        }
608
609
        $sessionId = intval($this->getRequest()->get('id_session'));
610
611
        $criteria = ['cId' => $this->getCourse()->getId(), 'id' => $itemId];
612
        /** @var CTool $item */
613
        $item = $this->getRepository()->findOneBy($criteria);
614
615
        $form = $this->createForm($this->getFormType(), $item);
616
        $form->handleRequest($this->getRequest());
617
618
        if ($form->isValid()) {
619
            $entityManager = $this->getDoctrine()->getManager();
620
            $entityManager->persist($item);
621
            $entityManager->flush();
622
623
            $customIcon = $item->getCustomIcon();
624
            if (!empty($customIcon)) {
625
                $item->createGrayIcon($this->get('imagine'));
626
            }
627
628
            $this->get('session')->getFlashBag()->add('success', "Updated");
629
            $url = $this->generateUrl('course_home.controller:iconListAction', ['id_session' => $sessionId]);
630
631
            return $this->redirect($url);
632
        }
633
634
        $this->getTemplate()->assign('item', $item);
635
        $this->getTemplate()->assign('form', $form->createView());
636
        $this->getTemplate()->assign('links', $this->generateLinks());
637
638
        return $this->render('@ChamiloCourse/Home/edit.html.twig');
639
    }
640
641
    /**
642
     * @Route("/{itemId}/delete", methods={"GET"})
643
     */
644
    public function deleteIconAction($itemId)
645
    {
646
        if (!$this->isCourseTeacher()) {
647
            return $this->abort(404);
648
        }
649
650
        $criteria = ['cId' => $this->getCourse()->getId(), 'id' => $itemId];
651
652
        /** @var CTool $item */
653
        $item = $this->getRepository()->findOneBy($criteria);
654
        $entityManager = $this->getDoctrine()->getManager();
655
        $sessionId = $item->getSessionId();
0 ignored issues
show
Bug introduced by
The method getSessionId() does not exist on Chamilo\CourseBundle\Entity\CTool. Did you maybe mean getSession()? ( Ignorable by Annotation )

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

655
        /** @scrutinizer ignore-call */ 
656
        $sessionId = $item->getSessionId();

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...
656
        if (!empty($sessionId)) {
657
            $entityManager->remove($item);
658
        } else {
659
            $item->setCustomIcon(null);
660
            $entityManager->persist($item);
661
        }
662
        $entityManager->flush();
663
        $this->get('session')->getFlashBag()->add('success', "Deleted");
664
665
        $this->getTemplate()->assign('links', $this->generateLinks());
666
        $url = $this->generateUrl('course_home.controller:iconListAction');
667
668
        return $this->redirect($url);
669
    }
670
671
672
    /**
673
     * @return array
674
     */
675
    private function autoLaunch()
676
    {
677
        return;
678
        $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...
679
680
        // Exercise auto-launch
681
        $auto_launch = api_get_course_setting('enable_exercise_auto_launch');
682
683
        if (!empty($auto_launch)) {
684
            $session_id = api_get_session_id();
685
            //Exercise list
686
            if ($auto_launch == 2) {
687
                if (api_is_platform_admin() || api_is_allowed_to_edit()) {
688
                    $showAutoLaunchExerciseWarning = true;
689
                } else {
690
                    $session_key = 'exercise_autolunch_'.$session_id.'_'.api_get_course_int_id().'_'.api_get_user_id();
691
                    $sessionData = Session::read($session_key);
692
                    if (!isset($sessionData)) {
693
                        //redirecting to the Exercise
694
                        $url = api_get_path(WEB_CODE_PATH).'exercise/exercise.php?'.api_get_cidreq();
695
                        $_SESSION[$session_key] = true;
696
697
                        header("Location: $url");
698
                        exit;
699
                    }
700
                }
701
            } else {
702
                $table = \Database::get_course_table(TABLE_QUIZ_TEST);
703
                $course_id = api_get_course_int_id();
704
                $condition = '';
705
                if (!empty($session_id)) {
706
                    $condition = api_get_session_condition($session_id);
707
                    $sql = "SELECT iid FROM $table
708
                            WHERE c_id = $course_id AND autolaunch = 1 $condition
709
                            LIMIT 1";
710
                    $result = \Database::query($sql);
711
                    //If we found nothing in the session we just called the session_id =  0 autolaunch
712
                    if (\Database::num_rows($result) == 0) {
713
                        $condition = '';
714
                    } else {
715
                        //great, there is an specific auto lunch for this session we leave the $condition
716
                    }
717
                }
718
719
                $sql = "SELECT iid FROM $table
720
                        WHERE c_id = $course_id AND autolaunch = 1 $condition
721
                        LIMIT 1";
722
                $result = \Database::query($sql);
723
                if (\Database::num_rows($result) > 0) {
724
                    $data = \Database::fetch_array($result, 'ASSOC');
725
                    if (!empty($data['iid'])) {
726
                        if (api_is_platform_admin() || api_is_allowed_to_edit()) {
727
                            $showAutoLaunchExerciseWarning = true;
728
                        } else {
729
                            $session_key = 'exercise_autolunch_'.$session_id.'_'.api_get_course_int_id().'_'.api_get_user_id();
730
                            if (!isset($_SESSION[$session_key])) {
731
                                //redirecting to the LP
732
                                $url = api_get_path(WEB_CODE_PATH).'exercise/overview.php?'.api_get_cidreq().'&exerciseId='.$data['iid'];
733
734
                                $_SESSION[$session_key] = true;
735
                                header("Location: $url");
736
                                exit;
737
                            }
738
                        }
739
                    }
740
                }
741
            }
742
        }
743
744
        /* Auto launch code */
745
        $showAutoLaunchLpWarning = false;
746
        $auto_launch = api_get_course_setting('enable_lp_auto_launch');
747
        if (!empty($auto_launch)) {
748
            $session_id = api_get_session_id();
749
            //LP list
750
            if ($auto_launch == 2) {
751
                if (api_is_platform_admin() || api_is_allowed_to_edit()) {
752
                    $showAutoLaunchLpWarning = true;
753
                } else {
754
                    $session_key = 'lp_autolunch_'.$session_id.'_'.api_get_course_int_id().'_'.api_get_user_id();
755
                    if (!isset($_SESSION[$session_key])) {
756
                        //redirecting to the LP
757
                        $url = api_get_path(WEB_CODE_PATH).'lp/lp_controller.php?'.api_get_cidreq();
758
                        $_SESSION[$session_key] = true;
759
                        header("Location: $url");
760
                        exit;
761
                    }
762
                }
763
            } else {
764
                $lp_table = \Database::get_course_table(TABLE_LP_MAIN);
765
                $course_id = api_get_course_int_id();
766
                $condition = '';
767
                if (!empty($session_id)) {
768
                    $condition = api_get_session_condition($session_id);
769
                    $sql = "SELECT id FROM $lp_table WHERE c_id = $course_id AND autolunch = 1 $condition LIMIT 1";
770
                    $result = \Database::query($sql);
771
                    //If we found nothing in the session we just called the session_id =  0 autolunch
772
                    if (\Database::num_rows($result) == 0) {
773
                        $condition = '';
774
                    } else {
775
                        //great, there is an specific auto lunch for this session we leave the $condition
776
                    }
777
                }
778
779
                $sql = "SELECT id FROM $lp_table
780
                        WHERE c_id = $course_id AND autolunch = 1 $condition
781
                        LIMIT 1";
782
                $result = \Database::query($sql);
783
                if (\Database::num_rows($result) > 0) {
784
                    $lp_data = \Database::fetch_array($result, 'ASSOC');
785
                    if (!empty($lp_data['id'])) {
786
                        if (api_is_platform_admin() || api_is_allowed_to_edit()) {
787
                            $showAutoLaunchLpWarning = true;
788
                        } else {
789
                            $session_key = 'lp_autolunch_'.$session_id.'_'.api_get_course_int_id().'_'.api_get_user_id();
790
                            if (!isset($_SESSION[$session_key])) {
791
                                //redirecting to the LP
792
                                $url = api_get_path(WEB_CODE_PATH).'lp/lp_controller.php?'.api_get_cidreq().'&action=view&lp_id='.$lp_data['id'];
793
794
                                $_SESSION[$session_key] = true;
795
                                header("Location: $url");
796
                                exit;
797
                            }
798
                        }
799
                    }
800
                }
801
            }
802
        }
803
804
        return [
805
            'show_autolaunch_exercise_warning' => $showAutoLaunchExerciseWarning,
806
            'show_autolaunch_lp_warning' => $showAutoLaunchLpWarning,
807
        ];
808
    }
809
}
810