http.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764
  1. <?php
  2. /**
  3. * Core HTTP Request API
  4. *
  5. * Standardizes the HTTP requests for WordPress. Handles cookies, gzip encoding and decoding, chunk
  6. * decoding, if HTTP 1.1 and various other difficult HTTP protocol implementations.
  7. *
  8. * @package WordPress
  9. * @subpackage HTTP
  10. */
  11. /**
  12. * Returns the initialized WP_Http Object
  13. *
  14. * @since 2.7.0
  15. * @access private
  16. *
  17. * @staticvar WP_Http $http
  18. *
  19. * @return WP_Http HTTP Transport object.
  20. */
  21. function _wp_http_get_object() {
  22. static $http = null;
  23. if ( is_null( $http ) ) {
  24. $http = new WP_Http();
  25. }
  26. return $http;
  27. }
  28. /**
  29. * Retrieve the raw response from a safe HTTP request.
  30. *
  31. * This function is ideal when the HTTP request is being made to an arbitrary
  32. * URL. The URL is validated to avoid redirection and request forgery attacks.
  33. *
  34. * @since 3.6.0
  35. *
  36. * @see wp_remote_request() For more information on the response array format.
  37. * @see WP_Http::request() For default arguments information.
  38. *
  39. * @param string $url URL to retrieve.
  40. * @param array $args Optional. Request arguments. Default empty array.
  41. * @return WP_Error|array The response or WP_Error on failure.
  42. */
  43. function wp_safe_remote_request( $url, $args = array() ) {
  44. $args['reject_unsafe_urls'] = true;
  45. $http = _wp_http_get_object();
  46. return $http->request( $url, $args );
  47. }
  48. /**
  49. * Retrieve the raw response from a safe HTTP request using the GET method.
  50. *
  51. * This function is ideal when the HTTP request is being made to an arbitrary
  52. * URL. The URL is validated to avoid redirection and request forgery attacks.
  53. *
  54. * @since 3.6.0
  55. *
  56. * @see wp_remote_request() For more information on the response array format.
  57. * @see WP_Http::request() For default arguments information.
  58. *
  59. * @param string $url URL to retrieve.
  60. * @param array $args Optional. Request arguments. Default empty array.
  61. * @return WP_Error|array The response or WP_Error on failure.
  62. */
  63. function wp_safe_remote_get( $url, $args = array() ) {
  64. $args['reject_unsafe_urls'] = true;
  65. $http = _wp_http_get_object();
  66. return $http->get( $url, $args );
  67. }
  68. /**
  69. * Retrieve the raw response from a safe HTTP request using the POST method.
  70. *
  71. * This function is ideal when the HTTP request is being made to an arbitrary
  72. * URL. The URL is validated to avoid redirection and request forgery attacks.
  73. *
  74. * @since 3.6.0
  75. *
  76. * @see wp_remote_request() For more information on the response array format.
  77. * @see WP_Http::request() For default arguments information.
  78. *
  79. * @param string $url URL to retrieve.
  80. * @param array $args Optional. Request arguments. Default empty array.
  81. * @return WP_Error|array The response or WP_Error on failure.
  82. */
  83. function wp_safe_remote_post( $url, $args = array() ) {
  84. $args['reject_unsafe_urls'] = true;
  85. $http = _wp_http_get_object();
  86. return $http->post( $url, $args );
  87. }
  88. /**
  89. * Retrieve the raw response from a safe HTTP request using the HEAD method.
  90. *
  91. * This function is ideal when the HTTP request is being made to an arbitrary
  92. * URL. The URL is validated to avoid redirection and request forgery attacks.
  93. *
  94. * @since 3.6.0
  95. *
  96. * @see wp_remote_request() For more information on the response array format.
  97. * @see WP_Http::request() For default arguments information.
  98. *
  99. * @param string $url URL to retrieve.
  100. * @param array $args Optional. Request arguments. Default empty array.
  101. * @return WP_Error|array The response or WP_Error on failure.
  102. */
  103. function wp_safe_remote_head( $url, $args = array() ) {
  104. $args['reject_unsafe_urls'] = true;
  105. $http = _wp_http_get_object();
  106. return $http->head( $url, $args );
  107. }
  108. /**
  109. * Performs an HTTP request and returns its response.
  110. *
  111. * There are other API functions available which abstract away the HTTP method:
  112. *
  113. * - Default 'GET' for wp_remote_get()
  114. * - Default 'POST' for wp_remote_post()
  115. * - Default 'HEAD' for wp_remote_head()
  116. *
  117. * @since 2.7.0
  118. *
  119. * @see WP_Http::request() For information on default arguments.
  120. *
  121. * @param string $url URL to retrieve.
  122. * @param array $args Optional. Request arguments. Default empty array.
  123. * @return WP_Error|array {
  124. * The response array or a WP_Error on failure.
  125. *
  126. * @type string[] $headers Array of response headers keyed by their name.
  127. * @type string $body Response body.
  128. * @type array $response {
  129. * Data about the HTTP response.
  130. *
  131. * @type int|false $code HTTP response code.
  132. * @type string|false $message HTTP response message.
  133. * }
  134. * @type WP_HTTP_Cookie[] $cookies Array of response cookies.
  135. * @type WP_HTTP_Requests_Response|null $http_response Raw HTTP response object.
  136. * }
  137. */
  138. function wp_remote_request( $url, $args = array() ) {
  139. $http = _wp_http_get_object();
  140. return $http->request( $url, $args );
  141. }
  142. /**
  143. * Performs an HTTP request using the GET method and returns its response.
  144. *
  145. * @since 2.7.0
  146. *
  147. * @see wp_remote_request() For more information on the response array format.
  148. * @see WP_Http::request() For default arguments information.
  149. *
  150. * @param string $url URL to retrieve.
  151. * @param array $args Optional. Request arguments. Default empty array.
  152. * @return WP_Error|array The response or WP_Error on failure.
  153. */
  154. function wp_remote_get( $url, $args = array() ) {
  155. $http = _wp_http_get_object();
  156. return $http->get( $url, $args );
  157. }
  158. /**
  159. * Performs an HTTP request using the POST method and returns its response.
  160. *
  161. * @since 2.7.0
  162. *
  163. * @see wp_remote_request() For more information on the response array format.
  164. * @see WP_Http::request() For default arguments information.
  165. *
  166. * @param string $url URL to retrieve.
  167. * @param array $args Optional. Request arguments. Default empty array.
  168. * @return WP_Error|array The response or WP_Error on failure.
  169. */
  170. function wp_remote_post( $url, $args = array() ) {
  171. $http = _wp_http_get_object();
  172. return $http->post( $url, $args );
  173. }
  174. /**
  175. * Performs an HTTP request using the HEAD method and returns its response.
  176. *
  177. * @since 2.7.0
  178. *
  179. * @see wp_remote_request() For more information on the response array format.
  180. * @see WP_Http::request() For default arguments information.
  181. *
  182. * @param string $url URL to retrieve.
  183. * @param array $args Optional. Request arguments. Default empty array.
  184. * @return WP_Error|array The response or WP_Error on failure.
  185. */
  186. function wp_remote_head( $url, $args = array() ) {
  187. $http = _wp_http_get_object();
  188. return $http->head( $url, $args );
  189. }
  190. /**
  191. * Retrieve only the headers from the raw response.
  192. *
  193. * @since 2.7.0
  194. * @since 4.6.0 Return value changed from an array to an Requests_Utility_CaseInsensitiveDictionary instance.
  195. *
  196. * @see \Requests_Utility_CaseInsensitiveDictionary
  197. *
  198. * @param array|WP_Error $response HTTP response.
  199. * @return array|\Requests_Utility_CaseInsensitiveDictionary The headers of the response. Empty array if incorrect parameter given.
  200. */
  201. function wp_remote_retrieve_headers( $response ) {
  202. if ( is_wp_error( $response ) || ! isset( $response['headers'] ) ) {
  203. return array();
  204. }
  205. return $response['headers'];
  206. }
  207. /**
  208. * Retrieve a single header by name from the raw response.
  209. *
  210. * @since 2.7.0
  211. *
  212. * @param array|WP_Error $response HTTP response.
  213. * @param string $header Header name to retrieve value from.
  214. * @return string The header value. Empty string on if incorrect parameter given, or if the header doesn't exist.
  215. */
  216. function wp_remote_retrieve_header( $response, $header ) {
  217. if ( is_wp_error( $response ) || ! isset( $response['headers'] ) ) {
  218. return '';
  219. }
  220. if ( isset( $response['headers'][ $header ] ) ) {
  221. return $response['headers'][ $header ];
  222. }
  223. return '';
  224. }
  225. /**
  226. * Retrieve only the response code from the raw response.
  227. *
  228. * Will return an empty array if incorrect parameter value is given.
  229. *
  230. * @since 2.7.0
  231. *
  232. * @param array|WP_Error $response HTTP response.
  233. * @return int|string The response code as an integer. Empty string on incorrect parameter given.
  234. */
  235. function wp_remote_retrieve_response_code( $response ) {
  236. if ( is_wp_error( $response ) || ! isset( $response['response'] ) || ! is_array( $response['response'] ) ) {
  237. return '';
  238. }
  239. return $response['response']['code'];
  240. }
  241. /**
  242. * Retrieve only the response message from the raw response.
  243. *
  244. * Will return an empty array if incorrect parameter value is given.
  245. *
  246. * @since 2.7.0
  247. *
  248. * @param array|WP_Error $response HTTP response.
  249. * @return string The response message. Empty string on incorrect parameter given.
  250. */
  251. function wp_remote_retrieve_response_message( $response ) {
  252. if ( is_wp_error( $response ) || ! isset( $response['response'] ) || ! is_array( $response['response'] ) ) {
  253. return '';
  254. }
  255. return $response['response']['message'];
  256. }
  257. /**
  258. * Retrieve only the body from the raw response.
  259. *
  260. * @since 2.7.0
  261. *
  262. * @param array|WP_Error $response HTTP response.
  263. * @return string The body of the response. Empty string if no body or incorrect parameter given.
  264. */
  265. function wp_remote_retrieve_body( $response ) {
  266. if ( is_wp_error( $response ) || ! isset( $response['body'] ) ) {
  267. return '';
  268. }
  269. return $response['body'];
  270. }
  271. /**
  272. * Retrieve only the cookies from the raw response.
  273. *
  274. * @since 4.4.0
  275. *
  276. * @param array|WP_Error $response HTTP response.
  277. * @return WP_Http_Cookie[] An array of `WP_Http_Cookie` objects from the response. Empty array if there are none, or the response is a WP_Error.
  278. */
  279. function wp_remote_retrieve_cookies( $response ) {
  280. if ( is_wp_error( $response ) || empty( $response['cookies'] ) ) {
  281. return array();
  282. }
  283. return $response['cookies'];
  284. }
  285. /**
  286. * Retrieve a single cookie by name from the raw response.
  287. *
  288. * @since 4.4.0
  289. *
  290. * @param array|WP_Error $response HTTP response.
  291. * @param string $name The name of the cookie to retrieve.
  292. * @return WP_Http_Cookie|string The `WP_Http_Cookie` object. Empty string if the cookie isn't present in the response.
  293. */
  294. function wp_remote_retrieve_cookie( $response, $name ) {
  295. $cookies = wp_remote_retrieve_cookies( $response );
  296. if ( empty( $cookies ) ) {
  297. return '';
  298. }
  299. foreach ( $cookies as $cookie ) {
  300. if ( $cookie->name === $name ) {
  301. return $cookie;
  302. }
  303. }
  304. return '';
  305. }
  306. /**
  307. * Retrieve a single cookie's value by name from the raw response.
  308. *
  309. * @since 4.4.0
  310. *
  311. * @param array|WP_Error $response HTTP response.
  312. * @param string $name The name of the cookie to retrieve.
  313. * @return string The value of the cookie. Empty string if the cookie isn't present in the response.
  314. */
  315. function wp_remote_retrieve_cookie_value( $response, $name ) {
  316. $cookie = wp_remote_retrieve_cookie( $response, $name );
  317. if ( ! is_a( $cookie, 'WP_Http_Cookie' ) ) {
  318. return '';
  319. }
  320. return $cookie->value;
  321. }
  322. /**
  323. * Determines if there is an HTTP Transport that can process this request.
  324. *
  325. * @since 3.2.0
  326. *
  327. * @param array $capabilities Array of capabilities to test or a wp_remote_request() $args array.
  328. * @param string $url Optional. If given, will check if the URL requires SSL and adds
  329. * that requirement to the capabilities array.
  330. *
  331. * @return bool
  332. */
  333. function wp_http_supports( $capabilities = array(), $url = null ) {
  334. $http = _wp_http_get_object();
  335. $capabilities = wp_parse_args( $capabilities );
  336. $count = count( $capabilities );
  337. // If we have a numeric $capabilities array, spoof a wp_remote_request() associative $args array
  338. if ( $count && count( array_filter( array_keys( $capabilities ), 'is_numeric' ) ) == $count ) {
  339. $capabilities = array_combine( array_values( $capabilities ), array_fill( 0, $count, true ) );
  340. }
  341. if ( $url && ! isset( $capabilities['ssl'] ) ) {
  342. $scheme = parse_url( $url, PHP_URL_SCHEME );
  343. if ( 'https' == $scheme || 'ssl' == $scheme ) {
  344. $capabilities['ssl'] = true;
  345. }
  346. }
  347. return (bool) $http->_get_first_available_transport( $capabilities );
  348. }
  349. /**
  350. * Get the HTTP Origin of the current request.
  351. *
  352. * @since 3.4.0
  353. *
  354. * @return string URL of the origin. Empty string if no origin.
  355. */
  356. function get_http_origin() {
  357. $origin = '';
  358. if ( ! empty( $_SERVER['HTTP_ORIGIN'] ) ) {
  359. $origin = $_SERVER['HTTP_ORIGIN'];
  360. }
  361. /**
  362. * Change the origin of an HTTP request.
  363. *
  364. * @since 3.4.0
  365. *
  366. * @param string $origin The original origin for the request.
  367. */
  368. return apply_filters( 'http_origin', $origin );
  369. }
  370. /**
  371. * Retrieve list of allowed HTTP origins.
  372. *
  373. * @since 3.4.0
  374. *
  375. * @return string[] Array of origin URLs.
  376. */
  377. function get_allowed_http_origins() {
  378. $admin_origin = parse_url( admin_url() );
  379. $home_origin = parse_url( home_url() );
  380. // @todo preserve port?
  381. $allowed_origins = array_unique(
  382. array(
  383. 'http://' . $admin_origin['host'],
  384. 'https://' . $admin_origin['host'],
  385. 'http://' . $home_origin['host'],
  386. 'https://' . $home_origin['host'],
  387. )
  388. );
  389. /**
  390. * Change the origin types allowed for HTTP requests.
  391. *
  392. * @since 3.4.0
  393. *
  394. * @param string[] $allowed_origins {
  395. * Array of default allowed HTTP origins.
  396. *
  397. * @type string $0 Non-secure URL for admin origin.
  398. * @type string $1 Secure URL for admin origin.
  399. * @type string $2 Non-secure URL for home origin.
  400. * @type string $3 Secure URL for home origin.
  401. * }
  402. */
  403. return apply_filters( 'allowed_http_origins', $allowed_origins );
  404. }
  405. /**
  406. * Determines if the HTTP origin is an authorized one.
  407. *
  408. * @since 3.4.0
  409. *
  410. * @param null|string $origin Origin URL. If not provided, the value of get_http_origin() is used.
  411. * @return string Origin URL if allowed, empty string if not.
  412. */
  413. function is_allowed_http_origin( $origin = null ) {
  414. $origin_arg = $origin;
  415. if ( null === $origin ) {
  416. $origin = get_http_origin();
  417. }
  418. if ( $origin && ! in_array( $origin, get_allowed_http_origins() ) ) {
  419. $origin = '';
  420. }
  421. /**
  422. * Change the allowed HTTP origin result.
  423. *
  424. * @since 3.4.0
  425. *
  426. * @param string $origin Origin URL if allowed, empty string if not.
  427. * @param string $origin_arg Original origin string passed into is_allowed_http_origin function.
  428. */
  429. return apply_filters( 'allowed_http_origin', $origin, $origin_arg );
  430. }
  431. /**
  432. * Send Access-Control-Allow-Origin and related headers if the current request
  433. * is from an allowed origin.
  434. *
  435. * If the request is an OPTIONS request, the script exits with either access
  436. * control headers sent, or a 403 response if the origin is not allowed. For
  437. * other request methods, you will receive a return value.
  438. *
  439. * @since 3.4.0
  440. *
  441. * @return string|false Returns the origin URL if headers are sent. Returns false
  442. * if headers are not sent.
  443. */
  444. function send_origin_headers() {
  445. $origin = get_http_origin();
  446. if ( is_allowed_http_origin( $origin ) ) {
  447. header( 'Access-Control-Allow-Origin: ' . $origin );
  448. header( 'Access-Control-Allow-Credentials: true' );
  449. if ( 'OPTIONS' === $_SERVER['REQUEST_METHOD'] ) {
  450. exit;
  451. }
  452. return $origin;
  453. }
  454. if ( 'OPTIONS' === $_SERVER['REQUEST_METHOD'] ) {
  455. status_header( 403 );
  456. exit;
  457. }
  458. return false;
  459. }
  460. /**
  461. * Validate a URL for safe use in the HTTP API.
  462. *
  463. * @since 3.5.2
  464. *
  465. * @param string $url Request URL.
  466. * @return false|string URL or false on failure.
  467. */
  468. function wp_http_validate_url( $url ) {
  469. $original_url = $url;
  470. $url = wp_kses_bad_protocol( $url, array( 'http', 'https' ) );
  471. if ( ! $url || strtolower( $url ) !== strtolower( $original_url ) ) {
  472. return false;
  473. }
  474. $parsed_url = @parse_url( $url );
  475. if ( ! $parsed_url || empty( $parsed_url['host'] ) ) {
  476. return false;
  477. }
  478. if ( isset( $parsed_url['user'] ) || isset( $parsed_url['pass'] ) ) {
  479. return false;
  480. }
  481. if ( false !== strpbrk( $parsed_url['host'], ':#?[]' ) ) {
  482. return false;
  483. }
  484. $parsed_home = @parse_url( get_option( 'home' ) );
  485. if ( isset( $parsed_home['host'] ) ) {
  486. $same_host = strtolower( $parsed_home['host'] ) === strtolower( $parsed_url['host'] );
  487. } else {
  488. $same_host = false;
  489. }
  490. if ( ! $same_host ) {
  491. $host = trim( $parsed_url['host'], '.' );
  492. if ( preg_match( '#^(([1-9]?\d|1\d\d|25[0-5]|2[0-4]\d)\.){3}([1-9]?\d|1\d\d|25[0-5]|2[0-4]\d)$#', $host ) ) {
  493. $ip = $host;
  494. } else {
  495. $ip = gethostbyname( $host );
  496. if ( $ip === $host ) { // Error condition for gethostbyname()
  497. return false;
  498. }
  499. }
  500. if ( $ip ) {
  501. $parts = array_map( 'intval', explode( '.', $ip ) );
  502. if ( 127 === $parts[0] || 10 === $parts[0] || 0 === $parts[0]
  503. || ( 172 === $parts[0] && 16 <= $parts[1] && 31 >= $parts[1] )
  504. || ( 192 === $parts[0] && 168 === $parts[1] )
  505. ) {
  506. // If host appears local, reject unless specifically allowed.
  507. /**
  508. * Check if HTTP request is external or not.
  509. *
  510. * Allows to change and allow external requests for the HTTP request.
  511. *
  512. * @since 3.6.0
  513. *
  514. * @param bool $external Whether HTTP request is external or not.
  515. * @param string $host Host name of the requested URL.
  516. * @param string $url Requested URL.
  517. */
  518. if ( ! apply_filters( 'http_request_host_is_external', false, $host, $url ) ) {
  519. return false;
  520. }
  521. }
  522. }
  523. }
  524. if ( empty( $parsed_url['port'] ) ) {
  525. return $url;
  526. }
  527. $port = $parsed_url['port'];
  528. if ( 80 === $port || 443 === $port || 8080 === $port ) {
  529. return $url;
  530. }
  531. if ( $parsed_home && $same_host && isset( $parsed_home['port'] ) && $parsed_home['port'] === $port ) {
  532. return $url;
  533. }
  534. return false;
  535. }
  536. /**
  537. * Whitelists allowed redirect hosts for safe HTTP requests as well.
  538. *
  539. * Attached to the {@see 'http_request_host_is_external'} filter.
  540. *
  541. * @since 3.6.0
  542. *
  543. * @param bool $is_external
  544. * @param string $host
  545. * @return bool
  546. */
  547. function allowed_http_request_hosts( $is_external, $host ) {
  548. if ( ! $is_external && wp_validate_redirect( 'http://' . $host ) ) {
  549. $is_external = true;
  550. }
  551. return $is_external;
  552. }
  553. /**
  554. * Whitelists any domain in a multisite installation for safe HTTP requests.
  555. *
  556. * Attached to the {@see 'http_request_host_is_external'} filter.
  557. *
  558. * @since 3.6.0
  559. *
  560. * @global wpdb $wpdb WordPress database abstraction object.
  561. * @staticvar array $queried
  562. *
  563. * @param bool $is_external
  564. * @param string $host
  565. * @return bool
  566. */
  567. function ms_allowed_http_request_hosts( $is_external, $host ) {
  568. global $wpdb;
  569. static $queried = array();
  570. if ( $is_external ) {
  571. return $is_external;
  572. }
  573. if ( $host === get_network()->domain ) {
  574. return true;
  575. }
  576. if ( isset( $queried[ $host ] ) ) {
  577. return $queried[ $host ];
  578. }
  579. $queried[ $host ] = (bool) $wpdb->get_var( $wpdb->prepare( "SELECT domain FROM $wpdb->blogs WHERE domain = %s LIMIT 1", $host ) );
  580. return $queried[ $host ];
  581. }
  582. /**
  583. * A wrapper for PHP's parse_url() function that handles consistency in the return
  584. * values across PHP versions.
  585. *
  586. * PHP 5.4.7 expanded parse_url()'s ability to handle non-absolute url's, including
  587. * schemeless and relative url's with :// in the path. This function works around
  588. * those limitations providing a standard output on PHP 5.2~5.4+.
  589. *
  590. * Secondly, across various PHP versions, schemeless URLs starting containing a ":"
  591. * in the query are being handled inconsistently. This function works around those
  592. * differences as well.
  593. *
  594. * Error suppression is used as prior to PHP 5.3.3, an E_WARNING would be generated
  595. * when URL parsing failed.
  596. *
  597. * @since 4.4.0
  598. * @since 4.7.0 The `$component` parameter was added for parity with PHP's `parse_url()`.
  599. *
  600. * @link https://secure.php.net/manual/en/function.parse-url.php
  601. *
  602. * @param string $url The URL to parse.
  603. * @param int $component The specific component to retrieve. Use one of the PHP
  604. * predefined constants to specify which one.
  605. * Defaults to -1 (= return all parts as an array).
  606. * @return mixed False on parse failure; Array of URL components on success;
  607. * When a specific component has been requested: null if the component
  608. * doesn't exist in the given URL; a string or - in the case of
  609. * PHP_URL_PORT - integer when it does. See parse_url()'s return values.
  610. */
  611. function wp_parse_url( $url, $component = -1 ) {
  612. $to_unset = array();
  613. $url = strval( $url );
  614. if ( '//' === substr( $url, 0, 2 ) ) {
  615. $to_unset[] = 'scheme';
  616. $url = 'placeholder:' . $url;
  617. } elseif ( '/' === substr( $url, 0, 1 ) ) {
  618. $to_unset[] = 'scheme';
  619. $to_unset[] = 'host';
  620. $url = 'placeholder://placeholder' . $url;
  621. }
  622. $parts = @parse_url( $url );
  623. if ( false === $parts ) {
  624. // Parsing failure.
  625. return $parts;
  626. }
  627. // Remove the placeholder values.
  628. foreach ( $to_unset as $key ) {
  629. unset( $parts[ $key ] );
  630. }
  631. return _get_component_from_parsed_url_array( $parts, $component );
  632. }
  633. /**
  634. * Retrieve a specific component from a parsed URL array.
  635. *
  636. * @internal
  637. *
  638. * @since 4.7.0
  639. * @access private
  640. *
  641. * @link https://secure.php.net/manual/en/function.parse-url.php
  642. *
  643. * @param array|false $url_parts The parsed URL. Can be false if the URL failed to parse.
  644. * @param int $component The specific component to retrieve. Use one of the PHP
  645. * predefined constants to specify which one.
  646. * Defaults to -1 (= return all parts as an array).
  647. * @return mixed False on parse failure; Array of URL components on success;
  648. * When a specific component has been requested: null if the component
  649. * doesn't exist in the given URL; a string or - in the case of
  650. * PHP_URL_PORT - integer when it does. See parse_url()'s return values.
  651. */
  652. function _get_component_from_parsed_url_array( $url_parts, $component = -1 ) {
  653. if ( -1 === $component ) {
  654. return $url_parts;
  655. }
  656. $key = _wp_translate_php_url_constant_to_key( $component );
  657. if ( false !== $key && is_array( $url_parts ) && isset( $url_parts[ $key ] ) ) {
  658. return $url_parts[ $key ];
  659. } else {
  660. return null;
  661. }
  662. }
  663. /**
  664. * Translate a PHP_URL_* constant to the named array keys PHP uses.
  665. *
  666. * @internal
  667. *
  668. * @since 4.7.0
  669. * @access private
  670. *
  671. * @link https://secure.php.net/manual/en/url.constants.php
  672. *
  673. * @param int $constant PHP_URL_* constant.
  674. * @return string|false The named key or false.
  675. */
  676. function _wp_translate_php_url_constant_to_key( $constant ) {
  677. $translation = array(
  678. PHP_URL_SCHEME => 'scheme',
  679. PHP_URL_HOST => 'host',
  680. PHP_URL_PORT => 'port',
  681. PHP_URL_USER => 'user',
  682. PHP_URL_PASS => 'pass',
  683. PHP_URL_PATH => 'path',
  684. PHP_URL_QUERY => 'query',
  685. PHP_URL_FRAGMENT => 'fragment',
  686. );
  687. if ( isset( $translation[ $constant ] ) ) {
  688. return $translation[ $constant ];
  689. } else {
  690. return false;
  691. }
  692. }