Passed
Push — master ( f437d8...92f70a )
by Julito
10:14
created

Rest::decodeParams()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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