68 lines
2.1 KiB
PHP
Raw Normal View History

2023-01-21 01:31:34 +01:00
<?php
// =============================================================================
// SAVE BOOKMARKS FOR USERS - AJAX
// =============================================================================
/**
* Save bookmarks JSON for user via AJAX
*
* Note: Bookmarks are not evaluated server-side, only stored as JSON string.
* Everything else happens client-side.
*
* @since 4.0.0
* @link https://developer.wordpress.org/reference/functions/wp_send_json_success/
* @link https://developer.wordpress.org/reference/functions/wp_send_json_error/
* @see fictioneer_get_validated_ajax_user()
*/
function fictioneer_ajax_save_bookmarks() {
2023-08-21 15:45:54 +02:00
// Enabled?
if ( ! get_option( 'fictioneer_enable_bookmarks' ) ) {
2024-10-12 23:42:54 +02:00
wp_send_json_error( null, 403 );
2023-08-21 15:45:54 +02:00
}
// Setup and validations
$user = fictioneer_get_validated_ajax_user();
if ( ! $user ) {
2024-10-12 23:42:54 +02:00
wp_send_json_error( array( 'error' => 'Request did not pass validation.' ) );
}
if ( empty( $_POST['bookmarks'] ) ) {
2024-10-12 23:42:54 +02:00
wp_send_json_error( array( 'error' => 'Missing arguments.' ) );
}
// Valid?
$bookmarks = sanitize_text_field( $_POST['bookmarks'] );
2023-01-21 01:31:34 +01:00
2023-10-07 04:23:10 +02:00
if ( $bookmarks && fictioneer_is_valid_json( wp_unslash( $bookmarks ) ) ) {
// Inspect
2023-10-07 04:23:10 +02:00
$decoded = json_decode( wp_unslash( $bookmarks ), true );
2023-10-07 01:35:50 +02:00
if ( ! $decoded || ! isset( $decoded['data'] ) ) {
2024-10-12 23:42:54 +02:00
wp_send_json_error( array( 'error' => 'Invalid JSON.' ) );
2023-01-21 01:31:34 +01:00
}
2023-10-07 04:23:10 +02:00
// Update and response (uses wp_slash/wp_unslash internally)
2023-10-07 01:35:50 +02:00
$old_bookmarks = get_user_meta( $user->ID, 'fictioneer_bookmarks', true );
if ( wp_unslash( $bookmarks ) === $old_bookmarks ) {
2023-10-07 01:35:50 +02:00
wp_send_json_success(); // Nothing to update
}
if ( update_user_meta( $user->ID, 'fictioneer_bookmarks', $bookmarks ) ) {
2023-10-07 04:23:10 +02:00
wp_send_json_success();
} else {
2024-10-12 23:42:54 +02:00
wp_send_json_error( array( 'error' => 'Bookmarks could not be updated.' ) );
}
2023-01-21 01:31:34 +01:00
}
// Something went wrong if we end up here...
2024-10-12 23:42:54 +02:00
wp_send_json_error( array( 'error' => 'An unknown error occurred.' ) );
2023-01-21 01:31:34 +01:00
}
if ( get_option( 'fictioneer_enable_bookmarks' ) ) {
add_action( 'wp_ajax_fictioneer_ajax_save_bookmarks', 'fictioneer_ajax_save_bookmarks' );
}