lib.php 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185
  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. * External user API
  18. *
  19. * @package core_user
  20. * @copyright 2009 Moodle Pty Ltd (http://moodle.com)
  21. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  22. */
  23. /**
  24. * Creates a user
  25. *
  26. * @throws moodle_exception
  27. * @param stdClass $user user to create
  28. * @param bool $updatepassword if true, authentication plugin will update password.
  29. * @param bool $triggerevent set false if user_created event should not be triggred.
  30. * This will not affect user_password_updated event triggering.
  31. * @return int id of the newly created user
  32. */
  33. function user_create_user($user, $updatepassword = true, $triggerevent = true) {
  34. global $DB;
  35. // Set the timecreate field to the current time.
  36. if (!is_object($user)) {
  37. $user = (object) $user;
  38. }
  39. // Check username.
  40. if ($user->username !== core_text::strtolower($user->username)) {
  41. throw new moodle_exception('usernamelowercase');
  42. } else {
  43. if ($user->username !== core_user::clean_field($user->username, 'username')) {
  44. throw new moodle_exception('invalidusername');
  45. }
  46. }
  47. // Save the password in a temp value for later.
  48. if ($updatepassword && isset($user->password)) {
  49. // Check password toward the password policy.
  50. if (!check_password_policy($user->password, $errmsg)) {
  51. throw new moodle_exception($errmsg);
  52. }
  53. $userpassword = $user->password;
  54. unset($user->password);
  55. }
  56. // Apply default values for user preferences that are stored in users table.
  57. if (!isset($user->calendartype)) {
  58. $user->calendartype = core_user::get_property_default('calendartype');
  59. }
  60. if (!isset($user->maildisplay)) {
  61. $user->maildisplay = core_user::get_property_default('maildisplay');
  62. }
  63. if (!isset($user->mailformat)) {
  64. $user->mailformat = core_user::get_property_default('mailformat');
  65. }
  66. if (!isset($user->maildigest)) {
  67. $user->maildigest = core_user::get_property_default('maildigest');
  68. }
  69. if (!isset($user->autosubscribe)) {
  70. $user->autosubscribe = core_user::get_property_default('autosubscribe');
  71. }
  72. if (!isset($user->trackforums)) {
  73. $user->trackforums = core_user::get_property_default('trackforums');
  74. }
  75. if (!isset($user->lang)) {
  76. $user->lang = core_user::get_property_default('lang');
  77. }
  78. $user->timecreated = time();
  79. $user->timemodified = $user->timecreated;
  80. // Validate user data object.
  81. $uservalidation = core_user::validate($user);
  82. if ($uservalidation !== true) {
  83. foreach ($uservalidation as $field => $message) {
  84. debugging("The property '$field' has invalid data and has been cleaned.", DEBUG_DEVELOPER);
  85. $user->$field = core_user::clean_field($user->$field, $field);
  86. }
  87. }
  88. // Insert the user into the database.
  89. $newuserid = $DB->insert_record('user', $user);
  90. // Create USER context for this user.
  91. $usercontext = context_user::instance($newuserid);
  92. // Update user password if necessary.
  93. if (isset($userpassword)) {
  94. // Get full database user row, in case auth is default.
  95. $newuser = $DB->get_record('user', array('id' => $newuserid));
  96. $authplugin = get_auth_plugin($newuser->auth);
  97. $authplugin->user_update_password($newuser, $userpassword);
  98. }
  99. // Trigger event If required.
  100. if ($triggerevent) {
  101. \core\event\user_created::create_from_userid($newuserid)->trigger();
  102. }
  103. return $newuserid;
  104. }
  105. /**
  106. * Update a user with a user object (will compare against the ID)
  107. *
  108. * @throws moodle_exception
  109. * @param stdClass $user the user to update
  110. * @param bool $updatepassword if true, authentication plugin will update password.
  111. * @param bool $triggerevent set false if user_updated event should not be triggred.
  112. * This will not affect user_password_updated event triggering.
  113. */
  114. function user_update_user($user, $updatepassword = true, $triggerevent = true) {
  115. global $DB;
  116. // Set the timecreate field to the current time.
  117. if (!is_object($user)) {
  118. $user = (object) $user;
  119. }
  120. // Check username.
  121. if (isset($user->username)) {
  122. if ($user->username !== core_text::strtolower($user->username)) {
  123. throw new moodle_exception('usernamelowercase');
  124. } else {
  125. if ($user->username !== core_user::clean_field($user->username, 'username')) {
  126. throw new moodle_exception('invalidusername');
  127. }
  128. }
  129. }
  130. // Unset password here, for updating later, if password update is required.
  131. if ($updatepassword && isset($user->password)) {
  132. // Check password toward the password policy.
  133. if (!check_password_policy($user->password, $errmsg)) {
  134. throw new moodle_exception($errmsg);
  135. }
  136. $passwd = $user->password;
  137. unset($user->password);
  138. }
  139. // Make sure calendartype, if set, is valid.
  140. if (empty($user->calendartype)) {
  141. // Unset this variable, must be an empty string, which we do not want to update the calendartype to.
  142. unset($user->calendartype);
  143. }
  144. $user->timemodified = time();
  145. // Validate user data object.
  146. $uservalidation = core_user::validate($user);
  147. if ($uservalidation !== true) {
  148. foreach ($uservalidation as $field => $message) {
  149. debugging("The property '$field' has invalid data and has been cleaned.", DEBUG_DEVELOPER);
  150. $user->$field = core_user::clean_field($user->$field, $field);
  151. }
  152. }
  153. $DB->update_record('user', $user);
  154. if ($updatepassword) {
  155. // Get full user record.
  156. $updateduser = $DB->get_record('user', array('id' => $user->id));
  157. // If password was set, then update its hash.
  158. if (isset($passwd)) {
  159. $authplugin = get_auth_plugin($updateduser->auth);
  160. if ($authplugin->can_change_password()) {
  161. $authplugin->user_update_password($updateduser, $passwd);
  162. }
  163. }
  164. }
  165. // Trigger event if required.
  166. if ($triggerevent) {
  167. \core\event\user_updated::create_from_userid($user->id)->trigger();
  168. }
  169. }
  170. /**
  171. * Marks user deleted in internal user database and notifies the auth plugin.
  172. * Also unenrols user from all roles and does other cleanup.
  173. *
  174. * @todo Decide if this transaction is really needed (look for internal TODO:)
  175. * @param object $user Userobject before delete (without system magic quotes)
  176. * @return boolean success
  177. */
  178. function user_delete_user($user) {
  179. return delete_user($user);
  180. }
  181. /**
  182. * Get users by id
  183. *
  184. * @param array $userids id of users to retrieve
  185. * @return array
  186. */
  187. function user_get_users_by_id($userids) {
  188. global $DB;
  189. return $DB->get_records_list('user', 'id', $userids);
  190. }
  191. /**
  192. * Returns the list of default 'displayable' fields
  193. *
  194. * Contains database field names but also names used to generate information, such as enrolledcourses
  195. *
  196. * @return array of user fields
  197. */
  198. function user_get_default_fields() {
  199. return array( 'id', 'username', 'fullname', 'firstname', 'lastname', 'email',
  200. 'address', 'phone1', 'phone2', 'icq', 'skype', 'yahoo', 'aim', 'msn', 'department',
  201. 'institution', 'interests', 'firstaccess', 'lastaccess', 'auth', 'confirmed',
  202. 'idnumber', 'lang', 'theme', 'timezone', 'mailformat', 'description', 'descriptionformat',
  203. 'city', 'url', 'country', 'profileimageurlsmall', 'profileimageurl', 'customfields',
  204. 'groups', 'roles', 'preferences', 'enrolledcourses'
  205. );
  206. }
  207. /**
  208. *
  209. * Give user record from mdl_user, build an array contains all user details.
  210. *
  211. * Warning: description file urls are 'webservice/pluginfile.php' is use.
  212. * it can be changed with $CFG->moodlewstextformatlinkstoimagesfile
  213. *
  214. * @throws moodle_exception
  215. * @param stdClass $user user record from mdl_user
  216. * @param stdClass $course moodle course
  217. * @param array $userfields required fields
  218. * @return array|null
  219. */
  220. function user_get_user_details($user, $course = null, array $userfields = array()) {
  221. global $USER, $DB, $CFG, $PAGE;
  222. require_once($CFG->dirroot . "/user/profile/lib.php"); // Custom field library.
  223. require_once($CFG->dirroot . "/lib/filelib.php"); // File handling on description and friends.
  224. $defaultfields = user_get_default_fields();
  225. if (empty($userfields)) {
  226. $userfields = $defaultfields;
  227. }
  228. foreach ($userfields as $thefield) {
  229. if (!in_array($thefield, $defaultfields)) {
  230. throw new moodle_exception('invaliduserfield', 'error', '', $thefield);
  231. }
  232. }
  233. // Make sure id and fullname are included.
  234. if (!in_array('id', $userfields)) {
  235. $userfields[] = 'id';
  236. }
  237. if (!in_array('fullname', $userfields)) {
  238. $userfields[] = 'fullname';
  239. }
  240. if (!empty($course)) {
  241. $context = context_course::instance($course->id);
  242. $usercontext = context_user::instance($user->id);
  243. $canviewdetailscap = (has_capability('moodle/user:viewdetails', $context) || has_capability('moodle/user:viewdetails', $usercontext));
  244. } else {
  245. $context = context_user::instance($user->id);
  246. $usercontext = $context;
  247. $canviewdetailscap = has_capability('moodle/user:viewdetails', $usercontext);
  248. }
  249. $currentuser = ($user->id == $USER->id);
  250. $isadmin = is_siteadmin($USER);
  251. $showuseridentityfields = get_extra_user_fields($context);
  252. if (!empty($course)) {
  253. $canviewhiddenuserfields = has_capability('moodle/course:viewhiddenuserfields', $context);
  254. } else {
  255. $canviewhiddenuserfields = has_capability('moodle/user:viewhiddendetails', $context);
  256. }
  257. $canviewfullnames = has_capability('moodle/site:viewfullnames', $context);
  258. if (!empty($course)) {
  259. $canviewuseremail = has_capability('moodle/course:useremail', $context);
  260. } else {
  261. $canviewuseremail = false;
  262. }
  263. $cannotviewdescription = !empty($CFG->profilesforenrolledusersonly) && !$currentuser && !$DB->record_exists('role_assignments', array('userid' => $user->id));
  264. if (!empty($course)) {
  265. $canaccessallgroups = has_capability('moodle/site:accessallgroups', $context);
  266. } else {
  267. $canaccessallgroups = false;
  268. }
  269. if (!$currentuser && !$canviewdetailscap && !has_coursecontact_role($user->id)) {
  270. // Skip this user details.
  271. return null;
  272. }
  273. $userdetails = array();
  274. $userdetails['id'] = $user->id;
  275. if (in_array('username', $userfields)) {
  276. if ($currentuser or has_capability('moodle/user:viewalldetails', $context)) {
  277. $userdetails['username'] = $user->username;
  278. }
  279. }
  280. if ($isadmin or $canviewfullnames) {
  281. if (in_array('firstname', $userfields)) {
  282. $userdetails['firstname'] = $user->firstname;
  283. }
  284. if (in_array('lastname', $userfields)) {
  285. $userdetails['lastname'] = $user->lastname;
  286. }
  287. }
  288. $userdetails['fullname'] = fullname($user);
  289. if (in_array('customfields', $userfields)) {
  290. $fields = $DB->get_recordset_sql("SELECT f.*
  291. FROM {user_info_field} f
  292. JOIN {user_info_category} c
  293. ON f.categoryid=c.id
  294. ORDER BY c.sortorder ASC, f.sortorder ASC");
  295. $userdetails['customfields'] = array();
  296. foreach ($fields as $field) {
  297. require_once($CFG->dirroot.'/user/profile/field/'.$field->datatype.'/field.class.php');
  298. $newfield = 'profile_field_'.$field->datatype;
  299. $formfield = new $newfield($field->id, $user->id);
  300. if ($formfield->is_visible() and !$formfield->is_empty()) {
  301. // TODO: Part of MDL-50728, this conditional coding must be moved to
  302. // proper profile fields API so they are self-contained.
  303. // We only use display_data in fields that require text formatting.
  304. if ($field->datatype == 'text' or $field->datatype == 'textarea') {
  305. $fieldvalue = $formfield->display_data();
  306. } else {
  307. // Cases: datetime, checkbox and menu.
  308. $fieldvalue = $formfield->data;
  309. }
  310. $userdetails['customfields'][] =
  311. array('name' => $formfield->field->name, 'value' => $fieldvalue,
  312. 'type' => $field->datatype, 'shortname' => $formfield->field->shortname);
  313. }
  314. }
  315. $fields->close();
  316. // Unset customfields if it's empty.
  317. if (empty($userdetails['customfields'])) {
  318. unset($userdetails['customfields']);
  319. }
  320. }
  321. // Profile image.
  322. if (in_array('profileimageurl', $userfields)) {
  323. $userpicture = new user_picture($user);
  324. $userpicture->size = 1; // Size f1.
  325. $userdetails['profileimageurl'] = $userpicture->get_url($PAGE)->out(false);
  326. }
  327. if (in_array('profileimageurlsmall', $userfields)) {
  328. if (!isset($userpicture)) {
  329. $userpicture = new user_picture($user);
  330. }
  331. $userpicture->size = 0; // Size f2.
  332. $userdetails['profileimageurlsmall'] = $userpicture->get_url($PAGE)->out(false);
  333. }
  334. // Hidden user field.
  335. if ($canviewhiddenuserfields) {
  336. $hiddenfields = array();
  337. // Address, phone1 and phone2 not appears in hidden fields list but require viewhiddenfields capability
  338. // according to user/profile.php.
  339. if ($user->address && in_array('address', $userfields)) {
  340. $userdetails['address'] = $user->address;
  341. }
  342. } else {
  343. $hiddenfields = array_flip(explode(',', $CFG->hiddenuserfields));
  344. }
  345. if ($user->phone1 && in_array('phone1', $userfields) &&
  346. (in_array('phone1', $showuseridentityfields) or $canviewhiddenuserfields)) {
  347. $userdetails['phone1'] = $user->phone1;
  348. }
  349. if ($user->phone2 && in_array('phone2', $userfields) &&
  350. (in_array('phone2', $showuseridentityfields) or $canviewhiddenuserfields)) {
  351. $userdetails['phone2'] = $user->phone2;
  352. }
  353. if (isset($user->description) &&
  354. ((!isset($hiddenfields['description']) && !$cannotviewdescription) or $isadmin)) {
  355. if (in_array('description', $userfields)) {
  356. // Always return the descriptionformat if description is requested.
  357. list($userdetails['description'], $userdetails['descriptionformat']) =
  358. external_format_text($user->description, $user->descriptionformat,
  359. $usercontext->id, 'user', 'profile', null);
  360. }
  361. }
  362. if (in_array('country', $userfields) && (!isset($hiddenfields['country']) or $isadmin) && $user->country) {
  363. $userdetails['country'] = $user->country;
  364. }
  365. if (in_array('city', $userfields) && (!isset($hiddenfields['city']) or $isadmin) && $user->city) {
  366. $userdetails['city'] = $user->city;
  367. }
  368. if (in_array('url', $userfields) && $user->url && (!isset($hiddenfields['webpage']) or $isadmin)) {
  369. $url = $user->url;
  370. if (strpos($user->url, '://') === false) {
  371. $url = 'http://'. $url;
  372. }
  373. $user->url = clean_param($user->url, PARAM_URL);
  374. $userdetails['url'] = $user->url;
  375. }
  376. if (in_array('icq', $userfields) && $user->icq && (!isset($hiddenfields['icqnumber']) or $isadmin)) {
  377. $userdetails['icq'] = $user->icq;
  378. }
  379. if (in_array('skype', $userfields) && $user->skype && (!isset($hiddenfields['skypeid']) or $isadmin)) {
  380. $userdetails['skype'] = $user->skype;
  381. }
  382. if (in_array('yahoo', $userfields) && $user->yahoo && (!isset($hiddenfields['yahooid']) or $isadmin)) {
  383. $userdetails['yahoo'] = $user->yahoo;
  384. }
  385. if (in_array('aim', $userfields) && $user->aim && (!isset($hiddenfields['aimid']) or $isadmin)) {
  386. $userdetails['aim'] = $user->aim;
  387. }
  388. if (in_array('msn', $userfields) && $user->msn && (!isset($hiddenfields['msnid']) or $isadmin)) {
  389. $userdetails['msn'] = $user->msn;
  390. }
  391. if (in_array('firstaccess', $userfields) && (!isset($hiddenfields['firstaccess']) or $isadmin)) {
  392. if ($user->firstaccess) {
  393. $userdetails['firstaccess'] = $user->firstaccess;
  394. } else {
  395. $userdetails['firstaccess'] = 0;
  396. }
  397. }
  398. if (in_array('lastaccess', $userfields) && (!isset($hiddenfields['lastaccess']) or $isadmin)) {
  399. if ($user->lastaccess) {
  400. $userdetails['lastaccess'] = $user->lastaccess;
  401. } else {
  402. $userdetails['lastaccess'] = 0;
  403. }
  404. }
  405. if (in_array('email', $userfields) && ($isadmin // The admin is allowed the users email.
  406. or $currentuser // Of course the current user is as well.
  407. or $canviewuseremail // This is a capability in course context, it will be false in usercontext.
  408. or in_array('email', $showuseridentityfields)
  409. or $user->maildisplay == 1
  410. or ($user->maildisplay == 2 and enrol_sharing_course($user, $USER)))) {
  411. $userdetails['email'] = $user->email;
  412. }
  413. if (in_array('interests', $userfields)) {
  414. $interests = core_tag_tag::get_item_tags_array('core', 'user', $user->id, core_tag_tag::BOTH_STANDARD_AND_NOT, 0, false);
  415. if ($interests) {
  416. $userdetails['interests'] = join(', ', $interests);
  417. }
  418. }
  419. // Departement/Institution/Idnumber are not displayed on any profile, however you can get them from editing profile.
  420. if (in_array('idnumber', $userfields) && $user->idnumber) {
  421. if (in_array('idnumber', $showuseridentityfields) or $currentuser or
  422. has_capability('moodle/user:viewalldetails', $context)) {
  423. $userdetails['idnumber'] = $user->idnumber;
  424. }
  425. }
  426. if (in_array('institution', $userfields) && $user->institution) {
  427. if (in_array('institution', $showuseridentityfields) or $currentuser or
  428. has_capability('moodle/user:viewalldetails', $context)) {
  429. $userdetails['institution'] = $user->institution;
  430. }
  431. }
  432. // Isset because it's ok to have department 0.
  433. if (in_array('department', $userfields) && isset($user->department)) {
  434. if (in_array('department', $showuseridentityfields) or $currentuser or
  435. has_capability('moodle/user:viewalldetails', $context)) {
  436. $userdetails['department'] = $user->department;
  437. }
  438. }
  439. if (in_array('roles', $userfields) && !empty($course)) {
  440. // Not a big secret.
  441. $roles = get_user_roles($context, $user->id, false);
  442. $userdetails['roles'] = array();
  443. foreach ($roles as $role) {
  444. $userdetails['roles'][] = array(
  445. 'roleid' => $role->roleid,
  446. 'name' => $role->name,
  447. 'shortname' => $role->shortname,
  448. 'sortorder' => $role->sortorder
  449. );
  450. }
  451. }
  452. // If groups are in use and enforced throughout the course, then make sure we can meet in at least one course level group.
  453. if (in_array('groups', $userfields) && !empty($course) && $canaccessallgroups) {
  454. $usergroups = groups_get_all_groups($course->id, $user->id, $course->defaultgroupingid,
  455. 'g.id, g.name,g.description,g.descriptionformat');
  456. $userdetails['groups'] = array();
  457. foreach ($usergroups as $group) {
  458. list($group->description, $group->descriptionformat) =
  459. external_format_text($group->description, $group->descriptionformat,
  460. $context->id, 'group', 'description', $group->id);
  461. $userdetails['groups'][] = array('id' => $group->id, 'name' => $group->name,
  462. 'description' => $group->description, 'descriptionformat' => $group->descriptionformat);
  463. }
  464. }
  465. // List of courses where the user is enrolled.
  466. if (in_array('enrolledcourses', $userfields) && !isset($hiddenfields['mycourses'])) {
  467. $enrolledcourses = array();
  468. if ($mycourses = enrol_get_users_courses($user->id, true)) {
  469. foreach ($mycourses as $mycourse) {
  470. if ($mycourse->category) {
  471. $coursecontext = context_course::instance($mycourse->id);
  472. $enrolledcourse = array();
  473. $enrolledcourse['id'] = $mycourse->id;
  474. $enrolledcourse['fullname'] = format_string($mycourse->fullname, true, array('context' => $coursecontext));
  475. $enrolledcourse['shortname'] = format_string($mycourse->shortname, true, array('context' => $coursecontext));
  476. $enrolledcourses[] = $enrolledcourse;
  477. }
  478. }
  479. $userdetails['enrolledcourses'] = $enrolledcourses;
  480. }
  481. }
  482. // User preferences.
  483. if (in_array('preferences', $userfields) && $currentuser) {
  484. $preferences = array();
  485. $userpreferences = get_user_preferences();
  486. foreach ($userpreferences as $prefname => $prefvalue) {
  487. $preferences[] = array('name' => $prefname, 'value' => $prefvalue);
  488. }
  489. $userdetails['preferences'] = $preferences;
  490. }
  491. return $userdetails;
  492. }
  493. /**
  494. * Tries to obtain user details, either recurring directly to the user's system profile
  495. * or through one of the user's course enrollments (course profile).
  496. *
  497. * @param stdClass $user The user.
  498. * @return array if unsuccessful or the allowed user details.
  499. */
  500. function user_get_user_details_courses($user) {
  501. global $USER;
  502. $userdetails = null;
  503. // Get the courses that the user is enrolled in (only active).
  504. $courses = enrol_get_users_courses($user->id, true);
  505. $systemprofile = false;
  506. if (can_view_user_details_cap($user) || ($user->id == $USER->id) || has_coursecontact_role($user->id)) {
  507. $systemprofile = true;
  508. }
  509. // Try using system profile.
  510. if ($systemprofile) {
  511. $userdetails = user_get_user_details($user, null);
  512. } else {
  513. // Try through course profile.
  514. foreach ($courses as $course) {
  515. if (can_view_user_details_cap($user, $course) || ($user->id == $USER->id) || has_coursecontact_role($user->id)) {
  516. $userdetails = user_get_user_details($user, $course);
  517. }
  518. }
  519. }
  520. return $userdetails;
  521. }
  522. /**
  523. * Check if $USER have the necessary capabilities to obtain user details.
  524. *
  525. * @param stdClass $user
  526. * @param stdClass $course if null then only consider system profile otherwise also consider the course's profile.
  527. * @return bool true if $USER can view user details.
  528. */
  529. function can_view_user_details_cap($user, $course = null) {
  530. // Check $USER has the capability to view the user details at user context.
  531. $usercontext = context_user::instance($user->id);
  532. $result = has_capability('moodle/user:viewdetails', $usercontext);
  533. // Otherwise can $USER see them at course context.
  534. if (!$result && !empty($course)) {
  535. $context = context_course::instance($course->id);
  536. $result = has_capability('moodle/user:viewdetails', $context);
  537. }
  538. return $result;
  539. }
  540. /**
  541. * Return a list of page types
  542. * @param string $pagetype current page type
  543. * @param stdClass $parentcontext Block's parent context
  544. * @param stdClass $currentcontext Current context of block
  545. * @return array
  546. */
  547. function user_page_type_list($pagetype, $parentcontext, $currentcontext) {
  548. return array('user-profile' => get_string('page-user-profile', 'pagetype'));
  549. }
  550. /**
  551. * Count the number of failed login attempts for the given user, since last successful login.
  552. *
  553. * @param int|stdclass $user user id or object.
  554. * @param bool $reset Resets failed login count, if set to true.
  555. *
  556. * @return int number of failed login attempts since the last successful login.
  557. */
  558. function user_count_login_failures($user, $reset = true) {
  559. global $DB;
  560. if (!is_object($user)) {
  561. $user = $DB->get_record('user', array('id' => $user), '*', MUST_EXIST);
  562. }
  563. if ($user->deleted) {
  564. // Deleted user, nothing to do.
  565. return 0;
  566. }
  567. $count = get_user_preferences('login_failed_count_since_success', 0, $user);
  568. if ($reset) {
  569. set_user_preference('login_failed_count_since_success', 0, $user);
  570. }
  571. return $count;
  572. }
  573. /**
  574. * Converts a string into a flat array of menu items, where each menu items is a
  575. * stdClass with fields type, url, title, pix, and imgsrc.
  576. *
  577. * @param string $text the menu items definition
  578. * @param moodle_page $page the current page
  579. * @return array
  580. */
  581. function user_convert_text_to_menu_items($text, $page) {
  582. global $OUTPUT, $CFG;
  583. $lines = explode("\n", $text);
  584. $items = array();
  585. $lastchild = null;
  586. $lastdepth = null;
  587. $lastsort = 0;
  588. $children = array();
  589. foreach ($lines as $line) {
  590. $line = trim($line);
  591. $bits = explode('|', $line, 3);
  592. $itemtype = 'link';
  593. if (preg_match("/^#+$/", $line)) {
  594. $itemtype = 'divider';
  595. } else if (!array_key_exists(0, $bits) or empty($bits[0])) {
  596. // Every item must have a name to be valid.
  597. continue;
  598. } else {
  599. $bits[0] = ltrim($bits[0], '-');
  600. }
  601. // Create the child.
  602. $child = new stdClass();
  603. $child->itemtype = $itemtype;
  604. if ($itemtype === 'divider') {
  605. // Add the divider to the list of children and skip link
  606. // processing.
  607. $children[] = $child;
  608. continue;
  609. }
  610. // Name processing.
  611. $namebits = explode(',', $bits[0], 2);
  612. if (count($namebits) == 2) {
  613. // Check the validity of the identifier part of the string.
  614. if (clean_param($namebits[0], PARAM_STRINGID) !== '') {
  615. // Treat this as a language string.
  616. $child->title = get_string($namebits[0], $namebits[1]);
  617. $child->titleidentifier = implode(',', $namebits);
  618. }
  619. }
  620. if (empty($child->title)) {
  621. // Use it as is, don't even clean it.
  622. $child->title = $bits[0];
  623. $child->titleidentifier = str_replace(" ", "-", $bits[0]);
  624. }
  625. // URL processing.
  626. if (!array_key_exists(1, $bits) or empty($bits[1])) {
  627. // Set the url to null, and set the itemtype to invalid.
  628. $bits[1] = null;
  629. $child->itemtype = "invalid";
  630. } else {
  631. // Nasty hack to replace the grades with the direct url.
  632. if (strpos($bits[1], '/grade/report/mygrades.php') !== false) {
  633. $bits[1] = user_mygrades_url();
  634. }
  635. // Make sure the url is a moodle url.
  636. $bits[1] = new moodle_url(trim($bits[1]));
  637. }
  638. $child->url = $bits[1];
  639. // PIX processing.
  640. $pixpath = "t/edit";
  641. if (!array_key_exists(2, $bits) or empty($bits[2])) {
  642. // Use the default.
  643. $child->pix = $pixpath;
  644. } else {
  645. // Check for the specified image existing.
  646. $pixpath = "t/" . $bits[2];
  647. if ($page->theme->resolve_image_location($pixpath, 'moodle', true)) {
  648. // Use the image.
  649. $child->pix = $pixpath;
  650. } else {
  651. // Treat it like a URL.
  652. $child->pix = null;
  653. $child->imgsrc = $bits[2];
  654. }
  655. }
  656. // Add this child to the list of children.
  657. $children[] = $child;
  658. }
  659. return $children;
  660. }
  661. /**
  662. * Get a list of essential user navigation items.
  663. *
  664. * @param stdclass $user user object.
  665. * @param moodle_page $page page object.
  666. * @param array $options associative array.
  667. * options are:
  668. * - avatarsize=35 (size of avatar image)
  669. * @return stdClass $returnobj navigation information object, where:
  670. *
  671. * $returnobj->navitems array array of links where each link is a
  672. * stdClass with fields url, title, and
  673. * pix
  674. * $returnobj->metadata array array of useful user metadata to be
  675. * used when constructing navigation;
  676. * fields include:
  677. *
  678. * ROLE FIELDS
  679. * asotherrole bool whether viewing as another role
  680. * rolename string name of the role
  681. *
  682. * USER FIELDS
  683. * These fields are for the currently-logged in user, or for
  684. * the user that the real user is currently logged in as.
  685. *
  686. * userid int the id of the user in question
  687. * userfullname string the user's full name
  688. * userprofileurl moodle_url the url of the user's profile
  689. * useravatar string a HTML fragment - the rendered
  690. * user_picture for this user
  691. * userloginfail string an error string denoting the number
  692. * of login failures since last login
  693. *
  694. * "REAL USER" FIELDS
  695. * These fields are for when asotheruser is true, and
  696. * correspond to the underlying "real user".
  697. *
  698. * asotheruser bool whether viewing as another user
  699. * realuserid int the id of the user in question
  700. * realuserfullname string the user's full name
  701. * realuserprofileurl moodle_url the url of the user's profile
  702. * realuseravatar string a HTML fragment - the rendered
  703. * user_picture for this user
  704. *
  705. * MNET PROVIDER FIELDS
  706. * asmnetuser bool whether viewing as a user from an
  707. * MNet provider
  708. * mnetidprovidername string name of the MNet provider
  709. * mnetidproviderwwwroot string URL of the MNet provider
  710. */
  711. function user_get_user_navigation_info($user, $page, $options = array()) {
  712. global $OUTPUT, $DB, $SESSION, $CFG;
  713. $returnobject = new stdClass();
  714. $returnobject->navitems = array();
  715. $returnobject->metadata = array();
  716. $course = $page->course;
  717. // Query the environment.
  718. $context = context_course::instance($course->id);
  719. // Get basic user metadata.
  720. $returnobject->metadata['userid'] = $user->id;
  721. $returnobject->metadata['userfullname'] = fullname($user, true);
  722. $returnobject->metadata['userprofileurl'] = new moodle_url('/user/profile.php', array(
  723. 'id' => $user->id
  724. ));
  725. $avataroptions = array('link' => false, 'visibletoscreenreaders' => false);
  726. if (!empty($options['avatarsize'])) {
  727. $avataroptions['size'] = $options['avatarsize'];
  728. }
  729. $returnobject->metadata['useravatar'] = $OUTPUT->user_picture (
  730. $user, $avataroptions
  731. );
  732. // Build a list of items for a regular user.
  733. // Query MNet status.
  734. if ($returnobject->metadata['asmnetuser'] = is_mnet_remote_user($user)) {
  735. $mnetidprovider = $DB->get_record('mnet_host', array('id' => $user->mnethostid));
  736. $returnobject->metadata['mnetidprovidername'] = $mnetidprovider->name;
  737. $returnobject->metadata['mnetidproviderwwwroot'] = $mnetidprovider->wwwroot;
  738. }
  739. // Did the user just log in?
  740. if (isset($SESSION->justloggedin)) {
  741. // Don't unset this flag as login_info still needs it.
  742. if (!empty($CFG->displayloginfailures)) {
  743. // We're already in /user/lib.php, so we don't need to include.
  744. if ($count = user_count_login_failures($user)) {
  745. // Get login failures string.
  746. $a = new stdClass();
  747. $a->attempts = html_writer::tag('span', $count, array('class' => 'value'));
  748. $returnobject->metadata['userloginfail'] =
  749. get_string('failedloginattempts', '', $a);
  750. }
  751. }
  752. }
  753. // Links: Dashboard.
  754. $myhome = new stdClass();
  755. $myhome->itemtype = 'link';
  756. $myhome->url = new moodle_url('/my/');
  757. $myhome->title = get_string('mymoodle', 'admin');
  758. $myhome->titleidentifier = 'mymoodle,admin';
  759. $myhome->pix = "i/course";
  760. $returnobject->navitems[] = $myhome;
  761. // Links: My Profile.
  762. $myprofile = new stdClass();
  763. $myprofile->itemtype = 'link';
  764. $myprofile->url = new moodle_url('/user/profile.php', array('id' => $user->id));
  765. $myprofile->title = get_string('profile');
  766. $myprofile->titleidentifier = 'profile,moodle';
  767. $myprofile->pix = "i/user";
  768. $returnobject->navitems[] = $myprofile;
  769. // Links: Role-return or logout link.
  770. $lastobj = null;
  771. $buildlogout = true;
  772. $returnobject->metadata['asotherrole'] = false;
  773. if (is_role_switched($course->id)) {
  774. if ($role = $DB->get_record('role', array('id' => $user->access['rsw'][$context->path]))) {
  775. // Build role-return link instead of logout link.
  776. $rolereturn = new stdClass();
  777. $rolereturn->itemtype = 'link';
  778. $rolereturn->url = new moodle_url('/course/switchrole.php', array(
  779. 'id' => $course->id,
  780. 'sesskey' => sesskey(),
  781. 'switchrole' => 0,
  782. 'returnurl' => $page->url->out_as_local_url(false)
  783. ));
  784. $rolereturn->pix = "a/logout";
  785. $rolereturn->title = get_string('switchrolereturn');
  786. $rolereturn->titleidentifier = 'switchrolereturn,moodle';
  787. $lastobj = $rolereturn;
  788. $returnobject->metadata['asotherrole'] = true;
  789. $returnobject->metadata['rolename'] = role_get_name($role, $context);
  790. $buildlogout = false;
  791. }
  792. }
  793. if ($returnobject->metadata['asotheruser'] = \core\session\manager::is_loggedinas()) {
  794. $realuser = \core\session\manager::get_realuser();
  795. // Save values for the real user, as $user will be full of data for the
  796. // user the user is disguised as.
  797. $returnobject->metadata['realuserid'] = $realuser->id;
  798. $returnobject->metadata['realuserfullname'] = fullname($realuser, true);
  799. $returnobject->metadata['realuserprofileurl'] = new moodle_url('/user/profile.php', array(
  800. 'id' => $realuser->id
  801. ));
  802. $returnobject->metadata['realuseravatar'] = $OUTPUT->user_picture($realuser, $avataroptions);
  803. // Build a user-revert link.
  804. $userrevert = new stdClass();
  805. $userrevert->itemtype = 'link';
  806. $userrevert->url = new moodle_url('/course/loginas.php', array(
  807. 'id' => $course->id,
  808. 'sesskey' => sesskey()
  809. ));
  810. $userrevert->pix = "a/logout";
  811. $userrevert->title = get_string('logout');
  812. $userrevert->titleidentifier = 'logout,moodle';
  813. $lastobj = $userrevert;
  814. $buildlogout = false;
  815. }
  816. if ($buildlogout) {
  817. // Build a logout link.
  818. $logout = new stdClass();
  819. $logout->itemtype = 'link';
  820. $logout->url = new moodle_url('/login/logout.php', array('sesskey' => sesskey()));
  821. $logout->pix = "a/logout";
  822. $logout->title = get_string('logout');
  823. $logout->titleidentifier = 'logout,moodle';
  824. $lastobj = $logout;
  825. }
  826. // Before we add the last item (usually a logout link), add any
  827. // custom-defined items.
  828. $customitems = user_convert_text_to_menu_items($CFG->customusermenuitems, $page);
  829. foreach ($customitems as $item) {
  830. $returnobject->navitems[] = $item;
  831. }
  832. // Add the last item to the list.
  833. if (!is_null($lastobj)) {
  834. $returnobject->navitems[] = $lastobj;
  835. }
  836. return $returnobject;
  837. }
  838. /**
  839. * Add password to the list of used hashes for this user.
  840. *
  841. * This is supposed to be used from:
  842. * 1/ change own password form
  843. * 2/ password reset process
  844. * 3/ user signup in auth plugins if password changing supported
  845. *
  846. * @param int $userid user id
  847. * @param string $password plaintext password
  848. * @return void
  849. */
  850. function user_add_password_history($userid, $password) {
  851. global $CFG, $DB;
  852. if (empty($CFG->passwordreuselimit) or $CFG->passwordreuselimit < 0) {
  853. return;
  854. }
  855. // Note: this is using separate code form normal password hashing because
  856. // we need to have this under control in the future. Also the auth
  857. // plugin might not store the passwords locally at all.
  858. $record = new stdClass();
  859. $record->userid = $userid;
  860. $record->hash = password_hash($password, PASSWORD_DEFAULT);
  861. $record->timecreated = time();
  862. $DB->insert_record('user_password_history', $record);
  863. $i = 0;
  864. $records = $DB->get_records('user_password_history', array('userid' => $userid), 'timecreated DESC, id DESC');
  865. foreach ($records as $record) {
  866. $i++;
  867. if ($i > $CFG->passwordreuselimit) {
  868. $DB->delete_records('user_password_history', array('id' => $record->id));
  869. }
  870. }
  871. }
  872. /**
  873. * Was this password used before on change or reset password page?
  874. *
  875. * The $CFG->passwordreuselimit setting determines
  876. * how many times different password needs to be used
  877. * before allowing previously used password again.
  878. *
  879. * @param int $userid user id
  880. * @param string $password plaintext password
  881. * @return bool true if password reused
  882. */
  883. function user_is_previously_used_password($userid, $password) {
  884. global $CFG, $DB;
  885. if (empty($CFG->passwordreuselimit) or $CFG->passwordreuselimit < 0) {
  886. return false;
  887. }
  888. $reused = false;
  889. $i = 0;
  890. $records = $DB->get_records('user_password_history', array('userid' => $userid), 'timecreated DESC, id DESC');
  891. foreach ($records as $record) {
  892. $i++;
  893. if ($i > $CFG->passwordreuselimit) {
  894. $DB->delete_records('user_password_history', array('id' => $record->id));
  895. continue;
  896. }
  897. // NOTE: this is slow but we cannot compare the hashes directly any more.
  898. if (password_verify($password, $record->hash)) {
  899. $reused = true;
  900. }
  901. }
  902. return $reused;
  903. }
  904. /**
  905. * Remove a user device from the Moodle database (for PUSH notifications usually).
  906. *
  907. * @param string $uuid The device UUID.
  908. * @param string $appid The app id. If empty all the devices matching the UUID for the user will be removed.
  909. * @return bool true if removed, false if the device didn't exists in the database
  910. * @since Moodle 2.9
  911. */
  912. function user_remove_user_device($uuid, $appid = "") {
  913. global $DB, $USER;
  914. $conditions = array('uuid' => $uuid, 'userid' => $USER->id);
  915. if (!empty($appid)) {
  916. $conditions['appid'] = $appid;
  917. }
  918. if (!$DB->count_records('user_devices', $conditions)) {
  919. return false;
  920. }
  921. $DB->delete_records('user_devices', $conditions);
  922. return true;
  923. }
  924. /**
  925. * Trigger user_list_viewed event.
  926. *
  927. * @param stdClass $course course object
  928. * @param stdClass $context course context object
  929. * @since Moodle 2.9
  930. */
  931. function user_list_view($course, $context) {
  932. $event = \core\event\user_list_viewed::create(array(
  933. 'objectid' => $course->id,
  934. 'courseid' => $course->id,
  935. 'context' => $context,
  936. 'other' => array(
  937. 'courseshortname' => $course->shortname,
  938. 'coursefullname' => $course->fullname
  939. )
  940. ));
  941. $event->trigger();
  942. }
  943. /**
  944. * Returns the url to use for the "Grades" link in the user navigation.
  945. *
  946. * @param int $userid The user's ID.
  947. * @param int $courseid The course ID if available.
  948. * @return mixed A URL to be directed to for "Grades".
  949. */
  950. function user_mygrades_url($userid = null, $courseid = SITEID) {
  951. global $CFG, $USER;
  952. $url = null;
  953. if (isset($CFG->grade_mygrades_report) && $CFG->grade_mygrades_report != 'external') {
  954. if (isset($userid) && $USER->id != $userid) {
  955. // Send to the gradebook report.
  956. $url = new moodle_url('/grade/report/' . $CFG->grade_mygrades_report . '/index.php',
  957. array('id' => $courseid, 'userid' => $userid));
  958. } else {
  959. $url = new moodle_url('/grade/report/' . $CFG->grade_mygrades_report . '/index.php');
  960. }
  961. } else if (isset($CFG->grade_mygrades_report) && $CFG->grade_mygrades_report == 'external'
  962. && !empty($CFG->gradereport_mygradeurl)) {
  963. $url = $CFG->gradereport_mygradeurl;
  964. } else {
  965. $url = $CFG->wwwroot;
  966. }
  967. return $url;
  968. }
  969. /**
  970. * Check if a user has the permission to viewdetails in a shared course's context.
  971. *
  972. * @param object $user The other user's details.
  973. * @param object $course Use this course to see if we have permission to see this user's profile.
  974. * @param context $usercontext The user context if available.
  975. * @return bool true for ability to view this user, else false.
  976. */
  977. function user_can_view_profile($user, $course = null, $usercontext = null) {
  978. global $USER, $CFG;
  979. if ($user->deleted) {
  980. return false;
  981. }
  982. // If any of these four things, return true.
  983. // Number 1.
  984. if ($USER->id == $user->id) {
  985. return true;
  986. }
  987. // Number 2.
  988. if (empty($CFG->forceloginforprofiles)) {
  989. return true;
  990. }
  991. if (empty($usercontext)) {
  992. $usercontext = context_user::instance($user->id);
  993. }
  994. // Number 3.
  995. if (has_capability('moodle/user:viewdetails', $usercontext)) {
  996. return true;
  997. }
  998. // Number 4.
  999. if (has_coursecontact_role($user->id)) {
  1000. return true;
  1001. }
  1002. if (isset($course)) {
  1003. $sharedcourses = array($course);
  1004. } else {
  1005. $sharedcourses = enrol_get_shared_courses($USER->id, $user->id, true);
  1006. }
  1007. foreach ($sharedcourses as $sharedcourse) {
  1008. $coursecontext = context_course::instance($sharedcourse->id);
  1009. if (has_capability('moodle/user:viewdetails', $coursecontext)) {
  1010. if (!groups_user_groups_visible($sharedcourse, $user->id)) {
  1011. // Not a member of the same group.
  1012. continue;
  1013. }
  1014. return true;
  1015. }
  1016. }
  1017. return false;
  1018. }
  1019. /**
  1020. * Returns users tagged with a specified tag.
  1021. *
  1022. * @param core_tag_tag $tag
  1023. * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
  1024. * are displayed on the page and the per-page limit may be bigger
  1025. * @param int $fromctx context id where the link was displayed, may be used by callbacks
  1026. * to display items in the same context first
  1027. * @param int $ctx context id where to search for records
  1028. * @param bool $rec search in subcontexts as well
  1029. * @param int $page 0-based number of page being displayed
  1030. * @return \core_tag\output\tagindex
  1031. */
  1032. function user_get_tagged_users($tag, $exclusivemode = false, $fromctx = 0, $ctx = 0, $rec = 1, $page = 0) {
  1033. global $PAGE;
  1034. if ($ctx && $ctx != context_system::instance()->id) {
  1035. $usercount = 0;
  1036. } else {
  1037. // Users can only be displayed in system context.
  1038. $usercount = $tag->count_tagged_items('core', 'user',
  1039. 'it.deleted=:notdeleted', array('notdeleted' => 0));
  1040. }
  1041. $perpage = $exclusivemode ? 24 : 5;
  1042. $content = '';
  1043. $totalpages = ceil($usercount / $perpage);
  1044. if ($usercount) {
  1045. $userlist = $tag->get_tagged_items('core', 'user', $page * $perpage, $perpage,
  1046. 'it.deleted=:notdeleted', array('notdeleted' => 0));
  1047. $renderer = $PAGE->get_renderer('core', 'user');
  1048. $content .= $renderer->user_list($userlist, $exclusivemode);
  1049. }
  1050. return new core_tag\output\tagindex($tag, 'core', 'user', $content,
  1051. $exclusivemode, $fromctx, $ctx, $rec, $page, $totalpages);
  1052. }