MDL-49143 LTI: Fix missing resource id
[moodle.git] / mod / lti / locallib.php
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 // This file is part of BasicLTI4Moodle
18 //
19 // BasicLTI4Moodle is an IMS BasicLTI (Basic Learning Tools for Interoperability)
20 // consumer for Moodle 1.9 and Moodle 2.0. BasicLTI is a IMS Standard that allows web
21 // based learning tools to be easily integrated in LMS as native ones. The IMS BasicLTI
22 // specification is part of the IMS standard Common Cartridge 1.1 Sakai and other main LMS
23 // are already supporting or going to support BasicLTI. This project Implements the consumer
24 // for Moodle. Moodle is a Free Open source Learning Management System by Martin Dougiamas.
25 // BasicLTI4Moodle is a project iniciated and leaded by Ludo(Marc Alier) and Jordi Piguillem
26 // at the GESSI research group at UPC.
27 // SimpleLTI consumer for Moodle is an implementation of the early specification of LTI
28 // by Charles Severance (Dr Chuck) htp://dr-chuck.com , developed by Jordi Piguillem in a
29 // Google Summer of Code 2008 project co-mentored by Charles Severance and Marc Alier.
30 //
31 // BasicLTI4Moodle is copyright 2009 by Marc Alier Forment, Jordi Piguillem and Nikolas Galanis
32 // of the Universitat Politecnica de Catalunya http://www.upc.edu
33 // Contact info: Marc Alier Forment granludo @ gmail.com or marc.alier @ upc.edu.
35 /**
36  * This file contains the library of functions and constants for the lti module
37  *
38  * @package mod_lti
39  * @copyright  2009 Marc Alier, Jordi Piguillem, Nikolas Galanis
40  *  marc.alier@upc.edu
41  * @copyright  2009 Universitat Politecnica de Catalunya http://www.upc.edu
42  * @author     Marc Alier
43  * @author     Jordi Piguillem
44  * @author     Nikolas Galanis
45  * @author     Chris Scribner
46  * @copyright  2015 Vital Source Technologies http://vitalsource.com
47  * @author     Stephen Vickers
48  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
49  */
51 defined('MOODLE_INTERNAL') || die;
53 // TODO: Switch to core oauthlib once implemented - MDL-30149.
54 use moodle\mod\lti as lti;
56 require_once($CFG->dirroot.'/mod/lti/OAuth.php');
58 define('LTI_URL_DOMAIN_REGEX', '/(?:https?:\/\/)?(?:www\.)?([^\/]+)(?:\/|$)/i');
60 define('LTI_LAUNCH_CONTAINER_DEFAULT', 1);
61 define('LTI_LAUNCH_CONTAINER_EMBED', 2);
62 define('LTI_LAUNCH_CONTAINER_EMBED_NO_BLOCKS', 3);
63 define('LTI_LAUNCH_CONTAINER_WINDOW', 4);
64 define('LTI_LAUNCH_CONTAINER_REPLACE_MOODLE_WINDOW', 5);
66 define('LTI_TOOL_STATE_ANY', 0);
67 define('LTI_TOOL_STATE_CONFIGURED', 1);
68 define('LTI_TOOL_STATE_PENDING', 2);
69 define('LTI_TOOL_STATE_REJECTED', 3);
70 define('LTI_TOOL_PROXY_TAB', 4);
72 define('LTI_TOOL_PROXY_STATE_CONFIGURED', 1);
73 define('LTI_TOOL_PROXY_STATE_PENDING', 2);
74 define('LTI_TOOL_PROXY_STATE_ACCEPTED', 3);
75 define('LTI_TOOL_PROXY_STATE_REJECTED', 4);
77 define('LTI_SETTING_NEVER', 0);
78 define('LTI_SETTING_ALWAYS', 1);
79 define('LTI_SETTING_DELEGATE', 2);
81 /**
82  * Prints a Basic LTI activity
83  *
84  * $param int $basicltiid       Basic LTI activity id
85  */
86 function lti_view($instance) {
87     global $PAGE, $CFG;
89     if (empty($instance->typeid)) {
90         $tool = lti_get_tool_by_url_match($instance->toolurl, $instance->course);
91         if ($tool) {
92             $typeid = $tool->id;
93         } else {
94             $typeid = null;
95         }
96     } else {
97         $typeid = $instance->typeid;
98         $tool = lti_get_type($typeid);
99     }
101     if ($typeid) {
102         $typeconfig = lti_get_type_config($typeid);
103     } else {
104         // There is no admin configuration for this tool. Use configuration in the lti instance record plus some defaults.
105         $typeconfig = (array)$instance;
107         $typeconfig['sendname'] = $instance->instructorchoicesendname;
108         $typeconfig['sendemailaddr'] = $instance->instructorchoicesendemailaddr;
109         $typeconfig['customparameters'] = $instance->instructorcustomparameters;
110         $typeconfig['acceptgrades'] = $instance->instructorchoiceacceptgrades;
111         $typeconfig['allowroster'] = $instance->instructorchoiceallowroster;
112         $typeconfig['forcessl'] = '0';
113     }
115     // Default the organizationid if not specified.
116     if (empty($typeconfig['organizationid'])) {
117         $urlparts = parse_url($CFG->wwwroot);
119         $typeconfig['organizationid'] = $urlparts['host'];
120     }
122     if (isset($tool->toolproxyid)) {
123         $toolproxy = lti_get_tool_proxy($tool->toolproxyid);
124         $key = $toolproxy->guid;
125         $secret = $toolproxy->secret;
126     } else {
127         $toolproxy = null;
128         if (!empty($instance->resourcekey)) {
129             $key = $instance->resourcekey;
130         } else if (!empty($typeconfig['resourcekey'])) {
131             $key = $typeconfig['resourcekey'];
132         } else {
133             $key = '';
134         }
135         if (!empty($instance->password)) {
136             $secret = $instance->password;
137         } else if (!empty($typeconfig['password'])) {
138             $secret = $typeconfig['password'];
139         } else {
140             $secret = '';
141         }
142     }
144     $endpoint = !empty($instance->toolurl) ? $instance->toolurl : $typeconfig['toolurl'];
145     $endpoint = trim($endpoint);
147     // If the current request is using SSL and a secure tool URL is specified, use it.
148     if (lti_request_is_using_ssl() && !empty($instance->securetoolurl)) {
149         $endpoint = trim($instance->securetoolurl);
150     }
152     // If SSL is forced, use the secure tool url if specified. Otherwise, make sure https is on the normal launch URL.
153     if (isset($typeconfig['forcessl']) && ($typeconfig['forcessl'] == '1')) {
154         if (!empty($instance->securetoolurl)) {
155             $endpoint = trim($instance->securetoolurl);
156         }
158         $endpoint = lti_ensure_url_is_https($endpoint);
159     } else {
160         if (!strstr($endpoint, '://')) {
161             $endpoint = 'http://' . $endpoint;
162         }
163     }
165     $orgid = $typeconfig['organizationid'];
167     $course = $PAGE->course;
168     $islti2 = isset($tool->toolproxyid);
169     $allparams = lti_build_request($instance, $typeconfig, $course, $typeid, $islti2);
170     if ($islti2) {
171         $requestparams = lti_build_request_lti2($tool, $allparams);
172     } else {
173         $requestparams = $allparams;
174     }
175     $requestparams = array_merge($requestparams, lti_build_standard_request($instance, $orgid, $islti2));
176     $customstr = '';
177     if (isset($typeconfig['customparameters'])) {
178         $customstr = $typeconfig['customparameters'];
179     }
180     $requestparams = array_merge($requestparams, lti_build_custom_parameters($toolproxy, $tool, $instance, $allparams, $customstr,
181         $instance->instructorcustomparameters, $islti2));
183     $launchcontainer = lti_get_launch_container($instance, $typeconfig);
184     $returnurlparams = array('course' => $course->id,
185                              'launch_container' => $launchcontainer,
186                              'instanceid' => $instance->id,
187                              'sesskey' => sesskey());
189     // Add the return URL. We send the launch container along to help us avoid frames-within-frames when the user returns.
190     $url = new \moodle_url('/mod/lti/return.php', $returnurlparams);
191     $returnurl = $url->out(false);
193     if (isset($typeconfig['forcessl']) && ($typeconfig['forcessl'] == '1')) {
194         $returnurl = lti_ensure_url_is_https($returnurl);
195     }
197     $target = '';
198     switch($launchcontainer) {
199         case LTI_LAUNCH_CONTAINER_EMBED:
200         case LTI_LAUNCH_CONTAINER_EMBED_NO_BLOCKS:
201             $target = 'iframe';
202             break;
203         case LTI_LAUNCH_CONTAINER_REPLACE_MOODLE_WINDOW:
204             $target = 'frame';
205             break;
206         case LTI_LAUNCH_CONTAINER_WINDOW:
207             $target = 'window';
208             break;
209     }
210     if (!empty($target)) {
211         $requestparams['launch_presentation_document_target'] = $target;
212     }
214     $requestparams['launch_presentation_return_url'] = $returnurl;
216     // Allow request params to be updated by sub-plugins.
217     $plugins = core_component::get_plugin_list('ltisource');
218     foreach (array_keys($plugins) as $plugin) {
219         $pluginparams = component_callback('ltisource_'.$plugin, 'before_launch',
220             array($instance, $endpoint, $requestparams), array());
222         if (!empty($pluginparams) && is_array($pluginparams)) {
223             $requestparams = array_merge($requestparams, $pluginparams);
224         }
225     }
227     if (!empty($key) && !empty($secret)) {
228         $parms = lti_sign_parameters($requestparams, $endpoint, "POST", $key, $secret);
230         $endpointurl = new \moodle_url($endpoint);
231         $endpointparams = $endpointurl->params();
233         // Strip querystring params in endpoint url from $parms to avoid duplication.
234         if (!empty($endpointparams) && !empty($parms)) {
235             foreach (array_keys($endpointparams) as $paramname) {
236                 if (isset($parms[$paramname])) {
237                     unset($parms[$paramname]);
238                 }
239             }
240         }
242     } else {
243         // If no key and secret, do the launch unsigned.
244         $returnurlparams['unsigned'] = '1';
245         $parms = $requestparams;
246     }
248     $debuglaunch = ( $instance->debuglaunch == 1 );
250     $content = lti_post_launch_html($parms, $endpoint, $debuglaunch);
252     echo $content;
255 /**
256  * Prepares an LTI registration request message
257  *
258  * $param object $instance       Tool Proxy instance object
259  */
260 function lti_register($toolproxy) {
261     global $PAGE, $CFG;
263     $key = $toolproxy->guid;
264     $secret = $toolproxy->secret;
265     $endpoint = $toolproxy->regurl;
267     $requestparams = array();
268     $requestparams['lti_message_type'] = 'ToolProxyRegistrationRequest';
269     $requestparams['lti_version'] = 'LTI-2p0';
270     $requestparams['reg_key'] = $key;
271     $requestparams['reg_password'] = $secret;
273     // Change the status to pending.
274     $toolproxy->state = LTI_TOOL_PROXY_STATE_PENDING;
275     lti_update_tool_proxy($toolproxy);
277     // Add the profile URL.
278     $profileservice = lti_get_service_by_name('profile');
279     $profileservice->set_tool_proxy($toolproxy);
280     $requestparams['tc_profile_url'] = $profileservice->parse_value('$ToolConsumerProfile.url');
282     // Add the return URL.
283     $returnurlparams = array('id' => $toolproxy->id, 'sesskey' => sesskey());
284     $url = new \moodle_url('/mod/lti/registrationreturn.php', $returnurlparams);
285     $returnurl = $url->out(false);
287     $requestparams['launch_presentation_return_url'] = $returnurl;
288     $content = lti_post_launch_html($requestparams, $endpoint, false);
290     echo $content;
293 /**
294  * Build source ID
295  *
296  * @param int $instanceid
297  * @param int $userid
298  * @param string $servicesalt
299  * @param null|int $typeid
300  * @param null|int $launchid
301  * @return stdClass
302  */
303 function lti_build_sourcedid($instanceid, $userid, $servicesalt, $typeid = null, $launchid = null) {
304     $data = new \stdClass();
306     $data->instanceid = $instanceid;
307     $data->userid = $userid;
308     $data->typeid = $typeid;
309     if (!empty($launchid)) {
310         $data->launchid = $launchid;
311     } else {
312         $data->launchid = mt_rand();
313     }
315     $json = json_encode($data);
317     $hash = hash('sha256', $json . $servicesalt, false);
319     $container = new \stdClass();
320     $container->data = $data;
321     $container->hash = $hash;
323     return $container;
326 /**
327  * This function builds the request that must be sent to the tool producer
328  *
329  * @param object    $instance       Basic LTI instance object
330  * @param array     $typeconfig     Basic LTI tool configuration
331  * @param object    $course         Course object
332  * @param int|null  $typeid         Basic LTI tool ID
333  * @param boolean   $islti2         True if an LTI 2 tool is being launched
334  *
335  * @return array                    Request details
336  */
337 function lti_build_request($instance, $typeconfig, $course, $typeid = null, $islti2 = false) {
338     global $USER, $CFG;
340     if (empty($instance->cmid)) {
341         $instance->cmid = 0;
342     }
344     $role = lti_get_ims_role($USER, $instance->cmid, $instance->course, $islti2);
346     $intro = '';
347     if (!empty($instance->cmid)) {
348         $intro = format_module_intro('lti', $instance, $instance->cmid);
349         $intro = html_to_text($intro, 0, false);
351         // This may look weird, but this is required for new lines
352         // so we generate the same OAuth signature as the tool provider.
353         $intro = str_replace("\n", "\r\n", $intro);
354     }
355     $requestparams = array(
356         'resource_link_title' => $instance->name,
357         'resource_link_description' => $intro,
358         'user_id' => $USER->id,
359         'lis_person_sourcedid' => $USER->idnumber,
360         'roles' => $role,
361         'context_id' => $course->id,
362         'context_label' => $course->shortname,
363         'context_title' => $course->fullname,
364     );
365     if (!empty($instance->id)) {
366         $requestparams['resource_link_id'] = $instance->id;
367     }
368     if (!empty($instance->resource_link_id)) {
369         $requestparams['resource_link_id'] = $instance->resource_link_id;
370     }
371     if ($course->format == 'site') {
372         $requestparams['context_type'] = 'Group';
373     } else {
374         $requestparams['context_type'] = 'CourseSection';
375         $requestparams['lis_course_section_sourcedid'] = $course->idnumber;
376     }
377     $placementsecret = $instance->servicesalt;
379     if ( !empty($instance->id) && isset($placementsecret) && ($islti2 ||
380          $typeconfig['acceptgrades'] == LTI_SETTING_ALWAYS ||
381          ($typeconfig['acceptgrades'] == LTI_SETTING_DELEGATE && $instance->instructorchoiceacceptgrades == LTI_SETTING_ALWAYS))) {
383         $sourcedid = json_encode(lti_build_sourcedid($instance->id, $USER->id, $placementsecret, $typeid));
384         $requestparams['lis_result_sourcedid'] = $sourcedid;
386         // Add outcome service URL.
387         $serviceurl = new \moodle_url('/mod/lti/service.php');
388         $serviceurl = $serviceurl->out();
390         $forcessl = false;
391         if (!empty($CFG->mod_lti_forcessl)) {
392             $forcessl = true;
393         }
395         if ((isset($typeconfig['forcessl']) && ($typeconfig['forcessl'] == '1')) or $forcessl) {
396             $serviceurl = lti_ensure_url_is_https($serviceurl);
397         }
399         $requestparams['lis_outcome_service_url'] = $serviceurl;
400     }
402     // Send user's name and email data if appropriate.
403     if ($islti2 || $typeconfig['sendname'] == LTI_SETTING_ALWAYS ||
404          ( $typeconfig['sendname'] == LTI_SETTING_DELEGATE && $instance->instructorchoicesendname == LTI_SETTING_ALWAYS ) ) {
405         $requestparams['lis_person_name_given'] = $USER->firstname;
406         $requestparams['lis_person_name_family'] = $USER->lastname;
407         $requestparams['lis_person_name_full'] = $USER->firstname . ' ' . $USER->lastname;
408         $requestparams['ext_user_username'] = $USER->username;
409     }
411     if ($islti2 || $typeconfig['sendemailaddr'] == LTI_SETTING_ALWAYS ||
412          ($typeconfig['sendemailaddr'] == LTI_SETTING_DELEGATE && $instance->instructorchoicesendemailaddr == LTI_SETTING_ALWAYS)) {
413         $requestparams['lis_person_contact_email_primary'] = $USER->email;
414     }
416     return $requestparams;
419 /**
420  * This function builds the request that must be sent to an LTI 2 tool provider
421  *
422  * @param object    $tool           Basic LTI tool object
423  * @param array     $params         Custom launch parameters
424  *
425  * @return array                    Request details
426  */
427 function lti_build_request_lti2($tool, $params) {
429     $requestparams = array();
431     $capabilities = lti_get_capabilities();
432     $enabledcapabilities = explode("\n", $tool->enabledcapability);
433     foreach ($enabledcapabilities as $capability) {
434         if (array_key_exists($capability, $capabilities)) {
435             $val = $capabilities[$capability];
436             if ($val && (substr($val, 0, 1) != '$')) {
437                 if (isset($params[$val])) {
438                     $requestparams[$capabilities[$capability]] = $params[$capabilities[$capability]];
439                 }
440             }
441         }
442     }
444     return $requestparams;
448 /**
449  * This function builds the standard parameters for an LTI 1 or 2 request that must be sent to the tool producer
450  *
451  * @param object    $instance       Basic LTI instance object
452  * @param string    $orgid          Organisation ID
453  * @param boolean   $islti2         True if an LTI 2 tool is being launched
454  *
455  * @return array                    Request details
456  */
457 function lti_build_standard_request($instance, $orgid, $islti2) {
458     global $CFG;
460     $requestparams = array();
462     $requestparams['resource_link_id'] = $instance->id;
463     if (property_exists($instance, 'resource_link_id') and !empty($instance->resource_link_id)) {
464         $requestparams['resource_link_id'] = $instance->resource_link_id;
465     }
467     $requestparams['launch_presentation_locale'] = current_language();
469     // Make sure we let the tool know what LMS they are being called from.
470     $requestparams['ext_lms'] = 'moodle-2';
471     $requestparams['tool_consumer_info_product_family_code'] = 'moodle';
472     $requestparams['tool_consumer_info_version'] = strval($CFG->version);
474     // Add oauth_callback to be compliant with the 1.0A spec.
475     $requestparams['oauth_callback'] = 'about:blank';
477     if (!$islti2) {
478         $requestparams['lti_version'] = 'LTI-1p0';
479     } else {
480         $requestparams['lti_version'] = 'LTI-2p0';
481     }
482     $requestparams['lti_message_type'] = 'basic-lti-launch-request';
484     if ($orgid) {
485         $requestparams["tool_consumer_instance_guid"] = $orgid;
486     }
487     if (!empty($CFG->mod_lti_institution_name)) {
488         $requestparams['tool_consumer_instance_name'] = $CFG->mod_lti_institution_name;
489     } else {
490         $requestparams['tool_consumer_instance_name'] = get_site()->fullname;
491     }
493     return $requestparams;
496 /**
497  * This function builds the custom parameters
498  *
499  * @param object    $toolproxy      Tool proxy instance object
500  * @param object    $tool           Tool instance object
501  * @param object    $instance       Tool placement instance object
502  * @param array     $params         LTI launch parameters
503  * @param string    $customstr      Custom parameters defined for tool
504  * @param string    $instructorcustomstr      Custom parameters defined for this placement
505  * @param boolean   $islti2         True if an LTI 2 tool is being launched
506  *
507  * @return array                    Custom parameters
508  */
509 function lti_build_custom_parameters($toolproxy, $tool, $instance, $params, $customstr, $instructorcustomstr, $islti2) {
511     // Concatenate the custom parameters from the administrator and the instructor
512     // Instructor parameters are only taken into consideration if the administrator
513     // has given permission.
514     $custom = array();
515     if ($customstr) {
516         $custom = lti_split_custom_parameters($toolproxy, $tool, $params, $customstr, $islti2);
517     }
518     if (!isset($typeconfig['allowinstructorcustom']) || $typeconfig['allowinstructorcustom'] != LTI_SETTING_NEVER) {
519         if ($instructorcustomstr) {
520             $custom = array_merge(lti_split_custom_parameters($toolproxy, $tool, $params,
521                 $instructorcustomstr, $islti2), $custom);
522         }
523     }
524     if ($islti2) {
525         $custom = array_merge(lti_split_custom_parameters($toolproxy, $tool, $params,
526             $tool->parameter, true), $custom);
527         $settings = lti_get_tool_settings($tool->toolproxyid);
528         $custom = array_merge($custom, lti_get_custom_parameters($toolproxy, $tool, $params, $settings));
529         $settings = lti_get_tool_settings($tool->toolproxyid, $instance->course);
530         $custom = array_merge($custom, lti_get_custom_parameters($toolproxy, $tool, $params, $settings));
531         $settings = lti_get_tool_settings($tool->toolproxyid, $instance->course, $instance->id);
532         $custom = array_merge($custom, lti_get_custom_parameters($toolproxy, $tool, $params, $settings));
533     }
535     return $custom;
538 function lti_get_tool_table($tools, $id) {
539     global $CFG, $OUTPUT, $USER;
540     $html = '';
542     $typename = get_string('typename', 'lti');
543     $baseurl = get_string('baseurl', 'lti');
544     $action = get_string('action', 'lti');
545     $createdon = get_string('createdon', 'lti');
547     if (!empty($tools)) {
548         $html .= "
549         <div id=\"{$id}_tools_container\" style=\"margin-top:.5em;margin-bottom:.5em\">
550             <table id=\"{$id}_tools\">
551                 <thead>
552                     <tr>
553                         <th>$typename</th>
554                         <th>$baseurl</th>
555                         <th>$createdon</th>
556                         <th>$action</th>
557                     </tr>
558                 </thead>
559         ";
561         foreach ($tools as $type) {
562             $date = userdate($type->timecreated, get_string('strftimedatefullshort', 'core_langconfig'));
563             $accept = get_string('accept', 'lti');
564             $update = get_string('update', 'lti');
565             $delete = get_string('delete', 'lti');
567             if (empty($type->toolproxyid)) {
568                 $baseurl = new \moodle_url('/mod/lti/typessettings.php', array(
569                         'action' => 'accept',
570                         'id' => $type->id,
571                         'sesskey' => sesskey(),
572                         'tab' => $id
573                     ));
574                 $ref = $type->baseurl;
575             } else {
576                 $baseurl = new \moodle_url('/mod/lti/toolssettings.php', array(
577                         'action' => 'accept',
578                         'id' => $type->id,
579                         'sesskey' => sesskey(),
580                         'tab' => $id
581                     ));
582                 $ref = $type->tpname;
583             }
585             $accepthtml = $OUTPUT->action_icon($baseurl,
586                     new \pix_icon('t/check', $accept, '', array('class' => 'iconsmall')), null,
587                     array('title' => $accept, 'class' => 'editing_accept'));
589             $deleteaction = 'delete';
591             if ($type->state == LTI_TOOL_STATE_CONFIGURED) {
592                 $accepthtml = '';
593             }
595             if ($type->state != LTI_TOOL_STATE_REJECTED) {
596                 $deleteaction = 'reject';
597                 $delete = get_string('reject', 'lti');
598             }
600             $updateurl = clone($baseurl);
601             $updateurl->param('action', 'update');
602             $updatehtml = $OUTPUT->action_icon($updateurl,
603                     new \pix_icon('t/edit', $update, '', array('class' => 'iconsmall')), null,
604                     array('title' => $update, 'class' => 'editing_update'));
606             if (($type->state != LTI_TOOL_STATE_REJECTED) || empty($type->toolproxyid)) {
607                 $deleteurl = clone($baseurl);
608                 $deleteurl->param('action', $deleteaction);
609                 $deletehtml = $OUTPUT->action_icon($deleteurl,
610                         new \pix_icon('t/delete', $delete, '', array('class' => 'iconsmall')), null,
611                         array('title' => $delete, 'class' => 'editing_delete'));
612             } else {
613                 $deletehtml = '';
614             }
615             $html .= "
616             <tr>
617                 <td>
618                     {$type->name}
619                 </td>
620                 <td>
621                     {$ref}
622                 </td>
623                 <td>
624                     {$date}
625                 </td>
626                 <td align=\"center\">
627                     {$accepthtml}{$updatehtml}{$deletehtml}
628                 </td>
629             </tr>
630             ";
631         }
632         $html .= '</table></div>';
633     } else {
634         $html .= get_string('no_' . $id, 'lti');
635     }
637     return $html;
640 /**
641  * This function builds the tab for a category of tool proxies
642  *
643  * @param object    $toolproxies    Tool proxy instance objects
644  * @param string    $id             Category ID
645  *
646  * @return string                   HTML for tab
647  */
648 function lti_get_tool_proxy_table($toolproxies, $id) {
649     global $OUTPUT;
651     if (!empty($toolproxies)) {
652         $typename = get_string('typename', 'lti');
653         $url = get_string('registrationurl', 'lti');
654         $action = get_string('action', 'lti');
655         $createdon = get_string('createdon', 'lti');
657         $html = <<< EOD
658         <div id="{$id}_tool_proxies_container" style="margin-top: 0.5em; margin-bottom: 0.5em">
659             <table id="{$id}_tool_proxies">
660                 <thead>
661                     <tr>
662                         <th>{$typename}</th>
663                         <th>{$url}</th>
664                         <th>{$createdon}</th>
665                         <th>{$action}</th>
666                     </tr>
667                 </thead>
668 EOD;
669         foreach ($toolproxies as $toolproxy) {
670             $date = userdate($toolproxy->timecreated, get_string('strftimedatefullshort', 'core_langconfig'));
671             $accept = get_string('register', 'lti');
672             $update = get_string('update', 'lti');
673             $delete = get_string('delete', 'lti');
675             $baseurl = new \moodle_url('/mod/lti/registersettings.php', array(
676                     'action' => 'accept',
677                     'id' => $toolproxy->id,
678                     'sesskey' => sesskey(),
679                     'tab' => $id
680                 ));
682             $registerurl = new \moodle_url('/mod/lti/register.php', array(
683                     'id' => $toolproxy->id,
684                     'sesskey' => sesskey(),
685                     'tab' => 'tool_proxy'
686                 ));
688             $accepthtml = $OUTPUT->action_icon($registerurl,
689                     new \pix_icon('t/check', $accept, '', array('class' => 'iconsmall')), null,
690                     array('title' => $accept, 'class' => 'editing_accept'));
692             $deleteaction = 'delete';
694             if ($toolproxy->state != LTI_TOOL_PROXY_STATE_CONFIGURED) {
695                 $accepthtml = '';
696             }
698             if (($toolproxy->state == LTI_TOOL_PROXY_STATE_CONFIGURED) || ($toolproxy->state == LTI_TOOL_PROXY_STATE_PENDING)) {
699                 $delete = get_string('cancel', 'lti');
700             }
702             $updateurl = clone($baseurl);
703             $updateurl->param('action', 'update');
704             $updatehtml = $OUTPUT->action_icon($updateurl,
705                     new \pix_icon('t/edit', $update, '', array('class' => 'iconsmall')), null,
706                     array('title' => $update, 'class' => 'editing_update'));
708             $deleteurl = clone($baseurl);
709             $deleteurl->param('action', $deleteaction);
710             $deletehtml = $OUTPUT->action_icon($deleteurl,
711                     new \pix_icon('t/delete', $delete, '', array('class' => 'iconsmall')), null,
712                     array('title' => $delete, 'class' => 'editing_delete'));
713             $html .= <<< EOD
714             <tr>
715                 <td>
716                     {$toolproxy->name}
717                 </td>
718                 <td>
719                     {$toolproxy->regurl}
720                 </td>
721                 <td>
722                     {$date}
723                 </td>
724                 <td align="center">
725                     {$accepthtml}{$updatehtml}{$deletehtml}
726                 </td>
727             </tr>
728 EOD;
729         }
730         $html .= '</table></div>';
731     } else {
732         $html = get_string('no_' . $id, 'lti');
733     }
735     return $html;
738 /**
739  * Extracts the enabled capabilities into an array, including those implicitly declared in a parameter
740  *
741  * @param object    $tool           Tool instance object
742  *
743  * @return Array of enabled capabilities
744  */
745 function lti_get_enabled_capabilities($tool) {
746     if (!empty($tool->enabledcapability)) {
747         $enabledcapabilities = explode("\n", $tool->enabledcapability);
748     } else {
749         $enabledcapabilities = array();
750     }
751     $paramstr = str_replace("\r\n", "\n", $tool->parameter);
752     $paramstr = str_replace("\n\r", "\n", $paramstr);
753     $paramstr = str_replace("\r", "\n", $paramstr);
754     $params = explode("\n", $paramstr);
755     foreach ($params as $param) {
756         $pos = strpos($param, '=');
757         if (($pos === false) || ($pos < 1)) {
758             continue;
759         }
760         $value = trim(core_text::substr($param, $pos + 1, strlen($param)));
761         if (substr($value, 0, 1) == '$') {
762             $value = substr($value, 1);
763             if (!in_array($value, $enabledcapabilities)) {
764                 $enabledcapabilities[] = $value;
765             }
766         }
767     }
768     return $enabledcapabilities;
771 /**
772  * Splits the custom parameters field to the various parameters
773  *
774  * @param object    $toolproxy      Tool proxy instance object
775  * @param object    $tool           Tool instance object
776  * @param array     $params         LTI launch parameters
777  * @param string    $customstr      String containing the parameters
778  * @param boolean   $islti2         True if an LTI 2 tool is being launched
779  *
780  * @return Array of custom parameters
781  */
782 function lti_split_custom_parameters($toolproxy, $tool, $params, $customstr, $islti2 = false) {
783     $customstr = str_replace("\r\n", "\n", $customstr);
784     $customstr = str_replace("\n\r", "\n", $customstr);
785     $customstr = str_replace("\r", "\n", $customstr);
786     $lines = explode("\n", $customstr);  // Or should this split on "/[\n;]/"?
787     $retval = array();
788     foreach ($lines as $line) {
789         $pos = strpos($line, '=');
790         if ( $pos === false || $pos < 1 ) {
791             continue;
792         }
793         $key = trim(core_text::substr($line, 0, $pos));
794         $val = trim(core_text::substr($line, $pos + 1, strlen($line)));
795         $val = lti_parse_custom_parameter($toolproxy, $tool, $params, $val, $islti2);
796         $key2 = lti_map_keyname($key);
797         $retval['custom_'.$key2] = $val;
798         if ($islti2 && ($key != $key2)) {
799             $retval['custom_'.$key] = $val;
800         }
801     }
802     return $retval;
805 /**
806  * Adds the custom parameters to an array
807  *
808  * @param object    $toolproxy      Tool proxy instance object
809  * @param object    $tool           Tool instance object
810  * @param array     $params         LTI launch parameters
811  * @param array     $parameters     Array containing the parameters
812  *
813  * @return array    Array of custom parameters
814  */
815 function lti_get_custom_parameters($toolproxy, $tool, $params, $parameters) {
816     $retval = array();
817     foreach ($parameters as $key => $val) {
818         $key2 = lti_map_keyname($key);
819         $val = lti_parse_custom_parameter($toolproxy, $tool, $params, $val, true);
820         $retval['custom_'.$key2] = $val;
821         if ($key != $key2) {
822             $retval['custom_'.$key] = $val;
823         }
824     }
825     return $retval;
828 /**
829  * Parse a custom parameter to replace any substitution variables
830  *
831  * @param object    $toolproxy      Tool proxy instance object
832  * @param object    $tool           Tool instance object
833  * @param array     $params         LTI launch parameters
834  * @param string    $value          Custom parameter value
835  * @param boolean   $islti2         True if an LTI 2 tool is being launched
836  *
837  * @return Parsed value of custom parameter
838  */
839 function lti_parse_custom_parameter($toolproxy, $tool, $params, $value, $islti2) {
840     global $USER, $COURSE;
842     if ($value) {
843         if (substr($value, 0, 1) == '\\') {
844             $value = substr($value, 1);
845         } else if (substr($value, 0, 1) == '$') {
846             $value1 = substr($value, 1);
847             $enabledcapabilities = lti_get_enabled_capabilities($tool);
848             if (!$islti2 || in_array($value1, $enabledcapabilities)) {
849                 $capabilities = lti_get_capabilities();
850                 if (array_key_exists($value1, $capabilities)) {
851                     $val = $capabilities[$value1];
852                     if ($val) {
853                         if (substr($val, 0, 1) != '$') {
854                             $value = $params[$val];
855                         } else {
856                             $valarr = explode('->', substr($val, 1), 2);
857                             $value = "{${$valarr[0]}->$valarr[1]}";
858                             $value = str_replace('<br />' , ' ', $value);
859                             $value = str_replace('<br>' , ' ', $value);
860                             $value = format_string($value);
861                         }
862                     }
863                 } else if ($islti2) {
864                     $val = $value;
865                     $services = lti_get_services();
866                     foreach ($services as $service) {
867                         $service->set_tool_proxy($toolproxy);
868                         $value = $service->parse_value($val);
869                         if ($val != $value) {
870                             break;
871                         }
872                     }
873                 }
874             }
875         }
876     }
877     return $value;
880 /**
881  * Used for building the names of the different custom parameters
882  *
883  * @param string $key   Parameter name
884  *
885  * @return string       Processed name
886  */
887 function lti_map_keyname($key) {
888     $newkey = "";
889     $key = core_text::strtolower(trim($key));
890     foreach (str_split($key) as $ch) {
891         if ( ($ch >= 'a' && $ch <= 'z') || ($ch >= '0' && $ch <= '9') ) {
892             $newkey .= $ch;
893         } else {
894             $newkey .= '_';
895         }
896     }
897     return $newkey;
900 /**
901  * Gets the IMS role string for the specified user and LTI course module.
902  *
903  * @param mixed    $user      User object or user id
904  * @param int      $cmid      The course module id of the LTI activity
905  * @param int      $courseid  The course id of the LTI activity
906  * @param boolean  $islti2    True if an LTI 2 tool is being launched
907  *
908  * @return string A role string suitable for passing with an LTI launch
909  */
910 function lti_get_ims_role($user, $cmid, $courseid, $islti2) {
911     $roles = array();
913     if (empty($cmid)) {
914         // If no cmid is passed, check if the user is a teacher in the course
915         // This allows other modules to programmatically "fake" a launch without
916         // a real LTI instance.
917         $coursecontext = context_course::instance($courseid);
919         if (has_capability('moodle/course:manageactivities', $coursecontext)) {
920             array_push($roles, 'Instructor');
921         } else {
922             array_push($roles, 'Learner');
923         }
924     } else {
925         $context = context_module::instance($cmid);
927         if (has_capability('mod/lti:manage', $context)) {
928             array_push($roles, 'Instructor');
929         } else {
930             array_push($roles, 'Learner');
931         }
932     }
934     if (is_siteadmin($user)) {
935         if (!$islti2) {
936             array_push($roles, 'urn:lti:sysrole:ims/lis/Administrator', 'urn:lti:instrole:ims/lis/Administrator');
937         } else {
938             array_push($roles, 'http://purl.imsglobal.org/vocab/lis/v2/person#Administrator');
939         }
940     }
942     return join(',', $roles);
945 /**
946  * Returns configuration details for the tool
947  *
948  * @param int $typeid   Basic LTI tool typeid
949  *
950  * @return array        Tool Configuration
951  */
952 function lti_get_type_config($typeid) {
953     global $DB;
955     $query = "SELECT name, value
956                 FROM {lti_types_config}
957                WHERE typeid = :typeid1
958            UNION ALL
959               SELECT 'toolurl' AS name, " . $DB->sql_compare_text('baseurl', 1333) . " AS value
960                 FROM {lti_types}
961                WHERE id = :typeid2
962            UNION ALL
963               SELECT 'icon' AS name, " . $DB->sql_compare_text('icon', 1333) . " AS value
964                 FROM {lti_types}
965                WHERE id = :typeid3
966            UNION ALL
967               SELECT 'secureicon' AS name, " . $DB->sql_compare_text('secureicon', 1333) . " AS value
968                 FROM {lti_types}
969                WHERE id = :typeid4";
971     $typeconfig = array();
972     $configs = $DB->get_records_sql($query,
973         array('typeid1' => $typeid, 'typeid2' => $typeid, 'typeid3' => $typeid, 'typeid4' => $typeid));
975     if (!empty($configs)) {
976         foreach ($configs as $config) {
977             $typeconfig[$config->name] = $config->value;
978         }
979     }
981     return $typeconfig;
984 function lti_get_tools_by_url($url, $state, $courseid = null) {
985     $domain = lti_get_domain_from_url($url);
987     return lti_get_tools_by_domain($domain, $state, $courseid);
990 function lti_get_tools_by_domain($domain, $state = null, $courseid = null) {
991     global $DB, $SITE;
993     $filters = array('tooldomain' => $domain);
995     $statefilter = '';
996     $coursefilter = '';
998     if ($state) {
999         $statefilter = 'AND state = :state';
1000     }
1002     if ($courseid && $courseid != $SITE->id) {
1003         $coursefilter = 'OR course = :courseid';
1004     }
1006     $query = "SELECT *
1007                 FROM {lti_types}
1008                WHERE tooldomain = :tooldomain
1009                  AND (course = :siteid $coursefilter)
1010                  $statefilter";
1012     return $DB->get_records_sql($query, array(
1013         'courseid' => $courseid,
1014         'siteid' => $SITE->id,
1015         'tooldomain' => $domain,
1016         'state' => $state
1017     ));
1020 /**
1021  * Returns all basicLTI tools configured by the administrator
1022  *
1023  */
1024 function lti_filter_get_types($course) {
1025     global $DB;
1027     if (!empty($course)) {
1028         $where = "WHERE t.course = :course";
1029         $params = array('course' => $course);
1030     } else {
1031         $where = '';
1032         $params = array();
1033     }
1034     $query = "SELECT t.id, t.name, t.baseurl, t.state, t.toolproxyid, t.timecreated, tp.name tpname
1035                 FROM {lti_types} t LEFT OUTER JOIN {lti_tool_proxies} tp ON t.toolproxyid = tp.id
1036                 {$where}";
1037     return $DB->get_records_sql($query, $params);
1040 /**
1041  * Given an array of tools, filter them based on their state
1042  *
1043  * @param array $tools An array of lti_types records
1044  * @param int $state One of the LTI_TOOL_STATE_* constants
1045  * @return array
1046  */
1047 function lti_filter_tool_types(array $tools, $state) {
1048     $return = array();
1049     foreach ($tools as $key => $tool) {
1050         if ($tool->state == $state) {
1051             $return[$key] = $tool;
1052         }
1053     }
1054     return $return;
1057 function lti_get_types_for_add_instance() {
1058     global $DB, $SITE, $COURSE;
1060     $query = "SELECT *
1061                 FROM {lti_types}
1062                WHERE coursevisible = 1
1063                  AND (course = :siteid OR course = :courseid)
1064                  AND state = :active";
1066     $admintypes = $DB->get_records_sql($query,
1067         array('siteid' => $SITE->id, 'courseid' => $COURSE->id, 'active' => LTI_TOOL_STATE_CONFIGURED));
1069     $types = array();
1070     $types[0] = (object)array('name' => get_string('automatic', 'lti'), 'course' => 0, 'toolproxyid' => null);
1072     foreach ($admintypes as $type) {
1073         $types[$type->id] = $type;
1074     }
1076     return $types;
1079 function lti_get_domain_from_url($url) {
1080     $matches = array();
1082     if (preg_match(LTI_URL_DOMAIN_REGEX, $url, $matches)) {
1083         return $matches[1];
1084     }
1087 function lti_get_tool_by_url_match($url, $courseid = null, $state = LTI_TOOL_STATE_CONFIGURED) {
1088     $possibletools = lti_get_tools_by_url($url, $state, $courseid);
1090     return lti_get_best_tool_by_url($url, $possibletools, $courseid);
1093 function lti_get_url_thumbprint($url) {
1094     // Parse URL requires a schema otherwise everything goes into 'path'.  Fixed 5.4.7 or later.
1095     if (preg_match('/https?:\/\//', $url) !== 1) {
1096         $url = 'http://'.$url;
1097     }
1098     $urlparts = parse_url(strtolower($url));
1099     if (!isset($urlparts['path'])) {
1100         $urlparts['path'] = '';
1101     }
1103     if (!isset($urlparts['host'])) {
1104         $urlparts['host'] = '';
1105     }
1107     if (substr($urlparts['host'], 0, 4) === 'www.') {
1108         $urlparts['host'] = substr($urlparts['host'], 4);
1109     }
1111     return $urllower = $urlparts['host'] . '/' . $urlparts['path'];
1114 function lti_get_best_tool_by_url($url, $tools, $courseid = null) {
1115     if (count($tools) === 0) {
1116         return null;
1117     }
1119     $urllower = lti_get_url_thumbprint($url);
1121     foreach ($tools as $tool) {
1122         $tool->_matchscore = 0;
1124         $toolbaseurllower = lti_get_url_thumbprint($tool->baseurl);
1126         if ($urllower === $toolbaseurllower) {
1127             // 100 points for exact thumbprint match.
1128             $tool->_matchscore += 100;
1129         } else if (substr($urllower, 0, strlen($toolbaseurllower)) === $toolbaseurllower) {
1130             // 50 points if tool thumbprint starts with the base URL thumbprint.
1131             $tool->_matchscore += 50;
1132         }
1134         // Prefer course tools over site tools.
1135         if (!empty($courseid)) {
1136             // Minus 10 points for not matching the course id (global tools).
1137             if ($tool->course != $courseid) {
1138                 $tool->_matchscore -= 10;
1139             }
1140         }
1141     }
1143     $bestmatch = array_reduce($tools, function($value, $tool) {
1144         if ($tool->_matchscore > $value->_matchscore) {
1145             return $tool;
1146         } else {
1147             return $value;
1148         }
1150     }, (object)array('_matchscore' => -1));
1152     // None of the tools are suitable for this URL.
1153     if ($bestmatch->_matchscore <= 0) {
1154         return null;
1155     }
1157     return $bestmatch;
1160 function lti_get_shared_secrets_by_key($key) {
1161     global $DB;
1163     // Look up the shared secret for the specified key in both the types_config table (for configured tools)
1164     // And in the lti resource table for ad-hoc tools.
1165     $query = "SELECT t2.value
1166                 FROM {lti_types_config} t1
1167                 JOIN {lti_types_config} t2 ON t1.typeid = t2.typeid
1168                 JOIN {lti_types} type ON t2.typeid = type.id
1169               WHERE t1.name = 'resourcekey'
1170                 AND t1.value = :key1
1171                 AND t2.name = 'password'
1172                 AND type.state = :configured1
1173                UNION
1174               SELECT tp.secret AS value
1175                 FROM {lti_tool_proxies} tp
1176                 JOIN {lti_types} t ON tp.id = t.toolproxyid
1177               WHERE tp.guid = :key2
1178                 AND t.state = :configured2
1179               UNION
1180              SELECT password AS value
1181                FROM {lti}
1182               WHERE resourcekey = :key3";
1184     $sharedsecrets = $DB->get_records_sql($query, array('configured1' => LTI_TOOL_STATE_CONFIGURED,
1185         'configured2' => LTI_TOOL_STATE_CONFIGURED, 'key1' => $key, 'key2' => $key, 'key3' => $key));
1187     $values = array_map(function($item) {
1188         return $item->value;
1189     }, $sharedsecrets);
1191     // There should really only be one shared secret per key. But, we can't prevent
1192     // more than one getting entered. For instance, if the same key is used for two tool providers.
1193     return $values;
1196 /**
1197  * Delete a Basic LTI configuration
1198  *
1199  * @param int $id   Configuration id
1200  */
1201 function lti_delete_type($id) {
1202     global $DB;
1204     // We should probably just copy the launch URL to the tool instances in this case... using a single query.
1205     /*
1206     $instances = $DB->get_records('lti', array('typeid' => $id));
1207     foreach ($instances as $instance) {
1208         $instance->typeid = 0;
1209         $DB->update_record('lti', $instance);
1210     }*/
1212     $DB->delete_records('lti_types', array('id' => $id));
1213     $DB->delete_records('lti_types_config', array('typeid' => $id));
1216 function lti_set_state_for_type($id, $state) {
1217     global $DB;
1219     $DB->update_record('lti_types', array('id' => $id, 'state' => $state));
1222 /**
1223  * Transforms a basic LTI object to an array
1224  *
1225  * @param object $ltiobject    Basic LTI object
1226  *
1227  * @return array Basic LTI configuration details
1228  */
1229 function lti_get_config($ltiobject) {
1230     $typeconfig = array();
1231     $typeconfig = (array)$ltiobject;
1232     $additionalconfig = lti_get_type_config($ltiobject->typeid);
1233     $typeconfig = array_merge($typeconfig, $additionalconfig);
1234     return $typeconfig;
1237 /**
1238  *
1239  * Generates some of the tool configuration based on the instance details
1240  *
1241  * @param int $id
1242  *
1243  * @return Instance configuration
1244  *
1245  */
1246 function lti_get_type_config_from_instance($id) {
1247     global $DB;
1249     $instance = $DB->get_record('lti', array('id' => $id));
1250     $config = lti_get_config($instance);
1252     $type = new \stdClass();
1253     $type->lti_fix = $id;
1254     if (isset($config['toolurl'])) {
1255         $type->lti_toolurl = $config['toolurl'];
1256     }
1257     if (isset($config['instructorchoicesendname'])) {
1258         $type->lti_sendname = $config['instructorchoicesendname'];
1259     }
1260     if (isset($config['instructorchoicesendemailaddr'])) {
1261         $type->lti_sendemailaddr = $config['instructorchoicesendemailaddr'];
1262     }
1263     if (isset($config['instructorchoiceacceptgrades'])) {
1264         $type->lti_acceptgrades = $config['instructorchoiceacceptgrades'];
1265     }
1266     if (isset($config['instructorchoiceallowroster'])) {
1267         $type->lti_allowroster = $config['instructorchoiceallowroster'];
1268     }
1270     if (isset($config['instructorcustomparameters'])) {
1271         $type->lti_allowsetting = $config['instructorcustomparameters'];
1272     }
1273     return $type;
1276 /**
1277  * Generates some of the tool configuration based on the admin configuration details
1278  *
1279  * @param int $id
1280  *
1281  * @return Configuration details
1282  */
1283 function lti_get_type_type_config($id) {
1284     global $DB;
1286     $basicltitype = $DB->get_record('lti_types', array('id' => $id));
1287     $config = lti_get_type_config($id);
1289     $type = new \stdClass();
1291     $type->lti_typename = $basicltitype->name;
1293     $type->typeid = $basicltitype->id;
1295     $type->toolproxyid = $basicltitype->toolproxyid;
1297     $type->lti_toolurl = $basicltitype->baseurl;
1299     $type->lti_parameters = $basicltitype->parameter;
1301     $type->lti_icon = $basicltitype->icon;
1303     $type->lti_secureicon = $basicltitype->secureicon;
1305     if (isset($config['resourcekey'])) {
1306         $type->lti_resourcekey = $config['resourcekey'];
1307     }
1308     if (isset($config['password'])) {
1309         $type->lti_password = $config['password'];
1310     }
1312     if (isset($config['sendname'])) {
1313         $type->lti_sendname = $config['sendname'];
1314     }
1315     if (isset($config['instructorchoicesendname'])) {
1316         $type->lti_instructorchoicesendname = $config['instructorchoicesendname'];
1317     }
1318     if (isset($config['sendemailaddr'])) {
1319         $type->lti_sendemailaddr = $config['sendemailaddr'];
1320     }
1321     if (isset($config['instructorchoicesendemailaddr'])) {
1322         $type->lti_instructorchoicesendemailaddr = $config['instructorchoicesendemailaddr'];
1323     }
1324     if (isset($config['acceptgrades'])) {
1325         $type->lti_acceptgrades = $config['acceptgrades'];
1326     }
1327     if (isset($config['instructorchoiceacceptgrades'])) {
1328         $type->lti_instructorchoiceacceptgrades = $config['instructorchoiceacceptgrades'];
1329     }
1330     if (isset($config['allowroster'])) {
1331         $type->lti_allowroster = $config['allowroster'];
1332     }
1333     if (isset($config['instructorchoiceallowroster'])) {
1334         $type->lti_instructorchoiceallowroster = $config['instructorchoiceallowroster'];
1335     }
1337     if (isset($config['customparameters'])) {
1338         $type->lti_customparameters = $config['customparameters'];
1339     }
1341     if (isset($config['forcessl'])) {
1342         $type->lti_forcessl = $config['forcessl'];
1343     }
1345     if (isset($config['organizationid'])) {
1346         $type->lti_organizationid = $config['organizationid'];
1347     }
1348     if (isset($config['organizationurl'])) {
1349         $type->lti_organizationurl = $config['organizationurl'];
1350     }
1351     if (isset($config['organizationdescr'])) {
1352         $type->lti_organizationdescr = $config['organizationdescr'];
1353     }
1354     if (isset($config['launchcontainer'])) {
1355         $type->lti_launchcontainer = $config['launchcontainer'];
1356     }
1358     if (isset($config['coursevisible'])) {
1359         $type->lti_coursevisible = $config['coursevisible'];
1360     }
1362     if (isset($config['debuglaunch'])) {
1363         $type->lti_debuglaunch = $config['debuglaunch'];
1364     }
1366     if (isset($config['module_class_type'])) {
1367         $type->lti_module_class_type = $config['module_class_type'];
1368     }
1370     return $type;
1373 function lti_prepare_type_for_save($type, $config) {
1374     if (isset($config->lti_toolurl)) {
1375         $type->baseurl = $config->lti_toolurl;
1376         $type->tooldomain = lti_get_domain_from_url($config->lti_toolurl);
1377     }
1378     if (isset($config->lti_typename)) {
1379         $type->name = $config->lti_typename;
1380     }
1381     $type->coursevisible = !empty($config->lti_coursevisible) ? $config->lti_coursevisible : 0;
1382     $config->lti_coursevisible = $type->coursevisible;
1384     if (isset($config->lti_icon)) {
1385         $type->icon = $config->lti_icon;
1386     }
1387     if (isset($config->lti_secureicon)) {
1388         $type->secureicon = $config->lti_secureicon;
1389     }
1391     if (isset($config->lti_forcessl)) {
1392         $type->forcessl = !empty($config->lti_forcessl) ? $config->lti_forcessl : 0;
1393         $config->lti_forcessl = $type->forcessl;
1394     }
1396     $type->timemodified = time();
1398     unset ($config->lti_typename);
1399     unset ($config->lti_toolurl);
1400     unset ($config->lti_icon);
1401     unset ($config->lti_secureicon);
1404 function lti_update_type($type, $config) {
1405     global $DB, $CFG;
1407     lti_prepare_type_for_save($type, $config);
1409     $clearcache = false;
1410     if (lti_request_is_using_ssl() && !empty($type->secureicon)) {
1411         $clearcache = !isset($config->oldicon) || ($config->oldicon !== $type->secureicon);
1412     } else {
1413         $clearcache = isset($type->icon) && (!isset($config->oldicon) || ($config->oldicon !== $type->icon));
1414     }
1415     unset($config->oldicon);
1417     if ($DB->update_record('lti_types', $type)) {
1418         foreach ($config as $key => $value) {
1419             if (substr($key, 0, 4) == 'lti_' && !is_null($value)) {
1420                 $record = new \StdClass();
1421                 $record->typeid = $type->id;
1422                 $record->name = substr($key, 4);
1423                 $record->value = $value;
1424                 lti_update_config($record);
1425             }
1426         }
1427         require_once($CFG->libdir.'/modinfolib.php');
1428         if ($clearcache) {
1429             rebuild_course_cache();
1430         }
1431     }
1434 function lti_add_type($type, $config) {
1435     global $USER, $SITE, $DB;
1437     lti_prepare_type_for_save($type, $config);
1439     if (!isset($type->state)) {
1440         $type->state = LTI_TOOL_STATE_PENDING;
1441     }
1443     if (!isset($type->timecreated)) {
1444         $type->timecreated = time();
1445     }
1447     if (!isset($type->createdby)) {
1448         $type->createdby = $USER->id;
1449     }
1451     if (!isset($type->course)) {
1452         $type->course = $SITE->id;
1453     }
1455     // Create a salt value to be used for signing passed data to extension services
1456     // The outcome service uses the service salt on the instance. This can be used
1457     // for communication with services not related to a specific LTI instance.
1458     $config->lti_servicesalt = uniqid('', true);
1460     $id = $DB->insert_record('lti_types', $type);
1462     if ($id) {
1463         foreach ($config as $key => $value) {
1464             if (substr($key, 0, 4) == 'lti_' && !is_null($value)) {
1465                 $record = new \StdClass();
1466                 $record->typeid = $id;
1467                 $record->name = substr($key, 4);
1468                 $record->value = $value;
1470                 lti_add_config($record);
1471             }
1472         }
1473     }
1475     return $id;
1478 /**
1479  * Given an array of tool proxies, filter them based on their state
1480  *
1481  * @param array $toolproxies An array of lti_tool_proxies records
1482  * @param int $state One of the LTI_TOOL_PROXY_STATE_* constants
1483  *
1484  * @return array
1485  */
1486 function lti_filter_tool_proxy_types(array $toolproxies, $state) {
1487     $return = array();
1488     foreach ($toolproxies as $key => $toolproxy) {
1489         if ($toolproxy->state == $state) {
1490             $return[$key] = $toolproxy;
1491         }
1492     }
1493     return $return;
1496 /**
1497  * Get the tool proxy instance given its GUID
1498  *
1499  * @param string  $toolproxyguid   Tool proxy GUID value
1500  *
1501  * @return object
1502  */
1503 function lti_get_tool_proxy_from_guid($toolproxyguid) {
1504     global $DB;
1506     $toolproxy = $DB->get_record('lti_tool_proxies', array('guid' => $toolproxyguid));
1508     return $toolproxy;
1511 /**
1512  * Generates some of the tool proxy configuration based on the admin configuration details
1513  *
1514  * @param int $id
1515  *
1516  * @return Tool Proxy details
1517  */
1518 function lti_get_tool_proxy($id) {
1519     global $DB;
1521     $toolproxy = $DB->get_record('lti_tool_proxies', array('id' => $id));
1522     return $toolproxy;
1525 /**
1526  * Generates some of the tool proxy configuration based on the admin configuration details
1527  *
1528  * @param int $id
1529  *
1530  * @return Tool Proxy details
1531  */
1532 function lti_get_tool_proxy_config($id) {
1533     $toolproxy = lti_get_tool_proxy($id);
1535     $tp = new \stdClass();
1536     $tp->lti_registrationname = $toolproxy->name;
1537     $tp->toolproxyid = $toolproxy->id;
1538     $tp->state = $toolproxy->state;
1539     $tp->lti_registrationurl = $toolproxy->regurl;
1540     $tp->lti_capabilities = explode("\n", $toolproxy->capabilityoffered);
1541     $tp->lti_services = explode("\n", $toolproxy->serviceoffered);
1543     return $tp;
1546 /**
1547  * Update the database with a tool proxy instance
1548  *
1549  * @param object   $config    Tool proxy definition
1550  *
1551  * @return int  Record id number
1552  */
1553 function lti_add_tool_proxy($config) {
1554     global $USER, $DB;
1556     $toolproxy = new \stdClass();
1557     if (isset($config->lti_registrationname)) {
1558         $toolproxy->name = trim($config->lti_registrationname);
1559     }
1560     if (isset($config->lti_registrationurl)) {
1561         $toolproxy->regurl = trim($config->lti_registrationurl);
1562     }
1563     if (isset($config->lti_capabilities)) {
1564         $toolproxy->capabilityoffered = implode("\n", $config->lti_capabilities);
1565     }
1566     if (isset($config->lti_services)) {
1567         $toolproxy->serviceoffered = implode("\n", $config->lti_services);
1568     }
1569     if (isset($config->toolproxyid) && !empty($config->toolproxyid)) {
1570         $toolproxy->id = $config->toolproxyid;
1571         if (!isset($toolproxy->state) || ($toolproxy->state != LTI_TOOL_PROXY_STATE_ACCEPTED)) {
1572             $toolproxy->state = LTI_TOOL_PROXY_STATE_CONFIGURED;
1573             $toolproxy->guid = random_string();
1574             $toolproxy->secret = random_string();
1575         }
1576         $id = lti_update_tool_proxy($toolproxy);
1577     } else {
1578         $toolproxy->state = LTI_TOOL_PROXY_STATE_CONFIGURED;
1579         $toolproxy->timemodified = time();
1580         $toolproxy->timecreated = $toolproxy->timemodified;
1581         if (!isset($toolproxy->createdby)) {
1582             $toolproxy->createdby = $USER->id;
1583         }
1584         $toolproxy->guid = random_string();
1585         $toolproxy->secret = random_string();
1586         $id = $DB->insert_record('lti_tool_proxies', $toolproxy);
1587     }
1589     return $id;
1592 /**
1593  * Updates a tool proxy in the database
1594  *
1595  * @param object  $toolproxy   Tool proxy
1596  *
1597  * @return int    Record id number
1598  */
1599 function lti_update_tool_proxy($toolproxy) {
1600     global $DB;
1602     $toolproxy->timemodified = time();
1603     $id = $DB->update_record('lti_tool_proxies', $toolproxy);
1605     return $id;
1608 /**
1609  * Delete a Tool Proxy
1610  *
1611  * @param int $id   Tool Proxy id
1612  */
1613 function lti_delete_tool_proxy($id) {
1614     global $DB;
1615     $DB->delete_records('lti_tool_settings', array('toolproxyid' => $id));
1616     $tools = $DB->get_records('lti_types', array('toolproxyid' => $id));
1617     foreach ($tools as $tool) {
1618         lti_delete_type($tool->id);
1619     }
1620     $DB->delete_records('lti_tool_proxies', array('id' => $id));
1623 /**
1624  * Add a tool configuration in the database
1625  *
1626  * @param object $config   Tool configuration
1627  *
1628  * @return int Record id number
1629  */
1630 function lti_add_config($config) {
1631     global $DB;
1633     return $DB->insert_record('lti_types_config', $config);
1636 /**
1637  * Updates a tool configuration in the database
1638  *
1639  * @param object  $config   Tool configuration
1640  *
1641  * @return Record id number
1642  */
1643 function lti_update_config($config) {
1644     global $DB;
1646     $return = true;
1647     $old = $DB->get_record('lti_types_config', array('typeid' => $config->typeid, 'name' => $config->name));
1649     if ($old) {
1650         $config->id = $old->id;
1651         $return = $DB->update_record('lti_types_config', $config);
1652     } else {
1653         $return = $DB->insert_record('lti_types_config', $config);
1654     }
1655     return $return;
1658 /**
1659  * Gets the tool settings
1660  *
1661  * @param int  $toolproxyid   Id of tool proxy record
1662  * @param int  $courseid      Id of course (null if system settings)
1663  * @param int  $instanceid    Id of course module (null if system or context settings)
1664  *
1665  * @return array  Array settings
1666  */
1667 function lti_get_tool_settings($toolproxyid, $courseid = null, $instanceid = null) {
1668     global $DB;
1670     $settings = array();
1671     $settingsstr = $DB->get_field('lti_tool_settings', 'settings', array('toolproxyid' => $toolproxyid,
1672         'course' => $courseid, 'coursemoduleid' => $instanceid));
1673     if ($settingsstr !== false) {
1674         $settings = json_decode($settingsstr, true);
1675     }
1676     return $settings;
1679 /**
1680  * Sets the tool settings (
1681  *
1682  * @param array  $settings      Array of settings
1683  * @param int    $toolproxyid   Id of tool proxy record
1684  * @param int    $courseid      Id of course (null if system settings)
1685  * @param int    $instanceid    Id of course module (null if system or context settings)
1686  */
1687 function lti_set_tool_settings($settings, $toolproxyid, $courseid = null, $instanceid = null) {
1688     global $DB;
1690     $json = json_encode($settings);
1691     $record = $DB->get_record('lti_tool_settings', array('toolproxyid' => $toolproxyid,
1692         'course' => $courseid, 'coursemoduleid' => $instanceid));
1693     if ($record !== false) {
1694         $DB->update_record('lti_tool_settings', array('id' => $record->id, 'settings' => $json, 'timemodified' => time()));
1695     } else {
1696         $record = new \stdClass();
1697         $record->toolproxyid = $toolproxyid;
1698         $record->course = $courseid;
1699         $record->coursemoduleid = $instanceid;
1700         $record->settings = $json;
1701         $record->timecreated = time();
1702         $record->timemodified = $record->timecreated;
1703         $DB->insert_record('lti_tool_settings', $record);
1704     }
1707 /**
1708  * Signs the petition to launch the external tool using OAuth
1709  *
1710  * @param $oldparms     Parameters to be passed for signing
1711  * @param $endpoint     url of the external tool
1712  * @param $method       Method for sending the parameters (e.g. POST)
1713  * @param $oauth_consumoer_key          Key
1714  * @param $oauth_consumoer_secret       Secret
1715  */
1716 function lti_sign_parameters($oldparms, $endpoint, $method, $oauthconsumerkey, $oauthconsumersecret) {
1718     $parms = $oldparms;
1720     $testtoken = '';
1722     // TODO: Switch to core oauthlib once implemented - MDL-30149.
1723     $hmacmethod = new lti\OAuthSignatureMethod_HMAC_SHA1();
1724     $testconsumer = new lti\OAuthConsumer($oauthconsumerkey, $oauthconsumersecret, null);
1725     $accreq = lti\OAuthRequest::from_consumer_and_token($testconsumer, $testtoken, $method, $endpoint, $parms);
1726     $accreq->sign_request($hmacmethod, $testconsumer, $testtoken);
1728     $newparms = $accreq->get_parameters();
1730     return $newparms;
1733 /**
1734  * Posts the launch petition HTML
1735  *
1736  * @param $newparms     Signed parameters
1737  * @param $endpoint     URL of the external tool
1738  * @param $debug        Debug (true/false)
1739  */
1740 function lti_post_launch_html($newparms, $endpoint, $debug=false) {
1741     $r = "<form action=\"" . $endpoint .
1742         "\" name=\"ltiLaunchForm\" id=\"ltiLaunchForm\" method=\"post\" encType=\"application/x-www-form-urlencoded\">\n";
1744     // Contruct html for the launch parameters.
1745     foreach ($newparms as $key => $value) {
1746         $key = htmlspecialchars($key);
1747         $value = htmlspecialchars($value);
1748         if ( $key == "ext_submit" ) {
1749             $r .= "<input type=\"submit\"";
1750         } else {
1751             $r .= "<input type=\"hidden\" name=\"{$key}\"";
1752         }
1753         $r .= " value=\"";
1754         $r .= $value;
1755         $r .= "\"/>\n";
1756     }
1758     if ( $debug ) {
1759         $r .= "<script language=\"javascript\"> \n";
1760         $r .= "  //<![CDATA[ \n";
1761         $r .= "function basicltiDebugToggle() {\n";
1762         $r .= "    var ele = document.getElementById(\"basicltiDebug\");\n";
1763         $r .= "    if (ele.style.display == \"block\") {\n";
1764         $r .= "        ele.style.display = \"none\";\n";
1765         $r .= "    }\n";
1766         $r .= "    else {\n";
1767         $r .= "        ele.style.display = \"block\";\n";
1768         $r .= "    }\n";
1769         $r .= "} \n";
1770         $r .= "  //]]> \n";
1771         $r .= "</script>\n";
1772         $r .= "<a id=\"displayText\" href=\"javascript:basicltiDebugToggle();\">";
1773         $r .= get_string("toggle_debug_data", "lti")."</a>\n";
1774         $r .= "<div id=\"basicltiDebug\" style=\"display:none\">\n";
1775         $r .= "<b>".get_string("basiclti_endpoint", "lti")."</b><br/>\n";
1776         $r .= $endpoint . "<br/>\n&nbsp;<br/>\n";
1777         $r .= "<b>".get_string("basiclti_parameters", "lti")."</b><br/>\n";
1778         foreach ($newparms as $key => $value) {
1779             $key = htmlspecialchars($key);
1780             $value = htmlspecialchars($value);
1781             $r .= "$key = $value<br/>\n";
1782         }
1783         $r .= "&nbsp;<br/>\n";
1784         $r .= "</div>\n";
1785     }
1786     $r .= "</form>\n";
1788     if ( ! $debug ) {
1789         $r .= " <script type=\"text/javascript\"> \n" .
1790             "  //<![CDATA[ \n" .
1791             "    document.ltiLaunchForm.submit(); \n" .
1792             "  //]]> \n" .
1793             " </script> \n";
1794     }
1795     return $r;
1798 function lti_get_type($typeid) {
1799     global $DB;
1801     return $DB->get_record('lti_types', array('id' => $typeid));
1804 function lti_get_launch_container($lti, $toolconfig) {
1805     if (empty($lti->launchcontainer)) {
1806         $lti->launchcontainer = LTI_LAUNCH_CONTAINER_DEFAULT;
1807     }
1809     if ($lti->launchcontainer == LTI_LAUNCH_CONTAINER_DEFAULT) {
1810         if (isset($toolconfig['launchcontainer'])) {
1811             $launchcontainer = $toolconfig['launchcontainer'];
1812         }
1813     } else {
1814         $launchcontainer = $lti->launchcontainer;
1815     }
1817     if (empty($launchcontainer) || $launchcontainer == LTI_LAUNCH_CONTAINER_DEFAULT) {
1818         $launchcontainer = LTI_LAUNCH_CONTAINER_EMBED_NO_BLOCKS;
1819     }
1821     $devicetype = core_useragent::get_device_type();
1823     // Scrolling within the object element doesn't work on iOS or Android
1824     // Opening the popup window also had some issues in testing
1825     // For mobile devices, always take up the entire screen to ensure the best experience.
1826     if ($devicetype === core_useragent::DEVICETYPE_MOBILE || $devicetype === core_useragent::DEVICETYPE_TABLET ) {
1827         $launchcontainer = LTI_LAUNCH_CONTAINER_REPLACE_MOODLE_WINDOW;
1828     }
1830     return $launchcontainer;
1833 function lti_request_is_using_ssl() {
1834     global $CFG;
1835     return (stripos($CFG->httpswwwroot, 'https://') === 0);
1838 function lti_ensure_url_is_https($url) {
1839     if (!strstr($url, '://')) {
1840         $url = 'https://' . $url;
1841     } else {
1842         // If the URL starts with http, replace with https.
1843         if (stripos($url, 'http://') === 0) {
1844             $url = 'https://' . substr($url, 7);
1845         }
1846     }
1848     return $url;
1851 /**
1852  * Determines if we should try to log the request
1853  *
1854  * @param string $rawbody
1855  * @return bool
1856  */
1857 function lti_should_log_request($rawbody) {
1858     global $CFG;
1860     if (empty($CFG->mod_lti_log_users)) {
1861         return false;
1862     }
1864     $logusers = explode(',', $CFG->mod_lti_log_users);
1865     if (empty($logusers)) {
1866         return false;
1867     }
1869     try {
1870         $xml = new \SimpleXMLElement($rawbody);
1871         $ns  = $xml->getNamespaces();
1872         $ns  = array_shift($ns);
1873         $xml->registerXPathNamespace('lti', $ns);
1874         $requestuserid = '';
1875         if ($node = $xml->xpath('//lti:userId')) {
1876             $node = $node[0];
1877             $requestuserid = clean_param((string) $node, PARAM_INT);
1878         } else if ($node = $xml->xpath('//lti:sourcedId')) {
1879             $node = $node[0];
1880             $resultjson = json_decode((string) $node);
1881             $requestuserid = clean_param($resultjson->data->userid, PARAM_INT);
1882         }
1883     } catch (Exception $e) {
1884         return false;
1885     }
1887     if (empty($requestuserid) or !in_array($requestuserid, $logusers)) {
1888         return false;
1889     }
1891     return true;
1894 /**
1895  * Logs the request to a file in temp dir
1896  *
1897  * @param string $rawbody
1898  */
1899 function lti_log_request($rawbody) {
1900     if ($tempdir = make_temp_directory('mod_lti', false)) {
1901         if ($tempfile = tempnam($tempdir, 'mod_lti_request'.date('YmdHis'))) {
1902             file_put_contents($tempfile, $rawbody);
1903             chmod($tempfile, 0644);
1904         }
1905     }
1908 /**
1909  * Fetches LTI type configuration for an LTI instance
1910  *
1911  * @param stdClass $instance
1912  * @return array Can be empty if no type is found
1913  */
1914 function lti_get_type_config_by_instance($instance) {
1915     $typeid = null;
1916     if (empty($instance->typeid)) {
1917         $tool = lti_get_tool_by_url_match($instance->toolurl, $instance->course);
1918         if ($tool) {
1919             $typeid = $tool->id;
1920         }
1921     } else {
1922         $typeid = $instance->typeid;
1923     }
1924     if (!empty($typeid)) {
1925         return lti_get_type_config($typeid);
1926     }
1927     return array();
1930 /**
1931  * Enforce type config settings onto the LTI instance
1932  *
1933  * @param stdClass $instance
1934  * @param array $typeconfig
1935  */
1936 function lti_force_type_config_settings($instance, array $typeconfig) {
1937     $forced = array(
1938         'instructorchoicesendname'      => 'sendname',
1939         'instructorchoicesendemailaddr' => 'sendemailaddr',
1940         'instructorchoiceacceptgrades'  => 'acceptgrades',
1941     );
1943     foreach ($forced as $instanceparam => $typeconfigparam) {
1944         if (array_key_exists($typeconfigparam, $typeconfig) && $typeconfig[$typeconfigparam] != LTI_SETTING_DELEGATE) {
1945             $instance->$instanceparam = $typeconfig[$typeconfigparam];
1946         }
1947     }
1950 /**
1951  * Initializes an array with the capabilities supported by the LTI module
1952  *
1953  * @return array List of capability names (without a dollar sign prefix)
1954  */
1955 function lti_get_capabilities() {
1957     $capabilities = array(
1958        'basic-lti-launch-request' => '',
1959        'Context.id' => 'context_id',
1960        'CourseSection.title' => 'context_title',
1961        'CourseSection.label' => 'context_label',
1962        'CourseSection.sourcedId' => 'lis_course_section_sourcedid',
1963        'CourseSection.longDescription' => '$COURSE->summary',
1964        'CourseSection.timeFrame.begin' => '$COURSE->startdate',
1965        'ResourceLink.id' => 'resource_link_id',
1966        'ResourceLink.title' => 'resource_link_title',
1967        'ResourceLink.description' => 'resource_link_description',
1968        'User.id' => 'user_id',
1969        'User.username' => '$USER->username',
1970        'Person.name.full' => 'lis_person_name_full',
1971        'Person.name.given' => 'lis_person_name_given',
1972        'Person.name.family' => 'lis_person_name_family',
1973        'Person.email.primary' => 'lis_person_contact_email_primary',
1974        'Person.sourcedId' => 'lis_person_sourcedid',
1975        'Person.name.middle' => '$USER->middlename',
1976        'Person.address.street1' => '$USER->address',
1977        'Person.address.locality' => '$USER->city',
1978        'Person.address.country' => '$USER->country',
1979        'Person.address.timezone' => '$USER->timezone',
1980        'Person.phone.primary' => '$USER->phone1',
1981        'Person.phone.mobile' => '$USER->phone2',
1982        'Person.webaddress' => '$USER->url',
1983        'Membership.role' => 'roles',
1984        'Result.sourcedId' => 'lis_result_sourcedid',
1985        'Result.autocreate' => 'lis_outcome_service_url');
1987     return $capabilities;
1991 /**
1992  * Initializes an array with the services supported by the LTI module
1993  *
1994  * @return array List of services
1995  */
1996 function lti_get_services() {
1998     $services = array();
1999     $definedservices = core_component::get_plugin_list('ltiservice');
2000     foreach ($definedservices as $name => $location) {
2001         $classname = "\\ltiservice_{$name}\\local\\service\\{$name}";
2002         $services[] = new $classname();
2003     }
2005     return $services;
2009 /**
2010  * Initializes an instance of the named service
2011  *
2012  * @param string $servicename Name of service
2013  *
2014  * @return mod_lti\local\ltiservice\service_base Service
2015  */
2016 function lti_get_service_by_name($servicename) {
2018     $service = false;
2019     $classname = "\\ltiservice_{$servicename}\\local\\service\\{$servicename}";
2020     if (class_exists($classname)) {
2021         $service = new $classname();
2022     }
2024     return $service;
2028 /**
2029  * Finds a service by id
2030  *
2031  * @param array  $services    Array of services
2032  * @param string $resourceid  ID of resource
2033  *
2034  * @return mod_lti\local\ltiservice\service_base Service
2035  */
2036 function lti_get_service_by_resource_id($services, $resourceid) {
2038     $service = false;
2039     foreach ($services as $aservice) {
2040         foreach ($aservice->get_resources() as $resource) {
2041             if ($resource->get_id() === $resourceid) {
2042                 $service = $aservice;
2043                 break 2;
2044             }
2045         }
2046     }
2048     return $service;
2052 /**
2053  * Extracts the named contexts from a tool proxy
2054  *
2055  * @param object $json
2056  *
2057  * @return array Contexts
2058  */
2059 function lti_get_contexts($json) {
2061     $contexts = array();
2062     if (isset($json->{'@context'})) {
2063         foreach ($json->{'@context'} as $context) {
2064             if (is_object($context)) {
2065                 $contexts = array_merge(get_object_vars($context), $contexts);
2066             }
2067         }
2068     }
2070     return $contexts;
2074 /**
2075  * Converts an ID to a fully-qualified ID
2076  *
2077  * @param array $contexts
2078  * @param string $id
2079  *
2080  * @return string Fully-qualified ID
2081  */
2082 function lti_get_fqid($contexts, $id) {
2084     $parts = explode(':', $id, 2);
2085     if (count($parts) > 1) {
2086         if (array_key_exists($parts[0], $contexts)) {
2087             $id = $contexts[$parts[0]] . $parts[1];
2088         }
2089     }
2091     return $id;