Completed
Push — master ( 024a20...a0a31d )
by Julito
09:32
created

Rest::addUser()   C

Complexity

Conditions 12
Paths 224

Size

Total Lines 114
Code Lines 80

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 12
eloc 80
nc 224
nop 1
dl 0
loc 114
rs 5.103
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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