Passed
Push — 1.11.x ( b7dbbd...c78fc6 )
by Angel Fernando Quiroz
11:59 queued 12s
created

Rest::updateSession()   F

Complexity

Conditions 36
Paths > 20000

Size

Total Lines 141
Code Lines 91

Duplication

Lines 0
Ratio 0 %

Importance

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