Completed
Push — master ( a73e85...13dd2e )
by Julito
08:28
created

Rest::addUser()   D

Complexity

Conditions 13
Paths 256

Size

Total Lines 113
Code Lines 75

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 13
eloc 75
c 0
b 0
f 0
nc 256
nop 1
dl 0
loc 113
rs 4.6121

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 POST_USER_MESSAGE_READ = 'user_message_read';
24
    const POST_USER_MESSAGE_UNREAD = 'user_message_unread';
25
    const SAVE_GCM_ID = 'gcm_id';
26
    const GET_USER_COURSES = 'user_courses';
27
    const GET_PROFILE = 'user_profile';
28
    const GET_COURSE_INFO = 'course_info';
29
    const GET_COURSE_DESCRIPTIONS = 'course_descriptions';
30
    const GET_COURSE_DOCUMENTS = 'course_documents';
31
    const GET_COURSE_ANNOUNCEMENTS = 'course_announcements';
32
    const GET_COURSE_ANNOUNCEMENT = 'course_announcement';
33
    const GET_COURSE_AGENDA = 'course_agenda';
34
    const GET_COURSE_NOTEBOOKS = 'course_notebooks';
35
    const GET_COURSE_FORUM_CATEGORIES = 'course_forumcategories';
36
    const GET_COURSE_FORUM = 'course_forum';
37
    const GET_COURSE_FORUM_THREAD = 'course_forumthread';
38
    const GET_COURSE_LEARNPATHS = 'course_learnpaths';
39
    const GET_COURSE_LEARNPATH = 'course_learnpath';
40
    const GET_COURSE_LP_PROGRESS = 'course_lp_progress';
41
    const SAVE_FORUM_POST = 'save_forum_post';
42
    const GET_USER_SESSIONS = 'user_sessions';
43
    const SAVE_USER_MESSAGE = 'save_user_message';
44
    const GET_MESSAGE_USERS = 'message_users';
45
    const SAVE_COURSE_NOTEBOOK = 'save_course_notebook';
46
    const SAVE_FORUM_THREAD = 'save_forum_thread';
47
    const SAVE_COURSE = 'save_course';
48
    const SAVE_USER = 'save_user';
49
    const SAVE_USER_JSON = 'save_user_json';
50
    const SUBSCRIBE_USER_TO_COURSE = 'subscribe_user_to_course';
51
    const EXTRAFIELD_GCM_ID = 'gcm_registration_id';
52
    const GET_USER_MESSAGES_RECEIVED = 'user_messages_received';
53
    const GET_USER_MESSAGES_SENT = 'user_messages_sent';
54
    const DELETE_USER_MESSAGE = 'delete_user_message';
55
    const SET_MESSAGE_READ = 'set_message_read';
56
    const CREATE_CAMPUS = 'add_campus';
57
    const EDIT_CAMPUS = 'edit_campus';
58
    const DELETE_CAMPUS = 'delete_campus';
59
    const SAVE_SESSION = 'save_session';
60
    const GET_USERS = 'get_users';
61
    const GET_COURSES = 'get_courses';
62
    const ADD_COURSES_SESSION = 'add_courses_session';
63
    const ADD_USERS_SESSION = 'add_users_session';
64
    const CREATE_SESSION_FROM_MODEL = 'create_session_from_model';
65
    const SUBSCRIBE_USER_TO_SESSION_FROM_USERNAME = 'subscribe_user_to_session_from_username';
66
    const GET_SESSION_FROM_EXTRA_FIELD = 'get_session_from_extra_field';
67
    const UPDATE_USER_FROM_USERNAME = 'update_user_from_username';
68
    const USERNAME_EXIST = 'username_exist';
69
    const GET_COURSE_QUIZ_MDL_COMPAT = 'get_course_quiz_mdl_compat';
70
    const UPDATE_USER_PAUSE_TRAINING = 'update_user_pause_training';
71
72
    /**
73
     * @var Session
74
     */
75
    private $session;
76
77
    /**
78
     * @var Course
79
     */
80
    private $course;
81
82
    /**
83
     * Rest constructor.
84
     *
85
     * @param string $username
86
     * @param string $apiKey
87
     */
88
    public function __construct($username, $apiKey)
89
    {
90
        parent::__construct($username, $apiKey);
91
    }
92
93
    /**
94
     * @param string $username
95
     * @param string $apiKeyToValidate
96
     *
97
     * @throws Exception
98
     *
99
     * @return Rest
100
     */
101
    public static function validate($username, $apiKeyToValidate)
102
    {
103
        $apiKey = self::findUserApiKey($username, self::SERVICE_NAME);
104
105
        if ($apiKey != $apiKeyToValidate) {
106
            throw new Exception(get_lang('InvalidApiKey'));
107
        }
108
109
        return new self($username, $apiKey);
110
    }
111
112
    /**
113
     * Create the gcm_registration_id extra field for users.
114
     */
115
    public static function init()
116
    {
117
        $extraField = new ExtraField('user');
118
        $fieldInfo = $extraField->get_handler_field_info_by_field_variable(self::EXTRA_FIELD_GCM_REGISTRATION);
119
120
        if (empty($fieldInfo)) {
121
            $extraField->save(
122
                [
123
                    'variable' => self::EXTRA_FIELD_GCM_REGISTRATION,
124
                    'field_type' => ExtraField::FIELD_TYPE_TEXT,
125
                    'display_text' => self::EXTRA_FIELD_GCM_REGISTRATION,
126
                ]
127
            );
128
        }
129
    }
130
131
    /**
132
     * @param string $encoded
133
     *
134
     * @return array
135
     */
136
    public static function decodeParams($encoded)
137
    {
138
        return json_decode($encoded);
139
    }
140
141
    /**
142
     * Set the current course.
143
     *
144
     * @param int $id
145
     *
146
     * @throws Exception
147
     */
148
    public function setCourse($id)
149
    {
150
        if (!$id) {
151
            $this->course = null;
152
153
            return;
154
        }
155
156
        $em = Database::getManager();
157
        /** @var Course $course */
158
        $course = $em->find('ChamiloCoreBundle:Course', $id);
159
160
        if (!$course) {
0 ignored issues
show
introduced by
$course is of type Chamilo\CoreBundle\Entity\Course, thus it always evaluated to true.
Loading history...
161
            throw new Exception(get_lang('NoCourse'));
162
        }
163
164
        $this->course = $course;
165
    }
166
167
    /**
168
     * Set the current session.
169
     *
170
     * @param int $id
171
     *
172
     * @throws Exception
173
     */
174
    public function setSession($id)
175
    {
176
        if (!$id) {
177
            $this->session = null;
178
179
            return;
180
        }
181
182
        $em = Database::getManager();
183
        /** @var Session $session */
184
        $session = $em->find('ChamiloCoreBundle:Session', $id);
185
186
        if (!$session) {
0 ignored issues
show
introduced by
$session is of type Chamilo\CoreBundle\Entity\Session, thus it always evaluated to true.
Loading history...
187
            throw new Exception(get_lang('NoSession'));
188
        }
189
190
        $this->session = $session;
191
    }
192
193
    /**
194
     * @param string $registrationId
195
     *
196
     * @return bool
197
     */
198
    public function setGcmId($registrationId)
199
    {
200
        $registrationId = Security::remove_XSS($registrationId);
201
        $extraFieldValue = new ExtraFieldValue('user');
202
203
        return $extraFieldValue->save(
204
            [
205
                'variable' => self::EXTRA_FIELD_GCM_REGISTRATION,
206
                'value' => $registrationId,
207
                'item_id' => $this->user->getId(),
208
            ]
209
        );
210
    }
211
212
    /**
213
     * @param int $lastMessageId
214
     *
215
     * @return array
216
     */
217
    public function getUserMessages($lastMessageId = 0)
218
    {
219
        $lastMessages = MessageManager::getMessagesFromLastReceivedMessage($this->user->getId(), $lastMessageId);
220
        $messages = [];
221
222
        foreach ($lastMessages as $message) {
223
            $hasAttachments = MessageManager::hasAttachments($message['id']);
224
225
            $messages[] = [
226
                'id' => $message['id'],
227
                'title' => $message['title'],
228
                'sender' => [
229
                    'id' => $message['user_id'],
230
                    'lastname' => $message['lastname'],
231
                    'firstname' => $message['firstname'],
232
                    'completeName' => api_get_person_name($message['firstname'], $message['lastname']),
233
                ],
234
                'sendDate' => $message['send_date'],
235
                'content' => $message['content'],
236
                'hasAttachments' => $hasAttachments,
237
                'url' => api_get_path(WEB_CODE_PATH).'messages/view_message.php?'
238
                    .http_build_query(['type' => 1, 'id' => $message['id']]),
239
            ];
240
        }
241
242
        return $messages;
243
    }
244
245
    /**
246
     * @return array
247
     */
248
    public function getUserReceivedMessages()
249
    {
250
        $lastMessages = MessageManager::getReceivedMessages($this->user->getId(), 0);
251
        $messages = [];
252
253
        foreach ($lastMessages as $message) {
254
            $hasAttachments = MessageManager::hasAttachments($message['id']);
255
            $attachmentList = [];
256
            if ($hasAttachments) {
257
                $attachmentList = MessageManager::getAttachmentList($message['id']);
258
            }
259
            $messages[] = [
260
                'id' => $message['id'],
261
                'title' => $message['title'],
262
                'msgStatus' => $message['msg_status'],
263
                'sender' => [
264
                    'id' => $message['user_id'],
265
                    'lastname' => $message['lastname'],
266
                    'firstname' => $message['firstname'],
267
                    'completeName' => api_get_person_name($message['firstname'], $message['lastname']),
268
                    'pictureUri' => $message['pictureUri'],
269
                ],
270
                'sendDate' => $message['send_date'],
271
                'content' => $message['content'],
272
                'hasAttachments' => $hasAttachments,
273
                'attachmentList' => $attachmentList,
274
                'url' => '',
275
            ];
276
        }
277
278
        return $messages;
279
    }
280
281
    /**
282
     * @return array
283
     */
284
    public function getUserSentMessages()
285
    {
286
        $lastMessages = MessageManager::getSentMessages($this->user->getId(), 0);
287
        $messages = [];
288
289
        foreach ($lastMessages as $message) {
290
            $hasAttachments = MessageManager::hasAttachments($message['id']);
291
292
            $messages[] = [
293
                'id' => $message['id'],
294
                'title' => $message['title'],
295
                'msgStatus' => $message['msg_status'],
296
                'receiver' => [
297
                    'id' => $message['user_id'],
298
                    'lastname' => $message['lastname'],
299
                    'firstname' => $message['firstname'],
300
                    'completeName' => api_get_person_name($message['firstname'], $message['lastname']),
301
                    'pictureUri' => $message['pictureUri'],
302
                ],
303
                'sendDate' => $message['send_date'],
304
                'content' => $message['content'],
305
                'hasAttachments' => $hasAttachments,
306
                'url' => '',
307
            ];
308
        }
309
310
        return $messages;
311
    }
312
313
    /**
314
     * Get the user courses.
315
     *
316
     * @throws \Doctrine\ORM\TransactionRequiredException
317
     * @throws \Doctrine\ORM\ORMException
318
     * @throws \Doctrine\ORM\OptimisticLockException
319
     *
320
     * @return array
321
     */
322
    public function getUserCourses()
323
    {
324
        $courses = CourseManager::get_courses_list_by_user_id($this->user->getId());
325
        $data = [];
326
327
        foreach ($courses as $courseInfo) {
328
            /** @var Course $course */
329
            $course = Database::getManager()->find('ChamiloCoreBundle:Course', $courseInfo['real_id']);
330
            $teachers = CourseManager::getTeacherListFromCourseCodeToString($course->getCode());
331
            $picturePath = CourseManager::getPicturePath($course, true)
332
                ?: Display::return_icon('session_default.png', null, null, null, null, true);
333
334
            $data[] = [
335
                'id' => $course->getId(),
336
                'title' => $course->getTitle(),
337
                'code' => $course->getCode(),
338
                'directory' => $course->getDirectory(),
339
                'urlPicture' => $picturePath,
340
                'teachers' => $teachers,
341
                'isSpecial' => !empty($courseInfo['special_course']),
342
            ];
343
        }
344
345
        return $data;
346
    }
347
348
    /**
349
     * @throws Exception
350
     *
351
     * @return array
352
     */
353
    public function getCourseInfo()
354
    {
355
        $teachers = CourseManager::getTeacherListFromCourseCodeToString($this->course->getCode());
356
        $tools = CourseHome::get_tools_category(
357
            TOOL_STUDENT_VIEW,
358
            $this->course->getId(),
359
            $this->session ? $this->session->getId() : 0
360
        );
361
362
        return [
363
            'id' => $this->course->getId(),
364
            'title' => $this->course->getTitle(),
365
            'code' => $this->course->getCode(),
366
            'directory' => $this->course->getDirectory(),
367
            'urlPicture' => CourseManager::getPicturePath($this->course, true),
368
            'teachers' => $teachers,
369
            'tools' => array_map(
370
                function ($tool) {
371
                    return ['type' => $tool['name']];
372
                },
373
                $tools
374
            ),
375
        ];
376
    }
377
378
    /**
379
     * Get the course descriptions.
380
     *
381
     * @throws Exception
382
     *
383
     * @return array
384
     */
385
    public function getCourseDescriptions()
386
    {
387
        $descriptions = CourseDescription::get_descriptions($this->course->getId());
388
        $results = [];
389
390
        /** @var CourseDescription $description */
391
        foreach ($descriptions as $description) {
392
            $results[] = [
393
                'id' => $description->get_description_type(),
394
                'title' => $description->get_title(),
395
                'content' => str_replace('src="/', 'src="'.api_get_path(WEB_PATH), $description->get_content()),
396
            ];
397
        }
398
399
        return $results;
400
    }
401
402
    /**
403
     * @param int $directoryId
404
     *
405
     * @throws Exception
406
     *
407
     * @return array
408
     */
409
    public function getCourseDocuments($directoryId = 0)
410
    {
411
        /** @var string $path */
412
        $path = '/';
413
        $sessionId = $this->session ? $this->session->getId() : 0;
414
415
        if ($directoryId) {
416
            $directory = DocumentManager::get_document_data_by_id(
417
                $directoryId,
418
                $this->course->getCode(),
419
                false,
420
                $sessionId
421
            );
422
423
            if (!$directory) {
424
                throw new Exception('NoDataAvailable');
425
            }
426
427
            $path = $directory['path'];
428
        }
429
430
        $courseInfo = api_get_course_info_by_id($this->course->getId());
431
        $documents = DocumentManager::getAllDocumentData(
432
            $courseInfo,
433
            $path,
434
            0,
435
            null,
436
            false,
437
            false,
438
            $sessionId
439
        );
440
        $results = [];
441
442
        if (!empty($documents)) {
443
            $webPath = api_get_path(WEB_CODE_PATH).'document/document.php?';
444
445
            /** @var array $document */
446
            foreach ($documents as $document) {
447
                if ($document['visibility'] != '1') {
448
                    continue;
449
                }
450
451
                $icon = $document['filetype'] == 'file'
452
                    ? choose_image($document['path'])
453
                    : chooseFolderIcon($document['path']);
454
455
                $results[] = [
456
                    'id' => $document['id'],
457
                    'type' => $document['filetype'],
458
                    'title' => $document['title'],
459
                    'path' => $document['path'],
460
                    'url' => $webPath.http_build_query(
461
                        [
462
                            'username' => $this->user->getUsername(),
463
                            'api_key' => $this->apiKey,
464
                            'cidReq' => $this->course->getCode(),
465
                            'id_session' => $sessionId,
466
                            'gidReq' => 0,
467
                            'gradebook' => 0,
468
                            'origin' => '',
469
                            'action' => 'download',
470
                            'id' => $document['id'],
471
                        ]
472
                    ),
473
                    'icon' => $icon,
474
                    'size' => format_file_size($document['size']),
475
                ];
476
            }
477
        }
478
479
        return $results;
480
    }
481
482
    /**
483
     * @throws Exception
484
     *
485
     * @return array
486
     */
487
    public function getCourseAnnouncements()
488
    {
489
        $sessionId = $this->session ? $this->session->getId() : 0;
490
491
        $announcements = AnnouncementManager::getAnnouncements(
492
            null,
493
            null,
494
            false,
495
            null,
496
            null,
497
            null,
498
            null,
499
            null,
500
            0,
501
            $this->user->getId(),
502
            $this->course->getId(),
503
            $sessionId
504
        );
505
506
        $announcements = array_map(
507
            function ($announcement) {
508
                return [
509
                    'id' => (int) $announcement['id'],
510
                    'title' => strip_tags($announcement['title']),
511
                    'creatorName' => strip_tags($announcement['username']),
512
                    'date' => strip_tags($announcement['insert_date']),
513
                ];
514
            },
515
            $announcements
516
        );
517
518
        return $announcements;
519
    }
520
521
    /**
522
     * @param int $announcementId
523
     *
524
     * @throws Exception
525
     *
526
     * @return array
527
     */
528
    public function getCourseAnnouncement($announcementId)
529
    {
530
        $sessionId = $this->session ? $this->session->getId() : 0;
531
        $announcement = AnnouncementManager::getAnnouncementInfoById(
532
            $announcementId,
533
            $this->course->getId(),
534
            $this->user->getId()
535
        );
536
537
        if (!$announcement) {
538
            throw new Exception(get_lang('NoAnnouncement'));
539
        }
540
541
        return [
542
            'id' => $announcement['announcement']->getIid(),
543
            'title' => $announcement['announcement']->getTitle(),
544
            'creatorName' => UserManager::formatUserFullName($announcement['item_property']->getInsertUser()),
545
            'date' => api_convert_and_format_date(
546
                $announcement['item_property']->getInsertDate(),
547
                DATE_TIME_FORMAT_LONG_24H
548
            ),
549
            'content' => AnnouncementManager::parseContent(
550
                $this->user->getId(),
551
                $announcement['announcement']->getContent(),
552
                $this->course->getCode(),
553
                $sessionId
554
            ),
555
        ];
556
    }
557
558
    /**
559
     * @throws Exception
560
     *
561
     * @return array
562
     */
563
    public function getCourseAgenda()
564
    {
565
        $sessionId = $this->session ? $this->session->getId() : 0;
566
567
        $agenda = new Agenda(
568
            'course',
569
            $this->user->getId(),
570
            $this->course->getId(),
571
            $sessionId
572
        );
573
        $result = $agenda->parseAgendaFilter(null);
574
575
        $start = new DateTime(api_get_utc_datetime(), new DateTimeZone('UTC'));
576
        $start->modify('first day of this month');
577
        $start->setTime(0, 0, 0);
578
        $end = new DateTime(api_get_utc_datetime(), new DateTimeZone('UTC'));
579
        $end->modify('last day of this month');
580
        $end->setTime(23, 59, 59);
581
582
        $groupId = current($result['groups']);
583
        $userId = current($result['users']);
584
585
        $events = $agenda->getEvents(
586
            $start->getTimestamp(),
587
            $end->getTimestamp(),
588
            $this->course->getId(),
589
            $groupId,
590
            $userId,
591
            'array'
592
        );
593
594
        if (!is_array($events)) {
595
            return [];
596
        }
597
598
        $webPath = api_get_path(WEB_PATH);
599
600
        return array_map(
601
            function ($event) use ($webPath) {
602
                return [
603
                    'id' => (int) $event['unique_id'],
604
                    'title' => $event['title'],
605
                    'content' => str_replace('src="/', 'src="'.$webPath, $event['description']),
606
                    'startDate' => $event['start_date_localtime'],
607
                    'endDate' => $event['end_date_localtime'],
608
                    'isAllDay' => $event['allDay'] ? true : false,
609
                ];
610
            },
611
            $events
612
        );
613
    }
614
615
    /**
616
     * @throws Exception
617
     *
618
     * @return array
619
     */
620
    public function getCourseNotebooks()
621
    {
622
        $em = Database::getManager();
623
        /** @var CNotebookRepository $notebooksRepo */
624
        $notebooksRepo = $em->getRepository('ChamiloCourseBundle:CNotebook');
625
        $notebooks = $notebooksRepo->findByUser($this->user, $this->course, $this->session);
626
627
        return array_map(
628
            function (CNotebook $notebook) {
629
                return [
630
                    'id' => $notebook->getIid(),
631
                    'title' => $notebook->getTitle(),
632
                    'description' => $notebook->getDescription(),
633
                    'creationDate' => api_format_date(
634
                        $notebook->getCreationDate()->getTimestamp()
635
                    ),
636
                    'updateDate' => api_format_date(
637
                        $notebook->getUpdateDate()->getTimestamp()
638
                    ),
639
                ];
640
            },
641
            $notebooks
642
        );
643
    }
644
645
    /**
646
     * @throws Exception
647
     *
648
     * @return array
649
     */
650
    public function getCourseForumCategories()
651
    {
652
        $sessionId = $this->session ? $this->session->getId() : 0;
653
        $webCoursePath = api_get_path(WEB_COURSE_PATH).$this->course->getDirectory().'/upload/forum/images/';
654
655
        require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
656
657
        $categoriesFullData = get_forum_categories('', $this->course->getId(), $sessionId);
658
        $categories = [];
659
        $includeGroupsForums = api_get_setting('display_groups_forum_in_general_tool') === 'true';
660
        $forumsFullData = get_forums('', $this->course->getCode(), $includeGroupsForums, $sessionId);
661
        $forums = [];
662
663
        foreach ($forumsFullData as $forumId => $forumInfo) {
664
            $forum = [
665
                'id' => (int) $forumInfo['iid'],
666
                'catId' => (int) $forumInfo['forum_category'],
667
                'title' => $forumInfo['forum_title'],
668
                'description' => $forumInfo['forum_comment'],
669
                'image' => $forumInfo['forum_image'] ? ($webCoursePath.$forumInfo['forum_image']) : '',
670
                'numberOfThreads' => isset($forumInfo['number_of_threads']) ? intval(
671
                    $forumInfo['number_of_threads']
672
                ) : 0,
673
                'lastPost' => null,
674
            ];
675
676
            $lastPostInfo = get_last_post_information($forumId, false, $this->course->getId(), $sessionId);
677
678
            if ($lastPostInfo) {
679
                $forum['lastPost'] = [
680
                    'date' => api_convert_and_format_date($lastPostInfo['last_post_date']),
681
                    'user' => api_get_person_name(
682
                        $lastPostInfo['last_poster_firstname'],
683
                        $lastPostInfo['last_poster_lastname']
684
                    ),
685
                ];
686
            }
687
688
            $forums[] = $forum;
689
        }
690
691
        foreach ($categoriesFullData as $category) {
692
            $categoryForums = array_filter(
693
                $forums,
694
                function (array $forum) use ($category) {
695
                    if ($forum['catId'] != $category['cat_id']) {
696
                        return false;
697
                    }
698
699
                    return true;
700
                }
701
            );
702
703
            $categories[] = [
704
                'id' => (int) $category['iid'],
705
                'title' => $category['cat_title'],
706
                'catId' => (int) $category['cat_id'],
707
                'description' => $category['cat_comment'],
708
                'forums' => $categoryForums,
709
                'courseId' => $this->course->getId(),
710
            ];
711
        }
712
713
        return $categories;
714
    }
715
716
    /**
717
     * @param int $forumId
718
     *
719
     * @throws Exception
720
     *
721
     * @return array
722
     */
723
    public function getCourseForum($forumId)
724
    {
725
        require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
726
727
        $sessionId = $this->session ? $this->session->getId() : 0;
728
        $forumInfo = get_forums($forumId, $this->course->getCode(), true, $sessionId);
729
730
        if (!isset($forumInfo['iid'])) {
731
            throw new Exception(get_lang('NoForum'));
732
        }
733
734
        $webCoursePath = api_get_path(WEB_COURSE_PATH).$this->course->getDirectory().'/upload/forum/images/';
735
        $forum = [
736
            'id' => $forumInfo['iid'],
737
            'title' => $forumInfo['forum_title'],
738
            'description' => $forumInfo['forum_comment'],
739
            'image' => $forumInfo['forum_image'] ? ($webCoursePath.$forumInfo['forum_image']) : '',
740
            'threads' => [],
741
        ];
742
743
        $threads = get_threads($forumInfo['iid'], $this->course->getId(), $sessionId);
744
745
        foreach ($threads as $thread) {
746
            $forum['threads'][] = [
747
                'id' => $thread['iid'],
748
                'title' => $thread['thread_title'],
749
                'lastEditDate' => api_convert_and_format_date($thread['lastedit_date'], DATE_TIME_FORMAT_LONG_24H),
750
                'numberOfReplies' => $thread['thread_replies'],
751
                'numberOfViews' => $thread['thread_views'],
752
                'author' => api_get_person_name($thread['firstname'], $thread['lastname']),
753
            ];
754
        }
755
756
        return $forum;
757
    }
758
759
    /**
760
     * @param int $forumId
761
     * @param int $threadId
762
     *
763
     * @return array
764
     */
765
    public function getCourseForumThread($forumId, $threadId)
766
    {
767
        require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
768
769
        $sessionId = $this->session ? $this->session->getId() : 0;
770
        $threadInfo = get_thread_information($forumId, $threadId, $sessionId);
771
772
        $thread = [
773
            'id' => intval($threadInfo['iid']),
774
            'cId' => intval($threadInfo['c_id']),
775
            'title' => $threadInfo['thread_title'],
776
            'forumId' => intval($threadInfo['forum_id']),
777
            'posts' => [],
778
        ];
779
780
        $forumInfo = get_forums($threadInfo['forum_id'], $this->course->getCode(), true, $sessionId);
781
        $postsInfo = getPosts($forumInfo, $threadInfo['iid'], 'ASC');
782
783
        foreach ($postsInfo as $postInfo) {
784
            $thread['posts'][] = [
785
                'id' => $postInfo['iid'],
786
                'title' => $postInfo['post_title'],
787
                'text' => $postInfo['post_text'],
788
                'author' => api_get_person_name($postInfo['firstname'], $postInfo['lastname']),
789
                'date' => api_convert_and_format_date($postInfo['post_date'], DATE_TIME_FORMAT_LONG_24H),
790
                'parentId' => $postInfo['post_parent_id'],
791
            ];
792
        }
793
794
        return $thread;
795
    }
796
797
    /**
798
     * @return array
799
     */
800
    public function getUserProfile()
801
    {
802
        $pictureInfo = UserManager::get_user_picture_path_by_id($this->user->getId(), 'web');
803
804
        $result = [
805
            'pictureUri' => $pictureInfo['dir'].$pictureInfo['file'],
806
            'id' => $this->user->getId(),
807
            'status' => $this->user->getStatus(),
808
            'fullName' => UserManager::formatUserFullName($this->user),
809
            'username' => $this->user->getUsername(),
810
            'officialCode' => $this->user->getOfficialCode(),
811
            'phone' => $this->user->getPhone(),
812
            'extra' => [],
813
        ];
814
815
        $fieldValue = new ExtraFieldValue('user');
816
        $extraInfo = $fieldValue->getAllValuesForAnItem($this->user->getId(), true);
817
818
        foreach ($extraInfo as $extra) {
819
            /** @var ExtraFieldValues $extraValue */
820
            $extraValue = $extra['value'];
821
            $result['extra'][] = [
822
                'title' => $extraValue->getField()->getDisplayText(true),
823
                'value' => $extraValue->getValue(),
824
            ];
825
        }
826
827
        return $result;
828
    }
829
830
    public function getCourseLpProgress()
831
    {
832
        $sessionId = $this->session ? $this->session->getId() : 0;
833
        $userId = $this->user->getId();
834
835
        /*$sessionId = $this->session ? $this->session->getId() : 0;
836
        $courseId = $this->course->getId();*/
837
838
        $result = Tracking::getCourseLpProgress($userId, $sessionId);
839
840
        return [$result];
841
    }
842
843
    /**
844
     * @throws Exception
845
     *
846
     * @return array
847
     */
848
    public function getCourseLearnPaths()
849
    {
850
        $sessionId = $this->session ? $this->session->getId() : 0;
851
        $categoriesTempList = learnpath::getCategories($this->course->getId());
852
853
        $categoryNone = new CLpCategory();
854
        $categoryNone->setId(0);
855
        $categoryNone->setName(get_lang('WithOutCategory'));
856
        $categoryNone->setPosition(0);
857
858
        $categories = array_merge([$categoryNone], $categoriesTempList);
859
        $categoryData = [];
860
861
        /** @var CLpCategory $category */
862
        foreach ($categories as $category) {
863
            $learnPathList = new LearnpathList(
864
                $this->user->getId(),
865
                api_get_course_info($this->course->getCode()),
866
                $sessionId,
867
                null,
868
                false,
869
                $category->getId()
870
            );
871
872
            $flatLpList = $learnPathList->get_flat_list();
873
874
            if (empty($flatLpList)) {
875
                continue;
876
            }
877
878
            $listData = [];
879
880
            foreach ($flatLpList as $lpId => $lpDetails) {
881
                if ($lpDetails['lp_visibility'] == 0) {
882
                    continue;
883
                }
884
885
                if (!learnpath::is_lp_visible_for_student(
886
                    $lpId,
887
                    $this->user->getId(),
888
                    api_get_course_info($this->course->getCode()),
889
                    $sessionId
890
                )) {
891
                    continue;
892
                }
893
894
                $timeLimits = false;
895
896
                // This is an old LP (from a migration 1.8.7) so we do nothing
897
                if (empty($lpDetails['created_on']) && empty($lpDetails['modified_on'])) {
898
                    $timeLimits = false;
899
                }
900
901
                // Checking if expired_on is ON
902
                if (!empty($lpDetails['expired_on'])) {
903
                    $timeLimits = true;
904
                }
905
906
                if ($timeLimits) {
907
                    if (!empty($lpDetails['publicated_on']) && !empty($lpDetails['expired_on'])) {
908
                        $startTime = api_strtotime($lpDetails['publicated_on'], 'UTC');
909
                        $endTime = api_strtotime($lpDetails['expired_on'], 'UTC');
910
                        $now = time();
911
                        $isActiveTime = false;
912
913
                        if ($now > $startTime && $endTime > $now) {
914
                            $isActiveTime = true;
915
                        }
916
917
                        if (!$isActiveTime) {
918
                            continue;
919
                        }
920
                    }
921
                }
922
923
                $progress = learnpath::getProgress($lpId, $this->user->getId(), $this->course->getId(), $sessionId);
924
925
                $listData[] = [
926
                    'id' => $lpId,
927
                    'title' => Security::remove_XSS($lpDetails['lp_name']),
928
                    'progress' => $progress,
929
                    'url' => api_get_path(WEB_CODE_PATH).'webservices/api/v2.php?'.http_build_query(
930
                        [
931
                            'hash' => $this->encodeParams(
932
                                [
933
                                    'action' => 'course_learnpath',
934
                                    'lp_id' => $lpId,
935
                                    'course' => $this->course->getId(),
936
                                    'session' => $sessionId,
937
                                ]
938
                            ),
939
                        ]
940
                    ),
941
                ];
942
            }
943
944
            if (empty($listData)) {
945
                continue;
946
            }
947
948
            $categoryData[] = [
949
                'id' => $category->getId(),
950
                'name' => $category->getName(),
951
                'learnpaths' => $listData,
952
            ];
953
        }
954
955
        return $categoryData;
956
    }
957
958
    /**
959
     * Start login for a user. Then make a redirect to show the learnpath.
960
     *
961
     * @param int $lpId
962
     */
963
    public function showLearningPath($lpId)
964
    {
965
        $loggedUser['user_id'] = $this->user->getId();
966
        $loggedUser['status'] = $this->user->getStatus();
967
        $loggedUser['uidReset'] = true;
968
        $sessionId = $this->session ? $this->session->getId() : 0;
969
970
        ChamiloSession::write('_user', $loggedUser);
971
        Login::init_user($this->user->getId(), true);
972
973
        $url = api_get_path(WEB_CODE_PATH).'lp/lp_controller.php?'.http_build_query(
974
            [
975
                'cidReq' => $this->course->getCode(),
976
                'id_session' => $sessionId,
977
                'gidReq' => 0,
978
                'gradebook' => 0,
979
                'origin' => '',
980
                'action' => 'view',
981
                'lp_id' => (int) $lpId,
982
                'isStudentView' => 'true',
983
            ]
984
        );
985
986
        header("Location: $url");
987
        exit;
988
    }
989
990
    /**
991
     * @param int $forumId
992
     *
993
     * @return array
994
     */
995
    public function saveForumPost(array $postValues, $forumId)
996
    {
997
        require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
998
999
        $forum = get_forums($forumId, $this->course->getCode());
1000
        store_reply($forum, $postValues, $this->course->getId(), $this->user->getId());
1001
1002
        return [
1003
            'registered' => true,
1004
        ];
1005
    }
1006
1007
    /**
1008
     * Get the list of sessions for current user.
1009
     *
1010
     * @return array the sessions list
1011
     */
1012
    public function getUserSessions()
1013
    {
1014
        $data = [];
1015
        $sessionsByCategory = UserManager::get_sessions_by_category($this->user->getId(), false);
1016
1017
        foreach ($sessionsByCategory as $category) {
1018
            $categorySessions = [];
1019
1020
            foreach ($category['sessions'] as $sessions) {
1021
                $sessionCourses = [];
1022
1023
                foreach ($sessions['courses'] as $course) {
1024
                    $courseInfo = api_get_course_info_by_id($course['real_id']);
1025
                    $teachers = SessionManager::getCoachesByCourseSessionToString(
1026
                        $sessions['session_id'],
1027
                        $course['real_id']
1028
                    );
1029
1030
                    $sessionCourses[] = [
1031
                        'id' => $courseInfo['real_id'],
1032
                        'title' => $courseInfo['title'],
1033
                        'code' => $courseInfo['code'],
1034
                        'directory' => $courseInfo['directory'],
1035
                        'pictureUrl' => $courseInfo['course_image_large'],
1036
                        'urlPicture' => $courseInfo['course_image_large'],
1037
                        'teachers' => $teachers,
1038
                    ];
1039
                }
1040
1041
                $sessionBox = Display::getSessionTitleBox($sessions['session_id']);
1042
1043
                $categorySessions[] = [
1044
                    'name' => $sessionBox['title'],
1045
                    'id' => $sessions['session_id'],
1046
                    'date' => $sessionBox['dates'],
1047
                    'duration' => isset($sessionBox['duration']) ? $sessionBox['duration'] : null,
1048
                    'courses' => $sessionCourses,
1049
                ];
1050
            }
1051
1052
            $data[] = [
1053
                'id' => $category['session_category']['id'],
1054
                'name' => $category['session_category']['name'],
1055
                'sessions' => $categorySessions,
1056
            ];
1057
        }
1058
1059
        return $data;
1060
    }
1061
1062
    /**
1063
     * @param string $subject
1064
     * @param string $text
1065
     *
1066
     * @return array
1067
     */
1068
    public function saveUserMessage($subject, $text, array $receivers)
1069
    {
1070
        foreach ($receivers as $userId) {
1071
            MessageManager::send_message($userId, $subject, $text);
1072
        }
1073
1074
        return [
1075
            'sent' => true,
1076
        ];
1077
    }
1078
1079
    /**
1080
     * @param string $search
1081
     *
1082
     * @return array
1083
     */
1084
    public function getMessageUsers($search)
1085
    {
1086
        $repo = UserManager::getRepository();
1087
1088
        $users = $repo->findUsersToSendMessage($this->user->getId(), $search);
1089
        $showEmail = api_get_setting('show_email_addresses') === 'true';
1090
        $data = [];
1091
1092
        /** @var User $user */
1093
        foreach ($users as $user) {
1094
            $userName = UserManager::formatUserFullName($user);
1095
1096
            if ($showEmail) {
1097
                $userName .= " ({$user->getEmail()})";
1098
            }
1099
1100
            $data[] = [
1101
                'id' => $user->getId(),
1102
                'name' => $userName,
1103
            ];
1104
        }
1105
1106
        return $data;
1107
    }
1108
1109
    /**
1110
     * @param string $title
1111
     * @param string $text
1112
     *
1113
     * @return array
1114
     */
1115
    public function saveCourseNotebook($title, $text)
1116
    {
1117
        $values = ['note_title' => $title, 'note_comment' => $text];
1118
        $sessionId = $this->session ? $this->session->getId() : 0;
1119
1120
        $noteBookId = NotebookManager::save_note(
1121
            $values,
1122
            $this->user->getId(),
1123
            $this->course->getId(),
1124
            $sessionId
1125
        );
1126
1127
        return [
1128
            'registered' => $noteBookId,
1129
        ];
1130
    }
1131
1132
    /**
1133
     * @param int $forumId
1134
     *
1135
     * @return array
1136
     */
1137
    public function saveForumThread(array $values, $forumId)
1138
    {
1139
        require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
1140
1141
        $sessionId = $this->session ? $this->session->getId() : 0;
1142
        $forum = get_forums($forumId, $this->course->getCode(), true, $sessionId);
1143
        $courseInfo = api_get_course_info($this->course->getCode());
1144
        $thread = store_thread($forum, $values, $courseInfo, false, $this->user->getId(), $sessionId);
1145
1146
        return [
1147
            'registered' => $thread->getIid(),
1148
        ];
1149
    }
1150
1151
    /**
1152
     * @return array
1153
     */
1154
    public function getUsersCampus(array $params)
1155
    {
1156
        $conditions = [
1157
            'status' => $params['status'],
1158
        ];
1159
        $idCampus = $params['id_campus'];
1160
        $users = UserManager::get_user_list($conditions, ['firstname'], false, false, $idCampus);
1161
        $list = [];
1162
        foreach ($users as $item) {
1163
            $listTemp = [
1164
                'id' => $item['user_id'],
1165
                'firstname' => $item['firstname'],
1166
                'lastname' => $item['lastname'],
1167
                'email' => $item['email'],
1168
            ];
1169
            $list[] = $listTemp;
1170
        }
1171
1172
        return $list;
1173
    }
1174
1175
    /**
1176
     * @return array
1177
     */
1178
    public function getCoursesCampus(array $params)
1179
    {
1180
        $idCampus = $params['id_campus'];
1181
1182
        $courseList = CourseManager::get_courses_list(
1183
            0, //offset
1184
            0, //howMany
1185
            1, //$orderby = 1
1186
            'ASC',
1187
            -1, //visibility
1188
            null,
1189
            $idCampus, //$urlId
1190
            true //AlsoSearchCode
1191
        );
1192
1193
        return $courseList;
1194
    }
1195
1196
    /**
1197
     * @return array
1198
     */
1199
    public function addSession(array $params)
1200
    {
1201
        $name = $params['name'];
1202
        $coach_username = (int) $params['coach_username'];
1203
        $startDate = $params['access_start_date'];
1204
        $endDate = $params['access_end_date'];
1205
        $displayStartDate = $startDate;
1206
        $displayEndDate = $endDate;
1207
        $description = $params['description'];
1208
        $idUrlCampus = $params['id_campus'];
1209
        $extraFields = isset($params['extra']) ? $params['extra'] : [];
1210
1211
        $return = SessionManager::create_session(
1212
            $name,
1213
            $startDate,
1214
            $endDate,
1215
            $displayStartDate,
1216
            $displayEndDate,
1217
            null,
1218
            null,
1219
            $coach_username,
1220
            null,
1221
            1,
1222
            false,
1223
            null,
1224
            $description,
1225
            1,
1226
            $extraFields,
1227
            null,
1228
            false,
1229
            $idUrlCampus
1230
        );
1231
1232
        if ($return) {
1233
            $out = [
1234
                'status' => true,
1235
                'message' => get_lang('ANewSessionWasCreated'),
1236
                'id_session' => $return,
1237
            ];
1238
        } else {
1239
            $out = [
1240
                'status' => false,
1241
                'message' => get_lang('ErrorOccurred'),
1242
            ];
1243
        }
1244
1245
        return $out;
1246
    }
1247
1248
    /**
1249
     * @return array
1250
     */
1251
    public function addCourse(array $courseParam)
1252
    {
1253
        $results = [];
1254
        $idCampus = isset($courseParam['id_campus']) ? $courseParam['id_campus'] : 1;
1255
        $title = isset($courseParam['title']) ? $courseParam['title'] : '';
1256
        $wantedCode = isset($courseParam['wanted_code']) ? $courseParam['wanted_code'] : null;
1257
        $diskQuota = isset($courseParam['disk_quota']) ? $courseParam['disk_quota'] : '100';
1258
        $visibility = isset($courseParam['visibility']) ? (int) $courseParam['visibility'] : null;
1259
1260
        if (isset($courseParam['visibility'])) {
1261
            if ($courseParam['visibility'] &&
1262
                $courseParam['visibility'] >= 0 &&
1263
                $courseParam['visibility'] <= 3
1264
            ) {
1265
                $visibility = (int) $courseParam['visibility'];
1266
            }
1267
        }
1268
1269
        $params = [];
1270
        $params['title'] = $title;
1271
        $params['wanted_code'] = 'CAMPUS_'.$idCampus.'_'.$wantedCode;
1272
        $params['user_id'] = $this->user->getId();
1273
        $params['visibility'] = $visibility;
1274
        $params['disk_quota'] = $diskQuota;
1275
1276
        $courseInfo = CourseManager::create_course($params, $params['user_id'], $idCampus);
1277
1278
        if (!empty($courseInfo)) {
1279
            $results['status'] = true;
1280
            $results['code_course'] = $courseInfo['code'];
1281
            $results['title_course'] = $courseInfo['title'];
1282
            $results['message'] = sprintf(get_lang('CourseXAdded'), $courseInfo['code']);
1283
        } else {
1284
            $results['status'] = false;
1285
            $results['message'] = get_lang('CourseCreationFailed');
1286
        }
1287
1288
        return $results;
1289
    }
1290
1291
    /**
1292
     * @param $userParam
1293
     *
1294
     * @throws Exception
1295
     *
1296
     * @return array
1297
     */
1298
    public function addUser($userParam)
1299
    {
1300
        $firstName = $userParam['firstname'];
1301
        $lastName = $userParam['lastname'];
1302
        $status = $userParam['status'];
1303
        $email = $userParam['email'];
1304
        $loginName = $userParam['loginname'];
1305
        $password = $userParam['password'];
1306
1307
        $official_code = '';
1308
        $language = '';
1309
        $phone = '';
1310
        $picture_uri = '';
1311
        $auth_source = PLATFORM_AUTH_SOURCE;
1312
        $expiration_date = '';
1313
        $active = 1;
1314
        $hr_dept_id = 0;
1315
        $extra = null;
1316
1317
        $original_user_id_name = $userParam['original_user_id_name'];
1318
        $original_user_id_value = $userParam['original_user_id_value'];
1319
1320
        $extra_list = isset($userParam['extra']) ? $userParam['extra'] : [];
1321
        if (isset($userParam['language'])) {
1322
            $language = $userParam['language'];
1323
        }
1324
        if (isset($userParam['phone'])) {
1325
            $phone = $userParam['phone'];
1326
        }
1327
        if (isset($userParam['expiration_date'])) {
1328
            $expiration_date = $userParam['expiration_date'];
1329
        }
1330
1331
        // Default language.
1332
        if (empty($language)) {
1333
            $language = api_get_setting('platformLanguage');
1334
        }
1335
1336
        // First check wether the login already exists.
1337
        if (!UserManager::is_username_available($loginName)) {
1338
            throw new Exception(get_lang('UserNameNotAvailable'));
1339
        }
1340
1341
        $userId = UserManager::create_user(
1342
            $firstName,
1343
            $lastName,
1344
            $status,
1345
            $email,
1346
            $loginName,
1347
            $password,
1348
            $official_code,
1349
            $language,
1350
            $phone,
1351
            $picture_uri,
1352
            $auth_source,
1353
            $expiration_date,
1354
            $active,
1355
            $hr_dept_id
1356
        );
1357
1358
        if (empty($userId)) {
1359
            throw new Exception(get_lang('UserNotRegistered'));
1360
        }
1361
1362
        if (api_is_multiple_url_enabled()) {
1363
            if (api_get_current_access_url_id() != -1) {
1364
                UrlManager::add_user_to_url(
1365
                    $userId,
1366
                    api_get_current_access_url_id()
1367
                );
1368
            } else {
1369
                UrlManager::add_user_to_url($userId, 1);
1370
            }
1371
        } else {
1372
            // We add by default the access_url_user table with access_url_id = 1
1373
            UrlManager::add_user_to_url($userId, 1);
1374
        }
1375
1376
        // Save new field label into user_field table.
1377
        UserManager::create_extra_field(
1378
            $original_user_id_name,
1379
            1,
1380
            $original_user_id_name,
1381
            ''
1382
        );
1383
        // Save the external system's id into user_field_value table.
1384
        UserManager::update_extra_field_value(
1385
            $userId,
1386
            $original_user_id_name,
1387
            $original_user_id_value
1388
        );
1389
1390
        if (is_array($extra_list) && count($extra_list) > 0) {
1391
            foreach ($extra_list as $extra) {
1392
                $extra_field_name = $extra['field_name'];
1393
                $extra_field_value = $extra['field_value'];
1394
                // Save new field label into user_field table.
1395
                UserManager::create_extra_field(
1396
                    $extra_field_name,
1397
                    1,
1398
                    $extra_field_name,
1399
                    ''
1400
                );
1401
                // Save the external system's id into user_field_value table.
1402
                UserManager::update_extra_field_value(
1403
                    $userId,
1404
                    $extra_field_name,
1405
                    $extra_field_value
1406
                );
1407
            }
1408
        }
1409
1410
        return [$userId];
1411
    }
1412
1413
    /**
1414
     * Subscribe User to Course.
1415
     *
1416
     * @param array $params
1417
     *
1418
     * @return array
1419
     */
1420
    public function subscribeUserToCourse($params)
1421
    {
1422
        $course_id = $params['course_id'];
1423
        $course_code = $params['course_code'];
1424
        $user_id = $params['user_id'];
1425
        if (!$course_id && !$course_code) {
1426
            return [false];
1427
        }
1428
        if (!$course_code) {
1429
            $course_code = CourseManager::get_course_code_from_course_id($course_id);
1430
        }
1431
        if (CourseManager::subscribeUser($user_id, $course_code)) {
1432
            return [true];
1433
        } else {
1434
            return [false];
1435
        }
1436
1437
        return [true];
0 ignored issues
show
Unused Code introduced by
return array(true) is not reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
1438
    }
1439
1440
    public function deleteUserMessage($messageId, $messageType)
1441
    {
1442
        if ($messageType === "sent") {
1443
            return MessageManager::delete_message_by_user_sender($this->user->getId(), $messageId);
1444
        } else {
1445
            return MessageManager::delete_message_by_user_receiver($this->user->getId(), $messageId);
1446
        }
1447
    }
1448
1449
    public function setMessageRead($messageId)
1450
    {
1451
        MessageManager::update_message($this->user->getId(), $messageId);
1452
    }
1453
1454
    /**
1455
     * Add Campus Virtual.
1456
     *
1457
     * @param array Params Campus
1458
     *
1459
     * @return array
1460
     */
1461
    public function createCampusURL($params)
1462
    {
1463
        $urlCampus = Security::remove_XSS($params['url']);
1464
        $description = Security::remove_XSS($params['description']);
1465
1466
        $active = isset($params['active']) ? intval($params['active']) : 0;
1467
        $num = UrlManager::url_exist($urlCampus);
1468
        if ($num == 0) {
1469
            // checking url
1470
            if (substr($urlCampus, strlen($urlCampus) - 1, strlen($urlCampus)) == '/') {
1471
                $idCampus = UrlManager::add($urlCampus, $description, $active, true);
1472
            } else {
1473
                //create
1474
                $idCampus = UrlManager::add($urlCampus.'/', $description, $active, true);
1475
            }
1476
1477
            return [
1478
                'status' => true,
1479
                'id_campus' => $idCampus,
1480
            ];
1481
        }
1482
1483
        return [
1484
            'status' => false,
1485
            'id_campus' => 0,
1486
        ];
1487
    }
1488
1489
    /**
1490
     * Edit Campus Virtual.
1491
     *
1492
     * @param array Params Campus
1493
     *
1494
     * @return array
1495
     */
1496
    public function editCampusURL($params)
1497
    {
1498
        $urlCampus = Security::remove_XSS($params['url']);
1499
        $description = Security::remove_XSS($params['description']);
1500
1501
        $active = isset($params['active']) ? intval($params['active']) : 0;
1502
        $url_id = isset($params['id']) ? intval($params['id']) : 0;
1503
1504
        if (!empty($url_id)) {
1505
            //we can't change the status of the url with id=1
1506
            if ($url_id == 1) {
1507
                $active = 1;
1508
            }
1509
            //checking url
1510
            if (substr($urlCampus, strlen($urlCampus) - 1, strlen($urlCampus)) == '/') {
1511
                UrlManager::update($url_id, $urlCampus, $description, $active);
1512
            } else {
1513
                UrlManager::update($url_id, $urlCampus.'/', $description, $active);
1514
            }
1515
1516
            return [true];
1517
        }
1518
1519
        return [false];
1520
    }
1521
1522
    /**
1523
     * Delete Campus Virtual.
1524
     *
1525
     * @param array Params Campus
1526
     *
1527
     * @return array
1528
     */
1529
    public function deleteCampusURL($params)
1530
    {
1531
        $url_id = isset($params['id']) ? intval($params['id']) : 0;
1532
1533
        $result = UrlManager::delete($url_id);
1534
        if ($result) {
1535
            return [
1536
                'status' => true,
1537
                'message' => get_lang('URLDeleted'),
1538
            ];
1539
        } else {
1540
            return [
1541
                'status' => false,
1542
                'message' => get_lang('Error'),
1543
            ];
1544
        }
1545
    }
1546
1547
    /**
1548
     * @throws Exception
1549
     *
1550
     * @return array
1551
     */
1552
    public function addCoursesSession(array $params)
1553
    {
1554
        $sessionId = $params['id_session'];
1555
        $courseList = $params['list_courses'];
1556
1557
        $result = SessionManager::add_courses_to_session(
1558
            $sessionId,
1559
            $courseList,
1560
            true,
1561
            false
1562
        );
1563
1564
        if ($result) {
1565
            return [
1566
                'status' => $result,
1567
                'message' => get_lang('Updated'),
1568
            ];
1569
        } else {
1570
            return [
1571
                'status' => $result,
1572
                'message' => get_lang('ErrorOccurred'),
1573
            ];
1574
        }
1575
    }
1576
1577
    /**
1578
     * @return array
1579
     */
1580
    public function addUsersSession(array $params)
1581
    {
1582
        $sessionId = $params['id_session'];
1583
        $userList = $params['list_users'];
1584
1585
        if (!is_array($userList)) {
1586
            $userList = [];
1587
        }
1588
1589
        SessionManager::subscribeUsersToSession(
1590
            $sessionId,
1591
            $userList,
1592
            null,
1593
            false
1594
        );
1595
1596
        return [
1597
            'status' => true,
1598
            'message' => get_lang('UsersAdded'),
1599
        ];
1600
    }
1601
1602
    /**
1603
     * Creates a session from a model session.
1604
     *
1605
     * @param $modelSessionId
1606
     * @param $sessionName
1607
     * @param $startDate
1608
     * @param $endDate
1609
     *
1610
     * @throws Exception
1611
     *
1612
     * @return int, the id of the new session
1613
     */
1614
    public function createSessionFromModel($modelSessionId, $sessionName, $startDate, $endDate, array $extraFields = [])
1615
    {
1616
        if (empty($modelSessionId) || empty($sessionName) || empty($startDate) || empty($endDate)) {
1617
            throw new Exception(get_lang('NoData'));
1618
        }
1619
1620
        if (!SessionManager::isValidId($modelSessionId)) {
1621
            throw new Exception(get_lang('ModelSessionDoesNotExist'));
1622
        }
1623
1624
        $modelSession = SessionManager::fetch($modelSessionId);
1625
1626
        $modelSession['accessUrlId'] = 1;
1627
        if (api_is_multiple_url_enabled()) {
1628
            if (api_get_current_access_url_id() != -1) {
1629
                $modelSession['accessUrlId'] = api_get_current_access_url_id();
1630
            }
1631
        }
1632
1633
        $newSessionId = SessionManager::create_session(
1634
            $sessionName,
1635
            $startDate,
1636
            $endDate,
1637
            $startDate,
1638
            $endDate,
1639
            $startDate,
1640
            $endDate,
1641
            $modelSession['id_coach'],
1642
            $modelSession['session_category_id'],
1643
            $modelSession['visibility'],
1644
            false,
1645
            $modelSession['duration'],
1646
            $modelSession['description'],
1647
            $modelSession['show_description'],
1648
            $extraFields,
1649
            $modelSession['session_admin_id'],
1650
            $modelSession['send_subscription_notification'],
1651
            $modelSession['accessUrlId']
1652
        );
1653
1654
        if (empty($newSessionId)) {
1655
            throw new Exception(get_lang('SessionNotRegistered'));
1656
        }
1657
1658
        if (is_string($newSessionId)) {
1659
            throw new Exception($newSessionId);
1660
        }
1661
1662
        $promotionId = $modelSession['promotion_id'];
1663
        if ($promotionId) {
1664
            $sessionList = array_keys(SessionManager::get_all_sessions_by_promotion($promotionId));
1665
            $sessionList[] = $newSessionId;
1666
            SessionManager::subscribe_sessions_to_promotion($modelSession['promotion_id'], $sessionList);
1667
        }
1668
1669
        $modelExtraFields = [];
1670
        $fields = SessionManager::getFilteredExtraFields($modelSessionId);
1671
        if (is_array($fields) and !empty($fields)) {
1672
            foreach ($fields as $field) {
1673
                $modelExtraFields[$field['variable']] = $field['value'];
1674
            }
1675
        }
1676
        $allExtraFields = array_merge($modelExtraFields, $extraFields);
1677
        foreach ($allExtraFields as $name => $value) {
1678
            // SessionManager::update_session_extra_field_value returns false when no row is changed,
1679
            // which can happen since extra field values are initialized by SessionManager::create_session
1680
            // therefore we do not throw an exception when false is returned
1681
            SessionManager::update_session_extra_field_value($newSessionId, $name, $value);
1682
        }
1683
1684
        $courseList = array_keys(SessionManager::get_course_list_by_session_id($modelSessionId));
1685
        if (is_array($courseList)
1686
            && !empty($courseList)
1687
            && !SessionManager::add_courses_to_session($newSessionId, $courseList)) {
1688
            throw new Exception(get_lang('CoursesNotAddedToSession'));
1689
        }
1690
1691
        if (api_is_multiple_url_enabled()) {
1692
            if (api_get_current_access_url_id() != -1) {
1693
                UrlManager::add_session_to_url(
1694
                    $newSessionId,
1695
                    api_get_current_access_url_id()
1696
                );
1697
            } else {
1698
                UrlManager::add_session_to_url($newSessionId, 1);
1699
            }
1700
        } else {
1701
            UrlManager::add_session_to_url($newSessionId, 1);
1702
        }
1703
1704
        return $newSessionId;
1705
    }
1706
1707
    /**
1708
     * subscribes a user to a session.
1709
     *
1710
     * @param int    $sessionId the session id
1711
     * @param string $loginName the user's login name
1712
     *
1713
     * @throws Exception
1714
     *
1715
     * @return boolean, whether it worked
1716
     */
1717
    public function subscribeUserToSessionFromUsername($sessionId, $loginName)
1718
    {
1719
        if (!SessionManager::isValidId($sessionId)) {
1720
            throw new Exception(get_lang('SessionNotFound'));
1721
        }
1722
1723
        $userId = UserManager::get_user_id_from_username($loginName);
1724
        if (false === $userId) {
1725
            throw new Exception(get_lang('UserNotFound'));
1726
        }
1727
1728
        $subscribed = SessionManager::subscribeUsersToSession(
1729
            $sessionId,
1730
            [$userId],
1731
            SESSION_VISIBLE_READ_ONLY,
1732
            false
1733
        );
1734
        if (!$subscribed) {
1735
            throw new Exception(get_lang('UserNotSubscribed'));
1736
        }
1737
1738
        return true;
1739
    }
1740
1741
    /**
1742
     * finds the session which has a specific value in a specific extra field.
1743
     *
1744
     * @param $fieldName
1745
     * @param $fieldValue
1746
     *
1747
     * @throws Exception when no session matched or more than one session matched
1748
     *
1749
     * @return int, the matching session id
1750
     */
1751
    public function getSessionFromExtraField($fieldName, $fieldValue)
1752
    {
1753
        // find sessions that that have value in field
1754
        $valueModel = new ExtraFieldValue('session');
1755
        $sessionIdList = $valueModel->get_item_id_from_field_variable_and_field_value(
1756
            $fieldName,
1757
            $fieldValue,
1758
            false,
1759
            false,
1760
            true
1761
        );
1762
1763
        // throw if none found
1764
        if (empty($sessionIdList)) {
1765
            throw new Exception(get_lang('NoSessionMatched'));
1766
        }
1767
1768
        // throw if more than one found
1769
        if (count($sessionIdList) > 1) {
1770
            throw new Exception(get_lang('MoreThanOneSessionMatched'));
1771
        }
1772
1773
        // return sessionId
1774
        return intval($sessionIdList[0]['item_id']);
1775
    }
1776
1777
    /**
1778
     * updates a user identified by its login name.
1779
     *
1780
     * @param array $parameters
1781
     *
1782
     * @throws Exception on failure
1783
     *
1784
     * @return boolean, true on success
1785
     */
1786
    public function updateUserFromUserName($parameters)
1787
    {
1788
        // find user
1789
        $userId = null;
1790
        if (!is_array($parameters) || empty($parameters)) {
1791
            throw new Exception('NoData');
1792
        }
1793
        foreach ($parameters as $name => $value) {
1794
            if (strtolower($name) === 'loginname') {
1795
                $userId = UserManager::get_user_id_from_username($value);
1796
                if (false === $userId) {
1797
                    throw new Exception(get_lang('UserNotFound'));
1798
                }
1799
                break;
1800
            }
1801
        }
1802
        if (is_null($userId)) {
1803
            throw new Exception(get_lang('NoData'));
1804
        }
1805
        /** @var User $user */
1806
        $user = UserManager::getRepository()->find($userId);
1807
        if (empty($user)) {
1808
            throw new Exception(get_lang('CouldNotLoadUser'));
1809
        }
1810
1811
        // tell the world we are about to update a user
1812
        $hook = HookUpdateUser::create();
1813
        if (!empty($hook)) {
1814
            $hook->notifyUpdateUser(HOOK_EVENT_TYPE_PRE);
1815
        }
1816
1817
        // apply submitted modifications
1818
        foreach ($parameters as $name => $value) {
1819
            switch (strtolower($name)) {
1820
                case 'email':
1821
                    $user->setEmail($value);
1822
                    break;
1823
                case 'enabled':
1824
                    $user->setEnabled($value);
1825
                    break;
1826
                case 'lastname':
1827
                    $user->setLastname($value);
1828
                    break;
1829
                case 'firstname':
1830
                    $user->setFirstname($value);
1831
                    break;
1832
                case 'phone':
1833
                    $user->setPhone($value);
1834
                    break;
1835
                case 'address':
1836
                    $user->setAddress($value);
1837
                    break;
1838
                case 'roles':
1839
                    $user->setRoles($value);
1840
                    break;
1841
                case 'profile_completed':
1842
                    $user->setProfileCompleted($value);
1843
                    break;
1844
                case 'auth_source':
1845
                    $user->setAuthSource($value);
1846
                    break;
1847
                case 'status':
1848
                    $user->setStatus($value);
1849
                    break;
1850
                case 'official_code':
1851
                    $user->setOfficialCode($value);
1852
                    break;
1853
                case 'picture_uri':
1854
                    $user->setPictureUri($value);
1855
                    break;
1856
                case 'creator_id':
1857
                    $user->setCreatorId($value);
1858
                    break;
1859
                case 'competences':
1860
                    $user->setCompetences($value);
1861
                    break;
1862
                case 'diplomas':
1863
                    $user->setDiplomas($value);
1864
                    break;
1865
                case 'openarea':
1866
                    $user->setOpenArea($value);
1867
                    break;
1868
                case 'teach':
1869
                    $user->setTeach($value);
1870
                    break;
1871
                case 'productions':
1872
                    $user->setProductions($value);
1873
                    break;
1874
                case 'language':
1875
                    $languages = api_get_languages();
1876
                    if (!in_array($value, $languages['folder'])) {
1877
                        throw new Exception(get_lang('LanguageUnavailable'));
1878
                    }
1879
                    $user->setLanguage($value);
1880
                    break;
1881
                case 'registration_date':
1882
                    $user->setRegistrationDate($value);
1883
                    break;
1884
                case 'expiration_date':
1885
                    $user->setExpirationDate(
1886
                        new DateTime(
1887
                            api_get_utc_datetime($value),
1888
                            new DateTimeZone('UTC')
1889
                        )
1890
                    );
1891
                    break;
1892
                case 'active':
1893
                    // see UserManager::update_user() usermanager.lib.php:1205
1894
                    if ($user->getActive() != $value) {
1895
                        $user->setActive($value);
1896
                        Event::addEvent($value ? LOG_USER_ENABLE : LOG_USER_DISABLE, LOG_USER_ID, $userId);
1897
                    }
1898
                    break;
1899
                case 'openid':
1900
                    $user->setOpenId($value);
1901
                    break;
1902
                case 'theme':
1903
                    $user->setTheme($value);
1904
                    break;
1905
                case 'hr_dept_id':
1906
                    $user->setHrDeptId($value);
1907
                    break;
1908
                case 'extra':
1909
                    if (is_array($value)) {
1910
                        if (count($value) > 0) {
1911
                            if (is_array($value[0])) {
1912
                                foreach ($value as $field) {
1913
                                    $fieldName = $field['field_name'];
1914
                                    $fieldValue = $field['field_value'];
1915
                                    if (!isset($fieldName) || !isset($fieldValue) ||
1916
                                        !UserManager::update_extra_field_value($userId, $fieldName, $fieldValue)) {
1917
                                        throw new Exception(get_lang('CouldNotUpdateExtraFieldValue').': '.print_r($field, true));
1918
                                    }
1919
                                }
1920
                            } else {
1921
                                foreach ($value as $fieldName => $fieldValue) {
1922
                                    if (!UserManager::update_extra_field_value($userId, $fieldName, $fieldValue)) {
1923
                                        throw new Exception(get_lang('CouldNotUpdateExtraFieldValue').': '.$fieldName);
1924
                                    }
1925
                                }
1926
                            }
1927
                        }
1928
                    }
1929
                    break;
1930
                case 'username':
1931
                case 'api_key':
1932
                case 'action':
1933
                case 'loginname':
1934
                    break;
1935
                case 'email_canonical':
1936
                case 'locked':
1937
                case 'expired':
1938
                case 'credentials_expired':
1939
                case 'credentials_expire_at':
1940
                case 'expires_at':
1941
                case 'salt':
1942
                case 'last_login':
1943
                case 'created_at':
1944
                case 'updated_at':
1945
                case 'confirmation_token':
1946
                case 'password_requested_at':
1947
                case 'password': // see UserManager::update_user usermanager.lib.php:1182
1948
                case 'username_canonical':
1949
                default:
1950
                    throw new Exception(get_lang('UnsupportedUpdate')." '$name'");
1951
            }
1952
        }
1953
1954
        // save modifications
1955
        UserManager::getManager()->updateUser($user, true);
1956
1957
        // tell the world we just updated this user
1958
        if (!empty($hook)) {
1959
            $hook->setEventData(['user' => $user]);
1960
            $hook->notifyUpdateUser(HOOK_EVENT_TYPE_POST);
1961
        }
1962
1963
        // invalidate cache for this user
1964
        $cacheAvailable = api_get_configuration_value('apc');
1965
        if ($cacheAvailable === true) {
1966
            $apcVar = api_get_configuration_value('apc_prefix').'userinfo_'.$userId;
1967
            if (apcu_exists($apcVar)) {
1968
                apcu_delete($apcVar);
1969
            }
1970
        }
1971
1972
        return true;
1973
    }
1974
1975
    /**
1976
     * Returns whether a user login name exists.
1977
     *
1978
     * @param string $loginname the user login name
1979
     *
1980
     * @return bool whether the user login name exists
1981
     */
1982
    public function usernameExist($loginname)
1983
    {
1984
        return false !== api_get_user_info_from_username($loginname);
1985
    }
1986
1987
    /**
1988
     * This service roughly matches what the call to MDL's API core_course_get_contents function returns.
1989
     *
1990
     * @return array
1991
     */
1992
    public function getCourseQuizMdlCompat()
1993
    {
1994
        $userId = $this->user->getId();
1995
        $courseId = $this->course->getId();
1996
        $sessionId = $this->session ? $this->session->getId() : 0;
1997
1998
        $toolVisibility = CourseHome::getToolVisibility(TOOL_QUIZ, $courseId, $sessionId);
1999
2000
        $json = [
2001
            "id" => $this->course->getId(),
2002
            "name" => get_lang('Exercises'),
2003
            "visible" => (int) $toolVisibility,
2004
            "summary" => '',
2005
            "summaryformat" => 1,
2006
            "section" => 1,
2007
            "hiddenbynumsections" => 0,
2008
            "uservisible" => $toolVisibility,
2009
            "modules" => [],
2010
        ];
2011
2012
        $quizIcon = Display::return_icon('quiz.png', '', [], ICON_SIZE_SMALL, false, true);
2013
2014
        $json['modules'] = array_map(
2015
            function (array $exercise) use ($quizIcon) {
2016
                return [
2017
                    'id' => $exercise['id'],
2018
                    'url' => $exercise['url'],
2019
                    'name' => $exercise['name'],
2020
                    'instance' => 1,
2021
                    'visible' => 1,
2022
                    'uservisible' => true,
2023
                    'visibleoncoursepage' => 0,
2024
                    'modicon' => $quizIcon,
2025
                    'modname' => 'quiz',
2026
                    'modplural' => get_lang('Exercises'),
2027
                    'availability' => null,
2028
                    'indent' => 0,
2029
                    'onclick' => '',
2030
                    'afterlink' => null,
2031
                    'customdata' => "",
2032
                    'noviewlink' => false,
2033
                    'completion' => (int) ($exercise[1] > 0),
2034
                ];
2035
            },
2036
            Exercise::exerciseGrid(0, '', $userId, $courseId, $sessionId, true)
2037
        );
2038
2039
        return [$json];
2040
    }
2041
2042
    /**
2043
     * @param array $additionalParams Optional
2044
     *
2045
     * @return string
2046
     */
2047
    private function encodeParams(array $additionalParams = [])
2048
    {
2049
        $params = array_merge(
2050
            $additionalParams,
2051
            [
2052
                'api_key' => $this->apiKey,
2053
                'username' => $this->user->getUsername(),
2054
            ]
2055
        );
2056
2057
        return json_encode($params);
2058
    }
2059
}
2060