PageRenderTime 44ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/mod/lti/servicelib.php

https://github.com/pauln/moodle
PHP | 300 lines | 195 code | 61 blank | 44 comment | 29 complexity | 7b32b87d4c04fb834bd10c64161d6868 MD5 | raw file
  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. * Utility code for LTI service handling.
  18. *
  19. * @package mod_lti
  20. * @copyright Copyright (c) 2011 Moodlerooms Inc. (http://www.moodlerooms.com)
  21. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  22. * @author Chris Scribner
  23. */
  24. defined('MOODLE_INTERNAL') || die;
  25. require_once($CFG->dirroot.'/mod/lti/OAuthBody.php');
  26. // TODO: Switch to core oauthlib once implemented - MDL-30149.
  27. use moodle\mod\lti as lti;
  28. define('LTI_ITEM_TYPE', 'mod');
  29. define('LTI_ITEM_MODULE', 'lti');
  30. define('LTI_SOURCE', 'mod/lti');
  31. function lti_get_response_xml($codemajor, $description, $messageref, $messagetype) {
  32. $xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><imsx_POXEnvelopeResponse />');
  33. $xml->addAttribute('xmlns', 'http://www.imsglobal.org/services/ltiv1p1/xsd/imsoms_v1p0');
  34. $headerinfo = $xml->addChild('imsx_POXHeader')->addChild('imsx_POXResponseHeaderInfo');
  35. $headerinfo->addChild('imsx_version', 'V1.0');
  36. $headerinfo->addChild('imsx_messageIdentifier', (string)mt_rand());
  37. $statusinfo = $headerinfo->addChild('imsx_statusInfo');
  38. $statusinfo->addchild('imsx_codeMajor', $codemajor);
  39. $statusinfo->addChild('imsx_severity', 'status');
  40. $statusinfo->addChild('imsx_description', $description);
  41. $statusinfo->addChild('imsx_messageRefIdentifier', $messageref);
  42. $incomingtype = str_replace('Response', 'Request', $messagetype);
  43. $statusinfo->addChild('imsx_operationRefIdentifier', $incomingtype);
  44. $xml->addChild('imsx_POXBody')->addChild($messagetype);
  45. return $xml;
  46. }
  47. function lti_parse_message_id($xml) {
  48. if (empty($xml->imsx_POXHeader)) {
  49. return '';
  50. }
  51. $node = $xml->imsx_POXHeader->imsx_POXRequestHeaderInfo->imsx_messageIdentifier;
  52. $messageid = (string)$node;
  53. return $messageid;
  54. }
  55. function lti_parse_grade_replace_message($xml) {
  56. $node = $xml->imsx_POXBody->replaceResultRequest->resultRecord->sourcedGUID->sourcedId;
  57. $resultjson = json_decode((string)$node);
  58. $node = $xml->imsx_POXBody->replaceResultRequest->resultRecord->result->resultScore->textString;
  59. $score = (string) $node;
  60. if ( ! is_numeric($score) ) {
  61. throw new Exception('Score must be numeric');
  62. }
  63. $grade = floatval($score);
  64. if ( $grade < 0.0 || $grade > 1.0 ) {
  65. throw new Exception('Score not between 0.0 and 1.0');
  66. }
  67. $parsed = new stdClass();
  68. $parsed->gradeval = $grade;
  69. $parsed->instanceid = $resultjson->data->instanceid;
  70. $parsed->userid = $resultjson->data->userid;
  71. $parsed->launchid = $resultjson->data->launchid;
  72. $parsed->typeid = $resultjson->data->typeid;
  73. $parsed->sourcedidhash = $resultjson->hash;
  74. $parsed->messageid = lti_parse_message_id($xml);
  75. return $parsed;
  76. }
  77. function lti_parse_grade_read_message($xml) {
  78. $node = $xml->imsx_POXBody->readResultRequest->resultRecord->sourcedGUID->sourcedId;
  79. $resultjson = json_decode((string)$node);
  80. $parsed = new stdClass();
  81. $parsed->instanceid = $resultjson->data->instanceid;
  82. $parsed->userid = $resultjson->data->userid;
  83. $parsed->launchid = $resultjson->data->launchid;
  84. $parsed->typeid = $resultjson->data->typeid;
  85. $parsed->sourcedidhash = $resultjson->hash;
  86. $parsed->messageid = lti_parse_message_id($xml);
  87. return $parsed;
  88. }
  89. function lti_parse_grade_delete_message($xml) {
  90. $node = $xml->imsx_POXBody->deleteResultRequest->resultRecord->sourcedGUID->sourcedId;
  91. $resultjson = json_decode((string)$node);
  92. $parsed = new stdClass();
  93. $parsed->instanceid = $resultjson->data->instanceid;
  94. $parsed->userid = $resultjson->data->userid;
  95. $parsed->launchid = $resultjson->data->launchid;
  96. $parsed->typeid = $resultjson->data->typeid;
  97. $parsed->sourcedidhash = $resultjson->hash;
  98. $parsed->messageid = lti_parse_message_id($xml);
  99. return $parsed;
  100. }
  101. function lti_accepts_grades($ltiinstance) {
  102. global $DB;
  103. $acceptsgrades = true;
  104. $ltitype = $DB->get_record('lti_types', array('id' => $ltiinstance->typeid));
  105. if (empty($ltitype->toolproxyid)) {
  106. $typeconfig = lti_get_config($ltiinstance);
  107. $typeacceptgrades = isset($typeconfig['acceptgrades']) ? $typeconfig['acceptgrades'] : LTI_SETTING_DELEGATE;
  108. if (!($typeacceptgrades == LTI_SETTING_ALWAYS ||
  109. ($typeacceptgrades == LTI_SETTING_DELEGATE && $ltiinstance->instructorchoiceacceptgrades == LTI_SETTING_ALWAYS))) {
  110. $acceptsgrades = false;
  111. }
  112. } else {
  113. $enabledcapabilities = explode("\n", $ltitype->enabledcapability);
  114. $acceptsgrades = in_array('Result.autocreate', $enabledcapabilities);
  115. }
  116. return $acceptsgrades;
  117. }
  118. /**
  119. * Set the passed user ID to the session user.
  120. *
  121. * @param int $userid
  122. */
  123. function lti_set_session_user($userid) {
  124. global $DB;
  125. if ($user = $DB->get_record('user', array('id' => $userid))) {
  126. \core\session\manager::set_user($user);
  127. }
  128. }
  129. function lti_update_grade($ltiinstance, $userid, $launchid, $gradeval) {
  130. global $CFG, $DB;
  131. require_once($CFG->libdir . '/gradelib.php');
  132. $params = array();
  133. $params['itemname'] = $ltiinstance->name;
  134. $gradeval = $gradeval * floatval($ltiinstance->grade);
  135. $grade = new stdClass();
  136. $grade->userid = $userid;
  137. $grade->rawgrade = $gradeval;
  138. $status = grade_update(LTI_SOURCE, $ltiinstance->course, LTI_ITEM_TYPE, LTI_ITEM_MODULE, $ltiinstance->id, 0, $grade, $params);
  139. $record = $DB->get_record('lti_submission', array('ltiid' => $ltiinstance->id, 'userid' => $userid,
  140. 'launchid' => $launchid), 'id');
  141. if ($record) {
  142. $id = $record->id;
  143. } else {
  144. $id = null;
  145. }
  146. if (!empty($id)) {
  147. $DB->update_record('lti_submission', array(
  148. 'id' => $id,
  149. 'dateupdated' => time(),
  150. 'gradepercent' => $gradeval,
  151. 'state' => 2
  152. ));
  153. } else {
  154. $DB->insert_record('lti_submission', array(
  155. 'ltiid' => $ltiinstance->id,
  156. 'userid' => $userid,
  157. 'datesubmitted' => time(),
  158. 'dateupdated' => time(),
  159. 'gradepercent' => $gradeval,
  160. 'originalgrade' => $gradeval,
  161. 'launchid' => $launchid,
  162. 'state' => 1
  163. ));
  164. }
  165. return $status == GRADE_UPDATE_OK;
  166. }
  167. function lti_read_grade($ltiinstance, $userid) {
  168. global $CFG;
  169. require_once($CFG->libdir . '/gradelib.php');
  170. $grades = grade_get_grades($ltiinstance->course, LTI_ITEM_TYPE, LTI_ITEM_MODULE, $ltiinstance->id, $userid);
  171. $ltigrade = floatval($ltiinstance->grade);
  172. if (!empty($ltigrade) && isset($grades) && isset($grades->items[0]) && is_array($grades->items[0]->grades)) {
  173. foreach ($grades->items[0]->grades as $agrade) {
  174. $grade = $agrade->grade;
  175. if (isset($grade)) {
  176. return $grade / $ltigrade;
  177. }
  178. }
  179. }
  180. }
  181. function lti_delete_grade($ltiinstance, $userid) {
  182. global $CFG;
  183. require_once($CFG->libdir . '/gradelib.php');
  184. $grade = new stdClass();
  185. $grade->userid = $userid;
  186. $grade->rawgrade = null;
  187. $status = grade_update(LTI_SOURCE, $ltiinstance->course, LTI_ITEM_TYPE, LTI_ITEM_MODULE, $ltiinstance->id, 0, $grade);
  188. return $status == GRADE_UPDATE_OK;
  189. }
  190. function lti_verify_message($key, $sharedsecrets, $body, $headers = null) {
  191. foreach ($sharedsecrets as $secret) {
  192. $signaturefailed = false;
  193. try {
  194. // TODO: Switch to core oauthlib once implemented - MDL-30149.
  195. lti\handle_oauth_body_post($key, $secret, $body, $headers);
  196. } catch (Exception $e) {
  197. $signaturefailed = true;
  198. }
  199. if (!$signaturefailed) {
  200. return $secret; // Return the secret used to sign the message).
  201. }
  202. }
  203. return false;
  204. }
  205. /**
  206. * Validate source ID from external request
  207. *
  208. * @param object $ltiinstance
  209. * @param object $parsed
  210. * @throws Exception
  211. */
  212. function lti_verify_sourcedid($ltiinstance, $parsed) {
  213. $sourceid = lti_build_sourcedid($parsed->instanceid, $parsed->userid,
  214. $ltiinstance->servicesalt, $parsed->typeid, $parsed->launchid);
  215. if ($sourceid->hash != $parsed->sourcedidhash) {
  216. throw new Exception('SourcedId hash not valid');
  217. }
  218. }
  219. /**
  220. * Extend the LTI services through the ltisource plugins
  221. *
  222. * @param stdClass $data LTI request data
  223. * @return bool
  224. * @throws coding_exception
  225. */
  226. function lti_extend_lti_services($data) {
  227. $plugins = get_plugin_list_with_function('ltisource', $data->messagetype);
  228. if (!empty($plugins)) {
  229. // There can only be one.
  230. if (count($plugins) > 1) {
  231. throw new coding_exception('More than one ltisource plugin handler found');
  232. }
  233. $data->xml = new SimpleXMLElement($data->body);
  234. $callback = current($plugins);
  235. call_user_func($callback, $data);
  236. return true;
  237. }
  238. return false;
  239. }