No Description

class-wp-community-events.php 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  1. <?php
  2. /**
  3. * Administration: Community Events class.
  4. *
  5. * @package WordPress
  6. * @subpackage Administration
  7. * @since 4.8.0
  8. */
  9. /**
  10. * Class WP_Community_Events.
  11. *
  12. * A client for api.wordpress.org/events.
  13. *
  14. * @since 4.8.0
  15. */
  16. class WP_Community_Events {
  17. /**
  18. * ID for a WordPress user account.
  19. *
  20. * @since 4.8.0
  21. *
  22. * @var int
  23. */
  24. protected $user_id = 0;
  25. /**
  26. * Stores location data for the user.
  27. *
  28. * @since 4.8.0
  29. *
  30. * @var false|array
  31. */
  32. protected $user_location = false;
  33. /**
  34. * Constructor for WP_Community_Events.
  35. *
  36. * @since 4.8.0
  37. *
  38. * @param int $user_id WP user ID.
  39. * @param false|array $user_location {
  40. * Stored location data for the user. false to pass no location.
  41. *
  42. * @type string $description The name of the location
  43. * @type string $latitude The latitude in decimal degrees notation, without the degree
  44. * symbol. e.g.: 47.615200.
  45. * @type string $longitude The longitude in decimal degrees notation, without the degree
  46. * symbol. e.g.: -122.341100.
  47. * @type string $country The ISO 3166-1 alpha-2 country code. e.g.: BR
  48. * }
  49. */
  50. public function __construct( $user_id, $user_location = false ) {
  51. $this->user_id = absint( $user_id );
  52. $this->user_location = $user_location;
  53. }
  54. /**
  55. * Gets data about events near a particular location.
  56. *
  57. * Cached events will be immediately returned if the `user_location` property
  58. * is set for the current user, and cached events exist for that location.
  59. *
  60. * Otherwise, this method sends a request to the w.org Events API with location
  61. * data. The API will send back a recognized location based on the data, along
  62. * with nearby events.
  63. *
  64. * The browser's request for events is proxied with this method, rather
  65. * than having the browser make the request directly to api.wordpress.org,
  66. * because it allows results to be cached server-side and shared with other
  67. * users and sites in the network. This makes the process more efficient,
  68. * since increasing the number of visits that get cached data means users
  69. * don't have to wait as often; if the user's browser made the request
  70. * directly, it would also need to make a second request to WP in order to
  71. * pass the data for caching. Having WP make the request also introduces
  72. * the opportunity to anonymize the IP before sending it to w.org, which
  73. * mitigates possible privacy concerns.
  74. *
  75. * @since 4.8.0
  76. * @since 5.5.2 Response no longer contains formatted date field. They're added
  77. * in `wp.communityEvents.populateDynamicEventFields()` now.
  78. *
  79. * @param string $location_search Optional. City name to help determine the location.
  80. * e.g., "Seattle". Default empty string.
  81. * @param string $timezone Optional. Timezone to help determine the location.
  82. * Default empty string.
  83. * @return array|WP_Error A WP_Error on failure; an array with location and events on
  84. * success.
  85. */
  86. public function get_events( $location_search = '', $timezone = '' ) {
  87. $cached_events = $this->get_cached_events();
  88. if ( ! $location_search && $cached_events ) {
  89. return $cached_events;
  90. }
  91. // Include an unmodified $wp_version.
  92. require ABSPATH . WPINC . '/version.php';
  93. $api_url = 'http://api.wordpress.org/events/1.0/';
  94. $request_args = $this->get_request_args( $location_search, $timezone );
  95. $request_args['user-agent'] = 'WordPress/' . $wp_version . '; ' . home_url( '/' );
  96. if ( wp_http_supports( array( 'ssl' ) ) ) {
  97. $api_url = set_url_scheme( $api_url, 'https' );
  98. }
  99. $response = wp_remote_get( $api_url, $request_args );
  100. $response_code = wp_remote_retrieve_response_code( $response );
  101. $response_body = json_decode( wp_remote_retrieve_body( $response ), true );
  102. $response_error = null;
  103. if ( is_wp_error( $response ) ) {
  104. $response_error = $response;
  105. } elseif ( 200 !== $response_code ) {
  106. $response_error = new WP_Error(
  107. 'api-error',
  108. /* translators: %d: Numeric HTTP status code, e.g. 400, 403, 500, 504, etc. */
  109. sprintf( __( 'Invalid API response code (%d).' ), $response_code )
  110. );
  111. } elseif ( ! isset( $response_body['location'], $response_body['events'] ) ) {
  112. $response_error = new WP_Error(
  113. 'api-invalid-response',
  114. isset( $response_body['error'] ) ? $response_body['error'] : __( 'Unknown API error.' )
  115. );
  116. }
  117. if ( is_wp_error( $response_error ) ) {
  118. return $response_error;
  119. } else {
  120. $expiration = false;
  121. if ( isset( $response_body['ttl'] ) ) {
  122. $expiration = $response_body['ttl'];
  123. unset( $response_body['ttl'] );
  124. }
  125. /*
  126. * The IP in the response is usually the same as the one that was sent
  127. * in the request, but in some cases it is different. In those cases,
  128. * it's important to reset it back to the IP from the request.
  129. *
  130. * For example, if the IP sent in the request is private (e.g., 192.168.1.100),
  131. * then the API will ignore that and use the corresponding public IP instead,
  132. * and the public IP will get returned. If the public IP were saved, though,
  133. * then get_cached_events() would always return `false`, because the transient
  134. * would be generated based on the public IP when saving the cache, but generated
  135. * based on the private IP when retrieving the cache.
  136. */
  137. if ( ! empty( $response_body['location']['ip'] ) ) {
  138. $response_body['location']['ip'] = $request_args['body']['ip'];
  139. }
  140. /*
  141. * The API doesn't return a description for latitude/longitude requests,
  142. * but the description is already saved in the user location, so that
  143. * one can be used instead.
  144. */
  145. if ( $this->coordinates_match( $request_args['body'], $response_body['location'] ) && empty( $response_body['location']['description'] ) ) {
  146. $response_body['location']['description'] = $this->user_location['description'];
  147. }
  148. /*
  149. * Store the raw response, because events will expire before the cache does.
  150. * The response will need to be processed every page load.
  151. */
  152. $this->cache_events( $response_body, $expiration );
  153. $response_body['events'] = $this->trim_events( $response_body['events'] );
  154. return $response_body;
  155. }
  156. }
  157. /**
  158. * Builds an array of args to use in an HTTP request to the w.org Events API.
  159. *
  160. * @since 4.8.0
  161. *
  162. * @param string $search Optional. City search string. Default empty string.
  163. * @param string $timezone Optional. Timezone string. Default empty string.
  164. * @return array The request args.
  165. */
  166. protected function get_request_args( $search = '', $timezone = '' ) {
  167. $args = array(
  168. 'number' => 5, // Get more than three in case some get trimmed out.
  169. 'ip' => self::get_unsafe_client_ip(),
  170. );
  171. /*
  172. * Include the minimal set of necessary arguments, in order to increase the
  173. * chances of a cache-hit on the API side.
  174. */
  175. if ( empty( $search ) && isset( $this->user_location['latitude'], $this->user_location['longitude'] ) ) {
  176. $args['latitude'] = $this->user_location['latitude'];
  177. $args['longitude'] = $this->user_location['longitude'];
  178. } else {
  179. $args['locale'] = get_user_locale( $this->user_id );
  180. if ( $timezone ) {
  181. $args['timezone'] = $timezone;
  182. }
  183. if ( $search ) {
  184. $args['location'] = $search;
  185. }
  186. }
  187. // Wrap the args in an array compatible with the second parameter of `wp_remote_get()`.
  188. return array(
  189. 'body' => $args,
  190. );
  191. }
  192. /**
  193. * Determines the user's actual IP address and attempts to partially
  194. * anonymize an IP address by converting it to a network ID.
  195. *
  196. * Geolocating the network ID usually returns a similar location as the
  197. * actual IP, but provides some privacy for the user.
  198. *
  199. * $_SERVER['REMOTE_ADDR'] cannot be used in all cases, such as when the user
  200. * is making their request through a proxy, or when the web server is behind
  201. * a proxy. In those cases, $_SERVER['REMOTE_ADDR'] is set to the proxy address rather
  202. * than the user's actual address.
  203. *
  204. * Modified from https://stackoverflow.com/a/2031935/450127, MIT license.
  205. * Modified from https://github.com/geertw/php-ip-anonymizer, MIT license.
  206. *
  207. * SECURITY WARNING: This function is _NOT_ intended to be used in
  208. * circumstances where the authenticity of the IP address matters. This does
  209. * _NOT_ guarantee that the returned address is valid or accurate, and it can
  210. * be easily spoofed.
  211. *
  212. * @since 4.8.0
  213. *
  214. * @return string|false The anonymized address on success; the given address
  215. * or false on failure.
  216. */
  217. public static function get_unsafe_client_ip() {
  218. $client_ip = false;
  219. // In order of preference, with the best ones for this purpose first.
  220. $address_headers = array(
  221. 'HTTP_CLIENT_IP',
  222. 'HTTP_X_FORWARDED_FOR',
  223. 'HTTP_X_FORWARDED',
  224. 'HTTP_X_CLUSTER_CLIENT_IP',
  225. 'HTTP_FORWARDED_FOR',
  226. 'HTTP_FORWARDED',
  227. 'REMOTE_ADDR',
  228. );
  229. foreach ( $address_headers as $header ) {
  230. if ( array_key_exists( $header, $_SERVER ) ) {
  231. /*
  232. * HTTP_X_FORWARDED_FOR can contain a chain of comma-separated
  233. * addresses. The first one is the original client. It can't be
  234. * trusted for authenticity, but we don't need to for this purpose.
  235. */
  236. $address_chain = explode( ',', $_SERVER[ $header ] );
  237. $client_ip = trim( $address_chain[0] );
  238. break;
  239. }
  240. }
  241. if ( ! $client_ip ) {
  242. return false;
  243. }
  244. $anon_ip = wp_privacy_anonymize_ip( $client_ip, true );
  245. if ( '0.0.0.0' === $anon_ip || '::' === $anon_ip ) {
  246. return false;
  247. }
  248. return $anon_ip;
  249. }
  250. /**
  251. * Test if two pairs of latitude/longitude coordinates match each other.
  252. *
  253. * @since 4.8.0
  254. *
  255. * @param array $a The first pair, with indexes 'latitude' and 'longitude'.
  256. * @param array $b The second pair, with indexes 'latitude' and 'longitude'.
  257. * @return bool True if they match, false if they don't.
  258. */
  259. protected function coordinates_match( $a, $b ) {
  260. if ( ! isset( $a['latitude'], $a['longitude'], $b['latitude'], $b['longitude'] ) ) {
  261. return false;
  262. }
  263. return $a['latitude'] === $b['latitude'] && $a['longitude'] === $b['longitude'];
  264. }
  265. /**
  266. * Generates a transient key based on user location.
  267. *
  268. * This could be reduced to a one-liner in the calling functions, but it's
  269. * intentionally a separate function because it's called from multiple
  270. * functions, and having it abstracted keeps the logic consistent and DRY,
  271. * which is less prone to errors.
  272. *
  273. * @since 4.8.0
  274. *
  275. * @param array $location Should contain 'latitude' and 'longitude' indexes.
  276. * @return string|false Transient key on success, false on failure.
  277. */
  278. protected function get_events_transient_key( $location ) {
  279. $key = false;
  280. if ( isset( $location['ip'] ) ) {
  281. $key = 'community-events-' . md5( $location['ip'] );
  282. } elseif ( isset( $location['latitude'], $location['longitude'] ) ) {
  283. $key = 'community-events-' . md5( $location['latitude'] . $location['longitude'] );
  284. }
  285. return $key;
  286. }
  287. /**
  288. * Caches an array of events data from the Events API.
  289. *
  290. * @since 4.8.0
  291. *
  292. * @param array $events Response body from the API request.
  293. * @param int|false $expiration Optional. Amount of time to cache the events. Defaults to false.
  294. * @return bool true if events were cached; false if not.
  295. */
  296. protected function cache_events( $events, $expiration = false ) {
  297. $set = false;
  298. $transient_key = $this->get_events_transient_key( $events['location'] );
  299. $cache_expiration = $expiration ? absint( $expiration ) : HOUR_IN_SECONDS * 12;
  300. if ( $transient_key ) {
  301. $set = set_site_transient( $transient_key, $events, $cache_expiration );
  302. }
  303. return $set;
  304. }
  305. /**
  306. * Gets cached events.
  307. *
  308. * @since 4.8.0
  309. * @since 5.5.2 Response no longer contains formatted date field. They're added
  310. * in `wp.communityEvents.populateDynamicEventFields()` now.
  311. *
  312. * @return array|false An array containing `location` and `events` items
  313. * on success, false on failure.
  314. */
  315. public function get_cached_events() {
  316. $cached_response = get_site_transient( $this->get_events_transient_key( $this->user_location ) );
  317. if ( isset( $cached_response['events'] ) ) {
  318. $cached_response['events'] = $this->trim_events( $cached_response['events'] );
  319. }
  320. return $cached_response;
  321. }
  322. /**
  323. * Adds formatted date and time items for each event in an API response.
  324. *
  325. * This has to be called after the data is pulled from the cache, because
  326. * the cached events are shared by all users. If it was called before storing
  327. * the cache, then all users would see the events in the localized data/time
  328. * of the user who triggered the cache refresh, rather than their own.
  329. *
  330. * @since 4.8.0
  331. * @deprecated 5.6.0 No longer used in core.
  332. *
  333. * @param array $response_body The response which contains the events.
  334. * @return array The response with dates and times formatted.
  335. */
  336. protected function format_event_data_time( $response_body ) {
  337. _deprecated_function(
  338. __METHOD__,
  339. '5.5.2',
  340. 'This is no longer used by core, and only kept for backward compatibility.'
  341. );
  342. if ( isset( $response_body['events'] ) ) {
  343. foreach ( $response_body['events'] as $key => $event ) {
  344. $timestamp = strtotime( $event['date'] );
  345. /*
  346. * The `date_format` option is not used because it's important
  347. * in this context to keep the day of the week in the formatted date,
  348. * so that users can tell at a glance if the event is on a day they
  349. * are available, without having to open the link.
  350. */
  351. /* translators: Date format for upcoming events on the dashboard. Include the day of the week. See https://www.php.net/manual/datetime.format.php */
  352. $formatted_date = date_i18n( __( 'l, M j, Y' ), $timestamp );
  353. $formatted_time = date_i18n( get_option( 'time_format' ), $timestamp );
  354. if ( isset( $event['end_date'] ) ) {
  355. $end_timestamp = strtotime( $event['end_date'] );
  356. $formatted_end_date = date_i18n( __( 'l, M j, Y' ), $end_timestamp );
  357. if ( 'meetup' !== $event['type'] && $formatted_end_date !== $formatted_date ) {
  358. /* translators: Upcoming events month format. See https://www.php.net/manual/datetime.format.php */
  359. $start_month = date_i18n( _x( 'F', 'upcoming events month format' ), $timestamp );
  360. $end_month = date_i18n( _x( 'F', 'upcoming events month format' ), $end_timestamp );
  361. if ( $start_month === $end_month ) {
  362. $formatted_date = sprintf(
  363. /* translators: Date string for upcoming events. 1: Month, 2: Starting day, 3: Ending day, 4: Year. */
  364. __( '%1$s %2$d–%3$d, %4$d' ),
  365. $start_month,
  366. /* translators: Upcoming events day format. See https://www.php.net/manual/datetime.format.php */
  367. date_i18n( _x( 'j', 'upcoming events day format' ), $timestamp ),
  368. date_i18n( _x( 'j', 'upcoming events day format' ), $end_timestamp ),
  369. /* translators: Upcoming events year format. See https://www.php.net/manual/datetime.format.php */
  370. date_i18n( _x( 'Y', 'upcoming events year format' ), $timestamp )
  371. );
  372. } else {
  373. $formatted_date = sprintf(
  374. /* translators: Date string for upcoming events. 1: Starting month, 2: Starting day, 3: Ending month, 4: Ending day, 5: Year. */
  375. __( '%1$s %2$d – %3$s %4$d, %5$d' ),
  376. $start_month,
  377. date_i18n( _x( 'j', 'upcoming events day format' ), $timestamp ),
  378. $end_month,
  379. date_i18n( _x( 'j', 'upcoming events day format' ), $end_timestamp ),
  380. date_i18n( _x( 'Y', 'upcoming events year format' ), $timestamp )
  381. );
  382. }
  383. $formatted_date = wp_maybe_decline_date( $formatted_date, 'F j, Y' );
  384. }
  385. }
  386. $response_body['events'][ $key ]['formatted_date'] = $formatted_date;
  387. $response_body['events'][ $key ]['formatted_time'] = $formatted_time;
  388. }
  389. }
  390. return $response_body;
  391. }
  392. /**
  393. * Prepares the event list for presentation.
  394. *
  395. * Discards expired events, and makes WordCamps "sticky." Attendees need more
  396. * advanced notice about WordCamps than they do for meetups, so camps should
  397. * appear in the list sooner. If a WordCamp is coming up, the API will "stick"
  398. * it in the response, even if it wouldn't otherwise appear. When that happens,
  399. * the event will be at the end of the list, and will need to be moved into a
  400. * higher position, so that it doesn't get trimmed off.
  401. *
  402. * @since 4.8.0
  403. * @since 4.9.7 Stick a WordCamp to the final list.
  404. * @since 5.5.2 Accepts and returns only the events, rather than an entire HTTP response.
  405. *
  406. * @param array $events The events that will be prepared.
  407. * @return array The response body with events trimmed.
  408. */
  409. protected function trim_events( array $events ) {
  410. $future_events = array();
  411. foreach ( $events as $event ) {
  412. /*
  413. * The API's `date` and `end_date` fields are in the _event's_ local timezone, but UTC is needed so
  414. * it can be converted to the _user's_ local time.
  415. */
  416. $end_time = (int) $event['end_unix_timestamp'];
  417. if ( time() < $end_time ) {
  418. array_push( $future_events, $event );
  419. }
  420. }
  421. $future_wordcamps = array_filter(
  422. $future_events,
  423. function( $wordcamp ) {
  424. return 'wordcamp' === $wordcamp['type'];
  425. }
  426. );
  427. $future_wordcamps = array_values( $future_wordcamps ); // Remove gaps in indices.
  428. $trimmed_events = array_slice( $future_events, 0, 3 );
  429. $trimmed_event_types = wp_list_pluck( $trimmed_events, 'type' );
  430. // Make sure the soonest upcoming WordCamp is pinned in the list.
  431. if ( $future_wordcamps && ! in_array( 'wordcamp', $trimmed_event_types, true ) ) {
  432. array_pop( $trimmed_events );
  433. array_push( $trimmed_events, $future_wordcamps[0] );
  434. }
  435. return $trimmed_events;
  436. }
  437. /**
  438. * Logs responses to Events API requests.
  439. *
  440. * @since 4.8.0
  441. * @deprecated 4.9.0 Use a plugin instead. See #41217 for an example.
  442. *
  443. * @param string $message A description of what occurred.
  444. * @param array $details Details that provide more context for the
  445. * log entry.
  446. */
  447. protected function maybe_log_events_response( $message, $details ) {
  448. _deprecated_function( __METHOD__, '4.9.0' );
  449. if ( ! WP_DEBUG_LOG ) {
  450. return;
  451. }
  452. error_log(
  453. sprintf(
  454. '%s: %s. Details: %s',
  455. __METHOD__,
  456. trim( $message, '.' ),
  457. wp_json_encode( $details )
  458. )
  459. );
  460. }
  461. }