Passed
Push — 1.11.x ( be8a0c...24974d )
by Yannick
18:24 queued 01:46
created

Rest::getWorkStudentList()   B

Complexity

Conditions 6
Paths 8

Size

Total Lines 61
Code Lines 35

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 35
c 0
b 0
f 0
nc 8
nop 1
dl 0
loc 61
rs 8.7377

How to fix   Long Method   

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 SAVE_GCM_ID = 'gcm_id';
23
    const LOGOUT = 'logout';
24
25
    const GET_USER_MESSAGES = 'user_messages';
26
    const GET_USER_MESSAGES_RECEIVED = 'user_messages_received';
27
    const DELETE_USER_MESSAGE = 'delete_user_message';
28
    const GET_USER_MESSAGES_SENT = 'user_messages_sent';
29
    const GET_COUNT_NEW_MESSAGES = 'get_count_new_messages';
30
    const SET_MESSAGE_READ = 'set_message_read';
31
    const POST_USER_MESSAGE_READ = 'user_message_read';
32
    const POST_USER_MESSAGE_UNREAD = 'user_message_unread';
33
    const SAVE_USER_MESSAGE = 'save_user_message';
34
    const GET_MESSAGE_USERS = 'message_users';
35
36
    const GET_USER_COURSES = 'user_courses';
37
    const GET_USER_SESSIONS = 'user_sessions';
38
39
    const GET_PROFILE = 'user_profile';
40
41
    const GET_COURSE_INFO = 'course_info';
42
    const GET_COURSE_DESCRIPTIONS = 'course_descriptions';
43
    const GET_COURSE_DOCUMENTS = 'course_documents';
44
    const GET_COURSE_ANNOUNCEMENTS = 'course_announcements';
45
    const GET_COURSE_ANNOUNCEMENT = 'course_announcement';
46
    const GET_COURSE_AGENDA = 'course_agenda';
47
    const GET_COURSE_NOTEBOOKS = 'course_notebooks';
48
    const GET_COURSE_FORUM_CATEGORIES = 'course_forumcategories';
49
    const GET_COURSE_FORUM = 'course_forum';
50
    const GET_COURSE_FORUM_THREAD = 'course_forumthread';
51
    const GET_COURSE_LEARNPATHS = 'course_learnpaths';
52
    const GET_COURSE_LEARNPATH = 'course_learnpath';
53
    const GET_COURSE_LP_PROGRESS = 'course_lp_progress';
54
    const GET_COURSE_LINKS = 'course_links';
55
    const GET_COURSE_WORKS = 'course_works';
56
57
    const SAVE_COURSE_NOTEBOOK = 'save_course_notebook';
58
59
    const SAVE_FORUM_POST = 'save_forum_post';
60
    const SAVE_FORUM_THREAD = 'save_forum_thread';
61
    const SET_THREAD_NOTIFY = 'set_thread_notify';
62
63
    const GET_WORK_LIST = 'get_work_list';
64
    const GET_WORK_STUDENTS_WITHOUT_PUBLICATIONS = 'get_work_students_without_publications';
65
    const GET_WORK_USERS = 'get_work_users';
66
    const GET_WORK_STUDENT_LIST = 'get_work_student_list';
67
    const PUT_WORK_STUDENT_ITEM_VISIBILITY = 'put_course_work_visibility';
68
    const DELETE_WORK_STUDENT_ITEM = 'delete_work_student_item';
69
    const DELETE_WORK_CORRECTIONS = 'delete_work_corrections';
70
71
    const VIEW_DOCUMENT_IN_FRAME = 'view_document_in_frame';
72
73
    const VIEW_QUIZ_TOOL = 'view_quiz_tool';
74
75
    const VIEW_SURVEY_TOOL = 'view_survey_tool';
76
77
    const CREATE_CAMPUS = 'add_campus';
78
    const EDIT_CAMPUS = 'edit_campus';
79
    const DELETE_CAMPUS = 'delete_campus';
80
81
    const GET_USERS = 'get_users';
82
    const USERNAME_EXIST = 'username_exist';
83
    const SAVE_USER = 'save_user';
84
    const SAVE_USER_JSON = 'save_user_json';
85
    const UPDATE_USER_FROM_USERNAME = 'update_user_from_username';
86
    const DELETE_USER = 'delete_user';
87
88
    const GET_COURSES = 'get_courses';
89
    const GET_COURSES_FROM_EXTRA_FIELD = 'get_courses_from_extra_field';
90
    const SAVE_COURSE = 'save_course';
91
    const DELETE_COURSE = 'delete_course';
92
93
    const GET_SESSION_FROM_EXTRA_FIELD = 'get_session_from_extra_field';
94
    const SAVE_SESSION = 'save_session';
95
    const CREATE_SESSION_FROM_MODEL = 'create_session_from_model';
96
    const UPDATE_SESSION = 'update_session';
97
98
    const SUBSCRIBE_USER_TO_COURSE = 'subscribe_user_to_course';
99
    const SUBSCRIBE_USER_TO_COURSE_PASSWORD = 'subscribe_user_to_course_password';
100
    const UNSUBSCRIBE_USER_FROM_COURSE = 'unsubscribe_user_from_course';
101
    const GET_USERS_SUBSCRIBED_TO_COURSE = 'get_users_subscribed_to_course';
102
103
    const ADD_COURSES_SESSION = 'add_courses_session';
104
    const ADD_USERS_SESSION = 'add_users_session';
105
    const SUBSCRIBE_USER_TO_SESSION_FROM_USERNAME = 'subscribe_user_to_session_from_username';
106
107
    const GET_COURSE_QUIZ_MDL_COMPAT = 'get_course_quiz_mdl_compat';
108
109
    const UPDATE_USER_PAUSE_TRAINING = 'update_user_pause_training';
110
111
    const CHECK_CONDITIONAL_LOGIN = 'check_conditional_login';
112
    const GET_LEGAL_CONDITIONS = 'get_legal_conditions';
113
    const UPDATE_CONDITION_ACCEPTED = 'update_condition_accepted';
114
115
    /**
116
     * @var Session
117
     */
118
    private $session;
119
120
    /**
121
     * @var Course
122
     */
123
    private $course;
124
125
    /**
126
     * Rest constructor.
127
     *
128
     * @param string $username
129
     * @param string $apiKey
130
     */
131
    public function __construct($username, $apiKey)
132
    {
133
        parent::__construct($username, $apiKey);
134
    }
135
136
    /**
137
     * @param string $username
138
     * @param string $apiKeyToValidate
139
     *
140
     * @throws Exception
141
     *
142
     * @return Rest
143
     */
144
    public static function validate($username, $apiKeyToValidate)
145
    {
146
        $apiKey = self::findUserApiKey($username, self::SERVICE_NAME);
147
148
        if ($apiKey != $apiKeyToValidate) {
149
            throw new Exception(get_lang('InvalidApiKey'));
150
        }
151
152
        return new self($username, $apiKey);
153
    }
154
155
    /**
156
     * Create the gcm_registration_id extra field for users.
157
     */
158
    public static function init()
159
    {
160
        $extraField = new ExtraField('user');
161
        $fieldInfo = $extraField->get_handler_field_info_by_field_variable(self::EXTRA_FIELD_GCM_REGISTRATION);
162
163
        if (empty($fieldInfo)) {
164
            $extraField->save(
165
                [
166
                    'variable' => self::EXTRA_FIELD_GCM_REGISTRATION,
167
                    'field_type' => ExtraField::FIELD_TYPE_TEXT,
168
                    'display_text' => self::EXTRA_FIELD_GCM_REGISTRATION,
169
                ]
170
            );
171
        }
172
    }
173
174
    /**
175
     * @param string $encoded
176
     *
177
     * @return array
178
     */
179
    public static function decodeParams($encoded)
180
    {
181
        return json_decode($encoded);
182
    }
183
184
    /**
185
     * Set the current course.
186
     *
187
     * @param int $id
188
     *
189
     * @throws Exception
190
     */
191
    public function setCourse($id)
192
    {
193
        global $_course;
194
195
        if (!$id) {
196
            $this->course = null;
197
198
            ChamiloSession::erase('_real_cid');
199
            ChamiloSession::erase('_cid');
200
            ChamiloSession::erase('_course');
201
202
            return;
203
        }
204
205
        $em = Database::getManager();
206
        /** @var Course $course */
207
        $course = $em->find('ChamiloCoreBundle:Course', $id);
208
209
        if (!$course) {
0 ignored issues
show
introduced by jmontoyaa
$course is of type Chamilo\CoreBundle\Entity\Course, thus it always evaluated to true.
Loading history...
210
            throw new Exception(get_lang('NoCourse'));
211
        }
212
213
        $this->course = $course;
214
215
        $courseInfo = api_get_course_info($course->getCode());
216
        $_course = $courseInfo;
217
218
        ChamiloSession::write('_real_cid', $course->getId());
219
        ChamiloSession::write('_cid', $course->getCode());
220
        ChamiloSession::write('_course', $courseInfo);
221
    }
222
223
    /**
224
     * Set the current session.
225
     *
226
     * @param int $id
227
     *
228
     * @throws Exception
229
     */
230
    public function setSession($id)
231
    {
232
        if (!$id) {
233
            $this->session = null;
234
235
            ChamiloSession::erase('session_name');
236
            ChamiloSession::erase('id_session');
237
238
            return;
239
        }
240
241
        $em = Database::getManager();
242
        /** @var Session $session */
243
        $session = $em->find('ChamiloCoreBundle:Session', $id);
244
245
        if (!$session) {
0 ignored issues
show
introduced by Angel Fernando Quiroz Campos
$session is of type Chamilo\CoreBundle\Entity\Session, thus it always evaluated to true.
Loading history...
246
            throw new Exception(get_lang('NoSession'));
247
        }
248
249
        $this->session = $session;
250
251
        ChamiloSession::write('session_name', $session->getName());
252
        ChamiloSession::write('id_session', $session->getId());
253
    }
254
255
    /**
256
     * @param string $registrationId
257
     *
258
     * @return bool
259
     */
260
    public function setGcmId($registrationId)
261
    {
262
        $registrationId = Security::remove_XSS($registrationId);
263
        $extraFieldValue = new ExtraFieldValue('user');
264
265
        return $extraFieldValue->save(
266
            [
267
                'variable' => self::EXTRA_FIELD_GCM_REGISTRATION,
268
                'value' => $registrationId,
269
                'item_id' => $this->user->getId(),
270
            ]
271
        );
272
    }
273
274
    /**
275
     * @param int $lastMessageId
276
     *
277
     * @return array
278
     */
279
    public function getUserMessages($lastMessageId = 0)
280
    {
281
        $lastMessages = MessageManager::getMessagesFromLastReceivedMessage($this->user->getId(), $lastMessageId);
282
        $messages = [];
283
284
        foreach ($lastMessages as $message) {
285
            $hasAttachments = MessageManager::hasAttachments($message['id']);
286
287
            $messages[] = [
288
                'id' => $message['id'],
289
                'title' => $message['title'],
290
                'sender' => [
291
                    'id' => $message['user_id'],
292
                    'lastname' => $message['lastname'],
293
                    'firstname' => $message['firstname'],
294
                    'completeName' => api_get_person_name($message['firstname'], $message['lastname']),
295
                ],
296
                'sendDate' => $message['send_date'],
297
                'content' => $message['content'],
298
                'hasAttachments' => $hasAttachments,
299
                'url' => api_get_path(WEB_CODE_PATH).'messages/view_message.php?'
300
                    .http_build_query(['type' => 1, 'id' => $message['id']]),
301
            ];
302
        }
303
304
        return $messages;
305
    }
306
307
    /**
308
     * @return array
309
     */
310
    public function getUserReceivedMessages()
311
    {
312
        $lastMessages = MessageManager::getReceivedMessages($this->user->getId(), 0);
313
        $messages = [];
314
315
        $webPath = api_get_path(WEB_PATH);
316
317
        foreach ($lastMessages as $message) {
318
            $hasAttachments = MessageManager::hasAttachments($message['id']);
319
            $attachmentList = [];
320
            if ($hasAttachments) {
321
                $attachmentList = MessageManager::getAttachmentList($message['id']);
322
            }
323
            $messages[] = [
324
                'id' => $message['id'],
325
                'title' => $message['title'],
326
                'msgStatus' => $message['msg_status'],
327
                'sender' => [
328
                    'id' => $message['user_id'],
329
                    'lastname' => $message['lastname'],
330
                    'firstname' => $message['firstname'],
331
                    'completeName' => api_get_person_name($message['firstname'], $message['lastname']),
332
                    'pictureUri' => $message['pictureUri'],
333
                ],
334
                'sendDate' => $message['send_date'],
335
                'content' => str_replace('src="/"', $webPath, $message['content']),
336
                'hasAttachments' => $hasAttachments,
337
                'attachmentList' => $attachmentList,
338
                'url' => '',
339
            ];
340
        }
341
342
        return $messages;
343
    }
344
345
    /**
346
     * @return array
347
     */
348
    public function getUserSentMessages()
349
    {
350
        $lastMessages = MessageManager::getSentMessages($this->user->getId(), 0);
351
        $messages = [];
352
353
        foreach ($lastMessages as $message) {
354
            $hasAttachments = MessageManager::hasAttachments($message['id']);
355
356
            $messages[] = [
357
                'id' => $message['id'],
358
                'title' => $message['title'],
359
                'msgStatus' => $message['msg_status'],
360
                'receiver' => [
361
                    'id' => $message['user_id'],
362
                    'lastname' => $message['lastname'],
363
                    'firstname' => $message['firstname'],
364
                    'completeName' => api_get_person_name($message['firstname'], $message['lastname']),
365
                    'pictureUri' => $message['pictureUri'],
366
                ],
367
                'sendDate' => $message['send_date'],
368
                'content' => $message['content'],
369
                'hasAttachments' => $hasAttachments,
370
                'url' => '',
371
            ];
372
        }
373
374
        return $messages;
375
    }
376
377
    /**
378
     * Get the user courses.
379
     */
380
    public function getUserCourses($userId = 0): array
381
    {
382
        if (empty($userId)) {
383
            $userId = $this->user->getId();
384
        }
385
386
        Event::courseLogout(
387
            [
388
                'uid' => $userId,
389
                'cid' => api_get_course_id(),
390
                'sid' => api_get_session_id(),
391
            ]
392
        );
393
394
        $courses = CourseManager::get_courses_list_by_user_id($userId);
395
        $data = [];
396
397
        foreach ($courses as $courseInfo) {
398
            /** @var Course $course */
399
            $course = Database::getManager()->find('ChamiloCoreBundle:Course', $courseInfo['real_id']);
400
            $teachers = CourseManager::getTeacherListFromCourseCodeToString($course->getCode());
401
            $picturePath = CourseManager::getPicturePath($course, true)
402
                ?: Display::return_icon('session_default.png', null, null, null, null, true);
403
404
            $data[] = [
405
                'id' => $course->getId(),
406
                'title' => $course->getTitle(),
407
                'code' => $course->getCode(),
408
                'directory' => $course->getDirectory(),
409
                'urlPicture' => $picturePath,
410
                'teachers' => $teachers,
411
                'isSpecial' => !empty($courseInfo['special_course']),
412
            ];
413
        }
414
415
        return $data;
416
    }
417
418
    /**
419
     * @throws Exception
420
     *
421
     * @return array
422
     */
423
    public function getCourseInfo()
424
    {
425
        $teachers = CourseManager::getTeacherListFromCourseCodeToString($this->course->getCode());
426
        $tools = CourseHome::get_tools_category(
427
            TOOL_STUDENT_VIEW,
428
            $this->course->getId(),
429
            $this->session ? $this->session->getId() : 0
430
        );
431
432
        return [
433
            'id' => $this->course->getId(),
434
            'title' => $this->course->getTitle(),
435
            'code' => $this->course->getCode(),
436
            'directory' => $this->course->getDirectory(),
437
            'urlPicture' => CourseManager::getPicturePath($this->course, true),
438
            'teachers' => $teachers,
439
            'tools' => array_map(
440
                function ($tool) {
441
                    return ['type' => $tool['name']];
442
                },
443
                $tools
444
            ),
445
        ];
446
    }
447
448
    /**
449
     * Get the course descriptions.
450
     *
451
     * @throws Exception
452
     *
453
     * @return array
454
     */
455
    public function getCourseDescriptions()
456
    {
457
        Event::event_access_tool(TOOL_COURSE_DESCRIPTION);
458
459
        $descriptions = CourseDescription::get_descriptions($this->course->getId());
460
        $results = [];
461
462
        $webPath = api_get_path(WEB_PATH);
463
464
        /** @var CourseDescription $description */
465
        foreach ($descriptions as $description) {
466
            $results[] = [
467
                'id' => $description->get_description_type(),
468
                'title' => $description->get_title(),
469
                'content' => str_replace('src="/', 'src="'.$webPath, $description->get_content()),
470
            ];
471
        }
472
473
        return $results;
474
    }
475
476
    /**
477
     * @param int $directoryId
478
     *
479
     * @throws Exception
480
     *
481
     * @return array
482
     */
483
    public function getCourseDocuments($directoryId = 0)
484
    {
485
        Event::event_access_tool(TOOL_DOCUMENT);
486
487
        /** @var string $path */
488
        $path = '/';
489
        $sessionId = $this->session ? $this->session->getId() : 0;
490
491
        if ($directoryId) {
492
            $directory = DocumentManager::get_document_data_by_id(
493
                $directoryId,
494
                $this->course->getCode(),
495
                false,
496
                $sessionId
497
            );
498
499
            if (!$directory) {
500
                throw new Exception('NoDataAvailable');
501
            }
502
503
            $path = $directory['path'];
504
        }
505
506
        $courseInfo = api_get_course_info_by_id($this->course->getId());
507
        $documents = DocumentManager::getAllDocumentData(
508
            $courseInfo,
509
            $path,
510
            0,
511
            null,
512
            false,
513
            false,
514
            $sessionId
515
        );
516
        $results = [];
517
518
        if (!empty($documents)) {
519
            $webPath = api_get_path(WEB_CODE_PATH).'document/document.php?';
520
521
            /** @var array $document */
522
            foreach ($documents as $document) {
523
                if ($document['visibility'] != '1') {
524
                    continue;
525
                }
526
527
                $icon = $document['filetype'] == 'file'
528
                    ? choose_image($document['path'])
529
                    : chooseFolderIcon($document['path']);
530
531
                $results[] = [
532
                    'id' => $document['id'],
533
                    'type' => $document['filetype'],
534
                    'title' => $document['title'],
535
                    'path' => $document['path'],
536
                    'url' => $webPath.http_build_query(
537
                        [
538
                            'username' => $this->user->getUsername(),
539
                            'api_key' => $this->apiKey,
540
                            'cidReq' => $this->course->getCode(),
541
                            'id_session' => $sessionId,
542
                            'gidReq' => 0,
543
                            'gradebook' => 0,
544
                            'origin' => '',
545
                            'action' => 'download',
546
                            'id' => $document['id'],
547
                        ]
548
                    ),
549
                    'icon' => $icon,
550
                    'size' => format_file_size($document['size']),
551
                ];
552
            }
553
        }
554
555
        return $results;
556
    }
557
558
    /**
559
     * @throws Exception
560
     *
561
     * @return array
562
     */
563
    public function getCourseAnnouncements()
564
    {
565
        Event::event_access_tool(TOOL_ANNOUNCEMENT);
566
567
        $sessionId = $this->session ? $this->session->getId() : 0;
568
569
        $announcements = AnnouncementManager::getAnnouncements(
570
            null,
571
            null,
572
            false,
573
            null,
574
            null,
575
            null,
576
            null,
577
            null,
578
            0,
579
            $this->user->getId(),
580
            $this->course->getId(),
581
            $sessionId
582
        );
583
584
        $announcements = array_map(
585
            function ($announcement) {
586
                return [
587
                    'id' => (int) $announcement['id'],
588
                    'title' => strip_tags($announcement['title']),
589
                    'creatorName' => strip_tags($announcement['username']),
590
                    'date' => strip_tags($announcement['insert_date']),
591
                ];
592
            },
593
            $announcements
594
        );
595
596
        return $announcements;
597
    }
598
599
    /**
600
     * @param int $announcementId
601
     *
602
     * @throws Exception
603
     *
604
     * @return array
605
     */
606
    public function getCourseAnnouncement($announcementId)
607
    {
608
        Event::event_access_tool(TOOL_ANNOUNCEMENT);
609
610
        $sessionId = $this->session ? $this->session->getId() : 0;
611
        $announcement = AnnouncementManager::getAnnouncementInfoById(
612
            $announcementId,
613
            $this->course->getId(),
614
            $this->user->getId()
615
        );
616
617
        if (!$announcement) {
618
            throw new Exception(get_lang('NoAnnouncement'));
619
        }
620
621
        return [
622
            'id' => $announcement['announcement']->getIid(),
623
            'title' => $announcement['announcement']->getTitle(),
624
            'creatorName' => UserManager::formatUserFullName($announcement['item_property']->getInsertUser()),
625
            'date' => api_convert_and_format_date(
626
                $announcement['item_property']->getInsertDate(),
627
                DATE_TIME_FORMAT_LONG_24H
628
            ),
629
            'content' => AnnouncementManager::parseContent(
630
                $this->user->getId(),
631
                $announcement['announcement']->getContent(),
632
                $this->course->getCode(),
633
                $sessionId
634
            ),
635
        ];
636
    }
637
638
    /**
639
     * @throws Exception
640
     *
641
     * @return array
642
     */
643
    public function getCourseAgenda()
644
    {
645
        Event::event_access_tool(TOOL_CALENDAR_EVENT);
646
647
        $sessionId = $this->session ? $this->session->getId() : 0;
648
649
        $agenda = new Agenda(
650
            'course',
651
            $this->user->getId(),
652
            $this->course->getId(),
653
            $sessionId
654
        );
655
        $result = $agenda->parseAgendaFilter(null);
656
657
        $start = new DateTime(api_get_utc_datetime(), new DateTimeZone('UTC'));
658
        $start->modify('first day of this month');
659
        $start->setTime(0, 0, 0);
660
        $end = new DateTime(api_get_utc_datetime(), new DateTimeZone('UTC'));
661
        $end->modify('last day of this month');
662
        $end->setTime(23, 59, 59);
663
664
        $groupId = current($result['groups']);
665
        $userId = current($result['users']);
666
667
        $events = $agenda->getEvents(
668
            $start->getTimestamp(),
669
            $end->getTimestamp(),
670
            $this->course->getId(),
671
            $groupId,
672
            $userId,
673
            'array'
674
        );
675
676
        if (!is_array($events)) {
677
            return [];
678
        }
679
680
        $webPath = api_get_path(WEB_PATH);
681
682
        return array_map(
683
            function ($event) use ($webPath) {
684
                return [
685
                    'id' => (int) $event['unique_id'],
686
                    'title' => $event['title'],
687
                    'content' => str_replace('src="/', 'src="'.$webPath, $event['description']),
688
                    'startDate' => $event['start_date_localtime'],
689
                    'endDate' => $event['end_date_localtime'],
690
                    'isAllDay' => $event['allDay'] ? true : false,
691
                ];
692
            },
693
            $events
694
        );
695
    }
696
697
    /**
698
     * @throws Exception
699
     *
700
     * @return array
701
     */
702
    public function getCourseNotebooks()
703
    {
704
        Event::event_access_tool(TOOL_NOTEBOOK);
705
706
        $em = Database::getManager();
707
        /** @var CNotebookRepository $notebooksRepo */
708
        $notebooksRepo = $em->getRepository('ChamiloCourseBundle:CNotebook');
709
        $notebooks = $notebooksRepo->findByUser($this->user, $this->course, $this->session);
710
711
        return array_map(
712
            function (CNotebook $notebook) {
713
                return [
714
                    'id' => $notebook->getIid(),
715
                    'title' => $notebook->getTitle(),
716
                    'description' => $notebook->getDescription(),
717
                    'creationDate' => api_format_date(
718
                        $notebook->getCreationDate()->getTimestamp()
719
                    ),
720
                    'updateDate' => api_format_date(
721
                        $notebook->getUpdateDate()->getTimestamp()
722
                    ),
723
                ];
724
            },
725
            $notebooks
726
        );
727
    }
728
729
    /**
730
     * @throws Exception
731
     *
732
     * @return array
733
     */
734
    public function getCourseForumCategories()
735
    {
736
        Event::event_access_tool(TOOL_FORUM);
737
738
        $sessionId = $this->session ? $this->session->getId() : 0;
739
        $webCoursePath = api_get_path(WEB_COURSE_PATH).$this->course->getDirectory().'/upload/forum/images/';
740
741
        require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
742
743
        $categoriesFullData = get_forum_categories('', $this->course->getId(), $sessionId);
744
        $categories = [];
745
        $includeGroupsForums = api_get_setting('display_groups_forum_in_general_tool') === 'true';
746
        $forumsFullData = get_forums('', $this->course->getCode(), $includeGroupsForums, $sessionId);
747
        $forums = [];
748
749
        foreach ($forumsFullData as $forumId => $forumInfo) {
750
            $forum = [
751
                'id' => (int) $forumInfo['iid'],
752
                'catId' => (int) $forumInfo['forum_category'],
753
                'title' => $forumInfo['forum_title'],
754
                'description' => $forumInfo['forum_comment'],
755
                'image' => $forumInfo['forum_image'] ? ($webCoursePath.$forumInfo['forum_image']) : '',
756
                'numberOfThreads' => isset($forumInfo['number_of_threads']) ? intval(
757
                    $forumInfo['number_of_threads']
758
                ) : 0,
759
                'lastPost' => null,
760
            ];
761
762
            $lastPostInfo = get_last_post_information($forumId, false, $this->course->getId(), $sessionId);
763
764
            if ($lastPostInfo) {
765
                $forum['lastPost'] = [
766
                    'date' => api_convert_and_format_date($lastPostInfo['last_post_date']),
767
                    'user' => api_get_person_name(
768
                        $lastPostInfo['last_poster_firstname'],
769
                        $lastPostInfo['last_poster_lastname']
770
                    ),
771
                ];
772
            }
773
774
            $forums[] = $forum;
775
        }
776
777
        foreach ($categoriesFullData as $category) {
778
            $categoryForums = array_filter(
779
                $forums,
780
                function (array $forum) use ($category) {
781
                    if ($forum['catId'] != $category['cat_id']) {
782
                        return false;
783
                    }
784
785
                    return true;
786
                }
787
            );
788
789
            $categories[] = [
790
                'id' => (int) $category['iid'],
791
                'title' => $category['cat_title'],
792
                'catId' => (int) $category['cat_id'],
793
                'description' => $category['cat_comment'],
794
                'forums' => $categoryForums,
795
                'courseId' => $this->course->getId(),
796
            ];
797
        }
798
799
        return $categories;
800
    }
801
802
    /**
803
     * @param int $forumId
804
     *
805
     * @throws Exception
806
     *
807
     * @return array
808
     */
809
    public function getCourseForum($forumId)
810
    {
811
        Event::event_access_tool(TOOL_FORUM);
812
813
        require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
814
815
        $sessionId = $this->session ? $this->session->getId() : 0;
816
        $forumInfo = get_forums($forumId, $this->course->getCode(), true, $sessionId);
817
818
        if (!isset($forumInfo['iid'])) {
819
            throw new Exception(get_lang('NoForum'));
820
        }
821
822
        $webCoursePath = api_get_path(WEB_COURSE_PATH).$this->course->getDirectory().'/upload/forum/images/';
823
        $forum = [
824
            'id' => $forumInfo['iid'],
825
            'title' => $forumInfo['forum_title'],
826
            'description' => $forumInfo['forum_comment'],
827
            'image' => $forumInfo['forum_image'] ? ($webCoursePath.$forumInfo['forum_image']) : '',
828
            'threads' => [],
829
        ];
830
831
        $threads = get_threads($forumInfo['iid'], $this->course->getId(), $sessionId);
832
833
        foreach ($threads as $thread) {
834
            $forum['threads'][] = [
835
                'id' => $thread['iid'],
836
                'title' => $thread['thread_title'],
837
                'lastEditDate' => api_convert_and_format_date($thread['lastedit_date'], DATE_TIME_FORMAT_LONG_24H),
838
                'numberOfReplies' => $thread['thread_replies'],
839
                'numberOfViews' => $thread['thread_views'],
840
                'author' => api_get_person_name($thread['firstname'], $thread['lastname']),
841
            ];
842
        }
843
844
        return $forum;
845
    }
846
847
    /**
848
     * @param int $forumId
849
     * @param int $threadId
850
     *
851
     * @return array
852
     */
853
    public function getCourseForumThread($forumId, $threadId)
854
    {
855
        Event::event_access_tool(TOOL_FORUM);
856
857
        require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
858
859
        $sessionId = $this->session ? $this->session->getId() : 0;
860
        $threadInfo = get_thread_information($forumId, $threadId, $sessionId);
861
862
        $thread = [
863
            'id' => intval($threadInfo['iid']),
864
            'cId' => intval($threadInfo['c_id']),
865
            'title' => $threadInfo['thread_title'],
866
            'forumId' => intval($threadInfo['forum_id']),
867
            'posts' => [],
868
        ];
869
870
        $forumInfo = get_forums($threadInfo['forum_id'], $this->course->getCode(), true, $sessionId);
871
        $postsInfo = getPosts($forumInfo, $threadInfo['iid'], 'ASC');
872
873
        foreach ($postsInfo as $postInfo) {
874
            $thread['posts'][] = [
875
                'id' => $postInfo['iid'],
876
                'title' => $postInfo['post_title'],
877
                'text' => $postInfo['post_text'],
878
                'author' => api_get_person_name($postInfo['firstname'], $postInfo['lastname']),
879
                'date' => api_convert_and_format_date($postInfo['post_date'], DATE_TIME_FORMAT_LONG_24H),
880
                'parentId' => $postInfo['post_parent_id'],
881
            ];
882
        }
883
884
        return $thread;
885
    }
886
887
    public function getCourseLinks(): array
888
    {
889
        Event::event_access_tool(TOOL_LINK);
890
891
        $courseId = $this->course->getId();
892
        $sessionId = $this->session ? $this->session->getId() : 0;
893
894
        $webCodePath = api_get_path(WEB_CODE_PATH);
895
        $cidReq = api_get_cidreq();
896
897
        $categories = array_merge(
898
            [
899
                [
900
                    'iid' => 0,
901
                    'c_id' => $courseId,
902
                    'id' => 0,
903
                    'category_title' => get_lang('NoCategory'),
904
                    'description' => '',
905
                    'display_order' => 0,
906
                    'session_id' => $sessionId,
907
                    'visibility' => 1,
908
                ],
909
            ],
910
            Link::getLinkCategories($courseId, $sessionId)
911
        );
912
913
        $categories = array_filter(
914
            $categories,
915
            function (array $category) {
916
                return $category['visibility'] != 0;
917
            }
918
        );
919
920
        return array_map(
921
            function (array $category) use ($webCodePath, $cidReq, $courseId, $sessionId) {
922
                $links = array_filter(
923
                    Link::getLinksPerCategory($category['iid'], $courseId, $sessionId),
924
                    function (array $link) {
925
                        return $link['visibility'] != 0;
926
                    }
927
                );
928
929
                $links = array_map(
930
                    function (array $link) use ($webCodePath, $cidReq) {
931
                        return [
932
                            'id' => (int) $link['id'],
933
                            'title' => Security::remove_XSS($link['title']),
934
                            'description' => Security::remove_XSS($link['description']),
935
                            'visibility' => (int) $link['visibility'],
936
                            'url' => $webCodePath."link/link_goto.php?$cidReq&link_id=".$link['id'],
937
                        ];
938
                    },
939
                    $links
940
                );
941
942
                return [
943
                    'id' => (int) $category['iid'],
944
                    'title' => Security::remove_XSS($category['category_title']),
945
                    'description' => Security::remove_XSS($category['description']),
946
                    'visibility' => (int) $category['visibility'],
947
                    'links' => $links,
948
                ];
949
            },
950
            $categories
951
        );
952
    }
953
954
    /**
955
     * @return array
956
     */
957
    public function getUserProfile()
958
    {
959
        $pictureInfo = UserManager::get_user_picture_path_by_id($this->user->getId(), 'web');
960
961
        $result = [
962
            'pictureUri' => $pictureInfo['dir'].$pictureInfo['file'],
963
            'id' => $this->user->getId(),
964
            'status' => $this->user->getStatus(),
965
            'fullName' => UserManager::formatUserFullName($this->user),
966
            'username' => $this->user->getUsername(),
967
            'officialCode' => $this->user->getOfficialCode(),
968
            'phone' => $this->user->getPhone(),
969
            'extra' => [],
970
        ];
971
972
        $fieldValue = new ExtraFieldValue('user');
973
        $extraInfo = $fieldValue->getAllValuesForAnItem($this->user->getId(), true);
974
975
        foreach ($extraInfo as $extra) {
976
            /** @var ExtraFieldValues $extraValue */
977
            $extraValue = $extra['value'];
978
            $result['extra'][] = [
979
                'title' => $extraValue->getField()->getDisplayText(true),
980
                'value' => $extraValue->getValue(),
981
            ];
982
        }
983
984
        return $result;
985
    }
986
987
    public function getCourseLpProgress()
988
    {
989
        $sessionId = $this->session ? $this->session->getId() : 0;
990
        $userId = $this->user->getId();
991
992
        /*$sessionId = $this->session ? $this->session->getId() : 0;
993
        $courseId = $this->course->getId();*/
994
995
        $result = Tracking::getCourseLpProgress($userId, $sessionId);
996
997
        return [$result];
998
    }
999
1000
    /**
1001
     * @throws Exception
1002
     *
1003
     * @return array
1004
     */
1005
    public function getCourseLearnPaths()
1006
    {
1007
        Event::event_access_tool(TOOL_LEARNPATH);
1008
1009
        $sessionId = $this->session ? $this->session->getId() : 0;
1010
        $categoriesTempList = learnpath::getCategories($this->course->getId());
1011
1012
        $categoryNone = new CLpCategory();
1013
        $categoryNone->setId(0);
1014
        $categoryNone->setName(get_lang('WithOutCategory'));
1015
        $categoryNone->setPosition(0);
1016
1017
        $categories = array_merge([$categoryNone], $categoriesTempList);
1018
        $categoryData = [];
1019
1020
        /** @var CLpCategory $category */
1021
        foreach ($categories as $category) {
1022
            $learnPathList = new LearnpathList(
1023
                $this->user->getId(),
1024
                api_get_course_info($this->course->getCode()),
1025
                $sessionId,
1026
                null,
1027
                false,
1028
                $category->getId()
1029
            );
1030
1031
            $flatLpList = $learnPathList->get_flat_list();
1032
1033
            if (empty($flatLpList)) {
1034
                continue;
1035
            }
1036
1037
            $listData = [];
1038
1039
            foreach ($flatLpList as $lpId => $lpDetails) {
1040
                if ($lpDetails['lp_visibility'] == 0) {
1041
                    continue;
1042
                }
1043
1044
                if (!learnpath::is_lp_visible_for_student(
1045
                    $lpId,
1046
                    $this->user->getId(),
1047
                    api_get_course_info($this->course->getCode()),
1048
                    $sessionId
1049
                )) {
1050
                    continue;
1051
                }
1052
1053
                $timeLimits = false;
1054
1055
                // This is an old LP (from a migration 1.8.7) so we do nothing
1056
                if (empty($lpDetails['created_on']) && empty($lpDetails['modified_on'])) {
1057
                    $timeLimits = false;
1058
                }
1059
1060
                // Checking if expired_on is ON
1061
                if (!empty($lpDetails['expired_on'])) {
1062
                    $timeLimits = true;
1063
                }
1064
1065
                if ($timeLimits) {
1066
                    if (!empty($lpDetails['publicated_on']) && !empty($lpDetails['expired_on'])) {
1067
                        $startTime = api_strtotime($lpDetails['publicated_on'], 'UTC');
1068
                        $endTime = api_strtotime($lpDetails['expired_on'], 'UTC');
1069
                        $now = time();
1070
                        $isActiveTime = false;
1071
1072
                        if ($now > $startTime && $endTime > $now) {
1073
                            $isActiveTime = true;
1074
                        }
1075
1076
                        if (!$isActiveTime) {
1077
                            continue;
1078
                        }
1079
                    }
1080
                }
1081
1082
                $progress = learnpath::getProgress($lpId, $this->user->getId(), $this->course->getId(), $sessionId);
1083
1084
                $listData[] = [
1085
                    'id' => $lpId,
1086
                    'title' => Security::remove_XSS($lpDetails['lp_name']),
1087
                    'progress' => $progress,
1088
                    'url' => api_get_path(WEB_CODE_PATH).'webservices/api/v2.php?'.http_build_query(
1089
                        [
1090
                            'hash' => $this->encodeParams(
1091
                                [
1092
                                    'action' => 'course_learnpath',
1093
                                    'lp_id' => $lpId,
1094
                                    'course' => $this->course->getId(),
1095
                                    'session' => $sessionId,
1096
                                ]
1097
                            ),
1098
                        ]
1099
                    ),
1100
                ];
1101
            }
1102
1103
            if (empty($listData)) {
1104
                continue;
1105
            }
1106
1107
            $categoryData[] = [
1108
                'id' => $category->getId(),
1109
                'name' => $category->getName(),
1110
                'learnpaths' => $listData,
1111
            ];
1112
        }
1113
1114
        return $categoryData;
1115
    }
1116
1117
    /**
1118
     * Start login for a user. Then make a redirect to show the learnpath.
1119
     *
1120
     * @param int $lpId
1121
     */
1122
    public function showLearningPath($lpId)
1123
    {
1124
        $loggedUser['user_id'] = $this->user->getId();
1125
        $loggedUser['status'] = $this->user->getStatus();
1126
        $loggedUser['uidReset'] = true;
1127
        $sessionId = $this->session ? $this->session->getId() : 0;
1128
1129
        ChamiloSession::write('_user', $loggedUser);
1130
        Login::init_user($this->user->getId(), true);
1131
1132
        $url = api_get_path(WEB_CODE_PATH).'lp/lp_controller.php?'.http_build_query(
1133
            [
1134
                'cidReq' => $this->course->getCode(),
1135
                'id_session' => $sessionId,
1136
                'gidReq' => 0,
1137
                'gradebook' => 0,
1138
                'origin' => '',
1139
                'action' => 'view',
1140
                'lp_id' => (int) $lpId,
1141
                'isStudentView' => 'true',
1142
            ]
1143
        );
1144
1145
        header("Location: $url");
1146
        exit;
1147
    }
1148
1149
    /**
1150
     * @param int $forumId
1151
     *
1152
     * @return array
1153
     */
1154
    public function saveForumPost(array $postValues, $forumId)
1155
    {
1156
        Event::event_access_tool(TOOL_FORUM);
1157
1158
        require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
1159
1160
        $forum = get_forums($forumId, $this->course->getCode());
1161
        store_reply($forum, $postValues, $this->course->getId(), $this->user->getId());
1162
1163
        return [
1164
            'registered' => true,
1165
        ];
1166
    }
1167
1168
    /**
1169
     * Get the list of sessions for current user.
1170
     *
1171
     * @return array the sessions list
1172
     */
1173
    public function getUserSessions()
1174
    {
1175
        $data = [];
1176
        $sessionsByCategory = UserManager::get_sessions_by_category($this->user->getId(), false);
1177