Completed
Push — master ( 7c77d2...d749ed )
by Julito
126:22 queued 88:09
created

CoursesController::getFormatedSessionsBlock()   F

Complexity

Conditions 13
Paths 385

Size

Total Lines 116
Code Lines 80

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 13
eloc 80
nc 385
nop 1
dl 0
loc 116
rs 3.7737
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
use Chamilo\CoreBundle\Framework\Container;
5
use Chamilo\CoreBundle\Entity\SequenceResource;
6
7
/**
8
 * Class CoursesController
9
 *
10
 * This file contains class used like controller,
11
 * it should be included inside a dispatcher file (e.g: index.php)
12
 * @author Christian Fasanando <[email protected]> - BeezNest
13
 * @package chamilo.auth
14
 */
15
class CoursesController
16
{
17
    private $toolname;
18
    private $view;
19
    private $model;
20
21
    /**
22
     * Constructor
23
     */
24
    public function __construct()
25
    {
26
        $this->toolname = 'auth';
27
        $actived_theme_path = api_get_path(SYS_TEMPLATE_PATH).'default/';
28
        $this->view = new View($this->toolname, $actived_theme_path);
29
        $this->model = new Auth();
30
    }
31
32
    /**
33
     * It's used for listing courses,
34
     * render to courses_list view
35
     * @param string   	action
36
     * @param string    confirmation message(optional)
37
     * @param string $action
38
     */
39
    public function courses_list($action, $message = '')
40
    {
41
        $data = array();
42
        $user_id = api_get_user_id();
43
44
        $data['user_courses'] = $this->model->get_courses_of_user($user_id);
45
        $data['user_course_categories'] = $this->model->get_user_course_categories();
46
        $data['courses_in_category'] = $this->model->get_courses_in_category();
47
        $data['all_user_categories'] = $this->model->get_user_course_categories();
48
        $data['action'] = $action;
49
        $data['message'] = $message;
50
51
        // render to the view
52
        $this->view->set_data($data);
53
        $this->view->set_layout('catalog_layout');
54
        $this->view->set_template('courses_list');
55
        $this->view->render();
56
    }
57
58
    /**
59
     * It's used for listing categories,
60
     * render to categories_list view
61
     * @param string   	$action
62
     * @param string   $message confirmation message(optional)
63
     * @param string   $error error message(optional)
64
     */
65
    public function categories_list($action, $message='', $error='')
66
    {
67
        $data = array();
68
        $data['user_course_categories'] = $this->model->get_user_course_categories();
69
        $data['action'] = $action;
70
        $data['message'] = $message;
71
        $data['error'] = $error;
72
73
        // render to the view
74
        $this->view->set_data($data);
75
        $this->view->set_layout('catalog_layout');
76
        $this->view->set_template('categories_list');
77
        $this->view->render();
78
    }
79
80
    /**
81
     * It's used for listing courses with categories,
82
     * render to courses_categories view
83
     * @param string $action
84
     * @param string $category_code
85
     * @param string $message
86
     * @param string $error
87
     * @param string $content
88
     * @param array $limit will be used if $random_value is not set.
89
     * This array should contains 'start' and 'length' keys
90
     * @internal param \action $string
91
     * @internal param \Category $string code (optional)
92
     */
93
    public function courses_categories(
94
        $action,
95
        $category_code = null,
96
        $message = '',
97
        $error = '',
98
        $content = null,
99
        $limit = array()
100
    ) {
101
        $data = array();
102
        $browse_course_categories = $this->model->browse_course_categories();
103
        $data['countCoursesInCategory'] = $this->model->count_courses_in_category($category_code);
104
        if ($action === 'display_random_courses') {
105
            // Random value is used instead limit filter
106
            $data['browse_courses_in_category'] = $this->model->browse_courses_in_category(null, 12);
107
            $data['countCoursesInCategory'] = count($data['browse_courses_in_category']);
108
        } else {
109
            if (!isset($category_code)) {
110
                $category_code = $browse_course_categories[0][1]['code']; // by default first category
111
            }
112
            $limit = isset($limit) ? $limit : CourseCategory::getLimitArray();
113
            $data['browse_courses_in_category'] = $this->model->browse_courses_in_category($category_code, null, $limit);
114
        }
115
116
        $data['browse_course_categories'] = $browse_course_categories;
117
        $data['code'] = Security::remove_XSS($category_code);
118
119
        // getting all the courses to which the user is subscribed to
120
        $curr_user_id = api_get_user_id();
121
        $user_courses = $this->model->get_courses_of_user($curr_user_id);
122
        $user_coursecodes = array();
123
124
        // we need only the course codes as these will be used to match against the courses of the category
125
        if ($user_courses != '') {
126
            foreach($user_courses as $key => $value) {
127
                $user_coursecodes[] = $value['code'];
128
            }
129
        }
130
131
        if (api_is_drh()) {
132
            $courses = CourseManager::get_courses_followed_by_drh(api_get_user_id());
133
            foreach ($courses as $course) {
134
                $user_coursecodes[] = $course['code'];
135
            }
136
        }
137
138
        $data['user_coursecodes'] = $user_coursecodes;
139
        $data['action'] = $action;
140
        $data['message'] = $message;
141
        $data['content'] = $content;
142
        $data['error'] = $error;
143
144
        $data['catalogShowCoursesSessions'] = 0;
145
146
        $showCoursesSessions = intval('catalog_show_courses_sessions');
147
        if ($showCoursesSessions > 0) {
148
            $data['catalogShowCoursesSessions'] = $showCoursesSessions;
149
        }
150
151
        // render to the view
152
        $this->view->set_data($data);
153
        $this->view->set_layout('catalog_layout');
154
        $this->view->set_template('courses_categories');
155
        $this->view->render();
156
    }
157
158
    /**
159
     * @param string $search_term
160
     * @param string $message
161
     * @param string $error
162
     * @param string $content
163
     * @param $limit
164
     * @param boolean $justVisible Whether to search only in courses visibles in the catalogue
165
     */
166
    public function search_courses(
167
        $search_term,
168
        $message = '',
169
        $error = '',
170
        $content = null,
171
        $limit = array(),
172
        $justVisible = false
173
    ) {
174
        $data = array();
175
        $limit = !empty($limit) ? $limit : CourseCategory::getLimitArray();
176
177
        $browse_course_categories = $this->model->browse_course_categories();
178
        $data['countCoursesInCategory'] = $this->model->count_courses_in_category('ALL', $search_term);
179
        $data['browse_courses_in_category'] = $this->model->search_courses($search_term, $limit, $justVisible);
180
        $data['browse_course_categories']   = $browse_course_categories;
181
182
        $data['search_term'] = Security::remove_XSS($search_term); //filter before showing in template
183
184
        // getting all the courses to which the user is subscribed to
185
        $curr_user_id = api_get_user_id();
186
        $user_courses = $this->model->get_courses_of_user($curr_user_id);
187
        $user_coursecodes = array();
188
189
        // we need only the course codes as these will be used to match against the courses of the category
190
        if ($user_courses != '') {
191
            foreach ($user_courses as $value) {
192
                $user_coursecodes[] = $value['code'];
193
            }
194
        }
195
196
        $data['user_coursecodes'] = $user_coursecodes;
197
        $data['message'] = $message;
198
        $data['content'] = $content;
199
        $data['error'] = $error;
200
        $data['action'] = 'display_courses';
201
202
        // render to the view
203
        $this->view->set_data($data);
204
        $this->view->set_layout('catalog_layout');
205
        $this->view->set_template('courses_categories');
206
        $this->view->render();
207
    }
208
209
    /**
210
     * Auto user subscription to a course
211
     */
212
    public function subscribe_user($course_code, $search_term, $category_code)
213
    {
214
        $courseInfo = api_get_course_info($course_code);
215
216
        if (empty($courseInfo)) {
217
            return false;
218
        }
219
220
        $message = '';
221
        $error = '';
222
        $content = '';
223
        $result = [];
224
225
        // The course must be open in order to access the auto subscription
226
        if (in_array(
227
            $courseInfo['visibility'],
228
            array(COURSE_VISIBILITY_CLOSED, COURSE_VISIBILITY_REGISTERED, COURSE_VISIBILITY_HIDDEN))
229
        ) {
230
            $error = get_lang('SubscribingNotAllowed');
231
        } else {
232
            $result = $this->model->subscribe_user($course_code);
233
            if (!$result) {
234
                $error = get_lang('CourseRegistrationCodeIncorrect');
235
            } else {
236
                // Redirect directly to the course after subscription
237
                $message = isset($result['message']) ? $result['message'] : '';
238
                $content = isset($result['content']) ? $result['content'] : '';
239
            }
240
        }
241
242 View Code Duplication
        if (!empty($search_term)) {
243
            $this->search_courses($search_term, $message, $error, $content);
244
        } else {
245
            $this->courses_categories('subscribe', $category_code, $message, $error, $content);
246
        }
247
248
        return $result;
249
    }
250
251
    /**
252
     * Create a category
253
     * render to listing view
254
     * @param   string  Category title
255
     */
256
    public function add_course_category($category_title)
257
    {
258
        $result = $this->model->store_course_category($category_title);
259
        if ($result) {
260
            Display::addFlash(Display::return_message(get_lang('CourseCategoryStored')));
261
        } else {
262
            Display::addFlash(Display::return_message(get_lang('ACourseCategoryWithThisNameAlreadyExists'), 'error'));
263
        }
264
        $action = 'sortmycourses';
265
        $this->courses_list($action);
266
    }
267
268
    /**
269
     * Change course category
270
     * render to listing view
271
     * @param string    $course_code
272
     * @param int    $category_id
273
     */
274
    public function change_course_category($course_code, $category_id)
275
    {
276
        $courseInfo = api_get_course_info($course_code);
277
        $courseId = $courseInfo['real_id'];
278
279
        $result = $this->model->updateCourseCategory($courseId, $category_id);
280
        if ($result) {
281
            Display::addFlash(Display::return_message(get_lang('EditCourseCategorySucces')));
282
        }
283
        $action = 'sortmycourses';
284
        $this->courses_list($action);
285
    }
286
287
    /**
288
     * Move up/down courses inside a category
289
     * render to listing view
290
     * @param string    $move move to up or down
291
     * @param string    $course_code
292
     * @param int    $category_id Category id
293
     */
294 View Code Duplication
    public function move_course($move, $course_code, $category_id)
295
    {
296
        $result = $this->model->move_course($move, $course_code, $category_id);
297
        if ($result) {
298
            Display::addFlash(Display::return_message(get_lang('CourseSortingDone')));
299
        }
300
        $action = 'sortmycourses';
301
        $this->courses_list($action);
302
    }
303
304
    /**
305
     * Move up/down categories
306
     * render to listing view
307
     * @param string    $move move to up or down
308
     * @param int    $category_id Category id
309
     */
310 View Code Duplication
    public function move_category($move, $category_id)
311
    {
312
        $result = $this->model->move_category($move, $category_id);
313
        if ($result) {
314
            Display::addFlash(Display::return_message(get_lang('CategorySortingDone')));
315
        }
316
        $action = 'sortmycourses';
317
        $this->courses_list($action);
318
    }
319
320
    /**
321
     * Edit course category
322
     * render to listing view
323
     * @param string $title Category title
324
     * @param int    $category Category id
325
     */
326 View Code Duplication
    public function edit_course_category($title, $category)
327
    {
328
        $result = $this->model->store_edit_course_category($title, $category);
329
        if ($result) {
330
            Display::addFlash(Display::return_message(get_lang('CourseCategoryEditStored')));
331
        }
332
        $action = 'sortmycourses';
333
        $this->courses_list($action);
334
    }
335
336
    /**
337
     * Delete a course category
338
     * render to listing view
339
     * @param int    Category id
340
     */
341 View Code Duplication
    public function delete_course_category($category_id)
342
    {
343
        $result = $this->model->delete_course_category($category_id);
344
        if ($result) {
345
            Display::addFlash(Display::return_message(get_lang('CourseCategoryDeleted')));
346
        }
347
        $action = 'sortmycourses';
348
        $this->courses_list($action);
349
    }
350
351
    /**
352
     * Unsubscribe user from a course
353
     * render to listing view
354
     * @param string $course_code
355
     * @param string $search_term
356
     * @param string $category_code
357
     */
358
    public function unsubscribe_user_from_course($course_code, $search_term = null, $category_code = null)
359
    {
360
        $result = $this->model->remove_user_from_course($course_code);
361
        $message = '';
362
        $error = '';
363
364
        if ($result) {
365
            Display::addFlash(Display::return_message(get_lang('YouAreNowUnsubscribed')));
366
        }
367
        $action = 'sortmycourses';
368
369 View Code Duplication
        if (!empty($search_term)) {
370
            $this->search_courses($search_term, $message, $error);
371
        } else {
372
            $this->courses_categories('subcribe', $category_code, $message, $error);
373
        }
374
    }
375
376
    /**
377
     * Get the html block for courses categories
378
     * @param string $code Current category code
379
     * @param boolean $hiddenLinks Whether hidden links
380
     * @param array $limit
381
     * @return string The HTML block
382
     */
383
    public function getCoursesCategoriesBlock($code = null, $hiddenLinks = false, $limit = null)
384
    {
385
        $categories = $this->model->browse_course_categories();
386
387
        $html = '';
388
389
        if (!empty($categories)) {
390
            $action = 'display_courses';
391
            foreach ($categories[0] as $category) {
392
                $categoryName = $category['name'];
393
                $categoryCode = $category['code'];
394
                $categoryCourses = $category['count_courses'];
395
396
                $html .= '<li>';
397
398
                if ($code == $categoryCode) {
399
                    $html .= '<strong>';
400
                    $html .= "$categoryName ($categoryCourses)";
401
                    $html .= '</strong>';
402 View Code Duplication
                } else {
403
                    if (!empty($categoryCourses)) {
404
                        $html .= '<a href="' . CourseCategory::getCourseCategoryUrl(
405
                                1,
406
                                $limit['length'],
407
                                $categoryCode,
408
                                $hiddenLinks,
409
                                $action
410
                            ) . '">';
411
                        $html .= "$categoryName ($categoryCourses)";
412
                        $html .= '</a>';
413
                    } else {
414
                        $html .= "$categoryName ($categoryCourses)";
415
                    }
416
                }
417
418
                if (!empty($categories[$categoryCode])) {
419
                    $html .= '<ul class="nav nav-list">';
420
421
                    foreach ($categories[$categoryCode] as $subCategory1) {
422
                        $subCategory1Name = $subCategory1['name'];
423
                        $subCategory1Code = $subCategory1['code'];
424
                        $subCategory1Courses = $subCategory1['count_courses'];
425
426
                        $html .= '<li>';
427
428 View Code Duplication
                        if ($code == $subCategory1Code) {
429
                            $html .= "<strong>$subCategory1Name ($subCategory1Courses)</strong>";
430
                        } else {
431
                            $html .= '<a href="' . CourseCategory::getCourseCategoryUrl(
432
                                    1,
433
                                    $limit['length'],
434
                                    $categoryCode,
435
                                    $hiddenLinks,
436
                                    $action
437
                                ) . '">';
438
                            $html .= "$subCategory1Name ($subCategory1Courses)";
439
                            $html .= '</a>';
440
                        }
441
442
                        if (!empty($categories[$subCategory1Code])) {
443
                            $html .= '<ul class="nav nav-list">';
444
445
                            foreach ($categories[$subCategory1Code] as $subCategory2) {
446
                                $subCategory2Name = $subCategory2['name'];
447
                                $subCategory2Code = $subCategory2['code'];
448
                                $subCategory2Courses = $subCategory2['count_courses'];
449
450
                                $html .= '<li>';
451
452 View Code Duplication
                                if ($code == $subCategory2Code) {
453
                                    $html .= "<strong>$subCategory2Name ($subCategory2Courses)</strong>";
454
                                } else {
455
                                    $html .= '<a href="' . CourseCategory::getCourseCategoryUrl(
456
                                            1,
457
                                            $limit['length'],
458
                                            $categoryCode,
459
                                            $hiddenLinks,
460
                                            $action
461
                                        ) . '">';
462
                                    $html .= "$subCategory2Name ($subCategory2Courses)";
463
                                    $html .= '</a>';
464
                                }
465
466
                                if (!empty($categories[$subCategory2Code])) {
467
                                    $html .= '<ul class="nav nav-list">';
468
469
                                    foreach ($categories[$subCategory2Code] as $subCategory3) {
470
                                        $subCategory3Name = $subCategory3['name'];
471
                                        $subCategory3Code = $subCategory3['code'];
472
                                        $subCategory3Courses = $subCategory3['count_courses'];
473
474
                                        $html .= '<li>';
475
476 View Code Duplication
                                        if ($code == $subCategory3Code) {
477
                                            $html .= "<strong>$subCategory3Name ($subCategory3Courses)</strong>";
478
                                        } else {
479
                                            $html .= '<a href="' . CourseCategory::getCourseCategoryUrl(
480
                                                    1,
481
                                                    $limit['length'],
482
                                                    $categoryCode,
483
                                                    $hiddenLinks,
484
                                                    $action
485
                                                ) . '">';
486
                                            $html .= "$subCategory3Name ($subCategory3Courses)";
487
                                            $html .= '</a>';
488
                                        }
489
                                        $html .= '</li>';
490
                                    }
491
                                    $html .= '</ul>';
492
                                }
493
                                $html .= '</li>';
494
                            }
495
                            $html .= '</ul>';
496
                        }
497
                        $html .= '</li>';
498
                    }
499
                    $html .= '</ul>';
500
                }
501
                $html .= '</li>';
502
            }
503
        }
504
505
        return $html;
506
    }
507
508
    /**
509
     * Get a HTML button for subscribe to session
510
     * @param int $sessionId The session ID
511
     * @param string $sessionName The session name
512
     * @param boolean $checkRequirements Optional.
513
     *        Whether the session has requirement. Default is false
514
     * @return string The button HTML
515
     */
516
    public function getRegisteredInSessionButton(
517
        $sessionId,
518
        $sessionName,
519
        $checkRequirements = false
520
    ) {
521
        if ($checkRequirements) {
522
            $url = api_get_path(WEB_AJAX_PATH);
523
            $url .= 'sequence.ajax.php?';
524
            $url .= http_build_query([
525
                'a' => 'get_requirements',
526
                'id' => intval($sessionId),
527
                'type' => SequenceResource::SESSION_TYPE,
528
            ]);
529
530
            return Display::toolbarButton(
531
                null,
532
                $url,
533
                'shield',
534
                'default',
535
                [
536
                    'class' => 'btn-sm ajax',
537
                    'data-title' => get_lang('CheckRequirements'),
538
                    'data-size' => 'md',
539
                    'title' => get_lang('CheckRequirements')
540
                ]
541
            );
542
        }
543
544
        $catalogSessionAutoSubscriptionAllowed = false;
545
546
        if (
547
            api_get_setting('session.catalog_allow_session_auto_subscription') === 'true'
548
        ) {
549
            $catalogSessionAutoSubscriptionAllowed = true;
550
        }
551
552
        $url = api_get_path(WEB_CODE_PATH);
553
554
        if ($catalogSessionAutoSubscriptionAllowed) {
555
            $url .= 'auth/courses.php?';
556
            $url .= http_build_query([
557
                'action' => 'subscribe_to_session',
558
                'session_id' => intval($sessionId)
559
            ]);
560
561
            $result = Display::toolbarButton(
562
                null,
563
                $url,
564
                'sign-in',
565
                'success',
566
                [
567
                    'class' => 'btn-sm ajax',
568
                    'data-title' => get_lang('AreYouSureToSubscribe'),
569
                    'data-size' => 'md',
570
                    'title' => get_lang('Subscribe')
571
                ]
572
            );
573
        } else {
574
            $url .= 'inc/email_editor.php?';
575
            $url .= http_build_query([
576
                'action' => 'subscribe_me_to_session',
577
                'session' => Security::remove_XSS($sessionName),
578
            ]);
579
580
            $result = Display::toolbarButton(
581
                null,
582
                $url,
583
                'sign-in',
584
                'success',
585
                ['class' => 'btn-sm']
586
            );
587
        }
588
589
        $hook = HookResubscribe::create();
590
        if (!empty($hook)) {
591
            $hook->setEventData(array(
592
                'session_id' => intval($sessionId),
593
            ));
594
            try {
595
                $hook->notifyResubscribe(HOOK_EVENT_TYPE_PRE);
596
            } catch (Exception $exception) {
597
                $result = $exception->getMessage();
598
            }
599
        }
600
601
        return $result;
602
    }
603
604
    /**
605
     * Generate a label if the user has been  registered in session
606
     * @return string The label
607
     */
608
    public function getAlreadyRegisteredInSessionLabel()
609
    {
610
        $icon = '<em class="fa fa-graduation-cap"></em>';
611
612
        return Display::div(
613
            $icon,
614
            array('class' => 'btn btn-default btn-sm registered', 'title' => get_lang("AlreadyRegisteredToSession"))
615
        );
616
    }
617
618
    /**
619
     * Get a icon for a session
620
     * @param string $sessionName The session name
621
     * @return string The icon
622
     */
623
    public function getSessionIcon($sessionName)
624
    {
625
        return Display::return_icon('window_list.png', $sessionName, null,ICON_SIZE_MEDIUM);
626
    }
627
628
    /**
629
     * Return Session Catalogue rendered view
630
     * @param string $action
631
     * @param string $nameTools
632
     * @param array $limit
633
     */
634
    public function sessionsList($action, $nameTools, $limit = array())
635
    {
636
        $date = isset($_POST['date']) ? $_POST['date'] : date('Y-m-d');
637
        $hiddenLinks = isset($_GET['hidden_links']) ? intval($_GET['hidden_links']) == 1 : false;
638
        $limit = isset($limit) ? $limit : CourseCategory::getLimitArray();
639
640
        $countSessions = $this->model->countSessions($date);
641
        $sessions = $this->model->browseSessions($date, $limit);
642
643
        $pageTotal = intval(ceil(intval($countSessions) / $limit['length']));
644
        // Do NOT show pagination if only one page or less
645
        $cataloguePagination = $pageTotal > 1 ?
646
            CourseCategory::getCatalogPagination($limit['current'], $limit['length'], $pageTotal) :
647
            '';
648
        $sessionsBlocks = $this->getFormatedSessionsBlock($sessions);
649
650
        // Get session list catalogue URL
651
        //$sessionUrl = CourseCategoryManager::getCourseCategoryUrl(1, $limit['length'], null, 0, 'display_sessions');
652
        // Get session search catalogue URL
653
        $courseUrl = CourseCategoryManager::getCourseCategoryUrl(1, $limit['length'], null, 0, 'subscribe');
654
655
        $tpl = \Chamilo\CoreBundle\Framework\Container::getTwig();
656
        $tpl->addGlobal(
657
            'show_courses',
658
            CoursesAndSessionsCatalog::showCourses()
659
        );
660
        $tpl->addGlobal(
661
            'show_sessions',
662
            CoursesAndSessionsCatalog::showSessions()
663
        );
664
        $tpl->addGlobal(
665
            'show_tutor',
666
            (api_get_setting(
667
                'session.show_session_coach'
668
            ) === 'true' ? true : false)
669
        );
670
        $tpl->addGlobal('course_url', $courseUrl);
671
        $tpl->addGlobal('catalog_pagination', $cataloguePagination);
672
        $tpl->addGlobal('hidden_links', $hiddenLinks);
673
        $tpl->addGlobal('search_token', Security::get_token());
674
        $tpl->addGlobal('search_date', $date);
675
        $tpl->addGlobal(
676
            'web_session_courses_ajax_url',
677
            api_get_path(WEB_AJAX_PATH).'course.ajax.php'
678
        );
679
        $tpl->addGlobal('sessions', $sessionsBlocks);
680
        $tpl->addGlobal(
681
            'already_subscribed_label',
682
            $this->getAlreadyRegisteredInSessionLabel()
683
        );
684
685
        echo $tpl->render('@template_style/auth/session_catalog.html.twig');
686
    }
687
688
    /**
689
     * Show the Session Catalogue with filtered session by course tags
690
     * @param array $limit Limit info
691
     */
692 View Code Duplication
    public function sessionsListByCoursesTag(array $limit)
693
    {
694
        $searchTag = isset($_POST['search_tag']) ? $_POST['search_tag'] : null;
695
        $searchDate = isset($_POST['date']) ? $_POST['date'] : date('Y-m-d');
696
        $hiddenLinks = isset($_GET['hidden_links']) ? intval($_GET['hidden_links']) == 1 : false;
697
        $courseUrl = CourseCategory::getCourseCategoryUrl(1, $limit['length'], null, 0, 'subscribe');
698
699
        $sessions = $this->model->browseSessionsByTags($searchTag, $limit);
700
        $sessionsBlocks = $this->getFormatedSessionsBlock($sessions);
701
702
        echo Container::getTemplating()->render(
703
            '@template_style/auth/session_catalog.html.twig',
704
            [
705
                'show_courses' => CoursesAndSessionsCatalog::showCourses(),
706
                'show_sessions' => CoursesAndSessionsCatalog::showSessions(),
707
                'show_tutor' => (api_get_setting('session.show_session_coach') === 'true' ? true : false),
708
                'course_url' => $courseUrl,
709
                'already_subscribed_label' => $this->getAlreadyRegisteredInSessionLabel(),
710
                'hidden_links' => $hiddenLinks,
711
                'search_token' => Security::get_token(),
712
                'search_date' => Security::remove_XSS($searchDate),
713
                'search_tag' => Security::remove_XSS($searchTag),
714
                'sessions' => $sessionsBlocks
715
            ]
716
        );
717
718
719
720
    }
721
722
    /**
723
     * Show the Session Catalogue with filtered session by a query term
724
     * @param array $limit
725
     */
726 View Code Duplication
    public function sessionListBySearch(array $limit)
727
    {
728
        $q = isset($_REQUEST['q']) ? Security::remove_XSS($_REQUEST['q']) : null;
729
        $hiddenLinks = isset($_GET['hidden_links']) ? intval($_GET['hidden_links']) == 1 : false;
730
        $courseUrl = CourseCategory::getCourseCategoryUrl(1, $limit['length'], null, 0, 'subscribe');
731
        $searchDate = isset($_POST['date']) ? $_POST['date'] : date('Y-m-d');
732
733
        $sessions = $this->model->browseSessionsBySearch($q, $limit);
734
        $sessionsBlocks = $this->getFormatedSessionsBlock($sessions);
735
736
        echo Container::getTemplating()->render(
737
            '@temaplte_style/auth/session_catalog.html.twig',
738
            [
739
                'show_courses' => CoursesAndSessionsCatalog::showCourses(),
740
                'show_sessions' => CoursesAndSessionsCatalog::showSessions(),
741
                'show_tutor' => (api_get_setting('session.show_session_coach') === 'true' ? true : false),
742
                'course_url' => $courseUrl,
743
                'already_subscribed_label' =>  $this->getAlreadyRegisteredInSessionLabel(),
744
                'hidden_links' => $hiddenLinks,
745
                'search_token' => Security::get_token(),
746
                'search_date' => Security::remove_XSS($searchDate),
747
                'search_tag' => Security::remove_XSS($q),
748
                'sessions' => $sessionsBlocks
749
            ]
750
        );
751
    }
752
753
    /**
754
     * Get the formated data for sessions block to be displayed on Session Catalog page
755
     * @param array $sessions The session list
756
     * @return array
757
     */
758
    private function getFormatedSessionsBlock(array $sessions)
759
    {
760
        $extraFieldValue = new ExtraFieldValue('session');
761
        $userId = api_get_user_id();
762
        $sessionsBlocks = [];
763
764
        $entityManager = Database::getManager();
765
        $sessionRelCourseRepo = $entityManager->getRepository('ChamiloCoreBundle:SessionRelCourse');
766
        $extraFieldRepo = $entityManager->getRepository('ChamiloCoreBundle:ExtraField');
767
        $extraFieldRelTagRepo = $entityManager->getRepository('ChamiloCoreBundle:ExtraFieldRelTag');
768
769
        $tagsField = $extraFieldRepo->findOneBy([
770
            'extraFieldType' => Chamilo\CoreBundle\Entity\ExtraField::COURSE_FIELD_TYPE,
771
            'variable' => 'tags',
772
        ]);
773
        /** @var \Chamilo\CoreBundle\Entity\Session $session */
774
        foreach ($sessions as $session) {
775
            $sessionDates = SessionManager::parseSessionDates([
776
                'display_start_date' => $session->getDisplayStartDate(),
777
                'display_end_date' => $session->getDisplayEndDate(),
778
                'access_start_date' => $session->getAccessStartDate(),
779
                'access_end_date' => $session->getAccessEndDate(),
780
                'coach_access_start_date' => $session->getCoachAccessStartDate(),
781
                'coach_access_end_date' => $session->getCoachAccessEndDate(),
782
            ]);
783
784
            $imageField = $extraFieldValue->get_values_by_handler_and_field_variable($session->getId(), 'image');
785
786
            $sessionCourseTags = [];
787
788
            if (!is_null($tagsField)) {
789
                $sessionRelCourses = $sessionRelCourseRepo->findBy([
790
                    'session' => $session,
791
                ]);
792
793
                foreach ($sessionRelCourses as $sessionRelCourse) {
794
                    $courseTags = $extraFieldRelTagRepo->getTags(
795
                        $tagsField,
796
                        $sessionRelCourse->getCourse()->getId()
797
                    );
798
799
                    foreach ($courseTags as $tag) {
800
                        $sessionCourseTags[] = $tag->getTag();
801
                    }
802
                }
803
            }
804
805
            if (!empty($sessionCourseTags)) {
806
                $sessionCourseTags = array_unique($sessionCourseTags);
807
            }
808
809
            $repo = $entityManager->getRepository('ChamiloCoreBundle:SequenceResource');
810
            $sequences = $repo->getRequirementsAndDependenciesWithinSequences(
811
                $session->getId(),
812
                SequenceResource::SESSION_TYPE
813
            );
814
815
            $hasRequirements = false;
816
817
            foreach ($sequences['sequences'] as $sequence) {
818
                if (count($sequence['requirements']) === 0) {
819
                    continue;
820
                }
821
822
                $hasRequirements = true;
823
                break;
824
            }
825
            $cat = $session->getCategory();
826
            if (empty($cat)) {
827
                $cat = null;
828
                $catName = '';
829
            } else {
830
                $catName = $cat->getName();
831
            }
832
833
            $coachId = $session->getGeneralCoach()->getId();
834
            $coachName = $session->getGeneralCoach()->getCompleteName();
835
            $actions = null;
836
            if (api_is_platform_admin()) {
837
                $actions = api_get_path(WEB_CODE_PATH) .'session/resume_session.php?id_session='.$session->getId();
838
            }
839
840
            $isThisSessionOnSale = $session->getBuyCoursePluginPrice();
841
842
            $sessionsBlock = array(
843
                'id' => $session->getId(),
844
                'name' => $session->getName(),
845
                'image' => isset($imageField['value']) ? $imageField['value'] : null,
846
                'nbr_courses' => $session->getNbrCourses(),
847
                'nbr_users' => $session->getNbrUsers(),
848
                'coach_id' => $coachId,
849
                'coach_url' => api_get_path(WEB_AJAX_PATH) . 'user_manager.ajax.php?a=get_user_popup&user_id=' . $coachId,
850
                'coach_name' => $coachName,
851
                'coach_avatar' => UserManager::getUserPicture($coachId, USER_IMAGE_SIZE_SMALL),
852
                'is_subscribed' => SessionManager::isUserSubscribedAsStudent($session->getId(), $userId),
853
                'icon' => $this->getSessionIcon($session->getName()),
854
                'date' => $sessionDates['display'],
855
                'price' => (!empty($isThisSessionOnSale['html'])?$isThisSessionOnSale['html']:''),
856
                'subscribe_button' => isset($isThisSessionOnSale['buy_button']) ? $isThisSessionOnSale['buy_button'] : $this->getRegisteredInSessionButton(
857
                    $session->getId(),
858
                    $session->getName(),
859
                    $hasRequirements
860
                ),
861
                'show_description' => $session->getShowDescription(),
862
                'description' => $session->getDescription(),
863
                'category' => $catName,
864
                'tags' => $sessionCourseTags,
865
                'edit_actions' => $actions
866
            );
867
868
            $sessionsBlock = array_merge($sessionsBlock, $sequences);
869
            $sessionsBlocks[] = $sessionsBlock;
870
        }
871
872
        return $sessionsBlocks;
873
    }
874
}
875