MDL-47113 lti: Add link to open in new window, when popup blocked
[moodle.git] / mod / lti / lib.php
CommitLineData
aa6eca66 1<?php
61eb12d4
CS
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//
aa6eca66
CS
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
e3f69b58 33// Contact info: Marc Alier Forment granludo @ gmail.com or marc.alier @ upc.edu.
aa6eca66
CS
34
35/**
61eb12d4 36 * This file contains a library of functions and constants for the lti module
aa6eca66 37 *
2b17ec3d 38 * @package mod_lti
61eb12d4 39 * @copyright 2009 Marc Alier, Jordi Piguillem, Nikolas Galanis
aa6eca66 40 * marc.alier@upc.edu
61eb12d4
CS
41 * @copyright 2009 Universitat Politecnica de Catalunya http://www.upc.edu
42 * @author Marc Alier
43 * @author Jordi Piguillem
44 * @author Nikolas Galanis
8f45215d 45 * @author Chris Scribner
61eb12d4 46 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
aa6eca66
CS
47 */
48
49defined('MOODLE_INTERNAL') || die;
50
06ca6cc9
TH
51/**
52 * Returns all other caps used in module.
53 *
54 * @return array
55 */
56function lti_get_extra_capabilities() {
57 return array('moodle/site:accessallgroups');
58}
59
aa6eca66
CS
60/**
61 * List of features supported in URL module
62 * @param string $feature FEATURE_xx constant for requested feature
63 * @return mixed True if module supports feature, false if not, null if doesn't know
64 */
65function lti_supports($feature) {
e3f69b58 66 switch ($feature) {
67 case FEATURE_GROUPS:
68 case FEATURE_GROUPINGS:
69 return false;
70 case FEATURE_MOD_INTRO:
71 case FEATURE_COMPLETION_TRACKS_VIEWS:
72 case FEATURE_GRADE_HAS_GRADE:
73 case FEATURE_GRADE_OUTCOMES:
74 case FEATURE_BACKUP_MOODLE2:
75 case FEATURE_SHOW_DESCRIPTION:
76 return true;
77
78 default:
79 return null;
aa6eca66
CS
80 }
81}
82
83/**
84 * Given an object containing all the necessary data,
85 * (defined by the form in mod.html) this function
86 * will create a new instance and return the id number
87 * of the new instance.
88 *
89 * @param object $instance An object from the form in mod.html
90 * @return int The id of the newly inserted basiclti record
91 **/
c69bd1af 92function lti_add_instance($lti, $mform) {
42a2c7f1
CS
93 global $DB, $CFG;
94 require_once($CFG->dirroot.'/mod/lti/locallib.php');
e27cb316 95
e3f69b58 96 if (!isset($lti->toolurl)) {
97 $lti->toolurl = '';
98 }
99
8aec804a
JO
100 lti_load_tool_if_cartridge($lti);
101
c69bd1af
EL
102 $lti->timecreated = time();
103 $lti->timemodified = $lti->timecreated;
104 $lti->servicesalt = uniqid('', true);
e27cb316 105
8fa50fdd
MN
106 lti_force_type_config_settings($lti, lti_get_type_config_by_instance($lti));
107
5582fe49 108 if (empty($lti->typeid) && isset($lti->urlmatchedtypeid)) {
ea5d0515
AF
109 $lti->typeid = $lti->urlmatchedtypeid;
110 }
111
8fa50fdd
MN
112 if (!isset($lti->instructorchoiceacceptgrades) || $lti->instructorchoiceacceptgrades != LTI_SETTING_ALWAYS) {
113 // The instance does not accept grades back from the provider, so set to "No grade" value 0.
114 $lti->grade = 0;
c69bd1af 115 }
aa6eca66 116
c69bd1af 117 $lti->id = $DB->insert_record('lti', $lti);
e27cb316 118
8fa50fdd 119 if (isset($lti->instructorchoiceacceptgrades) && $lti->instructorchoiceacceptgrades == LTI_SETTING_ALWAYS) {
c69bd1af
EL
120 if (!isset($lti->cmidnumber)) {
121 $lti->cmidnumber = '';
32c079dc 122 }
e27cb316 123
c69bd1af 124 lti_grade_item_update($lti);
aa6eca66
CS
125 }
126
c69bd1af 127 return $lti->id;
aa6eca66
CS
128}
129
130/**
131 * Given an object containing all the necessary data,
132 * (defined by the form in mod.html) this function
133 * will update an existing instance with new data.
134 *
135 * @param object $instance An object from the form in mod.html
136 * @return boolean Success/Fail
137 **/
c69bd1af 138function lti_update_instance($lti, $mform) {
42a2c7f1
CS
139 global $DB, $CFG;
140 require_once($CFG->dirroot.'/mod/lti/locallib.php');
aa6eca66 141
8aec804a
JO
142 lti_load_tool_if_cartridge($lti);
143
c69bd1af
EL
144 $lti->timemodified = time();
145 $lti->id = $lti->instance;
aa6eca66 146
b07878ec
CS
147 if (!isset($lti->showtitlelaunch)) {
148 $lti->showtitlelaunch = 0;
aa6eca66 149 }
e27cb316 150
b07878ec
CS
151 if (!isset($lti->showdescriptionlaunch)) {
152 $lti->showdescriptionlaunch = 0;
aa6eca66 153 }
e27cb316 154
8fa50fdd 155 lti_force_type_config_settings($lti, lti_get_type_config_by_instance($lti));
e27cb316 156
8fa50fdd 157 if (isset($lti->instructorchoiceacceptgrades) && $lti->instructorchoiceacceptgrades == LTI_SETTING_ALWAYS) {
c69bd1af 158 lti_grade_item_update($lti);
aa6eca66 159 } else {
8fa50fdd
MN
160 // Instance is no longer accepting grades from Provider, set grade to "No grade" value 0.
161 $lti->grade = 0;
162 $lti->instructorchoiceacceptgrades = 0;
163
c69bd1af 164 lti_grade_item_delete($lti);
aa6eca66
CS
165 }
166
ea5d0515
AF
167 if ($lti->typeid == 0 && isset($lti->urlmatchedtypeid)) {
168 $lti->typeid = $lti->urlmatchedtypeid;
169 }
170
c69bd1af 171 return $DB->update_record('lti', $lti);
aa6eca66
CS
172}
173
174/**
175 * Given an ID of an instance of this module,
176 * this function will permanently delete the instance
177 * and any data that depends on it.
178 *
179 * @param int $id Id of the module instance
180 * @return boolean Success/Failure
181 **/
182function lti_delete_instance($id) {
183 global $DB;
184
185 if (! $basiclti = $DB->get_record("lti", array("id" => $id))) {
186 return false;
187 }
188
189 $result = true;
190
e3f69b58 191 // Delete any dependent records here.
aa6eca66
CS
192 lti_grade_item_delete($basiclti);
193
e3f69b58 194 $ltitype = $DB->get_record('lti_types', array('id' => $basiclti->typeid));
496bf3ea
DM
195 if ($ltitype) {
196 $DB->delete_records('lti_tool_settings',
197 array('toolproxyid' => $ltitype->toolproxyid, 'course' => $basiclti->course, 'coursemoduleid' => $id));
198 }
e3f69b58 199
aa6eca66
CS
200 return $DB->delete_records("lti", array("id" => $basiclti->id));
201}
202
01e8bfd7
JO
203/**
204 * Return aliases of this activity. LTI should have an alias for each configured tool type
2348c137 205 * This is so you can add an external tool types directly to the activity chooser
01e8bfd7 206 *
2348c137
MG
207 * @param stdClass $defaultitem default item that would be added to the activity chooser if this callback was not present.
208 * It has properties: archetype, name, title, help, icon, link
f418d899
JD
209 * @return array An array of aliases for this activity. Each element is an object with same list of properties as $defaultitem,
210 * plus an additional property, helplink.
2348c137 211 * Properties title and link are required
01e8bfd7 212 **/
2348c137 213function lti_get_shortcuts($defaultitem) {
01e8bfd7
JO
214 global $CFG, $COURSE;
215 require_once($CFG->dirroot.'/mod/lti/locallib.php');
216
2348c137
MG
217 $types = lti_get_configured_types($COURSE->id, $defaultitem->link->param('sr'));
218 $types[] = $defaultitem;
219
220 // Add items defined in ltisource plugins.
221 foreach (core_component::get_plugin_list('ltisource') as $pluginname => $dir) {
222 if ($moretypes = component_callback("ltisource_$pluginname", 'get_types')) {
223 // Callback 'get_types()' in 'ltisource' plugins is deprecated in 3.1 and will be removed in 3.5, TODO MDL-53697.
224 debugging('Deprecated callback get_types() is found in ltisource_' . $pluginname .
225 ', use get_shortcuts() instead', DEBUG_DEVELOPER);
226 $grouptitle = get_string('modulenameplural', 'mod_lti');
227 foreach ($moretypes as $subtype) {
228 // Instead of adding subitems combine the name of the group with the name of the subtype.
229 $subtype->title = get_string('activitytypetitle', '',
230 (object)['activity' => $grouptitle, 'type' => $subtype->typestr]);
231 // Re-implement the logic of get_module_metadata() in Moodle 3.0 and below for converting
232 // subtypes into items in activity chooser.
233 $subtype->type = str_replace('&amp;', '&', $subtype->type);
234 $subtype->name = preg_replace('/.*type=/', '', $subtype->type);
235 $subtype->link = new moodle_url($defaultitem->link, array('type' => $subtype->name));
236 if (empty($subtype->help) && !empty($subtype->name) &&
237 get_string_manager()->string_exists('help' . $subtype->name, $pluginname)) {
238 $subtype->help = get_string('help' . $subtype->name, $pluginname);
239 }
240 unset($subtype->typestr);
241 $types[] = $subtype;
242 }
243 }
244 // LTISOURCE plugins can also implement callback get_shortcuts() to add items to the activity chooser.
245 // The return values are the same as of the 'mod' callbacks except that $defaultitem is only passed for reference and
246 // should not be added to the return value.
247 if ($moretypes = component_callback("ltisource_$pluginname", 'get_shortcuts', array($defaultitem))) {
248 $types = array_merge($types, $moretypes);
976b5bca
CS
249 }
250 }
251 return $types;
252}
253
6c64e8ac
EL
254/**
255 * Given a coursemodule object, this function returns the extra
256 * information needed to print this activity in various places.
257 * For this module we just need to support external urls as
258 * activity icons
259 *
3de55d24 260 * @param stdClass $coursemodule
6c64e8ac
EL
261 * @return cached_cm_info info
262 */
ea04a9f9 263function lti_get_coursemodule_info($coursemodule) {
42a2c7f1
CS
264 global $DB, $CFG;
265 require_once($CFG->dirroot.'/mod/lti/locallib.php');
e27cb316 266
6c64e8ac 267 if (!$lti = $DB->get_record('lti', array('id' => $coursemodule->instance),
3f358828 268 'icon, secureicon, intro, introformat, name, typeid, toolurl, launchcontainer')) {
6c64e8ac
EL
269 return null;
270 }
c07aec16 271
6c64e8ac 272 $info = new cached_cm_info();
e27cb316 273
b07878ec
CS
274 if ($coursemodule->showdescription) {
275 // Convert intro to html. Do not filter cached version, filters run at display time.
276 $info->content = format_module_intro('lti', $lti, $coursemodule->id, false);
277 }
e27cb316 278
3f358828 279 if (!empty($lti->typeid)) {
280 $toolconfig = lti_get_type_config($lti->typeid);
281 } else if ($tool = lti_get_tool_by_url_match($lti->toolurl)) {
3de55d24
TH
282 $toolconfig = lti_get_type_config($tool->id);
283 } else {
284 $toolconfig = array();
285 }
3f358828 286
287 // We want to use the right icon based on whether the
288 // current page is being requested over http or https.
289 if (lti_request_is_using_ssl() &&
290 (!empty($lti->secureicon) || (isset($toolconfig['secureicon']) && !empty($toolconfig['secureicon'])))) {
291 if (!empty($lti->secureicon)) {
292 $info->iconurl = new moodle_url($lti->secureicon);
293 } else {
294 $info->iconurl = new moodle_url($toolconfig['secureicon']);
295 }
296 } else if (!empty($lti->icon)) {
297 $info->iconurl = new moodle_url($lti->icon);
298 } else if (isset($toolconfig['icon']) && !empty($toolconfig['icon'])) {
299 $info->iconurl = new moodle_url($toolconfig['icon']);
300 }
301
302 // Does the link open in a new window?
3de55d24
TH
303 $launchcontainer = lti_get_launch_container($lti, $toolconfig);
304 if ($launchcontainer == LTI_LAUNCH_CONTAINER_WINDOW) {
305 $launchurl = new moodle_url('/mod/lti/launch.php', array('id' => $coursemodule->id));
b346737e 306 $info->onclick = "window.open('" . $launchurl->out(false) . "', 'lti-".$coursemodule->id."'); return false;";
3de55d24
TH
307 }
308
b07878ec 309 $info->name = $lti->name;
194f2c60 310
c07aec16
CS
311 return $info;
312}
313
aa6eca66
CS
314/**
315 * Return a small object with summary information about what a
316 * user has done with a given particular instance of this module
317 * Used for user activity reports.
318 * $return->time = the time they did it
319 * $return->info = a short text description
320 *
321 * @return null
322 * @TODO: implement this moodle function (if needed)
323 **/
324function lti_user_outline($course, $user, $mod, $basiclti) {
64ce589b 325 return null;
aa6eca66
CS
326}
327
328/**
329 * Print a detailed representation of what a user has done with
330 * a given particular instance of this module, for user activity reports.
331 *
332 * @return boolean
333 * @TODO: implement this moodle function (if needed)
334 **/
335function lti_user_complete($course, $user, $mod, $basiclti) {
336 return true;
337}
338
339/**
340 * Given a course and a time, this module should find recent activity
341 * that has occurred in basiclti activities and print it out.
342 * Return true if there was output, or false is there was none.
343 *
344 * @uses $CFG
345 * @return boolean
346 * @TODO: implement this moodle function
347 **/
348function lti_print_recent_activity($course, $isteacher, $timestart) {
e3f69b58 349 return false; // True if anything was printed, otherwise false.
aa6eca66
CS
350}
351
352/**
353 * Function to be run periodically according to the moodle cron
354 * This function searches for things that need to be done, such
355 * as sending out mail, toggling flags etc ...
356 *
357 * @uses $CFG
358 * @return boolean
359 **/
360function lti_cron () {
361 return true;
362}
363
364/**
365 * Must return an array of grades for a given instance of this module,
366 * indexed by user. It also returns a maximum allowed grade.
367 *
368 * Example:
369 * $return->grades = array of grades;
370 * $return->maxgrade = maximum allowed grade;
371 *
372 * return $return;
373 *
374 * @param int $basicltiid ID of an instance of this module
375 * @return mixed Null or object with an array of grades and with the maximum grade
376 *
377 * @TODO: implement this moodle function (if needed)
378 **/
379function lti_grades($basicltiid) {
380 return null;
381}
382
aa6eca66
CS
383/**
384 * This function returns if a scale is being used by one basiclti
385 * it it has support for grading and scales. Commented code should be
386 * modified if necessary. See forum, glossary or journal modules
387 * as reference.
388 *
389 * @param int $basicltiid ID of an instance of this module
390 * @return mixed
391 *
392 * @TODO: implement this moodle function (if needed)
393 **/
394function lti_scale_used ($basicltiid, $scaleid) {
395 $return = false;
396
e3f69b58 397 // $rec = get_record("basiclti","id","$basicltiid","scale","-$scaleid");
aa6eca66 398 //
e3f69b58 399 // if (!empty($rec) && !empty($scaleid)) {
400 // $return = true;
401 // }
aa6eca66
CS
402
403 return $return;
404}
405
406/**
407 * Checks if scale is being used by any instance of basiclti.
408 * This function was added in 1.9
409 *
410 * This is used to find out if scale used anywhere
411 * @param $scaleid int
412 * @return boolean True if the scale is used by any basiclti
413 *
414 */
415function lti_scale_used_anywhere($scaleid) {
416 global $DB;
417
418 if ($scaleid and $DB->record_exists('lti', array('grade' => -$scaleid))) {
419 return true;
420 } else {
421 return false;
422 }
423}
424
425/**
426 * Execute post-install custom actions for the module
427 * This function was added in 1.9
428 *
429 * @return boolean true if success, false on error
430 */
431function lti_install() {
432 return true;
433}
434
435/**
436 * Execute post-uninstall custom actions for the module
437 * This function was added in 1.9
438 *
439 * @return boolean true if success, false on error
440 */
441function lti_uninstall() {
442 return true;
443}
444
445/**
446 * Returns available Basic LTI types
447 *
448 * @return array of basicLTI types
449 */
450function lti_get_lti_types() {
451 global $DB;
452
cc193e0d
RW
453 return $DB->get_records('lti_types', null, 'state DESC, timemodified DESC');
454}
455
456/**
457 * Returns available Basic LTI types that match the given
458 * tool proxy id
459 *
af9d3a92 460 * @param int $toolproxyid Tool proxy id
cc193e0d
RW
461 * @return array of basicLTI types
462 */
463function lti_get_lti_types_from_proxy_id($toolproxyid) {
464 global $DB;
465
466 return $DB->get_records('lti_types', array('toolproxyid' => $toolproxyid), 'state DESC, timemodified DESC');
aa6eca66
CS
467}
468
aa6eca66
CS
469/**
470 * Create grade item for given basiclti
471 *
a153c9f2 472 * @category grade
aa6eca66
CS
473 * @param object $basiclti object with extra cmidnumber
474 * @param mixed optional array/object of grade(s); 'reset' means reset grades in gradebook
475 * @return int 0 if ok, error code otherwise
476 */
e3f69b58 477function lti_grade_item_update($basiclti, $grades = null) {
aa6eca66
CS
478 global $CFG;
479 require_once($CFG->libdir.'/gradelib.php');
480
e3f69b58 481 $params = array('itemname' => $basiclti->name, 'idnumber' => $basiclti->cmidnumber);
aa6eca66
CS
482
483 if ($basiclti->grade > 0) {
484 $params['gradetype'] = GRADE_TYPE_VALUE;
485 $params['grademax'] = $basiclti->grade;
486 $params['grademin'] = 0;
487
488 } else if ($basiclti->grade < 0) {
489 $params['gradetype'] = GRADE_TYPE_SCALE;
490 $params['scaleid'] = -$basiclti->grade;
491
492 } else {
e3f69b58 493 $params['gradetype'] = GRADE_TYPE_TEXT; // Allow text comments only.
aa6eca66
CS
494 }
495
e3f69b58 496 if ($grades === 'reset') {
aa6eca66
CS
497 $params['reset'] = true;
498 $grades = null;
499 }
500
501 return grade_update('mod/lti', $basiclti->course, 'mod', 'lti', $basiclti->id, 0, $grades, $params);
502}
503
504/**
505 * Delete grade item for given basiclti
506 *
a153c9f2 507 * @category grade
aa6eca66
CS
508 * @param object $basiclti object
509 * @return object basiclti
510 */
511function lti_grade_item_delete($basiclti) {
512 global $CFG;
513 require_once($CFG->libdir.'/gradelib.php');
514
e3f69b58 515 return grade_update('mod/lti', $basiclti->course, 'mod', 'lti', $basiclti->id, 0, null, array('deleted' => 1));
aa6eca66
CS
516}
517
8fa50fdd
MN
518/**
519 * Log post actions
520 *
521 * @return array
522 */
523function lti_get_post_actions() {
524 return array();
525}
526
527/**
528 * Log view actions
529 *
530 * @return array
531 */
532function lti_get_view_actions() {
533 return array('view all', 'view');
534}
4bed1682
JL
535
536/**
537 * Mark the activity completed (if required) and trigger the course_module_viewed event.
538 *
539 * @param stdClass $lti lti object
540 * @param stdClass $course course object
541 * @param stdClass $cm course module object
542 * @param stdClass $context context object
543 * @since Moodle 3.0
544 */
545function lti_view($lti, $course, $cm, $context) {
546
547 // Trigger course_module_viewed event.
548 $params = array(
549 'context' => $context,
550 'objectid' => $lti->id
551 );
552
553 $event = \mod_lti\event\course_module_viewed::create($params);
554 $event->add_record_snapshot('course_modules', $cm);
555 $event->add_record_snapshot('course', $course);
556 $event->add_record_snapshot('lti', $lti);
557 $event->trigger();
558
559 // Completion.
560 $completion = new completion_info($course);
561 $completion->set_module_viewed($cm);
562}