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