PK      \>  >  !  class-wc-wccom-site-installer.phpnu W+A        <?php
/**
 * WooCommerce.com Product Installation.
 *
 * @package WooCommerce\WooCommerce_Site
 * @since   3.7.0
 */

defined( 'ABSPATH' ) || exit;

/**
 * WC_WCCOM_Site_Installer Class
 *
 * Contains functionalities to install products via WooCommerce.com helper connection.
 */
class WC_WCCOM_Site_Installer {

	/**
	 * Error message returned install_package if the folder already exists.
	 *
	 * @var string
	 */
	private static $folder_exists = 'folder_exists';

	/**
	 * Default state.
	 *
	 * @var array
	 */
	private static $default_state = array(
		'status'       => 'idle',
		'steps'        => array(),
		'current_step' => null,
	);

	/**
	 * Represents product step state.
	 *
	 * @var array
	 */
	private static $default_step_state = array(
		'download_url'   => '',
		'product_type'   => '',
		'last_step'      => '',
		'last_error'     => '',
		'download_path'  => '',
		'unpacked_path'  => '',
		'installed_path' => '',
		'activate'       => false,
	);

	/**
	 * Product install steps. Each step is a method name in this class that
	 * will be passed with product ID arg \WP_Upgrader instance.
	 *
	 * @var array
	 */
	private static $install_steps = array(
		'get_product_info',
		'download_product',
		'unpack_product',
		'move_product',
		'activate_product',
	);

	/**
	 * Get the product install state.
	 *
	 * @since 3.7.0
	 * @param string $key Key in state data. If empty key is passed array of
	 *                    state will be returned.
	 * @return array Product install state.
	 */
	public static function get_state( $key = '' ) {
		$state = WC_Helper_Options::get( 'product_install', self::$default_state );
		if ( ! empty( $key ) ) {
			return isset( $state[ $key ] ) ? $state[ $key ] : null;
		}

		return $state;
	}

	/**
	 * Update the product install state.
	 *
	 * @since 3.7.0
	 * @param string $key   Key in state data.
	 * @param mixed  $value Value.
	 */
	public static function update_state( $key, $value ) {
		$state = WC_Helper_Options::get( 'product_install', self::$default_state );

		$state[ $key ] = $value;
		WC_Helper_Options::update( 'product_install', $state );
	}

	/**
	 * Reset product install state.
	 *
	 * @since 3.7.0
	 * @param array $products List of product IDs.
	 */
	public static function reset_state( $products = array() ) {
		WC()->queue()->cancel_all( 'woocommerce_wccom_install_products' );
		WC_Helper_Options::update( 'product_install', self::$default_state );
	}

	/**
	 * Schedule installing given list of products.
	 *
	 * @since 3.7.0
	 * @param array $products Array of products where key is product ID and
	 *                        element is install args.
	 * @return array State.
	 */
	public static function schedule_install( $products ) {
		$state  = self::get_state();
		$status = ! empty( $state['status'] ) ? $state['status'] : '';
		if ( 'in-progress' === $status ) {
			return $state;
		}
		self::update_state( 'status', 'in-progress' );

		$steps = array_fill_keys( array_keys( $products ), self::$default_step_state );
		self::update_state( 'steps', $steps );

		self::update_state( 'current_step', null );

		$args = array(
			'products' => $products,
		);

		// Clear the cache of customer's subscription before asking for them.
		// Thus, they will be re-fetched from WooCommerce.com after a purchase.
		WC_Helper::_flush_subscriptions_cache();

		WC()->queue()->cancel_all( 'woocommerce_wccom_install_products', $args );
		WC()->queue()->add( 'woocommerce_wccom_install_products', $args );

		return self::get_state();
	}

	/**
	 * Install a given product IDs.
	 *
	 * Run via `woocommerce_wccom_install_products` hook.
	 *
	 * @since 3.7.0
	 * @param array $products Array of products where key is product ID and
	 *                        element is install args.
	 */
	public static function install( $products ) {
		require_once ABSPATH . 'wp-admin/includes/file.php';
		require_once ABSPATH . 'wp-admin/includes/plugin-install.php';
		require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
		require_once ABSPATH . 'wp-admin/includes/plugin.php';

		WP_Filesystem();
		$upgrader = new WP_Upgrader( new Automatic_Upgrader_Skin() );
		$upgrader->init();
		wp_clean_plugins_cache();

		foreach ( $products as $product_id => $install_args ) {
			self::install_product( $product_id, $install_args, $upgrader );
		}

		self::finish_installation();
	}

	/**
	 * Finish installation by updating the state.
	 *
	 * @since 3.7.0
	 */
	private static function finish_installation() {
		$state = self::get_state();
		if ( empty( $state['steps'] ) ) {
			return;
		}

		foreach ( $state['steps'] as $step ) {
			if ( ! empty( $step['last_error'] ) ) {
				$state['status'] = 'has_error';
				break;
			}
		}

		if ( 'has_error' !== $state['status'] ) {
			$state['status'] = 'finished';
		}

		WC_Helper_Options::update( 'product_install', $state );
	}

	/**
	 * Install a single product given its ID.
	 *
	 * @since 3.7.0
	 * @param int          $product_id   Product ID.
	 * @param array        $install_args Install args.
	 * @param \WP_Upgrader $upgrader     Core class to handle installation.
	 */
	private static function install_product( $product_id, $install_args, $upgrader ) {
		foreach ( self::$install_steps as $step ) {
			self::do_install_step( $product_id, $install_args, $step, $upgrader );
		}
	}

	/**
	 * Perform product installation step.
	 *
	 * @since 3.7.0
	 * @param int          $product_id   Product ID.
	 * @param array        $install_args Install args.
	 * @param string       $step         Installation step.
	 * @param \WP_Upgrader $upgrader     Core class to handle installation.
	 */
	private static function do_install_step( $product_id, $install_args, $step, $upgrader ) {
		$state_steps = self::get_state( 'steps' );
		if ( empty( $state_steps[ $product_id ] ) ) {
			$state_steps[ $product_id ] = self::$default_step_state;
		}

		if ( ! empty( $state_steps[ $product_id ]['last_error'] ) ) {
			return;
		}

		$state_steps[ $product_id ]['last_step'] = $step;

		if ( ! empty( $install_args['activate'] ) ) {
			$state_steps[ $product_id ]['activate'] = true;
		}

		self::update_state(
			'current_step',
			array(
				'product_id' => $product_id,
				'step'       => $step,
			)
		);

		$result = call_user_func( array( __CLASS__, $step ), $product_id, $upgrader );
		if ( is_wp_error( $result ) ) {
			$state_steps[ $product_id ]['last_error'] = $result->get_error_message();
		} else {
			switch ( $step ) {
				case 'get_product_info':
					$state_steps[ $product_id ]['download_url'] = $result['download_url'];
					$state_steps[ $product_id ]['product_type'] = $result['product_type'];
					$state_steps[ $product_id ]['product_name'] = $result['product_name'];
					break;
				case 'download_product':
					$state_steps[ $product_id ]['download_path'] = $result;
					break;
				case 'unpack_product':
					$state_steps[ $product_id ]['unpacked_path'] = $result;
					break;
				case 'move_product':
					$state_steps[ $product_id ]['installed_path'] = $result['destination'];
					if ( isset( $result[ self::$folder_exists ] ) ) {
						$state_steps[ $product_id ]['warning'] = array(
							'message'     => self::$folder_exists,
							'plugin_info' => self::get_plugin_info( $state_steps[ $product_id ]['installed_path'] ),
						);
					}
					break;
			}
		}

		self::update_state( 'steps', $state_steps );
	}

	/**
	 * Get product info from its ID.
	 *
	 * @since 3.7.0
	 * @param int $product_id Product ID.
	 * @return array|\WP_Error
	 */
	private static function get_product_info( $product_id ) {
		$product_info = array(
			'download_url' => '',
			'product_type' => '',
		);

		// Get product info from woocommerce.com.
		$request = WC_Helper_API::get(
			add_query_arg(
				array( 'product_id' => absint( $product_id ) ),
				'info'
			),
			array(
				'authenticated' => true,
			)
		);

		if ( 200 !== wp_remote_retrieve_response_code( $request ) ) {
			return new WP_Error( 'product_info_failed', __( 'Failed to retrieve product info from woocommerce.com', 'woocommerce' ) );
		}

		$result = json_decode( wp_remote_retrieve_body( $request ), true );

		$product_info['product_type'] = $result['_product_type'];
		$product_info['product_name'] = $result['name'];

		if ( ! empty( $result['_wporg_product'] ) && ! empty( $result['download_link'] ) ) {
			// For wporg product, download is set already from info response.
			$product_info['download_url'] = $result['download_link'];
		} elseif ( ! WC_Helper::has_product_subscription( $product_id ) ) {
			// Non-wporg product needs subscription.
			return new WP_Error( 'missing_subscription', __( 'Missing product subscription', 'woocommerce' ) );
		} else {
			// Retrieve download URL for non-wporg product.
			WC_Helper_Updater::flush_updates_cache();
			$updates = WC_Helper_Updater::get_update_data();
			if ( empty( $updates[ $product_id ]['package'] ) ) {
				return new WP_Error( 'missing_product_package', __( 'Could not find product package.', 'woocommerce' ) );
			}

			$product_info['download_url'] = $updates[ $product_id ]['package'];
		}

		return $product_info;
	}

	/**
	 * Download product by its ID and returns the path of the zip package.
	 *
	 * @since 3.7.0
	 * @param int          $product_id Product ID.
	 * @param \WP_Upgrader $upgrader   Core class to handle installation.
	 * @return \WP_Error|string
	 */
	private static function download_product( $product_id, $upgrader ) {
		$steps = self::get_state( 'steps' );
		if ( empty( $steps[ $product_id ]['download_url'] ) ) {
			return new WP_Error( 'missing_download_url', __( 'Could not find download url for the product.', 'woocommerce' ) );
		}
		return $upgrader->download_package( $steps[ $product_id ]['download_url'] );
	}

	/**
	 * Unpack downloaded product.
	 *
	 * @since 3.7.0
	 * @param int          $product_id Product ID.
	 * @param \WP_Upgrader $upgrader   Core class to handle installation.
	 * @return \WP_Error|string
	 */
	private static function unpack_product( $product_id, $upgrader ) {
		$steps = self::get_state( 'steps' );
		if ( empty( $steps[ $product_id ]['download_path'] ) ) {
			return new WP_Error( 'missing_download_path', __( 'Could not find download path.', 'woocommerce' ) );
		}

		return $upgrader->unpack_package( $steps[ $product_id ]['download_path'], true );
	}

	/**
	 * Move product to plugins directory.
	 *
	 * @since 3.7.0
	 * @param int          $product_id Product ID.
	 * @param \WP_Upgrader $upgrader   Core class to handle installation.
	 * @return array|\WP_Error
	 */
	private static function move_product( $product_id, $upgrader ) {
		$steps = self::get_state( 'steps' );
		if ( empty( $steps[ $product_id ]['unpacked_path'] ) ) {
			return new WP_Error( 'missing_unpacked_path', __( 'Could not find unpacked path.', 'woocommerce' ) );
		}

		$destination = 'plugin' === $steps[ $product_id ]['product_type']
			? WP_PLUGIN_DIR
			: get_theme_root();

		$package = array(
			'source'        => $steps[ $product_id ]['unpacked_path'],
			'destination'   => $destination,
			'clear_working' => true,
			'hook_extra'    => array(
				'type'   => $steps[ $product_id ]['product_type'],
				'action' => 'install',
			),
		);

		$result = $upgrader->install_package( $package );

		/**
		 * If install package returns error 'folder_exists' threat as success.
		 */
		if ( is_wp_error( $result ) && array_key_exists( self::$folder_exists, $result->errors ) ) {
			return array(
				self::$folder_exists => true,
				'destination'        => $result->error_data[ self::$folder_exists ],
			);
		}
		return $result;
	}

	/**
	 * Activate product given its product ID.
	 *
	 * @since 3.7.0
	 * @param int $product_id Product ID.
	 * @return \WP_Error|null
	 */
	private static function activate_product( $product_id ) {
		$steps = self::get_state( 'steps' );
		if ( ! $steps[ $product_id ]['activate'] ) {
			return null;
		}

		if ( 'plugin' === $steps[ $product_id ]['product_type'] ) {
			return self::activate_plugin( $product_id );
		}
		return self::activate_theme( $product_id );
	}

	/**
	 * Activate plugin given its product ID.
	 *
	 * @since 3.7.0
	 * @param int $product_id Product ID.
	 * @return \WP_Error|null
	 */
	private static function activate_plugin( $product_id ) {
		// Clear plugins cache used in `WC_Helper::get_local_woo_plugins`.
		wp_clean_plugins_cache();
		$filename = false;

		// If product is WP.org one, find out its filename.
		$dir_name = self::get_wporg_product_dir_name( $product_id );
		if ( false !== $dir_name ) {
			$filename = self::get_wporg_plugin_main_file( $dir_name );
		}

		if ( false === $filename ) {
			$plugins = wp_list_filter(
				WC_Helper::get_local_woo_plugins(),
				array(
					'_product_id' => $product_id,
				)
			);

			$filename = is_array( $plugins ) && ! empty( $plugins ) ? key( $plugins ) : '';
		}

		if ( empty( $filename ) ) {
			return new WP_Error( 'unknown_filename', __( 'Unknown product filename.', 'woocommerce' ) );
		}

		return activate_plugin( $filename );
	}

	/**
	 * Activate theme given its product ID.
	 *
	 * @since 3.7.0
	 * @param int $product_id Product ID.
	 * @return \WP_Error|null
	 */
	private static function activate_theme( $product_id ) {
		// Clear plugins cache used in `WC_Helper::get_local_woo_themes`.
		wp_clean_themes_cache();
		$theme_slug = false;

		// If product is WP.org theme, find out its slug.
		$dir_name = self::get_wporg_product_dir_name( $product_id );
		if ( false !== $dir_name ) {
			$theme_slug = basename( $dir_name );
		}

		if ( false === $theme_slug ) {
			$themes = wp_list_filter(
				WC_Helper::get_local_woo_themes(),
				array(
					'_product_id' => $product_id,
				)
			);

			$theme_slug = is_array( $themes ) && ! empty( $themes ) ? dirname( key( $themes ) ) : '';
		}

		if ( empty( $theme_slug ) ) {
			return new WP_Error( 'unknown_filename', __( 'Unknown product filename.', 'woocommerce' ) );
		}

		return switch_theme( $theme_slug );
	}

	/**
	 * Get installed directory of WP.org product.
	 *
	 * @since 3.7.0
	 * @param int $product_id Product ID.
	 * @return bool|string
	 */
	private static function get_wporg_product_dir_name( $product_id ) {
		$steps   = self::get_state( 'steps' );
		$product = $steps[ $product_id ];

		if ( empty( $product['download_url'] ) || empty( $product['installed_path'] ) ) {
			return false;
		}

		// Check whether product was downloaded from WordPress.org.
		$parsed_url = wp_parse_url( $product['download_url'] );
		if ( ! empty( $parsed_url['host'] ) && 'downloads.wordpress.org' !== $parsed_url['host'] ) {
			return false;
		}

		return basename( $product['installed_path'] );
	}

	/**
	 * Get WP.org plugin's main file.
	 *
	 * @since 3.7.0
	 * @param string $dir Directory name of the plugin.
	 * @return bool|string
	 */
	private static function get_wporg_plugin_main_file( $dir ) {
		// Ensure that exact dir name is used.
		$dir = trailingslashit( $dir );

		if ( ! function_exists( 'get_plugins' ) ) {
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
		}

		$plugins = get_plugins();
		foreach ( $plugins as $path => $plugin ) {
			if ( 0 === strpos( $path, $dir ) ) {
				return $path;
			}
		}

		return false;
	}


	/**
	 * Get plugin info
	 *
	 * @since 3.9.0
	 * @param string $dir Directory name of the plugin.
	 * @return bool|array
	 */
	private static function get_plugin_info( $dir ) {
		$plugin_folder = basename( $dir );

		if ( ! function_exists( 'get_plugins' ) ) {
			require_once ABSPATH . 'wp-admin/includes/plugin.php';
		}

		$plugins = get_plugins();

		$related_plugins = array_filter(
			$plugins,
			function( $key ) use ( $plugin_folder ) {
				return strpos( $key, $plugin_folder . '/' ) === 0;
			},
			ARRAY_FILTER_USE_KEY
		);

		if ( 1 === count( $related_plugins ) ) {
			$plugin_key  = array_keys( $related_plugins )[0];
			$plugin_data = $plugins[ $plugin_key ];
			return array(
				'name'    => $plugin_data['Name'],
				'version' => $plugin_data['Version'],
				'active'  => is_plugin_active( $plugin_key ),
			);
		}
		return false;
	}
}
PK      \#k!  k!    class-wc-wccom-site.phpnu W+A        <?php
/**
 * WooCommerce.com Product Installation.
 *
 * @package WooCommerce\WooCommerce_Site
 * @since   3.7.0
 */

defined( 'ABSPATH' ) || exit;

/**
 * WC_WCCOM_Site Class
 *
 * Main class for WooCommerce.com connected site.
 */
class WC_WCCOM_Site {

	const AUTH_ERROR_FILTER_NAME = 'wccom_auth_error';

	/**
	 * Load the WCCOM site class.
	 *
	 * @since 3.7.0
	 */
	public static function load() {
		self::includes();

		add_action( 'woocommerce_wccom_install_products', array( 'WC_WCCOM_Site_Installer', 'install' ) );
		add_filter( 'determine_current_user', array( __CLASS__, 'authenticate_wccom' ), 14 );
		add_action( 'woocommerce_rest_api_get_rest_namespaces', array( __CLASS__, 'register_rest_namespace' ) );
	}

	/**
	 * Include support files.
	 *
	 * @since 3.7.0
	 */
	protected static function includes() {
		require_once WC_ABSPATH . 'includes/admin/helper/class-wc-helper.php';
		require_once WC_ABSPATH . 'includes/wccom-site/class-wc-wccom-site-installer.php';
		require_once WC_ABSPATH . 'includes/wccom-site/class-wc-wccom-site-installer-requirements-check.php';
	}

	/**
	 * Authenticate WooCommerce.com request.
	 *
	 * @since 3.7.0
	 * @param int|false $user_id User ID.
	 * @return int|false
	 */
	public static function authenticate_wccom( $user_id ) {
		if ( ! empty( $user_id ) || ! self::is_request_to_wccom_site_rest_api() ) {
			return $user_id;
		}

		$auth_header = trim( self::get_authorization_header() );

		if ( stripos( $auth_header, 'Bearer ' ) === 0 ) {
			$access_token = trim( substr( $auth_header, 7 ) );
		} elseif ( ! empty( $_GET['token'] ) && is_string( $_GET['token'] ) ) {  // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			$access_token = trim( $_GET['token'] );  // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.MissingUnslash, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
		} else {
			add_filter(
				self::AUTH_ERROR_FILTER_NAME,
				function() {
					return new WP_Error(
						WC_REST_WCCOM_Site_Installer_Errors::NO_ACCESS_TOKEN_CODE,
						WC_REST_WCCOM_Site_Installer_Errors::NO_ACCESS_TOKEN_MESSAGE,
						array( 'status' => WC_REST_WCCOM_Site_Installer_Errors::NO_ACCESS_TOKEN_HTTP_CODE )
					);
				}
			);
			return false;
		}

		if ( ! empty( $_SERVER['HTTP_X_WOO_SIGNATURE'] ) ) {
			$signature = trim( $_SERVER['HTTP_X_WOO_SIGNATURE'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash,WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
		} elseif ( ! empty( $_GET['signature'] ) && is_string( $_GET['signature'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			$signature = trim( $_GET['signature'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.MissingUnslash, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
		} else {
			add_filter(
				self::AUTH_ERROR_FILTER_NAME,
				function() {
					return new WP_Error(
						WC_REST_WCCOM_Site_Installer_Errors::NO_SIGNATURE_CODE,
						WC_REST_WCCOM_Site_Installer_Errors::NO_SIGNATURE_MESSAGE,
						array( 'status' => WC_REST_WCCOM_Site_Installer_Errors::NO_SIGNATURE_HTTP_CODE )
					);
				}
			);
			return false;
		}

		require_once WC_ABSPATH . 'includes/admin/helper/class-wc-helper-options.php';
		$site_auth = WC_Helper_Options::get( 'auth' );

		if ( empty( $site_auth['access_token'] ) ) {
			add_filter(
				self::AUTH_ERROR_FILTER_NAME,
				function() {
					return new WP_Error(
						WC_REST_WCCOM_Site_Installer_Errors::SITE_NOT_CONNECTED_CODE,
						WC_REST_WCCOM_Site_Installer_Errors::SITE_NOT_CONNECTED_MESSAGE,
						array( 'status' => WC_REST_WCCOM_Site_Installer_Errors::SITE_NOT_CONNECTED_HTTP_CODE )
					);
				}
			);
			return false;
		}

		if ( ! hash_equals( $access_token, $site_auth['access_token'] ) ) {
			add_filter(
				self::AUTH_ERROR_FILTER_NAME,
				function() {
					return new WP_Error(
						WC_REST_WCCOM_Site_Installer_Errors::INVALID_TOKEN_CODE,
						WC_REST_WCCOM_Site_Installer_Errors::INVALID_TOKEN_MESSAGE,
						array( 'status' => WC_REST_WCCOM_Site_Installer_Errors::INVALID_TOKEN_HTTP_CODE )
					);
				}
			);
			return false;
		}

		$body = WP_REST_Server::get_raw_data();

		if ( ! self::verify_wccom_request( $body, $signature, $site_auth['access_token_secret'] ) ) {
			add_filter(
				self::AUTH_ERROR_FILTER_NAME,
				function() {
					return new WP_Error(
						WC_REST_WCCOM_Site_Installer_Errors::REQUEST_VERIFICATION_FAILED_CODE,
						WC_REST_WCCOM_Site_Installer_Errors::REQUEST_VERIFICATION_FAILED_MESSAGE,
						array( 'status' => WC_REST_WCCOM_Site_Installer_Errors::REQUEST_VERIFICATION_FAILED_HTTP_CODE )
					);
				}
			);
			return false;
		}

		$user = get_user_by( 'id', $site_auth['user_id'] );
		if ( ! $user ) {
			add_filter(
				self::AUTH_ERROR_FILTER_NAME,
				function() {
					return new WP_Error(
						WC_REST_WCCOM_Site_Installer_Errors::USER_NOT_FOUND_CODE,
						WC_REST_WCCOM_Site_Installer_Errors::USER_NOT_FOUND_MESSAGE,
						array( 'status' => WC_REST_WCCOM_Site_Installer_Errors::USER_NOT_FOUND_HTTP_CODE )
					);
				}
			);
			return false;
		}

		return $user;
	}

	/**
	 * Get the authorization header.
	 *
	 * On certain systems and configurations, the Authorization header will be
	 * stripped out by the server or PHP. Typically this is then used to
	 * generate `PHP_AUTH_USER`/`PHP_AUTH_PASS` but not passed on. We use
	 * `getallheaders` here to try and grab it out instead.
	 *
	 * @since 3.7.0
	 * @return string Authorization header if set.
	 */
	protected static function get_authorization_header() {
		if ( ! empty( $_SERVER['HTTP_AUTHORIZATION'] ) ) {
			return wp_unslash( $_SERVER['HTTP_AUTHORIZATION'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
		}

		if ( function_exists( 'getallheaders' ) ) {
			$headers = getallheaders();
			// Check for the authoization header case-insensitively.
			foreach ( $headers as $key => $value ) {
				if ( 'authorization' === strtolower( $key ) ) {
					return $value;
				}
			}
		}

		return '';
	}

	/**
	 * Check if this is a request to WCCOM Site REST API.
	 *
	 * @since 3.7.0
	 * @return bool
	 */
	protected static function is_request_to_wccom_site_rest_api() {

		if ( isset( $_REQUEST['rest_route'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
			$route       = wp_unslash( $_REQUEST['rest_route'] ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.NonceVerification.Recommended
			$rest_prefix = '';
		} else {
			$route       = wp_unslash( add_query_arg( array() ) );
			$rest_prefix = trailingslashit( rest_get_url_prefix() );
		}

		return false !== strpos( $route, $rest_prefix . 'wccom-site/' );
	}

	/**
	 * Verify WooCommerce.com request from a given body and signature request.
	 *
	 * @since 3.7.0
	 * @param string $body                Request body.
	 * @param string $signature           Request signature found in X-Woo-Signature header.
	 * @param string $access_token_secret Access token secret for this site.
	 * @return bool
	 */
	protected static function verify_wccom_request( $body, $signature, $access_token_secret ) {
		// phpcs:disable WordPress.Security.ValidatedSanitizedInput.InputNotValidated, WordPress.Security.ValidatedSanitizedInput.MissingUnslash, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
		$data = array(
			'host'        => $_SERVER['HTTP_HOST'],
			'request_uri' => urldecode( remove_query_arg( array( 'token', 'signature' ), $_SERVER['REQUEST_URI'] ) ),
			'method'      => strtoupper( $_SERVER['REQUEST_METHOD'] ),
		);
		// phpcs:enable

		if ( ! empty( $body ) ) {
			$data['body'] = $body;
		}

		$expected_signature = hash_hmac( 'sha256', wp_json_encode( $data ), $access_token_secret );

		return hash_equals( $expected_signature, $signature );
	}

	/**
	 * Register wccom-site REST namespace.
	 *
	 * @since 3.7.0
	 * @param array $namespaces List of registered namespaces.
	 * @return array Registered namespaces.
	 */
	public static function register_rest_namespace( $namespaces ) {
		require_once WC_ABSPATH . 'includes/wccom-site/rest-api/class-wc-rest-wccom-site-installer-errors.php';
		require_once WC_ABSPATH . 'includes/wccom-site/rest-api/endpoints/class-wc-rest-wccom-site-installer-controller.php';

		$namespaces['wccom-site/v1'] = array(
			'installer' => 'WC_REST_WCCOM_Site_Installer_Controller',
		);

		return $namespaces;
	}
}

WC_WCCOM_Site::load();
PK      \vٕ    4  class-wc-wccom-site-installer-requirements-check.phpnu W+A        <?php
/**
 * WooCommerce.com Product Installation Requirements Check.
 *
 * @package WooCommerce\WooCommerce_Site
 * @since   3.8.0
 */

use Automattic\Jetpack\Constants;

defined( 'ABSPATH' ) || exit;

/**
 * WC_WCCOM_Site_Installer_Requirements_Check Class
 * Contains functionality to check the necessary requirements for the installer.
 */
class WC_WCCOM_Site_Installer_Requirements_Check {
	/**
	 * Check if the site met the requirements
	 *
	 * @version 3.8.0
	 * @return bool|WP_Error Does the site met the requirements?
	 */
	public static function met_requirements() {
		$errs = array();

		if ( ! self::met_wp_cron_requirement() ) {
			$errs[] = 'wp-cron';
		}

		if ( ! self::met_filesystem_requirement() ) {
			$errs[] = 'filesystem';
		}

		if ( ! empty( $errs ) ) {
			// translators: %s: Requirements unmet.
			return new WP_Error( 'requirements_not_met', sprintf( __( 'Server requirements not met, missing requirement(s): %s.', 'woocommerce' ), implode( ', ', $errs ) ), array( 'status' => 400 ) );
		}

		return true;
	}

	/**
	 * Validates if WP CRON is enabled.
	 *
	 * @since 3.8.0
	 * @return bool
	 */
	private static function met_wp_cron_requirement() {
		return ! Constants::is_true( 'DISABLE_WP_CRON' );
	}

	/**
	 * Validates if `WP_CONTENT_DIR` is writable.
	 *
	 * @since 3.8.0
	 * @return bool
	 */
	private static function met_filesystem_requirement() {
		return is_writable( WP_CONTENT_DIR );
	}
}
PK      \    D  rest-api/endpoints/class-wc-rest-wccom-site-installer-controller.phpnu W+A        <?php
/**
 * WCCOM Site Installer REST API Controller
 *
 * Handles requests to /installer.
 *
 * @package WooCommerce\WooCommerce_Site\Rest_Api
 * @since   3.7.0
 */

defined( 'ABSPATH' ) || exit;

/**
 * REST API WCCOM Site Installer Controller Class.
 *
 * @package WooCommerce/WCCOM_Site/REST_API
 * @extends WC_REST_Controller
 */
class WC_REST_WCCOM_Site_Installer_Controller extends WC_REST_Controller {

	/**
	 * Endpoint namespace.
	 *
	 * @var string
	 */
	protected $namespace = 'wccom-site/v1';

	/**
	 * Route base.
	 *
	 * @var string
	 */
	protected $rest_base = 'installer';

	/**
	 * Register the routes for product reviews.
	 *
	 * @since 3.7.0
	 */
	public function register_routes() {
		register_rest_route(
			$this->namespace,
			'/' . $this->rest_base,
			array(
				array(
					'methods'             => WP_REST_Server::READABLE,
					'callback'            => array( $this, 'get_install_state' ),
					'permission_callback' => array( $this, 'check_permission' ),
				),
				array(
					'methods'             => WP_REST_Server::CREATABLE,
					'callback'            => array( $this, 'install' ),
					'permission_callback' => array( $this, 'check_permission' ),
					'args'                => array(
						'products' => array(
							'required' => true,
							'type'     => 'object',
						),
					),
				),
				array(
					'methods'             => WP_REST_Server::DELETABLE,
					'callback'            => array( $this, 'reset_install' ),
					'permission_callback' => array( $this, 'check_permission' ),
				),
			)
		);
	}

	/**
	 * Check permissions.
	 *
	 * @since 3.7.0
	 * @param WP_REST_Request $request Full details about the request.
	 * @return bool|WP_Error
	 */
	public function check_permission( $request ) {
		$current_user = wp_get_current_user();

		if ( empty( $current_user ) || ( $current_user instanceof WP_User && ! $current_user->exists() ) ) {
			return apply_filters(
				WC_WCCOM_Site::AUTH_ERROR_FILTER_NAME,
				new WP_Error(
					WC_REST_WCCOM_Site_Installer_Errors::NOT_AUTHENTICATED_CODE,
					WC_REST_WCCOM_Site_Installer_Errors::NOT_AUTHENTICATED_MESSAGE,
					array( 'status' => WC_REST_WCCOM_Site_Installer_Errors::NOT_AUTHENTICATED_HTTP_CODE )
				)
			);
		}

		if ( ! user_can( $current_user, 'install_plugins' ) || ! user_can( $current_user, 'install_themes' ) ) {
			return new WP_Error(
				WC_REST_WCCOM_Site_Installer_Errors::NO_PERMISSION_CODE,
				WC_REST_WCCOM_Site_Installer_Errors::NO_PERMISSION_MESSAGE,
				array( 'status' => WC_REST_WCCOM_Site_Installer_Errors::NO_PERMISSION_HTTP_CODE )
			);
		}

		return true;
	}

	/**
	 * Get installation state.
	 *
	 * @since 3.7.0
	 * @param WP_REST_Request $request Full details about the request.
	 * @return bool|WP_Error
	 */
	public function get_install_state( $request ) {
		$requirements_met = WC_WCCOM_Site_Installer_Requirements_Check::met_requirements();
		if ( is_wp_error( $requirements_met ) ) {
			return $requirements_met;
		}

		return rest_ensure_response( WC_WCCOM_Site_Installer::get_state() );
	}

	/**
	 * Install WooCommerce.com products.
	 *
	 * @since 3.7.0
	 * @param WP_REST_Request $request Full details about the request.
	 * @return bool|WP_Error
	 */
	public function install( $request ) {
		$requirements_met = WC_WCCOM_Site_Installer_Requirements_Check::met_requirements();
		if ( is_wp_error( $requirements_met ) ) {
			return $requirements_met;
		}

		if ( empty( $request['products'] ) ) {
			return new WP_Error( 'missing_products', __( 'Missing products in request body.', 'woocommerce' ), array( 'status' => 400 ) );
		}

		$validation_result = $this->validate_products( $request['products'] );
		if ( is_wp_error( $validation_result ) ) {
			return $validation_result;
		}

		return rest_ensure_response( WC_WCCOM_Site_Installer::schedule_install( $request['products'] ) );
	}

	/**
	 * Reset installation state.
	 *
	 * @since 3.7.0
	 * @param WP_REST_Request $request Full details about the request.
	 * @return bool|WP_Error
	 */
	public function reset_install( $request ) {
		$resp = rest_ensure_response( WC_WCCOM_Site_Installer::reset_state() );
		$resp->set_status( 204 );

		return $resp;
	}

	/**
	 * Validate products from request body.
	 *
	 * @since 3.7.0
	 * @param array $products Array of products where key is product ID and
	 *                        element is install args.
	 * @return bool|WP_Error
	 */
	protected function validate_products( $products ) {
		$err = new WP_Error( 'invalid_products', __( 'Invalid products in request body.', 'woocommerce' ), array( 'status' => 400 ) );

		if ( ! is_array( $products ) ) {
			return $err;
		}

		foreach ( $products as $product_id => $install_args ) {
			if ( ! absint( $product_id ) ) {
				return $err;
			}

			if ( empty( $install_args ) || ! is_array( $install_args ) ) {
				return $err;
			}
		}

		return true;
	}
}
PK      \FD    6  rest-api/class-wc-rest-wccom-site-installer-errors.phpnu W+A        <?php
/**
 * WCCOM Site Installer Errors Class
 *
 * @package WooCommerce\WooCommerce_Site\Rest_Api
 * @since   3.9.0
 */

defined( 'ABSPATH' ) || exit;

/**
 * WCCOM Site Installer Errors Class
 *
 * Stores data for errors, returned by installer API.
 */
class WC_REST_WCCOM_Site_Installer_Errors {

	/**
	 * Not unauthenticated generic error
	 */
	const NOT_AUTHENTICATED_CODE      = 'not_authenticated';
	const NOT_AUTHENTICATED_MESSAGE   = 'Authentication required';
	const NOT_AUTHENTICATED_HTTP_CODE = 401;

	/**
	 * No access token provided
	 */
	const NO_ACCESS_TOKEN_CODE      = 'no_access_token';
	const NO_ACCESS_TOKEN_MESSAGE   = 'No access token provided';
	const NO_ACCESS_TOKEN_HTTP_CODE = 400;

	/**
	 * No signature provided
	 */
	const NO_SIGNATURE_CODE      = 'no_signature';
	const NO_SIGNATURE_MESSAGE   = 'No signature provided';
	const NO_SIGNATURE_HTTP_CODE = 400;

	/**
	 * Site not connected to WooCommerce.com
	 */
	const SITE_NOT_CONNECTED_CODE      = 'site_not_connnected';
	const SITE_NOT_CONNECTED_MESSAGE   = 'Site not connected to WooCommerce.com';
	const SITE_NOT_CONNECTED_HTTP_CODE = 401;

	/**
	* Provided access token is not valid
	*/
	const INVALID_TOKEN_CODE      = 'invalid_token';
	const INVALID_TOKEN_MESSAGE   = 'Invalid access token provided';
	const INVALID_TOKEN_HTTP_CODE = 401;

	/**
	 * Request verification by provided signature failed
	 */
	const REQUEST_VERIFICATION_FAILED_CODE      = 'request_verification_failed';
	const REQUEST_VERIFICATION_FAILED_MESSAGE   = 'Request verification by signature failed';
	const REQUEST_VERIFICATION_FAILED_HTTP_CODE = 400;

	/**
	 * User doesn't exist
	 */
	const USER_NOT_FOUND_CODE      = 'user_not_found';
	const USER_NOT_FOUND_MESSAGE   = 'Token owning user not found';
	const USER_NOT_FOUND_HTTP_CODE = 401;

	/**
	 * No permissions error
	 */
	const NO_PERMISSION_CODE      = 'forbidden';
	const NO_PERMISSION_MESSAGE   = 'You do not have permission to install plugin or theme';
	const NO_PERMISSION_HTTP_CODE = 403;
}
PK        \>  >  !                class-wc-wccom-site-installer.phpnu W+A        PK        \#k!  k!              >  class-wc-wccom-site.phpnu W+A        PK        \vٕ    4            `  class-wc-wccom-site-installer-requirements-check.phpnu W+A        PK        \    D            }f  rest-api/endpoints/class-wc-rest-wccom-site-installer-controller.phpnu W+A        PK        \FD    6            y  rest-api/class-wc-rest-wccom-site-installer-errors.phpnu W+A        PK      &  #    