summaryrefslogtreecommitdiff
blob: c3d786d88805f0e72434b2e1b9007ee4d227b10b (plain)
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
<?php
/**
 * Sets up the Connection XML-RPC methods.
 *
 * @package automattic/jetpack-connection
 */

namespace Automattic\Jetpack\Connection;

/**
 * Registers the XML-RPC methods for Connections.
 */
class XMLRPC_Connector {
	/**
	 * The Connection Manager.
	 *
	 * @var Manager
	 */
	private $connection;

	/**
	 * Constructor.
	 *
	 * @param Manager $connection The Connection Manager.
	 */
	public function __construct( Manager $connection ) {
		$this->connection = $connection;

		// Adding the filter late to avoid being overwritten by Jetpack's XMLRPC server.
		add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ), 20 );
	}

	/**
	 * Attached to the `xmlrpc_methods` filter.
	 *
	 * @param array $methods The already registered XML-RPC methods.
	 * @return array
	 */
	public function xmlrpc_methods( $methods ) {
		return array_merge(
			$methods,
			array(
				'jetpack.verifyRegistration' => array( $this, 'verify_registration' ),
			)
		);
	}

	/**
	 * Handles verification that a site is registered.
	 *
	 * @param array $registration_data The data sent by the XML-RPC client:
	 *                                 [ $secret_1, $user_id ].
	 *
	 * @return string|IXR_Error
	 */
	public function verify_registration( $registration_data ) {
		return $this->output( $this->connection->handle_registration( $registration_data ) );
	}

	/**
	 * Normalizes output for XML-RPC.
	 *
	 * @param mixed $data The data to output.
	 */
	private function output( $data ) {
		if ( is_wp_error( $data ) ) {
			$code = $data->get_error_data();
			if ( ! $code ) {
				$code = -10520;
			}

			if ( ! class_exists( \IXR_Error::class ) ) {
				require_once ABSPATH . WPINC . '/class-IXR.php';
			}
			return new \IXR_Error(
				$code,
				sprintf( 'Jetpack: [%s] %s', $data->get_error_code(), $data->get_error_message() )
			);
		}

		return $data;
	}
}