user.php 165 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006
  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. * Authenticates 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. * Authenticates 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. * Strips 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, checks 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. * Gets the number of posts a 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. * Gets the 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. * Gets 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. * Retrieves 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. * Updates 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. * Deletes 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. * Retrieves 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. * Lists all the users of the site, with several options available.
  666. *
  667. * @since 5.9.0
  668. *
  669. * @param string|array $args {
  670. * Optional. Array or string of default arguments.
  671. *
  672. * @type string $orderby How to sort the users. Accepts 'nicename', 'email', 'url', 'registered',
  673. * 'user_nicename', 'user_email', 'user_url', 'user_registered', 'name',
  674. * 'display_name', 'post_count', 'ID', 'meta_value', 'user_login'. Default 'name'.
  675. * @type string $order Sorting direction for $orderby. Accepts 'ASC', 'DESC'. Default 'ASC'.
  676. * @type int $number Maximum users to return or display. Default empty (all users).
  677. * @type bool $exclude_admin Whether to exclude the 'admin' account, if it exists. Default false.
  678. * @type bool $show_fullname Whether to show the user's full name. Default false.
  679. * @type string $feed If not empty, show a link to the user's feed and use this text as the alt
  680. * parameter of the link. Default empty.
  681. * @type string $feed_image If not empty, show a link to the user's feed and use this image URL as
  682. * clickable anchor. Default empty.
  683. * @type string $feed_type The feed type to link to, such as 'rss2'. Defaults to default feed type.
  684. * @type bool $echo Whether to output the result or instead return it. Default true.
  685. * @type string $style If 'list', each user is wrapped in an `<li>` element, otherwise the users
  686. * will be separated by commas.
  687. * @type bool $html Whether to list the items in HTML form or plaintext. Default true.
  688. * @type string $exclude An array, comma-, or space-separated list of user IDs to exclude. Default empty.
  689. * @type string $include An array, comma-, or space-separated list of user IDs to include. Default empty.
  690. * }
  691. * @return string|null The output if echo is false. Otherwise null.
  692. */
  693. function wp_list_users( $args = array() ) {
  694. $defaults = array(
  695. 'orderby' => 'name',
  696. 'order' => 'ASC',
  697. 'number' => '',
  698. 'exclude_admin' => true,
  699. 'show_fullname' => false,
  700. 'feed' => '',
  701. 'feed_image' => '',
  702. 'feed_type' => '',
  703. 'echo' => true,
  704. 'style' => 'list',
  705. 'html' => true,
  706. 'exclude' => '',
  707. 'include' => '',
  708. );
  709. $parsed_args = wp_parse_args( $args, $defaults );
  710. $return = '';
  711. $query_args = wp_array_slice_assoc( $parsed_args, array( 'orderby', 'order', 'number', 'exclude', 'include' ) );
  712. $query_args['fields'] = 'ids';
  713. /**
  714. * Filters the query arguments for the list of all users of the site.
  715. *
  716. * @since 6.1.0
  717. *
  718. * @param array $query_args The query arguments for get_users().
  719. * @param array $parsed_args The arguments passed to wp_list_users() combined with the defaults.
  720. */
  721. $query_args = apply_filters( 'wp_list_users_args', $query_args, $parsed_args );
  722. $users = get_users( $query_args );
  723. foreach ( $users as $user_id ) {
  724. $user = get_userdata( $user_id );
  725. if ( $parsed_args['exclude_admin'] && 'admin' === $user->display_name ) {
  726. continue;
  727. }
  728. if ( $parsed_args['show_fullname'] && '' !== $user->first_name && '' !== $user->last_name ) {
  729. $name = sprintf(
  730. /* translators: 1: User's first name, 2: Last name. */
  731. _x( '%1$s %2$s', 'Display name based on first name and last name' ),
  732. $user->first_name,
  733. $user->last_name
  734. );
  735. } else {
  736. $name = $user->display_name;
  737. }
  738. if ( ! $parsed_args['html'] ) {
  739. $return .= $name . ', ';
  740. continue; // No need to go further to process HTML.
  741. }
  742. if ( 'list' === $parsed_args['style'] ) {
  743. $return .= '<li>';
  744. }
  745. $row = $name;
  746. if ( ! empty( $parsed_args['feed_image'] ) || ! empty( $parsed_args['feed'] ) ) {
  747. $row .= ' ';
  748. if ( empty( $parsed_args['feed_image'] ) ) {
  749. $row .= '(';
  750. }
  751. $row .= '<a href="' . get_author_feed_link( $user->ID, $parsed_args['feed_type'] ) . '"';
  752. $alt = '';
  753. if ( ! empty( $parsed_args['feed'] ) ) {
  754. $alt = ' alt="' . esc_attr( $parsed_args['feed'] ) . '"';
  755. $name = $parsed_args['feed'];
  756. }
  757. $row .= '>';
  758. if ( ! empty( $parsed_args['feed_image'] ) ) {
  759. $row .= '<img src="' . esc_url( $parsed_args['feed_image'] ) . '" style="border: none;"' . $alt . ' />';
  760. } else {
  761. $row .= $name;
  762. }
  763. $row .= '</a>';
  764. if ( empty( $parsed_args['feed_image'] ) ) {
  765. $row .= ')';
  766. }
  767. }
  768. $return .= $row;
  769. $return .= ( 'list' === $parsed_args['style'] ) ? '</li>' : ', ';
  770. }
  771. $return = rtrim( $return, ', ' );
  772. if ( ! $parsed_args['echo'] ) {
  773. return $return;
  774. }
  775. echo $return;
  776. }
  777. /**
  778. * Gets the sites a user belongs to.
  779. *
  780. * @since 3.0.0
  781. * @since 4.7.0 Converted to use `get_sites()`.
  782. *
  783. * @global wpdb $wpdb WordPress database abstraction object.
  784. *
  785. * @param int $user_id User ID
  786. * @param bool $all Whether to retrieve all sites, or only sites that are not
  787. * marked as deleted, archived, or spam.
  788. * @return object[] A list of the user's sites. An empty array if the user doesn't exist
  789. * or belongs to no sites.
  790. */
  791. function get_blogs_of_user( $user_id, $all = false ) {
  792. global $wpdb;
  793. $user_id = (int) $user_id;
  794. // Logged out users can't have sites.
  795. if ( empty( $user_id ) ) {
  796. return array();
  797. }
  798. /**
  799. * Filters the list of a user's sites before it is populated.
  800. *
  801. * Returning a non-null value from the filter will effectively short circuit
  802. * get_blogs_of_user(), returning that value instead.
  803. *
  804. * @since 4.6.0
  805. *
  806. * @param null|object[] $sites An array of site objects of which the user is a member.
  807. * @param int $user_id User ID.
  808. * @param bool $all Whether the returned array should contain all sites, including
  809. * those marked 'deleted', 'archived', or 'spam'. Default false.
  810. */
  811. $sites = apply_filters( 'pre_get_blogs_of_user', null, $user_id, $all );
  812. if ( null !== $sites ) {
  813. return $sites;
  814. }
  815. $keys = get_user_meta( $user_id );
  816. if ( empty( $keys ) ) {
  817. return array();
  818. }
  819. if ( ! is_multisite() ) {
  820. $site_id = get_current_blog_id();
  821. $sites = array( $site_id => new stdClass );
  822. $sites[ $site_id ]->userblog_id = $site_id;
  823. $sites[ $site_id ]->blogname = get_option( 'blogname' );
  824. $sites[ $site_id ]->domain = '';
  825. $sites[ $site_id ]->path = '';
  826. $sites[ $site_id ]->site_id = 1;
  827. $sites[ $site_id ]->siteurl = get_option( 'siteurl' );
  828. $sites[ $site_id ]->archived = 0;
  829. $sites[ $site_id ]->spam = 0;
  830. $sites[ $site_id ]->deleted = 0;
  831. return $sites;
  832. }
  833. $site_ids = array();
  834. if ( isset( $keys[ $wpdb->base_prefix . 'capabilities' ] ) && defined( 'MULTISITE' ) ) {
  835. $site_ids[] = 1;
  836. unset( $keys[ $wpdb->base_prefix . 'capabilities' ] );
  837. }
  838. $keys = array_keys( $keys );
  839. foreach ( $keys as $key ) {
  840. if ( 'capabilities' !== substr( $key, -12 ) ) {
  841. continue;
  842. }
  843. if ( $wpdb->base_prefix && 0 !== strpos( $key, $wpdb->base_prefix ) ) {
  844. continue;
  845. }
  846. $site_id = str_replace( array( $wpdb->base_prefix, '_capabilities' ), '', $key );
  847. if ( ! is_numeric( $site_id ) ) {
  848. continue;
  849. }
  850. $site_ids[] = (int) $site_id;
  851. }
  852. $sites = array();
  853. if ( ! empty( $site_ids ) ) {
  854. $args = array(
  855. 'number' => '',
  856. 'site__in' => $site_ids,
  857. 'update_site_meta_cache' => false,
  858. );
  859. if ( ! $all ) {
  860. $args['archived'] = 0;
  861. $args['spam'] = 0;
  862. $args['deleted'] = 0;
  863. }
  864. $_sites = get_sites( $args );
  865. foreach ( $_sites as $site ) {
  866. $sites[ $site->id ] = (object) array(
  867. 'userblog_id' => $site->id,
  868. 'blogname' => $site->blogname,
  869. 'domain' => $site->domain,
  870. 'path' => $site->path,
  871. 'site_id' => $site->network_id,
  872. 'siteurl' => $site->siteurl,
  873. 'archived' => $site->archived,
  874. 'mature' => $site->mature,
  875. 'spam' => $site->spam,
  876. 'deleted' => $site->deleted,
  877. );
  878. }
  879. }
  880. /**
  881. * Filters the list of sites a user belongs to.
  882. *
  883. * @since MU (3.0.0)
  884. *
  885. * @param object[] $sites An array of site objects belonging to the user.
  886. * @param int $user_id User ID.
  887. * @param bool $all Whether the returned sites array should contain all sites, including
  888. * those marked 'deleted', 'archived', or 'spam'. Default false.
  889. */
  890. return apply_filters( 'get_blogs_of_user', $sites, $user_id, $all );
  891. }
  892. /**
  893. * Finds out whether a user is a member of a given blog.
  894. *
  895. * @since MU (3.0.0)
  896. *
  897. * @global wpdb $wpdb WordPress database abstraction object.
  898. *
  899. * @param int $user_id Optional. The unique ID of the user. Defaults to the current user.
  900. * @param int $blog_id Optional. ID of the blog to check. Defaults to the current site.
  901. * @return bool
  902. */
  903. function is_user_member_of_blog( $user_id = 0, $blog_id = 0 ) {
  904. global $wpdb;
  905. $user_id = (int) $user_id;
  906. $blog_id = (int) $blog_id;
  907. if ( empty( $user_id ) ) {
  908. $user_id = get_current_user_id();
  909. }
  910. // Technically not needed, but does save calls to get_site() and get_user_meta()
  911. // in the event that the function is called when a user isn't logged in.
  912. if ( empty( $user_id ) ) {
  913. return false;
  914. } else {
  915. $user = get_userdata( $user_id );
  916. if ( ! $user instanceof WP_User ) {
  917. return false;
  918. }
  919. }
  920. if ( ! is_multisite() ) {
  921. return true;
  922. }
  923. if ( empty( $blog_id ) ) {
  924. $blog_id = get_current_blog_id();
  925. }
  926. $blog = get_site( $blog_id );
  927. if ( ! $blog || ! isset( $blog->domain ) || $blog->archived || $blog->spam || $blog->deleted ) {
  928. return false;
  929. }
  930. $keys = get_user_meta( $user_id );
  931. if ( empty( $keys ) ) {
  932. return false;
  933. }
  934. // No underscore before capabilities in $base_capabilities_key.
  935. $base_capabilities_key = $wpdb->base_prefix . 'capabilities';
  936. $site_capabilities_key = $wpdb->base_prefix . $blog_id . '_capabilities';
  937. if ( isset( $keys[ $base_capabilities_key ] ) && 1 == $blog_id ) {
  938. return true;
  939. }
  940. if ( isset( $keys[ $site_capabilities_key ] ) ) {
  941. return true;
  942. }
  943. return false;
  944. }
  945. /**
  946. * Adds meta data to a user.
  947. *
  948. * @since 3.0.0
  949. *
  950. * @param int $user_id User ID.
  951. * @param string $meta_key Metadata name.
  952. * @param mixed $meta_value Metadata value. Must be serializable if non-scalar.
  953. * @param bool $unique Optional. Whether the same key should not be added.
  954. * Default false.
  955. * @return int|false Meta ID on success, false on failure.
  956. */
  957. function add_user_meta( $user_id, $meta_key, $meta_value, $unique = false ) {
  958. return add_metadata( 'user', $user_id, $meta_key, $meta_value, $unique );
  959. }
  960. /**
  961. * Removes metadata matching criteria from a user.
  962. *
  963. * You can match based on the key, or key and value. Removing based on key and
  964. * value, will keep from removing duplicate metadata with the same key. It also
  965. * allows removing all metadata matching key, if needed.
  966. *
  967. * @since 3.0.0
  968. *
  969. * @link https://developer.wordpress.org/reference/functions/delete_user_meta/
  970. *
  971. * @param int $user_id User ID
  972. * @param string $meta_key Metadata name.
  973. * @param mixed $meta_value Optional. Metadata value. If provided,
  974. * rows will only be removed that match the value.
  975. * Must be serializable if non-scalar. Default empty.
  976. * @return bool True on success, false on failure.
  977. */
  978. function delete_user_meta( $user_id, $meta_key, $meta_value = '' ) {
  979. return delete_metadata( 'user', $user_id, $meta_key, $meta_value );
  980. }
  981. /**
  982. * Retrieves user meta field for a user.
  983. *
  984. * @since 3.0.0
  985. *
  986. * @link https://developer.wordpress.org/reference/functions/get_user_meta/
  987. *
  988. * @param int $user_id User ID.
  989. * @param string $key Optional. The meta key to retrieve. By default,
  990. * returns data for all keys.
  991. * @param bool $single Optional. Whether to return a single value.
  992. * This parameter has no effect if `$key` is not specified.
  993. * Default false.
  994. * @return mixed An array of values if `$single` is false.
  995. * The value of meta data field if `$single` is true.
  996. * False for an invalid `$user_id` (non-numeric, zero, or negative value).
  997. * An empty string if a valid but non-existing user ID is passed.
  998. */
  999. function get_user_meta( $user_id, $key = '', $single = false ) {
  1000. return get_metadata( 'user', $user_id, $key, $single );
  1001. }
  1002. /**
  1003. * Updates user meta field based on user ID.
  1004. *
  1005. * Use the $prev_value parameter to differentiate between meta fields with the
  1006. * same key and user ID.
  1007. *
  1008. * If the meta field for the user does not exist, it will be added.
  1009. *
  1010. * @since 3.0.0
  1011. *
  1012. * @link https://developer.wordpress.org/reference/functions/update_user_meta/
  1013. *
  1014. * @param int $user_id User ID.
  1015. * @param string $meta_key Metadata key.
  1016. * @param mixed $meta_value Metadata value. Must be serializable if non-scalar.
  1017. * @param mixed $prev_value Optional. Previous value to check before updating.
  1018. * If specified, only update existing metadata entries with
  1019. * this value. Otherwise, update all entries. Default empty.
  1020. * @return int|bool Meta ID if the key didn't exist, true on successful update,
  1021. * false on failure or if the value passed to the function
  1022. * is the same as the one that is already in the database.
  1023. */
  1024. function update_user_meta( $user_id, $meta_key, $meta_value, $prev_value = '' ) {
  1025. return update_metadata( 'user', $user_id, $meta_key, $meta_value, $prev_value );
  1026. }
  1027. /**
  1028. * Counts number of users who have each of the user roles.
  1029. *
  1030. * Assumes there are neither duplicated nor orphaned capabilities meta_values.
  1031. * Assumes role names are unique phrases. Same assumption made by WP_User_Query::prepare_query()
  1032. * Using $strategy = 'time' this is CPU-intensive and should handle around 10^7 users.
  1033. * Using $strategy = 'memory' this is memory-intensive and should handle around 10^5 users, but see WP Bug #12257.
  1034. *
  1035. * @since 3.0.0
  1036. * @since 4.4.0 The number of users with no role is now included in the `none` element.
  1037. * @since 4.9.0 The `$site_id` parameter was added to support multisite.
  1038. *
  1039. * @global wpdb $wpdb WordPress database abstraction object.
  1040. *
  1041. * @param string $strategy Optional. The computational strategy to use when counting the users.
  1042. * Accepts either 'time' or 'memory'. Default 'time'.
  1043. * @param int|null $site_id Optional. The site ID to count users for. Defaults to the current site.
  1044. * @return array {
  1045. * User counts.
  1046. *
  1047. * @type int $total_users Total number of users on the site.
  1048. * @type int[] $avail_roles Array of user counts keyed by user role.
  1049. * }
  1050. */
  1051. function count_users( $strategy = 'time', $site_id = null ) {
  1052. global $wpdb;
  1053. // Initialize.
  1054. if ( ! $site_id ) {
  1055. $site_id = get_current_blog_id();
  1056. }
  1057. /**
  1058. * Filters the user count before queries are run.
  1059. *
  1060. * Return a non-null value to cause count_users() to return early.
  1061. *
  1062. * @since 5.1.0
  1063. *
  1064. * @param null|array $result The value to return instead. Default null to continue with the query.
  1065. * @param string $strategy Optional. The computational strategy to use when counting the users.
  1066. * Accepts either 'time' or 'memory'. Default 'time'.
  1067. * @param int $site_id The site ID to count users for.
  1068. */
  1069. $pre = apply_filters( 'pre_count_users', null, $strategy, $site_id );
  1070. if ( null !== $pre ) {
  1071. return $pre;
  1072. }
  1073. $blog_prefix = $wpdb->get_blog_prefix( $site_id );
  1074. $result = array();
  1075. if ( 'time' === $strategy ) {
  1076. if ( is_multisite() && get_current_blog_id() != $site_id ) {
  1077. switch_to_blog( $site_id );
  1078. $avail_roles = wp_roles()->get_names();
  1079. restore_current_blog();
  1080. } else {
  1081. $avail_roles = wp_roles()->get_names();
  1082. }
  1083. // Build a CPU-intensive query that will return concise information.
  1084. $select_count = array();
  1085. foreach ( $avail_roles as $this_role => $name ) {
  1086. $select_count[] = $wpdb->prepare( 'COUNT(NULLIF(`meta_value` LIKE %s, false))', '%' . $wpdb->esc_like( '"' . $this_role . '"' ) . '%' );
  1087. }
  1088. $select_count[] = "COUNT(NULLIF(`meta_value` = 'a:0:{}', false))";
  1089. $select_count = implode( ', ', $select_count );
  1090. // Add the meta_value index to the selection list, then run the query.
  1091. $row = $wpdb->get_row(
  1092. "
  1093. SELECT {$select_count}, COUNT(*)
  1094. FROM {$wpdb->usermeta}
  1095. INNER JOIN {$wpdb->users} ON user_id = ID
  1096. WHERE meta_key = '{$blog_prefix}capabilities'
  1097. ",
  1098. ARRAY_N
  1099. );
  1100. // Run the previous loop again to associate results with role names.
  1101. $col = 0;
  1102. $role_counts = array();
  1103. foreach ( $avail_roles as $this_role => $name ) {
  1104. $count = (int) $row[ $col++ ];
  1105. if ( $count > 0 ) {
  1106. $role_counts[ $this_role ] = $count;
  1107. }
  1108. }
  1109. $role_counts['none'] = (int) $row[ $col++ ];
  1110. // Get the meta_value index from the end of the result set.
  1111. $total_users = (int) $row[ $col ];
  1112. $result['total_users'] = $total_users;
  1113. $result['avail_roles'] =& $role_counts;
  1114. } else {
  1115. $avail_roles = array(
  1116. 'none' => 0,
  1117. );
  1118. $users_of_blog = $wpdb->get_col(
  1119. "
  1120. SELECT meta_value
  1121. FROM {$wpdb->usermeta}
  1122. INNER JOIN {$wpdb->users} ON user_id = ID
  1123. WHERE meta_key = '{$blog_prefix}capabilities'
  1124. "
  1125. );
  1126. foreach ( $users_of_blog as $caps_meta ) {
  1127. $b_roles = maybe_unserialize( $caps_meta );
  1128. if ( ! is_array( $b_roles ) ) {
  1129. continue;
  1130. }
  1131. if ( empty( $b_roles ) ) {
  1132. $avail_roles['none']++;
  1133. }
  1134. foreach ( $b_roles as $b_role => $val ) {
  1135. if ( isset( $avail_roles[ $b_role ] ) ) {
  1136. $avail_roles[ $b_role ]++;
  1137. } else {
  1138. $avail_roles[ $b_role ] = 1;
  1139. }
  1140. }
  1141. }
  1142. $result['total_users'] = count( $users_of_blog );
  1143. $result['avail_roles'] =& $avail_roles;
  1144. }
  1145. return $result;
  1146. }
  1147. /**
  1148. * Returns the number of active users in your installation.
  1149. *
  1150. * Note that on a large site the count may be cached and only updated twice daily.
  1151. *
  1152. * @since MU (3.0.0)
  1153. * @since 4.8.0 The `$network_id` parameter has been added.
  1154. * @since 6.0.0 Moved to wp-includes/user.php.
  1155. *
  1156. * @param int|null $network_id ID of the network. Defaults to the current network.
  1157. * @return int Number of active users on the network.
  1158. */
  1159. function get_user_count( $network_id = null ) {
  1160. if ( ! is_multisite() && null !== $network_id ) {
  1161. _doing_it_wrong(
  1162. __FUNCTION__,
  1163. sprintf(
  1164. /* translators: %s: $network_id */
  1165. __( 'Unable to pass %s if not using multisite.' ),
  1166. '<code>$network_id</code>'
  1167. ),
  1168. '6.0.0'
  1169. );
  1170. }
  1171. return (int) get_network_option( $network_id, 'user_count', -1 );
  1172. }
  1173. /**
  1174. * Updates the total count of users on the site if live user counting is enabled.
  1175. *
  1176. * @since 6.0.0
  1177. *
  1178. * @param int|null $network_id ID of the network. Defaults to the current network.
  1179. * @return bool Whether the update was successful.
  1180. */
  1181. function wp_maybe_update_user_counts( $network_id = null ) {
  1182. if ( ! is_multisite() && null !== $network_id ) {
  1183. _doing_it_wrong(
  1184. __FUNCTION__,
  1185. sprintf(
  1186. /* translators: %s: $network_id */
  1187. __( 'Unable to pass %s if not using multisite.' ),
  1188. '<code>$network_id</code>'
  1189. ),
  1190. '6.0.0'
  1191. );
  1192. }
  1193. $is_small_network = ! wp_is_large_user_count( $network_id );
  1194. /** This filter is documented in wp-includes/ms-functions.php */
  1195. if ( ! apply_filters( 'enable_live_network_counts', $is_small_network, 'users' ) ) {
  1196. return false;
  1197. }
  1198. return wp_update_user_counts( $network_id );
  1199. }
  1200. /**
  1201. * Updates the total count of users on the site.
  1202. *
  1203. * @global wpdb $wpdb WordPress database abstraction object.
  1204. * @since 6.0.0
  1205. *
  1206. * @param int|null $network_id ID of the network. Defaults to the current network.
  1207. * @return bool Whether the update was successful.
  1208. */
  1209. function wp_update_user_counts( $network_id = null ) {
  1210. global $wpdb;
  1211. if ( ! is_multisite() && null !== $network_id ) {
  1212. _doing_it_wrong(
  1213. __FUNCTION__,
  1214. sprintf(
  1215. /* translators: %s: $network_id */
  1216. __( 'Unable to pass %s if not using multisite.' ),
  1217. '<code>$network_id</code>'
  1218. ),
  1219. '6.0.0'
  1220. );
  1221. }
  1222. $query = "SELECT COUNT(ID) as c FROM $wpdb->users";
  1223. if ( is_multisite() ) {
  1224. $query .= " WHERE spam = '0' AND deleted = '0'";
  1225. }
  1226. $count = $wpdb->get_var( $query );
  1227. return update_network_option( $network_id, 'user_count', $count );
  1228. }
  1229. /**
  1230. * Schedules a recurring recalculation of the total count of users.
  1231. *
  1232. * @since 6.0.0
  1233. */
  1234. function wp_schedule_update_user_counts() {
  1235. if ( ! is_main_site() ) {
  1236. return;
  1237. }
  1238. if ( ! wp_next_scheduled( 'wp_update_user_counts' ) && ! wp_installing() ) {
  1239. wp_schedule_event( time(), 'twicedaily', 'wp_update_user_counts' );
  1240. }
  1241. }
  1242. /**
  1243. * Determines whether the site has a large number of users.
  1244. *
  1245. * The default criteria for a large site is more than 10,000 users.
  1246. *
  1247. * @since 6.0.0
  1248. *
  1249. * @param int|null $network_id ID of the network. Defaults to the current network.
  1250. * @return bool Whether the site has a large number of users.
  1251. */
  1252. function wp_is_large_user_count( $network_id = null ) {
  1253. if ( ! is_multisite() && null !== $network_id ) {
  1254. _doing_it_wrong(
  1255. __FUNCTION__,
  1256. sprintf(
  1257. /* translators: %s: $network_id */
  1258. __( 'Unable to pass %s if not using multisite.' ),
  1259. '<code>$network_id</code>'
  1260. ),
  1261. '6.0.0'
  1262. );
  1263. }
  1264. $count = get_user_count( $network_id );
  1265. /**
  1266. * Filters whether the site is considered large, based on its number of users.
  1267. *
  1268. * @since 6.0.0
  1269. *
  1270. * @param bool $is_large_user_count Whether the site has a large number of users.
  1271. * @param int $count The total number of users.
  1272. * @param int|null $network_id ID of the network. `null` represents the current network.
  1273. */
  1274. return apply_filters( 'wp_is_large_user_count', $count > 10000, $count, $network_id );
  1275. }
  1276. //
  1277. // Private helper functions.
  1278. //
  1279. /**
  1280. * Sets up global user vars.
  1281. *
  1282. * Used by wp_set_current_user() for back compat. Might be deprecated in the future.
  1283. *
  1284. * @since 2.0.4
  1285. *
  1286. * @global string $user_login The user username for logging in
  1287. * @global WP_User $userdata User data.
  1288. * @global int $user_level The level of the user
  1289. * @global int $user_ID The ID of the user
  1290. * @global string $user_email The email address of the user
  1291. * @global string $user_url The url in the user's profile
  1292. * @global string $user_identity The display name of the user
  1293. *
  1294. * @param int $for_user_id Optional. User ID to set up global data. Default 0.
  1295. */
  1296. function setup_userdata( $for_user_id = 0 ) {
  1297. global $user_login, $userdata, $user_level, $user_ID, $user_email, $user_url, $user_identity;
  1298. if ( ! $for_user_id ) {
  1299. $for_user_id = get_current_user_id();
  1300. }
  1301. $user = get_userdata( $for_user_id );
  1302. if ( ! $user ) {
  1303. $user_ID = 0;
  1304. $user_level = 0;
  1305. $userdata = null;
  1306. $user_login = '';
  1307. $user_email = '';
  1308. $user_url = '';
  1309. $user_identity = '';
  1310. return;
  1311. }
  1312. $user_ID = (int) $user->ID;
  1313. $user_level = (int) $user->user_level;
  1314. $userdata = $user;
  1315. $user_login = $user->user_login;
  1316. $user_email = $user->user_email;
  1317. $user_url = $user->user_url;
  1318. $user_identity = $user->display_name;
  1319. }
  1320. /**
  1321. * Creates dropdown HTML content of users.
  1322. *
  1323. * The content can either be displayed, which it is by default or retrieved by
  1324. * setting the 'echo' argument. The 'include' and 'exclude' arguments do not
  1325. * need to be used; all users will be displayed in that case. Only one can be
  1326. * used, either 'include' or 'exclude', but not both.
  1327. *
  1328. * The available arguments are as follows:
  1329. *
  1330. * @since 2.3.0
  1331. * @since 4.5.0 Added the 'display_name_with_login' value for 'show'.
  1332. * @since 4.7.0 Added the `$role`, `$role__in`, and `$role__not_in` parameters.
  1333. *
  1334. * @param array|string $args {
  1335. * Optional. Array or string of arguments to generate a drop-down of users.
  1336. * See WP_User_Query::prepare_query() for additional available arguments.
  1337. *
  1338. * @type string $show_option_all Text to show as the drop-down default (all).
  1339. * Default empty.
  1340. * @type string $show_option_none Text to show as the drop-down default when no
  1341. * users were found. Default empty.
  1342. * @type int|string $option_none_value Value to use for $show_option_non when no users
  1343. * were found. Default -1.
  1344. * @type string $hide_if_only_one_author Whether to skip generating the drop-down
  1345. * if only one user was found. Default empty.
  1346. * @type string $orderby Field to order found users by. Accepts user fields.
  1347. * Default 'display_name'.
  1348. * @type string $order Whether to order users in ascending or descending
  1349. * order. Accepts 'ASC' (ascending) or 'DESC' (descending).
  1350. * Default 'ASC'.
  1351. * @type int[]|string $include Array or comma-separated list of user IDs to include.
  1352. * Default empty.
  1353. * @type int[]|string $exclude Array or comma-separated list of user IDs to exclude.
  1354. * Default empty.
  1355. * @type bool|int $multi Whether to skip the ID attribute on the 'select' element.
  1356. * Accepts 1|true or 0|false. Default 0|false.
  1357. * @type string $show User data to display. If the selected item is empty
  1358. * then the 'user_login' will be displayed in parentheses.
  1359. * Accepts any user field, or 'display_name_with_login' to show
  1360. * the display name with user_login in parentheses.
  1361. * Default 'display_name'.
  1362. * @type int|bool $echo Whether to echo or return the drop-down. Accepts 1|true (echo)
  1363. * or 0|false (return). Default 1|true.
  1364. * @type int $selected Which user ID should be selected. Default 0.
  1365. * @type bool $include_selected Whether to always include the selected user ID in the drop-
  1366. * down. Default false.
  1367. * @type string $name Name attribute of select element. Default 'user'.
  1368. * @type string $id ID attribute of the select element. Default is the value of $name.
  1369. * @type string $class Class attribute of the select element. Default empty.
  1370. * @type int $blog_id ID of blog (Multisite only). Default is ID of the current blog.
  1371. * @type string $who Which type of users to query. Accepts only an empty string or
  1372. * 'authors'. Default empty.
  1373. * @type string|array $role An array or a comma-separated list of role names that users must
  1374. * match to be included in results. Note that this is an inclusive
  1375. * list: users must match *each* role. Default empty.
  1376. * @type string[] $role__in An array of role names. Matched users must have at least one of
  1377. * these roles. Default empty array.
  1378. * @type string[] $role__not_in An array of role names to exclude. Users matching one or more of
  1379. * these roles will not be included in results. Default empty array.
  1380. * }
  1381. * @return string HTML dropdown list of users.
  1382. */
  1383. function wp_dropdown_users( $args = '' ) {
  1384. $defaults = array(
  1385. 'show_option_all' => '',
  1386. 'show_option_none' => '',
  1387. 'hide_if_only_one_author' => '',
  1388. 'orderby' => 'display_name',
  1389. 'order' => 'ASC',
  1390. 'include' => '',
  1391. 'exclude' => '',
  1392. 'multi' => 0,
  1393. 'show' => 'display_name',
  1394. 'echo' => 1,
  1395. 'selected' => 0,
  1396. 'name' => 'user',
  1397. 'class' => '',
  1398. 'id' => '',
  1399. 'blog_id' => get_current_blog_id(),
  1400. 'who' => '',
  1401. 'include_selected' => false,
  1402. 'option_none_value' => -1,
  1403. 'role' => '',
  1404. 'role__in' => array(),
  1405. 'role__not_in' => array(),
  1406. 'capability' => '',
  1407. 'capability__in' => array(),
  1408. 'capability__not_in' => array(),
  1409. );
  1410. $defaults['selected'] = is_author() ? get_query_var( 'author' ) : 0;
  1411. $parsed_args = wp_parse_args( $args, $defaults );
  1412. $query_args = wp_array_slice_assoc(
  1413. $parsed_args,
  1414. array(
  1415. 'blog_id',
  1416. 'include',
  1417. 'exclude',
  1418. 'orderby',
  1419. 'order',
  1420. 'who',
  1421. 'role',
  1422. 'role__in',
  1423. 'role__not_in',
  1424. 'capability',
  1425. 'capability__in',
  1426. 'capability__not_in',
  1427. )
  1428. );
  1429. $fields = array( 'ID', 'user_login' );
  1430. $show = ! empty( $parsed_args['show'] ) ? $parsed_args['show'] : 'display_name';
  1431. if ( 'display_name_with_login' === $show ) {
  1432. $fields[] = 'display_name';
  1433. } else {
  1434. $fields[] = $show;
  1435. }
  1436. $query_args['fields'] = $fields;
  1437. $show_option_all = $parsed_args['show_option_all'];
  1438. $show_option_none = $parsed_args['show_option_none'];
  1439. $option_none_value = $parsed_args['option_none_value'];
  1440. /**
  1441. * Filters the query arguments for the list of users in the dropdown.
  1442. *
  1443. * @since 4.4.0
  1444. *
  1445. * @param array $query_args The query arguments for get_users().
  1446. * @param array $parsed_args The arguments passed to wp_dropdown_users() combined with the defaults.
  1447. */
  1448. $query_args = apply_filters( 'wp_dropdown_users_args', $query_args, $parsed_args );
  1449. $users = get_users( $query_args );
  1450. $output = '';
  1451. if ( ! empty( $users ) && ( empty( $parsed_args['hide_if_only_one_author'] ) || count( $users ) > 1 ) ) {
  1452. $name = esc_attr( $parsed_args['name'] );
  1453. if ( $parsed_args['multi'] && ! $parsed_args['id'] ) {
  1454. $id = '';
  1455. } else {
  1456. $id = $parsed_args['id'] ? " id='" . esc_attr( $parsed_args['id'] ) . "'" : " id='$name'";
  1457. }
  1458. $output = "<select name='{$name}'{$id} class='" . $parsed_args['class'] . "'>\n";
  1459. if ( $show_option_all ) {
  1460. $output .= "\t<option value='0'>$show_option_all</option>\n";
  1461. }
  1462. if ( $show_option_none ) {
  1463. $_selected = selected( $option_none_value, $parsed_args['selected'], false );
  1464. $output .= "\t<option value='" . esc_attr( $option_none_value ) . "'$_selected>$show_option_none</option>\n";
  1465. }
  1466. if ( $parsed_args['include_selected'] && ( $parsed_args['selected'] > 0 ) ) {
  1467. $found_selected = false;
  1468. $parsed_args['selected'] = (int) $parsed_args['selected'];
  1469. foreach ( (array) $users as $user ) {
  1470. $user->ID = (int) $user->ID;
  1471. if ( $user->ID === $parsed_args['selected'] ) {
  1472. $found_selected = true;
  1473. }
  1474. }
  1475. if ( ! $found_selected ) {
  1476. $selected_user = get_userdata( $parsed_args['selected'] );
  1477. if ( $selected_user ) {
  1478. $users[] = $selected_user;
  1479. }
  1480. }
  1481. }
  1482. foreach ( (array) $users as $user ) {
  1483. if ( 'display_name_with_login' === $show ) {
  1484. /* translators: 1: User's display name, 2: User login. */
  1485. $display = sprintf( _x( '%1$s (%2$s)', 'user dropdown' ), $user->display_name, $user->user_login );
  1486. } elseif ( ! empty( $user->$show ) ) {
  1487. $display = $user->$show;
  1488. } else {
  1489. $display = '(' . $user->user_login . ')';
  1490. }
  1491. $_selected = selected( $user->ID, $parsed_args['selected'], false );
  1492. $output .= "\t<option value='$user->ID'$_selected>" . esc_html( $display ) . "</option>\n";
  1493. }
  1494. $output .= '</select>';
  1495. }
  1496. /**
  1497. * Filters the wp_dropdown_users() HTML output.
  1498. *
  1499. * @since 2.3.0
  1500. *
  1501. * @param string $output HTML output generated by wp_dropdown_users().
  1502. */
  1503. $html = apply_filters( 'wp_dropdown_users', $output );
  1504. if ( $parsed_args['echo'] ) {
  1505. echo $html;
  1506. }
  1507. return $html;
  1508. }
  1509. /**
  1510. * Sanitizes user field based on context.
  1511. *
  1512. * Possible context values are: 'raw', 'edit', 'db', 'display', 'attribute' and 'js'. The
  1513. * 'display' context is used by default. 'attribute' and 'js' contexts are treated like 'display'
  1514. * when calling filters.
  1515. *
  1516. * @since 2.3.0
  1517. *
  1518. * @param string $field The user Object field name.
  1519. * @param mixed $value The user Object value.
  1520. * @param int $user_id User ID.
  1521. * @param string $context How to sanitize user fields. Looks for 'raw', 'edit', 'db', 'display',
  1522. * 'attribute' and 'js'.
  1523. * @return mixed Sanitized value.
  1524. */
  1525. function sanitize_user_field( $field, $value, $user_id, $context ) {
  1526. $int_fields = array( 'ID' );
  1527. if ( in_array( $field, $int_fields, true ) ) {
  1528. $value = (int) $value;
  1529. }
  1530. if ( 'raw' === $context ) {
  1531. return $value;
  1532. }
  1533. if ( ! is_string( $value ) && ! is_numeric( $value ) ) {
  1534. return $value;
  1535. }
  1536. $prefixed = false !== strpos( $field, 'user_' );
  1537. if ( 'edit' === $context ) {
  1538. if ( $prefixed ) {
  1539. /** This filter is documented in wp-includes/post.php */
  1540. $value = apply_filters( "edit_{$field}", $value, $user_id );
  1541. } else {
  1542. /**
  1543. * Filters a user field value in the 'edit' context.
  1544. *
  1545. * The dynamic portion of the hook name, `$field`, refers to the prefixed user
  1546. * field being filtered, such as 'user_login', 'user_email', 'first_name', etc.
  1547. *
  1548. * @since 2.9.0
  1549. *
  1550. * @param mixed $value Value of the prefixed user field.
  1551. * @param int $user_id User ID.
  1552. */
  1553. $value = apply_filters( "edit_user_{$field}", $value, $user_id );
  1554. }
  1555. if ( 'description' === $field ) {
  1556. $value = esc_html( $value ); // textarea_escaped?
  1557. } else {
  1558. $value = esc_attr( $value );
  1559. }
  1560. } elseif ( 'db' === $context ) {
  1561. if ( $prefixed ) {
  1562. /** This filter is documented in wp-includes/post.php */
  1563. $value = apply_filters( "pre_{$field}", $value );
  1564. } else {
  1565. /**
  1566. * Filters the value of a user field in the 'db' context.
  1567. *
  1568. * The dynamic portion of the hook name, `$field`, refers to the prefixed user
  1569. * field being filtered, such as 'user_login', 'user_email', 'first_name', etc.
  1570. *
  1571. * @since 2.9.0
  1572. *
  1573. * @param mixed $value Value of the prefixed user field.
  1574. */
  1575. $value = apply_filters( "pre_user_{$field}", $value );
  1576. }
  1577. } else {
  1578. // Use display filters by default.
  1579. if ( $prefixed ) {
  1580. /** This filter is documented in wp-includes/post.php */
  1581. $value = apply_filters( "{$field}", $value, $user_id, $context );
  1582. } else {
  1583. /**
  1584. * Filters the value of a user field in a standard context.
  1585. *
  1586. * The dynamic portion of the hook name, `$field`, refers to the prefixed user
  1587. * field being filtered, such as 'user_login', 'user_email', 'first_name', etc.
  1588. *
  1589. * @since 2.9.0
  1590. *
  1591. * @param mixed $value The user object value to sanitize.
  1592. * @param int $user_id User ID.
  1593. * @param string $context The context to filter within.
  1594. */
  1595. $value = apply_filters( "user_{$field}", $value, $user_id, $context );
  1596. }
  1597. }
  1598. if ( 'user_url' === $field ) {
  1599. $value = esc_url( $value );
  1600. }
  1601. if ( 'attribute' === $context ) {
  1602. $value = esc_attr( $value );
  1603. } elseif ( 'js' === $context ) {
  1604. $value = esc_js( $value );
  1605. }
  1606. // Restore the type for integer fields after esc_attr().
  1607. if ( in_array( $field, $int_fields, true ) ) {
  1608. $value = (int) $value;
  1609. }
  1610. return $value;
  1611. }
  1612. /**
  1613. * Updates all user caches.
  1614. *
  1615. * @since 3.0.0
  1616. *
  1617. * @param object|WP_User $user User object or database row to be cached
  1618. * @return void|false Void on success, false on failure.
  1619. */
  1620. function update_user_caches( $user ) {
  1621. if ( $user instanceof WP_User ) {
  1622. if ( ! $user->exists() ) {
  1623. return false;
  1624. }
  1625. $user = $user->data;
  1626. }
  1627. wp_cache_add( $user->ID, $user, 'users' );
  1628. wp_cache_add( $user->user_login, $user->ID, 'userlogins' );
  1629. wp_cache_add( $user->user_nicename, $user->ID, 'userslugs' );
  1630. if ( ! empty( $user->user_email ) ) {
  1631. wp_cache_add( $user->user_email, $user->ID, 'useremail' );
  1632. }
  1633. }
  1634. /**
  1635. * Cleans all user caches.
  1636. *
  1637. * @since 3.0.0
  1638. * @since 4.4.0 'clean_user_cache' action was added.
  1639. *
  1640. * @param WP_User|int $user User object or ID to be cleaned from the cache
  1641. */
  1642. function clean_user_cache( $user ) {
  1643. if ( is_numeric( $user ) ) {
  1644. $user = new WP_User( $user );
  1645. }
  1646. if ( ! $user->exists() ) {
  1647. return;
  1648. }
  1649. wp_cache_delete( $user->ID, 'users' );
  1650. wp_cache_delete( $user->user_login, 'userlogins' );
  1651. wp_cache_delete( $user->user_nicename, 'userslugs' );
  1652. if ( ! empty( $user->user_email ) ) {
  1653. wp_cache_delete( $user->user_email, 'useremail' );
  1654. }
  1655. /**
  1656. * Fires immediately after the given user's cache is cleaned.
  1657. *
  1658. * @since 4.4.0
  1659. *
  1660. * @param int $user_id User ID.
  1661. * @param WP_User $user User object.
  1662. */
  1663. do_action( 'clean_user_cache', $user->ID, $user );
  1664. }
  1665. /**
  1666. * Determines whether the given username exists.
  1667. *
  1668. * For more information on this and similar theme functions, check out
  1669. * the {@link https://developer.wordpress.org/themes/basics/conditional-tags/
  1670. * Conditional Tags} article in the Theme Developer Handbook.
  1671. *
  1672. * @since 2.0.0
  1673. *
  1674. * @param string $username The username to check for existence.
  1675. * @return int|false The user ID on success, false on failure.
  1676. */
  1677. function username_exists( $username ) {
  1678. $user = get_user_by( 'login', $username );
  1679. if ( $user ) {
  1680. $user_id = $user->ID;
  1681. } else {
  1682. $user_id = false;
  1683. }
  1684. /**
  1685. * Filters whether the given username exists.
  1686. *
  1687. * @since 4.9.0
  1688. *
  1689. * @param int|false $user_id The user ID associated with the username,
  1690. * or false if the username does not exist.
  1691. * @param string $username The username to check for existence.
  1692. */
  1693. return apply_filters( 'username_exists', $user_id, $username );
  1694. }
  1695. /**
  1696. * Determines whether the given email exists.
  1697. *
  1698. * For more information on this and similar theme functions, check out
  1699. * the {@link https://developer.wordpress.org/themes/basics/conditional-tags/
  1700. * Conditional Tags} article in the Theme Developer Handbook.
  1701. *
  1702. * @since 2.1.0
  1703. *
  1704. * @param string $email The email to check for existence.
  1705. * @return int|false The user ID on success, false on failure.
  1706. */
  1707. function email_exists( $email ) {
  1708. $user = get_user_by( 'email', $email );
  1709. if ( $user ) {
  1710. $user_id = $user->ID;
  1711. } else {
  1712. $user_id = false;
  1713. }
  1714. /**
  1715. * Filters whether the given email exists.
  1716. *
  1717. * @since 5.6.0
  1718. *
  1719. * @param int|false $user_id The user ID associated with the email,
  1720. * or false if the email does not exist.
  1721. * @param string $email The email to check for existence.
  1722. */
  1723. return apply_filters( 'email_exists', $user_id, $email );
  1724. }
  1725. /**
  1726. * Checks whether a username is valid.
  1727. *
  1728. * @since 2.0.1
  1729. * @since 4.4.0 Empty sanitized usernames are now considered invalid.
  1730. *
  1731. * @param string $username Username.
  1732. * @return bool Whether username given is valid.
  1733. */
  1734. function validate_username( $username ) {
  1735. $sanitized = sanitize_user( $username, true );
  1736. $valid = ( $sanitized == $username && ! empty( $sanitized ) );
  1737. /**
  1738. * Filters whether the provided username is valid.
  1739. *
  1740. * @since 2.0.1
  1741. *
  1742. * @param bool $valid Whether given username is valid.
  1743. * @param string $username Username to check.
  1744. */
  1745. return apply_filters( 'validate_username', $valid, $username );
  1746. }
  1747. /**
  1748. * Inserts a user into the database.
  1749. *
  1750. * Most of the `$userdata` array fields have filters associated with the values. Exceptions are
  1751. * 'ID', 'rich_editing', 'syntax_highlighting', 'comment_shortcuts', 'admin_color', 'use_ssl',
  1752. * 'user_registered', 'user_activation_key', 'spam', and 'role'. The filters have the prefix
  1753. * 'pre_user_' followed by the field name. An example using 'description' would have the filter
  1754. * called 'pre_user_description' that can be hooked into.
  1755. *
  1756. * @since 2.0.0
  1757. * @since 3.6.0 The `aim`, `jabber`, and `yim` fields were removed as default user contact
  1758. * methods for new installations. See wp_get_user_contact_methods().
  1759. * @since 4.7.0 The `locale` field can be passed to `$userdata`.
  1760. * @since 5.3.0 The `user_activation_key` field can be passed to `$userdata`.
  1761. * @since 5.3.0 The `spam` field can be passed to `$userdata` (Multisite only).
  1762. * @since 5.9.0 The `meta_input` field can be passed to `$userdata` to allow addition of user meta data.
  1763. *
  1764. * @global wpdb $wpdb WordPress database abstraction object.
  1765. *
  1766. * @param array|object|WP_User $userdata {
  1767. * An array, object, or WP_User object of user data arguments.
  1768. *
  1769. * @type int $ID User ID. If supplied, the user will be updated.
  1770. * @type string $user_pass The plain-text user password.
  1771. * @type string $user_login The user's login username.
  1772. * @type string $user_nicename The URL-friendly user name.
  1773. * @type string $user_url The user URL.
  1774. * @type string $user_email The user email address.
  1775. * @type string $display_name The user's display name.
  1776. * Default is the user's username.
  1777. * @type string $nickname The user's nickname.
  1778. * Default is the user's username.
  1779. * @type string $first_name The user's first name. For new users, will be used
  1780. * to build the first part of the user's display name
  1781. * if `$display_name` is not specified.
  1782. * @type string $last_name The user's last name. For new users, will be used
  1783. * to build the second part of the user's display name
  1784. * if `$display_name` is not specified.
  1785. * @type string $description The user's biographical description.
  1786. * @type string $rich_editing Whether to enable the rich-editor for the user.
  1787. * Accepts 'true' or 'false' as a string literal,
  1788. * not boolean. Default 'true'.
  1789. * @type string $syntax_highlighting Whether to enable the rich code editor for the user.
  1790. * Accepts 'true' or 'false' as a string literal,
  1791. * not boolean. Default 'true'.
  1792. * @type string $comment_shortcuts Whether to enable comment moderation keyboard
  1793. * shortcuts for the user. Accepts 'true' or 'false'
  1794. * as a string literal, not boolean. Default 'false'.
  1795. * @type string $admin_color Admin color scheme for the user. Default 'fresh'.
  1796. * @type bool $use_ssl Whether the user should always access the admin over
  1797. * https. Default false.
  1798. * @type string $user_registered Date the user registered in UTC. Format is 'Y-m-d H:i:s'.
  1799. * @type string $user_activation_key Password reset key. Default empty.
  1800. * @type bool $spam Multisite only. Whether the user is marked as spam.
  1801. * Default false.
  1802. * @type string $show_admin_bar_front Whether to display the Admin Bar for the user
  1803. * on the site's front end. Accepts 'true' or 'false'
  1804. * as a string literal, not boolean. Default 'true'.
  1805. * @type string $role User's role.
  1806. * @type string $locale User's locale. Default empty.
  1807. * @type array $meta_input Array of custom user meta values keyed by meta key.
  1808. * Default empty.
  1809. * }
  1810. * @return int|WP_Error The newly created user's ID or a WP_Error object if the user could not
  1811. * be created.
  1812. */
  1813. function wp_insert_user( $userdata ) {
  1814. global $wpdb;
  1815. if ( $userdata instanceof stdClass ) {
  1816. $userdata = get_object_vars( $userdata );
  1817. } elseif ( $userdata instanceof WP_User ) {
  1818. $userdata = $userdata->to_array();
  1819. }
  1820. // Are we updating or creating?
  1821. if ( ! empty( $userdata['ID'] ) ) {
  1822. $user_id = (int) $userdata['ID'];
  1823. $update = true;
  1824. $old_user_data = get_userdata( $user_id );
  1825. if ( ! $old_user_data ) {
  1826. return new WP_Error( 'invalid_user_id', __( 'Invalid user ID.' ) );
  1827. }
  1828. // Hashed in wp_update_user(), plaintext if called directly.
  1829. $user_pass = ! empty( $userdata['user_pass'] ) ? $userdata['user_pass'] : $old_user_data->user_pass;
  1830. } else {
  1831. $update = false;
  1832. // Hash the password.
  1833. $user_pass = wp_hash_password( $userdata['user_pass'] );
  1834. }
  1835. $sanitized_user_login = sanitize_user( $userdata['user_login'], true );
  1836. /**
  1837. * Filters a username after it has been sanitized.
  1838. *
  1839. * This filter is called before the user is created or updated.
  1840. *
  1841. * @since 2.0.3
  1842. *
  1843. * @param string $sanitized_user_login Username after it has been sanitized.
  1844. */
  1845. $pre_user_login = apply_filters( 'pre_user_login', $sanitized_user_login );
  1846. // Remove any non-printable chars from the login string to see if we have ended up with an empty username.
  1847. $user_login = trim( $pre_user_login );
  1848. // user_login must be between 0 and 60 characters.
  1849. if ( empty( $user_login ) ) {
  1850. return new WP_Error( 'empty_user_login', __( 'Cannot create a user with an empty login name.' ) );
  1851. } elseif ( mb_strlen( $user_login ) > 60 ) {
  1852. return new WP_Error( 'user_login_too_long', __( 'Username may not be longer than 60 characters.' ) );
  1853. }
  1854. if ( ! $update && username_exists( $user_login ) ) {
  1855. return new WP_Error( 'existing_user_login', __( 'Sorry, that username already exists!' ) );
  1856. }
  1857. /**
  1858. * Filters the list of disallowed usernames.
  1859. *
  1860. * @since 4.4.0
  1861. *
  1862. * @param array $usernames Array of disallowed usernames.
  1863. */
  1864. $illegal_logins = (array) apply_filters( 'illegal_user_logins', array() );
  1865. if ( in_array( strtolower( $user_login ), array_map( 'strtolower', $illegal_logins ), true ) ) {
  1866. return new WP_Error( 'invalid_username', __( 'Sorry, that username is not allowed.' ) );
  1867. }
  1868. /*
  1869. * If a nicename is provided, remove unsafe user characters before using it.
  1870. * Otherwise build a nicename from the user_login.
  1871. */
  1872. if ( ! empty( $userdata['user_nicename'] ) ) {
  1873. $user_nicename = sanitize_user( $userdata['user_nicename'], true );
  1874. } else {
  1875. $user_nicename = mb_substr( $user_login, 0, 50 );
  1876. }
  1877. $user_nicename = sanitize_title( $user_nicename );
  1878. /**
  1879. * Filters a user's nicename before the user is created or updated.
  1880. *
  1881. * @since 2.0.3
  1882. *
  1883. * @param string $user_nicename The user's nicename.
  1884. */
  1885. $user_nicename = apply_filters( 'pre_user_nicename', $user_nicename );
  1886. if ( mb_strlen( $user_nicename ) > 50 ) {
  1887. return new WP_Error( 'user_nicename_too_long', __( 'Nicename may not be longer than 50 characters.' ) );
  1888. }
  1889. $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 ) );
  1890. if ( $user_nicename_check ) {
  1891. $suffix = 2;
  1892. while ( $user_nicename_check ) {
  1893. // user_nicename allows 50 chars. Subtract one for a hyphen, plus the length of the suffix.
  1894. $base_length = 49 - mb_strlen( $suffix );
  1895. $alt_user_nicename = mb_substr( $user_nicename, 0, $base_length ) . "-$suffix";
  1896. $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 ) );
  1897. $suffix++;
  1898. }
  1899. $user_nicename = $alt_user_nicename;
  1900. }
  1901. $raw_user_email = empty( $userdata['user_email'] ) ? '' : $userdata['user_email'];
  1902. /**
  1903. * Filters a user's email before the user is created or updated.
  1904. *
  1905. * @since 2.0.3
  1906. *
  1907. * @param string $raw_user_email The user's email.
  1908. */
  1909. $user_email = apply_filters( 'pre_user_email', $raw_user_email );
  1910. /*
  1911. * If there is no update, just check for `email_exists`. If there is an update,
  1912. * check if current email and new email are the same, and check `email_exists`
  1913. * accordingly.
  1914. */
  1915. if ( ( ! $update || ( ! empty( $old_user_data ) && 0 !== strcasecmp( $user_email, $old_user_data->user_email ) ) )
  1916. && ! defined( 'WP_IMPORTING' )
  1917. && email_exists( $user_email )
  1918. ) {
  1919. return new WP_Error( 'existing_user_email', __( 'Sorry, that email address is already used!' ) );
  1920. }
  1921. $raw_user_url = empty( $userdata['user_url'] ) ? '' : $userdata['user_url'];
  1922. /**
  1923. * Filters a user's URL before the user is created or updated.
  1924. *
  1925. * @since 2.0.3
  1926. *
  1927. * @param string $raw_user_url The user's URL.
  1928. */
  1929. $user_url = apply_filters( 'pre_user_url', $raw_user_url );
  1930. if ( mb_strlen( $user_url ) > 100 ) {
  1931. return new WP_Error( 'user_url_too_long', __( 'User URL may not be longer than 100 characters.' ) );
  1932. }
  1933. $user_registered = empty( $userdata['user_registered'] ) ? gmdate( 'Y-m-d H:i:s' ) : $userdata['user_registered'];
  1934. $user_activation_key = empty( $userdata['user_activation_key'] ) ? '' : $userdata['user_activation_key'];
  1935. if ( ! empty( $userdata['spam'] ) && ! is_multisite() ) {
  1936. return new WP_Error( 'no_spam', __( 'Sorry, marking a user as spam is only supported on Multisite.' ) );
  1937. }
  1938. $spam = empty( $userdata['spam'] ) ? 0 : (bool) $userdata['spam'];
  1939. // Store values to save in user meta.
  1940. $meta = array();
  1941. $nickname = empty( $userdata['nickname'] ) ? $user_login : $userdata['nickname'];
  1942. /**
  1943. * Filters a user's nickname before the user is created or updated.
  1944. *
  1945. * @since 2.0.3
  1946. *
  1947. * @param string $nickname The user's nickname.
  1948. */
  1949. $meta['nickname'] = apply_filters( 'pre_user_nickname', $nickname );
  1950. $first_name = empty( $userdata['first_name'] ) ? '' : $userdata['first_name'];
  1951. /**
  1952. * Filters a user's first name before the user is created or updated.
  1953. *
  1954. * @since 2.0.3
  1955. *
  1956. * @param string $first_name The user's first name.
  1957. */
  1958. $meta['first_name'] = apply_filters( 'pre_user_first_name', $first_name );
  1959. $last_name = empty( $userdata['last_name'] ) ? '' : $userdata['last_name'];
  1960. /**
  1961. * Filters a user's last name before the user is created or updated.
  1962. *
  1963. * @since 2.0.3
  1964. *
  1965. * @param string $last_name The user's last name.
  1966. */
  1967. $meta['last_name'] = apply_filters( 'pre_user_last_name', $last_name );
  1968. if ( empty( $userdata['display_name'] ) ) {
  1969. if ( $update ) {
  1970. $display_name = $user_login;
  1971. } elseif ( $meta['first_name'] && $meta['last_name'] ) {
  1972. $display_name = sprintf(
  1973. /* translators: 1: User's first name, 2: Last name. */
  1974. _x( '%1$s %2$s', 'Display name based on first name and last name' ),
  1975. $meta['first_name'],
  1976. $meta['last_name']
  1977. );
  1978. } elseif ( $meta['first_name'] ) {
  1979. $display_name = $meta['first_name'];
  1980. } elseif ( $meta['last_name'] ) {
  1981. $display_name = $meta['last_name'];
  1982. } else {
  1983. $display_name = $user_login;
  1984. }
  1985. } else {
  1986. $display_name = $userdata['display_name'];
  1987. }
  1988. /**
  1989. * Filters a user's display name before the user is created or updated.
  1990. *
  1991. * @since 2.0.3
  1992. *
  1993. * @param string $display_name The user's display name.
  1994. */
  1995. $display_name = apply_filters( 'pre_user_display_name', $display_name );
  1996. $description = empty( $userdata['description'] ) ? '' : $userdata['description'];
  1997. /**
  1998. * Filters a user's description before the user is created or updated.
  1999. *
  2000. * @since 2.0.3
  2001. *
  2002. * @param string $description The user's description.
  2003. */
  2004. $meta['description'] = apply_filters( 'pre_user_description', $description );
  2005. $meta['rich_editing'] = empty( $userdata['rich_editing'] ) ? 'true' : $userdata['rich_editing'];
  2006. $meta['syntax_highlighting'] = empty( $userdata['syntax_highlighting'] ) ? 'true' : $userdata['syntax_highlighting'];
  2007. $meta['comment_shortcuts'] = empty( $userdata['comment_shortcuts'] ) || 'false' === $userdata['comment_shortcuts'] ? 'false' : 'true';
  2008. $admin_color = empty( $userdata['admin_color'] ) ? 'fresh' : $userdata['admin_color'];
  2009. $meta['admin_color'] = preg_replace( '|[^a-z0-9 _.\-@]|i', '', $admin_color );
  2010. $meta['use_ssl'] = empty( $userdata['use_ssl'] ) ? 0 : (bool) $userdata['use_ssl'];
  2011. $meta['show_admin_bar_front'] = empty( $userdata['show_admin_bar_front'] ) ? 'true' : $userdata['show_admin_bar_front'];
  2012. $meta['locale'] = isset( $userdata['locale'] ) ? $userdata['locale'] : '';
  2013. $compacted = compact( 'user_pass', 'user_nicename', 'user_email', 'user_url', 'user_registered', 'user_activation_key', 'display_name' );
  2014. $data = wp_unslash( $compacted );
  2015. if ( ! $update ) {
  2016. $data = $data + compact( 'user_login' );
  2017. }
  2018. if ( is_multisite() ) {
  2019. $data = $data + compact( 'spam' );
  2020. }
  2021. /**
  2022. * Filters user data before the record is created or updated.
  2023. *
  2024. * It only includes data in the users table, not any user metadata.
  2025. *
  2026. * @since 4.9.0
  2027. * @since 5.8.0 The `$userdata` parameter was added.
  2028. *
  2029. * @param array $data {
  2030. * Values and keys for the user.
  2031. *
  2032. * @type string $user_login The user's login. Only included if $update == false
  2033. * @type string $user_pass The user's password.
  2034. * @type string $user_email The user's email.
  2035. * @type string $user_url The user's url.
  2036. * @type string $user_nicename The user's nice name. Defaults to a URL-safe version of user's login
  2037. * @type string $display_name The user's display name.
  2038. * @type string $user_registered MySQL timestamp describing the moment when the user registered. Defaults to
  2039. * the current UTC timestamp.
  2040. * }
  2041. * @param bool $update Whether the user is being updated rather than created.
  2042. * @param int|null $user_id ID of the user to be updated, or NULL if the user is being created.
  2043. * @param array $userdata The raw array of data passed to wp_insert_user().
  2044. */
  2045. $data = apply_filters( 'wp_pre_insert_user_data', $data, $update, ( $update ? $user_id : null ), $userdata );
  2046. if ( empty( $data ) || ! is_array( $data ) ) {
  2047. return new WP_Error( 'empty_data', __( 'Not enough data to create this user.' ) );
  2048. }
  2049. if ( $update ) {
  2050. if ( $user_email !== $old_user_data->user_email || $user_pass !== $old_user_data->user_pass ) {
  2051. $data['user_activation_key'] = '';
  2052. }
  2053. $wpdb->update( $wpdb->users, $data, array( 'ID' => $user_id ) );
  2054. } else {
  2055. $wpdb->insert( $wpdb->users, $data );
  2056. $user_id = (int) $wpdb->insert_id;
  2057. }
  2058. $user = new WP_User( $user_id );
  2059. /**
  2060. * Filters a user's meta values and keys immediately after the user is created or updated
  2061. * and before any user meta is inserted or updated.
  2062. *
  2063. * Does not include contact methods. These are added using `wp_get_user_contact_methods( $user )`.
  2064. *
  2065. * For custom meta fields, see the {@see 'insert_custom_user_meta'} filter.
  2066. *
  2067. * @since 4.4.0
  2068. * @since 5.8.0 The `$userdata` parameter was added.
  2069. *
  2070. * @param array $meta {
  2071. * Default meta values and keys for the user.
  2072. *
  2073. * @type string $nickname The user's nickname. Default is the user's username.
  2074. * @type string $first_name The user's first name.
  2075. * @type string $last_name The user's last name.
  2076. * @type string $description The user's description.
  2077. * @type string $rich_editing Whether to enable the rich-editor for the user. Default 'true'.
  2078. * @type string $syntax_highlighting Whether to enable the rich code editor for the user. Default 'true'.
  2079. * @type string $comment_shortcuts Whether to enable keyboard shortcuts for the user. Default 'false'.
  2080. * @type string $admin_color The color scheme for a user's admin screen. Default 'fresh'.
  2081. * @type int|bool $use_ssl Whether to force SSL on the user's admin area. 0|false if SSL
  2082. * is not forced.
  2083. * @type string $show_admin_bar_front Whether to show the admin bar on the front end for the user.
  2084. * Default 'true'.
  2085. * @type string $locale User's locale. Default empty.
  2086. * }
  2087. * @param WP_User $user User object.
  2088. * @param bool $update Whether the user is being updated rather than created.
  2089. * @param array $userdata The raw array of data passed to wp_insert_user().
  2090. */
  2091. $meta = apply_filters( 'insert_user_meta', $meta, $user, $update, $userdata );
  2092. $custom_meta = array();
  2093. if ( array_key_exists( 'meta_input', $userdata ) && is_array( $userdata['meta_input'] ) && ! empty( $userdata['meta_input'] ) ) {
  2094. $custom_meta = $userdata['meta_input'];
  2095. }
  2096. /**
  2097. * Filters a user's custom meta values and keys immediately after the user is created or updated
  2098. * and before any user meta is inserted or updated.
  2099. *
  2100. * For non-custom meta fields, see the {@see 'insert_user_meta'} filter.
  2101. *
  2102. * @since 5.9.0
  2103. *
  2104. * @param array $custom_meta Array of custom user meta values keyed by meta key.
  2105. * @param WP_User $user User object.
  2106. * @param bool $update Whether the user is being updated rather than created.
  2107. * @param array $userdata The raw array of data passed to wp_insert_user().
  2108. */
  2109. $custom_meta = apply_filters( 'insert_custom_user_meta', $custom_meta, $user, $update, $userdata );
  2110. $meta = array_merge( $meta, $custom_meta );
  2111. // Update user meta.
  2112. foreach ( $meta as $key => $value ) {
  2113. update_user_meta( $user_id, $key, $value );
  2114. }
  2115. foreach ( wp_get_user_contact_methods( $user ) as $key => $value ) {
  2116. if ( isset( $userdata[ $key ] ) ) {
  2117. update_user_meta( $user_id, $key, $userdata[ $key ] );
  2118. }
  2119. }
  2120. if ( isset( $userdata['role'] ) ) {
  2121. $user->set_role( $userdata['role'] );
  2122. } elseif ( ! $update ) {
  2123. $user->set_role( get_option( 'default_role' ) );
  2124. }
  2125. clean_user_cache( $user_id );
  2126. if ( $update ) {
  2127. /**
  2128. * Fires immediately after an existing user is updated.
  2129. *
  2130. * @since 2.0.0
  2131. * @since 5.8.0 The `$userdata` parameter was added.
  2132. *
  2133. * @param int $user_id User ID.
  2134. * @param WP_User $old_user_data Object containing user's data prior to update.
  2135. * @param array $userdata The raw array of data passed to wp_insert_user().
  2136. */
  2137. do_action( 'profile_update', $user_id, $old_user_data, $userdata );
  2138. if ( isset( $userdata['spam'] ) && $userdata['spam'] != $old_user_data->spam ) {
  2139. if ( 1 == $userdata['spam'] ) {
  2140. /**
  2141. * Fires after the user is marked as a SPAM user.
  2142. *
  2143. * @since 3.0.0
  2144. *
  2145. * @param int $user_id ID of the user marked as SPAM.
  2146. */
  2147. do_action( 'make_spam_user', $user_id );
  2148. } else {
  2149. /**
  2150. * Fires after the user is marked as a HAM user. Opposite of SPAM.
  2151. *
  2152. * @since 3.0.0
  2153. *
  2154. * @param int $user_id ID of the user marked as HAM.
  2155. */
  2156. do_action( 'make_ham_user', $user_id );
  2157. }
  2158. }
  2159. } else {
  2160. /**
  2161. * Fires immediately after a new user is registered.
  2162. *
  2163. * @since 1.5.0
  2164. * @since 5.8.0 The `$userdata` parameter was added.
  2165. *
  2166. * @param int $user_id User ID.
  2167. * @param array $userdata The raw array of data passed to wp_insert_user().
  2168. */
  2169. do_action( 'user_register', $user_id, $userdata );
  2170. }
  2171. return $user_id;
  2172. }
  2173. /**
  2174. * Updates a user in the database.
  2175. *
  2176. * It is possible to update a user's password by specifying the 'user_pass'
  2177. * value in the $userdata parameter array.
  2178. *
  2179. * If current user's password is being updated, then the cookies will be
  2180. * cleared.
  2181. *
  2182. * @since 2.0.0
  2183. *
  2184. * @see wp_insert_user() For what fields can be set in $userdata.
  2185. *
  2186. * @param array|object|WP_User $userdata An array of user data or a user object of type stdClass or WP_User.
  2187. * @return int|WP_Error The updated user's ID or a WP_Error object if the user could not be updated.
  2188. */
  2189. function wp_update_user( $userdata ) {
  2190. if ( $userdata instanceof stdClass ) {
  2191. $userdata = get_object_vars( $userdata );
  2192. } elseif ( $userdata instanceof WP_User ) {
  2193. $userdata = $userdata->to_array();
  2194. }
  2195. $user_id = isset( $userdata['ID'] ) ? (int) $userdata['ID'] : 0;
  2196. if ( ! $user_id ) {
  2197. return new WP_Error( 'invalid_user_id', __( 'Invalid user ID.' ) );
  2198. }
  2199. // First, get all of the original fields.
  2200. $user_obj = get_userdata( $user_id );
  2201. if ( ! $user_obj ) {
  2202. return new WP_Error( 'invalid_user_id', __( 'Invalid user ID.' ) );
  2203. }
  2204. $user = $user_obj->to_array();
  2205. // Add additional custom fields.
  2206. foreach ( _get_additional_user_keys( $user_obj ) as $key ) {
  2207. $user[ $key ] = get_user_meta( $user_id, $key, true );
  2208. }
  2209. // Escape data pulled from DB.
  2210. $user = add_magic_quotes( $user );
  2211. if ( ! empty( $userdata['user_pass'] ) && $userdata['user_pass'] !== $user_obj->user_pass ) {
  2212. // If password is changing, hash it now.
  2213. $plaintext_pass = $userdata['user_pass'];
  2214. $userdata['user_pass'] = wp_hash_password( $userdata['user_pass'] );
  2215. /**
  2216. * Filters whether to send the password change email.
  2217. *
  2218. * @since 4.3.0
  2219. *
  2220. * @see wp_insert_user() For `$user` and `$userdata` fields.
  2221. *
  2222. * @param bool $send Whether to send the email.
  2223. * @param array $user The original user array.
  2224. * @param array $userdata The updated user array.
  2225. */
  2226. $send_password_change_email = apply_filters( 'send_password_change_email', true, $user, $userdata );
  2227. }
  2228. if ( isset( $userdata['user_email'] ) && $user['user_email'] !== $userdata['user_email'] ) {
  2229. /**
  2230. * Filters whether to send the email change email.
  2231. *
  2232. * @since 4.3.0
  2233. *
  2234. * @see wp_insert_user() For `$user` and `$userdata` fields.
  2235. *
  2236. * @param bool $send Whether to send the email.
  2237. * @param array $user The original user array.
  2238. * @param array $userdata The updated user array.
  2239. */
  2240. $send_email_change_email = apply_filters( 'send_email_change_email', true, $user, $userdata );
  2241. }
  2242. clean_user_cache( $user_obj );
  2243. // Merge old and new fields with new fields overwriting old ones.
  2244. $userdata = array_merge( $user, $userdata );
  2245. $user_id = wp_insert_user( $userdata );
  2246. if ( is_wp_error( $user_id ) ) {
  2247. return $user_id;
  2248. }
  2249. $blog_name = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES );
  2250. $switched_locale = false;
  2251. if ( ! empty( $send_password_change_email ) || ! empty( $send_email_change_email ) ) {
  2252. $switched_locale = switch_to_locale( get_user_locale( $user_id ) );
  2253. }
  2254. if ( ! empty( $send_password_change_email ) ) {
  2255. /* translators: Do not translate USERNAME, ADMIN_EMAIL, EMAIL, SITENAME, SITEURL: those are placeholders. */
  2256. $pass_change_text = __(
  2257. 'Hi ###USERNAME###,
  2258. This notice confirms that your password was changed on ###SITENAME###.
  2259. If you did not change your password, please contact the Site Administrator at
  2260. ###ADMIN_EMAIL###
  2261. This email has been sent to ###EMAIL###
  2262. Regards,
  2263. All at ###SITENAME###
  2264. ###SITEURL###'
  2265. );
  2266. $pass_change_email = array(
  2267. 'to' => $user['user_email'],
  2268. /* translators: Password change notification email subject. %s: Site title. */
  2269. 'subject' => __( '[%s] Password Changed' ),
  2270. 'message' => $pass_change_text,
  2271. 'headers' => '',
  2272. );
  2273. /**
  2274. * Filters the contents of the email sent when the user's password is changed.
  2275. *
  2276. * @since 4.3.0
  2277. *
  2278. * @param array $pass_change_email {
  2279. * Used to build wp_mail().
  2280. *
  2281. * @type string $to The intended recipients. Add emails in a comma separated string.
  2282. * @type string $subject The subject of the email.
  2283. * @type string $message The content of the email.
  2284. * The following strings have a special meaning and will get replaced dynamically:
  2285. * - ###USERNAME### The current user's username.
  2286. * - ###ADMIN_EMAIL### The admin email in case this was unexpected.
  2287. * - ###EMAIL### The user's email address.
  2288. * - ###SITENAME### The name of the site.
  2289. * - ###SITEURL### The URL to the site.
  2290. * @type string $headers Headers. Add headers in a newline (\r\n) separated string.
  2291. * }
  2292. * @param array $user The original user array.
  2293. * @param array $userdata The updated user array.
  2294. */
  2295. $pass_change_email = apply_filters( 'password_change_email', $pass_change_email, $user, $userdata );
  2296. $pass_change_email['message'] = str_replace( '###USERNAME###', $user['user_login'], $pass_change_email['message'] );
  2297. $pass_change_email['message'] = str_replace( '###ADMIN_EMAIL###', get_option( 'admin_email' ), $pass_change_email['message'] );
  2298. $pass_change_email['message'] = str_replace( '###EMAIL###', $user['user_email'], $pass_change_email['message'] );
  2299. $pass_change_email['message'] = str_replace( '###SITENAME###', $blog_name, $pass_change_email['message'] );
  2300. $pass_change_email['message'] = str_replace( '###SITEURL###', home_url(), $pass_change_email['message'] );
  2301. wp_mail( $pass_change_email['to'], sprintf( $pass_change_email['subject'], $blog_name ), $pass_change_email['message'], $pass_change_email['headers'] );
  2302. }
  2303. if ( ! empty( $send_email_change_email ) ) {
  2304. /* translators: Do not translate USERNAME, ADMIN_EMAIL, NEW_EMAIL, EMAIL, SITENAME, SITEURL: those are placeholders. */
  2305. $email_change_text = __(
  2306. 'Hi ###USERNAME###,
  2307. This notice confirms that your email address on ###SITENAME### was changed to ###NEW_EMAIL###.
  2308. If you did not change your email, please contact the Site Administrator at
  2309. ###ADMIN_EMAIL###
  2310. This email has been sent to ###EMAIL###
  2311. Regards,
  2312. All at ###SITENAME###
  2313. ###SITEURL###'
  2314. );
  2315. $email_change_email = array(
  2316. 'to' => $user['user_email'],
  2317. /* translators: Email change notification email subject. %s: Site title. */
  2318. 'subject' => __( '[%s] Email Changed' ),
  2319. 'message' => $email_change_text,
  2320. 'headers' => '',
  2321. );
  2322. /**
  2323. * Filters the contents of the email sent when the user's email is changed.
  2324. *
  2325. * @since 4.3.0
  2326. *
  2327. * @param array $email_change_email {
  2328. * Used to build wp_mail().
  2329. *
  2330. * @type string $to The intended recipients.
  2331. * @type string $subject The subject of the email.
  2332. * @type string $message The content of the email.
  2333. * The following strings have a special meaning and will get replaced dynamically:
  2334. * - ###USERNAME### The current user's username.
  2335. * - ###ADMIN_EMAIL### The admin email in case this was unexpected.
  2336. * - ###NEW_EMAIL### The new email address.
  2337. * - ###EMAIL### The old email address.
  2338. * - ###SITENAME### The name of the site.
  2339. * - ###SITEURL### The URL to the site.
  2340. * @type string $headers Headers.
  2341. * }
  2342. * @param array $user The original user array.
  2343. * @param array $userdata The updated user array.
  2344. */
  2345. $email_change_email = apply_filters( 'email_change_email', $email_change_email, $user, $userdata );
  2346. $email_change_email['message'] = str_replace( '###USERNAME###', $user['user_login'], $email_change_email['message'] );
  2347. $email_change_email['message'] = str_replace( '###ADMIN_EMAIL###', get_option( 'admin_email' ), $email_change_email['message'] );
  2348. $email_change_email['message'] = str_replace( '###NEW_EMAIL###', $userdata['user_email'], $email_change_email['message'] );
  2349. $email_change_email['message'] = str_replace( '###EMAIL###', $user['user_email'], $email_change_email['message'] );
  2350. $email_change_email['message'] = str_replace( '###SITENAME###', $blog_name, $email_change_email['message'] );
  2351. $email_change_email['message'] = str_replace( '###SITEURL###', home_url(), $email_change_email['message'] );
  2352. wp_mail( $email_change_email['to'], sprintf( $email_change_email['subject'], $blog_name ), $email_change_email['message'], $email_change_email['headers'] );
  2353. }
  2354. if ( $switched_locale ) {
  2355. restore_previous_locale();
  2356. }
  2357. // Update the cookies if the password changed.
  2358. $current_user = wp_get_current_user();
  2359. if ( $current_user->ID == $user_id ) {
  2360. if ( isset( $plaintext_pass ) ) {
  2361. wp_clear_auth_cookie();
  2362. // Here we calculate the expiration length of the current auth cookie and compare it to the default expiration.
  2363. // If it's greater than this, then we know the user checked 'Remember Me' when they logged in.
  2364. $logged_in_cookie = wp_parse_auth_cookie( '', 'logged_in' );
  2365. /** This filter is documented in wp-includes/pluggable.php */
  2366. $default_cookie_life = apply_filters( 'auth_cookie_expiration', ( 2 * DAY_IN_SECONDS ), $user_id, false );
  2367. $remember = false;
  2368. if ( false !== $logged_in_cookie && ( $logged_in_cookie['expiration'] - time() ) > $default_cookie_life ) {
  2369. $remember = true;
  2370. }
  2371. wp_set_auth_cookie( $user_id, $remember );
  2372. }
  2373. }
  2374. return $user_id;
  2375. }
  2376. /**
  2377. * Provides a simpler way of inserting a user into the database.
  2378. *
  2379. * Creates a new user with just the username, password, and email. For more
  2380. * complex user creation use wp_insert_user() to specify more information.
  2381. *
  2382. * @since 2.0.0
  2383. *
  2384. * @see wp_insert_user() More complete way to create a new user.
  2385. *
  2386. * @param string $username The user's username.
  2387. * @param string $password The user's password.
  2388. * @param string $email Optional. The user's email. Default empty.
  2389. * @return int|WP_Error The newly created user's ID or a WP_Error object if the user could not
  2390. * be created.
  2391. */
  2392. function wp_create_user( $username, $password, $email = '' ) {
  2393. $user_login = wp_slash( $username );
  2394. $user_email = wp_slash( $email );
  2395. $user_pass = $password;
  2396. $userdata = compact( 'user_login', 'user_email', 'user_pass' );
  2397. return wp_insert_user( $userdata );
  2398. }
  2399. /**
  2400. * Returns a list of meta keys to be (maybe) populated in wp_update_user().
  2401. *
  2402. * The list of keys returned via this function are dependent on the presence
  2403. * of those keys in the user meta data to be set.
  2404. *
  2405. * @since 3.3.0
  2406. * @access private
  2407. *
  2408. * @param WP_User $user WP_User instance.
  2409. * @return string[] List of user keys to be populated in wp_update_user().
  2410. */
  2411. function _get_additional_user_keys( $user ) {
  2412. $keys = array( 'first_name', 'last_name', 'nickname', 'description', 'rich_editing', 'syntax_highlighting', 'comment_shortcuts', 'admin_color', 'use_ssl', 'show_admin_bar_front', 'locale' );
  2413. return array_merge( $keys, array_keys( wp_get_user_contact_methods( $user ) ) );
  2414. }
  2415. /**
  2416. * Sets up the user contact methods.
  2417. *
  2418. * Default contact methods were removed in 3.6. A filter dictates contact methods.
  2419. *
  2420. * @since 3.7.0
  2421. *
  2422. * @param WP_User|null $user Optional. WP_User object.
  2423. * @return string[] Array of contact method labels keyed by contact method.
  2424. */
  2425. function wp_get_user_contact_methods( $user = null ) {
  2426. $methods = array();
  2427. if ( get_site_option( 'initial_db_version' ) < 23588 ) {
  2428. $methods = array(
  2429. 'aim' => __( 'AIM' ),
  2430. 'yim' => __( 'Yahoo IM' ),
  2431. 'jabber' => __( 'Jabber / Google Talk' ),
  2432. );
  2433. }
  2434. /**
  2435. * Filters the user contact methods.
  2436. *
  2437. * @since 2.9.0
  2438. *
  2439. * @param string[] $methods Array of contact method labels keyed by contact method.
  2440. * @param WP_User|null $user WP_User object or null if none was provided.
  2441. */
  2442. return apply_filters( 'user_contactmethods', $methods, $user );
  2443. }
  2444. /**
  2445. * The old private function for setting up user contact methods.
  2446. *
  2447. * Use wp_get_user_contact_methods() instead.
  2448. *
  2449. * @since 2.9.0
  2450. * @access private
  2451. *
  2452. * @param WP_User|null $user Optional. WP_User object. Default null.
  2453. * @return string[] Array of contact method labels keyed by contact method.
  2454. */
  2455. function _wp_get_user_contactmethods( $user = null ) {
  2456. return wp_get_user_contact_methods( $user );
  2457. }
  2458. /**
  2459. * Gets the text suggesting how to create strong passwords.
  2460. *
  2461. * @since 4.1.0
  2462. *
  2463. * @return string The password hint text.
  2464. */
  2465. function wp_get_password_hint() {
  2466. $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; ).' );
  2467. /**
  2468. * Filters the text describing the site's password complexity policy.
  2469. *
  2470. * @since 4.1.0
  2471. *
  2472. * @param string $hint The password hint text.
  2473. */
  2474. return apply_filters( 'password_hint', $hint );
  2475. }
  2476. /**
  2477. * Creates, stores, then returns a password reset key for user.
  2478. *
  2479. * @since 4.4.0
  2480. *
  2481. * @global PasswordHash $wp_hasher Portable PHP password hashing framework.
  2482. *
  2483. * @param WP_User $user User to retrieve password reset key for.
  2484. * @return string|WP_Error Password reset key on success. WP_Error on error.
  2485. */
  2486. function get_password_reset_key( $user ) {
  2487. global $wp_hasher;
  2488. if ( ! ( $user instanceof WP_User ) ) {
  2489. return new WP_Error( 'invalidcombo', __( '<strong>Error:</strong> There is no account with that username or email address.' ) );
  2490. }
  2491. /**
  2492. * Fires before a new password is retrieved.
  2493. *
  2494. * Use the {@see 'retrieve_password'} hook instead.
  2495. *
  2496. * @since 1.5.0
  2497. * @deprecated 1.5.1 Misspelled. Use {@see 'retrieve_password'} hook instead.
  2498. *
  2499. * @param string $user_login The user login name.
  2500. */
  2501. do_action_deprecated( 'retreive_password', array( $user->user_login ), '1.5.1', 'retrieve_password' );
  2502. /**
  2503. * Fires before a new password is retrieved.
  2504. *
  2505. * @since 1.5.1
  2506. *
  2507. * @param string $user_login The user login name.
  2508. */
  2509. do_action( 'retrieve_password', $user->user_login );
  2510. $allow = true;
  2511. if ( is_multisite() && is_user_spammy( $user ) ) {
  2512. $allow = false;
  2513. }
  2514. /**
  2515. * Filters whether to allow a password to be reset.
  2516. *
  2517. * @since 2.7.0
  2518. *
  2519. * @param bool $allow Whether to allow the password to be reset. Default true.
  2520. * @param int $user_id The ID of the user attempting to reset a password.
  2521. */
  2522. $allow = apply_filters( 'allow_password_reset', $allow, $user->ID );
  2523. if ( ! $allow ) {
  2524. return new WP_Error( 'no_password_reset', __( 'Password reset is not allowed for this user' ) );
  2525. } elseif ( is_wp_error( $allow ) ) {
  2526. return $allow;
  2527. }
  2528. // Generate something random for a password reset key.
  2529. $key = wp_generate_password( 20, false );
  2530. /**
  2531. * Fires when a password reset key is generated.
  2532. *
  2533. * @since 2.5.0
  2534. *
  2535. * @param string $user_login The username for the user.
  2536. * @param string $key The generated password reset key.
  2537. */
  2538. do_action( 'retrieve_password_key', $user->user_login, $key );
  2539. // Now insert the key, hashed, into the DB.
  2540. if ( empty( $wp_hasher ) ) {
  2541. require_once ABSPATH . WPINC . '/class-phpass.php';
  2542. $wp_hasher = new PasswordHash( 8, true );
  2543. }
  2544. $hashed = time() . ':' . $wp_hasher->HashPassword( $key );
  2545. $key_saved = wp_update_user(
  2546. array(
  2547. 'ID' => $user->ID,
  2548. 'user_activation_key' => $hashed,
  2549. )
  2550. );
  2551. if ( is_wp_error( $key_saved ) ) {
  2552. return $key_saved;
  2553. }
  2554. return $key;
  2555. }
  2556. /**
  2557. * Retrieves a user row based on password reset key and login.
  2558. *
  2559. * A key is considered 'expired' if it exactly matches the value of the
  2560. * user_activation_key field, rather than being matched after going through the
  2561. * hashing process. This field is now hashed; old values are no longer accepted
  2562. * but have a different WP_Error code so good user feedback can be provided.
  2563. *
  2564. * @since 3.1.0
  2565. *
  2566. * @global wpdb $wpdb WordPress database object for queries.
  2567. * @global PasswordHash $wp_hasher Portable PHP password hashing framework instance.
  2568. *
  2569. * @param string $key Hash to validate sending user's password.
  2570. * @param string $login The user login.
  2571. * @return WP_User|WP_Error WP_User object on success, WP_Error object for invalid or expired keys.
  2572. */
  2573. function check_password_reset_key( $key, $login ) {
  2574. global $wpdb, $wp_hasher;
  2575. $key = preg_replace( '/[^a-z0-9]/i', '', $key );
  2576. if ( empty( $key ) || ! is_string( $key ) ) {
  2577. return new WP_Error( 'invalid_key', __( 'Invalid key.' ) );
  2578. }
  2579. if ( empty( $login ) || ! is_string( $login ) ) {
  2580. return new WP_Error( 'invalid_key', __( 'Invalid key.' ) );
  2581. }
  2582. $user = get_user_by( 'login', $login );
  2583. if ( ! $user ) {
  2584. return new WP_Error( 'invalid_key', __( 'Invalid key.' ) );
  2585. }
  2586. if ( empty( $wp_hasher ) ) {
  2587. require_once ABSPATH . WPINC . '/class-phpass.php';
  2588. $wp_hasher = new PasswordHash( 8, true );
  2589. }
  2590. /**
  2591. * Filters the expiration time of password reset keys.
  2592. *
  2593. * @since 4.3.0
  2594. *
  2595. * @param int $expiration The expiration time in seconds.
  2596. */
  2597. $expiration_duration = apply_filters( 'password_reset_expiration', DAY_IN_SECONDS );
  2598. if ( false !== strpos( $user->user_activation_key, ':' ) ) {
  2599. list( $pass_request_time, $pass_key ) = explode( ':', $user->user_activation_key, 2 );
  2600. $expiration_time = $pass_request_time + $expiration_duration;
  2601. } else {
  2602. $pass_key = $user->user_activation_key;
  2603. $expiration_time = false;
  2604. }
  2605. if ( ! $pass_key ) {
  2606. return new WP_Error( 'invalid_key', __( 'Invalid key.' ) );
  2607. }
  2608. $hash_is_correct = $wp_hasher->CheckPassword( $key, $pass_key );
  2609. if ( $hash_is_correct && $expiration_time && time() < $expiration_time ) {
  2610. return $user;
  2611. } elseif ( $hash_is_correct && $expiration_time ) {
  2612. // Key has an expiration time that's passed.
  2613. return new WP_Error( 'expired_key', __( 'Invalid key.' ) );
  2614. }
  2615. if ( hash_equals( $user->user_activation_key, $key ) || ( $hash_is_correct && ! $expiration_time ) ) {
  2616. $return = new WP_Error( 'expired_key', __( 'Invalid key.' ) );
  2617. $user_id = $user->ID;
  2618. /**
  2619. * Filters the return value of check_password_reset_key() when an
  2620. * old-style key is used.
  2621. *
  2622. * @since 3.7.0 Previously plain-text keys were stored in the database.
  2623. * @since 4.3.0 Previously key hashes were stored without an expiration time.
  2624. *
  2625. * @param WP_Error $return A WP_Error object denoting an expired key.
  2626. * Return a WP_User object to validate the key.
  2627. * @param int $user_id The matched user ID.
  2628. */
  2629. return apply_filters( 'password_reset_key_expired', $return, $user_id );
  2630. }
  2631. return new WP_Error( 'invalid_key', __( 'Invalid key.' ) );
  2632. }
  2633. /**
  2634. * Handles sending a password retrieval email to a user.
  2635. *
  2636. * @since 2.5.0
  2637. * @since 5.7.0 Added `$user_login` parameter.
  2638. *
  2639. * @global wpdb $wpdb WordPress database abstraction object.
  2640. * @global PasswordHash $wp_hasher Portable PHP password hashing framework.
  2641. *
  2642. * @param string $user_login Optional. Username to send a password retrieval email for.
  2643. * Defaults to `$_POST['user_login']` if not set.
  2644. * @return true|WP_Error True when finished, WP_Error object on error.
  2645. */
  2646. function retrieve_password( $user_login = null ) {
  2647. $errors = new WP_Error();
  2648. $user_data = false;
  2649. // Use the passed $user_login if available, otherwise use $_POST['user_login'].
  2650. if ( ! $user_login && ! empty( $_POST['user_login'] ) ) {
  2651. $user_login = $_POST['user_login'];
  2652. }
  2653. $user_login = trim( wp_unslash( $user_login ) );
  2654. if ( empty( $user_login ) ) {
  2655. $errors->add( 'empty_username', __( '<strong>Error:</strong> Please enter a username or email address.' ) );
  2656. } elseif ( strpos( $user_login, '@' ) ) {
  2657. $user_data = get_user_by( 'email', $user_login );
  2658. if ( empty( $user_data ) ) {
  2659. $user_data = get_user_by( 'login', $user_login );
  2660. }
  2661. if ( empty( $user_data ) ) {
  2662. $errors->add( 'invalid_email', __( '<strong>Error:</strong> There is no account with that username or email address.' ) );
  2663. }
  2664. } else {
  2665. $user_data = get_user_by( 'login', $user_login );
  2666. }
  2667. /**
  2668. * Filters the user data during a password reset request.
  2669. *
  2670. * Allows, for example, custom validation using data other than username or email address.
  2671. *
  2672. * @since 5.7.0
  2673. *
  2674. * @param WP_User|false $user_data WP_User object if found, false if the user does not exist.
  2675. * @param WP_Error $errors A WP_Error object containing any errors generated
  2676. * by using invalid credentials.
  2677. */
  2678. $user_data = apply_filters( 'lostpassword_user_data', $user_data, $errors );
  2679. /**
  2680. * Fires before errors are returned from a password reset request.
  2681. *
  2682. * @since 2.1.0
  2683. * @since 4.4.0 Added the `$errors` parameter.
  2684. * @since 5.4.0 Added the `$user_data` parameter.
  2685. *
  2686. * @param WP_Error $errors A WP_Error object containing any errors generated
  2687. * by using invalid credentials.
  2688. * @param WP_User|false $user_data WP_User object if found, false if the user does not exist.
  2689. */
  2690. do_action( 'lostpassword_post', $errors, $user_data );
  2691. /**
  2692. * Filters the errors encountered on a password reset request.
  2693. *
  2694. * The filtered WP_Error object may, for example, contain errors for an invalid
  2695. * username or email address. A WP_Error object should always be returned,
  2696. * but may or may not contain errors.
  2697. *
  2698. * If any errors are present in $errors, this will abort the password reset request.
  2699. *
  2700. * @since 5.5.0
  2701. *
  2702. * @param WP_Error $errors A WP_Error object containing any errors generated
  2703. * by using invalid credentials.
  2704. * @param WP_User|false $user_data WP_User object if found, false if the user does not exist.
  2705. */
  2706. $errors = apply_filters( 'lostpassword_errors', $errors, $user_data );
  2707. if ( $errors->has_errors() ) {
  2708. return $errors;
  2709. }
  2710. if ( ! $user_data ) {
  2711. $errors->add( 'invalidcombo', __( '<strong>Error:</strong> There is no account with that username or email address.' ) );
  2712. return $errors;
  2713. }
  2714. /**
  2715. * Filters whether to send the retrieve password email.
  2716. *
  2717. * Return false to disable sending the email.
  2718. *
  2719. * @since 6.0.0
  2720. *
  2721. * @param bool $send Whether to send the email.
  2722. * @param string $user_login The username for the user.
  2723. * @param WP_User $user_data WP_User object.
  2724. */
  2725. if ( ! apply_filters( 'send_retrieve_password_email', true, $user_login, $user_data ) ) {
  2726. return true;
  2727. }
  2728. // Redefining user_login ensures we return the right case in the email.
  2729. $user_login = $user_data->user_login;
  2730. $user_email = $user_data->user_email;
  2731. $key = get_password_reset_key( $user_data );
  2732. if ( is_wp_error( $key ) ) {
  2733. return $key;
  2734. }
  2735. // Localize password reset message content for user.
  2736. $locale = get_user_locale( $user_data );
  2737. $switched_locale = switch_to_locale( $locale );
  2738. if ( is_multisite() ) {
  2739. $site_name = get_network()->site_name;
  2740. } else {
  2741. /*
  2742. * The blogname option is escaped with esc_html on the way into the database
  2743. * in sanitize_option. We want to reverse this for the plain text arena of emails.
  2744. */
  2745. $site_name = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES );
  2746. }
  2747. $message = __( 'Someone has requested a password reset for the following account:' ) . "\r\n\r\n";
  2748. /* translators: %s: Site name. */
  2749. $message .= sprintf( __( 'Site Name: %s' ), $site_name ) . "\r\n\r\n";
  2750. /* translators: %s: User login. */
  2751. $message .= sprintf( __( 'Username: %s' ), $user_login ) . "\r\n\r\n";
  2752. $message .= __( 'If this was a mistake, ignore this email and nothing will happen.' ) . "\r\n\r\n";
  2753. $message .= __( 'To reset your password, visit the following address:' ) . "\r\n\r\n";
  2754. $message .= network_site_url( "wp-login.php?action=rp&key=$key&login=" . rawurlencode( $user_login ), 'login' ) . '&wp_lang=' . $locale . "\r\n\r\n";
  2755. if ( ! is_user_logged_in() ) {
  2756. $requester_ip = $_SERVER['REMOTE_ADDR'];
  2757. if ( $requester_ip ) {
  2758. $message .= sprintf(
  2759. /* translators: %s: IP address of password reset requester. */
  2760. __( 'This password reset request originated from the IP address %s.' ),
  2761. $requester_ip
  2762. ) . "\r\n";
  2763. }
  2764. }
  2765. /* translators: Password reset notification email subject. %s: Site title. */
  2766. $title = sprintf( __( '[%s] Password Reset' ), $site_name );
  2767. /**
  2768. * Filters the subject of the password reset email.
  2769. *
  2770. * @since 2.8.0
  2771. * @since 4.4.0 Added the `$user_login` and `$user_data` parameters.
  2772. *
  2773. * @param string $title Email subject.
  2774. * @param string $user_login The username for the user.
  2775. * @param WP_User $user_data WP_User object.
  2776. */
  2777. $title = apply_filters( 'retrieve_password_title', $title, $user_login, $user_data );
  2778. /**
  2779. * Filters the message body of the password reset mail.
  2780. *
  2781. * If the filtered message is empty, the password reset email will not be sent.
  2782. *
  2783. * @since 2.8.0
  2784. * @since 4.1.0 Added `$user_login` and `$user_data` parameters.
  2785. *
  2786. * @param string $message Email message.
  2787. * @param string $key The activation key.
  2788. * @param string $user_login The username for the user.
  2789. * @param WP_User $user_data WP_User object.
  2790. */
  2791. $message = apply_filters( 'retrieve_password_message', $message, $key, $user_login, $user_data );
  2792. // Short-circuit on falsey $message value for backwards compatibility.
  2793. if ( ! $message ) {
  2794. return true;
  2795. }
  2796. /*
  2797. * Wrap the single notification email arguments in an array
  2798. * to pass them to the retrieve_password_notification_email filter.
  2799. */
  2800. $defaults = array(
  2801. 'to' => $user_email,
  2802. 'subject' => $title,
  2803. 'message' => $message,
  2804. 'headers' => '',
  2805. );
  2806. /**
  2807. * Filters the contents of the reset password notification email sent to the user.
  2808. *
  2809. * @since 6.0.0
  2810. *
  2811. * @param array $defaults {
  2812. * The default notification email arguments. Used to build wp_mail().
  2813. *
  2814. * @type string $to The intended recipient - user email address.
  2815. * @type string $subject The subject of the email.
  2816. * @type string $message The body of the email.
  2817. * @type string $headers The headers of the email.
  2818. * }
  2819. * @type string $key The activation key.
  2820. * @type string $user_login The username for the user.
  2821. * @type WP_User $user_data WP_User object.
  2822. */
  2823. $notification_email = apply_filters( 'retrieve_password_notification_email', $defaults, $key, $user_login, $user_data );
  2824. if ( $switched_locale ) {
  2825. restore_previous_locale();
  2826. }
  2827. if ( is_array( $notification_email ) ) {
  2828. // Force key order and merge defaults in case any value is missing in the filtered array.
  2829. $notification_email = array_merge( $defaults, $notification_email );
  2830. } else {
  2831. $notification_email = $defaults;
  2832. }
  2833. list( $to, $subject, $message, $headers ) = array_values( $notification_email );
  2834. $subject = wp_specialchars_decode( $subject );
  2835. if ( ! wp_mail( $to, $subject, $message, $headers ) ) {
  2836. $errors->add(
  2837. 'retrieve_password_email_failure',
  2838. sprintf(
  2839. /* translators: %s: Documentation URL. */
  2840. __( '<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>.' ),
  2841. esc_url( __( 'https://wordpress.org/support/article/resetting-your-password/' ) )
  2842. )
  2843. );
  2844. return $errors;
  2845. }
  2846. return true;
  2847. }
  2848. /**
  2849. * Handles resetting the user's password.
  2850. *
  2851. * @since 2.5.0
  2852. *
  2853. * @param WP_User $user The user
  2854. * @param string $new_pass New password for the user in plaintext
  2855. */
  2856. function reset_password( $user, $new_pass ) {
  2857. /**
  2858. * Fires before the user's password is reset.
  2859. *
  2860. * @since 1.5.0
  2861. *
  2862. * @param WP_User $user The user.
  2863. * @param string $new_pass New user password.
  2864. */
  2865. do_action( 'password_reset', $user, $new_pass );
  2866. wp_set_password( $new_pass, $user->ID );
  2867. update_user_meta( $user->ID, 'default_password_nag', false );
  2868. /**
  2869. * Fires after the user's password is reset.
  2870. *
  2871. * @since 4.4.0
  2872. *
  2873. * @param WP_User $user The user.
  2874. * @param string $new_pass New user password.
  2875. */
  2876. do_action( 'after_password_reset', $user, $new_pass );
  2877. }
  2878. /**
  2879. * Handles registering a new user.
  2880. *
  2881. * @since 2.5.0
  2882. *
  2883. * @param string $user_login User's username for logging in
  2884. * @param string $user_email User's email address to send password and add
  2885. * @return int|WP_Error Either user's ID or error on failure.
  2886. */
  2887. function register_new_user( $user_login, $user_email ) {
  2888. $errors = new WP_Error();
  2889. $sanitized_user_login = sanitize_user( $user_login );
  2890. /**
  2891. * Filters the email address of a user being registered.
  2892. *
  2893. * @since 2.1.0
  2894. *
  2895. * @param string $user_email The email address of the new user.
  2896. */
  2897. $user_email = apply_filters( 'user_registration_email', $user_email );
  2898. // Check the username.
  2899. if ( '' === $sanitized_user_login ) {
  2900. $errors->add( 'empty_username', __( '<strong>Error:</strong> Please enter a username.' ) );
  2901. } elseif ( ! validate_username( $user_login ) ) {
  2902. $errors->add( 'invalid_username', __( '<strong>Error:</strong> This username is invalid because it uses illegal characters. Please enter a valid username.' ) );
  2903. $sanitized_user_login = '';
  2904. } elseif ( username_exists( $sanitized_user_login ) ) {
  2905. $errors->add( 'username_exists', __( '<strong>Error:</strong> This username is already registered. Please choose another one.' ) );
  2906. } else {
  2907. /** This filter is documented in wp-includes/user.php */
  2908. $illegal_user_logins = (array) apply_filters( 'illegal_user_logins', array() );
  2909. if ( in_array( strtolower( $sanitized_user_login ), array_map( 'strtolower', $illegal_user_logins ), true ) ) {
  2910. $errors->add( 'invalid_username', __( '<strong>Error:</strong> Sorry, that username is not allowed.' ) );
  2911. }
  2912. }
  2913. // Check the email address.
  2914. if ( '' === $user_email ) {
  2915. $errors->add( 'empty_email', __( '<strong>Error:</strong> Please type your email address.' ) );
  2916. } elseif ( ! is_email( $user_email ) ) {
  2917. $errors->add( 'invalid_email', __( '<strong>Error:</strong> The email address is not correct.' ) );
  2918. $user_email = '';
  2919. } elseif ( email_exists( $user_email ) ) {
  2920. $errors->add(
  2921. 'email_exists',
  2922. sprintf(
  2923. /* translators: %s: Link to the login page. */
  2924. __( '<strong>Error:</strong> This email address is already registered. <a href="%s">Log in</a> with this address or choose another one.' ),
  2925. wp_login_url()
  2926. )
  2927. );
  2928. }
  2929. /**
  2930. * Fires when submitting registration form data, before the user is created.
  2931. *
  2932. * @since 2.1.0
  2933. *
  2934. * @param string $sanitized_user_login The submitted username after being sanitized.
  2935. * @param string $user_email The submitted email.
  2936. * @param WP_Error $errors Contains any errors with submitted username and email,
  2937. * e.g., an empty field, an invalid username or email,
  2938. * or an existing username or email.
  2939. */
  2940. do_action( 'register_post', $sanitized_user_login, $user_email, $errors );
  2941. /**
  2942. * Filters the errors encountered when a new user is being registered.
  2943. *
  2944. * The filtered WP_Error object may, for example, contain errors for an invalid
  2945. * or existing username or email address. A WP_Error object should always be returned,
  2946. * but may or may not contain errors.
  2947. *
  2948. * If any errors are present in $errors, this will abort the user's registration.
  2949. *
  2950. * @since 2.1.0
  2951. *
  2952. * @param WP_Error $errors A WP_Error object containing any errors encountered
  2953. * during registration.
  2954. * @param string $sanitized_user_login User's username after it has been sanitized.
  2955. * @param string $user_email User's email.
  2956. */
  2957. $errors = apply_filters( 'registration_errors', $errors, $sanitized_user_login, $user_email );
  2958. if ( $errors->has_errors() ) {
  2959. return $errors;
  2960. }
  2961. $user_pass = wp_generate_password( 12, false );
  2962. $user_id = wp_create_user( $sanitized_user_login, $user_pass, $user_email );
  2963. if ( ! $user_id || is_wp_error( $user_id ) ) {
  2964. $errors->add(
  2965. 'registerfail',
  2966. sprintf(
  2967. /* translators: %s: Admin email address. */
  2968. __( '<strong>Error:</strong> Could not register you&hellip; please contact the <a href="mailto:%s">site admin</a>!' ),
  2969. get_option( 'admin_email' )
  2970. )
  2971. );
  2972. return $errors;
  2973. }
  2974. update_user_meta( $user_id, 'default_password_nag', true ); // Set up the password change nag.
  2975. if ( ! empty( $_COOKIE['wp_lang'] ) ) {
  2976. $wp_lang = sanitize_text_field( $_COOKIE['wp_lang'] );
  2977. if ( in_array( $wp_lang, get_available_languages(), true ) ) {
  2978. update_user_meta( $user_id, 'locale', $wp_lang ); // Set user locale if defined on registration.
  2979. }
  2980. }
  2981. /**
  2982. * Fires after a new user registration has been recorded.
  2983. *
  2984. * @since 4.4.0
  2985. *
  2986. * @param int $user_id ID of the newly registered user.
  2987. */
  2988. do_action( 'register_new_user', $user_id );
  2989. return $user_id;
  2990. }
  2991. /**
  2992. * Initiates email notifications related to the creation of new users.
  2993. *
  2994. * Notifications are sent both to the site admin and to the newly created user.
  2995. *
  2996. * @since 4.4.0
  2997. * @since 4.6.0 Converted the `$notify` parameter to accept 'user' for sending
  2998. * notifications only to the user created.
  2999. *
  3000. * @param int $user_id ID of the newly created user.
  3001. * @param string $notify Optional. Type of notification that should happen. Accepts 'admin'
  3002. * or an empty string (admin only), 'user', or 'both' (admin and user).
  3003. * Default 'both'.
  3004. */
  3005. function wp_send_new_user_notifications( $user_id, $notify = 'both' ) {
  3006. wp_new_user_notification( $user_id, null, $notify );
  3007. }
  3008. /**
  3009. * Retrieves the current session token from the logged_in cookie.
  3010. *
  3011. * @since 4.0.0
  3012. *
  3013. * @return string Token.
  3014. */
  3015. function wp_get_session_token() {
  3016. $cookie = wp_parse_auth_cookie( '', 'logged_in' );
  3017. return ! empty( $cookie['token'] ) ? $cookie['token'] : '';
  3018. }
  3019. /**
  3020. * Retrieves a list of sessions for the current user.
  3021. *
  3022. * @since 4.0.0
  3023. *
  3024. * @return array Array of sessions.
  3025. */
  3026. function wp_get_all_sessions() {
  3027. $manager = WP_Session_Tokens::get_instance( get_current_user_id() );
  3028. return $manager->get_all();
  3029. }
  3030. /**
  3031. * Removes the current session token from the database.
  3032. *
  3033. * @since 4.0.0
  3034. */
  3035. function wp_destroy_current_session() {
  3036. $token = wp_get_session_token();
  3037. if ( $token ) {
  3038. $manager = WP_Session_Tokens::get_instance( get_current_user_id() );
  3039. $manager->destroy( $token );
  3040. }
  3041. }
  3042. /**
  3043. * Removes all but the current session token for the current user for the database.
  3044. *
  3045. * @since 4.0.0
  3046. */
  3047. function wp_destroy_other_sessions() {
  3048. $token = wp_get_session_token();
  3049. if ( $token ) {
  3050. $manager = WP_Session_Tokens::get_instance( get_current_user_id() );
  3051. $manager->destroy_others( $token );
  3052. }
  3053. }
  3054. /**
  3055. * Removes all session tokens for the current user from the database.
  3056. *
  3057. * @since 4.0.0
  3058. */
  3059. function wp_destroy_all_sessions() {
  3060. $manager = WP_Session_Tokens::get_instance( get_current_user_id() );
  3061. $manager->destroy_all();
  3062. }
  3063. /**
  3064. * Gets the user IDs of all users with no role on this site.
  3065. *
  3066. * @since 4.4.0
  3067. * @since 4.9.0 The `$site_id` parameter was added to support multisite.
  3068. *
  3069. * @param int|null $site_id Optional. The site ID to get users with no role for. Defaults to the current site.
  3070. * @return string[] Array of user IDs as strings.
  3071. */
  3072. function wp_get_users_with_no_role( $site_id = null ) {
  3073. global $wpdb;
  3074. if ( ! $site_id ) {
  3075. $site_id = get_current_blog_id();
  3076. }
  3077. $prefix = $wpdb->get_blog_prefix( $site_id );
  3078. if ( is_multisite() && get_current_blog_id() != $site_id ) {
  3079. switch_to_blog( $site_id );
  3080. $role_names = wp_roles()->get_names();
  3081. restore_current_blog();
  3082. } else {
  3083. $role_names = wp_roles()->get_names();
  3084. }
  3085. $regex = implode( '|', array_keys( $role_names ) );
  3086. $regex = preg_replace( '/[^a-zA-Z_\|-]/', '', $regex );
  3087. $users = $wpdb->get_col(
  3088. $wpdb->prepare(
  3089. "
  3090. SELECT user_id
  3091. FROM $wpdb->usermeta
  3092. WHERE meta_key = '{$prefix}capabilities'
  3093. AND meta_value NOT REGEXP %s
  3094. ",
  3095. $regex
  3096. )
  3097. );
  3098. return $users;
  3099. }
  3100. /**
  3101. * Retrieves the current user object.
  3102. *
  3103. * Will set the current user, if the current user is not set. The current user
  3104. * will be set to the logged-in person. If no user is logged-in, then it will
  3105. * set the current user to 0, which is invalid and won't have any permissions.
  3106. *
  3107. * This function is used by the pluggable functions wp_get_current_user() and
  3108. * get_currentuserinfo(), the latter of which is deprecated but used for backward
  3109. * compatibility.
  3110. *
  3111. * @since 4.5.0
  3112. * @access private
  3113. *
  3114. * @see wp_get_current_user()
  3115. * @global WP_User $current_user Checks if the current user is set.
  3116. *
  3117. * @return WP_User Current WP_User instance.
  3118. */
  3119. function _wp_get_current_user() {
  3120. global $current_user;
  3121. if ( ! empty( $current_user ) ) {
  3122. if ( $current_user instanceof WP_User ) {
  3123. return $current_user;
  3124. }
  3125. // Upgrade stdClass to WP_User.
  3126. if ( is_object( $current_user ) && isset( $current_user->ID ) ) {
  3127. $cur_id = $current_user->ID;
  3128. $current_user = null;
  3129. wp_set_current_user( $cur_id );
  3130. return $current_user;
  3131. }
  3132. // $current_user has a junk value. Force to WP_User with ID 0.
  3133. $current_user = null;
  3134. wp_set_current_user( 0 );
  3135. return $current_user;
  3136. }
  3137. if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST ) {
  3138. wp_set_current_user( 0 );
  3139. return $current_user;
  3140. }
  3141. /**
  3142. * Filters the current user.
  3143. *
  3144. * The default filters use this to determine the current user from the
  3145. * request's cookies, if available.
  3146. *
  3147. * Returning a value of false will effectively short-circuit setting
  3148. * the current user.
  3149. *
  3150. * @since 3.9.0
  3151. *
  3152. * @param int|false $user_id User ID if one has been determined, false otherwise.
  3153. */
  3154. $user_id = apply_filters( 'determine_current_user', false );
  3155. if ( ! $user_id ) {
  3156. wp_set_current_user( 0 );
  3157. return $current_user;
  3158. }
  3159. wp_set_current_user( $user_id );
  3160. return $current_user;
  3161. }
  3162. /**
  3163. * Sends a confirmation request email when a change of user email address is attempted.
  3164. *
  3165. * @since 3.0.0
  3166. * @since 4.9.0 This function was moved from wp-admin/includes/ms.php so it's no longer Multisite specific.
  3167. *
  3168. * @global WP_Error $errors WP_Error object.
  3169. */
  3170. function send_confirmation_on_profile_email() {
  3171. global $errors;
  3172. $current_user = wp_get_current_user();
  3173. if ( ! is_object( $errors ) ) {
  3174. $errors = new WP_Error();
  3175. }
  3176. if ( $current_user->ID != $_POST['user_id'] ) {
  3177. return false;
  3178. }
  3179. if ( $current_user->user_email != $_POST['email'] ) {
  3180. if ( ! is_email( $_POST['email'] ) ) {
  3181. $errors->add(
  3182. 'user_email',
  3183. __( '<strong>Error:</strong> The email address is not correct.' ),
  3184. array(
  3185. 'form-field' => 'email',
  3186. )
  3187. );
  3188. return;
  3189. }
  3190. if ( email_exists( $_POST['email'] ) ) {
  3191. $errors->add(
  3192. 'user_email',
  3193. __( '<strong>Error:</strong> The email address is already used.' ),
  3194. array(
  3195. 'form-field' => 'email',
  3196. )
  3197. );
  3198. delete_user_meta( $current_user->ID, '_new_email' );
  3199. return;
  3200. }
  3201. $hash = md5( $_POST['email'] . time() . wp_rand() );
  3202. $new_user_email = array(
  3203. 'hash' => $hash,
  3204. 'newemail' => $_POST['email'],
  3205. );
  3206. update_user_meta( $current_user->ID, '_new_email', $new_user_email );
  3207. $sitename = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES );
  3208. /* translators: Do not translate USERNAME, ADMIN_URL, EMAIL, SITENAME, SITEURL: those are placeholders. */
  3209. $email_text = __(
  3210. 'Howdy ###USERNAME###,
  3211. You recently requested to have the email address on your account changed.
  3212. If this is correct, please click on the following link to change it:
  3213. ###ADMIN_URL###
  3214. You can safely ignore and delete this email if you do not want to
  3215. take this action.
  3216. This email has been sent to ###EMAIL###
  3217. Regards,
  3218. All at ###SITENAME###
  3219. ###SITEURL###'
  3220. );
  3221. /**
  3222. * Filters the text of the email sent when a change of user email address is attempted.
  3223. *
  3224. * The following strings have a special meaning and will get replaced dynamically:
  3225. * - ###USERNAME### The current user's username.
  3226. * - ###ADMIN_URL### The link to click on to confirm the email change.
  3227. * - ###EMAIL### The new email.
  3228. * - ###SITENAME### The name of the site.
  3229. * - ###SITEURL### The URL to the site.
  3230. *
  3231. * @since MU (3.0.0)
  3232. * @since 4.9.0 This filter is no longer Multisite specific.
  3233. *
  3234. * @param string $email_text Text in the email.
  3235. * @param array $new_user_email {
  3236. * Data relating to the new user email address.
  3237. *
  3238. * @type string $hash The secure hash used in the confirmation link URL.
  3239. * @type string $newemail The proposed new email address.
  3240. * }
  3241. */
  3242. $content = apply_filters( 'new_user_email_content', $email_text, $new_user_email );
  3243. $content = str_replace( '###USERNAME###', $current_user->user_login, $content );
  3244. $content = str_replace( '###ADMIN_URL###', esc_url( admin_url( 'profile.php?newuseremail=' . $hash ) ), $content );
  3245. $content = str_replace( '###EMAIL###', $_POST['email'], $content );
  3246. $content = str_replace( '###SITENAME###', $sitename, $content );
  3247. $content = str_replace( '###SITEURL###', home_url(), $content );
  3248. /* translators: New email address notification email subject. %s: Site title. */
  3249. wp_mail( $_POST['email'], sprintf( __( '[%s] Email Change Request' ), $sitename ), $content );
  3250. $_POST['email'] = $current_user->user_email;
  3251. }
  3252. }
  3253. /**
  3254. * Adds an admin notice alerting the user to check for confirmation request email
  3255. * after email address change.
  3256. *
  3257. * @since 3.0.0
  3258. * @since 4.9.0 This function was moved from wp-admin/includes/ms.php so it's no longer Multisite specific.
  3259. *
  3260. * @global string $pagenow The filename of the current screen.
  3261. */
  3262. function new_user_email_admin_notice() {
  3263. global $pagenow;
  3264. if ( 'profile.php' === $pagenow && isset( $_GET['updated'] ) ) {
  3265. $email = get_user_meta( get_current_user_id(), '_new_email', true );
  3266. if ( $email ) {
  3267. /* translators: %s: New email address. */
  3268. 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>';
  3269. }
  3270. }
  3271. }
  3272. /**
  3273. * Gets all personal data request types.
  3274. *
  3275. * @since 4.9.6
  3276. * @access private
  3277. *
  3278. * @return string[] List of core privacy action types.
  3279. */
  3280. function _wp_privacy_action_request_types() {
  3281. return array(
  3282. 'export_personal_data',
  3283. 'remove_personal_data',
  3284. );
  3285. }
  3286. /**
  3287. * Registers the personal data exporter for users.
  3288. *
  3289. * @since 4.9.6
  3290. *
  3291. * @param array[] $exporters An array of personal data exporters.
  3292. * @return array[] An array of personal data exporters.
  3293. */
  3294. function wp_register_user_personal_data_exporter( $exporters ) {
  3295. $exporters['wordpress-user'] = array(
  3296. 'exporter_friendly_name' => __( 'WordPress User' ),
  3297. 'callback' => 'wp_user_personal_data_exporter',
  3298. );
  3299. return $exporters;
  3300. }
  3301. /**
  3302. * Finds and exports personal data associated with an email address from the user and user_meta table.
  3303. *
  3304. * @since 4.9.6
  3305. * @since 5.4.0 Added 'Community Events Location' group to the export data.
  3306. * @since 5.4.0 Added 'Session Tokens' group to the export data.
  3307. *
  3308. * @param string $email_address The user's email address.
  3309. * @return array An array of personal data.
  3310. */
  3311. function wp_user_personal_data_exporter( $email_address ) {
  3312. $email_address = trim( $email_address );
  3313. $data_to_export = array();
  3314. $user = get_user_by( 'email', $email_address );
  3315. if ( ! $user ) {
  3316. return array(
  3317. 'data' => array(),
  3318. 'done' => true,
  3319. );
  3320. }
  3321. $user_meta = get_user_meta( $user->ID );
  3322. $user_props_to_export = array(
  3323. 'ID' => __( 'User ID' ),
  3324. 'user_login' => __( 'User Login Name' ),
  3325. 'user_nicename' => __( 'User Nice Name' ),
  3326. 'user_email' => __( 'User Email' ),
  3327. 'user_url' => __( 'User URL' ),
  3328. 'user_registered' => __( 'User Registration Date' ),
  3329. 'display_name' => __( 'User Display Name' ),
  3330. 'nickname' => __( 'User Nickname' ),
  3331. 'first_name' => __( 'User First Name' ),
  3332. 'last_name' => __( 'User Last Name' ),
  3333. 'description' => __( 'User Description' ),
  3334. );
  3335. $user_data_to_export = array();
  3336. foreach ( $user_props_to_export as $key => $name ) {
  3337. $value = '';
  3338. switch ( $key ) {
  3339. case 'ID':
  3340. case 'user_login':
  3341. case 'user_nicename':
  3342. case 'user_email':
  3343. case 'user_url':
  3344. case 'user_registered':
  3345. case 'display_name':
  3346. $value = $user->data->$key;
  3347. break;
  3348. case 'nickname':
  3349. case 'first_name':
  3350. case 'last_name':
  3351. case 'description':
  3352. $value = $user_meta[ $key ][0];
  3353. break;
  3354. }
  3355. if ( ! empty( $value ) ) {
  3356. $user_data_to_export[] = array(
  3357. 'name' => $name,
  3358. 'value' => $value,
  3359. );
  3360. }
  3361. }
  3362. // Get the list of reserved names.
  3363. $reserved_names = array_values( $user_props_to_export );
  3364. /**
  3365. * Filters the user's profile data for the privacy exporter.
  3366. *
  3367. * @since 5.4.0
  3368. *
  3369. * @param array $additional_user_profile_data {
  3370. * An array of name-value pairs of additional user data items. Default empty array.
  3371. *
  3372. * @type string $name The user-facing name of an item name-value pair,e.g. 'IP Address'.
  3373. * @type string $value The user-facing value of an item data pair, e.g. '50.60.70.0'.
  3374. * }
  3375. * @param WP_User $user The user whose data is being exported.
  3376. * @param string[] $reserved_names An array of reserved names. Any item in `$additional_user_data`
  3377. * that uses one of these for its `name` will not be included in the export.
  3378. */
  3379. $_extra_data = apply_filters( 'wp_privacy_additional_user_profile_data', array(), $user, $reserved_names );
  3380. if ( is_array( $_extra_data ) && ! empty( $_extra_data ) ) {
  3381. // Remove items that use reserved names.
  3382. $extra_data = array_filter(
  3383. $_extra_data,
  3384. static function( $item ) use ( $reserved_names ) {
  3385. return ! in_array( $item['name'], $reserved_names, true );
  3386. }
  3387. );
  3388. if ( count( $extra_data ) !== count( $_extra_data ) ) {
  3389. _doing_it_wrong(
  3390. __FUNCTION__,
  3391. sprintf(
  3392. /* translators: %s: wp_privacy_additional_user_profile_data */
  3393. __( 'Filter %s returned items with reserved names.' ),
  3394. '<code>wp_privacy_additional_user_profile_data</code>'
  3395. ),
  3396. '5.4.0'
  3397. );
  3398. }
  3399. if ( ! empty( $extra_data ) ) {
  3400. $user_data_to_export = array_merge( $user_data_to_export, $extra_data );
  3401. }
  3402. }
  3403. $data_to_export[] = array(
  3404. 'group_id' => 'user',
  3405. 'group_label' => __( 'User' ),
  3406. 'group_description' => __( 'User&#8217;s profile data.' ),
  3407. 'item_id' => "user-{$user->ID}",
  3408. 'data' => $user_data_to_export,
  3409. );
  3410. if ( isset( $user_meta['community-events-location'] ) ) {
  3411. $location = maybe_unserialize( $user_meta['community-events-location'][0] );
  3412. $location_props_to_export = array(
  3413. 'description' => __( 'City' ),
  3414. 'country' => __( 'Country' ),
  3415. 'latitude' => __( 'Latitude' ),
  3416. 'longitude' => __( 'Longitude' ),
  3417. 'ip' => __( 'IP' ),
  3418. );
  3419. $location_data_to_export = array();
  3420. foreach ( $location_props_to_export as $key => $name ) {
  3421. if ( ! empty( $location[ $key ] ) ) {
  3422. $location_data_to_export[] = array(
  3423. 'name' => $name,
  3424. 'value' => $location[ $key ],
  3425. );
  3426. }
  3427. }
  3428. $data_to_export[] = array(
  3429. 'group_id' => 'community-events-location',
  3430. 'group_label' => __( 'Community Events Location' ),
  3431. 'group_description' => __( 'User&#8217;s location data used for the Community Events in the WordPress Events and News dashboard widget.' ),
  3432. 'item_id' => "community-events-location-{$user->ID}",
  3433. 'data' => $location_data_to_export,
  3434. );
  3435. }
  3436. if ( isset( $user_meta['session_tokens'] ) ) {
  3437. $session_tokens = maybe_unserialize( $user_meta['session_tokens'][0] );
  3438. $session_tokens_props_to_export = array(
  3439. 'expiration' => __( 'Expiration' ),
  3440. 'ip' => __( 'IP' ),
  3441. 'ua' => __( 'User Agent' ),
  3442. 'login' => __( 'Last Login' ),
  3443. );
  3444. foreach ( $session_tokens as $token_key => $session_token ) {
  3445. $session_tokens_data_to_export = array();
  3446. foreach ( $session_tokens_props_to_export as $key => $name ) {
  3447. if ( ! empty( $session_token[ $key ] ) ) {
  3448. $value = $session_token[ $key ];
  3449. if ( in_array( $key, array( 'expiration', 'login' ), true ) ) {
  3450. $value = date_i18n( 'F d, Y H:i A', $value );
  3451. }
  3452. $session_tokens_data_to_export[] = array(
  3453. 'name' => $name,
  3454. 'value' => $value,
  3455. );
  3456. }
  3457. }
  3458. $data_to_export[] = array(
  3459. 'group_id' => 'session-tokens',
  3460. 'group_label' => __( 'Session Tokens' ),
  3461. 'group_description' => __( 'User&#8217;s Session Tokens data.' ),
  3462. 'item_id' => "session-tokens-{$user->ID}-{$token_key}",
  3463. 'data' => $session_tokens_data_to_export,
  3464. );
  3465. }
  3466. }
  3467. return array(
  3468. 'data' => $data_to_export,
  3469. 'done' => true,
  3470. );
  3471. }
  3472. /**
  3473. * Updates log when privacy request is confirmed.
  3474. *
  3475. * @since 4.9.6
  3476. * @access private
  3477. *
  3478. * @param int $request_id ID of the request.
  3479. */
  3480. function _wp_privacy_account_request_confirmed( $request_id ) {
  3481. $request = wp_get_user_request( $request_id );
  3482. if ( ! $request ) {
  3483. return;
  3484. }
  3485. if ( ! in_array( $request->status, array( 'request-pending', 'request-failed' ), true ) ) {
  3486. return;
  3487. }
  3488. update_post_meta( $request_id, '_wp_user_request_confirmed_timestamp', time() );
  3489. wp_update_post(
  3490. array(
  3491. 'ID' => $request_id,
  3492. 'post_status' => 'request-confirmed',
  3493. )
  3494. );
  3495. }
  3496. /**
  3497. * Notifies the site administrator via email when a request is confirmed.
  3498. *
  3499. * Without this, the admin would have to manually check the site to see if any
  3500. * action was needed on their part yet.
  3501. *
  3502. * @since 4.9.6
  3503. *
  3504. * @param int $request_id The ID of the request.
  3505. */
  3506. function _wp_privacy_send_request_confirmation_notification( $request_id ) {
  3507. $request = wp_get_user_request( $request_id );
  3508. if ( ! is_a( $request, 'WP_User_Request' ) || 'request-confirmed' !== $request->status ) {
  3509. return;
  3510. }
  3511. $already_notified = (bool) get_post_meta( $request_id, '_wp_admin_notified', true );
  3512. if ( $already_notified ) {
  3513. return;
  3514. }
  3515. if ( 'export_personal_data' === $request->action_name ) {
  3516. $manage_url = admin_url( 'export-personal-data.php' );
  3517. } elseif ( 'remove_personal_data' === $request->action_name ) {
  3518. $manage_url = admin_url( 'erase-personal-data.php' );
  3519. }
  3520. $action_description = wp_user_request_action_description( $request->action_name );
  3521. /**
  3522. * Filters the recipient of the data request confirmation notification.
  3523. *
  3524. * In a Multisite environment, this will default to the email address of the
  3525. * network admin because, by default, single site admins do not have the
  3526. * capabilities required to process requests. Some networks may wish to
  3527. * delegate those capabilities to a single-site admin, or a dedicated person
  3528. * responsible for managing privacy requests.
  3529. *
  3530. * @since 4.9.6
  3531. *
  3532. * @param string $admin_email The email address of the notification recipient.
  3533. * @param WP_User_Request $request The request that is initiating the notification.
  3534. */
  3535. $admin_email = apply_filters( 'user_request_confirmed_email_to', get_site_option( 'admin_email' ), $request );
  3536. $email_data = array(
  3537. 'request' => $request,
  3538. 'user_email' => $request->email,
  3539. 'description' => $action_description,
  3540. 'manage_url' => $manage_url,
  3541. 'sitename' => wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES ),
  3542. 'siteurl' => home_url(),
  3543. 'admin_email' => $admin_email,
  3544. );
  3545. $subject = sprintf(
  3546. /* translators: Privacy data request confirmed notification email subject. 1: Site title, 2: Name of the confirmed action. */
  3547. __( '[%1$s] Action Confirmed: %2$s' ),
  3548. $email_data['sitename'],
  3549. $action_description
  3550. );
  3551. /**
  3552. * Filters the subject of the user request confirmation email.
  3553. *
  3554. * @since 4.9.8
  3555. *
  3556. * @param string $subject The email subject.
  3557. * @param string $sitename The name of the site.
  3558. * @param array $email_data {
  3559. * Data relating to the account action email.
  3560. *
  3561. * @type WP_User_Request $request User request object.
  3562. * @type string $user_email The email address confirming a request
  3563. * @type string $description Description of the action being performed so the user knows what the email is for.
  3564. * @type string $manage_url The link to click manage privacy requests of this type.
  3565. * @type string $sitename The site name sending the mail.
  3566. * @type string $siteurl The site URL sending the mail.
  3567. * @type string $admin_email The administrator email receiving the mail.
  3568. * }
  3569. */
  3570. $subject = apply_filters( 'user_request_confirmed_email_subject', $subject, $email_data['sitename'], $email_data );
  3571. /* translators: Do not translate SITENAME, USER_EMAIL, DESCRIPTION, MANAGE_URL, SITEURL; those are placeholders. */
  3572. $content = __(
  3573. 'Howdy,
  3574. A user data privacy request has been confirmed on ###SITENAME###:
  3575. User: ###USER_EMAIL###
  3576. Request: ###DESCRIPTION###
  3577. You can view and manage these data privacy requests here:
  3578. ###MANAGE_URL###
  3579. Regards,
  3580. All at ###SITENAME###
  3581. ###SITEURL###'
  3582. );
  3583. /**
  3584. * Filters the body of the user request confirmation email.
  3585. *
  3586. * The email is sent to an administrator when a user request is confirmed.
  3587. *
  3588. * The following strings have a special meaning and will get replaced dynamically:
  3589. *
  3590. * ###SITENAME### The name of the site.
  3591. * ###USER_EMAIL### The user email for the request.
  3592. * ###DESCRIPTION### Description of the action being performed so the user knows what the email is for.
  3593. * ###MANAGE_URL### The URL to manage requests.
  3594. * ###SITEURL### The URL to the site.
  3595. *
  3596. * @since 4.9.6
  3597. * @deprecated 5.8.0 Use {@see 'user_request_confirmed_email_content'} instead.
  3598. * For user erasure fulfillment email content
  3599. * use {@see 'user_erasure_fulfillment_email_content'} instead.
  3600. *
  3601. * @param string $content The email content.
  3602. * @param array $email_data {
  3603. * Data relating to the account action email.
  3604. *
  3605. * @type WP_User_Request $request User request object.
  3606. * @type string $user_email The email address confirming a request
  3607. * @type string $description Description of the action being performed
  3608. * so the user knows what the email is for.
  3609. * @type string $manage_url The link to click manage privacy requests of this type.
  3610. * @type string $sitename The site name sending the mail.
  3611. * @type string $siteurl The site URL sending the mail.
  3612. * @type string $admin_email The administrator email receiving the mail.
  3613. * }
  3614. */
  3615. $content = apply_filters_deprecated(
  3616. 'user_confirmed_action_email_content',
  3617. array( $content, $email_data ),
  3618. '5.8.0',
  3619. sprintf(
  3620. /* translators: 1 & 2: Deprecation replacement options. */
  3621. __( '%1$s or %2$s' ),
  3622. 'user_request_confirmed_email_content',
  3623. 'user_erasure_fulfillment_email_content'
  3624. )
  3625. );
  3626. /**
  3627. * Filters the body of the user request confirmation email.
  3628. *
  3629. * The email is sent to an administrator when a user request is confirmed.
  3630. * The following strings have a special meaning and will get replaced dynamically:
  3631. *
  3632. * ###SITENAME### The name of the site.
  3633. * ###USER_EMAIL### The user email for the request.
  3634. * ###DESCRIPTION### Description of the action being performed so the user knows what the email is for.
  3635. * ###MANAGE_URL### The URL to manage requests.
  3636. * ###SITEURL### The URL to the site.
  3637. *
  3638. * @since 5.8.0
  3639. *
  3640. * @param string $content The email content.
  3641. * @param array $email_data {
  3642. * Data relating to the account action email.
  3643. *
  3644. * @type WP_User_Request $request User request object.
  3645. * @type string $user_email The email address confirming a request
  3646. * @type string $description Description of the action being performed so the user knows what the email is for.
  3647. * @type string $manage_url The link to click manage privacy requests of this type.
  3648. * @type string $sitename The site name sending the mail.
  3649. * @type string $siteurl The site URL sending the mail.
  3650. * @type string $admin_email The administrator email receiving the mail.
  3651. * }
  3652. */
  3653. $content = apply_filters( 'user_request_confirmed_email_content', $content, $email_data );
  3654. $content = str_replace( '###SITENAME###', $email_data['sitename'], $content );
  3655. $content = str_replace( '###USER_EMAIL###', $email_data['user_email'], $content );
  3656. $content = str_replace( '###DESCRIPTION###', $email_data['description'], $content );
  3657. $content = str_replace( '###MANAGE_URL###', sanitize_url( $email_data['manage_url'] ), $content );
  3658. $content = str_replace( '###SITEURL###', sanitize_url( $email_data['siteurl'] ), $content );
  3659. $headers = '';
  3660. /**
  3661. * Filters the headers of the user request confirmation email.
  3662. *
  3663. * @since 5.4.0
  3664. *
  3665. * @param string|array $headers The email headers.
  3666. * @param string $subject The email subject.
  3667. * @param string $content The email content.
  3668. * @param int $request_id The request ID.
  3669. * @param array $email_data {
  3670. * Data relating to the account action email.
  3671. *
  3672. * @type WP_User_Request $request User request object.
  3673. * @type string $user_email The email address confirming a request
  3674. * @type string $description Description of the action being performed so the user knows what the email is for.
  3675. * @type string $manage_url The link to click manage privacy requests of this type.
  3676. * @type string $sitename The site name sending the mail.
  3677. * @type string $siteurl The site URL sending the mail.
  3678. * @type string $admin_email The administrator email receiving the mail.
  3679. * }
  3680. */
  3681. $headers = apply_filters( 'user_request_confirmed_email_headers', $headers, $subject, $content, $request_id, $email_data );
  3682. $email_sent = wp_mail( $email_data['admin_email'], $subject, $content, $headers );
  3683. if ( $email_sent ) {
  3684. update_post_meta( $request_id, '_wp_admin_notified', true );
  3685. }
  3686. }
  3687. /**
  3688. * Notifies the user when their erasure request is fulfilled.
  3689. *
  3690. * Without this, the user would never know if their data was actually erased.
  3691. *
  3692. * @since 4.9.6
  3693. *
  3694. * @param int $request_id The privacy request post ID associated with this request.
  3695. */
  3696. function _wp_privacy_send_erasure_fulfillment_notification( $request_id ) {
  3697. $request = wp_get_user_request( $request_id );
  3698. if ( ! is_a( $request, 'WP_User_Request' ) || 'request-completed' !== $request->status ) {
  3699. return;
  3700. }
  3701. $already_notified = (bool) get_post_meta( $request_id, '_wp_user_notified', true );
  3702. if ( $already_notified ) {
  3703. return;
  3704. }
  3705. // Localize message content for user; fallback to site default for visitors.
  3706. if ( ! empty( $request->user_id ) ) {
  3707. $locale = get_user_locale( $request->user_id );
  3708. } else {
  3709. $locale = get_locale();
  3710. }
  3711. $switched_locale = switch_to_locale( $locale );
  3712. /**
  3713. * Filters the recipient of the data erasure fulfillment notification.
  3714. *
  3715. * @since 4.9.6
  3716. *
  3717. * @param string $user_email The email address of the notification recipient.
  3718. * @param WP_User_Request $request The request that is initiating the notification.
  3719. */
  3720. $user_email = apply_filters( 'user_erasure_fulfillment_email_to', $request->email, $request );
  3721. $email_data = array(
  3722. 'request' => $request,
  3723. 'message_recipient' => $user_email,
  3724. 'privacy_policy_url' => get_privacy_policy_url(),
  3725. 'sitename' => wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES ),
  3726. 'siteurl' => home_url(),
  3727. );
  3728. $subject = sprintf(
  3729. /* translators: Erasure request fulfilled notification email subject. %s: Site title. */
  3730. __( '[%s] Erasure Request Fulfilled' ),
  3731. $email_data['sitename']
  3732. );
  3733. /**
  3734. * Filters the subject of the email sent when an erasure request is completed.
  3735. *
  3736. * @since 4.9.8
  3737. * @deprecated 5.8.0 Use {@see 'user_erasure_fulfillment_email_subject'} instead.
  3738. *
  3739. * @param string $subject The email subject.
  3740. * @param string $sitename The name of the site.
  3741. * @param array $email_data {
  3742. * Data relating to the account action email.
  3743. *
  3744. * @type WP_User_Request $request User request object.
  3745. * @type string $message_recipient The address that the email will be sent to. Defaults
  3746. * to the value of `$request->email`, but can be changed
  3747. * by the `user_erasure_fulfillment_email_to` filter.
  3748. * @type string $privacy_policy_url Privacy policy URL.
  3749. * @type string $sitename The site name sending the mail.
  3750. * @type string $siteurl The site URL sending the mail.
  3751. * }
  3752. */
  3753. $subject = apply_filters_deprecated(
  3754. 'user_erasure_complete_email_subject',
  3755. array( $subject, $email_data['sitename'], $email_data ),
  3756. '5.8.0',
  3757. 'user_erasure_fulfillment_email_subject'
  3758. );
  3759. /**
  3760. * Filters the subject of the email sent when an erasure request is completed.
  3761. *
  3762. * @since 5.8.0
  3763. *
  3764. * @param string $subject The email subject.
  3765. * @param string $sitename The name of the site.
  3766. * @param array $email_data {
  3767. * Data relating to the account action email.
  3768. *
  3769. * @type WP_User_Request $request User request object.
  3770. * @type string $message_recipient The address that the email will be sent to. Defaults
  3771. * to the value of `$request->email`, but can be changed
  3772. * by the `user_erasure_fulfillment_email_to` filter.
  3773. * @type string $privacy_policy_url Privacy policy URL.
  3774. * @type string $sitename The site name sending the mail.
  3775. * @type string $siteurl The site URL sending the mail.
  3776. * }
  3777. */
  3778. $subject = apply_filters( 'user_erasure_fulfillment_email_subject', $subject, $email_data['sitename'], $email_data );
  3779. /* translators: Do not translate SITENAME, SITEURL; those are placeholders. */
  3780. $content = __(
  3781. 'Howdy,
  3782. Your request to erase your personal data on ###SITENAME### has been completed.
  3783. If you have any follow-up questions or concerns, please contact the site administrator.
  3784. Regards,
  3785. All at ###SITENAME###
  3786. ###SITEURL###'
  3787. );
  3788. if ( ! empty( $email_data['privacy_policy_url'] ) ) {
  3789. /* translators: Do not translate SITENAME, SITEURL, PRIVACY_POLICY_URL; those are placeholders. */
  3790. $content = __(
  3791. 'Howdy,
  3792. Your request to erase your personal data on ###SITENAME### has been completed.
  3793. If you have any follow-up questions or concerns, please contact the site administrator.
  3794. For more information, you can also read our privacy policy: ###PRIVACY_POLICY_URL###
  3795. Regards,
  3796. All at ###SITENAME###
  3797. ###SITEURL###'
  3798. );
  3799. }
  3800. /**
  3801. * Filters the body of the data erasure fulfillment notification.
  3802. *
  3803. * The email is sent to a user when their data erasure request is fulfilled
  3804. * by an administrator.
  3805. *
  3806. * The following strings have a special meaning and will get replaced dynamically:
  3807. *
  3808. * ###SITENAME### The name of the site.
  3809. * ###PRIVACY_POLICY_URL### Privacy policy page URL.
  3810. * ###SITEURL### The URL to the site.
  3811. *
  3812. * @since 4.9.6
  3813. * @deprecated 5.8.0 Use {@see 'user_erasure_fulfillment_email_content'} instead.
  3814. * For user request confirmation email content
  3815. * use {@see 'user_request_confirmed_email_content'} instead.
  3816. *
  3817. * @param string $content The email content.
  3818. * @param array $email_data {
  3819. * Data relating to the account action email.
  3820. *
  3821. * @type WP_User_Request $request User request object.
  3822. * @type string $message_recipient The address that the email will be sent to. Defaults
  3823. * to the value of `$request->email`, but can be changed
  3824. * by the `user_erasure_fulfillment_email_to` filter.
  3825. * @type string $privacy_policy_url Privacy policy URL.
  3826. * @type string $sitename The site name sending the mail.
  3827. * @type string $siteurl The site URL sending the mail.
  3828. * }
  3829. */
  3830. $content = apply_filters_deprecated(
  3831. 'user_confirmed_action_email_content',
  3832. array( $content, $email_data ),
  3833. '5.8.0',
  3834. sprintf(
  3835. /* translators: 1 & 2: Deprecation replacement options. */
  3836. __( '%1$s or %2$s' ),
  3837. 'user_erasure_fulfillment_email_content',
  3838. 'user_request_confirmed_email_content'
  3839. )
  3840. );
  3841. /**
  3842. * Filters the body of the data erasure fulfillment notification.
  3843. *
  3844. * The email is sent to a user when their data erasure request is fulfilled
  3845. * by an administrator.
  3846. *
  3847. * The following strings have a special meaning and will get replaced dynamically:
  3848. *
  3849. * ###SITENAME### The name of the site.
  3850. * ###PRIVACY_POLICY_URL### Privacy policy page URL.
  3851. * ###SITEURL### The URL to the site.
  3852. *
  3853. * @since 5.8.0
  3854. *
  3855. * @param string $content The email content.
  3856. * @param array $email_data {
  3857. * Data relating to the account action email.
  3858. *
  3859. * @type WP_User_Request $request User request object.
  3860. * @type string $message_recipient The address that the email will be sent to. Defaults
  3861. * to the value of `$request->email`, but can be changed
  3862. * by the `user_erasure_fulfillment_email_to` filter.
  3863. * @type string $privacy_policy_url Privacy policy URL.
  3864. * @type string $sitename The site name sending the mail.
  3865. * @type string $siteurl The site URL sending the mail.
  3866. * }
  3867. */
  3868. $content = apply_filters( 'user_erasure_fulfillment_email_content', $content, $email_data );
  3869. $content = str_replace( '###SITENAME###', $email_data['sitename'], $content );
  3870. $content = str_replace( '###PRIVACY_POLICY_URL###', $email_data['privacy_policy_url'], $content );
  3871. $content = str_replace( '###SITEURL###', sanitize_url( $email_data['siteurl'] ), $content );
  3872. $headers = '';
  3873. /**
  3874. * Filters the headers of the data erasure fulfillment notification.
  3875. *
  3876. * @since 5.4.0
  3877. * @deprecated 5.8.0 Use {@see 'user_erasure_fulfillment_email_headers'} instead.
  3878. *
  3879. * @param string|array $headers The email headers.
  3880. * @param string $subject The email subject.
  3881. * @param string $content The email content.
  3882. * @param int $request_id The request ID.
  3883. * @param array $email_data {
  3884. * Data relating to the account action email.
  3885. *
  3886. * @type WP_User_Request $request User request object.
  3887. * @type string $message_recipient The address that the email will be sent to. Defaults
  3888. * to the value of `$request->email`, but can be changed
  3889. * by the `user_erasure_fulfillment_email_to` filter.
  3890. * @type string $privacy_policy_url Privacy policy URL.
  3891. * @type string $sitename The site name sending the mail.
  3892. * @type string $siteurl The site URL sending the mail.
  3893. * }
  3894. */
  3895. $headers = apply_filters_deprecated(
  3896. 'user_erasure_complete_email_headers',
  3897. array( $headers, $subject, $content, $request_id, $email_data ),
  3898. '5.8.0',
  3899. 'user_erasure_fulfillment_email_headers'
  3900. );
  3901. /**
  3902. * Filters the headers of the data erasure fulfillment notification.
  3903. *
  3904. * @since 5.8.0
  3905. *
  3906. * @param string|array $headers The email headers.
  3907. * @param string $subject The email subject.
  3908. * @param string $content The email content.
  3909. * @param int $request_id The request ID.
  3910. * @param array $email_data {
  3911. * Data relating to the account action email.
  3912. *
  3913. * @type WP_User_Request $request User request object.
  3914. * @type string $message_recipient The address that the email will be sent to. Defaults
  3915. * to the value of `$request->email`, but can be changed
  3916. * by the `user_erasure_fulfillment_email_to` filter.
  3917. * @type string $privacy_policy_url Privacy policy URL.
  3918. * @type string $sitename The site name sending the mail.
  3919. * @type string $siteurl The site URL sending the mail.
  3920. * }
  3921. */
  3922. $headers = apply_filters( 'user_erasure_fulfillment_email_headers', $headers, $subject, $content, $request_id, $email_data );
  3923. $email_sent = wp_mail( $user_email, $subject, $content, $headers );
  3924. if ( $switched_locale ) {
  3925. restore_previous_locale();
  3926. }
  3927. if ( $email_sent ) {
  3928. update_post_meta( $request_id, '_wp_user_notified', true );
  3929. }
  3930. }
  3931. /**
  3932. * Returns request confirmation message HTML.
  3933. *
  3934. * @since 4.9.6
  3935. * @access private
  3936. *
  3937. * @param int $request_id The request ID being confirmed.
  3938. * @return string The confirmation message.
  3939. */
  3940. function _wp_privacy_account_request_confirmed_message( $request_id ) {
  3941. $request = wp_get_user_request( $request_id );
  3942. $message = '<p class="success">' . __( 'Action has been confirmed.' ) . '</p>';
  3943. $message .= '<p>' . __( 'The site administrator has been notified and will fulfill your request as soon as possible.' ) . '</p>';
  3944. if ( $request && in_array( $request->action_name, _wp_privacy_action_request_types(), true ) ) {
  3945. if ( 'export_personal_data' === $request->action_name ) {
  3946. $message = '<p class="success">' . __( 'Thanks for confirming your export request.' ) . '</p>';
  3947. $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>';
  3948. } elseif ( 'remove_personal_data' === $request->action_name ) {
  3949. $message = '<p class="success">' . __( 'Thanks for confirming your erasure request.' ) . '</p>';
  3950. $message .= '<p>' . __( 'The site administrator has been notified. You will receive an email confirmation when they erase your data.' ) . '</p>';
  3951. }
  3952. }
  3953. /**
  3954. * Filters the message displayed to a user when they confirm a data request.
  3955. *
  3956. * @since 4.9.6
  3957. *
  3958. * @param string $message The message to the user.
  3959. * @param int $request_id The ID of the request being confirmed.
  3960. */
  3961. $message = apply_filters( 'user_request_action_confirmed_message', $message, $request_id );
  3962. return $message;
  3963. }
  3964. /**
  3965. * Creates and logs a user request to perform a specific action.
  3966. *
  3967. * Requests are stored inside a post type named `user_request` since they can apply to both
  3968. * users on the site, or guests without a user account.
  3969. *
  3970. * @since 4.9.6
  3971. * @since 5.7.0 Added the `$status` parameter.
  3972. *
  3973. * @param string $email_address User email address. This can be the address of a registered
  3974. * or non-registered user.
  3975. * @param string $action_name Name of the action that is being confirmed. Required.
  3976. * @param array $request_data Misc data you want to send with the verification request and pass
  3977. * to the actions once the request is confirmed.
  3978. * @param string $status Optional request status (pending or confirmed). Default 'pending'.
  3979. * @return int|WP_Error Returns the request ID if successful, or a WP_Error object on failure.
  3980. */
  3981. function wp_create_user_request( $email_address = '', $action_name = '', $request_data = array(), $status = 'pending' ) {
  3982. $email_address = sanitize_email( $email_address );
  3983. $action_name = sanitize_key( $action_name );
  3984. if ( ! is_email( $email_address ) ) {
  3985. return new WP_Error( 'invalid_email', __( 'Invalid email address.' ) );
  3986. }
  3987. if ( ! in_array( $action_name, _wp_privacy_action_request_types(), true ) ) {
  3988. return new WP_Error( 'invalid_action', __( 'Invalid action name.' ) );
  3989. }
  3990. if ( ! in_array( $status, array( 'pending', 'confirmed' ), true ) ) {
  3991. return new WP_Error( 'invalid_status', __( 'Invalid request status.' ) );
  3992. }
  3993. $user = get_user_by( 'email', $email_address );
  3994. $user_id = $user && ! is_wp_error( $user ) ? $user->ID : 0;
  3995. // Check for duplicates.
  3996. $requests_query = new WP_Query(
  3997. array(
  3998. 'post_type' => 'user_request',
  3999. 'post_name__in' => array( $action_name ), // Action name stored in post_name column.
  4000. 'title' => $email_address, // Email address stored in post_title column.
  4001. 'post_status' => array(
  4002. 'request-pending',
  4003. 'request-confirmed',
  4004. ),
  4005. 'fields' => 'ids',
  4006. )
  4007. );
  4008. if ( $requests_query->found_posts ) {
  4009. return new WP_Error( 'duplicate_request', __( 'An incomplete personal data request for this email address already exists.' ) );
  4010. }
  4011. $request_id = wp_insert_post(
  4012. array(
  4013. 'post_author' => $user_id,
  4014. 'post_name' => $action_name,
  4015. 'post_title' => $email_address,
  4016. 'post_content' => wp_json_encode( $request_data ),
  4017. 'post_status' => 'request-' . $status,
  4018. 'post_type' => 'user_request',
  4019. 'post_date' => current_time( 'mysql', false ),
  4020. 'post_date_gmt' => current_time( 'mysql', true ),
  4021. ),
  4022. true
  4023. );
  4024. return $request_id;
  4025. }
  4026. /**
  4027. * Gets action description from the name and return a string.
  4028. *
  4029. * @since 4.9.6
  4030. *
  4031. * @param string $action_name Action name of the request.
  4032. * @return string Human readable action name.
  4033. */
  4034. function wp_user_request_action_description( $action_name ) {
  4035. switch ( $action_name ) {
  4036. case 'export_personal_data':
  4037. $description = __( 'Export Personal Data' );
  4038. break;
  4039. case 'remove_personal_data':
  4040. $description = __( 'Erase Personal Data' );
  4041. break;
  4042. default:
  4043. /* translators: %s: Action name. */
  4044. $description = sprintf( __( 'Confirm the "%s" action' ), $action_name );
  4045. break;
  4046. }
  4047. /**
  4048. * Filters the user action description.
  4049. *
  4050. * @since 4.9.6
  4051. *
  4052. * @param string $description The default description.
  4053. * @param string $action_name The name of the request.
  4054. */
  4055. return apply_filters( 'user_request_action_description', $description, $action_name );
  4056. }
  4057. /**
  4058. * Send a confirmation request email to confirm an action.
  4059. *
  4060. * If the request is not already pending, it will be updated.
  4061. *
  4062. * @since 4.9.6
  4063. *
  4064. * @param string $request_id ID of the request created via wp_create_user_request().
  4065. * @return true|WP_Error True on success, `WP_Error` on failure.
  4066. */
  4067. function wp_send_user_request( $request_id ) {
  4068. $request_id = absint( $request_id );
  4069. $request = wp_get_user_request( $request_id );
  4070. if ( ! $request ) {
  4071. return new WP_Error( 'invalid_request', __( 'Invalid personal data request.' ) );
  4072. }
  4073. // Localize message content for user; fallback to site default for visitors.
  4074. if ( ! empty( $request->user_id ) ) {
  4075. $locale = get_user_locale( $request->user_id );
  4076. } else {
  4077. $locale = get_locale();
  4078. }
  4079. $switched_locale = switch_to_locale( $locale );
  4080. $email_data = array(
  4081. 'request' => $request,
  4082. 'email' => $request->email,
  4083. 'description' => wp_user_request_action_description( $request->action_name ),
  4084. 'confirm_url' => add_query_arg(
  4085. array(
  4086. 'action' => 'confirmaction',
  4087. 'request_id' => $request_id,
  4088. 'confirm_key' => wp_generate_user_request_key( $request_id ),
  4089. ),
  4090. wp_login_url()
  4091. ),
  4092. 'sitename' => wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES ),
  4093. 'siteurl' => home_url(),
  4094. );
  4095. /* translators: Confirm privacy data request notification email subject. 1: Site title, 2: Name of the action. */
  4096. $subject = sprintf( __( '[%1$s] Confirm Action: %2$s' ), $email_data['sitename'], $email_data['description'] );
  4097. /**
  4098. * Filters the subject of the email sent when an account action is attempted.
  4099. *
  4100. * @since 4.9.6
  4101. *
  4102. * @param string $subject The email subject.
  4103. * @param string $sitename The name of the site.
  4104. * @param array $email_data {
  4105. * Data relating to the account action email.
  4106. *
  4107. * @type WP_User_Request $request User request object.
  4108. * @type string $email The email address this is being sent to.
  4109. * @type string $description Description of the action being performed so the user knows what the email is for.
  4110. * @type string $confirm_url The link to click on to confirm the account action.
  4111. * @type string $sitename The site name sending the mail.
  4112. * @type string $siteurl The site URL sending the mail.
  4113. * }
  4114. */
  4115. $subject = apply_filters( 'user_request_action_email_subject', $subject, $email_data['sitename'], $email_data );
  4116. /* translators: Do not translate DESCRIPTION, CONFIRM_URL, SITENAME, SITEURL: those are placeholders. */
  4117. $content = __(
  4118. 'Howdy,
  4119. A request has been made to perform the following action on your account:
  4120. ###DESCRIPTION###
  4121. To confirm this, please click on the following link:
  4122. ###CONFIRM_URL###
  4123. You can safely ignore and delete this email if you do not want to
  4124. take this action.
  4125. Regards,
  4126. All at ###SITENAME###
  4127. ###SITEURL###'
  4128. );
  4129. /**
  4130. * Filters the text of the email sent when an account action is attempted.
  4131. *
  4132. * The following strings have a special meaning and will get replaced dynamically:
  4133. *
  4134. * ###DESCRIPTION### Description of the action being performed so the user knows what the email is for.
  4135. * ###CONFIRM_URL### The link to click on to confirm the account action.
  4136. * ###SITENAME### The name of the site.
  4137. * ###SITEURL### The URL to the site.
  4138. *
  4139. * @since 4.9.6
  4140. *
  4141. * @param string $content Text in the email.
  4142. * @param array $email_data {
  4143. * Data relating to the account action email.
  4144. *
  4145. * @type WP_User_Request $request User request object.
  4146. * @type string $email The email address this is being sent to.
  4147. * @type string $description Description of the action being performed so the user knows what the email is for.
  4148. * @type string $confirm_url The link to click on to confirm the account action.
  4149. * @type string $sitename The site name sending the mail.
  4150. * @type string $siteurl The site URL sending the mail.
  4151. * }
  4152. */
  4153. $content = apply_filters( 'user_request_action_email_content', $content, $email_data );
  4154. $content = str_replace( '###DESCRIPTION###', $email_data['description'], $content );
  4155. $content = str_replace( '###CONFIRM_URL###', sanitize_url( $email_data['confirm_url'] ), $content );
  4156. $content = str_replace( '###EMAIL###', $email_data['email'], $content );
  4157. $content = str_replace( '###SITENAME###', $email_data['sitename'], $content );
  4158. $content = str_replace( '###SITEURL###', sanitize_url( $email_data['siteurl'] ), $content );
  4159. $headers = '';
  4160. /**
  4161. * Filters the headers of the email sent when an account action is attempted.
  4162. *
  4163. * @since 5.4.0
  4164. *
  4165. * @param string|array $headers The email headers.
  4166. * @param string $subject The email subject.
  4167. * @param string $content The email content.
  4168. * @param int $request_id The request ID.
  4169. * @param array $email_data {
  4170. * Data relating to the account action email.
  4171. *
  4172. * @type WP_User_Request $request User request object.
  4173. * @type string $email The email address this is being sent to.
  4174. * @type string $description Description of the action being performed so the user knows what the email is for.
  4175. * @type string $confirm_url The link to click on to confirm the account action.
  4176. * @type string $sitename The site name sending the mail.
  4177. * @type string $siteurl The site URL sending the mail.
  4178. * }
  4179. */
  4180. $headers = apply_filters( 'user_request_action_email_headers', $headers, $subject, $content, $request_id, $email_data );
  4181. $email_sent = wp_mail( $email_data['email'], $subject, $content, $headers );
  4182. if ( $switched_locale ) {
  4183. restore_previous_locale();
  4184. }
  4185. if ( ! $email_sent ) {
  4186. return new WP_Error( 'privacy_email_error', __( 'Unable to send personal data export confirmation email.' ) );
  4187. }
  4188. return true;
  4189. }
  4190. /**
  4191. * Returns a confirmation key for a user action and stores the hashed version for future comparison.
  4192. *
  4193. * @since 4.9.6
  4194. *
  4195. * @param int $request_id Request ID.
  4196. * @return string Confirmation key.
  4197. */
  4198. function wp_generate_user_request_key( $request_id ) {
  4199. global $wp_hasher;
  4200. // Generate something random for a confirmation key.
  4201. $key = wp_generate_password( 20, false );
  4202. // Return the key, hashed.
  4203. if ( empty( $wp_hasher ) ) {
  4204. require_once ABSPATH . WPINC . '/class-phpass.php';
  4205. $wp_hasher = new PasswordHash( 8, true );
  4206. }
  4207. wp_update_post(
  4208. array(
  4209. 'ID' => $request_id,
  4210. 'post_status' => 'request-pending',
  4211. 'post_password' => $wp_hasher->HashPassword( $key ),
  4212. )
  4213. );
  4214. return $key;
  4215. }
  4216. /**
  4217. * Validates a user request by comparing the key with the request's key.
  4218. *
  4219. * @since 4.9.6
  4220. *
  4221. * @param string $request_id ID of the request being confirmed.
  4222. * @param string $key Provided key to validate.
  4223. * @return true|WP_Error True on success, WP_Error on failure.
  4224. */
  4225. function wp_validate_user_request_key( $request_id, $key ) {
  4226. global $wp_hasher;
  4227. $request_id = absint( $request_id );
  4228. $request = wp_get_user_request( $request_id );
  4229. $saved_key = $request->confirm_key;
  4230. $key_request_time = $request->modified_timestamp;
  4231. if ( ! $request || ! $saved_key || ! $key_request_time ) {
  4232. return new WP_Error( 'invalid_request', __( 'Invalid personal data request.' ) );
  4233. }
  4234. if ( ! in_array( $request->status, array( 'request-pending', 'request-failed' ), true ) ) {
  4235. return new WP_Error( 'expired_request', __( 'This personal data request has expired.' ) );
  4236. }
  4237. if ( empty( $key ) ) {
  4238. return new WP_Error( 'missing_key', __( 'The confirmation key is missing from this personal data request.' ) );
  4239. }
  4240. if ( empty( $wp_hasher ) ) {
  4241. require_once ABSPATH . WPINC . '/class-phpass.php';
  4242. $wp_hasher = new PasswordHash( 8, true );
  4243. }
  4244. /**
  4245. * Filters the expiration time of confirm keys.
  4246. *
  4247. * @since 4.9.6
  4248. *
  4249. * @param int $expiration The expiration time in seconds.
  4250. */
  4251. $expiration_duration = (int) apply_filters( 'user_request_key_expiration', DAY_IN_SECONDS );
  4252. $expiration_time = $key_request_time + $expiration_duration;
  4253. if ( ! $wp_hasher->CheckPassword( $key, $saved_key ) ) {
  4254. return new WP_Error( 'invalid_key', __( 'The confirmation key is invalid for this personal data request.' ) );
  4255. }
  4256. if ( ! $expiration_time || time() > $expiration_time ) {
  4257. return new WP_Error( 'expired_key', __( 'The confirmation key has expired for this personal data request.' ) );
  4258. }
  4259. return true;
  4260. }
  4261. /**
  4262. * Returns the user request object for the specified request ID.
  4263. *
  4264. * @since 4.9.6
  4265. *
  4266. * @param int $request_id The ID of the user request.
  4267. * @return WP_User_Request|false
  4268. */
  4269. function wp_get_user_request( $request_id ) {
  4270. $request_id = absint( $request_id );
  4271. $post = get_post( $request_id );
  4272. if ( ! $post || 'user_request' !== $post->post_type ) {
  4273. return false;
  4274. }
  4275. return new WP_User_Request( $post );
  4276. }
  4277. /**
  4278. * Checks if Application Passwords is supported.
  4279. *
  4280. * Application Passwords is supported only by sites using SSL or local environments
  4281. * but may be made available using the {@see 'wp_is_application_passwords_available'} filter.
  4282. *
  4283. * @since 5.9.0
  4284. *
  4285. * @return bool
  4286. */
  4287. function wp_is_application_passwords_supported() {
  4288. return is_ssl() || 'local' === wp_get_environment_type();
  4289. }
  4290. /**
  4291. * Checks if Application Passwords is globally available.
  4292. *
  4293. * By default, Application Passwords is available to all sites using SSL or to local environments.
  4294. * Use the {@see 'wp_is_application_passwords_available'} filter to adjust its availability.
  4295. *
  4296. * @since 5.6.0
  4297. *
  4298. * @return bool
  4299. */
  4300. function wp_is_application_passwords_available() {
  4301. /**
  4302. * Filters whether Application Passwords is available.
  4303. *
  4304. * @since 5.6.0
  4305. *
  4306. * @param bool $available True if available, false otherwise.
  4307. */
  4308. return apply_filters( 'wp_is_application_passwords_available', wp_is_application_passwords_supported() );
  4309. }
  4310. /**
  4311. * Checks if Application Passwords is available for a specific user.
  4312. *
  4313. * By default all users can use Application Passwords. Use {@see 'wp_is_application_passwords_available_for_user'}
  4314. * to restrict availability to certain users.
  4315. *
  4316. * @since 5.6.0
  4317. *
  4318. * @param int|WP_User $user The user to check.
  4319. * @return bool
  4320. */
  4321. function wp_is_application_passwords_available_for_user( $user ) {
  4322. if ( ! wp_is_application_passwords_available() ) {
  4323. return false;
  4324. }
  4325. if ( ! is_object( $user ) ) {
  4326. $user = get_userdata( $user );
  4327. }
  4328. if ( ! $user || ! $user->exists() ) {
  4329. return false;
  4330. }
  4331. /**
  4332. * Filters whether Application Passwords is available for a specific user.
  4333. *
  4334. * @since 5.6.0
  4335. *
  4336. * @param bool $available True if available, false otherwise.
  4337. * @param WP_User $user The user to check.
  4338. */
  4339. return apply_filters( 'wp_is_application_passwords_available_for_user', true, $user );
  4340. }
  4341. /**
  4342. * Registers the user meta property for persisted preferences.
  4343. *
  4344. * This property is used to store user preferences across page reloads and is
  4345. * currently used by the block editor for preferences like 'fullscreenMode' and
  4346. * 'fixedToolbar'.
  4347. *
  4348. * @since 6.1.0
  4349. * @access private
  4350. *
  4351. * @global wpdb $wpdb WordPress database abstraction object.
  4352. */
  4353. function wp_register_persisted_preferences_meta() {
  4354. /*
  4355. * Create a meta key that incorporates the blog prefix so that each site
  4356. * on a multisite can have distinct user preferences.
  4357. */
  4358. global $wpdb;
  4359. $meta_key = $wpdb->get_blog_prefix() . 'persisted_preferences';
  4360. register_meta(
  4361. 'user',
  4362. $meta_key,
  4363. array(
  4364. 'type' => 'object',
  4365. 'single' => true,
  4366. 'show_in_rest' => array(
  4367. 'name' => 'persisted_preferences',
  4368. 'type' => 'object',
  4369. 'schema' => array(
  4370. 'type' => 'object',
  4371. 'context' => array( 'edit' ),
  4372. 'properties' => array(
  4373. '_modified' => array(
  4374. 'description' => __( 'The date and time the preferences were updated.' ),
  4375. 'type' => 'string',
  4376. 'format' => 'date-time',
  4377. 'readonly' => false,
  4378. ),
  4379. ),
  4380. 'additionalProperties' => true,
  4381. ),
  4382. ),
  4383. )
  4384. );
  4385. }