/
externallib.php
1710 lines (1529 loc) · 79.7 KB
/
externallib.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
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* External Web Service Template
*
* @package localatypaxreports
* @copyright 2011 Moodle Pty Ltd (http://moodle.com)
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once($CFG->libdir . "/externallib.php");
class local_atypaxreports_external extends external_api {
public static function grade_course_detail_parameters() {
return new external_function_parameters(
array(
'itemUser' => new external_multiple_structure(
new external_single_structure(
array(
'userid' => new external_value(PARAM_RAW, 'userid'),
'itemid' => new external_value(PARAM_INT, 'itemid'),
)
)
)
)
);
}
public static function grade_course_detail($itemUser) {
global $DB;
$returnValue = array();
//validamos los parametros ingrasados en la llamada al webservice
$params = self::validate_parameters(self::grade_course_detail_parameters(), array('itemUser' => $itemUser));
$userid = 0;
$itemid = 0;
foreach ($params['itemUser'] as $value) {
$u = $DB->get_record('user', array('username' => $value['userid']));
if (is_object($u)) {
$value['userid'] = $u->id;
} else {
throw new moodle_exception('El identificador del usuario: ' . $value['userid'] . ' no existe en Moodle', 'enrol_manual');
}
// $userid = $value['userid'];
// $itemid = $value['itemid'];
// break;
$item = $DB->get_record('grade_items', array('id' => $value['itemid']));
if (is_object($item)) {
$return['IdCurso'] = $item->courseid;
$return['ID'] = $item->id;
$return['item'] = $item->itemname;
$return['type'] = $item->itemtype;
$return['module'] = $item->itemmodule;
$return['peso'] = $item->multfactor;
$return['Nota'] = NULL;
$return['Username'] = $u->username;
$grade = $DB->get_record('grade_grades', array('itemid' => $item->id, 'userid' => $value['userid']));
if (is_object($grade)) {
$return['Nota'] = $grade->finalgrade;
}
}
array_push($returnValue, $return);
}
return $returnValue;
}
public static function grade_course_detail_returns() {
return new external_multiple_structure(
new external_single_structure(
array(
'IdCurso' => new external_value(PARAM_INT, 'id of course'),
'ID' => new external_value(PARAM_INT, 'id of item'),
'item' => new external_value(PARAM_RAW, 'name of item'),
'type' => new external_value(PARAM_RAW, 'type of item'),
'module' => new external_value(PARAM_RAW, 'module of item'),
'peso' => new external_value(PARAM_RAW, 'multiplicador del item'),
'Nota' => new external_value(PARAM_RAW, 'Nota final del item'),
'Username' => new external_value(PARAM_RAW, 'username'),
)
)
);
}
public static function grade_course_parameters() {
return new external_function_parameters(
array(
'userlist' => new external_multiple_structure(
new external_single_structure(
array(
'userid' => new external_value(PARAM_RAW, 'userid'),
'courseid' => new external_value(PARAM_RAW, 'courseid'),
)
)
)
)
);
}
public static function grade_course($userlist) {
global $DB;
$returnValue = array();
//validamos los parametros ingrasados en la llamada al webservice
$params = self::validate_parameters(self::grade_course_parameters(), array('userlist' => $userlist));
$userid = 0;
$courseid = 0;
foreach ($params['userlist'] as $value) {
//reemplazamos los valores del courseId
$ci = $DB->get_record('course', array('idnumber' => $value['courseid']));
if (is_object($ci)) {
$value['courseid'] = $ci->id;
} else {
throw new moodle_exception('El identificador del curso: ' . $value['courseid'] . ' no existe en Moodle', 'enrol_manual');
//$value['courseid'] = 0;
}
//reemplazamos los valores del usuario
$u = $DB->get_record('user', array('username' => $value['userid']));
if (is_object($u)) {
$value['userid'] = $u->id;
} else {
throw new moodle_exception('El identificador del usuario: ' . $value['userid'] . ' no existe en Moodle', 'enrol_manual');
//$value['userid'] = 0;
}
$userid = $value['userid'];
$courseid = $value['courseid'];
break;
}
// //listamos las notas del curso del estudiante en forma general
$items = $DB->get_records('grade_items', array('courseid' => $courseid));
if (is_array($items) && count($items) > 0) {
foreach ($items as $indice => $item) {
//filtramos los items de tipo curso
if ($item->itemtype != 'course') {
$return['IDCurso'] = $item->courseid;
$return['IDAlumno'] = $userid;
$return['IDCriterio'] = $item->id;
$return['Nota'] = NULL;
$return['idnumber'] = $item->idnumber;
$return['calculation'] = $item->calculation;
//obtenemos la nota de cada alumno
$grade = $DB->get_record('grade_grades', array('itemid' => $item->id, 'userid' => $userid));
if (is_object($grade)) {
$return['Nota'] = $grade->finalgrade;
}
//agregamos al arreglo de notas
array_push($returnValue, $return);
}
}
}
return $returnValue;
}
public static function grade_course_returns() {
return new external_multiple_structure(
new external_single_structure(
array(
'IDCurso' => new external_value(PARAM_INT, 'id of course'),
'IDAlumno' => new external_value(PARAM_INT, 'id of student'),
'IDCriterio' => new external_value(PARAM_INT, 'id of item'),
'Nota' => new external_value(PARAM_RAW, 'nota'),
'idnumber' => new external_value(PARAM_RAW, 'id number'),
'calculation' => new external_value(PARAM_RAW, 'formula de calculo'),
)
)
);
}
public static function course_config_parameters() {
return new external_function_parameters(
array('courseid' => new external_value(PARAM_RAW, 'course ID'))
);
}
public static function course_config($courseid) {
global $DB, $CFG, $USER;
$returnValue = array();
$params = self::validate_parameters(self::course_config_parameters(), array('courseid' => $courseid));
if (is_array($params)) {
//reemplazamos los valores del courseId
$ci = $DB->get_record('course', array('idnumber' => $params['courseid']));
if (is_object($ci)) {
$params['courseid'] = $ci->id;
} else {
throw new moodle_exception('El identificador del curso: ' . $params['courseid'] . ' no existe en Moodle', 'configuration');
//$arrayParam['courseid'] = 0;
}
}
//obtenemos el objeto del curso en el item
$objItemCourse = $DB->get_record('grade_items', array('courseid' => $params['courseid'], 'itemtype' => 'course'));
$formula = '';
if (is_object($objItemCourse)) {
$formula = $objItemCourse->calculation;
}
//$formula = '=(0.10*##gi3810##+0.20*##gi4015##+0.20*##gi4023##+0.20*##gi4026##+0.30*##gi4032##)';
preg_match_all('/##gi(\d+)##/', $formula, $matches);
//eliminamos el primer array
$matches = array_pop($matches);
//buscamos los items
$itemsArray = array();
if (is_array($matches)) {
foreach ($matches as $indice => $gradesItems) {
$objItem = $DB->get_record('grade_items', array('id' => $gradesItems));
if (is_object($objItem)) {
//$item = array();
$item['Id'] = $objItem->id;
$item['Actividad'] = $objItem->itemname;
$item['Peso'] = $objItem->multfactor;
array_push($itemsArray, $item);
}
}
}
//$r = self::localize($formula);
preg_match_all('/[\w.]+|".*?"|(?!\s)\W/', $formula, $list);
$list = array_shift($list);
$arrayPeso = array();
if (is_array($list)) {
$cont = 0;
foreach ($list as $index => $value) {
if (self::is_decimal($value)) {
array_push($arrayPeso, $value);
}
}
}
//agregamos los pesos en los items encontrados
if (is_array($itemsArray)) {
foreach ($itemsArray as $ind => $val) {
$val['Peso'] = $arrayPeso[$ind];
$itemsArray[$ind] = $val;
}
}
return array(array(
'course' => $ci->fullname,
'calculation' => $formula,
'items' => $itemsArray
));
}
public static function is_decimal($val) {
return is_numeric($val) && floor($val) != $val;
}
public static function course_config_returns() {
//return new external_value(PARAM_TEXT, 'The welcome message + user first name');
return new external_multiple_structure(
new external_single_structure(
array(
'course' => new external_value(PARAM_TEXT, 'full name of course'),
'calculation' => new external_value(PARAM_TEXT, 'full name of course'),
'items' => new external_multiple_structure(
new external_single_structure(
array(
'Id' => new external_value(PARAM_RAW, 'Id del item que se muestra en la formula'),
'Actividad' => new external_value(PARAM_RAW, 'Nombre de la actividad'),
'Peso' => new external_value(PARAM_RAW, 'El peso por el que se multiplica el item')
)
), 'Lista de items con sus respectivos pesos que se encuentran en la formula para calcular la nota del curso', VALUE_OPTIONAL),
), 'configuration of course'
)
);
}
public static function localize($formula) {
$formula = str_replace('.', '$', $formula); // temp placeholder
$formula = str_replace(',', get_string('listsep', 'langconfig'), $formula);
$formula = str_replace('$', get_string('decsep', 'langconfig'), $formula);
return $formula;
}
/**
* Returns description of method parameters
* @return external_function_parameters
*/
public static function hello_world_parameters() {
return new external_function_parameters(
array('welcomemessage' => new external_value(PARAM_TEXT, 'The welcome message. By default it is "Hello world,"', VALUE_DEFAULT, 'Hello world, '))
);
}
/**
* Returns welcome message
* @return string welcome message
*/
public static function hello_world($welcomemessage = 'Hello world, ') {
global $USER;
//Parameter validation
//REQUIRED
$params = self::validate_parameters(self::hello_world_parameters(), array('welcomemessage' => $welcomemessage));
//Context validation
//OPTIONAL but in most web service it should present
$context = get_context_instance(CONTEXT_USER, $USER->id);
self::validate_context($context);
//Capability checking
//OPTIONAL but in most web service it should present
if (!has_capability('moodle/user:viewdetails', $context)) {
throw new moodle_exception('cannotviewprofile');
}
return $params['welcomemessage'] . $USER->firstname.' '.$USER->lastname;
//return $USER;
}
/**
* Returns description of method parameters
*
* @return external_function_parameters
* @since Moodle 2.2
*/
public static function create_users_parameters() {
global $CFG;
return new external_function_parameters(
array(
'users' => new external_multiple_structure(
new external_single_structure(
array(
'username' =>
new external_value(PARAM_USERNAME, 'Username policy is defined in Moodle security config.'),
'password' =>
new external_value(PARAM_RAW, 'Plain text password consisting of any characters'),
'firstname' =>
new external_value(PARAM_NOTAGS, 'The first name(s) of the user'),
'lastname' =>
new external_value(PARAM_NOTAGS, 'The family name of the user'),
'email' =>
new external_value(PARAM_EMAIL, 'A valid and unique email address'),
'auth' =>
new external_value(PARAM_PLUGIN, 'Auth plugins include manual, ldap, imap, etc', VALUE_DEFAULT,
'manual', NULL_NOT_ALLOWED),
'idnumber' =>
new external_value(PARAM_RAW, 'An arbitrary ID code number perhaps from the institution',
VALUE_DEFAULT, ''),
'lang' =>
new external_value(PARAM_SAFEDIR, 'Language code such as "en", must exist on server', VALUE_DEFAULT,
$CFG->lang, NULL_NOT_ALLOWED),
'calendartype' =>
new external_value(PARAM_PLUGIN, 'Calendar type such as "gregorian", must exist on server',
VALUE_DEFAULT, $CFG->calendartype, VALUE_OPTIONAL),
'theme' =>
new external_value(PARAM_PLUGIN, 'Theme name such as "standard", must exist on server',
VALUE_OPTIONAL),
'timezone' =>
new external_value(PARAM_TIMEZONE, 'Timezone code such as Australia/Perth, or 99 for default',
VALUE_OPTIONAL),
'mailformat' =>
new external_value(PARAM_INT, 'Mail format code is 0 for plain text, 1 for HTML etc',
VALUE_OPTIONAL),
'description' =>
new external_value(PARAM_TEXT, 'User profile description, no HTML', VALUE_OPTIONAL),
'city' =>
new external_value(PARAM_NOTAGS, 'Home city of the user', VALUE_OPTIONAL),
'country' =>
new external_value(PARAM_ALPHA, 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL),
'firstnamephonetic' =>
new external_value(PARAM_NOTAGS, 'The first name(s) phonetically of the user', VALUE_OPTIONAL),
'lastnamephonetic' =>
new external_value(PARAM_NOTAGS, 'The family name phonetically of the user', VALUE_OPTIONAL),
'middlename' =>
new external_value(PARAM_NOTAGS, 'The middle name of the user', VALUE_OPTIONAL),
'alternatename' =>
new external_value(PARAM_NOTAGS, 'The alternate name of the user', VALUE_OPTIONAL),
'preferences' => new external_multiple_structure(
new external_single_structure(
array(
'type' => new external_value(PARAM_ALPHANUMEXT, 'The name of the preference'),
'value' => new external_value(PARAM_RAW, 'The value of the preference')
)
), 'User preferences', VALUE_OPTIONAL),
'customfields' => new external_multiple_structure(
new external_single_structure(
array(
'type' => new external_value(PARAM_ALPHANUMEXT, 'The name of the custom field'),
'value' => new external_value(PARAM_RAW, 'The value of the custom field')
)
), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL)
)
)
)
)
);
}
/**
* Create one or more users.
*
* @throws invalid_parameter_exception
* @param array $users An array of users to create.
* @return array An array of arrays
* @since Moodle 2.2
*/
public static function create_users($users) {
global $CFG, $DB;
require_once($CFG->dirroot."/lib/weblib.php");
require_once($CFG->dirroot."/user/lib.php");
require_once($CFG->dirroot."/user/profile/lib.php"); // Required for customfields related function.
// Ensure the current user is allowed to run this function.
$context = context_system::instance();
self::validate_context($context);
require_capability('moodle/user:create', $context);
// Do basic automatic PARAM checks on incoming data, using params description.
// If any problems are found then exceptions are thrown with helpful error messages.
$params = self::validate_parameters(self::create_users_parameters(), array('users' => $users));
$availableauths = core_component::get_plugin_list('auth');
unset($availableauths['mnet']); // These would need mnethostid too.
unset($availableauths['webservice']); // We do not want new webservice users for now.
$availablethemes = core_component::get_plugin_list('theme');
$availablelangs = get_string_manager()->get_list_of_translations();
$transaction = $DB->start_delegated_transaction();
$userids = array();
foreach ($params['users'] as $user) {
// Make sure that the username doesn't already exist.
if ($DB->record_exists('user', array('username' => $user['username'], 'mnethostid' => $CFG->mnet_localhost_id))) {
throw new invalid_parameter_exception('Username already exists: '.$user['username']);
}
// Make sure auth is valid.
if (empty($availableauths[$user['auth']])) {
throw new invalid_parameter_exception('Invalid authentication type: '.$user['auth']);
}
// Make sure lang is valid.
if (empty($availablelangs[$user['lang']])) {
throw new invalid_parameter_exception('Invalid language code: '.$user['lang']);
}
// Make sure lang is valid.
if (!empty($user['theme']) && empty($availablethemes[$user['theme']])) { // Theme is VALUE_OPTIONAL,
// so no default value
// We need to test if the client sent it
// => !empty($user['theme']).
throw new invalid_parameter_exception('Invalid theme: '.$user['theme']);
}
$user['confirmed'] = true;
$user['mnethostid'] = $CFG->mnet_localhost_id;
// Start of user info validation.
// Make sure we validate current user info as handled by current GUI. See user/editadvanced_form.php func validation().
if (!validate_email($user['email'])) {
throw new invalid_parameter_exception('Email address is invalid: '.$user['email']);
} else if ($DB->record_exists('user', array('email' => $user['email'], 'mnethostid' => $user['mnethostid']))) {
throw new invalid_parameter_exception('Email address already exists: '.$user['email']);
}
// End of user info validation.
// Create the user data now!
$user['id'] = user_create_user($user, true, false);
// Custom fields.
if (!empty($user['customfields'])) {
foreach ($user['customfields'] as $customfield) {
// Profile_save_data() saves profile file it's expecting a user with the correct id,
// and custom field to be named profile_field_"shortname".
$user["profile_field_".$customfield['type']] = $customfield['value'];
}
profile_save_data((object) $user);
}
// Trigger event.
\core\event\user_created::create_from_userid($user['id'])->trigger();
// Preferences.
if (!empty($user['preferences'])) {
foreach ($user['preferences'] as $preference) {
set_user_preference($preference['type'], $preference['value'], $user['id']);
}
}
//var_dump(array('id' => $user['id'], 'username' => $user['username']));
$userids[] = array('id' => $user['id'], 'username' => $user['username']);
}
$transaction->allow_commit();
return $userids;
}
/**
* Returns description of method result value
*
* @return external_description
* @since Moodle 2.2
*/
public static function create_users_returns() {
return new external_multiple_structure(
new external_single_structure(
array(
'id' => new external_value(PARAM_INT, 'user id'),
'username' => new external_value(PARAM_USERNAME, 'user name'),
)
)
);
}
/**
* Returns description of method result value
* @return external_description
*/
public static function hello_world_returns() {
return new external_value(PARAM_TEXT, 'The welcome message + user first name');
}
public static function enrol_users_parameters() {
return new external_function_parameters(
array(
'enrolments' => new external_multiple_structure(
new external_single_structure(
array(
'roleid' => new external_value(PARAM_INT, 'Role to assign to the user'),
'userid' => new external_value(PARAM_RAW, 'The id user that is going to be enrolled'),
'courseid' => new external_value(PARAM_TEXT, 'The course to enrol the user role in',VALUE_OPTIONAL),
'timestart' => new external_value(PARAM_INT, 'Timestamp when the enrolment start', VALUE_OPTIONAL),
'timeend' => new external_value(PARAM_INT, 'Timestamp when the enrolment end', VALUE_OPTIONAL),
'suspend' => new external_value(PARAM_INT, 'set to 1 to suspend the enrolment', VALUE_OPTIONAL),
'firstname' => new external_value(PARAM_TEXT, 'set Firstname', VALUE_OPTIONAL),
'lastname' => new external_value(PARAM_TEXT, 'set Lastname', VALUE_OPTIONAL),
'email' => new external_value(PARAM_TEXT, 'set email', VALUE_OPTIONAL),
'password' => new external_value(PARAM_TEXT, 'set password', VALUE_OPTIONAL),
'city' => new external_value(PARAM_RAW, 'City', VALUE_OPTIONAL),
'idnumber' => new external_value(PARAM_RAW, 'idnumber', VALUE_OPTIONAL),
'institution' => new external_value(PARAM_RAW, 'institution', VALUE_OPTIONAL),
'department' => new external_value(PARAM_RAW, 'department', VALUE_OPTIONAL)
)
)
)
)
);
}
public static function enrol_users($enrolments) {
global $DB, $CFG;
require_once($CFG->libdir . '/enrollib.php');
require_once($CFG->libdir . '/../user/lib.php');
require_once($CFG->libdir . "/../lib/weblib.php");
$params = self::validate_parameters(self::enrol_users_parameters(), array('enrolments' => $enrolments));
$transaction = $DB->start_delegated_transaction();
//retrieve the manual enrolment plugin
$enrol = enrol_get_plugin('manual');
if (empty($enrol)) {
throw new moodle_exception('manualpluginnotinstalled', 'enrol_manual');
}
//throw new moodle_exception('El email no es correcto', 'enrol_manual');
//print_r($params['enrolments']);
//print_r($params['enrolments']);
foreach ($params['enrolments'] as $enrolment) {
//reemplazamos los valores del courseId
$ci = $DB->get_record('course', array('shortname' => $enrolment['courseid']));
//print_r($enrolment['courseid'].'--');
//print_r($enrolment);
if (is_object($ci)) {
$enrolment['courseid'] = $ci->id;
} else {
throw new moodle_exception('El identificador del curso: ' . $enrolment['courseid'] . ' no existe en Moodle', 'enrol_manual');
//$enrolment['courseid'] = 0;
}
//reemplazamos los valores del usuario
$u = $DB->get_record('user', array('idnumber' => $enrolment['userid']));
if(!is_object($u)){
$u = $DB->get_record('user', array('username' => $enrolment['userid']));
}
if (is_object($u)) {
$enrolment['userid'] = $u->id;
} else {
throw new invalid_parameter_exception('userId is invalid: ');
}
// Ensure the current user is allowed to run this function in the enrolment context
$context = get_context_instance(CONTEXT_COURSE, $enrolment['courseid']);
self::validate_context($context);
//check that the user has the permission to manual enrol
require_capability('enrol/manual:enrol', $context);
//throw an exception if user is not able to assign the role
$roles = get_assignable_roles($context);
if (!array_key_exists($enrolment['roleid'], $roles)) {
$errorparams = new stdClass();
$errorparams->roleid = $enrolment['roleid'];
$errorparams->courseid = $enrolment['courseid'];
$errorparams->userid = $enrolment['userid'];
throw new moodle_exception('wsusercannotassign', 'enrol_manual', '', $errorparams);
}
//check manual enrolment plugin instance is enabled/exist
$enrolinstances = enrol_get_instances($enrolment['courseid'], true);
foreach ($enrolinstances as $courseenrolinstance) {
if ($courseenrolinstance->enrol == "manual") {
$instance = $courseenrolinstance;
break;
}
}
if (empty($instance)) {
$errorparams = new stdClass();
$errorparams->courseid = $enrolment['courseid'];
throw new moodle_exception('wsnoinstance', 'enrol_manual', $errorparams);
}
//check that the plugin accept enrolment (it should always the case, it's hard coded in the plugin)
if (!$enrol->allow_enrol($instance)) {
$errorparams = new stdClass();
$errorparams->roleid = $enrolment['roleid'];
$errorparams->courseid = $enrolment['courseid'];
$errorparams->userid = $enrolment['userid'];
throw new moodle_exception('wscannotenrol', 'enrol_manual', '', $errorparams);
}
//finally proceed the enrolment
$enrolment['timestart'] = isset($enrolment['timestart']) ? $enrolment['timestart'] : 0;
$enrolment['timeend'] = isset($enrolment['timeend']) ? $enrolment['timeend'] : 0;
$enrolment['status'] = (isset($enrolment['suspend']) && !empty($enrolment['suspend'])) ?
ENROL_USER_SUSPENDED : ENROL_USER_ACTIVE;
//var_dump($enrolment);die();
$enrol->enrol_user($instance, $enrolment['userid'], $enrolment['roleid'], $enrolment['timestart'], $enrolment['timeend'], $enrolment['status']);
}
$transaction->allow_commit();
//var_dump($enrolment);die();
return 'Usuarios Matriculados';
}
public static function enrol_users_returns() {
return new external_value(PARAM_TEXT, 'The welcome message + user first name');
}
/**
* Returns description of method parameters
*
* @return external_function_parameters
* @since Moodle 2.2
*/
public static function get_users_by_id_parameters() {
return new external_function_parameters(
array(
'userids' => new external_multiple_structure(new external_value(PARAM_RAW, 'user username')),
)
);
}
/**
* Get user information
* - This function is matching the permissions of /user/profil.php
* - It is also matching some permissions from /user/editadvanced.php for the following fields:
* auth, confirmed, idnumber, lang, theme, timezone, mailformat
*
* @param array $userids array of user ids
* @return array An array of arrays describing users
* @since Moodle 2.2
*/
public static function get_users_by_id($userids) {
global $CFG, $USER, $DB;
require_once($CFG->dirroot . "/user/lib.php");
//iteramos los parametros y reemplazamos por los ID
if (is_array($userids)) {
foreach ($userids as $indice => $dni) {
$u = $DB->get_record('user', array('username' => $dni));
if (is_object($u)) {
$userids[$indice] = $u->id;
}
}
}
$params = self::validate_parameters(self::get_users_by_id_parameters(), array('userids' => $userids));
list($uselect, $ujoin) = context_instance_preload_sql('u.id', CONTEXT_USER, 'ctx');
list($sqluserids, $params) = $DB->get_in_or_equal($userids);
$usersql = "SELECT u.* $uselect
FROM {user} u $ujoin
WHERE u.id $sqluserids";
$users = $DB->get_recordset_sql($usersql, $params);
$result = array();
$hasuserupdatecap = has_capability('moodle/user:update', get_system_context());
foreach ($users as $user) {
if (!empty($user->deleted)) {
continue;
}
context_instance_preload($user);
$usercontext = get_context_instance(CONTEXT_USER, $user->id);
self::validate_context($usercontext);
$currentuser = ($user->id == $USER->id);
if ($userarray = user_get_user_details($user)) {
//fields matching permissions from /user/editadvanced.php
if ($currentuser or $hasuserupdatecap) {
$userarray['auth'] = $user->auth;
$userarray['confirmed'] = $user->confirmed;
$userarray['idnumber'] = $user->idnumber;
$userarray['lang'] = $user->lang;
$userarray['theme'] = $user->theme;
$userarray['timezone'] = $user->timezone;
$userarray['mailformat'] = $user->mailformat;
}
$result[] = $userarray;
}
}
$users->close();
return $result;
}
/**
* Returns description of method result value
*
* @return external_description
* @since Moodle 2.2
*/
public static function get_users_by_id_returns() {
return new external_multiple_structure(
new external_single_structure(
array(
'id' => new external_value(PARAM_NUMBER, 'ID of the user'),
'username' => new external_value(PARAM_RAW, 'Username policy is defined in Moodle security config', VALUE_OPTIONAL),
'firstname' => new external_value(PARAM_NOTAGS, 'The first name(s) of the user', VALUE_OPTIONAL),
'lastname' => new external_value(PARAM_NOTAGS, 'The family name of the user', VALUE_OPTIONAL),
'fullname' => new external_value(PARAM_NOTAGS, 'The fullname of the user'),
'email' => new external_value(PARAM_TEXT, 'An email address - allow email as root@localhost', VALUE_OPTIONAL),
'address' => new external_value(PARAM_MULTILANG, 'Postal address', VALUE_OPTIONAL),
'phone1' => new external_value(PARAM_NOTAGS, 'Phone 1', VALUE_OPTIONAL),
'phone2' => new external_value(PARAM_NOTAGS, 'Phone 2', VALUE_OPTIONAL),
'icq' => new external_value(PARAM_NOTAGS, 'icq number', VALUE_OPTIONAL),
'skype' => new external_value(PARAM_NOTAGS, 'skype id', VALUE_OPTIONAL),
'yahoo' => new external_value(PARAM_NOTAGS, 'yahoo id', VALUE_OPTIONAL),
'aim' => new external_value(PARAM_NOTAGS, 'aim id', VALUE_OPTIONAL),
'msn' => new external_value(PARAM_NOTAGS, 'msn number', VALUE_OPTIONAL),
'department' => new external_value(PARAM_TEXT, 'department', VALUE_OPTIONAL),
'institution' => new external_value(PARAM_TEXT, 'institution', VALUE_OPTIONAL),
'interests' => new external_value(PARAM_TEXT, 'user interests (separated by commas)', VALUE_OPTIONAL),
'firstaccess' => new external_value(PARAM_INT, 'first access to the site (0 if never)', VALUE_OPTIONAL),
'lastaccess' => new external_value(PARAM_INT, 'last access to the site (0 if never)', VALUE_OPTIONAL),
'auth' => new external_value(PARAM_PLUGIN, 'Auth plugins include manual, ldap, imap, etc', VALUE_OPTIONAL),
'confirmed' => new external_value(PARAM_NUMBER, 'Active user: 1 if confirmed, 0 otherwise', VALUE_OPTIONAL),
'idnumber' => new external_value(PARAM_RAW, 'An arbitrary ID code number perhaps from the institution', VALUE_OPTIONAL),
'lang' => new external_value(PARAM_SAFEDIR, 'Language code such as "en", must exist on server', VALUE_OPTIONAL),
'theme' => new external_value(PARAM_PLUGIN, 'Theme name such as "standard", must exist on server', VALUE_OPTIONAL),
'timezone' => new external_value(PARAM_TIMEZONE, 'Timezone code such as Australia/Perth, or 99 for default', VALUE_OPTIONAL),
'mailformat' => new external_value(PARAM_INTEGER, 'Mail format code is 0 for plain text, 1 for HTML etc', VALUE_OPTIONAL),
'description' => new external_value(PARAM_RAW, 'User profile description', VALUE_OPTIONAL),
'descriptionformat' => new external_format_value('description', VALUE_OPTIONAL),
'city' => new external_value(PARAM_NOTAGS, 'Home city of the user', VALUE_OPTIONAL),
'url' => new external_value(PARAM_URL, 'URL of the user', VALUE_OPTIONAL),
'country' => new external_value(PARAM_ALPHA, 'Home country code of the user, such as AU or CZ', VALUE_OPTIONAL),
'profileimageurlsmall' => new external_value(PARAM_URL, 'User image profile URL - small version'),
'profileimageurl' => new external_value(PARAM_URL, 'User image profile URL - big version'),
'customfields' => new external_multiple_structure(
new external_single_structure(
array(
'type' => new external_value(PARAM_ALPHANUMEXT, 'The type of the custom field - text field, checkbox...'),
'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
'name' => new external_value(PARAM_RAW, 'The name of the custom field'),
'shortname' => new external_value(PARAM_RAW, 'The shortname of the custom field - to be able to build the field class in the code'),
)
), 'User custom fields (also known as user profil fields)', VALUE_OPTIONAL),
'preferences' => new external_multiple_structure(
new external_single_structure(
array(
'name' => new external_value(PARAM_ALPHANUMEXT, 'The name of the preferences'),
'value' => new external_value(PARAM_RAW, 'The value of the custom field'),
)
), 'User preferences', VALUE_OPTIONAL),
'enrolledcourses' => new external_multiple_structure(
new external_single_structure(
array(
'id' => new external_value(PARAM_INT, 'Id of the course'),
'fullname' => new external_value(PARAM_RAW, 'Fullname of the course'),
'shortname' => new external_value(PARAM_RAW, 'Shortname of the course')
)
), 'Courses where the user is enrolled - limited by which courses the user is able to see', VALUE_OPTIONAL)
)
)
);
}
/**
* Returns description of method parameters
*
* @return external_function_parameters
* @since Moodle 2.3
*/
public static function get_courses_parameters() {
return new external_function_parameters(
array('options' => new external_single_structure(
array('ids' => new external_multiple_structure(
new external_value(PARAM_RAW, 'Course id')
, 'List of course id. If empty return all courses
except front page course.', VALUE_OPTIONAL)
), 'options - operator OR is used', VALUE_DEFAULT, array())
)
);
}
/**
* Get courses
*
* @param array $options It contains an array (list of ids)
* @return array
* @since Moodle 2.2
*/
public static function get_courses($options = array()) {
global $CFG, $DB;
require_once($CFG->dirroot . "/course/lib.php");
//iteramos los cursos para reemplazar por los IDs
if (is_array($options)) {
foreach ($options['ids'] as $indice => $courseCode) {
$ci = $DB->get_record('course', array('idnumber' => $courseCode));
if (is_object($ci)) {
$options['ids'][$indice] = $ci->id;
}
}
}
//validate parameter
$params = self::validate_parameters(self::get_courses_parameters(), array('options' => $options));
//retrieve courses
if (!array_key_exists('ids', $params['options'])
or empty($params['options']['ids'])) {
$courses = $DB->get_records('course');
} else {
$courses = $DB->get_records_list('course', 'id', $params['options']['ids']);
}
//create return value
$coursesinfo = array();
foreach ($courses as $course) {
// now security checks
$context = get_context_instance(CONTEXT_COURSE, $course->id);
try {
self::validate_context($context);
} catch (Exception $e) {
$exceptionparam = new stdClass();
$exceptionparam->message = $e->getMessage();
$exceptionparam->courseid = $course->id;
throw new moodle_exception('errorcoursecontextnotvalid', 'webservice', '', $exceptionparam);
}
require_capability('moodle/course:view', $context);
$courseinfo = array();
$courseinfo['id'] = $course->id;
$courseinfo['fullname'] = $course->fullname;
$courseinfo['shortname'] = $course->shortname;
$courseinfo['categoryid'] = $course->category;
list($courseinfo['summary'], $courseinfo['summaryformat']) = external_format_text($course->summary, $course->summaryformat, $context->id, 'course', 'summary', 0);
$courseinfo['format'] = $course->format;
$courseinfo['startdate'] = $course->startdate;
$courseinfo['numsections'] = $course->numsections;
//some field should be returned only if the user has update permission
$courseadmin = has_capability('moodle/course:update', $context);
if ($courseadmin) {
$courseinfo['categorysortorder'] = $course->sortorder;
$courseinfo['idnumber'] = $course->idnumber;
$courseinfo['showgrades'] = $course->showgrades;
$courseinfo['showreports'] = $course->showreports;
$courseinfo['newsitems'] = $course->newsitems;
$courseinfo['visible'] = $course->visible;
$courseinfo['maxbytes'] = $course->maxbytes;
$courseinfo['hiddensections'] = $course->hiddensections;
$courseinfo['groupmode'] = $course->groupmode;
$courseinfo['groupmodeforce'] = $course->groupmodeforce;
$courseinfo['defaultgroupingid'] = $course->defaultgroupingid;
$courseinfo['lang'] = $course->lang;
$courseinfo['timecreated'] = $course->timecreated;
$courseinfo['timemodified'] = $course->timemodified;
$courseinfo['forcetheme'] = $course->theme;
$courseinfo['enablecompletion'] = $course->enablecompletion;
$courseinfo['completionstartonenrol'] = $course->completionstartonenrol;
$courseinfo['completionnotify'] = $course->completionnotify;
}
if ($courseadmin or $course->visible
or has_capability('moodle/course:viewhiddencourses', $context)) {
$coursesinfo[] = $courseinfo;
}
}
return $coursesinfo;
}
/**
* Returns description of method result value
*
* @return external_description
* @since Moodle 2.2
*/
public static function get_courses_returns() {
return new external_multiple_structure(
new external_single_structure(
array(
'id' => new external_value(PARAM_INT, 'course id'),
'shortname' => new external_value(PARAM_TEXT, 'course short name'),
'categoryid' => new external_value(PARAM_INT, 'category id'),
'categorysortorder' => new external_value(PARAM_INT, 'sort order into the category', VALUE_OPTIONAL),
'fullname' => new external_value(PARAM_TEXT, 'full name'),
'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
'summary' => new external_value(PARAM_RAW, 'summary'),
'summaryformat' => new external_format_value('summary'),
'format' => new external_value(PARAM_PLUGIN, 'course format: weeks, topics, social, site,..'),
'showgrades' => new external_value(PARAM_INT, '1 if grades are shown, otherwise 0', VALUE_OPTIONAL),
'newsitems' => new external_value(PARAM_INT, 'number of recent items appearing on the course page', VALUE_OPTIONAL),
'startdate' => new external_value(PARAM_INT, 'timestamp when the course start'),
'numsections' => new external_value(PARAM_INT, 'number of weeks/topics'),
'maxbytes' => new external_value(PARAM_INT, 'largest size of file that can be uploaded into the course', VALUE_OPTIONAL),
'showreports' => new external_value(PARAM_INT, 'are activity report shown (yes = 1, no =0)', VALUE_OPTIONAL),
'visible' => new external_value(PARAM_INT, '1: available to student, 0:not available', VALUE_OPTIONAL),
'hiddensections' => new external_value(PARAM_INT, 'How the hidden sections in the course are displayed to students', VALUE_OPTIONAL),
'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible', VALUE_OPTIONAL),
'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no', VALUE_OPTIONAL),
'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id', VALUE_OPTIONAL),
'timecreated' => new external_value(PARAM_INT, 'timestamp when the course have been created', VALUE_OPTIONAL),
'timemodified' => new external_value(PARAM_INT, 'timestamp when the course have been modified', VALUE_OPTIONAL),
'enablecompletion' => new external_value(PARAM_INT, 'Enabled, control via completion and activity settings. Disbaled,
not shown in activity settings.', VALUE_OPTIONAL),
'completionstartonenrol' => new external_value(PARAM_INT, '1: begin tracking a student\'s progress in course completion
after course enrolment. 0: does not', VALUE_OPTIONAL),
'completionnotify' => new external_value(PARAM_INT, '1: yes 0: no', VALUE_OPTIONAL),
'lang' => new external_value(PARAM_SAFEDIR, 'forced course language', VALUE_OPTIONAL),
'forcetheme' => new external_value(PARAM_PLUGIN, 'name of the force theme', VALUE_OPTIONAL),
), 'course'
)
);
}
/**
* Returns description of method parameters
*
* @return external_function_parameters
* @since Moodle 2.2
*/
public static function create_courses_parameters() {
$courseconfig = get_config('moodlecourse'); //needed for many default values
return new external_function_parameters(
array(
'courses' => new external_multiple_structure(
new external_single_structure(
array(
'fullname' => new external_value(PARAM_TEXT, 'full name'),
'shortname' => new external_value(PARAM_TEXT, 'course short name'),
'categoryid' => new external_value(PARAM_TEXT, 'category id'),
'idnumber' => new external_value(PARAM_RAW, 'id number', VALUE_OPTIONAL),
'summary' => new external_value(PARAM_RAW, 'summary', VALUE_OPTIONAL),
'summaryformat' => new external_format_value('summary', VALUE_DEFAULT),
'format' => new external_value(PARAM_PLUGIN,
'course format: weeks, topics, social, site,..',
VALUE_DEFAULT, $courseconfig->format),
'showgrades' => new external_value(PARAM_INT,
'1 if grades are shown, otherwise 0', VALUE_DEFAULT,
$courseconfig->showgrades),
'newsitems' => new external_value(PARAM_INT,
'number of recent items appearing on the course page',
VALUE_DEFAULT, $courseconfig->newsitems),
'startdate' => new external_value(PARAM_INT,
'timestamp when the course start', VALUE_OPTIONAL),
'numsections' => new external_value(PARAM_INT,
'(deprecated, use courseformatoptions) number of weeks/topics',
VALUE_OPTIONAL),
'maxbytes' => new external_value(PARAM_INT,
'largest size of file that can be uploaded into the course',
VALUE_DEFAULT, $courseconfig->maxbytes),
'showreports' => new external_value(PARAM_INT,
'are activity report shown (yes = 1, no =0)', VALUE_DEFAULT,
$courseconfig->showreports),
'visible' => new external_value(PARAM_INT,
'1: available to student, 0:not available', VALUE_OPTIONAL),
'hiddensections' => new external_value(PARAM_INT,
'(deprecated, use courseformatoptions) How the hidden sections in the course are displayed to students',
VALUE_OPTIONAL),
'groupmode' => new external_value(PARAM_INT, 'no group, separate, visible',
VALUE_DEFAULT, $courseconfig->groupmode),
'groupmodeforce' => new external_value(PARAM_INT, '1: yes, 0: no',
VALUE_DEFAULT, $courseconfig->groupmodeforce),
'defaultgroupingid' => new external_value(PARAM_INT, 'default grouping id',