Passed
Push — 1.11.x ( a18d33...1657fc )
by Angel Fernando Quiroz
08:16
created

Rest::getCourseLinks()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 64
Code Lines 41

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 41
nc 2
nop 0
dl 0
loc 64
rs 9.264
c 0
b 0
f 0

How to fix   Long Method   

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
3
/* For licensing terms, see /license.txt */
4
5
use Chamilo\CoreBundle\Entity\Course;
6
use Chamilo\CoreBundle\Entity\ExtraFieldValues;
7
use Chamilo\CoreBundle\Entity\Session;
8
use Chamilo\CourseBundle\Entity\CLpCategory;
9
use Chamilo\CourseBundle\Entity\CNotebook;
10
use Chamilo\CourseBundle\Entity\Repository\CNotebookRepository;
11
use Chamilo\UserBundle\Entity\User;
12
13
/**
14
 * Class RestApi.
15
 */
16
class Rest extends WebService
17
{
18
    const SERVICE_NAME = 'MsgREST';
19
    const EXTRA_FIELD_GCM_REGISTRATION = 'gcm_registration_id';
20
21
    const GET_AUTH = 'authenticate';
22
    const SAVE_GCM_ID = 'gcm_id';
23
    const LOGOUT = 'logout';
24
25
    const GET_USER_MESSAGES = 'user_messages';
26
    const GET_USER_MESSAGES_RECEIVED = 'user_messages_received';
27
    const DELETE_USER_MESSAGE = 'delete_user_message';
28
    const GET_USER_MESSAGES_SENT = 'user_messages_sent';
29
    const GET_COUNT_NEW_MESSAGES = 'get_count_new_messages';
30
    const SET_MESSAGE_READ = 'set_message_read';
31
    const POST_USER_MESSAGE_READ = 'user_message_read';
32
    const POST_USER_MESSAGE_UNREAD = 'user_message_unread';
33
    const SAVE_USER_MESSAGE = 'save_user_message';
34
    const GET_MESSAGE_USERS = 'message_users';
35
36
    const GET_USER_COURSES = 'user_courses';
37
    const GET_USER_SESSIONS = 'user_sessions';
38
39
    const GET_PROFILE = 'user_profile';
40
41
    const GET_COURSE_INFO = 'course_info';
42
    const GET_COURSE_DESCRIPTIONS = 'course_descriptions';
43
    const GET_COURSE_DOCUMENTS = 'course_documents';
44
    const GET_COURSE_ANNOUNCEMENTS = 'course_announcements';
45
    const GET_COURSE_ANNOUNCEMENT = 'course_announcement';
46
    const GET_COURSE_AGENDA = 'course_agenda';
47
    const GET_COURSE_NOTEBOOKS = 'course_notebooks';
48
    const GET_COURSE_FORUM_CATEGORIES = 'course_forumcategories';
49
    const GET_COURSE_FORUM = 'course_forum';
50
    const GET_COURSE_FORUM_THREAD = 'course_forumthread';
51
    const GET_COURSE_LEARNPATHS = 'course_learnpaths';
52
    const GET_COURSE_LEARNPATH = 'course_learnpath';
53
    const GET_COURSE_LP_PROGRESS = 'course_lp_progress';
54
    const GET_COURSE_LINKS = 'course_links';
55
56
    const SAVE_COURSE_NOTEBOOK = 'save_course_notebook';
57
58
    const SAVE_FORUM_POST = 'save_forum_post';
59
    const SAVE_FORUM_THREAD = 'save_forum_thread';
60
61
    const CREATE_CAMPUS = 'add_campus';
62
    const EDIT_CAMPUS = 'edit_campus';
63
    const DELETE_CAMPUS = 'delete_campus';
64
65
    const GET_USERS = 'get_users';
66
    const USERNAME_EXIST = 'username_exist';
67
    const SAVE_USER = 'save_user';
68
    const SAVE_USER_JSON = 'save_user_json';
69
    const UPDATE_USER_FROM_USERNAME = 'update_user_from_username';
70
    const DELETE_USER = 'delete_user';
71
72
    const GET_COURSES = 'get_courses';
73
    const GET_COURSES_FROM_EXTRA_FIELD = 'get_courses_from_extra_field';
74
    const SAVE_COURSE = 'save_course';
75
    const DELETE_COURSE = 'delete_course';
76
77
    const GET_SESSION_FROM_EXTRA_FIELD = 'get_session_from_extra_field';
78
    const SAVE_SESSION = 'save_session';
79
    const CREATE_SESSION_FROM_MODEL = 'create_session_from_model';
80
    const UPDATE_SESSION = 'update_session';
81
82
    const SUBSCRIBE_USER_TO_COURSE = 'subscribe_user_to_course';
83
    const SUBSCRIBE_USER_TO_COURSE_PASSWORD = 'subscribe_user_to_course_password';
84
    const UNSUBSCRIBE_USER_FROM_COURSE = 'unsubscribe_user_from_course';
85
    const GET_USERS_SUBSCRIBED_TO_COURSE = 'get_users_subscribed_to_course';
86
87
    const ADD_COURSES_SESSION = 'add_courses_session';
88
    const ADD_USERS_SESSION = 'add_users_session';
89
    const SUBSCRIBE_USER_TO_SESSION_FROM_USERNAME = 'subscribe_user_to_session_from_username';
90
91
    const GET_COURSE_QUIZ_MDL_COMPAT = 'get_course_quiz_mdl_compat';
92
93
    const UPDATE_USER_PAUSE_TRAINING = 'update_user_pause_training';
94
95
    const CHECK_CONDITIONAL_LOGIN = 'check_conditional_login';
96
    const GET_LEGAL_CONDITIONS = 'get_legal_conditions';
97
    const UPDATE_CONDITION_ACCEPTED = 'update_condition_accepted';
98
99
    /**
100
     * @var Session
101
     */
102
    private $session;
103
104
    /**
105
     * @var Course
106
     */
107
    private $course;
108
109
    /**
110
     * Rest constructor.
111
     *
112
     * @param string $username
113
     * @param string $apiKey
114
     */
115
    public function __construct($username, $apiKey)
116
    {
117
        parent::__construct($username, $apiKey);
118
    }
119
120
    /**
121
     * @param string $username
122
     * @param string $apiKeyToValidate
123
     *
124
     * @throws Exception
125
     *
126
     * @return Rest
127
     */
128
    public static function validate($username, $apiKeyToValidate)
129
    {
130
        $apiKey = self::findUserApiKey($username, self::SERVICE_NAME);
131
132
        if ($apiKey != $apiKeyToValidate) {
133
            throw new Exception(get_lang('InvalidApiKey'));
134
        }
135
136
        return new self($username, $apiKey);
137
    }
138
139
    /**
140
     * Create the gcm_registration_id extra field for users.
141
     */
142
    public static function init()
143
    {
144
        $extraField = new ExtraField('user');
145
        $fieldInfo = $extraField->get_handler_field_info_by_field_variable(self::EXTRA_FIELD_GCM_REGISTRATION);
146
147
        if (empty($fieldInfo)) {
148
            $extraField->save(
149
                [
150
                    'variable' => self::EXTRA_FIELD_GCM_REGISTRATION,
151
                    'field_type' => ExtraField::FIELD_TYPE_TEXT,
152
                    'display_text' => self::EXTRA_FIELD_GCM_REGISTRATION,
153
                ]
154
            );
155
        }
156
    }
157
158
    /**
159
     * @param string $encoded
160
     *
161
     * @return array
162
     */
163
    public static function decodeParams($encoded)
164
    {
165
        return json_decode($encoded);
166
    }
167
168
    /**
169
     * Set the current course.
170
     *
171
     * @param int $id
172
     *
173
     * @throws Exception
174
     */
175
    public function setCourse($id)
176
    {
177
        if (!$id) {
178
            $this->course = null;
179
180
            ChamiloSession::erase('_real_cid');
181
            ChamiloSession::erase('_cid');
182
            ChamiloSession::erase('_course');
183
184
            return;
185
        }
186
187
        $em = Database::getManager();
188
        /** @var Course $course */
189
        $course = $em->find('ChamiloCoreBundle:Course', $id);
190
191
        if (!$course) {
0 ignored issues
show
introduced by jmontoyaa
$course is of type Chamilo\CoreBundle\Entity\Course, thus it always evaluated to true.
Loading history...
192
            throw new Exception(get_lang('NoCourse'));
193
        }
194
195
        $this->course = $course;
196
197
        ChamiloSession::write('_real_cid', $course->getId());
198
        ChamiloSession::write('_cid', $course->getCode());
199
        ChamiloSession::write('_course', api_get_course_info($course->getCode()));
200
    }
201
202
    /**
203
     * Set the current session.
204
     *
205
     * @param int $id
206
     *
207
     * @throws Exception
208
     */
209
    public function setSession($id)
210
    {
211
        if (!$id) {
212
            $this->session = null;
213
214
            ChamiloSession::erase('session_name');
215
            ChamiloSession::erase('id_session');
216
217
            return;
218
        }
219
220
        $em = Database::getManager();
221
        /** @var Session $session */
222
        $session = $em->find('ChamiloCoreBundle:Session', $id);
223
224
        if (!$session) {
0 ignored issues
show
introduced by Angel Fernando Quiroz Campos
$session is of type Chamilo\CoreBundle\Entity\Session, thus it always evaluated to true.
Loading history...
225
            throw new Exception(get_lang('NoSession'));
226
        }
227
228
        $this->session = $session;
229
230
        ChamiloSession::write('session_name', $session->getName());
231
        ChamiloSession::write('id_session', $session->getId());
232
    }
233
234
    /**
235
     * @param string $registrationId
236
     *
237
     * @return bool
238
     */
239
    public function setGcmId($registrationId)
240
    {
241
        $registrationId = Security::remove_XSS($registrationId);
242
        $extraFieldValue = new ExtraFieldValue('user');
243
244
        return $extraFieldValue->save(
245
            [
246
                'variable' => self::EXTRA_FIELD_GCM_REGISTRATION,
247
                'value' => $registrationId,
248
                'item_id' => $this->user->getId(),
249
            ]
250
        );
251
    }
252
253
    /**
254
     * @param int $lastMessageId
255
     *
256
     * @return array
257
     */
258
    public function getUserMessages($lastMessageId = 0)
259
    {
260
        $lastMessages = MessageManager::getMessagesFromLastReceivedMessage($this->user->getId(), $lastMessageId);
261
        $messages = [];
262
263
        foreach ($lastMessages as $message) {
264
            $hasAttachments = MessageManager::hasAttachments($message['id']);
265
266
            $messages[] = [
267
                'id' => $message['id'],
268
                'title' => $message['title'],
269
                'sender' => [
270
                    'id' => $message['user_id'],
271
                    'lastname' => $message['lastname'],
272
                    'firstname' => $message['firstname'],
273
                    'completeName' => api_get_person_name($message['firstname'], $message['lastname']),
274
                ],
275
                'sendDate' => $message['send_date'],
276
                'content' => $message['content'],
277
                'hasAttachments' => $hasAttachments,
278
                'url' => api_get_path(WEB_CODE_PATH).'messages/view_message.php?'
279
                    .http_build_query(['type' => 1, 'id' => $message['id']]),
280
            ];
281
        }
282
283
        return $messages;
284
    }
285
286
    /**
287
     * @return array
288
     */
289
    public function getUserReceivedMessages()
290
    {
291
        $lastMessages = MessageManager::getReceivedMessages($this->user->getId(), 0);
292
        $messages = [];
293
294
        $webPath = api_get_path(WEB_PATH);
295
296
        foreach ($lastMessages as $message) {
297
            $hasAttachments = MessageManager::hasAttachments($message['id']);
298
            $attachmentList = [];
299
            if ($hasAttachments) {
300
                $attachmentList = MessageManager::getAttachmentList($message['id']);
301
            }
302
            $messages[] = [
303
                'id' => $message['id'],
304
                'title' => $message['title'],
305
                'msgStatus' => $message['msg_status'],
306
                'sender' => [
307
                    'id' => $message['user_id'],
308
                    'lastname' => $message['lastname'],
309
                    'firstname' => $message['firstname'],
310
                    'completeName' => api_get_person_name($message['firstname'], $message['lastname']),
311
                    'pictureUri' => $message['pictureUri'],
312
                ],
313
                'sendDate' => $message['send_date'],
314
                'content' => str_replace('src="/"', $webPath, $message['content']),
315
                'hasAttachments' => $hasAttachments,
316
                'attachmentList' => $attachmentList,
317
                'url' => '',
318
            ];
319
        }
320
321
        return $messages;
322
    }
323
324
    /**
325
     * @return array
326
     */
327
    public function getUserSentMessages()
328
    {
329
        $lastMessages = MessageManager::getSentMessages($this->user->getId(), 0);
330
        $messages = [];
331
332
        foreach ($lastMessages as $message) {
333
            $hasAttachments = MessageManager::hasAttachments($message['id']);
334
335
            $messages[] = [
336
                'id' => $message['id'],
337
                'title' => $message['title'],
338
                'msgStatus' => $message['msg_status'],
339
                'receiver' => [
340
                    'id' => $message['user_id'],
341
                    'lastname' => $message['lastname'],
342
                    'firstname' => $message['firstname'],
343
                    'completeName' => api_get_person_name($message['firstname'], $message['lastname']),
344
                    'pictureUri' => $message['pictureUri'],
345
                ],
346
                'sendDate' => $message['send_date'],
347
                'content' => $message['content'],
348
                'hasAttachments' => $hasAttachments,
349
                'url' => '',
350
            ];
351
        }
352
353
        return $messages;
354
    }
355
356
    /**
357
     * Get the user courses.
358
     */
359
    public function getUserCourses($userId = 0): array
360
    {
361
        if (empty($userId)) {
362
            $userId = $this->user->getId();
363
        }
364
365
        Event::courseLogout(
366
            [
367
                'uid' => $userId,
368
                'cid' => api_get_course_id(),
369
                'sid' => api_get_session_id(),
370
            ]
371
        );
372
373
        $courses = CourseManager::get_courses_list_by_user_id($userId);
374
        $data = [];
375
376
        foreach ($courses as $courseInfo) {
377
            /** @var Course $course */
378
            $course = Database::getManager()->find('ChamiloCoreBundle:Course', $courseInfo['real_id']);
379
            $teachers = CourseManager::getTeacherListFromCourseCodeToString($course->getCode());
380
            $picturePath = CourseManager::getPicturePath($course, true)
381
                ?: Display::return_icon('session_default.png', null, null, null, null, true);
382
383
            $data[] = [
384
                'id' => $course->getId(),
385
                'title' => $course->getTitle(),
386
                'code' => $course->getCode(),
387
                'directory' => $course->getDirectory(),
388
                'urlPicture' => $picturePath,
389
                'teachers' => $teachers,
390
                'isSpecial' => !empty($courseInfo['special_course']),
391
            ];
392
        }
393
394
        return $data;
395
    }
396
397
    /**
398
     * @throws Exception
399
     *
400
     * @return array
401
     */
402
    public function getCourseInfo()
403
    {
404
        $teachers = CourseManager::getTeacherListFromCourseCodeToString($this->course->getCode());
405
        $tools = CourseHome::get_tools_category(
406
            TOOL_STUDENT_VIEW,
407
            $this->course->getId(),
408
            $this->session ? $this->session->getId() : 0
409
        );
410
411
        return [
412
            'id' => $this->course->getId(),
413
            'title' => $this->course->getTitle(),
414
            'code' => $this->course->getCode(),
415
            'directory' => $this->course->getDirectory(),
416
            'urlPicture' => CourseManager::getPicturePath($this->course, true),
417
            'teachers' => $teachers,
418
            'tools' => array_map(
419
                function ($tool) {
420
                    return ['type' => $tool['name']];
421
                },
422
                $tools
423
            ),
424
        ];
425
    }
426
427
    /**
428
     * Get the course descriptions.
429
     *
430
     * @throws Exception
431
     *
432
     * @return array
433
     */
434
    public function getCourseDescriptions()
435
    {
436
        Event::event_access_tool(TOOL_COURSE_DESCRIPTION);
437
438
        $descriptions = CourseDescription::get_descriptions($this->course->getId());
439
        $results = [];
440
441
        $webPath = api_get_path(WEB_PATH);
442
443
        /** @var CourseDescription $description */
444
        foreach ($descriptions as $description) {
445
            $results[] = [
446
                'id' => $description->get_description_type(),
447
                'title' => $description->get_title(),
448
                'content' => str_replace('src="/', 'src="'.$webPath, $description->get_content()),
449
            ];
450
        }
451
452
        return $results;
453
    }
454
455
    /**
456
     * @param int $directoryId
457
     *
458
     * @throws Exception
459
     *
460
     * @return array
461
     */
462
    public function getCourseDocuments($directoryId = 0)
463
    {
464
        Event::event_access_tool(TOOL_DOCUMENT);
465
466
        /** @var string $path */
467
        $path = '/';
468
        $sessionId = $this->session ? $this->session->getId() : 0;
469
470
        if ($directoryId) {
471
            $directory = DocumentManager::get_document_data_by_id(
472
                $directoryId,
473
                $this->course->getCode(),
474
                false,
475
                $sessionId
476
            );
477
478
            if (!$directory) {
479
                throw new Exception('NoDataAvailable');
480
            }
481
482
            $path = $directory['path'];
483
        }
484
485
        $courseInfo = api_get_course_info_by_id($this->course->getId());
486
        $documents = DocumentManager::getAllDocumentData(
487
            $courseInfo,
488
            $path,
489
            0,
490
            null,
491
            false,
492
            false,
493
            $sessionId
494
        );
495
        $results = [];
496
497
        if (!empty($documents)) {
498
            $webPath = api_get_path(WEB_CODE_PATH).'document/document.php?';
499
500
            /** @var array $document */
501
            foreach ($documents as $document) {
502
                if ($document['visibility'] != '1') {
503
                    continue;
504
                }
505
506
                $icon = $document['filetype'] == 'file'
507
                    ? choose_image($document['path'])
508
                    : chooseFolderIcon($document['path']);
509
510
                $results[] = [
511
                    'id' => $document['id'],
512
                    'type' => $document['filetype'],
513
                    'title' => $document['title'],
514
                    'path' => $document['path'],
515
                    'url' => $webPath.http_build_query(
516
                        [
517
                            'username' => $this->user->getUsername(),
518
                            'api_key' => $this->apiKey,
519
                            'cidReq' => $this->course->getCode(),
520
                            'id_session' => $sessionId,
521
                            'gidReq' => 0,
522
                            'gradebook' => 0,
523
                            'origin' => '',
524
                            'action' => 'download',
525
                            'id' => $document['id'],
526
                        ]
527
                    ),
528
                    'icon' => $icon,
529
                    'size' => format_file_size($document['size']),
530
                ];
531
            }
532
        }
533
534
        return $results;
535
    }
536
537
    /**
538
     * @throws Exception
539
     *
540
     * @return array
541
     */
542
    public function getCourseAnnouncements()
543
    {
544
        Event::event_access_tool(TOOL_ANNOUNCEMENT);
545
546
        $sessionId = $this->session ? $this->session->getId() : 0;
547
548
        $announcements = AnnouncementManager::getAnnouncements(
549
            null,
550
            null,
551
            false,
552
            null,
553
            null,
554
            null,
555
            null,
556
            null,
557
            0,
558
            $this->user->getId(),
559
            $this->course->getId(),
560
            $sessionId
561
        );
562
563
        $announcements = array_map(
564
            function ($announcement) {
565
                return [
566
                    'id' => (int) $announcement['id'],
567
                    'title' => strip_tags($announcement['title']),
568
                    'creatorName' => strip_tags($announcement['username']),
569
                    'date' => strip_tags($announcement['insert_date']),
570
                ];
571
            },
572
            $announcements
573
        );
574
575
        return $announcements;
576
    }
577
578
    /**
579
     * @param int $announcementId
580
     *
581
     * @throws Exception
582
     *
583
     * @return array
584
     */
585
    public function getCourseAnnouncement($announcementId)
586
    {
587
        Event::event_access_tool(TOOL_ANNOUNCEMENT);
588
589
        $sessionId = $this->session ? $this->session->getId() : 0;
590
        $announcement = AnnouncementManager::getAnnouncementInfoById(
591
            $announcementId,
592
            $this->course->getId(),
593
            $this->user->getId()
594
        );
595
596
        if (!$announcement) {
597
            throw new Exception(get_lang('NoAnnouncement'));
598
        }
599
600
        return [
601
            'id' => $announcement['announcement']->getIid(),
602
            'title' => $announcement['announcement']->getTitle(),
603
            'creatorName' => UserManager::formatUserFullName($announcement['item_property']->getInsertUser()),
604
            'date' => api_convert_and_format_date(
605
                $announcement['item_property']->getInsertDate(),
606
                DATE_TIME_FORMAT_LONG_24H
607
            ),
608
            'content' => AnnouncementManager::parseContent(
609
                $this->user->getId(),
610
                $announcement['announcement']->getContent(),
611
                $this->course->getCode(),
612
                $sessionId
613
            ),
614
        ];
615
    }
616
617
    /**
618
     * @throws Exception
619
     *
620
     * @return array
621
     */
622
    public function getCourseAgenda()
623
    {
624
        Event::event_access_tool(TOOL_CALENDAR_EVENT);
625
626
        $sessionId = $this->session ? $this->session->getId() : 0;
627
628
        $agenda = new Agenda(
629
            'course',
630
            $this->user->getId(),
631
            $this->course->getId(),
632
            $sessionId
633
        );
634
        $result = $agenda->parseAgendaFilter(null);
635
636
        $start = new DateTime(api_get_utc_datetime(), new DateTimeZone('UTC'));
637
        $start->modify('first day of this month');
638
        $start->setTime(0, 0, 0);
639
        $end = new DateTime(api_get_utc_datetime(), new DateTimeZone('UTC'));
640
        $end->modify('last day of this month');
641
        $end->setTime(23, 59, 59);
642
643
        $groupId = current($result['groups']);
644
        $userId = current($result['users']);
645
646
        $events = $agenda->getEvents(
647
            $start->getTimestamp(),
648
            $end->getTimestamp(),
649
            $this->course->getId(),
650
            $groupId,
651
            $userId,
652
            'array'
653
        );
654
655
        if (!is_array($events)) {
656
            return [];
657
        }
658
659
        $webPath = api_get_path(WEB_PATH);
660
661
        return array_map(
662
            function ($event) use ($webPath) {
663
                return [
664
                    'id' => (int) $event['unique_id'],
665
                    'title' => $event['title'],
666
                    'content' => str_replace('src="/', 'src="'.$webPath, $event['description']),
667
                    'startDate' => $event['start_date_localtime'],
668
                    'endDate' => $event['end_date_localtime'],
669
                    'isAllDay' => $event['allDay'] ? true : false,
670
                ];
671
            },
672
            $events
673
        );
674
    }
675
676
    /**
677
     * @throws Exception
678
     *
679
     * @return array
680
     */
681
    public function getCourseNotebooks()
682
    {
683
        Event::event_access_tool(TOOL_NOTEBOOK);
684
685
        $em = Database::getManager();
686
        /** @var CNotebookRepository $notebooksRepo */
687
        $notebooksRepo = $em->getRepository('ChamiloCourseBundle:CNotebook');
688
        $notebooks = $notebooksRepo->findByUser($this->user, $this->course, $this->session);
689
690
        return array_map(
691
            function (CNotebook $notebook) {
692
                return [
693
                    'id' => $notebook->getIid(),
694
                    'title' => $notebook->getTitle(),
695
                    'description' => $notebook->getDescription(),
696
                    'creationDate' => api_format_date(
697
                        $notebook->getCreationDate()->getTimestamp()
698
                    ),
699
                    'updateDate' => api_format_date(
700
                        $notebook->getUpdateDate()->getTimestamp()
701
                    ),
702
                ];
703
            },
704
            $notebooks
705
        );
706
    }
707
708
    /**
709
     * @throws Exception
710
     *
711
     * @return array
712
     */
713
    public function getCourseForumCategories()
714
    {
715
        Event::event_access_tool(TOOL_FORUM);
716
717
        $sessionId = $this->session ? $this->session->getId() : 0;
718
        $webCoursePath = api_get_path(WEB_COURSE_PATH).$this->course->getDirectory().'/upload/forum/images/';
719
720
        require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
721
722
        $categoriesFullData = get_forum_categories('', $this->course->getId(), $sessionId);
723
        $categories = [];
724
        $includeGroupsForums = api_get_setting('display_groups_forum_in_general_tool') === 'true';
725
        $forumsFullData = get_forums('', $this->course->getCode(), $includeGroupsForums, $sessionId);
726
        $forums = [];
727
728
        foreach ($forumsFullData as $forumId => $forumInfo) {
729
            $forum = [
730
                'id' => (int) $forumInfo['iid'],
731
                'catId' => (int) $forumInfo['forum_category'],
732
                'title' => $forumInfo['forum_title'],
733
                'description' => $forumInfo['forum_comment'],
734
                'image' => $forumInfo['forum_image'] ? ($webCoursePath.$forumInfo['forum_image']) : '',
735
                'numberOfThreads' => isset($forumInfo['number_of_threads']) ? intval(
736
                    $forumInfo['number_of_threads']
737
                ) : 0,
738
                'lastPost' => null,
739
            ];
740
741
            $lastPostInfo = get_last_post_information($forumId, false, $this->course->getId(), $sessionId);
742
743
            if ($lastPostInfo) {
744
                $forum['lastPost'] = [
745
                    'date' => api_convert_and_format_date($lastPostInfo['last_post_date']),
746
                    'user' => api_get_person_name(
747
                        $lastPostInfo['last_poster_firstname'],
748
                        $lastPostInfo['last_poster_lastname']
749
                    ),
750
                ];
751
            }
752
753
            $forums[] = $forum;
754
        }
755
756
        foreach ($categoriesFullData as $category) {
757
            $categoryForums = array_filter(
758
                $forums,
759
                function (array $forum) use ($category) {
760
                    if ($forum['catId'] != $category['cat_id']) {
761
                        return false;
762
                    }
763
764
                    return true;
765
                }
766
            );
767
768
            $categories[] = [
769
                'id' => (int) $category['iid'],
770
                'title' => $category['cat_title'],
771
                'catId' => (int) $category['cat_id'],
772
                'description' => $category['cat_comment'],
773
                'forums' => $categoryForums,
774
                'courseId' => $this->course->getId(),
775
            ];
776
        }
777
778
        return $categories;
779
    }
780
781
    /**
782
     * @param int $forumId
783
     *
784
     * @throws Exception
785
     *
786
     * @return array
787
     */
788
    public function getCourseForum($forumId)
789
    {
790
        Event::event_access_tool(TOOL_FORUM);
791
792
        require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
793
794
        $sessionId = $this->session ? $this->session->getId() : 0;
795
        $forumInfo = get_forums($forumId, $this->course->getCode(), true, $sessionId);
796
797
        if (!isset($forumInfo['iid'])) {
798
            throw new Exception(get_lang('NoForum'));
799
        }
800
801
        $webCoursePath = api_get_path(WEB_COURSE_PATH).$this->course->getDirectory().'/upload/forum/images/';
802
        $forum = [
803
            'id' => $forumInfo['iid'],
804
            'title' => $forumInfo['forum_title'],
805
            'description' => $forumInfo['forum_comment'],
806
            'image' => $forumInfo['forum_image'] ? ($webCoursePath.$forumInfo['forum_image']) : '',
807
            'threads' => [],
808
        ];
809
810
        $threads = get_threads($forumInfo['iid'], $this->course->getId(), $sessionId);
811
812
        foreach ($threads as $thread) {
813
            $forum['threads'][] = [
814
                'id' => $thread['iid'],
815
                'title' => $thread['thread_title'],
816
                'lastEditDate' => api_convert_and_format_date($thread['lastedit_date'], DATE_TIME_FORMAT_LONG_24H),
817
                'numberOfReplies' => $thread['thread_replies'],
818
                'numberOfViews' => $thread['thread_views'],
819
                'author' => api_get_person_name($thread['firstname'], $thread['lastname']),
820
            ];
821
        }
822
823
        return $forum;
824
    }
825
826
    /**
827
     * @param int $forumId
828
     * @param int $threadId
829
     *
830
     * @return array
831
     */
832
    public function getCourseForumThread($forumId, $threadId)
833
    {
834
        Event::event_access_tool(TOOL_FORUM);
835
836
        require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
837
838
        $sessionId = $this->session ? $this->session->getId() : 0;
839
        $threadInfo = get_thread_information($forumId, $threadId, $sessionId);
840
841
        $thread = [
842
            'id' => intval($threadInfo['iid']),
843
            'cId' => intval($threadInfo['c_id']),
844
            'title' => $threadInfo['thread_title'],
845
            'forumId' => intval($threadInfo['forum_id']),
846
            'posts' => [],
847
        ];
848
849
        $forumInfo = get_forums($threadInfo['forum_id'], $this->course->getCode(), true, $sessionId);
850
        $postsInfo = getPosts($forumInfo, $threadInfo['iid'], 'ASC');
851
852
        foreach ($postsInfo as $postInfo) {
853
            $thread['posts'][] = [
854
                'id' => $postInfo['iid'],
855
                'title' => $postInfo['post_title'],
856
                'text' => $postInfo['post_text'],
857
                'author' => api_get_person_name($postInfo['firstname'], $postInfo['lastname']),
858
                'date' => api_convert_and_format_date($postInfo['post_date'], DATE_TIME_FORMAT_LONG_24H),
859
                'parentId' => $postInfo['post_parent_id'],
860
            ];
861
        }
862
863
        return $thread;
864
    }
865
866
    public function getCourseLinks(): array
867
    {
868
        Event::event_access_tool(TOOL_LINK);
869
870
        $courseId = $this->course->getId();
871
        $sessionId = $this->session ? $this->session->getId() : 0;
872
873
        $webCodePath = api_get_path(WEB_CODE_PATH);
874
        $cidReq = api_get_cidreq();
875
876
        $categories = array_merge(
877
            [
878
                [
879
                    'iid' => 0,
880
                    'c_id' => $courseId,
881
                    'id' => 0,
882
                    'category_title' => get_lang('NoCategory'),
883
                    'description' => '',
884
                    'display_order' => 0,
885
                    'session_id' => $sessionId,
886
                    'visibility' => 1,
887
                ]
888
            ],
889
            Link::getLinkCategories($courseId, $sessionId)
890
        );
891
892
        $categories = array_filter(
893
            $categories,
894
            function (array $category) {
895
                return $category['visibility'] != 0;
896
            }
897
        );
898
899
        return array_map(
900
            function (array $category) use ($webCodePath, $cidReq, $courseId, $sessionId) {
901
                $links = array_filter(
902
                    Link::getLinksPerCategory($category['iid'], $courseId, $sessionId),
903
                    function (array $link) {
904
                        return $link['visibility'] != 0;
905
                    }
906
                );
907
908
                $links = array_map(
909
                    function (array $link) use ($webCodePath, $cidReq) {
910
                        return [
911
                            'id' => (int) $link['id'],
912
                            'title' => Security::remove_XSS($link['title']),
913
                            'description' => Security::remove_XSS($link['description']),
914
                            'visibility' => (int) $link['visibility'],
915
                            'url' => $webCodePath."link/link_goto.php?$cidReq&link_id=".$link['id']
916
                        ];
917
                    },
918
                    $links
919
                );
920
921
                return [
922
                    'id' => (int) $category['iid'],
923
                    'title' => Security::remove_XSS($category['category_title']),
924
                    'description' => Security::remove_XSS($category['description']),
925
                    'visibility' => (int) $category['visibility'],
926
                    'links' => $links,
927
                ];
928
            },
929
            $categories
930
        );
931
    }
932
933
    /**
934
     * @return array
935
     */
936
    public function getUserProfile()
937
    {
938
        $pictureInfo = UserManager::get_user_picture_path_by_id($this->user->getId(), 'web');
939
940
        $result = [
941
            'pictureUri' => $pictureInfo['dir'].$pictureInfo['file'],
942
            'id' => $this->user->getId(),
943
            'status' => $this->user->getStatus(),
944
            'fullName' => UserManager::formatUserFullName($this->user),
945
            'username' => $this->user->getUsername(),
946
            'officialCode' => $this->user->getOfficialCode(),
947
            'phone' => $this->user->getPhone(),
948
            'extra' => [],
949
        ];
950
951
        $fieldValue = new ExtraFieldValue('user');
952
        $extraInfo = $fieldValue->getAllValuesForAnItem($this->user->getId(), true);
953
954
        foreach ($extraInfo as $extra) {
955
            /** @var ExtraFieldValues $extraValue */
956
            $extraValue = $extra['value'];
957
            $result['extra'][] = [
958
                'title' => $extraValue->getField()->getDisplayText(true),
959
                'value' => $extraValue->getValue(),
960
            ];
961
        }
962
963
        return $result;
964
    }
965
966
    public function getCourseLpProgress()
967
    {
968
        $sessionId = $this->session ? $this->session->getId() : 0;
969
        $userId = $this->user->getId();
970
971
        /*$sessionId = $this->session ? $this->session->getId() : 0;
972
        $courseId = $this->course->getId();*/
973
974
        $result = Tracking::getCourseLpProgress($userId, $sessionId);
975
976
        return [$result];
977
    }
978
979
    /**
980
     * @throws Exception
981
     *
982
     * @return array
983
     */
984
    public function getCourseLearnPaths()
985
    {
986
        Event::event_access_tool(TOOL_LEARNPATH);
987
988
        $sessionId = $this->session ? $this->session->getId() : 0;
989
        $categoriesTempList = learnpath::getCategories($this->course->getId());
990
991
        $categoryNone = new CLpCategory();
992
        $categoryNone->setId(0);
993
        $categoryNone->setName(get_lang('WithOutCategory'));
994
        $categoryNone->setPosition(0);
995
996
        $categories = array_merge([$categoryNone], $categoriesTempList);
997
        $categoryData = [];
998
999
        /** @var CLpCategory $category */
1000
        foreach ($categories as $category) {
1001
            $learnPathList = new LearnpathList(
1002
                $this->user->getId(),
1003
                api_get_course_info($this->course->getCode()),
1004
                $sessionId,
1005
                null,
1006
                false,
1007
                $category->getId()
1008
            );
1009
1010
            $flatLpList = $learnPathList->get_flat_list();
1011
1012
            if (empty($flatLpList)) {
1013
                continue;
1014
            }
1015
1016
            $listData = [];
1017
1018
            foreach ($flatLpList as $lpId => $lpDetails) {
1019
                if ($lpDetails['lp_visibility'] == 0) {
1020
                    continue;
1021
                }
1022
1023
                if (!learnpath::is_lp_visible_for_student(
1024
                    $lpId,
1025
                    $this->user->getId(),
1026
                    api_get_course_info($this->course->getCode()),
1027
                    $sessionId
1028
                )) {
1029
                    continue;
1030
                }
1031
1032
                $timeLimits = false;
1033
1034
                // This is an old LP (from a migration 1.8.7) so we do nothing
1035
                if (empty($lpDetails['created_on']) && empty($lpDetails['modified_on'])) {
1036
                    $timeLimits = false;
1037
                }
1038
1039
                // Checking if expired_on is ON
1040
                if (!empty($lpDetails['expired_on'])) {
1041
                    $timeLimits = true;
1042
                }
1043
1044
                if ($timeLimits) {
1045
                    if (!empty($lpDetails['publicated_on']) && !empty($lpDetails['expired_on'])) {
1046
                        $startTime = api_strtotime($lpDetails['publicated_on'], 'UTC');
1047
                        $endTime = api_strtotime($lpDetails['expired_on'], 'UTC');
1048
                        $now = time();
1049
                        $isActiveTime = false;
1050
1051
                        if ($now > $startTime && $endTime > $now) {
1052
                            $isActiveTime = true;
1053
                        }
1054
1055
                        if (!$isActiveTime) {
1056
                            continue;
1057
                        }
1058
                    }
1059
                }
1060
1061
                $progress = learnpath::getProgress($lpId, $this->user->getId(), $this->course->getId(), $sessionId);
1062
1063
                $listData[] = [
1064
                    'id' => $lpId,
1065
                    'title' => Security::remove_XSS($lpDetails['lp_name']),
1066
                    'progress' => $progress,
1067
                    'url' => api_get_path(WEB_CODE_PATH).'webservices/api/v2.php?'.http_build_query(
1068
                        [
1069
                            'hash' => $this->encodeParams(
1070
                                [
1071
                                    'action' => 'course_learnpath',
1072
                                    'lp_id' => $lpId,
1073
                                    'course' => $this->course->getId(),
1074
                                    'session' => $sessionId,
1075
                                ]
1076
                            ),
1077
                        ]
1078
                    ),
1079
                ];
1080
            }
1081
1082
            if (empty($listData)) {
1083
                continue;
1084
            }
1085
1086
            $categoryData[] = [
1087
                'id' => $category->getId(),
1088
                'name' => $category->getName(),
1089
                'learnpaths' => $listData,
1090
            ];
1091
        }
1092
1093
        return $categoryData;
1094
    }
1095
1096
    /**
1097
     * Start login for a user. Then make a redirect to show the learnpath.
1098
     *
1099
     * @param int $lpId
1100
     */
1101
    public function showLearningPath($lpId)
1102
    {
1103
        $loggedUser['user_id'] = $this->user->getId();
1104
        $loggedUser['status'] = $this->user->getStatus();
1105
        $loggedUser['uidReset'] = true;
1106
        $sessionId = $this->session ? $this->session->getId() : 0;
1107
1108
        ChamiloSession::write('_user', $loggedUser);
1109
        Login::init_user($this->user->getId(), true);
1110
1111
        $url = api_get_path(WEB_CODE_PATH).'lp/lp_controller.php?'.http_build_query(
1112
            [
1113
                'cidReq' => $this->course->getCode(),
1114
                'id_session' => $sessionId,
1115
                'gidReq' => 0,
1116
                'gradebook' => 0,
1117
                'origin' => '',
1118
                'action' => 'view',
1119
                'lp_id' => (int) $lpId,
1120
                'isStudentView' => 'true',
1121
            ]
1122
        );
1123
1124
        header("Location: $url");
1125
        exit;
1126
    }
1127
1128
    /**
1129
     * @param int $forumId
1130
     *
1131
     * @return array
1132
     */
1133
    public function saveForumPost(array $postValues, $forumId)
1134
    {
1135
        Event::event_access_tool(TOOL_FORUM);
1136
1137
        require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
1138
1139
        $forum = get_forums($forumId, $this->course->getCode());
1140
        store_reply($forum, $postValues, $this->course->getId(), $this->user->getId());
1141
1142
        return [
1143
            'registered' => true,
1144
        ];
1145
    }
1146
1147
    /**
1148
     * Get the list of sessions for current user.
1149
     *
1150
     * @return array the sessions list
1151
     */
1152
    public function getUserSessions()
1153
    {
1154
        $data = [];
1155
        $sessionsByCategory = UserManager::get_sessions_by_category($this->user->getId(), false);
1156
1157
        foreach ($sessionsByCategory as $category) {
1158
            $categorySessions = [];
1159
1160
            foreach ($category['sessions'] as $sessions) {
1161
                $sessionCourses = [];
1162
1163
                foreach ($sessions['courses'] as $course) {
1164
                    $courseInfo = api_get_course_info_by_id($course['real_id']);
1165
                    $teachers = SessionManager::getCoachesByCourseSessionToString(
1166
                        $sessions['session_id'],
1167
                        $course['real_id']
1168
                    );
1169
1170
                    $sessionCourses[] = [
1171
                        'id' => $courseInfo['real_id'],
1172
                        'title' => $courseInfo['title'],
1173
                        'code' => $courseInfo['code'],
1174
                        'directory' => $courseInfo['directory'],
1175
                        'pictureUrl' => $courseInfo['course_image_large'],
1176
                        'urlPicture' => $courseInfo['course_image_large'],
1177
                        'teachers' => $teachers,
1178
                    ];
1179
                }
1180
1181
                $sessionBox = Display::getSessionTitleBox($sessions['session_id']);
1182
1183