/
Rest.php
4313 lines (3694 loc) · 141 KB
/
Rest.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/* For licensing terms, see /license.txt */
use Chamilo\CoreBundle\Entity\Course;
use Chamilo\CoreBundle\Entity\ExtraFieldValues;
use Chamilo\CoreBundle\Entity\Session;
use Chamilo\CourseBundle\Entity\CLpCategory;
use Chamilo\CourseBundle\Entity\CNotebook;
use Chamilo\CourseBundle\Entity\Repository\CNotebookRepository;
use Chamilo\UserBundle\Entity\User;
use Symfony\Component\HttpFoundation\Request as HttpRequest;
/**
* Class RestApi.
*/
class Rest extends WebService
{
public const SERVICE_NAME = 'MsgREST';
public const EXTRA_FIELD_GCM_REGISTRATION = 'gcm_registration_id';
public const GET_AUTH = 'authenticate';
public const SAVE_GCM_ID = 'gcm_id';
public const LOGOUT = 'logout';
public const GET_USER_MESSAGES = 'user_messages';
public const GET_USER_MESSAGES_RECEIVED = 'user_messages_received';
public const DELETE_USER_MESSAGE = 'delete_user_message';
public const GET_USER_MESSAGES_SENT = 'user_messages_sent';
public const GET_COUNT_NEW_MESSAGES = 'get_count_new_messages';
public const SET_MESSAGE_READ = 'set_message_read';
public const POST_USER_MESSAGE_READ = 'user_message_read';
public const POST_USER_MESSAGE_UNREAD = 'user_message_unread';
public const SAVE_USER_MESSAGE = 'save_user_message';
public const GET_MESSAGE_USERS = 'message_users';
public const VIEW_MESSAGE = 'view_message';
public const GET_USER_COURSES = 'user_courses';
public const GET_USER_COURSES_BY_DATES = 'user_courses_by_dates';
public const GET_USER_SESSIONS = 'user_sessions';
public const VIEW_PROFILE = 'view_user_profile';
public const GET_PROFILE = 'user_profile';
public const GET_PROFILES_BY_EXTRA_FIELD = 'users_profiles_by_extra_field';
public const VIEW_MY_COURSES = 'view_my_courses';
public const VIEW_COURSE_HOME = 'view_course_home';
public const GET_COURSE_INFO = 'course_info';
public const GET_COURSE_DESCRIPTIONS = 'course_descriptions';
public const GET_COURSE_DOCUMENTS = 'course_documents';
public const GET_COURSE_ANNOUNCEMENTS = 'course_announcements';
public const GET_COURSE_ANNOUNCEMENT = 'course_announcement';
public const GET_COURSE_AGENDA = 'course_agenda';
public const GET_COURSE_NOTEBOOKS = 'course_notebooks';
public const GET_COURSE_FORUM_CATEGORIES = 'course_forumcategories';
public const GET_COURSE_FORUM = 'course_forum';
public const GET_COURSE_FORUM_THREAD = 'course_forumthread';
public const GET_COURSE_LEARNPATHS = 'course_learnpaths';
public const GET_COURSE_LEARNPATH = 'course_learnpath';
public const GET_COURSE_LP_PROGRESS = 'course_lp_progress';
public const GET_COURSE_LINKS = 'course_links';
public const GET_COURSE_WORKS = 'course_works';
public const GET_COURSE_EXERCISES = 'course_exercises';
public const GET_COURSES_DETAILS_BY_EXTRA_FIELD = 'courses_details_by_extra_field';
public const SAVE_COURSE_NOTEBOOK = 'save_course_notebook';
public const SAVE_FORUM_POST = 'save_forum_post';
public const SAVE_FORUM_THREAD = 'save_forum_thread';
public const SET_THREAD_NOTIFY = 'set_thread_notify';
public const DOWNLOAD_FORUM_ATTACHMENT = 'download_forum_attachment';
public const GET_WORK_LIST = 'get_work_list';
public const GET_WORK_STUDENTS_WITHOUT_PUBLICATIONS = 'get_work_students_without_publications';
public const GET_WORK_USERS = 'get_work_users';
public const GET_WORK_STUDENT_LIST = 'get_work_student_list';
public const PUT_WORK_STUDENT_ITEM_VISIBILITY = 'put_course_work_visibility';
public const DELETE_WORK_STUDENT_ITEM = 'delete_work_student_item';
public const DELETE_WORK_CORRECTIONS = 'delete_work_corrections';
public const DOWNLOAD_WORK_FOLDER = 'download_work_folder';
public const DOWNLOAD_WORK_COMMENT_ATTACHMENT = 'download_work_comment_attachment';
public const DOWNLOAD_WORK = 'download_work';
public const VIEW_DOCUMENT_IN_FRAME = 'view_document_in_frame';
public const VIEW_QUIZ_TOOL = 'view_quiz_tool';
public const VIEW_SURVEY_TOOL = 'view_survey_tool';
public const CREATE_CAMPUS = 'add_campus';
public const EDIT_CAMPUS = 'edit_campus';
public const DELETE_CAMPUS = 'delete_campus';
public const GET_USERS = 'get_users';
public const USERNAME_EXIST = 'username_exist';
public const SAVE_USER = 'save_user';
public const SAVE_USER_GET_APIKEY = 'save_user_get_apikey';
public const SAVE_USER_JSON = 'save_user_json';
public const UPDATE_USER_FROM_USERNAME = 'update_user_from_username';
public const UPDATE_USER_APIKEY = 'update_user_apikey';
public const DELETE_USER = 'delete_user';
public const GET_USERS_API_KEYS = 'get_users_api_keys';
public const GET_USER_API_KEY = 'get_user_api_key';
public const GET_USER_LAST_CONNEXION = 'get_user_last_connexion';
public const GET_USER_TOTAL_CONNEXION_TIME = 'get_user_total_connexion_time';
public const GET_USER_SUB_GROUP = 'get_user_sub_group';
public const GET_COURSES = 'get_courses';
public const GET_COURSES_FROM_EXTRA_FIELD = 'get_courses_from_extra_field';
public const SAVE_COURSE = 'save_course';
public const DELETE_COURSE = 'delete_course';
public const GET_SESSION_FROM_EXTRA_FIELD = 'get_session_from_extra_field';
public const SAVE_SESSION = 'save_session';
public const CREATE_SESSION_FROM_MODEL = 'create_session_from_model';
public const UPDATE_SESSION = 'update_session';
public const GET_SESSIONS = 'get_sessions';
public const SUBSCRIBE_USER_TO_COURSE = 'subscribe_user_to_course';
public const SUBSCRIBE_USER_TO_COURSE_PASSWORD = 'subscribe_user_to_course_password';
public const UNSUBSCRIBE_USER_FROM_COURSE = 'unsubscribe_user_from_course';
public const GET_USERS_SUBSCRIBED_TO_COURSE = 'get_users_subscribed_to_course';
public const ADD_COURSES_SESSION = 'add_courses_session';
public const ADD_USERS_SESSION = 'add_users_session';
public const SUBSCRIBE_USER_TO_SESSION_FROM_USERNAME = 'subscribe_user_to_session_from_username';
public const SUBSCRIBE_USERS_TO_SESSION = 'subscribe_users_to_session';
public const UNSUBSCRIBE_USERS_FROM_SESSION = 'unsubscribe_users_from_session';
public const GET_USERS_SUBSCRIBED_TO_SESSION = 'get_users_subscribed_to_session';
public const GET_COURSE_QUIZ_MDL_COMPAT = 'get_course_quiz_mdl_compat';
public const UPDATE_USER_PAUSE_TRAINING = 'update_user_pause_training';
public const CHECK_CONDITIONAL_LOGIN = 'check_conditional_login';
public const GET_LEGAL_CONDITIONS = 'get_legal_conditions';
public const UPDATE_CONDITION_ACCEPTED = 'update_condition_accepted';
public const GET_TEST_UPDATES_LIST = 'get_test_updates_list';
public const GET_TEST_AVERAGE_RESULTS_LIST = 'get_test_average_results_list';
public const GET_GROUPS = 'get_groups';
public const GROUP_EXISTS = 'group_exists';
public const ADD_GROUP = 'add_group';
public const DELETE_GROUP = 'delete_group';
public const GET_GROUP_SUB_USERS = 'get_group_sub_users';
public const GET_GROUP_SUB_COURSES = 'get_group_sub_courses';
public const GET_GROUP_SUB_SESSIONS = 'get_group_sub_sessions';
public const ADD_GROUP_SUB_USER = 'add_group_sub_user';
public const ADD_GROUP_SUB_COURSE = 'add_group_sub_course';
public const ADD_GROUP_SUB_SESSION = 'add_group_sub_session';
public const DELETE_GROUP_SUB_USER = 'delete_group_sub_user';
public const DELETE_GROUP_SUB_COURSE = 'delete_group_sub_course';
public const DELETE_GROUP_SUB_SESSION = 'delete_group_sub_session';
public const GET_AUDIT_ITEMS = 'get_audit_items';
/**
* @var Session
*/
private $session;
/**
* @var Course
*/
private $course;
/**
* Rest constructor.
*
* @param string $username
* @param string $apiKey
*/
public function __construct($username, $apiKey)
{
parent::__construct($username, $apiKey);
}
/**
* Get user's username or another field if so configured through $_configuration['webservice_return_user_field'].
*
* @param int $userId
*/
private function __getConfiguredUsernameById(int $userId = null): string
{
if (empty($userId)) {
return '';
}
$userField = api_get_configuration_value('webservice_return_user_field');
if (empty($userField)) {
return api_get_user_info($userId)['username'];
}
$fieldValue = new ExtraFieldValue('user');
$extraInfo = $fieldValue->get_values_by_handler_and_field_variable($userId, $userField);
if (!empty($extraInfo)) {
return $extraInfo['value'];
} else {
return api_get_user_info($userId)['username'];
}
}
/**
* @param string $username
* @param string $apiKeyToValidate
*
* @throws Exception
*
* @return Rest
*/
public static function validate($username, $apiKeyToValidate)
{
$apiKey = self::findUserApiKey($username, self::SERVICE_NAME);
if ($apiKey != $apiKeyToValidate) {
throw new Exception(get_lang('InvalidApiKey'));
}
return new self($username, $apiKey);
}
/**
* Create the gcm_registration_id extra field for users.
*/
public static function init()
{
$extraField = new ExtraField('user');
$fieldInfo = $extraField->get_handler_field_info_by_field_variable(self::EXTRA_FIELD_GCM_REGISTRATION);
if (empty($fieldInfo)) {
$extraField->save(
[
'variable' => self::EXTRA_FIELD_GCM_REGISTRATION,
'field_type' => ExtraField::FIELD_TYPE_TEXT,
'display_text' => self::EXTRA_FIELD_GCM_REGISTRATION,
]
);
}
}
/**
* @param string $encoded
*
* @return array
*/
public static function decodeParams($encoded)
{
return json_decode($encoded);
}
/**
* Set the current course.
*
* @param int $id
*
* @throws Exception
*/
public function setCourse($id)
{
global $_course;
if (!$id) {
$this->course = null;
ChamiloSession::erase('_real_cid');
ChamiloSession::erase('_cid');
ChamiloSession::erase('_course');
return;
}
$em = Database::getManager();
/** @var Course $course */
$course = $em->find('ChamiloCoreBundle:Course', $id);
if (!$course) {
throw new Exception(get_lang('NoCourse'));
}
$this->course = $course;
$courseInfo = api_get_course_info($course->getCode());
$_course = $courseInfo;
ChamiloSession::write('_real_cid', $course->getId());
ChamiloSession::write('_cid', $course->getCode());
ChamiloSession::write('_course', $courseInfo);
}
/**
* Set the current session.
*
* @param int $id
*
* @throws Exception
*/
public function setSession($id)
{
if (!$id) {
$this->session = null;
ChamiloSession::erase('session_name');
ChamiloSession::erase('id_session');
return;
}
$em = Database::getManager();
/** @var Session $session */
$session = $em->find('ChamiloCoreBundle:Session', $id);
if (!$session) {
throw new Exception(get_lang('NoSession'));
}
$this->session = $session;
ChamiloSession::write('session_name', $session->getName());
ChamiloSession::write('id_session', $session->getId());
}
/**
* @param string $registrationId
*
* @return bool
*/
public function setGcmId($registrationId)
{
$registrationId = Security::remove_XSS($registrationId);
$extraFieldValue = new ExtraFieldValue('user');
return $extraFieldValue->save(
[
'variable' => self::EXTRA_FIELD_GCM_REGISTRATION,
'value' => $registrationId,
'item_id' => $this->user->getId(),
]
);
}
/**
* @param int $lastMessageId
*
* @return array
*/
public function getUserMessages($lastMessageId = 0)
{
$lastMessages = MessageManager::getMessagesFromLastReceivedMessage($this->user->getId(), $lastMessageId);
$messages = [];
foreach ($lastMessages as $message) {
$hasAttachments = MessageManager::hasAttachments($message['id']);
$messages[] = [
'id' => $message['id'],
'title' => $message['title'],
'sender' => [
'id' => $message['user_id'],
'lastname' => $message['lastname'],
'firstname' => $message['firstname'],
'completeName' => api_get_person_name($message['firstname'], $message['lastname']),
],
'sendDate' => $message['send_date'],
'content' => $message['content'],
'hasAttachments' => $hasAttachments,
'url' => api_get_path(WEB_CODE_PATH).'messages/view_message.php?'
.http_build_query(['type' => 1, 'id' => $message['id']]),
];
}
return $messages;
}
/**
* @return array
*/
public function getUserReceivedMessages()
{
$lastMessages = MessageManager::getReceivedMessages($this->user->getId(), 0);
$messages = [];
$webPath = api_get_path(WEB_PATH);
foreach ($lastMessages as $message) {
$hasAttachments = MessageManager::hasAttachments($message['id']);
$attachmentList = [];
if ($hasAttachments) {
$attachmentList = MessageManager::getAttachmentList($message['id']);
}
$messages[] = [
'id' => $message['id'],
'title' => $message['title'],
'msgStatus' => $message['msg_status'],
'sender' => [
'id' => $message['user_id'],
'lastname' => $message['lastname'],
'firstname' => $message['firstname'],
'completeName' => api_get_person_name($message['firstname'], $message['lastname']),
'pictureUri' => $message['pictureUri'],
],
'sendDate' => $message['send_date'],
'content' => str_replace('src="/"', $webPath, $message['content']),
'hasAttachments' => $hasAttachments,
'attachmentList' => $attachmentList,
'url' => '',
];
}
return $messages;
}
/**
* @return array
*/
public function getUserSentMessages()
{
$lastMessages = MessageManager::getSentMessages($this->user->getId(), 0);
$messages = [];
foreach ($lastMessages as $message) {
$hasAttachments = MessageManager::hasAttachments($message['id']);
$messages[] = [
'id' => $message['id'],
'title' => $message['title'],
'msgStatus' => $message['msg_status'],
'receiver' => [
'id' => $message['user_id'],
'lastname' => $message['lastname'],
'firstname' => $message['firstname'],
'completeName' => api_get_person_name($message['firstname'], $message['lastname']),
'pictureUri' => $message['pictureUri'],
],
'sendDate' => $message['send_date'],
'content' => $message['content'],
'hasAttachments' => $hasAttachments,
'url' => '',
];
}
return $messages;
}
/**
* Get the user courses.
*
* @throws Exception
*/
public function getUserCourses($userId = 0): array
{
if (!empty($userId)) {
if (!api_is_platform_admin() && $userId != $this->user->getId()) {
self::throwNotAllowedException();
}
}
if (empty($userId)) {
$userId = $this->user->getId();
}
Event::courseLogout(
[
'uid' => $userId,
'cid' => api_get_course_id(),
'sid' => api_get_session_id(),
]
);
$courses = CourseManager::get_courses_list_by_user_id($userId);
$data = [];
$webCodePath = api_get_path(WEB_CODE_PATH).'webservices/api/v2.php?';
foreach ($courses as $courseInfo) {
/** @var Course $course */
$course = Database::getManager()->find('ChamiloCoreBundle:Course', $courseInfo['real_id']);
$teachers = CourseManager::getTeacherListFromCourseCodeToString($course->getCode());
$picturePath = CourseManager::getPicturePath($course, true)
?: Display::return_icon('session_default.png', null, null, null, null, true);
$data[] = [
'id' => $course->getId(),
'title' => $course->getTitle(),
'code' => $course->getCode(),
'directory' => $course->getDirectory(),
'urlPicture' => $picturePath,
'teachers' => $teachers,
'isSpecial' => !empty($courseInfo['special_course']),
'url' => $webCodePath.http_build_query(
[
'action' => self::VIEW_COURSE_HOME,
'api_key' => $this->apiKey,
'username' => $this->user->getUsername(),
'course' => $course->getId(),
]
),
];
}
return $data;
}
/**
* @throws Exception
*
* @return array
*/
public function getCourseInfo()
{
$teachers = CourseManager::getTeacherListFromCourseCodeToString($this->course->getCode());
$tools = CourseHome::get_tools_category(
TOOL_STUDENT_VIEW,
$this->course->getId(),
$this->session ? $this->session->getId() : 0
);
return [
'id' => $this->course->getId(),
'title' => $this->course->getTitle(),
'code' => $this->course->getCode(),
'directory' => $this->course->getDirectory(),
'urlPicture' => CourseManager::getPicturePath($this->course, true),
'teachers' => $teachers,
'tools' => array_map(
function ($tool) {
return ['type' => $tool['name']];
},
$tools
),
];
}
/**
* Get the course descriptions.
*
* @param array $fields A list of extra fields to include in the answer. Searches for the field in the including course
*
* @throws Exception
*/
public function getCourseDescriptions($fields = []): array
{
Event::event_access_tool(TOOL_COURSE_DESCRIPTION);
// Check the extra fields criteria (whether to add extra field information or not)
$fieldSource = [];
if (count($fields) > 0) {
// For each field, check where to get it from (quiz or course)
$courseExtraField = new ExtraField('course');
foreach ($fields as $fieldName) {
// The field does not exist on the exercise, so use it from the course
$courseFieldExists = $courseExtraField->get_handler_field_info_by_field_variable($fieldName);
if ($courseFieldExists === false) {
continue;
}
$fieldSource[$fieldName] = ['item_type' => 'course', 'id' => $courseFieldExists['id']];
}
}
$courseId = $this->course->getId();
$descriptions = CourseDescription::get_descriptions($courseId);
$results = [];
$webPath = api_get_path(WEB_PATH);
/** @var CourseDescription $description */
foreach ($descriptions as $description) {
$descriptionDetails = [
'id' => $description->get_description_type(),
'title' => $description->get_title(),
'content' => str_replace('src="/', 'src="'.$webPath, $description->get_content()),
];
if (count($fieldSource) > 0) {
$extraFieldValuesTable = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
$fieldsSearchString = "SELECT field_id, value FROM $extraFieldValuesTable WHERE item_id = %d AND field_id = %d";
foreach ($fieldSource as $fieldName => $fieldDetails) {
$itemId = $courseId;
$result = Database::query(sprintf($fieldsSearchString, $itemId, $fieldDetails['id']));
if (Database::num_rows($result) > 0) {
$row = Database::fetch_assoc($result);
$descriptionDetails['extra_'.$fieldName] = $row['value'];
} else {
$descriptionDetails['extra_'.$fieldName] = '';
}
}
}
$results[] = $descriptionDetails;
}
return $results;
}
/**
* @param int $directoryId
*
* @throws Exception
*
* @return array
*/
public function getCourseDocuments($directoryId = 0)
{
Event::event_access_tool(TOOL_DOCUMENT);
/** @var string $path */
$path = '/';
$sessionId = $this->session ? $this->session->getId() : 0;
if ($directoryId) {
$directory = DocumentManager::get_document_data_by_id(
$directoryId,
$this->course->getCode(),
false,
$sessionId
);
if (!$directory) {
throw new Exception('NoDataAvailable');
}
$path = $directory['path'];
}
$courseInfo = api_get_course_info_by_id($this->course->getId());
$documents = DocumentManager::getAllDocumentData(
$courseInfo,
$path,
0,
null,
false,
false,
$sessionId
);
$results = [];
if (!empty($documents)) {
$webPath = api_get_path(WEB_CODE_PATH).'document/document.php?';
/** @var array $document */
foreach ($documents as $document) {
if ($document['visibility'] != '1') {
continue;
}
$icon = $document['filetype'] == 'file'
? choose_image($document['path'])
: chooseFolderIcon($document['path']);
$results[] = [
'id' => $document['id'],
'type' => $document['filetype'],
'title' => $document['title'],
'path' => $document['path'],
'url' => $webPath.http_build_query(
[
'username' => $this->user->getUsername(),
'api_key' => $this->apiKey,
'cidReq' => $this->course->getCode(),
'id_session' => $sessionId,
'gidReq' => 0,
'gradebook' => 0,
'origin' => '',
'action' => 'download',
'id' => $document['id'],
]
),
'icon' => $icon,
'size' => format_file_size($document['size']),
];
}
}
return $results;
}
/**
* @throws Exception
*
* @return array
*/
public function getCourseAnnouncements()
{
Event::event_access_tool(TOOL_ANNOUNCEMENT);
$sessionId = $this->session ? $this->session->getId() : 0;
$announcements = AnnouncementManager::getAnnouncements(
null,
null,
false,
null,
null,
null,
null,
null,
0,
$this->user->getId(),
$this->course->getId(),
$sessionId
);
$announcements = array_map(
function ($announcement) {
return [
'id' => (int) $announcement['id'],
'title' => strip_tags($announcement['title']),
'creatorName' => strip_tags($announcement['username']),
'date' => strip_tags($announcement['insert_date']),
];
},
$announcements
);
return $announcements;
}
/**
* @param int $announcementId
*
* @throws Exception
*
* @return array
*/
public function getCourseAnnouncement($announcementId)
{
Event::event_access_tool(TOOL_ANNOUNCEMENT);
$sessionId = $this->session ? $this->session->getId() : 0;
$announcement = AnnouncementManager::getAnnouncementInfoById(
$announcementId,
$this->course->getId(),
$this->user->getId()
);
if (!$announcement) {
throw new Exception(get_lang('NoAnnouncement'));
}
return [
'id' => $announcement['announcement']->getIid(),
'title' => $announcement['announcement']->getTitle(),
'creatorName' => UserManager::formatUserFullName($announcement['item_property']->getInsertUser()),
'date' => api_convert_and_format_date(
$announcement['item_property']->getInsertDate(),
DATE_TIME_FORMAT_LONG_24H
),
'content' => AnnouncementManager::parseContent(
$this->user->getId(),
$announcement['announcement']->getContent(),
$this->course->getCode(),
$sessionId
),
];
}
/**
* @throws Exception
*
* @return array
*/
public function getCourseAgenda()
{
Event::event_access_tool(TOOL_CALENDAR_EVENT);
$sessionId = $this->session ? $this->session->getId() : 0;
$agenda = new Agenda(
'course',
$this->user->getId(),
$this->course->getId(),
$sessionId
);
$result = $agenda->parseAgendaFilter(null);
$start = new DateTime(api_get_utc_datetime(), new DateTimeZone('UTC'));
$start->modify('first day of this month');
$start->setTime(0, 0, 0);
$end = new DateTime(api_get_utc_datetime(), new DateTimeZone('UTC'));
$end->modify('last day of this month');
$end->setTime(23, 59, 59);
$groupId = current($result['groups']);
$userId = current($result['users']);
$events = $agenda->getEvents(
$start->getTimestamp(),
$end->getTimestamp(),
$this->course->getId(),
$groupId,
$userId,
'array'
);
if (!is_array($events)) {
return [];
}
$webPath = api_get_path(WEB_PATH);
return array_map(
function ($event) use ($webPath) {
return [
'id' => (int) $event['unique_id'],
'title' => $event['title'],
'content' => str_replace('src="/', 'src="'.$webPath, $event['description']),
'startDate' => $event['start_date_localtime'],
'endDate' => $event['end_date_localtime'],
'isAllDay' => $event['allDay'] ? true : false,
];
},
$events
);
}
/**
* @throws Exception
*
* @return array
*/
public function getCourseNotebooks()
{
Event::event_access_tool(TOOL_NOTEBOOK);
$em = Database::getManager();
/** @var CNotebookRepository $notebooksRepo */
$notebooksRepo = $em->getRepository('ChamiloCourseBundle:CNotebook');
$notebooks = $notebooksRepo->findByUser($this->user, $this->course, $this->session);
return array_map(
function (CNotebook $notebook) {
return [
'id' => $notebook->getIid(),
'title' => $notebook->getTitle(),
'description' => $notebook->getDescription(),
'creationDate' => api_format_date(
$notebook->getCreationDate()->getTimestamp()
),
'updateDate' => api_format_date(
$notebook->getUpdateDate()->getTimestamp()
),
];
},
$notebooks
);
}
/**
* @throws Exception
*
* @return array
*/
public function getCourseForumCategories()
{
Event::event_access_tool(TOOL_FORUM);
$sessionId = $this->session ? $this->session->getId() : 0;
$webCoursePath = api_get_path(WEB_COURSE_PATH).$this->course->getDirectory().'/upload/forum/images/';
require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
$categoriesFullData = get_forum_categories('', $this->course->getId(), $sessionId);
$categories = [];
$includeGroupsForums = api_get_setting('display_groups_forum_in_general_tool') === 'true';
$forumsFullData = get_forums('', $this->course->getCode(), $includeGroupsForums, $sessionId);
$forums = [];
foreach ($forumsFullData as $forumId => $forumInfo) {
$forum = [
'id' => (int) $forumInfo['iid'],
'catId' => (int) $forumInfo['forum_category'],
'title' => $forumInfo['forum_title'],
'description' => $forumInfo['forum_comment'],
'image' => $forumInfo['forum_image'] ? ($webCoursePath.$forumInfo['forum_image']) : '',
'numberOfThreads' => isset($forumInfo['number_of_threads']) ? intval(
$forumInfo['number_of_threads']
) : 0,
'lastPost' => null,
];
$lastPostInfo = get_last_post_information($forumId, false, $this->course->getId(), $sessionId);
if ($lastPostInfo) {
$forum['lastPost'] = [
'date' => api_convert_and_format_date($lastPostInfo['last_post_date']),
'user' => api_get_person_name(
$lastPostInfo['last_poster_firstname'],
$lastPostInfo['last_poster_lastname']
),
];
}
$forums[] = $forum;
}
foreach ($categoriesFullData as $category) {
$categoryForums = array_filter(
$forums,
function (array $forum) use ($category) {
if ($forum['catId'] != $category['cat_id']) {
return false;
}
return true;
}
);
$categories[] = [
'id' => (int) $category['iid'],
'title' => $category['cat_title'],
'catId' => (int) $category['cat_id'],
'description' => $category['cat_comment'],
'forums' => $categoryForums,
'courseId' => $this->course->getId(),
];
}
return $categories;
}
/**
* @param int $forumId
*
* @throws Exception
*
* @return array
*/
public function getCourseForum($forumId)
{
Event::event_access_tool(TOOL_FORUM);
require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
$sessionId = $this->session ? $this->session->getId() : 0;
$forumInfo = get_forums($forumId, $this->course->getCode(), true, $sessionId);
if (!isset($forumInfo['iid'])) {
throw new Exception(get_lang('NoForum'));
}
$webCoursePath = api_get_path(WEB_COURSE_PATH).$this->course->getDirectory().'/upload/forum/images/';
$forum = [
'id' => $forumInfo['iid'],
'title' => $forumInfo['forum_title'],
'description' => $forumInfo['forum_comment'],
'image' => $forumInfo['forum_image'] ? ($webCoursePath.$forumInfo['forum_image']) : '',
'threads' => [],
];
$threads = get_threads($forumInfo['iid'], $this->course->getId(), $sessionId);
foreach ($threads as $thread) {
$forum['threads'][] = [
'id' => $thread['iid'],
'title' => $thread['thread_title'],
'lastEditDate' => api_convert_and_format_date($thread['lastedit_date'], DATE_TIME_FORMAT_LONG_24H),
'numberOfReplies' => $thread['thread_replies'],
'numberOfViews' => $thread['thread_views'],
'author' => api_get_person_name($thread['firstname'], $thread['lastname']),
];
}
return $forum;
}
/**
* @param int $forumId
* @param int $threadId
*
* @return array
*/
public function getCourseForumThread($forumId, $threadId)
{
Event::event_access_tool(TOOL_FORUM);
require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
$sessionId = $this->session ? $this->session->getId() : 0;
$threadInfo = get_thread_information($forumId, $threadId, $sessionId);
$thread = [
'id' => intval($threadInfo['iid']),
'cId' => intval($threadInfo['c_id']),
'title' => $threadInfo['thread_title'],
'forumId' => intval($threadInfo['forum_id']),
'posts' => [],
];
$forumInfo = get_forums($threadInfo['forum_id'], $this->course->getCode(), true, $sessionId);
$postsInfo = getPosts($forumInfo, $threadInfo['iid'], 'ASC');
foreach ($postsInfo as $postInfo) {
$thread['posts'][] = [
'id' => $postInfo['iid'],
'title' => $postInfo['post_title'],
'text' => $postInfo['post_text'],
'author' => api_get_person_name($postInfo['firstname'], $postInfo['lastname']),
'date' => api_convert_and_format_date($postInfo['post_date'], DATE_TIME_FORMAT_LONG_24H),
'parentId' => $postInfo['post_parent_id'],
'attachments' => getAttachedFiles(
$forumId,
$threadId,
$postInfo['iid'],
0,
$this->course->getId()