comment.php 109 KB

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