MDL-29794 It is now possible to re-use a form without sharing it as a template
[moodle.git] / grade / grading / lib.php
CommitLineData
4333580e
DM
1<?php
2
3// This file is part of Moodle - http://moodle.org/
4//
5// Moodle is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// Moodle is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU General Public License
16// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17
18/**
19 * Advanced grading methods support
20 *
21 * @package core
22 * @subpackage grading
23 * @copyright 2011 David Mudrak <david@moodle.com>
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 */
26
27defined('MOODLE_INTERNAL') || die();
28
29/**
30 * Factory method returning an instance of the grading manager
31 *
fb13a148 32 * @param stdClass|int $context or $areaid
4333580e 33 * @param string $component the frankenstyle name of the component
8a4acb3a 34 * @param string $area the name of the gradable area
4333580e
DM
35 * @return grading_manager
36 */
fb13a148
DM
37function get_grading_manager($context_or_areaid = null, $component = null, $area = null) {
38 global $DB;
4333580e
DM
39
40 $manager = new grading_manager();
41
fb13a148
DM
42 if (is_object($context_or_areaid)) {
43 $context = $context_or_areaid;
44 } else {
45 $context = null;
46
47 if (is_numeric($context_or_areaid)) {
48 $manager->load($context_or_areaid);
49 return $manager;
50 }
51 }
52
4333580e
DM
53 if (!is_null($context)) {
54 $manager->set_context($context);
55 }
56
57 if (!is_null($component)) {
58 $manager->set_component($component);
59 }
60
8a4acb3a
DM
61 if (!is_null($area)) {
62 $manager->set_area($area);
4333580e
DM
63 }
64
65 return $manager;
66}
67
68/**
69 * General class providing access to common grading features
70 *
9b8550f8
DM
71 * Grading manager provides access to the particular grading method controller
72 * in that area.
73 *
4333580e
DM
74 * Fully initialized instance of the grading manager operates over a single
75 * gradable area. It is possible to work with a partially initialized manager
8a4acb3a
DM
76 * that knows just context and component without known area, for example.
77 * It is also possible to change context, component and area of an existing
4333580e
DM
78 * manager. Such pattern is used when copying form definitions, for example.
79 */
80class grading_manager {
81
82 /** @var stdClass the context */
83 protected $context;
84
85 /** @var string the frankenstyle name of the component */
86 protected $component;
87
88 /** @var string the name of the gradable area */
8a4acb3a 89 protected $area;
4333580e 90
9b8550f8
DM
91 /** @var stdClass|false|null the raw record from {grading_areas}, false if does not exist, null if invalidated cache */
92 private $areacache = null;
93
21d37aa6
DM
94 /**
95 * @return stdClass grading manager context
96 */
97 public function get_context() {
98 return $this->context;
99 }
100
4333580e
DM
101 /**
102 * Sets the context the manager operates on
103 *
104 * @param stdClass $context
105 */
106 public function set_context(stdClass $context) {
9b8550f8 107 $this->areacache = null;
4333580e
DM
108 $this->context = $context;
109 }
110
21d37aa6
DM
111 /**
112 * @return string grading manager component
113 */
114 public function get_component() {
115 return $this->component;
116 }
117
4333580e
DM
118 /**
119 * Sets the component the manager operates on
120 *
121 * @param string $component the frankenstyle name of the component
122 */
123 public function set_component($component) {
9b8550f8
DM
124 $this->areacache = null;
125 list($type, $name) = normalize_component($component);
126 $this->component = $type.'_'.$name;
4333580e
DM
127 }
128
21d37aa6
DM
129 /**
130 * @return string grading manager area name
131 */
132 public function get_area() {
133 return $this->area;
134 }
135
4333580e 136 /**
8a4acb3a 137 * Sets the area the manager operates on
4333580e 138 *
8a4acb3a 139 * @param string $area the name of the gradable area
4333580e 140 */
8a4acb3a 141 public function set_area($area) {
9b8550f8 142 $this->areacache = null;
8a4acb3a 143 $this->area = $area;
4333580e
DM
144 }
145
6832a102
DM
146 /**
147 * Returns a text describing the context and the component
148 *
149 * At the moment this works for gradable areas in course modules. In the future, this
150 * method should be improved so it works for other contexts (blocks, gradebook items etc)
151 * or subplugins.
152 *
153 * @return string
154 */
155 public function get_component_title() {
156
157 $this->ensure_isset(array('context', 'component'));
6832a102 158
fde33804
DM
159 if ($this->get_context()->contextlevel == CONTEXT_SYSTEM) {
160 if ($this->get_component() == 'core_grading') {
161 $title = ''; // we are in the bank UI
162 } else {
163 throw new coding_exception('Unsupported component at the system context');
164 }
165
166 } else if ($this->get_context()->contextlevel >= CONTEXT_COURSE) {
167 list($context, $course, $cm) = get_context_info_array($this->get_context()->id);
168
169 if (!empty($cm->name)) {
170 $title = $cm->name;
171 } else {
172 debugging('Gradable areas are currently supported at the course module level only', DEBUG_DEVELOPER);
173 $title = $this->get_component();
174 }
175
6832a102 176 } else {
fde33804 177 throw new coding_exception('Unsupported gradable area context level');
6832a102
DM
178 }
179
180 return $title;
181 }
182
183 /**
184 * Returns the localized title of the currently set area
185 *
186 * @return string
187 */
188 public function get_area_title() {
189
fde33804
DM
190 if ($this->get_context()->contextlevel == CONTEXT_SYSTEM) {
191 return '';
192
193 } else if ($this->get_context()->contextlevel >= CONTEXT_COURSE) {
194 $this->ensure_isset(array('context', 'component', 'area'));
195 $areas = $this->get_available_areas();
196 if (array_key_exists($this->get_area(), $areas)) {
197 return $areas[$this->get_area()];
198 } else {
199 debugging('Unknown area!');
200 return '???';
201 }
6832a102 202
fde33804
DM
203 } else {
204 throw new coding_exception('Unsupported context level');
205 }
6832a102
DM
206 }
207
fb13a148
DM
208 /**
209 * Loads the gradable area info from the database
210 *
211 * @param int $areaid
212 */
213 public function load($areaid) {
214 global $DB;
215
216 $this->areacache = $DB->get_record('grading_areas', array('id' => $areaid), '*', MUST_EXIST);
217 $this->context = get_context_instance_by_id($this->areacache->contextid, MUST_EXIST);
218 $this->component = $this->areacache->component;
219 $this->area = $this->areacache->areaname;
220 }
221
4333580e
DM
222 /**
223 * Returns the list of available grading methods in the given context
224 *
225 * Basically this returns the list of installed grading plugins with an empty value
226 * for simple direct grading. In the future, the list of available methods may be
227 * controlled per-context.
228 *
229 * Requires the context property to be set in advance.
6c9e506c
DM
230 *
231 * @param bool $includenone should the 'Simple direct grading' be included
4333580e
DM
232 * @return array of the (string)name => (string)localized title of the method
233 */
6c9e506c 234 public function get_available_methods($includenone = true) {
4333580e
DM
235
236 $this->ensure_isset(array('context'));
237
6c9e506c
DM
238 if ($includenone) {
239 $list = array('' => get_string('gradingmethodnone', 'core_grading'));
240 } else {
241 $list = array();
242 }
243
244 foreach (get_plugin_list('gradingform') as $name => $location) {
245 $list[$name] = get_string('pluginname', 'gradingform_'.$name);
246 }
247
248 return $list;
4333580e
DM
249 }
250
251 /**
252 * Returns the list of gradable areas in the given context and component
253 *
254 * This performs a callback to the library of the relevant plugin to obtain
255 * the list of supported areas.
256 * @return array of (string)areacode => (string)localized title of the area
257 */
258 public function get_available_areas() {
259 global $CFG;
260
261 $this->ensure_isset(array('context', 'component'));
262
263 // example: if the given context+component lead to mod_assignment, this method
264 // will do something like
265 // require_once($CFG->dirroot.'/mod/assignment/lib.php');
266 // return assignment_gradable_area_list();
267
fde33804 268 // todo - what to return for bank areas in the system context
4333580e 269 // todo - hardcoded list for now
9b8550f8 270 return array('submission' => 'Submissions');
4333580e
DM
271 }
272
273 /**
8a4acb3a 274 * Returns the currently active grading method in the gradable area
4333580e 275 *
64402867 276 * @return string|null the name of the grading plugin of null if it has not been set
4333580e 277 */
8a4acb3a 278 public function get_active_method() {
64402867
DM
279 global $DB;
280
281 $this->ensure_isset(array('context', 'component', 'area'));
282
283 // get the current grading area record if it exists
9b8550f8
DM
284 if (is_null($this->areacache)) {
285 $this->areacache = $DB->get_record('grading_areas', array(
286 'contextid' => $this->context->id,
287 'component' => $this->component,
288 'areaname' => $this->area),
289 '*', IGNORE_MISSING);
290 }
64402867 291
9b8550f8 292 if ($this->areacache === false) {
64402867
DM
293 // no area record yet
294 return null;
295 }
296
9b8550f8 297 return $this->areacache->activemethod;
64402867
DM
298 }
299
300 /**
301 * Sets the currently active grading method in the gradable area
302 *
303 * @param string $method the method name, eg 'rubric' (must be available)
3bd217aa 304 * @return bool true if the method changed or was just set, false otherwise
64402867
DM
305 */
306 public function set_active_method($method) {
307 global $DB;
308
8a4acb3a 309 $this->ensure_isset(array('context', 'component', 'area'));
64402867 310
8cd65f16
DM
311 // make sure the passed method is empty or a valid plugin name
312 if (empty($method)) {
313 $method = null;
314 } else {
315 if ('gradingform_'.$method !== clean_param('gradingform_'.$method, PARAM_COMPONENT)) {
316 throw new moodle_exception('invalid_method_name', 'core_grading');
317 }
318 $available = $this->get_available_methods(false);
319 if (!array_key_exists($method, $available)) {
320 throw new moodle_exception('invalid_method_name', 'core_grading');
321 }
64402867
DM
322 }
323
324 // get the current grading area record if it exists
9b8550f8
DM
325 if (is_null($this->areacache)) {
326 $this->areacache = $DB->get_record('grading_areas', array(
327 'contextid' => $this->context->id,
328 'component' => $this->component,
329 'areaname' => $this->area),
330 '*', IGNORE_MISSING);
331 }
64402867 332
3bd217aa
DM
333 $methodchanged = false;
334
9b8550f8 335 if ($this->areacache === false) {
64402867
DM
336 // no area record yet, create one with the active method set
337 $area = array(
338 'contextid' => $this->context->id,
339 'component' => $this->component,
340 'areaname' => $this->area,
341 'activemethod' => $method);
342 $DB->insert_record('grading_areas', $area);
3bd217aa 343 $methodchanged = true;
64402867
DM
344
345 } else {
346 // update the existing record if needed
8cd65f16 347 if ($this->areacache->activemethod !== $method) {
9b8550f8 348 $DB->set_field('grading_areas', 'activemethod', $method, array('id' => $this->areacache->id));
3bd217aa 349 $methodchanged = true;
64402867
DM
350 }
351 }
9b8550f8
DM
352
353 $this->areacache = null;
3bd217aa
DM
354
355 return $methodchanged;
9b8550f8
DM
356 }
357
358 /**
359 * Extends the settings navigation with the grading settings
360 *
361 * This function is called when the context for the page is an activity module with the
362 * FEATURE_ADVANCED_GRADING and the user has the permission moodle/grade:managegradingforms.
363 *
364 * @param settings_navigation $settingsnav {@link settings_navigation}
365 * @param navigation_node $modulenode {@link navigation_node}
366 */
367 public function extend_settings_navigation(settings_navigation $settingsnav, navigation_node $modulenode=null) {
9b8550f8
DM
368
369 $this->ensure_isset(array('context', 'component'));
370
371 $areas = $this->get_available_areas();
372
373 if (empty($areas)) {
374 // no money, no funny
375 return;
8168299d 376
98a73bb7
DM
377 } else if (count($areas) == 1) {
378 // make just a single node for the management screen
379 $areatitle = reset($areas);
380 $areaname = key($areas);
9b8550f8
DM
381 $this->set_area($areaname);
382 $method = $this->get_active_method();
98a73bb7
DM
383 $managementnode = $modulenode->add(get_string('gradingmanagement', 'core_grading'),
384 $this->get_management_url(), settings_navigation::TYPE_CUSTOM);
385 if ($method) {
386 $controller = $this->get_controller($method);
387 $controller->extend_settings_navigation($settingsnav, $managementnode);
9b8550f8
DM
388 }
389
98a73bb7
DM
390 } else {
391 // make management screen node for each area
392 $managementnode = $modulenode->add(get_string('gradingmanagement', 'core_grading'),
393 null, settings_navigation::TYPE_CUSTOM);
394 foreach ($areas as $areaname => $areatitle) {
395 $this->set_area($areaname);
396 $method = $this->get_active_method();
397 $node = $managementnode->add($areatitle,
398 $this->get_management_url(), settings_navigation::TYPE_CUSTOM);
399 if ($method) {
400 $controller = $this->get_controller($method);
401 $controller->extend_settings_navigation($settingsnav, $node);
402 }
9b8550f8 403 }
9b8550f8
DM
404 }
405 }
406
407 /**
408 * Returns the given method's controller in the gradable area
409 *
410 * @param string $method the method name, eg 'rubric' (must be available)
411 * @return grading_controller
412 */
413 public function get_controller($method) {
414 global $CFG;
415
416 $this->ensure_isset(array('context', 'component', 'area'));
417
418 // make sure the passed method is a valid plugin name
419 if ('gradingform_'.$method !== clean_param('gradingform_'.$method, PARAM_COMPONENT)) {
420 throw new moodle_exception('invalid_method_name', 'core_grading');
421 }
422 $available = $this->get_available_methods(false);
423 if (!array_key_exists($method, $available)) {
424 throw new moodle_exception('invalid_method_name', 'core_grading');
425 }
426
427 // get the current grading area record if it exists
428 if (is_null($this->areacache)) {
429 $this->areacache = $DB->get_record('grading_areas', array(
430 'contextid' => $this->context->id,
431 'component' => $this->component,
432 'areaname' => $this->area),
433 '*', IGNORE_MISSING);
434 }
435
436 if ($this->areacache === false) {
437 // no area record yet, create one
438 $area = array(
439 'contextid' => $this->context->id,
440 'component' => $this->component,
441 'areaname' => $this->area);
442 $areaid = $DB->insert_record('grading_areas', $area);
443 // reload the cache
444 $this->areacache = $DB->get_record('grading_areas', array('id' => $areaid), '*', MUST_EXIST);
445 }
446
447 require_once($CFG->dirroot.'/grade/grading/form/'.$method.'/lib.php');
3e43eff5 448 $classname = 'gradingform_'.$method.'_controller';
9b8550f8
DM
449
450 return new $classname($this->context, $this->component, $this->area, $this->areacache->id);
4333580e
DM
451 }
452
18e6298c
MG
453 /**
454 * Returns the controller for the active method if it is available
03d448e5
DM
455 *
456 * @return null|grading_controller
18e6298c
MG
457 */
458 public function get_active_controller() {
459 if ($gradingmethod = $this->get_active_method()) {
460 $controller = $this->get_controller($gradingmethod);
461 if ($controller->is_form_available()) {
462 return $controller;
463 }
464 }
465 return null;
466 }
467
03d448e5
DM
468 /**
469 * Returns the URL of the grading area management page
470 *
471 * @param moodle_url $returnurl optional URL of the page where the user should be sent back to
472 * @return moodle_url
473 */
98a73bb7 474 public function get_management_url(moodle_url $returnurl = null) {
03d448e5
DM
475
476 $this->ensure_isset(array('context', 'component'));
477
478 if ($this->areacache) {
479 $params = array('areaid' => $this->areacache->id);
480 } else {
481 $params = array('contextid' => $this->context->id, 'component' => $this->component);
98a73bb7
DM
482 if ($this->area) {
483 $params['area'] = $this->area;
6832a102 484 }
03d448e5
DM
485 }
486
487 if (!is_null($returnurl)) {
488 $params['returnurl'] = $returnurl->out(false);
489 }
490
6832a102 491 return new moodle_url('/grade/grading/manage.php', $params);
03d448e5
DM
492 }
493
fde33804
DM
494 /**
495 * Creates a new shared area to hold a grading form template
496 *
497 * Shared area are implemented as virtual gradable areas at the system level context
498 * with the component set to core_grading and unique random area name.
499 *
500 * @param string $method the name of the plugin we create the area for
501 * @return int the new area id
502 */
503 public function create_shared_area($method) {
504 global $DB;
505
506 // generate some unique random name for the new area
507 $name = $method . '_' . sha1(rand().uniqid($method, true));
508 // create new area record
509 $area = array(
510 'contextid' => get_system_context()->id,
511 'component' => 'core_grading',
512 'areaname' => $name,
513 'activemethod' => $method);
514 return $DB->insert_record('grading_areas', $area);
515 }
516
20836db9
DM
517 /**
518 * Helper method to tokenize the given string
519 *
520 * Splits the given string into smaller strings. This is a helper method for
521 * full text searching in grading forms. If the given string is surrounded with
522 * double quotes, the resulting array consists of a single item containing the
523 * quoted content.
524 *
525 * Otherwise, string like 'grammar, english language' would be tokenized into
526 * the three tokens 'grammar', 'english', 'language'.
527 *
528 * One-letter tokens like are dropped in non-phrase mode. Repeated tokens are
529 * returned just once.
530 *
531 * @param string $needle
532 * @return array
533 */
534 public static function tokenize($needle) {
535
536 // check if we are searching for the exact phrase
537 if (preg_match('/^[\s]*"[\s]*(.*?)[\s]*"[\s]*$/', $needle, $matches)) {
538 $token = $matches[1];
539 if ($token === '') {
540 return array();
541 } else {
542 return array($token);
543 }
544 }
545
546 // split the needle into smaller parts separated by non-word characters
547 $tokens = preg_split("/\W/u", $needle);
548 // keep just non-empty parts
549 $tokens = array_filter($tokens);
550 // distinct
551 $tokens = array_unique($tokens);
552 // drop one-letter tokens
553 foreach ($tokens as $ix => $token) {
554 if (strlen($token) == 1) {
555 unset($tokens[$ix]);
556 }
557 }
558
559 return array_values($tokens);
560 }
561
9b8550f8 562 ////////////////////////////////////////////////////////////////////////////
64402867 563
4333580e
DM
564 /**
565 * Make sure that the given properties were set to some not-null value
566 *
567 * @param array $properties the list of properties
568 * @throws coding_exception
569 */
570 private function ensure_isset(array $properties) {
571 foreach ($properties as $property) {
572 if (!isset($this->$property)) {
9b8550f8 573 throw new coding_exception('The property "'.$property.'" is not set.');
4333580e
DM
574 }
575 }
576 }
577}