Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.10.x will end 8 November 2021 (12 months).
  • Bug fixes for security issues in 3.10.x will end 9 May 2022 (18 months).
  • PHP version: minimum PHP 7.2.0 Note: minimum PHP version has increased since Moodle 3.8. PHP 7.3.x and 7.4.x are supported too.

Differences Between: [Versions 310 and 311] [Versions 310 and 400] [Versions 310 and 401] [Versions 310 and 402] [Versions 310 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   * Fee enrolment plugin.
  19   *
  20   * This plugin allows you to set up paid courses.
  21   *
  22   * @package    enrol_fee
  23   * @copyright  2019 Shamim Rezaie <shamim@moodle.com>
  24   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  25   */
  26  
  27  /**
  28   * Fee enrolment plugin implementation.
  29   *
  30   * @copyright  2019 Shamim Rezaie <shamim@moodle.com>
  31   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  32   */
  33  class enrol_fee_plugin extends enrol_plugin {
  34  
  35      /**
  36       * Returns the list of currencies that the payment subsystem supports and therefore we can work with.
  37       *
  38       * @return array[currencycode => currencyname]
  39       */
  40      public function get_possible_currencies(): array {
  41          $codes = \core_payment\helper::get_supported_currencies();
  42  
  43          $currencies = [];
  44          foreach ($codes as $c) {
  45              $currencies[$c] = new lang_string($c, 'core_currencies');
  46          }
  47  
  48          uasort($currencies, function($a, $b) {
  49              return strcmp($a, $b);
  50          });
  51  
  52          return $currencies;
  53      }
  54  
  55      /**
  56       * Returns optional enrolment information icons.
  57       *
  58       * This is used in course list for quick overview of enrolment options.
  59       *
  60       * We are not using single instance parameter because sometimes
  61       * we might want to prevent icon repetition when multiple instances
  62       * of one type exist. One instance may also produce several icons.
  63       *
  64       * @param array $instances all enrol instances of this type in one course
  65       * @return array of pix_icon
  66       */
  67      public function get_info_icons(array $instances) {
  68          $found = false;
  69          foreach ($instances as $instance) {
  70              if ($instance->enrolstartdate != 0 && $instance->enrolstartdate > time()) {
  71                  continue;
  72              }
  73              if ($instance->enrolenddate != 0 && $instance->enrolenddate < time()) {
  74                  continue;
  75              }
  76              $found = true;
  77              break;
  78          }
  79          if ($found) {
  80              return array(new pix_icon('icon', get_string('pluginname', 'enrol_fee'), 'enrol_fee'));
  81          }
  82          return array();
  83      }
  84  
  85      public function roles_protected() {
  86          // Users with role assign cap may tweak the roles later.
  87          return false;
  88      }
  89  
  90      public function allow_unenrol(stdClass $instance) {
  91          // Users with unenrol cap may unenrol other users manually - requires enrol/fee:unenrol.
  92          return true;
  93      }
  94  
  95      public function allow_manage(stdClass $instance) {
  96          // Users with manage cap may tweak period and status - requires enrol/fee:manage.
  97          return true;
  98      }
  99  
 100      public function show_enrolme_link(stdClass $instance) {
 101          return ($instance->status == ENROL_INSTANCE_ENABLED);
 102      }
 103  
 104      /**
 105       * Returns true if the user can add a new instance in this course.
 106       * @param int $courseid
 107       * @return boolean
 108       */
 109      public function can_add_instance($courseid) {
 110          $context = context_course::instance($courseid, MUST_EXIST);
 111  
 112          if (empty(\core_payment\helper::get_supported_currencies())) {
 113              return false;
 114          }
 115  
 116          if (!has_capability('moodle/course:enrolconfig', $context) or !has_capability('enrol/fee:config', $context)) {
 117              return false;
 118          }
 119  
 120          // Multiple instances supported - different cost for different roles.
 121          return true;
 122      }
 123  
 124      /**
 125       * We are a good plugin and don't invent our own UI/validation code path.
 126       *
 127       * @return boolean
 128       */
 129      public function use_standard_editing_ui() {
 130          return true;
 131      }
 132  
 133      /**
 134       * Add new instance of enrol plugin.
 135       * @param object $course
 136       * @param array $fields instance fields
 137       * @return int id of new instance, null if can not be created
 138       */
 139      public function add_instance($course, array $fields = null) {
 140          if ($fields && !empty($fields['cost'])) {
 141              $fields['cost'] = unformat_float($fields['cost']);
 142          }
 143          return parent::add_instance($course, $fields);
 144      }
 145  
 146      /**
 147       * Update instance of enrol plugin.
 148       * @param stdClass $instance
 149       * @param stdClass $data modified instance fields
 150       * @return boolean
 151       */
 152      public function update_instance($instance, $data) {
 153          if ($data) {
 154              $data->cost = unformat_float($data->cost);
 155          }
 156          return parent::update_instance($instance, $data);
 157      }
 158  
 159      /**
 160       * Creates course enrol form, checks if form submitted
 161       * and enrols user if necessary. It can also redirect.
 162       *
 163       * @param stdClass $instance
 164       * @return string html text, usually a form in a text box
 165       */
 166      public function enrol_page_hook(stdClass $instance) {
 167          global $CFG, $USER, $OUTPUT, $PAGE, $DB;
 168  
 169          ob_start();
 170  
 171          if ($DB->record_exists('user_enrolments', array('userid' => $USER->id, 'enrolid' => $instance->id))) {
 172              return ob_get_clean();
 173          }
 174  
 175          if ($instance->enrolstartdate != 0 && $instance->enrolstartdate > time()) {
 176              return ob_get_clean();
 177          }
 178  
 179          if ($instance->enrolenddate != 0 && $instance->enrolenddate < time()) {
 180              return ob_get_clean();
 181          }
 182  
 183          $course = $DB->get_record('course', array('id' => $instance->courseid));
 184          $context = context_course::instance($course->id);
 185  
 186          $shortname = format_string($course->shortname, true, array('context' => $context));
 187          $strloginto = get_string("loginto", "", $shortname);
 188          $strcourses = get_string("courses");
 189  
 190          // Pass $view=true to filter hidden caps if the user cannot see them.
 191          if ($users = get_users_by_capability($context, 'moodle/course:update', 'u.*', 'u.id ASC',
 192                                               '', '', '', '', false, true)) {
 193              $users = sort_by_roleassignment_authority($users, $context);
 194              $teacher = array_shift($users);
 195          } else {
 196              $teacher = false;
 197          }
 198  
 199          if ( (float) $instance->cost <= 0 ) {
 200              $cost = (float) $this->get_config('cost');
 201          } else {
 202              $cost = (float) $instance->cost;
 203          }
 204  
 205          if (abs($cost) < 0.01) { // No cost, other enrolment methods (instances) should be used.
 206              echo '<p>'.get_string('nocost', 'enrol_fee').'</p>';
 207          } else {
 208  
 209              $data = [
 210                  'isguestuser' => isguestuser(),
 211                  'cost' => \core_payment\helper::get_cost_as_string($cost, $instance->currency),
 212                  'instanceid' => $instance->id,
 213                  'description' => get_string('purchasedescription', 'enrol_fee',
 214                      format_string($course->fullname, true, ['context' => $context])),
 215              ];
 216              echo $OUTPUT->render_from_template('enrol_fee/payment_region', $data);
 217          }
 218  
 219          return $OUTPUT->box(ob_get_clean());
 220      }
 221  
 222      /**
 223       * Restore instance and map settings.
 224       *
 225       * @param restore_enrolments_structure_step $step
 226       * @param stdClass $data
 227       * @param stdClass $course
 228       * @param int $oldid
 229       */
 230      public function restore_instance(restore_enrolments_structure_step $step, stdClass $data, $course, $oldid) {
 231          global $DB;
 232          if ($step->get_task()->get_target() == backup::TARGET_NEW_COURSE) {
 233              $merge = false;
 234          } else {
 235              $merge = array(
 236                  'courseid'   => $data->courseid,
 237                  'enrol'      => $this->get_name(),
 238                  'roleid'     => $data->roleid,
 239                  'cost'       => $data->cost,
 240                  'currency'   => $data->currency,
 241              );
 242          }
 243          if ($merge and $instances = $DB->get_records('enrol', $merge, 'id')) {
 244              $instance = reset($instances);
 245              $instanceid = $instance->id;
 246          } else {
 247              $instanceid = $this->add_instance($course, (array) $data);
 248          }
 249          $step->set_mapping('enrol', $oldid, $instanceid);
 250      }
 251  
 252      /**
 253       * Restore user enrolment.
 254       *
 255       * @param restore_enrolments_structure_step $step
 256       * @param stdClass $data
 257       * @param stdClass $instance
 258       * @param int $oldinstancestatus
 259       * @param int $userid
 260       */
 261      public function restore_user_enrolment(restore_enrolments_structure_step $step, $data, $instance, $userid, $oldinstancestatus) {
 262          $this->enrol_user($instance, $userid, null, $data->timestart, $data->timeend, $data->status);
 263      }
 264  
 265      /**
 266       * Return an array of valid options for the status.
 267       *
 268       * @return array
 269       */
 270      protected function get_status_options() {
 271          $options = array(ENROL_INSTANCE_ENABLED  => get_string('yes'),
 272                           ENROL_INSTANCE_DISABLED => get_string('no'));
 273          return $options;
 274      }
 275  
 276      /**
 277       * Return an array of valid options for the roleid.
 278       *
 279       * @param stdClass $instance
 280       * @param context $context
 281       * @return array
 282       */
 283      protected function get_roleid_options($instance, $context) {
 284          if ($instance->id) {
 285              $roles = get_default_enrol_roles($context, $instance->roleid);
 286          } else {
 287              $roles = get_default_enrol_roles($context, $this->get_config('roleid'));
 288          }
 289          return $roles;
 290      }
 291  
 292  
 293      /**
 294       * Add elements to the edit instance form.
 295       *
 296       * @param stdClass $instance
 297       * @param MoodleQuickForm $mform
 298       * @param context $context
 299       * @return bool
 300       */
 301      public function edit_instance_form($instance, MoodleQuickForm $mform, $context) {
 302  
 303          $mform->addElement('text', 'name', get_string('custominstancename', 'enrol'));
 304          $mform->setType('name', PARAM_TEXT);
 305  
 306          $options = $this->get_status_options();
 307          $mform->addElement('select', 'status', get_string('status', 'enrol_fee'), $options);
 308          $mform->setDefault('status', $this->get_config('status'));
 309  
 310          $accounts = \core_payment\helper::get_payment_accounts_menu($context);
 311          if ($accounts) {
 312              $accounts = ((count($accounts) > 1) ? ['' => ''] : []) + $accounts;
 313              $mform->addElement('select', 'customint1', get_string('paymentaccount', 'payment'), $accounts);
 314          } else {
 315              $mform->addElement('static', 'customint1_text', get_string('paymentaccount', 'payment'),
 316                  html_writer::span(get_string('noaccountsavilable', 'payment'), 'alert alert-danger'));
 317              $mform->addElement('hidden', 'customint1');
 318              $mform->setType('customint1', PARAM_INT);
 319          }
 320          $mform->addHelpButton('customint1', 'paymentaccount', 'enrol_fee');
 321  
 322          $mform->addElement('text', 'cost', get_string('cost', 'enrol_fee'), array('size' => 4));
 323          $mform->setType('cost', PARAM_RAW);
 324          $mform->setDefault('cost', format_float($this->get_config('cost'), 2, true));
 325  
 326          $supportedcurrencies = $this->get_possible_currencies();
 327          $mform->addElement('select', 'currency', get_string('currency', 'enrol_fee'), $supportedcurrencies);
 328          $mform->setDefault('currency', $this->get_config('currency'));
 329  
 330          $roles = $this->get_roleid_options($instance, $context);
 331          $mform->addElement('select', 'roleid', get_string('assignrole', 'enrol_fee'), $roles);
 332          $mform->setDefault('roleid', $this->get_config('roleid'));
 333  
 334          $options = array('optional' => true, 'defaultunit' => 86400);
 335          $mform->addElement('duration', 'enrolperiod', get_string('enrolperiod', 'enrol_fee'), $options);
 336          $mform->setDefault('enrolperiod', $this->get_config('enrolperiod'));
 337          $mform->addHelpButton('enrolperiod', 'enrolperiod', 'enrol_fee');
 338  
 339          $options = array('optional' => true);
 340          $mform->addElement('date_time_selector', 'enrolstartdate', get_string('enrolstartdate', 'enrol_fee'), $options);
 341          $mform->setDefault('enrolstartdate', 0);
 342          $mform->addHelpButton('enrolstartdate', 'enrolstartdate', 'enrol_fee');
 343  
 344          $options = array('optional' => true);
 345          $mform->addElement('date_time_selector', 'enrolenddate', get_string('enrolenddate', 'enrol_fee'), $options);
 346          $mform->setDefault('enrolenddate', 0);
 347          $mform->addHelpButton('enrolenddate', 'enrolenddate', 'enrol_fee');
 348  
 349          if (enrol_accessing_via_instance($instance)) {
 350              $warningtext = get_string('instanceeditselfwarningtext', 'core_enrol');
 351              $mform->addElement('static', 'selfwarn', get_string('instanceeditselfwarning', 'core_enrol'), $warningtext);
 352          }
 353      }
 354  
 355      /**
 356       * Perform custom validation of the data used to edit the instance.
 357       *
 358       * @param array $data array of ("fieldname"=>value) of submitted data
 359       * @param array $files array of uploaded files "element_name"=>tmp_file_path
 360       * @param object $instance The instance loaded from the DB
 361       * @param context $context The context of the instance we are editing
 362       * @return array of "element_name"=>"error_description" if there are errors,
 363       *         or an empty array if everything is OK.
 364       * @return void
 365       */
 366      public function edit_instance_validation($data, $files, $instance, $context) {
 367          $errors = array();
 368  
 369          if (!empty($data['enrolenddate']) and $data['enrolenddate'] < $data['enrolstartdate']) {
 370              $errors['enrolenddate'] = get_string('enrolenddaterror', 'enrol_fee');
 371          }
 372  
 373          $cost = str_replace(get_string('decsep', 'langconfig'), '.', $data['cost']);
 374          if (!is_numeric($cost)) {
 375              $errors['cost'] = get_string('costerror', 'enrol_fee');
 376          }
 377  
 378          $validstatus = array_keys($this->get_status_options());
 379          $validcurrency = array_keys($this->get_possible_currencies());
 380          $validroles = array_keys($this->get_roleid_options($instance, $context));
 381          $tovalidate = array(
 382              'name' => PARAM_TEXT,
 383              'status' => $validstatus,
 384              'currency' => $validcurrency,
 385              'roleid' => $validroles,
 386              'enrolperiod' => PARAM_INT,
 387              'enrolstartdate' => PARAM_INT,
 388              'enrolenddate' => PARAM_INT
 389          );
 390  
 391          $typeerrors = $this->validate_param_types($data, $tovalidate);
 392          $errors = array_merge($errors, $typeerrors);
 393  
 394          if ($data['status'] == ENROL_INSTANCE_ENABLED &&
 395                  (!$data['customint1']
 396                      || !array_key_exists($data['customint1'], \core_payment\helper::get_payment_accounts_menu($context)))) {
 397              $errors['status'] = 'Enrolments can not be enabled without specifying the payment account';
 398          }
 399  
 400          return $errors;
 401      }
 402  
 403      /**
 404       * Execute synchronisation.
 405       * @param progress_trace $trace
 406       * @return int exit code, 0 means ok
 407       */
 408      public function sync(progress_trace $trace) {
 409          $this->process_expirations($trace);
 410          return 0;
 411      }
 412  
 413      /**
 414       * Is it possible to delete enrol instance via standard UI?
 415       *
 416       * @param stdClass $instance
 417       * @return bool
 418       */
 419      public function can_delete_instance($instance) {
 420          $context = context_course::instance($instance->courseid);
 421          return has_capability('enrol/fee:config', $context);
 422      }
 423  
 424      /**
 425       * Is it possible to hide/show enrol instance via standard UI?
 426       *
 427       * @param stdClass $instance
 428       * @return bool
 429       */
 430      public function can_hide_show_instance($instance) {
 431          $context = context_course::instance($instance->courseid);
 432          return has_capability('enrol/fee:config', $context);
 433      }
 434  }