Brak opisu

http.php 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772
  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 array|\Requests_Utility_CaseInsensitiveDictionary The headers of the response. Empty array if incorrect parameter given.
  198. */
  199. function wp_remote_retrieve_headers( $response ) {
  200. if ( is_wp_error( $response ) || ! isset( $response['headers'] ) ) {
  201. return array();
  202. }
  203. return $response['headers'];
  204. }
  205. /**
  206. * Retrieve a single header by name from the raw response.
  207. *
  208. * @since 2.7.0
  209. *
  210. * @param array|WP_Error $response HTTP response.
  211. * @param string $header Header name to retrieve value from.
  212. * @return array|string The header(s) value(s). Array if multiple headers with the same name are retrieved.
  213. * Empty string if incorrect parameter given, or if the header doesn't exist.
  214. */
  215. function wp_remote_retrieve_header( $response, $header ) {
  216. if ( is_wp_error( $response ) || ! isset( $response['headers'] ) ) {
  217. return '';
  218. }
  219. if ( isset( $response['headers'][ $header ] ) ) {
  220. return $response['headers'][ $header ];
  221. }
  222. return '';
  223. }
  224. /**
  225. * Retrieve only the response code from the raw response.
  226. *
  227. * Will return an empty string if incorrect parameter value is given.
  228. *
  229. * @since 2.7.0
  230. *
  231. * @param array|WP_Error $response HTTP response.
  232. * @return int|string The response code as an integer. Empty string on incorrect parameter given.
  233. */
  234. function wp_remote_retrieve_response_code( $response ) {
  235. if ( is_wp_error( $response ) || ! isset( $response['response'] ) || ! is_array( $response['response'] ) ) {
  236. return '';
  237. }
  238. return $response['response']['code'];
  239. }
  240. /**
  241. * Retrieve only the response message from the raw response.
  242. *
  243. * Will return an empty string if incorrect parameter value is given.
  244. *
  245. * @since 2.7.0
  246. *
  247. * @param array|WP_Error $response HTTP response.
  248. * @return string The response message. Empty string on incorrect parameter given.
  249. */
  250. function wp_remote_retrieve_response_message( $response ) {
  251. if ( is_wp_error( $response ) || ! isset( $response['response'] ) || ! is_array( $response['response'] ) ) {
  252. return '';
  253. }
  254. return $response['response']['message'];
  255. }
  256. /**
  257. * Retrieve only the body from the raw response.
  258. *
  259. * @since 2.7.0
  260. *
  261. * @param array|WP_Error $response HTTP response.
  262. * @return string The body of the response. Empty string if no body or incorrect parameter given.
  263. */
  264. function wp_remote_retrieve_body( $response ) {
  265. if ( is_wp_error( $response ) || ! isset( $response['body'] ) ) {
  266. return '';
  267. }
  268. return $response['body'];
  269. }
  270. /**
  271. * Retrieve only the cookies from the raw response.
  272. *
  273. * @since 4.4.0
  274. *
  275. * @param array|WP_Error $response HTTP response.
  276. * @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.
  277. */
  278. function wp_remote_retrieve_cookies( $response ) {
  279. if ( is_wp_error( $response ) || empty( $response['cookies'] ) ) {
  280. return array();
  281. }
  282. return $response['cookies'];
  283. }
  284. /**
  285. * Retrieve a single cookie by name from the raw response.
  286. *
  287. * @since 4.4.0
  288. *
  289. * @param array|WP_Error $response HTTP response.
  290. * @param string $name The name of the cookie to retrieve.
  291. * @return WP_Http_Cookie|string The `WP_Http_Cookie` object. Empty string if the cookie isn't present in the response.
  292. */
  293. function wp_remote_retrieve_cookie( $response, $name ) {
  294. $cookies = wp_remote_retrieve_cookies( $response );
  295. if ( empty( $cookies ) ) {
  296. return '';
  297. }
  298. foreach ( $cookies as $cookie ) {
  299. if ( $cookie->name === $name ) {
  300. return $cookie;
  301. }
  302. }
  303. return '';
  304. }
  305. /**
  306. * Retrieve a single cookie's value by name from the raw response.
  307. *
  308. * @since 4.4.0
  309. *
  310. * @param array|WP_Error $response HTTP response.
  311. * @param string $name The name of the cookie to retrieve.
  312. * @return string The value of the cookie. Empty string if the cookie isn't present in the response.
  313. */
  314. function wp_remote_retrieve_cookie_value( $response, $name ) {
  315. $cookie = wp_remote_retrieve_cookie( $response, $name );
  316. if ( ! is_a( $cookie, 'WP_Http_Cookie' ) ) {
  317. return '';
  318. }
  319. return $cookie->value;
  320. }
  321. /**
  322. * Determines if there is an HTTP Transport that can process this request.
  323. *
  324. * @since 3.2.0
  325. *
  326. * @param array $capabilities Array of capabilities to test or a wp_remote_request() $args array.
  327. * @param string $url Optional. If given, will check if the URL requires SSL and adds
  328. * that requirement to the capabilities array.
  329. *
  330. * @return bool
  331. */
  332. function wp_http_supports( $capabilities = array(), $url = null ) {
  333. $http = _wp_http_get_object();
  334. $capabilities = wp_parse_args( $capabilities );
  335. $count = count( $capabilities );
  336. // If we have a numeric $capabilities array, spoof a wp_remote_request() associative $args array.
  337. if ( $count && count( array_filter( array_keys( $capabilities ), 'is_numeric' ) ) == $count ) {
  338. $capabilities = array_combine( array_values( $capabilities ), array_fill( 0, $count, true ) );
  339. }
  340. if ( $url && ! isset( $capabilities['ssl'] ) ) {
  341. $scheme = parse_url( $url, PHP_URL_SCHEME );
  342. if ( 'https' === $scheme || 'ssl' === $scheme ) {
  343. $capabilities['ssl'] = true;
  344. }
  345. }
  346. return (bool) $http->_get_first_available_transport( $capabilities );
  347. }
  348. /**
  349. * Get the HTTP Origin of the current request.
  350. *
  351. * @since 3.4.0
  352. *
  353. * @return string URL of the origin. Empty string if no origin.
  354. */
  355. function get_http_origin() {
  356. $origin = '';
  357. if ( ! empty( $_SERVER['HTTP_ORIGIN'] ) ) {
  358. $origin = $_SERVER['HTTP_ORIGIN'];
  359. }
  360. /**
  361. * Change the origin of an HTTP request.
  362. *
  363. * @since 3.4.0
  364. *
  365. * @param string $origin The original origin for the request.
  366. */
  367. return apply_filters( 'http_origin', $origin );
  368. }
  369. /**
  370. * Retrieve list of allowed HTTP origins.
  371. *
  372. * @since 3.4.0
  373. *
  374. * @return string[] Array of origin URLs.
  375. */
  376. function get_allowed_http_origins() {
  377. $admin_origin = parse_url( admin_url() );
  378. $home_origin = parse_url( home_url() );
  379. // @todo Preserve port?
  380. $allowed_origins = array_unique(
  381. array(
  382. 'http://' . $admin_origin['host'],
  383. 'https://' . $admin_origin['host'],
  384. 'http://' . $home_origin['host'],
  385. 'https://' . $home_origin['host'],
  386. )
  387. );
  388. /**
  389. * Change the origin types allowed for HTTP requests.
  390. *
  391. * @since 3.4.0
  392. *
  393. * @param string[] $allowed_origins {
  394. * Array of default allowed HTTP origins.
  395. *
  396. * @type string $0 Non-secure URL for admin origin.
  397. * @type string $1 Secure URL for admin origin.
  398. * @type string $2 Non-secure URL for home origin.
  399. * @type string $3 Secure URL for home origin.
  400. * }
  401. */
  402. return apply_filters( 'allowed_http_origins', $allowed_origins );
  403. }
  404. /**
  405. * Determines if the HTTP origin is an authorized one.
  406. *
  407. * @since 3.4.0
  408. *
  409. * @param null|string $origin Origin URL. If not provided, the value of get_http_origin() is used.
  410. * @return string Origin URL if allowed, empty string if not.
  411. */
  412. function is_allowed_http_origin( $origin = null ) {
  413. $origin_arg = $origin;
  414. if ( null === $origin ) {
  415. $origin = get_http_origin();
  416. }
  417. if ( $origin && ! in_array( $origin, get_allowed_http_origins(), true ) ) {
  418. $origin = '';
  419. }
  420. /**
  421. * Change the allowed HTTP origin result.
  422. *
  423. * @since 3.4.0
  424. *
  425. * @param string $origin Origin URL if allowed, empty string if not.
  426. * @param string $origin_arg Original origin string passed into is_allowed_http_origin function.
  427. */
  428. return apply_filters( 'allowed_http_origin', $origin, $origin_arg );
  429. }
  430. /**
  431. * Send Access-Control-Allow-Origin and related headers if the current request
  432. * is from an allowed origin.
  433. *
  434. * If the request is an OPTIONS request, the script exits with either access
  435. * control headers sent, or a 403 response if the origin is not allowed. For
  436. * other request methods, you will receive a return value.
  437. *
  438. * @since 3.4.0
  439. *
  440. * @return string|false Returns the origin URL if headers are sent. Returns false
  441. * if headers are not sent.
  442. */
  443. function send_origin_headers() {
  444. $origin = get_http_origin();
  445. if ( is_allowed_http_origin( $origin ) ) {
  446. header( 'Access-Control-Allow-Origin: ' . $origin );
  447. header( 'Access-Control-Allow-Credentials: true' );
  448. if ( 'OPTIONS' === $_SERVER['REQUEST_METHOD'] ) {
  449. exit;
  450. }
  451. return $origin;
  452. }
  453. if ( 'OPTIONS' === $_SERVER['REQUEST_METHOD'] ) {
  454. status_header( 403 );
  455. exit;
  456. }
  457. return false;
  458. }
  459. /**
  460. * Validate a URL for safe use in the HTTP API.
  461. *
  462. * @since 3.5.2
  463. *
  464. * @param string $url Request URL.
  465. * @return string|false URL or false on failure.
  466. */
  467. function wp_http_validate_url( $url ) {
  468. if ( ! is_string( $url ) || '' === $url || is_numeric( $url ) ) {
  469. return false;
  470. }
  471. $original_url = $url;
  472. $url = wp_kses_bad_protocol( $url, array( 'http', 'https' ) );
  473. if ( ! $url || strtolower( $url ) !== strtolower( $original_url ) ) {
  474. return false;
  475. }
  476. $parsed_url = parse_url( $url );
  477. if ( ! $parsed_url || empty( $parsed_url['host'] ) ) {
  478. return false;
  479. }
  480. if ( isset( $parsed_url['user'] ) || isset( $parsed_url['pass'] ) ) {
  481. return false;
  482. }
  483. if ( false !== strpbrk( $parsed_url['host'], ':#?[]' ) ) {
  484. return false;
  485. }
  486. $parsed_home = parse_url( get_option( 'home' ) );
  487. $same_host = isset( $parsed_home['host'] ) && strtolower( $parsed_home['host'] ) === strtolower( $parsed_url['host'] );
  488. $host = trim( $parsed_url['host'], '.' );
  489. if ( ! $same_host ) {
  490. 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 ) ) {
  491. $ip = $host;
  492. } else {
  493. $ip = gethostbyname( $host );
  494. if ( $ip === $host ) { // Error condition for gethostbyname().
  495. return false;
  496. }
  497. }
  498. if ( $ip ) {
  499. $parts = array_map( 'intval', explode( '.', $ip ) );
  500. if ( 127 === $parts[0] || 10 === $parts[0] || 0 === $parts[0]
  501. || ( 172 === $parts[0] && 16 <= $parts[1] && 31 >= $parts[1] )
  502. || ( 192 === $parts[0] && 168 === $parts[1] )
  503. ) {
  504. // If host appears local, reject unless specifically allowed.
  505. /**
  506. * Check if HTTP request is external or not.
  507. *
  508. * Allows to change and allow external requests for the HTTP request.
  509. *
  510. * @since 3.6.0
  511. *
  512. * @param bool $external Whether HTTP request is external or not.
  513. * @param string $host Host name of the requested URL.
  514. * @param string $url Requested URL.
  515. */
  516. if ( ! apply_filters( 'http_request_host_is_external', false, $host, $url ) ) {
  517. return false;
  518. }
  519. }
  520. }
  521. }
  522. if ( empty( $parsed_url['port'] ) ) {
  523. return $url;
  524. }
  525. $port = $parsed_url['port'];
  526. /**
  527. * Controls the list of ports considered safe in HTTP API.
  528. *
  529. * Allows to change and allow external requests for the HTTP request.
  530. *
  531. * @since 5.9.0
  532. *
  533. * @param array $allowed_ports Array of integers for valid ports.
  534. * @param string $host Host name of the requested URL.
  535. * @param string $url Requested URL.
  536. */
  537. $allowed_ports = apply_filters( 'http_allowed_safe_ports', array( 80, 443, 8080 ), $host, $url );
  538. if ( is_array( $allowed_ports ) && in_array( $port, $allowed_ports, true ) ) {
  539. return $url;
  540. }
  541. if ( $parsed_home && $same_host && isset( $parsed_home['port'] ) && $parsed_home['port'] === $port ) {
  542. return $url;
  543. }
  544. return false;
  545. }
  546. /**
  547. * Mark allowed redirect hosts safe for HTTP requests as well.
  548. *
  549. * Attached to the {@see 'http_request_host_is_external'} filter.
  550. *
  551. * @since 3.6.0
  552. *
  553. * @param bool $is_external
  554. * @param string $host
  555. * @return bool
  556. */
  557. function allowed_http_request_hosts( $is_external, $host ) {
  558. if ( ! $is_external && wp_validate_redirect( 'http://' . $host ) ) {
  559. $is_external = true;
  560. }
  561. return $is_external;
  562. }
  563. /**
  564. * Adds any domain in a multisite installation for safe HTTP requests to the
  565. * allowed list.
  566. *
  567. * Attached to the {@see 'http_request_host_is_external'} filter.
  568. *
  569. * @since 3.6.0
  570. *
  571. * @global wpdb $wpdb WordPress database abstraction object.
  572. *
  573. * @param bool $is_external
  574. * @param string $host
  575. * @return bool
  576. */
  577. function ms_allowed_http_request_hosts( $is_external, $host ) {
  578. global $wpdb;
  579. static $queried = array();
  580. if ( $is_external ) {
  581. return $is_external;
  582. }
  583. if ( get_network()->domain === $host ) {
  584. return true;
  585. }
  586. if ( isset( $queried[ $host ] ) ) {
  587. return $queried[ $host ];
  588. }
  589. $queried[ $host ] = (bool) $wpdb->get_var( $wpdb->prepare( "SELECT domain FROM $wpdb->blogs WHERE domain = %s LIMIT 1", $host ) );
  590. return $queried[ $host ];
  591. }
  592. /**
  593. * A wrapper for PHP's parse_url() function that handles consistency in the return values
  594. * across PHP versions.
  595. *
  596. * PHP 5.4.7 expanded parse_url()'s ability to handle non-absolute URLs, including
  597. * schemeless and relative URLs with "://" in the path. This function works around
  598. * those limitations providing a standard output on PHP 5.2~5.4+.
  599. *
  600. * Secondly, across various PHP versions, schemeless URLs containing a ":" in the query
  601. * are being handled inconsistently. This function works around those differences as well.
  602. *
  603. * @since 4.4.0
  604. * @since 4.7.0 The `$component` parameter was added for parity with PHP's `parse_url()`.
  605. *
  606. * @link https://www.php.net/manual/en/function.parse-url.php
  607. *
  608. * @param string $url The URL to parse.
  609. * @param int $component The specific component to retrieve. Use one of the PHP
  610. * predefined constants to specify which one.
  611. * Defaults to -1 (= return all parts as an array).
  612. * @return mixed False on parse failure; Array of URL components on success;
  613. * When a specific component has been requested: null if the component
  614. * doesn't exist in the given URL; a string or - in the case of
  615. * PHP_URL_PORT - integer when it does. See parse_url()'s return values.
  616. */
  617. function wp_parse_url( $url, $component = -1 ) {
  618. $to_unset = array();
  619. $url = (string) $url;
  620. if ( '//' === substr( $url, 0, 2 ) ) {
  621. $to_unset[] = 'scheme';
  622. $url = 'placeholder:' . $url;
  623. } elseif ( '/' === substr( $url, 0, 1 ) ) {
  624. $to_unset[] = 'scheme';
  625. $to_unset[] = 'host';
  626. $url = 'placeholder://placeholder' . $url;
  627. }
  628. $parts = parse_url( $url );
  629. if ( false === $parts ) {
  630. // Parsing failure.
  631. return $parts;
  632. }
  633. // Remove the placeholder values.
  634. foreach ( $to_unset as $key ) {
  635. unset( $parts[ $key ] );
  636. }
  637. return _get_component_from_parsed_url_array( $parts, $component );
  638. }
  639. /**
  640. * Retrieve a specific component from a parsed URL array.
  641. *
  642. * @internal
  643. *
  644. * @since 4.7.0
  645. * @access private
  646. *
  647. * @link https://www.php.net/manual/en/function.parse-url.php
  648. *
  649. * @param array|false $url_parts The parsed URL. Can be false if the URL failed to parse.
  650. * @param int $component The specific component to retrieve. Use one of the PHP
  651. * predefined constants to specify which one.
  652. * Defaults to -1 (= return all parts as an array).
  653. * @return mixed False on parse failure; Array of URL components on success;
  654. * When a specific component has been requested: null if the component
  655. * doesn't exist in the given URL; a string or - in the case of
  656. * PHP_URL_PORT - integer when it does. See parse_url()'s return values.
  657. */
  658. function _get_component_from_parsed_url_array( $url_parts, $component = -1 ) {
  659. if ( -1 === $component ) {
  660. return $url_parts;
  661. }
  662. $key = _wp_translate_php_url_constant_to_key( $component );
  663. if ( false !== $key && is_array( $url_parts ) && isset( $url_parts[ $key ] ) ) {
  664. return $url_parts[ $key ];
  665. } else {
  666. return null;
  667. }
  668. }
  669. /**
  670. * Translate a PHP_URL_* constant to the named array keys PHP uses.
  671. *
  672. * @internal
  673. *
  674. * @since 4.7.0
  675. * @access private
  676. *
  677. * @link https://www.php.net/manual/en/url.constants.php
  678. *
  679. * @param int $constant PHP_URL_* constant.
  680. * @return string|false The named key or false.
  681. */
  682. function _wp_translate_php_url_constant_to_key( $constant ) {
  683. $translation = array(
  684. PHP_URL_SCHEME => 'scheme',
  685. PHP_URL_HOST => 'host',
  686. PHP_URL_PORT => 'port',
  687. PHP_URL_USER => 'user',
  688. PHP_URL_PASS => 'pass',
  689. PHP_URL_PATH => 'path',
  690. PHP_URL_QUERY => 'query',
  691. PHP_URL_FRAGMENT => 'fragment',
  692. );
  693. if ( isset( $translation[ $constant ] ) ) {
  694. return $translation[ $constant ];
  695. } else {
  696. return false;
  697. }
  698. }