http.php 23 KB

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