Completed
Push — master ( 162b1e...50d94b )
by Julito
11:02
created

Rest::editCampusURL()   A

Complexity

Conditions 6
Paths 20

Size

Total Lines 24
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

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