Publish eventLabs 0.5.0
This commit is contained in:
495
includes/class-admin.php
Normal file
495
includes/class-admin.php
Normal file
@@ -0,0 +1,495 @@
|
||||
<?php
|
||||
|
||||
namespace BurnEvents;
|
||||
|
||||
use DateTimeImmutable;
|
||||
use DateTimeZone;
|
||||
use WP_Post;
|
||||
use WP_Term;
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
final class Admin {
|
||||
private const OPTION = 'burn_events_settings';
|
||||
|
||||
public static function register(): void {
|
||||
add_action( 'admin_menu', [ self::class, 'menu' ] );
|
||||
add_action( 'admin_init', [ self::class, 'settings' ] );
|
||||
add_action( 'add_meta_boxes', [ self::class, 'boxes' ] );
|
||||
add_action( 'save_post_' . Events::EVENT, [ self::class, 'save_event' ] );
|
||||
add_action( 'save_post_' . Events::VENUE, [ self::class, 'save_location' ] );
|
||||
add_action( 'save_post_' . Events::ORGANIZER, [ self::class, 'save_location' ] );
|
||||
add_action( 'admin_notices', [ self::class, 'errors' ] );
|
||||
add_action( 'admin_enqueue_scripts', [ self::class, 'assets' ] );
|
||||
add_action( Events::CATEGORY . '_edit_form_fields', [ self::class, 'category_color_field' ] );
|
||||
add_action( 'edited_' . Events::CATEGORY, [ self::class, 'save_category_color' ] );
|
||||
add_filter( 'manage_burn_event_posts_columns', [ self::class, 'columns' ] );
|
||||
add_action( 'manage_burn_event_posts_custom_column', [ self::class, 'column' ], 10, 2 );
|
||||
}
|
||||
|
||||
public static function assets(): void {
|
||||
$screen = get_current_screen();
|
||||
if ( $screen && 'post' === $screen->base && Events::EVENT === $screen->post_type ) {
|
||||
wp_enqueue_style( 'burn-events-editor', plugins_url( 'assets/event-editor.css', BURN_EVENTS_FILE ), [], BURN_EVENTS_VERSION );
|
||||
wp_enqueue_script( 'burn-events-editor', plugins_url( 'assets/event-editor.js', BURN_EVENTS_FILE ), [], BURN_EVENTS_VERSION, true );
|
||||
}
|
||||
if ( ! $screen || Events::CATEGORY !== $screen->taxonomy || 'term' !== $screen->base ) {
|
||||
return;
|
||||
}
|
||||
wp_enqueue_style( 'wp-color-picker' );
|
||||
wp_enqueue_script( 'wp-color-picker' );
|
||||
wp_add_inline_script( 'wp-color-picker', 'jQuery(function ($) { $(".be-category-color").wpColorPicker(); });' );
|
||||
}
|
||||
|
||||
public static function category_color_field( WP_Term $term ): void {
|
||||
$color = sanitize_hex_color( (string) get_term_meta( $term->term_id, Calendar_Grid::COLOR_META, true ) );
|
||||
?>
|
||||
<tr class="form-field">
|
||||
<th scope="row"><label for="be-category-color"><?php esc_html_e( 'Calendar color', 'burn-events' ); ?></label></th>
|
||||
<td>
|
||||
<?php wp_nonce_field( 'burn_events_category_color', 'burn_events_category_color_nonce', false ); ?>
|
||||
<input type="text" id="be-category-color" class="be-category-color" name="burn_events_category_color" value="<?php echo esc_attr( $color ?? '' ); ?>" aria-describedby="be-category-color-description">
|
||||
<p class="description" id="be-category-color-description"><?php esc_html_e( 'Leave blank to use the automatic color for this category.', 'burn-events' ); ?></p>
|
||||
</td>
|
||||
</tr>
|
||||
<?php
|
||||
}
|
||||
|
||||
public static function save_category_color( int $term_id ): void {
|
||||
$nonce = $_POST['burn_events_category_color_nonce'] ?? null;
|
||||
$input = $_POST['burn_events_category_color'] ?? null;
|
||||
if ( ! is_string( $nonce ) || ! is_string( $input ) || ! current_user_can( 'edit_term', $term_id )
|
||||
|| ! wp_verify_nonce( sanitize_text_field( wp_unslash( $nonce ) ), 'burn_events_category_color' )
|
||||
) {
|
||||
return;
|
||||
}
|
||||
$input = trim( wp_unslash( $input ) );
|
||||
if ( '' === $input ) {
|
||||
delete_term_meta( $term_id, Calendar_Grid::COLOR_META );
|
||||
} elseif ( $color = sanitize_hex_color( $input ) ) {
|
||||
update_term_meta( $term_id, Calendar_Grid::COLOR_META, $color );
|
||||
}
|
||||
}
|
||||
|
||||
public static function options(): array {
|
||||
return (array) get_option( self::OPTION, [] ) + [
|
||||
'view' => 'list', 'per_page' => 12, 'timezone' => wp_timezone_string(),
|
||||
'venue' => 0, 'organizer' => 0, 'anonymous' => false, 'community_edit' => true,
|
||||
'maps' => false, 'fields' => [], 'definitions' => '',
|
||||
];
|
||||
}
|
||||
|
||||
public static function menu(): void {
|
||||
add_submenu_page( 'edit.php?post_type=' . Events::EVENT, __( 'eventLabs Settings', 'burn-events' ), __( 'Settings', 'burn-events' ), 'manage_options', 'burn-events-settings', [ self::class, 'settings_page' ] );
|
||||
add_submenu_page( 'edit.php?post_type=' . Events::EVENT, __( 'Import and Export Events', 'burn-events' ), __( 'Import and Export', 'burn-events' ), 'manage_options', 'burn-events-transfer', [ Transfer::class, 'admin_page' ] );
|
||||
}
|
||||
|
||||
public static function settings(): void {
|
||||
register_setting( 'burn_events', self::OPTION, [ 'sanitize_callback' => [ self::class, 'sanitize_options' ] ] );
|
||||
Maps::register_setting();
|
||||
}
|
||||
|
||||
public static function sanitize_options( $input ): array {
|
||||
$input = (array) $input;
|
||||
$view = sanitize_key( $input['view'] ?? 'list' );
|
||||
$zone = sanitize_text_field( $input['timezone'] ?? '' );
|
||||
try {
|
||||
$timezone = ( new DateTimeZone( $zone ) )->getName();
|
||||
} catch ( \Exception $error ) {
|
||||
$timezone = wp_timezone_string();
|
||||
add_settings_error( self::OPTION, 'timezone', __( 'The time zone was reset to the WordPress site time zone.', 'burn-events' ) );
|
||||
}
|
||||
$fields = [];
|
||||
$definitions = sanitize_textarea_field( $input['definitions'] ?? '' );
|
||||
foreach ( preg_split( '/\R/', $definitions, -1, PREG_SPLIT_NO_EMPTY ) as $line ) {
|
||||
[ $key, $label, $type, $choices ] = array_pad( explode( '|', $line, 4 ), 4, '' );
|
||||
$key = sanitize_key( trim( $key ) );
|
||||
$label = sanitize_text_field( trim( $label ) );
|
||||
$type = sanitize_key( trim( $type ) );
|
||||
if ( $key && $label && in_array( $type, [ 'text', 'url', 'checkbox', 'select' ], true ) ) {
|
||||
$fields[ $key ] = [ 'label' => $label, 'type' => $type, 'choices' => array_values( array_filter( array_map( 'sanitize_text_field', explode( ',', $choices ) ) ) ) ];
|
||||
}
|
||||
}
|
||||
return [
|
||||
'view' => in_array( $view, Calendar::VIEWS, true ) ? $view : 'list',
|
||||
'per_page' => max( 1, min( 50, absint( $input['per_page'] ?? 12 ) ) ),
|
||||
'timezone' => $timezone,
|
||||
'venue' => absint( $input['venue'] ?? 0 ),
|
||||
'organizer' => absint( $input['organizer'] ?? 0 ),
|
||||
'anonymous' => ! empty( $input['anonymous'] ),
|
||||
'community_edit' => ! empty( $input['community_edit'] ),
|
||||
'maps' => ! empty( $input['maps'] ),
|
||||
'definitions' => $definitions,
|
||||
'fields' => $fields,
|
||||
];
|
||||
}
|
||||
|
||||
public static function settings_page(): void {
|
||||
$options = self::options();
|
||||
?>
|
||||
<div class="wrap">
|
||||
<h1><?php esc_html_e( 'eventLabs Settings', 'burn-events' ); ?></h1>
|
||||
<p><a href="<?php echo esc_url( Calendar::archive_url() ); ?>"><?php esc_html_e( 'View calendar', 'burn-events' ); ?></a> · <a href="<?php echo esc_url( Community::url( 'submit' ) ); ?>"><?php esc_html_e( 'View submission form', 'burn-events' ); ?></a></p>
|
||||
<?php settings_errors(); ?>
|
||||
<form action="options.php" method="post">
|
||||
<?php settings_fields( 'burn_events' ); ?>
|
||||
<table class="form-table" role="presentation">
|
||||
<tr><th scope="row"><label for="be-view"><?php esc_html_e( 'Default calendar view', 'burn-events' ); ?></label></th><td><select id="be-view" name="burn_events_settings[view]"><?php foreach ( Calendar::view_labels() as $id => $label ) : ?><option value="<?php echo esc_attr( $id ); ?>" <?php selected( $options['view'], $id ); ?>><?php echo esc_html( $label ); ?></option><?php endforeach; ?></select></td></tr>
|
||||
<tr><th scope="row"><label for="be-per-page"><?php esc_html_e( 'Events per page', 'burn-events' ); ?></label></th><td><input id="be-per-page" name="burn_events_settings[per_page]" type="number" min="1" max="50" value="<?php echo esc_attr( (string) $options['per_page'] ); ?>"></td></tr>
|
||||
<tr><th scope="row"><label for="be-timezone"><?php esc_html_e( 'Default time zone', 'burn-events' ); ?></label></th><td><input id="be-timezone" name="burn_events_settings[timezone]" class="regular-text" value="<?php echo esc_attr( $options['timezone'] ); ?>"><p class="description"><?php esc_html_e( 'Use a time zone such as America/New_York.', 'burn-events' ); ?></p></td></tr>
|
||||
<?php foreach ( [ 'venue' => Events::VENUE, 'organizer' => Events::ORGANIZER ] as $name => $type ) : ?>
|
||||
<tr><th scope="row"><label for="be-default-<?php echo esc_attr( $name ); ?>"><?php echo esc_html( 'venue' === $name ? __( 'Default venue', 'burn-events' ) : __( 'Default organizer', 'burn-events' ) ); ?></label></th><td><?php self::relation_select( "burn_events_settings[$name]", $type, [ $options[ $name ] ], false, 'be-default-' . $name ); ?></td></tr>
|
||||
<?php endforeach; ?>
|
||||
<tr><th scope="row"><?php esc_html_e( 'Community submissions', 'burn-events' ); ?></th><td>
|
||||
<label><input name="burn_events_settings[anonymous]" type="checkbox" value="1" <?php checked( $options['anonymous'] ); ?>> <?php esc_html_e( 'Allow submissions from guests', 'burn-events' ); ?></label><br>
|
||||
<label><input name="burn_events_settings[community_edit]" type="checkbox" value="1" <?php checked( $options['community_edit'] ); ?>> <?php esc_html_e( 'Let contributors edit their own submissions', 'burn-events' ); ?></label>
|
||||
<p class="description"><?php esc_html_e( 'New submissions and edits go to Pending Review.', 'burn-events' ); ?></p>
|
||||
</td></tr>
|
||||
<tr>
|
||||
<th scope="row"><label for="be-maps-key"><?php esc_html_e( 'Maps API key', 'burn-events' ); ?></label></th>
|
||||
<td>
|
||||
<input id="be-maps-key" name="<?php echo esc_attr( Maps::KEY_OPTION ); ?>" class="regular-text" type="password" autocomplete="new-password" placeholder="<?php echo Maps::has_key() ? esc_attr__( 'Key saved', 'burn-events' ) : ''; ?>">
|
||||
<p class="description"><?php esc_html_e( 'Use a Geoapify key. When you save a venue or organizer, its street address is sent to Geoapify to look up coordinates.', 'burn-events' ); ?></p>
|
||||
<?php if ( Maps::has_key() ) : ?><label><input name="burn_events_remove_maps_key" type="checkbox" value="1"> <?php esc_html_e( 'Remove saved key', 'burn-events' ); ?></label><br><?php endif; ?>
|
||||
<label><input name="burn_events_settings[maps]" type="checkbox" value="1" <?php checked( $options['maps'] ); ?>> <?php esc_html_e( 'Show OpenStreetMap maps for venues with coordinates', 'burn-events' ); ?></label>
|
||||
</td>
|
||||
</tr>
|
||||
<tr><th scope="row"><label for="be-fields"><?php esc_html_e( 'Custom event fields', 'burn-events' ); ?></label></th><td><textarea id="be-fields" class="large-text code" name="burn_events_settings[definitions]" rows="5"><?php echo esc_textarea( $options['definitions'] ); ?></textarea><p class="description"><?php esc_html_e( 'One field per line. Use key|Label|type. Types are text, url, checkbox, and select. Add |First,Second for select choices.', 'burn-events' ); ?></p></td></tr>
|
||||
</table>
|
||||
<?php submit_button(); ?>
|
||||
</form>
|
||||
</div>
|
||||
<?php
|
||||
}
|
||||
|
||||
public static function boxes(): void {
|
||||
add_meta_box( 'burn-event-details', __( 'Event Details', 'burn-events' ), [ self::class, 'event_box' ], Events::EVENT, 'normal', 'high' );
|
||||
add_meta_box( 'burn-location-details', __( 'Contact and Location', 'burn-events' ), [ self::class, 'location_box' ], [ Events::VENUE, Events::ORGANIZER ], 'normal', 'high' );
|
||||
}
|
||||
|
||||
public static function event_box( WP_Post $post ): void {
|
||||
wp_nonce_field( 'burn_event_details', 'burn_event_nonce' );
|
||||
$data = Events::event_data( $post->ID );
|
||||
$data['imported_schedule'] = Events::uses_imported_dates( $post->ID );
|
||||
if ( ! $data['schedule'] ) {
|
||||
$options = self::options();
|
||||
$data['venue'] = array_filter( [ $options['venue'] ] );
|
||||
$data['organizer'] = array_filter( [ $options['organizer'] ] );
|
||||
}
|
||||
self::event_fields( $data );
|
||||
}
|
||||
|
||||
public static function event_fields( array $data, bool $public = false ): void {
|
||||
$options = self::options();
|
||||
$start = new DateTimeImmutable( 'tomorrow', new DateTimeZone( $options['timezone'] ) );
|
||||
$rule = ( $data['schedule'] ?? [] ) + [
|
||||
'start_date' => $start->format( 'Y-m-d' ), 'end_date' => $start->format( 'Y-m-d' ), 'start_time' => '10:00', 'end_time' => '11:00',
|
||||
'timezone' => $options['timezone'], 'all_day' => false, 'repeat' => 'none', 'interval' => 1,
|
||||
'weekdays' => [], 'monthly' => 'day', 'until' => '', 'count' => 0, 'include' => [], 'exclude' => [],
|
||||
];
|
||||
if ( ! $public ) {
|
||||
self::editor_fields( $data, $rule, $options['fields'] );
|
||||
return;
|
||||
}
|
||||
?>
|
||||
<div class="be-fields">
|
||||
<?php self::schedule_fields( $rule ); ?>
|
||||
<label><input type="checkbox" name="be[all_day]" value="1" <?php checked( $rule['all_day'] ); ?>> <?php esc_html_e( 'All day', 'burn-events' ); ?></label>
|
||||
</div>
|
||||
<?php self::recurrence_fields( $rule ); ?>
|
||||
<div class="be-fields">
|
||||
<?php
|
||||
self::input_field( 'location', __( 'Location name or address', 'burn-events' ), $data['location'] ?? '' );
|
||||
self::input_field( 'cost', __( 'Cost', 'burn-events' ), $data['cost'] ?? '' );
|
||||
self::input_field( 'url', __( 'Event website', 'burn-events' ), $data['url'] ?? '', 'url' );
|
||||
foreach ( [ 'venue' => Events::VENUE, 'organizer' => Events::ORGANIZER ] as $name => $type ) :
|
||||
?>
|
||||
<label><?php echo esc_html( get_post_type_object( $type )->labels->name ); ?> <?php self::relation_select( "be[$name]", $type, $data[ $name ] ?? [], true ); ?></label>
|
||||
<?php endforeach; ?>
|
||||
<?php self::custom_field_controls( $options['fields'], $data['fields'] ?? [] ); ?>
|
||||
</div>
|
||||
<?php
|
||||
}
|
||||
|
||||
private static function editor_fields( array $data, array $rule, array $custom_fields ): void {
|
||||
?>
|
||||
<div class="be-event-editor" data-be-event-editor>
|
||||
<section class="be-editor-section be-editor-schedule">
|
||||
<header class="be-editor-heading">
|
||||
<h3><?php esc_html_e( 'Schedule', 'burn-events' ); ?></h3>
|
||||
<label class="be-editor-toggle"><input type="checkbox" name="be[all_day]" value="1" <?php checked( $rule['all_day'] ); ?>> <?php esc_html_e( 'All day', 'burn-events' ); ?></label>
|
||||
</header>
|
||||
<div class="be-editor-fields be-editor-dates"><?php self::schedule_fields( $rule ); ?></div>
|
||||
<?php if ( ! empty( $data['imported_schedule'] ) ) : ?>
|
||||
<p class="description"><?php esc_html_e( 'This event uses saved dates from the migration. Changing its schedule replaces those dates.', 'burn-events' ); ?></p>
|
||||
<?php endif; ?>
|
||||
</section>
|
||||
|
||||
<?php self::recurrence_fields( $rule, true ); ?>
|
||||
|
||||
<section class="be-editor-section">
|
||||
<header class="be-editor-heading"><h3><?php esc_html_e( 'Location and people', 'burn-events' ); ?></h3></header>
|
||||
<div class="be-editor-fields">
|
||||
<?php foreach ( Events::RELATIONS as $name => $type ) { self::relation_picker( "be[$name]", $type, $data[ $name ] ?? [] ); } ?>
|
||||
</div>
|
||||
<div class="be-editor-location">
|
||||
<?php self::input_field( 'location', __( 'Location name or address', 'burn-events' ), $data['location'] ?? '' ); ?>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="be-editor-section">
|
||||
<header class="be-editor-heading"><h3><?php esc_html_e( 'Event settings', 'burn-events' ); ?></h3></header>
|
||||
<div class="be-editor-fields">
|
||||
<?php self::input_field( 'cost', __( 'Cost', 'burn-events' ), $data['cost'] ?? '' ); ?>
|
||||
<?php self::input_field( 'url', __( 'Event website', 'burn-events' ), $data['url'] ?? '', 'url' ); ?>
|
||||
<label><?php esc_html_e( 'Event status', 'burn-events' ); ?>
|
||||
<select name="be[status]">
|
||||
<?php foreach ( Events::statuses() as $key => $label ) : ?>
|
||||
<option value="<?php echo esc_attr( $key ); ?>" <?php selected( $data['status'] ?? 'scheduled', $key ); ?>><?php echo esc_html( $label ); ?></option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
<div class="be-editor-visibility">
|
||||
<label class="be-editor-toggle"><input type="checkbox" name="be[featured]" value="1" <?php checked( $data['featured'] ?? false ); ?>> <?php esc_html_e( 'Featured event', 'burn-events' ); ?></label>
|
||||
<label class="be-editor-toggle"><input type="checkbox" name="be[hidden]" value="1" <?php checked( $data['hidden'] ?? false ); ?>> <?php esc_html_e( 'Hide from calendar listings', 'burn-events' ); ?></label>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<?php if ( $custom_fields ) : ?>
|
||||
<section class="be-editor-section">
|
||||
<header class="be-editor-heading"><h3><?php esc_html_e( 'Custom fields', 'burn-events' ); ?></h3></header>
|
||||
<div class="be-editor-fields"><?php self::custom_field_controls( $custom_fields, $data['fields'] ?? [] ); ?></div>
|
||||
</section>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
<?php
|
||||
}
|
||||
|
||||
private static function input_field( string $key, string $label, string $value, string $type = 'text' ): void {
|
||||
?>
|
||||
<label<?php if ( 'time' === $type ) : ?> data-be-time<?php elseif ( 'timezone' === $key ) : ?> class="be-editor-zone"<?php endif; ?>>
|
||||
<?php echo esc_html( $label ); ?>
|
||||
<input type="<?php echo esc_attr( $type ); ?>" <?php if ( 'time' === $type ) { echo 'step="1"'; } ?> name="be[<?php echo esc_attr( $key ); ?>]" value="<?php echo esc_attr( $value ); ?>">
|
||||
</label>
|
||||
<?php
|
||||
}
|
||||
|
||||
private static function schedule_fields( array $rule ): void {
|
||||
self::input_field( 'start_date', __( 'Start date', 'burn-events' ), $rule['start_date'], 'date' );
|
||||
self::input_field( 'start_time', __( 'Start time', 'burn-events' ), $rule['start_time'], 'time' );
|
||||
self::input_field( 'end_date', __( 'End date', 'burn-events' ), $rule['end_date'], 'date' );
|
||||
self::input_field( 'end_time', __( 'End time', 'burn-events' ), $rule['end_time'], 'time' );
|
||||
self::input_field( 'timezone', __( 'Time zone', 'burn-events' ), $rule['timezone'] );
|
||||
}
|
||||
|
||||
private static function recurrence_fields( array $rule, bool $editor = false ): void {
|
||||
global $wp_locale;
|
||||
$labels = [
|
||||
'none' => __( 'Does not repeat', 'burn-events' ), 'daily' => __( 'Daily', 'burn-events' ),
|
||||
'weekly' => __( 'Weekly', 'burn-events' ), 'monthly' => __( 'Monthly', 'burn-events' ), 'yearly' => __( 'Yearly', 'burn-events' ),
|
||||
];
|
||||
$open = 'none' !== $rule['repeat'] || ( $editor && ( $rule['include'] || $rule['exclude'] ) );
|
||||
?>
|
||||
<details class="be-recurrence<?php echo $editor ? ' be-editor-section be-editor-recurrence' : ''; ?>" <?php if ( $open ) { echo 'open'; } ?>>
|
||||
<summary>
|
||||
<span><?php esc_html_e( 'Recurrence', 'burn-events' ); ?></span>
|
||||
<?php if ( $editor ) : ?><span class="be-editor-frequency" data-be-frequency><?php echo esc_html( $labels[ $rule['repeat'] ] ?? $labels['none'] ); ?></span><?php endif; ?>
|
||||
</summary>
|
||||
<div class="be-editor-recurrence-body">
|
||||
<div class="be-fields be-editor-fields be-editor-repeat-fields">
|
||||
<label><?php esc_html_e( 'Repeat', 'burn-events' ); ?>
|
||||
<select name="be[repeat]">
|
||||
<?php foreach ( Schedule::REPEATS as $type ) : ?>
|
||||
<option value="<?php echo esc_attr( $type ); ?>" <?php selected( $type, $rule['repeat'] ); ?>><?php echo esc_html( $labels[ $type ] ?? ucfirst( $type ) ); ?></option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
</label>
|
||||
<label data-be-repeat="enabled"><?php esc_html_e( 'Repeat every', 'burn-events' ); ?><input type="number" min="1" max="365" name="be[interval]" value="<?php echo esc_attr( (string) $rule['interval'] ); ?>"></label>
|
||||
<label data-be-repeat="enabled"><?php esc_html_e( 'Repeat through', 'burn-events' ); ?><input type="date" name="be[until]" value="<?php echo esc_attr( $rule['until'] ); ?>"></label>
|
||||
<label data-be-repeat="enabled"><?php esc_html_e( 'Occurrence limit', 'burn-events' ); ?><input type="number" min="0" max="10000" name="be[count]" value="<?php echo esc_attr( (string) $rule['count'] ); ?>"></label>
|
||||
<label data-be-repeat="monthly"><?php esc_html_e( 'Monthly pattern', 'burn-events' ); ?>
|
||||
<select name="be[monthly]">
|
||||
<option value="day" <?php selected( $rule['monthly'], 'day' ); ?>><?php esc_html_e( 'Same day of month', 'burn-events' ); ?></option>
|
||||
<option value="weekday" <?php selected( $rule['monthly'], 'weekday' ); ?>><?php esc_html_e( 'Same weekday of month', 'burn-events' ); ?></option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
<fieldset class="be-editor-weekdays" data-be-repeat="weekly">
|
||||
<legend><?php esc_html_e( 'Days for weekly recurrence', 'burn-events' ); ?></legend>
|
||||
<div>
|
||||
<?php foreach ( array_keys( Schedule::WEEKDAYS ) as $day ) : ?>
|
||||
<?php $name = $wp_locale->get_weekday( $day % 7 ); ?>
|
||||
<label>
|
||||
<input type="checkbox" name="be[weekdays][]" value="<?php echo esc_attr( (string) $day ); ?>" <?php checked( in_array( $day, $rule['weekdays'], true ) ); ?>>
|
||||
<?php if ( $editor ) : ?>
|
||||
<span aria-hidden="true"><?php echo esc_html( $wp_locale->get_weekday_abbrev( $name ) ); ?></span><span class="screen-reader-text"><?php echo esc_html( $name ); ?></span>
|
||||
<?php else : ?>
|
||||
<?php echo esc_html( $name ); ?>
|
||||
<?php endif; ?>
|
||||
</label>
|
||||
<?php endforeach; ?>
|
||||
</div>
|
||||
</fieldset>
|
||||
<div class="be-fields be-editor-fields be-editor-exceptions">
|
||||
<?php foreach ( [ 'include' => __( 'Additional dates', 'burn-events' ), 'exclude' => __( 'Excluded dates', 'burn-events' ) ] as $key => $label ) : ?>
|
||||
<label><?php echo esc_html( $label ); ?>
|
||||
<input name="be[<?php echo esc_attr( $key ); ?>]" value="<?php echo esc_attr( implode( ', ', $rule[ $key ] ) ); ?>" placeholder="YYYY-MM-DD, YYYY-MM-DD">
|
||||
</label>
|
||||
<?php endforeach; ?>
|
||||
</div>
|
||||
<p class="description" data-be-repeat="enabled"><?php esc_html_e( 'Leave Repeat through blank and the occurrence limit at zero for no end. Weekly recurrence uses the start weekday when no days are selected.', 'burn-events' ); ?></p>
|
||||
</div>
|
||||
</details>
|
||||
<?php
|
||||
}
|
||||
|
||||
private static function custom_field_controls( array $fields, array $values ): void {
|
||||
foreach ( $fields as $key => $field ) :
|
||||
$value = $values[ $key ] ?? '';
|
||||
?>
|
||||
<label<?php if ( 'checkbox' === $field['type'] ) : ?> class="be-editor-toggle"<?php endif; ?>>
|
||||
<?php if ( 'select' === $field['type'] ) : ?>
|
||||
<?php echo esc_html( $field['label'] ); ?>
|
||||
<select name="be[fields][<?php echo esc_attr( $key ); ?>]">
|
||||
<option value=""><?php esc_html_e( 'Select', 'burn-events' ); ?></option>
|
||||
<?php foreach ( $field['choices'] as $choice ) : ?><option <?php selected( $value, $choice ); ?>><?php echo esc_html( $choice ); ?></option><?php endforeach; ?>
|
||||
</select>
|
||||
<?php elseif ( 'checkbox' === $field['type'] ) : ?>
|
||||
<input type="checkbox" name="be[fields][<?php echo esc_attr( $key ); ?>]" value="1" <?php checked( $value, '1' ); ?>> <?php echo esc_html( $field['label'] ); ?>
|
||||
<?php else : ?>
|
||||
<?php echo esc_html( $field['label'] ); ?>
|
||||
<input type="<?php echo esc_attr( $field['type'] ); ?>" name="be[fields][<?php echo esc_attr( $key ); ?>]" value="<?php echo esc_attr( $value ); ?>">
|
||||
<?php endif; ?>
|
||||
</label>
|
||||
<?php
|
||||
endforeach;
|
||||
}
|
||||
|
||||
private static function relation_posts( string $type ): array {
|
||||
return get_posts( [ 'post_type' => $type, 'post_status' => 'publish', 'has_password' => false, 'posts_per_page' => -1, 'orderby' => 'title', 'order' => 'ASC' ] );
|
||||
}
|
||||
|
||||
private static function relation_picker( string $name, string $type, array $selected ): void {
|
||||
$posts = self::relation_posts( $type );
|
||||
$selected = array_map( 'intval', $selected );
|
||||
$choices = array_map( static fn( WP_Post $post ): string => get_the_title( $post ), $posts );
|
||||
$chosen = [];
|
||||
foreach ( $posts as $index => $post ) {
|
||||
if ( in_array( $post->ID, $selected, true ) ) {
|
||||
$chosen[] = $choices[ $index ];
|
||||
}
|
||||
}
|
||||
$placeholder = __( 'None selected', 'burn-events' );
|
||||
?>
|
||||
<fieldset class="be-editor-picker" data-be-picker>
|
||||
<legend><?php echo esc_html( get_post_type_object( $type )->labels->name ); ?></legend>
|
||||
<?php if ( $posts ) : ?>
|
||||
<details>
|
||||
<summary><span data-be-picker-selection data-be-empty="<?php echo esc_attr( $placeholder ); ?>"><?php echo esc_html( $chosen ? implode( ', ', $chosen ) : $placeholder ); ?></span></summary>
|
||||
<div class="be-editor-picker-body">
|
||||
<?php if ( count( $posts ) > 8 ) : ?>
|
||||
<label><span class="screen-reader-text"><?php esc_html_e( 'Filter options', 'burn-events' ); ?></span><input type="search" data-be-picker-search placeholder="<?php esc_attr_e( 'Filter options', 'burn-events' ); ?>"></label>
|
||||
<?php endif; ?>
|
||||
<div class="be-editor-picker-options">
|
||||
<?php foreach ( $posts as $index => $post ) : ?>
|
||||
<label data-be-picker-option>
|
||||
<input type="checkbox" name="<?php echo esc_attr( $name . '[]' ); ?>" value="<?php echo esc_attr( (string) $post->ID ); ?>" <?php checked( in_array( $post->ID, $selected, true ) ); ?>>
|
||||
<span><?php echo esc_html( $choices[ $index ] ); ?></span>
|
||||
</label>
|
||||
<?php endforeach; ?>
|
||||
<p class="be-editor-no-matches" data-be-no-options hidden><?php esc_html_e( 'No matching options.', 'burn-events' ); ?></p>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
<?php else : ?>
|
||||
<div class="be-editor-picker-empty"><?php esc_html_e( 'None available', 'burn-events' ); ?></div>
|
||||
<?php endif; ?>
|
||||
</fieldset>
|
||||
<?php
|
||||
}
|
||||
|
||||
private static function relation_select( string $name, string $type, array $selected, bool $multiple, string $id = '' ): void {
|
||||
$posts = self::relation_posts( $type );
|
||||
?>
|
||||
<select <?php if ( $id ) { echo 'id="' . esc_attr( $id ) . '"'; } ?> name="<?php echo esc_attr( $name . ( $multiple ? '[]' : '' ) ); ?>" <?php if ( $multiple ) { echo 'multiple size="3"'; } ?>>
|
||||
<?php if ( ! $multiple ) : ?><option value="0"><?php esc_html_e( 'None', 'burn-events' ); ?></option><?php endif; ?>
|
||||
<?php foreach ( $posts as $post ) : ?><option value="<?php echo esc_attr( (string) $post->ID ); ?>" <?php selected( in_array( $post->ID, $selected, true ) ); ?>><?php echo esc_html( get_the_title( $post ) ); ?></option><?php endforeach; ?>
|
||||
</select>
|
||||
<?php
|
||||
}
|
||||
|
||||
public static function save_event( int $id ): void {
|
||||
if ( ! self::valid_save( $id, 'burn_event_nonce', 'burn_event_details' ) || ! is_array( $_POST['be'] ?? null ) ) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
Events::save( $id, Events::validate_event( wp_unslash( $_POST['be'] ) ) );
|
||||
} catch ( \Throwable $error ) {
|
||||
set_transient( 'burn_events_error_' . get_current_user_id(), $error->getMessage(), MINUTE_IN_SECONDS );
|
||||
}
|
||||
}
|
||||
|
||||
public static function location_box( WP_Post $post ): void {
|
||||
wp_nonce_field( 'burn_location_details', 'burn_location_nonce' );
|
||||
$data = Events::location_data( $post->ID );
|
||||
$labels = [
|
||||
'address' => __( 'Street address', 'burn-events' ), 'city' => __( 'City', 'burn-events' ),
|
||||
'region' => __( 'State or region', 'burn-events' ), 'postal' => __( 'Postal code', 'burn-events' ),
|
||||
'country' => __( 'Country', 'burn-events' ), 'website' => __( 'Website', 'burn-events' ),
|
||||
'email' => __( 'Email', 'burn-events' ), 'phone' => __( 'Phone', 'burn-events' ),
|
||||
];
|
||||
foreach ( $labels as $key => $label ) {
|
||||
echo '<p><label>' . esc_html( $label ) . ' <input class="regular-text" name="be_location[' . esc_attr( $key ) . ']" value="' . esc_attr( $data[ $key ] ) . '"></label></p>';
|
||||
}
|
||||
echo '<p><strong>' . esc_html__( 'Address lookup', 'burn-events' ) . '</strong> ' . esc_html( Maps::lookup_message( $data ) ) . '</p>';
|
||||
if ( '' !== $data['latitude'] && '' !== $data['longitude'] ) {
|
||||
echo '<p>' . esc_html( $data['latitude'] . ', ' . $data['longitude'] ) . '</p>';
|
||||
Maps::attribution( $data );
|
||||
}
|
||||
if ( Maps::has_key() && Maps::address( $data ) ) {
|
||||
echo '<p><label><input type="checkbox" name="be_lookup_address" value="1"> ' . esc_html__( 'Look up this address again on save', 'burn-events' ) . '</label></p>';
|
||||
}
|
||||
}
|
||||
|
||||
public static function save_location( int $id ): void {
|
||||
if ( ! self::valid_save( $id, 'burn_location_nonce', 'burn_location_details' ) || ! is_array( $_POST['be_location'] ?? null ) ) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
Events::save_location( $id, wp_unslash( $_POST['be_location'] ), ! empty( $_POST['be_lookup_address'] ) );
|
||||
} catch ( \Throwable $error ) {
|
||||
set_transient( 'burn_events_error_' . get_current_user_id(), $error->getMessage(), MINUTE_IN_SECONDS );
|
||||
}
|
||||
}
|
||||
|
||||
private static function valid_save( int $id, string $key, string $action ): bool {
|
||||
return ! wp_is_post_autosave( $id ) && ! wp_is_post_revision( $id ) && current_user_can( 'edit_post', $id )
|
||||
&& isset( $_POST[ $key ] ) && is_string( $_POST[ $key ] ) && wp_verify_nonce( wp_unslash( $_POST[ $key ] ), $action );
|
||||
}
|
||||
|
||||
public static function errors(): void {
|
||||
$key = 'burn_events_error_' . get_current_user_id();
|
||||
$error = get_transient( $key );
|
||||
if ( $error ) {
|
||||
delete_transient( $key );
|
||||
echo '<div class="notice notice-error"><p>' . esc_html( $error ) . '</p></div>';
|
||||
}
|
||||
}
|
||||
|
||||
public static function columns( array $columns ): array {
|
||||
$columns['burn_event_schedule'] = __( 'Schedule', 'burn-events' );
|
||||
return $columns;
|
||||
}
|
||||
|
||||
public static function column( string $name, int $id ): void {
|
||||
if ( 'burn_event_schedule' === $name ) {
|
||||
$data = Events::event_data( $id );
|
||||
$row = Events::occurrence( $id );
|
||||
echo $row ? esc_html( Calendar::period( $row, $data ) ) : esc_html__( 'Unscheduled', 'burn-events' );
|
||||
if ( $data['schedule'] && 'none' !== $data['schedule']['repeat'] ) {
|
||||
echo '<br>' . esc_html__( 'Recurring', 'burn-events' );
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
560
includes/class-api.php
Normal file
560
includes/class-api.php
Normal file
@@ -0,0 +1,560 @@
|
||||
<?php
|
||||
|
||||
namespace BurnEvents;
|
||||
|
||||
use InvalidArgumentException;
|
||||
use RuntimeException;
|
||||
use WP_Error;
|
||||
use WP_Post;
|
||||
use WP_REST_Request;
|
||||
use WP_REST_Response;
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
final class Api {
|
||||
public const NAMESPACE = 'eventlabs/v1';
|
||||
public const CAPABILITY = 'eventlabs_sync';
|
||||
private const RESOURCES = [
|
||||
'events' => Events::EVENT, 'venues' => Events::VENUE, 'organizers' => Events::ORGANIZER, 'series' => Events::SERIES,
|
||||
];
|
||||
private const POST_FIELDS = [
|
||||
'title' => 'post_title', 'description' => 'post_content', 'excerpt' => 'post_excerpt',
|
||||
'slug' => 'post_name', 'post_status' => 'post_status',
|
||||
];
|
||||
private const EVENT_FIELDS = [ 'status', 'venue', 'organizer', 'series', 'location', 'cost', 'url', 'featured', 'hidden', 'fields' ];
|
||||
private const TAXONOMIES = [ 'categories' => Events::CATEGORY, 'tags' => 'post_tag' ];
|
||||
private const METADATA = '_eventlabs_metadata';
|
||||
|
||||
public static function install(): void {
|
||||
if ( '1' === get_option( 'eventlabs_api_schema' ) ) {
|
||||
return;
|
||||
}
|
||||
global $wpdb;
|
||||
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
|
||||
$table = self::table();
|
||||
$collation = $wpdb->get_charset_collate();
|
||||
dbDelta( "CREATE TABLE $table (
|
||||
sync_key char(64) NOT NULL,
|
||||
post_id bigint unsigned NOT NULL,
|
||||
source varchar(40) NOT NULL,
|
||||
external_id varchar(160) NOT NULL,
|
||||
PRIMARY KEY (sync_key),
|
||||
UNIQUE KEY post_id (post_id)
|
||||
) ENGINE=InnoDB $collation;" );
|
||||
if ( $table === $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->esc_like( $table ) ) ) ) {
|
||||
add_role( 'eventlabs_connector', __( 'eventLabs Integration', 'burn-events' ), [ 'read' => true, self::CAPABILITY => true ] );
|
||||
update_option( 'eventlabs_api_schema', '1' );
|
||||
}
|
||||
}
|
||||
|
||||
private static function table(): string {
|
||||
global $wpdb;
|
||||
return $wpdb->prefix . 'eventlabs_external_ids';
|
||||
}
|
||||
|
||||
public static function register(): void {
|
||||
$resource = '/(?P<resource>events|venues|organizers|series)';
|
||||
register_rest_route( self::NAMESPACE, $resource, [
|
||||
self::route( 'GET', 'listing' ),
|
||||
self::route( 'POST', 'create' ),
|
||||
] );
|
||||
register_rest_route( self::NAMESPACE, $resource . '/(?P<id>[1-9][0-9]*)', [
|
||||
self::route( 'GET', 'read' ),
|
||||
self::route( 'PATCH', 'update' ),
|
||||
] );
|
||||
register_rest_route( self::NAMESPACE, $resource . '/external/(?P<source>[a-z0-9_-]{1,40})/(?P<external_id>[A-Za-z0-9_.:-]{1,160})', [
|
||||
self::route( 'GET', 'read_external' ),
|
||||
self::route( 'PUT', 'put_external' ),
|
||||
] );
|
||||
register_rest_route( self::NAMESPACE, '/schema', self::route( 'GET', 'describe' ) );
|
||||
register_rest_route( self::NAMESPACE, '/(?P<taxonomy>categories|tags)', self::route( 'GET', 'terms' ) );
|
||||
register_rest_route( self::NAMESPACE, '/events/(?P<id>[1-9][0-9]*)/occurrences', self::route( 'GET', 'occurrences' ) );
|
||||
}
|
||||
|
||||
private static function route( string $method, string $callback ): array {
|
||||
return [
|
||||
'methods' => $method, 'callback' => [ self::class, $callback ],
|
||||
'permission_callback' => [ self::class, 'permission' ],
|
||||
];
|
||||
}
|
||||
|
||||
public static function permission() {
|
||||
if ( current_user_can( 'manage_options' ) || current_user_can( self::CAPABILITY ) ) {
|
||||
return true;
|
||||
}
|
||||
return self::error( 'access_denied', __( 'An authorized eventLabs account is required.', 'burn-events' ), rest_authorization_required_code() );
|
||||
}
|
||||
|
||||
public static function error( string $code, string $message, int $status ): WP_Error {
|
||||
return new WP_Error( 'eventlabs_' . $code, $message, [ 'status' => $status ] );
|
||||
}
|
||||
|
||||
private static function resource( WP_REST_Request $request ): string {
|
||||
return strtolower( $request->get_url_params()['resource'] );
|
||||
}
|
||||
|
||||
public static function response( array $body, int $status = 200, string $revision = '' ): WP_REST_Response {
|
||||
$response = new WP_REST_Response( $body, $status );
|
||||
$response->header( 'Cache-Control', 'private, no-store' );
|
||||
if ( $revision ) {
|
||||
$response->header( 'ETag', '"' . $revision . '"' );
|
||||
}
|
||||
return $response;
|
||||
}
|
||||
|
||||
public static function listing( WP_REST_Request $request ) {
|
||||
$resource = self::resource( $request );
|
||||
$limit = self::limit( $request );
|
||||
$after = absint( $request->get_param( 'after_id' ) );
|
||||
$since = $request->get_param( 'modified_since' );
|
||||
$args = [
|
||||
'post_type' => self::RESOURCES[ $resource ], 'post_status' => [ 'publish', 'draft', 'pending', 'private', 'future', 'trash' ],
|
||||
'orderby' => 'ID', 'order' => 'ASC', 'posts_per_page' => $limit + 1, 'no_found_rows' => true,
|
||||
'eventlabs_after_id' => $after,
|
||||
];
|
||||
if ( null !== $since ) {
|
||||
$parsed = is_string( $since ) ? rest_parse_date( $since ) : false;
|
||||
if ( false === $parsed ) {
|
||||
return self::error( 'modified_since', __( 'Use an ISO 8601 date and time for modified_since.', 'burn-events' ), 400 );
|
||||
}
|
||||
$args['date_query'] = [ [
|
||||
'after' => gmdate( 'Y-m-d H:i:s', $parsed ), 'column' => 'post_modified_gmt', 'inclusive' => true,
|
||||
] ];
|
||||
}
|
||||
$where = static function ( string $where, \WP_Query $query ): string {
|
||||
global $wpdb;
|
||||
$after = (int) $query->get( 'eventlabs_after_id' );
|
||||
return $after ? $where . $wpdb->prepare( " AND $wpdb->posts.ID > %d", $after ) : $where;
|
||||
};
|
||||
add_filter( 'posts_where', $where, 10, 2 );
|
||||
try {
|
||||
$query = new \WP_Query( $args );
|
||||
} finally {
|
||||
remove_filter( 'posts_where', $where, 10 );
|
||||
}
|
||||
$posts = array_slice( $query->posts, 0, $limit );
|
||||
return self::response( [
|
||||
'items' => array_map( static fn( WP_Post $post ): array => self::record( $post, $resource ), $posts ),
|
||||
'next_after_id' => count( $query->posts ) > $limit ? end( $posts )->ID : null,
|
||||
] );
|
||||
}
|
||||
|
||||
public static function read( WP_REST_Request $request ) {
|
||||
$resource = self::resource( $request );
|
||||
$post = self::post( $resource, (int) $request->get_url_params()['id'] );
|
||||
return $post ? self::record_response( self::record( $post, $resource ) ) : self::missing();
|
||||
}
|
||||
|
||||
public static function read_external( WP_REST_Request $request ) {
|
||||
$identity = $request->get_url_params();
|
||||
return self::external( self::resource( $request ), strtolower( $identity['source'] ), $identity['external_id'] );
|
||||
}
|
||||
|
||||
public static function external( string $resource, string $source, string $external_id ) {
|
||||
$id = self::external_id( self::sync_key( $resource, $source, $external_id ) );
|
||||
if ( ! $id ) {
|
||||
return self::missing();
|
||||
}
|
||||
$post = self::post( $resource, $id );
|
||||
return $post ? self::record_response( self::record( $post, $resource ) ) : self::missing( true );
|
||||
}
|
||||
|
||||
private static function post( string $resource, int $id ): ?WP_Post {
|
||||
$post = $id ? get_post( $id ) : null;
|
||||
return $post && self::RESOURCES[ $resource ] === $post->post_type && ! in_array( $post->post_status, [ 'inherit', 'auto-draft' ], true ) ? $post : null;
|
||||
}
|
||||
|
||||
private static function missing( bool $removed = false ): WP_Error {
|
||||
return $removed
|
||||
? self::error( 'removed', __( 'The record for this external ID was permanently deleted.', 'burn-events' ), 410 )
|
||||
: self::error( 'not_found', __( 'The eventLabs record was not found.', 'burn-events' ), 404 );
|
||||
}
|
||||
|
||||
private static function limit( WP_REST_Request $request ): int {
|
||||
return max( 1, min( 100, absint( $request->get_param( 'limit' ) ?? 50 ) ) );
|
||||
}
|
||||
|
||||
private static function record_response( array $record, int $status = 200 ): WP_REST_Response {
|
||||
return self::response( $record, $status, $record['revision'] );
|
||||
}
|
||||
|
||||
private static function record( WP_Post $post, string $resource ): array {
|
||||
global $wpdb;
|
||||
$id = $post->ID;
|
||||
$table = self::table();
|
||||
$external = $wpdb->get_row( $wpdb->prepare( "SELECT source, external_id AS id FROM $table WHERE post_id = %d", $id ), ARRAY_A );
|
||||
$record = [
|
||||
'id' => $id, 'resource' => $resource, 'external' => $external ?: null,
|
||||
'title' => $post->post_title, 'description' => $post->post_content, 'excerpt' => $post->post_excerpt,
|
||||
'slug' => $post->post_name, 'post_status' => $post->post_status,
|
||||
'featured_media' => (int) get_post_thumbnail_id( $id ), 'author_id' => (int) $post->post_author,
|
||||
'password_protected' => '' !== $post->post_password,
|
||||
'created_gmt' => self::utc( $post->post_date_gmt ), 'modified_gmt' => self::utc( $post->post_modified_gmt ),
|
||||
'url_public' => 'publish' === $post->post_status && ! $post->post_password ? get_permalink( $post ) : null,
|
||||
'metadata' => json_decode( (string) get_post_meta( $id, self::METADATA, true ) ) ?? new \stdClass(),
|
||||
];
|
||||
|
||||
if ( 'events' === $resource ) {
|
||||
$event = Events::event_data( $id );
|
||||
$event['schedule'] = $event['schedule'] ?: null;
|
||||
$event['fields'] = (object) $event['fields'];
|
||||
foreach ( Admin::options()['fields'] as $key => $definition ) {
|
||||
if ( 'checkbox' === $definition['type'] && isset( $event['fields']->$key ) ) {
|
||||
$event['fields']->$key = (bool) $event['fields']->$key;
|
||||
}
|
||||
}
|
||||
$record += $event;
|
||||
foreach ( self::TAXONOMIES as $field => $taxonomy ) {
|
||||
$terms = wp_get_object_terms( $id, $taxonomy, [ 'fields' => 'ids', 'orderby' => 'term_id' ] );
|
||||
$record[ $field ] = is_wp_error( $terms ) ? [] : array_map( 'intval', $terms );
|
||||
}
|
||||
$record['burnworks'] = BurnWorks::snapshot( $id ) ?: null;
|
||||
$record['sub_club'] = (string) get_post_meta( $id, Clubs::EVENT_META, true );
|
||||
$record['club'] = Clubs::event( $id );
|
||||
} elseif ( in_array( $resource, [ 'venues', 'organizers' ], true ) ) {
|
||||
$place = Events::location_data( $id );
|
||||
foreach ( [ 'latitude', 'longitude' ] as $coordinate ) {
|
||||
$place[ $coordinate ] = is_numeric( $place[ $coordinate ] ) ? (float) $place[ $coordinate ] : null;
|
||||
}
|
||||
$place['geocode'] = $place['geocode'] ?: null;
|
||||
$record += $place;
|
||||
}
|
||||
|
||||
$record['revision'] = hash( 'sha256', wp_json_encode( $record, JSON_PRESERVE_ZERO_FRACTION | JSON_INVALID_UTF8_SUBSTITUTE ) );
|
||||
return $record;
|
||||
}
|
||||
|
||||
private static function utc( string $date ): ?string {
|
||||
return '0000-00-00 00:00:00' === $date || '' === $date ? null : str_replace( ' ', 'T', $date ) . 'Z';
|
||||
}
|
||||
|
||||
public static function create( WP_REST_Request $request ) {
|
||||
return self::receive( $request );
|
||||
}
|
||||
|
||||
public static function update( WP_REST_Request $request ) {
|
||||
return self::receive( $request, (int) $request->get_url_params()['id'] );
|
||||
}
|
||||
|
||||
public static function put_external( WP_REST_Request $request ) {
|
||||
$identity = $request->get_url_params();
|
||||
$source = strtolower( $identity['source'] );
|
||||
if ( 'burnworks' === $source ) {
|
||||
return self::error( 'burnworks_route', __( 'Use the burnWorks publishing route for burnWorks event records.', 'burn-events' ), 400 );
|
||||
}
|
||||
if ( Legacy_Migration::SOURCE === $source ) {
|
||||
return self::error( 'migration_route', __( 'Use Import and Export in WordPress for legacy calendar migration.', 'burn-events' ), 400 );
|
||||
}
|
||||
return self::receive( $request, 0, [ $source, $identity['external_id'] ] );
|
||||
}
|
||||
|
||||
private static function receive( WP_REST_Request $request, int $id = 0, ?array $identity = null ) {
|
||||
$resource = self::resource( $request );
|
||||
$raw = json_decode( $request->get_body() );
|
||||
if ( ! $raw instanceof \stdClass || ! $request->is_json_content_type() ) {
|
||||
return self::error( 'invalid_json', __( 'Send a JSON object with Content-Type: application/json.', 'burn-events' ), 400 );
|
||||
}
|
||||
$schema = self::schema( $resource );
|
||||
$payload = $request->get_json_params();
|
||||
$valid = rest_validate_value_from_schema( $payload, $schema, 'body' );
|
||||
if ( is_wp_error( $valid ) ) {
|
||||
$valid->add_data( [ 'status' => 400 ] );
|
||||
return $valid;
|
||||
}
|
||||
$payload = rest_sanitize_value_from_schema( $payload, $schema, 'body' );
|
||||
if ( isset( $raw->metadata ) ) {
|
||||
if ( ! $raw->metadata instanceof \stdClass ) {
|
||||
return self::error( 'invalid_metadata', __( 'metadata must be a JSON object.', 'burn-events' ), 400 );
|
||||
}
|
||||
$payload['metadata'] = $raw->metadata;
|
||||
}
|
||||
return self::write( $resource, $payload, $request, $id, $identity );
|
||||
}
|
||||
|
||||
public static function write( string $resource, array $payload, WP_REST_Request $request, int $id = 0, ?array $identity = null, ?array $burnworks = null ) {
|
||||
global $wpdb;
|
||||
$sync_key = $identity ? self::sync_key( $resource, ...$identity ) : '';
|
||||
$lock = $sync_key ? 'el-' . substr( $sync_key, 0, 60 ) : '';
|
||||
if ( $lock && '1' !== (string) $wpdb->get_var( $wpdb->prepare( 'SELECT GET_LOCK(%s, 5)', $lock ) ) ) {
|
||||
return self::error( 'record_busy', __( 'This record is being updated. Retry the request.', 'burn-events' ), 503 );
|
||||
}
|
||||
$saved_id = 0;
|
||||
try {
|
||||
return Events::transaction( static function () use ( $resource, $payload, $request, $id, $identity, $sync_key, $burnworks, &$saved_id ) {
|
||||
global $wpdb;
|
||||
$id = $sync_key ? self::external_id( $sync_key ) : $id;
|
||||
if ( $id && ! Events::lock_post( $id ) ) {
|
||||
return self::missing( (bool) $identity );
|
||||
}
|
||||
$post = self::post( $resource, $id );
|
||||
if ( $id && ! $post ) {
|
||||
return self::missing( (bool) $identity );
|
||||
}
|
||||
if ( $post && '*' === $request->get_header( 'if-none-match' ) ) {
|
||||
return self::error( 'already_exists', __( 'The external record has already been created.', 'burn-events' ), 412 );
|
||||
}
|
||||
$if_match = $request->get_header( 'if-match' );
|
||||
if ( $if_match && ( ! $post || ( '*' !== $if_match && '"' . self::record( $post, $resource )['revision'] . '"' !== $if_match ) ) ) {
|
||||
return self::error( 'stale_revision', __( 'The record changed. Fetch it again before saving.', 'burn-events' ), 412 );
|
||||
}
|
||||
if ( $burnworks && $post && ! BurnWorks::accepts_version( $burnworks, BurnWorks::snapshot( $id ) ) ) {
|
||||
return self::error( 'stale_source_version', __( 'A newer or different version of this burnWorks record has been saved.', 'burn-events' ), 409 );
|
||||
}
|
||||
$blocked = apply_filters( 'eventlabs_api_validate_write', null, $resource, $payload, $post, $request );
|
||||
if ( is_wp_error( $blocked ) ) {
|
||||
return $blocked;
|
||||
}
|
||||
$saved_id = $id;
|
||||
$result = self::persist( $resource, $payload, $post, $burnworks, $saved_id );
|
||||
if ( is_wp_error( $result ) ) {
|
||||
return $result;
|
||||
}
|
||||
if ( $identity && ! $id && ! $wpdb->insert( self::table(), [
|
||||
'sync_key' => $sync_key, 'post_id' => $saved_id, 'source' => $identity[0], 'external_id' => $identity[1],
|
||||
], [ '%s', '%d', '%s', '%s' ] ) ) {
|
||||
throw new RuntimeException( 'External ID write failed.' );
|
||||
}
|
||||
return self::record_response( self::record( get_post( $saved_id ), $resource ), $id ? 200 : 201 );
|
||||
} );
|
||||
} catch ( InvalidArgumentException $error ) {
|
||||
return self::error( 'invalid_record', $error->getMessage(), 422 );
|
||||
} catch ( \Throwable $error ) {
|
||||
return self::error( 'write_failed', __( 'The eventLabs record could not be saved.', 'burn-events' ), 500 );
|
||||
} finally {
|
||||
if ( $saved_id ) {
|
||||
wp_cache_delete( $saved_id, 'posts' );
|
||||
wp_cache_delete( $saved_id, 'post_meta' );
|
||||
clean_object_term_cache( $saved_id, self::RESOURCES[ $resource ] );
|
||||
}
|
||||
if ( $lock ) {
|
||||
$wpdb->get_var( $wpdb->prepare( 'SELECT RELEASE_LOCK(%s)', $lock ) );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static function persist( string $resource, array $payload, ?WP_Post $post, ?array $burnworks, int &$saved_id ) {
|
||||
$id = $post->ID ?? 0;
|
||||
$title = sanitize_text_field( $payload['title'] ?? ( $post->post_title ?? '' ) );
|
||||
if ( '' === $title ) {
|
||||
throw new InvalidArgumentException( __( 'A title is required.', 'burn-events' ) );
|
||||
}
|
||||
$attributes = [ 'post_type' => self::RESOURCES[ $resource ] ];
|
||||
if ( ! $id ) {
|
||||
$attributes += [ 'post_title' => $title, 'post_status' => 'draft', 'comment_status' => 'closed' ];
|
||||
}
|
||||
foreach ( self::POST_FIELDS as $field => $column ) {
|
||||
if ( array_key_exists( $field, $payload ) ) {
|
||||
$attributes[ $column ] = match ( $field ) {
|
||||
'title' => $title,
|
||||
'description', 'excerpt' => str_replace( '[', '[', wp_kses_post( $payload[ $field ] ) ),
|
||||
default => $payload[ $field ],
|
||||
};
|
||||
}
|
||||
}
|
||||
$source = $burnworks ? wp_json_encode( $burnworks, JSON_PRESERVE_ZERO_FRACTION | JSON_THROW_ON_ERROR ) : null;
|
||||
if ( null !== $source ) {
|
||||
if ( $id ) {
|
||||
Events::write_meta( $id, BurnWorks::META, $source );
|
||||
} else {
|
||||
$attributes['meta_input'] = [ BurnWorks::META => $source ];
|
||||
}
|
||||
}
|
||||
$model = 'events' === $resource ? self::event_model( $id, $payload ) : null;
|
||||
$terms = self::validate_links( $payload, self::TAXONOMIES, true );
|
||||
$media = $payload['featured_media'] ?? null;
|
||||
if ( $media && ! wp_attachment_is_image( $media ) ) {
|
||||
throw new InvalidArgumentException( __( 'featured_media must refer to a WordPress image attachment.', 'burn-events' ) );
|
||||
}
|
||||
|
||||
$result = $id ? wp_update_post( wp_slash( $attributes + [ 'ID' => $id ] ), true ) : wp_insert_post( wp_slash( $attributes ), true );
|
||||
if ( is_wp_error( $result ) || ! $result ) {
|
||||
return self::error( 'post_write', __( 'WordPress could not save the record.', 'burn-events' ), 500 );
|
||||
}
|
||||
$saved_id = $result;
|
||||
if ( ! $id && null !== $source ) {
|
||||
Events::write_meta( $result, BurnWorks::META, $source );
|
||||
}
|
||||
if ( null !== $media ) {
|
||||
if ( $media ) {
|
||||
Events::write_meta( $result, '_thumbnail_id', (string) $media );
|
||||
} else {
|
||||
delete_post_thumbnail( $result );
|
||||
}
|
||||
}
|
||||
if ( array_key_exists( 'metadata', $payload ) ) {
|
||||
Events::write_meta( $result, self::METADATA, wp_json_encode( (object) $payload['metadata'], JSON_PRESERVE_ZERO_FRACTION ) );
|
||||
}
|
||||
if ( $model ) {
|
||||
Events::save( $result, $model, $payload['imported_dates'] ?? null );
|
||||
} elseif ( in_array( $resource, [ 'venues', 'organizers' ], true )
|
||||
&& ( ! $id || ! empty( $payload['lookup_address'] ) || array_intersect_key( $payload, array_flip( Events::LOCATION_FIELDS ) ) )
|
||||
) {
|
||||
Events::save_location( $result, $payload, ! empty( $payload['lookup_address'] ) );
|
||||
}
|
||||
if ( $burnworks ) {
|
||||
Clubs::assign( $result, $burnworks['workspace_id'] . ':' . $burnworks['club_id'], true );
|
||||
} elseif ( 'events' === $resource && array_key_exists( 'sub_club', $payload ) ) {
|
||||
if ( BurnWorks::snapshot( $result ) ) {
|
||||
throw new InvalidArgumentException( __( 'Change the club for a synced event in burnWorks.', 'burn-events' ) );
|
||||
}
|
||||
Clubs::assign( $result, $payload['sub_club'] );
|
||||
}
|
||||
foreach ( $terms as $field => $ids ) {
|
||||
$updated = wp_set_object_terms( $result, $ids, self::TAXONOMIES[ $field ] );
|
||||
if ( is_wp_error( $updated ) ) {
|
||||
throw new RuntimeException( 'Taxonomy write failed.' );
|
||||
}
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
private static function event_model( int $id, array $payload ): ?array {
|
||||
$old = $id ? Events::event_data( $id ) : [ 'schedule' => [], 'fields' => [] ];
|
||||
$changed = array_intersect_key( $payload, array_flip( self::EVENT_FIELDS ) );
|
||||
if ( $id && ! array_key_exists( 'schedule', $payload ) && ! $changed ) {
|
||||
return null;
|
||||
}
|
||||
$rule = array_replace( $old['schedule'], $payload['schedule'] ?? [] );
|
||||
foreach ( [ 'include', 'exclude' ] as $date_set ) {
|
||||
$rule[ $date_set ] = implode( ',', (array) ( $rule[ $date_set ] ?? [] ) );
|
||||
}
|
||||
$input = $rule + array_replace( $old, $changed );
|
||||
$input['fields'] = array_replace( (array) $old['fields'], (array) ( $changed['fields'] ?? [] ) );
|
||||
$linked = self::validate_links( $changed, Events::RELATIONS );
|
||||
$event = Events::validate_event( $input );
|
||||
foreach ( Events::RELATIONS as $field => $type ) {
|
||||
$event[ $field ] = $linked[ $field ] ?? $old[ $field ] ?? [];
|
||||
}
|
||||
$event['fields'] = array_replace( $input['fields'], $event['fields'] );
|
||||
return $event;
|
||||
}
|
||||
|
||||
private static function validate_links( array $payload, array $types, bool $taxonomy = false ): array {
|
||||
$links = [];
|
||||
foreach ( array_intersect_key( $payload, $types ) as $field => $ids ) {
|
||||
$links[ $field ] = [];
|
||||
foreach ( array_unique( array_map( 'intval', $ids ) ) as $id ) {
|
||||
$item = $taxonomy ? get_term( $id, $types[ $field ] ) : get_post( $id );
|
||||
if ( ! $item || is_wp_error( $item ) || ( ! $taxonomy && ( $types[ $field ] !== $item->post_type || 'trash' === $item->post_status ) ) ) {
|
||||
throw new InvalidArgumentException( sprintf( __( '%1$s contains an invalid record ID (%2$d).', 'burn-events' ), $field, $id ) );
|
||||
}
|
||||
$links[ $field ][] = $id;
|
||||
}
|
||||
}
|
||||
return $links;
|
||||
}
|
||||
|
||||
private static function sync_key( string $resource, string $source, string $external_id ): string {
|
||||
return hash( 'sha256', get_current_blog_id() . '/' . $resource . '/' . $source . '/' . $external_id );
|
||||
}
|
||||
|
||||
private static function external_id( string $key ): int {
|
||||
global $wpdb;
|
||||
$table = self::table();
|
||||
return (int) $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $table WHERE sync_key = %s", $key ) );
|
||||
}
|
||||
|
||||
public static function terms( WP_REST_Request $request ) {
|
||||
$name = strtolower( $request->get_url_params()['taxonomy'] );
|
||||
$limit = self::limit( $request );
|
||||
$page = max( 1, absint( $request->get_param( 'page' ) ) );
|
||||
$terms = get_terms( [
|
||||
'taxonomy' => self::TAXONOMIES[ $name ], 'hide_empty' => false, 'orderby' => 'id',
|
||||
'number' => $limit + 1, 'offset' => ( $page - 1 ) * $limit,
|
||||
] );
|
||||
if ( is_wp_error( $terms ) ) {
|
||||
return self::error( 'terms_unavailable', __( 'The event terms could not be read.', 'burn-events' ), 500 );
|
||||
}
|
||||
return self::response( [
|
||||
'items' => array_map( static fn( \WP_Term $term ): array => [
|
||||
'id' => $term->term_id, 'name' => $term->name, 'slug' => $term->slug, 'parent' => $term->parent,
|
||||
], array_slice( $terms, 0, $limit ) ),
|
||||
'next_page' => count( $terms ) > $limit ? $page + 1 : null,
|
||||
] );
|
||||
}
|
||||
|
||||
public static function occurrences( WP_REST_Request $request ) {
|
||||
$id = (int) $request->get_url_params()['id'];
|
||||
if ( ! self::post( 'events', $id ) ) {
|
||||
return self::missing();
|
||||
}
|
||||
global $wpdb;
|
||||
$table = Events::table();
|
||||
$limit = self::limit( $request );
|
||||
$after = $request->get_param( 'after_start' );
|
||||
$parsed = is_string( $after ) ? rest_parse_date( $after ) : false;
|
||||
if ( null !== $after && false === $parsed ) {
|
||||
return self::error( 'after_start', __( 'Use an ISO 8601 date and time for after_start.', 'burn-events' ), 400 );
|
||||
}
|
||||
$rows = $wpdb->get_results( $wpdb->prepare(
|
||||
"SELECT starts_at, ends_at FROM $table WHERE event_id = %d AND starts_at > %s ORDER BY starts_at LIMIT %d",
|
||||
$id, false === $parsed ? '1000-01-01 00:00:00' : gmdate( 'Y-m-d H:i:s', $parsed ), $limit + 1
|
||||
), ARRAY_A );
|
||||
if ( ! is_array( $rows ) ) {
|
||||
return self::error( 'occurrences_unavailable', __( 'The event occurrences could not be read.', 'burn-events' ), 500 );
|
||||
}
|
||||
$items = array_map( static fn( array $row ): array => [
|
||||
'start_utc' => self::utc( $row['starts_at'] ), 'end_utc' => self::utc( $row['ends_at'] ),
|
||||
], array_slice( $rows, 0, $limit ) );
|
||||
return self::response( [
|
||||
'items' => $items, 'next_after_start' => count( $rows ) > $limit ? end( $items )['start_utc'] : null,
|
||||
] );
|
||||
}
|
||||
|
||||
public static function describe(): WP_REST_Response {
|
||||
$resources = [];
|
||||
foreach ( array_keys( self::RESOURCES ) as $resource ) {
|
||||
$resources[ $resource ] = self::schema( $resource );
|
||||
}
|
||||
return self::response( [
|
||||
'version' => 1, 'resource_writes' => $resources,
|
||||
'custom_event_fields' => (object) Admin::options()['fields'],
|
||||
'burnworks_event' => BurnWorks::schema(),
|
||||
'burnworks_club' => Clubs::schema(),
|
||||
] );
|
||||
}
|
||||
|
||||
private static function schema( string $resource ): array {
|
||||
$string = static fn( int $max ): array => [ 'type' => 'string', 'maxLength' => $max ];
|
||||
$boolean = [ 'type' => 'boolean' ];
|
||||
$enum = static fn( array $values ): array => [ 'type' => 'string', 'enum' => $values ];
|
||||
$number = static fn( int $min, int $max = PHP_INT_MAX ): array => [ 'type' => 'integer', 'minimum' => $min, 'maximum' => $max ];
|
||||
$list = static fn( array $item, int $max = 200 ): array => [ 'type' => 'array', 'items' => $item, 'maxItems' => $max ];
|
||||
$object = static fn( array $properties ): array => [ 'type' => 'object', 'properties' => $properties, 'additionalProperties' => false ];
|
||||
$properties = [
|
||||
'title' => $string( 200 ), 'description' => $string( 60000 ), 'excerpt' => $string( 4000 ),
|
||||
'slug' => $string( 200 ), 'post_status' => $enum( [ 'publish', 'draft', 'pending', 'private' ] ),
|
||||
'featured_media' => $number( 0 ), 'metadata' => [ 'type' => 'object', 'additionalProperties' => true ],
|
||||
];
|
||||
if ( 'events' === $resource ) {
|
||||
$day = [ 'type' => 'string', 'pattern' => '^\d{4}-\d{2}-\d{2}$' ];
|
||||
$time = [ 'type' => 'string', 'pattern' => '^\d{2}:\d{2}(?::\d{2})?$' ];
|
||||
$custom = [];
|
||||
foreach ( Admin::options()['fields'] as $key => $field ) {
|
||||
$custom[ $key ] = match ( $field['type'] ) {
|
||||
'checkbox' => $boolean,
|
||||
'select' => $enum( array_merge( [ '' ], $field['choices'] ) ),
|
||||
default => $string( 4000 ),
|
||||
};
|
||||
}
|
||||
$properties += [
|
||||
'schedule' => $object( [
|
||||
'start_date' => $day, 'end_date' => $day, 'start_time' => $time, 'end_time' => $time,
|
||||
'timezone' => $string( 120 ), 'all_day' => $boolean, 'repeat' => $enum( Schedule::REPEATS ),
|
||||
'interval' => $number( 1, 365 ), 'weekdays' => $list( $number( 1, 7 ), 7 ),
|
||||
'monthly' => $enum( [ 'day', 'weekday' ] ), 'count' => $number( 0, 10000 ),
|
||||
'until' => [ 'type' => 'string', 'pattern' => '^(?:\d{4}-\d{2}-\d{2})?$' ],
|
||||
'include' => $list( $day ), 'exclude' => $list( $day ),
|
||||
] ),
|
||||
'status' => $enum( array_keys( Events::statuses() ) ), 'location' => $string( 400 ), 'cost' => $string( 120 ),
|
||||
'sub_club' => [ 'type' => 'string', 'pattern' => '^(?:' . BurnWorks::UUID . ':' . BurnWorks::UUID . ')?$' ],
|
||||
'url' => $string( 2000 ), 'featured' => $boolean, 'hidden' => $boolean, 'fields' => $object( $custom ),
|
||||
] + array_fill_keys( array_merge( array_keys( Events::RELATIONS ), array_keys( self::TAXONOMIES ) ), $list( $number( 1 ) ) );
|
||||
} elseif ( in_array( $resource, [ 'venues', 'organizers' ], true ) ) {
|
||||
$properties += array_fill_keys( Events::LOCATION_FIELDS, $string( 400 ) );
|
||||
$properties['website'] = $string( 2000 );
|
||||
$properties['lookup_address'] = $boolean;
|
||||
}
|
||||
return $object( $properties );
|
||||
}
|
||||
}
|
||||
146
includes/class-burnworks.php
Normal file
146
includes/class-burnworks.php
Normal file
@@ -0,0 +1,146 @@
|
||||
<?php
|
||||
|
||||
namespace BurnEvents;
|
||||
|
||||
use DateTimeImmutable;
|
||||
use DateTimeZone;
|
||||
use WP_REST_Request;
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
final class BurnWorks {
|
||||
public const META = '_eventlabs_burnworks';
|
||||
public const UUID = '[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}';
|
||||
|
||||
public static function register(): void {
|
||||
$path = '/burnworks/workspaces/(?P<workspace_id>' . self::UUID . ')/events/(?P<event_id>' . self::UUID . ')';
|
||||
register_rest_route( Api::NAMESPACE, $path, [
|
||||
[
|
||||
'methods' => 'GET', 'callback' => [ self::class, 'read' ],
|
||||
'permission_callback' => [ Api::class, 'permission' ],
|
||||
],
|
||||
[
|
||||
'methods' => 'PUT', 'callback' => [ self::class, 'publish' ],
|
||||
'permission_callback' => [ Api::class, 'permission' ],
|
||||
],
|
||||
] );
|
||||
}
|
||||
|
||||
public static function schema(): array {
|
||||
$string = static fn( int $max ): array => [ 'type' => 'string', 'maxLength' => $max ];
|
||||
$uuid = [ 'type' => 'string', 'pattern' => '^' . self::UUID . '$' ];
|
||||
$date = [ 'type' => 'string', 'format' => 'date-time' ];
|
||||
$boolean = [ 'type' => 'boolean' ];
|
||||
return [
|
||||
'type' => 'object',
|
||||
'required' => [ 'club_id', 'title', 'description', 'starts_at', 'venue', 'status', 'audience', 'capacity', 'kind' ],
|
||||
'additionalProperties' => false,
|
||||
'properties' => [
|
||||
'workspace_id' => $uuid, 'id' => $uuid, 'club_id' => $uuid,
|
||||
'title' => [ 'type' => 'string', 'minLength' => 2, 'maxLength' => 160 ],
|
||||
'description' => $string( 4000 ), 'venue' => $string( 160 ), 'starts_at' => $date,
|
||||
'status' => [ 'type' => 'string', 'enum' => [ 'draft', 'published', 'cancelled' ] ],
|
||||
'audience' => [ 'type' => 'string', 'enum' => [ 'public', 'members', 'private' ] ],
|
||||
'capacity' => [ 'type' => 'integer', 'minimum' => 0, 'maximum' => 100000 ],
|
||||
'kind' => [ 'type' => 'string', 'enum' => [ 'event', 'volunteer', 'meeting' ] ],
|
||||
'created_by' => $string( 254 ), 'created_at' => $date,
|
||||
'ends_at' => $date, 'website_enabled' => $boolean, 'public_events_enabled' => $boolean,
|
||||
'publish_to_wordpress' => $boolean,
|
||||
'source_version' => [ 'type' => 'integer', 'minimum' => 1, 'maximum' => 9007199254740991 ],
|
||||
'custom' => [ 'type' => 'object', 'additionalProperties' => true ],
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
public static function snapshot( int $id ): array {
|
||||
return self::decode_snapshot( get_post_meta( $id, self::META, true ) );
|
||||
}
|
||||
|
||||
private static function decode_snapshot( $value ): array {
|
||||
if ( is_array( $value ) ) {
|
||||
return $value;
|
||||
}
|
||||
$record = is_string( $value ) ? json_decode( $value ) : null;
|
||||
return $record instanceof \stdClass ? (array) $record : [];
|
||||
}
|
||||
|
||||
private static function identity( WP_REST_Request $request ): array {
|
||||
$params = $request->get_url_params();
|
||||
return array_map( 'strtolower', [ $params['workspace_id'], $params['event_id'] ] );
|
||||
}
|
||||
|
||||
public static function read( WP_REST_Request $request ) {
|
||||
return Api::external( 'events', 'burnworks', implode( ':', self::identity( $request ) ) );
|
||||
}
|
||||
|
||||
public static function publish( WP_REST_Request $request ) {
|
||||
$raw = json_decode( $request->get_body() );
|
||||
if ( ! $raw instanceof \stdClass || ! $request->is_json_content_type() ) {
|
||||
return Api::error( 'invalid_json', __( 'Send a JSON object with Content-Type: application/json.', 'burn-events' ), 400 );
|
||||
}
|
||||
$input = $request->get_json_params();
|
||||
$schema = self::schema();
|
||||
$valid = rest_validate_value_from_schema( $input, $schema, 'body' );
|
||||
if ( is_wp_error( $valid ) ) {
|
||||
$valid->add_data( [ 'status' => 400 ] );
|
||||
return $valid;
|
||||
}
|
||||
[ $workspace, $id ] = self::identity( $request );
|
||||
if ( strtolower( $input['workspace_id'] ?? $workspace ) !== $workspace || strtolower( $input['id'] ?? $id ) !== $id ) {
|
||||
return Api::error( 'identity_mismatch', __( 'The burnWorks IDs must match the route.', 'burn-events' ), 400 );
|
||||
}
|
||||
$record = rest_sanitize_value_from_schema( $input, $schema, 'body' );
|
||||
$record += [ 'workspace_id' => $workspace, 'id' => $id ];
|
||||
if ( isset( $raw->custom ) ) {
|
||||
if ( ! $raw->custom instanceof \stdClass ) {
|
||||
return Api::error( 'invalid_custom', __( 'custom must be a JSON object.', 'burn-events' ), 400 );
|
||||
}
|
||||
$record['custom'] = $raw->custom;
|
||||
}
|
||||
|
||||
$start = new DateTimeImmutable( $record['starts_at'] );
|
||||
$end = isset( $record['ends_at'] ) ? new DateTimeImmutable( $record['ends_at'] ) : $start->modify( '+1 hour' );
|
||||
if ( $end->getTimestamp() <= $start->getTimestamp() ) {
|
||||
return Api::error( 'invalid_time_range', __( 'The burnWorks event end must be after its start.', 'burn-events' ), 422 );
|
||||
}
|
||||
$utc = new DateTimeZone( 'UTC' );
|
||||
$start = $start->setTimezone( $utc );
|
||||
$end = $end->setTimezone( $utc );
|
||||
return Api::write( 'events', [
|
||||
'title' => $record['title'],
|
||||
'description' => esc_html( $record['description'] ),
|
||||
'location' => $record['venue'],
|
||||
'post_status' => self::publishable( $record ) ? 'publish' : 'draft',
|
||||
'status' => 'cancelled' === $record['status'] ? 'cancelled' : 'scheduled',
|
||||
'schedule' => [
|
||||
'start_date' => $start->format( 'Y-m-d' ), 'start_time' => $start->format( 'H:i:s' ),
|
||||
'end_date' => $end->format( 'Y-m-d' ), 'end_time' => $end->format( 'H:i:s' ),
|
||||
'timezone' => 'UTC', 'all_day' => false, 'repeat' => 'none',
|
||||
],
|
||||
], $request, 0, [ 'burnworks', $workspace . ':' . $id ], $record );
|
||||
}
|
||||
|
||||
private static function publishable( array $record ): bool {
|
||||
return 'published' === $record['status'] && 'public' === $record['audience']
|
||||
&& ! empty( $record['website_enabled'] ) && ! empty( $record['public_events_enabled'] )
|
||||
&& ( $record['publish_to_wordpress'] ?? true );
|
||||
}
|
||||
|
||||
public static function accepts_version( array $incoming, array $stored ): bool {
|
||||
$previous = $stored['source_version'] ?? 0;
|
||||
$version = $incoming['source_version'] ?? 0;
|
||||
return ! $previous || $version > $previous || ( $version === $previous && maybe_serialize( $incoming ) === maybe_serialize( $stored ) );
|
||||
}
|
||||
|
||||
public static function protect_publication( array $data, array $post ): array {
|
||||
if ( Events::EVENT !== $data['post_type'] || ! in_array( $data['post_status'], [ 'publish', 'future' ], true ) ) {
|
||||
return $data;
|
||||
}
|
||||
$id = (int) ( $post['ID'] ?? 0 );
|
||||
$record = $id ? self::snapshot( $id ) : self::decode_snapshot( wp_unslash( $post['meta_input'][ self::META ] ?? '' ) );
|
||||
if ( $record && ! self::publishable( $record ) ) {
|
||||
$data['post_status'] = 'draft';
|
||||
}
|
||||
return $data;
|
||||
}
|
||||
}
|
||||
200
includes/class-calendar-grid.php
Normal file
200
includes/class-calendar-grid.php
Normal file
@@ -0,0 +1,200 @@
|
||||
<?php
|
||||
|
||||
namespace BurnEvents;
|
||||
|
||||
use DateTimeImmutable;
|
||||
use DateTimeZone;
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
final class Calendar_Grid {
|
||||
public const SCRIPT = 'burn-events-grid';
|
||||
public const COLOR_META = '_burn_events_category_color';
|
||||
|
||||
public static function register_assets(): void {
|
||||
wp_register_script( self::SCRIPT, plugins_url( 'assets/calendar-grid.js', BURN_EVENTS_FILE ), [], BURN_EVENTS_VERSION, true );
|
||||
}
|
||||
|
||||
public static function occurrences( array $filters, DateTimeImmutable $start, DateTimeImmutable $end ): array {
|
||||
$first = $start->format( 'Y-m-d' );
|
||||
$after = $end->format( 'Y-m-d' );
|
||||
$utc = new DateTimeZone( 'UTC' );
|
||||
// The index stores UTC. Leave room for events whose local dates cross the UTC boundary.
|
||||
$filters['from'] = ( new DateTimeImmutable( $first, $utc ) )->modify( '-1 day' )->format( 'Y-m-d H:i:s' );
|
||||
$filters['to'] = ( new DateTimeImmutable( $after, $utc ) )->modify( '+1 day' )->format( 'Y-m-d H:i:s' );
|
||||
$rows = [];
|
||||
do {
|
||||
$batch = Events::query( $filters );
|
||||
update_meta_cache( 'post', array_unique( array_column( $batch, 'event_id' ) ) );
|
||||
foreach ( $batch as $row ) {
|
||||
$data = Events::event_data( (int) $row['event_id'] );
|
||||
$zone = $data['schedule']['timezone'] ?? wp_timezone_string();
|
||||
$from = Events::local_time( $row['starts_at'], $zone )->format( 'Y-m-d' );
|
||||
// An occurrence ending at midnight stops before the next day's cell.
|
||||
$end_utc = new DateTimeImmutable( $row['ends_at'], $utc );
|
||||
$last = $end_utc->modify( '-1 second' )->setTimezone( new DateTimeZone( $zone ) )->format( 'Y-m-d' );
|
||||
if ( $last >= $first && $from < $after ) {
|
||||
$rows[] = $row + [ 'first_day' => $from, 'last_day' => $last ];
|
||||
if ( count( $rows ) === $filters['limit'] ) {
|
||||
return $rows;
|
||||
}
|
||||
}
|
||||
}
|
||||
$filters['offset'] += count( $batch );
|
||||
} while ( count( $batch ) === $filters['limit'] );
|
||||
return $rows;
|
||||
}
|
||||
|
||||
public static function render( array $rows, DateTimeImmutable $start, DateTimeImmutable $end, DateTimeImmutable $day, bool $month, string $category ): void {
|
||||
$dates = [];
|
||||
for ( $date = $start; $date < $end; $date = $date->modify( '+1 day' ) ) {
|
||||
$dates[] = $date;
|
||||
}
|
||||
$indices = array_flip( array_map( static fn( DateTimeImmutable $date ): string => $date->format( 'Y-m-d' ), $dates ) );
|
||||
$first = $start->format( 'Y-m-d' );
|
||||
$last = end( $dates )->format( 'Y-m-d' );
|
||||
$weeks = array_chunk( $dates, 7 );
|
||||
$segments = array_fill( 0, count( $weeks ), [] );
|
||||
$posts = $events = $legend = [];
|
||||
if ( $rows ) {
|
||||
wp_enqueue_script( self::SCRIPT );
|
||||
update_object_term_cache( array_unique( array_column( $rows, 'event_id' ) ), Events::EVENT );
|
||||
}
|
||||
foreach ( $rows as $index => $row ) {
|
||||
$id = (int) $row['event_id'];
|
||||
$posts[ $id ] ??= self::event( $id, $category );
|
||||
$event = $posts[ $id ];
|
||||
$legend[ $event['category_id'] ] = [ 'name' => $event['category'], 'color' => $event['color'] ];
|
||||
$events[ $index ] = $event + [
|
||||
'url' => Events::event_url( $row ),
|
||||
'period' => Calendar::period( $row, $event['data'] ),
|
||||
'preview' => wp_unique_id( 'be-event-preview-' ),
|
||||
];
|
||||
$from = $indices[ max( $first, $row['first_day'] ) ];
|
||||
$through = $indices[ min( $last, $row['last_day'] ) ];
|
||||
for ( $week = intdiv( $from, 7 ); $week <= intdiv( $through, 7 ); ++$week ) {
|
||||
$offset = $week * 7;
|
||||
$segments[ $week ][] = [
|
||||
'event' => $index,
|
||||
'first' => max( 0, $from - $offset ),
|
||||
'last' => min( 6, $through - $offset ),
|
||||
'before' => $row['first_day'] < $dates[ $offset ]->format( 'Y-m-d' ),
|
||||
'after' => $row['last_day'] > $dates[ $offset + 6 ]->format( 'Y-m-d' ),
|
||||
];
|
||||
}
|
||||
}
|
||||
ksort( $legend );
|
||||
?>
|
||||
<?php if ( $legend && [ 0 ] !== array_keys( $legend ) ) : ?>
|
||||
<ul class="be-grid-legend" aria-label="<?php esc_attr_e( 'Event categories', 'burn-events' ); ?>">
|
||||
<?php foreach ( $legend as $term ) : ?>
|
||||
<li class="be-grid-color" style="<?php echo esc_attr( $term['color'] ); ?>"><?php echo esc_html( $term['name'] ); ?></li>
|
||||
<?php endforeach; ?>
|
||||
</ul>
|
||||
<?php endif; ?>
|
||||
<div class="be-grid-scroll" role="region" aria-label="<?php esc_attr_e( 'Calendar grid', 'burn-events' ); ?>" tabindex="0">
|
||||
<div class="be-grid">
|
||||
<div class="be-grid-weekdays" aria-hidden="true">
|
||||
<?php foreach ( $weeks[0] as $date ) : ?>
|
||||
<div class="be-weekday"><?php echo esc_html( wp_date( 'D', $date->getTimestamp(), $date->getTimezone() ) ); ?></div>
|
||||
<?php endforeach; ?>
|
||||
</div>
|
||||
<?php foreach ( $weeks as $week => $days ) { self::week( $days, $segments[ $week ], $events, $month ? $day->format( 'Y-m' ) : '' ); } ?>
|
||||
</div>
|
||||
</div>
|
||||
<?php
|
||||
foreach ( $events as $event ) {
|
||||
self::preview( $event );
|
||||
}
|
||||
if ( ! $rows ) {
|
||||
echo '<p class="be-empty">' . esc_html__( 'No events in this date range.', 'burn-events' ) . '</p>';
|
||||
}
|
||||
}
|
||||
|
||||
private static function event( int $id, string $category ): array {
|
||||
$terms = get_the_terms( $id, Events::CATEGORY );
|
||||
$terms = is_array( $terms ) ? $terms : [];
|
||||
usort( $terms, static fn( $left, $right ): int => $left->term_id <=> $right->term_id );
|
||||
$term = $terms[0] ?? null;
|
||||
foreach ( $terms as $candidate ) {
|
||||
if ( $candidate->slug === $category ) {
|
||||
$term = $candidate;
|
||||
break;
|
||||
}
|
||||
}
|
||||
$term_id = (int) ( $term->term_id ?? 0 );
|
||||
$data = Events::event_data( $id );
|
||||
$label = $term->name ?? __( 'Uncategorized', 'burn-events' );
|
||||
$color = $term_id ? sanitize_hex_color( (string) get_term_meta( $term_id, self::COLOR_META, true ) ) : '';
|
||||
return [
|
||||
'title' => get_the_title( $id ),
|
||||
'data' => $data,
|
||||
'location' => Calendar::event_location( $data ),
|
||||
'excerpt' => Calendar::event_excerpt( $id ),
|
||||
'image' => get_the_post_thumbnail_url( $id, 'thumbnail' ),
|
||||
'category_id' => $term_id,
|
||||
'category' => $label,
|
||||
'categories' => $terms ? implode( ' · ', array_column( $terms, 'name' ) ) : $label,
|
||||
'color' => $color ? '--be-category-custom:' . $color : ( $term_id ? sprintf( '--be-category-hue:%.2F;--be-category-saturation:63%%', fmod( $term_id * 137.508, 360 ) ) : '' ),
|
||||
];
|
||||
}
|
||||
|
||||
private static function week( array $days, array $segments, array $events, string $month ): void {
|
||||
usort( $segments, static function ( array $left, array $right ): int {
|
||||
return $left['first'] <=> $right['first'] ?: $right['last'] <=> $left['last'] ?: $left['event'] <=> $right['event'];
|
||||
} );
|
||||
$ends = [];
|
||||
foreach ( $segments as $index => $segment ) {
|
||||
$track = 0;
|
||||
while ( isset( $ends[ $track ] ) && $ends[ $track ] >= $segment['first'] ) {
|
||||
++$track;
|
||||
}
|
||||
$ends[ $track ] = $segment['last'];
|
||||
$segments[ $index ]['track'] = $track + 2;
|
||||
}
|
||||
$today = wp_date( 'Y-m-d' );
|
||||
?>
|
||||
<div class="be-grid-week" style="--be-tracks:<?php echo max( 1, count( $ends ) ); ?>">
|
||||
<?php foreach ( $days as $column => $date ) : ?>
|
||||
<?php $key = $date->format( 'Y-m-d' ); ?>
|
||||
<div class="be-grid-day<?php echo $month && $date->format( 'Y-m' ) !== $month ? ' be-grid-other' : ''; ?>" style="--be-day:<?php echo $column + 1; ?>">
|
||||
<time datetime="<?php echo esc_attr( $key ); ?>" aria-label="<?php echo esc_attr( wp_date( 'l, F j', $date->getTimestamp(), $date->getTimezone() ) ); ?>"<?php if ( $today === $key ) : ?> aria-current="date"<?php endif; ?>><?php echo esc_html( $date->format( 'j' ) ); ?></time>
|
||||
</div>
|
||||
<?php endforeach; ?>
|
||||
<?php foreach ( $segments as $segment ) : ?>
|
||||
<?php
|
||||
$event = $events[ $segment['event'] ];
|
||||
$style = sprintf( '--be-start:%d;--be-span:%d;--be-track:%d;%s', $segment['first'] + 1, $segment['last'] - $segment['first'] + 1, $segment['track'], $event['color'] );
|
||||
?>
|
||||
<a class="be-grid-event be-grid-color<?php echo $segment['before'] ? ' be-grid-continued' : ''; ?><?php echo $segment['after'] ? ' be-grid-continues' : ''; ?>"
|
||||
href="<?php echo esc_url( $event['url'] ); ?>" data-be-preview="<?php echo esc_attr( $event['preview'] ); ?>"
|
||||
style="<?php echo esc_attr( $style ); ?>" aria-label="<?php echo esc_attr( wp_strip_all_tags( html_entity_decode( $event['title'], ENT_QUOTES | ENT_HTML5, 'UTF-8' ) ) . ', ' . $event['period'] . ', ' . $event['categories'] ); ?>">
|
||||
<span><?php echo esc_html( $event['title'] ); ?></span>
|
||||
</a>
|
||||
<?php endforeach; ?>
|
||||
</div>
|
||||
<?php
|
||||
}
|
||||
|
||||
private static function preview( array $event ): void {
|
||||
$data = $event['data'];
|
||||
?>
|
||||
<template id="<?php echo esc_attr( $event['preview'] ); ?>">
|
||||
<div class="be-preview-content be-grid-color" style="<?php echo esc_attr( $event['color'] ); ?>">
|
||||
<div class="be-preview-heading">
|
||||
<?php if ( $event['image'] ) : ?><img src="<?php echo esc_url( $event['image'] ); ?>" alt="" width="56" height="56" decoding="async"><?php endif; ?>
|
||||
<div>
|
||||
<p class="be-preview-category"><?php echo esc_html( $event['categories'] ); ?></p>
|
||||
<strong><?php echo esc_html( $event['title'] ); ?></strong>
|
||||
</div>
|
||||
</div>
|
||||
<p class="be-preview-time"><?php echo esc_html( $event['period'] ); ?></p>
|
||||
<?php if ( $event['location'] ) : ?><p><?php echo esc_html( $event['location'] ); ?></p><?php endif; ?>
|
||||
<?php if ( '' !== $data['cost'] ) : ?><p class="be-preview-cost"><?php echo esc_html( '0' === $data['cost'] ? __( 'Free', 'burn-events' ) : $data['cost'] ); ?></p><?php endif; ?>
|
||||
<?php if ( 'scheduled' !== $data['status'] ) : ?><p class="be-preview-cost"><?php echo esc_html( Events::statuses()[ $data['status'] ] ?? '' ); ?></p><?php endif; ?>
|
||||
<?php if ( $event['excerpt'] ) : ?><p class="be-preview-excerpt"><?php echo esc_html( $event['excerpt'] ); ?></p><?php endif; ?>
|
||||
</div>
|
||||
</template>
|
||||
<?php
|
||||
}
|
||||
}
|
||||
624
includes/class-calendar.php
Normal file
624
includes/class-calendar.php
Normal file
@@ -0,0 +1,624 @@
|
||||
<?php
|
||||
|
||||
namespace BurnEvents;
|
||||
|
||||
use DateTimeImmutable;
|
||||
use DateTimeZone;
|
||||
use WP_Post;
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
final class Calendar {
|
||||
public const VIEWS = [ 'list', 'month', 'week', 'day', 'photo', 'map', 'summary' ];
|
||||
private static string $content = '';
|
||||
private static string $schema = '';
|
||||
|
||||
public static function register(): void {
|
||||
add_shortcode( 'burn_events', [ self::class, 'render' ] );
|
||||
add_filter( 'query_vars', static function ( array $vars ): array {
|
||||
return array_merge( $vars, [ 'be_view', 'be_date', 'be_community' ] );
|
||||
} );
|
||||
add_rewrite_rule( '^events/(list|month|week|day|photo|map|summary)/?$', 'index.php?post_type=burn_event&be_view=$matches[1]', 'top' );
|
||||
add_filter( 'template_include', [ self::class, 'route' ], 90 );
|
||||
}
|
||||
|
||||
public static function view_labels(): array {
|
||||
return [
|
||||
'list' => __( 'List', 'burn-events' ), 'month' => __( 'Month', 'burn-events' ),
|
||||
'week' => __( 'Week', 'burn-events' ), 'day' => __( 'Day', 'burn-events' ),
|
||||
'photo' => __( 'Photo', 'burn-events' ), 'map' => __( 'Map', 'burn-events' ),
|
||||
'summary' => __( 'Summary', 'burn-events' ),
|
||||
];
|
||||
}
|
||||
|
||||
public static function request( string $key ): string {
|
||||
return isset( $_GET[ $key ] ) && is_string( $_GET[ $key ] ) ? sanitize_text_field( wp_unslash( $_GET[ $key ] ) ) : '';
|
||||
}
|
||||
|
||||
public static function archive_url(): string {
|
||||
return (string) get_post_type_archive_link( Events::EVENT );
|
||||
}
|
||||
|
||||
public static function route( string $path ): string {
|
||||
if ( is_feed() || is_embed() ) {
|
||||
return $path;
|
||||
}
|
||||
if ( get_query_var( 'be_community' ) ) {
|
||||
$view = (string) get_query_var( 'be_community' );
|
||||
if ( ! in_array( $view, [ 'submit', 'mine' ], true ) ) {
|
||||
return $path;
|
||||
}
|
||||
self::$content = 'mine' === $view ? Community::mine() : Community::form();
|
||||
} elseif ( is_singular( Events::EVENT ) ) {
|
||||
self::$content = self::single( get_queried_object() );
|
||||
} elseif ( is_singular( array_values( Events::RELATIONS ) ) ) {
|
||||
self::$content = self::linked( get_queried_object() );
|
||||
} elseif ( is_post_type_archive( Events::EVENT ) || is_tax( Events::CATEGORY ) ) {
|
||||
$term = is_tax( Events::CATEGORY ) ? get_queried_object() : null;
|
||||
$term_link = $term ? get_term_link( $term ) : self::archive_url();
|
||||
self::$content = self::render( [
|
||||
'category' => $term->slug ?? '',
|
||||
'title' => $term->name ?? __( 'Events', 'burn-events' ),
|
||||
'url' => is_string( $term_link ) ? $term_link : self::archive_url(),
|
||||
] );
|
||||
} else {
|
||||
return $path;
|
||||
}
|
||||
return dirname( __DIR__ ) . '/templates/front.php';
|
||||
}
|
||||
|
||||
public static function content(): string {
|
||||
return self::$content . self::$schema;
|
||||
}
|
||||
|
||||
public static function render( $attributes = [] ): string {
|
||||
$options = Admin::options();
|
||||
$attributes = shortcode_atts( [
|
||||
'view' => $options['view'], 'title' => __( 'Events', 'burn-events' ), 'url' => '',
|
||||
'category' => '', 'tag' => '', 'location' => '', 'featured' => 'no',
|
||||
'limit' => $options['per_page'], 'filters' => 'yes', 'relation' => null, 'scope' => '',
|
||||
], (array) $attributes, 'burn_events' );
|
||||
$interactive = 'no' !== $attributes['filters'];
|
||||
$selected = $interactive ? ( self::request( 'be_view' ) ?: (string) get_query_var( 'be_view' ) ) : '';
|
||||
$view = $selected ?: $attributes['view'];
|
||||
$view = in_array( $view, self::VIEWS, true ) ? $view : 'list';
|
||||
$day_value = $interactive ? self::request( 'be_date' ) : '';
|
||||
$day = self::date( $day_value );
|
||||
$search = $interactive ? self::request( 'be_search' ) : '';
|
||||
$location = $attributes['location'] ?: ( $interactive ? self::request( 'be_location' ) : '' );
|
||||
$category = sanitize_title( $attributes['category'] ?: ( $interactive ? self::request( 'be_category' ) : '' ) );
|
||||
$page = $interactive ? max( 1, min( 10000, absint( self::request( 'be_page' ) ) ) ) : 1;
|
||||
$past_requested = $interactive && '1' === self::request( 'be_past' );
|
||||
$past = $past_requested && in_array( $view, [ 'list', 'photo', 'summary' ], true );
|
||||
$limit = max( 1, min( 50, absint( $attributes['limit'] ) ) );
|
||||
$grid = in_array( $view, [ 'month', 'week' ], true );
|
||||
$map = 'map' === $view;
|
||||
$map_period = $map ? self::map_period( $day, $interactive, $past_requested ) : null;
|
||||
$range = self::range( $view, $day );
|
||||
$from = $map_period['start'] ?? $range[0] ?? ( $day_value ? $day : new DateTimeImmutable( 'now', wp_timezone() ) );
|
||||
$to = $map ? $map_period['end']?->modify( '+1 day' ) : ( $range[1] ?? null );
|
||||
$max_rows = $grid || $map ? 600 : $limit;
|
||||
$utc = new DateTimeZone( 'UTC' );
|
||||
$filters = [
|
||||
'from' => $past ? null : $from->setTimezone( $utc )->format( 'Y-m-d H:i:s' ),
|
||||
'to' => $past ? gmdate( 'Y-m-d H:i:s' ) : ( $to ? $to->setTimezone( $utc )->format( 'Y-m-d H:i:s' ) : null ),
|
||||
'past' => $past, 'search' => $search, 'category' => $category, 'tag' => sanitize_title( $attributes['tag'] ),
|
||||
'scope' => sanitize_text_field( $attributes['scope'] ),
|
||||
'location' => $location, 'relation' => is_array( $attributes['relation'] ) ? $attributes['relation'] : null, 'featured' => 'yes' === $attributes['featured'],
|
||||
'offset' => $grid || $map ? 0 : ( $page - 1 ) * $limit, 'limit' => $max_rows + 1,
|
||||
];
|
||||
if ( $grid ) {
|
||||
$rows = Calendar_Grid::occurrences( $filters, $range[0], $range[1] );
|
||||
} else {
|
||||
$rows = ! empty( $map_period['error'] ) ? [] : Events::query( $filters );
|
||||
}
|
||||
$more = count( $rows ) > $max_rows;
|
||||
$rows = array_slice( $rows, 0, $max_rows );
|
||||
$base = $attributes['url'] ?: ( is_singular() ? ( get_permalink() ?: self::archive_url() ) : self::archive_url() );
|
||||
$state = array_filter( [
|
||||
'be_view' => $view, 'be_date' => $day_value ? $day->format( 'Y-m-d' ) : '',
|
||||
'be_search' => $search, 'be_category' => $category, 'be_location' => $location, 'be_past' => $past ? '1' : '',
|
||||
] );
|
||||
ob_start();
|
||||
?>
|
||||
<section class="be-calendar">
|
||||
<?php if ( $attributes['title'] ) : ?>
|
||||
<header class="be-calendar-header">
|
||||
<h1><?php echo esc_html( $attributes['title'] ); ?></h1>
|
||||
<?php if ( $interactive ) : ?><a class="be-calendar-subscribe" href="<?php echo esc_url( Transfer::ics_url() ); ?>"><?php esc_html_e( 'Subscribe', 'burn-events' ); ?></a><?php endif; ?>
|
||||
</header>
|
||||
<?php endif; ?>
|
||||
<?php if ( $interactive ) : ?>
|
||||
<?php self::search_form( $base, $state, $attributes['category'], $map_period ); ?>
|
||||
<div class="be-calendar-toolbar">
|
||||
<nav class="be-view-tabs" aria-label="<?php esc_attr_e( 'Calendar views', 'burn-events' ); ?>">
|
||||
<?php foreach ( self::view_labels() as $key => $label ) : ?>
|
||||
<?php
|
||||
$tab = [ 'be_view' => $key, 'be_past' => false ];
|
||||
if ( 'map' === $key && $map_period ) {
|
||||
$tab += [ 'be_start' => $map_period['start']?->format( 'Y-m-d' ), 'be_end' => $map_period['end']?->format( 'Y-m-d' ) ];
|
||||
}
|
||||
?>
|
||||
<a <?php if ( $key === $view ) { echo 'aria-current="page"'; } ?> href="<?php echo esc_url( add_query_arg( array_replace( $state, $tab ), $base ) ); ?>"><?php echo esc_html( $label ); ?></a>
|
||||
<?php endforeach; ?>
|
||||
</nav>
|
||||
<?php if ( ! $range && ! $map ) : ?>
|
||||
<a href="<?php echo esc_url( add_query_arg( array_replace( $state, [ 'be_past' => $past ? false : '1', 'be_date' => false ] ), $base ) ); ?>"><?php echo esc_html( $past ? __( 'Upcoming events', 'burn-events' ) : __( 'Past events', 'burn-events' ) ); ?></a>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
<?php if ( $range ) { self::date_navigation( $view, $day, $range, $base, $state ); } ?>
|
||||
<?php endif; ?>
|
||||
|
||||
<?php
|
||||
if ( $grid ) {
|
||||
Calendar_Grid::render( $rows, $range[0], $range[1], $day, 'month' === $view, $category );
|
||||
if ( $more ) {
|
||||
echo '<p>' . esc_html__( 'Showing the first 600 occurrences in this date range.', 'burn-events' ) . '</p>';
|
||||
}
|
||||
} elseif ( ! empty( $map_period['error'] ) ) {
|
||||
echo '<p class="be-empty" role="alert">' . esc_html( $map_period['error'] ) . '</p>';
|
||||
} elseif ( ! $rows ) {
|
||||
echo '<p class="be-empty">' . esc_html__( 'No events found for this selection.', 'burn-events' ) . '</p>';
|
||||
} elseif ( $map ) {
|
||||
Map_View::archive( $rows );
|
||||
if ( $more ) {
|
||||
echo '<p>' . esc_html__( 'Showing the first 600 occurrences. Choose a shorter date range to see all matching locations.', 'burn-events' ) . '</p>';
|
||||
}
|
||||
} else {
|
||||
echo '<div class="be-event-list be-view-' . esc_attr( $view ) . '">';
|
||||
foreach ( $rows as $row ) {
|
||||
self::card( $row, $view );
|
||||
}
|
||||
echo '</div>';
|
||||
}
|
||||
?>
|
||||
<?php if ( $interactive && ! $grid && ! $map && ( $page > 1 || $more ) ) : ?>
|
||||
<nav class="be-pagination" aria-label="<?php esc_attr_e( 'Event pages', 'burn-events' ); ?>">
|
||||
<?php if ( $page > 1 ) : ?><a href="<?php echo esc_url( add_query_arg( $state + [ 'be_page' => $page - 1 ], $base ) ); ?>"><?php esc_html_e( 'Previous events', 'burn-events' ); ?></a><?php endif; ?>
|
||||
<?php if ( $more ) : ?><a href="<?php echo esc_url( add_query_arg( $state + [ 'be_page' => $page + 1 ], $base ) ); ?>"><?php esc_html_e( 'More events', 'burn-events' ); ?></a><?php endif; ?>
|
||||
</nav>
|
||||
<?php endif; ?>
|
||||
</section>
|
||||
<?php
|
||||
return ob_get_clean();
|
||||
}
|
||||
|
||||
private static function date( string $value ): DateTimeImmutable {
|
||||
return self::parse_date( $value ) ?? new DateTimeImmutable( 'today', wp_timezone() );
|
||||
}
|
||||
|
||||
private static function parse_date( string $value ): ?DateTimeImmutable {
|
||||
if ( ! preg_match( '/^\d{4}-\d{2}-\d{2}$/D', $value ) ) {
|
||||
return null;
|
||||
}
|
||||
$day = DateTimeImmutable::createFromFormat( '!Y-m-d', $value, wp_timezone() );
|
||||
return $day && $day->format( 'Y-m-d' ) === $value ? $day : null;
|
||||
}
|
||||
|
||||
private static function map_period( DateTimeImmutable $day, bool $interactive, bool $past ): array {
|
||||
$start_input = $interactive ? self::request( 'be_start' ) : '';
|
||||
$end_input = $interactive ? self::request( 'be_end' ) : '';
|
||||
$start = $start_input ? self::parse_date( $start_input ) : ( $past ? $day->modify( '-29 days' ) : $day );
|
||||
$end = $end_input ? self::parse_date( $end_input ) : $start?->modify( '+29 days' );
|
||||
$error = '';
|
||||
if ( ! $start || ! $end ) {
|
||||
$error = __( 'Enter a valid start and end date.', 'burn-events' );
|
||||
} elseif ( $end < $start ) {
|
||||
$error = __( 'The end date must be on or after the start date.', 'burn-events' );
|
||||
}
|
||||
return [ 'start' => $start, 'end' => $end, 'error' => $error ];
|
||||
}
|
||||
|
||||
private static function range( string $view, DateTimeImmutable $day ): ?array {
|
||||
if ( 'day' === $view ) {
|
||||
return [ $day, $day->modify( '+1 day' ) ];
|
||||
}
|
||||
if ( ! in_array( $view, [ 'month', 'week' ], true ) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$start_day = (int) get_option( 'start_of_week', 1 );
|
||||
$first = 'month' === $view ? $day->modify( 'first day of this month' ) : $day;
|
||||
$diff = ( (int) $first->format( 'w' ) - $start_day + 7 ) % 7;
|
||||
$start = $first->modify( "-{$diff} days" );
|
||||
if ( 'week' === $view ) {
|
||||
return [ $start, $start->modify( '+7 days' ) ];
|
||||
}
|
||||
$last = $day->modify( 'last day of this month' );
|
||||
$remaining = ( $start_day - (int) $last->format( 'w' ) + 7 ) % 7;
|
||||
return [ $start, $last->modify( '+' . ( $remaining ?: 7 ) . ' days' ) ];
|
||||
}
|
||||
|
||||
private static function search_form( string $url, array $state, string $fixed_category, ?array $map_period = null ): void {
|
||||
$terms = $fixed_category ? [] : get_terms( [ 'taxonomy' => Events::CATEGORY, 'hide_empty' => true ] );
|
||||
$query = [];
|
||||
parse_str( (string) wp_parse_url( $url, PHP_URL_QUERY ), $query );
|
||||
?>
|
||||
<form class="be-search" method="get" action="<?php echo esc_url( strtok( $url, '?' ) ); ?>" role="search" aria-label="<?php esc_attr_e( 'Search events', 'burn-events' ); ?>">
|
||||
<?php foreach ( $query + array_intersect_key( $state, array_flip( [ 'be_view', 'be_date', 'be_past' ] ) ) as $key => $value ) : ?>
|
||||
<?php if ( is_scalar( $value ) ) : ?><input type="hidden" name="<?php echo esc_attr( $key ); ?>" value="<?php echo esc_attr( (string) $value ); ?>"><?php endif; ?>
|
||||
<?php endforeach; ?>
|
||||
<label><?php esc_html_e( 'Search events', 'burn-events' ); ?><input name="be_search" type="search" placeholder="<?php esc_attr_e( 'Name or keyword', 'burn-events' ); ?>" value="<?php echo esc_attr( $state['be_search'] ?? '' ); ?>"></label>
|
||||
<label><?php esc_html_e( 'Location', 'burn-events' ); ?><input name="be_location" type="search" placeholder="<?php esc_attr_e( 'City or venue', 'burn-events' ); ?>" value="<?php echo esc_attr( $state['be_location'] ?? '' ); ?>"></label>
|
||||
<?php if ( $terms && ! is_wp_error( $terms ) ) : ?>
|
||||
<label><?php esc_html_e( 'Category', 'burn-events' ); ?><select name="be_category"><option value=""><?php esc_html_e( 'All categories', 'burn-events' ); ?></option>
|
||||
<?php foreach ( $terms as $term ) : ?><option value="<?php echo esc_attr( $term->slug ); ?>" <?php selected( $state['be_category'] ?? '', $term->slug ); ?>><?php echo esc_html( $term->name ); ?></option><?php endforeach; ?>
|
||||
</select></label>
|
||||
<?php endif; ?>
|
||||
<?php if ( $map_period ) : ?>
|
||||
<label><?php esc_html_e( 'Start date', 'burn-events' ); ?><input name="be_start" type="date" value="<?php echo esc_attr( $map_period['start']?->format( 'Y-m-d' ) ?? '' ); ?>" required></label>
|
||||
<label><?php esc_html_e( 'End date', 'burn-events' ); ?><input name="be_end" type="date" value="<?php echo esc_attr( $map_period['end']?->format( 'Y-m-d' ) ?? '' ); ?>" required></label>
|
||||
<?php endif; ?>
|
||||
<button class="be-button" type="submit"><?php echo $map_period ? esc_html__( 'Update map', 'burn-events' ) : esc_html__( 'Find events', 'burn-events' ); ?></button>
|
||||
</form>
|
||||
<?php
|
||||
}
|
||||
|
||||
private static function date_navigation( string $view, DateTimeImmutable $day, array $range, string $base, array $state ): void {
|
||||
if ( 'month' === $view ) {
|
||||
$previous = $day->modify( 'first day of last month' );
|
||||
$next = $day->modify( 'first day of next month' );
|
||||
$title = wp_date( 'F Y', $day->getTimestamp() );
|
||||
} else {
|
||||
$step = 'week' === $view ? 7 : 1;
|
||||
$previous = $range[0]->modify( "-{$step} days" );
|
||||
$next = $range[1];
|
||||
$title = wp_date( 'M j, Y', $range[0]->getTimestamp() );
|
||||
if ( 7 === $step ) {
|
||||
$title = wp_date( 'M j', $range[0]->getTimestamp() ) . ' – ' . wp_date( 'M j, Y', $range[1]->modify( '-1 day' )->getTimestamp() );
|
||||
}
|
||||
}
|
||||
?>
|
||||
<nav class="be-date-nav" aria-label="<?php esc_attr_e( 'Calendar dates', 'burn-events' ); ?>">
|
||||
<a href="<?php echo esc_url( add_query_arg( array_replace( $state, [ 'be_date' => $previous->format( 'Y-m-d' ) ] ), $base ) ); ?>" aria-label="<?php esc_attr_e( 'Previous date range', 'burn-events' ); ?>">‹</a>
|
||||
<h2><?php echo esc_html( $title ); ?></h2>
|
||||
<a href="<?php echo esc_url( add_query_arg( array_replace( $state, [ 'be_date' => $next->format( 'Y-m-d' ) ] ), $base ) ); ?>" aria-label="<?php esc_attr_e( 'Next date range', 'burn-events' ); ?>">›</a>
|
||||
<a class="be-today" href="<?php echo esc_url( add_query_arg( array_replace( $state, [ 'be_date' => false ] ), $base ) ); ?>"><?php esc_html_e( 'Today', 'burn-events' ); ?></a>
|
||||
</nav>
|
||||
<?php
|
||||
}
|
||||
|
||||
public static function event_location( array $data ): string {
|
||||
$venue = Events::locations( $data['venue'], Events::VENUE )[0] ?? null;
|
||||
return $venue ? get_the_title( $venue ) : $data['location'];
|
||||
}
|
||||
|
||||
public static function event_excerpt( int $id ): string {
|
||||
$excerpt = get_post_field( 'post_excerpt', $id ) ?: get_post_field( 'post_content', $id );
|
||||
return wp_trim_words( wp_strip_all_tags( strip_shortcodes( $excerpt ) ), 27 );
|
||||
}
|
||||
|
||||
private static function card( array $row, string $view ): void {
|
||||
$id = (int) $row['event_id'];
|
||||
$data = Events::event_data( $id );
|
||||
$zone = $data['schedule']['timezone'] ?? wp_timezone_string();
|
||||
$start = Events::local_time( $row['starts_at'], $zone );
|
||||
$link = Events::event_url( $row );
|
||||
$location = self::event_location( $data );
|
||||
?>
|
||||
<article class="be-event-card">
|
||||
<?php if ( 'photo' === $view && has_post_thumbnail( $id ) ) : ?><a class="be-card-image" href="<?php echo esc_url( $link ); ?>" tabindex="-1" aria-hidden="true"><?php echo get_the_post_thumbnail( $id, 'large', [ 'loading' => 'lazy' ] ); ?></a><?php endif; ?>
|
||||
<time class="be-date-tile" datetime="<?php echo esc_attr( $start->format( DATE_ATOM ) ); ?>"><span><?php echo esc_html( wp_date( 'M', $start->getTimestamp(), $start->getTimezone() ) ); ?></span><strong><?php echo esc_html( $start->format( 'j' ) ); ?></strong></time>
|
||||
<div class="be-card-body">
|
||||
<p class="be-meta"><?php echo esc_html( self::period( $row, $data ) ); ?></p>
|
||||
<h3><a href="<?php echo esc_url( $link ); ?>"><?php echo esc_html( get_the_title( $id ) ); ?></a></h3>
|
||||
<?php if ( $location ) : ?><p class="be-meta"><?php echo esc_html( $location ); ?></p><?php endif; ?>
|
||||
<?php self::status( $data ); ?>
|
||||
<?php if ( 'list' === $view || 'photo' === $view ) : ?><p><?php echo esc_html( self::event_excerpt( $id ) ); ?></p><?php endif; ?>
|
||||
</div>
|
||||
</article>
|
||||
<?php
|
||||
}
|
||||
|
||||
private static function status( array $data ): void {
|
||||
if ( 'scheduled' !== $data['status'] ) {
|
||||
echo '<span class="be-status">' . esc_html( Events::statuses()[ $data['status'] ] ?? '' ) . '</span>';
|
||||
} elseif ( $data['featured'] ) {
|
||||
echo '<span class="be-status">' . esc_html__( 'Featured', 'burn-events' ) . '</span>';
|
||||
}
|
||||
}
|
||||
|
||||
public static function period( array $row, array $data ): string {
|
||||
$zone = $data['schedule']['timezone'] ?? wp_timezone_string();
|
||||
$start = Events::local_time( $row['starts_at'], $zone );
|
||||
$end = Events::local_time( $row['ends_at'], $zone );
|
||||
$timezone = $start->getTimezone();
|
||||
$date = (string) get_option( 'date_format' );
|
||||
$time = (string) get_option( 'time_format' );
|
||||
$start_label = wp_date( $date, $start->getTimestamp(), $timezone );
|
||||
if ( ! empty( $data['schedule']['all_day'] ) ) {
|
||||
$last = $end->modify( '-1 day' );
|
||||
return ( $start->format( 'Y-m-d' ) === $last->format( 'Y-m-d' ) ? $start_label : $start_label . ' – ' . wp_date( $date, $last->getTimestamp(), $timezone ) )
|
||||
. ' · ' . __( 'All day', 'burn-events' );
|
||||
}
|
||||
$end_label = $start->format( 'Y-m-d' ) === $end->format( 'Y-m-d' ) ? '' : wp_date( $date, $end->getTimestamp(), $timezone ) . ', ';
|
||||
return $start_label . ' · ' . wp_date( $time, $start->getTimestamp(), $timezone ) . ' – ' . $end_label . wp_date( $time . ' T', $end->getTimestamp(), $timezone );
|
||||
}
|
||||
|
||||
private static function linked( WP_Post $post ): string {
|
||||
if ( post_password_required( $post ) ) {
|
||||
return '<main class="be-single">' . get_the_password_form( $post ) . '</main>';
|
||||
}
|
||||
$type = array_search( $post->post_type, Events::RELATIONS, true );
|
||||
$data = Events::location_data( $post->ID );
|
||||
ob_start();
|
||||
?>
|
||||
<header class="be-linked-header">
|
||||
<a href="<?php echo esc_url( self::archive_url() ); ?>"><?php esc_html_e( 'All events', 'burn-events' ); ?></a>
|
||||
<h1><?php echo esc_html( get_the_title( $post ) ); ?></h1>
|
||||
<?php self::contact( $data ); ?>
|
||||
<?php
|
||||
$view = self::request( 'be_view' ) ?: (string) get_query_var( 'be_view' ) ?: Admin::options()['view'];
|
||||
if ( Events::VENUE === $post->post_type && 'map' !== $view ) {
|
||||
echo Map_View::venues( [ $post ] );
|
||||
}
|
||||
?>
|
||||
<?php echo apply_filters( 'the_content', $post->post_content ); ?>
|
||||
</header>
|
||||
<?php
|
||||
echo self::render( [ 'relation' => [ $type, $post->ID ], 'title' => __( 'Upcoming events', 'burn-events' ) ] );
|
||||
return ob_get_clean();
|
||||
}
|
||||
|
||||
private static function contact( array $data ): void {
|
||||
$address = array_filter( array_intersect_key( $data, array_flip( [ 'address', 'city', 'region', 'postal', 'country' ] ) ) );
|
||||
if ( $address ) {
|
||||
echo '<p>' . esc_html( implode( ', ', $address ) ) . '</p>';
|
||||
}
|
||||
if ( $data['phone'] ) {
|
||||
echo '<p><a href="tel:' . esc_attr( preg_replace( '/[^0-9+]/', '', $data['phone'] ) ) . '">' . esc_html( $data['phone'] ) . '</a></p>';
|
||||
}
|
||||
if ( $data['email'] ) {
|
||||
echo '<p><a href="' . esc_url( 'mailto:' . $data['email'] ) . '">' . esc_html( $data['email'] ) . '</a></p>';
|
||||
}
|
||||
if ( $data['website'] ) {
|
||||
echo '<p><a href="' . esc_url( $data['website'] ) . '">' . esc_html__( 'Website', 'burn-events' ) . '</a></p>';
|
||||
}
|
||||
}
|
||||
|
||||
private static function single( WP_Post $event ): string {
|
||||
if ( post_password_required( $event ) ) {
|
||||
return '<article class="be-single"><h1>' . esc_html( get_the_title( $event ) ) . '</h1>' . get_the_password_form( $event ) . '</article>';
|
||||
}
|
||||
$row = Events::occurrence( $event->ID, self::request( 'be_occ' ) );
|
||||
$data = Events::event_data( $event->ID );
|
||||
self::schema( $event, $row, $data );
|
||||
$layout = Single_Event_Templates::render( $event, $row );
|
||||
if ( $layout ) {
|
||||
if ( ! str_contains( $layout, 'data-be-event-map="' . $event->ID . '"' ) ) {
|
||||
$map = Map_View::venues( Events::locations( $data['venue'], Events::VENUE ), $event->ID );
|
||||
if ( $map ) {
|
||||
$layout .= '<section class="be-single-map"><h2>' . esc_html__( 'Event location', 'burn-events' ) . '</h2>' . $map . '</section>';
|
||||
}
|
||||
}
|
||||
return '<article class="be-single be-custom-single">' . $layout . '</article>';
|
||||
}
|
||||
ob_start();
|
||||
?>
|
||||
<article class="be-single">
|
||||
<header class="be-single-header">
|
||||
<?php echo self::field( 'back', $event, $row ); ?>
|
||||
<?php echo self::field( 'title', $event, $row ); ?>
|
||||
<?php echo self::field( 'schedule', $event, $row ); ?>
|
||||
<?php echo self::field( 'status', $event, $row ); ?>
|
||||
</header>
|
||||
<?php echo self::field( 'image', $event, $row ); ?>
|
||||
<div class="be-single-columns">
|
||||
<div>
|
||||
<?php echo self::field( 'description', $event, $row ); ?>
|
||||
<?php echo self::field( 'fields', $event, $row ); ?>
|
||||
<?php echo self::field( 'export', $event, $row ); ?>
|
||||
</div>
|
||||
<aside class="be-single-details" aria-label="<?php esc_attr_e( 'Event details', 'burn-events' ); ?>">
|
||||
<?php foreach ( [ 'cost', 'venue', 'organizer', 'series', 'website', 'terms' ] as $field ) { echo self::field( $field, $event, $row ); } ?>
|
||||
</aside>
|
||||
</div>
|
||||
<?php echo self::field( 'related', $event, $row ); ?>
|
||||
</article>
|
||||
<?php
|
||||
return ob_get_clean();
|
||||
}
|
||||
|
||||
public static function fields(): array {
|
||||
return [
|
||||
'title' => __( 'Event title', 'burn-events' ), 'schedule' => __( 'Date and time', 'burn-events' ),
|
||||
'description' => __( 'Description', 'burn-events' ), 'image' => __( 'Featured image', 'burn-events' ),
|
||||
'status' => __( 'Status', 'burn-events' ), 'cost' => __( 'Cost', 'burn-events' ),
|
||||
'venue' => __( 'Venue', 'burn-events' ), 'organizer' => __( 'Organizers', 'burn-events' ), 'series' => __( 'Series', 'burn-events' ),
|
||||
'website' => __( 'Website', 'burn-events' ), 'fields' => __( 'Custom fields', 'burn-events' ),
|
||||
'terms' => __( 'Categories and tags', 'burn-events' ), 'related' => __( 'Related events', 'burn-events' ),
|
||||
'export' => __( 'Add to calendar', 'burn-events' ), 'back' => __( 'All events link', 'burn-events' ),
|
||||
];
|
||||
}
|
||||
|
||||
public static function field( string $field, WP_Post $event, ?array $row ): string {
|
||||
$data = Events::event_data( $event->ID );
|
||||
ob_start();
|
||||
switch ( $field ) {
|
||||
case 'title':
|
||||
echo '<h1 class="be-event-title">' . esc_html( get_the_title( $event ) ) . '</h1>';
|
||||
break;
|
||||
case 'back':
|
||||
echo '<a class="be-back" href="' . esc_url( self::archive_url() ) . '">← ' . esc_html__( 'All events', 'burn-events' ) . '</a>';
|
||||
break;
|
||||
case 'schedule':
|
||||
if ( $row ) {
|
||||
echo '<p class="be-single-date">' . esc_html( self::period( $row, $data ) ) . '</p>';
|
||||
}
|
||||
break;
|
||||
case 'status':
|
||||
self::status( $data );
|
||||
break;
|
||||
case 'image':
|
||||
if ( has_post_thumbnail( $event ) ) {
|
||||
echo '<figure class="be-single-image">' . get_the_post_thumbnail( $event, 'large' ) . '</figure>';
|
||||
}
|
||||
break;
|
||||
case 'description':
|
||||
self::description( $event );
|
||||
break;
|
||||
case 'cost':
|
||||
if ( '' !== $data['cost'] ) {
|
||||
echo '<p class="be-cost">' . esc_html( '0' === $data['cost'] ? __( 'Free', 'burn-events' ) : $data['cost'] ) . '</p>';
|
||||
}
|
||||
break;
|
||||
case 'venue':
|
||||
case 'organizer':
|
||||
case 'series':
|
||||
self::relation( $field, $data, $event->ID );
|
||||
break;
|
||||
case 'website':
|
||||
if ( $data['url'] ) {
|
||||
echo '<p><a class="be-button" href="' . esc_url( $data['url'] ) . '">' . esc_html__( 'Event website', 'burn-events' ) . '</a></p>';
|
||||
}
|
||||
break;
|
||||
case 'fields':
|
||||
self::custom_fields( $data );
|
||||
break;
|
||||
case 'terms':
|
||||
foreach ( [ Events::CATEGORY, 'post_tag' ] as $taxonomy ) {
|
||||
$terms = get_the_term_list( $event->ID, $taxonomy, '<p class="be-term-links">', ' · ', '</p>' );
|
||||
if ( is_string( $terms ) ) {
|
||||
echo wp_kses_post( $terms );
|
||||
}
|
||||
}
|
||||
break;
|
||||
case 'export':
|
||||
if ( $row ) {
|
||||
echo '<p class="be-export-links"><a href="' . esc_url( Transfer::ics_url( $row ) ) . '">' . esc_html__( 'Download .ics', 'burn-events' ) . '</a><a href="' . esc_url( Transfer::google_url( $event, $row, $data ) ) . '">' . esc_html__( 'Google Calendar', 'burn-events' ) . '</a></p>';
|
||||
}
|
||||
break;
|
||||
case 'related':
|
||||
self::related( $event );
|
||||
break;
|
||||
}
|
||||
return ob_get_clean();
|
||||
}
|
||||
|
||||
private static function description( WP_Post $event ): void {
|
||||
static $rendering = false;
|
||||
if ( $rendering || '' === $event->post_content ) {
|
||||
return;
|
||||
}
|
||||
global $post;
|
||||
$previous = $post;
|
||||
$post = $event;
|
||||
$rendering = true;
|
||||
try {
|
||||
echo '<div class="be-description">' . apply_filters( 'the_content', $event->post_content ) . '</div>';
|
||||
} finally {
|
||||
$post = $previous;
|
||||
$rendering = false;
|
||||
}
|
||||
}
|
||||
|
||||
private static function relation( string $type, array $data, int $event_id ): void {
|
||||
$posts = Events::locations( $data[ $type ], Events::RELATIONS[ $type ] );
|
||||
if ( ! $posts && ( 'venue' !== $type || ! $data['location'] ) ) {
|
||||
return;
|
||||
}
|
||||
echo '<section class="be-related-detail"><h2>' . esc_html( self::fields()[ $type ] ) . '</h2>';
|
||||
if ( 'venue' === $type && $data['location'] ) {
|
||||
echo '<p>' . esc_html( $data['location'] ) . '</p>';
|
||||
}
|
||||
foreach ( $posts as $item ) {
|
||||
echo '<p><a href="' . esc_url( get_permalink( $item ) ) . '">' . esc_html( get_the_title( $item ) ) . '</a></p>';
|
||||
if ( 'series' !== $type ) {
|
||||
$place = Events::location_data( $item->ID );
|
||||
self::contact( $place );
|
||||
}
|
||||
}
|
||||
if ( 'venue' === $type ) {
|
||||
echo Map_View::venues( $posts, $event_id );
|
||||
}
|
||||
echo '</section>';
|
||||
}
|
||||
|
||||
private static function custom_fields( array $data ): void {
|
||||
$display = '';
|
||||
foreach ( Admin::options()['fields'] as $key => $field ) {
|
||||
$value = $data['fields'][ $key ] ?? '';
|
||||
if ( '' === $value ) {
|
||||
continue;
|
||||
}
|
||||
$display .= '<dt>' . esc_html( $field['label'] ) . '</dt><dd>';
|
||||
$display .= 'url' === $field['type']
|
||||
? '<a href="' . esc_url( $value ) . '">' . esc_html( $value ) . '</a>'
|
||||
: esc_html( 'checkbox' === $field['type'] ? __( 'Yes', 'burn-events' ) : $value );
|
||||
$display .= '</dd>';
|
||||
}
|
||||
if ( $display ) {
|
||||
echo '<dl class="be-custom-fields">' . $display . '</dl>';
|
||||
}
|
||||
}
|
||||
|
||||
private static function related( WP_Post $event ): void {
|
||||
$terms = wp_get_post_terms( $event->ID, Events::CATEGORY, [ 'fields' => 'slugs' ] );
|
||||
if ( is_wp_error( $terms ) || ! $terms ) {
|
||||
return;
|
||||
}
|
||||
$rows = Events::query( [ 'category' => $terms[0], 'from' => gmdate( 'Y-m-d H:i:s' ), 'limit' => 25 ] );
|
||||
$related = [ $event->ID => true ];
|
||||
ob_start();
|
||||
foreach ( $rows as $row ) {
|
||||
if ( ! isset( $related[ $row['event_id'] ] ) ) {
|
||||
self::card( $row, 'summary' );
|
||||
$related[ $row['event_id'] ] = true;
|
||||
}
|
||||
if ( count( $related ) >= 4 ) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
$html = ob_get_clean();
|
||||
if ( $html ) {
|
||||
echo '<section class="be-related-events"><h2>' . esc_html__( 'Related events', 'burn-events' ) . '</h2><div class="be-event-list be-view-summary">' . $html . '</div></section>';
|
||||
}
|
||||
}
|
||||
|
||||
private static function schema( WP_Post $post, ?array $row, array $data ): void {
|
||||
if ( ! $row || 'publish' !== $post->post_status || $post->post_password ) {
|
||||
return;
|
||||
}
|
||||
$zone = $data['schedule']['timezone'];
|
||||
$format = $data['schedule']['all_day'] ? 'Y-m-d' : DATE_ATOM;
|
||||
$details = [
|
||||
'@context' => 'https://schema.org', '@type' => 'Event', 'name' => get_the_title( $post ),
|
||||
'url' => Events::event_url( $row ), 'startDate' => Events::local_time( $row['starts_at'], $zone )->format( $format ),
|
||||
'endDate' => Events::local_time( $row['ends_at'], $zone )->format( $format ),
|
||||
'eventStatus' => 'https://schema.org/' . ( [ 'cancelled' => 'EventCancelled', 'postponed' => 'EventPostponed', 'moved_online' => 'EventMovedOnline' ][ $data['status'] ] ?? 'EventScheduled' ),
|
||||
];
|
||||
$image = get_the_post_thumbnail_url( $post, 'large' );
|
||||
if ( $image ) {
|
||||
$details['image'] = $image;
|
||||
}
|
||||
$venue = Events::locations( $data['venue'], Events::VENUE )[0] ?? null;
|
||||
if ( $venue ) {
|
||||
$details['location'] = [ '@type' => 'Place', 'name' => get_the_title( $venue ), 'url' => get_permalink( $venue ) ];
|
||||
}
|
||||
self::$schema = '<script type="application/ld+json">' . wp_json_encode( $details, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT ) . '</script>';
|
||||
}
|
||||
|
||||
public static function register_api(): void {
|
||||
register_rest_route( 'burn-events/v1', '/events', [
|
||||
'methods' => 'GET', 'permission_callback' => '__return_true',
|
||||
'callback' => static function ( \WP_REST_Request $request ): \WP_REST_Response {
|
||||
$limit = max( 1, min( 50, absint( $request->get_param( 'limit' ) ?: 20 ) ) );
|
||||
$rows = Events::query( [
|
||||
'from' => gmdate( 'Y-m-d H:i:s' ),
|
||||
'search' => sanitize_text_field( $request->get_param( 'search' ) ?? '' ),
|
||||
'category' => sanitize_title( (string) $request->get_param( 'category' ) ),
|
||||
'limit' => $limit,
|
||||
'offset' => ( max( 1, min( 10000, absint( $request->get_param( 'page' ) ) ) ) - 1 ) * $limit,
|
||||
] );
|
||||
return rest_ensure_response( array_map( static function ( array $row ): array {
|
||||
return [
|
||||
'id' => (int) $row['event_id'], 'title' => get_the_title( (int) $row['event_id'] ),
|
||||
'start_utc' => gmdate( DATE_ATOM, strtotime( $row['starts_at'] . ' UTC' ) ),
|
||||
'end_utc' => gmdate( DATE_ATOM, strtotime( $row['ends_at'] . ' UTC' ) ),
|
||||
'url' => Events::event_url( $row ),
|
||||
];
|
||||
}, $rows ) );
|
||||
},
|
||||
] );
|
||||
}
|
||||
}
|
||||
197
includes/class-clubs.php
Normal file
197
includes/class-clubs.php
Normal file
@@ -0,0 +1,197 @@
|
||||
<?php
|
||||
|
||||
namespace BurnEvents;
|
||||
|
||||
use RuntimeException;
|
||||
use WP_REST_Request;
|
||||
use WP_Term;
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
final class Clubs {
|
||||
public const EVENT_META = '_eventlabs_sub_club';
|
||||
private const TAXONOMY = 'eventlabs_club_directory';
|
||||
private const DETAILS = '_eventlabs_club_details';
|
||||
private const BACKFILL = 'eventlabs_club_backfill';
|
||||
|
||||
public static function register(): void {
|
||||
register_taxonomy( self::TAXONOMY, [], [
|
||||
'public' => false, 'show_ui' => false, 'show_in_rest' => false, 'rewrite' => false, 'query_var' => false,
|
||||
] );
|
||||
register_post_meta( Events::EVENT, self::EVENT_META, [ 'type' => 'string', 'single' => true, 'default' => '', 'show_in_rest' => false ] );
|
||||
}
|
||||
|
||||
public static function register_api(): void {
|
||||
$base = '/burnworks/workspaces/(?P<workspace_id>' . BurnWorks::UUID . ')/clubs';
|
||||
register_rest_route( Api::NAMESPACE, $base, [
|
||||
'methods' => 'GET', 'callback' => [ self::class, 'listing' ], 'permission_callback' => [ Api::class, 'permission' ],
|
||||
] );
|
||||
register_rest_route( Api::NAMESPACE, $base . '/(?P<club_id>' . BurnWorks::UUID . ')', [
|
||||
'methods' => 'PUT', 'callback' => [ self::class, 'put' ], 'permission_callback' => [ Api::class, 'permission' ],
|
||||
] );
|
||||
}
|
||||
|
||||
public static function schema(): array {
|
||||
return [
|
||||
'type' => 'object', 'required' => [ 'name', 'kind' ], 'additionalProperties' => false,
|
||||
'properties' => [
|
||||
'name' => [ 'type' => 'string', 'minLength' => 1, 'maxLength' => 120 ],
|
||||
'kind' => [ 'type' => 'string', 'enum' => [ 'organization', 'subclub' ] ],
|
||||
'status' => [ 'type' => 'string', 'enum' => [ 'active', 'archived' ] ],
|
||||
'workspace_name' => [ 'type' => 'string', 'maxLength' => 120 ],
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
public static function put( WP_REST_Request $request ) {
|
||||
$input = $request->get_json_params();
|
||||
$schema = self::schema();
|
||||
$valid = rest_validate_value_from_schema( $input, $schema, 'body' );
|
||||
if ( is_wp_error( $valid ) ) {
|
||||
$valid->add_data( [ 'status' => 400 ] );
|
||||
return $valid;
|
||||
}
|
||||
$params = $request->get_url_params();
|
||||
$scope = strtolower( $params['workspace_id'] . ':' . $params['club_id'] );
|
||||
$name = sanitize_text_field( $input['name'] );
|
||||
if ( '' === $name ) {
|
||||
return Api::error( 'club_name', __( 'Enter a club name.', 'burn-events' ), 400 );
|
||||
}
|
||||
try {
|
||||
$term = self::ensure( $scope );
|
||||
$previous = self::record( $term );
|
||||
$details = [
|
||||
'name' => $name, 'kind' => $input['kind'], 'status' => $input['status'] ?? $previous['status'],
|
||||
'workspace_name' => sanitize_text_field( $input['workspace_name'] ?? $previous['workspace_name'] ),
|
||||
];
|
||||
$saved = update_term_meta( $term->term_id, self::DETAILS, wp_slash( $details ) );
|
||||
if ( is_wp_error( $saved ) || $details !== get_term_meta( $term->term_id, self::DETAILS, true ) ) {
|
||||
throw new RuntimeException( 'Club details write failed.' );
|
||||
}
|
||||
return Api::response( self::record( $term ) );
|
||||
} catch ( \Throwable $error ) {
|
||||
return Api::error( 'club_write', __( 'The club could not be saved.', 'burn-events' ), 500 );
|
||||
}
|
||||
}
|
||||
|
||||
public static function listing( WP_REST_Request $request ): \WP_REST_Response {
|
||||
$workspace = strtolower( $request->get_url_params()['workspace_id'] );
|
||||
$items = array_values( array_filter( self::directory(), static fn( array $record ): bool => $workspace === $record['workspace_id'] ) );
|
||||
return Api::response( [ 'items' => $items ] );
|
||||
}
|
||||
|
||||
public static function event( int $id ): ?array {
|
||||
$term = self::find( (string) get_post_meta( $id, self::EVENT_META, true ) );
|
||||
return $term ? self::record( $term ) : null;
|
||||
}
|
||||
|
||||
public static function assign( int $id, string $scope, bool $discover = false ): void {
|
||||
$scope = strtolower( $scope );
|
||||
if ( '' !== $scope ) {
|
||||
if ( ! preg_match( '/^' . BurnWorks::UUID . ':' . BurnWorks::UUID . '$/D', $scope ) ) {
|
||||
throw new \InvalidArgumentException( __( 'Use a burnWorks workspace and club ID for the sub-club.', 'burn-events' ) );
|
||||
}
|
||||
if ( $discover ) {
|
||||
self::ensure( $scope );
|
||||
} elseif ( ! self::find( $scope ) ) {
|
||||
throw new \InvalidArgumentException( __( 'Sync this club from burnWorks before assigning it.', 'burn-events' ) );
|
||||
}
|
||||
}
|
||||
Events::write_meta( $id, self::EVENT_META, $scope );
|
||||
}
|
||||
|
||||
private static function slug( string $scope ): string {
|
||||
return str_replace( ':', '_', $scope );
|
||||
}
|
||||
|
||||
private static function find( string $scope ): ?WP_Term {
|
||||
$term = $scope ? get_term_by( 'slug', self::slug( $scope ), self::TAXONOMY ) : null;
|
||||
return $term instanceof WP_Term ? $term : null;
|
||||
}
|
||||
|
||||
private static function ensure( string $scope ): WP_Term {
|
||||
$term = self::find( $scope );
|
||||
if ( $term ) {
|
||||
return $term;
|
||||
}
|
||||
wp_insert_term( $scope, self::TAXONOMY, [ 'slug' => self::slug( $scope ) ] );
|
||||
return self::find( $scope ) ?? throw new RuntimeException( 'Club directory write failed.' );
|
||||
}
|
||||
|
||||
private static function record( WP_Term $term ): array {
|
||||
[ $workspace, $club ] = explode( '_', $term->slug, 2 );
|
||||
$details = (array) get_term_meta( $term->term_id, self::DETAILS, true );
|
||||
return [ 'workspace_id' => $workspace, 'club_id' => $club, 'scope' => $workspace . ':' . $club ] + $details + [
|
||||
'name' => sprintf( __( 'Club %s', 'burn-events' ), substr( $club, 0, 8 ) ),
|
||||
'kind' => 'unknown', 'status' => 'active', 'workspace_name' => '',
|
||||
];
|
||||
}
|
||||
|
||||
private static function directory(): array {
|
||||
$terms = get_terms( [ 'taxonomy' => self::TAXONOMY, 'hide_empty' => false ] );
|
||||
return is_array( $terms ) ? array_map( [ self::class, 'record' ], $terms ) : [];
|
||||
}
|
||||
|
||||
public static function options(): array {
|
||||
$directory = self::directory();
|
||||
$names = $workspaces = $clubs = [];
|
||||
foreach ( $directory as $club ) {
|
||||
if ( $club['workspace_name'] ) {
|
||||
$names[ $club['workspace_id'] ] = $club['workspace_name'];
|
||||
}
|
||||
}
|
||||
foreach ( $directory as $club ) {
|
||||
$workspace = $names[ $club['workspace_id'] ] ?? sprintf( __( 'Workspace %s', 'burn-events' ), substr( $club['workspace_id'], 0, 8 ) );
|
||||
$workspaces[ $club['workspace_id'] ] = sprintf( __( '%s (all clubs)', 'burn-events' ), $workspace );
|
||||
$label = $workspace . ' / ' . $club['name'];
|
||||
$clubs[ $club['scope'] ] = 'archived' === $club['status'] ? sprintf( __( '%s (archived)', 'burn-events' ), $label ) : $label;
|
||||
}
|
||||
natcasesort( $workspaces );
|
||||
natcasesort( $clubs );
|
||||
return [ '' => __( 'All events', 'burn-events' ) ] + $workspaces + $clubs;
|
||||
}
|
||||
|
||||
public static function condition( string $scope ): string {
|
||||
global $wpdb;
|
||||
$scope = strtolower( $scope );
|
||||
if ( ! preg_match( '/^' . BurnWorks::UUID . '(?::' . BurnWorks::UUID . ')?$/D', $scope ) ) {
|
||||
return '1=0';
|
||||
}
|
||||
$exact = str_contains( $scope, ':' );
|
||||
$operator = $exact ? '=' : 'LIKE';
|
||||
$value = $exact ? $scope : $wpdb->esc_like( $scope . ':' ) . '%';
|
||||
return $wpdb->prepare( "EXISTS (SELECT 1 FROM $wpdb->postmeta c WHERE c.post_id = p.ID AND c.meta_key = %s AND c.meta_value $operator %s)", self::EVENT_META, $value );
|
||||
}
|
||||
|
||||
public static function backfill(): void {
|
||||
global $wpdb;
|
||||
$cursor = get_option( self::BACKFILL, 0 );
|
||||
if ( 'done' === $cursor ) {
|
||||
return;
|
||||
}
|
||||
$ids = $wpdb->get_col( $wpdb->prepare( "SELECT DISTINCT p.ID FROM $wpdb->posts p JOIN $wpdb->postmeta m ON m.post_id = p.ID AND m.meta_key = %s WHERE p.post_type = %s AND p.ID > %d ORDER BY p.ID LIMIT 50", BurnWorks::META, Events::EVENT, (int) $cursor ) );
|
||||
if ( $wpdb->last_error ) {
|
||||
return;
|
||||
}
|
||||
foreach ( $ids as $id ) {
|
||||
try {
|
||||
Events::transaction( static function () use ( $id ): void {
|
||||
if ( ! Events::lock_post( (int) $id ) || get_post_meta( $id, self::EVENT_META, true ) ) {
|
||||
return;
|
||||
}
|
||||
$record = BurnWorks::snapshot( (int) $id );
|
||||
if ( isset( $record['workspace_id'], $record['club_id'] ) ) {
|
||||
self::assign( (int) $id, $record['workspace_id'] . ':' . $record['club_id'], true );
|
||||
}
|
||||
} );
|
||||
} catch ( \InvalidArgumentException $error ) {
|
||||
// Ignore snapshots without a valid club identity.
|
||||
} catch ( \Throwable $error ) {
|
||||
return;
|
||||
} finally {
|
||||
wp_cache_delete( $id, 'post_meta' );
|
||||
}
|
||||
}
|
||||
update_option( self::BACKFILL, count( $ids ) < 50 ? 'done' : (string) end( $ids ), false );
|
||||
}
|
||||
}
|
||||
213
includes/class-community.php
Normal file
213
includes/class-community.php
Normal file
@@ -0,0 +1,213 @@
|
||||
<?php
|
||||
|
||||
namespace BurnEvents;
|
||||
|
||||
use WP_Post;
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
final class Community {
|
||||
public static function register(): void {
|
||||
add_shortcode( 'burn_events_submit', [ self::class, 'form' ] );
|
||||
add_shortcode( 'burn_events_mine', [ self::class, 'mine' ] );
|
||||
add_rewrite_rule( '^events/(submit|mine)/?$', 'index.php?be_community=$matches[1]', 'top' );
|
||||
add_filter( 'redirect_canonical', static fn( $url ) => get_query_var( 'be_community' ) ? false : $url );
|
||||
add_filter( 'document_title_parts', static function ( array $parts ): array {
|
||||
$view = get_query_var( 'be_community' );
|
||||
if ( in_array( $view, [ 'submit', 'mine' ], true ) ) {
|
||||
$parts['title'] = 'mine' === $view ? __( 'My events', 'burn-events' ) : __( 'Submit an event', 'burn-events' );
|
||||
}
|
||||
return $parts;
|
||||
} );
|
||||
add_action( 'template_redirect', static function (): void {
|
||||
if ( get_query_var( 'be_community' ) ) {
|
||||
nocache_headers();
|
||||
}
|
||||
} );
|
||||
add_action( 'admin_post_burn_event_submit', [ self::class, 'submit' ] );
|
||||
add_action( 'admin_post_nopriv_burn_event_submit', [ self::class, 'submit' ] );
|
||||
add_action( 'admin_post_burn_event_withdraw', [ self::class, 'withdraw' ] );
|
||||
}
|
||||
|
||||
public static function url( string $view ): string {
|
||||
return get_option( 'permalink_structure' )
|
||||
? home_url( user_trailingslashit( 'events/' . $view ) )
|
||||
: add_query_arg( 'be_community', $view, home_url( '/' ) );
|
||||
}
|
||||
|
||||
private static function owned( int $id ): ?WP_Post {
|
||||
$post = $id && is_user_logged_in() ? get_post( $id ) : null;
|
||||
return $post && Events::EVENT === $post->post_type && 'trash' !== $post->post_status
|
||||
&& (int) $post->post_author === get_current_user_id() && get_post_meta( $post->ID, '_burn_community', true ) ? $post : null;
|
||||
}
|
||||
|
||||
public static function form(): string {
|
||||
$options = Admin::options();
|
||||
$id = absint( Calendar::request( 'be_edit' ) );
|
||||
$post = $id && $options['community_edit'] ? self::owned( $id ) : null;
|
||||
ob_start();
|
||||
?>
|
||||
<section class="be-community">
|
||||
<header class="be-calendar-header">
|
||||
<h1><?php echo esc_html( $post ? __( 'Edit your event', 'burn-events' ) : __( 'Submit an event', 'burn-events' ) ); ?></h1>
|
||||
<?php if ( is_user_logged_in() ) : ?><a href="<?php echo esc_url( self::url( 'mine' ) ); ?>"><?php esc_html_e( 'My events', 'burn-events' ); ?></a><?php endif; ?>
|
||||
</header>
|
||||
<?php if ( '1' === Calendar::request( 'be_sent' ) ) : ?>
|
||||
<p class="be-confirmation" role="status"><?php esc_html_e( 'Your event was submitted for review.', 'burn-events' ); ?></p>
|
||||
<?php endif; ?>
|
||||
<?php if ( ! is_user_logged_in() && ! $options['anonymous'] ) : ?>
|
||||
<p><a class="be-button" href="<?php echo esc_url( wp_login_url( self::url( 'submit' ) ) ); ?>"><?php esc_html_e( 'Log in to submit an event', 'burn-events' ); ?></a></p>
|
||||
<?php elseif ( $id && ! $post ) : ?>
|
||||
<p><?php esc_html_e( 'This submission is unavailable for editing.', 'burn-events' ); ?></p>
|
||||
<?php else : ?>
|
||||
<form class="be-submission" method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" enctype="multipart/form-data">
|
||||
<input type="hidden" name="action" value="burn_event_submit">
|
||||
<input type="hidden" name="event_id" value="<?php echo esc_attr( (string) $id ); ?>">
|
||||
<?php wp_nonce_field( 'burn_event_submit_' . $id ); ?>
|
||||
<p><?php esc_html_e( 'Submissions are reviewed before they appear on the calendar.', 'burn-events' ); ?></p>
|
||||
<label><?php esc_html_e( 'Event title', 'burn-events' ); ?><input name="event_title" required maxlength="180" value="<?php echo esc_attr( $post->post_title ?? '' ); ?>"></label>
|
||||
<label><?php esc_html_e( 'Description', 'burn-events' ); ?><textarea name="event_description" rows="6" maxlength="12000" required><?php echo esc_textarea( $post->post_content ?? '' ); ?></textarea></label>
|
||||
<?php
|
||||
$defaults = [ 'venue' => array_filter( [ $options['venue'] ] ), 'organizer' => array_filter( [ $options['organizer'] ] ) ];
|
||||
Admin::event_fields( $post ? Events::event_data( $id ) : $defaults, true );
|
||||
$terms = get_terms( [ 'taxonomy' => Events::CATEGORY, 'hide_empty' => false ] );
|
||||
$selected = $post ? wp_get_post_terms( $id, Events::CATEGORY, [ 'fields' => 'ids' ] ) : [];
|
||||
?>
|
||||
<?php if ( $terms && ! is_wp_error( $terms ) ) : ?>
|
||||
<label><?php esc_html_e( 'Event categories', 'burn-events' ); ?><select name="event_categories[]" multiple size="3"><?php foreach ( $terms as $term ) : ?><option value="<?php echo esc_attr( (string) $term->term_id ); ?>" <?php selected( is_array( $selected ) && in_array( $term->term_id, $selected, true ) ); ?>><?php echo esc_html( $term->name ); ?></option><?php endforeach; ?></select></label>
|
||||
<?php endif; ?>
|
||||
<?php if ( is_user_logged_in() ) : ?><label><?php esc_html_e( 'Featured image', 'burn-events' ); ?><input name="event_image" type="file" accept="image/jpeg,image/png,image/webp"></label><?php endif; ?>
|
||||
<label class="be-honeypot" aria-hidden="true"><?php esc_html_e( 'Leave this blank', 'burn-events' ); ?><input name="be_website" tabindex="-1" autocomplete="off"></label>
|
||||
<button class="be-button" type="submit"><?php esc_html_e( 'Send for review', 'burn-events' ); ?></button>
|
||||
</form>
|
||||
<?php endif; ?>
|
||||
</section>
|
||||
<?php
|
||||
return ob_get_clean();
|
||||
}
|
||||
|
||||
public static function submit(): void {
|
||||
$id = isset( $_POST['event_id'] ) && is_scalar( $_POST['event_id'] ) ? absint( $_POST['event_id'] ) : 0;
|
||||
check_admin_referer( 'burn_event_submit_' . $id );
|
||||
$options = Admin::options();
|
||||
$post = $id && $options['community_edit'] ? self::owned( $id ) : null;
|
||||
if ( ( ! is_user_logged_in() && ! $options['anonymous'] ) || ( $id && ! $post ) || ! empty( $_POST['be_website'] ) ) {
|
||||
self::fail( __( 'This submission is unavailable.', 'burn-events' ), 403 );
|
||||
}
|
||||
$rate_key = 'be_submit_' . hash_hmac( 'sha256', (string) ( $_SERVER['REMOTE_ADDR'] ?? '' ) . '/' . get_current_user_id(), wp_salt() );
|
||||
if ( get_transient( $rate_key ) ) {
|
||||
self::fail( __( 'Please wait a moment before submitting again.', 'burn-events' ), 429 );
|
||||
}
|
||||
$title = isset( $_POST['event_title'] ) && is_string( $_POST['event_title'] ) ? sanitize_text_field( wp_unslash( $_POST['event_title'] ) ) : '';
|
||||
$body = isset( $_POST['event_description'] ) && is_string( $_POST['event_description'] ) ? wp_kses_post( wp_unslash( $_POST['event_description'] ) ) : '';
|
||||
// Public submissions contain formatted text. Shortcodes are added by editors during review.
|
||||
$body = str_replace( '[', '[', $body );
|
||||
if ( ! $title || ! $body || strlen( $title ) > 720 || strlen( $body ) > 48000 || ! is_array( $_POST['be'] ?? null ) ) {
|
||||
self::fail( __( 'Enter a title, description, and event schedule.', 'burn-events' ) );
|
||||
}
|
||||
$event = null;
|
||||
try {
|
||||
$input = wp_unslash( $_POST['be'] );
|
||||
unset( $input['status'], $input['series'], $input['featured'], $input['hidden'] );
|
||||
$data = Events::validate_event( $input );
|
||||
if ( $post ) {
|
||||
$old = Events::event_data( $id );
|
||||
foreach ( [ 'status', 'series', 'featured', 'hidden' ] as $field ) {
|
||||
$data[ $field ] = $old[ $field ];
|
||||
}
|
||||
}
|
||||
$attributes = [
|
||||
'post_type' => Events::EVENT, 'post_title' => $title, 'post_content' => $body,
|
||||
'post_status' => 'pending', 'comment_status' => 'closed',
|
||||
];
|
||||
$event = $id ? wp_update_post( wp_slash( $attributes + [ 'ID' => $id ] ), true ) : wp_insert_post( wp_slash( $attributes + [ 'post_author' => get_current_user_id() ] ), true );
|
||||
if ( is_wp_error( $event ) ) {
|
||||
self::fail( $event->get_error_message() );
|
||||
}
|
||||
Events::save( $event, $data );
|
||||
update_post_meta( $event, '_burn_community', '1' );
|
||||
$categories = array_values( array_filter( array_map( 'absint', (array) ( $_POST['event_categories'] ?? [] ) ) ) );
|
||||
wp_set_object_terms( $event, $categories, Events::CATEGORY );
|
||||
if ( is_user_logged_in() && UPLOAD_ERR_OK === ( $_FILES['event_image']['error'] ?? UPLOAD_ERR_NO_FILE ) ) {
|
||||
self::image( $event );
|
||||
}
|
||||
} catch ( \Throwable $error ) {
|
||||
if ( ! $id && is_int( $event ) ) {
|
||||
wp_trash_post( $event );
|
||||
}
|
||||
self::fail( $error->getMessage() );
|
||||
}
|
||||
set_transient( $rate_key, '1', 10 );
|
||||
wp_safe_redirect( add_query_arg( 'be_sent', '1', self::url( 'submit' ) ), 303 );
|
||||
exit;
|
||||
}
|
||||
|
||||
private static function image( int $event ): void {
|
||||
require_once ABSPATH . 'wp-admin/includes/file.php';
|
||||
require_once ABSPATH . 'wp-admin/includes/media.php';
|
||||
require_once ABSPATH . 'wp-admin/includes/image.php';
|
||||
$file = media_handle_upload( 'event_image', $event, [], [
|
||||
'test_form' => false,
|
||||
'mimes' => [ 'jpg|jpeg' => 'image/jpeg', 'png' => 'image/png', 'webp' => 'image/webp' ],
|
||||
] );
|
||||
if ( ! is_wp_error( $file ) ) {
|
||||
set_post_thumbnail( $event, $file );
|
||||
}
|
||||
}
|
||||
|
||||
public static function mine(): string {
|
||||
$page = max( 1, min( 1000, absint( Calendar::request( 'be_page' ) ) ) );
|
||||
$list = is_user_logged_in() ? new \WP_Query( [
|
||||
'post_type' => Events::EVENT, 'post_status' => [ 'publish', 'pending', 'draft', 'future' ],
|
||||
'author' => get_current_user_id(), 'posts_per_page' => 20, 'paged' => $page,
|
||||
'meta_key' => '_burn_community', 'meta_value' => '1',
|
||||
] ) : null;
|
||||
ob_start();
|
||||
?>
|
||||
<section class="be-community">
|
||||
<header class="be-calendar-header"><h1><?php esc_html_e( 'My events', 'burn-events' ); ?></h1><a href="<?php echo esc_url( self::url( 'submit' ) ); ?>"><?php esc_html_e( 'Submit an event', 'burn-events' ); ?></a></header>
|
||||
<?php if ( ! $list ) : ?>
|
||||
<p><a class="be-button" href="<?php echo esc_url( wp_login_url( self::url( 'mine' ) ) ); ?>"><?php esc_html_e( 'Log in to see your submissions', 'burn-events' ); ?></a></p>
|
||||
<?php elseif ( ! $list->posts ) : ?>
|
||||
<p class="be-empty"><?php esc_html_e( 'You have no submissions on this page.', 'burn-events' ); ?></p>
|
||||
<?php else : ?>
|
||||
<ul class="be-submission-list">
|
||||
<?php foreach ( $list->posts as $post ) : ?>
|
||||
<li>
|
||||
<strong><?php echo esc_html( get_the_title( $post ) ); ?></strong>
|
||||
<span><?php echo esc_html( get_post_status_object( $post->post_status )->label ); ?></span>
|
||||
<?php if ( 'publish' === $post->post_status ) : ?><a href="<?php echo esc_url( get_permalink( $post ) ); ?>"><?php esc_html_e( 'View', 'burn-events' ); ?></a><?php endif; ?>
|
||||
<?php if ( Admin::options()['community_edit'] ) : ?>
|
||||
<a href="<?php echo esc_url( add_query_arg( 'be_edit', $post->ID, self::url( 'submit' ) ) ); ?>"><?php esc_html_e( 'Edit', 'burn-events' ); ?></a>
|
||||
<form method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
|
||||
<input type="hidden" name="action" value="burn_event_withdraw">
|
||||
<input type="hidden" name="event_id" value="<?php echo esc_attr( (string) $post->ID ); ?>">
|
||||
<?php wp_nonce_field( 'burn_event_withdraw_' . $post->ID ); ?>
|
||||
<button type="submit"><?php esc_html_e( 'Withdraw', 'burn-events' ); ?></button>
|
||||
</form>
|
||||
<?php endif; ?>
|
||||
</li>
|
||||
<?php endforeach; ?>
|
||||
</ul>
|
||||
<?php echo wp_kses_post( paginate_links( [ 'base' => add_query_arg( 'be_page', '%#%', self::url( 'mine' ) ), 'format' => '', 'total' => $list->max_num_pages, 'current' => $page ] ) ); ?>
|
||||
<?php endif; ?>
|
||||
</section>
|
||||
<?php
|
||||
return ob_get_clean();
|
||||
}
|
||||
|
||||
public static function withdraw(): void {
|
||||
$id = isset( $_POST['event_id'] ) && is_scalar( $_POST['event_id'] ) ? absint( $_POST['event_id'] ) : 0;
|
||||
check_admin_referer( 'burn_event_withdraw_' . $id );
|
||||
if ( ! Admin::options()['community_edit'] || ! self::owned( $id ) ) {
|
||||
self::fail( __( 'You cannot withdraw this event.', 'burn-events' ), 403 );
|
||||
}
|
||||
wp_trash_post( $id );
|
||||
wp_safe_redirect( self::url( 'mine' ), 303 );
|
||||
exit;
|
||||
}
|
||||
|
||||
private static function fail( string $message, int $status = 400 ): void {
|
||||
wp_die( esc_html( $message ), esc_html__( 'Event submission', 'burn-events' ), [ 'response' => $status, 'back_link' => true ] );
|
||||
}
|
||||
}
|
||||
288
includes/class-elementor-widgets.php
Normal file
288
includes/class-elementor-widgets.php
Normal file
@@ -0,0 +1,288 @@
|
||||
<?php
|
||||
|
||||
namespace BurnEvents;
|
||||
|
||||
use Elementor\Controls_Manager;
|
||||
use Elementor\Group_Control_Typography;
|
||||
use Elementor\Plugin as Elementor;
|
||||
use Elementor\Widget_Base;
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
abstract class Burn_Widget extends Widget_Base {
|
||||
public function get_categories(): array {
|
||||
return [ 'burn-events' ];
|
||||
}
|
||||
|
||||
protected function is_dynamic_content(): bool {
|
||||
return true;
|
||||
}
|
||||
|
||||
protected function start_display_controls(): void {
|
||||
$this->start_controls_section( 'display', [ 'label' => __( 'Display', 'burn-events' ) ] );
|
||||
}
|
||||
|
||||
protected function event_id_control(): void {
|
||||
$this->add_control( 'event_id', [
|
||||
'label' => __( 'Event ID', 'burn-events' ),
|
||||
'description' => __( 'Leave blank to use the current event or the template preview event.', 'burn-events' ),
|
||||
'type' => Controls_Manager::NUMBER,
|
||||
'min' => 1,
|
||||
] );
|
||||
}
|
||||
}
|
||||
|
||||
class Event_Field_Widget extends Burn_Widget {
|
||||
protected const FIELD = '';
|
||||
|
||||
public function get_name(): string {
|
||||
return static::FIELD ? 'burn-events-event-' . static::FIELD : 'burn-events-field';
|
||||
}
|
||||
|
||||
public function get_title(): string {
|
||||
return match ( static::FIELD ) {
|
||||
'title' => __( 'Event Title', 'burn-events' ),
|
||||
'schedule' => __( 'Event Date and Time', 'burn-events' ),
|
||||
'description' => __( 'Event Description', 'burn-events' ),
|
||||
'image' => __( 'Event Image', 'burn-events' ),
|
||||
'venue' => __( 'Event Venue', 'burn-events' ),
|
||||
'organizer' => __( 'Event Organizer', 'burn-events' ),
|
||||
'cost' => __( 'Event Cost', 'burn-events' ),
|
||||
'export' => __( 'Event Calendar Links', 'burn-events' ),
|
||||
'related' => __( 'Related Events', 'burn-events' ),
|
||||
default => __( 'Event Field', 'burn-events' ),
|
||||
};
|
||||
}
|
||||
|
||||
public function get_icon(): string {
|
||||
return 'eicon-post-content';
|
||||
}
|
||||
|
||||
protected function register_controls(): void {
|
||||
$this->start_display_controls();
|
||||
if ( ! static::FIELD ) {
|
||||
$this->add_control( 'field', [
|
||||
'label' => __( 'Event field', 'burn-events' ), 'type' => Controls_Manager::SELECT,
|
||||
'options' => Calendar::fields(), 'default' => 'title',
|
||||
] );
|
||||
}
|
||||
$this->event_id_control();
|
||||
$this->end_controls_section();
|
||||
|
||||
$this->start_controls_section( 'appearance', [ 'label' => __( 'Text', 'burn-events' ), 'tab' => Controls_Manager::TAB_STYLE ] );
|
||||
$this->add_group_control( Group_Control_Typography::get_type(), [
|
||||
'name' => 'field_typography',
|
||||
'selector' => '{{WRAPPER}} .be-elementor-field, {{WRAPPER}} .be-elementor-field :is(h1, h2, p, a, dt, dd)',
|
||||
] );
|
||||
$this->add_control( 'text_color', [
|
||||
'label' => __( 'Text color', 'burn-events' ), 'type' => Controls_Manager::COLOR,
|
||||
'selectors' => [ '{{WRAPPER}} .be-elementor-field, {{WRAPPER}} .be-elementor-field :is(h1, h2, p, a, dt, dd)' => 'color: {{VALUE}};' ],
|
||||
] );
|
||||
$this->end_controls_section();
|
||||
}
|
||||
|
||||
protected function render(): void {
|
||||
[ $event, $row ] = Single_Event_Templates::widget_context( (int) $this->get_settings_for_display( 'event_id' ) );
|
||||
$field = static::FIELD ?: (string) $this->get_settings_for_display( 'field' );
|
||||
if ( $event ) {
|
||||
echo '<div class="be-elementor-field">' . Calendar::field( $field, $event, $row ) . '</div>';
|
||||
} elseif ( Elementor::instance()->editor->is_edit_mode() || Elementor::instance()->preview->is_preview_mode() ) {
|
||||
$label = Calendar::fields()[ $field ] ?? __( 'Event field', 'burn-events' );
|
||||
echo '<p class="be-widget-preview">' . esc_html( $label ) . '</p>';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final class Event_Title_Widget extends Event_Field_Widget {
|
||||
protected const FIELD = 'title';
|
||||
}
|
||||
|
||||
final class Event_Date_Widget extends Event_Field_Widget {
|
||||
protected const FIELD = 'schedule';
|
||||
}
|
||||
|
||||
final class Event_Description_Widget extends Event_Field_Widget {
|
||||
protected const FIELD = 'description';
|
||||
}
|
||||
|
||||
final class Event_Image_Widget extends Event_Field_Widget {
|
||||
protected const FIELD = 'image';
|
||||
}
|
||||
|
||||
final class Event_Venue_Widget extends Event_Field_Widget {
|
||||
protected const FIELD = 'venue';
|
||||
|
||||
public function get_script_depends(): array {
|
||||
return Admin::options()['maps'] ? [ Map_View::SCRIPT ] : [];
|
||||
}
|
||||
|
||||
public function get_style_depends(): array {
|
||||
return Admin::options()['maps'] ? [ Map_View::STYLE ] : [];
|
||||
}
|
||||
}
|
||||
|
||||
final class Event_Organizer_Widget extends Event_Field_Widget {
|
||||
protected const FIELD = 'organizer';
|
||||
}
|
||||
|
||||
final class Event_Cost_Widget extends Event_Field_Widget {
|
||||
protected const FIELD = 'cost';
|
||||
}
|
||||
|
||||
final class Event_Calendar_Links_Widget extends Event_Field_Widget {
|
||||
protected const FIELD = 'export';
|
||||
}
|
||||
|
||||
final class Event_Related_Widget extends Event_Field_Widget {
|
||||
protected const FIELD = 'related';
|
||||
}
|
||||
|
||||
final class Event_Details_Widget extends Burn_Widget {
|
||||
public function get_name(): string {
|
||||
return 'burn-events-event-details';
|
||||
}
|
||||
|
||||
public function get_title(): string {
|
||||
return __( 'Event Details', 'burn-events' );
|
||||
}
|
||||
|
||||
public function get_icon(): string {
|
||||
return 'eicon-post-content';
|
||||
}
|
||||
|
||||
protected function register_controls(): void {
|
||||
$this->start_display_controls();
|
||||
$this->event_id_control();
|
||||
$this->add_control( 'fields', [
|
||||
'label' => __( 'Show fields', 'burn-events' ), 'type' => Controls_Manager::SELECT2,
|
||||
'options' => Calendar::fields(), 'multiple' => true,
|
||||
'default' => [ 'title', 'schedule', 'description', 'venue', 'export' ],
|
||||
] );
|
||||
$this->end_controls_section();
|
||||
}
|
||||
|
||||
protected function render(): void {
|
||||
[ $event, $row ] = Single_Event_Templates::widget_context( (int) $this->get_settings_for_display( 'event_id' ) );
|
||||
if ( $event ) {
|
||||
echo '<div class="be-elementor-field">';
|
||||
foreach ( (array) $this->get_settings_for_display( 'fields' ) as $field ) {
|
||||
echo Calendar::field( (string) $field, $event, $row );
|
||||
}
|
||||
echo '</div>';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class Calendar_Widget extends Burn_Widget {
|
||||
protected const LIST_ONLY = false;
|
||||
|
||||
public function get_script_depends(): array {
|
||||
return static::LIST_ONLY ? [] : [ Calendar_Grid::SCRIPT ];
|
||||
}
|
||||
|
||||
public function get_name(): string {
|
||||
return static::LIST_ONLY ? 'burn-events-list' : 'burn-events-calendar';
|
||||
}
|
||||
|
||||
public function get_title(): string {
|
||||
return static::LIST_ONLY ? __( 'Event List', 'burn-events' ) : __( 'Event Calendar', 'burn-events' );
|
||||
}
|
||||
|
||||
public function get_icon(): string {
|
||||
return 'eicon-calendar';
|
||||
}
|
||||
|
||||
protected function register_controls(): void {
|
||||
$this->start_display_controls();
|
||||
if ( ! static::LIST_ONLY ) {
|
||||
$this->add_control( 'view', [ 'label' => __( 'View', 'burn-events' ), 'type' => Controls_Manager::SELECT, 'options' => Calendar::view_labels(), 'default' => 'list' ] );
|
||||
$this->add_control( 'filters', [ 'label' => __( 'Show search and navigation', 'burn-events' ), 'type' => Controls_Manager::SWITCHER, 'default' => 'yes' ] );
|
||||
}
|
||||
$this->add_control( 'heading', [ 'label' => __( 'Heading', 'burn-events' ), 'type' => Controls_Manager::TEXT, 'default' => __( 'Events', 'burn-events' ) ] );
|
||||
$this->add_control( 'category', [ 'label' => __( 'Category slug', 'burn-events' ), 'type' => Controls_Manager::TEXT ] );
|
||||
$this->add_control( 'tag', [ 'label' => __( 'Tag slug', 'burn-events' ), 'type' => Controls_Manager::TEXT ] );
|
||||
$this->add_control( 'club_scope', [
|
||||
'label' => __( 'Club or sub-club', 'burn-events' ), 'type' => Controls_Manager::SELECT2, 'options' => Clubs::options(), 'default' => '',
|
||||
] );
|
||||
$this->add_control( 'location', [ 'label' => __( 'Location', 'burn-events' ), 'type' => Controls_Manager::TEXT ] );
|
||||
$this->add_control( 'limit', [ 'label' => __( 'Events per page', 'burn-events' ), 'type' => Controls_Manager::NUMBER, 'min' => 1, 'max' => 50, 'default' => 12 ] );
|
||||
$this->add_control( 'featured', [ 'label' => __( 'Featured events only', 'burn-events' ), 'type' => Controls_Manager::SWITCHER ] );
|
||||
$this->end_controls_section();
|
||||
}
|
||||
|
||||
protected function render(): void {
|
||||
$settings = $this->get_settings_for_display();
|
||||
echo Calendar::render( [
|
||||
'view' => $settings['view'] ?? 'list', 'title' => $settings['heading'], 'category' => $settings['category'] ?? '',
|
||||
'tag' => $settings['tag'] ?? '', 'location' => $settings['location'] ?? '', 'limit' => $settings['limit'],
|
||||
'scope' => $settings['club_scope'] ?? '',
|
||||
'filters' => 'yes' === ( $settings['filters'] ?? '' ) ? 'yes' : 'no', 'featured' => $settings['featured'] ?? '',
|
||||
] );
|
||||
}
|
||||
}
|
||||
|
||||
final class Event_List_Widget extends Calendar_Widget {
|
||||
protected const LIST_ONLY = true;
|
||||
}
|
||||
|
||||
final class Countdown_Widget extends Burn_Widget {
|
||||
public function get_name(): string {
|
||||
return 'burn-events-countdown';
|
||||
}
|
||||
|
||||
public function get_title(): string {
|
||||
return __( 'Event Countdown', 'burn-events' );
|
||||
}
|
||||
|
||||
public function get_icon(): string {
|
||||
return 'eicon-countdown';
|
||||
}
|
||||
|
||||
protected function register_controls(): void {
|
||||
$this->start_display_controls();
|
||||
$this->event_id_control();
|
||||
$this->end_controls_section();
|
||||
}
|
||||
|
||||
protected function render(): void {
|
||||
[ $event, $row ] = Single_Event_Templates::widget_context( (int) $this->get_settings_for_display( 'event_id' ) );
|
||||
if ( ! $event || ! $row ) {
|
||||
return;
|
||||
}
|
||||
wp_enqueue_script( 'burn-events' );
|
||||
$start = strtotime( $row['starts_at'] . ' UTC' );
|
||||
printf(
|
||||
'<time class="be-countdown" datetime="%1$s" data-be-countdown="%2$d" data-be-started="%3$s">%4$s</time>',
|
||||
esc_attr( gmdate( DATE_ATOM, $start ) ), $start,
|
||||
esc_attr__( 'Event has started', 'burn-events' ), esc_html( Calendar::period( $row, Events::event_data( $event->ID ) ) )
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
final class Community_Widget extends Burn_Widget {
|
||||
public function get_name(): string {
|
||||
return 'burn-events-community';
|
||||
}
|
||||
|
||||
public function get_title(): string {
|
||||
return __( 'Community Events', 'burn-events' );
|
||||
}
|
||||
|
||||
public function get_icon(): string {
|
||||
return 'eicon-form-horizontal';
|
||||
}
|
||||
|
||||
protected function register_controls(): void {
|
||||
$this->start_display_controls();
|
||||
$this->add_control( 'view', [
|
||||
'label' => __( 'Community view', 'burn-events' ), 'type' => Controls_Manager::SELECT,
|
||||
'options' => [ 'submit' => __( 'Submit an event', 'burn-events' ), 'mine' => __( 'My events', 'burn-events' ) ],
|
||||
'default' => 'submit',
|
||||
] );
|
||||
$this->end_controls_section();
|
||||
}
|
||||
|
||||
protected function render(): void {
|
||||
echo 'mine' === $this->get_settings_for_display( 'view' ) ? Community::mine() : Community::form();
|
||||
}
|
||||
}
|
||||
423
includes/class-events.php
Normal file
423
includes/class-events.php
Normal file
@@ -0,0 +1,423 @@
|
||||
<?php
|
||||
|
||||
namespace BurnEvents;
|
||||
|
||||
use DateTimeImmutable;
|
||||
use DateTimeZone;
|
||||
use RuntimeException;
|
||||
use WP_Post;
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
final class Events {
|
||||
public const EVENT = 'burn_event';
|
||||
public const VENUE = 'burn_venue';
|
||||
public const ORGANIZER = 'burn_organizer';
|
||||
public const SERIES = 'burn_series';
|
||||
public const CATEGORY = 'burn_event_category';
|
||||
public const RELATIONS = [ 'venue' => 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, 'past' => false, 'search' => '', 'category' => '', 'tag' => '', 'location' => '', 'relation' => null, 'scope' => '', 'featured' => false, '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['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 ] ) {
|
||||
$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 = %s)", $taxonomy, $filters[ $key ] );
|
||||
}
|
||||
}
|
||||
if ( $filters['relation'] ) {
|
||||
[ $type, $id ] = $filters['relation'];
|
||||
$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 = %s)", '_burn_' . $type, (string) $id );
|
||||
}
|
||||
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'] ) {
|
||||
$where[] = "EXISTS (SELECT 1 FROM $wpdb->postmeta f WHERE f.post_id = p.ID AND f.meta_key = '_burn_featured' AND f.meta_value = '1')";
|
||||
}
|
||||
$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'] ) );
|
||||
}
|
||||
}
|
||||
333
includes/class-legacy-migration.php
Normal file
333
includes/class-legacy-migration.php
Normal file
@@ -0,0 +1,333 @@
|
||||
<?php
|
||||
|
||||
namespace BurnEvents;
|
||||
|
||||
use DateTimeImmutable;
|
||||
use DateTimeZone;
|
||||
use InvalidArgumentException;
|
||||
use RuntimeException;
|
||||
use WP_Post;
|
||||
use WP_REST_Request;
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
final class Legacy_Migration {
|
||||
public const SOURCE = 'calendar-migration';
|
||||
private const EVENT = 'tribe_events';
|
||||
private const CATEGORY = 'tribe_events_cat';
|
||||
private const BATCH = 8;
|
||||
private const ACTION = 'burn_events_legacy_migrate';
|
||||
private const TYPES = [ 'venue' => 'tribe_venue', 'organizer' => 'tribe_organizer', 'series' => 'tribe_event_series' ];
|
||||
|
||||
public static function register(): void {
|
||||
add_action( 'admin_notices', [ self::class, 'notice' ] );
|
||||
add_action( 'wp_ajax_' . self::ACTION, [ self::class, 'ajax' ] );
|
||||
}
|
||||
|
||||
public static function notice(): void {
|
||||
$screen = get_current_screen();
|
||||
if ( ! current_user_can( 'manage_options' ) || ! $screen || 'edit' !== $screen->base || Events::EVENT !== $screen->post_type || isset( $_GET['page'] ) || ! self::count() ) {
|
||||
return;
|
||||
}
|
||||
$url = admin_url( 'edit.php?post_type=burn_event&page=burn-events-transfer#eventlabs-migration' );
|
||||
echo '<div class="notice notice-info"><p>' . esc_html__( 'The Events Calendar data was found on this site.', 'burn-events' )
|
||||
. ' <a href="' . esc_url( $url ) . '">' . esc_html__( 'Review event migration', 'burn-events' ) . '</a></p></div>';
|
||||
}
|
||||
|
||||
private static function installed(): bool {
|
||||
require_once ABSPATH . 'wp-admin/includes/plugin.php';
|
||||
foreach ( get_plugins() as $path => $plugin ) {
|
||||
if ( 'the-events-calendar/the-events-calendar.php' === $path || 'the-events-calendar' === $plugin['TextDomain'] ) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static function count(): int {
|
||||
global $wpdb;
|
||||
return (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->posts WHERE post_type = %s AND post_status NOT IN ('trash', 'auto-draft', 'inherit')", self::EVENT ) );
|
||||
}
|
||||
|
||||
public static function section(): void {
|
||||
$count = self::count();
|
||||
if ( ! $count && ! self::installed() ) {
|
||||
return;
|
||||
}
|
||||
?>
|
||||
<section id="eventlabs-migration">
|
||||
<h2><?php esc_html_e( 'Migrate from The Events Calendar', 'burn-events' ); ?></h2>
|
||||
<?php if ( ! $count ) : ?>
|
||||
<p><?php esc_html_e( 'The plugin is installed. No events are available to migrate.', 'burn-events' ); ?></p>
|
||||
<?php else : ?>
|
||||
<p><?php printf( esc_html( _n( '%s source event found.', '%s source events found.', $count, 'burn-events' ) ), esc_html( number_format_i18n( $count ) ) ); ?></p>
|
||||
<p><?php esc_html_e( 'Copy events as drafts with their saved dates, linked venues, organizers and series, categories, tags, and featured images. The source events stay available for review.', 'burn-events' ); ?></p>
|
||||
<p><?php esc_html_e( 'Imported recurring events use the dates already saved in the source calendar. Set a new repeat rule to generate new dates.', 'burn-events' ); ?></p>
|
||||
<form data-be-migrate action="<?php echo esc_url( admin_url( 'admin-ajax.php' ) ); ?>" method="post">
|
||||
<input type="hidden" name="action" value="<?php echo esc_attr( self::ACTION ); ?>">
|
||||
<?php wp_nonce_field( self::ACTION ); ?>
|
||||
<button type="submit" class="button button-primary" disabled><?php esc_html_e( 'Copy events as drafts', 'burn-events' ); ?></button>
|
||||
<p data-be-migrate-status role="status"></p>
|
||||
<ul data-be-migrate-errors></ul>
|
||||
</form>
|
||||
<?php wp_enqueue_script( 'burn-events-migration', plugins_url( 'assets/migration.js', BURN_EVENTS_FILE ), [ 'wp-i18n' ], BURN_EVENTS_VERSION, true ); ?>
|
||||
<?php endif; ?>
|
||||
</section>
|
||||
<?php
|
||||
}
|
||||
|
||||
public static function ajax(): void {
|
||||
if ( ! current_user_can( 'manage_options' ) || ! check_ajax_referer( self::ACTION, '_wpnonce', false ) ) {
|
||||
wp_send_json_error( __( 'Refresh the migration page and sign in as an administrator.', 'burn-events' ), 403 );
|
||||
}
|
||||
$after = is_scalar( $_POST['after'] ?? null ) ? absint( $_POST['after'] ) : 0;
|
||||
try {
|
||||
wp_send_json_success( self::batch( $after ) );
|
||||
} catch ( \Throwable $error ) {
|
||||
wp_send_json_error( __( 'The source calendar could not be read. You can retry the migration.', 'burn-events' ), 500 );
|
||||
}
|
||||
}
|
||||
|
||||
public static function batch( int $after ): array {
|
||||
global $wpdb;
|
||||
$ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_type = %s AND ID > %d AND post_status NOT IN ('trash', 'auto-draft', 'inherit') ORDER BY ID LIMIT %d", self::EVENT, $after, self::BATCH + 1 ) );
|
||||
if ( $wpdb->last_error ) {
|
||||
throw new RuntimeException( 'Source event query failed.' );
|
||||
}
|
||||
$result = [ 'copied' => 0, 'skipped' => 0, 'errors' => [], 'next' => 0 ];
|
||||
$more = count( $ids ) > self::BATCH;
|
||||
foreach ( array_slice( $ids, 0, self::BATCH ) as $id ) {
|
||||
$after = (int) $id;
|
||||
try {
|
||||
++$result[ self::event( $after ) ];
|
||||
} catch ( InvalidArgumentException $error ) {
|
||||
$result['errors'][] = sprintf( __( 'Event #%1$d — %2$s', 'burn-events' ), $after, $error->getMessage() );
|
||||
} catch ( \Throwable $error ) {
|
||||
$result['errors'][] = sprintf( __( 'Event #%d could not be copied.', 'burn-events' ), $after );
|
||||
}
|
||||
}
|
||||
$result['next'] = $more ? $after : 0;
|
||||
return $result;
|
||||
}
|
||||
|
||||
private static function event( int $id ): string {
|
||||
$source = get_post( $id );
|
||||
if ( ! $source || self::EVENT !== $source->post_type || 'trash' === $source->post_status ) {
|
||||
throw new InvalidArgumentException( __( 'The source event is unavailable.', 'burn-events' ) );
|
||||
}
|
||||
if ( self::copied( 'events', $id ) ) {
|
||||
return 'skipped';
|
||||
}
|
||||
[ $schedule, $dates ] = self::schedule( $id );
|
||||
$status = match ( self::meta( $id, '_tribe_events_status' ) ) {
|
||||
'canceled', 'cancelled' => 'cancelled',
|
||||
'postponed' => 'postponed',
|
||||
'moved-online', 'moved_online' => 'moved_online',
|
||||
default => 'scheduled',
|
||||
};
|
||||
$costs = array_filter( get_post_meta( $id, '_EventCost', false ), static fn( $cost ): bool => is_scalar( $cost ) && '' !== (string) $cost );
|
||||
$payload = self::post_fields( $source ) + self::event_terms( $id ) + [
|
||||
'post_status' => 'draft', 'schedule' => $schedule, 'imported_dates' => $dates, 'status' => $status,
|
||||
'cost' => implode( ' – ', array_unique( $costs ) ),
|
||||
'url' => self::meta( $id, '_EventURL' ), 'featured' => self::flag( $id, '_tribe_featured' ),
|
||||
'hidden' => self::flag( $id, '_EventHideFromUpcoming' ),
|
||||
'metadata' => [ 'migration' => [ 'source_post_id' => $id, 'source_status' => $source->post_status, 'saved_dates' => count( $dates ) ] ],
|
||||
];
|
||||
foreach ( self::TYPES as $type => $post_type ) {
|
||||
$payload[ $type ] = [];
|
||||
$links = 'series' === $type ? self::series_ids( $id ) : get_post_meta( $id, '_Event' . ucfirst( $type ) . 'ID', false );
|
||||
foreach ( array_unique( array_filter( array_map( 'absint', $links ) ) ) as $linked_id ) {
|
||||
$linked = get_post( $linked_id );
|
||||
if ( $linked && $post_type === $linked->post_type && 'trash' !== $linked->post_status ) {
|
||||
$payload[ $type ][] = self::linked( $type, $linked );
|
||||
}
|
||||
}
|
||||
}
|
||||
$created = self::create( 'events', $id, $payload );
|
||||
return 201 === $created->get_status() ? 'copied' : 'skipped';
|
||||
}
|
||||
|
||||
private static function post_fields( WP_Post $source ): array {
|
||||
$image = get_post_thumbnail_id( $source );
|
||||
return [
|
||||
'title' => $source->post_title ?: __( 'Untitled event', 'burn-events' ),
|
||||
'description' => $source->post_content, 'excerpt' => $source->post_excerpt, 'slug' => $source->post_name,
|
||||
'featured_media' => $image && wp_attachment_is_image( $image ) ? $image : 0,
|
||||
];
|
||||
}
|
||||
|
||||
private static function linked( string $type, WP_Post $source ): int {
|
||||
$id = $source->ID;
|
||||
$resource = 'series' === $type ? 'series' : $type . 's';
|
||||
$saved = self::copied( $resource, $id );
|
||||
if ( $saved ) {
|
||||
return $saved;
|
||||
}
|
||||
$payload = self::post_fields( $source ) + [
|
||||
'post_status' => 'publish' === $source->post_status && '' === $source->post_password ? 'publish' : 'draft',
|
||||
];
|
||||
$fields = match ( $type ) {
|
||||
'venue' => [
|
||||
'address' => '_VenueAddress', 'city' => '_VenueCity', 'region' => '_VenueStateProvince',
|
||||
'postal' => '_VenueZip', 'country' => '_VenueCountry', 'phone' => '_VenuePhone', 'website' => '_VenueURL',
|
||||
],
|
||||
'organizer' => [ 'phone' => '_OrganizerPhone', 'website' => '_OrganizerWebsite', 'email' => '_OrganizerEmail' ],
|
||||
default => [],
|
||||
};
|
||||
foreach ( $fields as $field => $key ) {
|
||||
$payload[ $field ] = self::meta( $id, $key );
|
||||
}
|
||||
if ( 'venue' === $type && ! $payload['region'] ) {
|
||||
$payload['region'] = self::meta( $id, '_VenueState' ) ?: self::meta( $id, '_VenueProvince' );
|
||||
}
|
||||
$created = self::create( $resource, $id, $payload );
|
||||
return (int) $created->get_data()['id'];
|
||||
}
|
||||
|
||||
private static function copied( string $resource, int $source_id ): int {
|
||||
$record = Api::external( $resource, self::SOURCE, (string) $source_id );
|
||||
if ( is_wp_error( $record ) ) {
|
||||
if ( 410 === ( $record->get_error_data()['status'] ?? 0 ) ) {
|
||||
throw new InvalidArgumentException( __( 'The previously migrated copy was removed.', 'burn-events' ) );
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
return (int) $record->get_data()['id'];
|
||||
}
|
||||
|
||||
private static function create( string $resource, int $source_id, array $payload ): \WP_REST_Response {
|
||||
$request = new WP_REST_Request( 'PUT' );
|
||||
$request->set_header( 'If-None-Match', '*' );
|
||||
$result = Api::write( $resource, $payload, $request, 0, [ self::SOURCE, (string) $source_id ] );
|
||||
if ( is_wp_error( $result ) ) {
|
||||
if ( 412 === ( $result->get_error_data()['status'] ?? 0 ) ) {
|
||||
$existing = Api::external( $resource, self::SOURCE, (string) $source_id );
|
||||
if ( ! is_wp_error( $existing ) ) {
|
||||
return $existing;
|
||||
}
|
||||
}
|
||||
throw new InvalidArgumentException( $result->get_error_message() );
|
||||
}
|
||||
return $result;
|
||||
}
|
||||
|
||||
private static function source_table( string $suffix ): string {
|
||||
global $wpdb;
|
||||
static $tables = [];
|
||||
$table = $wpdb->prefix . $suffix;
|
||||
return $tables[ $table ] ??= ( $table === $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->esc_like( $table ) ) ) ? $table : '' );
|
||||
}
|
||||
|
||||
private static function series_ids( int $id ): array {
|
||||
global $wpdb;
|
||||
$table = self::source_table( 'tec_series_relationships' );
|
||||
return $table ? $wpdb->get_col( $wpdb->prepare( "SELECT series_post_id FROM $table WHERE event_post_id = %d", $id ) ) : [];
|
||||
}
|
||||
|
||||
private static function schedule( int $id ): array {
|
||||
global $wpdb;
|
||||
$utc = new DateTimeZone( 'UTC' );
|
||||
try {
|
||||
$zone = new DateTimeZone( self::meta( $id, '_EventTimezone' ) ?: wp_timezone_string() );
|
||||
} catch ( \Exception $error ) {
|
||||
$zone = wp_timezone();
|
||||
}
|
||||
$table = self::source_table( 'tec_occurrences' );
|
||||
$rows = $table ? $wpdb->get_results( $wpdb->prepare( "SELECT start_date_utc, end_date_utc FROM $table WHERE post_id = %d ORDER BY start_date_utc", $id ), ARRAY_N ) : [];
|
||||
if ( $table && $wpdb->last_error ) {
|
||||
throw new InvalidArgumentException( __( 'The saved occurrences could not be read.', 'burn-events' ) );
|
||||
}
|
||||
$all_day = self::flag( $id, '_EventAllDay' );
|
||||
$dates = [];
|
||||
$schedule = null;
|
||||
if ( ! $rows ) {
|
||||
$start = self::meta_date( $id, '_EventStartDate', $zone, $utc );
|
||||
$end = self::meta_date( $id, '_EventEndDate', $zone, $utc );
|
||||
$rows = [ [ $start, $end ] ];
|
||||
}
|
||||
foreach ( $rows as [ $start, $end ] ) {
|
||||
$from = self::date( $start, $utc )->setTimezone( $zone );
|
||||
$to = self::date( $end, $utc )->setTimezone( $zone );
|
||||
if ( $all_day ) {
|
||||
$from = $from->setTime( 0, 0 );
|
||||
$to = '00:00:00' === $to->format( 'H:i:s' ) ? $to : $to->modify( 'tomorrow' )->setTime( 0, 0 );
|
||||
}
|
||||
if ( $to <= $from ) {
|
||||
throw new InvalidArgumentException( __( 'A source occurrence ends at or before its start.', 'burn-events' ) );
|
||||
}
|
||||
$last_day = $all_day ? $to->modify( '-1 day' ) : $to;
|
||||
$schedule ??= [
|
||||
'start_date' => $from->format( 'Y-m-d' ), 'start_time' => $from->format( 'H:i:s' ),
|
||||
'end_date' => $last_day->format( 'Y-m-d' ), 'end_time' => $to->format( 'H:i:s' ),
|
||||
'timezone' => $zone->getName(), 'all_day' => $all_day, 'repeat' => 'none',
|
||||
];
|
||||
$key = $from->setTimezone( $utc )->format( 'Y-m-d H:i:s' );
|
||||
$end_utc = $to->setTimezone( $utc )->format( 'Y-m-d H:i:s' );
|
||||
if ( isset( $dates[ $key ] ) && $end_utc !== $dates[ $key ][1] ) {
|
||||
throw new InvalidArgumentException( __( 'Two source occurrences share a start time with different end times.', 'burn-events' ) );
|
||||
}
|
||||
$dates[ $key ] = [ $key, $end_utc ];
|
||||
}
|
||||
return [ $schedule, array_values( $dates ) ];
|
||||
}
|
||||
|
||||
private static function meta_date( int $id, string $key, DateTimeZone $zone, DateTimeZone $utc ): string {
|
||||
$value = self::meta( $id, $key . 'UTC' );
|
||||
$date = $value && '0000-00-00 00:00:00' !== $value ? self::date( $value, $utc ) : self::date( self::meta( $id, $key ), $zone );
|
||||
return $date->setTimezone( $utc )->format( 'Y-m-d H:i:s' );
|
||||
}
|
||||
|
||||
private static function date( string $value, DateTimeZone $zone ): DateTimeImmutable {
|
||||
$date = preg_match( '/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/D', $value ) ? DateTimeImmutable::createFromFormat( '!Y-m-d H:i:s', $value, $zone ) : false;
|
||||
if ( ! $date || $value !== $date->format( 'Y-m-d H:i:s' ) ) {
|
||||
throw new InvalidArgumentException( __( 'The source schedule is missing or invalid.', 'burn-events' ) );
|
||||
}
|
||||
return $date;
|
||||
}
|
||||
|
||||
private static function event_terms( int $id ): array {
|
||||
global $wpdb;
|
||||
$rows = $wpdb->get_results( $wpdb->prepare( "SELECT tt.term_id, tt.taxonomy FROM $wpdb->term_relationships r JOIN $wpdb->term_taxonomy tt ON tt.term_taxonomy_id = r.term_taxonomy_id WHERE r.object_id = %d AND tt.taxonomy IN (%s, 'post_tag')", $id, self::CATEGORY ), ARRAY_A );
|
||||
if ( $wpdb->last_error ) {
|
||||
throw new RuntimeException( 'Source category query failed.' );
|
||||
}
|
||||
$terms = [ 'categories' => [], 'tags' => [] ];
|
||||
foreach ( $rows as $row ) {
|
||||
$term_id = (int) $row['term_id'];
|
||||
if ( self::CATEGORY === $row['taxonomy'] ) {
|
||||
$terms['categories'][] = self::category( $term_id );
|
||||
} else {
|
||||
$terms['tags'][] = $term_id;
|
||||
}
|
||||
}
|
||||
return $terms;
|
||||
}
|
||||
|
||||
private static function category( int $id, array $ancestors = [] ): int {
|
||||
global $wpdb;
|
||||
static $mapped = [];
|
||||
if ( isset( $mapped[ $id ] ) ) {
|
||||
return $mapped[ $id ];
|
||||
}
|
||||
$term = $wpdb->get_row( $wpdb->prepare( "SELECT t.name, t.slug, tt.description, tt.parent FROM $wpdb->terms t JOIN $wpdb->term_taxonomy tt ON tt.term_id = t.term_id WHERE t.term_id = %d AND tt.taxonomy = %s", $id, self::CATEGORY ), ARRAY_A );
|
||||
if ( ! $term || in_array( $id, $ancestors, true ) ) {
|
||||
throw new InvalidArgumentException( __( 'A source category or its parent is unavailable.', 'burn-events' ) );
|
||||
}
|
||||
$parent = $term['parent'] ? self::category( (int) $term['parent'], [ ...$ancestors, $id ] ) : 0;
|
||||
$existing = term_exists( $term['slug'], Events::CATEGORY, $parent );
|
||||
$created = $existing ?: wp_insert_term( $term['name'], Events::CATEGORY, [ 'slug' => $term['slug'], 'parent' => $parent, 'description' => $term['description'] ] );
|
||||
if ( is_wp_error( $created ) ) {
|
||||
throw new InvalidArgumentException( $created->get_error_message() );
|
||||
}
|
||||
return $mapped[ $id ] = (int) $created['term_id'];
|
||||
}
|
||||
|
||||
private static function meta( int $id, string $key ): string {
|
||||
$value = get_post_meta( $id, $key, true );
|
||||
return is_scalar( $value ) ? (string) $value : '';
|
||||
}
|
||||
|
||||
private static function flag( int $id, string $key ): bool {
|
||||
return in_array( strtolower( self::meta( $id, $key ) ), [ '1', 'true', 'yes', 'on' ], true );
|
||||
}
|
||||
}
|
||||
169
includes/class-map-view.php
Normal file
169
includes/class-map-view.php
Normal file
@@ -0,0 +1,169 @@
|
||||
<?php
|
||||
|
||||
namespace BurnEvents;
|
||||
|
||||
use WP_Post;
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
final class Map_View {
|
||||
public const SCRIPT = 'burn-events-map';
|
||||
public const STYLE = 'burn-events-leaflet';
|
||||
|
||||
public static function register_assets(): void {
|
||||
$base = plugins_url( 'assets/', BURN_EVENTS_FILE );
|
||||
wp_register_style( self::STYLE, $base . 'vendor/leaflet/leaflet.css', [], '1.9.4' );
|
||||
wp_register_script( self::STYLE, $base . 'vendor/leaflet/leaflet.js', [], '1.9.4', true );
|
||||
wp_register_script( self::SCRIPT, $base . 'maps.js', [ self::STYLE ], BURN_EVENTS_VERSION, true );
|
||||
}
|
||||
|
||||
public static function venues( array $venues, int $event_id = 0 ): string {
|
||||
if ( ! Admin::options()['maps'] ) {
|
||||
return '';
|
||||
}
|
||||
$pins = [];
|
||||
foreach ( $venues as $venue ) {
|
||||
$place = self::place( $venue );
|
||||
if ( $place ) {
|
||||
self::add_pin( $pins, $place );
|
||||
}
|
||||
}
|
||||
return $pins ? self::canvas( $pins, $event_id ? __( 'Event location map', 'burn-events' ) : __( 'Venue map', 'burn-events' ), true, $event_id ) : '';
|
||||
}
|
||||
|
||||
public static function archive( array $rows ): void {
|
||||
$pins = $places = $unmapped = [];
|
||||
$mapped = 0;
|
||||
update_meta_cache( 'post', array_unique( array_column( $rows, 'event_id' ) ) );
|
||||
foreach ( $rows as $row ) {
|
||||
$id = (int) $row['event_id'];
|
||||
$data = Events::event_data( $id );
|
||||
$event = [
|
||||
'title' => self::title( $id ),
|
||||
'date' => Calendar::period( $row, $data ),
|
||||
'url' => esc_url_raw( Events::event_url( $row ), [ 'http', 'https' ] ),
|
||||
];
|
||||
$located = false;
|
||||
foreach ( Events::locations( $data['venue'], Events::VENUE ) as $venue ) {
|
||||
if ( ! array_key_exists( $venue->ID, $places ) ) {
|
||||
$places[ $venue->ID ] = self::place( $venue );
|
||||
}
|
||||
if ( $places[ $venue->ID ] ) {
|
||||
self::add_pin( $pins, $places[ $venue->ID ], $event );
|
||||
$located = true;
|
||||
}
|
||||
}
|
||||
if ( $located ) {
|
||||
++$mapped;
|
||||
} else {
|
||||
$unmapped[] = $event;
|
||||
}
|
||||
}
|
||||
|
||||
if ( $pins ) {
|
||||
$enabled = Admin::options()['maps'];
|
||||
$counts = [
|
||||
sprintf( _n( '%s event date', '%s event dates', $mapped, 'burn-events' ), number_format_i18n( $mapped ) ),
|
||||
sprintf( _n( '%s location', '%s locations', count( $pins ), 'burn-events' ), number_format_i18n( count( $pins ) ) ),
|
||||
];
|
||||
echo '<p class="be-map-count">' . esc_html( implode( ' · ', $counts ) ) . '</p>';
|
||||
if ( ! $enabled ) {
|
||||
echo '<p class="be-empty">' . esc_html__( 'Maps are disabled on this site.', 'burn-events' ) . '</p>';
|
||||
}
|
||||
?>
|
||||
<div class="be-map-layout<?php echo $enabled ? '' : ' be-map-layout-list'; ?>">
|
||||
<?php if ( $enabled ) { echo self::canvas( $pins, __( 'Event locations', 'burn-events' ) ); } ?>
|
||||
<section class="be-map-locations" aria-label="<?php esc_attr_e( 'Locations in this date range', 'burn-events' ); ?>">
|
||||
<?php foreach ( $pins as $key => $pin ) : ?>
|
||||
<details class="be-map-location">
|
||||
<summary><span><?php echo esc_html( implode( ' / ', array_column( $pin['places'], 'name' ) ) ); ?></span>
|
||||
<span class="be-map-location-count"><?php echo esc_html( number_format_i18n( count( $pin['events'] ) ) ); ?></span>
|
||||
</summary>
|
||||
<div class="be-map-location-body">
|
||||
<?php self::event_links( $pin['events'] ); ?>
|
||||
<?php if ( $enabled ) : ?><button class="be-map-focus" type="button" data-be-map-focus="<?php echo esc_attr( $key ); ?>" hidden><?php esc_html_e( 'Center map here', 'burn-events' ); ?></button><?php endif; ?>
|
||||
</div>
|
||||
</details>
|
||||
<?php endforeach; ?>
|
||||
</section>
|
||||
</div>
|
||||
<?php
|
||||
} else {
|
||||
echo '<p class="be-empty">' . esc_html__( 'No events have mapped venues in this date range.', 'burn-events' ) . '</p>';
|
||||
}
|
||||
if ( $unmapped ) {
|
||||
echo '<details class="be-map-location be-map-unmapped"><summary>' . esc_html__( 'Events without a map pin', 'burn-events' ) . '</summary><div class="be-map-location-body">';
|
||||
self::event_links( $unmapped );
|
||||
echo '</div></details>';
|
||||
}
|
||||
}
|
||||
|
||||
private static function title( int $id ): string {
|
||||
return html_entity_decode( wp_strip_all_tags( get_the_title( $id ) ), ENT_QUOTES | ENT_HTML5, 'UTF-8' );
|
||||
}
|
||||
|
||||
private static function place( WP_Post $venue ): ?array {
|
||||
$data = Events::location_data( $venue->ID );
|
||||
if ( ! Maps::valid_coordinates( $data['latitude'], $data['longitude'] ) ) {
|
||||
return null;
|
||||
}
|
||||
return [
|
||||
'id' => $venue->ID, 'name' => self::title( $venue->ID ), 'address' => Maps::address( $data ),
|
||||
'latitude' => (float) $data['latitude'], 'longitude' => (float) $data['longitude'],
|
||||
'url' => esc_url_raw( get_permalink( $venue ), [ 'http', 'https' ] ), 'geocode' => $data['geocode'],
|
||||
];
|
||||
}
|
||||
|
||||
private static function add_pin( array &$pins, array $place, ?array $event = null ): void {
|
||||
$key = sprintf( '%.6F,%.6F', $place['latitude'], $place['longitude'] );
|
||||
if ( ! isset( $pins[ $key ] ) ) {
|
||||
$pins[ $key ] = [
|
||||
'key' => $key, 'latitude' => $place['latitude'], 'longitude' => $place['longitude'],
|
||||
'places' => [], 'events' => [],
|
||||
];
|
||||
}
|
||||
$pins[ $key ]['places'][ $place['id'] ] = $place;
|
||||
if ( $event ) {
|
||||
$pins[ $key ]['events'][ $event['url'] ] = $event;
|
||||
}
|
||||
}
|
||||
|
||||
private static function canvas( array $pins, string $label, bool $compact = false, int $event_id = 0 ): string {
|
||||
wp_enqueue_style( self::STYLE );
|
||||
wp_enqueue_script( self::SCRIPT );
|
||||
ob_start();
|
||||
?>
|
||||
<div class="be-map<?php echo $compact ? ' be-map-compact' : ''; ?>" data-be-map<?php if ( $event_id ) : ?> data-be-event-map="<?php echo esc_attr( (string) $event_id ); ?>"<?php endif; ?>>
|
||||
<div class="be-map-canvas" role="region" aria-label="<?php echo esc_attr( $label ); ?>"></div>
|
||||
<script type="application/json" class="be-map-pins"><?php echo wp_json_encode( array_values( $pins ), JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT ); ?></script>
|
||||
<p class="be-map-error" hidden><?php esc_html_e( 'The map tiles are temporarily unavailable.', 'burn-events' ); ?></p>
|
||||
<noscript><p><?php esc_html_e( 'Enable JavaScript to view the map.', 'burn-events' ); ?></p></noscript>
|
||||
<?php
|
||||
$credits = [];
|
||||
foreach ( $pins as $pin ) {
|
||||
foreach ( $pin['places'] as $place ) {
|
||||
$geocode = $place['geocode'];
|
||||
if ( $geocode ) {
|
||||
$key = ( $geocode['provider'] ?? '' ) . '|' . ( $geocode['attribution'] ?? '' );
|
||||
$credits[ $key ] = $place;
|
||||
}
|
||||
}
|
||||
}
|
||||
foreach ( $credits as $place ) {
|
||||
Maps::attribution( $place );
|
||||
}
|
||||
?>
|
||||
</div>
|
||||
<?php
|
||||
return ob_get_clean();
|
||||
}
|
||||
|
||||
private static function event_links( array $events ): void {
|
||||
echo '<ul class="be-map-event-links">';
|
||||
foreach ( $events as $event ) {
|
||||
echo '<li><a href="' . esc_url( $event['url'] ) . '">' . esc_html( $event['title'] ) . '</a>';
|
||||
echo '<span>' . esc_html( $event['date'] ) . '</span></li>';
|
||||
}
|
||||
echo '</ul>';
|
||||
}
|
||||
}
|
||||
164
includes/class-maps.php
Normal file
164
includes/class-maps.php
Normal file
@@ -0,0 +1,164 @@
|
||||
<?php
|
||||
|
||||
namespace BurnEvents;
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
final class Maps {
|
||||
public const KEY_OPTION = 'burn_events_maps_api_key';
|
||||
public const ADDRESS_FIELDS = [ 'address', 'city', 'region', 'postal', 'country' ];
|
||||
|
||||
public static function register_setting(): void {
|
||||
add_option( self::KEY_OPTION, '', '', false );
|
||||
register_setting( 'burn_events', self::KEY_OPTION, [
|
||||
'type' => 'string',
|
||||
'sanitize_callback' => [ self::class, 'sanitize_key' ],
|
||||
'show_in_rest' => false,
|
||||
] );
|
||||
}
|
||||
|
||||
public static function sanitize_key( $value ): string {
|
||||
if ( ! empty( $_POST['burn_events_remove_maps_key'] ) && current_user_can( 'manage_options' ) ) {
|
||||
return '';
|
||||
}
|
||||
$value = is_string( $value ) ? trim( $value ) : '';
|
||||
if ( '' === $value ) {
|
||||
return self::api_key();
|
||||
}
|
||||
if ( ! preg_match( '/^[A-Za-z0-9_-]{1,160}$/D', $value ) ) {
|
||||
add_settings_error( self::KEY_OPTION, 'invalid_key', __( 'Enter a valid Geoapify API key.', 'burn-events' ) );
|
||||
return self::api_key();
|
||||
}
|
||||
return $value;
|
||||
}
|
||||
|
||||
public static function has_key(): bool {
|
||||
return '' !== self::api_key();
|
||||
}
|
||||
|
||||
private static function api_key(): string {
|
||||
return (string) get_option( self::KEY_OPTION, '' );
|
||||
}
|
||||
|
||||
public static function address( array $data ): string {
|
||||
$parts = array_map( static fn( string $field ): string => trim( (string) ( $data[ $field ] ?? '' ) ), self::ADDRESS_FIELDS );
|
||||
return implode( ', ', array_filter( $parts, static fn( string $part ): bool => '' !== $part ) );
|
||||
}
|
||||
|
||||
public static function with_coordinates( array $data, array $previous, bool $retry ): array {
|
||||
$address = self::address( $data );
|
||||
$same_address = $address === self::address( $previous );
|
||||
$status = $previous['geocode']['status'] ?? '';
|
||||
$has_pin = self::valid_coordinates( $previous['latitude'] ?? null, $previous['longitude'] ?? null );
|
||||
$data['latitude'] = '';
|
||||
$data['longitude'] = '';
|
||||
$data['geocode'] = [];
|
||||
|
||||
if ( $same_address && ! $retry ) {
|
||||
if ( $has_pin && ( 'resolved' === $status || ! self::has_key() ) ) {
|
||||
$data['latitude'] = $previous['latitude'];
|
||||
$data['longitude'] = $previous['longitude'];
|
||||
$data['geocode'] = $previous['geocode'] ?: [ 'status' => 'existing' ];
|
||||
return $data;
|
||||
}
|
||||
if ( in_array( $status, [ 'unmatched', 'ambiguous', 'unavailable' ], true ) ) {
|
||||
$data['geocode'] = $previous['geocode'];
|
||||
return $data;
|
||||
}
|
||||
}
|
||||
|
||||
if ( '' === $address ) {
|
||||
return $data;
|
||||
}
|
||||
if ( '' === $data['address'] || ( '' === $data['city'] && '' === $data['postal'] ) ) {
|
||||
$data['geocode'] = [ 'status' => 'incomplete' ];
|
||||
return $data;
|
||||
}
|
||||
$key = self::api_key();
|
||||
if ( '' === $key ) {
|
||||
$data['geocode'] = [ 'status' => 'missing_key' ];
|
||||
return $data;
|
||||
}
|
||||
return array_replace( $data, self::lookup( $address, $key ) );
|
||||
}
|
||||
|
||||
private static function lookup( string $address, string $key ): array {
|
||||
$query = http_build_query( [
|
||||
'text' => $address, 'format' => 'json', 'limit' => 5, 'apiKey' => $key,
|
||||
], '', '&', PHP_QUERY_RFC3986 );
|
||||
$response = wp_safe_remote_get( 'https://api.geoapify.com/v1/geocode/search?' . $query, [
|
||||
'timeout' => 5, 'redirection' => 0, 'limit_response_size' => 262144,
|
||||
] );
|
||||
$body = json_decode( wp_remote_retrieve_body( $response ), true );
|
||||
if ( 200 !== wp_remote_retrieve_response_code( $response ) || ! is_array( $body['results'] ?? null ) ) {
|
||||
return [ 'geocode' => [ 'status' => 'unavailable' ] ];
|
||||
}
|
||||
|
||||
$matches = array_filter( $body['results'], static function ( $candidate ): bool {
|
||||
return is_array( $candidate )
|
||||
&& self::valid_coordinates( $candidate['lat'] ?? null, $candidate['lon'] ?? null )
|
||||
&& (float) ( $candidate['rank']['confidence'] ?? 0 ) >= 0.8
|
||||
&& in_array( $candidate['rank']['match_type'] ?? '', [ 'full_match', 'match_by_building' ], true )
|
||||
&& ( ! empty( $candidate['housenumber'] ) || in_array( $candidate['result_type'] ?? '', [ 'building', 'amenity' ], true ) );
|
||||
} );
|
||||
usort( $matches, static fn( array $first, array $second ): int => $second['rank']['confidence'] <=> $first['rank']['confidence'] );
|
||||
if ( ! $matches ) {
|
||||
return [ 'geocode' => [ 'status' => 'unmatched' ] ];
|
||||
}
|
||||
$match = array_shift( $matches );
|
||||
foreach ( $matches as $other ) {
|
||||
$similar_confidence = $match['rank']['confidence'] - $other['rank']['confidence'] < 0.05;
|
||||
$different_place = abs( $match['lat'] - $other['lat'] ) > 0.0005 || abs( $match['lon'] - $other['lon'] ) > 0.0005;
|
||||
if ( $similar_confidence && $different_place ) {
|
||||
return [ 'geocode' => [ 'status' => 'ambiguous' ] ];
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
'latitude' => (float) $match['lat'],
|
||||
'longitude' => (float) $match['lon'],
|
||||
'geocode' => [
|
||||
'status' => 'resolved',
|
||||
'provider' => 'geoapify',
|
||||
'formatted_address' => sanitize_text_field( $match['formatted'] ?? '' ),
|
||||
'attribution' => sanitize_text_field( $match['datasource']['attribution'] ?? '' ),
|
||||
'license' => sanitize_text_field( $match['datasource']['license'] ?? '' ),
|
||||
'source_url' => esc_url_raw( $match['datasource']['url'] ?? '', [ 'http', 'https' ] ),
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
public static function valid_coordinates( $latitude, $longitude ): bool {
|
||||
return is_numeric( $latitude ) && is_numeric( $longitude ) && abs( (float) $latitude ) <= 90 && abs( (float) $longitude ) <= 180;
|
||||
}
|
||||
|
||||
public static function lookup_message( array $data ): string {
|
||||
return match ( $data['geocode']['status'] ?? '' ) {
|
||||
'resolved' => __( 'Coordinates resolved from the saved address.', 'burn-events' ),
|
||||
'existing' => __( 'Saved coordinates. Recheck the address to look up a new pin.', 'burn-events' ),
|
||||
'incomplete' => __( 'Enter a street address and a city or postal code.', 'burn-events' ),
|
||||
'missing_key' => __( 'Save a Geoapify API key under Events → Settings, then save this address again.', 'burn-events' ),
|
||||
'unmatched' => __( 'No street-address match. Check the address, city, and postal code.', 'burn-events' ),
|
||||
'ambiguous' => __( 'Multiple addresses matched. Add a postal code or country and save again.', 'burn-events' ),
|
||||
'unavailable' => __( 'Address lookup failed. Check the Maps API key or try again.', 'burn-events' ),
|
||||
default => __( 'Save a complete address to look up coordinates.', 'burn-events' ),
|
||||
};
|
||||
}
|
||||
|
||||
public static function attribution( array $data ): void {
|
||||
$geocode = $data['geocode'] ?? [];
|
||||
$geoapify = 'geoapify' === ( $geocode['provider'] ?? '' );
|
||||
if ( ! $geoapify && empty( $geocode['attribution'] ) ) {
|
||||
return;
|
||||
}
|
||||
echo '<small class="be-map-credit">';
|
||||
if ( $geoapify ) {
|
||||
echo '<a href="https://www.geoapify.com/">' . esc_html__( 'Geocoding by Geoapify', 'burn-events' ) . '</a>';
|
||||
}
|
||||
if ( ! empty( $geocode['attribution'] ) ) {
|
||||
$credit = esc_html( $geocode['attribution'] );
|
||||
echo ( $geoapify ? ' · ' : '' ) . ( empty( $geocode['source_url'] ) ? $credit : '<a href="' . esc_url( $geocode['source_url'] ) . '">' . $credit . '</a>' );
|
||||
}
|
||||
echo '</small>';
|
||||
}
|
||||
}
|
||||
65
includes/class-platform.php
Normal file
65
includes/class-platform.php
Normal file
@@ -0,0 +1,65 @@
|
||||
<?php
|
||||
|
||||
namespace BurnEvents;
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
final class Platform {
|
||||
public static function register(): void {
|
||||
register_activation_hook( BURN_EVENTS_FILE, [ self::class, 'activate' ] );
|
||||
register_deactivation_hook( BURN_EVENTS_FILE, [ self::class, 'deactivate' ] );
|
||||
add_action( 'init', [ Events::class, 'register_types' ] );
|
||||
add_action( 'init', [ Clubs::class, 'register' ] );
|
||||
add_action( 'init', [ Clubs::class, 'backfill' ], 20 );
|
||||
add_action( 'init', [ Calendar::class, 'register' ] );
|
||||
add_action( 'init', [ Calendar_Grid::class, 'register_assets' ] );
|
||||
add_action( 'init', [ Map_View::class, 'register_assets' ] );
|
||||
add_action( 'init', [ Community::class, 'register' ] );
|
||||
add_action( 'init', [ Transfer::class, 'register' ] );
|
||||
Legacy_Migration::register();
|
||||
add_action( 'init', [ Events::class, 'ensure_schema' ], 1 );
|
||||
add_action( 'init', [ Api::class, 'install' ], 1 );
|
||||
add_action( 'rest_api_init', [ Calendar::class, 'register_api' ] );
|
||||
add_action( 'rest_api_init', [ Api::class, 'register' ] );
|
||||
add_action( 'rest_api_init', [ BurnWorks::class, 'register' ] );
|
||||
add_action( 'rest_api_init', [ Clubs::class, 'register_api' ] );
|
||||
add_filter( 'wp_insert_post_data', [ BurnWorks::class, 'protect_publication' ], PHP_INT_MAX, 2 );
|
||||
add_action( 'wp_enqueue_scripts', [ self::class, 'styles' ] );
|
||||
add_action( 'burn_events_rebuild_schedule', [ Events::class, 'rebuild' ] );
|
||||
add_action( 'burn_events_extend_schedules', [ Events::class, 'extend' ] );
|
||||
add_action( 'before_delete_post', [ Events::class, 'delete_occurrences' ] );
|
||||
add_filter( 'plugin_action_links_' . plugin_basename( BURN_EVENTS_FILE ), [ self::class, 'links' ] );
|
||||
Admin::register();
|
||||
Single_Event_Templates::register();
|
||||
}
|
||||
|
||||
public static function activate(): void {
|
||||
Events::ensure_schema();
|
||||
Api::install();
|
||||
Events::register_types();
|
||||
Calendar::register();
|
||||
Community::register();
|
||||
flush_rewrite_rules( false );
|
||||
if ( ! wp_next_scheduled( 'burn_events_extend_schedules' ) ) {
|
||||
wp_schedule_event( time() + HOUR_IN_SECONDS, 'daily', 'burn_events_extend_schedules' );
|
||||
}
|
||||
}
|
||||
|
||||
public static function deactivate(): void {
|
||||
wp_clear_scheduled_hook( 'burn_events_extend_schedules' );
|
||||
delete_option( 'rewrite_rules' );
|
||||
}
|
||||
|
||||
public static function styles(): void {
|
||||
wp_enqueue_style( 'burn-events', plugins_url( 'assets/events.css', BURN_EVENTS_FILE ), [], BURN_EVENTS_VERSION );
|
||||
wp_register_script( 'burn-events', plugins_url( 'assets/events.js', BURN_EVENTS_FILE ), [], BURN_EVENTS_VERSION, [ 'in_footer' => true ] );
|
||||
}
|
||||
|
||||
public static function links( array $links ): array {
|
||||
$links[] = '<a href="' . esc_url( admin_url( 'edit.php?post_type=burn_event' ) ) . '">' . esc_html__( 'Events', 'burn-events' ) . '</a>';
|
||||
if ( current_user_can( 'edit_theme_options' ) ) {
|
||||
$links[] = '<a href="' . esc_url( Single_Event_Templates::list_url() ) . '">' . esc_html__( 'Single Event Templates', 'burn-events' ) . '</a>';
|
||||
}
|
||||
return $links;
|
||||
}
|
||||
}
|
||||
139
includes/class-schedule.php
Normal file
139
includes/class-schedule.php
Normal file
@@ -0,0 +1,139 @@
|
||||
<?php
|
||||
|
||||
namespace BurnEvents;
|
||||
|
||||
use DateTimeImmutable;
|
||||
use DateTimeZone;
|
||||
use Generator;
|
||||
use InvalidArgumentException;
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
final class Schedule {
|
||||
public const REPEATS = [ 'none', 'daily', 'weekly', 'monthly', 'yearly' ];
|
||||
public const WEEKDAYS = [ 1 => 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday' ];
|
||||
|
||||
public static function validate( array $input, string $default_zone ): array {
|
||||
$value = static fn( string $key ): string => is_scalar( $input[ $key ] ?? null ) ? trim( (string) $input[ $key ] ) : '';
|
||||
$zone = $value( 'timezone' ) ?: $default_zone;
|
||||
try {
|
||||
$timezone = new DateTimeZone( $zone );
|
||||
} catch ( \Exception $error ) {
|
||||
throw new InvalidArgumentException( __( 'Choose a valid time zone.', 'burn-events' ) );
|
||||
}
|
||||
|
||||
$all_day = ! empty( $input['all_day'] );
|
||||
$start = self::parse( $value( 'start_date' ), $all_day ? '00:00' : $value( 'start_time' ), $timezone );
|
||||
$end = self::parse( $value( 'end_date' ) ?: $value( 'start_date' ), $all_day ? '00:00' : $value( 'end_time' ), $timezone );
|
||||
if ( $end < $start || ( ! $all_day && $end == $start ) ) {
|
||||
throw new InvalidArgumentException( __( 'The end must be after the start.', 'burn-events' ) );
|
||||
}
|
||||
|
||||
$repeat = $value( 'repeat' );
|
||||
$until = $value( 'until' );
|
||||
if ( $until && self::parse( $until, '00:00', $timezone )->format( 'Y-m-d' ) < $start->format( 'Y-m-d' ) ) {
|
||||
throw new InvalidArgumentException( __( 'The recurrence end date must be on or after the event start.', 'burn-events' ) );
|
||||
}
|
||||
$weekdays = array_intersect( array_keys( self::WEEKDAYS ), array_map( 'intval', (array) ( $input['weekdays'] ?? [] ) ) );
|
||||
|
||||
return [
|
||||
'start_date' => $start->format( 'Y-m-d' ),
|
||||
'start_time' => $start->format( '00' === $start->format( 's' ) ? 'H:i' : 'H:i:s' ),
|
||||
'end_date' => $end->format( 'Y-m-d' ),
|
||||
'end_time' => $end->format( '00' === $end->format( 's' ) ? 'H:i' : 'H:i:s' ),
|
||||
'timezone' => $timezone->getName(),
|
||||
'all_day' => $all_day,
|
||||
'repeat' => in_array( $repeat, self::REPEATS, true ) ? $repeat : 'none',
|
||||
'interval' => max( 1, min( 365, (int) $value( 'interval' ) ) ),
|
||||
'weekdays' => array_values( $weekdays ),
|
||||
'monthly' => 'weekday' === $value( 'monthly' ) ? 'weekday' : 'day',
|
||||
'count' => max( 0, min( 10000, (int) $value( 'count' ) ) ),
|
||||
'until' => $until,
|
||||
'include' => self::dates( $value( 'include' ), $timezone ),
|
||||
'exclude' => self::dates( $value( 'exclude' ), $timezone ),
|
||||
];
|
||||
}
|
||||
|
||||
private static function parse( string $day, string $time, DateTimeZone $zone ): DateTimeImmutable {
|
||||
$value = $day . ' ' . $time;
|
||||
$format = 8 === strlen( $time ) ? 'Y-m-d H:i:s' : 'Y-m-d H:i';
|
||||
$date = DateTimeImmutable::createFromFormat( '!' . $format, $value, $zone );
|
||||
if ( ! $date || $date->format( $format ) !== $value ) {
|
||||
throw new InvalidArgumentException( __( 'Enter a valid date and time for the selected time zone.', 'burn-events' ) );
|
||||
}
|
||||
return $date;
|
||||
}
|
||||
|
||||
private static function dates( string $value, DateTimeZone $zone ): array {
|
||||
$dates = preg_split( '/[\s,]+/', $value, -1, PREG_SPLIT_NO_EMPTY );
|
||||
return array_values( array_unique( array_map( static fn( string $day ): string => self::parse( $day, '00:00', $zone )->format( 'Y-m-d' ), $dates ) ) );
|
||||
}
|
||||
|
||||
public static function occurrences( array $rule, DateTimeImmutable $horizon ): Generator {
|
||||
$zone = new DateTimeZone( $rule['timezone'] );
|
||||
$start = self::parse( $rule['start_date'], $rule['start_time'], $zone );
|
||||
$end = self::parse( $rule['end_date'], $rule['end_time'], $zone );
|
||||
$span = (int) $start->setTime( 0, 0 )->diff( $end->setTime( 0, 0 ) )->days + (int) $rule['all_day'];
|
||||
$anchor = $start->setTime( 0, 0 );
|
||||
$limit = $horizon->setTimezone( $zone )->setTime( 0, 0 );
|
||||
$dates = [ $rule['start_date'] => true ];
|
||||
$generated = 1;
|
||||
|
||||
if ( 'none' !== $rule['repeat'] ) {
|
||||
$until = $rule['until'] ? new DateTimeImmutable( $rule['until'], $zone ) : $limit;
|
||||
$until = min( $limit, $until );
|
||||
for ( $date = $anchor->modify( '+1 day' ); $date <= $until; $date = $date->modify( '+1 day' ) ) {
|
||||
if ( $rule['count'] && $generated >= $rule['count'] ) {
|
||||
break;
|
||||
}
|
||||
if ( self::matches( $rule, $anchor, $date ) ) {
|
||||
$dates[ $date->format( 'Y-m-d' ) ] = true;
|
||||
$generated++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
foreach ( $rule['include'] as $date ) {
|
||||
$dates[ $date ] = true;
|
||||
}
|
||||
foreach ( $rule['exclude'] as $date ) {
|
||||
unset( $dates[ $date ] );
|
||||
}
|
||||
ksort( $dates );
|
||||
|
||||
$utc = new DateTimeZone( 'UTC' );
|
||||
foreach ( array_keys( $dates ) as $day ) {
|
||||
$from = new DateTimeImmutable( $day . ' ' . $rule['start_time'], $zone );
|
||||
$last_day = ( new DateTimeImmutable( $day, $zone ) )->modify( "+{$span} days" )->format( 'Y-m-d' );
|
||||
$to = new DateTimeImmutable( $last_day . ' ' . $rule['end_time'], $zone );
|
||||
if ( $to <= $from ) {
|
||||
$to = $from->modify( '+' . max( 60, $end->getTimestamp() - $start->getTimestamp() ) . ' seconds' );
|
||||
}
|
||||
yield [ $from->setTimezone( $utc )->format( 'Y-m-d H:i:s' ), $to->setTimezone( $utc )->format( 'Y-m-d H:i:s' ) ];
|
||||
}
|
||||
}
|
||||
|
||||
private static function matches( array $rule, DateTimeImmutable $anchor, DateTimeImmutable $date ): bool {
|
||||
$interval = $rule['interval'];
|
||||
$days = (int) $anchor->diff( $date )->days;
|
||||
switch ( $rule['repeat'] ) {
|
||||
case 'daily':
|
||||
return 0 === $days % $interval;
|
||||
case 'weekly':
|
||||
$week = intdiv( $days + (int) $anchor->format( 'N' ) - 1, 7 );
|
||||
$weekdays = $rule['weekdays'] ?: [ (int) $anchor->format( 'N' ) ];
|
||||
return 0 === $week % $interval && in_array( (int) $date->format( 'N' ), $weekdays, true );
|
||||
case 'monthly':
|
||||
$months = ( (int) $date->format( 'Y' ) - (int) $anchor->format( 'Y' ) ) * 12 + (int) $date->format( 'n' ) - (int) $anchor->format( 'n' );
|
||||
if ( 0 !== $months % $interval ) {
|
||||
return false;
|
||||
}
|
||||
return 'weekday' === $rule['monthly']
|
||||
? $date->format( 'N' ) === $anchor->format( 'N' ) && intdiv( (int) $date->format( 'j' ) - 1, 7 ) === intdiv( (int) $anchor->format( 'j' ) - 1, 7 )
|
||||
: $date->format( 'j' ) === $anchor->format( 'j' );
|
||||
case 'yearly':
|
||||
return 0 === ( (int) $date->format( 'Y' ) - (int) $anchor->format( 'Y' ) ) % $interval && $date->format( 'm-d' ) === $anchor->format( 'm-d' );
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
341
includes/class-single-event-templates.php
Normal file
341
includes/class-single-event-templates.php
Normal file
@@ -0,0 +1,341 @@
|
||||
<?php
|
||||
|
||||
namespace BurnEvents;
|
||||
|
||||
use Elementor\Core\Base\Document;
|
||||
use Elementor\Plugin as Elementor;
|
||||
use WP_Post;
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
final class Single_Event_Templates {
|
||||
public const POST_TYPE = 'burn_event_template';
|
||||
private const EVENT = Events::EVENT;
|
||||
private const DEFAULT_OPTION = 'burn_events_default_template';
|
||||
private const EVENT_TEMPLATE_META = '_burn_events_template';
|
||||
private const SAMPLE_META = '_burn_events_sample_event';
|
||||
private const CAPABILITY = 'edit_theme_options';
|
||||
|
||||
private static ?WP_Post $rendering_event = null;
|
||||
private static ?array $rendering_occurrence = null;
|
||||
|
||||
public static function register(): void {
|
||||
add_action( 'init', [ self::class, 'register_post_type' ] );
|
||||
add_action( 'template_redirect', [ self::class, 'protect_template_preview' ], 0 );
|
||||
add_action( 'elementor/elements/categories_registered', [ self::class, 'register_widget_category' ] );
|
||||
add_filter( 'elementor/editor/localize_settings', [ self::class, 'order_widget_category' ], 20 );
|
||||
add_action( 'elementor/widgets/register', [ self::class, 'register_widgets' ] );
|
||||
|
||||
add_action( 'add_meta_boxes_' . self::POST_TYPE, [ self::class, 'add_preview_box' ] );
|
||||
add_action( 'add_meta_boxes_' . self::EVENT, [ self::class, 'add_assignment_box' ] );
|
||||
add_action( 'save_post_' . self::POST_TYPE, [ self::class, 'save_preview_event' ] );
|
||||
add_action( 'save_post_' . self::EVENT, [ self::class, 'save_assignment' ] );
|
||||
add_action( 'admin_notices', [ self::class, 'builder_notice' ] );
|
||||
add_filter( 'post_row_actions', [ self::class, 'default_row_action' ], 10, 2 );
|
||||
add_filter( 'display_post_states', [ self::class, 'display_default_state' ], 10, 2 );
|
||||
add_action( 'admin_post_burn_events_set_default', [ self::class, 'set_default' ] );
|
||||
add_action( 'admin_post_burn_events_create_starter', [ self::class, 'create_starter' ] );
|
||||
}
|
||||
|
||||
public static function register_post_type(): void {
|
||||
register_post_type(
|
||||
self::POST_TYPE,
|
||||
[
|
||||
'labels' => [
|
||||
'name' => __( 'Single Event Templates', 'burn-events' ),
|
||||
'singular_name' => __( 'Single Event Template', 'burn-events' ),
|
||||
'add_new_item' => __( 'Add Single Event Template', 'burn-events' ),
|
||||
'edit_item' => __( 'Edit Single Event Template', 'burn-events' ),
|
||||
],
|
||||
'public' => false,
|
||||
'publicly_queryable' => true,
|
||||
'exclude_from_search' => true,
|
||||
'show_ui' => true,
|
||||
'show_in_menu' => 'edit.php?post_type=' . self::EVENT,
|
||||
'rewrite' => false,
|
||||
'map_meta_cap' => false,
|
||||
'capabilities' => array_fill_keys(
|
||||
[ 'edit_post', 'read_post', 'delete_post', 'edit_posts', 'edit_others_posts', 'publish_posts', 'read_private_posts', 'create_posts' ],
|
||||
self::CAPABILITY
|
||||
),
|
||||
'supports' => [ 'title', 'editor', 'revisions', 'elementor' ],
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
public static function list_url(): string {
|
||||
return admin_url( 'edit.php?post_type=' . self::POST_TYPE );
|
||||
}
|
||||
|
||||
public static function protect_template_preview(): void {
|
||||
if ( is_singular( self::POST_TYPE ) ) {
|
||||
nocache_headers();
|
||||
if ( ! current_user_can( 'edit_post', get_queried_object_id() ) ) {
|
||||
wp_die( esc_html__( 'Page not found.', 'burn-events' ), '', [ 'response' => 404 ] );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static function register_widget_category( $manager ): void {
|
||||
$manager->add_category( 'burn-events', [ 'title' => 'eventLabs', 'icon' => 'eicon-calendar' ] );
|
||||
}
|
||||
|
||||
public static function order_widget_category( array $settings ): array {
|
||||
$categories = $settings['initial_document']['panel']['elements_categories'] ?? [];
|
||||
if ( isset( $categories['burn-events'] ) ) {
|
||||
$favorites = array_intersect_key( $categories, [ 'favorites' => true ] );
|
||||
$settings['initial_document']['panel']['elements_categories'] = $favorites + [ 'burn-events' => $categories['burn-events'] ] + $categories;
|
||||
}
|
||||
return $settings;
|
||||
}
|
||||
|
||||
public static function register_widgets( $manager ): void {
|
||||
require_once __DIR__ . '/class-elementor-widgets.php';
|
||||
$widgets = [
|
||||
new Calendar_Widget(), new Event_List_Widget(), new Event_Details_Widget(), new Event_Title_Widget(),
|
||||
new Event_Date_Widget(), new Event_Image_Widget(), new Event_Description_Widget(), new Event_Venue_Widget(),
|
||||
new Event_Organizer_Widget(), new Event_Cost_Widget(), new Event_Calendar_Links_Widget(),
|
||||
new Event_Related_Widget(), new Countdown_Widget(), new Community_Widget(), new Event_Field_Widget(),
|
||||
];
|
||||
foreach ( $widgets as $widget ) {
|
||||
$manager->register( $widget );
|
||||
}
|
||||
}
|
||||
|
||||
private static function sample_event( int $template_id ): ?WP_Post {
|
||||
$sample_id = (int) get_post_meta( $template_id, self::SAMPLE_META, true );
|
||||
$sample = $sample_id ? get_post( $sample_id ) : null;
|
||||
if ( $sample && self::EVENT === $sample->post_type && 'publish' === $sample->post_status && '' === $sample->post_password ) {
|
||||
return $sample;
|
||||
}
|
||||
|
||||
$events = get_posts(
|
||||
[
|
||||
'post_type' => self::EVENT,
|
||||
'post_status' => 'publish',
|
||||
'has_password' => false,
|
||||
'posts_per_page' => 1,
|
||||
]
|
||||
);
|
||||
return $events[0] ?? null;
|
||||
}
|
||||
|
||||
public static function widget_context( int $id = 0 ): array {
|
||||
if ( ! $id && self::$rendering_event ) {
|
||||
return [ self::$rendering_event, self::$rendering_occurrence ];
|
||||
}
|
||||
|
||||
$post = $id ? get_post( $id ) : get_post();
|
||||
if ( $post && ! $id && self::POST_TYPE === $post->post_type && current_user_can( 'edit_post', $post->ID ) ) {
|
||||
$post = self::sample_event( $post->ID );
|
||||
}
|
||||
|
||||
if ( ! $post || self::EVENT !== $post->post_type || post_password_required( $post )
|
||||
|| ( 'publish' !== $post->post_status && ! current_user_can( 'read_post', $post->ID ) )
|
||||
) {
|
||||
return [ null, null ];
|
||||
}
|
||||
return [ $post, Events::occurrence( $post->ID, Calendar::request( 'be_occ' ) ) ];
|
||||
}
|
||||
|
||||
private static function is_layout( ?WP_Post $template ): bool {
|
||||
return $template && self::POST_TYPE === $template->post_type
|
||||
&& 'publish' === $template->post_status && '' === $template->post_password;
|
||||
}
|
||||
|
||||
private static function is_elementor_ready(): bool {
|
||||
return did_action( 'elementor/loaded' ) && class_exists( Elementor::class );
|
||||
}
|
||||
|
||||
private static function get_assignment( int $event_id ): int {
|
||||
return (int) get_post_meta( $event_id, self::EVENT_TEMPLATE_META, true );
|
||||
}
|
||||
|
||||
public static function render( WP_Post $event, ?array $row ): string {
|
||||
if ( ! self::is_elementor_ready() || Elementor::instance()->preview->is_preview_mode() ) {
|
||||
return '';
|
||||
}
|
||||
|
||||
$assignment = self::get_assignment( $event->ID );
|
||||
if ( -1 === $assignment ) {
|
||||
return '';
|
||||
}
|
||||
$default = (int) get_option( self::DEFAULT_OPTION, 0 );
|
||||
$frontend = Elementor::instance()->frontend;
|
||||
|
||||
foreach ( array_unique( array_filter( [ $assignment, $default ] ) ) as $template_id ) {
|
||||
if ( ! self::is_layout( get_post( $template_id ) ) ) {
|
||||
continue;
|
||||
}
|
||||
self::$rendering_event = $event;
|
||||
self::$rendering_occurrence = $row;
|
||||
try {
|
||||
$markup = $frontend->get_builder_content_for_display( $template_id );
|
||||
} finally {
|
||||
self::$rendering_event = null;
|
||||
self::$rendering_occurrence = null;
|
||||
}
|
||||
if ( trim( $markup ) ) {
|
||||
add_action( 'wp_enqueue_scripts', [ $frontend, 'enqueue_styles' ] );
|
||||
return $markup;
|
||||
}
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
public static function add_preview_box(): void {
|
||||
add_meta_box( 'burn-events-preview', __( 'Preview event', 'burn-events' ), [ self::class, 'preview_box' ], self::POST_TYPE, 'side' );
|
||||
}
|
||||
|
||||
public static function preview_box( WP_Post $post ): void {
|
||||
$sample = (int) get_post_meta( $post->ID, self::SAMPLE_META, true );
|
||||
wp_nonce_field( 'burn_events_save_preview', 'burn_events_preview_nonce' );
|
||||
?>
|
||||
<label class="screen-reader-text" for="burn-events-sample"><?php esc_html_e( 'Preview event ID', 'burn-events' ); ?></label>
|
||||
<input id="burn-events-sample" name="burn_events_sample" type="number" min="1" step="1" class="small-text" value="<?php echo $sample ? esc_attr( (string) $sample ) : ''; ?>">
|
||||
<p class="description"><?php esc_html_e( 'Enter a published event ID to preview its details in Elementor. Leave blank to use the most recently published event.', 'burn-events' ); ?></p>
|
||||
<?php
|
||||
}
|
||||
|
||||
public static function save_preview_event( int $post_id ): void {
|
||||
if ( ! self::can_save( $post_id, 'burn_events_preview_nonce', 'burn_events_save_preview' ) ) {
|
||||
return;
|
||||
}
|
||||
$sample_id = isset( $_POST['burn_events_sample'] ) && is_scalar( $_POST['burn_events_sample'] ) ? absint( $_POST['burn_events_sample'] ) : 0;
|
||||
$sample = $sample_id ? get_post( $sample_id ) : null;
|
||||
if ( $sample && self::EVENT === $sample->post_type && 'publish' === $sample->post_status && '' === $sample->post_password ) {
|
||||
update_post_meta( $post_id, self::SAMPLE_META, $sample_id );
|
||||
} else {
|
||||
delete_post_meta( $post_id, self::SAMPLE_META );
|
||||
}
|
||||
}
|
||||
|
||||
public static function add_assignment_box(): void {
|
||||
add_meta_box( 'burn-events-template', __( 'Single Event Template', 'burn-events' ), [ self::class, 'assignment_box' ], self::EVENT, 'side' );
|
||||
}
|
||||
|
||||
public static function assignment_box( WP_Post $post ): void {
|
||||
$selected = self::get_assignment( $post->ID );
|
||||
$templates = get_posts(
|
||||
[
|
||||
'post_type' => self::POST_TYPE,
|
||||
'post_status' => 'publish',
|
||||
'has_password' => false,
|
||||
'posts_per_page' => -1,
|
||||
'orderby' => 'title',
|
||||
'order' => 'ASC',
|
||||
]
|
||||
);
|
||||
wp_nonce_field( 'burn_events_save_assignment', 'burn_events_assignment_nonce' );
|
||||
?>
|
||||
<label class="screen-reader-text" for="burn-events-assignment"><?php esc_html_e( 'Single Event Template', 'burn-events' ); ?></label>
|
||||
<select id="burn-events-assignment" name="burn_events_assignment" style="width:100%">
|
||||
<option value="0" <?php selected( $selected, 0 ); ?>><?php esc_html_e( 'Inherit default', 'burn-events' ); ?></option>
|
||||
<option value="-1" <?php selected( $selected, -1 ); ?>><?php esc_html_e( 'Use calendar layout', 'burn-events' ); ?></option>
|
||||
<?php foreach ( $templates as $template ) : ?>
|
||||
<option value="<?php echo esc_attr( (string) $template->ID ); ?>" <?php selected( $selected, $template->ID ); ?>><?php echo esc_html( get_the_title( $template ) ); ?></option>
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
<?php
|
||||
}
|
||||
|
||||
public static function save_assignment( int $post_id ): void {
|
||||
if ( ! self::can_save( $post_id, 'burn_events_assignment_nonce', 'burn_events_save_assignment' ) ) {
|
||||
return;
|
||||
}
|
||||
$value = isset( $_POST['burn_events_assignment'] ) && is_scalar( $_POST['burn_events_assignment'] ) ? (int) $_POST['burn_events_assignment'] : 0;
|
||||
if ( -1 === $value || ( $value > 0 && self::is_layout( get_post( $value ) ) ) ) {
|
||||
update_post_meta( $post_id, self::EVENT_TEMPLATE_META, $value );
|
||||
} else {
|
||||
delete_post_meta( $post_id, self::EVENT_TEMPLATE_META );
|
||||
}
|
||||
}
|
||||
|
||||
private static function can_save( int $id, string $field, string $action ): bool {
|
||||
return ! wp_is_post_autosave( $id ) && ! wp_is_post_revision( $id )
|
||||
&& current_user_can( 'edit_post', $id )
|
||||
&& isset( $_POST[ $field ] ) && is_string( $_POST[ $field ] )
|
||||
&& wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST[ $field ] ) ), $action );
|
||||
}
|
||||
|
||||
public static function builder_notice(): void {
|
||||
$screen = get_current_screen();
|
||||
if ( ! $screen || self::POST_TYPE !== $screen->post_type || ! current_user_can( self::CAPABILITY ) ) {
|
||||
return;
|
||||
}
|
||||
if ( ! self::is_elementor_ready() ) {
|
||||
echo '<div class="notice notice-info"><p>' . esc_html__( 'Activate Elementor to design and publish Single Event templates.', 'burn-events' ) . '</p></div>';
|
||||
return;
|
||||
}
|
||||
if ( 'edit' !== $screen->base ) {
|
||||
return;
|
||||
}
|
||||
?>
|
||||
<div class="notice notice-info">
|
||||
<p><?php esc_html_e( 'Design a template with Elementor, publish it, then choose Use as default. You can also select a template on an individual event.', 'burn-events' ); ?></p>
|
||||
<form action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" method="post">
|
||||
<input type="hidden" name="action" value="burn_events_create_starter">
|
||||
<?php wp_nonce_field( 'burn_events_create_starter' ); ?>
|
||||
<p><button type="submit" class="button"><?php esc_html_e( 'Create starter template', 'burn-events' ); ?></button></p>
|
||||
</form>
|
||||
</div>
|
||||
<?php
|
||||
}
|
||||
|
||||
public static function default_row_action( array $actions, WP_Post $post ): array {
|
||||
if ( ! self::is_layout( $post ) || ! current_user_can( self::CAPABILITY ) ) {
|
||||
return $actions;
|
||||
}
|
||||
$is_default = $post->ID === (int) get_option( self::DEFAULT_OPTION, 0 );
|
||||
$id = $is_default ? 0 : $post->ID;
|
||||
$url = add_query_arg( [ 'action' => 'burn_events_set_default', 'template' => $id ], admin_url( 'admin-post.php' ) );
|
||||
$label = $is_default ? __( 'Clear default', 'burn-events' ) : __( 'Use as default', 'burn-events' );
|
||||
$actions['burn-events-default'] = '<a href="' . esc_url( wp_nonce_url( $url, 'burn_events_set_default_' . $id ) ) . '">' . esc_html( $label ) . '</a>';
|
||||
return $actions;
|
||||
}
|
||||
|
||||
public static function display_default_state( array $states, WP_Post $post ): array {
|
||||
if ( self::is_layout( $post ) && $post->ID === (int) get_option( self::DEFAULT_OPTION, 0 ) ) {
|
||||
$states['burn-events-default'] = __( 'Default event template', 'burn-events' );
|
||||
}
|
||||
return $states;
|
||||
}
|
||||
|
||||
public static function set_default(): void {
|
||||
$id = isset( $_GET['template'] ) && is_scalar( $_GET['template'] ) ? absint( $_GET['template'] ) : 0;
|
||||
if ( ! current_user_can( self::CAPABILITY ) ) {
|
||||
wp_die( esc_html__( 'You cannot change the default event template.', 'burn-events' ), '', [ 'response' => 403 ] );
|
||||
}
|
||||
check_admin_referer( 'burn_events_set_default_' . $id );
|
||||
if ( $id && ! self::is_layout( get_post( $id ) ) ) {
|
||||
wp_die( esc_html__( 'Publish the template before making it the default.', 'burn-events' ), '', [ 'response' => 400, 'back_link' => true ] );
|
||||
}
|
||||
update_option( self::DEFAULT_OPTION, $id, false );
|
||||
wp_safe_redirect( self::list_url() );
|
||||
exit;
|
||||
}
|
||||
|
||||
public static function create_starter(): void {
|
||||
if ( ! current_user_can( self::CAPABILITY ) || ! self::is_elementor_ready() ) {
|
||||
wp_die( esc_html__( 'You cannot create an Elementor event template.', 'burn-events' ), '', [ 'response' => 403 ] );
|
||||
}
|
||||
check_admin_referer( 'burn_events_create_starter' );
|
||||
$id = wp_insert_post(
|
||||
[
|
||||
'post_type' => self::POST_TYPE,
|
||||
'post_title' => __( 'Single Event', 'burn-events' ),
|
||||
'post_status' => 'draft',
|
||||
],
|
||||
true
|
||||
);
|
||||
if ( is_wp_error( $id ) ) {
|
||||
wp_die( esc_html( $id->get_error_message() ), '', [ 'response' => 500, 'back_link' => true ] );
|
||||
}
|
||||
$layout = require __DIR__ . '/starter-layout.php';
|
||||
update_post_meta( $id, Document::ELEMENTOR_DATA_META_KEY, wp_slash( wp_json_encode( $layout ) ) );
|
||||
$document = Elementor::instance()->documents->get( $id );
|
||||
$document->set_is_built_with_elementor( true );
|
||||
wp_safe_redirect( $document->get_edit_url() );
|
||||
exit;
|
||||
}
|
||||
}
|
||||
390
includes/class-transfer.php
Normal file
390
includes/class-transfer.php
Normal file
@@ -0,0 +1,390 @@
|
||||
<?php
|
||||
|
||||
namespace BurnEvents;
|
||||
|
||||
use DateTimeImmutable;
|
||||
use DateTimeZone;
|
||||
use InvalidArgumentException;
|
||||
use WP_Post;
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
final class Transfer {
|
||||
private const CSV_COLUMNS = [
|
||||
'source_id', 'title', 'description', 'start_date', 'start_time', 'end_date', 'end_time', 'timezone',
|
||||
'all_day', 'location', 'cost', 'url', 'status', 'featured', 'hidden', 'repeat', 'interval', 'weekdays',
|
||||
'monthly', 'count', 'until', 'include', 'exclude', 'categories', 'tags', 'venues', 'organizers', 'series', 'fields',
|
||||
];
|
||||
|
||||
public static function register(): void {
|
||||
add_action( 'template_redirect', [ self::class, 'download_ics' ], 1 );
|
||||
add_action( 'admin_post_burn_events_export', [ self::class, 'export_csv' ] );
|
||||
add_action( 'admin_post_burn_events_import', [ self::class, 'import' ] );
|
||||
}
|
||||
|
||||
public static function ics_url( ?array $row = null ): string {
|
||||
if ( $row ) {
|
||||
return add_query_arg( 'be_ical', '1', Events::event_url( $row ) );
|
||||
}
|
||||
return add_query_arg( 'be_ical', '1', Calendar::archive_url() );
|
||||
}
|
||||
|
||||
public static function google_url( WP_Post $event, array $row, array $data ): string {
|
||||
[ $start, $end ] = self::ics_dates( $row, $data );
|
||||
return add_query_arg( [
|
||||
'action' => 'TEMPLATE', 'text' => get_the_title( $event ), 'dates' => $start . '/' . $end,
|
||||
'details' => Events::event_url( $row ), 'location' => $data['location'],
|
||||
], 'https://calendar.google.com/calendar/render' );
|
||||
}
|
||||
|
||||
public static function download_ics(): void {
|
||||
if ( '1' !== Calendar::request( 'be_ical' ) ) {
|
||||
return;
|
||||
}
|
||||
if ( is_singular( Events::EVENT ) ) {
|
||||
$event = get_queried_object();
|
||||
$row = 'publish' === $event->post_status && '' === $event->post_password ? Events::occurrence( $event->ID, Calendar::request( 'be_occ' ) ) : null;
|
||||
$rows = $row ? [ $row ] : [];
|
||||
} elseif ( is_post_type_archive( Events::EVENT ) ) {
|
||||
$rows = Events::query( [ 'from' => gmdate( 'Y-m-d H:i:s' ), 'limit' => 1000 ] );
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
nocache_headers();
|
||||
header( 'Content-Type: text/calendar; charset=utf-8' );
|
||||
header( 'Content-Disposition: attachment; filename="eventlabs.ics"' );
|
||||
echo "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//hostLabs//eventLabs//EN\r\nCALSCALE:GREGORIAN\r\n";
|
||||
$site = wp_parse_url( home_url(), PHP_URL_HOST );
|
||||
foreach ( $rows as $row ) {
|
||||
$id = (int) $row['event_id'];
|
||||
$data = Events::event_data( $id );
|
||||
[ $start, $end, $all_day ] = self::ics_dates( $row, $data );
|
||||
$location = $data['location'];
|
||||
$venue = Events::locations( $data['venue'], Events::VENUE )[0] ?? null;
|
||||
if ( $venue ) {
|
||||
$location = get_the_title( $venue );
|
||||
}
|
||||
$lines = [
|
||||
'BEGIN:VEVENT',
|
||||
'UID:' . $id . '-' . strtotime( $row['starts_at'] . ' UTC' ) . '@' . $site,
|
||||
'DTSTAMP:' . gmdate( 'Ymd\THis\Z' ),
|
||||
'DTSTART' . ( $all_day ? ';VALUE=DATE:' : ':' ) . $start,
|
||||
'DTEND' . ( $all_day ? ';VALUE=DATE:' : ':' ) . $end,
|
||||
'SUMMARY:' . self::ics_text( get_the_title( $id ) ),
|
||||
'DESCRIPTION:' . self::ics_text( wp_strip_all_tags( strip_shortcodes( get_post_field( 'post_content', $id ) ) ) ),
|
||||
'LOCATION:' . self::ics_text( $location ),
|
||||
'URL:' . esc_url_raw( Events::event_url( $row ) ),
|
||||
'STATUS:' . ( [ 'cancelled' => 'CANCELLED', 'postponed' => 'TENTATIVE' ][ $data['status'] ] ?? 'CONFIRMED' ),
|
||||
'END:VEVENT',
|
||||
];
|
||||
foreach ( $lines as $line ) {
|
||||
echo self::fold( $line ) . "\r\n";
|
||||
}
|
||||
}
|
||||
echo "END:VCALENDAR\r\n";
|
||||
exit;
|
||||
}
|
||||
|
||||
private static function ics_dates( array $row, array $data ): array {
|
||||
$all_day = ! empty( $data['schedule']['all_day'] );
|
||||
if ( $all_day ) {
|
||||
$zone = $data['schedule']['timezone'];
|
||||
return [ Events::local_time( $row['starts_at'], $zone )->format( 'Ymd' ), Events::local_time( $row['ends_at'], $zone )->format( 'Ymd' ), true ];
|
||||
}
|
||||
return [ gmdate( 'Ymd\THis\Z', strtotime( $row['starts_at'] . ' UTC' ) ), gmdate( 'Ymd\THis\Z', strtotime( $row['ends_at'] . ' UTC' ) ), false ];
|
||||
}
|
||||
|
||||
private static function ics_text( string $value ): string {
|
||||
return str_replace( [ '\\', "\r\n", "\r", "\n", ';', ',' ], [ '\\\\', '\\n', '\\n', '\\n', '\\;', '\\,' ], $value );
|
||||
}
|
||||
|
||||
private static function fold( string $line ): string {
|
||||
$parts = [];
|
||||
while ( strlen( $line ) > 75 ) {
|
||||
$bytes = 75;
|
||||
while ( ( ord( $line[ $bytes ] ) & 0xc0 ) === 0x80 ) {
|
||||
$bytes--;
|
||||
}
|
||||
$parts[] = substr( $line, 0, $bytes );
|
||||
$line = ' ' . substr( $line, $bytes );
|
||||
}
|
||||
$parts[] = $line;
|
||||
return implode( "\r\n", $parts );
|
||||
}
|
||||
|
||||
private static function admin_url(): string {
|
||||
return admin_url( 'edit.php?post_type=burn_event&page=burn-events-transfer' );
|
||||
}
|
||||
|
||||
public static function admin_page(): void {
|
||||
$result = get_transient( 'burn_events_import_' . get_current_user_id() );
|
||||
delete_transient( 'burn_events_import_' . get_current_user_id() );
|
||||
?>
|
||||
<div class="wrap">
|
||||
<h1><?php esc_html_e( 'Import and Export Events', 'burn-events' ); ?></h1>
|
||||
<?php if ( is_array( $result ) ) : ?>
|
||||
<div class="notice notice-info">
|
||||
<p><?php printf( esc_html__( '%1$d imported. %2$d previously imported.', 'burn-events' ), $result['imported'], $result['skipped'] ); ?></p>
|
||||
<?php if ( $result['errors'] ) : ?><ul><?php foreach ( $result['errors'] as $error ) : ?><li><?php echo esc_html( $error ); ?></li><?php endforeach; ?></ul><?php endif; ?>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
<?php Legacy_Migration::section(); ?>
|
||||
<h2><?php esc_html_e( 'Import events', 'burn-events' ); ?></h2>
|
||||
<p><?php esc_html_e( 'Upload a CSV or iCalendar (.ics) file. Imported events are saved as drafts for review.', 'burn-events' ); ?></p>
|
||||
<p><?php esc_html_e( 'Required CSV columns are title, start_date, start_time, and end_time. Use YYYY-MM-DD dates and HH:MM times. All-day events can leave times blank.', 'burn-events' ); ?></p>
|
||||
<form action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>" method="post" enctype="multipart/form-data">
|
||||
<input type="hidden" name="action" value="burn_events_import">
|
||||
<?php wp_nonce_field( 'burn_events_import' ); ?>
|
||||
<label><?php esc_html_e( 'Calendar file', 'burn-events' ); ?> <input type="file" name="calendar_file" accept=".csv,.ics,text/csv,text/calendar" required></label>
|
||||
<?php submit_button( __( 'Import drafts', 'burn-events' ), 'primary' ); ?>
|
||||
</form>
|
||||
<h2><?php esc_html_e( 'Export events', 'burn-events' ); ?></h2>
|
||||
<p><a class="button" href="<?php echo esc_url( wp_nonce_url( admin_url( 'admin-post.php?action=burn_events_export' ), 'burn_events_export' ) ); ?>"><?php esc_html_e( 'Download CSV', 'burn-events' ); ?></a></p>
|
||||
</div>
|
||||
<?php
|
||||
}
|
||||
|
||||
private static function authorize( string $action ): void {
|
||||
if ( ! current_user_can( 'manage_options' ) ) {
|
||||
wp_die( esc_html__( 'Administrator access is required.', 'burn-events' ), '', [ 'response' => 403 ] );
|
||||
}
|
||||
check_admin_referer( $action );
|
||||
}
|
||||
|
||||
public static function export_csv(): void {
|
||||
self::authorize( 'burn_events_export' );
|
||||
nocache_headers();
|
||||
header( 'Content-Type: text/csv; charset=utf-8' );
|
||||
header( 'Content-Disposition: attachment; filename="eventlabs.csv"' );
|
||||
$output = fopen( 'php://output', 'w' );
|
||||
fputcsv( $output, self::CSV_COLUMNS, ',', '"', '' );
|
||||
for ( $page = 1; ; $page++ ) {
|
||||
$posts = get_posts( [
|
||||
'post_type' => Events::EVENT, 'post_status' => [ 'publish', 'private', 'draft', 'pending', 'future' ],
|
||||
'posts_per_page' => 100, 'paged' => $page, 'orderby' => 'ID', 'order' => 'ASC',
|
||||
] );
|
||||
foreach ( $posts as $post ) {
|
||||
$data = Events::event_data( $post->ID );
|
||||
$category = wp_get_post_terms( $post->ID, Events::CATEGORY, [ 'fields' => 'names' ] );
|
||||
$tags = wp_get_post_terms( $post->ID, 'post_tag', [ 'fields' => 'names' ] );
|
||||
$row = [
|
||||
'source_id' => get_post_meta( $post->ID, '_burn_import_id', true ) ?: home_url( '/' ) . '#event-' . $post->ID,
|
||||
'title' => $post->post_title, 'description' => $post->post_content,
|
||||
'categories' => is_array( $category ) ? implode( '|', $category ) : '',
|
||||
'tags' => is_array( $tags ) ? implode( '|', $tags ) : '',
|
||||
'venues' => self::titles( $data['venue'], Events::VENUE ),
|
||||
'organizers' => self::titles( $data['organizer'], Events::ORGANIZER ),
|
||||
'series' => self::titles( $data['series'], Events::SERIES ),
|
||||
'fields' => wp_json_encode( $data['fields'] ),
|
||||
] + $data['schedule'] + $data;
|
||||
$values = [];
|
||||
foreach ( self::CSV_COLUMNS as $column ) {
|
||||
$value = $row[ $column ] ?? '';
|
||||
$text = is_array( $value ) ? implode( ',', $value ) : (string) $value;
|
||||
$values[] = preg_match( '/^[\t\r\n ]*[=+@-]/', $text ) ? "'" . $text : $text;
|
||||
}
|
||||
fputcsv( $output, $values, ',', '"', '' );
|
||||
}
|
||||
if ( count( $posts ) < 100 ) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
fclose( $output );
|
||||
exit;
|
||||
}
|
||||
|
||||
private static function titles( array $ids, string $type ): string {
|
||||
return implode( '|', array_map( 'get_the_title', Events::locations( $ids, $type ) ) );
|
||||
}
|
||||
|
||||
public static function import(): void {
|
||||
self::authorize( 'burn_events_import' );
|
||||
$file = $_FILES['calendar_file'] ?? null;
|
||||
$result = [ 'imported' => 0, 'skipped' => 0, 'errors' => [] ];
|
||||
try {
|
||||
if ( ! is_array( $file ) || UPLOAD_ERR_OK !== $file['error'] || ! is_uploaded_file( $file['tmp_name'] ) || $file['size'] > min( wp_max_upload_size(), 5 * MB_IN_BYTES ) ) {
|
||||
throw new InvalidArgumentException( __( 'Choose a CSV or iCalendar file up to 5 MB.', 'burn-events' ) );
|
||||
}
|
||||
$extension = strtolower( pathinfo( $file['name'], PATHINFO_EXTENSION ) );
|
||||
if ( ! in_array( $extension, [ 'csv', 'ics' ], true ) ) {
|
||||
throw new InvalidArgumentException( __( 'Choose a .csv or .ics file.', 'burn-events' ) );
|
||||
}
|
||||
$rows = 'csv' === $extension ? self::csv_rows( $file['tmp_name'] ) : self::ics_rows( $file['tmp_name'] );
|
||||
foreach ( $rows as $line => $row ) {
|
||||
try {
|
||||
if ( $row instanceof \Throwable ) {
|
||||
throw $row;
|
||||
}
|
||||
$status = self::import_row( $row );
|
||||
$result[ $status ]++;
|
||||
} catch ( \Throwable $error ) {
|
||||
$result['errors'][] = sprintf( __( 'Entry %1$d: %2$s', 'burn-events' ), $line, $error->getMessage() );
|
||||
}
|
||||
}
|
||||
} catch ( \Throwable $error ) {
|
||||
$result['errors'][] = $error->getMessage();
|
||||
}
|
||||
set_transient( 'burn_events_import_' . get_current_user_id(), $result, MINUTE_IN_SECONDS );
|
||||
wp_safe_redirect( self::admin_url(), 303 );
|
||||
exit;
|
||||
}
|
||||
|
||||
private static function csv_rows( string $path ): \Generator {
|
||||
$input = fopen( $path, 'r' );
|
||||
if ( ! $input ) {
|
||||
throw new InvalidArgumentException( __( 'The CSV could not be read.', 'burn-events' ) );
|
||||
}
|
||||
try {
|
||||
$header = fgetcsv( $input, 0, ',', '"', '' ) ?: [];
|
||||
$header = array_map( static fn( $column ): string => sanitize_key( trim( (string) $column ) ), $header );
|
||||
if ( ! in_array( 'title', $header, true ) || ! in_array( 'start_date', $header, true ) ) {
|
||||
throw new InvalidArgumentException( __( 'The CSV needs title and start_date column headers.', 'burn-events' ) );
|
||||
}
|
||||
for ( $line = 2; false !== ( $cells = fgetcsv( $input, 0, ',', '"', '' ) ); $line++ ) {
|
||||
if ( [ null ] === $cells ) {
|
||||
continue;
|
||||
}
|
||||
if ( count( $cells ) !== count( $header ) ) {
|
||||
yield $line => new InvalidArgumentException( __( 'This row has a different number of columns than the header.', 'burn-events' ) );
|
||||
continue;
|
||||
}
|
||||
$cells = array_map( static fn( $text ): string => (string) preg_replace( '/^\x27(?=[\t\r\n ]*[=+@-])/', '', (string) $text ), $cells );
|
||||
yield $line => array_combine( $header, $cells );
|
||||
}
|
||||
} finally {
|
||||
fclose( $input );
|
||||
}
|
||||
}
|
||||
|
||||
private static function ics_rows( string $path ): \Generator {
|
||||
$content = file_get_contents( $path );
|
||||
if ( ! is_string( $content ) || ! str_contains( $content, 'BEGIN:VCALENDAR' ) ) {
|
||||
throw new InvalidArgumentException( __( 'This is not a readable iCalendar file.', 'burn-events' ) );
|
||||
}
|
||||
$content = preg_replace( '/\r?\n[ \t]/', '', $content );
|
||||
preg_match_all( '/^BEGIN:VEVENT\r?\n(.*?)^END:VEVENT\r?$/ms', $content, $matches );
|
||||
foreach ( $matches[1] as $index => $entry ) {
|
||||
try {
|
||||
yield $index + 1 => self::ics_entry( $entry );
|
||||
} catch ( \Throwable $error ) {
|
||||
yield $index + 1 => $error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static function ics_entry( string $entry ): array {
|
||||
$fields = [];
|
||||
foreach ( preg_split( '/\R/', $entry ) as $line ) {
|
||||
[ $key, $value ] = array_pad( explode( ':', $line, 2 ), 2, '' );
|
||||
[ $name, $parameter ] = array_pad( explode( ';', $key, 2 ), 2, '' );
|
||||
$fields[ $name ][] = [ $parameter, $value ];
|
||||
}
|
||||
$start = self::ics_parse_date( $fields['DTSTART'][0] ?? [ '', '' ], Admin::options()['timezone'] );
|
||||
$all_day = strlen( $fields['DTSTART'][0][1] ) === 8;
|
||||
$end = isset( $fields['DTEND'][0] ) ? self::ics_parse_date( $fields['DTEND'][0], $start->getTimezone()->getName() )->setTimezone( $start->getTimezone() ) : $start->modify( $all_day ? '+1 day' : '+1 hour' );
|
||||
if ( $all_day ) {
|
||||
$end = $end->modify( '-1 day' );
|
||||
}
|
||||
$unescape = static fn( string $text ): string => strtr( $text, [ '\\n' => "\n", '\\N' => "\n", '\\,' => ',', '\\;' => ';', '\\\\' => '\\' ] );
|
||||
$row = [
|
||||
'source_id' => $fields['UID'][0][1] ?? '',
|
||||
'title' => $unescape( $fields['SUMMARY'][0][1] ?? '' ),
|
||||
'description' => $unescape( $fields['DESCRIPTION'][0][1] ?? '' ),
|
||||
'location' => $unescape( $fields['LOCATION'][0][1] ?? '' ),
|
||||
'url' => $fields['URL'][0][1] ?? '',
|
||||
'status' => 'CANCELLED' === ( $fields['STATUS'][0][1] ?? '' ) ? 'cancelled' : 'scheduled',
|
||||
'start_date' => $start->format( 'Y-m-d' ), 'start_time' => $start->format( 'H:i' ),
|
||||
'end_date' => $end->format( 'Y-m-d' ), 'end_time' => $end->format( 'H:i' ),
|
||||
'timezone' => $start->getTimezone()->getName(), 'all_day' => $all_day,
|
||||
];
|
||||
if ( isset( $fields['RRULE'][0] ) ) {
|
||||
$rule = [];
|
||||
foreach ( explode( ';', $fields['RRULE'][0][1] ) as $part ) {
|
||||
[ $key, $value ] = array_pad( explode( '=', $part, 2 ), 2, '' );
|
||||
$rule[ $key ] = $value;
|
||||
}
|
||||
$freq = strtolower( $rule['FREQ'] ?? '' );
|
||||
if ( ! in_array( $freq, Schedule::REPEATS, true ) || array_diff( array_keys( $rule ), [ 'FREQ', 'INTERVAL', 'COUNT', 'UNTIL', 'BYDAY' ] ) || ( isset( $rule['BYDAY'] ) && 'weekly' !== $freq ) ) {
|
||||
throw new InvalidArgumentException( __( 'This recurrence rule requires manual review.', 'burn-events' ) );
|
||||
}
|
||||
$days = [ 'MO' => 1, 'TU' => 2, 'WE' => 3, 'TH' => 4, 'FR' => 5, 'SA' => 6, 'SU' => 7 ];
|
||||
$row['repeat'] = $freq;
|
||||
$row['interval'] = $rule['INTERVAL'] ?? '1';
|
||||
$row['count'] = $rule['COUNT'] ?? '0';
|
||||
$row['weekdays'] = implode( ',', array_values( array_intersect_key( $days, array_flip( explode( ',', $rule['BYDAY'] ?? '' ) ) ) ) );
|
||||
$row['until'] = isset( $rule['UNTIL'] ) ? self::ics_parse_date( [ '', $rule['UNTIL'] ], $row['timezone'] )->setTimezone( $start->getTimezone() )->format( 'Y-m-d' ) : '';
|
||||
}
|
||||
foreach ( [ 'EXDATE' => 'exclude', 'RDATE' => 'include' ] as $name => $key ) {
|
||||
$dates = [];
|
||||
foreach ( $fields[ $name ] ?? [] as [ $parameters, $values ] ) {
|
||||
foreach ( explode( ',', $values ) as $value ) {
|
||||
$dates[] = self::ics_parse_date( [ $parameters, $value ], $row['timezone'] )->setTimezone( $start->getTimezone() )->format( 'Y-m-d' );
|
||||
}
|
||||
}
|
||||
$row[ $key ] = implode( ',', $dates );
|
||||
}
|
||||
return $row;
|
||||
}
|
||||
|
||||
private static function ics_parse_date( array $pair, string $fallback ): DateTimeImmutable {
|
||||
[ $parameters, $value ] = $pair;
|
||||
preg_match( '/(?:^|;)TZID=([^;]+)/', $parameters, $match );
|
||||
$zone = new DateTimeZone( str_ends_with( $value, 'Z' ) ? 'UTC' : ( $match[1] ?? $fallback ) );
|
||||
$format = 8 === strlen( $value ) ? 'Ymd' : 'Ymd\THis';
|
||||
$value = rtrim( $value, 'Z' );
|
||||
$date = DateTimeImmutable::createFromFormat( '!' . $format, $value, $zone );
|
||||
if ( ! $date || $date->format( $format ) !== $value ) {
|
||||
throw new InvalidArgumentException( __( 'The event contains an invalid iCalendar date.', 'burn-events' ) );
|
||||
}
|
||||
return $date;
|
||||
}
|
||||
|
||||
private static function import_row( array $row ): string {
|
||||
$title = sanitize_text_field( $row['title'] ?? '' );
|
||||
if ( '' === $title ) {
|
||||
throw new InvalidArgumentException( __( 'The event title is missing.', 'burn-events' ) );
|
||||
}
|
||||
$source = sanitize_text_field( $row['source_id'] ?? '' );
|
||||
if ( $source && get_posts( [
|
||||
'post_type' => Events::EVENT, 'post_status' => 'any', 'fields' => 'ids', 'posts_per_page' => 1,
|
||||
'meta_key' => '_burn_import_id', 'meta_value' => $source,
|
||||
] ) ) {
|
||||
return 'skipped';
|
||||
}
|
||||
$relations = [ 'venues' => 'venue', 'organizers' => 'organizer', 'series' => 'series' ];
|
||||
foreach ( $relations as $column => $key ) {
|
||||
$ids = [];
|
||||
foreach ( array_filter( array_map( 'trim', explode( '|', $row[ $column ] ?? '' ) ) ) as $name ) {
|
||||
$found = get_posts( [ 'post_type' => Events::RELATIONS[ $key ], 'post_status' => 'publish', 'title' => $name, 'fields' => 'ids', 'posts_per_page' => 1 ] );
|
||||
if ( $found ) {
|
||||
$ids[] = $found[0];
|
||||
}
|
||||
}
|
||||
$row[ $key ] = $ids;
|
||||
}
|
||||
$row['weekdays'] = explode( ',', $row['weekdays'] ?? '' );
|
||||
$row['fields'] = (array) json_decode( $row['fields'] ?? '{}', true );
|
||||
$event = Events::validate_event( $row );
|
||||
$id = wp_insert_post( wp_slash( [
|
||||
'post_type' => Events::EVENT, 'post_status' => 'draft', 'post_title' => $title,
|
||||
'post_content' => wp_kses_post( $row['description'] ?? '' ), 'comment_status' => 'closed',
|
||||
] ), true );
|
||||
if ( is_wp_error( $id ) ) {
|
||||
throw new InvalidArgumentException( $id->get_error_message() );
|
||||
}
|
||||
try {
|
||||
Events::save( $id, $event );
|
||||
if ( $source ) {
|
||||
update_post_meta( $id, '_burn_import_id', $source );
|
||||
}
|
||||
foreach ( [ 'categories' => Events::CATEGORY, 'tags' => 'post_tag' ] as $column => $taxonomy ) {
|
||||
$names = array_values( array_filter( array_map( 'sanitize_text_field', explode( '|', $row[ $column ] ?? '' ) ) ) );
|
||||
wp_set_object_terms( $id, $names, $taxonomy );
|
||||
}
|
||||
} catch ( \Throwable $error ) {
|
||||
wp_trash_post( $id );
|
||||
throw $error;
|
||||
}
|
||||
return 'imported';
|
||||
}
|
||||
}
|
||||
47
includes/starter-layout.php
Normal file
47
includes/starter-layout.php
Normal file
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
|
||||
defined( 'ABSPATH' ) || exit;
|
||||
|
||||
$widget = static function ( string $name, array $settings = [] ): array {
|
||||
return [
|
||||
'id' => Elementor\Utils::generate_random_string(),
|
||||
'elType' => 'widget', 'widgetType' => $name,
|
||||
'settings' => $settings, 'elements' => [],
|
||||
];
|
||||
};
|
||||
|
||||
$field = static fn( string $key ): array => $widget( 'burn-events-field', [ 'field' => $key ] );
|
||||
$event = static fn( string $key ): array => $widget( 'burn-events-event-' . $key );
|
||||
|
||||
$container = static function ( string $class, array $children, bool $inner = true ): array {
|
||||
return [
|
||||
'id' => Elementor\Utils::generate_random_string(), 'elType' => 'container', 'isInner' => $inner,
|
||||
'settings' => [ 'content_width' => 'full', 'css_classes' => $class ], 'elements' => $children,
|
||||
];
|
||||
};
|
||||
|
||||
return [
|
||||
$container( 'be-starter be-single-layout', [
|
||||
$container( 'be-layout-nav', [ $field( 'back' ), $field( 'terms' ) ] ),
|
||||
$container( 'be-layout-hero', [
|
||||
$container( 'be-layout-title', [ $event( 'title' ), $event( 'schedule' ), $field( 'status' ) ] ),
|
||||
$container( 'be-layout-photo', [ $event( 'image' ) ] ),
|
||||
] ),
|
||||
$container( 'be-layout-body', [
|
||||
$container( 'be-layout-reading', [
|
||||
$container( 'be-layout-overview', [
|
||||
$widget( 'heading', [ 'title' => __( 'About the event', 'burn-events' ), 'header_size' => 'h2' ] ),
|
||||
$event( 'description' ), $field( 'fields' ),
|
||||
] ),
|
||||
$container( 'be-layout-calendar', [
|
||||
$widget( 'heading', [ 'title' => __( 'Add to calendar', 'burn-events' ), 'header_size' => 'h2' ] ),
|
||||
$event( 'export' ),
|
||||
] ),
|
||||
] ),
|
||||
$container( 'be-layout-details', [
|
||||
$event( 'cost' ), $event( 'venue' ), $event( 'organizer' ), $field( 'series' ), $field( 'website' ),
|
||||
] ),
|
||||
] ),
|
||||
$event( 'related' ),
|
||||
], false ),
|
||||
];
|
||||
Reference in New Issue
Block a user