prefix . 'evwr_occurrences'; } /** * Create or update the table. */ public static function install() { global $wpdb; require_once ABSPATH . 'wp-admin/includes/upgrade.php'; $table = self::table(); $charset = $wpdb->get_charset_collate(); $sql = "CREATE TABLE {$table} ( id bigint(20) unsigned NOT NULL AUTO_INCREMENT, event_id bigint(20) unsigned NOT NULL, start_local datetime NOT NULL, end_local datetime NOT NULL, start_utc datetime NOT NULL, end_utc datetime NOT NULL, all_day tinyint(1) NOT NULL DEFAULT 0, PRIMARY KEY (id), KEY event_id (event_id), KEY start_local (start_local), KEY end_utc (end_utc), KEY start_utc (start_utc) ) {$charset};"; dbDelta( $sql ); } /** * Hook up. */ public static function init() { add_action( 'save_post_' . Post_Types::EVENT, array( __CLASS__, 'mark_dirty' ), 99 ); add_action( 'rest_after_insert_' . Post_Types::EVENT, array( __CLASS__, 'on_rest_insert' ) ); add_action( 'added_post_meta', array( __CLASS__, 'on_meta_change' ), 10, 3 ); add_action( 'updated_post_meta', array( __CLASS__, 'on_meta_change' ), 10, 3 ); add_action( 'deleted_post_meta', array( __CLASS__, 'on_meta_change' ), 10, 3 ); add_action( 'deleted_post', array( __CLASS__, 'delete_event' ) ); add_action( 'shutdown', array( __CLASS__, 'flush_dirty' ) ); add_action( 'evwr_extend_recurrences', array( __CLASS__, 'extend_open_ended' ) ); } /** * Mark an event for re-sync. * * @param int $event_id Event. */ public static function mark_dirty( $event_id ) { $event_id = (int) $event_id; if ( wp_is_post_revision( $event_id ) || wp_is_post_autosave( $event_id ) ) { return; } if ( self::$sync_now ) { self::sync( $event_id ); return; } self::$dirty[ $event_id ] = true; } /** * Block editor saves meta after the post; sync once it is all stored. * * @param \WP_Post $post Post. */ public static function on_rest_insert( $post ) { self::sync( $post->ID ); unset( self::$dirty[ $post->ID ] ); } /** * React to meta changes from any source. * * @param int|int[] $meta_id Meta id(s). * @param int $object_id Post. * @param string $meta_key Key. */ public static function on_meta_change( $meta_id, $object_id, $meta_key ) { if ( in_array( $meta_key, self::DATE_KEYS, true ) && get_post_type( $object_id ) === Post_Types::EVENT ) { self::mark_dirty( $object_id ); } } /** * Sync everything that changed during this request. */ public static function flush_dirty() { $ids = array_keys( self::$dirty ); self::$dirty = array(); foreach ( $ids as $id ) { self::sync( $id ); } } /** * Rebuild the rows of one event. * * @param int $event_id Event. * @return int Rows written. */ public static function sync( $event_id ) { global $wpdb; $event_id = (int) $event_id; $table = self::table(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Custom table. $wpdb->delete( $table, array( 'event_id' => $event_id ), array( '%d' ) ); unset( self::$dirty[ $event_id ] ); $post = get_post( $event_id ); if ( ! $post || Post_Types::EVENT !== $post->post_type ) { return 0; } $start = eventwright_sanitize_local_datetime( get_post_meta( $event_id, '_evwr_start', true ) ); if ( ! $start ) { return 0; } $end = eventwright_sanitize_local_datetime( get_post_meta( $event_id, '_evwr_end', true ) ); $all_day = (bool) get_post_meta( $event_id, '_evwr_all_day', true ); $tz = eventwright_event_timezone( $event_id ); if ( $all_day ) { $start = substr( $start, 0, 10 ) . ' 00:00:00'; $end = ( $end ? substr( $end, 0, 10 ) : substr( $start, 0, 10 ) ) . ' 23:59:59'; } $rule = Recurrence::get_rule( $event_id ); $occs = Recurrence::expand( $start, $end, $rule ); $count = 0; foreach ( $occs as $occ ) { $s = $occ['start']; $e = $occ['end']; if ( $all_day ) { $s = substr( $s, 0, 10 ) . ' 00:00:00'; $e = substr( $e, 0, 10 ) . ' 23:59:59'; } // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- Custom table. $wpdb->insert( $table, array( 'event_id' => $event_id, 'start_local' => $s, 'end_local' => $e, 'start_utc' => eventwright_local_to_utc( $s, $tz ), 'end_utc' => eventwright_local_to_utc( $e, $tz ), 'all_day' => $all_day ? 1 : 0, ), array( '%d', '%s', '%s', '%s', '%s', '%d' ) ); ++$count; } wp_cache_delete( 'evwr_occ_' . $event_id, 'eventwright' ); wp_cache_set( 'last_changed', microtime(), 'eventwright' ); return $count; } /** * Remove rows of a deleted event. * * @param int $post_id Post. */ public static function delete_event( $post_id ) { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Custom table. $wpdb->delete( self::table(), array( 'event_id' => (int) $post_id ), array( '%d' ) ); wp_cache_set( 'last_changed', microtime(), 'eventwright' ); } /** * Daily job: keep open-ended series generated two years ahead. */ public static function extend_open_ended() { $ids = get_posts( array( 'post_type' => Post_Types::EVENT, 'post_status' => array( 'publish', 'future', 'private', 'draft' ), 'posts_per_page' => 500, 'fields' => 'ids', 'meta_key' => '_evwr_recurrence', // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key 'meta_compare' => 'LIKE', 'meta_value' => '"end":"never"', // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_value ) ); foreach ( $ids as $id ) { if ( 'none' !== Recurrence::get_rule( $id )['freq'] ) { self::sync( $id ); } } } /** * All rows of one event. * * @param int $event_id Event. * @return array */ public static function for_event( $event_id ) { global $wpdb; $event_id = (int) $event_id; $rows = wp_cache_get( 'evwr_occ_' . $event_id, 'eventwright' ); if ( false === $rows ) { $table = self::table(); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Custom table name. $rows = $wpdb->get_results( $wpdb->prepare( 'SELECT * FROM %i WHERE event_id = %d ORDER BY start_local ASC', $table, $event_id ), ARRAY_A ); wp_cache_set( 'evwr_occ_' . $event_id, $rows, 'eventwright' ); } return $rows ? $rows : array(); } /** * The occurrence to show for an event: the one on $date, else the next upcoming, else the last one. * * @param int $event_id Event. * @param string $date Y-m-d (optional). * @return array|null */ public static function pick( $event_id, $date = '' ) { $rows = self::for_event( $event_id ); if ( ! $rows ) { return null; } if ( $date ) { foreach ( $rows as $row ) { if ( substr( $row['start_local'], 0, 10 ) === $date ) { return $row; } } } $now = eventwright_now_utc(); foreach ( $rows as $row ) { if ( $row['end_utc'] >= $now ) { return $row; } } return end( $rows ); } /** * Upcoming rows of one event (for "other dates" lists). * * @param int $event_id Event. * @param int $limit Max rows. * @return array */ public static function upcoming_for_event( $event_id, $limit = 10 ) { $now = eventwright_now_utc(); $out = array(); foreach ( self::for_event( $event_id ) as $row ) { if ( $row['end_utc'] >= $now ) { $out[] = $row; if ( count( $out ) >= $limit ) { break; } } } return $out; } /** * Query occurrences joined with their events. * * @param array $args { * @type string $from Local date-time; rows ending on/after it ('' = no limit). * @type string $to Local date-time; rows starting on/before it ('' = no limit). * @type bool $upcoming Only rows that have not ended yet (by UTC now). * @type bool $past Only rows that already ended. * @type int[] $categories Category term ids. * @type int $venue Venue id. * @type int $organizer Organizer id. * @type string $search Search text in titles. * @type bool $hide_hidden Leave out events marked "hide from lists". * @type int $limit Max rows (0 = no limit). * @type int $offset Offset. * @type string $order ASC or DESC. * @type bool $count Return the number of rows instead. * } * @return array|int */ public static function query( array $args = array() ) { global $wpdb; $args = wp_parse_args( $args, array( 'from' => '', 'to' => '', 'upcoming' => false, 'past' => false, 'categories' => array(), 'venue' => 0, 'organizer' => 0, 'search' => '', 'hide_hidden' => false, 'limit' => 0, 'offset' => 0, 'order' => 'ASC', 'count' => false, ) ); $time_bucket = ( $args['upcoming'] || $args['past'] ) ? (int) floor( time() / 300 ) : 0; $cache_key = 'q_' . md5( wp_json_encode( $args ) . $time_bucket . wp_cache_get_last_changed( 'eventwright' ) . wp_cache_get_last_changed( 'posts' ) . ( current_user_can( 'read_private_posts' ) ? 'p' : '' ) ); $cached = wp_cache_get( $cache_key, 'eventwright' ); if ( false !== $cached ) { return $cached; } $table = self::table(); $join = array( "INNER JOIN {$wpdb->posts} p ON p.ID = o.event_id" ); $where = array( $wpdb->prepare( 'p.post_type = %s', Post_Types::EVENT ) ); $status = array( "p.post_status = 'publish'" ); if ( current_user_can( 'read_private_posts' ) ) { $status[] = "p.post_status = 'private'"; } $where[] = '(' . implode( ' OR ', $status ) . ')'; $where[] = "p.post_password = ''"; if ( $args['from'] ) { $where[] = $wpdb->prepare( 'o.end_local >= %s', $args['from'] ); } if ( $args['to'] ) { $where[] = $wpdb->prepare( 'o.start_local <= %s', $args['to'] ); } if ( $args['upcoming'] ) { $where[] = $wpdb->prepare( 'o.end_utc >= %s', eventwright_now_utc() ); } if ( $args['past'] ) { $where[] = $wpdb->prepare( 'o.end_utc < %s', eventwright_now_utc() ); } $cats = array_filter( array_map( 'absint', (array) $args['categories'] ) ); if ( $cats ) { $all = array(); foreach ( $cats as $cat ) { $all[] = $cat; $kids = get_term_children( $cat, Post_Types::CATEGORY ); if ( is_array( $kids ) ) { $all = array_merge( $all, $kids ); } } $tt = array(); foreach ( array_unique( $all ) as $term_id ) { $term = get_term( $term_id, Post_Types::CATEGORY ); if ( $term && ! is_wp_error( $term ) ) { $tt[] = (int) $term->term_taxonomy_id; } } $tt = $tt ? $tt : array( 0 ); $where[] = 'EXISTS (SELECT 1 FROM ' . $wpdb->term_relationships . ' tr WHERE tr.object_id = p.ID AND tr.term_taxonomy_id IN (' . implode( ',', $tt ) . '))'; } if ( $args['venue'] ) { $where[] = $wpdb->prepare( "EXISTS (SELECT 1 FROM {$wpdb->postmeta} vm WHERE vm.post_id = p.ID AND vm.meta_key = '_evwr_venue_id' AND vm.meta_value = %s)", (string) absint( $args['venue'] ) ); } if ( $args['organizer'] ) { // Organizer ids are stored as a serialized array; match the exact integer element. $where[] = $wpdb->prepare( "EXISTS (SELECT 1 FROM {$wpdb->postmeta} om WHERE om.post_id = p.ID AND om.meta_key = '_evwr_organizer_ids' AND om.meta_value LIKE %s)", '%' . $wpdb->esc_like( 'i:' . absint( $args['organizer'] ) . ';' ) . '%' ); } if ( '' !== $args['search'] ) { $where[] = $wpdb->prepare( 'p.post_title LIKE %s', '%' . $wpdb->esc_like( $args['search'] ) . '%' ); } if ( $args['hide_hidden'] ) { $where[] = "NOT EXISTS (SELECT 1 FROM {$wpdb->postmeta} hm WHERE hm.post_id = p.ID AND hm.meta_key = '_evwr_hide_from_lists' AND hm.meta_value = '1')"; } $sql_where = implode( ' AND ', $where ); $sql_join = implode( ' ', $join ); $from = $wpdb->prepare( 'FROM %i o', $table ); if ( $args['count'] ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Every WHERE/JOIN part is built with $wpdb->prepare() or from integers above. $result = (int) $wpdb->get_var( "SELECT COUNT(*) {$from} {$sql_join} WHERE {$sql_where}" ); } else { $order = 'DESC' === strtoupper( $args['order'] ) ? 'DESC' : 'ASC'; $limit = ''; if ( $args['limit'] ) { $limit = $wpdb->prepare( 'LIMIT %d OFFSET %d', absint( $args['limit'] ), absint( $args['offset'] ) ); } // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Every WHERE/JOIN part is built with $wpdb->prepare() or from integers above. $result = $wpdb->get_results( "SELECT o.*, p.post_title {$from} {$sql_join} WHERE {$sql_where} ORDER BY o.start_local {$order}, o.all_day DESC, p.menu_order ASC, p.post_title ASC {$limit}", ARRAY_A ); $result = $result ? $result : array(); } wp_cache_set( $cache_key, $result, 'eventwright', HOUR_IN_SECONDS ); return $result; } }