Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.11.x will end 14 Nov 2022 (12 months plus 6 months extension).
  • Bug fixes for security issues in 3.11.x will end 13 Nov 2023 (18 months plus 12 months extension).
  • PHP version: minimum PHP 7.3.0 Note: minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is supported too.
/enrol/lti/ -> lib.php (source)

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

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