-
Notifications
You must be signed in to change notification settings - Fork 5
/
externallib.php
1204 lines (1056 loc) · 42.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
// This file is part of Moodle - http://moodle.org/
//
// 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/>.
/**
* This file contains the external api class for the mhaairs-moodle integration.
*
* @package block_mhaairs
* @copyright 2014 Itamar Tzadok <itamar@substantialmethods.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') or die();
global $CFG;
require_once("$CFG->libdir/externallib.php");
require_once("$CFG->libdir/gradelib.php");
require_once("$CFG->dirroot/blocks/mhaairs/block_mhaairs_util.php");
/**
* Block mhaairs gradebook web service.
*
* @package block_mhaairs
* @copyright 2014 Itamar Tzadok <itamar@substantialmethods.com>
* @copyright 2013-2014 Moodlerooms inc.
* @author Teresa Hardy <thardy@moodlerooms.com>
* @author Darko MIletic <dmiletic@moodlerooms.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class block_mhaairs_gradebookservice_external extends external_api {
const ITEM_DEFAULT_TYPE = 'manual';
const ITEM_DEFAULT_MODULE = 'mhaairs';
// UPDATE GRADE.
/**
* Allows external systems to push grade items and scores into the course gradebook. The service as to be
* activated by the site admin.
* A typical usage requires two calls, the first to create/update the grade item and the second to update
* the user grade. The create/update grade item call should not pass null for the grades. The update user
* grade call may require the identity_type flag which can be passed either in the grades parameter or in
* the itemdetails paramter. The latter is otherwise not required.
*
* @param string $source - Any string or empty.
* @param string $courseid - Expected idnumber or Moodle id; requires identity_type in itemdetails.
* @param string $itemtype - Ignored; all mhaairs items should be manual.
* @param string $itemmodule - Ignored; all mhaairs items should be identified as mhaairs.
* @param string $iteminstance - The mhaairs assignment id.
* @param string $itemnumber - Any integer.
* @param string $grades - Url encoded, json encoded, array of the following user grade details:
* userid - The user username or internal id (depends on identity_type). Required. PARAM_TEXT.
* rawgrade - The user grade. Optional. PARAM_FLOAT.
* identity_type - Whether to treat the userid as username or internal id. Optional. PARAM_ALPHA.
* @param string $itemdetails - Url encoded, json encoded, array of the following item details and flags:
* itemname - The item name. Required. PARAM_TEXT.
* idnumber - The item idnumber. Optional. PARAM_TEXT.
* gradetype - The item grade type. Optional. PARAM_INT. Defaults to point.
* grademax - The item grade max. Optional. PARAM_FLOAT. Defaults to 100.
* hidden - Whether the item is hidden. Optional. PARAM_INT.
* deleted - Whether to delete the item. Optional. PARAM_INT.
* categoryid - The name of the target category for the item. Optional. PARAM_TEXT.
* identity_type - Whether to treat the courseid as idnumber or internal id. Optional. PARAM_ALPHA.
* needsupdate - Optional. PARAM_INT.
* useexisting - Whether to use an existing item by name. Optional. PARAM_INT.
*
* @return mixed
* @throws invalid_parameter_exception
* @throws moodle_exception
*/
public static function update_grade($source = 'mhaairs', $courseid ='',
$itemtype = self::ITEM_DEFAULT_TYPE, $itemmodule = self::ITEM_DEFAULT_MODULE,
$iteminstance = '0', $itemnumber = '0',
$grades = null, $itemdetails = null) {
global $USER, $DB;
$logger = MHLog::instance();
$logger->log('==================================');
$logger->log('New webservice request started on '. $logger->time_stamp);
$logger->log('Entry parameters:');
$logger->log("source = {$source}");
$logger->log("courseid = {$courseid}");
$logger->log("itemtype = {$itemtype}");
$logger->log("itemmodule = {$itemmodule}");
$logger->log("iteminstance = {$iteminstance}");
$logger->log("itemnumber = {$itemnumber}");
$logger->log("grades = {$grades}");
$logger->log("itemdetails = {$itemdetails}");
// Gradebook sync must be enabled by admin in the block's site configuration.
if (!$syncgrades = get_config('core', 'block_mhaairs_sync_gradebook')) {
$logger->log('Grade sync is not enabled in global settings. Returning 1.');
return GRADE_UPDATE_FAILED;
}
// Parameters validation.
$params = self::validate_parameters(
self::update_grade_parameters(),
array(
'source' => $source,
'courseid' => $courseid,
'itemtype' => $itemtype,
'itemmodule' => $itemmodule,
'iteminstance' => $iteminstance,
'itemnumber' => $itemnumber,
'grades' => $grades,
'itemdetails' => $itemdetails,
)
);
$logger->log('Parameters validated.');
// Extract the validated parameters to their respective variables.
foreach ($params as $var => $value) {
${$var} = $value;
}
// Context validation.
// OPTIONAL but in most web service it should be present.
$context = context_user::instance($USER->id);
self::validate_context($context);
$logger->log('Context validated.');
// Capability checking.
// OPTIONAL but in most web service it should be present.
require_capability('moodle/user:viewdetails', $context, null, true, 'cannotviewprofile');
$logger->log('Capability validated.');
// Validate item details.
$logger->log("Checking if any item details were sent.");
$itemdetails = json_decode(urldecode($itemdetails), true);
$itemdetails = self::validate_item_details($itemdetails);
$logger->log('Item details validated: '. var_export($itemdetails, true));
// Get the item details identity type variable.
$identitytype = self::get_details_itentity_type($itemdetails);
// Validate grades.
$logger->log("Checking if any grades were sent.");
$grades = json_decode(urldecode($grades), true);
$grades = self::validate_grades($grades);
// HACK Make sure grades has identity type; take from item details if must.
if ($grades and !isset($grades['identity_type'])) {
$grades['identity_type'] = null;
if ($identitytype) {
$grades['identity_type'] = $identitytype;
}
}
$logger->log('Grades validated: '. var_export($grades, true));
// Get the course.
if (!$course = self::get_course($courseid, $identitytype)) {
// No valid course specified.
$logger->log("Course id received was not correct. courseid = {$courseid}.");
$logger->log('Returning '. GRADE_UPDATE_FAILED. '.');
return GRADE_UPDATE_FAILED;
}
$courseid = $course->id;
$logger->log('Course validated.');
if (!$grades) {
// A request without grades is for creating/updating/deleting a grade item.
$result = self::update_grade_item(
$source,
$courseid,
$iteminstance,
$itemnumber,
$itemdetails
);
$resultverbose = ($result == GRADE_UPDATE_OK) ? 'completed successfully' : 'failed';
$logger->log("Grade item update $resultverbose");
} else {
$result = self::update_user_grade(
$source,
$courseid,
$iteminstance,
$itemnumber,
$grades
);
$resultverbose = ($result == GRADE_UPDATE_OK) ? 'completed successfully' : 'failed';
$logger->log("User grade update $resultverbose");
}
return $result;
}
/**
* Returns description of method parameters.
*
* @return external_function_parameters
*/
public static function update_grade_parameters() {
$params = array();
// Source.
$desc = 'string $source source of the grade such as "mhaairs"';
$params['source'] = new external_value(PARAM_TEXT, $desc, VALUE_DEFAULT, 'mhaairs');
// Courseid.
$desc = 'string $courseid id of course';
$params['courseid'] = new external_value(PARAM_TEXT, $desc, VALUE_DEFAULT, 'NULL');
// Item type.
$desc = 'string $itemtype type of grade item - mod, block, manual';
$params['itemtype'] = new external_value(PARAM_TEXT, $desc, VALUE_DEFAULT, self::ITEM_DEFAULT_TYPE);
// Item module.
$desc = 'string $itemmodule more specific then $itemtype - assignment,'.
' forum, etc.; maybe NULL for some item types or anything for manual.';
$params['itemmodule'] = new external_value(PARAM_TEXT, $desc, VALUE_DEFAULT, self::ITEM_DEFAULT_MODULE);
// Item instance.
$desc = 'ID of the item module';
$params['iteminstance'] = new external_value(PARAM_TEXT, $desc, VALUE_DEFAULT, '0');
// Item number.
$desc = 'int $itemnumber most probably 0, modules can use other '.
'numbers when having more than one grades for each user';
$params['itemnumber'] = new external_value(PARAM_INT, $desc, VALUE_DEFAULT, 0);
// Grades.
$desc = 'mixed $grades grade (object, array) or several grades '.
'(arrays of arrays or objects), NULL if updating grade_item definition only';
$params['grades'] = new external_value(PARAM_TEXT, $desc, VALUE_DEFAULT, 'NULL');
// Item details.
$desc = 'mixed $itemdetails object or array describing the grading item, NULL if no change';
$params['itemdetails'] = new external_value(PARAM_TEXT, $desc, VALUE_DEFAULT, 'NULL');
return new external_function_parameters($params);
}
/**
* Returns description of method result value.
*
* @return external_description
*/
public static function update_grade_returns() {
return new external_value(PARAM_TEXT, '0 for success anything else for failure');
}
// GET GRADE.
/**
* Returns grade item info and grades.
*
* @param string $source
* @param string $courseid
* @param string $itemtype
* @param string $itemmodule
* @param string $iteminstance
* @param string $itemnumber
* @param string $grades
* @param string $itemdetails
* @return mixed
* @throws invalid_parameter_exception
* @throws moodle_exception
*/
public static function get_grade($source = 'mhaairs', $courseid ='',
$itemtype = self::ITEM_DEFAULT_TYPE, $itemmodule = self::ITEM_DEFAULT_MODULE,
$iteminstance = '0', $itemnumber = '0',
$grades = null, $itemdetails = null) {
global $USER;
$result = array();
// Gradebook sync must be enabled by admin in the block's site configuration.
if (!$syncgrades = get_config('core', 'block_mhaairs_sync_gradebook')) {
return $result;
}
// Parameters validation.
$params = self::validate_parameters(
self::update_grade_parameters(),
array(
'source' => $source,
'courseid' => $courseid,
'itemtype' => $itemtype,
'itemmodule' => $itemmodule,
'iteminstance' => $iteminstance,
'itemnumber' => $itemnumber,
'grades' => $grades,
'itemdetails' => $itemdetails,
)
);
// Extract the validated parameters to their respective variables.
foreach ($params as $var => $value) {
${$var} = $value;
}
// Context validation.
// OPTIONAL but in most web service it should be present.
$context = context_user::instance($USER->id);
self::validate_context($context);
// Capability checking.
// OPTIONAL but in most web service it should be present.
require_capability('moodle/user:viewdetails', $context, null, true, 'cannotviewprofile');
// Validate item details.
$itemdetails = json_decode(urldecode($itemdetails), true);
$itemdetails = self::validate_item_details($itemdetails);
// Get the item details identity type variable.
$identitytype = self::get_details_itentity_type($itemdetails);
// Validate grades.
$grades = json_decode(urldecode($grades), true);
$grades = self::validate_grades($grades);
// HACK Make sure grades has identity type; take from item details if must.
if ($grades and !isset($grades['identity_type'])) {
$grades['identity_type'] = null;
if ($identitytype) {
$grades['identity_type'] = $identitytype;
}
}
// Get the course.
$course = self::get_course($courseid, $identitytype);
if ($course === false) {
// No valid course specified.
return GRADE_UPDATE_FAILED;
}
$courseid = $course->id;
// Get the grade item.
$gitem = self::get_grade_item(
$source,
$courseid,
self::ITEM_DEFAULT_TYPE,
self::ITEM_DEFAULT_MODULE,
$iteminstance,
$itemnumber
);
if (!$gitem) {
return $result;
}
// Prepare result.
$result = array(
'item' => array(
'courseid' => $courseid,
'categoryid' => $gitem->categoryid,
'itemname' => $gitem->itemname,
'itemtype' => $gitem->itemtype,
'idnumber' => $gitem->idnumber,
'gradetype' => $gitem->gradetype,
'grademax' => $gitem->grademax,
),
'grades' => array(),
);
if ($grades) {
if (!empty($grades['userid'])) {
$gradegrades = grade_grade::fetch_users_grades($gitem, array($grades['userid']), false);
} else {
$gradegrades = grade_grade::fetch_all(array('itemid' => $gitem->id));
}
if ($gradegrades) {
foreach ($gradegrades as $grade) {
$result['grades'][] = array(
'userid' => $grade->userid,
'grade' => $grade->finalgrade,
);
}
}
}
return $result;
}
/**
* Returns description of method parameters.
*
* @return external_function_parameters
*/
public static function get_grade_parameters() {
return self::update_grade_parameters();
}
/**
* Returns description of method result value.
*
* @return external_description
*/
public static function get_grade_returns() {
return new external_single_structure(
array(
'item' => new external_single_structure(
array(
'courseid' => new external_value(PARAM_INT, 'Course id'),
'categoryid' => new external_value(PARAM_INT, 'Grade category id'),
'itemname' => new external_value(PARAM_RAW, 'Item name'),
'itemtype' => new external_value(PARAM_RAW, 'Item type'),
'idnumber' => new external_value(PARAM_INT, 'Course id'),
'gradetype' => new external_value(PARAM_INT, 'Grade type'),
'grademax' => new external_value(PARAM_FLOAT, 'Maximum grade'),
), 'An array of items associated with the grade item', VALUE_OPTIONAL
),
'grades' => new external_multiple_structure(
new external_single_structure(
array(
'userid' => new external_value(PARAM_INT, 'Student ID'),
'grade' => new external_value(PARAM_FLOAT, 'Student grade'),
)
), 'An array of grades associated with the grade item', VALUE_OPTIONAL
),
)
);
}
// DEPRACATED: GRADEBOOKSERVICE.
/**
* Allows external services to push grades into the course gradebook.
* Alias for {@link block_mhaairs_gradebookservice_external::update_grade()}.
*
* @return mixed
* @throws invalid_parameter_exception
* @throws moodle_exception
*/
public static function gradebookservice($source = 'mhaairs', $courseid ='',
$itemtype = self::ITEM_DEFAULT_TYPE, $itemmodule = self::ITEM_DEFAULT_MODULE,
$iteminstance = '0', $itemnumber = '0',
$grades = null, $itemdetails = null) {
return self::update_grade(
$source,
$courseid,
$itemtype,
$itemmodule,
$iteminstance,
$itemnumber,
$grades,
$itemdetails
);
}
/**
* Returns description of method parameters.
*
* @return external_function_parameters
*/
public static function gradebookservice_parameters() {
return self::update_grade_parameters();
}
/**
* Returns description of method result value.
*
* @return external_description
*/
public static function gradebookservice_returns() {
return self::update_grade_returns();
}
// UTILITY.
/**
* Creates/updates/delete an mhaairs grade item.
*
* @param string $source
* @param string $courseid
* @param string $iteminstance
* @param string $itemnumber
* @param string $itemdetails
* @return mixed
* @throws moodle_exception
*/
protected static function update_grade_item($source, $courseid, $iteminstance, $itemnumber, $itemdetails) {
// Create/update/delete the grade item if needed.
$gitem = self::get_grade_item(
$source,
$courseid,
self::ITEM_DEFAULT_TYPE,
self::ITEM_DEFAULT_MODULE,
$iteminstance,
$itemnumber,
$itemdetails
);
// Are we deleting the item?
$isdeleting = self::is_deleting($itemdetails);
// No grade item is either successful deletion of failure on creation.
if (!$gitem) {
if (!$isdeleting) {
return GRADE_UPDATE_FAILED;
} else {
return GRADE_UPDATE_OK;
}
}
// We might fail to delete.
if ($gitem and $isdeleting) {
return GRADE_UPDATE_FAILED;
}
return GRADE_UPDATE_OK;
}
/**
* Updates user grade in an mhaairs grade item.
*
* @param string $source
* @param string $courseid
* @param string $iteminstance
* @param string $itemnumber
* @param string $grades
* @return mixed
* @throws moodle_exception
*/
protected static function update_user_grade($source, $courseid, $iteminstance, $itemnumber, $grades) {
// Userid and rawgrade must be set.
if (!isset($grades['userid']) or !isset($grades['rawgrade'])) {
return GRADE_UPDATE_FAILED;
}
// Get the grade item.
$gitem = self::get_grade_item(
$source,
$courseid,
self::ITEM_DEFAULT_TYPE,
self::ITEM_DEFAULT_MODULE,
$iteminstance,
$itemnumber
);
// Verify grade item exists.
if (!$gitem) {
return GRADE_UPDATE_FAILED;
}
// Update the user grade.
if (!$gitem->update_final_grade($grades['userid'], $grades['rawgrade'], $source)) {
return GRADE_UPDATE_FAILED;
}
return GRADE_UPDATE_OK;
}
/**
* Cleans the item details data.
*
* @param array $itemdetails An array of item details and flags.
* @throws invalid_parameter_exception if $param is not of given type
* @return array|null
*/
protected static function validate_item_details($itemdetails) {
if (!$itemdetails or $itemdetails == "null") {
return null;
}
// The following are the variables that can be passed via itemdetails.
// We ignore any other variables.
$allowed = array(
'itemname' => PARAM_TEXT,
'idnumber' => PARAM_TEXT,
'gradetype' => PARAM_INT,
'grademax' => PARAM_FLOAT,
'hidden' => PARAM_INT,
'deleted' => PARAM_INT,
'categoryid' => PARAM_TEXT,
'identity_type' => PARAM_ALPHA,
'needsupdate' => PARAM_INT,
'useexisting' => PARAM_INT,
);
$details = array();
// Check type of each parameter.
foreach ($allowed as $var => $type) {
if (isset($itemdetails[$var]) and $itemdetails[$var] !== '') {
$details[$var] = validate_param($itemdetails[$var], $type);
}
}
// Remove empty deleted, b/c it grade_item cannot process it.
if (empty($details['deleted'])) {
unset($details['deleted']);
}
// Remove empty gradetype, so that it takes default.
if (empty($details['gradetype'])) {
unset($details['gradetype']);
}
// Remove empty grademax, so that it takes default.
if (empty($details['grademax'])) {
unset($details['grademax']);
}
return $details;
}
/**
* Cleans the grades data and maps the userid to the internal id.
*
* @param array $grades An array user grade details.
* @throws invalid_parameter_exception if $param is not of given type
* @return array|null
*/
protected static function validate_grades($grades) {
global $DB;
if (!$grades or $grades == "null") {
return null;
}
// The following are the variables that can be passed via grades.
// We ignore any other variables.
$allowed = array(
'userid' => PARAM_TEXT,
'rawgrade' => PARAM_FLOAT,
'identity_type' => PARAM_ALPHA,
);
$details = array();
// Check type of each parameter.
foreach ($allowed as $var => $type) {
if (isset($grades[$var]) and $grades[$var] !== '') {
$details[$var] = validate_param($grades[$var], $type);
}
}
// Map userID to numerical userID if required.
$idtype = !empty($details['identity_type']) ? $details['identity_type'] : null;
if (!$idtype or ($idtype != 'lti')) {
$userid = $DB->get_field('user', 'id', array('username' => $details['userid']));
if ($userid !== false) {
$details['userid'] = $userid;
}
}
return $details;
}
/**
* Adds the grade item to the category specified by fullname.
* If the category does not it is first created. This may create a performance hit
* as the service call locks the database table until it completes adding the category.
* Adding the category is delegated to an ad-hoc task.
* If desired the code can be adjusted to queue the task for cron instead of executing
* it here. This can consist of a mode switch by a config setting and when in background
* mode, calling \core\task\manager::queue_adhoc_task($addcat) to queue the task.
*
* @param \grade_item $gitem
* @param string $catnam
* @return void.
*/
protected static function update_grade_item_category($gitem, $catname) {
$courseid = $gitem->courseid;
// Fetch the grade category item that matches the target grade category by fullname.
// There could be more than one grade category with the same name, so fetch all and
// sort by id so that we always use the oldest one.
$fetchparams = array(
'fullname' => $catname,
'courseid' => $courseid
);
if ($categories = \grade_category::fetch_all($fetchparams)) {
// Categories found.
if (count($categories) > 1) {
// Sort by key which is the category id,
// to put the oldest first.
ksort($categories);
}
// Take the first.
$category = reset($categories);
if ($gitem->categoryid != $category->id) {
// Item needs update.
$gitem->categoryid = $category->id;
$gitem->update();
}
} else {
// Category not found so we task it.
$addcat = new \block_mhaairs\task\add_grade_category_task();
// We don't set blocking by set_blocking(true).
// We add custom data.
$addcat->set_custom_data(array(
'catname' => $catname,
'courseid' => $courseid,
'itemid' => $gitem->id,
));
// We execute the task.
// This will throw an exception if fails to create the category.
$addcat->execute();
}
}
/**
* Returns course object by id or idnumber, or false if not found.
*
* @param mixed $courseid
* @param bool $idtype
* @return false|stdClass
*/
private static function get_course($courseid, $idtype = null) {
global $DB;
// We must have course id.
if (empty($courseid)) {
return false;
}
// Do we need to look up the course only by internal id?
$idonly = $idtype ? in_array($idtype, array('internal', 'lti'), true) : false;
// Is courseid a positive integer and as such can be internal id?
$ispositiveint = filter_var($courseid, FILTER_VALIDATE_INT, array('options' => array('min_range' => 1)));
$course = false;
// First search course by id number.
if (!$idonly) {
$params = array('idnumber' => $courseid);
$course = $DB->get_record('course', $params, '*', IGNORE_MULTIPLE);
}
// If not found and the courseid is a positive integer, we search by course id.
if (!$course and $ispositiveint) {
$params = array('id' => (int) $courseid);
$course = $DB->get_record('course', $params);
}
return $course;
}
/**
* Returns a grade item with the specified data.
* If the item does not exist it is created.
*
* @param string $source
* @param int $courseid Course id
* @param string $itemtype Item type
* @param string $itemmodule Item module
* @param int $iteminstance Item instance
* @param int $itemnumber Item number
* @param array $itemdetails Item details
* @return grade_item A grade_item instance
*/
private static function get_grade_item($source, $courseid, $itemtype, $itemmodule,
$iteminstance = 0, $itemnumber = 0, $itemdetails = null) {
global $DB;
// TODO: Do we need to fetch course grade item?
if ($itemtype == 'course') {
// We are looking for the course grade item,
// so just return if exists.
$params = array(
'courseid' => $courseid,
'itemtype' => $itemtype,
);
return grade_item::fetch($params);
}
// Must have item instance.
if (empty($iteminstance)) {
return null;
}
// The target item params.
$itemparams = array(
'courseid' => $courseid,
'itemtype' => $itemtype,
'itemmodule' => $itemmodule,
'iteminstance' => $iteminstance,
'itemnumber' => $itemnumber,
);
// If there are no item details, we just need the item if exists.
if (!$itemdetails) {
return grade_item::fetch($itemparams);
}
// We are looking for an mhaairs manual item.
// CONTRIB-5863 - Migrate old mod/quiz grade items to manual/mhaairs.
if ($itemtype == self::ITEM_DEFAULT_TYPE) {
// Does a mod quiz item exist for the requested iteminstance?
$params = array(
'courseid' => $courseid,
'itemtype' => 'mod',
'itemmodule' => 'quiz',
'iteminstance' => $iteminstance,
'itemnumber' => $itemnumber,
);
if ($gitem = grade_item::fetch($params)) {
// There is such an item but we need to ensure first that
// it is not an actual quiz instance in the course.
$quizparams = array('id' => $iteminstance, 'course' => $courseid);
if (!$quizexists = $DB->record_exists('quiz', $quizparams)) {
// There is no such quiz instance in the course
// and we can safely convert to an mhaairs item.
$gitem->itemtype = $itemtype;
$gitem->itemmodule = $itemmodule;
$gitem->update();
}
}
}
// We may need to create/update/delete the item.
$useexisting = self::is_using_existing($itemdetails);
$isdeleting = self::is_deleting($itemdetails);
$itemname = self::get_details_item_name($itemdetails);
$catname = self::get_details_category_name($itemdetails);
// Remove the category id b/c it's not yet a valid value for the item.
unset($itemdetails['categoryid']);
// Try to use existing if applicable.
$existing = false;
if ($useexisting) {
if ($itemname) {
$gitems = null;
$params = array(
'courseid' => $courseid,
'itemtype' => self::ITEM_DEFAULT_TYPE,
'itemmodule' => self::ITEM_DEFAULT_MODULE,
'itemname' => $itemname,
);
// Try to fetch all mhaairs items with that name.
if (!$gitems = grade_item::fetch_all($params)) {
// No mhaairs items so try any manual items.
unset($params['itemmodule']);
$params['itemtype'] = 'manual';
$gitems = grade_item::fetch_all($params);
}
if ($gitems) {
// Take the first item.
$gitem = reset($gitems);
$gitem->itemmodule = $itemmodule;
$gitem->iteminstance = $iteminstance;
$gitem->itemnumber = $itemnumber;
$gitem->update();
$existing = true;
}
}
} else {
// Fetch the item.
$gitem = grade_item::fetch($itemparams);
}
// Create/update/delete the item.
if ($itemdetails and (!$gitem or !$existing)) {
// If creating, must have item name; the rest can default.
if (!$isdeleting and !$itemname) {
return null;
}
$result = grade_update(
$source,
$courseid,
$itemtype,
$itemmodule,
$iteminstance,
$itemnumber,
null,
$itemdetails
);
if ($result != GRADE_UPDATE_OK) {
return null;
}
if (!$gitem = grade_item::fetch($itemparams)) {
return null;
}
// Add the item to the specified category if applicable.
if ($catname) {
self::update_grade_item_category($gitem, $catname);
}
}
return $gitem;
}
/**
* Returns the requested identity type from the item details or null if not provided.
*
* @param array $itemdetails
* @return string|null
*/
private static function get_details_itentity_type($itemdetails) {
if (!empty($itemdetails['identity_type'])) {
return $itemdetails['identity_type'];
}
return null;
}
/**
* Returns the requested item name from the item details or null if not provided.
*
* @param array $itemdetails
* @return string|null
*/
private static function get_details_item_name($itemdetails) {
if (!empty($itemdetails['itemname'])) {
return $itemdetails['itemname'];
}
return null;
}
/**
* Returns the requested category id from the item details or null if not provided.
*
* @param array $itemdetails
* @return string|null
*/
private static function get_details_category_name($itemdetails) {
if (!empty($itemdetails['categoryid'])) {
return $itemdetails['categoryid'];
}
return null;
}
/**
* Returns true if 'deleted' parameter is not empty in item details; false otherwise.
*
* @param array $itemdetails
* @return bool
*/
private static function is_deleting($itemdetails) {
return !empty($itemdetails['deleted']);
}
/**
* Returns true if 'useexisting' parameter is not empty in item details; false otherwise.
*
* @param array $itemdetails
* @return bool
*/
private static function is_using_existing($itemdetails) {
return !empty($itemdetails['useexisting']);
}
}
/**
* Block mhaairs util web service.
*
* @package block_mhaairs
* @copyright 2014 Itamar Tzadok <itamar@substantialmethods.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class block_mhaairs_utilservice_external extends external_api {
/**
* Allows external applications to retrieve the environment info.
*
* @return
*/
public static function get_environment_info() {
// Get the environment info.
$result = MHUtil::get_environment_info();
return $result;
}
/**
* Returns description of method parameters.
*
* @return external_function_parameters
*/
public static function get_environment_info_parameters() {
return new external_function_parameters(array());
}
/**
* Returns description of method result value.
*
* @return external_description
*/
public static function get_environment_info_returns() {
return new external_single_structure(
array(
'system' => new external_value(PARAM_TEXT, 'Operating system'),
'server' => new external_value(PARAM_TEXT, 'Server api'),
'phpversion' => new external_value(PARAM_TEXT, 'PHP version'),
'dbvendor' => new external_value(PARAM_TEXT, 'DB vendor'),
'dbversion' => new external_value(PARAM_TEXT, 'DB version'),
'moodleversion' => new external_value(PARAM_TEXT, 'Moodle version'),
'pluginversion' => new external_value(PARAM_TEXT, 'Plugin version'),