'POST', 'permission_callback' => 'sevenbe_texts_signed', 'callback' => 'sevenbe_texts_route', ) ); } ); /** * Only 7BE may call the route: the body signed with the store's key, sent within the last hour. * * @param WP_REST_Request $request The request. * @return true|WP_Error */ function sevenbe_texts_signed( $request ) { $options = sevenbe_options(); $signature = (string) $request->get_header( 'x-7be-signature' ); $raw = (string) $request->get_body(); if ( '' === $options['key'] || '' === $signature || ! hash_equals( hash_hmac( 'sha256', $raw, $options['key'] ), $signature ) ) { return new WP_Error( 'sevenbe_signature', 'Bad signature.', array( 'status' => 401 ) ); } $body = json_decode( $raw, true ); $sent = is_array( $body ) && isset( $body['sent'] ) ? (int) floor( (float) $body['sent'] / 1000 ) : 0; if ( abs( time() - $sent ) > HOUR_IN_SECONDS ) { return new WP_Error( 'sevenbe_clock', 'The request is too old.', array( 'status' => 401 ) ); } return true; } /** * Apply a text to a product, or undo it. * * @param WP_REST_Request $request The request. * @return array|WP_Error */ function sevenbe_texts_route( $request ) { $body = json_decode( (string) $request->get_body(), true ); $action = isset( $body['action'] ) ? sanitize_key( $body['action'] ) : ''; $product = wc_get_product( isset( $body['product'] ) ? absint( $body['product'] ) : 0 ); if ( ! $product || $product->get_parent_id() ) { return new WP_Error( 'sevenbe_product', 'No such product.', array( 'status' => 404 ) ); } $id = $product->get_id(); if ( 'apply' === $action ) { $html = isset( $body['html'] ) ? wp_kses_post( (string) $body['html'] ) : ''; if ( '' === trim( wp_strip_all_tags( $html ) ) ) { return new WP_Error( 'sevenbe_empty', 'The text is empty.', array( 'status' => 400 ) ); } // The description before the first text is kept; later texts replace each other. if ( ! metadata_exists( 'post', $id, SEVENBE_TEXT_BACKUP ) ) { update_post_meta( $id, SEVENBE_TEXT_BACKUP, $product->get_description() ); } $product->set_description( $html ); $product->save(); update_post_meta( $id, SEVENBE_TEXT_APPLIED, gmdate( 'c' ) ); return array( 'ok' => true, 'original' => (string) get_post_meta( $id, SEVENBE_TEXT_BACKUP, true ), ); } if ( 'undo' === $action ) { if ( ! metadata_exists( 'post', $id, SEVENBE_TEXT_BACKUP ) ) { return new WP_Error( 'sevenbe_nothing', 'No text to undo on this product.', array( 'status' => 409 ) ); } $product->set_description( (string) get_post_meta( $id, SEVENBE_TEXT_BACKUP, true ) ); $product->save(); delete_post_meta( $id, SEVENBE_TEXT_BACKUP ); delete_post_meta( $id, SEVENBE_TEXT_APPLIED ); return array( 'ok' => true ); } return new WP_Error( 'sevenbe_action', 'Unknown action.', array( 'status' => 400 ) ); }