Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.10.x will end 8 November 2021 (12 months).
  • Bug fixes for security issues in 3.10.x will end 9 May 2022 (18 months).
  • PHP version: minimum PHP 7.2.0 Note: minimum PHP version has increased since Moodle 3.8. PHP 7.3.x and 7.4.x are supported too.
   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   * Implements the XML-RPC methods this plugin publishes to MNet peers
  19   *
  20   * This file must be named enrol.php because current MNet framework has the
  21   * filename hardcoded in XML-RPC path and we want to be compatible with
  22   * Moodle 1.x MNet clients. There is a proposal in MDL-21993 to allow
  23   * map XMP-RPC calls to whatever file, function, class or methods. Once this
  24   * is fixed, this file will be probably renamed to mnetlib.php (which could
  25   * be a common name of a plugin library containing functions/methods callable
  26   * via MNet framework.
  27   *
  28   * @package    enrol_mnet
  29   * @copyright  2010 David Mudrak <david@moodle.com>
  30   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  31   */
  32  
  33  defined('MOODLE_INTERNAL') || die();
  34  
  35  /**
  36   * MNet server-side methods that are part of mnetservice_enrol
  37   *
  38   * The weird name of the class tries to follow a pattern
  39   * {plugintype}_{pluginnname}_mnetservice_{servicename}
  40   *
  41   * Class methods are compatible with API 1 of the service used by Moodle 1.x
  42   * and 2.0 peers. The API version might become a part of class name but it is
  43   * not neccessary due to how xml-rcp methods are/will be mapped to php methods.
  44   */
  45  class enrol_mnet_mnetservice_enrol {
  46  
  47      /**
  48       * Returns list of courses that we offer to the caller for remote enrolment of their users
  49       *
  50       * Since Moodle 2.0, courses are made available for MNet peers by creating an instance
  51       * of enrol_mnet plugin for the course. Hidden courses are not returned. If there are two
  52       * instances - one specific for the host and one for 'All hosts', the setting of the specific
  53       * one is used. The id of the peer is kept in customint1, no other custom fields are used.
  54       *
  55       * @uses mnet_remote_client Callable via XML-RPC only
  56       * @return array
  57       */
  58      public function available_courses() {
  59          global $CFG, $DB;
  60          require_once($CFG->libdir.'/filelib.php');
  61  
  62          if (!$client = get_mnet_remote_client()) {
  63              die('Callable via XML-RPC only');
  64          }
  65  
  66          // we call our id as 'remoteid' because it will be sent to the peer
  67          // the column aliases are required by MNet protocol API for clients 1.x and 2.0
  68          $sql = "SELECT c.id AS remoteid, c.fullname, c.shortname, c.idnumber, c.summary, c.summaryformat,
  69                         c.sortorder, c.startdate, cat.id AS cat_id, cat.name AS cat_name,
  70                         cat.description AS cat_description, cat.descriptionformat AS cat_descriptionformat,
  71                         e.cost, e.currency, e.roleid AS defaultroleid, r.name AS defaultrolename,
  72                         e.customint1
  73                    FROM {enrol} e
  74              INNER JOIN {course} c ON c.id = e.courseid
  75              INNER JOIN {course_categories} cat ON cat.id = c.category
  76              INNER JOIN {role} r ON r.id = e.roleid
  77                   WHERE e.enrol = 'mnet'
  78                         AND (e.customint1 = 0 OR e.customint1 = ?)
  79                         AND c.visible = 1
  80                ORDER BY cat.sortorder, c.sortorder, c.shortname";
  81  
  82          $rs = $DB->get_recordset_sql($sql, array($client->id));
  83  
  84          $courses = array();
  85          foreach ($rs as $course) {
  86              // use the record if it does not exist yet or is host-specific
  87              if (empty($courses[$course->remoteid]) or ($course->customint1 > 0)) {
  88                  unset($course->customint1); // the client does not need to know this
  89                  $context = context_course::instance($course->remoteid);
  90                  // Rewrite file URLs so that they are correct
  91                  $course->summary = file_rewrite_pluginfile_urls($course->summary, 'pluginfile.php', $context->id, 'course', 'summary', false);
  92                  $courses[$course->remoteid] = $course;
  93              }
  94          }
  95          $rs->close();
  96  
  97          return array_values($courses); // can not use keys for backward compatibility
  98      }
  99  
 100      /**
 101       * This method has never been implemented in Moodle MNet API
 102       *
 103       * @uses mnet_remote_client Callable via XML-RPC only
 104       * @return array empty array
 105       */
 106      public function user_enrolments() {
 107          global $CFG, $DB;
 108  
 109          if (!$client = get_mnet_remote_client()) {
 110              die('Callable via XML-RPC only');
 111          }
 112          return array();
 113      }
 114  
 115      /**
 116       * Enrol remote user to our course
 117       *
 118       * If we do not have local record for the remote user in our database,
 119       * it gets created here.
 120       *
 121       * @uses mnet_remote_client Callable via XML-RPC only
 122       * @param array $userdata user details {@see mnet_fields_to_import()}
 123       * @param int $courseid our local course id
 124       * @return bool true if the enrolment has been successful, throws exception otherwise
 125       */
 126      public function enrol_user(array $userdata, $courseid) {
 127          global $CFG, $DB;
 128          require_once (__DIR__.'/lib.php');
 129  
 130          if (!$client = get_mnet_remote_client()) {
 131              die('Callable via XML-RPC only');
 132          }
 133  
 134          if (empty($userdata['username'])) {
 135              throw new mnet_server_exception(5021, 'emptyusername', 'enrol_mnet');
 136          }
 137  
 138          // do we know the remote user?
 139          $user = $DB->get_record('user', array('username'=>$userdata['username'], 'mnethostid'=>$client->id));
 140  
 141          if ($user === false) {
 142              // here we could check the setting if the enrol_mnet is allowed to auto-register
 143              // users {@link http://tracker.moodle.org/browse/MDL-21327}
 144              $user = mnet_strip_user((object)$userdata, mnet_fields_to_import($client));
 145              $user->mnethostid = $client->id;
 146              $user->auth = 'mnet';
 147              $user->confirmed = 1;
 148              try {
 149                  $user->id = $DB->insert_record('user', $user);
 150              } catch (Exception $e) {
 151                  throw new mnet_server_exception(5011, 'couldnotcreateuser', 'enrol_mnet');
 152              }
 153          }
 154  
 155          if (! $course = $DB->get_record('course', array('id'=>$courseid))) {
 156              throw new mnet_server_exception(5012, 'coursenotfound', 'enrol_mnet');
 157          }
 158  
 159          $courses = $this->available_courses();
 160          $isavailable = false;
 161          foreach ($courses as $available) {
 162              if ($available->remoteid == $course->id) {
 163                  $isavailable = true;
 164                  break;
 165              }
 166          }
 167          if (!$isavailable) {
 168              throw new mnet_server_exception(5013, 'courseunavailable', 'enrol_mnet');
 169          }
 170  
 171          // try to load host specific enrol_mnet instance first
 172          $instance = $DB->get_record('enrol', array('courseid'=>$course->id, 'enrol'=>'mnet', 'customint1'=>$client->id), '*', IGNORE_MISSING);
 173  
 174          if ($instance === false) {
 175              // if not found, try to load instance for all hosts
 176              $instance = $DB->get_record('enrol', array('courseid'=>$course->id, 'enrol'=>'mnet', 'customint1'=>0), '*', IGNORE_MISSING);
 177          }
 178  
 179          if ($instance === false) {
 180              // this should not happen as the course was returned by {@see self::available_courses()}
 181              throw new mnet_server_exception(5017, 'noenrolinstance', 'enrol_mnet');
 182          }
 183  
 184          if (!$enrol = enrol_get_plugin('mnet')) {
 185              throw new mnet_server_exception(5018, 'couldnotinstantiate', 'enrol_mnet');
 186          }
 187  
 188          try {
 189              $enrol->enrol_user($instance, $user->id, $instance->roleid, time());
 190  
 191          } catch (Exception $e) {
 192              throw new mnet_server_exception(5019, 'couldnotenrol', 'enrol_mnet', $e->getMessage());
 193          }
 194  
 195          return true;
 196      }
 197  
 198      /**
 199       * Unenrol remote user from our course
 200       *
 201       * Only users enrolled via enrol_mnet plugin can be unenrolled remotely. If the
 202       * remote user is enrolled into the local course via some other enrol plugin
 203       * (enrol_manual for example), the remote host can't touch such enrolment. Please
 204       * do not report this behaviour as bug, it is a feature ;-)
 205       *
 206       * @uses mnet_remote_client Callable via XML-RPC only
 207       * @param string $username of the remote user
 208       * @param int $courseid of our local course
 209       * @return bool true if the unenrolment has been successful, throws exception otherwise
 210       */
 211      public function unenrol_user($username, $courseid) {
 212          global $CFG, $DB;
 213  
 214          if (!$client = get_mnet_remote_client()) {
 215              die('Callable via XML-RPC only');
 216          }
 217  
 218          $user = $DB->get_record('user', array('username'=>$username, 'mnethostid'=>$client->id));
 219  
 220          if ($user === false) {
 221              throw new mnet_server_exception(5014, 'usernotfound', 'enrol_mnet');
 222          }
 223  
 224          if (! $course = $DB->get_record('course', array('id'=>$courseid))) {
 225              throw new mnet_server_exception(5012, 'coursenotfound', 'enrol_mnet');
 226          }
 227  
 228          $courses = $this->available_courses();
 229          $isavailable = false;
 230          foreach ($courses as $available) {
 231              if ($available->remoteid == $course->id) {
 232                  $isavailable = true;
 233                  break;
 234              }
 235          }
 236          if (!$isavailable) {
 237              // if they can not enrol, they can not unenrol
 238              throw new mnet_server_exception(5013, 'courseunavailable', 'enrol_mnet');
 239          }
 240  
 241          // try to load host specific enrol_mnet instance first
 242          $instance = $DB->get_record('enrol', array('courseid'=>$course->id, 'enrol'=>'mnet', 'customint1'=>$client->id), '*', IGNORE_MISSING);
 243  
 244          if ($instance === false) {
 245              // if not found, try to load instance for all hosts
 246              $instance = $DB->get_record('enrol', array('courseid'=>$course->id, 'enrol'=>'mnet', 'customint1'=>0), '*', IGNORE_MISSING);
 247              $instanceforall = true;
 248          }
 249  
 250          if ($instance === false) {
 251              // this should not happen as the course was returned by {@see self::available_courses()}
 252              throw new mnet_server_exception(5017, 'noenrolinstance', 'enrol_mnet');
 253          }
 254  
 255          if (!$enrol = enrol_get_plugin('mnet')) {
 256              throw new mnet_server_exception(5018, 'couldnotinstantiate', 'enrol_mnet');
 257          }
 258  
 259          if ($DB->record_exists('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$user->id))) {
 260              try {
 261                  $enrol->unenrol_user($instance, $user->id);
 262  
 263              } catch (Exception $e) {
 264                  throw new mnet_server_exception(5020, 'couldnotunenrol', 'enrol_mnet', $e->getMessage());
 265              }
 266          }
 267  
 268          if (empty($instanceforall)) {
 269              // if the user was enrolled via 'All hosts' instance and the specific one
 270              // was created after that, the first enrolment would be kept.
 271              $instance = $DB->get_record('enrol', array('courseid'=>$course->id, 'enrol'=>'mnet', 'customint1'=>0), '*', IGNORE_MISSING);
 272  
 273              if ($instance) {
 274                  // repeat the same procedure for 'All hosts' instance, too. Note that as the host specific
 275                  // instance exists, it will be used for the future enrolments
 276  
 277                  if ($DB->record_exists('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$user->id))) {
 278                      try {
 279                          $enrol->unenrol_user($instance, $user->id);
 280  
 281                      } catch (Exception $e) {
 282                          throw new mnet_server_exception(5020, 'couldnotunenrol', 'enrol_mnet', $e->getMessage());
 283                      }
 284                  }
 285              }
 286          }
 287  
 288          return true;
 289      }
 290  
 291      /**
 292       * Returns a list of users from the client server who are enrolled in our course
 293       *
 294       * Suitable instance of enrol_mnet must be created in the course. This method will not
 295       * return any information about the enrolments in courses that are not available for
 296       * remote enrolment, even if their users are enrolled into them via other plugin
 297       * (note the difference from {@link self::user_enrolments()}).
 298       *
 299       * This method will return enrolment information for users from hosts regardless
 300       * the enrolment plugin. It does not matter if the user was enrolled remotely by
 301       * their admin or locally. Once the course is available for remote enrolments, we
 302       * will tell them everything about their users.
 303       *
 304       * In Moodle 1.x the returned array used to be indexed by username. The side effect
 305       * of MDL-19219 fix is that we do not need to use such index and therefore we can
 306       * return all enrolment records. MNet clients 1.x will only use the last record for
 307       * the student, if she is enrolled via multiple plugins.
 308       *
 309       * @uses mnet_remote_client Callable via XML-RPC only
 310       * @param int $courseid ID of our course
 311       * @param string|array $roles comma separated list of role shortnames (or array of them)
 312       * @return array
 313       */
 314      public function course_enrolments($courseid, $roles=null) {
 315          global $DB, $CFG;
 316  
 317          if (!$client = get_mnet_remote_client()) {
 318              die('Callable via XML-RPC only');
 319          }
 320  
 321          $sql = "SELECT u.username, r.shortname, r.name, e.enrol, ue.timemodified
 322                    FROM {user_enrolments} ue
 323                    JOIN {user} u ON ue.userid = u.id
 324                    JOIN {enrol} e ON ue.enrolid = e.id
 325                    JOIN {role} r ON e.roleid = r.id
 326                   WHERE u.mnethostid = :mnethostid
 327                         AND e.courseid = :courseid
 328                         AND u.id <> :guestid
 329                         AND u.confirmed = 1
 330                         AND u.deleted = 0";
 331          $params['mnethostid'] = $client->id;
 332          $params['courseid'] = $courseid;
 333          $params['guestid'] = $CFG->siteguest;
 334  
 335          if (!is_null($roles)) {
 336              if (!is_array($roles)) {
 337                  $roles = explode(',', $roles);
 338              }
 339              $roles = array_map('trim', $roles);
 340              list($rsql, $rparams) = $DB->get_in_or_equal($roles, SQL_PARAMS_NAMED);
 341              $sql .= " AND r.shortname $rsql";
 342              $params = array_merge($params, $rparams);
 343          }
 344  
 345          list($sort, $sortparams) = users_order_by_sql('u');
 346          $sql .= " ORDER BY $sort";
 347  
 348          $rs = $DB->get_recordset_sql($sql, array_merge($params, $sortparams));
 349          $list = array();
 350          foreach ($rs as $record) {
 351              $list[] = $record;
 352          }
 353          $rs->close();
 354  
 355          return $list;
 356      }
 357  }