user.php 118 KB

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