Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
// This file is part of Moodle - http://moodle.org/
3
//
4
// Moodle is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8
//
9
// Moodle is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13
//
14
// You should have received a copy of the GNU General Public License
15
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
16
 
17
namespace gradereport_user\external;
18
 
19
use context_course;
20
use core_user;
21
use core_external\external_api;
22
use core_external\external_description;
23
use core_external\external_format_value;
24
use core_external\external_function_parameters;
25
use core_external\external_multiple_structure;
26
use core_external\external_single_structure;
27
use core_external\external_value;
28
use core_external\external_warnings;
29
use grade_plugin_return;
30
use graded_users_iterator;
31
use moodle_exception;
32
use stdClass;
33
use gradereport_user\report\user as user_report;
34
 
35
require_once($CFG->dirroot.'/grade/lib.php');
36
 
37
/**
38
 * External grade report API implementation
39
 *
40
 * @package    gradereport_user
41
 * @copyright  2015 Juan Leyva <juan@moodle.com>
42
 * @category   external
43
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
44
 */
45
class user extends external_api {
46
 
47
    /**
48
     * Validate access permissions to the report
49
     *
50
     * @param  int  $courseid the courseid
51
     * @param  int  $userid   the user id to retrieve data from
52
     * @param  int $groupid   the group id
53
     * @return array with the parameters cleaned and other required information
54
     * @since  Moodle 3.2
55
     */
56
    protected static function check_report_access(int $courseid, int $userid, int $groupid = 0): array {
57
        global $USER;
58
 
59
        // Validate the parameter.
60
        $params = self::validate_parameters(self::get_grades_table_parameters(),
61
            [
62
                'courseid' => $courseid,
63
                'userid' => $userid,
64
                'groupid' => $groupid,
65
            ]
66
        );
67
 
68
        // Compact/extract functions are not recommended.
69
        $courseid = $params['courseid'];
70
        $userid   = $params['userid'];
71
        $groupid  = $params['groupid'];
72
 
73
        // Function get_course internally throws an exception if the course doesn't exist.
74
        $course = get_course($courseid);
75
 
76
        $context = context_course::instance($courseid);
77
        self::validate_context($context);
78
 
79
        // Specific capabilities.
80
        require_capability('gradereport/user:view', $context);
81
 
82
        $user = null;
83
 
84
        if (empty($userid)) {
85
            require_capability('moodle/grade:viewall', $context);
86
        } else {
87
            $user = core_user::get_user($userid, '*', MUST_EXIST);
88
            core_user::require_active_user($user);
89
            // Check if we can view the user group (if any).
90
            // When userid == 0, we are retrieving all the users, we'll check then if a groupid is required.
91
            // User are always in their own group, also when they don't have groups.
92
            if ($userid != $USER->id && !groups_user_groups_visible($course, $user->id)) {
93
                throw new moodle_exception('notingroup');
94
            }
95
        }
96
 
97
        $access = false;
98
 
99
        if (has_capability('moodle/grade:viewall', $context)) {
100
            // Can view all course grades.
101
            $access = true;
102
        } else if ($userid == $USER->id && has_capability('moodle/grade:view', $context) && $course->showgrades) {
103
            // View own grades.
104
            $access = true;
105
        }
106
 
107
        if (!$access) {
108
            throw new moodle_exception('nopermissiontoviewgrades', 'error');
109
        }
110
 
111
        // User are always in their own group, also when they don't have groups.
112
        if ($userid != $USER->id) {
113
            if (!empty($groupid)) {
114
                // Determine if the group is visible to user.
115
                if (!groups_group_visible($groupid, $course)) {
116
                    throw new moodle_exception('notingroup');
117
                }
118
            } else {
119
                // Check to see if groups are being used here.
120
                if ($groupmode = groups_get_course_groupmode($course)) {
121
                    $groupid = groups_get_course_group($course);
122
                    // Determine if the group is visible to the user (this is particularly for group 0).
123
                    if (!groups_group_visible($groupid, $course)) {
124
                        throw new moodle_exception('notingroup');
125
                    }
126
                } else {
127
                    $groupid = 0;
128
                }
129
            }
130
        }
131
 
132
        return [$params, $course, $context, $user, $groupid];
133
    }
134
 
135
    /**
136
     * Get the report data
137
     * @param  stdClass $course  course object
138
     * @param  stdClass $context context object
139
     * @param  null|stdClass $user    user object (it can be null for all the users)
140
     * @param  int $userid       the user to retrieve data from, 0 for all
141
     * @param  int $groupid      the group id to filter
142
     * @param  bool $tabledata   whether to get the table data (true) or the gradeitemdata
143
     * @return array data and possible warnings
144
     * @since  Moodle 3.2
145
     */
146
    protected static function get_report_data(
147
        stdClass $course,
148
        stdClass $context,
149
        ?stdClass $user,
150
        int $userid,
151
        int $groupid,
152
        bool $tabledata = true
153
    ): array {
154
        global $CFG;
155
 
156
        $warnings = [];
157
        // Require files here to save some memory in case validation fails.
158
        require_once($CFG->dirroot . '/group/lib.php');
159
        require_once($CFG->libdir  . '/gradelib.php');
160
        require_once($CFG->dirroot . '/grade/lib.php');
161
        require_once($CFG->dirroot . '/grade/report/user/lib.php');
162
 
163
        // Force regrade to update items marked as 'needupdate'.
164
        grade_regrade_final_grades($course->id);
165
 
166
        $gpr = new grade_plugin_return(
167
            [
168
                'type'           => 'report',
169
                'plugin'         => 'user',
170
                'courseid'       => $course->id,
171
                'courseidnumber' => $course->idnumber,
172
                'userid'         => $userid
173
            ]
174
        );
175
 
176
        $reportdata = [];
177
 
178
        // Just one user.
179
        if ($user) {
180
            $report = new user_report($course->id, $gpr, $context, $userid);
181
            $report->fill_table();
182
 
183
            $gradeuserdata = [
184
                'courseid'       => $course->id,
185
                'courseidnumber' => $course->idnumber,
186
                'userid'         => $user->id,
187
                'userfullname'   => fullname($user),
188
                'useridnumber'   => $user->idnumber,
189
                'maxdepth'       => $report->maxdepth,
190
            ];
191
            if ($tabledata) {
192
                $gradeuserdata['tabledata'] = $report->tabledata;
193
            } else {
194
                $gradeuserdata['gradeitems'] = $report->gradeitemsdata;
195
            }
196
            $reportdata[] = $gradeuserdata;
197
        } else {
198
            $defaultgradeshowactiveenrol = !empty($CFG->grade_report_showonlyactiveenrol);
199
            $showonlyactiveenrol = get_user_preferences('grade_report_showonlyactiveenrol', $defaultgradeshowactiveenrol);
200
            $showonlyactiveenrol = $showonlyactiveenrol || !has_capability('moodle/course:viewsuspendedusers', $context);
201
 
202
            $gui = new graded_users_iterator($course, null, $groupid);
203
            $gui->require_active_enrolment($showonlyactiveenrol);
204
            $gui->init();
205
 
206
            while ($userdata = $gui->next_user()) {
207
                $currentuser = $userdata->user;
208
                $report = new user_report($course->id, $gpr, $context, $currentuser->id);
209
                $report->fill_table();
210
 
211
                $gradeuserdata = [
212
                    'courseid'       => $course->id,
213
                    'courseidnumber' => $course->idnumber,
214
                    'userid'         => $currentuser->id,
215
                    'userfullname'   => fullname($currentuser),
216
                    'useridnumber'   => $currentuser->idnumber,
217
                    'maxdepth'       => $report->maxdepth,
218
                ];
219
                if ($tabledata) {
220
                    $gradeuserdata['tabledata'] = $report->tabledata;
221
                } else {
222
                    $gradeuserdata['gradeitems'] = $report->gradeitemsdata;
223
                }
224
                $reportdata[] = $gradeuserdata;
225
            }
226
            $gui->close();
227
        }
228
        return [$reportdata, $warnings];
229
    }
230
 
231
    /**
232
     * Describes the parameters for get_grades_table.
233
     *
234
     * @return external_function_parameters
235
     * @since Moodle 2.9
236
     */
237
    public static function get_grades_table_parameters(): external_function_parameters {
238
        return new external_function_parameters (
239
            [
240
                'courseid' => new external_value(PARAM_INT, 'Course Id', VALUE_REQUIRED),
241
                'userid'   => new external_value(PARAM_INT, 'Return grades only for this user (optional)', VALUE_DEFAULT, 0),
242
                'groupid'  => new external_value(PARAM_INT, 'Get users from this group only', VALUE_DEFAULT, 0)
243
            ]
244
        );
245
    }
246
 
247
    /**
248
     * Returns a list of grades tables for users in a course.
249
     *
250
     * @param int $courseid Course Id
251
     * @param int $userid   Only this user (optional)
252
     * @param int $groupid  Get users from this group only
253
     *
254
     * @return array the grades tables
255
     * @since Moodle 2.9
256
     */
257
    public static function get_grades_table(int $courseid, int $userid = 0, int $groupid = 0): array {
258
 
259
        list($params, $course, $context, $user, $groupid) = self::check_report_access($courseid, $userid, $groupid);
260
        $userid = $params['userid'];
261
 
262
        // We pass userid because it can be still 0.
263
        list($tables, $warnings) = self::get_report_data($course, $context, $user, $userid, $groupid);
264
 
265
        return [
266
            'tables' => $tables,
267
            'warnings' => $warnings
268
        ];
269
    }
270
 
271
    /**
272
     * Creates a table column structure
273
     *
274
     * @return array
275
     * @since  Moodle 2.9
276
     */
277
    private static function grades_table_column(): array {
278
        return [
279
            'class'   => new external_value(PARAM_RAW, 'class'),
280
            'content' => new external_value(PARAM_RAW, 'cell content'),
281
            'headers' => new external_value(PARAM_RAW, 'headers')
282
        ];
283
    }
284
 
285
    /**
286
     * Describes tget_grades_table return value.
287
     *
288
     * @return external_single_structure
289
     * @since Moodle 2.9
290
     */
291
    public static function get_grades_table_returns(): external_single_structure {
292
        return new external_single_structure(
293
            [
294
                'tables' => new external_multiple_structure(
295
                    new external_single_structure(
296
                        [
297
                            'courseid' => new external_value(PARAM_INT, 'course id'),
298
                            'userid'   => new external_value(PARAM_INT, 'user id'),
299
                            'userfullname' => new external_value(PARAM_TEXT, 'user fullname'),
300
                            'maxdepth'   => new external_value(PARAM_INT, 'table max depth (needed for printing it)'),
301
                            'tabledata' => new external_multiple_structure(
302
                                new external_single_structure(
303
                                    [
304
                                        'itemname' => new external_single_structure(
305
                                            [
306
                                                'class' => new external_value(PARAM_RAW, 'class'),
307
                                                'colspan' => new external_value(PARAM_INT, 'col span'),
308
                                                'content'  => new external_value(PARAM_RAW, 'cell content'),
309
                                                'id'  => new external_value(PARAM_ALPHANUMEXT, 'id')
310
                                            ], 'The item returned data', VALUE_OPTIONAL
311
                                        ),
312
                                        'leader' => new external_single_structure(
313
                                            [
314
                                                'class' => new external_value(PARAM_RAW, 'class'),
315
                                                'rowspan' => new external_value(PARAM_INT, 'row span')
316
                                            ], 'The item returned data', VALUE_OPTIONAL
317
                                        ),
318
                                        'weight' => new external_single_structure(
319
                                            self::grades_table_column(), 'weight column', VALUE_OPTIONAL
320
                                        ),
321
                                        'grade' => new external_single_structure(
322
                                            self::grades_table_column(), 'grade column', VALUE_OPTIONAL
323
                                        ),
324
                                        'range' => new external_single_structure(
325
                                            self::grades_table_column(), 'range column', VALUE_OPTIONAL
326
                                        ),
327
                                        'percentage' => new external_single_structure(
328
                                            self::grades_table_column(), 'percentage column', VALUE_OPTIONAL
329
                                        ),
330
                                        'lettergrade' => new external_single_structure(
331
                                            self::grades_table_column(), 'lettergrade column', VALUE_OPTIONAL
332
                                        ),
333
                                        'rank' => new external_single_structure(
334
                                            self::grades_table_column(), 'rank column', VALUE_OPTIONAL
335
                                        ),
336
                                        'average' => new external_single_structure(
337
                                            self::grades_table_column(), 'average column', VALUE_OPTIONAL
338
                                        ),
339
                                        'feedback' => new external_single_structure(
340
                                            self::grades_table_column(), 'feedback column', VALUE_OPTIONAL
341
                                        ),
342
                                        'contributiontocoursetotal' => new external_single_structure(
343
                                            self::grades_table_column(), 'contributiontocoursetotal column', VALUE_OPTIONAL
344
                                        ),
345
                                        'parentcategories' => new external_multiple_structure(
346
                                            new external_value(PARAM_INT, 'Parent grade category ID.')
347
                                        ),
348
                                    ], 'table'
349
                                )
350
                            )
351
                        ]
352
                    )
353
                ),
354
                'warnings' => new external_warnings()
355
            ]
356
        );
357
    }
358
 
359
    /**
360
     * Returns description of method parameters
361
     *
362
     * @return external_function_parameters
363
     * @since Moodle 2.9
364
     */
365
    public static function view_grade_report_parameters(): external_function_parameters {
366
        return new external_function_parameters(
367
            [
368
                'courseid' => new external_value(PARAM_INT, 'id of the course'),
369
                'userid' => new external_value(PARAM_INT, 'id of the user, 0 means current user', VALUE_DEFAULT, 0),
370
            ]
371
        );
372
    }
373
 
374
    /**
375
     * Trigger the user report events, do the same that the web interface view of the report
376
     *
377
     * @param int $courseid id of course
378
     * @param int $userid id of the user the report belongs to
379
     * @return array of warnings and status result
380
     * @since Moodle 2.9
381
     * @throws moodle_exception
382
     */
383
    public static function view_grade_report(int $courseid, int $userid = 0): array {
384
        global $CFG, $USER;
385
        require_once($CFG->dirroot . "/grade/lib.php");
386
        require_once($CFG->dirroot . "/grade/report/user/lib.php");
387
 
388
        $params = self::validate_parameters(self::view_grade_report_parameters(),
389
            [
390
                'courseid' => $courseid,
391
                'userid' => $userid
392
            ]);
393
 
394
        $warnings = [];
395
 
396
        $course = get_course($params['courseid']);
397
 
398
        $context = context_course::instance($course->id);
399
        self::validate_context($context);
400
 
401
        $userid = $params['userid'];
402
        if (empty($userid)) {
403
            $userid = $USER->id;
404
        } else {
405
            $user = core_user::get_user($userid, '*', MUST_EXIST);
406
            core_user::require_active_user($user);
407
        }
408
 
409
        $access = false;
410
 
411
        if (has_capability('moodle/grade:viewall', $context)) {
412
            // Can view all course grades (any user).
413
            $access = true;
414
        } else if ($userid == $USER->id && has_capability('moodle/grade:view', $context) && $course->showgrades) {
415
            // View own grades.
416
            $access = true;
417
        }
418
 
419
        if (!$access) {
420
            throw new moodle_exception('nopermissiontoviewgrades', 'error');
421
        }
422
 
423
        // Create a report instance. We don't need the gpr second parameter.
424
        $report = new user_report($course->id, null, $context, $userid);
425
        $report->viewed();
426
 
427
        return [
428
            'status' => true,
429
            'warnings' => $warnings
430
        ];
431
    }
432
 
433
    /**
434
     * Returns description of method result value
435
     *
436
     * @return external_description
437
     * @since Moodle 2.9
438
     */
439
    public static function view_grade_report_returns(): external_description {
440
        return new external_single_structure(
441
            [
442
                'status' => new external_value(PARAM_BOOL, 'status: true if success'),
443
                'warnings' => new external_warnings()
444
            ]
445
        );
446
    }
447
 
448
    /**
449
     * Describes the parameters for get_grade_items.
450
     *
451
     * @return external_function_parameters
452
     * @since Moodle 3.2
453
     */
454
    public static function get_grade_items_parameters(): external_function_parameters {
455
        return self::get_grades_table_parameters();
456
    }
457
 
458
    /**
459
     * Returns the complete list of grade items for users in a course.
460
     *
461
     * @param int $courseid Course Id
462
     * @param int $userid   Only this user (optional)
463
     * @param int $groupid  Get users from this group only
464
     *
465
     * @return array the grades tables
466
     * @since Moodle 3.2
467
     */
468
    public static function get_grade_items(int $courseid, int $userid = 0, int $groupid = 0): array {
469
 
470
        list($params, $course, $context, $user, $groupid) = self::check_report_access($courseid, $userid, $groupid);
471
        $userid = $params['userid'];
472
 
473
        // We pass userid because it can be still 0.
474
        list($gradeitems, $warnings) = self::get_report_data($course, $context, $user, $userid, $groupid, false);
475
 
476
        foreach ($gradeitems as $gradeitem) {
477
            if (isset($gradeitem['feedback']) && isset($gradeitem['feedbackformat'])) {
478
                list($gradeitem['feedback'], $gradeitem['feedbackformat']) =
479
                    \core_external\util::format_text($gradeitem['feedback'], $gradeitem['feedbackformat'], $context->id);
480
            }
481
        }
482
 
483
        return [
484
            'usergrades' => $gradeitems,
485
            'warnings' => $warnings
486
        ];
487
    }
488
 
489
    /**
490
     * Describes tget_grade_items return value.
491
     *
492
     * @return external_single_structure
493
     * @since Moodle 3.2
494
     */
495
    public static function get_grade_items_returns(): external_single_structure {
496
        return new external_single_structure(
497
            [
498
                'usergrades' => new external_multiple_structure(
499
                    new external_single_structure(
500
                        [
501
                            'courseid' => new external_value(PARAM_INT, 'course id'),
502
                            'courseidnumber' => new external_value(PARAM_TEXT, 'course idnumber'),
503
                            'userid'   => new external_value(PARAM_INT, 'user id'),
504
                            'userfullname' => new external_value(PARAM_TEXT, 'user fullname'),
505
                            'useridnumber' => new external_value(
506
                                core_user::get_property_type('idnumber'), 'user idnumber'),
507
                            'maxdepth'   => new external_value(PARAM_INT, 'table max depth (needed for printing it)'),
508
                            'gradeitems' => new external_multiple_structure(
509
                                new external_single_structure(
510
                                    [
511
                                        'id' => new external_value(PARAM_INT, 'Grade item id'),
11 efrain 512
                                        'itemname' => new external_value(PARAM_RAW, 'Grade item name'),
1 efrain 513
                                        'itemtype' => new external_value(PARAM_ALPHA, 'Grade item type'),
514
                                        'itemmodule' => new external_value(PARAM_PLUGIN, 'Grade item module'),
515
                                        'iteminstance' => new external_value(PARAM_INT, 'Grade item instance'),
516
                                        'itemnumber' => new external_value(PARAM_INT, 'Grade item item number'),
517
                                        'idnumber' => new external_value(PARAM_TEXT, 'Grade item idnumber'),
518
                                        'categoryid' => new external_value(PARAM_INT, 'Grade item category id'),
519
                                        'outcomeid' => new external_value(PARAM_INT, 'Outcome id'),
520
                                        'scaleid' => new external_value(PARAM_INT, 'Scale id'),
521
                                        'locked' => new external_value(PARAM_BOOL, 'Grade item for user locked?', VALUE_OPTIONAL),
522
                                        'cmid' => new external_value(PARAM_INT, 'Course module id (if type mod)', VALUE_OPTIONAL),
523
                                        'weightraw' => new external_value(PARAM_FLOAT, 'Weight raw', VALUE_OPTIONAL),
524
                                        'weightformatted' => new external_value(PARAM_NOTAGS, 'Weight', VALUE_OPTIONAL),
525
                                        'status' => new external_value(PARAM_ALPHA, 'Status', VALUE_OPTIONAL),
526
                                        'graderaw' => new external_value(PARAM_FLOAT, 'Grade raw', VALUE_OPTIONAL),
527
                                        'gradedatesubmitted' => new external_value(PARAM_INT, 'Grade submit date', VALUE_OPTIONAL),
528
                                        'gradedategraded' => new external_value(PARAM_INT, 'Grade graded date', VALUE_OPTIONAL),
529
                                        'gradehiddenbydate' => new external_value(PARAM_BOOL, 'Grade hidden by date?', VALUE_OPTIONAL),
530
                                        'gradeneedsupdate' => new external_value(PARAM_BOOL, 'Grade needs update?', VALUE_OPTIONAL),
531
                                        'gradeishidden' => new external_value(PARAM_BOOL, 'Grade is hidden?', VALUE_OPTIONAL),
532
                                        'gradeislocked' => new external_value(PARAM_BOOL, 'Grade is locked?', VALUE_OPTIONAL),
533
                                        'gradeisoverridden' => new external_value(PARAM_BOOL, 'Grade overridden?', VALUE_OPTIONAL),
534
                                        'gradeformatted' => new external_value(PARAM_RAW, 'The grade formatted', VALUE_OPTIONAL),
535
                                        'grademin' => new external_value(PARAM_FLOAT, 'Grade min', VALUE_OPTIONAL),
536
                                        'grademax' => new external_value(PARAM_FLOAT, 'Grade max', VALUE_OPTIONAL),
537
                                        'rangeformatted' => new external_value(PARAM_NOTAGS, 'Range formatted', VALUE_OPTIONAL),
538
                                        'percentageformatted' => new external_value(PARAM_NOTAGS, 'Percentage', VALUE_OPTIONAL),
539
                                        'lettergradeformatted' => new external_value(PARAM_NOTAGS, 'Letter grade', VALUE_OPTIONAL),
540
                                        'rank' => new external_value(PARAM_INT, 'Rank in the course', VALUE_OPTIONAL),
541
                                        'numusers' => new external_value(PARAM_INT, 'Num users in course', VALUE_OPTIONAL),
542
                                        'averageformatted' => new external_value(PARAM_NOTAGS, 'Grade average', VALUE_OPTIONAL),
543
                                        'feedback' => new external_value(PARAM_RAW, 'Grade feedback', VALUE_OPTIONAL),
544
                                        'feedbackformat' => new external_format_value('feedback', VALUE_OPTIONAL),
545
                                    ], 'Grade items'
546
                                )
547
                            )
548
                        ]
549
                    )
550
                ),
551
                'warnings' => new external_warnings()
552
            ]
553
        );
554
    }
555
}