Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.0.x will end 8 May 2023 (12 months).
  • Bug fixes for security issues in 4.0.x will end 13 November 2023 (18 months).
  • PHP version: minimum PHP 7.3.0 Note: the minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is also supported.
/admin/ -> user.php (source)

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

   1  <?php
   2  
   3      require_once('../config.php');
   4      require_once($CFG->libdir.'/adminlib.php');
   5      require_once($CFG->libdir.'/authlib.php');
   6      require_once($CFG->dirroot.'/user/filters/lib.php');
   7      require_once($CFG->dirroot.'/user/lib.php');
   8  
   9      $delete       = optional_param('delete', 0, PARAM_INT);
  10      $confirm      = optional_param('confirm', '', PARAM_ALPHANUM);   //md5 confirmation hash
  11      $confirmuser  = optional_param('confirmuser', 0, PARAM_INT);
  12      $sort         = optional_param('sort', 'name', PARAM_ALPHANUMEXT);
  13      $dir          = optional_param('dir', 'ASC', PARAM_ALPHA);
  14      $page         = optional_param('page', 0, PARAM_INT);
  15      $perpage      = optional_param('perpage', 30, PARAM_INT);        // how many per page
  16      $ru           = optional_param('ru', '2', PARAM_INT);            // show remote users
  17      $lu           = optional_param('lu', '2', PARAM_INT);            // show local users
  18      $acl          = optional_param('acl', '0', PARAM_INT);           // id of user to tweak mnet ACL (requires $access)
  19      $suspend      = optional_param('suspend', 0, PARAM_INT);
  20      $unsuspend    = optional_param('unsuspend', 0, PARAM_INT);
  21      $unlock       = optional_param('unlock', 0, PARAM_INT);
  22      $resendemail  = optional_param('resendemail', 0, PARAM_INT);
  23  
  24      admin_externalpage_setup('editusers');
  25  
  26      $sitecontext = context_system::instance();
  27      $site = get_site();
  28  
  29      if (!has_capability('moodle/user:update', $sitecontext) and !has_capability('moodle/user:delete', $sitecontext)) {
  30          print_error('nopermissions', 'error', '', 'edit/delete users');
  31      }
  32  
  33      $stredit   = get_string('edit');
  34      $strdelete = get_string('delete');
  35      $strdeletecheck = get_string('deletecheck');
  36      $strshowallusers = get_string('showallusers');
  37      $strsuspend = get_string('suspenduser', 'admin');
  38      $strunsuspend = get_string('unsuspenduser', 'admin');
  39      $strunlock = get_string('unlockaccount', 'admin');
  40      $strconfirm = get_string('confirm');
  41      $strresendemail = get_string('resendemail');
  42  
  43      $returnurl = new moodle_url('/admin/user.php', array('sort' => $sort, 'dir' => $dir, 'perpage' => $perpage, 'page'=>$page));
  44  
  45      $PAGE->set_primary_active_tab('siteadminnode');
  46      $PAGE->navbar->add(get_string('userlist', 'admin'), $PAGE->url);
  47  
  48      // The $user variable is also used outside of these if statements.
  49      $user = null;
  50      if ($confirmuser and confirm_sesskey()) {
  51          require_capability('moodle/user:update', $sitecontext);
  52          if (!$user = $DB->get_record('user', array('id'=>$confirmuser, 'mnethostid'=>$CFG->mnet_localhost_id))) {
  53              print_error('nousers');
  54          }
  55  
  56          $auth = get_auth_plugin($user->auth);
  57  
  58          $result = $auth->user_confirm($user->username, $user->secret);
  59  
  60          if ($result == AUTH_CONFIRM_OK or $result == AUTH_CONFIRM_ALREADY) {
  61              redirect($returnurl);
  62          } else {
  63              echo $OUTPUT->header();
  64              redirect($returnurl, get_string('usernotconfirmed', '', fullname($user, true)));
  65          }
  66  
  67      } else if ($resendemail && confirm_sesskey()) {
  68          if (!$user = $DB->get_record('user', ['id' => $resendemail, 'mnethostid' => $CFG->mnet_localhost_id, 'deleted' => 0])) {
  69              print_error('nousers');
  70          }
  71  
  72          // Prevent spamming users who are already confirmed.
  73          if ($user->confirmed) {
  74              print_error('alreadyconfirmed');
  75          }
  76  
  77          $returnmsg = get_string('emailconfirmsentsuccess');
  78          $messagetype = \core\output\notification::NOTIFY_SUCCESS;
  79          if (!send_confirmation_email($user)) {
  80              $returnmsg = get_string('emailconfirmsentfailure');
  81              $messagetype = \core\output\notification::NOTIFY_ERROR;
  82          }
  83  
  84          redirect($returnurl, $returnmsg, null, $messagetype);
  85      } else if ($delete and confirm_sesskey()) {              // Delete a selected user, after confirmation
  86          require_capability('moodle/user:delete', $sitecontext);
  87  
  88          $user = $DB->get_record('user', array('id'=>$delete, 'mnethostid'=>$CFG->mnet_localhost_id), '*', MUST_EXIST);
  89  
  90          if ($user->deleted) {
  91              print_error('usernotdeleteddeleted', 'error');
  92          }
  93          if (is_siteadmin($user->id)) {
  94              print_error('useradminodelete', 'error');
  95          }
  96  
  97          if ($confirm != md5($delete)) {
  98              echo $OUTPUT->header();
  99              $fullname = fullname($user, true);
 100              echo $OUTPUT->heading(get_string('deleteuser', 'admin'));
 101  
 102              $optionsyes = array('delete'=>$delete, 'confirm'=>md5($delete), 'sesskey'=>sesskey());
 103              $deleteurl = new moodle_url($returnurl, $optionsyes);
 104              $deletebutton = new single_button($deleteurl, get_string('delete'), 'post');
 105  
 106              echo $OUTPUT->confirm(get_string('deletecheckfull', '', "'$fullname'"), $deletebutton, $returnurl);
 107              echo $OUTPUT->footer();
 108              die;
 109          } else if (data_submitted()) {
 110              if (delete_user($user)) {
 111                  \core\session\manager::gc(); // Remove stale sessions.
 112                  redirect($returnurl);
 113              } else {
 114                  \core\session\manager::gc(); // Remove stale sessions.
 115                  echo $OUTPUT->header();
 116                  echo $OUTPUT->notification($returnurl, get_string('deletednot', '', fullname($user, true)));
 117              }
 118          }
 119      } else if ($acl and confirm_sesskey()) {
 120          if (!has_capability('moodle/user:update', $sitecontext)) {
 121              print_error('nopermissions', 'error', '', 'modify the NMET access control list');
 122          }
 123          if (!$user = $DB->get_record('user', array('id'=>$acl))) {
 124              print_error('nousers', 'error');
 125          }
 126          if (!is_mnet_remote_user($user)) {
 127              print_error('usermustbemnet', 'error');
 128          }
 129          $accessctrl = strtolower(required_param('accessctrl', PARAM_ALPHA));
 130          if ($accessctrl != 'allow' and $accessctrl != 'deny') {
 131              print_error('invalidaccessparameter', 'error');
 132          }
 133          $aclrecord = $DB->get_record('mnet_sso_access_control', array('username'=>$user->username, 'mnet_host_id'=>$user->mnethostid));
 134          if (empty($aclrecord)) {
 135              $aclrecord = new stdClass();
 136              $aclrecord->mnet_host_id = $user->mnethostid;
 137              $aclrecord->username = $user->username;
 138              $aclrecord->accessctrl = $accessctrl;
 139              $DB->insert_record('mnet_sso_access_control', $aclrecord);
 140          } else {
 141              $aclrecord->accessctrl = $accessctrl;
 142              $DB->update_record('mnet_sso_access_control', $aclrecord);
 143          }
 144          $mnethosts = $DB->get_records('mnet_host', null, 'id', 'id,wwwroot,name');
 145          redirect($returnurl);
 146  
 147      } else if ($suspend and confirm_sesskey()) {
 148          require_capability('moodle/user:update', $sitecontext);
 149  
 150          if ($user = $DB->get_record('user', array('id'=>$suspend, 'mnethostid'=>$CFG->mnet_localhost_id, 'deleted'=>0))) {
 151              if (!is_siteadmin($user) and $USER->id != $user->id and $user->suspended != 1) {
 152                  $user->suspended = 1;
 153                  // Force logout.
 154                  \core\session\manager::kill_user_sessions($user->id);
 155                  user_update_user($user, false);
 156              }
 157          }
 158          redirect($returnurl);
 159  
 160      } else if ($unsuspend and confirm_sesskey()) {
 161          require_capability('moodle/user:update', $sitecontext);
 162  
 163          if ($user = $DB->get_record('user', array('id'=>$unsuspend, 'mnethostid'=>$CFG->mnet_localhost_id, 'deleted'=>0))) {
 164              if ($user->suspended != 0) {
 165                  $user->suspended = 0;
 166                  user_update_user($user, false);
 167              }
 168          }
 169          redirect($returnurl);
 170  
 171      } else if ($unlock and confirm_sesskey()) {
 172          require_capability('moodle/user:update', $sitecontext);
 173  
 174          if ($user = $DB->get_record('user', array('id'=>$unlock, 'mnethostid'=>$CFG->mnet_localhost_id, 'deleted'=>0))) {
 175              login_unlock_account($user);
 176          }
 177          redirect($returnurl);
 178      }
 179  
 180      // create the user filter form
 181      $ufiltering = new user_filtering();
 182      echo $OUTPUT->header();
 183  
 184      // Carry on with the user listing
 185      $context = context_system::instance();
 186      // These columns are always shown in the users list.
 187      $requiredcolumns = array('city', 'country', 'lastaccess');
 188      // Extra columns containing the extra user fields, excluding the required columns (city and country, to be specific).
 189      $userfields = \core_user\fields::for_identity($context, true)->excluding(...$requiredcolumns);
 190      $extracolumns = $userfields->get_required_fields();
 191      // Get all user name fields as an array, but with firstname and lastname first.
 192      $allusernamefields = \core_user\fields::get_name_fields(true);
 193      $columns = array_merge($allusernamefields, $extracolumns, $requiredcolumns);
 194  
 195      foreach ($columns as $column) {
 196          $string[$column] = \core_user\fields::get_display_name($column);
 197          if ($sort != $column) {
 198              $columnicon = "";
 199              if ($column == "lastaccess") {
 200                  $columndir = "DESC";
 201              } else {
 202                  $columndir = "ASC";
 203              }
 204          } else {
 205              $columndir = $dir == "ASC" ? "DESC":"ASC";
 206              if ($column == "lastaccess") {
 207                  $columnicon = ($dir == "ASC") ? "sort_desc" : "sort_asc";
 208              } else {
 209                  $columnicon = ($dir == "ASC") ? "sort_asc" : "sort_desc";
 210              }
 211              $columnicon = $OUTPUT->pix_icon('t/' . $columnicon, get_string(strtolower($columndir)), 'core',
 212                                              ['class' => 'iconsort']);
 213  
 214          }
 215          $$column = "<a href=\"user.php?sort=$column&amp;dir=$columndir\">".$string[$column]."</a>$columnicon";
 216      }
 217  
 218      // We need to check that alternativefullnameformat is not set to '' or language.
 219      // We don't need to check the fullnamedisplay setting here as the fullname function call further down has
 220      // the override parameter set to true.
 221      $fullnamesetting = $CFG->alternativefullnameformat;
 222      // If we are using language or it is empty, then retrieve the default user names of just 'firstname' and 'lastname'.
 223      if ($fullnamesetting == 'language' || empty($fullnamesetting)) {
 224          // Set $a variables to return 'firstname' and 'lastname'.
 225          $a = new stdClass();
 226          $a->firstname = 'firstname';
 227          $a->lastname = 'lastname';
 228          // Getting the fullname display will ensure that the order in the language file is maintained.
 229          $fullnamesetting = get_string('fullnamedisplay', null, $a);
 230      }
 231  
 232      // Order in string will ensure that the name columns are in the correct order.
 233      $usernames = order_in_string($allusernamefields, $fullnamesetting);
 234      $fullnamedisplay = array();
 235      foreach ($usernames as $name) {
 236          // Use the link from $$column for sorting on the user's name.
 237          $fullnamedisplay[] = ${$name};
 238      }
 239      // All of the names are in one column. Put them into a string and separate them with a /.
 240      $fullnamedisplay = implode(' / ', $fullnamedisplay);
 241      // If $sort = name then it is the default for the setting and we should use the first name to sort by.
 242      if ($sort == "name") {
 243          // Use the first item in the array.
 244          $sort = reset($usernames);
 245      }
 246  
 247      list($extrasql, $params) = $ufiltering->get_sql_filter();
 248      $users = get_users_listing($sort, $dir, $page*$perpage, $perpage, '', '', '',
 249              $extrasql, $params, $context);
 250      $usercount = get_users(false);
 251      $usersearchcount = get_users(false, '', false, null, "", '', '', '', '', '*', $extrasql, $params);
 252  
 253      if ($extrasql !== '') {
 254          echo $OUTPUT->heading("$usersearchcount / $usercount ".get_string('users'));
 255          $usercount = $usersearchcount;
 256      } else {
 257          echo $OUTPUT->heading("$usercount ".get_string('users'));
 258      }
 259  
 260      $strall = get_string('all');
 261  
 262      $baseurl = new moodle_url('/admin/user.php', array('sort' => $sort, 'dir' => $dir, 'perpage' => $perpage));
 263      echo $OUTPUT->paging_bar($usercount, $page, $perpage, $baseurl);
 264  
 265      flush();
 266  
 267  
 268      if (!$users) {
 269          $match = array();
 270          echo $OUTPUT->heading(get_string('nousersfound'));
 271  
 272          $table = NULL;
 273  
 274      } else {
 275  
 276          $countries = get_string_manager()->get_list_of_countries(true);
 277          if (empty($mnethosts)) {
 278              $mnethosts = $DB->get_records('mnet_host', null, 'id', 'id,wwwroot,name');
 279          }
 280  
 281          foreach ($users as $key => $user) {
 282              if (isset($countries[$user->country])) {
 283                  $users[$key]->country = $countries[$user->country];
 284              }
 285          }
 286          if ($sort == "country") {
 287              // Need to resort by full country name, not code.
 288              foreach ($users as $user) {
 289                  $susers[$user->id] = $user->country;
 290              }
 291              // Sort by country name, according to $dir.
 292              if ($dir === 'DESC') {
 293                  arsort($susers);
 294              } else {
 295                  asort($susers);
 296              }
 297              foreach ($susers as $key => $value) {
 298                  $nusers[] = $users[$key];
 299              }
 300              $users = $nusers;
 301          }
 302  
 303          $table = new html_table();
 304          $table->head = array ();
 305          $table->colclasses = array();
 306          $table->head[] = $fullnamedisplay;
 307          $table->attributes['class'] = 'admintable generaltable table-sm';
 308          foreach ($extracolumns as $field) {
 309              $table->head[] = ${$field};
 310          }
 311          $table->head[] = $city;
 312          $table->head[] = $country;
 313          $table->head[] = $lastaccess;
 314          $table->head[] = get_string('edit');
 315          $table->colclasses[] = 'centeralign';
 316          $table->head[] = "";
 317          $table->colclasses[] = 'centeralign';
 318  
 319          $table->id = "users";
 320          foreach ($users as $user) {
 321              $buttons = array();
 322              $lastcolumn = '';
 323  
 324              // delete button
 325              if (has_capability('moodle/user:delete', $sitecontext)) {
 326                  if (is_mnet_remote_user($user) or $user->id == $USER->id or is_siteadmin($user)) {
 327                      // no deleting of self, mnet accounts or admins allowed
 328                  } else {
 329                      $url = new moodle_url($returnurl, array('delete'=>$user->id, 'sesskey'=>sesskey()));
 330                      $buttons[] = html_writer::link($url, $OUTPUT->pix_icon('t/delete', $strdelete));
 331                  }
 332              }
 333  
 334              // suspend button
 335              if (has_capability('moodle/user:update', $sitecontext)) {
 336                  if (is_mnet_remote_user($user)) {
 337                      // mnet users have special access control, they can not be deleted the standard way or suspended
 338                      $accessctrl = 'allow';
 339                      if ($acl = $DB->get_record('mnet_sso_access_control', array('username'=>$user->username, 'mnet_host_id'=>$user->mnethostid))) {
 340                          $accessctrl = $acl->accessctrl;
 341                      }
 342                      $changeaccessto = ($accessctrl == 'deny' ? 'allow' : 'deny');
 343                      $buttons[] = " (<a href=\"?acl={$user->id}&amp;accessctrl=$changeaccessto&amp;sesskey=".sesskey()."\">".get_string($changeaccessto, 'mnet') . " access</a>)";
 344  
 345                  } else {
 346                      if ($user->suspended) {
 347                          $url = new moodle_url($returnurl, array('unsuspend'=>$user->id, 'sesskey'=>sesskey()));
 348                          $buttons[] = html_writer::link($url, $OUTPUT->pix_icon('t/show', $strunsuspend));
 349                      } else {
 350                          if ($user->id == $USER->id or is_siteadmin($user)) {
 351                              // no suspending of admins or self!
 352                          } else {
 353                              $url = new moodle_url($returnurl, array('suspend'=>$user->id, 'sesskey'=>sesskey()));
 354                              $buttons[] = html_writer::link($url, $OUTPUT->pix_icon('t/hide', $strsuspend));
 355                          }
 356                      }
 357  
 358                      if (login_is_lockedout($user)) {
 359                          $url = new moodle_url($returnurl, array('unlock'=>$user->id, 'sesskey'=>sesskey()));
 360                          $buttons[] = html_writer::link($url, $OUTPUT->pix_icon('t/unlock', $strunlock));
 361                      }
 362                  }
 363              }
 364  
 365              // edit button
 366              if (has_capability('moodle/user:update', $sitecontext)) {
 367                  // prevent editing of admins by non-admins
 368                  if (is_siteadmin($USER) or !is_siteadmin($user)) {
 369                      $url = new moodle_url('/user/editadvanced.php', array('id'=>$user->id, 'course'=>$site->id));
 370                      $buttons[] = html_writer::link($url, $OUTPUT->pix_icon('t/edit', $stredit));
 371                  }
 372              }
 373  
 374              // the last column - confirm or mnet info
 375              if (is_mnet_remote_user($user)) {
 376                  // all mnet users are confirmed, let's print just the name of the host there
 377                  if (isset($mnethosts[$user->mnethostid])) {
 378                      $lastcolumn = get_string($accessctrl, 'mnet').': '.$mnethosts[$user->mnethostid]->name;
 379                  } else {
 380                      $lastcolumn = get_string($accessctrl, 'mnet');
 381                  }
 382  
 383              } else if ($user->confirmed == 0) {
 384                  if (has_capability('moodle/user:update', $sitecontext)) {
 385                      $lastcolumn = html_writer::link(new moodle_url($returnurl, array('confirmuser'=>$user->id, 'sesskey'=>sesskey())), $strconfirm);
 386                  } else {
 387                      $lastcolumn = "<span class=\"dimmed_text\">".get_string('confirm')."</span>";
 388                  }
 389  
 390                  $lastcolumn .= ' | ' . html_writer::link(new moodle_url($returnurl,
 391                      [
 392                          'resendemail' => $user->id,
 393                          'sesskey' => sesskey()
 394                      ]
 395                  ), $strresendemail);
 396              }
 397  
 398              if ($user->lastaccess) {
 399                  $strlastaccess = format_time(time() - $user->lastaccess);
 400              } else {
 401                  $strlastaccess = get_string('never');
 402              }
 403              $fullname = fullname($user, true);
 404  
 405              $row = array ();
 406              $row[] = "<a href=\"../user/view.php?id=$user->id&amp;course=$site->id\">$fullname</a>";
 407              foreach ($extracolumns as $field) {
 408                  $row[] = s($user->{$field});
 409              }
 410              $row[] = $user->city;
 411              $row[] = $user->country;
 412              $row[] = $strlastaccess;
 413              if ($user->suspended) {
 414                  foreach ($row as $k=>$v) {
 415                      $row[$k] = html_writer::tag('span', $v, array('class'=>'usersuspended'));
 416                  }
 417              }
 418              $row[] = implode(' ', $buttons);
 419              $row[] = $lastcolumn;
 420              $table->data[] = $row;
 421          }
 422      }
 423  
 424      // add filters
 425      $ufiltering->display_add();
 426      $ufiltering->display_active();
 427  
 428      if (!empty($table)) {
 429          echo html_writer::start_tag('div', array('class'=>'no-overflow'));
 430          echo html_writer::table($table);
 431          echo html_writer::end_tag('div');
 432          echo $OUTPUT->paging_bar($usercount, $page, $perpage, $baseurl);
 433      }
 434      if (has_capability('moodle/user:create', $sitecontext)) {
 435          $url = new moodle_url('/user/editadvanced.php', array('id' => -1));
 436          echo $OUTPUT->single_button($url, get_string('addnewuser'), 'get');
 437      }
 438  
 439      echo $OUTPUT->footer();