Completed
Push — master ( a5288e...b5a1ce )
by Julito
29:24 queued 11:53
created

CourseHomeController::editIconAction()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 36
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 21
c 0
b 0
f 0
nc 4
nop 1
dl 0
loc 36
rs 9.584
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
namespace Chamilo\CoreBundle\Controller;
5
6
use Chamilo\CoreBundle\ToolChain;
7
use Chamilo\CourseBundle\Controller\ToolBaseController;
8
use Chamilo\CourseBundle\Entity\CTool;
9
use Chamilo\CourseBundle\Repository\CToolRepository;
10
use Chamilosession as Session;
11
use CourseManager;
12
use Database;
13
use Display;
14
use Event;
15
use ExtraFieldValue;
16
use Security;
17
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Entity;
18
use Symfony\Component\HttpFoundation\Request;
19
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
20
use Symfony\Component\Routing\Annotation\Route;
21
22
/**
23
 * Class CourseHomeController.
24
 *
25
 * @author Julio Montoya <[email protected]>
26
 *
27
 * @Route("/courses")
28
 */
29
class CourseHomeController extends ToolBaseController
30
{
31
    /**
32
     * @Route("/{cid}/home", name="chamilo_core_course_home")
33
     *
34
     * @Entity("course", expr="repository.find(cid)")
35
     */
36
    public function indexAction(Request $request, CToolRepository $toolRepository, ToolChain $toolChain)
37
    {
38
        $this->autoLaunch();
39
        $course = $this->getCourse();
40
41
        $js = '<script>'.api_get_language_translate_html().'</script>';
42
        $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...
43
44
        $userId = $this->getUser()->getId();
45
        $courseCode = $course->getCode();
46
        $courseId = $course->getId();
47
        $sessionId = $this->getSessionId();
48
49
        if (api_is_invitee()) {
50
            $isInASession = $sessionId > 0;
51
            $isSubscribed = CourseManager::is_user_subscribed_in_course(
52
                $userId,
53
                $courseCode,
54
                $isInASession,
55
                $sessionId
56
            );
57
58
            if (!$isSubscribed) {
59
                api_not_allowed(true);
60
            }
61
        }
62
63
        // Deleting group session
64
        Session::erase('toolgroup');
65
        Session::erase('_gid');
66
67
        $isSpecialCourse = CourseManager::isSpecialCourse($courseId);
68
69
        if ($isSpecialCourse) {
70
            if (isset($_GET['autoreg']) && $_GET['autoreg'] == 1) {
71
                if (CourseManager::subscribeUser($userId, $courseCode, STUDENT)) {
72
                    Session::write('is_allowed_in_course', true);
73
                }
74
            }
75
        }
76
77
        $action = !empty($_GET['action']) ? Security::remove_XSS($_GET['action']) : '';
78
        if ($action == 'subscribe') {
79
            if (Security::check_token('get')) {
80
                Security::clear_token();
81
                $result = CourseManager::autoSubscribeToCourse($courseCode);
82
                if ($result) {
83
                    if (CourseManager::is_user_subscribed_in_course($userId, $courseCode)) {
84
                        Session::write('is_allowed_in_course', true);
85
                    }
86
                }
87
                header('Location: '.api_get_self());
88
                exit;
89
            }
90
        }
91
92
        /*  STATISTICS */
93
        if (!isset($coursesAlreadyVisited[$courseCode])) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $coursesAlreadyVisited does not exist. Did you maybe mean $course?
Loading history...
94
            Event::accessCourse();
95
            $coursesAlreadyVisited[$courseCode] = 1;
0 ignored issues
show
Comprehensibility Best Practice introduced by
$coursesAlreadyVisited was never initialized. Although not strictly required by PHP, it is generally a good practice to add $coursesAlreadyVisited = array(); before regardless.
Loading history...
96
            Session::write('coursesAlreadyVisited', $coursesAlreadyVisited);
97
        }
98
99
        $logInfo = [
100
            'tool' => 'course-main',
101
            'action' => $action,
102
        ];
103
        Event::registerLog($logInfo);
104
105
        /*	Introduction section (editable by course admins) */
106
        /*$introduction = Display::return_introduction_section(
107
            TOOL_COURSE_HOMEPAGE,
108
            [
109
                'CreateDocumentWebDir' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/document/',
110
                'CreateDocumentDir' => 'document/',
111
                'BaseHref' => api_get_path(WEB_COURSE_PATH).api_get_course_path().'/',
112
            ]
113
        );*/
114
115
        $qb = $toolRepository->getResourcesByCourse($course, $this->getSession());
116
        $result = $qb->getQuery()->getResult();
117
118
        $tools = [];
119
        /** @var CTool $item */
120
        foreach ($result as $item) {
121
            $toolModel = $toolChain->getToolFromName($item->getTool()->getName());
122
            // Dont show admin links.
123
            if ($toolModel->getAdmin()) {
124
                continue;
125
            }
126
127
            if ($toolModel->getCategory() === 'admin' && !$this->isGranted('ROLE_CURRENT_COURSE_TEACHER')) {
128
                continue;
129
            }
130
            $tools[$item->getCategory()][] = $item;
131
        }
132
133
        // Get session-career diagram
134
        $diagram = '';
135
        $allow = api_get_configuration_value('allow_career_diagram');
136
        if ($allow === true) {
137
            $htmlHeadXtra[] = api_get_js('jsplumb2.js');
138
            $extra = new ExtraFieldValue('session');
139
            $value = $extra->get_values_by_handler_and_field_variable(
140
                api_get_session_id(),
141
                'external_career_id'
142
            );
143
144
            if (!empty($value) && isset($value['value'])) {
145
                $careerId = $value['value'];
146
                $extraFieldValue = new ExtraFieldValue('career');
147
                $item = $extraFieldValue->get_item_id_from_field_variable_and_field_value(
148
                    'external_career_id',
149
                    $careerId,
150
                    false,
151
                    false,
152
                    false
153
                );
154
155
                if (!empty($item) && isset($item['item_id'])) {
156
                    $careerId = $item['item_id'];
157
                    $career = new Career();
0 ignored issues
show
Bug introduced by
The type Chamilo\CoreBundle\Controller\Career was not found. Did you mean Career? If so, make sure to prefix the type with \.
Loading history...
158
                    $careerInfo = $career->get($careerId);
159
                    if (!empty($careerInfo)) {
160
                        $extraFieldValue = new ExtraFieldValue('career');
161
                        $item = $extraFieldValue->get_values_by_handler_and_field_variable(
162
                            $careerId,
163
                            'career_diagram',
164
                            false,
165
                            false,
166
                            false
167
                        );
168
169
                        if (!empty($item) && isset($item['value']) && !empty($item['value'])) {
170
                            /** @var Graph $graph */
171
                            $graph = UnserializeApi::unserialize(
0 ignored issues
show
Bug introduced by
The type Chamilo\CoreBundle\Controller\UnserializeApi was not found. Did you mean UnserializeApi? If so, make sure to prefix the type with \.
Loading history...
172
                                'career',
173
                                $item['value']
174
                            );
175
                            $diagram = Career::renderDiagram($careerInfo, $graph);
176
                        }
177
                    }
178
                }
179
            }
180
        }
181
182
        // Deleting the objects
183
        Session::erase('_gid');
184
        Session::erase('oLP');
185
        Session::erase('lpobject');
186
        api_remove_in_gradebook();
187
        \Exercise::cleanSessionVariables();
188
        \DocumentManager::removeGeneratedAudioTempFile();
189
190
        return $this->render(
191
            '@ChamiloTheme/Course/home.html.twig',
192
            [
193
                'course' => $course,
194
                'diagram' => $diagram,
195
               // 'session_info' => $sessionInfo,
196
                'tools' => $tools,
197
                //'edit_icons' => $editIcons,
198
                //'introduction_text' => $introduction,
199
                'exercise_warning' => null,
200
                'lp_warning' => null,
201
            ]
202
        );
203
    }
204
205
    /**
206
     * @Route("/{cid}/tool/{toolId}", name="chamilo_core_course_redirect_tool")
207
     */
208
    public function redirectTool($toolId, ToolChain $toolChain)
209
    {
210
        $criteria = ['id' => $toolId];
211
        /** @var CTool $tool */
212
        $tool = $this->getDoctrine()->getRepository('Chamilo\CourseBundle\Entity\CTool')->findOneBy($criteria);
213
214
        if (null === $tool) {
215
            throw new NotFoundHttpException($this->trans('Tool not found'));
216
        }
217
218
        $tool = $toolChain->getToolFromName($tool->getTool()->getName());
219
        $url = $tool->getLink().'?'.$this->getCourseUrlQuery();
220
221
        return $this->redirect($url);
222
    }
223
224
    /**
225
     * @return array
226
     */
227
    private function autoLaunch()
228
    {
229
        /* Auto launch code */
230
        $autoLaunchWarning = '';
231
        $showAutoLaunchLpWarning = false;
232
        $course_id = api_get_course_int_id();
233
        $lpAutoLaunch = api_get_course_setting('enable_lp_auto_launch');
234
        $session_id = api_get_session_id();
235
        $allowAutoLaunchForCourseAdmins = api_is_platform_admin() || api_is_allowed_to_edit(true, true) || api_is_coach();
236
237
        if (!empty($lpAutoLaunch)) {
238
            if ($lpAutoLaunch == 2) {
239
                // LP list
240
                if ($allowAutoLaunchForCourseAdmins) {
241
                    $showAutoLaunchLpWarning = true;
242
                } else {
243
                    $session_key = 'lp_autolaunch_'.$session_id.'_'.api_get_course_int_id().'_'.api_get_user_id();
244
                    if (!isset($_SESSION[$session_key])) {
245
                        // Redirecting to the LP
246
                        $url = api_get_path(WEB_CODE_PATH).'lp/lp_controller.php?'.api_get_cidreq();
247
                        $_SESSION[$session_key] = true;
248
                        header("Location: $url");
249
                        exit;
250
                    }
251
                }
252
            } else {
253
                $lp_table = Database::get_course_table(TABLE_LP_MAIN);
254
                $condition = '';
255
                if (!empty($session_id)) {
256
                    $condition = api_get_session_condition($session_id);
257
                    $sql = "SELECT id FROM $lp_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
                    }
265
                }
266
267
                $sql = "SELECT id FROM $lp_table
268
                        WHERE c_id = $course_id AND autolaunch = 1 $condition
269
                        LIMIT 1";
270
                $result = Database::query($sql);
271
                if (Database::num_rows($result) > 0) {
272
                    $lp_data = Database::fetch_array($result, 'ASSOC');
273
                    if (!empty($lp_data['id'])) {
274
                        if ($allowAutoLaunchForCourseAdmins) {
275
                            $showAutoLaunchLpWarning = true;
276
                        } else {
277
                            $session_key = 'lp_autolaunch_'.$session_id.'_'.api_get_course_int_id().'_'.api_get_user_id();
278
                            if (!isset($_SESSION[$session_key])) {
279
                                // Redirecting to the LP
280
                                $url = api_get_path(WEB_CODE_PATH).'lp/lp_controller.php?'.api_get_cidreq().'&action=view&lp_id='.$lp_data['id'];
281
282
                                $_SESSION[$session_key] = true;
283
                                header("Location: $url");
284
                                exit;
285
                            }
286
                        }
287
                    }
288
                }
289
            }
290
        }
291
292
        if ($showAutoLaunchLpWarning) {
293
            $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.');
294
        }
295
296
        $forumAutoLaunch = api_get_course_setting('enable_forum_auto_launch');
297
        if ($forumAutoLaunch == 1) {
298
            if ($allowAutoLaunchForCourseAdmins) {
299
                if (empty($autoLaunchWarning)) {
300
                    $autoLaunchWarning = get_lang('The forum\'s auto-launch setting is on. Students will be redirected to the forum tool when entering this course.');
301
                }
302
            } else {
303
                $url = api_get_path(WEB_CODE_PATH).'forum/index.php?'.api_get_cidreq();
304
                header("Location: $url");
305
                exit;
306
            }
307
        }
308
309
        if (api_get_configuration_value('allow_exercise_auto_launch')) {
310
            $exerciseAutoLaunch = (int) api_get_course_setting('enable_exercise_auto_launch');
311
            if ($exerciseAutoLaunch == 2) {
312
                if ($allowAutoLaunchForCourseAdmins) {
313
                    if (empty($autoLaunchWarning)) {
314
                        $autoLaunchWarning = get_lang(
315
                            'TheExerciseAutoLaunchSettingIsONStudentsWillBeRedirectToTheExerciseList'
316
                        );
317
                    }
318
                } else {
319
                    // Redirecting to the document
320
                    $url = api_get_path(WEB_CODE_PATH).'exercise/exercise.php?'.api_get_cidreq();
321
                    header("Location: $url");
322
                    exit;
323
                }
324
            } elseif ($exerciseAutoLaunch == 1) {
325
                if ($allowAutoLaunchForCourseAdmins) {
326
                    if (empty($autoLaunchWarning)) {
327
                        $autoLaunchWarning = get_lang(
328
                            'TheExerciseAutoLaunchSettingIsONStudentsWillBeRedirectToAnSpecificExercise'
329
                        );
330
                    }
331
                } else {
332
                    // Redirecting to an exercise
333
                    $table = Database::get_course_table(TABLE_QUIZ_TEST);
334
                    $condition = '';
335
                    if (!empty($session_id)) {
336
                        $condition = api_get_session_condition($session_id);
337
                        $sql = "SELECT iid FROM $table
338
                        WHERE c_id = $course_id AND autolaunch = 1 $condition
339
                        LIMIT 1";
340
                        $result = Database::query($sql);
341
                        // If we found nothing in the session we just called the session_id = 0 autolaunch
342
                        if (Database::num_rows($result) == 0) {
343
                            $condition = '';
344
                        }
345
                    }
346
347
                    $sql = "SELECT iid FROM $table
348
                    WHERE c_id = $course_id AND autolaunch = 1 $condition
349
                    LIMIT 1";
350
                    $result = Database::query($sql);
351
                    if (Database::num_rows($result) > 0) {
352
                        $row = Database::fetch_array($result, 'ASSOC');
353
                        $exerciseId = $row['iid'];
354
                        $url = api_get_path(WEB_CODE_PATH).
355
                            'exercise/overview.php?exerciseId='.$exerciseId.'&'.api_get_cidreq();
356
                        header("Location: $url");
357
                        exit;
358
                    }
359
                }
360
            }
361
        }
362
363
        $documentAutoLaunch = api_get_course_setting('enable_document_auto_launch');
364
        if ($documentAutoLaunch == 1) {
365
            if ($allowAutoLaunchForCourseAdmins) {
366
                if (empty($autoLaunchWarning)) {
367
                    $autoLaunchWarning = get_lang('The document auto-launch feature configuration is enabled. Learners will be automatically redirected to document tool.');
368
                }
369
            } else {
370
                // Redirecting to the document
371
                $url = api_get_path(WEB_CODE_PATH).'document/document.php?'.api_get_cidreq();
372
                header("Location: $url");
373
                exit;
374
            }
375
        }
376
377
        /*	SWITCH TO A DIFFERENT HOMEPAGE VIEW
378
         the setting homepage_view is adjustable through
379
         the platform administration section */
380
        if (!empty($autoLaunchWarning)) {
381
            $this->addFlash(
382
            Display::return_message(
383
                $autoLaunchWarning,
384
                'warning'
385
            ));
386
        }
387
    }
388
}
389