pluggable.php 97 KB

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