forked from moodle/moodle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtool_provider.php
452 lines (388 loc) · 16.2 KB
/
tool_provider.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Extends the IMS Tool provider library for the LTI enrolment.
*
* @package enrol_lti
* @copyright 2016 John Okely <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace enrol_lti;
defined('MOODLE_INTERNAL') || die;
use context;
use core\notification;
use core_user;
use enrol_lti\output\registration;
use html_writer;
use IMSGlobal\LTI\Profile\Item;
use IMSGlobal\LTI\Profile\Message;
use IMSGlobal\LTI\Profile\ResourceHandler;
use IMSGlobal\LTI\Profile\ServiceDefinition;
use IMSGlobal\LTI\ToolProvider\ToolProvider;
use moodle_exception;
use moodle_url;
use stdClass;
require_once($CFG->dirroot . '/user/lib.php');
/**
* Extends the IMS Tool provider library for the LTI enrolment.
*
* @package enrol_lti
* @copyright 2016 John Okely <[email protected]>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class tool_provider extends ToolProvider {
/**
* @var stdClass $tool The object representing the enrol instance providing this LTI tool
*/
protected $tool;
/**
* Remove $this->baseUrl (wwwroot) from a given url string and return it.
*
* @param string $url The url from which to remove the base url
* @return string|null A string of the relative path to the url, or null if it couldn't be determined.
*/
protected function strip_base_url($url) {
if (substr($url, 0, strlen($this->baseUrl)) == $this->baseUrl) {
return substr($url, strlen($this->baseUrl));
}
return null;
}
/**
* Create a new instance of tool_provider to handle all the LTI tool provider interactions.
*
* @param int $toolid The id of the tool to be provided.
*/
public function __construct($toolid) {
global $CFG, $SITE;
$token = helper::generate_proxy_token($toolid);
$tool = helper::get_lti_tool($toolid);
$this->tool = $tool;
$dataconnector = new data_connector();
parent::__construct($dataconnector);
// Override debugMode and set to the configured value.
$this->debugMode = $CFG->debugdeveloper;
$this->baseUrl = $CFG->wwwroot;
$toolpath = helper::get_launch_url($toolid);
$toolpath = $this->strip_base_url($toolpath);
$vendorid = $SITE->shortname;
$vendorname = $SITE->fullname;
$vendordescription = trim(html_to_text($SITE->summary));
$this->vendor = new Item($vendorid, $vendorname, $vendordescription, $CFG->wwwroot);
$name = helper::get_name($tool);
$description = helper::get_description($tool);
$icon = helper::get_icon($tool)->out();
$icon = $this->strip_base_url($icon);
$this->product = new Item(
$token,
$name,
$description,
helper::get_proxy_url($tool),
'1.0'
);
$requiredmessages = [
new Message(
'basic-lti-launch-request',
$toolpath,
[
'Context.id',
'CourseSection.title',
'CourseSection.label',
'CourseSection.sourcedId',
'CourseSection.longDescription',
'CourseSection.timeFrame.begin',
'ResourceLink.id',
'ResourceLink.title',
'ResourceLink.description',
'User.id',
'User.username',
'Person.name.full',
'Person.name.given',
'Person.name.family',
'Person.email.primary',
'Person.sourcedId',
'Person.name.middle',
'Person.address.street1',
'Person.address.locality',
'Person.address.country',
'Person.address.timezone',
'Person.phone.primary',
'Person.phone.mobile',
'Person.webaddress',
'Membership.role',
'Result.sourcedId',
'Result.autocreate'
]
)
];
$optionalmessages = [
];
$this->resourceHandlers[] = new ResourceHandler(
new Item(
$token,
helper::get_name($tool),
$description
),
$icon,
$requiredmessages,
$optionalmessages
);
$this->requiredServices[] = new ServiceDefinition(['application/vnd.ims.lti.v2.toolproxy+json'], ['POST']);
$this->requiredServices[] = new ServiceDefinition(['application/vnd.ims.lis.v2.membershipcontainer+json'], ['GET']);
}
/**
* Override onError for custom error handling.
* @return void
*/
protected function onError() {
global $OUTPUT;
$message = $this->message;
if ($this->debugMode && !empty($this->reason)) {
$message = $this->reason;
}
// Display the error message from the provider's side if the consumer has not specified a URL to pass the error to.
if (empty($this->returnUrl)) {
$this->errorOutput = $OUTPUT->notification(get_string('failedrequest', 'enrol_lti', ['reason' => $message]), 'error');
}
}
/**
* Override onLaunch with tool logic.
* @return void
*/
protected function onLaunch() {
global $DB, $SESSION, $CFG;
// Check for valid consumer.
if (empty($this->consumer) || $this->dataConnector->loadToolConsumer($this->consumer) === false) {
$this->ok = false;
$this->message = get_string('invalidtoolconsumer', 'enrol_lti');
return;
}
$url = helper::get_launch_url($this->tool->id);
// If a tool proxy has been stored for the current consumer trying to access a tool,
// check that the tool is being launched from the correct url.
$correctlaunchurl = false;
if (!empty($this->consumer->toolProxy)) {
$proxy = json_decode($this->consumer->toolProxy);
$handlers = $proxy->tool_profile->resource_handler;
foreach ($handlers as $handler) {
foreach ($handler->message as $message) {
$handlerurl = new moodle_url($message->path);
$fullpath = $handlerurl->out(false);
if ($message->message_type == "basic-lti-launch-request" && $fullpath == $url) {
$correctlaunchurl = true;
break 2;
}
}
}
} else if ($this->tool->secret == $this->consumer->secret) {
// Test if the LTI1 secret for this tool is being used. Then we know the correct tool is being launched.
$correctlaunchurl = true;
}
if (!$correctlaunchurl) {
$this->ok = false;
$this->message = get_string('invalidrequest', 'enrol_lti');
return;
}
// Before we do anything check that the context is valid.
$tool = $this->tool;
$context = context::instance_by_id($tool->contextid);
// Set the user data.
$user = new stdClass();
$user->username = helper::create_username($this->consumer->getKey(), $this->user->ltiUserId);
if (!empty($this->user->firstname)) {
$user->firstname = $this->user->firstname;
} else {
$user->firstname = $this->user->getRecordId();
}
if (!empty($this->user->lastname)) {
$user->lastname = $this->user->lastname;
} else {
$user->lastname = $this->tool->contextid;
}
$user->email = core_user::clean_field($this->user->email, 'email');
// Get the user data from the LTI consumer.
$user = helper::assign_user_tool_data($tool, $user);
// Check if the user exists.
if (!$dbuser = $DB->get_record('user', ['username' => $user->username, 'deleted' => 0])) {
// If the email was stripped/not set then fill it with a default one. This
// stops the user from being redirected to edit their profile page.
if (empty($user->email)) {
$user->email = $user->username . "@example.com";
}
$user->auth = 'lti';
$user->id = \user_create_user($user);
// Get the updated user record.
$user = $DB->get_record('user', ['id' => $user->id]);
} else {
if (helper::user_match($user, $dbuser)) {
$user = $dbuser;
} else {
// If email is empty remove it, so we don't update the user with an empty email.
if (empty($user->email)) {
unset($user->email);
}
$user->id = $dbuser->id;
\user_update_user($user);
// Get the updated user record.
$user = $DB->get_record('user', ['id' => $user->id]);
}
}
// Update user image.
if (isset($this->user) && isset($this->user->image) && !empty($this->user->image)) {
$image = $this->user->image;
} else {
// Use custom_user_image parameter as a fallback.
$image = $this->resourceLink->getSetting('custom_user_image');
}
// Check if there is an image to process.
if ($image) {
helper::update_user_profile_image($user->id, $image);
}
// Check if we need to force the page layout to embedded.
$isforceembed = $this->resourceLink->getSetting('custom_force_embed') == 1;
// Check if we are an instructor.
$isinstructor = $this->user->isStaff() || $this->user->isAdmin();
if ($context->contextlevel == CONTEXT_COURSE) {
$courseid = $context->instanceid;
$urltogo = new moodle_url('/course/view.php', ['id' => $courseid]);
} else if ($context->contextlevel == CONTEXT_MODULE) {
$cm = get_coursemodule_from_id(false, $context->instanceid, 0, false, MUST_EXIST);
$urltogo = new moodle_url('/mod/' . $cm->modname . '/view.php', ['id' => $cm->id]);
// If we are a student in the course module context we do not want to display blocks.
if (!$isforceembed && !$isinstructor) {
$isforceembed = true;
}
} else {
print_error('invalidcontext');
exit();
}
// Force page layout to embedded if necessary.
if ($isforceembed) {
$SESSION->forcepagelayout = 'embedded';
} else {
// May still be set from previous session, so unset it.
unset($SESSION->forcepagelayout);
}
// Enrol the user in the course with no role.
$result = helper::enrol_user($tool, $user->id);
// Display an error, if there is one.
if ($result !== helper::ENROLMENT_SUCCESSFUL) {
print_error($result, 'enrol_lti');
exit();
}
// Give the user the role in the given context.
$roleid = $isinstructor ? $tool->roleinstructor : $tool->rolelearner;
role_assign($roleid, $user->id, $tool->contextid);
// Login user.
$sourceid = $this->user->ltiResultSourcedId;
$serviceurl = $this->resourceLink->getSetting('lis_outcome_service_url');
// Check if we have recorded this user before.
if ($userlog = $DB->get_record('enrol_lti_users', ['toolid' => $tool->id, 'userid' => $user->id])) {
if ($userlog->sourceid != $sourceid) {
$userlog->sourceid = $sourceid;
}
if ($userlog->serviceurl != $serviceurl) {
$userlog->serviceurl = $serviceurl;
}
$userlog->lastaccess = time();
$DB->update_record('enrol_lti_users', $userlog);
} else {
// Add the user details so we can use it later when syncing grades and members.
$userlog = new stdClass();
$userlog->userid = $user->id;
$userlog->toolid = $tool->id;
$userlog->serviceurl = $serviceurl;
$userlog->sourceid = $sourceid;
$userlog->consumerkey = $this->consumer->getKey();
$userlog->consumersecret = $tool->secret;
$userlog->lastgrade = 0;
$userlog->lastaccess = time();
$userlog->timecreated = time();
$userlog->membershipsurl = $this->resourceLink->getSetting('ext_ims_lis_memberships_url');
$userlog->membershipsid = $this->resourceLink->getSetting('ext_ims_lis_memberships_id');
$DB->insert_record('enrol_lti_users', $userlog);
}
// Finalise the user log in.
complete_user_login($user);
// Everything's good. Set appropriate OK flag and message values.
$this->ok = true;
$this->message = get_string('success');
if (empty($CFG->allowframembedding)) {
// Provide an alternative link.
$stropentool = get_string('opentool', 'enrol_lti');
echo html_writer::tag('p', get_string('frameembeddingnotenabled', 'enrol_lti'));
echo html_writer::link($urltogo, $stropentool, ['target' => '_blank']);
} else {
// All done, redirect the user to where they want to go.
redirect($urltogo);
}
}
/**
* Override onRegister with registration code.
*/
protected function onRegister() {
global $PAGE;
if (empty($this->consumer)) {
$this->ok = false;
$this->message = get_string('invalidtoolconsumer', 'enrol_lti');
return;
}
if (empty($this->returnUrl)) {
$this->ok = false;
$this->message = get_string('returnurlnotset', 'enrol_lti');
return;
}
if ($this->doToolProxyService()) {
// Map tool consumer and published tool, if necessary.
$this->map_tool_to_consumer();
// Indicate successful processing in message.
$this->message = get_string('successfulregistration', 'enrol_lti');
// Prepare response.
$returnurl = new moodle_url($this->returnUrl);
$returnurl->param('lti_msg', get_string("successfulregistration", "enrol_lti"));
$returnurl->param('status', 'success');
$guid = $this->consumer->getKey();
$returnurl->param('tool_proxy_guid', $guid);
$returnurlout = $returnurl->out(false);
$registration = new registration($returnurlout);
$output = $PAGE->get_renderer('enrol_lti');
echo $output->render($registration);
} else {
// Tell the consumer that the registration failed.
$this->ok = false;
$this->message = get_string('couldnotestablishproxy', 'enrol_lti');
}
}
/**
* Performs mapping of the tool consumer to a published tool.
*
* @throws moodle_exception
*/
public function map_tool_to_consumer() {
global $DB;
if (empty($this->consumer)) {
throw new moodle_exception('invalidtoolconsumer', 'enrol_lti');
}
// Map the consumer to the tool.
$mappingparams = [
'toolid' => $this->tool->id,
'consumerid' => $this->consumer->getRecordId()
];
$mappingexists = $DB->record_exists('enrol_lti_tool_consumer_map', $mappingparams);
if (!$mappingexists) {
$DB->insert_record('enrol_lti_tool_consumer_map', (object) $mappingparams);
}
}
}