Files
eventLabs/includes/class-transfer.php
2026-11-11 21:30:20 -05:00

391 lines
17 KiB
PHP

<?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';
}
}