| 1 |
<?php |
| 2 |
/** |
| 3 |
* Desktop Mode AJAX endpoints. |
| 4 |
* |
| 5 |
* @package WPDesktopMode |
| 6 |
*/ |
| 7 |
|
| 8 |
defined( 'ABSPATH' ) || exit; |
| 9 |
|
| 10 |
/** |
| 11 |
* Handles saving the user's desktop mode preference via AJAX. |
| 12 |
* |
| 13 |
* @since 0.1.0 |
| 14 |
*/ |
| 15 |
function desktop_mode_ajax_save() { |
| 16 |
check_ajax_referer( 'save-desktop-mode', 'nonce' ); |
| 17 |
|
| 18 |
// A valid nonce proves *this* request was authored by the current |
| 19 |
// user, but WP's cap system is the authoritative gate for "is this |
| 20 |
// account allowed to touch admin state at all". `read` is the |
| 21 |
// minimum cap every admin-visible role carries; subscribers on sites |
| 22 |
// that revoke it have no business flipping an admin-UI preference. |
| 23 |
if ( ! current_user_can( 'read' ) ) { |
| 24 |
wp_send_json_error( 'desktop_mode_forbidden', 403 ); |
| 25 |
} |
| 26 |
|
| 27 |
/** |
| 28 |
* Filters whether desktop mode is available for this user. |
| 29 |
* |
| 30 |
* Plugins can disable desktop mode for certain roles, capabilities, or conditions. |
| 31 |
* |
| 32 |
* @since 0.1.0 |
| 33 |
* |
| 34 |
* @param bool $enabled Whether desktop mode is enabled. Default true. |
| 35 |
* @param int $user_id The current user ID. |
| 36 |
*/ |
| 37 |
$allowed = apply_filters( 'desktop_mode_mode_enabled', true, get_current_user_id() ); |
| 38 |
if ( ! $allowed ) { |
| 39 |
wp_send_json_error( 'desktop_mode_disabled' ); |
| 40 |
} |
| 41 |
|
| 42 |
$enabled = ! empty( $_POST['enabled'] ) && '1' === $_POST['enabled'] ? '1' : ''; |
| 43 |
|
| 44 |
update_user_meta( get_current_user_id(), 'desktop_mode_mode', $enabled ); |
| 45 |
|
| 46 |
// Tell the client where to land. Enabling from classic admin forwards |
| 47 |
// through the portal so the shell takes over and the address bar |
| 48 |
// collapses to /desktop-mode/. Disabling from the shell jumps to a |
| 49 |
// plain admin URL — NOT the portal, which would auto-re-enable the |
| 50 |
// mode via the `desktop_mode_portal_auto_enable` filter and trap the |
| 51 |
// user in a loop. |
| 52 |
$redirect = '1' === $enabled ? desktop_mode_portal_url() : admin_url(); |
| 53 |
|
| 54 |
wp_send_json_success( |
| 55 |
array( |
| 56 |
'enabled' => $enabled, |
| 57 |
'redirect' => esc_url_raw( $redirect ), |
| 58 |
) |
| 59 |
); |
| 60 |
} |
| 61 |
add_action( 'wp_ajax_save-desktop-mode', 'desktop_mode_ajax_save' ); |
| 62 |
|