Search moodle.org's
Developer Documentation


/enrol/ -> locallib.php (source)
   1  <?php
   2  // This file is part of Moodle - http://moodle.org/
   3  //
   4  // Moodle is free software: you can redistribute it and/or modify
   5  // it under the terms of the GNU General Public License as published by
   6  // the Free Software Foundation, either version 3 of the License, or
   7  // (at your option) any later version.
   8  //
   9  // Moodle is distributed in the hope that it will be useful,
  10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12  // GNU General Public License for more details.
  13  //
  14  // You should have received a copy of the GNU General Public License
  15  // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
  16  
  17  /**
  18   * This file contains the course_enrolment_manager class which is used to interface
  19   * with the functions that exist in enrollib.php in relation to a single course.
  20   *
  21   * @package    core_enrol
  22   * @copyright  2010 Sam Hemelryk
  23   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  24   */
  25  
  26  defined('MOODLE_INTERNAL') || die();
  27  
  28  /**
  29   * This class provides a targeted tied together means of interfacing the enrolment
  30   * tasks together with a course.
  31   *
  32   * It is provided as a convenience more than anything else.
  33   *
  34   * @copyright 2010 Sam Hemelryk
  35   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  36   */
  37  class course_enrolment_manager {
  38  
  39      /**
  40       * The course context
  41       * @var stdClass
  42       */
  43      protected $context;
  44      /**
  45       * The course we are managing enrolments for
  46       * @var stdClass
  47       */
  48      protected $course = null;
  49      /**
  50       * Limits the focus of the manager to one enrolment plugin instance
  51       * @var string
  52       */
  53      protected $instancefilter = null;
  54      /**
  55       * Limits the focus of the manager to users with specified role
  56       * @var int
  57       */
  58      protected $rolefilter = 0;
  59      /**
  60       * Limits the focus of the manager to users who match search string
  61       * @var string
  62       */
  63      protected $searchfilter = '';
  64      /**
  65       * Limits the focus of the manager to users in specified group
  66       * @var int
  67       */
  68      protected $groupfilter = 0;
  69      /**
  70       * Limits the focus of the manager to users who match status active/inactive
  71       * @var int
  72       */
  73      protected $statusfilter = -1;
  74  
  75      /**
  76       * The total number of users enrolled in the course
  77       * Populated by course_enrolment_manager::get_total_users
  78       * @var int
  79       */
  80      protected $totalusers = null;
  81      /**
  82       * An array of users currently enrolled in the course
  83       * Populated by course_enrolment_manager::get_users
  84       * @var array
  85       */
  86      protected $users = array();
  87  
  88      /**
  89       * An array of users who have roles within this course but who have not
  90       * been enrolled in the course
  91       * @var array
  92       */
  93      protected $otherusers = array();
  94  
  95      /**
  96       * The total number of users who hold a role within the course but who
  97       * arn't enrolled.
  98       * @var int
  99       */
 100      protected $totalotherusers = null;
 101  
 102      /**
 103       * The current moodle_page object
 104       * @var moodle_page
 105       */
 106      protected $moodlepage = null;
 107  
 108      /**#@+
 109       * These variables are used to cache the information this class uses
 110       * please never use these directly instead use their get_ counterparts.
 111       * @access private
 112       * @var array
 113       */
 114      private $_instancessql = null;
 115      private $_instances = null;
 116      private $_inames = null;
 117      private $_plugins = null;
 118      private $_allplugins = null;
 119      private $_roles = null;
 120      private $_assignableroles = null;
 121      private $_assignablerolesothers = null;
 122      private $_groups = null;
 123      /**#@-*/
 124  
 125      /**
 126       * Constructs the course enrolment manager
 127       *
 128       * @param moodle_page $moodlepage
 129       * @param stdClass $course
 130       * @param string $instancefilter
 131       * @param int $rolefilter If non-zero, filters to users with specified role
 132       * @param string $searchfilter If non-blank, filters to users with search text
 133       * @param int $groupfilter if non-zero, filter users with specified group
 134       * @param int $statusfilter if not -1, filter users with active/inactive enrollment.
 135       */
 136      public function __construct(moodle_page $moodlepage, $course, $instancefilter = null,
 137              $rolefilter = 0, $searchfilter = '', $groupfilter = 0, $statusfilter = -1) {
 138          $this->moodlepage = $moodlepage;
 139          $this->context = context_course::instance($course->id);
 140          $this->course = $course;
 141          $this->instancefilter = $instancefilter;
 142          $this->rolefilter = $rolefilter;
 143          $this->searchfilter = $searchfilter;
 144          $this->groupfilter = $groupfilter;
 145          $this->statusfilter = $statusfilter;
 146      }
 147  
 148      /**
 149       * Returns the current moodle page
 150       * @return moodle_page
 151       */
 152      public function get_moodlepage() {
 153          return $this->moodlepage;
 154      }
 155  
 156      /**
 157       * Returns the total number of enrolled users in the course.
 158       *
 159       * If a filter was specificed this will be the total number of users enrolled
 160       * in this course by means of that instance.
 161       *
 162       * @global moodle_database $DB
 163       * @return int
 164       */
 165      public function get_total_users() {
 166          global $DB;
 167          if ($this->totalusers === null) {
 168              list($instancessql, $params, $filter) = $this->get_instance_sql();
 169              list($filtersql, $moreparams) = $this->get_filter_sql();
 170              $params += $moreparams;
 171              $sqltotal = "SELECT COUNT(DISTINCT u.id)
 172                             FROM {user} u
 173                             JOIN {user_enrolments} ue ON (ue.userid = u.id  AND ue.enrolid $instancessql)
 174                             JOIN {enrol} e ON (e.id = ue.enrolid)
 175                        LEFT JOIN {groups_members} gm ON u.id = gm.userid
 176                            WHERE $filtersql";
 177              $this->totalusers = (int)$DB->count_records_sql($sqltotal, $params);
 178          }
 179          return $this->totalusers;
 180      }
 181  
 182      /**
 183       * Returns the total number of enrolled users in the course.
 184       *
 185       * If a filter was specificed this will be the total number of users enrolled
 186       * in this course by means of that instance.
 187       *
 188       * @global moodle_database $DB
 189       * @return int
 190       */
 191      public function get_total_other_users() {
 192          global $DB;
 193          if ($this->totalotherusers === null) {
 194              list($ctxcondition, $params) = $DB->get_in_or_equal($this->context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'ctx');
 195              $params['courseid'] = $this->course->id;
 196              $sql = "SELECT COUNT(DISTINCT u.id)
 197                        FROM {role_assignments} ra
 198                        JOIN {user} u ON u.id = ra.userid
 199                        JOIN {context} ctx ON ra.contextid = ctx.id
 200                   LEFT JOIN (
 201                             SELECT ue.id, ue.userid
 202                               FROM {user_enrolments} ue
 203                          LEFT JOIN {enrol} e ON e.id=ue.enrolid
 204                              WHERE e.courseid = :courseid
 205                           ) ue ON ue.userid=u.id
 206                       WHERE ctx.id $ctxcondition AND
 207                             ue.id IS NULL";
 208              $this->totalotherusers = (int)$DB->count_records_sql($sql, $params);
 209          }
 210          return $this->totalotherusers;
 211      }
 212  
 213      /**
 214       * Gets all of the users enrolled in this course.
 215       *
 216       * If a filter was specified this will be the users who were enrolled
 217       * in this course by means of that instance. If role or search filters were
 218       * specified then these will also be applied.
 219       *
 220       * @global moodle_database $DB
 221       * @param string $sort
 222       * @param string $direction ASC or DESC
 223       * @param int $page First page should be 0
 224       * @param int $perpage Defaults to 25
 225       * @return array
 226       */
 227      public function get_users($sort, $direction='ASC', $page=0, $perpage=25) {
 228          global $DB;
 229          if ($direction !== 'ASC') {
 230              $direction = 'DESC';
 231          }
 232          $key = md5("$sort-$direction-$page-$perpage");
 233          if (!array_key_exists($key, $this->users)) {
 234              list($instancessql, $params, $filter) = $this->get_instance_sql();
 235              list($filtersql, $moreparams) = $this->get_filter_sql();
 236              $params += $moreparams;
 237              $extrafields = get_extra_user_fields($this->get_context());
 238              $extrafields[] = 'lastaccess';
 239              $ufields = user_picture::fields('u', $extrafields);
 240              $sql = "SELECT DISTINCT $ufields, ul.timeaccess AS lastseen
 241                        FROM {user} u
 242                        JOIN {user_enrolments} ue ON (ue.userid = u.id  AND ue.enrolid $instancessql)
 243                        JOIN {enrol} e ON (e.id = ue.enrolid)
 244                   LEFT JOIN {user_lastaccess} ul ON (ul.courseid = e.courseid AND ul.userid = u.id)
 245                   LEFT JOIN {groups_members} gm ON u.id = gm.userid
 246                       WHERE $filtersql";
 247              if ($sort === 'firstname') {
 248                  $sql .= " ORDER BY u.firstname $direction, u.lastname $direction";
 249              } else if ($sort === 'lastname') {
 250                  $sql .= " ORDER BY u.lastname $direction, u.firstname $direction";
 251              } else if ($sort === 'email') {
 252                  $sql .= " ORDER BY u.email $direction, u.lastname $direction, u.firstname $direction";
 253              } else if ($sort === 'lastseen') {
 254                  $sql .= " ORDER BY ul.timeaccess $direction, u.lastname $direction, u.firstname $direction";
 255              }
 256              $this->users[$key] = $DB->get_records_sql($sql, $params, $page*$perpage, $perpage);
 257          }
 258          return $this->users[$key];
 259      }
 260  
 261      /**
 262       * Obtains WHERE clause to filter results by defined search and role filter
 263       * (instance filter is handled separately in JOIN clause, see
 264       * get_instance_sql).
 265       *
 266       * @return array Two-element array with SQL and params for WHERE clause
 267       */
 268      protected function get_filter_sql() {
 269          global $DB;
 270  
 271          // Search condition.
 272          $extrafields = get_extra_user_fields($this->get_context());
 273          list($sql, $params) = users_search_sql($this->searchfilter, 'u', true, $extrafields);
 274  
 275          // Role condition.
 276          if ($this->rolefilter) {
 277              // Get context SQL.
 278              $contextids = $this->context->get_parent_context_ids();
 279              $contextids[] = $this->context->id;
 280              list($contextsql, $contextparams) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED);
 281              $params += $contextparams;
 282  
 283              // Role check condition.
 284              $sql .= " AND (SELECT COUNT(1) FROM {role_assignments} ra WHERE ra.userid = u.id " .
 285                      "AND ra.roleid = :roleid AND ra.contextid $contextsql) > 0";
 286              $params['roleid'] = $this->rolefilter;
 287          }
 288  
 289          // Group condition.
 290          if ($this->groupfilter) {
 291              $sql .= " AND gm.groupid = :groupid";
 292              $params['groupid'] = $this->groupfilter;
 293          }
 294  
 295          // Status condition.
 296          if ($this->statusfilter === ENROL_USER_ACTIVE) {
 297              $sql .= " AND ue.status = :active AND e.status = :enabled AND ue.timestart < :now1
 298                      AND (ue.timeend = 0 OR ue.timeend > :now2)";
 299              $now = round(time(), -2); // rounding helps caching in DB
 300              $params += array('enabled' => ENROL_INSTANCE_ENABLED,
 301                               'active' => ENROL_USER_ACTIVE,
 302                               'now1' => $now,
 303                               'now2' => $now);
 304          } else if ($this->statusfilter === ENROL_USER_SUSPENDED) {
 305              $sql .= " AND (ue.status = :inactive OR e.status = :disabled OR ue.timestart > :now1
 306                      OR (ue.timeend <> 0 AND ue.timeend < :now2))";
 307              $now = round(time(), -2); // rounding helps caching in DB
 308              $params += array('disabled' => ENROL_INSTANCE_DISABLED,
 309                               'inactive' => ENROL_USER_SUSPENDED,
 310                               'now1' => $now,
 311                               'now2' => $now);
 312          }
 313  
 314          return array($sql, $params);
 315      }
 316  
 317      /**
 318       * Gets and array of other users.
 319       *
 320       * Other users are users who have been assigned roles or inherited roles
 321       * within this course but who have not been enrolled in the course
 322       *
 323       * @global moodle_database $DB
 324       * @param string $sort
 325       * @param string $direction
 326       * @param int $page
 327       * @param int $perpage
 328       * @return array
 329       */
 330      public function get_other_users($sort, $direction='ASC', $page=0, $perpage=25) {
 331          global $DB;
 332          if ($direction !== 'ASC') {
 333              $direction = 'DESC';
 334          }
 335          $key = md5("$sort-$direction-$page-$perpage");
 336          if (!array_key_exists($key, $this->otherusers)) {
 337              list($ctxcondition, $params) = $DB->get_in_or_equal($this->context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'ctx');
 338              $params['courseid'] = $this->course->id;
 339              $params['cid'] = $this->course->id;
 340              $sql = "SELECT ra.id as raid, ra.contextid, ra.component, ctx.contextlevel, ra.roleid, u.*, ue.lastseen
 341                      FROM {role_assignments} ra
 342                      JOIN {user} u ON u.id = ra.userid
 343                      JOIN {context} ctx ON ra.contextid = ctx.id
 344                 LEFT JOIN (
 345                         SELECT ue.id, ue.userid, ul.timeaccess AS lastseen
 346                           FROM {user_enrolments} ue
 347                      LEFT JOIN {enrol} e ON e.id=ue.enrolid
 348                      LEFT JOIN {user_lastaccess} ul ON (ul.courseid = e.courseid AND ul.userid = ue.userid)
 349                          WHERE e.courseid = :courseid
 350                         ) ue ON ue.userid=u.id
 351                     WHERE ctx.id $ctxcondition AND
 352                           ue.id IS NULL
 353                  ORDER BY u.$sort $direction, ctx.depth DESC";
 354              $this->otherusers[$key] = $DB->get_records_sql($sql, $params, $page*$perpage, $perpage);
 355          }
 356          return $this->otherusers[$key];
 357      }
 358  
 359      /**
 360       * Helper method used by {@link get_potential_users()} and {@link search_other_users()}.
 361       *
 362       * @param string $search the search term, if any.
 363       * @param bool $searchanywhere Can the search term be anywhere, or must it be at the start.
 364       * @return array with three elements:
 365       *     string list of fields to SELECT,
 366       *     string contents of SQL WHERE clause,
 367       *     array query params. Note that the SQL snippets use named parameters.
 368       */
 369      protected function get_basic_search_conditions($search, $searchanywhere) {
 370          global $DB, $CFG;
 371  
 372          // Add some additional sensible conditions
 373          $tests = array("u.id <> :guestid", 'u.deleted = 0', 'u.confirmed = 1');
 374          $params = array('guestid' => $CFG->siteguest);
 375          if (!empty($search)) {
 376              $conditions = get_extra_user_fields($this->get_context());
 377              $conditions[] = 'u.firstname';
 378              $conditions[] = 'u.lastname';
 379              $conditions[] = $DB->sql_fullname('u.firstname', 'u.lastname');
 380              if ($searchanywhere) {
 381                  $searchparam = '%' . $search . '%';
 382              } else {
 383                  $searchparam = $search . '%';
 384              }
 385              $i = 0;
 386              foreach ($conditions as $key => $condition) {
 387                  $conditions[$key] = $DB->sql_like($condition, ":con{$i}00", false);
 388                  $params["con{$i}00"] = $searchparam;
 389                  $i++;
 390              }
 391              $tests[] = '(' . implode(' OR ', $conditions) . ')';
 392          }
 393          $wherecondition = implode(' AND ', $tests);
 394  
 395          $extrafields = get_extra_user_fields($this->get_context(), array('username', 'lastaccess'));
 396          $extrafields[] = 'username';
 397          $extrafields[] = 'lastaccess';
 398          $ufields = user_picture::fields('u', $extrafields);
 399  
 400          return array($ufields, $params, $wherecondition);
 401      }
 402  
 403      /**
 404       * Helper method used by {@link get_potential_users()} and {@link search_other_users()}.
 405       *
 406       * @param string $search the search string, if any.
 407       * @param string $fields the first bit of the SQL when returning some users.
 408       * @param string $countfields fhe first bit of the SQL when counting the users.
 409       * @param string $sql the bulk of the SQL statement.
 410       * @param array $params query parameters.
 411       * @param int $page which page number of the results to show.
 412       * @param int $perpage number of users per page.
 413       * @param int $addedenrollment number of users added to enrollment.
 414       * @return array with two elememts:
 415       *      int total number of users matching the search.
 416       *      array of user objects returned by the query.
 417       */
 418      protected function execute_search_queries($search, $fields, $countfields, $sql, array $params, $page, $perpage, $addedenrollment=0) {
 419          global $DB, $CFG;
 420  
 421          list($sort, $sortparams) = users_order_by_sql('u', $search, $this->get_context());
 422          $order = ' ORDER BY ' . $sort;
 423  
 424          $totalusers = $DB->count_records_sql($countfields . $sql, $params);
 425          $availableusers = $DB->get_records_sql($fields . $sql . $order,
 426                  array_merge($params, $sortparams), ($page*$perpage) - $addedenrollment, $perpage);
 427  
 428          return array('totalusers' => $totalusers, 'users' => $availableusers);
 429      }
 430  
 431      /**
 432       * Gets an array of the users that can be enrolled in this course.
 433       *
 434       * @global moodle_database $DB
 435       * @param int $enrolid
 436       * @param string $search
 437       * @param bool $searchanywhere
 438       * @param int $page Defaults to 0
 439       * @param int $perpage Defaults to 25
 440       * @param int $addedenrollment Defaults to 0
 441       * @return array Array(totalusers => int, users => array)
 442       */
 443      public function get_potential_users($enrolid, $search='', $searchanywhere=false, $page=0, $perpage=25, $addedenrollment=0) {
 444          global $DB;
 445  
 446          list($ufields, $params, $wherecondition) = $this->get_basic_search_conditions($search, $searchanywhere);
 447  
 448          $fields      = 'SELECT '.$ufields;
 449          $countfields = 'SELECT COUNT(1)';
 450          $sql = " FROM {user} u
 451              LEFT JOIN {user_enrolments} ue ON (ue.userid = u.id AND ue.enrolid = :enrolid)
 452                  WHERE $wherecondition
 453                        AND ue.id IS NULL";
 454          $params['enrolid'] = $enrolid;
 455  
 456          return $this->execute_search_queries($search, $fields, $countfields, $sql, $params, $page, $perpage, $addedenrollment);
 457      }
 458  
 459      /**
 460       * Searches other users and returns paginated results
 461       *
 462       * @global moodle_database $DB
 463       * @param string $search
 464       * @param bool $searchanywhere
 465       * @param int $page Starting at 0
 466       * @param int $perpage
 467       * @return array
 468       */
 469      public function search_other_users($search='', $searchanywhere=false, $page=0, $perpage=25) {
 470          global $DB, $CFG;
 471  
 472          list($ufields, $params, $wherecondition) = $this->get_basic_search_conditions($search, $searchanywhere);
 473  
 474          $fields      = 'SELECT ' . $ufields;
 475          $countfields = 'SELECT COUNT(u.id)';
 476          $sql   = " FROM {user} u
 477                LEFT JOIN {role_assignments} ra ON (ra.userid = u.id AND ra.contextid = :contextid)
 478                    WHERE $wherecondition
 479                      AND ra.id IS NULL";
 480          $params['contextid'] = $this->context->id;
 481  
 482          return $this->execute_search_queries($search, $fields, $countfields, $sql, $params, $page, $perpage);
 483      }
 484  
 485      /**
 486       * Gets an array containing some SQL to user for when selecting, params for
 487       * that SQL, and the filter that was used in constructing the sql.
 488       *
 489       * @global moodle_database $DB
 490       * @return string
 491       */
 492      protected function get_instance_sql() {
 493          global $DB;
 494          if ($this->_instancessql === null) {
 495              $instances = $this->get_enrolment_instances();
 496              $filter = $this->get_enrolment_filter();
 497              if ($filter && array_key_exists($filter, $instances)) {
 498                  $sql = " = :ifilter";
 499                  $params = array('ifilter'=>$filter);
 500              } else {
 501                  $filter = 0;
 502                  if ($instances) {
 503                      list($sql, $params) = $DB->get_in_or_equal(array_keys($this->get_enrolment_instances()), SQL_PARAMS_NAMED);
 504                  } else {
 505                      // no enabled instances, oops, we should probably say something
 506                      $sql = "= :never";
 507                      $params = array('never'=>-1);
 508                  }
 509              }
 510              $this->instancefilter = $filter;
 511              $this->_instancessql = array($sql, $params, $filter);
 512          }
 513          return $this->_instancessql;
 514      }
 515  
 516      /**
 517       * Returns all of the enrolment instances for this course.
 518       *
 519       * NOTE: since 2.4 it includes instances of disabled plugins too.
 520       *
 521       * @return array
 522       */
 523      public function get_enrolment_instances() {
 524          if ($this->_instances === null) {
 525              $this->_instances = enrol_get_instances($this->course->id, false);
 526          }
 527          return $this->_instances;
 528      }
 529  
 530      /**
 531       * Returns the names for all of the enrolment instances for this course.
 532       *
 533       * NOTE: since 2.4 it includes instances of disabled plugins too.
 534       *
 535       * @return array
 536       */
 537      public function get_enrolment_instance_names() {
 538          if ($this->_inames === null) {
 539              $instances = $this->get_enrolment_instances();
 540              $plugins = $this->get_enrolment_plugins(false);
 541              foreach ($instances as $key=>$instance) {
 542                  if (!isset($plugins[$instance->enrol])) {
 543                      // weird, some broken stuff in plugin
 544                      unset($instances[$key]);
 545                      continue;
 546                  }
 547                  $this->_inames[$key] = $plugins[$instance->enrol]->get_instance_name($instance);
 548              }
 549          }
 550          return $this->_inames;
 551      }
 552  
 553      /**
 554       * Gets all of the enrolment plugins that are active for this course.
 555       *
 556       * @param bool $onlyenabled return only enabled enrol plugins
 557       * @return array
 558       */
 559      public function get_enrolment_plugins($onlyenabled = true) {
 560          if ($this->_plugins === null) {
 561              $this->_plugins = enrol_get_plugins(true);
 562          }
 563  
 564          if ($onlyenabled) {
 565              return $this->_plugins;
 566          }
 567  
 568          if ($this->_allplugins === null) {
 569              // Make sure we have the same objects in _allplugins and _plugins.
 570              $this->_allplugins = $this->_plugins;
 571              foreach (enrol_get_plugins(false) as $name=>$plugin) {
 572                  if (!isset($this->_allplugins[$name])) {
 573                      $this->_allplugins[$name] = $plugin;
 574                  }
 575              }
 576          }
 577  
 578          return $this->_allplugins;
 579      }
 580  
 581      /**
 582       * Gets all of the roles this course can contain.
 583       *
 584       * @return array
 585       */
 586      public function get_all_roles() {
 587          if ($this->_roles === null) {
 588              $this->_roles = role_fix_names(get_all_roles($this->context), $this->context);
 589          }
 590          return $this->_roles;
 591      }
 592  
 593      /**
 594       * Gets all of the assignable roles for this course.
 595       *
 596       * @return array
 597       */
 598      public function get_assignable_roles($otherusers = false) {
 599          if ($this->_assignableroles === null) {
 600              $this->_assignableroles = get_assignable_roles($this->context, ROLENAME_ALIAS, false); // verifies unassign access control too
 601          }
 602  
 603          if ($otherusers) {
 604              if (!is_array($this->_assignablerolesothers)) {
 605                  $this->_assignablerolesothers = array();
 606                  list($courseviewroles, $ignored) = get_roles_with_cap_in_context($this->context, 'moodle/course:view');
 607                  foreach ($this->_assignableroles as $roleid=>$role) {
 608                      if (isset($courseviewroles[$roleid])) {
 609                          $this->_assignablerolesothers[$roleid] = $role;
 610                      }
 611                  }
 612              }
 613              return $this->_assignablerolesothers;
 614          } else {
 615              return $this->_assignableroles;
 616          }
 617      }
 618  
 619      /**
 620       * Gets all of the groups for this course.
 621       *
 622       * @return array
 623       */
 624      public function get_all_groups() {
 625          if ($this->_groups === null) {
 626              $this->_groups = groups_get_all_groups($this->course->id);
 627              foreach ($this->_groups as $gid=>$group) {
 628                  $this->_groups[$gid]->name = format_string($group->name);
 629              }
 630          }
 631          return $this->_groups;
 632      }
 633  
 634      /**
 635       * Unenrols a user from the course given the users ue entry
 636       *
 637       * @global moodle_database $DB
 638       * @param stdClass $ue
 639       * @return bool
 640       */
 641      public function unenrol_user($ue) {
 642          global $DB;
 643          list ($instance, $plugin) = $this->get_user_enrolment_components($ue);
 644          if ($instance && $plugin && $plugin->allow_unenrol_user($instance, $ue) && has_capability("enrol/$instance->enrol:unenrol", $this->context)) {
 645              $plugin->unenrol_user($instance, $ue->userid);
 646              return true;
 647          }
 648          return false;
 649      }
 650  
 651      /**
 652       * Given a user enrolment record this method returns the plugin and enrolment
 653       * instance that relate to it.
 654       *
 655       * @param stdClass|int $userenrolment
 656       * @return array array($instance, $plugin)
 657       */
 658      public function get_user_enrolment_components($userenrolment) {
 659          global $DB;
 660          if (is_numeric($userenrolment)) {
 661              $userenrolment = $DB->get_record('user_enrolments', array('id'=>(int)$userenrolment));
 662          }
 663          $instances = $this->get_enrolment_instances();
 664          $plugins = $this->get_enrolment_plugins(false);
 665          if (!$userenrolment || !isset($instances[$userenrolment->enrolid])) {
 666              return array(false, false);
 667          }
 668          $instance = $instances[$userenrolment->enrolid];
 669          $plugin = $plugins[$instance->enrol];
 670          return array($instance, $plugin);
 671      }
 672  
 673      /**
 674       * Removes an assigned role from a user.
 675       *
 676       * @global moodle_database $DB
 677       * @param int $userid
 678       * @param int $roleid
 679       * @return bool
 680       */
 681      public function unassign_role_from_user($userid, $roleid) {
 682          global $DB;
 683          // Admins may unassign any role, others only those they could assign.
 684          if (!is_siteadmin() and !array_key_exists($roleid, $this->get_assignable_roles())) {
 685              if (defined('AJAX_SCRIPT')) {
 686                  throw new moodle_exception('invalidrole');
 687              }
 688              return false;
 689          }
 690          $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
 691          $ras = $DB->get_records('role_assignments', array('contextid'=>$this->context->id, 'userid'=>$user->id, 'roleid'=>$roleid));
 692          foreach ($ras as $ra) {
 693              if ($ra->component) {
 694                  if (strpos($ra->component, 'enrol_') !== 0) {
 695                      continue;
 696                  }
 697                  if (!$plugin = enrol_get_plugin(substr($ra->component, 6))) {
 698                      continue;
 699                  }
 700                  if ($plugin->roles_protected()) {
 701                      continue;
 702                  }
 703              }
 704              role_unassign($ra->roleid, $ra->userid, $ra->contextid, $ra->component, $ra->itemid);
 705          }
 706          return true;
 707      }
 708  
 709      /**
 710       * Assigns a role to a user.
 711       *
 712       * @param int $roleid
 713       * @param int $userid
 714       * @return int|false
 715       */
 716      public function assign_role_to_user($roleid, $userid) {
 717          require_capability('moodle/role:assign', $this->context);
 718          if (!array_key_exists($roleid, $this->get_assignable_roles())) {
 719              if (defined('AJAX_SCRIPT')) {
 720                  throw new moodle_exception('invalidrole');
 721              }
 722              return false;
 723          }
 724          return role_assign($roleid, $userid, $this->context->id, '', NULL);
 725      }
 726  
 727      /**
 728       * Adds a user to a group
 729       *
 730       * @param stdClass $user
 731       * @param int $groupid
 732       * @return bool
 733       */
 734      public function add_user_to_group($user, $groupid) {
 735          require_capability('moodle/course:managegroups', $this->context);
 736          $group = $this->get_group($groupid);
 737          if (!$group) {
 738              return false;
 739          }
 740          return groups_add_member($group->id, $user->id);
 741      }
 742  
 743      /**
 744       * Removes a user from a group
 745       *
 746       * @global moodle_database $DB
 747       * @param StdClass $user
 748       * @param int $groupid
 749       * @return bool
 750       */
 751      public function remove_user_from_group($user, $groupid) {
 752          global $DB;
 753          require_capability('moodle/course:managegroups', $this->context);
 754          $group = $this->get_group($groupid);
 755          if (!groups_remove_member_allowed($group, $user)) {
 756              return false;
 757          }
 758          if (!$group) {
 759              return false;
 760          }
 761          return groups_remove_member($group, $user);
 762      }
 763  
 764      /**
 765       * Gets the requested group
 766       *
 767       * @param int $groupid
 768       * @return stdClass|int
 769       */
 770      public function get_group($groupid) {
 771          $groups = $this->get_all_groups();
 772          if (!array_key_exists($groupid, $groups)) {
 773              return false;
 774          }
 775          return $groups[$groupid];
 776      }
 777  
 778      /**
 779       * Edits an enrolment
 780       *
 781       * @param stdClass $userenrolment
 782       * @param stdClass $data
 783       * @return bool
 784       */
 785      public function edit_enrolment($userenrolment, $data) {
 786          //Only allow editing if the user has the appropriate capability
 787          //Already checked in /enrol/users.php but checking again in case this function is called from elsewhere
 788          list($instance, $plugin) = $this->get_user_enrolment_components($userenrolment);
 789          if ($instance && $plugin && $plugin->allow_manage($instance) && has_capability("enrol/$instance->enrol:manage", $this->context)) {
 790              if (!isset($data->status)) {
 791                  $data->status = $userenrolment->status;
 792              }
 793              $plugin->update_user_enrol($instance, $userenrolment->userid, $data->status, $data->timestart, $data->timeend);
 794              return true;
 795          }
 796          return false;
 797      }
 798  
 799      /**
 800       * Returns the current enrolment filter that is being applied by this class
 801       * @return string
 802       */
 803      public function get_enrolment_filter() {
 804          return $this->instancefilter;
 805      }
 806  
 807      /**
 808       * Gets the roles assigned to this user that are applicable for this course.
 809       *
 810       * @param int $userid
 811       * @return array
 812       */
 813      public function get_user_roles($userid) {
 814          $roles = array();
 815          $ras = get_user_roles($this->context, $userid, true, 'c.contextlevel DESC, r.sortorder ASC');
 816          $plugins = $this->get_enrolment_plugins(false);
 817          foreach ($ras as $ra) {
 818              if ($ra->contextid != $this->context->id) {
 819                  if (!array_key_exists($ra->roleid, $roles)) {
 820                      $roles[$ra->roleid] = null;
 821                  }
 822                  // higher ras, course always takes precedence
 823                  continue;
 824              }
 825              if (array_key_exists($ra->roleid, $roles) && $roles[$ra->roleid] === false) {
 826                  continue;
 827              }
 828              $changeable = true;
 829              if ($ra->component) {
 830                  $changeable = false;
 831                  if (strpos($ra->component, 'enrol_') === 0) {
 832                      $plugin = substr($ra->component, 6);
 833                      if (isset($plugins[$plugin])) {
 834                          $changeable = !$plugins[$plugin]->roles_protected();
 835                      }
 836                  }
 837              }
 838  
 839              $roles[$ra->roleid] = $changeable;
 840          }
 841          return $roles;
 842      }
 843  
 844      /**
 845       * Gets the enrolments this user has in the course - including all suspended plugins and instances.
 846       *
 847       * @global moodle_database $DB
 848       * @param int $userid
 849       * @return array
 850       */
 851      public function get_user_enrolments($userid) {
 852          global $DB;
 853          list($instancessql, $params, $filter) = $this->get_instance_sql();
 854          $params['userid'] = $userid;
 855          $userenrolments = $DB->get_records_select('user_enrolments', "enrolid $instancessql AND userid = :userid", $params);
 856          $instances = $this->get_enrolment_instances();
 857          $plugins = $this->get_enrolment_plugins(false);
 858          $inames = $this->get_enrolment_instance_names();
 859          foreach ($userenrolments as &$ue) {
 860              $ue->enrolmentinstance     = $instances[$ue->enrolid];
 861              $ue->enrolmentplugin       = $plugins[$ue->enrolmentinstance->enrol];
 862              $ue->enrolmentinstancename = $inames[$ue->enrolmentinstance->id];
 863          }
 864          return $userenrolments;
 865      }
 866  
 867      /**
 868       * Gets the groups this user belongs to
 869       *
 870       * @param int $userid
 871       * @return array
 872       */
 873      public function get_user_groups($userid) {
 874          return groups_get_all_groups($this->course->id, $userid, 0, 'g.id');
 875      }
 876  
 877      /**
 878       * Retursn an array of params that would go into the URL to return to this
 879       * exact page.
 880       *
 881       * @return array
 882       */
 883      public function get_url_params() {
 884          $args = array(
 885              'id' => $this->course->id
 886          );
 887          if (!empty($this->instancefilter)) {
 888              $args['ifilter'] = $this->instancefilter;
 889          }
 890          if (!empty($this->rolefilter)) {
 891              $args['role'] = $this->rolefilter;
 892          }
 893          if ($this->searchfilter !== '') {
 894              $args['search'] = $this->searchfilter;
 895          }
 896          if (!empty($this->groupfilter)) {
 897              $args['filtergroup'] = $this->groupfilter;
 898          }
 899          if ($this->statusfilter !== -1) {
 900              $args['status'] = $this->statusfilter;
 901          }
 902          return $args;
 903      }
 904  
 905      /**
 906       * Returns the course this object is managing enrolments for
 907       *
 908       * @return stdClass
 909       */
 910      public function get_course() {
 911          return $this->course;
 912      }
 913  
 914      /**
 915       * Returns the course context
 916       *
 917       * @return stdClass
 918       */
 919      public function get_context() {
 920          return $this->context;
 921      }
 922  
 923      /**
 924       * Gets an array of other users in this course ready for display.
 925       *
 926       * Other users are users who have been assigned or inherited roles within this
 927       * course but have not been enrolled.
 928       *
 929       * @param core_enrol_renderer $renderer
 930       * @param moodle_url $pageurl
 931       * @param string $sort
 932       * @param string $direction ASC | DESC
 933       * @param int $page Starting from 0
 934       * @param int $perpage
 935       * @return array
 936       */
 937      public function get_other_users_for_display(core_enrol_renderer $renderer, moodle_url $pageurl, $sort, $direction, $page, $perpage) {
 938  
 939          $userroles = $this->get_other_users($sort, $direction, $page, $perpage);
 940          $roles = $this->get_all_roles();
 941          $plugins = $this->get_enrolment_plugins(false);
 942  
 943          $context    = $this->get_context();
 944          $now = time();
 945          $extrafields = get_extra_user_fields($context);
 946  
 947          $users = array();
 948          foreach ($userroles as $userrole) {
 949              $contextid = $userrole->contextid;
 950              unset($userrole->contextid); // This would collide with user avatar.
 951              if (!array_key_exists($userrole->id, $users)) {
 952                  $users[$userrole->id] = $this->prepare_user_for_display($userrole, $extrafields, $now);
 953              }
 954              $a = new stdClass;
 955              $a->role = $roles[$userrole->roleid]->localname;
 956              if ($contextid == $this->context->id) {
 957                  $changeable = true;
 958                  if ($userrole->component) {
 959                      $changeable = false;
 960                      if (strpos($userrole->component, 'enrol_') === 0) {
 961                          $plugin = substr($userrole->component, 6);
 962                          if (isset($plugins[$plugin])) {
 963                              $changeable = !$plugins[$plugin]->roles_protected();
 964                          }
 965                      }
 966                  }
 967                  $roletext = get_string('rolefromthiscourse', 'enrol', $a);
 968              } else {
 969                  $changeable = false;
 970                  switch ($userrole->contextlevel) {
 971                      case CONTEXT_COURSE :
 972                          // Meta course
 973                          $roletext = get_string('rolefrommetacourse', 'enrol', $a);
 974                          break;
 975                      case CONTEXT_COURSECAT :
 976                          $roletext = get_string('rolefromcategory', 'enrol', $a);
 977                          break;
 978                      case CONTEXT_SYSTEM:
 979                      default:
 980                          $roletext = get_string('rolefromsystem', 'enrol', $a);
 981                          break;
 982                  }
 983              }
 984              if (!isset($users[$userrole->id]['roles'])) {
 985                  $users[$userrole->id]['roles'] = array();
 986              }
 987              $users[$userrole->id]['roles'][$userrole->roleid] = array(
 988                  'text' => $roletext,
 989                  'unchangeable' => !$changeable
 990              );
 991          }
 992          return $users;
 993      }
 994  
 995      /**
 996       * Gets an array of users for display, this includes minimal user information
 997       * as well as minimal information on the users roles, groups, and enrolments.
 998       *
 999       * @param core_enrol_renderer $renderer
1000       * @param moodle_url $pageurl
1001       * @param int $sort
1002       * @param string $direction ASC or DESC
1003       * @param int $page
1004       * @param int $perpage
1005       * @return array
1006       */
1007      public function get_users_for_display(course_enrolment_manager $manager, $sort, $direction, $page, $perpage) {
1008          $pageurl = $manager->get_moodlepage()->url;
1009          $users = $this->get_users($sort, $direction, $page, $perpage);
1010  
1011          $now = time();
1012          $straddgroup = get_string('addgroup', 'group');
1013          $strunenrol = get_string('unenrol', 'enrol');
1014          $stredit = get_string('edit');
1015  
1016          $allroles   = $this->get_all_roles();
1017          $assignable = $this->get_assignable_roles();
1018          $allgroups  = $this->get_all_groups();
1019          $context    = $this->get_context();
1020          $canmanagegroups = has_capability('moodle/course:managegroups', $context);
1021  
1022          $url = new moodle_url($pageurl, $this->get_url_params());
1023          $extrafields = get_extra_user_fields($context);
1024  
1025          $enabledplugins = $this->get_enrolment_plugins(true);
1026  
1027          $userdetails = array();
1028          foreach ($users as $user) {
1029              $details = $this->prepare_user_for_display($user, $extrafields, $now);
1030  
1031              // Roles
1032              $details['roles'] = array();
1033              foreach ($this->get_user_roles($user->id) as $rid=>$rassignable) {
1034                  $unchangeable = !$rassignable;
1035                  if (!is_siteadmin() and !isset($assignable[$rid])) {
1036                      $unchangeable = true;
1037                  }
1038                  $details['roles'][$rid] = array('text'=>$allroles[$rid]->localname, 'unchangeable'=>$unchangeable);
1039              }
1040  
1041              // Users
1042              $usergroups = $this->get_user_groups($user->id);
1043              $details['groups'] = array();
1044              foreach($usergroups as $gid=>$unused) {
1045                  $details['groups'][$gid] = $allgroups[$gid]->name;
1046              }
1047  
1048              // Enrolments
1049              $details['enrolments'] = array();
1050              foreach ($this->get_user_enrolments($user->id) as $ue) {
1051                  if (!isset($enabledplugins[$ue->enrolmentinstance->enrol])) {
1052                      $details['enrolments'][$ue->id] = array(
1053                          'text' => $ue->enrolmentinstancename,
1054                          'period' => null,
1055                          'dimmed' =>  true,
1056                          'actions' => array()
1057                      );
1058                      continue;
1059                  } else if ($ue->timestart and $ue->timeend) {
1060                      $period = get_string('periodstartend', 'enrol', array('start'=>userdate($ue->timestart), 'end'=>userdate($ue->timeend)));
1061                      $periodoutside = ($ue->timestart && $ue->timeend && ($now < $ue->timestart || $now > $ue->timeend));
1062                  } else if ($ue->timestart) {
1063                      $period = get_string('periodstart', 'enrol', userdate($ue->timestart));
1064                      $periodoutside = ($ue->timestart && $now < $ue->timestart);
1065                  } else if ($ue->timeend) {
1066                      $period = get_string('periodend', 'enrol', userdate($ue->timeend));
1067                      $periodoutside = ($ue->timeend && $now > $ue->timeend);
1068                  } else {
1069                      // If there is no start or end show when user was enrolled.
1070                      $period = get_string('periodnone', 'enrol', userdate($ue->timecreated));
1071                      $periodoutside = false;
1072                  }
1073                  $details['enrolments'][$ue->id] = array(
1074                      'text' => $ue->enrolmentinstancename,
1075                      'period' => $period,
1076                      'dimmed' =>  ($periodoutside or $ue->status != ENROL_USER_ACTIVE or $ue->enrolmentinstance->status != ENROL_INSTANCE_ENABLED),
1077                      'actions' => $ue->enrolmentplugin->get_user_enrolment_actions($manager, $ue)
1078                  );
1079              }
1080              $userdetails[$user->id] = $details;
1081          }
1082          return $userdetails;
1083      }
1084  
1085      /**
1086       * Prepare a user record for display
1087       *
1088       * This function is called by both {@link get_users_for_display} and {@link get_other_users_for_display} to correctly
1089       * prepare user fields for display
1090       *
1091       * Please note that this function does not check capability for moodle/coures:viewhiddenuserfields
1092       *
1093       * @param object $user The user record
1094       * @param array $extrafields The list of fields as returned from get_extra_user_fields used to determine which
1095       * additional fields may be displayed
1096       * @param int $now The time used for lastaccess calculation
1097       * @return array The fields to be displayed including userid, courseid, picture, firstname, lastseen and any
1098       * additional fields from $extrafields
1099       */
1100      private function prepare_user_for_display($user, $extrafields, $now) {
1101          $details = array(
1102              'userid'           => $user->id,
1103              'courseid'         => $this->get_course()->id,
1104              'picture'          => new user_picture($user),
1105              'firstname'        => fullname($user, has_capability('moodle/site:viewfullnames', $this->get_context())),
1106              'lastseen'         => get_string('never'),
1107              'lastcourseaccess' => get_string('never'),
1108          );
1109          foreach ($extrafields as $field) {
1110              $details[$field] = $user->{$field};
1111          }
1112  
1113          // Last time user has accessed the site.
1114          if ($user->lastaccess) {
1115              $details['lastseen'] = format_time($now - $user->lastaccess);
1116          }
1117  
1118          // Last time user has accessed the course.
1119          if ($user->lastseen) {
1120              $details['lastcourseaccess'] = format_time($now - $user->lastseen);
1121          }
1122          return $details;
1123      }
1124  
1125      public function get_manual_enrol_buttons() {
1126          $plugins = $this->get_enrolment_plugins(true); // Skip disabled plugins.
1127          $buttons = array();
1128          foreach ($plugins as $plugin) {
1129              $newbutton = $plugin->get_manual_enrol_button($this);
1130              if (is_array($newbutton)) {
1131                  $buttons += $newbutton;
1132              } else if ($newbutton instanceof enrol_user_button) {
1133                  $buttons[] = $newbutton;
1134              }
1135          }
1136          return $buttons;
1137      }
1138  
1139      public function has_instance($enrolpluginname) {
1140          // Make sure manual enrolments instance exists
1141          foreach ($this->get_enrolment_instances() as $instance) {
1142              if ($instance->enrol == $enrolpluginname) {
1143                  return true;
1144              }
1145          }
1146          return false;
1147      }
1148  
1149      /**
1150       * Returns the enrolment plugin that the course manager was being filtered to.
1151       *
1152       * If no filter was being applied then this function returns false.
1153       *
1154       * @return enrol_plugin
1155       */
1156      public function get_filtered_enrolment_plugin() {
1157          $instances = $this->get_enrolment_instances();
1158          $plugins = $this->get_enrolment_plugins(false);
1159  
1160          if (empty($this->instancefilter) || !array_key_exists($this->instancefilter, $instances)) {
1161              return false;
1162          }
1163  
1164          $instance = $instances[$this->instancefilter];
1165          return $plugins[$instance->enrol];
1166      }
1167  
1168      /**
1169       * Returns and array of users + enrolment details.
1170       *
1171       * Given an array of user id's this function returns and array of user enrolments for those users
1172       * as well as enough user information to display the users name and picture for each enrolment.
1173       *
1174       * @global moodle_database $DB
1175       * @param array $userids
1176       * @return array
1177       */
1178      public function get_users_enrolments(array $userids) {
1179          global $DB;
1180  
1181          $instances = $this->get_enrolment_instances();
1182          $plugins = $this->get_enrolment_plugins(false);
1183  
1184          if  (!empty($this->instancefilter)) {
1185              $instancesql = ' = :instanceid';
1186              $instanceparams = array('instanceid' => $this->instancefilter);
1187          } else {
1188              list($instancesql, $instanceparams) = $DB->get_in_or_equal(array_keys($instances), SQL_PARAMS_NAMED, 'instanceid0000');
1189          }
1190  
1191          $userfields = user_picture::fields('u');
1192          list($idsql, $idparams) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED, 'userid0000');
1193  
1194          list($sort, $sortparams) = users_order_by_sql('u');
1195  
1196          $sql = "SELECT ue.id AS ueid, ue.status, ue.enrolid, ue.userid, ue.timestart, ue.timeend, ue.modifierid, ue.timecreated, ue.timemodified, $userfields
1197                    FROM {user_enrolments} ue
1198               LEFT JOIN {user} u ON u.id = ue.userid
1199                   WHERE ue.enrolid $instancesql AND
1200                         u.id $idsql
1201                ORDER BY $sort";
1202  
1203          $rs = $DB->get_recordset_sql($sql, $idparams + $instanceparams + $sortparams);
1204          $users = array();
1205          foreach ($rs as $ue) {
1206              $user = user_picture::unalias($ue);
1207              $ue->id = $ue->ueid;
1208              unset($ue->ueid);
1209              if (!array_key_exists($user->id, $users)) {
1210                  $user->enrolments = array();
1211                  $users[$user->id] = $user;
1212              }
1213              $ue->enrolmentinstance = $instances[$ue->enrolid];
1214              $ue->enrolmentplugin = $plugins[$ue->enrolmentinstance->enrol];
1215              $users[$user->id]->enrolments[$ue->id] = $ue;
1216          }
1217          $rs->close();
1218          return $users;
1219      }
1220  }
1221  
1222  /**
1223   * A button that is used to enrol users in a course
1224   *
1225   * @copyright 2010 Sam Hemelryk
1226   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1227   */
1228  class enrol_user_button extends single_button {
1229  
1230      /**
1231       * An array containing JS YUI modules required by this button
1232       * @var array
1233       */
1234      protected $jsyuimodules = array();
1235  
1236      /**
1237       * An array containing JS initialisation calls required by this button
1238       * @var array
1239       */
1240      protected $jsinitcalls = array();
1241  
1242      /**
1243       * An array strings required by JS for this button
1244       * @var array
1245       */
1246      protected $jsstrings = array();
1247  
1248      /**
1249       * Initialises the new enrol_user_button
1250       *
1251       * @staticvar int $count The number of enrol user buttons already created
1252       * @param moodle_url $url
1253       * @param string $label The text to display in the button
1254       * @param string $method Either post or get
1255       */
1256      public function __construct(moodle_url $url, $label, $method = 'post') {
1257          static $count = 0;
1258          $count ++;
1259          parent::__construct($url, $label, $method);
1260          $this->class = 'singlebutton enrolusersbutton';
1261          $this->formid = 'enrolusersbutton-'.$count;
1262      }
1263  
1264      /**
1265       * Adds a YUI module call that will be added to the page when the button is used.
1266       *
1267       * @param string|array $modules One or more modules to require
1268       * @param string $function The JS function to call
1269       * @param array $arguments An array of arguments to pass to the function
1270       * @param string $galleryversion Deprecated: The gallery version to use
1271       * @param bool $ondomready If true the call is postponed until the DOM is finished loading
1272       */
1273      public function require_yui_module($modules, $function, array $arguments = null, $galleryversion = null, $ondomready = false) {
1274          if ($galleryversion != null) {
1275              debugging('The galleryversion parameter to yui_module has been deprecated since Moodle 2.3.', DEBUG_DEVELOPER);
1276          }
1277  
1278          $js = new stdClass;
1279          $js->modules = (array)$modules;
1280          $js->function = $function;
1281          $js->arguments = $arguments;
1282          $js->ondomready = $ondomready;
1283          $this->jsyuimodules[] = $js;
1284      }
1285  
1286      /**
1287       * Adds a JS initialisation call to the page when the button is used.
1288       *
1289       * @param string $function The function to call
1290       * @param array $extraarguments An array of arguments to pass to the function
1291       * @param bool $ondomready If true the call is postponed until the DOM is finished loading
1292       * @param array $module A module definition
1293       */
1294      public function require_js_init_call($function, array $extraarguments = null, $ondomready = false, array $module = null) {
1295          $js = new stdClass;
1296          $js->function = $function;
1297          $js->extraarguments = $extraarguments;
1298          $js->ondomready = $ondomready;
1299          $js->module = $module;
1300          $this->jsinitcalls[] = $js;
1301      }
1302  
1303      /**
1304       * Requires strings for JS that will be loaded when the button is used.
1305       *
1306       * @param type $identifiers
1307       * @param string $component
1308       * @param mixed $a
1309       */
1310      public function strings_for_js($identifiers, $component = 'moodle', $a = null) {
1311          $string = new stdClass;
1312          $string->identifiers = (array)$identifiers;
1313          $string->component = $component;
1314          $string->a = $a;
1315          $this->jsstrings[] = $string;
1316      }
1317  
1318      /**
1319       * Initialises the JS that is required by this button
1320       *
1321       * @param moodle_page $page
1322       */
1323      public function initialise_js(moodle_page $page) {
1324          foreach ($this->jsyuimodules as $js) {
1325              $page->requires->yui_module($js->modules, $js->function, $js->arguments, null, $js->ondomready);
1326          }
1327          foreach ($this->jsinitcalls as $js) {
1328              $page->requires->js_init_call($js->function, $js->extraarguments, $js->ondomready, $js->module);
1329          }
1330          foreach ($this->jsstrings as $string) {
1331              $page->requires->strings_for_js($string->identifiers, $string->component, $string->a);
1332          }
1333      }
1334  }
1335  
1336  /**
1337   * User enrolment action
1338   *
1339   * This class is used to manage a renderable ue action such as editing an user enrolment or deleting
1340   * a user enrolment.
1341   *
1342   * @copyright  2011 Sam Hemelryk
1343   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1344   */
1345  class user_enrolment_action implements renderable {
1346  
1347      /**
1348       * The icon to display for the action
1349       * @var pix_icon
1350       */
1351      protected $icon;
1352  
1353      /**
1354       * The title for the action
1355       * @var string
1356       */
1357      protected $title;
1358  
1359      /**
1360       * The URL to the action
1361       * @var moodle_url
1362       */
1363      protected $url;
1364  
1365      /**
1366       * An array of HTML attributes
1367       * @var array
1368       */
1369      protected $attributes = array();
1370  
1371      /**
1372       * Constructor
1373       * @param pix_icon $icon
1374       * @param string $title
1375       * @param moodle_url $url
1376       * @param array $attributes
1377       */
1378      public function __construct(pix_icon $icon, $title, $url, array $attributes = null) {
1379          $this->icon = $icon;
1380          $this->title = $title;
1381          $this->url = new moodle_url($url);
1382          if (!empty($attributes)) {
1383              $this->attributes = $attributes;
1384          }
1385          $this->attributes['title'] = $title;
1386      }
1387  
1388      /**
1389       * Returns the icon for this action
1390       * @return pix_icon
1391       */
1392      public function get_icon() {
1393          return $this->icon;
1394      }
1395  
1396      /**
1397       * Returns the title for this action
1398       * @return string
1399       */
1400      public function get_title() {
1401          return $this->title;
1402      }
1403  
1404      /**
1405       * Returns the URL for this action
1406       * @return moodle_url
1407       */
1408      public function get_url() {
1409          return $this->url;
1410      }
1411  
1412      /**
1413       * Returns the attributes to use for this action
1414       * @return array
1415       */
1416      public function get_attributes() {
1417          return $this->attributes;
1418      }
1419  }
1420  
1421  class enrol_ajax_exception extends moodle_exception {
1422      /**
1423       * Constructor
1424       * @param string $errorcode The name of the string from error.php to print
1425       * @param string $module name of module
1426       * @param string $link The url where the user will be prompted to continue. If no url is provided the user will be directed to the site index page.
1427       * @param object $a Extra words and phrases that might be required in the error string
1428       * @param string $debuginfo optional debugging information
1429       */
1430      public function __construct($errorcode, $link = '', $a = NULL, $debuginfo = null) {
1431          parent::__construct($errorcode, 'enrol', $link, $a, $debuginfo);
1432      }
1433  }
1434  
1435  /**
1436   * This class is used to manage a bulk operations for enrolment plugins.
1437   *
1438   * @copyright 2011 Sam Hemelryk
1439   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1440   */
1441  abstract class enrol_bulk_enrolment_operation {
1442  
1443      /**
1444       * The course enrolment manager
1445       * @var course_enrolment_manager
1446       */
1447      protected $manager;
1448  
1449      /**
1450       * The enrolment plugin to which this operation belongs
1451       * @var enrol_plugin
1452       */
1453      protected $plugin;
1454  
1455      /**
1456       * Contructor
1457       * @param course_enrolment_manager $manager
1458       * @param stdClass $plugin
1459       */
1460      public function __construct(course_enrolment_manager $manager, enrol_plugin $plugin = null) {
1461          $this->manager = $manager;
1462          $this->plugin = $plugin;
1463      }
1464  
1465      /**
1466       * Returns a moodleform used for this operation, or false if no form is required and the action
1467       * should be immediatly processed.
1468       *
1469       * @param moodle_url|string $defaultaction
1470       * @param mixed $defaultcustomdata
1471       * @return enrol_bulk_enrolment_change_form|moodleform|false
1472       */
1473      public function get_form($defaultaction = null, $defaultcustomdata = null) {
1474          return false;
1475      }
1476  
1477      /**
1478       * Returns the title to use for this bulk operation
1479       *
1480       * @return string
1481       */
1482      abstract public function get_title();
1483  
1484      /**
1485       * Returns the identifier for this bulk operation.
1486       * This should be the same identifier used by the plugins function when returning
1487       * all of its bulk operations.
1488       *
1489       * @return string
1490       */
1491      abstract public function get_identifier();
1492  
1493      /**
1494       * Processes the bulk operation on the given users
1495       *
1496       * @param course_enrolment_manager $manager
1497       * @param array $users
1498       * @param stdClass $properties
1499       */
1500      abstract public function process(course_enrolment_manager $manager, array $users, stdClass $properties);
1501  }

Search This Site: