summaryrefslogtreecommitdiff
blob: c664e9e824b6764b0e6c2d288d271fb95c65fed3 (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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
<?php
/**
 * Class for the Jetpack partner coupon logic.
 *
 * @package automattic/jetpack-partner
 */

namespace Automattic\Jetpack;

use Automattic\Jetpack\Connection\Client as Connection_Client;
use Automattic\Jetpack\Connection\Manager as Connection_Manager;
use Jetpack_Options;

/**
 * Disable direct access.
 */
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class Jetpack_Partner_Coupon
 *
 * @since 1.6.0
 */
class Partner_Coupon {

	/**
	 * Name of the Jetpack_Option coupon option.
	 *
	 * @var string
	 */
	public static $coupon_option = 'partner_coupon';

	/**
	 * Name of the Jetpack_Option added option.
	 *
	 * @var string
	 */
	public static $added_option = 'partner_coupon_added';

	/**
	 * Name of "last availability check" transient.
	 *
	 * @var string
	 */
	public static $last_check_transient = 'jetpack_partner_coupon_last_check';

	/**
	 * Callable that executes a blog-authenticated request.
	 *
	 * @var callable
	 */
	protected $request_as_blog;

	/**
	 * Jetpack_Partner_Coupon
	 *
	 * @var Partner_Coupon|null
	 **/
	private static $instance = null;

	/**
	 * A list of supported partners.
	 *
	 * @var array
	 */
	private static $supported_partners = array(
		'IONOS' => array(
			'name' => 'IONOS',
			'logo' => array(
				'src'    => '/images/ionos-logo.jpg',
				'width'  => 119,
				'height' => 32,
			),
		),
	);

	/**
	 * A list of supported presets.
	 *
	 * @var array
	 */
	private static $supported_presets = array(
		'IONA' => 'jetpack_backup_daily',
	);

	/**
	 * Get singleton instance of class.
	 *
	 * @return Partner_Coupon
	 */
	public static function get_instance() {
		if ( self::$instance === null ) {
			self::$instance = new Partner_Coupon( array( Connection_Client::class, 'wpcom_json_api_request_as_blog' ) );
		}

		return self::$instance;
	}

	/**
	 * Constructor.
	 *
	 * @param callable $request_as_blog Callable that executes a blog-authenticated request.
	 */
	public function __construct( $request_as_blog ) {
		$this->request_as_blog = $request_as_blog;
	}

	/**
	 * Register hooks to catch and purge coupon.
	 *
	 * @param string $plugin_slug The plugin slug to differentiate between Jetpack connections.
	 * @param string $redirect_location The location we should redirect to after catching the coupon.
	 */
	public static function register_coupon_admin_hooks( $plugin_slug, $redirect_location ) {
		$instance = self::get_instance();

		// We have to use an anonymous function, so we can pass along relevant information
		// and not have to hardcode values for a single plugin.
		// This open up the opportunity for e.g. the "all-in-one" and backup plugins
		// to both implement partner coupon logic.
		add_action(
			'admin_init',
			function () use ( $plugin_slug, $redirect_location, $instance ) {
				$instance->catch_coupon( $plugin_slug, $redirect_location );
				$instance->maybe_purge_coupon( $plugin_slug );
			}
		);
	}

	/**
	 * Catch partner coupon and redirect to claim component.
	 *
	 * @param string $plugin_slug The plugin slug to differentiate between Jetpack connections.
	 * @param string $redirect_location The location we should redirect to after catching the coupon.
	 */
	public function catch_coupon( $plugin_slug, $redirect_location ) {
		// Accept and store a partner coupon if present, and redirect to Jetpack connection screen.
		$partner_coupon = isset( $_GET['jetpack-partner-coupon'] ) ? sanitize_text_field( wp_unslash( $_GET['jetpack-partner-coupon'] ) ) : false; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
		if ( $partner_coupon ) {
			Jetpack_Options::update_options(
				array(
					self::$coupon_option => $partner_coupon,
					self::$added_option  => time(),
				)
			);

			$connection = new Connection_Manager( $plugin_slug );
			if ( $connection->is_connected() ) {
				$redirect_location = add_query_arg( array( 'showCouponRedemption' => 1 ), $redirect_location );
				wp_safe_redirect( $redirect_location );
			} else {
				wp_safe_redirect( $redirect_location );
			}
		}
	}

	/**
	 * Purge partner coupon.
	 *
	 * We try to remotely check if a coupon looks valid. We also automatically purge
	 * partner coupons after a certain amount of time to prevent unnecessary look-ups
	 * and/or promoting a product for months or years in the future due to unknown
	 * errors.
	 *
	 * @param string $plugin_slug The plugin slug to differentiate between Jetpack connections.
	 */
	public function maybe_purge_coupon( $plugin_slug ) {
		// Only run coupon checks on Jetpack admin pages.
		// The "admin-ui" package is responsible for registering the Jetpack admin
		// page for all Jetpack plugins and has hardcoded the settings page to be
		// "jetpack", so we shouldn't need to allow for dynamic/custom values.
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		if ( ! isset( $_GET['page'] ) || 'jetpack' !== $_GET['page'] ) {
			return;
		}

		if ( ( new Status() )->is_offline_mode() ) {
			return;
		}

		$connection = new Connection_Manager( $plugin_slug );
		if ( ! $connection->is_connected() ) {
			return;
		}

		if ( $this->maybe_purge_coupon_by_added_date() ) {
			return;
		}

		// Limit checks to happen once a minute at most.
		if ( get_transient( self::$last_check_transient ) ) {
			return;
		}

		set_transient( self::$last_check_transient, true, MINUTE_IN_SECONDS );

		$this->maybe_purge_coupon_by_availability_check();
	}

	/**
	 * Purge coupon based on local added date.
	 *
	 * We automatically remove the coupon after a month to "self-heal" if
	 * something in the claim process has broken with the site.
	 *
	 * @return bool Return whether we should skip further purge checks.
	 */
	protected function maybe_purge_coupon_by_added_date() {
		$date = Jetpack_Options::get_option( self::$added_option, '' );

		if ( empty( $date ) ) {
			return true;
		}

		$expire_date = strtotime( '+30 days', $date );
		$today       = time();

		if ( $today >= $expire_date ) {
			$this->delete_coupon_data();

			return true;
		}

		return false;
	}

	/**
	 * Purge coupon based on availability check.
	 *
	 * @return bool Return whether we deleted coupon data.
	 */
	protected function maybe_purge_coupon_by_availability_check() {
		$blog_id = Jetpack_Options::get_option( 'id', false );

		if ( ! $blog_id ) {
			return false;
		}

		$coupon = self::get_coupon();

		if ( ! $coupon ) {
			return false;
		}

		$response = call_user_func_array(
			$this->request_as_blog,
			array(
				add_query_arg(
					array( 'coupon_code' => $coupon['coupon_code'] ),
					sprintf(
						'/sites/%d/jetpack-partner/coupon/v1/site/coupon',
						$blog_id
					)
				),
				2,
				array( 'method' => 'GET' ),
				null,
				'wpcom',
			)
		);

		$body = json_decode( wp_remote_retrieve_body( $response ), true );

		if (
			200 === wp_remote_retrieve_response_code( $response ) &&
			is_array( $body ) &&
			isset( $body['available'] ) &&
			false === $body['available']
		) {
			$this->delete_coupon_data();

			return true;
		}

		return false;
	}

	/**
	 * Delete all coupon data.
	 */
	protected function delete_coupon_data() {
		Jetpack_Options::delete_option(
			array(
				self::$coupon_option,
				self::$added_option,
			)
		);
	}

	/**
	 * Get partner coupon data.
	 *
	 * @return array|bool
	 */
	public static function get_coupon() {
		$coupon_code = Jetpack_Options::get_option( self::$coupon_option, '' );

		if ( ! is_string( $coupon_code ) || empty( $coupon_code ) ) {
			return false;
		}

		$instance = self::get_instance();
		$partner  = $instance->get_coupon_partner( $coupon_code );

		if ( ! $partner ) {
			return false;
		}

		$preset = $instance->get_coupon_preset( $coupon_code );

		if ( ! $preset ) {
			return false;
		}

		$product = $instance->get_coupon_product( $preset );

		if ( ! $product ) {
			return false;
		}

		return array(
			'coupon_code' => $coupon_code,
			'partner'     => $partner,
			'preset'      => $preset,
			'product'     => $product,
		);
	}

	/**
	 * Get coupon partner.
	 *
	 * @param string $coupon_code Coupon code to go through.
	 * @return array|bool
	 */
	private function get_coupon_partner( $coupon_code ) {
		if ( ! is_string( $coupon_code ) || false === strpos( $coupon_code, '_' ) ) {
			return false;
		}

		$prefix             = strtok( $coupon_code, '_' );
		$supported_partners = $this->get_supported_partners();

		if ( ! isset( $supported_partners[ $prefix ] ) ) {
			return false;
		}

		return array(
			'name'   => $supported_partners[ $prefix ]['name'],
			'prefix' => $prefix,
			'logo'   => isset( $supported_partners[ $prefix ]['logo'] ) ? $supported_partners[ $prefix ]['logo'] : null,
		);
	}

	/**
	 * Get coupon product.
	 *
	 * @param string $coupon_preset The preset we wish to find a product for.
	 * @return array|bool
	 */
	private function get_coupon_product( $coupon_preset ) {
		if ( ! is_string( $coupon_preset ) ) {
			return false;
		}

		/**
		 * Allow for plugins to register supported products.
		 *
		 * @since 1.6.0
		 *
		 * @param array A list of product details.
		 * @return array
		 */
		$product_details = apply_filters( 'jetpack_partner_coupon_products', array() );
		$product_slug    = $this->get_supported_presets()[ $coupon_preset ];

		foreach ( $product_details as $product ) {
			if ( ! $this->array_keys_exist( array( 'title', 'slug', 'description', 'features' ), $product ) ) {
				continue;
			}

			if ( $product_slug === $product['slug'] ) {
				return $product;
			}
		}

		return false;
	}

	/**
	 * Checks if multiple keys are present in an array.
	 *
	 * @param array $needles The keys we wish to check for.
	 * @param array $haystack The array we want to compare keys against.
	 *
	 * @return bool
	 */
	private function array_keys_exist( $needles, $haystack ) {
		foreach ( $needles as $needle ) {
			if ( ! isset( $haystack[ $needle ] ) ) {
				return false;
			}
		}

		return true;
	}

	/**
	 * Get coupon preset.
	 *
	 * @param string $coupon_code Coupon code to go through.
	 * @return string|bool
	 */
	private function get_coupon_preset( $coupon_code ) {
		if ( ! is_string( $coupon_code ) ) {
			return false;
		}

		$regex   = '/^.*?_(?P<slug>.*?)_.+$/';
		$matches = array();

		if ( ! preg_match( $regex, $coupon_code, $matches ) ) {
			return false;
		}

		return isset( $this->get_supported_presets()[ $matches['slug'] ] ) ? $matches['slug'] : false;
	}

	/**
	 * Get supported partners.
	 *
	 * @return array
	 */
	private function get_supported_partners() {
		/**
		 * Allow external code to add additional supported partners.
		 *
		 * @since 1.6.0
		 *
		 * @param array $supported_partners A list of supported partners.
		 * @return array
		 */
		return apply_filters( 'jetpack_partner_coupon_supported_partners', self::$supported_partners );
	}

	/**
	 * Get supported presets.
	 *
	 * @return array
	 */
	private function get_supported_presets() {
		/**
		 * Allow external code to add additional supported presets.
		 *
		 * @since 1.6.0
		 *
		 * @param array $supported_presets A list of supported presets.
		 * @return array
		 */
		return apply_filters( 'jetpack_partner_coupon_supported_presets', self::$supported_presets );
	}

}