MDL-44616 behat: Adding steps to test MDLQA-1709 and MDLQA-62
[moodle.git] / mod / lti / servicelib.php
blob3d7cc0eb18082c33d78c26d40af540fb0a2ff357
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.
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/>.
17 /**
18 * Utility code for LTI service handling.
20 * @package mod_lti
21 * @copyright Copyright (c) 2011 Moodlerooms Inc. (http://www.moodlerooms.com)
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 * @author Chris Scribner
26 defined('MOODLE_INTERNAL') || die;
28 require_once($CFG->dirroot.'/mod/lti/OAuthBody.php');
30 // TODO: Switch to core oauthlib once implemented - MDL-30149
31 use moodle\mod\lti as lti;
33 define('LTI_ITEM_TYPE', 'mod');
34 define('LTI_ITEM_MODULE', 'lti');
35 define('LTI_SOURCE', 'mod/lti');
37 function lti_get_response_xml($codemajor, $description, $messageref, $messagetype) {
38 $xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><imsx_POXEnvelopeResponse />');
39 $xml->addAttribute('xmlns', 'http://www.imsglobal.org/services/ltiv1p1/xsd/imsoms_v1p0');
41 $headerinfo = $xml->addChild('imsx_POXHeader')->addChild('imsx_POXResponseHeaderInfo');
43 $headerinfo->addChild('imsx_version', 'V1.0');
44 $headerinfo->addChild('imsx_messageIdentifier', (string)mt_rand());
46 $statusinfo = $headerinfo->addChild('imsx_statusInfo');
47 $statusinfo->addchild('imsx_codeMajor', $codemajor);
48 $statusinfo->addChild('imsx_severity', 'status');
49 $statusinfo->addChild('imsx_description', $description);
50 $statusinfo->addChild('imsx_messageRefIdentifier', $messageref);
51 $incomingtype = str_replace('Response','Request', $messagetype);
52 $statusinfo->addChild('imsx_operationRefIdentifier', $incomingtype);
54 $xml->addChild('imsx_POXBody')->addChild($messagetype);
56 return $xml;
59 function lti_parse_message_id($xml) {
60 $node = $xml->imsx_POXHeader->imsx_POXRequestHeaderInfo->imsx_messageIdentifier;
61 $messageid = (string)$node;
63 return $messageid;
66 function lti_parse_grade_replace_message($xml) {
67 $node = $xml->imsx_POXBody->replaceResultRequest->resultRecord->sourcedGUID->sourcedId;
68 $resultjson = json_decode((string)$node);
70 $node = $xml->imsx_POXBody->replaceResultRequest->resultRecord->result->resultScore->textString;
72 $score = (string) $node;
73 if ( ! is_numeric($score) ) {
74 throw new Exception('Score must be numeric');
76 $grade = floatval($score);
77 if ( $grade < 0.0 || $grade > 1.0 ) {
78 throw new Exception('Score not between 0.0 and 1.0');
81 $parsed = new stdClass();
82 $parsed->gradeval = $grade * 100;
84 $parsed->instanceid = $resultjson->data->instanceid;
85 $parsed->userid = $resultjson->data->userid;
86 $parsed->launchid = $resultjson->data->launchid;
87 $parsed->sourcedidhash = $resultjson->hash;
89 $parsed->messageid = lti_parse_message_id($xml);
91 return $parsed;
94 function lti_parse_grade_read_message($xml) {
95 $node = $xml->imsx_POXBody->readResultRequest->resultRecord->sourcedGUID->sourcedId;
96 $resultjson = json_decode((string)$node);
98 $parsed = new stdClass();
99 $parsed->instanceid = $resultjson->data->instanceid;
100 $parsed->userid = $resultjson->data->userid;
101 $parsed->launchid = $resultjson->data->launchid;
102 $parsed->sourcedidhash = $resultjson->hash;
104 $parsed->messageid = lti_parse_message_id($xml);
106 return $parsed;
109 function lti_parse_grade_delete_message($xml) {
110 $node = $xml->imsx_POXBody->deleteResultRequest->resultRecord->sourcedGUID->sourcedId;
111 $resultjson = json_decode((string)$node);
113 $parsed = new stdClass();
114 $parsed->instanceid = $resultjson->data->instanceid;
115 $parsed->userid = $resultjson->data->userid;
116 $parsed->launchid = $resultjson->data->launchid;
117 $parsed->sourcedidhash = $resultjson->hash;
119 $parsed->messageid = lti_parse_message_id($xml);
121 return $parsed;
124 function lti_update_grade($ltiinstance, $userid, $launchid, $gradeval) {
125 global $CFG, $DB;
126 require_once($CFG->libdir . '/gradelib.php');
128 $params = array();
129 $params['itemname'] = $ltiinstance->name;
131 $grade = new stdClass();
132 $grade->userid = $userid;
133 $grade->rawgrade = $gradeval;
135 $status = grade_update(LTI_SOURCE, $ltiinstance->course, LTI_ITEM_TYPE, LTI_ITEM_MODULE, $ltiinstance->id, 0, $grade, $params);
137 $record = $DB->get_record('lti_submission', array('ltiid' => $ltiinstance->id, 'userid' => $userid, 'launchid' => $launchid), 'id');
138 if ($record) {
139 $id = $record->id;
140 } else {
141 $id = null;
144 if (!empty($id)) {
145 $DB->update_record('lti_submission', array(
146 'id' => $id,
147 'dateupdated' => time(),
148 'gradepercent' => $gradeval,
149 'state' => 2
151 } else {
152 $DB->insert_record('lti_submission', array(
153 'ltiid' => $ltiinstance->id,
154 'userid' => $userid,
155 'datesubmitted' => time(),
156 'dateupdated' => time(),
157 'gradepercent' => $gradeval,
158 'originalgrade' => $gradeval,
159 'launchid' => $launchid,
160 'state' => 1
164 return $status == GRADE_UPDATE_OK;
167 function lti_read_grade($ltiinstance, $userid) {
168 global $CFG;
169 require_once($CFG->libdir . '/gradelib.php');
171 $grades = grade_get_grades($ltiinstance->course, LTI_ITEM_TYPE, LTI_ITEM_MODULE, $ltiinstance->id, $userid);
173 if (isset($grades) && isset($grades->items[0]) && is_array($grades->items[0]->grades)) {
174 foreach ($grades->items[0]->grades as $agrade) {
175 $grade = $agrade->grade;
176 $grade = $grade / 100.0;
177 break;
181 if (isset($grade)) {
182 return $grade;
186 function lti_delete_grade($ltiinstance, $userid) {
187 global $CFG;
188 require_once($CFG->libdir . '/gradelib.php');
190 $grade = new stdClass();
191 $grade->userid = $userid;
192 $grade->rawgrade = null;
194 $status = grade_update(LTI_SOURCE, $ltiinstance->course, LTI_ITEM_TYPE, LTI_ITEM_MODULE, $ltiinstance->id, 0, $grade, array('deleted'=>1));
196 return $status == GRADE_UPDATE_OK;
199 function lti_verify_message($key, $sharedsecrets, $body, $headers = null) {
200 foreach ($sharedsecrets as $secret) {
201 $signaturefailed = false;
203 try {
204 // TODO: Switch to core oauthlib once implemented - MDL-30149
205 lti\handleOAuthBodyPOST($key, $secret, $body, $headers);
206 } catch (Exception $e) {
207 $signaturefailed = true;
210 if (!$signaturefailed) {
211 return $secret;//Return the secret used to sign the message)
215 return false;
218 function lti_verify_sourcedid($ltiinstance, $parsed) {
219 $sourceid = lti_build_sourcedid($parsed->instanceid, $parsed->userid, $parsed->launchid, $ltiinstance->servicesalt);
221 if ($sourceid->hash != $parsed->sourcedidhash) {
222 throw new Exception('SourcedId hash not valid');
227 * Extend the LTI services through the ltisource plugins
229 * @param stdClass $data LTI request data
230 * @return bool
231 * @throws coding_exception
233 function lti_extend_lti_services($data) {
234 $plugins = get_plugin_list_with_function('ltisource', $data->messagetype);
235 if (!empty($plugins)) {
236 try {
237 // There can only be one
238 if (count($plugins) > 1) {
239 throw new coding_exception('More than one ltisource plugin handler found');
241 $callback = current($plugins);
242 call_user_func($callback, $data);
243 } catch (moodle_exception $e) {
244 $error = $e->getMessage();
245 if (debugging('', DEBUG_DEVELOPER)) {
246 $error .= ' '.format_backtrace(get_exception_info($e)->backtrace);
248 $responsexml = lti_get_response_xml(
249 'failure',
250 $error,
251 $data->messageid,
252 $data->messagetype
255 header('HTTP/1.0 400 bad request');
256 echo $responsexml->asXML();
258 return true;
260 return false;