class-wp-comment-query.php 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235
  1. <?php
  2. /**
  3. * Comment API: WP_Comment_Query class
  4. *
  5. * @package WordPress
  6. * @subpackage Comments
  7. * @since 4.4.0
  8. */
  9. /**
  10. * Core class used for querying comments.
  11. *
  12. * @since 3.1.0
  13. *
  14. * @see WP_Comment_Query::__construct() for accepted arguments.
  15. */
  16. #[AllowDynamicProperties]
  17. class WP_Comment_Query {
  18. /**
  19. * SQL for database query.
  20. *
  21. * @since 4.0.1
  22. * @var string
  23. */
  24. public $request;
  25. /**
  26. * Metadata query container
  27. *
  28. * @since 3.5.0
  29. * @var WP_Meta_Query A meta query instance.
  30. */
  31. public $meta_query = false;
  32. /**
  33. * Metadata query clauses.
  34. *
  35. * @since 4.4.0
  36. * @var array
  37. */
  38. protected $meta_query_clauses;
  39. /**
  40. * SQL query clauses.
  41. *
  42. * @since 4.4.0
  43. * @var array
  44. */
  45. protected $sql_clauses = array(
  46. 'select' => '',
  47. 'from' => '',
  48. 'where' => array(),
  49. 'groupby' => '',
  50. 'orderby' => '',
  51. 'limits' => '',
  52. );
  53. /**
  54. * SQL WHERE clause.
  55. *
  56. * Stored after the {@see 'comments_clauses'} filter is run on the compiled WHERE sub-clauses.
  57. *
  58. * @since 4.4.2
  59. * @var string
  60. */
  61. protected $filtered_where_clause;
  62. /**
  63. * Date query container
  64. *
  65. * @since 3.7.0
  66. * @var WP_Date_Query A date query instance.
  67. */
  68. public $date_query = false;
  69. /**
  70. * Query vars set by the user.
  71. *
  72. * @since 3.1.0
  73. * @var array
  74. */
  75. public $query_vars;
  76. /**
  77. * Default values for query vars.
  78. *
  79. * @since 4.2.0
  80. * @var array
  81. */
  82. public $query_var_defaults;
  83. /**
  84. * List of comments located by the query.
  85. *
  86. * @since 4.0.0
  87. * @var int[]|WP_Comment[]
  88. */
  89. public $comments;
  90. /**
  91. * The amount of found comments for the current query.
  92. *
  93. * @since 4.4.0
  94. * @var int
  95. */
  96. public $found_comments = 0;
  97. /**
  98. * The number of pages.
  99. *
  100. * @since 4.4.0
  101. * @var int
  102. */
  103. public $max_num_pages = 0;
  104. /**
  105. * Make private/protected methods readable for backward compatibility.
  106. *
  107. * @since 4.0.0
  108. *
  109. * @param string $name Method to call.
  110. * @param array $arguments Arguments to pass when calling.
  111. * @return mixed|false Return value of the callback, false otherwise.
  112. */
  113. public function __call( $name, $arguments ) {
  114. if ( 'get_search_sql' === $name ) {
  115. return $this->get_search_sql( ...$arguments );
  116. }
  117. return false;
  118. }
  119. /**
  120. * Constructor.
  121. *
  122. * Sets up the comment query, based on the query vars passed.
  123. *
  124. * @since 4.2.0
  125. * @since 4.4.0 `$parent__in` and `$parent__not_in` were added.
  126. * @since 4.4.0 Order by `comment__in` was added. `$update_comment_meta_cache`, `$no_found_rows`,
  127. * `$hierarchical`, and `$update_comment_post_cache` were added.
  128. * @since 4.5.0 Introduced the `$author_url` argument.
  129. * @since 4.6.0 Introduced the `$cache_domain` argument.
  130. * @since 4.9.0 Introduced the `$paged` argument.
  131. * @since 5.1.0 Introduced the `$meta_compare_key` argument.
  132. * @since 5.3.0 Introduced the `$meta_type_key` argument.
  133. *
  134. * @param string|array $query {
  135. * Optional. Array or query string of comment query parameters. Default empty.
  136. *
  137. * @type string $author_email Comment author email address. Default empty.
  138. * @type string $author_url Comment author URL. Default empty.
  139. * @type int[] $author__in Array of author IDs to include comments for. Default empty.
  140. * @type int[] $author__not_in Array of author IDs to exclude comments for. Default empty.
  141. * @type int[] $comment__in Array of comment IDs to include. Default empty.
  142. * @type int[] $comment__not_in Array of comment IDs to exclude. Default empty.
  143. * @type bool $count Whether to return a comment count (true) or array of
  144. * comment objects (false). Default false.
  145. * @type array $date_query Date query clauses to limit comments by. See WP_Date_Query.
  146. * Default null.
  147. * @type string $fields Comment fields to return. Accepts 'ids' for comment IDs
  148. * only or empty for all fields. Default empty.
  149. * @type array $include_unapproved Array of IDs or email addresses of users whose unapproved
  150. * comments will be returned by the query regardless of
  151. * `$status`. Default empty.
  152. * @type int $karma Karma score to retrieve matching comments for.
  153. * Default empty.
  154. * @type string|string[] $meta_key Meta key or keys to filter by.
  155. * @type string|string[] $meta_value Meta value or values to filter by.
  156. * @type string $meta_compare MySQL operator used for comparing the meta value.
  157. * See WP_Meta_Query::__construct() for accepted values and default value.
  158. * @type string $meta_compare_key MySQL operator used for comparing the meta key.
  159. * See WP_Meta_Query::__construct() for accepted values and default value.
  160. * @type string $meta_type MySQL data type that the meta_value column will be CAST to for comparisons.
  161. * See WP_Meta_Query::__construct() for accepted values and default value.
  162. * @type string $meta_type_key MySQL data type that the meta_key column will be CAST to for comparisons.
  163. * See WP_Meta_Query::__construct() for accepted values and default value.
  164. * @type array $meta_query An associative array of WP_Meta_Query arguments.
  165. * See WP_Meta_Query::__construct() for accepted values.
  166. * @type int $number Maximum number of comments to retrieve.
  167. * Default empty (no limit).
  168. * @type int $paged When used with `$number`, defines the page of results to return.
  169. * When used with `$offset`, `$offset` takes precedence. Default 1.
  170. * @type int $offset Number of comments to offset the query. Used to build
  171. * LIMIT clause. Default 0.
  172. * @type bool $no_found_rows Whether to disable the `SQL_CALC_FOUND_ROWS` query.
  173. * Default: true.
  174. * @type string|array $orderby Comment status or array of statuses. To use 'meta_value'
  175. * or 'meta_value_num', `$meta_key` must also be defined.
  176. * To sort by a specific `$meta_query` clause, use that
  177. * clause's array key. Accepts:
  178. * - 'comment_agent'
  179. * - 'comment_approved'
  180. * - 'comment_author'
  181. * - 'comment_author_email'
  182. * - 'comment_author_IP'
  183. * - 'comment_author_url'
  184. * - 'comment_content'
  185. * - 'comment_date'
  186. * - 'comment_date_gmt'
  187. * - 'comment_ID'
  188. * - 'comment_karma'
  189. * - 'comment_parent'
  190. * - 'comment_post_ID'
  191. * - 'comment_type'
  192. * - 'user_id'
  193. * - 'comment__in'
  194. * - 'meta_value'
  195. * - 'meta_value_num'
  196. * - The value of `$meta_key`
  197. * - The array keys of `$meta_query`
  198. * - false, an empty array, or 'none' to disable `ORDER BY` clause.
  199. * Default: 'comment_date_gmt'.
  200. * @type string $order How to order retrieved comments. Accepts 'ASC', 'DESC'.
  201. * Default: 'DESC'.
  202. * @type int $parent Parent ID of comment to retrieve children of.
  203. * Default empty.
  204. * @type int[] $parent__in Array of parent IDs of comments to retrieve children for.
  205. * Default empty.
  206. * @type int[] $parent__not_in Array of parent IDs of comments *not* to retrieve
  207. * children for. Default empty.
  208. * @type int[] $post_author__in Array of author IDs to retrieve comments for.
  209. * Default empty.
  210. * @type int[] $post_author__not_in Array of author IDs *not* to retrieve comments for.
  211. * Default empty.
  212. * @type int $post_id Limit results to those affiliated with a given post ID.
  213. * Default 0.
  214. * @type int[] $post__in Array of post IDs to include affiliated comments for.
  215. * Default empty.
  216. * @type int[] $post__not_in Array of post IDs to exclude affiliated comments for.
  217. * Default empty.
  218. * @type int $post_author Post author ID to limit results by. Default empty.
  219. * @type string|string[] $post_status Post status or array of post statuses to retrieve
  220. * affiliated comments for. Pass 'any' to match any value.
  221. * Default empty.
  222. * @type string|string[] $post_type Post type or array of post types to retrieve affiliated
  223. * comments for. Pass 'any' to match any value. Default empty.
  224. * @type string $post_name Post name to retrieve affiliated comments for.
  225. * Default empty.
  226. * @type int $post_parent Post parent ID to retrieve affiliated comments for.
  227. * Default empty.
  228. * @type string $search Search term(s) to retrieve matching comments for.
  229. * Default empty.
  230. * @type string|array $status Comment statuses to limit results by. Accepts an array
  231. * or space/comma-separated list of 'hold' (`comment_status=0`),
  232. * 'approve' (`comment_status=1`), 'all', or a custom
  233. * comment status. Default 'all'.
  234. * @type string|string[] $type Include comments of a given type, or array of types.
  235. * Accepts 'comment', 'pings' (includes 'pingback' and
  236. * 'trackback'), or any custom type string. Default empty.
  237. * @type string[] $type__in Include comments from a given array of comment types.
  238. * Default empty.
  239. * @type string[] $type__not_in Exclude comments from a given array of comment types.
  240. * Default empty.
  241. * @type int $user_id Include comments for a specific user ID. Default empty.
  242. * @type bool|string $hierarchical Whether to include comment descendants in the results.
  243. * - 'threaded' returns a tree, with each comment's children
  244. * stored in a `children` property on the `WP_Comment` object.
  245. * - 'flat' returns a flat array of found comments plus
  246. * their children.
  247. * - Boolean `false` leaves out descendants.
  248. * The parameter is ignored (forced to `false`) when
  249. * `$fields` is 'ids' or 'counts'. Accepts 'threaded',
  250. * 'flat', or false. Default: false.
  251. * @type string $cache_domain Unique cache key to be produced when this query is stored in
  252. * an object cache. Default is 'core'.
  253. * @type bool $update_comment_meta_cache Whether to prime the metadata cache for found comments.
  254. * Default true.
  255. * @type bool $update_comment_post_cache Whether to prime the cache for comment posts.
  256. * Default false.
  257. * }
  258. */
  259. public function __construct( $query = '' ) {
  260. $this->query_var_defaults = array(
  261. 'author_email' => '',
  262. 'author_url' => '',
  263. 'author__in' => '',
  264. 'author__not_in' => '',
  265. 'include_unapproved' => '',
  266. 'fields' => '',
  267. 'ID' => '',
  268. 'comment__in' => '',
  269. 'comment__not_in' => '',
  270. 'karma' => '',
  271. 'number' => '',
  272. 'offset' => '',
  273. 'no_found_rows' => true,
  274. 'orderby' => '',
  275. 'order' => 'DESC',
  276. 'paged' => 1,
  277. 'parent' => '',
  278. 'parent__in' => '',
  279. 'parent__not_in' => '',
  280. 'post_author__in' => '',
  281. 'post_author__not_in' => '',
  282. 'post_ID' => '',
  283. 'post_id' => 0,
  284. 'post__in' => '',
  285. 'post__not_in' => '',
  286. 'post_author' => '',
  287. 'post_name' => '',
  288. 'post_parent' => '',
  289. 'post_status' => '',
  290. 'post_type' => '',
  291. 'status' => 'all',
  292. 'type' => '',
  293. 'type__in' => '',
  294. 'type__not_in' => '',
  295. 'user_id' => '',
  296. 'search' => '',
  297. 'count' => false,
  298. 'meta_key' => '',
  299. 'meta_value' => '',
  300. 'meta_query' => '',
  301. 'date_query' => null, // See WP_Date_Query.
  302. 'hierarchical' => false,
  303. 'cache_domain' => 'core',
  304. 'update_comment_meta_cache' => true,
  305. 'update_comment_post_cache' => false,
  306. );
  307. if ( ! empty( $query ) ) {
  308. $this->query( $query );
  309. }
  310. }
  311. /**
  312. * Parse arguments passed to the comment query with default query parameters.
  313. *
  314. * @since 4.2.0 Extracted from WP_Comment_Query::query().
  315. *
  316. * @param string|array $query WP_Comment_Query arguments. See WP_Comment_Query::__construct()
  317. */
  318. public function parse_query( $query = '' ) {
  319. if ( empty( $query ) ) {
  320. $query = $this->query_vars;
  321. }
  322. $this->query_vars = wp_parse_args( $query, $this->query_var_defaults );
  323. /**
  324. * Fires after the comment query vars have been parsed.
  325. *
  326. * @since 4.2.0
  327. *
  328. * @param WP_Comment_Query $query The WP_Comment_Query instance (passed by reference).
  329. */
  330. do_action_ref_array( 'parse_comment_query', array( &$this ) );
  331. }
  332. /**
  333. * Sets up the WordPress query for retrieving comments.
  334. *
  335. * @since 3.1.0
  336. * @since 4.1.0 Introduced 'comment__in', 'comment__not_in', 'post_author__in',
  337. * 'post_author__not_in', 'author__in', 'author__not_in', 'post__in',
  338. * 'post__not_in', 'include_unapproved', 'type__in', and 'type__not_in'
  339. * arguments to $query_vars.
  340. * @since 4.2.0 Moved parsing to WP_Comment_Query::parse_query().
  341. *
  342. * @param string|array $query Array or URL query string of parameters.
  343. * @return array|int List of comments, or number of comments when 'count' is passed as a query var.
  344. */
  345. public function query( $query ) {
  346. $this->query_vars = wp_parse_args( $query );
  347. return $this->get_comments();
  348. }
  349. /**
  350. * Get a list of comments matching the query vars.
  351. *
  352. * @since 4.2.0
  353. *
  354. * @global wpdb $wpdb WordPress database abstraction object.
  355. *
  356. * @return int|int[]|WP_Comment[] List of comments or number of found comments if `$count` argument is true.
  357. */
  358. public function get_comments() {
  359. global $wpdb;
  360. $this->parse_query();
  361. // Parse meta query.
  362. $this->meta_query = new WP_Meta_Query();
  363. $this->meta_query->parse_query_vars( $this->query_vars );
  364. /**
  365. * Fires before comments are retrieved.
  366. *
  367. * @since 3.1.0
  368. *
  369. * @param WP_Comment_Query $query Current instance of WP_Comment_Query (passed by reference).
  370. */
  371. do_action_ref_array( 'pre_get_comments', array( &$this ) );
  372. // Reparse query vars, in case they were modified in a 'pre_get_comments' callback.
  373. $this->meta_query->parse_query_vars( $this->query_vars );
  374. if ( ! empty( $this->meta_query->queries ) ) {
  375. $this->meta_query_clauses = $this->meta_query->get_sql( 'comment', $wpdb->comments, 'comment_ID', $this );
  376. }
  377. $comment_data = null;
  378. /**
  379. * Filters the comments data before the query takes place.
  380. *
  381. * Return a non-null value to bypass WordPress' default comment queries.
  382. *
  383. * The expected return type from this filter depends on the value passed
  384. * in the request query vars:
  385. * - When `$this->query_vars['count']` is set, the filter should return
  386. * the comment count as an integer.
  387. * - When `'ids' === $this->query_vars['fields']`, the filter should return
  388. * an array of comment IDs.
  389. * - Otherwise the filter should return an array of WP_Comment objects.
  390. *
  391. * Note that if the filter returns an array of comment data, it will be assigned
  392. * to the `comments` property of the current WP_Comment_Query instance.
  393. *
  394. * Filtering functions that require pagination information are encouraged to set
  395. * the `found_comments` and `max_num_pages` properties of the WP_Comment_Query object,
  396. * passed to the filter by reference. If WP_Comment_Query does not perform a database
  397. * query, it will not have enough information to generate these values itself.
  398. *
  399. * @since 5.3.0
  400. * @since 5.6.0 The returned array of comment data is assigned to the `comments` property
  401. * of the current WP_Comment_Query instance.
  402. *
  403. * @param array|int|null $comment_data Return an array of comment data to short-circuit WP's comment query,
  404. * the comment count as an integer if `$this->query_vars['count']` is set,
  405. * or null to allow WP to run its normal queries.
  406. * @param WP_Comment_Query $query The WP_Comment_Query instance, passed by reference.
  407. */
  408. $comment_data = apply_filters_ref_array( 'comments_pre_query', array( $comment_data, &$this ) );
  409. if ( null !== $comment_data ) {
  410. if ( is_array( $comment_data ) && ! $this->query_vars['count'] ) {
  411. $this->comments = $comment_data;
  412. }
  413. return $comment_data;
  414. }
  415. /*
  416. * Only use the args defined in the query_var_defaults to compute the key,
  417. * but ignore 'fields', 'update_comment_meta_cache', 'update_comment_post_cache' which does not affect query results.
  418. */
  419. $_args = wp_array_slice_assoc( $this->query_vars, array_keys( $this->query_var_defaults ) );
  420. unset( $_args['fields'], $_args['update_comment_meta_cache'], $_args['update_comment_post_cache'] );
  421. $key = md5( serialize( $_args ) );
  422. $last_changed = wp_cache_get_last_changed( 'comment' );
  423. $cache_key = "get_comments:$key:$last_changed";
  424. $cache_value = wp_cache_get( $cache_key, 'comment' );
  425. if ( false === $cache_value ) {
  426. $comment_ids = $this->get_comment_ids();
  427. if ( $comment_ids ) {
  428. $this->set_found_comments();
  429. }
  430. $cache_value = array(
  431. 'comment_ids' => $comment_ids,
  432. 'found_comments' => $this->found_comments,
  433. );
  434. wp_cache_add( $cache_key, $cache_value, 'comment' );
  435. } else {
  436. $comment_ids = $cache_value['comment_ids'];
  437. $this->found_comments = $cache_value['found_comments'];
  438. }
  439. if ( $this->found_comments && $this->query_vars['number'] ) {
  440. $this->max_num_pages = ceil( $this->found_comments / $this->query_vars['number'] );
  441. }
  442. // If querying for a count only, there's nothing more to do.
  443. if ( $this->query_vars['count'] ) {
  444. // $comment_ids is actually a count in this case.
  445. return (int) $comment_ids;
  446. }
  447. $comment_ids = array_map( 'intval', $comment_ids );
  448. if ( 'ids' === $this->query_vars['fields'] ) {
  449. $this->comments = $comment_ids;
  450. return $this->comments;
  451. }
  452. _prime_comment_caches( $comment_ids, $this->query_vars['update_comment_meta_cache'] );
  453. // Fetch full comment objects from the primed cache.
  454. $_comments = array();
  455. foreach ( $comment_ids as $comment_id ) {
  456. $_comment = get_comment( $comment_id );
  457. if ( $_comment ) {
  458. $_comments[] = $_comment;
  459. }
  460. }
  461. // Prime comment post caches.
  462. if ( $this->query_vars['update_comment_post_cache'] ) {
  463. $comment_post_ids = array();
  464. foreach ( $_comments as $_comment ) {
  465. $comment_post_ids[] = $_comment->comment_post_ID;
  466. }
  467. _prime_post_caches( $comment_post_ids, false, false );
  468. }
  469. /**
  470. * Filters the comment query results.
  471. *
  472. * @since 3.1.0
  473. *
  474. * @param WP_Comment[] $_comments An array of comments.
  475. * @param WP_Comment_Query $query Current instance of WP_Comment_Query (passed by reference).
  476. */
  477. $_comments = apply_filters_ref_array( 'the_comments', array( $_comments, &$this ) );
  478. // Convert to WP_Comment instances.
  479. $comments = array_map( 'get_comment', $_comments );
  480. if ( $this->query_vars['hierarchical'] ) {
  481. $comments = $this->fill_descendants( $comments );
  482. }
  483. $this->comments = $comments;
  484. return $this->comments;
  485. }
  486. /**
  487. * Used internally to get a list of comment IDs matching the query vars.
  488. *
  489. * @since 4.4.0
  490. *
  491. * @global wpdb $wpdb WordPress database abstraction object.
  492. *
  493. * @return int|array A single count of comment IDs if a count query. An array of comment IDs if a full query.
  494. */
  495. protected function get_comment_ids() {
  496. global $wpdb;
  497. // Assemble clauses related to 'comment_approved'.
  498. $approved_clauses = array();
  499. // 'status' accepts an array or a comma-separated string.
  500. $status_clauses = array();
  501. $statuses = wp_parse_list( $this->query_vars['status'] );
  502. // Empty 'status' should be interpreted as 'all'.
  503. if ( empty( $statuses ) ) {
  504. $statuses = array( 'all' );
  505. }
  506. // 'any' overrides other statuses.
  507. if ( ! in_array( 'any', $statuses, true ) ) {
  508. foreach ( $statuses as $status ) {
  509. switch ( $status ) {
  510. case 'hold':
  511. $status_clauses[] = "comment_approved = '0'";
  512. break;
  513. case 'approve':
  514. $status_clauses[] = "comment_approved = '1'";
  515. break;
  516. case 'all':
  517. case '':
  518. $status_clauses[] = "( comment_approved = '0' OR comment_approved = '1' )";
  519. break;
  520. default:
  521. $status_clauses[] = $wpdb->prepare( 'comment_approved = %s', $status );
  522. break;
  523. }
  524. }
  525. if ( ! empty( $status_clauses ) ) {
  526. $approved_clauses[] = '( ' . implode( ' OR ', $status_clauses ) . ' )';
  527. }
  528. }
  529. // User IDs or emails whose unapproved comments are included, regardless of $status.
  530. if ( ! empty( $this->query_vars['include_unapproved'] ) ) {
  531. $include_unapproved = wp_parse_list( $this->query_vars['include_unapproved'] );
  532. $unapproved_ids = array();
  533. $unapproved_emails = array();
  534. foreach ( $include_unapproved as $unapproved_identifier ) {
  535. // Numeric values are assumed to be user IDs.
  536. if ( is_numeric( $unapproved_identifier ) ) {
  537. $approved_clauses[] = $wpdb->prepare( "( user_id = %d AND comment_approved = '0' )", $unapproved_identifier );
  538. } else {
  539. // Otherwise we match against email addresses.
  540. if ( ! empty( $_GET['unapproved'] ) && ! empty( $_GET['moderation-hash'] ) ) {
  541. // Only include requested comment.
  542. $approved_clauses[] = $wpdb->prepare( "( comment_author_email = %s AND comment_approved = '0' AND {$wpdb->comments}.comment_ID = %d )", $unapproved_identifier, (int) $_GET['unapproved'] );
  543. } else {
  544. // Include all of the author's unapproved comments.
  545. $approved_clauses[] = $wpdb->prepare( "( comment_author_email = %s AND comment_approved = '0' )", $unapproved_identifier );
  546. }
  547. }
  548. }
  549. }
  550. // Collapse comment_approved clauses into a single OR-separated clause.
  551. if ( ! empty( $approved_clauses ) ) {
  552. if ( 1 === count( $approved_clauses ) ) {
  553. $this->sql_clauses['where']['approved'] = $approved_clauses[0];
  554. } else {
  555. $this->sql_clauses['where']['approved'] = '( ' . implode( ' OR ', $approved_clauses ) . ' )';
  556. }
  557. }
  558. $order = ( 'ASC' === strtoupper( $this->query_vars['order'] ) ) ? 'ASC' : 'DESC';
  559. // Disable ORDER BY with 'none', an empty array, or boolean false.
  560. if ( in_array( $this->query_vars['orderby'], array( 'none', array(), false ), true ) ) {
  561. $orderby = '';
  562. } elseif ( ! empty( $this->query_vars['orderby'] ) ) {
  563. $ordersby = is_array( $this->query_vars['orderby'] ) ?
  564. $this->query_vars['orderby'] :
  565. preg_split( '/[,\s]/', $this->query_vars['orderby'] );
  566. $orderby_array = array();
  567. $found_orderby_comment_id = false;
  568. foreach ( $ordersby as $_key => $_value ) {
  569. if ( ! $_value ) {
  570. continue;
  571. }
  572. if ( is_int( $_key ) ) {
  573. $_orderby = $_value;
  574. $_order = $order;
  575. } else {
  576. $_orderby = $_key;
  577. $_order = $_value;
  578. }
  579. if ( ! $found_orderby_comment_id && in_array( $_orderby, array( 'comment_ID', 'comment__in' ), true ) ) {
  580. $found_orderby_comment_id = true;
  581. }
  582. $parsed = $this->parse_orderby( $_orderby );
  583. if ( ! $parsed ) {
  584. continue;
  585. }
  586. if ( 'comment__in' === $_orderby ) {
  587. $orderby_array[] = $parsed;
  588. continue;
  589. }
  590. $orderby_array[] = $parsed . ' ' . $this->parse_order( $_order );
  591. }
  592. // If no valid clauses were found, order by comment_date_gmt.
  593. if ( empty( $orderby_array ) ) {
  594. $orderby_array[] = "$wpdb->comments.comment_date_gmt $order";
  595. }
  596. // To ensure determinate sorting, always include a comment_ID clause.
  597. if ( ! $found_orderby_comment_id ) {
  598. $comment_id_order = '';
  599. // Inherit order from comment_date or comment_date_gmt, if available.
  600. foreach ( $orderby_array as $orderby_clause ) {
  601. if ( preg_match( '/comment_date(?:_gmt)*\ (ASC|DESC)/', $orderby_clause, $match ) ) {
  602. $comment_id_order = $match[1];
  603. break;
  604. }
  605. }
  606. // If no date-related order is available, use the date from the first available clause.
  607. if ( ! $comment_id_order ) {
  608. foreach ( $orderby_array as $orderby_clause ) {
  609. if ( false !== strpos( 'ASC', $orderby_clause ) ) {
  610. $comment_id_order = 'ASC';
  611. } else {
  612. $comment_id_order = 'DESC';
  613. }
  614. break;
  615. }
  616. }
  617. // Default to DESC.
  618. if ( ! $comment_id_order ) {
  619. $comment_id_order = 'DESC';
  620. }
  621. $orderby_array[] = "$wpdb->comments.comment_ID $comment_id_order";
  622. }
  623. $orderby = implode( ', ', $orderby_array );
  624. } else {
  625. $orderby = "$wpdb->comments.comment_date_gmt $order";
  626. }
  627. $number = absint( $this->query_vars['number'] );
  628. $offset = absint( $this->query_vars['offset'] );
  629. $paged = absint( $this->query_vars['paged'] );
  630. $limits = '';
  631. if ( ! empty( $number ) ) {
  632. if ( $offset ) {
  633. $limits = 'LIMIT ' . $offset . ',' . $number;
  634. } else {
  635. $limits = 'LIMIT ' . ( $number * ( $paged - 1 ) ) . ',' . $number;
  636. }
  637. }
  638. if ( $this->query_vars['count'] ) {
  639. $fields = 'COUNT(*)';
  640. } else {
  641. $fields = "$wpdb->comments.comment_ID";
  642. }
  643. $post_id = absint( $this->query_vars['post_id'] );
  644. if ( ! empty( $post_id ) ) {
  645. $this->sql_clauses['where']['post_id'] = $wpdb->prepare( 'comment_post_ID = %d', $post_id );
  646. }
  647. // Parse comment IDs for an IN clause.
  648. if ( ! empty( $this->query_vars['comment__in'] ) ) {
  649. $this->sql_clauses['where']['comment__in'] = "$wpdb->comments.comment_ID IN ( " . implode( ',', wp_parse_id_list( $this->query_vars['comment__in'] ) ) . ' )';
  650. }
  651. // Parse comment IDs for a NOT IN clause.
  652. if ( ! empty( $this->query_vars['comment__not_in'] ) ) {
  653. $this->sql_clauses['where']['comment__not_in'] = "$wpdb->comments.comment_ID NOT IN ( " . implode( ',', wp_parse_id_list( $this->query_vars['comment__not_in'] ) ) . ' )';
  654. }
  655. // Parse comment parent IDs for an IN clause.
  656. if ( ! empty( $this->query_vars['parent__in'] ) ) {
  657. $this->sql_clauses['where']['parent__in'] = 'comment_parent IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['parent__in'] ) ) . ' )';
  658. }
  659. // Parse comment parent IDs for a NOT IN clause.
  660. if ( ! empty( $this->query_vars['parent__not_in'] ) ) {
  661. $this->sql_clauses['where']['parent__not_in'] = 'comment_parent NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['parent__not_in'] ) ) . ' )';
  662. }
  663. // Parse comment post IDs for an IN clause.
  664. if ( ! empty( $this->query_vars['post__in'] ) ) {
  665. $this->sql_clauses['where']['post__in'] = 'comment_post_ID IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post__in'] ) ) . ' )';
  666. }
  667. // Parse comment post IDs for a NOT IN clause.
  668. if ( ! empty( $this->query_vars['post__not_in'] ) ) {
  669. $this->sql_clauses['where']['post__not_in'] = 'comment_post_ID NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post__not_in'] ) ) . ' )';
  670. }
  671. if ( '' !== $this->query_vars['author_email'] ) {
  672. $this->sql_clauses['where']['author_email'] = $wpdb->prepare( 'comment_author_email = %s', $this->query_vars['author_email'] );
  673. }
  674. if ( '' !== $this->query_vars['author_url'] ) {
  675. $this->sql_clauses['where']['author_url'] = $wpdb->prepare( 'comment_author_url = %s', $this->query_vars['author_url'] );
  676. }
  677. if ( '' !== $this->query_vars['karma'] ) {
  678. $this->sql_clauses['where']['karma'] = $wpdb->prepare( 'comment_karma = %d', $this->query_vars['karma'] );
  679. }
  680. // Filtering by comment_type: 'type', 'type__in', 'type__not_in'.
  681. $raw_types = array(
  682. 'IN' => array_merge( (array) $this->query_vars['type'], (array) $this->query_vars['type__in'] ),
  683. 'NOT IN' => (array) $this->query_vars['type__not_in'],
  684. );
  685. $comment_types = array();
  686. foreach ( $raw_types as $operator => $_raw_types ) {
  687. $_raw_types = array_unique( $_raw_types );
  688. foreach ( $_raw_types as $type ) {
  689. switch ( $type ) {
  690. // An empty translates to 'all', for backward compatibility.
  691. case '':
  692. case 'all':
  693. break;
  694. case 'comment':
  695. case 'comments':
  696. $comment_types[ $operator ][] = "''";
  697. $comment_types[ $operator ][] = "'comment'";
  698. break;
  699. case 'pings':
  700. $comment_types[ $operator ][] = "'pingback'";
  701. $comment_types[ $operator ][] = "'trackback'";
  702. break;
  703. default:
  704. $comment_types[ $operator ][] = $wpdb->prepare( '%s', $type );
  705. break;
  706. }
  707. }
  708. if ( ! empty( $comment_types[ $operator ] ) ) {
  709. $types_sql = implode( ', ', $comment_types[ $operator ] );
  710. $this->sql_clauses['where'][ 'comment_type__' . strtolower( str_replace( ' ', '_', $operator ) ) ] = "comment_type $operator ($types_sql)";
  711. }
  712. }
  713. $parent = $this->query_vars['parent'];
  714. if ( $this->query_vars['hierarchical'] && ! $parent ) {
  715. $parent = 0;
  716. }
  717. if ( '' !== $parent ) {
  718. $this->sql_clauses['where']['parent'] = $wpdb->prepare( 'comment_parent = %d', $parent );
  719. }
  720. if ( is_array( $this->query_vars['user_id'] ) ) {
  721. $this->sql_clauses['where']['user_id'] = 'user_id IN (' . implode( ',', array_map( 'absint', $this->query_vars['user_id'] ) ) . ')';
  722. } elseif ( '' !== $this->query_vars['user_id'] ) {
  723. $this->sql_clauses['where']['user_id'] = $wpdb->prepare( 'user_id = %d', $this->query_vars['user_id'] );
  724. }
  725. // Falsey search strings are ignored.
  726. if ( isset( $this->query_vars['search'] ) && strlen( $this->query_vars['search'] ) ) {
  727. $search_sql = $this->get_search_sql(
  728. $this->query_vars['search'],
  729. array( 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_author_IP', 'comment_content' )
  730. );
  731. // Strip leading 'AND'.
  732. $this->sql_clauses['where']['search'] = preg_replace( '/^\s*AND\s*/', '', $search_sql );
  733. }
  734. // If any post-related query vars are passed, join the posts table.
  735. $join_posts_table = false;
  736. $plucked = wp_array_slice_assoc( $this->query_vars, array( 'post_author', 'post_name', 'post_parent' ) );
  737. $post_fields = array_filter( $plucked );
  738. if ( ! empty( $post_fields ) ) {
  739. $join_posts_table = true;
  740. foreach ( $post_fields as $field_name => $field_value ) {
  741. // $field_value may be an array.
  742. $esses = array_fill( 0, count( (array) $field_value ), '%s' );
  743. // phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
  744. $this->sql_clauses['where'][ $field_name ] = $wpdb->prepare( " {$wpdb->posts}.{$field_name} IN (" . implode( ',', $esses ) . ')', $field_value );
  745. }
  746. }
  747. // 'post_status' and 'post_type' are handled separately, due to the specialized behavior of 'any'.
  748. foreach ( array( 'post_status', 'post_type' ) as $field_name ) {
  749. $q_values = array();
  750. if ( ! empty( $this->query_vars[ $field_name ] ) ) {
  751. $q_values = $this->query_vars[ $field_name ];
  752. if ( ! is_array( $q_values ) ) {
  753. $q_values = explode( ',', $q_values );
  754. }
  755. // 'any' will cause the query var to be ignored.
  756. if ( in_array( 'any', $q_values, true ) || empty( $q_values ) ) {
  757. continue;
  758. }
  759. $join_posts_table = true;
  760. $esses = array_fill( 0, count( $q_values ), '%s' );
  761. // phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
  762. $this->sql_clauses['where'][ $field_name ] = $wpdb->prepare( " {$wpdb->posts}.{$field_name} IN (" . implode( ',', $esses ) . ')', $q_values );
  763. }
  764. }
  765. // Comment author IDs for an IN clause.
  766. if ( ! empty( $this->query_vars['author__in'] ) ) {
  767. $this->sql_clauses['where']['author__in'] = 'user_id IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['author__in'] ) ) . ' )';
  768. }
  769. // Comment author IDs for a NOT IN clause.
  770. if ( ! empty( $this->query_vars['author__not_in'] ) ) {
  771. $this->sql_clauses['where']['author__not_in'] = 'user_id NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['author__not_in'] ) ) . ' )';
  772. }
  773. // Post author IDs for an IN clause.
  774. if ( ! empty( $this->query_vars['post_author__in'] ) ) {
  775. $join_posts_table = true;
  776. $this->sql_clauses['where']['post_author__in'] = 'post_author IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post_author__in'] ) ) . ' )';
  777. }
  778. // Post author IDs for a NOT IN clause.
  779. if ( ! empty( $this->query_vars['post_author__not_in'] ) ) {
  780. $join_posts_table = true;
  781. $this->sql_clauses['where']['post_author__not_in'] = 'post_author NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post_author__not_in'] ) ) . ' )';
  782. }
  783. $join = '';
  784. $groupby = '';
  785. if ( $join_posts_table ) {
  786. $join .= "JOIN $wpdb->posts ON $wpdb->posts.ID = $wpdb->comments.comment_post_ID";
  787. }
  788. if ( ! empty( $this->meta_query_clauses ) ) {
  789. $join .= $this->meta_query_clauses['join'];
  790. // Strip leading 'AND'.
  791. $this->sql_clauses['where']['meta_query'] = preg_replace( '/^\s*AND\s*/', '', $this->meta_query_clauses['where'] );
  792. if ( ! $this->query_vars['count'] ) {
  793. $groupby = "{$wpdb->comments}.comment_ID";
  794. }
  795. }
  796. if ( ! empty( $this->query_vars['date_query'] ) && is_array( $this->query_vars['date_query'] ) ) {
  797. $this->date_query = new WP_Date_Query( $this->query_vars['date_query'], 'comment_date' );
  798. // Strip leading 'AND'.
  799. $this->sql_clauses['where']['date_query'] = preg_replace( '/^\s*AND\s*/', '', $this->date_query->get_sql() );
  800. }
  801. $where = implode( ' AND ', $this->sql_clauses['where'] );
  802. $pieces = array( 'fields', 'join', 'where', 'orderby', 'limits', 'groupby' );
  803. /**
  804. * Filters the comment query clauses.
  805. *
  806. * @since 3.1.0
  807. *
  808. * @param string[] $clauses An associative array of comment query clauses.
  809. * @param WP_Comment_Query $query Current instance of WP_Comment_Query (passed by reference).
  810. */
  811. $clauses = apply_filters_ref_array( 'comments_clauses', array( compact( $pieces ), &$this ) );
  812. $fields = isset( $clauses['fields'] ) ? $clauses['fields'] : '';
  813. $join = isset( $clauses['join'] ) ? $clauses['join'] : '';
  814. $where = isset( $clauses['where'] ) ? $clauses['where'] : '';
  815. $orderby = isset( $clauses['orderby'] ) ? $clauses['orderby'] : '';
  816. $limits = isset( $clauses['limits'] ) ? $clauses['limits'] : '';
  817. $groupby = isset( $clauses['groupby'] ) ? $clauses['groupby'] : '';
  818. $this->filtered_where_clause = $where;
  819. if ( $where ) {
  820. $where = 'WHERE ' . $where;
  821. }
  822. if ( $groupby ) {
  823. $groupby = 'GROUP BY ' . $groupby;
  824. }
  825. if ( $orderby ) {
  826. $orderby = "ORDER BY $orderby";
  827. }
  828. $found_rows = '';
  829. if ( ! $this->query_vars['no_found_rows'] ) {
  830. $found_rows = 'SQL_CALC_FOUND_ROWS';
  831. }
  832. $this->sql_clauses['select'] = "SELECT $found_rows $fields";
  833. $this->sql_clauses['from'] = "FROM $wpdb->comments $join";
  834. $this->sql_clauses['groupby'] = $groupby;
  835. $this->sql_clauses['orderby'] = $orderby;
  836. $this->sql_clauses['limits'] = $limits;
  837. $this->request = "
  838. {$this->sql_clauses['select']}
  839. {$this->sql_clauses['from']}
  840. {$where}
  841. {$this->sql_clauses['groupby']}
  842. {$this->sql_clauses['orderby']}
  843. {$this->sql_clauses['limits']}
  844. ";
  845. if ( $this->query_vars['count'] ) {
  846. return (int) $wpdb->get_var( $this->request );
  847. } else {
  848. $comment_ids = $wpdb->get_col( $this->request );
  849. return array_map( 'intval', $comment_ids );
  850. }
  851. }
  852. /**
  853. * Populates found_comments and max_num_pages properties for the current
  854. * query if the limit clause was used.
  855. *
  856. * @since 4.6.0
  857. *
  858. * @global wpdb $wpdb WordPress database abstraction object.
  859. */
  860. private function set_found_comments() {
  861. global $wpdb;
  862. if ( $this->query_vars['number'] && ! $this->query_vars['no_found_rows'] ) {
  863. /**
  864. * Filters the query used to retrieve found comment count.
  865. *
  866. * @since 4.4.0
  867. *
  868. * @param string $found_comments_query SQL query. Default 'SELECT FOUND_ROWS()'.
  869. * @param WP_Comment_Query $comment_query The `WP_Comment_Query` instance.
  870. */
  871. $found_comments_query = apply_filters( 'found_comments_query', 'SELECT FOUND_ROWS()', $this );
  872. $this->found_comments = (int) $wpdb->get_var( $found_comments_query );
  873. }
  874. }
  875. /**
  876. * Fetch descendants for located comments.
  877. *
  878. * Instead of calling `get_children()` separately on each child comment, we do a single set of queries to fetch
  879. * the descendant trees for all matched top-level comments.
  880. *
  881. * @since 4.4.0
  882. *
  883. * @global wpdb $wpdb WordPress database abstraction object.
  884. *
  885. * @param WP_Comment[] $comments Array of top-level comments whose descendants should be filled in.
  886. * @return array
  887. */
  888. protected function fill_descendants( $comments ) {
  889. global $wpdb;
  890. $levels = array(
  891. 0 => wp_list_pluck( $comments, 'comment_ID' ),
  892. );
  893. $key = md5( serialize( wp_array_slice_assoc( $this->query_vars, array_keys( $this->query_var_defaults ) ) ) );
  894. $last_changed = wp_cache_get_last_changed( 'comment' );
  895. // Fetch an entire level of the descendant tree at a time.
  896. $level = 0;
  897. $exclude_keys = array( 'parent', 'parent__in', 'parent__not_in' );
  898. do {
  899. // Parent-child relationships may be cached. Only query for those that are not.
  900. $child_ids = array();
  901. $uncached_parent_ids = array();
  902. $_parent_ids = $levels[ $level ];
  903. foreach ( $_parent_ids as $parent_id ) {
  904. $cache_key = "get_comment_child_ids:$parent_id:$key:$last_changed";
  905. $parent_child_ids = wp_cache_get( $cache_key, 'comment' );
  906. if ( false !== $parent_child_ids ) {
  907. $child_ids = array_merge( $child_ids, $parent_child_ids );
  908. } else {
  909. $uncached_parent_ids[] = $parent_id;
  910. }
  911. }
  912. if ( $uncached_parent_ids ) {
  913. // Fetch this level of comments.
  914. $parent_query_args = $this->query_vars;
  915. foreach ( $exclude_keys as $exclude_key ) {
  916. $parent_query_args[ $exclude_key ] = '';
  917. }
  918. $parent_query_args['parent__in'] = $uncached_parent_ids;
  919. $parent_query_args['no_found_rows'] = true;
  920. $parent_query_args['hierarchical'] = false;
  921. $parent_query_args['offset'] = 0;
  922. $parent_query_args['number'] = 0;
  923. $level_comments = get_comments( $parent_query_args );
  924. // Cache parent-child relationships.
  925. $parent_map = array_fill_keys( $uncached_parent_ids, array() );
  926. foreach ( $level_comments as $level_comment ) {
  927. $parent_map[ $level_comment->comment_parent ][] = $level_comment->comment_ID;
  928. $child_ids[] = $level_comment->comment_ID;
  929. }
  930. $data = array();
  931. foreach ( $parent_map as $parent_id => $children ) {
  932. $cache_key = "get_comment_child_ids:$parent_id:$key:$last_changed";
  933. $data[ $cache_key ] = $children;
  934. }
  935. wp_cache_set_multiple( $data, 'comment' );
  936. }
  937. $level++;
  938. $levels[ $level ] = $child_ids;
  939. } while ( $child_ids );
  940. // Prime comment caches for non-top-level comments.
  941. $descendant_ids = array();
  942. for ( $i = 1, $c = count( $levels ); $i < $c; $i++ ) {
  943. $descendant_ids = array_merge( $descendant_ids, $levels[ $i ] );
  944. }
  945. _prime_comment_caches( $descendant_ids, $this->query_vars['update_comment_meta_cache'] );
  946. // Assemble a flat array of all comments + descendants.
  947. $all_comments = $comments;
  948. foreach ( $descendant_ids as $descendant_id ) {
  949. $all_comments[] = get_comment( $descendant_id );
  950. }
  951. // If a threaded representation was requested, build the tree.
  952. if ( 'threaded' === $this->query_vars['hierarchical'] ) {
  953. $threaded_comments = array();
  954. $ref = array();
  955. foreach ( $all_comments as $k => $c ) {
  956. $_c = get_comment( $c->comment_ID );
  957. // If the comment isn't in the reference array, it goes in the top level of the thread.
  958. if ( ! isset( $ref[ $c->comment_parent ] ) ) {
  959. $threaded_comments[ $_c->comment_ID ] = $_c;
  960. $ref[ $_c->comment_ID ] = $threaded_comments[ $_c->comment_ID ];
  961. // Otherwise, set it as a child of its parent.
  962. } else {
  963. $ref[ $_c->comment_parent ]->add_child( $_c );
  964. $ref[ $_c->comment_ID ] = $ref[ $_c->comment_parent ]->get_child( $_c->comment_ID );
  965. }
  966. }
  967. // Set the 'populated_children' flag, to ensure additional database queries aren't run.
  968. foreach ( $ref as $_ref ) {
  969. $_ref->populated_children( true );
  970. }
  971. $comments = $threaded_comments;
  972. } else {
  973. $comments = $all_comments;
  974. }
  975. return $comments;
  976. }
  977. /**
  978. * Used internally to generate an SQL string for searching across multiple columns.
  979. *
  980. * @since 3.1.0
  981. *
  982. * @global wpdb $wpdb WordPress database abstraction object.
  983. *
  984. * @param string $search Search string.
  985. * @param string[] $columns Array of columns to search.
  986. * @return string Search SQL.
  987. */
  988. protected function get_search_sql( $search, $columns ) {
  989. global $wpdb;
  990. $like = '%' . $wpdb->esc_like( $search ) . '%';
  991. $searches = array();
  992. foreach ( $columns as $column ) {
  993. $searches[] = $wpdb->prepare( "$column LIKE %s", $like );
  994. }
  995. return ' AND (' . implode( ' OR ', $searches ) . ')';
  996. }
  997. /**
  998. * Parse and sanitize 'orderby' keys passed to the comment query.
  999. *
  1000. * @since 4.2.0
  1001. *
  1002. * @global wpdb $wpdb WordPress database abstraction object.
  1003. *
  1004. * @param string $orderby Alias for the field to order by.
  1005. * @return string|false Value to used in the ORDER clause. False otherwise.
  1006. */
  1007. protected function parse_orderby( $orderby ) {
  1008. global $wpdb;
  1009. $allowed_keys = array(
  1010. 'comment_agent',
  1011. 'comment_approved',
  1012. 'comment_author',
  1013. 'comment_author_email',
  1014. 'comment_author_IP',
  1015. 'comment_author_url',
  1016. 'comment_content',
  1017. 'comment_date',
  1018. 'comment_date_gmt',
  1019. 'comment_ID',
  1020. 'comment_karma',
  1021. 'comment_parent',
  1022. 'comment_post_ID',
  1023. 'comment_type',
  1024. 'user_id',
  1025. );
  1026. if ( ! empty( $this->query_vars['meta_key'] ) ) {
  1027. $allowed_keys[] = $this->query_vars['meta_key'];
  1028. $allowed_keys[] = 'meta_value';
  1029. $allowed_keys[] = 'meta_value_num';
  1030. }
  1031. $meta_query_clauses = $this->meta_query->get_clauses();
  1032. if ( $meta_query_clauses ) {
  1033. $allowed_keys = array_merge( $allowed_keys, array_keys( $meta_query_clauses ) );
  1034. }
  1035. $parsed = false;
  1036. if ( $this->query_vars['meta_key'] === $orderby || 'meta_value' === $orderby ) {
  1037. $parsed = "$wpdb->commentmeta.meta_value";
  1038. } elseif ( 'meta_value_num' === $orderby ) {
  1039. $parsed = "$wpdb->commentmeta.meta_value+0";
  1040. } elseif ( 'comment__in' === $orderby ) {
  1041. $comment__in = implode( ',', array_map( 'absint', $this->query_vars['comment__in'] ) );
  1042. $parsed = "FIELD( {$wpdb->comments}.comment_ID, $comment__in )";
  1043. } elseif ( in_array( $orderby, $allowed_keys, true ) ) {
  1044. if ( isset( $meta_query_clauses[ $orderby ] ) ) {
  1045. $meta_clause = $meta_query_clauses[ $orderby ];
  1046. $parsed = sprintf( 'CAST(%s.meta_value AS %s)', esc_sql( $meta_clause['alias'] ), esc_sql( $meta_clause['cast'] ) );
  1047. } else {
  1048. $parsed = "$wpdb->comments.$orderby";
  1049. }
  1050. }
  1051. return $parsed;
  1052. }
  1053. /**
  1054. * Parse an 'order' query variable and cast it to ASC or DESC as necessary.
  1055. *
  1056. * @since 4.2.0
  1057. *
  1058. * @param string $order The 'order' query variable.
  1059. * @return string The sanitized 'order' query variable.
  1060. */
  1061. protected function parse_order( $order ) {
  1062. if ( ! is_string( $order ) || empty( $order ) ) {
  1063. return 'DESC';
  1064. }
  1065. if ( 'ASC' === strtoupper( $order ) ) {
  1066. return 'ASC';
  1067. } else {
  1068. return 'DESC';
  1069. }
  1070. }
  1071. }