Esempio n. 1
1
function wpsms_list(WP_REST_Request $request)
{
    $list_sms = array();
    $item = array();
    global $account_sid;
    global $auth_token;
    try {
        $client = new Services_Twilio($account_sid, $auth_token);
        foreach ($client->account->messages as $message) {
            $from = $message->from;
            $to = $message->to;
            $body = $message->body;
            $date_sent = $message->date_sent;
            array_push($item, array("from" => $from, "to" => $to, "body" => $body, "date_sent" => $date_sent));
        }
        $list_sms = array_merge($list_sms, array("list" => $item));
        $response = new WP_REST_Response($list_sms);
        $response->header('Access-Control-Allow-Origin', apply_filters('wpsms_access_control_allow_origin', '*'));
        return $response;
    } catch (Exception $ex) {
        $user_msgs = array("data" => 'ERROR:' . $ex->getMessage());
        $response = new WP_REST_Response($user_msgs);
        $response->header('Access-Control-Allow-Origin', apply_filters('wpsms_access_control_allow_origin', '*'));
    }
}
Esempio n. 2
1
 /**
  * get_item function.
  *
  * returns data about a BuddyPress site
  * 
  * @access public
  * @param mixed $request
  * @return void
  */
 public function get_item($request)
 {
     global $bp;
     $core = array('version' => $bp->version, 'active_components' => $bp->active_components, 'directory_page_ids' => bp_core_get_directory_page_ids());
     $core = apply_filters('core_api_data_filter', $core);
     $response = new WP_REST_Response();
     $response->set_data($core);
     $response = rest_ensure_response($response);
     return $response;
 }
 /**
  * Update a location.
  *
  * @param WP_REST_Request $request
  *
  * @return WP_Error|WP_REST_Response
  */
 function update_location(WP_REST_Request $request)
 {
     // Get the location data
     //
     $result = $this->slplus->currentLocation->get_location($request['id']);
     if (is_wp_error($result)) {
         return $result;
     }
     // Set the incoming parameters array for the update
     //
     $location_data = $request->get_params();
     unset($location_data['id']);
     $location_data['sl_id'] = $this->slplus->currentLocation->id;
     foreach ($location_data as $key => $value) {
         if (is_numeric($key)) {
             unset($location_data[$key]);
         }
     }
     // Error During Prep
     //
     if (empty($location_data)) {
         return new WP_Error('slp_missing_location_data', $this->slplus->text_manager->get_error_text('slp_missing_location_data'), array('status' => 404));
     }
     // Update Location
     //
     $result = $this->slplus->currentLocation->add_to_database($location_data, 'update', false);
     // Error During Update
     //
     if ($result !== 'updated') {
         return new WP_Error('slp_location_not_updated', $this->slplus->text_manager->get_error_text('slp_location_not_updated'), array('status' => 404));
     }
     $response_data = array('message_slug' => 'location_updated', 'message' => __('Location updated. ', 'store-locator-le'), 'location_id' => $this->slplus->currentLocation->id);
     $response = new WP_REST_Response($response_data);
     $response->set_status(201);
     return $response;
 }
Esempio n. 4
0
 /**
  * Gets a list of modules for our API endpoint
  * 
  * Callback for the GET method of the "modules" endpoint
  *
  * @since 0.1.1
  * 
  * 
  */
 function me_get_modules()
 {
     $return = Me_Utils::get_all_modules();
     $response = new WP_REST_Response($return);
     $response->header('Access-Control-Allow-Origin', apply_filters('giar_access_control_allow_origin', '*'));
     return $response;
 }
 public function create_price($request)
 {
     $required_keys = array('ticket_price', 'price_band_id', 'ticket_type_id');
     $meta = $request[$this->post_type . "_meta"] ? $request[$this->post_type . "_meta"] : array();
     if (count(array_intersect_key(array_flip($required_keys), $meta)) >= count($required_keys)) {
         return $this->create_item($request);
     } else {
         $error = new WP_REST_Response(array('message' => 'Insufficient parameters', 'data' => array('status' => 422)));
         $error->set_status(422);
         return $error;
     }
 }
Esempio n. 6
0
 /**
  * Adds EE metadata to the index
  * @param WP_REST_Response $rest_response_obj
  * @return WP_REST_Response
  */
 public static function filter_ee_metadata_into_index($rest_response_obj)
 {
     $response_data = $rest_response_obj->get_data();
     $addons = array();
     foreach (\EE_Registry::instance()->addons as $addon) {
         $addon_json = array('name' => $addon->name(), 'version' => $addon->version());
         $addons[$addon_json['name']] = $addon_json;
     }
     $response_data['ee'] = array('version' => \EEM_System_Status::instance()->get_ee_version(), 'addons' => $addons, 'maintenance_mode' => \EE_Maintenance_Mode::instance()->real_level(), 'served_core_versions' => array_keys(\EED_Core_Rest_Api::versions_served()));
     $rest_response_obj->set_data($response_data);
     return $rest_response_obj;
 }
 public function create_event_instance($request)
 {
     $event_id = $request['event_id'];
     $event_post = get_post($event_id);
     if ($event_post) {
         return $this->create_item($request);
     } else {
         $error = new WP_REST_Response(array('message' => 'Event not found'));
         $error->set_status(404);
         return $error;
     }
 }
Esempio n. 8
0
 /**
  * Adds EE metadata to the index
  * @param \WP_REST_Response $rest_response_obj
  * @return \WP_REST_Response
  */
 public static function filter_ee_metadata_into_index(\WP_REST_Response $rest_response_obj)
 {
     $response_data = $rest_response_obj->get_data();
     $addons = array();
     foreach (\EE_Registry::instance()->addons as $addon) {
         $addon_json = array('name' => $addon->name(), 'version' => $addon->version());
         $addons[$addon_json['name']] = $addon_json;
     }
     $response_data['ee'] = array('version' => \EEM_System_Status::instance()->get_ee_version(), 'documentation_url' => 'https://github.com/eventespresso/event-espresso-core/tree/master/docs/C--REST-API', 'addons' => $addons, 'maintenance_mode' => \EE_Maintenance_Mode::instance()->real_level(), 'served_core_versions' => array_keys(\EED_Core_Rest_Api::versions_served()));
     $rest_response_obj->set_data($response_data);
     return $rest_response_obj;
 }
Esempio n. 9
0
 public function get_pins()
 {
     if (0 || false === ($return = get_transient('rmaps_all_posts'))) {
         $query = apply_filters('rmaps_get_posts_query', array('numberposts' => 20, 'post_type' => 'pin', 'post_status' => 'publish'));
         $pins = get_posts($query);
         $return = array();
         foreach ($pins as $pin) {
             $return[] = array('ID' => $pin->ID, 'title' => esc_attr($pin->post_title), 'infowindow' => wp_kses_post($pin->post_content), 'see_more' => _x('See More', 'Link', $this->textdomain), 'permalink' => esc_url(get_permalink($pin->ID)), 'lat' => esc_attr(get_post_meta($pin->ID, 'latitude', true)), 'lon' => esc_attr(get_post_meta($pin->ID, 'longitude', true)));
         }
         /** Cache the query for 3 minutes */
         set_transient('rmaps_all_posts', $return, apply_filters('rmaps_posts_ttl', 60 * 3));
     }
     $response = new \WP_REST_Response($return);
     $response->header('Access-Control-Allow-Origin', apply_filters('rmaps_access_control_allow_origin', '*'));
     return $response;
 }
Esempio n. 10
0
 /**
  * get_activity function.
  * 
  * @access public
  * @param mixed $filter
  * @return void
  */
 public function get_activity($filter)
 {
     $args = $filter;
     if (bp_has_activities($args)) {
         while (bp_activities()) {
             bp_the_activity();
             $activity = array('avatar' => bp_core_fetch_avatar(array('html' => false, 'item_id' => bp_get_activity_id())), 'action' => bp_get_activity_action(), 'content' => bp_get_activity_content_body(), 'activity_id' => bp_get_activity_id(), 'activity_username' => bp_core_get_username(bp_get_activity_user_id()), 'user_id' => bp_get_activity_user_id(), 'comment_count' => bp_activity_get_comment_count(), 'can_comment' => bp_activity_can_comment(), 'can_favorite' => bp_activity_can_favorite(), 'is_favorite' => bp_get_activity_is_favorite(), 'can_delete' => bp_activity_user_can_delete());
             $activity = apply_filters('bp_json_prepare_activity', $activity);
             $activities[] = $activity;
         }
         $data = array('activity' => $activities, 'has_more_items' => bp_activity_has_more_items());
         $data = apply_filters('bp_json_prepare_activities', $data);
     } else {
         return new WP_Error('bp_json_activity', __('No Activity Found.', 'buddypress'), array('status' => 200));
     }
     $response = new WP_REST_Response();
     $response->set_data($data);
     $response = rest_ensure_response($response);
     return $response;
 }
Esempio n. 11
0
 /**
  * This method use for handler request from Github's webhook.
  *
  * Because of github not required to response payload on response, so we can make a do_action instead of apply_filters
  *
  * @param \WP_REST_Request $request
  *
  * @return \WP_REST_Response
  */
 public function onGithubRequest(\WP_REST_Request $request)
 {
     // Create the response object
     $request_payload = json_decode($request->get_body());
     $response = new \WP_REST_Response();
     if ($request_payload) {
         ob_start();
         $repo = new Repository($request_payload->repository->git_url);
         if ($repo->exists()) {
             $event = $request->get_header('X-Github-Event');
             do_action('wppm_webhook_recived_' . $event, $repo, $request_payload);
         } else {
             $response->set_status(404);
             echo "Repo is not exist.";
         }
         $out_put = ob_get_clean();
         $response->set_data($out_put);
     } else {
         $response->set_status(500);
     }
     return $response;
 }
 /**
  * Deletes a comment.
  *
  * @since 4.7.0
  * @access public
  *
  * @param WP_REST_Request $request Full details about the request.
  * @return WP_Error|WP_REST_Response Response object on success, or error object on failure.
  */
 public function delete_item($request)
 {
     $id = (int) $request['id'];
     $force = isset($request['force']) ? (bool) $request['force'] : false;
     $comment = get_comment($id);
     if (empty($comment)) {
         return new WP_Error('rest_comment_invalid_id', __('Invalid comment ID.'), array('status' => 404));
     }
     /**
      * Filters whether a comment can be trashed.
      *
      * Return false to disable trash support for the post.
      *
      * @since 4.7.0
      *
      * @param bool    $supports_trash Whether the post type support trashing.
      * @param WP_Post $comment        The comment object being considered for trashing support.
      */
     $supports_trash = apply_filters('rest_comment_trashable', EMPTY_TRASH_DAYS > 0, $comment);
     $request->set_param('context', 'edit');
     if ($force) {
         $previous = $this->prepare_item_for_response($comment, $request);
         $result = wp_delete_comment($comment->comment_ID, true);
         $response = new WP_REST_Response();
         $response->set_data(array('deleted' => true, 'previous' => $previous->get_data()));
     } else {
         // If this type doesn't support trashing, error out.
         if (!$supports_trash) {
             return new WP_Error('rest_trash_not_supported', __('The comment does not support trashing. Set force=true to delete.'), array('status' => 501));
         }
         if ('trash' === $comment->comment_approved) {
             return new WP_Error('rest_already_trashed', __('The comment has already been trashed.'), array('status' => 410));
         }
         $result = wp_trash_comment($comment->comment_ID);
         $comment = get_comment($comment->comment_ID);
         $response = $this->prepare_item_for_response($comment, $request);
     }
     if (!$result) {
         return new WP_Error('rest_cannot_delete', __('The comment cannot be deleted.'), array('status' => 500));
     }
     /**
      * Fires after a comment is deleted via the REST API.
      *
      * @since 4.7.0
      *
      * @param WP_Comment       $comment  The deleted comment data.
      * @param WP_REST_Response $response The response returned from the API.
      * @param WP_REST_Request  $request  The request sent to the API.
      */
     do_action('rest_delete_comment', $comment, $response, $request);
     return $response;
 }
Esempio n. 13
0
 /**
  * @depends test_link_embedding_params
  */
 public function test_link_embedding_error()
 {
     // Register our testing route
     $this->server->register_route('test', '/test/embeddable', array('methods' => 'GET', 'callback' => array($this, 'embedded_response_callback')));
     $response = new WP_REST_Response();
     $response->add_link('up', rest_url('/test/embeddable?error=1'), array('embeddable' => true));
     $data = $this->server->response_to_data($response, true);
     $this->assertArrayHasKey('_embedded', $data);
     $this->assertArrayHasKey('up', $data['_embedded']);
     // Check that errors are embedded correctly
     $up = $data['_embedded']['up'];
     $this->assertCount(1, $up);
     $this->assertInstanceOf('WP_REST_Response', $up[0]);
     $this->assertEquals(403, $up[0]->get_status());
     $up_data = $up[0]->get_data();
     $this->assertEquals('wp-api-test-error', $up_data[0]['code']);
     $this->assertEquals('Test message', $up_data[0]['message']);
 }
Esempio n. 14
0
/**
 * Create a REST response
 *
 * @param array|object|\WP_Error $data Response data
 * @param int $code Optional. Status cod. Default is 200
 * @param int|null $total Optional. if is an integer, will be used to set X-Ingot-Total header
 *
 * @return \WP_REST_Response|\WP_Error
 */
function ingot_rest_response($data, $code = 200, $total = null)
{
    if (!is_wp_error($data)) {
        if (404 == $code || empty($data)) {
            $response = new \WP_REST_Response(null, 404);
        } else {
            $response = new \WP_REST_Response($data, $code);
        }
        if (0 < absint($total)) {
            $response->header('X-Ingot-Total', (int) \ingot\testing\crud\group::total());
        }
        return $response;
    } else {
        return $data;
    }
}
Esempio n. 15
0
 /**
  * Sends a response, but also makes sure to attach headers that
  * are handy for debugging.
  * Specifically, we assume folks will want to know what exactly was the DB query that got run,
  * what exactly was the Models query that got run, what capabilities came into play, what fields were omitted from
  * the response, others?
  *
  * @param array|\WP_Error|\Exception $response
  * @return \WP_REST_Response
  */
 public function send_response($response)
 {
     if ($response instanceof \Exception) {
         $response = new \WP_Error($response->getCode(), $response->getMessage());
     }
     if ($response instanceof \WP_Error) {
         $response = $this->_add_ee_errors_to_response($response);
         $rest_response = $this->_create_rest_response_from_wp_error($response);
     } else {
         $rest_response = new \WP_REST_Response($response, 200);
     }
     $headers = array();
     if ($this->_debug_mode && is_array($this->_debug_info)) {
         foreach ($this->_debug_info as $debug_key => $debug_info) {
             if (is_array($debug_info)) {
                 $debug_info = json_encode($debug_info);
             }
             $headers['X-EE4-Debug-' . ucwords($debug_key)] = $debug_info;
         }
     }
     $headers = array_merge($headers, $this->_get_headers_from_ee_notices());
     $rest_response->set_headers($headers);
     return $rest_response;
 }
Esempio n. 16
0
 /**
  * Sends a response to the API request.
  *
  * @since	1.4
  * @param	int		$status_code	Status code.
  * @return	void
  */
 public function output($status_code = 200)
 {
     $response = new WP_REST_Response(array('result' => true));
     $response->set_status($status_code);
     $response->header('Content-type', 'application/json');
     $response->set_data($this->data);
     echo wp_json_encode($response);
     die;
 }
 public function test_removing_links_for_href()
 {
     $response = new WP_REST_Response();
     $response->add_link('self', 'http://example.com/');
     $response->add_link('self', 'https://example.com/');
     $response->remove_link('self', 'https://example.com/');
     $data = $this->server->response_to_data($response, false);
     $this->assertArrayHasKey('_links', $data);
     $this->assertArrayHasKey('self', $data['_links']);
     $self_not_filtered = array('href' => 'http://example.com/');
     $this->assertEquals($self_not_filtered, $data['_links']['self'][0]);
 }
 /**
  * Retrieves the site index.
  *
  * This endpoint describes the capabilities of the site.
  *
  * @since 4.4.0
  * @access public
  *
  * @param array $request {
  *     Request.
  *
  *     @type string $context Context.
  * }
  * @return array Index entity
  */
 public function get_index($request)
 {
     // General site data.
     $available = array('name' => get_option('blogname'), 'description' => get_option('blogdescription'), 'url' => get_option('siteurl'), 'home' => home_url(), 'namespaces' => array_keys($this->namespaces), 'authentication' => array(), 'routes' => $this->get_data_for_routes($this->get_routes(), $request['context']));
     $response = new WP_REST_Response($available);
     $response->add_link('help', 'http://v2.wp-api.org/');
     /**
      * Filters the API root index data.
      *
      * This contains the data describing the API. This includes information
      * about supported authentication schemes, supported namespaces, routes
      * available on the API, and a small amount of data about the site.
      *
      * @since 4.4.0
      *
      * @param WP_REST_Response $response Response data.
      */
     return apply_filters('rest_index', $response);
 }
 /**
  * Check response data.
  *
  * @since 4.4.0
  *
  * @param array            $data
  * @param WP_REST_Response $response
  */
 protected function assertResponseData($data, $response)
 {
     $response_data = $response->get_data();
     $tested_data = array();
     foreach ($data as $key => $value) {
         if (isset($response_data[$key])) {
             $tested_data[$key] = $response_data[$key];
         } else {
             $tested_data[$key] = null;
         }
     }
     $this->assertEquals($data, $tested_data);
 }
Esempio n. 20
0
/**
 * Sends the "Allow" header to state all methods that can be sent to the current route.
 *
 * @since 4.4.0
 *
 * @param WP_REST_Response $response Current response being served.
 * @param WP_REST_Server   $server   ResponseHandler instance (usually WP_REST_Server).
 * @param WP_REST_Request  $request  The request that was used to make current response.
 * @return WP_REST_Response Response to be served, with "Allow" header if route has allowed methods.
 */
function rest_send_allow_header($response, $server, $request)
{
    $matched_route = $response->get_matched_route();
    if (!$matched_route) {
        return $response;
    }
    $routes = $server->get_routes();
    $allowed_methods = array();
    // Get the allowed methods across the routes.
    foreach ($routes[$matched_route] as $_handler) {
        foreach ($_handler['methods'] as $handler_method => $value) {
            if (!empty($_handler['permission_callback'])) {
                $permission = call_user_func($_handler['permission_callback'], $request);
                $allowed_methods[$handler_method] = true === $permission;
            } else {
                $allowed_methods[$handler_method] = true;
            }
        }
    }
    // Strip out all the methods that are not allowed (false values).
    $allowed_methods = array_filter($allowed_methods);
    if ($allowed_methods) {
        $response->header('Allow', implode(', ', array_map('strtoupper', array_keys($allowed_methods))));
    }
    return $response;
}
 /**
  * Prepare a response for inserting into a collection.
  *
  * @param WP_REST_Response $response Response object.
  * @return array Response data, ready for insertion into collection data.
  */
 public function prepare_response_for_collection($response)
 {
     if (!$response instanceof WP_REST_Response) {
         return $response;
     }
     $data = (array) $response->get_data();
     $links = WP_REST_Server::get_response_links($response);
     if (!empty($links)) {
         $data['_links'] = $links;
     }
     return $data;
 }
 /**
  * Deletes a single user.
  *
  * @since 4.7.0
  * @access public
  *
  * @param WP_REST_Request $request Full details about the request.
  * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
  */
 public function delete_item($request)
 {
     $id = (int) $request['id'];
     $reassign = isset($request['reassign']) ? absint($request['reassign']) : null;
     $force = isset($request['force']) ? (bool) $request['force'] : false;
     // We don't support trashing for this type, error out.
     if (!$force) {
         return new WP_Error('rest_trash_not_supported', __('Users do not support trashing. Set force=true to delete.'), array('status' => 501));
     }
     $user = get_userdata($id);
     if (!$user) {
         return new WP_Error('rest_user_invalid_id', __('Invalid resource id.'), array('status' => 404));
     }
     if (!empty($reassign)) {
         if ($reassign === $id || !get_userdata($reassign)) {
             return new WP_Error('rest_user_invalid_reassign', __('Invalid resource id for reassignment.'), array('status' => 400));
         }
     }
     $request->set_param('context', 'edit');
     $previous = $this->prepare_item_for_response($user, $request);
     /** Include admin user functions to get access to wp_delete_user() */
     require_once ABSPATH . 'wp-admin/includes/user.php';
     $result = wp_delete_user($id, $reassign);
     if (!$result) {
         return new WP_Error('rest_cannot_delete', __('The resource cannot be deleted.'), array('status' => 500));
     }
     $response = new WP_REST_Response();
     $response->set_data(array('deleted' => true, 'previous' => $previous->get_data()));
     /**
      * Fires immediately after a user is deleted via the REST API.
      *
      * @since 4.7.0
      *
      * @param WP_User          $user     The user data.
      * @param WP_REST_Response $response The response returned from the API.
      * @param WP_REST_Request  $request  The request sent to the API.
      */
     do_action('rest_delete_user', $user, $response, $request);
     return $response;
 }
 /**
  * If the consumer_key and consumer_secret $_GET parameters are NOT provided
  * and the Basic auth headers are either not present or the consumer secret does not match the consumer
  * key provided, then return the correct Basic headers and an error message.
  *
  * @param WP_REST_Response $response Current response being served.
  * @return WP_REST_Response
  */
 public function send_unauthorized_headers($response)
 {
     global $wc_rest_authentication_error;
     if (is_wp_error($wc_rest_authentication_error) && is_ssl()) {
         $auth_message = __('WooCommerce API - Use a consumer key in the username field and a consumer secret in the password field.', 'woocommerce');
         $response->header('WWW-Authenticate', 'Basic realm="' . $auth_message . '"', true);
     }
     return $response;
 }
 /**
  * Deletes a single post.
  *
  * @since 4.7.0
  * @access public
  *
  * @param WP_REST_Request $request Full details about the request.
  * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
  */
 public function delete_item($request)
 {
     $id = (int) $request['id'];
     $force = (bool) $request['force'];
     $post = get_post($id);
     if (empty($id) || empty($post->ID) || $this->post_type !== $post->post_type) {
         return new WP_Error('rest_post_invalid_id', __('Invalid post ID.'), array('status' => 404));
     }
     $supports_trash = EMPTY_TRASH_DAYS > 0;
     if ('attachment' === $post->post_type) {
         $supports_trash = $supports_trash && MEDIA_TRASH;
     }
     /**
      * Filters whether a post is trashable.
      *
      * The dynamic portion of the hook name, `$this->post_type`, refers to the post type slug.
      *
      * Pass false to disable trash support for the post.
      *
      * @since 4.7.0
      *
      * @param bool    $supports_trash Whether the post type support trashing.
      * @param WP_Post $post           The Post object being considered for trashing support.
      */
     $supports_trash = apply_filters("rest_{$this->post_type}_trashable", $supports_trash, $post);
     if (!$this->check_delete_permission($post)) {
         return new WP_Error('rest_user_cannot_delete_post', __('Sorry, you are not allowed to delete this post.'), array('status' => rest_authorization_required_code()));
     }
     $request->set_param('context', 'edit');
     // If we're forcing, then delete permanently.
     if ($force) {
         $previous = $this->prepare_item_for_response($post, $request);
         $result = wp_delete_post($id, true);
         $response = new WP_REST_Response();
         $response->set_data(array('deleted' => true, 'previous' => $previous->get_data()));
     } else {
         // If we don't support trashing for this type, error out.
         if (!$supports_trash) {
             return new WP_Error('rest_trash_not_supported', __('The post does not support trashing. Set force=true to delete.'), array('status' => 501));
         }
         // Otherwise, only trash if we haven't already.
         if ('trash' === $post->post_status) {
             return new WP_Error('rest_already_trashed', __('The post has already been deleted.'), array('status' => 410));
         }
         // (Note that internally this falls through to `wp_delete_post` if
         // the trash is disabled.)
         $result = wp_trash_post($id);
         $post = get_post($id);
         $response = $this->prepare_item_for_response($post, $request);
     }
     if (!$result) {
         return new WP_Error('rest_cannot_delete', __('The post cannot be deleted.'), array('status' => 500));
     }
     /**
      * Fires immediately after a single post is deleted or trashed via the REST API.
      *
      * They dynamic portion of the hook name, `$this->post_type`, refers to the post type slug.
      *
      * @since 4.7.0
      *
      * @param object           $post     The deleted or trashed post.
      * @param WP_REST_Response $response The response data.
      * @param WP_REST_Request  $request  The request sent to the API.
      */
     do_action("rest_delete_{$this->post_type}", $post, $response, $request);
     return $response;
 }
 /**
  * Deletes a single revision.
  *
  * @since 4.7.0
  * @access public
  *
  * @param WP_REST_Request $request Full details about the request.
  * @return true|WP_Error True on success, or WP_Error object on failure.
  */
 public function delete_item($request)
 {
     $force = isset($request['force']) ? (bool) $request['force'] : false;
     // We don't support trashing for revisions.
     if (!$force) {
         return new WP_Error('rest_trash_not_supported', __('Revisions do not support trashing. Set force=true to delete.'), array('status' => 501));
     }
     $revision = get_post($request['id']);
     $previous = $this->prepare_item_for_response($revision, $request);
     $result = wp_delete_post($request['id'], true);
     /**
      * Fires after a revision is deleted via the REST API.
      *
      * @since 4.7.0
      *
      * @param (mixed) $result The revision object (if it was deleted or moved to the trash successfully)
      *                        or false (failure). If the revision was moved to to the trash, $result represents
      *                        its new state; if it was deleted, $result represents its state before deletion.
      * @param WP_REST_Request $request The request sent to the API.
      */
     do_action('rest_delete_revision', $result, $request);
     if (!$result) {
         return new WP_Error('rest_cannot_delete', __('The post cannot be deleted.'), array('status' => 500));
     }
     $response = new WP_REST_Response();
     $response->set_data(array('deleted' => true, 'previous' => $previous->get_data()));
     return $response;
 }
 /**
  * Deletes a single term from a taxonomy.
  *
  * @since 4.7.0
  * @access public
  *
  * @param WP_REST_Request $request Full details about the request.
  * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure.
  */
 public function delete_item($request)
 {
     $force = isset($request['force']) ? (bool) $request['force'] : false;
     // We don't support trashing for terms.
     if (!$force) {
         return new WP_Error('rest_trash_not_supported', __('Terms do not support trashing. Set force=true to delete.'), array('status' => 501));
     }
     $term = get_term((int) $request['id'], $this->taxonomy);
     $request->set_param('context', 'view');
     $previous = $this->prepare_item_for_response($term, $request);
     $retval = wp_delete_term($term->term_id, $term->taxonomy);
     if (!$retval) {
         return new WP_Error('rest_cannot_delete', __('The term cannot be deleted.'), array('status' => 500));
     }
     $response = new WP_REST_Response();
     $response->set_data(array('deleted' => true, 'previous' => $previous->get_data()));
     /**
      * Fires after a single term is deleted via the REST API.
      *
      * The dynamic portion of the hook name, `$this->taxonomy`, refers to the taxonomy slug.
      *
      * @since 4.7.0
      *
      * @param WP_Term          $term     The deleted term.
      * @param WP_REST_Response $response The response data.
      * @param WP_REST_Request  $request  The request sent to the API.
      */
     do_action("rest_delete_{$this->taxonomy}", $term, $response, $request);
     return $response;
 }
Esempio n. 27
-2
 /**
  * Sends a response, but also makes sure to attach headers that
  * are handy for debugging.
  * Specifically, we assume folks will want to know what exactly was the DB query that got run,
  * what exactly was the Models query that got run, what capabilities came into play, what fields were omitted from
  * the response, others?
  *
  * @param array|\WP_Error|\Exception $response
  * @return \WP_REST_Response
  */
 public function send_response($response)
 {
     if ($response instanceof \Exception) {
         $response = new \WP_Error($response->getCode(), $response->getMessage());
     }
     if ($response instanceof \WP_Error) {
         //we want to send a "normal"-looking WP error response, but we also
         //want to add headers. It doesn't seem WP API 1.2 supports this.
         //I'd like to use WP_JSON_Server::error_to_response() but its protected
         //so here's most of it copy-and-pasted :P
         $error_data = $response->get_error_data();
         if (is_array($error_data) && isset($error_data['status'])) {
             $status = $error_data['status'];
         } else {
             $status = 500;
         }
         $errors = array();
         foreach ((array) $response->errors as $code => $messages) {
             foreach ((array) $messages as $message) {
                 $errors[] = array('code' => $code, 'message' => $message, 'data' => $response->get_error_data($code));
             }
         }
         $data = isset($errors[0]) ? $errors[0] : array();
         if (count($errors) > 1) {
             // Remove the primary error.
             array_shift($errors);
             $data['additional_errors'] = $errors;
         }
         $rest_response = new \WP_REST_Response($data, $status);
     } else {
         $rest_response = new \WP_REST_Response($response, 200);
     }
     $headers = array();
     if ($this->_debug_mode && is_array($this->_debug_info)) {
         foreach ($this->_debug_info as $debug_key => $debug_info) {
             if (is_array($debug_info)) {
                 $debug_info = json_encode($debug_info);
             }
             $headers['X-EE4-Debug-' . ucwords($debug_key)] = $debug_info;
         }
     }
     $rest_response->set_headers($headers);
     return $rest_response;
 }
 /**
  * Prepare a response for inserting into a collection.
  *
  * @param WP_REST_Response $response Response object.
  * @return array Response data, ready for insertion into collection data.
  */
 public function prepare_response_for_collection($response)
 {
     if (!$response instanceof WP_REST_Response) {
         return $response;
     }
     $data = (array) $response->get_data();
     $server = rest_get_server();
     if (method_exists($server, 'get_compact_response_links')) {
         $links = call_user_func(array($server, 'get_compact_response_links'), $response);
     } else {
         $links = call_user_func(array($server, 'get_response_links'), $response);
     }
     if (!empty($links)) {
         $data['_links'] = $links;
     }
     return $data;
 }