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