__( 'WebCalendar', 'agenticdaisy-calendar' ), 'description' => __( 'Calendar event management abilities provided by the WebCalendar plugin.', 'agenticdaisy-calendar' ), ] ); } /** * Register all WebCalendar abilities. */ public function register_abilities(): void { $this->register_list_events(); $this->register_get_event(); $this->register_list_users(); // Mutating abilities are skipped entirely in read-only mode, so an AI // reaching the calendar through the WordPress Abilities API cannot write. if ( ! $this->is_read_only() ) { $this->register_create_event(); $this->register_update_event(); $this->register_delete_event(); } $this->register_list_categories(); $this->register_get_calendar_info(); } /** * Whether AI access is restricted to read-only tools. * * Mirrors McpServer::is_read_only() (option + filter) so both AI exposure * paths — the built-in MCP server and the WordPress Abilities API — honor * the same setting. * * @return bool */ private function is_read_only(): bool { $raw = get_option( 'webcal_mcp_read_only', 'no' ); $enabled = is_scalar( $raw ) && (string) $raw === 'yes'; /** This filter is documented in src/MCP/McpServer.php */ return (bool) apply_filters( 'webcal_mcp_read_only', $enabled ); } /** * List events in a date range. */ private function register_list_events(): void { if ( ! function_exists( 'wp_register_ability' ) ) { return; } wp_register_ability( 'webcalendar/list-events', [ 'label' => __( 'List Events', 'agenticdaisy-calendar' ), 'description' => __( 'Retrieve calendar events within a date range, optionally filtered by user or category.', 'agenticdaisy-calendar' ), 'category' => self::CATEGORY, 'input_schema' => [ 'type' => 'object', 'properties' => [ 'start_date' => [ 'type' => 'string', 'description' => __( 'Start date in ISO 8601 format (e.g. 2026-03-01).', 'agenticdaisy-calendar' ), ], 'end_date' => [ 'type' => 'string', 'description' => __( 'End date in ISO 8601 format (e.g. 2026-03-31).', 'agenticdaisy-calendar' ), ], 'user' => [ 'type' => 'string', 'description' => __( 'Filter by WordPress user login. Omit for all users.', 'agenticdaisy-calendar' ), ], 'category_id' => [ 'type' => 'integer', 'description' => __( 'Filter by category ID.', 'agenticdaisy-calendar' ), ], 'max_results' => [ 'type' => 'integer', 'description' => __( 'Maximum number of events to return (default 50, max 200).', 'agenticdaisy-calendar' ), 'default' => 50, 'minimum' => 1, 'maximum' => 200, ], ], 'required' => [ 'start_date', 'end_date' ], ], 'output_schema' => [ 'type' => 'object', 'properties' => [ 'total' => [ 'type' => 'integer', 'description' => __( 'Total number of events found.', 'agenticdaisy-calendar' ), ], 'events' => [ 'type' => 'array', 'items' => $this->event_schema(), ], ], ], 'execute_callback' => [ $this, 'execute_list_events' ], 'permission_callback' => fn() => current_user_can( 'webcal_can_view' ), ] ); } /** * Execute list-events ability. * * @param array $input Input parameters. * @return array */ public function execute_list_events( array $input ): array { try { $container = Container::get_instance(); $event_service = $container->get_event_service(); $transformer = $container->get_event_transformer(); $category_repo = $container->get_category_repository(); $start = new DateTimeImmutable( is_string( $input['start_date'] ?? null ) ? $input['start_date'] : 'now' ); $end = new DateTimeImmutable( is_string( $input['end_date'] ?? null ) ? $input['end_date'] : '+30 days' ); $range = new DateRange( $start, $end ); $users_filter = null; if ( ! empty( $input['user'] ) && is_string( $input['user'] ) ) { $users_filter = [ sanitize_text_field( $input['user'] ) ]; } // Scope to what the calling user may see. The ability is gated on // webcal_can_view, which reaches Subscriber, so the capability // check alone does not decide *which* events — and unlike the MCP // endpoint this surface is registered with WordPress directly, so // it is not covered by the webcal_mcp_audience setting either. // // limitedToUsers( [] ) is no calendar restriction, which is what a // null filter meant before — hence the ?? []. $events = EventVisibility::filter( $event_service->getEventsInDateRange( $range, EventVisibility::scope_for_viewer()->limitedToUsers( $users_filter ?? [] ) ) ); // Optional category filter (post-query) $raw_cat_id = $input['category_id'] ?? null; if ( is_numeric( $raw_cat_id ) && (int) $raw_cat_id > 0 ) { $cat_id = (int) $raw_cat_id; $user_login = is_user_logged_in() ? wp_get_current_user()->user_login : ''; $events = array_filter( $events, function ( $event ) use ( $category_repo, $cat_id, $user_login ) { $cats = $category_repo->getForEvent( $event->id(), $user_login ?: $event->createdBy() ); foreach ( $cats as $cat ) { if ( $cat->id() === $cat_id ) { return true; } } return false; } ); $events = array_values( $events ); } // Expand recurring events into individual occurrences within the date range. // Without this, recurring events appear with their original start date, // which may be outside the requested range. $recurrence_svc = $container->get_recurrence_service(); $queue = []; foreach ( $events as $event ) { if ( $event->recurrence()->isRepeating() ) { $occurrences = $recurrence_svc->expand( $event, $range ); foreach ( $occurrences as $occurrence ) { $queue[] = [ 'event' => $event, 'occurrence' => $occurrence, ]; } } else { $queue[] = [ 'event' => $event, 'occurrence' => null, ]; } } // Sort by occurrence/event start date ascending. usort( $queue, function ( $a, $b ) { /** @var \DateTimeImmutable $start_a */ $start_a = $a['occurrence'] !== null ? $a['occurrence']->getStart() : $a['event']->start(); /** @var \DateTimeImmutable $start_b */ $start_b = $b['occurrence'] !== null ? $b['occurrence']->getStart() : $b['event']->start(); return $start_a <=> $start_b; } ); $raw_max = $input['max_results'] ?? 0; $max = is_numeric( $raw_max ) && (int) $raw_max > 0 ? min( (int) $raw_max, 200 ) : 50; $total = count( $queue ); $queue = array_slice( $queue, 0, $max ); $result = []; foreach ( $queue as $item ) { if ( $item['occurrence'] !== null ) { $result[] = $this->summarize_occurrence( $item['occurrence'], $item['event'], $transformer ); } else { $result[] = $this->summarize_event( $item['event'], $transformer ); } } return [ 'total' => $total, 'events' => $result, ]; } catch ( \Exception $e ) { return [ 'error' => __( 'Failed to list events: ', 'agenticdaisy-calendar' ) . $e->getMessage() ]; } } /** * Get a single event by ID. */ private function register_get_event(): void { if ( ! function_exists( 'wp_register_ability' ) ) { return; } wp_register_ability( 'webcalendar/get-event', [ 'label' => __( 'Get Event', 'agenticdaisy-calendar' ), 'description' => __( 'Retrieve full details of a single calendar event by its ID.', 'agenticdaisy-calendar' ), 'category' => self::CATEGORY, 'input_schema' => [ 'type' => 'object', 'properties' => [ 'event_id' => [ 'type' => 'integer', 'description' => __( 'The event ID.', 'agenticdaisy-calendar' ), ], ], 'required' => [ 'event_id' ], ], 'output_schema' => [ 'type' => 'object', 'properties' => array_merge( $this->event_detail_properties(), [ 'participants' => [ 'type' => 'array', 'items' => [ 'type' => 'string' ], ], 'attachments' => [ 'type' => 'array' ], ] ), ], 'execute_callback' => [ $this, 'execute_get_event' ], 'permission_callback' => fn() => current_user_can( 'webcal_can_view' ), ] ); } /** * Execute get-event ability. * * @param array $input Input parameters. * @return array */ public function execute_get_event( array $input ): array { try { $container = Container::get_instance(); $event_service = $container->get_event_service(); $transformer = $container->get_event_transformer(); $raw_id = $input['event_id'] ?? 0; $id = is_numeric( $raw_id ) ? (int) $raw_id : 0; $event = $event_service->getEventById( new EventId( $id ) ); if ( ! $event ) { return [ 'error' => __( 'Event not found.', 'agenticdaisy-calendar' ) ]; } // An id is not an entitlement. Without this the ability reads back // any event on the site — including other people's Private and // Confidential ones — for anyone holding webcal_can_view. The // message deliberately matches the not-found case so the ability // cannot be used to probe which ids exist. if ( ! EventVisibility::can_view( $event ) ) { return [ 'error' => __( 'Event not found.', 'agenticdaisy-calendar' ) ]; } $data = $transformer->transform_event( $event ); // Coalesce nulls for Abilities API schema validation $data['location'] = $data['location'] ?? ''; $data['category_id'] = $data['category_id'] ?? 0; $data['category_color'] = $data['category_color'] ?? ''; $data['featured_image_id'] = $data['featured_image_id'] ?? 0; $data['featured_image_url'] = $data['featured_image_url'] ?? ''; return $data; } catch ( \Exception $e ) { return [ 'error' => __( 'Failed to get event: ', 'agenticdaisy-calendar' ) . $e->getMessage() ]; } } /** * Create a new event. */ private function register_create_event(): void { if ( ! function_exists( 'wp_register_ability' ) ) { return; } wp_register_ability( 'webcalendar/create-event', [ 'label' => __( 'Create Event', 'agenticdaisy-calendar' ), 'description' => __( 'Create a new calendar event with title, date/time, location, and optional recurrence.', 'agenticdaisy-calendar' ), 'category' => self::CATEGORY, 'input_schema' => [ 'type' => 'object', 'properties' => [ 'title' => [ 'type' => 'string', 'description' => __( 'Event title.', 'agenticdaisy-calendar' ), ], 'start' => [ 'type' => 'string', 'description' => __( 'Start date/time in ISO 8601 format (e.g. 2026-03-15T14:00:00). Times without a timezone offset are interpreted as the site\'s configured timezone. A date-only value (e.g. 2026-03-15) creates an all-day event.', 'agenticdaisy-calendar' ), ], 'duration' => [ 'type' => 'integer', 'description' => __( 'Duration in minutes (default 60).', 'agenticdaisy-calendar' ), 'default' => 60, ], 'all_day' => [ 'type' => 'boolean', 'description' => __( 'Whether this is an all-day event.', 'agenticdaisy-calendar' ), 'default' => false, ], 'description' => [ 'type' => 'string', 'description' => __( 'Event description (plain text or HTML).', 'agenticdaisy-calendar' ), ], 'location' => [ 'type' => 'string', 'description' => __( 'Event location.', 'agenticdaisy-calendar' ), ], 'access' => [ 'type' => 'string', 'description' => __( 'Access level: P (Public), C (Confidential), or R (Private). Default: P.', 'agenticdaisy-calendar' ), 'enum' => [ 'P', 'C', 'R' ], 'default' => 'P', ], 'rrule' => [ 'type' => 'string', 'description' => __( 'RFC 5545 recurrence rule (e.g. FREQ=WEEKLY;BYDAY=MO,WE,FR).', 'agenticdaisy-calendar' ), ], 'category_id' => [ 'type' => 'integer', 'description' => __( 'Category ID to assign.', 'agenticdaisy-calendar' ), ], 'participants' => [ 'type' => 'array', 'items' => [ 'type' => 'string' ], 'description' => __( 'WordPress user logins to add as participants.', 'agenticdaisy-calendar' ), ], ], 'required' => [ 'title', 'start' ], ], 'output_schema' => [ 'type' => 'object', 'properties' => [ 'id' => [ 'type' => 'integer', 'description' => __( 'Created event ID.', 'agenticdaisy-calendar' ), ], 'message' => [ 'type' => 'string' ], 'invalid_participants' => [ 'type' => 'array', 'items' => [ 'type' => 'string' ], ], ], ], 'execute_callback' => [ $this, 'execute_create_event' ], 'permission_callback' => fn() => current_user_can( 'webcal_can_edit' ), ] ); } /** * Execute create-event ability. * * @param array $input Input parameters. * @return array */ public function execute_create_event( array $input ): array { try { $container = Container::get_instance(); $event_service = $container->get_event_service(); // Infer all-day when explicit flag is set, or when start is date-only // (no time component). This prevents date-only starts like "2026-03-12" // from creating midnight timed events that get buried in month view. $start_str = is_string( $input['start'] ?? null ) ? $input['start'] : 'now'; $is_all_day = ! empty( $input['all_day'] ) || ( ! str_contains( $start_str, 'T' ) && ! preg_match( '/\d{2}:\d{2}/', $start_str ) ); $creator = wp_get_current_user()->user_login; $recurrence = new Recurrence(); $rrule_str = is_string( $input['rrule'] ?? null ) ? $input['rrule'] : ''; if ( $rrule_str !== '' ) { $recurrence = new Recurrence( new RecurrenceRule( $rrule_str ) ); } $access_str = is_string( $input['access'] ?? null ) ? $input['access'] : 'P'; $access = AccessLevel::tryFrom( $access_str ) ?? AccessLevel::PUBLIC; $event = new Event( id: new EventId( 0 ), uid: wp_generate_uuid4(), name: sanitize_text_field( is_string( $input['title'] ?? null ) ? $input['title'] : '' ), description: wp_kses_post( is_string( $input['description'] ?? null ) ? $input['description'] : '' ), location: sanitize_text_field( is_string( $input['location'] ?? null ) ? $input['location'] : '' ), start: new DateTimeImmutable( $start_str ), duration: $is_all_day ? 1440 : ( is_numeric( $input['duration'] ?? null ) && (int) $input['duration'] > 0 ? (int) $input['duration'] : 60 ), createdBy: $creator, type: $recurrence->isRepeating() ? EventType::REPEATING_EVENT : EventType::EVENT, access: $access, recurrence: $recurrence, allDay: $is_all_day, ); $user_repo = $container->get_user_repository(); $actor = $user_repo->findByLogin( $creator ); if ( $actor === null ) { $actor = new User( login: $creator, firstName: $creator, lastName: '', email: '', isAdmin: true, isEnabled: true ); } $event_service->createEvent( $event, $actor ); // Retrieve saved event to get the generated ID $event_repo = $container->get_event_repository(); $saved_event = $event_repo->findByUid( $event->uid() ); $event_id = $saved_event ? $saved_event->id()->value() : 0; // Handle category $raw_cat = $input['category_id'] ?? null; if ( $event_id > 0 && is_numeric( $raw_cat ) && (int) $raw_cat > 0 ) { $action_service = $container->get_event_action_service(); $action_service->save_category( $event_id, (int) $raw_cat ); } // Handle participants $invalid_participants = []; if ( $event_id > 0 ) { $participant_list = [ $creator ]; if ( ! empty( $input['participants'] ) && is_array( $input['participants'] ) ) { $result = $this->validate_participants( $input['participants'] ); foreach ( $result['valid'] as $login ) { if ( ! in_array( $login, $participant_list, true ) ) { $participant_list[] = $login; } } $invalid_participants = $result['invalid']; } $container->get_participant_repository()->save_participants( $event_id, $participant_list ); } $response = [ 'id' => $event_id, 'message' => __( 'Event created successfully.', 'agenticdaisy-calendar' ), ]; if ( ! empty( $invalid_participants ) ) { $response['invalid_participants'] = $invalid_participants; } return $response; } catch ( \Exception $e ) { return [ 'error' => __( 'Failed to create event: ', 'agenticdaisy-calendar' ) . $e->getMessage() ]; } } /** * Update an existing event. */ private function register_update_event(): void { if ( ! function_exists( 'wp_register_ability' ) ) { return; } wp_register_ability( 'webcalendar/update-event', [ 'label' => __( 'Update Event', 'agenticdaisy-calendar' ), 'description' => __( 'Update an existing calendar event. Only provided fields are changed.', 'agenticdaisy-calendar' ), 'category' => self::CATEGORY, 'input_schema' => [ 'type' => 'object', 'properties' => [ 'event_id' => [ 'type' => 'integer', 'description' => __( 'The event ID to update.', 'agenticdaisy-calendar' ), ], 'title' => [ 'type' => 'string', 'description' => __( 'New event title.', 'agenticdaisy-calendar' ), ], 'start' => [ 'type' => 'string', 'description' => __( 'New start date/time in ISO 8601 format (e.g. 2026-03-15T14:00:00). Times without a timezone offset are interpreted as the site\'s configured timezone. A date-only value (e.g. 2026-03-15) creates an all-day event.', 'agenticdaisy-calendar' ), ], 'duration' => [ 'type' => 'integer', 'description' => __( 'New duration in minutes.', 'agenticdaisy-calendar' ), ], 'all_day' => [ 'type' => 'boolean', 'description' => __( 'Whether this is an all-day event.', 'agenticdaisy-calendar' ), ], 'description' => [ 'type' => 'string', 'description' => __( 'New event description.', 'agenticdaisy-calendar' ), ], 'location' => [ 'type' => 'string', 'description' => __( 'New event location.', 'agenticdaisy-calendar' ), ], 'access' => [ 'type' => 'string', 'description' => __( 'Access level: P, C, or R.', 'agenticdaisy-calendar' ), 'enum' => [ 'P', 'C', 'R' ], ], 'category_id' => [ 'type' => 'integer', 'description' => __( 'Category ID to assign (0 to remove).', 'agenticdaisy-calendar' ), ], 'participants' => [ 'type' => 'array', 'items' => [ 'type' => 'string' ], 'description' => __( 'WordPress user logins to set as participants (replaces existing).', 'agenticdaisy-calendar' ), ], ], 'required' => [ 'event_id' ], ], 'output_schema' => [ 'type' => 'object', 'properties' => [ 'id' => [ 'type' => 'integer' ], 'message' => [ 'type' => 'string' ], 'invalid_participants' => [ 'type' => 'array', 'items' => [ 'type' => 'string' ], ], ], ], 'execute_callback' => [ $this, 'execute_update_event' ], 'permission_callback' => fn() => current_user_can( 'webcal_can_edit' ), ] ); } /** * Execute update-event ability. * * @param array $input Input parameters. * @return array */ public function execute_update_event( array $input ): array { $container = Container::get_instance(); $event_service = $container->get_event_service(); $raw_id = $input['event_id'] ?? 0; $id = is_numeric( $raw_id ) ? (int) $raw_id : 0; $existing = $event_service->getEventById( new EventId( $id ) ); if ( ! $existing ) { return [ 'error' => __( 'Event not found.', 'agenticdaisy-calendar' ) ]; } // Ownership check for non-admins if ( ! current_user_can( 'webcal_can_edit_others' ) && $existing->createdBy() !== wp_get_current_user()->user_login ) { return [ 'error' => __( 'You do not have permission to edit this event.', 'agenticdaisy-calendar' ) ]; } try { $is_all_day = array_key_exists( 'all_day', $input ) ? ! empty( $input['all_day'] ) : $existing->isAllDay(); $access = $existing->access(); if ( isset( $input['access'] ) && is_string( $input['access'] ) ) { $access = AccessLevel::tryFrom( $input['access'] ) ?? $existing->access(); } $recurrence = $existing->recurrence(); if ( isset( $input['rrule'] ) && is_string( $input['rrule'] ) ) { $recurrence = $input['rrule'] === '' ? new Recurrence() : new Recurrence( new RecurrenceRule( $input['rrule'] ) ); } // Only the editable fields are named; with() carries the rest. // save() is a full-row UPDATE, so anything omitted from a // hand-rolled rebuild is written back as NULL — which let an // agent-driven edit erase an event's venue, organizer and // conference details, and clear the TENTATIVE status that holds // a frontend submission back from the calendar. $event = $existing->with( name: sanitize_text_field( isset( $input['title'] ) && is_string( $input['title'] ) ? $input['title'] : $existing->name() ), description: wp_kses_post( isset( $input['description'] ) && is_string( $input['description'] ) ? $input['description'] : $existing->description() ), location: sanitize_text_field( isset( $input['location'] ) && is_string( $input['location'] ) ? $input['location'] : $existing->location() ), start: isset( $input['start'] ) && is_string( $input['start'] ) ? new DateTimeImmutable( $input['start'] ) : $existing->start(), duration: $is_all_day ? 1440 : ( is_numeric( $input['duration'] ?? null ) && (int) $input['duration'] > 0 ? (int) $input['duration'] : $existing->duration() ), type: $recurrence->isRepeating() ? EventType::REPEATING_EVENT : EventType::EVENT, access: $access, recurrence: $recurrence, allDay: $is_all_day, ); $creator = wp_get_current_user()->user_login; $user_repo = $container->get_user_repository(); $actor = $user_repo->findByLogin( $creator ); if ( $actor === null ) { $actor = new User( login: $creator, firstName: $creator, lastName: '', email: '', isAdmin: true, isEnabled: true ); } $event_service->updateEvent( $event, $actor ); // Handle category if ( array_key_exists( 'category_id', $input ) ) { $raw_cat_val = $input['category_id'] ?? 0; $cat_id = is_numeric( $raw_cat_val ) ? (int) $raw_cat_val : 0; $action_service = $container->get_event_action_service(); if ( $cat_id > 0 ) { $action_service->save_category( $id, $cat_id ); } else { $action_service->delete_category( $id ); } } // Handle participants (only when explicitly provided — partial update semantics) $invalid_participants = []; if ( array_key_exists( 'participants', $input ) && is_array( $input['participants'] ) ) { $event_creator = $existing->createdBy(); $participant_list = [ $event_creator ]; $result = $this->validate_participants( $input['participants'] ); foreach ( $result['valid'] as $login ) { if ( ! in_array( $login, $participant_list, true ) ) { $participant_list[] = $login; } } $invalid_participants = $result['invalid']; $container->get_participant_repository()->save_participants( $id, $participant_list ); } $response = [ 'id' => $id, 'message' => __( 'Event updated successfully.', 'agenticdaisy-calendar' ), ]; if ( ! empty( $invalid_participants ) ) { $response['invalid_participants'] = $invalid_participants; } return $response; } catch ( \Exception $e ) { return [ 'error' => __( 'Failed to update event: ', 'agenticdaisy-calendar' ) . $e->getMessage() ]; } } /** * Delete an event. */ private function register_delete_event(): void { if ( ! function_exists( 'wp_register_ability' ) ) { return; } wp_register_ability( 'webcalendar/delete-event', [ 'label' => __( 'Delete Event', 'agenticdaisy-calendar' ), 'description' => __( 'Permanently delete a calendar event by ID.', 'agenticdaisy-calendar' ), 'category' => self::CATEGORY, 'input_schema' => [ 'type' => 'object', 'properties' => [ 'event_id' => [ 'type' => 'integer', 'description' => __( 'The event ID to delete.', 'agenticdaisy-calendar' ), ], ], 'required' => [ 'event_id' ], ], 'output_schema' => [ 'type' => 'object', 'properties' => [ 'message' => [ 'type' => 'string' ], ], ], 'execute_callback' => [ $this, 'execute_delete_event' ], 'permission_callback' => fn() => current_user_can( 'webcal_can_delete' ), ] ); } /** * Execute delete-event ability. * * @param array $input Input parameters. * @return array */ public function execute_delete_event( array $input ): array { $container = Container::get_instance(); $event_service = $container->get_event_service(); $raw_id = $input['event_id'] ?? 0; $id = is_numeric( $raw_id ) ? (int) $raw_id : 0; $event = $event_service->getEventById( new EventId( $id ) ); if ( ! $event ) { return [ 'error' => __( 'Event not found.', 'agenticdaisy-calendar' ) ]; } // Ownership check if ( ! current_user_can( 'webcal_can_delete_others' ) && $event->createdBy() !== wp_get_current_user()->user_login ) { return [ 'error' => __( 'You do not have permission to delete this event.', 'agenticdaisy-calendar' ) ]; } try { $creator = wp_get_current_user()->user_login; $user_repo = $container->get_user_repository(); $actor = $user_repo->findByLogin( $creator ); if ( $actor === null ) { $actor = new User( login: $creator, firstName: $creator, lastName: '', email: '', isAdmin: true, isEnabled: true ); } $event_service->deleteEvent( new EventId( $id ), $actor ); // Clean up associated data delete_option( 'webcal_attachments_' . $id ); delete_option( 'webcal_featured_image_' . $id ); return [ 'message' => __( 'Event deleted successfully.', 'agenticdaisy-calendar' ) ]; } catch ( \Exception $e ) { return [ 'error' => __( 'Failed to delete event: ', 'agenticdaisy-calendar' ) . $e->getMessage() ]; } } /** * List categories. */ private function register_list_users(): void { if ( ! function_exists( 'wp_register_ability' ) ) { return; } wp_register_ability( 'webcalendar/list-users', [ 'label' => __( 'List Users', 'agenticdaisy-calendar' ), 'description' => __( 'List calendar users and shared/remote calendars (login, display name, and type) so events can be filtered by user and participants can be specified by login.', 'agenticdaisy-calendar' ), 'category' => self::CATEGORY, 'input_schema' => [ 'type' => 'object', 'properties' => [ 'search' => [ 'type' => 'string', 'description' => __( 'Optional search term to filter by login, display name, or email.', 'agenticdaisy-calendar' ), ], ], ], 'output_schema' => [ 'type' => 'object', 'properties' => [ 'total' => [ 'type' => 'integer' ], 'users' => [ 'type' => 'array', 'items' => [ 'type' => 'object', 'properties' => [ 'login' => [ 'type' => 'string' ], 'name' => [ 'type' => 'string' ], 'type' => [ 'type' => 'string', 'enum' => [ 'user', 'shared_calendar', 'remote_calendar' ], ], ], ], ], ], ], 'execute_callback' => [ $this, 'execute_list_users' ], 'permission_callback' => fn() => current_user_can( 'webcal_can_view' ), ] ); } /** * Execute list-users ability. * * Returns everything that can appear in the `user` event filter and the * `participants` field — the same set the admin participant picker uses — * each tagged with a `type`: * - `user` — a WordPress user with `webcal_can_view` * - `shared_calendar` — an internal shared calendar (resource, no URL) * - `remote_calendar` — an external subscription (resource with a URL) * Read-only. Resources are optional: if they cannot be loaded the WordPress * users are still returned. * * @param array $input Input parameters (optional `search`). * @return array */ public function execute_list_users( array $input = [] ): array { try { $search = isset( $input['search'] ) && is_scalar( $input['search'] ) ? trim( (string) $input['search'] ) : ''; $query = new \WP_User_Query( [ 'search' => $search !== '' ? '*' . $search . '*' : '', 'search_columns' => [ 'user_login', 'display_name', 'user_email' ], 'number' => 100, 'fields' => [ 'ID', 'user_login', 'display_name' ], 'capability' => 'webcal_can_view', 'orderby' => 'display_name', ] ); $users = []; /** @var \WP_User $user */ foreach ( $query->get_results() as $user ) { $users[] = [ 'login' => $user->user_login, 'name' => $user->display_name, 'type' => 'user', ]; } // Shared + remote calendars are stored together as resources and are // valid participant/user-filter values too. Optional — degrade to // users-only if the repository is unavailable. try { $resource_repo = Container::get_instance()->get_resource_repository(); foreach ( $resource_repo->findAll() as $resource ) { $login = $resource->login(); $name = $resource->name(); if ( $search !== '' && stripos( $login, $search ) === false && stripos( $name, $search ) === false ) { continue; } $users[] = [ 'login' => $login, 'name' => $name, 'type' => $resource->url() === null ? 'shared_calendar' : 'remote_calendar', ]; } } catch ( \Exception $e ) { // Resources unavailable; WordPress users are returned on their own. unset( $e ); } return [ 'total' => count( $users ), 'users' => $users, ]; } catch ( \Exception $e ) { return [ 'error' => __( 'Failed to list users: ', 'agenticdaisy-calendar' ) . $e->getMessage() ]; } } private function register_list_categories(): void { if ( ! function_exists( 'wp_register_ability' ) ) { return; } wp_register_ability( 'webcalendar/list-categories', [ 'label' => __( 'List Categories', 'agenticdaisy-calendar' ), 'description' => __( 'Retrieve all event categories with their names and colors.', 'agenticdaisy-calendar' ), 'category' => self::CATEGORY, 'input_schema' => [ 'type' => 'object', 'properties' => [], ], 'output_schema' => [ 'type' => 'array', 'items' => [ 'type' => 'object', 'properties' => [ 'id' => [ 'type' => 'integer' ], 'name' => [ 'type' => 'string' ], 'color' => [ 'type' => 'string' ], ], ], ], 'execute_callback' => [ $this, 'execute_list_categories' ], 'permission_callback' => fn() => current_user_can( 'webcal_can_view' ), ] ); } /** * Execute list-categories ability. * * @param array $input Input parameters. * @return array */ public function execute_list_categories( array $input = [] ): array { try { $container = Container::get_instance(); $category_svc = $container->get_category_service(); $user_login = is_user_logged_in() ? wp_get_current_user()->user_login : ''; $categories = $category_svc->getCategoriesForUser( $user_login ); $result = []; foreach ( $categories as $cat ) { $result[] = [ 'id' => $cat->id(), 'name' => $cat->name(), 'color' => $cat->color() ?? '', ]; } return $result; } catch ( \Exception $e ) { return [ 'error' => __( 'Failed to list categories: ', 'agenticdaisy-calendar' ) . $e->getMessage() ]; } } /** * Get calendar info and statistics. */ private function register_get_calendar_info(): void { if ( ! function_exists( 'wp_register_ability' ) ) { return; } wp_register_ability( 'webcalendar/get-calendar-info', [ 'label' => __( 'Get Calendar Info', 'agenticdaisy-calendar' ), 'description' => __( 'Get general calendar information including total events, categories, and configuration.', 'agenticdaisy-calendar' ), 'category' => self::CATEGORY, 'input_schema' => [ 'type' => 'object', 'properties' => [], ], 'output_schema' => [ 'type' => 'object', 'properties' => [ 'plugin_version' => [ 'type' => 'string' ], 'total_events' => [ 'type' => 'integer' ], 'total_categories' => [ 'type' => 'integer' ], 'time_format' => [ 'type' => 'string' ], 'site_name' => [ 'type' => 'string' ], ], ], 'execute_callback' => [ $this, 'execute_get_calendar_info' ], 'permission_callback' => fn() => current_user_can( 'webcal_can_view' ), ] ); } /** * Execute get-calendar-info ability. * * @param array $input Input parameters. * @return array */ public function execute_get_calendar_info( array $input = [] ): array { try { $container = Container::get_instance(); $category_svc = $container->get_category_service(); $user_login = is_user_logged_in() ? wp_get_current_user()->user_login : ''; // Count events via direct SQL to avoid loading all events into memory. /** @var \wpdb $wpdb */ $wpdb = $GLOBALS['wpdb']; $table = $wpdb->prefix . 'webcal_entry'; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $total = (int) $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM %i', $table ) ); $categories = $category_svc->getCategoriesForUser( $user_login ); return [ 'plugin_version' => defined( 'WEBCALENDAR_WP_VERSION' ) ? WEBCALENDAR_WP_VERSION : 'unknown', 'total_events' => $total, 'total_categories' => count( $categories ), 'time_format' => get_option( 'webcal_config_TIME_FORMAT', '12' ), 'site_name' => get_bloginfo( 'name' ), ]; } catch ( \Exception $e ) { return [ 'error' => __( 'Failed to get calendar info: ', 'agenticdaisy-calendar' ) . $e->getMessage() ]; } } /** * Validate participant logins against WordPress users. * * @param array $logins Raw user login strings. * @return array{valid: string[], invalid: string[]} */ private function validate_participants( array $logins ): array { $valid = []; $invalid = []; foreach ( $logins as $login ) { if ( ! is_string( $login ) ) { continue; } $sanitized = sanitize_text_field( $login ); if ( $sanitized === '' ) { continue; } if ( get_user_by( 'login', $sanitized ) ) { $valid[] = $sanitized; } else { $invalid[] = $sanitized; } } return [ 'valid' => $valid, 'invalid' => $invalid, ]; } /** * Summarize an event for list output (compact format). * * @param Event $event Event entity. * @param \WebCalendar\WP\REST\EventTransformer $transformer Transformer instance. * @return array */ private function summarize_event( Event $event, REST\EventTransformer $transformer ): array { $data = $transformer->transform_event( $event ); return $this->compact_event_data( $data ); } /** * Summarize a recurring event occurrence for list output (compact format). * * Uses the occurrence's actual start/end dates instead of the base event's * original dates, so results fall within the requested date range. * * @param \WebCalendarDeps\Icalendar\Recurrence\Occurrence $occurrence Recurrence occurrence. * @param Event $event Base event entity. * @param \WebCalendar\WP\REST\EventTransformer $transformer Transformer instance. * @return array */ private function summarize_occurrence( \WebCalendarDeps\Icalendar\Recurrence\Occurrence $occurrence, Event $event, REST\EventTransformer $transformer ): array { $data = $transformer->transform_occurrence( $occurrence, $event ); return $this->compact_event_data( $data ); } /** * Extract the compact subset of event data for MCP tool output. * * @param array $data Full transformed event data. * @return array */ private function compact_event_data( array $data ): array { return [ 'id' => $data['id'] ?? 0, 'title' => $data['title'] ?? '', 'start' => $data['start'] ?? '', 'end' => $data['end'] ?? '', 'allDay' => $data['allDay'] ?? false, 'location' => $data['location'] ?? '', 'category_id' => $data['category_id'] ?? 0, 'createdBy' => $data['createdBy'] ?? '', 'access' => $data['access'] ?? '', 'rrule' => $data['rrule'] ?? '', 'url' => $data['url'] ?? '', ]; } /** * Event properties array for use in array_merge (typed return). * * @return array> */ private function event_detail_properties(): array { return [ 'id' => [ 'type' => 'integer' ], 'title' => [ 'type' => 'string' ], 'start' => [ 'type' => 'string' ], 'end' => [ 'type' => 'string' ], 'allDay' => [ 'type' => 'boolean' ], 'location' => [ 'type' => 'string' ], 'description' => [ 'type' => 'string' ], 'category_id' => [ 'type' => 'integer' ], 'createdBy' => [ 'type' => 'string' ], 'access' => [ 'type' => 'string' ], 'rrule' => [ 'type' => 'string' ], 'url' => [ 'type' => 'string' ], ]; } /** * JSON Schema fragment for an event in output schemas. * * @return array */ private function event_schema(): array { return [ 'type' => 'object', 'properties' => [ 'id' => [ 'type' => 'integer' ], 'title' => [ 'type' => 'string' ], 'start' => [ 'type' => 'string' ], 'end' => [ 'type' => 'string' ], 'allDay' => [ 'type' => 'boolean' ], 'location' => [ 'type' => 'string' ], 'category_id' => [ 'type' => 'integer' ], 'createdBy' => [ 'type' => 'string' ], 'access' => [ 'type' => 'string' ], 'rrule' => [ 'type' => 'string' ], 'url' => [ 'type' => 'string' ], ], ]; } }