user.php 121 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709
  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. * Note: wp_signon() doesn't handle setting the current user. This means that if the
  20. * function is called before the {@see 'init'} hook is fired, is_user_logged_in() will
  21. * evaluate as false until that point. If is_user_logged_in() is needed in conjunction
  22. * with wp_signon(), wp_set_current_user() should be called explicitly.
  23. *
  24. * @since 2.5.0
  25. *
  26. * @global string $auth_secure_cookie
  27. *
  28. * @param array $credentials Optional. User info in order to sign on.
  29. * @param string|bool $secure_cookie Optional. Whether to use secure cookie.
  30. * @return WP_User|WP_Error WP_User on success, WP_Error on failure.
  31. */
  32. function wp_signon( $credentials = array(), $secure_cookie = '' ) {
  33. if ( empty( $credentials ) ) {
  34. $credentials = array(); // Back-compat for plugins passing an empty string.
  35. if ( ! empty( $_POST['log'] ) ) {
  36. $credentials['user_login'] = $_POST['log'];
  37. }
  38. if ( ! empty( $_POST['pwd'] ) ) {
  39. $credentials['user_password'] = $_POST['pwd'];
  40. }
  41. if ( ! empty( $_POST['rememberme'] ) ) {
  42. $credentials['remember'] = $_POST['rememberme'];
  43. }
  44. }
  45. if ( ! empty( $credentials['remember'] ) ) {
  46. $credentials['remember'] = true;
  47. } else {
  48. $credentials['remember'] = false;
  49. }
  50. /**
  51. * Fires before the user is authenticated.
  52. *
  53. * The variables passed to the callbacks are passed by reference,
  54. * and can be modified by callback functions.
  55. *
  56. * @since 1.5.1
  57. *
  58. * @todo Decide whether to deprecate the wp_authenticate action.
  59. *
  60. * @param string $user_login Username (passed by reference).
  61. * @param string $user_password User password (passed by reference).
  62. */
  63. do_action_ref_array( 'wp_authenticate', array( &$credentials['user_login'], &$credentials['user_password'] ) );
  64. if ( '' === $secure_cookie ) {
  65. $secure_cookie = is_ssl();
  66. }
  67. /**
  68. * Filters whether to use a secure sign-on cookie.
  69. *
  70. * @since 3.1.0
  71. *
  72. * @param bool $secure_cookie Whether to use a secure sign-on cookie.
  73. * @param array $credentials {
  74. * Array of entered sign-on data.
  75. *
  76. * @type string $user_login Username.
  77. * @type string $user_password Password entered.
  78. * @type bool $remember Whether to 'remember' the user. Increases the time
  79. * that the cookie will be kept. Default false.
  80. * }
  81. */
  82. $secure_cookie = apply_filters( 'secure_signon_cookie', $secure_cookie, $credentials );
  83. global $auth_secure_cookie; // XXX ugly hack to pass this to wp_authenticate_cookie
  84. $auth_secure_cookie = $secure_cookie;
  85. add_filter( 'authenticate', 'wp_authenticate_cookie', 30, 3 );
  86. $user = wp_authenticate( $credentials['user_login'], $credentials['user_password'] );
  87. if ( is_wp_error( $user ) ) {
  88. return $user;
  89. }
  90. wp_set_auth_cookie( $user->ID, $credentials['remember'], $secure_cookie );
  91. /**
  92. * Fires after the user has successfully logged in.
  93. *
  94. * @since 1.5.0
  95. *
  96. * @param string $user_login Username.
  97. * @param WP_User $user WP_User object of the logged-in user.
  98. */
  99. do_action( 'wp_login', $user->user_login, $user );
  100. return $user;
  101. }
  102. /**
  103. * Authenticate a user, confirming the username and password are valid.
  104. *
  105. * @since 2.8.0
  106. *
  107. * @param WP_User|WP_Error|null $user WP_User or WP_Error object from a previous callback. Default null.
  108. * @param string $username Username for authentication.
  109. * @param string $password Password for authentication.
  110. * @return WP_User|WP_Error WP_User on success, WP_Error on failure.
  111. */
  112. function wp_authenticate_username_password( $user, $username, $password ) {
  113. if ( $user instanceof WP_User ) {
  114. return $user;
  115. }
  116. if ( empty( $username ) || empty( $password ) ) {
  117. if ( is_wp_error( $user ) ) {
  118. return $user;
  119. }
  120. $error = new WP_Error();
  121. if ( empty( $username ) ) {
  122. $error->add( 'empty_username', __( '<strong>ERROR</strong>: The username field is empty.' ) );
  123. }
  124. if ( empty( $password ) ) {
  125. $error->add( 'empty_password', __( '<strong>ERROR</strong>: The password field is empty.' ) );
  126. }
  127. return $error;
  128. }
  129. $user = get_user_by( 'login', $username );
  130. if ( ! $user ) {
  131. return new WP_Error(
  132. 'invalid_username',
  133. __( 'Unknown username. Check again or try your email address.' )
  134. );
  135. }
  136. /**
  137. * Filters whether the given user can be authenticated with the provided $password.
  138. *
  139. * @since 2.5.0
  140. *
  141. * @param WP_User|WP_Error $user WP_User or WP_Error object if a previous
  142. * callback failed authentication.
  143. * @param string $password Password to check against the user.
  144. */
  145. $user = apply_filters( 'wp_authenticate_user', $user, $password );
  146. if ( is_wp_error( $user ) ) {
  147. return $user;
  148. }
  149. if ( ! wp_check_password( $password, $user->user_pass, $user->ID ) ) {
  150. return new WP_Error(
  151. 'incorrect_password',
  152. sprintf(
  153. /* translators: %s: User name. */
  154. __( '<strong>ERROR</strong>: The password you entered for the username %s is incorrect.' ),
  155. '<strong>' . $username . '</strong>'
  156. ) .
  157. ' <a href="' . wp_lostpassword_url() . '">' .
  158. __( 'Lost your password?' ) .
  159. '</a>'
  160. );
  161. }
  162. return $user;
  163. }
  164. /**
  165. * Authenticates a user using the email and password.
  166. *
  167. * @since 4.5.0
  168. *
  169. * @param WP_User|WP_Error|null $user WP_User or WP_Error object if a previous
  170. * callback failed authentication.
  171. * @param string $email Email address for authentication.
  172. * @param string $password Password for authentication.
  173. * @return WP_User|WP_Error WP_User on success, WP_Error on failure.
  174. */
  175. function wp_authenticate_email_password( $user, $email, $password ) {
  176. if ( $user instanceof WP_User ) {
  177. return $user;
  178. }
  179. if ( empty( $email ) || empty( $password ) ) {
  180. if ( is_wp_error( $user ) ) {
  181. return $user;
  182. }
  183. $error = new WP_Error();
  184. if ( empty( $email ) ) {
  185. $error->add( 'empty_username', __( '<strong>ERROR</strong>: The email field is empty.' ) ); // Uses 'empty_username' for back-compat with wp_signon()
  186. }
  187. if ( empty( $password ) ) {
  188. $error->add( 'empty_password', __( '<strong>ERROR</strong>: The password field is empty.' ) );
  189. }
  190. return $error;
  191. }
  192. if ( ! is_email( $email ) ) {
  193. return $user;
  194. }
  195. $user = get_user_by( 'email', $email );
  196. if ( ! $user ) {
  197. return new WP_Error(
  198. 'invalid_email',
  199. __( 'Unknown email address. Check again or try your username.' )
  200. );
  201. }
  202. /** This filter is documented in wp-includes/user.php */
  203. $user = apply_filters( 'wp_authenticate_user', $user, $password );
  204. if ( is_wp_error( $user ) ) {
  205. return $user;
  206. }
  207. if ( ! wp_check_password( $password, $user->user_pass, $user->ID ) ) {
  208. return new WP_Error(
  209. 'incorrect_password',
  210. sprintf(
  211. /* translators: %s: Email address. */
  212. __( '<strong>ERROR</strong>: The password you entered for the email address %s is incorrect.' ),
  213. '<strong>' . $email . '</strong>'
  214. ) .
  215. ' <a href="' . wp_lostpassword_url() . '">' .
  216. __( 'Lost your password?' ) .
  217. '</a>'
  218. );
  219. }
  220. return $user;
  221. }
  222. /**
  223. * Authenticate the user using the WordPress auth cookie.
  224. *
  225. * @since 2.8.0
  226. *
  227. * @global string $auth_secure_cookie
  228. *
  229. * @param WP_User|WP_Error|null $user WP_User or WP_Error object from a previous callback. Default null.
  230. * @param string $username Username. If not empty, cancels the cookie authentication.
  231. * @param string $password Password. If not empty, cancels the cookie authentication.
  232. * @return WP_User|WP_Error WP_User on success, WP_Error on failure.
  233. */
  234. function wp_authenticate_cookie( $user, $username, $password ) {
  235. if ( $user instanceof WP_User ) {
  236. return $user;
  237. }
  238. if ( empty( $username ) && empty( $password ) ) {
  239. $user_id = wp_validate_auth_cookie();
  240. if ( $user_id ) {
  241. return new WP_User( $user_id );
  242. }
  243. global $auth_secure_cookie;
  244. if ( $auth_secure_cookie ) {
  245. $auth_cookie = SECURE_AUTH_COOKIE;
  246. } else {
  247. $auth_cookie = AUTH_COOKIE;
  248. }
  249. if ( ! empty( $_COOKIE[ $auth_cookie ] ) ) {
  250. return new WP_Error( 'expired_session', __( 'Please log in again.' ) );
  251. }
  252. // If the cookie is not set, be silent.
  253. }
  254. return $user;
  255. }
  256. /**
  257. * For Multisite blogs, check if the authenticated user has been marked as a
  258. * spammer, or if the user's primary blog has been marked as spam.
  259. *
  260. * @since 3.7.0
  261. *
  262. * @param WP_User|WP_Error|null $user WP_User or WP_Error object from a previous callback. Default null.
  263. * @return WP_User|WP_Error WP_User on success, WP_Error if the user is considered a spammer.
  264. */
  265. function wp_authenticate_spam_check( $user ) {
  266. if ( $user instanceof WP_User && is_multisite() ) {
  267. /**
  268. * Filters whether the user has been marked as a spammer.
  269. *
  270. * @since 3.7.0
  271. *
  272. * @param bool $spammed Whether the user is considered a spammer.
  273. * @param WP_User $user User to check against.
  274. */
  275. $spammed = apply_filters( 'check_is_user_spammed', is_user_spammy( $user ), $user );
  276. if ( $spammed ) {
  277. return new WP_Error( 'spammer_account', __( '<strong>ERROR</strong>: Your account has been marked as a spammer.' ) );
  278. }
  279. }
  280. return $user;
  281. }
  282. /**
  283. * Validates the logged-in cookie.
  284. *
  285. * Checks the logged-in cookie if the previous auth cookie could not be
  286. * validated and parsed.
  287. *
  288. * This is a callback for the {@see 'determine_current_user'} filter, rather than API.
  289. *
  290. * @since 3.9.0
  291. *
  292. * @param int|bool $user_id The user ID (or false) as received from the
  293. * determine_current_user filter.
  294. * @return int|false User ID if validated, false otherwise. If a user ID from
  295. * an earlier filter callback is received, that value is returned.
  296. */
  297. function wp_validate_logged_in_cookie( $user_id ) {
  298. if ( $user_id ) {
  299. return $user_id;
  300. }
  301. if ( is_blog_admin() || is_network_admin() || empty( $_COOKIE[ LOGGED_IN_COOKIE ] ) ) {
  302. return false;
  303. }
  304. return wp_validate_auth_cookie( $_COOKIE[ LOGGED_IN_COOKIE ], 'logged_in' );
  305. }
  306. /**
  307. * Number of posts user has written.
  308. *
  309. * @since 3.0.0
  310. * @since 4.1.0 Added `$post_type` argument.
  311. * @since 4.3.0 Added `$public_only` argument. Added the ability to pass an array
  312. * of post types to `$post_type`.
  313. *
  314. * @global wpdb $wpdb WordPress database abstraction object.
  315. *
  316. * @param int $userid User ID.
  317. * @param array|string $post_type Optional. Single post type or array of post types to count the number of posts for. Default 'post'.
  318. * @param bool $public_only Optional. Whether to only return counts for public posts. Default false.
  319. * @return string Number of posts the user has written in this post type.
  320. */
  321. function count_user_posts( $userid, $post_type = 'post', $public_only = false ) {
  322. global $wpdb;
  323. $where = get_posts_by_author_sql( $post_type, true, $userid, $public_only );
  324. $count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->posts $where" );
  325. /**
  326. * Filters the number of posts a user has written.
  327. *
  328. * @since 2.7.0
  329. * @since 4.1.0 Added `$post_type` argument.
  330. * @since 4.3.1 Added `$public_only` argument.
  331. *
  332. * @param int $count The user's post count.
  333. * @param int $userid User ID.
  334. * @param string|array $post_type Single post type or array of post types to count the number of posts for.
  335. * @param bool $public_only Whether to limit counted posts to public posts.
  336. */
  337. return apply_filters( 'get_usernumposts', $count, $userid, $post_type, $public_only );
  338. }
  339. /**
  340. * Number of posts written by a list of users.
  341. *
  342. * @since 3.0.0
  343. *
  344. * @global wpdb $wpdb WordPress database abstraction object.
  345. *
  346. * @param array $users Array of user IDs.
  347. * @param string|array $post_type Optional. Single post type or array of post types to check. Defaults to 'post'.
  348. * @param bool $public_only Optional. Only return counts for public posts. Defaults to false.
  349. * @return array Amount of posts each user has written.
  350. */
  351. function count_many_users_posts( $users, $post_type = 'post', $public_only = false ) {
  352. global $wpdb;
  353. $count = array();
  354. if ( empty( $users ) || ! is_array( $users ) ) {
  355. return $count;
  356. }
  357. $userlist = implode( ',', array_map( 'absint', $users ) );
  358. $where = get_posts_by_author_sql( $post_type, true, null, $public_only );
  359. $result = $wpdb->get_results( "SELECT post_author, COUNT(*) FROM $wpdb->posts $where AND post_author IN ($userlist) GROUP BY post_author", ARRAY_N );
  360. foreach ( $result as $row ) {
  361. $count[ $row[0] ] = $row[1];
  362. }
  363. foreach ( $users as $id ) {
  364. if ( ! isset( $count[ $id ] ) ) {
  365. $count[ $id ] = 0;
  366. }
  367. }
  368. return $count;
  369. }
  370. //
  371. // User option functions
  372. //
  373. /**
  374. * Get the current user's ID
  375. *
  376. * @since MU (3.0.0)
  377. *
  378. * @return int The current user's ID, or 0 if no user is logged in.
  379. */
  380. function get_current_user_id() {
  381. if ( ! function_exists( 'wp_get_current_user' ) ) {
  382. return 0;
  383. }
  384. $user = wp_get_current_user();
  385. return ( isset( $user->ID ) ? (int) $user->ID : 0 );
  386. }
  387. /**
  388. * Retrieve user option that can be either per Site or per Network.
  389. *
  390. * If the user ID is not given, then the current user will be used instead. If
  391. * the user ID is given, then the user data will be retrieved. The filter for
  392. * the result, will also pass the original option name and finally the user data
  393. * object as the third parameter.
  394. *
  395. * The option will first check for the per site name and then the per Network name.
  396. *
  397. * @since 2.0.0
  398. *
  399. * @global wpdb $wpdb WordPress database abstraction object.
  400. *
  401. * @param string $option User option name.
  402. * @param int $user Optional. User ID.
  403. * @param string $deprecated Use get_option() to check for an option in the options table.
  404. * @return mixed User option value on success, false on failure.
  405. */
  406. function get_user_option( $option, $user = 0, $deprecated = '' ) {
  407. global $wpdb;
  408. if ( ! empty( $deprecated ) ) {
  409. _deprecated_argument( __FUNCTION__, '3.0.0' );
  410. }
  411. if ( empty( $user ) ) {
  412. $user = get_current_user_id();
  413. }
  414. $user = get_userdata( $user );
  415. if ( ! $user ) {
  416. return false;
  417. }
  418. $prefix = $wpdb->get_blog_prefix();
  419. if ( $user->has_prop( $prefix . $option ) ) { // Blog specific
  420. $result = $user->get( $prefix . $option );
  421. } elseif ( $user->has_prop( $option ) ) { // User specific and cross-blog
  422. $result = $user->get( $option );
  423. } else {
  424. $result = false;
  425. }
  426. /**
  427. * Filters a specific user option value.
  428. *
  429. * The dynamic portion of the hook name, `$option`, refers to the user option name.
  430. *
  431. * @since 2.5.0
  432. *
  433. * @param mixed $result Value for the user's option.
  434. * @param string $option Name of the option being retrieved.
  435. * @param WP_User $user WP_User object of the user whose option is being retrieved.
  436. */
  437. return apply_filters( "get_user_option_{$option}", $result, $option, $user );
  438. }
  439. /**
  440. * Update user option with global blog capability.
  441. *
  442. * User options are just like user metadata except that they have support for
  443. * global blog options. If the 'global' parameter is false, which it is by default
  444. * it will prepend the WordPress table prefix to the option name.
  445. *
  446. * Deletes the user option if $newvalue is empty.
  447. *
  448. * @since 2.0.0
  449. *
  450. * @global wpdb $wpdb WordPress database abstraction object.
  451. *
  452. * @param int $user_id User ID.
  453. * @param string $option_name User option name.
  454. * @param mixed $newvalue User option value.
  455. * @param bool $global Optional. Whether option name is global or blog specific.
  456. * Default false (blog specific).
  457. * @return int|bool User meta ID if the option didn't exist, true on successful update,
  458. * false on failure.
  459. */
  460. function update_user_option( $user_id, $option_name, $newvalue, $global = false ) {
  461. global $wpdb;
  462. if ( ! $global ) {
  463. $option_name = $wpdb->get_blog_prefix() . $option_name;
  464. }
  465. return update_user_meta( $user_id, $option_name, $newvalue );
  466. }
  467. /**
  468. * Delete user option with global blog capability.
  469. *
  470. * User options are just like user metadata except that they have support for
  471. * global blog options. If the 'global' parameter is false, which it is by default
  472. * it will prepend the WordPress table prefix to the option name.
  473. *
  474. * @since 3.0.0
  475. *
  476. * @global wpdb $wpdb WordPress database abstraction object.
  477. *
  478. * @param int $user_id User ID
  479. * @param string $option_name User option name.
  480. * @param bool $global Optional. Whether option name is global or blog specific.
  481. * Default false (blog specific).
  482. * @return bool True on success, false on failure.
  483. */
  484. function delete_user_option( $user_id, $option_name, $global = false ) {
  485. global $wpdb;
  486. if ( ! $global ) {
  487. $option_name = $wpdb->get_blog_prefix() . $option_name;
  488. }
  489. return delete_user_meta( $user_id, $option_name );
  490. }
  491. /**
  492. * Retrieve list of users matching criteria.
  493. *
  494. * @since 3.1.0
  495. *
  496. * @see WP_User_Query
  497. *
  498. * @param array $args Optional. Arguments to retrieve users. See WP_User_Query::prepare_query().
  499. * for more information on accepted arguments.
  500. * @return array List of users.
  501. */
  502. function get_users( $args = array() ) {
  503. $args = wp_parse_args( $args );
  504. $args['count_total'] = false;
  505. $user_search = new WP_User_Query( $args );
  506. return (array) $user_search->get_results();
  507. }
  508. /**
  509. * Get the sites a user belongs to.
  510. *
  511. * @since 3.0.0
  512. * @since 4.7.0 Converted to use `get_sites()`.
  513. *
  514. * @global wpdb $wpdb WordPress database abstraction object.
  515. *
  516. * @param int $user_id User ID
  517. * @param bool $all Whether to retrieve all sites, or only sites that are not
  518. * marked as deleted, archived, or spam.
  519. * @return array A list of the user's sites. An empty array if the user doesn't exist
  520. * or belongs to no sites.
  521. */
  522. function get_blogs_of_user( $user_id, $all = false ) {
  523. global $wpdb;
  524. $user_id = (int) $user_id;
  525. // Logged out users can't have sites
  526. if ( empty( $user_id ) ) {
  527. return array();
  528. }
  529. /**
  530. * Filters the list of a user's sites before it is populated.
  531. *
  532. * Passing a non-null value to the filter will effectively short circuit
  533. * get_blogs_of_user(), returning that value instead.
  534. *
  535. * @since 4.6.0
  536. *
  537. * @param null|array $sites An array of site objects of which the user is a member.
  538. * @param int $user_id User ID.
  539. * @param bool $all Whether the returned array should contain all sites, including
  540. * those marked 'deleted', 'archived', or 'spam'. Default false.
  541. */
  542. $sites = apply_filters( 'pre_get_blogs_of_user', null, $user_id, $all );
  543. if ( null !== $sites ) {
  544. return $sites;
  545. }
  546. $keys = get_user_meta( $user_id );
  547. if ( empty( $keys ) ) {
  548. return array();
  549. }
  550. if ( ! is_multisite() ) {
  551. $site_id = get_current_blog_id();
  552. $sites = array( $site_id => new stdClass );
  553. $sites[ $site_id ]->userblog_id = $site_id;
  554. $sites[ $site_id ]->blogname = get_option( 'blogname' );
  555. $sites[ $site_id ]->domain = '';
  556. $sites[ $site_id ]->path = '';
  557. $sites[ $site_id ]->site_id = 1;
  558. $sites[ $site_id ]->siteurl = get_option( 'siteurl' );
  559. $sites[ $site_id ]->archived = 0;
  560. $sites[ $site_id ]->spam = 0;
  561. $sites[ $site_id ]->deleted = 0;
  562. return $sites;
  563. }
  564. $site_ids = array();
  565. if ( isset( $keys[ $wpdb->base_prefix . 'capabilities' ] ) && defined( 'MULTISITE' ) ) {
  566. $site_ids[] = 1;
  567. unset( $keys[ $wpdb->base_prefix . 'capabilities' ] );
  568. }
  569. $keys = array_keys( $keys );
  570. foreach ( $keys as $key ) {
  571. if ( 'capabilities' !== substr( $key, -12 ) ) {
  572. continue;
  573. }
  574. if ( $wpdb->base_prefix && 0 !== strpos( $key, $wpdb->base_prefix ) ) {
  575. continue;
  576. }
  577. $site_id = str_replace( array( $wpdb->base_prefix, '_capabilities' ), '', $key );
  578. if ( ! is_numeric( $site_id ) ) {
  579. continue;
  580. }
  581. $site_ids[] = (int) $site_id;
  582. }
  583. $sites = array();
  584. if ( ! empty( $site_ids ) ) {
  585. $args = array(
  586. 'number' => '',
  587. 'site__in' => $site_ids,
  588. 'update_site_meta_cache' => false,
  589. );
  590. if ( ! $all ) {
  591. $args['archived'] = 0;
  592. $args['spam'] = 0;
  593. $args['deleted'] = 0;
  594. }
  595. $_sites = get_sites( $args );
  596. foreach ( $_sites as $site ) {
  597. $sites[ $site->id ] = (object) array(
  598. 'userblog_id' => $site->id,
  599. 'blogname' => $site->blogname,
  600. 'domain' => $site->domain,
  601. 'path' => $site->path,
  602. 'site_id' => $site->network_id,
  603. 'siteurl' => $site->siteurl,
  604. 'archived' => $site->archived,
  605. 'mature' => $site->mature,
  606. 'spam' => $site->spam,
  607. 'deleted' => $site->deleted,
  608. );
  609. }
  610. }
  611. /**
  612. * Filters the list of sites a user belongs to.
  613. *
  614. * @since MU (3.0.0)
  615. *
  616. * @param array $sites An array of site objects belonging to the user.
  617. * @param int $user_id User ID.
  618. * @param bool $all Whether the returned sites array should contain all sites, including
  619. * those marked 'deleted', 'archived', or 'spam'. Default false.
  620. */
  621. return apply_filters( 'get_blogs_of_user', $sites, $user_id, $all );
  622. }
  623. /**
  624. * Find out whether a user is a member of a given blog.
  625. *
  626. * @since MU (3.0.0)
  627. *
  628. * @global wpdb $wpdb WordPress database abstraction object.
  629. *
  630. * @param int $user_id Optional. The unique ID of the user. Defaults to the current user.
  631. * @param int $blog_id Optional. ID of the blog to check. Defaults to the current site.
  632. * @return bool
  633. */
  634. function is_user_member_of_blog( $user_id = 0, $blog_id = 0 ) {
  635. global $wpdb;
  636. $user_id = (int) $user_id;
  637. $blog_id = (int) $blog_id;
  638. if ( empty( $user_id ) ) {
  639. $user_id = get_current_user_id();
  640. }
  641. // Technically not needed, but does save calls to get_site and get_user_meta
  642. // in the event that the function is called when a user isn't logged in
  643. if ( empty( $user_id ) ) {
  644. return false;
  645. } else {
  646. $user = get_userdata( $user_id );
  647. if ( ! $user instanceof WP_User ) {
  648. return false;
  649. }
  650. }
  651. if ( ! is_multisite() ) {
  652. return true;
  653. }
  654. if ( empty( $blog_id ) ) {
  655. $blog_id = get_current_blog_id();
  656. }
  657. $blog = get_site( $blog_id );
  658. if ( ! $blog || ! isset( $blog->domain ) || $blog->archived || $blog->spam || $blog->deleted ) {
  659. return false;
  660. }
  661. $keys = get_user_meta( $user_id );
  662. if ( empty( $keys ) ) {
  663. return false;
  664. }
  665. // no underscore before capabilities in $base_capabilities_key
  666. $base_capabilities_key = $wpdb->base_prefix . 'capabilities';
  667. $site_capabilities_key = $wpdb->base_prefix . $blog_id . '_capabilities';
  668. if ( isset( $keys[ $base_capabilities_key ] ) && $blog_id == 1 ) {
  669. return true;
  670. }
  671. if ( isset( $keys[ $site_capabilities_key ] ) ) {
  672. return true;
  673. }
  674. return false;
  675. }
  676. /**
  677. * Adds meta data to a user.
  678. *
  679. * @since 3.0.0
  680. *
  681. * @param int $user_id User ID.
  682. * @param string $meta_key Metadata name.
  683. * @param mixed $meta_value Metadata value.
  684. * @param bool $unique Optional. Whether the same key should not be added. Default false.
  685. * @return int|false Meta ID on success, false on failure.
  686. */
  687. function add_user_meta( $user_id, $meta_key, $meta_value, $unique = false ) {
  688. return add_metadata( 'user', $user_id, $meta_key, $meta_value, $unique );
  689. }
  690. /**
  691. * Remove metadata matching criteria from a user.
  692. *
  693. * You can match based on the key, or key and value. Removing based on key and
  694. * value, will keep from removing duplicate metadata with the same key. It also
  695. * allows removing all metadata matching key, if needed.
  696. *
  697. * @since 3.0.0
  698. * @link https://developer.wordpress.org/reference/functions/delete_user_meta/
  699. *
  700. * @param int $user_id User ID
  701. * @param string $meta_key Metadata name.
  702. * @param mixed $meta_value Optional. Metadata value.
  703. * @return bool True on success, false on failure.
  704. */
  705. function delete_user_meta( $user_id, $meta_key, $meta_value = '' ) {
  706. return delete_metadata( 'user', $user_id, $meta_key, $meta_value );
  707. }
  708. /**
  709. * Retrieve user meta field for a user.
  710. *
  711. * @since 3.0.0
  712. * @link https://developer.wordpress.org/reference/functions/get_user_meta/
  713. *
  714. * @param int $user_id User ID.
  715. * @param string $key Optional. The meta key to retrieve. By default, returns data for all keys.
  716. * @param bool $single Whether to return a single value.
  717. * @return mixed Will be an array if $single is false. Will be value of meta data field if $single is true.
  718. */
  719. function get_user_meta( $user_id, $key = '', $single = false ) {
  720. return get_metadata( 'user', $user_id, $key, $single );
  721. }
  722. /**
  723. * Update user meta field based on user ID.
  724. *
  725. * Use the $prev_value parameter to differentiate between meta fields with the
  726. * same key and user ID.
  727. *
  728. * If the meta field for the user does not exist, it will be added.
  729. *
  730. * @since 3.0.0
  731. * @link https://developer.wordpress.org/reference/functions/update_user_meta/
  732. *
  733. * @param int $user_id User ID.
  734. * @param string $meta_key Metadata key.
  735. * @param mixed $meta_value Metadata value.
  736. * @param mixed $prev_value Optional. Previous value to check before removing.
  737. * @return int|bool Meta ID if the key didn't exist, true on successful update, false on failure.
  738. */
  739. function update_user_meta( $user_id, $meta_key, $meta_value, $prev_value = '' ) {
  740. return update_metadata( 'user', $user_id, $meta_key, $meta_value, $prev_value );
  741. }
  742. /**
  743. * Count number of users who have each of the user roles.
  744. *
  745. * Assumes there are neither duplicated nor orphaned capabilities meta_values.
  746. * Assumes role names are unique phrases. Same assumption made by WP_User_Query::prepare_query()
  747. * Using $strategy = 'time' this is CPU-intensive and should handle around 10^7 users.
  748. * Using $strategy = 'memory' this is memory-intensive and should handle around 10^5 users, but see WP Bug #12257.
  749. *
  750. * @since 3.0.0
  751. * @since 4.4.0 The number of users with no role is now included in the `none` element.
  752. * @since 4.9.0 The `$site_id` parameter was added to support multisite.
  753. *
  754. * @global wpdb $wpdb WordPress database abstraction object.
  755. *
  756. * @param string $strategy Optional. The computational strategy to use when counting the users.
  757. * Accepts either 'time' or 'memory'. Default 'time'.
  758. * @param int|null $site_id Optional. The site ID to count users for. Defaults to the current site.
  759. * @return array Includes a grand total and an array of counts indexed by role strings.
  760. */
  761. function count_users( $strategy = 'time', $site_id = null ) {
  762. global $wpdb;
  763. // Initialize
  764. if ( ! $site_id ) {
  765. $site_id = get_current_blog_id();
  766. }
  767. /**
  768. * Filter the user count before queries are run. Return a non-null value to cause count_users()
  769. * to return early.
  770. *
  771. * @since 5.1.0
  772. *
  773. * @param null|string $result Default null.
  774. * @param string $strategy Optional. The computational strategy to use when counting the users.
  775. * Accepts either 'time' or 'memory'. Default 'time'.
  776. * @param int|null $site_id Optional. The site ID to count users for. Defaults to the current site.
  777. */
  778. $pre = apply_filters( 'pre_count_users', null, $strategy, $site_id );
  779. if ( null !== $pre ) {
  780. return $pre;
  781. }
  782. $blog_prefix = $wpdb->get_blog_prefix( $site_id );
  783. $result = array();
  784. if ( 'time' == $strategy ) {
  785. if ( is_multisite() && $site_id != get_current_blog_id() ) {
  786. switch_to_blog( $site_id );
  787. $avail_roles = wp_roles()->get_names();
  788. restore_current_blog();
  789. } else {
  790. $avail_roles = wp_roles()->get_names();
  791. }
  792. // Build a CPU-intensive query that will return concise information.
  793. $select_count = array();
  794. foreach ( $avail_roles as $this_role => $name ) {
  795. $select_count[] = $wpdb->prepare( 'COUNT(NULLIF(`meta_value` LIKE %s, false))', '%' . $wpdb->esc_like( '"' . $this_role . '"' ) . '%' );
  796. }
  797. $select_count[] = "COUNT(NULLIF(`meta_value` = 'a:0:{}', false))";
  798. $select_count = implode( ', ', $select_count );
  799. // Add the meta_value index to the selection list, then run the query.
  800. $row = $wpdb->get_row(
  801. "
  802. SELECT {$select_count}, COUNT(*)
  803. FROM {$wpdb->usermeta}
  804. INNER JOIN {$wpdb->users} ON user_id = ID
  805. WHERE meta_key = '{$blog_prefix}capabilities'
  806. ",
  807. ARRAY_N
  808. );
  809. // Run the previous loop again to associate results with role names.
  810. $col = 0;
  811. $role_counts = array();
  812. foreach ( $avail_roles as $this_role => $name ) {
  813. $count = (int) $row[ $col++ ];
  814. if ( $count > 0 ) {
  815. $role_counts[ $this_role ] = $count;
  816. }
  817. }
  818. $role_counts['none'] = (int) $row[ $col++ ];
  819. // Get the meta_value index from the end of the result set.
  820. $total_users = (int) $row[ $col ];
  821. $result['total_users'] = $total_users;
  822. $result['avail_roles'] =& $role_counts;
  823. } else {
  824. $avail_roles = array(
  825. 'none' => 0,
  826. );
  827. $users_of_blog = $wpdb->get_col(
  828. "
  829. SELECT meta_value
  830. FROM {$wpdb->usermeta}
  831. INNER JOIN {$wpdb->users} ON user_id = ID
  832. WHERE meta_key = '{$blog_prefix}capabilities'
  833. "
  834. );
  835. foreach ( $users_of_blog as $caps_meta ) {
  836. $b_roles = maybe_unserialize( $caps_meta );
  837. if ( ! is_array( $b_roles ) ) {
  838. continue;
  839. }
  840. if ( empty( $b_roles ) ) {
  841. $avail_roles['none']++;
  842. }
  843. foreach ( $b_roles as $b_role => $val ) {
  844. if ( isset( $avail_roles[ $b_role ] ) ) {
  845. $avail_roles[ $b_role ]++;
  846. } else {
  847. $avail_roles[ $b_role ] = 1;
  848. }
  849. }
  850. }
  851. $result['total_users'] = count( $users_of_blog );
  852. $result['avail_roles'] =& $avail_roles;
  853. }
  854. return $result;
  855. }
  856. //
  857. // Private helper functions
  858. //
  859. /**
  860. * Set up global user vars.
  861. *
  862. * Used by wp_set_current_user() for back compat. Might be deprecated in the future.
  863. *
  864. * @since 2.0.4
  865. *
  866. * @global string $user_login The user username for logging in
  867. * @global WP_User $userdata User data.
  868. * @global int $user_level The level of the user
  869. * @global int $user_ID The ID of the user
  870. * @global string $user_email The email address of the user
  871. * @global string $user_url The url in the user's profile
  872. * @global string $user_identity The display name of the user
  873. *
  874. * @param int $for_user_id Optional. User ID to set up global data. Default 0.
  875. */
  876. function setup_userdata( $for_user_id = 0 ) {
  877. global $user_login, $userdata, $user_level, $user_ID, $user_email, $user_url, $user_identity;
  878. if ( ! $for_user_id ) {
  879. $for_user_id = get_current_user_id();
  880. }
  881. $user = get_userdata( $for_user_id );
  882. if ( ! $user ) {
  883. $user_ID = 0;
  884. $user_level = 0;
  885. $userdata = null;
  886. $user_login = '';
  887. $user_email = '';
  888. $user_url = '';
  889. $user_identity = '';
  890. return;
  891. }
  892. $user_ID = (int) $user->ID;
  893. $user_level = (int) $user->user_level;
  894. $userdata = $user;
  895. $user_login = $user->user_login;
  896. $user_email = $user->user_email;
  897. $user_url = $user->user_url;
  898. $user_identity = $user->display_name;
  899. }
  900. /**
  901. * Create dropdown HTML content of users.
  902. *
  903. * The content can either be displayed, which it is by default or retrieved by
  904. * setting the 'echo' argument. The 'include' and 'exclude' arguments do not
  905. * need to be used; all users will be displayed in that case. Only one can be
  906. * used, either 'include' or 'exclude', but not both.
  907. *
  908. * The available arguments are as follows:
  909. *
  910. * @since 2.3.0
  911. * @since 4.5.0 Added the 'display_name_with_login' value for 'show'.
  912. * @since 4.7.0 Added the `$role`, `$role__in`, and `$role__not_in` parameters.
  913. *
  914. * @param array|string $args {
  915. * Optional. Array or string of arguments to generate a drop-down of users.
  916. * See WP_User_Query::prepare_query() for additional available arguments.
  917. *
  918. * @type string $show_option_all Text to show as the drop-down default (all).
  919. * Default empty.
  920. * @type string $show_option_none Text to show as the drop-down default when no
  921. * users were found. Default empty.
  922. * @type int|string $option_none_value Value to use for $show_option_non when no users
  923. * were found. Default -1.
  924. * @type string $hide_if_only_one_author Whether to skip generating the drop-down
  925. * if only one user was found. Default empty.
  926. * @type string $orderby Field to order found users by. Accepts user fields.
  927. * Default 'display_name'.
  928. * @type string $order Whether to order users in ascending or descending
  929. * order. Accepts 'ASC' (ascending) or 'DESC' (descending).
  930. * Default 'ASC'.
  931. * @type array|string $include Array or comma-separated list of user IDs to include.
  932. * Default empty.
  933. * @type array|string $exclude Array or comma-separated list of user IDs to exclude.
  934. * Default empty.
  935. * @type bool|int $multi Whether to skip the ID attribute on the 'select' element.
  936. * Accepts 1|true or 0|false. Default 0|false.
  937. * @type string $show User data to display. If the selected item is empty
  938. * then the 'user_login' will be displayed in parentheses.
  939. * Accepts any user field, or 'display_name_with_login' to show
  940. * the display name with user_login in parentheses.
  941. * Default 'display_name'.
  942. * @type int|bool $echo Whether to echo or return the drop-down. Accepts 1|true (echo)
  943. * or 0|false (return). Default 1|true.
  944. * @type int $selected Which user ID should be selected. Default 0.
  945. * @type bool $include_selected Whether to always include the selected user ID in the drop-
  946. * down. Default false.
  947. * @type string $name Name attribute of select element. Default 'user'.
  948. * @type string $id ID attribute of the select element. Default is the value of $name.
  949. * @type string $class Class attribute of the select element. Default empty.
  950. * @type int $blog_id ID of blog (Multisite only). Default is ID of the current blog.
  951. * @type string $who Which type of users to query. Accepts only an empty string or
  952. * 'authors'. Default empty.
  953. * @type string|array $role An array or a comma-separated list of role names that users must
  954. * match to be included in results. Note that this is an inclusive
  955. * list: users must match *each* role. Default empty.
  956. * @type array $role__in An array of role names. Matched users must have at least one of
  957. * these roles. Default empty array.
  958. * @type array $role__not_in An array of role names to exclude. Users matching one or more of
  959. * these roles will not be included in results. Default empty array.
  960. * }
  961. * @return string String of HTML content.
  962. */
  963. function wp_dropdown_users( $args = '' ) {
  964. $defaults = array(
  965. 'show_option_all' => '',
  966. 'show_option_none' => '',
  967. 'hide_if_only_one_author' => '',
  968. 'orderby' => 'display_name',
  969. 'order' => 'ASC',
  970. 'include' => '',
  971. 'exclude' => '',
  972. 'multi' => 0,
  973. 'show' => 'display_name',
  974. 'echo' => 1,
  975. 'selected' => 0,
  976. 'name' => 'user',
  977. 'class' => '',
  978. 'id' => '',
  979. 'blog_id' => get_current_blog_id(),
  980. 'who' => '',
  981. 'include_selected' => false,
  982. 'option_none_value' => -1,
  983. 'role' => '',
  984. 'role__in' => array(),
  985. 'role__not_in' => array(),
  986. );
  987. $defaults['selected'] = is_author() ? get_query_var( 'author' ) : 0;
  988. $parsed_args = wp_parse_args( $args, $defaults );
  989. $query_args = wp_array_slice_assoc( $parsed_args, array( 'blog_id', 'include', 'exclude', 'orderby', 'order', 'who', 'role', 'role__in', 'role__not_in' ) );
  990. $fields = array( 'ID', 'user_login' );
  991. $show = ! empty( $parsed_args['show'] ) ? $parsed_args['show'] : 'display_name';
  992. if ( 'display_name_with_login' === $show ) {
  993. $fields[] = 'display_name';
  994. } else {
  995. $fields[] = $show;
  996. }
  997. $query_args['fields'] = $fields;
  998. $show_option_all = $parsed_args['show_option_all'];
  999. $show_option_none = $parsed_args['show_option_none'];
  1000. $option_none_value = $parsed_args['option_none_value'];
  1001. /**
  1002. * Filters the query arguments for the list of users in the dropdown.
  1003. *
  1004. * @since 4.4.0
  1005. *
  1006. * @param array $query_args The query arguments for get_users().
  1007. * @param array $parsed_args The arguments passed to wp_dropdown_users() combined with the defaults.
  1008. */
  1009. $query_args = apply_filters( 'wp_dropdown_users_args', $query_args, $parsed_args );
  1010. $users = get_users( $query_args );
  1011. $output = '';
  1012. if ( ! empty( $users ) && ( empty( $parsed_args['hide_if_only_one_author'] ) || count( $users ) > 1 ) ) {
  1013. $name = esc_attr( $parsed_args['name'] );
  1014. if ( $parsed_args['multi'] && ! $parsed_args['id'] ) {
  1015. $id = '';
  1016. } else {
  1017. $id = $parsed_args['id'] ? " id='" . esc_attr( $parsed_args['id'] ) . "'" : " id='$name'";
  1018. }
  1019. $output = "<select name='{$name}'{$id} class='" . $parsed_args['class'] . "'>\n";
  1020. if ( $show_option_all ) {
  1021. $output .= "\t<option value='0'>$show_option_all</option>\n";
  1022. }
  1023. if ( $show_option_none ) {
  1024. $_selected = selected( $option_none_value, $parsed_args['selected'], false );
  1025. $output .= "\t<option value='" . esc_attr( $option_none_value ) . "'$_selected>$show_option_none</option>\n";
  1026. }
  1027. if ( $parsed_args['include_selected'] && ( $parsed_args['selected'] > 0 ) ) {
  1028. $found_selected = false;
  1029. $parsed_args['selected'] = (int) $parsed_args['selected'];
  1030. foreach ( (array) $users as $user ) {
  1031. $user->ID = (int) $user->ID;
  1032. if ( $user->ID === $parsed_args['selected'] ) {
  1033. $found_selected = true;
  1034. }
  1035. }
  1036. if ( ! $found_selected ) {
  1037. $users[] = get_userdata( $parsed_args['selected'] );
  1038. }
  1039. }
  1040. foreach ( (array) $users as $user ) {
  1041. if ( 'display_name_with_login' === $show ) {
  1042. /* translators: 1: User's display name, 2: User login. */
  1043. $display = sprintf( _x( '%1$s (%2$s)', 'user dropdown' ), $user->display_name, $user->user_login );
  1044. } elseif ( ! empty( $user->$show ) ) {
  1045. $display = $user->$show;
  1046. } else {
  1047. $display = '(' . $user->user_login . ')';
  1048. }
  1049. $_selected = selected( $user->ID, $parsed_args['selected'], false );
  1050. $output .= "\t<option value='$user->ID'$_selected>" . esc_html( $display ) . "</option>\n";
  1051. }
  1052. $output .= '</select>';
  1053. }
  1054. /**
  1055. * Filters the wp_dropdown_users() HTML output.
  1056. *
  1057. * @since 2.3.0
  1058. *
  1059. * @param string $output HTML output generated by wp_dropdown_users().
  1060. */
  1061. $html = apply_filters( 'wp_dropdown_users', $output );
  1062. if ( $parsed_args['echo'] ) {
  1063. echo $html;
  1064. }
  1065. return $html;
  1066. }
  1067. /**
  1068. * Sanitize user field based on context.
  1069. *
  1070. * Possible context values are: 'raw', 'edit', 'db', 'display', 'attribute' and 'js'. The
  1071. * 'display' context is used by default. 'attribute' and 'js' contexts are treated like 'display'
  1072. * when calling filters.
  1073. *
  1074. * @since 2.3.0
  1075. *
  1076. * @param string $field The user Object field name.
  1077. * @param mixed $value The user Object value.
  1078. * @param int $user_id User ID.
  1079. * @param string $context How to sanitize user fields. Looks for 'raw', 'edit', 'db', 'display',
  1080. * 'attribute' and 'js'.
  1081. * @return mixed Sanitized value.
  1082. */
  1083. function sanitize_user_field( $field, $value, $user_id, $context ) {
  1084. $int_fields = array( 'ID' );
  1085. if ( in_array( $field, $int_fields ) ) {
  1086. $value = (int) $value;
  1087. }
  1088. if ( 'raw' == $context ) {
  1089. return $value;
  1090. }
  1091. if ( ! is_string( $value ) && ! is_numeric( $value ) ) {
  1092. return $value;
  1093. }
  1094. $prefixed = false !== strpos( $field, 'user_' );
  1095. if ( 'edit' == $context ) {
  1096. if ( $prefixed ) {
  1097. /** This filter is documented in wp-includes/post.php */
  1098. $value = apply_filters( "edit_{$field}", $value, $user_id );
  1099. } else {
  1100. /**
  1101. * Filters a user field value in the 'edit' context.
  1102. *
  1103. * The dynamic portion of the hook name, `$field`, refers to the prefixed user
  1104. * field being filtered, such as 'user_login', 'user_email', 'first_name', etc.
  1105. *
  1106. * @since 2.9.0
  1107. *
  1108. * @param mixed $value Value of the prefixed user field.
  1109. * @param int $user_id User ID.
  1110. */
  1111. $value = apply_filters( "edit_user_{$field}", $value, $user_id );
  1112. }
  1113. if ( 'description' == $field ) {
  1114. $value = esc_html( $value ); // textarea_escaped?
  1115. } else {
  1116. $value = esc_attr( $value );
  1117. }
  1118. } elseif ( 'db' == $context ) {
  1119. if ( $prefixed ) {
  1120. /** This filter is documented in wp-includes/post.php */
  1121. $value = apply_filters( "pre_{$field}", $value );
  1122. } else {
  1123. /**
  1124. * Filters the value of a user field in the 'db' context.
  1125. *
  1126. * The dynamic portion of the hook name, `$field`, refers to the prefixed user
  1127. * field being filtered, such as 'user_login', 'user_email', 'first_name', etc.
  1128. *
  1129. * @since 2.9.0
  1130. *
  1131. * @param mixed $value Value of the prefixed user field.
  1132. */
  1133. $value = apply_filters( "pre_user_{$field}", $value );
  1134. }
  1135. } else {
  1136. // Use display filters by default.
  1137. if ( $prefixed ) {
  1138. /** This filter is documented in wp-includes/post.php */
  1139. $value = apply_filters( "{$field}", $value, $user_id, $context );
  1140. } else {
  1141. /**
  1142. * Filters the value of a user field in a standard context.
  1143. *
  1144. * The dynamic portion of the hook name, `$field`, refers to the prefixed user
  1145. * field being filtered, such as 'user_login', 'user_email', 'first_name', etc.
  1146. *
  1147. * @since 2.9.0
  1148. *
  1149. * @param mixed $value The user object value to sanitize.
  1150. * @param int $user_id User ID.
  1151. * @param string $context The context to filter within.
  1152. */
  1153. $value = apply_filters( "user_{$field}", $value, $user_id, $context );
  1154. }
  1155. }
  1156. if ( 'user_url' == $field ) {
  1157. $value = esc_url( $value );
  1158. }
  1159. if ( 'attribute' == $context ) {
  1160. $value = esc_attr( $value );
  1161. } elseif ( 'js' == $context ) {
  1162. $value = esc_js( $value );
  1163. }
  1164. return $value;
  1165. }
  1166. /**
  1167. * Update all user caches
  1168. *
  1169. * @since 3.0.0
  1170. *
  1171. * @param WP_User $user User object to be cached
  1172. * @return bool|null Returns false on failure.
  1173. */
  1174. function update_user_caches( $user ) {
  1175. if ( $user instanceof WP_User ) {
  1176. if ( ! $user->exists() ) {
  1177. return false;
  1178. }
  1179. $user = $user->data;
  1180. }
  1181. wp_cache_add( $user->ID, $user, 'users' );
  1182. wp_cache_add( $user->user_login, $user->ID, 'userlogins' );
  1183. wp_cache_add( $user->user_email, $user->ID, 'useremail' );
  1184. wp_cache_add( $user->user_nicename, $user->ID, 'userslugs' );
  1185. }
  1186. /**
  1187. * Clean all user caches
  1188. *
  1189. * @since 3.0.0
  1190. * @since 4.4.0 'clean_user_cache' action was added.
  1191. *
  1192. * @param WP_User|int $user User object or ID to be cleaned from the cache
  1193. */
  1194. function clean_user_cache( $user ) {
  1195. if ( is_numeric( $user ) ) {
  1196. $user = new WP_User( $user );
  1197. }
  1198. if ( ! $user->exists() ) {
  1199. return;
  1200. }
  1201. wp_cache_delete( $user->ID, 'users' );
  1202. wp_cache_delete( $user->user_login, 'userlogins' );
  1203. wp_cache_delete( $user->user_email, 'useremail' );
  1204. wp_cache_delete( $user->user_nicename, 'userslugs' );
  1205. /**
  1206. * Fires immediately after the given user's cache is cleaned.
  1207. *
  1208. * @since 4.4.0
  1209. *
  1210. * @param int $user_id User ID.
  1211. * @param WP_User $user User object.
  1212. */
  1213. do_action( 'clean_user_cache', $user->ID, $user );
  1214. }
  1215. /**
  1216. * Determines whether the given username exists.
  1217. *
  1218. * For more information on this and similar theme functions, check out
  1219. * the {@link https://developer.wordpress.org/themes/basics/conditional-tags/
  1220. * Conditional Tags} article in the Theme Developer Handbook.
  1221. *
  1222. * @since 2.0.0
  1223. *
  1224. * @param string $username Username.
  1225. * @return int|false The user's ID on success, and false on failure.
  1226. */
  1227. function username_exists( $username ) {
  1228. $user = get_user_by( 'login', $username );
  1229. if ( $user ) {
  1230. $user_id = $user->ID;
  1231. } else {
  1232. $user_id = false;
  1233. }
  1234. /**
  1235. * Filters whether the given username exists or not.
  1236. *
  1237. * @since 4.9.0
  1238. *
  1239. * @param int|false $user_id The user's ID on success, and false on failure.
  1240. * @param string $username Username to check.
  1241. */
  1242. return apply_filters( 'username_exists', $user_id, $username );
  1243. }
  1244. /**
  1245. * Determines whether the given email exists.
  1246. *
  1247. * For more information on this and similar theme functions, check out
  1248. * the {@link https://developer.wordpress.org/themes/basics/conditional-tags/
  1249. * Conditional Tags} article in the Theme Developer Handbook.
  1250. *
  1251. * @since 2.1.0
  1252. *
  1253. * @param string $email Email.
  1254. * @return int|false The user's ID on success, and false on failure.
  1255. */
  1256. function email_exists( $email ) {
  1257. $user = get_user_by( 'email', $email );
  1258. if ( $user ) {
  1259. return $user->ID;
  1260. }
  1261. return false;
  1262. }
  1263. /**
  1264. * Checks whether a username is valid.
  1265. *
  1266. * @since 2.0.1
  1267. * @since 4.4.0 Empty sanitized usernames are now considered invalid
  1268. *
  1269. * @param string $username Username.
  1270. * @return bool Whether username given is valid
  1271. */
  1272. function validate_username( $username ) {
  1273. $sanitized = sanitize_user( $username, true );
  1274. $valid = ( $sanitized == $username && ! empty( $sanitized ) );
  1275. /**
  1276. * Filters whether the provided username is valid or not.
  1277. *
  1278. * @since 2.0.1
  1279. *
  1280. * @param bool $valid Whether given username is valid.
  1281. * @param string $username Username to check.
  1282. */
  1283. return apply_filters( 'validate_username', $valid, $username );
  1284. }
  1285. /**
  1286. * Insert a user into the database.
  1287. *
  1288. * Most of the `$userdata` array fields have filters associated with the values. Exceptions are
  1289. * 'ID', 'rich_editing', 'syntax_highlighting', 'comment_shortcuts', 'admin_color', 'use_ssl',
  1290. * 'user_registered', 'user_activation_key', 'spam', and 'role'. The filters have the prefix
  1291. * 'pre_user_' followed by the field name. An example using 'description' would have the filter
  1292. * called 'pre_user_description' that can be hooked into.
  1293. *
  1294. * @since 2.0.0
  1295. * @since 3.6.0 The `aim`, `jabber`, and `yim` fields were removed as default user contact
  1296. * methods for new installations. See wp_get_user_contact_methods().
  1297. * @since 4.7.0 The user's locale can be passed to `$userdata`.
  1298. * @since 5.3.0 The `user_activation_key` field can be passed to `$userdata`.
  1299. * @since 5.3.0 The `spam` field can be passed to `$userdata` (Multisite only).
  1300. *
  1301. * @global wpdb $wpdb WordPress database abstraction object.
  1302. *
  1303. * @param array|object|WP_User $userdata {
  1304. * An array, object, or WP_User object of user data arguments.
  1305. *
  1306. * @type int $ID User ID. If supplied, the user will be updated.
  1307. * @type string $user_pass The plain-text user password.
  1308. * @type string $user_login The user's login username.
  1309. * @type string $user_nicename The URL-friendly user name.
  1310. * @type string $user_url The user URL.
  1311. * @type string $user_email The user email address.
  1312. * @type string $display_name The user's display name.
  1313. * Default is the user's username.
  1314. * @type string $nickname The user's nickname.
  1315. * Default is the user's username.
  1316. * @type string $first_name The user's first name. For new users, will be used
  1317. * to build the first part of the user's display name
  1318. * if `$display_name` is not specified.
  1319. * @type string $last_name The user's last name. For new users, will be used
  1320. * to build the second part of the user's display name
  1321. * if `$display_name` is not specified.
  1322. * @type string $description The user's biographical description.
  1323. * @type string|bool $rich_editing Whether to enable the rich-editor for the user.
  1324. * False if not empty.
  1325. * @type string|bool $syntax_highlighting Whether to enable the rich code editor for the user.
  1326. * False if not empty.
  1327. * @type string|bool $comment_shortcuts Whether to enable comment moderation keyboard
  1328. * shortcuts for the user. Default false.
  1329. * @type string $admin_color Admin color scheme for the user. Default 'fresh'.
  1330. * @type bool $use_ssl Whether the user should always access the admin over
  1331. * https. Default false.
  1332. * @type string $user_registered Date the user registered. Format is 'Y-m-d H:i:s'.
  1333. * @type string $user_activation_key Password reset key. Default empty.
  1334. * @type bool $spam Multisite only. Whether the user is marked as spam.
  1335. * Default false.
  1336. * @type string|bool $show_admin_bar_front Whether to display the Admin Bar for the user on the
  1337. * site's front end. Default true.
  1338. * @type string $role User's role.
  1339. * @type string $locale User's locale. Default empty.
  1340. * }
  1341. * @return int|WP_Error The newly created user's ID or a WP_Error object if the user could not
  1342. * be created.
  1343. */
  1344. function wp_insert_user( $userdata ) {
  1345. global $wpdb;
  1346. if ( $userdata instanceof stdClass ) {
  1347. $userdata = get_object_vars( $userdata );
  1348. } elseif ( $userdata instanceof WP_User ) {
  1349. $userdata = $userdata->to_array();
  1350. }
  1351. // Are we updating or creating?
  1352. if ( ! empty( $userdata['ID'] ) ) {
  1353. $ID = (int) $userdata['ID'];
  1354. $update = true;
  1355. $old_user_data = get_userdata( $ID );
  1356. if ( ! $old_user_data ) {
  1357. return new WP_Error( 'invalid_user_id', __( 'Invalid user ID.' ) );
  1358. }
  1359. // hashed in wp_update_user(), plaintext if called directly
  1360. $user_pass = ! empty( $userdata['user_pass'] ) ? $userdata['user_pass'] : $old_user_data->user_pass;
  1361. } else {
  1362. $update = false;
  1363. // Hash the password
  1364. $user_pass = wp_hash_password( $userdata['user_pass'] );
  1365. }
  1366. $sanitized_user_login = sanitize_user( $userdata['user_login'], true );
  1367. /**
  1368. * Filters a username after it has been sanitized.
  1369. *
  1370. * This filter is called before the user is created or updated.
  1371. *
  1372. * @since 2.0.3
  1373. *
  1374. * @param string $sanitized_user_login Username after it has been sanitized.
  1375. */
  1376. $pre_user_login = apply_filters( 'pre_user_login', $sanitized_user_login );
  1377. //Remove any non-printable chars from the login string to see if we have ended up with an empty username
  1378. $user_login = trim( $pre_user_login );
  1379. // user_login must be between 0 and 60 characters.
  1380. if ( empty( $user_login ) ) {
  1381. return new WP_Error( 'empty_user_login', __( 'Cannot create a user with an empty login name.' ) );
  1382. } elseif ( mb_strlen( $user_login ) > 60 ) {
  1383. return new WP_Error( 'user_login_too_long', __( 'Username may not be longer than 60 characters.' ) );
  1384. }
  1385. if ( ! $update && username_exists( $user_login ) ) {
  1386. return new WP_Error( 'existing_user_login', __( 'Sorry, that username already exists!' ) );
  1387. }
  1388. /**
  1389. * Filters the list of blacklisted usernames.
  1390. *
  1391. * @since 4.4.0
  1392. *
  1393. * @param array $usernames Array of blacklisted usernames.
  1394. */
  1395. $illegal_logins = (array) apply_filters( 'illegal_user_logins', array() );
  1396. if ( in_array( strtolower( $user_login ), array_map( 'strtolower', $illegal_logins ) ) ) {
  1397. return new WP_Error( 'invalid_username', __( 'Sorry, that username is not allowed.' ) );
  1398. }
  1399. /*
  1400. * If a nicename is provided, remove unsafe user characters before using it.
  1401. * Otherwise build a nicename from the user_login.
  1402. */
  1403. if ( ! empty( $userdata['user_nicename'] ) ) {
  1404. $user_nicename = sanitize_user( $userdata['user_nicename'], true );
  1405. if ( mb_strlen( $user_nicename ) > 50 ) {
  1406. return new WP_Error( 'user_nicename_too_long', __( 'Nicename may not be longer than 50 characters.' ) );
  1407. }
  1408. } else {
  1409. $user_nicename = mb_substr( $user_login, 0, 50 );
  1410. }
  1411. $user_nicename = sanitize_title( $user_nicename );
  1412. /**
  1413. * Filters a user's nicename before the user is created or updated.
  1414. *
  1415. * @since 2.0.3
  1416. *
  1417. * @param string $user_nicename The user's nicename.
  1418. */
  1419. $user_nicename = apply_filters( 'pre_user_nicename', $user_nicename );
  1420. $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 ) );
  1421. if ( $user_nicename_check ) {
  1422. $suffix = 2;
  1423. while ( $user_nicename_check ) {
  1424. // user_nicename allows 50 chars. Subtract one for a hyphen, plus the length of the suffix.
  1425. $base_length = 49 - mb_strlen( $suffix );
  1426. $alt_user_nicename = mb_substr( $user_nicename, 0, $base_length ) . "-$suffix";
  1427. $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 ) );
  1428. $suffix++;
  1429. }
  1430. $user_nicename = $alt_user_nicename;
  1431. }
  1432. $raw_user_email = empty( $userdata['user_email'] ) ? '' : $userdata['user_email'];
  1433. /**
  1434. * Filters a user's email before the user is created or updated.
  1435. *
  1436. * @since 2.0.3
  1437. *
  1438. * @param string $raw_user_email The user's email.
  1439. */
  1440. $user_email = apply_filters( 'pre_user_email', $raw_user_email );
  1441. /*
  1442. * If there is no update, just check for `email_exists`. If there is an update,
  1443. * check if current email and new email are the same, or not, and check `email_exists`
  1444. * accordingly.
  1445. */
  1446. if ( ( ! $update || ( ! empty( $old_user_data ) && 0 !== strcasecmp( $user_email, $old_user_data->user_email ) ) )
  1447. && ! defined( 'WP_IMPORTING' )
  1448. && email_exists( $user_email )
  1449. ) {
  1450. return new WP_Error( 'existing_user_email', __( 'Sorry, that email address is already used!' ) );
  1451. }
  1452. $raw_user_url = empty( $userdata['user_url'] ) ? '' : $userdata['user_url'];
  1453. /**
  1454. * Filters a user's URL before the user is created or updated.
  1455. *
  1456. * @since 2.0.3
  1457. *
  1458. * @param string $raw_user_url The user's URL.
  1459. */
  1460. $user_url = apply_filters( 'pre_user_url', $raw_user_url );
  1461. $user_registered = empty( $userdata['user_registered'] ) ? gmdate( 'Y-m-d H:i:s' ) : $userdata['user_registered'];
  1462. $user_activation_key = empty( $userdata['user_activation_key'] ) ? '' : $userdata['user_activation_key'];
  1463. if ( ! empty( $userdata['spam'] ) && ! is_multisite() ) {
  1464. return new WP_Error( 'no_spam', __( 'Sorry, marking a user as spam is only supported on Multisite.' ) );
  1465. }
  1466. $spam = empty( $userdata['spam'] ) ? 0 : (bool) $userdata['spam'];
  1467. // Store values to save in user meta.
  1468. $meta = array();
  1469. $nickname = empty( $userdata['nickname'] ) ? $user_login : $userdata['nickname'];
  1470. /**
  1471. * Filters a user's nickname before the user is created or updated.
  1472. *
  1473. * @since 2.0.3
  1474. *
  1475. * @param string $nickname The user's nickname.
  1476. */
  1477. $meta['nickname'] = apply_filters( 'pre_user_nickname', $nickname );
  1478. $first_name = empty( $userdata['first_name'] ) ? '' : $userdata['first_name'];
  1479. /**
  1480. * Filters a user's first name before the user is created or updated.
  1481. *
  1482. * @since 2.0.3
  1483. *
  1484. * @param string $first_name The user's first name.
  1485. */
  1486. $meta['first_name'] = apply_filters( 'pre_user_first_name', $first_name );
  1487. $last_name = empty( $userdata['last_name'] ) ? '' : $userdata['last_name'];
  1488. /**
  1489. * Filters a user's last name before the user is created or updated.
  1490. *
  1491. * @since 2.0.3
  1492. *
  1493. * @param string $last_name The user's last name.
  1494. */
  1495. $meta['last_name'] = apply_filters( 'pre_user_last_name', $last_name );
  1496. if ( empty( $userdata['display_name'] ) ) {
  1497. if ( $update ) {
  1498. $display_name = $user_login;
  1499. } elseif ( $meta['first_name'] && $meta['last_name'] ) {
  1500. /* translators: 1: User's first name, 2: Last name. */
  1501. $display_name = sprintf( _x( '%1$s %2$s', 'Display name based on first name and last name' ), $meta['first_name'], $meta['last_name'] );
  1502. } elseif ( $meta['first_name'] ) {
  1503. $display_name = $meta['first_name'];
  1504. } elseif ( $meta['last_name'] ) {
  1505. $display_name = $meta['last_name'];
  1506. } else {
  1507. $display_name = $user_login;
  1508. }
  1509. } else {
  1510. $display_name = $userdata['display_name'];
  1511. }
  1512. /**
  1513. * Filters a user's display name before the user is created or updated.
  1514. *
  1515. * @since 2.0.3
  1516. *
  1517. * @param string $display_name The user's display name.
  1518. */
  1519. $display_name = apply_filters( 'pre_user_display_name', $display_name );
  1520. $description = empty( $userdata['description'] ) ? '' : $userdata['description'];
  1521. /**
  1522. * Filters a user's description before the user is created or updated.
  1523. *
  1524. * @since 2.0.3
  1525. *
  1526. * @param string $description The user's description.
  1527. */
  1528. $meta['description'] = apply_filters( 'pre_user_description', $description );
  1529. $meta['rich_editing'] = empty( $userdata['rich_editing'] ) ? 'true' : $userdata['rich_editing'];
  1530. $meta['syntax_highlighting'] = empty( $userdata['syntax_highlighting'] ) ? 'true' : $userdata['syntax_highlighting'];
  1531. $meta['comment_shortcuts'] = empty( $userdata['comment_shortcuts'] ) || 'false' === $userdata['comment_shortcuts'] ? 'false' : 'true';
  1532. $admin_color = empty( $userdata['admin_color'] ) ? 'fresh' : $userdata['admin_color'];
  1533. $meta['admin_color'] = preg_replace( '|[^a-z0-9 _.\-@]|i', '', $admin_color );
  1534. $meta['use_ssl'] = empty( $userdata['use_ssl'] ) ? 0 : (bool) $userdata['use_ssl'];
  1535. $meta['show_admin_bar_front'] = empty( $userdata['show_admin_bar_front'] ) ? 'true' : $userdata['show_admin_bar_front'];
  1536. $meta['locale'] = isset( $userdata['locale'] ) ? $userdata['locale'] : '';
  1537. $compacted = compact( 'user_pass', 'user_nicename', 'user_email', 'user_url', 'user_registered', 'user_activation_key', 'display_name' );
  1538. $data = wp_unslash( $compacted );
  1539. if ( ! $update ) {
  1540. $data = $data + compact( 'user_login' );
  1541. }
  1542. if ( is_multisite() ) {
  1543. $data = $data + compact( 'spam' );
  1544. }
  1545. /**
  1546. * Filters user data before the record is created or updated.
  1547. *
  1548. * It only includes data in the wp_users table wp_user, not any user metadata.
  1549. *
  1550. * @since 4.9.0
  1551. *
  1552. * @param array $data {
  1553. * Values and keys for the user.
  1554. *
  1555. * @type string $user_login The user's login. Only included if $update == false
  1556. * @type string $user_pass The user's password.
  1557. * @type string $user_email The user's email.
  1558. * @type string $user_url The user's url.
  1559. * @type string $user_nicename The user's nice name. Defaults to a URL-safe version of user's login
  1560. * @type string $display_name The user's display name.
  1561. * @type string $user_registered MySQL timestamp describing the moment when the user registered. Defaults to
  1562. * the current UTC timestamp.
  1563. * }
  1564. * @param bool $update Whether the user is being updated rather than created.
  1565. * @param int|null $id ID of the user to be updated, or NULL if the user is being created.
  1566. */
  1567. $data = apply_filters( 'wp_pre_insert_user_data', $data, $update, $update ? (int) $ID : null );
  1568. if ( empty( $data ) || ! is_array( $data ) ) {
  1569. return new WP_Error( 'empty_data', __( 'Not enough data to create this user.' ) );
  1570. }
  1571. if ( $update ) {
  1572. if ( $user_email !== $old_user_data->user_email ) {
  1573. $data['user_activation_key'] = '';
  1574. }
  1575. $wpdb->update( $wpdb->users, $data, compact( 'ID' ) );
  1576. $user_id = (int) $ID;
  1577. } else {
  1578. $wpdb->insert( $wpdb->users, $data );
  1579. $user_id = (int) $wpdb->insert_id;
  1580. }
  1581. $user = new WP_User( $user_id );
  1582. /**
  1583. * Filters a user's meta values and keys immediately after the user is created or updated
  1584. * and before any user meta is inserted or updated.
  1585. *
  1586. * Does not include contact methods. These are added using `wp_get_user_contact_methods( $user )`.
  1587. *
  1588. * @since 4.4.0
  1589. *
  1590. * @param array $meta {
  1591. * Default meta values and keys for the user.
  1592. *
  1593. * @type string $nickname The user's nickname. Default is the user's username.
  1594. * @type string $first_name The user's first name.
  1595. * @type string $last_name The user's last name.
  1596. * @type string $description The user's description.
  1597. * @type bool $rich_editing Whether to enable the rich-editor for the user. False if not empty.
  1598. * @type bool $syntax_highlighting Whether to enable the rich code editor for the user. False if not empty.
  1599. * @type bool $comment_shortcuts Whether to enable keyboard shortcuts for the user. Default false.
  1600. * @type string $admin_color The color scheme for a user's admin screen. Default 'fresh'.
  1601. * @type int|bool $use_ssl Whether to force SSL on the user's admin area. 0|false if SSL is
  1602. * not forced.
  1603. * @type bool $show_admin_bar_front Whether to show the admin bar on the front end for the user.
  1604. * Default true.
  1605. * @type string $locale User's locale. Default empty.
  1606. * }
  1607. * @param WP_User $user User object.
  1608. * @param bool $update Whether the user is being updated rather than created.
  1609. */
  1610. $meta = apply_filters( 'insert_user_meta', $meta, $user, $update );
  1611. // Update user meta.
  1612. foreach ( $meta as $key => $value ) {
  1613. update_user_meta( $user_id, $key, $value );
  1614. }
  1615. foreach ( wp_get_user_contact_methods( $user ) as $key => $value ) {
  1616. if ( isset( $userdata[ $key ] ) ) {
  1617. update_user_meta( $user_id, $key, $userdata[ $key ] );
  1618. }
  1619. }
  1620. if ( isset( $userdata['role'] ) ) {
  1621. $user->set_role( $userdata['role'] );
  1622. } elseif ( ! $update ) {
  1623. $user->set_role( get_option( 'default_role' ) );
  1624. }
  1625. clean_user_cache( $user_id );
  1626. if ( $update ) {
  1627. /**
  1628. * Fires immediately after an existing user is updated.
  1629. *
  1630. * @since 2.0.0
  1631. *
  1632. * @param int $user_id User ID.
  1633. * @param WP_User $old_user_data Object containing user's data prior to update.
  1634. */
  1635. do_action( 'profile_update', $user_id, $old_user_data );
  1636. if ( isset( $userdata['spam'] ) && $userdata['spam'] != $old_user_data->spam ) {
  1637. if ( $userdata['spam'] == 1 ) {
  1638. /**
  1639. * Fires after the user is marked as a SPAM user.
  1640. *
  1641. * @since 3.0.0
  1642. *
  1643. * @param int $user_id ID of the user marked as SPAM.
  1644. */
  1645. do_action( 'make_spam_user', $user_id );
  1646. } else {
  1647. /**
  1648. * Fires after the user is marked as a HAM user. Opposite of SPAM.
  1649. *
  1650. * @since 3.0.0
  1651. *
  1652. * @param int $user_id ID of the user marked as HAM.
  1653. */
  1654. do_action( 'make_ham_user', $user_id );
  1655. }
  1656. }
  1657. } else {
  1658. /**
  1659. * Fires immediately after a new user is registered.
  1660. *
  1661. * @since 1.5.0
  1662. *
  1663. * @param int $user_id User ID.
  1664. */
  1665. do_action( 'user_register', $user_id );
  1666. }
  1667. return $user_id;
  1668. }
  1669. /**
  1670. * Update a user in the database.
  1671. *
  1672. * It is possible to update a user's password by specifying the 'user_pass'
  1673. * value in the $userdata parameter array.
  1674. *
  1675. * If current user's password is being updated, then the cookies will be
  1676. * cleared.
  1677. *
  1678. * @since 2.0.0
  1679. *
  1680. * @see wp_insert_user() For what fields can be set in $userdata.
  1681. *
  1682. * @param array|object|WP_User $userdata An array of user data or a user object of type stdClass or WP_User.
  1683. * @return int|WP_Error The updated user's ID or a WP_Error object if the user could not be updated.
  1684. */
  1685. function wp_update_user( $userdata ) {
  1686. if ( $userdata instanceof stdClass ) {
  1687. $userdata = get_object_vars( $userdata );
  1688. } elseif ( $userdata instanceof WP_User ) {
  1689. $userdata = $userdata->to_array();
  1690. }
  1691. $ID = isset( $userdata['ID'] ) ? (int) $userdata['ID'] : 0;
  1692. if ( ! $ID ) {
  1693. return new WP_Error( 'invalid_user_id', __( 'Invalid user ID.' ) );
  1694. }
  1695. // First, get all of the original fields
  1696. $user_obj = get_userdata( $ID );
  1697. if ( ! $user_obj ) {
  1698. return new WP_Error( 'invalid_user_id', __( 'Invalid user ID.' ) );
  1699. }
  1700. $user = $user_obj->to_array();
  1701. // Add additional custom fields
  1702. foreach ( _get_additional_user_keys( $user_obj ) as $key ) {
  1703. $user[ $key ] = get_user_meta( $ID, $key, true );
  1704. }
  1705. // Escape data pulled from DB.
  1706. $user = add_magic_quotes( $user );
  1707. if ( ! empty( $userdata['user_pass'] ) && $userdata['user_pass'] !== $user_obj->user_pass ) {
  1708. // If password is changing, hash it now
  1709. $plaintext_pass = $userdata['user_pass'];
  1710. $userdata['user_pass'] = wp_hash_password( $userdata['user_pass'] );
  1711. /**
  1712. * Filters whether to send the password change email.
  1713. *
  1714. * @since 4.3.0
  1715. *
  1716. * @see wp_insert_user() For `$user` and `$userdata` fields.
  1717. *
  1718. * @param bool $send Whether to send the email.
  1719. * @param array $user The original user array.
  1720. * @param array $userdata The updated user array.
  1721. */
  1722. $send_password_change_email = apply_filters( 'send_password_change_email', true, $user, $userdata );
  1723. }
  1724. if ( isset( $userdata['user_email'] ) && $user['user_email'] !== $userdata['user_email'] ) {
  1725. /**
  1726. * Filters whether to send the email change email.
  1727. *
  1728. * @since 4.3.0
  1729. *
  1730. * @see wp_insert_user() For `$user` and `$userdata` fields.
  1731. *
  1732. * @param bool $send Whether to send the email.
  1733. * @param array $user The original user array.
  1734. * @param array $userdata The updated user array.
  1735. */
  1736. $send_email_change_email = apply_filters( 'send_email_change_email', true, $user, $userdata );
  1737. }
  1738. clean_user_cache( $user_obj );
  1739. // Merge old and new fields with new fields overwriting old ones.
  1740. $userdata = array_merge( $user, $userdata );
  1741. $user_id = wp_insert_user( $userdata );
  1742. if ( ! is_wp_error( $user_id ) ) {
  1743. $blog_name = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES );
  1744. $switched_locale = false;
  1745. if ( ! empty( $send_password_change_email ) || ! empty( $send_email_change_email ) ) {
  1746. $switched_locale = switch_to_locale( get_user_locale( $user_id ) );
  1747. }
  1748. if ( ! empty( $send_password_change_email ) ) {
  1749. /* translators: Do not translate USERNAME, ADMIN_EMAIL, EMAIL, SITENAME, SITEURL: those are placeholders. */
  1750. $pass_change_text = __(
  1751. 'Hi ###USERNAME###,
  1752. This notice confirms that your password was changed on ###SITENAME###.
  1753. If you did not change your password, please contact the Site Administrator at
  1754. ###ADMIN_EMAIL###
  1755. This email has been sent to ###EMAIL###
  1756. Regards,
  1757. All at ###SITENAME###
  1758. ###SITEURL###'
  1759. );
  1760. $pass_change_email = array(
  1761. 'to' => $user['user_email'],
  1762. /* translators: Password change notification email subject. %s: Site title. */
  1763. 'subject' => __( '[%s] Password Changed' ),
  1764. 'message' => $pass_change_text,
  1765. 'headers' => '',
  1766. );
  1767. /**
  1768. * Filters the contents of the email sent when the user's password is changed.
  1769. *
  1770. * @since 4.3.0
  1771. *
  1772. * @param array $pass_change_email {
  1773. * Used to build wp_mail().
  1774. * @type string $to The intended recipients. Add emails in a comma separated string.
  1775. * @type string $subject The subject of the email.
  1776. * @type string $message The content of the email.
  1777. * The following strings have a special meaning and will get replaced dynamically:
  1778. * - ###USERNAME### The current user's username.
  1779. * - ###ADMIN_EMAIL### The admin email in case this was unexpected.
  1780. * - ###EMAIL### The user's email address.
  1781. * - ###SITENAME### The name of the site.
  1782. * - ###SITEURL### The URL to the site.
  1783. * @type string $headers Headers. Add headers in a newline (\r\n) separated string.
  1784. * }
  1785. * @param array $user The original user array.
  1786. * @param array $userdata The updated user array.
  1787. */
  1788. $pass_change_email = apply_filters( 'password_change_email', $pass_change_email, $user, $userdata );
  1789. $pass_change_email['message'] = str_replace( '###USERNAME###', $user['user_login'], $pass_change_email['message'] );
  1790. $pass_change_email['message'] = str_replace( '###ADMIN_EMAIL###', get_option( 'admin_email' ), $pass_change_email['message'] );
  1791. $pass_change_email['message'] = str_replace( '###EMAIL###', $user['user_email'], $pass_change_email['message'] );
  1792. $pass_change_email['message'] = str_replace( '###SITENAME###', $blog_name, $pass_change_email['message'] );
  1793. $pass_change_email['message'] = str_replace( '###SITEURL###', home_url(), $pass_change_email['message'] );
  1794. wp_mail( $pass_change_email['to'], sprintf( $pass_change_email['subject'], $blog_name ), $pass_change_email['message'], $pass_change_email['headers'] );
  1795. }
  1796. if ( ! empty( $send_email_change_email ) ) {
  1797. /* translators: Do not translate USERNAME, ADMIN_EMAIL, NEW_EMAIL, EMAIL, SITENAME, SITEURL: those are placeholders. */
  1798. $email_change_text = __(
  1799. 'Hi ###USERNAME###,
  1800. This notice confirms that your email address on ###SITENAME### was changed to ###NEW_EMAIL###.
  1801. If you did not change your email, please contact the Site Administrator at
  1802. ###ADMIN_EMAIL###
  1803. This email has been sent to ###EMAIL###
  1804. Regards,
  1805. All at ###SITENAME###
  1806. ###SITEURL###'
  1807. );
  1808. $email_change_email = array(
  1809. 'to' => $user['user_email'],
  1810. /* translators: Email change notification email subject. %s: Site title. */
  1811. 'subject' => __( '[%s] Email Changed' ),
  1812. 'message' => $email_change_text,
  1813. 'headers' => '',
  1814. );
  1815. /**
  1816. * Filters the contents of the email sent when the user's email is changed.
  1817. *
  1818. * @since 4.3.0
  1819. *
  1820. * @param array $email_change_email {
  1821. * Used to build wp_mail().
  1822. * @type string $to The intended recipients.
  1823. * @type string $subject The subject of the email.
  1824. * @type string $message The content of the email.
  1825. * The following strings have a special meaning and will get replaced dynamically:
  1826. * - ###USERNAME### The current user's username.
  1827. * - ###ADMIN_EMAIL### The admin email in case this was unexpected.
  1828. * - ###NEW_EMAIL### The new email address.
  1829. * - ###EMAIL### The old email address.
  1830. * - ###SITENAME### The name of the site.
  1831. * - ###SITEURL### The URL to the site.
  1832. * @type string $headers Headers.
  1833. * }
  1834. * @param array $user The original user array.
  1835. * @param array $userdata The updated user array.
  1836. */
  1837. $email_change_email = apply_filters( 'email_change_email', $email_change_email, $user, $userdata );
  1838. $email_change_email['message'] = str_replace( '###USERNAME###', $user['user_login'], $email_change_email['message'] );
  1839. $email_change_email['message'] = str_replace( '###ADMIN_EMAIL###', get_option( 'admin_email' ), $email_change_email['message'] );
  1840. $email_change_email['message'] = str_replace( '###NEW_EMAIL###', $userdata['user_email'], $email_change_email['message'] );
  1841. $email_change_email['message'] = str_replace( '###EMAIL###', $user['user_email'], $email_change_email['message'] );
  1842. $email_change_email['message'] = str_replace( '###SITENAME###', $blog_name, $email_change_email['message'] );
  1843. $email_change_email['message'] = str_replace( '###SITEURL###', home_url(), $email_change_email['message'] );
  1844. wp_mail( $email_change_email['to'], sprintf( $email_change_email['subject'], $blog_name ), $email_change_email['message'], $email_change_email['headers'] );
  1845. }
  1846. if ( $switched_locale ) {
  1847. restore_previous_locale();
  1848. }
  1849. }
  1850. // Update the cookies if the password changed.
  1851. $current_user = wp_get_current_user();
  1852. if ( $current_user->ID == $ID ) {
  1853. if ( isset( $plaintext_pass ) ) {
  1854. wp_clear_auth_cookie();
  1855. // Here we calculate the expiration length of the current auth cookie and compare it to the default expiration.
  1856. // If it's greater than this, then we know the user checked 'Remember Me' when they logged in.
  1857. $logged_in_cookie = wp_parse_auth_cookie( '', 'logged_in' );
  1858. /** This filter is documented in wp-includes/pluggable.php */
  1859. $default_cookie_life = apply_filters( 'auth_cookie_expiration', ( 2 * DAY_IN_SECONDS ), $ID, false );
  1860. $remember = false;
  1861. if ( false !== $logged_in_cookie && ( $logged_in_cookie['expiration'] - time() ) > $default_cookie_life ) {
  1862. $remember = true;
  1863. }
  1864. wp_set_auth_cookie( $ID, $remember );
  1865. }
  1866. }
  1867. return $user_id;
  1868. }
  1869. /**
  1870. * A simpler way of inserting a user into the database.
  1871. *
  1872. * Creates a new user with just the username, password, and email. For more
  1873. * complex user creation use wp_insert_user() to specify more information.
  1874. *
  1875. * @since 2.0.0
  1876. * @see wp_insert_user() More complete way to create a new user
  1877. *
  1878. * @param string $username The user's username.
  1879. * @param string $password The user's password.
  1880. * @param string $email Optional. The user's email. Default empty.
  1881. * @return int|WP_Error The newly created user's ID or a WP_Error object if the user could not
  1882. * be created.
  1883. */
  1884. function wp_create_user( $username, $password, $email = '' ) {
  1885. $user_login = wp_slash( $username );
  1886. $user_email = wp_slash( $email );
  1887. $user_pass = $password;
  1888. $userdata = compact( 'user_login', 'user_email', 'user_pass' );
  1889. return wp_insert_user( $userdata );
  1890. }
  1891. /**
  1892. * Returns a list of meta keys to be (maybe) populated in wp_update_user().
  1893. *
  1894. * The list of keys returned via this function are dependent on the presence
  1895. * of those keys in the user meta data to be set.
  1896. *
  1897. * @since 3.3.0
  1898. * @access private
  1899. *
  1900. * @param WP_User $user WP_User instance.
  1901. * @return array List of user keys to be populated in wp_update_user().
  1902. */
  1903. function _get_additional_user_keys( $user ) {
  1904. $keys = array( 'first_name', 'last_name', 'nickname', 'description', 'rich_editing', 'syntax_highlighting', 'comment_shortcuts', 'admin_color', 'use_ssl', 'show_admin_bar_front', 'locale' );
  1905. return array_merge( $keys, array_keys( wp_get_user_contact_methods( $user ) ) );
  1906. }
  1907. /**
  1908. * Set up the user contact methods.
  1909. *
  1910. * Default contact methods were removed in 3.6. A filter dictates contact methods.
  1911. *
  1912. * @since 3.7.0
  1913. *
  1914. * @param WP_User $user Optional. WP_User object.
  1915. * @return array Array of contact methods and their labels.
  1916. */
  1917. function wp_get_user_contact_methods( $user = null ) {
  1918. $methods = array();
  1919. if ( get_site_option( 'initial_db_version' ) < 23588 ) {
  1920. $methods = array(
  1921. 'aim' => __( 'AIM' ),
  1922. 'yim' => __( 'Yahoo IM' ),
  1923. 'jabber' => __( 'Jabber / Google Talk' ),
  1924. );
  1925. }
  1926. /**
  1927. * Filters the user contact methods.
  1928. *
  1929. * @since 2.9.0
  1930. *
  1931. * @param array $methods Array of contact methods and their labels.
  1932. * @param WP_User $user WP_User object.
  1933. */
  1934. return apply_filters( 'user_contactmethods', $methods, $user );
  1935. }
  1936. /**
  1937. * The old private function for setting up user contact methods.
  1938. *
  1939. * Use wp_get_user_contact_methods() instead.
  1940. *
  1941. * @since 2.9.0
  1942. * @access private
  1943. *
  1944. * @param WP_User $user Optional. WP_User object. Default null.
  1945. * @return array Array of contact methods and their labels.
  1946. */
  1947. function _wp_get_user_contactmethods( $user = null ) {
  1948. return wp_get_user_contact_methods( $user );
  1949. }
  1950. /**
  1951. * Gets the text suggesting how to create strong passwords.
  1952. *
  1953. * @since 4.1.0
  1954. *
  1955. * @return string The password hint text.
  1956. */
  1957. function wp_get_password_hint() {
  1958. $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; ).' );
  1959. /**
  1960. * Filters the text describing the site's password complexity policy.
  1961. *
  1962. * @since 4.1.0
  1963. *
  1964. * @param string $hint The password hint text.
  1965. */
  1966. return apply_filters( 'password_hint', $hint );
  1967. }
  1968. /**
  1969. * Creates, stores, then returns a password reset key for user.
  1970. *
  1971. * @since 4.4.0
  1972. *
  1973. * @global PasswordHash $wp_hasher Portable PHP password hashing framework.
  1974. *
  1975. * @param WP_User $user User to retrieve password reset key for.
  1976. *
  1977. * @return string|WP_Error Password reset key on success. WP_Error on error.
  1978. */
  1979. function get_password_reset_key( $user ) {
  1980. global $wp_hasher;
  1981. if ( ! ( $user instanceof WP_User ) ) {
  1982. return new WP_Error( 'invalidcombo', __( '<strong>ERROR</strong>: There is no account with that username or email address.' ) );
  1983. }
  1984. /**
  1985. * Fires before a new password is retrieved.
  1986. *
  1987. * Use the {@see 'retrieve_password'} hook instead.
  1988. *
  1989. * @since 1.5.0
  1990. * @deprecated 1.5.1 Misspelled. Use 'retrieve_password' hook instead.
  1991. *
  1992. * @param string $user_login The user login name.
  1993. */
  1994. do_action( 'retreive_password', $user->user_login );
  1995. /**
  1996. * Fires before a new password is retrieved.
  1997. *
  1998. * @since 1.5.1
  1999. *
  2000. * @param string $user_login The user login name.
  2001. */
  2002. do_action( 'retrieve_password', $user->user_login );
  2003. $allow = true;
  2004. if ( is_multisite() && is_user_spammy( $user ) ) {
  2005. $allow = false;
  2006. }
  2007. /**
  2008. * Filters whether to allow a password to be reset.
  2009. *
  2010. * @since 2.7.0
  2011. *
  2012. * @param bool $allow Whether to allow the password to be reset. Default true.
  2013. * @param int $user_data->ID The ID of the user attempting to reset a password.
  2014. */
  2015. $allow = apply_filters( 'allow_password_reset', $allow, $user->ID );
  2016. if ( ! $allow ) {
  2017. return new WP_Error( 'no_password_reset', __( 'Password reset is not allowed for this user' ) );
  2018. } elseif ( is_wp_error( $allow ) ) {
  2019. return $allow;
  2020. }
  2021. // Generate something random for a password reset key.
  2022. $key = wp_generate_password( 20, false );
  2023. /**
  2024. * Fires when a password reset key is generated.
  2025. *
  2026. * @since 2.5.0
  2027. *
  2028. * @param string $user_login The username for the user.
  2029. * @param string $key The generated password reset key.
  2030. */
  2031. do_action( 'retrieve_password_key', $user->user_login, $key );
  2032. // Now insert the key, hashed, into the DB.
  2033. if ( empty( $wp_hasher ) ) {
  2034. require_once ABSPATH . WPINC . '/class-phpass.php';
  2035. $wp_hasher = new PasswordHash( 8, true );
  2036. }
  2037. $hashed = time() . ':' . $wp_hasher->HashPassword( $key );
  2038. $key_saved = wp_update_user(
  2039. array(
  2040. 'ID' => $user->ID,
  2041. 'user_activation_key' => $hashed,
  2042. )
  2043. );
  2044. if ( is_wp_error( $key_saved ) ) {
  2045. return $key_saved;
  2046. }
  2047. return $key;
  2048. }
  2049. /**
  2050. * Retrieves a user row based on password reset key and login
  2051. *
  2052. * A key is considered 'expired' if it exactly matches the value of the
  2053. * user_activation_key field, rather than being matched after going through the
  2054. * hashing process. This field is now hashed; old values are no longer accepted
  2055. * but have a different WP_Error code so good user feedback can be provided.
  2056. *
  2057. * @since 3.1.0
  2058. *
  2059. * @global wpdb $wpdb WordPress database object for queries.
  2060. * @global PasswordHash $wp_hasher Portable PHP password hashing framework instance.
  2061. *
  2062. * @param string $key Hash to validate sending user's password.
  2063. * @param string $login The user login.
  2064. * @return WP_User|WP_Error WP_User object on success, WP_Error object for invalid or expired keys.
  2065. */
  2066. function check_password_reset_key( $key, $login ) {
  2067. global $wpdb, $wp_hasher;
  2068. $key = preg_replace( '/[^a-z0-9]/i', '', $key );
  2069. if ( empty( $key ) || ! is_string( $key ) ) {
  2070. return new WP_Error( 'invalid_key', __( 'Invalid key.' ) );
  2071. }
  2072. if ( empty( $login ) || ! is_string( $login ) ) {
  2073. return new WP_Error( 'invalid_key', __( 'Invalid key.' ) );
  2074. }
  2075. $user = get_user_by( 'login', $login );
  2076. if ( ! $user ) {
  2077. return new WP_Error( 'invalid_key', __( 'Invalid key.' ) );
  2078. }
  2079. if ( empty( $wp_hasher ) ) {
  2080. require_once ABSPATH . WPINC . '/class-phpass.php';
  2081. $wp_hasher = new PasswordHash( 8, true );
  2082. }
  2083. /**
  2084. * Filters the expiration time of password reset keys.
  2085. *
  2086. * @since 4.3.0
  2087. *
  2088. * @param int $expiration The expiration time in seconds.
  2089. */
  2090. $expiration_duration = apply_filters( 'password_reset_expiration', DAY_IN_SECONDS );
  2091. if ( false !== strpos( $user->user_activation_key, ':' ) ) {
  2092. list( $pass_request_time, $pass_key ) = explode( ':', $user->user_activation_key, 2 );
  2093. $expiration_time = $pass_request_time + $expiration_duration;
  2094. } else {
  2095. $pass_key = $user->user_activation_key;
  2096. $expiration_time = false;
  2097. }
  2098. if ( ! $pass_key ) {
  2099. return new WP_Error( 'invalid_key', __( 'Invalid key.' ) );
  2100. }
  2101. $hash_is_correct = $wp_hasher->CheckPassword( $key, $pass_key );
  2102. if ( $hash_is_correct && $expiration_time && time() < $expiration_time ) {
  2103. return $user;
  2104. } elseif ( $hash_is_correct && $expiration_time ) {
  2105. // Key has an expiration time that's passed
  2106. return new WP_Error( 'expired_key', __( 'Invalid key.' ) );
  2107. }
  2108. if ( hash_equals( $user->user_activation_key, $key ) || ( $hash_is_correct && ! $expiration_time ) ) {
  2109. $return = new WP_Error( 'expired_key', __( 'Invalid key.' ) );
  2110. $user_id = $user->ID;
  2111. /**
  2112. * Filters the return value of check_password_reset_key() when an
  2113. * old-style key is used.
  2114. *
  2115. * @since 3.7.0 Previously plain-text keys were stored in the database.
  2116. * @since 4.3.0 Previously key hashes were stored without an expiration time.
  2117. *
  2118. * @param WP_Error $return A WP_Error object denoting an expired key.
  2119. * Return a WP_User object to validate the key.
  2120. * @param int $user_id The matched user ID.
  2121. */
  2122. return apply_filters( 'password_reset_key_expired', $return, $user_id );
  2123. }
  2124. return new WP_Error( 'invalid_key', __( 'Invalid key.' ) );
  2125. }
  2126. /**
  2127. * Handles resetting the user's password.
  2128. *
  2129. * @since 2.5.0
  2130. *
  2131. * @param WP_User $user The user
  2132. * @param string $new_pass New password for the user in plaintext
  2133. */
  2134. function reset_password( $user, $new_pass ) {
  2135. /**
  2136. * Fires before the user's password is reset.
  2137. *
  2138. * @since 1.5.0
  2139. *
  2140. * @param object $user The user.
  2141. * @param string $new_pass New user password.
  2142. */
  2143. do_action( 'password_reset', $user, $new_pass );
  2144. wp_set_password( $new_pass, $user->ID );
  2145. update_user_option( $user->ID, 'default_password_nag', false, true );
  2146. /**
  2147. * Fires after the user's password is reset.
  2148. *
  2149. * @since 4.4.0
  2150. *
  2151. * @param WP_User $user The user.
  2152. * @param string $new_pass New user password.
  2153. */
  2154. do_action( 'after_password_reset', $user, $new_pass );
  2155. }
  2156. /**
  2157. * Handles registering a new user.
  2158. *
  2159. * @since 2.5.0
  2160. *
  2161. * @param string $user_login User's username for logging in
  2162. * @param string $user_email User's email address to send password and add
  2163. * @return int|WP_Error Either user's ID or error on failure.
  2164. */
  2165. function register_new_user( $user_login, $user_email ) {
  2166. $errors = new WP_Error();
  2167. $sanitized_user_login = sanitize_user( $user_login );
  2168. /**
  2169. * Filters the email address of a user being registered.
  2170. *
  2171. * @since 2.1.0
  2172. *
  2173. * @param string $user_email The email address of the new user.
  2174. */
  2175. $user_email = apply_filters( 'user_registration_email', $user_email );
  2176. // Check the username
  2177. if ( $sanitized_user_login == '' ) {
  2178. $errors->add( 'empty_username', __( '<strong>ERROR</strong>: Please enter a username.' ) );
  2179. } elseif ( ! validate_username( $user_login ) ) {
  2180. $errors->add( 'invalid_username', __( '<strong>ERROR</strong>: This username is invalid because it uses illegal characters. Please enter a valid username.' ) );
  2181. $sanitized_user_login = '';
  2182. } elseif ( username_exists( $sanitized_user_login ) ) {
  2183. $errors->add( 'username_exists', __( '<strong>ERROR</strong>: This username is already registered. Please choose another one.' ) );
  2184. } else {
  2185. /** This filter is documented in wp-includes/user.php */
  2186. $illegal_user_logins = (array) apply_filters( 'illegal_user_logins', array() );
  2187. if ( in_array( strtolower( $sanitized_user_login ), array_map( 'strtolower', $illegal_user_logins ) ) ) {
  2188. $errors->add( 'invalid_username', __( '<strong>ERROR</strong>: Sorry, that username is not allowed.' ) );
  2189. }
  2190. }
  2191. // Check the email address
  2192. if ( $user_email == '' ) {
  2193. $errors->add( 'empty_email', __( '<strong>ERROR</strong>: Please type your email address.' ) );
  2194. } elseif ( ! is_email( $user_email ) ) {
  2195. $errors->add( 'invalid_email', __( '<strong>ERROR</strong>: The email address isn&#8217;t correct.' ) );
  2196. $user_email = '';
  2197. } elseif ( email_exists( $user_email ) ) {
  2198. $errors->add( 'email_exists', __( '<strong>ERROR</strong>: This email is already registered, please choose another one.' ) );
  2199. }
  2200. /**
  2201. * Fires when submitting registration form data, before the user is created.
  2202. *
  2203. * @since 2.1.0
  2204. *
  2205. * @param string $sanitized_user_login The submitted username after being sanitized.
  2206. * @param string $user_email The submitted email.
  2207. * @param WP_Error $errors Contains any errors with submitted username and email,
  2208. * e.g., an empty field, an invalid username or email,
  2209. * or an existing username or email.
  2210. */
  2211. do_action( 'register_post', $sanitized_user_login, $user_email, $errors );
  2212. /**
  2213. * Filters the errors encountered when a new user is being registered.
  2214. *
  2215. * The filtered WP_Error object may, for example, contain errors for an invalid
  2216. * or existing username or email address. A WP_Error object should always returned,
  2217. * but may or may not contain errors.
  2218. *
  2219. * If any errors are present in $errors, this will abort the user's registration.
  2220. *
  2221. * @since 2.1.0
  2222. *
  2223. * @param WP_Error $errors A WP_Error object containing any errors encountered
  2224. * during registration.
  2225. * @param string $sanitized_user_login User's username after it has been sanitized.
  2226. * @param string $user_email User's email.
  2227. */
  2228. $errors = apply_filters( 'registration_errors', $errors, $sanitized_user_login, $user_email );
  2229. if ( $errors->has_errors() ) {
  2230. return $errors;
  2231. }
  2232. $user_pass = wp_generate_password( 12, false );
  2233. $user_id = wp_create_user( $sanitized_user_login, $user_pass, $user_email );
  2234. if ( ! $user_id || is_wp_error( $user_id ) ) {
  2235. $errors->add(
  2236. 'registerfail',
  2237. sprintf(
  2238. /* translators: %s: Admin email address. */
  2239. __( '<strong>ERROR</strong>: Couldn&#8217;t register you&hellip; please contact the <a href="mailto:%s">webmaster</a> !' ),
  2240. get_option( 'admin_email' )
  2241. )
  2242. );
  2243. return $errors;
  2244. }
  2245. update_user_option( $user_id, 'default_password_nag', true, true ); //Set up the Password change nag.
  2246. /**
  2247. * Fires after a new user registration has been recorded.
  2248. *
  2249. * @since 4.4.0
  2250. *
  2251. * @param int $user_id ID of the newly registered user.
  2252. */
  2253. do_action( 'register_new_user', $user_id );
  2254. return $user_id;
  2255. }
  2256. /**
  2257. * Initiates email notifications related to the creation of new users.
  2258. *
  2259. * Notifications are sent both to the site admin and to the newly created user.
  2260. *
  2261. * @since 4.4.0
  2262. * @since 4.6.0 Converted the `$notify` parameter to accept 'user' for sending
  2263. * notifications only to the user created.
  2264. *
  2265. * @param int $user_id ID of the newly created user.
  2266. * @param string $notify Optional. Type of notification that should happen. Accepts 'admin'
  2267. * or an empty string (admin only), 'user', or 'both' (admin and user).
  2268. * Default 'both'.
  2269. */
  2270. function wp_send_new_user_notifications( $user_id, $notify = 'both' ) {
  2271. wp_new_user_notification( $user_id, null, $notify );
  2272. }
  2273. /**
  2274. * Retrieve the current session token from the logged_in cookie.
  2275. *
  2276. * @since 4.0.0
  2277. *
  2278. * @return string Token.
  2279. */
  2280. function wp_get_session_token() {
  2281. $cookie = wp_parse_auth_cookie( '', 'logged_in' );
  2282. return ! empty( $cookie['token'] ) ? $cookie['token'] : '';
  2283. }
  2284. /**
  2285. * Retrieve a list of sessions for the current user.
  2286. *
  2287. * @since 4.0.0
  2288. * @return array Array of sessions.
  2289. */
  2290. function wp_get_all_sessions() {
  2291. $manager = WP_Session_Tokens::get_instance( get_current_user_id() );
  2292. return $manager->get_all();
  2293. }
  2294. /**
  2295. * Remove the current session token from the database.
  2296. *
  2297. * @since 4.0.0
  2298. */
  2299. function wp_destroy_current_session() {
  2300. $token = wp_get_session_token();
  2301. if ( $token ) {
  2302. $manager = WP_Session_Tokens::get_instance( get_current_user_id() );
  2303. $manager->destroy( $token );
  2304. }
  2305. }
  2306. /**
  2307. * Remove all but the current session token for the current user for the database.
  2308. *
  2309. * @since 4.0.0
  2310. */
  2311. function wp_destroy_other_sessions() {
  2312. $token = wp_get_session_token();
  2313. if ( $token ) {
  2314. $manager = WP_Session_Tokens::get_instance( get_current_user_id() );
  2315. $manager->destroy_others( $token );
  2316. }
  2317. }
  2318. /**
  2319. * Remove all session tokens for the current user from the database.
  2320. *
  2321. * @since 4.0.0
  2322. */
  2323. function wp_destroy_all_sessions() {
  2324. $manager = WP_Session_Tokens::get_instance( get_current_user_id() );
  2325. $manager->destroy_all();
  2326. }
  2327. /**
  2328. * Get the user IDs of all users with no role on this site.
  2329. *
  2330. * @since 4.4.0
  2331. * @since 4.9.0 The `$site_id` parameter was added to support multisite.
  2332. *
  2333. * @param int|null $site_id Optional. The site ID to get users with no role for. Defaults to the current site.
  2334. * @return array Array of user IDs.
  2335. */
  2336. function wp_get_users_with_no_role( $site_id = null ) {
  2337. global $wpdb;
  2338. if ( ! $site_id ) {
  2339. $site_id = get_current_blog_id();
  2340. }
  2341. $prefix = $wpdb->get_blog_prefix( $site_id );
  2342. if ( is_multisite() && $site_id != get_current_blog_id() ) {
  2343. switch_to_blog( $site_id );
  2344. $role_names = wp_roles()->get_names();
  2345. restore_current_blog();
  2346. } else {
  2347. $role_names = wp_roles()->get_names();
  2348. }
  2349. $regex = implode( '|', array_keys( $role_names ) );
  2350. $regex = preg_replace( '/[^a-zA-Z_\|-]/', '', $regex );
  2351. $users = $wpdb->get_col(
  2352. $wpdb->prepare(
  2353. "
  2354. SELECT user_id
  2355. FROM $wpdb->usermeta
  2356. WHERE meta_key = '{$prefix}capabilities'
  2357. AND meta_value NOT REGEXP %s
  2358. ",
  2359. $regex
  2360. )
  2361. );
  2362. return $users;
  2363. }
  2364. /**
  2365. * Retrieves the current user object.
  2366. *
  2367. * Will set the current user, if the current user is not set. The current user
  2368. * will be set to the logged-in person. If no user is logged-in, then it will
  2369. * set the current user to 0, which is invalid and won't have any permissions.
  2370. *
  2371. * This function is used by the pluggable functions wp_get_current_user() and
  2372. * get_currentuserinfo(), the latter of which is deprecated but used for backward
  2373. * compatibility.
  2374. *
  2375. * @since 4.5.0
  2376. * @access private
  2377. *
  2378. * @see wp_get_current_user()
  2379. * @global WP_User $current_user Checks if the current user is set.
  2380. *
  2381. * @return WP_User Current WP_User instance.
  2382. */
  2383. function _wp_get_current_user() {
  2384. global $current_user;
  2385. if ( ! empty( $current_user ) ) {
  2386. if ( $current_user instanceof WP_User ) {
  2387. return $current_user;
  2388. }
  2389. // Upgrade stdClass to WP_User
  2390. if ( is_object( $current_user ) && isset( $current_user->ID ) ) {
  2391. $cur_id = $current_user->ID;
  2392. $current_user = null;
  2393. wp_set_current_user( $cur_id );
  2394. return $current_user;
  2395. }
  2396. // $current_user has a junk value. Force to WP_User with ID 0.
  2397. $current_user = null;
  2398. wp_set_current_user( 0 );
  2399. return $current_user;
  2400. }
  2401. if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST ) {
  2402. wp_set_current_user( 0 );
  2403. return $current_user;
  2404. }
  2405. /**
  2406. * Filters the current user.
  2407. *
  2408. * The default filters use this to determine the current user from the
  2409. * request's cookies, if available.
  2410. *
  2411. * Returning a value of false will effectively short-circuit setting
  2412. * the current user.
  2413. *
  2414. * @since 3.9.0
  2415. *
  2416. * @param int|bool $user_id User ID if one has been determined, false otherwise.
  2417. */
  2418. $user_id = apply_filters( 'determine_current_user', false );
  2419. if ( ! $user_id ) {
  2420. wp_set_current_user( 0 );
  2421. return $current_user;
  2422. }
  2423. wp_set_current_user( $user_id );
  2424. return $current_user;
  2425. }
  2426. /**
  2427. * Send a confirmation request email when a change of user email address is attempted.
  2428. *
  2429. * @since 3.0.0
  2430. * @since 4.9.0 This function was moved from wp-admin/includes/ms.php so it's no longer Multisite specific.
  2431. *
  2432. * @global WP_Error $errors WP_Error object.
  2433. */
  2434. function send_confirmation_on_profile_email() {
  2435. global $errors;
  2436. $current_user = wp_get_current_user();
  2437. if ( ! is_object( $errors ) ) {
  2438. $errors = new WP_Error();
  2439. }
  2440. if ( $current_user->ID != $_POST['user_id'] ) {
  2441. return false;
  2442. }
  2443. if ( $current_user->user_email != $_POST['email'] ) {
  2444. if ( ! is_email( $_POST['email'] ) ) {
  2445. $errors->add(
  2446. 'user_email',
  2447. __( '<strong>ERROR</strong>: The email address isn&#8217;t correct.' ),
  2448. array(
  2449. 'form-field' => 'email',
  2450. )
  2451. );
  2452. return;
  2453. }
  2454. if ( email_exists( $_POST['email'] ) ) {
  2455. $errors->add(
  2456. 'user_email',
  2457. __( '<strong>ERROR</strong>: The email address is already used.' ),
  2458. array(
  2459. 'form-field' => 'email',
  2460. )
  2461. );
  2462. delete_user_meta( $current_user->ID, '_new_email' );
  2463. return;
  2464. }
  2465. $hash = md5( $_POST['email'] . time() . wp_rand() );
  2466. $new_user_email = array(
  2467. 'hash' => $hash,
  2468. 'newemail' => $_POST['email'],
  2469. );
  2470. update_user_meta( $current_user->ID, '_new_email', $new_user_email );
  2471. $sitename = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES );
  2472. /* translators: Do not translate USERNAME, ADMIN_URL, EMAIL, SITENAME, SITEURL: those are placeholders. */
  2473. $email_text = __(
  2474. 'Howdy ###USERNAME###,
  2475. You recently requested to have the email address on your account changed.
  2476. If this is correct, please click on the following link to change it:
  2477. ###ADMIN_URL###
  2478. You can safely ignore and delete this email if you do not want to
  2479. take this action.
  2480. This email has been sent to ###EMAIL###
  2481. Regards,
  2482. All at ###SITENAME###
  2483. ###SITEURL###'
  2484. );
  2485. /**
  2486. * Filters the text of the email sent when a change of user email address is attempted.
  2487. *
  2488. * The following strings have a special meaning and will get replaced dynamically:
  2489. * ###USERNAME### The current user's username.
  2490. * ###ADMIN_URL### The link to click on to confirm the email change.
  2491. * ###EMAIL### The new email.
  2492. * ###SITENAME### The name of the site.
  2493. * ###SITEURL### The URL to the site.
  2494. *
  2495. * @since MU (3.0.0)
  2496. * @since 4.9.0 This filter is no longer Multisite specific.
  2497. *
  2498. * @param string $email_text Text in the email.
  2499. * @param array $new_user_email {
  2500. * Data relating to the new user email address.
  2501. *
  2502. * @type string $hash The secure hash used in the confirmation link URL.
  2503. * @type string $newemail The proposed new email address.
  2504. * }
  2505. */
  2506. $content = apply_filters( 'new_user_email_content', $email_text, $new_user_email );
  2507. $content = str_replace( '###USERNAME###', $current_user->user_login, $content );
  2508. $content = str_replace( '###ADMIN_URL###', esc_url( admin_url( 'profile.php?newuseremail=' . $hash ) ), $content );
  2509. $content = str_replace( '###EMAIL###', $_POST['email'], $content );
  2510. $content = str_replace( '###SITENAME###', $sitename, $content );
  2511. $content = str_replace( '###SITEURL###', home_url(), $content );
  2512. /* translators: New email address notification email subject. %s: Site title. */
  2513. wp_mail( $_POST['email'], sprintf( __( '[%s] Email Change Request' ), $sitename ), $content );
  2514. $_POST['email'] = $current_user->user_email;
  2515. }
  2516. }
  2517. /**
  2518. * Adds an admin notice alerting the user to check for confirmation request email
  2519. * after email address change.
  2520. *
  2521. * @since 3.0.0
  2522. * @since 4.9.0 This function was moved from wp-admin/includes/ms.php so it's no longer Multisite specific.
  2523. *
  2524. * @global string $pagenow
  2525. */
  2526. function new_user_email_admin_notice() {
  2527. global $pagenow;
  2528. if ( 'profile.php' === $pagenow && isset( $_GET['updated'] ) ) {
  2529. $email = get_user_meta( get_current_user_id(), '_new_email', true );
  2530. if ( $email ) {
  2531. /* translators: %s: New email address. */
  2532. echo '<div class="notice notice-info"><p>' . sprintf( __( 'Your email address has not been updated yet. Please check your inbox at %s for a confirmation email.' ), '<code>' . esc_html( $email['newemail'] ) . '</code>' ) . '</p></div>';
  2533. }
  2534. }
  2535. }
  2536. /**
  2537. * Get all user privacy request types.
  2538. *
  2539. * @since 4.9.6
  2540. * @access private
  2541. *
  2542. * @return array List of core privacy action types.
  2543. */
  2544. function _wp_privacy_action_request_types() {
  2545. return array(
  2546. 'export_personal_data',
  2547. 'remove_personal_data',
  2548. );
  2549. }
  2550. /**
  2551. * Registers the personal data exporter for users.
  2552. *
  2553. * @since 4.9.6
  2554. *
  2555. * @param array $exporters An array of personal data exporters.
  2556. * @return array An array of personal data exporters.
  2557. */
  2558. function wp_register_user_personal_data_exporter( $exporters ) {
  2559. $exporters['wordpress-user'] = array(
  2560. 'exporter_friendly_name' => __( 'WordPress User' ),
  2561. 'callback' => 'wp_user_personal_data_exporter',
  2562. );
  2563. return $exporters;
  2564. }
  2565. /**
  2566. * Finds and exports personal data associated with an email address from the user and user_meta table.
  2567. *
  2568. * @since 4.9.6
  2569. *
  2570. * @param string $email_address The users email address.
  2571. * @return array An array of personal data.
  2572. */
  2573. function wp_user_personal_data_exporter( $email_address ) {
  2574. $email_address = trim( $email_address );
  2575. $data_to_export = array();
  2576. $user = get_user_by( 'email', $email_address );
  2577. if ( ! $user ) {
  2578. return array(
  2579. 'data' => array(),
  2580. 'done' => true,
  2581. );
  2582. }
  2583. $user_meta = get_user_meta( $user->ID );
  2584. $user_prop_to_export = array(
  2585. 'ID' => __( 'User ID' ),
  2586. 'user_login' => __( 'User Login Name' ),
  2587. 'user_nicename' => __( 'User Nice Name' ),
  2588. 'user_email' => __( 'User Email' ),
  2589. 'user_url' => __( 'User URL' ),
  2590. 'user_registered' => __( 'User Registration Date' ),
  2591. 'display_name' => __( 'User Display Name' ),
  2592. 'nickname' => __( 'User Nickname' ),
  2593. 'first_name' => __( 'User First Name' ),
  2594. 'last_name' => __( 'User Last Name' ),
  2595. 'description' => __( 'User Description' ),
  2596. );
  2597. $user_data_to_export = array();
  2598. foreach ( $user_prop_to_export as $key => $name ) {
  2599. $value = '';
  2600. switch ( $key ) {
  2601. case 'ID':
  2602. case 'user_login':
  2603. case 'user_nicename':
  2604. case 'user_email':
  2605. case 'user_url':
  2606. case 'user_registered':
  2607. case 'display_name':
  2608. $value = $user->data->$key;
  2609. break;
  2610. case 'nickname':
  2611. case 'first_name':
  2612. case 'last_name':
  2613. case 'description':
  2614. $value = $user_meta[ $key ][0];
  2615. break;
  2616. }
  2617. if ( ! empty( $value ) ) {
  2618. $user_data_to_export[] = array(
  2619. 'name' => $name,
  2620. 'value' => $value,
  2621. );
  2622. }
  2623. }
  2624. $data_to_export[] = array(
  2625. 'group_id' => 'user',
  2626. 'group_label' => __( 'User' ),
  2627. 'group_description' => __( 'User&#8217;s profile data.' ),
  2628. 'item_id' => "user-{$user->ID}",
  2629. 'data' => $user_data_to_export,
  2630. );
  2631. return array(
  2632. 'data' => $data_to_export,
  2633. 'done' => true,
  2634. );
  2635. }
  2636. /**
  2637. * Update log when privacy request is confirmed.
  2638. *
  2639. * @since 4.9.6
  2640. * @access private
  2641. *
  2642. * @param int $request_id ID of the request.
  2643. */
  2644. function _wp_privacy_account_request_confirmed( $request_id ) {
  2645. $request = wp_get_user_request_data( $request_id );
  2646. if ( ! $request ) {
  2647. return;
  2648. }
  2649. if ( ! in_array( $request->status, array( 'request-pending', 'request-failed' ), true ) ) {
  2650. return;
  2651. }
  2652. update_post_meta( $request_id, '_wp_user_request_confirmed_timestamp', time() );
  2653. wp_update_post(
  2654. array(
  2655. 'ID' => $request_id,
  2656. 'post_status' => 'request-confirmed',
  2657. )
  2658. );
  2659. }
  2660. /**
  2661. * Notify the site administrator via email when a request is confirmed.
  2662. *
  2663. * Without this, the admin would have to manually check the site to see if any
  2664. * action was needed on their part yet.
  2665. *
  2666. * @since 4.9.6
  2667. *
  2668. * @param int $request_id The ID of the request.
  2669. */
  2670. function _wp_privacy_send_request_confirmation_notification( $request_id ) {
  2671. $request = wp_get_user_request_data( $request_id );
  2672. if ( ! is_a( $request, 'WP_User_Request' ) || 'request-confirmed' !== $request->status ) {
  2673. return;
  2674. }
  2675. $already_notified = (bool) get_post_meta( $request_id, '_wp_admin_notified', true );
  2676. if ( $already_notified ) {
  2677. return;
  2678. }
  2679. $manage_url = add_query_arg( 'page', $request->action_name, admin_url( 'tools.php' ) );
  2680. $action_description = wp_user_request_action_description( $request->action_name );
  2681. /**
  2682. * Filters the recipient of the data request confirmation notification.
  2683. *
  2684. * In a Multisite environment, this will default to the email address of the
  2685. * network admin because, by default, single site admins do not have the
  2686. * capabilities required to process requests. Some networks may wish to
  2687. * delegate those capabilities to a single-site admin, or a dedicated person
  2688. * responsible for managing privacy requests.
  2689. *
  2690. * @since 4.9.6
  2691. *
  2692. * @param string $admin_email The email address of the notification recipient.
  2693. * @param WP_User_Request $request The request that is initiating the notification.
  2694. */
  2695. $admin_email = apply_filters( 'user_request_confirmed_email_to', get_site_option( 'admin_email' ), $request );
  2696. $email_data = array(
  2697. 'request' => $request,
  2698. 'user_email' => $request->email,
  2699. 'description' => $action_description,
  2700. 'manage_url' => $manage_url,
  2701. 'sitename' => wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES ),
  2702. 'siteurl' => home_url(),
  2703. 'admin_email' => $admin_email,
  2704. );
  2705. /* translators: Do not translate SITENAME, USER_EMAIL, DESCRIPTION, MANAGE_URL, SITEURL; those are placeholders. */
  2706. $email_text = __(
  2707. 'Howdy,
  2708. A user data privacy request has been confirmed on ###SITENAME###:
  2709. User: ###USER_EMAIL###
  2710. Request: ###DESCRIPTION###
  2711. You can view and manage these data privacy requests here:
  2712. ###MANAGE_URL###
  2713. Regards,
  2714. All at ###SITENAME###
  2715. ###SITEURL###'
  2716. );
  2717. /**
  2718. * Filters the body of the user request confirmation email.
  2719. *
  2720. * The email is sent to an administrator when an user request is confirmed.
  2721. * The following strings have a special meaning and will get replaced dynamically:
  2722. *
  2723. * ###SITENAME### The name of the site.
  2724. * ###USER_EMAIL### The user email for the request.
  2725. * ###DESCRIPTION### Description of the action being performed so the user knows what the email is for.
  2726. * ###MANAGE_URL### The URL to manage requests.
  2727. * ###SITEURL### The URL to the site.
  2728. *
  2729. * @since 4.9.6
  2730. *
  2731. * @param string $email_text Text in the email.
  2732. * @param array $email_data {
  2733. * Data relating to the account action email.
  2734. *
  2735. * @type WP_User_Request $request User request object.
  2736. * @type string $user_email The email address confirming a request
  2737. * @type string $description Description of the action being performed so the user knows what the email is for.
  2738. * @type string $manage_url The link to click manage privacy requests of this type.
  2739. * @type string $sitename The site name sending the mail.
  2740. * @type string $siteurl The site URL sending the mail.
  2741. * @type string $admin_email The administrator email receiving the mail.
  2742. * }
  2743. */
  2744. $content = apply_filters( 'user_confirmed_action_email_content', $email_text, $email_data );
  2745. $content = str_replace( '###SITENAME###', $email_data['sitename'], $content );
  2746. $content = str_replace( '###USER_EMAIL###', $email_data['user_email'], $content );
  2747. $content = str_replace( '###DESCRIPTION###', $email_data['description'], $content );
  2748. $content = str_replace( '###MANAGE_URL###', esc_url_raw( $email_data['manage_url'] ), $content );
  2749. $content = str_replace( '###SITEURL###', esc_url_raw( $email_data['siteurl'] ), $content );
  2750. $subject = sprintf(
  2751. /* translators: Privacy data request confirmed notification email subject. 1: Site title, 2: Name of the confirmed action. */
  2752. __( '[%1$s] Action Confirmed: %2$s' ),
  2753. $email_data['sitename'],
  2754. $action_description
  2755. );
  2756. /**
  2757. * Filters the subject of the user request confirmation email.
  2758. *
  2759. * @since 4.9.8
  2760. *
  2761. * @param string $subject The email subject.
  2762. * @param string $sitename The name of the site.
  2763. * @param array $email_data {
  2764. * Data relating to the account action email.
  2765. *
  2766. * @type WP_User_Request $request User request object.
  2767. * @type string $user_email The email address confirming a request
  2768. * @type string $description Description of the action being performed so the user knows what the email is for.
  2769. * @type string $manage_url The link to click manage privacy requests of this type.
  2770. * @type string $sitename The site name sending the mail.
  2771. * @type string $siteurl The site URL sending the mail.
  2772. * @type string $admin_email The administrator email receiving the mail.
  2773. * }
  2774. */
  2775. $subject = apply_filters( 'user_request_confirmed_email_subject', $subject, $email_data['sitename'], $email_data );
  2776. $email_sent = wp_mail( $email_data['admin_email'], $subject, $content );
  2777. if ( $email_sent ) {
  2778. update_post_meta( $request_id, '_wp_admin_notified', true );
  2779. }
  2780. }
  2781. /**
  2782. * Notify the user when their erasure request is fulfilled.
  2783. *
  2784. * Without this, the user would never know if their data was actually erased.
  2785. *
  2786. * @since 4.9.6
  2787. *
  2788. * @param int $request_id The privacy request post ID associated with this request.
  2789. */
  2790. function _wp_privacy_send_erasure_fulfillment_notification( $request_id ) {
  2791. $request = wp_get_user_request_data( $request_id );
  2792. if ( ! is_a( $request, 'WP_User_Request' ) || 'request-completed' !== $request->status ) {
  2793. return;
  2794. }
  2795. $already_notified = (bool) get_post_meta( $request_id, '_wp_user_notified', true );
  2796. if ( $already_notified ) {
  2797. return;
  2798. }
  2799. // Localize message content for user; fallback to site default for visitors.
  2800. if ( ! empty( $request->user_id ) ) {
  2801. $locale = get_user_locale( $request->user_id );
  2802. } else {
  2803. $locale = get_locale();
  2804. }
  2805. $switched_locale = switch_to_locale( $locale );
  2806. /**
  2807. * Filters the recipient of the data erasure fulfillment notification.
  2808. *
  2809. * @since 4.9.6
  2810. *
  2811. * @param string $user_email The email address of the notification recipient.
  2812. * @param WP_User_Request $request The request that is initiating the notification.
  2813. */
  2814. $user_email = apply_filters( 'user_erasure_fulfillment_email_to', $request->email, $request );
  2815. $email_data = array(
  2816. 'request' => $request,
  2817. 'message_recipient' => $user_email,
  2818. 'privacy_policy_url' => get_privacy_policy_url(),
  2819. 'sitename' => wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES ),
  2820. 'siteurl' => home_url(),
  2821. );
  2822. $subject = sprintf(
  2823. /* translators: Erasure request fulfilled notification email subject. %s: Site title. */
  2824. __( '[%s] Erasure Request Fulfilled' ),
  2825. $email_data['sitename']
  2826. );
  2827. /**
  2828. * Filters the subject of the email sent when an erasure request is completed.
  2829. *
  2830. * @since 4.9.8
  2831. *
  2832. * @param string $subject The email subject.
  2833. * @param string $sitename The name of the site.
  2834. * @param array $email_data {
  2835. * Data relating to the account action email.
  2836. *
  2837. * @type WP_User_Request $request User request object.
  2838. * @type string $message_recipient The address that the email will be sent to. Defaults
  2839. * to the value of `$request->email`, but can be changed
  2840. * by the `user_erasure_fulfillment_email_to` filter.
  2841. * @type string $privacy_policy_url Privacy policy URL.
  2842. * @type string $sitename The site name sending the mail.
  2843. * @type string $siteurl The site URL sending the mail.
  2844. * }
  2845. */
  2846. $subject = apply_filters( 'user_erasure_complete_email_subject', $subject, $email_data['sitename'], $email_data );
  2847. if ( empty( $email_data['privacy_policy_url'] ) ) {
  2848. /* translators: Do not translate SITENAME, SITEURL; those are placeholders. */
  2849. $email_text = __(
  2850. 'Howdy,
  2851. Your request to erase your personal data on ###SITENAME### has been completed.
  2852. If you have any follow-up questions or concerns, please contact the site administrator.
  2853. Regards,
  2854. All at ###SITENAME###
  2855. ###SITEURL###'
  2856. );
  2857. } else {
  2858. /* translators: Do not translate SITENAME, SITEURL, PRIVACY_POLICY_URL; those are placeholders. */
  2859. $email_text = __(
  2860. 'Howdy,
  2861. Your request to erase your personal data on ###SITENAME### has been completed.
  2862. If you have any follow-up questions or concerns, please contact the site administrator.
  2863. For more information, you can also read our privacy policy: ###PRIVACY_POLICY_URL###
  2864. Regards,
  2865. All at ###SITENAME###
  2866. ###SITEURL###'
  2867. );
  2868. }
  2869. /**
  2870. * Filters the body of the data erasure fulfillment notification.
  2871. *
  2872. * The email is sent to a user when a their data erasure request is fulfilled
  2873. * by an administrator.
  2874. *
  2875. * The following strings have a special meaning and will get replaced dynamically:
  2876. *
  2877. * ###SITENAME### The name of the site.
  2878. * ###PRIVACY_POLICY_URL### Privacy policy page URL.
  2879. * ###SITEURL### The URL to the site.
  2880. *
  2881. * @since 4.9.6
  2882. *
  2883. * @param string $email_text Text in the email.
  2884. * @param array $email_data {
  2885. * Data relating to the account action email.
  2886. *
  2887. * @type WP_User_Request $request User request object.
  2888. * @type string $message_recipient The address that the email will be sent to. Defaults
  2889. * to the value of `$request->email`, but can be changed
  2890. * by the `user_erasure_fulfillment_email_to` filter.
  2891. * @type string $privacy_policy_url Privacy policy URL.
  2892. * @type string $sitename The site name sending the mail.
  2893. * @type string $siteurl The site URL sending the mail.
  2894. * }
  2895. */
  2896. $content = apply_filters( 'user_confirmed_action_email_content', $email_text, $email_data );
  2897. $content = str_replace( '###SITENAME###', $email_data['sitename'], $content );
  2898. $content = str_replace( '###PRIVACY_POLICY_URL###', $email_data['privacy_policy_url'], $content );
  2899. $content = str_replace( '###SITEURL###', esc_url_raw( $email_data['siteurl'] ), $content );
  2900. $email_sent = wp_mail( $user_email, $subject, $content );
  2901. if ( $switched_locale ) {
  2902. restore_previous_locale();
  2903. }
  2904. if ( $email_sent ) {
  2905. update_post_meta( $request_id, '_wp_user_notified', true );
  2906. }
  2907. }
  2908. /**
  2909. * Return request confirmation message HTML.
  2910. *
  2911. * @since 4.9.6
  2912. * @access private
  2913. *
  2914. * @param int $request_id The request ID being confirmed.
  2915. * @return string $message The confirmation message.
  2916. */
  2917. function _wp_privacy_account_request_confirmed_message( $request_id ) {
  2918. $request = wp_get_user_request_data( $request_id );
  2919. $message = '<p class="success">' . __( 'Action has been confirmed.' ) . '</p>';
  2920. $message .= '<p>' . __( 'The site administrator has been notified and will fulfill your request as soon as possible.' ) . '</p>';
  2921. if ( $request && in_array( $request->action_name, _wp_privacy_action_request_types(), true ) ) {
  2922. if ( 'export_personal_data' === $request->action_name ) {
  2923. $message = '<p class="success">' . __( 'Thanks for confirming your export request.' ) . '</p>';
  2924. $message .= '<p>' . __( 'The site administrator has been notified. You will receive a link to download your export via email when they fulfill your request.' ) . '</p>';
  2925. } elseif ( 'remove_personal_data' === $request->action_name ) {
  2926. $message = '<p class="success">' . __( 'Thanks for confirming your erasure request.' ) . '</p>';
  2927. $message .= '<p>' . __( 'The site administrator has been notified. You will receive an email confirmation when they erase your data.' ) . '</p>';
  2928. }
  2929. }
  2930. /**
  2931. * Filters the message displayed to a user when they confirm a data request.
  2932. *
  2933. * @since 4.9.6
  2934. *
  2935. * @param string $message The message to the user.
  2936. * @param int $request_id The ID of the request being confirmed.
  2937. */
  2938. $message = apply_filters( 'user_request_action_confirmed_message', $message, $request_id );
  2939. return $message;
  2940. }
  2941. /**
  2942. * Create and log a user request to perform a specific action.
  2943. *
  2944. * Requests are stored inside a post type named `user_request` since they can apply to both
  2945. * users on the site, or guests without a user account.
  2946. *
  2947. * @since 4.9.6
  2948. *
  2949. * @param string $email_address User email address. This can be the address of a registered or non-registered user.
  2950. * @param string $action_name Name of the action that is being confirmed. Required.
  2951. * @param array $request_data Misc data you want to send with the verification request and pass to the actions once the request is confirmed.
  2952. * @return int|WP_Error Returns the request ID if successful, or a WP_Error object on failure.
  2953. */
  2954. function wp_create_user_request( $email_address = '', $action_name = '', $request_data = array() ) {
  2955. $email_address = sanitize_email( $email_address );
  2956. $action_name = sanitize_key( $action_name );
  2957. if ( ! is_email( $email_address ) ) {
  2958. return new WP_Error( 'invalid_email', __( 'Invalid email address.' ) );
  2959. }
  2960. if ( ! $action_name ) {
  2961. return new WP_Error( 'invalid_action', __( 'Invalid action name.' ) );
  2962. }
  2963. $user = get_user_by( 'email', $email_address );
  2964. $user_id = $user && ! is_wp_error( $user ) ? $user->ID : 0;
  2965. // Check for duplicates.
  2966. $requests_query = new WP_Query(
  2967. array(
  2968. 'post_type' => 'user_request',
  2969. 'post_name__in' => array( $action_name ), // Action name stored in post_name column.
  2970. 'title' => $email_address, // Email address stored in post_title column.
  2971. 'post_status' => array(
  2972. 'request-pending',
  2973. 'request-confirmed',
  2974. ),
  2975. 'fields' => 'ids',
  2976. )
  2977. );
  2978. if ( $requests_query->found_posts ) {
  2979. return new WP_Error( 'duplicate_request', __( 'An incomplete request for this email address already exists.' ) );
  2980. }
  2981. $request_id = wp_insert_post(
  2982. array(
  2983. 'post_author' => $user_id,
  2984. 'post_name' => $action_name,
  2985. 'post_title' => $email_address,
  2986. 'post_content' => wp_json_encode( $request_data ),
  2987. 'post_status' => 'request-pending',
  2988. 'post_type' => 'user_request',
  2989. 'post_date' => current_time( 'mysql', false ),
  2990. 'post_date_gmt' => current_time( 'mysql', true ),
  2991. ),
  2992. true
  2993. );
  2994. return $request_id;
  2995. }
  2996. /**
  2997. * Get action description from the name and return a string.
  2998. *
  2999. * @since 4.9.6
  3000. *
  3001. * @param string $action_name Action name of the request.
  3002. * @return string Human readable action name.
  3003. */
  3004. function wp_user_request_action_description( $action_name ) {
  3005. switch ( $action_name ) {
  3006. case 'export_personal_data':
  3007. $description = __( 'Export Personal Data' );
  3008. break;
  3009. case 'remove_personal_data':
  3010. $description = __( 'Erase Personal Data' );
  3011. break;
  3012. default:
  3013. /* translators: %s: Action name. */
  3014. $description = sprintf( __( 'Confirm the "%s" action' ), $action_name );
  3015. break;
  3016. }
  3017. /**
  3018. * Filters the user action description.
  3019. *
  3020. * @since 4.9.6
  3021. *
  3022. * @param string $description The default description.
  3023. * @param string $action_name The name of the request.
  3024. */
  3025. return apply_filters( 'user_request_action_description', $description, $action_name );
  3026. }
  3027. /**
  3028. * Send a confirmation request email to confirm an action.
  3029. *
  3030. * If the request is not already pending, it will be updated.
  3031. *
  3032. * @since 4.9.6
  3033. *
  3034. * @param string $request_id ID of the request created via wp_create_user_request().
  3035. * @return bool|WP_Error True on success, `WP_Error` on failure.
  3036. */
  3037. function wp_send_user_request( $request_id ) {
  3038. $request_id = absint( $request_id );
  3039. $request = wp_get_user_request_data( $request_id );
  3040. if ( ! $request ) {
  3041. return new WP_Error( 'invalid_request', __( 'Invalid user request.' ) );
  3042. }
  3043. // Localize message content for user; fallback to site default for visitors.
  3044. if ( ! empty( $request->user_id ) ) {
  3045. $locale = get_user_locale( $request->user_id );
  3046. } else {
  3047. $locale = get_locale();
  3048. }
  3049. $switched_locale = switch_to_locale( $locale );
  3050. $email_data = array(
  3051. 'request' => $request,
  3052. 'email' => $request->email,
  3053. 'description' => wp_user_request_action_description( $request->action_name ),
  3054. 'confirm_url' => add_query_arg(
  3055. array(
  3056. 'action' => 'confirmaction',
  3057. 'request_id' => $request_id,
  3058. 'confirm_key' => wp_generate_user_request_key( $request_id ),
  3059. ),
  3060. wp_login_url()
  3061. ),
  3062. 'sitename' => wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES ),
  3063. 'siteurl' => home_url(),
  3064. );
  3065. /* translators: Do not translate DESCRIPTION, CONFIRM_URL, SITENAME, SITEURL: those are placeholders. */
  3066. $email_text = __(
  3067. 'Howdy,
  3068. A request has been made to perform the following action on your account:
  3069. ###DESCRIPTION###
  3070. To confirm this, please click on the following link:
  3071. ###CONFIRM_URL###
  3072. You can safely ignore and delete this email if you do not want to
  3073. take this action.
  3074. Regards,
  3075. All at ###SITENAME###
  3076. ###SITEURL###'
  3077. );
  3078. /**
  3079. * Filters the text of the email sent when an account action is attempted.
  3080. *
  3081. * The following strings have a special meaning and will get replaced dynamically:
  3082. *
  3083. * ###DESCRIPTION### Description of the action being performed so the user knows what the email is for.
  3084. * ###CONFIRM_URL### The link to click on to confirm the account action.
  3085. * ###SITENAME### The name of the site.
  3086. * ###SITEURL### The URL to the site.
  3087. *
  3088. * @since 4.9.6
  3089. *
  3090. * @param string $email_text Text in the email.
  3091. * @param array $email_data {
  3092. * Data relating to the account action email.
  3093. *
  3094. * @type WP_User_Request $request User request object.
  3095. * @type string $email The email address this is being sent to.
  3096. * @type string $description Description of the action being performed so the user knows what the email is for.
  3097. * @type string $confirm_url The link to click on to confirm the account action.
  3098. * @type string $sitename The site name sending the mail.
  3099. * @type string $siteurl The site URL sending the mail.
  3100. * }
  3101. */
  3102. $content = apply_filters( 'user_request_action_email_content', $email_text, $email_data );
  3103. $content = str_replace( '###DESCRIPTION###', $email_data['description'], $content );
  3104. $content = str_replace( '###CONFIRM_URL###', esc_url_raw( $email_data['confirm_url'] ), $content );
  3105. $content = str_replace( '###EMAIL###', $email_data['email'], $content );
  3106. $content = str_replace( '###SITENAME###', $email_data['sitename'], $content );
  3107. $content = str_replace( '###SITEURL###', esc_url_raw( $email_data['siteurl'] ), $content );
  3108. /* translators: Confirm privacy data request notification email subject. 1: Site title, 2: Name of the action. */
  3109. $subject = sprintf( __( '[%1$s] Confirm Action: %2$s' ), $email_data['sitename'], $email_data['description'] );
  3110. /**
  3111. * Filters the subject of the email sent when an account action is attempted.
  3112. *
  3113. * @since 4.9.6
  3114. *
  3115. * @param string $subject The email subject.
  3116. * @param string $sitename The name of the site.
  3117. * @param array $email_data {
  3118. * Data relating to the account action email.
  3119. *
  3120. * @type WP_User_Request $request User request object.
  3121. * @type string $email The email address this is being sent to.
  3122. * @type string $description Description of the action being performed so the user knows what the email is for.
  3123. * @type string $confirm_url The link to click on to confirm the account action.
  3124. * @type string $sitename The site name sending the mail.
  3125. * @type string $siteurl The site URL sending the mail.
  3126. * }
  3127. */
  3128. $subject = apply_filters( 'user_request_action_email_subject', $subject, $email_data['sitename'], $email_data );
  3129. $email_sent = wp_mail( $email_data['email'], $subject, $content );
  3130. if ( $switched_locale ) {
  3131. restore_previous_locale();
  3132. }
  3133. if ( ! $email_sent ) {
  3134. return new WP_Error( 'privacy_email_error', __( 'Unable to send personal data export confirmation email.' ) );
  3135. }
  3136. return true;
  3137. }
  3138. /**
  3139. * Returns a confirmation key for a user action and stores the hashed version for future comparison.
  3140. *
  3141. * @since 4.9.6
  3142. *
  3143. * @param int $request_id Request ID.
  3144. * @return string Confirmation key.
  3145. */
  3146. function wp_generate_user_request_key( $request_id ) {
  3147. global $wp_hasher;
  3148. // Generate something random for a confirmation key.
  3149. $key = wp_generate_password( 20, false );
  3150. // Return the key, hashed.
  3151. if ( empty( $wp_hasher ) ) {
  3152. require_once ABSPATH . WPINC . '/class-phpass.php';
  3153. $wp_hasher = new PasswordHash( 8, true );
  3154. }
  3155. wp_update_post(
  3156. array(
  3157. 'ID' => $request_id,
  3158. 'post_status' => 'request-pending',
  3159. 'post_password' => $wp_hasher->HashPassword( $key ),
  3160. )
  3161. );
  3162. return $key;
  3163. }
  3164. /**
  3165. * Validate a user request by comparing the key with the request's key.
  3166. *
  3167. * @since 4.9.6
  3168. *
  3169. * @param string $request_id ID of the request being confirmed.
  3170. * @param string $key Provided key to validate.
  3171. * @return bool|WP_Error WP_Error on failure, true on success.
  3172. */
  3173. function wp_validate_user_request_key( $request_id, $key ) {
  3174. global $wp_hasher;
  3175. $request_id = absint( $request_id );
  3176. $request = wp_get_user_request_data( $request_id );
  3177. if ( ! $request ) {
  3178. return new WP_Error( 'invalid_request', __( 'Invalid request.' ) );
  3179. }
  3180. if ( ! in_array( $request->status, array( 'request-pending', 'request-failed' ), true ) ) {
  3181. return new WP_Error( 'expired_link', __( 'This link has expired.' ) );
  3182. }
  3183. if ( empty( $key ) ) {
  3184. return new WP_Error( 'missing_key', __( 'Missing confirm key.' ) );
  3185. }
  3186. if ( empty( $wp_hasher ) ) {
  3187. require_once ABSPATH . WPINC . '/class-phpass.php';
  3188. $wp_hasher = new PasswordHash( 8, true );
  3189. }
  3190. $key_request_time = $request->modified_timestamp;
  3191. $saved_key = $request->confirm_key;
  3192. if ( ! $saved_key ) {
  3193. return new WP_Error( 'invalid_key', __( 'Invalid key.' ) );
  3194. }
  3195. if ( ! $key_request_time ) {
  3196. return new WP_Error( 'invalid_key', __( 'Invalid action.' ) );
  3197. }
  3198. /**
  3199. * Filters the expiration time of confirm keys.
  3200. *
  3201. * @since 4.9.6
  3202. *
  3203. * @param int $expiration The expiration time in seconds.
  3204. */
  3205. $expiration_duration = (int) apply_filters( 'user_request_key_expiration', DAY_IN_SECONDS );
  3206. $expiration_time = $key_request_time + $expiration_duration;
  3207. if ( ! $wp_hasher->CheckPassword( $key, $saved_key ) ) {
  3208. return new WP_Error( 'invalid_key', __( 'Invalid key.' ) );
  3209. }
  3210. if ( ! $expiration_time || time() > $expiration_time ) {
  3211. return new WP_Error( 'expired_key', __( 'The confirmation email has expired.' ) );
  3212. }
  3213. return true;
  3214. }
  3215. /**
  3216. * Return data about a user request.
  3217. *
  3218. * @since 4.9.6
  3219. *
  3220. * @param int $request_id Request ID to get data about.
  3221. * @return WP_User_Request|false
  3222. */
  3223. function wp_get_user_request_data( $request_id ) {
  3224. $request_id = absint( $request_id );
  3225. $post = get_post( $request_id );
  3226. if ( ! $post || 'user_request' !== $post->post_type ) {
  3227. return false;
  3228. }
  3229. return new WP_User_Request( $post );
  3230. }