Completed
Push — master ( 82664b...176635 )
by Julito
88:10 queued 58:03
created

UserPortalController::indexAction()   C

Complexity

Conditions 7
Paths 7

Size

Total Lines 89
Code Lines 52

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 52
nc 7
nop 4
dl 0
loc 89
rs 6.5134
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/* For licensing terms, see /license.txt */
3
4
namespace Chamilo\CoreBundle\Controller;
5
6
use Chamilo\CoreBundle\Framework\PageController;
7
use Chamilo\CoreBundle\Controller\BaseController;
8
use Symfony\Component\HttpFoundation\BinaryFileResponse;
9
use Symfony\Component\HttpFoundation\Response;
10
use Symfony\Component\HttpFoundation\Request;
11
use Symfony\Component\HttpFoundation\StreamedResponse;
12
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
13
use Symfony\Component\HttpKernel\HttpKernelInterface;
14
use Symfony\Component\Finder\Finder;
15
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
16
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
17
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
18
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
19
20
/**
21
 * Class UserPortalController
22
 * author Julio Montoya <[email protected]>
23
 * @package Chamilo\CoreBundle\Controller
24
 */
25
class UserPortalController extends BaseController
26
{
27
    /**
28
     * @Route("/add_course", name="add_course")
29
     * @Method({"GET|POST"})
30
     * @Security("has_role('ROLE_USER')")
31
     *
32
     * @return Response
33
     */
34
    public function addCourseAction()
35
    {
36
        // "Course validation" feature. This value affects the way of a new course creation:
37
        // true  - the new course is requested only and it is created after approval;
38
        // false - the new course is created immediately, after filling this form.
39
        $courseValidation = false;
40
        if (api_get_setting('course.course_validation') == 'true' &&
41
            !api_is_platform_admin()
42
        ) {
43
            $courseValidation = true;
44
        }
45
46
        // Displaying the header.
47
        $tool_name = $courseValidation ? get_lang('CreateCourseRequest') : get_lang('CreateSite');
48
49
        if (api_get_setting('course.allow_users_to_create_courses') == 'false' &&
50
            !api_is_platform_admin()
51
        ) {
52
            api_not_allowed(true);
53
        }
54
55
        // Check access rights.
56
        if (!api_is_allowed_to_create_course()) {
57
            api_not_allowed(true);
58
        }
59
60
        $url = $this->generateUrl('add_course');
61
        // Build the form.
62
        $form = new \FormValidator('add_course', 'post', $url);
63
64
        // Form title
65
        $form->addElement('header', $tool_name);
66
67
        // Title
68
        $form->addElement(
69
            'text',
70
            'title',
71
            array(
72
                get_lang('CourseName'),
73
                get_lang('Ex'),
74
            ),
75
            array(
76
                'id' => 'title',
77
            )
78
        );
79
        $form->applyFilter('title', 'html_filter');
80
        $form->addRule('title', get_lang('ThisFieldIsRequired'), 'required');
81
82
        $form->addButtonAdvancedSettings('advanced_params');
83
        $form->addElement(
84
            'html',
85
            '<div id="advanced_params_options" style="display:none">'
86
        );
87
88
        // Category category.
89
        $url = api_get_path(WEB_AJAX_PATH).'course.ajax.php?a=search_category';
90
91
        $form->addElement(
92
            'select_ajax',
93
            'category_code',
94
            get_lang('CourseFaculty'),
95
            null,
96
            array('url' => $url)
97
        );
98
99
        // Course code
100
        $form->addText(
101
            'wanted_code',
102
            array(
103
                get_lang('Code'),
104
                get_lang('OnlyLettersAndNumbers'),
105
            ),
106
            '',
107
            array(
108
                'maxlength' => \CourseManager::MAX_COURSE_LENGTH_CODE,
109
                'pattern' => '[a-zA-Z0-9]+',
110
                'title' => get_lang('OnlyLettersAndNumbers'),
111
            )
112
        );
113
        $form->applyFilter('wanted_code', 'html_filter');
114
        $form->addRule(
115
            'wanted_code',
116
            get_lang('Max'),
117
            'maxlength',
118
            \CourseManager::MAX_COURSE_LENGTH_CODE
119
        );
120
121
        // The teacher
122 View Code Duplication
        if ($courseValidation) {
123
124
            // Description of the requested course.
125
            $form->addElement(
126
                'textarea',
127
                'description',
128
                get_lang('Description'),
129
                array('rows' => '3')
130
            );
131
132
            // Objectives of the requested course.
133
            $form->addElement(
134
                'textarea',
135
                'objetives',
136
                get_lang('Objectives'),
137
                array('rows' => '3')
138
            );
139
140
            // Target audience of the requested course.
141
            $form->addElement(
142
                'textarea',
143
                'target_audience',
144
                get_lang('TargetAudience'),
145
                array('rows' => '3')
146
            );
147
        }
148
149
        // Course language.
150
        $form->addElement(
151
            'select_language',
152
            'course_language',
153
            get_lang('Ln'),
154
            array(),
155
            array('style' => 'width:150px')
156
        );
157
        $form->applyFilter('select_language', 'html_filter');
158
159
        // Exemplary content checkbox.
160
        $form->addElement(
161
            'checkbox',
162
            'exemplary_content',
163
            null,
164
            get_lang('FillWithExemplaryContent')
165
        );
166
167 View Code Duplication
        if ($courseValidation) {
168
169
            // A special URL to terms and conditions that is set
170
            // in the platform settings page.
171
            $terms_and_conditions_url = trim(
172
                api_get_setting('course_validation_terms_and_conditions_url')
173
            );
174
175
            // If the special setting is empty,
176
            // then we may get the URL from Chamilo's module "Terms and conditions",
177
            // if it is activated.
178
            if (empty($terms_and_conditions_url)) {
179
                if (api_get_setting(
180
                        'registration.allow_terms_conditions'
181
                    ) == 'true'
182
                ) {
183
                    $terms_and_conditions_url = api_get_path(WEB_CODE_PATH);
184
                    $terms_and_conditions_url .= 'auth/inscription.php?legal';
185
                }
186
            }
187
188
            if (!empty($terms_and_conditions_url)) {
189
                // Terms and conditions to be accepted before sending a course request.
190
                $form->addElement(
191
                    'checkbox',
192
                    'legal',
193
                    null,
194
                    get_lang('IAcceptTermsAndConditions'),
195
                    1
196
                );
197
                $form->addRule(
198
                    'legal',
199
                    get_lang('YouHaveToAcceptTermsAndConditions'),
200
                    'required'
201
                );
202
                // Link to terms and conditions.
203
                $link_terms_and_conditions = '
204
                    <script>
205
                    function MM_openBrWindow(theURL, winName, features) { //v2.0
206
                        window.open(theURL,winName,features);
207
                    }
208
                    </script>
209
                ';
210
                $link_terms_and_conditions .= \Display::url(
211
                    get_lang('ReadTermsAndConditions'),
212
                    '#',
213
                    ['onclick' => "javascript:MM_openBrWindow('$terms_and_conditions_url', 'Conditions', 'scrollbars=yes, width=800');"]
214
                );
215
                $form->addElement('label', null, $link_terms_and_conditions);
216
            }
217
        }
218
219
        $obj = new \GradeModel();
220
        $obj->fill_grade_model_select_in_form($form);
221
222 View Code Duplication
        if (api_get_setting('course.teacher_can_select_course_template') === 'true') {
223
            $form->addElement(
224
                'select_ajax',
225
                'course_template',
226
                [
227
                    get_lang('CourseTemplate'),
228
                    get_lang('PickACourseAsATemplateForThisNewCourse'),
229
                ],
230
                null,
231
                ['url' => api_get_path(WEB_AJAX_PATH) . 'course.ajax.php?a=search_course']
232
            );
233
        }
234
235
        $form->addElement('html', '</div>');
236
237
        // Submit button.
238
        $form->addButtonCreate(
239
            $courseValidation ? get_lang(
240
                'CreateThisCourseRequest'
241
            ) : get_lang('CreateCourseArea')
242
        );
243
244
        // Set default values.
245 View Code Duplication
        if (isset($_user['language']) && $_user['language'] != '') {
0 ignored issues
show
Bug introduced by
The variable $_user seems to never exist, and therefore isset should always return false. Did you maybe rename this variable?

This check looks for calls to isset(...) or empty() on variables that are yet undefined. These calls will always produce the same result and can be removed.

This is most likely caused by the renaming of a variable or the removal of a function/method parameter.

Loading history...
246
            $values['course_language'] = $_user['language'];
247
        } else {
248
            $values['course_language'] = api_get_setting('language.platform_language');
249
        }
250
251
        $form->setDefaults($values);
252
        $message = null;
253
        $content = null;
254
255
        // Validate the form.
256
        if ($form->validate()) {
257
            $course_values = $form->exportValues();
258
259
            $wanted_code = $course_values['wanted_code'];
260
            //$category_code = $course_values['category_code'];
261
            $category_code = '';
262
            $title = $course_values['title'];
263
            $course_language = $course_values['course_language'];
264
            $exemplary_content = !empty($course_values['exemplary_content']);
265
266
            if ($courseValidation) {
267
                $description = $course_values['description'];
268
                $objetives = $course_values['objetives'];
269
                $target_audience = $course_values['target_audience'];
270
            }
271
272
            if ($wanted_code == '') {
273
                $wanted_code = \CourseManager::generate_course_code(
274
                    api_substr(
0 ignored issues
show
Security Bug introduced by
It seems like api_substr($title, 0, \C...MAX_COURSE_LENGTH_CODE) targeting api_substr() can also be of type false; however, CourseManager::generate_course_code() does only seem to accept string, did you maybe forget to handle an error condition?
Loading history...
275
                        $title,
276
                        0,
277
                        \CourseManager::MAX_COURSE_LENGTH_CODE
278
                    )
279
                );
280
            }
281
282
            // Check whether the requested course code has already been occupied.
283 View Code Duplication
            if (!$courseValidation) {
284
                $course_code_ok = !\CourseManager::course_code_exists(
285
                    $wanted_code
286
                );
287
            } else {
288
                $course_code_ok = !\CourseRequestManager::course_code_exists(
289
                    $wanted_code
290
                );
291
            }
292
293
            if ($course_code_ok) {
294
                if (!$courseValidation) {
295
296
                    $params = array();
297
                    $params['title'] = $title;
298
                    $params['exemplary_content'] = $exemplary_content;
299
                    $params['wanted_code'] = $wanted_code;
300
                    $params['course_category'] = $category_code;
301
                    $params['course_language'] = $course_language;
302
                    $params['gradebook_model_id'] = isset($course_values['gradebook_model_id']) ? $course_values['gradebook_model_id'] : null;
303
304
                    $course_info = \CourseManager::create_course($params);
305
306
                    if (!empty($course_info)) {
307
308
                        $url = api_get_path(WEB_CODE_PATH);
309
                        $url .= 'course_info/start.php?cidReq=';
310
                        $url .= $course_info['code'];
311
                        $url .= '&first=1';
312
                        header('Location: '.$url);
313
                        exit;
314
                    } else {
315
                        $this->addFlash(
316
                            'error',
317
                            $this->trans('CourseCreationFailed')
318
                        );
319
                        // Display the form.
320
                        $content = $form->returnForm();
321
                    }
322
                } else {
323
                    // Create a request for a new course.
324
                    $request_id = \CourseRequestManager::create_course_request(
325
                        $wanted_code,
326
                        $title,
327
                        $description,
328
                        $category_code,
329
                        $course_language,
330
                        $objetives,
331
                        $target_audience,
332
                        api_get_user_id(),
333
                        $exemplary_content
334
                    );
335
336
                    if ($request_id) {
337
                        $course_request_info = \CourseRequestManager::get_course_request_info(
338
                            $request_id
339
                        );
340
                        $message = (is_array(
341
                                $course_request_info
342
                            ) ? '<strong>'.$course_request_info['code'].'</strong> : ' : '').get_lang(
343
                                'CourseRequestCreated'
344
                            );
345
                        \Display::return_message(
346
                            $message,
347
                            'confirmation',
348
                            false
349
                        );
350
                        \Display::return_message(
351
                            'div',
352
                            \Display::url(
353
                                get_lang('Enter'),
354
                                api_get_path(WEB_PATH).'user_portal.php',
355
                                ['class' => 'btn btn-default']
356
                            ),
357
                            ['style' => 'float: left; margin:0px; padding: 0px;']
358
                        );
359
                    } else {
360
                        \Display::return_message(
361
                            get_lang('CourseRequestCreationFailed'),
362
                            'error',
363
                            false
364
                        );
365
                        // Display the form.
366
                        $content = $form->returnForm();
367
                    }
368
                }
369
            } else {
370
                \Display::return_message(
371
                    get_lang('CourseCodeAlreadyExists'),
372
                    'error',
373
                    false
374
                );
375
                // Display the form.
376
                $content = $form->returnForm();
377
            }
378
        } else {
379
            if (!$courseValidation) {
380
                $this->addFlash('warning', get_lang('Explanation'));
381
            }
382
            // Display the form.
383
            $content = $form->returnForm();
384
        }
385
386
        return $this->render(
387
            'ChamiloCoreBundle:Index:userportal.html.twig',
388
            array(
389
                'content' => $content,
390
            )
391
        );
392
    }
393
394
    /**
395
     * @Route("/{type}/{filter}", name="userportal")
396
     * @Method({"GET"})
397
     * @Security("has_role('ROLE_USER')")
398
     *
399
     * @param string $type courses|sessions|mycoursecategories
400
     * @param string $filter history|current for the userportal courses page
401
     * @param int $coursePage
402
     * @param Request $request
403
     *
404
     * @return Response
405
     */
406
    public function indexAction(
407
        $type = 'courses',
408
        $filter = 'current',
409
        $coursePage = 1,
410
        Request $request
411
    ) {
412
        //$settingsManager = $this->get('chamilo.settings.manager');
413
        //$setting = $settingsManager->getSetting('platform.institution');
414
415
        /*$settingsManagerCourse = $this->get('chamilo_course.settings.manager');
416
        $course = $this->getDoctrine()->getRepository('ChamiloCoreBundle:Course')->find(1);
417
        if ($course) {
418
            $settingsManagerCourse->setCourse($course);
419
            $agenda = $settingsManagerCourse->getSetting(
420
                'calendar_event.enabled'
421
            );
422
        }*/
423
424
        $user = $this->getUser();
425
        $pageController = new PageController();
426
        $items = null;
427
        $page = $coursePage;
428
429
        if (!empty($user)) {
430
            $userId = $user->getId();
431
432
            // Main courses and session list
433
            $type = str_replace('/', '', $type);
434
            switch ($type) {
435
                case 'sessions':
436
                    $items = $pageController->returnSessions(
437
                        $userId,
438
                        $filter,
439
                        $page
440
                    );
441
                    break;
442
                case 'sessioncategories':
443
                    $items = $pageController->returnSessionsCategories(
444
                        $userId,
445
                        $filter,
446
                        $page
447
                    );
448
                    break;
449
                case 'courses':
450
                    $items = $pageController->returnCourses(
451
                        $userId,
452
                        $filter,
453
                        $page
454
                    );
455
                    break;
456
                case 'mycoursecategories':
457
                    $items = $pageController->returnMyCourseCategories(
458
                        $userId,
459
                        $filter,
460
                        $page
461
                    );
462
                    break;
463
                case 'specialcourses':
464
                    $items = $pageController->returnSpecialCourses(
465
                        $userId,
466
                        $filter,
467
                        $page
468
                    );
469
                    break;
470
            }
471
        }
472
473
        /** @var \Chamilo\SettingsBundle\Manager\SettingsManager $settingManager */
474
        $settingManager = $this->get('chamilo.settings.manager');
475
        /*var_dump($settingManager->getSetting('platform.institution'));
476
        $settings = $settingManager->loadSettings('platform');
477
        var_dump($settings->get('institution'));
478
        var_dump(api_get_setting('platform.institution'));*/
479
480
        $pageController->returnSkillsLinks();
481
482
        // Deleting the session_id.
483
        $request->getSession()->remove('session_id');
484
485
        $countCourses = \CourseManager::count_courses();
486
487
        return $this->render(
488
            'ChamiloCoreBundle:Index:userportal.html.twig',
489
            array(
490
                'content' => $items,
491
                'count_courses' => $countCourses
492
            )
493
        );
494
    }
495
496
497
498
}
499