PageRenderTime 57ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/classes/grading_external.php

https://bitbucket.org/moodle/moodle
PHP | 583 lines | 412 code | 35 blank | 136 comment | 40 complexity | ecbe7b112dce28b840df4f3aa120f171 MD5 | raw file
Possible License(s): Apache-2.0, LGPL-2.1, BSD-3-Clause, MIT, GPL-3.0
  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. * External grading API
  18. *
  19. * @package core_grading
  20. * @since Moodle 2.5
  21. * @copyright 2013 Paul Charsley
  22. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  23. */
  24. defined('MOODLE_INTERNAL') || die;
  25. require_once("$CFG->libdir/externallib.php");
  26. require_once("$CFG->dirroot/grade/grading/lib.php");
  27. /**
  28. * core grading functions
  29. */
  30. class core_grading_external extends external_api {
  31. /**
  32. * Describes the parameters for get_definitions
  33. * @return external_function_parameters
  34. * @since Moodle 2.5
  35. */
  36. public static function get_definitions_parameters() {
  37. return new external_function_parameters(
  38. array(
  39. 'cmids' => new external_multiple_structure(
  40. new external_value(PARAM_INT, 'course module id'), '1 or more course module ids'),
  41. 'areaname' => new external_value(PARAM_AREA, 'area name'),
  42. 'activeonly' => new external_value(PARAM_BOOL, 'Only the active method', VALUE_DEFAULT, 0)
  43. )
  44. );
  45. }
  46. /**
  47. * Returns the definitions for the requested course module ids
  48. * @param array of ints $cmids
  49. * @param string $areaname
  50. * @param boolean $activeonly default is false, if true, only the active method is returned
  51. * @return array of areas with definitions for each requested course module id
  52. * @since Moodle 2.5
  53. */
  54. public static function get_definitions($cmids, $areaname, $activeonly = false) {
  55. global $DB, $CFG;
  56. require_once("$CFG->dirroot/grade/grading/form/lib.php");
  57. $params = self::validate_parameters(self::get_definitions_parameters(),
  58. array('cmids' => $cmids,
  59. 'areaname' => $areaname,
  60. 'activeonly' => $activeonly));
  61. $warnings = array();
  62. $areas = array();
  63. foreach ($params['cmids'] as $cmid) {
  64. $context = context_module::instance($cmid);
  65. try {
  66. self::validate_context($context);
  67. } catch (Exception $e) {
  68. $warnings[] = array(
  69. 'item' => 'module',
  70. 'itemid' => $cmid,
  71. 'message' => 'No access rights in module context',
  72. 'warningcode' => '1'
  73. );
  74. continue;
  75. }
  76. // Check if the user has managegradingforms capability.
  77. $isgradingmethodmanager = false;
  78. if (has_capability('moodle/grade:managegradingforms', $context)) {
  79. $isgradingmethodmanager = true;
  80. }
  81. $module = get_coursemodule_from_id('', $cmid, 0, false, MUST_EXIST);
  82. $componentname = "mod_".$module->modname;
  83. // Get the grading manager.
  84. $gradingmanager = get_grading_manager($context, $componentname, $params['areaname']);
  85. // Get the controller for each grading method.
  86. $methods = array();
  87. if ($params['activeonly'] == true) {
  88. $methods[] = $gradingmanager->get_active_method();
  89. } else {
  90. $methods = array_keys($gradingmanager->get_available_methods(false));
  91. }
  92. $area = array();
  93. $area['cmid'] = $cmid;
  94. $area['contextid'] = $context->id;
  95. $area['component'] = $componentname;
  96. $area['areaname'] = $params['areaname'];
  97. $area['activemethod'] = $gradingmanager->get_active_method();
  98. $area['definitions'] = array();
  99. foreach ($methods as $method) {
  100. $controller = $gradingmanager->get_controller($method);
  101. $def = $controller->get_definition(true);
  102. if ($def == false) {
  103. continue;
  104. }
  105. if ($isgradingmethodmanager == false) {
  106. $isviewable = true;
  107. if ($def->status != gradingform_controller::DEFINITION_STATUS_READY) {
  108. $warnings[] = array(
  109. 'item' => 'module',
  110. 'itemid' => $cmid,
  111. 'message' => 'Capability moodle/grade:managegradingforms required to view draft definitions',
  112. 'warningcode' => '1'
  113. );
  114. $isviewable = false;
  115. }
  116. if (!empty($def->options)) {
  117. $options = json_decode($def->options);
  118. if (isset($options->alwaysshowdefinition) &&
  119. $options->alwaysshowdefinition == 0) {
  120. $warnings[] = array(
  121. 'item' => 'module',
  122. 'itemid' => $cmid,
  123. 'message' => 'Capability moodle/grade:managegradingforms required to preview definition',
  124. 'warningcode' => '1'
  125. );
  126. $isviewable = false;
  127. }
  128. }
  129. if ($isviewable == false) {
  130. continue;
  131. }
  132. }
  133. $definition = array();
  134. $definition['id'] = $def->id;
  135. $definition['method'] = $method;
  136. $definition['name'] = $def->name;
  137. $definition['description'] = $def->description;
  138. $definition['descriptionformat'] = $def->descriptionformat;
  139. $definition['status'] = $def->status;
  140. $definition['copiedfromid'] = $def->copiedfromid;
  141. $definition['timecreated'] = $def->timecreated;
  142. $definition['usercreated'] = $def->usercreated;
  143. $definition['timemodified'] = $def->timemodified;
  144. $definition['usermodified'] = $def->usermodified;
  145. $definition['timecopied'] = $def->timecopied;
  146. // Format the description text field.
  147. $formattedtext = external_format_text($definition['description'],
  148. $definition['descriptionformat'],
  149. $context->id,
  150. $componentname,
  151. 'description',
  152. $def->id);
  153. $definition['description'] = $formattedtext[0];
  154. $definition['descriptionformat'] = $formattedtext[1];
  155. $details = $controller->get_external_definition_details();
  156. $items = array();
  157. foreach ($details as $key => $value) {
  158. $items[$key] = self::format_text($def->{$key}, $context->id, $componentname, $def->id);
  159. }
  160. $definition[$method] = $items;
  161. $area['definitions'][] = $definition;
  162. }
  163. $areas[] = $area;
  164. }
  165. $result = array(
  166. 'areas' => $areas,
  167. 'warnings' => $warnings
  168. );
  169. return $result;
  170. }
  171. /**
  172. * Recursively processes all elements in an array and runs external_format_text()on
  173. * all elements which have a text field and associated format field with a key name
  174. * that ends with the text 'format'. The modified array is returned.
  175. * @param array $items the array to be processed
  176. * @param int $contextid
  177. * @param string $componentname
  178. * @param int $itemid
  179. * @see external_format_text in lib/externallib.php
  180. * @return array the input array with all fields formatted
  181. */
  182. private static function format_text($items, $contextid, $componentname, $itemid) {
  183. $formatkeys = array();
  184. foreach ($items as $key => $value) {
  185. if (!is_array($value) && substr_compare($key, 'format', -6, 6) === 0) {
  186. $formatkeys[] = $key;
  187. }
  188. }
  189. foreach ($formatkeys as $formatkey) {
  190. $descriptionkey = substr($formatkey, 0, -6);
  191. $formattedtext = external_format_text($items[$descriptionkey],
  192. $items[$formatkey],
  193. $contextid,
  194. $componentname,
  195. 'description',
  196. $itemid);
  197. $items[$descriptionkey] = $formattedtext[0];
  198. $items[$formatkey] = $formattedtext[1];
  199. }
  200. foreach ($items as $key => $value) {
  201. if (is_array($value)) {
  202. $items[$key] = self::format_text($value, $contextid, $componentname, $itemid);
  203. }
  204. }
  205. return $items;
  206. }
  207. /**
  208. * Creates a grading area
  209. * @return external_single_structure
  210. * @since Moodle 2.5
  211. */
  212. private static function grading_area() {
  213. return new external_single_structure(
  214. array (
  215. 'cmid' => new external_value(PARAM_INT, 'course module id'),
  216. 'contextid' => new external_value(PARAM_INT, 'context id'),
  217. 'component' => new external_value(PARAM_TEXT, 'component name'),
  218. 'areaname' => new external_value(PARAM_TEXT, 'area name'),
  219. 'activemethod' => new external_value(PARAM_TEXT, 'active method', VALUE_OPTIONAL),
  220. 'definitions' => new external_multiple_structure(self::definition(), 'definitions')
  221. )
  222. );
  223. }
  224. /**
  225. * creates a grading form definition
  226. * @return external_single_structure
  227. * @since Moodle 2.5
  228. */
  229. private static function definition() {
  230. global $CFG;
  231. $definition = array();
  232. $definition['id'] = new external_value(PARAM_INT, 'definition id', VALUE_OPTIONAL);
  233. $definition['method'] = new external_value(PARAM_TEXT, 'method');
  234. $definition['name'] = new external_value(PARAM_TEXT, 'name');
  235. $definition['description'] = new external_value(PARAM_RAW, 'description', VALUE_OPTIONAL);
  236. $definition['descriptionformat'] = new external_format_value('description', VALUE_OPTIONAL);
  237. $definition['status'] = new external_value(PARAM_INT, 'status');
  238. $definition['copiedfromid'] = new external_value(PARAM_INT, 'copied from id', VALUE_OPTIONAL);
  239. $definition['timecreated'] = new external_value(PARAM_INT, 'creation time');
  240. $definition['usercreated'] = new external_value(PARAM_INT, 'user who created definition');
  241. $definition['timemodified'] = new external_value(PARAM_INT, 'last modified time');
  242. $definition['usermodified'] = new external_value(PARAM_INT, 'user who modified definition');
  243. $definition['timecopied'] = new external_value(PARAM_INT, 'time copied', VALUE_OPTIONAL);
  244. foreach (self::get_grading_methods() as $method) {
  245. require_once($CFG->dirroot.'/grade/grading/form/'.$method.'/lib.php');
  246. $details = call_user_func('gradingform_'.$method.'_controller::get_external_definition_details');
  247. if ($details != null) {
  248. $items = array();
  249. foreach ($details as $key => $value) {
  250. $details[$key]->required = VALUE_OPTIONAL;
  251. $items[$key] = $value;
  252. }
  253. $definition[$method] = new external_single_structure($items, 'items', VALUE_OPTIONAL);
  254. }
  255. }
  256. return new external_single_structure($definition);
  257. }
  258. /**
  259. * Describes the get_definitions return value
  260. * @return external_single_structure
  261. * @since Moodle 2.5
  262. */
  263. public static function get_definitions_returns() {
  264. return new external_single_structure(
  265. array(
  266. 'areas' => new external_multiple_structure(self::grading_area(), 'list of grading areas'),
  267. 'warnings' => new external_warnings()
  268. )
  269. );
  270. }
  271. /**
  272. * @return array of available grading methods
  273. * @since Moodle 2.5
  274. */
  275. private static function get_grading_methods() {
  276. $methods = array_keys(grading_manager::available_methods(false));
  277. return $methods;
  278. }
  279. /**
  280. * Describes the parameters for get_gradingform_instances
  281. *
  282. * @return external_function_parameters
  283. * @since Moodle 2.6
  284. */
  285. public static function get_gradingform_instances_parameters() {
  286. return new external_function_parameters(
  287. array(
  288. 'definitionid' => new external_value(PARAM_INT, 'definition id'),
  289. 'since' => new external_value(PARAM_INT, 'submitted since', VALUE_DEFAULT, 0)
  290. )
  291. );
  292. }
  293. /**
  294. * Returns the instances and fillings for the requested definition id
  295. *
  296. * @param int $definitionid
  297. * @param int $since only return instances with timemodified >= since
  298. * @return array of grading instances with fillings for the definition id
  299. * @since Moodle 2.6
  300. */
  301. public static function get_gradingform_instances($definitionid, $since = 0) {
  302. global $DB, $CFG;
  303. require_once("$CFG->dirroot/grade/grading/form/lib.php");
  304. $params = self::validate_parameters(self::get_gradingform_instances_parameters(),
  305. array('definitionid' => $definitionid,
  306. 'since' => $since));
  307. $instances = array();
  308. $warnings = array();
  309. $definition = $DB->get_record('grading_definitions',
  310. array('id' => $params['definitionid']),
  311. 'areaid,method', MUST_EXIST);
  312. $area = $DB->get_record('grading_areas',
  313. array('id' => $definition->areaid),
  314. 'contextid,component', MUST_EXIST);
  315. $context = context::instance_by_id($area->contextid);
  316. require_capability('moodle/grade:managegradingforms', $context);
  317. $gradingmanager = get_grading_manager($definition->areaid);
  318. $controller = $gradingmanager->get_controller($definition->method);
  319. $activeinstances = $controller->get_all_active_instances ($params['since']);
  320. $details = $controller->get_external_instance_filling_details();
  321. if ($details == null) {
  322. $warnings[] = array(
  323. 'item' => 'definition',
  324. 'itemid' => $params['definitionid'],
  325. 'message' => 'Fillings unavailable because get_external_instance_filling_details is not defined',
  326. 'warningcode' => '1'
  327. );
  328. }
  329. $getfilling = null;
  330. if (method_exists('gradingform_'.$definition->method.'_instance', 'get_'.$definition->method.'_filling')) {
  331. $getfilling = 'get_'.$definition->method.'_filling';
  332. } else {
  333. $warnings[] = array(
  334. 'item' => 'definition',
  335. 'itemid' => $params['definitionid'],
  336. 'message' => 'Fillings unavailable because get_'.$definition->method.'_filling is not defined',
  337. 'warningcode' => '1'
  338. );
  339. }
  340. foreach ($activeinstances as $activeinstance) {
  341. $instance = array();
  342. $instance['id'] = $activeinstance->get_id();
  343. $instance['raterid'] = $activeinstance->get_data('raterid');
  344. $instance['itemid'] = $activeinstance->get_data('itemid');
  345. $instance['rawgrade'] = $activeinstance->get_data('rawgrade');
  346. $instance['status'] = $activeinstance->get_data('status');
  347. $instance['feedback'] = $activeinstance->get_data('feedback');
  348. $instance['feedbackformat'] = $activeinstance->get_data('feedbackformat');
  349. // Format the feedback text field.
  350. $formattedtext = external_format_text($activeinstance->get_data('feedback'),
  351. $activeinstance->get_data('feedbackformat'),
  352. $context->id,
  353. $area->component,
  354. 'feedback',
  355. $params['definitionid']);
  356. $instance['feedback'] = $formattedtext[0];
  357. $instance['feedbackformat'] = $formattedtext[1];
  358. $instance['timemodified'] = $activeinstance->get_data('timemodified');
  359. if ($details != null && $getfilling != null) {
  360. $fillingdata = $activeinstance->$getfilling();
  361. $filling = array();
  362. foreach ($details as $key => $value) {
  363. $filling[$key] = self::format_text($fillingdata[$key],
  364. $context->id,
  365. $area->component,
  366. $params['definitionid']);
  367. }
  368. $instance[$definition->method] = $filling;
  369. }
  370. $instances[] = $instance;
  371. }
  372. $result = array(
  373. 'instances' => $instances,
  374. 'warnings' => $warnings
  375. );
  376. return $result;
  377. }
  378. /**
  379. * Creates a grading instance
  380. *
  381. * @return external_single_structure
  382. * @since Moodle 2.6
  383. */
  384. private static function grading_instance() {
  385. global $CFG;
  386. $instance = array();
  387. $instance['id'] = new external_value(PARAM_INT, 'instance id');
  388. $instance['raterid'] = new external_value(PARAM_INT, 'rater id');
  389. $instance['itemid'] = new external_value(PARAM_INT, 'item id');
  390. $instance['rawgrade'] = new external_value(PARAM_TEXT, 'raw grade', VALUE_OPTIONAL);
  391. $instance['status'] = new external_value(PARAM_INT, 'status');
  392. $instance['feedback'] = new external_value(PARAM_RAW, 'feedback', VALUE_OPTIONAL);
  393. $instance['feedbackformat'] = new external_format_value('feedback', VALUE_OPTIONAL);
  394. $instance['timemodified'] = new external_value(PARAM_INT, 'modified time');
  395. foreach (self::get_grading_methods() as $method) {
  396. require_once($CFG->dirroot.'/grade/grading/form/'.$method.'/lib.php');
  397. $details = call_user_func('gradingform_'.$method.'_controller::get_external_instance_filling_details');
  398. if ($details != null) {
  399. $items = array();
  400. foreach ($details as $key => $value) {
  401. $details[$key]->required = VALUE_OPTIONAL;
  402. $items[$key] = $value;
  403. }
  404. $instance[$method] = new external_single_structure($items, 'items', VALUE_OPTIONAL);
  405. }
  406. }
  407. return new external_single_structure($instance);
  408. }
  409. /**
  410. * Describes the get_gradingform_instances return value
  411. *
  412. * @return external_single_structure
  413. * @since Moodle 2.6
  414. */
  415. public static function get_gradingform_instances_returns() {
  416. return new external_single_structure(
  417. array(
  418. 'instances' => new external_multiple_structure(self::grading_instance(), 'list of grading instances'),
  419. 'warnings' => new external_warnings()
  420. )
  421. );
  422. }
  423. /**
  424. * Describes the parameters for save_definitions
  425. *
  426. * @return external_function_parameters
  427. * @since Moodle 2.8
  428. */
  429. public static function save_definitions_parameters() {
  430. return new external_function_parameters(
  431. array(
  432. 'areas' => new external_multiple_structure(self::grading_area(), 'areas with definitions to save')
  433. )
  434. );
  435. }
  436. /**
  437. * Saves the areas and definitions
  438. * @param array $areas array of areas containing definitions to be saved
  439. * @return null
  440. * @throws invalid_parameter_exception
  441. * @since Moodle 2.8
  442. */
  443. public static function save_definitions($areas) {
  444. $params = self::validate_parameters(self::save_definitions_parameters(),
  445. array('areas' => $areas));
  446. foreach ($params['areas'] as $area) {
  447. $context = context::instance_by_id($area['contextid']);
  448. require_capability('moodle/grade:managegradingforms', $context);
  449. $gradingmanager = get_grading_manager($context, $area['component'], $area['areaname']);
  450. $gradingmanager->set_active_method($area['activemethod']);
  451. $availablemethods = $gradingmanager->get_available_methods();
  452. foreach ($area['definitions'] as $definition) {
  453. if (array_key_exists($definition['method'], $availablemethods)) {
  454. $controller = $gradingmanager->get_controller($definition['method']);
  455. $controller->update_definition(self::create_definition_object($definition));
  456. } else {
  457. throw new invalid_parameter_exception('Unknown Grading method: '. $definition['method']);
  458. }
  459. }
  460. }
  461. }
  462. /**
  463. * Describes the return value for save_definitions
  464. *
  465. * @return external_single_structure
  466. * @since Moodle 2.8
  467. */
  468. public static function save_definitions_returns() {
  469. return null;
  470. }
  471. /**
  472. * Creates a definition stdClass object using the values from the definition
  473. * array that is passed in as a parameter
  474. *
  475. * @param array $definition
  476. * @return stdClass definition object
  477. * @since Moodle 2.8
  478. */
  479. private static function create_definition_object($definition) {
  480. global $CFG;
  481. $method = $definition['method'];
  482. $definitionobject = new stdClass();
  483. foreach ($definition as $key => $value) {
  484. if (!is_array($value)) {
  485. $definitionobject->$key = $value;
  486. }
  487. }
  488. $text = '';
  489. $format = FORMAT_MOODLE;
  490. if (isset($definition['description'])) {
  491. $text = $definition['description'];
  492. if (isset($definition['descriptionformat'])) {
  493. $format = $definition['descriptionformat'];
  494. }
  495. }
  496. $definitionobject->description_editor = array('text' => $text, 'format' => $format);
  497. require_once("$CFG->libdir/filelib.php");
  498. require_once($CFG->dirroot.'/grade/grading/form/'.$method.'/lib.php');
  499. $details = call_user_func('gradingform_'.$method.'_controller::get_external_definition_details');
  500. $methodarray = array();
  501. foreach (array_keys($details) as $definitionkey) {
  502. $items = array();
  503. $idnumber = 1;
  504. foreach ($definition[$method][$definitionkey] as $item) {
  505. $processeditem = self::set_new_ids($item, $idnumber);
  506. $items[$processeditem['id']] = $processeditem;
  507. $idnumber++;
  508. }
  509. $definitionobjectkey = substr($definitionkey, strlen($method.'_'));
  510. $methodarray[$definitionobjectkey] = $items;
  511. $definitionobject->$method = $methodarray;
  512. }
  513. return $definitionobject;
  514. }
  515. /**
  516. * Recursively iterates through arrays. Any array without an id key-value combination
  517. * is assumed to be an array of values to be inserted and an id key-value is added with
  518. * the value matching the regex '/^NEWID\d+$/' that is expected by each grading form implementation.
  519. *
  520. * @param array $arraytoset the array to be processed
  521. * @param int $startnumber the starting number for the new id numbers
  522. * @return array with missing id keys added for all arrays
  523. * @since Moodle 2.8
  524. */
  525. private static function set_new_ids($arraytoset, $startnumber) {
  526. $result = array();
  527. $foundid = false;
  528. $number = $startnumber;
  529. foreach ($arraytoset as $key1 => $value1) {
  530. if (is_array($value1)) {
  531. foreach ($value1 as $key2 => $value2) {
  532. $processedvalue = self::set_new_ids($value2, $number);
  533. $result[$key1][$processedvalue['id']] = $processedvalue;
  534. $number++;
  535. }
  536. } else {
  537. $result[$key1] = $value1;
  538. }
  539. if ($key1 === 'id') {
  540. $foundid = true;
  541. }
  542. }
  543. if (!$foundid) {
  544. $result['id'] = 'NEWID'.$number;
  545. }
  546. return $result;
  547. }
  548. }