class-wc-api-server.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777
  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. *
  310. * @return string|array Decoded data.
  311. */
  312. protected function urldecode_deep( $value ) {
  313. if ( is_array( $value ) ) {
  314. return array_map( array( $this, 'urldecode_deep' ), $value );
  315. } else {
  316. return urldecode( $value );
  317. }
  318. }
  319. /**
  320. * Sort parameters by order specified in method declaration
  321. *
  322. * Takes a callback and a list of available params, then filters and sorts
  323. * by the parameters the method actually needs, using the Reflection API
  324. *
  325. * @since 2.2
  326. *
  327. * @param callable|array $callback the endpoint callback
  328. * @param array $provided the provided request parameters
  329. *
  330. * @return array|WP_Error
  331. */
  332. protected function sort_callback_params( $callback, $provided ) {
  333. if ( is_array( $callback ) ) {
  334. $ref_func = new ReflectionMethod( $callback[0], $callback[1] );
  335. } else {
  336. $ref_func = new ReflectionFunction( $callback );
  337. }
  338. $wanted = $ref_func->getParameters();
  339. $ordered_parameters = array();
  340. foreach ( $wanted as $param ) {
  341. if ( isset( $provided[ $param->getName() ] ) ) {
  342. // We have this parameters in the list to choose from
  343. if ( 'data' == $param->getName() ) {
  344. $ordered_parameters[] = $provided[ $param->getName() ];
  345. continue;
  346. }
  347. $ordered_parameters[] = $this->urldecode_deep( $provided[ $param->getName() ] );
  348. } elseif ( $param->isDefaultValueAvailable() ) {
  349. // We don't have this parameter, but it's optional
  350. $ordered_parameters[] = $param->getDefaultValue();
  351. } else {
  352. // We don't have this parameter and it wasn't optional, abort!
  353. return new WP_Error( 'woocommerce_api_missing_callback_param', sprintf( __( 'Missing parameter %s', 'woocommerce' ), $param->getName() ), array( 'status' => 400 ) );
  354. }
  355. }
  356. return $ordered_parameters;
  357. }
  358. /**
  359. * Get the site index.
  360. *
  361. * This endpoint describes the capabilities of the site.
  362. *
  363. * @since 2.3
  364. * @return array Index entity
  365. */
  366. public function get_index() {
  367. // General site data
  368. $available = array(
  369. 'store' => array(
  370. 'name' => get_option( 'blogname' ),
  371. 'description' => get_option( 'blogdescription' ),
  372. 'URL' => get_option( 'siteurl' ),
  373. 'wc_version' => WC()->version,
  374. 'version' => WC_API::VERSION,
  375. 'routes' => array(),
  376. 'meta' => array(
  377. 'timezone' => wc_timezone_string(),
  378. 'currency' => get_woocommerce_currency(),
  379. 'currency_format' => get_woocommerce_currency_symbol(),
  380. 'currency_position' => get_option( 'woocommerce_currency_pos' ),
  381. 'thousand_separator' => get_option( 'woocommerce_price_thousand_sep' ),
  382. 'decimal_separator' => get_option( 'woocommerce_price_decimal_sep' ),
  383. 'price_num_decimals' => wc_get_price_decimals(),
  384. 'tax_included' => wc_prices_include_tax(),
  385. 'weight_unit' => get_option( 'woocommerce_weight_unit' ),
  386. 'dimension_unit' => get_option( 'woocommerce_dimension_unit' ),
  387. 'ssl_enabled' => ( 'yes' === get_option( 'woocommerce_force_ssl_checkout' ) || wc_site_is_https() ),
  388. 'permalinks_enabled' => ( '' !== get_option( 'permalink_structure' ) ),
  389. 'generate_password' => ( 'yes' === get_option( 'woocommerce_registration_generate_password' ) ),
  390. 'links' => array(
  391. 'help' => 'https://woocommerce.github.io/woocommerce-rest-api-docs/',
  392. ),
  393. ),
  394. ),
  395. );
  396. // Find the available routes
  397. foreach ( $this->get_routes() as $route => $callbacks ) {
  398. $data = array();
  399. $route = preg_replace( '#\(\?P(<\w+?>).*?\)#', '$1', $route );
  400. foreach ( self::$method_map as $name => $bitmask ) {
  401. foreach ( $callbacks as $callback ) {
  402. // Skip to the next route if any callback is hidden
  403. if ( $callback[1] & self::HIDDEN_ENDPOINT ) {
  404. continue 3;
  405. }
  406. if ( $callback[1] & $bitmask ) {
  407. $data['supports'][] = $name;
  408. }
  409. if ( $callback[1] & self::ACCEPT_DATA ) {
  410. $data['accepts_data'] = true;
  411. }
  412. // For non-variable routes, generate links
  413. if ( strpos( $route, '<' ) === false ) {
  414. $data['meta'] = array(
  415. 'self' => get_woocommerce_api_url( $route ),
  416. );
  417. }
  418. }
  419. }
  420. $available['store']['routes'][ $route ] = apply_filters( 'woocommerce_api_endpoints_description', $data );
  421. }
  422. return apply_filters( 'woocommerce_api_index', $available );
  423. }
  424. /**
  425. * Send a HTTP status code
  426. *
  427. * @since 2.1
  428. * @param int $code HTTP status
  429. */
  430. public function send_status( $code ) {
  431. status_header( $code );
  432. }
  433. /**
  434. * Send a HTTP header
  435. *
  436. * @since 2.1
  437. * @param string $key Header key
  438. * @param string $value Header value
  439. * @param boolean $replace Should we replace the existing header?
  440. */
  441. public function header( $key, $value, $replace = true ) {
  442. header( sprintf( '%s: %s', $key, $value ), $replace );
  443. }
  444. /**
  445. * Send a Link header
  446. *
  447. * @internal The $rel parameter is first, as this looks nicer when sending multiple
  448. *
  449. * @link http://tools.ietf.org/html/rfc5988
  450. * @link http://www.iana.org/assignments/link-relations/link-relations.xml
  451. *
  452. * @since 2.1
  453. * @param string $rel Link relation. Either a registered type, or an absolute URL
  454. * @param string $link Target IRI for the link
  455. * @param array $other Other parameters to send, as an associative array
  456. */
  457. public function link_header( $rel, $link, $other = array() ) {
  458. $header = sprintf( '<%s>; rel="%s"', $link, esc_attr( $rel ) );
  459. foreach ( $other as $key => $value ) {
  460. if ( 'title' == $key ) {
  461. $value = '"' . $value . '"';
  462. }
  463. $header .= '; ' . $key . '=' . $value;
  464. }
  465. $this->header( 'Link', $header, false );
  466. }
  467. /**
  468. * Send pagination headers for resources
  469. *
  470. * @since 2.1
  471. * @param WP_Query|WP_User_Query|stdClass $query
  472. */
  473. public function add_pagination_headers( $query ) {
  474. // WP_User_Query
  475. if ( is_a( $query, 'WP_User_Query' ) ) {
  476. $single = count( $query->get_results() ) == 1;
  477. $total = $query->get_total();
  478. if ( $query->get( 'number' ) > 0 ) {
  479. $page = ( $query->get( 'offset' ) / $query->get( 'number' ) ) + 1;
  480. $total_pages = ceil( $total / $query->get( 'number' ) );
  481. } else {
  482. $page = 1;
  483. $total_pages = 1;
  484. }
  485. } elseif ( is_a( $query, 'stdClass' ) ) {
  486. $page = $query->page;
  487. $single = $query->is_single;
  488. $total = $query->total;
  489. $total_pages = $query->total_pages;
  490. // WP_Query
  491. } else {
  492. $page = $query->get( 'paged' );
  493. $single = $query->is_single();
  494. $total = $query->found_posts;
  495. $total_pages = $query->max_num_pages;
  496. }
  497. if ( ! $page ) {
  498. $page = 1;
  499. }
  500. $next_page = absint( $page ) + 1;
  501. if ( ! $single ) {
  502. // first/prev
  503. if ( $page > 1 ) {
  504. $this->link_header( 'first', $this->get_paginated_url( 1 ) );
  505. $this->link_header( 'prev', $this->get_paginated_url( $page -1 ) );
  506. }
  507. // next
  508. if ( $next_page <= $total_pages ) {
  509. $this->link_header( 'next', $this->get_paginated_url( $next_page ) );
  510. }
  511. // last
  512. if ( $page != $total_pages ) {
  513. $this->link_header( 'last', $this->get_paginated_url( $total_pages ) );
  514. }
  515. }
  516. $this->header( 'X-WC-Total', $total );
  517. $this->header( 'X-WC-TotalPages', $total_pages );
  518. do_action( 'woocommerce_api_pagination_headers', $this, $query );
  519. }
  520. /**
  521. * Returns the request URL with the page query parameter set to the specified page
  522. *
  523. * @since 2.1
  524. * @param int $page
  525. * @return string
  526. */
  527. private function get_paginated_url( $page ) {
  528. // remove existing page query param
  529. $request = remove_query_arg( 'page' );
  530. // add provided page query param
  531. $request = urldecode( add_query_arg( 'page', $page, $request ) );
  532. // get the home host
  533. $host = parse_url( get_home_url(), PHP_URL_HOST );
  534. return set_url_scheme( "http://{$host}{$request}" );
  535. }
  536. /**
  537. * Retrieve the raw request entity (body)
  538. *
  539. * @since 2.1
  540. * @return string
  541. */
  542. public function get_raw_data() {
  543. // @codingStandardsIgnoreStart
  544. // $HTTP_RAW_POST_DATA is deprecated on PHP 5.6.
  545. if ( function_exists( 'phpversion' ) && version_compare( phpversion(), '5.6', '>=' ) ) {
  546. return file_get_contents( 'php://input' );
  547. }
  548. global $HTTP_RAW_POST_DATA;
  549. // A bug in PHP < 5.2.2 makes $HTTP_RAW_POST_DATA not set by default,
  550. // but we can do it ourself.
  551. if ( ! isset( $HTTP_RAW_POST_DATA ) ) {
  552. $HTTP_RAW_POST_DATA = file_get_contents( 'php://input' );
  553. }
  554. return $HTTP_RAW_POST_DATA;
  555. // @codingStandardsIgnoreEnd
  556. }
  557. /**
  558. * Parse an RFC3339 datetime into a MySQl datetime
  559. *
  560. * Invalid dates default to unix epoch
  561. *
  562. * @since 2.1
  563. * @param string $datetime RFC3339 datetime
  564. * @return string MySQl datetime (YYYY-MM-DD HH:MM:SS)
  565. */
  566. public function parse_datetime( $datetime ) {
  567. // Strip millisecond precision (a full stop followed by one or more digits)
  568. if ( strpos( $datetime, '.' ) !== false ) {
  569. $datetime = preg_replace( '/\.\d+/', '', $datetime );
  570. }
  571. // default timezone to UTC
  572. $datetime = preg_replace( '/[+-]\d+:+\d+$/', '+00:00', $datetime );
  573. try {
  574. $datetime = new DateTime( $datetime, new DateTimeZone( 'UTC' ) );
  575. } catch ( Exception $e ) {
  576. $datetime = new DateTime( '@0' );
  577. }
  578. return $datetime->format( 'Y-m-d H:i:s' );
  579. }
  580. /**
  581. * Format a unix timestamp or MySQL datetime into an RFC3339 datetime
  582. *
  583. * @since 2.1
  584. * @param int|string $timestamp unix timestamp or MySQL datetime
  585. * @param bool $convert_to_utc
  586. * @param bool $convert_to_gmt Use GMT timezone.
  587. * @return string RFC3339 datetime
  588. */
  589. public function format_datetime( $timestamp, $convert_to_utc = false, $convert_to_gmt = false ) {
  590. if ( $convert_to_gmt ) {
  591. if ( is_numeric( $timestamp ) ) {
  592. $timestamp = date( 'Y-m-d H:i:s', $timestamp );
  593. }
  594. $timestamp = get_gmt_from_date( $timestamp );
  595. }
  596. if ( $convert_to_utc ) {
  597. $timezone = new DateTimeZone( wc_timezone_string() );
  598. } else {
  599. $timezone = new DateTimeZone( 'UTC' );
  600. }
  601. try {
  602. if ( is_numeric( $timestamp ) ) {
  603. $date = new DateTime( "@{$timestamp}" );
  604. } else {
  605. $date = new DateTime( $timestamp, $timezone );
  606. }
  607. // convert to UTC by adjusting the time based on the offset of the site's timezone
  608. if ( $convert_to_utc ) {
  609. $date->modify( -1 * $date->getOffset() . ' seconds' );
  610. }
  611. } catch ( Exception $e ) {
  612. $date = new DateTime( '@0' );
  613. }
  614. return $date->format( 'Y-m-d\TH:i:s\Z' );
  615. }
  616. /**
  617. * Extract headers from a PHP-style $_SERVER array
  618. *
  619. * @since 2.1
  620. * @param array $server Associative array similar to $_SERVER
  621. * @return array Headers extracted from the input
  622. */
  623. public function get_headers( $server ) {
  624. $headers = array();
  625. // CONTENT_* headers are not prefixed with HTTP_
  626. $additional = array( 'CONTENT_LENGTH' => true, 'CONTENT_MD5' => true, 'CONTENT_TYPE' => true );
  627. foreach ( $server as $key => $value ) {
  628. if ( strpos( $key, 'HTTP_' ) === 0 ) {
  629. $headers[ substr( $key, 5 ) ] = $value;
  630. } elseif ( isset( $additional[ $key ] ) ) {
  631. $headers[ $key ] = $value;
  632. }
  633. }
  634. return $headers;
  635. }
  636. }