Completed
Push — master ( fdc5ea...16ee5f )
by Julito
32:45
created

HomeController::render2ColumnView()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 4
rs 10
c 0
b 0
f 0
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 Symfony\Component\HttpFoundation\Response;
8
use Symfony\Component\Routing\Annotation\Route;
9
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
10
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
11
use Chamilo\CourseBundle\Entity\CTool;
12
use Display;
13
use CourseHome;
14
use Symfony\Component\HttpFoundation\Request;
15
16
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
17
18
/**
19
 * Class HomeController
20
 * @package Chamilo\CourseBundle\Controller\Home
21
 * @author Julio Montoya <[email protected]>
22
 * @Route("/")
23
 */
24
class HomeController extends ToolBaseController
25
{
26
    /**
27
     * @Route("/", name="course_home")
28
     * @Route("/index.php")
29
     * @Method({"GET"})
30
     *
31
     * @param Request $request
32
     * @return Response
33
     */
34
    public function indexAction(Request $request)
35
    {
36
        $sessionId = api_get_session_id();
37
        $course = $this->getCourse();
38
        $courseCode = $course->getId();
39
        $result = $this->autoLaunch();
40
41
        $showAutoLaunchLpWarning = $result['show_autolaunch_lp_warning'];
42
        $showAutoLaunchExerciseWarning = $result['show_autolaunch_exercise_warning'];
43
44
        if ($showAutoLaunchLpWarning) {
45
            $this->addFlash(
46
                'warning',
47
                $this->trans('TheLPAutoLaunchSettingIsONStudentsWillBeRedirectToAnSpecificLP')
48
            );
49
        }
50
51
        if ($showAutoLaunchExerciseWarning) {
52
            $this->addFlash(
53
                'warning',
54
                $this->trans('TheExerciseAutoLaunchSettingIsONStudentsWillBeRedirectToAnSpecificExercise')
55
            );
56
        }
57
58
        if (true) {
0 ignored issues
show
Bug introduced by
Avoid IF statements that are always true or false
Loading history...
59
            $editIcons = Display::url(
60
                Display::return_icon('edit.png'),
61
                $this->generateUrl(
62
                    'chamilo_course_home_home_iconlist',
63
                    array(
64
                        'course' => api_get_course_id(),
65
                    )
66
                )
67
            );
68
        }
69
70
        $isSpecialCourse = \CourseManager::isSpecialCourse($courseCode);
71
72
        if ($isSpecialCourse) {
73
            $user = $this->getUser();
74
            if (!empty($user)) {
75
                $userId = $this->getUser()->getId();
76
                $autoreg = $request->get('autoreg');
77
                if ($autoreg == 1) {
78
                    \CourseManager::subscribe_user(
79
                        $userId,
80
                        $courseCode,
81
                        STUDENT
82
                    );
83
                }
84
            }
85
        }
86
87
        $homeView = api_get_setting('course.homepage_view');
88
89
        if ($homeView == 'activity' || $homeView == 'activity_big') {
90
            $result = $this->renderActivityView();
91
        } elseif ($homeView == '2column') {
92
            $result = $this->render2ColumnView();
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $result is correct as $this->render2ColumnView() (which targets Chamilo\CourseBundle\Con...er::render2ColumnView()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
93
        } elseif ($homeView == '3column') {
94
            $result = $this->render3ColumnView();
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $result is correct as $this->render3ColumnView() (which targets Chamilo\CourseBundle\Con...er::render3ColumnView()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
95
        } elseif ($homeView == 'vertical_activity') {
96
            $result = $this->renderVerticalActivityView();
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $result is correct as $this->renderVerticalActivityView() (which targets Chamilo\CourseBundle\Con...rVerticalActivityView()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
97
        }
98
99
        $toolList = $result['tool_list'];
100
101
        $introduction = Display::return_introduction_section(
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $introduction is correct as \Display::return_introdu...SE_HOMEPAGE, $toolList) (which targets Display::return_introduction_section()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
102
            TOOL_COURSE_HOMEPAGE,
103
            $toolList
104
        );
105
106
        $sessionInfo = null;
107
        if (api_get_setting('session.show_session_data') == 'true' && $sessionId) {
108
            $sessionInfo = CourseHome::show_session_data($sessionId);
109
        }
110
111
        return $this->render(
112
            'ChamiloCourseBundle:Home:index.html.twig',
113
            array(
114
                'course' => $course,
115
                'session_info' => $sessionInfo,
116
                'icons' => $result['content'],
117
                'edit_icons' => $editIcons,
118
                'introduction_text' => $introduction,
119
                'exercise_warning' => null,
120
                'lp_warning' => null
121
            )
122
        );
123
    }
124
125
    /**
126
     * @param string $title
127
     * @param string $content
128
     * @param string $class
129
     * @return string
130
     */
131 View Code Duplication
    private function return_block($title, $content, $class = null)
132
    {
133
        $html = '<div class="row">
134
                <div class="col-xs-12 col-md-12">
135
                    <div class="title-tools">'.$title.'</div>
136
                </div>
137
            </div>
138
            <div class="row '.$class.'">'.$content.'</div>';
139
140
        return $html;
141
    }
142
143
    /**
144
     * @return array
145
     */
146
    private function renderActivityView()
147
    {
148
        $session_id = api_get_session_id();
149
150
        $urlGenerator = $this->get('router');
151
152
        $content = '';
153
154
        // Start of tools for CourseAdmins (teachers/tutors)
155
        $totalList = array();
156
157
        if ($session_id == 0 &&
158
            api_is_course_admin() &&
159
            api_is_allowed_to_edit(null, true)
160
        ) {
161
            $list = CourseHome::get_tools_category(TOOL_AUTHORING);
162
            $result = CourseHome::show_tools_category($urlGenerator, $list);
163
164
            $content .= $this->return_block(get_lang('Authoring'), $result['content']);
165
166
            $totalList = $result['tool_list'];
167
168
            $list = CourseHome::get_tools_category(TOOL_INTERACTION);
169
            $list2 = CourseHome::get_tools_category(TOOL_COURSE_PLUGIN);
170
            $list = array_merge($list, $list2);
171
            $result =  CourseHome::show_tools_category($urlGenerator, $list);
172
            $totalList = array_merge($totalList, $result['tool_list']);
173
174
            $content .= $this->return_block(get_lang('Interaction'), $result['content']);
175
176
            $list = CourseHome::get_tools_category(TOOL_ADMIN_PLATFORM);
177
            $totalList = array_merge($totalList, $list);
178
            $result = CourseHome::show_tools_category($urlGenerator, $list);
179
            $totalList = array_merge($totalList, $result['tool_list']);
180
181
            $content .= $this->return_block(get_lang('Administration'), $result['content']);
182
183
        } elseif (api_is_coach()) {
184
            $content .=  '<div class="row">';
185
            $list = CourseHome::get_tools_category(TOOL_STUDENT_VIEW);
186
            $result = CourseHome::show_tools_category($urlGenerator, $list);
187
            $content .= $result['content'];
188
            $totalList = array_merge($totalList, $result['tool_list']);
189
            $content .= '</div>';
190
        } else {
191
            $list = CourseHome::get_tools_category(TOOL_STUDENT_VIEW);
192
            if (count($list) > 0) {
193
                $content .= '<div class="row">';
194
                $result = CourseHome::show_tools_category($urlGenerator, $list);
195
                $content .= $result['content'];
196
                $totalList = array_merge($totalList, $result['tool_list']);
197
                $content .= '</div>';
198
            }
199
        }
200
201
        return array(
202
            'content' => $content,
203
            'tool_list' => $totalList
204
        );
205
    }
206
207
    private function render2ColumnView()
208
    {
209
210
    }
211
212
    private function render3ColumnView()
213
    {
214
215
    }
216
217
    private function renderVerticalActivityView()
218
    {
219
220
    }
221
222
    /**
223
     * @return array
224
     */
225
    private function autoLaunch()
226
    {
227
        return;
228
        $showAutoLaunchExerciseWarning = false;
0 ignored issues
show
Unused Code introduced by
$showAutoLaunchExerciseWarning = false; does not seem to be 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...
229
230
        // Exercise auto-launch
231
        $auto_launch = api_get_course_setting('enable_exercise_auto_launch');
232
233 View Code Duplication
        if (!empty($auto_launch)) {
234
            $session_id = api_get_session_id();
235
            //Exercise list
236
            if ($auto_launch == 2) {
237
                if (api_is_platform_admin() || api_is_allowed_to_edit()) {
238
                    $showAutoLaunchExerciseWarning = true;
239
                } else {
240
                    $session_key = 'exercise_autolunch_'.$session_id.'_'.api_get_course_int_id().'_'.api_get_user_id();
241
                    $sessionData = Session::read($session_key);
242
                    if (!isset($sessionData)) {
243
                        //redirecting to the Exercise
244
                        $url = api_get_path(WEB_CODE_PATH).'exercice/exercice.php?'.api_get_cidreq().'&id_session='.$session_id;
245
                        $_SESSION[$session_key] = true;
246
247
                        header("Location: $url");
248
                        exit;
249
                    }
250
                }
251
            } else {
252
                $table = \Database::get_course_table(TABLE_QUIZ_TEST);
253
                $course_id = api_get_course_int_id();
254
                $condition = '';
255
                if (!empty($session_id)) {
256
                    $condition =  api_get_session_condition($session_id);
257
                    $sql = "SELECT iid FROM $table
258
                            WHERE c_id = $course_id AND autolaunch = 1 $condition
259
                            LIMIT 1";
260
                    $result = \Database::query($sql);
261
                    //If we found nothing in the session we just called the session_id =  0 autolaunch
262
                    if (\Database::num_rows($result) ==  0) {
263
                        $condition = '';
264
                    } else {
0 ignored issues
show
Unused Code introduced by
This else statement is empty and can be removed.

This check looks for the else branches of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These else branches can be removed.

if (rand(1, 6) > 3) {
print "Check failed";
} else {
    //print "Check succeeded";
}

could be turned into

if (rand(1, 6) > 3) {
    print "Check failed";
}

This is much more concise to read.

Loading history...
265
                        //great, there is an specific auto lunch for this session we leave the $condition
266
                    }
267
                }
268
269
                $sql = "SELECT iid FROM $table
270
                        WHERE c_id = $course_id AND autolaunch = 1 $condition
271
                        LIMIT 1";
272
                $result = \Database::query($sql);
273
                if (\Database::num_rows($result) >  0) {
274
                    $data = \Database::fetch_array($result, 'ASSOC');
275
                    if (!empty($data['iid'])) {
276
                        if (api_is_platform_admin() || api_is_allowed_to_edit()) {
277
                            $showAutoLaunchExerciseWarning = true;
278
                        } else {
279
                            $session_key = 'exercise_autolunch_'.$session_id.'_'.api_get_course_int_id().'_'.api_get_user_id();
280
                            if (!isset($_SESSION[$session_key])) {
281
                                //redirecting to the LP
282
                                $url = api_get_path(WEB_CODE_PATH).'exercice/overview.php?'.api_get_cidreq().'&exerciseId='.$data['iid'];
283
284
                                $_SESSION[$session_key] = true;
285
                                header("Location: $url");
286
                                exit;
287
                            }
288
                        }
289
                    }
290
                }
291
            }
292
        }
293
294
        /* Auto launch code */
295
        $showAutoLaunchLpWarning = false;
296
        $auto_launch = api_get_course_setting('enable_lp_auto_launch');
297 View Code Duplication
        if (!empty($auto_launch)) {
298
            $session_id = api_get_session_id();
299
            //LP list
300
            if ($auto_launch == 2) {
301
                if (api_is_platform_admin() || api_is_allowed_to_edit()) {
302
                    $showAutoLaunchLpWarning = true;
303
                } else {
304
                    $session_key = 'lp_autolunch_'.$session_id.'_'.api_get_course_int_id().'_'.api_get_user_id();
305
                    if (!isset($_SESSION[$session_key])) {
306
                        //redirecting to the LP
307
                        $url = api_get_path(WEB_CODE_PATH).'newscorm/lp_controller.php?'.api_get_cidreq().'&id_session='.$session_id;
308
                        $_SESSION[$session_key] = true;
309
                        header("Location: $url");
310
                        exit;
311
                    }
312
                }
313
            } else {
314
                $lp_table = \Database::get_course_table(TABLE_LP_MAIN);
315
                $course_id = api_get_course_int_id();
316
                $condition = '';
317
                if (!empty($session_id)) {
318
                    $condition =  api_get_session_condition($session_id);
319
                    $sql = "SELECT id FROM $lp_table WHERE c_id = $course_id AND autolunch = 1 $condition LIMIT 1";
320
                    $result = \Database::query($sql);
321
                    //If we found nothing in the session we just called the session_id =  0 autolunch
322
                    if (\Database::num_rows($result) ==  0) {
323
                        $condition = '';
324
                    } else {
0 ignored issues
show
Unused Code introduced by
This else statement is empty and can be removed.

This check looks for the else branches of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These else branches can be removed.

if (rand(1, 6) > 3) {
print "Check failed";
} else {
    //print "Check succeeded";
}

could be turned into

if (rand(1, 6) > 3) {
    print "Check failed";
}

This is much more concise to read.

Loading history...
325
                        //great, there is an specific auto lunch for this session we leave the $condition
326
                    }
327
                }
328
329
                $sql = "SELECT id FROM $lp_table
330
                        WHERE c_id = $course_id AND autolunch = 1 $condition
331
                        LIMIT 1";
332
                $result = \Database::query($sql);
333
                if (\Database::num_rows($result) >  0) {
334
                    $lp_data = \Database::fetch_array($result, 'ASSOC');
335
                    if (!empty($lp_data['id'])) {
336
                        if (api_is_platform_admin() || api_is_allowed_to_edit()) {
337
                            $showAutoLaunchLpWarning = true;
338
                        } else {
339
                            $session_key = 'lp_autolunch_'.$session_id.'_'.api_get_course_int_id().'_'.api_get_user_id();
340
                            if (!isset($_SESSION[$session_key])) {
341
                                //redirecting to the LP
342
                                $url = api_get_path(WEB_CODE_PATH).'newscorm/lp_controller.php?'.api_get_cidreq().'&action=view&lp_id='.$lp_data['id'];
343
344
                                $_SESSION[$session_key] = true;
345
                                header("Location: $url");
346
                                exit;
347
                            }
348
                        }
349
                    }
350
                }
351
            }
352
        }
353
354
        return array(
355
            'show_autolaunch_exercise_warning' => $showAutoLaunchExerciseWarning,
356
            'show_autolaunch_lp_warning' => $showAutoLaunchLpWarning
357
        );
358
    }
359
360
    /**
361
     * @param string $courseCode
362
     * @param string $fileName
363
     * @return \Symfony\Component\HttpFoundation\BinaryFileResponse
364
     */
365
    public function getFileAction($courseCode, $fileName)
366
    {
367
        $courseInfo = api_get_course_info($courseCode);
368
        $sessionId = $this->getRequest()->get('id_session');
0 ignored issues
show
Deprecated Code introduced by
The method Symfony\Bundle\Framework...ontroller::getRequest() has been deprecated with message: since version 2.4, to be removed in 3.0. Ask Symfony to inject the Request object into your controller method instead by type hinting it in the method's signature.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
369
370
        $docId = \DocumentManager::get_document_id($courseInfo, "/".$fileName);
371
372
        $filePath = null;
373
374
        if ($docId) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $docId of type integer|false is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
375
            $isVisible = \DocumentManager::is_visible_by_id($docId, $courseInfo, $sessionId, api_get_user_id());
376
            $documentData = \DocumentManager::get_document_data_by_id($docId, $courseCode);
377
            $filePath = $documentData['absolute_path'];
378
            event_download($filePath);
379
        }
380
381
        if (!api_is_allowed_to_edit() && !$isVisible) {
382
            $this->abort(500);
383
        }
384
        return $this->sendFile($filePath);
385
    }
386
387
    /**
388
     * @Route("/show/{iconId}")
389
     * @Method({"GET"})
390
     * @param $iconId
391
     * @return null|string
392
     */
393
    public function showIconAction($iconId)
394
    {
395
        $entityManager = $this->getDoctrine()->getManager();
396
        $criteria = array('cId' => api_get_course_int_id(), 'id' => $iconId);
397
        $tool = $this->getRepository(
398
            'Chamilo\CourseBundle\Entity\CTool'
399
        )->findOneBy($criteria);
400
        if ($tool) {
401
            $tool->setVisibility(1);
402
        }
403
        $entityManager->persist($tool);
404
        //$entityManager->flush();
405
        return Display::return_message(get_lang('Visible'), 'confirmation');
406
    }
407
408
    /**
409
     * @Route("/hide/{iconId}")
410
     * @Method({"GET"})
411
     * @param $iconId
412
     * @return null|string
413
     */
414 View Code Duplication
    public function hideIconAction($iconId)
415
    {
416
        if (!$this->isCourseTeacher()) {
417
            return $this->abort(404);
418
        }
419
420
        $entityManager = $this->getDoctrine()->getManager();
421
        $criteria = array('cId' => api_get_course_int_id(), 'id' => $iconId);
422
        $tool = $this->getRepository(
423
            'Chamilo\CourseBundle\Entity\CTool'
424
        )->findOneBy($criteria);
425
        if ($tool) {
426
            $tool->setVisibility(0);
427
        }
428
        $entityManager->persist($tool);
429
        //$entityManager->flush();
430
        return Display::return_message(get_lang('ToolIsNowHidden'), 'confirmation');
431
    }
432
433
    /**
434
     * @Route("/delete/{iconId}")
435
     * @Method({"GET"})
436
     * @param $iconId
437
     * @return null|string
438
     */
439 View Code Duplication
    public function deleteIcon($iconId)
440
    {
441
        if (!$this->isCourseTeacher()) {
442
            return $this->abort(404);
443
        }
444
445
        $entityManager = $this->getDoctrine()->getManager();
446
        $criteria = array('cId' => api_get_course_int_id(), 'id' => $iconId, 'added_tool' => 1);
447
        $tool = $this->getRepository(
448
            'Chamilo\CourseBundle\Entity\CTool'
449
        )->findOneBy($criteria);
450
        $entityManager->remove($tool);
451
        //$entityManager->flush();
452
        return Display::return_message(get_lang('Deleted'), 'confirmation');
453
    }
454
455
    /**
456
     * @Route("/icon_list")
457
     * @Method({"GET"})
458
     * @param Request $request
459
     */
460
    public function iconListAction(Request $request)
461
    {
462
        $em = $this->getDoctrine()->getManager();
463
        $repo = $this->getDoctrine()->getRepository(
464
            'ChamiloCourseBundle:CTool'
465
        );
466
467
        $sessionId = intval($request->get('id_session'));
468
        $itemsFromSession = array();
469
        if (!empty($sessionId)) {
470
            $query = $repo->createQueryBuilder('a');
471
            $query->select('s');
472
            $query->from('Chamilo\CourseBundle\Entity\CTool', 's');
473
            $query->where('s.cId  = :courseId AND s.sessionId = :sessionId')
474
                ->setParameters(
475
                    array(
476
                        'courseId' => $this->getCourse()->getId(),
477
                        'sessionId' => $sessionId
478
                    )
479
                );
480
            $itemsFromSession = $query->getQuery()->getResult();
481
482
            $itemNameList = array();
483
            foreach ($itemsFromSession as $item) {
484
                $itemNameList[] = $item->getName();
485
            }
486
487
            //$itemsFromSession = $this->getRepository()->findBy($criteria);
488
            $query = $repo->createQueryBuilder('a');
489
            $query->select('s');
490
            $query->from('Chamilo\CourseBundle\Entity\CTool', 's');
491
            $query->where('s.cId  = :courseId AND s.sessionId = 0')
492
                ->setParameters(
493
                    array(
494
                        'courseId' => $this->getCourse()->getId()
495
                    )
496
                );
497
            if (!empty($itemNameList)) {
498
                $query->andWhere($query->expr()->notIn('s.name', $itemNameList));
499
            }
500
            $itemsFromCourse = $query->getQuery()->getResult();
501
        } else {
502
            $criteria = array('cId' => $this->getCourse()->getId(), 'sessionId' => 0);
503
            $itemsFromCourse = $repo->findBy($criteria);
504
        }
505
506
507
        return $this->render(
508
            '@ChamiloCourse/Home/list.html.twig',
509
            [
510
                'items_from_course' => $itemsFromCourse,
511
                'items_from_session' => $itemsFromSession,
512
                'links' => '',
513
            ]
514
        );
515
    }
516
517
    /**
518
     *
519
     * @Route("/{itemName}/add")
520
     * @Method({"GET|POST"})
521
     * @param $itemName
522
     * @return mixed
523
     */
524
    public function addIconAction($itemName)
525
    {
526
        if (!$this->isCourseTeacher()) {
527
            return $this->abort(404);
528
        }
529
530
        $sessionId = intval($this->getRequest()->get('id_session'));
0 ignored issues
show
Deprecated Code introduced by
The method Symfony\Bundle\Framework...ontroller::getRequest() has been deprecated with message: since version 2.4, to be removed in 3.0. Ask Symfony to inject the Request object into your controller method instead by type hinting it in the method's signature.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
531
532
        if (empty($sessionId)) {
533
            return $this->abort(500);
534
        }
535
536
        $criteria = array('cId' => $this->getCourse()->getId(), 'sessionId' => 0, 'name' => $itemName);
537
        $itemFromDatabase = $this->getRepository()->findOneBy($criteria);
538
539
        if (!$itemFromDatabase) {
540
            $this->createNotFoundException();
541
        }
542
        /** @var CTool $item */
543
        $item = clone $itemFromDatabase;
544
        $item->setId(null);
545
        $item->setSessionId($sessionId);
546
        $form = $this->createForm($this->getFormType(), $item);
547
548
        $form->handleRequest($this->getRequest());
0 ignored issues
show
Deprecated Code introduced by
The method Symfony\Bundle\Framework...ontroller::getRequest() has been deprecated with message: since version 2.4, to be removed in 3.0. Ask Symfony to inject the Request object into your controller method instead by type hinting it in the method's signature.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
549
550
        if ($form->isValid()) {
551
552
            $query = $this->getDoctrine()->getManager()->createQueryBuilder('a');
553
            $query->select('MAX(s.id) as id');
554
            $query->from('Chamilo\CourseBundle\Entity\CTool', 's');
555
            $query->where('s.cId  = :courseId')->setParameter('courseId', $this->getCourse()->getId());
556
            $result = $query->getQuery()->getArrayResult();
557
            $maxId = $result[0]['id'] + 1;
558
            $item->setId($maxId);
559
560
            $entityManager = $this->getDoctrine()->getManager();
561
            $entityManager->persist($item);
562
            $entityManager->flush();
563
            $customIcon = $item->getCustomIcon();
564
            if (!empty($customIcon)) {
565
                $item->createGrayIcon($this->get('imagine'));
566
            }
567
568
            $this->get('session')->getFlashBag()->add('success', "Added");
569
            $url = $this->generateUrl('course_home.controller:iconListAction', array('id_session' => $sessionId));
570
            return $this->redirect($url);
571
        }
572
573
        $this->getTemplate()->assign('item', $item);
574
        $this->getTemplate()->assign('form', $form->createView());
575
        $this->getTemplate()->assign('links', $this->generateLinks());
576
577
        return $this->render('@ChamiloCourse/Home/add.html.twig');
578
579
    }
580
581
    /**
582
     * @Route("/{itemId}/edit")
583
     * @Method({"GET"})
584
     */
585
    public function editIconAction($itemId)
586
    {
587
        if (!$this->isCourseTeacher()) {
588
            return $this->abort(404);
589
        }
590
591
        $sessionId = intval($this->getRequest()->get('id_session'));
0 ignored issues
show
Deprecated Code introduced by
The method Symfony\Bundle\Framework...ontroller::getRequest() has been deprecated with message: since version 2.4, to be removed in 3.0. Ask Symfony to inject the Request object into your controller method instead by type hinting it in the method's signature.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
592
593
        $criteria = array('cId' => $this->getCourse()->getId(), 'id' => $itemId);
594
        /** @var CTool $item */
595
        $item = $this->getRepository()->findOneBy($criteria);
596
597
        $form = $this->createForm($this->getFormType(), $item);
598
        $form->handleRequest($this->getRequest());
0 ignored issues
show
Deprecated Code introduced by
The method Symfony\Bundle\Framework...ontroller::getRequest() has been deprecated with message: since version 2.4, to be removed in 3.0. Ask Symfony to inject the Request object into your controller method instead by type hinting it in the method's signature.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
599
600
        if ($form->isValid()) {
601
            $entityManager = $this->getDoctrine()->getManager();
602
            $entityManager->persist($item);
603
            $entityManager->flush();
604
605
            $customIcon = $item->getCustomIcon();
606
            if (!empty($customIcon)) {
607
                $item->createGrayIcon($this->get('imagine'));
608
            }
609
610
            $this->get('session')->getFlashBag()->add('success', "Updated");
611
            $url = $this->generateUrl('course_home.controller:iconListAction', array('id_session' => $sessionId));
612
            return $this->redirect($url);
613
        }
614
615
        $this->getTemplate()->assign('item', $item);
616
        $this->getTemplate()->assign('form', $form->createView());
617
        $this->getTemplate()->assign('links', $this->generateLinks());
618
619
        return $this->render('@ChamiloCourse/Home/edit.html.twig');
620
    }
621
622
    /**
623
     * @Route("/{itemId}/delete")
624
     * @Method({"GET"})
625
     */
626
    public function deleteIconAction($itemId)
627
    {
628
        if (!$this->isCourseTeacher()) {
629
            return $this->abort(404);
630
        }
631
632
        $criteria = array('cId' => $this->getCourse()->getId(), 'id' => $itemId);
633
634
        /** @var CTool $item */
635
        $item = $this->getRepository()->findOneBy($criteria);
636
        $entityManager = $this->getDoctrine()->getManager();
637
        $sessionId = $item->getSessionId();
638
        if (!empty($sessionId)) {
639
            $entityManager->remove($item);
640
        } else {
641
            $item->setCustomIcon(null);
642
            $entityManager->persist($item);
643
        }
644
        $entityManager->flush();
645
        $this->get('session')->getFlashBag()->add('success', "Deleted");
646
647
        $this->getTemplate()->assign('links', $this->generateLinks());
648
        $url = $this->generateUrl('course_home.controller:iconListAction');
649
        return $this->redirect($url);
650
    }
651
}
652