Nessuna descrizione

comment.php 123KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913
  1. <?php
  2. /**
  3. * Core Comment API
  4. *
  5. * @package WordPress
  6. * @subpackage Comment
  7. */
  8. /**
  9. * Check whether a comment passes internal checks to be allowed to add.
  10. *
  11. * If manual comment moderation is set in the administration, then all checks,
  12. * regardless of their type and substance, will fail and the function will
  13. * return false.
  14. *
  15. * If the number of links exceeds the amount in the administration, then the
  16. * check fails. If any of the parameter contents contain any disallowed words,
  17. * then the check fails.
  18. *
  19. * If the comment author was approved before, then the comment is automatically
  20. * approved.
  21. *
  22. * If all checks pass, the function will return true.
  23. *
  24. * @since 1.2.0
  25. *
  26. * @global wpdb $wpdb WordPress database abstraction object.
  27. *
  28. * @param string $author Comment author name.
  29. * @param string $email Comment author email.
  30. * @param string $url Comment author URL.
  31. * @param string $comment Content of the comment.
  32. * @param string $user_ip Comment author IP address.
  33. * @param string $user_agent Comment author User-Agent.
  34. * @param string $comment_type Comment type, either user-submitted comment,
  35. * trackback, or pingback.
  36. * @return bool If all checks pass, true, otherwise false.
  37. */
  38. function check_comment( $author, $email, $url, $comment, $user_ip, $user_agent, $comment_type ) {
  39. global $wpdb;
  40. // If manual moderation is enabled, skip all checks and return false.
  41. if ( 1 == get_option( 'comment_moderation' ) ) {
  42. return false;
  43. }
  44. /** This filter is documented in wp-includes/comment-template.php */
  45. $comment = apply_filters( 'comment_text', $comment, null, array() );
  46. // Check for the number of external links if a max allowed number is set.
  47. $max_links = get_option( 'comment_max_links' );
  48. if ( $max_links ) {
  49. $num_links = preg_match_all( '/<a [^>]*href/i', $comment, $out );
  50. /**
  51. * Filters the number of links found in a comment.
  52. *
  53. * @since 3.0.0
  54. * @since 4.7.0 Added the `$comment` parameter.
  55. *
  56. * @param int $num_links The number of links found.
  57. * @param string $url Comment author's URL. Included in allowed links total.
  58. * @param string $comment Content of the comment.
  59. */
  60. $num_links = apply_filters( 'comment_max_links_url', $num_links, $url, $comment );
  61. /*
  62. * If the number of links in the comment exceeds the allowed amount,
  63. * fail the check by returning false.
  64. */
  65. if ( $num_links >= $max_links ) {
  66. return false;
  67. }
  68. }
  69. $mod_keys = trim( get_option( 'moderation_keys' ) );
  70. // If moderation 'keys' (keywords) are set, process them.
  71. if ( ! empty( $mod_keys ) ) {
  72. $words = explode( "\n", $mod_keys );
  73. foreach ( (array) $words as $word ) {
  74. $word = trim( $word );
  75. // Skip empty lines.
  76. if ( empty( $word ) ) {
  77. continue;
  78. }
  79. /*
  80. * Do some escaping magic so that '#' (number of) characters in the spam
  81. * words don't break things:
  82. */
  83. $word = preg_quote( $word, '#' );
  84. /*
  85. * Check the comment fields for moderation keywords. If any are found,
  86. * fail the check for the given field by returning false.
  87. */
  88. $pattern = "#$word#i";
  89. if ( preg_match( $pattern, $author ) ) {
  90. return false;
  91. }
  92. if ( preg_match( $pattern, $email ) ) {
  93. return false;
  94. }
  95. if ( preg_match( $pattern, $url ) ) {
  96. return false;
  97. }
  98. if ( preg_match( $pattern, $comment ) ) {
  99. return false;
  100. }
  101. if ( preg_match( $pattern, $user_ip ) ) {
  102. return false;
  103. }
  104. if ( preg_match( $pattern, $user_agent ) ) {
  105. return false;
  106. }
  107. }
  108. }
  109. /*
  110. * Check if the option to approve comments by previously-approved authors is enabled.
  111. *
  112. * If it is enabled, check whether the comment author has a previously-approved comment,
  113. * as well as whether there are any moderation keywords (if set) present in the author
  114. * email address. If both checks pass, return true. Otherwise, return false.
  115. */
  116. if ( 1 == get_option( 'comment_previously_approved' ) ) {
  117. if ( 'trackback' !== $comment_type && 'pingback' !== $comment_type && '' !== $author && '' !== $email ) {
  118. $comment_user = get_user_by( 'email', wp_unslash( $email ) );
  119. if ( ! empty( $comment_user->ID ) ) {
  120. $ok_to_comment = $wpdb->get_var( $wpdb->prepare( "SELECT comment_approved FROM $wpdb->comments WHERE user_id = %d AND comment_approved = '1' LIMIT 1", $comment_user->ID ) );
  121. } else {
  122. // expected_slashed ($author, $email)
  123. $ok_to_comment = $wpdb->get_var( $wpdb->prepare( "SELECT comment_approved FROM $wpdb->comments WHERE comment_author = %s AND comment_author_email = %s and comment_approved = '1' LIMIT 1", $author, $email ) );
  124. }
  125. if ( ( 1 == $ok_to_comment ) &&
  126. ( empty( $mod_keys ) || false === strpos( $email, $mod_keys ) ) ) {
  127. return true;
  128. } else {
  129. return false;
  130. }
  131. } else {
  132. return false;
  133. }
  134. }
  135. return true;
  136. }
  137. /**
  138. * Retrieve the approved comments for post $post_id.
  139. *
  140. * @since 2.0.0
  141. * @since 4.1.0 Refactored to leverage WP_Comment_Query over a direct query.
  142. *
  143. * @param int $post_id The ID of the post.
  144. * @param array $args Optional. See WP_Comment_Query::__construct() for information on accepted arguments.
  145. * @return int|array The approved comments, or number of comments if `$count`
  146. * argument is true.
  147. */
  148. function get_approved_comments( $post_id, $args = array() ) {
  149. if ( ! $post_id ) {
  150. return array();
  151. }
  152. $defaults = array(
  153. 'status' => 1,
  154. 'post_id' => $post_id,
  155. 'order' => 'ASC',
  156. );
  157. $parsed_args = wp_parse_args( $args, $defaults );
  158. $query = new WP_Comment_Query;
  159. return $query->query( $parsed_args );
  160. }
  161. /**
  162. * Retrieves comment data given a comment ID or comment object.
  163. *
  164. * If an object is passed then the comment data will be cached and then returned
  165. * after being passed through a filter. If the comment is empty, then the global
  166. * comment variable will be used, if it is set.
  167. *
  168. * @since 2.0.0
  169. *
  170. * @global WP_Comment $comment Global comment object.
  171. *
  172. * @param WP_Comment|string|int $comment Comment to retrieve.
  173. * @param string $output Optional. The required return type. One of OBJECT, ARRAY_A, or ARRAY_N, which
  174. * correspond to a WP_Comment object, an associative array, or a numeric array,
  175. * respectively. Default OBJECT.
  176. * @return WP_Comment|array|null Depends on $output value.
  177. */
  178. function get_comment( $comment = null, $output = OBJECT ) {
  179. if ( empty( $comment ) && isset( $GLOBALS['comment'] ) ) {
  180. $comment = $GLOBALS['comment'];
  181. }
  182. if ( $comment instanceof WP_Comment ) {
  183. $_comment = $comment;
  184. } elseif ( is_object( $comment ) ) {
  185. $_comment = new WP_Comment( $comment );
  186. } else {
  187. $_comment = WP_Comment::get_instance( $comment );
  188. }
  189. if ( ! $_comment ) {
  190. return null;
  191. }
  192. /**
  193. * Fires after a comment is retrieved.
  194. *
  195. * @since 2.3.0
  196. *
  197. * @param WP_Comment $_comment Comment data.
  198. */
  199. $_comment = apply_filters( 'get_comment', $_comment );
  200. if ( OBJECT === $output ) {
  201. return $_comment;
  202. } elseif ( ARRAY_A === $output ) {
  203. return $_comment->to_array();
  204. } elseif ( ARRAY_N === $output ) {
  205. return array_values( $_comment->to_array() );
  206. }
  207. return $_comment;
  208. }
  209. /**
  210. * Retrieve a list of comments.
  211. *
  212. * The comment list can be for the blog as a whole or for an individual post.
  213. *
  214. * @since 2.7.0
  215. *
  216. * @param string|array $args Optional. Array or string of arguments. See WP_Comment_Query::__construct()
  217. * for information on accepted arguments. Default empty.
  218. * @return int|array List of comments or number of found comments if `$count` argument is true.
  219. */
  220. function get_comments( $args = '' ) {
  221. $query = new WP_Comment_Query;
  222. return $query->query( $args );
  223. }
  224. /**
  225. * Retrieve all of the WordPress supported comment statuses.
  226. *
  227. * Comments have a limited set of valid status values, this provides the comment
  228. * status values and descriptions.
  229. *
  230. * @since 2.7.0
  231. *
  232. * @return string[] List of comment status labels keyed by status.
  233. */
  234. function get_comment_statuses() {
  235. $status = array(
  236. 'hold' => __( 'Unapproved' ),
  237. 'approve' => _x( 'Approved', 'comment status' ),
  238. 'spam' => _x( 'Spam', 'comment status' ),
  239. 'trash' => _x( 'Trash', 'comment status' ),
  240. );
  241. return $status;
  242. }
  243. /**
  244. * Gets the default comment status for a post type.
  245. *
  246. * @since 4.3.0
  247. *
  248. * @param string $post_type Optional. Post type. Default 'post'.
  249. * @param string $comment_type Optional. Comment type. Default 'comment'.
  250. * @return string Expected return value is 'open' or 'closed'.
  251. */
  252. function get_default_comment_status( $post_type = 'post', $comment_type = 'comment' ) {
  253. switch ( $comment_type ) {
  254. case 'pingback':
  255. case 'trackback':
  256. $supports = 'trackbacks';
  257. $option = 'ping';
  258. break;
  259. default:
  260. $supports = 'comments';
  261. $option = 'comment';
  262. break;
  263. }
  264. // Set the status.
  265. if ( 'page' === $post_type ) {
  266. $status = 'closed';
  267. } elseif ( post_type_supports( $post_type, $supports ) ) {
  268. $status = get_option( "default_{$option}_status" );
  269. } else {
  270. $status = 'closed';
  271. }
  272. /**
  273. * Filters the default comment status for the given post type.
  274. *
  275. * @since 4.3.0
  276. *
  277. * @param string $status Default status for the given post type,
  278. * either 'open' or 'closed'.
  279. * @param string $post_type Post type. Default is `post`.
  280. * @param string $comment_type Type of comment. Default is `comment`.
  281. */
  282. return apply_filters( 'get_default_comment_status', $status, $post_type, $comment_type );
  283. }
  284. /**
  285. * The date the last comment was modified.
  286. *
  287. * @since 1.5.0
  288. * @since 4.7.0 Replaced caching the modified date in a local static variable
  289. * with the Object Cache API.
  290. *
  291. * @global wpdb $wpdb WordPress database abstraction object.
  292. *
  293. * @param string $timezone Which timezone to use in reference to 'gmt', 'blog', or 'server' locations.
  294. * @return string|false Last comment modified date on success, false on failure.
  295. */
  296. function get_lastcommentmodified( $timezone = 'server' ) {
  297. global $wpdb;
  298. $timezone = strtolower( $timezone );
  299. $key = "lastcommentmodified:$timezone";
  300. $comment_modified_date = wp_cache_get( $key, 'timeinfo' );
  301. if ( false !== $comment_modified_date ) {
  302. return $comment_modified_date;
  303. }
  304. switch ( $timezone ) {
  305. case 'gmt':
  306. $comment_modified_date = $wpdb->get_var( "SELECT comment_date_gmt FROM $wpdb->comments WHERE comment_approved = '1' ORDER BY comment_date_gmt DESC LIMIT 1" );
  307. break;
  308. case 'blog':
  309. $comment_modified_date = $wpdb->get_var( "SELECT comment_date FROM $wpdb->comments WHERE comment_approved = '1' ORDER BY comment_date_gmt DESC LIMIT 1" );
  310. break;
  311. case 'server':
  312. $add_seconds_server = gmdate( 'Z' );
  313. $comment_modified_date = $wpdb->get_var( $wpdb->prepare( "SELECT DATE_ADD(comment_date_gmt, INTERVAL %s SECOND) FROM $wpdb->comments WHERE comment_approved = '1' ORDER BY comment_date_gmt DESC LIMIT 1", $add_seconds_server ) );
  314. break;
  315. }
  316. if ( $comment_modified_date ) {
  317. wp_cache_set( $key, $comment_modified_date, 'timeinfo' );
  318. return $comment_modified_date;
  319. }
  320. return false;
  321. }
  322. /**
  323. * Retrieves the total comment counts for the whole site or a single post.
  324. *
  325. * Unlike wp_count_comments(), this function always returns the live comment counts without caching.
  326. *
  327. * @since 2.0.0
  328. *
  329. * @global wpdb $wpdb WordPress database abstraction object.
  330. *
  331. * @param int $post_id Optional. Restrict the comment counts to the given post. Default 0, which indicates that
  332. * comment counts for the whole site will be retrieved.
  333. * @return array() {
  334. * The number of comments keyed by their status.
  335. *
  336. * @type int $approved The number of approved comments.
  337. * @type int $awaiting_moderation The number of comments awaiting moderation (a.k.a. pending).
  338. * @type int $spam The number of spam comments.
  339. * @type int $trash The number of trashed comments.
  340. * @type int $post-trashed The number of comments for posts that are in the trash.
  341. * @type int $total_comments The total number of non-trashed comments, including spam.
  342. * @type int $all The total number of pending or approved comments.
  343. * }
  344. */
  345. function get_comment_count( $post_id = 0 ) {
  346. global $wpdb;
  347. $post_id = (int) $post_id;
  348. $where = '';
  349. if ( $post_id > 0 ) {
  350. $where = $wpdb->prepare( 'WHERE comment_post_ID = %d', $post_id );
  351. }
  352. $totals = (array) $wpdb->get_results(
  353. "
  354. SELECT comment_approved, COUNT( * ) AS total
  355. FROM {$wpdb->comments}
  356. {$where}
  357. GROUP BY comment_approved
  358. ",
  359. ARRAY_A
  360. );
  361. $comment_count = array(
  362. 'approved' => 0,
  363. 'awaiting_moderation' => 0,
  364. 'spam' => 0,
  365. 'trash' => 0,
  366. 'post-trashed' => 0,
  367. 'total_comments' => 0,
  368. 'all' => 0,
  369. );
  370. foreach ( $totals as $row ) {
  371. switch ( $row['comment_approved'] ) {
  372. case 'trash':
  373. $comment_count['trash'] = $row['total'];
  374. break;
  375. case 'post-trashed':
  376. $comment_count['post-trashed'] = $row['total'];
  377. break;
  378. case 'spam':
  379. $comment_count['spam'] = $row['total'];
  380. $comment_count['total_comments'] += $row['total'];
  381. break;
  382. case '1':
  383. $comment_count['approved'] = $row['total'];
  384. $comment_count['total_comments'] += $row['total'];
  385. $comment_count['all'] += $row['total'];
  386. break;
  387. case '0':
  388. $comment_count['awaiting_moderation'] = $row['total'];
  389. $comment_count['total_comments'] += $row['total'];
  390. $comment_count['all'] += $row['total'];
  391. break;
  392. default:
  393. break;
  394. }
  395. }
  396. return array_map( 'intval', $comment_count );
  397. }
  398. //
  399. // Comment meta functions.
  400. //
  401. /**
  402. * Add meta data field to a comment.
  403. *
  404. * @since 2.9.0
  405. *
  406. * @link https://developer.wordpress.org/reference/functions/add_comment_meta/
  407. *
  408. * @param int $comment_id Comment ID.
  409. * @param string $meta_key Metadata name.
  410. * @param mixed $meta_value Metadata value. Must be serializable if non-scalar.
  411. * @param bool $unique Optional. Whether the same key should not be added.
  412. * Default false.
  413. * @return int|false Meta ID on success, false on failure.
  414. */
  415. function add_comment_meta( $comment_id, $meta_key, $meta_value, $unique = false ) {
  416. return add_metadata( 'comment', $comment_id, $meta_key, $meta_value, $unique );
  417. }
  418. /**
  419. * Remove metadata matching criteria from a comment.
  420. *
  421. * You can match based on the key, or key and value. Removing based on key and
  422. * value, will keep from removing duplicate metadata with the same key. It also
  423. * allows removing all metadata matching key, if needed.
  424. *
  425. * @since 2.9.0
  426. *
  427. * @link https://developer.wordpress.org/reference/functions/delete_comment_meta/
  428. *
  429. * @param int $comment_id Comment ID.
  430. * @param string $meta_key Metadata name.
  431. * @param mixed $meta_value Optional. Metadata value. If provided,
  432. * rows will only be removed that match the value.
  433. * Must be serializable if non-scalar. Default empty.
  434. * @return bool True on success, false on failure.
  435. */
  436. function delete_comment_meta( $comment_id, $meta_key, $meta_value = '' ) {
  437. return delete_metadata( 'comment', $comment_id, $meta_key, $meta_value );
  438. }
  439. /**
  440. * Retrieve comment meta field for a comment.
  441. *
  442. * @since 2.9.0
  443. *
  444. * @link https://developer.wordpress.org/reference/functions/get_comment_meta/
  445. *
  446. * @param int $comment_id Comment ID.
  447. * @param string $key Optional. The meta key to retrieve. By default,
  448. * returns data for all keys.
  449. * @param bool $single Optional. Whether to return a single value.
  450. * This parameter has no effect if `$key` is not specified.
  451. * Default false.
  452. * @return mixed An array of values if `$single` is false.
  453. * The value of meta data field if `$single` is true.
  454. * False for an invalid `$comment_id` (non-numeric, zero, or negative value).
  455. * An empty string if a valid but non-existing comment ID is passed.
  456. */
  457. function get_comment_meta( $comment_id, $key = '', $single = false ) {
  458. return get_metadata( 'comment', $comment_id, $key, $single );
  459. }
  460. /**
  461. * Update comment meta field based on comment ID.
  462. *
  463. * Use the $prev_value parameter to differentiate between meta fields with the
  464. * same key and comment ID.
  465. *
  466. * If the meta field for the comment does not exist, it will be added.
  467. *
  468. * @since 2.9.0
  469. *
  470. * @link https://developer.wordpress.org/reference/functions/update_comment_meta/
  471. *
  472. * @param int $comment_id Comment ID.
  473. * @param string $meta_key Metadata key.
  474. * @param mixed $meta_value Metadata value. Must be serializable if non-scalar.
  475. * @param mixed $prev_value Optional. Previous value to check before updating.
  476. * If specified, only update existing metadata entries with
  477. * this value. Otherwise, update all entries. Default empty.
  478. * @return int|bool Meta ID if the key didn't exist, true on successful update,
  479. * false on failure or if the value passed to the function
  480. * is the same as the one that is already in the database.
  481. */
  482. function update_comment_meta( $comment_id, $meta_key, $meta_value, $prev_value = '' ) {
  483. return update_metadata( 'comment', $comment_id, $meta_key, $meta_value, $prev_value );
  484. }
  485. /**
  486. * Queues comments for metadata lazy-loading.
  487. *
  488. * @since 4.5.0
  489. *
  490. * @param WP_Comment[] $comments Array of comment objects.
  491. */
  492. function wp_queue_comments_for_comment_meta_lazyload( $comments ) {
  493. // Don't use `wp_list_pluck()` to avoid by-reference manipulation.
  494. $comment_ids = array();
  495. if ( is_array( $comments ) ) {
  496. foreach ( $comments as $comment ) {
  497. if ( $comment instanceof WP_Comment ) {
  498. $comment_ids[] = $comment->comment_ID;
  499. }
  500. }
  501. }
  502. if ( $comment_ids ) {
  503. $lazyloader = wp_metadata_lazyloader();
  504. $lazyloader->queue_objects( 'comment', $comment_ids );
  505. }
  506. }
  507. /**
  508. * Sets the cookies used to store an unauthenticated commentator's identity. Typically used
  509. * to recall previous comments by this commentator that are still held in moderation.
  510. *
  511. * @since 3.4.0
  512. * @since 4.9.6 The `$cookies_consent` parameter was added.
  513. *
  514. * @param WP_Comment $comment Comment object.
  515. * @param WP_User $user Comment author's user object. The user may not exist.
  516. * @param bool $cookies_consent Optional. Comment author's consent to store cookies. Default true.
  517. */
  518. function wp_set_comment_cookies( $comment, $user, $cookies_consent = true ) {
  519. // If the user already exists, or the user opted out of cookies, don't set cookies.
  520. if ( $user->exists() ) {
  521. return;
  522. }
  523. if ( false === $cookies_consent ) {
  524. // Remove any existing cookies.
  525. $past = time() - YEAR_IN_SECONDS;
  526. setcookie( 'comment_author_' . COOKIEHASH, ' ', $past, COOKIEPATH, COOKIE_DOMAIN );
  527. setcookie( 'comment_author_email_' . COOKIEHASH, ' ', $past, COOKIEPATH, COOKIE_DOMAIN );
  528. setcookie( 'comment_author_url_' . COOKIEHASH, ' ', $past, COOKIEPATH, COOKIE_DOMAIN );
  529. return;
  530. }
  531. /**
  532. * Filters the lifetime of the comment cookie in seconds.
  533. *
  534. * @since 2.8.0
  535. *
  536. * @param int $seconds Comment cookie lifetime. Default 30000000.
  537. */
  538. $comment_cookie_lifetime = time() + apply_filters( 'comment_cookie_lifetime', 30000000 );
  539. $secure = ( 'https' === parse_url( home_url(), PHP_URL_SCHEME ) );
  540. setcookie( 'comment_author_' . COOKIEHASH, $comment->comment_author, $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN, $secure );
  541. setcookie( 'comment_author_email_' . COOKIEHASH, $comment->comment_author_email, $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN, $secure );
  542. setcookie( 'comment_author_url_' . COOKIEHASH, esc_url( $comment->comment_author_url ), $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN, $secure );
  543. }
  544. /**
  545. * Sanitizes the cookies sent to the user already.
  546. *
  547. * Will only do anything if the cookies have already been created for the user.
  548. * Mostly used after cookies had been sent to use elsewhere.
  549. *
  550. * @since 2.0.4
  551. */
  552. function sanitize_comment_cookies() {
  553. if ( isset( $_COOKIE[ 'comment_author_' . COOKIEHASH ] ) ) {
  554. /**
  555. * Filters the comment author's name cookie before it is set.
  556. *
  557. * When this filter hook is evaluated in wp_filter_comment(),
  558. * the comment author's name string is passed.
  559. *
  560. * @since 1.5.0
  561. *
  562. * @param string $author_cookie The comment author name cookie.
  563. */
  564. $comment_author = apply_filters( 'pre_comment_author_name', $_COOKIE[ 'comment_author_' . COOKIEHASH ] );
  565. $comment_author = wp_unslash( $comment_author );
  566. $comment_author = esc_attr( $comment_author );
  567. $_COOKIE[ 'comment_author_' . COOKIEHASH ] = $comment_author;
  568. }
  569. if ( isset( $_COOKIE[ 'comment_author_email_' . COOKIEHASH ] ) ) {
  570. /**
  571. * Filters the comment author's email cookie before it is set.
  572. *
  573. * When this filter hook is evaluated in wp_filter_comment(),
  574. * the comment author's email string is passed.
  575. *
  576. * @since 1.5.0
  577. *
  578. * @param string $author_email_cookie The comment author email cookie.
  579. */
  580. $comment_author_email = apply_filters( 'pre_comment_author_email', $_COOKIE[ 'comment_author_email_' . COOKIEHASH ] );
  581. $comment_author_email = wp_unslash( $comment_author_email );
  582. $comment_author_email = esc_attr( $comment_author_email );
  583. $_COOKIE[ 'comment_author_email_' . COOKIEHASH ] = $comment_author_email;
  584. }
  585. if ( isset( $_COOKIE[ 'comment_author_url_' . COOKIEHASH ] ) ) {
  586. /**
  587. * Filters the comment author's URL cookie before it is set.
  588. *
  589. * When this filter hook is evaluated in wp_filter_comment(),
  590. * the comment author's URL string is passed.
  591. *
  592. * @since 1.5.0
  593. *
  594. * @param string $author_url_cookie The comment author URL cookie.
  595. */
  596. $comment_author_url = apply_filters( 'pre_comment_author_url', $_COOKIE[ 'comment_author_url_' . COOKIEHASH ] );
  597. $comment_author_url = wp_unslash( $comment_author_url );
  598. $_COOKIE[ 'comment_author_url_' . COOKIEHASH ] = $comment_author_url;
  599. }
  600. }
  601. /**
  602. * Validates whether this comment is allowed to be made.
  603. *
  604. * @since 2.0.0
  605. * @since 4.7.0 The `$avoid_die` parameter was added, allowing the function
  606. * to return a WP_Error object instead of dying.
  607. * @since 5.5.0 The `$avoid_die` parameter was renamed to `$wp_error`.
  608. *
  609. * @global wpdb $wpdb WordPress database abstraction object.
  610. *
  611. * @param array $commentdata Contains information on the comment.
  612. * @param bool $wp_error When true, a disallowed comment will result in the function
  613. * returning a WP_Error object, rather than executing wp_die().
  614. * Default false.
  615. * @return int|string|WP_Error Allowed comments return the approval status (0|1|'spam'|'trash').
  616. * If `$wp_error` is true, disallowed comments return a WP_Error.
  617. */
  618. function wp_allow_comment( $commentdata, $wp_error = false ) {
  619. global $wpdb;
  620. // Simple duplicate check.
  621. // expected_slashed ($comment_post_ID, $comment_author, $comment_author_email, $comment_content)
  622. $dupe = $wpdb->prepare(
  623. "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_parent = %s AND comment_approved != 'trash' AND ( comment_author = %s ",
  624. wp_unslash( $commentdata['comment_post_ID'] ),
  625. wp_unslash( $commentdata['comment_parent'] ),
  626. wp_unslash( $commentdata['comment_author'] )
  627. );
  628. if ( $commentdata['comment_author_email'] ) {
  629. $dupe .= $wpdb->prepare(
  630. 'AND comment_author_email = %s ',
  631. wp_unslash( $commentdata['comment_author_email'] )
  632. );
  633. }
  634. $dupe .= $wpdb->prepare(
  635. ') AND comment_content = %s LIMIT 1',
  636. wp_unslash( $commentdata['comment_content'] )
  637. );
  638. $dupe_id = $wpdb->get_var( $dupe );
  639. /**
  640. * Filters the ID, if any, of the duplicate comment found when creating a new comment.
  641. *
  642. * Return an empty value from this filter to allow what WP considers a duplicate comment.
  643. *
  644. * @since 4.4.0
  645. *
  646. * @param int $dupe_id ID of the comment identified as a duplicate.
  647. * @param array $commentdata Data for the comment being created.
  648. */
  649. $dupe_id = apply_filters( 'duplicate_comment_id', $dupe_id, $commentdata );
  650. if ( $dupe_id ) {
  651. /**
  652. * Fires immediately after a duplicate comment is detected.
  653. *
  654. * @since 3.0.0
  655. *
  656. * @param array $commentdata Comment data.
  657. */
  658. do_action( 'comment_duplicate_trigger', $commentdata );
  659. /**
  660. * Filters duplicate comment error message.
  661. *
  662. * @since 5.2.0
  663. *
  664. * @param string $comment_duplicate_message Duplicate comment error message.
  665. */
  666. $comment_duplicate_message = apply_filters( 'comment_duplicate_message', __( 'Duplicate comment detected; it looks as though you&#8217;ve already said that!' ) );
  667. if ( $wp_error ) {
  668. return new WP_Error( 'comment_duplicate', $comment_duplicate_message, 409 );
  669. } else {
  670. if ( wp_doing_ajax() ) {
  671. die( $comment_duplicate_message );
  672. }
  673. wp_die( $comment_duplicate_message, 409 );
  674. }
  675. }
  676. /**
  677. * Fires immediately before a comment is marked approved.
  678. *
  679. * Allows checking for comment flooding.
  680. *
  681. * @since 2.3.0
  682. * @since 4.7.0 The `$avoid_die` parameter was added.
  683. * @since 5.5.0 The `$avoid_die` parameter was renamed to `$wp_error`.
  684. *
  685. * @param string $comment_author_IP Comment author's IP address.
  686. * @param string $comment_author_email Comment author's email.
  687. * @param string $comment_date_gmt GMT date the comment was posted.
  688. * @param bool $wp_error Whether to return a WP_Error object instead of executing
  689. * wp_die() or die() if a comment flood is occurring.
  690. */
  691. do_action(
  692. 'check_comment_flood',
  693. $commentdata['comment_author_IP'],
  694. $commentdata['comment_author_email'],
  695. $commentdata['comment_date_gmt'],
  696. $wp_error
  697. );
  698. /**
  699. * Filters whether a comment is part of a comment flood.
  700. *
  701. * The default check is wp_check_comment_flood(). See check_comment_flood_db().
  702. *
  703. * @since 4.7.0
  704. * @since 5.5.0 The `$avoid_die` parameter was renamed to `$wp_error`.
  705. *
  706. * @param bool $is_flood Is a comment flooding occurring? Default false.
  707. * @param string $comment_author_IP Comment author's IP address.
  708. * @param string $comment_author_email Comment author's email.
  709. * @param string $comment_date_gmt GMT date the comment was posted.
  710. * @param bool $wp_error Whether to return a WP_Error object instead of executing
  711. * wp_die() or die() if a comment flood is occurring.
  712. */
  713. $is_flood = apply_filters(
  714. 'wp_is_comment_flood',
  715. false,
  716. $commentdata['comment_author_IP'],
  717. $commentdata['comment_author_email'],
  718. $commentdata['comment_date_gmt'],
  719. $wp_error
  720. );
  721. if ( $is_flood ) {
  722. /** This filter is documented in wp-includes/comment-template.php */
  723. $comment_flood_message = apply_filters( 'comment_flood_message', __( 'You are posting comments too quickly. Slow down.' ) );
  724. return new WP_Error( 'comment_flood', $comment_flood_message, 429 );
  725. }
  726. if ( ! empty( $commentdata['user_id'] ) ) {
  727. $user = get_userdata( $commentdata['user_id'] );
  728. $post_author = $wpdb->get_var(
  729. $wpdb->prepare(
  730. "SELECT post_author FROM $wpdb->posts WHERE ID = %d LIMIT 1",
  731. $commentdata['comment_post_ID']
  732. )
  733. );
  734. }
  735. if ( isset( $user ) && ( $commentdata['user_id'] == $post_author || $user->has_cap( 'moderate_comments' ) ) ) {
  736. // The author and the admins get respect.
  737. $approved = 1;
  738. } else {
  739. // Everyone else's comments will be checked.
  740. if ( check_comment(
  741. $commentdata['comment_author'],
  742. $commentdata['comment_author_email'],
  743. $commentdata['comment_author_url'],
  744. $commentdata['comment_content'],
  745. $commentdata['comment_author_IP'],
  746. $commentdata['comment_agent'],
  747. $commentdata['comment_type']
  748. ) ) {
  749. $approved = 1;
  750. } else {
  751. $approved = 0;
  752. }
  753. if ( wp_check_comment_disallowed_list(
  754. $commentdata['comment_author'],
  755. $commentdata['comment_author_email'],
  756. $commentdata['comment_author_url'],
  757. $commentdata['comment_content'],
  758. $commentdata['comment_author_IP'],
  759. $commentdata['comment_agent']
  760. ) ) {
  761. $approved = EMPTY_TRASH_DAYS ? 'trash' : 'spam';
  762. }
  763. }
  764. /**
  765. * Filters a comment's approval status before it is set.
  766. *
  767. * @since 2.1.0
  768. * @since 4.9.0 Returning a WP_Error value from the filter will short-circuit comment insertion
  769. * and allow skipping further processing.
  770. *
  771. * @param int|string|WP_Error $approved The approval status. Accepts 1, 0, 'spam', 'trash',
  772. * or WP_Error.
  773. * @param array $commentdata Comment data.
  774. */
  775. return apply_filters( 'pre_comment_approved', $approved, $commentdata );
  776. }
  777. /**
  778. * Hooks WP's native database-based comment-flood check.
  779. *
  780. * This wrapper maintains backward compatibility with plugins that expect to
  781. * be able to unhook the legacy check_comment_flood_db() function from
  782. * 'check_comment_flood' using remove_action().
  783. *
  784. * @since 2.3.0
  785. * @since 4.7.0 Converted to be an add_filter() wrapper.
  786. */
  787. function check_comment_flood_db() {
  788. add_filter( 'wp_is_comment_flood', 'wp_check_comment_flood', 10, 5 );
  789. }
  790. /**
  791. * Checks whether comment flooding is occurring.
  792. *
  793. * Won't run, if current user can manage options, so to not block
  794. * administrators.
  795. *
  796. * @since 4.7.0
  797. *
  798. * @global wpdb $wpdb WordPress database abstraction object.
  799. *
  800. * @param bool $is_flood Is a comment flooding occurring?
  801. * @param string $ip Comment author's IP address.
  802. * @param string $email Comment author's email address.
  803. * @param string $date MySQL time string.
  804. * @param bool $avoid_die When true, a disallowed comment will result in the function
  805. * returning without executing wp_die() or die(). Default false.
  806. * @return bool Whether comment flooding is occurring.
  807. */
  808. function wp_check_comment_flood( $is_flood, $ip, $email, $date, $avoid_die = false ) {
  809. global $wpdb;
  810. // Another callback has declared a flood. Trust it.
  811. if ( true === $is_flood ) {
  812. return $is_flood;
  813. }
  814. // Don't throttle admins or moderators.
  815. if ( current_user_can( 'manage_options' ) || current_user_can( 'moderate_comments' ) ) {
  816. return false;
  817. }
  818. $hour_ago = gmdate( 'Y-m-d H:i:s', time() - HOUR_IN_SECONDS );
  819. if ( is_user_logged_in() ) {
  820. $user = get_current_user_id();
  821. $check_column = '`user_id`';
  822. } else {
  823. $user = $ip;
  824. $check_column = '`comment_author_IP`';
  825. }
  826. $sql = $wpdb->prepare(
  827. "SELECT `comment_date_gmt` FROM `$wpdb->comments` WHERE `comment_date_gmt` >= %s AND ( $check_column = %s OR `comment_author_email` = %s ) ORDER BY `comment_date_gmt` DESC LIMIT 1",
  828. $hour_ago,
  829. $user,
  830. $email
  831. );
  832. $lasttime = $wpdb->get_var( $sql );
  833. if ( $lasttime ) {
  834. $time_lastcomment = mysql2date( 'U', $lasttime, false );
  835. $time_newcomment = mysql2date( 'U', $date, false );
  836. /**
  837. * Filters the comment flood status.
  838. *
  839. * @since 2.1.0
  840. *
  841. * @param bool $bool Whether a comment flood is occurring. Default false.
  842. * @param int $time_lastcomment Timestamp of when the last comment was posted.
  843. * @param int $time_newcomment Timestamp of when the new comment was posted.
  844. */
  845. $flood_die = apply_filters( 'comment_flood_filter', false, $time_lastcomment, $time_newcomment );
  846. if ( $flood_die ) {
  847. /**
  848. * Fires before the comment flood message is triggered.
  849. *
  850. * @since 1.5.0
  851. *
  852. * @param int $time_lastcomment Timestamp of when the last comment was posted.
  853. * @param int $time_newcomment Timestamp of when the new comment was posted.
  854. */
  855. do_action( 'comment_flood_trigger', $time_lastcomment, $time_newcomment );
  856. if ( $avoid_die ) {
  857. return true;
  858. } else {
  859. /**
  860. * Filters the comment flood error message.
  861. *
  862. * @since 5.2.0
  863. *
  864. * @param string $comment_flood_message Comment flood error message.
  865. */
  866. $comment_flood_message = apply_filters( 'comment_flood_message', __( 'You are posting comments too quickly. Slow down.' ) );
  867. if ( wp_doing_ajax() ) {
  868. die( $comment_flood_message );
  869. }
  870. wp_die( $comment_flood_message, 429 );
  871. }
  872. }
  873. }
  874. return false;
  875. }
  876. /**
  877. * Separates an array of comments into an array keyed by comment_type.
  878. *
  879. * @since 2.7.0
  880. *
  881. * @param WP_Comment[] $comments Array of comments
  882. * @return WP_Comment[] Array of comments keyed by comment_type.
  883. */
  884. function separate_comments( &$comments ) {
  885. $comments_by_type = array(
  886. 'comment' => array(),
  887. 'trackback' => array(),
  888. 'pingback' => array(),
  889. 'pings' => array(),
  890. );
  891. $count = count( $comments );
  892. for ( $i = 0; $i < $count; $i++ ) {
  893. $type = $comments[ $i ]->comment_type;
  894. if ( empty( $type ) ) {
  895. $type = 'comment';
  896. }
  897. $comments_by_type[ $type ][] = &$comments[ $i ];
  898. if ( 'trackback' === $type || 'pingback' === $type ) {
  899. $comments_by_type['pings'][] = &$comments[ $i ];
  900. }
  901. }
  902. return $comments_by_type;
  903. }
  904. /**
  905. * Calculate the total number of comment pages.
  906. *
  907. * @since 2.7.0
  908. *
  909. * @uses Walker_Comment
  910. *
  911. * @global WP_Query $wp_query WordPress Query object.
  912. *
  913. * @param WP_Comment[] $comments Optional. Array of WP_Comment objects. Defaults to `$wp_query->comments`.
  914. * @param int $per_page Optional. Comments per page.
  915. * @param bool $threaded Optional. Control over flat or threaded comments.
  916. * @return int Number of comment pages.
  917. */
  918. function get_comment_pages_count( $comments = null, $per_page = null, $threaded = null ) {
  919. global $wp_query;
  920. if ( null === $comments && null === $per_page && null === $threaded && ! empty( $wp_query->max_num_comment_pages ) ) {
  921. return $wp_query->max_num_comment_pages;
  922. }
  923. if ( ( ! $comments || ! is_array( $comments ) ) && ! empty( $wp_query->comments ) ) {
  924. $comments = $wp_query->comments;
  925. }
  926. if ( empty( $comments ) ) {
  927. return 0;
  928. }
  929. if ( ! get_option( 'page_comments' ) ) {
  930. return 1;
  931. }
  932. if ( ! isset( $per_page ) ) {
  933. $per_page = (int) get_query_var( 'comments_per_page' );
  934. }
  935. if ( 0 === $per_page ) {
  936. $per_page = (int) get_option( 'comments_per_page' );
  937. }
  938. if ( 0 === $per_page ) {
  939. return 1;
  940. }
  941. if ( ! isset( $threaded ) ) {
  942. $threaded = get_option( 'thread_comments' );
  943. }
  944. if ( $threaded ) {
  945. $walker = new Walker_Comment;
  946. $count = ceil( $walker->get_number_of_root_elements( $comments ) / $per_page );
  947. } else {
  948. $count = ceil( count( $comments ) / $per_page );
  949. }
  950. return $count;
  951. }
  952. /**
  953. * Calculate what page number a comment will appear on for comment paging.
  954. *
  955. * @since 2.7.0
  956. *
  957. * @global wpdb $wpdb WordPress database abstraction object.
  958. *
  959. * @param int $comment_ID Comment ID.
  960. * @param array $args {
  961. * Array of optional arguments.
  962. *
  963. * @type string $type Limit paginated comments to those matching a given type.
  964. * Accepts 'comment', 'trackback', 'pingback', 'pings'
  965. * (trackbacks and pingbacks), or 'all'. Default 'all'.
  966. * @type int $per_page Per-page count to use when calculating pagination.
  967. * Defaults to the value of the 'comments_per_page' option.
  968. * @type int|string $max_depth If greater than 1, comment page will be determined
  969. * for the top-level parent `$comment_ID`.
  970. * Defaults to the value of the 'thread_comments_depth' option.
  971. * } *
  972. * @return int|null Comment page number or null on error.
  973. */
  974. function get_page_of_comment( $comment_ID, $args = array() ) {
  975. global $wpdb;
  976. $page = null;
  977. $comment = get_comment( $comment_ID );
  978. if ( ! $comment ) {
  979. return;
  980. }
  981. $defaults = array(
  982. 'type' => 'all',
  983. 'page' => '',
  984. 'per_page' => '',
  985. 'max_depth' => '',
  986. );
  987. $args = wp_parse_args( $args, $defaults );
  988. $original_args = $args;
  989. // Order of precedence: 1. `$args['per_page']`, 2. 'comments_per_page' query_var, 3. 'comments_per_page' option.
  990. if ( get_option( 'page_comments' ) ) {
  991. if ( '' === $args['per_page'] ) {
  992. $args['per_page'] = get_query_var( 'comments_per_page' );
  993. }
  994. if ( '' === $args['per_page'] ) {
  995. $args['per_page'] = get_option( 'comments_per_page' );
  996. }
  997. }
  998. if ( empty( $args['per_page'] ) ) {
  999. $args['per_page'] = 0;
  1000. $args['page'] = 0;
  1001. }
  1002. if ( $args['per_page'] < 1 ) {
  1003. $page = 1;
  1004. }
  1005. if ( null === $page ) {
  1006. if ( '' === $args['max_depth'] ) {
  1007. if ( get_option( 'thread_comments' ) ) {
  1008. $args['max_depth'] = get_option( 'thread_comments_depth' );
  1009. } else {
  1010. $args['max_depth'] = -1;
  1011. }
  1012. }
  1013. // Find this comment's top-level parent if threading is enabled.
  1014. if ( $args['max_depth'] > 1 && 0 != $comment->comment_parent ) {
  1015. return get_page_of_comment( $comment->comment_parent, $args );
  1016. }
  1017. $comment_args = array(
  1018. 'type' => $args['type'],
  1019. 'post_id' => $comment->comment_post_ID,
  1020. 'fields' => 'ids',
  1021. 'count' => true,
  1022. 'status' => 'approve',
  1023. 'parent' => 0,
  1024. 'date_query' => array(
  1025. array(
  1026. 'column' => "$wpdb->comments.comment_date_gmt",
  1027. 'before' => $comment->comment_date_gmt,
  1028. ),
  1029. ),
  1030. );
  1031. if ( is_user_logged_in() ) {
  1032. $comment_args['include_unapproved'] = array( get_current_user_id() );
  1033. } else {
  1034. $unapproved_email = wp_get_unapproved_comment_author_email();
  1035. if ( $unapproved_email ) {
  1036. $comment_args['include_unapproved'] = array( $unapproved_email );
  1037. }
  1038. }
  1039. /**
  1040. * Filters the arguments used to query comments in get_page_of_comment().
  1041. *
  1042. * @since 5.5.0
  1043. *
  1044. * @see WP_Comment_Query::__construct()
  1045. *
  1046. * @param array $comment_args {
  1047. * Array of WP_Comment_Query arguments.
  1048. *
  1049. * @type string $type Limit paginated comments to those matching a given type.
  1050. * Accepts 'comment', 'trackback', 'pingback', 'pings'
  1051. * (trackbacks and pingbacks), or 'all'. Default 'all'.
  1052. * @type int $post_id ID of the post.
  1053. * @type string $fields Comment fields to return.
  1054. * @type bool $count Whether to return a comment count (true) or array
  1055. * of comment objects (false).
  1056. * @type string $status Comment status.
  1057. * @type int $parent Parent ID of comment to retrieve children of.
  1058. * @type array $date_query Date query clauses to limit comments by. See WP_Date_Query.
  1059. * @type array $include_unapproved Array of IDs or email addresses whose unapproved comments
  1060. * will be included in paginated comments.
  1061. * }
  1062. */
  1063. $comment_args = apply_filters( 'get_page_of_comment_query_args', $comment_args );
  1064. $comment_query = new WP_Comment_Query();
  1065. $older_comment_count = $comment_query->query( $comment_args );
  1066. // No older comments? Then it's page #1.
  1067. if ( 0 == $older_comment_count ) {
  1068. $page = 1;
  1069. // Divide comments older than this one by comments per page to get this comment's page number.
  1070. } else {
  1071. $page = ceil( ( $older_comment_count + 1 ) / $args['per_page'] );
  1072. }
  1073. }
  1074. /**
  1075. * Filters the calculated page on which a comment appears.
  1076. *
  1077. * @since 4.4.0
  1078. * @since 4.7.0 Introduced the `$comment_ID` parameter.
  1079. *
  1080. * @param int $page Comment page.
  1081. * @param array $args {
  1082. * Arguments used to calculate pagination. These include arguments auto-detected by the function,
  1083. * based on query vars, system settings, etc. For pristine arguments passed to the function,
  1084. * see `$original_args`.
  1085. *
  1086. * @type string $type Type of comments to count.
  1087. * @type int $page Calculated current page.
  1088. * @type int $per_page Calculated number of comments per page.
  1089. * @type int $max_depth Maximum comment threading depth allowed.
  1090. * }
  1091. * @param array $original_args {
  1092. * Array of arguments passed to the function. Some or all of these may not be set.
  1093. *
  1094. * @type string $type Type of comments to count.
  1095. * @type int $page Current comment page.
  1096. * @type int $per_page Number of comments per page.
  1097. * @type int $max_depth Maximum comment threading depth allowed.
  1098. * }
  1099. * @param int $comment_ID ID of the comment.
  1100. */
  1101. return apply_filters( 'get_page_of_comment', (int) $page, $args, $original_args, $comment_ID );
  1102. }
  1103. /**
  1104. * Retrieves the maximum character lengths for the comment form fields.
  1105. *
  1106. * @since 4.5.0
  1107. *
  1108. * @global wpdb $wpdb WordPress database abstraction object.
  1109. *
  1110. * @return int[] Array of maximum lengths keyed by field name.
  1111. */
  1112. function wp_get_comment_fields_max_lengths() {
  1113. global $wpdb;
  1114. $lengths = array(
  1115. 'comment_author' => 245,
  1116. 'comment_author_email' => 100,
  1117. 'comment_author_url' => 200,
  1118. 'comment_content' => 65525,
  1119. );
  1120. if ( $wpdb->is_mysql ) {
  1121. foreach ( $lengths as $column => $length ) {
  1122. $col_length = $wpdb->get_col_length( $wpdb->comments, $column );
  1123. $max_length = 0;
  1124. // No point if we can't get the DB column lengths.
  1125. if ( is_wp_error( $col_length ) ) {
  1126. break;
  1127. }
  1128. if ( ! is_array( $col_length ) && (int) $col_length > 0 ) {
  1129. $max_length = (int) $col_length;
  1130. } elseif ( is_array( $col_length ) && isset( $col_length['length'] ) && (int) $col_length['length'] > 0 ) {
  1131. $max_length = (int) $col_length['length'];
  1132. if ( ! empty( $col_length['type'] ) && 'byte' === $col_length['type'] ) {
  1133. $max_length = $max_length - 10;
  1134. }
  1135. }
  1136. if ( $max_length > 0 ) {
  1137. $lengths[ $column ] = $max_length;
  1138. }
  1139. }
  1140. }
  1141. /**
  1142. * Filters the lengths for the comment form fields.
  1143. *
  1144. * @since 4.5.0
  1145. *
  1146. * @param int[] $lengths Array of maximum lengths keyed by field name.
  1147. */
  1148. return apply_filters( 'wp_get_comment_fields_max_lengths', $lengths );
  1149. }
  1150. /**
  1151. * Compares the lengths of comment data against the maximum character limits.
  1152. *
  1153. * @since 4.7.0
  1154. *
  1155. * @param array $comment_data Array of arguments for inserting a comment.
  1156. * @return WP_Error|true WP_Error when a comment field exceeds the limit,
  1157. * otherwise true.
  1158. */
  1159. function wp_check_comment_data_max_lengths( $comment_data ) {
  1160. $max_lengths = wp_get_comment_fields_max_lengths();
  1161. if ( isset( $comment_data['comment_author'] ) && mb_strlen( $comment_data['comment_author'], '8bit' ) > $max_lengths['comment_author'] ) {
  1162. return new WP_Error( 'comment_author_column_length', __( '<strong>Error</strong>: Your name is too long.' ), 200 );
  1163. }
  1164. if ( isset( $comment_data['comment_author_email'] ) && strlen( $comment_data['comment_author_email'] ) > $max_lengths['comment_author_email'] ) {
  1165. return new WP_Error( 'comment_author_email_column_length', __( '<strong>Error</strong>: Your email address is too long.' ), 200 );
  1166. }
  1167. if ( isset( $comment_data['comment_author_url'] ) && strlen( $comment_data['comment_author_url'] ) > $max_lengths['comment_author_url'] ) {
  1168. return new WP_Error( 'comment_author_url_column_length', __( '<strong>Error</strong>: Your URL is too long.' ), 200 );
  1169. }
  1170. if ( isset( $comment_data['comment_content'] ) && mb_strlen( $comment_data['comment_content'], '8bit' ) > $max_lengths['comment_content'] ) {
  1171. return new WP_Error( 'comment_content_column_length', __( '<strong>Error</strong>: Your comment is too long.' ), 200 );
  1172. }
  1173. return true;
  1174. }
  1175. /**
  1176. * Checks if a comment contains disallowed characters or words.
  1177. *
  1178. * @since 5.5.0
  1179. *
  1180. * @param string $author The author of the comment
  1181. * @param string $email The email of the comment
  1182. * @param string $url The url used in the comment
  1183. * @param string $comment The comment content
  1184. * @param string $user_ip The comment author's IP address
  1185. * @param string $user_agent The author's browser user agent
  1186. * @return bool True if comment contains disallowed content, false if comment does not
  1187. */
  1188. function wp_check_comment_disallowed_list( $author, $email, $url, $comment, $user_ip, $user_agent ) {
  1189. /**
  1190. * Fires before the comment is tested for disallowed characters or words.
  1191. *
  1192. * @since 1.5.0
  1193. * @deprecated 5.5.0 Use {@see 'wp_check_comment_disallowed_list'} instead.
  1194. *
  1195. * @param string $author Comment author.
  1196. * @param string $email Comment author's email.
  1197. * @param string $url Comment author's URL.
  1198. * @param string $comment Comment content.
  1199. * @param string $user_ip Comment author's IP address.
  1200. * @param string $user_agent Comment author's browser user agent.
  1201. */
  1202. do_action_deprecated(
  1203. 'wp_blacklist_check',
  1204. array( $author, $email, $url, $comment, $user_ip, $user_agent ),
  1205. '5.5.0',
  1206. 'wp_check_comment_disallowed_list',
  1207. __( 'Please consider writing more inclusive code.' )
  1208. );
  1209. /**
  1210. * Fires before the comment is tested for disallowed characters or words.
  1211. *
  1212. * @since 5.5.0
  1213. *
  1214. * @param string $author Comment author.
  1215. * @param string $email Comment author's email.
  1216. * @param string $url Comment author's URL.
  1217. * @param string $comment Comment content.
  1218. * @param string $user_ip Comment author's IP address.
  1219. * @param string $user_agent Comment author's browser user agent.
  1220. */
  1221. do_action( 'wp_check_comment_disallowed_list', $author, $email, $url, $comment, $user_ip, $user_agent );
  1222. $mod_keys = trim( get_option( 'disallowed_keys' ) );
  1223. if ( '' === $mod_keys ) {
  1224. return false; // If moderation keys are empty.
  1225. }
  1226. // Ensure HTML tags are not being used to bypass the list of disallowed characters and words.
  1227. $comment_without_html = wp_strip_all_tags( $comment );
  1228. $words = explode( "\n", $mod_keys );
  1229. foreach ( (array) $words as $word ) {
  1230. $word = trim( $word );
  1231. // Skip empty lines.
  1232. if ( empty( $word ) ) {
  1233. continue; }
  1234. // Do some escaping magic so that '#' chars
  1235. // in the spam words don't break things:
  1236. $word = preg_quote( $word, '#' );
  1237. $pattern = "#$word#i";
  1238. if ( preg_match( $pattern, $author )
  1239. || preg_match( $pattern, $email )
  1240. || preg_match( $pattern, $url )
  1241. || preg_match( $pattern, $comment )
  1242. || preg_match( $pattern, $comment_without_html )
  1243. || preg_match( $pattern, $user_ip )
  1244. || preg_match( $pattern, $user_agent )
  1245. ) {
  1246. return true;
  1247. }
  1248. }
  1249. return false;
  1250. }
  1251. /**
  1252. * Retrieves the total comment counts for the whole site or a single post.
  1253. *
  1254. * The comment stats are cached and then retrieved, if they already exist in the
  1255. * cache.
  1256. *
  1257. * @see get_comment_count() Which handles fetching the live comment counts.
  1258. *
  1259. * @since 2.5.0
  1260. *
  1261. * @param int $post_id Optional. Restrict the comment counts to the given post. Default 0, which indicates that
  1262. * comment counts for the whole site will be retrieved.
  1263. * @return stdClass {
  1264. * The number of comments keyed by their status.
  1265. *
  1266. * @type int $approved The number of approved comments.
  1267. * @type int $moderated The number of comments awaiting moderation (a.k.a. pending).
  1268. * @type int $spam The number of spam comments.
  1269. * @type int $trash The number of trashed comments.
  1270. * @type int $post-trashed The number of comments for posts that are in the trash.
  1271. * @type int $total_comments The total number of non-trashed comments, including spam.
  1272. * @type int $all The total number of pending or approved comments.
  1273. * }
  1274. */
  1275. function wp_count_comments( $post_id = 0 ) {
  1276. $post_id = (int) $post_id;
  1277. /**
  1278. * Filters the comments count for a given post or the whole site.
  1279. *
  1280. * @since 2.7.0
  1281. *
  1282. * @param array|stdClass $count An empty array or an object containing comment counts.
  1283. * @param int $post_id The post ID. Can be 0 to represent the whole site.
  1284. */
  1285. $filtered = apply_filters( 'wp_count_comments', array(), $post_id );
  1286. if ( ! empty( $filtered ) ) {
  1287. return $filtered;
  1288. }
  1289. $count = wp_cache_get( "comments-{$post_id}", 'counts' );
  1290. if ( false !== $count ) {
  1291. return $count;
  1292. }
  1293. $stats = get_comment_count( $post_id );
  1294. $stats['moderated'] = $stats['awaiting_moderation'];
  1295. unset( $stats['awaiting_moderation'] );
  1296. $stats_object = (object) $stats;
  1297. wp_cache_set( "comments-{$post_id}", $stats_object, 'counts' );
  1298. return $stats_object;
  1299. }
  1300. /**
  1301. * Trashes or deletes a comment.
  1302. *
  1303. * The comment is moved to Trash instead of permanently deleted unless Trash is
  1304. * disabled, item is already in the Trash, or $force_delete is true.
  1305. *
  1306. * The post comment count will be updated if the comment was approved and has a
  1307. * post ID available.
  1308. *
  1309. * @since 2.0.0
  1310. *
  1311. * @global wpdb $wpdb WordPress database abstraction object.
  1312. *
  1313. * @param int|WP_Comment $comment_id Comment ID or WP_Comment object.
  1314. * @param bool $force_delete Whether to bypass Trash and force deletion. Default false.
  1315. * @return bool True on success, false on failure.
  1316. */
  1317. function wp_delete_comment( $comment_id, $force_delete = false ) {
  1318. global $wpdb;
  1319. $comment = get_comment( $comment_id );
  1320. if ( ! $comment ) {
  1321. return false;
  1322. }
  1323. if ( ! $force_delete && EMPTY_TRASH_DAYS && ! in_array( wp_get_comment_status( $comment ), array( 'trash', 'spam' ), true ) ) {
  1324. return wp_trash_comment( $comment_id );
  1325. }
  1326. /**
  1327. * Fires immediately before a comment is deleted from the database.
  1328. *
  1329. * @since 1.2.0
  1330. * @since 4.9.0 Added the `$comment` parameter.
  1331. *
  1332. * @param int $comment_id The comment ID.
  1333. * @param WP_Comment $comment The comment to be deleted.
  1334. */
  1335. do_action( 'delete_comment', $comment->comment_ID, $comment );
  1336. // Move children up a level.
  1337. $children = $wpdb->get_col( $wpdb->prepare( "SELECT comment_ID FROM $wpdb->comments WHERE comment_parent = %d", $comment->comment_ID ) );
  1338. if ( ! empty( $children ) ) {
  1339. $wpdb->update( $wpdb->comments, array( 'comment_parent' => $comment->comment_parent ), array( 'comment_parent' => $comment->comment_ID ) );
  1340. clean_comment_cache( $children );
  1341. }
  1342. // Delete metadata.
  1343. $meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->commentmeta WHERE comment_id = %d", $comment->comment_ID ) );
  1344. foreach ( $meta_ids as $mid ) {
  1345. delete_metadata_by_mid( 'comment', $mid );
  1346. }
  1347. if ( ! $wpdb->delete( $wpdb->comments, array( 'comment_ID' => $comment->comment_ID ) ) ) {
  1348. return false;
  1349. }
  1350. /**
  1351. * Fires immediately after a comment is deleted from the database.
  1352. *
  1353. * @since 2.9.0
  1354. * @since 4.9.0 Added the `$comment` parameter.
  1355. *
  1356. * @param int $comment_id The comment ID.
  1357. * @param WP_Comment $comment The deleted comment.
  1358. */
  1359. do_action( 'deleted_comment', $comment->comment_ID, $comment );
  1360. $post_id = $comment->comment_post_ID;
  1361. if ( $post_id && 1 == $comment->comment_approved ) {
  1362. wp_update_comment_count( $post_id );
  1363. }
  1364. clean_comment_cache( $comment->comment_ID );
  1365. /** This action is documented in wp-includes/comment.php */
  1366. do_action( 'wp_set_comment_status', $comment->comment_ID, 'delete' );
  1367. wp_transition_comment_status( 'delete', $comment->comment_approved, $comment );
  1368. return true;
  1369. }
  1370. /**
  1371. * Moves a comment to the Trash
  1372. *
  1373. * If Trash is disabled, comment is permanently deleted.
  1374. *
  1375. * @since 2.9.0
  1376. *
  1377. * @param int|WP_Comment $comment_id Comment ID or WP_Comment object.
  1378. * @return bool True on success, false on failure.
  1379. */
  1380. function wp_trash_comment( $comment_id ) {
  1381. if ( ! EMPTY_TRASH_DAYS ) {
  1382. return wp_delete_comment( $comment_id, true );
  1383. }
  1384. $comment = get_comment( $comment_id );
  1385. if ( ! $comment ) {
  1386. return false;
  1387. }
  1388. /**
  1389. * Fires immediately before a comment is sent to the Trash.
  1390. *
  1391. * @since 2.9.0
  1392. * @since 4.9.0 Added the `$comment` parameter.
  1393. *
  1394. * @param int $comment_id The comment ID.
  1395. * @param WP_Comment $comment The comment to be trashed.
  1396. */
  1397. do_action( 'trash_comment', $comment->comment_ID, $comment );
  1398. if ( wp_set_comment_status( $comment, 'trash' ) ) {
  1399. delete_comment_meta( $comment->comment_ID, '_wp_trash_meta_status' );
  1400. delete_comment_meta( $comment->comment_ID, '_wp_trash_meta_time' );
  1401. add_comment_meta( $comment->comment_ID, '_wp_trash_meta_status', $comment->comment_approved );
  1402. add_comment_meta( $comment->comment_ID, '_wp_trash_meta_time', time() );
  1403. /**
  1404. * Fires immediately after a comment is sent to Trash.
  1405. *
  1406. * @since 2.9.0
  1407. * @since 4.9.0 Added the `$comment` parameter.
  1408. *
  1409. * @param int $comment_id The comment ID.
  1410. * @param WP_Comment $comment The trashed comment.
  1411. */
  1412. do_action( 'trashed_comment', $comment->comment_ID, $comment );
  1413. return true;
  1414. }
  1415. return false;
  1416. }
  1417. /**
  1418. * Removes a comment from the Trash
  1419. *
  1420. * @since 2.9.0
  1421. *
  1422. * @param int|WP_Comment $comment_id Comment ID or WP_Comment object.
  1423. * @return bool True on success, false on failure.
  1424. */
  1425. function wp_untrash_comment( $comment_id ) {
  1426. $comment = get_comment( $comment_id );
  1427. if ( ! $comment ) {
  1428. return false;
  1429. }
  1430. /**
  1431. * Fires immediately before a comment is restored from the Trash.
  1432. *
  1433. * @since 2.9.0
  1434. * @since 4.9.0 Added the `$comment` parameter.
  1435. *
  1436. * @param int $comment_id The comment ID.
  1437. * @param WP_Comment $comment The comment to be untrashed.
  1438. */
  1439. do_action( 'untrash_comment', $comment->comment_ID, $comment );
  1440. $status = (string) get_comment_meta( $comment->comment_ID, '_wp_trash_meta_status', true );
  1441. if ( empty( $status ) ) {
  1442. $status = '0';
  1443. }
  1444. if ( wp_set_comment_status( $comment, $status ) ) {
  1445. delete_comment_meta( $comment->comment_ID, '_wp_trash_meta_time' );
  1446. delete_comment_meta( $comment->comment_ID, '_wp_trash_meta_status' );
  1447. /**
  1448. * Fires immediately after a comment is restored from the Trash.
  1449. *
  1450. * @since 2.9.0
  1451. * @since 4.9.0 Added the `$comment` parameter.
  1452. *
  1453. * @param int $comment_id The comment ID.
  1454. * @param WP_Comment $comment The untrashed comment.
  1455. */
  1456. do_action( 'untrashed_comment', $comment->comment_ID, $comment );
  1457. return true;
  1458. }
  1459. return false;
  1460. }
  1461. /**
  1462. * Marks a comment as Spam
  1463. *
  1464. * @since 2.9.0
  1465. *
  1466. * @param int|WP_Comment $comment_id Comment ID or WP_Comment object.
  1467. * @return bool True on success, false on failure.
  1468. */
  1469. function wp_spam_comment( $comment_id ) {
  1470. $comment = get_comment( $comment_id );
  1471. if ( ! $comment ) {
  1472. return false;
  1473. }
  1474. /**
  1475. * Fires immediately before a comment is marked as Spam.
  1476. *
  1477. * @since 2.9.0
  1478. * @since 4.9.0 Added the `$comment` parameter.
  1479. *
  1480. * @param int $comment_id The comment ID.
  1481. * @param WP_Comment $comment The comment to be marked as spam.
  1482. */
  1483. do_action( 'spam_comment', $comment->comment_ID, $comment );
  1484. if ( wp_set_comment_status( $comment, 'spam' ) ) {
  1485. delete_comment_meta( $comment->comment_ID, '_wp_trash_meta_status' );
  1486. delete_comment_meta( $comment->comment_ID, '_wp_trash_meta_time' );
  1487. add_comment_meta( $comment->comment_ID, '_wp_trash_meta_status', $comment->comment_approved );
  1488. add_comment_meta( $comment->comment_ID, '_wp_trash_meta_time', time() );
  1489. /**
  1490. * Fires immediately after a comment is marked as Spam.
  1491. *
  1492. * @since 2.9.0
  1493. * @since 4.9.0 Added the `$comment` parameter.
  1494. *
  1495. * @param int $comment_id The comment ID.
  1496. * @param WP_Comment $comment The comment marked as spam.
  1497. */
  1498. do_action( 'spammed_comment', $comment->comment_ID, $comment );
  1499. return true;
  1500. }
  1501. return false;
  1502. }
  1503. /**
  1504. * Removes a comment from the Spam
  1505. *
  1506. * @since 2.9.0
  1507. *
  1508. * @param int|WP_Comment $comment_id Comment ID or WP_Comment object.
  1509. * @return bool True on success, false on failure.
  1510. */
  1511. function wp_unspam_comment( $comment_id ) {
  1512. $comment = get_comment( $comment_id );
  1513. if ( ! $comment ) {
  1514. return false;
  1515. }
  1516. /**
  1517. * Fires immediately before a comment is unmarked as Spam.
  1518. *
  1519. * @since 2.9.0
  1520. * @since 4.9.0 Added the `$comment` parameter.
  1521. *
  1522. * @param int $comment_id The comment ID.
  1523. * @param WP_Comment $comment The comment to be unmarked as spam.
  1524. */
  1525. do_action( 'unspam_comment', $comment->comment_ID, $comment );
  1526. $status = (string) get_comment_meta( $comment->comment_ID, '_wp_trash_meta_status', true );
  1527. if ( empty( $status ) ) {
  1528. $status = '0';
  1529. }
  1530. if ( wp_set_comment_status( $comment, $status ) ) {
  1531. delete_comment_meta( $comment->comment_ID, '_wp_trash_meta_status' );
  1532. delete_comment_meta( $comment->comment_ID, '_wp_trash_meta_time' );
  1533. /**
  1534. * Fires immediately after a comment is unmarked as Spam.
  1535. *
  1536. * @since 2.9.0
  1537. * @since 4.9.0 Added the `$comment` parameter.
  1538. *
  1539. * @param int $comment_id The comment ID.
  1540. * @param WP_Comment $comment The comment unmarked as spam.
  1541. */
  1542. do_action( 'unspammed_comment', $comment->comment_ID, $comment );
  1543. return true;
  1544. }
  1545. return false;
  1546. }
  1547. /**
  1548. * The status of a comment by ID.
  1549. *
  1550. * @since 1.0.0
  1551. *
  1552. * @param int|WP_Comment $comment_id Comment ID or WP_Comment object
  1553. * @return string|false Status might be 'trash', 'approved', 'unapproved', 'spam'. False on failure.
  1554. */
  1555. function wp_get_comment_status( $comment_id ) {
  1556. $comment = get_comment( $comment_id );
  1557. if ( ! $comment ) {
  1558. return false;
  1559. }
  1560. $approved = $comment->comment_approved;
  1561. if ( null == $approved ) {
  1562. return false;
  1563. } elseif ( '1' == $approved ) {
  1564. return 'approved';
  1565. } elseif ( '0' == $approved ) {
  1566. return 'unapproved';
  1567. } elseif ( 'spam' === $approved ) {
  1568. return 'spam';
  1569. } elseif ( 'trash' === $approved ) {
  1570. return 'trash';
  1571. } else {
  1572. return false;
  1573. }
  1574. }
  1575. /**
  1576. * Call hooks for when a comment status transition occurs.
  1577. *
  1578. * Calls hooks for comment status transitions. If the new comment status is not the same
  1579. * as the previous comment status, then two hooks will be ran, the first is
  1580. * {@see 'transition_comment_status'} with new status, old status, and comment data.
  1581. * The next action called is {@see 'comment_$old_status_to_$new_status'}. It has
  1582. * the comment data.
  1583. *
  1584. * The final action will run whether or not the comment statuses are the same.
  1585. * The action is named {@see 'comment_$new_status_$comment->comment_type'}.
  1586. *
  1587. * @since 2.7.0
  1588. *
  1589. * @param string $new_status New comment status.
  1590. * @param string $old_status Previous comment status.
  1591. * @param WP_Comment $comment Comment object.
  1592. */
  1593. function wp_transition_comment_status( $new_status, $old_status, $comment ) {
  1594. /*
  1595. * Translate raw statuses to human-readable formats for the hooks.
  1596. * This is not a complete list of comment status, it's only the ones
  1597. * that need to be renamed.
  1598. */
  1599. $comment_statuses = array(
  1600. 0 => 'unapproved',
  1601. 'hold' => 'unapproved', // wp_set_comment_status() uses "hold".
  1602. 1 => 'approved',
  1603. 'approve' => 'approved', // wp_set_comment_status() uses "approve".
  1604. );
  1605. if ( isset( $comment_statuses[ $new_status ] ) ) {
  1606. $new_status = $comment_statuses[ $new_status ];
  1607. }
  1608. if ( isset( $comment_statuses[ $old_status ] ) ) {
  1609. $old_status = $comment_statuses[ $old_status ];
  1610. }
  1611. // Call the hooks.
  1612. if ( $new_status != $old_status ) {
  1613. /**
  1614. * Fires when the comment status is in transition.
  1615. *
  1616. * @since 2.7.0
  1617. *
  1618. * @param int|string $new_status The new comment status.
  1619. * @param int|string $old_status The old comment status.
  1620. * @param WP_Comment $comment Comment object.
  1621. */
  1622. do_action( 'transition_comment_status', $new_status, $old_status, $comment );
  1623. /**
  1624. * Fires when the comment status is in transition from one specific status to another.
  1625. *
  1626. * The dynamic portions of the hook name, `$old_status`, and `$new_status`,
  1627. * refer to the old and new comment statuses, respectively.
  1628. *
  1629. * @since 2.7.0
  1630. *
  1631. * @param WP_Comment $comment Comment object.
  1632. */
  1633. do_action( "comment_{$old_status}_to_{$new_status}", $comment );
  1634. }
  1635. /**
  1636. * Fires when the status of a specific comment type is in transition.
  1637. *
  1638. * The dynamic portions of the hook name, `$new_status`, and `$comment->comment_type`,
  1639. * refer to the new comment status, and the type of comment, respectively.
  1640. *
  1641. * Typical comment types include an empty string (standard comment), 'pingback',
  1642. * or 'trackback'.
  1643. *
  1644. * @since 2.7.0
  1645. *
  1646. * @param int $comment_ID The comment ID.
  1647. * @param WP_Comment $comment Comment object.
  1648. */
  1649. do_action( "comment_{$new_status}_{$comment->comment_type}", $comment->comment_ID, $comment );
  1650. }
  1651. /**
  1652. * Clear the lastcommentmodified cached value when a comment status is changed.
  1653. *
  1654. * Deletes the lastcommentmodified cache key when a comment enters or leaves
  1655. * 'approved' status.
  1656. *
  1657. * @since 4.7.0
  1658. * @access private
  1659. *
  1660. * @param string $new_status The new comment status.
  1661. * @param string $old_status The old comment status.
  1662. */
  1663. function _clear_modified_cache_on_transition_comment_status( $new_status, $old_status ) {
  1664. if ( 'approved' === $new_status || 'approved' === $old_status ) {
  1665. foreach ( array( 'server', 'gmt', 'blog' ) as $timezone ) {
  1666. wp_cache_delete( "lastcommentmodified:$timezone", 'timeinfo' );
  1667. }
  1668. }
  1669. }
  1670. /**
  1671. * Get current commenter's name, email, and URL.
  1672. *
  1673. * Expects cookies content to already be sanitized. User of this function might
  1674. * wish to recheck the returned array for validity.
  1675. *
  1676. * @see sanitize_comment_cookies() Use to sanitize cookies
  1677. *
  1678. * @since 2.0.4
  1679. *
  1680. * @return array {
  1681. * An array of current commenter variables.
  1682. *
  1683. * @type string $comment_author The name of the current commenter, or an empty string.
  1684. * @type string $comment_author_email The email address of the current commenter, or an empty string.
  1685. * @type string $comment_author_url The URL address of the current commenter, or an empty string.
  1686. * }
  1687. */
  1688. function wp_get_current_commenter() {
  1689. // Cookies should already be sanitized.
  1690. $comment_author = '';
  1691. if ( isset( $_COOKIE[ 'comment_author_' . COOKIEHASH ] ) ) {
  1692. $comment_author = $_COOKIE[ 'comment_author_' . COOKIEHASH ];
  1693. }
  1694. $comment_author_email = '';
  1695. if ( isset( $_COOKIE[ 'comment_author_email_' . COOKIEHASH ] ) ) {
  1696. $comment_author_email = $_COOKIE[ 'comment_author_email_' . COOKIEHASH ];
  1697. }
  1698. $comment_author_url = '';
  1699. if ( isset( $_COOKIE[ 'comment_author_url_' . COOKIEHASH ] ) ) {
  1700. $comment_author_url = $_COOKIE[ 'comment_author_url_' . COOKIEHASH ];
  1701. }
  1702. /**
  1703. * Filters the current commenter's name, email, and URL.
  1704. *
  1705. * @since 3.1.0
  1706. *
  1707. * @param array $comment_author_data {
  1708. * An array of current commenter variables.
  1709. *
  1710. * @type string $comment_author The name of the current commenter, or an empty string.
  1711. * @type string $comment_author_email The email address of the current commenter, or an empty string.
  1712. * @type string $comment_author_url The URL address of the current commenter, or an empty string.
  1713. * }
  1714. */
  1715. return apply_filters( 'wp_get_current_commenter', compact( 'comment_author', 'comment_author_email', 'comment_author_url' ) );
  1716. }
  1717. /**
  1718. * Get unapproved comment author's email.
  1719. *
  1720. * Used to allow the commenter to see their pending comment.
  1721. *
  1722. * @since 5.1.0
  1723. * @since 5.7.0 The window within which the author email for an unapproved comment
  1724. * can be retrieved was extended to 10 minutes.
  1725. *
  1726. * @return string The unapproved comment author's email (when supplied).
  1727. */
  1728. function wp_get_unapproved_comment_author_email() {
  1729. $commenter_email = '';
  1730. if ( ! empty( $_GET['unapproved'] ) && ! empty( $_GET['moderation-hash'] ) ) {
  1731. $comment_id = (int) $_GET['unapproved'];
  1732. $comment = get_comment( $comment_id );
  1733. if ( $comment && hash_equals( $_GET['moderation-hash'], wp_hash( $comment->comment_date_gmt ) ) ) {
  1734. // The comment will only be viewable by the comment author for 10 minutes.
  1735. $comment_preview_expires = strtotime( $comment->comment_date_gmt . '+10 minutes' );
  1736. if ( time() < $comment_preview_expires ) {
  1737. $commenter_email = $comment->comment_author_email;
  1738. }
  1739. }
  1740. }
  1741. if ( ! $commenter_email ) {
  1742. $commenter = wp_get_current_commenter();
  1743. $commenter_email = $commenter['comment_author_email'];
  1744. }
  1745. return $commenter_email;
  1746. }
  1747. /**
  1748. * Inserts a comment into the database.
  1749. *
  1750. * @since 2.0.0
  1751. * @since 4.4.0 Introduced the `$comment_meta` argument.
  1752. * @since 5.5.0 Default value for `$comment_type` argument changed to `comment`.
  1753. *
  1754. * @global wpdb $wpdb WordPress database abstraction object.
  1755. *
  1756. * @param array $commentdata {
  1757. * Array of arguments for inserting a new comment.
  1758. *
  1759. * @type string $comment_agent The HTTP user agent of the `$comment_author` when
  1760. * the comment was submitted. Default empty.
  1761. * @type int|string $comment_approved Whether the comment has been approved. Default 1.
  1762. * @type string $comment_author The name of the author of the comment. Default empty.
  1763. * @type string $comment_author_email The email address of the `$comment_author`. Default empty.
  1764. * @type string $comment_author_IP The IP address of the `$comment_author`. Default empty.
  1765. * @type string $comment_author_url The URL address of the `$comment_author`. Default empty.
  1766. * @type string $comment_content The content of the comment. Default empty.
  1767. * @type string $comment_date The date the comment was submitted. To set the date
  1768. * manually, `$comment_date_gmt` must also be specified.
  1769. * Default is the current time.
  1770. * @type string $comment_date_gmt The date the comment was submitted in the GMT timezone.
  1771. * Default is `$comment_date` in the site's GMT timezone.
  1772. * @type int $comment_karma The karma of the comment. Default 0.
  1773. * @type int $comment_parent ID of this comment's parent, if any. Default 0.
  1774. * @type int $comment_post_ID ID of the post that relates to the comment, if any.
  1775. * Default 0.
  1776. * @type string $comment_type Comment type. Default 'comment'.
  1777. * @type array $comment_meta Optional. Array of key/value pairs to be stored in commentmeta for the
  1778. * new comment.
  1779. * @type int $user_id ID of the user who submitted the comment. Default 0.
  1780. * }
  1781. * @return int|false The new comment's ID on success, false on failure.
  1782. */
  1783. function wp_insert_comment( $commentdata ) {
  1784. global $wpdb;
  1785. $data = wp_unslash( $commentdata );
  1786. $comment_author = ! isset( $data['comment_author'] ) ? '' : $data['comment_author'];
  1787. $comment_author_email = ! isset( $data['comment_author_email'] ) ? '' : $data['comment_author_email'];
  1788. $comment_author_url = ! isset( $data['comment_author_url'] ) ? '' : $data['comment_author_url'];
  1789. $comment_author_IP = ! isset( $data['comment_author_IP'] ) ? '' : $data['comment_author_IP'];
  1790. $comment_date = ! isset( $data['comment_date'] ) ? current_time( 'mysql' ) : $data['comment_date'];
  1791. $comment_date_gmt = ! isset( $data['comment_date_gmt'] ) ? get_gmt_from_date( $comment_date ) : $data['comment_date_gmt'];
  1792. $comment_post_ID = ! isset( $data['comment_post_ID'] ) ? 0 : $data['comment_post_ID'];
  1793. $comment_content = ! isset( $data['comment_content'] ) ? '' : $data['comment_content'];
  1794. $comment_karma = ! isset( $data['comment_karma'] ) ? 0 : $data['comment_karma'];
  1795. $comment_approved = ! isset( $data['comment_approved'] ) ? 1 : $data['comment_approved'];
  1796. $comment_agent = ! isset( $data['comment_agent'] ) ? '' : $data['comment_agent'];
  1797. $comment_type = empty( $data['comment_type'] ) ? 'comment' : $data['comment_type'];
  1798. $comment_parent = ! isset( $data['comment_parent'] ) ? 0 : $data['comment_parent'];
  1799. $user_id = ! isset( $data['user_id'] ) ? 0 : $data['user_id'];
  1800. $compacted = compact( 'comment_post_ID', 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_author_IP', 'comment_date', 'comment_date_gmt', 'comment_content', 'comment_karma', 'comment_approved', 'comment_agent', 'comment_type', 'comment_parent', 'user_id' );
  1801. if ( ! $wpdb->insert( $wpdb->comments, $compacted ) ) {
  1802. return false;
  1803. }
  1804. $id = (int) $wpdb->insert_id;
  1805. if ( 1 == $comment_approved ) {
  1806. wp_update_comment_count( $comment_post_ID );
  1807. foreach ( array( 'server', 'gmt', 'blog' ) as $timezone ) {
  1808. wp_cache_delete( "lastcommentmodified:$timezone", 'timeinfo' );
  1809. }
  1810. }
  1811. clean_comment_cache( $id );
  1812. $comment = get_comment( $id );
  1813. // If metadata is provided, store it.
  1814. if ( isset( $commentdata['comment_meta'] ) && is_array( $commentdata['comment_meta'] ) ) {
  1815. foreach ( $commentdata['comment_meta'] as $meta_key => $meta_value ) {
  1816. add_comment_meta( $comment->comment_ID, $meta_key, $meta_value, true );
  1817. }
  1818. }
  1819. /**
  1820. * Fires immediately after a comment is inserted into the database.
  1821. *
  1822. * @since 2.8.0
  1823. *
  1824. * @param int $id The comment ID.
  1825. * @param WP_Comment $comment Comment object.
  1826. */
  1827. do_action( 'wp_insert_comment', $id, $comment );
  1828. return $id;
  1829. }
  1830. /**
  1831. * Filters and sanitizes comment data.
  1832. *
  1833. * Sets the comment data 'filtered' field to true when finished. This can be
  1834. * checked as to whether the comment should be filtered and to keep from
  1835. * filtering the same comment more than once.
  1836. *
  1837. * @since 2.0.0
  1838. *
  1839. * @param array $commentdata Contains information on the comment.
  1840. * @return array Parsed comment information.
  1841. */
  1842. function wp_filter_comment( $commentdata ) {
  1843. if ( isset( $commentdata['user_ID'] ) ) {
  1844. /**
  1845. * Filters the comment author's user ID before it is set.
  1846. *
  1847. * The first time this filter is evaluated, 'user_ID' is checked
  1848. * (for back-compat), followed by the standard 'user_id' value.
  1849. *
  1850. * @since 1.5.0
  1851. *
  1852. * @param int $user_ID The comment author's user ID.
  1853. */
  1854. $commentdata['user_id'] = apply_filters( 'pre_user_id', $commentdata['user_ID'] );
  1855. } elseif ( isset( $commentdata['user_id'] ) ) {
  1856. /** This filter is documented in wp-includes/comment.php */
  1857. $commentdata['user_id'] = apply_filters( 'pre_user_id', $commentdata['user_id'] );
  1858. }
  1859. /**
  1860. * Filters the comment author's browser user agent before it is set.
  1861. *
  1862. * @since 1.5.0
  1863. *
  1864. * @param string $comment_agent The comment author's browser user agent.
  1865. */
  1866. $commentdata['comment_agent'] = apply_filters( 'pre_comment_user_agent', ( isset( $commentdata['comment_agent'] ) ? $commentdata['comment_agent'] : '' ) );
  1867. /** This filter is documented in wp-includes/comment.php */
  1868. $commentdata['comment_author'] = apply_filters( 'pre_comment_author_name', $commentdata['comment_author'] );
  1869. /**
  1870. * Filters the comment content before it is set.
  1871. *
  1872. * @since 1.5.0
  1873. *
  1874. * @param string $comment_content The comment content.
  1875. */
  1876. $commentdata['comment_content'] = apply_filters( 'pre_comment_content', $commentdata['comment_content'] );
  1877. /**
  1878. * Filters the comment author's IP address before it is set.
  1879. *
  1880. * @since 1.5.0
  1881. *
  1882. * @param string $comment_author_ip The comment author's IP address.
  1883. */
  1884. $commentdata['comment_author_IP'] = apply_filters( 'pre_comment_user_ip', $commentdata['comment_author_IP'] );
  1885. /** This filter is documented in wp-includes/comment.php */
  1886. $commentdata['comment_author_url'] = apply_filters( 'pre_comment_author_url', $commentdata['comment_author_url'] );
  1887. /** This filter is documented in wp-includes/comment.php */
  1888. $commentdata['comment_author_email'] = apply_filters( 'pre_comment_author_email', $commentdata['comment_author_email'] );
  1889. $commentdata['filtered'] = true;
  1890. return $commentdata;
  1891. }
  1892. /**
  1893. * Whether a comment should be blocked because of comment flood.
  1894. *
  1895. * @since 2.1.0
  1896. *
  1897. * @param bool $block Whether plugin has already blocked comment.
  1898. * @param int $time_lastcomment Timestamp for last comment.
  1899. * @param int $time_newcomment Timestamp for new comment.
  1900. * @return bool Whether comment should be blocked.
  1901. */
  1902. function wp_throttle_comment_flood( $block, $time_lastcomment, $time_newcomment ) {
  1903. if ( $block ) { // A plugin has already blocked... we'll let that decision stand.
  1904. return $block;
  1905. }
  1906. if ( ( $time_newcomment - $time_lastcomment ) < 15 ) {
  1907. return true;
  1908. }
  1909. return false;
  1910. }
  1911. /**
  1912. * Adds a new comment to the database.
  1913. *
  1914. * Filters new comment to ensure that the fields are sanitized and valid before
  1915. * inserting comment into database. Calls {@see 'comment_post'} action with comment ID
  1916. * and whether comment is approved by WordPress. Also has {@see 'preprocess_comment'}
  1917. * filter for processing the comment data before the function handles it.
  1918. *
  1919. * We use `REMOTE_ADDR` here directly. If you are behind a proxy, you should ensure
  1920. * that it is properly set, such as in wp-config.php, for your environment.
  1921. *
  1922. * See {@link https://core.trac.wordpress.org/ticket/9235}
  1923. *
  1924. * @since 1.5.0
  1925. * @since 4.3.0 Introduced the `comment_agent` and `comment_author_IP` arguments.
  1926. * @since 4.7.0 The `$avoid_die` parameter was added, allowing the function
  1927. * to return a WP_Error object instead of dying.
  1928. * @since 5.5.0 The `$avoid_die` parameter was renamed to `$wp_error`.
  1929. * @since 5.5.0 Introduced the `comment_type` argument.
  1930. *
  1931. * @see wp_insert_comment()
  1932. * @global wpdb $wpdb WordPress database abstraction object.
  1933. *
  1934. * @param array $commentdata {
  1935. * Comment data.
  1936. *
  1937. * @type string $comment_author The name of the comment author.
  1938. * @type string $comment_author_email The comment author email address.
  1939. * @type string $comment_author_url The comment author URL.
  1940. * @type string $comment_content The content of the comment.
  1941. * @type string $comment_date The date the comment was submitted. Default is the current time.
  1942. * @type string $comment_date_gmt The date the comment was submitted in the GMT timezone.
  1943. * Default is `$comment_date` in the GMT timezone.
  1944. * @type string $comment_type Comment type. Default 'comment'.
  1945. * @type int $comment_parent The ID of this comment's parent, if any. Default 0.
  1946. * @type int $comment_post_ID The ID of the post that relates to the comment.
  1947. * @type int $user_id The ID of the user who submitted the comment. Default 0.
  1948. * @type int $user_ID Kept for backward-compatibility. Use `$user_id` instead.
  1949. * @type string $comment_agent Comment author user agent. Default is the value of 'HTTP_USER_AGENT'
  1950. * in the `$_SERVER` superglobal sent in the original request.
  1951. * @type string $comment_author_IP Comment author IP address in IPv4 format. Default is the value of
  1952. * 'REMOTE_ADDR' in the `$_SERVER` superglobal sent in the original request.
  1953. * }
  1954. * @param bool $wp_error Should errors be returned as WP_Error objects instead of
  1955. * executing wp_die()? Default false.
  1956. * @return int|false|WP_Error The ID of the comment on success, false or WP_Error on failure.
  1957. */
  1958. function wp_new_comment( $commentdata, $wp_error = false ) {
  1959. global $wpdb;
  1960. if ( isset( $commentdata['user_ID'] ) ) {
  1961. $commentdata['user_ID'] = (int) $commentdata['user_ID'];
  1962. $commentdata['user_id'] = $commentdata['user_ID'];
  1963. }
  1964. $prefiltered_user_id = ( isset( $commentdata['user_id'] ) ) ? (int) $commentdata['user_id'] : 0;
  1965. if ( ! isset( $commentdata['comment_author_IP'] ) ) {
  1966. $commentdata['comment_author_IP'] = $_SERVER['REMOTE_ADDR'];
  1967. }
  1968. if ( ! isset( $commentdata['comment_agent'] ) ) {
  1969. $commentdata['comment_agent'] = isset( $_SERVER['HTTP_USER_AGENT'] ) ? $_SERVER['HTTP_USER_AGENT'] : '';
  1970. }
  1971. /**
  1972. * Filters a comment's data before it is sanitized and inserted into the database.
  1973. *
  1974. * @since 1.5.0
  1975. * @since 5.6.0 Comment data includes the `comment_agent` and `comment_author_IP` values.
  1976. *
  1977. * @param array $commentdata Comment data.
  1978. */
  1979. $commentdata = apply_filters( 'preprocess_comment', $commentdata );
  1980. $commentdata['comment_post_ID'] = (int) $commentdata['comment_post_ID'];
  1981. if ( isset( $commentdata['user_ID'] ) && $prefiltered_user_id !== (int) $commentdata['user_ID'] ) {
  1982. $commentdata['user_ID'] = (int) $commentdata['user_ID'];
  1983. $commentdata['user_id'] = $commentdata['user_ID'];
  1984. } elseif ( isset( $commentdata['user_id'] ) ) {
  1985. $commentdata['user_id'] = (int) $commentdata['user_id'];
  1986. }
  1987. $commentdata['comment_parent'] = isset( $commentdata['comment_parent'] ) ? absint( $commentdata['comment_parent'] ) : 0;
  1988. $parent_status = ( $commentdata['comment_parent'] > 0 ) ? wp_get_comment_status( $commentdata['comment_parent'] ) : '';
  1989. $commentdata['comment_parent'] = ( 'approved' === $parent_status || 'unapproved' === $parent_status ) ? $commentdata['comment_parent'] : 0;
  1990. $commentdata['comment_author_IP'] = preg_replace( '/[^0-9a-fA-F:., ]/', '', $commentdata['comment_author_IP'] );
  1991. $commentdata['comment_agent'] = substr( $commentdata['comment_agent'], 0, 254 );
  1992. if ( empty( $commentdata['comment_date'] ) ) {
  1993. $commentdata['comment_date'] = current_time( 'mysql' );
  1994. }
  1995. if ( empty( $commentdata['comment_date_gmt'] ) ) {
  1996. $commentdata['comment_date_gmt'] = current_time( 'mysql', 1 );
  1997. }
  1998. if ( empty( $commentdata['comment_type'] ) ) {
  1999. $commentdata['comment_type'] = 'comment';
  2000. }
  2001. $commentdata = wp_filter_comment( $commentdata );
  2002. $commentdata['comment_approved'] = wp_allow_comment( $commentdata, $wp_error );
  2003. if ( is_wp_error( $commentdata['comment_approved'] ) ) {
  2004. return $commentdata['comment_approved'];
  2005. }
  2006. $comment_ID = wp_insert_comment( $commentdata );
  2007. if ( ! $comment_ID ) {
  2008. $fields = array( 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_content' );
  2009. foreach ( $fields as $field ) {
  2010. if ( isset( $commentdata[ $field ] ) ) {
  2011. $commentdata[ $field ] = $wpdb->strip_invalid_text_for_column( $wpdb->comments, $field, $commentdata[ $field ] );
  2012. }
  2013. }
  2014. $commentdata = wp_filter_comment( $commentdata );
  2015. $commentdata['comment_approved'] = wp_allow_comment( $commentdata, $wp_error );
  2016. if ( is_wp_error( $commentdata['comment_approved'] ) ) {
  2017. return $commentdata['comment_approved'];
  2018. }
  2019. $comment_ID = wp_insert_comment( $commentdata );
  2020. if ( ! $comment_ID ) {
  2021. return false;
  2022. }
  2023. }
  2024. /**
  2025. * Fires immediately after a comment is inserted into the database.
  2026. *
  2027. * @since 1.2.0
  2028. * @since 4.5.0 The `$commentdata` parameter was added.
  2029. *
  2030. * @param int $comment_ID The comment ID.
  2031. * @param int|string $comment_approved 1 if the comment is approved, 0 if not, 'spam' if spam.
  2032. * @param array $commentdata Comment data.
  2033. */
  2034. do_action( 'comment_post', $comment_ID, $commentdata['comment_approved'], $commentdata );
  2035. return $comment_ID;
  2036. }
  2037. /**
  2038. * Send a comment moderation notification to the comment moderator.
  2039. *
  2040. * @since 4.4.0
  2041. *
  2042. * @param int $comment_ID ID of the comment.
  2043. * @return bool True on success, false on failure.
  2044. */
  2045. function wp_new_comment_notify_moderator( $comment_ID ) {
  2046. $comment = get_comment( $comment_ID );
  2047. // Only send notifications for pending comments.
  2048. $maybe_notify = ( '0' == $comment->comment_approved );
  2049. /** This filter is documented in wp-includes/comment.php */
  2050. $maybe_notify = apply_filters( 'notify_moderator', $maybe_notify, $comment_ID );
  2051. if ( ! $maybe_notify ) {
  2052. return false;
  2053. }
  2054. return wp_notify_moderator( $comment_ID );
  2055. }
  2056. /**
  2057. * Send a notification of a new comment to the post author.
  2058. *
  2059. * @since 4.4.0
  2060. *
  2061. * Uses the {@see 'notify_post_author'} filter to determine whether the post author
  2062. * should be notified when a new comment is added, overriding site setting.
  2063. *
  2064. * @param int $comment_ID Comment ID.
  2065. * @return bool True on success, false on failure.
  2066. */
  2067. function wp_new_comment_notify_postauthor( $comment_ID ) {
  2068. $comment = get_comment( $comment_ID );
  2069. $maybe_notify = get_option( 'comments_notify' );
  2070. /**
  2071. * Filters whether to send the post author new comment notification emails,
  2072. * overriding the site setting.
  2073. *
  2074. * @since 4.4.0
  2075. *
  2076. * @param bool $maybe_notify Whether to notify the post author about the new comment.
  2077. * @param int $comment_ID The ID of the comment for the notification.
  2078. */
  2079. $maybe_notify = apply_filters( 'notify_post_author', $maybe_notify, $comment_ID );
  2080. /*
  2081. * wp_notify_postauthor() checks if notifying the author of their own comment.
  2082. * By default, it won't, but filters can override this.
  2083. */
  2084. if ( ! $maybe_notify ) {
  2085. return false;
  2086. }
  2087. // Only send notifications for approved comments.
  2088. if ( ! isset( $comment->comment_approved ) || '1' != $comment->comment_approved ) {
  2089. return false;
  2090. }
  2091. return wp_notify_postauthor( $comment_ID );
  2092. }
  2093. /**
  2094. * Sets the status of a comment.
  2095. *
  2096. * The {@see 'wp_set_comment_status'} action is called after the comment is handled.
  2097. * If the comment status is not in the list, then false is returned.
  2098. *
  2099. * @since 1.0.0
  2100. *
  2101. * @global wpdb $wpdb WordPress database abstraction object.
  2102. *
  2103. * @param int|WP_Comment $comment_id Comment ID or WP_Comment object.
  2104. * @param string $comment_status New comment status, either 'hold', 'approve', 'spam', or 'trash'.
  2105. * @param bool $wp_error Whether to return a WP_Error object if there is a failure. Default false.
  2106. * @return bool|WP_Error True on success, false or WP_Error on failure.
  2107. */
  2108. function wp_set_comment_status( $comment_id, $comment_status, $wp_error = false ) {
  2109. global $wpdb;
  2110. switch ( $comment_status ) {
  2111. case 'hold':
  2112. case '0':
  2113. $status = '0';
  2114. break;
  2115. case 'approve':
  2116. case '1':
  2117. $status = '1';
  2118. add_action( 'wp_set_comment_status', 'wp_new_comment_notify_postauthor' );
  2119. break;
  2120. case 'spam':
  2121. $status = 'spam';
  2122. break;
  2123. case 'trash':
  2124. $status = 'trash';
  2125. break;
  2126. default:
  2127. return false;
  2128. }
  2129. $comment_old = clone get_comment( $comment_id );
  2130. if ( ! $wpdb->update( $wpdb->comments, array( 'comment_approved' => $status ), array( 'comment_ID' => $comment_old->comment_ID ) ) ) {
  2131. if ( $wp_error ) {
  2132. return new WP_Error( 'db_update_error', __( 'Could not update comment status.' ), $wpdb->last_error );
  2133. } else {
  2134. return false;
  2135. }
  2136. }
  2137. clean_comment_cache( $comment_old->comment_ID );
  2138. $comment = get_comment( $comment_old->comment_ID );
  2139. /**
  2140. * Fires immediately after transitioning a comment's status from one to another in the database
  2141. * and removing the comment from the object cache, but prior to all status transition hooks.
  2142. *
  2143. * @since 1.5.0
  2144. *
  2145. * @param int $comment_id Comment ID.
  2146. * @param string $comment_status Current comment status. Possible values include
  2147. * 'hold', '0', 'approve', '1', 'spam', and 'trash'.
  2148. */
  2149. do_action( 'wp_set_comment_status', $comment->comment_ID, $comment_status );
  2150. wp_transition_comment_status( $comment_status, $comment_old->comment_approved, $comment );
  2151. wp_update_comment_count( $comment->comment_post_ID );
  2152. return true;
  2153. }
  2154. /**
  2155. * Updates an existing comment in the database.
  2156. *
  2157. * Filters the comment and makes sure certain fields are valid before updating.
  2158. *
  2159. * @since 2.0.0
  2160. * @since 4.9.0 Add updating comment meta during comment update.
  2161. * @since 5.5.0 The `$wp_error` parameter was added.
  2162. * @since 5.5.0 The return values for an invalid comment or post ID
  2163. * were changed to false instead of 0.
  2164. *
  2165. * @global wpdb $wpdb WordPress database abstraction object.
  2166. *
  2167. * @param array $commentarr Contains information on the comment.
  2168. * @param bool $wp_error Optional. Whether to return a WP_Error on failure. Default false.
  2169. * @return int|false|WP_Error The value 1 if the comment was updated, 0 if not updated.
  2170. * False or a WP_Error object on failure.
  2171. */
  2172. function wp_update_comment( $commentarr, $wp_error = false ) {
  2173. global $wpdb;
  2174. // First, get all of the original fields.
  2175. $comment = get_comment( $commentarr['comment_ID'], ARRAY_A );
  2176. if ( empty( $comment ) ) {
  2177. if ( $wp_error ) {
  2178. return new WP_Error( 'invalid_comment_id', __( 'Invalid comment ID.' ) );
  2179. } else {
  2180. return false;
  2181. }
  2182. }
  2183. // Make sure that the comment post ID is valid (if specified).
  2184. if ( ! empty( $commentarr['comment_post_ID'] ) && ! get_post( $commentarr['comment_post_ID'] ) ) {
  2185. if ( $wp_error ) {
  2186. return new WP_Error( 'invalid_post_id', __( 'Invalid post ID.' ) );
  2187. } else {
  2188. return false;
  2189. }
  2190. }
  2191. // Escape data pulled from DB.
  2192. $comment = wp_slash( $comment );
  2193. $old_status = $comment['comment_approved'];
  2194. // Merge old and new fields with new fields overwriting old ones.
  2195. $commentarr = array_merge( $comment, $commentarr );
  2196. $commentarr = wp_filter_comment( $commentarr );
  2197. // Now extract the merged array.
  2198. $data = wp_unslash( $commentarr );
  2199. /**
  2200. * Filters the comment content before it is updated in the database.
  2201. *
  2202. * @since 1.5.0
  2203. *
  2204. * @param string $comment_content The comment data.
  2205. */
  2206. $data['comment_content'] = apply_filters( 'comment_save_pre', $data['comment_content'] );
  2207. $data['comment_date_gmt'] = get_gmt_from_date( $data['comment_date'] );
  2208. if ( ! isset( $data['comment_approved'] ) ) {
  2209. $data['comment_approved'] = 1;
  2210. } elseif ( 'hold' === $data['comment_approved'] ) {
  2211. $data['comment_approved'] = 0;
  2212. } elseif ( 'approve' === $data['comment_approved'] ) {
  2213. $data['comment_approved'] = 1;
  2214. }
  2215. $comment_ID = $data['comment_ID'];
  2216. $comment_post_ID = $data['comment_post_ID'];
  2217. /**
  2218. * Filters the comment data immediately before it is updated in the database.
  2219. *
  2220. * Note: data being passed to the filter is already unslashed.
  2221. *
  2222. * @since 4.7.0
  2223. * @since 5.5.0 Returning a WP_Error value from the filter will short-circuit comment update
  2224. * and allow skipping further processing.
  2225. *
  2226. * @param array|WP_Error $data The new, processed comment data, or WP_Error.
  2227. * @param array $comment The old, unslashed comment data.
  2228. * @param array $commentarr The new, raw comment data.
  2229. */
  2230. $data = apply_filters( 'wp_update_comment_data', $data, $comment, $commentarr );
  2231. // Do not carry on on failure.
  2232. if ( is_wp_error( $data ) ) {
  2233. if ( $wp_error ) {
  2234. return $data;
  2235. } else {
  2236. return false;
  2237. }
  2238. }
  2239. $keys = array( 'comment_post_ID', 'comment_content', 'comment_author', 'comment_author_email', 'comment_approved', 'comment_karma', 'comment_author_url', 'comment_date', 'comment_date_gmt', 'comment_type', 'comment_parent', 'user_id', 'comment_agent', 'comment_author_IP' );
  2240. $data = wp_array_slice_assoc( $data, $keys );
  2241. $rval = $wpdb->update( $wpdb->comments, $data, compact( 'comment_ID' ) );
  2242. if ( false === $rval ) {
  2243. if ( $wp_error ) {
  2244. return new WP_Error( 'db_update_error', __( 'Could not update comment in the database.' ), $wpdb->last_error );
  2245. } else {
  2246. return false;
  2247. }
  2248. }
  2249. // If metadata is provided, store it.
  2250. if ( isset( $commentarr['comment_meta'] ) && is_array( $commentarr['comment_meta'] ) ) {
  2251. foreach ( $commentarr['comment_meta'] as $meta_key => $meta_value ) {
  2252. update_comment_meta( $comment_ID, $meta_key, $meta_value );
  2253. }
  2254. }
  2255. clean_comment_cache( $comment_ID );
  2256. wp_update_comment_count( $comment_post_ID );
  2257. /**
  2258. * Fires immediately after a comment is updated in the database.
  2259. *
  2260. * The hook also fires immediately before comment status transition hooks are fired.
  2261. *
  2262. * @since 1.2.0
  2263. * @since 4.6.0 Added the `$data` parameter.
  2264. *
  2265. * @param int $comment_ID The comment ID.
  2266. * @param array $data Comment data.
  2267. */
  2268. do_action( 'edit_comment', $comment_ID, $data );
  2269. $comment = get_comment( $comment_ID );
  2270. wp_transition_comment_status( $comment->comment_approved, $old_status, $comment );
  2271. return $rval;
  2272. }
  2273. /**
  2274. * Whether to defer comment counting.
  2275. *
  2276. * When setting $defer to true, all post comment counts will not be updated
  2277. * until $defer is set to false. When $defer is set to false, then all
  2278. * previously deferred updated post comment counts will then be automatically
  2279. * updated without having to call wp_update_comment_count() after.
  2280. *
  2281. * @since 2.5.0
  2282. *
  2283. * @param bool $defer
  2284. * @return bool
  2285. */
  2286. function wp_defer_comment_counting( $defer = null ) {
  2287. static $_defer = false;
  2288. if ( is_bool( $defer ) ) {
  2289. $_defer = $defer;
  2290. // Flush any deferred counts.
  2291. if ( ! $defer ) {
  2292. wp_update_comment_count( null, true );
  2293. }
  2294. }
  2295. return $_defer;
  2296. }
  2297. /**
  2298. * Updates the comment count for post(s).
  2299. *
  2300. * When $do_deferred is false (is by default) and the comments have been set to
  2301. * be deferred, the post_id will be added to a queue, which will be updated at a
  2302. * later date and only updated once per post ID.
  2303. *
  2304. * If the comments have not be set up to be deferred, then the post will be
  2305. * updated. When $do_deferred is set to true, then all previous deferred post
  2306. * IDs will be updated along with the current $post_id.
  2307. *
  2308. * @since 2.1.0
  2309. *
  2310. * @see wp_update_comment_count_now() For what could cause a false return value
  2311. *
  2312. * @param int|null $post_id Post ID.
  2313. * @param bool $do_deferred Optional. Whether to process previously deferred
  2314. * post comment counts. Default false.
  2315. * @return bool|void True on success, false on failure or if post with ID does
  2316. * not exist.
  2317. */
  2318. function wp_update_comment_count( $post_id, $do_deferred = false ) {
  2319. static $_deferred = array();
  2320. if ( empty( $post_id ) && ! $do_deferred ) {
  2321. return false;
  2322. }
  2323. if ( $do_deferred ) {
  2324. $_deferred = array_unique( $_deferred );
  2325. foreach ( $_deferred as $i => $_post_id ) {
  2326. wp_update_comment_count_now( $_post_id );
  2327. unset( $_deferred[ $i ] );
  2328. /** @todo Move this outside of the foreach and reset $_deferred to an array instead */
  2329. }
  2330. }
  2331. if ( wp_defer_comment_counting() ) {
  2332. $_deferred[] = $post_id;
  2333. return true;
  2334. } elseif ( $post_id ) {
  2335. return wp_update_comment_count_now( $post_id );
  2336. }
  2337. }
  2338. /**
  2339. * Updates the comment count for the post.
  2340. *
  2341. * @since 2.5.0
  2342. *
  2343. * @global wpdb $wpdb WordPress database abstraction object.
  2344. *
  2345. * @param int $post_id Post ID
  2346. * @return bool True on success, false if the post does not exist.
  2347. */
  2348. function wp_update_comment_count_now( $post_id ) {
  2349. global $wpdb;
  2350. $post_id = (int) $post_id;
  2351. if ( ! $post_id ) {
  2352. return false;
  2353. }
  2354. wp_cache_delete( 'comments-0', 'counts' );
  2355. wp_cache_delete( "comments-{$post_id}", 'counts' );
  2356. $post = get_post( $post_id );
  2357. if ( ! $post ) {
  2358. return false;
  2359. }
  2360. $old = (int) $post->comment_count;
  2361. /**
  2362. * Filters a post's comment count before it is updated in the database.
  2363. *
  2364. * @since 4.5.0
  2365. *
  2366. * @param int|null $new The new comment count. Default null.
  2367. * @param int $old The old comment count.
  2368. * @param int $post_id Post ID.
  2369. */
  2370. $new = apply_filters( 'pre_wp_update_comment_count_now', null, $old, $post_id );
  2371. if ( is_null( $new ) ) {
  2372. $new = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_approved = '1'", $post_id ) );
  2373. } else {
  2374. $new = (int) $new;
  2375. }
  2376. $wpdb->update( $wpdb->posts, array( 'comment_count' => $new ), array( 'ID' => $post_id ) );
  2377. clean_post_cache( $post );
  2378. /**
  2379. * Fires immediately after a post's comment count is updated in the database.
  2380. *
  2381. * @since 2.3.0
  2382. *
  2383. * @param int $post_id Post ID.
  2384. * @param int $new The new comment count.
  2385. * @param int $old The old comment count.
  2386. */
  2387. do_action( 'wp_update_comment_count', $post_id, $new, $old );
  2388. /** This action is documented in wp-includes/post.php */
  2389. do_action( "edit_post_{$post->post_type}", $post_id, $post );
  2390. /** This action is documented in wp-includes/post.php */
  2391. do_action( 'edit_post', $post_id, $post );
  2392. return true;
  2393. }
  2394. //
  2395. // Ping and trackback functions.
  2396. //
  2397. /**
  2398. * Finds a pingback server URI based on the given URL.
  2399. *
  2400. * Checks the HTML for the rel="pingback" link and x-pingback headers. It does
  2401. * a check for the x-pingback headers first and returns that, if available. The
  2402. * check for the rel="pingback" has more overhead than just the header.
  2403. *
  2404. * @since 1.5.0
  2405. *
  2406. * @param string $url URL to ping.
  2407. * @param string $deprecated Not Used.
  2408. * @return string|false String containing URI on success, false on failure.
  2409. */
  2410. function discover_pingback_server_uri( $url, $deprecated = '' ) {
  2411. if ( ! empty( $deprecated ) ) {
  2412. _deprecated_argument( __FUNCTION__, '2.7.0' );
  2413. }
  2414. $pingback_str_dquote = 'rel="pingback"';
  2415. $pingback_str_squote = 'rel=\'pingback\'';
  2416. /** @todo Should use Filter Extension or custom preg_match instead. */
  2417. $parsed_url = parse_url( $url );
  2418. if ( ! isset( $parsed_url['host'] ) ) { // Not a URL. This should never happen.
  2419. return false;
  2420. }
  2421. // Do not search for a pingback server on our own uploads.
  2422. $uploads_dir = wp_get_upload_dir();
  2423. if ( 0 === strpos( $url, $uploads_dir['baseurl'] ) ) {
  2424. return false;
  2425. }
  2426. $response = wp_safe_remote_head(
  2427. $url,
  2428. array(
  2429. 'timeout' => 2,
  2430. 'httpversion' => '1.0',
  2431. )
  2432. );
  2433. if ( is_wp_error( $response ) ) {
  2434. return false;
  2435. }
  2436. if ( wp_remote_retrieve_header( $response, 'x-pingback' ) ) {
  2437. return wp_remote_retrieve_header( $response, 'x-pingback' );
  2438. }
  2439. // Not an (x)html, sgml, or xml page, no use going further.
  2440. if ( preg_match( '#(image|audio|video|model)/#is', wp_remote_retrieve_header( $response, 'content-type' ) ) ) {
  2441. return false;
  2442. }
  2443. // Now do a GET since we're going to look in the HTML headers (and we're sure it's not a binary file).
  2444. $response = wp_safe_remote_get(
  2445. $url,
  2446. array(
  2447. 'timeout' => 2,
  2448. 'httpversion' => '1.0',
  2449. )
  2450. );
  2451. if ( is_wp_error( $response ) ) {
  2452. return false;
  2453. }
  2454. $contents = wp_remote_retrieve_body( $response );
  2455. $pingback_link_offset_dquote = strpos( $contents, $pingback_str_dquote );
  2456. $pingback_link_offset_squote = strpos( $contents, $pingback_str_squote );
  2457. if ( $pingback_link_offset_dquote || $pingback_link_offset_squote ) {
  2458. $quote = ( $pingback_link_offset_dquote ) ? '"' : '\'';
  2459. $pingback_link_offset = ( '"' === $quote ) ? $pingback_link_offset_dquote : $pingback_link_offset_squote;
  2460. $pingback_href_pos = strpos( $contents, 'href=', $pingback_link_offset );
  2461. $pingback_href_start = $pingback_href_pos + 6;
  2462. $pingback_href_end = strpos( $contents, $quote, $pingback_href_start );
  2463. $pingback_server_url_len = $pingback_href_end - $pingback_href_start;
  2464. $pingback_server_url = substr( $contents, $pingback_href_start, $pingback_server_url_len );
  2465. // We may find rel="pingback" but an incomplete pingback URL.
  2466. if ( $pingback_server_url_len > 0 ) { // We got it!
  2467. return $pingback_server_url;
  2468. }
  2469. }
  2470. return false;
  2471. }
  2472. /**
  2473. * Perform all pingbacks, enclosures, trackbacks, and send to pingback services.
  2474. *
  2475. * @since 2.1.0
  2476. * @since 5.6.0 Introduced `do_all_pings` action hook for individual services.
  2477. */
  2478. function do_all_pings() {
  2479. /**
  2480. * Fires immediately after the `do_pings` event to hook services individually.
  2481. *
  2482. * @since 5.6.0
  2483. */
  2484. do_action( 'do_all_pings' );
  2485. }
  2486. /**
  2487. * Perform all pingbacks.
  2488. *
  2489. * @since 5.6.0
  2490. */
  2491. function do_all_pingbacks() {
  2492. $pings = get_posts(
  2493. array(
  2494. 'post_type' => get_post_types(),
  2495. 'suppress_filters' => false,
  2496. 'nopaging' => true,
  2497. 'meta_key' => '_pingme',
  2498. 'fields' => 'ids',
  2499. )
  2500. );
  2501. foreach ( $pings as $ping ) {
  2502. delete_post_meta( $ping, '_pingme' );
  2503. pingback( null, $ping );
  2504. }
  2505. }
  2506. /**
  2507. * Perform all enclosures.
  2508. *
  2509. * @since 5.6.0
  2510. */
  2511. function do_all_enclosures() {
  2512. $enclosures = get_posts(
  2513. array(
  2514. 'post_type' => get_post_types(),
  2515. 'suppress_filters' => false,
  2516. 'nopaging' => true,
  2517. 'meta_key' => '_encloseme',
  2518. 'fields' => 'ids',
  2519. )
  2520. );
  2521. foreach ( $enclosures as $enclosure ) {
  2522. delete_post_meta( $enclosure, '_encloseme' );
  2523. do_enclose( null, $enclosure );
  2524. }
  2525. }
  2526. /**
  2527. * Perform all trackbacks.
  2528. *
  2529. * @since 5.6.0
  2530. */
  2531. function do_all_trackbacks() {
  2532. $trackbacks = get_posts(
  2533. array(
  2534. 'post_type' => get_post_types(),
  2535. 'suppress_filters' => false,
  2536. 'nopaging' => true,
  2537. 'meta_key' => '_trackbackme',
  2538. 'fields' => 'ids',
  2539. )
  2540. );
  2541. foreach ( $trackbacks as $trackback ) {
  2542. delete_post_meta( $trackback, '_trackbackme' );
  2543. do_trackbacks( $trackback );
  2544. }
  2545. }
  2546. /**
  2547. * Perform trackbacks.
  2548. *
  2549. * @since 1.5.0
  2550. * @since 4.7.0 `$post_id` can be a WP_Post object.
  2551. *
  2552. * @global wpdb $wpdb WordPress database abstraction object.
  2553. *
  2554. * @param int|WP_Post $post_id Post object or ID to do trackbacks on.
  2555. */
  2556. function do_trackbacks( $post_id ) {
  2557. global $wpdb;
  2558. $post = get_post( $post_id );
  2559. if ( ! $post ) {
  2560. return false;
  2561. }
  2562. $to_ping = get_to_ping( $post );
  2563. $pinged = get_pung( $post );
  2564. if ( empty( $to_ping ) ) {
  2565. $wpdb->update( $wpdb->posts, array( 'to_ping' => '' ), array( 'ID' => $post->ID ) );
  2566. return;
  2567. }
  2568. if ( empty( $post->post_excerpt ) ) {
  2569. /** This filter is documented in wp-includes/post-template.php */
  2570. $excerpt = apply_filters( 'the_content', $post->post_content, $post->ID );
  2571. } else {
  2572. /** This filter is documented in wp-includes/post-template.php */
  2573. $excerpt = apply_filters( 'the_excerpt', $post->post_excerpt );
  2574. }
  2575. $excerpt = str_replace( ']]>', ']]&gt;', $excerpt );
  2576. $excerpt = wp_html_excerpt( $excerpt, 252, '&#8230;' );
  2577. /** This filter is documented in wp-includes/post-template.php */
  2578. $post_title = apply_filters( 'the_title', $post->post_title, $post->ID );
  2579. $post_title = strip_tags( $post_title );
  2580. if ( $to_ping ) {
  2581. foreach ( (array) $to_ping as $tb_ping ) {
  2582. $tb_ping = trim( $tb_ping );
  2583. if ( ! in_array( $tb_ping, $pinged, true ) ) {
  2584. trackback( $tb_ping, $post_title, $excerpt, $post->ID );
  2585. $pinged[] = $tb_ping;
  2586. } else {
  2587. $wpdb->query(
  2588. $wpdb->prepare(
  2589. "UPDATE $wpdb->posts SET to_ping = TRIM(REPLACE(to_ping, %s,
  2590. '')) WHERE ID = %d",
  2591. $tb_ping,
  2592. $post->ID
  2593. )
  2594. );
  2595. }
  2596. }
  2597. }
  2598. }
  2599. /**
  2600. * Sends pings to all of the ping site services.
  2601. *
  2602. * @since 1.2.0
  2603. *
  2604. * @param int $post_id Post ID.
  2605. * @return int Same as Post ID from parameter
  2606. */
  2607. function generic_ping( $post_id = 0 ) {
  2608. $services = get_option( 'ping_sites' );
  2609. $services = explode( "\n", $services );
  2610. foreach ( (array) $services as $service ) {
  2611. $service = trim( $service );
  2612. if ( '' !== $service ) {
  2613. weblog_ping( $service );
  2614. }
  2615. }
  2616. return $post_id;
  2617. }
  2618. /**
  2619. * Pings back the links found in a post.
  2620. *
  2621. * @since 0.71
  2622. * @since 4.7.0 `$post_id` can be a WP_Post object.
  2623. *
  2624. * @param string $content Post content to check for links. If empty will retrieve from post.
  2625. * @param int|WP_Post $post_id Post Object or ID.
  2626. */
  2627. function pingback( $content, $post_id ) {
  2628. include_once ABSPATH . WPINC . '/class-IXR.php';
  2629. include_once ABSPATH . WPINC . '/class-wp-http-ixr-client.php';
  2630. // Original code by Mort (http://mort.mine.nu:8080).
  2631. $post_links = array();
  2632. $post = get_post( $post_id );
  2633. if ( ! $post ) {
  2634. return;
  2635. }
  2636. $pung = get_pung( $post );
  2637. if ( empty( $content ) ) {
  2638. $content = $post->post_content;
  2639. }
  2640. /*
  2641. * Step 1.
  2642. * Parsing the post, external links (if any) are stored in the $post_links array.
  2643. */
  2644. $post_links_temp = wp_extract_urls( $content );
  2645. /*
  2646. * Step 2.
  2647. * Walking through the links array.
  2648. * First we get rid of links pointing to sites, not to specific files.
  2649. * Example:
  2650. * http://dummy-weblog.org
  2651. * http://dummy-weblog.org/
  2652. * http://dummy-weblog.org/post.php
  2653. * We don't wanna ping first and second types, even if they have a valid <link/>.
  2654. */
  2655. foreach ( (array) $post_links_temp as $link_test ) {
  2656. // If we haven't pung it already and it isn't a link to itself.
  2657. if ( ! in_array( $link_test, $pung, true ) && ( url_to_postid( $link_test ) != $post->ID )
  2658. // Also, let's never ping local attachments.
  2659. && ! is_local_attachment( $link_test )
  2660. ) {
  2661. $test = parse_url( $link_test );
  2662. if ( $test ) {
  2663. if ( isset( $test['query'] ) ) {
  2664. $post_links[] = $link_test;
  2665. } elseif ( isset( $test['path'] ) && ( '/' !== $test['path'] ) && ( '' !== $test['path'] ) ) {
  2666. $post_links[] = $link_test;
  2667. }
  2668. }
  2669. }
  2670. }
  2671. $post_links = array_unique( $post_links );
  2672. /**
  2673. * Fires just before pinging back links found in a post.
  2674. *
  2675. * @since 2.0.0
  2676. *
  2677. * @param string[] $post_links Array of link URLs to be checked (passed by reference).
  2678. * @param string[] $pung Array of link URLs already pinged (passed by reference).
  2679. * @param int $post_ID The post ID.
  2680. */
  2681. do_action_ref_array( 'pre_ping', array( &$post_links, &$pung, $post->ID ) );
  2682. foreach ( (array) $post_links as $pagelinkedto ) {
  2683. $pingback_server_url = discover_pingback_server_uri( $pagelinkedto );
  2684. if ( $pingback_server_url ) {
  2685. set_time_limit( 60 );
  2686. // Now, the RPC call.
  2687. $pagelinkedfrom = get_permalink( $post );
  2688. // Using a timeout of 3 seconds should be enough to cover slow servers.
  2689. $client = new WP_HTTP_IXR_Client( $pingback_server_url );
  2690. $client->timeout = 3;
  2691. /**
  2692. * Filters the user agent sent when pinging-back a URL.
  2693. *
  2694. * @since 2.9.0
  2695. *
  2696. * @param string $concat_useragent The user agent concatenated with ' -- WordPress/'
  2697. * and the WordPress version.
  2698. * @param string $useragent The useragent.
  2699. * @param string $pingback_server_url The server URL being linked to.
  2700. * @param string $pagelinkedto URL of page linked to.
  2701. * @param string $pagelinkedfrom URL of page linked from.
  2702. */
  2703. $client->useragent = apply_filters( 'pingback_useragent', $client->useragent . ' -- WordPress/' . get_bloginfo( 'version' ), $client->useragent, $pingback_server_url, $pagelinkedto, $pagelinkedfrom );
  2704. // When set to true, this outputs debug messages by itself.
  2705. $client->debug = false;
  2706. if ( $client->query( 'pingback.ping', $pagelinkedfrom, $pagelinkedto ) || ( isset( $client->error->code ) && 48 == $client->error->code ) ) { // Already registered.
  2707. add_ping( $post, $pagelinkedto );
  2708. }
  2709. }
  2710. }
  2711. }
  2712. /**
  2713. * Check whether blog is public before returning sites.
  2714. *
  2715. * @since 2.1.0
  2716. *
  2717. * @param mixed $sites Will return if blog is public, will not return if not public.
  2718. * @return mixed Empty string if blog is not public, returns $sites, if site is public.
  2719. */
  2720. function privacy_ping_filter( $sites ) {
  2721. if ( '0' != get_option( 'blog_public' ) ) {
  2722. return $sites;
  2723. } else {
  2724. return '';
  2725. }
  2726. }
  2727. /**
  2728. * Send a Trackback.
  2729. *
  2730. * Updates database when sending trackback to prevent duplicates.
  2731. *
  2732. * @since 0.71
  2733. *
  2734. * @global wpdb $wpdb WordPress database abstraction object.
  2735. *
  2736. * @param string $trackback_url URL to send trackbacks.
  2737. * @param string $title Title of post.
  2738. * @param string $excerpt Excerpt of post.
  2739. * @param int $ID Post ID.
  2740. * @return int|false|void Database query from update.
  2741. */
  2742. function trackback( $trackback_url, $title, $excerpt, $ID ) {
  2743. global $wpdb;
  2744. if ( empty( $trackback_url ) ) {
  2745. return;
  2746. }
  2747. $options = array();
  2748. $options['timeout'] = 10;
  2749. $options['body'] = array(
  2750. 'title' => $title,
  2751. 'url' => get_permalink( $ID ),
  2752. 'blog_name' => get_option( 'blogname' ),
  2753. 'excerpt' => $excerpt,
  2754. );
  2755. $response = wp_safe_remote_post( $trackback_url, $options );
  2756. if ( is_wp_error( $response ) ) {
  2757. return;
  2758. }
  2759. $wpdb->query( $wpdb->prepare( "UPDATE $wpdb->posts SET pinged = CONCAT(pinged, '\n', %s) WHERE ID = %d", $trackback_url, $ID ) );
  2760. return $wpdb->query( $wpdb->prepare( "UPDATE $wpdb->posts SET to_ping = TRIM(REPLACE(to_ping, %s, '')) WHERE ID = %d", $trackback_url, $ID ) );
  2761. }
  2762. /**
  2763. * Send a pingback.
  2764. *
  2765. * @since 1.2.0
  2766. *
  2767. * @param string $server Host of blog to connect to.
  2768. * @param string $path Path to send the ping.
  2769. */
  2770. function weblog_ping( $server = '', $path = '' ) {
  2771. include_once ABSPATH . WPINC . '/class-IXR.php';
  2772. include_once ABSPATH . WPINC . '/class-wp-http-ixr-client.php';
  2773. // Using a timeout of 3 seconds should be enough to cover slow servers.
  2774. $client = new WP_HTTP_IXR_Client( $server, ( ( ! strlen( trim( $path ) ) || ( '/' === $path ) ) ? false : $path ) );
  2775. $client->timeout = 3;
  2776. $client->useragent .= ' -- WordPress/' . get_bloginfo( 'version' );
  2777. // When set to true, this outputs debug messages by itself.
  2778. $client->debug = false;
  2779. $home = trailingslashit( home_url() );
  2780. if ( ! $client->query( 'weblogUpdates.extendedPing', get_option( 'blogname' ), $home, get_bloginfo( 'rss2_url' ) ) ) { // Then try a normal ping.
  2781. $client->query( 'weblogUpdates.ping', get_option( 'blogname' ), $home );
  2782. }
  2783. }
  2784. /**
  2785. * Default filter attached to pingback_ping_source_uri to validate the pingback's Source URI
  2786. *
  2787. * @since 3.5.1
  2788. *
  2789. * @see wp_http_validate_url()
  2790. *
  2791. * @param string $source_uri
  2792. * @return string
  2793. */
  2794. function pingback_ping_source_uri( $source_uri ) {
  2795. return (string) wp_http_validate_url( $source_uri );
  2796. }
  2797. /**
  2798. * Default filter attached to xmlrpc_pingback_error.
  2799. *
  2800. * Returns a generic pingback error code unless the error code is 48,
  2801. * which reports that the pingback is already registered.
  2802. *
  2803. * @since 3.5.1
  2804. *
  2805. * @link https://www.hixie.ch/specs/pingback/pingback#TOC3
  2806. *
  2807. * @param IXR_Error $ixr_error
  2808. * @return IXR_Error
  2809. */
  2810. function xmlrpc_pingback_error( $ixr_error ) {
  2811. if ( 48 === $ixr_error->code ) {
  2812. return $ixr_error;
  2813. }
  2814. return new IXR_Error( 0, '' );
  2815. }
  2816. //
  2817. // Cache.
  2818. //
  2819. /**
  2820. * Removes a comment from the object cache.
  2821. *
  2822. * @since 2.3.0
  2823. *
  2824. * @param int|array $ids Comment ID or an array of comment IDs to remove from cache.
  2825. */
  2826. function clean_comment_cache( $ids ) {
  2827. foreach ( (array) $ids as $id ) {
  2828. wp_cache_delete( $id, 'comment' );
  2829. /**
  2830. * Fires immediately after a comment has been removed from the object cache.
  2831. *
  2832. * @since 4.5.0
  2833. *
  2834. * @param int $id Comment ID.
  2835. */
  2836. do_action( 'clean_comment_cache', $id );
  2837. }
  2838. wp_cache_set( 'last_changed', microtime(), 'comment' );
  2839. }
  2840. /**
  2841. * Updates the comment cache of given comments.
  2842. *
  2843. * Will add the comments in $comments to the cache. If comment ID already exists
  2844. * in the comment cache then it will not be updated. The comment is added to the
  2845. * cache using the comment group with the key using the ID of the comments.
  2846. *
  2847. * @since 2.3.0
  2848. * @since 4.4.0 Introduced the `$update_meta_cache` parameter.
  2849. *
  2850. * @param WP_Comment[] $comments Array of comment objects
  2851. * @param bool $update_meta_cache Whether to update commentmeta cache. Default true.
  2852. */
  2853. function update_comment_cache( $comments, $update_meta_cache = true ) {
  2854. foreach ( (array) $comments as $comment ) {
  2855. wp_cache_add( $comment->comment_ID, $comment, 'comment' );
  2856. }
  2857. if ( $update_meta_cache ) {
  2858. // Avoid `wp_list_pluck()` in case `$comments` is passed by reference.
  2859. $comment_ids = array();
  2860. foreach ( $comments as $comment ) {
  2861. $comment_ids[] = $comment->comment_ID;
  2862. }
  2863. update_meta_cache( 'comment', $comment_ids );
  2864. }
  2865. }
  2866. /**
  2867. * Adds any comments from the given IDs to the cache that do not already exist in cache.
  2868. *
  2869. * @since 4.4.0
  2870. * @access private
  2871. *
  2872. * @see update_comment_cache()
  2873. * @global wpdb $wpdb WordPress database abstraction object.
  2874. *
  2875. * @param int[] $comment_ids Array of comment IDs.
  2876. * @param bool $update_meta_cache Optional. Whether to update the meta cache. Default true.
  2877. */
  2878. function _prime_comment_caches( $comment_ids, $update_meta_cache = true ) {
  2879. global $wpdb;
  2880. $non_cached_ids = _get_non_cached_ids( $comment_ids, 'comment' );
  2881. if ( ! empty( $non_cached_ids ) ) {
  2882. $fresh_comments = $wpdb->get_results( sprintf( "SELECT $wpdb->comments.* FROM $wpdb->comments WHERE comment_ID IN (%s)", implode( ',', array_map( 'intval', $non_cached_ids ) ) ) );
  2883. update_comment_cache( $fresh_comments, $update_meta_cache );
  2884. }
  2885. }
  2886. //
  2887. // Internal.
  2888. //
  2889. /**
  2890. * Close comments on old posts on the fly, without any extra DB queries. Hooked to the_posts.
  2891. *
  2892. * @since 2.7.0
  2893. * @access private
  2894. *
  2895. * @param WP_Post $posts Post data object.
  2896. * @param WP_Query $query Query object.
  2897. * @return array
  2898. */
  2899. function _close_comments_for_old_posts( $posts, $query ) {
  2900. if ( empty( $posts ) || ! $query->is_singular() || ! get_option( 'close_comments_for_old_posts' ) ) {
  2901. return $posts;
  2902. }
  2903. /**
  2904. * Filters the list of post types to automatically close comments for.
  2905. *
  2906. * @since 3.2.0
  2907. *
  2908. * @param string[] $post_types An array of post type names.
  2909. */
  2910. $post_types = apply_filters( 'close_comments_for_post_types', array( 'post' ) );
  2911. if ( ! in_array( $posts[0]->post_type, $post_types, true ) ) {
  2912. return $posts;
  2913. }
  2914. $days_old = (int) get_option( 'close_comments_days_old' );
  2915. if ( ! $days_old ) {
  2916. return $posts;
  2917. }
  2918. if ( time() - strtotime( $posts[0]->post_date_gmt ) > ( $days_old * DAY_IN_SECONDS ) ) {
  2919. $posts[0]->comment_status = 'closed';
  2920. $posts[0]->ping_status = 'closed';
  2921. }
  2922. return $posts;
  2923. }
  2924. /**
  2925. * Close comments on an old post. Hooked to comments_open and pings_open.
  2926. *
  2927. * @since 2.7.0
  2928. * @access private
  2929. *
  2930. * @param bool $open Comments open or closed.
  2931. * @param int $post_id Post ID.
  2932. * @return bool $open
  2933. */
  2934. function _close_comments_for_old_post( $open, $post_id ) {
  2935. if ( ! $open ) {
  2936. return $open;
  2937. }
  2938. if ( ! get_option( 'close_comments_for_old_posts' ) ) {
  2939. return $open;
  2940. }
  2941. $days_old = (int) get_option( 'close_comments_days_old' );
  2942. if ( ! $days_old ) {
  2943. return $open;
  2944. }
  2945. $post = get_post( $post_id );
  2946. /** This filter is documented in wp-includes/comment.php */
  2947. $post_types = apply_filters( 'close_comments_for_post_types', array( 'post' ) );
  2948. if ( ! in_array( $post->post_type, $post_types, true ) ) {
  2949. return $open;
  2950. }
  2951. // Undated drafts should not show up as comments closed.
  2952. if ( '0000-00-00 00:00:00' === $post->post_date_gmt ) {
  2953. return $open;
  2954. }
  2955. if ( time() - strtotime( $post->post_date_gmt ) > ( $days_old * DAY_IN_SECONDS ) ) {
  2956. return false;
  2957. }
  2958. return $open;
  2959. }
  2960. /**
  2961. * Handles the submission of a comment, usually posted to wp-comments-post.php via a comment form.
  2962. *
  2963. * This function expects unslashed data, as opposed to functions such as `wp_new_comment()` which
  2964. * expect slashed data.
  2965. *
  2966. * @since 4.4.0
  2967. *
  2968. * @param array $comment_data {
  2969. * Comment data.
  2970. *
  2971. * @type string|int $comment_post_ID The ID of the post that relates to the comment.
  2972. * @type string $author The name of the comment author.
  2973. * @type string $email The comment author email address.
  2974. * @type string $url The comment author URL.
  2975. * @type string $comment The content of the comment.
  2976. * @type string|int $comment_parent The ID of this comment's parent, if any. Default 0.
  2977. * @type string $_wp_unfiltered_html_comment The nonce value for allowing unfiltered HTML.
  2978. * }
  2979. * @return WP_Comment|WP_Error A WP_Comment object on success, a WP_Error object on failure.
  2980. */
  2981. function wp_handle_comment_submission( $comment_data ) {
  2982. $comment_post_ID = 0;
  2983. $comment_parent = 0;
  2984. $user_ID = 0;
  2985. $comment_author = null;
  2986. $comment_author_email = null;
  2987. $comment_author_url = null;
  2988. $comment_content = null;
  2989. if ( isset( $comment_data['comment_post_ID'] ) ) {
  2990. $comment_post_ID = (int) $comment_data['comment_post_ID'];
  2991. }
  2992. if ( isset( $comment_data['author'] ) && is_string( $comment_data['author'] ) ) {
  2993. $comment_author = trim( strip_tags( $comment_data['author'] ) );
  2994. }
  2995. if ( isset( $comment_data['email'] ) && is_string( $comment_data['email'] ) ) {
  2996. $comment_author_email = trim( $comment_data['email'] );
  2997. }
  2998. if ( isset( $comment_data['url'] ) && is_string( $comment_data['url'] ) ) {
  2999. $comment_author_url = trim( $comment_data['url'] );
  3000. }
  3001. if ( isset( $comment_data['comment'] ) && is_string( $comment_data['comment'] ) ) {
  3002. $comment_content = trim( $comment_data['comment'] );
  3003. }
  3004. if ( isset( $comment_data['comment_parent'] ) ) {
  3005. $comment_parent = absint( $comment_data['comment_parent'] );
  3006. }
  3007. $post = get_post( $comment_post_ID );
  3008. if ( empty( $post->comment_status ) ) {
  3009. /**
  3010. * Fires when a comment is attempted on a post that does not exist.
  3011. *
  3012. * @since 1.5.0
  3013. *
  3014. * @param int $comment_post_ID Post ID.
  3015. */
  3016. do_action( 'comment_id_not_found', $comment_post_ID );
  3017. return new WP_Error( 'comment_id_not_found' );
  3018. }
  3019. // get_post_status() will get the parent status for attachments.
  3020. $status = get_post_status( $post );
  3021. if ( ( 'private' === $status ) && ! current_user_can( 'read_post', $comment_post_ID ) ) {
  3022. return new WP_Error( 'comment_id_not_found' );
  3023. }
  3024. $status_obj = get_post_status_object( $status );
  3025. if ( ! comments_open( $comment_post_ID ) ) {
  3026. /**
  3027. * Fires when a comment is attempted on a post that has comments closed.
  3028. *
  3029. * @since 1.5.0
  3030. *
  3031. * @param int $comment_post_ID Post ID.
  3032. */
  3033. do_action( 'comment_closed', $comment_post_ID );
  3034. return new WP_Error( 'comment_closed', __( 'Sorry, comments are closed for this item.' ), 403 );
  3035. } elseif ( 'trash' === $status ) {
  3036. /**
  3037. * Fires when a comment is attempted on a trashed post.
  3038. *
  3039. * @since 2.9.0
  3040. *
  3041. * @param int $comment_post_ID Post ID.
  3042. */
  3043. do_action( 'comment_on_trash', $comment_post_ID );
  3044. return new WP_Error( 'comment_on_trash' );
  3045. } elseif ( ! $status_obj->public && ! $status_obj->private ) {
  3046. /**
  3047. * Fires when a comment is attempted on a post in draft mode.
  3048. *
  3049. * @since 1.5.1
  3050. *
  3051. * @param int $comment_post_ID Post ID.
  3052. */
  3053. do_action( 'comment_on_draft', $comment_post_ID );
  3054. if ( current_user_can( 'read_post', $comment_post_ID ) ) {
  3055. return new WP_Error( 'comment_on_draft', __( 'Sorry, comments are not allowed for this item.' ), 403 );
  3056. } else {
  3057. return new WP_Error( 'comment_on_draft' );
  3058. }
  3059. } elseif ( post_password_required( $comment_post_ID ) ) {
  3060. /**
  3061. * Fires when a comment is attempted on a password-protected post.
  3062. *
  3063. * @since 2.9.0
  3064. *
  3065. * @param int $comment_post_ID Post ID.
  3066. */
  3067. do_action( 'comment_on_password_protected', $comment_post_ID );
  3068. return new WP_Error( 'comment_on_password_protected' );
  3069. } else {
  3070. /**
  3071. * Fires before a comment is posted.
  3072. *
  3073. * @since 2.8.0
  3074. *
  3075. * @param int $comment_post_ID Post ID.
  3076. */
  3077. do_action( 'pre_comment_on_post', $comment_post_ID );
  3078. }
  3079. // If the user is logged in.
  3080. $user = wp_get_current_user();
  3081. if ( $user->exists() ) {
  3082. if ( empty( $user->display_name ) ) {
  3083. $user->display_name = $user->user_login;
  3084. }
  3085. $comment_author = $user->display_name;
  3086. $comment_author_email = $user->user_email;
  3087. $comment_author_url = $user->user_url;
  3088. $user_ID = $user->ID;
  3089. if ( current_user_can( 'unfiltered_html' ) ) {
  3090. if ( ! isset( $comment_data['_wp_unfiltered_html_comment'] )
  3091. || ! wp_verify_nonce( $comment_data['_wp_unfiltered_html_comment'], 'unfiltered-html-comment_' . $comment_post_ID )
  3092. ) {
  3093. kses_remove_filters(); // Start with a clean slate.
  3094. kses_init_filters(); // Set up the filters.
  3095. remove_filter( 'pre_comment_content', 'wp_filter_post_kses' );
  3096. add_filter( 'pre_comment_content', 'wp_filter_kses' );
  3097. }
  3098. }
  3099. } else {
  3100. if ( get_option( 'comment_registration' ) ) {
  3101. return new WP_Error( 'not_logged_in', __( 'Sorry, you must be logged in to comment.' ), 403 );
  3102. }
  3103. }
  3104. $comment_type = 'comment';
  3105. if ( get_option( 'require_name_email' ) && ! $user->exists() ) {
  3106. if ( '' == $comment_author_email || '' == $comment_author ) {
  3107. return new WP_Error( 'require_name_email', __( '<strong>Error</strong>: Please fill the required fields (name, email).' ), 200 );
  3108. } elseif ( ! is_email( $comment_author_email ) ) {
  3109. return new WP_Error( 'require_valid_email', __( '<strong>Error</strong>: Please enter a valid email address.' ), 200 );
  3110. }
  3111. }
  3112. $commentdata = compact(
  3113. 'comment_post_ID',
  3114. 'comment_author',
  3115. 'comment_author_email',
  3116. 'comment_author_url',
  3117. 'comment_content',
  3118. 'comment_type',
  3119. 'comment_parent',
  3120. 'user_ID'
  3121. );
  3122. /**
  3123. * Filters whether an empty comment should be allowed.
  3124. *
  3125. * @since 5.1.0
  3126. *
  3127. * @param bool $allow_empty_comment Whether to allow empty comments. Default false.
  3128. * @param array $commentdata Array of comment data to be sent to wp_insert_comment().
  3129. */
  3130. $allow_empty_comment = apply_filters( 'allow_empty_comment', false, $commentdata );
  3131. if ( '' === $comment_content && ! $allow_empty_comment ) {
  3132. return new WP_Error( 'require_valid_comment', __( '<strong>Error</strong>: Please type your comment text.' ), 200 );
  3133. }
  3134. $check_max_lengths = wp_check_comment_data_max_lengths( $commentdata );
  3135. if ( is_wp_error( $check_max_lengths ) ) {
  3136. return $check_max_lengths;
  3137. }
  3138. $comment_id = wp_new_comment( wp_slash( $commentdata ), true );
  3139. if ( is_wp_error( $comment_id ) ) {
  3140. return $comment_id;
  3141. }
  3142. if ( ! $comment_id ) {
  3143. return new WP_Error( 'comment_save_error', __( '<strong>Error</strong>: The comment could not be saved. Please try again later.' ), 500 );
  3144. }
  3145. return get_comment( $comment_id );
  3146. }
  3147. /**
  3148. * Registers the personal data exporter for comments.
  3149. *
  3150. * @since 4.9.6
  3151. *
  3152. * @param array $exporters An array of personal data exporters.
  3153. * @return array An array of personal data exporters.
  3154. */
  3155. function wp_register_comment_personal_data_exporter( $exporters ) {
  3156. $exporters['wordpress-comments'] = array(
  3157. 'exporter_friendly_name' => __( 'WordPress Comments' ),
  3158. 'callback' => 'wp_comments_personal_data_exporter',
  3159. );
  3160. return $exporters;
  3161. }
  3162. /**
  3163. * Finds and exports personal data associated with an email address from the comments table.
  3164. *
  3165. * @since 4.9.6
  3166. *
  3167. * @param string $email_address The comment author email address.
  3168. * @param int $page Comment page.
  3169. * @return array An array of personal data.
  3170. */
  3171. function wp_comments_personal_data_exporter( $email_address, $page = 1 ) {
  3172. // Limit us to 500 comments at a time to avoid timing out.
  3173. $number = 500;
  3174. $page = (int) $page;
  3175. $data_to_export = array();
  3176. $comments = get_comments(
  3177. array(
  3178. 'author_email' => $email_address,
  3179. 'number' => $number,
  3180. 'paged' => $page,
  3181. 'order_by' => 'comment_ID',
  3182. 'order' => 'ASC',
  3183. 'update_comment_meta_cache' => false,
  3184. )
  3185. );
  3186. $comment_prop_to_export = array(
  3187. 'comment_author' => __( 'Comment Author' ),
  3188. 'comment_author_email' => __( 'Comment Author Email' ),
  3189. 'comment_author_url' => __( 'Comment Author URL' ),
  3190. 'comment_author_IP' => __( 'Comment Author IP' ),
  3191. 'comment_agent' => __( 'Comment Author User Agent' ),
  3192. 'comment_date' => __( 'Comment Date' ),
  3193. 'comment_content' => __( 'Comment Content' ),
  3194. 'comment_link' => __( 'Comment URL' ),
  3195. );
  3196. foreach ( (array) $comments as $comment ) {
  3197. $comment_data_to_export = array();
  3198. foreach ( $comment_prop_to_export as $key => $name ) {
  3199. $value = '';
  3200. switch ( $key ) {
  3201. case 'comment_author':
  3202. case 'comment_author_email':
  3203. case 'comment_author_url':
  3204. case 'comment_author_IP':
  3205. case 'comment_agent':
  3206. case 'comment_date':
  3207. $value = $comment->{$key};
  3208. break;
  3209. case 'comment_content':
  3210. $value = get_comment_text( $comment->comment_ID );
  3211. break;
  3212. case 'comment_link':
  3213. $value = get_comment_link( $comment->comment_ID );
  3214. $value = sprintf(
  3215. '<a href="%s" target="_blank" rel="noopener">%s</a>',
  3216. esc_url( $value ),
  3217. esc_html( $value )
  3218. );
  3219. break;
  3220. }
  3221. if ( ! empty( $value ) ) {
  3222. $comment_data_to_export[] = array(
  3223. 'name' => $name,
  3224. 'value' => $value,
  3225. );
  3226. }
  3227. }
  3228. $data_to_export[] = array(
  3229. 'group_id' => 'comments',
  3230. 'group_label' => __( 'Comments' ),
  3231. 'group_description' => __( 'User&#8217;s comment data.' ),
  3232. 'item_id' => "comment-{$comment->comment_ID}",
  3233. 'data' => $comment_data_to_export,
  3234. );
  3235. }
  3236. $done = count( $comments ) < $number;
  3237. return array(
  3238. 'data' => $data_to_export,
  3239. 'done' => $done,
  3240. );
  3241. }
  3242. /**
  3243. * Registers the personal data eraser for comments.
  3244. *
  3245. * @since 4.9.6
  3246. *
  3247. * @param array $erasers An array of personal data erasers.
  3248. * @return array An array of personal data erasers.
  3249. */
  3250. function wp_register_comment_personal_data_eraser( $erasers ) {
  3251. $erasers['wordpress-comments'] = array(
  3252. 'eraser_friendly_name' => __( 'WordPress Comments' ),
  3253. 'callback' => 'wp_comments_personal_data_eraser',
  3254. );
  3255. return $erasers;
  3256. }
  3257. /**
  3258. * Erases personal data associated with an email address from the comments table.
  3259. *
  3260. * @since 4.9.6
  3261. *
  3262. * @param string $email_address The comment author email address.
  3263. * @param int $page Comment page.
  3264. * @return array
  3265. */
  3266. function wp_comments_personal_data_eraser( $email_address, $page = 1 ) {
  3267. global $wpdb;
  3268. if ( empty( $email_address ) ) {
  3269. return array(
  3270. 'items_removed' => false,
  3271. 'items_retained' => false,
  3272. 'messages' => array(),
  3273. 'done' => true,
  3274. );
  3275. }
  3276. // Limit us to 500 comments at a time to avoid timing out.
  3277. $number = 500;
  3278. $page = (int) $page;
  3279. $items_removed = false;
  3280. $items_retained = false;
  3281. $comments = get_comments(
  3282. array(
  3283. 'author_email' => $email_address,
  3284. 'number' => $number,
  3285. 'paged' => $page,
  3286. 'order_by' => 'comment_ID',
  3287. 'order' => 'ASC',
  3288. 'include_unapproved' => true,
  3289. )
  3290. );
  3291. /* translators: Name of a comment's author after being anonymized. */
  3292. $anon_author = __( 'Anonymous' );
  3293. $messages = array();
  3294. foreach ( (array) $comments as $comment ) {
  3295. $anonymized_comment = array();
  3296. $anonymized_comment['comment_agent'] = '';
  3297. $anonymized_comment['comment_author'] = $anon_author;
  3298. $anonymized_comment['comment_author_email'] = '';
  3299. $anonymized_comment['comment_author_IP'] = wp_privacy_anonymize_data( 'ip', $comment->comment_author_IP );
  3300. $anonymized_comment['comment_author_url'] = '';
  3301. $anonymized_comment['user_id'] = 0;
  3302. $comment_id = (int) $comment->comment_ID;
  3303. /**
  3304. * Filters whether to anonymize the comment.
  3305. *
  3306. * @since 4.9.6
  3307. *
  3308. * @param bool|string $anon_message Whether to apply the comment anonymization (bool) or a custom
  3309. * message (string). Default true.
  3310. * @param WP_Comment $comment WP_Comment object.
  3311. * @param array $anonymized_comment Anonymized comment data.
  3312. */
  3313. $anon_message = apply_filters( 'wp_anonymize_comment', true, $comment, $anonymized_comment );
  3314. if ( true !== $anon_message ) {
  3315. if ( $anon_message && is_string( $anon_message ) ) {
  3316. $messages[] = esc_html( $anon_message );
  3317. } else {
  3318. /* translators: %d: Comment ID. */
  3319. $messages[] = sprintf( __( 'Comment %d contains personal data but could not be anonymized.' ), $comment_id );
  3320. }
  3321. $items_retained = true;
  3322. continue;
  3323. }
  3324. $args = array(
  3325. 'comment_ID' => $comment_id,
  3326. );
  3327. $updated = $wpdb->update( $wpdb->comments, $anonymized_comment, $args );
  3328. if ( $updated ) {
  3329. $items_removed = true;
  3330. clean_comment_cache( $comment_id );
  3331. } else {
  3332. $items_retained = true;
  3333. }
  3334. }
  3335. $done = count( $comments ) < $number;
  3336. return array(
  3337. 'items_removed' => $items_removed,
  3338. 'items_retained' => $items_retained,
  3339. 'messages' => $messages,
  3340. 'done' => $done,
  3341. );
  3342. }
  3343. /**
  3344. * Sets the last changed time for the 'comment' cache group.
  3345. *
  3346. * @since 5.0.0
  3347. */
  3348. function wp_cache_set_comments_last_changed() {
  3349. wp_cache_set( 'last_changed', microtime(), 'comment' );
  3350. }
  3351. /**
  3352. * Updates the comment type for a batch of comments.
  3353. *
  3354. * @since 5.5.0
  3355. *
  3356. * @global wpdb $wpdb WordPress database abstraction object.
  3357. */
  3358. function _wp_batch_update_comment_type() {
  3359. global $wpdb;
  3360. $lock_name = 'update_comment_type.lock';
  3361. // Try to lock.
  3362. $lock_result = $wpdb->query( $wpdb->prepare( "INSERT IGNORE INTO `$wpdb->options` ( `option_name`, `option_value`, `autoload` ) VALUES (%s, %s, 'no') /* LOCK */", $lock_name, time() ) );
  3363. if ( ! $lock_result ) {
  3364. $lock_result = get_option( $lock_name );
  3365. // Bail if we were unable to create a lock, or if the existing lock is still valid.
  3366. if ( ! $lock_result || ( $lock_result > ( time() - HOUR_IN_SECONDS ) ) ) {
  3367. wp_schedule_single_event( time() + ( 5 * MINUTE_IN_SECONDS ), 'wp_update_comment_type_batch' );
  3368. return;
  3369. }
  3370. }
  3371. // Update the lock, as by this point we've definitely got a lock, just need to fire the actions.
  3372. update_option( $lock_name, time() );
  3373. // Check if there's still an empty comment type.
  3374. $empty_comment_type = $wpdb->get_var(
  3375. "SELECT comment_ID FROM $wpdb->comments
  3376. WHERE comment_type = ''
  3377. LIMIT 1"
  3378. );
  3379. // No empty comment type, we're done here.
  3380. if ( ! $empty_comment_type ) {
  3381. update_option( 'finished_updating_comment_type', true );
  3382. delete_option( $lock_name );
  3383. return;
  3384. }
  3385. // Empty comment type found? We'll need to run this script again.
  3386. wp_schedule_single_event( time() + ( 2 * MINUTE_IN_SECONDS ), 'wp_update_comment_type_batch' );
  3387. /**
  3388. * Filters the comment batch size for updating the comment type.
  3389. *
  3390. * @since 5.5.0
  3391. *
  3392. * @param int $comment_batch_size The comment batch size. Default 100.
  3393. */
  3394. $comment_batch_size = (int) apply_filters( 'wp_update_comment_type_batch_size', 100 );
  3395. // Get the IDs of the comments to update.
  3396. $comment_ids = $wpdb->get_col(
  3397. $wpdb->prepare(
  3398. "SELECT comment_ID
  3399. FROM {$wpdb->comments}
  3400. WHERE comment_type = ''
  3401. ORDER BY comment_ID DESC
  3402. LIMIT %d",
  3403. $comment_batch_size
  3404. )
  3405. );
  3406. if ( $comment_ids ) {
  3407. $comment_id_list = implode( ',', $comment_ids );
  3408. // Update the `comment_type` field value to be `comment` for the next batch of comments.
  3409. $wpdb->query(
  3410. "UPDATE {$wpdb->comments}
  3411. SET comment_type = 'comment'
  3412. WHERE comment_type = ''
  3413. AND comment_ID IN ({$comment_id_list})" // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
  3414. );
  3415. // Make sure to clean the comment cache.
  3416. clean_comment_cache( $comment_ids );
  3417. }
  3418. delete_option( $lock_name );
  3419. }
  3420. /**
  3421. * In order to avoid the _wp_batch_update_comment_type() job being accidentally removed,
  3422. * check that it's still scheduled while we haven't finished updating comment types.
  3423. *
  3424. * @ignore
  3425. * @since 5.5.0
  3426. */
  3427. function _wp_check_for_scheduled_update_comment_type() {
  3428. if ( ! get_option( 'finished_updating_comment_type' ) && ! wp_next_scheduled( 'wp_update_comment_type_batch' ) ) {
  3429. wp_schedule_single_event( time() + MINUTE_IN_SECONDS, 'wp_update_comment_type_batch' );
  3430. }
  3431. }