Passed
Pull Request — 1.10.x (#986)
by
unknown
65:04
created

CoursesController::getFormatedSessionsBlock()   D

Complexity

Conditions 12
Paths 193

Size

Total Lines 102
Code Lines 68

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 102
rs 4.6933
cc 12
eloc 68
nc 193
nop 1

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