Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.0.x will end 8 May 2023 (12 months).
  • Bug fixes for security issues in 4.0.x will end 13 November 2023 (18 months).
  • PHP version: minimum PHP 7.3.0 Note: the minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is also supported.
/mod/lti/ -> lib.php (source)

Differences Between: [Versions 310 and 400] [Versions 311 and 400] [Versions 39 and 400] [Versions 400 and 401] [Versions 400 and 402] [Versions 400 and 403]

   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.
  34  
  35  /**
  36   * This file contains a 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   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  47   */
  48  
  49  defined('MOODLE_INTERNAL') || die;
  50  
  51  /**
  52   * List of features supported in URL module
  53   * @param string $feature FEATURE_xx constant for requested feature
  54   * @return mixed True if module supports feature, false if not, null if doesn't know or string for the module purpose.
  55   */
  56  function lti_supports($feature) {
  57      switch ($feature) {
  58          case FEATURE_GROUPS:
  59          case FEATURE_GROUPINGS:
  60              return false;
  61          case FEATURE_MOD_INTRO:
  62          case FEATURE_COMPLETION_TRACKS_VIEWS:
  63          case FEATURE_GRADE_HAS_GRADE:
  64          case FEATURE_GRADE_OUTCOMES:
  65          case FEATURE_BACKUP_MOODLE2:
  66          case FEATURE_SHOW_DESCRIPTION:
  67              return true;
  68          case FEATURE_MOD_PURPOSE:
  69              return MOD_PURPOSE_CONTENT;
  70  
  71          default:
  72              return null;
  73      }
  74  }
  75  
  76  /**
  77   * Given an object containing all the necessary data,
  78   * (defined by the form in mod.html) this function
  79   * will create a new instance and return the id number
  80   * of the new instance.
  81   *
  82   * @param object $instance An object from the form in mod.html
  83   * @return int The id of the newly inserted basiclti record
  84   **/
  85  function lti_add_instance($lti, $mform) {
  86      global $DB, $CFG;
  87      require_once($CFG->dirroot.'/mod/lti/locallib.php');
  88  
  89      if (!isset($lti->toolurl)) {
  90          $lti->toolurl = '';
  91      }
  92  
  93      lti_load_tool_if_cartridge($lti);
  94  
  95      $lti->timecreated = time();
  96      $lti->timemodified = $lti->timecreated;
  97      $lti->servicesalt = uniqid('', true);
  98      if (!isset($lti->typeid)) {
  99          $lti->typeid = null;
 100      }
 101  
 102      lti_force_type_config_settings($lti, lti_get_type_config_by_instance($lti));
 103  
 104      if (empty($lti->typeid) && isset($lti->urlmatchedtypeid)) {
 105          $lti->typeid = $lti->urlmatchedtypeid;
 106      }
 107  
 108      if (!isset($lti->instructorchoiceacceptgrades) || $lti->instructorchoiceacceptgrades != LTI_SETTING_ALWAYS) {
 109          // The instance does not accept grades back from the provider, so set to "No grade" value 0.
 110          $lti->grade = 0;
 111      }
 112  
 113      $lti->id = $DB->insert_record('lti', $lti);
 114  
 115      if (isset($lti->instructorchoiceacceptgrades) && $lti->instructorchoiceacceptgrades == LTI_SETTING_ALWAYS) {
 116          if (!isset($lti->cmidnumber)) {
 117              $lti->cmidnumber = '';
 118          }
 119  
 120          lti_grade_item_update($lti);
 121      }
 122  
 123      $services = lti_get_services();
 124      foreach ($services as $service) {
 125          $service->instance_added( $lti );
 126      }
 127  
 128      $completiontimeexpected = !empty($lti->completionexpected) ? $lti->completionexpected : null;
 129      \core_completion\api::update_completion_date_event($lti->coursemodule, 'lti', $lti->id, $completiontimeexpected);
 130  
 131      return $lti->id;
 132  }
 133  
 134  /**
 135   * Given an object containing all the necessary data,
 136   * (defined by the form in mod.html) this function
 137   * will update an existing instance with new data.
 138   *
 139   * @param object $instance An object from the form in mod.html
 140   * @return boolean Success/Fail
 141   **/
 142  function lti_update_instance($lti, $mform) {
 143      global $DB, $CFG;
 144      require_once($CFG->dirroot.'/mod/lti/locallib.php');
 145  
 146      lti_load_tool_if_cartridge($lti);
 147  
 148      $lti->timemodified = time();
 149      $lti->id = $lti->instance;
 150  
 151      if (!isset($lti->showtitlelaunch)) {
 152          $lti->showtitlelaunch = 0;
 153      }
 154  
 155      if (!isset($lti->showdescriptionlaunch)) {
 156          $lti->showdescriptionlaunch = 0;
 157      }
 158  
 159      lti_force_type_config_settings($lti, lti_get_type_config_by_instance($lti));
 160  
 161      if (isset($lti->instructorchoiceacceptgrades) && $lti->instructorchoiceacceptgrades == LTI_SETTING_ALWAYS) {
 162          lti_grade_item_update($lti);
 163      } else {
 164          // Instance is no longer accepting grades from Provider, set grade to "No grade" value 0.
 165          $lti->grade = 0;
 166          $lti->instructorchoiceacceptgrades = 0;
 167  
 168          lti_grade_item_delete($lti);
 169      }
 170  
 171      if ($lti->typeid == 0 && isset($lti->urlmatchedtypeid)) {
 172          $lti->typeid = $lti->urlmatchedtypeid;
 173      }
 174  
 175      $services = lti_get_services();
 176      foreach ($services as $service) {
 177          $service->instance_updated( $lti );
 178      }
 179  
 180      $completiontimeexpected = !empty($lti->completionexpected) ? $lti->completionexpected : null;
 181      \core_completion\api::update_completion_date_event($lti->coursemodule, 'lti', $lti->id, $completiontimeexpected);
 182  
 183      return $DB->update_record('lti', $lti);
 184  }
 185  
 186  /**
 187   * Given an ID of an instance of this module,
 188   * this function will permanently delete the instance
 189   * and any data that depends on it.
 190   *
 191   * @param int $id Id of the module instance
 192   * @return boolean Success/Failure
 193   **/
 194  function lti_delete_instance($id) {
 195      global $DB, $CFG;
 196      require_once($CFG->dirroot.'/mod/lti/locallib.php');
 197  
 198      if (! $basiclti = $DB->get_record("lti", array("id" => $id))) {
 199          return false;
 200      }
 201  
 202      $result = true;
 203  
 204      // Delete any dependent records here.
 205      lti_grade_item_delete($basiclti);
 206  
 207      $ltitype = $DB->get_record('lti_types', array('id' => $basiclti->typeid));
 208      if ($ltitype) {
 209          $DB->delete_records('lti_tool_settings',
 210              array('toolproxyid' => $ltitype->toolproxyid, 'course' => $basiclti->course, 'coursemoduleid' => $id));
 211      }
 212  
 213      $cm = get_coursemodule_from_instance('lti', $id);
 214      \core_completion\api::update_completion_date_event($cm->id, 'lti', $id, null);
 215  
 216      // We must delete the module record after we delete the grade item.
 217      if ($DB->delete_records("lti", array("id" => $basiclti->id)) ) {
 218          $services = lti_get_services();
 219          foreach ($services as $service) {
 220              $service->instance_deleted( $id );
 221          }
 222          return true;
 223      }
 224      return false;
 225  
 226  }
 227  
 228  /**
 229   * Return aliases of this activity. LTI should have an alias for each configured tool type
 230   * This is so you can add an external tool types directly to the activity chooser
 231   *
 232   * @deprecated since 3.9
 233   * @todo MDL-68011 This is to be moved from here to deprecatedlib.php in Moodle 4.1
 234   * @param stdClass $defaultitem default item that would be added to the activity chooser if this callback was not present.
 235   *     It has properties: archetype, name, title, help, icon, link
 236   * @return array An array of aliases for this activity. Each element is an object with same list of properties as $defaultitem,
 237   *     plus an additional property, helplink.
 238   *     Properties title and link are required
 239   **/
 240  function lti_get_shortcuts($defaultitem) {
 241      global $CFG, $COURSE;
 242      require_once($CFG->dirroot.'/mod/lti/locallib.php');
 243  
 244      $types = lti_get_configured_types($COURSE->id, $defaultitem->link->param('sr'));
 245      if (has_capability('mod/lti:addmanualinstance', context_course::instance($COURSE->id))) {
 246          $types[] = $defaultitem;
 247      }
 248  
 249      // Add items defined in ltisource plugins.
 250      foreach (core_component::get_plugin_list('ltisource') as $pluginname => $dir) {
 251          // LTISOURCE plugins can also implement callback get_shortcuts() to add items to the activity chooser.
 252          // The return values are the same as of the 'mod' callbacks except that $defaultitem is only passed for reference and
 253          // should not be added to the return value.
 254          if ($moretypes = component_callback("ltisource_$pluginname", 'get_shortcuts', array($defaultitem))) {
 255              $types = array_merge($types, $moretypes);
 256          }
 257      }
 258      return $types;
 259  }
 260  
 261  /**
 262   * Return the preconfigured tools which are configured for inclusion in the activity picker.
 263   *
 264   * @param \core_course\local\entity\content_item $defaultmodulecontentitem reference to the content item for the LTI module.
 265   * @param \stdClass $user the user object, to use for cap checks if desired.
 266   * @param stdClass $course the course to scope items to.
 267   * @return array the array of content items.
 268   */
 269  function lti_get_course_content_items(\core_course\local\entity\content_item $defaultmodulecontentitem, \stdClass $user,
 270          \stdClass $course) {
 271      global $CFG, $OUTPUT;
 272      require_once($CFG->dirroot.'/mod/lti/locallib.php');
 273  
 274      $types = [];
 275  
 276      // The 'External tool' entry (the main module content item), should always take the id of 1.
 277      if (has_capability('mod/lti:addmanualinstance', context_course::instance($course->id), $user)) {
 278          $types = [new \core_course\local\entity\content_item(
 279              1,
 280              $defaultmodulecontentitem->get_name(),
 281              $defaultmodulecontentitem->get_title(),
 282              $defaultmodulecontentitem->get_link(),
 283              $defaultmodulecontentitem->get_icon(),
 284              $defaultmodulecontentitem->get_help(),
 285              $defaultmodulecontentitem->get_archetype(),
 286              $defaultmodulecontentitem->get_component_name(),
 287              $defaultmodulecontentitem->get_purpose()
 288          )];
 289      }
 290  
 291      // Other, preconfigured tools take their own id + 1, so we'll never clash with the module's entry.
 292      $preconfiguredtools = lti_get_configured_types($course->id, $defaultmodulecontentitem->get_link()->param('sr'));
 293      foreach ($preconfiguredtools as $preconfiguredtool) {
 294  
 295          // Append the help link to the help text.
 296          if (isset($preconfiguredtool->help)) {
 297              if (isset($preconfiguredtool->helplink)) {
 298                  $linktext = get_string('morehelp');
 299                  $preconfiguredtool->help .= html_writer::tag('div',
 300                      $OUTPUT->doc_link($preconfiguredtool->helplink, $linktext, true), ['class' => 'helpdoclink']);
 301              }
 302          } else {
 303              $preconfiguredtool->help = '';
 304          }
 305  
 306          $types[] = new \core_course\local\entity\content_item(
 307              $preconfiguredtool->id + 1,
 308              $preconfiguredtool->name,
 309              new \core_course\local\entity\string_title($preconfiguredtool->title),
 310              $preconfiguredtool->link,
 311              $preconfiguredtool->icon,
 312              $preconfiguredtool->help,
 313              $defaultmodulecontentitem->get_archetype(),
 314              $defaultmodulecontentitem->get_component_name(),
 315              $defaultmodulecontentitem->get_purpose()
 316          );
 317      }
 318      return $types;
 319  }
 320  
 321  /**
 322   * Return all content items which can be added to any course.
 323   *
 324   * @param \core_course\local\entity\content_item $defaultmodulecontentitem
 325   * @return array the array of content items.
 326   */
 327  function mod_lti_get_all_content_items(\core_course\local\entity\content_item $defaultmodulecontentitem): array {
 328      global $OUTPUT, $CFG;
 329      require_once($CFG->dirroot . '/mod/lti/locallib.php'); // For access to constants.
 330  
 331      // The 'External tool' entry (the main module content item), should always take the id of 1.
 332      $types = [new \core_course\local\entity\content_item(
 333          1,
 334          $defaultmodulecontentitem->get_name(),
 335          $defaultmodulecontentitem->get_title(),
 336          $defaultmodulecontentitem->get_link(),
 337          $defaultmodulecontentitem->get_icon(),
 338          $defaultmodulecontentitem->get_help(),
 339          $defaultmodulecontentitem->get_archetype(),
 340          $defaultmodulecontentitem->get_component_name(),
 341          $defaultmodulecontentitem->get_purpose()
 342      )];
 343  
 344      foreach (lti_get_lti_types() as $ltitype) {
 345          if ($ltitype->coursevisible != LTI_COURSEVISIBLE_ACTIVITYCHOOSER) {
 346              continue;
 347          }
 348          $type           = new stdClass();
 349          $type->id       = $ltitype->id;
 350          $type->modclass = MOD_CLASS_ACTIVITY;
 351          $type->name     = 'lti_type_' . $ltitype->id;
 352          // Clean the name. We don't want tags here.
 353          $type->title    = clean_param($ltitype->name, PARAM_NOTAGS);
 354          $trimmeddescription = trim($ltitype->description);
 355          $type->help = '';
 356          if ($trimmeddescription != '') {
 357              // Clean the description. We don't want tags here.
 358              $type->help     = clean_param($trimmeddescription, PARAM_NOTAGS);
 359              $type->helplink = get_string('modulename_shortcut_link', 'lti');
 360          }
 361          if (empty($ltitype->icon)) {
 362              $type->icon = $OUTPUT->pix_icon('monologo', '', 'lti', array('class' => 'icon'));
 363          } else {
 364              $type->icon = html_writer::empty_tag('img', array('src' => $ltitype->icon, 'alt' => $ltitype->name, 'class' => 'icon'));
 365          }
 366          $type->link = new moodle_url('/course/modedit.php', array('add' => 'lti', 'return' => 0, 'typeid' => $ltitype->id));
 367  
 368          $types[] = new \core_course\local\entity\content_item(
 369              $type->id + 1,
 370              $type->name,
 371              new \core_course\local\entity\string_title($type->title),
 372              $type->link,
 373              $type->icon,
 374              $type->help,
 375              $defaultmodulecontentitem->get_archetype(),
 376              $defaultmodulecontentitem->get_component_name(),
 377              $defaultmodulecontentitem->get_purpose()
 378          );
 379      }
 380  
 381      return $types;
 382  }
 383  
 384  /**
 385   * Given a coursemodule object, this function returns the extra
 386   * information needed to print this activity in various places.
 387   * For this module we just need to support external urls as
 388   * activity icons
 389   *
 390   * @param stdClass $coursemodule
 391   * @return cached_cm_info info
 392   */
 393  function lti_get_coursemodule_info($coursemodule) {
 394      global $DB, $CFG;
 395      require_once($CFG->dirroot.'/mod/lti/locallib.php');
 396  
 397      if (!$lti = $DB->get_record('lti', array('id' => $coursemodule->instance),
 398              'icon, secureicon, intro, introformat, name, typeid, toolurl, launchcontainer')) {
 399          return null;
 400      }
 401  
 402      $info = new cached_cm_info();
 403  
 404      if ($coursemodule->showdescription) {
 405          // Convert intro to html. Do not filter cached version, filters run at display time.
 406          $info->content = format_module_intro('lti', $lti, $coursemodule->id, false);
 407      }
 408  
 409      if (!empty($lti->typeid)) {
 410          $toolconfig = lti_get_type_config($lti->typeid);
 411      } else if ($tool = lti_get_tool_by_url_match($lti->toolurl)) {
 412          $toolconfig = lti_get_type_config($tool->id);
 413      } else {
 414          $toolconfig = array();
 415      }
 416  
 417      // We want to use the right icon based on whether the
 418      // current page is being requested over http or https.
 419      if (lti_request_is_using_ssl() &&
 420          (!empty($lti->secureicon) || (isset($toolconfig['secureicon']) && !empty($toolconfig['secureicon'])))) {
 421          if (!empty($lti->secureicon)) {
 422              $info->iconurl = new moodle_url($lti->secureicon);
 423          } else {
 424              $info->iconurl = new moodle_url($toolconfig['secureicon']);
 425          }
 426      } else if (!empty($lti->icon)) {
 427          $info->iconurl = new moodle_url($lti->icon);
 428      } else if (isset($toolconfig['icon']) && !empty($toolconfig['icon'])) {
 429          $info->iconurl = new moodle_url($toolconfig['icon']);
 430      }
 431  
 432      // Does the link open in a new window?
 433      $launchcontainer = lti_get_launch_container($lti, $toolconfig);
 434      if ($launchcontainer == LTI_LAUNCH_CONTAINER_WINDOW) {
 435          $launchurl = new moodle_url('/mod/lti/launch.php', array('id' => $coursemodule->id));
 436          $info->onclick = "window.open('" . $launchurl->out(false) . "', 'lti-".$coursemodule->id."'); return false;";
 437      }
 438  
 439      $info->name = $lti->name;
 440  
 441      return $info;
 442  }
 443  
 444  /**
 445   * Return a small object with summary information about what a
 446   * user has done with a given particular instance of this module
 447   * Used for user activity reports.
 448   * $return->time = the time they did it
 449   * $return->info = a short text description
 450   *
 451   * @return null
 452   * @TODO: implement this moodle function (if needed)
 453   **/
 454  function lti_user_outline($course, $user, $mod, $basiclti) {
 455      return null;
 456  }
 457  
 458  /**
 459   * Print a detailed representation of what a user has done with
 460   * a given particular instance of this module, for user activity reports.
 461   *
 462   * @return boolean
 463   * @TODO: implement this moodle function (if needed)
 464   **/
 465  function lti_user_complete($course, $user, $mod, $basiclti) {
 466      return true;
 467  }
 468  
 469  /**
 470   * Given a course and a time, this module should find recent activity
 471   * that has occurred in basiclti activities and print it out.
 472   * Return true if there was output, or false is there was none.
 473   *
 474   * @uses $CFG
 475   * @return boolean
 476   * @TODO: implement this moodle function
 477   **/
 478  function lti_print_recent_activity($course, $isteacher, $timestart) {
 479      return false;  //  True if anything was printed, otherwise false.
 480  }
 481  
 482  /**
 483   * Function to be run periodically according to the moodle cron
 484   * This function searches for things that need to be done, such
 485   * as sending out mail, toggling flags etc ...
 486   *
 487   * @uses $CFG
 488   * @return boolean
 489   **/
 490  function lti_cron () {
 491      return true;
 492  }
 493  
 494  /**
 495   * Must return an array of grades for a given instance of this module,
 496   * indexed by user.  It also returns a maximum allowed grade.
 497   *
 498   * Example:
 499   *    $return->grades = array of grades;
 500   *    $return->maxgrade = maximum allowed grade;
 501   *
 502   *    return $return;
 503   *
 504   * @param int $basicltiid ID of an instance of this module
 505   * @return mixed Null or object with an array of grades and with the maximum grade
 506   *
 507   * @TODO: implement this moodle function (if needed)
 508   **/
 509  function lti_grades($basicltiid) {
 510      return null;
 511  }
 512  
 513  /**
 514   * @deprecated since Moodle 3.8
 515   */
 516  function lti_scale_used() {
 517      throw new coding_exception('lti_scale_used() can not be used anymore. Plugins can implement ' .
 518          '<modname>_scale_used_anywhere, all implementations of <modname>_scale_used are now ignored');
 519  }
 520  
 521  /**
 522   * Checks if scale is being used by any instance of basiclti.
 523   * This function was added in 1.9
 524   *
 525   * This is used to find out if scale used anywhere
 526   * @param $scaleid int
 527   * @return boolean True if the scale is used by any basiclti
 528   *
 529   */
 530  function lti_scale_used_anywhere($scaleid) {
 531      global $DB;
 532  
 533      if ($scaleid and $DB->record_exists('lti', array('grade' => -$scaleid))) {
 534          return true;
 535      } else {
 536          return false;
 537      }
 538  }
 539  
 540  /**
 541   * Execute post-install custom actions for the module
 542   * This function was added in 1.9
 543   *
 544   * @return boolean true if success, false on error
 545   */
 546  function lti_install() {
 547       return true;
 548  }
 549  
 550  /**
 551   * Execute post-uninstall custom actions for the module
 552   * This function was added in 1.9
 553   *
 554   * @return boolean true if success, false on error
 555   */
 556  function lti_uninstall() {
 557      return true;
 558  }
 559  
 560  /**
 561   * Returns available Basic LTI types
 562   *
 563   * @return array of basicLTI types
 564   */
 565  function lti_get_lti_types() {
 566      global $DB;
 567  
 568      return $DB->get_records('lti_types', null, 'state DESC, timemodified DESC');
 569  }
 570  
 571  /**
 572   * Returns available Basic LTI types that match the given
 573   * tool proxy id
 574   *
 575   * @param int $toolproxyid Tool proxy id
 576   * @return array of basicLTI types
 577   */
 578  function lti_get_lti_types_from_proxy_id($toolproxyid) {
 579      global $DB;
 580  
 581      return $DB->get_records('lti_types', array('toolproxyid' => $toolproxyid), 'state DESC, timemodified DESC');
 582  }
 583  
 584  /**
 585   * Create grade item for given basiclti
 586   *
 587   * @category grade
 588   * @param object $basiclti object with extra cmidnumber
 589   * @param mixed optional array/object of grade(s); 'reset' means reset grades in gradebook
 590   * @return int 0 if ok, error code otherwise
 591   */
 592  function lti_grade_item_update($basiclti, $grades = null) {
 593      global $CFG;
 594      require_once($CFG->libdir.'/gradelib.php');
 595      require_once($CFG->dirroot.'/mod/lti/servicelib.php');
 596  
 597      if (!lti_accepts_grades($basiclti)) {
 598          return 0;
 599      }
 600  
 601      $params = array('itemname' => $basiclti->name, 'idnumber' => $basiclti->cmidnumber);
 602  
 603      if ($basiclti->grade > 0) {
 604          $params['gradetype'] = GRADE_TYPE_VALUE;
 605          $params['grademax']  = $basiclti->grade;
 606          $params['grademin']  = 0;
 607  
 608      } else if ($basiclti->grade < 0) {
 609          $params['gradetype'] = GRADE_TYPE_SCALE;
 610          $params['scaleid']   = -$basiclti->grade;
 611  
 612      } else {
 613          $params['gradetype'] = GRADE_TYPE_TEXT; // Allow text comments only.
 614      }
 615  
 616      if ($grades === 'reset') {
 617          $params['reset'] = true;
 618          $grades = null;
 619      }
 620  
 621      return grade_update('mod/lti', $basiclti->course, 'mod', 'lti', $basiclti->id, 0, $grades, $params);
 622  }
 623  
 624  /**
 625   * Update activity grades
 626   *
 627   * @param stdClass $basiclti The LTI instance
 628   * @param int      $userid Specific user only, 0 means all.
 629   * @param bool     $nullifnone Not used
 630   */
 631  function lti_update_grades($basiclti, $userid=0, $nullifnone=true) {
 632      global $CFG;
 633      require_once($CFG->dirroot.'/mod/lti/servicelib.php');
 634      // LTI doesn't have its own grade table so the only thing to do is update the grade item.
 635      if (lti_accepts_grades($basiclti)) {
 636          lti_grade_item_update($basiclti);
 637      }
 638  }
 639  
 640  /**
 641   * Delete grade item for given basiclti
 642   *
 643   * @category grade
 644   * @param object $basiclti object
 645   * @return object basiclti
 646   */
 647  function lti_grade_item_delete($basiclti) {
 648      global $CFG;
 649      require_once($CFG->libdir.'/gradelib.php');
 650  
 651      return grade_update('mod/lti', $basiclti->course, 'mod', 'lti', $basiclti->id, 0, null, array('deleted' => 1));
 652  }
 653  
 654  /**
 655   * Log post actions
 656   *
 657   * @return array
 658   */
 659  function lti_get_post_actions() {
 660      return array();
 661  }
 662  
 663  /**
 664   * Log view actions
 665   *
 666   * @return array
 667   */
 668  function lti_get_view_actions() {
 669      return array('view all', 'view');
 670  }
 671  
 672  /**
 673   * Mark the activity completed (if required) and trigger the course_module_viewed event.
 674   *
 675   * @param  stdClass $lti        lti object
 676   * @param  stdClass $course     course object
 677   * @param  stdClass $cm         course module object
 678   * @param  stdClass $context    context object
 679   * @since Moodle 3.0
 680   */
 681  function lti_view($lti, $course, $cm, $context) {
 682  
 683      // Trigger course_module_viewed event.
 684      $params = array(
 685          'context' => $context,
 686          'objectid' => $lti->id
 687      );
 688  
 689      $event = \mod_lti\event\course_module_viewed::create($params);
 690      $event->add_record_snapshot('course_modules', $cm);
 691      $event->add_record_snapshot('course', $course);
 692      $event->add_record_snapshot('lti', $lti);
 693      $event->trigger();
 694  
 695      // Completion.
 696      $completion = new completion_info($course);
 697      $completion->set_module_viewed($cm);
 698  }
 699  
 700  /**
 701   * Check if the module has any update that affects the current user since a given time.
 702   *
 703   * @param  cm_info $cm course module data
 704   * @param  int $from the time to check updates from
 705   * @param  array $filter  if we need to check only specific updates
 706   * @return stdClass an object with the different type of areas indicating if they were updated or not
 707   * @since Moodle 3.2
 708   */
 709  function lti_check_updates_since(cm_info $cm, $from, $filter = array()) {
 710      global $DB, $USER;
 711  
 712      $updates = course_check_module_updates_since($cm, $from, array(), $filter);
 713  
 714      // Check if there is a new submission.
 715      $updates->submissions = (object) array('updated' => false);
 716      $select = 'ltiid = :id AND userid = :userid AND (datesubmitted > :since1 OR dateupdated > :since2)';
 717      $params = array('id' => $cm->instance, 'userid' => $USER->id, 'since1' => $from, 'since2' => $from);
 718      $submissions = $DB->get_records_select('lti_submission', $select, $params, '', 'id');
 719      if (!empty($submissions)) {
 720          $updates->submissions->updated = true;
 721          $updates->submissions->itemids = array_keys($submissions);
 722      }
 723  
 724      // Now, teachers should see other students updates.
 725      if (has_capability('mod/lti:manage', $cm->context)) {
 726          $select = 'ltiid = :id AND (datesubmitted > :since1 OR dateupdated > :since2)';
 727          $params = array('id' => $cm->instance, 'since1' => $from, 'since2' => $from);
 728  
 729          if (groups_get_activity_groupmode($cm) == SEPARATEGROUPS) {
 730              $groupusers = array_keys(groups_get_activity_shared_group_members($cm));
 731              if (empty($groupusers)) {
 732                  return $updates;
 733              }
 734              list($insql, $inparams) = $DB->get_in_or_equal($groupusers, SQL_PARAMS_NAMED);
 735              $select .= ' AND userid ' . $insql;
 736              $params = array_merge($params, $inparams);
 737          }
 738  
 739          $updates->usersubmissions = (object) array('updated' => false);
 740          $submissions = $DB->get_records_select('lti_submission', $select, $params, '', 'id');
 741          if (!empty($submissions)) {
 742              $updates->usersubmissions->updated = true;
 743              $updates->usersubmissions->itemids = array_keys($submissions);
 744          }
 745      }
 746  
 747      return $updates;
 748  }
 749  
 750  /**
 751   * Get icon mapping for font-awesome.
 752   */
 753  function mod_lti_get_fontawesome_icon_map() {
 754      return [
 755          'mod_lti:warning' => 'fa-exclamation text-warning',
 756      ];
 757  }
 758  
 759  /**
 760   * This function receives a calendar event and returns the action associated with it, or null if there is none.
 761   *
 762   * This is used by block_myoverview in order to display the event appropriately. If null is returned then the event
 763   * is not displayed on the block.
 764   *
 765   * @param calendar_event $event
 766   * @param \core_calendar\action_factory $factory
 767   * @param int $userid User id to use for all capability checks, etc. Set to 0 for current user (default).
 768   * @return \core_calendar\local\event\entities\action_interface|null
 769   */
 770  function mod_lti_core_calendar_provide_event_action(calendar_event $event,
 771                                                        \core_calendar\action_factory $factory,
 772                                                        int $userid = 0) {
 773      global $USER;
 774  
 775      if (empty($userid)) {
 776          $userid = $USER->id;
 777      }
 778  
 779      $cm = get_fast_modinfo($event->courseid, $userid)->instances['lti'][$event->instance];
 780  
 781      if (!$cm->uservisible) {
 782          // The module is not visible to the user for any reason.
 783          return null;
 784      }
 785  
 786      $completion = new \completion_info($cm->get_course());
 787  
 788      $completiondata = $completion->get_data($cm, false, $userid);
 789  
 790      if ($completiondata->completionstate != COMPLETION_INCOMPLETE) {
 791          return null;
 792      }
 793  
 794      return $factory->create_instance(
 795          get_string('view'),
 796          new \moodle_url('/mod/lti/view.php', ['id' => $cm->id]),
 797          1,
 798          true
 799      );
 800  }