Test Setup Failed
Push — master ( ec638a...cb9435 )
by Julito
51:10
created

CoursesController::getFormattedSessionsBlock()   F

Complexity

Conditions 13
Paths 385

Size

Total Lines 121
Code Lines 85

Duplication

Lines 0
Ratio 0 %

Importance

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