icalendar-reader.php 29 KB

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