[ [ name, price ] ], type, capacity, * staff => [ [ id, name ] ], locations => [ [ index, type, label ] ], * min_notice, availability => [ start, end ], timezone, image, permalink ] */ class Timetics_Public_Gateway { // Pages of 50 read for the meeting list (500 meetings at most). private const MAX_MEETING_PAGES = 10; /** * Slot answers for this request, by query: the model sometimes asks the * same range twice in one turn. * * @var array */ private array $slots_cache = []; /** * Whether Timetics is loaded. * * @return bool */ public function is_active(): bool { // Not function_exists( 'timetics' ): Timetics declares that helper inside // its namespace, so the global name never exists. return class_exists( 'Timetics\Bootstrap' ); } /** * Whether this Timetics version has the pre-filled link and the * booking-links email. Both ship in the same release. * * @return bool */ public function supports_manage_links(): bool { return false !== has_action( 'timetics_send_manage_links' ); } /** * The visitor's timezone; Timetics shows times in it. * * @return string */ public function visitor_timezone(): string { return Visitor_Timezone::get(); } /** * Now. * * @return \DateTimeImmutable */ public function now(): \DateTimeImmutable { return new \DateTimeImmutable( 'now', new \DateTimeZone( 'UTC' ) ); } /** * Meetings a visitor can book. * * @return array List of meetings in the shape above. */ public function meetings(): array { $out = []; for ( $page = 1; $page <= self::MAX_MEETING_PAGES; $page++ ) { $data = $this->data_of( '/timetics/v1/appointments/filter', [ 'per_page' => 50, 'paged' => $page, ] ); $items = is_array( $data['items'] ?? null ) ? $data['items'] : []; foreach ( $items as $item ) { $meeting = is_array( $item ) && self::bookable( (int) ( $item['id'] ?? 0 ) ) ? self::shape_meeting( $this->with_category( $item ) ) : null; if ( null !== $meeting ) { $out[] = $meeting; } } if ( count( $items ) < 50 ) { break; } } return $out; } /** * One meeting a visitor can book, or null. * * @param int $id Meeting id. * @return array|null */ public function meeting( int $id ): ?array { if ( ! self::bookable( $id ) ) { return null; } $item = $this->data_of( '/timetics/v1/appointments/' . $id, [] ); return $item ? self::shape_meeting( $this->with_category( $item ) ) : null; } /** * Whether a visitor may see this meeting. Timetics' single-meeting route * only checks the post type, and its list keeps password protected posts. * * @param int $id Meeting id. * @return bool */ private static function bookable( int $id ): bool { return $id > 0 && 'publish' === get_post_status( $id ) && ! post_password_required( $id ); } /** * Raw days and slots for one staff member, from Timetics' slot route. * * @param int $meeting_id Meeting id. * @param int $staff_id Staff id. * @param string $start Y-m-d. * @param string $end Y-m-d. * @param string $timezone Timezone the times come back in. * @return array List of [ date, slots => [ [ start_time, status ] ] ]; [] on any error. */ public function slots( int $meeting_id, int $staff_id, string $start, string $end, string $timezone ): array { $query = [ 'meeting_id' => $meeting_id, 'staff_id' => $staff_id, 'start_date' => $start, 'end_date' => $end, 'timezone' => $timezone, ]; $key = md5( (string) wp_json_encode( $query ) ); if ( ! isset( $this->slots_cache[ $key ] ) ) { $data = $this->data_of( '/timetics/v1/bookings/entries', $query ); $this->slots_cache[ $key ] = is_array( $data['days'] ?? null ) ? array_values( $data['days'] ) : []; } return $this->slots_cache[ $key ]; } /** * Days the owner blocked for every meeting (Timetics settings). * * @return array List of [ date, schedule => [ [ start => [ label ], end => [ label ] ] ] ]. */ public function blocked_days(): array { $days = function_exists( 'timetics_get_option' ) ? timetics_get_option( 'blocked_days', [] ) : []; return is_array( $days ) ? $days : []; } /** * A price in the Timetics currency. * * @param float $price Price. * @return string e.g. "$25.00", or "Free". */ public function price_text( float $price ): string { if ( $price <= 0 ) { return __( 'Free', 'aisentic' ); } // The currency Timetics charges and shows in: WooCommerce's when that // integration is on (timetics/core/bookings/api-booking.php). // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Timetics' own filter. $currency = (string) apply_filters( 'timetics_currency', function_exists( 'timetics_get_option' ) ? timetics_get_option( 'currency', 'USD' ) : 'USD' ); // ponytail: intl's formatter when the server has it, else "USD 25.00". if ( class_exists( '\NumberFormatter' ) ) { $text = ( new \NumberFormatter( get_locale(), \NumberFormatter::CURRENCY ) )->formatCurrency( $price, $currency ); if ( false !== $text ) { return $text; } } return $currency . ' ' . number_format_i18n( $price, 2 ); } /** * Public page of a meeting. * * @param int $id Meeting id. * @return string */ public function meeting_url( int $id ): string { return (string) get_permalink( $id ); } /** * Shape one raw meeting, or null when a visitor may not book it. * * Only `enabled`: the booking form refuses anything else * (timetics/core/frontend/shortcode.php), though the REST list also shows * a blank visibility. * * @param array $item Raw meeting from Timetics' REST routes. * @return array|null */ public static function shape_meeting( array $item ): ?array { $id = (int) ( $item['id'] ?? 0 ); if ( 0 === $id || 'enabled' !== ( $item['visibility'] ?? '' ) ) { return null; } $staff = []; foreach ( (array) ( $item['staff'] ?? [] ) as $member ) { if ( is_array( $member ) && ! empty( $member['id'] ) ) { $staff[] = [ 'id' => (int) $member['id'], 'name' => self::text( $member['full_name'] ?? '' ), ]; } } $locations = []; foreach ( array_values( (array) ( $item['locations'] ?? [] ) ) as $index => $location ) { if ( is_array( $location ) ) { $locations[] = [ 'index' => $index, 'type' => (string) ( $location['location_type'] ?? '' ), 'label' => self::location_label( $location ), ]; } } // Seat meetings can sell several tickets ("default", "Vip"); one-to-one // meetings have one. $tickets = []; foreach ( is_array( $item['price'] ?? null ) ? $item['price'] : [] as $ticket ) { if ( is_array( $ticket ) ) { $tickets[] = [ 'name' => self::text( (string) ( $ticket['ticket_name'] ?? '' ) ), 'price' => (float) ( $ticket['ticket_price'] ?? 0 ), ]; } } $duration = (string) ( $item['duration'] ?? '' ); $window = is_array( $item['availability'] ?? null ) ? $item['availability'] : []; return [ 'id' => $id, 'name' => self::text( $item['name'] ?? '' ), 'description' => mb_substr( trim( wp_strip_all_tags( self::text( $item['description'] ?? '' ) ) ), 0, 300 ), 'category' => (string) ( $item['category_name'] ?? '' ), 'duration' => $duration, 'minutes' => self::minutes( $duration ), 'price' => $tickets ? min( array_column( $tickets, 'price' ) ) : 0.0, 'tickets' => $tickets, 'type' => (string) ( $item['type'] ?? '' ), 'capacity' => max( 1, (int) ( $item['capacity'] ?? 1 ) ), 'staff' => $staff, 'locations' => $locations, 'min_notice' => (string) ( $item['min_notice_time'] ?? '' ), 'availability' => [ 'start' => (string) ( $window['start'] ?? '' ), 'end' => (string) ( $window['end'] ?? '' ), ], 'timezone' => (string) ( $item['timezone'] ?? '' ), // Cards put these in src and href. 'image' => is_string( $item['image'] ?? null ) ? esc_url_raw( $item['image'] ) : '', 'permalink' => esc_url_raw( (string) ( $item['permalink'] ?? '' ) ), ]; } /** * Keep only what the Timetics booking form would offer. * * The slot route returns everything; the form then hides, in the browser * (BookingSlot.js, BookingCalendar.js): unavailable slots, days outside the * meeting's date window, blocked days and blocked time ranges (inclusive), * and times not after now plus the minimum notice. * * @param array $days Raw days from slots(). * @param array $meeting Shaped meeting. * @param array $blocked_days From blocked_days(). * @param \DateTimeImmutable $now Now, in the timezone the slots are in. * @return array List of [ date => Y-m-d, slots => [ H:i ] ], days without slots dropped. */ public static function filter_slots( array $days, array $meeting, array $blocked_days, \DateTimeImmutable $now ): array { $from = (string) ( $meeting['availability']['start'] ?? '' ); $to = (string) ( $meeting['availability']['end'] ?? '' ); $cutoff = $now->modify( '+' . self::notice_minutes( (string) ( $meeting['min_notice'] ?? '' ) ) . ' minutes' ); $blocked = []; foreach ( $blocked_days as $day ) { if ( is_array( $day ) && ! empty( $day['date'] ) ) { $blocked[ (string) $day['date'] ] = (array) ( $day['schedule'] ?? [] ); } } $out = []; foreach ( $days as $day ) { $date = (string) ( $day['date'] ?? '' ); if ( '' === $date || ( '' !== $from && $date < $from ) || ( '' !== $to && $date > $to ) ) { continue; } if ( isset( $blocked[ $date ] ) && ! $blocked[ $date ] ) { continue; } $times = []; foreach ( (array) ( $day['slots'] ?? [] ) as $slot ) { $time = self::hm( (string) ( $slot['start_time'] ?? '' ) ); if ( '' === $time || 'available' !== ( $slot['status'] ?? '' ) ) { continue; } foreach ( $blocked[ $date ] ?? [] as $range ) { // Timetics saves "HH:mm"; read "10:00 am" too, so a format change // cannot quietly let blocked times through. // Not $from/$to: those hold the meeting's date window for later days. $block_from = self::hm( (string) ( $range['start']['label'] ?? '' ) ); $block_to = self::hm( (string) ( $range['end']['label'] ?? '' ) ); if ( '' !== $block_from && '' !== $block_to && $time >= $block_from && $time <= $block_to ) { continue 2; } } $start = \DateTimeImmutable::createFromFormat( 'Y-m-d H:i', $date . ' ' . $time, $now->getTimezone() ); if ( ! $start || $start <= $cutoff ) { continue; } $times[] = $time; } if ( $times ) { $out[] = [ 'date' => $date, 'slots' => $times, ]; } } return $out; } /** * A Timetics time ("10:00am", "2:30 pm", "14:30") as "H:i", or ''. * * @param string $time Time. * @return string */ public static function hm( string $time ): string { if ( ! preg_match( '/^(\d{1,2}):(\d{2})\s*(am|pm)?$/i', trim( $time ), $match ) ) { return ''; } $hour = (int) $match[1]; $minute = (int) $match[2]; $period = strtolower( $match[3] ?? '' ); if ( $minute > 59 || ( '' === $period ? $hour > 23 : ( $hour < 1 || $hour > 12 ) ) ) { return ''; } if ( '' !== $period ) { $hour = $hour % 12 + ( 'pm' === $period ? 12 : 0 ); } return sprintf( '%02d:%02d', $hour, $minute ); } /** * Minutes in "30 min" or "1 hr". * * @param string $duration Duration. * @return int */ private static function minutes( string $duration ): int { if ( ! preg_match( '/^\s*(\d+(?:\.\d+)?)\s*(min|hr)/i', $duration, $match ) ) { return 0; } return (int) round( (float) $match[1] * ( 'hr' === strtolower( $match[2] ) ? 60 : 1 ) ); } /** * Minutes in a minimum notice like "2 hr" or "1 day". Anything else is 0, * as in the booking form. * * @param string $notice Notice. * @return int */ private static function notice_minutes( string $notice ): int { if ( ! preg_match( '/^\s*(\d+)\s*(min|hr|day)/i', $notice, $match ) ) { return 0; } $unit = [ 'min' => 1, 'hr' => 60, 'day' => 1440, ]; return (int) $match[1] * $unit[ strtolower( $match[2] ) ]; } /** * A meeting location for visitors. * * @param array $location [ location_type, location ]. * @return string */ private static function location_label( array $location ): string { $type = (string) ( $location['location_type'] ?? '' ); $place = self::text( $location['location'] ?? '' ); switch ( $type ) { case 'in-person-meeting': return '' !== $place ? sprintf( /* translators: %s: address */ __( 'In person: %s', 'aisentic' ), $place ) : __( 'In person', 'aisentic' ); case 'google-meet': return __( 'Google Meet', 'aisentic' ); case 'zoom': return __( 'Zoom', 'aisentic' ); case 'phone-call': return __( 'Phone call', 'aisentic' ); case 'attendee-call': return __( 'Phone call (we call you)', 'aisentic' ); default: return '' !== $place ? $place : $type; } } /** * Add the first category name, for search and cards. * * @param array $item Raw meeting. * @return array */ private function with_category( array $item ): array { foreach ( (array) ( $item['categories'] ?? [] ) as $term_id ) { $term = get_term( (int) $term_id, 'timetics-meeting-category' ); if ( $term instanceof \WP_Term ) { $item['category_name'] = self::text( $term->name ); break; } } return $item; } /** * Plain text for visitors: titles can be stored HTML-encoded. * * @param mixed $value Raw value. * @return string */ private static function text( $value ): string { return html_entity_decode( (string) $value, ENT_QUOTES | ENT_HTML5, 'UTF-8' ); } /** * Run a Timetics REST read as the current visitor and unwrap `{ data }`. * * @param string $route Route. * @param array $query Query params. * @return array */ private function data_of( string $route, array $query ): array { $request = new \WP_REST_Request( 'GET', $route ); $request->set_query_params( $query ); $response = rest_do_request( $request ); if ( $response->is_error() ) { Log::warning( 'Timetics public gateway error', [ 'route' => $route ] ); return []; } $body = $response->get_data(); return is_array( $body['data'] ?? null ) ? $body['data'] : []; } }