Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 4.1.x will end 13 November 2023 (12 months).
  • Bug fixes for security issues in 4.1.x will end 10 November 2025 (36 months).
  • PHP version: minimum PHP 7.4.0 Note: minimum PHP version has increased since Moodle 4.0. PHP 8.0.x is supported too.

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

   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 User Filter API.
  19   *
  20   * @package   core_user
  21   * @category  user
  22   * @copyright 1999 Martin Dougiamas  http://dougiamas.com
  23   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  24   */
  25  
  26  require_once($CFG->dirroot.'/user/filters/text.php');
  27  require_once($CFG->dirroot.'/user/filters/date.php');
  28  require_once($CFG->dirroot.'/user/filters/select.php');
  29  require_once($CFG->dirroot.'/user/filters/simpleselect.php');
  30  require_once($CFG->dirroot.'/user/filters/courserole.php');
  31  require_once($CFG->dirroot.'/user/filters/globalrole.php');
  32  require_once($CFG->dirroot.'/user/filters/profilefield.php');
  33  require_once($CFG->dirroot.'/user/filters/yesno.php');
  34  require_once($CFG->dirroot.'/user/filters/anycourses.php');
  35  require_once($CFG->dirroot.'/user/filters/cohort.php');
  36  require_once($CFG->dirroot.'/user/filters/user_filter_forms.php');
  37  require_once($CFG->dirroot.'/user/filters/checkbox.php');
  38  
  39  /**
  40   * User filtering wrapper class.
  41   *
  42   * @copyright 1999 Martin Dougiamas  http://dougiamas.com
  43   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  44   */
  45  class user_filtering {
  46      /** @var array */
  47      public $_fields;
  48      /** @var \user_add_filter_form */
  49      public $_addform;
  50      /** @var \user_active_filter_form */
  51      public $_activeform;
  52  
  53      /**
  54       * Contructor
  55       * @param array $fieldnames array of visible user fields
  56       * @param string $baseurl base url used for submission/return, null if the same of current page
  57       * @param array $extraparams extra page parameters
  58       */
  59      public function __construct($fieldnames = null, $baseurl = null, $extraparams = null) {
  60          global $SESSION;
  61  
  62          if (!isset($SESSION->user_filtering)) {
  63              $SESSION->user_filtering = array();
  64          }
  65  
  66          if (empty($fieldnames)) {
  67              // As a start, add all fields as advanced fields (which are only available after clicking on "Show more").
  68              $fieldnames = array('realname' => 1, 'lastname' => 1, 'firstname' => 1, 'username' => 1, 'email' => 1, 'city' => 1,
  69                                  'country' => 1, 'confirmed' => 1, 'suspended' => 1, 'profile' => 1, 'courserole' => 1,
  70                                  'anycourses' => 1, 'systemrole' => 1, 'cohort' => 1, 'firstaccess' => 1, 'lastaccess' => 1,
  71                                  'neveraccessed' => 1, 'timecreated' => 1, 'timemodified' => 1, 'nevermodified' => 1, 'auth' => 1,
  72                                  'mnethostid' => 1, 'idnumber' => 1, 'institution' => 1, 'department' => 1, 'lastip' => 1);
  73  
  74              // Get the config which filters the admin wanted to show by default.
  75              $userfiltersdefault = get_config('core', 'userfiltersdefault');
  76  
  77              // If the admin did not enable any filter, the form will not make much sense if all fields are hidden behind
  78              // "Show more". Thus, we enable the 'realname' filter automatically.
  79              if ($userfiltersdefault == '') {
  80                  $userfiltersdefault = array('realname');
  81  
  82                  // Otherwise, we split the enabled filters into an array.
  83              } else {
  84                  $userfiltersdefault = explode(',', $userfiltersdefault);
  85              }
  86  
  87              // Show these fields by default which the admin has enabled in the config.
  88              foreach ($userfiltersdefault as $key) {
  89                  $fieldnames[$key] = 0;
  90              }
  91          }
  92  
  93          $this->_fields  = array();
  94  
  95          foreach ($fieldnames as $fieldname => $advanced) {
  96              if ($field = $this->get_field($fieldname, $advanced)) {
  97                  $this->_fields[$fieldname] = $field;
  98              }
  99          }
 100  
 101          // Fist the new filter form.
 102          $this->_addform = new user_add_filter_form($baseurl, array('fields' => $this->_fields, 'extraparams' => $extraparams));
 103          if ($adddata = $this->_addform->get_data()) {
 104              // Clear previous filters.
 105              if (!empty($adddata->replacefilters)) {
 106                  $SESSION->user_filtering = [];
 107              }
 108  
 109              // Add new filters.
 110              foreach ($this->_fields as $fname => $field) {
 111                  $data = $field->check_data($adddata);
 112                  if ($data === false) {
 113                      continue; // Nothing new.
 114                  }
 115                  if (!array_key_exists($fname, $SESSION->user_filtering)) {
 116                      $SESSION->user_filtering[$fname] = array();
 117                  }
 118                  $SESSION->user_filtering[$fname][] = $data;
 119              }
 120          }
 121  
 122          // Now the active filters.
 123          $this->_activeform = new user_active_filter_form($baseurl, array('fields' => $this->_fields, 'extraparams' => $extraparams));
 124          if ($activedata = $this->_activeform->get_data()) {
 125              if (!empty($activedata->removeall)) {
 126                  $SESSION->user_filtering = array();
 127  
 128              } else if (!empty($activedata->removeselected) and !empty($activedata->filter)) {
 129                  foreach ($activedata->filter as $fname => $instances) {
 130                      foreach ($instances as $i => $val) {
 131                          if (empty($val)) {
 132                              continue;
 133                          }
 134                          unset($SESSION->user_filtering[$fname][$i]);
 135                      }
 136                      if (empty($SESSION->user_filtering[$fname])) {
 137                          unset($SESSION->user_filtering[$fname]);
 138                      }
 139                  }
 140              }
 141          }
 142  
 143          // Rebuild the forms if filters data was processed.
 144          if ($adddata || $activedata) {
 145              $_POST = []; // Reset submitted data.
 146              $this->_addform = new user_add_filter_form($baseurl, ['fields' => $this->_fields, 'extraparams' => $extraparams]);
 147              $this->_activeform = new user_active_filter_form($baseurl, ['fields' => $this->_fields, 'extraparams' => $extraparams]);
 148          }
 149      }
 150  
 151      /**
 152       * Creates known user filter if present
 153       * @param string $fieldname
 154       * @param boolean $advanced
 155       * @return object filter
 156       */
 157      public function get_field($fieldname, $advanced) {
 158          global $USER, $CFG, $DB, $SITE;
 159  
 160          switch ($fieldname) {
 161              case 'username':    return new user_filter_text('username', get_string('username'), $advanced, 'username');
 162              case 'realname':    return new user_filter_text('realname', get_string('fullnameuser'), $advanced, $DB->sql_fullname());
 163              case 'lastname':    return new user_filter_text('lastname', get_string('lastname'), $advanced, 'lastname');
 164              case 'firstname':    return new user_filter_text('firstname', get_string('firstname'), $advanced, 'firstname');
 165              case 'email':       return new user_filter_text('email', get_string('email'), $advanced, 'email');
 166              case 'city':        return new user_filter_text('city', get_string('city'), $advanced, 'city');
 167              case 'country':     return new user_filter_select('country', get_string('country'), $advanced, 'country', get_string_manager()->get_list_of_countries(), $USER->country);
 168              case 'confirmed':   return new user_filter_yesno('confirmed', get_string('confirmed', 'admin'), $advanced, 'confirmed');
 169              case 'suspended':   return new user_filter_yesno('suspended', get_string('suspended', 'auth'), $advanced, 'suspended');
 170              case 'profile':     return new user_filter_profilefield('profile', get_string('profilefields', 'admin'), $advanced);
 171              case 'courserole':  return new user_filter_courserole('courserole', get_string('courserole', 'filters'), $advanced);
 172              case 'anycourses':
 173                  return new user_filter_anycourses('anycourses', get_string('anycourses', 'filters'), $advanced, 'user_enrolments');
 174              case 'systemrole':  return new user_filter_globalrole('systemrole', get_string('globalrole', 'role'), $advanced);
 175              case 'firstaccess': return new user_filter_date('firstaccess', get_string('firstaccess', 'filters'), $advanced, 'firstaccess');
 176              case 'lastaccess':  return new user_filter_date('lastaccess', get_string('lastaccess'), $advanced, 'lastaccess');
 177              case 'neveraccessed': return new user_filter_checkbox('neveraccessed', get_string('neveraccessed', 'filters'), $advanced, 'firstaccess', array('lastaccess_sck', 'lastaccess_eck', 'firstaccess_eck', 'firstaccess_sck'));
 178              case 'timecreated': return new user_filter_date('timecreated', get_string('timecreated'), $advanced, 'timecreated');
 179              case 'timemodified': return new user_filter_date('timemodified', get_string('lastmodified'), $advanced, 'timemodified');
 180              case 'nevermodified': return new user_filter_checkbox('nevermodified', get_string('nevermodified', 'filters'), $advanced, array('timemodified', 'timecreated'), array('timemodified_sck', 'timemodified_eck'));
 181              case 'cohort':      return new user_filter_cohort($advanced);
 182              case 'idnumber':    return new user_filter_text('idnumber', get_string('idnumber'), $advanced, 'idnumber');
 183              case 'institution': return new user_filter_text('institution', get_string('institution'), $advanced, 'institution');
 184              case 'department': return new user_filter_text('department', get_string('department'), $advanced, 'department');
 185              case 'lastip':    return new user_filter_text('lastip', get_string('lastip'), $advanced, 'lastip');
 186              case 'auth':
 187                  $plugins = core_component::get_plugin_list('auth');
 188                  $choices = array();
 189                  foreach ($plugins as $auth => $unused) {
 190                      $choices[$auth] = get_string('pluginname', "auth_{$auth}");
 191                  }
 192                  return new user_filter_simpleselect('auth', get_string('authentication'), $advanced, 'auth', $choices);
 193  
 194              case 'mnethostid':
 195                  // Include all hosts even those deleted or otherwise problematic.
 196                  if (!$hosts = $DB->get_records('mnet_host', null, 'id', 'id, wwwroot, name')) {
 197                      $hosts = array();
 198                  }
 199                  $choices = array();
 200                  foreach ($hosts as $host) {
 201                      if ($host->id == $CFG->mnet_localhost_id) {
 202                          $choices[$host->id] = format_string($SITE->fullname).' ('.get_string('local').')';
 203                      } else if (empty($host->wwwroot)) {
 204                          // All hosts.
 205                          continue;
 206                      } else {
 207                          $choices[$host->id] = $host->name.' ('.$host->wwwroot.')';
 208                      }
 209                  }
 210                  if ($usedhosts = $DB->get_fieldset_sql("SELECT DISTINCT mnethostid FROM {user} WHERE deleted=0")) {
 211                      foreach ($usedhosts as $hostid) {
 212                          if (empty($hosts[$hostid])) {
 213                              $choices[$hostid] = 'id: '.$hostid.' ('.get_string('error').')';
 214                          }
 215                      }
 216                  }
 217                  if (count($choices) < 2) {
 218                      return null; // Filter not needed.
 219                  }
 220                  return new user_filter_simpleselect('mnethostid', get_string('mnetidprovider', 'mnet'), $advanced, 'mnethostid', $choices);
 221  
 222              default:
 223                  return null;
 224          }
 225      }
 226  
 227      /**
 228       * Returns sql where statement based on active user filters
 229       * @param string $extra sql
 230       * @param array $params named params (recommended prefix ex)
 231       * @return array sql string and $params
 232       */
 233      public function get_sql_filter($extra='', array $params=null) {
 234          global $SESSION;
 235  
 236          $sqls = array();
 237          if ($extra != '') {
 238              $sqls[] = $extra;
 239          }
 240          $params = (array)$params;
 241  
 242          if (!empty($SESSION->user_filtering)) {
 243              foreach ($SESSION->user_filtering as $fname => $datas) {
 244                  if (!array_key_exists($fname, $this->_fields)) {
 245                      continue; // Filter not used.
 246                  }
 247                  $field = $this->_fields[$fname];
 248                  foreach ($datas as $i => $data) {
 249                      list($s, $p) = $field->get_sql_filter($data);
 250                      $sqls[] = $s;
 251                      $params = $params + $p;
 252                  }
 253              }
 254          }
 255  
 256          if (empty($sqls)) {
 257              return array('', array());
 258          } else {
 259              $sqls = implode(' AND ', $sqls);
 260              return array($sqls, $params);
 261          }
 262      }
 263  
 264      /**
 265       * Print the add filter form.
 266       */
 267      public function display_add() {
 268          $this->_addform->display();
 269      }
 270  
 271      /**
 272       * Print the active filter form.
 273       */
 274      public function display_active() {
 275          $this->_activeform->display();
 276      }
 277  
 278  }
 279  
 280  /**
 281   * The base user filter class. All abstract classes must be implemented.
 282   *
 283   * @copyright 1999 Martin Dougiamas  http://dougiamas.com
 284   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 285   */
 286  class user_filter_type {
 287      /**
 288       * The name of this filter instance.
 289       * @var string
 290       */
 291      public $_name;
 292  
 293      /**
 294       * The label of this filter instance.
 295       * @var string
 296       */
 297      public $_label;
 298  
 299      /**
 300       * Advanced form element flag
 301       * @var bool
 302       */
 303      public $_advanced;
 304  
 305      /**
 306       * Constructor
 307       * @param string $name the name of the filter instance
 308       * @param string $label the label of the filter instance
 309       * @param boolean $advanced advanced form element flag
 310       */
 311      public function __construct($name, $label, $advanced) {
 312          $this->_name     = $name;
 313          $this->_label    = $label;
 314          $this->_advanced = $advanced;
 315      }
 316  
 317      /**
 318       * Old syntax of class constructor. Deprecated in PHP7.
 319       *
 320       * @deprecated since Moodle 3.1
 321       */
 322      public function user_filter_type($name, $label, $advanced) {
 323          debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
 324          self::__construct($name, $label, $advanced);
 325      }
 326  
 327      /**
 328       * Returns the condition to be used with SQL where
 329       * @param array $data filter settings
 330       * @return string the filtering condition or null if the filter is disabled
 331       */
 332      public function get_sql_filter($data) {
 333          throw new \moodle_exception('mustbeoveride', 'debug', '', 'get_sql_filter');
 334      }
 335  
 336      /**
 337       * Retrieves data from the form data
 338       * @param stdClass $formdata data submited with the form
 339       * @return mixed array filter data or false when filter not set
 340       */
 341      public function check_data($formdata) {
 342          throw new \moodle_exception('mustbeoveride', 'debug', '', 'check_data');
 343      }
 344  
 345      /**
 346       * Adds controls specific to this filter in the form.
 347       * @param moodleform $mform a MoodleForm object to setup
 348       */
 349      public function setupForm(&$mform) {
 350          throw new \moodle_exception('mustbeoveride', 'debug', '', 'setupForm');
 351      }
 352  
 353      /**
 354       * Returns a human friendly description of the filter used as label.
 355       * @param array $data filter settings
 356       * @return string active filter label
 357       */
 358      public function get_label($data) {
 359          throw new \moodle_exception('mustbeoveride', 'debug', '', 'get_label');
 360      }
 361  }