self::VENUE, 'organizer' => self::ORGANIZER, 'series' => self::SERIES ]; public const LOCATION_FIELDS = [ 'address', 'city', 'region', 'postal', 'country', 'website', 'email', 'phone' ]; private const IMPORTED_DATES = '_burn_imported_dates'; private static bool $in_transaction = false; public static function register_types(): void { register_post_type( self::EVENT, [ 'labels' => [ 'name' => __( 'Events', 'burn-events' ), 'menu_name' => __( 'Events', 'burn-events' ), 'singular_name' => __( 'Event', 'burn-events' ), 'add_new' => __( 'Add Event', 'burn-events' ), 'add_new_item' => __( 'Add Event', 'burn-events' ), 'edit_item' => __( 'Edit Event', 'burn-events' ), 'view_item' => __( 'View Event', 'burn-events' ), ], 'public' => true, 'show_in_rest' => true, 'has_archive' => 'events', 'rewrite' => [ 'slug' => 'event', 'with_front' => false ], 'menu_icon' => 'dashicons-calendar-alt', 'supports' => [ 'title', 'editor', 'thumbnail', 'excerpt', 'author', 'revisions', 'comments' ], ] ); $types = [ self::VENUE => [ __( 'Venues', 'burn-events' ), __( 'Venue', 'burn-events' ), __( 'New Venue', 'burn-events' ), 'event-venue' ], self::ORGANIZER => [ __( 'Organizers', 'burn-events' ), __( 'Organizer', 'burn-events' ), __( 'New Organizer', 'burn-events' ), 'event-organizer' ], self::SERIES => [ __( 'Series', 'burn-events' ), __( 'Series', 'burn-events' ), __( 'New Series', 'burn-events' ), 'event-series' ], ]; foreach ( $types as $type => [ $plural, $singular, $create, $slug ] ) { register_post_type( $type, [ 'labels' => [ 'name' => $plural, 'singular_name' => $singular, 'add_new' => $create, 'add_new_item' => $create, 'new_item' => $create ], 'public' => true, 'show_in_menu' => 'edit.php?post_type=' . self::EVENT, 'show_in_rest' => true, 'rewrite' => [ 'slug' => $slug, 'with_front' => false ], 'supports' => [ 'title', 'editor', 'thumbnail', 'revisions' ], ] ); } register_taxonomy( self::CATEGORY, [ self::EVENT ], [ 'labels' => [ 'name' => __( 'Event Categories', 'burn-events' ), 'singular_name' => __( 'Event Category', 'burn-events' ) ], 'hierarchical' => true, 'public' => true, 'show_in_rest' => true, 'show_admin_column' => true, 'rewrite' => [ 'slug' => 'event-category', 'with_front' => false ], ] ); register_taxonomy_for_object_type( 'post_tag', self::EVENT ); } public static function table(): string { global $wpdb; return $wpdb->prefix . 'burn_event_occurrences'; } public static function ensure_schema(): void { if ( '1' === get_option( 'burn_events_schema' ) ) { return; } global $wpdb; require_once ABSPATH . 'wp-admin/includes/upgrade.php'; $table = self::table(); $collation = $wpdb->get_charset_collate(); dbDelta( "CREATE TABLE $table ( event_id bigint unsigned NOT NULL, starts_at datetime NOT NULL, ends_at datetime NOT NULL, PRIMARY KEY (event_id,starts_at), KEY starts_at (starts_at), KEY ends_at (ends_at) ) ENGINE=InnoDB $collation;" ); if ( $table === $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->esc_like( $table ) ) ) ) { update_option( 'burn_events_schema', '1' ); } } public static function event_data( int $id ): array { $data = (array) get_post_meta( $id, '_burn_event', true ); return $data + [ 'schedule' => [], 'status' => 'scheduled', 'venue' => [], 'organizer' => [], 'series' => [], 'location' => '', 'cost' => '', 'url' => '', 'featured' => false, 'hidden' => false, 'fields' => [], ]; } public static function location_data( int $id ): array { return (array) get_post_meta( $id, '_burn_location', true ) + [ 'address' => '', 'city' => '', 'region' => '', 'postal' => '', 'country' => '', 'latitude' => '', 'longitude' => '', 'website' => '', 'email' => '', 'phone' => '', 'geocode' => [], ]; } public static function save_location( int $id, array $input, bool $retry = false ): array { try { return self::transaction( static function () use ( $id, $input, $retry ): array { if ( ! self::lock_post( $id ) ) { throw new RuntimeException( __( 'The location could not be saved.', 'burn-events' ) ); } $previous = self::location_data( $id ); $data = []; foreach ( self::LOCATION_FIELDS as $field ) { $value = $input[ $field ] ?? $previous[ $field ]; $data[ $field ] = is_scalar( $value ) ? sanitize_text_field( (string) $value ) : ''; } $data['website'] = esc_url_raw( $data['website'], [ 'http', 'https' ] ); $data['email'] = sanitize_email( $data['email'] ); $data = Maps::with_coordinates( $data, $previous, $retry ); self::write_meta( $id, '_burn_location', $data ); self::write_meta( $id, '_burn_address', Maps::address( $data ) ); return $data; } ); } finally { wp_cache_delete( $id, 'post_meta' ); } } public static function lock_post( int $id ): bool { global $wpdb; $locked = (bool) $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE ID = %d FOR UPDATE", $id ) ); wp_cache_delete( $id, 'posts' ); wp_cache_delete( $id, 'post_meta' ); return $locked; } public static function write_meta( int $id, string $key, $value ): void { $expected = maybe_serialize( $value ); if ( maybe_serialize( get_post_meta( $id, $key, true ) ) === $expected ) { return; } if ( update_post_meta( $id, $key, wp_slash( $value ) ) ) { return; } wp_cache_delete( $id, 'post_meta' ); if ( maybe_serialize( get_post_meta( $id, $key, true ) ) !== $expected ) { throw new RuntimeException( __( 'The event data could not be saved.', 'burn-events' ) ); } } public static function transaction( callable $write ) { if ( self::$in_transaction ) { return $write(); } global $wpdb; if ( false === $wpdb->query( 'START TRANSACTION' ) ) { throw new RuntimeException( __( 'The database write could not start.', 'burn-events' ) ); } self::$in_transaction = true; try { $result = $write(); if ( is_wp_error( $result ) ) { $wpdb->query( 'ROLLBACK' ); } elseif ( false === $wpdb->query( 'COMMIT' ) ) { throw new RuntimeException( __( 'The database write could not finish.', 'burn-events' ) ); } return $result; } catch ( \Throwable $error ) { $wpdb->query( 'ROLLBACK' ); throw $error; } finally { self::$in_transaction = false; } } public static function locations( array $ids, string $type ): array { $locations = []; foreach ( $ids as $id ) { $post = get_post( $id ); if ( $post && $type === $post->post_type && 'publish' === $post->post_status && '' === $post->post_password ) { $locations[] = $post; } } return $locations; } public static function validate_event( array $input ): array { $settings = Admin::options(); $schedule = Schedule::validate( $input, $settings['timezone'] ); $string = static fn( string $key ): string => is_scalar( $input[ $key ] ?? null ) ? sanitize_text_field( (string) $input[ $key ] ) : ''; $status = $string( 'status' ); $event = [ 'schedule' => $schedule, 'status' => array_key_exists( $status, self::statuses() ) ? $status : 'scheduled', 'location' => $string( 'location' ), 'cost' => $string( 'cost' ), 'url' => esc_url_raw( $string( 'url' ), [ 'http', 'https' ] ), 'featured' => ! empty( $input['featured'] ), 'hidden' => ! empty( $input['hidden'] ), 'fields' => [], ]; foreach ( self::RELATIONS as $name => $type ) { $ids = array_unique( array_filter( array_map( 'absint', (array) ( $input[ $name ] ?? [] ) ) ) ); $event[ $name ] = array_map( static fn( WP_Post $post ): int => $post->ID, self::locations( $ids, $type ) ); } foreach ( $settings['fields'] as $key => $field ) { $raw = $input['fields'][ $key ] ?? ''; $value = is_scalar( $raw ) ? sanitize_text_field( (string) $raw ) : ''; switch ( $field['type'] ) { case 'url': $value = esc_url_raw( $value, [ 'http', 'https' ] ); break; case 'checkbox': $value = $value ? '1' : ''; break; case 'select': $value = in_array( $value, $field['choices'], true ) ? $value : ''; break; } $event['fields'][ $key ] = $value; } return $event; } public static function statuses(): array { return [ 'scheduled' => __( 'Scheduled', 'burn-events' ), 'postponed' => __( 'Postponed', 'burn-events' ), 'cancelled' => __( 'Cancelled', 'burn-events' ), 'moved_online' => __( 'Moved online', 'burn-events' ), ]; } public static function save( int $id, array $event, ?array $imported_dates = null ): void { self::index( $id, $event, $imported_dates ); } public static function uses_imported_dates( int $id ): bool { return (bool) get_post_meta( $id, self::IMPORTED_DATES, true ); } public static function rebuild( int $id ): void { if ( self::EVENT === get_post_type( $id ) ) { self::index( $id ); } } private static function index( int $id, ?array $new_data = null, ?array $imported_dates = null ): void { try { self::transaction( static function () use ( $id, $new_data, $imported_dates ): void { global $wpdb; $table = self::table(); if ( ! self::lock_post( $id ) ) { throw new RuntimeException( __( 'The event could not be saved.', 'burn-events' ) ); } $previous_data = self::event_data( $id ); $data = $new_data ?? $previous_data; if ( ! $data['schedule'] ) { return; } $dates = get_post_meta( $id, self::IMPORTED_DATES, true ); if ( null !== $imported_dates ) { $dates = $imported_dates; self::write_meta( $id, self::IMPORTED_DATES, $dates ); } elseif ( $dates && $new_data && $data['schedule'] !== $previous_data['schedule'] ) { if ( ! delete_post_meta( $id, self::IMPORTED_DATES ) ) { throw new RuntimeException( __( 'The imported dates could not be replaced.', 'burn-events' ) ); } $dates = []; } $horizon = new DateTimeImmutable( '+2 years', wp_timezone() ); if ( false === $wpdb->delete( $table, [ 'event_id' => $id ], [ '%d' ] ) ) { throw new RuntimeException( __( 'The schedule could not be indexed.', 'burn-events' ) ); } $rows = []; foreach ( $dates ?: Schedule::occurrences( $data['schedule'], $horizon ) as [ $start, $end ] ) { $rows[] = $wpdb->prepare( '(%d, %s, %s)', $id, $start, $end ); if ( 100 === count( $rows ) ) { self::insert_occurrences( $table, $rows ); $rows = []; } } if ( $rows ) { self::insert_occurrences( $table, $rows ); } if ( null !== $new_data ) { self::write_meta( $id, '_burn_event', $data ); self::write_meta( $id, '_burn_hidden', $data['hidden'] ? '1' : '0' ); self::write_meta( $id, '_burn_featured', $data['featured'] ? '1' : '0' ); self::write_meta( $id, '_burn_search_location', $data['location'] ); self::write_meta( $id, '_burn_repeating', 'none' === $data['schedule']['repeat'] ? '0' : '1' ); foreach ( self::RELATIONS as $name => $type ) { $key = '_burn_' . $name; $previous = get_post_meta( $id, $key, false ); $ids = array_map( 'strval', $data[ $name ] ); if ( $previous === $ids ) { continue; } if ( $previous && ! delete_post_meta( $id, $key ) ) { throw new RuntimeException( __( 'Event links could not be saved.', 'burn-events' ) ); } foreach ( $ids as $linked_id ) { if ( ! add_post_meta( $id, $key, $linked_id ) ) { throw new RuntimeException( __( 'Event links could not be saved.', 'burn-events' ) ); } } } } } ); } finally { wp_cache_delete( $id, 'post_meta' ); } } private static function insert_occurrences( string $table, array $rows ): void { global $wpdb; if ( false === $wpdb->query( "INSERT INTO $table (event_id, starts_at, ends_at) VALUES " . implode( ',', $rows ) ) ) { throw new RuntimeException( __( 'The schedule could not be indexed.', 'burn-events' ) ); } } public static function extend(): void { for ( $page = 1; ; $page++ ) { $ids = get_posts( [ 'post_type' => self::EVENT, 'post_status' => [ 'publish', 'pending', 'draft', 'private', 'future' ], 'fields' => 'ids', 'meta_key' => '_burn_repeating', 'meta_value' => '1', 'posts_per_page' => 100, 'paged' => $page, 'orderby' => 'ID', 'order' => 'ASC', ] ); foreach ( $ids as $id ) { try { self::rebuild( $id ); } catch ( \Throwable $error ) { if ( ! wp_next_scheduled( 'burn_events_rebuild_schedule', [ $id ] ) ) { wp_schedule_single_event( time() + HOUR_IN_SECONDS, 'burn_events_rebuild_schedule', [ $id ] ); } } } if ( count( $ids ) < 100 ) { break; } } } public static function delete_occurrences( int $id ): void { if ( self::EVENT === get_post_type( $id ) ) { global $wpdb; $wpdb->delete( self::table(), [ 'event_id' => $id ], [ '%d' ] ); } } public static function query( array $filters ): array { global $wpdb; $table = self::table(); $filters += [ 'from' => null, 'to' => null, 'end_by' => null, 'past' => false, 'order' => '', 'search' => '', 'category' => '', 'tag' => '', 'location' => '', 'relation' => null, 'relations' => [], 'scope' => '', 'featured' => false, 'exclude' => 0, 'offset' => 0, 'limit' => 20 ]; $where = [ "p.post_type = 'burn_event'", "p.post_status = 'publish'", "p.post_password = ''" ]; $where[] = "NOT EXISTS (SELECT 1 FROM $wpdb->postmeta h WHERE h.post_id = p.ID AND h.meta_key = '_burn_hidden' AND h.meta_value = '1')"; if ( '' !== $filters['scope'] ) { $where[] = Clubs::condition( $filters['scope'] ); } if ( $filters['from'] ) { $where[] = $wpdb->prepare( 'o.ends_at > %s', $filters['from'] ); } if ( $filters['to'] ) { $where[] = $wpdb->prepare( $filters['past'] ? 'o.ends_at <= %s' : 'o.starts_at < %s', $filters['to'] ); } if ( $filters['end_by'] ) { $where[] = $wpdb->prepare( 'o.ends_at <= %s', $filters['end_by'] ); } if ( $filters['exclude'] ) { $where[] = $wpdb->prepare( 'p.ID <> %d', $filters['exclude'] ); } if ( $filters['search'] ) { $like = '%' . $wpdb->esc_like( $filters['search'] ) . '%'; $where[] = $wpdb->prepare( '(p.post_title LIKE %s OR p.post_content LIKE %s)', $like, $like ); } foreach ( [ 'category' => self::CATEGORY, 'tag' => 'post_tag' ] as $key => $taxonomy ) { if ( $filters[ $key ] ) { $slugs = array_values( (array) $filters[ $key ] ); $placeholders = implode( ', ', array_fill( 0, count( $slugs ), '%s' ) ); $where[] = $wpdb->prepare( "EXISTS (SELECT 1 FROM $wpdb->term_relationships r JOIN $wpdb->term_taxonomy tt ON tt.term_taxonomy_id = r.term_taxonomy_id JOIN $wpdb->terms t ON t.term_id = tt.term_id WHERE r.object_id = p.ID AND tt.taxonomy = %s AND t.slug IN ($placeholders))", $taxonomy, ...$slugs ); } } $relations = array_intersect_key( $filters['relations'], self::RELATIONS ); if ( $filters['relation'] ) { [ $type, $id ] = $filters['relation']; $relations[ $type ] = [ (string) $id ]; } foreach ( $relations as $type => $ids ) { if ( $ids ) { $placeholders = implode( ', ', array_fill( 0, count( $ids ), '%s' ) ); $where[] = $wpdb->prepare( "EXISTS (SELECT 1 FROM $wpdb->postmeta m WHERE m.post_id = p.ID AND m.meta_key = %s AND m.meta_value IN ($placeholders))", '_burn_' . $type, ...array_values( $ids ) ); } } if ( $filters['location'] ) { $like = '%' . $wpdb->esc_like( $filters['location'] ) . '%'; $where[] = $wpdb->prepare( "EXISTS (SELECT 1 FROM $wpdb->postmeta m LEFT JOIN $wpdb->posts v ON m.meta_key = '_burn_venue' AND v.ID = CAST(m.meta_value AS UNSIGNED) AND v.post_status = 'publish' LEFT JOIN $wpdb->postmeta a ON a.post_id = v.ID AND a.meta_key = '_burn_address' WHERE m.post_id = p.ID AND (v.post_title LIKE %s OR a.meta_value LIKE %s OR (m.meta_key = '_burn_search_location' AND m.meta_value LIKE %s)))", $like, $like, $like ); } if ( $filters['featured'] ) { $featured = "EXISTS (SELECT 1 FROM $wpdb->postmeta f WHERE f.post_id = p.ID AND f.meta_key = '_burn_featured' AND f.meta_value = '1')"; $where[] = 'regular' === $filters['featured'] ? 'NOT ' . $featured : $featured; } $order = in_array( $filters['order'], [ 'ASC', 'DESC' ], true ) ? $filters['order'] : ( $filters['past'] ? 'DESC' : 'ASC' ); $limit = $wpdb->prepare( ' LIMIT %d OFFSET %d', $filters['limit'], $filters['offset'] ); return $wpdb->get_results( "SELECT o.event_id, o.starts_at, o.ends_at FROM $table o JOIN $wpdb->posts p ON p.ID = o.event_id WHERE " . implode( ' AND ', $where ) . " ORDER BY o.starts_at $order, o.event_id $order" . $limit, ARRAY_A ) ?: []; } public static function occurrence( int $id, string $requested = '' ): ?array { global $wpdb; $table = self::table(); $date = preg_match( '/^-?\d{1,12}$/D', $requested ) ? gmdate( 'Y-m-d H:i:s', (int) $requested ) : ''; if ( $date ) { $row = $wpdb->get_row( $wpdb->prepare( "SELECT event_id, starts_at, ends_at FROM $table WHERE event_id = %d AND starts_at = %s", $id, $date ), ARRAY_A ); if ( $row ) { return $row; } } return $wpdb->get_row( $wpdb->prepare( "SELECT event_id, starts_at, ends_at FROM $table WHERE event_id = %d ORDER BY CASE WHEN ends_at > %s THEN 0 ELSE 1 END, starts_at LIMIT 1", $id, gmdate( 'Y-m-d H:i:s' ) ), ARRAY_A ); } public static function local_time( string $utc, string $zone ): DateTimeImmutable { return ( new DateTimeImmutable( $utc, new DateTimeZone( 'UTC' ) ) )->setTimezone( new DateTimeZone( $zone ) ); } public static function event_url( array $occurrence ): string { return add_query_arg( 'be_occ', strtotime( $occurrence['starts_at'] . ' UTC' ), get_permalink( (int) $occurrence['event_id'] ) ); } }