Passed
Push — 1.11.x ( 76923f...fc4f1e )
by Julito
10:27
created

Rest::getCourseNotebooks()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 22
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

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