Passed
Push — master ( aacfc9...8578c1 )
by Julito
09:03
created

HomeController::autoLaunch()   D

Complexity

Conditions 25
Paths 1

Size

Total Lines 132
Code Lines 86

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 25
eloc 86
nc 1
nop 0
dl 0
loc 132
rs 4.1666
c 0
b 0
f 0

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

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