Files
eventLabs/includes/class-legacy-migration.php
josh db4747d85f
All checks were successful
WordPress release / release (push) Successful in 7s
Choose an Elementor event template during or after migration
2026-11-12 15:34:43 -05:00

439 lines
21 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?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 TEMPLATE_BATCH = 100;
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' ] );
add_action( 'wp_ajax_nopriv_' . 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 ) );
}
private static function copied_count(): int {
global $wpdb;
$table = Api::table();
return (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $table x JOIN $wpdb->posts p ON p.ID = x.post_id WHERE x.source = %s AND p.post_type = %s AND p.post_status NOT IN ('trash', 'auto-draft', 'inherit')", self::SOURCE, Events::EVENT ) );
}
public static function section(): void {
$count = self::count();
$copies = self::copied_count();
if ( ! $count && ! $copies && ! self::installed() ) {
return;
}
$templates = $count || $copies ? Single_Event_Templates::migration_templates() : [];
?>
<section id="eventlabs-migration">
<h2><?php esc_html_e( 'Migrate from The Events Calendar', 'burn-events' ); ?></h2>
<p><a href="<?php echo esc_url( 'https://git.labs.casa/josh/eventLabs/src/branch/main/docs/MIGRATION.md' ); ?>"><?php esc_html_e( 'Read the migration guide', 'burn-events' ); ?></a></p>
<?php if ( ! $count ) : ?>
<p><?php esc_html_e( 'No source events are available to copy.', '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>
<?php endif; ?>
<?php if ( $copies ) : ?>
<p><?php printf( esc_html( _n( '%s event already copied.', '%s events already copied.', $copies, 'burn-events' ) ), esc_html( number_format_i18n( $copies ) ) ); ?></p>
<?php endif; ?>
<?php if ( ( $count || $copies ) && ! $templates ) : ?>
<p><?php esc_html_e( 'To choose an Elementor layout here, activate Elementor and publish a layout under', 'burn-events' ); ?> <a href="<?php echo esc_url( Single_Event_Templates::list_url() ); ?>"><?php esc_html_e( 'Single Event Templates', 'burn-events' ); ?></a>.</p>
<?php endif; ?>
<?php if ( $count || ( $copies && $templates ) ) : ?>
<form data-be-migrate data-has-copies="<?php echo $copies ? '1' : '0'; ?>" action="<?php echo esc_url( admin_url( 'admin-ajax.php', 'relative' ) ); ?>" method="post">
<input type="hidden" name="action" value="<?php echo esc_attr( self::ACTION ); ?>">
<?php wp_nonce_field( self::ACTION ); ?>
<?php if ( $templates ) : ?>
<p>
<label for="be-migration-template"><?php esc_html_e( 'Single event template', 'burn-events' ); ?></label>
<select id="be-migration-template" name="template_id" aria-describedby="be-migration-template-help">
<option value="0"><?php esc_html_e( 'Inherit site default', 'burn-events' ); ?></option>
<?php foreach ( $templates as $template ) : ?>
<option value="<?php echo esc_attr( (string) $template->ID ); ?>"><?php echo esc_html( get_the_title( $template ) ); ?></option>
<?php endforeach; ?>
</select>
</p>
<p class="description" id="be-migration-template-help"><?php esc_html_e( 'Choose a template for new copies. Applying it to copied events replaces their current template, including on published events.', 'burn-events' ); ?></p>
<?php endif; ?>
<p>
<?php if ( $count ) : ?>
<button type="submit" class="button button-primary" data-be-operation value="copy" disabled><?php esc_html_e( 'Copy events as drafts', 'burn-events' ); ?></button>
<?php endif; ?>
<?php if ( $templates ) : ?>
<button type="submit" class="button" data-be-operation value="apply" disabled><?php esc_html_e( 'Apply template to copied events', 'burn-events' ); ?></button>
<?php endif; ?>
</p>
<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 {
$signed_in = is_user_logged_in();
if ( ! $signed_in || ! 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' ), $signed_in ? 403 : 401 );
}
$after = is_scalar( $_POST['after'] ?? null ) ? absint( $_POST['after'] ) : 0;
$operation = $_POST['operation'] ?? 'copy';
$template_id = $_POST['template_id'] ?? '0';
if ( ! in_array( $operation, [ 'copy', 'apply' ], true ) || ! is_scalar( $template_id ) || ! ctype_digit( (string) $template_id ) ) {
wp_send_json_error( __( 'Choose a valid migration action and template.', 'burn-events' ), 400 );
}
$template_id = (int) $template_id;
// Other plugins may print during post creation. Keep that output out of the JSON response.
$buffer_level = ob_get_level();
ob_start();
try {
$result = 'apply' === $operation ? self::apply_template_batch( $after, $template_id ) : self::batch( $after, $template_id );
} catch ( InvalidArgumentException $error ) {
$validation_error = $error->getMessage();
$result = null;
} catch ( \Throwable ) {
$result = null;
} finally {
while ( ob_get_level() > $buffer_level && ob_end_clean() ) {
// Close only buffers opened while copying this batch.
}
}
if ( isset( $validation_error ) ) {
wp_send_json_error( $validation_error, 400 );
}
if ( null === $result ) {
$message = 'apply' === $operation ? __( 'The copied events could not be updated. You can retry the template assignment.', 'burn-events' ) : __( 'The source calendar could not be read. You can retry the migration.', 'burn-events' );
wp_send_json_error( $message, 500 );
}
wp_send_json_success( $result );
}
public static function batch( int $after, int $template_id = 0 ): array {
global $wpdb;
if ( $template_id ) {
self::require_template( $template_id );
}
$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, $template_id ) ];
} 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 require_template( int $template_id ): void {
if ( ! Single_Event_Templates::can_use_for_migration( $template_id ) ) {
throw new InvalidArgumentException( __( 'Choose a published template built with Elementor. Refresh the migration page if the template changed.', 'burn-events' ) );
}
}
public static function apply_template_batch( int $after, int $template_id ): array {
global $wpdb;
self::require_template( $template_id );
$table = Api::table();
$ids = $wpdb->get_col( $wpdb->prepare( "SELECT p.ID FROM $table x JOIN $wpdb->posts p ON p.ID = x.post_id WHERE x.source = %s AND p.post_type = %s AND p.ID > %d AND p.post_status NOT IN ('trash', 'auto-draft', 'inherit') ORDER BY p.ID LIMIT %d", self::SOURCE, Events::EVENT, $after, self::TEMPLATE_BATCH + 1 ) );
if ( $wpdb->last_error ) {
throw new RuntimeException( 'Copied event query failed.' );
}
$result = [ 'applied' => 0, 'skipped' => 0, 'errors' => [], 'next' => 0 ];
foreach ( array_slice( $ids, 0, self::TEMPLATE_BATCH ) as $id ) {
$after = (int) $id;
if ( ! current_user_can( 'edit_post', $after ) ) {
$result['errors'][] = sprintf( __( 'You cannot edit event #%d.', 'burn-events' ), $after );
continue;
}
try {
if ( Single_Event_Templates::assign( $after, $template_id ) ) {
clean_post_cache( $after );
++$result['applied'];
} else {
++$result['skipped'];
}
} catch ( \Throwable ) {
$result['errors'][] = sprintf( __( 'The template could not be assigned to event #%d.', 'burn-events' ), $after );
}
}
$result['next'] = count( $ids ) > self::TEMPLATE_BATCH ? $after : 0;
return $result;
}
private static function event( int $id, int $template_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 ) ] ],
];
if ( $template_id ) {
$payload['migration_template_id'] = $template_id;
}
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 );
}
}