editlib.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  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. * This file contains function used when editing a users profile and preferences.
  18. *
  19. * @copyright 1999 Martin Dougiamas http://dougiamas.com
  20. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  21. * @package core_user
  22. */
  23. require_once($CFG->dirroot . '/user/lib.php');
  24. /**
  25. * Cancels the requirement for a user to update their email address.
  26. *
  27. * @param int $userid
  28. */
  29. function cancel_email_update($userid) {
  30. unset_user_preference('newemail', $userid);
  31. unset_user_preference('newemailkey', $userid);
  32. unset_user_preference('newemailattemptsleft', $userid);
  33. }
  34. /**
  35. * Performs the common access checks and page setup for all
  36. * user preference pages.
  37. *
  38. * @param int $userid The user id to edit taken from the page params.
  39. * @param int $courseid The optional course id if we came from a course context.
  40. * @return array containing the user and course records.
  41. */
  42. function useredit_setup_preference_page($userid, $courseid) {
  43. global $PAGE, $SESSION, $DB, $CFG, $OUTPUT, $USER;
  44. // Guest can not edit.
  45. if (isguestuser()) {
  46. print_error('guestnoeditprofile');
  47. }
  48. if (!$course = $DB->get_record('course', array('id' => $courseid))) {
  49. print_error('invalidcourseid');
  50. }
  51. if ($course->id != SITEID) {
  52. require_login($course);
  53. } else if (!isloggedin()) {
  54. if (empty($SESSION->wantsurl)) {
  55. $SESSION->wantsurl = $CFG->wwwroot.'/user/preferences.php';
  56. }
  57. redirect(get_login_url());
  58. } else {
  59. $PAGE->set_context(context_system::instance());
  60. }
  61. // The user profile we are editing.
  62. if (!$user = $DB->get_record('user', array('id' => $userid))) {
  63. print_error('invaliduserid');
  64. }
  65. // Guest can not be edited.
  66. if (isguestuser($user)) {
  67. print_error('guestnoeditprofile');
  68. }
  69. // Remote users cannot be edited.
  70. if (is_mnet_remote_user($user)) {
  71. if (user_not_fully_set_up($user, false)) {
  72. $hostwwwroot = $DB->get_field('mnet_host', 'wwwroot', array('id' => $user->mnethostid));
  73. print_error('usernotfullysetup', 'mnet', '', $hostwwwroot);
  74. }
  75. redirect($CFG->wwwroot . "/user/view.php?course={$course->id}");
  76. }
  77. $systemcontext = context_system::instance();
  78. $personalcontext = context_user::instance($user->id);
  79. // Check access control.
  80. if ($user->id == $USER->id) {
  81. // Editing own profile - require_login() MUST NOT be used here, it would result in infinite loop!
  82. if (!has_capability('moodle/user:editownprofile', $systemcontext)) {
  83. print_error('cannotedityourprofile');
  84. }
  85. } else {
  86. // Teachers, parents, etc.
  87. require_capability('moodle/user:editprofile', $personalcontext);
  88. // No editing of primary admin!
  89. if (is_siteadmin($user) and !is_siteadmin($USER)) { // Only admins may edit other admins.
  90. print_error('useradmineditadmin');
  91. }
  92. }
  93. if ($user->deleted) {
  94. echo $OUTPUT->header();
  95. echo $OUTPUT->heading(get_string('userdeleted'));
  96. echo $OUTPUT->footer();
  97. die;
  98. }
  99. $PAGE->set_pagelayout('admin');
  100. $PAGE->set_context($personalcontext);
  101. if ($USER->id != $user->id) {
  102. $PAGE->navigation->extend_for_user($user);
  103. } else {
  104. if ($node = $PAGE->navigation->find('myprofile', navigation_node::TYPE_ROOTNODE)) {
  105. $node->force_open();
  106. }
  107. }
  108. return array($user, $course);
  109. }
  110. /**
  111. * Loads the given users preferences into the given user object.
  112. *
  113. * @param stdClass $user The user object, modified by reference.
  114. * @param bool $reload
  115. */
  116. function useredit_load_preferences(&$user, $reload=true) {
  117. global $USER;
  118. if (!empty($user->id)) {
  119. if ($reload and $USER->id == $user->id) {
  120. // Reload preferences in case it was changed in other session.
  121. unset($USER->preference);
  122. }
  123. if ($preferences = get_user_preferences(null, null, $user->id)) {
  124. foreach ($preferences as $name => $value) {
  125. $user->{'preference_'.$name} = $value;
  126. }
  127. }
  128. }
  129. }
  130. /**
  131. * Updates the user preferences for the given user
  132. *
  133. * Only preference that can be updated directly will be updated here. This method is called from various WS
  134. * updating users and should be used when updating user details. Plugins may list preferences that can
  135. * be updated by defining 'user_preferences' callback, {@see core_user::fill_preferences_cache()}
  136. *
  137. * Some parts of code may use user preference table to store internal data, in these cases it is acceptable
  138. * to call set_user_preference()
  139. *
  140. * @param stdClass|array $usernew object or array that has user preferences as attributes with keys starting with preference_
  141. */
  142. function useredit_update_user_preference($usernew) {
  143. global $USER;
  144. $ua = (array)$usernew;
  145. if (is_object($usernew) && isset($usernew->id) && isset($usernew->deleted) && isset($usernew->confirmed)) {
  146. // This is already a full user object, maybe not completely full but these fields are enough.
  147. $user = $usernew;
  148. } else if (empty($ua['id']) || $ua['id'] == $USER->id) {
  149. // We are updating current user.
  150. $user = $USER;
  151. } else {
  152. // Retrieve user object.
  153. $user = core_user::get_user($ua['id'], '*', MUST_EXIST);
  154. }
  155. foreach ($ua as $key => $value) {
  156. if (strpos($key, 'preference_') === 0) {
  157. $name = substr($key, strlen('preference_'));
  158. if (core_user::can_edit_preference($name, $user)) {
  159. $value = core_user::clean_preference($value, $name);
  160. set_user_preference($name, $value, $user->id);
  161. }
  162. }
  163. }
  164. }
  165. /**
  166. * @deprecated since Moodle 3.2
  167. * @see core_user::update_picture()
  168. */
  169. function useredit_update_picture() {
  170. throw new coding_exception('useredit_update_picture() can not be used anymore. Please use ' .
  171. 'core_user::update_picture() instead.');
  172. }
  173. /**
  174. * Updates the user email bounce + send counts when the user is edited.
  175. *
  176. * @param stdClass $user The current user object.
  177. * @param stdClass $usernew The updated user object.
  178. */
  179. function useredit_update_bounces($user, $usernew) {
  180. if (!isset($usernew->email)) {
  181. // Locked field.
  182. return;
  183. }
  184. if (!isset($user->email) || $user->email !== $usernew->email) {
  185. set_bounce_count($usernew, true);
  186. set_send_count($usernew, true);
  187. }
  188. }
  189. /**
  190. * Updates the forums a user is tracking when the user is edited.
  191. *
  192. * @param stdClass $user The original user object.
  193. * @param stdClass $usernew The updated user object.
  194. */
  195. function useredit_update_trackforums($user, $usernew) {
  196. global $CFG;
  197. if (!isset($usernew->trackforums)) {
  198. // Locked field.
  199. return;
  200. }
  201. if ((!isset($user->trackforums) || ($usernew->trackforums != $user->trackforums)) and !$usernew->trackforums) {
  202. require_once($CFG->dirroot.'/mod/forum/lib.php');
  203. forum_tp_delete_read_records($usernew->id);
  204. }
  205. }
  206. /**
  207. * Updates a users interests.
  208. *
  209. * @param stdClass $user
  210. * @param array $interests
  211. */
  212. function useredit_update_interests($user, $interests) {
  213. core_tag_tag::set_item_tags('core', 'user', $user->id,
  214. context_user::instance($user->id), $interests);
  215. }
  216. /**
  217. * Powerful function that is used by edit and editadvanced to add common form elements/rules/etc.
  218. *
  219. * @param moodleform $mform
  220. * @param array $editoroptions
  221. * @param array $filemanageroptions
  222. * @param stdClass $user
  223. */
  224. function useredit_shared_definition(&$mform, $editoroptions, $filemanageroptions, $user) {
  225. global $CFG, $USER, $DB;
  226. if ($user->id > 0) {
  227. useredit_load_preferences($user, false);
  228. }
  229. $strrequired = get_string('required');
  230. $stringman = get_string_manager();
  231. // Add the necessary names.
  232. foreach (useredit_get_required_name_fields() as $fullname) {
  233. $purpose = user_edit_map_field_purpose($user->id, $fullname);
  234. $mform->addElement('text', $fullname, get_string($fullname), 'maxlength="100" size="30"' . $purpose);
  235. if ($stringman->string_exists('missing'.$fullname, 'core')) {
  236. $strmissingfield = get_string('missing'.$fullname, 'core');
  237. } else {
  238. $strmissingfield = $strrequired;
  239. }
  240. $mform->addRule($fullname, $strmissingfield, 'required', null, 'client');
  241. $mform->setType($fullname, PARAM_NOTAGS);
  242. }
  243. $enabledusernamefields = useredit_get_enabled_name_fields();
  244. // Add the enabled additional name fields.
  245. foreach ($enabledusernamefields as $addname) {
  246. $purpose = user_edit_map_field_purpose($user->id, $addname);
  247. $mform->addElement('text', $addname, get_string($addname), 'maxlength="100" size="30"' . $purpose);
  248. $mform->setType($addname, PARAM_NOTAGS);
  249. }
  250. // Do not show email field if change confirmation is pending.
  251. if ($user->id > 0 and !empty($CFG->emailchangeconfirmation) and !empty($user->preference_newemail)) {
  252. $notice = get_string('emailchangepending', 'auth', $user);
  253. $notice .= '<br /><a href="edit.php?cancelemailchange=1&amp;id='.$user->id.'">'
  254. . get_string('emailchangecancel', 'auth') . '</a>';
  255. $mform->addElement('static', 'emailpending', get_string('email'), $notice);
  256. } else {
  257. $purpose = user_edit_map_field_purpose($user->id, 'email');
  258. $mform->addElement('text', 'email', get_string('email'), 'maxlength="100" size="30"' . $purpose);
  259. $mform->addRule('email', $strrequired, 'required', null, 'client');
  260. $mform->setType('email', PARAM_RAW_TRIMMED);
  261. }
  262. $choices = array();
  263. $choices['0'] = get_string('emaildisplayno');
  264. $choices['1'] = get_string('emaildisplayyes');
  265. $choices['2'] = get_string('emaildisplaycourse');
  266. $mform->addElement('select', 'maildisplay', get_string('emaildisplay'), $choices);
  267. $mform->setDefault('maildisplay', core_user::get_property_default('maildisplay'));
  268. $mform->addHelpButton('maildisplay', 'emaildisplay');
  269. $mform->addElement('text', 'moodlenetprofile', get_string('moodlenetprofile', 'user'));
  270. $mform->setType('moodlenetprofile', PARAM_NOTAGS);
  271. $mform->addHelpButton('moodlenetprofile', 'moodlenetprofile', 'user');
  272. $mform->addElement('text', 'city', get_string('city'), 'maxlength="120" size="21"');
  273. $mform->setType('city', PARAM_TEXT);
  274. if (!empty($CFG->defaultcity)) {
  275. $mform->setDefault('city', $CFG->defaultcity);
  276. }
  277. $purpose = user_edit_map_field_purpose($user->id, 'country');
  278. $choices = get_string_manager()->get_list_of_countries();
  279. $choices = array('' => get_string('selectacountry') . '...') + $choices;
  280. $mform->addElement('select', 'country', get_string('selectacountry'), $choices, $purpose);
  281. if (!empty($CFG->country)) {
  282. $mform->setDefault('country', core_user::get_property_default('country'));
  283. }
  284. if (isset($CFG->forcetimezone) and $CFG->forcetimezone != 99) {
  285. $choices = core_date::get_list_of_timezones($CFG->forcetimezone);
  286. $mform->addElement('static', 'forcedtimezone', get_string('timezone'), $choices[$CFG->forcetimezone]);
  287. $mform->addElement('hidden', 'timezone');
  288. $mform->setType('timezone', core_user::get_property_type('timezone'));
  289. } else {
  290. $choices = core_date::get_list_of_timezones($user->timezone, true);
  291. $mform->addElement('select', 'timezone', get_string('timezone'), $choices);
  292. }
  293. if ($user->id < 0) {
  294. $purpose = user_edit_map_field_purpose($user->id, 'lang');
  295. $translations = get_string_manager()->get_list_of_translations();
  296. $mform->addElement('select', 'lang', get_string('preferredlanguage'), $translations, $purpose);
  297. $lang = empty($user->lang) ? $CFG->lang : $user->lang;
  298. $mform->setDefault('lang', $lang);
  299. }
  300. if (!empty($CFG->allowuserthemes)) {
  301. $choices = array();
  302. $choices[''] = get_string('default');
  303. $themes = get_list_of_themes();
  304. foreach ($themes as $key => $theme) {
  305. if (empty($theme->hidefromselector)) {
  306. $choices[$key] = get_string('pluginname', 'theme_'.$theme->name);
  307. }
  308. }
  309. $mform->addElement('select', 'theme', get_string('preferredtheme'), $choices);
  310. }
  311. $mform->addElement('editor', 'description_editor', get_string('userdescription'), null, $editoroptions);
  312. $mform->setType('description_editor', PARAM_RAW);
  313. $mform->addHelpButton('description_editor', 'userdescription');
  314. if (empty($USER->newadminuser)) {
  315. $mform->addElement('header', 'moodle_picture', get_string('pictureofuser'));
  316. $mform->setExpanded('moodle_picture', true);
  317. if (!empty($CFG->enablegravatar)) {
  318. $mform->addElement('html', html_writer::tag('p', get_string('gravatarenabled')));
  319. }
  320. $mform->addElement('static', 'currentpicture', get_string('currentpicture'));
  321. $mform->addElement('checkbox', 'deletepicture', get_string('deletepicture'));
  322. $mform->setDefault('deletepicture', 0);
  323. $mform->addElement('filemanager', 'imagefile', get_string('newpicture'), '', $filemanageroptions);
  324. $mform->addHelpButton('imagefile', 'newpicture');
  325. $mform->addElement('text', 'imagealt', get_string('imagealt'), 'maxlength="100" size="30"');
  326. $mform->setType('imagealt', PARAM_TEXT);
  327. }
  328. // Display user name fields that are not currenlty enabled here if there are any.
  329. $disabledusernamefields = useredit_get_disabled_name_fields($enabledusernamefields);
  330. if (count($disabledusernamefields) > 0) {
  331. $mform->addElement('header', 'moodle_additional_names', get_string('additionalnames'));
  332. foreach ($disabledusernamefields as $allname) {
  333. $purpose = user_edit_map_field_purpose($user->id, $allname);
  334. $mform->addElement('text', $allname, get_string($allname), 'maxlength="100" size="30"' . $purpose);
  335. $mform->setType($allname, PARAM_NOTAGS);
  336. }
  337. }
  338. if (core_tag_tag::is_enabled('core', 'user') and empty($USER->newadminuser)) {
  339. $mform->addElement('header', 'moodle_interests', get_string('interests'));
  340. $mform->addElement('tags', 'interests', get_string('interestslist'),
  341. array('itemtype' => 'user', 'component' => 'core'));
  342. $mform->addHelpButton('interests', 'interestslist');
  343. }
  344. // Moodle optional fields.
  345. $mform->addElement('header', 'moodle_optional', get_string('optional', 'form'));
  346. $mform->addElement('text', 'idnumber', get_string('idnumber'), 'maxlength="255" size="25"');
  347. $mform->setType('idnumber', core_user::get_property_type('idnumber'));
  348. $mform->addElement('text', 'institution', get_string('institution'), 'maxlength="255" size="25"');
  349. $mform->setType('institution', core_user::get_property_type('institution'));
  350. $mform->addElement('text', 'department', get_string('department'), 'maxlength="255" size="25"');
  351. $mform->setType('department', core_user::get_property_type('department'));
  352. $mform->addElement('text', 'phone1', get_string('phone1'), 'maxlength="20" size="25"');
  353. $mform->setType('phone1', core_user::get_property_type('phone1'));
  354. $mform->setForceLtr('phone1');
  355. $mform->addElement('text', 'phone2', get_string('phone2'), 'maxlength="20" size="25"');
  356. $mform->setType('phone2', core_user::get_property_type('phone2'));
  357. $mform->setForceLtr('phone2');
  358. $mform->addElement('text', 'address', get_string('address'), 'maxlength="255" size="25"');
  359. $mform->setType('address', core_user::get_property_type('address'));
  360. }
  361. /**
  362. * Return required user name fields for forms.
  363. *
  364. * @return array required user name fields in order according to settings.
  365. */
  366. function useredit_get_required_name_fields() {
  367. global $CFG;
  368. // Get the name display format.
  369. $nameformat = $CFG->fullnamedisplay;
  370. // Names that are required fields on user forms.
  371. $necessarynames = array('firstname', 'lastname', 'middlename');
  372. $languageformat = get_string('fullnamedisplay');
  373. // Check that the language string and the $nameformat contain the necessary names.
  374. foreach ($necessarynames as $necessaryname) {
  375. $pattern = "/$necessaryname\b/";
  376. if (!preg_match($pattern, $languageformat)) {
  377. // If the language string has been altered then fall back on the below order.
  378. $languageformat = 'firstname lastname middlename';
  379. }
  380. if (!preg_match($pattern, $nameformat)) {
  381. // If the nameformat doesn't contain the necessary name fields then use the languageformat.
  382. $nameformat = $languageformat;
  383. }
  384. }
  385. // Order all of the name fields in the postion they are written in the fullnamedisplay setting.
  386. $necessarynames = order_in_string($necessarynames, $nameformat);
  387. return $necessarynames;
  388. }
  389. /**
  390. * Gets enabled (from fullnameformate setting) user name fields in appropriate order.
  391. *
  392. * @return array Enabled user name fields.
  393. */
  394. function useredit_get_enabled_name_fields() {
  395. global $CFG;
  396. // Get all of the other name fields which are not ranked as necessary.
  397. $additionalusernamefields = array_diff(\core_user\fields::get_name_fields(), array('firstname', 'lastname', 'middlename'));
  398. // Find out which additional name fields are actually being used from the fullnamedisplay setting.
  399. $enabledadditionalusernames = array();
  400. foreach ($additionalusernamefields as $enabledname) {
  401. if (strpos($CFG->fullnamedisplay, $enabledname) !== false) {
  402. $enabledadditionalusernames[] = $enabledname;
  403. }
  404. }
  405. // Order all of the name fields in the postion they are written in the fullnamedisplay setting.
  406. $enabledadditionalusernames = order_in_string($enabledadditionalusernames, $CFG->fullnamedisplay);
  407. return $enabledadditionalusernames;
  408. }
  409. /**
  410. * Gets user name fields not enabled from the setting fullnamedisplay.
  411. *
  412. * @param array $enabledadditionalusernames Current enabled additional user name fields.
  413. * @return array Disabled user name fields.
  414. */
  415. function useredit_get_disabled_name_fields($enabledadditionalusernames = null) {
  416. // If we don't have enabled additional user name information then go and fetch it (try to avoid).
  417. if (!isset($enabledadditionalusernames)) {
  418. $enabledadditionalusernames = useredit_get_enabled_name_fields();
  419. }
  420. // These are the additional fields that are not currently enabled.
  421. $nonusednamefields = array_diff(\core_user\fields::get_name_fields(),
  422. array_merge(array('firstname', 'lastname', 'middlename'), $enabledadditionalusernames));
  423. // It may not be significant anywhere, but for compatibility, this used to return an array
  424. // with keys and values the same.
  425. $result = [];
  426. foreach ($nonusednamefields as $field) {
  427. $result[$field] = $field;
  428. }
  429. return $result;
  430. }