Nenhuma Descrição

class-wc-comments.php 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. <?php
  2. /**
  3. * Comments
  4. *
  5. * Handle comments (reviews and order notes).
  6. *
  7. * @package WooCommerce\Classes\Products
  8. * @version 2.3.0
  9. */
  10. defined( 'ABSPATH' ) || exit;
  11. /**
  12. * Comments class.
  13. */
  14. class WC_Comments {
  15. /**
  16. * Hook in methods.
  17. */
  18. public static function init() {
  19. // Rating posts.
  20. add_filter( 'comments_open', array( __CLASS__, 'comments_open' ), 10, 2 );
  21. add_filter( 'preprocess_comment', array( __CLASS__, 'check_comment_rating' ), 0 );
  22. add_action( 'comment_post', array( __CLASS__, 'add_comment_rating' ), 1 );
  23. add_action( 'comment_moderation_recipients', array( __CLASS__, 'comment_moderation_recipients' ), 10, 2 );
  24. // Clear transients.
  25. add_action( 'wp_update_comment_count', array( __CLASS__, 'clear_transients' ) );
  26. // Secure order notes.
  27. add_filter( 'comments_clauses', array( __CLASS__, 'exclude_order_comments' ), 10, 1 );
  28. add_filter( 'comment_feed_where', array( __CLASS__, 'exclude_order_comments_from_feed_where' ) );
  29. // Secure webhook comments.
  30. add_filter( 'comments_clauses', array( __CLASS__, 'exclude_webhook_comments' ), 10, 1 );
  31. add_filter( 'comment_feed_where', array( __CLASS__, 'exclude_webhook_comments_from_feed_where' ) );
  32. // Count comments.
  33. add_filter( 'wp_count_comments', array( __CLASS__, 'wp_count_comments' ), 10, 2 );
  34. // Delete comments count cache whenever there is a new comment or a comment status changes.
  35. add_action( 'wp_insert_comment', array( __CLASS__, 'delete_comments_count_cache' ) );
  36. add_action( 'wp_set_comment_status', array( __CLASS__, 'delete_comments_count_cache' ) );
  37. // Support avatars for `review` comment type.
  38. add_filter( 'get_avatar_comment_types', array( __CLASS__, 'add_avatar_for_review_comment_type' ) );
  39. // Review of verified purchase.
  40. add_action( 'comment_post', array( __CLASS__, 'add_comment_purchase_verification' ) );
  41. // Set comment type.
  42. add_action( 'preprocess_comment', array( __CLASS__, 'update_comment_type' ), 1 );
  43. // Validate product reviews if requires verified owners.
  44. add_action( 'pre_comment_on_post', array( __CLASS__, 'validate_product_review_verified_owners' ) );
  45. }
  46. /**
  47. * See if comments are open.
  48. *
  49. * @since 3.1.0
  50. * @param bool $open Whether the current post is open for comments.
  51. * @param int $post_id Post ID.
  52. * @return bool
  53. */
  54. public static function comments_open( $open, $post_id ) {
  55. if ( 'product' === get_post_type( $post_id ) && ! post_type_supports( 'product', 'comments' ) ) {
  56. $open = false;
  57. }
  58. return $open;
  59. }
  60. /**
  61. * Exclude order comments from queries and RSS.
  62. *
  63. * This code should exclude shop_order comments from queries. Some queries (like the recent comments widget on the dashboard) are hardcoded.
  64. * and are not filtered, however, the code current_user_can( 'read_post', $comment->comment_post_ID ) should keep them safe since only admin and.
  65. * shop managers can view orders anyway.
  66. *
  67. * The frontend view order pages get around this filter by using remove_filter('comments_clauses', array( 'WC_Comments' ,'exclude_order_comments'), 10, 1 );
  68. *
  69. * @param array $clauses A compacted array of comment query clauses.
  70. * @return array
  71. */
  72. public static function exclude_order_comments( $clauses ) {
  73. $clauses['where'] .= ( $clauses['where'] ? ' AND ' : '' ) . " comment_type != 'order_note' ";
  74. return $clauses;
  75. }
  76. /**
  77. * Exclude order comments from feed.
  78. *
  79. * @deprecated 3.1
  80. * @param mixed $join Deprecated.
  81. */
  82. public static function exclude_order_comments_from_feed_join( $join ) {
  83. wc_deprecated_function( 'WC_Comments::exclude_order_comments_from_feed_join', '3.1' );
  84. }
  85. /**
  86. * Exclude order comments from queries and RSS.
  87. *
  88. * @param string $where The WHERE clause of the query.
  89. * @return string
  90. */
  91. public static function exclude_order_comments_from_feed_where( $where ) {
  92. return $where . ( $where ? ' AND ' : '' ) . " comment_type != 'order_note' ";
  93. }
  94. /**
  95. * Exclude webhook comments from queries and RSS.
  96. *
  97. * @since 2.2
  98. * @param array $clauses A compacted array of comment query clauses.
  99. * @return array
  100. */
  101. public static function exclude_webhook_comments( $clauses ) {
  102. $clauses['where'] .= ( $clauses['where'] ? ' AND ' : '' ) . " comment_type != 'webhook_delivery' ";
  103. return $clauses;
  104. }
  105. /**
  106. * Exclude webhooks comments from feed.
  107. *
  108. * @deprecated 3.1
  109. * @param mixed $join Deprecated.
  110. */
  111. public static function exclude_webhook_comments_from_feed_join( $join ) {
  112. wc_deprecated_function( 'WC_Comments::exclude_webhook_comments_from_feed_join', '3.1' );
  113. }
  114. /**
  115. * Exclude webhook comments from queries and RSS.
  116. *
  117. * @since 2.1
  118. * @param string $where The WHERE clause of the query.
  119. * @return string
  120. */
  121. public static function exclude_webhook_comments_from_feed_where( $where ) {
  122. return $where . ( $where ? ' AND ' : '' ) . " comment_type != 'webhook_delivery' ";
  123. }
  124. /**
  125. * Validate the comment ratings.
  126. *
  127. * @param array $comment_data Comment data.
  128. * @return array
  129. */
  130. public static function check_comment_rating( $comment_data ) {
  131. // If posting a comment (not trackback etc) and not logged in.
  132. if ( ! is_admin() && isset( $_POST['comment_post_ID'], $_POST['rating'], $comment_data['comment_type'] ) && 'product' === get_post_type( absint( $_POST['comment_post_ID'] ) ) && empty( $_POST['rating'] ) && self::is_default_comment_type( $comment_data['comment_type'] ) && wc_review_ratings_enabled() && wc_review_ratings_required() ) { // WPCS: input var ok, CSRF ok.
  133. wp_die( esc_html__( 'Please rate the product.', 'woocommerce' ) );
  134. exit;
  135. }
  136. return $comment_data;
  137. }
  138. /**
  139. * Rating field for comments.
  140. *
  141. * @param int $comment_id Comment ID.
  142. */
  143. public static function add_comment_rating( $comment_id ) {
  144. if ( isset( $_POST['rating'], $_POST['comment_post_ID'] ) && 'product' === get_post_type( absint( $_POST['comment_post_ID'] ) ) ) { // WPCS: input var ok, CSRF ok.
  145. if ( ! $_POST['rating'] || $_POST['rating'] > 5 || $_POST['rating'] < 0 ) { // WPCS: input var ok, CSRF ok, sanitization ok.
  146. return;
  147. }
  148. add_comment_meta( $comment_id, 'rating', intval( $_POST['rating'] ), true ); // WPCS: input var ok, CSRF ok.
  149. $post_id = isset( $_POST['comment_post_ID'] ) ? absint( $_POST['comment_post_ID'] ) : 0; // WPCS: input var ok, CSRF ok.
  150. if ( $post_id ) {
  151. self::clear_transients( $post_id );
  152. }
  153. }
  154. }
  155. /**
  156. * Modify recipient of review email.
  157. *
  158. * @param array $emails Emails.
  159. * @param int $comment_id Comment ID.
  160. * @return array
  161. */
  162. public static function comment_moderation_recipients( $emails, $comment_id ) {
  163. $comment = get_comment( $comment_id );
  164. if ( $comment && 'product' === get_post_type( $comment->comment_post_ID ) ) {
  165. $emails = array( get_option( 'admin_email' ) );
  166. }
  167. return $emails;
  168. }
  169. /**
  170. * Ensure product average rating and review count is kept up to date.
  171. *
  172. * @param int $post_id Post ID.
  173. */
  174. public static function clear_transients( $post_id ) {
  175. if ( 'product' === get_post_type( $post_id ) ) {
  176. $product = wc_get_product( $post_id );
  177. $product->set_rating_counts( self::get_rating_counts_for_product( $product ) );
  178. $product->set_average_rating( self::get_average_rating_for_product( $product ) );
  179. $product->set_review_count( self::get_review_count_for_product( $product ) );
  180. $product->save();
  181. }
  182. }
  183. /**
  184. * Delete comments count cache whenever there is
  185. * new comment or the status of a comment changes. Cache
  186. * will be regenerated next time WC_Comments::wp_count_comments()
  187. * is called.
  188. */
  189. public static function delete_comments_count_cache() {
  190. delete_transient( 'wc_count_comments' );
  191. }
  192. /**
  193. * Remove order notes and webhook delivery logs from wp_count_comments().
  194. *
  195. * @since 2.2
  196. * @param object $stats Comment stats.
  197. * @param int $post_id Post ID.
  198. * @return object
  199. */
  200. public static function wp_count_comments( $stats, $post_id ) {
  201. global $wpdb;
  202. if ( 0 === $post_id ) {
  203. $stats = get_transient( 'wc_count_comments' );
  204. if ( ! $stats ) {
  205. $stats = array(
  206. 'total_comments' => 0,
  207. 'all' => 0,
  208. );
  209. $count = $wpdb->get_results(
  210. "
  211. SELECT comment_approved, COUNT(*) AS num_comments
  212. FROM {$wpdb->comments}
  213. WHERE comment_type NOT IN ('action_log', 'order_note', 'webhook_delivery')
  214. GROUP BY comment_approved
  215. ",
  216. ARRAY_A
  217. );
  218. $approved = array(
  219. '0' => 'moderated',
  220. '1' => 'approved',
  221. 'spam' => 'spam',
  222. 'trash' => 'trash',
  223. 'post-trashed' => 'post-trashed',
  224. );
  225. foreach ( (array) $count as $row ) {
  226. // Don't count post-trashed toward totals.
  227. if ( ! in_array( $row['comment_approved'], array( 'post-trashed', 'trash', 'spam' ), true ) ) {
  228. $stats['all'] += $row['num_comments'];
  229. $stats['total_comments'] += $row['num_comments'];
  230. } elseif ( ! in_array( $row['comment_approved'], array( 'post-trashed', 'trash' ), true ) ) {
  231. $stats['total_comments'] += $row['num_comments'];
  232. }
  233. if ( isset( $approved[ $row['comment_approved'] ] ) ) {
  234. $stats[ $approved[ $row['comment_approved'] ] ] = $row['num_comments'];
  235. }
  236. }
  237. foreach ( $approved as $key ) {
  238. if ( empty( $stats[ $key ] ) ) {
  239. $stats[ $key ] = 0;
  240. }
  241. }
  242. $stats = (object) $stats;
  243. set_transient( 'wc_count_comments', $stats );
  244. }
  245. }
  246. return $stats;
  247. }
  248. /**
  249. * Make sure WP displays avatars for comments with the `review` type.
  250. *
  251. * @since 2.3
  252. * @param array $comment_types Comment types.
  253. * @return array
  254. */
  255. public static function add_avatar_for_review_comment_type( $comment_types ) {
  256. return array_merge( $comment_types, array( 'review' ) );
  257. }
  258. /**
  259. * Determine if a review is from a verified owner at submission.
  260. *
  261. * @param int $comment_id Comment ID.
  262. * @return bool
  263. */
  264. public static function add_comment_purchase_verification( $comment_id ) {
  265. $comment = get_comment( $comment_id );
  266. $verified = false;
  267. if ( 'product' === get_post_type( $comment->comment_post_ID ) ) {
  268. $verified = wc_customer_bought_product( $comment->comment_author_email, $comment->user_id, $comment->comment_post_ID );
  269. add_comment_meta( $comment_id, 'verified', (int) $verified, true );
  270. }
  271. return $verified;
  272. }
  273. /**
  274. * Get product rating for a product. Please note this is not cached.
  275. *
  276. * @since 3.0.0
  277. * @param WC_Product $product Product instance.
  278. * @return float
  279. */
  280. public static function get_average_rating_for_product( &$product ) {
  281. global $wpdb;
  282. $count = $product->get_rating_count();
  283. if ( $count ) {
  284. $ratings = $wpdb->get_var(
  285. $wpdb->prepare(
  286. "
  287. SELECT SUM(meta_value) FROM $wpdb->commentmeta
  288. LEFT JOIN $wpdb->comments ON $wpdb->commentmeta.comment_id = $wpdb->comments.comment_ID
  289. WHERE meta_key = 'rating'
  290. AND comment_post_ID = %d
  291. AND comment_approved = '1'
  292. AND meta_value > 0
  293. ",
  294. $product->get_id()
  295. )
  296. );
  297. $average = number_format( $ratings / $count, 2, '.', '' );
  298. } else {
  299. $average = 0;
  300. }
  301. return $average;
  302. }
  303. /**
  304. * Utility function for getting review counts for multiple products in one query. This is not cached.
  305. *
  306. * @since 5.0.0
  307. *
  308. * @param array $product_ids Array of product IDs.
  309. *
  310. * @return array
  311. */
  312. public static function get_review_counts_for_product_ids( $product_ids ) {
  313. global $wpdb;
  314. if ( empty( $product_ids ) ) {
  315. return array();
  316. }
  317. $product_id_string_placeholder = substr( str_repeat( ',%s', count( $product_ids ) ), 1 );
  318. $review_counts = $wpdb->get_results(
  319. // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Ignored for allowing interpolation in IN query.
  320. $wpdb->prepare(
  321. "
  322. SELECT comment_post_ID as product_id, COUNT( comment_post_ID ) as review_count
  323. FROM $wpdb->comments
  324. WHERE
  325. comment_parent = 0
  326. AND comment_post_ID IN ( $product_id_string_placeholder )
  327. AND comment_approved = '1'
  328. AND comment_type in ( 'review', '', 'comment' )
  329. GROUP BY product_id
  330. ",
  331. $product_ids
  332. ),
  333. // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared.
  334. ARRAY_A
  335. );
  336. // Convert to key value pairs.
  337. $counts = array_replace( array_fill_keys( $product_ids, 0 ), array_column( $review_counts, 'review_count', 'product_id' ) );
  338. return $counts;
  339. }
  340. /**
  341. * Get product review count for a product (not replies). Please note this is not cached.
  342. *
  343. * @since 3.0.0
  344. * @param WC_Product $product Product instance.
  345. * @return int
  346. */
  347. public static function get_review_count_for_product( &$product ) {
  348. $counts = self::get_review_counts_for_product_ids( array( $product->get_id() ) );
  349. return $counts[ $product->get_id() ];
  350. }
  351. /**
  352. * Get product rating count for a product. Please note this is not cached.
  353. *
  354. * @since 3.0.0
  355. * @param WC_Product $product Product instance.
  356. * @return int[]
  357. */
  358. public static function get_rating_counts_for_product( &$product ) {
  359. global $wpdb;
  360. $counts = array();
  361. $raw_counts = $wpdb->get_results(
  362. $wpdb->prepare(
  363. "
  364. SELECT meta_value, COUNT( * ) as meta_value_count FROM $wpdb->commentmeta
  365. LEFT JOIN $wpdb->comments ON $wpdb->commentmeta.comment_id = $wpdb->comments.comment_ID
  366. WHERE meta_key = 'rating'
  367. AND comment_post_ID = %d
  368. AND comment_approved = '1'
  369. AND meta_value > 0
  370. GROUP BY meta_value
  371. ",
  372. $product->get_id()
  373. )
  374. );
  375. foreach ( $raw_counts as $count ) {
  376. $counts[ $count->meta_value ] = absint( $count->meta_value_count ); // WPCS: slow query ok.
  377. }
  378. return $counts;
  379. }
  380. /**
  381. * Update comment type of product reviews.
  382. *
  383. * @since 3.5.0
  384. * @param array $comment_data Comment data.
  385. * @return array
  386. */
  387. public static function update_comment_type( $comment_data ) {
  388. if ( ! is_admin() && isset( $_POST['comment_post_ID'], $comment_data['comment_type'] ) && self::is_default_comment_type( $comment_data['comment_type'] ) && 'product' === get_post_type( absint( $_POST['comment_post_ID'] ) ) ) { // WPCS: input var ok, CSRF ok.
  389. $comment_data['comment_type'] = 'review';
  390. }
  391. return $comment_data;
  392. }
  393. /**
  394. * Validate product reviews if requires a verified owner.
  395. *
  396. * @param int $comment_post_id Post ID.
  397. */
  398. public static function validate_product_review_verified_owners( $comment_post_id ) {
  399. // Only validate if option is enabled.
  400. if ( 'yes' !== get_option( 'woocommerce_review_rating_verification_required' ) ) {
  401. return;
  402. }
  403. // Validate only products.
  404. if ( 'product' !== get_post_type( $comment_post_id ) ) {
  405. return;
  406. }
  407. // Skip if is a verified owner.
  408. if ( wc_customer_bought_product( '', get_current_user_id(), $comment_post_id ) ) {
  409. return;
  410. }
  411. wp_die(
  412. esc_html__( 'Only logged in customers who have purchased this product may leave a review.', 'woocommerce' ),
  413. esc_html__( 'Reviews can only be left by "verified owners"', 'woocommerce' ),
  414. array(
  415. 'code' => 403,
  416. )
  417. );
  418. }
  419. /**
  420. * Determines if a comment is of the default type.
  421. *
  422. * Prior to WordPress 5.5, '' was the default comment type.
  423. * As of 5.5, the default type is 'comment'.
  424. *
  425. * @since 4.3.0
  426. * @param string $comment_type Comment type.
  427. * @return bool
  428. */
  429. private static function is_default_comment_type( $comment_type ) {
  430. return ( '' === $comment_type || 'comment' === $comment_type );
  431. }
  432. }
  433. WC_Comments::init();