Brak opisu

class-wp-comment-query.php 47KB

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. class WP_Comment_Query {
  17. /**
  18. * SQL for database query.
  19. *
  20. * @since 4.0.1
  21. * @var string
  22. */
  23. public $request;
  24. /**
  25. * Metadata query container
  26. *
  27. * @since 3.5.0
  28. * @var WP_Meta_Query A meta query instance.
  29. */
  30. public $meta_query = false;
  31. /**
  32. * Metadata query clauses.
  33. *
  34. * @since 4.4.0
  35. * @var array
  36. */
  37. protected $meta_query_clauses;
  38. /**
  39. * SQL query clauses.
  40. *
  41. * @since 4.4.0
  42. * @var array
  43. */
  44. protected $sql_clauses = array(
  45. 'select' => '',
  46. 'from' => '',
  47. 'where' => array(),
  48. 'groupby' => '',
  49. 'orderby' => '',
  50. 'limits' => '',
  51. );
  52. /**
  53. * SQL WHERE clause.
  54. *
  55. * Stored after the {@see 'comments_clauses'} filter is run on the compiled WHERE sub-clauses.
  56. *
  57. * @since 4.4.2
  58. * @var string
  59. */
  60. protected $filtered_where_clause;
  61. /**
  62. * Date query container
  63. *
  64. * @since 3.7.0
  65. * @var WP_Date_Query A date query instance.
  66. */
  67. public $date_query = false;
  68. /**
  69. * Query vars set by the user.
  70. *
  71. * @since 3.1.0
  72. * @var array
  73. */
  74. public $query_vars;
  75. /**
  76. * Default values for query vars.
  77. *
  78. * @since 4.2.0
  79. * @var array
  80. */
  81. public $query_var_defaults;
  82. /**
  83. * List of comments located by the query.
  84. *
  85. * @since 4.0.0
  86. * @var int[]|WP_Comment[]
  87. */
  88. public $comments;
  89. /**
  90. * The amount of found comments for the current query.
  91. *
  92. * @since 4.4.0
  93. * @var int
  94. */
  95. public $found_comments = 0;
  96. /**
  97. * The number of pages.
  98. *
  99. * @since 4.4.0
  100. * @var int
  101. */
  102. public $max_num_pages = 0;
  103. /**
  104. * Make private/protected methods readable for backward compatibility.
  105. *
  106. * @since 4.0.0
  107. *
  108. * @param string $name Method to call.
  109. * @param array $arguments Arguments to pass when calling.
  110. * @return mixed|false Return value of the callback, false otherwise.
  111. */
  112. public function __call( $name, $arguments ) {
  113. if ( 'get_search_sql' === $name ) {
  114. return $this->get_search_sql( ...$arguments );
  115. }
  116. return false;
  117. }
  118. /**
  119. * Constructor.
  120. *
  121. * Sets up the comment query, based on the query vars passed.
  122. *
  123. * @since 4.2.0
  124. * @since 4.4.0 `$parent__in` and `$parent__not_in` were added.
  125. * @since 4.4.0 Order by `comment__in` was added. `$update_comment_meta_cache`, `$no_found_rows`,
  126. * `$hierarchical`, and `$update_comment_post_cache` were added.
  127. * @since 4.5.0 Introduced the `$author_url` argument.
  128. * @since 4.6.0 Introduced the `$cache_domain` argument.
  129. * @since 4.9.0 Introduced the `$paged` argument.
  130. * @since 5.1.0 Introduced the `$meta_compare_key` argument.
  131. * @since 5.3.0 Introduced the `$meta_type_key` argument.
  132. *
  133. * @param string|array $query {
  134. * Optional. Array or query string of comment query parameters. Default empty.
  135. *
  136. * @type string $author_email Comment author email address. Default empty.
  137. * @type string $author_url Comment author URL. Default empty.
  138. * @type int[] $author__in Array of author IDs to include comments for. Default empty.
  139. * @type int[] $author__not_in Array of author IDs to exclude comments for. Default empty.
  140. * @type int[] $comment__in Array of comment IDs to include. Default empty.
  141. * @type int[] $comment__not_in Array of comment IDs to exclude. Default empty.
  142. * @type bool $count Whether to return a comment count (true) or array of
  143. * comment objects (false). Default false.
  144. * @type array $date_query Date query clauses to limit comments by. See WP_Date_Query.
  145. * Default null.
  146. * @type string $fields Comment fields to return. Accepts 'ids' for comment IDs
  147. * only or empty for all fields. Default empty.
  148. * @type int $ID Currently unused.
  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 Currently unused.
  213. * @type int $post_id Limit results to those affiliated with a given post ID.
  214. * Default 0.
  215. * @type int[] $post__in Array of post IDs to include affiliated comments for.
  216. * Default empty.
  217. * @type int[] $post__not_in Array of post IDs to exclude affiliated comments for.
  218. * Default empty.
  219. * @type int $post_author Post author ID to limit results by. Default empty.
  220. * @type string|string[] $post_status Post status or array of post statuses to retrieve
  221. * affiliated comments for. Pass 'any' to match any value.
  222. * Default empty.
  223. * @type string|string[] $post_type Post type or array of post types to retrieve affiliated
  224. * comments for. Pass 'any' to match any value. Default empty.
  225. * @type string $post_name Post name to retrieve affiliated comments for.
  226. * Default empty.
  227. * @type int $post_parent Post parent ID to retrieve affiliated comments for.
  228. * Default empty.
  229. * @type string $search Search term(s) to retrieve matching comments for.
  230. * Default empty.
  231. * @type string|array $status Comment statuses to limit results by. Accepts an array
  232. * or space/comma-separated list of 'hold' (`comment_status=0`),
  233. * 'approve' (`comment_status=1`), 'all', or a custom
  234. * comment status. Default 'all'.
  235. * @type string|string[] $type Include comments of a given type, or array of types.
  236. * Accepts 'comment', 'pings' (includes 'pingback' and
  237. * 'trackback'), or any custom type string. Default empty.
  238. * @type string[] $type__in Include comments from a given array of comment types.
  239. * Default empty.
  240. * @type string[] $type__not_in Exclude comments from a given array of comment types.
  241. * Default empty.
  242. * @type int $user_id Include comments for a specific user ID. Default empty.
  243. * @type bool|string $hierarchical Whether to include comment descendants in the results.
  244. * - 'threaded' returns a tree, with each comment's children
  245. * stored in a `children` property on the `WP_Comment` object.
  246. * - 'flat' returns a flat array of found comments plus
  247. * their children.
  248. * - Boolean `false` leaves out descendants.
  249. * The parameter is ignored (forced to `false`) when
  250. * `$fields` is 'ids' or 'counts'. Accepts 'threaded',
  251. * 'flat', or false. Default: false.
  252. * @type string $cache_domain Unique cache key to be produced when this query is stored in
  253. * an object cache. Default is 'core'.
  254. * @type bool $update_comment_meta_cache Whether to prime the metadata cache for found comments.
  255. * Default true.
  256. * @type bool $update_comment_post_cache Whether to prime the cache for comment posts.
  257. * Default false.
  258. * }
  259. */
  260. public function __construct( $query = '' ) {
  261. $this->query_var_defaults = array(
  262. 'author_email' => '',
  263. 'author_url' => '',
  264. 'author__in' => '',
  265. 'author__not_in' => '',
  266. 'include_unapproved' => '',
  267. 'fields' => '',
  268. 'ID' => '',
  269. 'comment__in' => '',
  270. 'comment__not_in' => '',
  271. 'karma' => '',
  272. 'number' => '',
  273. 'offset' => '',
  274. 'no_found_rows' => true,
  275. 'orderby' => '',
  276. 'order' => 'DESC',
  277. 'paged' => 1,
  278. 'parent' => '',
  279. 'parent__in' => '',
  280. 'parent__not_in' => '',
  281. 'post_author__in' => '',
  282. 'post_author__not_in' => '',
  283. 'post_ID' => '',
  284. 'post_id' => 0,
  285. 'post__in' => '',
  286. 'post__not_in' => '',
  287. 'post_author' => '',
  288. 'post_name' => '',
  289. 'post_parent' => '',
  290. 'post_status' => '',
  291. 'post_type' => '',
  292. 'status' => 'all',
  293. 'type' => '',
  294. 'type__in' => '',
  295. 'type__not_in' => '',
  296. 'user_id' => '',
  297. 'search' => '',
  298. 'count' => false,
  299. 'meta_key' => '',
  300. 'meta_value' => '',
  301. 'meta_query' => '',
  302. 'date_query' => null, // See WP_Date_Query.
  303. 'hierarchical' => false,
  304. 'cache_domain' => 'core',
  305. 'update_comment_meta_cache' => true,
  306. 'update_comment_post_cache' => false,
  307. );
  308. if ( ! empty( $query ) ) {
  309. $this->query( $query );
  310. }
  311. }
  312. /**
  313. * Parse arguments passed to the comment query with default query parameters.
  314. *
  315. * @since 4.2.0 Extracted from WP_Comment_Query::query().
  316. *
  317. * @param string|array $query WP_Comment_Query arguments. See WP_Comment_Query::__construct()
  318. */
  319. public function parse_query( $query = '' ) {
  320. if ( empty( $query ) ) {
  321. $query = $this->query_vars;
  322. }
  323. $this->query_vars = wp_parse_args( $query, $this->query_var_defaults );
  324. /**
  325. * Fires after the comment query vars have been parsed.
  326. *
  327. * @since 4.2.0
  328. *
  329. * @param WP_Comment_Query $query The WP_Comment_Query instance (passed by reference).
  330. */
  331. do_action_ref_array( 'parse_comment_query', array( &$this ) );
  332. }
  333. /**
  334. * Sets up the WordPress query for retrieving comments.
  335. *
  336. * @since 3.1.0
  337. * @since 4.1.0 Introduced 'comment__in', 'comment__not_in', 'post_author__in',
  338. * 'post_author__not_in', 'author__in', 'author__not_in', 'post__in',
  339. * 'post__not_in', 'include_unapproved', 'type__in', and 'type__not_in'
  340. * arguments to $query_vars.
  341. * @since 4.2.0 Moved parsing to WP_Comment_Query::parse_query().
  342. *
  343. * @param string|array $query Array or URL query string of parameters.
  344. * @return array|int List of comments, or number of comments when 'count' is passed as a query var.
  345. */
  346. public function query( $query ) {
  347. $this->query_vars = wp_parse_args( $query );
  348. return $this->get_comments();
  349. }
  350. /**
  351. * Get a list of comments matching the query vars.
  352. *
  353. * @since 4.2.0
  354. *
  355. * @global wpdb $wpdb WordPress database abstraction object.
  356. *
  357. * @return int|int[]|WP_Comment[] List of comments or number of found comments if `$count` argument is true.
  358. */
  359. public function get_comments() {
  360. global $wpdb;
  361. $this->parse_query();
  362. // Parse meta query.
  363. $this->meta_query = new WP_Meta_Query();
  364. $this->meta_query->parse_query_vars( $this->query_vars );
  365. /**
  366. * Fires before comments are retrieved.
  367. *
  368. * @since 3.1.0
  369. *
  370. * @param WP_Comment_Query $query Current instance of WP_Comment_Query (passed by reference).
  371. */
  372. do_action_ref_array( 'pre_get_comments', array( &$this ) );
  373. // Reparse query vars, in case they were modified in a 'pre_get_comments' callback.
  374. $this->meta_query->parse_query_vars( $this->query_vars );
  375. if ( ! empty( $this->meta_query->queries ) ) {
  376. $this->meta_query_clauses = $this->meta_query->get_sql( 'comment', $wpdb->comments, 'comment_ID', $this );
  377. }
  378. $comment_data = null;
  379. /**
  380. * Filters the comments data before the query takes place.
  381. *
  382. * Return a non-null value to bypass WordPress' default comment queries.
  383. *
  384. * The expected return type from this filter depends on the value passed
  385. * in the request query vars:
  386. * - When `$this->query_vars['count']` is set, the filter should return
  387. * the comment count as an integer.
  388. * - When `'ids' === $this->query_vars['fields']`, the filter should return
  389. * an array of comment IDs.
  390. * - Otherwise the filter should return an array of WP_Comment objects.
  391. *
  392. * Note that if the filter returns an array of comment data, it will be assigned
  393. * to the `comments` property of the current WP_Comment_Query instance.
  394. *
  395. * Filtering functions that require pagination information are encouraged to set
  396. * the `found_comments` and `max_num_pages` properties of the WP_Comment_Query object,
  397. * passed to the filter by reference. If WP_Comment_Query does not perform a database
  398. * query, it will not have enough information to generate these values itself.
  399. *
  400. * @since 5.3.0
  401. * @since 5.6.0 The returned array of comment data is assigned to the `comments` property
  402. * of the current WP_Comment_Query instance.
  403. *
  404. * @param array|int|null $comment_data Return an array of comment data to short-circuit WP's comment query,
  405. * the comment count as an integer if `$this->query_vars['count']` is set,
  406. * or null to allow WP to run its normal queries.
  407. * @param WP_Comment_Query $query The WP_Comment_Query instance, passed by reference.
  408. */
  409. $comment_data = apply_filters_ref_array( 'comments_pre_query', array( $comment_data, &$this ) );
  410. if ( null !== $comment_data ) {
  411. if ( is_array( $comment_data ) && ! $this->query_vars['count'] ) {
  412. $this->comments = $comment_data;
  413. }
  414. return $comment_data;
  415. }
  416. /*
  417. * Only use the args defined in the query_var_defaults to compute the key,
  418. * but ignore 'fields', 'update_comment_meta_cache', 'update_comment_post_cache' which does not affect query results.
  419. */
  420. $_args = wp_array_slice_assoc( $this->query_vars, array_keys( $this->query_var_defaults ) );
  421. unset( $_args['fields'], $_args['update_comment_meta_cache'], $_args['update_comment_post_cache'] );
  422. $key = md5( serialize( $_args ) );
  423. $last_changed = wp_cache_get_last_changed( 'comment' );
  424. $cache_key = "get_comments:$key:$last_changed";
  425. $cache_value = wp_cache_get( $cache_key, 'comment' );
  426. if ( false === $cache_value ) {
  427. $comment_ids = $this->get_comment_ids();
  428. if ( $comment_ids ) {
  429. $this->set_found_comments();
  430. }
  431. $cache_value = array(
  432. 'comment_ids' => $comment_ids,
  433. 'found_comments' => $this->found_comments,
  434. );
  435. wp_cache_add( $cache_key, $cache_value, 'comment' );
  436. } else {
  437. $comment_ids = $cache_value['comment_ids'];
  438. $this->found_comments = $cache_value['found_comments'];
  439. }
  440. if ( $this->found_comments && $this->query_vars['number'] ) {
  441. $this->max_num_pages = ceil( $this->found_comments / $this->query_vars['number'] );
  442. }
  443. // If querying for a count only, there's nothing more to do.
  444. if ( $this->query_vars['count'] ) {
  445. // $comment_ids is actually a count in this case.
  446. return (int) $comment_ids;
  447. }
  448. $comment_ids = array_map( 'intval', $comment_ids );
  449. if ( 'ids' === $this->query_vars['fields'] ) {
  450. $this->comments = $comment_ids;
  451. return $this->comments;
  452. }
  453. _prime_comment_caches( $comment_ids, $this->query_vars['update_comment_meta_cache'] );
  454. // Fetch full comment objects from the primed cache.
  455. $_comments = array();
  456. foreach ( $comment_ids as $comment_id ) {
  457. $_comment = get_comment( $comment_id );
  458. if ( $_comment ) {
  459. $_comments[] = $_comment;
  460. }
  461. }
  462. // Prime comment post caches.
  463. if ( $this->query_vars['update_comment_post_cache'] ) {
  464. $comment_post_ids = array();
  465. foreach ( $_comments as $_comment ) {
  466. $comment_post_ids[] = $_comment->comment_post_ID;
  467. }
  468. _prime_post_caches( $comment_post_ids, false, false );
  469. }
  470. /**
  471. * Filters the comment query results.
  472. *
  473. * @since 3.1.0
  474. *
  475. * @param WP_Comment[] $_comments An array of comments.
  476. * @param WP_Comment_Query $query Current instance of WP_Comment_Query (passed by reference).
  477. */
  478. $_comments = apply_filters_ref_array( 'the_comments', array( $_comments, &$this ) );
  479. // Convert to WP_Comment instances.
  480. $comments = array_map( 'get_comment', $_comments );
  481. if ( $this->query_vars['hierarchical'] ) {
  482. $comments = $this->fill_descendants( $comments );
  483. }
  484. $this->comments = $comments;
  485. return $this->comments;
  486. }
  487. /**
  488. * Used internally to get a list of comment IDs matching the query vars.
  489. *
  490. * @since 4.4.0
  491. *
  492. * @global wpdb $wpdb WordPress database abstraction object.
  493. *
  494. * @return int|array A single count of comment IDs if a count query. An array of comment IDs if a full query.
  495. */
  496. protected function get_comment_ids() {
  497. global $wpdb;
  498. // Assemble clauses related to 'comment_approved'.
  499. $approved_clauses = array();
  500. // 'status' accepts an array or a comma-separated string.
  501. $status_clauses = array();
  502. $statuses = wp_parse_list( $this->query_vars['status'] );
  503. // Empty 'status' should be interpreted as 'all'.
  504. if ( empty( $statuses ) ) {
  505. $statuses = array( 'all' );
  506. }
  507. // 'any' overrides other statuses.
  508. if ( ! in_array( 'any', $statuses, true ) ) {
  509. foreach ( $statuses as $status ) {
  510. switch ( $status ) {
  511. case 'hold':
  512. $status_clauses[] = "comment_approved = '0'";
  513. break;
  514. case 'approve':
  515. $status_clauses[] = "comment_approved = '1'";
  516. break;
  517. case 'all':
  518. case '':
  519. $status_clauses[] = "( comment_approved = '0' OR comment_approved = '1' )";
  520. break;
  521. default:
  522. $status_clauses[] = $wpdb->prepare( 'comment_approved = %s', $status );
  523. break;
  524. }
  525. }
  526. if ( ! empty( $status_clauses ) ) {
  527. $approved_clauses[] = '( ' . implode( ' OR ', $status_clauses ) . ' )';
  528. }
  529. }
  530. // User IDs or emails whose unapproved comments are included, regardless of $status.
  531. if ( ! empty( $this->query_vars['include_unapproved'] ) ) {
  532. $include_unapproved = wp_parse_list( $this->query_vars['include_unapproved'] );
  533. $unapproved_ids = array();
  534. $unapproved_emails = array();
  535. foreach ( $include_unapproved as $unapproved_identifier ) {
  536. // Numeric values are assumed to be user IDs.
  537. if ( is_numeric( $unapproved_identifier ) ) {
  538. $approved_clauses[] = $wpdb->prepare( "( user_id = %d AND comment_approved = '0' )", $unapproved_identifier );
  539. } else {
  540. // Otherwise we match against email addresses.
  541. if ( ! empty( $_GET['unapproved'] ) && ! empty( $_GET['moderation-hash'] ) ) {
  542. // Only include requested comment.
  543. $approved_clauses[] = $wpdb->prepare( "( comment_author_email = %s AND comment_approved = '0' AND {$wpdb->comments}.comment_ID = %d )", $unapproved_identifier, (int) $_GET['unapproved'] );
  544. } else {
  545. // Include all of the author's unapproved comments.
  546. $approved_clauses[] = $wpdb->prepare( "( comment_author_email = %s AND comment_approved = '0' )", $unapproved_identifier );
  547. }
  548. }
  549. }
  550. }
  551. // Collapse comment_approved clauses into a single OR-separated clause.
  552. if ( ! empty( $approved_clauses ) ) {
  553. if ( 1 === count( $approved_clauses ) ) {
  554. $this->sql_clauses['where']['approved'] = $approved_clauses[0];
  555. } else {
  556. $this->sql_clauses['where']['approved'] = '( ' . implode( ' OR ', $approved_clauses ) . ' )';
  557. }
  558. }
  559. $order = ( 'ASC' === strtoupper( $this->query_vars['order'] ) ) ? 'ASC' : 'DESC';
  560. // Disable ORDER BY with 'none', an empty array, or boolean false.
  561. if ( in_array( $this->query_vars['orderby'], array( 'none', array(), false ), true ) ) {
  562. $orderby = '';
  563. } elseif ( ! empty( $this->query_vars['orderby'] ) ) {
  564. $ordersby = is_array( $this->query_vars['orderby'] ) ?
  565. $this->query_vars['orderby'] :
  566. preg_split( '/[,\s]/', $this->query_vars['orderby'] );
  567. $orderby_array = array();
  568. $found_orderby_comment_id = false;
  569. foreach ( $ordersby as $_key => $_value ) {
  570. if ( ! $_value ) {
  571. continue;
  572. }
  573. if ( is_int( $_key ) ) {
  574. $_orderby = $_value;
  575. $_order = $order;
  576. } else {
  577. $_orderby = $_key;
  578. $_order = $_value;
  579. }
  580. if ( ! $found_orderby_comment_id && in_array( $_orderby, array( 'comment_ID', 'comment__in' ), true ) ) {
  581. $found_orderby_comment_id = true;
  582. }
  583. $parsed = $this->parse_orderby( $_orderby );
  584. if ( ! $parsed ) {
  585. continue;
  586. }
  587. if ( 'comment__in' === $_orderby ) {
  588. $orderby_array[] = $parsed;
  589. continue;
  590. }
  591. $orderby_array[] = $parsed . ' ' . $this->parse_order( $_order );
  592. }
  593. // If no valid clauses were found, order by comment_date_gmt.
  594. if ( empty( $orderby_array ) ) {
  595. $orderby_array[] = "$wpdb->comments.comment_date_gmt $order";
  596. }
  597. // To ensure determinate sorting, always include a comment_ID clause.
  598. if ( ! $found_orderby_comment_id ) {
  599. $comment_id_order = '';
  600. // Inherit order from comment_date or comment_date_gmt, if available.
  601. foreach ( $orderby_array as $orderby_clause ) {
  602. if ( preg_match( '/comment_date(?:_gmt)*\ (ASC|DESC)/', $orderby_clause, $match ) ) {
  603. $comment_id_order = $match[1];
  604. break;
  605. }
  606. }
  607. // If no date-related order is available, use the date from the first available clause.
  608. if ( ! $comment_id_order ) {
  609. foreach ( $orderby_array as $orderby_clause ) {
  610. if ( false !== strpos( 'ASC', $orderby_clause ) ) {
  611. $comment_id_order = 'ASC';
  612. } else {
  613. $comment_id_order = 'DESC';
  614. }
  615. break;
  616. }
  617. }
  618. // Default to DESC.
  619. if ( ! $comment_id_order ) {
  620. $comment_id_order = 'DESC';
  621. }
  622. $orderby_array[] = "$wpdb->comments.comment_ID $comment_id_order";
  623. }
  624. $orderby = implode( ', ', $orderby_array );
  625. } else {
  626. $orderby = "$wpdb->comments.comment_date_gmt $order";
  627. }
  628. $number = absint( $this->query_vars['number'] );
  629. $offset = absint( $this->query_vars['offset'] );
  630. $paged = absint( $this->query_vars['paged'] );
  631. $limits = '';
  632. if ( ! empty( $number ) ) {
  633. if ( $offset ) {
  634. $limits = 'LIMIT ' . $offset . ',' . $number;
  635. } else {
  636. $limits = 'LIMIT ' . ( $number * ( $paged - 1 ) ) . ',' . $number;
  637. }
  638. }
  639. if ( $this->query_vars['count'] ) {
  640. $fields = 'COUNT(*)';
  641. } else {
  642. $fields = "$wpdb->comments.comment_ID";
  643. }
  644. $post_id = absint( $this->query_vars['post_id'] );
  645. if ( ! empty( $post_id ) ) {
  646. $this->sql_clauses['where']['post_id'] = $wpdb->prepare( 'comment_post_ID = %d', $post_id );
  647. }
  648. // Parse comment IDs for an IN clause.
  649. if ( ! empty( $this->query_vars['comment__in'] ) ) {
  650. $this->sql_clauses['where']['comment__in'] = "$wpdb->comments.comment_ID IN ( " . implode( ',', wp_parse_id_list( $this->query_vars['comment__in'] ) ) . ' )';
  651. }
  652. // Parse comment IDs for a NOT IN clause.
  653. if ( ! empty( $this->query_vars['comment__not_in'] ) ) {
  654. $this->sql_clauses['where']['comment__not_in'] = "$wpdb->comments.comment_ID NOT IN ( " . implode( ',', wp_parse_id_list( $this->query_vars['comment__not_in'] ) ) . ' )';
  655. }
  656. // Parse comment parent IDs for an IN clause.
  657. if ( ! empty( $this->query_vars['parent__in'] ) ) {
  658. $this->sql_clauses['where']['parent__in'] = 'comment_parent IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['parent__in'] ) ) . ' )';
  659. }
  660. // Parse comment parent IDs for a NOT IN clause.
  661. if ( ! empty( $this->query_vars['parent__not_in'] ) ) {
  662. $this->sql_clauses['where']['parent__not_in'] = 'comment_parent NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['parent__not_in'] ) ) . ' )';
  663. }
  664. // Parse comment post IDs for an IN clause.
  665. if ( ! empty( $this->query_vars['post__in'] ) ) {
  666. $this->sql_clauses['where']['post__in'] = 'comment_post_ID IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post__in'] ) ) . ' )';
  667. }
  668. // Parse comment post IDs for a NOT IN clause.
  669. if ( ! empty( $this->query_vars['post__not_in'] ) ) {
  670. $this->sql_clauses['where']['post__not_in'] = 'comment_post_ID NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post__not_in'] ) ) . ' )';
  671. }
  672. if ( '' !== $this->query_vars['author_email'] ) {
  673. $this->sql_clauses['where']['author_email'] = $wpdb->prepare( 'comment_author_email = %s', $this->query_vars['author_email'] );
  674. }
  675. if ( '' !== $this->query_vars['author_url'] ) {
  676. $this->sql_clauses['where']['author_url'] = $wpdb->prepare( 'comment_author_url = %s', $this->query_vars['author_url'] );
  677. }
  678. if ( '' !== $this->query_vars['karma'] ) {
  679. $this->sql_clauses['where']['karma'] = $wpdb->prepare( 'comment_karma = %d', $this->query_vars['karma'] );
  680. }
  681. // Filtering by comment_type: 'type', 'type__in', 'type__not_in'.
  682. $raw_types = array(
  683. 'IN' => array_merge( (array) $this->query_vars['type'], (array) $this->query_vars['type__in'] ),
  684. 'NOT IN' => (array) $this->query_vars['type__not_in'],
  685. );
  686. $comment_types = array();
  687. foreach ( $raw_types as $operator => $_raw_types ) {
  688. $_raw_types = array_unique( $_raw_types );
  689. foreach ( $_raw_types as $type ) {
  690. switch ( $type ) {
  691. // An empty translates to 'all', for backward compatibility.
  692. case '':
  693. case 'all':
  694. break;
  695. case 'comment':
  696. case 'comments':
  697. $comment_types[ $operator ][] = "''";
  698. $comment_types[ $operator ][] = "'comment'";
  699. break;
  700. case 'pings':
  701. $comment_types[ $operator ][] = "'pingback'";
  702. $comment_types[ $operator ][] = "'trackback'";
  703. break;
  704. default:
  705. $comment_types[ $operator ][] = $wpdb->prepare( '%s', $type );
  706. break;
  707. }
  708. }
  709. if ( ! empty( $comment_types[ $operator ] ) ) {
  710. $types_sql = implode( ', ', $comment_types[ $operator ] );
  711. $this->sql_clauses['where'][ 'comment_type__' . strtolower( str_replace( ' ', '_', $operator ) ) ] = "comment_type $operator ($types_sql)";
  712. }
  713. }
  714. $parent = $this->query_vars['parent'];
  715. if ( $this->query_vars['hierarchical'] && ! $parent ) {
  716. $parent = 0;
  717. }
  718. if ( '' !== $parent ) {
  719. $this->sql_clauses['where']['parent'] = $wpdb->prepare( 'comment_parent = %d', $parent );
  720. }
  721. if ( is_array( $this->query_vars['user_id'] ) ) {
  722. $this->sql_clauses['where']['user_id'] = 'user_id IN (' . implode( ',', array_map( 'absint', $this->query_vars['user_id'] ) ) . ')';
  723. } elseif ( '' !== $this->query_vars['user_id'] ) {
  724. $this->sql_clauses['where']['user_id'] = $wpdb->prepare( 'user_id = %d', $this->query_vars['user_id'] );
  725. }
  726. // Falsey search strings are ignored.
  727. if ( isset( $this->query_vars['search'] ) && strlen( $this->query_vars['search'] ) ) {
  728. $search_sql = $this->get_search_sql(
  729. $this->query_vars['search'],
  730. array( 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_author_IP', 'comment_content' )
  731. );
  732. // Strip leading 'AND'.
  733. $this->sql_clauses['where']['search'] = preg_replace( '/^\s*AND\s*/', '', $search_sql );
  734. }
  735. // If any post-related query vars are passed, join the posts table.
  736. $join_posts_table = false;
  737. $plucked = wp_array_slice_assoc( $this->query_vars, array( 'post_author', 'post_name', 'post_parent' ) );
  738. $post_fields = array_filter( $plucked );
  739. if ( ! empty( $post_fields ) ) {
  740. $join_posts_table = true;
  741. foreach ( $post_fields as $field_name => $field_value ) {
  742. // $field_value may be an array.
  743. $esses = array_fill( 0, count( (array) $field_value ), '%s' );
  744. // phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
  745. $this->sql_clauses['where'][ $field_name ] = $wpdb->prepare( " {$wpdb->posts}.{$field_name} IN (" . implode( ',', $esses ) . ')', $field_value );
  746. }
  747. }
  748. // 'post_status' and 'post_type' are handled separately, due to the specialized behavior of 'any'.
  749. foreach ( array( 'post_status', 'post_type' ) as $field_name ) {
  750. $q_values = array();
  751. if ( ! empty( $this->query_vars[ $field_name ] ) ) {
  752. $q_values = $this->query_vars[ $field_name ];
  753. if ( ! is_array( $q_values ) ) {
  754. $q_values = explode( ',', $q_values );
  755. }
  756. // 'any' will cause the query var to be ignored.
  757. if ( in_array( 'any', $q_values, true ) || empty( $q_values ) ) {
  758. continue;
  759. }
  760. $join_posts_table = true;
  761. $esses = array_fill( 0, count( $q_values ), '%s' );
  762. // phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
  763. $this->sql_clauses['where'][ $field_name ] = $wpdb->prepare( " {$wpdb->posts}.{$field_name} IN (" . implode( ',', $esses ) . ')', $q_values );
  764. }
  765. }
  766. // Comment author IDs for an IN clause.
  767. if ( ! empty( $this->query_vars['author__in'] ) ) {
  768. $this->sql_clauses['where']['author__in'] = 'user_id IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['author__in'] ) ) . ' )';
  769. }
  770. // Comment author IDs for a NOT IN clause.
  771. if ( ! empty( $this->query_vars['author__not_in'] ) ) {
  772. $this->sql_clauses['where']['author__not_in'] = 'user_id NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['author__not_in'] ) ) . ' )';
  773. }
  774. // Post author IDs for an IN clause.
  775. if ( ! empty( $this->query_vars['post_author__in'] ) ) {
  776. $join_posts_table = true;
  777. $this->sql_clauses['where']['post_author__in'] = 'post_author IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post_author__in'] ) ) . ' )';
  778. }
  779. // Post author IDs for a NOT IN clause.
  780. if ( ! empty( $this->query_vars['post_author__not_in'] ) ) {
  781. $join_posts_table = true;
  782. $this->sql_clauses['where']['post_author__not_in'] = 'post_author NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post_author__not_in'] ) ) . ' )';
  783. }
  784. $join = '';
  785. $groupby = '';
  786. if ( $join_posts_table ) {
  787. $join .= "JOIN $wpdb->posts ON $wpdb->posts.ID = $wpdb->comments.comment_post_ID";
  788. }
  789. if ( ! empty( $this->meta_query_clauses ) ) {
  790. $join .= $this->meta_query_clauses['join'];
  791. // Strip leading 'AND'.
  792. $this->sql_clauses['where']['meta_query'] = preg_replace( '/^\s*AND\s*/', '', $this->meta_query_clauses['where'] );
  793. if ( ! $this->query_vars['count'] ) {
  794. $groupby = "{$wpdb->comments}.comment_ID";
  795. }
  796. }
  797. if ( ! empty( $this->query_vars['date_query'] ) && is_array( $this->query_vars['date_query'] ) ) {
  798. $this->date_query = new WP_Date_Query( $this->query_vars['date_query'], 'comment_date' );
  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. $clauses = 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( $clauses ), &$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. }