Passed
Push — 1.11.x ( 118af0...2cce6b )
by Angel Fernando Quiroz
09:20
created

Rest::updateConditionAccepted()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

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