| 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\Campaign_Templates\Campaign_Templates; |
| 11 |
use SureDonation\Inc\Campaigns\Campaign_Cpt; |
| 12 |
use SureDonation\Inc\Helper; |
| 13 |
use SureDonation\Inc\Payments\Offline\Offline_Helper; |
| 14 |
use SureDonation\Inc\Payments\Payment_Helper; |
| 15 |
use SureDonation\Inc\Payments\PayPal\PayPal_Helper; |
| 16 |
use SureDonation\Inc\Payments\Stripe\Stripe_Helper; |
| 17 |
use SureDonation\Inc\Privacy\Privacy_Settings; |
| 18 |
use SureDonation\Inc\Traits\Get_Instance; |
| 19 |
|
| 20 |
// Exit if accessed directly. |
| 21 |
if ( ! defined( 'ABSPATH' ) ) { |
| 22 |
exit; |
| 23 |
} |
| 24 |
|
| 25 |
/** |
| 26 |
* Analytics class. |
| 27 |
* |
| 28 |
* @since 1.0.0 |
| 29 |
*/ |
| 30 |
class Analytics { |
| 31 |
use Get_Instance; |
| 32 |
|
| 33 |
/** |
| 34 |
* Allowlist of React admin-notice / UI analytics events. |
| 35 |
* |
| 36 |
* Single source of truth for the track-notice-event REST endpoint: the notice |
| 37 |
* registrations (Admin::register_react_notices) and the dashboard Quick Access |
| 38 |
* item set an event to one of these values, and handle_track_notice_event() |
| 39 |
* only records events present here. Add a new event here (and reference it on |
| 40 |
* the notice/item) to track it end-to-end. |
| 41 |
* |
| 42 |
* @var array<string, string> |
| 43 |
* @since 1.3.0 |
| 44 |
*/ |
| 45 |
public const TRACKED_EVENTS = [ |
| 46 |
'configure_gateway' => 'configure_gateway_notice_react_cta', |
| 47 |
'webhook' => 'webhook_notice_react_cta', |
| 48 |
'test_mode' => 'test_mode_notice_react_cta', |
| 49 |
'quick_access' => 'quick_access_configure_gateway_react_cta', |
| 50 |
]; |
| 51 |
|
| 52 |
/** |
| 53 |
* BSF_Analytics_Events instance for one-time event tracking. |
| 54 |
* |
| 55 |
* @var \BSF_Analytics_Events|null |
| 56 |
* @since 1.0.0 |
| 57 |
*/ |
| 58 |
private static $events = null; |
| 59 |
|
| 60 |
/** |
| 61 |
* Request-cached donation aggregates. |
| 62 |
* |
| 63 |
* @var array<string, int>|null |
| 64 |
* @since 1.0.0 |
| 65 |
*/ |
| 66 |
private static $donation_aggregates = null; |
| 67 |
|
| 68 |
/** |
| 69 |
* Class constructor. |
| 70 |
* |
| 71 |
* @return void |
| 72 |
* @since 1.0.0 |
| 73 |
*/ |
| 74 |
public function __construct() { |
| 75 |
/* |
| 76 |
* Entity registration is deferred to init priority 0 so that add-on |
| 77 |
* plugins (e.g. SureDonation Pro) registering filters such as |
| 78 |
* suredonation_deactivation_survey_data on plugins_loaded are in |
| 79 |
* place before the deactivation survey data is filtered, and the |
| 80 |
* entity is still set before the BSF Analytics loader consumes it on |
| 81 |
* init priority 10. |
| 82 |
*/ |
| 83 |
add_action( 'init', [ $this, 'register_entity' ], 0 ); |
| 84 |
|
| 85 |
// REST route the React admin app calls to record notice/UI clicks. |
| 86 |
add_action( 'rest_api_init', [ $this, 'register_routes' ] ); |
| 87 |
|
| 88 |
add_filter( 'bsf_core_stats', [ $this, 'add_suredonation_analytics_data' ] ); |
| 89 |
|
| 90 |
// Keep analytics sends (and their stat queries) off the frontend. |
| 91 |
add_filter( 'suredonation_tracking_enabled', [ $this, 'restrict_tracking_to_admin' ] ); |
| 92 |
|
| 93 |
// Event tracking hooks. Registered outside is_admin() on purpose — |
| 94 |
// onboarding completion and campaign publishes fire during REST requests. |
| 95 |
add_action( 'suredonation_onboarding_user_details_saved', [ $this, 'track_onboarding_completed' ] ); |
| 96 |
add_action( 'suredonation_campaign_tour_shown', [ $this, 'track_campaign_tour_shown' ] ); |
| 97 |
add_action( 'suredonation_campaign_tour_outcome', [ $this, 'track_campaign_tour_outcome' ], 10, 2 ); |
| 98 |
add_action( 'suredonation_campaign_template_picker_opened', [ $this, 'track_campaign_template_picker_opened' ] ); |
| 99 |
add_action( 'suredonation_campaign_created_from_template', [ $this, 'track_campaign_created_from_template' ] ); |
| 100 |
add_action( 'transition_post_status', [ $this, 'track_first_campaign_published' ], 10, 3 ); |
| 101 |
add_action( 'current_screen', [ $this, 'track_first_campaign_editor_opened' ] ); |
| 102 |
add_action( 'suredonation_privacy_data_exported', [ $this, 'track_privacy_data_exported' ] ); |
| 103 |
add_action( 'suredonation_privacy_data_erased', [ $this, 'track_privacy_data_erased' ] ); |
| 104 |
|
| 105 |
// Detect state-based events (daily throttle; dedup prevents repeat |
| 106 |
// tracking). Admin-only so the detection never runs on the frontend. |
| 107 |
if ( is_admin() ) { |
| 108 |
$this->detect_state_events(); |
| 109 |
} |
| 110 |
} |
| 111 |
|
| 112 |
/** |
| 113 |
* Register the SureDonation entity with the BSF Analytics loader. |
| 114 |
* |
| 115 |
* Runs on init priority 0 — after add-on plugins have registered their |
| 116 |
* filters on plugins_loaded, and before the loader's own init callback |
| 117 |
* loads the analytics library. |
| 118 |
* |
| 119 |
* @return void |
| 120 |
* @since 1.0.0 |
| 121 |
*/ |
| 122 |
public function register_entity() { |
| 123 |
if ( ! class_exists( 'BSF_Analytics_Loader' ) ) { |
| 124 |
require_once SUREDONATION_DIR . 'inc/lib/bsf-analytics/class-bsf-analytics-loader.php'; |
| 125 |
} |
| 126 |
|
| 127 |
if ( ! class_exists( 'BSF_Admin_Notices' ) ) { |
| 128 |
require_once SUREDONATION_DIR . 'inc/lib/astra-notices/class-bsf-admin-notices.php'; |
| 129 |
} |
| 130 |
|
| 131 |
/** |
| 132 |
* The loader's get_instance() carries no return type. |
| 133 |
* |
| 134 |
* @var \BSF_Analytics_Loader $suredonation_bsf_analytics |
| 135 |
*/ |
| 136 |
$suredonation_bsf_analytics = \BSF_Analytics_Loader::get_instance(); |
| 137 |
|
| 138 |
$suredonation_bsf_analytics->set_entity( |
| 139 |
[ |
| 140 |
'suredonation' => [ |
| 141 |
'product_name' => 'SureDonation', |
| 142 |
'path' => SUREDONATION_DIR . 'inc/lib/bsf-analytics', |
| 143 |
'author' => 'SureDonation', |
| 144 |
'time_to_display' => '+24 hours', |
| 145 |
'deactivation_survey' => apply_filters( |
| 146 |
'suredonation_deactivation_survey_data', |
| 147 |
[ |
| 148 |
[ |
| 149 |
'id' => 'deactivation-survey-suredonation', |
| 150 |
'popup_logo' => SUREDONATION_URL . 'images/suredonation-icon.svg', |
| 151 |
'plugin_slug' => 'suredonation', |
| 152 |
'popup_title' => __( 'Quick Feedback', 'suredonation' ), |
| 153 |
'support_url' => 'https://suredonation.com/support/', |
| 154 |
'popup_description' => __( 'If you have a moment, please share why you are deactivating SureDonation:', 'suredonation' ), |
| 155 |
'show_on_screens' => [ 'plugins' ], |
| 156 |
'plugin_version' => SUREDONATION_VER, |
| 157 |
], |
| 158 |
] |
| 159 |
), |
| 160 |
'hide_optin_checkbox' => true, |
| 161 |
], |
| 162 |
] |
| 163 |
); |
| 164 |
} |
| 165 |
|
| 166 |
/** |
| 167 |
* Get the shared BSF_Analytics_Events instance. |
| 168 |
* |
| 169 |
* Uses SureDonation's Helper option methods so the event data stays |
| 170 |
* inside the consolidated suredonation_options row. |
| 171 |
* |
| 172 |
* @return \BSF_Analytics_Events|null Events instance, or null when the library is unavailable. |
| 173 |
* @since 1.0.0 |
| 174 |
*/ |
| 175 |
public static function events() { |
| 176 |
if ( null === self::$events ) { |
| 177 |
if ( ! class_exists( 'BSF_Analytics_Events' ) ) { |
| 178 |
$events_file = SUREDONATION_DIR . 'inc/lib/bsf-analytics/class-bsf-analytics-events.php'; |
| 179 |
if ( file_exists( $events_file ) ) { |
| 180 |
require_once $events_file; |
| 181 |
} |
| 182 |
} |
| 183 |
|
| 184 |
if ( ! class_exists( 'BSF_Analytics_Events' ) ) { |
| 185 |
return null; |
| 186 |
} |
| 187 |
|
| 188 |
self::$events = new \BSF_Analytics_Events( |
| 189 |
'suredonation', |
| 190 |
[ |
| 191 |
'get' => [ Helper::class, 'get_suredonation_option' ], |
| 192 |
'update' => [ Helper::class, 'update_suredonation_option' ], |
| 193 |
] |
| 194 |
); |
| 195 |
} |
| 196 |
|
| 197 |
return self::$events; |
| 198 |
} |
| 199 |
|
| 200 |
/** |
| 201 |
* Register REST routes. |
| 202 |
* |
| 203 |
* Hooked - rest_api_init |
| 204 |
* |
| 205 |
* @return void |
| 206 |
* @since 1.3.0 |
| 207 |
*/ |
| 208 |
public function register_routes() { |
| 209 |
register_rest_route( |
| 210 |
'suredonation/v1', |
| 211 |
'/track-notice-event', |
| 212 |
[ |
| 213 |
'methods' => \WP_REST_Server::CREATABLE, |
| 214 |
'callback' => [ $this, 'handle_track_notice_event' ], |
| 215 |
// A named method rather than a closure: the capability guard in |
| 216 |
// tests/unit/inc/test-rest-api.php introspects every write |
| 217 |
// route's permission_callback, and a closure is opaque to it. |
| 218 |
'permission_callback' => [ $this, 'check_permissions' ], |
| 219 |
'args' => [ |
| 220 |
'event' => [ |
| 221 |
'type' => 'string', |
| 222 |
'required' => true, |
| 223 |
], |
| 224 |
], |
| 225 |
] |
| 226 |
); |
| 227 |
} |
| 228 |
|
| 229 |
/** |
| 230 |
* Whether the current user may record notice events. |
| 231 |
* |
| 232 |
* Named check_permissions to match the other REST controllers, which is also |
| 233 |
* what the write-route capability guard asserts on. |
| 234 |
* |
| 235 |
* @return bool True when the user can manage options. |
| 236 |
* @since 1.4.0 |
| 237 |
*/ |
| 238 |
public function check_permissions() { |
| 239 |
return current_user_can( 'manage_options' ); |
| 240 |
} |
| 241 |
|
| 242 |
/** |
| 243 |
* Record a React notice/UI interaction event. |
| 244 |
* |
| 245 |
* Validates the event against an allowlist (so arbitrary events cannot be |
| 246 |
* injected) and records it via the shared analytics events, respecting the |
| 247 |
* usage-tracking opt-in. Event names are suffixed `_react` to keep them |
| 248 |
* distinct from the wp-admin notice events. |
| 249 |
* |
| 250 |
* @param \WP_REST_Request<array<string, mixed>> $request REST request. |
| 251 |
* @return \WP_REST_Response |
| 252 |
* @since 1.3.0 |
| 253 |
*/ |
| 254 |
public function handle_track_notice_event( $request ) { |
| 255 |
$event = sanitize_key( (string) $request->get_param( 'event' ) ); |
| 256 |
|
| 257 |
if ( ! in_array( $event, self::TRACKED_EVENTS, true ) ) { |
| 258 |
return new \WP_REST_Response( [ 'success' => false ], 400 ); |
| 259 |
} |
| 260 |
|
| 261 |
$events = self::events(); |
| 262 |
if ( null !== $events ) { |
| 263 |
$events->track( $event ); |
| 264 |
} |
| 265 |
|
| 266 |
return new \WP_REST_Response( [ 'success' => true ], 200 ); |
| 267 |
} |
| 268 |
|
| 269 |
/** |
| 270 |
* Callback function to add SureDonation specific analytics data. |
| 271 |
* |
| 272 |
* @param array<string, mixed> $stats_data Existing stats data. |
| 273 |
* @return array<string, mixed> |
| 274 |
* @since 1.0.0 |
| 275 |
*/ |
| 276 |
public function add_suredonation_analytics_data( $stats_data ) { |
| 277 |
$aggregates = $this->get_donation_aggregates(); |
| 278 |
$campaign_counts = wp_count_posts( 'suredonation_cmpgn' ); |
| 279 |
$form_counts = wp_count_posts( 'suredonation_form' ); |
| 280 |
|
| 281 |
$bsf_internal_referrer = get_option( 'bsf_product_referers', [] ); |
| 282 |
$internal_referer = is_array( $bsf_internal_referrer ) && ! empty( $bsf_internal_referrer['suredonation'] ) |
| 283 |
? sanitize_text_field( (string) $bsf_internal_referrer['suredonation'] ) |
| 284 |
: 'self'; |
| 285 |
|
| 286 |
$privacy_settings = Privacy_Settings::get_settings(); |
| 287 |
|
| 288 |
// Computed once: the headline total below is derived from the same rows. |
| 289 |
$template_usage = $this->get_campaign_template_usage(); |
| 290 |
|
| 291 |
$plugin_data = [ |
| 292 |
'free_version' => SUREDONATION_VER, |
| 293 |
'numeric_values' => [ |
| 294 |
'total_campaigns' => absint( $campaign_counts->publish ?? 0 ), |
| 295 |
'total_donation_forms' => absint( $form_counts->publish ?? 0 ), |
| 296 |
'total_donations' => $aggregates['total'], |
| 297 |
'completed_donations' => $aggregates['completed'], |
| 298 |
'recurring_donations' => $aggregates['recurring'], |
| 299 |
'total_donors' => $this->get_total_donors(), |
| 300 |
'forms_with_image_block' => $this->get_image_block_form_count(), |
| 301 |
'posts_with_social_sharing_block' => $this->get_social_sharing_block_count(), |
| 302 |
'stripe_accounts_count' => count( Stripe_Helper::get_all_accounts() ), |
| 303 |
// Campaigns started from a gallery template — excludes both the |
| 304 |
// scratch path and the `general` fallback, so this is the count |
| 305 |
// of campaigns that actually adopted a cause template. |
| 306 |
'campaigns_from_template' => array_sum( |
| 307 |
array_diff_key( |
| 308 |
$template_usage, |
| 309 |
[ |
| 310 |
'scratch' => 0, |
| 311 |
Campaign_Templates::GENERAL => 0, |
| 312 |
] |
| 313 |
) |
| 314 |
), |
| 315 |
], |
| 316 |
'boolean_values' => [ |
| 317 |
'stripe_enabled' => Stripe_Helper::is_stripe_connected(), |
| 318 |
'paypal_enabled' => PayPal_Helper::is_paypal_connected(), |
| 319 |
'offline_enabled' => Offline_Helper::is_offline_enabled(), |
| 320 |
// True only when the OttoKit plugin is active AND authenticated, |
| 321 |
// so this implies the plugin is active. |
| 322 |
'ottokit_connected' => Helper::is_suretriggers_ready(), |
| 323 |
'contact_consent_enabled' => ! empty( $privacy_settings['contact_consent_field'] ), |
| 324 |
'privacy_policy_field_enabled' => ! empty( $privacy_settings['privacy_policy_field'] ), |
| 325 |
'terms_field_enabled' => ! empty( $privacy_settings['terms_conditions_field'] ), |
| 326 |
], |
| 327 |
'data_retention_period' => isset( $privacy_settings['minimum_data_retention_period'] ) ? Helper::get_string_value( $privacy_settings['minimum_data_retention_period'] ) : 'none', |
| 328 |
'block_usage' => $this->get_block_usage(), |
| 329 |
'campaign_template_usage' => $template_usage, |
| 330 |
'elementor_widget_usage' => $this->get_elementor_widget_usage(), |
| 331 |
'bricks_element_usage' => $this->get_bricks_element_usage(), |
| 332 |
'internal_referer' => $internal_referer, |
| 333 |
]; |
| 334 |
|
| 335 |
// Add KPI tracking data. |
| 336 |
$kpi_data = $this->get_kpi_tracking_data(); |
| 337 |
if ( ! empty( $kpi_data ) ) { |
| 338 |
$plugin_data['kpi_records'] = $kpi_data; |
| 339 |
} |
| 340 |
|
| 341 |
// Flush pending events into payload (only if any exist). |
| 342 |
$events = self::events(); |
| 343 |
if ( null !== $events ) { |
| 344 |
$pending_events = $events->flush_pending(); |
| 345 |
if ( ! empty( $pending_events ) ) { |
| 346 |
$plugin_data['events_record'] = $pending_events; |
| 347 |
} |
| 348 |
} |
| 349 |
|
| 350 |
if ( ! isset( $stats_data['plugin_data'] ) || ! is_array( $stats_data['plugin_data'] ) ) { |
| 351 |
$stats_data['plugin_data'] = []; |
| 352 |
} |
| 353 |
|
| 354 |
$stats_data['plugin_data']['suredonation'] = $plugin_data; |
| 355 |
|
| 356 |
return $stats_data; |
| 357 |
} |
| 358 |
|
| 359 |
/** |
| 360 |
* Keep analytics sends off the frontend. |
| 361 |
* |
| 362 |
* Filter callback for `suredonation_tracking_enabled`. The library |
| 363 |
* evaluates this on every request via `is_tracking_enabled()`; gating on |
| 364 |
* is_admin() means the stats queries never run on frontend page loads. |
| 365 |
* Deliberately NOT narrowed further (e.g. to plugin screens): the library |
| 366 |
* also consults this filter from `register_usage_tracking_setting()` on |
| 367 |
* admin_init, where returning false aborts settings registration for all |
| 368 |
* registered BSF products. |
| 369 |
* |
| 370 |
* @param bool $is_enabled Whether tracking is enabled (opt-in state). |
| 371 |
* @return bool |
| 372 |
* @since 1.0.0 |
| 373 |
*/ |
| 374 |
public function restrict_tracking_to_admin( $is_enabled ) { |
| 375 |
return $is_enabled && is_admin(); |
| 376 |
} |
| 377 |
|
| 378 |
/** |
| 379 |
* Track onboarding completion when lead-capture details are saved. |
| 380 |
* |
| 381 |
* The payload contains PII (name/email) — only the opt-in flag is |
| 382 |
* forwarded to analytics. |
| 383 |
* |
| 384 |
* @param array<string, mixed> $payload Sanitized onboarding payload. |
| 385 |
* @return void |
| 386 |
* @since 1.0.0 |
| 387 |
*/ |
| 388 |
public function track_onboarding_completed( $payload ) { |
| 389 |
$events = self::events(); |
| 390 |
if ( null === $events ) { |
| 391 |
return; |
| 392 |
} |
| 393 |
|
| 394 |
$payload = is_array( $payload ) ? $payload : []; |
| 395 |
|
| 396 |
$events->track( |
| 397 |
'onboarding_completed', |
| 398 |
'', |
| 399 |
[ |
| 400 |
'opted_in' => ! empty( $payload['opted_in'] ) ? 'yes' : 'no', |
| 401 |
] |
| 402 |
); |
| 403 |
} |
| 404 |
|
| 405 |
/** |
| 406 |
* Track the first time the campaign guided tour is shown to a user. |
| 407 |
* |
| 408 |
* Fired from the REST layer on the tour's first render. The events tracker |
| 409 |
* dedups by name, so this is recorded once per site regardless of how many |
| 410 |
* users see the tour or how often it re-triggers. |
| 411 |
* |
| 412 |
* @return void |
| 413 |
* @since 1.5.0 |
| 414 |
*/ |
| 415 |
public function track_campaign_tour_shown() { |
| 416 |
$events = self::events(); |
| 417 |
if ( null === $events ) { |
| 418 |
return; |
| 419 |
} |
| 420 |
|
| 421 |
$events->track( 'campaign_tour_shown' ); |
| 422 |
} |
| 423 |
|
| 424 |
/** |
| 425 |
* Track how a campaign guided-tour run ended. |
| 426 |
* |
| 427 |
* `campaign_tour_shown` tells us the tour was seen; these tell us whether it |
| 428 |
* worked. Four outcomes, each recorded under its own event name: |
| 429 |
* |
| 430 |
* - `completed` — the user reached the final step. |
| 431 |
* - `dismissed` — closed part-way; the step key rides along as the |
| 432 |
* event value so we can see where runs are abandoned. |
| 433 |
* - `opted_out` — ticked "Don't show this again". |
| 434 |
* - `manual_started` — replayed deliberately via "Take a tour". |
| 435 |
* |
| 436 |
* `dismissed` is tracked with $force so the most recent drop-off step wins |
| 437 |
* rather than only the first one ever recorded on the site; the others keep |
| 438 |
* the default once-per-site semantics. |
| 439 |
* |
| 440 |
* @param string $outcome How the run ended. Unknown values are ignored. |
| 441 |
* @param string $step Step key the run ended on. Only used for `dismissed`. |
| 442 |
* @return void |
| 443 |
* @since 1.5.0 |
| 444 |
*/ |
| 445 |
public function track_campaign_tour_outcome( $outcome, $step = '' ) { |
| 446 |
$events = self::events(); |
| 447 |
if ( null === $events ) { |
| 448 |
return; |
| 449 |
} |
| 450 |
|
| 451 |
$outcome = Helper::get_string_value( $outcome ); |
| 452 |
$step = Helper::get_string_value( $step ); |
| 453 |
|
| 454 |
switch ( $outcome ) { |
| 455 |
case 'completed': |
| 456 |
$events->track( 'campaign_tour_completed' ); |
| 457 |
break; |
| 458 |
case 'dismissed': |
| 459 |
// Retrackable: the latest abandonment point is the useful one. |
| 460 |
$events->track( 'campaign_tour_dismissed', $step, [], true ); |
| 461 |
break; |
| 462 |
case 'opted_out': |
| 463 |
$events->track( 'campaign_tour_opted_out', $step ); |
| 464 |
break; |
| 465 |
case 'manual_started': |
| 466 |
$events->track( 'campaign_tour_manual_started' ); |
| 467 |
break; |
| 468 |
} |
| 469 |
} |
| 470 |
|
| 471 |
/** |
| 472 |
* Track the first time the campaign template picker is opened. |
| 473 |
* |
| 474 |
* Deduped, so it answers "did this site ever discover the picker?" — the |
| 475 |
* denominator for template adoption, since `campaign_template_usage` in the |
| 476 |
* stats payload only counts campaigns that were actually created from one. |
| 477 |
* |
| 478 |
* @return void |
| 479 |
* @since 1.5.0 |
| 480 |
*/ |
| 481 |
public function track_campaign_template_picker_opened() { |
| 482 |
$events = self::events(); |
| 483 |
if ( null === $events ) { |
| 484 |
return; |
| 485 |
} |
| 486 |
|
| 487 |
$events->track( 'campaign_template_picker_opened' ); |
| 488 |
} |
| 489 |
|
| 490 |
/** |
| 491 |
* Track the first campaign a site creates from a template. |
| 492 |
* |
| 493 |
* Deduped, so the event value is the template the site reached for *first* — |
| 494 |
* the running per-template totals live in `campaign_template_usage` on the |
| 495 |
* stats payload, which is recomputed on every send. |
| 496 |
* |
| 497 |
* @param string $template_id Template the campaign was created from. |
| 498 |
* @return void |
| 499 |
* @since 1.5.0 |
| 500 |
*/ |
| 501 |
public function track_campaign_created_from_template( $template_id ) { |
| 502 |
$events = self::events(); |
| 503 |
if ( null === $events ) { |
| 504 |
return; |
| 505 |
} |
| 506 |
|
| 507 |
$template_id = Helper::get_string_value( $template_id ); |
| 508 |
if ( '' === $template_id ) { |
| 509 |
return; |
| 510 |
} |
| 511 |
|
| 512 |
$events->track( 'first_campaign_from_template', $template_id ); |
| 513 |
} |
| 514 |
|
| 515 |
/** |
| 516 |
* Track first personal-data export that included SureDonation data |
| 517 |
* (adoption event — deduped, sent once). |
| 518 |
* |
| 519 |
* @since 1.2.0 |
| 520 |
* @return void |
| 521 |
*/ |
| 522 |
public function track_privacy_data_exported() { |
| 523 |
$events = self::events(); |
| 524 |
if ( null === $events ) { |
| 525 |
return; |
| 526 |
} |
| 527 |
|
| 528 |
$events->track( 'privacy_data_export_used' ); |
| 529 |
} |
| 530 |
|
| 531 |
/** |
| 532 |
* Track first personal-data erasure processed for SureDonation data |
| 533 |
* (adoption event — deduped, sent once). |
| 534 |
* |
| 535 |
* @since 1.2.0 |
| 536 |
* @param array<string, mixed> $outcome Erasure outcome flags. |
| 537 |
* @return void |
| 538 |
*/ |
| 539 |
public function track_privacy_data_erased( $outcome ) { |
| 540 |
$events = self::events(); |
| 541 |
if ( null === $events ) { |
| 542 |
return; |
| 543 |
} |
| 544 |
|
| 545 |
$outcome = is_array( $outcome ) ? $outcome : []; |
| 546 |
|
| 547 |
$events->track( |
| 548 |
'privacy_data_erasure_used', |
| 549 |
'', |
| 550 |
[ |
| 551 |
'items_removed' => ! empty( $outcome['items_removed'] ) ? 'yes' : 'no', |
| 552 |
'items_retained' => ! empty( $outcome['items_retained'] ) ? 'yes' : 'no', |
| 553 |
'erase_failed' => ! empty( $outcome['erase_failed'] ) ? 'yes' : 'no', |
| 554 |
] |
| 555 |
); |
| 556 |
} |
| 557 |
|
| 558 |
/** |
| 559 |
* Track first time a campaign is published (activation event). |
| 560 |
* |
| 561 |
* @param string $new_status New post status. |
| 562 |
* @param string $old_status Old post status. |
| 563 |
* @param \WP_Post $post Post object. |
| 564 |
* @return void |
| 565 |
* @since 1.0.0 |
| 566 |
*/ |
| 567 |
public function track_first_campaign_published( $new_status, $old_status, $post ) { |
| 568 |
if ( 'publish' !== $new_status || 'publish' === $old_status || ! $post instanceof \WP_Post || 'suredonation_cmpgn' !== $post->post_type ) { |
| 569 |
return; |
| 570 |
} |
| 571 |
|
| 572 |
$events = self::events(); |
| 573 |
if ( null === $events ) { |
| 574 |
return; |
| 575 |
} |
| 576 |
|
| 577 |
$meta = Helper::get_campaign_meta( $post->ID ); |
| 578 |
$goal_amount = isset( $meta['goal_amount'] ) && is_numeric( $meta['goal_amount'] ) ? (float) $meta['goal_amount'] : 0.0; |
| 579 |
$goal_type = isset( $meta['goal_type'] ) && is_scalar( $meta['goal_type'] ) ? sanitize_text_field( (string) $meta['goal_type'] ) : ''; |
| 580 |
|
| 581 |
$events->track( |
| 582 |
'first_campaign_published', |
| 583 |
(string) $post->ID, |
| 584 |
[ |
| 585 |
'goal_type' => $goal_type, |
| 586 |
'has_goal' => $goal_amount > 0 ? '1' : '0', |
| 587 |
] |
| 588 |
); |
| 589 |
} |
| 590 |
|
| 591 |
/** |
| 592 |
* Track first time a user opens the campaign editor. |
| 593 |
* |
| 594 |
* @param \WP_Screen $screen Current screen object. |
| 595 |
* @return void |
| 596 |
* @since 1.0.0 |
| 597 |
*/ |
| 598 |
public function track_first_campaign_editor_opened( $screen ) { |
| 599 |
if ( ! $screen instanceof \WP_Screen || 'suredonation_cmpgn' !== $screen->post_type || 'post' !== $screen->base ) { |
| 600 |
return; |
| 601 |
} |
| 602 |
|
| 603 |
$events = self::events(); |
| 604 |
if ( null === $events ) { |
| 605 |
return; |
| 606 |
} |
| 607 |
|
| 608 |
$events->track( 'first_campaign_editor_opened' ); |
| 609 |
} |
| 610 |
|
| 611 |
/** |
| 612 |
* Get donation aggregates in a single request-cached query. |
| 613 |
* |
| 614 |
* Feeds both the stats numeric values and the state-event detection so |
| 615 |
* the donations table is only ever hit once per request. |
| 616 |
* |
| 617 |
* @return array<string, int> Aggregate counts. |
| 618 |
* @since 1.0.0 |
| 619 |
*/ |
| 620 |
private function get_donation_aggregates() { |
| 621 |
if ( null !== self::$donation_aggregates ) { |
| 622 |
return self::$donation_aggregates; |
| 623 |
} |
| 624 |
|
| 625 |
global $wpdb; |
| 626 |
|
| 627 |
$defaults = [ |
| 628 |
'total' => 0, |
| 629 |
'completed' => 0, |
| 630 |
'completed_live' => 0, |
| 631 |
'recurring' => 0, |
| 632 |
'anonymous_completed' => 0, |
| 633 |
'fees_covered_completed' => 0, |
| 634 |
'refunded' => 0, |
| 635 |
]; |
| 636 |
|
| 637 |
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Single aggregate query on a custom table, request-cached in a static. |
| 638 |
$row = $wpdb->get_row( |
| 639 |
$wpdb->prepare( |
| 640 |
"SELECT COUNT(*) AS total, |
| 641 |
COALESCE(SUM(payment_status = 'completed'),0) AS completed, |
| 642 |
COALESCE(SUM(payment_status = 'completed' AND payment_mode = 'live'),0) AS completed_live, |
| 643 |
COALESCE(SUM(subscription_id IS NOT NULL AND subscription_id <> ''),0) AS recurring, |
| 644 |
COALESCE(SUM(is_anonymous = 1 AND payment_status = 'completed'),0) AS anonymous_completed, |
| 645 |
COALESCE(SUM(fees_covered > 0 AND payment_status = 'completed'),0) AS fees_covered_completed, |
| 646 |
COALESCE(SUM(payment_status IN ('refunded','partially_refunded')),0) AS refunded |
| 647 |
FROM %i", |
| 648 |
$wpdb->prefix . 'suredonation_donations' |
| 649 |
), |
| 650 |
ARRAY_A |
| 651 |
); |
| 652 |
|
| 653 |
self::$donation_aggregates = is_array( $row ) |
| 654 |
? array_map( 'absint', array_merge( $defaults, $row ) ) |
| 655 |
: $defaults; |
| 656 |
|
| 657 |
return self::$donation_aggregates; |
| 658 |
} |
| 659 |
|
| 660 |
/** |
| 661 |
* Get the total number of donors. |
| 662 |
* |
| 663 |
* @return int |
| 664 |
* @since 1.0.0 |
| 665 |
*/ |
| 666 |
private function get_total_donors() { |
| 667 |
global $wpdb; |
| 668 |
|
| 669 |
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Single COUNT query on a custom table, runs only at analytics send time. |
| 670 |
$count = $wpdb->get_var( |
| 671 |
$wpdb->prepare( |
| 672 |
'SELECT COUNT(*) FROM %i', |
| 673 |
$wpdb->prefix . 'suredonation_donors' |
| 674 |
) |
| 675 |
); |
| 676 |
|
| 677 |
return absint( $count ); |
| 678 |
} |
| 679 |
|
| 680 |
/** |
| 681 |
* How many published posts use each SureDonation campaign/donation block. |
| 682 |
* |
| 683 |
* A privacy-preserving usage count (no content leaves the site) so we can see |
| 684 |
* which blocks are actually adopted. One conditional-SUM query (a single table |
| 685 |
* scan), run only at analytics send time. Elementor/Bricks placements are not |
| 686 |
* counted here (they store their config outside the block grammar) — see |
| 687 |
* get_elementor_widget_usage(). |
| 688 |
* |
| 689 |
* @return array<string, int> Block key => number of published posts using it. |
| 690 |
* @since 1.2.0 |
| 691 |
*/ |
| 692 |
private function get_block_usage() { |
| 693 |
global $wpdb; |
| 694 |
|
| 695 |
$blocks = [ |
| 696 |
'campaign_goal' => 'suredonation/campaign-goal', |
| 697 |
'campaign_stats' => 'suredonation/campaign-stats', |
| 698 |
'campaign_donations' => 'suredonation/campaign-donations', |
| 699 |
'campaign_donors' => 'suredonation/campaign-donors', |
| 700 |
'campaign_donate_button' => 'suredonation/campaign-donate-button', |
| 701 |
'campaign_social_sharing' => 'suredonation/campaign-social-sharing', |
| 702 |
'donation_form' => 'suredonation/donation-form', |
| 703 |
]; |
| 704 |
|
| 705 |
// prepare() fills placeholders in SQL order: the SELECT-list %s LIKEs |
| 706 |
// first, then the FROM %i, then the status %s. |
| 707 |
$selects = []; |
| 708 |
$values = []; |
| 709 |
foreach ( array_keys( $blocks ) as $key ) { |
| 710 |
$selects[] = "SUM(post_content LIKE %s) AS {$key}"; |
| 711 |
// The space after the block name is the delimiter the serializer always |
| 712 |
// emits (before attrs JSON, "-->" or "/-->"), so a future |
| 713 |
// "campaign-goal-x" block can't prefix-match campaign-goal. |
| 714 |
$values[] = '%' . $wpdb->esc_like( '<!-- wp:' . $blocks[ $key ] . ' ' ) . '%'; |
| 715 |
} |
| 716 |
$values[] = $wpdb->posts; |
| 717 |
$values[] = 'publish'; |
| 718 |
|
| 719 |
// 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. |
| 720 |
$row = $wpdb->get_row( |
| 721 |
$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. |
| 722 |
ARRAY_A |
| 723 |
); |
| 724 |
|
| 725 |
$usage = []; |
| 726 |
foreach ( array_keys( $blocks ) as $key ) { |
| 727 |
$usage[ $key ] = absint( is_array( $row ) ? ( $row[ $key ] ?? 0 ) : 0 ); |
| 728 |
} |
| 729 |
|
| 730 |
return $usage; |
| 731 |
} |
| 732 |
|
| 733 |
/** |
| 734 |
* How many published campaigns were created from each campaign template. |
| 735 |
* |
| 736 |
* The running answer to "which template gets used, and how often" — a |
| 737 |
* snapshot rather than an event, because the stats payload is rebuilt on |
| 738 |
* every send while events dedup by name and fire once per site. |
| 739 |
* |
| 740 |
* Every known template id is seeded to 0 so the payload keeps the same shape |
| 741 |
* across sites (same contract as get_block_usage()). Campaigns with no |
| 742 |
* template meta — anything created before templates shipped, or via "Start |
| 743 |
* from scratch" — land in `scratch`. Ids that are no longer registered are |
| 744 |
* dropped rather than passed through, so a stale or hand-edited meta value |
| 745 |
* can never widen the payload. |
| 746 |
* |
| 747 |
* @return array<string, int> Template id => number of published campaigns. |
| 748 |
* @since 1.5.0 |
| 749 |
*/ |
| 750 |
private function get_campaign_template_usage() { |
| 751 |
global $wpdb; |
| 752 |
|
| 753 |
$registry = Campaign_Templates::get_instance(); |
| 754 |
|
| 755 |
// Seed the known ids, plus the two buckets that are not gallery cards: |
| 756 |
// `general` (the built-in fallback) and `scratch` (no meta at all). |
| 757 |
$usage = [ 'scratch' => 0 ]; |
| 758 |
foreach ( $registry->get_all() as $template ) { |
| 759 |
$id = Helper::get_string_value( $template['id'] ?? '' ); |
| 760 |
if ( '' !== $id ) { |
| 761 |
$usage[ $id ] = 0; |
| 762 |
} |
| 763 |
} |
| 764 |
$usage[ Campaign_Templates::GENERAL ] = 0; |
| 765 |
|
| 766 |
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Single grouped scan at analytics send time only. |
| 767 |
$rows = $wpdb->get_results( |
| 768 |
$wpdb->prepare( |
| 769 |
'SELECT pm.meta_value AS template_id, COUNT(*) AS total |
| 770 |
FROM %i AS p |
| 771 |
LEFT JOIN %i AS pm ON pm.post_id = p.ID AND pm.meta_key = %s |
| 772 |
WHERE p.post_type = %s AND p.post_status = %s |
| 773 |
GROUP BY pm.meta_value', |
| 774 |
$wpdb->posts, |
| 775 |
$wpdb->postmeta, |
| 776 |
Campaign_Cpt::META_TEMPLATE_ID, |
| 777 |
SUREDONATION_POST_TYPE, |
| 778 |
'publish' |
| 779 |
), |
| 780 |
ARRAY_A |
| 781 |
); |
| 782 |
|
| 783 |
if ( ! is_array( $rows ) ) { |
| 784 |
return $usage; |
| 785 |
} |
| 786 |
|
| 787 |
foreach ( $rows as $row ) { |
| 788 |
$id = Helper::get_string_value( $row['template_id'] ?? '' ); |
| 789 |
$total = absint( $row['total'] ?? 0 ); |
| 790 |
|
| 791 |
// No meta (NULL from the LEFT JOIN, or an empty string) => scratch. |
| 792 |
if ( '' === $id ) { |
| 793 |
$usage['scratch'] += $total; |
| 794 |
continue; |
| 795 |
} |
| 796 |
|
| 797 |
// Only report ids we still recognise. |
| 798 |
if ( array_key_exists( $id, $usage ) ) { |
| 799 |
$usage[ $id ] += $total; |
| 800 |
} |
| 801 |
} |
| 802 |
|
| 803 |
return $usage; |
| 804 |
} |
| 805 |
|
| 806 |
/** |
| 807 |
* How many published posts use each SureDonation Elementor widget. |
| 808 |
* |
| 809 |
* The Elementor counterpart of get_block_usage(): widgets live in the |
| 810 |
* _elementor_data postmeta (JSON with a quoted "widgetType"), not in the |
| 811 |
* block grammar. Same privacy-preserving single-scan shape, run only at |
| 812 |
* analytics send time. |
| 813 |
* |
| 814 |
* @return array<string, int> Widget key => number of published posts using it. |
| 815 |
* @since 1.2.0 |
| 816 |
*/ |
| 817 |
private function get_elementor_widget_usage() { |
| 818 |
global $wpdb; |
| 819 |
|
| 820 |
$widgets = [ |
| 821 |
'campaign_goal' => 'suredonation-campaign-goal', |
| 822 |
'campaign_stats' => 'suredonation-campaign-stats', |
| 823 |
'campaign_donations' => 'suredonation-campaign-donations', |
| 824 |
'campaign_donors' => 'suredonation-campaign-donors', |
| 825 |
'campaign_donate_button' => 'suredonation-campaign-donate-button', |
| 826 |
'campaign_social_sharing' => 'suredonation-campaign-social-sharing', |
| 827 |
'donation_form' => 'suredonation-donation-form', |
| 828 |
]; |
| 829 |
|
| 830 |
// prepare() fills placeholders in SQL order: the SELECT-list %s LIKEs |
| 831 |
// first, then the two FROM/JOIN %i tables, then meta_key and status. |
| 832 |
$selects = []; |
| 833 |
$values = []; |
| 834 |
foreach ( array_keys( $widgets ) as $key ) { |
| 835 |
$selects[] = "SUM(pm.meta_value LIKE %s) AS {$key}"; |
| 836 |
// Quoted as stored in the _elementor_data JSON ("widgetType":"…"), |
| 837 |
// which bounds the match on both sides. |
| 838 |
$values[] = '%' . $wpdb->esc_like( '"' . $widgets[ $key ] . '"' ) . '%'; |
| 839 |
} |
| 840 |
$values[] = $wpdb->postmeta; |
| 841 |
$values[] = $wpdb->posts; |
| 842 |
$values[] = '_elementor_data'; |
| 843 |
$values[] = 'publish'; |
| 844 |
|
| 845 |
// 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. |
| 846 |
$row = $wpdb->get_row( |
| 847 |
$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. |
| 848 |
ARRAY_A |
| 849 |
); |
| 850 |
|
| 851 |
$usage = []; |
| 852 |
foreach ( array_keys( $widgets ) as $key ) { |
| 853 |
$usage[ $key ] = absint( is_array( $row ) ? ( $row[ $key ] ?? 0 ) : 0 ); |
| 854 |
} |
| 855 |
|
| 856 |
return $usage; |
| 857 |
} |
| 858 |
|
| 859 |
/** |
| 860 |
* How many published posts use each SureDonation Bricks element. |
| 861 |
* |
| 862 |
* A privacy-preserving usage count (no content leaves the site) so we can see |
| 863 |
* which Bricks elements are actually adopted — the Bricks counterpart of the |
| 864 |
* Gutenberg block_usage stat. Bricks stores builder data as serialized element |
| 865 |
* arrays in postmeta, so each element name is matched inside its quotes. |
| 866 |
* One conditional-SUM query (a single scan), run only at analytics send time. |
| 867 |
* |
| 868 |
* @return array<string, int> Element key => number of published posts using it. |
| 869 |
* @since 1.2.0 |
| 870 |
*/ |
| 871 |
private function get_bricks_element_usage() { |
| 872 |
global $wpdb; |
| 873 |
|
| 874 |
$elements = [ |
| 875 |
'campaign_goal' => 'suredonation-campaign-goal', |
| 876 |
'campaign_stats' => 'suredonation-campaign-stats', |
| 877 |
'campaign_donations' => 'suredonation-campaign-donations', |
| 878 |
'campaign_donors' => 'suredonation-campaign-donors', |
| 879 |
'campaign_donate_button' => 'suredonation-campaign-donate-button', |
| 880 |
'campaign_social_sharing' => 'suredonation-campaign-social-sharing', |
| 881 |
'donation_form' => 'suredonation-donation-form', |
| 882 |
]; |
| 883 |
|
| 884 |
// prepare() fills placeholders in SQL order: the SELECT-list %s LIKEs |
| 885 |
// first, then the two FROM/JOIN %i tables, then meta keys and status. |
| 886 |
$selects = []; |
| 887 |
$values = []; |
| 888 |
foreach ( array_keys( $elements ) as $key ) { |
| 889 |
$selects[] = "SUM(pm.meta_value LIKE %s) AS {$key}"; |
| 890 |
// Quoted as stored in the serialized Bricks element data, which |
| 891 |
// bounds the match on both sides. |
| 892 |
$values[] = '%' . $wpdb->esc_like( '"' . $elements[ $key ] . '"' ) . '%'; |
| 893 |
} |
| 894 |
$values[] = $wpdb->postmeta; |
| 895 |
$values[] = $wpdb->posts; |
| 896 |
$values[] = '_bricks_page_content_2'; |
| 897 |
$values[] = '_bricks_page_header_2'; |
| 898 |
$values[] = '_bricks_page_footer_2'; |
| 899 |
$values[] = 'publish'; |
| 900 |
|
| 901 |
// 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. |
| 902 |
$row = $wpdb->get_row( |
| 903 |
$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. |
| 904 |
ARRAY_A |
| 905 |
); |
| 906 |
|
| 907 |
$usage = []; |
| 908 |
foreach ( array_keys( $elements ) as $key ) { |
| 909 |
$usage[ $key ] = absint( is_array( $row ) ? ( $row[ $key ] ?? 0 ) : 0 ); |
| 910 |
} |
| 911 |
|
| 912 |
return $usage; |
| 913 |
} |
| 914 |
|
| 915 |
/** |
| 916 |
* How many published posts use the Campaign Social Sharing block. |
| 917 |
* |
| 918 |
* A privacy-preserving adoption count (no content leaves the site), run only |
| 919 |
* at analytics send time. The trailing space is the delimiter the block |
| 920 |
* serializer always emits after the block name, so a future |
| 921 |
* "campaign-social-sharing-x" block can't prefix-match. |
| 922 |
* |
| 923 |
* @return int Number of published posts containing the block. |
| 924 |
* @since 1.2.0 |
| 925 |
*/ |
| 926 |
private function get_social_sharing_block_count() { |
| 927 |
global $wpdb; |
| 928 |
|
| 929 |
$like = '%' . $wpdb->esc_like( '<!-- wp:suredonation/campaign-social-sharing ' ) . '%'; |
| 930 |
|
| 931 |
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Single aggregate COUNT run only at analytics send time. |
| 932 |
$count = $wpdb->get_var( |
| 933 |
$wpdb->prepare( |
| 934 |
'SELECT COUNT(ID) FROM %i WHERE post_status = %s AND post_content LIKE %s', |
| 935 |
$wpdb->posts, |
| 936 |
'publish', |
| 937 |
$like |
| 938 |
) |
| 939 |
); |
| 940 |
|
| 941 |
return absint( $count ); |
| 942 |
} |
| 943 |
|
| 944 |
/** |
| 945 |
* How many published donation forms use the Image block. |
| 946 |
* |
| 947 |
* A privacy-preserving adoption count (no content leaves the site), run only |
| 948 |
* at analytics send time. The trailing space is the delimiter the block |
| 949 |
* serializer always emits after the block name, so a future |
| 950 |
* "image-x" block can't prefix-match. |
| 951 |
* |
| 952 |
* @return int Number of published donation forms containing the block. |
| 953 |
* @since 1.3.0 |
| 954 |
*/ |
| 955 |
private function get_image_block_form_count() { |
| 956 |
global $wpdb; |
| 957 |
|
| 958 |
$like = '%' . $wpdb->esc_like( '<!-- wp:suredonation/image ' ) . '%'; |
| 959 |
|
| 960 |
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Single aggregate COUNT run only at analytics send time. |
| 961 |
$count = $wpdb->get_var( |
| 962 |
$wpdb->prepare( |
| 963 |
'SELECT COUNT(ID) FROM %i WHERE post_type = %s AND post_status = %s AND post_content LIKE %s', |
| 964 |
$wpdb->posts, |
| 965 |
'suredonation_form', |
| 966 |
'publish', |
| 967 |
$like |
| 968 |
) |
| 969 |
); |
| 970 |
|
| 971 |
return absint( $count ); |
| 972 |
} |
| 973 |
|
| 974 |
/** |
| 975 |
* Get KPI tracking data for the last 2 full days (excluding today). |
| 976 |
* |
| 977 |
* Single grouped query; raw revenue never enters the payload — only |
| 978 |
* the donation count and a coarse revenue tier per day. |
| 979 |
* |
| 980 |
* Date boundaries use GMT because `created_at` is written with |
| 981 |
* current_time( 'mysql', true ). |
| 982 |
* |
| 983 |
* @return array<string, array<string, array<string, mixed>>> KPI data keyed by Y-m-d date. |
| 984 |
* @since 1.0.0 |
| 985 |
*/ |
| 986 |
private function get_kpi_tracking_data() { |
| 987 |
global $wpdb; |
| 988 |
|
| 989 |
$start = gmdate( 'Y-m-d', strtotime( '-2 days' ) ) . ' 00:00:00'; |
| 990 |
$end = gmdate( 'Y-m-d' ) . ' 00:00:00'; |
| 991 |
|
| 992 |
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Single grouped query on a custom table, runs only at analytics send time. |
| 993 |
$rows = $wpdb->get_results( |
| 994 |
$wpdb->prepare( |
| 995 |
"SELECT DATE(created_at) AS day, COUNT(*) AS donations, COALESCE(SUM(amount),0) AS revenue |
| 996 |
FROM %i |
| 997 |
WHERE payment_status = 'completed' AND created_at >= %s AND created_at < %s |
| 998 |
GROUP BY day", |
| 999 |
$wpdb->prefix . 'suredonation_donations', |
| 1000 |
$start, |
| 1001 |
$end |
| 1002 |
), |
| 1003 |
ARRAY_A |
| 1004 |
); |
| 1005 |
|
| 1006 |
$kpi_data = []; |
| 1007 |
|
| 1008 |
// Seed both days so dates with zero donations are still reported. |
| 1009 |
for ( $i = 2; $i >= 1; $i-- ) { |
| 1010 |
$day = gmdate( 'Y-m-d', strtotime( '-' . $i . ' days' ) ); |
| 1011 |
|
| 1012 |
$kpi_data[ $day ] = [ |
| 1013 |
'numeric_values' => [ |
| 1014 |
'donations' => 0, |
| 1015 |
], |
| 1016 |
'string_values' => [ |
| 1017 |
'donation_revenue_tier' => '0', |
| 1018 |
], |
| 1019 |
]; |
| 1020 |
} |
| 1021 |
|
| 1022 |
$rows = is_array( $rows ) ? $rows : []; |
| 1023 |
|
| 1024 |
foreach ( $rows as $row ) { |
| 1025 |
if ( empty( $row['day'] ) || ! isset( $kpi_data[ $row['day'] ] ) ) { |
| 1026 |
continue; |
| 1027 |
} |
| 1028 |
|
| 1029 |
$kpi_data[ $row['day'] ] = [ |
| 1030 |
'numeric_values' => [ |
| 1031 |
'donations' => absint( $row['donations'] ?? 0 ), |
| 1032 |
], |
| 1033 |
'string_values' => [ |
| 1034 |
'donation_revenue_tier' => $this->get_revenue_tier( (float) ( $row['revenue'] ?? 0 ) ), |
| 1035 |
], |
| 1036 |
]; |
| 1037 |
} |
| 1038 |
|
| 1039 |
return $kpi_data; |
| 1040 |
} |
| 1041 |
|
| 1042 |
/** |
| 1043 |
* Map a raw daily revenue amount to a coarse reporting tier. |
| 1044 |
* |
| 1045 |
* @param float $revenue Daily revenue. |
| 1046 |
* @return string Revenue tier label. |
| 1047 |
* @since 1.0.0 |
| 1048 |
*/ |
| 1049 |
private function get_revenue_tier( float $revenue ): string { |
| 1050 |
if ( $revenue <= 0 ) { |
| 1051 |
return '0'; |
| 1052 |
} |
| 1053 |
if ( $revenue < 100 ) { |
| 1054 |
return '1-100'; |
| 1055 |
} |
| 1056 |
if ( $revenue < 500 ) { |
| 1057 |
return '100-500'; |
| 1058 |
} |
| 1059 |
if ( $revenue < 1000 ) { |
| 1060 |
return '500-1000'; |
| 1061 |
} |
| 1062 |
if ( $revenue < 5000 ) { |
| 1063 |
return '1000-5000'; |
| 1064 |
} |
| 1065 |
return '5000+'; |
| 1066 |
} |
| 1067 |
|
| 1068 |
/** |
| 1069 |
* Detect state-based events that can't use direct hooks. |
| 1070 |
* |
| 1071 |
* Throttled by a daily transient; uses the request-cached donation |
| 1072 |
* aggregates plus option reads only — no extra queries. The events |
| 1073 |
* tracker dedups, so repeated calls are safe. |
| 1074 |
* |
| 1075 |
* @return void |
| 1076 |
* @since 1.0.0 |
| 1077 |
*/ |
| 1078 |
private function detect_state_events() { |
| 1079 |
if ( get_transient( 'suredonation_state_events_checked' ) ) { |
| 1080 |
return; |
| 1081 |
} |
| 1082 |
|
| 1083 |
$events = self::events(); |
| 1084 |
if ( null === $events ) { |
| 1085 |
return; // Tracker unavailable — retry on next admin load. |
| 1086 |
} |
| 1087 |
|
| 1088 |
// Set only after the tracker is confirmed available. |
| 1089 |
set_transient( 'suredonation_state_events_checked', true, DAY_IN_SECONDS ); |
| 1090 |
|
| 1091 |
$aggregates = $this->get_donation_aggregates(); |
| 1092 |
$mode = Payment_Helper::get_payment_mode(); |
| 1093 |
|
| 1094 |
// plugin_activated: dedup ensures this fires only once. |
| 1095 |
$bsf_referrers = get_option( 'bsf_product_referers', [] ); |
| 1096 |
$source = is_array( $bsf_referrers ) && ! empty( $bsf_referrers['suredonation'] ) |
| 1097 |
? sanitize_text_field( (string) $bsf_referrers['suredonation'] ) |
| 1098 |
: 'self'; |
| 1099 |
$events->track( 'plugin_activated', SUREDONATION_VER, [ 'source' => $source ] ); |
| 1100 |
|
| 1101 |
// plugin_updated: re-track on every version change. |
| 1102 |
$tracked_version = get_option( 'suredonation_tracked_version', '' ); |
| 1103 |
if ( SUREDONATION_VER !== $tracked_version ) { |
| 1104 |
if ( ! empty( $tracked_version ) && is_string( $tracked_version ) ) { |
| 1105 |
$events->flush_pushed( [ 'plugin_updated' ] ); |
| 1106 |
$events->track( 'plugin_updated', SUREDONATION_VER, [ 'from_version' => $tracked_version ] ); |
| 1107 |
} |
| 1108 |
update_option( 'suredonation_tracked_version', SUREDONATION_VER, false ); |
| 1109 |
} |
| 1110 |
|
| 1111 |
// stripe_connected: detect connection state. |
| 1112 |
if ( Stripe_Helper::is_stripe_connected() ) { |
| 1113 |
$events->track( 'stripe_connected', $mode ); |
| 1114 |
} |
| 1115 |
|
| 1116 |
// paypal_connected: detect connection state. |
| 1117 |
if ( PayPal_Helper::is_paypal_connected() ) { |
| 1118 |
$events->track( 'paypal_connected', $mode ); |
| 1119 |
} |
| 1120 |
|
| 1121 |
// payment_mode_live: site switched to live payments. |
| 1122 |
if ( 'live' === $mode ) { |
| 1123 |
$events->track( 'payment_mode_live' ); |
| 1124 |
} |
| 1125 |
|
| 1126 |
// first_donation_received: time-to-value milestone. |
| 1127 |
if ( $aggregates['completed'] > 0 ) { |
| 1128 |
$install_time_raw = get_site_option( 'suredonation_usage_installed_time', 0 ); |
| 1129 |
$install_time = is_numeric( $install_time_raw ) ? (int) $install_time_raw : 0; |
| 1130 |
$days_since_install = $install_time > 0 ? (int) floor( ( time() - $install_time ) / DAY_IN_SECONDS ) : 0; |
| 1131 |
|
| 1132 |
$events->track( |
| 1133 |
'first_donation_received', |
| 1134 |
Payment_Helper::get_currency(), |
| 1135 |
[ |
| 1136 |
'days_since_install' => (string) $days_since_install, |
| 1137 |
'payment_mode' => $mode, |
| 1138 |
] |
| 1139 |
); |
| 1140 |
|
| 1141 |
// first_live_donation_received: first completed LIVE donation. A |
| 1142 |
// separate event with its own dedup key — first_donation_received |
| 1143 |
// almost always fires on a test donation (sites start in test |
| 1144 |
// mode) and the name-only dedup then suppresses it forever, so |
| 1145 |
// the live milestone would otherwise never be visible. Gated on |
| 1146 |
// the donation rows' own payment_mode, not the mode at detection |
| 1147 |
// time, so a later mode switch can't skew the signal. |
| 1148 |
if ( $aggregates['completed_live'] > 0 ) { |
| 1149 |
$events->track( |
| 1150 |
'first_live_donation_received', |
| 1151 |
Payment_Helper::get_currency(), |
| 1152 |
[ |
| 1153 |
'days_since_install' => (string) $days_since_install, |
| 1154 |
] |
| 1155 |
); |
| 1156 |
} |
| 1157 |
} |
| 1158 |
|
| 1159 |
// anonymous_donation_submitted: at least one completed anonymous donation. |
| 1160 |
if ( $aggregates['anonymous_completed'] > 0 ) { |
| 1161 |
$events->track( 'anonymous_donation_submitted' ); |
| 1162 |
} |
| 1163 |
|
| 1164 |
// cover_fees_used: at least one completed donation covered fees. |
| 1165 |
if ( $aggregates['fees_covered_completed'] > 0 ) { |
| 1166 |
$events->track( 'cover_fees_used' ); |
| 1167 |
} |
| 1168 |
|
| 1169 |
// first_refund_processed: at least one (partially) refunded donation. |
| 1170 |
if ( $aggregates['refunded'] > 0 ) { |
| 1171 |
$events->track( 'first_refund_processed' ); |
| 1172 |
} |
| 1173 |
|
| 1174 |
// webhook_configured: a Stripe webhook secret is stored for the current |
| 1175 |
// mode on any connected account (multi-account aware — reading only the |
| 1176 |
// default account would false-negative on sites using a non-default one). |
| 1177 |
$webhook_configured = false; |
| 1178 |
foreach ( array_keys( Stripe_Helper::get_all_accounts() ) as $wh_account_id ) { |
| 1179 |
if ( '' !== Stripe_Helper::get_webhook_secret( $mode, (string) $wh_account_id ) ) { |
| 1180 |
$webhook_configured = true; |
| 1181 |
break; |
| 1182 |
} |
| 1183 |
} |
| 1184 |
if ( $webhook_configured ) { |
| 1185 |
$events->track( 'webhook_configured', $mode ); |
| 1186 |
} |
| 1187 |
} |
| 1188 |
} |
| 1189 |
|