| 1 |
<?php |
| 2 |
/** |
| 3 |
* Analytics class helps to connect BSF Analytics. |
| 4 |
* |
| 5 |
* @package SureDonation |
| 6 |
*/ |
| 7 |
|
| 8 |
namespace SureDonation\Inc\Admin; |
| 9 |
|
| 10 |
use SureDonation\Inc\Helper; |
| 11 |
use SureDonation\Inc\Payments\Offline\Offline_Helper; |
| 12 |
use SureDonation\Inc\Payments\Payment_Helper; |
| 13 |
use SureDonation\Inc\Payments\PayPal\PayPal_Helper; |
| 14 |
use SureDonation\Inc\Payments\Stripe\Stripe_Helper; |
| 15 |
use SureDonation\Inc\Privacy\Privacy_Settings; |
| 16 |
use SureDonation\Inc\Traits\Get_Instance; |
| 17 |
|
| 18 |
// Exit if accessed directly. |
| 19 |
if ( ! defined( 'ABSPATH' ) ) { |
| 20 |
exit; |
| 21 |
} |
| 22 |
|
| 23 |
/** |
| 24 |
* Analytics class. |
| 25 |
* |
| 26 |
* @since 1.0.0 |
| 27 |
*/ |
| 28 |
class Analytics { |
| 29 |
use Get_Instance; |
| 30 |
|
| 31 |
/** |
| 32 |
* BSF_Analytics_Events instance for one-time event tracking. |
| 33 |
* |
| 34 |
* @var \BSF_Analytics_Events|null |
| 35 |
* @since 1.0.0 |
| 36 |
*/ |
| 37 |
private static $events = null; |
| 38 |
|
| 39 |
/** |
| 40 |
* Request-cached donation aggregates. |
| 41 |
* |
| 42 |
* @var array<string, int>|null |
| 43 |
* @since 1.0.0 |
| 44 |
*/ |
| 45 |
private static $donation_aggregates = null; |
| 46 |
|
| 47 |
/** |
| 48 |
* Class constructor. |
| 49 |
* |
| 50 |
* @return void |
| 51 |
* @since 1.0.0 |
| 52 |
*/ |
| 53 |
public function __construct() { |
| 54 |
/* |
| 55 |
* Entity registration is deferred to init priority 0 so that add-on |
| 56 |
* plugins (e.g. SureDonation Pro) registering filters such as |
| 57 |
* suredonation_deactivation_survey_data on plugins_loaded are in |
| 58 |
* place before the deactivation survey data is filtered, and the |
| 59 |
* entity is still set before the BSF Analytics loader consumes it on |
| 60 |
* init priority 10. |
| 61 |
*/ |
| 62 |
add_action( 'init', [ $this, 'register_entity' ], 0 ); |
| 63 |
|
| 64 |
add_filter( 'bsf_core_stats', [ $this, 'add_suredonation_analytics_data' ] ); |
| 65 |
|
| 66 |
// Keep analytics sends (and their stat queries) off the frontend. |
| 67 |
add_filter( 'suredonation_tracking_enabled', [ $this, 'restrict_tracking_to_admin' ] ); |
| 68 |
|
| 69 |
// Event tracking hooks. Registered outside is_admin() on purpose — |
| 70 |
// onboarding completion and campaign publishes fire during REST requests. |
| 71 |
add_action( 'suredonation_onboarding_user_details_saved', [ $this, 'track_onboarding_completed' ] ); |
| 72 |
add_action( 'transition_post_status', [ $this, 'track_first_campaign_published' ], 10, 3 ); |
| 73 |
add_action( 'current_screen', [ $this, 'track_first_campaign_editor_opened' ] ); |
| 74 |
add_action( 'suredonation_privacy_data_exported', [ $this, 'track_privacy_data_exported' ] ); |
| 75 |
add_action( 'suredonation_privacy_data_erased', [ $this, 'track_privacy_data_erased' ] ); |
| 76 |
|
| 77 |
// Detect state-based events (daily throttle; dedup prevents repeat |
| 78 |
// tracking). Admin-only so the detection never runs on the frontend. |
| 79 |
if ( is_admin() ) { |
| 80 |
$this->detect_state_events(); |
| 81 |
} |
| 82 |
} |
| 83 |
|
| 84 |
/** |
| 85 |
* Register the SureDonation entity with the BSF Analytics loader. |
| 86 |
* |
| 87 |
* Runs on init priority 0 — after add-on plugins have registered their |
| 88 |
* filters on plugins_loaded, and before the loader's own init callback |
| 89 |
* loads the analytics library. |
| 90 |
* |
| 91 |
* @return void |
| 92 |
* @since 1.0.0 |
| 93 |
*/ |
| 94 |
public function register_entity() { |
| 95 |
if ( ! class_exists( 'BSF_Analytics_Loader' ) ) { |
| 96 |
require_once SUREDONATION_DIR . 'inc/lib/bsf-analytics/class-bsf-analytics-loader.php'; |
| 97 |
} |
| 98 |
|
| 99 |
if ( ! class_exists( 'BSF_Admin_Notices' ) ) { |
| 100 |
require_once SUREDONATION_DIR . 'inc/lib/astra-notices/class-bsf-admin-notices.php'; |
| 101 |
} |
| 102 |
|
| 103 |
/** |
| 104 |
* The loader's get_instance() carries no return type. |
| 105 |
* |
| 106 |
* @var \BSF_Analytics_Loader $suredonation_bsf_analytics |
| 107 |
*/ |
| 108 |
$suredonation_bsf_analytics = \BSF_Analytics_Loader::get_instance(); |
| 109 |
|
| 110 |
$suredonation_bsf_analytics->set_entity( |
| 111 |
[ |
| 112 |
'suredonation' => [ |
| 113 |
'product_name' => 'SureDonation', |
| 114 |
'path' => SUREDONATION_DIR . 'inc/lib/bsf-analytics', |
| 115 |
'author' => 'SureDonation', |
| 116 |
'time_to_display' => '+24 hours', |
| 117 |
'deactivation_survey' => apply_filters( |
| 118 |
'suredonation_deactivation_survey_data', |
| 119 |
[ |
| 120 |
[ |
| 121 |
'id' => 'deactivation-survey-suredonation', |
| 122 |
'popup_logo' => SUREDONATION_URL . 'images/suredonation-icon.svg', |
| 123 |
'plugin_slug' => 'suredonation', |
| 124 |
'popup_title' => __( 'Quick Feedback', 'suredonation' ), |
| 125 |
'support_url' => 'https://suredonation.com/support/', |
| 126 |
'popup_description' => __( 'If you have a moment, please share why you are deactivating SureDonation:', 'suredonation' ), |
| 127 |
'show_on_screens' => [ 'plugins' ], |
| 128 |
'plugin_version' => SUREDONATION_VER, |
| 129 |
], |
| 130 |
] |
| 131 |
), |
| 132 |
'hide_optin_checkbox' => true, |
| 133 |
], |
| 134 |
] |
| 135 |
); |
| 136 |
} |
| 137 |
|
| 138 |
/** |
| 139 |
* Get the shared BSF_Analytics_Events instance. |
| 140 |
* |
| 141 |
* Uses SureDonation's Helper option methods so the event data stays |
| 142 |
* inside the consolidated suredonation_options row. |
| 143 |
* |
| 144 |
* @return \BSF_Analytics_Events|null Events instance, or null when the library is unavailable. |
| 145 |
* @since 1.0.0 |
| 146 |
*/ |
| 147 |
public static function events() { |
| 148 |
if ( null === self::$events ) { |
| 149 |
if ( ! class_exists( 'BSF_Analytics_Events' ) ) { |
| 150 |
$events_file = SUREDONATION_DIR . 'inc/lib/bsf-analytics/class-bsf-analytics-events.php'; |
| 151 |
if ( file_exists( $events_file ) ) { |
| 152 |
require_once $events_file; |
| 153 |
} |
| 154 |
} |
| 155 |
|
| 156 |
if ( ! class_exists( 'BSF_Analytics_Events' ) ) { |
| 157 |
return null; |
| 158 |
} |
| 159 |
|
| 160 |
self::$events = new \BSF_Analytics_Events( |
| 161 |
'suredonation', |
| 162 |
[ |
| 163 |
'get' => [ Helper::class, 'get_suredonation_option' ], |
| 164 |
'update' => [ Helper::class, 'update_suredonation_option' ], |
| 165 |
] |
| 166 |
); |
| 167 |
} |
| 168 |
|
| 169 |
return self::$events; |
| 170 |
} |
| 171 |
|
| 172 |
/** |
| 173 |
* Callback function to add SureDonation specific analytics data. |
| 174 |
* |
| 175 |
* @param array<string, mixed> $stats_data Existing stats data. |
| 176 |
* @return array<string, mixed> |
| 177 |
* @since 1.0.0 |
| 178 |
*/ |
| 179 |
public function add_suredonation_analytics_data( $stats_data ) { |
| 180 |
$aggregates = $this->get_donation_aggregates(); |
| 181 |
$campaign_counts = wp_count_posts( 'suredonation_cmpgn' ); |
| 182 |
$form_counts = wp_count_posts( 'suredonation_form' ); |
| 183 |
|
| 184 |
$bsf_internal_referrer = get_option( 'bsf_product_referers', [] ); |
| 185 |
$internal_referer = is_array( $bsf_internal_referrer ) && ! empty( $bsf_internal_referrer['suredonation'] ) |
| 186 |
? sanitize_text_field( (string) $bsf_internal_referrer['suredonation'] ) |
| 187 |
: 'self'; |
| 188 |
|
| 189 |
$privacy_settings = Privacy_Settings::get_settings(); |
| 190 |
|
| 191 |
$plugin_data = [ |
| 192 |
'free_version' => SUREDONATION_VER, |
| 193 |
'numeric_values' => [ |
| 194 |
'total_campaigns' => absint( $campaign_counts->publish ?? 0 ), |
| 195 |
'total_donation_forms' => absint( $form_counts->publish ?? 0 ), |
| 196 |
'total_donations' => $aggregates['total'], |
| 197 |
'completed_donations' => $aggregates['completed'], |
| 198 |
'recurring_donations' => $aggregates['recurring'], |
| 199 |
'total_donors' => $this->get_total_donors(), |
| 200 |
'posts_with_social_sharing_block' => $this->get_social_sharing_block_count(), |
| 201 |
], |
| 202 |
'boolean_values' => [ |
| 203 |
'stripe_enabled' => Stripe_Helper::is_stripe_connected(), |
| 204 |
'paypal_enabled' => PayPal_Helper::is_paypal_connected(), |
| 205 |
'offline_enabled' => Offline_Helper::is_offline_enabled(), |
| 206 |
// True only when the OttoKit plugin is active AND authenticated, |
| 207 |
// so this implies the plugin is active. |
| 208 |
'ottokit_connected' => Helper::is_suretriggers_ready(), |
| 209 |
'contact_consent_enabled' => ! empty( $privacy_settings['contact_consent_field'] ), |
| 210 |
'privacy_policy_field_enabled' => ! empty( $privacy_settings['privacy_policy_field'] ), |
| 211 |
'terms_field_enabled' => ! empty( $privacy_settings['terms_conditions_field'] ), |
| 212 |
], |
| 213 |
'data_retention_period' => isset( $privacy_settings['minimum_data_retention_period'] ) ? Helper::get_string_value( $privacy_settings['minimum_data_retention_period'] ) : 'none', |
| 214 |
'block_usage' => $this->get_block_usage(), |
| 215 |
'elementor_widget_usage' => $this->get_elementor_widget_usage(), |
| 216 |
'bricks_element_usage' => $this->get_bricks_element_usage(), |
| 217 |
'internal_referer' => $internal_referer, |
| 218 |
]; |
| 219 |
|
| 220 |
// Add KPI tracking data. |
| 221 |
$kpi_data = $this->get_kpi_tracking_data(); |
| 222 |
if ( ! empty( $kpi_data ) ) { |
| 223 |
$plugin_data['kpi_records'] = $kpi_data; |
| 224 |
} |
| 225 |
|
| 226 |
// Flush pending events into payload (only if any exist). |
| 227 |
$events = self::events(); |
| 228 |
if ( null !== $events ) { |
| 229 |
$pending_events = $events->flush_pending(); |
| 230 |
if ( ! empty( $pending_events ) ) { |
| 231 |
$plugin_data['events_record'] = $pending_events; |
| 232 |
} |
| 233 |
} |
| 234 |
|
| 235 |
if ( ! isset( $stats_data['plugin_data'] ) || ! is_array( $stats_data['plugin_data'] ) ) { |
| 236 |
$stats_data['plugin_data'] = []; |
| 237 |
} |
| 238 |
|
| 239 |
$stats_data['plugin_data']['suredonation'] = $plugin_data; |
| 240 |
|
| 241 |
return $stats_data; |
| 242 |
} |
| 243 |
|
| 244 |
/** |
| 245 |
* Keep analytics sends off the frontend. |
| 246 |
* |
| 247 |
* Filter callback for `suredonation_tracking_enabled`. The library |
| 248 |
* evaluates this on every request via `is_tracking_enabled()`; gating on |
| 249 |
* is_admin() means the stats queries never run on frontend page loads. |
| 250 |
* Deliberately NOT narrowed further (e.g. to plugin screens): the library |
| 251 |
* also consults this filter from `register_usage_tracking_setting()` on |
| 252 |
* admin_init, where returning false aborts settings registration for all |
| 253 |
* registered BSF products. |
| 254 |
* |
| 255 |
* @param bool $is_enabled Whether tracking is enabled (opt-in state). |
| 256 |
* @return bool |
| 257 |
* @since 1.0.0 |
| 258 |
*/ |
| 259 |
public function restrict_tracking_to_admin( $is_enabled ) { |
| 260 |
return $is_enabled && is_admin(); |
| 261 |
} |
| 262 |
|
| 263 |
/** |
| 264 |
* Track onboarding completion when lead-capture details are saved. |
| 265 |
* |
| 266 |
* The payload contains PII (name/email) — only the opt-in flag is |
| 267 |
* forwarded to analytics. |
| 268 |
* |
| 269 |
* @param array<string, mixed> $payload Sanitized onboarding payload. |
| 270 |
* @return void |
| 271 |
* @since 1.0.0 |
| 272 |
*/ |
| 273 |
public function track_onboarding_completed( $payload ) { |
| 274 |
$events = self::events(); |
| 275 |
if ( null === $events ) { |
| 276 |
return; |
| 277 |
} |
| 278 |
|
| 279 |
$payload = is_array( $payload ) ? $payload : []; |
| 280 |
|
| 281 |
$events->track( |
| 282 |
'onboarding_completed', |
| 283 |
'', |
| 284 |
[ |
| 285 |
'opted_in' => ! empty( $payload['opted_in'] ) ? 'yes' : 'no', |
| 286 |
] |
| 287 |
); |
| 288 |
} |
| 289 |
|
| 290 |
/** |
| 291 |
* Track first personal-data export that included SureDonation data |
| 292 |
* (adoption event — deduped, sent once). |
| 293 |
* |
| 294 |
* @since 1.2.0 |
| 295 |
* @return void |
| 296 |
*/ |
| 297 |
public function track_privacy_data_exported() { |
| 298 |
$events = self::events(); |
| 299 |
if ( null === $events ) { |
| 300 |
return; |
| 301 |
} |
| 302 |
|
| 303 |
$events->track( 'privacy_data_export_used' ); |
| 304 |
} |
| 305 |
|
| 306 |
/** |
| 307 |
* Track first personal-data erasure processed for SureDonation data |
| 308 |
* (adoption event — deduped, sent once). |
| 309 |
* |
| 310 |
* @since 1.2.0 |
| 311 |
* @param array<string, mixed> $outcome Erasure outcome flags. |
| 312 |
* @return void |
| 313 |
*/ |
| 314 |
public function track_privacy_data_erased( $outcome ) { |
| 315 |
$events = self::events(); |
| 316 |
if ( null === $events ) { |
| 317 |
return; |
| 318 |
} |
| 319 |
|
| 320 |
$outcome = is_array( $outcome ) ? $outcome : []; |
| 321 |
|
| 322 |
$events->track( |
| 323 |
'privacy_data_erasure_used', |
| 324 |
'', |
| 325 |
[ |
| 326 |
'items_removed' => ! empty( $outcome['items_removed'] ) ? 'yes' : 'no', |
| 327 |
'items_retained' => ! empty( $outcome['items_retained'] ) ? 'yes' : 'no', |
| 328 |
'erase_failed' => ! empty( $outcome['erase_failed'] ) ? 'yes' : 'no', |
| 329 |
] |
| 330 |
); |
| 331 |
} |
| 332 |
|
| 333 |
/** |
| 334 |
* Track first time a campaign is published (activation event). |
| 335 |
* |
| 336 |
* @param string $new_status New post status. |
| 337 |
* @param string $old_status Old post status. |
| 338 |
* @param \WP_Post $post Post object. |
| 339 |
* @return void |
| 340 |
* @since 1.0.0 |
| 341 |
*/ |
| 342 |
public function track_first_campaign_published( $new_status, $old_status, $post ) { |
| 343 |
if ( 'publish' !== $new_status || 'publish' === $old_status || ! $post instanceof \WP_Post || 'suredonation_cmpgn' !== $post->post_type ) { |
| 344 |
return; |
| 345 |
} |
| 346 |
|
| 347 |
$events = self::events(); |
| 348 |
if ( null === $events ) { |
| 349 |
return; |
| 350 |
} |
| 351 |
|
| 352 |
$meta = Helper::get_campaign_meta( $post->ID ); |
| 353 |
$goal_amount = isset( $meta['goal_amount'] ) && is_numeric( $meta['goal_amount'] ) ? (float) $meta['goal_amount'] : 0.0; |
| 354 |
$goal_type = isset( $meta['goal_type'] ) && is_scalar( $meta['goal_type'] ) ? sanitize_text_field( (string) $meta['goal_type'] ) : ''; |
| 355 |
|
| 356 |
$events->track( |
| 357 |
'first_campaign_published', |
| 358 |
(string) $post->ID, |
| 359 |
[ |
| 360 |
'goal_type' => $goal_type, |
| 361 |
'has_goal' => $goal_amount > 0 ? '1' : '0', |
| 362 |
] |
| 363 |
); |
| 364 |
} |
| 365 |
|
| 366 |
/** |
| 367 |
* Track first time a user opens the campaign editor. |
| 368 |
* |
| 369 |
* @param \WP_Screen $screen Current screen object. |
| 370 |
* @return void |
| 371 |
* @since 1.0.0 |
| 372 |
*/ |
| 373 |
public function track_first_campaign_editor_opened( $screen ) { |
| 374 |
if ( ! $screen instanceof \WP_Screen || 'suredonation_cmpgn' !== $screen->post_type || 'post' !== $screen->base ) { |
| 375 |
return; |
| 376 |
} |
| 377 |
|
| 378 |
$events = self::events(); |
| 379 |
if ( null === $events ) { |
| 380 |
return; |
| 381 |
} |
| 382 |
|
| 383 |
$events->track( 'first_campaign_editor_opened' ); |
| 384 |
} |
| 385 |
|
| 386 |
/** |
| 387 |
* Get donation aggregates in a single request-cached query. |
| 388 |
* |
| 389 |
* Feeds both the stats numeric values and the state-event detection so |
| 390 |
* the donations table is only ever hit once per request. |
| 391 |
* |
| 392 |
* @return array<string, int> Aggregate counts. |
| 393 |
* @since 1.0.0 |
| 394 |
*/ |
| 395 |
private function get_donation_aggregates() { |
| 396 |
if ( null !== self::$donation_aggregates ) { |
| 397 |
return self::$donation_aggregates; |
| 398 |
} |
| 399 |
|
| 400 |
global $wpdb; |
| 401 |
|
| 402 |
$defaults = [ |
| 403 |
'total' => 0, |
| 404 |
'completed' => 0, |
| 405 |
'recurring' => 0, |
| 406 |
'anonymous_completed' => 0, |
| 407 |
'fees_covered_completed' => 0, |
| 408 |
'refunded' => 0, |
| 409 |
]; |
| 410 |
|
| 411 |
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Single aggregate query on a custom table, request-cached in a static. |
| 412 |
$row = $wpdb->get_row( |
| 413 |
$wpdb->prepare( |
| 414 |
"SELECT COUNT(*) AS total, |
| 415 |
COALESCE(SUM(payment_status = 'completed'),0) AS completed, |
| 416 |
COALESCE(SUM(subscription_id IS NOT NULL AND subscription_id <> ''),0) AS recurring, |
| 417 |
COALESCE(SUM(is_anonymous = 1 AND payment_status = 'completed'),0) AS anonymous_completed, |
| 418 |
COALESCE(SUM(fees_covered > 0 AND payment_status = 'completed'),0) AS fees_covered_completed, |
| 419 |
COALESCE(SUM(payment_status IN ('refunded','partially_refunded')),0) AS refunded |
| 420 |
FROM %i", |
| 421 |
$wpdb->prefix . 'suredonation_donations' |
| 422 |
), |
| 423 |
ARRAY_A |
| 424 |
); |
| 425 |
|
| 426 |
self::$donation_aggregates = is_array( $row ) |
| 427 |
? array_map( 'absint', array_merge( $defaults, $row ) ) |
| 428 |
: $defaults; |
| 429 |
|
| 430 |
return self::$donation_aggregates; |
| 431 |
} |
| 432 |
|
| 433 |
/** |
| 434 |
* Get the total number of donors. |
| 435 |
* |
| 436 |
* @return int |
| 437 |
* @since 1.0.0 |
| 438 |
*/ |
| 439 |
private function get_total_donors() { |
| 440 |
global $wpdb; |
| 441 |
|
| 442 |
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Single COUNT query on a custom table, runs only at analytics send time. |
| 443 |
$count = $wpdb->get_var( |
| 444 |
$wpdb->prepare( |
| 445 |
'SELECT COUNT(*) FROM %i', |
| 446 |
$wpdb->prefix . 'suredonation_donors' |
| 447 |
) |
| 448 |
); |
| 449 |
|
| 450 |
return absint( $count ); |
| 451 |
} |
| 452 |
|
| 453 |
/** |
| 454 |
* How many published posts use each SureDonation campaign/donation block. |
| 455 |
* |
| 456 |
* A privacy-preserving usage count (no content leaves the site) so we can see |
| 457 |
* which blocks are actually adopted. One conditional-SUM query (a single table |
| 458 |
* scan), run only at analytics send time. Elementor/Bricks placements are not |
| 459 |
* counted here (they store their config outside the block grammar) — see |
| 460 |
* get_elementor_widget_usage(). |
| 461 |
* |
| 462 |
* @return array<string, int> Block key => number of published posts using it. |
| 463 |
* @since 1.2.0 |
| 464 |
*/ |
| 465 |
private function get_block_usage() { |
| 466 |
global $wpdb; |
| 467 |
|
| 468 |
$blocks = [ |
| 469 |
'campaign_goal' => 'suredonation/campaign-goal', |
| 470 |
'campaign_stats' => 'suredonation/campaign-stats', |
| 471 |
'campaign_donations' => 'suredonation/campaign-donations', |
| 472 |
'campaign_donors' => 'suredonation/campaign-donors', |
| 473 |
'campaign_donate_button' => 'suredonation/campaign-donate-button', |
| 474 |
'campaign_social_sharing' => 'suredonation/campaign-social-sharing', |
| 475 |
'donation_form' => 'suredonation/donation-form', |
| 476 |
]; |
| 477 |
|
| 478 |
// prepare() fills placeholders in SQL order: the SELECT-list %s LIKEs |
| 479 |
// first, then the FROM %i, then the status %s. |
| 480 |
$selects = []; |
| 481 |
$values = []; |
| 482 |
foreach ( array_keys( $blocks ) as $key ) { |
| 483 |
$selects[] = "SUM(post_content LIKE %s) AS {$key}"; |
| 484 |
// The space after the block name is the delimiter the serializer always |
| 485 |
// emits (before attrs JSON, "-->" or "/-->"), so a future |
| 486 |
// "campaign-goal-x" block can't prefix-match campaign-goal. |
| 487 |
$values[] = '%' . $wpdb->esc_like( '<!-- wp:' . $blocks[ $key ] . ' ' ) . '%'; |
| 488 |
} |
| 489 |
$values[] = $wpdb->posts; |
| 490 |
$values[] = 'publish'; |
| 491 |
|
| 492 |
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared -- Single aggregate scan at analytics send time; SELECT list is built from hardcoded keys and %s placeholders only. |
| 493 |
$row = $wpdb->get_row( |
| 494 |
$wpdb->prepare( 'SELECT ' . implode( ', ', $selects ) . ' FROM %i WHERE post_status = %s', $values ), // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber -- placeholders are built alongside $values; prepare() accepts the array form. |
| 495 |
ARRAY_A |
| 496 |
); |
| 497 |
|
| 498 |
$usage = []; |
| 499 |
foreach ( array_keys( $blocks ) as $key ) { |
| 500 |
$usage[ $key ] = absint( is_array( $row ) ? ( $row[ $key ] ?? 0 ) : 0 ); |
| 501 |
} |
| 502 |
|
| 503 |
return $usage; |
| 504 |
} |
| 505 |
|
| 506 |
/** |
| 507 |
* How many published posts use each SureDonation Elementor widget. |
| 508 |
* |
| 509 |
* The Elementor counterpart of get_block_usage(): widgets live in the |
| 510 |
* _elementor_data postmeta (JSON with a quoted "widgetType"), not in the |
| 511 |
* block grammar. Same privacy-preserving single-scan shape, run only at |
| 512 |
* analytics send time. |
| 513 |
* |
| 514 |
* @return array<string, int> Widget key => number of published posts using it. |
| 515 |
* @since 1.2.0 |
| 516 |
*/ |
| 517 |
private function get_elementor_widget_usage() { |
| 518 |
global $wpdb; |
| 519 |
|
| 520 |
$widgets = [ |
| 521 |
'campaign_goal' => 'suredonation-campaign-goal', |
| 522 |
'campaign_stats' => 'suredonation-campaign-stats', |
| 523 |
'campaign_donations' => 'suredonation-campaign-donations', |
| 524 |
'campaign_donors' => 'suredonation-campaign-donors', |
| 525 |
'campaign_donate_button' => 'suredonation-campaign-donate-button', |
| 526 |
'campaign_social_sharing' => 'suredonation-campaign-social-sharing', |
| 527 |
'donation_form' => 'suredonation-donation-form', |
| 528 |
]; |
| 529 |
|
| 530 |
// prepare() fills placeholders in SQL order: the SELECT-list %s LIKEs |
| 531 |
// first, then the two FROM/JOIN %i tables, then meta_key and status. |
| 532 |
$selects = []; |
| 533 |
$values = []; |
| 534 |
foreach ( array_keys( $widgets ) as $key ) { |
| 535 |
$selects[] = "SUM(pm.meta_value LIKE %s) AS {$key}"; |
| 536 |
// Quoted as stored in the _elementor_data JSON ("widgetType":"…"), |
| 537 |
// which bounds the match on both sides. |
| 538 |
$values[] = '%' . $wpdb->esc_like( '"' . $widgets[ $key ] . '"' ) . '%'; |
| 539 |
} |
| 540 |
$values[] = $wpdb->postmeta; |
| 541 |
$values[] = $wpdb->posts; |
| 542 |
$values[] = '_elementor_data'; |
| 543 |
$values[] = 'publish'; |
| 544 |
|
| 545 |
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared -- Single aggregate scan at analytics send time; SELECT list is built from hardcoded keys and %s placeholders only. |
| 546 |
$row = $wpdb->get_row( |
| 547 |
$wpdb->prepare( 'SELECT ' . implode( ', ', $selects ) . ' FROM %i AS pm INNER JOIN %i AS p ON p.ID = pm.post_id WHERE pm.meta_key = %s AND p.post_status = %s', $values ), // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber -- placeholders are built alongside $values; prepare() accepts the array form. |
| 548 |
ARRAY_A |
| 549 |
); |
| 550 |
|
| 551 |
$usage = []; |
| 552 |
foreach ( array_keys( $widgets ) as $key ) { |
| 553 |
$usage[ $key ] = absint( is_array( $row ) ? ( $row[ $key ] ?? 0 ) : 0 ); |
| 554 |
} |
| 555 |
|
| 556 |
return $usage; |
| 557 |
} |
| 558 |
|
| 559 |
/** |
| 560 |
* How many published posts use each SureDonation Bricks element. |
| 561 |
* |
| 562 |
* A privacy-preserving usage count (no content leaves the site) so we can see |
| 563 |
* which Bricks elements are actually adopted — the Bricks counterpart of the |
| 564 |
* Gutenberg block_usage stat. Bricks stores builder data as serialized element |
| 565 |
* arrays in postmeta, so each element name is matched inside its quotes. |
| 566 |
* One conditional-SUM query (a single scan), run only at analytics send time. |
| 567 |
* |
| 568 |
* @return array<string, int> Element key => number of published posts using it. |
| 569 |
* @since 1.2.0 |
| 570 |
*/ |
| 571 |
private function get_bricks_element_usage() { |
| 572 |
global $wpdb; |
| 573 |
|
| 574 |
$elements = [ |
| 575 |
'campaign_goal' => 'suredonation-campaign-goal', |
| 576 |
'campaign_stats' => 'suredonation-campaign-stats', |
| 577 |
'campaign_donations' => 'suredonation-campaign-donations', |
| 578 |
'campaign_donors' => 'suredonation-campaign-donors', |
| 579 |
'campaign_donate_button' => 'suredonation-campaign-donate-button', |
| 580 |
'campaign_social_sharing' => 'suredonation-campaign-social-sharing', |
| 581 |
'donation_form' => 'suredonation-donation-form', |
| 582 |
]; |
| 583 |
|
| 584 |
// prepare() fills placeholders in SQL order: the SELECT-list %s LIKEs |
| 585 |
// first, then the two FROM/JOIN %i tables, then meta keys and status. |
| 586 |
$selects = []; |
| 587 |
$values = []; |
| 588 |
foreach ( array_keys( $elements ) as $key ) { |
| 589 |
$selects[] = "SUM(pm.meta_value LIKE %s) AS {$key}"; |
| 590 |
// Quoted as stored in the serialized Bricks element data, which |
| 591 |
// bounds the match on both sides. |
| 592 |
$values[] = '%' . $wpdb->esc_like( '"' . $elements[ $key ] . '"' ) . '%'; |
| 593 |
} |
| 594 |
$values[] = $wpdb->postmeta; |
| 595 |
$values[] = $wpdb->posts; |
| 596 |
$values[] = '_bricks_page_content_2'; |
| 597 |
$values[] = '_bricks_page_header_2'; |
| 598 |
$values[] = '_bricks_page_footer_2'; |
| 599 |
$values[] = 'publish'; |
| 600 |
|
| 601 |
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared -- Single aggregate scan at analytics send time; SELECT list is built from hardcoded keys and %s placeholders only. |
| 602 |
$row = $wpdb->get_row( |
| 603 |
$wpdb->prepare( 'SELECT ' . implode( ', ', $selects ) . ' FROM %i AS pm INNER JOIN %i AS p ON p.ID = pm.post_id WHERE pm.meta_key IN ( %s, %s, %s ) AND p.post_status = %s', $values ), // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber -- placeholders are built alongside $values; prepare() accepts the array form. |
| 604 |
ARRAY_A |
| 605 |
); |
| 606 |
|
| 607 |
$usage = []; |
| 608 |
foreach ( array_keys( $elements ) as $key ) { |
| 609 |
$usage[ $key ] = absint( is_array( $row ) ? ( $row[ $key ] ?? 0 ) : 0 ); |
| 610 |
} |
| 611 |
|
| 612 |
return $usage; |
| 613 |
} |
| 614 |
|
| 615 |
/** |
| 616 |
* How many published posts use the Campaign Social Sharing block. |
| 617 |
* |
| 618 |
* A privacy-preserving adoption count (no content leaves the site), run only |
| 619 |
* at analytics send time. The trailing space is the delimiter the block |
| 620 |
* serializer always emits after the block name, so a future |
| 621 |
* "campaign-social-sharing-x" block can't prefix-match. |
| 622 |
* |
| 623 |
* @return int Number of published posts containing the block. |
| 624 |
* @since 1.2.0 |
| 625 |
*/ |
| 626 |
private function get_social_sharing_block_count() { |
| 627 |
global $wpdb; |
| 628 |
|
| 629 |
$like = '%' . $wpdb->esc_like( '<!-- wp:suredonation/campaign-social-sharing ' ) . '%'; |
| 630 |
|
| 631 |
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Single aggregate COUNT run only at analytics send time. |
| 632 |
$count = $wpdb->get_var( |
| 633 |
$wpdb->prepare( |
| 634 |
'SELECT COUNT(ID) FROM %i WHERE post_status = %s AND post_content LIKE %s', |
| 635 |
$wpdb->posts, |
| 636 |
'publish', |
| 637 |
$like |
| 638 |
) |
| 639 |
); |
| 640 |
|
| 641 |
return absint( $count ); |
| 642 |
} |
| 643 |
|
| 644 |
/** |
| 645 |
* Get KPI tracking data for the last 2 full days (excluding today). |
| 646 |
* |
| 647 |
* Single grouped query; raw revenue never enters the payload — only |
| 648 |
* the donation count and a coarse revenue tier per day. |
| 649 |
* |
| 650 |
* Date boundaries use GMT because `created_at` is written with |
| 651 |
* current_time( 'mysql', true ). |
| 652 |
* |
| 653 |
* @return array<string, array<string, array<string, mixed>>> KPI data keyed by Y-m-d date. |
| 654 |
* @since 1.0.0 |
| 655 |
*/ |
| 656 |
private function get_kpi_tracking_data() { |
| 657 |
global $wpdb; |
| 658 |
|
| 659 |
$start = gmdate( 'Y-m-d', strtotime( '-2 days' ) ) . ' 00:00:00'; |
| 660 |
$end = gmdate( 'Y-m-d' ) . ' 00:00:00'; |
| 661 |
|
| 662 |
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Single grouped query on a custom table, runs only at analytics send time. |
| 663 |
$rows = $wpdb->get_results( |
| 664 |
$wpdb->prepare( |
| 665 |
"SELECT DATE(created_at) AS day, COUNT(*) AS donations, COALESCE(SUM(amount),0) AS revenue |
| 666 |
FROM %i |
| 667 |
WHERE payment_status = 'completed' AND created_at >= %s AND created_at < %s |
| 668 |
GROUP BY day", |
| 669 |
$wpdb->prefix . 'suredonation_donations', |
| 670 |
$start, |
| 671 |
$end |
| 672 |
), |
| 673 |
ARRAY_A |
| 674 |
); |
| 675 |
|
| 676 |
$kpi_data = []; |
| 677 |
|
| 678 |
// Seed both days so dates with zero donations are still reported. |
| 679 |
for ( $i = 2; $i >= 1; $i-- ) { |
| 680 |
$day = gmdate( 'Y-m-d', strtotime( '-' . $i . ' days' ) ); |
| 681 |
|
| 682 |
$kpi_data[ $day ] = [ |
| 683 |
'numeric_values' => [ |
| 684 |
'donations' => 0, |
| 685 |
], |
| 686 |
'string_values' => [ |
| 687 |
'donation_revenue_tier' => '0', |
| 688 |
], |
| 689 |
]; |
| 690 |
} |
| 691 |
|
| 692 |
$rows = is_array( $rows ) ? $rows : []; |
| 693 |
|
| 694 |
foreach ( $rows as $row ) { |
| 695 |
if ( empty( $row['day'] ) || ! isset( $kpi_data[ $row['day'] ] ) ) { |
| 696 |
continue; |
| 697 |
} |
| 698 |
|
| 699 |
$kpi_data[ $row['day'] ] = [ |
| 700 |
'numeric_values' => [ |
| 701 |
'donations' => absint( $row['donations'] ?? 0 ), |
| 702 |
], |
| 703 |
'string_values' => [ |
| 704 |
'donation_revenue_tier' => $this->get_revenue_tier( (float) ( $row['revenue'] ?? 0 ) ), |
| 705 |
], |
| 706 |
]; |
| 707 |
} |
| 708 |
|
| 709 |
return $kpi_data; |
| 710 |
} |
| 711 |
|
| 712 |
/** |
| 713 |
* Map a raw daily revenue amount to a coarse reporting tier. |
| 714 |
* |
| 715 |
* @param float $revenue Daily revenue. |
| 716 |
* @return string Revenue tier label. |
| 717 |
* @since 1.0.0 |
| 718 |
*/ |
| 719 |
private function get_revenue_tier( float $revenue ): string { |
| 720 |
if ( $revenue <= 0 ) { |
| 721 |
return '0'; |
| 722 |
} |
| 723 |
if ( $revenue < 100 ) { |
| 724 |
return '1-100'; |
| 725 |
} |
| 726 |
if ( $revenue < 500 ) { |
| 727 |
return '100-500'; |
| 728 |
} |
| 729 |
if ( $revenue < 1000 ) { |
| 730 |
return '500-1000'; |
| 731 |
} |
| 732 |
if ( $revenue < 5000 ) { |
| 733 |
return '1000-5000'; |
| 734 |
} |
| 735 |
return '5000+'; |
| 736 |
} |
| 737 |
|
| 738 |
/** |
| 739 |
* Detect state-based events that can't use direct hooks. |
| 740 |
* |
| 741 |
* Throttled by a daily transient; uses the request-cached donation |
| 742 |
* aggregates plus option reads only — no extra queries. The events |
| 743 |
* tracker dedups, so repeated calls are safe. |
| 744 |
* |
| 745 |
* @return void |
| 746 |
* @since 1.0.0 |
| 747 |
*/ |
| 748 |
private function detect_state_events() { |
| 749 |
if ( get_transient( 'suredonation_state_events_checked' ) ) { |
| 750 |
return; |
| 751 |
} |
| 752 |
|
| 753 |
$events = self::events(); |
| 754 |
if ( null === $events ) { |
| 755 |
return; // Tracker unavailable — retry on next admin load. |
| 756 |
} |
| 757 |
|
| 758 |
// Set only after the tracker is confirmed available. |
| 759 |
set_transient( 'suredonation_state_events_checked', true, DAY_IN_SECONDS ); |
| 760 |
|
| 761 |
$aggregates = $this->get_donation_aggregates(); |
| 762 |
$mode = Payment_Helper::get_payment_mode(); |
| 763 |
|
| 764 |
// plugin_activated: dedup ensures this fires only once. |
| 765 |
$bsf_referrers = get_option( 'bsf_product_referers', [] ); |
| 766 |
$source = is_array( $bsf_referrers ) && ! empty( $bsf_referrers['suredonation'] ) |
| 767 |
? sanitize_text_field( (string) $bsf_referrers['suredonation'] ) |
| 768 |
: 'self'; |
| 769 |
$events->track( 'plugin_activated', SUREDONATION_VER, [ 'source' => $source ] ); |
| 770 |
|
| 771 |
// plugin_updated: re-track on every version change. |
| 772 |
$tracked_version = get_option( 'suredonation_tracked_version', '' ); |
| 773 |
if ( SUREDONATION_VER !== $tracked_version ) { |
| 774 |
if ( ! empty( $tracked_version ) && is_string( $tracked_version ) ) { |
| 775 |
$events->flush_pushed( [ 'plugin_updated' ] ); |
| 776 |
$events->track( 'plugin_updated', SUREDONATION_VER, [ 'from_version' => $tracked_version ] ); |
| 777 |
} |
| 778 |
update_option( 'suredonation_tracked_version', SUREDONATION_VER, false ); |
| 779 |
} |
| 780 |
|
| 781 |
// stripe_connected: detect connection state. |
| 782 |
if ( Stripe_Helper::is_stripe_connected() ) { |
| 783 |
$events->track( 'stripe_connected', $mode ); |
| 784 |
} |
| 785 |
|
| 786 |
// paypal_connected: detect connection state. |
| 787 |
if ( PayPal_Helper::is_paypal_connected() ) { |
| 788 |
$events->track( 'paypal_connected', $mode ); |
| 789 |
} |
| 790 |
|
| 791 |
// payment_mode_live: site switched to live payments. |
| 792 |
if ( 'live' === $mode ) { |
| 793 |
$events->track( 'payment_mode_live' ); |
| 794 |
} |
| 795 |
|
| 796 |
// first_donation_received: time-to-value milestone. |
| 797 |
if ( $aggregates['completed'] > 0 ) { |
| 798 |
$install_time_raw = get_site_option( 'suredonation_usage_installed_time', 0 ); |
| 799 |
$install_time = is_numeric( $install_time_raw ) ? (int) $install_time_raw : 0; |
| 800 |
$days_since_install = $install_time > 0 ? (int) floor( ( time() - $install_time ) / DAY_IN_SECONDS ) : 0; |
| 801 |
|
| 802 |
$events->track( |
| 803 |
'first_donation_received', |
| 804 |
Payment_Helper::get_currency(), |
| 805 |
[ |
| 806 |
'days_since_install' => (string) $days_since_install, |
| 807 |
'payment_mode' => $mode, |
| 808 |
] |
| 809 |
); |
| 810 |
} |
| 811 |
|
| 812 |
// anonymous_donation_submitted: at least one completed anonymous donation. |
| 813 |
if ( $aggregates['anonymous_completed'] > 0 ) { |
| 814 |
$events->track( 'anonymous_donation_submitted' ); |
| 815 |
} |
| 816 |
|
| 817 |
// cover_fees_used: at least one completed donation covered fees. |
| 818 |
if ( $aggregates['fees_covered_completed'] > 0 ) { |
| 819 |
$events->track( 'cover_fees_used' ); |
| 820 |
} |
| 821 |
|
| 822 |
// first_refund_processed: at least one (partially) refunded donation. |
| 823 |
if ( $aggregates['refunded'] > 0 ) { |
| 824 |
$events->track( 'first_refund_processed' ); |
| 825 |
} |
| 826 |
|
| 827 |
// webhook_configured: a Stripe webhook secret is stored for the current mode. |
| 828 |
if ( '' !== Stripe_Helper::get_webhook_secret() ) { |
| 829 |
$events->track( 'webhook_configured', $mode ); |
| 830 |
} |
| 831 |
} |
| 832 |
} |
| 833 |
|