class.llms.tracker.php 2.06 KB
Newer Older
cyrille's avatar
cyrille committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
<?php
/**
 * Handle sending data to LifterLMS when tracking is enabled
 *
 * @package LifterLMS/Classes
 *
 * @since 3.0.0
 * @version 3.0.0
 */

defined( 'ABSPATH' ) || exit;

/**
 * LifterLMS telemetry tracking data.
 *
 * @since 3.0.0
 */
class LLMS_Tracker {

	/**
	 * URL endpoint where we'll receive the data
	 */
	const API_URL = 'https://lifterlms.com/llms-api/tracking';

	/**
	 * Initialize.
	 *
	 * @since 3.0.0
	 *
	 * @return void
	 */
	public static function init() {
		add_action( 'llms_send_tracking_data', array( __CLASS__, 'send_data' ) );
	}

	/**
	 * Retrieve a timestamp of the last time the tracks sent data home
	 *
	 * @since    3.0.0
	 *
	 * @return   int        a timestamp
	 */
	private static function get_last_send_time() {
		return apply_filters( 'llms_tracker_get_last_send_time', get_option( 'llms_tracker_last_send_time', 0 ) );
	}

	/**
	 * Send data home
	 *
	 * @since    3.0.0
	 *
	 * @param    boolean $force  force a send regardless or the last send time
	 *
	 * @return   void
	 */
	public static function send_data( $force = false ) {

		// Don't trigger during AJAX Requests.
		if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
			return;
		}

		// Allow forcing of the send despite the interval.
		if ( ! $force && ! apply_filters( 'llms_tracker_force_send', false ) ) {

			// Only send data once a week.
			$last_send = self::get_last_send_time();
			if ( $last_send && $last_send > apply_filters( 'llms_tracker_send_interval', strtotime( '-1 week' ) ) ) {
				return;
			}
		}

		// Record a last send time.
		update_option( 'llms_tracker_last_send_time', time() );

		$r = wp_remote_post(
			self::API_URL,
			array(
				'body'        => array(
					'data' => json_encode( LLMS_Data::get_data( 'tracker' ) ),
				),
				'cookies'     => array(),
				'headers'     => array(
					'user-agent' => 'LifterLMS_Tracker/' . md5( esc_url( home_url( '/' ) ) ) . ';',
				),
				'method'      => 'POST',
				'redirection' => 5,
				'timeout'     => 60,
			)
		);

		if ( ! is_wp_error( $r ) ) {

			return json_decode( $r['body'], true );

		} else {

			return $r;

		}

	}

}