| 2761 | * Adds target="_blank" and rel="noreferrer noopener" strings to all HTML A elements |
| 2762 | * in content. |
| 2763 | * |
| 2764 | * Removes current target and rel attributes prior. |
| 2765 | * |
| 2766 | * @since TODO Ticket #40916 |
| 2767 | * |
| 2768 | * @param string $text Content that may contain HTML A elements. |
| 2769 | * @return string Converted content. |
| 2770 | */ |
| 2771 | function wp_unbind_links( $text ) { |
| 2772 | |
| 2773 | // Ticket #40916 Filter usage to be determined... |
| 2774 | if ( 'pre_comment_content' === current_filter() ) { |
| 2775 | // This is a pre save filter, so text is already escaped. |
| 2776 | $text = stripslashes( $text ); |
| 2777 | $text = preg_replace_callback( '|<a (.+?)>|i', 'wp_unbind_links_callback', $text ); |
| 2778 | return wp_slash( $text ); |
| 2779 | } |
| 2780 | |
| 2781 | return preg_replace_callback( '|<a (.+?)>|i', 'wp_unbind_links_callback', $text ); |
| 2782 | } |
| 2783 | |
| 2784 | /** |
| 2785 | * Callback to add target="_blank" and rel="noreferrer noopener" string to HTML A element. |
| 2786 | * |
| 2787 | * Will remove already existing rel="noreferrer", rel='noreferrer', rel="noopener" |
| 2788 | * and rel='noopener' from the string to prevent from invalidating (X)HTML. |
| 2789 | * |
| 2790 | * @since TODO Ticket #40916 |
| 2791 | * |
| 2792 | * @param array $matches Single Match |
| 2793 | * @return string HTML A Element with target="_blank" and rel="noreferrer noopener". |
| 2794 | */ |
| 2795 | function wp_unbind_links_callback( $matches ) { |
| 2796 | |
| 2797 | $text = $matches[1]; |
| 2798 | |
| 2799 | // TODO Do we want to exclude own pages? |
| 2800 | /* |
| 2801 | if ( preg_match( '%href=["\'](https?' . preg_quote( str_replace( 'http://', '://', set_url_scheme( home_url(), 'http' ) ) ) . ')%i', $text ) ) { |
| 2802 | return "<a $text>"; |
| 2803 | } |
| 2804 | */ |
| 2805 | |
| 2806 | /** |
| 2807 | * Captures rel and target attributes with content. |
| 2808 | * Closing/opening tag aware, i.e. it captures: |
| 2809 | * rel='nofollow"', rel="nofollow", rel=nofollow, rel="nofollow noreferrer" |
| 2810 | */ |
| 2811 | $regex = '/(target|rel)\=(\'|"?)((?:.(?!\2?\s+(?:\S+)=|[>]\2))+.)\2?/i'; |
| 2812 | |
| 2813 | //* TODO This will add stray whitespaces... It's not important enough to clean up. |
| 2814 | $text = preg_replace( $regex, '', $text ); |
| 2815 | |
| 2816 | return sprintf( '<a %s target=_blank rel="noopener noreferrer">', $text ); |
| 2817 | } |
| 2818 | |
| 2819 | /** |