Passed
Push — 1.11.x ( 1657fc...a933b7 )
by Angel Fernando Quiroz
10:12
created

Rest::setThreadNotify()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

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