Passed
Push — 1.11.x ( fc4f1e...153878 )
by Julito
12:47
created

Rest::getUserSentMessages()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 27
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 19
nc 2
nop 0
dl 0
loc 27
rs 9.6333
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 GET_USER_MESSAGES = 'user_messages';
23
    const POST_USER_MESSAGE_READ = 'user_message_read';
24
    const POST_USER_MESSAGE_UNREAD = 'user_message_unread';
25
    const SAVE_GCM_ID = 'gcm_id';
26
    const GET_USER_COURSES = 'user_courses';
27
    const GET_PROFILE = 'user_profile';
28
    const GET_COURSE_INFO = 'course_info';
29
    const GET_COURSE_DESCRIPTIONS = 'course_descriptions';
30
    const GET_COURSE_DOCUMENTS = 'course_documents';
31
    const GET_COURSE_ANNOUNCEMENTS = 'course_announcements';
32
    const GET_COURSE_ANNOUNCEMENT = 'course_announcement';
33
    const GET_COURSE_AGENDA = 'course_agenda';
34
    const GET_COURSE_NOTEBOOKS = 'course_notebooks';
35
    const GET_COURSE_FORUM_CATEGORIES = 'course_forumcategories';
36
    const GET_COURSE_FORUM = 'course_forum';
37
    const GET_COURSE_FORUM_THREAD = 'course_forumthread';
38
    const GET_COURSE_LEARNPATHS = 'course_learnpaths';
39
    const GET_COURSE_LEARNPATH = 'course_learnpath';
40
    const GET_COURSE_LP_PROGRESS = 'course_lp_progress';
41
    const SAVE_FORUM_POST = 'save_forum_post';
42
    const GET_USER_SESSIONS = 'user_sessions';
43
    const SAVE_USER_MESSAGE = 'save_user_message';
44
    const GET_MESSAGE_USERS = 'message_users';
45
    const SAVE_COURSE_NOTEBOOK = 'save_course_notebook';
46
    const SAVE_FORUM_THREAD = 'save_forum_thread';
47
    const SAVE_COURSE = 'save_course';
48
    const SAVE_USER = 'save_user';
49
    const SUBSCRIBE_USER_TO_COURSE = 'subscribe_user_to_course';
50
    const EXTRAFIELD_GCM_ID = 'gcm_registration_id';
51
    const GET_USER_MESSAGES_RECEIVED = 'user_messages_received';
52
    const GET_USER_MESSAGES_SENT = 'user_messages_sent';
53
    const DELETE_USER_MESSAGE = 'delete_user_message';
54
    const SET_MESSAGE_READ = 'set_message_read';
55
    const CREATE_CAMPUS = 'add_campus';
56
    const EDIT_CAMPUS = 'edit_campus';
57
    const DELETE_CAMPUS = 'delete_campus';
58
    const SAVE_SESSION = 'save_session';
59
    const GET_USERS = 'get_users';
60
    const GET_COURSES = 'get_courses';
61
    const ADD_COURSES_SESSION = 'add_courses_session';
62
    const ADD_USERS_SESSION = 'add_users_session';
63
    const CREATE_SESSION_FROM_MODEL = 'create_session_from_model';
64
    const SUBSCRIBE_USER_TO_SESSION_FROM_USERNAME = 'subscribe_user_to_session_from_username';
65
    const GET_SESSION_FROM_EXTRA_FIELD = 'get_session_from_extra_field';
66
    const UPDATE_USER_FROM_USERNAME = 'update_user_from_username';
67
    const USERNAME_EXIST = 'username_exist';
68
69
    /**
70
     * @var Session
71
     */
72
    private $session;
73
74
    /**
75
     * @var Course
76
     */
77
    private $course;
78
79
    /**
80
     * Rest constructor.
81
     *
82
     * @param string $username
83
     * @param string $apiKey
84
     */
85
    public function __construct($username, $apiKey)
86
    {
87
        parent::__construct($username, $apiKey);
88
    }
89
90
    /**
91
     * @param string $username
92
     * @param string $apiKeyToValidate
93
     *
94
     * @return Rest
95
     * @throws Exception
96
     *
97
     */
98
    public static function validate($username, $apiKeyToValidate)
99
    {
100
        $apiKey = self::findUserApiKey($username, self::SERVICE_NAME);
101
102
        if ($apiKey != $apiKeyToValidate) {
103
            throw new Exception(get_lang('InvalidApiKey'));
104
        }
105
106
        return new self($username, $apiKey);
107
    }
108
109
    /**
110
     * Create the gcm_registration_id extra field for users.
111
     */
112
    public static function init()
113
    {
114
        $extraField = new ExtraField('user');
115
        $fieldInfo = $extraField->get_handler_field_info_by_field_variable(self::EXTRA_FIELD_GCM_REGISTRATION);
116
117
        if (empty($fieldInfo)) {
118
            $extraField->save(
119
                [
120
                    'variable' => self::EXTRA_FIELD_GCM_REGISTRATION,
121
                    'field_type' => ExtraField::FIELD_TYPE_TEXT,
122
                    'display_text' => self::EXTRA_FIELD_GCM_REGISTRATION,
123
                ]
124
            );
125
        }
126
    }
127
128
    /**
129
     * @param string $encoded
130
     *
131
     * @return array
132
     */
133
    public static function decodeParams($encoded)
134
    {
135
        return json_decode($encoded);
136
    }
137
138
    /**
139
     * Set the current course.
140
     *
141
     * @param int $id
142
     *
143
     * @throws Exception
144
     */
145
    public function setCourse($id)
146
    {
147
        if (!$id) {
148
            $this->course = null;
149
150
            return;
151
        }
152
153
        $em = Database::getManager();
154
        /** @var Course $course */
155
        $course = $em->find('ChamiloCoreBundle:Course', $id);
156
157
        if (!$course) {
0 ignored issues
show
introduced by
$course is of type Chamilo\CoreBundle\Entity\Course, thus it always evaluated to true.
Loading history...
158
            throw new Exception(get_lang('NoCourse'));
159
        }
160
161
        $this->course = $course;
162
    }
163
164
    /** Set the current session
165
     *
166
     * @param int $id
167
     *
168
     * @throws Exception
169
     */
170
    public function setSession($id)
171
    {
172
        if (!$id) {
173
            $this->session = null;
174
175
            return;
176
        }
177
178
        $em = Database::getManager();
179
        /** @var Session $session */
180
        $session = $em->find('ChamiloCoreBundle:Session', $id);
181
182
        if (!$session) {
0 ignored issues
show
introduced by
$session is of type Chamilo\CoreBundle\Entity\Session, thus it always evaluated to true.
Loading history...
183
            throw new Exception(get_lang('NoSession'));
184
        }
185
186
        $this->session = $session;
187
    }
188
189
    /**
190
     * @param string $registrationId
191
     *
192
     * @return bool
193
     */
194
    public function setGcmId($registrationId)
195
    {
196
        $registrationId = Security::remove_XSS($registrationId);
197
        $extraFieldValue = new ExtraFieldValue('user');
198
199
        return $extraFieldValue->save(
200
            [
201
                'variable' => self::EXTRA_FIELD_GCM_REGISTRATION,
202
                'value' => $registrationId,
203
                'item_id' => $this->user->getId(),
204
            ]
205
        );
206
    }
207
208
    /**
209
     * @param int $lastMessageId
210
     *
211
     * @return array
212
     */
213
    public function getUserMessages($lastMessageId = 0)
214
    {
215
        $lastMessages = MessageManager::getMessagesFromLastReceivedMessage($this->user->getId(), $lastMessageId);
216
        $messages = [];
217
218
        foreach ($lastMessages as $message) {
219
            $hasAttachments = MessageManager::hasAttachments($message['id']);
220
221
            $messages[] = [
222
                'id' => $message['id'],
223
                'title' => $message['title'],
224
                'sender' => [
225
                    'id' => $message['user_id'],
226
                    'lastname' => $message['lastname'],
227
                    'firstname' => $message['firstname'],
228
                    'completeName' => api_get_person_name($message['firstname'], $message['lastname']),
229
                ],
230
                'sendDate' => $message['send_date'],
231
                'content' => $message['content'],
232
                'hasAttachments' => $hasAttachments,
233
                'url' => api_get_path(WEB_CODE_PATH).'messages/view_message.php?'
234
                    .http_build_query(['type' => 1, 'id' => $message['id']]),
235
            ];
236
        }
237
238
        return $messages;
239
    }
240
241
    /**
242
     * @return array
243
     */
244
    public function getUserReceivedMessages()
245
    {
246
        $lastMessages = MessageManager::getReceivedMessages($this->user->getId(), 0);
247
        $messages = [];
248
249
        foreach ($lastMessages as $message) {
250
            $hasAttachments = MessageManager::hasAttachments($message['id']);
251
            $attachmentList = [];
252
            if ($hasAttachments) {
253
                $attachmentList = MessageManager::getAttachmentList($message['id']);
254
            }
255
            $messages[] = [
256
                'id' => $message['id'],
257
                'title' => $message['title'],
258
                'msgStatus' => $message['msg_status'],
259
                'sender' => [
260
                    'id' => $message['user_id'],
261
                    'lastname' => $message['lastname'],
262
                    'firstname' => $message['firstname'],
263
                    'completeName' => api_get_person_name($message['firstname'], $message['lastname']),
264
                    'pictureUri' => $message['pictureUri'],
265
                ],
266
                'sendDate' => $message['send_date'],
267
                'content' => $message['content'],
268
                'hasAttachments' => $hasAttachments,
269
                'attachmentList' => $attachmentList,
270
                'url' => '',
271
            ];
272
        }
273
274
        return $messages;
275
    }
276
277
    /**
278
     * @return array
279
     */
280
    public function getUserSentMessages()
281
    {
282
        $lastMessages = MessageManager::getSentMessages($this->user->getId(), 0);
283
        $messages = [];
284
285
        foreach ($lastMessages as $message) {
286
            $hasAttachments = MessageManager::hasAttachments($message['id']);
287
288
            $messages[] = [
289
                'id' => $message['id'],
290
                'title' => $message['title'],
291
                'msgStatus' => $message['msg_status'],
292
                'receiver' => [
293
                    'id' => $message['user_id'],
294
                    'lastname' => $message['lastname'],
295
                    'firstname' => $message['firstname'],
296
                    'completeName' => api_get_person_name($message['firstname'], $message['lastname']),
297
                    'pictureUri' => $message['pictureUri'],
298
                ],
299
                'sendDate' => $message['send_date'],
300
                'content' => $message['content'],
301
                'hasAttachments' => $hasAttachments,
302
                'url' => '',
303
            ];
304
        }
305
306
        return $messages;
307
    }
308
309
    /**
310
     * Get the user courses.
311
     *
312
     * @return array
313
     * @throws \Doctrine\ORM\TransactionRequiredException
314
     * @throws \Doctrine\ORM\ORMException
315
     *
316
     * @throws \Doctrine\ORM\OptimisticLockException
317
     */
318
    public function getUserCourses()
319
    {
320
        $courses = CourseManager::get_courses_list_by_user_id($this->user->getId());
321
        $data = [];
322
323
        foreach ($courses as $courseInfo) {
324
            /** @var Course $course */
325
            $course = Database::getManager()->find('ChamiloCoreBundle:Course', $courseInfo['real_id']);
326
            $teachers = CourseManager::getTeacherListFromCourseCodeToString($course->getCode());
327
            $picturePath = CourseManager::getPicturePath($course, true)
328
                ?: Display::return_icon('session_default.png', null, null, null, null, true);
329
330
            $data[] = [
331
                'id' => $course->getId(),
332
                'title' => $course->getTitle(),
333
                'code' => $course->getCode(),
334
                'directory' => $course->getDirectory(),
335
                'urlPicture' => $picturePath,
336
                'teachers' => $teachers,
337
                'isSpecial' => !empty($courseInfo['special_course']),
338
            ];
339
        }
340
341
        return $data;
342
    }
343
344
    /**
345
     * @return array
346
     * @throws Exception
347
     *
348
     */
349
    public function getCourseInfo()
350
    {
351
        $teachers = CourseManager::getTeacherListFromCourseCodeToString($this->course->getCode());
352
        $tools = CourseHome::get_tools_category(
353
            TOOL_STUDENT_VIEW,
354
            $this->course->getId(),
355
            $this->session ? $this->session->getId() : 0
356
        );
357
358
        return [
359
            'id' => $this->course->getId(),
360
            'title' => $this->course->getTitle(),
361
            'code' => $this->course->getCode(),
362
            'directory' => $this->course->getDirectory(),
363
            'urlPicture' => CourseManager::getPicturePath($this->course, true),
364
            'teachers' => $teachers,
365
            'tools' => array_map(
366
                function ($tool) {
367
                    return ['type' => $tool['name']];
368
                },
369
                $tools
370
            ),
371
        ];
372
    }
373
374
    /**
375
     * Get the course descriptions.
376
     *
377
     * @return array
378
     * @throws Exception
379
     *
380
     */
381
    public function getCourseDescriptions()
382
    {
383
        $descriptions = CourseDescription::get_descriptions($this->course->getId());
384
        $results = [];
385
386
        /** @var CourseDescription $description */
387
        foreach ($descriptions as $description) {
388
            $results[] = [
389
                'id' => $description->get_description_type(),
390
                'title' => $description->get_title(),
391
                'content' => str_replace('src="/', 'src="'.api_get_path(WEB_PATH), $description->get_content()),
392
            ];
393
        }
394
395
        return $results;
396
    }
397
398
    /**
399
     * @param int $directoryId
400
     *
401
     * @return array
402
     * @throws Exception
403
     *
404
     */
405
    public function getCourseDocuments($directoryId = 0)
406
    {
407
        /** @var string $path */
408
        $path = '/';
409
        $sessionId = $this->session ? $this->session->getId() : 0;
410
411
        if ($directoryId) {
412
            $directory = DocumentManager::get_document_data_by_id(
413
                $directoryId,
414
                $this->course->getCode(),
415
                false,
416
                $sessionId
417
            );
418
419
            if (!$directory) {
420
                throw new Exception('NoDataAvailable');
421
            }
422
423
            $path = $directory['path'];
424
        }
425
426
        $courseInfo = api_get_course_info_by_id($this->course->getId());
427
        $documents = DocumentManager::getAllDocumentData(
428
            $courseInfo,
429
            $path,
430
            0,
431
            null,
432
            false,
433
            false,
434
            $sessionId
435
        );
436
        $results = [];
437
438
        if (!empty($documents)) {
439
            $webPath = api_get_path(WEB_CODE_PATH).'document/document.php?';
440
441
            /** @var array $document */
442
            foreach ($documents as $document) {
443
                if ($document['visibility'] != '1') {
444
                    continue;
445
                }
446
447
                $icon = $document['filetype'] == 'file'
448
                    ? choose_image($document['path'])
449
                    : chooseFolderIcon($document['path']);
450
451
                $results[] = [
452
                    'id' => $document['id'],
453
                    'type' => $document['filetype'],
454
                    'title' => $document['title'],
455
                    'path' => $document['path'],
456
                    'url' => $webPath.http_build_query(
457
                        [
458
                            'username' => $this->user->getUsername(),
459
                            'api_key' => $this->apiKey,
460
                            'cidReq' => $this->course->getCode(),
461
                            'id_session' => $sessionId,
462
                            'gidReq' => 0,
463
                            'gradebook' => 0,
464
                            'origin' => '',
465
                            'action' => 'download',
466
                            'id' => $document['id'],
467
                        ]
468
                    ),
469
                    'icon' => $icon,
470
                    'size' => format_file_size($document['size']),
471
                ];
472
            }
473
        }
474
475
        return $results;
476
    }
477
478
    /**
479
     * @return array
480
     * @throws Exception
481
     *
482
     */
483
    public function getCourseAnnouncements()
484
    {
485
        $sessionId = $this->session ? $this->session->getId() : 0;
486
487
        $announcements = AnnouncementManager::getAnnouncements(
488
            null,
489
            null,
490
            false,
491
            null,
492
            null,
493
            null,
494
            null,
495
            null,
496
            0,
497
            $this->user->getId(),
498
            $this->course->getId(),
499
            $sessionId
500
        );
501
502
        $announcements = array_map(
503
            function ($announcement) {
504
                return [
505
                    'id' => (int) $announcement['id'],
506
                    'title' => strip_tags($announcement['title']),
507
                    'creatorName' => strip_tags($announcement['username']),
508
                    'date' => strip_tags($announcement['insert_date']),
509
                ];
510
            },
511
            $announcements
512
        );
513
514
        return $announcements;
515
    }
516
517
    /**
518
     * @param int $announcementId
519
     *
520
     * @return array
521
     * @throws Exception
522
     *
523
     */
524
    public function getCourseAnnouncement($announcementId)
525
    {
526
        $sessionId = $this->session ? $this->session->getId() : 0;
527
        $announcement = AnnouncementManager::getAnnouncementInfoById(
528
            $announcementId,
529
            $this->course->getId(),
530
            $this->user->getId()
531
        );
532
533
        if (!$announcement) {
534
            throw new Exception(get_lang('NoAnnouncement'));
535
        }
536
537
        return [
538
            'id' => $announcement['announcement']->getIid(),
539
            'title' => $announcement['announcement']->getTitle(),
540
            'creatorName' => UserManager::formatUserFullName($announcement['item_property']->getInsertUser()),
541
            'date' => api_convert_and_format_date(
542
                $announcement['item_property']->getInsertDate(),
543
                DATE_TIME_FORMAT_LONG_24H
544
            ),
545
            'content' => AnnouncementManager::parseContent(
546
                $this->user->getId(),
547
                $announcement['announcement']->getContent(),
548
                $this->course->getCode(),
549
                $sessionId
550
            ),
551
        ];
552
    }
553
554
    /**
555
     * @return array
556
     * @throws Exception
557
     *
558
     */
559
    public function getCourseAgenda()
560
    {
561
        $sessionId = $this->session ? $this->session->getId() : 0;
562
563
        $agenda = new Agenda(
564
            'course',
565
            $this->user->getId(),
566
            $this->course->getId(),
567
            $sessionId
568
        );
569
        $result = $agenda->parseAgendaFilter(null);
570
571
        $start = new DateTime(api_get_utc_datetime(), new DateTimeZone('UTC'));
572
        $start->modify('first day of this month');
573
        $start->setTime(0, 0, 0);
574
        $end = new DateTime(api_get_utc_datetime(), new DateTimeZone('UTC'));
575
        $end->modify('last day of this month');
576
        $end->setTime(23, 59, 59);
577
578
        $groupId = current($result['groups']);
579
        $userId = current($result['users']);
580
581
        $events = $agenda->getEvents(
582
            $start->getTimestamp(),
583
            $end->getTimestamp(),
584
            $this->course->getId(),
585
            $groupId,
586
            $userId,
587
            'array'
588
        );
589
590
        if (!is_array($events)) {
591
            return [];
592
        }
593
594
        $webPath = api_get_path(WEB_PATH);
595
596
        return array_map(
597
            function ($event) use ($webPath) {
598
                return [
599
                    'id' => (int) $event['unique_id'],
600
                    'title' => $event['title'],
601
                    'content' => str_replace('src="/', 'src="'.$webPath, $event['description']),
602
                    'startDate' => $event['start_date_localtime'],
603
                    'endDate' => $event['end_date_localtime'],
604
                    'isAllDay' => $event['allDay'] ? true : false,
605
                ];
606
            },
607
            $events
608
        );
609
    }
610
611
    /**
612
     * @return array
613
     * @throws Exception
614
     *
615
     */
616
    public function getCourseNotebooks()
617
    {
618
        $em = Database::getManager();
619
        /** @var CNotebookRepository $notebooksRepo */
620
        $notebooksRepo = $em->getRepository('ChamiloCourseBundle:CNotebook');
621
        $notebooks = $notebooksRepo->findByUser($this->user, $this->course, $this->session);
622
623
        return array_map(
624
            function (CNotebook $notebook) {
625
                return [
626
                    'id' => $notebook->getIid(),
627
                    'title' => $notebook->getTitle(),
628
                    'description' => $notebook->getDescription(),
629
                    'creationDate' => api_format_date(
630
                        $notebook->getCreationDate()->getTimestamp()
631
                    ),
632
                    'updateDate' => api_format_date(
633
                        $notebook->getUpdateDate()->getTimestamp()
634
                    ),
635
                ];
636
            },
637
            $notebooks
638
        );
639
    }
640
641
    /**
642
     * @return array
643
     * @throws Exception
644
     *
645
     */
646
    public function getCourseForumCategories()
647
    {
648
        $sessionId = $this->session ? $this->session->getId() : 0;
649
        $webCoursePath = api_get_path(WEB_COURSE_PATH).$this->course->getDirectory().'/upload/forum/images/';
650
651
        require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
652
653
        $categoriesFullData = get_forum_categories('', $this->course->getId(), $sessionId);
654
        $categories = [];
655
        $includeGroupsForums = api_get_setting('display_groups_forum_in_general_tool') === 'true';
656
        $forumsFullData = get_forums('', $this->course->getCode(), $includeGroupsForums, $sessionId);
657
        $forums = [];
658
659
        foreach ($forumsFullData as $forumId => $forumInfo) {
660
            $forum = [
661
                'id' => (int) $forumInfo['iid'],
662
                'catId' => (int) $forumInfo['forum_category'],
663
                'title' => $forumInfo['forum_title'],
664
                'description' => $forumInfo['forum_comment'],
665
                'image' => $forumInfo['forum_image'] ? ($webCoursePath.$forumInfo['forum_image']) : '',
666
                'numberOfThreads' => isset($forumInfo['number_of_threads']) ? intval(
667
                    $forumInfo['number_of_threads']
668
                ) : 0,
669
                'lastPost' => null,
670
            ];
671
672
            $lastPostInfo = get_last_post_information($forumId, false, $this->course->getId(), $sessionId);
673
674
            if ($lastPostInfo) {
675
                $forum['lastPost'] = [
676
                    'date' => api_convert_and_format_date($lastPostInfo['last_post_date']),
677
                    'user' => api_get_person_name(
678
                        $lastPostInfo['last_poster_firstname'],
679
                        $lastPostInfo['last_poster_lastname']
680
                    ),
681
                ];
682
            }
683
684
            $forums[] = $forum;
685
        }
686
687
        foreach ($categoriesFullData as $category) {
688
            $categoryForums = array_filter(
689
                $forums,
690
                function (array $forum) use ($category) {
691
                    if ($forum['catId'] != $category['cat_id']) {
692
                        return false;
693
                    }
694
695
                    return true;
696
                }
697
            );
698
699
            $categories[] = [
700
                'id' => (int) $category['iid'],
701
                'title' => $category['cat_title'],
702
                'catId' => (int) $category['cat_id'],
703
                'description' => $category['cat_comment'],
704
                'forums' => $categoryForums,
705
                'courseId' => $this->course->getId(),
706
            ];
707
        }
708
709
        return $categories;
710
    }
711
712
    /**
713
     * @param int $forumId
714
     *
715
     * @return array
716
     * @throws Exception
717
     *
718
     */
719
    public function getCourseForum($forumId)
720
    {
721
        require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
722
723
        $sessionId = $this->session ? $this->session->getId() : 0;
724
        $forumInfo = get_forums($forumId, $this->course->getCode(), true, $sessionId);
725
726
        if (!isset($forumInfo['iid'])) {
727
            throw new Exception(get_lang('NoForum'));
728
        }
729
730
        $webCoursePath = api_get_path(WEB_COURSE_PATH).$this->course->getDirectory().'/upload/forum/images/';
731
        $forum = [
732
            'id' => $forumInfo['iid'],
733
            'title' => $forumInfo['forum_title'],
734
            'description' => $forumInfo['forum_comment'],
735
            'image' => $forumInfo['forum_image'] ? ($webCoursePath.$forumInfo['forum_image']) : '',
736
            'threads' => [],
737
        ];
738
739
        $threads = get_threads($forumInfo['iid'], $this->course->getId(), $sessionId);
740
741
        foreach ($threads as $thread) {
742
            $forum['threads'][] = [
743
                'id' => $thread['iid'],
744
                'title' => $thread['thread_title'],
745
                'lastEditDate' => api_convert_and_format_date($thread['lastedit_date'], DATE_TIME_FORMAT_LONG_24H),
746
                'numberOfReplies' => $thread['thread_replies'],
747
                'numberOfViews' => $thread['thread_views'],
748
                'author' => api_get_person_name($thread['firstname'], $thread['lastname']),
749
            ];
750
        }
751
752
        return $forum;
753
    }
754
755
    /**
756
     * @param int $forumId
757
     * @param int $threadId
758
     *
759
     * @return array
760
     */
761
    public function getCourseForumThread($forumId, $threadId)
762
    {
763
        require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
764
765
        $sessionId = $this->session ? $this->session->getId() : 0;
766
        $threadInfo = get_thread_information($forumId, $threadId, $sessionId);
767
768
        $thread = [
769
            'id' => intval($threadInfo['iid']),
770
            'cId' => intval($threadInfo['c_id']),
771
            'title' => $threadInfo['thread_title'],
772
            'forumId' => intval($threadInfo['forum_id']),
773
            'posts' => [],
774
        ];
775
776
        $forumInfo = get_forums($threadInfo['forum_id'], $this->course->getCode(), true, $sessionId);
777
        $postsInfo = getPosts($forumInfo, $threadInfo['iid'], 'ASC');
778
779
        foreach ($postsInfo as $postInfo) {
780
            $thread['posts'][] = [
781
                'id' => $postInfo['iid'],
782
                'title' => $postInfo['post_title'],
783
                'text' => $postInfo['post_text'],
784
                'author' => api_get_person_name($postInfo['firstname'], $postInfo['lastname']),
785
                'date' => api_convert_and_format_date($postInfo['post_date'], DATE_TIME_FORMAT_LONG_24H),
786
                'parentId' => $postInfo['post_parent_id'],
787
            ];
788
        }
789
790
        return $thread;
791
    }
792
793
    /**
794
     * @return array
795
     */
796
    public function getUserProfile()
797
    {
798
        $pictureInfo = UserManager::get_user_picture_path_by_id($this->user->getId(), 'web');
799
800
        $result = [
801
            'pictureUri' => $pictureInfo['dir'].$pictureInfo['file'],
802
            'id' => $this->user->getId(),
803
            'status' => $this->user->getStatus(),
804
            'fullName' => UserManager::formatUserFullName($this->user),
805
            'username' => $this->user->getUsername(),
806
            'officialCode' => $this->user->getOfficialCode(),
807
            'phone' => $this->user->getPhone(),
808
            'extra' => [],
809
        ];
810
811
        $fieldValue = new ExtraFieldValue('user');
812
        $extraInfo = $fieldValue->getAllValuesForAnItem($this->user->getId(), true);
813
814
        foreach ($extraInfo as $extra) {
815
            /** @var ExtraFieldValues $extraValue */
816
            $extraValue = $extra['value'];
817
            $result['extra'][] = [
818
                'title' => $extraValue->getField()->getDisplayText(true),
819
                'value' => $extraValue->getValue(),
820
            ];
821
        }
822
823
        return $result;
824
    }
825
826
    public function getCourseLpProgress()
827
    {
828
        $userId = $this->user->getId();
829
        /*$sessionId = $this->session ? $this->session->getId() : 0;
830
        $courseId = $this->course->getId();*/
831
832
        $controller = new IndexManager(get_lang('MyCourses'));
833
        $data = $controller->returnCoursesAndSessions($userId);
834
        $courseList = $data['courses'];
835
        $sessionId = $this->session ? $this->session->getId() : 0;
836
837
        $result = [];
838
        if ($courseList) {
839
            $counter = 0;
840
            foreach ($courseList as $course) {
841
                $courseId = $course['course_id'];
842
                $courseInfo = api_get_course_info_by_id($courseId);
843
                if (empty($courseInfo)) {
844
                    continue;
845
                }
846
                $courseCode = $courseInfo['code'];
847
                $categoriesTempList = learnpath::getCategories($courseId);
848
849
                $categoryNone = new CLpCategory();
850
                $categoryNone->setId(0);
851
                $categoryNone->setName(get_lang('WithOutCategory'));
852
                $categoryNone->setPosition(0);
853
854
                $categories = array_merge([$categoryNone], $categoriesTempList);
855
856
                /** @var CLpCategory $category */
857
                foreach ($categories as $category) {
858
                    $learnPathList = new LearnpathList(
859
                        $userId,
860
                        $courseInfo,
861
                        $sessionId,
862
                        null,
863
                        false,
864
                        $category->getId()
865
                    );
866
867
                    $flatLpList = $learnPathList->get_flat_list();
868
869
                    if (empty($flatLpList)) {
870
                        continue;
871
                    }
872
873
                    foreach ($flatLpList as $lpId => $lpDetails) {
874
                        if ($lpDetails['lp_visibility'] == 0) {
875
                            continue;
876
                        }
877
878
                        if (!learnpath::is_lp_visible_for_student(
879
                            $lpId,
880
                            $userId,
881
                            $courseInfo,
882
                            $sessionId
883
                        )) {
884
                            continue;
885
                        }
886
887
                        $timeLimits = false;
888
889
                        // This is an old LP (from a migration 1.8.7) so we do nothing
890
                        if (empty($lpDetails['created_on']) && empty($lpDetails['modified_on'])) {
891
                            $timeLimits = false;
892
                        }
893
894
                        // Checking if expired_on is ON
895
                        if (!empty($lpDetails['expired_on'])) {
896
                            $timeLimits = true;
897
                        }
898
899
                        if ($timeLimits) {
900
                            if (!empty($lpDetails['publicated_on']) && !empty($lpDetails['expired_on'])) {
901
                                $startTime = api_strtotime($lpDetails['publicated_on'], 'UTC');
902
                                $endTime = api_strtotime($lpDetails['expired_on'], 'UTC');
903
                                $now = time();
904
                                $isActiveTime = false;
905
906
                                if ($now > $startTime && $endTime > $now) {
907
                                    $isActiveTime = true;
908
                                }
909
910
                                if (!$isActiveTime) {
911
                                    continue;
912
                                }
913
                            }
914
                        }
915
916
                        $progress = learnpath::getProgress($lpId, $userId, $courseId, $sessionId);
917
                        $time = Tracking::get_time_spent_in_lp($userId, $courseCode, [], $sessionId);
918
                        $score = Tracking::getAverageStudentScore($userId, $courseCode, [], $sessionId);
919
920
                        /*$listData[] = [
921
                            'id' => $lpId,
922
                            'title' => Security::remove_XSS($lpDetails['lp_name']),
923
                            'progress' => $progress,
924
                            'url' => api_get_path(WEB_CODE_PATH).'webservices/api/v2.php?'.http_build_query(
925
                                    [
926
                                        'hash' => $this->encodeParams(
927
                                            [
928
                                                'action' => 'course_learnpath',
929
                                                'lp_id' => $lpId,
930
                                                'course' => $this->course->getId(),
931
                                                'session' => $sessionId,
932
                                            ]
933
                                        ),
934
                                    ]
935
                                ),
936
                        ];*/
937
938
                        $counter++;
939
                        $result['course'.$counter] = [
940
                            'module' => $lpDetails['lp_name'],
941
                            'progress' => $progress,
942
                            'qualification' => $score,
943
                            'activeTime' => $time,
944
                        ];
945
                    }
946
                }
947
            }
948
        }
949
950
        return [$result];
951
    }
952
953
    /**
954
     * @return array
955
     * @throws Exception
956
     *
957
     */
958
    public function getCourseLearnPaths()
959
    {
960
        $sessionId = $this->session ? $this->session->getId() : 0;
961
        $categoriesTempList = learnpath::getCategories($this->course->getId());
962
963
        $categoryNone = new CLpCategory();
964
        $categoryNone->setId(0);
965
        $categoryNone->setName(get_lang('WithOutCategory'));
966
        $categoryNone->setPosition(0);
967
968
        $categories = array_merge([$categoryNone], $categoriesTempList);
969
        $categoryData = [];
970
971
        /** @var CLpCategory $category */
972
        foreach ($categories as $category) {
973
            $learnPathList = new LearnpathList(
974
                $this->user->getId(),
975
                api_get_course_info($this->course->getCode()),
976
                $sessionId,
977
                null,
978
                false,
979
                $category->getId()
980
            );
981
982
            $flatLpList = $learnPathList->get_flat_list();
983
984
            if (empty($flatLpList)) {
985
                continue;
986
            }
987
988
            $listData = [];
989
990
            foreach ($flatLpList as $lpId => $lpDetails) {
991
                if ($lpDetails['lp_visibility'] == 0) {
992
                    continue;
993
                }
994
995
                if (!learnpath::is_lp_visible_for_student(
996
                    $lpId,
997
                    $this->user->getId(),
998
                    api_get_course_info($this->course->getCode()),
999
                    $sessionId
1000
                )) {
1001
                    continue;
1002
                }
1003
1004
                $timeLimits = false;
1005
1006
                // This is an old LP (from a migration 1.8.7) so we do nothing
1007
                if (empty($lpDetails['created_on']) && empty($lpDetails['modified_on'])) {
1008
                    $timeLimits = false;
1009
                }
1010
1011
                // Checking if expired_on is ON
1012
                if (!empty($lpDetails['expired_on'])) {
1013
                    $timeLimits = true;
1014
                }
1015
1016
                if ($timeLimits) {
1017
                    if (!empty($lpDetails['publicated_on']) && !empty($lpDetails['expired_on'])) {
1018
                        $startTime = api_strtotime($lpDetails['publicated_on'], 'UTC');
1019
                        $endTime = api_strtotime($lpDetails['expired_on'], 'UTC');
1020
                        $now = time();
1021
                        $isActiveTime = false;
1022
1023
                        if ($now > $startTime && $endTime > $now) {
1024
                            $isActiveTime = true;
1025
                        }
1026
1027
                        if (!$isActiveTime) {
1028
                            continue;
1029
                        }
1030
                    }
1031
                }
1032
1033
                $progress = learnpath::getProgress($lpId, $this->user->getId(), $this->course->getId(), $sessionId);
1034
1035
                $listData[] = [
1036
                    'id' => $lpId,
1037
                    'title' => Security::remove_XSS($lpDetails['lp_name']),
1038
                    'progress' => $progress,
1039
                    'url' => api_get_path(WEB_CODE_PATH).'webservices/api/v2.php?'.http_build_query(
1040
                        [
1041
                            'hash' => $this->encodeParams(
1042
                                [
1043
                                    'action' => 'course_learnpath',
1044
                                    'lp_id' => $lpId,
1045
                                    'course' => $this->course->getId(),
1046
                                    'session' => $sessionId,
1047
                                ]
1048
                            ),
1049
                        ]
1050
                    ),
1051
                ];
1052
            }
1053
1054
            if (empty($listData)) {
1055
                continue;
1056
            }
1057
1058
            $categoryData[] = [
1059
                'id' => $category->getId(),
1060
                'name' => $category->getName(),
1061
                'learnpaths' => $listData,
1062
            ];
1063
        }
1064
1065
        return $categoryData;
1066
    }
1067
1068
    /**
1069
     * @param array $additionalParams Optional
1070
     *
1071
     * @return string
1072
     */
1073
    private function encodeParams(array $additionalParams = [])
1074
    {
1075
        $params = array_merge(
1076
            $additionalParams,
1077
            [
1078
                'api_key' => $this->apiKey,
1079
                'username' => $this->user->getUsername(),
1080
            ]
1081
        );
1082
1083
        return json_encode($params);
1084
    }
1085
1086
    /**
1087
     * Start login for a user. Then make a redirect to show the learnpath.
1088
     *
1089
     * @param int $lpId
1090
     */
1091
    public function showLearningPath($lpId)
1092
    {
1093
        $loggedUser['user_id'] = $this->user->getId();
1094
        $loggedUser['status'] = $this->user->getStatus();
1095
        $loggedUser['uidReset'] = true;
1096
        $sessionId = $this->session ? $this->session->getId() : 0;
1097
1098
        ChamiloSession::write('_user', $loggedUser);
1099
        Login::init_user($this->user->getId(), true);
1100
1101
        $url = api_get_path(WEB_CODE_PATH).'lp/lp_controller.php?'.http_build_query(
1102
            [
1103
                'cidReq' => $this->course->getCode(),
1104
                'id_session' => $sessionId,
1105
                'gidReq' => 0,
1106
                'gradebook' => 0,
1107
                'origin' => '',
1108
                'action' => 'view',
1109
                'lp_id' => (int) $lpId,
1110
                'isStudentView' => 'true',
1111
            ]
1112
        );
1113
1114
        header("Location: $url");
1115
        exit;
1116
    }
1117
1118
    /**
1119
     * @param int $forumId
1120
     *
1121
     * @return array
1122
     */
1123
    public function saveForumPost(array $postValues, $forumId)
1124
    {
1125
        require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
1126
1127
        $forum = get_forums($forumId, $this->course->getCode());
1128
        store_reply($forum, $postValues, $this->course->getId(), $this->user->getId());
1129
1130
        return [
1131
            'registered' => true,
1132
        ];
1133
    }
1134
1135
    /**
1136
     * Get the list of sessions for current user.
1137
     *
1138
     * @return array the sessions list
1139
     */
1140
    public function getUserSessions()
1141
    {
1142
        $data = [];
1143
        $sessionsByCategory = UserManager::get_sessions_by_category($this->user->getId(), false);
1144
1145
        foreach ($sessionsByCategory as $category) {
1146
            $categorySessions = [];
1147
1148
            foreach ($category['sessions'] as $sessions) {
1149
                $sessionCourses = [];
1150
1151
                foreach ($sessions['courses'] as $course) {
1152
                    $courseInfo = api_get_course_info_by_id($course['real_id']);
1153
                    $teachers = SessionManager::getCoachesByCourseSessionToString(
1154
                        $sessions['session_id'],
1155
                        $course['real_id']
1156
                    );
1157
1158
                    $sessionCourses[] = [
1159
                        'id' => $courseInfo['real_id'],
1160
                        'title' => $courseInfo['title'],
1161
                        'code' => $courseInfo['code'],
1162
                        'directory' => $courseInfo['directory'],
1163
                        'pictureUrl' => $courseInfo['course_image_large'],
1164
                        'urlPicture' => $courseInfo['course_image_large'],
1165
                        'teachers' => $teachers,
1166
                    ];
1167
                }
1168
1169
                $sessionBox = Display::getSessionTitleBox($sessions['session_id']);
1170
1171
                $categorySessions[] = [
1172
                    'name' => $sessionBox['title'],
1173
                    'id' => $sessions['session_id'],
1174
                    'date' => $sessionBox['dates'],
1175
                    'duration' => isset($sessionBox['duration']) ? $sessionBox['duration'] : null,
1176
                    'courses' => $sessionCourses,
1177
                ];
1178
            }
1179
1180
            $data[] = [
1181
                'id' => $category['session_category']['id'],
1182
                'name' => $category['session_category']['name'],
1183
                'sessions' => $categorySessions,
1184
            ];
1185
        }
1186
1187
        return $data;
1188
    }
1189
1190
    /**
1191
     * @param string $subject
1192
     * @param string $text
1193
     *
1194
     * @return array
1195
     */
1196
    public function saveUserMessage($subject, $text, array $receivers)
1197
    {
1198
        foreach ($receivers as $userId) {
1199
            MessageManager::send_message($userId, $subject, $text);
1200
        }
1201
1202
        return [
1203
            'sent' => true,
1204
        ];
1205
    }
1206
1207
    /**
1208
     * @param string $search
1209
     *
1210
     * @return array
1211
     */
1212
    public function getMessageUsers($search)
1213
    {
1214
        $repo = UserManager::getRepository();
1215
1216
        $users = $repo->findUsersToSendMessage($this->user->getId(), $search);
1217
        $showEmail = api_get_setting('show_email_addresses') === 'true';
1218
        $data = [];
1219
1220
        /** @var User $user */
1221
        foreach ($users as $user) {
1222
            $userName = UserManager::formatUserFullName($user);
1223
1224
            if ($showEmail) {
1225
                $userName .= " ({$user->getEmail()})";
1226
            }
1227
1228
            $data[] = [
1229
                'id' => $user->getId(),
1230
                'name' => $userName,
1231
            ];
1232
        }
1233
1234
        return $data;
1235
    }
1236
1237
    /**
1238
     * @param string $title
1239
     * @param string $text
1240
     *
1241
     * @return array
1242
     */
1243
    public function saveCourseNotebook($title, $text)
1244
    {
1245
        $values = ['note_title' => $title, 'note_comment' => $text];
1246
        $sessionId = $this->session ? $this->session->getId() : 0;
1247
1248
        $noteBookId = NotebookManager::save_note(
1249
            $values,
1250
            $this->user->getId(),
1251
            $this->course->getId(),
1252
            $sessionId
1253
        );
1254
1255
        return [
1256
            'registered' => $noteBookId,
1257
        ];
1258
    }
1259
1260
    /**
1261
     * @param int $forumId
1262
     *
1263
     * @return array
1264
     */
1265
    public function saveForumThread(array $values, $forumId)
1266
    {
1267
        require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
1268
1269
        $sessionId = $this->session ? $this->session->getId() : 0;
1270
        $forum = get_forums($forumId, $this->course->getCode(), true, $sessionId);
1271
        $courseInfo = api_get_course_info($this->course->getCode());
1272
        $thread = store_thread($forum, $values, $courseInfo, false, $this->user->getId(), $sessionId);
1273
1274
        return [
1275
            'registered' => $thread->getIid(),
1276
        ];
1277
    }
1278
1279
    /**
1280
     * @return array
1281
     */
1282
    public function getUsersCampus(array $params)
1283
    {
1284
        $conditions = [
1285
            'status' => $params['status'],
1286
        ];
1287
        $idCampus = $params['id_campus'];
1288
        $users = UserManager::get_user_list($conditions, ['firstname'], false, false, $idCampus);
1289
        $list = [];
1290
        foreach ($users as $item) {
1291
            $listTemp = [
1292
                'id' => $item['user_id'],
1293
                'firstname' => $item['firstname'],
1294
                'lastname' => $item['lastname'],
1295
                'email' => $item['email'],
1296
            ];
1297
            $list[] = $listTemp;
1298
        }
1299
1300
        return $list;
1301
    }
1302
1303
    /**
1304
     * @return array
1305
     */
1306
    public function getCoursesCampus(array $params)
1307
    {
1308
        $idCampus = $params['id_campus'];
1309
1310
        $courseList = CourseManager::get_courses_list(
1311
            0, //offset
1312
            0, //howMany
1313
            1, //$orderby = 1
1314
            'ASC',
1315
            -1, //visibility
1316
            null,
1317
            $idCampus, //$urlId
1318
            true //AlsoSearchCode
1319
        );
1320
1321
        return $courseList;
1322
    }
1323
1324
    /**
1325
     * @return array
1326
     */
1327
    public function addSession(array $params)
1328
    {
1329
        $name = $params['name'];
1330
        $coach_username = (int) $params['coach_username'];
1331
        $startDate = $params['access_start_date'];
1332
        $endDate = $params['access_end_date'];
1333
        $displayStartDate = $startDate;
1334
        $displayEndDate = $endDate;
1335
        $description = $params['description'];
1336
        $idUrlCampus = $params['id_campus'];
1337
1338
        $return = SessionManager::create_session(
1339
            $name,
1340
            $startDate,
1341
            $endDate,
1342
            $displayStartDate,
1343
            $displayEndDate,
1344
            null,
1345
            null,
1346
            $coach_username,
1347
            null,
1348
            1,
1349
            false,
1350
            null,
1351
            $description,
1352
            1,
1353
            [],
1354
            null,
1355
            false,
1356
            $idUrlCampus
1357
        );
1358
1359
        if ($return) {
1360
            $out = [
1361
                'status' => true,
1362
                'message' => get_lang('ANewSessionWasCreated'),
1363
                'id_session' => $return,
1364
            ];
1365
        } else {
1366
            $out = [
1367
                'status' => false,
1368
                'message' => get_lang('ErrorOccurred'),
1369
            ];
1370
        }
1371
1372
        return $out;
1373
    }
1374
1375
    /**
1376
     * @return array
1377
     */
1378
    public function addCourse(array $courseParam)
1379
    {
1380
        $results = [];
1381
        $idCampus = isset($courseParam['id_campus']) ? $courseParam['id_campus'] : 1;
1382
        $title = isset($courseParam['title']) ? $courseParam['title'] : '';
1383
        $wantedCode = isset($courseParam['wanted_code']) ? $courseParam['wanted_code'] : null;
1384
        $diskQuota = isset($courseParam['disk_quota']) ? $courseParam['disk_quota'] : '100';
1385
        $visibility = isset($courseParam['visibility']) ? (int) $courseParam['visibility'] : null;
1386
1387
        if (isset($courseParam['visibility'])) {
1388
            if ($courseParam['visibility'] &&
1389
                $courseParam['visibility'] >= 0 &&
1390
                $courseParam['visibility'] <= 3
1391
            ) {
1392
                $visibility = (int) $courseParam['visibility'];
1393
            }
1394
        }
1395
1396
        $params = [];
1397
        $params['title'] = $title;
1398
        $params['wanted_code'] = 'CAMPUS_'.$idCampus.'_'.$wantedCode;
1399
        $params['user_id'] = $this->user->getId();
1400
        $params['visibility'] = $visibility;
1401
        $params['disk_quota'] = $diskQuota;
1402
1403
        $courseInfo = CourseManager::create_course($params, $params['user_id'], $idCampus);
1404
1405
        if (!empty($courseInfo)) {
1406
            $results['status'] = true;
1407
            $results['code_course'] = $courseInfo['code'];
1408
            $results['title_course'] = $courseInfo['title'];
1409
            $results['message'] = sprintf(get_lang('CourseXAdded'), $courseInfo['code']);
1410
        } else {
1411
            $results['status'] = false;
1412
            $results['message'] = get_lang('CourseCreationFailed');
1413
        }
1414
1415
        return $results;
1416
    }
1417
1418
    /**
1419
     * @param $userParam
1420
     *
1421
     * @return array
1422
     * @throws Exception
1423
     *
1424
     */
1425
    public function addUser($userParam)
1426
    {
1427
        $firstName = $userParam['firstname'];
1428
        $lastName = $userParam['lastname'];
1429
        $status = $userParam['status'];
1430
        $email = $userParam['email'];
1431
        $loginName = $userParam['loginname'];
1432
        $password = $userParam['password'];
1433
1434
        $official_code = '';
1435
        $language = '';
1436
        $phone = '';
1437
        $picture_uri = '';
1438
        $auth_source = PLATFORM_AUTH_SOURCE;
1439
        $expiration_date = '';
1440
        $active = 1;
1441
        $hr_dept_id = 0;
1442
        $extra = null;
1443
1444
        $original_user_id_name = $userParam['original_user_id_name'];
1445
        $original_user_id_value = $userParam['original_user_id_value'];
1446
1447
        $extra_list = isset($userParam['extra']) ? $userParam['extra'] : [];
1448
        if (isset($userParam['language'])) {
1449
            $language = $userParam['language'];
1450
        }
1451
        if (isset($userParam['phone'])) {
1452
            $phone = $userParam['phone'];
1453
        }
1454
        if (isset($userParam['expiration_date'])) {
1455
            $expiration_date = $userParam['expiration_date'];
1456
        }
1457
1458
        // Default language.
1459
        if (empty($language)) {
1460
            $language = api_get_setting('platformLanguage');
1461
        }
1462
1463
        // First check wether the login already exists.
1464
        if (!UserManager::is_username_available($loginName)) {
1465
            throw new Exception(get_lang('UserNameNotAvailable'));
1466
        }
1467
1468
        $userId = UserManager::create_user(
1469
            $firstName,
1470
            $lastName,
1471
            $status,
1472
            $email,
1473
            $loginName,
1474
            $password,
1475
            $official_code,
1476
            $language,
1477
            $phone,
1478
            $picture_uri,
1479
            $auth_source,
1480
            $expiration_date,
1481
            $active,
1482
            $hr_dept_id
1483
        );
1484
1485
        if (empty($userId)) {
1486
            throw new Exception(get_lang('UserNotRegistered'));
1487
        }
1488
1489
        if (api_is_multiple_url_enabled()) {
1490
            if (api_get_current_access_url_id() != -1) {
1491
                UrlManager::add_user_to_url(
1492
                    $userId,
1493
                    api_get_current_access_url_id()
1494
                );
1495
            } else {
1496
                UrlManager::add_user_to_url($userId, 1);
1497
            }
1498
        } else {
1499
            // We add by default the access_url_user table with access_url_id = 1
1500
            UrlManager::add_user_to_url($userId, 1);
1501
        }
1502
1503
        // Save new field label into user_field table.
1504
        UserManager::create_extra_field(
1505
            $original_user_id_name,
1506
            1,
1507
            $original_user_id_name,
1508
            ''
1509
        );
1510
        // Save the external system's id into user_field_value table.
1511
        UserManager::update_extra_field_value(
1512
            $userId,
1513
            $original_user_id_name,
1514
            $original_user_id_value
1515
        );
1516
1517
        if (is_array($extra_list) && count($extra_list) > 0) {
1518
            foreach ($extra_list as $extra) {
1519
                $extra_field_name = $extra['field_name'];
1520
                $extra_field_value = $extra['field_value'];
1521
                // Save new field label into user_field table.
1522
                UserManager::create_extra_field(
1523
                    $extra_field_name,
1524
                    1,
1525
                    $extra_field_name,
1526
                    ''
1527
                );
1528
                // Save the external system's id into user_field_value table.
1529
                UserManager::update_extra_field_value(
1530
                    $userId,
1531
                    $extra_field_name,
1532
                    $extra_field_value
1533
                );
1534
            }
1535
        }
1536
1537
        return [$userId];
1538
    }
1539
1540
    /**
1541
     * Subscribe User to Course.
1542
     *
1543
     * @param array $params
1544
     *
1545
     * @return array
1546
     */
1547
    public function subscribeUserToCourse($params)
1548
    {
1549
        $course_id = $params['course_id'];
1550
        $course_code = $params['course_code'];
1551
        $user_id = $params['user_id'];
1552
        if (!$course_id && !$course_code) {
1553
            return [false];
1554
        }
1555
        if (!$course_code) {
1556
            $course_code = CourseManager::get_course_code_from_course_id($course_id);
1557
        }
1558
        if (CourseManager::subscribeUser($user_id, $course_code)) {
1559
            return [true];
1560
        } else {
1561
            return [false];
1562
        }
1563
1564
        return [true];
0 ignored issues
show
Unused Code introduced by
return array(true) is not reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
1565
    }
1566
1567
    public function deleteUserMessage($messageId, $messageType)
1568
    {
1569
        if ($messageType === "sent") {
1570
            return MessageManager::delete_message_by_user_sender($this->user->getId(), $messageId);
1571
        } else {
1572
            return MessageManager::delete_message_by_user_receiver($this->user->getId(), $messageId);
1573
        }
1574
    }
1575
1576
    public function setMessageRead($messageId)
1577
    {
1578
        MessageManager::update_message($this->user->getId(), $messageId);
1579
    }
1580
1581
    /**
1582
     * Add Campus Virtual.
1583
     *
1584
     * @param array Params Campus
1585
     *
1586
     * @return array
1587
     */
1588
    public function createCampusURL($params)
1589
    {
1590
        $urlCampus = Security::remove_XSS($params['url']);
1591
        $description = Security::remove_XSS($params['description']);
1592
1593
        $active = isset($params['active']) ? intval($params['active']) : 0;
1594
        $num = UrlManager::url_exist($urlCampus);
1595
        if ($num == 0) {
1596
            // checking url
1597
            if (substr($urlCampus, strlen($urlCampus) - 1, strlen($urlCampus)) == '/') {
1598
                $idCampus = UrlManager::add($urlCampus, $description, $active, true);
1599
            } else {
1600
                //create
1601
                $idCampus = UrlManager::add($urlCampus.'/', $description, $active, true);
1602
            }
1603
1604
            return [
1605
                'status' => true,
1606
                'id_campus' => $idCampus,
1607
            ];
1608
        }
1609
1610
        return [
1611
            'status' => false,
1612
            'id_campus' => 0,
1613
        ];
1614
    }
1615
1616
    /**
1617
     * Edit Campus Virtual.
1618
     *
1619
     * @param array Params Campus
1620
     *
1621
     * @return array
1622
     */
1623
    public function editCampusURL($params)
1624
    {
1625
        $urlCampus = Security::remove_XSS($params['url']);
1626
        $description = Security::remove_XSS($params['description']);
1627
1628
        $active = isset($params['active']) ? intval($params['active']) : 0;
1629
        $url_id = isset($params['id']) ? intval($params['id']) : 0;
1630
1631
        if (!empty($url_id)) {
1632
            //we can't change the status of the url with id=1
1633
            if ($url_id == 1) {
1634
                $active = 1;
1635
            }
1636
            //checking url
1637
            if (substr($urlCampus, strlen($urlCampus) - 1, strlen($urlCampus)) == '/') {
1638
                UrlManager::update($url_id, $urlCampus, $description, $active);
1639
            } else {
1640
                UrlManager::update($url_id, $urlCampus.'/', $description, $active);
1641
            }
1642
1643
            return [true];
1644
        }
1645
1646
        return [false];
1647
    }
1648
1649
    /**
1650
     * Delete Campus Virtual.
1651
     *
1652
     * @param array Params Campus
1653
     *
1654
     * @return array
1655
     */
1656
    public function deleteCampusURL($params)
1657
    {
1658
        $url_id = isset($params['id']) ? intval($params['id']) : 0;
1659
1660
        $result = UrlManager::delete($url_id);
1661
        if ($result) {
1662
            return [
1663
                'status' => true,
1664
                'message' => get_lang('URLDeleted'),
1665
            ];
1666
        } else {
1667
            return [
1668
                'status' => false,
1669
                'message' => get_lang('Error'),
1670
            ];
1671
        }
1672
    }
1673
1674
    /**
1675
     * @return array
1676
     * @throws Exception
1677
     *
1678
     */
1679
    public function addCoursesSession(array $params)
1680
    {
1681
        $sessionId = $params['id_session'];
1682
        $courseList = $params['list_courses'];
1683
1684
        $result = SessionManager::add_courses_to_session(
1685
            $sessionId,
1686
            $courseList,
1687
            true,
1688
            false
1689
        );
1690
1691
        if ($result) {
1692
            return [
1693
                'status' => $result,
1694
                'message' => get_lang('Updated'),
1695
            ];
1696
        } else {
1697
            return [
1698
                'status' => $result,
1699
                'message' => get_lang('ErrorOccurred'),
1700
            ];
1701
        }
1702
    }
1703
1704
    /**
1705
     * @return array
1706
     */
1707
    public function addUsersSession(array $params)
1708
    {
1709
        $sessionId = $params['id_session'];
1710
        $userList = $params['list_users'];
1711
1712
        if (!is_array($userList)) {
1713
            $userList = [];
1714
        }
1715
1716
        SessionManager::subscribeUsersToSession(
1717
            $sessionId,
1718
            $userList,
1719
            null,
1720
            false
1721
        );
1722
1723
        return [
1724
            'status' => true,
1725
            'message' => get_lang('UsersAdded'),
1726
        ];
1727
    }
1728
1729
    /**
1730
     * Creates a session from a model session.
1731
     *
1732
     * @param $modelSessionId
1733
     * @param $sessionName
1734
     * @param $startDate
1735
     * @param $endDate
1736
     *
1737
     * @return int, the id of the new session
1738
     * @throws Exception
1739
     *
1740
     */
1741
    public function createSessionFromModel($modelSessionId, $sessionName, $startDate, $endDate, array $extraFields = [])
1742
    {
1743
        if (empty($modelSessionId) || empty($sessionName) || empty($startDate) || empty($endDate)) {
1744
            throw new Exception(get_lang('NoData'));
1745
        }
1746
1747
        if (!SessionManager::isValidId($modelSessionId)) {
1748
            throw new Exception(get_lang('ModelSessionDoesNotExist'));
1749
        }
1750
1751
        $modelSession = SessionManager::fetch($modelSessionId);
1752
1753
        $modelSession['accessUrlId'] = 1;
1754
        if (api_is_multiple_url_enabled()) {
1755
            if (api_get_current_access_url_id() != -1) {
1756
                $modelSession['accessUrlId'] = api_get_current_access_url_id();
1757
            }
1758
        }
1759
1760
        $newSessionId = SessionManager::create_session(
1761
            $sessionName,
1762
            $startDate,
1763
            $endDate,
1764
            $startDate,
1765
            $endDate,
1766
            $startDate,
1767
            $endDate,
1768
            $modelSession['id_coach'],
1769
            $modelSession['session_category_id'],
1770
            $modelSession['visibility'],
1771
            false,
1772
            $modelSession['duration'],
1773
            $modelSession['description'],
1774
            $modelSession['show_description'],
1775
            $extraFields,
1776
            $modelSession['session_admin_id'],
1777
            $modelSession['send_subscription_notification'],
1778
            $modelSession['accessUrlId']
1779
        );
1780
1781
        if (empty($newSessionId)) {
1782
            throw new Exception(get_lang('SessionNotRegistered'));
1783
        }
1784
1785
        if (is_string($newSessionId)) {
1786
            throw new Exception($newSessionId);
1787
        }
1788
1789
        $promotionId = $modelSession['promotion_id'];
1790
        if ($promotionId) {
1791
            $sessionList = array_keys(SessionManager::get_all_sessions_by_promotion($promotionId));
1792
            $sessionList[] = $newSessionId;
1793
            SessionManager::subscribe_sessions_to_promotion($modelSession['promotion_id'], $sessionList);
1794
        }
1795
1796
        $modelExtraFields = [];
1797
        $fields = SessionManager::getFilteredExtraFields($modelSessionId);
1798
        if (is_array($fields) and !empty($fields)) {
1799
            foreach ($fields as $field) {
1800
                $modelExtraFields[$field['variable']] = $field['value'];
1801
            }
1802
        }
1803
        $allExtraFields = array_merge($modelExtraFields, $extraFields);
1804
        foreach ($allExtraFields as $name => $value) {
1805
            // SessionManager::update_session_extra_field_value returns false when no row is changed,
1806
            // which can happen since extra field values are initialized by SessionManager::create_session
1807
            // therefore we do not throw an exception when false is returned
1808
            SessionManager::update_session_extra_field_value($newSessionId, $name, $value);
1809
        }
1810
1811
        $courseList = array_keys(SessionManager::get_course_list_by_session_id($modelSessionId));
1812
        if (is_array($courseList)
1813
            && !empty($courseList)
1814
            && !SessionManager::add_courses_to_session($newSessionId, $courseList)) {
1815
            throw new Exception(get_lang('CoursesNotAddedToSession'));
1816
        }
1817
1818
        if (api_is_multiple_url_enabled()) {
1819
            if (api_get_current_access_url_id() != -1) {
1820
                UrlManager::add_session_to_url(
1821
                    $newSessionId,
1822
                    api_get_current_access_url_id()
1823
                );
1824
            } else {
1825
                UrlManager::add_session_to_url($newSessionId, 1);
1826
            }
1827
        } else {
1828
            UrlManager::add_session_to_url($newSessionId, 1);
1829
        }
1830
1831
        return $newSessionId;
1832
    }
1833
1834
    /**
1835
     * subscribes a user to a session.
1836
     *
1837
     * @param int $sessionId    the session id
1838
     * @param string $loginName the user's login name
1839
     *
1840
     * @return boolean, whether it worked
1841
     * @throws Exception
1842
     *
1843
     */
1844
    public function subscribeUserToSessionFromUsername($sessionId, $loginName)
1845
    {
1846
        if (!SessionManager::isValidId($sessionId)) {
1847
            throw new Exception(get_lang('SessionNotFound'));
1848
        }
1849
1850
        $userId = UserManager::get_user_id_from_username($loginName);
1851
        if (false === $userId) {
1852
            throw new Exception(get_lang('UserNotFound'));
1853
        }
1854
1855
        $subscribed = SessionManager::subscribeUsersToSession(
1856
            $sessionId,
1857
            [$userId],
1858
            SESSION_VISIBLE_READ_ONLY,
1859
            false
1860
        );
1861
        if (!$subscribed) {
1862
            throw new Exception(get_lang('UserNotSubscribed'));
1863
        }
1864
1865
        return true;
1866
    }
1867
1868
    /**
1869
     * finds the session which has a specific value in a specific extra field.
1870
     *
1871
     * @param $fieldName
1872
     * @param $fieldValue
1873
     *
1874
     * @return int, the matching session id
1875
     * @throws Exception when no session matched or more than one session matched
1876
     *
1877
     */
1878
    public function getSessionFromExtraField($fieldName, $fieldValue)
1879
    {
1880
        // find sessions that that have value in field
1881
        $valueModel = new ExtraFieldValue('session');
1882
        $sessionIdList = $valueModel->get_item_id_from_field_variable_and_field_value(
1883
            $fieldName,
1884
            $fieldValue,
1885
            false,
1886
            false,
1887
            true
1888
        );
1889
1890
        // throw if none found
1891
        if (empty($sessionIdList)) {
1892
            throw new Exception(get_lang('NoSessionMatched'));
1893
        }
1894
1895
        // throw if more than one found
1896
        if (count($sessionIdList) > 1) {
1897
            throw new Exception(get_lang('MoreThanOneSessionMatched'));
1898
        }
1899
1900
        // return sessionId
1901
        return intval($sessionIdList[0]['item_id']);
1902
    }
1903
1904
    /**
1905
     * updates a user identified by its login name.
1906
     *
1907
     * @param array $parameters
1908
     *
1909
     * @return boolean, true on success
1910
     * @throws Exception on failure
1911
     *
1912
     */
1913
    public function updateUserFromUserName($parameters)
1914
    {
1915
        // find user
1916
        $userId = null;
1917
        if (!is_array($parameters) || empty($parameters)) {
1918
            throw new Exception('NoData');
1919
        }
1920
        foreach ($parameters as $name => $value) {
1921
            if (strtolower($name) === 'loginname') {
1922
                $userId = UserManager::get_user_id_from_username($value);
1923
                if (false === $userId) {
1924
                    throw new Exception(get_lang('UserNotFound'));
1925
                }
1926
                break;
1927
            }
1928
        }
1929
        if (is_null($userId)) {
1930
            throw new Exception(get_lang('NoData'));
1931
        }
1932
        /** @var User $user */
1933
        $user = UserManager::getRepository()->find($userId);
1934
        if (empty($user)) {
1935
            throw new Exception(get_lang('CouldNotLoadUser'));
1936
        }
1937
1938
        // tell the world we are about to update a user
1939
        $hook = HookUpdateUser::create();
1940
        if (!empty($hook)) {
1941
            $hook->notifyUpdateUser(HOOK_EVENT_TYPE_PRE);
1942
        }
1943
1944
        // apply submitted modifications
1945
        foreach ($parameters as $name => $value) {
1946
            switch (strtolower($name)) {
1947
                case 'email':
1948
                    $user->setEmail($value);
1949
                    break;
1950
                case 'enabled':
1951
                    $user->setEnabled($value);
1952
                    break;
1953
                case 'lastname':
1954
                    $user->setLastname($value);
1955
                    break;
1956
                case 'firstname':
1957
                    $user->setFirstname($value);
1958
                    break;
1959
                case 'phone':
1960
                    $user->setPhone($value);
1961
                    break;
1962
                case 'address':
1963
                    $user->setAddress($value);
1964
                    break;
1965
                case 'roles':
1966
                    $user->setRoles($value);
1967
                    break;
1968
                case 'profile_completed':
1969
                    $user->setProfileCompleted($value);
1970
                    break;
1971
                case 'auth_source':
1972
                    $user->setAuthSource($value);
1973
                    break;
1974
                case 'status':
1975
                    $user->setStatus($value);
1976
                    break;
1977
                case 'official_code':
1978
                    $user->setOfficialCode($value);
1979
                    break;
1980
                case 'picture_uri':
1981
                    $user->setPictureUri($value);
1982
                    break;
1983
                case 'creator_id':
1984
                    $user->setCreatorId($value);
1985
                    break;
1986
                case 'competences':
1987
                    $user->setCompetences($value);
1988
                    break;
1989
                case 'diplomas':
1990
                    $user->setDiplomas($value);
1991
                    break;
1992
                case 'openarea':
1993
                    $user->setOpenArea($value);
1994
                    break;
1995
                case 'teach':
1996
                    $user->setTeach($value);
1997
                    break;
1998
                case 'productions':
1999
                    $user->setProductions($value);
2000
                    break;
2001
                case 'language':
2002
                    $languages = api_get_languages();
2003
                    if (!in_array($value, $languages['folder'])) {
2004
                        throw new Exception(get_lang('LanguageUnavailable'));
2005
                    }
2006
                    $user->setLanguage($value);
2007
                    break;
2008
                case 'registration_date':
2009
                    $user->setRegistrationDate($value);
2010
                    break;
2011
                case 'expiration_date':
2012
                    $user->setExpirationDate(
2013
                        new DateTime(
2014
                            api_get_utc_datetime($value),
2015
                            new DateTimeZone('UTC')
2016
                        )
2017
                    );
2018
                    break;
2019
                case 'active':
2020
                    // see UserManager::update_user() usermanager.lib.php:1205
2021
                    if ($user->getActive() != $value) {
2022
                        $user->setActive($value);
2023
                        Event::addEvent($value ? LOG_USER_ENABLE : LOG_USER_DISABLE, LOG_USER_ID, $userId);
2024
                    }
2025
                    break;
2026
                case 'openid':
2027
                    $user->setOpenId($value);
2028
                    break;
2029
                case 'theme':
2030
                    $user->setTheme($value);
2031
                    break;
2032
                case 'hr_dept_id':
2033
                    $user->setHrDeptId($value);
2034
                    break;
2035
                case 'extra':
2036
                    if (is_array($value)) {
2037
                        if (count($value) > 0) {
2038
                            if (is_array($value[0])) {
2039
                                foreach ($value as $field) {
2040
                                    $fieldName = $field['field_name'];
2041
                                    $fieldValue = $field['field_value'];
2042
                                    if (!isset($fieldName) || !isset($fieldValue) ||
2043
                                        !UserManager::update_extra_field_value($userId, $fieldName, $fieldValue)) {
2044
                                        throw new Exception(
2045
                                            get_lang('CouldNotUpdateExtraFieldValue').': '.print_r($field, true)
2046
                                        );
2047
                                    }
2048
                                }
2049
                            } else {
2050
                                foreach ($value as $fieldName => $fieldValue) {
2051
                                    if (!UserManager::update_extra_field_value($userId, $fieldName, $fieldValue)) {
2052
                                        throw new Exception(get_lang('CouldNotUpdateExtraFieldValue').': '.$fieldName);
2053
                                    }
2054
                                }
2055
                            }
2056
                        }
2057
                    }
2058
                    break;
2059
                case 'username':
2060
                case 'api_key':
2061
                case 'action':
2062
                case 'loginname':
2063
                    break;
2064
                case 'email_canonical':
2065
                case 'locked':
2066
                case 'expired':
2067
                case 'credentials_expired':
2068
                case 'credentials_expire_at':
2069
                case 'expires_at':
2070
                case 'salt':
2071
                case 'last_login':
2072
                case 'created_at':
2073
                case 'updated_at':
2074
                case 'confirmation_token':
2075
                case 'password_requested_at':
2076
                case 'password': // see UserManager::update_user usermanager.lib.php:1182
2077
                case 'username_canonical':
2078
                default:
2079
                    throw new Exception(get_lang('UnsupportedUpdate')." '$name'");
2080
            }
2081
        }
2082
2083
        // save modifications
2084
        UserManager::getManager()->updateUser($user, true);
2085
2086
        // tell the world we just updated this user
2087
        if (!empty($hook)) {
2088
            $hook->setEventData(['user' => $user]);
2089
            $hook->notifyUpdateUser(HOOK_EVENT_TYPE_POST);
2090
        }
2091
2092
        // invalidate cache for this user
2093
        $cacheAvailable = api_get_configuration_value('apc');
2094
        if ($cacheAvailable === true) {
2095
            $apcVar = api_get_configuration_value('apc_prefix').'userinfo_'.$userId;
2096
            if (apcu_exists($apcVar)) {
2097
                apcu_delete($apcVar);
2098
            }
2099
        }
2100
2101
        return true;
2102
    }
2103
2104
    /**
2105
     * Returns whether a user login name exists.
2106
     *
2107
     * @param string $loginname the user login name
2108
     *
2109
     * @return bool whether the user login name exists
2110
     */
2111
    public function usernameExist($loginname)
2112
    {
2113
        return false !== api_get_user_info_from_username($loginname);
2114
    }
2115
}
2116