venue_repository ??= new \WebCalendar\Core\Infrastructure\Persistence\PdoVenueRepository( $this->pdo, $this->prefix ); return $this->venue_repository; } private function organizers(): \WebCalendar\Core\Infrastructure\Persistence\PdoOrganizerRepository { $this->organizer_repository ??= new \WebCalendar\Core\Infrastructure\Persistence\PdoOrganizerRepository( $this->pdo, $this->prefix ); return $this->organizer_repository; } /** * Link the event to matchOrCreate'd venue/organizer entities * (core 4.6 adoption): repeated runs reuse the stored entities. */ private function with_entities( Event $event, MappedTecEvent $item ): Event { if ( null !== $item->venue ) { $venue = $this->venues()->findByName( $item->venue->name() ) ?? $this->venues()->save( $item->venue ); $event = $event->withVenueId( $venue->id() ); } if ( null !== $item->organizer ) { $organizer = $this->organizers()->findByName( $item->organizer->name() ) ?? $this->organizers()->save( $item->organizer ); $event = $event->withOrganizerId( $organizer->id() ); } return $event; } /** * Import a batch of mapped events inside one transaction. * * @param list $mapped Mapped events. * @param array> $instance_map Occurrence * starts (site timezone) keyed by uid, for events flagged * needs_instance_expansion. * @return array{import_id: int, imported: int, duplicates: int, instances: int, categories: int, tags: int, warnings: list} * @throws \Throwable A mid-import failure rolls everything back first. */ public function import( array $mapped, array $instance_map = array() ): array { $report = array( 'import_id' => 0, 'imported' => 0, 'duplicates' => 0, 'instances' => 0, 'categories' => 0, 'tags' => 0, 'warnings' => array(), ); $this->pdo->beginTransaction(); try { $import_id = $this->next_id( 'webcal_import', 'cal_import_id' ); $report['import_id'] = $import_id; $this->exec( "INSERT INTO {$this->prefix}webcal_import ( cal_import_id, cal_name, cal_date, cal_type, cal_login ) VALUES ( ?, ?, ?, ?, ? )", array( $import_id, 'The Events Calendar import', (int) gmdate( 'Ymd' ), self::RUN_TYPE, '' ) ); $label_ids = array(); foreach ( $mapped as $item ) { foreach ( $item->warnings as $warning ) { $report['warnings'][] = $warning; } $desired = $this->desired_events( $item, $instance_map ); $report['instances'] += $desired['instances']; foreach ( $desired['events'] as $event ) { if ( $this->uid_exists( $event->uid() ) ) { ++$report['duplicates']; continue; } $created = $this->insert_event( $event, $item, $import_id, $label_ids ); $report['categories'] += $created['categories']; $report['tags'] += $created['tags']; ++$report['imported']; } } // A run that imported nothing would only clutter the runs list // with an empty undo target (1.9 migration parity). if ( 0 === $report['imported'] ) { $this->exec( "DELETE FROM {$this->prefix}webcal_import WHERE cal_import_id = ?", array( $import_id ) ); $report['import_id'] = 0; } $this->pdo->commit(); } catch ( \Throwable $e ) { $this->pdo->rollBack(); throw $e; } return $report; } /** * Past TEC import runs, newest first. * * @return list */ public function list_runs(): array { $stmt = $this->pdo->prepare( "SELECT i.cal_import_id, i.cal_date, COUNT(d.cal_id) AS entries FROM {$this->prefix}webcal_import i LEFT JOIN {$this->prefix}webcal_import_data d ON d.cal_import_id = i.cal_import_id WHERE i.cal_type = ? GROUP BY i.cal_import_id, i.cal_date ORDER BY i.cal_import_id DESC" ); $stmt->execute( array( self::RUN_TYPE ) ); $runs = array(); foreach ( $stmt->fetchAll( PDO::FETCH_ASSOC ) as $row ) { $runs[] = array( 'import_id' => (int) $row['cal_import_id'], 'date' => (int) $row['cal_date'], 'entries' => (int) $row['entries'], ); } return $runs; } /** * Deletes everything a previous TEC import run inserted. Categories the * run created are kept (1.9 migration parity). */ public function rollback( int $import_id ): int { // Only ids whose current entry is still the one this run created: a // lineage row can outlive its event (deletes did not use to remove // it), and core hands a freed id to the next new event, whoever's. $stmt = $this->pdo->prepare( "SELECT d.cal_id FROM {$this->prefix}webcal_import_data d JOIN {$this->prefix}webcal_entry e ON e.cal_id = d.cal_id AND e.cal_uid = d.cal_external_id WHERE d.cal_import_id = ? AND d.cal_import_type = ?" ); $stmt->execute( array( $import_id, self::RUN_TYPE ) ); $ids = $stmt->fetchAll( PDO::FETCH_COLUMN ); $this->pdo->beginTransaction(); try { foreach ( $ids as $id ) { $this->delete_event_rows( (int) $id ); } $this->exec( "DELETE FROM {$this->prefix}webcal_import_data WHERE cal_import_id = ?", array( $import_id ) ); $this->exec( "DELETE FROM {$this->prefix}webcal_import WHERE cal_import_id = ?", array( $import_id ) ); $this->pdo->commit(); } catch ( \Throwable $e ) { $this->pdo->rollBack(); throw $e; } return count( $ids ); } /** * One TEC sync cycle: overwrite changed mirrored events in place, * insert new ones, prune family members the new recurrence shape no * longer wants — Epic 8.1 (STATUS.md). * * Callers hand in the CHANGED events (a modified-since read); anything * whose mapped content already matches the mirror is left untouched, so * a spurious TEC modification bump causes no churn. In-place updates * keep their cal_id (single-event-page URLs survive) and stay owned by * the run that originally imported them; only insertions create new * undo targets, so an add-free cycle records no run row. * * @param list $mapped Changed events. * @param array> $instance_map Occurrence * starts (site timezone) keyed by uid, for events flagged * needs_instance_expansion. * @return array{import_id: int, added: int, updated: int, unchanged: int, removed: int, instances: int, categories: int, tags: int, warnings: list} * @throws \Throwable A mid-cycle failure rolls the whole cycle back first. */ public function sync( array $mapped, array $instance_map = array() ): array { $report = array( 'import_id' => 0, 'added' => 0, 'updated' => 0, 'unchanged' => 0, 'removed' => 0, 'instances' => 0, 'categories' => 0, 'tags' => 0, 'warnings' => array(), ); $this->pdo->beginTransaction(); try { $import_id = $this->next_id( 'webcal_import', 'cal_import_id' ); $report['import_id'] = $import_id; $this->exec( "INSERT INTO {$this->prefix}webcal_import ( cal_import_id, cal_name, cal_date, cal_type, cal_login ) VALUES ( ?, ?, ?, ?, ? )", array( $import_id, 'The Events Calendar sync', (int) gmdate( 'Ymd' ), self::RUN_TYPE, '' ) ); $label_ids = array(); foreach ( $mapped as $item ) { foreach ( $item->warnings as $warning ) { $report['warnings'][] = $warning; } // Each event in its own savepoint: one the database refuses // (a title longer than the column, under strict mode) used to // roll back the whole batch, every cycle, and the deletion // sweep after it never ran, so the mirror froze. $before_report = $report; $before_labels = $label_ids; $this->pdo->exec( 'SAVEPOINT webcal_tec_item' ); try { $this->sync_item( $item, $instance_map, $import_id, $label_ids, $report ); $this->pdo->exec( 'RELEASE SAVEPOINT webcal_tec_item' ); } catch ( \PDOException $e ) { $this->pdo->exec( 'ROLLBACK TO SAVEPOINT webcal_tec_item' ); $warnings = $report['warnings']; $report = $before_report; $report['warnings'] = $warnings; $label_ids = $before_labels; $report['warnings'][] = sprintf( /* translators: 1: TEC event uid, 2: database error */ __( 'Skipped The Events Calendar event %1$s: %2$s', 'agenticdaisy-calendar' ), $item->event->uid(), $e->getMessage() ); } } // Only insertions create undo targets (updates stay owned by // their original run), so an add-free cycle records no run. if ( 0 === $report['added'] ) { $this->exec( "DELETE FROM {$this->prefix}webcal_import WHERE cal_import_id = ?", array( $import_id ) ); $report['import_id'] = 0; } $this->pdo->commit(); } catch ( \Throwable $e ) { $this->pdo->rollBack(); throw $e; } return $report; } /** * "Stop the trial": delete every mirrored TEC event across all runs, * plus the runs themselves — Epic 8.4 (STATUS.md). Created categories * are kept (undo parity); nothing outside cal_type 'tec' is touched; * TEC's own data is never modified. * * @return int Number of mirrored events removed. */ public function remove_all(): int { // Only ids whose current entry is still the one this run created: a // lineage row can outlive its event (deletes did not use to remove // it), and core hands a freed id to the next new event, whoever's. $stmt = $this->pdo->prepare( "SELECT d.cal_id FROM {$this->prefix}webcal_import_data d JOIN {$this->prefix}webcal_entry e ON e.cal_id = d.cal_id AND e.cal_uid = d.cal_external_id WHERE d.cal_import_type = ?" ); $stmt->execute( array( self::RUN_TYPE ) ); $ids = $stmt->fetchAll( PDO::FETCH_COLUMN ); $this->pdo->beginTransaction(); try { foreach ( $ids as $id ) { $this->delete_event_rows( (int) $id ); } $this->exec( "DELETE FROM {$this->prefix}webcal_import_data WHERE cal_import_type = ?", array( self::RUN_TYPE ) ); $this->exec( "DELETE FROM {$this->prefix}webcal_import WHERE cal_type = ?", array( self::RUN_TYPE ) ); $this->pdo->commit(); } catch ( \Throwable $e ) { $this->pdo->rollBack(); throw $e; } return count( $ids ); } /** * Base uids of every mirrored TEC event, from the import lineage. * Expanded `#YmdTHis` instances collapse onto their base uid. This is * the mirror side of the deletion sweep: anything here whose TEC post * no longer exists in the published set should be removed. * * @return list */ public function mirrored_base_uids(): array { $stmt = $this->pdo->prepare( "SELECT DISTINCT cal_external_id FROM {$this->prefix}webcal_import_data WHERE cal_import_type = ?" ); $stmt->execute( array( self::RUN_TYPE ) ); $uids = array(); foreach ( $stmt->fetchAll( PDO::FETCH_COLUMN ) as $external ) { if ( ! is_string( $external ) || '' === $external ) { continue; } $pos = strpos( $external, '#' ); $base = false === $pos ? $external : substr( $external, 0, $pos ); $uids[ $base ] = true; } return array_keys( $uids ); } /** * Delete every mirrored event belonging to the given TEC base uids — * the whole family: the base event and any expanded `#YmdTHis` * instances, plus their import lineage. Serves the sync engine's * removal needs: events that left `publish` status and the Epic 8.2 * deletion sweep. TEC data is never touched. * * @param list $base_uids Base uids (`tec-{id}@host`). * @return int Number of mirrored events removed. */ public function remove( array $base_uids ): int { if ( array() === $base_uids ) { return 0; } $removed = 0; $this->pdo->beginTransaction(); try { foreach ( $base_uids as $uid ) { foreach ( $this->family_rows( $uid ) as $row ) { $this->delete_event_rows( $row['cal_id'] ); ++$removed; } } $this->pdo->commit(); } catch ( \Throwable $e ) { $this->pdo->rollBack(); throw $e; } return $removed; } /** * The events one MappedTecEvent contributes: itself, or one standalone * event per occurrence when its recurrence could not be converted. * * @param MappedTecEvent $item The mapped event. * @param array> $instance_map Occurrences by uid. * @return array{events: list, instances: int} */ private function desired_events( MappedTecEvent $item, array $instance_map ): array { if ( ! $item->needs_instance_expansion ) { return array( 'events' => array( $item->event ), 'instances' => 0, ); } $occurrences = $instance_map[ $item->event->uid() ] ?? array(); if ( array() === $occurrences ) { // No occurrence data available; the base event is still real. return array( 'events' => array( $item->event ), 'instances' => 0, ); } $events = array(); foreach ( $occurrences as $start ) { $events[] = $this->as_instance( $item->event, $start ); } return array( 'events' => $events, 'instances' => count( $events ), ); } /** * Insert one event with its sidecars and lineage row; shared by the * import and sync paths. * * @param array $label_ids "kind:name" => cat_id cache (by reference). * @return array{categories: int, tags: int} Labels created for this event. */ private function insert_event( Event $event, MappedTecEvent $item, int $import_id, array &$label_ids ): array { $this->event_repository->save( $this->with_entities( $this->with_image( $event, $item->thumbnail_id ), $item ) ); $saved = $this->event_repository->findByUid( $event->uid() ); if ( null === $saved ) { throw new \RuntimeException( sprintf( 'Event "%s" was not found after saving.', esc_html( $event->uid() ) ) ); } $new_id = $saved->id()->value(); $created = $this->assign_labels( $new_id, $item->category_names, $item->tag_names, $label_ids ); $this->store_coordinates( $new_id, $item->lat, $item->lng ); $this->store_extras( $new_id, $item->extras ); $this->exec( "INSERT INTO {$this->prefix}webcal_import_data ( cal_import_id, cal_id, cal_login, cal_import_type, cal_external_id ) VALUES ( ?, ?, ?, ?, ? )", array( $import_id, $new_id, $event->createdBy(), self::RUN_TYPE, $event->uid() ) ); return $created; } /** * Whether the mirrored event already matches what TEC would write — * entity fields, recurrence, categories, tags and coordinates. UNTIL-based * rules may normalize differently on the two sides; a false negative * there costs one harmless rewrite, never a missed change. */ private function is_unchanged( Event $existing, Event $incoming, MappedTecEvent $item ): bool { if ( $existing->name() !== $incoming->name() || $existing->description() !== $incoming->description() || $existing->location() !== $incoming->location() || $existing->duration() !== $incoming->duration() || $existing->createdBy() !== $incoming->createdBy() || $existing->type() !== $incoming->type() || $existing->access() !== $incoming->access() // A cancellation changes nothing else about the event, so without // this a canceled event reads as unchanged and never reaches the // mirror. || $existing->status() !== $incoming->status() || $existing->isAllDay() !== $incoming->isAllDay() || ( $existing->image() ?? '' ) !== ( $incoming->image() ?? '' ) || $existing->venueId()?->value() !== $incoming->venueId()?->value() || $existing->organizerId()?->value() !== $incoming->organizerId()?->value() ) { return false; } // Wall-time comparison: stored dates are timezone-less integers. $fmt = $existing->isAllDay() ? 'Ymd' : 'Ymd\THis'; if ( $existing->start()->format( $fmt ) !== $incoming->start()->format( $fmt ) ) { return false; } if ( $this->recurrence_signature( $existing ) !== $this->recurrence_signature( $incoming ) ) { return false; } $id = $existing->id()->value(); $current = $this->current_label_names( $id ); if ( $current['categories'] !== $item->category_names || $current['tags'] !== $item->tag_names ) { return false; } list( $lat, $lng ) = $this->current_coordinates( $id ); return $this->same_coordinate( $lat, $item->lat ) && $this->same_coordinate( $lng, $item->lng ); } /** * Order-independent recurrence fingerprint. INTERVAL=1 and WKST=MO are * RFC 5545 defaults that round-trip inconsistently through storage. */ private function recurrence_signature( Event $event ): string { $recurrence = $event->recurrence(); $rule = $recurrence->rule(); $parts = array(); if ( null !== $rule ) { foreach ( explode( ';', str_replace( 'RRULE:', '', $rule->toString() ) ) as $part ) { if ( '' !== $part && 'INTERVAL=1' !== $part && 'WKST=MO' !== $part ) { $parts[] = $part; } } sort( $parts ); } $exdates = array_map( static fn ( DateTimeImmutable $d ): string => $d->format( 'Ymd' ), $recurrence->exDate()->dates() ); sort( $exdates ); $rdates = array_map( static fn ( DateTimeImmutable $d ): string => $d->format( 'Ymd' ), $recurrence->rDate()->dates() ); sort( $rdates ); return implode( ';', $parts ) . '|' . implode( ',', $exdates ) . '|' . implode( ',', $rdates ); } /** * Global label names currently assigned to an event, in cat_order, * split by kind. * * Both kinds have to be compared: a sync that only looked at categories * treated a retagged event as unchanged, so the mirror kept the old tags * indefinitely. * * @return array{categories: list, tags: list} */ private function current_label_names( int $event_id ): array { $stmt = $this->pdo->prepare( "SELECT c.cat_name, c.cat_is_tag FROM {$this->prefix}webcal_entry_categories ec JOIN {$this->prefix}webcal_categories c ON c.cat_id = ec.cat_id AND c.cat_owner = '' WHERE ec.cal_id = ? ORDER BY ec.cat_order" ); $stmt->execute( array( $event_id ) ); $labels = array( 'categories' => array(), 'tags' => array(), ); foreach ( $stmt->fetchAll( PDO::FETCH_ASSOC ) as $row ) { $key = ( 'Y' === ( $row['cat_is_tag'] ?? 'N' ) ) ? 'tags' : 'categories'; $labels[ $key ][] = (string) $row['cat_name']; } return $labels; } /** * @return array{0: ?float, 1: ?float} [lat, lng] */ private function current_coordinates( int $event_id ): array { $stmt = $this->pdo->prepare( "SELECT cal_geo_lat, cal_geo_lon FROM {$this->prefix}webcal_entry WHERE cal_id = ?" ); $stmt->execute( array( $event_id ) ); $row = $stmt->fetch( PDO::FETCH_ASSOC ); if ( ! is_array( $row ) ) { return array( null, null ); } return array( is_numeric( $row['cal_geo_lat'] ) ? (float) $row['cal_geo_lat'] : null, is_numeric( $row['cal_geo_lon'] ) ? (float) $row['cal_geo_lon'] : null, ); } private function same_coordinate( ?float $a, ?float $b ): bool { if ( null === $a || null === $b ) { return $a === $b; } return abs( $a - $b ) < 0.000001; } /** * Every mirrored row for one TEC base uid: the base event and any * expanded `#YmdTHis` instances. The `!` LIKE escape is portable * across MySQL and SQLite (backslash is not). * * @return list */ private function family_rows( string $base_uid ): array { $pattern = str_replace( array( '!', '%', '_' ), array( '!!', '!%', '!_' ), $base_uid ) . '#%'; $stmt = $this->pdo->prepare( "SELECT cal_id, cal_uid FROM {$this->prefix}webcal_entry WHERE cal_uid = ? OR cal_uid LIKE ? ESCAPE '!'" ); $stmt->execute( array( $base_uid, $pattern ) ); $rows = array(); foreach ( $stmt->fetchAll( PDO::FETCH_ASSOC ) as $row ) { $rows[] = array( 'cal_id' => (int) $row['cal_id'], 'cal_uid' => (string) $row['cal_uid'], ); } return $rows; } /** * Mirror one TEC event (and its instances) inside the sync's transaction. * * @param MappedTecEvent $item Event to mirror. * @param array> $instance_map Expanded occurrences by base uid. * @param int $import_id Current run. * @param array $label_ids Label id cache, by name. * @param-out array $label_ids * @param array{import_id: int, added: int, updated: int, unchanged: int, removed: int, instances: int, categories: int, tags: int, warnings: list} $report Report being built. * @param-out array{import_id: int, added: int, updated: int, unchanged: int, removed: int, instances: int, categories: int, tags: int, warnings: list} $report */ private function sync_item( MappedTecEvent $item, array $instance_map, int $import_id, array &$label_ids, array &$report ): void { $desired = $this->desired_events( $item, $instance_map ); $report['instances'] += $desired['instances']; $desired_uids = array(); foreach ( $desired['events'] as $event ) { $desired_uids[] = $event->uid(); $existing = $this->event_repository->findByUid( $event->uid() ); if ( null === $existing ) { $added = $this->insert_event( $event, $item, $import_id, $label_ids ); $report['categories'] += $added['categories']; $report['tags'] += $added['tags']; ++$report['added']; continue; } $incoming = $this->with_entities( $this->with_image( $event, $item->thumbnail_id ), $item ); if ( $this->is_unchanged( $existing, $incoming, $item ) ) { ++$report['unchanged']; continue; } $id = $existing->id()->value(); $this->event_repository->save( $incoming->withId( $existing->id() ) ); $this->exec( "DELETE FROM {$this->prefix}webcal_entry_categories WHERE cal_id = ?", array( $id ) ); $reassigned = $this->assign_labels( $id, $item->category_names, $item->tag_names, $label_ids ); $report['categories'] += $reassigned['categories']; $report['tags'] += $reassigned['tags']; $this->exec( "UPDATE {$this->prefix}webcal_entry SET cal_geo_lat = NULL, cal_geo_lon = NULL WHERE cal_id = ?", array( $id ) ); $this->store_coordinates( $id, $item->lat, $item->lng ); ++$report['updated']; } // A recurrence-shape change (rule <-> expanded instances, or // shifted occurrence dates) leaves family rows behind that // the new shape no longer wants. foreach ( $this->family_rows( $item->event->uid() ) as $row ) { if ( ! in_array( $row['cal_uid'], $desired_uids, true ) ) { $this->delete_event_rows( $row['cal_id'] ); ++$report['removed']; } } } /** * Delete one event's rows everywhere, including its import lineage. */ private function delete_event_rows( int $cal_id ): void { // Side tables first, on this connection so they share the run's // transaction; see EventSideData for why they matter. $tables = array_merge( \WebCalendar\WP\Database\EventSideData::TABLES, array( 'webcal_entry_repeats', 'webcal_entry_repeats_not', 'webcal_entry_user', 'webcal_entry' ) ); foreach ( array_unique( $tables ) as $table ) { $this->exec( "DELETE FROM {$this->prefix}{$table} WHERE cal_id = ?", array( $cal_id ) ); } \WebCalendar\WP\Database\EventSideData::purge_options( $cal_id ); } /** * A standalone single occurrence of a non-convertible recurring event. * The uid gains a deterministic per-instance suffix so re-runs dedup. */ private function as_instance( Event $event, DateTimeImmutable $start ): Event { // A standalone copy on a new date: only the identity, the date and // the now-absent recurrence differ. Everything descriptive comes // along by itself. return $event->with( id: new EventId( 0 ), uid: $event->uid() . '#' . $start->format( 'Ymd\THis' ), start: $start, type: EventType::EVENT, recurrence: new Recurrence(), ); } /** * The event with its featured image URL attached (ADR-3: Media Library * reference, no file copying). */ private function with_image( Event $event, ?int $thumbnail_id ): Event { if ( null === $thumbnail_id ) { return $event; } $url = wp_get_attachment_url( $thumbnail_id ); if ( ! is_string( $url ) || '' === $url ) { return $event; } return $event->with( image: $url ); } private function uid_exists( string $uid ): bool { $stmt = $this->pdo->prepare( "SELECT cal_id FROM {$this->prefix}webcal_entry WHERE cal_uid = ?" ); $stmt->execute( array( $uid ) ); return false !== $stmt->fetchColumn(); } /** * Match-or-create global categories and tags by name, and assign them. * * Both kinds live in webcal_categories and are assigned through the same * junction table, told apart only by cat_is_tag. Two consequences drive * this method: * * - Every lookup has to filter on cat_is_tag. Matching on name alone * hands a TEC category the id of a same-named tag, and the event ends * up carrying the wrong kind of label. The cache is keyed by kind for * the same reason. * - Categories are written first, so the color-bearing label keeps * cat_order 0 and stays the event's primary category. * * @param int $event_id Target cal_id. * @param list $category_names Category names. * @param list $tag_names Tag names. * @param array $label_ids "kind:name" => cat_id cache (by reference). * @return array{categories: int, tags: int} Newly created counts. */ private function assign_labels( int $event_id, array $category_names, array $tag_names, array &$label_ids ): array { $created = array( 'categories' => 0, 'tags' => 0, ); $order = 0; foreach ( array( false, true ) as $is_tag ) { $names = $is_tag ? $tag_names : $category_names; $key = $is_tag ? 'tags' : 'categories'; foreach ( $names as $name ) { $cache_key = ( $is_tag ? 'tag:' : 'cat:' ) . $name; if ( ! isset( $label_ids[ $cache_key ] ) ) { $match = $is_tag ? "cat_is_tag = 'Y'" : "( cat_is_tag IS NULL OR cat_is_tag <> 'Y' )"; $stmt = $this->pdo->prepare( "SELECT cat_id FROM {$this->prefix}webcal_categories WHERE cat_name = ? AND cat_owner = '' AND {$match}" ); $stmt->execute( array( $name ) ); $existing = $stmt->fetchColumn(); if ( false !== $existing ) { $label_ids[ $cache_key ] = (int) $existing; } else { $new_cat_id = $this->next_id( 'webcal_categories', 'cat_id' ); $this->exec( "INSERT INTO {$this->prefix}webcal_categories ( cat_id, cat_owner, cat_name, cat_color, cat_status, cat_is_tag ) VALUES ( ?, '', ?, NULL, 'A', ? )", array( $new_cat_id, $name, $is_tag ? 'Y' : 'N' ) ); $label_ids[ $cache_key ] = $new_cat_id; ++$created[ $key ]; } } $this->exec( "INSERT INTO {$this->prefix}webcal_entry_categories ( cal_id, cat_id, cat_order, cat_owner ) VALUES ( ?, ?, ?, '' )", array( $event_id, $label_ids[ $cache_key ], $order ) ); ++$order; } } return $created; } /** * Store venue coordinates on the entry row. The columns exist in the * schema (unused elsewhere today); preserving the data costs nothing * and future map features can pick it up. */ private function store_coordinates( int $event_id, ?float $lat, ?float $lng ): void { if ( null === $lat || null === $lng ) { return; } $this->exec( "UPDATE {$this->prefix}webcal_entry SET cal_geo_lat = ?, cal_geo_lon = ? WHERE cal_id = ?", array( $lat, $lng, $event_id ) ); } private function next_id( string $table, string $column ): int { $stmt = $this->pdo->query( "SELECT IFNULL(MAX({$column}), 0) + 1 FROM {$this->prefix}{$table}" ); $val = false !== $stmt ? $stmt->fetchColumn() : 1; return is_numeric( $val ) ? (int) $val : 1; } /** * @param list $params Bound values. */ private function exec( string $sql, array $params ): void { $this->pdo->prepare( $sql )->execute( $params ); } /** * Write an event's custom field values. * * Through core's service rather than SQL here, so a value written by an * import is indistinguishable from one typed into the event form — and so * a sync that later rewrites the event replaces the whole set rather than * accumulating rows. * * @param array $extras Values keyed by this site's field names. */ private function store_extras( int $event_id, array $extras ): void { if ( array() === $extras ) { return; } ( new \WebCalendar\Core\Application\Service\SiteExtraService( new \WebCalendar\Core\Infrastructure\Persistence\PdoSiteExtraRepository( $this->pdo, $this->prefix ) ) )->saveExtrasForEvent( $event_id, $extras ); } }