|WP_Error */ public static function summary( $from = '', $to = '' ) { return self::authed_get( self::with_window( '/plugin/v1/summary', $from, $to ) ); } /** * Fetch the connected site's per-day verdict series for the trend chart. * * @param string $from Optional start date (YYYY-MM-DD). * @param string $to Optional end date (YYYY-MM-DD). * @return array|WP_Error */ public static function timeseries( $from = '', $to = '' ) { return self::authed_get( self::with_window( '/plugin/v1/timeseries', $from, $to ) ); } /** * Append a from/to window to an endpoint path. An empty window returns the bare * path so the no-argument summary() call is byte-for-byte unchanged. * * @param string $path Endpoint path beginning with '/'. * @param string $from Start date or ''. * @param string $to End date or ''. * @return string */ private static function with_window( $path, $from, $to ) { $args = array(); if ( '' !== (string) $from ) { $args['from'] = (string) $from; } if ( '' !== (string) $to ) { $args['to'] = (string) $to; } return empty( $args ) ? $path : add_query_arg( $args, $path ); } /** * Perform a GET against an AdPriva plugin endpoint, retrying once after a * token refresh if the first attempt is unauthorized. * * @param string $path Endpoint path beginning with '/'. * @return array|WP_Error */ private static function authed_get( $path ) { $token = Adpriva_Tokens::access_token(); if ( '' === $token ) { return new WP_Error( 'adpriva_not_connected', __( 'This site is not connected to AdPriva.', 'adpriva' ) ); } $response = self::do_get( $path, $token ); if ( self::is_unauthorized( $response ) && Adpriva_OAuth::refresh() ) { $response = self::do_get( $path, Adpriva_Tokens::access_token() ); } return self::decode( $response ); } /** * Issue the bearer-authed GET request. * * @param string $path Endpoint path. * @param string $token Access token. * @return array|WP_Error */ private static function do_get( $path, $token ) { return wp_remote_get( Adpriva_Config::api_base() . $path, array( 'timeout' => 10, 'headers' => array( 'Authorization' => 'Bearer ' . $token ), ) ); } /** * Whether a response is an HTTP 401. * * @param array|WP_Error $response Response. * @return bool */ private static function is_unauthorized( $response ) { return ! is_wp_error( $response ) && 401 === (int) wp_remote_retrieve_response_code( $response ); } /** * Decode a successful JSON response or return a WP_Error. * * @param array|WP_Error $response Response. * @return array|WP_Error */ private static function decode( $response ) { if ( is_wp_error( $response ) ) { return $response; } $code = (int) wp_remote_retrieve_response_code( $response ); $body = json_decode( wp_remote_retrieve_body( $response ), true ); if ( $code < 200 || $code >= 300 || ! is_array( $body ) ) { return new WP_Error( 'adpriva_api_error', __( 'The AdPriva request failed.', 'adpriva' ), array( 'status' => $code ) ); } return $body; } }