Nenhuma Descrição

user.php 152KB

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