Completed
Push — master ( 3742bc...55196a )
by Julito
13:21
created

CourseHomeController::addIconAction()   B

Complexity

Conditions 6
Paths 8

Size

Total Lines 54
Code Lines 35

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 35
nc 8
nop 1
dl 0
loc 54
rs 8.7377
c 0
b 0
f 0

How to fix   Long Method   

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

590
                $item->/** @scrutinizer ignore-call */ 
591
                       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...
591
            }
592
593
            $this->get('session')->getFlashBag()->add('success', "Added");
594
            $url = $this->generateUrl('course_home.controller:iconListAction', ['id_session' => $sessionId]);
595
596
            return $this->redirect($url);
597
        }
598
599
        $this->getTemplate()->assign('item', $item);
600
        $this->getTemplate()->assign('form', $form->createView());
601
        $this->getTemplate()->assign('links', $this->generateLinks());
602
603
        return $this->render('@ChamiloCourse/Home/add.html.twig');
604
    }
605
606
    /**
607
     * @Route("/{itemId}/edit", methods={"GET"})
608
     */
609
    public function editIconAction($itemId)
610
    {
611
        if (!$this->isCourseTeacher()) {
612
            return $this->abort(404);
613
        }
614
615
        $sessionId = intval($this->getRequest()->get('id_session'));
616
617
        $criteria = ['cId' => $this->getCourse()->getId(), 'id' => $itemId];
618
        /** @var CTool $item */
619
        $item = $this->getRepository()->findOneBy($criteria);
620
621
        $form = $this->createForm($this->getFormType(), $item);
622
        $form->handleRequest($this->getRequest());
623
624
        if ($form->isValid()) {
625
            $entityManager = $this->getDoctrine()->getManager();
626
            $entityManager->persist($item);
627
            $entityManager->flush();
628
629
            $customIcon = $item->getCustomIcon();
630
            if (!empty($customIcon)) {
631
                $item->createGrayIcon($this->get('imagine'));
632
            }
633
634
            $this->get('session')->getFlashBag()->add('success', "Updated");
635
            $url = $this->generateUrl('course_home.controller:iconListAction', ['id_session' => $sessionId]);
636
637
            return $this->redirect($url);
638
        }
639
640
        $this->getTemplate()->assign('item', $item);
641
        $this->getTemplate()->assign('form', $form->createView());
642
        $this->getTemplate()->assign('links', $this->generateLinks());
643
644
        return $this->render('@ChamiloCourse/Home/edit.html.twig');
645
    }
646
647
    /**
648
     * @Route("/{itemId}/delete", methods={"GET"})
649
     */
650
    public function deleteIconAction($itemId)
651
    {
652
        if (!$this->isCourseTeacher()) {
653
            return $this->abort(404);
654
        }
655
656
        $criteria = ['cId' => $this->getCourse()->getId(), 'id' => $itemId];
657
658
        /** @var CTool $item */
659
        $item = $this->getRepository()->findOneBy($criteria);
660
        $entityManager = $this->getDoctrine()->getManager();
661
        $sessionId = $item->getSessionId();
662
        if (!empty($sessionId)) {
663
            $entityManager->remove($item);
664
        } else {
665
            $item->setCustomIcon(null);
666
            $entityManager->persist($item);
667
        }
668
        $entityManager->flush();
669
        $this->get('session')->getFlashBag()->add('success', "Deleted");
670
671
        $this->getTemplate()->assign('links', $this->generateLinks());
672
        $url = $this->generateUrl('course_home.controller:iconListAction');
673
674
        return $this->redirect($url);
675
    }
676
677
    /**
678
     * @param string $title
679
     * @param string $content
680
     * @param string $class
681
     *
682
     * @return string
683
     */
684
    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...
685
    {
686
        $html = '<div class="row">
687
                <div class="col-xs-12 col-md-12">
688
                    <div class="title-tools">'.$title.'</div>
689
                </div>
690
            </div>
691
            <div class="row '.$class.'">'.$content.'</div>';
692
693
        return $html;
694
    }
695
696
    /**
697
     * @return array
698
     */
699
    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...
700
    {
701
        $session_id = api_get_session_id();
702
        $urlGenerator = $this->get('router');
703
        $content = '';
704
705
        $enabled = api_get_plugin_setting('courselegal', 'tool_enable');
706
        $pluginExtra = null;
707
        if ($enabled === 'true') {
708
            /*require_once api_get_path(SYS_PLUGIN_PATH).'courselegal/config.php';
709
            $plugin = CourseLegalPlugin::create();
710
            $pluginExtra = $plugin->getTeacherLink();*/
711
        }
712
713
        // Start of tools for CourseAdmins (teachers/tutors)
714
        $totalList = [];
715
716
        // Start of tools for CourseAdmins (teachers/tutors)
717
        if ($session_id === 0 && api_is_course_admin() && api_is_allowed_to_edit(null, true)) {
718
            $content .= '<div class="alert alert-success" style="border:0px; margin-top: 0px;padding:0px;">
719
                <div class="normal-message" id="id_normal_message" style="display:none">';
720
            $content .= '<img src="'.api_get_path(WEB_PATH).'main/inc/lib/javascript/indicator.gif"/>&nbsp;&nbsp;';
721
            $content .= get_lang('Please stand by...');
722
            $content .= '</div>
723
                <div class="alert alert-success" id="id_confirmation_message" style="display:none"></div>
724
            </div>';
725
726
            $content .= $pluginExtra;
727
728
            if (api_get_setting('show_session_data') == 'true' && $session_id > 0) {
729
                $content .= '
730
                <div class="row">
731
                    <div class="col-xs-12 col-md-12">
732
                        <span class="viewcaption">'.get_lang('Session\'s data').'</span>
733
                        <table class="course_activity_home">'.
734
                            CourseHome::show_session_data($session_id).'
735
                        </table>
736
                    </div>
737
                </div>';
738
            }
739
740
            $my_list = CourseHome::get_tools_category(TOOL_AUTHORING);
741
742
            $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...
743
                'title' => get_lang('Authoring'),
744
                'class' => 'course-tools-author',
745
                'content' => CourseHome::show_tools_category($my_list),
746
            ];
747
748
            $list1 = CourseHome::get_tools_category(TOOL_INTERACTION);
749
            $list2 = CourseHome::get_tools_category(TOOL_COURSE_PLUGIN);
750
            $my_list = array_merge($list1, $list2);
751
752
            $blocks[] = [
753
                'title' => get_lang('Interaction'),
754
                'class' => 'course-tools-interaction',
755
                'content' => CourseHome::show_tools_category($my_list),
756
            ];
757
758
            $my_list = CourseHome::get_tools_category(TOOL_ADMIN_PLATFORM);
759
760
            $blocks[] = [
761
                'title' => get_lang('Administration'),
762
                'class' => 'course-tools-administration',
763
                'content' => CourseHome::show_tools_category($my_list),
764
            ];
765
        } elseif (api_is_coach()) {
766
            $content .= $pluginExtra;
767
            if (api_get_setting('show_session_data') === 'true' && $session_id > 0) {
768
                $content .= '<div class="row">
769
                    <div class="col-xs-12 col-md-12">
770
                    <span class="viewcaption">'.get_lang('Session\'s data').'</span>
771
                    <table class="course_activity_home">';
772
                $content .= CourseHome::show_session_data($session_id);
773
                $content .= '</table></div></div>';
774
            }
775
776
            $my_list = CourseHome::get_tools_category(TOOL_STUDENT_VIEW);
777
778
            $blocks[] = [
779
                'content' => CourseHome::show_tools_category($my_list),
780
            ];
781
782
            $sessionsCopy = api_get_setting('allow_session_course_copy_for_teachers');
783
            if ($sessionsCopy === 'true') {
784
                // Adding only maintenance for coaches.
785
                $myList = CourseHome::get_tools_category(TOOL_ADMIN_PLATFORM);
786
                $onlyMaintenanceList = [];
787
788
                foreach ($myList as $item) {
789
                    if ($item['name'] === 'course_maintenance') {
790
                        $item['link'] = 'course_info/maintenance_coach.php';
791
792
                        $onlyMaintenanceList[] = $item;
793
                    }
794
                }
795
796
                $blocks[] = [
797
                    'title' => get_lang('Administration'),
798
                    'content' => CourseHome::show_tools_category($onlyMaintenanceList),
799
                ];
800
            }
801
        } else {
802
            $tools = CourseHome::get_tools_category(TOOL_STUDENT_VIEW);
803
804
            $isDrhOfCourse = \CourseManager::isUserSubscribedInCourseAsDrh(
805
                api_get_user_id(),
806
                api_get_course_info()
807
            );
808
809
            // Force user icon for DRH
810
            if ($isDrhOfCourse) {
811
                $addUserTool = true;
812
                foreach ($tools as $tool) {
813
                    if ($tool['name'] === 'user') {
814
                        $addUserTool = false;
815
                        break;
816
                    }
817
                }
818
819
                if ($addUserTool) {
820
                    $tools[] = [
821
                        'c_id' => api_get_course_int_id(),
822
                        'name' => 'user',
823
                        'link' => 'user/user.php',
824
                        'image' => 'members.gif',
825
                        'visibility' => '1',
826
                        'admin' => '0',
827
                        'address' => 'squaregrey.gif',
828
                        'added_tool' => '0',
829
                        'target' => '_self',
830
                        'category' => 'interaction',
831
                        'session_id' => api_get_session_id(),
832
                    ];
833
                }
834
            }
835
836
            if (count($tools) > 0) {
837
                $blocks[] = ['content' => CourseHome::show_tools_category($tools)];
838
            }
839
840
            if ($isDrhOfCourse) {
841
                $drhTool = CourseHome::get_tools_category(TOOL_DRH);
842
                $blocks[] = ['content' => CourseHome::show_tools_category($drhTool)];
843
            }
844
        }
845
846
        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...
847
    }
848
849
    /**
850
     * @return array
851
     */
852
    private function autoLaunch()
853
    {
854
        return;
855
        $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...
856
857
        // Exercise auto-launch
858
        $auto_launch = api_get_course_setting('enable_exercise_auto_launch');
859
860
        if (!empty($auto_launch)) {
861
            $session_id = api_get_session_id();
862
            //Exercise list
863
            if ($auto_launch == 2) {
864
                if (api_is_platform_admin() || api_is_allowed_to_edit()) {
865
                    $showAutoLaunchExerciseWarning = true;
866
                } else {
867
                    $session_key = 'exercise_autolunch_'.$session_id.'_'.api_get_course_int_id().'_'.api_get_user_id();
868
                    $sessionData = Session::read($session_key);
869
                    if (!isset($sessionData)) {
870
                        //redirecting to the Exercise
871
                        $url = api_get_path(WEB_CODE_PATH).'exercise/exercise.php?'.api_get_cidreq().'&id_session='.$session_id;
872
                        $_SESSION[$session_key] = true;
873
874
                        header("Location: $url");
875
                        exit;
876
                    }
877
                }
878
            } else {
879
                $table = \Database::get_course_table(TABLE_QUIZ_TEST);
880
                $course_id = api_get_course_int_id();
881
                $condition = '';
882
                if (!empty($session_id)) {
883
                    $condition = api_get_session_condition($session_id);
884
                    $sql = "SELECT iid FROM $table
885
                            WHERE c_id = $course_id AND autolaunch = 1 $condition
886
                            LIMIT 1";
887
                    $result = \Database::query($sql);
888
                    //If we found nothing in the session we just called the session_id =  0 autolaunch
889
                    if (\Database::num_rows($result) == 0) {
890
                        $condition = '';
891
                    } else {
892
                        //great, there is an specific auto lunch for this session we leave the $condition
893
                    }
894
                }
895
896
                $sql = "SELECT iid FROM $table
897
                        WHERE c_id = $course_id AND autolaunch = 1 $condition
898
                        LIMIT 1";
899
                $result = \Database::query($sql);
900
                if (\Database::num_rows($result) > 0) {
901
                    $data = \Database::fetch_array($result, 'ASSOC');
902
                    if (!empty($data['iid'])) {
903
                        if (api_is_platform_admin() || api_is_allowed_to_edit()) {
904
                            $showAutoLaunchExerciseWarning = true;
905
                        } else {
906
                            $session_key = 'exercise_autolunch_'.$session_id.'_'.api_get_course_int_id().'_'.api_get_user_id();
907
                            if (!isset($_SESSION[$session_key])) {
908
                                //redirecting to the LP
909
                                $url = api_get_path(WEB_CODE_PATH).'exercise/overview.php?'.api_get_cidreq().'&exerciseId='.$data['iid'];
910
911
                                $_SESSION[$session_key] = true;
912
                                header("Location: $url");
913
                                exit;
914
                            }
915
                        }
916
                    }
917
                }
918
            }
919
        }
920
921
        /* Auto launch code */
922
        $showAutoLaunchLpWarning = false;
923
        $auto_launch = api_get_course_setting('enable_lp_auto_launch');
924
        if (!empty($auto_launch)) {
925
            $session_id = api_get_session_id();
926
            //LP list
927
            if ($auto_launch == 2) {
928
                if (api_is_platform_admin() || api_is_allowed_to_edit()) {
929
                    $showAutoLaunchLpWarning = true;
930
                } else {
931
                    $session_key = 'lp_autolunch_'.$session_id.'_'.api_get_course_int_id().'_'.api_get_user_id();
932
                    if (!isset($_SESSION[$session_key])) {
933
                        //redirecting to the LP
934
                        $url = api_get_path(WEB_CODE_PATH).'lp/lp_controller.php?'.api_get_cidreq().'&id_session='.$session_id;
935
                        $_SESSION[$session_key] = true;
936
                        header("Location: $url");
937
                        exit;
938
                    }
939
                }
940
            } else {
941
                $lp_table = \Database::get_course_table(TABLE_LP_MAIN);
942
                $course_id = api_get_course_int_id();
943
                $condition = '';
944
                if (!empty($session_id)) {
945
                    $condition = api_get_session_condition($session_id);
946
                    $sql = "SELECT id FROM $lp_table WHERE c_id = $course_id AND autolunch = 1 $condition LIMIT 1";
947
                    $result = \Database::query($sql);
948
                    //If we found nothing in the session we just called the session_id =  0 autolunch
949
                    if (\Database::num_rows($result) == 0) {
950
                        $condition = '';
951
                    } else {
952
                        //great, there is an specific auto lunch for this session we leave the $condition
953
                    }
954
                }
955
956
                $sql = "SELECT id FROM $lp_table
957
                        WHERE c_id = $course_id AND autolunch = 1 $condition
958
                        LIMIT 1";
959
                $result = \Database::query($sql);
960
                if (\Database::num_rows($result) > 0) {
961
                    $lp_data = \Database::fetch_array($result, 'ASSOC');
962
                    if (!empty($lp_data['id'])) {
963
                        if (api_is_platform_admin() || api_is_allowed_to_edit()) {
964
                            $showAutoLaunchLpWarning = true;
965
                        } else {
966
                            $session_key = 'lp_autolunch_'.$session_id.'_'.api_get_course_int_id().'_'.api_get_user_id();
967
                            if (!isset($_SESSION[$session_key])) {
968
                                //redirecting to the LP
969
                                $url = api_get_path(WEB_CODE_PATH).'lp/lp_controller.php?'.api_get_cidreq().'&action=view&lp_id='.$lp_data['id'];
970
971
                                $_SESSION[$session_key] = true;
972
                                header("Location: $url");
973
                                exit;
974
                            }
975
                        }
976
                    }
977
                }
978
            }
979
        }
980
981
        return [
982
            'show_autolaunch_exercise_warning' => $showAutoLaunchExerciseWarning,
983
            'show_autolaunch_lp_warning' => $showAutoLaunchLpWarning,
984
        ];
985
    }
986
}
987