pluggable.php 90 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640
  1. <?php
  2. /**
  3. * These functions can be replaced via plugins. If plugins do not redefine these
  4. * functions, then these will be used instead.
  5. *
  6. * @package WordPress
  7. */
  8. if ( !function_exists('wp_set_current_user') ) :
  9. /**
  10. * Changes the current user by ID or name.
  11. *
  12. * Set $id to null and specify a name if you do not know a user's ID.
  13. *
  14. * Some WordPress functionality is based on the current user and not based on
  15. * the signed in user. Therefore, it opens the ability to edit and perform
  16. * actions on users who aren't signed in.
  17. *
  18. * @since 2.0.3
  19. * @global WP_User $current_user The current user object which holds the user data.
  20. *
  21. * @param int $id User ID
  22. * @param string $name User's username
  23. * @return WP_User Current user User object
  24. */
  25. function wp_set_current_user($id, $name = '') {
  26. global $current_user;
  27. // If `$id` matches the user who's already current, there's nothing to do.
  28. if ( isset( $current_user )
  29. && ( $current_user instanceof WP_User )
  30. && ( $id == $current_user->ID )
  31. && ( null !== $id )
  32. ) {
  33. return $current_user;
  34. }
  35. $current_user = new WP_User( $id, $name );
  36. setup_userdata( $current_user->ID );
  37. /**
  38. * Fires after the current user is set.
  39. *
  40. * @since 2.0.1
  41. */
  42. do_action( 'set_current_user' );
  43. return $current_user;
  44. }
  45. endif;
  46. if ( !function_exists('wp_get_current_user') ) :
  47. /**
  48. * Retrieve the current user object.
  49. *
  50. * Will set the current user, if the current user is not set. The current user
  51. * will be set to the logged-in person. If no user is logged-in, then it will
  52. * set the current user to 0, which is invalid and won't have any permissions.
  53. *
  54. * @since 2.0.3
  55. *
  56. * @see _wp_get_current_user()
  57. * @global WP_User $current_user Checks if the current user is set.
  58. *
  59. * @return WP_User Current WP_User instance.
  60. */
  61. function wp_get_current_user() {
  62. return _wp_get_current_user();
  63. }
  64. endif;
  65. if ( !function_exists('get_userdata') ) :
  66. /**
  67. * Retrieve user info by user ID.
  68. *
  69. * @since 0.71
  70. *
  71. * @param int $user_id User ID
  72. * @return WP_User|false WP_User object on success, false on failure.
  73. */
  74. function get_userdata( $user_id ) {
  75. return get_user_by( 'id', $user_id );
  76. }
  77. endif;
  78. if ( !function_exists('get_user_by') ) :
  79. /**
  80. * Retrieve user info by a given field
  81. *
  82. * @since 2.8.0
  83. * @since 4.4.0 Added 'ID' as an alias of 'id' for the `$field` parameter.
  84. *
  85. * @param string $field The field to retrieve the user with. id | ID | slug | email | login.
  86. * @param int|string $value A value for $field. A user ID, slug, email address, or login name.
  87. * @return WP_User|false WP_User object on success, false on failure.
  88. */
  89. function get_user_by( $field, $value ) {
  90. $userdata = WP_User::get_data_by( $field, $value );
  91. if ( !$userdata )
  92. return false;
  93. $user = new WP_User;
  94. $user->init( $userdata );
  95. return $user;
  96. }
  97. endif;
  98. if ( !function_exists('cache_users') ) :
  99. /**
  100. * Retrieve info for user lists to prevent multiple queries by get_userdata()
  101. *
  102. * @since 3.0.0
  103. *
  104. * @global wpdb $wpdb WordPress database abstraction object.
  105. *
  106. * @param array $user_ids User ID numbers list
  107. */
  108. function cache_users( $user_ids ) {
  109. global $wpdb;
  110. $clean = _get_non_cached_ids( $user_ids, 'users' );
  111. if ( empty( $clean ) )
  112. return;
  113. $list = implode( ',', $clean );
  114. $users = $wpdb->get_results( "SELECT * FROM $wpdb->users WHERE ID IN ($list)" );
  115. $ids = array();
  116. foreach ( $users as $user ) {
  117. update_user_caches( $user );
  118. $ids[] = $user->ID;
  119. }
  120. update_meta_cache( 'user', $ids );
  121. }
  122. endif;
  123. if ( !function_exists( 'wp_mail' ) ) :
  124. /**
  125. * Send mail, similar to PHP's mail
  126. *
  127. * A true return value does not automatically mean that the user received the
  128. * email successfully. It just only means that the method used was able to
  129. * process the request without any errors.
  130. *
  131. * Using the two 'wp_mail_from' and 'wp_mail_from_name' hooks allow from
  132. * creating a from address like 'Name <email@address.com>' when both are set. If
  133. * just 'wp_mail_from' is set, then just the email address will be used with no
  134. * name.
  135. *
  136. * The default content type is 'text/plain' which does not allow using HTML.
  137. * However, you can set the content type of the email by using the
  138. * {@see 'wp_mail_content_type'} filter.
  139. *
  140. * The default charset is based on the charset used on the blog. The charset can
  141. * be set using the {@see 'wp_mail_charset'} filter.
  142. *
  143. * @since 1.2.1
  144. *
  145. * @global PHPMailer $phpmailer
  146. *
  147. * @param string|array $to Array or comma-separated list of email addresses to send message.
  148. * @param string $subject Email subject
  149. * @param string $message Message contents
  150. * @param string|array $headers Optional. Additional headers.
  151. * @param string|array $attachments Optional. Files to attach.
  152. * @return bool Whether the email contents were sent successfully.
  153. */
  154. function wp_mail( $to, $subject, $message, $headers = '', $attachments = array() ) {
  155. // Compact the input, apply the filters, and extract them back out
  156. /**
  157. * Filters the wp_mail() arguments.
  158. *
  159. * @since 2.2.0
  160. *
  161. * @param array $args A compacted array of wp_mail() arguments, including the "to" email,
  162. * subject, message, headers, and attachments values.
  163. */
  164. $atts = apply_filters( 'wp_mail', compact( 'to', 'subject', 'message', 'headers', 'attachments' ) );
  165. if ( isset( $atts['to'] ) ) {
  166. $to = $atts['to'];
  167. }
  168. if ( !is_array( $to ) ) {
  169. $to = explode( ',', $to );
  170. }
  171. if ( isset( $atts['subject'] ) ) {
  172. $subject = $atts['subject'];
  173. }
  174. if ( isset( $atts['message'] ) ) {
  175. $message = $atts['message'];
  176. }
  177. if ( isset( $atts['headers'] ) ) {
  178. $headers = $atts['headers'];
  179. }
  180. if ( isset( $atts['attachments'] ) ) {
  181. $attachments = $atts['attachments'];
  182. }
  183. if ( ! is_array( $attachments ) ) {
  184. $attachments = explode( "\n", str_replace( "\r\n", "\n", $attachments ) );
  185. }
  186. global $phpmailer;
  187. // (Re)create it, if it's gone missing
  188. if ( ! ( $phpmailer instanceof PHPMailer ) ) {
  189. require_once ABSPATH . WPINC . '/class-phpmailer.php';
  190. require_once ABSPATH . WPINC . '/class-smtp.php';
  191. $phpmailer = new PHPMailer( true );
  192. }
  193. // Headers
  194. $cc = $bcc = $reply_to = array();
  195. if ( empty( $headers ) ) {
  196. $headers = array();
  197. } else {
  198. if ( !is_array( $headers ) ) {
  199. // Explode the headers out, so this function can take both
  200. // string headers and an array of headers.
  201. $tempheaders = explode( "\n", str_replace( "\r\n", "\n", $headers ) );
  202. } else {
  203. $tempheaders = $headers;
  204. }
  205. $headers = array();
  206. // If it's actually got contents
  207. if ( !empty( $tempheaders ) ) {
  208. // Iterate through the raw headers
  209. foreach ( (array) $tempheaders as $header ) {
  210. if ( strpos($header, ':') === false ) {
  211. if ( false !== stripos( $header, 'boundary=' ) ) {
  212. $parts = preg_split('/boundary=/i', trim( $header ) );
  213. $boundary = trim( str_replace( array( "'", '"' ), '', $parts[1] ) );
  214. }
  215. continue;
  216. }
  217. // Explode them out
  218. list( $name, $content ) = explode( ':', trim( $header ), 2 );
  219. // Cleanup crew
  220. $name = trim( $name );
  221. $content = trim( $content );
  222. switch ( strtolower( $name ) ) {
  223. // Mainly for legacy -- process a From: header if it's there
  224. case 'from':
  225. $bracket_pos = strpos( $content, '<' );
  226. if ( $bracket_pos !== false ) {
  227. // Text before the bracketed email is the "From" name.
  228. if ( $bracket_pos > 0 ) {
  229. $from_name = substr( $content, 0, $bracket_pos - 1 );
  230. $from_name = str_replace( '"', '', $from_name );
  231. $from_name = trim( $from_name );
  232. }
  233. $from_email = substr( $content, $bracket_pos + 1 );
  234. $from_email = str_replace( '>', '', $from_email );
  235. $from_email = trim( $from_email );
  236. // Avoid setting an empty $from_email.
  237. } elseif ( '' !== trim( $content ) ) {
  238. $from_email = trim( $content );
  239. }
  240. break;
  241. case 'content-type':
  242. if ( strpos( $content, ';' ) !== false ) {
  243. list( $type, $charset_content ) = explode( ';', $content );
  244. $content_type = trim( $type );
  245. if ( false !== stripos( $charset_content, 'charset=' ) ) {
  246. $charset = trim( str_replace( array( 'charset=', '"' ), '', $charset_content ) );
  247. } elseif ( false !== stripos( $charset_content, 'boundary=' ) ) {
  248. $boundary = trim( str_replace( array( 'BOUNDARY=', 'boundary=', '"' ), '', $charset_content ) );
  249. $charset = '';
  250. }
  251. // Avoid setting an empty $content_type.
  252. } elseif ( '' !== trim( $content ) ) {
  253. $content_type = trim( $content );
  254. }
  255. break;
  256. case 'cc':
  257. $cc = array_merge( (array) $cc, explode( ',', $content ) );
  258. break;
  259. case 'bcc':
  260. $bcc = array_merge( (array) $bcc, explode( ',', $content ) );
  261. break;
  262. case 'reply-to':
  263. $reply_to = array_merge( (array) $reply_to, explode( ',', $content ) );
  264. break;
  265. default:
  266. // Add it to our grand headers array
  267. $headers[trim( $name )] = trim( $content );
  268. break;
  269. }
  270. }
  271. }
  272. }
  273. // Empty out the values that may be set
  274. $phpmailer->clearAllRecipients();
  275. $phpmailer->clearAttachments();
  276. $phpmailer->clearCustomHeaders();
  277. $phpmailer->clearReplyTos();
  278. // From email and name
  279. // If we don't have a name from the input headers
  280. if ( !isset( $from_name ) )
  281. $from_name = 'WordPress';
  282. /* If we don't have an email from the input headers default to wordpress@$sitename
  283. * Some hosts will block outgoing mail from this address if it doesn't exist but
  284. * there's no easy alternative. Defaulting to admin_email might appear to be another
  285. * option but some hosts may refuse to relay mail from an unknown domain. See
  286. * https://core.trac.wordpress.org/ticket/5007.
  287. */
  288. if ( !isset( $from_email ) ) {
  289. // Get the site domain and get rid of www.
  290. $sitename = strtolower( $_SERVER['SERVER_NAME'] );
  291. if ( substr( $sitename, 0, 4 ) == 'www.' ) {
  292. $sitename = substr( $sitename, 4 );
  293. }
  294. $from_email = 'wordpress@' . $sitename;
  295. }
  296. /**
  297. * Filters the email address to send from.
  298. *
  299. * @since 2.2.0
  300. *
  301. * @param string $from_email Email address to send from.
  302. */
  303. $from_email = apply_filters( 'wp_mail_from', $from_email );
  304. /**
  305. * Filters the name to associate with the "from" email address.
  306. *
  307. * @since 2.3.0
  308. *
  309. * @param string $from_name Name associated with the "from" email address.
  310. */
  311. $from_name = apply_filters( 'wp_mail_from_name', $from_name );
  312. try {
  313. $phpmailer->setFrom( $from_email, $from_name, false );
  314. } catch ( phpmailerException $e ) {
  315. $mail_error_data = compact( 'to', 'subject', 'message', 'headers', 'attachments' );
  316. $mail_error_data['phpmailer_exception_code'] = $e->getCode();
  317. /** This filter is documented in wp-includes/pluggable.php */
  318. do_action( 'wp_mail_failed', new WP_Error( 'wp_mail_failed', $e->getMessage(), $mail_error_data ) );
  319. return false;
  320. }
  321. // Set mail's subject and body
  322. $phpmailer->Subject = $subject;
  323. $phpmailer->Body = $message;
  324. // Set destination addresses, using appropriate methods for handling addresses
  325. $address_headers = compact( 'to', 'cc', 'bcc', 'reply_to' );
  326. foreach ( $address_headers as $address_header => $addresses ) {
  327. if ( empty( $addresses ) ) {
  328. continue;
  329. }
  330. foreach ( (array) $addresses as $address ) {
  331. try {
  332. // Break $recipient into name and address parts if in the format "Foo <bar@baz.com>"
  333. $recipient_name = '';
  334. if ( preg_match( '/(.*)<(.+)>/', $address, $matches ) ) {
  335. if ( count( $matches ) == 3 ) {
  336. $recipient_name = $matches[1];
  337. $address = $matches[2];
  338. }
  339. }
  340. switch ( $address_header ) {
  341. case 'to':
  342. $phpmailer->addAddress( $address, $recipient_name );
  343. break;
  344. case 'cc':
  345. $phpmailer->addCc( $address, $recipient_name );
  346. break;
  347. case 'bcc':
  348. $phpmailer->addBcc( $address, $recipient_name );
  349. break;
  350. case 'reply_to':
  351. $phpmailer->addReplyTo( $address, $recipient_name );
  352. break;
  353. }
  354. } catch ( phpmailerException $e ) {
  355. continue;
  356. }
  357. }
  358. }
  359. // Set to use PHP's mail()
  360. $phpmailer->isMail();
  361. // Set Content-Type and charset
  362. // If we don't have a content-type from the input headers
  363. if ( !isset( $content_type ) )
  364. $content_type = 'text/plain';
  365. /**
  366. * Filters the wp_mail() content type.
  367. *
  368. * @since 2.3.0
  369. *
  370. * @param string $content_type Default wp_mail() content type.
  371. */
  372. $content_type = apply_filters( 'wp_mail_content_type', $content_type );
  373. $phpmailer->ContentType = $content_type;
  374. // Set whether it's plaintext, depending on $content_type
  375. if ( 'text/html' == $content_type )
  376. $phpmailer->isHTML( true );
  377. // If we don't have a charset from the input headers
  378. if ( !isset( $charset ) )
  379. $charset = get_bloginfo( 'charset' );
  380. // Set the content-type and charset
  381. /**
  382. * Filters the default wp_mail() charset.
  383. *
  384. * @since 2.3.0
  385. *
  386. * @param string $charset Default email charset.
  387. */
  388. $phpmailer->CharSet = apply_filters( 'wp_mail_charset', $charset );
  389. // Set custom headers
  390. if ( !empty( $headers ) ) {
  391. foreach ( (array) $headers as $name => $content ) {
  392. $phpmailer->addCustomHeader( sprintf( '%1$s: %2$s', $name, $content ) );
  393. }
  394. if ( false !== stripos( $content_type, 'multipart' ) && ! empty($boundary) )
  395. $phpmailer->addCustomHeader( sprintf( "Content-Type: %s;\n\t boundary=\"%s\"", $content_type, $boundary ) );
  396. }
  397. if ( !empty( $attachments ) ) {
  398. foreach ( $attachments as $attachment ) {
  399. try {
  400. $phpmailer->addAttachment($attachment);
  401. } catch ( phpmailerException $e ) {
  402. continue;
  403. }
  404. }
  405. }
  406. /**
  407. * Fires after PHPMailer is initialized.
  408. *
  409. * @since 2.2.0
  410. *
  411. * @param PHPMailer $phpmailer The PHPMailer instance (passed by reference).
  412. */
  413. do_action_ref_array( 'phpmailer_init', array( &$phpmailer ) );
  414. // Send!
  415. try {
  416. return $phpmailer->send();
  417. } catch ( phpmailerException $e ) {
  418. $mail_error_data = compact( 'to', 'subject', 'message', 'headers', 'attachments' );
  419. $mail_error_data['phpmailer_exception_code'] = $e->getCode();
  420. /**
  421. * Fires after a phpmailerException is caught.
  422. *
  423. * @since 4.4.0
  424. *
  425. * @param WP_Error $error A WP_Error object with the phpmailerException message, and an array
  426. * containing the mail recipient, subject, message, headers, and attachments.
  427. */
  428. do_action( 'wp_mail_failed', new WP_Error( 'wp_mail_failed', $e->getMessage(), $mail_error_data ) );
  429. return false;
  430. }
  431. }
  432. endif;
  433. if ( !function_exists('wp_authenticate') ) :
  434. /**
  435. * Authenticate a user, confirming the login credentials are valid.
  436. *
  437. * @since 2.5.0
  438. * @since 4.5.0 `$username` now accepts an email address.
  439. *
  440. * @param string $username User's username or email address.
  441. * @param string $password User's password.
  442. * @return WP_User|WP_Error WP_User object if the credentials are valid,
  443. * otherwise WP_Error.
  444. */
  445. function wp_authenticate($username, $password) {
  446. $username = sanitize_user($username);
  447. $password = trim($password);
  448. /**
  449. * Filters whether a set of user login credentials are valid.
  450. *
  451. * A WP_User object is returned if the credentials authenticate a user.
  452. * WP_Error or null otherwise.
  453. *
  454. * @since 2.8.0
  455. * @since 4.5.0 `$username` now accepts an email address.
  456. *
  457. * @param null|WP_User|WP_Error $user WP_User if the user is authenticated.
  458. * WP_Error or null otherwise.
  459. * @param string $username Username or email address.
  460. * @param string $password User password
  461. */
  462. $user = apply_filters( 'authenticate', null, $username, $password );
  463. if ( $user == null ) {
  464. // TODO what should the error message be? (Or would these even happen?)
  465. // Only needed if all authentication handlers fail to return anything.
  466. $user = new WP_Error( 'authentication_failed', __( '<strong>ERROR</strong>: Invalid username, email address or incorrect password.' ) );
  467. }
  468. $ignore_codes = array('empty_username', 'empty_password');
  469. if (is_wp_error($user) && !in_array($user->get_error_code(), $ignore_codes) ) {
  470. /**
  471. * Fires after a user login has failed.
  472. *
  473. * @since 2.5.0
  474. * @since 4.5.0 The value of `$username` can now be an email address.
  475. *
  476. * @param string $username Username or email address.
  477. */
  478. do_action( 'wp_login_failed', $username );
  479. }
  480. return $user;
  481. }
  482. endif;
  483. if ( !function_exists('wp_logout') ) :
  484. /**
  485. * Log the current user out.
  486. *
  487. * @since 2.5.0
  488. */
  489. function wp_logout() {
  490. wp_destroy_current_session();
  491. wp_clear_auth_cookie();
  492. /**
  493. * Fires after a user is logged-out.
  494. *
  495. * @since 1.5.0
  496. */
  497. do_action( 'wp_logout' );
  498. }
  499. endif;
  500. if ( !function_exists('wp_validate_auth_cookie') ) :
  501. /**
  502. * Validates authentication cookie.
  503. *
  504. * The checks include making sure that the authentication cookie is set and
  505. * pulling in the contents (if $cookie is not used).
  506. *
  507. * Makes sure the cookie is not expired. Verifies the hash in cookie is what is
  508. * should be and compares the two.
  509. *
  510. * @since 2.5.0
  511. *
  512. * @global int $login_grace_period
  513. *
  514. * @param string $cookie Optional. If used, will validate contents instead of cookie's
  515. * @param string $scheme Optional. The cookie scheme to use: auth, secure_auth, or logged_in
  516. * @return false|int False if invalid cookie, User ID if valid.
  517. */
  518. function wp_validate_auth_cookie($cookie = '', $scheme = '') {
  519. if ( ! $cookie_elements = wp_parse_auth_cookie($cookie, $scheme) ) {
  520. /**
  521. * Fires if an authentication cookie is malformed.
  522. *
  523. * @since 2.7.0
  524. *
  525. * @param string $cookie Malformed auth cookie.
  526. * @param string $scheme Authentication scheme. Values include 'auth', 'secure_auth',
  527. * or 'logged_in'.
  528. */
  529. do_action( 'auth_cookie_malformed', $cookie, $scheme );
  530. return false;
  531. }
  532. $scheme = $cookie_elements['scheme'];
  533. $username = $cookie_elements['username'];
  534. $hmac = $cookie_elements['hmac'];
  535. $token = $cookie_elements['token'];
  536. $expired = $expiration = $cookie_elements['expiration'];
  537. // Allow a grace period for POST and Ajax requests
  538. if ( wp_doing_ajax() || 'POST' == $_SERVER['REQUEST_METHOD'] ) {
  539. $expired += HOUR_IN_SECONDS;
  540. }
  541. // Quick check to see if an honest cookie has expired
  542. if ( $expired < time() ) {
  543. /**
  544. * Fires once an authentication cookie has expired.
  545. *
  546. * @since 2.7.0
  547. *
  548. * @param array $cookie_elements An array of data for the authentication cookie.
  549. */
  550. do_action( 'auth_cookie_expired', $cookie_elements );
  551. return false;
  552. }
  553. $user = get_user_by('login', $username);
  554. if ( ! $user ) {
  555. /**
  556. * Fires if a bad username is entered in the user authentication process.
  557. *
  558. * @since 2.7.0
  559. *
  560. * @param array $cookie_elements An array of data for the authentication cookie.
  561. */
  562. do_action( 'auth_cookie_bad_username', $cookie_elements );
  563. return false;
  564. }
  565. $pass_frag = substr($user->user_pass, 8, 4);
  566. $key = wp_hash( $username . '|' . $pass_frag . '|' . $expiration . '|' . $token, $scheme );
  567. // If ext/hash is not present, compat.php's hash_hmac() does not support sha256.
  568. $algo = function_exists( 'hash' ) ? 'sha256' : 'sha1';
  569. $hash = hash_hmac( $algo, $username . '|' . $expiration . '|' . $token, $key );
  570. if ( ! hash_equals( $hash, $hmac ) ) {
  571. /**
  572. * Fires if a bad authentication cookie hash is encountered.
  573. *
  574. * @since 2.7.0
  575. *
  576. * @param array $cookie_elements An array of data for the authentication cookie.
  577. */
  578. do_action( 'auth_cookie_bad_hash', $cookie_elements );
  579. return false;
  580. }
  581. $manager = WP_Session_Tokens::get_instance( $user->ID );
  582. if ( ! $manager->verify( $token ) ) {
  583. do_action( 'auth_cookie_bad_session_token', $cookie_elements );
  584. return false;
  585. }
  586. // Ajax/POST grace period set above
  587. if ( $expiration < time() ) {
  588. $GLOBALS['login_grace_period'] = 1;
  589. }
  590. /**
  591. * Fires once an authentication cookie has been validated.
  592. *
  593. * @since 2.7.0
  594. *
  595. * @param array $cookie_elements An array of data for the authentication cookie.
  596. * @param WP_User $user User object.
  597. */
  598. do_action( 'auth_cookie_valid', $cookie_elements, $user );
  599. return $user->ID;
  600. }
  601. endif;
  602. if ( !function_exists('wp_generate_auth_cookie') ) :
  603. /**
  604. * Generate authentication cookie contents.
  605. *
  606. * @since 2.5.0
  607. * @since 4.0.0 The `$token` parameter was added.
  608. *
  609. * @param int $user_id User ID
  610. * @param int $expiration The time the cookie expires as a UNIX timestamp.
  611. * @param string $scheme Optional. The cookie scheme to use: auth, secure_auth, or logged_in
  612. * @param string $token User's session token to use for this cookie
  613. * @return string Authentication cookie contents. Empty string if user does not exist.
  614. */
  615. function wp_generate_auth_cookie( $user_id, $expiration, $scheme = 'auth', $token = '' ) {
  616. $user = get_userdata($user_id);
  617. if ( ! $user ) {
  618. return '';
  619. }
  620. if ( ! $token ) {
  621. $manager = WP_Session_Tokens::get_instance( $user_id );
  622. $token = $manager->create( $expiration );
  623. }
  624. $pass_frag = substr($user->user_pass, 8, 4);
  625. $key = wp_hash( $user->user_login . '|' . $pass_frag . '|' . $expiration . '|' . $token, $scheme );
  626. // If ext/hash is not present, compat.php's hash_hmac() does not support sha256.
  627. $algo = function_exists( 'hash' ) ? 'sha256' : 'sha1';
  628. $hash = hash_hmac( $algo, $user->user_login . '|' . $expiration . '|' . $token, $key );
  629. $cookie = $user->user_login . '|' . $expiration . '|' . $token . '|' . $hash;
  630. /**
  631. * Filters the authentication cookie.
  632. *
  633. * @since 2.5.0
  634. * @since 4.0.0 The `$token` parameter was added.
  635. *
  636. * @param string $cookie Authentication cookie.
  637. * @param int $user_id User ID.
  638. * @param int $expiration The time the cookie expires as a UNIX timestamp.
  639. * @param string $scheme Cookie scheme used. Accepts 'auth', 'secure_auth', or 'logged_in'.
  640. * @param string $token User's session token used.
  641. */
  642. return apply_filters( 'auth_cookie', $cookie, $user_id, $expiration, $scheme, $token );
  643. }
  644. endif;
  645. if ( !function_exists('wp_parse_auth_cookie') ) :
  646. /**
  647. * Parse a cookie into its components
  648. *
  649. * @since 2.7.0
  650. *
  651. * @param string $cookie
  652. * @param string $scheme Optional. The cookie scheme to use: auth, secure_auth, or logged_in
  653. * @return array|false Authentication cookie components
  654. */
  655. function wp_parse_auth_cookie($cookie = '', $scheme = '') {
  656. if ( empty($cookie) ) {
  657. switch ($scheme){
  658. case 'auth':
  659. $cookie_name = AUTH_COOKIE;
  660. break;
  661. case 'secure_auth':
  662. $cookie_name = SECURE_AUTH_COOKIE;
  663. break;
  664. case "logged_in":
  665. $cookie_name = LOGGED_IN_COOKIE;
  666. break;
  667. default:
  668. if ( is_ssl() ) {
  669. $cookie_name = SECURE_AUTH_COOKIE;
  670. $scheme = 'secure_auth';
  671. } else {
  672. $cookie_name = AUTH_COOKIE;
  673. $scheme = 'auth';
  674. }
  675. }
  676. if ( empty($_COOKIE[$cookie_name]) )
  677. return false;
  678. $cookie = $_COOKIE[$cookie_name];
  679. }
  680. $cookie_elements = explode('|', $cookie);
  681. if ( count( $cookie_elements ) !== 4 ) {
  682. return false;
  683. }
  684. list( $username, $expiration, $token, $hmac ) = $cookie_elements;
  685. return compact( 'username', 'expiration', 'token', 'hmac', 'scheme' );
  686. }
  687. endif;
  688. if ( !function_exists('wp_set_auth_cookie') ) :
  689. /**
  690. * Log in a user by setting authentication cookies.
  691. *
  692. * The $remember parameter increases the time that the cookie will be kept. The
  693. * default the cookie is kept without remembering is two days. When $remember is
  694. * set, the cookies will be kept for 14 days or two weeks.
  695. *
  696. * @since 2.5.0
  697. * @since 4.3.0 Added the `$token` parameter.
  698. *
  699. * @param int $user_id User ID
  700. * @param bool $remember Whether to remember the user
  701. * @param mixed $secure Whether the admin cookies should only be sent over HTTPS.
  702. * Default is_ssl().
  703. * @param string $token Optional. User's session token to use for this cookie.
  704. */
  705. function wp_set_auth_cookie( $user_id, $remember = false, $secure = '', $token = '' ) {
  706. if ( $remember ) {
  707. /**
  708. * Filters the duration of the authentication cookie expiration period.
  709. *
  710. * @since 2.8.0
  711. *
  712. * @param int $length Duration of the expiration period in seconds.
  713. * @param int $user_id User ID.
  714. * @param bool $remember Whether to remember the user login. Default false.
  715. */
  716. $expiration = time() + apply_filters( 'auth_cookie_expiration', 14 * DAY_IN_SECONDS, $user_id, $remember );
  717. /*
  718. * Ensure the browser will continue to send the cookie after the expiration time is reached.
  719. * Needed for the login grace period in wp_validate_auth_cookie().
  720. */
  721. $expire = $expiration + ( 12 * HOUR_IN_SECONDS );
  722. } else {
  723. /** This filter is documented in wp-includes/pluggable.php */
  724. $expiration = time() + apply_filters( 'auth_cookie_expiration', 2 * DAY_IN_SECONDS, $user_id, $remember );
  725. $expire = 0;
  726. }
  727. if ( '' === $secure ) {
  728. $secure = is_ssl();
  729. }
  730. // Front-end cookie is secure when the auth cookie is secure and the site's home URL is forced HTTPS.
  731. $secure_logged_in_cookie = $secure && 'https' === parse_url( get_option( 'home' ), PHP_URL_SCHEME );
  732. /**
  733. * Filters whether the connection is secure.
  734. *
  735. * @since 3.1.0
  736. *
  737. * @param bool $secure Whether the connection is secure.
  738. * @param int $user_id User ID.
  739. */
  740. $secure = apply_filters( 'secure_auth_cookie', $secure, $user_id );
  741. /**
  742. * Filters whether to use a secure cookie when logged-in.
  743. *
  744. * @since 3.1.0
  745. *
  746. * @param bool $secure_logged_in_cookie Whether to use a secure cookie when logged-in.
  747. * @param int $user_id User ID.
  748. * @param bool $secure Whether the connection is secure.
  749. */
  750. $secure_logged_in_cookie = apply_filters( 'secure_logged_in_cookie', $secure_logged_in_cookie, $user_id, $secure );
  751. if ( $secure ) {
  752. $auth_cookie_name = SECURE_AUTH_COOKIE;
  753. $scheme = 'secure_auth';
  754. } else {
  755. $auth_cookie_name = AUTH_COOKIE;
  756. $scheme = 'auth';
  757. }
  758. if ( '' === $token ) {
  759. $manager = WP_Session_Tokens::get_instance( $user_id );
  760. $token = $manager->create( $expiration );
  761. }
  762. $auth_cookie = wp_generate_auth_cookie( $user_id, $expiration, $scheme, $token );
  763. $logged_in_cookie = wp_generate_auth_cookie( $user_id, $expiration, 'logged_in', $token );
  764. /**
  765. * Fires immediately before the authentication cookie is set.
  766. *
  767. * @since 2.5.0
  768. * @since 4.9.0 The `$token` parameter was added.
  769. *
  770. * @param string $auth_cookie Authentication cookie.
  771. * @param int $expire The time the login grace period expires as a UNIX timestamp.
  772. * Default is 12 hours past the cookie's expiration time.
  773. * @param int $expiration The time when the authentication cookie expires as a UNIX timestamp.
  774. * Default is 14 days from now.
  775. * @param int $user_id User ID.
  776. * @param string $scheme Authentication scheme. Values include 'auth', 'secure_auth', or 'logged_in'.
  777. * @param string $token User's session token to use for this cookie.
  778. */
  779. do_action( 'set_auth_cookie', $auth_cookie, $expire, $expiration, $user_id, $scheme, $token );
  780. /**
  781. * Fires immediately before the logged-in authentication cookie is set.
  782. *
  783. * @since 2.6.0
  784. * @since 4.9.0 The `$token` parameter was added.
  785. *
  786. * @param string $logged_in_cookie The logged-in cookie.
  787. * @param int $expire The time the login grace period expires as a UNIX timestamp.
  788. * Default is 12 hours past the cookie's expiration time.
  789. * @param int $expiration The time when the logged-in authentication cookie expires as a UNIX timestamp.
  790. * Default is 14 days from now.
  791. * @param int $user_id User ID.
  792. * @param string $scheme Authentication scheme. Default 'logged_in'.
  793. * @param string $token User's session token to use for this cookie.
  794. */
  795. do_action( 'set_logged_in_cookie', $logged_in_cookie, $expire, $expiration, $user_id, 'logged_in', $token );
  796. /**
  797. * Allows preventing auth cookies from actually being sent to the client.
  798. *
  799. * @since 4.7.4
  800. *
  801. * @param bool $send Whether to send auth cookies to the client.
  802. */
  803. if ( ! apply_filters( 'send_auth_cookies', true ) ) {
  804. return;
  805. }
  806. setcookie($auth_cookie_name, $auth_cookie, $expire, PLUGINS_COOKIE_PATH, COOKIE_DOMAIN, $secure, true);
  807. setcookie($auth_cookie_name, $auth_cookie, $expire, ADMIN_COOKIE_PATH, COOKIE_DOMAIN, $secure, true);
  808. setcookie(LOGGED_IN_COOKIE, $logged_in_cookie, $expire, COOKIEPATH, COOKIE_DOMAIN, $secure_logged_in_cookie, true);
  809. if ( COOKIEPATH != SITECOOKIEPATH )
  810. setcookie(LOGGED_IN_COOKIE, $logged_in_cookie, $expire, SITECOOKIEPATH, COOKIE_DOMAIN, $secure_logged_in_cookie, true);
  811. }
  812. endif;
  813. if ( !function_exists('wp_clear_auth_cookie') ) :
  814. /**
  815. * Removes all of the cookies associated with authentication.
  816. *
  817. * @since 2.5.0
  818. */
  819. function wp_clear_auth_cookie() {
  820. /**
  821. * Fires just before the authentication cookies are cleared.
  822. *
  823. * @since 2.7.0
  824. */
  825. do_action( 'clear_auth_cookie' );
  826. /** This filter is documented in wp-includes/pluggable.php */
  827. if ( ! apply_filters( 'send_auth_cookies', true ) ) {
  828. return;
  829. }
  830. // Auth cookies
  831. setcookie( AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, ADMIN_COOKIE_PATH, COOKIE_DOMAIN );
  832. setcookie( SECURE_AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, ADMIN_COOKIE_PATH, COOKIE_DOMAIN );
  833. setcookie( AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, PLUGINS_COOKIE_PATH, COOKIE_DOMAIN );
  834. setcookie( SECURE_AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, PLUGINS_COOKIE_PATH, COOKIE_DOMAIN );
  835. setcookie( LOGGED_IN_COOKIE, ' ', time() - YEAR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN );
  836. setcookie( LOGGED_IN_COOKIE, ' ', time() - YEAR_IN_SECONDS, SITECOOKIEPATH, COOKIE_DOMAIN );
  837. // Settings cookies
  838. setcookie( 'wp-settings-' . get_current_user_id(), ' ', time() - YEAR_IN_SECONDS, SITECOOKIEPATH );
  839. setcookie( 'wp-settings-time-' . get_current_user_id(), ' ', time() - YEAR_IN_SECONDS, SITECOOKIEPATH );
  840. // Old cookies
  841. setcookie( AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN );
  842. setcookie( AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, SITECOOKIEPATH, COOKIE_DOMAIN );
  843. setcookie( SECURE_AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN );
  844. setcookie( SECURE_AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, SITECOOKIEPATH, COOKIE_DOMAIN );
  845. // Even older cookies
  846. setcookie( USER_COOKIE, ' ', time() - YEAR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN );
  847. setcookie( PASS_COOKIE, ' ', time() - YEAR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN );
  848. setcookie( USER_COOKIE, ' ', time() - YEAR_IN_SECONDS, SITECOOKIEPATH, COOKIE_DOMAIN );
  849. setcookie( PASS_COOKIE, ' ', time() - YEAR_IN_SECONDS, SITECOOKIEPATH, COOKIE_DOMAIN );
  850. // Post password cookie
  851. setcookie( 'wp-postpass_' . COOKIEHASH, ' ', time() - YEAR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN );
  852. }
  853. endif;
  854. if ( !function_exists('is_user_logged_in') ) :
  855. /**
  856. * Checks if the current visitor is a logged in user.
  857. *
  858. * @since 2.0.0
  859. *
  860. * @return bool True if user is logged in, false if not logged in.
  861. */
  862. function is_user_logged_in() {
  863. $user = wp_get_current_user();
  864. return $user->exists();
  865. }
  866. endif;
  867. if ( !function_exists('auth_redirect') ) :
  868. /**
  869. * Checks if a user is logged in, if not it redirects them to the login page.
  870. *
  871. * @since 1.5.0
  872. */
  873. function auth_redirect() {
  874. // Checks if a user is logged in, if not redirects them to the login page
  875. $secure = ( is_ssl() || force_ssl_admin() );
  876. /**
  877. * Filters whether to use a secure authentication redirect.
  878. *
  879. * @since 3.1.0
  880. *
  881. * @param bool $secure Whether to use a secure authentication redirect. Default false.
  882. */
  883. $secure = apply_filters( 'secure_auth_redirect', $secure );
  884. // If https is required and request is http, redirect
  885. if ( $secure && !is_ssl() && false !== strpos($_SERVER['REQUEST_URI'], 'wp-admin') ) {
  886. if ( 0 === strpos( $_SERVER['REQUEST_URI'], 'http' ) ) {
  887. wp_redirect( set_url_scheme( $_SERVER['REQUEST_URI'], 'https' ) );
  888. exit();
  889. } else {
  890. wp_redirect( 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );
  891. exit();
  892. }
  893. }
  894. /**
  895. * Filters the authentication redirect scheme.
  896. *
  897. * @since 2.9.0
  898. *
  899. * @param string $scheme Authentication redirect scheme. Default empty.
  900. */
  901. $scheme = apply_filters( 'auth_redirect_scheme', '' );
  902. if ( $user_id = wp_validate_auth_cookie( '', $scheme) ) {
  903. /**
  904. * Fires before the authentication redirect.
  905. *
  906. * @since 2.8.0
  907. *
  908. * @param int $user_id User ID.
  909. */
  910. do_action( 'auth_redirect', $user_id );
  911. // If the user wants ssl but the session is not ssl, redirect.
  912. if ( !$secure && get_user_option('use_ssl', $user_id) && false !== strpos($_SERVER['REQUEST_URI'], 'wp-admin') ) {
  913. if ( 0 === strpos( $_SERVER['REQUEST_URI'], 'http' ) ) {
  914. wp_redirect( set_url_scheme( $_SERVER['REQUEST_URI'], 'https' ) );
  915. exit();
  916. } else {
  917. wp_redirect( 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );
  918. exit();
  919. }
  920. }
  921. return; // The cookie is good so we're done
  922. }
  923. // The cookie is no good so force login
  924. nocache_headers();
  925. $redirect = ( strpos( $_SERVER['REQUEST_URI'], '/options.php' ) && wp_get_referer() ) ? wp_get_referer() : set_url_scheme( 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );
  926. $login_url = wp_login_url($redirect, true);
  927. wp_redirect($login_url);
  928. exit();
  929. }
  930. endif;
  931. if ( !function_exists('check_admin_referer') ) :
  932. /**
  933. * Makes sure that a user was referred from another admin page.
  934. *
  935. * To avoid security exploits.
  936. *
  937. * @since 1.2.0
  938. *
  939. * @param int|string $action Action nonce.
  940. * @param string $query_arg Optional. Key to check for nonce in `$_REQUEST` (since 2.5).
  941. * Default '_wpnonce'.
  942. * @return false|int False if the nonce is invalid, 1 if the nonce is valid and generated between
  943. * 0-12 hours ago, 2 if the nonce is valid and generated between 12-24 hours ago.
  944. */
  945. function check_admin_referer( $action = -1, $query_arg = '_wpnonce' ) {
  946. if ( -1 == $action )
  947. _doing_it_wrong( __FUNCTION__, __( 'You should specify a nonce action to be verified by using the first parameter.' ), '3.2.0' );
  948. $adminurl = strtolower(admin_url());
  949. $referer = strtolower(wp_get_referer());
  950. $result = isset($_REQUEST[$query_arg]) ? wp_verify_nonce($_REQUEST[$query_arg], $action) : false;
  951. /**
  952. * Fires once the admin request has been validated or not.
  953. *
  954. * @since 1.5.1
  955. *
  956. * @param string $action The nonce action.
  957. * @param false|int $result False if the nonce is invalid, 1 if the nonce is valid and generated between
  958. * 0-12 hours ago, 2 if the nonce is valid and generated between 12-24 hours ago.
  959. */
  960. do_action( 'check_admin_referer', $action, $result );
  961. if ( ! $result && ! ( -1 == $action && strpos( $referer, $adminurl ) === 0 ) ) {
  962. wp_nonce_ays( $action );
  963. die();
  964. }
  965. return $result;
  966. }
  967. endif;
  968. if ( !function_exists('check_ajax_referer') ) :
  969. /**
  970. * Verifies the Ajax request to prevent processing requests external of the blog.
  971. *
  972. * @since 2.0.3
  973. *
  974. * @param int|string $action Action nonce.
  975. * @param false|string $query_arg Optional. Key to check for the nonce in `$_REQUEST` (since 2.5). If false,
  976. * `$_REQUEST` values will be evaluated for '_ajax_nonce', and '_wpnonce'
  977. * (in that order). Default false.
  978. * @param bool $die Optional. Whether to die early when the nonce cannot be verified.
  979. * Default true.
  980. * @return false|int False if the nonce is invalid, 1 if the nonce is valid and generated between
  981. * 0-12 hours ago, 2 if the nonce is valid and generated between 12-24 hours ago.
  982. */
  983. function check_ajax_referer( $action = -1, $query_arg = false, $die = true ) {
  984. if ( -1 == $action ) {
  985. _doing_it_wrong( __FUNCTION__, __( 'You should specify a nonce action to be verified by using the first parameter.' ), '4.7' );
  986. }
  987. $nonce = '';
  988. if ( $query_arg && isset( $_REQUEST[ $query_arg ] ) )
  989. $nonce = $_REQUEST[ $query_arg ];
  990. elseif ( isset( $_REQUEST['_ajax_nonce'] ) )
  991. $nonce = $_REQUEST['_ajax_nonce'];
  992. elseif ( isset( $_REQUEST['_wpnonce'] ) )
  993. $nonce = $_REQUEST['_wpnonce'];
  994. $result = wp_verify_nonce( $nonce, $action );
  995. /**
  996. * Fires once the Ajax request has been validated or not.
  997. *
  998. * @since 2.1.0
  999. *
  1000. * @param string $action The Ajax nonce action.
  1001. * @param false|int $result False if the nonce is invalid, 1 if the nonce is valid and generated between
  1002. * 0-12 hours ago, 2 if the nonce is valid and generated between 12-24 hours ago.
  1003. */
  1004. do_action( 'check_ajax_referer', $action, $result );
  1005. if ( $die && false === $result ) {
  1006. if ( wp_doing_ajax() ) {
  1007. wp_die( -1, 403 );
  1008. } else {
  1009. die( '-1' );
  1010. }
  1011. }
  1012. return $result;
  1013. }
  1014. endif;
  1015. if ( !function_exists('wp_redirect') ) :
  1016. /**
  1017. * Redirects to another page.
  1018. *
  1019. * Note: wp_redirect() does not exit automatically, and should almost always be
  1020. * followed by a call to `exit;`:
  1021. *
  1022. * wp_redirect( $url );
  1023. * exit;
  1024. *
  1025. * Exiting can also be selectively manipulated by using wp_redirect() as a conditional
  1026. * in conjunction with the {@see 'wp_redirect'} and {@see 'wp_redirect_location'} hooks:
  1027. *
  1028. * if ( wp_redirect( $url ) ) {
  1029. * exit;
  1030. * }
  1031. *
  1032. * @since 1.5.1
  1033. *
  1034. * @global bool $is_IIS
  1035. *
  1036. * @param string $location The path to redirect to.
  1037. * @param int $status Status code to use.
  1038. * @return bool False if $location is not provided, true otherwise.
  1039. */
  1040. function wp_redirect($location, $status = 302) {
  1041. global $is_IIS;
  1042. /**
  1043. * Filters the redirect location.
  1044. *
  1045. * @since 2.1.0
  1046. *
  1047. * @param string $location The path to redirect to.
  1048. * @param int $status Status code to use.
  1049. */
  1050. $location = apply_filters( 'wp_redirect', $location, $status );
  1051. /**
  1052. * Filters the redirect status code.
  1053. *
  1054. * @since 2.3.0
  1055. *
  1056. * @param int $status Status code to use.
  1057. * @param string $location The path to redirect to.
  1058. */
  1059. $status = apply_filters( 'wp_redirect_status', $status, $location );
  1060. if ( ! $location )
  1061. return false;
  1062. $location = wp_sanitize_redirect($location);
  1063. if ( !$is_IIS && PHP_SAPI != 'cgi-fcgi' )
  1064. status_header($status); // This causes problems on IIS and some FastCGI setups
  1065. header("Location: $location", true, $status);
  1066. return true;
  1067. }
  1068. endif;
  1069. if ( !function_exists('wp_sanitize_redirect') ) :
  1070. /**
  1071. * Sanitizes a URL for use in a redirect.
  1072. *
  1073. * @since 2.3.0
  1074. *
  1075. * @param string $location The path to redirect to.
  1076. * @return string Redirect-sanitized URL.
  1077. **/
  1078. function wp_sanitize_redirect($location) {
  1079. $regex = '/
  1080. (
  1081. (?: [\xC2-\xDF][\x80-\xBF] # double-byte sequences 110xxxxx 10xxxxxx
  1082. | \xE0[\xA0-\xBF][\x80-\xBF] # triple-byte sequences 1110xxxx 10xxxxxx * 2
  1083. | [\xE1-\xEC][\x80-\xBF]{2}
  1084. | \xED[\x80-\x9F][\x80-\xBF]
  1085. | [\xEE-\xEF][\x80-\xBF]{2}
  1086. | \xF0[\x90-\xBF][\x80-\xBF]{2} # four-byte sequences 11110xxx 10xxxxxx * 3
  1087. | [\xF1-\xF3][\x80-\xBF]{3}
  1088. | \xF4[\x80-\x8F][\x80-\xBF]{2}
  1089. ){1,40} # ...one or more times
  1090. )/x';
  1091. $location = preg_replace_callback( $regex, '_wp_sanitize_utf8_in_redirect', $location );
  1092. $location = preg_replace('|[^a-z0-9-~+_.?#=&;,/:%!*\[\]()@]|i', '', $location);
  1093. $location = wp_kses_no_null($location);
  1094. // remove %0d and %0a from location
  1095. $strip = array('%0d', '%0a', '%0D', '%0A');
  1096. return _deep_replace( $strip, $location );
  1097. }
  1098. /**
  1099. * URL encode UTF-8 characters in a URL.
  1100. *
  1101. * @ignore
  1102. * @since 4.2.0
  1103. * @access private
  1104. *
  1105. * @see wp_sanitize_redirect()
  1106. *
  1107. * @param array $matches RegEx matches against the redirect location.
  1108. * @return string URL-encoded version of the first RegEx match.
  1109. */
  1110. function _wp_sanitize_utf8_in_redirect( $matches ) {
  1111. return urlencode( $matches[0] );
  1112. }
  1113. endif;
  1114. if ( !function_exists('wp_safe_redirect') ) :
  1115. /**
  1116. * Performs a safe (local) redirect, using wp_redirect().
  1117. *
  1118. * Checks whether the $location is using an allowed host, if it has an absolute
  1119. * path. A plugin can therefore set or remove allowed host(s) to or from the
  1120. * list.
  1121. *
  1122. * If the host is not allowed, then the redirect defaults to wp-admin on the siteurl
  1123. * instead. This prevents malicious redirects which redirect to another host,
  1124. * but only used in a few places.
  1125. *
  1126. * @since 2.3.0
  1127. *
  1128. * @param string $location The path to redirect to.
  1129. * @param int $status Status code to use.
  1130. */
  1131. function wp_safe_redirect($location, $status = 302) {
  1132. // Need to look at the URL the way it will end up in wp_redirect()
  1133. $location = wp_sanitize_redirect($location);
  1134. /**
  1135. * Filters the redirect fallback URL for when the provided redirect is not safe (local).
  1136. *
  1137. * @since 4.3.0
  1138. *
  1139. * @param string $fallback_url The fallback URL to use by default.
  1140. * @param int $status The redirect status.
  1141. */
  1142. $location = wp_validate_redirect( $location, apply_filters( 'wp_safe_redirect_fallback', admin_url(), $status ) );
  1143. wp_redirect($location, $status);
  1144. }
  1145. endif;
  1146. if ( !function_exists('wp_validate_redirect') ) :
  1147. /**
  1148. * Validates a URL for use in a redirect.
  1149. *
  1150. * Checks whether the $location is using an allowed host, if it has an absolute
  1151. * path. A plugin can therefore set or remove allowed host(s) to or from the
  1152. * list.
  1153. *
  1154. * If the host is not allowed, then the redirect is to $default supplied
  1155. *
  1156. * @since 2.8.1
  1157. *
  1158. * @param string $location The redirect to validate
  1159. * @param string $default The value to return if $location is not allowed
  1160. * @return string redirect-sanitized URL
  1161. **/
  1162. function wp_validate_redirect($location, $default = '') {
  1163. $location = trim( $location, " \t\n\r\0\x08\x0B" );
  1164. // browsers will assume 'http' is your protocol, and will obey a redirect to a URL starting with '//'
  1165. if ( substr($location, 0, 2) == '//' )
  1166. $location = 'http:' . $location;
  1167. // In php 5 parse_url may fail if the URL query part contains http://, bug #38143
  1168. $test = ( $cut = strpos($location, '?') ) ? substr( $location, 0, $cut ) : $location;
  1169. // @-operator is used to prevent possible warnings in PHP < 5.3.3.
  1170. $lp = @parse_url($test);
  1171. // Give up if malformed URL
  1172. if ( false === $lp )
  1173. return $default;
  1174. // Allow only http and https schemes. No data:, etc.
  1175. if ( isset($lp['scheme']) && !('http' == $lp['scheme'] || 'https' == $lp['scheme']) )
  1176. return $default;
  1177. // Reject if certain components are set but host is not. This catches urls like https:host.com for which parse_url does not set the host field.
  1178. if ( ! isset( $lp['host'] ) && ( isset( $lp['scheme'] ) || isset( $lp['user'] ) || isset( $lp['pass'] ) || isset( $lp['port'] ) ) ) {
  1179. return $default;
  1180. }
  1181. // Reject malformed components parse_url() can return on odd inputs.
  1182. foreach ( array( 'user', 'pass', 'host' ) as $component ) {
  1183. if ( isset( $lp[ $component ] ) && strpbrk( $lp[ $component ], ':/?#@' ) ) {
  1184. return $default;
  1185. }
  1186. }
  1187. $wpp = parse_url(home_url());
  1188. /**
  1189. * Filters the whitelist of hosts to redirect to.
  1190. *
  1191. * @since 2.3.0
  1192. *
  1193. * @param array $hosts An array of allowed hosts.
  1194. * @param bool|string $host The parsed host; empty if not isset.
  1195. */
  1196. $allowed_hosts = (array) apply_filters( 'allowed_redirect_hosts', array($wpp['host']), isset($lp['host']) ? $lp['host'] : '' );
  1197. if ( isset($lp['host']) && ( !in_array($lp['host'], $allowed_hosts) && $lp['host'] != strtolower($wpp['host'])) )
  1198. $location = $default;
  1199. return $location;
  1200. }
  1201. endif;
  1202. if ( ! function_exists('wp_notify_postauthor') ) :
  1203. /**
  1204. * Notify an author (and/or others) of a comment/trackback/pingback on a post.
  1205. *
  1206. * @since 1.0.0
  1207. *
  1208. * @param int|WP_Comment $comment_id Comment ID or WP_Comment object.
  1209. * @param string $deprecated Not used
  1210. * @return bool True on completion. False if no email addresses were specified.
  1211. */
  1212. function wp_notify_postauthor( $comment_id, $deprecated = null ) {
  1213. if ( null !== $deprecated ) {
  1214. _deprecated_argument( __FUNCTION__, '3.8.0' );
  1215. }
  1216. $comment = get_comment( $comment_id );
  1217. if ( empty( $comment ) || empty( $comment->comment_post_ID ) )
  1218. return false;
  1219. $post = get_post( $comment->comment_post_ID );
  1220. $author = get_userdata( $post->post_author );
  1221. // Who to notify? By default, just the post author, but others can be added.
  1222. $emails = array();
  1223. if ( $author ) {
  1224. $emails[] = $author->user_email;
  1225. }
  1226. /**
  1227. * Filters the list of email addresses to receive a comment notification.
  1228. *
  1229. * By default, only post authors are notified of comments. This filter allows
  1230. * others to be added.
  1231. *
  1232. * @since 3.7.0
  1233. *
  1234. * @param array $emails An array of email addresses to receive a comment notification.
  1235. * @param int $comment_id The comment ID.
  1236. */
  1237. $emails = apply_filters( 'comment_notification_recipients', $emails, $comment->comment_ID );
  1238. $emails = array_filter( $emails );
  1239. // If there are no addresses to send the comment to, bail.
  1240. if ( ! count( $emails ) ) {
  1241. return false;
  1242. }
  1243. // Facilitate unsetting below without knowing the keys.
  1244. $emails = array_flip( $emails );
  1245. /**
  1246. * Filters whether to notify comment authors of their comments on their own posts.
  1247. *
  1248. * By default, comment authors aren't notified of their comments on their own
  1249. * posts. This filter allows you to override that.
  1250. *
  1251. * @since 3.8.0
  1252. *
  1253. * @param bool $notify Whether to notify the post author of their own comment.
  1254. * Default false.
  1255. * @param int $comment_id The comment ID.
  1256. */
  1257. $notify_author = apply_filters( 'comment_notification_notify_author', false, $comment->comment_ID );
  1258. // The comment was left by the author
  1259. if ( $author && ! $notify_author && $comment->user_id == $post->post_author ) {
  1260. unset( $emails[ $author->user_email ] );
  1261. }
  1262. // The author moderated a comment on their own post
  1263. if ( $author && ! $notify_author && $post->post_author == get_current_user_id() ) {
  1264. unset( $emails[ $author->user_email ] );
  1265. }
  1266. // The post author is no longer a member of the blog
  1267. if ( $author && ! $notify_author && ! user_can( $post->post_author, 'read_post', $post->ID ) ) {
  1268. unset( $emails[ $author->user_email ] );
  1269. }
  1270. // If there's no email to send the comment to, bail, otherwise flip array back around for use below
  1271. if ( ! count( $emails ) ) {
  1272. return false;
  1273. } else {
  1274. $emails = array_flip( $emails );
  1275. }
  1276. $switched_locale = switch_to_locale( get_locale() );
  1277. $comment_author_domain = @gethostbyaddr($comment->comment_author_IP);
  1278. // The blogname option is escaped with esc_html on the way into the database in sanitize_option
  1279. // we want to reverse this for the plain text arena of emails.
  1280. $blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
  1281. $comment_content = wp_specialchars_decode( $comment->comment_content );
  1282. switch ( $comment->comment_type ) {
  1283. case 'trackback':
  1284. /* translators: 1: Post title */
  1285. $notify_message = sprintf( __( 'New trackback on your post "%s"' ), $post->post_title ) . "\r\n";
  1286. /* translators: 1: Trackback/pingback website name, 2: website IP address, 3: website hostname */
  1287. $notify_message .= sprintf( __('Website: %1$s (IP address: %2$s, %3$s)'), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n";
  1288. $notify_message .= sprintf( __( 'URL: %s' ), $comment->comment_author_url ) . "\r\n";
  1289. $notify_message .= sprintf( __( 'Comment: %s' ), "\r\n" . $comment_content ) . "\r\n\r\n";
  1290. $notify_message .= __( 'You can see all trackbacks on this post here:' ) . "\r\n";
  1291. /* translators: 1: blog name, 2: post title */
  1292. $subject = sprintf( __('[%1$s] Trackback: "%2$s"'), $blogname, $post->post_title );
  1293. break;
  1294. case 'pingback':
  1295. /* translators: 1: Post title */
  1296. $notify_message = sprintf( __( 'New pingback on your post "%s"' ), $post->post_title ) . "\r\n";
  1297. /* translators: 1: Trackback/pingback website name, 2: website IP address, 3: website hostname */
  1298. $notify_message .= sprintf( __('Website: %1$s (IP address: %2$s, %3$s)'), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n";
  1299. $notify_message .= sprintf( __( 'URL: %s' ), $comment->comment_author_url ) . "\r\n";
  1300. $notify_message .= sprintf( __( 'Comment: %s' ), "\r\n" . $comment_content ) . "\r\n\r\n";
  1301. $notify_message .= __( 'You can see all pingbacks on this post here:' ) . "\r\n";
  1302. /* translators: 1: blog name, 2: post title */
  1303. $subject = sprintf( __('[%1$s] Pingback: "%2$s"'), $blogname, $post->post_title );
  1304. break;
  1305. default: // Comments
  1306. $notify_message = sprintf( __( 'New comment on your post "%s"' ), $post->post_title ) . "\r\n";
  1307. /* translators: 1: comment author, 2: comment author's IP address, 3: comment author's hostname */
  1308. $notify_message .= sprintf( __( 'Author: %1$s (IP address: %2$s, %3$s)' ), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n";
  1309. $notify_message .= sprintf( __( 'Email: %s' ), $comment->comment_author_email ) . "\r\n";
  1310. $notify_message .= sprintf( __( 'URL: %s' ), $comment->comment_author_url ) . "\r\n";
  1311. $notify_message .= sprintf( __('Comment: %s' ), "\r\n" . $comment_content ) . "\r\n\r\n";
  1312. $notify_message .= __( 'You can see all comments on this post here:' ) . "\r\n";
  1313. /* translators: 1: blog name, 2: post title */
  1314. $subject = sprintf( __('[%1$s] Comment: "%2$s"'), $blogname, $post->post_title );
  1315. break;
  1316. }
  1317. $notify_message .= get_permalink($comment->comment_post_ID) . "#comments\r\n\r\n";
  1318. $notify_message .= sprintf( __('Permalink: %s'), get_comment_link( $comment ) ) . "\r\n";
  1319. if ( user_can( $post->post_author, 'edit_comment', $comment->comment_ID ) ) {
  1320. if ( EMPTY_TRASH_DAYS ) {
  1321. $notify_message .= sprintf( __( 'Trash it: %s' ), admin_url( "comment.php?action=trash&c={$comment->comment_ID}#wpbody-content" ) ) . "\r\n";
  1322. } else {
  1323. $notify_message .= sprintf( __( 'Delete it: %s' ), admin_url( "comment.php?action=delete&c={$comment->comment_ID}#wpbody-content" ) ) . "\r\n";
  1324. }
  1325. $notify_message .= sprintf( __( 'Spam it: %s' ), admin_url( "comment.php?action=spam&c={$comment->comment_ID}#wpbody-content" ) ) . "\r\n";
  1326. }
  1327. $wp_email = 'wordpress@' . preg_replace('#^www\.#', '', strtolower($_SERVER['SERVER_NAME']));
  1328. if ( '' == $comment->comment_author ) {
  1329. $from = "From: \"$blogname\" <$wp_email>";
  1330. if ( '' != $comment->comment_author_email )
  1331. $reply_to = "Reply-To: $comment->comment_author_email";
  1332. } else {
  1333. $from = "From: \"$comment->comment_author\" <$wp_email>";
  1334. if ( '' != $comment->comment_author_email )
  1335. $reply_to = "Reply-To: \"$comment->comment_author_email\" <$comment->comment_author_email>";
  1336. }
  1337. $message_headers = "$from\n"
  1338. . "Content-Type: text/plain; charset=\"" . get_option('blog_charset') . "\"\n";
  1339. if ( isset($reply_to) )
  1340. $message_headers .= $reply_to . "\n";
  1341. /**
  1342. * Filters the comment notification email text.
  1343. *
  1344. * @since 1.5.2
  1345. *
  1346. * @param string $notify_message The comment notification email text.
  1347. * @param int $comment_id Comment ID.
  1348. */
  1349. $notify_message = apply_filters( 'comment_notification_text', $notify_message, $comment->comment_ID );
  1350. /**
  1351. * Filters the comment notification email subject.
  1352. *
  1353. * @since 1.5.2
  1354. *
  1355. * @param string $subject The comment notification email subject.
  1356. * @param int $comment_id Comment ID.
  1357. */
  1358. $subject = apply_filters( 'comment_notification_subject', $subject, $comment->comment_ID );
  1359. /**
  1360. * Filters the comment notification email headers.
  1361. *
  1362. * @since 1.5.2
  1363. *
  1364. * @param string $message_headers Headers for the comment notification email.
  1365. * @param int $comment_id Comment ID.
  1366. */
  1367. $message_headers = apply_filters( 'comment_notification_headers', $message_headers, $comment->comment_ID );
  1368. foreach ( $emails as $email ) {
  1369. @wp_mail( $email, wp_specialchars_decode( $subject ), $notify_message, $message_headers );
  1370. }
  1371. if ( $switched_locale ) {
  1372. restore_previous_locale();
  1373. }
  1374. return true;
  1375. }
  1376. endif;
  1377. if ( !function_exists('wp_notify_moderator') ) :
  1378. /**
  1379. * Notifies the moderator of the site about a new comment that is awaiting approval.
  1380. *
  1381. * @since 1.0.0
  1382. *
  1383. * @global wpdb $wpdb WordPress database abstraction object.
  1384. *
  1385. * Uses the {@see 'notify_moderator'} filter to determine whether the site moderator
  1386. * should be notified, overriding the site setting.
  1387. *
  1388. * @param int $comment_id Comment ID.
  1389. * @return true Always returns true.
  1390. */
  1391. function wp_notify_moderator($comment_id) {
  1392. global $wpdb;
  1393. $maybe_notify = get_option( 'moderation_notify' );
  1394. /**
  1395. * Filters whether to send the site moderator email notifications, overriding the site setting.
  1396. *
  1397. * @since 4.4.0
  1398. *
  1399. * @param bool $maybe_notify Whether to notify blog moderator.
  1400. * @param int $comment_ID The id of the comment for the notification.
  1401. */
  1402. $maybe_notify = apply_filters( 'notify_moderator', $maybe_notify, $comment_id );
  1403. if ( ! $maybe_notify ) {
  1404. return true;
  1405. }
  1406. $comment = get_comment($comment_id);
  1407. $post = get_post($comment->comment_post_ID);
  1408. $user = get_userdata( $post->post_author );
  1409. // Send to the administration and to the post author if the author can modify the comment.
  1410. $emails = array( get_option( 'admin_email' ) );
  1411. if ( $user && user_can( $user->ID, 'edit_comment', $comment_id ) && ! empty( $user->user_email ) ) {
  1412. if ( 0 !== strcasecmp( $user->user_email, get_option( 'admin_email' ) ) )
  1413. $emails[] = $user->user_email;
  1414. }
  1415. $switched_locale = switch_to_locale( get_locale() );
  1416. $comment_author_domain = @gethostbyaddr($comment->comment_author_IP);
  1417. $comments_waiting = $wpdb->get_var("SELECT count(comment_ID) FROM $wpdb->comments WHERE comment_approved = '0'");
  1418. // The blogname option is escaped with esc_html on the way into the database in sanitize_option
  1419. // we want to reverse this for the plain text arena of emails.
  1420. $blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
  1421. $comment_content = wp_specialchars_decode( $comment->comment_content );
  1422. switch ( $comment->comment_type ) {
  1423. case 'trackback':
  1424. /* translators: 1: Post title */
  1425. $notify_message = sprintf( __('A new trackback on the post "%s" is waiting for your approval'), $post->post_title ) . "\r\n";
  1426. $notify_message .= get_permalink($comment->comment_post_ID) . "\r\n\r\n";
  1427. /* translators: 1: Trackback/pingback website name, 2: website IP address, 3: website hostname */
  1428. $notify_message .= sprintf( __( 'Website: %1$s (IP address: %2$s, %3$s)' ), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n";
  1429. /* translators: 1: Trackback/pingback/comment author URL */
  1430. $notify_message .= sprintf( __( 'URL: %s' ), $comment->comment_author_url ) . "\r\n";
  1431. $notify_message .= __('Trackback excerpt: ') . "\r\n" . $comment_content . "\r\n\r\n";
  1432. break;
  1433. case 'pingback':
  1434. /* translators: 1: Post title */
  1435. $notify_message = sprintf( __('A new pingback on the post "%s" is waiting for your approval'), $post->post_title ) . "\r\n";
  1436. $notify_message .= get_permalink($comment->comment_post_ID) . "\r\n\r\n";
  1437. /* translators: 1: Trackback/pingback website name, 2: website IP address, 3: website hostname */
  1438. $notify_message .= sprintf( __( 'Website: %1$s (IP address: %2$s, %3$s)' ), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n";
  1439. /* translators: 1: Trackback/pingback/comment author URL */
  1440. $notify_message .= sprintf( __( 'URL: %s' ), $comment->comment_author_url ) . "\r\n";
  1441. $notify_message .= __('Pingback excerpt: ') . "\r\n" . $comment_content . "\r\n\r\n";
  1442. break;
  1443. default: // Comments
  1444. /* translators: 1: Post title */
  1445. $notify_message = sprintf( __('A new comment on the post "%s" is waiting for your approval'), $post->post_title ) . "\r\n";
  1446. $notify_message .= get_permalink($comment->comment_post_ID) . "\r\n\r\n";
  1447. /* translators: 1: Comment author name, 2: comment author's IP address, 3: comment author's hostname */
  1448. $notify_message .= sprintf( __( 'Author: %1$s (IP address: %2$s, %3$s)' ), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n";
  1449. /* translators: 1: Comment author URL */
  1450. $notify_message .= sprintf( __( 'Email: %s' ), $comment->comment_author_email ) . "\r\n";
  1451. /* translators: 1: Trackback/pingback/comment author URL */
  1452. $notify_message .= sprintf( __( 'URL: %s' ), $comment->comment_author_url ) . "\r\n";
  1453. /* translators: 1: Comment text */
  1454. $notify_message .= sprintf( __( 'Comment: %s' ), "\r\n" . $comment_content ) . "\r\n\r\n";
  1455. break;
  1456. }
  1457. /* translators: Comment moderation. 1: Comment action URL */
  1458. $notify_message .= sprintf( __( 'Approve it: %s' ), admin_url( "comment.php?action=approve&c={$comment_id}#wpbody-content" ) ) . "\r\n";
  1459. if ( EMPTY_TRASH_DAYS ) {
  1460. /* translators: Comment moderation. 1: Comment action URL */
  1461. $notify_message .= sprintf( __( 'Trash it: %s' ), admin_url( "comment.php?action=trash&c={$comment_id}#wpbody-content" ) ) . "\r\n";
  1462. } else {
  1463. /* translators: Comment moderation. 1: Comment action URL */
  1464. $notify_message .= sprintf( __( 'Delete it: %s' ), admin_url( "comment.php?action=delete&c={$comment_id}#wpbody-content" ) ) . "\r\n";
  1465. }
  1466. /* translators: Comment moderation. 1: Comment action URL */
  1467. $notify_message .= sprintf( __( 'Spam it: %s' ), admin_url( "comment.php?action=spam&c={$comment_id}#wpbody-content" ) ) . "\r\n";
  1468. /* translators: Comment moderation. 1: Number of comments awaiting approval */
  1469. $notify_message .= sprintf( _n('Currently %s comment is waiting for approval. Please visit the moderation panel:',
  1470. 'Currently %s comments are waiting for approval. Please visit the moderation panel:', $comments_waiting), number_format_i18n($comments_waiting) ) . "\r\n";
  1471. $notify_message .= admin_url( "edit-comments.php?comment_status=moderated#wpbody-content" ) . "\r\n";
  1472. /* translators: Comment moderation notification email subject. 1: Site name, 2: Post title */
  1473. $subject = sprintf( __('[%1$s] Please moderate: "%2$s"'), $blogname, $post->post_title );
  1474. $message_headers = '';
  1475. /**
  1476. * Filters the list of recipients for comment moderation emails.
  1477. *
  1478. * @since 3.7.0
  1479. *
  1480. * @param array $emails List of email addresses to notify for comment moderation.
  1481. * @param int $comment_id Comment ID.
  1482. */
  1483. $emails = apply_filters( 'comment_moderation_recipients', $emails, $comment_id );
  1484. /**
  1485. * Filters the comment moderation email text.
  1486. *
  1487. * @since 1.5.2
  1488. *
  1489. * @param string $notify_message Text of the comment moderation email.
  1490. * @param int $comment_id Comment ID.
  1491. */
  1492. $notify_message = apply_filters( 'comment_moderation_text', $notify_message, $comment_id );
  1493. /**
  1494. * Filters the comment moderation email subject.
  1495. *
  1496. * @since 1.5.2
  1497. *
  1498. * @param string $subject Subject of the comment moderation email.
  1499. * @param int $comment_id Comment ID.
  1500. */
  1501. $subject = apply_filters( 'comment_moderation_subject', $subject, $comment_id );
  1502. /**
  1503. * Filters the comment moderation email headers.
  1504. *
  1505. * @since 2.8.0
  1506. *
  1507. * @param string $message_headers Headers for the comment moderation email.
  1508. * @param int $comment_id Comment ID.
  1509. */
  1510. $message_headers = apply_filters( 'comment_moderation_headers', $message_headers, $comment_id );
  1511. foreach ( $emails as $email ) {
  1512. @wp_mail( $email, wp_specialchars_decode( $subject ), $notify_message, $message_headers );
  1513. }
  1514. if ( $switched_locale ) {
  1515. restore_previous_locale();
  1516. }
  1517. return true;
  1518. }
  1519. endif;
  1520. if ( !function_exists('wp_password_change_notification') ) :
  1521. /**
  1522. * Notify the blog admin of a user changing password, normally via email.
  1523. *
  1524. * @since 2.7.0
  1525. *
  1526. * @param WP_User $user User object.
  1527. */
  1528. function wp_password_change_notification( $user ) {
  1529. // send a copy of password change notification to the admin
  1530. // but check to see if it's the admin whose password we're changing, and skip this
  1531. if ( 0 !== strcasecmp( $user->user_email, get_option( 'admin_email' ) ) ) {
  1532. /* translators: %s: user name */
  1533. $message = sprintf( __( 'Password changed for user: %s' ), $user->user_login ) . "\r\n";
  1534. // The blogname option is escaped with esc_html on the way into the database in sanitize_option
  1535. // we want to reverse this for the plain text arena of emails.
  1536. $blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
  1537. $wp_password_change_notification_email = array(
  1538. 'to' => get_option( 'admin_email' ),
  1539. /* translators: Password change notification email subject. %s: Site title */
  1540. 'subject' => __( '[%s] Password Changed' ),
  1541. 'message' => $message,
  1542. 'headers' => '',
  1543. );
  1544. /**
  1545. * Filters the contents of the password change notification email sent to the site admin.
  1546. *
  1547. * @since 4.9.0
  1548. *
  1549. * @param array $wp_password_change_notification_email {
  1550. * Used to build wp_mail().
  1551. *
  1552. * @type string $to The intended recipient - site admin email address.
  1553. * @type string $subject The subject of the email.
  1554. * @type string $message The body of the email.
  1555. * @type string $headers The headers of the email.
  1556. * }
  1557. * @param WP_User $user User object for user whose password was changed.
  1558. * @param string $blogname The site title.
  1559. */
  1560. $wp_password_change_notification_email = apply_filters( 'wp_password_change_notification_email', $wp_password_change_notification_email, $user, $blogname );
  1561. wp_mail(
  1562. $wp_password_change_notification_email['to'],
  1563. wp_specialchars_decode( sprintf( $wp_password_change_notification_email['subject'], $blogname ) ),
  1564. $wp_password_change_notification_email['message'],
  1565. $wp_password_change_notification_email['headers']
  1566. );
  1567. }
  1568. }
  1569. endif;
  1570. if ( !function_exists('wp_new_user_notification') ) :
  1571. /**
  1572. * Email login credentials to a newly-registered user.
  1573. *
  1574. * A new user registration notification is also sent to admin email.
  1575. *
  1576. * @since 2.0.0
  1577. * @since 4.3.0 The `$plaintext_pass` parameter was changed to `$notify`.
  1578. * @since 4.3.1 The `$plaintext_pass` parameter was deprecated. `$notify` added as a third parameter.
  1579. * @since 4.6.0 The `$notify` parameter accepts 'user' for sending notification only to the user created.
  1580. *
  1581. * @global wpdb $wpdb WordPress database object for queries.
  1582. * @global PasswordHash $wp_hasher Portable PHP password hashing framework instance.
  1583. *
  1584. * @param int $user_id User ID.
  1585. * @param null $deprecated Not used (argument deprecated).
  1586. * @param string $notify Optional. Type of notification that should happen. Accepts 'admin' or an empty
  1587. * string (admin only), 'user', or 'both' (admin and user). Default empty.
  1588. */
  1589. function wp_new_user_notification( $user_id, $deprecated = null, $notify = '' ) {
  1590. if ( $deprecated !== null ) {
  1591. _deprecated_argument( __FUNCTION__, '4.3.1' );
  1592. }
  1593. global $wpdb, $wp_hasher;
  1594. $user = get_userdata( $user_id );
  1595. // The blogname option is escaped with esc_html on the way into the database in sanitize_option
  1596. // we want to reverse this for the plain text arena of emails.
  1597. $blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
  1598. if ( 'user' !== $notify ) {
  1599. $switched_locale = switch_to_locale( get_locale() );
  1600. /* translators: %s: site title */
  1601. $message = sprintf( __( 'New user registration on your site %s:' ), $blogname ) . "\r\n\r\n";
  1602. /* translators: %s: user login */
  1603. $message .= sprintf( __( 'Username: %s' ), $user->user_login ) . "\r\n\r\n";
  1604. /* translators: %s: user email address */
  1605. $message .= sprintf( __( 'Email: %s' ), $user->user_email ) . "\r\n";
  1606. $wp_new_user_notification_email_admin = array(
  1607. 'to' => get_option( 'admin_email' ),
  1608. /* translators: Password change notification email subject. %s: Site title */
  1609. 'subject' => __( '[%s] New User Registration' ),
  1610. 'message' => $message,
  1611. 'headers' => '',
  1612. );
  1613. /**
  1614. * Filters the contents of the new user notification email sent to the site admin.
  1615. *
  1616. * @since 4.9.0
  1617. *
  1618. * @param array $wp_new_user_notification_email {
  1619. * Used to build wp_mail().
  1620. *
  1621. * @type string $to The intended recipient - site admin email address.
  1622. * @type string $subject The subject of the email.
  1623. * @type string $message The body of the email.
  1624. * @type string $headers The headers of the email.
  1625. * }
  1626. * @param WP_User $user User object for new user.
  1627. * @param string $blogname The site title.
  1628. */
  1629. $wp_new_user_notification_email_admin = apply_filters( 'wp_new_user_notification_email_admin', $wp_new_user_notification_email_admin, $user, $blogname );
  1630. @wp_mail(
  1631. $wp_new_user_notification_email_admin['to'],
  1632. wp_specialchars_decode( sprintf( $wp_new_user_notification_email_admin['subject'], $blogname ) ),
  1633. $wp_new_user_notification_email_admin['message'],
  1634. $wp_new_user_notification_email_admin['headers']
  1635. );
  1636. if ( $switched_locale ) {
  1637. restore_previous_locale();
  1638. }
  1639. }
  1640. // `$deprecated was pre-4.3 `$plaintext_pass`. An empty `$plaintext_pass` didn't sent a user notification.
  1641. if ( 'admin' === $notify || ( empty( $deprecated ) && empty( $notify ) ) ) {
  1642. return;
  1643. }
  1644. // Generate something random for a password reset key.
  1645. $key = wp_generate_password( 20, false );
  1646. /** This action is documented in wp-login.php */
  1647. do_action( 'retrieve_password_key', $user->user_login, $key );
  1648. // Now insert the key, hashed, into the DB.
  1649. if ( empty( $wp_hasher ) ) {
  1650. require_once ABSPATH . WPINC . '/class-phpass.php';
  1651. $wp_hasher = new PasswordHash( 8, true );
  1652. }
  1653. $hashed = time() . ':' . $wp_hasher->HashPassword( $key );
  1654. $wpdb->update( $wpdb->users, array( 'user_activation_key' => $hashed ), array( 'user_login' => $user->user_login ) );
  1655. $switched_locale = switch_to_locale( get_user_locale( $user ) );
  1656. /* translators: %s: user login */
  1657. $message = sprintf(__('Username: %s'), $user->user_login) . "\r\n\r\n";
  1658. $message .= __('To set your password, visit the following address:') . "\r\n\r\n";
  1659. $message .= '<' . network_site_url("wp-login.php?action=rp&key=$key&login=" . rawurlencode($user->user_login), 'login') . ">\r\n\r\n";
  1660. $message .= wp_login_url() . "\r\n";
  1661. $wp_new_user_notification_email = array(
  1662. 'to' => $user->user_email,
  1663. /* translators: Password change notification email subject. %s: Site title */
  1664. 'subject' => __( '[%s] Your username and password info' ),
  1665. 'message' => $message,
  1666. 'headers' => '',
  1667. );
  1668. /**
  1669. * Filters the contents of the new user notification email sent to the new user.
  1670. *
  1671. * @since 4.9.0
  1672. *
  1673. * @param array $wp_new_user_notification_email {
  1674. * Used to build wp_mail().
  1675. *
  1676. * @type string $to The intended recipient - New user email address.
  1677. * @type string $subject The subject of the email.
  1678. * @type string $message The body of the email.
  1679. * @type string $headers The headers of the email.
  1680. * }
  1681. * @param WP_User $user User object for new user.
  1682. * @param string $blogname The site title.
  1683. */
  1684. $wp_new_user_notification_email = apply_filters( 'wp_new_user_notification_email', $wp_new_user_notification_email, $user, $blogname );
  1685. wp_mail(
  1686. $wp_new_user_notification_email['to'],
  1687. wp_specialchars_decode( sprintf( $wp_new_user_notification_email['subject'], $blogname ) ),
  1688. $wp_new_user_notification_email['message'],
  1689. $wp_new_user_notification_email['headers']
  1690. );
  1691. if ( $switched_locale ) {
  1692. restore_previous_locale();
  1693. }
  1694. }
  1695. endif;
  1696. if ( !function_exists('wp_nonce_tick') ) :
  1697. /**
  1698. * Get the time-dependent variable for nonce creation.
  1699. *
  1700. * A nonce has a lifespan of two ticks. Nonces in their second tick may be
  1701. * updated, e.g. by autosave.
  1702. *
  1703. * @since 2.5.0
  1704. *
  1705. * @return float Float value rounded up to the next highest integer.
  1706. */
  1707. function wp_nonce_tick() {
  1708. /**
  1709. * Filters the lifespan of nonces in seconds.
  1710. *
  1711. * @since 2.5.0
  1712. *
  1713. * @param int $lifespan Lifespan of nonces in seconds. Default 86,400 seconds, or one day.
  1714. */
  1715. $nonce_life = apply_filters( 'nonce_life', DAY_IN_SECONDS );
  1716. return ceil(time() / ( $nonce_life / 2 ));
  1717. }
  1718. endif;
  1719. if ( !function_exists('wp_verify_nonce') ) :
  1720. /**
  1721. * Verify that correct nonce was used with time limit.
  1722. *
  1723. * The user is given an amount of time to use the token, so therefore, since the
  1724. * UID and $action remain the same, the independent variable is the time.
  1725. *
  1726. * @since 2.0.3
  1727. *
  1728. * @param string $nonce Nonce that was used in the form to verify
  1729. * @param string|int $action Should give context to what is taking place and be the same when nonce was created.
  1730. * @return false|int False if the nonce is invalid, 1 if the nonce is valid and generated between
  1731. * 0-12 hours ago, 2 if the nonce is valid and generated between 12-24 hours ago.
  1732. */
  1733. function wp_verify_nonce( $nonce, $action = -1 ) {
  1734. $nonce = (string) $nonce;
  1735. $user = wp_get_current_user();
  1736. $uid = (int) $user->ID;
  1737. if ( ! $uid ) {
  1738. /**
  1739. * Filters whether the user who generated the nonce is logged out.
  1740. *
  1741. * @since 3.5.0
  1742. *
  1743. * @param int $uid ID of the nonce-owning user.
  1744. * @param string $action The nonce action.
  1745. */
  1746. $uid = apply_filters( 'nonce_user_logged_out', $uid, $action );
  1747. }
  1748. if ( empty( $nonce ) ) {
  1749. return false;
  1750. }
  1751. $token = wp_get_session_token();
  1752. $i = wp_nonce_tick();
  1753. // Nonce generated 0-12 hours ago
  1754. $expected = substr( wp_hash( $i . '|' . $action . '|' . $uid . '|' . $token, 'nonce'), -12, 10 );
  1755. if ( hash_equals( $expected, $nonce ) ) {
  1756. return 1;
  1757. }
  1758. // Nonce generated 12-24 hours ago
  1759. $expected = substr( wp_hash( ( $i - 1 ) . '|' . $action . '|' . $uid . '|' . $token, 'nonce' ), -12, 10 );
  1760. if ( hash_equals( $expected, $nonce ) ) {
  1761. return 2;
  1762. }
  1763. /**
  1764. * Fires when nonce verification fails.
  1765. *
  1766. * @since 4.4.0
  1767. *
  1768. * @param string $nonce The invalid nonce.
  1769. * @param string|int $action The nonce action.
  1770. * @param WP_User $user The current user object.
  1771. * @param string $token The user's session token.
  1772. */
  1773. do_action( 'wp_verify_nonce_failed', $nonce, $action, $user, $token );
  1774. // Invalid nonce
  1775. return false;
  1776. }
  1777. endif;
  1778. if ( !function_exists('wp_create_nonce') ) :
  1779. /**
  1780. * Creates a cryptographic token tied to a specific action, user, user session,
  1781. * and window of time.
  1782. *
  1783. * @since 2.0.3
  1784. * @since 4.0.0 Session tokens were integrated with nonce creation
  1785. *
  1786. * @param string|int $action Scalar value to add context to the nonce.
  1787. * @return string The token.
  1788. */
  1789. function wp_create_nonce($action = -1) {
  1790. $user = wp_get_current_user();
  1791. $uid = (int) $user->ID;
  1792. if ( ! $uid ) {
  1793. /** This filter is documented in wp-includes/pluggable.php */
  1794. $uid = apply_filters( 'nonce_user_logged_out', $uid, $action );
  1795. }
  1796. $token = wp_get_session_token();
  1797. $i = wp_nonce_tick();
  1798. return substr( wp_hash( $i . '|' . $action . '|' . $uid . '|' . $token, 'nonce' ), -12, 10 );
  1799. }
  1800. endif;
  1801. if ( !function_exists('wp_salt') ) :
  1802. /**
  1803. * Get salt to add to hashes.
  1804. *
  1805. * Salts are created using secret keys. Secret keys are located in two places:
  1806. * in the database and in the wp-config.php file. The secret key in the database
  1807. * is randomly generated and will be appended to the secret keys in wp-config.php.
  1808. *
  1809. * The secret keys in wp-config.php should be updated to strong, random keys to maximize
  1810. * security. Below is an example of how the secret key constants are defined.
  1811. * Do not paste this example directly into wp-config.php. Instead, have a
  1812. * {@link https://api.wordpress.org/secret-key/1.1/salt/ secret key created} just
  1813. * for you.
  1814. *
  1815. * define('AUTH_KEY', ' Xakm<o xQy rw4EMsLKM-?!T+,PFF})H4lzcW57AF0U@N@< >M%G4Yt>f`z]MON');
  1816. * define('SECURE_AUTH_KEY', 'LzJ}op]mr|6+![P}Ak:uNdJCJZd>(Hx.-Mh#Tz)pCIU#uGEnfFz|f ;;eU%/U^O~');
  1817. * define('LOGGED_IN_KEY', '|i|Ux`9<p-h$aFf(qnT:sDO:D1P^wZ$$/Ra@miTJi9G;ddp_<q}6H1)o|a +&JCM');
  1818. * define('NONCE_KEY', '%:R{[P|,s.KuMltH5}cI;/k<Gx~j!f0I)m_sIyu+&NJZ)-iO>z7X>QYR0Z_XnZ@|');
  1819. * define('AUTH_SALT', 'eZyT)-Naw]F8CwA*VaW#q*|.)g@o}||wf~@C-YSt}(dh_r6EbI#A,y|nU2{B#JBW');
  1820. * define('SECURE_AUTH_SALT', '!=oLUTXh,QW=H `}`L|9/^4-3 STz},T(w}W<I`.JjPi)<Bmf1v,HpGe}T1:Xt7n');
  1821. * define('LOGGED_IN_SALT', '+XSqHc;@Q*K_b|Z?NC[3H!!EONbh.n<+=uKR:>*c(u`g~EJBf#8u#R{mUEZrozmm');
  1822. * define('NONCE_SALT', 'h`GXHhD>SLWVfg1(1(N{;.V!MoE(SfbA_ksP@&`+AycHcAV$+?@3q+rxV{%^VyKT');
  1823. *
  1824. * Salting passwords helps against tools which has stored hashed values of
  1825. * common dictionary strings. The added values makes it harder to crack.
  1826. *
  1827. * @since 2.5.0
  1828. *
  1829. * @link https://api.wordpress.org/secret-key/1.1/salt/ Create secrets for wp-config.php
  1830. *
  1831. * @staticvar array $cached_salts
  1832. * @staticvar array $duplicated_keys
  1833. *
  1834. * @param string $scheme Authentication scheme (auth, secure_auth, logged_in, nonce)
  1835. * @return string Salt value
  1836. */
  1837. function wp_salt( $scheme = 'auth' ) {
  1838. static $cached_salts = array();
  1839. if ( isset( $cached_salts[ $scheme ] ) ) {
  1840. /**
  1841. * Filters the WordPress salt.
  1842. *
  1843. * @since 2.5.0
  1844. *
  1845. * @param string $cached_salt Cached salt for the given scheme.
  1846. * @param string $scheme Authentication scheme. Values include 'auth',
  1847. * 'secure_auth', 'logged_in', and 'nonce'.
  1848. */
  1849. return apply_filters( 'salt', $cached_salts[ $scheme ], $scheme );
  1850. }
  1851. static $duplicated_keys;
  1852. if ( null === $duplicated_keys ) {
  1853. $duplicated_keys = array( 'put your unique phrase here' => true );
  1854. foreach ( array( 'AUTH', 'SECURE_AUTH', 'LOGGED_IN', 'NONCE', 'SECRET' ) as $first ) {
  1855. foreach ( array( 'KEY', 'SALT' ) as $second ) {
  1856. if ( ! defined( "{$first}_{$second}" ) ) {
  1857. continue;
  1858. }
  1859. $value = constant( "{$first}_{$second}" );
  1860. $duplicated_keys[ $value ] = isset( $duplicated_keys[ $value ] );
  1861. }
  1862. }
  1863. }
  1864. $values = array(
  1865. 'key' => '',
  1866. 'salt' => ''
  1867. );
  1868. if ( defined( 'SECRET_KEY' ) && SECRET_KEY && empty( $duplicated_keys[ SECRET_KEY ] ) ) {
  1869. $values['key'] = SECRET_KEY;
  1870. }
  1871. if ( 'auth' == $scheme && defined( 'SECRET_SALT' ) && SECRET_SALT && empty( $duplicated_keys[ SECRET_SALT ] ) ) {
  1872. $values['salt'] = SECRET_SALT;
  1873. }
  1874. if ( in_array( $scheme, array( 'auth', 'secure_auth', 'logged_in', 'nonce' ) ) ) {
  1875. foreach ( array( 'key', 'salt' ) as $type ) {
  1876. $const = strtoupper( "{$scheme}_{$type}" );
  1877. if ( defined( $const ) && constant( $const ) && empty( $duplicated_keys[ constant( $const ) ] ) ) {
  1878. $values[ $type ] = constant( $const );
  1879. } elseif ( ! $values[ $type ] ) {
  1880. $values[ $type ] = get_site_option( "{$scheme}_{$type}" );
  1881. if ( ! $values[ $type ] ) {
  1882. $values[ $type ] = wp_generate_password( 64, true, true );
  1883. update_site_option( "{$scheme}_{$type}", $values[ $type ] );
  1884. }
  1885. }
  1886. }
  1887. } else {
  1888. if ( ! $values['key'] ) {
  1889. $values['key'] = get_site_option( 'secret_key' );
  1890. if ( ! $values['key'] ) {
  1891. $values['key'] = wp_generate_password( 64, true, true );
  1892. update_site_option( 'secret_key', $values['key'] );
  1893. }
  1894. }
  1895. $values['salt'] = hash_hmac( 'md5', $scheme, $values['key'] );
  1896. }
  1897. $cached_salts[ $scheme ] = $values['key'] . $values['salt'];
  1898. /** This filter is documented in wp-includes/pluggable.php */
  1899. return apply_filters( 'salt', $cached_salts[ $scheme ], $scheme );
  1900. }
  1901. endif;
  1902. if ( !function_exists('wp_hash') ) :
  1903. /**
  1904. * Get hash of given string.
  1905. *
  1906. * @since 2.0.3
  1907. *
  1908. * @param string $data Plain text to hash
  1909. * @param string $scheme Authentication scheme (auth, secure_auth, logged_in, nonce)
  1910. * @return string Hash of $data
  1911. */
  1912. function wp_hash($data, $scheme = 'auth') {
  1913. $salt = wp_salt($scheme);
  1914. return hash_hmac('md5', $data, $salt);
  1915. }
  1916. endif;
  1917. if ( !function_exists('wp_hash_password') ) :
  1918. /**
  1919. * Create a hash (encrypt) of a plain text password.
  1920. *
  1921. * For integration with other applications, this function can be overwritten to
  1922. * instead use the other package password checking algorithm.
  1923. *
  1924. * @since 2.5.0
  1925. *
  1926. * @global PasswordHash $wp_hasher PHPass object
  1927. *
  1928. * @param string $password Plain text user password to hash
  1929. * @return string The hash string of the password
  1930. */
  1931. function wp_hash_password($password) {
  1932. global $wp_hasher;
  1933. if ( empty($wp_hasher) ) {
  1934. require_once( ABSPATH . WPINC . '/class-phpass.php');
  1935. // By default, use the portable hash from phpass
  1936. $wp_hasher = new PasswordHash(8, true);
  1937. }
  1938. return $wp_hasher->HashPassword( trim( $password ) );
  1939. }
  1940. endif;
  1941. if ( !function_exists('wp_check_password') ) :
  1942. /**
  1943. * Checks the plaintext password against the encrypted Password.
  1944. *
  1945. * Maintains compatibility between old version and the new cookie authentication
  1946. * protocol using PHPass library. The $hash parameter is the encrypted password
  1947. * and the function compares the plain text password when encrypted similarly
  1948. * against the already encrypted password to see if they match.
  1949. *
  1950. * For integration with other applications, this function can be overwritten to
  1951. * instead use the other package password checking algorithm.
  1952. *
  1953. * @since 2.5.0
  1954. *
  1955. * @global PasswordHash $wp_hasher PHPass object used for checking the password
  1956. * against the $hash + $password
  1957. * @uses PasswordHash::CheckPassword
  1958. *
  1959. * @param string $password Plaintext user's password
  1960. * @param string $hash Hash of the user's password to check against.
  1961. * @param string|int $user_id Optional. User ID.
  1962. * @return bool False, if the $password does not match the hashed password
  1963. */
  1964. function wp_check_password($password, $hash, $user_id = '') {
  1965. global $wp_hasher;
  1966. // If the hash is still md5...
  1967. if ( strlen($hash) <= 32 ) {
  1968. $check = hash_equals( $hash, md5( $password ) );
  1969. if ( $check && $user_id ) {
  1970. // Rehash using new hash.
  1971. wp_set_password($password, $user_id);
  1972. $hash = wp_hash_password($password);
  1973. }
  1974. /**
  1975. * Filters whether the plaintext password matches the encrypted password.
  1976. *
  1977. * @since 2.5.0
  1978. *
  1979. * @param bool $check Whether the passwords match.
  1980. * @param string $password The plaintext password.
  1981. * @param string $hash The hashed password.
  1982. * @param string|int $user_id User ID. Can be empty.
  1983. */
  1984. return apply_filters( 'check_password', $check, $password, $hash, $user_id );
  1985. }
  1986. // If the stored hash is longer than an MD5, presume the
  1987. // new style phpass portable hash.
  1988. if ( empty($wp_hasher) ) {
  1989. require_once( ABSPATH . WPINC . '/class-phpass.php');
  1990. // By default, use the portable hash from phpass
  1991. $wp_hasher = new PasswordHash(8, true);
  1992. }
  1993. $check = $wp_hasher->CheckPassword($password, $hash);
  1994. /** This filter is documented in wp-includes/pluggable.php */
  1995. return apply_filters( 'check_password', $check, $password, $hash, $user_id );
  1996. }
  1997. endif;
  1998. if ( !function_exists('wp_generate_password') ) :
  1999. /**
  2000. * Generates a random password drawn from the defined set of characters.
  2001. *
  2002. * @since 2.5.0
  2003. *
  2004. * @param int $length Optional. The length of password to generate. Default 12.
  2005. * @param bool $special_chars Optional. Whether to include standard special characters.
  2006. * Default true.
  2007. * @param bool $extra_special_chars Optional. Whether to include other special characters.
  2008. * Used when generating secret keys and salts. Default false.
  2009. * @return string The random password.
  2010. */
  2011. function wp_generate_password( $length = 12, $special_chars = true, $extra_special_chars = false ) {
  2012. $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  2013. if ( $special_chars )
  2014. $chars .= '!@#$%^&*()';
  2015. if ( $extra_special_chars )
  2016. $chars .= '-_ []{}<>~`+=,.;:/?|';
  2017. $password = '';
  2018. for ( $i = 0; $i < $length; $i++ ) {
  2019. $password .= substr($chars, wp_rand(0, strlen($chars) - 1), 1);
  2020. }
  2021. /**
  2022. * Filters the randomly-generated password.
  2023. *
  2024. * @since 3.0.0
  2025. *
  2026. * @param string $password The generated password.
  2027. */
  2028. return apply_filters( 'random_password', $password );
  2029. }
  2030. endif;
  2031. if ( !function_exists('wp_rand') ) :
  2032. /**
  2033. * Generates a random number
  2034. *
  2035. * @since 2.6.2
  2036. * @since 4.4.0 Uses PHP7 random_int() or the random_compat library if available.
  2037. *
  2038. * @global string $rnd_value
  2039. * @staticvar string $seed
  2040. * @staticvar bool $external_rand_source_available
  2041. *
  2042. * @param int $min Lower limit for the generated number
  2043. * @param int $max Upper limit for the generated number
  2044. * @return int A random number between min and max
  2045. */
  2046. function wp_rand( $min = 0, $max = 0 ) {
  2047. global $rnd_value;
  2048. // Some misconfigured 32bit environments (Entropy PHP, for example) truncate integers larger than PHP_INT_MAX to PHP_INT_MAX rather than overflowing them to floats.
  2049. $max_random_number = 3000000000 === 2147483647 ? (float) "4294967295" : 4294967295; // 4294967295 = 0xffffffff
  2050. // We only handle Ints, floats are truncated to their integer value.
  2051. $min = (int) $min;
  2052. $max = (int) $max;
  2053. // Use PHP's CSPRNG, or a compatible method
  2054. static $use_random_int_functionality = true;
  2055. if ( $use_random_int_functionality ) {
  2056. try {
  2057. $_max = ( 0 != $max ) ? $max : $max_random_number;
  2058. // wp_rand() can accept arguments in either order, PHP cannot.
  2059. $_max = max( $min, $_max );
  2060. $_min = min( $min, $_max );
  2061. $val = random_int( $_min, $_max );
  2062. if ( false !== $val ) {
  2063. return absint( $val );
  2064. } else {
  2065. $use_random_int_functionality = false;
  2066. }
  2067. } catch ( Error $e ) {
  2068. $use_random_int_functionality = false;
  2069. } catch ( Exception $e ) {
  2070. $use_random_int_functionality = false;
  2071. }
  2072. }
  2073. // Reset $rnd_value after 14 uses
  2074. // 32(md5) + 40(sha1) + 40(sha1) / 8 = 14 random numbers from $rnd_value
  2075. if ( strlen($rnd_value) < 8 ) {
  2076. if ( defined( 'WP_SETUP_CONFIG' ) )
  2077. static $seed = '';
  2078. else
  2079. $seed = get_transient('random_seed');
  2080. $rnd_value = md5( uniqid(microtime() . mt_rand(), true ) . $seed );
  2081. $rnd_value .= sha1($rnd_value);
  2082. $rnd_value .= sha1($rnd_value . $seed);
  2083. $seed = md5($seed . $rnd_value);
  2084. if ( ! defined( 'WP_SETUP_CONFIG' ) && ! defined( 'WP_INSTALLING' ) ) {
  2085. set_transient( 'random_seed', $seed );
  2086. }
  2087. }
  2088. // Take the first 8 digits for our value
  2089. $value = substr($rnd_value, 0, 8);
  2090. // Strip the first eight, leaving the remainder for the next call to wp_rand().
  2091. $rnd_value = substr($rnd_value, 8);
  2092. $value = abs(hexdec($value));
  2093. // Reduce the value to be within the min - max range
  2094. if ( $max != 0 )
  2095. $value = $min + ( $max - $min + 1 ) * $value / ( $max_random_number + 1 );
  2096. return abs(intval($value));
  2097. }
  2098. endif;
  2099. if ( !function_exists('wp_set_password') ) :
  2100. /**
  2101. * Updates the user's password with a new encrypted one.
  2102. *
  2103. * For integration with other applications, this function can be overwritten to
  2104. * instead use the other package password checking algorithm.
  2105. *
  2106. * Please note: This function should be used sparingly and is really only meant for single-time
  2107. * application. Leveraging this improperly in a plugin or theme could result in an endless loop
  2108. * of password resets if precautions are not taken to ensure it does not execute on every page load.
  2109. *
  2110. * @since 2.5.0
  2111. *
  2112. * @global wpdb $wpdb WordPress database abstraction object.
  2113. *
  2114. * @param string $password The plaintext new user password
  2115. * @param int $user_id User ID
  2116. */
  2117. function wp_set_password( $password, $user_id ) {
  2118. global $wpdb;
  2119. $hash = wp_hash_password( $password );
  2120. $wpdb->update($wpdb->users, array('user_pass' => $hash, 'user_activation_key' => ''), array('ID' => $user_id) );
  2121. wp_cache_delete($user_id, 'users');
  2122. }
  2123. endif;
  2124. if ( !function_exists( 'get_avatar' ) ) :
  2125. /**
  2126. * Retrieve the avatar `<img>` tag for a user, email address, MD5 hash, comment, or post.
  2127. *
  2128. * @since 2.5.0
  2129. * @since 4.2.0 Optional `$args` parameter added.
  2130. *
  2131. * @param mixed $id_or_email The Gravatar to retrieve. Accepts a user_id, gravatar md5 hash,
  2132. * user email, WP_User object, WP_Post object, or WP_Comment object.
  2133. * @param int $size Optional. Height and width of the avatar image file in pixels. Default 96.
  2134. * @param string $default Optional. URL for the default image or a default type. Accepts '404'
  2135. * (return a 404 instead of a default image), 'retro' (8bit), 'monsterid'
  2136. * (monster), 'wavatar' (cartoon face), 'indenticon' (the "quilt"),
  2137. * 'mystery', 'mm', or 'mysteryman' (The Oyster Man), 'blank' (transparent GIF),
  2138. * or 'gravatar_default' (the Gravatar logo). Default is the value of the
  2139. * 'avatar_default' option, with a fallback of 'mystery'.
  2140. * @param string $alt Optional. Alternative text to use in &lt;img&gt; tag. Default empty.
  2141. * @param array $args {
  2142. * Optional. Extra arguments to retrieve the avatar.
  2143. *
  2144. * @type int $height Display height of the avatar in pixels. Defaults to $size.
  2145. * @type int $width Display width of the avatar in pixels. Defaults to $size.
  2146. * @type bool $force_default Whether to always show the default image, never the Gravatar. Default false.
  2147. * @type string $rating What rating to display avatars up to. Accepts 'G', 'PG', 'R', 'X', and are
  2148. * judged in that order. Default is the value of the 'avatar_rating' option.
  2149. * @type string $scheme URL scheme to use. See set_url_scheme() for accepted values.
  2150. * Default null.
  2151. * @type array|string $class Array or string of additional classes to add to the &lt;img&gt; element.
  2152. * Default null.
  2153. * @type bool $force_display Whether to always show the avatar - ignores the show_avatars option.
  2154. * Default false.
  2155. * @type string $extra_attr HTML attributes to insert in the IMG element. Is not sanitized. Default empty.
  2156. * }
  2157. * @return false|string `<img>` tag for the user's avatar. False on failure.
  2158. */
  2159. function get_avatar( $id_or_email, $size = 96, $default = '', $alt = '', $args = null ) {
  2160. $defaults = array(
  2161. // get_avatar_data() args.
  2162. 'size' => 96,
  2163. 'height' => null,
  2164. 'width' => null,
  2165. 'default' => get_option( 'avatar_default', 'mystery' ),
  2166. 'force_default' => false,
  2167. 'rating' => get_option( 'avatar_rating' ),
  2168. 'scheme' => null,
  2169. 'alt' => '',
  2170. 'class' => null,
  2171. 'force_display' => false,
  2172. 'extra_attr' => '',
  2173. );
  2174. if ( empty( $args ) ) {
  2175. $args = array();
  2176. }
  2177. $args['size'] = (int) $size;
  2178. $args['default'] = $default;
  2179. $args['alt'] = $alt;
  2180. $args = wp_parse_args( $args, $defaults );
  2181. if ( empty( $args['height'] ) ) {
  2182. $args['height'] = $args['size'];
  2183. }
  2184. if ( empty( $args['width'] ) ) {
  2185. $args['width'] = $args['size'];
  2186. }
  2187. if ( is_object( $id_or_email ) && isset( $id_or_email->comment_ID ) ) {
  2188. $id_or_email = get_comment( $id_or_email );
  2189. }
  2190. /**
  2191. * Filters whether to retrieve the avatar URL early.
  2192. *
  2193. * Passing a non-null value will effectively short-circuit get_avatar(), passing
  2194. * the value through the {@see 'get_avatar'} filter and returning early.
  2195. *
  2196. * @since 4.2.0
  2197. *
  2198. * @param string $avatar HTML for the user's avatar. Default null.
  2199. * @param mixed $id_or_email The Gravatar to retrieve. Accepts a user_id, gravatar md5 hash,
  2200. * user email, WP_User object, WP_Post object, or WP_Comment object.
  2201. * @param array $args Arguments passed to get_avatar_url(), after processing.
  2202. */
  2203. $avatar = apply_filters( 'pre_get_avatar', null, $id_or_email, $args );
  2204. if ( ! is_null( $avatar ) ) {
  2205. /** This filter is documented in wp-includes/pluggable.php */
  2206. return apply_filters( 'get_avatar', $avatar, $id_or_email, $args['size'], $args['default'], $args['alt'], $args );
  2207. }
  2208. if ( ! $args['force_display'] && ! get_option( 'show_avatars' ) ) {
  2209. return false;
  2210. }
  2211. $url2x = get_avatar_url( $id_or_email, array_merge( $args, array( 'size' => $args['size'] * 2 ) ) );
  2212. $args = get_avatar_data( $id_or_email, $args );
  2213. $url = $args['url'];
  2214. if ( ! $url || is_wp_error( $url ) ) {
  2215. return false;
  2216. }
  2217. $class = array( 'avatar', 'avatar-' . (int) $args['size'], 'photo' );
  2218. if ( ! $args['found_avatar'] || $args['force_default'] ) {
  2219. $class[] = 'avatar-default';
  2220. }
  2221. if ( $args['class'] ) {
  2222. if ( is_array( $args['class'] ) ) {
  2223. $class = array_merge( $class, $args['class'] );
  2224. } else {
  2225. $class[] = $args['class'];
  2226. }
  2227. }
  2228. $avatar = sprintf(
  2229. "<img alt='%s' src='%s' srcset='%s' class='%s' height='%d' width='%d' %s/>",
  2230. esc_attr( $args['alt'] ),
  2231. esc_url( $url ),
  2232. esc_url( $url2x ) . ' 2x',
  2233. esc_attr( join( ' ', $class ) ),
  2234. (int) $args['height'],
  2235. (int) $args['width'],
  2236. $args['extra_attr']
  2237. );
  2238. /**
  2239. * Filters the avatar to retrieve.
  2240. *
  2241. * @since 2.5.0
  2242. * @since 4.2.0 The `$args` parameter was added.
  2243. *
  2244. * @param string $avatar &lt;img&gt; tag for the user's avatar.
  2245. * @param mixed $id_or_email The Gravatar to retrieve. Accepts a user_id, gravatar md5 hash,
  2246. * user email, WP_User object, WP_Post object, or WP_Comment object.
  2247. * @param int $size Square avatar width and height in pixels to retrieve.
  2248. * @param string $default URL for the default image or a default type. Accepts '404', 'retro', 'monsterid',
  2249. * 'wavatar', 'indenticon','mystery' (or 'mm', or 'mysteryman'), 'blank', or 'gravatar_default'.
  2250. * Default is the value of the 'avatar_default' option, with a fallback of 'mystery'.
  2251. * @param string $alt Alternative text to use in the avatar image tag. Default empty.
  2252. * @param array $args Arguments passed to get_avatar_data(), after processing.
  2253. */
  2254. return apply_filters( 'get_avatar', $avatar, $id_or_email, $args['size'], $args['default'], $args['alt'], $args );
  2255. }
  2256. endif;
  2257. if ( !function_exists( 'wp_text_diff' ) ) :
  2258. /**
  2259. * Displays a human readable HTML representation of the difference between two strings.
  2260. *
  2261. * The Diff is available for getting the changes between versions. The output is
  2262. * HTML, so the primary use is for displaying the changes. If the two strings
  2263. * are equivalent, then an empty string will be returned.
  2264. *
  2265. * The arguments supported and can be changed are listed below.
  2266. *
  2267. * 'title' : Default is an empty string. Titles the diff in a manner compatible
  2268. * with the output.
  2269. * 'title_left' : Default is an empty string. Change the HTML to the left of the
  2270. * title.
  2271. * 'title_right' : Default is an empty string. Change the HTML to the right of
  2272. * the title.
  2273. *
  2274. * @since 2.6.0
  2275. *
  2276. * @see wp_parse_args() Used to change defaults to user defined settings.
  2277. * @uses Text_Diff
  2278. * @uses WP_Text_Diff_Renderer_Table
  2279. *
  2280. * @param string $left_string "old" (left) version of string
  2281. * @param string $right_string "new" (right) version of string
  2282. * @param string|array $args Optional. Change 'title', 'title_left', and 'title_right' defaults.
  2283. * @return string Empty string if strings are equivalent or HTML with differences.
  2284. */
  2285. function wp_text_diff( $left_string, $right_string, $args = null ) {
  2286. $defaults = array( 'title' => '', 'title_left' => '', 'title_right' => '' );
  2287. $args = wp_parse_args( $args, $defaults );
  2288. if ( ! class_exists( 'WP_Text_Diff_Renderer_Table', false ) )
  2289. require( ABSPATH . WPINC . '/wp-diff.php' );
  2290. $left_string = normalize_whitespace($left_string);
  2291. $right_string = normalize_whitespace($right_string);
  2292. $left_lines = explode("\n", $left_string);
  2293. $right_lines = explode("\n", $right_string);
  2294. $text_diff = new Text_Diff($left_lines, $right_lines);
  2295. $renderer = new WP_Text_Diff_Renderer_Table( $args );
  2296. $diff = $renderer->render($text_diff);
  2297. if ( !$diff )
  2298. return '';
  2299. $r = "<table class='diff'>\n";
  2300. if ( ! empty( $args[ 'show_split_view' ] ) ) {
  2301. $r .= "<col class='content diffsplit left' /><col class='content diffsplit middle' /><col class='content diffsplit right' />";
  2302. } else {
  2303. $r .= "<col class='content' />";
  2304. }
  2305. if ( $args['title'] || $args['title_left'] || $args['title_right'] )
  2306. $r .= "<thead>";
  2307. if ( $args['title'] )
  2308. $r .= "<tr class='diff-title'><th colspan='4'>$args[title]</th></tr>\n";
  2309. if ( $args['title_left'] || $args['title_right'] ) {
  2310. $r .= "<tr class='diff-sub-title'>\n";
  2311. $r .= "\t<td></td><th>$args[title_left]</th>\n";
  2312. $r .= "\t<td></td><th>$args[title_right]</th>\n";
  2313. $r .= "</tr>\n";
  2314. }
  2315. if ( $args['title'] || $args['title_left'] || $args['title_right'] )
  2316. $r .= "</thead>\n";
  2317. $r .= "<tbody>\n$diff\n</tbody>\n";
  2318. $r .= "</table>";
  2319. return $r;
  2320. }
  2321. endif;