'default' => $route_namespace, ), 'context' => array( 'default' => 'view', ), ), ), ) ); } // Associative to avoid double-registration. $this->namespaces[ $route_namespace ][ $route ] = true; $route_args['namespace'] = $route_namespace; if ( $override || empty( $this->endpoints[ $route ] ) ) { $this->endpoints[ $route ] = $route_args; } else { $this->endpoints[ $route ] = array_merge( $this->endpoints[ $route ], $route_args ); } } /** * Retrieves the route map. * * The route map is an associative array with path regexes as the keys. The * value is an indexed array with the callback function/method as the first * item, and a bitmask of HTTP methods as the second item (see the class * constants). * * Each route can be mapped to more than one callback by using an array of * the indexed arrays. This allows mapping e.g. GET requests to one callback * and POST requests to another. * * Note that the path regexes (array keys) must have @ escaped, as this is * used as the delimiter with preg_match() * * @since 4.4.0 * @since 5.4.0 Added `$route_namespace` parameter. * * @param string $route_namespace Optionally, only return routes in the given namespace. * @return array `'/path/regex' => array( $callback, $bitmask )` or * `'/path/regex' => array( array( $callback, $bitmask ), ...)`. */ public function get_routes( $route_namespace = '' ) { $endpoints = $this->endpoints; if ( $route_namespace ) { $endpoints = wp_list_filter( $endpoints, array( 'namespace' => $route_namespace ) ); } /** * Filters the array of available REST API endpoints. * * @since 4.4.0 * * @param array $endpoints The available endpoints. An array of matching regex patterns, each mapped * to an array of callbacks for the endpoint. These take the format * `'/path/regex' => array( $callback, $bitmask )` or * `'/path/regex' => array( array( $callback, $bitmask ). */ $endpoints = apply_filters( 'rest_endpoints', $endpoints ); // Normalize the endpoints. $defaults = array( 'methods' => '', 'accept_json' => false, 'accept_raw' => false, 'show_in_index' => true, 'args' => array(), ); foreach ( $endpoints as $route => &$handlers ) { if ( isset( $handlers['callback'] ) ) { // Single endpoint, add one deeper. $handlers = array( $handlers ); } if ( ! isset( $this->route_options[ $route ] ) ) { $this->route_options[ $route ] = array(); } foreach ( $handlers as $key => &$handler ) { if ( ! is_numeric( $key ) ) { // Route option, move it to the options. $this->route_options[ $route ][ $key ] = $handler; unset( $handlers[ $key ] ); continue; } $handler = wp_parse_args( $handler, $defaults ); // Allow comma-separated HTTP methods. if ( is_string( $handler['methods'] ) ) { $methods = explode( ',', $handler['methods'] ); } elseif ( is_array( $handler['methods'] ) ) { $methods = $handler['methods']; } else { $methods = array(); } $handler['methods'] = array(); foreach ( $methods as $method ) { $method = strtoupper( trim( $method ) ); $handler['methods'][ $method ] = true; } } } return $endpoints; } /** * Retrieves namespaces registered on the server. * * @since 4.4.0 * * @return string[] List of registered namespaces. */ public function get_namespaces() { return array_keys( $this->namespaces ); } /** * Retrieves specified options for a route. * * @since 4.4.0 * * @param string $route Route pattern to fetch options for. * @return array|null Data as an associative array if found, or null if not found. */ public function get_route_options( $route ) { if ( ! isset( $this->route_options[ $route ] ) ) { return null; } return $this->route_options[ $route ]; } /** * Matches the request to a callback and call it. * * @since 4.4.0 * * @param WP_REST_Request $request Request to attempt dispatching. * @return WP_REST_Response Response returned by the callback. */ public function dispatch( $request ) { /** * Filters the pre-calculated result of a REST API dispatch request. * * Allow hijacking the request before dispatching by returning a non-empty. The returned value * will be used to serve the request instead. * * @since 4.4.0 * * @param mixed $result Response to replace the requested version with. Can be anything * a normal endpoint can return, or null to not hijack the request. * @param WP_REST_Server $server Server instance. * @param WP_REST_Request $request Request used to generate the response. */ $result = apply_filters( 'rest_pre_dispatch', null, $this, $request ); if ( ! empty( $result ) ) { // Normalize to either WP_Error or WP_REST_Response... $result = rest_ensure_response( $result ); // ...then convert WP_Error across. if ( is_wp_error( $result ) ) { $result = $this->error_to_response( $result ); } return $result; } $error = null; $matched = $this->match_request_to_handler( $request ); if ( is_wp_error( $matched ) ) { return $this->error_to_response( $matched ); } list( $route, $handler ) = $matched; if ( ! is_callable( $handler['callback'] ) ) { $error = new WP_Error( 'rest_invalid_handler', __( 'The handler for the route is invalid.' ), array( 'status' => 500 ) ); } if ( ! is_wp_error( $error ) ) { $check_required = $request->has_valid_params(); if ( is_wp_error( $check_required ) ) { $error = $check_required; } else { $check_sanitized = $request->sanitize_params(); if ( is_wp_error( $check_sanitized ) ) { $error = $check_sanitized; } } } return $this->respond_to_request( $request, $route, $handler, $error ); } /** * Matches a request object to its handler. * * @access private * @since 5.6.0 * * @param WP_REST_Request $request The request object. * @return array|WP_Error The route and request handler on success or a WP_Error instance if no handler was found. */ protected function match_request_to_handler( $request ) { $method = $request->get_method(); $path = $request->get_route(); $with_namespace = array(); foreach ( $this->get_namespaces() as $namespace ) { if ( str_starts_with( trailingslashit( ltrim( $path, '/' ) ), $namespace ) ) { $with_namespace[] = $this->get_routes( $namespace ); } } if ( $with_namespace ) { $routes = array_merge( ...$with_namespace ); } else { $routes = $this->get_routes(); } foreach ( $routes as $route => $handlers ) { $match = preg_match( '@^' . $route . '$@i', $path, $matches ); if ( ! $match ) { continue; } $args = array(); foreach ( $matches as $param => $value ) { if ( ! is_int( $param ) ) { $args[ $param ] = $value; } } foreach ( $handlers as $handler ) { $callback = $handler['callback']; $response = null; // Fallback to GET method if no HEAD method is registered. $checked_method = $method; if ( 'HEAD' === $method && empty( $handler['methods']['HEAD'] ) ) { $checked_method = 'GET'; } if ( empty( $handler['methods'][ $checked_method ] ) ) { continue; } if ( ! is_callable( $callback ) ) { return array( $route, $handler ); } $request->set_url_params( $args ); $request->set_attributes( $handler ); $defaults = array(); foreach ( $handler['args'] as $arg => $options ) { if ( isset( $options['default'] ) ) { $defaults[ $arg ] = $options['default']; } } $request->set_default_params( $defaults ); return array( $route, $handler ); } } return new WP_Error( 'rest_no_route', __( 'No route was found matching the URL and request method.' ), array( 'status' => 404 ) ); } /** * Dispatches the request to the callback handler. * * @access private * @since 5.6.0 * * @param WP_REST_Request $request The request object. * @param string $route The matched route regex. * @param array $handler The matched route handler. * @param WP_Error|null $response The current error object if any. * @return WP_REST_Response */ protected function respond_to_request( $request, $route, $handler, $response ) { /** * Filters the response before executing any REST API callbacks. * * Allows plugins to perform additional validation after a * request is initialized and matched to a registered route, * but before it is executed. * * Note that this filter will not be called for requests that * fail to authenticate or match to a registered route. * * @since 4.7.0 * * @param WP_REST_Response|WP_HTTP_Response|WP_Error|mixed $response Result to send to the client. * Usually a WP_REST_Response or WP_Error. * @param array $handler Route handler used for the request. * @param WP_REST_Request $request Request used to generate the response. */ $response = apply_filters( 'rest_request_before_callbacks', $response, $handler, $request ); // Check permission specified on the route. if ( ! is_wp_error( $response ) && ! empty( $handler['permission_callback'] ) ) { $permission = call_user_func( $handler['permission_callback'], $request ); if ( is_wp_error( $permission ) ) { $response = $permission; } elseif ( false === $permission || null === $permission ) { $response = new WP_Error( 'rest_forbidden', __( 'Sorry, you are not allowed to do that.' ), array( 'status' => rest_authorization_required_code() ) ); } } if ( ! is_wp_error( $response ) ) { /** * Filters the REST API dispatch request result. * * Allow plugins to override dispatching the request. * * @since 4.4.0 * @since 4.5.0 Added `$route` and `$handler` parameters. * * @param mixed $dispatch_result Dispatch result, will be used if not empty. * @param WP_REST_Request $request Request used to generate the response. * @param string $route Route matched for the request. * @param array $handler Route handler used for the request. */ $dispatch_result = apply_filters( 'rest_dispatch_request', null, $request, $route, $handler ); // Allow plugins to halt the request via this filter. if ( null !== $dispatch_result ) { $response = $dispatch_result; } else { $response = call_user_func( $handler['callback'], $request ); } } /** * Filters the response immediately after executing any REST API * callbacks. * * Allows plugins to perform any needed cleanup, for example, * to undo changes made during the {@see 'rest_request_before_callbacks'} * filter. * * Note that this filter will not be called for requests that * fail to authenticate or match to a registered route. * * Note that an endpoint's `permission_callback` can still be * called after this filter - see `rest_send_allow_header()`. * * @since 4.7.0 * * @param WP_REST_Response|WP_HTTP_Response|WP_Error|mixed $response Result to send to the client. * Usually a WP_REST_Response or WP_Error. * @param array $handler Route handler used for the request. * @param WP_REST_Request $request Request used to generate the response. */ $response = apply_filters( 'rest_request_after_callbacks', $response, $handler, $request ); if ( is_wp_error( $response ) ) { $response = $this->error_to_response( $response ); } else { $response = rest_ensure_response( $response ); } $response->set_matched_route( $route ); $response->set_matched_handler( $handler ); return $response; } /** * Returns if an error occurred during most recent JSON encode/decode. * * Strings to be translated will be in format like * "Encoding error: Maximum stack depth exceeded". * * @since 4.4.0 * * @return false|string Boolean false or string error message. */ protected function get_json_last_error() { $last_error_code = json_last_error(); if ( JSON_ERROR_NONE === $last_error_code || empty( $last_error_code ) ) { return false; } return json_last_error_msg(); } /** * Retrieves the site index. * * This endpoint describes the capabilities of the site. * * @since 4.4.0 * * @param array $request { * Request. * * @type string $context Context. * } * @return WP_REST_Response The API root index data. */ 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(), 'gmt_offset' => get_option( 'gmt_offset' ), 'timezone_string' => get_option( 'timezone_string' ), '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', 'https://developer.wordpress.org/rest-api/' ); $this->add_active_theme_link_to_index( $response ); $this->add_site_logo_to_index( $response ); $this->add_site_icon_to_index( $response ); /** * Filters the REST 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 * @since 6.0.0 Added `$request` parameter. * * @param WP_REST_Response $response Response data. * @param WP_REST_Request $request Request data. */ return apply_filters( 'rest_index', $response, $request ); } /** * Adds a link to the active theme for users who have proper permissions. * * @since 5.7.0 * * @param WP_REST_Response $response REST API response. */ protected function add_active_theme_link_to_index( WP_REST_Response $response ) { $should_add = current_user_can( 'switch_themes' ) || current_user_can( 'manage_network_themes' ); if ( ! $should_add && current_user_can( 'edit_posts' ) ) { $should_add = true; } if ( ! $should_add ) { foreach ( get_post_types( array( 'show_in_rest' => true ), 'objects' ) as $post_type ) { if ( current_user_can( $post_type->cap->edit_posts ) ) { $should_add = true; break; } } } if ( $should_add ) { $theme = wp_get_theme(); $response->add_link( 'https://api.w.org/active-theme', rest_url( 'wp/v2/themes/' . $theme->get_stylesheet() ) ); } } /** * Exposes the site logo through the WordPress REST API. * * This is used for fetching this information when user has no rights * to update settings. * * @since 5.8.0 * * @param WP_REST_Response $response REST API response. */ protected function add_site_logo_to_index( WP_REST_Response $response ) { $site_logo_id = get_theme_mod( 'custom_logo', 0 ); $this->add_image_to_index( $response, $site_logo_id, 'site_logo' ); } /** * Exposes the site icon through the WordPress REST API. * * This is used for fetching this information when user has no rights * to update settings. * * @since 5.9.0 * * @param WP_REST_Response $response REST API response. */ protected function add_site_icon_to_index( WP_REST_Response $response ) { $site_icon_id = get_option( 'site_icon', 0 ); $this->add_image_to_index( $response, $site_icon_id, 'site_icon' ); $response->data['site_icon_url'] = get_site_icon_url(); } /** * Exposes an image through the WordPress REST API. * This is used for fetching this information when user has no rights * to update settings. * * @since 5.9.0 * * @param WP_REST_Response $response REST API response. * @param int $image_id Image attachment ID. * @param string $type Type of Image. */ protected function add_image_to_index( WP_REST_Response $response, $image_id, $type ) { $response->data[ $type ] = (int) $image_id; if ( $image_id ) { $response->add_link( 'https://api.w.org/featuredmedia', rest_url( rest_get_route_for_post( $image_id ) ), array( 'embeddable' => true, 'type' => $type, ) ); } } /** * Retrieves the index for a namespace. * * @since 4.4.0 * * @param WP_REST_Request $request REST request instance. * @return WP_REST_Response|WP_Error WP_REST_Response instance if the index was found, * WP_Error if the namespace isn't set. */ public function get_namespace_index( $request ) { $namespace = $request['namespace']; if ( ! isset( $this->namespaces[ $namespace ] ) ) { return new WP_Error( 'rest_invalid_namespace', __( 'The specified namespace could not be found.' ), array( 'status' => 404 ) ); } $routes = $this->namespaces[ $namespace ]; $endpoints = array_intersect_key( $this->get_routes(), $routes ); $data = array( 'namespace' => $namespace, 'routes' => $this->get_data_for_routes( $endpoints, $request['context'] ), ); $response = rest_ensure_response( $data ); // Link to the root index. $response->add_link( 'up', rest_url( '/' ) ); /** * Filters the REST API namespace index data. * * This typically is just the route data for the namespace, but you can * add any data you'd like here. * * @since 4.4.0 * * @param WP_REST_Response $response Response data. * @param WP_REST_Request $request Request data. The namespace is passed as the 'namespace' parameter. */ return apply_filters( 'rest_namespace_index', $response, $request ); } /** * Retrieves the publicly-visible data for routes. * * @since 4.4.0 * * @param array $routes Routes to get data for. * @param string $context Optional. Context for data. Accepts 'view' or 'help'. Default 'view'. * @return array[] Route data to expose in indexes, keyed by route. */ public function get_data_for_routes( $routes, $context = 'view' ) { $available = array(); // Find the available routes. foreach ( $routes as $route => $callbacks ) { $data = $this->get_data_for_route( $route, $callbacks, $context ); if ( empty( $data ) ) { continue; } /** * Filters the publicly-visible data for a single REST API route. * * @since 4.4.0 * * @param array $data Publicly-visible data for the route. */ $available[ $route ] = apply_filters( 'rest_endpoints_description', $data ); } /** * Filters the publicly-visible data for REST API routes. * * This data is exposed on indexes and can be used by clients or * developers to investigate the site and find out how to use it. It * acts as a form of self-documentation. * * @since 4.4.0 * * @param array[] $available Route data to expose in indexes, keyed by route. * @param array $routes Internal route data as an associative array. */ return apply_filters( 'rest_route_data', $available, $routes ); } /** * Retrieves publicly-visible data for the route. * * @since 4.4.0 * * @param string $route Route to get data for. * @param array $callbacks Callbacks to convert to data. * @param string $context Optional. Context for the data. Accepts 'view' or 'help'. Default 'view'. * @return array|null Data for the route, or null if no publicly-visible data. */ public function get_data_for_route( $route, $callbacks, $context = 'view' ) { $data = array( 'namespace' => '', 'methods' => array(), 'endpoints' => array(), ); $allow_batch = false; if ( isset( $this->route_options[ $route ] ) ) { $options = $this->route_options[ $route ]; if ( isset( $options['namespace'] ) ) { $data['namespace'] = $options['namespace']; } $allow_batch = isset( $options['allow_batch'] ) ? $options['allow_batch'] : false; if ( isset( $options['schema'] ) && 'help' === $context ) { $data['schema'] = call_user_func( $options['schema'] ); } } $allowed_schema_keywords = array_flip( rest_get_allowed_schema_keywords() ); $route = preg_replace( '#\(\?P<(\w+?)>.*?\)#', '{$1}', $route ); foreach ( $callbacks as $callback ) { // Skip to the next route if any callback is hidden. if ( empty( $callback['show_in_index'] ) ) { continue; } $data['methods'] = array_merge( $data['methods'], array_keys( $callback['methods'] ) ); $endpoint_data = array( 'methods' => array_keys( $callback['methods'] ), ); $callback_batch = isset( $callback['allow_batch'] ) ? $callback['allow_batch'] : $allow_batch; if ( $callback_batch ) { $endpoint_data['allow_batch'] = $callback_batch; } if ( isset( $callback['args'] ) ) { $endpoint_data['args'] = array(); foreach ( $callback['args'] as $key => $opts ) { if ( is_string( $opts ) ) { $opts = array( $opts => 0 ); } elseif ( ! is_array( $opts ) ) { $opts = array(); } $arg_data = array_intersect_key( $opts, $allowed_schema_keywords ); $arg_data['required'] = ! empty( $opts['required'] ); $endpoint_data['args'][ $key ] = $arg_data; } } $data['endpoints'][] = $endpoint_data; // For non-variable routes, generate links. if ( ! str_contains( $route, '{' ) ) { $data['_links'] = array( 'self' => array( array( 'href' => rest_url( $route ), ), ), ); } } if ( empty( $data['methods'] ) ) { // No methods supported, hide the route. return null; } return $data; } /** * Gets the maximum number of requests that can be included in a batch. * * @since 5.6.0 * * @return int The maximum requests. */ protected function get_max_batch_size() { /** * Filters the maximum number of REST API requests that can be included in a batch. * * @since 5.6.0 * * @param int $max_size The maximum size. */ return apply_filters( 'rest_get_max_batch_size', 25 ); } /** * Serves the batch/v1 request. * * @since 5.6.0 * * @param WP_REST_Request $batch_request The batch request object. * @return WP_REST_Response The generated response object. */ public function serve_batch_request_v1( WP_REST_Request $batch_request ) { $requests = array(); foreach ( $batch_request['requests'] as $args ) { $parsed_url = wp_parse_url( $args['path'] ); if ( false === $parsed_url ) { $requests[] = new WP_Error( 'parse_path_failed', __( 'Could not parse the path.' ), array( 'status' => 400 ) ); continue; } $single_request = new WP_REST_Request( isset( $args['method'] ) ? $args['method'] : 'POST', $parsed_url['path'] ); if ( ! empty( $parsed_url['query'] ) ) { $query_args = null; // Satisfy linter. wp_parse_str( $parsed_url['query'], $query_args ); $single_request->set_query_params( $query_args ); } if ( ! empty( $args['body'] ) ) { $single_request->set_body_params( $args['body'] ); } if ( ! empty( $args['headers'] ) ) { $single_request->set_headers( $args['headers'] ); } $requests[] = $single_request; } $matches = array(); $validation = array(); $has_error = false; foreach ( $requests as $single_request ) { $match = $this->match_request_to_handler( $single_request ); $matches[] = $match; $error = null; if ( is_wp_error( $match ) ) { $error = $match; } if ( ! $error ) { list( $route, $handler ) = $match; if ( isset( $handler['allow_batch'] ) ) { $allow_batch = $handler['allow_batch']; } else { $route_options = $this->get_route_options( $route ); $allow_batch = isset( $route_options['allow_batch'] ) ? $route_options['allow_batch'] : false; } if ( ! is_array( $allow_batch ) || empty( $allow_batch['v1'] ) ) { $error = new WP_Error( 'rest_batch_not_allowed', __( 'The requested route does not support batch requests.' ), array( 'status' => 400 ) ); } } if ( ! $error ) { $check_required = $single_request->has_valid_params(); if ( is_wp_error( $check_required ) ) { $error = $check_required; } } if ( ! $error ) { $check_sanitized = $single_request->sanitize_params(); if ( is_wp_error( $check_sanitized ) ) { $error = $check_sanitized; } } if ( $error ) { $has_error = true; $validation[] = $error; } else { $validation[] = true; } } $responses = array(); if ( $has_error && 'require-all-validate' === $batch_request['validation'] ) { foreach ( $validation as $valid ) { if ( is_wp_error( $valid ) ) { $responses[] = $this->envelope_response( $this->error_to_response( $valid ), false )->get_data(); } else { $responses[] = null; } } return new WP_REST_Response( array( 'failed' => 'validation', 'responses' => $responses, ), WP_Http::MULTI_STATUS ); } foreach ( $requests as $i => $single_request ) { $clean_request = clone $single_request; $clean_request->set_url_params( array() ); $clean_request->set_attributes( array() ); $clean_request->set_default_params( array() ); /** This filter is documented in wp-includes/rest-api/class-wp-rest-server.php */ $result = apply_filters( 'rest_pre_dispatch', null, $this, $clean_request ); if ( empty( $result ) ) { $match = $matches[ $i ]; $error = null; if ( is_wp_error( $validation[ $i ] ) ) { $error = $validation[ $i ]; } if ( is_wp_error( $match ) ) { $result = $this->error_to_response( $match ); } else { list( $route, $handler ) = $match; if ( ! $error && ! is_callable( $handler['callback'] ) ) { $error = new WP_Error( 'rest_invalid_handler', __( 'The handler for the route is invalid' ), array( 'status' => 500 ) ); } $result = $this->respond_to_request( $single_request, $route, $handler, $error ); } } /** This filter is documented in wp-includes/rest-api/class-wp-rest-server.php */ $result = apply_filters( 'rest_post_dispatch', rest_ensure_response( $result ), $this, $single_request ); $responses[] = $this->envelope_response( $result, false )->get_data(); } return new WP_REST_Response( array( 'responses' => $responses ), WP_Http::MULTI_STATUS ); } /** * Sends an HTTP status code. * * @since 4.4.0 * * @param int $code HTTP status. */ protected function set_status( $code ) { status_header( $code ); } /** * Sends an HTTP header. * * @since 4.4.0 * * @param string $key Header key. * @param string $value Header value. */ public function send_header( $key, $value ) { /* * Sanitize as per RFC2616 (Section 4.2): * * Any LWS that occurs between field-content MAY be replaced with a * single SP before interpreting the field value or forwarding the * message downstream. */ $value = preg_replace( '/\s+/', ' ', $value ); header( sprintf( '%s: %s', $key, $value ) ); } /** * Sends multiple HTTP headers. * * @since 4.4.0 * * @param array $headers Map of header name to header value. */ public function send_headers( $headers ) { foreach ( $headers as $key => $value ) { $this->send_header( $key, $value ); } } /** * Removes an HTTP header from the current response. * * @since 4.8.0 * * @param string $key Header key. */ public function remove_header( $key ) { header_remove( $key ); } /** * Retrieves the raw request entity (body). * * @since 4.4.0 * * @global string $HTTP_RAW_POST_DATA Raw post data. * * @return string Raw request data. */ public static function get_raw_data() { // phpcs:disable PHPCompatibility.Variables.RemovedPredefinedGlobalVariables.http_raw_post_dataDeprecatedRemoved global $HTTP_RAW_POST_DATA; // $HTTP_RAW_POST_DATA was deprecated in PHP 5.6 and removed in PHP 7.0. if ( ! isset( $HTTP_RAW_POST_DATA ) ) { $HTTP_RAW_POST_DATA = file_get_contents( 'php://input' ); } return $HTTP_RAW_POST_DATA; // phpcs:enable } /** * Extracts headers from a PHP-style $_SERVER array. * * @since 4.4.0 * * @param array $server Associative array similar to `$_SERVER`. * @return array Headers extracted from the input. */ public function get_headers( $server ) { $headers = array(); // CONTENT_* headers are not prefixed with HTTP_. $additional = array( 'CONTENT_LENGTH' => true, 'CONTENT_MD5' => true, 'CONTENT_TYPE' => true, ); foreach ( $server as $key => $value ) { if ( str_starts_with( $key, 'HTTP_' ) ) { $headers[ substr( $key, 5 ) ] = $value; } elseif ( 'REDIRECT_HTTP_AUTHORIZATION' === $key && empty( $server['HTTP_AUTHORIZATION'] ) ) { /* * In some server configurations, the authorization header is passed in this alternate location. * Since it would not be passed in in both places we do not check for both headers and resolve. */ $headers['AUTHORIZATION'] = $value; } elseif ( isset( $additional[ $key ] ) ) { $headers[ $key ] = $value; } } return $headers; } } into item, and cut out non-keys for meta $columns = $this->get_column_names(); $data = array_merge( $item, $data ); $meta = array_diff_key( $data, $columns ); $save = array_intersect_key( $data, $columns ); // Maybe save meta keys if ( ! empty( $meta ) ) { $this->save_extra_item_meta( $item_id, $meta ); } // Bail if no change if ( (array) $save === (array) $item ) { return true; } // Unset the primary key from data to save unset( $save[ $primary ] ); // If date-modified is empty, use the current time $modified = $this->get_column_by( array( 'modified' => true ) ); if ( ! empty( $modified ) ) { $save[ $modified->name ] = $this->get_current_time(); } // Try to update $table = $this->get_table_name(); $reduce = $this->reduce_item( 'update', $save ); $save = $this->validate_item( $reduce ); $where = array( $primary => $item_id ); $result = ! empty( $save ) ? $this->get_db()->update( $table, $save, $where ) : false; // Bail on failure if ( ! $this->is_success( $result ) ) { return false; } // Use get item to prime caches $this->update_item_cache( $item_id ); // Transition item data $this->transition_item( $save, $item ); // Return result return $result; } /** * Delete an item from the database. * * @since 1.0.0 * * @param int $item_id * @return bool */ public function delete_item( $item_id = 0 ) { // Bail if no item ID $item_id = $this->shape_item_id( $item_id ); if ( empty( $item_id ) ) { return false; } // Get the primary column name $primary = $this->get_primary_column_name(); // Get item (before it's deleted) $item = $this->get_item_raw( $primary, $item_id ); // Bail if item does not exist to delete if ( empty( $item ) ) { return false; } // Attempt to reduce this item $item = $this->reduce_item( 'delete', $item ); // Bail if item was reduced to nothing if ( empty( $item ) ) { return false; } // Try to delete $table = $this->get_table_name(); $where = array( $primary => $item_id ); $result = $this->get_db()->delete( $table, $where ); // Bail on failure if ( ! $this->is_success( $result ) ) { return false; } // Clean caches on successful delete $this->delete_all_item_meta( $item_id ); $this->clean_item_cache( $item ); // Return result return $result; } /** * Filter an item before it is inserted of updated in the database. * * This method is public to allow subclasses to perform JIT manipulation * of the parameters passed into it. * * @since 1.0.0 * * @param array $item * @return array */ public function filter_item( $item = array() ) { return (array) apply_filters_ref_array( $this->apply_prefix( "filter_{$this->item_name}_item" ), array( $item, &$this ) ); } /** * Shape an item from the database into the type of object it always wanted * to be when it grew up. * * @since 1.0.0 * * @param mixed ID of item, or row from database * @return mixed False on error, Object of single-object class type on success */ private function shape_item( $item = 0 ) { // Get the item from an ID if ( is_numeric( $item ) ) { $item = $this->get_item( $item ); } // Return the item if it's already shaped if ( $item instanceof $this->item_shape ) { return $item; } // Shape the item as needed $item = ! empty( $this->item_shape ) ? new $this->item_shape( $item ) : (object) $item; // Return the item object return $item; } /** * Validate an item before it is updated in or added to the database. * * @since 1.0.0 * * @param array $item * @return array|false False on error, Array of validated values on success */ private function validate_item( $item = array() ) { // Bail if item is empty or not an array if ( empty( $item ) || ! is_array( $item ) ) { return $item; } // Loop through item attributes foreach ( $item as $key => $value ) { // Strip slashes from all strings /*if ( is_string( $value ) ) { $value = stripslashes( $value );// We removed this line at PR #3847 to solve if the content has backslash. }*/ // Get the column $column = $this->get_column_by( array( 'name' => $key ) ); // Null value is special for all item keys if ( is_null( $value ) ) { // Bail if null is not allowed if ( false === $column->allow_null ) { return false; } // Attempt to validate } elseif ( ! empty( $column->validate ) && is_callable( $column->validate ) ) { $validated = call_user_func( $column->validate, $value ); // Bail if error if ( is_wp_error( $validated ) ) { return false; } // Update the value $item[ $key ] = $validated; /** * Fallback to using the raw value. * * Note: This may change at a later date, so do not rely on this. * Please always validate all data. */ } else { $item[ $key ] = $value; } } // Return the validated item return $this->filter_item( $item ); } /** * Reduce an item down to the keys and values the current user has the * appropriate capabilities to select|insert|update|delete. * * Note that internally, this method works with both arrays and objects of * any type, and also resets the key values. It looks weird, but is * currently by design to protect the integrity of the return value. * * @since 1.0.0 * * @param string $method select|insert|update|delete * @param mixed $item Object|Array of keys/values to reduce * * @return mixed Object|Array without keys the current user does not have caps for */ private function reduce_item( $method = 'update', $item = array() ) { // Bail if item is empty if ( empty( $item ) ) { return $item; } // Loop through item attributes foreach ( $item as $key => $value ) { // Get capabilities for this column $caps = $this->get_column_field( array( 'name' => $key ), 'caps' ); // Unset if not explicitly allowed if ( empty( $caps[ $method ] ) || ! current_user_can( $caps[ $method ] ) ) { if ( is_array( $item ) ) { unset( $item[ $key ] ); } elseif ( is_object( $item ) ) { $item->{$key} = null; } // Set if explicitly allowed } elseif ( is_array( $item ) ) { $item[ $key ] = $value; } elseif ( is_object( $item ) ) { $item->{$key} = $value; } } // Return the reduced item return $item; } /** * Return an item comprised of all default values. * * This is used by `add_item()` to populate known default values, to ensure * new item data is always what we expect it to be. * * @since 1.0.0 * * @return array */ private function default_item() { // Default return value $retval = array(); // Get the column names and their defaults $names = $this->get_columns( array(), 'and', 'name' ); $defaults = $this->get_columns( array(), 'and', 'default' ); // Put together an item using default values foreach ( $names as $key => $name ) { $retval[ $name ] = $defaults[ $key ]; } // Return return $retval; } /** * Transition an item when adding or updating. * * This method takes the data being saved, looks for any columns that are * known to transition between values, and fires actions on them. * * @since 1.0.0 * * @param array $item * @return array */ private function transition_item( $new_data = array(), $old_data = array() ) { // Look for transition columns $columns = $this->get_columns( array( 'transition' => true ), 'and', 'name' ); // Bail if no columns to transition if ( empty( $columns ) ) { return; } // Get the item ID $item_id = $this->shape_item_id( $old_data ); // Bail if item ID cannot be retrieved if ( empty( $item_id ) ) { return; } // If no old value(s), it's new if ( ! is_array( $old_data ) ) { $old_data = $new_data; // Set all old values to "new" foreach ( $old_data as $key => $value ) { $value = 'new'; $old_data[ $key ] = $value; } } // Compare $keys = array_flip( $columns ); $new = array_intersect_key( $new_data, $keys ); $old = array_intersect_key( $old_data, $keys ); // Get the difference $diff = array_diff( $new, $old ); // Bail if nothing is changing if ( empty( $diff ) ) { return; } // Do the actions foreach ( $diff as $key => $value ) { $old_value = $old_data[ $key ]; $new_value = $new_data[ $key ]; $key_action = $this->apply_prefix( "transition_{$this->item_name}_{$key}" ); /** * Fires after an object value has transitioned. * * @since 1.0.0 * * @param mixed $old_value The value being transitioned FROM. * @param mixed $new_value The value being transitioned TO. * @param int $item_id The ID of the item that is transitioning. */ do_action( $key_action, $old_value, $new_value, $item_id ); } } /** Meta ******************************************************************/ /** * Add meta data to an item. * * @since 1.0.0 * * @param int $item_id * @param string $meta_key * @param string $meta_value * @param string $unique * @return int|false The meta ID on success, false on failure. */ protected function add_item_meta( $item_id = 0, $meta_key = '', $meta_value = '', $unique = false ) { // Bail if no meta was returned $item_id = $this->shape_item_id( $item_id ); if ( empty( $item_id ) || empty( $meta_key ) ) { return false; } // Bail if no meta table exists if ( false === $this->get_meta_table_name() ) { return false; } // Get the meta type $meta_type = $this->get_meta_type(); // Return results of adding meta data return add_metadata( $meta_type, $item_id, $meta_key, $meta_value, $unique ); } /** * Get meta data for an item. * * @since 1.0.0 * * @param int $item_id * @param string $meta_key * @param bool $single * @return mixed Single metadata value, or array of values */ protected function get_item_meta( $item_id = 0, $meta_key = '', $single = false ) { // Bail if no meta was returned $item_id = $this->shape_item_id( $item_id ); if ( empty( $item_id ) || empty( $meta_key ) ) { return false; } // Bail if no meta table exists if ( false === $this->get_meta_table_name() ) { return false; } // Get the meta type $meta_type = $this->get_meta_type(); // Return results of getting meta data return get_metadata( $meta_type, $item_id, $meta_key, $single ); } /** * Update meta data for an item. * * @since 1.0.0 * * @param int $item_id * @param string $meta_key * @param string $meta_value * @param string $prev_value * @return bool True on successful update, false on failure. */ protected function update_item_meta( $item_id = 0, $meta_key = '', $meta_value = '', $prev_value = '' ) { // Bail if no meta was returned $item_id = $this->shape_item_id( $item_id ); if ( empty( $item_id ) || empty( $meta_key ) ) { return false; } // Bail if no meta table exists if ( false === $this->get_meta_table_name() ) { return false; } // Get the meta type $meta_type = $this->get_meta_type(); // Return results of updating meta data return update_metadata( $meta_type, $item_id, $meta_key, $meta_value, $prev_value ); } /** * Delete meta data for an item. * * @since 1.0.0 * * @param int $item_id * @param string $meta_key * @param string $meta_value * @param string $delete_all * @return bool True on successful delete, false on failure. */ protected function delete_item_meta( $item_id = 0, $meta_key = '', $meta_value = '', $delete_all = false ) { // Bail if no meta was returned $item_id = $this->shape_item_id( $item_id ); if ( empty( $item_id ) || empty( $meta_key ) ) { return false; } // Bail if no meta table exists if ( false === $this->get_meta_table_name() ) { return false; } // Get the meta type $meta_type = $this->get_meta_type(); // Return results of deleting meta data return delete_metadata( $meta_type, $item_id, $meta_key, $meta_value, $delete_all ); } /** * Get registered meta data keys. * * @since 1.0.0 * * @param string $object_subtype The sub-type of meta keys * * @return array */ private function get_registered_meta_keys( $object_subtype = '' ) { // Get the object type $object_type = $this->get_meta_type(); // Return the keys return get_registered_meta_keys( $object_type, $object_subtype ); } /** * Maybe update meta values on item update/save. * * @since 1.0.0 * * @param array $meta */ private function save_extra_item_meta( $item_id = 0, $meta = array() ) { // Bail if there is no bulk meta to save $item_id = $this->shape_item_id( $item_id ); if ( empty( $item_id ) || empty( $meta ) ) { return; } // Bail if no meta table exists if ( false === $this->get_meta_table_name() ) { return; } // Only save registered keys $keys = $this->get_registered_meta_keys(); $meta = array_intersect_key( $meta, $keys ); // Bail if no registered meta keys if ( empty( $meta ) ) { return; } // Save or delete meta data foreach ( $meta as $key => $value ) { ! empty( $value ) ? $this->update_item_meta( $item_id, $key, $value ) : $this->delete_item_meta( $item_id, $key ); } } /** * Delete all meta data for an item. * * @since 1.0.0 * * @param int $item_id */ private function delete_all_item_meta( $item_id = 0 ) { // Bail if no meta was returned $item_id = $this->shape_item_id( $item_id ); if ( empty( $item_id ) ) { return; } // Get the meta table name $table = $this->get_meta_table_name(); // Bail if no meta table exists if ( empty( $table ) ) { return; } // Guess the item ID column for the meta table $primary_id = $this->get_primary_column_name(); $item_id_column = $this->apply_prefix( "{$this->item_name}_{$primary_id}" ); // Get meta IDs $query = "SELECT meta_id FROM {$table} WHERE {$item_id_column} = %d"; $prepared = $this->get_db()->prepare( $query, $item_id ); $meta_ids = $this->get_db()->get_col( $prepared ); // Bail if no meta IDs to delete if ( empty( $meta_ids ) ) { return; } // Get the meta type $meta_type = $this->get_meta_type(); // Delete all meta data for this item ID foreach ( $meta_ids as $mid ) { delete_metadata_by_mid( $meta_type, $mid ); } } /** * Get the meta table for this query. * * Forked from WordPress\_get_meta_table() so it can be more accurately * predicted in a future iteration and default to returning false. * * @since 1.0.0 * * @return mixed Table name if exists, False if not */ private function get_meta_table_name() { // Get the meta-type $type = $this->get_meta_type(); // Append "meta" to end of meta-type $table_name = "{$type}meta"; // Variable'ize the database interface, to use inside empty() $db = $this->get_db(); // If not empty, return table name if ( ! empty( $db->{$table_name} ) ) { return $table_name; } // Default return false return false; } /** * Get the meta type for this query. * * This method exists to reduce some duplication for now. Future iterations * will likely use Column::relationships to * * @since 1.1.0 * * @return string */ private function get_meta_type() { return $this->apply_prefix( $this->item_name ); } /** Cache *****************************************************************/ /** * Get cache key from query_vars and query_var_defaults. * * @since 1.0.0 * * @return string */ private function get_cache_key( $group = '' ) { // Slice query vars $slice = wp_array_slice_assoc( $this->query_vars, array_keys( $this->query_var_defaults ) ); // Unset `fields` so it does not effect the cache key unset( $slice['fields'] ); // Setup key & last_changed $key = md5( serialize( $slice ) ); $last_changed = $this->get_last_changed_cache( $group ); // Concatenate and return cache key return "get_{$this->item_name_plural}:{$key}:{$last_changed}"; } /** * Get the cache group, or fallback to the primary one. * * @since 1.0.0 * * @param string $group * @return string */ private function get_cache_group( $group = '' ) { // Get the primary column $primary = $this->get_primary_column_name(); // Default return value $retval = $this->cache_group; // Only allow non-primary groups if ( ! empty( $group ) && ( $group !== $primary ) ) { $retval = $group; } // Return the group return $retval; } /** * Get array of which database columns have uniquely cached groups. * * @since 1.0.0 * * @return array */ private function get_cache_groups() { // Return value $cache_groups = array(); // Get the cache groups $groups = $this->get_columns( array( 'cache_key' => true ), 'and', 'name' ); if ( ! empty( $groups ) ) { // Get the primary column name $primary = $this->get_primary_column_name(); // Setup return values foreach ( $groups as $name ) { if ( $primary !== $name ) { $cache_groups[ $name ] = "{$this->cache_group}-by-{$name}"; } else { $cache_groups[ $name ] = $this->cache_group; } } } // Return cache groups array return $cache_groups; } /** * Maybe prime item & item-meta caches by querying 1 time for all un-cached * items. * * Accepts a single ID, or an array of IDs. * * The reason this accepts only IDs is because it gets called immediately * after an item is inserted in the database, but before items have been * "shaped" into proper objects, so object properties may not be set yet. * * @since 1.0.0 * * @param array $item_ids * @param bool $force * * @return bool False if empty */ private function prime_item_caches( $item_ids = array(), $force = false ) { // Bail if no items to cache if ( empty( $item_ids ) ) { return false; } // Accepts single values, so cast to array $item_ids = (array) $item_ids; // Update item caches if ( ! empty( $force ) || ! empty( $this->query_vars['update_item_cache'] ) ) { // Look for non-cached IDs $ids = $this->get_non_cached_ids( $item_ids, $this->cache_group ); // Bail if IDs are cached if ( empty( $ids ) ) { return false; } // Get query parts $table = $this->get_table_name(); $primary = $this->get_primary_column_name(); // Query database $query = "SELECT * FROM {$table} WHERE {$primary} IN (%s)"; $ids = implode( ',', array_map( 'absint', $ids ) ); $prepare = sprintf( $query, $ids ); $results = $this->get_db()->get_results( $prepare ); // Update item caches $this->update_item_cache( $results ); } // Update meta data caches if ( ! empty( $this->query_vars['update_meta_cache'] ) ) { $singular = rtrim( $this->table_name, 's' ); // sic update_meta_cache( $singular, $item_ids ); } } /** * Update the cache for an item. Does not update item-meta cache. * * Accepts a single object, or an array of objects. * * The reason this does not accept ID's is because this gets called * after an item is already updated in the database, so we want to avoid * querying for it again. It's just safer this way. * * @since 1.0.0 * * @param array $items */ private function update_item_cache( $items = array() ) { // Maybe query for single item if ( is_numeric( $items ) ) { $primary = $this->get_primary_column_name(); $items = $this->get_item_raw( $primary, $items ); } // Bail if no items to cache if ( empty( $items ) ) { return false; } // Make sure items are an array (without casting objects to arrays) if ( ! is_array( $items ) ) { $items = array( $items ); } // Get the cache groups $groups = $this->get_cache_groups(); // Loop through all items and cache them foreach ( $items as $item ) { // Skip if item is not an object if ( ! is_object( $item ) ) { continue; } // Loop through groups and set cache if ( ! empty( $groups ) ) { foreach ( $groups as $key => $group ) { $this->cache_set( $item->{$key}, $item, $group ); } } } // Update last changed $this->update_last_changed_cache(); } /** * Clean the cache for an item. Does not clean item-meta. * * Accepts a single object, or an array of objects. * * The reason this does not accept ID's is because this gets called * after an item is already deleted from the database, so it cannot be * queried and may not exist in the cache. It's just safer this way. * * @since 1.0.0 * * @param mixed $items Single object item, or Array of object items * * @return bool */ private function clean_item_cache( $items = array() ) { // Bail if no items to clean if ( empty( $items ) ) { return false; } // Make sure items are an array if ( ! is_array( $items ) ) { $items = array( $items ); } // Get the cache groups $groups = $this->get_cache_groups(); // Loop through all items and clean them foreach ( $items as $item ) { // Skip if item is not an object if ( ! is_object( $item ) ) { continue; } // Loop through groups and delete cache if ( ! empty( $groups ) ) { foreach ( $groups as $key => $group ) { $this->cache_delete( $item->{$key}, $group ); } } } // Update last changed $this->update_last_changed_cache(); } /** * Update the last_changed key for the cache group. * * @since 1.0.0 * * @return string The last time a cache group was changed. */ private function update_last_changed_cache( $group = '' ) { // Fallback to microtime if ( empty( $this->last_changed ) ) { $this->set_last_changed(); } // Set the last changed time for this cache group $this->cache_set( 'last_changed', $this->last_changed, $group ); // Return the last changed time return $this->last_changed; } /** * Get the last_changed key for a cache group. * * @since 1.0.0 * * @param string $group Cache group. Defaults to $this->cache_group * * @return string The last time a cache group was changed. */ private function get_last_changed_cache( $group = '' ) { // Get the last changed cache value $last_changed = $this->cache_get( 'last_changed', $group ); // Maybe update the last changed value if ( false === $last_changed ) { $last_changed = $this->update_last_changed_cache( $group ); } // Return the last changed value for the cache group return $last_changed; } /** * Get array of non-cached item IDs. * * @since 1.0.0 * * @param array $item_ids Array of item IDs * @param string $group Cache group. Defaults to $this->cache_group * * @return array */ private function get_non_cached_ids( $item_ids = array(), $group = '' ) { $retval = array(); // Bail if no item IDs if ( empty( $item_ids ) ) { return $retval; } // Loop through item IDs foreach ( $item_ids as $id ) { $id = $this->shape_item_id( $id ); if ( false === $this->cache_get( $id, $group ) ) { $retval[] = $id; } } // Return array of IDs return $retval; } /** * Add a cache value for a key and group. * * @since 1.0.0 * * @param string $key Cache key. * @param mixed $value Cache value. * @param string $group Cache group. Defaults to $this->cache_group * @param int $expire Expiration. */ private function cache_add( $key = '', $value = '', $group = '', $expire = 0 ) { // Bail if cache invalidation is suspended if ( wp_suspend_cache_addition() ) { return; } // Bail if no cache key if ( empty( $key ) ) { return; } // Get the cache group $group = $this->get_cache_group( $group ); // Add to the cache wp_cache_add( $key, $value, $group, $expire ); } /** * Get a cache value for a key and group. * * @since 1.0.0 * * @param string $key Cache key. * @param string $group Cache group. Defaults to $this->cache_group * @param bool $force */ private function cache_get( $key = '', $group = '', $force = false ) { // Bail if no cache key if ( empty( $key ) ) { return; } // Get the cache group $group = $this->get_cache_group( $group ); // Return from the cache return wp_cache_get( $key, $group, $force ); } /** * Set a cache value for a key and group. * * @since 1.0.0 * * @param string $key Cache key. * @param mixed $value Cache value. * @param string $group Cache group. Defaults to $this->cache_group * @param int $expire Expiration. */ private function cache_set( $key = '', $value = '', $group = '', $expire = 0 ) { // Bail if cache invalidation is suspended if ( wp_suspend_cache_addition() ) { return; } // Bail if no cache key if ( empty( $key ) ) { return; } // Get the cache group $group = $this->get_cache_group( $group ); // Update the cache wp_cache_set( $key, $value, $group, $expire ); } /** * Delete a cache key for a group. * * @since 1.0.0 * * @global bool $_wp_suspend_cache_invalidation * * @param string $key Cache key. * @param string $group Cache group. Defaults to $this->cache_group */ private function cache_delete( $key = '', $group = '' ) { global $_wp_suspend_cache_invalidation; // Bail if cache invalidation is suspended if ( ! empty( $_wp_suspend_cache_invalidation ) ) { return; } // Bail if no cache key if ( empty( $key ) ) { return; } // Get the cache group $group = $this->get_cache_group( $group ); // Delete the cache wp_cache_delete( $key, $group ); } /** * Fetch raw results directly from the database. * * @since 1.0.0 * * @param array $cols Columns for `SELECT`. * @param array $where_cols Where clauses. Each key-value pair in the array * represents a column and a comparison. * @param int $limit Optional. LIMIT value. Default 25. * @param null $offset Optional. OFFSET value. Default null. * @param string $output Optional. Any of ARRAY_A | ARRAY_N | OBJECT | OBJECT_K constants. * Default OBJECT. * With one of the first three, return an array of * rows indexed from 0 by SQL result row number. * Each row is an associative array (column => value, ...), * a numerically indexed array (0 => value, ...), * or an object. ( ->column = value ), respectively. * With OBJECT_K, return an associative array of * row objects keyed by the value of each row's * first column's value. * * @return array|object|null Database query results. */ public function get_results( $cols = array(), $where_cols = array(), $limit = 25, $offset = null, $output = OBJECT ) { // Bail if no columns have been passed if ( empty( $cols ) ) { return null; } // Fetch all the columns for the table being queried $column_names = $this->get_column_names(); // Ensure valid column names have been passed for the `SELECT` clause foreach ( $cols as $index => $column ) { if ( ! array_key_exists( $column, $column_names ) ) { unset( $cols[ $index ] ); } } // Columns to retrieve $columns = implode( ',', $cols ); // Get the table name $table = $this->get_table_name(); // Setup base query $query = implode( ' ', array( "SELECT", $columns, "FROM {$table} {$this->table_alias}", "WHERE 1=1" ) ); // Ensure valid columns have been passed for the `WHERE` clause if ( ! empty( $where_cols ) ) { // Get keys from where columns $columns = array_keys( $where_cols ); // Loop through columns and unset any invalid names foreach ( $columns as $index => $column ) { if ( ! array_key_exists( $column, $column_names ) ) { unset( $where_cols[ $index ] ); } } // Parse WHERE clauses foreach ( $where_cols as $column => $compare ) { // Basic WHERE clause if ( ! is_array( $compare ) ) { $pattern = $this->get_column_field( array( 'name' => $column ), 'pattern', '%s' ); $statement = " AND {$this->table_alias}.{$column} = {$pattern} "; $query .= $this->get_db()->prepare( $statement, $compare ); // More complex WHERE clause } else { $value = isset( $compare['value'] ) ? $compare['value'] : false; // Skip if a value was not provided if ( false === $value ) { continue; } // Default compare clause to equals $compare_clause = isset( $compare['compare_query'] ) ? trim( strtoupper( $compare['compare_query'] ) ) : '='; // Array (unprepared) if ( is_array( $compare['value'] ) ) { // Default to IN if clause not specified if ( ! in_array( $compare_clause, array( 'IN', 'NOT IN', 'BETWEEN' ), true ) ) { $compare_clause = 'IN'; } // Parse & escape for IN and NOT IN if ( 'IN' === $compare_clause || 'NOT IN' === $compare_clause ) { $value = "('" . implode( "','", $this->get_db()->_escape( $compare['value'] ) ) . "')"; // Parse & escape for BETWEEN } elseif ( is_array( $value ) && 2 === count( $value ) && 'BETWEEN' === $compare_clause ) { $_this = $this->get_db()->_escape( $value[0] ); $_that = $this->get_db()->_escape( $value[1] ); $value = " {$_this} AND {$_that} "; } } // Add WHERE clause $query .= " AND {$this->table_alias}.{$column} {$compare_clause} {$value} "; } } } // Maybe set an offset if ( ! empty( $offset ) ) { $values = explode( ',', $offset ); $values = array_filter( $values, 'intval' ); $offset = implode( ',', $values ); $query .= " OFFSET {$offset} "; } // Maybe set a limit if ( ! empty( $limit ) && ( $limit > 0 ) ) { $limit = intval( $limit ); $query .= " LIMIT {$limit} "; } // Execute query $results = $this->get_db()->get_results( $query, $output ); // Return results return $results; } }