class-wp-community-events.php 18 KB

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