Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
96.18% covered (success)
96.18%
151 / 157
71.43% covered (warning)
71.43%
10 / 14
CRAP
0.00% covered (danger)
0.00%
0 / 1
Tracking_Pixel
96.18% covered (success)
96.18%
151 / 157
71.43% covered (warning)
71.43%
10 / 14
69
0.00% covered (danger)
0.00%
0 / 1
 build_view_data
100.00% covered (success)
100.00%
50 / 50
100.00% covered (success)
100.00%
1 / 1
22
 build_search_filters
95.45% covered (success)
95.45%
21 / 22
0.00% covered (danger)
0.00%
0 / 1
11
 build_stats_details
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
2
 build_consent_gate
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 add_low_fetchpriority
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 remove_stats_dns_prefetch
94.44% covered (success)
94.44%
17 / 18
0.00% covered (danger)
0.00%
0 / 1
9.01
 enqueue_stats_script
95.45% covered (success)
95.45%
21 / 22
0.00% covered (danger)
0.00%
0 / 1
2
 get_amp_pixel_url
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
 add_amp_pixel
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 print_amp_pixel
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
4
 add_amp_consent_sanitizer
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 add_to_footer
n/a
0 / 0
n/a
0 / 0
1
 get_footer_to_add
n/a
0 / 0
n/a
0 / 0
1
 render_footer
n/a
0 / 0
n/a
0 / 0
1
 render_amp_footer
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 stats_array_to_string
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 is_amp_request
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
4
1<?php
2/**
3 * Stats Tracking_Pixel
4 *
5 * @package automattic/jetpack-stats
6 */
7
8namespace Automattic\Jetpack\Stats;
9
10use Jetpack_Options;
11use WP_Post;
12
13/**
14 * Stats Tracking_Pixel class.
15 *
16 * Responsible for embedding the Stats tracking pixel.
17 *
18 * @since 0.1.0
19 */
20class Tracking_Pixel {
21
22    /**
23     * Array name.
24     *
25     * @var string $array_name The 'stats' array name
26     */
27    const STATS_ARRAY_TO_STRING_FILTER = 'stats_array';
28
29    /**
30     * Where the AMP pixel sends views, which AMP_Consent_Sanitizer matches on.
31     *
32     * @var string
33     */
34    const AMP_PIXEL_URL = 'https://pixel.wp.com/g.gif';
35
36    const TRACKED_UTM_PARAMETERS = array(
37        'utm_id',
38        'utm_source',
39        'utm_medium',
40        'utm_campaign',
41        'utm_term',
42        'utm_content',
43        'utm_source_platform',
44        'utm_creative_format',
45        'utm_marketing_tactic',
46    );
47
48    /**
49     * Stats Build View Data.
50     *
51     * @access public
52     * @return array
53     */
54    public static function build_view_data() {
55        global $wp_the_query;
56
57        $blog        = Jetpack_Options::get_option( 'id' );
58        $tz          = get_option( 'gmt_offset' );
59        $v           = 'ext';
60        $blog_url    = wp_parse_url( site_url() );
61        $srv         = $blog_url['host'];
62        $is_not_post = false;
63        if ( $wp_the_query->is_single || $wp_the_query->is_page || $wp_the_query->is_posts_page ) {
64            // Store and reset the queried_object and queried_object_id
65            // Otherwise, redirect_canonical() will redirect to home_url( '/' ) for show_on_front = page sites where home_url() is not all lowercase.
66            // Repro:
67            // 1. Set home_url = https://ExamPle.com/
68            // 2. Set show_on_front = page
69            // 3. Set page_on_front = something
70            // 4. Visit https://example.com/ !
71            $queried_object    = $wp_the_query->queried_object ?? null;
72            $queried_object_id = $wp_the_query->queried_object_id ?? null;
73            try {
74                $post_obj = $wp_the_query->get_queried_object();
75                $post     = $post_obj instanceof WP_Post ? $post_obj->ID : '0';
76            } finally {
77                $wp_the_query->queried_object    = $queried_object;
78                $wp_the_query->queried_object_id = $queried_object_id;
79            }
80        } else {
81            $post        = '0';
82            $is_not_post = true;
83        }
84        $view_data = compact( 'v', 'blog', 'post', 'tz', 'srv' );
85        // Batcache removes some of the UTM params from $_GET, we need to extract them from uri directly instead.
86        // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- We're sanitizing individual params in the loop.
87        $url_query = wp_parse_url( wp_unslash( $_SERVER['REQUEST_URI'] ?? '' ), PHP_URL_QUERY );
88        parse_str( (string) $url_query, $url_params );
89        foreach ( self::TRACKED_UTM_PARAMETERS as $utm_parameter ) {
90            if ( isset( $url_params[ $utm_parameter ] ) && is_scalar( $url_params[ $utm_parameter ] ) ) {
91                $view_data[ $utm_parameter ] = substr( sanitize_textarea_field( wp_unslash( $url_params[ $utm_parameter ] ) ), 0, 255 );
92            }
93        }
94
95        if ( $is_not_post ) {
96            if ( $wp_the_query->is_home() ) {
97                $view_data['arch_home'] = '1';
98            } elseif ( $wp_the_query->is_search() ) {
99                $search_term               = $wp_the_query->query['s'] ?? $wp_the_query->query_vars['s'] ?? '';
100                $view_data['arch_search']  = sanitize_text_field( $search_term );
101                $view_data['arch_filters'] = sanitize_text_field( self::build_search_filters( $wp_the_query ) );
102                $view_data['arch_results'] = $wp_the_query->posts ? $wp_the_query->post_count : 0;
103            } elseif ( $wp_the_query->is_archive() ) {
104                if ( $wp_the_query->is_date ) {
105                    $query                  = $wp_the_query->query;
106                    $date_parts             = array_filter( array( $query['year'] ?? null, $query['monthnum'] ?? null, $query['day'] ?? null ) );
107                    $date                   = implode( '/', $date_parts );
108                    $view_data['arch_date'] = $date;
109                }
110                if ( $wp_the_query->is_category ) {
111                    $view_data['arch_cat'] = $wp_the_query->query['category_name'] ?? $wp_the_query->query_vars['category_name'] ?? '';
112                }
113                if ( $wp_the_query->is_tag ) {
114                    $view_data['arch_tag'] = $wp_the_query->query['tag'] ?? $wp_the_query->query_vars['tag'] ?? '';
115                }
116                if ( $wp_the_query->is_author ) {
117                    $view_data['arch_author'] = $wp_the_query->query['author_name'] ?? '';
118                }
119                if ( $wp_the_query->is_tax ) {
120                    $query = $wp_the_query->query;
121                    if ( is_array( $query ) && count( $query ) === 1 ) {
122                        $view_data[ 'arch_tax_' . array_keys( $query )[0] ] = array_values( $query )[0];
123                    }
124                }
125                $view_data['arch_results'] = $wp_the_query->posts ? $wp_the_query->post_count : 0;
126            } elseif ( $wp_the_query->is_404() ) {
127                $view_data['arch_err'] = sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ?? '' ) );
128            } else {
129                $view_data['arch_other'] = sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ?? '' ) );
130            }
131        }
132        return $view_data;
133    }
134
135    /**
136     * Collect the tracking data for a search page.
137     *
138     * @access private
139     * @param  \WP_Query $query The WP_Query object to parse all the filters from.
140     * @return string The search filters in a URL query string format.
141     */
142    private static function build_search_filters( $query ) {
143        $data = array(
144            'posts_per_page' => $query->get( 'posts_per_page' ),
145            'paged'          => ( $query->get( 'paged' ) ) ? absint( $query->get( 'paged' ) ) : 1,
146            'orderby'        => $query->get( 'orderby' ),
147            'order'          => $query->get( 'order' ),
148        );
149
150        if ( $query->get( 'author_name' ) ) {
151            $data['author_name'] = $query->get( 'author_name' );
152        }
153        $filters = http_build_query( $data );
154
155        $the_tax_query = $query->tax_query;
156        $terms         = array();
157        if ( ! empty( $the_tax_query->queried_terms ) && is_array( $the_tax_query->queried_terms ) ) {
158            foreach ( $the_tax_query->queries as $tax_query ) {
159                if ( ! is_array( $tax_query ) || ! isset( $tax_query['taxonomy'] ) ) {
160                    continue;
161                }
162                $taxonomy = $tax_query['taxonomy'];
163                if ( ! isset( $terms[ $taxonomy ] ) || ! is_array( $terms[ $taxonomy ] ) ) {
164                    $terms[ $taxonomy ] = array();
165                }
166                $terms[ $taxonomy ] = array_merge( $terms[ $taxonomy ], $tax_query['terms'] );
167            }
168        }
169        if ( ! empty( $terms ) ) {
170            $filters .= '&terms=' . wp_json_encode( $terms, JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP );
171        }
172        return $filters;
173    }
174
175    /**
176     * Build the Stats tracking details.
177     *
178     * @since 0.6.0
179     *
180     * @access private
181     * @param array $data Array of options about the site and page for the inline (non-AMP) tracker.
182     * @return string
183     */
184    private static function build_stats_details( $data ) {
185        $data_stats_array = self::stats_array_to_string( $data );
186
187        $pushes = sprintf(
188            '_stq.push([ "view", %1$s ]);
189_stq.push([ "clickTrackerInit", "%2$s", "%3$s" ]);',
190            $data_stats_array,
191            $data['blog'],
192            $data['post']
193        );
194
195        // Without the WP Consent API plugin there is no consent to honor, so the output stays byte-for-byte historical.
196        if ( ! function_exists( 'wp_has_consent' ) ) {
197            return "_stq = window._stq || [];\n" . $pushes;
198        }
199
200        return self::build_consent_gate( $pushes );
201    }
202
203    /**
204     * Wrap the tracking pushes in a WP Consent API gate, checked in the browser because cached HTML is shared across visitors.
205     *
206     * `_jpStatsFire.done` is set before the pushes so a push that throws is never replayed: the
207     * sender assigns the beacon `src` first, so that view was already counted.
208     *
209     * @access private
210     * @param string $pushes The `_stq.push(...)` statements to gate.
211     * @return string
212     */
213    private static function build_consent_gate( $pushes ) {
214        // A delay-JS optimizer can load the WP Consent API after `load` without any event, so recheck on each script load (captured: it doesn't bubble).
215        // That recheck needs a stored allow, a type a banner has set, or an opt-out fallback: an empty fallback allows anyone, even where a delayed banner has yet to set opt-in.
216        // A stored deny wins: without a consent type, which some banners set only on the first visit, wp_has_consent() ignores it.
217        return sprintf(
218            '_stq = window._stq || [];
219function _jpStatsFire() {
220    if ( _jpStatsFire.done ) { return; }
221    _jpStatsFire.done = true;
222    %1$s
223}
224function _jpStatsStoredChoice() {
225    return typeof window.consent_api_get_cookie === "function" && !! window.consent_api ?
226        window.consent_api_get_cookie( window.consent_api.cookie_prefix + "_statistics" ) : "";
227}
228function _jpStatsSafeToRecheck() {
229    return _jpStatsStoredChoice() === "allow" || typeof window.wp_consent_type !== "undefined" || String( window.wp_fallback_consent_type || "" ).indexOf( "optout" ) !== -1;
230}
231function _jpStatsCheck() {
232    if ( _jpStatsFire.done || typeof window.wp_has_consent !== "function" ) { return; }
233    if ( window.waitfor_consent_hook && typeof window.wp_consent_type === "undefined" ) { return; }
234    var consented;
235    try {
236        consented = _jpStatsStoredChoice() !== "deny" && window.wp_has_consent( "statistics" );
237    } catch ( e ) {
238        window.console && console.warn( "Jetpack Stats: wp_has_consent() threw, so Stats waits for a consent change.", e );
239        return;
240    }
241    if ( consented ) { _jpStatsFire(); }
242}
243document.addEventListener( "wp_listen_for_consent_change", function ( event ) {
244    if ( event && event.detail && event.detail.statistics === "allow" ) { _jpStatsFire(); }
245} );
246document.addEventListener( "wp_consent_type_defined", _jpStatsCheck );
247window.addEventListener( "wp_consent_type_defined", _jpStatsCheck );
248document.addEventListener( "load", function ( event ) {
249    if ( event && event.target && event.target.tagName === "SCRIPT" && _jpStatsSafeToRecheck() ) { _jpStatsCheck(); }
250}, true );
251window.addEventListener( "load", function () {
252    if ( typeof window.wp_has_consent !== "function" ) {
253        window.console && console.warn( "Jetpack Stats: the WP Consent API script has not loaded yet, so Stats waits for it and for a consent choice." );
254    }
255    _jpStatsCheck();
256}, { once: true } );
257if ( document.readyState === "loading" ) {
258    document.addEventListener( "DOMContentLoaded", _jpStatsCheck, { once: true } );
259} else {
260    _jpStatsCheck();
261}',
262            $pushes
263        );
264    }
265
266    /**
267     * Add fetchpriority="low" to the Stats script attributes.
268     *
269     * Reduces network contention with resources in the critical rendering path (e.g., the LCP
270     * element image). This benefits Safari and Firefox, which don't automatically assign low
271     * priority to async/defer scripts (unlike Chrome).
272     *
273     * @since 0.19.5
274     *
275     * @param array $attributes Script tag attributes.
276     * @return array Modified attributes.
277     */
278    public static function add_low_fetchpriority( $attributes ) {
279        // WordPress derives the tag id from the enqueue handle as "{handle}-js", so the
280        // 'jetpack-stats' script (registered in enqueue_stats_script()) prints as
281        // 'jetpack-stats-js'. Keep this in sync if the handle is ever renamed.
282        if ( isset( $attributes['id'] ) && 'jetpack-stats-js' === $attributes['id'] ) {
283            $attributes['fetchpriority'] = 'low';
284        }
285        return $attributes;
286    }
287
288    /**
289     * Remove the dns-prefetch resource hint for stats.wp.com.
290     *
291     * WordPress automatically adds dns-prefetch hints for enqueued script hosts via
292     * wp_dependencies_unique_hosts(). Since we're deprioritizing the stats script,
293     * the dns-prefetch is counterproductive â€” it front-loads DNS resolution for a
294     * resource we're intentionally delaying.
295     *
296     * @since 0.19.5
297     *
298     * @param array  $urls          Array of resource hint URLs.
299     * @param string $relation_type The relation type (dns-prefetch, preconnect, etc.).
300     * @return array Filtered URLs.
301     */
302    public static function remove_stats_dns_prefetch( $urls, $relation_type ) {
303        if ( 'dns-prefetch' !== $relation_type ) {
304            return $urls;
305        }
306
307        return array_filter(
308            $urls,
309            static function ( $url ) {
310                // Resource hints can be arrays that carry the URL under an 'href' key.
311                if ( is_array( $url ) ) {
312                    $candidate = ( isset( $url['href'] ) && is_string( $url['href'] ) ) ? $url['href'] : '';
313                } elseif ( is_string( $url ) ) {
314                    $candidate = $url;
315                } else {
316                    return true; // Unknown entry shape; leave it untouched.
317                }
318
319                // dns-prefetch entries arrive in several shapes: WordPress core emits bare
320                // hosts ('stats.wp.com') via wp_dependencies_unique_hosts(), while other
321                // filters may add scheme-relative ('//stats.wp.com') or full URLs. Normalize
322                // each to a host so we drop stats.wp.com exactly without removing look-alike
323                // hosts such as 'mystats.wp.com' or 'stats.wp.com.evil.tld'.
324                if ( str_starts_with( $candidate, '//' ) ) {
325                    $host = wp_parse_url( 'https:' . $candidate, PHP_URL_HOST );
326                } elseif ( str_contains( $candidate, '://' ) ) {
327                    $host = wp_parse_url( $candidate, PHP_URL_HOST );
328                } else {
329                    $host = $candidate; // Bare host form, e.g. 'stats.wp.com'.
330                }
331
332                return ! is_string( $host ) || 'stats.wp.com' !== strtolower( $host );
333            }
334        );
335    }
336
337    /**
338     * Enqueue the Stats pixel.
339     * Do not use this function directly, it is hooked into `wp_enqueue_scripts`.
340     *
341     * @access public
342     * @return void
343     */
344    public static function enqueue_stats_script() {
345        if ( self::is_amp_request() ) {
346            return;
347        }
348
349        wp_enqueue_script(
350            'jetpack-stats',
351            'https://stats.wp.com/e-' . gmdate( 'YW' ) . '.js',
352            array(),
353            null, // phpcs:ignore WordPress.WP.EnqueuedResourceParameters.MissingVersion -- The version is set in the URL.
354            array(
355                'in_footer' => true,
356                'strategy'  => 'defer',
357            )
358        );
359        add_filter( 'wp_script_attributes', array( static::class, 'add_low_fetchpriority' ) );
360        add_filter( 'wp_resource_hints', array( static::class, 'remove_stats_dns_prefetch' ), 100, 2 );
361
362        $data = self::build_view_data();
363
364        /**
365         * Filter the parameters added to the JavaScript stats tracking code.
366         *
367         * @module stats
368         *
369         * @since-jetpack 10.9
370         *
371         * @param array $data Array of options about the site and page you're on.
372         */
373        $data = (array) apply_filters( 'jetpack_stats_footer_js_data', $data );
374
375        $triggers = self::build_stats_details( $data );
376        wp_add_inline_script(
377            'jetpack-stats',
378            $triggers,
379            'before'
380        );
381    }
382
383    /**
384     * Gets the tracking pixel URL for AMP output.
385     *
386     * @access private
387     * @param array $data Array of data for the AMP pixel tracker.
388     * @return string Returns the URL for the Stats tracker in an AMP scenario.
389     */
390    private static function get_amp_pixel_url( $data ) {
391        /**
392         * Filter the parameters added to the AMP pixel tracking code.
393         *
394         * @module stats
395         *
396         * @since-jetpack 10.9
397         *
398         * @param array $data Array of options about the site and page you're on.
399         */
400        $data = (array) apply_filters( 'jetpack_stats_footer_amp_data', $data );
401
402        $data['host'] = isset( $_SERVER['HTTP_HOST'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_HOST'] ) ) : ''; // input var ok.
403        $data['rand'] = 'RANDOM'; // AMP placeholder.
404        $data['ref']  = 'DOCUMENT_REFERRER'; // AMP placeholder.
405        $data         = array_map( 'rawurlencode', $data );
406        return add_query_arg( $data, self::AMP_PIXEL_URL );
407    }
408
409    /**
410     * Build an AMP pixel.
411     * Do not use this function directly, it is hooked into `wp_footer`.
412     *
413     * @access public
414     * @return void
415     */
416    public static function add_amp_pixel() {
417        $data = self::build_view_data();
418        if ( ! self::is_amp_request() ) {
419            return;
420        }
421
422        self::print_amp_pixel( $data );
423    }
424
425    /**
426     * Print the AMP pixel, held for the page's `amp-consent` when the WP Consent API is active.
427     *
428     * @param array $data Array of data for the AMP pixel tracker.
429     * @return void
430     */
431    private static function print_amp_pixel( $data ) {
432        if ( ! function_exists( 'wp_has_consent' ) ) {
433            printf( '<amp-pixel src="%s"></amp-pixel>', esc_url( self::get_amp_pixel_url( $data ) ) );
434            return;
435        }
436
437        // Only the AMP plugin runs AMP_Consent_Sanitizer.
438        if ( ! function_exists( 'amp_is_request' ) || ! amp_is_request() ) {
439            return;
440        }
441
442        printf( '<amp-pixel data-block-on-consent src="%s"></amp-pixel>', esc_url( self::get_amp_pixel_url( $data ) ) );
443    }
444
445    /**
446     * Register AMP_Consent_Sanitizer when the WP Consent API is active.
447     * Do not use this function directly, it is hooked into `amp_content_sanitizers`.
448     *
449     * @since $$next-version$$
450     *
451     * @param array $sanitizers Sanitizer classes and their args.
452     * @return array
453     */
454    public static function add_amp_consent_sanitizer( $sanitizers ) {
455        if ( function_exists( 'wp_has_consent' ) ) {
456            $sanitizers[ AMP_Consent_Sanitizer::class ] = array();
457        }
458        return $sanitizers;
459    }
460
461    /**
462     * Stats Footer.
463     *
464     * @deprecated 0.6.0
465     *
466     * @access public
467     * @return void
468     */
469    public static function add_to_footer() {
470        _deprecated_function( __METHOD__, '0.6.0' );
471    }
472
473    /**
474     * Gets the footer to add for the Stats tracker.
475     *
476     * @deprecated 0.6.0
477     *
478     * @access public
479     * @param array $data Array of data for the JS stats tracker.
480     * @return void
481     */
482    public static function get_footer_to_add( $data ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
483        _deprecated_function( __METHOD__, '0.6.0' );
484    }
485
486    /**
487     * Render the stats footer. Kept for backward compatibility on legacy AMF views.
488     *
489     * @deprecated 0.6.0
490     *
491     * @access public
492     * @param array $data Array of data for the JS stats tracker.
493     */
494    public static function render_footer( $data ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
495        _deprecated_function( __METHOD__, '0.6.0' );
496    }
497
498    /**
499     * Render the stats footer for AMP output. Kept for backward compatibility.
500     *
501     * @access public
502     * @param array $data Array of data for the AMP pixel tracker.
503     */
504    public static function render_amp_footer( $data ) {
505        self::print_amp_pixel( $data );
506    }
507
508    /**
509     * Creates the "array" string used as part of the JS tracker.
510     *
511     * @access private
512     * @param array $kvs Array of options about the site and page you're on.
513     * @return string
514     */
515    private static function stats_array_to_string( $kvs ) {
516        /**
517         * Filters the options added to the JavaScript Stats tracking code.
518         *
519         * @since-jetpack 1.1.0
520         *
521         * @param array $kvs Array of options about the site and page you're on.
522         */
523        $kvs = (array) apply_filters( self::STATS_ARRAY_TO_STRING_FILTER, $kvs );
524        $kvs = array_map( 'strval', $kvs );
525
526        // Encode into JSON object for direct use in JS.
527        return wp_json_encode( $kvs, JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP );
528    }
529
530    /**
531     * Does the page return AMP content.
532     *
533     * @return bool $is_amp_request Are we on AMP view.
534     */
535    private static function is_amp_request() {
536        $is_amp_request = ( function_exists( 'amp_is_request' ) && amp_is_request() );
537        $is_amp_request = $is_amp_request || ( function_exists( 'ampforwp_is_amp_endpoint' ) && ampforwp_is_amp_endpoint() );
538
539        /**
540         * Returns true if the current request should return valid AMP content.
541         *
542         * @since 6.2.0
543         *
544         * @param boolean $is_amp_request Is this request supposed to return valid AMP content?
545         */
546        return apply_filters( 'jetpack_is_amp_request', $is_amp_request );
547    }
548}