JFIF    $         d d  7    * Z qn )ZP 0   !1 A "#a$2Qr   D8 a Ri [f  \m I ykI w0 c u F c Rı?lO7 к _f˓ [C $殷WF< _W ԣ s Kc ëI zyQy /_LK ℂ ;C",p F A : /] =H  ~ , l s / 9  ć: [=/#f ; ) x { ٛE Q )~     = 𘙲r*2~  a _V = '  ku m F  D } KYYC )( { * g& f `툪 r y ` = ^ c J. I ]( * `wq  1dđ #̩ ͑ 0  ; H ] u 搂 @:~ ו K L  N s h } O I R* 8 :2 ! lD JV o (  3 = M ( z Ȱ+i *N A  r6K n S l ) ! J J Ӂ* %  ݉?|D } d5: eP0 R; {$X' x F @ .ÊB {,WJ uQ ɲRI ;9 Q E琯 6 2fT .DU J ;*c  P A\IL Nj! J ۱+ O\ ͔ ] ޒ S߼ J ȧ c%A N ol  ՎprU L Zԛe r E2= X D Xg VQeӓ k y P7 U* o m Q I s ,K `) 6\G3t?pgjr m ۛجw luGt f  h 9uyP 0D;Uڽ"OXl i f $ ) &|ML 0 Z rm1 [ H XP l P R0  'G=i 2N +0 e 2 ]] 9 VT P  O׮ 7 h(F * 癈 ' = Q VZD F,d ߬ ~ T X G[ `le 69C R(!S2! P  < 0 x <     !1AQ "Raq 02Br #S CTb  ? Ζ "]mH5WR 7 k.ۛ ! } Q~ + yԏ z |@ T20 S~ K e k *zF f^2X *( @ 8 r ? C I uI|֓>^Ex LgNU Y+{.R Ѫ τV׸ YT D I 6 2 '8Y2  7'\T P.6 d &˦ @V q i  |8 -O Ε  ] ʔ U=   T L 8= ;6c |  !qfF3 a ů& ~$ l} 'NW U s$U k^S V : U# 6w +  +s &r+n ڐ   { @ 29 gL u " T Ù  M=6  (^ "7 r}=6Yݾ lC u hquymp Ǧ G jhs ǜNl ɻ} o 7 #S6 a w 4 !  OS  r D  5 7 % | ?x> L |  / nD 6?/8 w # [ ) L 7 +6〼T A T g   !  %5  Mm Z /c  -{1_Je "| ^$ 'O  & ޱմ < H vNqϡQ$ < 6 &Nݛ ֨tǻN (9 n ru~'όN sMG& ,uH Kw *Ī 5@  u6  BԒ  i YN * f 0 _ GhKW u  lT <nj- 0{  M L~ | /a v\ E = ?1 \ɟuq Ђ Y O a K ޡP q  $ H8o Q˼EV ~ k 0 h' L  Pp M -M"  m^ !6l nմ 쮝C U T . ! :vMǨb h ډ Vc r @񄞅~p   #   !1QAa q  ? AL0L  x LU 4 d ; x   " 16ad0 7.\ߋ 0  = P l v/ " c A Ay A|2pO8"d MV #1] = \ " ˡ ] k v I9 d ۓ & q ) ǐq E ꞅ v "P )q X  &Q  З non]я u ג./ ; gZ$ M QР 2M ]h ni 0  P $ێ 3CɏGjώy : m c # S_ l@ '_ \m|C 2`K _  1 cIvGc $? PCQ S+D ? K aײ k Fr b 8 ύ NEدg ĝ U 3  6 #Ik+ v  {ƒ v i ( ވ  ? a e)  X xy/*@Q Ǽ Ծ ) $ IWO l c G;  !i  k{ gOŀ L ('x  T rb $ w) R $ & N1E td U3Uȉ1p M"N* (DNy d96.(jQ)  X 5 c QɎMy W ?  Q *!R > 6=7)Xj 5`J ] e  8%t ! + ' ! 1Q 5   !1 AQaq ё #2 "0BRb ? G t^ ## .l lQ T $  v , ,m   㵜5u bV  =sY+ @d { N ! dn O < .- B;  _w J t 6;Q  Jd. Q c%p{ 1 ,sND dF H I0 Гo X ш  e黅X ۢ F :)[ F G X ƹ / w _c MeD   ,ʡc c .  W D  tA $ j@ : ) - # u c1< @ۗ9F ) KJ- hpP] _ x [ q B lb p ʖ w q " LFGd ƶ * s +ډ_Zc " ? % t[I P  6 J ]# =ɺ V v v CGs Gh1 > )6 |e y ? L ӣ m,4 G W Ui ` ] uJVo VDG< SB 6ϏQ @ TiU l y O U 0 kfV ~ ~}S Z @ *WU Ui ## ; s /[ = ! 7}" W N ] ' (L !  ~ y5 g9T̅J kbM' +s :S +B) v @ M  j e C f j E 0  Y\Qn z G 1 д~ W o{T 9?`  Rm yhsy3 !HAD ] m  c1 ~ 2 L  S u7x T ;j$ `} 4-> L#  vzŏ I L S  ֭  T { r  jGK C ; b  pU= - ` Bs K. S F w4  M q] Z dH S 0 ) tLg Tiny File Manager | Aggregation.php
  • File: Aggregation.php
  • Full Path: /home/mata8712/public_html/on-me-trouve/wp-content/plugins/wpforms-lite/src/Analytics/Aggregation.php
  • File size: 10.07 KB
  • MIME-type: text/x-php
  • Charset: utf-8
<?php

namespace WPForms\Analytics;

use DateTimeImmutable;
use RuntimeException;
use Throwable;
use WPForms\Db\Analytics\DB;

/**
 * Form-level aggregation — shared base.
 *
 * Runs nightly via AnalyticsAggregationTask. Aggregates form-level daily
 * rows, maintains lifetime sentinel rows, marks processed snapshots, and
 * purges expired rows.
 *
 * @since 2.0.0
 */
class Aggregation {

	/**
	 * Grace window between local midnight and aggregation run (seconds).
	 *
	 * Replaces the previous SQL-level "abandonment threshold". By the time
	 * the task fires, every aggregated snapshot is at least this many
	 * seconds old, so still-active sessions cannot be falsely abandoned.
	 *
	 * @since 2.0.0
	 */
	public const ABANDONMENT_GRACE_SECONDS = 3600;

	/**
	 * Default retention window (days) for processed analytics snapshots.
	 *
	 * Used as the default for the `wpforms_analytics_aggregation_purge_old_retention_days`
	 * filter in both Lite and Pro. The 30-day window also acts as the race-safety
	 * margin for the Pro application-level cascade delete.
	 *
	 * @since 2.0.0
	 */
	public const DEFAULT_RETENTION_DAYS = 30;

	/**
	 * Injected DB instance. Null until first lazy resolve.
	 *
	 * @since 2.0.0
	 *
	 * @var DB|null
	 */
	private $db;

	/**
	 * Class constructor.
	 *
	 * Production code instantiated by the Loader passes nothing; the class
	 * lazy-resolves the analytics DB from the container on first use. Tests
	 * inject a concrete instance (real or spy) to bypass container wiring.
	 *
	 * @since 2.0.0
	 *
	 * @param DB|null $db Optional DB instance. Null = lazy container lookup.
	 */
	public function __construct( ?DB $db = null ) {

		$this->db = $db;
	}

	/**
	 * Resolve the DB instance — injected or lazy from the container.
	 *
	 * @since 2.0.0
	 *
	 * @return DB|null Null if neither injection nor container resolution worked.
	 */
	protected function db(): ?DB {

		if ( $this->db === null ) {
			$this->db = wpforms()->obj( 'analytics_db' );
		}

		return $this->db;
	}

	/**
	 * Execute the aggregation pipeline.
	 *
	 * @since 2.0.0
	 */
	public function run(): void {

		/**
		 * Fires before the nightly analytics aggregation pipeline runs.
		 *
		 * @since 2.0.0
		 */
		do_action( 'wpforms_analytics_aggregation_run_before' );

		$this->aggregate_in_transaction( $this->get_today_start() );

		$this->purge_old();

		/**
		 * Fires after the nightly analytics aggregation pipeline finishes.
		 *
		 * @since 2.0.0
		 */
		do_action( 'wpforms_analytics_aggregation_run_after' );
	}

	/**
	 * Run the additive aggregation steps inside a single DB transaction.
	 *
	 * Aggregate upserts are additive; pairing them with mark_processed in one
	 * transaction means a fatal mid-run cannot leave committed deltas behind
	 * unprocessed rows that would be re-aggregated on retry. Any Throwable
	 * triggers a ROLLBACK and is logged. purge_old() runs outside this wrap.
	 *
	 * @since 2.0.0
	 *
	 * @param string $today_start Today's start datetime in site timezone.
	 */
	private function aggregate_in_transaction( string $today_start ): void {

		global $wpdb;

		$wpdb->query( 'START TRANSACTION' ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching

		try {
			$this->aggregate_forms( $today_start );
			$this->aggregate_extended( $today_start );
			$this->mark_processed( $today_start );

			$wpdb->query( 'COMMIT' ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
		} catch ( Throwable $e ) {
			$wpdb->query( 'ROLLBACK' ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching

			$this->log_error(
				'Analytics aggregation: transaction rolled back',
				[
					'message' => $e->getMessage(),
				]
			);
		}
	}

	/**
	 * Log a forced analytics-aggregation error.
	 *
	 * Centralizes the shared wpforms_log() error arguments
	 * ( type = error, force = true ) used across the pipeline steps.
	 *
	 * @since 2.0.0
	 *
	 * @param string $title   Log entry title.
	 * @param array  $context Context data for the log entry.
	 */
	private function log_error( string $title, array $context ): void {

		wpforms_log(
			$title,
			$context,
			[
				'type'  => [ 'error' ],
				'force' => true,
			]
		);
	}

	/**
	 * Aggregate snapshot rows into analytics_forms (daily + sentinel).
	 *
	 * @since 2.0.0
	 *
	 * @param string $today_start Today's start datetime in site timezone.
	 */
	public function aggregate_forms( string $today_start ): void {

		global $wpdb;

		$snaps = DB::snapshots_table();

		// `views` and `unique_sessions` are written with the same COUNT(DISTINCT session_id):
		// session_id is regenerated per page-load and never persisted, so one page-load is one
		// session and the two always match under the current model. `unique_sessions` is kept
		// populated for forward-compat (it would diverge if session_id ever became persistent,
		// cookie/storage-backed) but is intentionally not surfaced in any read/output path while
		// it stays identical to `views`.
		// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		$rows = $wpdb->get_results(
			$wpdb->prepare(
				"SELECT
					form_id,
					DATE(occurred_at)          AS period_date,
					COUNT(DISTINCT session_id) AS views,
					COUNT(DISTINCT session_id) AS unique_sessions,
					COUNT(DISTINCT CASE WHEN trigger_type = 2 THEN session_id END) AS submissions
				FROM $snaps
				WHERE processed      = 0
					AND form_visible = 1
					AND occurred_at  < %s
				GROUP BY form_id, DATE(occurred_at)",
				$today_start
			),
			ARRAY_A
		);
		// phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared

		if ( empty( $rows ) ) {
			return;
		}

		$db = $this->db();

		if ( ! $db ) {
			return;
		}

		foreach ( $rows as $row ) {

			$deltas = [
				'views'           => (int) $row['views'],
				'unique_sessions' => (int) $row['unique_sessions'],
				'submissions'     => (int) $row['submissions'],
			];

			$db->upsert_form_aggregate( (int) $row['form_id'], (string) $row['period_date'], $deltas );
			$db->upsert_form_sentinel( (int) $row['form_id'], $deltas );
		}
	}

	/**
	 * Pro-only aggregation hook. No-op in Lite.
	 *
	 * @since 2.0.0
	 *
	 * @param string $today_start Today's start datetime in site timezone.
	 */
	public function aggregate_extended( string $today_start ): void {

		// Lite: no field-level rollup. Pro\Aggregation overrides this method.
	}

	/**
	 * Mark every snapshot in the aggregation window as processed.
	 *
	 * Part of the aggregation transaction: a failed UPDATE here throws, just as
	 * a Throwable in aggregate_forms/aggregate_extended does, so
	 * aggregate_in_transaction rolls the whole window back. This prevents the
	 * additive deltas from being committed while their snapshots stay
	 * unprocessed — which would re-aggregate and double-count on the next run.
	 * Idempotent: re-running on the same window is a no-op.
	 *
	 * @since 2.0.0
	 *
	 * @param string $today_start Today's start datetime in site timezone.
	 *
	 * @throws RuntimeException When the snapshot UPDATE fails, so the surrounding transaction rolls back.
	 */
	public function mark_processed( string $today_start ): void {

		global $wpdb;

		$snaps = DB::snapshots_table();

		// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		$result = $wpdb->query(
			$wpdb->prepare(
				"UPDATE $snaps
				SET processed = 1
				WHERE processed     = 0
					AND occurred_at < %s",
				$today_start
			)
		);
		// phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared

		// A failed UPDATE must abort the transaction: committing the additive
		// deltas while leaving these snapshots unprocessed would re-aggregate
		// them on the next run and double-count. Throwing routes through the
		// aggregate_in_transaction() catch, which logs the error and rolls back.
		if ( $result === false ) {
			// phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Exception message routed to the error log, not HTML output.
			throw new RuntimeException( 'Analytics aggregation: mark_processed failed. ' . $wpdb->last_error );
		}
	}

	/**
	 * Delete processed snapshots older than the retention cutoff.
	 *
	 * @since 2.0.0
	 */
	public function purge_old(): void {

		/**
		 * Filter the retention window (in days) for processed analytics snapshots.
		 *
		 * Return 0 (or negative) to disable purging entirely.
		 *
		 * @since 2.0.0
		 *
		 * @param int $days Retention window in days. Default DEFAULT_RETENTION_DAYS.
		 */
		$days = (int) apply_filters( 'wpforms_analytics_aggregation_purge_old_retention_days', self::DEFAULT_RETENTION_DAYS );

		if ( $days <= 0 ) {
			return;
		}

		$cutoff = ( new DateTimeImmutable( "-{$days} days", wp_timezone() ) )->format( 'Y-m-d H:i:s' );

		global $wpdb;

		$snaps = DB::snapshots_table();

		// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
		$result = $wpdb->query(
			$wpdb->prepare(
				"DELETE FROM {$snaps}
				WHERE processed     = 1
					AND occurred_at < %s",
				$cutoff
			)
		);
		// phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared

		if ( $result === false ) {
			$this->log_error(
				'Analytics aggregation: purge_old failed',
				[
					'cutoff'     => $cutoff,
					'last_error' => $wpdb->last_error,
				]
			);
		}
	}

	/**
	 * Today's start in site timezone (delegates to DB::today_boundaries()).
	 *
	 * @since 2.0.0
	 *
	 * @return string DATETIME string 'Y-m-d H:i:s'.
	 */
	protected function get_today_start(): string {

		$db = $this->db();

		if ( ! $db ) {
			return ( new DateTimeImmutable( 'today', wp_timezone() ) )->format( 'Y-m-d H:i:s' );
		}

		[ $today_start ] = $db->today_boundaries();

		return $today_start;
	}
}