Below is a differential between the unpatched vulnerable code and the patched update, for reference.
--- a/give/build/Campaigns/Blocks/Campaign/render.php
+++ b/give/build/Campaigns/Blocks/Campaign/render.php
@@ -15,4 +15,4 @@
}
?>
-<div data-givewp-campaign-block data-attributes=<?= json_encode($attributes) ?>></div>
+<div data-givewp-campaign-block data-attributes="<?= esc_attr(json_encode($attributes)) ?>"></div>
--- a/give/build/Campaigns/Blocks/CampaignGrid/render.php
+++ b/give/build/Campaigns/Blocks/CampaignGrid/render.php
@@ -3,4 +3,4 @@
* @var array $attributes
*/
?>
-<div data-givewp-campaign-grid data-attributes='<?= json_encode($attributes) ?>'></div>
+<div data-givewp-campaign-grid data-attributes="<?= esc_attr(json_encode($attributes)) ?>"></div>
--- a/give/build/assets/dist/js/give-migrations-list-table-app.asset.php
+++ b/give/build/assets/dist/js/give-migrations-list-table-app.asset.php
@@ -1 +1 @@
-<?php return array('dependencies' => array('moment', 'react', 'react-dom', 'wp-api-fetch', 'wp-core-data', 'wp-date', 'wp-i18n'), 'version' => 'aedab888789e6d50639f');
+<?php return array('dependencies' => array('moment', 'react', 'react-dom', 'wp-api-fetch', 'wp-core-data', 'wp-date', 'wp-i18n'), 'version' => '7476441abeaf61e3efb2');
--- a/give/give.php
+++ b/give/give.php
@@ -6,7 +6,7 @@
* Description: The most robust, flexible, and intuitive way to accept donations on WordPress.
* Author: GiveWP
* Author URI: https://givewp.com/
- * Version: 4.17.0
+ * Version: 4.18.0
* Requires at least: 6.9
* Requires PHP: 7.4
* Text Domain: give
@@ -426,7 +426,7 @@
{
// Plugin version.
if (!defined('GIVE_VERSION')) {
- define('GIVE_VERSION', '4.17.0');
+ define('GIVE_VERSION', '4.18.0');
}
// Plugin Root File.
--- a/give/includes/admin/emails/class-new-offline-donation-email.php
+++ b/give/includes/admin/emails/class-new-offline-donation-email.php
@@ -246,12 +246,19 @@
/**
* Setup email notification.
*
+ * @since 4.18.0 Check the gateway from meta before loading the legacy payment object.
* @since 2.0
* @access public
*
* @param int $payment_id
*/
public function setup_email_notification( $payment_id ) {
+ // Exit if not donation was not with offline donation. Checked from meta first so every
+ // non-offline donation does not pay for building a Give_Payment on insert.
+ if ( 'offline' !== give_get_payment_gateway( $payment_id ) ) {
+ return;
+ }
+
$this->payment = new Give_Payment( $payment_id );
if ( ! $this->payment->ID ) {
@@ -264,11 +271,6 @@
);
}
- // Exit if not donation was not with offline donation.
- if ( 'offline' !== $this->payment->gateway ) {
- return;
- }
-
// Set email data.
$this->setup_email_data();
--- a/give/includes/admin/emails/class-offline-donation-instruction-email.php
+++ b/give/includes/admin/emails/class-offline-donation-instruction-email.php
@@ -212,12 +212,19 @@
/**
* Setup email notification.
*
+ * @since 4.18.0 Check the gateway from meta before loading the legacy payment object.
* @since 2.0
* @access public
*
* @param int $payment_id
*/
public function setup_email_notification( $payment_id ) {
+ // Exit if not donation was not with offline donation. Checked from meta first so every
+ // non-offline donation does not pay for building a Give_Payment on insert.
+ if ( 'offline' !== give_get_payment_gateway( $payment_id ) ) {
+ return;
+ }
+
$this->payment = new Give_Payment( $payment_id );
if ( ! $this->payment->ID ) {
@@ -230,11 +237,6 @@
);
}
- // Exit if not donation was not with offline donation.
- if ( 'offline' !== $this->payment->gateway ) {
- return;
- }
-
// Set email data.
$this->setup_email_data();
--- a/give/includes/class-give-email-access.php
+++ b/give/includes/class-give-email-access.php
@@ -351,6 +351,7 @@
/**
* Is this a valid verify key?
*
+ * @since 4.18.0 Verify keys expire with the same window as access tokens.
* @since 4.16.7 Only accept non-empty string tokens.
* @since 1.0
* @access public
@@ -368,9 +369,13 @@
return false;
}
+ // A verify key expires with the same window as an access token, so a
+ // key generated before that window can no longer be redeemed.
+ $expires = date( 'Y-m-d H:i:s', time() - $this->token_expiration );
+
// See if the verify_key exists.
$row = $wpdb->get_row(
- $wpdb->prepare( "SELECT id, email FROM {$wpdb->donors} WHERE verify_key = %s LIMIT 1", $token )
+ $wpdb->prepare( "SELECT id, email FROM {$wpdb->donors} WHERE verify_key = %s AND verify_throttle >= %s LIMIT 1", $token, $expires )
);
$now = date( 'Y-m-d H:i:s' );
--- a/give/includes/donors/class-give-donor-wall.php
+++ b/give/includes/donors/class-give-donor-wall.php
@@ -381,6 +381,8 @@
/**
* Get donation data.
*
+ * @since 4.18.0 Read meta values as stored instead of unserializing them, and read the donor
+ * comment from the fetched rows instead of a per-donation meta lookup.
* @since 4.16.7.2 Restrict unserialize to prevent object instantiation.
* @since 2.27.0 Change to read comment from donations meta table
* @since 2.3.0
@@ -417,7 +419,7 @@
/* @var stdClass $result */
foreach ( $results as $result ) {
- $temp[ $result->{$donation_id_col} ][ $result->meta_key ] = unserialize( $result->meta_value, [ 'allowed_classes' => false ] );
+ $temp[ $result->{$donation_id_col} ][ $result->meta_key ] = $result->meta_value;
// Set donation date.
if ( empty( $temp[ $result->{$donation_id_col} ]['donation_date'] ) ) {
@@ -436,14 +438,11 @@
]
);
- $temp[$donation_id]['donor_comment'] = give_get_payment_meta(
- $donation_id,
- DonationMetaKeys::COMMENT
- );
+ $temp[ $donation_id ]['donor_comment'] = $donation_data[ DonationMetaKeys::COMMENT ] ?? '';
}
- }
- $results = ! empty( $temp ) ? $temp : [];
+ $results = ! empty( $temp ) ? $temp : [];
+ }
}
return $results;
--- a/give/includes/emails/class-give-email-tags.php
+++ b/give/includes/emails/class-give-email-tags.php
@@ -283,6 +283,7 @@
* @since 1.0
* @since 2.0 $payment_id deprecated.
* @since 2.0 $tag_args added.
+ * @since 4.18.0 Only the {meta_*} tags present in the original content are resolved.
*
* @return string Content with email tags filtered out.
*/
@@ -292,6 +293,16 @@
$tag_args = [ 'payment_id' => $tag_args ];
}
+ // Replace the {meta_*} tags the content started with by placeholders before
+ // any other tag is substituted. Values inserted by tag substitution,
+ // including donor-supplied ones, must not be interpreted as tags, and a
+ // placeholder keeps an original occurrence distinguishable from an injected
+ // one carrying the same syntax.
+ if ( is_array( $tag_args ) ) {
+ list( $content, $meta_tag_placeholders ) = give_protect_meta_email_tags( $content );
+ $tag_args['content_meta_placeholders'] = $meta_tag_placeholders;
+ }
+
$email_tags = Give()->email_tags instanceof Give_Email_Template_Tags
? Give()->email_tags
: new Give_Email_Template_Tags();
@@ -312,6 +323,48 @@
}
/**
+ * Replaces each distinct {meta_*} tag in the content with a unique placeholder.
+ *
+ * The placeholder is generated for the current call only, so the tags the
+ * content started with can be told apart from the same syntax inserted later by
+ * tag substitution. The placeholder contains a dot, which keeps the email tag
+ * engine from treating it as a tag of its own.
+ *
+ * @since 4.18.0
+ *
+ * @param string $content Content to protect.
+ *
+ * @return array{0: string, 1: array<string, string>} Protected content, then a
+ * placeholder => original tag map.
+ */
+function give_protect_meta_email_tags( $content ) {
+ preg_match_all( '/{meta_([A-z0-9-_ ]+)}/s', $content, $matches );
+
+ if ( empty( $matches[0] ) ) {
+ return [ $content, [] ];
+ }
+
+ $placeholder_prefix = '{{' . uniqid( 'givewp_meta_', true ) . '_';
+ $tag_placeholders = [];
+
+ foreach ( array_unique( $matches[0] ) as $index => $meta_tag ) {
+ $tag_placeholders[ $meta_tag ] = "{$placeholder_prefix}{$index}}}";
+ }
+
+ $protected = preg_replace_callback(
+ '/{meta_[A-z0-9-_ ]+}/s',
+ static function ( $tag_match ) use ( $tag_placeholders ) {
+ return isset( $tag_placeholders[ $tag_match[0] ] )
+ ? $tag_placeholders[ $tag_match[0] ]
+ : $tag_match[0];
+ },
+ $content
+ );
+
+ return [ $protected, array_flip( $tag_placeholders ) ];
+}
+
+/**
* Load email tags.
*
* @since 1.0
@@ -1649,6 +1702,7 @@
*
* @since 4.9.0 rename function - PHP 8 compatibility
* @since 2.0.3
+ * @since 4.18.0 Only resolve {meta_*} tags that the content contained before tag substitution.
* @see https://github.com/impress-org/give/issues/2801#issuecomment-365136602
*
* @param $content
@@ -1657,16 +1711,41 @@
* @return mixed
*/
function give_render_metadata_email_tag( $content, $tag_args ) {
- preg_match_all( '/{meta_([A-z0-9-_ ]+)}/s', $content, $matches );
+ $meta_placeholders = isset( $tag_args['content_meta_placeholders'] ) && is_array( $tag_args['content_meta_placeholders'] )
+ ? $tag_args['content_meta_placeholders']
+ : null;
+
+ /**
+ * When the content comes through give_do_email_tags(), the {meta_*} tags it
+ * started with were replaced by placeholders before tag substitution, and
+ * only those placeholders may resolve. A {meta_*} literal still in the
+ * content was inserted by a substituted value and stays literal. Calls made
+ * directly to this function keep the original behavior.
+ */
+ if ( is_array( $meta_placeholders ) ) {
+ if ( empty( $meta_placeholders ) ) {
+ return $content;
+ }
+
+ $matches = [ array_values( $meta_placeholders ) ];
+ $tag_placeholder = array_flip( $meta_placeholders );
+ } else {
+ preg_match_all( '/{meta_([A-z0-9-_ ]+)}/s', $content, $matches );
+ $tag_placeholder = [];
+ }
if ( ! empty( $matches[0] ) ) {
$search = $replace = [];
foreach ( $matches[0] as $index => $meta_tag ) {
+ $original_meta_tag = $meta_tag;
+
if ( in_array( $meta_tag, $search ) ) {
continue;
}
- $search[] = $meta_tag;
+ $search[] = isset( $tag_placeholder[ $original_meta_tag ] )
+ ? $tag_placeholder[ $original_meta_tag ]
+ : $original_meta_tag;
$meta_tag = str_replace( [ '{', 'meta_', '}' ], '', $meta_tag );
$meta_tag_arr = array_map( 'trim', explode( ' ', $meta_tag, 2 ) );
@@ -1722,10 +1801,24 @@
}
}
- $meta_data = Give()->donor_meta->get_meta( $donor_id, $meta_name, true );
-
- if ( empty( $meta_data ) && in_array( $meta_name, array_keys( Give()->donors->get_columns() ) ) ) {
- $meta_data = Give()->donors->get_column_by( $meta_name, 'id', $donor_id );
+ // Donor meta stays available to add-ons, but the email-access
+ // secrets are never rendered, and the donors-table fallback is
+ // restricted to columns that are safe to display.
+ $meta_data = '';
+
+ if ( ! in_array( $meta_name, [ 'token', 'verify_key', 'verify_throttle' ], true ) ) {
+ $meta_data = Give()->donor_meta->get_meta( $donor_id, $meta_name, true );
+
+ if (
+ empty( $meta_data )
+ && in_array(
+ $meta_name,
+ [ 'id', 'user_id', 'name', 'email', 'payment_ids', 'purchase_value', 'purchase_count', 'date_created' ],
+ true
+ )
+ ) {
+ $meta_data = Give()->donors->get_column_by( $meta_name, 'id', $donor_id );
+ }
}
if ( ! isset( $meta_tag_arr[1] ) || ! is_array( $meta_data ) ) {
@@ -1737,7 +1830,7 @@
break;
default:
- $replace[] = end( $search );
+ $replace[] = $original_meta_tag;
}
}
--- a/give/includes/gateways/stripe/includes/class-give-stripe-webhooks.php
+++ b/give/includes/gateways/stripe/includes/class-give-stripe-webhooks.php
@@ -113,7 +113,7 @@
}
status_header(200);
- exit($message);
+ exit(esc_html($message));
}
/**
--- a/give/includes/payments/class-payment-stats.php
+++ b/give/includes/payments/class-payment-stats.php
@@ -28,6 +28,7 @@
/**
* Retrieve sale stats
*
+ * @since 4.18.0 Count donations with one SQL query instead of loading every ID
* @since 1.0
* @access public
*
@@ -65,6 +66,12 @@
$args['give_forms'] = $form_id;
}
+ $count = $this->count_donations_in_sql( $args );
+
+ if ( null !== $count ) {
+ return $count;
+ }
+
/* @var Give_Payments_Query $payments */
$payments = new Give_Payments_Query( $args );
$payments = $payments->get_payments();
@@ -76,6 +83,7 @@
/**
* Retrieve earning stats
*
+ * @since 4.18.0 Sum donation totals with one SQL query instead of loading every ID and formatting each amount
* @since 1.0
* @access public
*
@@ -138,9 +146,14 @@
if ( false === $earnings ) {
$this->timestamp = false;
- $payments = new Give_Payments_Query( $args );
- $payments = $payments->get_payments();
- $earnings = 0;
+ $payments = [];
+ $earnings = $this->sum_earnings_in_sql( $args );
+
+ if ( null === $earnings ) {
+ $payments = new Give_Payments_Query( $args );
+ $payments = $payments->get_payments();
+ $earnings = 0;
+ }
if ( ! empty( $payments ) ) {
$donation_id_col = Give()->payment_meta->get_meta_type() . '_id';
@@ -264,6 +277,200 @@
}
/**
+ * Sum donation totals in one query instead of loading every matching donation ID into PHP
+ * and formatting each amount. Uses the Currency Switcher base amount when a donation has one,
+ * which is what its `give_donation_amount` filter returns for stats.
+ *
+ * Returns null when the query args contain something this method does not translate, or when an
+ * add-on filters `give_donation_amount`, so the caller falls back to the per-donation loop.
+ *
+ * @since 4.18.0
+ *
+ * @param array $args Give_Payments_Query arguments.
+ *
+ * @return float|null
+ */
+ private function sum_earnings_in_sql( array $args ) {
+ global $wpdb;
+
+ if ( $this->has_donation_amount_filter() ) {
+ return null;
+ }
+
+ $where = $this->stats_where_sql( $args );
+
+ if ( null === $where ) {
+ return null;
+ }
+
+ $donation_id_col = Give()->payment_meta->get_meta_type() . '_id';
+
+ $sql = "SELECT SUM( COALESCE( NULLIF( base.meta_value, '' ), total.meta_value ) + 0 )
+ FROM {$wpdb->posts} AS p
+ INNER JOIN {$wpdb->donationmeta} AS total ON total.{$donation_id_col} = p.ID AND total.meta_key = '_give_payment_total'
+ LEFT JOIN {$wpdb->donationmeta} AS base ON base.{$donation_id_col} = p.ID AND base.meta_key = '_give_cs_base_amount'
+ WHERE p.post_type = 'give_payment' {$where}";
+
+ return (float) $wpdb->get_var( $sql );
+ }
+
+ /**
+ * Count matching donations in one query instead of loading every ID into PHP.
+ *
+ * @since 4.18.0
+ *
+ * @param array $args Give_Payments_Query arguments.
+ *
+ * @return int|null
+ */
+ private function count_donations_in_sql( array $args ) {
+ global $wpdb;
+
+ $where = $this->stats_where_sql( $args );
+
+ if ( null === $where ) {
+ return null;
+ }
+
+ return (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->posts} AS p WHERE p.post_type = 'give_payment' {$where}" );
+ }
+
+ /**
+ * Add-ons that change amounts through `give_donation_amount` (Fee Recovery, Currency Switcher) need
+ * the per-donation loop for earnings so their callbacks run. Counts are unaffected and stay in SQL. Core itself always hooks the deprecated filter
+ * mapping there, so that one callback does not count.
+ *
+ * @since 4.18.0
+ *
+ * @return bool
+ */
+ private function has_donation_amount_filter() {
+ global $wp_filter;
+
+ if ( has_filter( 'give_payment_amount' ) ) {
+ return true;
+ }
+
+ foreach ( $wp_filter['give_donation_amount']->callbacks ?? [] as $callbacks ) {
+ foreach ( $callbacks as $callback ) {
+ if ( 'give_deprecated_filter_mapping' !== $callback['function'] ) {
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * Translate the subset of Give_Payments_Query arguments the stats methods build (status, date
+ * range, form, parent, and simple meta equality) into a WHERE fragment. Anything else returns null.
+ *
+ * @since 4.18.0
+ *
+ * @param array $args
+ *
+ * @return string|null
+ */
+ private function stats_where_sql( array $args ) {
+ global $wpdb;
+
+ /**
+ * Allow add-ons that alter stats amounts some other way to keep the per-donation code path.
+ *
+ * @since 4.18.0
+ *
+ * @param bool $aggregate_in_sql
+ * @param array $args
+ */
+ if ( ! apply_filters( 'givewp_payment_stats_aggregate_in_sql', true, $args ) ) {
+ return null;
+ }
+
+ $known = [ 'status', 'post_status', 'start_date', 'end_date', 'fields', 'number', 'output', 'meta_query', 'give_forms' ];
+
+ if ( array_diff( array_keys( $args ), $known ) ) {
+ return null;
+ }
+
+ if ( isset( $args['number'] ) && -1 !== (int) $args['number'] ) {
+ return null;
+ }
+
+ /*
+ * Give_Payments_Query excludes child donations such as renewals by setting post_parent to 0, and
+ * add-ons like Recurring clear that through `give_pre_get_payments`. Give the hook the same query
+ * object it would see on the legacy path so the SQL path keeps the same rows.
+ */
+ $query = new Give_Payments_Query( $args );
+ $query->__set( 'post_parent', 0 );
+ do_action( 'give_pre_get_payments', $query );
+
+ $statuses = (array) ( $args['post_status'] ?? $args['status'] ?? 'publish' );
+ $where = ' AND p.post_status IN (' . implode( ',', array_map( static function ( $status ) use ( $wpdb ) {
+ return $wpdb->prepare( '%s', $status );
+ }, $statuses ) ) . ')';
+
+ if ( isset( $query->args['post_parent'] ) && is_numeric( $query->args['post_parent'] ) ) {
+ $where .= $wpdb->prepare( ' AND p.post_parent = %d', $query->args['post_parent'] );
+ }
+
+ if ( ! empty( $args['start_date'] ) && ! is_wp_error( $args['start_date'] ) ) {
+ $where .= $wpdb->prepare( ' AND p.post_date >= %s', date( 'Y-m-d H:i:s', $args['start_date'] ) );
+ }
+
+ if ( ! empty( $args['end_date'] ) && ! is_wp_error( $args['end_date'] ) ) {
+ $where .= $wpdb->prepare( ' AND p.post_date <= %s', date( 'Y-m-d H:i:s', $args['end_date'] ) );
+ }
+
+ $donation_id_col = Give()->payment_meta->get_meta_type() . '_id';
+ $meta_conditions = [];
+
+ if ( ! empty( $args['give_forms'] ) ) {
+ $meta_conditions[] = [ 'key' => '_give_payment_form_id', 'value' => $args['give_forms'] ];
+ }
+
+ foreach ( (array) ( $args['meta_query'] ?? [] ) as $index => $condition ) {
+ if ( 'relation' === $index ) {
+ if ( 'AND' !== strtoupper( $condition ) ) {
+ return null;
+ }
+ continue;
+ }
+
+ if ( ! is_array( $condition ) || empty( $condition['key'] ) || ! isset( $condition['value'] ) ) {
+ return null;
+ }
+
+ if ( ! in_array( strtoupper( $condition['compare'] ?? '=' ), [ '=', 'IN' ], true ) ) {
+ return null;
+ }
+
+ if ( array_diff( array_keys( $condition ), [ 'key', 'value', 'compare' ] ) ) {
+ return null;
+ }
+
+ $meta_conditions[] = $condition;
+ }
+
+ foreach ( $meta_conditions as $condition ) {
+ $values = array_map( 'strval', (array) $condition['value'] );
+
+ if ( ! $values ) {
+ return null;
+ }
+
+ $placeholders = implode( ',', array_fill( 0, count( $values ), '%s' ) );
+ $where .= $wpdb->prepare(
+ " AND p.ID IN (SELECT {$donation_id_col} FROM {$wpdb->donationmeta} WHERE meta_key = %s AND meta_value IN ({$placeholders}))",
+ array_merge( [ $condition['key'] ], $values )
+ );
+ }
+
+ return $where;
+ }
+
+ /**
* Get the best selling forms
*
* @since 1.0
--- a/give/src/Campaigns/Actions/CacheCampaignData.php
+++ b/give/src/Campaigns/Actions/CacheCampaignData.php
@@ -47,10 +47,28 @@
/**
* Handle campaign cache
+ *
+ * @since 4.18.0 Read the subscriptions cache from the option it is written to; always compute live stats, keep zero rows when a campaign has no donations.
* @since 4.8.0
*/
public function handleCache(int $campaignId): void
{
+ // The cache holds live stats only. The queries follow the site's payment mode, so force
+ // live for the duration of the job in case test mode was switched on before it ran.
+ add_filter('give_is_test_mode', '__return_false', PHP_INT_MAX);
+
+ try {
+ $this->refresh($campaignId);
+ } finally {
+ remove_filter('give_is_test_mode', '__return_false', PHP_INT_MAX);
+ }
+ }
+
+ /**
+ * @since 4.18.0
+ */
+ private function refresh(int $campaignId): void
+ {
$campaign = Campaign::find($campaignId);
if (!$campaign) {
@@ -58,7 +76,7 @@
}
$campaignsData = get_option('give_campaigns_data', []);
- $campaignsSubscriptionData = get_option('give_campaigns_subscription_data', []);
+ $campaignsSubscriptionData = get_option('give_campaigns_subscriptions_data', []);
// Prefill cache structure to ensure keys exist
$campaignsData = array_merge([
@@ -82,21 +100,21 @@
if ($data['campaign_id'] == $campaign->id) {
$isCached = true;
- $campaignsData['amounts'][$i] = $donations->collectIntendedAmounts()[0];
+ $campaignsData['amounts'][$i] = $this->row($donations->collectIntendedAmounts(), $campaign->id, 'sum');
break;
}
}
foreach ($campaignsData['donationsCount'] as $i => $data) {
if ($data['campaign_id'] == $campaign->id) {
- $campaignsData['donationsCount'][$i] = $donations->collectDonations()[0];
+ $campaignsData['donationsCount'][$i] = $this->row($donations->collectDonations(), $campaign->id, 'count');
break;
}
}
foreach ($campaignsData['donorsCount'] as $i => $data) {
if ($data['campaign_id'] == $campaign->id) {
- $campaignsData['donorsCount'][$i] = $donations->collectDonors()[0];
+ $campaignsData['donorsCount'][$i] = $this->row($donations->collectDonors(), $campaign->id, 'count');
break;
}
}
@@ -111,21 +129,21 @@
if ($data['campaign_id'] == $campaign->id) {
$isSubscriptionCached = true;
- $campaignsSubscriptionData['amounts'][$i] = $subscriptions->collectInitialAmounts()[0];
+ $campaignsSubscriptionData['amounts'][$i] = $this->row($subscriptions->collectInitialAmounts(), $campaign->id, 'sum');
break;
}
}
foreach ($campaignsSubscriptionData['donationsCount'] as $i => $data) {
if ($data['campaign_id'] == $campaign->id) {
- $campaignsSubscriptionData['donationsCount'][$i] = $subscriptions->collectDonations()[0];
+ $campaignsSubscriptionData['donationsCount'][$i] = $this->row($subscriptions->collectDonations(), $campaign->id, 'count');
break;
}
}
foreach ($campaignsSubscriptionData['donorsCount'] as $i => $data) {
if ($data['campaign_id'] == $campaign->id) {
- $campaignsSubscriptionData['donorsCount'][$i] = $subscriptions->collectDonors()[0];
+ $campaignsSubscriptionData['donorsCount'][$i] = $this->row($subscriptions->collectDonors(), $campaign->id, 'count');
break;
}
}
@@ -164,7 +182,7 @@
update_option('give_campaigns_subscriptions_data', [
'amounts' => array_merge(
$campaignsSubscriptionData['amounts'] ?? [],
- $subscriptions->collectIntendedAmounts()
+ $subscriptions->collectInitialAmounts()
),
'donationsCount' => array_merge(
$campaignsSubscriptionData['donationsCount'] ?? [],
@@ -177,4 +195,15 @@
]);
}
}
+
+ /**
+ * The aggregate queries return no row for a campaign with no donations. Keep a zero row so the
+ * campaign stays cached instead of turning into a null row and a PHP warning.
+ *
+ * @since 4.18.0
+ */
+ private function row($rows, int $campaignId, string $column): array
+ {
+ return $rows[0] ?? ['campaign_id' => (string)$campaignId, $column => 0];
+ }
}
--- a/give/src/Campaigns/Blocks/Campaign/render.php
+++ b/give/src/Campaigns/Blocks/Campaign/render.php
@@ -15,4 +15,4 @@
}
?>
-<div data-givewp-campaign-block data-attributes=<?= json_encode($attributes) ?>></div>
+<div data-givewp-campaign-block data-attributes="<?= esc_attr(json_encode($attributes)) ?>"></div>
--- a/give/src/Campaigns/Blocks/CampaignGrid/render.php
+++ b/give/src/Campaigns/Blocks/CampaignGrid/render.php
@@ -3,4 +3,4 @@
* @var array $attributes
*/
?>
-<div data-givewp-campaign-grid data-attributes='<?= json_encode($attributes) ?>'></div>
+<div data-givewp-campaign-grid data-attributes="<?= esc_attr(json_encode($attributes)) ?>"></div>
--- a/give/src/Campaigns/Migrations/CacheCampaignsData.php
+++ b/give/src/Campaigns/Migrations/CacheCampaignsData.php
@@ -53,6 +53,7 @@
/**
* @inheritDoc
*
+ * @since 4.18.0 Merge donors into the donors list and subscriptions into the subscriptions option; always compute live stats, the cache holds live stats only.
* @since 4.12.0 add early return if no campaigns found
* @since 4.8.0
*
@@ -60,6 +61,8 @@
*/
public function runBatch($firstId, $lastId)
{
+ add_filter('give_is_test_mode', '__return_false', PHP_INT_MAX);
+
try {
$query = $this->query();
@@ -93,14 +96,14 @@
$donations->collectDonations()
),
'donorsCount' => array_merge(
- $campaignsData['donationsCount'] ?? [],
+ $campaignsData['donorsCount'] ?? [],
$donations->collectDonors()
),
]);
// Set subscriptions data
if (defined('GIVE_RECURRING_VERSION')) {
- $subscriptionsData = get_option('give_campaigns_data', []);
+ $subscriptionsData = get_option('give_campaigns_subscriptions_data', []);
$subscriptions = CampaignsDataQuery::subscriptions($campaignIds);
update_option('give_campaigns_subscriptions_data', [
@@ -120,6 +123,8 @@
}
} catch (DatabaseQueryException $exception) {
throw new DatabaseMigrationException("An error occurred while caching campaign data", 0, $exception);
+ } finally {
+ remove_filter('give_is_test_mode', '__return_false', PHP_INT_MAX);
}
}
--- a/give/src/Campaigns/Migrations/FlushCampaignsDataCache.php
+++ b/give/src/Campaigns/Migrations/FlushCampaignsDataCache.php
@@ -0,0 +1,50 @@
+<?php
+
+namespace GiveCampaignsMigrations;
+
+use GiveFrameworkMigrationsContractsMigration;
+
+/**
+ * Drops the campaign stats cache so it is rebuilt from scratch. Before this migration the
+ * subscriptions cache was written under one option name and read under another, and the
+ * rebuild migration merged donation rows into it, so what is stored cannot be trusted.
+ * The repository repopulates the cache on demand.
+ *
+ * @since 4.18.0
+ */
+class FlushCampaignsDataCache extends Migration
+{
+ /**
+ * @since 4.18.0
+ */
+ public static function id(): string
+ {
+ return 'flush_campaigns_data_cache';
+ }
+
+ /**
+ * @since 4.18.0
+ */
+ public static function title(): string
+ {
+ return 'Flush campaign stats cache';
+ }
+
+ /**
+ * @since 4.18.0
+ */
+ public static function timestamp(): string
+ {
+ return strtotime('2026-09-21 00:00:00');
+ }
+
+ /**
+ * @since 4.18.0
+ */
+ public function run()
+ {
+ delete_option('give_campaigns_data');
+ delete_option('give_campaigns_subscriptions_data');
+ delete_option('give_campaigns_subscription_data');
+ }
+}
--- a/give/src/Campaigns/Models/Campaign.php
+++ b/give/src/Campaigns/Models/Campaign.php
@@ -78,6 +78,7 @@
}
/**
+ * @since 4.18.0 Return each associated form once when its metadata contains duplicate keys.
* @since 4.0.0
*/
public function forms(): ModelQueryBuilder
@@ -88,7 +89,8 @@
->leftJoin('give_campaign_forms', 'campaign_forms')
->on('campaign_forms.form_id', 'id');
})
- ->where('campaign_forms.campaign_id', $this->id);
+ ->where('campaign_forms.campaign_id', $this->id)
+ ->groupBy('forms.ID');
}
/**
--- a/give/src/Campaigns/Repositories/CampaignPageRepository.php
+++ b/give/src/Campaigns/Repositories/CampaignPageRepository.php
@@ -55,6 +55,7 @@
}
/**
+ * @since 4.18.0 Keep the original error as the previous exception when the write fails.
* @since 4.0.0
* @throws Exception
*/
@@ -109,7 +110,7 @@
Log::error('Failed creating a campaign page', [$campaignPage]);
- throw new $exception('Failed creating a campaign page');
+ throw new Exception('Failed creating a campaign page', 0, $exception);
}
DB::query('COMMIT');
@@ -118,6 +119,7 @@
}
/**
+ * @since 4.18.0 Keep the original error as the previous exception when the write fails.
* @since 4.0.0
* @throws Exception
*/
@@ -152,7 +154,7 @@
Log::error('Failed updating a campaign page', [$campaignPage]);
- throw new $exception('Failed updating a campaign page');
+ throw new Exception('Failed updating a campaign page', 0, $exception);
}
DB::query('COMMIT');
@@ -161,6 +163,7 @@
}
/**
+ * @since 4.18.0 Keep the original error as the previous exception when the write fails.
* @since 4.0.0
* @throws Exception
*/
@@ -183,7 +186,7 @@
Log::error('Failed deleting a campaign page', [$campaignPage]);
- throw new $exception('Failed deleting a campaign page');
+ throw new Exception('Failed deleting a campaign page', 0, $exception);
}
DB::query('COMMIT');
--- a/give/src/Campaigns/Repositories/CampaignRepository.php
+++ b/give/src/Campaigns/Repositories/CampaignRepository.php
@@ -78,6 +78,7 @@
}
/**
+ * @since 4.18.0 Keep the original error as the previous exception when the write fails.
* @since 4.0.0
*
* @throws Exception|InvalidArgumentException
@@ -126,7 +127,7 @@
Log::error('Failed creating a campaign', compact('campaign'));
- throw new $exception('Failed creating a campaign');
+ throw new Exception('Failed creating a campaign', 0, $exception);
}
DB::query('COMMIT');
@@ -139,6 +140,7 @@
}
/**
+ * @since 4.18.0 Keep the original error as the previous exception when the write fails.
* @since 4.0.0
*
* @throws Exception|InvalidArgumentException
@@ -178,7 +180,7 @@
Log::error('Failed updating a campaign', compact('campaign'));
- throw new $exception('Failed updating a campaign');
+ throw new Exception('Failed updating a campaign', 0, $exception);
}
DB::query('COMMIT');
@@ -187,6 +189,7 @@
}
/**
+ * @since 4.18.0 Keep the original error as the previous exception when the write fails.
* @since 4.0.0
*
* @throws Exception
@@ -218,7 +221,7 @@
Log::error('Failed creating a campaign form relationship', compact('campaign'));
- throw new $exception('Failed creating a campaign form relationship');
+ throw new Exception('Failed creating a campaign form relationship', 0, $exception);
}
DB::query('COMMIT');
@@ -227,6 +230,7 @@
}
/**
+ * @since 4.18.0 Keep the original error as the previous exception when the write fails.
* @since 4.0.0
*
* @throws Exception
@@ -250,7 +254,7 @@
Log::error('Failed updating the campaign default form', compact('campaign'));
- throw new $exception('Failed updating the campaign default form');
+ throw new Exception('Failed updating the campaign default form', 0, $exception);
}
DB::query('COMMIT');
@@ -259,6 +263,7 @@
}
/**
+ * @since 4.18.0 Keep the original error as the previous exception when the write fails.
* @since 4.0.0
*
* @throws Exception
@@ -279,7 +284,7 @@
Log::error('Failed deleting a campaign', compact('campaign'));
- throw new $exception('Failed deleting a campaign');
+ throw new Exception('Failed deleting a campaign', 0, $exception);
}
DB::query('COMMIT');
@@ -290,6 +295,7 @@
}
/**
+ * @since 4.18.0 Keep the original error as the previous exception when the write fails.
* @since 4.0.0
*
* @throws Exception
@@ -345,7 +351,7 @@
'destinationCampaign' => compact('destinationCampaign'),
]);
- throw new $exception('Failed merging campaigns into destination campaign');
+ throw new Exception('Failed merging campaigns into destination campaign', 0, $exception);
}
DB::query('COMMIT');
--- a/give/src/Campaigns/Repositories/CampaignsDataRepository.php
+++ b/give/src/Campaigns/Repositories/CampaignsDataRepository.php
@@ -40,7 +40,13 @@
private $subscriptionDonorsCount = [];
/**
+ * Cached stats for the given campaigns. Campaigns missing from the cache are queried and added
+ * to it, so a warm cache never hides a campaign that arrived after it was built.
*
+ * The cache holds live-mode stats only. The queries filter by the site's payment mode, and the
+ * options carry no mode, so test mode reads straight from the database and never writes.
+ *
+ * @since 4.18.0 Query and cache campaigns that are missing from the cache; read subscriptions from the option they are written to; bypass the cache in test mode.
* @since 4.8.0 added data caching layer
*
* @param int[] $ids
@@ -50,70 +56,95 @@
public static function campaigns(array $ids): CampaignsDataRepository
{
$self = new self();
- $campaignsData = get_option('give_campaigns_data', []);
- $campaignsSubscriptionData = get_option('give_campaigns_subscription_data', []);
+ $emptyCache = ['amounts' => [], 'donationsCount' => [], 'donorsCount' => []];
+ $useCache = ! give_is_test_mode();
+ $campaignsData = $useCache
+ ? array_merge($emptyCache, (array)get_option('give_campaigns_data', []))
+ : $emptyCache;
+ $campaignsSubscriptionData = $useCache
+ ? array_merge($emptyCache, (array)get_option('give_campaigns_subscriptions_data', []))
+ : $emptyCache;
+
+ $uncachedIds = self::missingIds($campaignsData, $ids);
+
+ if ($uncachedIds) {
+ $donations = CampaignsDataQuery::donations($uncachedIds);
+
+ $campaignsData = [
+ 'amounts' => array_merge($campaignsData['amounts'], self::withZeroRows($donations->collectIntendedAmounts(), $uncachedIds, 'sum')),
+ 'donationsCount' => array_merge($campaignsData['donationsCount'], self::withZeroRows($donations->collectDonations(), $uncachedIds, 'count')),
+ 'donorsCount' => array_merge($campaignsData['donorsCount'], self::withZeroRows($donations->collectDonors(), $uncachedIds, 'count')),
+ ];
- // remove cached campaign ids
- $campaignIds = array_filter($ids, function ($id) use ($campaignsData) {
- foreach ($campaignsData as $row) {
- foreach($row as $campaign) {
- if ($campaign['campaign_id'] == $id) {
- return false;
- }
- }
+ if ($useCache) {
+ update_option('give_campaigns_data', $campaignsData);
}
+ }
- return true;
- });
+ // The subscriptions cache can lag the donations cache, for example when Recurring is activated later
+ $uncachedSubscriptionIds = defined('GIVE_RECURRING_VERSION')
+ ? self::missingIds($campaignsSubscriptionData, $ids)
+ : [];
+
+ if ($uncachedSubscriptionIds) {
+ $subscriptions = CampaignsDataQuery::subscriptions($uncachedSubscriptionIds);
+
+ $campaignsSubscriptionData = [
+ 'amounts' => array_merge($campaignsSubscriptionData['amounts'], self::withZeroRows($subscriptions->collectInitialAmounts(), $uncachedSubscriptionIds, 'sum')),
+ 'donationsCount' => array_merge($campaignsSubscriptionData['donationsCount'], self::withZeroRows($subscriptions->collectDonations(), $uncachedSubscriptionIds, 'count')),
+ 'donorsCount' => array_merge($campaignsSubscriptionData['donorsCount'], self::withZeroRows($subscriptions->collectDonors(), $uncachedSubscriptionIds, 'count')),
+ ];
- if (
- ! empty($campaignsData['donationsCount'])
- || ! empty($campaignsSubscriptionData['donationsCount'])
- ) {
- $self->amounts = $campaignsData['amounts'];
- $self->donationsCount = $campaignsData['donationsCount'];
- $self->donorsCount = $campaignsData['donorsCount'];
-
- if (defined('GIVE_RECURRING_VERSION')) {
- $self->subscriptionAmounts = $campaignsSubscriptionData['amounts'];
- $self->subscriptionDonationsCount = $campaignsSubscriptionData['donationsCount'];
- $self->subscriptionDonorsCount = $campaignsSubscriptionData['donorsCount'];
+ if ($useCache) {
+ update_option('give_campaigns_subscriptions_data', $campaignsSubscriptionData);
}
+ }
- return $self;
+ $self->amounts = $campaignsData['amounts'];
+ $self->donationsCount = $campaignsData['donationsCount'];
+ $self->donorsCount = $campaignsData['donorsCount'];
+
+ if (defined('GIVE_RECURRING_VERSION')) {
+ $self->subscriptionAmounts = $campaignsSubscriptionData['amounts'];
+ $self->subscriptionDonationsCount = $campaignsSubscriptionData['donationsCount'];
+ $self->subscriptionDonorsCount = $campaignsSubscriptionData['donorsCount'];
}
- // Fetch data from db
- $donations = CampaignsDataQuery::donations($campaignIds);
+ return $self;
+ }
+
+ /**
+ * Ids with no row in the given cache.
+ *
+ * @since 4.18.0
+ */
+ private static function missingIds(array $cache, array $ids): array
+ {
+ $cachedIds = array_map('strval', array_column($cache['donationsCount'], 'campaign_id'));
- $self->amounts = $donations->collectIntendedAmounts();
- $self->donationsCount = $donations->collectDonations();
- $self->donorsCount = $donations->collectDonors();
-
- // cache campaigns data
- update_option('give_campaigns_data', [
- 'amounts' => array_merge($campaignsData['amounts'] ?? [], $self->amounts),
- 'donationsCount' => array_merge($campaignsData['donationsCount'] ?? [], $self->donationsCount),
- 'donorsCount' => array_merge($campaignsData['donorsCount'] ?? [], $self->donorsCount),
- ]);
+ return array_values(array_filter($ids, static function ($id) use ($cachedIds) {
+ return ! in_array((string)$id, $cachedIds, true);
+ }));
+ }
- // Set subscriptions data
- if (defined('GIVE_RECURRING_VERSION')) {
- $subscriptions = CampaignsDataQuery::subscriptions($campaignIds);
+ /**
+ * The aggregate queries return no row for a campaign with no donations. Add a zero row for each
+ * such campaign so it counts as cached and is not queried again on every page load.
+ *
+ * @since 4.18.0
+ */
+ private static function withZeroRows($rows, array $ids, string $column): array
+ {
+ $rows = is_array($rows) ? $rows : [];
+ $present = array_map('strval', array_column($rows, 'campaign_id'));
- $self->subscriptionAmounts = $subscriptions->collectInitialAmounts();
- $self->subscriptionDonationsCount = $subscriptions->collectDonations();
- $self->subscriptionDonorsCount = $subscriptions->collectDonors();
-
- // cache campaigns subscriptions data
- update_option('give_campaigns_subscriptions_data', [
- 'amounts' => array_merge($campaignsSubscriptionData['amounts'] ?? [], $self->subscriptionAmounts),
- 'donationsCount' => array_merge($campaignsSubscriptionData['donationsCount'] ?? [], $self->subscriptionDonationsCount),
- 'donorsCount' => array_merge($campaignsSubscriptionData['donorsCount'] ?? [], $self->subscriptionDonorsCount),
- ]);
+ foreach ($ids as $id) {
+ if ( ! in_array((string)$id, $present, true)) {
+ $rows[] = ['campaign_id' => (string)$id, $column => 0];
+ }
}
- return $self;
+ return $rows;
}
/**
--- a/give/src/Campaigns/ServiceProvider.php
+++ b/give/src/Campaigns/ServiceProvider.php
@@ -19,6 +19,7 @@
use GiveCampaignsListTableRoutesDeleteCampaignListTable;
use GiveCampaignsListTableRoutesGetCampaignsListTable;
use GiveCampaignsMigrationsCacheCampaignsData;
+use GiveCampaignsMigrationsFlushCampaignsDataCache;
use GiveCampaignsMigrationsDonationsAddCampaignId as DonationsAddCampaignId;
use GiveCampaignsMigrationsMigrateFormsToCampaignForms;
use GiveCampaignsMigrationsP2PSetCampaignType;
@@ -98,7 +99,8 @@
AssociateDonationsToCampaign::class,
AddIndexes::class,
DonationsAddCampaignId::class,
- CacheCampaignsData::class
+ CacheCampaignsData::class,
+ FlushCampaignsDataCache::class,
]
);
}
--- a/give/src/Campaigns/Shortcodes/CampaignGridShortcode.php
+++ b/give/src/Campaigns/Shortcodes/CampaignGridShortcode.php
@@ -65,6 +65,7 @@
}
/**
+ * @since 4.18.0 Sanitize string attributes and restrict enumerated values.
* @since 4.2.0
*/
private function parseAttributes($atts): array
@@ -82,15 +83,23 @@
], $atts, 'givewp_campaign_grid');
return [
- 'layout' => $atts['layout'],
+ 'layout' => $this->pickAllowed($atts['layout'], ['full', 'double', 'triple'], 'full'),
'showImage' => filter_var($atts['show_image'], FILTER_VALIDATE_BOOLEAN),
'showDescription' => filter_var($atts['show_description'], FILTER_VALIDATE_BOOLEAN),
'showGoal' => filter_var($atts['show_goal'], FILTER_VALIDATE_BOOLEAN),
- 'sortBy' => $atts['sort_by'],
- 'orderBy' => $atts['order_by'],
- 'filterBy' => $atts['filter_by'],
+ 'sortBy' => $this->pickAllowed($atts['sort_by'], ['date', 'amount', 'donations', 'donors'], 'date'),
+ 'orderBy' => $this->pickAllowed($atts['order_by'], ['asc', 'desc'], 'desc'),
+ 'filterBy' => $atts['filter_by'] ? sanitize_text_field($atts['filter_by']) : $atts['filter_by'],
'perPage' => (int)$atts['per_page'],
'showPagination' => filter_var($atts['show_pagination'], FILTER_VALIDATE_BOOLEAN),
];
}
+
+ /**
+ * @since 4.18.0
+ */
+ private function pickAllowed($value, array $allowed, $default): string
+ {
+ return in_array($value, $allowed, true) ? $value : $default;
+ }
}
--- a/give/src/DonationForms/Repositories/DonationFormRepository.php
+++ b/give/src/DonationForms/Repositories/DonationFormRepository.php
@@ -70,6 +70,7 @@
}
/**
+ * @since 4.18.0 Keep the original error as the previous exception when the write fails.
* @since 3.7.0 Add post_excerpt to the list of fields being inserted
* @since 3.0.0
*
@@ -131,7 +132,7 @@
Log::error('Failed creating a donation form', compact('donationForm'));
- throw new $exception('Failed creating a donation form');
+ throw new Exception('Failed creating a donation form', 0, $exception);
}
DB::query('COMMIT');
@@ -148,6 +149,7 @@
}
/**
+ * @since 4.18.0 Keep the original error as the previous exception when the write fails.
* @since 3.7.0 Add post_excerpt to the list of fields being updated
* @since 3.0.0
*
@@ -206,7 +208,7 @@
Log::error('Failed updating a donation form', compact('donationForm'));
- throw new $exception('Failed updating a donation form');
+ throw new Exception('Failed updating a donation form', 0, $exception);
}
DB::query('COMMIT');
@@ -215,6 +217,7 @@
}
/**
+ * @since 4.18.0 Keep the original error as the previous exception when the write fails.
* @since 3.0.0
*
* @throws Exception
@@ -238,7 +241,7 @@
Log::error('Failed deleting a donation form', compact('donationForm'));
- throw new $exception('Failed deleting a donation form');
+ throw new Exception('Failed deleting a donation form', 0, $exception);
}
DB::query('COMMIT');
--- a/give/src/DonationForms/V2/Repositories/DonationFormsRepository.php
+++ b/give/src/DonationForms/V2/Repositories/DonationFormsRepository.php
@@ -30,6 +30,7 @@
}
/**
+ * @since 4.18.0 Alias the posts table so grouped queries can qualify columns (e.g. GROUP BY forms.ID).
* @since 2.24.0
*
* @return ModelQueryBuilder<Donation>
@@ -38,7 +39,7 @@
{
$builder = new ModelQueryBuilder(DonationForm::class);
- return $builder->from('posts')
+ return $builder->from('posts', 'forms')
->select(
['ID', 'id'],
['post_title', 'title'],
--- a/give/src/Donations/Endpoints/ListDonations.php
+++ b/give/src/Donations/Endpoints/ListDonations.php
@@ -2,6 +2,7 @@
namespace GiveDonationsEndpoints;
+use Closure;
use GiveDonationsListTableDonationsListTable;
use GiveDonationsValueObjectsDonationMetaKeys;
use GiveDonationsValueObjectsDonationMode;
@@ -179,6 +180,7 @@
}
/**
+ * @since 4.18.0 Select the page of IDs first, then hydrate, so deep pages do not join every row
* @since 2.24.0 Replace Query Builder with Donations model
* @since 2.21.0
*
@@ -191,26 +193,65 @@
$sortColumns = $this->listTable->getSortColumnById($this->request->get_param('sortColumn') ?: 'id');
$sortDirection = $this->request->get_param('sortDirection') ?: 'desc';
- $query = give()->donations->prepareQuery();
- list($query) = $this->getWhereConditions($query);
+ // Resolve the page of IDs against the posts table with only the meta the filters and sort
+ // need, then hydrate those rows. Paging the fully joined model query scans every row.
+ $idQuery = DB::table('posts')->select(
+ ['ID', 'id'],
+ ['post_date', 'createdAt'],
+ ['post_modified', 'updatedAt'],
+ ['post_status', 'status']
+ );
+ list($idQuery, $dependencies) = $this->getWhereConditions($idQuery);
+ $dependencies = array_merge($dependencies, $this->getSortDependencies($sortColumns));
- foreach ($sortColumns as $sortColumn) {
- $query->orderBy($sortColumn, $sortDirection);
+ if ($dependencies) {
+ $idQuery->attachMeta(
+ 'give_donationmeta',
+ 'ID',
+ 'donation_id',
+ ...DonationMetaKeys::getColumnsForAttachMetaQueryFromArray($dependencies)
+ );
}
- $query->limit($perPage)
- ->offset(($page - 1) * $perPage);
+ foreach ($sortColumns as $sortColumn) {
+ $idQuery->orderBy($sortColumn, $sortDirection);
+ }
- $donations = $query->getAll();
+ $ids = array_column($idQuery->limit($perPage)->offset(($page - 1) * $perPage)->getAll() ?: [], 'id');
- if (!$donations) {
+ if (!$ids) {
return [];
}
- return $donations;
+ $query = give()->donations->prepareQuery()->whereIn('ID', $ids);
+
+ foreach ($sortColumns as $sortColumn) {
+ $query->orderBy($sortColumn, $sortDirection);
+ }
+
+ return $query->getAll() ?: [];
}
/**
+ * Meta keys a sort expression references, so the ID query can attach them.
+ *
+ * @since 4.18.0
+ *
+ * @param string[] $sortColumns
+ *
+ * @return DonationMetaKeys[]
+ */
+ private function getSortDependencies(array $sortColumns): array
+ {
+ $sortSql = implode(' ', $sortColumns);
+
+ return array_values(array_filter(DonationMetaKeys::values(), static function (DonationMetaKeys $key) use ($sortSql) {
+ return strpos($sortSql, $key->getKeyAsCamelCase()) !== false;
+ }));
+ }
+
+ /**
+ * @since 4.18.0 Drop the GROUP BY on mode, which made count() return the size of one mode group
* @since 2.24.0 Replace Query Builder with Donations model
* @since 2.21.0
*
@@ -218,23 +259,52 @@
*/
public function getTotalDonationsCount(): int
{
- $query = DB::table('posts')
- ->where('post_type', 'give_payment')
- ->groupBy('mode');
-
- list($query, $dependencies) = $this->getWhereConditions($query);
-
- $query->attachMeta(
- 'give_donationmeta',
- 'ID',
- 'donation_id',
- ...DonationMetaKeys::getColumnsForAttachMetaQueryFromArray($dependencies)
- );
+ list($query, $dependencies) = $this->getWhereConditions(DB::table('posts'));
+
+ if ($dependencies) {
+ $query->attachMeta(
+ 'give_donationmeta',
+ 'ID',
+ 'donation_id',
+ ...DonationMetaKeys::getColumnsForAttachMetaQueryFromArray($dependencies)
+ );
+ }
return $query->count();
}
/**
+ * @since 4.18.0
+ */
+ private function donationIdsWithNamePrefix(string $value): Closure
+ {
+ return $this->donationIdsWithMetaPrefix([DonationMetaKeys::FIRST_NAME, DonationMetaKeys::LAST_NAME], $value);
+ }
+
+ /**
+ * Subquery for donation IDs whose meta value starts with the search term. A prefix match on
+ * the (meta_key, meta_value) index replaces a leading-wildcard LIKE across joined meta tables,
+ * which had to scan every row for the key.
+ *
+ * @since 4.18.0
+ *
+ * @param string[] $metaKeys
+ */
+ private function donationIdsWithMetaPrefix(array $metaKeys, string $value): Closure
+ {
+ $prefix = DB::esc_like($value) . '%';
+
+ return static function (QueryBuilder $builder) use ($metaKeys, $prefix) {
+ $builder
+ ->select('donation_id')
+ ->from('give_donationmeta')
+ ->whereIn('meta_key', $metaKeys)
+ ->where('meta_value', $prefix, 'LIKE');
+ };
+ }
+
+ /**
+ * @since 4.18.0 Match name and email searches by prefix through indexed subqueries, and filter test mode the same way instead of HAVING
* @since 4.12.0 Updated status filtering to accept multiple comma-separated values
* @since 4.8.0 Added support for subscriptionId parameter to filter donations
* @since 4.6.0 add status status condition to filter donations
@@ -257,11 +327,7 @@
$campaignId = $this->request->get_param('campaignId');
$subscriptionId = $this->request->get_param('subscriptionId');
$status = $this->request->get_param('status');
- $dependencies = [
- DonationMetaKeys::MODE(),
- ];
-
- $hasWhereConditions = $search || $start || $end || $campaignId || $subscriptionId || $donor || $status;
+ $dependencies = [];
$query->where('post_type', 'give_payment');
@@ -276,15 +342,9 @@
if (ctype_digit($search)) {
$query->where('id', $search);
} elseif (strpos($search, '@') !== false) {
- $query
- ->whereLike('give_donationmeta_attach_meta_email.meta_value', $search);
- $dependencies[] = DonationMetaKeys::EMAIL();
+ $query->whereIn('ID', $this->donationIdsWithMetaPrefix([DonationMetaKeys::EMAIL], $search));
} else {
- $query
- ->whereLike('give_donationmeta_attach_meta_firstName.meta_value', $search)
- ->orWhereLike('give_donationmeta_attach_meta_lastName.meta_value', $search);
- $dependencies[] = DonationMetaKeys::FIRST_NAME();
- $dependencies[] = DonationMetaKeys::LAST_NAME();
+ $query->whereIn('ID', $this->donationIdsWithNamePrefix($search));
}
}
@@ -294,11 +354,7 @@
->where('give_donationmeta_attach_meta_donorId.meta_value', $donor);
$dependencies[] = DonationMetaKeys::DONOR_ID();
} else {
- $query
- ->whereLike('give_donationmeta_attach_meta_firstName.meta_value', $donor)
- ->orWhereLike('give_donationmeta_attach_meta_lastName.meta_value', $donor);
- $dependencies[] = DonationMetaKeys::FIRST_NAME();
- $dependencies[] = DonationMetaKeys::LAST_NAME();
+ $query->whereIn('ID', $this->donationIdsWithNamePrefix($donor));
}
}
@@ -322,13 +378,20 @@
$query->where('post_date', $end, '<=');
}
- if ($hasWhereConditions) {
- $query->havingRaw('HAVING COALESCE(give_donationmeta_attach_meta_mode.meta_value, %s) = %s', DonationMode::LIVE, $testMode ? DonationMode::TEST : DonationMode::LIVE);
- } elseif ($testMode) {
- $query->where('give_donationmeta_attach_meta_mode.meta_value', DonationMode::TEST);
+ // Test-mode donations carry a mode meta row; live donations may have none. A subquery on
+ // (meta_key, meta_value) is index-friendly, unlike a LEFT JOIN with an IS NULL OR condition.
+ $testModeDonationIds = static function (QueryBuilder $builder) {
+ $builder
+ ->select('donation_id')
+ ->from('give_donationmeta')
+ ->where('meta_key', DonationMetaKeys::MODE)
+ ->where('meta_value', DonationMode::TEST);
+ };
+
+ if ($testMode) {
+ $query->whereIn('ID', $testModeDonationIds);
} else {
- $query->whereIsNull('give_donationmeta_attach_meta_mode.meta_value')
- ->orWhere('give_donationmeta_attach_meta_mode.meta_value', DonationMode::TEST, '<>');
+ $query->whereNotIn('ID', $testModeDonationIds);
}
return [
--- a/give/src/Donations/Migrations/AddIndexesToDonationMetaTable.php
+++ b/give/src/Donations/Migrations/AddIndexesToDonationMetaTable.php
@@ -0,0 +1,90 @@
+<?php
+
+namespace GiveDonationsMigrations;
+
+use GiveFrameworkDatabaseDB;
+use GiveFrameworkDatabaseExceptionsDatabaseQueryException;
+use GiveFrameworkMigrationsContractsMigration;
+use GiveFrameworkMigrationsExceptionsDatabaseMigrationException;
+
+/**
+ * The donation meta table only indexes donation_id and meta_key on their own. Every model query
+ * joins the table once per meta key, and every filter by value (test mode, campaign, email) has
+ * to scan the whole key. Two composite indexes cover both patterns, and the single-column indexes
+ * they start with become redundant, so they are dropped to keep the table from growing by more
+ * than about a third. This mirrors the WooCommerce HPOS order meta table, which indexes
+ * (meta_key, meta_value) and (order_id, meta_key, meta_value) only.
+ *
+ * @since 4.18.0
+ */
+class AddIndexesToDonationMetaTable extends Migration
+{
+ /**
+ * @inheritdoc
+ */
+ public static function id(): string
+ {
+ return 'add_indexes_to_donation_meta_table';
+ }
+
+ /**
+ * @inheritdoc
+ */
+ public static function title(): string
+ {
+ return 'Add composite indexes to the donation meta table';
+ }
+
+ /**
+ * @inheritdoc
+ */
+ public static function timestamp(): string
+ {
+ return strtotime('2026-09-18 00:00:00');
+ }
+
+ /**
+ * @inheritDoc
+ * @throws DatabaseMigrationException
+ */
+ public function run()
+ {
+ global $wpdb;
+
+ $table = $wpdb->prefix . 'give_donationmeta';
+ $wanted = ['donation_meta_key', 'meta_key_value'];
+
+ try {
+ $existing = array_flip(DB::get_col("SHOW INDEX FROM {$table}", 2));
+
+ // Prefix lengths match WooCommerce HPOS wc_orders_meta. Under utf8mb4 they keep each key part under
+ // the 767-byte InnoDB COMPACT limit and the whole key under the 1000-byte MyISAM limit, so the
+ // ALTER succeeds on tables created by any host GiveWP has ever run on.
+ $clauses = array_diff_key([
+ 'donation_meta_key' => 'ADD INDEX donation_meta_key (donation_id, meta_key(100))',
+ 'meta_key_value' => 'ADD INDEX meta_key_value (meta_key(100), meta_value(82))',
+ ], $existing);
+
+ $clauses += array_intersect_key([
+ 'donation_id' => 'DROP INDEX donation_id',
+ 'meta_key' => 'DROP INDEX meta_key',
+ ], $existing);
+
+ if (!$clauses) {
+ return;
+ }
+
+ DB::query("ALTER TABLE {$table} " . implode(', ', $clauses));
+ } catch (DatabaseQueryException $exception) {
+ // Another request may have built the indexes while this one waited on the table lock.
+ // Only the finished layout counts, so a failed DROP alone still fails the migration.
+ $indexes = DB::get_col("SHOW INDEX FROM {$table}", 2);
+
+ if (!array_diff($wanted, $indexes) && !array_intersect(['donation_id', 'meta_key'], $indexes)) {
+ return;
+ }
+
+ throw new DatabaseMigrationException("An error occurred while adding indexes to the {$table} table", 0, $exception);
+ }
+ }
+}
--- a/give/src/Donations/Repositories/DonationNotesRepository.php
+++ b/give/src/Donations/Repositories/DonationNotesRepository.php
@@ -44,6 +44,7 @@
}
/**
+ * @since 4.18.0 Keep the original error as the previous exception when the write fails.
* @since 2.21.0
*
* @param DonationNote $donationNote
@@ -91,7 +92,7 @@
Log::error('Failed creating a donation note', compact('donationNote'));
- throw new $exception('Failed creating a donation note');
+ throw new Exception('Failed creating a donation note', 0, $exception);
}
DB::query('COMMIT');
@@ -103,6 +104,7 @@
}
/**
+ * @since 4.18.0 Keep the original error as the previous exception when the write fails