<?php
/**
 * Jetpack Heartbeat package.
 *
 * @package  automattic/jetpack-connection
 */

namespace Automattic\Jetpack;

use Automattic\Jetpack\Connection\Rest_Authentication;
use Automattic\Jetpack\Connection\REST_Connector;
use Automattic\Jetpack\Connection\Utils;
use Jetpack_Options;
use WP_CLI;
use WP_Error;
use WP_REST_Request;
use WP_REST_Server;

/**
 * Heartbeat sends a batch of stats to wp.com once a day
 */
class Heartbeat {

	/**
	 * Holds the singleton instance of this class
	 *
	 * @since 1.0.0
	 * @since-jetpack 2.3.3
	 * @var Heartbeat
	 */
	private static $instance = false;

	/**
	 * Cronjob identifier
	 *
	 * @var string
	 */
	private $cron_name = 'jetpack_v2_heartbeat';

	/**
	 * Singleton
	 *
	 * @since 1.0.0
	 * @since-jetpack 2.3.3
	 * @static
	 * @return Heartbeat
	 */
	public static function init() {
		if ( ! self::$instance ) {
			self::$instance = new Heartbeat();
		}

		return self::$instance;
	}

	/**
	 * Constructor for singleton
	 *
	 * @since 1.0.0
	 * @since-jetpack 2.3.3
	 */
	private function __construct() {

		// Schedule the task.
		add_action( $this->cron_name, array( $this, 'cron_exec' ) );

		if ( ! wp_next_scheduled( $this->cron_name ) ) {
			// Deal with the old pre-3.0 weekly one.
			$timestamp = wp_next_scheduled( 'jetpack_heartbeat' );
			if ( $timestamp ) {
				wp_unschedule_event( $timestamp, 'jetpack_heartbeat' );
			}

			wp_schedule_event( time(), 'daily', $this->cron_name );
		}

		add_filter( 'jetpack_xmlrpc_unauthenticated_methods', array( __CLASS__, 'jetpack_xmlrpc_methods' ) );

		if ( defined( 'WP_CLI' ) && WP_CLI ) {
			WP_CLI::add_command( 'jetpack-heartbeat', array( $this, 'cli_callback' ) );
		}

		add_action( 'rest_api_init', array( $this, 'initialize_rest_api' ) );
	}

	/**
	 * Method that gets executed on the wp-cron call
	 *
	 * @since 1.0.0
	 * @since-jetpack 2.3.3
	 * @global string $wp_version
	 */
	public function cron_exec() {

		$a8c_mc_stats = new A8c_Mc_Stats();

		/*
		 * This should run daily.  Figuring in for variances in
		 * WP_CRON, don't let it run more than every 23 hours at most.
		 *
		 * i.e. if it ran less than 23 hours ago, fail out.
		 */
		$last = (int) Jetpack_Options::get_option( 'last_heartbeat' );
		if ( $last && ( $last + DAY_IN_SECONDS - HOUR_IN_SECONDS > time() ) ) {
			return;
		}

		/*
		 * Check for an identity crisis
		 *
		 * If one exists:
		 * - Bump stat for ID crisis
		 * - Email site admin about potential ID crisis
		 */

		// Coming Soon!

		foreach ( self::generate_stats_array( 'v2-' ) as $key => $value ) {
			if ( is_array( $value ) ) {
				foreach ( $value as $v ) {
					$a8c_mc_stats->add( $key, (string) $v );
				}
			} else {
				$a8c_mc_stats->add( $key, (string) $value );
			}
		}

		Jetpack_Options::update_option( 'last_heartbeat', time() );

		$a8c_mc_stats->do_server_side_stats();

		/**
		 * Fires when we synchronize all registered options on heartbeat.
		 *
		 * @since 3.3.0
		 */
		do_action( 'jetpack_heartbeat' );
	}

	/**
	 * Generates heartbeat stats data.
	 *
	 * @param string $prefix Prefix to add before stats identifier.
	 *
	 * @return array The stats array.
	 */
	public static function generate_stats_array( $prefix = '' ) {

		/**
		 * This filter is used to build the array of stats that are bumped once a day by Jetpack Heartbeat.
		 *
		 * Filter the array and add key => value pairs where
		 * * key is the stat group name
		 * * value is the stat name.
		 *
		 * Example:
		 * add_filter( 'jetpack_heartbeat_stats_array', function( $stats ) {
		 *    $stats['is-https'] = is_ssl() ? 'https' : 'http';
		 * });
		 *
		 * This will bump the stats for the 'is-https/https' or 'is-https/http' stat.
		 *
		 * @param array  $stats The stats to be filtered.
		 * @param string $prefix The prefix that will automatically be added at the begining at each stat group name.
		 */
		$stats  = apply_filters( 'jetpack_heartbeat_stats_array', array(), $prefix );
		$return = array();

		// Apply prefix to stats.
		foreach ( $stats as $stat => $value ) {
			$return[ "$prefix$stat" ] = $value;
		}

		return $return;
	}

	/**
	 * Generates the site environment stats that are reported in the heartbeat.
	 *
	 * These describe the host environment (WordPress/PHP versions, site configuration, etc.)
	 * rather than the Jetpack plugin itself, so they live in the Connection package and are
	 * reported for every connected site, including standalone-connection installs.
	 *
	 * @since 8.7.9
	 *
	 * @return array The environment stats array, keyed by unprefixed stat name.
	 */
	public static function get_environment_stats() {
		$stats = array();

		$stats['wp-version']   = get_bloginfo( 'version' );
		$stats['php-version']  = PHP_VERSION;
		$stats['wp-branch']    = (float) get_bloginfo( 'version' );
		$stats['php-branch']   = (float) PHP_VERSION;
		$stats['public']       = Jetpack_Options::get_option( 'public' );
		$stats['ssl']          = self::permit_ssl();
		$stats['is-https']     = is_ssl() ? 'https' : 'http';
		$stats['language']     = get_bloginfo( 'language' );
		$stats['charset']      = get_bloginfo( 'charset' );
		$stats['is-multisite'] = is_multisite() ? 'multisite' : 'singlesite';
		$stats['plugins']      = implode( ',', self::get_active_plugins() );

		if ( function_exists( 'get_mu_plugins' ) ) {
			$stats['mu-plugins'] = implode( ',', array_keys( get_mu_plugins() ) );
		}

		if ( function_exists( 'get_space_used' ) ) { // Only available in multisite.
			$space_used = get_space_used();
		} else {
			// This is the same as `get_space_used`, except it does not apply the short-circuit filter.
			$upload_dir = wp_upload_dir();
			$space_used = get_dirsize( $upload_dir['basedir'] ) / MB_IN_BYTES;
		}

		$stats['space-used'] = $space_used;

		// is-multi-network can have three values, `single-site`, `single-network`, and `multi-network`.
		$stats['is-multi-network'] = 'single-site';
		if ( is_multisite() ) {
			$stats['is-multi-network'] = ( new Status() )->is_multi_network() ? 'multi-network' : 'single-network';
		}

		if ( ! empty( $_SERVER['SERVER_ADDR'] ) || ! empty( $_SERVER['LOCAL_ADDR'] ) ) {
			$ip     = ! empty( $_SERVER['SERVER_ADDR'] ) ? wp_unslash( $_SERVER['SERVER_ADDR'] ) : wp_unslash( $_SERVER['LOCAL_ADDR'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Sanitized just below.
			$ip_arr = array_map( 'intval', explode( '.', $ip ) );
			if ( 4 === count( $ip_arr ) ) {
				$stats['ip-2-octets'] = implode( '.', array_slice( $ip_arr, 0, 2 ) );
			}
		}

		return $stats;
	}

	/**
	 * Checks whether the site can connect to WordPress.com over SSL.
	 *
	 * This is the canonical SSL connectivity check. It caches both the boolean result (in the
	 * `jetpack_https_test` transient) and a structured failure reason (via
	 * {@see self::get_ssl_test_error()}) so a single check serves both the `ssl` heartbeat stat
	 * and consumers such as the Jetpack plugin's admin notice, which renders a localized message
	 * from the reason code. This avoids duplicate network checks and keeps translated strings out
	 * of the package.
	 *
	 * @since 8.7.9
	 *
	 * @param bool $force_recheck Force the SSL recheck instead of using the cached result.
	 * @return bool Whether the site can connect to WordPress.com over SSL.
	 */
	public static function permit_ssl( $force_recheck = false ) {
		$ssl = false;
		if ( ! $force_recheck ) {
			$ssl = get_transient( 'jetpack_https_test' );
		}

		if ( $force_recheck || false === $ssl ) {
			$error = array(
				'code'   => '',
				'detail' => '',
			);

			$api_base = Constants::get_constant( 'JETPACK__API_BASE' );
			if ( ! $api_base ) {
				$api_base = Utils::DEFAULT_JETPACK__API_BASE;
			}

			if ( ! str_starts_with( $api_base, 'https' ) ) {
				$ssl = 0;
			} else {
				$ssl = 1;

				if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
					$ssl           = 0;
					$error['code'] = 'no_ssl_support';
				} else {
					$response = wp_remote_get( $api_base . 'test/1/' );
					if ( is_wp_error( $response ) ) {
						$ssl           = 0;
						$error['code'] = 'no_ssl_support';
					} elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
						$ssl             = 0;
						$error['code']   = 'bad_response';
						$error['detail'] = wp_remote_retrieve_body( $response );
					}
				}
			}
			set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
			set_transient( 'jetpack_https_test_error', $error, DAY_IN_SECONDS );
		}

		return (bool) $ssl;
	}

	/**
	 * Returns the structured reason for the last SSL connectivity failure.
	 *
	 * Consumers can map the returned reason code to a localized message. The `detail` value
	 * carries any additional context (e.g. the unexpected response body for `bad_response`).
	 *
	 * @since 8.7.9
	 *
	 * @return array {
	 *     The last SSL test error.
	 *
	 *     @type string $code   Reason code: '' (no error), 'no_ssl_support', or 'bad_response'.
	 *     @type string $detail Additional context for the failure, if any.
	 * }
	 */
	public static function get_ssl_test_error() {
		$error = get_transient( 'jetpack_https_test_error' );

		if ( ! is_array( $error ) ) {
			$error = array();
		}

		return array(
			'code'   => isset( $error['code'] ) ? (string) $error['code'] : '',
			'detail' => isset( $error['detail'] ) ? (string) $error['detail'] : '',
		);
	}

	/**
	 * Gets all plugins currently active, regardless of whether they're traditionally
	 * activated or network activated.
	 *
	 * Ported from the Jetpack plugin so the `plugins` heartbeat stat can be generated from
	 * the Connection package. This is the canonical implementation; the Jetpack plugin's
	 * `Jetpack::get_active_plugins()` delegates to it.
	 *
	 * @since 8.7.9
	 *
	 * @return array
	 */
	public static function get_active_plugins() {
		$active_plugins = (array) get_option( 'active_plugins', array() );

		if ( is_multisite() ) {
			// Due to legacy code, active_sitewide_plugins stores them in the keys,
			// whereas active_plugins stores them in the values.
			$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
			if ( $network_plugins ) {
				$active_plugins = array_merge( $active_plugins, $network_plugins );
			}
		}

		sort( $active_plugins );

		return array_unique( $active_plugins );
	}

	/**
	 * Registers jetpack.getHeartbeatData xmlrpc method
	 *
	 * @param array $methods The list of methods to be filtered.
	 * @return array $methods
	 */
	public static function jetpack_xmlrpc_methods( $methods ) {
		$methods['jetpack.getHeartbeatData'] = array( __CLASS__, 'xmlrpc_data_response' );
		return $methods;
	}

	/**
	 * Handles the response for the jetpack.getHeartbeatData xmlrpc method
	 *
	 * @param array $params The parameters received in the request.
	 * @return array $params all the stats that heartbeat handles.
	 */
	public static function xmlrpc_data_response( $params = array() ) {
		// The WordPress XML-RPC server sets a default param of array()
		// if no argument is passed on the request and the method handlers get this array in $params.
		// generate_stats_array() needs a string as first argument.
		$params = empty( $params ) ? '' : $params;
		return self::generate_stats_array( $params );
	}

	/**
	 * Clear scheduled events
	 *
	 * @return void
	 */
	public function deactivate() {
		// Deal with the old pre-3.0 weekly one.
		$timestamp = wp_next_scheduled( 'jetpack_heartbeat' );
		if ( $timestamp ) {
			wp_unschedule_event( $timestamp, 'jetpack_heartbeat' );
		}

		$timestamp = wp_next_scheduled( $this->cron_name );
		wp_unschedule_event( $timestamp, $this->cron_name );
	}

	/**
	 * Interact with the Heartbeat
	 *
	 * ## OPTIONS
	 *
	 * inspect (default): Gets the list of data that is going to be sent in the heartbeat and the date/time of the last heartbeat
	 *
	 * @param array $args Arguments passed via CLI.
	 *
	 * @return void
	 */
	public function cli_callback( $args ) {

		$allowed_args = array(
			'inspect',
		);

		if ( isset( $args[0] ) && ! in_array( $args[0], $allowed_args, true ) ) {
			/* translators: %s is a command like "prompt" */
			WP_CLI::error( sprintf( __( '%s is not a valid command.', 'jetpack-connection' ), $args[0] ) );
		}

		$stats           = self::generate_stats_array();
		$formatted_stats = array();

		foreach ( $stats as $stat_name => $bin ) {
			$formatted_stats[] = array(
				'Stat name' => $stat_name,
				'Bin'       => $bin,
			);
		}

		WP_CLI\Utils\format_items( 'table', $formatted_stats, array( 'Stat name', 'Bin' ) );

		$last_heartbeat = Jetpack_Options::get_option( 'last_heartbeat' );

		if ( $last_heartbeat ) {
			$last_date = gmdate( 'Y-m-d H:i:s', $last_heartbeat );
			/* translators: %s is the full datetime of the last heart beat e.g. 2020-01-01 12:21:23 */
			WP_CLI::line( sprintf( __( 'Last heartbeat sent at: %s', 'jetpack-connection' ), $last_date ) );
		}
	}

	/**
	 * Initialize the heartbeat REST API.
	 *
	 * @return void
	 */
	public function initialize_rest_api() {
		register_rest_route(
			'jetpack/v4',
			'/heartbeat/data',
			array(
				'methods'             => WP_REST_Server::READABLE,
				'callback'            => array( $this, 'rest_heartbeat_data' ),
				'permission_callback' => array( $this, 'rest_heartbeat_data_permission_check' ),
				'args'                => array(
					'prefix' => array(
						'description' => __( 'Prefix to add before the stats identifiers.', 'jetpack-connection' ),
						'type'        => 'string',
					),
				),
			)
		);
	}

	/**
	 * Endpoint to retrieve the heartbeat data.
	 *
	 * @param WP_REST_Request $request The request data.
	 *
	 * @since 2.7.0
	 *
	 * @return array
	 */
	public function rest_heartbeat_data( WP_REST_Request $request ) {
		return static::generate_stats_array( $request->get_param( 'prefix' ) );
	}

	/**
	 * Check permissions for the `get_heartbeat_data` endpoint.
	 *
	 * @return true|WP_Error
	 */
	public function rest_heartbeat_data_permission_check() {
		if ( current_user_can( 'jetpack_connect' ) ) {
			return true;
		}

		return Rest_Authentication::is_signed_with_blog_token()
			? true
			: new WP_Error( 'invalid_permission_heartbeat_data', REST_Connector::get_user_permissions_error_msg(), array( 'status' => rest_authorization_required_code() ) );
	}
}
