Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
62.12% covered (warning)
62.12%
82 / 132
44.44% covered (danger)
44.44%
4 / 9
CRAP
0.00% covered (danger)
0.00%
0 / 1
Tracking
62.12% covered (warning)
62.12%
82 / 132
44.44% covered (danger)
44.44%
4 / 9
132.36
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
3
 ajax_tracks
50.00% covered (danger)
50.00%
10 / 20
0.00% covered (danger)
0.00%
0 / 1
16.00
 register_tracks_functions_scripts
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
2
 enqueue_tracks_scripts
0.00% covered (danger)
0.00%
0 / 18
0.00% covered (danger)
0.00%
0 / 1
2
 record_user_event
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
8
 tracks_record_event
90.00% covered (success)
90.00%
9 / 10
0.00% covered (danger)
0.00%
0 / 1
5.03
 should_enable_tracking
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 tracks_build_event_obj
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
3
 tracks_get_identity
84.00% covered (warning)
84.00%
21 / 25
0.00% covered (danger)
0.00%
0 / 1
9.33
1<?php
2/**
3 * Nosara Tracks for Jetpack
4 *
5 * @package automattic/jetpack-connection
6 */
7
8namespace Automattic\Jetpack;
9
10use Automattic\Jetpack\IP\Utils as IP_Utils;
11
12/**
13 * The Tracking class, used to record events in wpcom
14 */
15class Tracking {
16    /**
17     * The assets version.
18     *
19     * @since 1.13.1
20     * @deprecated since 1.40.1
21     *
22     * @var string Assets version.
23     */
24    const ASSETS_VERSION = '1.0.0';
25
26    /**
27     * Slug of the product that we are tracking.
28     *
29     * @var string
30     */
31    private $product_name;
32
33    /**
34     * Connection manager object.
35     *
36     * @var Object
37     */
38    private $connection;
39
40    /**
41     * Creates the Tracking object.
42     *
43     * @param string                                 $product_name the slug of the product that we are tracking.
44     * @param \Automattic\Jetpack\Connection\Manager $connection   the connection manager object.
45     */
46    public function __construct( $product_name = 'jetpack', $connection = null ) {
47        $this->product_name = $product_name;
48        $this->connection   = $connection;
49        if ( $this->connection === null ) {
50            // TODO We should always pass a Connection.
51            $this->connection = new Connection\Manager();
52        }
53
54        if ( ! did_action( 'jetpack_set_tracks_ajax_hook' ) ) {
55            add_action( 'wp_ajax_jetpack_tracks', array( $this, 'ajax_tracks' ) );
56
57            /**
58             * Fires when the Tracking::ajax_tracks() callback has been hooked to the
59             * wp_ajax_jetpack_tracks action. This action is used to ensure that
60             * the callback is hooked only once.
61             *
62             * @since 1.13.11
63             */
64            do_action( 'jetpack_set_tracks_ajax_hook' );
65        }
66    }
67
68    /**
69     * Universal method for for all tracking events triggered via the JavaScript client.
70     *
71     * @access public
72     */
73    public function ajax_tracks() {
74        // Check for nonce.
75        if (
76            empty( $_REQUEST['tracksNonce'] )
77            || ! wp_verify_nonce( $_REQUEST['tracksNonce'], 'jp-tracks-ajax-nonce' ) // phpcs:ignore WordPress.Security.ValidatedSanitizedInput -- WP core doesn't pre-sanitize nonces either.
78        ) {
79            wp_send_json_error(
80                __( 'You aren’t authorized to do that.', 'jetpack-connection' ),
81                403,
82                JSON_UNESCAPED_SLASHES
83            );
84        }
85
86        if ( ! isset( $_REQUEST['tracksEventName'] ) || ! isset( $_REQUEST['tracksEventType'] ) ) {
87            wp_send_json_error(
88                __( 'No valid event name or type.', 'jetpack-connection' ),
89                403,
90                JSON_UNESCAPED_SLASHES
91            );
92        }
93
94        $tracks_data = array();
95        if ( 'click' === $_REQUEST['tracksEventType'] && isset( $_REQUEST['tracksEventProp'] ) ) {
96            if ( is_array( $_REQUEST['tracksEventProp'] ) ) {
97                // map_deep() rather than array_map(): the request is client-supplied and may nest,
98                // and sanitize_text_field() returns an empty string when handed an array.
99                $tracks_data = map_deep( wp_unslash( $_REQUEST['tracksEventProp'] ), 'sanitize_text_field' );
100            } else {
101                $tracks_data = array( 'clicked' => sanitize_text_field( wp_unslash( $_REQUEST['tracksEventProp'] ) ) );
102            }
103        }
104
105        // Tracks only accepts lowercase alphanumerics and underscores in an event name
106        // (see Jetpack_Tracks_Event::EVENT_NAME_REGEX), which is what sanitize_key() permits.
107        $this->record_user_event( sanitize_key( wp_unslash( $_REQUEST['tracksEventName'] ) ), $tracks_data, null, false );
108
109        wp_send_json_success( null, null, JSON_UNESCAPED_SLASHES );
110    }
111
112    /**
113     * Register script necessary for tracking.
114     *
115     * @param boolean $enqueue Also enqueue? defaults to false.
116     */
117    public static function register_tracks_functions_scripts( $enqueue = false ) {
118
119        // Register jp-tracks as it is a dependency.
120        wp_register_script(
121            'jp-tracks',
122            '//stats.wp.com/w.js',
123            array(),
124            gmdate( 'YW' ),
125            true
126        );
127
128        Assets::register_script(
129            'jp-tracks-functions',
130            '../dist/tracks-callables.js',
131            __FILE__,
132            array(
133                'dependencies' => array( 'jp-tracks' ),
134                'enqueue'      => $enqueue,
135                'in_footer'    => true,
136            )
137        );
138    }
139
140    /**
141     * Enqueue script necessary for tracking.
142     */
143    public function enqueue_tracks_scripts() {
144        Assets::register_script(
145            'jptracks',
146            '../dist/tracks-ajax.js',
147            __FILE__,
148            array(
149                'dependencies' => array( 'jquery' ),
150                'enqueue'      => true,
151                'in_footer'    => true,
152            )
153        );
154
155        wp_localize_script(
156            'jptracks',
157            'jpTracksAJAX',
158            array(
159                'ajaxurl'            => admin_url( 'admin-ajax.php' ),
160                'jpTracksAJAX_nonce' => wp_create_nonce( 'jp-tracks-ajax-nonce' ),
161            )
162        );
163    }
164
165    /**
166     * Send an event in Tracks.
167     *
168     * @param string $event_type         Type of the event.
169     * @param array  $data               Data to send with the event.
170     * @param mixed  $user               Username, user_id, or WP_User object.
171     * @param bool   $use_product_prefix Whether to use the object's product name as a prefix to the event type. If
172     *                                   set to false, the prefix will be 'jetpack_'.
173     */
174    public function record_user_event( $event_type, $data = array(), $user = null, $use_product_prefix = true ) {
175        if ( ! $user ) {
176            $user = wp_get_current_user();
177        }
178        $site_url = get_option( 'siteurl' );
179
180        $data['_via_ua']  = isset( $_SERVER['HTTP_USER_AGENT'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ) : '';
181        $data['_via_ip']  = isset( $_SERVER['REMOTE_ADDR'] ) ? (string) IP_Utils::clean_ip( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : ''; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- clean_ip() validates the address.
182        $data['_lg']      = isset( $_SERVER['HTTP_ACCEPT_LANGUAGE'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_ACCEPT_LANGUAGE'] ) ) : '';
183        $data['blog_url'] = $site_url;
184        $data['blog_id']  = \Jetpack_Options::get_option( 'id' );
185
186        // Top level events should not be namespaced.
187        if ( '_aliasUser' !== $event_type ) {
188            $prefix     = $use_product_prefix ? $this->product_name : 'jetpack';
189            $event_type = $prefix . '_' . $event_type;
190        }
191
192        $data['jetpack_version'] = defined( 'JETPACK__VERSION' ) ? JETPACK__VERSION : '0';
193
194        return $this->tracks_record_event( $user, $event_type, $data );
195    }
196
197    /**
198     * Record an event in Tracks - this is the preferred way to record events from PHP.
199     *
200     * @param mixed  $user                   username, user_id, or WP_User object.
201     * @param string $event_name             The name of the event.
202     * @param array  $properties             Custom properties to send with the event.
203     * @param int    $event_timestamp_millis The time in millis since 1970-01-01 00:00:00 when the event occurred.
204     *
205     * @return bool true for success | \WP_Error if the event pixel could not be fired
206     */
207    public function tracks_record_event( $user, $event_name, $properties = array(), $event_timestamp_millis = false ) {
208
209        // We don't want to track user events during unit tests/CI runs.
210        if ( $user instanceof \WP_User && 'wptests_capabilities' === $user->cap_key ) {
211            return false;
212        }
213        $terms_of_service = new Terms_Of_Service();
214        $status           = new Status();
215        // Don't track users who have not agreed to our TOS.
216        if ( ! $this->should_enable_tracking( $terms_of_service, $status ) ) {
217            return false;
218        }
219
220        $event_obj = $this->tracks_build_event_obj( $user, $event_name, $properties, $event_timestamp_millis );
221
222        if ( is_wp_error( $event_obj->error ) ) {
223            return $event_obj->error;
224        }
225
226        return $event_obj->record();
227    }
228
229    /**
230     * Determines whether tracking should be enabled.
231     *
232     * @param \Automattic\Jetpack\Terms_Of_Service $terms_of_service A Terms_Of_Service object.
233     * @param \Automattic\Jetpack\Status           $status A Status object.
234     *
235     * @return boolean True if tracking should be enabled, else false.
236     */
237    public function should_enable_tracking( $terms_of_service, $status ) {
238        if ( $status->is_offline_mode() ) {
239            return false;
240        }
241
242        return $terms_of_service->has_agreed() || $this->connection->is_user_connected();
243    }
244
245    /**
246     * Procedurally build a Tracks Event Object.
247     * NOTE: Use this only when the simpler Automattic\Jetpack\Tracking->jetpack_tracks_record_event() function won't work for you.
248     *
249     * @param \WP_User $user                   WP_User object.
250     * @param string   $event_name             The name of the event.
251     * @param array    $properties             Custom properties to send with the event.
252     * @param int      $event_timestamp_millis The time in millis since 1970-01-01 00:00:00 when the event occurred.
253     *
254     * @return \Jetpack_Tracks_Event|\WP_Error
255     */
256    private function tracks_build_event_obj( $user, $event_name, $properties = array(), $event_timestamp_millis = false ) {
257        $identity = $this->tracks_get_identity( $user->ID );
258
259        $properties['user_lang'] = $user->get( 'WPLANG' );
260
261        $blog_details = array(
262            'blog_lang' => $properties['blog_lang'] ?? get_bloginfo( 'language' ),
263            'blog_id'   => \Jetpack_Options::get_option( 'id' ),
264        );
265
266        $timestamp        = ( false !== $event_timestamp_millis ) ? $event_timestamp_millis : round( microtime( true ) * 1000 );
267        $timestamp_string = is_string( $timestamp ) ? $timestamp : number_format( $timestamp, 0, '', '' );
268
269        return new \Jetpack_Tracks_Event(
270            array_merge(
271                $blog_details,
272                (array) $properties,
273                $identity,
274                array(
275                    '_en' => $event_name,
276                    '_ts' => $timestamp_string,
277                )
278            )
279        );
280    }
281
282    /**
283     * Get the identity to send to tracks.
284     *
285     * @param int $user_id The user id of the local user.
286     *
287     * @return array $identity
288     */
289    public function tracks_get_identity( $user_id ) {
290
291        // Meta is set, and user is still connected. Use WPCOM ID.
292        $wpcom_id = get_user_meta( $user_id, 'jetpack_tracks_wpcom_id', true );
293        if ( $wpcom_id && is_string( $wpcom_id ) && $this->connection->is_user_connected( $user_id ) ) {
294            return array(
295                '_ut' => 'wpcom:user_id',
296                '_ui' => $wpcom_id,
297            );
298        }
299
300        // User is connected, but no meta is set yet. Use WPCOM ID and set meta.
301        if ( $this->connection->is_user_connected( $user_id ) ) {
302            $wpcom_user_data = $this->connection->get_connected_user_data( $user_id );
303            $wpcom_id        = $wpcom_user_data['ID'] ?? null;
304
305            if ( is_string( $wpcom_id ) ) {
306                update_user_meta( $user_id, 'jetpack_tracks_wpcom_id', $wpcom_id );
307
308                return array(
309                    '_ut' => 'wpcom:user_id',
310                    '_ui' => $wpcom_id,
311                );
312            }
313        }
314
315        // User isn't linked at all.  Fall back to anonymous ID.
316        $anon_id = get_user_meta( $user_id, 'jetpack_tracks_anon_id', true );
317        if ( ! $anon_id ) {
318            $anon_id = \Jetpack_Tracks_Client::get_anon_id();
319            add_user_meta( $user_id, 'jetpack_tracks_anon_id', $anon_id, false );
320        }
321
322        if ( ! isset( $_COOKIE['tk_ai'] ) && ! headers_sent() ) {
323            setcookie( 'tk_ai', $anon_id, 0, COOKIEPATH, COOKIE_DOMAIN, is_ssl(), false ); // phpcs:ignore Jetpack.Functions.SetCookie -- This is a random string and should be fine.
324        }
325
326        return array(
327            '_ut' => 'anon',
328            '_ui' => $anon_id,
329        );
330    }
331}