comment.php 109 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389
  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. }
  2743. }
  2744. } else {
  2745. if ( get_option( 'comment_registration' ) ) {
  2746. return new WP_Error( 'not_logged_in', __( 'Sorry, you must be logged in to comment.' ), 403 );
  2747. }
  2748. }
  2749. $comment_type = '';
  2750. if ( get_option( 'require_name_email' ) && ! $user->exists() ) {
  2751. if ( '' == $comment_author_email || '' == $comment_author ) {
  2752. return new WP_Error( 'require_name_email', __( '<strong>ERROR</strong>: please fill the required fields (name, email).' ), 200 );
  2753. } elseif ( ! is_email( $comment_author_email ) ) {
  2754. return new WP_Error( 'require_valid_email', __( '<strong>ERROR</strong>: please enter a valid email address.' ), 200 );
  2755. }
  2756. }
  2757. if ( '' == $comment_content ) {
  2758. return new WP_Error( 'require_valid_comment', __( '<strong>ERROR</strong>: please type a comment.' ), 200 );
  2759. }
  2760. $commentdata = compact(
  2761. 'comment_post_ID',
  2762. 'comment_author',
  2763. 'comment_author_email',
  2764. 'comment_author_url',
  2765. 'comment_content',
  2766. 'comment_type',
  2767. 'comment_parent',
  2768. 'user_ID'
  2769. );
  2770. $check_max_lengths = wp_check_comment_data_max_lengths( $commentdata );
  2771. if ( is_wp_error( $check_max_lengths ) ) {
  2772. return $check_max_lengths;
  2773. }
  2774. $comment_id = wp_new_comment( wp_slash( $commentdata ), true );
  2775. if ( is_wp_error( $comment_id ) ) {
  2776. return $comment_id;
  2777. }
  2778. if ( ! $comment_id ) {
  2779. return new WP_Error( 'comment_save_error', __( '<strong>ERROR</strong>: The comment could not be saved. Please try again later.' ), 500 );
  2780. }
  2781. return get_comment( $comment_id );
  2782. }
  2783. /**
  2784. * Registers the personal data exporter for comments.
  2785. *
  2786. * @since 4.9.6
  2787. *
  2788. * @param array $exporters An array of personal data exporters.
  2789. * @return array $exporters An array of personal data exporters.
  2790. */
  2791. function wp_register_comment_personal_data_exporter( $exporters ) {
  2792. $exporters['wordpress-comments'] = array(
  2793. 'exporter_friendly_name' => __( 'WordPress Comments' ),
  2794. 'callback' => 'wp_comments_personal_data_exporter',
  2795. );
  2796. return $exporters;
  2797. }
  2798. /**
  2799. * Finds and exports personal data associated with an email address from the comments table.
  2800. *
  2801. * @since 4.9.6
  2802. *
  2803. * @param string $email_address The comment author email address.
  2804. * @param int $page Comment page.
  2805. * @return array $return An array of personal data.
  2806. */
  2807. function wp_comments_personal_data_exporter( $email_address, $page = 1 ) {
  2808. // Limit us to 500 comments at a time to avoid timing out.
  2809. $number = 500;
  2810. $page = (int) $page;
  2811. $data_to_export = array();
  2812. $comments = get_comments(
  2813. array(
  2814. 'author_email' => $email_address,
  2815. 'number' => $number,
  2816. 'paged' => $page,
  2817. 'order_by' => 'comment_ID',
  2818. 'order' => 'ASC',
  2819. 'update_comment_meta_cache' => false,
  2820. )
  2821. );
  2822. $comment_prop_to_export = array(
  2823. 'comment_author' => __( 'Comment Author' ),
  2824. 'comment_author_email' => __( 'Comment Author Email' ),
  2825. 'comment_author_url' => __( 'Comment Author URL' ),
  2826. 'comment_author_IP' => __( 'Comment Author IP' ),
  2827. 'comment_agent' => __( 'Comment Author User Agent' ),
  2828. 'comment_date' => __( 'Comment Date' ),
  2829. 'comment_content' => __( 'Comment Content' ),
  2830. 'comment_link' => __( 'Comment URL' ),
  2831. );
  2832. foreach ( (array) $comments as $comment ) {
  2833. $comment_data_to_export = array();
  2834. foreach ( $comment_prop_to_export as $key => $name ) {
  2835. $value = '';
  2836. switch ( $key ) {
  2837. case 'comment_author':
  2838. case 'comment_author_email':
  2839. case 'comment_author_url':
  2840. case 'comment_author_IP':
  2841. case 'comment_agent':
  2842. case 'comment_date':
  2843. $value = $comment->{$key};
  2844. break;
  2845. case 'comment_content':
  2846. $value = get_comment_text( $comment->comment_ID );
  2847. break;
  2848. case 'comment_link':
  2849. $value = get_comment_link( $comment->comment_ID );
  2850. $value = sprintf(
  2851. '<a href="%s" target="_blank" rel="noreferrer noopener">%s</a>',
  2852. esc_url( $value ),
  2853. esc_html( $value )
  2854. );
  2855. break;
  2856. }
  2857. if ( ! empty( $value ) ) {
  2858. $comment_data_to_export[] = array(
  2859. 'name' => $name,
  2860. 'value' => $value,
  2861. );
  2862. }
  2863. }
  2864. $data_to_export[] = array(
  2865. 'group_id' => 'comments',
  2866. 'group_label' => __( 'Comments' ),
  2867. 'item_id' => "comment-{$comment->comment_ID}",
  2868. 'data' => $comment_data_to_export,
  2869. );
  2870. }
  2871. $done = count( $comments ) < $number;
  2872. return array(
  2873. 'data' => $data_to_export,
  2874. 'done' => $done,
  2875. );
  2876. }
  2877. /**
  2878. * Registers the personal data eraser for comments.
  2879. *
  2880. * @since 4.9.6
  2881. *
  2882. * @param array $erasers An array of personal data erasers.
  2883. * @return array $erasers An array of personal data erasers.
  2884. */
  2885. function wp_register_comment_personal_data_eraser( $erasers ) {
  2886. $erasers['wordpress-comments'] = array(
  2887. 'eraser_friendly_name' => __( 'WordPress Comments' ),
  2888. 'callback' => 'wp_comments_personal_data_eraser',
  2889. );
  2890. return $erasers;
  2891. }
  2892. /**
  2893. * Erases personal data associated with an email address from the comments table.
  2894. *
  2895. * @since 4.9.6
  2896. *
  2897. * @param string $email_address The comment author email address.
  2898. * @param int $page Comment page.
  2899. * @return array
  2900. */
  2901. function wp_comments_personal_data_eraser( $email_address, $page = 1 ) {
  2902. global $wpdb;
  2903. if ( empty( $email_address ) ) {
  2904. return array(
  2905. 'items_removed' => false,
  2906. 'items_retained' => false,
  2907. 'messages' => array(),
  2908. 'done' => true,
  2909. );
  2910. }
  2911. // Limit us to 500 comments at a time to avoid timing out.
  2912. $number = 500;
  2913. $page = (int) $page;
  2914. $items_removed = false;
  2915. $items_retained = false;
  2916. $comments = get_comments(
  2917. array(
  2918. 'author_email' => $email_address,
  2919. 'number' => $number,
  2920. 'paged' => $page,
  2921. 'order_by' => 'comment_ID',
  2922. 'order' => 'ASC',
  2923. 'include_unapproved' => true,
  2924. )
  2925. );
  2926. /* translators: Name of a comment's author after being anonymized. */
  2927. $anon_author = __( 'Anonymous' );
  2928. $messages = array();
  2929. foreach ( (array) $comments as $comment ) {
  2930. $anonymized_comment = array();
  2931. $anonymized_comment['comment_agent'] = '';
  2932. $anonymized_comment['comment_author'] = $anon_author;
  2933. $anonymized_comment['comment_author_email'] = '';
  2934. $anonymized_comment['comment_author_IP'] = wp_privacy_anonymize_data( 'ip', $comment->comment_author_IP );
  2935. $anonymized_comment['comment_author_url'] = '';
  2936. $anonymized_comment['user_id'] = 0;
  2937. $comment_id = (int) $comment->comment_ID;
  2938. /**
  2939. * Filters whether to anonymize the comment.
  2940. *
  2941. * @since 4.9.6
  2942. *
  2943. * @param bool|string Whether to apply the comment anonymization (bool).
  2944. * Custom prevention message (string). Default true.
  2945. * @param WP_Comment $comment WP_Comment object.
  2946. * @param array $anonymized_comment Anonymized comment data.
  2947. */
  2948. $anon_message = apply_filters( 'wp_anonymize_comment', true, $comment, $anonymized_comment );
  2949. if ( true !== $anon_message ) {
  2950. if ( $anon_message && is_string( $anon_message ) ) {
  2951. $messages[] = esc_html( $anon_message );
  2952. } else {
  2953. /* translators: %d: Comment ID */
  2954. $messages[] = sprintf( __( 'Comment %d contains personal data but could not be anonymized.' ), $comment_id );
  2955. }
  2956. $items_retained = true;
  2957. continue;
  2958. }
  2959. $args = array(
  2960. 'comment_ID' => $comment_id,
  2961. );
  2962. $updated = $wpdb->update( $wpdb->comments, $anonymized_comment, $args );
  2963. if ( $updated ) {
  2964. $items_removed = true;
  2965. clean_comment_cache( $comment_id );
  2966. } else {
  2967. $items_retained = true;
  2968. }
  2969. }
  2970. $done = count( $comments ) < $number;
  2971. return array(
  2972. 'items_removed' => $items_removed,
  2973. 'items_retained' => $items_retained,
  2974. 'messages' => $messages,
  2975. 'done' => $done,
  2976. );
  2977. }