php-src icon indicating copy to clipboard operation
php-src copied to clipboard

`mb_detect_encoding()` detects UTF-8 emoji byte sequence as ISO-8859-1 since PHP 8.1

Open filecage opened this issue 4 years ago • 53 comments

Description

I have a piece of code that tries to normalise the encoding of incoming strings using mb_detect_encoding(). While upgrading to PHP 8.1, I've noticed that a test which ensures that an urlencoded UTF-8 sequence (party hat emoji) now fails. It all comes down to a behaviour change of mb_detect_encoding() when passing UTF-8 and ISO-8859-1 (in which ever order) as $encodings in PHP 8.1.

I know that the way this method works (or the way that determining the enconding of a string works at all) can not be 100% realiable, so I'd also agree on not classifying this as a bug. However, it is an undocumented behaviour change introduced in 8.1 that might break existing code as it did with mine.

I assume that this change has been introduced with 28b346bc.

Example

See https://3v4l.org/RgdfE

<?php
echo mb_detect_encoding('🥳', ['UTF-8', 'ISO-8859-1']);

Resulted in this output:

ISO-8859-1

But I expected this output instead:

UTF-8

PHP Version

8.1.1

Operating System

No response

filecage avatar Jan 02 '22 17:01 filecage

In our old test case we have the following comment, don't know if it helps or not:

Are you allowed to share more of the test case code or not? If so, and we add it to the official test cases for PHP, it will help to ensure that future development on mbstring does not break your application.

alexdowad avatar Mar 09 '23 13:03 alexdowad

They are not that sophisticated. We have 2 files, one we expect to identify as CP1252 and one we expect to identify as UTF-8

The files needs to be saved utf-8 and windows-1252 respectively, but I guess that is a given :)

We use the content to test html_entity_decode encoding as well, that explains the encoded characters in the CP1252 block.

# This file contains UTF-8 encoded data
abcde
æøå
æøå
ð
<p>Goddag<br />
{readobj objectid=$result[0].parentid assign="doc"}<br />
# This is to ensure that different kinds of HTML entities are being converted correctly
ð
Ð
≗
䎇
顃
ᕡ
abcde æøå æøå ð ð Ð <p>Goddag<br /> {readobj objectid=$result[0].parentid assign="doc"}<br /> ≗ 䎇 顃 ᕡ
# The following characters are special characters that has different code points in ISO-8859-1 and Windows-1252 - that we differentiate correctly between ISO-8859-1 and Windows-1252
Œ
‰
# This file contains Windows-1252 encoded data and HTML entities
abcde
æøå
&aelig;&oslash;&aring;
ð
<p>Goddag<br />
{readobj objectid=$result[0].parentid assign="doc"}<br />
# This is to ensure that different kinds of HTML entities are being converted correctly
&eth;
&ETH;
&#8791;
&#17287;
&#38979;
&#5473;
abcde æøå &aelig;&oslash;&aring; ð &eth; &ETH; <p>Goddag<br /> {readobj objectid=$result[0].parentid assign="doc"}<br /> &#8791; &#17287; &#38979; &#5473;
# The following characters are special characters that has different code points in ISO-8859-1 and Windows-1252 - that we differentiate correctly between ISO-8859-1 and Windows-1252
Œ
‰

mrbase avatar Mar 09 '23 13:03 mrbase

They are not that sophisticated. We have 2 files, one we expect to identify as CP1252 and one we expect to identify as UTF-8

I'm just adding these to the PHP test suite, but I would like to know: what do you provide as $encodings when detecting text encoding?

alexdowad avatar Mar 27 '23 11:03 alexdowad

@alexdowad ups, guess that would have been useful information :)

We use \mb_detect_encoding($text, ['UTF-8', 'CP1252', 'ISO-8859-1'], true);

mrbase avatar Mar 27 '23 12:03 mrbase

@mrbase Thanks for that.

I would like to make sure that the strings which we will include in these test cases are byte-for-byte identical to the ones which you are testing. Would it be possible to temporarily insert something like echo bin2hex($file1); in your test suite, run it, and then get the hex dump back to me?

alexdowad avatar Mar 27 '23 15:03 alexdowad

@alexdowad No problem, here are the dumps

cp1252encoded: 2320546869732066696c6520636f6e7461696e732057696e646f77732d3132353220656e636f646564206461746120616e642048544d4c20656e7469746965730a61626364650ae6f8e50af00a3c703e476f646461673c6272202f3e0a7b726561646f626a206f626a65637469643d24726573756c745b305d2e706172656e7469642061737369676e3d22646f63227d3c6272202f3e0a23205468697320697320746f20656e73757265207468617420646966666572656e74206b696e6473206f662048544d4c20656e74697469657320617265206265696e6720636f6e76657274656420636f72726563746c790af00ad00a2623383739313b0a262331373238373b0a262333383937393b0a2623353437333b0a616263646520e6f8e520f020d0203c703e476f646461673c6272202f3e207b726561646f626a206f626a65637469643d24726573756c745b305d2e706172656e7469642061737369676e3d22646f63227d3c6272202f3e202623383739313b20262331373238373b20262333383937393b202623353437333b0a232054686520666f6c6c6f77696e67206368617261637465727320617265207370656369616c206368617261637465727320746861742068617320646966666572656e7420636f646520706f696e747320696e2049534f2d383835392d3120616e642057696e646f77732d31323532202d207468617420776520646966666572656e746961746520636f72726563746c79206265747765656e2049534f2d383835392d3120616e642057696e646f77732d313235320a8c0a890a2320506f6c69736820737472696e670a50727a656a6426233337383b20646f2070727a65676c26233236313b64750a

utf8encoded: 2320546869732066696c6520636f6e7461696e73205554462d3820656e636f64656420646174610a61626364650ac3a6c3b8c3a50ac3b00a3c703e476f646461673c6272202f3e0a7b726561646f626a206f626a65637469643d24726573756c745b305d2e706172656e7469642061737369676e3d22646f63227d3c6272202f3e0a23205468697320697320746f20656e73757265207468617420646966666572656e74206b696e6473206f662048544d4c20656e74697469657320617265206265696e6720636f6e76657274656420636f72726563746c790ac3b00ac3900ae289970ae48e870ae9a1830ae195a10a616263646520c3a6c3b8c3a520c3b020c390203c703e476f646461673c6272202f3e207b726561646f626a206f626a65637469643d24726573756c745b305d2e706172656e7469642061737369676e3d22646f63227d3c6272202f3e20e2899720e48e8720e9a18320e195a10a232054686520666f6c6c6f77696e67206368617261637465727320617265207370656369616c206368617261637465727320746861742068617320646966666572656e7420636f646520706f696e747320696e2049534f2d383835392d3120616e642057696e646f77732d31323532202d207468617420776520646966666572656e746961746520636f72726563746c79206265747765656e2049534f2d383835392d3120616e642057696e646f77732d313235320ac5920ae280b00a2320506f6c69736820737472696e670a50727a656a64c5ba20646f2070727a65676cc48564750a

mrbase avatar Mar 28 '23 07:03 mrbase

@mrbase Thanks very much...

Hmm. Well, on master, mb_detect_encoding guesses that both of those files are encoded as CP1252.

Take, for example, the final U+2030 PER MILLE SIGN (‰) character in the test files. In UTF-8, that's 0xE280B0. When interpreted as CP1252, the same bytes represent the three characters ‰. The current implementation of mb_detect_encoding looks at that, and says: "‰ is a rare character, but â, €, and ° are all common, so CP1252 looks like the more likely choice".

And I don't know if I can really fault it. Neither a bare "‰" nor the nonsense string "‰" really looks like natural text.

If I, a human, was given those bytes with no other context, I would probably guess that they were UTF-8, simply because they are valid as UTF-8 and most text on the Internet nowadays is UTF-8. So... does that mean that we should give UTF-8 a 'bonus' so that mb_detect_encoding is biased towards choosing UTF-8 when possible? I am very much open to that, but am not sure exactly how the details would work.

I am also open to giving a 'bonus' to the first candidate encoding in the provided array. Again, it's just a matter of working out the details.

alexdowad avatar Mar 28 '23 17:03 alexdowad

giving UTF8 per se a bonus might work today, but maybe a new charset will come up in the future which will take the lead and changing a implicit charset which gets a bonus (and decide at which point in time when this decision is made) is a big BC break.

I am also open to giving a 'bonus' to the first candidate encoding in the provided array

I think this makes more sense, as the consumer of the api is in control and can take better decisions for the use-case at hand then php alone for the whole ecosystem

staabm avatar Mar 29 '23 06:03 staabm

@alexdowad Hmm, it might be some wired test-thing we do to get different results - might be that on is "is this utf8" and the other "is this something else" have to dig into the actual tests...

But to go back to your original answer to @filecage, regarding returning utf8 and not iso.

Why would you not return the first match, when the list of test-charsets is prioritized? Is it because some (in this case uf8) characters is also valid iso characters? Is the guess done x times, eg. mb_detect_encoding('xxx', ['a', 'b', 'c']) results in 3 full tests, and then the "best" result is returned?

I might be talking out of my ass here, the topic is a little over my head :)

mrbase avatar Mar 29 '23 07:03 mrbase

Why would you not return the first match, when the list of test-charsets is prioritized?

The documentation for mb_detect_encoding states that the function "Detects the most likely character encoding for string string from an ordered list of candidates."

If the string is only valid in one of the provided candidate encodings, then definitely, we return that one. If it's valid in more than one candidate encoding, then we have to guess which is the "most likely character encoding".

Is it because some (in this case uf8) characters is also valid iso characters?

Again, when we don't know the encoding of a string, it's just a sequence of bytes. And yes, the same sequence of bytes may encode one sequence of characters as UTF-8, and encode a different sequence of characters as ISO-8859-1. We need to look at those two sequences of characters and guess which one is "right".

This is, of course, an impossible job, so all we can do is try to return results which are usually what the user intended. In this case, we need to guess whether the user wants ‰ or whether they want ‰.

If you just want to pick the "first match" in the list, then it is better to call mb_check_encoding in a loop.

alexdowad avatar Mar 29 '23 09:03 alexdowad

@alexdowad Yeah - that's what I figured :) Fantastic job you do btw . Thank you for taking the time to explain the issues in such detail.

mrbase avatar Mar 29 '23 09:03 mrbase

@mrbase You are very welcome. Thanks also for supporting the PHP project by providing feedback to the developers.

alexdowad avatar Mar 29 '23 11:03 alexdowad

@alexdowad Have been thinking about this a while. The process of the guesser, is that a:

  • loop over the provided encoding's (if any)
  • give each encoding a score
  • return encoding with the highest score

Simplified I know, but conceptually ...

I guess the score could be the same, if a string can be both cp1252 and utf8. So, if supplied, use the supplied encoding's order as weight - if the score is equal - or something like that...?

mrbase avatar Apr 19 '23 07:04 mrbase

@mrbase Thanks for the comment.

It is unlikely that two candidate encodings will have exactly the same score. In a few cases it will happen, but not much.

You used an interesting expression... "weight". If we treat the order of supplied encodings as "weight", that could mean (for example) that if 3 encodings are listed, we multiply the score for the 2nd one by 1.05 and the 3rd one by 1.1, or something along those lines.

The big question is how heavily the order should affect the results of the operation. Many users simply pass mb_list_encodings(), rather than an explicit list, and the order of mb_list_encodings means nothing at all. (Incidentally, it is not a good idea to pass mb_list_encodings() to this function!)

alexdowad avatar Apr 19 '23 07:04 alexdowad

If I read the mb_detect_order docs correctly, the order/weight is first is highest - so I would prefer the same to be true for the encoding's supplied :)

But you are correct, just supplying the full list does not make much sense.. Would it be an idea to compare the $encodings to the mb_list_encodings - and fall back to null, if they match?

I'm all for the weighted solution tho :)

mrbase avatar Apr 19 '23 08:04 mrbase

@Girgias @cmb69 I would like to modify mb_list_encodings so it returns a single, immutable array rather than initializing a new, mutable array on each call.

Just poking around in Zend core are trying to figure out the best way to initialize an immutable PHP array. Do you know?

alexdowad avatar Apr 19 '23 08:04 alexdowad

@iluuu1994 or @arnaud-lb would probably know more about those things then I do :/

Girgias avatar Apr 29 '23 09:04 Girgias

@alexdowad It depends on whether you'd like to share the value in the same request, across all requests, or even across processes. Either way, type should be set to IS_ARRAY | ((GC_IMMUTABLE|GC_PERSISTENT|GC_NOT_COLLECTABLE) << GC_FLAGS_SHIFT), refcount to 2 (so that the array always gets separated), and it should be allocated with malloc.

  • Share in the same request
    • Once mb_list_encodings is called, you can check in the globals (which are unique per process/thread) whether the array has been initialized, and if not do so. You can clean up the array on RSHUTDOWN.
  • Share across requests
    • Same as above, except you clean up the array in MSHUTDOWN.
  • Share across all processes/threads
    • You could initialize the array in MINIT in the same way, and then also clean it up in MSHUTDOWN.

The first option is probably enough. Is this function particularly slow? Or what's the motivation behind it?

iluuu1994 avatar Apr 29 '23 10:04 iluuu1994

The first option is probably enough. Is this function particularly slow? Or what's the motivation behind it?

@iluuu1994 The actual motivation is that so that a cheap pointer equality check can be used to check whether a list of text encodings passed in to mb_detect_encoding (or even other functions) is the complete list of all supported encodings returned by mb_list_encodings.

alexdowad avatar Apr 29 '23 11:04 alexdowad

@iluuu1994 What's the best way to free the memory used by such an array on module shutdown?

alexdowad avatar Apr 29 '23 12:04 alexdowad