Merge pull request #22625 from woocommerce/add/php-tracks-client

Tracks: Add PHP client
This commit is contained in:
Paul Sealock 2019-02-20 12:35:54 +13:00 committed by GitHub
commit 078057e9b2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 515 additions and 0 deletions

View File

@ -32,6 +32,10 @@ class WC_Admin {
add_action( 'admin_footer', 'wc_print_js', 25 );
add_filter( 'admin_footer_text', array( $this, 'admin_footer_text' ), 1 );
add_action( 'wp_ajax_setup_wizard_check_jetpack', array( $this, 'setup_wizard_check_jetpack' ) );
if ( 'yes' === get_option( 'woocommerce_allow_tracking', 'no' ) ) {
add_action( 'init', array( 'WC_Site_Tracking', 'init' ) );
}
}
/**
@ -59,6 +63,11 @@ class WC_Admin {
include_once dirname( __FILE__ ) . '/class-wc-admin-importers.php';
include_once dirname( __FILE__ ) . '/class-wc-admin-exporters.php';
include_once WC_ABSPATH . 'includes/tracks/class-wc-tracks.php';
include_once WC_ABSPATH . 'includes/tracks/class-wc-tracks-event.php';
include_once WC_ABSPATH . 'includes/tracks/class-wc-tracks-client.php';
include_once WC_ABSPATH . 'includes/tracks/class-wc-site-tracking.php';
// Help Tabs
if ( apply_filters( 'woocommerce_enable_admin_help_tab', true ) ) {
include_once dirname( __FILE__ ) . '/class-wc-admin-help.php';

View File

@ -0,0 +1,65 @@
<?php
/**
* Nosara Tracks for WooCommerce
*
* @package WooCommerce\Tracks
*/
defined( 'ABSPATH' ) || exit;
/**
* This class adds actions to track usage of WooCommerce.
*/
class WC_Site_Tracking {
/**
* Send a Tracks event when a product is updated.
*
* @param int $product_id Product id.
* @param array $post WordPress post.
*/
public static function tracks_product_updated( $product_id, $post ) {
if ( 'product' !== $post->post_type ) {
return;
}
$properties = array(
'product_id' => $product_id,
);
WC_Tracks::record_event( 'update_product', $properties );
}
/**
* Check if tracking is enabled.
*
* @return bool
*/
public static function is_tracking_enabled() {
/**
* Don't track users who haven't opted-in to tracking or if a filter
* has been applied to turn it off.
*/
if ( 'yes' !== get_option( 'woocommerce_allow_tracking' ) ||
! apply_filters( 'woocommerce_apply_user_tracking', true ) ) {
return false;
}
if ( ! class_exists( 'WC_Tracks' ) ) {
return false;
}
return true;
}
/**
* Init tracking.
*/
public static function init() {
if ( ! self::is_tracking_enabled() ) {
return;
}
add_action( 'edit_post', array( 'WC_Site_Tracking', 'tracks_product_updated' ), 10, 2 );
}
}

View File

@ -0,0 +1,132 @@
<?php
/**
* Send Tracks events on behalf of a user.
*
* @package WooCommerce\Tracks
*/
defined( 'ABSPATH' ) || exit;
/**
* WC_Tracks_Client class.
*/
class WC_Tracks_Client {
/**
* Pixel URL.
*/
const PIXEL = 'https://pixel.wp.com/t.gif';
/**
* Browser type.
*/
const BROWSER_TYPE = 'php-agent';
/**
* User agent.
*/
const USER_AGENT_SLUG = 'tracks-client';
/**
* Record a Tracks event
*
* @param array $event Array of event properties.
* @return bool|WP_Error True on success, WP_Error on failure.
*/
public static function record_event( $event ) {
if ( ! $event instanceof WC_Tracks_Event ) {
$event = new WC_Tracks_Event( $event );
}
if ( is_wp_error( $event ) ) {
return $event;
}
$pixel = $event->build_pixel_url( $event );
if ( ! $pixel ) {
return new WP_Error( 'invalid_pixel', 'cannot generate tracks pixel for given input', 400 );
}
return self::record_pixel( $pixel );
}
/**
* Synchronously request the pixel.
*
* @param string $pixel pixel url and query string.
* @return bool|WP_Error True on success, WP_Error on failure.
*/
public static function record_pixel( $pixel ) {
// Add the Request Timestamp and URL terminator just before the HTTP request.
$pixel .= '&_rt=' . self::build_timestamp() . '&_=_';
$response = wp_safe_remote_get(
$pixel,
array(
'blocking' => true, // The default, but being explicit here.
'redirection' => 2,
'httpversion' => '1.1',
)
);
if ( is_wp_error( $response ) ) {
return $response;
}
if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
return new WP_Error( 'request_failed', 'Tracks pixel request failed', $code );
}
return true;
}
/**
* Create a timestap representing milliseconds since 1970-01-01
*
* @return string A string representing a timestamp.
*/
public static function build_timestamp() {
$ts = round( microtime( true ) * 1000 );
return number_format( $ts, 0, '', '' );
}
/**
* Grabs the user's anon id from cookies, or generates and sets a new one
*
* @todo: Determine the best way to identify sites/users with/without Jetpack connection.
* @return string An anon id for the user
*/
public static function get_anon_id() {
static $anon_id = null;
if ( ! isset( $anon_id ) ) {
// Did the browser send us a cookie?
if ( isset( $_COOKIE['tk_ai'] ) && preg_match( '#^[A-Za-z0-9+/=]{24}$#', wp_unslash( $_COOKIE['tk_ai'] ) ) ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
$anon_id = wp_unslash( $_COOKIE['tk_ai'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
} else {
$binary = '';
// Generate a new anonId and try to save it in the browser's cookies
// Note that base64-encoding an 18 character string generates a 24-character anon id.
for ( $i = 0; $i < 18; ++$i ) {
$binary .= chr( wp_rand( 0, 255 ) );
}
$anon_id = 'jetpack:' . base64_encode( $binary );
if ( ! headers_sent()
&& ! ( defined( 'REST_REQUEST' ) && REST_REQUEST )
&& ! ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST )
) {
setcookie( 'tk_ai', $anon_id );
}
}
}
return $anon_id;
}
}

View File

@ -0,0 +1,161 @@
<?php
/**
* This class represents an event used to record a Tracks event
*
* @package WooCommerce\Tracks
*/
defined( 'ABSPATH' ) || exit;
/**
* WC_Tracks_Event class.
*/
class WC_Tracks_Event {
/**
* Event name regex.
*/
const EVENT_NAME_REGEX = '/^(([a-z0-9]+)_){2}([a-z0-9_]+)$/';
/**
* Property name regex.
*/
const PROP_NAME_REGEX = '/^[a-z_][a-z0-9_]*$/';
/**
* Error message as WP_Error.
*
* @var WP_Error
*/
public $error;
/**
* WC_Tracks_Event constructor.
*
* @param array $event Event properties.
*/
public function __construct( $event ) {
$_event = self::validate_and_sanitize( $event );
if ( is_wp_error( $_event ) ) {
$this->error = $_event;
return;
}
foreach ( $_event as $key => $value ) {
$this->{$key} = $value;
}
}
/**
* Record Tracks event
*
* @return bool|WP_Error True on success, WP_Error on failure.
*/
public function record() {
return WC_Tracks_Client::record_event( $this );
}
/**
* Annotate the event with all relevant info.
*
* @param array $event Event arguments.
* @return bool|WP_Error True on success, WP_Error on failure.
*/
public static function validate_and_sanitize( $event ) {
$event = (object) $event;
// Required.
if ( ! $event->_en ) {
return new WP_Error( 'invalid_event', 'A valid event must be specified via `_en`', 400 );
}
// Delete non-routable addresses otherwise geoip will discard the record entirely.
if ( property_exists( $event, '_via_ip' ) && preg_match( '/^192\.168|^10\./', $event->_via_ip ) ) {
unset( $event->_via_ip );
}
$validated = array(
'browser_type' => WC_Tracks_Client::BROWSER_TYPE,
);
$_event = (object) array_merge( (array) $event, $validated );
// If you want to blacklist property names, do it here.
// Make sure we have an event timestamp.
if ( ! isset( $_event->_ts ) ) {
$_event->_ts = WC_Tracks_Client::build_timestamp();
}
return $_event;
}
/**
* Build a pixel URL that will send a Tracks event when fired.
* On error, returns an empty string ('').
*
* @return string A pixel URL or empty string ('') if there were invalid args.
*/
public function build_pixel_url() {
if ( $this->error ) {
return '';
}
$args = get_object_vars( $this );
// Request Timestamp and URL Terminator must be added just before the HTTP request or not at all.
unset( $args['_rt'], $args['_'] );
$validated = self::validate_and_sanitize( $args );
if ( is_wp_error( $validated ) ) {
return '';
}
return esc_url_raw( WC_Tracks_Client::PIXEL . '?' . http_build_query( $validated ) );
}
/**
* Check if event name is valid.
*
* @param string $name Event name.
* @return false|int
*/
public static function event_name_is_valid( $name ) {
return preg_match( self::EVENT_NAME_REGEX, $name );
}
/**
* Check if a property name is valid.
*
* @param string $name Event property.
* @return false|int
*/
public static function prop_name_is_valid( $name ) {
return preg_match( self::PROP_NAME_REGEX, $name );
}
/**
* Check event names
*
* @param object $event An event object.
*/
public static function scrutinize_event_names( $event ) {
if ( ! self::event_name_is_valid( $event->_en ) ) {
return;
}
$whitelisted_key_names = array(
'anonId',
'Browser_Type',
);
foreach ( array_keys( (array) $event ) as $key ) {
if ( in_array( $key, $whitelisted_key_names, true ) ) {
continue;
}
if ( ! self::prop_name_is_valid( $key ) ) {
return;
}
}
}
}

View File

@ -0,0 +1,148 @@
<?php
/**
* PHP Tracks Client
*
* @package WooCommerce\Tracks
*/
/**
* WC_Tracks class.
*/
class WC_Tracks {
/**
* Prefix.
*
* @todo Find a good prefix.
*/
const PREFIX = 'wca_test_';
/**
* Get the identity to send to tracks.
*
* @todo Determine the best way to identify sites/users with/without Jetpack connection.
* @param int $user_id User id.
* @return array Identity properties.
*/
public static function get_identity( $user_id ) {
$has_jetpack = class_exists( 'Jetpack' ) && is_callable( 'Jetpack::is_active' ) && Jetpack::is_active();
// Meta is set, and user is still connected. Use WPCOM ID.
$wpcom_id = $has_jetpack && get_user_meta( $user_id, 'jetpack_tracks_wpcom_id', true );
if ( $wpcom_id && Jetpack::is_user_connected( $user_id ) ) {
return array(
'_ut' => 'wpcom:user_id',
'_ui' => $wpcom_id,
);
}
// User is connected, but no meta is set yet. Use WPCOM ID and set meta.
if ( $has_jetpack && Jetpack::is_user_connected( $user_id ) ) {
$wpcom_user_data = Jetpack::get_connected_user_data( $user_id );
add_user_meta( $user_id, 'jetpack_tracks_wpcom_id', $wpcom_user_data['ID'], true );
return array(
'_ut' => 'wpcom:user_id',
'_ui' => $wpcom_user_data['ID'],
);
}
// User isn't linked at all. Fall back to anonymous ID.
$anon_id = get_user_meta( $user_id, 'jetpack_tracks_anon_id', true );
if ( ! $anon_id ) {
$anon_id = WC_Tracks_Client::get_anon_id();
add_user_meta( $user_id, 'jetpack_tracks_anon_id', $anon_id, false );
}
if ( ! isset( $_COOKIE['tk_ai'] ) && ! headers_sent() ) {
wc_setcookie( 'tk_ai', $anon_id );
}
return array(
'_ut' => 'anon',
'_ui' => $anon_id,
);
}
/**
* Gather blog related properties.
*
* @param int $user_id User id.
* @return array Blog details.
*/
public static function get_blog_details( $user_id ) {
return array(
// @todo Add revenue/product info and url similar to wc-tracker.
'url' => get_option( 'siteurl' ),
'blog_lang' => get_user_locale( $user_id ),
'blog_id' => ( class_exists( 'Jetpack' ) && Jetpack_Options::get_option( 'id' ) ) || null,
);
}
/**
* Gather details from the request to the server.
*
* @return array Server details.
*/
public static function get_server_details() {
$data = array();
$data['_via_ua'] = isset( $_SERVER['HTTP_USER_AGENT'] ) ? wc_clean( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ) : '';
$data['_via_ip'] = isset( $_SERVER['REMOTE_ADDR'] ) ? wc_clean( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : '';
$data['_lg'] = isset( $_SERVER['HTTP_ACCEPT_LANGUAGE'] ) ? wc_clean( wp_unslash( $_SERVER['HTTP_ACCEPT_LANGUAGE'] ) ) : '';
$data['_dr'] = isset( $_SERVER['HTTP_REFERER'] ) ? wc_clean( wp_unslash( $_SERVER['HTTP_REFERER'] ) ) : '';
$uri = isset( $_SERVER['REQUEST_URI'] ) ? wc_clean( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '';
$host = isset( $_SERVER['HTTP_HOST'] ) ? wc_clean( wp_unslash( $_SERVER['HTTP_HOST'] ) ) : '';
$data['_dl'] = isset( $_SERVER['REQUEST_SCHEME'] ) ? wc_clean( wp_unslash( $_SERVER['REQUEST_SCHEME'] ) ) . '://' . $host . $uri : '';
return $data;
}
/**
* Record an event in Tracks - this is the preferred way to record events from PHP.
*
* @param string $event_name The name of the event.
* @param array $properties Custom properties to send with the event.
* @return bool|WP_Error True for success or WP_Error if the event pixel could not be fired.
*/
public static function record_event( $event_name, $properties = array() ) {
/**
* Don't track users who haven't opted-in to tracking or if a filter
* has been applied to turn it off.
*/
if (
'yes' !== get_option( 'woocommerce_allow_tracking' ) ||
! apply_filters( 'woocommerce_apply_tracking', true )
) {
return false;
}
$user = wp_get_current_user();
// We don't want to track user events during unit tests/CI runs.
if ( $user instanceof WP_User && 'wptests_capabilities' === $user->cap_key ) {
return false;
}
$data = array(
'_en' => self::PREFIX . $event_name,
'_ts' => WC_Tracks_Client::build_timestamp(),
);
$server_details = self::get_server_details();
$identity = self::get_identity( $user->ID );
$blog_details = self::get_blog_details( $user->ID );
$event_obj = new WC_Tracks_Event( array_merge( $data, $server_details, $identity, $blog_details, $properties ) );
if ( is_wp_error( $event_obj->error ) ) {
return $event_obj->error;
}
return $event_obj->record();
}
}