[ Index ]

PHP Cross Reference of moodle-2.8

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      public function cron() {
 165          $trace = new text_progress_trace();
 166          $this->sync($trace);
 167      }
 168  
 169      /**
 170       * Execute synchronisation.
 171       * @param progress_trace
 172       * @return int exit code, 0 means ok, 2 means plugin disabled
 173       */
 174      public function sync(progress_trace $trace) {
 175          if (!enrol_is_enabled('flatfile')) {
 176              return 2;
 177          }
 178  
 179          $mailadmins = $this->get_config('mailadmins', 0);
 180  
 181          if ($mailadmins) {
 182              $buffer = new progress_trace_buffer(new text_progress_trace(), false);
 183              $trace = new combined_progress_trace(array($trace, $buffer));
 184          }
 185  
 186          $processed = false;
 187  
 188          $processed = $this->process_file($trace) || $processed;
 189          $processed = $this->process_buffer($trace) || $processed;
 190          $processed = $this->process_expirations($trace) || $processed;
 191  
 192          if ($processed and $mailadmins) {
 193              if ($log = $buffer->get_buffer()) {
 194                  $eventdata = new stdClass();
 195                  $eventdata->modulename        = 'moodle';
 196                  $eventdata->component         = 'enrol_flatfile';
 197                  $eventdata->name              = 'flatfile_enrolment';
 198                  $eventdata->userfrom          = get_admin();
 199                  $eventdata->userto            = get_admin();
 200                  $eventdata->subject           = 'Flatfile Enrolment Log';
 201                  $eventdata->fullmessage       = $log;
 202                  $eventdata->fullmessageformat = FORMAT_PLAIN;
 203                  $eventdata->fullmessagehtml   = '';
 204                  $eventdata->smallmessage      = '';
 205                  message_send($eventdata);
 206              }
 207              $buffer->reset_buffer();
 208          }
 209  
 210          return 0;
 211      }
 212  
 213      /**
 214       * Sorry, we do not want to show paths in cron output.
 215       *
 216       * @param string $filepath
 217       * @return string
 218       */
 219      protected function obfuscate_filepath($filepath) {
 220          global $CFG;
 221  
 222          if (strpos($filepath, $CFG->dataroot.'/') === 0 or strpos($filepath, $CFG->dataroot.'\\') === 0) {
 223              $disclosefile = '$CFG->dataroot'.substr($filepath, strlen($CFG->dataroot));
 224  
 225          } else if (strpos($filepath, $CFG->dirroot.'/') === 0 or strpos($filepath, $CFG->dirroot.'\\') === 0) {
 226              $disclosefile = '$CFG->dirroot'.substr($filepath, strlen($CFG->dirroot));
 227  
 228          } else {
 229              $disclosefile = basename($filepath);
 230          }
 231  
 232          return $disclosefile;
 233      }
 234  
 235      /**
 236       * Process flatfile.
 237       * @param progress_trace $trace
 238       * @return bool true if any data processed, false if not
 239       */
 240      protected function process_file(progress_trace $trace) {
 241          global $CFG, $DB;
 242  
 243          // We may need more memory here.
 244          core_php_time_limit::raise();
 245          raise_memory_limit(MEMORY_HUGE);
 246  
 247          $filelocation = $this->get_config('location');
 248          if (empty($filelocation)) {
 249              // Default legacy location.
 250              $filelocation = "$CFG->dataroot/1/enrolments.txt";
 251          }
 252          $disclosefile = $this->obfuscate_filepath($filelocation);
 253  
 254          if (!file_exists($filelocation)) {
 255              $trace->output("Flatfile enrolments file not found: $disclosefile");
 256              $trace->finished();
 257              return false;
 258          }
 259          $trace->output("Processing flat file enrolments from: $disclosefile ...");
 260  
 261          $content = file_get_contents($filelocation);
 262  
 263          if ($content !== false) {
 264  
 265              $rolemap = $this->get_role_map($trace);
 266  
 267              $content = core_text::convert($content, $this->get_config('encoding', 'utf-8'), 'utf-8');
 268              $content = str_replace("\r", '', $content);
 269              $content = explode("\n", $content);
 270  
 271              $line = 0;
 272              foreach($content as $fields) {
 273                  $line++;
 274  
 275                  if (trim($fields) === '') {
 276                      // Empty lines are ignored.
 277                      continue;
 278                  }
 279  
 280                  // Deal with different separators.
 281                  if (strpos($fields, ',') !== false) {
 282                      $fields = explode(',', $fields);
 283                  } else {
 284                      $fields = explode(';', $fields);
 285                  }
 286  
 287                  // If a line is incorrectly formatted ie does not have 4 comma separated fields then ignore it.
 288                  if (count($fields) < 4 or count($fields) > 6) {
 289                      $trace->output("Line incorrectly formatted - ignoring $line", 1);
 290                      continue;
 291                  }
 292  
 293                  $fields[0] = trim(core_text::strtolower($fields[0]));
 294                  $fields[1] = trim(core_text::strtolower($fields[1]));
 295                  $fields[2] = trim($fields[2]);
 296                  $fields[3] = trim($fields[3]);
 297                  $fields[4] = isset($fields[4]) ? (int)trim($fields[4]) : 0;
 298                  $fields[5] = isset($fields[5]) ? (int)trim($fields[5]) : 0;
 299  
 300                  // Deal with quoted values - all or nothing, we need to support "' in idnumbers, sorry.
 301                  if (strpos($fields[0], "'") === 0) {
 302                      foreach ($fields as $k=>$v) {
 303                          $fields[$k] = trim($v, "'");
 304                      }
 305                  } else if (strpos($fields[0], '"') === 0) {
 306                      foreach ($fields as $k=>$v) {
 307                          $fields[$k] = trim($v, '"');
 308                      }
 309                  }
 310  
 311                  $trace->output("$line: $fields[0], $fields[1], $fields[2], $fields[3], $fields[4], $fields[5]", 1);
 312  
 313                  // Check correct formatting of operation field.
 314                  if ($fields[0] !== "add" and $fields[0] !== "del") {
 315                      $trace->output("Unknown operation in field 1 - ignoring line $line", 1);
 316                      continue;
 317                  }
 318  
 319                  // Check correct formatting of role field.
 320                  if (!isset($rolemap[$fields[1]])) {
 321                      $trace->output("Unknown role in field2 - ignoring line $line", 1);
 322                      continue;
 323                  }
 324                  $roleid = $rolemap[$fields[1]];
 325  
 326                  if (empty($fields[2]) or !$user = $DB->get_record("user", array("idnumber"=>$fields[2], 'deleted'=>0))) {
 327                      $trace->output("Unknown user idnumber or deleted user in field 3 - ignoring line $line", 1);
 328                      continue;
 329                  }
 330  
 331                  if (!$course = $DB->get_record("course", array("idnumber"=>$fields[3]))) {
 332                      $trace->output("Unknown course idnumber in field 4 - ignoring line $line", 1);
 333                      continue;
 334                  }
 335  
 336                  if ($fields[4] > $fields[5] and $fields[5] != 0) {
 337                      $trace->output("Start time was later than end time - ignoring line $line", 1);
 338                      continue;
 339                  }
 340  
 341                  $this->process_records($trace, $fields[0], $roleid, $user, $course, $fields[4], $fields[5]);
 342              }
 343  
 344              unset($content);
 345          }
 346  
 347          if (!unlink($filelocation)) {
 348              $eventdata = new stdClass();
 349              $eventdata->modulename        = 'moodle';
 350              $eventdata->component         = 'enrol_flatfile';
 351              $eventdata->name              = 'flatfile_enrolment';
 352              $eventdata->userfrom          = get_admin();
 353              $eventdata->userto            = get_admin();
 354              $eventdata->subject           = get_string('filelockedmailsubject', 'enrol_flatfile');
 355              $eventdata->fullmessage       = get_string('filelockedmail', 'enrol_flatfile', $filelocation);
 356              $eventdata->fullmessageformat = FORMAT_PLAIN;
 357              $eventdata->fullmessagehtml   = '';
 358              $eventdata->smallmessage      = '';
 359              message_send($eventdata);
 360              $trace->output("Error deleting enrolment file: $disclosefile", 1);
 361          } else {
 362              $trace->output("Deleted enrolment file", 1);
 363          }
 364  
 365          $trace->output("...finished enrolment file processing.");
 366          $trace->finished();
 367  
 368          return true;
 369      }
 370  
 371      /**
 372       * Process any future enrollments stored in the buffer.
 373       * @param progress_trace $trace
 374       * @return bool true if any data processed, false if not
 375       */
 376      protected function process_buffer(progress_trace $trace) {
 377          global $DB;
 378  
 379          if (!$future_enrols = $DB->get_records_select('enrol_flatfile', "timestart < ?", array(time()))) {
 380              $trace->output("No enrolments to be processed in flatfile buffer");
 381              $trace->finished();
 382              return false;
 383          }
 384  
 385          $trace->output("Starting processing of flatfile buffer");
 386          foreach($future_enrols as $en) {
 387              $user = $DB->get_record('user', array('id'=>$en->userid));
 388              $course = $DB->get_record('course', array('id'=>$en->courseid));
 389              if ($user and $course) {
 390                  $trace->output("buffer: $en->action $en->roleid $user->id $course->id $en->timestart $en->timeend", 1);
 391                  $this->process_records($trace, $en->action, $en->roleid, $user, $course, $en->timestart, $en->timeend, false);
 392              }
 393              $DB->delete_records('enrol_flatfile', array('id'=>$en->id));
 394          }
 395          $trace->output("Finished processing of flatfile buffer");
 396          $trace->finished();
 397  
 398          return true;
 399      }
 400  
 401      /**
 402       * Process user enrolment line.
 403       *
 404       * @param progress_trace $trace
 405       * @param string $action
 406       * @param int $roleid
 407       * @param stdClass $user
 408       * @param stdClass $course
 409       * @param int $timestart
 410       * @param int $timeend
 411       * @param bool $buffer_if_future
 412       */
 413      protected function process_records(progress_trace $trace, $action, $roleid, $user, $course, $timestart, $timeend, $buffer_if_future = true) {
 414          global $CFG, $DB;
 415  
 416          // Check if timestart is for future processing.
 417          if ($timestart > time() and $buffer_if_future) {
 418              // Populate into enrol_flatfile table as a future role to be assigned by cron.
 419              // Note: since 2.0 future enrolments do not cause problems if you disable guest access.
 420              $future_en = new stdClass();
 421              $future_en->action       = $action;
 422              $future_en->roleid       = $roleid;
 423              $future_en->userid       = $user->id;
 424              $future_en->courseid     = $course->id;
 425              $future_en->timestart    = $timestart;
 426              $future_en->timeend      = $timeend;
 427              $future_en->timemodified = time();
 428              $DB->insert_record('enrol_flatfile', $future_en);
 429              $trace->output("User $user->id will be enrolled later into course $course->id using role $roleid ($timestart, $timeend)", 1);
 430              return;
 431          }
 432  
 433          $context = context_course::instance($course->id);
 434  
 435          if ($action === 'add') {
 436              // Clear the buffer just in case there were some future enrolments.
 437              $DB->delete_records('enrol_flatfile', array('userid'=>$user->id, 'courseid'=>$course->id, 'roleid'=>$roleid));
 438  
 439              $instance = $DB->get_record('enrol', array('courseid' => $course->id, 'enrol' => 'flatfile'));
 440              if (empty($instance)) {
 441                  // Only add an enrol instance to the course if non-existent.
 442                  $enrolid = $this->add_instance($course);
 443                  $instance = $DB->get_record('enrol', array('id' => $enrolid));
 444              }
 445  
 446              $notify = false;
 447              if ($ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$user->id))) {
 448                  // Update only.
 449                  $this->update_user_enrol($instance, $user->id, ENROL_USER_ACTIVE, $roleid, $timestart, $timeend);
 450                  if (!$DB->record_exists('role_assignments', array('contextid'=>$context->id, 'roleid'=>$roleid, 'userid'=>$user->id, 'component'=>'enrol_flatfile', 'itemid'=>$instance->id))) {
 451                      role_assign($roleid, $user->id, $context->id, 'enrol_flatfile', $instance->id);
 452                  }
 453                  $trace->output("User $user->id enrolment updated in course $course->id using role $roleid ($timestart, $timeend)", 1);
 454  
 455              } else {
 456                  // Enrol the user with this plugin instance.
 457                  $this->enrol_user($instance, $user->id, $roleid, $timestart, $timeend);
 458                  $trace->output("User $user->id enrolled in course $course->id using role $roleid ($timestart, $timeend)", 1);
 459                  $notify = true;
 460              }
 461  
 462              if ($notify and $this->get_config('mailstudents')) {
 463                  $oldforcelang = force_current_language($user->lang);
 464  
 465                  // Send welcome notification to enrolled users.
 466                  $a = new stdClass();
 467                  $a->coursename = format_string($course->fullname, true, array('context' => $context));
 468                  $a->profileurl = "$CFG->wwwroot/user/view.php?id=$user->id&amp;course=$course->id";
 469                  $subject = get_string('enrolmentnew', 'enrol', format_string($course->shortname, true, array('context' => $context)));
 470  
 471                  $eventdata = new stdClass();
 472                  $eventdata->modulename        = 'moodle';
 473                  $eventdata->component         = 'enrol_flatfile';
 474                  $eventdata->name              = 'flatfile_enrolment';
 475                  $eventdata->userfrom          = $this->get_enroller($course->id);
 476                  $eventdata->userto            = $user;
 477                  $eventdata->subject           = $subject;
 478                  $eventdata->fullmessage       = get_string('welcometocoursetext', '', $a);
 479                  $eventdata->fullmessageformat = FORMAT_PLAIN;
 480                  $eventdata->fullmessagehtml   = '';
 481                  $eventdata->smallmessage      = '';
 482                  if (message_send($eventdata)) {
 483                      $trace->output("Notified enrolled user", 1);
 484                  } else {
 485                      $trace->output("Failed to notify enrolled user", 1);
 486                  }
 487  
 488                  force_current_language($oldforcelang);
 489              }
 490  
 491              if ($notify and $this->get_config('mailteachers', 0)) {
 492                  // Notify person responsible for enrolments.
 493                  $enroller = $this->get_enroller($course->id);
 494  
 495                  $oldforcelang = force_current_language($enroller->lang);
 496  
 497                  $a = new stdClass();
 498                  $a->course = format_string($course->fullname, true, array('context' => $context));
 499                  $a->user = fullname($user);
 500                  $subject = get_string('enrolmentnew', 'enrol', format_string($course->shortname, true, array('context' => $context)));
 501  
 502                  $eventdata = new stdClass();
 503                  $eventdata->modulename        = 'moodle';
 504                  $eventdata->component         = 'enrol_flatfile';
 505                  $eventdata->name              = 'flatfile_enrolment';
 506                  $eventdata->userfrom          = get_admin();
 507                  $eventdata->userto            = $enroller;
 508                  $eventdata->subject           = $subject;
 509                  $eventdata->fullmessage       = get_string('enrolmentnewuser', 'enrol', $a);
 510                  $eventdata->fullmessageformat = FORMAT_PLAIN;
 511                  $eventdata->fullmessagehtml   = '';
 512                  $eventdata->smallmessage      = '';
 513                  if (message_send($eventdata)) {
 514                      $trace->output("Notified enroller {$eventdata->userto->id}", 1);
 515                  } else {
 516                      $trace->output("Failed to notify enroller {$eventdata->userto->id}", 1);
 517                  }
 518  
 519                  force_current_language($oldforcelang);
 520              }
 521              return;
 522  
 523          } else if ($action === 'del') {
 524              // Clear the buffer just in case there were some future enrolments.
 525              $DB->delete_records('enrol_flatfile', array('userid'=>$user->id, 'courseid'=>$course->id, 'roleid'=>$roleid));
 526  
 527              $action = $this->get_config('unenrolaction');
 528              if ($action == ENROL_EXT_REMOVED_KEEP) {
 529                  $trace->output("del action is ignored", 1);
 530                  return;
 531              }
 532  
 533              // Loops through all enrolment methods, try to unenrol if roleid somehow matches.
 534              $instances = $DB->get_records('enrol', array('courseid' => $course->id));
 535              $unenrolled = false;
 536              foreach ($instances as $instance) {
 537                  if (!$ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$user->id))) {
 538                      continue;
 539                  }
 540                  if ($instance->enrol === 'flatfile') {
 541                      $plugin = $this;
 542                  } else {
 543                      if (!enrol_is_enabled($instance->enrol)) {
 544                          continue;
 545                      }
 546                      if (!$plugin = enrol_get_plugin($instance->enrol)) {
 547                          continue;
 548                      }
 549                      if (!$plugin->allow_unenrol_user($instance, $ue)) {
 550                          continue;
 551                      }
 552                  }
 553  
 554                  // For some reason the del action includes a role name, this complicates everything.
 555                  $componentroles = array();
 556                  $manualroles = array();
 557                  $ras = $DB->get_records('role_assignments', array('userid'=>$user->id, 'contextid'=>$context->id));
 558                  foreach ($ras as $ra) {
 559                      if ($ra->component === '') {
 560                          $manualroles[$ra->roleid] = $ra->roleid;
 561                      } else if ($ra->component === 'enrol_'.$instance->enrol and $ra->itemid == $instance->id) {
 562                          $componentroles[$ra->roleid] = $ra->roleid;
 563                      }
 564                  }
 565  
 566                  if ($componentroles and !isset($componentroles[$roleid])) {
 567                      // Do not unenrol using this method, user has some other protected role!
 568                      continue;
 569  
 570                  } else if (empty($ras)) {
 571                      // If user does not have any roles then let's just suspend as many methods as possible.
 572  
 573                  } else if (!$plugin->roles_protected()) {
 574                      if (!$componentroles and $manualroles and !isset($manualroles[$roleid])) {
 575                          // Most likely we want to keep users enrolled because they have some other course roles.
 576                          continue;
 577                      }
 578                  }
 579  
 580                  if ($action == ENROL_EXT_REMOVED_UNENROL) {
 581                      $unenrolled = true;
 582                      if (!$plugin->roles_protected()) {
 583                          role_unassign_all(array('contextid'=>$context->id, 'userid'=>$user->id, 'roleid'=>$roleid, 'component'=>'', 'itemid'=>0), true);
 584                      }
 585                      $plugin->unenrol_user($instance, $user->id);
 586                      $trace->output("User $user->id was unenrolled from course $course->id (enrol_$instance->enrol)", 1);
 587  
 588                  } else if ($action == ENROL_EXT_REMOVED_SUSPENDNOROLES) {
 589                      if ($plugin->allow_manage($instance)) {
 590                          if ($ue->status == ENROL_USER_ACTIVE) {
 591                              $unenrolled = true;
 592                              $plugin->update_user_enrol($instance, $user->id, ENROL_USER_SUSPENDED);
 593                              if (!$plugin->roles_protected()) {
 594                                  role_unassign_all(array('contextid'=>$context->id, 'userid'=>$user->id, 'component'=>'enrol_'.$instance->enrol, 'itemid'=>$instance->id), true);
 595                                  role_unassign_all(array('contextid'=>$context->id, 'userid'=>$user->id, 'roleid'=>$roleid, 'component'=>'', 'itemid'=>0), true);
 596                              }
 597                              $trace->output("User $user->id enrolment was suspended in course $course->id (enrol_$instance->enrol)", 1);
 598                          }
 599                      }
 600                  }
 601              }
 602  
 603              if (!$unenrolled) {
 604                  if (0 == $DB->count_records('role_assignments', array('userid'=>$user->id, 'contextid'=>$context->id))) {
 605                      role_unassign_all(array('contextid'=>$context->id, 'userid'=>$user->id, 'component'=>'', 'itemid'=>0), true);
 606                  }
 607                  $trace->output("User $user->id (with role $roleid) not unenrolled from course $course->id", 1);
 608              }
 609  
 610              return;
 611          }
 612      }
 613  
 614      /**
 615       * Returns the user who is responsible for flatfile enrolments in given curse.
 616       *
 617       * Usually it is the first editing teacher - the person with "highest authority"
 618       * as defined by sort_by_roleassignment_authority() having 'enrol/flatfile:manage'
 619       * or 'moodle/role:assign' capability.
 620       *
 621       * @param int $courseid enrolment instance id
 622       * @return stdClass user record
 623       */
 624      protected function get_enroller($courseid) {
 625          if ($this->lasternollercourseid == $courseid and $this->lasternoller) {
 626              return $this->lasternoller;
 627          }
 628  
 629          $context = context_course::instance($courseid);
 630  
 631          $users = get_enrolled_users($context, 'enrol/flatfile:manage');
 632          if (!$users) {
 633              $users = get_enrolled_users($context, 'moodle/role:assign');
 634          }
 635  
 636          if ($users) {
 637              $users = sort_by_roleassignment_authority($users, $context);
 638              $this->lasternoller = reset($users);
 639              unset($users);
 640          } else {
 641              $this->lasternoller = get_admin();
 642          }
 643  
 644          $this->lasternollercourseid == $courseid;
 645  
 646          return $this->lasternoller;
 647      }
 648  
 649      /**
 650       * Returns a mapping of ims roles to role ids.
 651       *
 652       * @param progress_trace $trace
 653       * @return array imsrolename=>roleid
 654       */
 655      protected function get_role_map(progress_trace $trace) {
 656          global $DB;
 657  
 658          // Get all roles.
 659          $rolemap = array();
 660          $roles = $DB->get_records('role', null, '', 'id, name, shortname');
 661          foreach ($roles as $id=>$role) {
 662              $alias = $this->get_config('map_'.$id, $role->shortname, '');
 663              $alias = trim(core_text::strtolower($alias));
 664              if ($alias === '') {
 665                  // Either not configured yet or somebody wants to skip these intentionally.
 666                  continue;
 667              }
 668              if (isset($rolemap[$alias])) {
 669                  $trace->output("Duplicate role alias $alias detected!");
 670              } else {
 671                  $rolemap[$alias] = $id;
 672              }
 673          }
 674  
 675          return $rolemap;
 676      }
 677  
 678      /**
 679       * Restore instance and map settings.
 680       *
 681       * @param restore_enrolments_structure_step $step
 682       * @param stdClass $data
 683       * @param stdClass $course
 684       * @param int $oldid
 685       */
 686      public function restore_instance(restore_enrolments_structure_step $step, stdClass $data, $course, $oldid) {
 687          global $DB;
 688  
 689          if ($instance = $DB->get_record('enrol', array('courseid'=>$course->id, 'enrol'=>$this->get_name()))) {
 690              $instanceid = $instance->id;
 691          } else {
 692              $instanceid = $this->add_instance($course);
 693          }
 694          $step->set_mapping('enrol', $oldid, $instanceid);
 695      }
 696  
 697      /**
 698       * Restore user enrolment.
 699       *
 700       * @param restore_enrolments_structure_step $step
 701       * @param stdClass $data
 702       * @param stdClass $instance
 703       * @param int $oldinstancestatus
 704       * @param int $userid
 705       */
 706      public function restore_user_enrolment(restore_enrolments_structure_step $step, $data, $instance, $userid, $oldinstancestatus) {
 707          $this->enrol_user($instance, $userid, null, $data->timestart, $data->timeend, $data->status);
 708      }
 709  
 710      /**
 711       * Restore role assignment.
 712       *
 713       * @param stdClass $instance
 714       * @param int $roleid
 715       * @param int $userid
 716       * @param int $contextid
 717       */
 718      public function restore_role_assignment($instance, $roleid, $userid, $contextid) {
 719          role_assign($roleid, $userid, $contextid, 'enrol_'.$instance->enrol, $instance->id);
 720      }
 721  }


Generated: Fri Nov 28 20:29:05 2014 Cross-referenced by PHPXref 0.7.1