Passed
Push — 1.11.x ( bce6cd...c146d9 )
by Angel Fernando Quiroz
12:25
created

Rest::getCourseWorks()   B

Complexity

Conditions 10
Paths 2

Size

Total Lines 68
Code Lines 39

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
eloc 39
c 0
b 0
f 0
nc 2
nop 0
dl 0
loc 68
rs 7.6666

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