Rest.php
90 lines
| 1 | <?php |
| 2 | |
| 3 | namespace WPStaging\Framework\Rest; |
| 4 | |
| 5 | use WPStaging\Framework\Utils\Sanitize; |
| 6 | |
| 7 | /** |
| 8 | * Class Rest |
| 9 | * |
| 10 | * @package WPStaging\Framework\Rest |
| 11 | * |
| 12 | * @todo merge into WPAdapter class? |
| 13 | */ |
| 14 | class Rest |
| 15 | { |
| 16 | /** @var string */ |
| 17 | const WPSTG_ROUTE_NAMESPACE_V1 = 'wpstg/v1'; |
| 18 | |
| 19 | /** @var int */ |
| 20 | const REQUEST_TIMEOUT = 30; |
| 21 | |
| 22 | /** @var Sanitize */ |
| 23 | private $sanitize; |
| 24 | |
| 25 | public function __construct(Sanitize $sanitize) |
| 26 | { |
| 27 | $this->sanitize = $sanitize; |
| 28 | } |
| 29 | |
| 30 | // Is Rest URL |
| 31 | public function isRestUrl() |
| 32 | { |
| 33 | // Early bail if uri is empty |
| 34 | if (empty($_SERVER['REQUEST_URI'])) { |
| 35 | return false; |
| 36 | } |
| 37 | |
| 38 | $requestPath = trim($this->sanitize->sanitizeUrl($_SERVER['REQUEST_URI']), '/'); |
| 39 | |
| 40 | $originalUrl = trailingslashit(get_home_url(get_current_blog_id(), '')); |
| 41 | |
| 42 | $url = add_query_arg('rest_route', '/', $originalUrl); |
| 43 | $restPath = $this->getApiRequestURI($url); |
| 44 | $requestPathApiURI = $this->getApiRequestURI($requestPath); |
| 45 | if (!empty($restPath) && strpos($requestPathApiURI, $restPath) === 0) { |
| 46 | return true; |
| 47 | } |
| 48 | |
| 49 | // nginx only allows HTTP/1.0 methods when redirecting from / to /index.php. |
| 50 | // To work around this, we manually add index.php to the URL, avoiding the redirect. |
| 51 | if ('index.php/' !== substr($originalUrl, -10)) { |
| 52 | $urlWithIndex = add_query_arg('rest_route', '/', $originalUrl . 'index.php'); |
| 53 | $restPathWithIndex = $this->getApiRequestURI($urlWithIndex); |
| 54 | if (!empty($restPathWithIndex) && strpos($requestPathApiURI, $restPathWithIndex) === 0) { |
| 55 | return true; |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | // Early bail rest url function not exists |
| 60 | if (!function_exists('rest_url')) { |
| 61 | return false; |
| 62 | } |
| 63 | |
| 64 | $baseRestURL = get_rest_url(get_current_blog_id(), '/'); |
| 65 | $restPath = $this->getApiRequestURI($baseRestURL); |
| 66 | |
| 67 | // Early bail if rest path is empty |
| 68 | if (empty($restPath)) { |
| 69 | return false; |
| 70 | } |
| 71 | |
| 72 | return strpos($requestPath, $restPath) === 0; |
| 73 | } |
| 74 | |
| 75 | private function getApiRequestURI($url) |
| 76 | { |
| 77 | if (empty($url)) { |
| 78 | return ''; |
| 79 | } |
| 80 | |
| 81 | $path = parse_url($url, PHP_URL_PATH); |
| 82 | $path = empty($path) ? '' : trim($path, '/'); |
| 83 | |
| 84 | $query = parse_url($url, PHP_URL_QUERY); |
| 85 | $query = empty($query) ? '' : trim($query, '/'); |
| 86 | |
| 87 | return $query === '' ? $path : $path . '?' . $query; |
| 88 | } |
| 89 | } |
| 90 |