find( $link_id ); $result = array( 'ok' => false, 'error' => '', 'events' => 0, 'conflicts' => 0, ); if ( null === $link || 'ical' !== $link['provider'] ) { $result['error'] = __( 'That calendar no longer exists.', 'schedulereed' ); return $result; } $events = $this->fetch( (string) $link['url'], $this->zone( $link ) ); if ( is_string( $events ) ) { // Keep what was imported last time: a calendar being down must not open up busy time. Services::calendars()->update( $link_id, array( 'last_error' => mb_substr( $events, 0, 255 ), 'last_sync' => Clock::now(), ) ); $result['error'] = $events; return $result; } $result = $this->store( $link, $events ) + $result; Services::calendars()->update( $link_id, array( 'last_error' => '', 'last_sync' => Clock::now(), ) ); $result['ok'] = true; return $result; } /** * Store events for a link and report new ones that clash with bookings. * Also used by Pro's Google and Outlook sync. * * @param array $link Link. * @param array> $events Events {uid, start, end, summary}. * @return array{events: int, conflicts: int} */ public function store( array $link, array $events ): array { $now = Clock::now(); $limit = $now + self::MAX_DAYS_AHEAD * DAY_IN_SECONDS; $known = array_flip( Services::calendars()->uids( $link['id'], $now ) ); $keep = array(); $fresh = array(); foreach ( $events as $event ) { if ( $event['end'] <= $now || $event['start'] >= $limit || $this->is_ours( (string) $event['uid'] ) ) { continue; } $keep[] = $event; if ( ! isset( $known[ $event['uid'] ] ) ) { $fresh[] = $event; } } $count = Services::calendars()->replace_events( $link, $keep, $now ); $conflicts = 0; foreach ( $fresh as $event ) { $filters = array( 'status' => array( Status::PENDING, Status::CONFIRMED, Status::AWAITING_PAYMENT ), 'from' => (int) $event['start'], 'to' => (int) $event['end'], 'per_page' => 1, ); $filters[ 'staff' === $link['owner_type'] ? 'staff_id' : 'bookable_id' ] = $link['owner_id']; if ( 'resource' === $link['owner_type'] ) { continue; } $clash = Services::bookings()->search( $filters )['items'][0] ?? null; if ( null !== $clash ) { ++$conflicts; /** * Fires when an imported calendar shows an event over an existing booking. * * @param array $conflict calendar (name), booking, summary, start, end. */ do_action( 'schedulereed_calendar_conflict', array( 'calendar' => $link['name'], 'booking' => $clash, 'summary' => $event['summary'], 'start' => $event['start'], 'end' => $event['end'], ) ); } } Cache::bump(); return array( 'events' => $count, 'conflicts' => $conflicts, ); } /** * Sync every imported iCal calendar; runs on the cron hook. * * @return array> Results by link ID. */ public function sync_all(): array { $results = array(); foreach ( Services::calendars()->links( '', 0, 'ical' ) as $link ) { $results[ $link['id'] ] = $this->sync( $link['id'] ); } return $results; } /** * Bookings as a calendar file, from a week ago on. Staff feeds show the * customer's name; the "busy" feed shows only that the time is taken. * * @param string $owner_type staff, bookable or all. * @param int $owner_id Owner, or 0 for all. * @param bool $private Include customer names and links. */ public function export( string $owner_type, int $owner_id, bool $private ): string { $now = Clock::now(); $filters = array( 'status' => array( Status::PENDING, Status::CONFIRMED, Status::COMPLETED ), 'from' => $now - WEEK_IN_SECONDS, 'to' => $now + 365 * DAY_IN_SECONDS, 'per_page' => 2000, 'order' => 'asc', ); if ( 'staff' === $owner_type || 'bookable' === $owner_type ) { $filters[ $owner_type . '_id' ] = $owner_id; } $host = self::host(); $events = array(); foreach ( Services::bookings()->search( $filters )['items'] as $booking ) { $details = Services::notifier()->details( $booking ); foreach ( $booking['items'] as $item ) { if ( 'staff' === $owner_type && $item['staff_id'] !== $owner_id ) { continue; } $bookable = Services::catalog()->bookable( $item['bookable_id'] ); $name = $bookable ? $bookable->name : ''; $events[] = array( 'uid' => sprintf( 'schedulereed-%d-%d@%s', $booking['id'], $item['id'], $host ), 'start' => $item['start'], 'end' => $item['end'], 'summary' => $private ? trim( $name . ' – ' . $details['name'], ' –' ) . ( Status::PENDING === $booking['status'] ? ' (' . __( 'to approve', 'schedulereed' ) . ')' : '' ) : __( 'Busy', 'schedulereed' ), 'description' => $private ? admin_url( 'admin.php?page=schedulereed#/bookings/' . $booking['id'] ) : '', 'location' => $private ? ( '' !== $details['meeting'] ? $details['meeting'] : $details['location'] ) : '', ); } } $name = get_bloginfo( 'name' ); if ( 'staff' === $owner_type ) { $member = Services::staff()->find( $owner_id ); $name .= $member ? ' – ' . $member['name'] : ''; } return ICal::write( $events, $name, new DateTimeImmutable( '@' . $now ) ); } /** * The secret part of a feed address. * * @param string $owner_type Owner type. * @param int $owner_id Owner. */ public static function token( string $owner_type, int $owner_id ): string { return substr( hash_hmac( 'sha256', $owner_type . '-' . $owner_id, Settings::ical_key() ), 0, 24 ); } /** * The address to subscribe to a feed. * * @param string $owner_type staff, bookable or all. * @param int $owner_id Owner. */ public static function export_url( string $owner_type, int $owner_id ): string { return rest_url( sprintf( 'schedulereed/v1/ical/%s-%d-%s.ics', $owner_type, $owner_id, self::token( $owner_type, $owner_id ) ) ); } /** * Download and read a calendar. * * @param string $url Address. * @param \DateTimeZone $tz Zone for floating times. * @return array>|string Events, or why it failed. */ private function fetch( string $url, \DateTimeZone $tz ): array|string { $response = wp_safe_remote_get( self::normalize_url( $url ), array( 'timeout' => 20, 'limit_response_size' => self::MAX_BYTES, 'user-agent' => 'ScheduleReed; ' . home_url(), ) ); if ( is_wp_error( $response ) ) { /* translators: %s: error message. */ return sprintf( __( 'Could not reach the calendar: %s', 'schedulereed' ), $response->get_error_message() ); } $status = (int) wp_remote_retrieve_response_code( $response ); if ( 200 !== $status ) { /* translators: %d: HTTP status code, e.g. 404. */ return sprintf( __( 'The calendar address answered with error %d. Check that it is still valid.', 'schedulereed' ), $status ); } $now = Clock::now(); $events = ICal::parse( (string) wp_remote_retrieve_body( $response ), $tz, $now, $now + self::MAX_DAYS_AHEAD * DAY_IN_SECONDS ); if ( null === $events ) { return __( 'That address did not return a calendar (.ics) file.', 'schedulereed' ); } return $events; } /** * The time zone of a calendar's owner. * * @param array $link Link. */ private function zone( array $link ): \DateTimeZone { if ( 'staff' === $link['owner_type'] ) { $member = Services::staff()->find( $link['owner_id'] ); return Settings::zone( (string) ( $member['timezone'] ?? '' ) ); } return Settings::timezone(); } /** * Accept webcal:// addresses, which calendar apps hand out. * * @param string $url Address as entered. */ public static function normalize_url( string $url ): string { $url = trim( $url ); return preg_match( '#^webcals?://#i', $url ) ? 'https://' . preg_replace( '#^webcals?://#i', '', $url ) : $url; } /** * Whether an event is one of this site's own, echoed back by a calendar * that subscribes to our feed. * * @param string $uid Event UID. */ private function is_ours( string $uid ): bool { return str_starts_with( $uid, 'schedulereed-' ) && str_ends_with( $uid, '@' . self::host() ); } private static function host(): string { return (string) wp_parse_url( home_url(), PHP_URL_HOST ); } }