| 1 |
<?php |
| 2 |
|
| 3 |
namespace Give\API\REST\V3\Entities\Actions; |
| 4 |
|
| 5 |
use Give\Framework\Support\Facades\Scripts\ScriptAsset; |
| 6 |
use Give\Helpers\Language; |
| 7 |
|
| 8 |
/** |
| 9 |
* @since 4.13.1 |
| 10 |
*/ |
| 11 |
class RegisterPublicEntities |
| 12 |
{ |
| 13 |
/** |
| 14 |
* @since 4.13.1 |
| 15 |
*/ |
| 16 |
public function __invoke() |
| 17 |
{ |
| 18 |
$handleName = 'givewp-entities-public'; |
| 19 |
$scriptAsset = ScriptAsset::get(GIVE_PLUGIN_DIR . 'build/entitiesPublic.asset.php'); |
| 20 |
|
| 21 |
wp_register_script( |
| 22 |
$handleName, |
| 23 |
GIVE_PLUGIN_URL . 'build/entitiesPublic.js', |
| 24 |
$scriptAsset['dependencies'], |
| 25 |
$scriptAsset['version'], |
| 26 |
true |
| 27 |
); |
| 28 |
|
| 29 |
// Prevent unnecessary current-user fetch/noise for logged-out visitors. |
| 30 |
if (!is_user_logged_in()) { |
| 31 |
$this->disableCurrentUserFetch(); |
| 32 |
} |
| 33 |
|
| 34 |
wp_enqueue_script($handleName); |
| 35 |
|
| 36 |
Language::setScriptTranslations($handleName); |
| 37 |
} |
| 38 |
|
| 39 |
/** |
| 40 |
* Adds an inline wp.apiFetch middleware that prevents unauthenticated requests |
| 41 |
* to the current-user REST endpoint from being sent. |
| 42 |
* |
| 43 |
* Why |
| 44 |
* - Core packages (e.g., preferences-persistence, core-data) may call |
| 45 |
* `/wp/v2/users/me` on the front end. When the visitor is not logged in, |
| 46 |
* WordPress responds with 401 `rest_not_logged_in`, which creates noisy |
| 47 |
* console errors. |
| 48 |
* |
| 49 |
* What it does |
| 50 |
* - Hooks into the global `wp.apiFetch` pipeline and normalizes the request |
| 51 |
* target from `options.path` or `options.url` to a path+query string. |
| 52 |
* - If the target contains `/wp/v2/users/me` (with or without query |
| 53 |
* parameters), it immediately resolves with `null`, avoiding the network |
| 54 |
* call and the resulting console error. |
| 55 |
* - Otherwise, it delegates to the next middleware. |
| 56 |
* |
| 57 |
* Scope |
| 58 |
* - Only applied for logged-out visitors (see caller). |
| 59 |
* - Does not affect logged-in users or other endpoints. |
| 60 |
* |
| 61 |
* @since 4.13.1 |
| 62 |
*/ |
| 63 |
private function disableCurrentUserFetch() |
| 64 |
{ |
| 65 |
wp_add_inline_script( |
| 66 |
'wp-api-fetch', |
| 67 |
'(function(){if(!window.wp||!wp.apiFetch||!wp.apiFetch.use){return;}wp.apiFetch.use(function(options,next){var p=String((options&&(options.path||options.url))||"");try{var u=new URL(p,window.location.origin);p=(u.pathname||"")+(u.search||"");}catch(e){}if(p.indexOf("/wp/v2/users/me")!==-1){return Promise.resolve(null);}return next(options);});})();', |
| 68 |
'after' |
| 69 |
); |
| 70 |
} |
| 71 |
} |
| 72 |
|