Publish eventLabs 0.5.0
This commit is contained in:
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 );
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user