[ Index ]

PHP Cross Reference of moodle-2.8

title

Body

[close]

/enrol/manual/ -> 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   * Auxiliary manual user enrolment lib, the main purpose is to lower memory requirements...
  19   *
  20   * @package    enrol_manual
  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  defined('MOODLE_INTERNAL') || die();
  26  
  27  require_once($CFG->dirroot . '/user/selector/lib.php');
  28  require_once($CFG->dirroot . '/enrol/locallib.php');
  29  
  30  
  31  /**
  32   * Enrol candidates.
  33   */
  34  class enrol_manual_potential_participant extends user_selector_base {
  35      protected $enrolid;
  36  
  37      public function __construct($name, $options) {
  38          $this->enrolid  = $options['enrolid'];
  39          parent::__construct($name, $options);
  40      }
  41  
  42      /**
  43       * Candidate users
  44       * @param string $search
  45       * @return array
  46       */
  47      public function find_users($search) {
  48          global $DB;
  49          // By default wherecondition retrieves all users except the deleted, not confirmed and guest.
  50          list($wherecondition, $params) = $this->search_sql($search, 'u');
  51          $params['enrolid'] = $this->enrolid;
  52  
  53          $fields      = 'SELECT ' . $this->required_fields_sql('u');
  54          $countfields = 'SELECT COUNT(1)';
  55  
  56          $sql = " FROM {user} u
  57              LEFT JOIN {user_enrolments} ue ON (ue.userid = u.id AND ue.enrolid = :enrolid)
  58                  WHERE $wherecondition
  59                        AND ue.id IS NULL";
  60  
  61          list($sort, $sortparams) = users_order_by_sql('u', $search, $this->accesscontext);
  62          $order = ' ORDER BY ' . $sort;
  63  
  64          if (!$this->is_validating()) {
  65              $potentialmemberscount = $DB->count_records_sql($countfields . $sql, $params);
  66              if ($potentialmemberscount > $this->maxusersperpage) {
  67                  return $this->too_many_results($search, $potentialmemberscount);
  68              }
  69          }
  70  
  71          $availableusers = $DB->get_records_sql($fields . $sql . $order, array_merge($params, $sortparams));
  72  
  73          if (empty($availableusers)) {
  74              return array();
  75          }
  76  
  77  
  78          if ($search) {
  79              $groupname = get_string('enrolcandidatesmatching', 'enrol', $search);
  80          } else {
  81              $groupname = get_string('enrolcandidates', 'enrol');
  82          }
  83  
  84          return array($groupname => $availableusers);
  85      }
  86  
  87      protected function get_options() {
  88          $options = parent::get_options();
  89          $options['enrolid'] = $this->enrolid;
  90          $options['file']    = 'enrol/manual/locallib.php';
  91          return $options;
  92      }
  93  }
  94  
  95  /**
  96   * Enrolled users.
  97   */
  98  class enrol_manual_current_participant extends user_selector_base {
  99      protected $courseid;
 100      protected $enrolid;
 101  
 102      public function __construct($name, $options) {
 103          $this->enrolid  = $options['enrolid'];
 104          parent::__construct($name, $options);
 105      }
 106  
 107      /**
 108       * Candidate users
 109       * @param string $search
 110       * @return array
 111       */
 112      public function find_users($search) {
 113          global $DB;
 114          // By default wherecondition retrieves all users except the deleted, not confirmed and guest.
 115          list($wherecondition, $params) = $this->search_sql($search, 'u');
 116          $params['enrolid'] = $this->enrolid;
 117  
 118          $fields      = 'SELECT ' . $this->required_fields_sql('u');
 119          $countfields = 'SELECT COUNT(1)';
 120  
 121          $sql = " FROM {user} u
 122                   JOIN {user_enrolments} ue ON (ue.userid = u.id AND ue.enrolid = :enrolid)
 123                  WHERE $wherecondition";
 124  
 125          list($sort, $sortparams) = users_order_by_sql('u', $search, $this->accesscontext);
 126          $order = ' ORDER BY ' . $sort;
 127  
 128          if (!$this->is_validating()) {
 129              $potentialmemberscount = $DB->count_records_sql($countfields . $sql, $params);
 130              if ($potentialmemberscount > $this->maxusersperpage) {
 131                  return $this->too_many_results($search, $potentialmemberscount);
 132              }
 133          }
 134  
 135          $availableusers = $DB->get_records_sql($fields . $sql . $order, array_merge($params, $sortparams));
 136  
 137          if (empty($availableusers)) {
 138              return array();
 139          }
 140  
 141  
 142          if ($search) {
 143              $groupname = get_string('enrolledusersmatching', 'enrol', $search);
 144          } else {
 145              $groupname = get_string('enrolledusers', 'enrol');
 146          }
 147  
 148          return array($groupname => $availableusers);
 149      }
 150  
 151      protected function get_options() {
 152          $options = parent::get_options();
 153          $options['enrolid'] = $this->enrolid;
 154          $options['file']    = 'enrol/manual/locallib.php';
 155          return $options;
 156      }
 157  }
 158  
 159  /**
 160   * A bulk operation for the manual enrolment plugin to edit selected users.
 161   *
 162   * @copyright 2011 Sam Hemelryk
 163   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 164   */
 165  class enrol_manual_editselectedusers_operation extends enrol_bulk_enrolment_operation {
 166  
 167      /**
 168       * Returns the title to display for this bulk operation.
 169       *
 170       * @return string
 171       */
 172      public function get_title() {
 173          return get_string('editselectedusers', 'enrol_manual');
 174      }
 175  
 176      /**
 177       * Returns the identifier for this bulk operation. This is the key used when the plugin
 178       * returns an array containing all of the bulk operations it supports.
 179       */
 180      public function get_identifier() {
 181          return 'editselectedusers';
 182      }
 183  
 184      /**
 185       * Processes the bulk operation request for the given userids with the provided properties.
 186       *
 187       * @param course_enrolment_manager $manager
 188       * @param array $userids
 189       * @param stdClass $properties The data returned by the form.
 190       */
 191      public function process(course_enrolment_manager $manager, array $users, stdClass $properties) {
 192          global $DB, $USER;
 193  
 194          if (!has_capability("enrol/manual:manage", $manager->get_context())) {
 195              return false;
 196          }
 197  
 198          // Get all of the user enrolment id's.
 199          $ueids = array();
 200          $instances = array();
 201          foreach ($users as $user) {
 202              foreach ($user->enrolments as $enrolment) {
 203                  $ueids[] = $enrolment->id;
 204                  if (!array_key_exists($enrolment->id, $instances)) {
 205                      $instances[$enrolment->id] = $enrolment;
 206                  }
 207              }
 208          }
 209  
 210          // Check that each instance is manageable by the current user.
 211          foreach ($instances as $instance) {
 212              if (!$this->plugin->allow_manage($instance)) {
 213                  return false;
 214              }
 215          }
 216  
 217          // Collect the known properties.
 218          $status = $properties->status;
 219          $timestart = $properties->timestart;
 220          $timeend = $properties->timeend;
 221  
 222          list($ueidsql, $params) = $DB->get_in_or_equal($ueids, SQL_PARAMS_NAMED);
 223  
 224          $updatesql = array();
 225          if ($status == ENROL_USER_ACTIVE || $status == ENROL_USER_SUSPENDED) {
 226              $updatesql[] = 'status = :status';
 227              $params['status'] = (int)$status;
 228          }
 229          if (!empty($timestart)) {
 230              $updatesql[] = 'timestart = :timestart';
 231              $params['timestart'] = (int)$timestart;
 232          }
 233          if (!empty($timeend)) {
 234              $updatesql[] = 'timeend = :timeend';
 235              $params['timeend'] = (int)$timeend;
 236          }
 237          if (empty($updatesql)) {
 238              return true;
 239          }
 240  
 241          // Update the modifierid.
 242          $updatesql[] = 'modifierid = :modifierid';
 243          $params['modifierid'] = (int)$USER->id;
 244  
 245          // Update the time modified.
 246          $updatesql[] = 'timemodified = :timemodified';
 247          $params['timemodified'] = time();
 248  
 249          // Build the SQL statement.
 250          $updatesql = join(', ', $updatesql);
 251          $sql = "UPDATE {user_enrolments}
 252                     SET $updatesql
 253                   WHERE id $ueidsql";
 254  
 255          if ($DB->execute($sql, $params)) {
 256              foreach ($users as $user) {
 257                  foreach ($user->enrolments as $enrolment) {
 258                      $enrolment->courseid  = $enrolment->enrolmentinstance->courseid;
 259                      $enrolment->enrol     = 'manual';
 260                      // Trigger event.
 261                      $event = \core\event\user_enrolment_updated::create(
 262                              array(
 263                                  'objectid' => $enrolment->id,
 264                                  'courseid' => $enrolment->courseid,
 265                                  'context' => context_course::instance($enrolment->courseid),
 266                                  'relateduserid' => $user->id,
 267                                  'other' => array('enrol' => 'manual')
 268                                  )
 269                              );
 270                      $event->trigger();
 271                  }
 272              }
 273              return true;
 274          }
 275  
 276          return false;
 277      }
 278  
 279      /**
 280       * Returns a enrol_bulk_enrolment_operation extension form to be used
 281       * in collecting required information for this operation to be processed.
 282       *
 283       * @param string|moodle_url|null $defaultaction
 284       * @param mixed $defaultcustomdata
 285       * @return enrol_manual_editselectedusers_form
 286       */
 287      public function get_form($defaultaction = null, $defaultcustomdata = null) {
 288          global $CFG;
 289          require_once($CFG->dirroot.'/enrol/manual/bulkchangeforms.php');
 290          return new enrol_manual_editselectedusers_form($defaultaction, $defaultcustomdata);
 291      }
 292  }
 293  
 294  
 295  /**
 296   * A bulk operation for the manual enrolment plugin to delete selected users enrolments.
 297   *
 298   * @copyright 2011 Sam Hemelryk
 299   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 300   */
 301  class enrol_manual_deleteselectedusers_operation extends enrol_bulk_enrolment_operation {
 302  
 303      /**
 304       * Returns the title to display for this bulk operation.
 305       *
 306       * @return string
 307       */
 308      public function get_identifier() {
 309          return 'deleteselectedusers';
 310      }
 311  
 312      /**
 313       * Returns the identifier for this bulk operation. This is the key used when the plugin
 314       * returns an array containing all of the bulk operations it supports.
 315       *
 316       * @return string
 317       */
 318      public function get_title() {
 319          return get_string('deleteselectedusers', 'enrol_manual');
 320      }
 321  
 322      /**
 323       * Returns a enrol_bulk_enrolment_operation extension form to be used
 324       * in collecting required information for this operation to be processed.
 325       *
 326       * @param string|moodle_url|null $defaultaction
 327       * @param mixed $defaultcustomdata
 328       * @return enrol_manual_editselectedusers_form
 329       */
 330      public function get_form($defaultaction = null, $defaultcustomdata = null) {
 331          global $CFG;
 332          require_once($CFG->dirroot.'/enrol/manual/bulkchangeforms.php');
 333          if (!array($defaultcustomdata)) {
 334              $defaultcustomdata = array();
 335          }
 336          $defaultcustomdata['title'] = $this->get_title();
 337          $defaultcustomdata['message'] = get_string('confirmbulkdeleteenrolment', 'enrol_manual');
 338          $defaultcustomdata['button'] = get_string('unenrolusers', 'enrol_manual');
 339          return new enrol_manual_deleteselectedusers_form($defaultaction, $defaultcustomdata);
 340      }
 341  
 342      /**
 343       * Processes the bulk operation request for the given userids with the provided properties.
 344       *
 345       * @global moodle_database $DB
 346       * @param course_enrolment_manager $manager
 347       * @param array $userids
 348       * @param stdClass $properties The data returned by the form.
 349       */
 350      public function process(course_enrolment_manager $manager, array $users, stdClass $properties) {
 351          global $DB;
 352  
 353          if (!has_capability("enrol/manual:unenrol", $manager->get_context())) {
 354              return false;
 355          }
 356          foreach ($users as $user) {
 357              foreach ($user->enrolments as $enrolment) {
 358                  $plugin = $enrolment->enrolmentplugin;
 359                  $instance = $enrolment->enrolmentinstance;
 360                  if ($plugin->allow_unenrol_user($instance, $enrolment)) {
 361                      $plugin->unenrol_user($instance, $user->id);
 362                  }
 363              }
 364          }
 365          return true;
 366      }
 367  }
 368  
 369  /**
 370   * Migrates all enrolments of the given plugin to enrol_manual plugin,
 371   * this is used for example during plugin uninstallation.
 372   *
 373   * NOTE: this function does not trigger role and enrolment related events.
 374   *
 375   * @param string $enrol  The enrolment method.
 376   */
 377  function enrol_manual_migrate_plugin_enrolments($enrol) {
 378      global $DB;
 379  
 380      if ($enrol === 'manual') {
 381          // We can not migrate to self.
 382          return;
 383      }
 384  
 385      $manualplugin = enrol_get_plugin('manual');
 386  
 387      $params = array('enrol'=>$enrol);
 388      $sql = "SELECT e.id, e.courseid, e.status, MIN(me.id) AS mid, COUNT(ue.id) AS cu
 389                FROM {enrol} e
 390                JOIN {user_enrolments} ue ON (ue.enrolid = e.id)
 391                JOIN {course} c ON (c.id = e.courseid)
 392           LEFT JOIN {enrol} me ON (me.courseid = e.courseid AND me.enrol='manual')
 393               WHERE e.enrol = :enrol
 394            GROUP BY e.id, e.courseid, e.status
 395            ORDER BY e.id";
 396      $rs = $DB->get_recordset_sql($sql, $params);
 397  
 398      foreach($rs as $e) {
 399          $minstance = false;
 400          if (!$e->mid) {
 401              // Manual instance does not exist yet, add a new one.
 402              $course = $DB->get_record('course', array('id'=>$e->courseid), '*', MUST_EXIST);
 403              if ($minstance = $DB->get_record('enrol', array('courseid'=>$course->id, 'enrol'=>'manual'))) {
 404                  // Already created by previous iteration.
 405                  $e->mid = $minstance->id;
 406              } else if ($e->mid = $manualplugin->add_default_instance($course)) {
 407                  $minstance = $DB->get_record('enrol', array('id'=>$e->mid));
 408                  if ($e->status != ENROL_INSTANCE_ENABLED) {
 409                      $DB->set_field('enrol', 'status', ENROL_INSTANCE_DISABLED, array('id'=>$e->mid));
 410                      $minstance->status = ENROL_INSTANCE_DISABLED;
 411                  }
 412              }
 413          } else {
 414              $minstance = $DB->get_record('enrol', array('id'=>$e->mid));
 415          }
 416  
 417          if (!$minstance) {
 418              // This should never happen unless adding of default instance fails unexpectedly.
 419              debugging('Failed to find manual enrolment instance', DEBUG_DEVELOPER);
 420              continue;
 421          }
 422  
 423          // First delete potential role duplicates.
 424          $params = array('id'=>$e->id, 'component'=>'enrol_'.$enrol, 'empty'=>'');
 425          $sql = "SELECT ra.id
 426                    FROM {role_assignments} ra
 427                    JOIN {role_assignments} mra ON (mra.contextid = ra.contextid AND mra.userid = ra.userid AND mra.roleid = ra.roleid AND mra.component = :empty AND mra.itemid = 0)
 428                   WHERE ra.component = :component AND ra.itemid = :id";
 429          $ras = $DB->get_records_sql($sql, $params);
 430          $ras = array_keys($ras);
 431          $DB->delete_records_list('role_assignments', 'id', $ras);
 432          unset($ras);
 433  
 434          // Migrate roles.
 435          $sql = "UPDATE {role_assignments}
 436                     SET itemid = 0, component = :empty
 437                   WHERE itemid = :id AND component = :component";
 438          $params = array('empty'=>'', 'id'=>$e->id, 'component'=>'enrol_'.$enrol);
 439          $DB->execute($sql, $params);
 440  
 441          // Delete potential enrol duplicates.
 442          $params = array('id'=>$e->id, 'mid'=>$e->mid);
 443          $sql = "SELECT ue.id
 444                    FROM {user_enrolments} ue
 445                    JOIN {user_enrolments} mue ON (mue.userid = ue.userid AND mue.enrolid = :mid)
 446                   WHERE ue.enrolid = :id";
 447          $ues = $DB->get_records_sql($sql, $params);
 448          $ues = array_keys($ues);
 449          $DB->delete_records_list('user_enrolments', 'id', $ues);
 450          unset($ues);
 451  
 452          // Migrate to manual enrol instance.
 453          $params = array('id'=>$e->id, 'mid'=>$e->mid);
 454          if ($e->status != ENROL_INSTANCE_ENABLED and $minstance->status == ENROL_INSTANCE_ENABLED) {
 455              $status = ", status = :disabled";
 456              $params['disabled'] = ENROL_USER_SUSPENDED;
 457          } else {
 458              $status = "";
 459          }
 460          $sql = "UPDATE {user_enrolments}
 461                     SET enrolid = :mid $status
 462                   WHERE enrolid = :id";
 463          $DB->execute($sql, $params);
 464      }
 465      $rs->close();
 466  }
 467  
 468  /**
 469   * Gets an array of the cohorts that can be enrolled in this course.
 470   *
 471   * @param int $enrolid
 472   * @param string $search
 473   * @param int $page Defaults to 0
 474   * @param int $perpage Defaults to 25
 475   * @param int $addedenrollment
 476   * @return array Array(totalcohorts => int, cohorts => array)
 477   */
 478  function enrol_manual_get_potential_cohorts($context, $enrolid, $search = '', $page = 0, $perpage = 25, $addedenrollment = 0) {
 479      global $CFG;
 480      require_once($CFG->dirroot . '/cohort/lib.php');
 481  
 482      $allcohorts = cohort_get_available_cohorts($context, COHORT_WITH_NOTENROLLED_MEMBERS_ONLY, 0, 0, $search);
 483      $totalcohorts = count($allcohorts);
 484      $cohorts = array();
 485      $cnt = 0;
 486      foreach ($allcohorts as $c) {
 487          if ($cnt >= $page * $perpage && (!$perpage || $cnt < ($page+1)*$perpage)) {
 488              $cohorts[] = (object)array(
 489                  'id' => $c->id,
 490                  'name' => format_string($c->name, true, array('context' => $c->contextid)),
 491                  'cnt' => $c->memberscnt - $c->enrolledcnt
 492              );
 493          }
 494          $cnt++;
 495      }
 496      return array('totalcohorts' => $totalcohorts, 'cohorts' => $cohorts);
 497  }


Generated: Fri Nov 28 20:29:05 2014 Cross-referenced by PHPXref 0.7.1