Passed
Pull Request — 1.11.x (#4080)
by Angel Fernando Quiroz
09:26
created

Rest::updateUserFromUserName()   F

Complexity

Conditions 69
Paths 1376

Size

Total Lines 187
Code Lines 148

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 69
eloc 148
nc 1376
nop 1
dl 0
loc 187
rs 0
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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