Passed
Push — master ( 9d7978...5faf0b )
by Julito
10:24
created

CoursesController::edit_course_category()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

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