Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid using deprecated mb_convert_encoding #2733

Draft
wants to merge 3 commits into
base: dev
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changelogs/fix_mb_convert_encoding_replace.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
significance: patch
type: fixed
links:
- "#2672"
entry: Removes use of deprecated mb_convert_encoding().
33 changes: 27 additions & 6 deletions includes/class-llms-dom-document.php
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,6 @@ public function load() {
libxml_use_internal_errors( $libxml_state );

return is_wp_error( $this->error ) && $this->error->has_errors() ? $this->error : true;

}

/**
Expand All @@ -122,22 +121,46 @@ public function load() {
public function dom() {

return $this->dom;

}

/**
* Load the HTML string in the DOMDocument using mb_convert_econding
* Load the HTML string in the DOMDocument using htmlspecialchars_decode( htmlentities() ) as mb_convert_encoding() is deprecated.
*
* @since 4.13.0
*
* @return void
*/
private function load_with_mb_convert_encoding() {
if ( ! $this->dom->loadHTML( mb_convert_encoding( $this->source, 'HTML-ENTITIES', 'UTF-8' ) ) ) {
if ( ! $this->dom->loadHTML( $this->convert_to_numeric_and_named_entities( $this->source ) ) ) {
$this->error = new WP_Error( 'llms-dom-document-error', __( 'DOMDocument XML Error encountered.', 'lifterlms' ), libxml_get_errors() );
}
}

private function convert_to_numeric_and_named_entities( $string ) {
return preg_replace_callback(
'/(<[^>]+>|&[^;]+;|[^<>&]+)/u',
function ( $matches ) {
$part = $matches[0];

// Skip HTML tags and named entities
if ( substr( $part, 0, 1 ) === '<' || ( substr( $part, 0, 1 ) === '&' && substr( $part, -1 ) === ';' ) ) {
return $part;
}

// Convert characters to numeric entities
$result = '';
$length = mb_strlen( $part, 'UTF-8' );
for ( $i = 0; $i < $length; $i++ ) {
$char = mb_substr( $part, $i, 1, 'UTF-8' );
$codepoint = mb_ord( $char, 'UTF-8' );
$result .= '&#' . $codepoint . ';';
}
return $result;
},
$string
);
}

/**
* Load the HTML string in the DOMDocument using the meta ut8 fixer
*
Expand All @@ -156,7 +179,5 @@ private function load_with_meta_utf_fixer() {
if ( $meta ) {
$meta->parentNode->removeChild( $meta ); // phpcs:ignore: WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
}

}

}
Loading