Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.2.x will end 22 April 2024 (12 months).
  • Bug fixes for security issues in 4.2.x will end 7 October 2024 (18 months).
  • PHP version: minimum PHP 8.0.0 Note: minimum PHP version has increased since Moodle 4.1. PHP 8.1.x is supported too.
/enrol/lti/ -> lib.php (source)

Differences Between: [Versions 310 and 402] [Versions 311 and 402] [Versions 39 and 402]

   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  /**
  18   * LTI enrolment plugin main library file.
  19   *
  20   * @package enrol_lti
  21   * @copyright 2016 Mark Nelson <markn@moodle.com>
  22   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  23   */
  24  
  25  use enrol_lti\data_connector;
  26  use enrol_lti\local\ltiadvantage\repository\resource_link_repository;
  27  use IMSGlobal\LTI\ToolProvider\ToolConsumer;
  28  
  29  defined('MOODLE_INTERNAL') || die();
  30  
  31  /**
  32   * LTI enrolment plugin class.
  33   *
  34   * @package enrol_lti
  35   * @copyright 2016 Mark Nelson <markn@moodle.com>
  36   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  37   */
  38  class enrol_lti_plugin extends enrol_plugin {
  39  
  40      /**
  41       * Return true if we can add a new instance to this course.
  42       *
  43       * @param int $courseid
  44       * @return boolean
  45       */
  46      public function can_add_instance($courseid) {
  47          $context = context_course::instance($courseid, MUST_EXIST);
  48          return has_capability('moodle/course:enrolconfig', $context) && has_capability('enrol/lti:config', $context);
  49      }
  50  
  51      /**
  52       * Is it possible to delete enrol instance via standard UI?
  53       *
  54       * @param object $instance
  55       * @return bool
  56       */
  57      public function can_delete_instance($instance) {
  58          $context = context_course::instance($instance->courseid);
  59          return has_capability('enrol/lti:config', $context);
  60      }
  61  
  62      /**
  63       * Is it possible to hide/show enrol instance via standard UI?
  64       *
  65       * @param stdClass $instance
  66       * @return bool
  67       */
  68      public function can_hide_show_instance($instance) {
  69          $context = context_course::instance($instance->courseid);
  70          return has_capability('enrol/lti:config', $context);
  71      }
  72  
  73      /**
  74       * Returns true if it's possible to unenrol users.
  75       *
  76       * @param stdClass $instance course enrol instance
  77       * @return bool
  78       */
  79      public function allow_unenrol(stdClass $instance) {
  80          return true;
  81      }
  82  
  83      /**
  84       * We are a good plugin and don't invent our own UI/validation code path.
  85       *
  86       * @return boolean
  87       */
  88      public function use_standard_editing_ui() {
  89          return true;
  90      }
  91  
  92      /**
  93       * Add new instance of enrol plugin.
  94       *
  95       * @param object $course
  96       * @param array $fields instance fields
  97       * @return int id of new instance, null if can not be created
  98       */
  99      public function add_instance($course, array $fields = null) {
 100          global $DB;
 101  
 102          $instanceid = parent::add_instance($course, $fields);
 103  
 104          // Add additional data to our table.
 105          $data = new stdClass();
 106          $data->enrolid = $instanceid;
 107          $data->timecreated = time();
 108          $data->timemodified = $data->timecreated;
 109          foreach ($fields as $field => $value) {
 110              $data->$field = $value;
 111          }
 112  
 113          // LTI Advantage: make a unique identifier for the published resource.
 114          if (empty($data->ltiversion) || $data->ltiversion == 'LTI-1p3') {
 115              $data->uuid = \core\uuid::generate();
 116          }
 117  
 118          $DB->insert_record('enrol_lti_tools', $data);
 119  
 120          return $instanceid;
 121      }
 122  
 123      /**
 124       * Update instance of enrol plugin.
 125       *
 126       * @param stdClass $instance
 127       * @param stdClass $data modified instance fields
 128       * @return boolean
 129       */
 130      public function update_instance($instance, $data) {
 131          global $DB;
 132  
 133          parent::update_instance($instance, $data);
 134  
 135          // Remove the fields we don't want to override.
 136          unset($data->id);
 137          unset($data->timecreated);
 138          unset($data->timemodified);
 139  
 140          // Convert to an array we can loop over.
 141          $fields = (array) $data;
 142  
 143          // Update the data in our table.
 144          $tool = new stdClass();
 145          $tool->id = $data->toolid;
 146          $tool->timemodified = time();
 147          foreach ($fields as $field => $value) {
 148              $tool->$field = $value;
 149          }
 150  
 151          // LTI Advantage: make a unique identifier for the published resource.
 152          if ($tool->ltiversion == 'LTI-1p3' && empty($tool->uuid)) {
 153              $tool->uuid = \core\uuid::generate();
 154          }
 155  
 156          return $DB->update_record('enrol_lti_tools', $tool);
 157      }
 158  
 159      /**
 160       * Delete plugin specific information.
 161       *
 162       * @param stdClass $instance
 163       * @return void
 164       */
 165      public function delete_instance($instance) {
 166          global $DB;
 167  
 168          // Get the tool associated with this instance.
 169          $tool = $DB->get_record('enrol_lti_tools', array('enrolid' => $instance->id), 'id', MUST_EXIST);
 170  
 171          // LTI Advantage: delete any resource_link and user_resource_link mappings.
 172          $resourcelinkrepo = new resource_link_repository();
 173          $resourcelinkrepo->delete_by_resource($tool->id);
 174  
 175          // Delete any users associated with this tool.
 176          $DB->delete_records('enrol_lti_users', array('toolid' => $tool->id));
 177  
 178          // Get tool and consumer mappings.
 179          $rsmapping = $DB->get_recordset('enrol_lti_tool_consumer_map', array('toolid' => $tool->id));
 180  
 181          // Delete consumers that are linked to this tool and their related data.
 182          $dataconnector = new data_connector();
 183          foreach ($rsmapping as $mapping) {
 184              $consumer = new ToolConsumer(null, $dataconnector);
 185              $consumer->setRecordId($mapping->consumerid);
 186              $dataconnector->deleteToolConsumer($consumer);
 187          }
 188          $rsmapping->close();
 189  
 190          // Delete mapping records.
 191          $DB->delete_records('enrol_lti_tool_consumer_map', array('toolid' => $tool->id));
 192  
 193          // Delete the lti tool record.
 194          $DB->delete_records('enrol_lti_tools', array('id' => $tool->id));
 195  
 196          // Time for the parent to do it's thang, yeow.
 197          parent::delete_instance($instance);
 198      }
 199  
 200      /**
 201       * Handles un-enrolling a user.
 202       *
 203       * @param stdClass $instance
 204       * @param int $userid
 205       * @return void
 206       */
 207      public function unenrol_user(stdClass $instance, $userid) {
 208          global $DB;
 209  
 210          // Get the tool associated with this instance. Note - it may not exist if we have deleted
 211          // the tool. This is fine because we have already cleaned the 'enrol_lti_users' table.
 212          if ($tool = $DB->get_record('enrol_lti_tools', array('enrolid' => $instance->id), 'id')) {
 213              // Need to remove the user from the users table.
 214              $DB->delete_records('enrol_lti_users', array('userid' => $userid, 'toolid' => $tool->id));
 215          }
 216  
 217          parent::unenrol_user($instance, $userid);
 218      }
 219  
 220      /**
 221       * Add elements to the edit instance form.
 222       *
 223       * @param stdClass $instance
 224       * @param MoodleQuickForm $mform
 225       * @param context $context
 226       * @return bool
 227       */
 228      public function edit_instance_form($instance, MoodleQuickForm $mform, $context) {
 229          global $DB;
 230  
 231          $versionoptions = [
 232              'LTI-1p3' => get_string('lti13', 'enrol_lti'),
 233              'LTI-1p0/LTI-2p0' => get_string('ltilegacy', 'enrol_lti')
 234          ];
 235          $mform->addElement('select', 'ltiversion', get_string('ltiversion', 'enrol_lti'), $versionoptions);
 236          $mform->addHelpButton('ltiversion', 'ltiversion', 'enrol_lti');
 237          $legacy = optional_param('legacy', 0, PARAM_INT);
 238          if (empty($instance->id)) {
 239              $mform->setDefault('ltiversion', $legacy ? 'LTI-1p0/LTI-2p0' : 'LTI-1p3');
 240          }
 241  
 242          $nameattribs = array('size' => '20', 'maxlength' => '255');
 243          $mform->addElement('text', 'name', get_string('custominstancename', 'enrol'), $nameattribs);
 244          $mform->setType('name', PARAM_TEXT);
 245          $mform->addRule('name', get_string('maximumchars', '', 255), 'maxlength', 255, 'server');
 246  
 247          $tools = array();
 248          $tools[$context->id] = get_string('course');
 249          $modinfo = get_fast_modinfo($instance->courseid);
 250          $mods = $modinfo->get_cms();
 251          foreach ($mods as $mod) {
 252              $tools[$mod->context->id] = format_string($mod->name);
 253          }
 254  
 255          $mform->addElement('select', 'contextid', get_string('tooltobeprovided', 'enrol_lti'), $tools);
 256          $mform->setDefault('contextid', $context->id);
 257  
 258          $mform->addElement('duration', 'enrolperiod', get_string('enrolperiod', 'enrol_lti'),
 259              array('optional' => true, 'defaultunit' => DAYSECS));
 260          $mform->setDefault('enrolperiod', 0);
 261          $mform->addHelpButton('enrolperiod', 'enrolperiod', 'enrol_lti');
 262  
 263          $mform->addElement('date_time_selector', 'enrolstartdate', get_string('enrolstartdate', 'enrol_lti'),
 264              array('optional' => true));
 265          $mform->setDefault('enrolstartdate', 0);
 266          $mform->addHelpButton('enrolstartdate', 'enrolstartdate', 'enrol_lti');
 267  
 268          $mform->addElement('date_time_selector', 'enrolenddate', get_string('enrolenddate', 'enrol_lti'),
 269              array('optional' => true));
 270          $mform->setDefault('enrolenddate', 0);
 271          $mform->addHelpButton('enrolenddate', 'enrolenddate', 'enrol_lti');
 272  
 273          $mform->addElement('text', 'maxenrolled', get_string('maxenrolled', 'enrol_lti'));
 274          $mform->setDefault('maxenrolled', 0);
 275          $mform->addHelpButton('maxenrolled', 'maxenrolled', 'enrol_lti');
 276          $mform->setType('maxenrolled', PARAM_INT);
 277  
 278          $assignableroles = get_assignable_roles($context);
 279  
 280          $mform->addElement('select', 'roleinstructor', get_string('roleinstructor', 'enrol_lti'), $assignableroles);
 281          $mform->setDefault('roleinstructor', '3');
 282          $mform->addHelpButton('roleinstructor', 'roleinstructor', 'enrol_lti');
 283  
 284          $mform->addElement('select', 'rolelearner', get_string('rolelearner', 'enrol_lti'), $assignableroles);
 285          $mform->setDefault('rolelearner', '5');
 286          $mform->addHelpButton('rolelearner', 'rolelearner', 'enrol_lti');
 287  
 288          if (!$legacy) {
 289              global $CFG;
 290              require_once($CFG->dirroot . '/auth/lti/auth.php');
 291              $authmodes = [
 292                  auth_plugin_lti::PROVISIONING_MODE_AUTO_ONLY => get_string('provisioningmodeauto', 'auth_lti'),
 293                  auth_plugin_lti::PROVISIONING_MODE_PROMPT_NEW_EXISTING => get_string('provisioningmodenewexisting', 'auth_lti'),
 294                  auth_plugin_lti::PROVISIONING_MODE_PROMPT_EXISTING_ONLY => get_string('provisioningmodeexistingonly', 'auth_lti')
 295              ];
 296              $mform->addElement('select', 'provisioningmodeinstructor', get_string('provisioningmodeteacherlaunch', 'enrol_lti'),
 297                  $authmodes);
 298              $mform->addHelpButton('provisioningmodeinstructor', 'provisioningmode', 'enrol_lti');
 299              $mform->setDefault('provisioningmodeinstructor', auth_plugin_lti::PROVISIONING_MODE_PROMPT_NEW_EXISTING);
 300  
 301              $mform->addElement('select', 'provisioningmodelearner', get_string('provisioningmodestudentlaunch', 'enrol_lti'),
 302                  $authmodes);
 303              $mform->addHelpButton('provisioningmodelearner', 'provisioningmode', 'enrol_lti');
 304              $mform->setDefault('provisioningmodelearner', auth_plugin_lti::PROVISIONING_MODE_AUTO_ONLY);
 305          }
 306  
 307          $mform->addElement('header', 'remotesystem', get_string('remotesystem', 'enrol_lti'));
 308  
 309          $mform->addElement('text', 'secret', get_string('secret', 'enrol_lti'), 'maxlength="64" size="25"');
 310          $mform->setType('secret', PARAM_ALPHANUM);
 311          $mform->setDefault('secret', random_string(32));
 312          $mform->addHelpButton('secret', 'secret', 'enrol_lti');
 313          $mform->hideIf('secret', 'ltiversion', 'eq', 'LTI-1p3');
 314  
 315          $mform->addElement('selectyesno', 'gradesync', get_string('gradesync', 'enrol_lti'));
 316          $mform->setDefault('gradesync', 1);
 317          $mform->addHelpButton('gradesync', 'gradesync', 'enrol_lti');
 318  
 319          $mform->addElement('selectyesno', 'gradesynccompletion', get_string('requirecompletion', 'enrol_lti'));
 320          $mform->setDefault('gradesynccompletion', 0);
 321          $mform->disabledIf('gradesynccompletion', 'gradesync', 0);
 322  
 323          $mform->addElement('selectyesno', 'membersync', get_string('membersync', 'enrol_lti'));
 324          $mform->setDefault('membersync', 1);
 325          $mform->addHelpButton('membersync', 'membersync', 'enrol_lti');
 326  
 327          $options = array();
 328          $options[\enrol_lti\helper::MEMBER_SYNC_ENROL_AND_UNENROL] = get_string('membersyncmodeenrolandunenrol', 'enrol_lti');
 329          $options[\enrol_lti\helper::MEMBER_SYNC_ENROL_NEW] = get_string('membersyncmodeenrolnew', 'enrol_lti');
 330          $options[\enrol_lti\helper::MEMBER_SYNC_UNENROL_MISSING] = get_string('membersyncmodeunenrolmissing', 'enrol_lti');
 331          $mform->addElement('select', 'membersyncmode', get_string('membersyncmode', 'enrol_lti'), $options);
 332          $mform->setDefault('membersyncmode', \enrol_lti\helper::MEMBER_SYNC_ENROL_AND_UNENROL);
 333          $mform->addHelpButton('membersyncmode', 'membersyncmode', 'enrol_lti');
 334          $mform->disabledIf('membersyncmode', 'membersync', 0);
 335  
 336          $mform->addElement('header', 'defaultheader', get_string('userdefaultvalues', 'enrol_lti'));
 337  
 338          $emaildisplay = get_config('enrol_lti', 'emaildisplay');
 339          $choices = array(
 340              0 => get_string('emaildisplayno'),
 341              1 => get_string('emaildisplayyes'),
 342              2 => get_string('emaildisplaycourse')
 343          );
 344          $mform->addElement('select', 'maildisplay', get_string('emaildisplay'), $choices);
 345          $mform->setDefault('maildisplay', $emaildisplay);
 346          $mform->addHelpButton('maildisplay', 'emaildisplay');
 347  
 348          $city = get_config('enrol_lti', 'city');
 349          $mform->addElement('text', 'city', get_string('city'), 'maxlength="100" size="25"');
 350          $mform->setType('city', PARAM_TEXT);
 351          $mform->setDefault('city', $city);
 352  
 353          $country = get_config('enrol_lti', 'country');
 354          $countries = array('' => get_string('selectacountry') . '...') + get_string_manager()->get_list_of_countries();
 355          $mform->addElement('select', 'country', get_string('selectacountry'), $countries);
 356          $mform->setDefault('country', $country);
 357          $mform->setAdvanced('country');
 358  
 359          $timezone = get_config('enrol_lti', 'timezone');
 360          $choices = core_date::get_list_of_timezones(null, true);
 361          $mform->addElement('select', 'timezone', get_string('timezone'), $choices);
 362          $mform->setDefault('timezone', $timezone);
 363          $mform->setAdvanced('timezone');
 364  
 365          $lang = get_config('enrol_lti', 'lang');
 366          $mform->addElement('select', 'lang', get_string('preferredlanguage'), get_string_manager()->get_list_of_translations());
 367          $mform->setDefault('lang', $lang);
 368          $mform->setAdvanced('lang');
 369  
 370          $institution = get_config('enrol_lti', 'institution');
 371          $mform->addElement('text', 'institution', get_string('institution'), 'maxlength="40" size="25"');
 372          $mform->setType('institution', core_user::get_property_type('institution'));
 373          $mform->setDefault('institution', $institution);
 374          $mform->setAdvanced('institution');
 375  
 376          // Check if we are editing an instance.
 377          if (!empty($instance->id)) {
 378              // Get the details from the enrol_lti_tools table.
 379              $ltitool = $DB->get_record('enrol_lti_tools', array('enrolid' => $instance->id), '*', MUST_EXIST);
 380  
 381              $mform->addElement('hidden', 'toolid');
 382              $mform->setType('toolid', PARAM_INT);
 383              $mform->setConstant('toolid', $ltitool->id);
 384  
 385              $mform->addElement('hidden', 'uuid');
 386              $mform->setType('uuid', PARAM_ALPHANUMEXT);
 387              $mform->setConstant('uuid', $ltitool->uuid);
 388  
 389              $mform->setDefaults((array) $ltitool);
 390          }
 391      }
 392  
 393      /**
 394       * Perform custom validation of the data used to edit the instance.
 395       *
 396       * @param array $data array of ("fieldname"=>value) of submitted data
 397       * @param array $files array of uploaded files "element_name"=>tmp_file_path
 398       * @param object $instance The instance loaded from the DB
 399       * @param context $context The context of the instance we are editing
 400       * @return array of "element_name"=>"error_description" if there are errors,
 401       *         or an empty array if everything is OK.
 402       * @return void
 403       */
 404      public function edit_instance_validation($data, $files, $instance, $context) {
 405          global $COURSE, $DB;
 406  
 407          $errors = array();
 408  
 409          // Secret must be set.
 410          if (empty($data['secret'])) {
 411              $errors['secret'] = get_string('required');
 412          }
 413  
 414          if (!empty($data['enrolenddate']) && $data['enrolenddate'] < $data['enrolstartdate']) {
 415              $errors['enrolenddate'] = get_string('enrolenddateerror', 'enrol_lti');
 416          }
 417  
 418          if (!empty($data['requirecompletion'])) {
 419              $completion = new completion_info($COURSE);
 420              $moodlecontext = $DB->get_record('context', array('id' => $data['contextid']));
 421              if ($moodlecontext->contextlevel == CONTEXT_MODULE) {
 422                  $cm = get_coursemodule_from_id(false, $moodlecontext->instanceid, 0, false, MUST_EXIST);
 423              } else {
 424                  $cm = null;
 425              }
 426  
 427              if (!$completion->is_enabled($cm)) {
 428                  $errors['requirecompletion'] = get_string('errorcompletionenabled', 'enrol_lti');
 429              }
 430          }
 431  
 432          return $errors;
 433      }
 434  
 435      /**
 436       * Restore instance and map settings.
 437       *
 438       * @param restore_enrolments_structure_step $step
 439       * @param stdClass $data
 440       * @param stdClass $course
 441       * @param int $oldid
 442       */
 443      public function restore_instance(restore_enrolments_structure_step $step, stdClass $data, $course, $oldid) {
 444          // We want to call the parent because we do not want to add an enrol_lti_tools row
 445          // as that is done as part of the restore process.
 446          $instanceid = parent::add_instance($course, (array)$data);
 447          $step->set_mapping('enrol', $oldid, $instanceid);
 448      }
 449  }
 450  
 451  /**
 452   * Display the LTI link in the course administration menu.
 453   *
 454   * @param settings_navigation $navigation The settings navigation object
 455   * @param stdClass $course The course
 456   * @param stdclass $context Course context
 457   */
 458  function enrol_lti_extend_navigation_course($navigation, $course, $context) {
 459      // Check that the LTI plugin is enabled.
 460      if (enrol_is_enabled('lti')) {
 461          // Check that they can add an instance.
 462          $ltiplugin = enrol_get_plugin('lti');
 463          if ($ltiplugin->can_add_instance($course->id)) {
 464              $url = new moodle_url('/enrol/lti/index.php', ['courseid' => $course->id]);
 465              $settingsnode = navigation_node::create(get_string('sharedexternaltools', 'enrol_lti'), $url,
 466                  navigation_node::TYPE_SETTING, null, 'publishedtools', new pix_icon('i/settings', ''));
 467              $navigation->add_node($settingsnode);
 468          }
 469      }
 470  }
 471  
 472  /**
 473   * Get icon mapping for font-awesome.
 474   */
 475  function enrol_lti_get_fontawesome_icon_map() {
 476      return [
 477          'enrol_lti:managedeployments' => 'fa-sitemap',
 478          'enrol_lti:platformdetails' => 'fa-pencil-square-o',
 479          'enrol_lti:enrolinstancewarning' => 'fa-exclamation-circle text-danger',
 480      ];
 481  }
 482  
 483  /**
 484   * Pre-delete course module hook which disables any methods referring to the deleted module, preventing launches and allowing remap.
 485   *
 486   * @param stdClass $cm The deleted course module record.
 487   */
 488  function enrol_lti_pre_course_module_delete(stdClass $cm) {
 489      global $DB;
 490      $sql = "id IN (SELECT t.enrolid
 491                       FROM {enrol_lti_tools} t
 492                       JOIN {context} c ON (t.contextid = c.id)
 493                      WHERE c.contextlevel = :contextlevel
 494                        AND c.instanceid = :cmid)";
 495      $DB->set_field_select('enrol', 'status', ENROL_INSTANCE_DISABLED, $sql, ['contextlevel' => CONTEXT_MODULE, 'cmid' => $cm->id]);
 496  }