namespace WPForms\Integrations\UsageTracking;
class SendUsageTask extends Task {
* Action name for this task.
const ACTION = 'wpforms_send_usage_data';
* Server URL to send requests to.
const TRACK_URL = 'https://wpformsusage.com/v1/track';
* Option name to store the timestamp of the last run.
const LAST_RUN = 'wpforms_send_usage_last_run';
public function __construct() {
parent::__construct( self::ACTION );
* Initialize the task with all the proper checks.
// Register the action handler.
$tasks = wpforms()->obj( 'tasks' );
// Add new if none exists.
if ( $tasks->is_scheduled( self::ACTION ) !== false ) {
$this->recurring( $this->generate_start_date(), WEEK_IN_SECONDS )->register();
private function hooks() {
add_action( self::ACTION, [ $this, 'process' ] );
* Randomly pick a timestamp
* which is not more than 1 week in the future
* starting from next sunday.
private function generate_start_date() {
$tracking['days'] = wp_rand( 0, 6 ) * DAY_IN_SECONDS;
$tracking['hours'] = wp_rand( 0, 23 ) * HOUR_IN_SECONDS;
$tracking['minutes'] = wp_rand( 0, 59 ) * MINUTE_IN_SECONDS;
$tracking['seconds'] = wp_rand( 0, 59 );
return strtotime( 'next sunday' ) + array_sum( $tracking );
* Send the actual data in a POST request.
public function process() {
$last_run = get_option( self::LAST_RUN );
// Make sure we do not run it more than once a day.
( time() - $last_run ) < DAY_IN_SECONDS
// Send data to the usage tracking API.
$ut = new UsageTracking();
'body' => $ut->get_data(),
'user-agent' => $ut->get_user_agent(),
// Update the last run option to the current timestamp.
update_option( self::LAST_RUN, time() );