You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

user.php 83 KiB

3 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533
  1. <?php
  2. /**
  3. * Core User API
  4. *
  5. * @package WordPress
  6. * @subpackage Users
  7. */
  8. /**
  9. * Authenticates and logs a user in with 'remember' capability.
  10. *
  11. * The credentials is an array that has 'user_login', 'user_password', and
  12. * 'remember' indices. If the credentials is not given, then the log in form
  13. * will be assumed and used if set.
  14. *
  15. * The various authentication cookies will be set by this function and will be
  16. * set for a longer period depending on if the 'remember' credential is set to
  17. * true.
  18. *
  19. * @since 2.5.0
  20. *
  21. * @global string $auth_secure_cookie
  22. *
  23. * @param array $credentials Optional. User info in order to sign on.
  24. * @param string|bool $secure_cookie Optional. Whether to use secure cookie.
  25. * @return WP_User|WP_Error WP_User on success, WP_Error on failure.
  26. */
  27. function wp_signon( $credentials = array(), $secure_cookie = '' ) {
  28. if ( empty($credentials) ) {
  29. $credentials = array(); // Back-compat for plugins passing an empty string.
  30. if ( ! empty($_POST['log']) )
  31. $credentials['user_login'] = $_POST['log'];
  32. if ( ! empty($_POST['pwd']) )
  33. $credentials['user_password'] = $_POST['pwd'];
  34. if ( ! empty($_POST['rememberme']) )
  35. $credentials['remember'] = $_POST['rememberme'];
  36. }
  37. if ( !empty($credentials['remember']) )
  38. $credentials['remember'] = true;
  39. else
  40. $credentials['remember'] = false;
  41. /**
  42. * Fires before the user is authenticated.
  43. *
  44. * The variables passed to the callbacks are passed by reference,
  45. * and can be modified by callback functions.
  46. *
  47. * @since 1.5.1
  48. *
  49. * @todo Decide whether to deprecate the wp_authenticate action.
  50. *
  51. * @param string $user_login Username, passed by reference.
  52. * @param string $user_password User password, passed by reference.
  53. */
  54. do_action_ref_array( 'wp_authenticate', array( &$credentials['user_login'], &$credentials['user_password'] ) );
  55. if ( '' === $secure_cookie )
  56. $secure_cookie = is_ssl();
  57. /**
  58. * Filters whether to use a secure sign-on cookie.
  59. *
  60. * @since 3.1.0
  61. *
  62. * @param bool $secure_cookie Whether to use a secure sign-on cookie.
  63. * @param array $credentials {
  64. * Array of entered sign-on data.
  65. *
  66. * @type string $user_login Username.
  67. * @type string $user_password Password entered.
  68. * @type bool $remember Whether to 'remember' the user. Increases the time
  69. * that the cookie will be kept. Default false.
  70. * }
  71. */
  72. $secure_cookie = apply_filters( 'secure_signon_cookie', $secure_cookie, $credentials );
  73. global $auth_secure_cookie; // XXX ugly hack to pass this to wp_authenticate_cookie
  74. $auth_secure_cookie = $secure_cookie;
  75. add_filter('authenticate', 'wp_authenticate_cookie', 30, 3);
  76. $user = wp_authenticate($credentials['user_login'], $credentials['user_password']);
  77. if ( is_wp_error($user) ) {
  78. if ( $user->get_error_codes() == array('empty_username', 'empty_password') ) {
  79. $user = new WP_Error('', '');
  80. }
  81. return $user;
  82. }
  83. wp_set_auth_cookie($user->ID, $credentials['remember'], $secure_cookie);
  84. /**
  85. * Fires after the user has successfully logged in.
  86. *
  87. * @since 1.5.0
  88. *
  89. * @param string $user_login Username.
  90. * @param WP_User $user WP_User object of the logged-in user.
  91. */
  92. do_action( 'wp_login', $user->user_login, $user );
  93. return $user;
  94. }
  95. /**
  96. * Authenticate a user, confirming the username and password are valid.
  97. *
  98. * @since 2.8.0
  99. *
  100. * @param WP_User|WP_Error|null $user WP_User or WP_Error object from a previous callback. Default null.
  101. * @param string $username Username for authentication.
  102. * @param string $password Password for authentication.
  103. * @return WP_User|WP_Error WP_User on success, WP_Error on failure.
  104. */
  105. function wp_authenticate_username_password($user, $username, $password) {
  106. if ( $user instanceof WP_User ) {
  107. return $user;
  108. }
  109. if ( empty($username) || empty($password) ) {
  110. if ( is_wp_error( $user ) )
  111. return $user;
  112. $error = new WP_Error();
  113. if ( empty($username) )
  114. $error->add('empty_username', __('<strong>ERROR</strong>: The username field is empty.'));
  115. if ( empty($password) )
  116. $error->add('empty_password', __('<strong>ERROR</strong>: The password field is empty.'));
  117. return $error;
  118. }
  119. $user = get_user_by('login', $username);
  120. if ( !$user ) {
  121. return new WP_Error( 'invalid_username',
  122. __( '<strong>ERROR</strong>: Invalid username.' ) .
  123. ' <a href="' . wp_lostpassword_url() . '">' .
  124. __( 'Lost your password?' ) .
  125. '</a>'
  126. );
  127. }
  128. /**
  129. * Filters whether the given user can be authenticated with the provided $password.
  130. *
  131. * @since 2.5.0
  132. *
  133. * @param WP_User|WP_Error $user WP_User or WP_Error object if a previous
  134. * callback failed authentication.
  135. * @param string $password Password to check against the user.
  136. */
  137. $user = apply_filters( 'wp_authenticate_user', $user, $password );
  138. if ( is_wp_error($user) )
  139. return $user;
  140. if ( ! wp_check_password( $password, $user->user_pass, $user->ID ) ) {
  141. return new WP_Error( 'incorrect_password',
  142. sprintf(
  143. /* translators: %s: user name */
  144. __( '<strong>ERROR</strong>: The password you entered for the username %s is incorrect.' ),
  145. '<strong>' . $username . '</strong>'
  146. ) .
  147. ' <a href="' . wp_lostpassword_url() . '">' .
  148. __( 'Lost your password?' ) .
  149. '</a>'
  150. );
  151. }
  152. return $user;
  153. }
  154. /**
  155. * Authenticates a user using the email and password.
  156. *
  157. * @since 4.5.0
  158. *
  159. * @param WP_User|WP_Error|null $user WP_User or WP_Error object if a previous
  160. * callback failed authentication.
  161. * @param string $email Email address for authentication.
  162. * @param string $password Password for authentication.
  163. * @return WP_User|WP_Error WP_User on success, WP_Error on failure.
  164. */
  165. function wp_authenticate_email_password( $user, $email, $password ) {
  166. if ( $user instanceof WP_User ) {
  167. return $user;
  168. }
  169. if ( empty( $email ) || empty( $password ) ) {
  170. if ( is_wp_error( $user ) ) {
  171. return $user;
  172. }
  173. $error = new WP_Error();
  174. if ( empty( $email ) ) {
  175. $error->add( 'empty_username', __( '<strong>ERROR</strong>: The email field is empty.' ) ); // Uses 'empty_username' for back-compat with wp_signon()
  176. }
  177. if ( empty( $password ) ) {
  178. $error->add( 'empty_password', __( '<strong>ERROR</strong>: The password field is empty.' ) );
  179. }
  180. return $error;
  181. }
  182. if ( ! is_email( $email ) ) {
  183. return $user;
  184. }
  185. $user = get_user_by( 'email', $email );
  186. if ( ! $user ) {
  187. return new WP_Error( 'invalid_email',
  188. __( '<strong>ERROR</strong>: Invalid email address.' ) .
  189. ' <a href="' . wp_lostpassword_url() . '">' .
  190. __( 'Lost your password?' ) .
  191. '</a>'
  192. );
  193. }
  194. /** This filter is documented in wp-includes/user.php */
  195. $user = apply_filters( 'wp_authenticate_user', $user, $password );
  196. if ( is_wp_error( $user ) ) {
  197. return $user;
  198. }
  199. if ( ! wp_check_password( $password, $user->user_pass, $user->ID ) ) {
  200. return new WP_Error( 'incorrect_password',
  201. sprintf(
  202. /* translators: %s: email address */
  203. __( '<strong>ERROR</strong>: The password you entered for the email address %s is incorrect.' ),
  204. '<strong>' . $email . '</strong>'
  205. ) .
  206. ' <a href="' . wp_lostpassword_url() . '">' .
  207. __( 'Lost your password?' ) .
  208. '</a>'
  209. );
  210. }
  211. return $user;
  212. }
  213. /**
  214. * Authenticate the user using the WordPress auth cookie.
  215. *
  216. * @since 2.8.0
  217. *
  218. * @global string $auth_secure_cookie
  219. *
  220. * @param WP_User|WP_Error|null $user WP_User or WP_Error object from a previous callback. Default null.
  221. * @param string $username Username. If not empty, cancels the cookie authentication.
  222. * @param string $password Password. If not empty, cancels the cookie authentication.
  223. * @return WP_User|WP_Error WP_User on success, WP_Error on failure.
  224. */
  225. function wp_authenticate_cookie($user, $username, $password) {
  226. if ( $user instanceof WP_User ) {
  227. return $user;
  228. }
  229. if ( empty($username) && empty($password) ) {
  230. $user_id = wp_validate_auth_cookie();
  231. if ( $user_id )
  232. return new WP_User($user_id);
  233. global $auth_secure_cookie;
  234. if ( $auth_secure_cookie )
  235. $auth_cookie = SECURE_AUTH_COOKIE;
  236. else
  237. $auth_cookie = AUTH_COOKIE;
  238. if ( !empty($_COOKIE[$auth_cookie]) )
  239. return new WP_Error('expired_session', __('Please log in again.'));
  240. // If the cookie is not set, be silent.
  241. }
  242. return $user;
  243. }
  244. /**
  245. * For Multisite blogs, check if the authenticated user has been marked as a
  246. * spammer, or if the user's primary blog has been marked as spam.
  247. *
  248. * @since 3.7.0
  249. *
  250. * @param WP_User|WP_Error|null $user WP_User or WP_Error object from a previous callback. Default null.
  251. * @return WP_User|WP_Error WP_User on success, WP_Error if the user is considered a spammer.
  252. */
  253. function wp_authenticate_spam_check( $user ) {
  254. if ( $user instanceof WP_User && is_multisite() ) {
  255. /**
  256. * Filters whether the user has been marked as a spammer.
  257. *
  258. * @since 3.7.0
  259. *
  260. * @param bool $spammed Whether the user is considered a spammer.
  261. * @param WP_User $user User to check against.
  262. */
  263. $spammed = apply_filters( 'check_is_user_spammed', is_user_spammy( $user ), $user );
  264. if ( $spammed )
  265. return new WP_Error( 'spammer_account', __( '<strong>ERROR</strong>: Your account has been marked as a spammer.' ) );
  266. }
  267. return $user;
  268. }
  269. /**
  270. * Validates the logged-in cookie.
  271. *
  272. * Checks the logged-in cookie if the previous auth cookie could not be
  273. * validated and parsed.
  274. *
  275. * This is a callback for the {@see 'determine_current_user'} filter, rather than API.
  276. *
  277. * @since 3.9.0
  278. *
  279. * @param int|bool $user_id The user ID (or false) as received from the
  280. * determine_current_user filter.
  281. * @return int|false User ID if validated, false otherwise. If a user ID from
  282. * an earlier filter callback is received, that value is returned.
  283. */
  284. function wp_validate_logged_in_cookie( $user_id ) {
  285. if ( $user_id ) {
  286. return $user_id;
  287. }
  288. if ( is_blog_admin() || is_network_admin() || empty( $_COOKIE[LOGGED_IN_COOKIE] ) ) {
  289. return false;
  290. }
  291. return wp_validate_auth_cookie( $_COOKIE[LOGGED_IN_COOKIE], 'logged_in' );
  292. }
  293. /**
  294. * Number of posts user has written.
  295. *
  296. * @since 3.0.0
  297. * @since 4.1.0 Added `$post_type` argument.
  298. * @since 4.3.0 Added `$public_only` argument. Added the ability to pass an array
  299. * of post types to `$post_type`.
  300. *
  301. * @global wpdb $wpdb WordPress database abstraction object.
  302. *
  303. * @param int $userid User ID.
  304. * @param array|string $post_type Optional. Single post type or array of post types to count the number of posts for. Default 'post'.
  305. * @param bool $public_only Optional. Whether to only return counts for public posts. Default false.
  306. * @return string Number of posts the user has written in this post type.
  307. */
  308. function count_user_posts( $userid, $post_type = 'post', $public_only = false ) {
  309. global $wpdb;
  310. $where = get_posts_by_author_sql( $post_type, true, $userid, $public_only );
  311. $count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->posts $where" );
  312. /**
  313. * Filters the number of posts a user has written.
  314. *
  315. * @since 2.7.0
  316. * @since 4.1.0 Added `$post_type` argument.
  317. * @since 4.3.1 Added `$public_only` argument.
  318. *
  319. * @param int $count The user's post count.
  320. * @param int $userid User ID.
  321. * @param string|array $post_type Single post type or array of post types to count the number of posts for.
  322. * @param bool $public_only Whether to limit counted posts to public posts.
  323. */
  324. return apply_filters( 'get_usernumposts', $count, $userid, $post_type, $public_only );
  325. }
  326. /**
  327. * Number of posts written by a list of users.
  328. *
  329. * @since 3.0.0
  330. *
  331. * @global wpdb $wpdb WordPress database abstraction object.
  332. *
  333. * @param array $users Array of user IDs.
  334. * @param string|array $post_type Optional. Single post type or array of post types to check. Defaults to 'post'.
  335. * @param bool $public_only Optional. Only return counts for public posts. Defaults to false.
  336. * @return array Amount of posts each user has written.
  337. */
  338. function count_many_users_posts( $users, $post_type = 'post', $public_only = false ) {
  339. global $wpdb;
  340. $count = array();
  341. if ( empty( $users ) || ! is_array( $users ) )
  342. return $count;
  343. $userlist = implode( ',', array_map( 'absint', $users ) );
  344. $where = get_posts_by_author_sql( $post_type, true, null, $public_only );
  345. $result = $wpdb->get_results( "SELECT post_author, COUNT(*) FROM $wpdb->posts $where AND post_author IN ($userlist) GROUP BY post_author", ARRAY_N );
  346. foreach ( $result as $row ) {
  347. $count[ $row[0] ] = $row[1];
  348. }
  349. foreach ( $users as $id ) {
  350. if ( ! isset( $count[ $id ] ) )
  351. $count[ $id ] = 0;
  352. }
  353. return $count;
  354. }
  355. //
  356. // User option functions
  357. //
  358. /**
  359. * Get the current user's ID
  360. *
  361. * @since MU
  362. *
  363. * @return int The current user's ID
  364. */
  365. function get_current_user_id() {
  366. if ( ! function_exists( 'wp_get_current_user' ) )
  367. return 0;
  368. $user = wp_get_current_user();
  369. return ( isset( $user->ID ) ? (int) $user->ID : 0 );
  370. }
  371. /**
  372. * Retrieve user option that can be either per Site or per Network.
  373. *
  374. * If the user ID is not given, then the current user will be used instead. If
  375. * the user ID is given, then the user data will be retrieved. The filter for
  376. * the result, will also pass the original option name and finally the user data
  377. * object as the third parameter.
  378. *
  379. * The option will first check for the per site name and then the per Network name.
  380. *
  381. * @since 2.0.0
  382. *
  383. * @global wpdb $wpdb WordPress database abstraction object.
  384. *
  385. * @param string $option User option name.
  386. * @param int $user Optional. User ID.
  387. * @param string $deprecated Use get_option() to check for an option in the options table.
  388. * @return mixed User option value on success, false on failure.
  389. */
  390. function get_user_option( $option, $user = 0, $deprecated = '' ) {
  391. global $wpdb;
  392. if ( !empty( $deprecated ) )
  393. _deprecated_argument( __FUNCTION__, '3.0.0' );
  394. if ( empty( $user ) )
  395. $user = get_current_user_id();
  396. if ( ! $user = get_userdata( $user ) )
  397. return false;
  398. $prefix = $wpdb->get_blog_prefix();
  399. if ( $user->has_prop( $prefix . $option ) ) // Blog specific
  400. $result = $user->get( $prefix . $option );
  401. elseif ( $user->has_prop( $option ) ) // User specific and cross-blog
  402. $result = $user->get( $option );
  403. else
  404. $result = false;
  405. /**
  406. * Filters a specific user option value.
  407. *
  408. * The dynamic portion of the hook name, `$option`, refers to the user option name.
  409. *
  410. * @since 2.5.0
  411. *
  412. * @param mixed $result Value for the user's option.
  413. * @param string $option Name of the option being retrieved.
  414. * @param WP_User $user WP_User object of the user whose option is being retrieved.
  415. */
  416. return apply_filters( "get_user_option_{$option}", $result, $option, $user );
  417. }
  418. /**
  419. * Update user option with global blog capability.
  420. *
  421. * User options are just like user metadata except that they have support for
  422. * global blog options. If the 'global' parameter is false, which it is by default
  423. * it will prepend the WordPress table prefix to the option name.
  424. *
  425. * Deletes the user option if $newvalue is empty.
  426. *
  427. * @since 2.0.0
  428. *
  429. * @global wpdb $wpdb WordPress database abstraction object.
  430. *
  431. * @param int $user_id User ID.
  432. * @param string $option_name User option name.
  433. * @param mixed $newvalue User option value.
  434. * @param bool $global Optional. Whether option name is global or blog specific.
  435. * Default false (blog specific).
  436. * @return int|bool User meta ID if the option didn't exist, true on successful update,
  437. * false on failure.
  438. */
  439. function update_user_option( $user_id, $option_name, $newvalue, $global = false ) {
  440. global $wpdb;
  441. if ( !$global )
  442. $option_name = $wpdb->get_blog_prefix() . $option_name;
  443. return update_user_meta( $user_id, $option_name, $newvalue );
  444. }
  445. /**
  446. * Delete user option with global blog capability.
  447. *
  448. * User options are just like user metadata except that they have support for
  449. * global blog options. If the 'global' parameter is false, which it is by default
  450. * it will prepend the WordPress table prefix to the option name.
  451. *
  452. * @since 3.0.0
  453. *
  454. * @global wpdb $wpdb WordPress database abstraction object.
  455. *
  456. * @param int $user_id User ID
  457. * @param string $option_name User option name.
  458. * @param bool $global Optional. Whether option name is global or blog specific.
  459. * Default false (blog specific).
  460. * @return bool True on success, false on failure.
  461. */
  462. function delete_user_option( $user_id, $option_name, $global = false ) {
  463. global $wpdb;
  464. if ( !$global )
  465. $option_name = $wpdb->get_blog_prefix() . $option_name;
  466. return delete_user_meta( $user_id, $option_name );
  467. }
  468. /**
  469. * Retrieve list of users matching criteria.
  470. *
  471. * @since 3.1.0
  472. *
  473. * @see WP_User_Query
  474. *
  475. * @param array $args Optional. Arguments to retrieve users. See WP_User_Query::prepare_query().
  476. * for more information on accepted arguments.
  477. * @return array List of users.
  478. */
  479. function get_users( $args = array() ) {
  480. $args = wp_parse_args( $args );
  481. $args['count_total'] = false;
  482. $user_search = new WP_User_Query($args);
  483. return (array) $user_search->get_results();
  484. }
  485. /**
  486. * Get the sites a user belongs to.
  487. *
  488. * @since 3.0.0
  489. * @since 4.7.0 Converted to use get_sites().
  490. *
  491. * @global wpdb $wpdb WordPress database abstraction object.
  492. *
  493. * @param int $user_id User ID
  494. * @param bool $all Whether to retrieve all sites, or only sites that are not
  495. * marked as deleted, archived, or spam.
  496. * @return array A list of the user's sites. An empty array if the user doesn't exist
  497. * or belongs to no sites.
  498. */
  499. function get_blogs_of_user( $user_id, $all = false ) {
  500. global $wpdb;
  501. $user_id = (int) $user_id;
  502. // Logged out users can't have sites
  503. if ( empty( $user_id ) )
  504. return array();
  505. /**
  506. * Filters the list of a user's sites before it is populated.
  507. *
  508. * Passing a non-null value to the filter will effectively short circuit
  509. * get_blogs_of_user(), returning that value instead.
  510. *
  511. * @since 4.6.0
  512. *
  513. * @param null|array $sites An array of site objects of which the user is a member.
  514. * @param int $user_id User ID.
  515. * @param bool $all Whether the returned array should contain all sites, including
  516. * those marked 'deleted', 'archived', or 'spam'. Default false.
  517. */
  518. $sites = apply_filters( 'pre_get_blogs_of_user', null, $user_id, $all );
  519. if ( null !== $sites ) {
  520. return $sites;
  521. }
  522. $keys = get_user_meta( $user_id );
  523. if ( empty( $keys ) )
  524. return array();
  525. if ( ! is_multisite() ) {
  526. $site_id = get_current_blog_id();
  527. $sites = array( $site_id => new stdClass );
  528. $sites[ $site_id ]->userblog_id = $site_id;
  529. $sites[ $site_id ]->blogname = get_option('blogname');
  530. $sites[ $site_id ]->domain = '';
  531. $sites[ $site_id ]->path = '';
  532. $sites[ $site_id ]->site_id = 1;
  533. $sites[ $site_id ]->siteurl = get_option('siteurl');
  534. $sites[ $site_id ]->archived = 0;
  535. $sites[ $site_id ]->spam = 0;
  536. $sites[ $site_id ]->deleted = 0;
  537. return $sites;
  538. }
  539. $site_ids = array();
  540. if ( isset( $keys[ $wpdb->base_prefix . 'capabilities' ] ) && defined( 'MULTISITE' ) ) {
  541. $site_ids[] = 1;
  542. unset( $keys[ $wpdb->base_prefix . 'capabilities' ] );
  543. }
  544. $keys = array_keys( $keys );
  545. foreach ( $keys as $key ) {
  546. if ( 'capabilities' !== substr( $key, -12 ) )
  547. continue;
  548. if ( $wpdb->base_prefix && 0 !== strpos( $key, $wpdb->base_prefix ) )
  549. continue;
  550. $site_id = str_replace( array( $wpdb->base_prefix, '_capabilities' ), '', $key );
  551. if ( ! is_numeric( $site_id ) )
  552. continue;
  553. $site_ids[] = (int) $site_id;
  554. }
  555. $sites = array();
  556. if ( ! empty( $site_ids ) ) {
  557. $args = array(
  558. 'number' => '',
  559. 'site__in' => $site_ids,
  560. );
  561. if ( ! $all ) {
  562. $args['archived'] = 0;
  563. $args['spam'] = 0;
  564. $args['deleted'] = 0;
  565. }
  566. $_sites = get_sites( $args );
  567. foreach ( $_sites as $site ) {
  568. $sites[ $site->id ] = (object) array(
  569. 'userblog_id' => $site->id,
  570. 'blogname' => $site->blogname,
  571. 'domain' => $site->domain,
  572. 'path' => $site->path,
  573. 'site_id' => $site->network_id,
  574. 'siteurl' => $site->siteurl,
  575. 'archived' => $site->archived,
  576. 'mature' => $site->mature,
  577. 'spam' => $site->spam,
  578. 'deleted' => $site->deleted,
  579. );
  580. }
  581. }
  582. /**
  583. * Filters the list of sites a user belongs to.
  584. *
  585. * @since MU
  586. *
  587. * @param array $sites An array of site objects belonging to the user.
  588. * @param int $user_id User ID.
  589. * @param bool $all Whether the returned sites array should contain all sites, including
  590. * those marked 'deleted', 'archived', or 'spam'. Default false.
  591. */
  592. return apply_filters( 'get_blogs_of_user', $sites, $user_id, $all );
  593. }
  594. /**
  595. * Find out whether a user is a member of a given blog.
  596. *
  597. * @since MU 1.1
  598. *
  599. * @param int $user_id Optional. The unique ID of the user. Defaults to the current user.
  600. * @param int $blog_id Optional. ID of the blog to check. Defaults to the current site.
  601. * @return bool
  602. */
  603. function is_user_member_of_blog( $user_id = 0, $blog_id = 0 ) {
  604. global $wpdb;
  605. $user_id = (int) $user_id;
  606. $blog_id = (int) $blog_id;
  607. if ( empty( $user_id ) ) {
  608. $user_id = get_current_user_id();
  609. }
  610. // Technically not needed, but does save calls to get_site and get_user_meta
  611. // in the event that the function is called when a user isn't logged in
  612. if ( empty( $user_id ) ) {
  613. return false;
  614. } else {
  615. $user = get_userdata( $user_id );
  616. if ( ! $user instanceof WP_User ) {
  617. return false;
  618. }
  619. }
  620. if ( ! is_multisite() ) {
  621. return true;
  622. }
  623. if ( empty( $blog_id ) ) {
  624. $blog_id = get_current_blog_id();
  625. }
  626. $blog = get_site( $blog_id );
  627. if ( ! $blog || ! isset( $blog->domain ) || $blog->archived || $blog->spam || $blog->deleted ) {
  628. return false;
  629. }
  630. $keys = get_user_meta( $user_id );
  631. if ( empty( $keys ) ) {
  632. return false;
  633. }
  634. // no underscore before capabilities in $base_capabilities_key
  635. $base_capabilities_key = $wpdb->base_prefix . 'capabilities';
  636. $site_capabilities_key = $wpdb->base_prefix . $blog_id . '_capabilities';
  637. if ( isset( $keys[ $base_capabilities_key ] ) && $blog_id == 1 ) {
  638. return true;
  639. }
  640. if ( isset( $keys[ $site_capabilities_key ] ) ) {
  641. return true;
  642. }
  643. return false;
  644. }
  645. /**
  646. * Add meta data field to a user.
  647. *
  648. * Post meta data is called "Custom Fields" on the Administration Screens.
  649. *
  650. * @since 3.0.0
  651. * @link https://codex.wordpress.org/Function_Reference/add_user_meta
  652. *
  653. * @param int $user_id User ID.
  654. * @param string $meta_key Metadata name.
  655. * @param mixed $meta_value Metadata value.
  656. * @param bool $unique Optional, default is false. Whether the same key should not be added.
  657. * @return int|false Meta ID on success, false on failure.
  658. */
  659. function add_user_meta($user_id, $meta_key, $meta_value, $unique = false) {
  660. return add_metadata('user', $user_id, $meta_key, $meta_value, $unique);
  661. }
  662. /**
  663. * Remove metadata matching criteria from a user.
  664. *
  665. * You can match based on the key, or key and value. Removing based on key and
  666. * value, will keep from removing duplicate metadata with the same key. It also
  667. * allows removing all metadata matching key, if needed.
  668. *
  669. * @since 3.0.0
  670. * @link https://codex.wordpress.org/Function_Reference/delete_user_meta
  671. *
  672. * @param int $user_id User ID
  673. * @param string $meta_key Metadata name.
  674. * @param mixed $meta_value Optional. Metadata value.
  675. * @return bool True on success, false on failure.
  676. */
  677. function delete_user_meta($user_id, $meta_key, $meta_value = '') {
  678. return delete_metadata('user', $user_id, $meta_key, $meta_value);
  679. }
  680. /**
  681. * Retrieve user meta field for a user.
  682. *
  683. * @since 3.0.0
  684. * @link https://codex.wordpress.org/Function_Reference/get_user_meta
  685. *
  686. * @param int $user_id User ID.
  687. * @param string $key Optional. The meta key to retrieve. By default, returns data for all keys.
  688. * @param bool $single Whether to return a single value.
  689. * @return mixed Will be an array if $single is false. Will be value of meta data field if $single is true.
  690. */
  691. function get_user_meta($user_id, $key = '', $single = false) {
  692. return get_metadata('user', $user_id, $key, $single);
  693. }
  694. /**
  695. * Update user meta field based on user ID.
  696. *
  697. * Use the $prev_value parameter to differentiate between meta fields with the
  698. * same key and user ID.
  699. *
  700. * If the meta field for the user does not exist, it will be added.
  701. *
  702. * @since 3.0.0
  703. * @link https://codex.wordpress.org/Function_Reference/update_user_meta
  704. *
  705. * @param int $user_id User ID.
  706. * @param string $meta_key Metadata key.
  707. * @param mixed $meta_value Metadata value.
  708. * @param mixed $prev_value Optional. Previous value to check before removing.
  709. * @return int|bool Meta ID if the key didn't exist, true on successful update, false on failure.
  710. */
  711. function update_user_meta($user_id, $meta_key, $meta_value, $prev_value = '') {
  712. return update_metadata('user', $user_id, $meta_key, $meta_value, $prev_value);
  713. }
  714. /**
  715. * Count number of users who have each of the user roles.
  716. *
  717. * Assumes there are neither duplicated nor orphaned capabilities meta_values.
  718. * Assumes role names are unique phrases. Same assumption made by WP_User_Query::prepare_query()
  719. * Using $strategy = 'time' this is CPU-intensive and should handle around 10^7 users.
  720. * Using $strategy = 'memory' this is memory-intensive and should handle around 10^5 users, but see WP Bug #12257.
  721. *
  722. * @since 3.0.0
  723. * @since 4.4.0 The number of users with no role is now included in the `none` element.
  724. *
  725. * @global wpdb $wpdb WordPress database abstraction object.
  726. *
  727. * @param string $strategy 'time' or 'memory'
  728. * @return array Includes a grand total and an array of counts indexed by role strings.
  729. */
  730. function count_users($strategy = 'time') {
  731. global $wpdb;
  732. // Initialize
  733. $id = get_current_blog_id();
  734. $blog_prefix = $wpdb->get_blog_prefix($id);
  735. $result = array();
  736. if ( 'time' == $strategy ) {
  737. $avail_roles = wp_roles()->get_names();
  738. // Build a CPU-intensive query that will return concise information.
  739. $select_count = array();
  740. foreach ( $avail_roles as $this_role => $name ) {
  741. $select_count[] = $wpdb->prepare( "COUNT(NULLIF(`meta_value` LIKE %s, false))", '%' . $wpdb->esc_like( '"' . $this_role . '"' ) . '%');
  742. }
  743. $select_count[] = "COUNT(NULLIF(`meta_value` = 'a:0:{}', false))";
  744. $select_count = implode(', ', $select_count);
  745. // Add the meta_value index to the selection list, then run the query.
  746. $row = $wpdb->get_row( "SELECT $select_count, COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$blog_prefix}capabilities'", ARRAY_N );
  747. // Run the previous loop again to associate results with role names.
  748. $col = 0;
  749. $role_counts = array();
  750. foreach ( $avail_roles as $this_role => $name ) {
  751. $count = (int) $row[$col++];
  752. if ($count > 0) {
  753. $role_counts[$this_role] = $count;
  754. }
  755. }
  756. $role_counts['none'] = (int) $row[$col++];
  757. // Get the meta_value index from the end of the result set.
  758. $total_users = (int) $row[$col];
  759. $result['total_users'] = $total_users;
  760. $result['avail_roles'] =& $role_counts;
  761. } else {
  762. $avail_roles = array(
  763. 'none' => 0,
  764. );
  765. $users_of_blog = $wpdb->get_col( "SELECT meta_value FROM $wpdb->usermeta WHERE meta_key = '{$blog_prefix}capabilities'" );
  766. foreach ( $users_of_blog as $caps_meta ) {
  767. $b_roles = maybe_unserialize($caps_meta);
  768. if ( ! is_array( $b_roles ) )
  769. continue;
  770. if ( empty( $b_roles ) ) {
  771. $avail_roles['none']++;
  772. }
  773. foreach ( $b_roles as $b_role => $val ) {
  774. if ( isset($avail_roles[$b_role]) ) {
  775. $avail_roles[$b_role]++;
  776. } else {
  777. $avail_roles[$b_role] = 1;
  778. }
  779. }
  780. }
  781. $result['total_users'] = count( $users_of_blog );
  782. $result['avail_roles'] =& $avail_roles;
  783. }
  784. if ( is_multisite() ) {
  785. $result['avail_roles']['none'] = 0;
  786. }
  787. return $result;
  788. }
  789. //
  790. // Private helper functions
  791. //
  792. /**
  793. * Set up global user vars.
  794. *
  795. * Used by wp_set_current_user() for back compat. Might be deprecated in the future.
  796. *
  797. * @since 2.0.4
  798. *
  799. * @global string $user_login The user username for logging in
  800. * @global object $userdata User data.
  801. * @global int $user_level The level of the user
  802. * @global int $user_ID The ID of the user
  803. * @global string $user_email The email address of the user
  804. * @global string $user_url The url in the user's profile
  805. * @global string $user_identity The display name of the user
  806. *
  807. * @param int $for_user_id Optional. User ID to set up global data.
  808. */
  809. function setup_userdata($for_user_id = '') {
  810. global $user_login, $userdata, $user_level, $user_ID, $user_email, $user_url, $user_identity;
  811. if ( '' == $for_user_id )
  812. $for_user_id = get_current_user_id();
  813. $user = get_userdata( $for_user_id );
  814. if ( ! $user ) {
  815. $user_ID = 0;
  816. $user_level = 0;
  817. $userdata = null;
  818. $user_login = $user_email = $user_url = $user_identity = '';
  819. return;
  820. }
  821. $user_ID = (int) $user->ID;
  822. $user_level = (int) $user->user_level;
  823. $userdata = $user;
  824. $user_login = $user->user_login;
  825. $user_email = $user->user_email;
  826. $user_url = $user->user_url;
  827. $user_identity = $user->display_name;
  828. }
  829. /**
  830. * Create dropdown HTML content of users.
  831. *
  832. * The content can either be displayed, which it is by default or retrieved by
  833. * setting the 'echo' argument. The 'include' and 'exclude' arguments do not
  834. * need to be used; all users will be displayed in that case. Only one can be
  835. * used, either 'include' or 'exclude', but not both.
  836. *
  837. * The available arguments are as follows:
  838. *
  839. * @since 2.3.0
  840. * @since 4.5.0 Added the 'display_name_with_login' value for 'show'.
  841. * @since 4.7.0 Added the `$role`, `$role__in`, and `$role__not_in` parameters.
  842. *
  843. * @param array|string $args {
  844. * Optional. Array or string of arguments to generate a drop-down of users.
  845. * See WP_User_Query::prepare_query() for additional available arguments.
  846. *
  847. * @type string $show_option_all Text to show as the drop-down default (all).
  848. * Default empty.
  849. * @type string $show_option_none Text to show as the drop-down default when no
  850. * users were found. Default empty.
  851. * @type int|string $option_none_value Value to use for $show_option_non when no users
  852. * were found. Default -1.
  853. * @type string $hide_if_only_one_author Whether to skip generating the drop-down
  854. * if only one user was found. Default empty.
  855. * @type string $orderby Field to order found users by. Accepts user fields.
  856. * Default 'display_name'.
  857. * @type string $order Whether to order users in ascending or descending
  858. * order. Accepts 'ASC' (ascending) or 'DESC' (descending).
  859. * Default 'ASC'.
  860. * @type array|string $include Array or comma-separated list of user IDs to include.
  861. * Default empty.
  862. * @type array|string $exclude Array or comma-separated list of user IDs to exclude.
  863. * Default empty.
  864. * @type bool|int $multi Whether to skip the ID attribute on the 'select' element.
  865. * Accepts 1|true or 0|false. Default 0|false.
  866. * @type string $show User data to display. If the selected item is empty
  867. * then the 'user_login' will be displayed in parentheses.
  868. * Accepts any user field, or 'display_name_with_login' to show
  869. * the display name with user_login in parentheses.
  870. * Default 'display_name'.
  871. * @type int|bool $echo Whether to echo or return the drop-down. Accepts 1|true (echo)
  872. * or 0|false (return). Default 1|true.
  873. * @type int $selected Which user ID should be selected. Default 0.
  874. * @type bool $include_selected Whether to always include the selected user ID in the drop-
  875. * down. Default false.
  876. * @type string $name Name attribute of select element. Default 'user'.
  877. * @type string $id ID attribute of the select element. Default is the value of $name.
  878. * @type string $class Class attribute of the select element. Default empty.
  879. * @type int $blog_id ID of blog (Multisite only). Default is ID of the current blog.
  880. * @type string $who Which type of users to query. Accepts only an empty string or
  881. * 'authors'. Default empty.
  882. * @type string|array $role An array or a comma-separated list of role names that users must
  883. * match to be included in results. Note that this is an inclusive
  884. * list: users must match *each* role. Default empty.
  885. * @type array $role__in An array of role names. Matched users must have at least one of
  886. * these roles. Default empty array.
  887. * @type array $role__not_in An array of role names to exclude. Users matching one or more of
  888. * these roles will not be included in results. Default empty array.
  889. * }
  890. * @return string String of HTML content.
  891. */
  892. function wp_dropdown_users( $args = '' ) {
  893. $defaults = array(
  894. 'show_option_all' => '', 'show_option_none' => '', 'hide_if_only_one_author' => '',
  895. 'orderby' => 'display_name', 'order' => 'ASC',
  896. 'include' => '', 'exclude' => '', 'multi' => 0,
  897. 'show' => 'display_name', 'echo' => 1,
  898. 'selected' => 0, 'name' => 'user', 'class' => '', 'id' => '',
  899. 'blog_id' => get_current_blog_id(), 'who' => '', 'include_selected' => false,
  900. 'option_none_value' => -1,
  901. 'role' => '',
  902. 'role__in' => array(),
  903. 'role__not_in' => array(),
  904. );
  905. $defaults['selected'] = is_author() ? get_query_var( 'author' ) : 0;
  906. $r = wp_parse_args( $args, $defaults );
  907. $query_args = wp_array_slice_assoc( $r, array( 'blog_id', 'include', 'exclude', 'orderby', 'order', 'who', 'role', 'role__in', 'role__not_in' ) );
  908. $fields = array( 'ID', 'user_login' );
  909. $show = ! empty( $r['show'] ) ? $r['show'] : 'display_name';
  910. if ( 'display_name_with_login' === $show ) {
  911. $fields[] = 'display_name';
  912. } else {
  913. $fields[] = $show;
  914. }
  915. $query_args['fields'] = $fields;
  916. $show_option_all = $r['show_option_all'];
  917. $show_option_none = $r['show_option_none'];
  918. $option_none_value = $r['option_none_value'];
  919. /**
  920. * Filters the query arguments for the list of users in the dropdown.
  921. *
  922. * @since 4.4.0
  923. *
  924. * @param array $query_args The query arguments for get_users().
  925. * @param array $r The arguments passed to wp_dropdown_users() combined with the defaults.
  926. */
  927. $query_args = apply_filters( 'wp_dropdown_users_args', $query_args, $r );
  928. $users = get_users( $query_args );
  929. $output = '';
  930. if ( ! empty( $users ) && ( empty( $r['hide_if_only_one_author'] ) || count( $users ) > 1 ) ) {
  931. $name = esc_attr( $r['name'] );
  932. if ( $r['multi'] && ! $r['id'] ) {
  933. $id = '';
  934. } else {
  935. $id = $r['id'] ? " id='" . esc_attr( $r['id'] ) . "'" : " id='$name'";
  936. }
  937. $output = "<select name='{$name}'{$id} class='" . $r['class'] . "'>\n";
  938. if ( $show_option_all ) {
  939. $output .= "\t<option value='0'>$show_option_all</option>\n";
  940. }
  941. if ( $show_option_none ) {
  942. $_selected = selected( $option_none_value, $r['selected'], false );
  943. $output .= "\t<option value='" . esc_attr( $option_none_value ) . "'$_selected>$show_option_none</option>\n";
  944. }
  945. if ( $r['include_selected'] && ( $r['selected'] > 0 ) ) {
  946. $found_selected = false;
  947. $r['selected'] = (int) $r['selected'];
  948. foreach ( (array) $users as $user ) {
  949. $user->ID = (int) $user->ID;
  950. if ( $user->ID === $r['selected'] ) {
  951. $found_selected = true;
  952. }
  953. }
  954. if ( ! $found_selected ) {
  955. $users[] = get_userdata( $r['selected'] );
  956. }
  957. }
  958. foreach ( (array) $users as $user ) {
  959. if ( 'display_name_with_login' === $show ) {
  960. /* translators: 1: display name, 2: user_login */
  961. $display = sprintf( _x( '%1$s (%2$s)', 'user dropdown' ), $user->display_name, $user->user_login );
  962. } elseif ( ! empty( $user->$show ) ) {
  963. $display = $user->$show;
  964. } else {
  965. $display = '(' . $user->user_login . ')';
  966. }
  967. $_selected = selected( $user->ID, $r['selected'], false );
  968. $output .= "\t<option value='$user->ID'$_selected>" . esc_html( $display ) . "</option>\n";
  969. }
  970. $output .= "</select>";
  971. }
  972. /**
  973. * Filters the wp_dropdown_users() HTML output.
  974. *
  975. * @since 2.3.0
  976. *
  977. * @param string $output HTML output generated by wp_dropdown_users().
  978. */
  979. $html = apply_filters( 'wp_dropdown_users', $output );
  980. if ( $r['echo'] ) {
  981. echo $html;
  982. }
  983. return $html;
  984. }
  985. /**
  986. * Sanitize user field based on context.
  987. *
  988. * Possible context values are: 'raw', 'edit', 'db', 'display', 'attribute' and 'js'. The
  989. * 'display' context is used by default. 'attribute' and 'js' contexts are treated like 'display'
  990. * when calling filters.
  991. *
  992. * @since 2.3.0
  993. *
  994. * @param string $field The user Object field name.
  995. * @param mixed $value The user Object value.
  996. * @param int $user_id User ID.
  997. * @param string $context How to sanitize user fields. Looks for 'raw', 'edit', 'db', 'display',
  998. * 'attribute' and 'js'.
  999. * @return mixed Sanitized value.
  1000. */
  1001. function sanitize_user_field($field, $value, $user_id, $context) {
  1002. $int_fields = array('ID');
  1003. if ( in_array($field, $int_fields) )
  1004. $value = (int) $value;
  1005. if ( 'raw' == $context )
  1006. return $value;
  1007. if ( !is_string($value) && !is_numeric($value) )
  1008. return $value;
  1009. $prefixed = false !== strpos( $field, 'user_' );
  1010. if ( 'edit' == $context ) {
  1011. if ( $prefixed ) {
  1012. /** This filter is documented in wp-includes/post.php */
  1013. $value = apply_filters( "edit_{$field}", $value, $user_id );
  1014. } else {
  1015. /**
  1016. * Filters a user field value in the 'edit' context.
  1017. *
  1018. * The dynamic portion of the hook name, `$field`, refers to the prefixed user
  1019. * field being filtered, such as 'user_login', 'user_email', 'first_name', etc.
  1020. *
  1021. * @since 2.9.0
  1022. *
  1023. * @param mixed $value Value of the prefixed user field.
  1024. * @param int $user_id User ID.
  1025. */
  1026. $value = apply_filters( "edit_user_{$field}", $value, $user_id );
  1027. }
  1028. if ( 'description' == $field )
  1029. $value = esc_html( $value ); // textarea_escaped?
  1030. else
  1031. $value = esc_attr($value);
  1032. } elseif ( 'db' == $context ) {
  1033. if ( $prefixed ) {
  1034. /** This filter is documented in wp-includes/post.php */
  1035. $value = apply_filters( "pre_{$field}", $value );
  1036. } else {
  1037. /**
  1038. * Filters the value of a user field in the 'db' context.
  1039. *
  1040. * The dynamic portion of the hook name, `$field`, refers to the prefixed user
  1041. * field being filtered, such as 'user_login', 'user_email', 'first_name', etc.
  1042. *
  1043. * @since 2.9.0
  1044. *
  1045. * @param mixed $value Value of the prefixed user field.
  1046. */
  1047. $value = apply_filters( "pre_user_{$field}", $value );
  1048. }
  1049. } else {
  1050. // Use display filters by default.
  1051. if ( $prefixed ) {
  1052. /** This filter is documented in wp-includes/post.php */
  1053. $value = apply_filters( $field, $value, $user_id, $context );
  1054. } else {
  1055. /**
  1056. * Filters the value of a user field in a standard context.
  1057. *
  1058. * The dynamic portion of the hook name, `$field`, refers to the prefixed user
  1059. * field being filtered, such as 'user_login', 'user_email', 'first_name', etc.
  1060. *
  1061. * @since 2.9.0
  1062. *
  1063. * @param mixed $value The user object value to sanitize.
  1064. * @param int $user_id User ID.
  1065. * @param string $context The context to filter within.
  1066. */
  1067. $value = apply_filters( "user_{$field}", $value, $user_id, $context );
  1068. }
  1069. }
  1070. if ( 'user_url' == $field )
  1071. $value = esc_url($value);
  1072. if ( 'attribute' == $context ) {
  1073. $value = esc_attr( $value );
  1074. } elseif ( 'js' == $context ) {
  1075. $value = esc_js( $value );
  1076. }
  1077. return $value;
  1078. }
  1079. /**
  1080. * Update all user caches
  1081. *
  1082. * @since 3.0.0
  1083. *
  1084. * @param object|WP_User $user User object to be cached
  1085. * @return bool|null Returns false on failure.
  1086. */
  1087. function update_user_caches( $user ) {
  1088. if ( $user instanceof WP_User ) {
  1089. if ( ! $user->exists() ) {
  1090. return false;
  1091. }
  1092. $user = $user->data;
  1093. }
  1094. wp_cache_add($user->ID, $user, 'users');
  1095. wp_cache_add($user->user_login, $user->ID, 'userlogins');
  1096. wp_cache_add($user->user_email, $user->ID, 'useremail');
  1097. wp_cache_add($user->user_nicename, $user->ID, 'userslugs');
  1098. }
  1099. /**
  1100. * Clean all user caches
  1101. *
  1102. * @since 3.0.0
  1103. * @since 4.4.0 'clean_user_cache' action was added.
  1104. *
  1105. * @param WP_User|int $user User object or ID to be cleaned from the cache
  1106. */
  1107. function clean_user_cache( $user ) {
  1108. if ( is_numeric( $user ) )
  1109. $user = new WP_User( $user );
  1110. if ( ! $user->exists() )
  1111. return;
  1112. wp_cache_delete( $user->ID, 'users' );
  1113. wp_cache_delete( $user->user_login, 'userlogins' );
  1114. wp_cache_delete( $user->user_email, 'useremail' );
  1115. wp_cache_delete( $user->user_nicename, 'userslugs' );
  1116. /**
  1117. * Fires immediately after the given user's cache is cleaned.
  1118. *
  1119. * @since 4.4.0
  1120. *
  1121. * @param int $user_id User ID.
  1122. * @param WP_User $user User object.
  1123. */
  1124. do_action( 'clean_user_cache', $user->ID, $user );
  1125. }
  1126. /**
  1127. * Checks whether the given username exists.
  1128. *
  1129. * @since 2.0.0
  1130. *
  1131. * @param string $username Username.
  1132. * @return int|false The user's ID on success, and false on failure.
  1133. */
  1134. function username_exists( $username ) {
  1135. if ( $user = get_user_by( 'login', $username ) ) {
  1136. return $user->ID;
  1137. }
  1138. return false;
  1139. }
  1140. /**
  1141. * Checks whether the given email exists.
  1142. *
  1143. * @since 2.1.0
  1144. *
  1145. * @param string $email Email.
  1146. * @return int|false The user's ID on success, and false on failure.
  1147. */
  1148. function email_exists( $email ) {
  1149. if ( $user = get_user_by( 'email', $email) ) {
  1150. return $user->ID;
  1151. }
  1152. return false;
  1153. }
  1154. /**
  1155. * Checks whether a username is valid.
  1156. *
  1157. * @since 2.0.1
  1158. * @since 4.4.0 Empty sanitized usernames are now considered invalid
  1159. *
  1160. * @param string $username Username.
  1161. * @return bool Whether username given is valid
  1162. */
  1163. function validate_username( $username ) {
  1164. $sanitized = sanitize_user( $username, true );
  1165. $valid = ( $sanitized == $username && ! empty( $sanitized ) );
  1166. /**
  1167. * Filters whether the provided username is valid or not.
  1168. *
  1169. * @since 2.0.1
  1170. *
  1171. * @param bool $valid Whether given username is valid.
  1172. * @param string $username Username to check.
  1173. */
  1174. return apply_filters( 'validate_username', $valid, $username );
  1175. }
  1176. /**
  1177. * Insert a user into the database.
  1178. *
  1179. * Most of the `$userdata` array fields have filters associated with the values. Exceptions are
  1180. * 'ID', 'rich_editing', 'comment_shortcuts', 'admin_color', 'use_ssl',
  1181. * 'user_registered', and 'role'. The filters have the prefix 'pre_user_' followed by the field
  1182. * name. An example using 'description' would have the filter called, 'pre_user_description' that
  1183. * can be hooked into.
  1184. *
  1185. * @since 2.0.0
  1186. * @since 3.6.0 The `aim`, `jabber`, and `yim` fields were removed as default user contact
  1187. * methods for new installs. See wp_get_user_contact_methods().
  1188. * @since 4.7.0 The user's locale can be passed to `$userdata`.
  1189. *
  1190. * @global wpdb $wpdb WordPress database abstraction object.
  1191. *
  1192. * @param array|object|WP_User $userdata {
  1193. * An array, object, or WP_User object of user data arguments.
  1194. *
  1195. * @type int $ID User ID. If supplied, the user will be updated.
  1196. * @type string $user_pass The plain-text user password.
  1197. * @type string $user_login The user's login username.
  1198. * @type string $user_nicename The URL-friendly user name.
  1199. * @type string $user_url The user URL.
  1200. * @type string $user_email The user email address.
  1201. * @type string $display_name The user's display name.
  1202. * Default is the user's username.
  1203. * @type string $nickname The user's nickname.
  1204. * Default is the user's username.
  1205. * @type string $first_name The user's first name. For new users, will be used
  1206. * to build the first part of the user's display name
  1207. * if `$display_name` is not specified.
  1208. * @type string $last_name The user's last name. For new users, will be used
  1209. * to build the second part of the user's display name
  1210. * if `$display_name` is not specified.
  1211. * @type string $description The user's biographical description.
  1212. * @type string|bool $rich_editing Whether to enable the rich-editor for the user.
  1213. * False if not empty.
  1214. * @type string|bool $comment_shortcuts Whether to enable comment moderation keyboard
  1215. * shortcuts for the user. Default false.
  1216. * @type string $admin_color Admin color scheme for the user. Default 'fresh'.
  1217. * @type bool $use_ssl Whether the user should always access the admin over
  1218. * https. Default false.
  1219. * @type string $user_registered Date the user registered. Format is 'Y-m-d H:i:s'.
  1220. * @type string|bool $show_admin_bar_front Whether to display the Admin Bar for the user on the
  1221. * site's front end. Default true.
  1222. * @type string $role User's role.
  1223. * @type string $locale User's locale. Default empty.
  1224. * }
  1225. * @return int|WP_Error The newly created user's ID or a WP_Error object if the user could not
  1226. * be created.
  1227. */
  1228. function wp_insert_user( $userdata ) {
  1229. global $wpdb;
  1230. if ( $userdata instanceof stdClass ) {
  1231. $userdata = get_object_vars( $userdata );
  1232. } elseif ( $userdata instanceof WP_User ) {
  1233. $userdata = $userdata->to_array();
  1234. }
  1235. // Are we updating or creating?
  1236. if ( ! empty( $userdata['ID'] ) ) {
  1237. $ID = (int) $userdata['ID'];
  1238. $update = true;
  1239. $old_user_data = get_userdata( $ID );
  1240. if ( ! $old_user_data ) {
  1241. return new WP_Error( 'invalid_user_id', __( 'Invalid user ID.' ) );
  1242. }
  1243. // hashed in wp_update_user(), plaintext if called directly
  1244. $user_pass = ! empty( $userdata['user_pass'] ) ? $userdata['user_pass'] : $old_user_data->user_pass;
  1245. } else {
  1246. $update = false;
  1247. // Hash the password
  1248. $user_pass = wp_hash_password( $userdata['user_pass'] );
  1249. }
  1250. $sanitized_user_login = sanitize_user( $userdata['user_login'], true );
  1251. /**
  1252. * Filters a username after it has been sanitized.
  1253. *
  1254. * This filter is called before the user is created or updated.
  1255. *
  1256. * @since 2.0.3
  1257. *
  1258. * @param string $sanitized_user_login Username after it has been sanitized.
  1259. */
  1260. $pre_user_login = apply_filters( 'pre_user_login', $sanitized_user_login );
  1261. //Remove any non-printable chars from the login string to see if we have ended up with an empty username
  1262. $user_login = trim( $pre_user_login );
  1263. // user_login must be between 0 and 60 characters.
  1264. if ( empty( $user_login ) ) {
  1265. return new WP_Error('empty_user_login', __('Cannot create a user with an empty login name.') );
  1266. } elseif ( mb_strlen( $user_login ) > 60 ) {
  1267. return new WP_Error( 'user_login_too_long', __( 'Username may not be longer than 60 characters.' ) );
  1268. }
  1269. if ( ! $update && username_exists( $user_login ) ) {
  1270. return new WP_Error( 'existing_user_login', __( 'Sorry, that username already exists!' ) );
  1271. }
  1272. /**
  1273. * Filters the list of blacklisted usernames.
  1274. *
  1275. * @since 4.4.0
  1276. *
  1277. * @param array $usernames Array of blacklisted usernames.
  1278. */
  1279. $illegal_logins = (array) apply_filters( 'illegal_user_logins', array() );
  1280. if ( in_array( strtolower( $user_login ), array_map( 'strtolower', $illegal_logins ) ) ) {
  1281. return new WP_Error( 'invalid_username', __( 'Sorry, that username is not allowed.' ) );
  1282. }
  1283. /*
  1284. * If a nicename is provided, remove unsafe user characters before using it.
  1285. * Otherwise build a nicename from the user_login.
  1286. */
  1287. if ( ! empty( $userdata['user_nicename'] ) ) {
  1288. $user_nicename = sanitize_user( $userdata['user_nicename'], true );
  1289. if ( mb_strlen( $user_nicename ) > 50 ) {
  1290. return new WP_Error( 'user_nicename_too_long', __( 'Nicename may not be longer than 50 characters.' ) );
  1291. }
  1292. } else {
  1293. $user_nicename = mb_substr( $user_login, 0, 50 );
  1294. }
  1295. $user_nicename = sanitize_title( $user_nicename );
  1296. // Store values to save in user meta.
  1297. $meta = array();
  1298. /**
  1299. * Filters a user's nicename before the user is created or updated.
  1300. *
  1301. * @since 2.0.3
  1302. *
  1303. * @param string $user_nicename The user's nicename.
  1304. */
  1305. $user_nicename = apply_filters( 'pre_user_nicename', $user_nicename );
  1306. $raw_user_url = empty( $userdata['user_url'] ) ? '' : $userdata['user_url'];
  1307. /**
  1308. * Filters a user's URL before the user is created or updated.
  1309. *
  1310. * @since 2.0.3
  1311. *
  1312. * @param string $raw_user_url The user's URL.
  1313. */
  1314. $user_url = apply_filters( 'pre_user_url', $raw_user_url );
  1315. $raw_user_email = empty( $userdata['user_email'] ) ? '' : $userdata['user_email'];
  1316. /**
  1317. * Filters a user's email before the user is created or updated.
  1318. *
  1319. * @since 2.0.3
  1320. *
  1321. * @param string $raw_user_email The user's email.
  1322. */
  1323. $user_email = apply_filters( 'pre_user_email', $raw_user_email );
  1324. /*
  1325. * If there is no update, just check for `email_exists`. If there is an update,
  1326. * check if current email and new email are the same, or not, and check `email_exists`
  1327. * accordingly.
  1328. */
  1329. if ( ( ! $update || ( ! empty( $old_user_data ) && 0 !== strcasecmp( $user_email, $old_user_data->user_email ) ) )
  1330. && ! defined( 'WP_IMPORTING' )
  1331. && email_exists( $user_email )
  1332. ) {
  1333. return new WP_Error( 'existing_user_email', __( 'Sorry, that email address is already used!' ) );
  1334. }
  1335. $nickname = empty( $userdata['nickname'] ) ? $user_login : $userdata['nickname'];
  1336. /**
  1337. * Filters a user's nickname before the user is created or updated.
  1338. *
  1339. * @since 2.0.3
  1340. *
  1341. * @param string $nickname The user's nickname.
  1342. */
  1343. $meta['nickname'] = apply_filters( 'pre_user_nickname', $nickname );
  1344. $first_name = empty( $userdata['first_name'] ) ? '' : $userdata['first_name'];
  1345. /**
  1346. * Filters a user's first name before the user is created or updated.
  1347. *
  1348. * @since 2.0.3
  1349. *
  1350. * @param string $first_name The user's first name.
  1351. */
  1352. $meta['first_name'] = apply_filters( 'pre_user_first_name', $first_name );
  1353. $last_name = empty( $userdata['last_name'] ) ? '' : $userdata['last_name'];
  1354. /**
  1355. * Filters a user's last name before the user is created or updated.
  1356. *
  1357. * @since 2.0.3
  1358. *
  1359. * @param string $last_name The user's last name.
  1360. */
  1361. $meta['last_name'] = apply_filters( 'pre_user_last_name', $last_name );
  1362. if ( empty( $userdata['display_name'] ) ) {
  1363. if ( $update ) {
  1364. $display_name = $user_login;
  1365. } elseif ( $meta['first_name'] && $meta['last_name'] ) {
  1366. /* translators: 1: first name, 2: last name */
  1367. $display_name = sprintf( _x( '%1$s %2$s', 'Display name based on first name and last name' ), $meta['first_name'], $meta['last_name'] );
  1368. } elseif ( $meta['first_name'] ) {
  1369. $display_name = $meta['first_name'];
  1370. } elseif ( $meta['last_name'] ) {
  1371. $display_name = $meta['last_name'];
  1372. } else {
  1373. $display_name = $user_login;
  1374. }
  1375. } else {
  1376. $display_name = $userdata['display_name'];
  1377. }
  1378. /**
  1379. * Filters a user's display name before the user is created or updated.
  1380. *
  1381. * @since 2.0.3
  1382. *
  1383. * @param string $display_name The user's display name.
  1384. */
  1385. $display_name = apply_filters( 'pre_user_display_name', $display_name );
  1386. $description = empty( $userdata['description'] ) ? '' : $userdata['description'];
  1387. /**
  1388. * Filters a user's description before the user is created or updated.
  1389. *
  1390. * @since 2.0.3
  1391. *
  1392. * @param string $description The user's description.
  1393. */
  1394. $meta['description'] = apply_filters( 'pre_user_description', $description );
  1395. $meta['rich_editing'] = empty( $userdata['rich_editing'] ) ? 'true' : $userdata['rich_editing'];
  1396. $meta['comment_shortcuts'] = empty( $userdata['comment_shortcuts'] ) || 'false' === $userdata['comment_shortcuts'] ? 'false' : 'true';
  1397. $admin_color = empty( $userdata['admin_color'] ) ? 'fresh' : $userdata['admin_color'];
  1398. $meta['admin_color'] = preg_replace( '|[^a-z0-9 _.\-@]|i', '', $admin_color );
  1399. $meta['use_ssl'] = empty( $userdata['use_ssl'] ) ? 0 : $userdata['use_ssl'];
  1400. $user_registered = empty( $userdata['user_registered'] ) ? gmdate( 'Y-m-d H:i:s' ) : $userdata['user_registered'];
  1401. $meta['show_admin_bar_front'] = empty( $userdata['show_admin_bar_front'] ) ? 'true' : $userdata['show_admin_bar_front'];
  1402. $meta['locale'] = isset( $userdata['locale'] ) ? $userdata['locale'] : '';
  1403. $user_nicename_check = $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->users WHERE user_nicename = %s AND user_login != %s LIMIT 1" , $user_nicename, $user_login));
  1404. if ( $user_nicename_check ) {
  1405. $suffix = 2;
  1406. while ($user_nicename_check) {
  1407. // user_nicename allows 50 chars. Subtract one for a hyphen, plus the length of the suffix.
  1408. $base_length = 49 - mb_strlen( $suffix );
  1409. $alt_user_nicename = mb_substr( $user_nicename, 0, $base_length ) . "-$suffix";
  1410. $user_nicename_check = $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->users WHERE user_nicename = %s AND user_login != %s LIMIT 1" , $alt_user_nicename, $user_login));
  1411. $suffix++;
  1412. }
  1413. $user_nicename = $alt_user_nicename;
  1414. }
  1415. $compacted = compact( 'user_pass', 'user_email', 'user_url', 'user_nicename', 'display_name', 'user_registered' );
  1416. $data = wp_unslash( $compacted );
  1417. if ( $update ) {
  1418. if ( $user_email !== $old_user_data->user_email ) {
  1419. $data['user_activation_key'] = '';
  1420. }
  1421. $wpdb->update( $wpdb->users, $data, compact( 'ID' ) );
  1422. $user_id = (int) $ID;
  1423. } else {
  1424. $wpdb->insert( $wpdb->users, $data + compact( 'user_login' ) );
  1425. $user_id = (int) $wpdb->insert_id;
  1426. }
  1427. $user = new WP_User( $user_id );
  1428. /**
  1429. * Filters a user's meta values and keys before the user is created or updated.
  1430. *
  1431. * Does not include contact methods. These are added using `wp_get_user_contact_methods( $user )`.
  1432. *
  1433. * @since 4.4.0
  1434. *
  1435. * @param array $meta {
  1436. * Default meta values and keys for the user.
  1437. *
  1438. * @type string $nickname The user's nickname. Default is the user's username.
  1439. * @type string $first_name The user's first name.
  1440. * @type string $last_name The user's last name.
  1441. * @type string $description The user's description.
  1442. * @type bool $rich_editing Whether to enable the rich-editor for the user. False if not empty.
  1443. * @type bool $comment_shortcuts Whether to enable keyboard shortcuts for the user. Default false.
  1444. * @type string $admin_color The color scheme for a user's admin screen. Default 'fresh'.
  1445. * @type int|bool $use_ssl Whether to force SSL on the user's admin area. 0|false if SSL is
  1446. * not forced.
  1447. * @type bool $show_admin_bar_front Whether to show the admin bar on the front end for the user.
  1448. * Default true.
  1449. * }
  1450. * @param WP_User $user User object.
  1451. * @param bool $update Whether the user is being updated rather than created.
  1452. */
  1453. $meta = apply_filters( 'insert_user_meta', $meta, $user, $update );
  1454. // Update user meta.
  1455. foreach ( $meta as $key => $value ) {
  1456. update_user_meta( $user_id, $key, $value );
  1457. }
  1458. foreach ( wp_get_user_contact_methods( $user ) as $key => $value ) {
  1459. if ( isset( $userdata[ $key ] ) ) {
  1460. update_user_meta( $user_id, $key, $userdata[ $key ] );
  1461. }
  1462. }
  1463. if ( isset( $userdata['role'] ) ) {
  1464. $user->set_role( $userdata['role'] );
  1465. } elseif ( ! $update ) {
  1466. $user->set_role(get_option('default_role'));
  1467. }
  1468. wp_cache_delete( $user_id, 'users' );
  1469. wp_cache_delete( $user_login, 'userlogins' );
  1470. if ( $update ) {
  1471. /**
  1472. * Fires immediately after an existing user is updated.
  1473. *
  1474. * @since 2.0.0
  1475. *
  1476. * @param int $user_id User ID.
  1477. * @param object $old_user_data Object containing user's data prior to update.
  1478. */
  1479. do_action( 'profile_update', $user_id, $old_user_data );
  1480. } else {
  1481. /**
  1482. * Fires immediately after a new user is registered.
  1483. *
  1484. * @since 1.5.0
  1485. *
  1486. * @param int $user_id User ID.
  1487. */
  1488. do_action( 'user_register', $user_id );
  1489. }
  1490. return $user_id;
  1491. }
  1492. /**
  1493. * Update a user in the database.
  1494. *
  1495. * It is possible to update a user's password by specifying the 'user_pass'
  1496. * value in the $userdata parameter array.
  1497. *
  1498. * If current user's password is being updated, then the cookies will be
  1499. * cleared.
  1500. *
  1501. * @since 2.0.0
  1502. *
  1503. * @see wp_insert_user() For what fields can be set in $userdata.
  1504. *
  1505. * @param mixed $userdata An array of user data or a user object of type stdClass or WP_User.
  1506. * @return int|WP_Error The updated user's ID or a WP_Error object if the user could not be updated.
  1507. */
  1508. function wp_update_user($userdata) {
  1509. if ( $userdata instanceof stdClass ) {
  1510. $userdata = get_object_vars( $userdata );
  1511. } elseif ( $userdata instanceof WP_User ) {
  1512. $userdata = $userdata->to_array();
  1513. }
  1514. $ID = isset( $userdata['ID'] ) ? (int) $userdata['ID'] : 0;
  1515. if ( ! $ID ) {
  1516. return new WP_Error( 'invalid_user_id', __( 'Invalid user ID.' ) );
  1517. }
  1518. // First, get all of the original fields
  1519. $user_obj = get_userdata( $ID );
  1520. if ( ! $user_obj ) {
  1521. return new WP_Error( 'invalid_user_id', __( 'Invalid user ID.' ) );
  1522. }
  1523. $user = $user_obj->to_array();
  1524. // Add additional custom fields
  1525. foreach ( _get_additional_user_keys( $user_obj ) as $key ) {
  1526. $user[ $key ] = get_user_meta( $ID, $key, true );
  1527. }
  1528. // Escape data pulled from DB.
  1529. $user = add_magic_quotes( $user );
  1530. if ( ! empty( $userdata['user_pass'] ) && $userdata['user_pass'] !== $user_obj->user_pass ) {
  1531. // If password is changing, hash it now
  1532. $plaintext_pass = $userdata['user_pass'];
  1533. $userdata['user_pass'] = wp_hash_password( $userdata['user_pass'] );
  1534. /**
  1535. * Filters whether to send the password change email.
  1536. *
  1537. * @since 4.3.0
  1538. *
  1539. * @see wp_insert_user() For `$user` and `$userdata` fields.
  1540. *
  1541. * @param bool $send Whether to send the email.
  1542. * @param array $user The original user array.
  1543. * @param array $userdata The updated user array.
  1544. *
  1545. */
  1546. $send_password_change_email = apply_filters( 'send_password_change_email', true, $user, $userdata );
  1547. }
  1548. if ( isset( $userdata['user_email'] ) && $user['user_email'] !== $userdata['user_email'] ) {
  1549. /**
  1550. * Filters whether to send the email change email.
  1551. *
  1552. * @since 4.3.0
  1553. *
  1554. * @see wp_insert_user() For `$user` and `$userdata` fields.
  1555. *
  1556. * @param bool $send Whether to send the email.
  1557. * @param array $user The original user array.
  1558. * @param array $userdata The updated user array.
  1559. *
  1560. */
  1561. $send_email_change_email = apply_filters( 'send_email_change_email', true, $user, $userdata );
  1562. }
  1563. wp_cache_delete( $user['user_email'], 'useremail' );
  1564. wp_cache_delete( $user['user_nicename'], 'userslugs' );
  1565. // Merge old and new fields with new fields overwriting old ones.
  1566. $userdata = array_merge( $user, $userdata );
  1567. $user_id = wp_insert_user( $userdata );
  1568. if ( ! is_wp_error( $user_id ) ) {
  1569. $blog_name = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES );
  1570. $switched_locale = false;
  1571. if ( ! empty( $send_password_change_email ) || ! empty( $send_email_change_email ) ) {
  1572. $switched_locale = switch_to_locale( get_user_locale( $user_id ) );
  1573. }
  1574. if ( ! empty( $send_password_change_email ) ) {
  1575. /* translators: Do not translate USERNAME, ADMIN_EMAIL, EMAIL, SITENAME, SITEURL: those are placeholders. */
  1576. $pass_change_text = __( 'Hi ###USERNAME###,
  1577. This notice confirms that your password was changed on ###SITENAME###.
  1578. If you did not change your password, please contact the Site Administrator at
  1579. ###ADMIN_EMAIL###
  1580. This email has been sent to ###EMAIL###
  1581. Regards,
  1582. All at ###SITENAME###
  1583. ###SITEURL###' );
  1584. $pass_change_email = array(
  1585. 'to' => $user['user_email'],
  1586. /* translators: User password change notification email subject. 1: Site name */
  1587. 'subject' => __( '[%s] Notice of Password Change' ),
  1588. 'message' => $pass_change_text,
  1589. 'headers' => '',
  1590. );
  1591. /**
  1592. * Filters the contents of the email sent when the user's password is changed.
  1593. *
  1594. * @since 4.3.0
  1595. *
  1596. * @param array $pass_change_email {
  1597. * Used to build wp_mail().
  1598. * @type string $to The intended recipients. Add emails in a comma separated string.
  1599. * @type string $subject The subject of the email.
  1600. * @type string $message The content of the email.
  1601. * The following strings have a special meaning and will get replaced dynamically:
  1602. * - ###USERNAME### The current user's username.
  1603. * - ###ADMIN_EMAIL### The admin email in case this was unexpected.
  1604. * - ###EMAIL### The old email.
  1605. * - ###SITENAME### The name of the site.
  1606. * - ###SITEURL### The URL to the site.
  1607. * @type string $headers Headers. Add headers in a newline (\r\n) separated string.
  1608. * }
  1609. * @param array $user The original user array.
  1610. * @param array $userdata The updated user array.
  1611. *
  1612. */
  1613. $pass_change_email = apply_filters( 'password_change_email', $pass_change_email, $user, $userdata );
  1614. $pass_change_email['message'] = str_replace( '###USERNAME###', $user['user_login'], $pass_change_email['message'] );
  1615. $pass_change_email['message'] = str_replace( '###ADMIN_EMAIL###', get_option( 'admin_email' ), $pass_change_email['message'] );
  1616. $pass_change_email['message'] = str_replace( '###EMAIL###', $user['user_email'], $pass_change_email['message'] );
  1617. $pass_change_email['message'] = str_replace( '###SITENAME###', $blog_name, $pass_change_email['message'] );
  1618. $pass_change_email['message'] = str_replace( '###SITEURL###', home_url(), $pass_change_email['message'] );
  1619. wp_mail( $pass_change_email['to'], sprintf( $pass_change_email['subject'], $blog_name ), $pass_change_email['message'], $pass_change_email['headers'] );
  1620. }
  1621. if ( ! empty( $send_email_change_email ) ) {
  1622. /* translators: Do not translate USERNAME, ADMIN_EMAIL, EMAIL, SITENAME, SITEURL: those are placeholders. */
  1623. $email_change_text = __( 'Hi ###USERNAME###,
  1624. This notice confirms that your email was changed on ###SITENAME###.
  1625. If you did not change your email, please contact the Site Administrator at
  1626. ###ADMIN_EMAIL###
  1627. This email has been sent to ###EMAIL###
  1628. Regards,
  1629. All at ###SITENAME###
  1630. ###SITEURL###' );
  1631. $email_change_email = array(
  1632. 'to' => $user['user_email'],
  1633. /* translators: User email change notification email subject. 1: Site name */
  1634. 'subject' => __( '[%s] Notice of Email Change' ),
  1635. 'message' => $email_change_text,
  1636. 'headers' => '',
  1637. );
  1638. /**
  1639. * Filters the contents of the email sent when the user's email is changed.
  1640. *
  1641. * @since 4.3.0
  1642. *
  1643. * @param array $email_change_email {
  1644. * Used to build wp_mail().
  1645. * @type string $to The intended recipients.
  1646. * @type string $subject The subject of the email.
  1647. * @type string $message The content of the email.
  1648. * The following strings have a special meaning and will get replaced dynamically:
  1649. * - ###USERNAME### The current user's username.
  1650. * - ###ADMIN_EMAIL### The admin email in case this was unexpected.
  1651. * - ###EMAIL### The old email.
  1652. * - ###SITENAME### The name of the site.
  1653. * - ###SITEURL### The URL to the site.
  1654. * @type string $headers Headers.
  1655. * }
  1656. * @param array $user The original user array.
  1657. * @param array $userdata The updated user array.
  1658. */
  1659. $email_change_email = apply_filters( 'email_change_email', $email_change_email, $user, $userdata );
  1660. $email_change_email['message'] = str_replace( '###USERNAME###', $user['user_login'], $email_change_email['message'] );
  1661. $email_change_email['message'] = str_replace( '###ADMIN_EMAIL###', get_option( 'admin_email' ), $email_change_email['message'] );
  1662. $email_change_email['message'] = str_replace( '###EMAIL###', $user['user_email'], $email_change_email['message'] );
  1663. $email_change_email['message'] = str_replace( '###SITENAME###', $blog_name, $email_change_email['message'] );
  1664. $email_change_email['message'] = str_replace( '###SITEURL###', home_url(), $email_change_email['message'] );
  1665. wp_mail( $email_change_email['to'], sprintf( $email_change_email['subject'], $blog_name ), $email_change_email['message'], $email_change_email['headers'] );
  1666. }
  1667. if ( $switched_locale ) {
  1668. restore_previous_locale();
  1669. }
  1670. }
  1671. // Update the cookies if the password changed.
  1672. $current_user = wp_get_current_user();
  1673. if ( $current_user->ID == $ID ) {
  1674. if ( isset($plaintext_pass) ) {
  1675. wp_clear_auth_cookie();
  1676. // Here we calculate the expiration length of the current auth cookie and compare it to the default expiration.
  1677. // If it's greater than this, then we know the user checked 'Remember Me' when they logged in.
  1678. $logged_in_cookie = wp_parse_auth_cookie( '', 'logged_in' );
  1679. /** This filter is documented in wp-includes/pluggable.php */
  1680. $default_cookie_life = apply_filters( 'auth_cookie_expiration', ( 2 * DAY_IN_SECONDS ), $ID, false );
  1681. $remember = ( ( $logged_in_cookie['expiration'] - time() ) > $default_cookie_life );
  1682. wp_set_auth_cookie( $ID, $remember );
  1683. }
  1684. }
  1685. return $user_id;
  1686. }
  1687. /**
  1688. * A simpler way of inserting a user into the database.
  1689. *
  1690. * Creates a new user with just the username, password, and email. For more
  1691. * complex user creation use wp_insert_user() to specify more information.
  1692. *
  1693. * @since 2.0.0
  1694. * @see wp_insert_user() More complete way to create a new user
  1695. *
  1696. * @param string $username The user's username.
  1697. * @param string $password The user's password.
  1698. * @param string $email Optional. The user's email. Default empty.
  1699. * @return int|WP_Error The newly created user's ID or a WP_Error object if the user could not
  1700. * be created.
  1701. */
  1702. function wp_create_user($username, $password, $email = '') {
  1703. $user_login = wp_slash( $username );
  1704. $user_email = wp_slash( $email );
  1705. $user_pass = $password;
  1706. $userdata = compact('user_login', 'user_email', 'user_pass');
  1707. return wp_insert_user($userdata);
  1708. }
  1709. /**
  1710. * Returns a list of meta keys to be (maybe) populated in wp_update_user().
  1711. *
  1712. * The list of keys returned via this function are dependent on the presence
  1713. * of those keys in the user meta data to be set.
  1714. *
  1715. * @since 3.3.0
  1716. * @access private
  1717. *
  1718. * @param WP_User $user WP_User instance.
  1719. * @return array List of user keys to be populated in wp_update_user().
  1720. */
  1721. function _get_additional_user_keys( $user ) {
  1722. $keys = array( 'first_name', 'last_name', 'nickname', 'description', 'rich_editing', 'comment_shortcuts', 'admin_color', 'use_ssl', 'show_admin_bar_front', 'locale' );
  1723. return array_merge( $keys, array_keys( wp_get_user_contact_methods( $user ) ) );
  1724. }
  1725. /**
  1726. * Set up the user contact methods.
  1727. *
  1728. * Default contact methods were removed in 3.6. A filter dictates contact methods.
  1729. *
  1730. * @since 3.7.0
  1731. *
  1732. * @param WP_User $user Optional. WP_User object.
  1733. * @return array Array of contact methods and their labels.
  1734. */
  1735. function wp_get_user_contact_methods( $user = null ) {
  1736. $methods = array();
  1737. if ( get_site_option( 'initial_db_version' ) < 23588 ) {
  1738. $methods = array(
  1739. 'aim' => __( 'AIM' ),
  1740. 'yim' => __( 'Yahoo IM' ),
  1741. 'jabber' => __( 'Jabber / Google Talk' )
  1742. );
  1743. }
  1744. /**
  1745. * Filters the user contact methods.
  1746. *
  1747. * @since 2.9.0
  1748. *
  1749. * @param array $methods Array of contact methods and their labels.
  1750. * @param WP_User $user WP_User object.
  1751. */
  1752. return apply_filters( 'user_contactmethods', $methods, $user );
  1753. }
  1754. /**
  1755. * The old private function for setting up user contact methods.
  1756. *
  1757. * Use wp_get_user_contact_methods() instead.
  1758. *
  1759. * @since 2.9.0
  1760. * @access private
  1761. *
  1762. * @param WP_User $user Optional. WP_User object. Default null.
  1763. * @return array Array of contact methods and their labels.
  1764. */
  1765. function _wp_get_user_contactmethods( $user = null ) {
  1766. return wp_get_user_contact_methods( $user );
  1767. }
  1768. /**
  1769. * Gets the text suggesting how to create strong passwords.
  1770. *
  1771. * @since 4.1.0
  1772. *
  1773. * @return string The password hint text.
  1774. */
  1775. function wp_get_password_hint() {
  1776. $hint = __( 'Hint: The password should be at least twelve characters long. To make it stronger, use upper and lower case letters, numbers, and symbols like ! " ? $ % ^ &amp; ).' );
  1777. /**
  1778. * Filters the text describing the site's password complexity policy.
  1779. *
  1780. * @since 4.1.0
  1781. *
  1782. * @param string $hint The password hint text.
  1783. */
  1784. return apply_filters( 'password_hint', $hint );
  1785. }
  1786. /**
  1787. * Creates, stores, then returns a password reset key for user.
  1788. *
  1789. * @since 4.4.0
  1790. *
  1791. * @global wpdb $wpdb WordPress database abstraction object.
  1792. * @global PasswordHash $wp_hasher Portable PHP password hashing framework.
  1793. *
  1794. * @param WP_User $user User to retrieve password reset key for.
  1795. *
  1796. * @return string|WP_Error Password reset key on success. WP_Error on error.
  1797. */
  1798. function get_password_reset_key( $user ) {
  1799. global $wpdb, $wp_hasher;
  1800. /**
  1801. * Fires before a new password is retrieved.
  1802. *
  1803. * Use the {@see 'retrieve_password'} hook instead.
  1804. *
  1805. * @since 1.5.0
  1806. * @deprecated 1.5.1 Misspelled. Use 'retrieve_password' hook instead.
  1807. *
  1808. * @param string $user_login The user login name.
  1809. */
  1810. do_action( 'retreive_password', $user->user_login );
  1811. /**
  1812. * Fires before a new password is retrieved.
  1813. *
  1814. * @since 1.5.1
  1815. *
  1816. * @param string $user_login The user login name.
  1817. */
  1818. do_action( 'retrieve_password', $user->user_login );
  1819. $allow = true;
  1820. if ( is_multisite() && is_user_spammy( $user ) ) {
  1821. $allow = false;
  1822. }
  1823. /**
  1824. * Filters whether to allow a password to be reset.
  1825. *
  1826. * @since 2.7.0
  1827. *
  1828. * @param bool $allow Whether to allow the password to be reset. Default true.
  1829. * @param int $user_data->ID The ID of the user attempting to reset a password.
  1830. */
  1831. $allow = apply_filters( 'allow_password_reset', $allow, $user->ID );
  1832. if ( ! $allow ) {
  1833. return new WP_Error( 'no_password_reset', __( 'Password reset is not allowed for this user' ) );
  1834. } elseif ( is_wp_error( $allow ) ) {
  1835. return $allow;
  1836. }
  1837. // Generate something random for a password reset key.
  1838. $key = wp_generate_password( 20, false );
  1839. /**
  1840. * Fires when a password reset key is generated.
  1841. *
  1842. * @since 2.5.0
  1843. *
  1844. * @param string $user_login The username for the user.
  1845. * @param string $key The generated password reset key.
  1846. */
  1847. do_action( 'retrieve_password_key', $user->user_login, $key );
  1848. // Now insert the key, hashed, into the DB.
  1849. if ( empty( $wp_hasher ) ) {
  1850. $wp_hasher = new PasswordHash( 8, true );
  1851. }
  1852. $hashed = time() . ':' . $wp_hasher->HashPassword( $key );
  1853. $key_saved = $wpdb->update( $wpdb->users, array( 'user_activation_key' => $hashed ), array( 'user_login' => $user->user_login ) );
  1854. if ( false === $key_saved ) {
  1855. return new WP_Error( 'no_password_key_update', __( 'Could not save password reset key to database.' ) );
  1856. }
  1857. return $key;
  1858. }
  1859. /**
  1860. * Retrieves a user row based on password reset key and login
  1861. *
  1862. * A key is considered 'expired' if it exactly matches the value of the
  1863. * user_activation_key field, rather than being matched after going through the
  1864. * hashing process. This field is now hashed; old values are no longer accepted
  1865. * but have a different WP_Error code so good user feedback can be provided.
  1866. *
  1867. * @since 3.1.0
  1868. *
  1869. * @global wpdb $wpdb WordPress database object for queries.
  1870. * @global PasswordHash $wp_hasher Portable PHP password hashing framework instance.
  1871. *
  1872. * @param string $key Hash to validate sending user's password.
  1873. * @param string $login The user login.
  1874. * @return WP_User|WP_Error WP_User object on success, WP_Error object for invalid or expired keys.
  1875. */
  1876. function check_password_reset_key($key, $login) {
  1877. global $wpdb, $wp_hasher;
  1878. $key = preg_replace('/[^a-z0-9]/i', '', $key);
  1879. if ( empty( $key ) || !is_string( $key ) )
  1880. return new WP_Error('invalid_key', __('Invalid key'));
  1881. if ( empty($login) || !is_string($login) )
  1882. return new WP_Error('invalid_key', __('Invalid key'));
  1883. $row = $wpdb->get_row( $wpdb->prepare( "SELECT ID, user_activation_key FROM $wpdb->users WHERE user_login = %s", $login ) );
  1884. if ( ! $row )
  1885. return new WP_Error('invalid_key', __('Invalid key'));
  1886. if ( empty( $wp_hasher ) ) {
  1887. $wp_hasher = new PasswordHash( 8, true );
  1888. }
  1889. /**
  1890. * Filters the expiration time of password reset keys.
  1891. *
  1892. * @since 4.3.0
  1893. *
  1894. * @param int $expiration The expiration time in seconds.
  1895. */
  1896. $expiration_duration = apply_filters( 'password_reset_expiration', DAY_IN_SECONDS );
  1897. if ( false !== strpos( $row->user_activation_key, ':' ) ) {
  1898. list( $pass_request_time, $pass_key ) = explode( ':', $row->user_activation_key, 2 );
  1899. $expiration_time = $pass_request_time + $expiration_duration;
  1900. } else {
  1901. $pass_key = $row->user_activation_key;
  1902. $expiration_time = false;
  1903. }
  1904. if ( ! $pass_key ) {
  1905. return new WP_Error( 'invalid_key', __( 'Invalid key' ) );
  1906. }
  1907. $hash_is_correct = $wp_hasher->CheckPassword( $key, $pass_key );
  1908. if ( $hash_is_correct && $expiration_time && time() < $expiration_time ) {
  1909. return get_userdata( $row->ID );
  1910. } elseif ( $hash_is_correct && $expiration_time ) {
  1911. // Key has an expiration time that's passed
  1912. return new WP_Error( 'expired_key', __( 'Invalid key' ) );
  1913. }
  1914. if ( hash_equals( $row->user_activation_key, $key ) || ( $hash_is_correct && ! $expiration_time ) ) {
  1915. $return = new WP_Error( 'expired_key', __( 'Invalid key' ) );
  1916. $user_id = $row->ID;
  1917. /**
  1918. * Filters the return value of check_password_reset_key() when an
  1919. * old-style key is used.
  1920. *
  1921. * @since 3.7.0 Previously plain-text keys were stored in the database.
  1922. * @since 4.3.0 Previously key hashes were stored without an expiration time.
  1923. *
  1924. * @param WP_Error $return A WP_Error object denoting an expired key.
  1925. * Return a WP_User object to validate the key.
  1926. * @param int $user_id The matched user ID.
  1927. */
  1928. return apply_filters( 'password_reset_key_expired', $return, $user_id );
  1929. }
  1930. return new WP_Error( 'invalid_key', __( 'Invalid key' ) );
  1931. }
  1932. /**
  1933. * Handles resetting the user's password.
  1934. *
  1935. * @since 2.5.0
  1936. *
  1937. * @param object $user The user
  1938. * @param string $new_pass New password for the user in plaintext
  1939. */
  1940. function reset_password( $user, $new_pass ) {
  1941. /**
  1942. * Fires before the user's password is reset.
  1943. *
  1944. * @since 1.5.0
  1945. *
  1946. * @param object $user The user.
  1947. * @param string $new_pass New user password.
  1948. */
  1949. do_action( 'password_reset', $user, $new_pass );
  1950. wp_set_password( $new_pass, $user->ID );
  1951. update_user_option( $user->ID, 'default_password_nag', false, true );
  1952. /**
  1953. * Fires after the user's password is reset.
  1954. *
  1955. * @since 4.4.0
  1956. *
  1957. * @param object $user The user.
  1958. * @param string $new_pass New user password.
  1959. */
  1960. do_action( 'after_password_reset', $user, $new_pass );
  1961. }
  1962. /**
  1963. * Handles registering a new user.
  1964. *
  1965. * @since 2.5.0
  1966. *
  1967. * @param string $user_login User's username for logging in
  1968. * @param string $user_email User's email address to send password and add
  1969. * @return int|WP_Error Either user's ID or error on failure.
  1970. */
  1971. function register_new_user( $user_login, $user_email ) {
  1972. $errors = new WP_Error();
  1973. $sanitized_user_login = sanitize_user( $user_login );
  1974. /**
  1975. * Filters the email address of a user being registered.
  1976. *
  1977. * @since 2.1.0
  1978. *
  1979. * @param string $user_email The email address of the new user.
  1980. */
  1981. $user_email = apply_filters( 'user_registration_email', $user_email );
  1982. // Check the username
  1983. if ( $sanitized_user_login == '' ) {
  1984. $errors->add( 'empty_username', __( '<strong>ERROR</strong>: Please enter a username.' ) );
  1985. } elseif ( ! validate_username( $user_login ) ) {
  1986. $errors->add( 'invalid_username', __( '<strong>ERROR</strong>: This username is invalid because it uses illegal characters. Please enter a valid username.' ) );
  1987. $sanitized_user_login = '';
  1988. } elseif ( username_exists( $sanitized_user_login ) ) {
  1989. $errors->add( 'username_exists', __( '<strong>ERROR</strong>: This username is already registered. Please choose another one.' ) );
  1990. } else {
  1991. /** This filter is documented in wp-includes/user.php */
  1992. $illegal_user_logins = array_map( 'strtolower', (array) apply_filters( 'illegal_user_logins', array() ) );
  1993. if ( in_array( strtolower( $sanitized_user_login ), $illegal_user_logins ) ) {
  1994. $errors->add( 'invalid_username', __( '<strong>ERROR</strong>: Sorry, that username is not allowed.' ) );
  1995. }
  1996. }
  1997. // Check the email address
  1998. if ( $user_email == '' ) {
  1999. $errors->add( 'empty_email', __( '<strong>ERROR</strong>: Please type your email address.' ) );
  2000. } elseif ( ! is_email( $user_email ) ) {
  2001. $errors->add( 'invalid_email', __( '<strong>ERROR</strong>: The email address isn&#8217;t correct.' ) );
  2002. $user_email = '';
  2003. } elseif ( email_exists( $user_email ) ) {
  2004. $errors->add( 'email_exists', __( '<strong>ERROR</strong>: This email is already registered, please choose another one.' ) );
  2005. }
  2006. /**
  2007. * Fires when submitting registration form data, before the user is created.
  2008. *
  2009. * @since 2.1.0
  2010. *
  2011. * @param string $sanitized_user_login The submitted username after being sanitized.
  2012. * @param string $user_email The submitted email.
  2013. * @param WP_Error $errors Contains any errors with submitted username and email,
  2014. * e.g., an empty field, an invalid username or email,
  2015. * or an existing username or email.
  2016. */
  2017. do_action( 'register_post', $sanitized_user_login, $user_email, $errors );
  2018. /**
  2019. * Filters the errors encountered when a new user is being registered.
  2020. *
  2021. * The filtered WP_Error object may, for example, contain errors for an invalid
  2022. * or existing username or email address. A WP_Error object should always returned,
  2023. * but may or may not contain errors.
  2024. *
  2025. * If any errors are present in $errors, this will abort the user's registration.
  2026. *
  2027. * @since 2.1.0
  2028. *
  2029. * @param WP_Error $errors A WP_Error object containing any errors encountered
  2030. * during registration.
  2031. * @param string $sanitized_user_login User's username after it has been sanitized.
  2032. * @param string $user_email User's email.
  2033. */
  2034. $errors = apply_filters( 'registration_errors', $errors, $sanitized_user_login, $user_email );
  2035. if ( $errors->get_error_code() )
  2036. return $errors;
  2037. $user_pass = wp_generate_password( 12, false );
  2038. $user_id = wp_create_user( $sanitized_user_login, $user_pass, $user_email );
  2039. if ( ! $user_id || is_wp_error( $user_id ) ) {
  2040. $errors->add( 'registerfail', sprintf( __( '<strong>ERROR</strong>: Couldn&#8217;t register you&hellip; please contact the <a href="mailto:%s">webmaster</a> !' ), get_option( 'admin_email' ) ) );
  2041. return $errors;
  2042. }
  2043. update_user_option( $user_id, 'default_password_nag', true, true ); //Set up the Password change nag.
  2044. /**
  2045. * Fires after a new user registration has been recorded.
  2046. *
  2047. * @since 4.4.0
  2048. *
  2049. * @param int $user_id ID of the newly registered user.
  2050. */
  2051. do_action( 'register_new_user', $user_id );
  2052. return $user_id;
  2053. }
  2054. /**
  2055. * Initiates email notifications related to the creation of new users.
  2056. *
  2057. * Notifications are sent both to the site admin and to the newly created user.
  2058. *
  2059. * @since 4.4.0
  2060. * @since 4.6.0 Converted the `$notify` parameter to accept 'user' for sending
  2061. * notifications only to the user created.
  2062. *
  2063. * @param int $user_id ID of the newly created user.
  2064. * @param string $notify Optional. Type of notification that should happen. Accepts 'admin'
  2065. * or an empty string (admin only), 'user', or 'both' (admin and user).
  2066. * Default 'both'.
  2067. */
  2068. function wp_send_new_user_notifications( $user_id, $notify = 'both' ) {
  2069. wp_new_user_notification( $user_id, null, $notify );
  2070. }
  2071. /**
  2072. * Retrieve the current session token from the logged_in cookie.
  2073. *
  2074. * @since 4.0.0
  2075. *
  2076. * @return string Token.
  2077. */
  2078. function wp_get_session_token() {
  2079. $cookie = wp_parse_auth_cookie( '', 'logged_in' );
  2080. return ! empty( $cookie['token'] ) ? $cookie['token'] : '';
  2081. }
  2082. /**
  2083. * Retrieve a list of sessions for the current user.
  2084. *
  2085. * @since 4.0.0
  2086. * @return array Array of sessions.
  2087. */
  2088. function wp_get_all_sessions() {
  2089. $manager = WP_Session_Tokens::get_instance( get_current_user_id() );
  2090. return $manager->get_all();
  2091. }
  2092. /**
  2093. * Remove the current session token from the database.
  2094. *
  2095. * @since 4.0.0
  2096. */
  2097. function wp_destroy_current_session() {
  2098. $token = wp_get_session_token();
  2099. if ( $token ) {
  2100. $manager = WP_Session_Tokens::get_instance( get_current_user_id() );
  2101. $manager->destroy( $token );
  2102. }
  2103. }
  2104. /**
  2105. * Remove all but the current session token for the current user for the database.
  2106. *
  2107. * @since 4.0.0
  2108. */
  2109. function wp_destroy_other_sessions() {
  2110. $token = wp_get_session_token();
  2111. if ( $token ) {
  2112. $manager = WP_Session_Tokens::get_instance( get_current_user_id() );
  2113. $manager->destroy_others( $token );
  2114. }
  2115. }
  2116. /**
  2117. * Remove all session tokens for the current user from the database.
  2118. *
  2119. * @since 4.0.0
  2120. */
  2121. function wp_destroy_all_sessions() {
  2122. $manager = WP_Session_Tokens::get_instance( get_current_user_id() );
  2123. $manager->destroy_all();
  2124. }
  2125. /**
  2126. * Get the user IDs of all users with no role on this site.
  2127. *
  2128. * This function returns an empty array when used on Multisite.
  2129. *
  2130. * @since 4.4.0
  2131. *
  2132. * @return array Array of user IDs.
  2133. */
  2134. function wp_get_users_with_no_role() {
  2135. global $wpdb;
  2136. if ( is_multisite() ) {
  2137. return array();
  2138. }
  2139. $prefix = $wpdb->get_blog_prefix();
  2140. $regex = implode( '|', array_keys( wp_roles()->get_names() ) );
  2141. $regex = preg_replace( '/[^a-zA-Z_\|-]/', '', $regex );
  2142. $users = $wpdb->get_col( $wpdb->prepare( "
  2143. SELECT user_id
  2144. FROM $wpdb->usermeta
  2145. WHERE meta_key = '{$prefix}capabilities'
  2146. AND meta_value NOT REGEXP %s
  2147. ", $regex ) );
  2148. return $users;
  2149. }
  2150. /**
  2151. * Retrieves the current user object.
  2152. *
  2153. * Will set the current user, if the current user is not set. The current user
  2154. * will be set to the logged-in person. If no user is logged-in, then it will
  2155. * set the current user to 0, which is invalid and won't have any permissions.
  2156. *
  2157. * This function is used by the pluggable functions wp_get_current_user() and
  2158. * get_currentuserinfo(), the latter of which is deprecated but used for backward
  2159. * compatibility.
  2160. *
  2161. * @since 4.5.0
  2162. * @access private
  2163. *
  2164. * @see wp_get_current_user()
  2165. * @global WP_User $current_user Checks if the current user is set.
  2166. *
  2167. * @return WP_User Current WP_User instance.
  2168. */
  2169. function _wp_get_current_user() {
  2170. global $current_user;
  2171. if ( ! empty( $current_user ) ) {
  2172. if ( $current_user instanceof WP_User ) {
  2173. return $current_user;
  2174. }
  2175. // Upgrade stdClass to WP_User
  2176. if ( is_object( $current_user ) && isset( $current_user->ID ) ) {
  2177. $cur_id = $current_user->ID;
  2178. $current_user = null;
  2179. wp_set_current_user( $cur_id );
  2180. return $current_user;
  2181. }
  2182. // $current_user has a junk value. Force to WP_User with ID 0.
  2183. $current_user = null;
  2184. wp_set_current_user( 0 );
  2185. return $current_user;
  2186. }
  2187. if ( defined('XMLRPC_REQUEST') && XMLRPC_REQUEST ) {
  2188. wp_set_current_user( 0 );
  2189. return $current_user;
  2190. }
  2191. /**
  2192. * Filters the current user.
  2193. *
  2194. * The default filters use this to determine the current user from the
  2195. * request's cookies, if available.
  2196. *
  2197. * Returning a value of false will effectively short-circuit setting
  2198. * the current user.
  2199. *
  2200. * @since 3.9.0
  2201. *
  2202. * @param int|bool $user_id User ID if one has been determined, false otherwise.
  2203. */
  2204. $user_id = apply_filters( 'determine_current_user', false );
  2205. if ( ! $user_id ) {
  2206. wp_set_current_user( 0 );
  2207. return $current_user;
  2208. }
  2209. wp_set_current_user( $user_id );
  2210. return $current_user;
  2211. }