Passed
Push — master ( ab8dec...906584 )
by Julito
09:36
created

Rest::validate()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 2
dl 0
loc 9
rs 10
c 0
b 0
f 0
1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
use Chamilo\CoreBundle\Entity\Course;
6
use Chamilo\CoreBundle\Entity\ExtraFieldValues;
7
use Chamilo\CoreBundle\Entity\Message;
8
use Chamilo\CoreBundle\Entity\Session;
9
use Chamilo\CoreBundle\Framework\Container;
10
use Chamilo\CourseBundle\Entity\CLpCategory;
11
use Chamilo\CourseBundle\Entity\CNotebook;
12
use Chamilo\CourseBundle\Entity\Repository\CNotebookRepository;
13
use Chamilo\UserBundle\Entity\User;
14
15
/**
16
 * Class RestApi.
17
 */
18
class Rest extends WebService
19
{
20
    const SERVICE_NAME = 'MsgREST';
21
    const EXTRA_FIELD_GCM_REGISTRATION = 'gcm_registration_id';
22
23
    const GET_AUTH = 'authenticate';
24
    const GET_USER_MESSAGES = 'user_messages';
25
    const POST_USER_MESSAGE_READ = 'user_message_read';
26
    const POST_USER_MESSAGE_UNREAD = 'user_message_unread';
27
    const SAVE_GCM_ID = 'gcm_id';
28
    const GET_USER_COURSES = 'user_courses';
29
    const GET_PROFILE = 'user_profile';
30
    const GET_COURSE_INFO = 'course_info';
31
    const GET_COURSE_DESCRIPTIONS = 'course_descriptions';
32
    const GET_COURSE_DOCUMENTS = 'course_documents';
33
    const GET_COURSE_ANNOUNCEMENTS = 'course_announcements';
34
    const GET_COURSE_ANNOUNCEMENT = 'course_announcement';
35
    const GET_COURSE_AGENDA = 'course_agenda';
36
    const GET_COURSE_NOTEBOOKS = 'course_notebooks';
37
    const GET_COURSE_FORUM_CATEGORIES = 'course_forumcategories';
38
    const GET_COURSE_FORUM = 'course_forum';
39
    const GET_COURSE_FORUM_THREAD = 'course_forumthread';
40
    const GET_COURSE_LEARNPATHS = 'course_learnpaths';
41
    const GET_COURSE_LEARNPATH = 'course_learnpath';
42
    const GET_COURSE_LP_PROGRESS = 'course_lp_progress';
43
    const SAVE_FORUM_POST = 'save_forum_post';
44
    const GET_USER_SESSIONS = 'user_sessions';
45
    const SAVE_USER_MESSAGE = 'save_user_message';
46
    const GET_MESSAGE_USERS = 'message_users';
47
    const SAVE_COURSE_NOTEBOOK = 'save_course_notebook';
48
    const SAVE_FORUM_THREAD = 'save_forum_thread';
49
    const SAVE_COURSE = 'save_course';
50
    const SAVE_USER = 'save_user';
51
    const SAVE_USER_JSON = 'save_user_json';
52
    const SUBSCRIBE_USER_TO_COURSE = 'subscribe_user_to_course';
53
    const EXTRAFIELD_GCM_ID = 'gcm_registration_id';
54
    const GET_USER_MESSAGES_RECEIVED = 'user_messages_received';
55
    const GET_USER_MESSAGES_SENT = 'user_messages_sent';
56
    const DELETE_USER_MESSAGE = 'delete_user_message';
57
    const SET_MESSAGE_READ = 'set_message_read';
58
    const CREATE_CAMPUS = 'add_campus';
59
    const EDIT_CAMPUS = 'edit_campus';
60
    const DELETE_CAMPUS = 'delete_campus';
61
    const SAVE_SESSION = 'save_session';
62
    const GET_USERS = 'get_users';
63
    const GET_COURSES = 'get_courses';
64
    const ADD_COURSES_SESSION = 'add_courses_session';
65
    const ADD_USERS_SESSION = 'add_users_session';
66
    const CREATE_SESSION_FROM_MODEL = 'create_session_from_model';
67
    const SUBSCRIBE_USER_TO_SESSION_FROM_USERNAME = 'subscribe_user_to_session_from_username';
68
    const GET_SESSION_FROM_EXTRA_FIELD = 'get_session_from_extra_field';
69
    const UPDATE_USER_FROM_USERNAME = 'update_user_from_username';
70
    const USERNAME_EXIST = 'username_exist';
71
    const GET_COURSE_QUIZ_MDL_COMPAT = 'get_course_quiz_mdl_compat';
72
    const UPDATE_USER_PAUSE_TRAINING = 'update_user_pause_training';
73
74
    /**
75
     * @var Session
76
     */
77
    private $session;
78
79
    /**
80
     * @var Course
81
     */
82
    private $course;
83
84
    /**
85
     * Rest constructor.
86
     *
87
     * @param string $username
88
     * @param string $apiKey
89
     */
90
    public function __construct($username, $apiKey)
91
    {
92
        parent::__construct($username, $apiKey);
93
    }
94
95
    /**
96
     * @param string $username
97
     * @param string $apiKeyToValidate
98
     *
99
     * @throws Exception
100
     *
101
     * @return Rest
102
     */
103
    public static function validate($username, $apiKeyToValidate)
104
    {
105
        $apiKey = self::findUserApiKey($username, self::SERVICE_NAME);
106
107
        if ($apiKey != $apiKeyToValidate) {
108
            throw new Exception(get_lang('InvalidApiKey'));
109
        }
110
111
        return new self($username, $apiKey);
112
    }
113
114
    /**
115
     * Create the gcm_registration_id extra field for users.
116
     */
117
    public static function init()
118
    {
119
        $extraField = new ExtraField('user');
120
        $fieldInfo = $extraField->get_handler_field_info_by_field_variable(self::EXTRA_FIELD_GCM_REGISTRATION);
121
122
        if (empty($fieldInfo)) {
123
            $extraField->save(
124
                [
125
                    'variable' => self::EXTRA_FIELD_GCM_REGISTRATION,
126
                    'field_type' => ExtraField::FIELD_TYPE_TEXT,
127
                    'display_text' => self::EXTRA_FIELD_GCM_REGISTRATION,
128
                ]
129
            );
130
        }
131
    }
132
133
    /**
134
     * @param string $encoded
135
     *
136
     * @return array
137
     */
138
    public static function decodeParams($encoded)
139
    {
140
        return json_decode($encoded);
141
    }
142
143
    /**
144
     * Set the current course.
145
     *
146
     * @param int $id
147
     *
148
     * @throws Exception
149
     */
150
    public function setCourse($id)
151
    {
152
        if (!$id) {
153
            $this->course = null;
154
155
            return;
156
        }
157
158
        $course = api_get_course_entity($id);
159
160
        if (!$course) {
161
            throw new Exception(get_lang('NoCourse'));
162
        }
163
164
        $this->course = $course;
165
    }
166
167
    /**
168
     * Set the current session.
169
     *
170
     * @param int $id
171
     *
172
     * @throws Exception
173
     */
174
    public function setSession($id)
175
    {
176
        if (!$id) {
177
            $this->session = null;
178
179
            return;
180
        }
181
182
        $session = api_get_session_entity($id);
183
184
        if (!$session) {
185
            throw new Exception(get_lang('NoSession'));
186
        }
187
188
        $this->session = $session;
189
    }
190
191
    /**
192
     * @param string $registrationId
193
     *
194
     * @return bool
195
     */
196
    public function setGcmId($registrationId)
197
    {
198
        $registrationId = Security::remove_XSS($registrationId);
199
        $extraFieldValue = new ExtraFieldValue('user');
200
201
        return $extraFieldValue->save(
202
            [
203
                'variable' => self::EXTRA_FIELD_GCM_REGISTRATION,
204
                'value' => $registrationId,
205
                'item_id' => $this->user->getId(),
206
            ]
207
        );
208
    }
209
210
    public function processMessage(Message $message)
211
    {
212
        $illustrationRepo = Container::getIllustrationRepository();
213
        $hasAttachments = $message->getAttachments()->count() > 0;
214
        $attachmentList = [];
215
        if ($hasAttachments) {
216
            $repo = Container::getMessageAttachmentRepository();
217
            $attachments = $message->getAttachments();
218
            foreach ($attachments as $attachment) {
219
                $attachmentList[] = [
220
                    'file_source' => $repo->getResourceFileUrl($attachment),
221
                ];
222
            }
223
        }
224
225
        $picture = $illustrationRepo->getIllustrationUrl($message->getUserSender());
226
        return [
227
            'id' => $message->getId(),
228
            'title' => $message->getTitle(),
229
            'sender' => [
230
                'id' => $message->getUserSender()->getId(),
231
                'lastname' => $message->getUserSender()->getLastname(),
232
                'firstname' => $message->getUserSender()->getFirstname(),
233
                'completeName' => UserManager::formatUserFullName($message->getUserSender()),
234
                'pictureUri' => $picture,
235
            ],
236
            'sendDate' => $message->getSendDate()->format('Y-m-d H:i:s'),
237
            'content' => $message->getContent(),
238
            'hasAttachments' => $hasAttachments,
239
            'attachmentList' => $attachmentList,
240
            'url' => api_get_path(WEB_CODE_PATH).'messages/view_message.php?'
241
                .http_build_query(['type' => 1, 'id' => $message->getId()]),
242
        ];
243
    }
244
245
    /**
246
     * @param int $lastMessageId
247
     *
248
     * @return array
249
     */
250
    public function getUserMessages($lastMessageId = 0)
251
    {
252
        $lastMessages = MessageManager::getMessagesFromLastReceivedMessage($this->user->getId(), $lastMessageId);
253
        $messages = [];
254
        foreach ($lastMessages as $message) {
255
            $messages[] = $this->processMessage($message);
256
        }
257
258
        return $messages;
259
    }
260
261
    /**
262
     * @return array
263
     */
264
    public function getUserReceivedMessages()
265
    {
266
        $lastMessages = MessageManager::getReceivedMessages($this->user->getId(), 0);
267
        $messages = [];
268
        foreach ($lastMessages as $message) {
269
            $messages[] = $this->processMessage($message);
270
        }
271
272
        return $messages;
273
    }
274
275
    /**
276
     * @return array
277
     */
278
    public function getUserSentMessages()
279
    {
280
        $lastMessages = MessageManager::getSentMessages($this->user->getId(), 0);
281
        $messages = [];
282
283
        foreach ($lastMessages as $message) {
284
            $messages[] = $this->processMessage($message);
285
        }
286
287
        return $messages;
288
    }
289
290
    /**
291
     * Get the user courses.
292
     *
293
     * @throws \Doctrine\ORM\TransactionRequiredException
294
     * @throws \Doctrine\ORM\ORMException
295
     * @throws \Doctrine\ORM\OptimisticLockException
296
     *
297
     * @return array
298
     */
299
    public function getUserCourses()
300
    {
301
        $courses = CourseManager::get_courses_list_by_user_id($this->user->getId());
302
        $data = [];
303
304
        foreach ($courses as $courseInfo) {
305
            $course = api_get_course_entity($courseInfo['real_id']);
306
            $teachers = CourseManager::getTeacherListFromCourseCodeToString($course->getCode());
307
            $picturePath = CourseManager::getPicturePath($course, true)
308
                ?: Display::return_icon('session_default.png', null, null, null, null, true);
309
310
            $data[] = [
311
                'id' => $course->getId(),
312
                'title' => $course->getTitle(),
313
                'code' => $course->getCode(),
314
                'directory' => $course->getDirectory(),
315
                'urlPicture' => $picturePath,
316
                'teachers' => $teachers,
317
                'isSpecial' => !empty($courseInfo['special_course']),
318
            ];
319
        }
320
321
        return $data;
322
    }
323
324
    /**
325
     * @throws Exception
326
     *
327
     * @return array
328
     */
329
    public function getCourseInfo()
330
    {
331
        $teachers = CourseManager::getTeacherListFromCourseCodeToString($this->course->getCode());
332
        $tools = CourseHome::get_tools_category(
333
            TOOL_STUDENT_VIEW,
334
            $this->course->getId(),
335
            $this->session ? $this->session->getId() : 0
336
        );
337
338
        return [
339
            'id' => $this->course->getId(),
340
            'title' => $this->course->getTitle(),
341
            'code' => $this->course->getCode(),
342
            'directory' => $this->course->getDirectory(),
343
            'urlPicture' => CourseManager::getPicturePath($this->course, true),
344
            'teachers' => $teachers,
345
            'tools' => array_map(
346
                function ($tool) {
347
                    return ['type' => $tool['name']];
348
                },
349
                $tools
350
            ),
351
        ];
352
    }
353
354
    /**
355
     * Get the course descriptions.
356
     *
357
     * @throws Exception
358
     *
359
     * @return array
360
     */
361
    public function getCourseDescriptions()
362
    {
363
        $descriptions = CourseDescription::get_descriptions($this->course->getId());
364
        $results = [];
365
366
        /** @var CourseDescription $description */
367
        foreach ($descriptions as $description) {
368
            $results[] = [
369
                'id' => $description->get_description_type(),
370
                'title' => $description->get_title(),
371
                'content' => str_replace('src="/', 'src="'.api_get_path(WEB_PATH), $description->get_content()),
372
            ];
373
        }
374
375
        return $results;
376
    }
377
378
    /**
379
     * @param int $directoryId
380
     *
381
     * @throws Exception
382
     *
383
     * @return array
384
     */
385
    public function getCourseDocuments($directoryId = 0)
386
    {
387
        /** @var string $path */
388
        $path = '/';
389
        $sessionId = $this->session ? $this->session->getId() : 0;
390
391
        if ($directoryId) {
392
            $directory = DocumentManager::get_document_data_by_id(
393
                $directoryId,
394
                $this->course->getCode(),
395
                false,
396
                $sessionId
397
            );
398
399
            if (!$directory) {
400
                throw new Exception('NoDataAvailable');
401
            }
402
403
            $path = $directory['path'];
404
        }
405
406
        $courseInfo = api_get_course_info_by_id($this->course->getId());
407
        $documents = DocumentManager::getAllDocumentData(
408
            $courseInfo,
409
            $path,
410
            0,
411
            null,
412
            false,
413
            false,
414
            $sessionId
415
        );
416
        $results = [];
417
418
        if (!empty($documents)) {
419
            $webPath = api_get_path(WEB_CODE_PATH).'document/document.php?';
420
421
            /** @var array $document */
422
            foreach ($documents as $document) {
423
                if ('1' != $document['visibility']) {
424
                    continue;
425
                }
426
427
                $icon = 'file' == $document['filetype']
428
                    ? choose_image($document['path'])
429
                    : chooseFolderIcon($document['path']);
430
431
                $results[] = [
432
                    'id' => $document['id'],
433
                    'type' => $document['filetype'],
434
                    'title' => $document['title'],
435
                    'path' => $document['path'],
436
                    'url' => $webPath.http_build_query(
437
                        [
438
                            'username' => $this->user->getUsername(),
439
                            'api_key' => $this->apiKey,
440
                            'cidReq' => $this->course->getCode(),
441
                            'id_session' => $sessionId,
442
                            'gidReq' => 0,
443
                            'gradebook' => 0,
444
                            'origin' => '',
445
                            'action' => 'download',
446
                            'id' => $document['id'],
447
                        ]
448
                    ),
449
                    'icon' => $icon,
450
                    'size' => format_file_size($document['size']),
451
                ];
452
            }
453
        }
454
455
        return $results;
456
    }
457
458
    /**
459
     * @throws Exception
460
     *
461
     * @return array
462
     */
463
    public function getCourseAnnouncements()
464
    {
465
        $sessionId = $this->session ? $this->session->getId() : 0;
466
467
        $announcements = AnnouncementManager::getAnnouncements(
468
            null,
469
            null,
470
            false,
471
            null,
472
            null,
473
            null,
474
            null,
475
            null,
476
            0,
477
            $this->user->getId(),
478
            $this->course->getId(),
479
            $sessionId
480
        );
481
482
        $announcements = array_map(
483
            function ($announcement) {
484
                return [
485
                    'id' => (int) $announcement['id'],
486
                    'title' => strip_tags($announcement['title']),
487
                    'creatorName' => strip_tags($announcement['username']),
488
                    'date' => strip_tags($announcement['insert_date']),
489
                ];
490
            },
491
            $announcements
492
        );
493
494
        return $announcements;
495
    }
496
497
    /**
498
     * @param int $announcementId
499
     *
500
     * @throws Exception
501
     *
502
     * @return array
503
     */
504
    public function getCourseAnnouncement($announcementId)
505
    {
506
        $sessionId = $this->session ? $this->session->getId() : 0;
507
        $announcement = AnnouncementManager::getAnnouncementInfoById(
508
            $announcementId,
509
            $this->course->getId(),
510
            $this->user->getId()
511
        );
512
513
        if (!$announcement) {
514
            throw new Exception(get_lang('NoAnnouncement'));
515
        }
516
517
        return [
518
            'id' => $announcement['announcement']->getIid(),
519
            'title' => $announcement['announcement']->getTitle(),
520
            'creatorName' => UserManager::formatUserFullName($announcement['item_property']->getInsertUser()),
521
            'date' => api_convert_and_format_date(
522
                $announcement['item_property']->getInsertDate(),
523
                DATE_TIME_FORMAT_LONG_24H
524
            ),
525
            'content' => AnnouncementManager::parseContent(
526
                $this->user->getId(),
527
                $announcement['announcement']->getContent(),
528
                $this->course->getCode(),
529
                $sessionId
530
            ),
531
        ];
532
    }
533
534
    /**
535
     * @throws Exception
536
     *
537
     * @return array
538
     */
539
    public function getCourseAgenda()
540
    {
541
        $sessionId = $this->session ? $this->session->getId() : 0;
542
543
        $agenda = new Agenda(
544
            'course',
545
            $this->user->getId(),
546
            $this->course->getId(),
547
            $sessionId
548
        );
549
        $result = $agenda->parseAgendaFilter(null);
550
551
        $start = new DateTime(api_get_utc_datetime(), new DateTimeZone('UTC'));
552
        $start->modify('first day of this month');
553
        $start->setTime(0, 0, 0);
554
        $end = new DateTime(api_get_utc_datetime(), new DateTimeZone('UTC'));
555
        $end->modify('last day of this month');
556
        $end->setTime(23, 59, 59);
557
558
        $groupId = current($result['groups']);
559
        $userId = current($result['users']);
560
561
        $events = $agenda->getEvents(
562
            $start->getTimestamp(),
563
            $end->getTimestamp(),
564
            $this->course->getId(),
565
            $groupId,
566
            $userId,
567
            'array'
568
        );
569
570
        if (!is_array($events)) {
571
            return [];
572
        }
573
574
        $webPath = api_get_path(WEB_PATH);
575
576
        return array_map(
577
            function ($event) use ($webPath) {
578
                return [
579
                    'id' => (int) $event['unique_id'],
580
                    'title' => $event['title'],
581
                    'content' => str_replace('src="/', 'src="'.$webPath, $event['description']),
582
                    'startDate' => $event['start_date_localtime'],
583
                    'endDate' => $event['end_date_localtime'],
584
                    'isAllDay' => $event['allDay'] ? true : false,
585
                ];
586
            },
587
            $events
588
        );
589
    }
590
591
    /**
592
     * @throws Exception
593
     *
594
     * @return array
595
     */
596
    public function getCourseNotebooks()
597
    {
598
        $em = Database::getManager();
599
        /** @var CNotebookRepository $notebooksRepo */
600
        $notebooksRepo = $em->getRepository('ChamiloCourseBundle:CNotebook');
601
        $notebooks = $notebooksRepo->findByUser($this->user, $this->course, $this->session);
602
603
        return array_map(
604
            function (CNotebook $notebook) {
605
                return [
606
                    'id' => $notebook->getIid(),
607
                    'title' => $notebook->getTitle(),
608
                    'description' => $notebook->getDescription(),
609
                    'creationDate' => api_format_date(
610
                        $notebook->getCreationDate()->getTimestamp()
611
                    ),
612
                    'updateDate' => api_format_date(
613
                        $notebook->getUpdateDate()->getTimestamp()
614
                    ),
615
                ];
616
            },
617
            $notebooks
618
        );
619
    }
620
621
    /**
622
     * @throws Exception
623
     *
624
     * @return array
625
     */
626
    public function getCourseForumCategories()
627
    {
628
        $sessionId = $this->session ? $this->session->getId() : 0;
629
        $webCoursePath = api_get_path(WEB_COURSE_PATH).$this->course->getDirectory().'/upload/forum/images/';
630
631
        require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
632
633
        $categoriesFullData = get_forum_categories('', $this->course->getId(), $sessionId);
634
        $categories = [];
635
        $includeGroupsForums = 'true' === api_get_setting('display_groups_forum_in_general_tool');
636
        $forumsFullData = get_forums('', $this->course->getCode(), $includeGroupsForums, $sessionId);
637
        $forums = [];
638
639
        foreach ($forumsFullData as $forumId => $forumInfo) {
640
            $forum = [
641
                'id' => (int) $forumInfo['iid'],
642
                'catId' => (int) $forumInfo['forum_category'],
643
                'title' => $forumInfo['forum_title'],
644
                'description' => $forumInfo['forum_comment'],
645
                'image' => $forumInfo['forum_image'] ? ($webCoursePath.$forumInfo['forum_image']) : '',
646
                'numberOfThreads' => isset($forumInfo['number_of_threads']) ? intval(
647
                    $forumInfo['number_of_threads']
648
                ) : 0,
649
                'lastPost' => null,
650
            ];
651
652
            $lastPostInfo = get_last_post_information($forumId, false, $this->course->getId(), $sessionId);
653
654
            if ($lastPostInfo) {
655
                $forum['lastPost'] = [
656
                    'date' => api_convert_and_format_date($lastPostInfo['last_post_date']),
657
                    'user' => api_get_person_name(
658
                        $lastPostInfo['last_poster_firstname'],
659
                        $lastPostInfo['last_poster_lastname']
660
                    ),
661
                ];
662
            }
663
664
            $forums[] = $forum;
665
        }
666
667
        foreach ($categoriesFullData as $category) {
668
            $categoryForums = array_filter(
669
                $forums,
670
                function (array $forum) use ($category) {
671
                    if ($forum['catId'] != $category['cat_id']) {
672
                        return false;
673
                    }
674
675
                    return true;
676
                }
677
            );
678
679
            $categories[] = [
680
                'id' => (int) $category['iid'],
681
                'title' => $category['cat_title'],
682
                'catId' => (int) $category['cat_id'],
683
                'description' => $category['cat_comment'],
684
                'forums' => $categoryForums,
685
                'courseId' => $this->course->getId(),
686
            ];
687
        }
688
689
        return $categories;
690
    }
691
692
    /**
693
     * @param int $forumId
694
     *
695
     * @throws Exception
696
     *
697
     * @return array
698
     */
699
    public function getCourseForum($forumId)
700
    {
701
        require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
702
703
        $sessionId = $this->session ? $this->session->getId() : 0;
704
        $forumInfo = get_forums($forumId, $this->course->getCode(), true, $sessionId);
705
706
        if (!isset($forumInfo['iid'])) {
707
            throw new Exception(get_lang('NoForum'));
708
        }
709
710
        $webCoursePath = api_get_path(WEB_COURSE_PATH).$this->course->getDirectory().'/upload/forum/images/';
711
        $forum = [
712
            'id' => $forumInfo['iid'],
713
            'title' => $forumInfo['forum_title'],
714
            'description' => $forumInfo['forum_comment'],
715
            'image' => $forumInfo['forum_image'] ? ($webCoursePath.$forumInfo['forum_image']) : '',
716
            'threads' => [],
717
        ];
718
719
        $threads = get_threads($forumInfo['iid'], $this->course->getId(), $sessionId);
720
721
        foreach ($threads as $thread) {
722
            $forum['threads'][] = [
723
                'id' => $thread['iid'],
724
                'title' => $thread['thread_title'],
725
                'lastEditDate' => api_convert_and_format_date($thread['lastedit_date'], DATE_TIME_FORMAT_LONG_24H),
726
                'numberOfReplies' => $thread['thread_replies'],
727
                'numberOfViews' => $thread['thread_views'],
728
                'author' => api_get_person_name($thread['firstname'], $thread['lastname']),
729
            ];
730
        }
731
732
        return $forum;
733
    }
734
735
    /**
736
     * @param int $forumId
737
     * @param int $threadId
738
     *
739
     * @return array
740
     */
741
    public function getCourseForumThread($forumId, $threadId)
742
    {
743
        require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
744
745
        $sessionId = $this->session ? $this->session->getId() : 0;
746
        $threadInfo = get_thread_information($forumId, $threadId, $sessionId);
747
748
        $thread = [
749
            'id' => intval($threadInfo['iid']),
750
            'cId' => intval($threadInfo['c_id']),
751
            'title' => $threadInfo['thread_title'],
752
            'forumId' => intval($threadInfo['forum_id']),
753
            'posts' => [],
754
        ];
755
756
        $forumInfo = get_forums($threadInfo['forum_id'], $this->course->getCode(), true, $sessionId);
757
        $postsInfo = getPosts($forumInfo, $threadInfo['iid'], 'ASC');
758
759
        foreach ($postsInfo as $postInfo) {
760
            $thread['posts'][] = [
761
                'id' => $postInfo['iid'],
762
                'title' => $postInfo['post_title'],
763
                'text' => $postInfo['post_text'],
764
                'author' => api_get_person_name($postInfo['firstname'], $postInfo['lastname']),
765
                'date' => api_convert_and_format_date($postInfo['post_date'], DATE_TIME_FORMAT_LONG_24H),
766
                'parentId' => $postInfo['post_parent_id'],
767
            ];
768
        }
769
770
        return $thread;
771
    }
772
773
    /**
774
     * @return array
775
     */
776
    public function getUserProfile()
777
    {
778
        $pictureInfo = UserManager::get_user_picture_path_by_id($this->user->getId(), 'web');
779
780
        $result = [
781
            'pictureUri' => $pictureInfo['dir'].$pictureInfo['file'],
782
            'id' => $this->user->getId(),
783
            'status' => $this->user->getStatus(),
784
            'fullName' => UserManager::formatUserFullName($this->user),
785
            'username' => $this->user->getUsername(),
786
            'officialCode' => $this->user->getOfficialCode(),
787
            'phone' => $this->user->getPhone(),
788
            'extra' => [],
789
        ];
790
791
        $fieldValue = new ExtraFieldValue('user');
792
        $extraInfo = $fieldValue->getAllValuesForAnItem($this->user->getId(), true);
793
794
        foreach ($extraInfo as $extra) {
795
            /** @var ExtraFieldValues $extraValue */
796
            $extraValue = $extra['value'];
797
            $result['extra'][] = [
798
                'title' => $extraValue->getField()->getDisplayText(true),
799
                'value' => $extraValue->getValue(),
800
            ];
801
        }
802
803
        return $result;
804
    }
805
806
    public function getCourseLpProgress()
807
    {
808
        $sessionId = $this->session ? $this->session->getId() : 0;
809
        $userId = $this->user->getId();
810
811
        /*$sessionId = $this->session ? $this->session->getId() : 0;
812
        $courseId = $this->course->getId();*/
813
814
        $result = Tracking::getCourseLpProgress($userId, $sessionId);
815
816
        return [$result];
817
    }
818
819
    /**
820
     * @throws Exception
821
     *
822
     * @return array
823
     */
824
    public function getCourseLearnPaths()
825
    {
826
        $sessionId = $this->session ? $this->session->getId() : 0;
827
        $categoriesTempList = learnpath::getCategories($this->course->getId());
828
829
        $categoryNone = new CLpCategory();
830
        $categoryNone->setId(0);
831
        $categoryNone->setName(get_lang('WithOutCategory'));
832
        $categoryNone->setPosition(0);
833
834
        $categories = array_merge([$categoryNone], $categoriesTempList);
835
        $categoryData = [];
836
837
        /** @var CLpCategory $category */
838
        foreach ($categories as $category) {
839
            $learnPathList = new LearnpathList(
840
                $this->user->getId(),
841
                api_get_course_info($this->course->getCode()),
842
                $sessionId,
843
                null,
844
                false,
845
                $category->getId()
846
            );
847
848
            $flatLpList = $learnPathList->get_flat_list();
849
850
            if (empty($flatLpList)) {
851
                continue;
852
            }
853
854
            $listData = [];
855
856
            foreach ($flatLpList as $lpId => $lpDetails) {
857
                if (0 == $lpDetails['lp_visibility']) {
858
                    continue;
859
                }
860
861
                if (!learnpath::is_lp_visible_for_student(
862
                    $lpId,
863
                    $this->user->getId(),
864
                    api_get_course_info($this->course->getCode()),
865
                    $sessionId
866
                )) {
867
                    continue;
868
                }
869
870
                $timeLimits = false;
871
872
                // This is an old LP (from a migration 1.8.7) so we do nothing
873
                if (empty($lpDetails['created_on']) && empty($lpDetails['modified_on'])) {
874
                    $timeLimits = false;
875
                }
876
877
                // Checking if expired_on is ON
878
                if (!empty($lpDetails['expired_on'])) {
879
                    $timeLimits = true;
880
                }
881
882
                if ($timeLimits) {
883
                    if (!empty($lpDetails['publicated_on']) && !empty($lpDetails['expired_on'])) {
884
                        $startTime = api_strtotime($lpDetails['publicated_on'], 'UTC');
885
                        $endTime = api_strtotime($lpDetails['expired_on'], 'UTC');
886
                        $now = time();
887
                        $isActiveTime = false;
888
889
                        if ($now > $startTime && $endTime > $now) {
890
                            $isActiveTime = true;
891
                        }
892
893
                        if (!$isActiveTime) {
894
                            continue;
895
                        }
896
                    }
897
                }
898
899
                $progress = learnpath::getProgress($lpId, $this->user->getId(), $this->course->getId(), $sessionId);
900
901
                $listData[] = [
902
                    'id' => $lpId,
903
                    'title' => Security::remove_XSS($lpDetails['lp_name']),
904
                    'progress' => $progress,
905
                    'url' => api_get_path(WEB_CODE_PATH).'webservices/api/v2.php?'.http_build_query(
906
                        [
907
                            'hash' => $this->encodeParams(
908
                                [
909
                                    'action' => 'course_learnpath',
910
                                    'lp_id' => $lpId,
911
                                    'course' => $this->course->getId(),
912
                                    'session' => $sessionId,
913
                                ]
914
                            ),
915
                        ]
916
                    ),
917
                ];
918
            }
919
920
            if (empty($listData)) {
921
                continue;
922
            }
923
924
            $categoryData[] = [
925
                'id' => $category->getId(),
926
                'name' => $category->getName(),
927
                'learnpaths' => $listData,
928
            ];
929
        }
930
931
        return $categoryData;
932
    }
933
934
    /**
935
     * Start login for a user. Then make a redirect to show the learnpath.
936
     *
937
     * @param int $lpId
938
     */
939
    public function showLearningPath($lpId)
940
    {
941
        $loggedUser['user_id'] = $this->user->getId();
942
        $loggedUser['status'] = $this->user->getStatus();
943
        $loggedUser['uidReset'] = true;
944
        $sessionId = $this->session ? $this->session->getId() : 0;
945
946
        ChamiloSession::write('_user', $loggedUser);
947
        Login::init_user($this->user->getId(), true);
948
949
        $url = api_get_path(WEB_CODE_PATH).'lp/lp_controller.php?'.http_build_query(
950
            [
951
                'cidReq' => $this->course->getCode(),
952
                'id_session' => $sessionId,
953
                'gidReq' => 0,
954
                'gradebook' => 0,
955
                'origin' => '',
956
                'action' => 'view',
957
                'lp_id' => (int) $lpId,
958
                'isStudentView' => 'true',
959
            ]
960
        );
961
962
        header("Location: $url");
963
        exit;
964
    }
965
966
    /**
967
     * @param int $forumId
968
     *
969
     * @return array
970
     */
971
    public function saveForumPost(array $postValues, $forumId)
972
    {
973
        require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
974
975
        $forum = get_forums($forumId, $this->course->getCode());
976
        store_reply($forum, $postValues, $this->course->getId(), $this->user->getId());
977
978
        return [
979
            'registered' => true,
980
        ];
981
    }
982
983
    /**
984
     * Get the list of sessions for current user.
985
     *
986
     * @return array the sessions list
987
     */
988
    public function getUserSessions()
989
    {
990
        $data = [];
991
        $sessionsByCategory = UserManager::get_sessions_by_category($this->user->getId(), false);
992
993
        foreach ($sessionsByCategory as $category) {
994
            $categorySessions = [];
995
996
            foreach ($category['sessions'] as $sessions) {
997
                $sessionCourses = [];
998
999
                foreach ($sessions['courses'] as $course) {
1000
                    $courseInfo = api_get_course_info_by_id($course['real_id']);
1001
                    $teachers = SessionManager::getCoachesByCourseSessionToString(
1002
                        $sessions['session_id'],
1003
                        $course['real_id']
1004
                    );
1005
1006
                    $sessionCourses[] = [
1007
                        'id' => $courseInfo['real_id'],
1008
                        'title' => $courseInfo['title'],
1009
                        'code' => $courseInfo['code'],
1010
                        'directory' => $courseInfo['directory'],
1011
                        'pictureUrl' => $courseInfo['course_image_large'],
1012
                        'urlPicture' => $courseInfo['course_image_large'],
1013
                        'teachers' => $teachers,
1014
                    ];
1015
                }
1016
1017
                $sessionBox = Display::getSessionTitleBox($sessions['session_id']);
1018
1019
                $categorySessions[] = [
1020
                    'name' => $sessionBox['title'],
1021
                    'id' => $sessions['session_id'],
1022
                    'date' => $sessionBox['dates'],
1023
                    'duration' => isset($sessionBox['duration']) ? $sessionBox['duration'] : null,
1024
                    'courses' => $sessionCourses,
1025
                ];
1026
            }
1027
1028
            $data[] = [
1029
                'id' => $category['session_category']['id'],
1030
                'name' => $category['session_category']['name'],
1031
                'sessions' => $categorySessions,
1032
            ];
1033
        }
1034
1035
        return $data;
1036
    }
1037
1038
    /**
1039
     * @param string $subject
1040
     * @param string $text
1041
     *
1042
     * @return array
1043
     */
1044
    public function saveUserMessage($subject, $text, array $receivers)
1045
    {
1046
        foreach ($receivers as $userId) {
1047
            MessageManager::send_message($userId, $subject, $text);
1048
        }
1049
1050
        return [
1051
            'sent' => true,
1052
        ];
1053
    }
1054
1055
    /**
1056
     * @param string $search
1057
     *
1058
     * @return array
1059
     */
1060
    public function getMessageUsers($search)
1061
    {
1062
        $repo = UserManager::getRepository();
1063
1064
        $users = $repo->findUsersToSendMessage($this->user->getId(), $search);
1065
        $showEmail = 'true' === api_get_setting('show_email_addresses');
1066
        $data = [];
1067
1068
        /** @var User $user */
1069
        foreach ($users as $user) {
1070
            $userName = UserManager::formatUserFullName($user);
1071
1072
            if ($showEmail) {
1073
                $userName .= " ({$user->getEmail()})";
1074
            }
1075
1076
            $data[] = [
1077
                'id' => $user->getId(),
1078
                'name' => $userName,
1079
            ];
1080
        }
1081
1082
        return $data;
1083
    }
1084
1085
    /**
1086
     * @param string $title
1087
     * @param string $text
1088
     *
1089
     * @return array
1090
     */
1091
    public function saveCourseNotebook($title, $text)
1092
    {
1093
        $values = ['note_title' => $title, 'note_comment' => $text];
1094
        $sessionId = $this->session ? $this->session->getId() : 0;
1095
1096
        $noteBookId = NotebookManager::save_note(
1097
            $values,
1098
            $this->user->getId(),
1099
            $this->course->getId(),
1100
            $sessionId
1101
        );
1102
1103
        return [
1104
            'registered' => $noteBookId,
1105
        ];
1106
    }
1107
1108
    /**
1109
     * @param int $forumId
1110
     *
1111
     * @return array
1112
     */
1113
    public function saveForumThread(array $values, $forumId)
1114
    {
1115
        require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
1116
1117
        $sessionId = $this->session ? $this->session->getId() : 0;
1118
        $forum = get_forums($forumId, $this->course->getCode(), true, $sessionId);
1119
        $courseInfo = api_get_course_info($this->course->getCode());
1120
        $thread = saveThread($forum, $values, $courseInfo, false, $this->user->getId(), $sessionId);
1121
1122
        return [
1123
            'registered' => $thread->getIid(),
1124
        ];
1125
    }
1126
1127
    /**
1128
     * @return array
1129
     */
1130
    public function getUsersCampus(array $params)
1131
    {
1132
        $conditions = [
1133
            'status' => $params['status'],
1134
        ];
1135
        $idCampus = $params['id_campus'];
1136
        $users = UserManager::get_user_list($conditions, ['firstname'], false, false, $idCampus);
1137
        $list = [];
1138
        foreach ($users as $item) {
1139
            $listTemp = [
1140
                'id' => $item['user_id'],
1141
                'firstname' => $item['firstname'],
1142
                'lastname' => $item['lastname'],
1143
                'email' => $item['email'],
1144
            ];
1145
            $list[] = $listTemp;
1146
        }
1147
1148
        return $list;
1149
    }
1150
1151
    /**
1152
     * @return array
1153
     */
1154
    public function getCoursesCampus(array $params)
1155
    {
1156
        $idCampus = $params['id_campus'];
1157
1158
        $courseList = CourseManager::get_courses_list(
1159
            0, //offset
1160
            0, //howMany
1161
            1, //$orderby = 1
1162
            'ASC',
1163
            -1, //visibility
1164
            null,
1165
            $idCampus, //$urlId
1166
            true //AlsoSearchCode
1167
        );
1168
1169
        return $courseList;
1170
    }
1171
1172
    /**
1173
     * @return array
1174
     */
1175
    public function addSession(array $params)
1176
    {
1177
        $name = $params['name'];
1178
        $coach_username = (int) $params['coach_username'];
1179
        $startDate = $params['access_start_date'];
1180
        $endDate = $params['access_end_date'];
1181
        $displayStartDate = $startDate;
1182
        $displayEndDate = $endDate;
1183
        $description = $params['description'];
1184
        $idUrlCampus = $params['id_campus'];
1185
        $extraFields = isset($params['extra']) ? $params['extra'] : [];
1186
1187
        $return = SessionManager::create_session(
1188
            $name,
1189
            $startDate,
1190
            $endDate,
1191
            $displayStartDate,
1192
            $displayEndDate,
1193
            null,
1194
            null,
1195
            $coach_username,
1196
            null,
1197
            1,
1198
            false,
1199
            null,
1200
            $description,
1201
            1,
1202
            $extraFields,
1203
            null,
1204
            false,
1205
            $idUrlCampus
1206
        );
1207
1208
        if ($return) {
1209
            $out = [
1210
                'status' => true,
1211
                'message' => get_lang('ANewSessionWasCreated'),
1212
                'id_session' => $return,
1213
            ];
1214
        } else {
1215
            $out = [
1216
                'status' => false,
1217
                'message' => get_lang('ErrorOccurred'),
1218
            ];
1219
        }
1220
1221
        return $out;
1222
    }
1223
1224
    /**
1225
     * @return array
1226
     */
1227
    public function addCourse(array $courseParam)
1228
    {
1229
        $results = [];
1230
        $idCampus = isset($courseParam['id_campus']) ? $courseParam['id_campus'] : 1;
1231
        $title = isset($courseParam['title']) ? $courseParam['title'] : '';
1232
        $wantedCode = isset($courseParam['wanted_code']) ? $courseParam['wanted_code'] : null;
1233
        $diskQuota = isset($courseParam['disk_quota']) ? $courseParam['disk_quota'] : '100';
1234
        $visibility = isset($courseParam['visibility']) ? (int) $courseParam['visibility'] : null;
1235
1236
        if (isset($courseParam['visibility'])) {
1237
            if ($courseParam['visibility'] &&
1238
                $courseParam['visibility'] >= 0 &&
1239
                $courseParam['visibility'] <= 3
1240
            ) {
1241
                $visibility = (int) $courseParam['visibility'];
1242
            }
1243
        }
1244
1245
        $params = [];
1246
        $params['title'] = $title;
1247
        $params['wanted_code'] = 'CAMPUS_'.$idCampus.'_'.$wantedCode;
1248
        $params['user_id'] = $this->user->getId();
1249
        $params['visibility'] = $visibility;
1250
        $params['disk_quota'] = $diskQuota;
1251
1252
        $courseInfo = CourseManager::create_course($params, $params['user_id'], $idCampus);
1253
1254
        if (!empty($courseInfo)) {
1255
            $results['status'] = true;
1256
            $results['code_course'] = $courseInfo['code'];
1257
            $results['title_course'] = $courseInfo['title'];
1258
            $results['message'] = sprintf(get_lang('CourseXAdded'), $courseInfo['code']);
1259
        } else {
1260
            $results['status'] = false;
1261
            $results['message'] = get_lang('CourseCreationFailed');
1262
        }
1263
1264
        return $results;
1265
    }
1266
1267
    /**
1268
     * @param $userParam
1269
     *
1270
     * @throws Exception
1271
     *
1272
     * @return array
1273
     */
1274
    public function addUser($userParam)
1275
    {
1276
        $firstName = $userParam['firstname'];
1277
        $lastName = $userParam['lastname'];
1278
        $status = $userParam['status'];
1279
        $email = $userParam['email'];
1280
        $loginName = $userParam['loginname'];
1281
        $password = $userParam['password'];
1282
1283
        $official_code = '';
1284
        $language = '';
1285
        $phone = '';
1286
        $picture_uri = '';
1287
        $auth_source = PLATFORM_AUTH_SOURCE;
1288
        $expiration_date = '';
1289
        $active = 1;
1290
        $hr_dept_id = 0;
1291
        $extra = null;
1292
1293
        $original_user_id_name = $userParam['original_user_id_name'];
1294
        $original_user_id_value = $userParam['original_user_id_value'];
1295
1296
        $extra_list = isset($userParam['extra']) ? $userParam['extra'] : [];
1297
        if (isset($userParam['language'])) {
1298
            $language = $userParam['language'];
1299
        }
1300
        if (isset($userParam['phone'])) {
1301
            $phone = $userParam['phone'];
1302
        }
1303
        if (isset($userParam['expiration_date'])) {
1304
            $expiration_date = $userParam['expiration_date'];
1305
        }
1306
1307
        // Default language.
1308
        if (empty($language)) {
1309
            $language = api_get_setting('platformLanguage');
1310
        }
1311
1312
        // First check wether the login already exists.
1313
        if (!UserManager::is_username_available($loginName)) {
1314
            throw new Exception(get_lang('UserNameNotAvailable'));
1315
        }
1316
1317
        $userId = UserManager::create_user(
1318
            $firstName,
1319
            $lastName,
1320
            $status,
1321
            $email,
1322
            $loginName,
1323
            $password,
1324
            $official_code,
1325
            $language,
1326
            $phone,
1327
            $picture_uri,
1328
            $auth_source,
1329
            $expiration_date,
1330
            $active,
1331
            $hr_dept_id
1332
        );
1333
1334
        if (empty($userId)) {
1335
            throw new Exception(get_lang('UserNotRegistered'));
1336
        }
1337
1338
        if (api_is_multiple_url_enabled()) {
1339
            if (-1 != api_get_current_access_url_id()) {
1340
                UrlManager::add_user_to_url(
1341
                    $userId,
1342
                    api_get_current_access_url_id()
1343
                );
1344
            } else {
1345
                UrlManager::add_user_to_url($userId, 1);
1346
            }
1347
        } else {
1348
            // We add by default the access_url_user table with access_url_id = 1
1349
            UrlManager::add_user_to_url($userId, 1);
1350
        }
1351
1352
        // Save new field label into user_field table.
1353
        UserManager::create_extra_field(
1354
            $original_user_id_name,
1355
            1,
1356
            $original_user_id_name,
1357
            ''
1358
        );
1359
        // Save the external system's id into user_field_value table.
1360
        UserManager::update_extra_field_value(
1361
            $userId,
1362
            $original_user_id_name,
1363
            $original_user_id_value
1364
        );
1365
1366
        if (is_array($extra_list) && count($extra_list) > 0) {
1367
            foreach ($extra_list as $extra) {
1368
                $extra_field_name = $extra['field_name'];
1369
                $extra_field_value = $extra['field_value'];
1370
                // Save new field label into user_field table.
1371
                UserManager::create_extra_field(
1372
                    $extra_field_name,
1373
                    1,
1374
                    $extra_field_name,
1375
                    ''
1376
                );
1377
                // Save the external system's id into user_field_value table.
1378
                UserManager::update_extra_field_value(
1379
                    $userId,
1380
                    $extra_field_name,
1381
                    $extra_field_value
1382
                );
1383
            }
1384
        }
1385
1386
        return [$userId];
1387
    }
1388
1389
    /**
1390
     * Subscribe User to Course.
1391
     *
1392
     * @param array $params
1393
     *
1394
     * @return array
1395
     */
1396
    public function subscribeUserToCourse($params)
1397
    {
1398
        $course_id = $params['course_id'];
1399
        $course_code = $params['course_code'];
1400
        $user_id = $params['user_id'];
1401
        if (!$course_id && !$course_code) {
1402
            return [false];
1403
        }
1404
        if (!$course_code) {
1405
            $course_code = CourseManager::get_course_code_from_course_id($course_id);
1406
        }
1407
        if (CourseManager::subscribeUser($user_id, $course_code)) {
1408
            return [true];
1409
        } else {
1410
            return [false];
1411
        }
1412
1413
        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...
1414
    }
1415
1416
    public function deleteUserMessage($messageId, $messageType)
1417
    {
1418
        if ("sent" === $messageType) {
1419
            return MessageManager::delete_message_by_user_sender($this->user->getId(), $messageId);
1420
        } else {
1421
            return MessageManager::delete_message_by_user_receiver($this->user->getId(), $messageId);
1422
        }
1423
    }
1424
1425
    public function setMessageRead($messageId)
1426
    {
1427
        MessageManager::update_message($this->user->getId(), $messageId);
1428
    }
1429
1430
    /**
1431
     * Add Campus Virtual.
1432
     *
1433
     * @param array Params Campus
1434
     *
1435
     * @return array
1436
     */
1437
    public function createCampusURL($params)
1438
    {
1439
        $urlCampus = Security::remove_XSS($params['url']);
1440
        $description = Security::remove_XSS($params['description']);
1441
1442
        $active = isset($params['active']) ? intval($params['active']) : 0;
1443
        $num = UrlManager::url_exist($urlCampus);
1444
        if (0 == $num) {
1445
            // checking url
1446
            if ('/' == substr($urlCampus, strlen($urlCampus) - 1, strlen($urlCampus))) {
1447
                $idCampus = UrlManager::add($urlCampus, $description, $active, true);
1448
            } else {
1449
                //create
1450
                $idCampus = UrlManager::add($urlCampus.'/', $description, $active, true);
1451
            }
1452
1453
            return [
1454
                'status' => true,
1455
                'id_campus' => $idCampus,
1456
            ];
1457
        }
1458
1459
        return [
1460
            'status' => false,
1461
            'id_campus' => 0,
1462
        ];
1463
    }
1464
1465
    /**
1466
     * Edit Campus Virtual.
1467
     *
1468
     * @param array Params Campus
1469
     *
1470
     * @return array
1471
     */
1472
    public function editCampusURL($params)
1473
    {
1474
        $urlCampus = Security::remove_XSS($params['url']);
1475
        $description = Security::remove_XSS($params['description']);
1476
1477
        $active = isset($params['active']) ? intval($params['active']) : 0;
1478
        $url_id = isset($params['id']) ? intval($params['id']) : 0;
1479
1480
        if (!empty($url_id)) {
1481
            //we can't change the status of the url with id=1
1482
            if (1 == $url_id) {
1483
                $active = 1;
1484
            }
1485
            //checking url
1486
            if ('/' == substr($urlCampus, strlen($urlCampus) - 1, strlen($urlCampus))) {
1487
                UrlManager::update($url_id, $urlCampus, $description, $active);
1488
            } else {
1489
                UrlManager::update($url_id, $urlCampus.'/', $description, $active);
1490
            }
1491
1492
            return [true];
1493
        }
1494
1495
        return [false];
1496
    }
1497
1498
    /**
1499
     * Delete Campus Virtual.
1500
     *
1501
     * @param array Params Campus
1502
     *
1503
     * @return array
1504
     */
1505
    public function deleteCampusURL($params)
1506
    {
1507
        $url_id = isset($params['id']) ? intval($params['id']) : 0;
1508
1509
        $result = UrlManager::delete($url_id);
1510
        if ($result) {
1511
            return [
1512
                'status' => true,
1513
                'message' => get_lang('URLDeleted'),
1514
            ];
1515
        } else {
1516
            return [
1517
                'status' => false,
1518
                'message' => get_lang('Error'),
1519
            ];
1520
        }
1521
    }
1522
1523
    /**
1524
     * @throws Exception
1525
     *
1526
     * @return array
1527
     */
1528
    public function addCoursesSession(array $params)
1529
    {
1530
        $sessionId = $params['id_session'];
1531
        $courseList = $params['list_courses'];
1532
        $importAssignments = isset($params['import_assignments']) ? 1 === (int) $params['import_assignments'] : false;
1533
1534
        $result = SessionManager::add_courses_to_session(
1535
            $sessionId,
1536
            $courseList,
1537
            true,
1538
            false,
1539
            false,
1540
            $importAssignments
1541
        );
1542
1543
        if ($result) {
1544
            return [
1545
                'status' => $result,
1546
                'message' => get_lang('Updated'),
1547
            ];
1548
        }
1549
1550
        return [
1551
                'status' => $result,
1552
                'message' => get_lang('ErrorOccurred'),
1553
            ];
1554
    }
1555
1556
    /**
1557
     * @return array
1558
     */
1559
    public function addUsersSession(array $params)
1560
    {
1561
        $sessionId = $params['id_session'];
1562
        $userList = $params['list_users'];
1563
1564
        if (!is_array($userList)) {
1565
            $userList = [];
1566
        }
1567
1568
        SessionManager::subscribeUsersToSession(
1569
            $sessionId,
1570
            $userList,
1571
            null,
1572
            false
1573
        );
1574
1575
        return [
1576
            'status' => true,
1577
            'message' => get_lang('UsersAdded'),
1578
        ];
1579
    }
1580
1581
    /**
1582
     * Creates a session from a model session.
1583
     *
1584
     * @param $modelSessionId
1585
     * @param $sessionName
1586
     * @param $startDate
1587
     * @param $endDate
1588
     *
1589
     * @throws Exception
1590
     *
1591
     * @return int, the id of the new session
1592
     */
1593
    public function createSessionFromModel($modelSessionId, $sessionName, $startDate, $endDate, array $extraFields = [])
1594
    {
1595
        if (empty($modelSessionId) || empty($sessionName) || empty($startDate) || empty($endDate)) {
1596
            throw new Exception(get_lang('NoData'));
1597
        }
1598
1599
        if (!SessionManager::isValidId($modelSessionId)) {
1600
            throw new Exception(get_lang('ModelSessionDoesNotExist'));
1601
        }
1602
1603
        $modelSession = SessionManager::fetch($modelSessionId);
1604
1605
        $modelSession['accessUrlId'] = 1;
1606
        if (api_is_multiple_url_enabled()) {
1607
            if (-1 != api_get_current_access_url_id()) {
1608
                $modelSession['accessUrlId'] = api_get_current_access_url_id();
1609
            }
1610
        }
1611
1612
        $newSessionId = SessionManager::create_session(
1613
            $sessionName,
1614
            $startDate,
1615
            $endDate,
1616
            $startDate,
1617
            $endDate,
1618
            $startDate,
1619
            $endDate,
1620
            $modelSession['id_coach'],
1621
            $modelSession['session_category_id'],
1622
            $modelSession['visibility'],
1623
            false,
1624
            $modelSession['duration'],
1625
            $modelSession['description'],
1626
            $modelSession['show_description'],
1627
            $extraFields,
1628
            $modelSession['session_admin_id'],
1629
            $modelSession['send_subscription_notification'],
1630
            $modelSession['accessUrlId']
1631
        );
1632
1633
        if (empty($newSessionId)) {
1634
            throw new Exception(get_lang('SessionNotRegistered'));
1635
        }
1636
1637
        if (is_string($newSessionId)) {
1638
            throw new Exception($newSessionId);
1639
        }
1640
1641
        $promotionId = $modelSession['promotion_id'];
1642
        if ($promotionId) {
1643
            $sessionList = array_keys(SessionManager::get_all_sessions_by_promotion($promotionId));
1644
            $sessionList[] = $newSessionId;
1645
            SessionManager::subscribe_sessions_to_promotion($modelSession['promotion_id'], $sessionList);
1646
        }
1647
1648
        $modelExtraFields = [];
1649
        $fields = SessionManager::getFilteredExtraFields($modelSessionId);
1650
        if (is_array($fields) and !empty($fields)) {
1651
            foreach ($fields as $field) {
1652
                $modelExtraFields[$field['variable']] = $field['value'];
1653
            }
1654
        }
1655
        $allExtraFields = array_merge($modelExtraFields, $extraFields);
1656
        foreach ($allExtraFields as $name => $value) {
1657
            // SessionManager::update_session_extra_field_value returns false when no row is changed,
1658
            // which can happen since extra field values are initialized by SessionManager::create_session
1659
            // therefore we do not throw an exception when false is returned
1660
            SessionManager::update_session_extra_field_value($newSessionId, $name, $value);
1661
        }
1662
1663
        $courseList = array_keys(SessionManager::get_course_list_by_session_id($modelSessionId));
1664
        if (is_array($courseList)
1665
            && !empty($courseList)
1666
            && !SessionManager::add_courses_to_session($newSessionId, $courseList)) {
1667
            throw new Exception(get_lang('CoursesNotAddedToSession'));
1668
        }
1669
1670
        if (api_is_multiple_url_enabled()) {
1671
            if (-1 != api_get_current_access_url_id()) {
1672
                UrlManager::add_session_to_url(
1673
                    $newSessionId,
1674
                    api_get_current_access_url_id()
1675
                );
1676
            } else {
1677
                UrlManager::add_session_to_url($newSessionId, 1);
1678
            }
1679
        } else {
1680
            UrlManager::add_session_to_url($newSessionId, 1);
1681
        }
1682
1683
        return $newSessionId;
1684
    }
1685
1686
    /**
1687
     * subscribes a user to a session.
1688
     *
1689
     * @param int    $sessionId the session id
1690
     * @param string $loginName the user's login name
1691
     *
1692
     * @throws Exception
1693
     *
1694
     * @return boolean, whether it worked
1695
     */
1696
    public function subscribeUserToSessionFromUsername($sessionId, $loginName)
1697
    {
1698
        if (!SessionManager::isValidId($sessionId)) {
1699
            throw new Exception(get_lang('SessionNotFound'));
1700
        }
1701
1702
        $userId = UserManager::get_user_id_from_username($loginName);
1703
        if (false === $userId) {
1704
            throw new Exception(get_lang('UserNotFound'));
1705
        }
1706
1707
        $subscribed = SessionManager::subscribeUsersToSession(
1708
            $sessionId,
1709
            [$userId],
1710
            SESSION_VISIBLE_READ_ONLY,
1711
            false
1712
        );
1713
        if (!$subscribed) {
1714
            throw new Exception(get_lang('UserNotSubscribed'));
1715
        }
1716
1717
        return true;
1718
    }
1719
1720
    /**
1721
     * finds the session which has a specific value in a specific extra field.
1722
     *
1723
     * @param $fieldName
1724
     * @param $fieldValue
1725
     *
1726
     * @throws Exception when no session matched or more than one session matched
1727
     *
1728
     * @return int, the matching session id
1729
     */
1730
    public function getSessionFromExtraField($fieldName, $fieldValue)
1731
    {
1732
        // find sessions that that have value in field
1733
        $valueModel = new ExtraFieldValue('session');
1734
        $sessionIdList = $valueModel->get_item_id_from_field_variable_and_field_value(
1735
            $fieldName,
1736
            $fieldValue,
1737
            false,
1738
            false,
1739
            true
1740
        );
1741
1742
        // throw if none found
1743
        if (empty($sessionIdList)) {
1744
            throw new Exception(get_lang('NoSessionMatched'));
1745
        }
1746
1747
        // throw if more than one found
1748
        if (count($sessionIdList) > 1) {
1749
            throw new Exception(get_lang('MoreThanOneSessionMatched'));
1750
        }
1751
1752
        // return sessionId
1753
        return intval($sessionIdList[0]['item_id']);
1754
    }
1755
1756
    /**
1757
     * updates a user identified by its login name.
1758
     *
1759
     * @param array $parameters
1760
     *
1761
     * @throws Exception on failure
1762
     *
1763
     * @return boolean, true on success
1764
     */
1765
    public function updateUserFromUserName($parameters)
1766
    {
1767
        // find user
1768
        $userId = null;
1769
        if (!is_array($parameters) || empty($parameters)) {
1770
            throw new Exception('NoData');
1771
        }
1772
        foreach ($parameters as $name => $value) {
1773
            if ('loginname' === strtolower($name)) {
1774
                $userId = UserManager::get_user_id_from_username($value);
1775
                if (false === $userId) {
1776
                    throw new Exception(get_lang('UserNotFound'));
1777
                }
1778
                break;
1779
            }
1780
        }
1781
        if (is_null($userId)) {
1782
            throw new Exception(get_lang('NoData'));
1783
        }
1784
        /** @var User $user */
1785
        $user = UserManager::getRepository()->find($userId);
1786
        if (empty($user)) {
1787
            throw new Exception(get_lang('CouldNotLoadUser'));
1788
        }
1789
1790
        // tell the world we are about to update a user
1791
        $hook = HookUpdateUser::create();
1792
        if (!empty($hook)) {
1793
            $hook->notifyUpdateUser(HOOK_EVENT_TYPE_PRE);
1794
        }
1795
1796
        // apply submitted modifications
1797
        foreach ($parameters as $name => $value) {
1798
            switch (strtolower($name)) {
1799
                case 'email':
1800
                    $user->setEmail($value);
1801
                    break;
1802
                case 'enabled':
1803
                    $user->setEnabled($value);
1804
                    break;
1805
                case 'lastname':
1806
                    $user->setLastname($value);
1807
                    break;
1808
                case 'firstname':
1809
                    $user->setFirstname($value);
1810
                    break;
1811
                case 'phone':
1812
                    $user->setPhone($value);
1813
                    break;
1814
                case 'address':
1815
                    $user->setAddress($value);
1816
                    break;
1817
                case 'roles':
1818
                    $user->setRoles($value);
1819
                    break;
1820
                case 'profile_completed':
1821
                    $user->setProfileCompleted($value);
1822
                    break;
1823
                case 'auth_source':
1824
                    $user->setAuthSource($value);
1825
                    break;
1826
                case 'status':
1827
                    $user->setStatus($value);
1828
                    break;
1829
                case 'official_code':
1830
                    $user->setOfficialCode($value);
1831
                    break;
1832
                case 'picture_uri':
1833
                    $user->setPictureUri($value);
1834
                    break;
1835
                case 'creator_id':
1836
                    $user->setCreatorId($value);
1837
                    break;
1838
                case 'competences':
1839
                    $user->setCompetences($value);
1840
                    break;
1841
                case 'diplomas':
1842
                    $user->setDiplomas($value);
1843
                    break;
1844
                case 'openarea':
1845
                    $user->setOpenArea($value);
1846
                    break;
1847
                case 'teach':
1848
                    $user->setTeach($value);
1849
                    break;
1850
                case 'productions':
1851
                    $user->setProductions($value);
1852
                    break;
1853
                case 'language':
1854
                    $languages = api_get_languages();
1855
                    if (!in_array($value, $languages['folder'])) {
1856
                        throw new Exception(get_lang('LanguageUnavailable'));
1857
                    }
1858
                    $user->setLanguage($value);
1859
                    break;
1860
                case 'registration_date':
1861
                    $user->setRegistrationDate($value);
1862
                    break;
1863
                case 'expiration_date':
1864
                    $user->setExpirationDate(
1865
                        new DateTime(
1866
                            api_get_utc_datetime($value),
1867
                            new DateTimeZone('UTC')
1868
                        )
1869
                    );
1870
                    break;
1871
                case 'active':
1872
                    // see UserManager::update_user() usermanager.lib.php:1205
1873
                    if ($user->getActive() != $value) {
1874
                        $user->setActive($value);
1875
                        Event::addEvent($value ? LOG_USER_ENABLE : LOG_USER_DISABLE, LOG_USER_ID, $userId);
1876
                    }
1877
                    break;
1878
                case 'openid':
1879
                    $user->setOpenId($value);
1880
                    break;
1881
                case 'theme':
1882
                    $user->setTheme($value);
1883
                    break;
1884
                case 'hr_dept_id':
1885
                    $user->setHrDeptId($value);
1886
                    break;
1887
                case 'extra':
1888
                    if (is_array($value)) {
1889
                        if (count($value) > 0) {
1890
                            if (is_array($value[0])) {
1891
                                foreach ($value as $field) {
1892
                                    $fieldName = $field['field_name'];
1893
                                    $fieldValue = $field['field_value'];
1894
                                    if (!isset($fieldName) || !isset($fieldValue) ||
1895
                                        !UserManager::update_extra_field_value($userId, $fieldName, $fieldValue)) {
1896
                                        throw new Exception(get_lang('CouldNotUpdateExtraFieldValue').': '.print_r($field, true));
1897
                                    }
1898
                                }
1899
                            } else {
1900
                                foreach ($value as $fieldName => $fieldValue) {
1901
                                    if (!UserManager::update_extra_field_value($userId, $fieldName, $fieldValue)) {
1902
                                        throw new Exception(get_lang('CouldNotUpdateExtraFieldValue').': '.$fieldName);
1903
                                    }
1904
                                }
1905
                            }
1906
                        }
1907
                    }
1908
                    break;
1909
                case 'username':
1910
                case 'api_key':
1911
                case 'action':
1912
                case 'loginname':
1913
                    break;
1914
                case 'email_canonical':
1915
                case 'locked':
1916
                case 'expired':
1917
                case 'credentials_expired':
1918
                case 'credentials_expire_at':
1919
                case 'expires_at':
1920
                case 'salt':
1921
                case 'last_login':
1922
                case 'created_at':
1923
                case 'updated_at':
1924
                case 'confirmation_token':
1925
                case 'password_requested_at':
1926
                case 'password': // see UserManager::update_user usermanager.lib.php:1182
1927
                case 'username_canonical':
1928
                default:
1929
                    throw new Exception(get_lang('UnsupportedUpdate')." '$name'");
1930
            }
1931
        }
1932
1933
        // save modifications
1934
        UserManager::getManager()->updateUser($user, true);
1935
1936
        // tell the world we just updated this user
1937
        if (!empty($hook)) {
1938
            $hook->setEventData(['user' => $user]);
1939
            $hook->notifyUpdateUser(HOOK_EVENT_TYPE_POST);
1940
        }
1941
1942
        // invalidate cache for this user
1943
        $cacheAvailable = api_get_configuration_value('apc');
1944
        if (true === $cacheAvailable) {
1945
            $apcVar = api_get_configuration_value('apc_prefix').'userinfo_'.$userId;
1946
            if (apcu_exists($apcVar)) {
1947
                apcu_delete($apcVar);
1948
            }
1949
        }
1950
1951
        return true;
1952
    }
1953
1954
    /**
1955
     * Returns whether a user login name exists.
1956
     *
1957
     * @param string $loginname the user login name
1958
     *
1959
     * @return bool whether the user login name exists
1960
     */
1961
    public function usernameExist($loginname)
1962
    {
1963
        return false !== api_get_user_info_from_username($loginname);
1964
    }
1965
1966
    /**
1967
     * This service roughly matches what the call to MDL's API core_course_get_contents function returns.
1968
     *
1969
     * @return array
1970
     */
1971
    public function getCourseQuizMdlCompat()
1972
    {
1973
        $userId = $this->user->getId();
1974
        $courseId = $this->course->getId();
1975
        $sessionId = $this->session ? $this->session->getId() : 0;
1976
1977
        $toolVisibility = CourseHome::getToolVisibility(TOOL_QUIZ, $courseId, $sessionId);
1978
1979
        $json = [
1980
            "id" => $this->course->getId(),
1981
            "name" => get_lang('Exercises'),
1982
            "visible" => (int) $toolVisibility,
1983
            "summary" => '',
1984
            "summaryformat" => 1,
1985
            "section" => 1,
1986
            "hiddenbynumsections" => 0,
1987
            "uservisible" => $toolVisibility,
1988
            "modules" => [],
1989
        ];
1990
1991
        $quizIcon = Display::return_icon('quiz.png', '', [], ICON_SIZE_SMALL, false, true);
1992
1993
        $json['modules'] = array_map(
1994
            function (array $exercise) use ($quizIcon) {
1995
                return [
1996
                    'id' => $exercise['id'],
1997
                    'url' => $exercise['url'],
1998
                    'name' => $exercise['name'],
1999
                    'instance' => 1,
2000
                    'visible' => 1,
2001
                    'uservisible' => true,
2002
                    'visibleoncoursepage' => 0,
2003
                    'modicon' => $quizIcon,
2004
                    'modname' => 'quiz',
2005
                    'modplural' => get_lang('Exercises'),
2006
                    'availability' => null,
2007
                    'indent' => 0,
2008
                    'onclick' => '',
2009
                    'afterlink' => null,
2010
                    'customdata' => "",
2011
                    'noviewlink' => false,
2012
                    'completion' => (int) ($exercise[1] > 0),
2013
                ];
2014
            },
2015
            Exercise::exerciseGrid(0, '', $userId, $courseId, $sessionId, true)
2016
        );
2017
2018
        return [$json];
2019
    }
2020
2021
    /**
2022
     * @param array $additionalParams Optional
2023
     *
2024
     * @return string
2025
     */
2026
    private function encodeParams(array $additionalParams = [])
2027
    {
2028
        $params = array_merge(
2029
            $additionalParams,
2030
            [
2031
                'api_key' => $this->apiKey,
2032
                'username' => $this->user->getUsername(),
2033
            ]
2034
        );
2035
2036
        return json_encode($params);
2037
    }
2038
}
2039