Below is a differential between the unpatched vulnerable code and the patched update, for reference.
--- a/events-manager/admin/em-bookings.php
+++ b/events-manager/admin/em-bookings.php
@@ -17,18 +17,38 @@
add_action('admin_init','em_admin_actions_bookings',100);
/**
+ * Whether a bookings admin action names a hook Events Manager already owns in the em_bookings_* namespace.
+ *
+ * Matched on prefix: that namespace also carries the booking lifecycle (em_bookings_add, em_bookings_deleted) and the admin templates (em_bookings_admin_*, em_bookings_table_*), whose listeners are called with arguments an admin action has none of.
+ *
+ * @param string $action Sanitized action name.
+ * @return bool
+ */
+function em_bookings_admin_action_is_reserved( $action ){
+ $reserved = array( 'add', 'admin_', 'build_sql_', 'dashboard', 'delete', 'event_', 'get', 'has_', 'is_', 'load', 'pending_count', 'person_', 'single_', 'sql_', 'table', 'ticket_' );
+ foreach( $reserved as $prefix ){
+ if( strpos( $action, $prefix ) === 0 ) return true;
+ }
+ return false;
+}
+
+/**
* Decide what content to show in the bookings section.
*/
function em_bookings_page(){
//First any actions take priority
do_action('em_bookings_admin_page');
if( !empty($_REQUEST['_wpnonce']) ){ $_REQUEST['_wpnonce'] = $_GET['_wpnonce'] = $_POST['_wpnonce'] = esc_attr($_REQUEST['_wpnonce']); } //XSS fix just in case here too
- if( !empty($_REQUEST['action']) && substr($_REQUEST['action'],0,7) != 'booking' && $_REQUEST['action'] !== 'em_bookings_table' ){ //actions not starting with booking_
+ $action = !empty($_REQUEST['action']) ? sanitize_key($_REQUEST['action']) : '';
+ if( $action !== '' && substr($action,0,7) != 'booking' && $action !== 'em_bookings_table' ){ //actions not starting with booking_
?>
- <div class="wrap em-bookings-admin-custom-<?php esc_attr($_REQUEST['action']); ?> <?php em_template_classes('bookings-admin'); ?>">
+ <div class="wrap em-bookings-admin-custom-<?php echo esc_attr($action); ?> <?php em_template_classes('bookings-admin'); ?>">
<div class="input">
<?php
- do_action('em_bookings_'.$_REQUEST['action']);
+ do_action('em_bookings_admin_action_'.$action, $action);
+ if( !em_bookings_admin_action_is_reserved($action) ){
+ do_action('em_bookings_'.$action); //deprecated by the hook above, kept one release so custom actions registered on this name keep working
+ }
?>
</div>
</div>
--- a/events-manager/admin/em-docs.php
+++ b/events-manager/admin/em-docs.php
@@ -410,7 +410,7 @@
)
),
'Gateway-Specific Information' => array(
- 'desc' => 'Information pertaining to speicifc gateways. '. sprintf('Requires <a href="%s">Events Manager Pro</a>','https://wp-events-plugin.com/features/'),
+ 'desc' => 'Information pertaining to specific gateways. '. sprintf('Requires <a href="%s">Events Manager Pro</a>','https://wp-events-plugin.com/features/'),
'placeholders' => array(
'#_BOOKINGTXNID' => array( 'desc' => '<em>Online Payments Only</em> - Prints the transaction ID of this booking if available.' )
)
--- a/events-manager/admin/em-options.php
+++ b/events-manager/admin/em-options.php
@@ -125,7 +125,9 @@
}
//Uninstall
if( !empty($_REQUEST['action']) && $_REQUEST['action'] == 'uninstall' && current_user_can('activate_plugins') && !empty($_REQUEST['confirmed']) && check_admin_referer('em_uninstall_'.get_current_user_id().'_wpnonce') && em_wp_is_super_admin() ){
- if( check_admin_referer('em_uninstall_'.get_current_user_id().'_confirmed','_wpnonce2') ){
+ if( EM_MS_GLOBAL && !is_main_site() ){
+ $EM_Notices->add_error( sprintf( esc_html__('Events Manager was not uninstalled. This network shares one set of event and booking tables, so uninstalling from this site would permanently delete the events and bookings of every site on the network. Uninstall from the %s instead.','events-manager'), '<a href="'. esc_url( network_admin_url('admin.php?page=events-manager-options') ) .'">'. esc_html__('network settings page','events-manager') .'</a>' ) );
+ }elseif( check_admin_referer('em_uninstall_'.get_current_user_id().'_confirmed','_wpnonce2') ){
//We have a go to uninstall
global $wpdb;
//delete EM posts
@@ -413,7 +415,7 @@
}
function em_admin_email_test_ajax(){
- if( wp_verify_nonce($_REQUEST['_check_email_nonce'],'check_email') && current_user_can('activate_plugins') ){
+ if( wp_verify_nonce($_REQUEST['_check_email_nonce'] ?? '','check_email') && current_user_can('manage_options') ){
$subject = __("Events Manager Test Email",'events-manager');
$content = __('Congratulations! Your email settings work.','events-manager');
$current_user = get_user_by('id', get_current_user_id());
@@ -453,6 +455,11 @@
);
}
echo EM_Object::json_encode($result);
+ }else{
+ echo EM_Object::json_encode( array(
+ 'result' => false,
+ 'message' => esc_html__('You do not have permission to send a test email, or this page has expired. Please reload the settings page and try again.','events-manager'),
+ ) );
}
exit();
}
@@ -485,15 +492,33 @@
}
function em_admin_options_uninstall_page(){
if( check_admin_referer('em_uninstall_'.get_current_user_id().'_wpnonce') && em_wp_is_super_admin() ){
+ $network_wide = EM_MS_GLOBAL;
+ $refused = $network_wide && !is_main_site();
?>
<div class="wrap">
<div id='icon-options-general' class='icon32'><br /></div>
<h2><?php _e('Uninstall Events Manager','events-manager'); ?></h2>
- <p style="color:red; font-weight:bold;"><?php _e('Are you sure you want to uninstall Events Manager?','events-manager')?></p>
- <p style="font-weight:bold;"><?php _e('All your settings and events will be permanently deleted. This cannot be undone.','events-manager')?></p>
+ <p style="color:red; font-weight:bold;"><?php
+ if( $refused ){
+ esc_html_e('Events Manager cannot be uninstalled from this site.','events-manager');
+ }else{
+ _e('Are you sure you want to uninstall Events Manager?','events-manager');
+ }
+ ?></p>
+ <p style="font-weight:bold;"><?php
+ if( $refused ){
+ echo sprintf( esc_html__('This network shares one set of event and booking tables, so uninstalling from this site would permanently delete the events and bookings of every site on the network. Uninstall from the %s instead.','events-manager'), '<a href="'. esc_url( network_admin_url('admin.php?page=events-manager-options') ) .'">'. esc_html__('network settings page','events-manager') .'</a>' );
+ }elseif( $network_wide ){
+ esc_html_e('All settings, events and bookings for every site on this network will be permanently deleted. This cannot be undone.','events-manager');
+ }else{
+ _e('All your settings and events will be permanently deleted. This cannot be undone.','events-manager');
+ }
+ ?></p>
<p><?php echo sprintf(__('If you just want to deactivate the plugin, <a href="%s">go to your plugins page</a>.','events-manager'), wp_nonce_url(admin_url('plugins.php'))); ?></p>
<p>
+ <?php if( !$refused ) : ?>
<a href="<?php echo esc_url(add_query_arg(array('_wpnonce2' => wp_create_nonce('em_uninstall_'.get_current_user_id().'_confirmed'), 'confirmed'=>1))); ?>" class="button-primary"><?php _e('Uninstall and Deactivate','events-manager'); ?></a>
+ <?php endif; ?>
<a href="<?php echo esc_url(em_wp_get_referer()); ?>" class="button-secondary"><?php _e('Cancel','events-manager'); ?></a>
</p>
</div>
--- a/events-manager/classes/api/em-api-service.php
+++ b/events-manager/classes/api/em-api-service.php
@@ -18,6 +18,8 @@
$total = (int) EM_Events::$num_rows_found;
$items = array();
foreach ( $events as $EM_Event ) {
+ // The query layer only knows about event_status/event_private, so a password-protected event still matches here and would be serialized with its raw content.
+ if ( $EM_Event->password_required() ) continue;
$items[] = static::prepare_event( $EM_Event, $params['context'] ?? 'view' );
}
return array(
@@ -456,6 +458,7 @@
$locations = EM_Locations::get( $args );
$items = array();
foreach ( $locations as $EM_Location ) {
+ if ( $EM_Location->password_required() ) continue;
$items[] = static::prepare_location( $EM_Location, $params['context'] ?? 'view' );
}
return array(
@@ -682,6 +685,10 @@
$args = Utils::collection_args( $params, Utils::pick_search_args( $params, $accepted ) );
if ( !current_user_can( 'manage_others_bookings' ) && !current_user_can( 'manage_bookings' ) ) {
$args['person'] = get_current_user_id();
+ $args['owner'] = get_current_user_id();
+ } else {
+ // EM_Bookings::get_default_search() scopes to the current user's own events unless owner is passed explicitly, so a manager with no owner override would otherwise only see their own bookings.
+ $args['owner'] = false;
}
if ( !empty( $params['event_id'] ) && empty( $args['event'] ) ) {
$args['event'] = $params['event_id'];
@@ -1000,6 +1007,10 @@
if ( $context === 'edit' ) {
return $EM_Event->can_manage( 'edit_events', 'edit_others_events' );
}
+ // A password-protected post stays published, so the checks below would otherwise wave it through and to_api() would hand back the raw post_content the password exists to withhold.
+ if ( $EM_Event->password_required() ) {
+ return false;
+ }
if ( $EM_Event->is_published() && empty( $EM_Event->event_private ) ) {
return true;
}
@@ -1013,6 +1024,9 @@
if ( $context === 'edit' ) {
return $EM_Location->can_manage( 'edit_locations', 'edit_others_locations' );
}
+ if ( $EM_Location->password_required() ) {
+ return false;
+ }
if ( $EM_Location->is_published() && empty( $EM_Location->location_private ) ) {
return true;
}
@@ -1407,8 +1421,17 @@
if ( !current_user_can( 'upload_files' ) ) {
return Utils::error( 'em_api_media_forbidden', __( 'You do not have permission to upload media.', 'events-manager' ), 403 );
}
+ // `post_id` lands on the attachment as post_parent, here and inside the sideload/upload helpers resolve_attachment_id() calls, so the caller has to be able to edit whatever they are attaching to.
+ if ( !empty( $data['post_id'] ) && !current_user_can( 'edit_post', absint( $data['post_id'] ) ) ) {
+ return Utils::error( 'em_api_media_parent_forbidden', __( 'You do not have permission to attach media to that post.', 'events-manager' ), 403 );
+ }
+ $supplied_attachment = !empty( $data['id'] ) || !empty( $data['attachment_id'] );
$attachment_id = static::resolve_attachment_id( $data );
if ( is_wp_error( $attachment_id ) ) return $attachment_id;
+ // `upload_files` authorises adding a file, not editing one somebody else added. An attachment we created below is owned by the caller and needs no further check, but one they passed in by ID does.
+ if ( $supplied_attachment && !current_user_can( 'edit_post', $attachment_id ) ) {
+ return Utils::error( 'em_api_media_edit_forbidden', __( 'You do not have permission to edit this attachment.', 'events-manager' ), 403 );
+ }
// Optional post-upload metadata.
$post_update = array( 'ID' => $attachment_id );
if ( !empty( $data['title'] ) ) $post_update['post_title'] = sanitize_text_field( $data['title'] );
--- a/events-manager/classes/em-archetypes.php
+++ b/events-manager/classes/em-archetypes.php
@@ -432,6 +432,9 @@
if ( empty($type['rewrite']) ) {
$archetype['rewrite'] = [ 'slug' => $archetype['slug'], 'with_front' => false ];
}
+ if ( !isset( $archetype['taxonomies'] ) || $archetype['taxonomies'] === '' ) {
+ $archetype['taxonomies'] = [];
+ }
// return final post type of archetype
return $archetype;
}
@@ -805,6 +808,9 @@
* @return string|false
*/
public static function get_post_type( $cpt ) {
+ if ( is_array( $cpt ) ) {
+ return false;
+ }
if ( !is_string( $cpt ) ) {
if( !empty( $cpt->post_type ) ){
$cpt = $cpt->post_type;
--- a/events-manager/classes/em-booking.php
+++ b/events-manager/classes/em-booking.php
@@ -432,6 +432,7 @@
}
}
// Step 3. Run filter for return value before sending emails
+ $this->flush_event_cache();
$this->compat_keys();
$return = apply_filters('em_booking_save', ( count($this->errors) == 0 ), $this, $update);
//Final Step: email if necessary after all the saving has been done
@@ -457,6 +458,12 @@
return apply_filters('em_booking_save', false, $this, false);
}
+ /**
+ * Drops the cached event this booking belongs to, whose bookings and spaces counts are stale as soon as one of its bookings changes.
+ */
+ protected function flush_event_cache(){
+ EM_Event::flush_cache( array( $this->get_event_id(), $this->get_event_uid() ) );
+ }
/**
* Gets the user meta for this booking, which may reside withih the booking context or in the user meta context.
@@ -1237,6 +1244,7 @@
$wpdb->delete( EM_META_TABLE, array('meta_key'=>'booking-note', 'object_id' => $this->booking_id), array('%s','%d'));
$wpdb->delete( EM_BOOKINGS_META_TABLE, array('booking_id'=> $this->booking_id), array('%d'));
$this->deleted = true;
+ $this->flush_event_cache();
do_action('em_booking_deleted', $this);
}else{
$this->add_error(sprintf(__('%s could not be deleted', 'events-manager'), __('Booking','events-manager')));
@@ -1339,6 +1347,7 @@
$this->booking_status = absint($status);
$result = $wpdb->query($wpdb->prepare('UPDATE '.EM_BOOKINGS_TABLE.' SET booking_status=%d WHERE booking_id=%d', array($status, $this->booking_id)));
if($result !== false){
+ $this->flush_event_cache();
$this->update_meta('previous_status', $this->previous_status);
$this->feedback_message = sprintf(__('Booking %s.','events-manager'), $action_string);
$result = apply_filters('em_booking_set_status', $result, $this); // run the filter before emails go out, in case others need to hook in first
@@ -1981,7 +1990,8 @@
*/
public function date( $utc_timezone = false ){
if( empty($this->date) || !$this->date->valid ){
- if( !empty($this->booking_date ) ){
+ // a zero MySQL datetime passes empty() and parses to year -0001 rather than throwing, so it has to be rejected by hand
+ if( !empty($this->booking_date) && substr($this->booking_date, 0, 4) !== '0000' ){
$this->date = new EM_DateTime($this->booking_date, 'UTC');
}else{
//we retrn a date regardless but it's not based on a 'valid' booking date
--- a/events-manager/classes/em-bookings-table.php
+++ b/events-manager/classes/em-bookings-table.php
@@ -399,12 +399,12 @@
}
if( !empty($EM_Bookings_Table) ) {
// Re-check management rights against the object actually being rendered: row_id/booking_id are request-supplied and the 'refresh' action reaches here without the capability gate applied to the mutating verbs above.
- if ( $_REQUEST['view'] === 'attendees' ) {
+ if ( isset( $_REQUEST['view'] ) && $_REQUEST['view'] === 'attendees' ) {
$EM_Ticket_Booking = new EM_Ticket_Booking( $_REQUEST['row_id'] );
if ( ! $EM_Ticket_Booking->can_manage( 'manage_bookings', 'manage_others_bookings' ) ) return;
$EM_Ticket_Booking->feedback_message = $EM_Booking->feedback_message;
$EM_Bookings_Table->single_row( $EM_Ticket_Booking );
- } elseif ( $_REQUEST['view'] === 'tickets' ) {
+ } elseif ( isset( $_REQUEST['view'] ) && $_REQUEST['view'] === 'tickets' ) {
$row_id = explode( '-', $_REQUEST['row_id'] );
$data = array( 'booking_id' => $row_id[0], 'ticket_id' => $row_id[1] );
if ( ! em_get_booking( $row_id[0] )->can_manage( 'manage_bookings', 'manage_others_bookings' ) ) return;
@@ -1158,7 +1158,7 @@
* @return false|string
*/
public function get_attendees_multiple_col( $attendees_array, $col, $EM_Object, $html = false ){
- ob_start();
+ $value = '';
if( !in_array( $this->format, ['csv', 'xls', 'xlsx'] ) ){
if ( $EM_Object instanceof EM_Ticket_Bookings ) {
$EM_Ticket_Bookings = $EM_Object;
@@ -1266,7 +1266,7 @@
extract( $this->get_item_objects($item) ); /* @var EM_Ticket $EM_Ticket *//* @var EM_Ticket_Booking $EM_Ticket_Booking *//* @var EM_Ticket_Bookings $EM_Ticket_Bookings *//* @var EM_Booking $EM_Booking */
$column_id = $item instanceof EM_Ticket_Bookings ? $item->booking_id . '-' . $item->ticket_id : $this->id;
$html = sprintf('<input type="checkbox" name="column_id[]" value="%s" data-id="%d" />', $column_id, $EM_Booking->booking_id);
- if( $EM_Booking->booking_status === false && DOING_AJAX && !empty($_REQUEST['row_action']) && $_REQUEST['row_action'] == 'bookings_delete' ){
+ if( $EM_Booking->booking_status === false && DOING_AJAX && !empty($_REQUEST['row_action']) && $_REQUEST['row_action'] == 'delete' ){
// booking deleted, no editing/actions possible
return $html;
}
--- a/events-manager/classes/em-bookings.php
+++ b/events-manager/classes/em-bookings.php
@@ -464,11 +464,12 @@
*/
function delete(){
global $wpdb;
- $booking_ids = $event_ids = array();
+ $booking_ids = $event_ids = $event_uids = array();
if( !empty($this->bookings) ){
//get the booking ids tied to this event or preloaded into this object
foreach( $this->bookings as $EM_Booking ){
$booking_ids[] = $EM_Booking->booking_id;
+ $event_uids[] = $EM_Booking->get_event_uid();
}
$result_tickets = true;
$result = true;
@@ -484,6 +485,7 @@
$event_id = absint($this->event_id);
$event_ids = array($event_id);
$timeslot = !empty($this->timeslot_id) ? ' AND timeslot_id = ' . absint($this->timeslot_id) : '';
+ if( !empty($this->timeslot_id) ) $event_uids[] = $event_id . ':' . absint($this->timeslot_id);
$booking_ids = $wpdb->get_col("SELECT booking_id FROM ".EM_BOOKINGS_TABLE." WHERE event_id = '$event_id' $timeslot");
$result_tickets = $wpdb->query("DELETE FROM ". EM_TICKETS_BOOKINGS_TABLE ." WHERE booking_id IN (SELECT booking_id FROM ".EM_BOOKINGS_TABLE." WHERE event_id = '$event_id' $timeslot)");
$result = $wpdb->query("DELETE FROM ".EM_BOOKINGS_TABLE." WHERE event_id = '$event_id' $timeslot");
@@ -494,6 +496,8 @@
//we have not bookings loaded to delete, nor an event to delete bookings from, so bookings are considered 'deleted' since there's nothing ot delete
$result = $result_tickets = true;
}
+ // this path never runs EM_Booking::delete(), so the events it just emptied are dropped from the cache here
+ EM_Event::flush_cache( array_merge($event_ids, $event_uids) );
do_action('em_bookings_deleted', $result, $booking_ids, $event_ids);
return apply_filters('em_bookings_delete', $result !== false && $result_tickets !== false, $booking_ids, $this, $event_ids);
}
@@ -642,7 +646,7 @@
function get_pending_spaces( $force_refresh = false ){
if( em_get_option('dbem_bookings_approval') ) {
if ( $this->pending_spaces === null || $force_refresh ) {
- $pending_spaces = $this->get_status_count( 0 );
+ $pending_spaces = $this->get_status_count( 0, $force_refresh );
$this->pending_spaces = $pending_spaces > 0 ? $pending_spaces : 0;
$this->pending_spaces = apply_filters('em_bookings_get_pending_spaces', $this->pending_spaces, $this, $force_refresh);
}
--- a/events-manager/classes/em-datetime.php
+++ b/events-manager/classes/em-datetime.php
@@ -47,6 +47,12 @@
@parent::__construct( (string) $time, $timezone);
if( substr($time,0,1) == '@' || $time == 'now' ) $this->setTimezone($timezone);
$this->valid = true; //if we get this far, supplied time is valid
+ if( (int) parent::format('Y') < 1000 ){
+ // zero dates such as 0000-00-00 00:00:00 do not throw, they parse to year -0001, so treat an impossible year as a failed date
+ $this->setDate(1970,1,1);
+ $this->setTime(0,0,0);
+ $this->valid = false; // setDate() and setTime() mark themselves valid, so this stays last
+ }
}catch( Exception $e ){
//get current date/time in relevant timezone and set valid flag to false
try {
--- a/events-manager/classes/em-event-post-admin.php
+++ b/events-manager/classes/em-event-post-admin.php
@@ -246,7 +246,8 @@
$post = get_post($EM_Event->post_id);
$EM_Event->load_postdata($post);
unset($EM_Event->refresh_cache);
- wp_cache_set($EM_Event->event_id, $EM_Event, 'em_events');
+ // a clone, so a persistent cache cannot store an emptied bookings child
+ wp_cache_set($EM_Event->event_id, clone $EM_Event, 'em_events');
wp_cache_set($EM_Event->post_id, $EM_Event->event_id, 'em_events_ids');
}
}
--- a/events-manager/classes/em-event.php
+++ b/events-manager/classes/em-event.php
@@ -592,32 +592,31 @@
}
/**
- * Sets the timeslot ID for this event
- * @param $timeslot_id
+ * Turns this event into one of its own timeslots, in place, taking on that slot's dates, times and status.
+ *
+ * @param int $timeslot_id
+ * @throws Exception If the id names no timeslot of this event.
*
* @return void
*/
public function set_timeslot_id( $timeslot_id ){
- global $wpdb;
if ( !$this->timeslot_id ) {
- $this->timeslot_id = absint( $timeslot_id );
- // change the date, times and overriding features of the event so it's specific to the timeslot
- $timeslot_data = $wpdb->get_row('SELECT * FROM '. EM_EVENT_TIMESLOTS_TABLE .' WHERE timeslot_id'. $this->timeslot_id .' event_id='. absint($this->event_id), ARRAY_A );
- $this->set_timeslot_data( $timeslot_data );
+ // Delegated rather than queried here: the loader in EMEventTimeslot binds the row to this event, which the id on its own does not, and a second copy of that query is how this one came to read columns the table has never had.
+ $this->convert_to_timeslot( absint( $timeslot_id ), true );
}
}
public function set_timeslot_data( $timeslot_data ) {
//reset start and end objects so they are recreated with the new dates/times if and when needed
- $start = explode(' ', $timeslot_data['event_timeslot_start'] );
- $end = explode(' ', $timeslot_data['event_timeslot_end'] );
+ $start = explode(' ', $timeslot_data['timeslot_start'] );
+ $end = explode(' ', $timeslot_data['timeslot_end'] );
$this->event_start_date = $start[0];
$this->event_start_time = $start[1];
$this->event_end_date = $end[0];
$this->event_end_time = $end[1];
$this->start = $this->end = $this->event_start = $this->event_end = null;
// event status
- $this->event_active_status = $timeslot_data['event_timeslot_status'];
+ $this->event_active_status = $timeslot_data['timeslot_status'];
// reset objects specific to the timeslot
$this->bookings = null;
}
@@ -787,6 +786,16 @@
}
}
+ /**
+ * Drops object-cached events by id, so anything derived from their bookings is queried again.
+ * @param int|string|array $event_ids One or more event ids, with or without a timeslot id.
+ */
+ public static function flush_cache( $event_ids ){
+ foreach( array_unique( (array) $event_ids ) as $event_id ){
+ if( $event_id ) wp_cache_delete( $event_id, 'em_events' );
+ }
+ }
+
function load_postdata($event_post, $search_by = false){
//load event post object if it's an actual object and also a post type of our event CPT names
if( is_object($event_post) && Archetypes::is_valid_cpt( $event_post->post_type, ['location'] ) ){
@@ -1347,6 +1356,13 @@
}
//start saving process
do_action('em_event_save_pre', $this);
+ // programmatic saves (imports, REST, add-ons) never run get_post(), which is where these are otherwise decided, and a NULL of either excludes the event from every listing query
+ if( empty($this->event_archetype) ){
+ $this->event_archetype = Archetypes::get_from_cpt( $this->post_type ) ?: EM_POST_TYPE_EVENT;
+ }
+ if( empty($this->event_type) ){
+ $this->event_type = $this->is_repeating() ? 'repeating' : 'single';
+ }
$post_array = array();
//Deal with updates to an event
if( !empty($this->post_id) ){
@@ -1428,7 +1444,8 @@
$this->load_postdata($this);
//postless events are never object-cached (matches the load path guard) and a NULL post_id must not become a cache key
if( $this->post_id ){
- wp_cache_set( $this->get_event_uid(), $this, 'em_events');
+ // a clone, because saving a new event empties its bookings child and a persistent cache would store that emptied array instead of rebuilding it on load
+ wp_cache_set( $this->get_event_uid(), clone $this, 'em_events');
wp_cache_set( $this->post_id, $this->get_event_uid(), 'em_events_ids');
}
}
@@ -2058,6 +2075,24 @@
}
/**
+ * Whether this event's post is password-protected and the current visitor hasn't unlocked it. Anyone who can manage the event sees it regardless, matching how location map balloons already behave.
+ * @return boolean
+ */
+ public function password_required(){
+ $required = false;
+ if ( !empty($this->post_id) ) {
+ // post_password lives in wp_posts, so in MS Global mode the lookup has to happen on the blog that owns the event.
+ if ( EM_MS_GLOBAL && !empty($this->blog_id) && get_current_blog_id() != $this->blog_id ) {
+ switch_to_blog($this->blog_id);
+ $switch_back = true;
+ }
+ $required = post_password_required( $this->post_id ) && !$this->can_manage('edit_events','edit_others_events');
+ if ( !empty($switch_back) ) restore_current_blog();
+ }
+ return apply_filters('em_event_password_required', $required, $this);
+ }
+
+ /**
* Returns an EM_DateTime object of the event start date/time in local timezone of event.
* @param bool $utc_timezone Returns EM_DateTime with UTC timezone if set to true, returns local timezone by default.
* @return EM_DateTime
--- a/events-manager/classes/em-location.php
+++ b/events-manager/classes/em-location.php
@@ -683,6 +683,24 @@
}
/**
+ * Whether this location's post is password-protected and the current visitor hasn't unlocked it. Anyone who can manage the location sees it regardless, matching how map balloons already behave.
+ * @return boolean
+ */
+ public function password_required(){
+ $required = false;
+ if ( !empty($this->post_id) ) {
+ // post_password lives in wp_posts, so in MS Global mode the lookup has to happen on the blog that owns the location.
+ if ( EM_MS_GLOBAL && !empty($this->blog_id) && get_current_blog_id() != $this->blog_id ) {
+ switch_to_blog($this->blog_id);
+ $switch_back = true;
+ }
+ $required = post_password_required( $this->post_id ) && !$this->can_manage('edit_locations','edit_others_locations');
+ if ( !empty($switch_back) ) restore_current_blog();
+ }
+ return apply_filters('em_location_password_required', $required, $this);
+ }
+
+ /**
* Change the status of the location. This will save to the Database too.
* @param int $status A number to change the status to, which may be -1 for trash, 1 for publish, 0 for pending or null if draft.
* @param boolean $set_post_status If set to true the wp_posts table status will also be changed to the new corresponding status.
--- a/events-manager/classes/em-permalinks.php
+++ b/events-manager/classes/em-permalinks.php
@@ -115,13 +115,14 @@
global $wpdb;
//get the slug of the event page
$events_page_id = em_get_option( 'dbem_events_page' );
- $events_page = get_post( $events_page_id );
+ $events_page = $events_page_id ? get_post( $events_page_id ) : null;
$em_rules = array ();
if ( is_object( $events_page ) ) {
$events_slug = urldecode( preg_replace( '//$/', '', str_replace( trailingslashit( home_url() ), '', get_permalink( $events_page_id ) ) ) );
$events_slug = ( !empty( $events_slug ) ) ? trailingslashit( $events_slug ) : $events_slug;
$events_pagename = trim( $events_slug, '/' );
$em_rules[ $events_slug . '(d{4}-d{2}-d{2})$' ] = 'index.php?pagename=' . $events_pagename . '&calendar_day=$matches[1]'; //event calendar date search
+ $em_rules[ $events_slug . '(d{4}-d{2}-d{2})/page/?([0-9]{1,})/?$' ] = 'index.php?pagename=' . $events_pagename . '&calendar_day=$matches[1]&paged=$matches[2]'; //event calendar date search paged
if ( $events_page_id != em_get_option( 'page_on_front' ) && EM_POST_TYPE_EVENT_SLUG != $events_slug ) { //ignore this rule if events page is the home page
$em_rules[ $events_slug . 'rss/?$' ] = 'index.php?post_type=' . EM_POST_TYPE_EVENT . '&feed=feed'; //rss page
$em_rules[ $events_slug . 'feed/?$' ] = 'index.php?post_type=' . EM_POST_TYPE_EVENT . '&feed=feed'; //compatible rss page
@@ -202,7 +203,7 @@
foreach ( array ( 'tags', 'categories' ) as $taxonomy_name ) {
if ( em_get_option( 'dbem_' . $taxonomy_name . '_enabled' ) ) {
$taxonomy_page_id = em_get_option( 'dbem_' . $taxonomy_name . '_page' );
- $taxonomy_page = get_post( $taxonomy_page_id );
+ $taxonomy_page = $taxonomy_page_id ? get_post( $taxonomy_page_id ) : null;
if ( is_object( $taxonomy_page ) ) {
//we are using a categories page, so we add it to permalinks if it's not a parent of the events page
if ( !is_object( $events_page ) || !in_array( $events_page->ID, get_post_ancestors( $taxonomy_page_id ) ) ) {
@@ -229,7 +230,7 @@
//If in MS global mode and locations are linked on same site
if ( EM_MS_GLOBAL && !get_site_option( 'dbem_ms_global_locations_links', true ) ) {
$locations_page_id = em_get_option( 'dbem_locations_page' );
- $locations_page = get_post( $locations_page_id );
+ $locations_page = $locations_page_id ? get_post( $locations_page_id ) : null;
if ( is_object( $locations_page ) ) {
$locations_slug = preg_replace( '//$/', '', str_replace( trailingslashit( home_url() ), '', get_permalink( $locations_page_id ) ) );
$em_rules[ $locations_slug . '/' . get_site_option( 'dbem_ms_locations_slug', EM_LOCATION_SLUG ) . '/(.+)$' ] = 'index.php?pagename=' . trim( $locations_slug, '/' ) . '&location_slug=$matches[1]'; //single event booking form with slug
@@ -374,23 +375,30 @@
/**
* returns the url of the my bookings page, depending on the settings page and if BP is installed.
+ * @param int $person_id if given and BP is active, returns that member's bookings url instead of the displayed user's
* @return string
*/
-function em_get_my_bookings_url(){
+function em_get_my_bookings_url( $person_id = 0 ){
global $bp, $wp_rewrite;
- // @todo add filter for bookings url, remove bp condition and add it to bp-em-core.php
+ $person_id = absint($person_id);
+ // @todo remove bp condition and add it to bp-em-core.php
if( !empty($bp->events->link) ){
//get member url
- return $bp->events->link.'attending/';
+ if( $person_id && function_exists('bp_core_get_user_domain') ){
+ $url = trailingslashit( bp_core_get_user_domain($person_id) ).BP_EM_SLUG.'/attending/';
+ }else{
+ $url = $bp->events->link.'attending/';
+ }
}elseif( em_get_option('dbem_my_bookings_page') ){
- return get_permalink(em_get_option('dbem_my_bookings_page'));
+ $url = get_permalink(em_get_option('dbem_my_bookings_page'));
}else{
if( $wp_rewrite->using_permalinks() && !defined('EM_DISABLE_PERMALINKS') ){
- return trailingslashit(EM_URI)."my-bookings/";
+ $url = trailingslashit(EM_URI)."my-bookings/";
}else{
- return preg_match('/?/',EM_URI) ? EM_URI.'&bookings_page=1':EM_URI.'?bookings_page=1';
+ $url = preg_match('/?/',EM_URI) ? EM_URI.'&bookings_page=1':EM_URI.'?bookings_page=1';
}
}
+ return apply_filters('em_get_my_bookings_url', $url, $person_id);
}
/**
--- a/events-manager/classes/lib/wp-oauth-app-passwords/loader.php
+++ b/events-manager/classes/lib/wp-oauth-app-passwords/loader.php
@@ -92,4 +92,4 @@
* Always register THIS copy. The version literal is the single source of truth
* for this bundled copy and is bumped on every library release.
*/
-pixelite_oauth_app_passwords_register( '0.1.14', __DIR__ );
+pixelite_oauth_app_passwords_register( '0.1.15', __DIR__ );
--- a/events-manager/classes/lib/wp-oauth-app-passwords/src/Consent.php
+++ b/events-manager/classes/lib/wp-oauth-app-passwords/src/Consent.php
@@ -26,6 +26,10 @@
*/
'account_note' => (string) apply_filters( 'pixelite_oauth_consent_account_note', '', $user ),
'branding' => self::branding(),
+ // Where approving actually sends the credential. Without this the user sees only a name the client chose and has no way to tell a first-party integration from someone else's host.
+ 'destination' => self::destination_label( $params['redirect_uri'] ),
+ // A client that registered itself through the open /register endpoint has been vetted by nobody, so say so rather than letting its chosen name imply otherwise.
+ 'self_registered' => ! empty( $params['client']['dynamic'] ),
'hidden' => array_filter( array(
'response_type' => 'code',
'client_id' => $params['client_id'],
@@ -34,7 +38,6 @@
'scope' => $params['scope'],
'code_challenge' => $params['code_challenge'],
'code_challenge_method' => $params['code_challenge_method'],
- 'client_name' => $params['client_name'],
) ),
'form_action' => Authorize::url(),
'switch_url' => wp_logout_url( self::current_url() ),
@@ -50,6 +53,22 @@
}
/**
+ * Short, readable form of the redirect URI for display: the host for an http(s) URI, the scheme itself for a custom-scheme app redirect, and the raw URI as a last resort.
+ */
+ private static function destination_label( string $redirect_uri ): string {
+ if ( '' === $redirect_uri ) {
+ return '';
+ }
+ $host = (string) wp_parse_url( $redirect_uri, PHP_URL_HOST );
+ if ( '' !== $host ) {
+ $port = wp_parse_url( $redirect_uri, PHP_URL_PORT );
+ return $port ? $host . ':' . (int) $port : $host;
+ }
+ $scheme = (string) wp_parse_url( $redirect_uri, PHP_URL_SCHEME );
+ return '' !== $scheme ? $scheme . '://' : $redirect_uri;
+ }
+
+ /**
* Build the list of permission rows shown on the consent screen.
*
* Important: the OAuth scope string is purely a client-side label in this library. The access token the client receives IS a WordPress Application Password, and App Passwords have no scope concept — they grant the user's full WordPress capabilities. Whichever scope the client requested, the granted access is identical.
--- a/events-manager/classes/lib/wp-oauth-app-passwords/src/Endpoints/Authorize.php
+++ b/events-manager/classes/lib/wp-oauth-app-passwords/src/Endpoints/Authorize.php
@@ -115,7 +115,8 @@
if ( '' === $scope ) {
$scope = Server::default_scope();
}
- $client_name = self::param( 'client_name' );
+ // The displayed name comes from the stored client record, never from the request. Taking it from a `client_name` parameter let anyone who could register a client (registration is open by RFC 7591's open profile) put an arbitrary trusted-looking name on a consent screen served from the site's own domain.
+ $client_name = is_array( $client ) ? (string) ( $client['name'] ?? '' ) : '';
return array(
'client_id' => $client_id,
@@ -126,7 +127,6 @@
'code_challenge' => self::param( 'code_challenge' ),
'code_challenge_method' => self::param( 'code_challenge_method' ),
'response_type' => self::param( 'response_type' ),
- 'client_name' => $client_name,
'app_name' => Support::guess_app_name( $client_name, $redirect ),
);
}
@@ -140,7 +140,6 @@
'scope' => $p['scope'],
'code_challenge' => $p['code_challenge'],
'code_challenge_method' => $p['code_challenge_method'],
- 'client_name' => $p['client_name'],
) ) ), self::url() );
}
--- a/events-manager/classes/lib/wp-oauth-app-passwords/templates/consent.php
+++ b/events-manager/classes/lib/wp-oauth-app-passwords/templates/consent.php
@@ -125,6 +125,27 @@
border-color: var(--wpoap-accent);
}
.wpoap-hint { font-size: 12px; color: var(--wpoap-muted); margin-top: 5px; }
+ .wpoap-dest {
+ text-align: center;
+ font-size: 13px;
+ color: var(--wpoap-muted);
+ margin: -12px 0 18px;
+ overflow-wrap: anywhere;
+ }
+ .wpoap-dest strong { color: var(--wpoap-text); font-weight: 600; }
+ .wpoap-unverified {
+ display: flex;
+ gap: 8px;
+ align-items: flex-start;
+ background: #fcf3e6;
+ border: 1px solid #dba617;
+ border-radius: 9px;
+ padding: 11px 13px;
+ font-size: 13px;
+ line-height: 1.45;
+ margin: 0 0 18px;
+ }
+ .wpoap-unverified svg { flex: 0 0 18px; margin-top: 1px; color: #8a6116; }
.wpoap-perms {
background: #f6f7f7;
border: 1px solid var(--wpoap-line);
@@ -201,6 +222,20 @@
printf( esc_html__( 'Grant this application access to %s on your behalf.', 'wp-oauth-app-passwords' ), esc_html( $branding['site_name'] ) );
?></p>
+ <?php if ( ! empty( $v['destination'] ) ) : ?>
+ <p class="wpoap-dest"><?php
+ /* translators: %s: host the credential will be sent to, e.g. claude.ai */
+ printf( esc_html__( 'Your credential will be sent to %s', 'wp-oauth-app-passwords' ), '<strong>' . esc_html( $v['destination'] ) . '</strong>' );
+ ?></p>
+ <?php endif; ?>
+
+ <?php if ( ! empty( $v['self_registered'] ) ) : ?>
+ <div class="wpoap-unverified">
+ <svg viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M10 2.5a1 1 0 0 1 .87.5l7 12A1 1 0 0 1 17 16.5H3a1 1 0 0 1-.87-1.5l7-12a1 1 0 0 1 .87-.5Zm0 4a.9.9 0 0 0-.9.98l.3 3.2a.6.6 0 0 0 1.2 0l.3-3.2A.9.9 0 0 0 10 6.5Zm0 6a1 1 0 1 0 0 2 1 1 0 0 0 0-2Z" fill="currentColor"/></svg>
+ <div><?php esc_html_e( 'This application registered itself with your site and has not been reviewed by anyone. Only approve it if you started this connection yourself and recognise the destination above.', 'wp-oauth-app-passwords' ); ?></div>
+ </div>
+ <?php endif; ?>
+
<form method="post" action="<?php echo esc_url( $v['form_action'] ); ?>">
<?php wp_nonce_field( 'pixelite_oauth_consent', '_pixelite_oauth_nonce' ); ?>
<?php foreach ( $v['hidden'] as $name => $value ) : ?>
--- a/events-manager/classes/recurrences/recurrence-set.php
+++ b/events-manager/classes/recurrences/recurrence-set.php
@@ -981,6 +981,8 @@
//Make template event index, post, and meta (we change event dates, timestamps, rsvp dates and other recurrence-relative info whilst saving each event recurrence)
list( $event, $post_fields, $meta_fields ) = $this->get_recurrence_saving_fields();
+ // post_name is overwritten with the dated slug on every iteration below, so the un-dated base has to be kept separately
+ $base_post_name = $post_fields['post_name'] ?? '';
$recurring_date_format = apply_filters( 'em_event_save_events_format', 'Y-m-d' );
// modify some field values we don't need for a recreation
$event['event_date_created'] = current_time( 'mysql' ); //since the recurrences are recreated
@@ -1012,7 +1014,7 @@
//set post slug, which may need to be sanitized for length as we pre/postfix a date for uniqueness
if ( $EM_Event->is_repeating() ) {
$event_slug_date = $EM_DateTime->format( $recurring_date_format );
- $event_slug = $this->sanitize_recurrence_slug( $post_fields['post_name'], $event_slug_date );
+ $event_slug = $this->sanitize_recurrence_slug( $base_post_name, $event_slug_date );
$event_slug = apply_filters( 'em_event_save_events_recurrence_slug', $event_slug . '-' . $event_slug_date, $event_slug, $event_slug_date, $day, $EM_Event, $this ); //use this instead
$post_fields['post_name'] = $event['event_slug'] = apply_filters( 'em_event_save_events_slug', $event_slug, $post_fields, $day, $matching_days, $EM_Event, $this ); //deprecated filter
}
--- a/events-manager/classes/timeslots/event-timeslot.php
+++ b/events-manager/classes/timeslots/event-timeslot.php
@@ -45,7 +45,12 @@
global $wpdb;
// load timeslot from database if id supplied
if ( is_numeric( $args ) ) {
- $args = $wpdb->get_row( "SELECT * FROM " . EM_EVENT_TIMESLOTS_TABLE . " WHERE timeslot_id = " . absint( $args ), ARRAY_A );
+ // Bound to the event as well as the id: a slot id posted from the browser could otherwise name any event's slot, and the booking would land on this event carrying the other one's times and a fresh per-slot count.
+ $sql = "SELECT * FROM " . EM_EVENT_TIMESLOTS_TABLE . " WHERE timeslot_id = " . absint( $args );
+ if ( ! empty( $EM_Event->event_id ) ) {
+ $sql .= " AND event_id = " . absint( $EM_Event->get_event_id() );
+ }
+ $args = $wpdb->get_row( $sql, ARRAY_A );
$loaded_event = true;
}
if ( $args ) {
--- a/events-manager/em-actions.php
+++ b/events-manager/em-actions.php
@@ -107,12 +107,7 @@
exit();
} elseif ( $_REQUEST['action'] == 'booking_form_nonces' ) {
if ( ( defined( 'WP_CACHE' ) && WP_CACHE ) || defined( 'EM_CACHE' ) && EM_CACHE ) {
- $nonces = array (
- 'booking_form' => wp_create_nonce( 'booking_form' ),
- 'booking_recurrences' => wp_create_nonce( 'booking_recurrences' ),
- 'booking_add' => wp_create_nonce( 'booking_add' ),
- );
- echo EM_Object::json_encode( $nonces );
+ echo EM_Object::json_encode( em_booking_form_nonces() );
exit();
}
}
@@ -360,7 +355,7 @@
if ( $_REQUEST['action'] == 'booking_add') {
//ADD/EDIT Booking
ob_start();
- em_verify_nonce('booking_add');
+ em_verify_booking_nonce('booking_add');
if( !is_user_logged_in() || $EM_Booking->get_option('dbem_bookings_double') || !$EM_Event->get_bookings()->has_booking(get_current_user_id()) ){
if ( $EM_Event->event_status != 1 || $EM_Event->event_active_status != 1 ) {
$EM_Notices->add_error( __('This event is not available or has been cancelled', 'events-manager') ); // uncommon, not needed for custom error.
@@ -671,12 +666,12 @@
if( $result && defined('DOING_AJAX') ){
$return = array('result'=>true, 'success'=>true, 'message'=>$feedback);
- header( 'Content-Type: application/javascript; charset=UTF-8', true ); //add this for HTTP -> HTTPS requests which assume it's a cross-site request
+ if( !headers_sent() ) header( 'Content-Type: application/javascript; charset=UTF-8', true ); //add this for HTTP -> HTTPS requests which assume it's a cross-site request
echo EM_Object::json_encode(apply_filters('em_action_'.$_REQUEST['action'], $return, $EM_Booking));
die();
}elseif( !$result && defined('DOING_AJAX') ){
$return = array('result'=>false, 'success'=>false, 'message'=>$feedback, 'errors'=>$EM_Notices->get_errors());
- header( 'Content-Type: application/javascript; charset=UTF-8', true ); //add this for HTTP -> HTTPS requests which assume it's a cross-site request
+ if( !headers_sent() ) header( 'Content-Type: application/javascript; charset=UTF-8', true ); //add this for HTTP -> HTTPS requests which assume it's a cross-site request
echo EM_Object::json_encode(apply_filters('em_action_'.$_REQUEST['action'], $return, $EM_Booking));
die();
}
--- a/events-manager/em-functions.php
+++ b/events-manager/em-functions.php
@@ -316,6 +316,57 @@
}
/**
+ * Verifies a booking form nonce, ending the request in the format it expects if verification fails.
+ * @param string $action
+ * @param string $nonce_name
+ * @return bool
+ */
+function em_verify_booking_nonce( $action, $nonce_name = '_wpnonce' ){
+ if( wp_verify_nonce( $_REQUEST[$nonce_name] ?? '', $action ) ) return true;
+ $message = __('This booking form has expired, please reload the page and try again.','events-manager');
+ if( !empty($_REQUEST['em_ajax']) ){
+ $return = array('result'=>false, 'success'=>false, 'message'=>$message, 'errors'=>array($message));
+ if( !headers_sent() ) header( 'Content-Type: application/javascript; charset=UTF-8', true );
+ // wp_die() rather than exit() so the body leaves through WP's ajax die handler, as core's own wp_send_json() does
+ wp_die( EM_Object::json_encode( apply_filters( 'em_booking_nonce_expired', $return, $action ) ), '', array('response' => null) );
+ }
+ exit( $message );
+}
+
+/**
+ * Booking form actions whose nonce is refreshed on cached pages. Add-ons with a booking form action of their own, such as waitlists, add theirs here so the refresh reaches their forms too.
+ * @return array
+ */
+function em_booking_form_nonce_actions(){
+ $actions = apply_filters( 'em_booking_form_nonce_actions', array('booking_add') );
+ return array_values( array_unique( array_filter( array_map( 'sanitize_key', (array) $actions ) ) ) );
+}
+
+/**
+ * Whether a booking form action's nonce is served by the cached-page nonce refresh.
+ * @param string $action
+ * @return bool
+ */
+function em_booking_form_nonce_refreshable( $action ){
+ return in_array( $action, em_booking_form_nonce_actions(), true );
+}
+
+/**
+ * Fresh nonces for booking forms on cached pages, keyed by the form action they belong to.
+ * @return array
+ */
+function em_booking_form_nonces(){
+ $nonces = array(
+ 'booking_form' => wp_create_nonce( 'booking_form' ),
+ 'booking_recurrences' => wp_create_nonce( 'booking_recurrences' ),
+ );
+ foreach( em_booking_form_nonce_actions() as $booking_action ){
+ $nonces[$booking_action] = wp_create_nonce( $booking_action );
+ }
+ return apply_filters( 'em_booking_form_nonces', $nonces );
+}
+
+/**
* Since WP 4.5 em_wp_get_referer() returns false if URL is the same. We use it to get a safe referrer url, so we use the new wp_get_raw_referer() argument instead.
* @since 5.6.3
* @return string
--- a/events-manager/em-ical.php
+++ b/events-manager/em-ical.php
@@ -8,6 +8,7 @@
header('Content-Type: text/calendar; charset=utf-8');
header('Content-Disposition: inline; filename="events.ics"');
//send headers
+ em_ical_protect_passworded_events();
em_locate_template('templates/ical.php', true);
die();
}
@@ -15,6 +16,22 @@
add_action ( 'init', 'em_ical' );
/**
+ * Keeps password-protected events out of an iCalendar feed. The feed publishes the event name, description, permalink, image, location and coordinates, none of which a visitor should get without the password, and the query layer can't tell: event_status and event_private say nothing about wp_posts.post_password.
+ *
+ * Filtering EM_Events::get() rather than the template means a theme carrying its own copy of ical.php is covered too.
+ */
+ function em_ical_protect_passworded_events(){
+ add_filter('em_events_get', function( $events ){
+ foreach ( $events as $key => $EM_Event ) {
+ if ( is_object($EM_Event) && method_exists($EM_Event, 'password_required') && $EM_Event->password_required() ) {
+ unset($events[$key]);
+ }
+ }
+ return $events;
+ });
+ }
+
+ /**
* Generates an ics file for a single event, or a specific archetype
*/
function em_ical_item(){
@@ -77,6 +94,7 @@
//send headers and output ical
header('Content-type: text/calendar; charset=utf-8');
header('Content-Disposition: inline; filename="'.$filename.'.ics"');
+ em_ical_protect_passworded_events();
em_locate_template('templates/ical.php', true, array('args'=>$args));
exit();
}else{
--- a/events-manager/em-install.php
+++ b/events-manager/em-install.php
@@ -526,6 +526,7 @@
function em_add_options() {
global $wp_locale, $wpdb;
+ if( !class_exists("EM_Admin_Notice") ) include_once( EM_DIR . "/classes/em-admin-notices.php" ); // only loaded for admin requests otherwise, but activation can run from WP-CLI
$already_installed = get_option('dbem_version', false) !== false;
if( !$already_installed ) {
$advice = sprintf( __("<p>Events Manager is ready to go! It is highly recommended you read the <a href='%s'>Getting Started</a> guide on our site, as well as checking out the <a href='%s'>Settings Page</a></p>", 'events-manager'), 'https://wp-events-plugin.com/documentation/getting-started-guide/?utm_source=em&utm_medium=plugin&utm_content=installationlink&utm_campaign=plugin_links', EM_ADMIN_URL .'&page=events-manager-options');
@@ -1625,6 +1626,7 @@
}
if( $current_version != '' && version_compare($current_version, '6.1.0.1', '<') ){
+ $flag_column_ready = true;
$cols = $wpdb->get_row('SELECT * FROM '. EM_BOOKINGS_TABLE . ' LIMIT 1', ARRAY_A);
if( is_array($cols) && !array_key_exists('booking_meta_migrated', $cols) ) {
$result = $wpdb->query('ALTER TABLE ' . EM_BOOKINGS_TABLE . ' ADD `booking_meta_migrated` INT(1) NULL');
@@ -1636,79 +1638,13 @@
EM_Admin_Notices::add($EM_Admin_Notice, is_multisite());
global $em_do_not_finalize_upgrade;
$em_do_not_finalize_upgrade = true;
+ $flag_column_ready = false;
}
}
// atomic booking meta! for 6.1
- // let's go through every booking and split it all up
- $query = 'SELECT booking_id, booking_meta FROM '. EM_BOOKINGS_TABLE ." WHERE booking_meta_migrated IS NULL LIMIT 500";
- $results = $wpdb->get_results( $query, ARRAY_A );
- $timeout = ini_get('max_execution_time') >= 30 ? ini_get('max_execution_time') : 30;
- while( !empty($results) ){
- set_time_limit($timeout); // reset the timer, let it run for 30 if we keep hitting the loop, if it gets stuck inside this then let it time out
- $migrated_bookings = $booking_meta_split = array();
- foreach( $results as $booking ) {
- // now we generate split meta, any meta in an array should be dealt with by corresponding plugin (e.g. Pro for form field meta)
- if( !empty($booking['booking_meta']) ) {
- $booking_meta = EM_Object::maybe_unserialize($booking['booking_meta']);
- foreach( $booking_meta as $k => $v ){
- if( is_array($v) ) {
- // we go down one level for automated array combining
- $prefix = '_'.$k.'_';
- foreach( $v as $kk => $vv ){
- $kk = $prefix . $kk;
- if( is_array($vv) ) $vv = serialize($vv);
- // handle emojis - copied check from wpdb
- if ( (function_exists( 'mb_check_encoding' ) && !mb_check_encoding( $vv, 'ASCII' )) || preg_match( '/[^x00-x7F]/', $vv ) ) {
- $vv = wp_encode_emoji($vv);
- }
- $booking_meta_split[] = $wpdb->prepare("({$booking['booking_id']}, %s, %s)", $kk, $vv);
- }
- }else{
- // handle emojis - copied check from wpdb
- if ( (function_exists( 'mb_check_encoding' ) && !mb_check_encoding( $v, 'ASCII' )) || preg_match( '/[^x00-x7F]/', $v ) ) {
- $v = wp_encode_emoji($v);
- }
- $booking_meta_split[] = $wpdb->prepare("({$booking['booking_id']}, %s, %s)", $k, $v);
- }
- }
- // insert the new split tickets and delete the old one, rinse and repeat
- }
- // finally update the booking again so we know it was migrated
- $migrated_bookings[] = absint($booking['booking_id']);
- }
- // first check that we maybe didn't die halfway through this and there aren't others with the same ticket/bookingid combo by simply deleting these
- $wpdb->query('DELETE FROM '. EM_BOOKINGS_META_TABLE .' WHERE booking_id IN ('. implode(',', $migrated_bookings).')');
- // now add the batch
- $result = $wpdb->query('INSERT INTO '. EM_BOOKINGS_META_TABLE . ' (booking_id, meta_key, meta_value) VALUES '. implode(',', $booking_meta_split) );
- if( $result === false ){
- $message = "<strong>Events Manager is trying to update your database, but the following error occured whilst copying booking meta to the new ".EM_BOOKINGS_META_TABLE." table:</strong>";
- $message .= '</p><p>'.'<code>'. $wpdb->last_error .'</code>';
- $message .= '</p><p>This may likely need some sort of intervention, please get in touch with our support for more advice, we are sorry for the inconveneince.';
- $EM_Admin_Notice = new EM_Admin_Notice(array( 'name' => 'v6.1-booking-atomic-meta-error', 'who' => 'admin', 'where' => 'all', 'message' => $message, 'what'=>'warning' ));
- EM_Admin_Notices::add($EM_Admin_Notice, is_multisite());
- global $em_do_not_finalize_upgrade;
- $em_do_not_finalize_upgrade = true;
- break;
- } else {
- $result = $wpdb->query('UPDATE '. EM_BOOKINGS_TABLE . ' SET booking_meta_migrated=1 WHERE booking_id IN ('. implode(',', $migrated_bookings).')');
- if( $result === false ){
- $message = "<strong>Events Manager is trying to update your database, but the following error occured whilst migrating to the new ".EM_BOOKINGS_META_TABLE." table:</strong>";
- $message .= '</p><p>'.'<code>'. $wpdb->last_error .'</code>';
- $message .= '</p><p>This may likely need some sort of intervention, please get in touch with our support for more advice, we are sorry for the inconveneince.';
- $EM_Admin_Notice = new EM_Admin_Notice(array( 'name' => 'v6.1-booking-atomic-meta-error', 'who' => 'admin', 'where' => 'all', 'message' => $message, 'what'=>'warning' ));
- EM_Admin_Notices::add($EM_Admin_Notice, is_multisite());
- global $em_do_not_finalize_upgrade;
- $em_do_not_finalize_upgrade = true;
- break;
- } else {
- $results = $wpdb->get_results($query, ARRAY_A);
- }
- }
+ if( $flag_column_ready && em_migrate_booking_meta() ){
+ update_option('dbem_version', '6.1.0.2'); // we don't need to make this happen again
}
- $wpdb->query('ALTER TABLE '. EM_BOOKINGS_TABLE . ' DROP `booking_meta_migrated`'); // flag done
- EM_Admin_Notices::remove('v6.1-booking-atomic-meta-error', is_multisite());
- EM_Admin_Notices::remove('v6.1-atomic-error', is_multisite());
- update_option('dbem_version', '6.1.0.2'); // we don't need to make this happen again
}
if( $current_version != '' && version_compare($current_version, '6.1.1', '<') ){
EM_Admin_Notices::remove('v6.1-atomic-error', is_multisite());
@@ -2049,6 +1985,9 @@
if ( version_compare( $current_version, '7.4.0.2', '<' ) ) {
em_repair_detached_events();
}
+ if ( version_compare( $current_version, '7.4.4', '<' ) ) {
+ em_repair_event_defaults();
+ }
$pro_update = function() {
if ( defined('EMP_VERSION') && version_compare( EMP_VERSION, '3.7.2', '<' ) ) {
@@ -2064,6 +2003,88 @@
}
}
+/**
+ * Migrates booking_meta into the atomic bookings meta table in batches of 500, flagging each booking with booking_meta_migrated as it goes, and drops that flag column once every booking is done.
+ * The flag column must already exist. On failure an admin notice is added and $em_do_not_finalize_upgrade is set, and the flag column is left in place so the next attempt resumes where this one stopped instead of re-migrating every booking.
+ *
+ * @return bool Whether the migration ran to completion.
+ */
+function em_migrate_booking_meta(){
+ global $wpdb, $em_do_not_finalize_upgrade;
+ // let's go through every booking and split it all up
+ $query = 'SELECT booking_id, booking_meta FROM '. EM_BOOKINGS_TABLE ." WHERE booking_meta_migrated IS NULL LIMIT 500";
+ $results = $wpdb->get_results( $query, ARRAY_A );
+ $timeout = ini_get('max_execution_time') >= 30 ? ini_get('max_execution_time') : 30;
+ while( !empty($results) ){
+ set_time_limit($timeout); // reset the timer, let it run for 30 if we keep hitting the loop, if it gets stuck inside this then let it time out
+ $migrated_bookings = $booking_meta_split = array();
+ foreach( $results as $booking ) {
+ // now we generate split meta, any meta in an array should be dealt with by corresponding plugin (e.g. Pro for form field meta)
+ if( !empty($booking['booking_meta']) ) {
+ $booking_meta = EM_Object::maybe_unserialize($booking['booking_meta']);
+ foreach( $booking_meta as $k => $v ){
+ if( is_array($v) ) {
+ // we go down one level for automated array combining
+ $prefix = '_'.$k.'_';
+ foreach( $v as $kk => $vv ){
+ $kk = $prefix . $kk;
+ if( is_array($vv) ) $vv = serialize($vv);
+ // handle emojis - copied check from wpdb
+ if ( (function_exists( 'mb_check_encoding' ) && !mb_check_encoding( $vv, 'ASCII' )) || preg_match( '/[^x00-x7F]/', $vv ) ) {
+ $vv = wp_encode_emoji($vv);
+ }
+ $booking_meta_split[] = $wpdb->prepare("({$booking['booking_id']}, %s, %s)", $kk, $vv);
+ }
+ }else{
+ // handle emojis - copied check from wpdb
+ if ( (function_exists( 'mb_check_encoding' ) && !mb_check_encoding( $v, 'ASCII' )) || preg_match( '/[^x00-x7F]/', $v ) ) {
+ $v = wp_encode_emoji($v);
+ }
+ $booking_meta_split[] = $wpdb->prepare("({$booking['booking_id']}, %s, %s)", $k, $v);
+ }
+ }
+ }
+ // finally update the booking again so we know it was migrated
+ $migrated_bookings[] = absint($booking['booking_id']);
+ }
+ if( empty($migrated_bookings) ){
+ // nothing readable in this batch, so stop rather than re-running the same query or dropping the flag column while rows are unmigrated
+ return false;
+ }
+ // first check that we maybe didn't die halfway through this and there aren't others with the same ticket/bookingid combo by simply deleting these
+ $wpdb->query('DELETE FROM '. EM_BOOKINGS_META_TABLE .' WHERE booking_id IN ('. implode(',', $migrated_bookings).')');
+ // now add the batch, a batch whose bookings all had empty meta has nothing to insert but must still be flagged as migrated or the same rows come back forever
+ $result = true;
+ if( !empty($booking_meta_split) ){
+ $result = $wpdb->query('INSERT INTO '. EM_BOOKINGS_META_TABLE . ' (booking_id, meta_key, meta_value) VALUES '. implode(',', $booking_meta_split) );
+ }
+ if( $result === false ){
+ $message = "<strong>Events Manager is trying to update your database, but the following error occured whilst copying booking meta to the new ".EM_BOOKINGS_META_TABLE." table:</strong>";
+ $message .= '</p><p>'.'<code>'. $wpdb->last_error .'</code>';
+ $message .= '</p><p>This may likely need some sort of intervention, please get in touch with our support for more advice, we are sorry for the inconveneince.';
+ $EM_Admin_Notice = new EM_Admin_Notice(array( 'name' => 'v6.1-booking-atomic-meta-error', 'who' => 'admin', 'where' => 'all', 'message' => $message, 'what'=>'warning' ));
+ EM_Admin_Notices::add($EM_Admin_Notice, is_multisite());
+ $em_do_not_finalize_upgrade = true;
+ return false;
+ }
+ $result = $wpdb->query('UPDATE '. EM_BOOKINGS_TABLE . ' SET booking_meta_migrated=1 WHERE booking_id IN ('. implode(',', $migrated_bookings).')');
+ if( $result === false ){
+ $message = "<strong>Events Manager is trying to update your database, but the following error occured whilst migrating to the new ".EM_BOOKINGS_META_TABLE." table:</strong>";
+ $message .= '</p><p>'.'<code>'. $wpdb->last_error .'</code>';
+ $message .= '</p><p>This may likely need some sort of intervention, please get in touch with our support for more advice, we are sorry for the inconveneince.';
+ $EM_Admin_Notice = new EM_Admin_Notice(array( 'name' => 'v6.1-booking-atomic-meta-error', 'who' => 'admin', 'where' => 'all', 'message' => $message, 'what'=>'warning' ));
+ EM_Admin_Notices::add($EM_Admin_Notice, is_multisite());
+ $em_do_not_finalize_upgrade = true;
+ return false;
+ }
+ $results = $wpdb->get_results($query, ARRAY_A);
+ }
+ $wpdb->query('ALTER TABLE '. EM_BOOKINGS_TABLE . ' DROP `booking_meta_migrated`'); // flag done
+ EM_Admin_Notices::remove('v6.1-booking-atomic-meta-error', is_multisite());
+ EM_Admin_Notices::remove('v6.1-atomic-error', is_multisite());
+ return true;
+}
+
function em_repair_detached_events(){
global $wpdb;
//the historical detach() bug committed _event_type='single' to post meta but the events-table half of the write hit a non-existent column and failed, so realign the diverged table rows to the postmeta that already succeeded
@@ -2084,6 +2105,39 @@
);
}
+/**
+ * Fills in event_archetype and event_type on rows where a programmatic save (imports, the REST API, add-ons) left them empty.
+ */
+function em_repair_event_defaults(){
+ global $wpdb;
+ //$wpdb->insert() writes an explicit NULL over the column default when the property was never set, and a NULL archetype or type is filtered out of every event listing
+ $blog_cond = '';
+ if ( EM_MS_GLOBAL ) {
+ //main