Нет описания

icalendar-reader.php 29KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899
  1. <?php
  2. /**
  3. * Gets and renders iCal feeds for the Upcoming Events widget and shortcode
  4. */
  5. class iCalendarReader {
  6. public $todo_count = 0;
  7. public $event_count = 0;
  8. public $cal = array();
  9. public $_lastKeyWord = '';
  10. public $timezone = null;
  11. /**
  12. * Class constructor
  13. *
  14. * @return void
  15. */
  16. public function __construct() {}
  17. /**
  18. * Return an array of events
  19. *
  20. * @param string $url (default: '')
  21. * @return array | false on failure
  22. */
  23. public function get_events( $url = '', $count = 5 ) {
  24. $count = (int) $count;
  25. $transient_id = 'icalendar_vcal_' . md5( $url ) . '_' . $count;
  26. $vcal = get_transient( $transient_id );
  27. if ( ! empty( $vcal ) ) {
  28. if ( isset( $vcal['TIMEZONE'] ) )
  29. $this->timezone = $this->timezone_from_string( $vcal['TIMEZONE'] );
  30. if ( isset( $vcal['VEVENT'] ) ) {
  31. $vevent = $vcal['VEVENT'];
  32. if ( $count > 0 )
  33. $vevent = array_slice( $vevent, 0, $count );
  34. $this->cal['VEVENT'] = $vevent;
  35. return $this->cal['VEVENT'];
  36. }
  37. }
  38. if ( ! $this->parse( $url ) )
  39. return false;
  40. $vcal = array();
  41. if ( $this->timezone ) {
  42. $vcal['TIMEZONE'] = $this->timezone->getName();
  43. } else {
  44. $this->timezone = $this->timezone_from_string( '' );
  45. }
  46. if ( ! empty( $this->cal['VEVENT'] ) ) {
  47. $vevent = $this->cal['VEVENT'];
  48. // check for recurring events
  49. // $vevent = $this->add_recurring_events( $vevent );
  50. // remove before caching - no sense in hanging onto the past
  51. $vevent = $this->filter_past_and_recurring_events( $vevent );
  52. // order by soonest start date
  53. $vevent = $this->sort_by_recent( $vevent );
  54. $vcal['VEVENT'] = $vevent;
  55. }
  56. set_transient( $transient_id, $vcal, HOUR_IN_SECONDS );
  57. if ( !isset( $vcal['VEVENT'] ) )
  58. return false;
  59. if ( $count > 0 )
  60. return array_slice( $vcal['VEVENT'], 0, $count );
  61. return $vcal['VEVENT'];
  62. }
  63. function apply_timezone_offset( $events ) {
  64. if ( ! $events ) {
  65. return $events;
  66. }
  67. // get timezone offset from the timezone name.
  68. $timezone = wp_timezone();
  69. $offsetted_events = array();
  70. foreach ( $events as $event ) {
  71. // Don't handle all-day events
  72. if ( 8 < strlen( $event['DTSTART'] ) ) {
  73. $start_time = preg_replace( '/Z$/', '', $event['DTSTART'] );
  74. $start_time = new DateTime( $start_time, $this->timezone );
  75. $start_time->setTimeZone( $timezone );
  76. $end_time = preg_replace( '/Z$/', '', $event['DTEND'] );
  77. $end_time = new DateTime( $end_time, $this->timezone );
  78. $end_time->setTimeZone( $timezone );
  79. $event['DTSTART'] = $start_time->format( 'YmdHis\Z' );
  80. $event['DTEND'] = $end_time->format( 'YmdHis\Z' );
  81. }
  82. $offsetted_events[] = $event;
  83. }
  84. return $offsetted_events;
  85. }
  86. protected function filter_past_and_recurring_events( $events ) {
  87. $upcoming = array();
  88. $set_recurring_events = array();
  89. $recurrences = array();
  90. /**
  91. * This filter allows any time to be passed in for testing or changing timezones, etc...
  92. *
  93. * @module widgets
  94. *
  95. * @since 3.4.0
  96. *
  97. * @param object time() A time object.
  98. */
  99. $current = apply_filters( 'ical_get_current_time', time() );
  100. foreach ( $events as $event ) {
  101. $date_from_ics = strtotime( $event['DTSTART'] );
  102. if ( isset( $event['DTEND'] ) ) {
  103. $duration = strtotime( $event['DTEND'] ) - strtotime( $event['DTSTART'] );
  104. } else {
  105. $duration = 0;
  106. }
  107. if ( isset( $event['RRULE'] ) && $this->timezone->getName() && 8 != strlen( $event['DTSTART'] ) ) {
  108. try {
  109. $adjusted_time = new DateTime( $event['DTSTART'], new DateTimeZone('UTC') );
  110. $adjusted_time->setTimeZone( new DateTimeZone( $this->timezone->getName() ) );
  111. $event['DTSTART'] = $adjusted_time->format('Ymd\THis');
  112. $date_from_ics = strtotime( $event['DTSTART'] );
  113. $event['DTEND'] = date( 'Ymd\THis', strtotime( $event['DTSTART'] ) + $duration );
  114. } catch ( Exception $e ) {
  115. // Invalid argument to DateTime
  116. }
  117. if ( isset( $event['EXDATE'] ) ) {
  118. $exdates = array();
  119. foreach ( (array) $event['EXDATE'] as $exdate ) {
  120. try {
  121. $adjusted_time = new DateTime( $exdate, new DateTimeZone('UTC') );
  122. $adjusted_time->setTimeZone( new DateTimeZone( $this->timezone->getName() ) );
  123. if ( 8 == strlen( $event['DTSTART'] ) ) {
  124. $exdates[] = $adjusted_time->format( 'Ymd' );
  125. } else {
  126. $exdates[] = $adjusted_time->format( 'Ymd\THis' );
  127. }
  128. } catch ( Exception $e ) {
  129. // Invalid argument to DateTime
  130. }
  131. }
  132. $event['EXDATE'] = $exdates;
  133. } else {
  134. $event['EXDATE'] = array();
  135. }
  136. }
  137. if ( ! isset( $event['DTSTART'] ) ) {
  138. continue;
  139. }
  140. // Process events with RRULE before other events
  141. $rrule = isset( $event['RRULE'] ) ? $event['RRULE'] : false ;
  142. $uid = $event['UID'];
  143. if ( $rrule && ! in_array( $uid, $set_recurring_events ) ) {
  144. // Break down the RRULE into digestible chunks
  145. $rrule_array = array();
  146. foreach ( explode( ";", $event['RRULE'] ) as $rline ) {
  147. list( $rkey, $rvalue ) = explode( "=", $rline, 2 );
  148. $rrule_array[$rkey] = $rvalue;
  149. }
  150. $interval = ( isset( $rrule_array['INTERVAL'] ) ) ? $rrule_array['INTERVAL'] : 1;
  151. $rrule_count = ( isset( $rrule_array['COUNT'] ) ) ? $rrule_array['COUNT'] : 0;
  152. $until = ( isset( $rrule_array['UNTIL'] ) ) ? strtotime( $rrule_array['UNTIL'] ) : strtotime( '+1 year', $current );
  153. // Used to bound event checks
  154. $echo_limit = 10;
  155. $noop = false;
  156. // Set bydays for the event
  157. $weekdays = array( 'SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA' );
  158. $bydays = $weekdays;
  159. // Calculate a recent start date for incrementing depending on the frequency and interval
  160. switch ( $rrule_array['FREQ'] ) {
  161. case 'DAILY':
  162. $frequency = 'day';
  163. $echo_limit = 10;
  164. if ( $date_from_ics >= $current ) {
  165. $recurring_event_date_start = date( 'Ymd\THis', strtotime( $event['DTSTART'] ) );
  166. } else {
  167. // Interval and count
  168. $catchup = floor( ( $current - strtotime( $event['DTSTART'] ) ) / ( $interval * DAY_IN_SECONDS ) );
  169. if ( $rrule_count && $catchup > 0 ) {
  170. if ( $catchup < $rrule_count ) {
  171. $rrule_count = $rrule_count - $catchup;
  172. $recurring_event_date_start = date( 'Ymd', strtotime( '+ ' . ( $interval * $catchup ) . ' days', strtotime( $event['DTSTART'] ) ) ) . date( '\THis', strtotime( $event['DTSTART'] ) );
  173. } else {
  174. $noop = true;
  175. }
  176. } else {
  177. $recurring_event_date_start = date( 'Ymd', strtotime( '+ ' . ( $interval * $catchup ) . ' days', strtotime( $event['DTSTART'] ) ) ) . date( '\THis', strtotime( $event['DTSTART'] ) );
  178. }
  179. }
  180. break;
  181. case 'WEEKLY':
  182. $frequency = 'week';
  183. $echo_limit = 4;
  184. // BYDAY exception to current date
  185. $day = false;
  186. if ( ! isset( $rrule_array['BYDAY'] ) ) {
  187. $day = $rrule_array['BYDAY'] = strtoupper( substr( date( 'D', strtotime( $event['DTSTART'] ) ), 0, 2 ) );
  188. }
  189. $bydays = explode( ',', $rrule_array['BYDAY'] );
  190. if ( $date_from_ics >= $current ) {
  191. $recurring_event_date_start = date( 'Ymd\THis', strtotime( $event['DTSTART'] ) );
  192. } else {
  193. // Interval and count
  194. $catchup = floor( ( $current - strtotime( $event['DTSTART'] ) ) / ( $interval * WEEK_IN_SECONDS ) );
  195. if ( $rrule_count && $catchup > 0 ) {
  196. if ( ( $catchup * count( $bydays ) ) < $rrule_count ) {
  197. $rrule_count = $rrule_count - ( $catchup * count( $bydays ) ); // Estimate current event count
  198. $recurring_event_date_start = date( 'Ymd', strtotime( '+ ' . ( $interval * $catchup ) . ' weeks', strtotime( $event['DTSTART'] ) ) ) . date( '\THis', strtotime( $event['DTSTART'] ) );
  199. } else {
  200. $noop = true;
  201. }
  202. } else {
  203. $recurring_event_date_start = date( 'Ymd', strtotime( '+ ' . ( $interval * $catchup ) . ' weeks', strtotime( $event['DTSTART'] ) ) ) . date( '\THis', strtotime( $event['DTSTART'] ) );
  204. }
  205. }
  206. // Set to Sunday start
  207. if ( ! $noop && 'SU' !== strtoupper( substr( date( 'D', strtotime( $recurring_event_date_start ) ), 0, 2 ) ) ) {
  208. $recurring_event_date_start = date( 'Ymd', strtotime( "last Sunday", strtotime( $recurring_event_date_start ) ) ) . date( '\THis', strtotime( $event['DTSTART'] ) );
  209. }
  210. break;
  211. case 'MONTHLY':
  212. $frequency = 'month';
  213. $echo_limit = 1;
  214. if ( $date_from_ics >= $current ) {
  215. $recurring_event_date_start = date( 'Ymd\THis', strtotime( $event['DTSTART'] ) );
  216. } else {
  217. // Describe the date in the month
  218. if ( isset( $rrule_array['BYDAY'] ) ) {
  219. $day_number = substr( $rrule_array['BYDAY'], 0, 1 );
  220. $week_day = substr( $rrule_array['BYDAY'], 1 );
  221. $day_cardinals = array( 1 => 'first', 2 => 'second', 3 => 'third', 4 => 'fourth', 5 => 'fifth' );
  222. $weekdays = array( 'SU' => 'Sunday', 'MO' => 'Monday', 'TU' => 'Tuesday', 'WE' => 'Wednesday', 'TH' => 'Thursday', 'FR' => 'Friday', 'SA' => 'Saturday' );
  223. $event_date_desc = "{$day_cardinals[$day_number]} {$weekdays[$week_day]} of ";
  224. } else {
  225. $event_date_desc = date( 'd ', strtotime( $event['DTSTART'] ) );
  226. }
  227. // Interval only
  228. if ( $interval > 1 ) {
  229. $catchup = 0;
  230. $maybe = strtotime( $event['DTSTART'] );
  231. while ( $maybe < $current ) {
  232. $maybe = strtotime( '+ ' . ( $interval * $catchup ) . ' months', strtotime( $event['DTSTART'] ) );
  233. $catchup++;
  234. }
  235. $recurring_event_date_start = date( 'Ymd', strtotime( $event_date_desc . date( 'F Y', strtotime( '+ ' . ( $interval * ( $catchup - 1 ) ) . ' months', strtotime( $event['DTSTART'] ) ) ) ) ) . date( '\THis', strtotime( $event['DTSTART'] ) );
  236. } else {
  237. $recurring_event_date_start = date( 'Ymd', strtotime( $event_date_desc . date( 'F Y', $current ) ) ) . date( '\THis', strtotime( $event['DTSTART'] ) );
  238. }
  239. // Add one interval if necessary
  240. if ( strtotime( $recurring_event_date_start ) < $current ) {
  241. if ( $interval > 1 ) {
  242. $recurring_event_date_start = date( 'Ymd', strtotime( $event_date_desc . date( 'F Y', strtotime( '+ ' . ( $interval * $catchup ) . ' months', strtotime( $event['DTSTART'] ) ) ) ) ) . date( '\THis', strtotime( $event['DTSTART'] ) );
  243. } else {
  244. try {
  245. $adjustment = new DateTime( date( 'Y-m-d', $current ) );
  246. $adjustment->modify( 'first day of next month' );
  247. $recurring_event_date_start = date( 'Ymd', strtotime( $event_date_desc . $adjustment->format( 'F Y' ) ) ) . date( '\THis', strtotime( $event['DTSTART'] ) );
  248. } catch ( Exception $e ) {
  249. // Invalid argument to DateTime
  250. }
  251. }
  252. }
  253. }
  254. break;
  255. case 'YEARLY':
  256. $frequency = 'year';
  257. $echo_limit = 1;
  258. if ( $date_from_ics >= $current ) {
  259. $recurring_event_date_start = date( "Ymd\THis", strtotime( $event['DTSTART'] ) );
  260. } else {
  261. $recurring_event_date_start = date( 'Y', $current ) . date( "md\THis", strtotime( $event['DTSTART'] ) );
  262. if ( strtotime( $recurring_event_date_start ) < $current ) {
  263. try {
  264. $next = new DateTime( date( 'Y-m-d', $current ) );
  265. $next->modify( 'first day of next year' );
  266. $recurring_event_date_start = $next->format( 'Y' ) . date ( 'md\THis', strtotime( $event['DTSTART'] ) );
  267. } catch ( Exception $e ) {
  268. // Invalid argument to DateTime
  269. }
  270. }
  271. }
  272. break;
  273. default:
  274. $frequency = false;
  275. }
  276. if ( $frequency !== false && ! $noop ) {
  277. $count_counter = 1;
  278. // If no COUNT limit, go to 10
  279. if ( empty( $rrule_count ) ) {
  280. $rrule_count = 10;
  281. }
  282. // Set up EXDATE handling for the event
  283. $exdates = ( isset( $event['EXDATE'] ) ) ? $event['EXDATE'] : array();
  284. for ( $i = 1; $i <= $echo_limit; $i++ ) {
  285. // Weeks need a daily loop and must check for inclusion in BYDAYS
  286. if ( 'week' == $frequency ) {
  287. $byday_event_date_start = strtotime( $recurring_event_date_start );
  288. foreach ( $weekdays as $day ) {
  289. $event_start_timestamp = $byday_event_date_start;
  290. $start_time = date( 'His', $event_start_timestamp );
  291. $event_end_timestamp = $event_start_timestamp + $duration;
  292. $end_time = date( 'His', $event_end_timestamp );
  293. if ( 8 == strlen( $event['DTSTART'] ) ) {
  294. $exdate_compare = date( 'Ymd', $event_start_timestamp );
  295. } else {
  296. $exdate_compare = date( 'Ymd\THis', $event_start_timestamp );
  297. }
  298. if ( in_array( $day, $bydays ) && $event_end_timestamp > $current && $event_start_timestamp < $until && $count_counter <= $rrule_count && $event_start_timestamp >= $date_from_ics && ! in_array( $exdate_compare, $exdates ) ) {
  299. if ( 8 == strlen( $event['DTSTART'] ) ) {
  300. $event['DTSTART'] = date( 'Ymd', $event_start_timestamp );
  301. $event['DTEND'] = date( 'Ymd', $event_end_timestamp );
  302. } else {
  303. $event['DTSTART'] = date( 'Ymd\THis', $event_start_timestamp );
  304. $event['DTEND'] = date( 'Ymd\THis', $event_end_timestamp );
  305. }
  306. if ( $this->timezone->getName() && 8 != strlen( $event['DTSTART'] ) ) {
  307. try {
  308. $adjusted_time = new DateTime( $event['DTSTART'], new DateTimeZone( $this->timezone->getName() ) );
  309. $adjusted_time->setTimeZone( new DateTimeZone( 'UTC' ) );
  310. $event['DTSTART'] = $adjusted_time->format('Ymd\THis');
  311. $event['DTEND'] = date( 'Ymd\THis', strtotime( $event['DTSTART'] ) + $duration );
  312. } catch ( Exception $e ) {
  313. // Invalid argument to DateTime
  314. }
  315. }
  316. $upcoming[] = $event;
  317. $count_counter++;
  318. }
  319. // Move forward one day
  320. $byday_event_date_start = strtotime( date( 'Ymd\T', strtotime( '+ 1 day', $event_start_timestamp ) ) . $start_time );
  321. }
  322. // Restore first event timestamp
  323. $event_start_timestamp = strtotime( $recurring_event_date_start );
  324. } else {
  325. $event_start_timestamp = strtotime( $recurring_event_date_start );
  326. $start_time = date( 'His', $event_start_timestamp );
  327. $event_end_timestamp = $event_start_timestamp + $duration;
  328. $end_time = date( 'His', $event_end_timestamp );
  329. if ( 8 == strlen( $event['DTSTART'] ) ) {
  330. $exdate_compare = date( 'Ymd', $event_start_timestamp );
  331. } else {
  332. $exdate_compare = date( 'Ymd\THis', $event_start_timestamp );
  333. }
  334. if ( $event_end_timestamp > $current && $event_start_timestamp < $until && $count_counter <= $rrule_count && $event_start_timestamp >= $date_from_ics && ! in_array( $exdate_compare, $exdates ) ) {
  335. if ( 8 == strlen( $event['DTSTART'] ) ) {
  336. $event['DTSTART'] = date( 'Ymd', $event_start_timestamp );
  337. $event['DTEND'] = date( 'Ymd', $event_end_timestamp );
  338. } else {
  339. $event['DTSTART'] = date( 'Ymd\T', $event_start_timestamp ) . $start_time;
  340. $event['DTEND'] = date( 'Ymd\T', $event_end_timestamp ) . $end_time;
  341. }
  342. if ( $this->timezone->getName() && 8 != strlen( $event['DTSTART'] ) ) {
  343. try {
  344. $adjusted_time = new DateTime( $event['DTSTART'], new DateTimeZone( $this->timezone->getName() ) );
  345. $adjusted_time->setTimeZone( new DateTimeZone( 'UTC' ) );
  346. $event['DTSTART'] = $adjusted_time->format('Ymd\THis');
  347. $event['DTEND'] = date( 'Ymd\THis', strtotime( $event['DTSTART'] ) + $duration );
  348. } catch ( Exception $e ) {
  349. // Invalid argument to DateTime
  350. }
  351. }
  352. $upcoming[] = $event;
  353. $count_counter++;
  354. }
  355. }
  356. // Set up next interval and reset $event['DTSTART'] and $event['DTEND'], keeping timestamps intact
  357. $next_start_timestamp = strtotime( "+ {$interval} {$frequency}s", $event_start_timestamp );
  358. if ( 8 == strlen( $event['DTSTART'] ) ) {
  359. $event['DTSTART'] = date( 'Ymd', $next_start_timestamp );
  360. $event['DTEND'] = date( 'Ymd', strtotime( $event['DTSTART'] ) + $duration );
  361. } else {
  362. $event['DTSTART'] = date( 'Ymd\THis', $next_start_timestamp );
  363. $event['DTEND'] = date( 'Ymd\THis', strtotime( $event['DTSTART'] ) + $duration );
  364. }
  365. // Move recurring event date forward
  366. $recurring_event_date_start = $event['DTSTART'];
  367. }
  368. $set_recurring_events[] = $uid;
  369. }
  370. } else {
  371. // Process normal events
  372. if ( strtotime( isset( $event['DTEND'] ) ? $event['DTEND'] : $event['DTSTART'] ) >= $current ) {
  373. $upcoming[] = $event;
  374. }
  375. }
  376. }
  377. return $upcoming;
  378. }
  379. /**
  380. * Parse events from an iCalendar feed
  381. *
  382. * @param string $url (default: '')
  383. * @return array | false on failure
  384. */
  385. public function parse( $url = '' ) {
  386. $cache_group = 'icalendar_reader_parse';
  387. $disable_get_key = 'disable:' . md5( $url );
  388. // Check to see if previous attempts have failed
  389. if ( false !== wp_cache_get( $disable_get_key, $cache_group ) )
  390. return false;
  391. // rewrite webcal: URI schem to HTTP
  392. $url = preg_replace('/^webcal/', 'http', $url );
  393. // try to fetch
  394. $r = wp_remote_get( $url, array( 'timeout' => 3, 'sslverify' => false ) );
  395. if ( 200 !== wp_remote_retrieve_response_code( $r ) ) {
  396. // We were unable to fetch any content, so don't try again for another 60 seconds
  397. wp_cache_set( $disable_get_key, 1, $cache_group, 60 );
  398. return false;
  399. }
  400. $body = wp_remote_retrieve_body( $r );
  401. if ( empty( $body ) )
  402. return false;
  403. $body = str_replace( "\r\n", "\n", $body );
  404. $lines = preg_split( "/\n(?=[A-Z])/", $body );
  405. if ( empty( $lines ) )
  406. return false;
  407. if ( false === stristr( $lines[0], 'BEGIN:VCALENDAR' ) )
  408. return false;
  409. foreach ( $lines as $line ) {
  410. $add = $this->key_value_from_string( $line );
  411. if ( ! $add ) {
  412. $this->add_component( $type, false, $line );
  413. continue;
  414. }
  415. list( $keyword, $value ) = $add;
  416. switch ( $keyword ) {
  417. case 'BEGIN':
  418. case 'END':
  419. switch ( $line ) {
  420. case 'BEGIN:VTODO':
  421. $this->todo_count++;
  422. $type = 'VTODO';
  423. break;
  424. case 'BEGIN:VEVENT':
  425. $this->event_count++;
  426. $type = 'VEVENT';
  427. break;
  428. case 'BEGIN:VCALENDAR':
  429. case 'BEGIN:DAYLIGHT':
  430. case 'BEGIN:VTIMEZONE':
  431. case 'BEGIN:STANDARD':
  432. $type = $value;
  433. break;
  434. case 'END:VTODO':
  435. case 'END:VEVENT':
  436. case 'END:VCALENDAR':
  437. case 'END:DAYLIGHT':
  438. case 'END:VTIMEZONE':
  439. case 'END:STANDARD':
  440. $type = 'VCALENDAR';
  441. break;
  442. }
  443. break;
  444. case 'TZID':
  445. if ( 'VTIMEZONE' == $type && ! $this->timezone )
  446. $this->timezone = $this->timezone_from_string( $value );
  447. break;
  448. case 'X-WR-TIMEZONE':
  449. if ( ! $this->timezone )
  450. $this->timezone = $this->timezone_from_string( $value );
  451. break;
  452. default:
  453. $this->add_component( $type, $keyword, $value );
  454. break;
  455. }
  456. }
  457. // Filter for RECURRENCE-IDs
  458. $recurrences = array();
  459. if ( array_key_exists( 'VEVENT', $this->cal ) ) {
  460. foreach ( $this->cal['VEVENT'] as $event ) {
  461. if ( isset( $event['RECURRENCE-ID'] ) ) {
  462. $recurrences[] = $event;
  463. }
  464. }
  465. foreach ( $recurrences as $recurrence ) {
  466. for ( $i = 0; $i < count( $this->cal['VEVENT'] ); $i++ ) {
  467. if ( $this->cal['VEVENT'][ $i ]['UID'] == $recurrence['UID'] && ! isset( $this->cal['VEVENT'][ $i ]['RECURRENCE-ID'] ) ) {
  468. $this->cal['VEVENT'][ $i ]['EXDATE'][] = $recurrence['RECURRENCE-ID'];
  469. break;
  470. }
  471. }
  472. }
  473. }
  474. return $this->cal;
  475. }
  476. /**
  477. * Parse key:value from a string
  478. *
  479. * @param string $text (default: '')
  480. * @return array
  481. */
  482. public function key_value_from_string( $text = '' ) {
  483. preg_match( '/([^:]+)(;[^:]+)?[:]([\w\W]*)/', $text, $matches );
  484. if ( 0 == count( $matches ) )
  485. return false;
  486. return array( $matches[1], $matches[3] );
  487. }
  488. /**
  489. * Convert a timezone name into a timezone object.
  490. *
  491. * @param string $text Timezone name. Example: America/Chicago
  492. * @return object|null A DateTimeZone object if the conversion was successful.
  493. */
  494. private function timezone_from_string( $text ) {
  495. try {
  496. $timezone = new DateTimeZone( $text );
  497. } catch ( Exception $e ) {
  498. $blog_timezone = get_option( 'timezone_string' );
  499. if ( ! $blog_timezone ) {
  500. $blog_timezone = 'Etc/UTC';
  501. }
  502. $timezone = new DateTimeZone( $blog_timezone );
  503. }
  504. return $timezone;
  505. }
  506. /**
  507. * Add a component to the calendar array
  508. *
  509. * @param string $component (default: '')
  510. * @param string $keyword (default: '')
  511. * @param string $value (default: '')
  512. * @return void
  513. */
  514. public function add_component( $component = '', $keyword = '', $value = '' ) {
  515. if ( false == $keyword ) {
  516. $keyword = $this->last_keyword;
  517. switch ( $component ) {
  518. case 'VEVENT':
  519. $value = $this->cal[ $component ][ $this->event_count - 1 ][ $keyword ] . $value;
  520. break;
  521. case 'VTODO' :
  522. $value = $this->cal[ $component ][ $this->todo_count - 1 ][ $keyword ] . $value;
  523. break;
  524. }
  525. }
  526. /*
  527. * Some events have a specific timezone set in their start/end date,
  528. * and it may or may not be different than the calendar timzeone.
  529. * Valid formats include:
  530. * DTSTART;TZID=Pacific Standard Time:20141219T180000
  531. * DTEND;TZID=Pacific Standard Time:20141219T200000
  532. * EXDATE:19960402T010000Z,19960403T010000Z,19960404T010000Z
  533. * EXDATE;VALUE=DATE:2015050
  534. * EXDATE;TZID=America/New_York:20150424T170000
  535. * EXDATE;TZID=Pacific Standard Time:20120615T140000,20120629T140000,20120706T140000
  536. */
  537. // Always store EXDATE as an array
  538. if ( stristr( $keyword, 'EXDATE' ) ) {
  539. $value = explode( ',', $value );
  540. }
  541. // Adjust DTSTART, DTEND, and EXDATE according to their TZID if set
  542. if ( strpos( $keyword, ';' ) && ( stristr( $keyword, 'DTSTART' ) || stristr( $keyword, 'DTEND' ) || stristr( $keyword, 'EXDATE' ) || stristr( $keyword, 'RECURRENCE-ID' ) ) ) {
  543. $keyword = explode( ';', $keyword );
  544. $tzid = false;
  545. if ( 2 == count( $keyword ) ) {
  546. $tparam = $keyword[1];
  547. if ( strpos( $tparam, "TZID" ) !== false ) {
  548. $tzid = $this->timezone_from_string( str_replace( 'TZID=', '', $tparam ) );
  549. }
  550. }
  551. // Normalize all times to default UTC
  552. if ( $tzid ) {
  553. $adjusted_times = array();
  554. foreach ( (array) $value as $v ) {
  555. try {
  556. $adjusted_time = new DateTime( $v, $tzid );
  557. $adjusted_time->setTimeZone( new DateTimeZone( 'UTC' ) );
  558. $adjusted_times[] = $adjusted_time->format('Ymd\THis');
  559. } catch ( Exception $e ) {
  560. // Invalid argument to DateTime
  561. return;
  562. }
  563. }
  564. $value = $adjusted_times;
  565. }
  566. // Format for adding to event
  567. $keyword = $keyword[0];
  568. if ( 'EXDATE' != $keyword ) {
  569. $value = implode( (array) $value );
  570. }
  571. }
  572. foreach ( (array) $value as $v ) {
  573. switch ($component) {
  574. case 'VTODO':
  575. if ( 'EXDATE' == $keyword ) {
  576. $this->cal[ $component ][ $this->todo_count - 1 ][ $keyword ][] = $v;
  577. } else {
  578. $this->cal[ $component ][ $this->todo_count - 1 ][ $keyword ] = $v;
  579. }
  580. break;
  581. case 'VEVENT':
  582. if ( 'EXDATE' == $keyword ) {
  583. $this->cal[ $component ][ $this->event_count - 1 ][ $keyword ][] = $v;
  584. } else {
  585. $this->cal[ $component ][ $this->event_count - 1 ][ $keyword ] = $v;
  586. }
  587. break;
  588. default:
  589. $this->cal[ $component ][ $keyword ] = $v;
  590. break;
  591. }
  592. }
  593. $this->last_keyword = $keyword;
  594. }
  595. /**
  596. * Escape strings with wp_kses, allow links
  597. *
  598. * @param string $string (default: '')
  599. * @return string
  600. */
  601. public function escape( $string = '' ) {
  602. // Unfold content lines per RFC 5545
  603. $string = str_replace( "\n\t", '', $string );
  604. $string = str_replace( "\n ", '', $string );
  605. $allowed_html = array(
  606. 'a' => array(
  607. 'href' => array(),
  608. 'title' => array()
  609. )
  610. );
  611. $allowed_tags = '';
  612. foreach ( array_keys( $allowed_html ) as $tag ) {
  613. $allowed_tags .= "<{$tag}>";
  614. }
  615. // Running strip_tags() first with allowed tags to get rid of remaining gallery markup, etc
  616. // because wp_kses() would only htmlentity'fy that. Then still running wp_kses(), for extra
  617. // safety and good measure.
  618. return wp_kses( strip_tags( $string, $allowed_tags ), $allowed_html );
  619. }
  620. /**
  621. * Render the events
  622. *
  623. * @param string $url (default: '')
  624. * @param string $context (default: 'widget') or 'shortcode'
  625. * @return mixed bool|string false on failure, rendered HTML string on success.
  626. */
  627. public function render( $url = '', $args = array() ) {
  628. $args = wp_parse_args( $args, array(
  629. 'context' => 'widget',
  630. 'number' => 5
  631. ) );
  632. $events = $this->get_events( $url, $args['number'] );
  633. $events = $this->apply_timezone_offset( $events );
  634. if ( empty( $events ) )
  635. return false;
  636. ob_start();
  637. if ( 'widget' == $args['context'] ) : ?>
  638. <ul class="upcoming-events">
  639. <?php foreach ( $events as $event ) : ?>
  640. <li>
  641. <strong class="event-summary"><?php echo $this->escape( stripslashes( $event['SUMMARY'] ) ); ?></strong>
  642. <span class="event-when"><?php echo $this->formatted_date( $event ); ?></span>
  643. <?php if ( ! empty( $event['LOCATION'] ) ) : ?>
  644. <span class="event-location"><?php echo $this->escape( stripslashes( $event['LOCATION'] ) ); ?></span>
  645. <?php endif; ?>
  646. <?php if ( ! empty( $event['DESCRIPTION'] ) ) : ?>
  647. <span class="event-description"><?php echo wp_trim_words( $this->escape( stripcslashes( $event['DESCRIPTION'] ) ) ); ?></span>
  648. <?php endif; ?>
  649. </li>
  650. <?php endforeach; ?>
  651. </ul>
  652. <?php endif;
  653. if ( 'shortcode' == $args['context'] ) : ?>
  654. <table class="upcoming-events">
  655. <thead>
  656. <tr>
  657. <th><?php esc_html_e( 'Location', 'jetpack' ); ?></th>
  658. <th><?php esc_html_e( 'When', 'jetpack' ); ?></th>
  659. <th><?php esc_html_e( 'Summary', 'jetpack' ); ?></th>
  660. <th><?php esc_html_e( 'Description', 'jetpack' ); ?></th>
  661. </tr>
  662. </thead>
  663. <tbody>
  664. <?php foreach ( $events as $event ) : ?>
  665. <tr>
  666. <td><?php echo empty( $event['LOCATION'] ) ? '&nbsp;' : $this->escape( stripslashes( $event['LOCATION'] ) ); ?></td>
  667. <td><?php echo $this->formatted_date( $event ); ?></td>
  668. <td><?php echo empty( $event['SUMMARY'] ) ? '&nbsp;' : $this->escape( stripslashes( $event['SUMMARY'] ) ); ?></td>
  669. <td><?php echo empty( $event['DESCRIPTION'] ) ? '&nbsp;' : wp_trim_words( $this->escape( stripcslashes( $event['DESCRIPTION'] ) ) ); ?></td>
  670. </tr>
  671. <?php endforeach; ?>
  672. </tbody>
  673. </table>
  674. <?php endif;
  675. $rendered = ob_get_clean();
  676. if ( empty( $rendered ) )
  677. return false;
  678. return $rendered;
  679. }
  680. public function formatted_date( $event ) {
  681. $date_format = get_option( 'date_format' );
  682. $time_format = get_option( 'time_format' );
  683. $start = strtotime( $event['DTSTART'] );
  684. $end = isset( $event['DTEND'] ) ? strtotime( $event['DTEND'] ) : false;
  685. $all_day = ( 8 == strlen( $event['DTSTART'] ) );
  686. if ( !$all_day && $this->timezone ) {
  687. try {
  688. $start_time = new DateTime( $event['DTSTART'] );
  689. $timezone_offset = $this->timezone->getOffset( $start_time );
  690. $start += $timezone_offset;
  691. if ( $end ) {
  692. $end += $timezone_offset;
  693. }
  694. } catch ( Exception $e ) {
  695. // Invalid argument to DateTime
  696. }
  697. }
  698. $single_day = $end ? ( $end - $start ) <= DAY_IN_SECONDS : true;
  699. /* translators: Date and time */
  700. $date_with_time = __( '%1$s at %2$s' , 'jetpack' );
  701. /* translators: Two dates with a separator */
  702. $two_dates = __( '%1$s &ndash; %2$s' , 'jetpack' );
  703. // we'll always have the start date. Maybe with time
  704. if ( $all_day )
  705. $date = date_i18n( $date_format, $start );
  706. else
  707. $date = sprintf( $date_with_time, date_i18n( $date_format, $start ), date_i18n( $time_format, $start ) );
  708. // single day, timed
  709. if ( $single_day && ! $all_day && false !== $end )
  710. $date = sprintf( $two_dates, $date, date_i18n( $time_format, $end ) );
  711. // multi-day
  712. if ( ! $single_day ) {
  713. if ( $all_day ) {
  714. // DTEND for multi-day events represents "until", not "including", so subtract one minute
  715. $end_date = date_i18n( $date_format, $end - 60 );
  716. } else {
  717. $end_date = sprintf( $date_with_time, date_i18n( $date_format, $end ), date_i18n( $time_format, $end ) );
  718. }
  719. $date = sprintf( $two_dates, $date, $end_date );
  720. }
  721. return $date;
  722. }
  723. protected function sort_by_recent( $list ) {
  724. $dates = $sorted_list = array();
  725. foreach ( $list as $key => $row ) {
  726. $date = $row['DTSTART'];
  727. // pad some time onto an all day date
  728. if ( 8 === strlen( $date ) )
  729. $date .= 'T000000Z';
  730. $dates[$key] = $date;
  731. }
  732. asort( $dates );
  733. foreach( $dates as $key => $value ) {
  734. $sorted_list[$key] = $list[$key];
  735. }
  736. unset($list);
  737. return $sorted_list;
  738. }
  739. }
  740. /**
  741. * Wrapper function for iCalendarReader->get_events()
  742. *
  743. * @param string $url (default: '')
  744. * @return array
  745. */
  746. function icalendar_get_events( $url = '', $count = 5 ) {
  747. // Find your calendar's address https://support.google.com/calendar/bin/answer.py?hl=en&answer=37103
  748. $ical = new iCalendarReader();
  749. return $ical->get_events( $url, $count );
  750. }
  751. /**
  752. * Wrapper function for iCalendarReader->render()
  753. *
  754. * @param string $url (default: '')
  755. * @param string $context (default: 'widget') or 'shortcode'
  756. * @return mixed bool|string false on failure, rendered HTML string on success.
  757. */
  758. function icalendar_render_events( $url = '', $args = array() ) {
  759. $ical = new iCalendarReader();
  760. return $ical->render( $url, $args );
  761. }