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