Search moodle.org's
Developer Documentation

See Release Notes

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

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

   1  <?php
   2  // This file is part of Moodle - http://moodle.org/
   3  //
   4  // Moodle is free software: you can redistribute it and/or modify
   5  // it under the terms of the GNU General Public License as published by
   6  // the Free Software Foundation, either version 3 of the License, or
   7  // (at your option) any later version.
   8  //
   9  // Moodle is distributed in the hope that it will be useful,
  10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12  // GNU General Public License for more details.
  13  //
  14  // You should have received a copy of the GNU General Public License
  15  // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
  16  
  17  /**
  18   * 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          // Check if user has the capability to enrol in this context.
 252          if (!has_capability('enrol/self:enrolself', context_course::instance($instance->courseid))) {
 253              return get_string('canntenrol', 'enrol_self');
 254          }
 255  
 256          if ($instance->enrolstartdate != 0 and $instance->enrolstartdate > time()) {
 257              return get_string('canntenrolearly', 'enrol_self', userdate($instance->enrolstartdate));
 258          }
 259  
 260          if ($instance->enrolenddate != 0 and $instance->enrolenddate < time()) {
 261              return get_string('canntenrollate', 'enrol_self', userdate($instance->enrolenddate));
 262          }
 263  
 264          if (!$instance->customint6) {
 265              // New enrols not allowed.
 266              return get_string('canntenrol', 'enrol_self');
 267          }
 268  
 269          if ($DB->record_exists('user_enrolments', array('userid' => $USER->id, 'enrolid' => $instance->id))) {
 270              return get_string('canntenrol', 'enrol_self');
 271          }
 272  
 273          if ($instance->customint3 > 0) {
 274              // Max enrol limit specified.
 275              $count = $DB->count_records('user_enrolments', array('enrolid' => $instance->id));
 276              if ($count >= $instance->customint3) {
 277                  // Bad luck, no more self enrolments here.
 278                  return get_string('maxenrolledreached', 'enrol_self');
 279              }
 280          }
 281  
 282          if ($instance->customint5) {
 283              require_once("$CFG->dirroot/cohort/lib.php");
 284              if (!cohort_is_member($instance->customint5, $USER->id)) {
 285                  $cohort = $DB->get_record('cohort', array('id' => $instance->customint5));
 286                  if (!$cohort) {
 287                      return null;
 288                  }
 289                  $a = format_string($cohort->name, true, array('context' => context::instance_by_id($cohort->contextid)));
 290                  return markdown_to_html(get_string('cohortnonmemberinfo', 'enrol_self', $a));
 291              }
 292          }
 293  
 294          return true;
 295      }
 296  
 297      /**
 298       * Return information for enrolment instance containing list of parameters required
 299       * for enrolment, name of enrolment plugin etc.
 300       *
 301       * @param stdClass $instance enrolment instance
 302       * @return stdClass instance info.
 303       */
 304      public function get_enrol_info(stdClass $instance) {
 305  
 306          $instanceinfo = new stdClass();
 307          $instanceinfo->id = $instance->id;
 308          $instanceinfo->courseid = $instance->courseid;
 309          $instanceinfo->type = $this->get_name();
 310          $instanceinfo->name = $this->get_instance_name($instance);
 311          $instanceinfo->status = $this->can_self_enrol($instance);
 312  
 313          if ($instance->password) {
 314              $instanceinfo->requiredparam = new stdClass();
 315              $instanceinfo->requiredparam->enrolpassword = get_string('password', 'enrol_self');
 316          }
 317  
 318          // If enrolment is possible and password is required then return ws function name to get more information.
 319          if ((true === $instanceinfo->status) && $instance->password) {
 320              $instanceinfo->wsfunction = 'enrol_self_get_instance_info';
 321          }
 322          return $instanceinfo;
 323      }
 324  
 325      /**
 326       * Add new instance of enrol plugin with default settings.
 327       * @param stdClass $course
 328       * @return int id of new instance
 329       */
 330      public function add_default_instance($course) {
 331          $fields = $this->get_instance_defaults();
 332  
 333          if ($this->get_config('requirepassword')) {
 334              $fields['password'] = generate_password(20);
 335          }
 336  
 337          return $this->add_instance($course, $fields);
 338      }
 339  
 340      /**
 341       * Returns defaults for new instances.
 342       * @return array
 343       */
 344      public function get_instance_defaults() {
 345          $expirynotify = $this->get_config('expirynotify');
 346          if ($expirynotify == 2) {
 347              $expirynotify = 1;
 348              $notifyall = 1;
 349          } else {
 350              $notifyall = 0;
 351          }
 352  
 353          $fields = array();
 354          $fields['status']          = $this->get_config('status');
 355          $fields['roleid']          = $this->get_config('roleid');
 356          $fields['enrolperiod']     = $this->get_config('enrolperiod');
 357          $fields['expirynotify']    = $expirynotify;
 358          $fields['notifyall']       = $notifyall;
 359          $fields['expirythreshold'] = $this->get_config('expirythreshold');
 360          $fields['customint1']      = $this->get_config('groupkey');
 361          $fields['customint2']      = $this->get_config('longtimenosee');
 362          $fields['customint3']      = $this->get_config('maxenrolled');
 363          $fields['customint4']      = $this->get_config('sendcoursewelcomemessage');
 364          $fields['customint5']      = 0;
 365          $fields['customint6']      = $this->get_config('newenrols');
 366  
 367          return $fields;
 368      }
 369  
 370      /**
 371       * Send welcome email to specified user.
 372       *
 373       * @param stdClass $instance
 374       * @param stdClass $user user record
 375       * @return void
 376       */
 377      protected function email_welcome_message($instance, $user) {
 378          global $CFG, $DB;
 379  
 380          $course = $DB->get_record('course', array('id'=>$instance->courseid), '*', MUST_EXIST);
 381          $context = context_course::instance($course->id);
 382  
 383          $a = new stdClass();
 384          $a->coursename = format_string($course->fullname, true, array('context'=>$context));
 385          $a->profileurl = "$CFG->wwwroot/user/view.php?id=$user->id&course=$course->id";
 386  
 387          if (trim($instance->customtext1) !== '') {
 388              $message = $instance->customtext1;
 389              $key = array('{$a->coursename}', '{$a->profileurl}', '{$a->fullname}', '{$a->email}');
 390              $value = array($a->coursename, $a->profileurl, fullname($user), $user->email);
 391              $message = str_replace($key, $value, $message);
 392              if (strpos($message, '<') === false) {
 393                  // Plain text only.
 394                  $messagetext = $message;
 395                  $messagehtml = text_to_html($messagetext, null, false, true);
 396              } else {
 397                  // This is most probably the tag/newline soup known as FORMAT_MOODLE.
 398                  $messagehtml = format_text($message, FORMAT_MOODLE, array('context'=>$context, 'para'=>false, 'newlines'=>true, 'filter'=>true));
 399                  $messagetext = html_to_text($messagehtml);
 400              }
 401          } else {
 402              $messagetext = get_string('welcometocoursetext', 'enrol_self', $a);
 403              $messagehtml = text_to_html($messagetext, null, false, true);
 404          }
 405  
 406          $subject = get_string('welcometocourse', 'enrol_self', format_string($course->fullname, true, array('context'=>$context)));
 407  
 408          $sendoption = $instance->customint4;
 409          $contact = $this->get_welcome_email_contact($sendoption, $context);
 410  
 411          // Directly emailing welcome message rather than using messaging.
 412          email_to_user($user, $contact, $subject, $messagetext, $messagehtml);
 413      }
 414  
 415      /**
 416       * Sync all meta course links.
 417       *
 418       * @param progress_trace $trace
 419       * @param int $courseid one course, empty mean all
 420       * @return int 0 means ok, 1 means error, 2 means plugin disabled
 421       */
 422      public function sync(progress_trace $trace, $courseid = null) {
 423          global $DB;
 424  
 425          if (!enrol_is_enabled('self')) {
 426              $trace->finished();
 427              return 2;
 428          }
 429  
 430          // Unfortunately this may take a long time, execution can be interrupted safely here.
 431          core_php_time_limit::raise();
 432          raise_memory_limit(MEMORY_HUGE);
 433  
 434          $trace->output('Verifying self-enrolments...');
 435  
 436          $params = array('now'=>time(), 'useractive'=>ENROL_USER_ACTIVE, 'courselevel'=>CONTEXT_COURSE);
 437          $coursesql = "";
 438          if ($courseid) {
 439              $coursesql = "AND e.courseid = :courseid";
 440              $params['courseid'] = $courseid;
 441          }
 442  
 443          // Note: the logic of self enrolment guarantees that user logged in at least once (=== u.lastaccess set)
 444          //       and that user accessed course at least once too (=== user_lastaccess record exists).
 445  
 446          // First deal with users that did not log in for a really long time - they do not have user_lastaccess records.
 447          $sql = "SELECT e.*, ue.userid
 448                    FROM {user_enrolments} ue
 449                    JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = 'self' AND e.customint2 > 0)
 450                    JOIN {user} u ON u.id = ue.userid
 451                   WHERE :now - u.lastaccess > e.customint2
 452                         $coursesql";
 453          $rs = $DB->get_recordset_sql($sql, $params);
 454          foreach ($rs as $instance) {
 455              $userid = $instance->userid;
 456              unset($instance->userid);
 457              $this->unenrol_user($instance, $userid);
 458              $days = $instance->customint2 / DAYSECS;
 459              $trace->output("unenrolling user $userid from course $instance->courseid " .
 460                  "as they did not log in for at least $days days", 1);
 461          }
 462          $rs->close();
 463  
 464          // Now unenrol from course user did not visit for a long time.
 465          $sql = "SELECT e.*, ue.userid
 466                    FROM {user_enrolments} ue
 467                    JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = 'self' AND e.customint2 > 0)
 468                    JOIN {user_lastaccess} ul ON (ul.userid = ue.userid AND ul.courseid = e.courseid)
 469                   WHERE :now - ul.timeaccess > e.customint2
 470                         $coursesql";
 471          $rs = $DB->get_recordset_sql($sql, $params);
 472          foreach ($rs as $instance) {
 473              $userid = $instance->userid;
 474              unset($instance->userid);
 475              $this->unenrol_user($instance, $userid);
 476              $days = $instance->customint2 / DAYSECS;
 477              $trace->output("unenrolling user $userid from course $instance->courseid " .
 478                  "as they did not access the course for at least $days days", 1);
 479          }
 480          $rs->close();
 481  
 482          $trace->output('...user self-enrolment updates finished.');
 483          $trace->finished();
 484  
 485          $this->process_expirations($trace, $courseid);
 486  
 487          return 0;
 488      }
 489  
 490      /**
 491       * Returns the user who is responsible for self enrolments in given instance.
 492       *
 493       * Usually it is the first editing teacher - the person with "highest authority"
 494       * as defined by sort_by_roleassignment_authority() having 'enrol/self:manage'
 495       * capability.
 496       *
 497       * @param int $instanceid enrolment instance id
 498       * @return stdClass user record
 499       */
 500      protected function get_enroller($instanceid) {
 501          global $DB;
 502  
 503          if ($this->lasternollerinstanceid == $instanceid and $this->lasternoller) {
 504              return $this->lasternoller;
 505          }
 506  
 507          $instance = $DB->get_record('enrol', array('id'=>$instanceid, 'enrol'=>$this->get_name()), '*', MUST_EXIST);
 508          $context = context_course::instance($instance->courseid);
 509  
 510          if ($users = get_enrolled_users($context, 'enrol/self:manage')) {
 511              $users = sort_by_roleassignment_authority($users, $context);
 512              $this->lasternoller = reset($users);
 513              unset($users);
 514          } else {
 515              $this->lasternoller = parent::get_enroller($instanceid);
 516          }
 517  
 518          $this->lasternollerinstanceid = $instanceid;
 519  
 520          return $this->lasternoller;
 521      }
 522  
 523      /**
 524       * Restore instance and map settings.
 525       *
 526       * @param restore_enrolments_structure_step $step
 527       * @param stdClass $data
 528       * @param stdClass $course
 529       * @param int $oldid
 530       */
 531      public function restore_instance(restore_enrolments_structure_step $step, stdClass $data, $course, $oldid) {
 532          global $DB;
 533          if ($step->get_task()->get_target() == backup::TARGET_NEW_COURSE) {
 534              $merge = false;
 535          } else {
 536              $merge = array(
 537                  'courseid'   => $data->courseid,
 538                  'enrol'      => $this->get_name(),
 539                  'status'     => $data->status,
 540                  'roleid'     => $data->roleid,
 541              );
 542          }
 543          if ($merge and $instances = $DB->get_records('enrol', $merge, 'id')) {
 544              $instance = reset($instances);
 545              $instanceid = $instance->id;
 546          } else {
 547              if (!empty($data->customint5)) {
 548                  if ($step->get_task()->is_samesite()) {
 549                      // Keep cohort restriction unchanged - we are on the same site.
 550                  } else {
 551                      // Use some id that can not exist in order to prevent self enrolment,
 552                      // because we do not know what cohort it is in this site.
 553                      $data->customint5 = -1;
 554                  }
 555              }
 556              $instanceid = $this->add_instance($course, (array)$data);
 557          }
 558          $step->set_mapping('enrol', $oldid, $instanceid);
 559      }
 560  
 561      /**
 562       * Restore user enrolment.
 563       *
 564       * @param restore_enrolments_structure_step $step
 565       * @param stdClass $data
 566       * @param stdClass $instance
 567       * @param int $oldinstancestatus
 568       * @param int $userid
 569       */
 570      public function restore_user_enrolment(restore_enrolments_structure_step $step, $data, $instance, $userid, $oldinstancestatus) {
 571          $this->enrol_user($instance, $userid, null, $data->timestart, $data->timeend, $data->status);
 572      }
 573  
 574      /**
 575       * Restore role assignment.
 576       *
 577       * @param stdClass $instance
 578       * @param int $roleid
 579       * @param int $userid
 580       * @param int $contextid
 581       */
 582      public function restore_role_assignment($instance, $roleid, $userid, $contextid) {
 583          // This is necessary only because we may migrate other types to this instance,
 584          // we do not use component in manual or self enrol.
 585          role_assign($roleid, $userid, $contextid, '', 0);
 586      }
 587  
 588      /**
 589       * Is it possible to delete enrol instance via standard UI?
 590       *
 591       * @param stdClass $instance
 592       * @return bool
 593       */
 594      public function can_delete_instance($instance) {
 595          $context = context_course::instance($instance->courseid);
 596          return has_capability('enrol/self:config', $context);
 597      }
 598  
 599      /**
 600       * Is it possible to hide/show enrol instance via standard UI?
 601       *
 602       * @param stdClass $instance
 603       * @return bool
 604       */
 605      public function can_hide_show_instance($instance) {
 606          $context = context_course::instance($instance->courseid);
 607  
 608          if (!has_capability('enrol/self:config', $context)) {
 609              return false;
 610          }
 611  
 612          // If the instance is currently disabled, before it can be enabled,
 613          // we must check whether the password meets the password policies.
 614          if ($instance->status == ENROL_INSTANCE_DISABLED) {
 615              if ($this->get_config('requirepassword')) {
 616                  if (empty($instance->password)) {
 617                      return false;
 618                  }
 619              }
 620              // Only check the password if it is set.
 621              if (!empty($instance->password) && $this->get_config('usepasswordpolicy')) {
 622                  if (!check_password_policy($instance->password, $errmsg)) {
 623                      return false;
 624                  }
 625              }
 626          }
 627  
 628          return true;
 629      }
 630  
 631      /**
 632       * Return an array of valid options for the status.
 633       *
 634       * @return array
 635       */
 636      protected function get_status_options() {
 637          $options = array(ENROL_INSTANCE_ENABLED  => get_string('yes'),
 638                           ENROL_INSTANCE_DISABLED => get_string('no'));
 639          return $options;
 640      }
 641  
 642      /**
 643       * Return an array of valid options for the newenrols property.
 644       *
 645       * @return array
 646       */
 647      protected function get_newenrols_options() {
 648          $options = array(1 => get_string('yes'), 0 => get_string('no'));
 649          return $options;
 650      }
 651  
 652      /**
 653       * Return an array of valid options for the groupkey property.
 654       *
 655       * @return array
 656       */
 657      protected function get_groupkey_options() {
 658          $options = array(1 => get_string('yes'), 0 => get_string('no'));
 659          return $options;
 660      }
 661  
 662      /**
 663       * Return an array of valid options for the expirynotify property.
 664       *
 665       * @return array
 666       */
 667      protected function get_expirynotify_options() {
 668          $options = array(0 => get_string('no'),
 669                           1 => get_string('expirynotifyenroller', 'enrol_self'),
 670                           2 => get_string('expirynotifyall', 'enrol_self'));
 671          return $options;
 672      }
 673  
 674      /**
 675       * Return an array of valid options for the longtimenosee property.
 676       *
 677       * @return array
 678       */
 679      protected function get_longtimenosee_options() {
 680          $options = array(0 => get_string('never'),
 681                           1800 * 3600 * 24 => get_string('numdays', '', 1800),
 682                           1000 * 3600 * 24 => get_string('numdays', '', 1000),
 683                           365 * 3600 * 24 => get_string('numdays', '', 365),
 684                           180 * 3600 * 24 => get_string('numdays', '', 180),
 685                           150 * 3600 * 24 => get_string('numdays', '', 150),
 686                           120 * 3600 * 24 => get_string('numdays', '', 120),
 687                           90 * 3600 * 24 => get_string('numdays', '', 90),
 688                           60 * 3600 * 24 => get_string('numdays', '', 60),
 689                           30 * 3600 * 24 => get_string('numdays', '', 30),
 690                           21 * 3600 * 24 => get_string('numdays', '', 21),
 691                           14 * 3600 * 24 => get_string('numdays', '', 14),
 692                           7 * 3600 * 24 => get_string('numdays', '', 7));
 693          return $options;
 694      }
 695  
 696      /**
 697       * The self enrollment plugin has several bulk operations that can be performed.
 698       * @param course_enrolment_manager $manager
 699       * @return array
 700       */
 701      public function get_bulk_operations(course_enrolment_manager $manager) {
 702          global $CFG;
 703          require_once($CFG->dirroot.'/enrol/self/locallib.php');
 704          $context = $manager->get_context();
 705          $bulkoperations = array();
 706          if (has_capability("enrol/self:manage", $context)) {
 707              $bulkoperations['editselectedusers'] = new enrol_self_editselectedusers_operation($manager, $this);
 708          }
 709          if (has_capability("enrol/self:unenrol", $context)) {
 710              $bulkoperations['deleteselectedusers'] = new enrol_self_deleteselectedusers_operation($manager, $this);
 711          }
 712          return $bulkoperations;
 713      }
 714  
 715      /**
 716       * Add elements to the edit instance form.
 717       *
 718       * @param stdClass $instance
 719       * @param MoodleQuickForm $mform
 720       * @param context $context
 721       * @return bool
 722       */
 723      public function edit_instance_form($instance, MoodleQuickForm $mform, $context) {
 724          global $CFG, $DB;
 725  
 726          // Merge these two settings to one value for the single selection element.
 727          if ($instance->notifyall and $instance->expirynotify) {
 728              $instance->expirynotify = 2;
 729          }
 730          unset($instance->notifyall);
 731  
 732          $nameattribs = array('size' => '20', 'maxlength' => '255');
 733          $mform->addElement('text', 'name', get_string('custominstancename', 'enrol'), $nameattribs);
 734          $mform->setType('name', PARAM_TEXT);
 735          $mform->addRule('name', get_string('maximumchars', '', 255), 'maxlength', 255, 'server');
 736  
 737          $options = $this->get_status_options();
 738          $mform->addElement('select', 'status', get_string('status', 'enrol_self'), $options);
 739          $mform->addHelpButton('status', 'status', 'enrol_self');
 740  
 741          $options = $this->get_newenrols_options();
 742          $mform->addElement('select', 'customint6', get_string('newenrols', 'enrol_self'), $options);
 743          $mform->addHelpButton('customint6', 'newenrols', 'enrol_self');
 744          $mform->disabledIf('customint6', 'status', 'eq', ENROL_INSTANCE_DISABLED);
 745  
 746          $passattribs = array('size' => '20', 'maxlength' => '50');
 747          $mform->addElement('passwordunmask', 'password', get_string('password', 'enrol_self'), $passattribs);
 748          $mform->addHelpButton('password', 'password', 'enrol_self');
 749          if (empty($instance->id) and $this->get_config('requirepassword')) {
 750              $mform->addRule('password', get_string('required'), 'required', null, 'client');
 751          }
 752          $mform->addRule('password', get_string('maximumchars', '', 50), 'maxlength', 50, 'server');
 753  
 754          $options = $this->get_groupkey_options();
 755          $mform->addElement('select', 'customint1', get_string('groupkey', 'enrol_self'), $options);
 756          $mform->addHelpButton('customint1', 'groupkey', 'enrol_self');
 757  
 758          $roles = $this->extend_assignable_roles($context, $instance->roleid);
 759          $mform->addElement('select', 'roleid', get_string('role', 'enrol_self'), $roles);
 760  
 761          $options = array('optional' => true, 'defaultunit' => 86400);
 762          $mform->addElement('duration', 'enrolperiod', get_string('enrolperiod', 'enrol_self'), $options);
 763          $mform->addHelpButton('enrolperiod', 'enrolperiod', 'enrol_self');
 764  
 765          $options = $this->get_expirynotify_options();
 766          $mform->addElement('select', 'expirynotify', get_string('expirynotify', 'core_enrol'), $options);
 767          $mform->addHelpButton('expirynotify', 'expirynotify', 'core_enrol');
 768  
 769          $options = array('optional' => false, 'defaultunit' => 86400);
 770          $mform->addElement('duration', 'expirythreshold', get_string('expirythreshold', 'core_enrol'), $options);
 771          $mform->addHelpButton('expirythreshold', 'expirythreshold', 'core_enrol');
 772          $mform->disabledIf('expirythreshold', 'expirynotify', 'eq', 0);
 773  
 774          $options = array('optional' => true);
 775          $mform->addElement('date_time_selector', 'enrolstartdate', get_string('enrolstartdate', 'enrol_self'), $options);
 776          $mform->setDefault('enrolstartdate', 0);
 777          $mform->addHelpButton('enrolstartdate', 'enrolstartdate', 'enrol_self');
 778  
 779          $options = array('optional' => true);
 780          $mform->addElement('date_time_selector', 'enrolenddate', get_string('enrolenddate', 'enrol_self'), $options);
 781          $mform->setDefault('enrolenddate', 0);
 782          $mform->addHelpButton('enrolenddate', 'enrolenddate', 'enrol_self');
 783  
 784          $options = $this->get_longtimenosee_options();
 785          $mform->addElement('select', 'customint2', get_string('longtimenosee', 'enrol_self'), $options);
 786          $mform->addHelpButton('customint2', 'longtimenosee', 'enrol_self');
 787  
 788          $mform->addElement('text', 'customint3', get_string('maxenrolled', 'enrol_self'));
 789          $mform->addHelpButton('customint3', 'maxenrolled', 'enrol_self');
 790          $mform->setType('customint3', PARAM_INT);
 791  
 792          require_once($CFG->dirroot.'/cohort/lib.php');
 793  
 794          $cohorts = array(0 => get_string('no'));
 795          $allcohorts = cohort_get_available_cohorts($context, 0, 0, 0);
 796          if ($instance->customint5 && !isset($allcohorts[$instance->customint5])) {
 797              $c = $DB->get_record('cohort',
 798                                   array('id' => $instance->customint5),
 799                                   'id, name, idnumber, contextid, visible',
 800                                   IGNORE_MISSING);
 801              if ($c) {
 802                  // Current cohort was not found because current user can not see it. Still keep it.
 803                  $allcohorts[$instance->customint5] = $c;
 804              }
 805          }
 806          foreach ($allcohorts as $c) {
 807              $cohorts[$c->id] = format_string($c->name, true, array('context' => context::instance_by_id($c->contextid)));
 808              if ($c->idnumber) {
 809                  $cohorts[$c->id] .= ' ['.s($c->idnumber).']';
 810              }
 811          }
 812          if ($instance->customint5 && !isset($allcohorts[$instance->customint5])) {
 813              // Somebody deleted a cohort, better keep the wrong value so that random ppl can not enrol.
 814              $cohorts[$instance->customint5] = get_string('unknowncohort', 'cohort', $instance->customint5);
 815          }
 816          if (count($cohorts) > 1) {
 817              $mform->addElement('select', 'customint5', get_string('cohortonly', 'enrol_self'), $cohorts);
 818              $mform->addHelpButton('customint5', 'cohortonly', 'enrol_self');
 819          } else {
 820              $mform->addElement('hidden', 'customint5');
 821              $mform->setType('customint5', PARAM_INT);
 822              $mform->setConstant('customint5', 0);
 823          }
 824  
 825          $mform->addElement('select', 'customint4', get_string('sendcoursewelcomemessage', 'enrol_self'),
 826                  enrol_send_welcome_email_options());
 827          $mform->addHelpButton('customint4', 'sendcoursewelcomemessage', 'enrol_self');
 828  
 829          $options = array('cols' => '60', 'rows' => '8');
 830          $mform->addElement('textarea', 'customtext1', get_string('customwelcomemessage', 'enrol_self'), $options);
 831          $mform->addHelpButton('customtext1', 'customwelcomemessage', 'enrol_self');
 832  
 833          if (enrol_accessing_via_instance($instance)) {
 834              $warntext = get_string('instanceeditselfwarningtext', 'core_enrol');
 835              $mform->addElement('static', 'selfwarn', get_string('instanceeditselfwarning', 'core_enrol'), $warntext);
 836          }
 837      }
 838  
 839      /**
 840       * We are a good plugin and don't invent our own UI/validation code path.
 841       *
 842       * @return boolean
 843       */
 844      public function use_standard_editing_ui() {
 845          return true;
 846      }
 847  
 848      /**
 849       * Perform custom validation of the data used to edit the instance.
 850       *
 851       * @param array $data array of ("fieldname"=>value) of submitted data
 852       * @param array $files array of uploaded files "element_name"=>tmp_file_path
 853       * @param object $instance The instance loaded from the DB
 854       * @param context $context The context of the instance we are editing
 855       * @return array of "element_name"=>"error_description" if there are errors,
 856       *         or an empty array if everything is OK.
 857       * @return void
 858       */
 859      public function edit_instance_validation($data, $files, $instance, $context) {
 860          $errors = array();
 861  
 862          $checkpassword = false;
 863  
 864          if ($instance->id) {
 865              // Check the password if we are enabling the plugin again.
 866              if (($instance->status == ENROL_INSTANCE_DISABLED) && ($data['status'] == ENROL_INSTANCE_ENABLED)) {
 867                  $checkpassword = true;
 868              }
 869  
 870              // Check the password if the instance is enabled and the password has changed.
 871              if (($data['status'] == ENROL_INSTANCE_ENABLED) && ($instance->password !== $data['password'])) {
 872                  $checkpassword = true;
 873              }
 874          } else {
 875              $checkpassword = true;
 876          }
 877  
 878          if ($checkpassword) {
 879              $require = $this->get_config('requirepassword');
 880              $policy  = $this->get_config('usepasswordpolicy');
 881              if ($require and trim($data['password']) === '') {
 882                  $errors['password'] = get_string('required');
 883              } else if (!empty($data['password']) && $policy) {
 884                  $errmsg = '';
 885                  if (!check_password_policy($data['password'], $errmsg)) {
 886                      $errors['password'] = $errmsg;
 887                  }
 888              }
 889          }
 890  
 891          if ($data['status'] == ENROL_INSTANCE_ENABLED) {
 892              if (!empty($data['enrolenddate']) and $data['enrolenddate'] < $data['enrolstartdate']) {
 893                  $errors['enrolenddate'] = get_string('enrolenddaterror', 'enrol_self');
 894              }
 895          }
 896  
 897          if ($data['expirynotify'] > 0 and $data['expirythreshold'] < 86400) {
 898              $errors['expirythreshold'] = get_string('errorthresholdlow', 'core_enrol');
 899          }
 900  
 901          // Now these ones are checked by quickforms, but we may be called by the upload enrolments tool, or a webservive.
 902          if (core_text::strlen($data['name']) > 255) {
 903              $errors['name'] = get_string('err_maxlength', 'form', 255);
 904          }
 905          $validstatus = array_keys($this->get_status_options());
 906          $validnewenrols = array_keys($this->get_newenrols_options());
 907          if (core_text::strlen($data['password']) > 50) {
 908              $errors['name'] = get_string('err_maxlength', 'form', 50);
 909          }
 910          $validgroupkey = array_keys($this->get_groupkey_options());
 911          $context = context_course::instance($instance->courseid);
 912          $validroles = array_keys($this->extend_assignable_roles($context, $instance->roleid));
 913          $validexpirynotify = array_keys($this->get_expirynotify_options());
 914          $validlongtimenosee = array_keys($this->get_longtimenosee_options());
 915          $tovalidate = array(
 916              'enrolstartdate' => PARAM_INT,
 917              'enrolenddate' => PARAM_INT,
 918              'name' => PARAM_TEXT,
 919              'customint1' => $validgroupkey,
 920              'customint2' => $validlongtimenosee,
 921              'customint3' => PARAM_INT,
 922              'customint4' => PARAM_INT,
 923              'customint5' => PARAM_INT,
 924              'customint6' => $validnewenrols,
 925              'status' => $validstatus,
 926              'enrolperiod' => PARAM_INT,
 927              'expirynotify' => $validexpirynotify,
 928              'roleid' => $validroles
 929          );
 930          if ($data['expirynotify'] != 0) {
 931              $tovalidate['expirythreshold'] = PARAM_INT;
 932          }
 933          $typeerrors = $this->validate_param_types($data, $tovalidate);
 934          $errors = array_merge($errors, $typeerrors);
 935  
 936          return $errors;
 937      }
 938  
 939      /**
 940       * Add new instance of enrol plugin.
 941       * @param object $course
 942       * @param array $fields instance fields
 943       * @return int id of new instance, null if can not be created
 944       */
 945      public function add_instance($course, array $fields = null) {
 946          // In the form we are representing 2 db columns with one field.
 947          if (!empty($fields) && !empty($fields['expirynotify'])) {
 948              if ($fields['expirynotify'] == 2) {
 949                  $fields['expirynotify'] = 1;
 950                  $fields['notifyall'] = 1;
 951              } else {
 952                  $fields['notifyall'] = 0;
 953              }
 954          }
 955  
 956          return parent::add_instance($course, $fields);
 957      }
 958  
 959      /**
 960       * Update instance of enrol plugin.
 961       * @param stdClass $instance
 962       * @param stdClass $data modified instance fields
 963       * @return boolean
 964       */
 965      public function update_instance($instance, $data) {
 966          // In the form we are representing 2 db columns with one field.
 967          if ($data->expirynotify == 2) {
 968              $data->expirynotify = 1;
 969              $data->notifyall = 1;
 970          } else {
 971              $data->notifyall = 0;
 972          }
 973          // Keep previous/default value of disabled expirythreshold option.
 974          if (!$data->expirynotify) {
 975              $data->expirythreshold = $instance->expirythreshold;
 976          }
 977          // Add previous value of newenrols if disabled.
 978          if (!isset($data->customint6)) {
 979              $data->customint6 = $instance->customint6;
 980          }
 981  
 982          return parent::update_instance($instance, $data);
 983      }
 984  
 985      /**
 986       * Gets a list of roles that this user can assign for the course as the default for self-enrolment.
 987       *
 988       * @param context $context the context.
 989       * @param integer $defaultrole the id of the role that is set as the default for self-enrolment
 990       * @return array index is the role id, value is the role name
 991       */
 992      public function extend_assignable_roles($context, $defaultrole) {
 993          global $DB;
 994  
 995          $roles = get_assignable_roles($context, ROLENAME_BOTH);
 996          if (!isset($roles[$defaultrole])) {
 997              if ($role = $DB->get_record('role', array('id' => $defaultrole))) {
 998                  $roles[$defaultrole] = role_get_name($role, $context, ROLENAME_BOTH);
 999              }
1000          }
1001          return $roles;
1002      }
1003  
1004      /**
1005       * Get the "from" contact which the email will be sent from.
1006       *
1007       * @param int $sendoption send email from constant ENROL_SEND_EMAIL_FROM_*
1008       * @param $context context where the user will be fetched
1009       * @return mixed|stdClass the contact user object.
1010       */
1011      public function get_welcome_email_contact($sendoption, $context) {
1012          global $CFG;
1013  
1014          $contact = null;
1015          // Send as the first user assigned as the course contact.
1016          if ($sendoption == ENROL_SEND_EMAIL_FROM_COURSE_CONTACT) {
1017              $rusers = array();
1018              if (!empty($CFG->coursecontact)) {
1019                  $croles = explode(',', $CFG->coursecontact);
1020                  list($sort, $sortparams) = users_order_by_sql('u');
1021                  // We only use the first user.
1022                  $i = 0;
1023                  do {
1024                      $userfieldsapi = \core_user\fields::for_name();
1025                      $allnames = $userfieldsapi->get_sql('u', false, '', '', false)->selects;
1026                      $rusers = get_role_users($croles[$i], $context, true, 'u.id,  u.confirmed, u.username, '. $allnames . ',
1027                      u.email, r.sortorder, ra.id', 'r.sortorder, ra.id ASC, ' . $sort, null, '', '', '', '', $sortparams);
1028                      $i++;
1029                  } while (empty($rusers) && !empty($croles[$i]));
1030              }
1031              if ($rusers) {
1032                  $contact = array_values($rusers)[0];
1033              }
1034          } else if ($sendoption == ENROL_SEND_EMAIL_FROM_KEY_HOLDER) {
1035              // Send as the first user with enrol/self:holdkey capability assigned in the course.
1036              list($sort) = users_order_by_sql('u');
1037              $keyholders = get_users_by_capability($context, 'enrol/self:holdkey', 'u.*', $sort);
1038              if (!empty($keyholders)) {
1039                  $contact = array_values($keyholders)[0];
1040              }
1041          }
1042  
1043          // If send welcome email option is set to no reply or if none of the previous options have
1044          // returned a contact send welcome message as noreplyuser.
1045          if ($sendoption == ENROL_SEND_EMAIL_FROM_NOREPLY || empty($contact)) {
1046              $contact = core_user::get_noreply_user();
1047          }
1048  
1049          return $contact;
1050      }
1051  }
1052  
1053  /**
1054   * Get icon mapping for font-awesome.
1055   */
1056  function enrol_self_get_fontawesome_icon_map() {
1057      return [
1058          'enrol_self:withkey' => 'fa-key',
1059          'enrol_self:withoutkey' => 'fa-sign-in',
1060      ];
1061  }