Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
62.56% covered (warning)
62.56%
132 / 211
17.39% covered (danger)
17.39%
4 / 23
CRAP
0.00% covered (danger)
0.00%
0 / 1
Tracks
62.56% covered (warning)
62.56%
132 / 211
17.39% covered (danger)
17.39%
4 / 23
525.63
0.00% covered (danger)
0.00%
0 / 1
 init
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
6
 record_episode_published
86.96% covered (warning)
86.96%
40 / 46
0.00% covered (danger)
0.00%
0 / 1
16.57
 record_media_uploaded
80.00% covered (warning)
80.00%
16 / 20
0.00% covered (danger)
0.00%
0 / 1
11.97
 record_category_added
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
2.15
 record_category_updated
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
2.15
 record_show_url_added
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 record_show_url_updated
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 maybe_record_show_url_addition
83.33% covered (warning)
83.33%
15 / 18
0.00% covered (danger)
0.00%
0 / 1
9.37
 record_setting_added
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 record_setting_updated
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 maybe_record_setting_first_saved
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
20
 filled_setting_count
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
12
 has_value
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
12
 set_surface_from_route
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
20
 clear_surface
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 platform
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
3.14
 current_product_slug
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
3.14
 maybe_record_status_change
94.74% covered (success)
94.74%
18 / 19
0.00% covered (danger)
0.00%
0 / 1
6.01
 bump_stat
30.00% covered (danger)
30.00%
3 / 10
0.00% covered (danger)
0.00%
0 / 1
9.49
 identity_for_post
40.00% covered (danger)
40.00%
2 / 5
0.00% covered (danger)
0.00%
0 / 1
4.94
 has_podcast_media
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
 is_first_episode_for_site
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
1
 record_event
54.55% covered (warning)
54.55%
6 / 11
0.00% covered (danger)
0.00%
0 / 1
9.38
1<?php
2/**
3 * Tracks instrumentation for Jetpack Podcast.
4 *
5 * @package automattic/jetpack-podcast
6 */
7
8declare( strict_types = 1 );
9
10namespace Automattic\Jetpack\Podcast;
11
12use Automattic\Jetpack\A8c_Mc_Stats;
13use Automattic\Jetpack\Connection\Manager as Connection_Manager;
14use Automattic\Jetpack\Podcast\Feed\Customize_Feed;
15use Automattic\Jetpack\Podcast\Feed\Episode_Block_Tags;
16use Automattic\Jetpack\Status\Host;
17use Throwable;
18use WP_Post;
19use WP_Query;
20use WP_REST_Request;
21use WP_User;
22
23/**
24 * Records podcast lifecycle events. Event names stay `wpcom_*` so analytics
25 * queries cover Simple, Atomic, and self-hosted Jetpack feeds without a rewrite.
26 * Dispatch tries `tracks_record_event` (Simple) and falls back to
27 * `\Automattic\Jetpack\Tracking::tracks_record_event` (Atomic). Neither is a
28 * hard dep — silently no-ops when neither is reachable.
29 */
30class Tracks {
31
32    /**
33     * Mirrors `getValidationIssues()` in
34     * `src/dashboard/hooks/use-validation-issues.ts` — keep the two in step.
35     * Not the directory-submission bar, which also wants an episode and a
36     * conforming cover.
37     *
38     * @var string[]
39     */
40    private const SETUP_OPTIONS = array(
41        'podcasting_category_id',
42        'podcasting_title',
43        'podcasting_summary',
44        'podcasting_talent_name',
45        'podcasting_email',
46        'podcasting_category_1',
47        'podcasting_image',
48    );
49
50    /**
51     * What is driving the option write in flight. Option hooks fire
52     * synchronously inside `update_option()`, so the value set for the
53     * dispatching route is the one the recorder reads.
54     *
55     * @var string
56     */
57    private static $surface = 'programmatic';
58
59    /**
60     * Wire the recorder hooks.
61     */
62    public static function init(): void {
63        // `wp_after_insert_post` runs after terms + meta are saved — required
64        // because Gutenberg/REST publishes set terms after `transition_post_status`.
65        add_action( 'wp_after_insert_post', array( __CLASS__, 'record_episode_published' ), 10, 4 );
66
67        add_action( 'add_attachment', array( __CLASS__, 'record_media_uploaded' ) );
68
69        add_action( 'add_option_podcasting_category_id', array( __CLASS__, 'record_category_added' ), 10, 2 );
70        add_action( 'update_option_podcasting_category_id', array( __CLASS__, 'record_category_updated' ), 10, 3 );
71
72        add_action( 'add_option_podcasting_show_urls', array( __CLASS__, 'record_show_url_added' ), 10, 2 );
73        add_action( 'update_option_podcasting_show_urls', array( __CLASS__, 'record_show_url_updated' ), 10, 3 );
74
75        // The options rather than the endpoint's `jetpack_podcast_settings_saved`,
76        // so setup lands whichever path writes it. `podcasting_category_id`
77        // intentionally overlaps `status_changed` above, which stays canonical
78        // for "site enabled podcasting".
79        foreach ( self::SETUP_OPTIONS as $option ) {
80            add_action( "add_option_{$option}", array( __CLASS__, 'record_setting_added' ), 10, 2 );
81            add_action( "update_option_{$option}", array( __CLASS__, 'record_setting_updated' ), 10, 3 );
82        }
83
84        add_filter( 'rest_request_before_callbacks', array( __CLASS__, 'set_surface_from_route' ), 10, 3 );
85        add_filter( 'rest_request_after_callbacks', array( __CLASS__, 'clear_surface' ) );
86    }
87
88    /**
89     * Emit `wpcom_podcast_episode_published` (and `wpcom_podcast_show_launched`
90     * once per site) when a podcast-category post enters `publish`.
91     *
92     * @param int          $post_id     Post ID.
93     * @param WP_Post|null $post        Post object.
94     * @param bool         $update      Whether this is an update.
95     * @param WP_Post|null $post_before Previous post state.
96     */
97    public static function record_episode_published( $post_id, $post, $update, $post_before ): void {
98        unset( $post_id, $update );
99
100        try {
101            if ( ! $post instanceof WP_Post ) {
102                return;
103            }
104
105            if ( 'publish' !== $post->post_status ) {
106                return;
107            }
108
109            if ( $post_before instanceof WP_Post && 'publish' === $post_before->post_status ) {
110                return;
111            }
112
113            if ( defined( 'WP_IMPORTING' ) && WP_IMPORTING ) {
114                return;
115            }
116
117            // @phan-suppress-next-line PhanUndeclaredFunction -- wpcom Simple-only; guarded above.
118            if ( function_exists( 'is_headstart_post' ) && is_headstart_post( $post ) ) {
119                return;
120            }
121
122            if ( in_array( $post->post_type, array( 'attachment', 'revision', 'nav_menu_item' ), true ) ) {
123                return;
124            }
125
126            $category_id = Customize_Feed::resolve_category_id();
127            if ( 0 === $category_id ) {
128                return;
129            }
130
131            if ( ! in_category( $category_id, $post ) ) {
132                return;
133            }
134
135            // Match the RSS feed's definition of an episode — must carry
136            // audio, not just sit in the podcast category.
137            if ( ! self::has_podcast_media( $post ) ) {
138                self::record_event(
139                    'wpcom_podcast_episode_missing_media',
140                    array(
141                        'post_id'                   => (int) $post->ID,
142                        'is_first_episode_for_site' => self::is_first_episode_for_site( $category_id, (int) $post->ID ),
143                    ),
144                    self::identity_for_post( $post )
145                );
146                return;
147            }
148
149            $is_first = self::is_first_episode_for_site( $category_id, (int) $post->ID );
150
151            self::record_event(
152                'wpcom_podcast_episode_published',
153                array(
154                    'post_id'                   => (int) $post->ID,
155                    'is_first_episode_for_site' => $is_first,
156                ),
157                self::identity_for_post( $post )
158            );
159            self::bump_stat( 'wpcom-podcast-episodes', 'published' );
160
161            // Atomic INSERT — only one concurrent caller per site wins, so
162            // `show_launched` fires exactly once per site.
163            if ( $is_first && add_option( 'podcast_show_launched_tracked', time(), '', false ) ) {
164                self::record_event(
165                    'wpcom_podcast_show_launched',
166                    array( 'post_id' => (int) $post->ID ),
167                    self::identity_for_post( $post )
168                );
169                self::bump_stat( 'wpcom-podcast-episodes', 'show-launched' );
170            }
171        } catch ( Throwable $e ) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedCatch
172            // Tracks is best-effort — never break a publish.
173        }
174    }
175
176    /**
177     * Emit `wpcom_podcast_media_uploaded` for audio/video attachments on a
178     * podcasting-enabled site.
179     *
180     * @param int $attachment_id Attachment post ID.
181     */
182    public static function record_media_uploaded( $attachment_id ): void {
183        try {
184            if ( defined( 'WP_IMPORTING' ) && WP_IMPORTING ) {
185                return;
186            }
187
188            $attachment = get_post( (int) $attachment_id );
189            // @phan-suppress-next-line PhanUndeclaredFunction -- wpcom Simple-only; guarded above.
190            if ( $attachment && function_exists( 'is_headstart_post' ) && is_headstart_post( $attachment ) ) {
191                return;
192            }
193
194            if ( 0 === Customize_Feed::resolve_category_id() ) {
195                return;
196            }
197
198            $mime_type = (string) get_post_mime_type( (int) $attachment_id );
199            if ( '' === $mime_type ) {
200                return;
201            }
202            if ( 0 !== strpos( $mime_type, 'audio/' ) && 0 !== strpos( $mime_type, 'video/' ) ) {
203                return;
204            }
205
206            self::record_event(
207                'wpcom_podcast_media_uploaded',
208                array(
209                    'attachment_id' => (int) $attachment_id,
210                    'mime_type'     => $mime_type,
211                )
212            );
213        } catch ( Throwable $e ) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedCatch
214            // Tracks is best-effort.
215        }
216    }
217
218    /**
219     * `add_option_podcasting_category_id` callback — first-ever write of the
220     * option (previous value treated as 0).
221     *
222     * @param string $option Option name.
223     * @param mixed  $value  Newly stored value.
224     */
225    public static function record_category_added( $option, $value ): void {
226        unset( $option );
227
228        try {
229            self::maybe_record_status_change( 0, (int) $value );
230        } catch ( Throwable $e ) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedCatch
231            // Tracks is best-effort.
232        }
233    }
234
235    /**
236     * `update_option_podcasting_category_id` callback — every change to an
237     * existing row.
238     *
239     * @param mixed  $old_value Previous stored value.
240     * @param mixed  $value     Newly stored value.
241     * @param string $option    Option name.
242     */
243    public static function record_category_updated( $old_value, $value, $option ): void {
244        unset( $option );
245
246        try {
247            self::maybe_record_status_change( (int) $old_value, (int) $value );
248        } catch ( Throwable $e ) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedCatch
249            // Tracks is best-effort.
250        }
251    }
252
253    /**
254     * `add_option_podcasting_show_urls` callback. No prior row exists, so
255     * every entry is a first-time entry.
256     *
257     * @param string $option    Option name.
258     * @param mixed  $new_value Newly stored value.
259     */
260    public static function record_show_url_added( $option, $new_value ): void {
261        unset( $option );
262        self::maybe_record_show_url_addition( array(), $new_value );
263    }
264
265    /**
266     * `update_option_podcasting_show_urls` callback. Compare the new value
267     * against the prior array to find the first directory that transitioned
268     * from absent/empty to a non-empty URL.
269     *
270     * @param mixed  $old_value Previous stored value (expected: array).
271     * @param mixed  $new_value Newly stored value.
272     * @param string $option    Option name.
273     */
274    public static function record_show_url_updated( $old_value, $new_value, $option ): void {
275        unset( $option );
276        self::maybe_record_show_url_addition( is_array( $old_value ) ? $old_value : array(), $new_value );
277    }
278
279    /**
280     * Emit `wpcom_podcasting_show_url_saved` for the first podcatcher key
281     * that transitions from absent/empty to a non-empty string.
282     *
283     * @param array $old_value Previous map of directory => url.
284     * @param mixed $new_value Newly stored value.
285     */
286    private static function maybe_record_show_url_addition( array $old_value, $new_value ): void {
287        try {
288            if ( ! is_array( $new_value ) ) {
289                return;
290            }
291
292            foreach ( $new_value as $app => $url ) {
293                if ( ! is_string( $url ) || '' === $url ) {
294                    continue;
295                }
296
297                $previous = isset( $old_value[ $app ] ) && is_string( $old_value[ $app ] ) ? $old_value[ $app ] : '';
298                if ( '' !== $previous ) {
299                    continue;
300                }
301
302                self::record_event(
303                    'wpcom_podcasting_show_url_saved',
304                    array(
305                        'app'     => (string) $app,
306                        'surface' => self::$surface,
307                    )
308                );
309                self::bump_stat( 'wpcom-podcast-distribution', (string) $app );
310                return;
311            }
312        } catch ( Throwable $e ) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedCatch
313            // Tracks is best-effort.
314        }
315    }
316
317    /**
318     * `add_option_{$option}` callback for a required setting. No prior row, so
319     * the previous value is empty by definition.
320     *
321     * @param string $option Option name.
322     * @param mixed  $value  Stored value.
323     */
324    public static function record_setting_added( $option, $value ): void {
325        self::maybe_record_setting_first_saved( (string) $option, '', $value );
326    }
327
328    /**
329     * `update_option_{$option}` callback for a required setting. Seldom the live
330     * path: `update_option()` defers to `add_option()` while the stored value
331     * still equals the registered empty default.
332     *
333     * @param mixed  $old_value Previous stored value.
334     * @param mixed  $new_value Newly stored value.
335     * @param string $option    Option name.
336     */
337    public static function record_setting_updated( $old_value, $new_value, $option ): void {
338        self::maybe_record_setting_first_saved( (string) $option, $old_value, $new_value );
339    }
340
341    /**
342     * Emit `wpcom_podcast_setting_first_saved` when a required setting picks up
343     * a value for the first time.
344     *
345     * Recording only the empty → filled transition bounds this at one event per
346     * setting instead of one per save, and keeps sites configured before it
347     * shipped silent rather than reporting a false completion. `is_complete`
348     * marks the transition that finished the set.
349     *
350     * @param string $option    Option name.
351     * @param mixed  $old_value Previous stored value.
352     * @param mixed  $new_value Newly stored value.
353     */
354    private static function maybe_record_setting_first_saved( string $option, $old_value, $new_value ): void {
355        try {
356            if ( self::has_value( $old_value ) || ! self::has_value( $new_value ) ) {
357                return;
358            }
359
360            // Both hooks fire after the write, so this counts the new value too.
361            $filled_count = self::filled_setting_count();
362
363            self::record_event(
364                'wpcom_podcast_setting_first_saved',
365                array(
366                    'setting'      => $option,
367                    'filled_count' => $filled_count,
368                    'is_complete'  => count( self::SETUP_OPTIONS ) === $filled_count,
369                    'surface'      => self::$surface,
370                    'user_id'      => (int) get_current_user_id(),
371                    'product_slug' => self::current_product_slug(),
372                )
373            );
374        } catch ( Throwable $e ) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedCatch
375            // Tracks is best-effort — never break a settings save.
376        }
377    }
378
379    /**
380     * How many required settings currently hold a value.
381     */
382    private static function filled_setting_count(): int {
383        $filled = 0;
384
385        foreach ( self::SETUP_OPTIONS as $option ) {
386            if ( self::has_value( get_option( $option, '' ) ) ) {
387                ++$filled;
388            }
389        }
390
391        return $filled;
392    }
393
394    /**
395     * Whether a required setting counts as filled in. Options read back as
396     * strings, so one rule covers both shapes: blank for the text fields, `'0'`
397     * for `podcasting_category_id`, where 0 is the disabled sentinel.
398     *
399     * @param mixed $value Value to test.
400     */
401    private static function has_value( $value ): bool {
402        $value = is_scalar( $value ) ? trim( (string) $value ) : '';
403
404        return '' !== $value && '0' !== $value;
405    }
406
407    /**
408     * Label writes made by the dashboard's own REST routes. Derived from the
409     * route rather than set by the endpoints, so nothing outside this class
410     * sits in a save path holding a reference to it.
411     *
412     * @param mixed $response Passed through untouched.
413     * @param array $handler  Unused.
414     * @param mixed $request  Request being dispatched.
415     * @return mixed
416     */
417    public static function set_surface_from_route( $response, $handler, $request ) {
418        unset( $handler );
419
420        if ( ! $request instanceof WP_REST_Request ) {
421            return $response;
422        }
423
424        $route = (string) $request->get_route();
425
426        if ( 0 === strpos( $route, '/wpcom/v2/podcast/settings' ) ) {
427            self::$surface = 'settings_rest';
428        } elseif ( 0 === strpos( $route, '/wpcom/v2/podcast-distribution/' ) ) {
429            self::$surface = 'distribution_rest';
430        }
431
432        return $response;
433    }
434
435    /**
436     * Reset once the route's callback is done, so a nested subrequest doesn't
437     * leave its surface set for the rest of the request.
438     *
439     * @param mixed $response Passed through untouched.
440     * @return mixed
441     */
442    public static function clear_surface( $response ) {
443        self::$surface = 'programmatic';
444
445        return $response;
446    }
447
448    /**
449     * Host the event came from. Plan slug is a lossy proxy — Atomic reports a
450     * WordPress.com plan server-side and a Jetpack one client-side.
451     */
452    private static function platform(): string {
453        $host = new Host();
454
455        if ( $host->is_wpcom_simple() ) {
456            return 'simple';
457        }
458
459        return $host->is_woa_site() ? 'atomic' : 'self_hosted';
460    }
461
462    /**
463     * Current plan slug. `WPCOM_Store_API` on Simple, `Current_Plan` on Atomic
464     * and self-hosted — same dual pattern as
465     * `Masterbar\Dashboard_Switcher_Tracking::get_plan()`.
466     */
467    private static function current_product_slug(): string {
468        $plan = class_exists( '\WPCOM_Store_API' )
469            ? \WPCOM_Store_API::get_current_plan( (int) get_current_blog_id() )
470            : ( class_exists( '\Automattic\Jetpack\Current_Plan' ) ? \Automattic\Jetpack\Current_Plan::get() : array() );
471
472        return (string) ( $plan['product_slug'] ?? '' );
473    }
474
475    /**
476     * Emit `wpcom_podcasting_status_changed` (enabled / disabled / changed)
477     * when the `podcasting_category_id` option transitions.
478     *
479     * @param int $old_value Previous category ID (0 == disabled).
480     * @param int $new_value New category ID (0 == disabled).
481     */
482    private static function maybe_record_status_change( int $old_value, int $new_value ): void {
483        if ( $old_value === $new_value ) {
484            return;
485        }
486
487        if ( 0 === $old_value && 0 !== $new_value ) {
488            $status = 'enabled';
489        } elseif ( 0 !== $old_value && 0 === $new_value ) {
490            $status = 'disabled';
491        } else {
492            $status = 'changed';
493        }
494
495        self::record_event(
496            'wpcom_podcasting_status_changed',
497            array(
498                'status'               => $status,
499                'surface'              => self::$surface,
500                'previous_category_id' => $old_value,
501                'new_category_id'      => $new_value,
502                'user_id'              => (int) get_current_user_id(),
503                'product_slug'         => self::current_product_slug(),
504            )
505        );
506
507        self::bump_stat( 'wpcom-podcasting-status', $status );
508    }
509
510    /**
511     * Bump a Mission Control stat. Calls `bump_stats_extras` directly on
512     * Simple; elsewhere pings the pixel so Atomic and self-hosted count too.
513     * The URL is built with the bare group rather than `A8c_Mc_Stats::add()`,
514     * whose `x_jetpack-` prefix would file the pixel bumps under a second name.
515     *
516     * @param string $group Stat group.
517     * @param string $bin   Stat name within the group.
518     */
519    private static function bump_stat( string $group, string $bin ): void {
520        try {
521            if ( function_exists( 'bump_stats_extras' ) ) {
522                bump_stats_extras( $group, $bin );
523                return;
524            }
525
526            $stats = new A8c_Mc_Stats();
527            $url   = $stats->build_stats_url( array( "x_{$group}" => $bin ) );
528            // An older copy of the package may be loaded by another plugin.
529            if ( method_exists( $stats, 'do_server_side_stat_without_waiting' ) ) {
530                $stats->do_server_side_stat_without_waiting( $url );
531            } else {
532                $stats->do_server_side_stat( $url );
533            }
534        } catch ( Throwable $e ) {
535            unset( $e );
536        }
537    }
538
539    /**
540     * Identity for the publish event. Scheduled/cron publishes have no
541     * logged-in user — fall back to the post author.
542     *
543     * @param WP_Post $post Post being published.
544     */
545    private static function identity_for_post( WP_Post $post ): WP_User {
546        if ( ! empty( $post->post_author ) ) {
547            $user = get_userdata( (int) $post->post_author );
548            if ( $user instanceof WP_User ) {
549                return $user;
550            }
551        }
552        return wp_get_current_user();
553    }
554
555    /**
556     * Filters out posts in the podcast category that aren't actually episodes.
557     * Covers all three authoring paths: the `jetpack/podcast-episode` block
558     * (the paid path — media lives in its `mediaUrl` attr, often an external or
559     * unattached URL that the two checks below miss), the `core/audio` block,
560     * and classic-editor attached audio.
561     *
562     * @param WP_Post $post Post being checked.
563     */
564    private static function has_podcast_media( WP_Post $post ): bool {
565        $attrs = Episode_Block_Tags::get_block_attrs( $post );
566        if ( ! empty( $attrs['mediaUrl'] ) ) {
567            return true;
568        }
569
570        return has_block( 'core/audio', $post )
571            || ! empty( get_attached_media( 'audio', $post->ID ) );
572    }
573
574    /**
575     * True when no other published post exists in the podcast category.
576     *
577     * @param int $category_id     Configured podcast category ID.
578     * @param int $current_post_id Post being published (excluded from the check).
579     */
580    private static function is_first_episode_for_site( int $category_id, int $current_post_id ): bool {
581        $existing = new WP_Query(
582            array(
583                'post_status'      => 'publish',
584                'post_type'        => 'post',
585                'cat'              => $category_id,
586                'post__not_in'     => array( $current_post_id ),
587                'posts_per_page'   => 1,
588                'fields'           => 'ids',
589                'no_found_rows'    => true,
590                'suppress_filters' => true,
591            )
592        );
593
594        return empty( $existing->posts );
595    }
596
597    /**
598     * Dispatch a tracks event. Auto-injects `blog_id` and defaults `$user`
599     * to the current user.
600     *
601     * @param string       $event_name Tracks event name.
602     * @param array        $properties Event properties.
603     * @param WP_User|null $user       Identity override; defaults to current user.
604     * @return mixed
605     */
606    private static function record_event( string $event_name, array $properties, ?WP_User $user = null ) {
607        try {
608            $user                 ??= wp_get_current_user();
609            $properties['blog_id']  = (int) Connection_Manager::get_site_id( true );
610            $properties['platform'] = self::platform();
611
612            if ( ! function_exists( 'tracks_record_event' ) && function_exists( 'require_lib' ) ) {
613                require_lib( 'tracks/client' );
614            }
615
616            if ( function_exists( 'tracks_record_event' ) ) {
617                return tracks_record_event( $user, $event_name, $properties );
618            }
619
620            if ( class_exists( '\Automattic\Jetpack\Tracking' ) ) {
621                return ( new \Automattic\Jetpack\Tracking() )->tracks_record_event( $user, $event_name, $properties );
622            }
623        } catch ( Throwable $e ) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedCatch
624            // Tracks is best-effort.
625        }
626
627        return null;
628    }
629}