Completed
Pull Request — 1.11.x (#1214)
by José
50:40
created

CoursesController::getFormatedSessionsBlock()   D

Complexity

Conditions 12
Paths 193

Size

Total Lines 116
Code Lines 80

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 12
eloc 80
c 1
b 0
f 1
nc 193
nop 1
dl 0
loc 116
rs 4.6933

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