Passed
Push — 1.11.x ( b1fec8...36e938 )
by Julito
10:30 queued 22s
created

Rest::getCourseLpProgress()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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