comment.php 124 KB

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