| 1 |
<?php |
| 2 |
|
| 3 |
namespace Yoast\WP\SEO\Helpers\Schema; |
| 4 |
|
| 5 |
/** |
| 6 |
* Class HTML_Helper. |
| 7 |
*/ |
| 8 |
class HTML_Helper { |
| 9 |
|
| 10 |
/** |
| 11 |
* Sanitizes a HTML string by stripping all tags except headings, breaks, lists, links, paragraphs and formatting. |
| 12 |
* |
| 13 |
* @param string $html The original HTML. |
| 14 |
* |
| 15 |
* @return string The sanitized HTML. |
| 16 |
*/ |
| 17 |
public function sanitize( $html ) { |
| 18 |
if ( ! $this->is_non_empty_string_or_stringable( $html ) ) { |
| 19 |
if ( \is_int( $html ) || \is_float( $html ) ) { |
| 20 |
return (string) $html; |
| 21 |
} |
| 22 |
|
| 23 |
return ''; |
| 24 |
} |
| 25 |
|
| 26 |
return \strip_tags( $html, '<h1><h2><h3><h4><h5><h6><br><ol><ul><li><a><p><b><strong><i><em>' ); |
| 27 |
} |
| 28 |
|
| 29 |
/** |
| 30 |
* Strips the tags in a smart way. |
| 31 |
* |
| 32 |
* @param string $html The original HTML. |
| 33 |
* |
| 34 |
* @return string The sanitized HTML. |
| 35 |
*/ |
| 36 |
public function smart_strip_tags( $html ) { |
| 37 |
if ( ! $this->is_non_empty_string_or_stringable( $html ) ) { |
| 38 |
if ( \is_int( $html ) || \is_float( $html ) ) { |
| 39 |
return (string) $html; |
| 40 |
} |
| 41 |
|
| 42 |
return ''; |
| 43 |
} |
| 44 |
|
| 45 |
// Replace all new lines with spaces. |
| 46 |
$html = \preg_replace( '/(\r|\n)/', ' ', $html ); |
| 47 |
|
| 48 |
// Replace <br> tags with spaces. |
| 49 |
$html = \preg_replace( '/<br(\s*)?\/?>/i', ' ', $html ); |
| 50 |
|
| 51 |
// Replace closing </p> and other tags with the same tag with a space after it, so we don't end up connecting words when we remove them later. |
| 52 |
$html = \preg_replace( '/<\/(p|div|h\d)>/i', '</$1> ', $html ); |
| 53 |
|
| 54 |
// Replace list items with list identifiers so it still looks natural. |
| 55 |
$html = \preg_replace( '/(<li[^>]*>)/i', '$1• ', $html ); |
| 56 |
|
| 57 |
// Strip tags. |
| 58 |
$html = \wp_strip_all_tags( $html ); |
| 59 |
|
| 60 |
// Replace multiple spaces with one space. |
| 61 |
$html = \preg_replace( '!\s+!', ' ', $html ); |
| 62 |
|
| 63 |
return \trim( $html ); |
| 64 |
} |
| 65 |
|
| 66 |
/** |
| 67 |
* Verifies that the received input is either a string or stringable object. |
| 68 |
* |
| 69 |
* @param string $html The original HTML. |
| 70 |
* |
| 71 |
* @return bool |
| 72 |
*/ |
| 73 |
private function is_non_empty_string_or_stringable( $html ) { |
| 74 |
return ( \is_string( $html ) || \is_object( $html ) && \method_exists( $html, '__toString' ) ) && ! empty( $html ); |
| 75 |
} |
| 76 |
} |
| 77 |
|