Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 3.9.x will end* 10 May 2021 (12 months).
  • Bug fixes for security issues in 3.9.x will end* 8 May 2023 (36 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.
/enrol/self/ -> lib.php (source)

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

   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   * Self enrolment plugin.
  19   *
  20   * @package    enrol_self
  21   * @copyright  2010 Petr Skoda  {@link http://skodak.org}
  22   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  23   */
  24  
  25  /**
  26   * Self enrolment plugin implementation.
  27   * @author Petr Skoda
  28   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  29   */
  30  class enrol_self_plugin extends enrol_plugin {
  31  
  32      protected $lasternoller = null;
  33      protected $lasternollerinstanceid = 0;
  34  
  35      /**
  36       * Returns optional enrolment information icons.
  37       *
  38       * This is used in course list for quick overview of enrolment options.
  39       *
  40       * We are not using single instance parameter because sometimes
  41       * we might want to prevent icon repetition when multiple instances
  42       * of one type exist. One instance may also produce several icons.
  43       *
  44       * @param array $instances all enrol instances of this type in one course
  45       * @return array of pix_icon
  46       */
  47      public function get_info_icons(array $instances) {
  48          $key = false;
  49          $nokey = false;
  50          foreach ($instances as $instance) {
  51              if ($this->can_self_enrol($instance, false) !== true) {
  52                  // User can not enrol himself.
  53                  // Note that we do not check here if user is already enrolled for performance reasons -
  54                  // such check would execute extra queries for each course in the list of courses and
  55                  // would hide self-enrolment icons from guests.
  56                  continue;
  57              }
  58              if ($instance->password or $instance->customint1) {
  59                  $key = true;
  60              } else {
  61                  $nokey = true;
  62              }
  63          }
  64          $icons = array();
  65          if ($nokey) {
  66              $icons[] = new pix_icon('withoutkey', get_string('pluginname', 'enrol_self'), 'enrol_self');
  67          }
  68          if ($key) {
  69              $icons[] = new pix_icon('withkey', get_string('pluginname', 'enrol_self'), 'enrol_self');
  70          }
  71          return $icons;
  72      }
  73  
  74      /**
  75       * Returns localised name of enrol instance
  76       *
  77       * @param stdClass $instance (null is accepted too)
  78       * @return string
  79       */
  80      public function get_instance_name($instance) {
  81          global $DB;
  82  
  83          if (empty($instance->name)) {
  84              if (!empty($instance->roleid) and $role = $DB->get_record('role', array('id'=>$instance->roleid))) {
  85                  $role = ' (' . role_get_name($role, context_course::instance($instance->courseid, IGNORE_MISSING)) . ')';
  86              } else {
  87                  $role = '';
  88              }
  89              $enrol = $this->get_name();
  90              return get_string('pluginname', 'enrol_'.$enrol) . $role;
  91          } else {
  92              return format_string($instance->name);
  93          }
  94      }
  95  
  96      public function roles_protected() {
  97          // Users may tweak the roles later.
  98          return false;
  99      }
 100  
 101      public function allow_unenrol(stdClass $instance) {
 102          // Users with unenrol cap may unenrol other users manually manually.
 103          return true;
 104      }
 105  
 106      public function allow_manage(stdClass $instance) {
 107          // Users with manage cap may tweak period and status.
 108          return true;
 109      }
 110  
 111      public function show_enrolme_link(stdClass $instance) {
 112  
 113          if (true !== $this->can_self_enrol($instance, false)) {
 114              return false;
 115          }
 116  
 117          return true;
 118      }
 119  
 120      /**
 121       * Return true if we can add a new instance to this course.
 122       *
 123       * @param int $courseid
 124       * @return boolean
 125       */
 126      public function can_add_instance($courseid) {
 127          $context = context_course::instance($courseid, MUST_EXIST);
 128  
 129          if (!has_capability('moodle/course:enrolconfig', $context) or !has_capability('enrol/self:config', $context)) {
 130              return false;
 131          }
 132  
 133          return true;
 134      }
 135  
 136      /**
 137       * Self enrol user to course
 138       *
 139       * @param stdClass $instance enrolment instance
 140       * @param stdClass $data data needed for enrolment.
 141       * @return bool|array true if enroled else eddor code and messege
 142       */
 143      public function enrol_self(stdClass $instance, $data = null) {
 144          global $DB, $USER, $CFG;
 145  
 146          // Don't enrol user if password is not passed when required.
 147          if ($instance->password && !isset($data->enrolpassword)) {
 148              return;
 149          }
 150  
 151          $timestart = time();
 152          if ($instance->enrolperiod) {
 153              $timeend = $timestart + $instance->enrolperiod;
 154          } else {
 155              $timeend = 0;
 156          }
 157  
 158          $this->enrol_user($instance, $USER->id, $instance->roleid, $timestart, $timeend);
 159  
 160          \core\notification::success(get_string('youenrolledincourse', 'enrol'));
 161  
 162          if ($instance->password and $instance->customint1 and $data->enrolpassword !== $instance->password) {
 163              // It must be a group enrolment, let's assign group too.
 164              $groups = $DB->get_records('groups', array('courseid'=>$instance->courseid), 'id', 'id, enrolmentkey');
 165              foreach ($groups as $group) {
 166                  if (empty($group->enrolmentkey)) {
 167                      continue;
 168                  }
 169                  if ($group->enrolmentkey === $data->enrolpassword) {
 170                      // Add user to group.
 171                      require_once($CFG->dirroot.'/group/lib.php');
 172                      groups_add_member($group->id, $USER->id);
 173                      break;
 174                  }
 175              }
 176          }
 177          // Send welcome message.
 178          if ($instance->customint4 != ENROL_DO_NOT_SEND_EMAIL) {
 179              $this->email_welcome_message($instance, $USER);
 180          }
 181      }
 182  
 183      /**
 184       * Creates course enrol form, checks if form submitted
 185       * and enrols user if necessary. It can also redirect.
 186       *
 187       * @param stdClass $instance
 188       * @return string html text, usually a form in a text box
 189       */
 190      public function enrol_page_hook(stdClass $instance) {
 191          global $CFG, $OUTPUT, $USER;
 192  
 193          require_once("$CFG->dirroot/enrol/self/locallib.php");
 194  
 195          $enrolstatus = $this->can_self_enrol($instance);
 196  
 197          if (true === $enrolstatus) {
 198              // This user can self enrol using this instance.
 199              $form = new enrol_self_enrol_form(null, $instance);
 200              $instanceid = optional_param('instance', 0, PARAM_INT);
 201              if ($instance->id == $instanceid) {
 202                  if ($data = $form->get_data()) {
 203                      $this->enrol_self($instance, $data);
 204                  }
 205              }
 206          } else {
 207              // This user can not self enrol using this instance. Using an empty form to keep
 208              // the UI consistent with other enrolment plugins that returns a form.
 209              $data = new stdClass();
 210              $data->header = $this->get_instance_name($instance);
 211              $data->info = $enrolstatus;
 212  
 213              // The can_self_enrol call returns a button to the login page if the user is a
 214              // guest, setting the login url to the form if that is the case.
 215              $url = isguestuser() ? get_login_url() : null;
 216              $form = new enrol_self_empty_form($url, $data);
 217          }
 218  
 219          ob_start();
 220          $form->display();
 221          $output = ob_get_clean();
 222          return $OUTPUT->box($output);
 223      }
 224  
 225      /**
 226       * Checks if user can self enrol.
 227       *
 228       * @param stdClass $instance enrolment instance
 229       * @param bool $checkuserenrolment if true will check if user enrolment is inactive.
 230       *             used by navigation to improve performance.
 231       * @return bool|string true if successful, else error message or false.
 232       */
 233      public function can_self_enrol(stdClass $instance, $checkuserenrolment = true) {
 234          global $CFG, $DB, $OUTPUT, $USER;
 235  
 236          if ($checkuserenrolment) {
 237              if (isguestuser()) {
 238                  // Can not enrol guest.
 239                  return get_string('noguestaccess', 'enrol') . $OUTPUT->continue_button(get_login_url());
 240              }
 241              // Check if user is already enroled.
 242              if ($DB->get_record('user_enrolments', array('userid' => $USER->id, 'enrolid' => $instance->id))) {
 243                  return get_string('canntenrol', 'enrol_self');
 244              }
 245          }
 246  
 247          if ($instance->status != ENROL_INSTANCE_ENABLED) {
 248              return get_string('canntenrol', 'enrol_self');
 249          }
 250  
 251          if ($instance->enrolstartdate != 0 and $instance->enrolstartdate > time()) {
 252              return get_string('canntenrolearly', 'enrol_self', userdate($instance->enrolstartdate));
 253          }
 254  
 255          if ($instance->enrolenddate != 0 and $instance->enrolenddate < time()) {
 256              return get_string('canntenrollate', 'enrol_self', userdate($instance->enrolenddate));
 257          }
 258  
 259          if (!$instance->customint6) {
 260              // New enrols not allowed.
 261              return get_string('canntenrol', 'enrol_self');
 262          }
 263  
 264          if ($DB->record_exists('user_enrolments', array('userid' => $USER->id, 'enrolid' => $instance->id))) {
 265              return get_string('canntenrol', 'enrol_self');
 266          }
 267  
 268          if ($instance->customint3 > 0) {
 269              // Max enrol limit specified.
 270              $count = $DB->count_records('user_enrolments', array('enrolid' => $instance->id));
 271              if ($count >= $instance->customint3) {
 272                  // Bad luck, no more self enrolments here.
 273                  return get_string('maxenrolledreached', 'enrol_self');
 274              }
 275          }
 276  
 277          if ($instance->customint5) {
 278              require_once("$CFG->dirroot/cohort/lib.php");
 279              if (!cohort_is_member($instance->customint5, $USER->id)) {
 280                  $cohort = $DB->get_record('cohort', array('id' => $instance->customint5));
 281                  if (!$cohort) {
 282                      return null;
 283                  }
 284                  $a = format_string($cohort->name, true, array('context' => context::instance_by_id($cohort->contextid)));
 285                  return markdown_to_html(get_string('cohortnonmemberinfo', 'enrol_self', $a));
 286              }
 287          }
 288  
 289          return true;
 290      }
 291  
 292      /**
 293       * Return information for enrolment instance containing list of parameters required
 294       * for enrolment, name of enrolment plugin etc.
 295       *
 296       * @param stdClass $instance enrolment instance
 297       * @return stdClass instance info.
 298       */
 299      public function get_enrol_info(stdClass $instance) {
 300  
 301          $instanceinfo = new stdClass();
 302          $instanceinfo->id = $instance->id;
 303          $instanceinfo->courseid = $instance->courseid;
 304          $instanceinfo->type = $this->get_name();
 305          $instanceinfo->name = $this->get_instance_name($instance);
 306          $instanceinfo->status = $this->can_self_enrol($instance);
 307  
 308          if ($instance->password) {
 309              $instanceinfo->requiredparam = new stdClass();
 310              $instanceinfo->requiredparam->enrolpassword = get_string('password', 'enrol_self');
 311          }
 312  
 313          // If enrolment is possible and password is required then return ws function name to get more information.
 314          if ((true === $instanceinfo->status) && $instance->password) {
 315              $instanceinfo->wsfunction = 'enrol_self_get_instance_info';
 316          }
 317          return $instanceinfo;
 318      }
 319  
 320      /**
 321       * Add new instance of enrol plugin with default settings.
 322       * @param stdClass $course
 323       * @return int id of new instance
 324       */
 325      public function add_default_instance($course) {
 326          $fields = $this->get_instance_defaults();
 327  
 328          if ($this->get_config('requirepassword')) {
 329              $fields['password'] = generate_password(20);
 330          }
 331  
 332          return $this->add_instance($course, $fields);
 333      }
 334  
 335      /**
 336       * Returns defaults for new instances.
 337       * @return array
 338       */
 339      public function get_instance_defaults() {
 340          $expirynotify = $this->get_config('expirynotify');
 341          if ($expirynotify == 2) {
 342              $expirynotify = 1;
 343              $notifyall = 1;
 344          } else {
 345              $notifyall = 0;
 346          }
 347  
 348          $fields = array();
 349          $fields['status']          = $this->get_config('status');
 350          $fields['roleid']          = $this->get_config('roleid');
 351          $fields['enrolperiod']     = $this->get_config('enrolperiod');
 352          $fields['expirynotify']    = $expirynotify;
 353          $fields['notifyall']       = $notifyall;
 354          $fields['expirythreshold'] = $this->get_config('expirythreshold');
 355          $fields['customint1']      = $this->get_config('groupkey');
 356          $fields['customint2']      = $this->get_config('longtimenosee');
 357          $fields['customint3']      = $this->get_config('maxenrolled');
 358          $fields['customint4']      = $this->get_config('sendcoursewelcomemessage');
 359          $fields['customint5']      = 0;
 360          $fields['customint6']      = $this->get_config('newenrols');
 361  
 362          return $fields;
 363      }
 364  
 365      /**
 366       * Send welcome email to specified user.
 367       *
 368       * @param stdClass $instance
 369       * @param stdClass $user user record
 370       * @return void
 371       */
 372      protected function email_welcome_message($instance, $user) {
 373          global $CFG, $DB;
 374  
 375          $course = $DB->get_record('course', array('id'=>$instance->courseid), '*', MUST_EXIST);
 376          $context = context_course::instance($course->id);
 377  
 378          $a = new stdClass();
 379          $a->coursename = format_string($course->fullname, true, array('context'=>$context));
 380          $a->profileurl = "$CFG->wwwroot/user/view.php?id=$user->id&course=$course->id";
 381  
 382          if (trim($instance->customtext1) !== '') {
 383              $message = $instance->customtext1;
 384              $key = array('{$a->coursename}', '{$a->profileurl}', '{$a->fullname}', '{$a->email}');
 385              $value = array($a->coursename, $a->profileurl, fullname($user), $user->email);
 386              $message = str_replace($key, $value, $message);
 387              if (strpos($message, '<') === false) {
 388                  // Plain text only.
 389                  $messagetext = $message;
 390                  $messagehtml = text_to_html($messagetext, null, false, true);
 391              } else {
 392                  // This is most probably the tag/newline soup known as FORMAT_MOODLE.
 393                  $messagehtml = format_text($message, FORMAT_MOODLE, array('context'=>$context, 'para'=>false, 'newlines'=>true, 'filter'=>true));
 394                  $messagetext = html_to_text($messagehtml);
 395              }
 396          } else {
 397              $messagetext = get_string('welcometocoursetext', 'enrol_self', $a);
 398              $messagehtml = text_to_html($messagetext, null, false, true);
 399          }
 400  
 401          $subject = get_string('welcometocourse', 'enrol_self', format_string($course->fullname, true, array('context'=>$context)));
 402  
 403          $sendoption = $instance->customint4;
 404          $contact = $this->get_welcome_email_contact($sendoption, $context);
 405  
 406          // Directly emailing welcome message rather than using messaging.
 407          email_to_user($user, $contact, $subject, $messagetext, $messagehtml);
 408      }
 409  
 410      /**
 411       * Sync all meta course links.
 412       *
 413       * @param progress_trace $trace
 414       * @param int $courseid one course, empty mean all
 415       * @return int 0 means ok, 1 means error, 2 means plugin disabled
 416       */
 417      public function sync(progress_trace $trace, $courseid = null) {
 418          global $DB;
 419  
 420          if (!enrol_is_enabled('self')) {
 421              $trace->finished();
 422              return 2;
 423          }
 424  
 425          // Unfortunately this may take a long time, execution can be interrupted safely here.
 426          core_php_time_limit::raise();
 427          raise_memory_limit(MEMORY_HUGE);
 428  
 429          $trace->output('Verifying self-enrolments...');
 430  
 431          $params = array('now'=>time(), 'useractive'=>ENROL_USER_ACTIVE, 'courselevel'=>CONTEXT_COURSE);
 432          $coursesql = "";
 433          if ($courseid) {
 434              $coursesql = "AND e.courseid = :courseid";
 435              $params['courseid'] = $courseid;
 436          }
 437  
 438          // Note: the logic of self enrolment guarantees that user logged in at least once (=== u.lastaccess set)
 439          //       and that user accessed course at least once too (=== user_lastaccess record exists).
 440  
 441          // First deal with users that did not log in for a really long time - they do not have user_lastaccess records.
 442          $sql = "SELECT e.*, ue.userid
 443                    FROM {user_enrolments} ue
 444                    JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = 'self' AND e.customint2 > 0)
 445                    JOIN {user} u ON u.id = ue.userid
 446                   WHERE :now - u.lastaccess > e.customint2
 447                         $coursesql";
 448          $rs = $DB->get_recordset_sql($sql, $params);
 449          foreach ($rs as $instance) {
 450              $userid = $instance->userid;
 451              unset($instance->userid);
 452              $this->unenrol_user($instance, $userid);
 453              $days = $instance->customint2 / DAYSECS;
 454              $trace->output("unenrolling user $userid from course $instance->courseid " .
 455                  "as they did not log in for at least $days days", 1);
 456          }
 457          $rs->close();
 458  
 459          // Now unenrol from course user did not visit for a long time.
 460          $sql = "SELECT e.*, ue.userid
 461                    FROM {user_enrolments} ue
 462                    JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = 'self' AND e.customint2 > 0)
 463                    JOIN {user_lastaccess} ul ON (ul.userid = ue.userid AND ul.courseid = e.courseid)
 464                   WHERE :now - ul.timeaccess > e.customint2
 465                         $coursesql";
 466          $rs = $DB->get_recordset_sql($sql, $params);
 467          foreach ($rs as $instance) {
 468              $userid = $instance->userid;
 469              unset($instance->userid);
 470              $this->unenrol_user($instance, $userid);
 471              $days = $instance->customint2 / DAYSECS;
 472              $trace->output("unenrolling user $userid from course $instance->courseid " .
 473                  "as they did not access the course for at least $days days", 1);
 474          }
 475          $rs->close();
 476  
 477          $trace->output('...user self-enrolment updates finished.');
 478          $trace->finished();
 479  
 480          $this->process_expirations($trace, $courseid);
 481  
 482          return 0;
 483      }
 484  
 485      /**
 486       * Returns the user who is responsible for self enrolments in given instance.
 487       *
 488       * Usually it is the first editing teacher - the person with "highest authority"
 489       * as defined by sort_by_roleassignment_authority() having 'enrol/self:manage'
 490       * capability.
 491       *
 492       * @param int $instanceid enrolment instance id
 493       * @return stdClass user record
 494       */
 495      protected function get_enroller($instanceid) {
 496          global $DB;
 497  
 498          if ($this->lasternollerinstanceid == $instanceid and $this->lasternoller) {
 499              return $this->lasternoller;
 500          }
 501  
 502          $instance = $DB->get_record('enrol', array('id'=>$instanceid, 'enrol'=>$this->get_name()), '*', MUST_EXIST);
 503          $context = context_course::instance($instance->courseid);
 504  
 505          if ($users = get_enrolled_users($context, 'enrol/self:manage')) {
 506              $users = sort_by_roleassignment_authority($users, $context);
 507              $this->lasternoller = reset($users);
 508              unset($users);
 509          } else {
 510              $this->lasternoller = parent::get_enroller($instanceid);
 511          }
 512  
 513          $this->lasternollerinstanceid = $instanceid;
 514  
 515          return $this->lasternoller;
 516      }
 517  
 518      /**
 519       * Restore instance and map settings.
 520       *
 521       * @param restore_enrolments_structure_step $step
 522       * @param stdClass $data
 523       * @param stdClass $course
 524       * @param int $oldid
 525       */
 526      public function restore_instance(restore_enrolments_structure_step $step, stdClass $data, $course, $oldid) {
 527          global $DB;
 528          if ($step->get_task()->get_target() == backup::TARGET_NEW_COURSE) {
 529              $merge = false;
 530          } else {
 531              $merge = array(
 532                  'courseid'   => $data->courseid,
 533                  'enrol'      => $this->get_name(),
 534                  'status'     => $data->status,
 535                  'roleid'     => $data->roleid,
 536              );
 537          }
 538          if ($merge and $instances = $DB->get_records('enrol', $merge, 'id')) {
 539              $instance = reset($instances);
 540              $instanceid = $instance->id;
 541          } else {
 542              if (!empty($data->customint5)) {
 543                  if ($step->get_task()->is_samesite()) {
 544                      // Keep cohort restriction unchanged - we are on the same site.
 545                  } else {
 546                      // Use some id that can not exist in order to prevent self enrolment,
 547                      // because we do not know what cohort it is in this site.
 548                      $data->customint5 = -1;
 549                  }
 550              }
 551              $instanceid = $this->add_instance($course, (array)$data);
 552          }
 553          $step->set_mapping('enrol', $oldid, $instanceid);
 554      }
 555  
 556      /**
 557       * Restore user enrolment.
 558       *
 559       * @param restore_enrolments_structure_step $step
 560       * @param stdClass $data
 561       * @param stdClass $instance
 562       * @param int $oldinstancestatus
 563       * @param int $userid
 564       */
 565      public function restore_user_enrolment(restore_enrolments_structure_step $step, $data, $instance, $userid, $oldinstancestatus) {
 566          $this->enrol_user($instance, $userid, null, $data->timestart, $data->timeend, $data->status);
 567      }
 568  
 569      /**
 570       * Restore role assignment.
 571       *
 572       * @param stdClass $instance
 573       * @param int $roleid
 574       * @param int $userid
 575       * @param int $contextid
 576       */
 577      public function restore_role_assignment($instance, $roleid, $userid, $contextid) {
 578          // This is necessary only because we may migrate other types to this instance,
 579          // we do not use component in manual or self enrol.
 580          role_assign($roleid, $userid, $contextid, '', 0);
 581      }
 582  
 583      /**
 584       * Is it possible to delete enrol instance via standard UI?
 585       *
 586       * @param stdClass $instance
 587       * @return bool
 588       */
 589      public function can_delete_instance($instance) {
 590          $context = context_course::instance($instance->courseid);
 591          return has_capability('enrol/self:config', $context);
 592      }
 593  
 594      /**
 595       * Is it possible to hide/show enrol instance via standard UI?
 596       *
 597       * @param stdClass $instance
 598       * @return bool
 599       */
 600      public function can_hide_show_instance($instance) {
 601          $context = context_course::instance($instance->courseid);
 602  
 603          if (!has_capability('enrol/self:config', $context)) {
 604              return false;
 605          }
 606  
 607          // If the instance is currently disabled, before it can be enabled,
 608          // we must check whether the password meets the password policies.
 609          if ($instance->status == ENROL_INSTANCE_DISABLED) {
 610              if ($this->get_config('requirepassword')) {
 611                  if (empty($instance->password)) {
 612                      return false;
 613                  }
 614              }
 615              // Only check the password if it is set.
 616              if (!empty($instance->password) && $this->get_config('usepasswordpolicy')) {
 617                  if (!check_password_policy($instance->password, $errmsg)) {
 618                      return false;
 619                  }
 620              }
 621          }
 622  
 623          return true;
 624      }
 625  
 626      /**
 627       * Return an array of valid options for the status.
 628       *
 629       * @return array
 630       */
 631      protected function get_status_options() {
 632          $options = array(ENROL_INSTANCE_ENABLED  => get_string('yes'),
 633                           ENROL_INSTANCE_DISABLED => get_string('no'));
 634          return $options;
 635      }
 636  
 637      /**
 638       * Return an array of valid options for the newenrols property.
 639       *
 640       * @return array
 641       */
 642      protected function get_newenrols_options() {
 643          $options = array(1 => get_string('yes'), 0 => get_string('no'));
 644          return $options;
 645      }
 646  
 647      /**
 648       * Return an array of valid options for the groupkey property.
 649       *
 650       * @return array
 651       */
 652      protected function get_groupkey_options() {
 653          $options = array(1 => get_string('yes'), 0 => get_string('no'));
 654          return $options;
 655      }
 656  
 657      /**
 658       * Return an array of valid options for the expirynotify property.
 659       *
 660       * @return array
 661       */
 662      protected function get_expirynotify_options() {
 663          $options = array(0 => get_string('no'),
 664                           1 => get_string('expirynotifyenroller', 'enrol_self'),
 665                           2 => get_string('expirynotifyall', 'enrol_self'));
 666          return $options;
 667      }
 668  
 669      /**
 670       * Return an array of valid options for the longtimenosee property.
 671       *
 672       * @return array
 673       */
 674      protected function get_longtimenosee_options() {
 675          $options = array(0 => get_string('never'),
 676                           1800 * 3600 * 24 => get_string('numdays', '', 1800),
 677                           1000 * 3600 * 24 => get_string('numdays', '', 1000),
 678                           365 * 3600 * 24 => get_string('numdays', '', 365),
 679                           180 * 3600 * 24 => get_string('numdays', '', 180),
 680                           150 * 3600 * 24 => get_string('numdays', '', 150),
 681                           120 * 3600 * 24 => get_string('numdays', '', 120),
 682                           90 * 3600 * 24 => get_string('numdays', '', 90),
 683                           60 * 3600 * 24 => get_string('numdays', '', 60),
 684                           30 * 3600 * 24 => get_string('numdays', '', 30),
 685                           21 * 3600 * 24 => get_string('numdays', '', 21),
 686                           14 * 3600 * 24 => get_string('numdays', '', 14),
 687                           7 * 3600 * 24 => get_string('numdays', '', 7));
 688          return $options;
 689      }
 690  
 691      /**
 692       * The self enrollment plugin has several bulk operations that can be performed.
 693       * @param course_enrolment_manager $manager
 694       * @return array
 695       */
 696      public function get_bulk_operations(course_enrolment_manager $manager) {
 697          global $CFG;
 698          require_once($CFG->dirroot.'/enrol/self/locallib.php');
 699          $context = $manager->get_context();
 700          $bulkoperations = array();
 701          if (has_capability("enrol/self:manage", $context)) {
 702              $bulkoperations['editselectedusers'] = new enrol_self_editselectedusers_operation($manager, $this);
 703          }
 704          if (has_capability("enrol/self:unenrol", $context)) {
 705              $bulkoperations['deleteselectedusers'] = new enrol_self_deleteselectedusers_operation($manager, $this);
 706          }
 707          return $bulkoperations;
 708      }
 709  
 710      /**
 711       * Add elements to the edit instance form.
 712       *
 713       * @param stdClass $instance
 714       * @param MoodleQuickForm $mform
 715       * @param context $context
 716       * @return bool
 717       */
 718      public function edit_instance_form($instance, MoodleQuickForm $mform, $context) {
 719          global $CFG, $DB;
 720  
 721          // Merge these two settings to one value for the single selection element.
 722          if ($instance->notifyall and $instance->expirynotify) {
 723              $instance->expirynotify = 2;
 724          }
 725          unset($instance->notifyall);
 726  
 727          $nameattribs = array('size' => '20', 'maxlength' => '255');
 728          $mform->addElement('text', 'name', get_string('custominstancename', 'enrol'), $nameattribs);
 729          $mform->setType('name', PARAM_TEXT);
 730          $mform->addRule('name', get_string('maximumchars', '', 255), 'maxlength', 255, 'server');
 731  
 732          $options = $this->get_status_options();
 733          $mform->addElement('select', 'status', get_string('status', 'enrol_self'), $options);
 734          $mform->addHelpButton('status', 'status', 'enrol_self');
 735  
 736          $options = $this->get_newenrols_options();
 737          $mform->addElement('select', 'customint6', get_string('newenrols', 'enrol_self'), $options);
 738          $mform->addHelpButton('customint6', 'newenrols', 'enrol_self');
 739          $mform->disabledIf('customint6', 'status', 'eq', ENROL_INSTANCE_DISABLED);
 740  
 741          $passattribs = array('size' => '20', 'maxlength' => '50');
 742          $mform->addElement('passwordunmask', 'password', get_string('password', 'enrol_self'), $passattribs);
 743          $mform->addHelpButton('password', 'password', 'enrol_self');
 744          if (empty($instance->id) and $this->get_config('requirepassword')) {
 745              $mform->addRule('password', get_string('required'), 'required', null, 'client');
 746          }
 747          $mform->addRule('password', get_string('maximumchars', '', 50), 'maxlength', 50, 'server');
 748  
 749          $options = $this->get_groupkey_options();
 750          $mform->addElement('select', 'customint1', get_string('groupkey', 'enrol_self'), $options);
 751          $mform->addHelpButton('customint1', 'groupkey', 'enrol_self');
 752  
 753          $roles = $this->extend_assignable_roles($context, $instance->roleid);
 754          $mform->addElement('select', 'roleid', get_string('role', 'enrol_self'), $roles);
 755  
 756          $options = array('optional' => true, 'defaultunit' => 86400);
 757          $mform->addElement('duration', 'enrolperiod', get_string('enrolperiod', 'enrol_self'), $options);
 758          $mform->addHelpButton('enrolperiod', 'enrolperiod', 'enrol_self');
 759  
 760          $options = $this->get_expirynotify_options();
 761          $mform->addElement('select', 'expirynotify', get_string('expirynotify', 'core_enrol'), $options);
 762          $mform->addHelpButton('expirynotify', 'expirynotify', 'core_enrol');
 763  
 764          $options = array('optional' => false, 'defaultunit' => 86400);
 765          $mform->addElement('duration', 'expirythreshold', get_string('expirythreshold', 'core_enrol'), $options);
 766          $mform->addHelpButton('expirythreshold', 'expirythreshold', 'core_enrol');
 767          $mform->disabledIf('expirythreshold', 'expirynotify', 'eq', 0);
 768  
 769          $options = array('optional' => true);
 770          $mform->addElement('date_time_selector', 'enrolstartdate', get_string('enrolstartdate', 'enrol_self'), $options);
 771          $mform->setDefault('enrolstartdate', 0);
 772          $mform->addHelpButton('enrolstartdate', 'enrolstartdate', 'enrol_self');
 773  
 774          $options = array('optional' => true);
 775          $mform->addElement('date_time_selector', 'enrolenddate', get_string('enrolenddate', 'enrol_self'), $options);
 776          $mform->setDefault('enrolenddate', 0);
 777          $mform->addHelpButton('enrolenddate', 'enrolenddate', 'enrol_self');
 778  
 779          $options = $this->get_longtimenosee_options();
 780          $mform->addElement('select', 'customint2', get_string('longtimenosee', 'enrol_self'), $options);
 781          $mform->addHelpButton('customint2', 'longtimenosee', 'enrol_self');
 782  
 783          $mform->addElement('text', 'customint3', get_string('maxenrolled', 'enrol_self'));
 784          $mform->addHelpButton('customint3', 'maxenrolled', 'enrol_self');
 785          $mform->setType('customint3', PARAM_INT);
 786  
 787          require_once($CFG->dirroot.'/cohort/lib.php');
 788  
 789          $cohorts = array(0 => get_string('no'));
 790          $allcohorts = cohort_get_available_cohorts($context, 0, 0, 0);
 791          if ($instance->customint5 && !isset($allcohorts[$instance->customint5])) {
 792              $c = $DB->get_record('cohort',
 793                                   array('id' => $instance->customint5),
 794                                   'id, name, idnumber, contextid, visible',
 795                                   IGNORE_MISSING);
 796              if ($c) {
 797                  // Current cohort was not found because current user can not see it. Still keep it.
 798                  $allcohorts[$instance->customint5] = $c;
 799              }
 800          }
 801          foreach ($allcohorts as $c) {
 802              $cohorts[$c->id] = format_string($c->name, true, array('context' => context::instance_by_id($c->contextid)));
 803              if ($c->idnumber) {
 804                  $cohorts[$c->id] .= ' ['.s($c->idnumber).']';
 805              }
 806          }
 807          if ($instance->customint5 && !isset($allcohorts[$instance->customint5])) {
 808              // Somebody deleted a cohort, better keep the wrong value so that random ppl can not enrol.
 809              $cohorts[$instance->customint5] = get_string('unknowncohort', 'cohort', $instance->customint5);
 810          }
 811          if (count($cohorts) > 1) {
 812              $mform->addElement('select', 'customint5', get_string('cohortonly', 'enrol_self'), $cohorts);
 813              $mform->addHelpButton('customint5', 'cohortonly', 'enrol_self');
 814          } else {
 815              $mform->addElement('hidden', 'customint5');
 816              $mform->setType('customint5', PARAM_INT);
 817              $mform->setConstant('customint5', 0);
 818          }
 819  
 820          $mform->addElement('select', 'customint4', get_string('sendcoursewelcomemessage', 'enrol_self'),
 821                  enrol_send_welcome_email_options());
 822          $mform->addHelpButton('customint4', 'sendcoursewelcomemessage', 'enrol_self');
 823  
 824          $options = array('cols' => '60', 'rows' => '8');
 825          $mform->addElement('textarea', 'customtext1', get_string('customwelcomemessage', 'enrol_self'), $options);
 826          $mform->addHelpButton('customtext1', 'customwelcomemessage', 'enrol_self');
 827  
 828          if (enrol_accessing_via_instance($instance)) {
 829              $warntext = get_string('instanceeditselfwarningtext', 'core_enrol');
 830              $mform->addElement('static', 'selfwarn', get_string('instanceeditselfwarning', 'core_enrol'), $warntext);
 831          }
 832      }
 833  
 834      /**
 835       * We are a good plugin and don't invent our own UI/validation code path.
 836       *
 837       * @return boolean
 838       */
 839      public function use_standard_editing_ui() {
 840          return true;
 841      }
 842  
 843      /**
 844       * Perform custom validation of the data used to edit the instance.
 845       *
 846       * @param array $data array of ("fieldname"=>value) of submitted data
 847       * @param array $files array of uploaded files "element_name"=>tmp_file_path
 848       * @param object $instance The instance loaded from the DB
 849       * @param context $context The context of the instance we are editing
 850       * @return array of "element_name"=>"error_description" if there are errors,
 851       *         or an empty array if everything is OK.
 852       * @return void
 853       */
 854      public function edit_instance_validation($data, $files, $instance, $context) {
 855          $errors = array();
 856  
 857          $checkpassword = false;
 858  
 859          if ($instance->id) {
 860              // Check the password if we are enabling the plugin again.
 861              if (($instance->status == ENROL_INSTANCE_DISABLED) && ($data['status'] == ENROL_INSTANCE_ENABLED)) {
 862                  $checkpassword = true;
 863              }
 864  
 865              // Check the password if the instance is enabled and the password has changed.
 866              if (($data['status'] == ENROL_INSTANCE_ENABLED) && ($instance->password !== $data['password'])) {
 867                  $checkpassword = true;
 868              }
 869          } else {
 870              $checkpassword = true;
 871          }
 872  
 873          if ($checkpassword) {
 874              $require = $this->get_config('requirepassword');
 875              $policy  = $this->get_config('usepasswordpolicy');
 876              if ($require and trim($data['password']) === '') {
 877                  $errors['password'] = get_string('required');
 878              } else if (!empty($data['password']) && $policy) {
 879                  $errmsg = '';
 880                  if (!check_password_policy($data['password'], $errmsg)) {
 881                      $errors['password'] = $errmsg;
 882                  }
 883              }
 884          }
 885  
 886          if ($data['status'] == ENROL_INSTANCE_ENABLED) {
 887              if (!empty($data['enrolenddate']) and $data['enrolenddate'] < $data['enrolstartdate']) {
 888                  $errors['enrolenddate'] = get_string('enrolenddaterror', 'enrol_self');
 889              }
 890          }
 891  
 892          if ($data['expirynotify'] > 0 and $data['expirythreshold'] < 86400) {
 893              $errors['expirythreshold'] = get_string('errorthresholdlow', 'core_enrol');
 894          }
 895  
 896          // Now these ones are checked by quickforms, but we may be called by the upload enrolments tool, or a webservive.
 897          if (core_text::strlen($data['name']) > 255) {
 898              $errors['name'] = get_string('err_maxlength', 'form', 255);
 899          }
 900          $validstatus = array_keys($this->get_status_options());
 901          $validnewenrols = array_keys($this->get_newenrols_options());
 902          if (core_text::strlen($data['password']) > 50) {
 903              $errors['name'] = get_string('err_maxlength', 'form', 50);
 904          }
 905          $validgroupkey = array_keys($this->get_groupkey_options());
 906          $context = context_course::instance($instance->courseid);
 907          $validroles = array_keys($this->extend_assignable_roles($context, $instance->roleid));
 908          $validexpirynotify = array_keys($this->get_expirynotify_options());
 909          $validlongtimenosee = array_keys($this->get_longtimenosee_options());
 910          $tovalidate = array(
 911              'enrolstartdate' => PARAM_INT,
 912              'enrolenddate' => PARAM_INT,
 913              'name' => PARAM_TEXT,
 914              'customint1' => $validgroupkey,
 915              'customint2' => $validlongtimenosee,
 916              'customint3' => PARAM_INT,
 917              'customint4' => PARAM_INT,
 918              'customint5' => PARAM_INT,
 919              'customint6' => $validnewenrols,
 920              'status' => $validstatus,
 921              'enrolperiod' => PARAM_INT,
 922              'expirynotify' => $validexpirynotify,
 923              'roleid' => $validroles
 924          );
 925          if ($data['expirynotify'] != 0) {
 926              $tovalidate['expirythreshold'] = PARAM_INT;
 927          }
 928          $typeerrors = $this->validate_param_types($data, $tovalidate);
 929          $errors = array_merge($errors, $typeerrors);
 930  
 931          return $errors;
 932      }
 933  
 934      /**
 935       * Add new instance of enrol plugin.
 936       * @param object $course
 937       * @param array $fields instance fields
 938       * @return int id of new instance, null if can not be created
 939       */
 940      public function add_instance($course, array $fields = null) {
 941          // In the form we are representing 2 db columns with one field.
 942          if (!empty($fields) && !empty($fields['expirynotify'])) {
 943              if ($fields['expirynotify'] == 2) {
 944                  $fields['expirynotify'] = 1;
 945                  $fields['notifyall'] = 1;
 946              } else {
 947                  $fields['notifyall'] = 0;
 948              }
 949          }
 950  
 951          return parent::add_instance($course, $fields);
 952      }
 953  
 954      /**
 955       * Update instance of enrol plugin.
 956       * @param stdClass $instance
 957       * @param stdClass $data modified instance fields
 958       * @return boolean
 959       */
 960      public function update_instance($instance, $data) {
 961          // In the form we are representing 2 db columns with one field.
 962          if ($data->expirynotify == 2) {
 963              $data->expirynotify = 1;
 964              $data->notifyall = 1;
 965          } else {
 966              $data->notifyall = 0;
 967          }
 968          // Keep previous/default value of disabled expirythreshold option.
 969          if (!$data->expirynotify) {
 970              $data->expirythreshold = $instance->expirythreshold;
 971          }
 972          // Add previous value of newenrols if disabled.
 973          if (!isset($data->customint6)) {
 974              $data->customint6 = $instance->customint6;
 975          }
 976  
 977          return parent::update_instance($instance, $data);
 978      }
 979  
 980      /**
 981       * Gets a list of roles that this user can assign for the course as the default for self-enrolment.
 982       *
 983       * @param context $context the context.
 984       * @param integer $defaultrole the id of the role that is set as the default for self-enrolment
 985       * @return array index is the role id, value is the role name
 986       */
 987      public function extend_assignable_roles($context, $defaultrole) {
 988          global $DB;
 989  
 990          $roles = get_assignable_roles($context, ROLENAME_BOTH);
 991          if (!isset($roles[$defaultrole])) {
 992              if ($role = $DB->get_record('role', array('id' => $defaultrole))) {
 993                  $roles[$defaultrole] = role_get_name($role, $context, ROLENAME_BOTH);
 994              }
 995          }
 996          return $roles;
 997      }
 998  
 999      /**
1000       * Get the "from" contact which the email will be sent from.
1001       *
1002       * @param int $sendoption send email from constant ENROL_SEND_EMAIL_FROM_*
1003       * @param $context context where the user will be fetched
1004       * @return mixed|stdClass the contact user object.
1005       */
1006      public function get_welcome_email_contact($sendoption, $context) {
1007          global $CFG;
1008  
1009          $contact = null;
1010          // Send as the first user assigned as the course contact.
1011          if ($sendoption == ENROL_SEND_EMAIL_FROM_COURSE_CONTACT) {
1012              $rusers = array();
1013              if (!empty($CFG->coursecontact)) {
1014                  $croles = explode(',', $CFG->coursecontact);
1015                  list($sort, $sortparams) = users_order_by_sql('u');
1016                  // We only use the first user.
1017                  $i = 0;
1018                  do {
1019                      $allnames = get_all_user_name_fields(true, 'u');
1020                      $rusers = get_role_users($croles[$i], $context, true, 'u.id,  u.confirmed, u.username, '. $allnames . ',
1021                      u.email, r.sortorder, ra.id', 'r.sortorder, ra.id ASC, ' . $sort, null, '', '', '', '', $sortparams);
1022                      $i++;
1023                  } while (empty($rusers) && !empty($croles[$i]));
1024              }
1025              if ($rusers) {
1026                  $contact = array_values($rusers)[0];
1027              }
1028          } else if ($sendoption == ENROL_SEND_EMAIL_FROM_KEY_HOLDER) {
1029              // Send as the first user with enrol/self:holdkey capability assigned in the course.
1030              list($sort) = users_order_by_sql('u');
1031              $keyholders = get_users_by_capability($context, 'enrol/self:holdkey', 'u.*', $sort);
1032              if (!empty($keyholders)) {
1033                  $contact = array_values($keyholders)[0];
1034              }
1035          }
1036  
1037          // If send welcome email option is set to no reply or if none of the previous options have
1038          // returned a contact send welcome message as noreplyuser.
1039          if ($sendoption == ENROL_SEND_EMAIL_FROM_NOREPLY || empty($contact)) {
1040              $contact = core_user::get_noreply_user();
1041          }
1042  
1043          return $contact;
1044      }
1045  }
1046  
1047  /**
1048   * Get icon mapping for font-awesome.
1049   */
1050  function enrol_self_get_fontawesome_icon_map() {
1051      return [
1052          'enrol_self:withkey' => 'fa-key',
1053          'enrol_self:withoutkey' => 'fa-sign-in',
1054      ];
1055  }