Burst-Statistics / burst

Burst Statistics by Really Simple Plugins
https://burst-statistics.com/
GNU General Public License v3.0
18 stars 6 forks source link

Lot of PHP warnings because data in API requests are encoded twice #15

Closed hyncica closed 1 year ago

hyncica commented 1 year ago

There are a lot of warnings generated by tracking api requests.

PHP Warning: foreach() argument must be of type array|object, string given in /www/hosting/unyp.cz/www/wp-includes/rest-api/class-wp-rest-request.php on line 814

This is caused because the JSON.stringify() function is applied twice on request data. The first time is in burst_update_hit() function. https://github.com/Really-Simple-Plugins/burst/blob/a788ac05203c1ec510bc6957d7129846b1a01c95/assets/js/src/burst.js#L250 Or in burst_track_hit() function. https://github.com/Really-Simple-Plugins/burst/blob/a788ac05203c1ec510bc6957d7129846b1a01c95/assets/js/src/burst.js#L292

The second time it's applied by wp.apiFetch() method used to send request. This method actually expects the object in the data property. The data shouldn't be already encoded JSON string. https://developer.wordpress.org/block-editor/reference-guides/packages/packages-api-fetch/#data-object

The request body is parsed by WP during WP_REST_Request::sanitize_params() https://github.com/WordPress/WordPress/blob/fe3e9324210c232ca82704df0c80396794cb928d/wp-includes/rest-api/class-wp-rest-request.php#L796 And then it's used in foreach() cycle because WP expects array as result of parsing JSON body.

The plugin decodes json second time in burst_rest_track_hit() function. https://github.com/Really-Simple-Plugins/burst/blob/a788ac05203c1ec510bc6957d7129846b1a01c95/tracking/tracking.php#L163

hesseldj commented 1 year ago

Hi @hyncica,

You are absolutely right. Thank you for finding this issue and explaining it so clearly. I've made a fix: https://github.com/Really-Simple-Plugins/burst/tree/1.3.4_remove_double_stringify

Can you try this out and tell me if all errors are gone?

Kind regards, Hessel

hyncica commented 1 year ago

Hello,

I've tested it in dev environment. It looks like the errors are gone. Thanks!

hesseldj commented 1 year ago

Hi @hyncica, Thanks for confirming the problem is solved. Also, we appreciate you giving us feedback and helping us improve Burst :)

Kind regards, Hessel