Passed
Push — 1.11.x ( 47505b...220ec2 )
by Angel Fernando Quiroz
09:45 queued 11s
created

Rest::subscribeUserToCoursePassword()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 15
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

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