Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.3.x will end 7 October 2024 (12 months).
  • Bug fixes for security issues in 4.3.x will end 21 April 2025 (18 months).
  • PHP version: minimum PHP 8.0.0 Note: minimum PHP version has increased since Moodle 4.1. PHP 8.2.x is supported too.
/enrol/self/ -> lib.php (source)

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