Completed
Push — update/build-to-prepare-for-wp... ( a960c5...31a28f )
by
unknown
156:22 queued 147:01
created

Jetpack_Memberships::user_can_edit()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 0
dl 0
loc 5
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * Jetpack_Memberships: wrapper for memberships functions.
4
 *
5
 * @package    Jetpack
6
 * @since      7.3.0
7
 */
8
9
use Automattic\Jetpack\Blocks;
10
11
/**
12
 * Class Jetpack_Memberships
13
 * This class represents the Memberships functionality.
14
 */
15
class Jetpack_Memberships {
16
	/**
17
	 * CSS class prefix to use in the styling.
18
	 *
19
	 * @var string
20
	 */
21
	public static $css_classname_prefix = 'jetpack-memberships';
22
	/**
23
	 * Our CPT type for the product (plan).
24
	 *
25
	 * @var string
26
	 */
27
	public static $post_type_plan = 'jp_mem_plan';
28
	/**
29
	 * Option that will store currently set up account (Stripe etc) id for memberships.
30
	 *
31
	 * @var string
32
	 */
33
	public static $connected_account_id_option_name = 'jetpack-memberships-connected-account-id';
34
	/**
35
	 * Button block type to use.
36
	 *
37
	 * @var string
38
	 */
39
	private static $button_block_name = 'recurring-payments';
40
41
	/**
42
	 * These are defaults for wp_kses ran on the membership button.
43
	 *
44
	 * @var array
45
	 */
46
	private static $tags_allowed_in_the_button = array( 'br' => array() );
47
48
	/**
49
	 * The minimum required plan for this Gutenberg block.
50
	 *
51
	 * @var string Plan slug
52
	 */
53
	private static $required_plan;
54
55
	/**
56
	 * Track recurring payments block registration.
57
	 *
58
	 * @var boolean True if block registration has been executed.
59
	 */
60
	private static $has_registered_block = false;
61
62
	/**
63
	 * Classic singleton pattern
64
	 *
65
	 * @var Jetpack_Memberships
66
	 */
67
	private static $instance;
68
69
	/**
70
	 * Currencies we support and Stripe's minimum amount for a transaction in that currency.
71
	 *
72
	 * @link https://stripe.com/docs/currencies#minimum-and-maximum-charge-amounts
73
	 *
74
	 * List has to be in with `SUPPORTED_CURRENCIES` in extensions/shared/currencies.js and
75
	 * `Memberships_Product::SUPPORTED_CURRENCIES` in the WP.com memberships library.
76
	 */
77
	const SUPPORTED_CURRENCIES = array(
78
		'USD' => 0.5,
79
		'AUD' => 0.5,
80
		'BRL' => 0.5,
81
		'CAD' => 0.5,
82
		'CHF' => 0.5,
83
		'DKK' => 2.5,
84
		'EUR' => 0.5,
85
		'GBP' => 0.3,
86
		'HKD' => 4.0,
87
		'INR' => 0.5,
88
		'JPY' => 50,
89
		'MXN' => 10,
90
		'NOK' => 3.0,
91
		'NZD' => 0.5,
92
		'PLN' => 2.0,
93
		'SEK' => 3.0,
94
		'SGD' => 0.5,
95
	);
96
97
	/**
98
	 * Jetpack_Memberships constructor.
99
	 */
100
	private function __construct() {}
101
102
	/**
103
	 * The actual constructor initializing the object.
104
	 *
105
	 * @return Jetpack_Memberships
106
	 */
107 View Code Duplication
	public static function get_instance() {
108
		if ( ! self::$instance ) {
109
			self::$instance = new self();
110
			self::$instance->register_init_hook();
111
			// Yes, `personal-bundle` with a dash, `jetpack_personal` with an underscore. Check the v1.5 endpoint to verify.
112
			self::$required_plan = ( defined( 'IS_WPCOM' ) && IS_WPCOM ) ? 'personal-bundle' : 'jetpack_personal';
113
		}
114
115
		return self::$instance;
116
	}
117
	/**
118
	 * Get the map that defines the shape of CPT post. keys are names of fields and
119
	 * 'meta' is the name of actual WP post meta field that corresponds.
120
	 *
121
	 * @return array
122
	 */
123
	private static function get_plan_property_mapping() {
124
		$meta_prefix = 'jetpack_memberships_';
125
		$properties  = array(
126
			'price'    => array(
127
				'meta' => $meta_prefix . 'price',
128
			),
129
			'currency' => array(
130
				'meta' => $meta_prefix . 'currency',
131
			),
132
		);
133
		return $properties;
134
	}
135
136
	/**
137
	 * Inits further hooks on init hook.
138
	 */
139
	private function register_init_hook() {
140
		add_action( 'init', array( $this, 'init_hook_action' ) );
141
		add_action( 'jetpack_register_gutenberg_extensions', array( $this, 'register_gutenberg_block' ) );
142
	}
143
144
	/**
145
	 * Actual hooks initializing on init.
146
	 */
147
	public function init_hook_action() {
148
		add_filter( 'rest_api_allowed_post_types', array( $this, 'allow_rest_api_types' ) );
149
		add_filter( 'jetpack_sync_post_meta_whitelist', array( $this, 'allow_sync_post_meta' ) );
150
		$this->setup_cpts();
151
	}
152
153
	/**
154
	 * Sets up the custom post types for the module.
155
	 */
156
	private function setup_cpts() {
157
		/*
158
		 * PLAN data structure.
159
		 */
160
		$capabilities = array(
161
			'edit_post'          => 'edit_posts',
162
			'read_post'          => 'read_private_posts',
163
			'delete_post'        => 'delete_posts',
164
			'edit_posts'         => 'edit_posts',
165
			'edit_others_posts'  => 'edit_others_posts',
166
			'publish_posts'      => 'publish_posts',
167
			'read_private_posts' => 'read_private_posts',
168
		);
169
		$order_args   = array(
170
			'label'               => esc_html__( 'Plan', 'jetpack' ),
171
			'description'         => esc_html__( 'Recurring Payments plans', 'jetpack' ),
172
			'supports'            => array( 'title', 'custom-fields', 'content' ),
173
			'hierarchical'        => false,
174
			'public'              => false,
175
			'show_ui'             => false,
176
			'show_in_menu'        => false,
177
			'show_in_admin_bar'   => false,
178
			'show_in_nav_menus'   => false,
179
			'can_export'          => true,
180
			'has_archive'         => false,
181
			'exclude_from_search' => true,
182
			'publicly_queryable'  => false,
183
			'rewrite'             => false,
184
			'capabilities'        => $capabilities,
185
			'show_in_rest'        => false,
186
		);
187
		register_post_type( self::$post_type_plan, $order_args );
188
	}
189
190
	/**
191
	 * Allows custom post types to be used by REST API.
192
	 *
193
	 * @param array $post_types - other post types.
194
	 *
195
	 * @see hook 'rest_api_allowed_post_types'
196
	 * @return array
197
	 */
198
	public function allow_rest_api_types( $post_types ) {
199
		$post_types[] = self::$post_type_plan;
200
201
		return $post_types;
202
	}
203
204
	/**
205
	 * Allows custom meta fields to sync.
206
	 *
207
	 * @param array $post_meta - previously changet post meta.
208
	 *
209
	 * @return array
210
	 */
211
	public function allow_sync_post_meta( $post_meta ) {
212
		$meta_keys = array_map(
213
			array( $this, 'return_meta' ),
214
			$this->get_plan_property_mapping()
215
		);
216
		return array_merge( $post_meta, array_values( $meta_keys ) );
217
	}
218
219
	/**
220
	 * This returns meta attribute of passet array.
221
	 * Used for array functions.
222
	 *
223
	 * @param array $map - stuff.
224
	 *
225
	 * @return mixed
226
	 */
227
	public function return_meta( $map ) {
228
		return $map['meta'];
229
	}
230
231
	/**
232
	 * Renders a preview of the Recurring Payment button, which is not hooked
233
	 * up to the subscription url. Used to preview the block on the frontend
234
	 * for site editors when Stripe has not been connected.
235
	 *
236
	 * @param array  $attrs - attributes in the shortcode.
237
	 * @param string $content - Recurring Payment block content.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $content not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
238
	 *
239
	 * @return string|void
240
	 */
241
	public function render_button_preview( $attrs, $content = null ) {
242
		if ( ! empty( $content ) ) {
243
			$block_id = esc_attr( wp_unique_id( 'recurring-payments-block-' ) );
244
			$content  = str_replace( 'recurring-payments-id', $block_id, $content );
245
			return $content;
246
		}
247
		return $this->deprecated_render_button_v1( $attrs, null );
248
	}
249
250
	/**
251
	 * Determines whether the button preview should be rendered. Returns true
252
	 * if the user has editing permissions, the button is not configured correctly
253
	 * (because it requires a plan upgrade or Stripe connection), and the
254
	 * button is a child of a Premium Content block.
255
	 *
256
	 * @param WP_Block $block Recurring Payments block instance.
257
	 *
258
	 * @return boolean
259
	 */
260
	public function should_render_button_preview( $block ) {
261
		$user_can_edit              = $this->user_can_edit();
262
		$requires_stripe_connection = ! $this->get_connected_account_id();
263
264
		$requires_upgrade = ! self::is_supported_jetpack_recurring_payments();
265
266
		$is_premium_content_child = false;
267
		if ( isset( $block ) && isset( $block->context['isPremiumContentChild'] ) ) {
268
			$is_premium_content_child = (int) $block->context['isPremiumContentChild'];
269
		}
270
271
		return (
272
			$is_premium_content_child &&
0 ignored issues
show
Bug Best Practice introduced by
The expression $is_premium_content_child of type integer|false is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
273
			$user_can_edit &&
274
			( $requires_upgrade || $requires_stripe_connection )
275
		);
276
	}
277
278
	/**
279
	 * Callback that parses the membership purchase shortcode.
280
	 *
281
	 * @param array    $attributes - attributes in the shortcode. `id` here is the CPT id of the plan.
282
	 * @param string   $content - Recurring Payment block content.
283
	 * @param WP_Block $block - Recurring Payment block instance.
284
	 *
285
	 * @return string|void
286
	 */
287
	public function render_button( $attributes, $content, $block ) {
288
		Jetpack_Gutenberg::load_assets_as_required( self::$button_block_name, array( 'thickbox', 'wp-polyfill' ) );
289
290
		if ( $this->should_render_button_preview( $block ) ) {
291
			return $this->render_button_preview( $attributes, $content );
292
		}
293
294
		if ( empty( $attributes['planId'] ) ) {
295
			return;
296
		}
297
298
		$plan_id = (int) $attributes['planId'];
299
		$product = get_post( $plan_id );
300
		if ( ! $product || is_wp_error( $product ) ) {
301
			return;
302
		}
303
		if ( $product->post_type !== self::$post_type_plan || 'publish' !== $product->post_status ) {
304
			return;
305
		}
306
307
		add_thickbox();
308
309
		if ( ! empty( $content ) ) {
310
			$block_id      = esc_attr( wp_unique_id( 'recurring-payments-block-' ) );
311
			$content       = str_replace( 'recurring-payments-id', $block_id, $content );
312
			$subscribe_url = $this->get_subscription_url( $plan_id );
313
			return str_replace( 'href="#"', 'href="' . $subscribe_url . '"', $content );
314
		}
315
316
		return $this->deprecated_render_button_v1( $attributes, $plan_id );
317
	}
318
319
	/**
320
	 * Builds subscription URL for this membership using the current blog and
321
	 * supplied plan IDs.
322
	 *
323
	 * @param integer $plan_id - Unique ID for the plan being subscribed to.
324
	 * @return string
325
	 */
326
	public function get_subscription_url( $plan_id ) {
327
		global $wp;
328
329
		return add_query_arg(
330
			array(
331
				'blog'     => esc_attr( self::get_blog_id() ),
332
				'plan'     => esc_attr( $plan_id ),
333
				'lang'     => esc_attr( get_locale() ),
334
				'pid'      => esc_attr( get_the_ID() ), // Needed for analytics purposes.
335
				'redirect' => esc_attr( rawurlencode( home_url( $wp->request ) ) ), // Needed for redirect back in case of redirect-based flow.
336
			),
337
			'https://subscribe.wordpress.com/memberships/'
338
		);
339
	}
340
341
	/**
342
	 * Renders a deprecated legacy version of the button HTML.
343
	 *
344
	 * @param array   $attrs - Array containing the Recurring Payment block attributes.
345
	 * @param integer $plan_id - Unique plan ID the membership is for.
346
	 *
347
	 * @return string
348
	 */
349
	public function deprecated_render_button_v1( $attrs, $plan_id ) {
350
		$button_label = isset( $attrs['submitButtonText'] )
351
			? $attrs['submitButtonText']
352
			: __( 'Your contribution', 'jetpack' );
353
354
		$button_styles = array();
355 View Code Duplication
		if ( ! empty( $attrs['customBackgroundButtonColor'] ) ) {
356
			array_push(
357
				$button_styles,
358
				sprintf(
359
					'background-color: %s',
360
					sanitize_hex_color( $attrs['customBackgroundButtonColor'] )
361
				)
362
			);
363
		}
364 View Code Duplication
		if ( ! empty( $attrs['customTextButtonColor'] ) ) {
365
			array_push(
366
				$button_styles,
367
				sprintf(
368
					'color: %s',
369
					sanitize_hex_color( $attrs['customTextButtonColor'] )
370
				)
371
			);
372
		}
373
		$button_styles = implode( ';', $button_styles );
374
375
		return sprintf(
376
			'<div class="%1$s"><a role="button" %6$s href="%2$s" class="%3$s" style="%4$s">%5$s</a></div>',
377
			esc_attr(
378
				Jetpack_Gutenberg::block_classes(
379
					self::$button_block_name,
380
					$attrs,
381
					array( 'wp-block-button' )
382
				)
383
			),
384
			esc_url( $this->get_subscription_url( $plan_id ) ),
385
			isset( $attrs['submitButtonClasses'] ) ? esc_attr( $attrs['submitButtonClasses'] ) : 'wp-block-button__link',
386
			esc_attr( $button_styles ),
387
			wp_kses( $button_label, self::$tags_allowed_in_the_button ),
388
			isset( $attrs['submitButtonAttributes'] ) ? sanitize_text_field( $attrs['submitButtonAttributes'] ) : '' // Needed for arbitrary target=_blank on WPCOM VIP.
389
		);
390
	}
391
392
	/**
393
	 * Get current blog id.
394
	 *
395
	 * @return int
396
	 */
397
	public static function get_blog_id() {
398
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
399
			return get_current_blog_id();
400
		}
401
402
		return Jetpack_Options::get_option( 'id' );
403
	}
404
405
	/**
406
	 * Get the id of the connected payment acount (Stripe etc).
407
	 *
408
	 * @return int|void
409
	 */
410
	public static function get_connected_account_id() {
411
		return get_option( self::$connected_account_id_option_name );
412
	}
413
414
	/**
415
	 * Determines whether the current user can edit.
416
	 *
417
	 * @return bool Whether the user can edit.
418
	 */
419
	public static function user_can_edit() {
420
		$user = wp_get_current_user();
421
		// phpcs:ignore ImportDetection.Imports.RequireImports.Symbol
422
		return 0 !== $user->ID && current_user_can( 'edit_post', get_the_ID() );
423
	}
424
425
	/**
426
	 * Whether Recurring Payments are enabled. True if the block
427
	 * is supported by the site's plan, or if it is a Jetpack site
428
	 * and the feature to enable upgrade nudges is active.
429
	 *
430
	 * @return bool
431
	 */
432
	public static function is_enabled_jetpack_recurring_payments() {
433
		return (
434
			self::is_supported_jetpack_recurring_payments() ||
435
			(
436
				Jetpack::is_active() &&
437
				/** This filter is documented in class.jetpack-gutenberg.php */
438
				! apply_filters( 'jetpack_block_editor_enable_upgrade_nudge', false )
439
			)
440
		);
441
	}
442
443
	/**
444
	 * Whether the site's plan supports the Recurring Payments block.
445
	 */
446
	public static function is_supported_jetpack_recurring_payments() {
447
		// For WPCOM sites.
448
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM && function_exists( 'has_any_blog_stickers' ) ) {
449
			$site_id = get_current_blog_id();
450
			return has_any_blog_stickers( array( 'personal-plan', 'premium-plan', 'business-plan', 'ecommerce-plan' ), $site_id );
451
		}
452
		// For Jetpack sites.
453
		return (
454
			Jetpack::is_active() &&
455
			Jetpack_Plan::supports( 'recurring-payments' )
456
		);
457
	}
458
459
	/**
460
	 * Register the Recurring Payments Gutenberg block
461
	 */
462
	public function register_gutenberg_block() {
463
		// This gate was introduced to prevent duplicate registration. A race condition exists where
464
		// the registration that happens via extensions/blocks/recurring-payments/recurring-payments.php
465
		// was adding the registration action after the action had been run in some contexts.
466
		if ( self::$has_registered_block ) {
467
			return;
468
		}
469
470
		if ( self::is_enabled_jetpack_recurring_payments() ) {
471
			$deprecated = function_exists( 'gutenberg_get_post_from_context' );
472
			$uses       = $deprecated ? 'context' : 'uses_context';
473
			Blocks::jetpack_register_block(
474
				'jetpack/recurring-payments',
475
				array(
476
					'render_callback' => array( $this, 'render_button' ),
477
					$uses             => array( 'isPremiumContentChild' ),
478
				)
479
			);
480
		} else {
481
			Jetpack_Gutenberg::set_extension_unavailable(
482
				'jetpack/recurring-payments',
483
				'missing_plan',
484
				array(
485
					'required_feature' => 'memberships',
486
					'required_plan'    => self::$required_plan,
487
				)
488
			);
489
		}
490
491
		self::$has_registered_block = true;
492
	}
493
}
494
Jetpack_Memberships::get_instance();
495