Passed
Push — 1.11.x ( d61c12...fab5d2 )
by Angel Fernando Quiroz
13:28
created

Rest::getUsersCampus()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 19
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 13
nop 1
dl 0
loc 19
rs 9.8333
c 0
b 0
f 0
nc 2
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 SAVE_GCM_ID = 'gcm_id';
23
    const LOGOUT = 'logout';
24
25
    const GET_USER_MESSAGES = 'user_messages';
26
    const GET_USER_MESSAGES_RECEIVED = 'user_messages_received';
27
    const DELETE_USER_MESSAGE = 'delete_user_message';
28
    const GET_USER_MESSAGES_SENT = 'user_messages_sent';
29
    const GET_COUNT_NEW_MESSAGES = 'get_count_new_messages';
30
    const SET_MESSAGE_READ = 'set_message_read';
31
    const POST_USER_MESSAGE_READ = 'user_message_read';
32
    const POST_USER_MESSAGE_UNREAD = 'user_message_unread';
33
    const SAVE_USER_MESSAGE = 'save_user_message';
34
    const GET_MESSAGE_USERS = 'message_users';
35
    const VIEW_MESSAGE = 'view_message';
36
37
    const GET_USER_COURSES = 'user_courses';
38
    const GET_USER_SESSIONS = 'user_sessions';
39
40
    const VIEW_PROFILE = 'view_user_profile';
41
    const GET_PROFILE = 'user_profile';
42
43
    const VIEW_COURSE_HOME = 'view_course_home';
44
    const GET_COURSE_INFO = 'course_info';
45
    const GET_COURSE_DESCRIPTIONS = 'course_descriptions';
46
    const GET_COURSE_DOCUMENTS = 'course_documents';
47
    const GET_COURSE_ANNOUNCEMENTS = 'course_announcements';
48
    const GET_COURSE_ANNOUNCEMENT = 'course_announcement';
49
    const GET_COURSE_AGENDA = 'course_agenda';
50
    const GET_COURSE_NOTEBOOKS = 'course_notebooks';
51
    const GET_COURSE_FORUM_CATEGORIES = 'course_forumcategories';
52
    const GET_COURSE_FORUM = 'course_forum';
53
    const GET_COURSE_FORUM_THREAD = 'course_forumthread';
54
    const GET_COURSE_LEARNPATHS = 'course_learnpaths';
55
    const GET_COURSE_LEARNPATH = 'course_learnpath';
56
    const GET_COURSE_LP_PROGRESS = 'course_lp_progress';
57
    const GET_COURSE_LINKS = 'course_links';
58
    const GET_COURSE_WORKS = 'course_works';
59
60
    const SAVE_COURSE_NOTEBOOK = 'save_course_notebook';
61
62
    const SAVE_FORUM_POST = 'save_forum_post';
63
    const SAVE_FORUM_THREAD = 'save_forum_thread';
64
    const SET_THREAD_NOTIFY = 'set_thread_notify';
65
    const DOWNLOAD_FORUM_ATTACHMENT = 'download_forum_attachment';
66
67
    const GET_WORK_LIST = 'get_work_list';
68
    const GET_WORK_STUDENTS_WITHOUT_PUBLICATIONS = 'get_work_students_without_publications';
69
    const GET_WORK_USERS = 'get_work_users';
70
    const GET_WORK_STUDENT_LIST = 'get_work_student_list';
71
    const PUT_WORK_STUDENT_ITEM_VISIBILITY = 'put_course_work_visibility';
72
    const DELETE_WORK_STUDENT_ITEM = 'delete_work_student_item';
73
    const DELETE_WORK_CORRECTIONS = 'delete_work_corrections';
74
    const DOWNLOAD_WORK_FOLDER = 'download_work_folder';
75
    const DOWNLOAD_WORK_COMMENT_ATTACHMENT = 'download_work_comment_attachment';
76
    const DOWNLOAD_WORK = 'download_work';
77
78
    const VIEW_DOCUMENT_IN_FRAME = 'view_document_in_frame';
79
80
    const VIEW_QUIZ_TOOL = 'view_quiz_tool';
81
82
    const VIEW_SURVEY_TOOL = 'view_survey_tool';
83
84
    const CREATE_CAMPUS = 'add_campus';
85
    const EDIT_CAMPUS = 'edit_campus';
86
    const DELETE_CAMPUS = 'delete_campus';
87
88
    const GET_USERS = 'get_users';
89
    const USERNAME_EXIST = 'username_exist';
90
    const SAVE_USER = 'save_user';
91
    const SAVE_USER_GET_APIKEY = 'save_user_get_apikey';
92
    const SAVE_USER_JSON = 'save_user_json';
93
    const UPDATE_USER_FROM_USERNAME = 'update_user_from_username';
94
    const UPDATE_USER_APIKEY = 'update_user_apikey';
95
    const DELETE_USER = 'delete_user';
96
97
    const GET_COURSES = 'get_courses';
98
    const GET_COURSES_FROM_EXTRA_FIELD = 'get_courses_from_extra_field';
99
    const SAVE_COURSE = 'save_course';
100
    const DELETE_COURSE = 'delete_course';
101
102
    const GET_SESSION_FROM_EXTRA_FIELD = 'get_session_from_extra_field';
103
    const SAVE_SESSION = 'save_session';
104
    const CREATE_SESSION_FROM_MODEL = 'create_session_from_model';
105
    const UPDATE_SESSION = 'update_session';
106
107
    const SUBSCRIBE_USER_TO_COURSE = 'subscribe_user_to_course';
108
    const SUBSCRIBE_USER_TO_COURSE_PASSWORD = 'subscribe_user_to_course_password';
109
    const UNSUBSCRIBE_USER_FROM_COURSE = 'unsubscribe_user_from_course';
110
    const GET_USERS_SUBSCRIBED_TO_COURSE = 'get_users_subscribed_to_course';
111
112
    const ADD_COURSES_SESSION = 'add_courses_session';
113
    const ADD_USERS_SESSION = 'add_users_session';
114
    const SUBSCRIBE_USER_TO_SESSION_FROM_USERNAME = 'subscribe_user_to_session_from_username';
115
116
    const GET_COURSE_QUIZ_MDL_COMPAT = 'get_course_quiz_mdl_compat';
117
118
    const UPDATE_USER_PAUSE_TRAINING = 'update_user_pause_training';
119
120
    const CHECK_CONDITIONAL_LOGIN = 'check_conditional_login';
121
    const GET_LEGAL_CONDITIONS = 'get_legal_conditions';
122
    const UPDATE_CONDITION_ACCEPTED = 'update_condition_accepted';
123
124
    /**
125
     * @var Session
126
     */
127
    private $session;
128
129
    /**
130
     * @var Course
131
     */
132
    private $course;
133
134
    /**
135
     * Rest constructor.
136
     *
137
     * @param string $username
138
     * @param string $apiKey
139
     */
140
    public function __construct($username, $apiKey)
141
    {
142
        parent::__construct($username, $apiKey);
143
    }
144
145
    /**
146
     * @param string $username
147
     * @param string $apiKeyToValidate
148
     *
149
     * @throws Exception
150
     *
151
     * @return Rest
152
     */
153
    public static function validate($username, $apiKeyToValidate)
154
    {
155
        $apiKey = self::findUserApiKey($username, self::SERVICE_NAME);
156
157
        if ($apiKey != $apiKeyToValidate) {
158
            throw new Exception(get_lang('InvalidApiKey'));
159
        }
160
161
        return new self($username, $apiKey);
162
    }
163
164
    /**
165
     * Create the gcm_registration_id extra field for users.
166
     */
167
    public static function init()
168
    {
169
        $extraField = new ExtraField('user');
170
        $fieldInfo = $extraField->get_handler_field_info_by_field_variable(self::EXTRA_FIELD_GCM_REGISTRATION);
171
172
        if (empty($fieldInfo)) {
173
            $extraField->save(
174
                [
175
                    'variable' => self::EXTRA_FIELD_GCM_REGISTRATION,
176
                    'field_type' => ExtraField::FIELD_TYPE_TEXT,
177
                    'display_text' => self::EXTRA_FIELD_GCM_REGISTRATION,
178
                ]
179
            );
180
        }
181
    }
182
183
    /**
184
     * @param string $encoded
185
     *
186
     * @return array
187
     */
188
    public static function decodeParams($encoded)
189
    {
190
        return json_decode($encoded);
191
    }
192
193
    /**
194
     * Set the current course.
195
     *
196
     * @param int $id
197
     *
198
     * @throws Exception
199
     */
200
    public function setCourse($id)
201
    {
202
        global $_course;
203
204
        if (!$id) {
205
            $this->course = null;
206
207
            ChamiloSession::erase('_real_cid');
208
            ChamiloSession::erase('_cid');
209
            ChamiloSession::erase('_course');
210
211
            return;
212
        }
213
214
        $em = Database::getManager();
215
        /** @var Course $course */
216
        $course = $em->find('ChamiloCoreBundle:Course', $id);
217
218
        if (!$course) {
0 ignored issues
show
introduced by
$course is of type Chamilo\CoreBundle\Entity\Course, thus it always evaluated to true.
Loading history...
219
            throw new Exception(get_lang('NoCourse'));
220
        }
221
222
        $this->course = $course;
223
224
        $courseInfo = api_get_course_info($course->getCode());
225
        $_course = $courseInfo;
226
227
        ChamiloSession::write('_real_cid', $course->getId());
228
        ChamiloSession::write('_cid', $course->getCode());
229
        ChamiloSession::write('_course', $courseInfo);
230
    }
231
232
    /**
233
     * Set the current session.
234
     *
235
     * @param int $id
236
     *
237
     * @throws Exception
238
     */
239
    public function setSession($id)
240
    {
241
        if (!$id) {
242
            $this->session = null;
243
244
            ChamiloSession::erase('session_name');
245
            ChamiloSession::erase('id_session');
246
247
            return;
248
        }
249
250
        $em = Database::getManager();
251
        /** @var Session $session */
252
        $session = $em->find('ChamiloCoreBundle:Session', $id);
253
254
        if (!$session) {
0 ignored issues
show
introduced by
$session is of type Chamilo\CoreBundle\Entity\Session, thus it always evaluated to true.
Loading history...
255
            throw new Exception(get_lang('NoSession'));
256
        }
257
258
        $this->session = $session;
259
260
        ChamiloSession::write('session_name', $session->getName());
261
        ChamiloSession::write('id_session', $session->getId());
262
    }
263
264
    /**
265
     * @param string $registrationId
266
     *
267
     * @return bool
268
     */
269
    public function setGcmId($registrationId)
270
    {
271
        $registrationId = Security::remove_XSS($registrationId);
272
        $extraFieldValue = new ExtraFieldValue('user');
273
274
        return $extraFieldValue->save(
275
            [
276
                'variable' => self::EXTRA_FIELD_GCM_REGISTRATION,
277
                'value' => $registrationId,
278
                'item_id' => $this->user->getId(),
279
            ]
280
        );
281
    }
282
283
    /**
284
     * @param int $lastMessageId
285
     *
286
     * @return array
287
     */
288
    public function getUserMessages($lastMessageId = 0)
289
    {
290
        $lastMessages = MessageManager::getMessagesFromLastReceivedMessage($this->user->getId(), $lastMessageId);
291
        $messages = [];
292
293
        foreach ($lastMessages as $message) {
294
            $hasAttachments = MessageManager::hasAttachments($message['id']);
295
296
            $messages[] = [
297
                'id' => $message['id'],
298
                'title' => $message['title'],
299
                'sender' => [
300
                    'id' => $message['user_id'],
301
                    'lastname' => $message['lastname'],
302
                    'firstname' => $message['firstname'],
303
                    'completeName' => api_get_person_name($message['firstname'], $message['lastname']),
304
                ],
305
                'sendDate' => $message['send_date'],
306
                'content' => $message['content'],
307
                'hasAttachments' => $hasAttachments,
308
                'url' => api_get_path(WEB_CODE_PATH).'messages/view_message.php?'
309
                    .http_build_query(['type' => 1, 'id' => $message['id']]),
310
            ];
311
        }
312
313
        return $messages;
314
    }
315
316
    /**
317
     * @return array
318
     */
319
    public function getUserReceivedMessages()
320
    {
321
        $lastMessages = MessageManager::getReceivedMessages($this->user->getId(), 0);
322
        $messages = [];
323
324
        $webPath = api_get_path(WEB_PATH);
325
326
        foreach ($lastMessages as $message) {
327
            $hasAttachments = MessageManager::hasAttachments($message['id']);
328
            $attachmentList = [];
329
            if ($hasAttachments) {
330
                $attachmentList = MessageManager::getAttachmentList($message['id']);
331
            }
332
            $messages[] = [
333
                'id' => $message['id'],
334
                'title' => $message['title'],
335
                'msgStatus' => $message['msg_status'],
336
                'sender' => [
337
                    'id' => $message['user_id'],
338
                    'lastname' => $message['lastname'],
339
                    'firstname' => $message['firstname'],
340
                    'completeName' => api_get_person_name($message['firstname'], $message['lastname']),
341
                    'pictureUri' => $message['pictureUri'],
342
                ],
343
                'sendDate' => $message['send_date'],
344
                'content' => str_replace('src="/"', $webPath, $message['content']),
345
                'hasAttachments' => $hasAttachments,
346
                'attachmentList' => $attachmentList,
347
                'url' => '',
348
            ];
349
        }
350
351
        return $messages;
352
    }
353
354
    /**
355
     * @return array
356
     */
357
    public function getUserSentMessages()
358
    {
359
        $lastMessages = MessageManager::getSentMessages($this->user->getId(), 0);
360
        $messages = [];
361
362
        foreach ($lastMessages as $message) {
363
            $hasAttachments = MessageManager::hasAttachments($message['id']);
364
365
            $messages[] = [
366
                'id' => $message['id'],
367
                'title' => $message['title'],
368
                'msgStatus' => $message['msg_status'],
369
                'receiver' => [
370
                    'id' => $message['user_id'],
371
                    'lastname' => $message['lastname'],
372
                    'firstname' => $message['firstname'],
373
                    'completeName' => api_get_person_name($message['firstname'], $message['lastname']),
374
                    'pictureUri' => $message['pictureUri'],
375
                ],
376
                'sendDate' => $message['send_date'],
377
                'content' => $message['content'],
378
                'hasAttachments' => $hasAttachments,
379
                'url' => '',
380
            ];
381
        }
382
383
        return $messages;
384
    }
385
386
    /**
387
     * Get the user courses.
388
     */
389
    public function getUserCourses($userId = 0): array
390
    {
391
        if (empty($userId)) {
392
            $userId = $this->user->getId();
393
        }
394
395
        Event::courseLogout(
396
            [
397
                'uid' => $userId,
398
                'cid' => api_get_course_id(),
399
                'sid' => api_get_session_id(),
400
            ]
401
        );
402
403
        $courses = CourseManager::get_courses_list_by_user_id($userId);
404
        $data = [];
405
406
        $webCodePath = api_get_path(WEB_CODE_PATH).'webservices/api/v2.php?';
407
408
        foreach ($courses as $courseInfo) {
409
            /** @var Course $course */
410
            $course = Database::getManager()->find('ChamiloCoreBundle:Course', $courseInfo['real_id']);
411
            $teachers = CourseManager::getTeacherListFromCourseCodeToString($course->getCode());
412
            $picturePath = CourseManager::getPicturePath($course, true)
413
                ?: Display::return_icon('session_default.png', null, null, null, null, true);
414
415
            $data[] = [
416
                'id' => $course->getId(),
417
                'title' => $course->getTitle(),
418
                'code' => $course->getCode(),
419
                'directory' => $course->getDirectory(),
420
                'urlPicture' => $picturePath,
421
                'teachers' => $teachers,
422
                'isSpecial' => !empty($courseInfo['special_course']),
423
                'url' => $webCodePath.http_build_query(
424
                    [
425
                        'action' => self::VIEW_COURSE_HOME,
426
                        'api_key' => $this->apiKey,
427
                        'username' => $this->user->getUsername(),
428
                        'course' => $course->getId()
429
                    ]
430
                ),
431
            ];
432
        }
433
434
        return $data;
435
    }
436
437
    /**
438
     * @throws Exception
439
     *
440
     * @return array
441
     */
442
    public function getCourseInfo()
443
    {
444
        $teachers = CourseManager::getTeacherListFromCourseCodeToString($this->course->getCode());
445
        $tools = CourseHome::get_tools_category(
446
            TOOL_STUDENT_VIEW,
447
            $this->course->getId(),
448
            $this->session ? $this->session->getId() : 0
449
        );
450
451
        return [
452
            'id' => $this->course->getId(),
453
            'title' => $this->course->getTitle(),
454
            'code' => $this->course->getCode(),
455
            'directory' => $this->course->getDirectory(),
456
            'urlPicture' => CourseManager::getPicturePath($this->course, true),
457
            'teachers' => $teachers,
458
            'tools' => array_map(
459
                function ($tool) {
460
                    return ['type' => $tool['name']];
461
                },
462
                $tools
463
            ),
464
        ];
465
    }
466
467
    /**
468
     * Get the course descriptions.
469
     *
470
     * @throws Exception
471
     *
472
     * @return array
473
     */
474
    public function getCourseDescriptions()
475
    {
476
        Event::event_access_tool(TOOL_COURSE_DESCRIPTION);
477
478
        $descriptions = CourseDescription::get_descriptions($this->course->getId());
479
        $results = [];
480
481
        $webPath = api_get_path(WEB_PATH);
482
483
        /** @var CourseDescription $description */
484
        foreach ($descriptions as $description) {
485
            $results[] = [
486
                'id' => $description->get_description_type(),
487
                'title' => $description->get_title(),
488
                'content' => str_replace('src="/', 'src="'.$webPath, $description->get_content()),
489
            ];
490
        }
491
492
        return $results;
493
    }
494
495
    /**
496
     * @param int $directoryId
497
     *
498
     * @throws Exception
499
     *
500
     * @return array
501
     */
502
    public function getCourseDocuments($directoryId = 0)
503
    {
504
        Event::event_access_tool(TOOL_DOCUMENT);
505
506
        /** @var string $path */
507
        $path = '/';
508
        $sessionId = $this->session ? $this->session->getId() : 0;
509
510
        if ($directoryId) {
511
            $directory = DocumentManager::get_document_data_by_id(
512
                $directoryId,
513
                $this->course->getCode(),
514
                false,
515
                $sessionId
516
            );
517
518
            if (!$directory) {
519
                throw new Exception('NoDataAvailable');
520
            }
521
522
            $path = $directory['path'];
523
        }
524
525
        $courseInfo = api_get_course_info_by_id($this->course->getId());
526
        $documents = DocumentManager::getAllDocumentData(
527
            $courseInfo,
528
            $path,
529
            0,
530
            null,
531
            false,
532
            false,
533
            $sessionId
534
        );
535
        $results = [];
536
537
        if (!empty($documents)) {
538
            $webPath = api_get_path(WEB_CODE_PATH).'document/document.php?';
539
540
            /** @var array $document */
541
            foreach ($documents as $document) {
542
                if ($document['visibility'] != '1') {
543
                    continue;
544
                }
545
546
                $icon = $document['filetype'] == 'file'
547
                    ? choose_image($document['path'])
548
                    : chooseFolderIcon($document['path']);
549
550
                $results[] = [
551
                    'id' => $document['id'],
552
                    'type' => $document['filetype'],
553
                    'title' => $document['title'],
554
                    'path' => $document['path'],
555
                    'url' => $webPath.http_build_query(
556
                        [
557
                            'username' => $this->user->getUsername(),
558
                            'api_key' => $this->apiKey,
559
                            'cidReq' => $this->course->getCode(),
560
                            'id_session' => $sessionId,
561
                            'gidReq' => 0,
562
                            'gradebook' => 0,
563
                            'origin' => '',
564
                            'action' => 'download',
565
                            'id' => $document['id'],
566
                        ]
567
                    ),
568
                    'icon' => $icon,
569
                    'size' => format_file_size($document['size']),
570
                ];
571
            }
572
        }
573
574
        return $results;
575
    }
576
577
    /**
578
     * @throws Exception
579
     *
580
     * @return array
581
     */
582
    public function getCourseAnnouncements()
583
    {
584
        Event::event_access_tool(TOOL_ANNOUNCEMENT);
585
586
        $sessionId = $this->session ? $this->session->getId() : 0;
587
588
        $announcements = AnnouncementManager::getAnnouncements(
589
            null,
590
            null,
591
            false,
592
            null,
593
            null,
594
            null,
595
            null,
596
            null,
597
            0,
598
            $this->user->getId(),
599
            $this->course->getId(),
600
            $sessionId
601
        );
602
603
        $announcements = array_map(
604
            function ($announcement) {
605
                return [
606
                    'id' => (int) $announcement['id'],
607
                    'title' => strip_tags($announcement['title']),
608
                    'creatorName' => strip_tags($announcement['username']),
609
                    'date' => strip_tags($announcement['insert_date']),
610
                ];
611
            },
612
            $announcements
613
        );
614
615
        return $announcements;
616
    }
617
618
    /**
619
     * @param int $announcementId
620
     *
621
     * @throws Exception
622
     *
623
     * @return array
624
     */
625
    public function getCourseAnnouncement($announcementId)
626
    {
627
        Event::event_access_tool(TOOL_ANNOUNCEMENT);
628
629
        $sessionId = $this->session ? $this->session->getId() : 0;
630
        $announcement = AnnouncementManager::getAnnouncementInfoById(
631
            $announcementId,
632
            $this->course->getId(),
633
            $this->user->getId()
634
        );
635
636
        if (!$announcement) {
637
            throw new Exception(get_lang('NoAnnouncement'));
638
        }
639
640
        return [
641
            'id' => $announcement['announcement']->getIid(),
642
            'title' => $announcement['announcement']->getTitle(),
643
            'creatorName' => UserManager::formatUserFullName($announcement['item_property']->getInsertUser()),
644
            'date' => api_convert_and_format_date(
645
                $announcement['item_property']->getInsertDate(),
646
                DATE_TIME_FORMAT_LONG_24H
647
            ),
648
            'content' => AnnouncementManager::parseContent(
649
                $this->user->getId(),
650
                $announcement['announcement']->getContent(),
651
                $this->course->getCode(),
652
                $sessionId
653
            ),
654
        ];
655
    }
656
657
    /**
658
     * @throws Exception
659
     *
660
     * @return array
661
     */
662
    public function getCourseAgenda()
663
    {
664
        Event::event_access_tool(TOOL_CALENDAR_EVENT);
665
666
        $sessionId = $this->session ? $this->session->getId() : 0;
667
668
        $agenda = new Agenda(
669
            'course',
670
            $this->user->getId(),
671
            $this->course->getId(),
672
            $sessionId
673
        );
674
        $result = $agenda->parseAgendaFilter(null);
675
676
        $start = new DateTime(api_get_utc_datetime(), new DateTimeZone('UTC'));
677
        $start->modify('first day of this month');
678
        $start->setTime(0, 0, 0);
679
        $end = new DateTime(api_get_utc_datetime(), new DateTimeZone('UTC'));
680
        $end->modify('last day of this month');
681
        $end->setTime(23, 59, 59);
682
683
        $groupId = current($result['groups']);
684
        $userId = current($result['users']);
685
686
        $events = $agenda->getEvents(
687
            $start->getTimestamp(),
688
            $end->getTimestamp(),
689
            $this->course->getId(),
690
            $groupId,
691
            $userId,
692
            'array'
693
        );
694
695
        if (!is_array($events)) {
696
            return [];
697
        }
698
699
        $webPath = api_get_path(WEB_PATH);
700
701
        return array_map(
702
            function ($event) use ($webPath) {
703
                return [
704
                    'id' => (int) $event['unique_id'],
705
                    'title' => $event['title'],
706
                    'content' => str_replace('src="/', 'src="'.$webPath, $event['description']),
707
                    'startDate' => $event['start_date_localtime'],
708
                    'endDate' => $event['end_date_localtime'],
709
                    'isAllDay' => $event['allDay'] ? true : false,
710
                ];
711
            },
712
            $events
713
        );
714
    }
715
716
    /**
717
     * @throws Exception
718
     *
719
     * @return array
720
     */
721
    public function getCourseNotebooks()
722
    {
723
        Event::event_access_tool(TOOL_NOTEBOOK);
724
725
        $em = Database::getManager();
726
        /** @var CNotebookRepository $notebooksRepo */
727
        $notebooksRepo = $em->getRepository('ChamiloCourseBundle:CNotebook');
728
        $notebooks = $notebooksRepo->findByUser($this->user, $this->course, $this->session);
729
730
        return array_map(
731
            function (CNotebook $notebook) {
732
                return [
733
                    'id' => $notebook->getIid(),
734
                    'title' => $notebook->getTitle(),
735
                    'description' => $notebook->getDescription(),
736
                    'creationDate' => api_format_date(
737
                        $notebook->getCreationDate()->getTimestamp()
738
                    ),
739
                    'updateDate' => api_format_date(
740
                        $notebook->getUpdateDate()->getTimestamp()
741
                    ),
742
                ];
743
            },
744
            $notebooks
745
        );
746
    }
747
748
    /**
749
     * @throws Exception
750
     *
751
     * @return array
752
     */
753
    public function getCourseForumCategories()
754
    {
755
        Event::event_access_tool(TOOL_FORUM);
756
757
        $sessionId = $this->session ? $this->session->getId() : 0;
758
        $webCoursePath = api_get_path(WEB_COURSE_PATH).$this->course->getDirectory().'/upload/forum/images/';
759
760
        require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
761
762
        $categoriesFullData = get_forum_categories('', $this->course->getId(), $sessionId);
763
        $categories = [];
764
        $includeGroupsForums = api_get_setting('display_groups_forum_in_general_tool') === 'true';
765
        $forumsFullData = get_forums('', $this->course->getCode(), $includeGroupsForums, $sessionId);
766
        $forums = [];
767
768
        foreach ($forumsFullData as $forumId => $forumInfo) {
769
            $forum = [
770
                'id' => (int) $forumInfo['iid'],
771
                'catId' => (int) $forumInfo['forum_category'],
772
                'title' => $forumInfo['forum_title'],
773
                'description' => $forumInfo['forum_comment'],
774
                'image' => $forumInfo['forum_image'] ? ($webCoursePath.$forumInfo['forum_image']) : '',
775
                'numberOfThreads' => isset($forumInfo['number_of_threads']) ? intval(
776
                    $forumInfo['number_of_threads']
777
                ) : 0,
778
                'lastPost' => null,
779
            ];
780
781
            $lastPostInfo = get_last_post_information($forumId, false, $this->course->getId(), $sessionId);
782
783
            if ($lastPostInfo) {
784
                $forum['lastPost'] = [
785
                    'date' => api_convert_and_format_date($lastPostInfo['last_post_date']),
786
                    'user' => api_get_person_name(
787
                        $lastPostInfo['last_poster_firstname'],
788
                        $lastPostInfo['last_poster_lastname']
789
                    ),
790
                ];
791
            }
792
793
            $forums[] = $forum;
794
        }
795
796
        foreach ($categoriesFullData as $category) {
797
            $categoryForums = array_filter(
798
                $forums,
799
                function (array $forum) use ($category) {
800
                    if ($forum['catId'] != $category['cat_id']) {
801
                        return false;
802
                    }
803
804
                    return true;
805
                }
806
            );
807
808
            $categories[] = [
809
                'id' => (int) $category['iid'],
810
                'title' => $category['cat_title'],
811
                'catId' => (int) $category['cat_id'],
812
                'description' => $category['cat_comment'],
813
                'forums' => $categoryForums,
814
                'courseId' => $this->course->getId(),
815
            ];
816
        }
817
818
        return $categories;
819
    }
820
821
    /**
822
     * @param int $forumId
823
     *
824
     * @throws Exception
825
     *
826
     * @return array
827
     */
828
    public function getCourseForum($forumId)
829
    {
830
        Event::event_access_tool(TOOL_FORUM);
831
832
        require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
833
834
        $sessionId = $this->session ? $this->session->getId() : 0;
835
        $forumInfo = get_forums($forumId, $this->course->getCode(), true, $sessionId);
836
837
        if (!isset($forumInfo['iid'])) {
838
            throw new Exception(get_lang('NoForum'));
839
        }
840
841
        $webCoursePath = api_get_path(WEB_COURSE_PATH).$this->course->getDirectory().'/upload/forum/images/';
842
        $forum = [
843
            'id' => $forumInfo['iid'],
844
            'title' => $forumInfo['forum_title'],
845
            'description' => $forumInfo['forum_comment'],
846
            'image' => $forumInfo['forum_image'] ? ($webCoursePath.$forumInfo['forum_image']) : '',
847
            'threads' => [],
848
        ];
849
850
        $threads = get_threads($forumInfo['iid'], $this->course->getId(), $sessionId);
851
852
        foreach ($threads as $thread) {
853
            $forum['threads'][] = [
854
                'id' => $thread['iid'],
855
                'title' => $thread['thread_title'],
856
                'lastEditDate' => api_convert_and_format_date($thread['lastedit_date'], DATE_TIME_FORMAT_LONG_24H),
857
                'numberOfReplies' => $thread['thread_replies'],
858
                'numberOfViews' => $thread['thread_views'],
859
                'author' => api_get_person_name($thread['firstname'], $thread['lastname']),
860
            ];
861
        }
862
863
        return $forum;
864
    }
865
866
    /**
867
     * @param int $forumId
868
     * @param int $threadId
869
     *
870
     * @return array
871
     */
872
    public function getCourseForumThread($forumId, $threadId)
873
    {
874
        Event::event_access_tool(TOOL_FORUM);
875
876
        require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
877
878
        $sessionId = $this->session ? $this->session->getId() : 0;
879
        $threadInfo = get_thread_information($forumId, $threadId, $sessionId);
880
881
        $thread = [
882
            'id' => intval($threadInfo['iid']),
883
            'cId' => intval($threadInfo['c_id']),
884
            'title' => $threadInfo['thread_title'],
885
            'forumId' => intval($threadInfo['forum_id']),
886
            'posts' => [],
887
        ];
888
889
        $forumInfo = get_forums($threadInfo['forum_id'], $this->course->getCode(), true, $sessionId);
890
        $postsInfo = getPosts($forumInfo, $threadInfo['iid'], 'ASC');
891
892
        foreach ($postsInfo as $postInfo) {
893
            $thread['posts'][] = [
894
                'id' => $postInfo['iid'],
895
                'title' => $postInfo['post_title'],
896
                'text' => $postInfo['post_text'],
897
                'author' => api_get_person_name($postInfo['firstname'], $postInfo['lastname']),
898
                'date' => api_convert_and_format_date($postInfo['post_date'], DATE_TIME_FORMAT_LONG_24H),
899
                'parentId' => $postInfo['post_parent_id'],
900
                'attachments' => getAttachedFiles(
901
                    $forumId,
902
                    $threadId,
903
                    $postInfo['iid'],
904
                    0,
905
                    $this->course->getId()
906
                ),
907
            ];
908
        }
909
910
        return $thread;
911
    }
912
913
    public function getCourseLinks(): array
914
    {
915
        Event::event_access_tool(TOOL_LINK);
916
917
        $courseId = $this->course->getId();
918
        $sessionId = $this->session ? $this->session->getId() : 0;
919
920
        $webCodePath = api_get_path(WEB_CODE_PATH);
921
        $cidReq = api_get_cidreq();
922
923
        $categories = array_merge(
924
            [
925
                [
926
                    'iid' => 0,
927
                    'c_id' => $courseId,
928
                    'id' => 0,
929
                    'category_title' => get_lang('NoCategory'),
930
                    'description' => '',
931
                    'display_order' => 0,
932
                    'session_id' => $sessionId,
933
                    'visibility' => 1,
934
                ],
935
            ],
936
            Link::getLinkCategories($courseId, $sessionId)
937
        );
938
939
        $categories = array_filter(
940
            $categories,
941
            function (array $category) {
942
                return $category['visibility'] != 0;
943
            }
944
        );
945
946
        return array_map(
947
            function (array $category) use ($webCodePath, $cidReq, $courseId, $sessionId) {
948
                $links = array_filter(
949
                    Link::getLinksPerCategory($category['iid'], $courseId, $sessionId),
950
                    function (array $link) {
951
                        return $link['visibility'] != 0;
952
                    }
953
                );
954
955
                $links = array_map(
956
                    function (array $link) use ($webCodePath, $cidReq) {
957
                        return [
958
                            'id' => (int) $link['id'],
959
                            'title' => Security::remove_XSS($link['title']),
960
                            'description' => Security::remove_XSS($link['description']),
961
                            'visibility' => (int) $link['visibility'],
962
                            'url' => $webCodePath."link/link_goto.php?$cidReq&link_id=".$link['id'],
963
                        ];
964
                    },
965
                    $links
966
                );
967
968
                return [
969
                    'id' => (int) $category['iid'],
970
                    'title' => Security::remove_XSS($category['category_title']),
971
                    'description' => Security::remove_XSS($category['description']),
972
                    'visibility' => (int) $category['visibility'],
973
                    'links' => $links,
974
                ];
975
            },
976
            $categories
977
        );
978
    }
979
980
    /**
981
     * @return array
982
     */
983
    public function getUserProfile()
984
    {
985
        $pictureInfo = UserManager::get_user_picture_path_by_id($this->user->getId(), 'web');
986
987
        $result = [
988
            'pictureUri' => $pictureInfo['dir'].$pictureInfo['file'],
989
            'id' => $this->user->getId(),
990
            'status' => $this->user->getStatus(),
991
            'fullName' => UserManager::formatUserFullName($this->user),
992
            'username' => $this->user->getUsername(),
993
            'officialCode' => $this->user->getOfficialCode(),
994
            'phone' => $this->user->getPhone(),
995
            'extra' => [],
996
        ];
997
998
        $fieldValue = new ExtraFieldValue('user');
999
        $extraInfo = $fieldValue->getAllValuesForAnItem($this->user->getId(), true);
1000
1001
        foreach ($extraInfo as $extra) {
1002
            /** @var ExtraFieldValues $extraValue */
1003
            $extraValue = $extra['value'];
1004
            $result['extra'][] = [
1005
                'title' => $extraValue->getField()->getDisplayText(true),
1006
                'value' => $extraValue->getValue(),
1007
            ];
1008
        }
1009
1010
        return $result;
1011
    }
1012
1013
    public function getCourseLpProgress()
1014
    {
1015
        $sessionId = $this->session ? $this->session->getId() : 0;
1016
        $userId = $this->user->getId();
1017
1018
        /*$sessionId = $this->session ? $this->session->getId() : 0;
1019
        $courseId = $this->course->getId();*/
1020
1021
        $result = Tracking::getCourseLpProgress($userId, $sessionId);
1022
1023
        return [$result];
1024
    }
1025
1026
    /**
1027
     * @throws Exception
1028
     *
1029
     * @return array
1030
     */
1031
    public function getCourseLearnPaths()
1032
    {
1033
        Event::event_access_tool(TOOL_LEARNPATH);
1034
1035
        $sessionId = $this->session ? $this->session->getId() : 0;
1036
        $categoriesTempList = learnpath::getCategories($this->course->getId());
1037
1038
        $categoryNone = new CLpCategory();
1039
        $categoryNone->setId(0);
1040
        $categoryNone->setName(get_lang('WithOutCategory'));
1041
        $categoryNone->setPosition(0);
1042
1043
        $categories = array_merge([$categoryNone], $categoriesTempList);
1044
        $categoryData = [];
1045
1046
        /** @var CLpCategory $category */
1047
        foreach ($categories as $category) {
1048
            $learnPathList = new LearnpathList(
1049
                $this->user->getId(),
1050
                api_get_course_info($this->course->getCode()),
1051
                $sessionId,
1052
                null,
1053
                false,
1054
                $category->getId()
1055
            );
1056
1057
            $flatLpList = $learnPathList->get_flat_list();
1058
1059
            if (empty($flatLpList)) {
1060
                continue;
1061
            }
1062
1063
            $listData = [];
1064
1065
            foreach ($flatLpList as $lpId => $lpDetails) {
1066
                if ($lpDetails['lp_visibility'] == 0) {
1067
                    continue;
1068
                }
1069
1070
                if (!learnpath::is_lp_visible_for_student(
1071
                    $lpId,
1072
                    $this->user->getId(),
1073
                    api_get_course_info($this->course->getCode()),
1074
                    $sessionId
1075
                )) {
1076
                    continue;
1077
                }
1078
1079
                $timeLimits = false;
1080
1081
                // This is an old LP (from a migration 1.8.7) so we do nothing
1082
                if (empty($lpDetails['created_on']) && empty($lpDetails['modified_on'])) {
1083
                    $timeLimits = false;
1084
                }
1085
1086
                // Checking if expired_on is ON
1087
                if (!empty($lpDetails['expired_on'])) {
1088
                    $timeLimits = true;
1089
                }
1090
1091
                if ($timeLimits) {
1092
                    if (!empty($lpDetails['publicated_on']) && !empty($lpDetails['expired_on'])) {
1093
                        $startTime = api_strtotime($lpDetails['publicated_on'], 'UTC');
1094
                        $endTime = api_strtotime($lpDetails['expired_on'], 'UTC');
1095
                        $now = time();
1096
                        $isActiveTime = false;
1097
1098
                        if ($now > $startTime && $endTime > $now) {
1099
                            $isActiveTime = true;
1100
                        }
1101
1102
                        if (!$isActiveTime) {
1103
                            continue;
1104
                        }
1105
                    }
1106
                }
1107
1108
                $progress = learnpath::getProgress($lpId, $this->user->getId(), $this->course->getId(), $sessionId);
1109
1110
                $listData[] = [
1111
                    'id' => $lpId,
1112
                    'title' => Security::remove_XSS($lpDetails['lp_name']),
1113
                    'progress' => $progress,
1114
                    'url' => api_get_path(WEB_CODE_PATH).'webservices/api/v2.php?'.http_build_query(
1115
                        [
1116
                            'hash' => $this->encodeParams(
1117
                                [
1118
                                    'action' => 'course_learnpath',
1119
                                    'lp_id' => $lpId,
1120
                                    'course' => $this->course->getId(),
1121
                                    'session' => $sessionId,
1122
                                ]
1123
                            ),
1124
                        ]
1125
                    ),
1126
                ];
1127
            }
1128
1129
            if (empty($listData)) {
1130
                continue;
1131
            }
1132
1133
            $categoryData[] = [
1134
                'id' => $category->getId(),
1135
                'name' => $category->getName(),
1136
                'learnpaths' => $listData,
1137
            ];
1138
        }
1139
1140
        return $categoryData;
1141
    }
1142
1143
    /**
1144
     * Start login for a user. Then make a redirect to show the learnpath.
1145
     *
1146
     * @param int $lpId
1147
     */
1148
    public function showLearningPath($lpId)
1149
    {
1150
        $loggedUser['user_id'] = $this->user->getId();
1151
        $loggedUser['status'] = $this->user->getStatus();
1152
        $loggedUser['uidReset'] = true;
1153
        $sessionId = $this->session ? $this->session->getId() : 0;
1154
1155
        ChamiloSession::write('_user', $loggedUser);
1156
        Login::init_user($this->user->getId(), true);
1157
1158
        $url = api_get_path(WEB_CODE_PATH).'lp/lp_controller.php?'.http_build_query(
1159
            [
1160
                'cidReq' => $this->course->getCode(),
1161
                'id_session' => $sessionId,
1162
                'gidReq' => 0,
1163
                'gradebook' => 0,
1164
                'origin' => '',
1165
                'action' => 'view',
1166
                'lp_id' => (int) $lpId,
1167
                'isStudentView' => 'true',
1168
            ]
1169
        );
1170
1171
        header("Location: $url");
1172
        exit;
1173
    }
1174
1175
    /**
1176
     * @param int $forumId
1177
     *
1178
     * @return array
1179
     */
1180
    public function saveForumPost(array $postValues, $forumId)
1181
    {
1182
        Event::event_access_tool(TOOL_FORUM);
1183
1184
        require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
1185
1186
        $forum = get_forums($forumId, $this->course->getCode());
1187
        store_reply($forum, $postValues, $this->course->getId(), $this->user->getId());
1188
1189
        return [
1190
            'registered' => true,
1191
        ];
1192
    }
1193
1194
    /**
1195
     * Get the list of sessions for current user.
1196
     *
1197
     * @return array the sessions list
1198
     */
1199
    public function getUserSessions()
1200
    {
1201
        $data = [];
1202
        $sessionsByCategory = UserManager::get_sessions_by_category($this->user->getId(), false);
1203
1204
        $webCodePath = api_get_path(WEB_CODE_PATH).'webservices/api/v2.php?';
1205
1206
        foreach ($sessionsByCategory as $category) {
1207
            $categorySessions = [];
1208
1209
            foreach ($category['sessions'] as $sessions) {
1210
                $sessionCourses = [];
1211
1212
                foreach ($sessions['courses'] as $course) {
1213
                    $courseInfo = api_get_course_info_by_id($course['real_id']);
1214
                    $teachers = SessionManager::getCoachesByCourseSessionToString(
1215
                        $sessions['session_id'],
1216
                        $course['real_id']
1217
                    );
1218
1219
                    $sessionCourses[] = [
1220
                        'id' => $courseInfo['real_id'],
1221
                        'title' => $courseInfo['title'],
1222
                        'code' => $courseInfo['code'],
1223
                        'directory' => $courseInfo['directory'],
1224
                        'pictureUrl' => $courseInfo['course_image_large'],
1225
                        'urlPicture' => $courseInfo['course_image_large'],
1226
                        'teachers' => $teachers,
1227
                        'url' => $webCodePath.http_build_query(
1228
                            [
1229
                                'action' => self::VIEW_COURSE_HOME,
1230
                                'api_key' => $this->apiKey,
1231
                                'username' => $this->user->getUsername(),
1232
                                'course' => $courseInfo['real_id'],
1233
                                'session' => $sessions['session_id'],
1234
                            ]
1235
                        ),
1236
                    ];
1237
                }
1238
1239
                $sessionBox = Display::getSessionTitleBox($sessions['session_id']);
1240
1241
                $categorySessions[] = [
1242
                    'name' => $sessionBox['title'],
1243
                    'id' => $sessions['session_id'],
1244
                    'date' => $sessionBox['dates'],
1245
                    'duration' => isset($sessionBox['duration']) ? $sessionBox['duration'] : null,
1246
                    'courses' => $sessionCourses,
1247
                ];
1248
            }
1249
1250
            $data[] = [
1251
                'id' => $category['session_category']['id'],
1252
                'name' => $category['session_category']['name'],
1253
                'sessions' => $categorySessions,
1254
            ];
1255
        }
1256
1257
        return $data;
1258
    }
1259
1260
    public function getUsersSubscribedToCourse()
1261
    {
1262
        $users = CourseManager::get_user_list_from_course_code($this->course->getCode());
1263
1264
        $userList = [];
1265
        foreach ($users as $user) {
1266
            $userList[] = [
1267
                'user_id' => $user['user_id'],
1268
                'username' => $user['username'],
1269
                'firstname' => $user['firstname'],
1270
                'lastname' => $user['lastname'],
1271
                'status_rel' => $user['status_rel'],
1272
            ];
1273
        }
1274
1275
        return $userList;
1276
    }
1277
1278
    /**
1279
     * @param string $subject
1280
     * @param string $text
1281
     *
1282
     * @return array
1283
     */
1284
    public function saveUserMessage($subject, $text, array $receivers)
1285
    {
1286
        foreach ($receivers as $userId) {
1287
            MessageManager::send_message($userId, $subject, $text);
1288
        }
1289
1290
        return [
1291
            'sent' => true,
1292
        ];
1293
    }
1294
1295
    /**
1296
     * @param string $search
1297
     *
1298
     * @return array
1299
     */
1300
    public function getMessageUsers($search)
1301
    {
1302
        $repo = UserManager::getRepository();
1303
1304
        $users = $repo->findUsersToSendMessage($this->user->getId(), $search);
1305
        $showEmail = api_get_setting('show_email_addresses') === 'true';
1306
        $data = [];
1307
1308
        /** @var User $user */
1309
        foreach ($users as $user) {
1310
            $userName = UserManager::formatUserFullName($user);
1311
1312
            if ($showEmail) {
1313
                $userName .= " ({$user->getEmail()})";
1314
            }
1315
1316
            $data[] = [
1317
                'id' => $user->getId(),
1318
                'name' => $userName,
1319
            ];
1320
        }
1321
1322
        return $data;
1323
    }
1324
1325
    /**
1326
     * @param string $title
1327
     * @param string $text
1328
     *
1329
     * @return array
1330
     */
1331
    public function saveCourseNotebook($title, $text)
1332
    {
1333
        Event::event_access_tool(TOOL_NOTEBOOK);
1334
1335
        $values = ['note_title' => $title, 'note_comment' => $text];
1336
        $sessionId = $this->session ? $this->session->getId() : 0;
1337
1338
        $noteBookId = NotebookManager::save_note(
1339
            $values,
1340
            $this->user->getId(),
1341
            $this->course->getId(),
1342
            $sessionId
1343
        );
1344
1345
        return [
1346
            'registered' => $noteBookId,
1347
        ];
1348
    }
1349
1350
    /**
1351
     * @param int $forumId
1352
     *
1353
     * @return array
1354
     */
1355
    public function saveForumThread(array $values, $forumId)
1356
    {
1357
        Event::event_access_tool(TOOL_FORUM);
1358
1359
        require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
1360
1361
        $sessionId = $this->session ? $this->session->getId() : 0;
1362
        $forum = get_forums($forumId, $this->course->getCode(), true, $sessionId);
1363
        $courseInfo = api_get_course_info($this->course->getCode());
1364
        $thread = store_thread($forum, $values, $courseInfo, false, $this->user->getId(), $sessionId);
1365
1366
        return [
1367
            'registered' => $thread->getIid(),
1368
        ];
1369
    }
1370
1371
    /**
1372
     * @return array
1373
     */
1374
    public function getUsersCampus(array $params)
1375
    {
1376
        $conditions = [
1377
            'status' => $params['status'],
1378
        ];
1379
        $idCampus = $params['id_campus'];
1380
        $users = UserManager::get_user_list($conditions, ['firstname'], false, false, $idCampus);
1381
        $list = [];
1382
        foreach ($users as $item) {
1383
            $listTemp = [
1384
                'id' => $item['user_id'],
1385
                'firstname' => $item['firstname'],
1386
                'lastname' => $item['lastname'],
1387
                'email' => $item['email'],
1388
            ];
1389
            $list[] = $listTemp;
1390
        }
1391
1392
        return $list;
1393
    }
1394
1395
    /**
1396
     * @return array
1397
     */
1398
    public function getCoursesCampus(array $params)
1399
    {
1400
        $idCampus = $params['id_campus'];
1401
1402
        return CourseManager::get_courses_list(
1403
            0, //offset
1404
            0, //howMany
1405
            1, //$orderby = 1
1406
            'ASC',
1407
            -1, //visibility
1408
            null,
1409
            $idCampus, //$urlId
1410
            true //AlsoSearchCode
1411
        );
1412
    }
1413
1414
    /**
1415
     * @return array
1416
     */
1417
    public function addSession(array $params)
1418
    {
1419
        $name = $params['name'];
1420
        $coach_username = (int) $params['coach_username'];
1421
        $startDate = $params['access_start_date'];
1422
        $endDate = $params['access_end_date'];
1423
        $displayStartDate = $startDate;
1424
        $displayEndDate = $endDate;
1425
        $description = $params['description'];
1426
        $idUrlCampus = $params['id_campus'];
1427
        $extraFields = isset($params['extra']) ? $params['extra'] : [];
1428
1429
        $return = SessionManager::create_session(
1430
            $name,
1431
            $startDate,
1432
            $endDate,
1433
            $displayStartDate,
1434
            $displayEndDate,
1435
            null,
1436
            null,
1437
            $coach_username,
1438
            null,
1439
            1,
1440
            false,
1441
            null,
1442
            $description,
1443
            1,
1444
            $extraFields,
1445
            null,
1446
            false,
1447
            $idUrlCampus
1448
        );
1449
1450
        if ($return) {
1451
            $out = [
1452
                'status' => true,
1453
                'message' => get_lang('ANewSessionWasCreated'),
1454
                'id_session' => $return,
1455
            ];
1456
        } else {
1457
            $out = [
1458
                'status' => false,
1459
                'message' => get_lang('ErrorOccurred'),
1460
            ];
1461
        }
1462
1463
        return $out;
1464
    }
1465
1466
    public function addCourse(array $courseParam): array
1467
    {
1468
        $idCampus = isset($courseParam['id_campus']) ? $courseParam['id_campus'] : 1;
1469
        $title = isset($courseParam['title']) ? $courseParam['title'] : '';
1470
        $wantedCode = isset($courseParam['wanted_code']) ? $courseParam['wanted_code'] : null;
1471
        $diskQuota = isset($courseParam['disk_quota']) ? $courseParam['disk_quota'] : '100';
1472
        $visibility = isset($courseParam['visibility']) ? (int) $courseParam['visibility'] : null;
1473
        $removeCampusId = $courseParam['remove_campus_id_from_wanted_code'] ?? 0;
1474
        $language = $courseParam['language'] ?? '';
1475
1476
        if (isset($courseParam['visibility'])) {
1477
            if ($courseParam['visibility'] &&
1478
                $courseParam['visibility'] >= 0 &&
1479
                $courseParam['visibility'] <= 3
1480
            ) {
1481
                $visibility = (int) $courseParam['visibility'];
1482
            }
1483
        }
1484
1485
        $params = [];
1486
        $params['title'] = $title;
1487
        $params['wanted_code'] = 'CAMPUS_'.$idCampus.'_'.$wantedCode;
1488
        if (1 === (int) $removeCampusId) {
1489
            $params['wanted_code'] = $wantedCode;
1490
        }
1491
        $params['user_id'] = $this->user->getId();
1492
        $params['visibility'] = $visibility;
1493
        $params['disk_quota'] = $diskQuota;
1494
        $params['course_language'] = $language;
1495
1496
        foreach ($courseParam as $key => $value) {
1497
            if (substr($key, 0, 6) === 'extra_') { //an extra field
1498
                $params[$key] = $value;
1499
            }
1500
        }
1501
1502
        $courseInfo = CourseManager::create_course($params, $params['user_id'], $idCampus);
1503
        $results = [];
1504
        if (!empty($courseInfo)) {
1505
            $results['status'] = true;
1506
            $results['code_course'] = $courseInfo['code'];
1507
            $results['title_course'] = $courseInfo['title'];
1508
            $extraFieldValues = new ExtraFieldValue('course');
1509
            $extraFields = $extraFieldValues->getAllValuesByItem($courseInfo['real_id']);
1510
            $results['extra_fields'] = $extraFields;
1511
            $results['message'] = sprintf(get_lang('CourseXAdded'), $courseInfo['code']);
1512
        } else {
1513
            $results['status'] = false;
1514
            $results['message'] = get_lang('CourseCreationFailed');
1515
        }
1516
1517
        return $results;
1518
    }
1519
1520
    /**
1521
     * @param $userParam
1522
     *
1523
     * @throws Exception
1524
     *
1525
     * @return array
1526
     */
1527
    public function addUser($userParam)
1528
    {
1529
        $firstName = $userParam['firstname'];
1530
        $lastName = $userParam['lastname'];
1531
        $status = $userParam['status'];
1532
        $email = $userParam['email'];
1533
        $loginName = $userParam['loginname'];
1534
        $password = $userParam['password'];
1535
1536
        $official_code = '';
1537
        $language = '';
1538
        $phone = '';
1539
        $picture_uri = '';
1540
        $auth_source = $userParam['auth_source'] ?? PLATFORM_AUTH_SOURCE;
1541
        $expiration_date = '';
1542
        $active = 1;
1543
        $hr_dept_id = 0;
1544
        $original_user_id_name = $userParam['original_user_id_name'];
1545
        $original_user_id_value = $userParam['original_user_id_value'];
1546
1547
        $extra_list = isset($userParam['extra']) ? $userParam['extra'] : [];
1548
        if (isset($userParam['language'])) {
1549
            $language = $userParam['language'];
1550
        }
1551
        if (isset($userParam['phone'])) {
1552
            $phone = $userParam['phone'];
1553
        }
1554
        if (isset($userParam['expiration_date'])) {
1555
            $expiration_date = $userParam['expiration_date'];
1556
        }
1557
1558
        // Default language.
1559
        if (empty($language)) {
1560
            $language = api_get_setting('platformLanguage');
1561
        }
1562
1563
        // First check wether the login already exists.
1564
        if (!UserManager::is_username_available($loginName)) {
1565
            throw new Exception(get_lang('UserNameNotAvailable'));
1566
        }
1567
1568
        $userId = UserManager::create_user(
1569
            $firstName,
1570
            $lastName,
1571
            $status,
1572
            $email,
1573
            $loginName,
1574
            $password,
1575
            $official_code,
1576
            $language,
1577
            $phone,
1578
            $picture_uri,
1579
            $auth_source,
1580
            $expiration_date,
1581
            $active,
1582
            $hr_dept_id
1583
        );
1584
1585
        if (empty($userId)) {
1586
            throw new Exception(get_lang('UserNotRegistered'));
1587
        }
1588
1589
        if (api_is_multiple_url_enabled()) {
1590
            if (api_get_current_access_url_id() != -1) {
1591
                UrlManager::add_user_to_url(
1592
                    $userId,
1593
                    api_get_current_access_url_id()
1594
                );
1595
            } else {
1596
                UrlManager::add_user_to_url($userId, 1);
1597
            }
1598
        } else {
1599
            // We add by default the access_url_user table with access_url_id = 1
1600
            UrlManager::add_user_to_url($userId, 1);
1601
        }
1602
1603
        // Save new field label into user_field table.
1604
        UserManager::create_extra_field(
1605
            $original_user_id_name,
1606
            1,
1607
            $original_user_id_name,
1608
            ''
1609
        );
1610
        // Save the external system's id into user_field_value table.
1611
        UserManager::update_extra_field_value(
1612
            $userId,
1613
            $original_user_id_name,
1614
            $original_user_id_value
1615
        );
1616
1617
        if (is_array($extra_list) && count($extra_list) > 0) {
1618
            foreach ($extra_list as $extra) {
1619
                $extra_field_name = $extra['field_name'];
1620
                $extra_field_value = $extra['field_value'];
1621
                // Save new field label into user_field table.
1622
                UserManager::create_extra_field(
1623
                    $extra_field_name,
1624
                    1,
1625
                    $extra_field_name,
1626
                    ''
1627
                );
1628
                // Save the external system's id into user_field_value table.
1629
                UserManager::update_extra_field_value(
1630
                    $userId,
1631
                    $extra_field_name,
1632
                    $extra_field_value
1633
                );
1634
            }
1635
        }
1636
1637
        return [$userId];
1638
    }
1639
1640
    /**
1641
     * @throws Exception
1642
     */
1643
    public function addUserGetApikey(array $userParams): array
1644
    {
1645
        list($userId) = $this->addUser($userParams);
1646
1647
        UserManager::add_api_key($userId, self::SERVICE_NAME);
1648
1649
        $apiKey = UserManager::get_api_keys($userId, self::SERVICE_NAME);
1650
1651
        return [
1652
            'id' => $userId,
1653
            'api_key' => current($apiKey),
1654
        ];
1655
    }
1656
1657
    /**
1658
     * @throws Exception
1659
     */
1660
    public function updateUserApiKey(int $userId, string $oldApiKey): array
1661
    {
1662
        if (false === $currentApiKeys = UserManager::get_api_keys($userId, self::SERVICE_NAME)) {
1663
            throw new Exception(get_lang('NotAllowed'));
1664
        }
1665
1666
        if (current($currentApiKeys) !== $oldApiKey) {
1667
            throw new Exception(get_lang('NotAllowed'));
1668
        }
1669
1670
        UserManager::update_api_key($userId, self::SERVICE_NAME);
1671
1672
        $apiKey = UserManager::get_api_keys($userId, self::SERVICE_NAME);
1673
1674
        return [
1675
            'api_key' => current($apiKey),
1676
        ];
1677
    }
1678
1679
    /**
1680
     * Subscribe User to Course.
1681
     *
1682
     * @param array $params
1683
     *
1684
     * @return array
1685
     */
1686
    public function subscribeUserToCourse($params)
1687
    {
1688
        $course_id = $params['course_id'];
1689
        $course_code = $params['course_code'];
1690
        $user_id = $params['user_id'];
1691
        $status = $params['status'] ?? STUDENT;
1692
1693
        if (!$course_id && !$course_code) {
1694
            return [false];
1695
        }
1696
        if (!$course_code) {
1697
            $course_code = CourseManager::get_course_code_from_course_id($course_id);
1698
        }
1699
1700
        if (CourseManager::subscribeUser($user_id, $course_code, $status, 0, 0, false)) {
1701
            return [true];
1702
        }
1703
1704
        return [false];
1705
    }
1706
1707
    /**
1708
     * @throws Exception
1709
     */
1710
    public function subscribeUserToCoursePassword($courseCode, $password)
1711
    {
1712
        $courseInfo = api_get_course_info($courseCode);
1713
1714
        if (empty($courseInfo)) {
1715
            throw new Exception(get_lang('NoCourse'));
1716
        }
1717
1718
        if (sha1($password) === $courseInfo['registration_code']) {
1719
            CourseManager::processAutoSubscribeToCourse($courseCode);
1720
1721
            return;
1722
        }
1723
1724
        throw new Exception(get_lang('CourseRegistrationCodeIncorrect'));
1725
    }
1726
1727
    public function unSubscribeUserToCourse(array $params): array
1728
    {
1729
        $courseId = $params['course_id'];
1730
        $courseCode = $params['course_code'];
1731
        $userId = $params['user_id'];
1732
1733
        if (!$courseId && !$courseCode) {
1734
            return [false];
1735
        }
1736
1737
        if (!$courseCode) {
1738
            $courseCode = CourseManager::get_course_code_from_course_id($courseId);
1739
        }
1740
1741
        if (CourseManager::unsubscribe_user($userId, $courseCode)) {
1742
            return [true];
1743
        }
1744
1745
        return [false];
1746
    }
1747
1748
    public function deleteUserMessage($messageId, $messageType)
1749
    {
1750
        if ($messageType === 'sent') {
1751
            return MessageManager::delete_message_by_user_sender($this->user->getId(), $messageId);
1752
        } else {
1753
            return MessageManager::delete_message_by_user_receiver($this->user->getId(), $messageId);
1754
        }
1755
    }
1756
1757
    public function setMessageRead($messageId)
1758
    {
1759
        MessageManager::update_message($this->user->getId(), $messageId);
1760
    }
1761
1762
    /**
1763
     * Add Campus Virtual.
1764
     *
1765
     * @param array Params Campus
1766
     *
1767
     * @return array
1768
     */
1769
    public function createCampusURL($params)
1770
    {
1771
        $urlCampus = Security::remove_XSS($params['url']);
1772
        $description = Security::remove_XSS($params['description']);
1773
1774
        $active = isset($params['active']) ? intval($params['active']) : 0;
1775
        $num = UrlManager::url_exist($urlCampus);
1776
        if ($num == 0) {
1777
            // checking url
1778
            if (substr($urlCampus, strlen($urlCampus) - 1, strlen($urlCampus)) == '/') {
1779
                $idCampus = UrlManager::add($urlCampus, $description, $active, true);
1780
            } else {
1781
                //create
1782
                $idCampus = UrlManager::add($urlCampus.'/', $description, $active, true);
1783
            }
1784
1785
            return [
1786
                'status' => true,
1787
                'id_campus' => $idCampus,
1788
            ];
1789
        }
1790
1791
        return [
1792
            'status' => false,
1793
            'id_campus' => 0,
1794
        ];
1795
    }
1796
1797
    /**
1798
     * Edit Campus Virtual.
1799
     *
1800
     * @param array Params Campus
1801
     *
1802
     * @return array
1803
     */
1804
    public function editCampusURL($params)
1805
    {
1806
        $urlCampus = Security::remove_XSS($params['url']);
1807
        $description = Security::remove_XSS($params['description']);
1808
1809
        $active = isset($params['active']) ? intval($params['active']) : 0;
1810
        $url_id = isset($params['id']) ? intval($params['id']) : 0;
1811
1812
        if (!empty($url_id)) {
1813
            //we can't change the status of the url with id=1
1814
            if ($url_id == 1) {
1815
                $active = 1;
1816
            }
1817
            //checking url
1818
            if (substr($urlCampus, strlen($urlCampus) - 1, strlen($urlCampus)) == '/') {
1819
                UrlManager::update($url_id, $urlCampus, $description, $active);
1820
            } else {
1821
                UrlManager::update($url_id, $urlCampus.'/', $description, $active);
1822
            }
1823
1824
            return [true];
1825
        }
1826
1827
        return [false];
1828
    }
1829
1830
    /**
1831
     * Delete Campus Virtual.
1832
     *
1833
     * @param array Params Campus
1834
     *
1835
     * @return array
1836
     */
1837
    public function deleteCampusURL($params)
1838
    {
1839
        $url_id = isset($params['id']) ? intval($params['id']) : 0;
1840
1841
        $result = UrlManager::delete($url_id);
1842
        if ($result) {
1843
            return [
1844
                'status' => true,
1845
                'message' => get_lang('URLDeleted'),
1846
            ];
1847
        } else {
1848
            return [
1849
                'status' => false,
1850
                'message' => get_lang('Error'),
1851
            ];
1852
        }
1853
    }
1854
1855
    /**
1856
     * @throws Exception
1857
     *
1858
     * @return array
1859
     */
1860
    public function addCoursesSession(array $params)
1861
    {
1862
        $sessionId = $params['id_session'];
1863
        $courseList = $params['list_courses'];
1864
        $importAssignments = isset($params['import_assignments']) ? 1 === (int) $params['import_assignments'] : false;
1865
1866
        $result = SessionManager::add_courses_to_session(
1867
            $sessionId,
1868
            $courseList,
1869
            true,
1870
            false,
1871
            false,
1872
            $importAssignments
1873
        );
1874
1875
        if ($result) {
1876
            return [
1877
                'status' => $result,
1878
                'message' => get_lang('Updated'),
1879
            ];
1880
        }
1881
1882
        return [
1883
            'status' => $result,
1884
            'message' => get_lang('ErrorOccurred'),
1885
        ];
1886
    }
1887
1888
    /**
1889
     * @return array
1890
     */
1891
    public function addUsersSession(array $params)
1892
    {
1893
        $sessionId = $params['id_session'];
1894
        $userList = $params['list_users'];
1895
1896
        if (!is_array($userList)) {
1897
            $userList = [];
1898
        }
1899
1900
        SessionManager::subscribeUsersToSession(
1901
            $sessionId,
1902
            $userList,
1903
            null,
1904
            false
1905
        );
1906
1907
        return [
1908
            'status' => true,
1909
            'message' => get_lang('UsersAdded'),
1910
        ];
1911
    }
1912
1913
    /**
1914
     * Creates a session from a model session.
1915
     *
1916
     * @param $modelSessionId
1917
     * @param $sessionName
1918
     * @param $startDate
1919
     * @param $endDate
1920
     *
1921
     * @throws Exception
1922
     *
1923
     * @return int, the id of the new session
1924
     */
1925
    public function createSessionFromModel($modelSessionId, $sessionName, $startDate, $endDate, array $extraFields = [])
1926
    {
1927
        if (empty($modelSessionId) || empty($sessionName) || empty($startDate) || empty($endDate)) {
1928
            throw new Exception(get_lang('NoData'));
1929
        }
1930
1931
        if (!SessionManager::isValidId($modelSessionId)) {
1932
            throw new Exception(get_lang('ModelSessionDoesNotExist'));
1933
        }
1934
1935
        $modelSession = SessionManager::fetch($modelSessionId);
1936
1937
        $modelSession['accessUrlId'] = 1;
1938
        if (api_is_multiple_url_enabled()) {
1939
            if (api_get_current_access_url_id() != -1) {
1940
                $modelSession['accessUrlId'] = api_get_current_access_url_id();
1941
            }
1942
        }
1943
1944
        $newSessionId = SessionManager::create_session(
1945
            $sessionName,
1946
            $startDate,
1947
            $endDate,
1948
            $startDate,
1949
            $endDate,
1950
            $startDate,
1951
            $endDate,
1952
            $modelSession['id_coach'],
1953
            $modelSession['session_category_id'],
1954
            $modelSession['visibility'],
1955
            false,
1956
            $modelSession['duration'],
1957
            $modelSession['description'],
1958
            $modelSession['show_description'],
1959
            $extraFields,
1960
            $modelSession['session_admin_id'],
1961
            $modelSession['send_subscription_notification'],
1962
            $modelSession['accessUrlId']
1963
        );
1964
1965
        if (empty($newSessionId)) {
1966
            throw new Exception(get_lang('SessionNotRegistered'));
1967
        }
1968
1969
        if (is_string($newSessionId)) {
1970
            throw new Exception($newSessionId);
1971
        }
1972
1973
        $promotionId = $modelSession['promotion_id'];
1974
        if ($promotionId) {
1975
            $sessionList = array_keys(SessionManager::get_all_sessions_by_promotion($promotionId));
1976
            $sessionList[] = $newSessionId;
1977
            SessionManager::subscribe_sessions_to_promotion($modelSession['promotion_id'], $sessionList);
1978
        }
1979
1980
        $modelExtraFields = [];
1981
        $fields = SessionManager::getFilteredExtraFields($modelSessionId);
1982
        if (is_array($fields) and !empty($fields)) {
1983
            foreach ($fields as $field) {
1984
                $modelExtraFields[$field['variable']] = $field['value'];
1985
            }
1986
        }
1987
        $allExtraFields = array_merge($modelExtraFields, $extraFields);
1988
        foreach ($allExtraFields as $name => $value) {
1989
            // SessionManager::update_session_extra_field_value returns false when no row is changed,
1990
            // which can happen since extra field values are initialized by SessionManager::create_session
1991
            // therefore we do not throw an exception when false is returned
1992
            SessionManager::update_session_extra_field_value($newSessionId, $name, $value);
1993
        }
1994
1995
        $courseList = array_keys(SessionManager::get_course_list_by_session_id($modelSessionId));
1996
        if (is_array($courseList)
1997
            && !empty($courseList)
1998
            && !SessionManager::add_courses_to_session($newSessionId, $courseList)) {
1999
            throw new Exception(get_lang('CoursesNotAddedToSession'));
2000
        }
2001
2002
        if (api_is_multiple_url_enabled()) {
2003
            if (api_get_current_access_url_id() != -1) {
2004
                UrlManager::add_session_to_url(
2005
                    $newSessionId,
2006
                    api_get_current_access_url_id()
2007
                );
2008
            } else {
2009
                UrlManager::add_session_to_url($newSessionId, 1);
2010
            }
2011
        } else {
2012
            UrlManager::add_session_to_url($newSessionId, 1);
2013
        }
2014
2015
        return $newSessionId;
2016
    }
2017
2018
    /**
2019
     * subscribes a user to a session.
2020
     *
2021
     * @param int    $sessionId the session id
2022
     * @param string $loginName the user's login name
2023
     *
2024
     * @throws Exception
2025
     *
2026
     * @return boolean, whether it worked
2027
     */
2028
    public function subscribeUserToSessionFromUsername($sessionId, $loginName)
2029
    {
2030
        if (!SessionManager::isValidId($sessionId)) {
2031
            throw new Exception(get_lang('SessionNotFound'));
2032
        }
2033
2034
        $userId = UserManager::get_user_id_from_username($loginName);
2035
        if (false === $userId) {
2036
            throw new Exception(get_lang('UserNotFound'));
2037
        }
2038
2039
        $subscribed = SessionManager::subscribeUsersToSession(
2040
            $sessionId,
2041
            [$userId],
2042
            SESSION_VISIBLE_READ_ONLY,
2043
            false
2044
        );
2045
        if (!$subscribed) {
2046
            throw new Exception(get_lang('UserNotSubscribed'));
2047
        }
2048
2049
        return true;
2050
    }
2051
2052
    /**
2053
     * finds the session which has a specific value in a specific extra field.
2054
     *
2055
     * @param $fieldName
2056
     * @param $fieldValue
2057
     *
2058
     * @throws Exception when no session matched or more than one session matched
2059
     *
2060
     * @return int, the matching session id
2061
     */
2062
    public function getSessionFromExtraField($fieldName, $fieldValue)
2063
    {
2064
        // find sessions that that have value in field
2065
        $valueModel = new ExtraFieldValue('session');
2066
        $sessionIdList = $valueModel->get_item_id_from_field_variable_and_field_value(
2067
            $fieldName,
2068
            $fieldValue,
2069
            false,
2070
            false,
2071
            true
2072
        );
2073
2074
        // throw if none found
2075
        if (empty($sessionIdList)) {
2076
            throw new Exception(get_lang('NoSessionMatched'));
2077
        }
2078
2079
        // throw if more than one found
2080
        if (count($sessionIdList) > 1) {
2081
            throw new Exception(get_lang('MoreThanOneSessionMatched'));
2082
        }
2083
2084
        // return sessionId
2085
        return intval($sessionIdList[0]['item_id']);
2086
    }
2087
2088
    /**
2089
     * updates a user identified by its login name.
2090
     *
2091
     * @param array $parameters
2092
     *
2093
     * @throws Exception on failure
2094
     *
2095
     * @return boolean, true on success
2096
     */
2097
    public function updateUserFromUserName($parameters)
2098
    {
2099
        // find user
2100
        $userId = null;
2101
        if (!is_array($parameters) || empty($parameters)) {
2102
            throw new Exception('NoData');
2103
        }
2104
        foreach ($parameters as $name => $value) {
2105
            if (strtolower($name) === 'loginname') {
2106
                $userId = UserManager::get_user_id_from_username($value);
2107
                if (false === $userId) {
2108
                    throw new Exception(get_lang('UserNotFound'));
2109
                }
2110
                break;
2111
            }
2112
        }
2113
        if (is_null($userId)) {
2114
            throw new Exception(get_lang('NoData'));
2115
        }
2116
        /** @var User $user */
2117
        $user = UserManager::getRepository()->find($userId);
2118
        if (empty($user)) {
2119
            throw new Exception(get_lang('CouldNotLoadUser'));
2120
        }
2121
2122
        // tell the world we are about to update a user
2123
        $hook = HookUpdateUser::create();
2124
        if (!empty($hook)) {
2125
            $hook->notifyUpdateUser(HOOK_EVENT_TYPE_PRE);
2126
        }
2127
2128
        // apply submitted modifications
2129
        foreach ($parameters as $name => $value) {
2130
            switch (strtolower($name)) {
2131
                case 'email':
2132
                    $user->setEmail($value);
2133
                    break;
2134
                case 'enabled':
2135
                    $user->setEnabled($value);
2136
                    break;
2137
                case 'lastname':
2138
                    $user->setLastname($value);
2139
                    break;
2140
                case 'firstname':
2141
                    $user->setFirstname($value);
2142
                    break;
2143
                case 'phone':
2144
                    $user->setPhone($value);
2145
                    break;
2146
                case 'address':
2147
                    $user->setAddress($value);
2148
                    break;
2149
                case 'roles':
2150
                    $user->setRoles($value);
2151
                    break;
2152
                case 'profile_completed':
2153
                    $user->setProfileCompleted($value);
2154
                    break;
2155
                case 'auth_source':
2156
                    $user->setAuthSource($value);
2157
                    break;
2158
                case 'status':
2159
                    $user->setStatus($value);
2160
                    break;
2161
                case 'official_code':
2162
                    $user->setOfficialCode($value);
2163
                    break;
2164
                case 'picture_uri':
2165
                    $user->setPictureUri($value);
2166
                    break;
2167
                case 'creator_id':
2168
                    $user->setCreatorId($value);
2169
                    break;
2170
                case 'competences':
2171
                    $user->setCompetences($value);
2172
                    break;
2173
                case 'diplomas':
2174
                    $user->setDiplomas($value);
2175
                    break;
2176
                case 'openarea':
2177
                    $user->setOpenArea($value);
2178
                    break;
2179
                case 'teach':
2180
                    $user->setTeach($value);
2181
                    break;
2182
                case 'productions':
2183
                    $user->setProductions($value);
2184
                    break;
2185
                case 'language':
2186
                    $languages = api_get_languages();
2187
                    if (!in_array($value, $languages['folder'])) {
2188
                        throw new Exception(get_lang('LanguageUnavailable'));
2189
                    }
2190
                    $user->setLanguage($value);
2191
                    break;
2192
                case 'registration_date':
2193
                    $user->setRegistrationDate($value);
2194
                    break;
2195
                case 'expiration_date':
2196
                    $user->setExpirationDate(
2197
                        new DateTime(
2198
                            api_get_utc_datetime($value),
2199
                            new DateTimeZone('UTC')
2200
                        )
2201
                    );
2202
                    break;
2203
                case 'active':
2204
                    // see UserManager::update_user() usermanager.lib.php:1205
2205
                    if ($user->getActive() != $value) {
2206
                        $user->setActive($value);
2207
                        Event::addEvent($value ? LOG_USER_ENABLE : LOG_USER_DISABLE, LOG_USER_ID, $userId);
2208
                    }
2209
                    break;
2210
                case 'openid':
2211
                    $user->setOpenId($value);
2212
                    break;
2213
                case 'theme':
2214
                    $user->setTheme($value);
2215
                    break;
2216
                case 'hr_dept_id':
2217
                    $user->setHrDeptId($value);
2218
                    break;
2219
                case 'extra':
2220
                    if (is_array($value)) {
2221
                        if (count($value) > 0) {
2222
                            if (is_array($value[0])) {
2223
                                foreach ($value as $field) {
2224
                                    $fieldName = $field['field_name'];
2225
                                    $fieldValue = $field['field_value'];
2226
                                    if (!isset($fieldName) || !isset($fieldValue) ||
2227
                                        !UserManager::update_extra_field_value($userId, $fieldName, $fieldValue)) {
2228
                                        throw new Exception(get_lang('CouldNotUpdateExtraFieldValue').': '.print_r($field, true));
2229
                                    }
2230
                                }
2231
                            } else {
2232
                                foreach ($value as $fieldName => $fieldValue) {
2233
                                    if (!UserManager::update_extra_field_value($userId, $fieldName, $fieldValue)) {
2234
                                        throw new Exception(get_lang('CouldNotUpdateExtraFieldValue').': '.$fieldName);
2235
                                    }
2236
                                }
2237
                            }
2238
                        }
2239
                    }
2240
                    break;
2241
                case 'username':
2242
                case 'api_key':
2243
                case 'action':
2244
                case 'loginname':
2245
                    break;
2246
                case 'email_canonical':
2247
                case 'locked':
2248
                case 'expired':
2249
                case 'credentials_expired':
2250
                case 'credentials_expire_at':
2251
                case 'expires_at':
2252
                case 'salt':
2253
                case 'last_login':
2254
                case 'created_at':
2255
                case 'updated_at':
2256
                case 'confirmation_token':
2257
                case 'password_requested_at':
2258
                case 'password': // see UserManager::update_user usermanager.lib.php:1182
2259
                case 'username_canonical':
2260
                default:
2261
                    throw new Exception(get_lang('UnsupportedUpdate')." '$name'");
2262
            }
2263
        }
2264
2265
        // save modifications
2266
        UserManager::getManager()->updateUser($user, true);
2267
2268
        // tell the world we just updated this user
2269
        if (!empty($hook)) {
2270
            $hook->setEventData(['user' => $user]);
2271
            $hook->notifyUpdateUser(HOOK_EVENT_TYPE_POST);
2272
        }
2273
2274
        // invalidate cache for this user
2275
        $cacheAvailable = api_get_configuration_value('apc');
2276
        if ($cacheAvailable === true) {
2277
            $apcVar = api_get_configuration_value('apc_prefix').'userinfo_'.$userId;
2278
            if (apcu_exists($apcVar)) {
2279
                apcu_delete($apcVar);
2280
            }
2281
        }
2282
2283
        return true;
2284
    }
2285
2286
    /**
2287
     * Returns whether a user login name exists.
2288
     *
2289
     * @param string $loginname the user login name
2290
     *
2291
     * @return bool whether the user login name exists
2292
     */
2293
    public function usernameExist($loginname)
2294
    {
2295
        return false !== api_get_user_info_from_username($loginname);
2296
    }
2297
2298
    /**
2299
     * This service roughly matches what the call to MDL's API core_course_get_contents function returns.
2300
     *
2301
     * @return array
2302
     */
2303
    public function getCourseQuizMdlCompat()
2304
    {
2305
        $userId = $this->user->getId();
2306
        $courseId = $this->course->getId();
2307
        $sessionId = $this->session ? $this->session->getId() : 0;
2308
2309
        $toolVisibility = CourseHome::getToolVisibility(TOOL_QUIZ, $courseId, $sessionId);
2310
2311
        $json = [
2312
            "id" => $this->course->getId(),
2313
            "name" => get_lang('Exercises'),
2314
            "visible" => (int) $toolVisibility,
2315
            "summary" => '',
2316
            "summaryformat" => 1,
2317
            "section" => 1,
2318
            "hiddenbynumsections" => 0,
2319
            "uservisible" => $toolVisibility,
2320
            "modules" => [],
2321
        ];
2322
2323
        $quizIcon = Display::return_icon('quiz.png', '', [], ICON_SIZE_SMALL, false, true);
2324
2325
        $json['modules'] = array_map(
2326
            function (array $exercise) use ($quizIcon) {
2327
                return [
2328
                    'id' => $exercise['id'],
2329
                    'url' => $exercise['url'],
2330
                    'name' => $exercise['name'],
2331
                    'instance' => 1,
2332
                    'visible' => 1,
2333
                    'uservisible' => true,
2334
                    'visibleoncoursepage' => 0,
2335
                    'modicon' => $quizIcon,
2336
                    'modname' => 'quiz',
2337
                    'modplural' => get_lang('Exercises'),
2338
                    'availability' => null,
2339
                    'indent' => 0,
2340
                    'onclick' => '',
2341
                    'afterlink' => null,
2342
                    'customdata' => "",
2343
                    'noviewlink' => false,
2344
                    'completion' => (int) ($exercise[1] > 0),
2345
                ];
2346
            },
2347
            Exercise::exerciseGrid(0, '', $userId, $courseId, $sessionId, true)
2348
        );
2349
2350
        return [$json];
2351
    }
2352
2353
    /**
2354
     * @throws Exception
2355
     */
2356
    public function updateSession(array $params): array
2357
    {
2358
        $id = $params['session_id'];
2359
        $reset = $params['reset'] ?? null;
2360
        $name = $params['name'] ?? null;
2361
        $coachId = isset($params['id_coach']) ? (int) $params['id_coach'] : null;
2362
        $sessionCategoryId = isset($params['session_category_id']) ? (int) $params['session_category_id'] : null;
2363
        $description = $params['description'] ?? null;
2364
        $showDescription = $params['show_description'] ?? null;
2365
        $duration = $params['duration'] ?? null;
2366
        $visibility = $params['visibility'] ?? null;
2367
        $promotionId = $params['promotion_id'] ?? null;
2368
        $displayStartDate = $params['display_start_date'] ?? null;
2369
        $displayEndDate = $params['display_end_date'] ?? null;
2370
        $accessStartDate = $params['access_start_date'] ?? null;
2371
        $accessEndDate = $params['access_end_date'] ?? null;
2372
        $coachStartDate = $params['coach_access_start_date'] ?? null;
2373
        $coachEndDate = $params['coach_access_end_date'] ?? null;
2374
        $sendSubscriptionNotification = $params['send_subscription_notification'] ?? null;
2375
        $extraFields = $params['extra'] ?? [];
2376
2377
        $reset = (bool) $reset;
2378
        $visibility = (int) $visibility;
2379
        $tblSession = Database::get_main_table(TABLE_MAIN_SESSION);
2380
2381
        if (!SessionManager::isValidId($id)) {
2382
            throw new Exception(get_lang('NoData'));
2383
        }
2384
2385
        if (!empty($accessStartDate) && !api_is_valid_date($accessStartDate, 'Y-m-d H:i') &&
2386
            !api_is_valid_date($accessStartDate, 'Y-m-d H:i:s')
2387
        ) {
2388
            throw new Exception(get_lang('InvalidDate'));
2389
        }
2390
2391
        if (!empty($accessEndDate) && !api_is_valid_date($accessEndDate, 'Y-m-d H:i') &&
2392
            !api_is_valid_date($accessEndDate, 'Y-m-d H:i:s')
2393
        ) {
2394
            throw new Exception(get_lang('InvalidDate'));
2395
        }
2396
2397
        if (!empty($accessStartDate) && !empty($accessEndDate) && $accessStartDate >= $accessEndDate) {
2398
            throw new Exception(get_lang('InvalidDate'));
2399
        }
2400
2401
        $values = [];
2402
2403
        if ($reset) {
2404
            $values['name'] = $name;
2405
            $values['id_coach'] = $coachId;
2406
            $values['session_category_id'] = $sessionCategoryId;
2407
            $values['description'] = $description;
2408
            $values['show_description'] = $showDescription;
2409
            $values['duration'] = $duration;
2410
            $values['visibility'] = $visibility;
2411
            $values['promotion_id'] = $promotionId;
2412
            $values['display_start_date'] = !empty($displayStartDate) ? api_get_utc_datetime($displayStartDate) : null;
2413
            $values['display_end_date'] = !empty($displayEndDate) ? api_get_utc_datetime($displayEndDate) : null;
2414
            $values['access_start_date'] = !empty($accessStartDate) ? api_get_utc_datetime($accessStartDate) : null;
2415
            $values['access_end_date'] = !empty($accessEndDate) ? api_get_utc_datetime($accessEndDate) : null;
2416
            $values['coach_access_start_date'] = !empty($coachStartDate) ? api_get_utc_datetime($coachStartDate) : null;
2417
            $values['coach_access_end_date'] = !empty($coachEndDate) ? api_get_utc_datetime($coachEndDate) : null;
2418
            $values['send_subscription_notification'] = $sendSubscriptionNotification;
2419
        } else {
2420
            if (!empty($name)) {
2421
                $values['name'] = $name;
2422
            }
2423
2424
            if (!empty($coachId)) {
2425
                $values['id_coach'] = $coachId;
2426
            }
2427
2428
            if (!empty($sessionCategoryId)) {
2429
                $values['session_category_id'] = $sessionCategoryId;
2430
            }
2431
2432
            if (!empty($description)) {
2433
                $values['description'] = $description;
2434
            }
2435
2436
            if (!empty($showDescription)) {
2437
                $values['show_description'] = $showDescription;
2438
            }
2439
2440
            if (!empty($duration)) {
2441
                $values['duration'] = $duration;
2442
            }
2443
2444
            if (!empty($visibility)) {
2445
                $values['visibility'] = $visibility;
2446
            }
2447
2448
            if (!empty($promotionId)) {
2449
                $values['promotion_id'] = $promotionId;
2450
            }
2451
2452
            if (!empty($displayStartDate)) {
2453
                $values['display_start_date'] = api_get_utc_datetime($displayStartDate);
2454
            }
2455
2456
            if (!empty($displayEndDate)) {
2457
                $values['display_end_date'] = api_get_utc_datetime($displayEndDate);
2458
            }
2459
2460
            if (!empty($accessStartDate)) {
2461
                $values['access_start_date'] = api_get_utc_datetime($accessStartDate);
2462
            }
2463
2464
            if (!empty($accessEndDate)) {
2465
                $values['access_end_date'] = api_get_utc_datetime($accessEndDate);
2466
            }
2467
2468
            if (!empty($coachStartDate)) {
2469
                $values['coach_access_start_date'] = api_get_utc_datetime($coachStartDate);
2470
            }
2471
2472
            if (!empty($coachEndDate)) {
2473
                $values['coach_access_end_date'] = api_get_utc_datetime($coachEndDate);
2474
            }
2475
2476
            if (!empty($sendSubscriptionNotification)) {
2477
                $values['send_subscription_notification'] = $sendSubscriptionNotification;
2478
            }
2479
        }
2480
2481
        Database::update(
2482
            $tblSession,
2483
            $values,
2484
            ['id = ?' => $id]
2485
        );
2486
2487
        if (!empty($extraFields)) {
2488
            $extraFields['item_id'] = $id;
2489
            $sessionFieldValue = new ExtraFieldValue('session');
2490
            $sessionFieldValue->saveFieldValues($extraFields);
2491
        }
2492
2493
        return [
2494
            'status' => true,
2495
            'message' => get_lang('Updated'),
2496
            'id_session' => $id,
2497
        ];
2498
    }
2499
2500
    public function checkConditionalLogin(): bool
2501
    {
2502
        $file = api_get_path(SYS_CODE_PATH).'auth/conditional_login/conditional_login.php';
2503
2504
        if (!file_exists($file)) {
2505
            return true;
2506
        }
2507
2508
        include_once $file;
2509
2510
        if (!isset($login_conditions)) {
2511
            return true;
2512
        }
2513
2514
        foreach ($login_conditions as $condition) {
2515
            //If condition fails we redirect to the URL defined by the condition
2516
            if (!isset($condition['conditional_function'])) {
2517
                continue;
2518
            }
2519
2520
            $function = $condition['conditional_function'];
2521
            $result = $function(['user_id' => $this->user->getId()]);
2522
2523
            if ($result == false) {
2524
                return false;
2525
            }
2526
        }
2527
2528
        return true;
2529
    }
2530
2531
    public function getLegalConditions(): array
2532
    {
2533
        $language = api_get_language_id(
2534
            api_get_interface_language()
2535
        );
2536
2537
        $termPreview = LegalManager::get_last_condition($language);
2538
2539
        if ($termPreview) {
2540
            return $termPreview;
2541
        }
2542
2543
        $language = api_get_language_id(
2544
            api_get_setting('platformLanguage')
2545
        );
2546
2547
        $termPreview = LegalManager::get_last_condition($language);
2548
2549
        if ($termPreview) {
2550
            return $termPreview;
2551
        }
2552
2553
        $language = api_get_language_id('english');
2554
2555
        return LegalManager::get_last_condition($language);
2556
    }
2557
2558
    public function updateConditionAccepted()
2559
    {
2560
        $legalAcceptType = $_POST['legal_accept_type'] ?? null;
2561
2562
        $condArray = explode(':', $legalAcceptType);
2563
        $condArray = array_map('intval', $condArray);
2564
2565
        if (empty($condArray[0]) || empty($condArray[1])) {
2566
            return;
2567
        }
2568
2569
        $conditionToSave = intval($condArray[0]).':'.intval($condArray[1]).':'.time();
2570
2571
        LegalManager::sendEmailToUserBoss(
2572
            $this->user->getId(),
2573
            $conditionToSave
2574
        );
2575
    }
2576
2577
    public function logout()
2578
    {
2579
        online_logout($this->user->getId());
2580
2581
        Event::courseLogout(
2582
            [
2583
                'uid' => $this->user->getId(),
2584
                'cid' => $this->course ? $this->course->getId() : 0,
2585
                'sid' => $this->session ? $this->session->getId() : 0,
2586
            ]
2587
        );
2588
    }
2589
2590
    /**
2591
     * @throws Exception
2592
     */
2593
    public function setThreadNotify(int $threadId): string
2594
    {
2595
        require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
2596
2597
        $result = set_notification(
2598
            'thread',
2599
            $threadId,
2600
            false,
2601
            api_get_user_info($this->user->getId()),
2602
            api_get_course_info($this->course->getCode())
2603
        );
2604
2605
        if (false === $result) {
2606
            throw new Exception(get_lang('NotAllowed'));
2607
        }
2608
2609
        return $result;
2610
    }
2611
2612
    public function getCourseWorks(): array
2613
    {
2614
        Event::event_access_tool(TOOL_STUDENTPUBLICATION);
2615
2616
        require_once api_get_path(SYS_CODE_PATH).'work/work.lib.php';
2617
2618
        $isAllowedToEdit = $this->user->getStatus() !== STUDENT;
2619
2620
        $courseId = $this->course->getId();
2621
        $sessionId = $this->session ? $this->session->getId() : 0;
2622
2623
        $courseInfo = api_get_course_info_by_id($this->course->getId());
2624
2625
        $works = array_filter(
2626
            getWorkListTeacherData($courseId, $sessionId, 0, 0, 0, 'title', 'ASC', ''),
2627
            function (array $work) use ($isAllowedToEdit, $courseInfo, $courseId, $sessionId) {
2628
                if (!$isAllowedToEdit
2629
                    && !userIsSubscribedToWork($this->user->getId(), $work['id'], $courseId)
2630
                ) {
2631
                    return false;
2632
                }
2633
2634
                $visibility = api_get_item_visibility($courseInfo, 'work', $work['id'], $sessionId);
2635
2636
                if (!$isAllowedToEdit && $visibility != 1) {
2637
                    return false;
2638
                }
2639
2640
                return true;
2641
            }
2642
        );
2643
2644
        return array_map(
2645
            function (array $work) use ($isAllowedToEdit, $courseInfo) {
2646
                $work['type'] = 'work.png';
2647
2648
                if (!$isAllowedToEdit) {
2649
                    $workList = get_work_user_list(
2650
                        0,
2651
                        1000,
2652
                        null,
2653
                        null,
2654
                        $work['id'],
2655
                        ' AND u.id = '.$this->user->getId()
2656
                    );
2657
2658
                    $count = getTotalWorkComment($workList, $courseInfo);
2659
                    $lastWork = getLastWorkStudentFromParentByUser($this->user->getId(), $work, $courseInfo);
2660
2661
                    $work['feedback'] = ' '.Display::label('0 '.get_lang('Feedback'), 'warning');
2662
2663
                    if (!empty($count)) {
2664
                        $work['feedback'] = ' '.Display::label($count.' '.get_lang('Feedback'), 'info');
2665
                    }
2666
2667
                    $work['last_upload'] = '';
2668
2669
                    if (!empty($lastWork)) {
2670
                        $work['last_upload'] = !empty($lastWork['qualification'])
2671
                            ? $lastWork['qualification_rounded'].' - '
2672
                            : '';
2673
                        $work['last_upload'] .= api_get_local_time($lastWork['sent_date']);
2674
                    }
2675
                }
2676
2677
                return $work;
2678
            },
2679
            $works
2680
        );
2681
    }
2682
2683
    /**
2684
     * @throws Exception
2685
     */
2686
    public function putCourseWorkVisibility(int $workId, int $status): bool
2687
    {
2688
        Event::event_access_tool(TOOL_STUDENTPUBLICATION);
2689
2690
        $courseInfo = api_get_course_info_by_id($this->course->getId());
2691
2692
        require_once api_get_path(SYS_CODE_PATH).'work/work.lib.php';
2693
2694
        switch ($status) {
2695
            case 1:
2696
                return makeVisible($workId, $courseInfo);
2697
            case 0:
2698
                return makeInvisible($workId, $courseInfo);
2699
            default:
2700
                throw new Exception(get_lang('ActionNotAllowed'));
2701
        }
2702
    }
2703
2704
    public function deleteWorkStudentItem(int $workId): string
2705
    {
2706
        Event::event_access_tool(TOOL_STUDENTPUBLICATION);
2707
2708
        require_once api_get_path(SYS_CODE_PATH).'work/work.lib.php';
2709
2710
        $courseInfo = api_get_course_info_by_id($this->course->getId());
2711
2712
        $fileDeleted = deleteWorkItem($workId, $courseInfo);
2713
2714
        if ($fileDeleted) {
2715
            return get_lang('TheDocumentHasBeenDeleted');
2716
        }
2717
2718
        return get_lang('YouAreNotAllowedToDeleteThisDocument');
2719
    }
2720
2721
    public function deleteWorkCorrections(int $workId): string
2722
    {
2723
        Event::event_access_tool(TOOL_STUDENTPUBLICATION);
2724
2725
        require_once api_get_path(SYS_CODE_PATH).'work/work.lib.php';
2726
2727
        $courseInfo = api_get_course_info_by_id($this->course->getId());
2728
2729
        $result = get_work_user_list(null, null, null, null, $workId);
2730
2731
        if ($result) {
2732
            foreach ($result as $item) {
2733
                $workInfo = get_work_data_by_id($item['id']);
2734
2735
                deleteCorrection($courseInfo, $workInfo);
2736
            }
2737
        }
2738
2739
        return get_lang('Deleted');
2740
    }
2741
2742
    public function getWorkList(int $workId): array
2743
    {
2744
        $isAllowedToEdit = api_is_allowed_to_edit();
2745
2746
        Event::event_access_tool(TOOL_STUDENTPUBLICATION);
2747
2748
        require_once api_get_path(SYS_CODE_PATH).'work/work.lib.php';
2749
2750
        $userId = $this->user->getId();
2751
        $courseId = $this->course->getId();
2752
        $sessionId = $this->session ? $this->session->getId() : 0;
2753
2754
        $courseInfo = api_get_course_info_by_id($courseId);
2755
        $webPath = api_get_path(WEB_PATH);
2756
2757
        $whereCondition = !$isAllowedToEdit ? " AND u.id = $userId" : '';
2758
2759
        $works = get_work_user_list(
2760
            0,
2761
            0,
2762
            'title',
2763
            'asc',
2764
            $workId,
2765
            $whereCondition,
2766
            null,
2767
            false,
2768
            $courseId,
2769
            $sessionId
2770
        );
2771
2772
        return array_map(
2773
            function (array $work) use ($courseInfo, $webPath) {
2774
                $itemId = $work['id'];
2775
                $count = getWorkCommentCount($itemId, $courseInfo);
2776
2777
                $work['feedback'] = $count.' '.Display::returnFontAwesomeIcon('comments-o');
2778
                $work['feedback_clean'] = $count;
2779
2780
                $workInfo = get_work_data_by_id($itemId);
2781
                $commentsTmp = getWorkComments($workInfo);
2782
                $comments = [];
2783
2784
                foreach ($commentsTmp as $comment) {
2785
                    $comment['comment'] = str_replace('src="/', 'src="'.$webPath.'app/', $comment['comment']);
2786
                    $comments[] = $comment;
2787
                }
2788
2789
                $work['comments'] = $comments;
2790
2791
                if (empty($workInfo['qualificator_id'])) {
2792
                    $qualificator_id = Display::label(get_lang('NotRevised'), 'warning');
2793
                } else {
2794
                    $qualificator_id = Display::label(get_lang('Revised'), 'success');
2795
                }
2796
2797
                $work['qualificator_id'] = $qualificator_id;
2798
2799
                return $work;
2800
            },
2801
            $works
2802
        );
2803
    }
2804
2805
    public function getWorkStudentsWithoutPublications(int $workId): array
2806
    {
2807
        Event::event_access_tool(TOOL_STUDENTPUBLICATION);
2808
2809
        require_once api_get_path(SYS_CODE_PATH).'work/work.lib.php';
2810
2811
        return get_list_users_without_publication($workId);
2812
    }
2813
2814
    public function getWorkUsers(int $workId): array
2815
    {
2816
        Event::event_access_tool(TOOL_STUDENTPUBLICATION);
2817
2818
        require_once api_get_path(SYS_CODE_PATH).'work/work.lib.php';
2819
2820
        $courseId = $this->course->getId();
2821
        $sessionId = $this->session ? $this->session->getId() : 0;
2822
        $courseInfo = api_get_course_info_by_id($courseId);
2823
2824
        $items = getAllUserToWork($workId, $courseId);
2825
        $usersAdded = [];
2826
        $result = [
2827
            'users_added' => [],
2828
            'users_to_add' => [],
2829
        ];
2830
2831
        if (!empty($items)) {
2832
            foreach ($items as $data) {
2833
                $usersAdded[] = $data['user_id'];
2834
2835
                $userInfo = api_get_user_info($data['user_id']);
2836
2837
                $result['users_added'][] = [
2838
                    'user_id' => (int) $data['user_id'],
2839
                    'complete_name_with_username' => $userInfo['complete_name_with_username'],
2840
                ];
2841
            }
2842
        }
2843
2844
        if (empty($sessionId)) {
2845
            $status = STUDENT;
2846
        } else {
2847
            $status = 0;
2848
        }
2849
2850
        $userList = CourseManager::get_user_list_from_course_code(
2851
            $courseInfo['code'],
2852
            $sessionId,
2853
            null,
2854
            null,
2855
            $status
2856
        );
2857
2858
        $userToAddList = [];
2859
        foreach ($userList as $user) {
2860
            if (!in_array($user['user_id'], $usersAdded)) {
2861
                $userToAddList[] = $user;
2862
            }
2863
        }
2864
2865
        if (!empty($userToAddList)) {
2866
            foreach ($userToAddList as $user) {
2867
                $userName = api_get_person_name($user['firstname'], $user['lastname']).' ('.$user['username'].') ';
2868
2869
                $result['users_to_add'][] = [
2870
                    'user_id' => (int) $user['user_id'],
2871
                    'complete_name_with_username' => $userName,
2872
                ];
2873
            }
2874
        }
2875
2876
        return $result;
2877
    }
2878
2879
    public function getWorkStudentList(int $workId): array
2880
    {
2881
        Event::event_access_tool(TOOL_STUDENTPUBLICATION);
2882
2883
        require_once api_get_path(SYS_CODE_PATH).'work/work.lib.php';
2884
2885
        $courseId = $this->course->getId();
2886
        $courseCode = $this->course->getCode();
2887
        $sessionId = $this->session ? $this->session->getId() : 0;
2888
2889
        $myFolderData = get_work_data_by_id($workId);
2890
2891
        $workParents = [];
2892
2893
        if (empty($myFolderData)) {
2894
            $workParents = getWorkList($workId, $myFolderData);
2895
        }
2896
2897
        $workIdList = [];
2898
2899
        if (!empty($workParents)) {
2900
            foreach ($workParents as $work) {
2901
                $workIdList[] = $work->id;
2902
            }
2903
        }
2904
2905
        $userList = getWorkUserList(
2906
            $courseCode,
2907
            $sessionId,
2908
            0,
2909
            0,
2910
            null,
2911
            null,
2912
            null
2913
        );
2914
2915
        return array_map(
2916
            function ($userId) use ($courseId, $sessionId, $workParents, $workIdList) {
2917
                $user = api_get_user_info($userId);
2918
2919
                $userWorks = 0;
2920
2921
                if (!empty($workIdList)) {
2922
                    $userWorks = getUniqueStudentAttempts(
2923
                        $workIdList,
2924
                        0,
2925
                        $courseId,
2926
                        $sessionId,
2927
                        $user['user_id']
2928
                    );
2929
                }
2930
2931
                $works = $userWorks." / ".count($workParents);
2932
2933
                return [
2934
                    'id' => $userId,
2935
                    'complete_name' => api_get_person_name($user['firstname'], $user['lastname']),
2936
                    'works' => $works,
2937
                ];
2938
            },
2939
            $userList
2940
        );
2941
    }
2942
2943
    public function viewUserProfile(int $userId)
2944
    {
2945
        $url = api_get_path(WEB_CODE_PATH).'social/profile.php';
2946
2947
        if ($userId) {
2948
            $url .= '?'.http_build_query(['u' => $userId]);
2949
        }
2950
2951
        header("Location: $url");
2952
        exit;
2953
    }
2954
2955
    public function viewCourseHome()
2956
    {
2957
        $url = api_get_course_url($this->course->getCode(), $this->session ? $this->session->getId() : 0);
2958
2959
        header("Location: $url");
2960
        exit;
2961
    }
2962
2963
    public function viewDocumentInFrame(int $documentId)
2964
    {
2965
        $courseCode = $this->course->getCode();
2966
        $sessionId = $this->session ? $this->session->getId() : 0;
2967
2968
        $url = api_get_path(WEB_CODE_PATH).'document/showinframes.php?'
2969
            .http_build_query(
2970
                [
2971
                    'cidReq' => $courseCode,
2972
                    'id_session' => $sessionId,
2973
                    'gidReq' => 0,
2974
                    'gradebook' => 0,
2975
                    'origin' => self::SERVICE_NAME,
2976
                    'id' => $documentId,
2977
                ]
2978
            );
2979
2980
        header("Location: $url");
2981
        exit;
2982
    }
2983
2984
    public function viewQuizTool()
2985
    {
2986
        $courseCode = $this->course->getCode();
2987
        $sessionId = $this->session ? $this->session->getId() : 0;
2988
2989
        $url = api_get_path(WEB_CODE_PATH).'exercise/exercise.php?'
2990
            .http_build_query(
2991
                [
2992
                    'cidReq' => $courseCode,
2993
                    'id_session' => $sessionId,
2994
                    'gidReq' => 0,
2995
                    'gradebook' => 0,
2996
                    'origin' => self::SERVICE_NAME,
2997
                ]
2998
            );
2999
3000
        header("Location: $url");
3001
        exit;
3002
    }
3003
3004
    public function viewSurveyTool()
3005
    {
3006
        $courseCode = $this->course->getCode();
3007
        $sessionId = $this->session ? $this->session->getId() : 0;
3008
3009
        $url = api_get_path(WEB_CODE_PATH).'survey/survey_list.php?'
3010
            .http_build_query(
3011
                [
3012
                    'cidReq' => $courseCode,
3013
                    'id_session' => $sessionId,
3014
                    'gidReq' => 0,
3015
                    'gradebook' => 0,
3016
                    'origin' => self::SERVICE_NAME,
3017
                ]
3018
            );
3019
3020
        header("Location: $url");
3021
        exit;
3022
    }
3023
3024
    public function viewMessage(int $messageId)
3025
    {
3026
        $url = api_get_path(WEB_CODE_PATH).'messages/view_message.php?'.http_build_query(['id' => $messageId]);
3027
3028
        header("Location: $url");
3029
        exit;
3030
    }
3031
3032
    public function downloadForumPostAttachment(string $path)
3033
    {
3034
        $courseCode = $this->course->getCode();
3035
        $sessionId = $this->session ? $this->session->getId() : 0;
3036
3037
        $url = api_get_path(WEB_CODE_PATH).'forum/download.php?'
3038
            .http_build_query(
3039
                [
3040
                    'cidReq' => $courseCode,
3041
                    'id_session' => $sessionId,
3042
                    'gidReq' => 0,
3043
                    'gradebook' => 0,
3044
                    'origin' => self::SERVICE_NAME,
3045
                    'file' => Security::remove_XSS($path),
3046
                ]
3047
            );
3048
3049
        header("Location: $url");
3050
        exit;
3051
    }
3052
3053
    public function downloadWorkFolder(int $workId)
3054
    {
3055
        $cidReq = api_get_cidreq();
3056
        $url = api_get_path(WEB_CODE_PATH)."work/downloadfolder.inc.php?id=$workId&$cidReq";
3057
3058
        header("Location: $url");
3059
        exit;
3060
    }
3061
3062
    public function downloadWorkCommentAttachment(int $commentId)
3063
    {
3064
        $cidReq = api_get_cidreq();
3065
        $url = api_get_path(WEB_CODE_PATH)."work/download_comment_file.php?comment_id=$commentId&$cidReq";
3066
3067
        header("Location: $url");
3068
        exit;
3069
    }
3070
3071
    public function downloadWork(int $workId, bool $isCorrection = false)
3072
    {
3073
        $cidReq = api_get_cidreq();
3074
        $url = api_get_path(WEB_CODE_PATH)."work/download.php?$cidReq&"
3075
            .http_build_query(
3076
                [
3077
                    'id' => $workId,
3078
                    'correction' => $isCorrection ? 1 : null,
3079
                ]
3080
            );
3081
3082
        header("Location: $url");
3083
        exit;
3084
    }
3085
3086
    public static function isAllowedByRequest(bool $inpersonate = false): bool
3087
    {
3088
        $username = $_GET['username'] ?? null;
3089
        $apiKey = $_GET['api_key'] ?? null;
3090
3091
        if (empty($username) || empty($apiKey)) {
3092
            return false;
3093
        }
3094
3095
        try {
3096
            $restApi = self::validate($username, $apiKey);
3097
        } catch (Exception $e) {
3098
            return false;
3099
        }
3100
3101
        if ($inpersonate) {
3102
            Login::init_user($restApi->getUser()->getId(), true);
3103
        }
3104
3105
        return (bool) $restApi;
3106
    }
3107
3108
    /**
3109
     * @param array $additionalParams Optional
3110
     *
3111
     * @return string
3112
     */
3113
    private function encodeParams(array $additionalParams = [])
3114
    {
3115
        $params = array_merge(
3116
            $additionalParams,
3117
            [
3118
                'api_key' => $this->apiKey,
3119
                'username' => $this->user->getUsername(),
3120
            ]
3121
        );
3122
3123
        return json_encode($params);
3124
    }
3125
}
3126