[ Index ]

PHP Cross Reference of Unnamed Project

title

Body

[close]

/enrol/flatfile/ -> lib.php (source)

   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   * Flatfile enrolment plugin.
  19   *
  20   * This plugin lets the user specify a "flatfile" (CSV) containing enrolment information.
  21   * On a regular cron cycle, the specified file is parsed and then deleted.
  22   *
  23   * @package    enrol_flatfile
  24   * @copyright  2010 Eugene Venter
  25   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  26   */
  27  
  28  defined('MOODLE_INTERNAL') || die();
  29  
  30  
  31  /**
  32   * Flatfile enrolment plugin implementation.
  33   *
  34   * Comma separated file assumed to have four or six fields per line:
  35   *   operation, role, idnumber(user), idnumber(course) [, starttime [, endtime]]
  36   * where:
  37   *   operation        = add | del
  38   *   role             = student | teacher | teacheredit
  39   *   idnumber(user)   = idnumber in the user table NB not id
  40   *   idnumber(course) = idnumber in the course table NB not id
  41   *   starttime        = start time (in seconds since epoch) - optional
  42   *   endtime          = end time (in seconds since epoch) - optional
  43   *
  44   * @author  Eugene Venter - based on code by Petr Skoda, Martin Dougiamas, Martin Langhoff and others
  45   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  46   */
  47  class enrol_flatfile_plugin extends enrol_plugin {
  48      protected $lasternoller = null;
  49      protected $lasternollercourseid = 0;
  50  
  51      /**
  52       * Does this plugin assign protected roles are can they be manually removed?
  53       * @return bool - false means anybody may tweak roles, it does not use itemid and component when assigning roles
  54       */
  55      public function roles_protected() {
  56          return false;
  57      }
  58  
  59      /**
  60       * Does this plugin allow manual unenrolment of all users?
  61       * All plugins allowing this must implement 'enrol/xxx:unenrol' capability
  62       *
  63       * @param stdClass $instance course enrol instance
  64       * @return bool - true means user with 'enrol/xxx:unenrol' may unenrol others freely, false means nobody may touch user_enrolments
  65       */
  66      public function allow_unenrol(stdClass $instance) {
  67          return true;
  68      }
  69  
  70      /**
  71       * Does this plugin allow manual unenrolment of a specific user?
  72       * All plugins allowing this must implement 'enrol/xxx:unenrol' capability
  73       *
  74       * This is useful especially for synchronisation plugins that
  75       * do suspend instead of full unenrolment.
  76       *
  77       * @param stdClass $instance course enrol instance
  78       * @param stdClass $ue record from user_enrolments table, specifies user
  79       *
  80       * @return bool - true means user with 'enrol/xxx:unenrol' may unenrol this user, false means nobody may touch this user enrolment
  81       */
  82      public function allow_unenrol_user(stdClass $instance, stdClass $ue) {
  83          return true;
  84      }
  85  
  86      /**
  87       * Does this plugin allow manual changes in user_enrolments table?
  88       *
  89       * All plugins allowing this must implement 'enrol/xxx:manage' capability
  90       *
  91       * @param stdClass $instance course enrol instance
  92       * @return bool - true means it is possible to change enrol period and status in user_enrolments table
  93       */
  94      public function allow_manage(stdClass $instance) {
  95          return true;
  96      }
  97  
  98      /**
  99       * Is it possible to delete enrol instance via standard UI?
 100       *
 101       * @param object $instance
 102       * @return bool
 103       */
 104      public function can_delete_instance($instance) {
 105          $context = context_course::instance($instance->courseid);
 106          return has_capability('enrol/flatfile:manage', $context);
 107      }
 108  
 109      /**
 110       * Is it possible to hide/show enrol instance via standard UI?
 111       *
 112       * @param stdClass $instance
 113       * @return bool
 114       */
 115      public function can_hide_show_instance($instance) {
 116          $context = context_course::instance($instance->courseid);
 117          return has_capability('enrol/flatfile:manage', $context);
 118      }
 119  
 120      /**
 121       * Gets an array of the user enrolment actions.
 122       *
 123       * @param course_enrolment_manager $manager
 124       * @param stdClass $ue A user enrolment object
 125       * @return array An array of user_enrolment_actions
 126       */
 127      public function get_user_enrolment_actions(course_enrolment_manager $manager, $ue) {
 128          $actions = array();
 129          $context = $manager->get_context();
 130          $instance = $ue->enrolmentinstance;
 131          $params = $manager->get_moodlepage()->url->params();
 132          $params['ue'] = $ue->id;
 133          if ($this->allow_unenrol_user($instance, $ue) && has_capability("enrol/flatfile:unenrol", $context)) {
 134              $url = new moodle_url('/enrol/unenroluser.php', $params);
 135              $actions[] = new user_enrolment_action(new pix_icon('t/delete', ''), get_string('unenrol', 'enrol'), $url, array('class'=>'unenrollink', 'rel'=>$ue->id));
 136          }
 137          if ($this->allow_manage($instance) && has_capability("enrol/flatfile:manage", $context)) {
 138              $url = new moodle_url('/enrol/editenrolment.php', $params);
 139              $actions[] = new user_enrolment_action(new pix_icon('t/edit', ''), get_string('edit'), $url, array('class'=>'editenrollink', 'rel'=>$ue->id));
 140          }
 141          return $actions;
 142      }
 143  
 144      /**
 145       * Enrol user into course via enrol instance.
 146       *
 147       * @param stdClass $instance
 148       * @param int $userid
 149       * @param int $roleid optional role id
 150       * @param int $timestart 0 means unknown
 151       * @param int $timeend 0 means forever
 152       * @param int $status default to ENROL_USER_ACTIVE for new enrolments, no change by default in updates
 153       * @param bool $recovergrades restore grade history
 154       * @return void
 155       */
 156      public function enrol_user(stdClass $instance, $userid, $roleid = null, $timestart = 0, $timeend = 0, $status = null, $recovergrades = null) {
 157          parent::enrol_user($instance, $userid, null, $timestart, $timeend, $status, $recovergrades);
 158          if ($roleid) {
 159              $context = context_course::instance($instance->courseid, MUST_EXIST);
 160              role_assign($roleid, $userid, $context->id, 'enrol_'.$this->get_name(), $instance->id);
 161          }
 162      }
 163  
 164      /**
 165       * Execute synchronisation.
 166       * @param progress_trace
 167       * @return int exit code, 0 means ok, 2 means plugin disabled
 168       */
 169      public function sync(progress_trace $trace) {
 170          if (!enrol_is_enabled('flatfile')) {
 171              return 2;
 172          }
 173  
 174          $mailadmins = $this->get_config('mailadmins', 0);
 175  
 176          if ($mailadmins) {
 177              $buffer = new progress_trace_buffer(new text_progress_trace(), false);
 178              $trace = new combined_progress_trace(array($trace, $buffer));
 179          }
 180  
 181          $processed = false;
 182  
 183          $processed = $this->process_file($trace) || $processed;
 184          $processed = $this->process_buffer($trace) || $processed;
 185          $processed = $this->process_expirations($trace) || $processed;
 186  
 187          if ($processed and $mailadmins) {
 188              if ($log = $buffer->get_buffer()) {
 189                  $eventdata = new stdClass();
 190                  $eventdata->modulename        = 'moodle';
 191                  $eventdata->component         = 'enrol_flatfile';
 192                  $eventdata->name              = 'flatfile_enrolment';
 193                  $eventdata->userfrom          = get_admin();
 194                  $eventdata->userto            = get_admin();
 195                  $eventdata->subject           = 'Flatfile Enrolment Log';
 196                  $eventdata->fullmessage       = $log;
 197                  $eventdata->fullmessageformat = FORMAT_PLAIN;
 198                  $eventdata->fullmessagehtml   = '';
 199                  $eventdata->smallmessage      = '';
 200                  message_send($eventdata);
 201              }
 202              $buffer->reset_buffer();
 203          }
 204  
 205          return 0;
 206      }
 207  
 208      /**
 209       * Sorry, we do not want to show paths in cron output.
 210       *
 211       * @param string $filepath
 212       * @return string
 213       */
 214      protected function obfuscate_filepath($filepath) {
 215          global $CFG;
 216  
 217          if (strpos($filepath, $CFG->dataroot.'/') === 0 or strpos($filepath, $CFG->dataroot.'\\') === 0) {
 218              $disclosefile = '$CFG->dataroot'.substr($filepath, strlen($CFG->dataroot));
 219  
 220          } else if (strpos($filepath, $CFG->dirroot.'/') === 0 or strpos($filepath, $CFG->dirroot.'\\') === 0) {
 221              $disclosefile = '$CFG->dirroot'.substr($filepath, strlen($CFG->dirroot));
 222  
 223          } else {
 224              $disclosefile = basename($filepath);
 225          }
 226  
 227          return $disclosefile;
 228      }
 229  
 230      /**
 231       * Process flatfile.
 232       * @param progress_trace $trace
 233       * @return bool true if any data processed, false if not
 234       */
 235      protected function process_file(progress_trace $trace) {
 236          global $CFG, $DB;
 237  
 238          // We may need more memory here.
 239          core_php_time_limit::raise();
 240          raise_memory_limit(MEMORY_HUGE);
 241  
 242          $filelocation = $this->get_config('location');
 243          if (empty($filelocation)) {
 244              // Default legacy location.
 245              $filelocation = "$CFG->dataroot/1/enrolments.txt";
 246          }
 247          $disclosefile = $this->obfuscate_filepath($filelocation);
 248  
 249          if (!file_exists($filelocation)) {
 250              $trace->output("Flatfile enrolments file not found: $disclosefile");
 251              $trace->finished();
 252              return false;
 253          }
 254          $trace->output("Processing flat file enrolments from: $disclosefile ...");
 255  
 256          $content = file_get_contents($filelocation);
 257  
 258          if ($content !== false) {
 259  
 260              $rolemap = $this->get_role_map($trace);
 261  
 262              $content = core_text::convert($content, $this->get_config('encoding', 'utf-8'), 'utf-8');
 263              $content = str_replace("\r", '', $content);
 264              $content = explode("\n", $content);
 265  
 266              $line = 0;
 267              foreach($content as $fields) {
 268                  $line++;
 269  
 270                  if (trim($fields) === '') {
 271                      // Empty lines are ignored.
 272                      continue;
 273                  }
 274  
 275                  // Deal with different separators.
 276                  if (strpos($fields, ',') !== false) {
 277                      $fields = explode(',', $fields);
 278                  } else {
 279                      $fields = explode(';', $fields);
 280                  }
 281  
 282                  // If a line is incorrectly formatted ie does not have 4 comma separated fields then ignore it.
 283                  if (count($fields) < 4 or count($fields) > 6) {
 284                      $trace->output("Line incorrectly formatted - ignoring $line", 1);
 285                      continue;
 286                  }
 287  
 288                  $fields[0] = trim(core_text::strtolower($fields[0]));
 289                  $fields[1] = trim(core_text::strtolower($fields[1]));
 290                  $fields[2] = trim($fields[2]);
 291                  $fields[3] = trim($fields[3]);
 292                  $fields[4] = isset($fields[4]) ? (int)trim($fields[4]) : 0;
 293                  $fields[5] = isset($fields[5]) ? (int)trim($fields[5]) : 0;
 294  
 295                  // Deal with quoted values - all or nothing, we need to support "' in idnumbers, sorry.
 296                  if (strpos($fields[0], "'") === 0) {
 297                      foreach ($fields as $k=>$v) {
 298                          $fields[$k] = trim($v, "'");
 299                      }
 300                  } else if (strpos($fields[0], '"') === 0) {
 301                      foreach ($fields as $k=>$v) {
 302                          $fields[$k] = trim($v, '"');
 303                      }
 304                  }
 305  
 306                  $trace->output("$line: $fields[0], $fields[1], $fields[2], $fields[3], $fields[4], $fields[5]", 1);
 307  
 308                  // Check correct formatting of operation field.
 309                  if ($fields[0] !== "add" and $fields[0] !== "del") {
 310                      $trace->output("Unknown operation in field 1 - ignoring line $line", 1);
 311                      continue;
 312                  }
 313  
 314                  // Check correct formatting of role field.
 315                  if (!isset($rolemap[$fields[1]])) {
 316                      $trace->output("Unknown role in field2 - ignoring line $line", 1);
 317                      continue;
 318                  }
 319                  $roleid = $rolemap[$fields[1]];
 320  
 321                  if (empty($fields[2]) or !$user = $DB->get_record("user", array("idnumber"=>$fields[2], 'deleted'=>0))) {
 322                      $trace->output("Unknown user idnumber or deleted user in field 3 - ignoring line $line", 1);
 323                      continue;
 324                  }
 325  
 326                  if (!$course = $DB->get_record("course", array("idnumber"=>$fields[3]))) {
 327                      $trace->output("Unknown course idnumber in field 4 - ignoring line $line", 1);
 328                      continue;
 329                  }
 330  
 331                  if ($fields[4] > $fields[5] and $fields[5] != 0) {
 332                      $trace->output("Start time was later than end time - ignoring line $line", 1);
 333                      continue;
 334                  }
 335  
 336                  $this->process_records($trace, $fields[0], $roleid, $user, $course, $fields[4], $fields[5]);
 337              }
 338  
 339              unset($content);
 340          }
 341  
 342          if (!unlink($filelocation)) {
 343              $eventdata = new stdClass();
 344              $eventdata->modulename        = 'moodle';
 345              $eventdata->component         = 'enrol_flatfile';
 346              $eventdata->name              = 'flatfile_enrolment';
 347              $eventdata->userfrom          = get_admin();
 348              $eventdata->userto            = get_admin();
 349              $eventdata->subject           = get_string('filelockedmailsubject', 'enrol_flatfile');
 350              $eventdata->fullmessage       = get_string('filelockedmail', 'enrol_flatfile', $filelocation);
 351              $eventdata->fullmessageformat = FORMAT_PLAIN;
 352              $eventdata->fullmessagehtml   = '';
 353              $eventdata->smallmessage      = '';
 354              message_send($eventdata);
 355              $trace->output("Error deleting enrolment file: $disclosefile", 1);
 356          } else {
 357              $trace->output("Deleted enrolment file", 1);
 358          }
 359  
 360          $trace->output("...finished enrolment file processing.");
 361          $trace->finished();
 362  
 363          return true;
 364      }
 365  
 366      /**
 367       * Process any future enrollments stored in the buffer.
 368       * @param progress_trace $trace
 369       * @return bool true if any data processed, false if not
 370       */
 371      protected function process_buffer(progress_trace $trace) {
 372          global $DB;
 373  
 374          if (!$future_enrols = $DB->get_records_select('enrol_flatfile', "timestart < ?", array(time()))) {
 375              $trace->output("No enrolments to be processed in flatfile buffer");
 376              $trace->finished();
 377              return false;
 378          }
 379  
 380          $trace->output("Starting processing of flatfile buffer");
 381          foreach($future_enrols as $en) {
 382              $user = $DB->get_record('user', array('id'=>$en->userid));
 383              $course = $DB->get_record('course', array('id'=>$en->courseid));
 384              if ($user and $course) {
 385                  $trace->output("buffer: $en->action $en->roleid $user->id $course->id $en->timestart $en->timeend", 1);
 386                  $this->process_records($trace, $en->action, $en->roleid, $user, $course, $en->timestart, $en->timeend, false);
 387              }
 388              $DB->delete_records('enrol_flatfile', array('id'=>$en->id));
 389          }
 390          $trace->output("Finished processing of flatfile buffer");
 391          $trace->finished();
 392  
 393          return true;
 394      }
 395  
 396      /**
 397       * Process user enrolment line.
 398       *
 399       * @param progress_trace $trace
 400       * @param string $action
 401       * @param int $roleid
 402       * @param stdClass $user
 403       * @param stdClass $course
 404       * @param int $timestart
 405       * @param int $timeend
 406       * @param bool $buffer_if_future
 407       */
 408      protected function process_records(progress_trace $trace, $action, $roleid, $user, $course, $timestart, $timeend, $buffer_if_future = true) {
 409          global $CFG, $DB;
 410  
 411          // Check if timestart is for future processing.
 412          if ($timestart > time() and $buffer_if_future) {
 413              // Populate into enrol_flatfile table as a future role to be assigned by cron.
 414              // Note: since 2.0 future enrolments do not cause problems if you disable guest access.
 415              $future_en = new stdClass();
 416              $future_en->action       = $action;
 417              $future_en->roleid       = $roleid;
 418              $future_en->userid       = $user->id;
 419              $future_en->courseid     = $course->id;
 420              $future_en->timestart    = $timestart;
 421              $future_en->timeend      = $timeend;
 422              $future_en->timemodified = time();
 423              $DB->insert_record('enrol_flatfile', $future_en);
 424              $trace->output("User $user->id will be enrolled later into course $course->id using role $roleid ($timestart, $timeend)", 1);
 425              return;
 426          }
 427  
 428          $context = context_course::instance($course->id);
 429  
 430          if ($action === 'add') {
 431              // Clear the buffer just in case there were some future enrolments.
 432              $DB->delete_records('enrol_flatfile', array('userid'=>$user->id, 'courseid'=>$course->id, 'roleid'=>$roleid));
 433  
 434              $instance = $DB->get_record('enrol', array('courseid' => $course->id, 'enrol' => 'flatfile'));
 435              if (empty($instance)) {
 436                  // Only add an enrol instance to the course if non-existent.
 437                  $enrolid = $this->add_instance($course);
 438                  $instance = $DB->get_record('enrol', array('id' => $enrolid));
 439              }
 440  
 441              $notify = false;
 442              if ($ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$user->id))) {
 443                  // Update only.
 444                  $this->update_user_enrol($instance, $user->id, ENROL_USER_ACTIVE, $timestart, $timeend);
 445                  if (!$DB->record_exists('role_assignments', array('contextid'=>$context->id, 'roleid'=>$roleid, 'userid'=>$user->id, 'component'=>'enrol_flatfile', 'itemid'=>$instance->id))) {
 446                      role_assign($roleid, $user->id, $context->id, 'enrol_flatfile', $instance->id);
 447                  }
 448                  $trace->output("User $user->id enrolment updated in course $course->id using role $roleid ($timestart, $timeend)", 1);
 449  
 450              } else {
 451                  // Enrol the user with this plugin instance.
 452                  $this->enrol_user($instance, $user->id, $roleid, $timestart, $timeend);
 453                  $trace->output("User $user->id enrolled in course $course->id using role $roleid ($timestart, $timeend)", 1);
 454                  $notify = true;
 455              }
 456  
 457              if ($notify and $this->get_config('mailstudents')) {
 458                  $oldforcelang = force_current_language($user->lang);
 459  
 460                  // Send welcome notification to enrolled users.
 461                  $a = new stdClass();
 462                  $a->coursename = format_string($course->fullname, true, array('context' => $context));
 463                  $a->profileurl = "$CFG->wwwroot/user/view.php?id=$user->id&amp;course=$course->id";
 464                  $subject = get_string('enrolmentnew', 'enrol', format_string($course->shortname, true, array('context' => $context)));
 465  
 466                  $eventdata = new stdClass();
 467                  $eventdata->modulename        = 'moodle';
 468                  $eventdata->component         = 'enrol_flatfile';
 469                  $eventdata->name              = 'flatfile_enrolment';
 470                  $eventdata->userfrom          = $this->get_enroller($course->id);
 471                  $eventdata->userto            = $user;
 472                  $eventdata->subject           = $subject;
 473                  $eventdata->fullmessage       = get_string('welcometocoursetext', '', $a);
 474                  $eventdata->fullmessageformat = FORMAT_PLAIN;
 475                  $eventdata->fullmessagehtml   = '';
 476                  $eventdata->smallmessage      = '';
 477                  if (message_send($eventdata)) {
 478                      $trace->output("Notified enrolled user", 1);
 479                  } else {
 480                      $trace->output("Failed to notify enrolled user", 1);
 481                  }
 482  
 483                  force_current_language($oldforcelang);
 484              }
 485  
 486              if ($notify and $this->get_config('mailteachers', 0)) {
 487                  // Notify person responsible for enrolments.
 488                  $enroller = $this->get_enroller($course->id);
 489  
 490                  $oldforcelang = force_current_language($enroller->lang);
 491  
 492                  $a = new stdClass();
 493                  $a->course = format_string($course->fullname, true, array('context' => $context));
 494                  $a->user = fullname($user);
 495                  $subject = get_string('enrolmentnew', 'enrol', format_string($course->shortname, true, array('context' => $context)));
 496  
 497                  $eventdata = new stdClass();
 498                  $eventdata->modulename        = 'moodle';
 499                  $eventdata->component         = 'enrol_flatfile';
 500                  $eventdata->name              = 'flatfile_enrolment';
 501                  $eventdata->userfrom          = get_admin();
 502                  $eventdata->userto            = $enroller;
 503                  $eventdata->subject           = $subject;
 504                  $eventdata->fullmessage       = get_string('enrolmentnewuser', 'enrol', $a);
 505                  $eventdata->fullmessageformat = FORMAT_PLAIN;
 506                  $eventdata->fullmessagehtml   = '';
 507                  $eventdata->smallmessage      = '';
 508                  if (message_send($eventdata)) {
 509                      $trace->output("Notified enroller {$eventdata->userto->id}", 1);
 510                  } else {
 511                      $trace->output("Failed to notify enroller {$eventdata->userto->id}", 1);
 512                  }
 513  
 514                  force_current_language($oldforcelang);
 515              }
 516              return;
 517  
 518          } else if ($action === 'del') {
 519              // Clear the buffer just in case there were some future enrolments.
 520              $DB->delete_records('enrol_flatfile', array('userid'=>$user->id, 'courseid'=>$course->id, 'roleid'=>$roleid));
 521  
 522              $action = $this->get_config('unenrolaction');
 523              if ($action == ENROL_EXT_REMOVED_KEEP) {
 524                  $trace->output("del action is ignored", 1);
 525                  return;
 526              }
 527  
 528              // Loops through all enrolment methods, try to unenrol if roleid somehow matches.
 529              $instances = $DB->get_records('enrol', array('courseid' => $course->id));
 530              $unenrolled = false;
 531              foreach ($instances as $instance) {
 532                  if (!$ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$user->id))) {
 533                      continue;
 534                  }
 535                  if ($instance->enrol === 'flatfile') {
 536                      $plugin = $this;
 537                  } else {
 538                      if (!enrol_is_enabled($instance->enrol)) {
 539                          continue;
 540                      }
 541                      if (!$plugin = enrol_get_plugin($instance->enrol)) {
 542                          continue;
 543                      }
 544                      if (!$plugin->allow_unenrol_user($instance, $ue)) {
 545                          continue;
 546                      }
 547                  }
 548  
 549                  // For some reason the del action includes a role name, this complicates everything.
 550                  $componentroles = array();
 551                  $manualroles = array();
 552                  $ras = $DB->get_records('role_assignments', array('userid'=>$user->id, 'contextid'=>$context->id));
 553                  foreach ($ras as $ra) {
 554                      if ($ra->component === '') {
 555                          $manualroles[$ra->roleid] = $ra->roleid;
 556                      } else if ($ra->component === 'enrol_'.$instance->enrol and $ra->itemid == $instance->id) {
 557                          $componentroles[$ra->roleid] = $ra->roleid;
 558                      }
 559                  }
 560  
 561                  if ($componentroles and !isset($componentroles[$roleid])) {
 562                      // Do not unenrol using this method, user has some other protected role!
 563                      continue;
 564  
 565                  } else if (empty($ras)) {
 566                      // If user does not have any roles then let's just suspend as many methods as possible.
 567  
 568                  } else if (!$plugin->roles_protected()) {
 569                      if (!$componentroles and $manualroles and !isset($manualroles[$roleid])) {
 570                          // Most likely we want to keep users enrolled because they have some other course roles.
 571                          continue;
 572                      }
 573                  }
 574  
 575                  if ($action == ENROL_EXT_REMOVED_UNENROL) {
 576                      $unenrolled = true;
 577                      if (!$plugin->roles_protected()) {
 578                          role_unassign_all(array('contextid'=>$context->id, 'userid'=>$user->id, 'roleid'=>$roleid, 'component'=>'', 'itemid'=>0), true);
 579                      }
 580                      $plugin->unenrol_user($instance, $user->id);
 581                      $trace->output("User $user->id was unenrolled from course $course->id (enrol_$instance->enrol)", 1);
 582  
 583                  } else if ($action == ENROL_EXT_REMOVED_SUSPENDNOROLES) {
 584                      if ($plugin->allow_manage($instance)) {
 585                          if ($ue->status == ENROL_USER_ACTIVE) {
 586                              $unenrolled = true;
 587                              $plugin->update_user_enrol($instance, $user->id, ENROL_USER_SUSPENDED);
 588                              if (!$plugin->roles_protected()) {
 589                                  role_unassign_all(array('contextid'=>$context->id, 'userid'=>$user->id, 'component'=>'enrol_'.$instance->enrol, 'itemid'=>$instance->id), true);
 590                                  role_unassign_all(array('contextid'=>$context->id, 'userid'=>$user->id, 'roleid'=>$roleid, 'component'=>'', 'itemid'=>0), true);
 591                              }
 592                              $trace->output("User $user->id enrolment was suspended in course $course->id (enrol_$instance->enrol)", 1);
 593                          }
 594                      }
 595                  }
 596              }
 597  
 598              if (!$unenrolled) {
 599                  if (0 == $DB->count_records('role_assignments', array('userid'=>$user->id, 'contextid'=>$context->id))) {
 600                      role_unassign_all(array('contextid'=>$context->id, 'userid'=>$user->id, 'component'=>'', 'itemid'=>0), true);
 601                  }
 602                  $trace->output("User $user->id (with role $roleid) not unenrolled from course $course->id", 1);
 603              }
 604  
 605              return;
 606          }
 607      }
 608  
 609      /**
 610       * Returns the user who is responsible for flatfile enrolments in given curse.
 611       *
 612       * Usually it is the first editing teacher - the person with "highest authority"
 613       * as defined by sort_by_roleassignment_authority() having 'enrol/flatfile:manage'
 614       * or 'moodle/role:assign' capability.
 615       *
 616       * @param int $courseid enrolment instance id
 617       * @return stdClass user record
 618       */
 619      protected function get_enroller($courseid) {
 620          if ($this->lasternollercourseid == $courseid and $this->lasternoller) {
 621              return $this->lasternoller;
 622          }
 623  
 624          $context = context_course::instance($courseid);
 625  
 626          $users = get_enrolled_users($context, 'enrol/flatfile:manage');
 627          if (!$users) {
 628              $users = get_enrolled_users($context, 'moodle/role:assign');
 629          }
 630  
 631          if ($users) {
 632              $users = sort_by_roleassignment_authority($users, $context);
 633              $this->lasternoller = reset($users);
 634              unset($users);
 635          } else {
 636              $this->lasternoller = get_admin();
 637          }
 638  
 639          $this->lasternollercourseid == $courseid;
 640  
 641          return $this->lasternoller;
 642      }
 643  
 644      /**
 645       * Returns a mapping of ims roles to role ids.
 646       *
 647       * @param progress_trace $trace
 648       * @return array imsrolename=>roleid
 649       */
 650      protected function get_role_map(progress_trace $trace) {
 651          global $DB;
 652  
 653          // Get all roles.
 654          $rolemap = array();
 655          $roles = $DB->get_records('role', null, '', 'id, name, shortname');
 656          foreach ($roles as $id=>$role) {
 657              $alias = $this->get_config('map_'.$id, $role->shortname, '');
 658              $alias = trim(core_text::strtolower($alias));
 659              if ($alias === '') {
 660                  // Either not configured yet or somebody wants to skip these intentionally.
 661                  continue;
 662              }
 663              if (isset($rolemap[$alias])) {
 664                  $trace->output("Duplicate role alias $alias detected!");
 665              } else {
 666                  $rolemap[$alias] = $id;
 667              }
 668          }
 669  
 670          return $rolemap;
 671      }
 672  
 673      /**
 674       * Restore instance and map settings.
 675       *
 676       * @param restore_enrolments_structure_step $step
 677       * @param stdClass $data
 678       * @param stdClass $course
 679       * @param int $oldid
 680       */
 681      public function restore_instance(restore_enrolments_structure_step $step, stdClass $data, $course, $oldid) {
 682          global $DB;
 683  
 684          if ($instance = $DB->get_record('enrol', array('courseid'=>$course->id, 'enrol'=>$this->get_name()))) {
 685              $instanceid = $instance->id;
 686          } else {
 687              $instanceid = $this->add_instance($course);
 688          }
 689          $step->set_mapping('enrol', $oldid, $instanceid);
 690      }
 691  
 692      /**
 693       * Restore user enrolment.
 694       *
 695       * @param restore_enrolments_structure_step $step
 696       * @param stdClass $data
 697       * @param stdClass $instance
 698       * @param int $oldinstancestatus
 699       * @param int $userid
 700       */
 701      public function restore_user_enrolment(restore_enrolments_structure_step $step, $data, $instance, $userid, $oldinstancestatus) {
 702          $this->enrol_user($instance, $userid, null, $data->timestart, $data->timeend, $data->status);
 703      }
 704  
 705      /**
 706       * Restore role assignment.
 707       *
 708       * @param stdClass $instance
 709       * @param int $roleid
 710       * @param int $userid
 711       * @param int $contextid
 712       */
 713      public function restore_role_assignment($instance, $roleid, $userid, $contextid) {
 714          role_assign($roleid, $userid, $contextid, 'enrol_'.$instance->enrol, $instance->id);
 715      }
 716  }


Generated: Thu Aug 11 10:00:09 2016 Cross-referenced by PHPXref 0.7.1