class-wc-api-server.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775
  1. <?php
  2. /**
  3. * WooCommerce API
  4. *
  5. * Handles REST API requests
  6. *
  7. * This class and related code (JSON response handler, resource classes) are based on WP-API v0.6 (https://github.com/WP-API/WP-API)
  8. * Many thanks to Ryan McCue and any other contributors!
  9. *
  10. * @author WooThemes
  11. * @category API
  12. * @package WooCommerce/API
  13. * @since 2.1
  14. */
  15. if ( ! defined( 'ABSPATH' ) ) {
  16. exit; // Exit if accessed directly
  17. }
  18. require_once ABSPATH . 'wp-admin/includes/admin.php';
  19. class WC_API_Server {
  20. const METHOD_GET = 1;
  21. const METHOD_POST = 2;
  22. const METHOD_PUT = 4;
  23. const METHOD_PATCH = 8;
  24. const METHOD_DELETE = 16;
  25. const READABLE = 1; // GET
  26. const CREATABLE = 2; // POST
  27. const EDITABLE = 14; // POST | PUT | PATCH
  28. const DELETABLE = 16; // DELETE
  29. const ALLMETHODS = 31; // GET | POST | PUT | PATCH | DELETE
  30. /**
  31. * Does the endpoint accept a raw request body?
  32. */
  33. const ACCEPT_RAW_DATA = 64;
  34. /** Does the endpoint accept a request body? (either JSON or XML) */
  35. const ACCEPT_DATA = 128;
  36. /**
  37. * Should we hide this endpoint from the index?
  38. */
  39. const HIDDEN_ENDPOINT = 256;
  40. /**
  41. * Map of HTTP verbs to constants
  42. * @var array
  43. */
  44. public static $method_map = array(
  45. 'HEAD' => self::METHOD_GET,
  46. 'GET' => self::METHOD_GET,
  47. 'POST' => self::METHOD_POST,
  48. 'PUT' => self::METHOD_PUT,
  49. 'PATCH' => self::METHOD_PATCH,
  50. 'DELETE' => self::METHOD_DELETE,
  51. );
  52. /**
  53. * Requested path (relative to the API root, wp-json.php)
  54. *
  55. * @var string
  56. */
  57. public $path = '';
  58. /**
  59. * Requested method (GET/HEAD/POST/PUT/PATCH/DELETE)
  60. *
  61. * @var string
  62. */
  63. public $method = 'HEAD';
  64. /**
  65. * Request parameters
  66. *
  67. * This acts as an abstraction of the superglobals
  68. * (GET => $_GET, POST => $_POST)
  69. *
  70. * @var array
  71. */
  72. public $params = array( 'GET' => array(), 'POST' => array() );
  73. /**
  74. * Request headers
  75. *
  76. * @var array
  77. */
  78. public $headers = array();
  79. /**
  80. * Request files (matches $_FILES)
  81. *
  82. * @var array
  83. */
  84. public $files = array();
  85. /**
  86. * Request/Response handler, either JSON by default
  87. * or XML if requested by client
  88. *
  89. * @var WC_API_Handler
  90. */
  91. public $handler;
  92. /**
  93. * Setup class and set request/response handler
  94. *
  95. * @since 2.1
  96. * @param $path
  97. */
  98. public function __construct( $path ) {
  99. if ( empty( $path ) ) {
  100. if ( isset( $_SERVER['PATH_INFO'] ) ) {
  101. $path = $_SERVER['PATH_INFO'];
  102. } else {
  103. $path = '/';
  104. }
  105. }
  106. $this->path = $path;
  107. $this->method = $_SERVER['REQUEST_METHOD'];
  108. $this->params['GET'] = $_GET;
  109. $this->params['POST'] = $_POST;
  110. $this->headers = $this->get_headers( $_SERVER );
  111. $this->files = $_FILES;
  112. // Compatibility for clients that can't use PUT/PATCH/DELETE
  113. if ( isset( $_GET['_method'] ) ) {
  114. $this->method = strtoupper( $_GET['_method'] );
  115. } elseif ( isset( $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'] ) ) {
  116. $this->method = $_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE'];
  117. }
  118. // load response handler
  119. $handler_class = apply_filters( 'woocommerce_api_default_response_handler', 'WC_API_JSON_Handler', $this->path, $this );
  120. $this->handler = new $handler_class();
  121. }
  122. /**
  123. * Check authentication for the request
  124. *
  125. * @since 2.1
  126. * @return WP_User|WP_Error WP_User object indicates successful login, WP_Error indicates unsuccessful login
  127. */
  128. public function check_authentication() {
  129. // allow plugins to remove default authentication or add their own authentication
  130. $user = apply_filters( 'woocommerce_api_check_authentication', null, $this );
  131. if ( is_a( $user, 'WP_User' ) ) {
  132. // API requests run under the context of the authenticated user
  133. wp_set_current_user( $user->ID );
  134. } elseif ( ! is_wp_error( $user ) ) {
  135. // WP_Errors are handled in serve_request()
  136. $user = new WP_Error( 'woocommerce_api_authentication_error', __( 'Invalid authentication method', 'woocommerce' ), array( 'code' => 500 ) );
  137. }
  138. return $user;
  139. }
  140. /**
  141. * Convert an error to an array
  142. *
  143. * This iterates over all error codes and messages to change it into a flat
  144. * array. This enables simpler client behaviour, as it is represented as a
  145. * list in JSON rather than an object/map
  146. *
  147. * @since 2.1
  148. * @param WP_Error $error
  149. * @return array List of associative arrays with code and message keys
  150. */
  151. protected function error_to_array( $error ) {
  152. $errors = array();
  153. foreach ( (array) $error->errors as $code => $messages ) {
  154. foreach ( (array) $messages as $message ) {
  155. $errors[] = array( 'code' => $code, 'message' => $message );
  156. }
  157. }
  158. return array( 'errors' => $errors );
  159. }
  160. /**
  161. * Handle serving an API request
  162. *
  163. * Matches the current server URI to a route and runs the first matching
  164. * callback then outputs a JSON representation of the returned value.
  165. *
  166. * @since 2.1
  167. * @uses WC_API_Server::dispatch()
  168. */
  169. public function serve_request() {
  170. do_action( 'woocommerce_api_server_before_serve', $this );
  171. $this->header( 'Content-Type', $this->handler->get_content_type(), true );
  172. // the API is enabled by default
  173. if ( ! apply_filters( 'woocommerce_api_enabled', true, $this ) || ( 'no' === get_option( 'woocommerce_api_enabled' ) ) ) {
  174. $this->send_status( 404 );
  175. echo $this->handler->generate_response( array( 'errors' => array( 'code' => 'woocommerce_api_disabled', 'message' => 'The WooCommerce API is disabled on this site' ) ) );
  176. return;
  177. }
  178. $result = $this->check_authentication();
  179. // if authorization check was successful, dispatch the request
  180. if ( ! is_wp_error( $result ) ) {
  181. $result = $this->dispatch();
  182. }
  183. // handle any dispatch errors
  184. if ( is_wp_error( $result ) ) {
  185. $data = $result->get_error_data();
  186. if ( is_array( $data ) && isset( $data['status'] ) ) {
  187. $this->send_status( $data['status'] );
  188. }
  189. $result = $this->error_to_array( $result );
  190. }
  191. // This is a filter rather than an action, since this is designed to be
  192. // re-entrant if needed
  193. $served = apply_filters( 'woocommerce_api_serve_request', false, $result, $this );
  194. if ( ! $served ) {
  195. if ( 'HEAD' === $this->method ) {
  196. return;
  197. }
  198. echo $this->handler->generate_response( $result );
  199. }
  200. }
  201. /**
  202. * Retrieve the route map
  203. *
  204. * The route map is an associative array with path regexes as the keys. The
  205. * value is an indexed array with the callback function/method as the first
  206. * item, and a bitmask of HTTP methods as the second item (see the class
  207. * constants).
  208. *
  209. * Each route can be mapped to more than one callback by using an array of
  210. * the indexed arrays. This allows mapping e.g. GET requests to one callback
  211. * and POST requests to another.
  212. *
  213. * Note that the path regexes (array keys) must have @ escaped, as this is
  214. * used as the delimiter with preg_match()
  215. *
  216. * @since 2.1
  217. * @return array `'/path/regex' => array( $callback, $bitmask )` or `'/path/regex' => array( array( $callback, $bitmask ), ...)`
  218. */
  219. public function get_routes() {
  220. // index added by default
  221. $endpoints = array(
  222. '/' => array( array( $this, 'get_index' ), self::READABLE ),
  223. );
  224. $endpoints = apply_filters( 'woocommerce_api_endpoints', $endpoints );
  225. // Normalise the endpoints
  226. foreach ( $endpoints as $route => &$handlers ) {
  227. if ( count( $handlers ) <= 2 && isset( $handlers[1] ) && ! is_array( $handlers[1] ) ) {
  228. $handlers = array( $handlers );
  229. }
  230. }
  231. return $endpoints;
  232. }
  233. /**
  234. * Match the request to a callback and call it
  235. *
  236. * @since 2.1
  237. * @return mixed The value returned by the callback, or a WP_Error instance
  238. */
  239. public function dispatch() {
  240. switch ( $this->method ) {
  241. case 'HEAD' :
  242. case 'GET' :
  243. $method = self::METHOD_GET;
  244. break;
  245. case 'POST' :
  246. $method = self::METHOD_POST;
  247. break;
  248. case 'PUT' :
  249. $method = self::METHOD_PUT;
  250. break;
  251. case 'PATCH' :
  252. $method = self::METHOD_PATCH;
  253. break;
  254. case 'DELETE' :
  255. $method = self::METHOD_DELETE;
  256. break;
  257. default :
  258. return new WP_Error( 'woocommerce_api_unsupported_method', __( 'Unsupported request method', 'woocommerce' ), array( 'status' => 400 ) );
  259. }
  260. foreach ( $this->get_routes() as $route => $handlers ) {
  261. foreach ( $handlers as $handler ) {
  262. $callback = $handler[0];
  263. $supported = isset( $handler[1] ) ? $handler[1] : self::METHOD_GET;
  264. if ( ! ( $supported & $method ) ) {
  265. continue;
  266. }
  267. $match = preg_match( '@^' . $route . '$@i', urldecode( $this->path ), $args );
  268. if ( ! $match ) {
  269. continue;
  270. }
  271. if ( ! is_callable( $callback ) ) {
  272. return new WP_Error( 'woocommerce_api_invalid_handler', __( 'The handler for the route is invalid', 'woocommerce' ), array( 'status' => 500 ) );
  273. }
  274. $args = array_merge( $args, $this->params['GET'] );
  275. if ( $method & self::METHOD_POST ) {
  276. $args = array_merge( $args, $this->params['POST'] );
  277. }
  278. if ( $supported & self::ACCEPT_DATA ) {
  279. $data = $this->handler->parse_body( $this->get_raw_data() );
  280. $args = array_merge( $args, array( 'data' => $data ) );
  281. } elseif ( $supported & self::ACCEPT_RAW_DATA ) {
  282. $data = $this->get_raw_data();
  283. $args = array_merge( $args, array( 'data' => $data ) );
  284. }
  285. $args['_method'] = $method;
  286. $args['_route'] = $route;
  287. $args['_path'] = $this->path;
  288. $args['_headers'] = $this->headers;
  289. $args['_files'] = $this->files;
  290. $args = apply_filters( 'woocommerce_api_dispatch_args', $args, $callback );
  291. // Allow plugins to halt the request via this filter
  292. if ( is_wp_error( $args ) ) {
  293. return $args;
  294. }
  295. $params = $this->sort_callback_params( $callback, $args );
  296. if ( is_wp_error( $params ) ) {
  297. return $params;
  298. }
  299. return call_user_func_array( $callback, $params );
  300. }
  301. }
  302. return new WP_Error( 'woocommerce_api_no_route', __( 'No route was found matching the URL and request method', 'woocommerce' ), array( 'status' => 404 ) );
  303. }
  304. /**
  305. * urldecode deep.
  306. *
  307. * @since 2.2
  308. * @param string|array $value Data to decode with urldecode.
  309. * @return string|array Decoded data.
  310. */
  311. protected function urldecode_deep( $value ) {
  312. if ( is_array( $value ) ) {
  313. return array_map( array( $this, 'urldecode_deep' ), $value );
  314. } else {
  315. return urldecode( $value );
  316. }
  317. }
  318. /**
  319. * Sort parameters by order specified in method declaration
  320. *
  321. * Takes a callback and a list of available params, then filters and sorts
  322. * by the parameters the method actually needs, using the Reflection API
  323. *
  324. * @since 2.2
  325. *
  326. * @param callable|array $callback the endpoint callback
  327. * @param array $provided the provided request parameters
  328. *
  329. * @return array|WP_Error
  330. */
  331. protected function sort_callback_params( $callback, $provided ) {
  332. if ( is_array( $callback ) ) {
  333. $ref_func = new ReflectionMethod( $callback[0], $callback[1] );
  334. } else {
  335. $ref_func = new ReflectionFunction( $callback );
  336. }
  337. $wanted = $ref_func->getParameters();
  338. $ordered_parameters = array();
  339. foreach ( $wanted as $param ) {
  340. if ( isset( $provided[ $param->getName() ] ) ) {
  341. // We have this parameters in the list to choose from
  342. if ( 'data' == $param->getName() ) {
  343. $ordered_parameters[] = $provided[ $param->getName() ];
  344. continue;
  345. }
  346. $ordered_parameters[] = $this->urldecode_deep( $provided[ $param->getName() ] );
  347. } elseif ( $param->isDefaultValueAvailable() ) {
  348. // We don't have this parameter, but it's optional
  349. $ordered_parameters[] = $param->getDefaultValue();
  350. } else {
  351. // We don't have this parameter and it wasn't optional, abort!
  352. return new WP_Error( 'woocommerce_api_missing_callback_param', sprintf( __( 'Missing parameter %s', 'woocommerce' ), $param->getName() ), array( 'status' => 400 ) );
  353. }
  354. }
  355. return $ordered_parameters;
  356. }
  357. /**
  358. * Get the site index.
  359. *
  360. * This endpoint describes the capabilities of the site.
  361. *
  362. * @since 2.3
  363. * @return array Index entity
  364. */
  365. public function get_index() {
  366. // General site data
  367. $available = array(
  368. 'store' => array(
  369. 'name' => get_option( 'blogname' ),
  370. 'description' => get_option( 'blogdescription' ),
  371. 'URL' => get_option( 'siteurl' ),
  372. 'wc_version' => WC()->version,
  373. 'routes' => array(),
  374. 'meta' => array(
  375. 'timezone' => wc_timezone_string(),
  376. 'currency' => get_woocommerce_currency(),
  377. 'currency_format' => get_woocommerce_currency_symbol(),
  378. 'currency_position' => get_option( 'woocommerce_currency_pos' ),
  379. 'thousand_separator' => get_option( 'woocommerce_price_thousand_sep' ),
  380. 'decimal_separator' => get_option( 'woocommerce_price_decimal_sep' ),
  381. 'price_num_decimals' => wc_get_price_decimals(),
  382. 'tax_included' => wc_prices_include_tax(),
  383. 'weight_unit' => get_option( 'woocommerce_weight_unit' ),
  384. 'dimension_unit' => get_option( 'woocommerce_dimension_unit' ),
  385. 'ssl_enabled' => ( 'yes' === get_option( 'woocommerce_force_ssl_checkout' ) ),
  386. 'permalinks_enabled' => ( '' !== get_option( 'permalink_structure' ) ),
  387. 'generate_password' => ( 'yes' === get_option( 'woocommerce_registration_generate_password' ) ),
  388. 'links' => array(
  389. 'help' => 'https://woocommerce.github.io/woocommerce-rest-api-docs/',
  390. ),
  391. ),
  392. ),
  393. );
  394. // Find the available routes
  395. foreach ( $this->get_routes() as $route => $callbacks ) {
  396. $data = array();
  397. $route = preg_replace( '#\(\?P(<\w+?>).*?\)#', '$1', $route );
  398. foreach ( self::$method_map as $name => $bitmask ) {
  399. foreach ( $callbacks as $callback ) {
  400. // Skip to the next route if any callback is hidden
  401. if ( $callback[1] & self::HIDDEN_ENDPOINT ) {
  402. continue 3;
  403. }
  404. if ( $callback[1] & $bitmask ) {
  405. $data['supports'][] = $name;
  406. }
  407. if ( $callback[1] & self::ACCEPT_DATA ) {
  408. $data['accepts_data'] = true;
  409. }
  410. // For non-variable routes, generate links
  411. if ( strpos( $route, '<' ) === false ) {
  412. $data['meta'] = array(
  413. 'self' => get_woocommerce_api_url( $route ),
  414. );
  415. }
  416. }
  417. }
  418. $available['store']['routes'][ $route ] = apply_filters( 'woocommerce_api_endpoints_description', $data );
  419. }
  420. return apply_filters( 'woocommerce_api_index', $available );
  421. }
  422. /**
  423. * Send a HTTP status code
  424. *
  425. * @since 2.1
  426. * @param int $code HTTP status
  427. */
  428. public function send_status( $code ) {
  429. status_header( $code );
  430. }
  431. /**
  432. * Send a HTTP header
  433. *
  434. * @since 2.1
  435. * @param string $key Header key
  436. * @param string $value Header value
  437. * @param boolean $replace Should we replace the existing header?
  438. */
  439. public function header( $key, $value, $replace = true ) {
  440. header( sprintf( '%s: %s', $key, $value ), $replace );
  441. }
  442. /**
  443. * Send a Link header
  444. *
  445. * @internal The $rel parameter is first, as this looks nicer when sending multiple
  446. *
  447. * @link http://tools.ietf.org/html/rfc5988
  448. * @link http://www.iana.org/assignments/link-relations/link-relations.xml
  449. *
  450. * @since 2.1
  451. * @param string $rel Link relation. Either a registered type, or an absolute URL
  452. * @param string $link Target IRI for the link
  453. * @param array $other Other parameters to send, as an associative array
  454. */
  455. public function link_header( $rel, $link, $other = array() ) {
  456. $header = sprintf( '<%s>; rel="%s"', $link, esc_attr( $rel ) );
  457. foreach ( $other as $key => $value ) {
  458. if ( 'title' == $key ) {
  459. $value = '"' . $value . '"';
  460. }
  461. $header .= '; ' . $key . '=' . $value;
  462. }
  463. $this->header( 'Link', $header, false );
  464. }
  465. /**
  466. * Send pagination headers for resources
  467. *
  468. * @since 2.1
  469. * @param WP_Query|WP_User_Query|stdClass $query
  470. */
  471. public function add_pagination_headers( $query ) {
  472. // WP_User_Query
  473. if ( is_a( $query, 'WP_User_Query' ) ) {
  474. $single = count( $query->get_results() ) == 1;
  475. $total = $query->get_total();
  476. if ( $query->get( 'number' ) > 0 ) {
  477. $page = ( $query->get( 'offset' ) / $query->get( 'number' ) ) + 1;
  478. $total_pages = ceil( $total / $query->get( 'number' ) );
  479. } else {
  480. $page = 1;
  481. $total_pages = 1;
  482. }
  483. } elseif ( is_a( $query, 'stdClass' ) ) {
  484. $page = $query->page;
  485. $single = $query->is_single;
  486. $total = $query->total;
  487. $total_pages = $query->total_pages;
  488. // WP_Query
  489. } else {
  490. $page = $query->get( 'paged' );
  491. $single = $query->is_single();
  492. $total = $query->found_posts;
  493. $total_pages = $query->max_num_pages;
  494. }
  495. if ( ! $page ) {
  496. $page = 1;
  497. }
  498. $next_page = absint( $page ) + 1;
  499. if ( ! $single ) {
  500. // first/prev
  501. if ( $page > 1 ) {
  502. $this->link_header( 'first', $this->get_paginated_url( 1 ) );
  503. $this->link_header( 'prev', $this->get_paginated_url( $page -1 ) );
  504. }
  505. // next
  506. if ( $next_page <= $total_pages ) {
  507. $this->link_header( 'next', $this->get_paginated_url( $next_page ) );
  508. }
  509. // last
  510. if ( $page != $total_pages ) {
  511. $this->link_header( 'last', $this->get_paginated_url( $total_pages ) );
  512. }
  513. }
  514. $this->header( 'X-WC-Total', $total );
  515. $this->header( 'X-WC-TotalPages', $total_pages );
  516. do_action( 'woocommerce_api_pagination_headers', $this, $query );
  517. }
  518. /**
  519. * Returns the request URL with the page query parameter set to the specified page
  520. *
  521. * @since 2.1
  522. * @param int $page
  523. * @return string
  524. */
  525. private function get_paginated_url( $page ) {
  526. // remove existing page query param
  527. $request = remove_query_arg( 'page' );
  528. // add provided page query param
  529. $request = urldecode( add_query_arg( 'page', $page, $request ) );
  530. // get the home host
  531. $host = parse_url( get_home_url(), PHP_URL_HOST );
  532. return set_url_scheme( "http://{$host}{$request}" );
  533. }
  534. /**
  535. * Retrieve the raw request entity (body)
  536. *
  537. * @since 2.1
  538. * @return string
  539. */
  540. public function get_raw_data() {
  541. // @codingStandardsIgnoreStart
  542. // $HTTP_RAW_POST_DATA is deprecated on PHP 5.6.
  543. if ( function_exists( 'phpversion' ) && version_compare( phpversion(), '5.6', '>=' ) ) {
  544. return file_get_contents( 'php://input' );
  545. }
  546. global $HTTP_RAW_POST_DATA;
  547. // A bug in PHP < 5.2.2 makes $HTTP_RAW_POST_DATA not set by default,
  548. // but we can do it ourself.
  549. if ( ! isset( $HTTP_RAW_POST_DATA ) ) {
  550. $HTTP_RAW_POST_DATA = file_get_contents( 'php://input' );
  551. }
  552. return $HTTP_RAW_POST_DATA;
  553. // @codingStandardsIgnoreEnd
  554. }
  555. /**
  556. * Parse an RFC3339 datetime into a MySQl datetime
  557. *
  558. * Invalid dates default to unix epoch
  559. *
  560. * @since 2.1
  561. * @param string $datetime RFC3339 datetime
  562. * @return string MySQl datetime (YYYY-MM-DD HH:MM:SS)
  563. */
  564. public function parse_datetime( $datetime ) {
  565. // Strip millisecond precision (a full stop followed by one or more digits)
  566. if ( strpos( $datetime, '.' ) !== false ) {
  567. $datetime = preg_replace( '/\.\d+/', '', $datetime );
  568. }
  569. // default timezone to UTC
  570. $datetime = preg_replace( '/[+-]\d+:+\d+$/', '+00:00', $datetime );
  571. try {
  572. $datetime = new DateTime( $datetime, new DateTimeZone( 'UTC' ) );
  573. } catch ( Exception $e ) {
  574. $datetime = new DateTime( '@0' );
  575. }
  576. return $datetime->format( 'Y-m-d H:i:s' );
  577. }
  578. /**
  579. * Format a unix timestamp or MySQL datetime into an RFC3339 datetime
  580. *
  581. * @since 2.1
  582. * @param int|string $timestamp unix timestamp or MySQL datetime
  583. * @param bool $convert_to_utc
  584. * @param bool $convert_to_gmt Use GMT timezone.
  585. * @return string RFC3339 datetime
  586. */
  587. public function format_datetime( $timestamp, $convert_to_utc = false, $convert_to_gmt = false ) {
  588. if ( $convert_to_gmt ) {
  589. if ( is_numeric( $timestamp ) ) {
  590. $timestamp = date( 'Y-m-d H:i:s', $timestamp );
  591. }
  592. $timestamp = get_gmt_from_date( $timestamp );
  593. }
  594. if ( $convert_to_utc ) {
  595. $timezone = new DateTimeZone( wc_timezone_string() );
  596. } else {
  597. $timezone = new DateTimeZone( 'UTC' );
  598. }
  599. try {
  600. if ( is_numeric( $timestamp ) ) {
  601. $date = new DateTime( "@{$timestamp}" );
  602. } else {
  603. $date = new DateTime( $timestamp, $timezone );
  604. }
  605. // convert to UTC by adjusting the time based on the offset of the site's timezone
  606. if ( $convert_to_utc ) {
  607. $date->modify( -1 * $date->getOffset() . ' seconds' );
  608. }
  609. } catch ( Exception $e ) {
  610. $date = new DateTime( '@0' );
  611. }
  612. return $date->format( 'Y-m-d\TH:i:s\Z' );
  613. }
  614. /**
  615. * Extract headers from a PHP-style $_SERVER array
  616. *
  617. * @since 2.1
  618. * @param array $server Associative array similar to $_SERVER
  619. * @return array Headers extracted from the input
  620. */
  621. public function get_headers( $server ) {
  622. $headers = array();
  623. // CONTENT_* headers are not prefixed with HTTP_
  624. $additional = array( 'CONTENT_LENGTH' => true, 'CONTENT_MD5' => true, 'CONTENT_TYPE' => true );
  625. foreach ( $server as $key => $value ) {
  626. if ( strpos( $key, 'HTTP_' ) === 0 ) {
  627. $headers[ substr( $key, 5 ) ] = $value;
  628. } elseif ( isset( $additional[ $key ] ) ) {
  629. $headers[ $key ] = $value;
  630. }
  631. }
  632. return $headers;
  633. }
  634. }