class-remove-reply-to-com.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. /**
  3. * WPSEO plugin file.
  4. *
  5. * @package WPSEO\Frontend
  6. */
  7. /**
  8. * Class WPSEO_Remove_Reply_To_Com.
  9. *
  10. * @since 7.0
  11. */
  12. class WPSEO_Remove_Reply_To_Com implements WPSEO_WordPress_Integration {
  13. /**
  14. * Registers the hooks necessary to handle removing ?replytocom.
  15. *
  16. * @since 7.0
  17. *
  18. * @return void
  19. */
  20. public function register_hooks() {
  21. if ( $this->clean_reply_to_com() ) {
  22. add_filter( 'comment_reply_link', [ $this, 'remove_reply_to_com' ] );
  23. add_action( 'template_redirect', [ $this, 'replytocom_redirect' ], 1 );
  24. }
  25. }
  26. /**
  27. * Removes the ?replytocom variable from the link, replacing it with a #comment-<number> anchor.
  28. *
  29. * @todo Should this function also allow for relative urls ?
  30. *
  31. * @param string $link The comment link as a string.
  32. *
  33. * @return string The modified link.
  34. */
  35. public function remove_reply_to_com( $link ) {
  36. return preg_replace( '`href=(["\'])(?:.*(?:\?|&|&#038;)replytocom=(\d+)#respond)`', 'href=$1#comment-$2', $link );
  37. }
  38. /**
  39. * Redirects out the ?replytocom variables.
  40. *
  41. * @since 1.4.13
  42. * @return boolean True when redirect has been done.
  43. */
  44. public function replytocom_redirect() {
  45. if ( isset( $_GET['replytocom'] ) && is_singular() ) {
  46. $url = get_permalink( $GLOBALS['post']->ID );
  47. $hash = sanitize_text_field( wp_unslash( $_GET['replytocom'] ) );
  48. $query_string = '';
  49. if ( isset( $_SERVER['QUERY_STRING'] ) ) {
  50. $query_string = remove_query_arg( 'replytocom', sanitize_text_field( wp_unslash( $_SERVER['QUERY_STRING'] ) ) );
  51. }
  52. if ( ! empty( $query_string ) ) {
  53. $url .= '?' . $query_string;
  54. }
  55. $url .= '#comment-' . $hash;
  56. $front = WPSEO_Frontend::get_instance();
  57. $front->redirect( $url, 301 );
  58. return true;
  59. }
  60. return false;
  61. }
  62. /**
  63. * Checks whether we can allow the feature that removes ?replytocom query parameters.
  64. *
  65. * @return bool True to remove, false not to remove.
  66. */
  67. private function clean_reply_to_com() {
  68. /**
  69. * Filter: 'wpseo_remove_reply_to_com' - Allow disabling the feature that removes ?replytocom query parameters.
  70. *
  71. * @param bool $return True to remove, false not to remove.
  72. */
  73. return (bool) apply_filters( 'wpseo_remove_reply_to_com', true );
  74. }
  75. }