public function test_get_items_orderby() { wp_set_object_terms($this->post_id, array('Banana', 'Carrot', 'Apple'), 'post_tag'); $request = new WP_REST_Request('GET', sprintf('/wp/v2/posts/%d/terms/tag', $this->post_id)); $request->set_param('orderby', 'term_order'); $response = $this->server->dispatch($request); $data = $response->get_data(); $this->assertEquals('Banana', $data[0]['name']); $this->assertEquals('Carrot', $data[1]['name']); $this->assertEquals('Apple', $data[2]['name']); $request = new WP_REST_Request('GET', sprintf('/wp/v2/posts/%d/terms/tag', $this->post_id)); $request->set_param('orderby', 'name'); $request->set_param('order', 'asc'); $response = $this->server->dispatch($request); $data = $response->get_data(); $this->assertEquals('Apple', $data[0]['name']); $this->assertEquals('Banana', $data[1]['name']); $this->assertEquals('Carrot', $data[2]['name']); $request = new WP_REST_Request('GET', sprintf('/wp/v2/posts/%d/terms/tag', $this->post_id)); $request->set_param('orderby', 'name'); $request->set_param('order', 'desc'); $response = $this->server->dispatch($request); $data = $response->get_data(); $this->assertEquals('Carrot', $data[0]['name']); $this->assertEquals('Banana', $data[1]['name']); $this->assertEquals('Apple', $data[2]['name']); }
/** * Verify sessions nonce * * @since 0.3.0 * * @param \WP_REST_Request $request Full data about the request. * * @return \WP_Error|\WP_REST_Response */ public static function verify_session_nonce($request) { $nonce = $request->get_param('ingot_session_nonce'); if (is_string($nonce)) { return ingot_verify_session_nonce($nonce); } }
function save_settings(WP_REST_Request $data) { $keys = $data->get_params(); if (isset($keys['mode'])) { update_option('stripe_wp_mode', $keys['mode']); } if (isset($keys['keys']['test'])) { update_option('stripe_wp_test_key', $keys['keys']['test']); } if (isset($keys['keys']['prod'])) { update_option('stripe_wp_live_key', $keys['keys']['prod']); } if (isset($keys['confirmation']['type'])) { update_option('stripe_wp_confirmation_type', $keys['confirmation']['type']); } if (isset($keys['confirmation']['page_id'])) { update_option('stripe_wp_confirmation_page', $keys['confirmation']['page_id']); } if (isset($keys['confirmation']['message'])) { update_option('stripe_wp_confirmation_message', $keys['confirmation']['message']); } $settings['mode'] = get_option('stripe_wp_mode', false); $settings['keys']['prod'] = get_option('stripe_wp_live_key', false); $settings['keys']['test'] = get_option('stripe_wp_test_key', false); $settings['confirmation']['type'] = get_option('stripe_wp_confirmation_type', false); $settings['confirmation']['page_id'] = get_option('stripe_wp_confirmation_page', false); $settings['confirmation']['message'] = get_option('stripe_wp_confirmation_message', false); return new WP_REST_Response($settings, 200); }
public function test_get_taxonomies_with_types() { $request = new WP_REST_Request('GET', '/wp/v2/taxonomies'); $request->set_param('post_type', 'post'); $response = $this->server->dispatch($request); $this->check_taxonomies_for_type_response('post', $response); }
/** * Retrieve the current event queue * * @subcommand get-queue */ public function get_queue($args, $assoc_args) { // Build and make request $queue_request = new \WP_REST_Request('POST', '/' . \Automattic\WP\Cron_Control\REST_API::API_NAMESPACE . '/' . \Automattic\WP\Cron_Control\REST_API::ENDPOINT_LIST); $queue_request->add_header('Content-Type', 'application/json'); $queue_request->set_body(wp_json_encode(array('secret' => \WP_CRON_CONTROL_SECRET))); $queue_request = rest_do_request($queue_request); // Oh well if ($queue_request->is_error()) { \WP_CLI::error($queue_request->as_error()->get_error_message()); } // Get the decoded JSON object returned by the API $queue_response = $queue_request->get_data(); // No events, nothing more to do if (empty($queue_response['events'])) { \WP_CLI::warning(__('No events in the current queue', 'automattic-cron-control')); return; } // Prepare items for display $events_for_display = $this->format_events($queue_response['events']); $total_events_to_display = count($events_for_display); \WP_CLI::line(sprintf(_n('Displaying one event', 'Displaying %s events', $total_events_to_display, 'automattic-cron-control'), number_format_i18n($total_events_to_display))); // And reformat $format = 'table'; if (isset($assoc_args['format'])) { if ('ids' === $assoc_args['format']) { \WP_CLI::error(__('Invalid output format requested', 'automattic-cron-control')); } else { $format = $assoc_args['format']; } } \WP_CLI\Utils\format_items($format, $events_for_display, array('timestamp', 'action', 'instance', 'scheduled_for', 'internal_event', 'schedule_name', 'event_args')); }
function delete_plan(WP_REST_Request $request) { $this->set_api_key(); $data = $request->get_params(); if (!isset($data['id'])) { return new WP_Error('data', __('No Customer ID Set'), array('status' => 404)); } try { $plan = \Stripe\Plan::retrieve($data['id']); $plan->delete(); return new WP_REST_Response($plan, 200); } catch (Stripe_AuthenticationError $e) { $body = $e->getJsonBody(); $err = $body['error']; return new WP_Error($err['type'], __($err['message']), array('status' => 403)); } catch (Stripe_Error $e) { $body = $e->getJsonBody(); $err = $body['error']; return new WP_Error($err['type'], __($err['message']), array('status' => 403)); } catch (\Stripe\Error\Base $e) { $body = $e->getJsonBody(); $err = $body['error']; return new WP_Error($err['type'], __($err['message']), array('status' => 403)); } }
public function test_get_items() { $request = new WP_REST_Request('GET', '/wp/v2/users'); $request->set_param('context', 'view'); $response = $this->server->dispatch($request); $this->assertEquals(200, $response->get_status()); }
function save_book(WP_REST_Request $data) { /* * Check if ID set & set $post */ if (!$data['ID']) { return new WP_Error('noID', __('No Book ID', 'js-app-plugin')); } $post = $data->get_params(); $meta = $post['meta']; unset($post[0]); /* * Save Post */ $book['save'] = wp_update_post($post, true); if (is_wp_error($book['save'])) { return new WP_Error('saveError', __($book['save']->get_error_messages(), 'js-app-plugin')); } /* * Save Post Meta */ foreach ($meta as $key => $value) { $book['meta-' . $key] = update_post_meta($post['ID'], $key, $value[0]); } /* * Get post and return */ $book['post'] = get_post($post['ID']); $book['post']->meta = get_post_meta($post['ID']); return new WP_REST_Response($book, 200); }
/** * Toggles whether the user is checked in or not. * * @param \WP_REST_Request $request * @return \WP_Error|\WP_REST_Response */ protected function _create_checkin_checkout_object(\WP_REST_Request $request) { $reg_id = $request->get_param('REG_ID'); $dtt_id = $request->get_param('DTT_ID'); $force = $request->get_param('force'); if ($force == 'true') { $force = true; } else { $force = false; } $reg = \EEM_Registration::instance()->get_one_by_ID($reg_id); if (!$reg instanceof \EE_Registration) { return $this->send_response(new \WP_Error('rest_registration_toggle_checkin_invalid_id', sprintf(__('You cannot checkin registration with ID %1$s because it doesn\'t exist.', 'event_espresso'), $reg_id), array('status' => 422))); } if (!\EE_Capabilities::instance()->current_user_can('ee_edit_checkin', 'rest_api_checkin_endpoint', $reg_id)) { return $this->send_response(new \WP_Error('rest_user_cannot_toggle_checkin', sprintf(__('You are not allowed to checkin registration with ID %1$s.', 'event_espresso'), $reg_id), array('status' => 403))); } $success = $reg->toggle_checkin_status($dtt_id, !$force); if ($success === false) { //rely on EE_Error::add_error messages to have been added to give more data about hwy it failed return $this->send_response(new \WP_Error('rest_toggle_checkin_failed', __('Registration checkin failed. Please see additional error data.', 'event_espresso'))); } $checkin = \EEM_Checkin::instance()->get_one(array(array('REG_ID' => $reg_id, 'DTT_ID' => $dtt_id), 'order_by' => array('CHK_timestamp' => 'DESC'))); if (!$checkin instanceof \EE_Checkin) { return $this->send_response(new \WP_Error('rest_toggle_checkin_error', sprintf(__('Supposedly we created a new checkin object for registration %1$s at datetime %2$s, but we can\'t find it.', 'event_espresso'), $reg_id, $dtt_id))); } $requested_version = $this->get_requested_version($request->get_route()); $get_request = new \WP_REST_Request('GET', \EED_Core_Rest_Api::ee_api_namespace . $requested_version . '/checkins/' . $checkin->ID()); $get_request->set_url_params(array('id' => $checkin->ID())); return Read::handle_request_get_one($get_request); }
public function e_tags(WP_REST_Request $request) { $id = $request->get_param("id"); if (empty($id)) { return get_tags(); } return wp_get_post_tags($id); }
function verify_admin(WP_REST_Request $request) { $data = $request->get_params(); if (!$this->verify_nonce($data)) { return false; } return current_user_can('edit_theme_options'); }
/** * Save new graph data to WordPress * @param WP_REST_Request $request The request containing the updated data * @return WP_REST_Response */ public function update_items(\WP_REST_Request $request) { $params = $request->get_params(); // First pass to create all new nodes and replace their temp ID with their true ID if (is_array($params['newNodeIndexes'])) { foreach ($params['newNodeIndexes'] as $nodeIndex) { $postID = ''; $oldPostID = $params['nodes'][$nodeIndex]['id']; switch ($params['nodes'][$nodeIndex]['type']) { case 'life': case 'perk': $postID = DataController::getInstance()->getCPT('point-node')->create($params['nodes'][$nodeIndex]); break; } $params['nodes'][$nodeIndex]['id'] = $postID; // Replace all instances of the temp ID with the newly inserted one in link data if (is_array($params['links'])) { foreach ($params['links'] as &$link) { if ($link[0] == $oldPostID) { $link[0] = $postID; } if ($link[1] == $oldPostID) { $link[1] = $postID; } } } } } // Update all data on all nodes foreach ($params['nodes'] as $node) { $links = $this->get_linked_nodes_from_id($node['id'], $params['links']); switch ($node['type']) { // Skill nodes case 'skill': DataController::getInstance()->getCPT('skill')->update_skill_graph_data($node, $links); break; // Upgrade nodes // Upgrade nodes case 'upgrade': DataController::getInstance()->getCPT('skill')->update_upgrade_graph_data($node, $links); break; // Point nodes // Point nodes case 'life': case 'perk': DataController::getInstance()->getCPT('point-node')->update_graph_data($node, $links); break; } } // Delete removed nodes if (is_array($params['deletedNodes'])) { foreach ($params['deletedNodes'] as $node) { wp_delete_post($node, true); } } return new \WP_REST_Response('Zodiaque sauvegardé avec succès!', 200); }
function push_key(WP_REST_Request $request) { $post_id = $request->get_param('post_id'); $nonce = $request->get_param('nonce'); $key = $request->get_param('key'); if (!wp_verify_nonce($nonce, 'register_' . $key)) { return new WP_Error('registration', 'Validation Fail', array('status' => 404)); } return update_post_meta($post_id, 'push_key', $key); }
public static function handle_request_models_meta(\WP_REST_Request $request) { $controller = new Meta(); $matches = $controller->parse_route($request->get_route(), '~' . \EED_Core_Rest_Api::ee_api_namespace_for_regex . 'resources~', array('version')); if ($matches instanceof \WP_REST_Response) { return $matches; } $controller->set_requested_version($matches['version']); return $controller->send_response($controller->_get_models_metadata_entity()); }
/** * @test * it should return true if current user can edit post */ public function it_should_return_true_if_current_user_can_edit_post() { $post_id = $this->factory()->post->create(); wp_set_current_user(1); $sut = $this->make_instance(); $supported_actions = $sut->supported_actions(); $request = new \WP_REST_Request('create', '/some-path'); $request->set_param('post_id', $post_id); $out = $sut->verify_auth($request, reset($supported_actions)); $this->assertTrue($out); }
/** * Test we can update both description and title */ public function test_update_both() { wp_set_current_user($this->editor_id); $request = new WP_REST_Request('POST', sprintf('/wp/v2/posts/%d', $this->post_id)); $request->set_body_params(array('_yoast_wpseo_title' => '1 2 3', '_yoast_wpseo_metadesc' => '4 5 6')); $response = $this->server->dispatch($request); $this->assertNotInstanceOf('WP_Error', $response); $response = rest_ensure_response($response); $this->assertEquals(200, $response->get_status()); $this->assertEquals('1 2 3', get_post_meta($this->post_id, '_yoast_wpseo_title', true)); $this->assertEquals('4 5 6', get_post_meta($this->post_id, '_yoast_wpseo_metadesc', true)); }
/** * Get one form * * @param \WP_REST_Request $request Full data about the request. * @return \WP_Error|\WP_REST_Response */ public function get_form($request) { $form_id = $request; if ($request instanceof \WP_REST_Request) { $form_id = $request->get_param('id'); } $form = \Caldera_Forms::get_form($form_id); if (null === $form) { return new \WP_Error('invalid_form_id', __('Invalid Form ID', 'caldera-forms')); } return new \WP_REST_Response($form, 200); }
/** * Do search and respond. * * @since 0.0.1 * * @param \WP_REST_Request $request * * @return \WP_REST_Response|WP_Error */ public function the_search($request) { $args = (array) $request->get_params(); $search = new \SWP_Query($args); $query_result = $search->posts; $posts = array(); foreach ($query_result as $post) { $data = $this->prepare_item_for_response($post, $request); $posts[] = $this->prepare_response_for_collection($data); } $response = rest_ensure_response($posts); return $response; }
/** * * @param WP_REST_Request $request - See WC_Connect_API_Client::get_label_rates() * @return array|WP_Error */ public function update_items($request) { $request_body = $request->get_body(); $payload = json_decode($request_body, true, WOOCOMMERCE_CONNECT_MAX_JSON_DECODE_DEPTH); // Hardcode USPS rates for now $payload['carrier'] = 'usps'; $response = $this->api_client->get_label_rates($payload); if (is_wp_error($response)) { $error = new WP_Error($response->get_error_code(), $response->get_error_message(), array('message' => $response->get_error_message())); $this->logger->log($error, __CLASS__); return $error; } return array('success' => true, 'rates' => property_exists($response, 'rates') ? $response->rates : new stdClass()); }
/** * Get one item from the collection * * @param WP_REST_Request $request Full data about the request. * @return WP_Error|WP_REST_Response */ public function get_item($request) { //get parameters from request $params = $request->get_params(); $item = get_post($params['id']); //do a query, call another class, etc $data = $this->prepare_item_for_response($item, $request); //return a response or error based on some conditional if (1 == 1) { return new WP_REST_Response($data, 200); } else { return new WP_Error('code', __('message', 'text-domain')); } }
/** * Get all graph data items * @param WP_REST_Request $request The current request * @return Array|WP_Error */ public function get_items($request) { $result = array(); // Fetch all skills $request->set_param('per_page', -1); $allSkills = parent::get_items($request); // Filter all skills to only return the ones tagged as starting skills foreach ($allSkills->data as $skill) { if ($skill['starting_skill']) { $result[] = $skill; } } return $result; }
/** * Get all products from an ecommerce plugin * * @since 0.2.0 * * @param \WP_REST_Request $request Full data about the request. * @return \WP_Error|\WP_REST_Response */ public function get_items($request) { $plugin = $request->get_param('plugin'); if (!in_array($plugin, ingot_accepted_plugins_for_price_tests())) { return new \WP_Error('ingot-invalid-plugin'); } if ('woo' == $plugin) { $products = $this->get_all_woo(); } elseif ('edd' == $plugin) { $products = $this->get_all_edd(); } else { $products = array(); } return rest_ensure_response($products); }
function code_check(WP_REST_Request $request) { $data = $request->get_params(); if (!$data['code']) { return new WP_Error('no code', __('you need to pass a code to check'), array('status' => 401)); } $users = new WP_User_Query(array('meta_query' => array(array('key' => '__stripe-wp-referral-code', 'value' => $data['code'])))); if (!empty($users->results)) { $user_id = $users->results[0]->ID; $return = array('code_valid' => true, 'user' => $user_id, 'cus_id' => get_user_meta($user_id, '__stripe_cus_id', true)); } else { $return = array('code_valid' => false); } return new WP_REST_Response($return, 200); }
function test_rest_pre_serve_request_headers() { if (!function_exists('xdebug_get_headers')) { $this->markTestSkipped('xdebug is required for this test'); } $post = $this->factory()->post->create_and_get(array('post_title' => 'Hello World')); $request = new WP_REST_Request('GET', '/oembed/1.0/embed'); $request->set_param('url', get_permalink($post->ID)); $request->set_param('format', 'xml'); $server = new WP_REST_Server(); $response = $server->dispatch($request); $output = get_echo('_oembed_rest_pre_serve_request', array(true, $response, $request, $server)); $this->assertNotEmpty($output); $headers = xdebug_get_headers(); $this->assertTrue(in_array('Content-Type: text/xml; charset=' . get_option('blog_charset'), $headers)); }
/** * Test that list endpoint returns expected format */ public function test_run_event() { $ev = Utils::create_test_event(); $ev['action'] = md5($ev['action']); $ev['instance'] = md5(maybe_serialize($ev['args'])); $ev['secret'] = \WP_CRON_CONTROL_SECRET; unset($ev['args']); $request = new \WP_REST_Request('PUT', '/' . \Automattic\WP\Cron_Control\REST_API::API_NAMESPACE . '/' . \Automattic\WP\Cron_Control\REST_API::ENDPOINT_RUN); $request->set_body(wp_json_encode($ev)); $request->set_header('content-type', 'application/json'); $response = $this->server->dispatch($request); $data = $response->get_data(); $this->assertResponseStatus(200, $response); $this->assertArrayHasKey('success', $data); $this->assertArrayHasKey('message', $data); }
/** * Get a list of a table's records' IDs and titles, filtered by * `$_GET['term']`, for foreign-key fields. Only used when there are more * than N records in a foreign table (otherwise the options are presented in * a select list). * @param \WP_REST_Request $request The request, with a 'table_name' parameter. * @return array */ public function foreign_key_values(\WP_REST_Request $request) { if (!isset($this->get['term'])) { return array(); } $db = new Database($this->wpdb); $table = $db->getTable($request->get_param('table_name')); if (!$table instanceof Table) { return array(); } // First get any exact matches. $out = $this->foreign_key_values_build($table, '=', $this->get['term']); // Then get any 'contains' matches. $out += $this->foreign_key_values_build($table, 'like', '%' . $this->get['term'] . '%'); return $out; }
function uoltt_api_v1_get_ship(WP_REST_Request $request) { global $scdb; $ships = $scdb->get_results("SELECT * FROM ships", ARRAY_A); $ships_arr = array(); for ($i = 0; $i < sizeof($ships); $i++) { $name = strtolower(str_replace(" ", "_", $ships[$i]['shipname'])); $ships_arr[$name] = $ships[$i]; } $shipname = urldecode($request->get_param('shipname')); $shipname = strtolower(str_replace(" ", "_", $shipname)); if (isset($ships_arr[$shipname])) { return array($ships_arr[$shipname]['shipname'] => $ships_arr[$shipname]); } else { return new WP_Error('uoltt_api_v1_not_found', "Ship " . $request->get_param('shipname') . " not found", array('status' => 404)); } }
/** * Create a form for testing * * @param array $fields * @since 6.0 * @return object */ public function _createForm($fields = array(array('type' => 'single-line-text')), $settings = array()) { $i = 1; foreach ($fields as &$field) { $field = wp_parse_args($field, $this->default_field); $field['label'] .= ' ' . $i; $field['value'] .= ' ' . $i; $field['placeholder'] .= ' ' . $i; $field['slug'] .= $i; $field['className'] .= $i; $i++; } $data = wp_parse_args($settings, array('fields' => $fields, 'type' => 'ccf_form', 'status' => 'publish', 'ID' => null, 'title' => array('raw' => 'Test Form'), 'description' => 'Test form description', 'buttonText' => 'Submit Text', 'buttonClass' => '', 'notifications' => array(), 'postCreation' => false, 'postCreationType' => 'post', 'postCreationStatus' => 'draft', 'postFieldMappings' => array(), 'author' => array(), 'excerpt' => '', 'link' => '', 'parent' => 0, 'format' => 'standard', 'slug' => '', 'guid' => '', 'comment_status' => 'open', 'ping_status' => 'open', 'menu_order' => 0, 'terms' => array(), 'post_meta' => array(), 'meta' => array('links' => array()), 'ping_status' => false, 'featured_image' => null)); $request = new WP_REST_Request(); $request->set_body(json_encode($data)); return $this->api->create_item($request); }
/** * Update one item from the collection * * @param \WP_REST_Request $request Full data about the request. * * @return \WP_Error|\WP_REST_Request */ public function update_item($request) { //$item = $this->prepare_item_for_database( $request ); $params = $request->get_params(); $id = intval($params[0]); if (!array_key_exists($id, self::$switches)) { return new \WP_Error('cant-update', __('message', 'particle-api'), array('status' => 500)); } $json = json_decode($request->get_body()); $status = isset($json->status) ? $json->status : null; $data = new \stdClass(); update_option(self::$switches[$id], $status); $data->status = $status; if (is_object($data)) { return new \WP_REST_Response($data, 200); } return new \WP_Error('cant-update', __('message', 'particle-api'), array('status' => 500)); }
/** * Update one item from the collection * * @param \WP_REST_Request $request Full data about the request. * * @return \WP_Error|\WP_REST_Request */ public function update_item($request) { $params = $request->get_params(); $color = $params[0]; if (!array_key_exists($color, self::$lights)) { return new \WP_Error('cant-update', __('message', 'particle-api'), array('status' => 500)); } $json = json_decode($request->get_body()); $status = isset($json->status) ? $json->status : null; $string_status = $status ? 'true' : 'false'; $data = new \stdClass(); update_option(self::$lights[$color], $string_status); $data->status = $status; if (is_object($data)) { return new \WP_REST_Response($data, 200); } return new \WP_Error('cant-update', __('message', 'particle-api'), array('status' => 500)); }