Completed
Push — renovate/puppeteer-5.x ( fecc33...bd64e9 )
by Bernhard
67:54 queued 59:02
created

Jetpack_Memberships::get_connected_account_id()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 3
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
	 * Callback that parses the membership purchase shortcode.
232
	 *
233
	 * @param array  $attrs - attributes in the shortcode. `id` here is the CPT id of the plan.
234
	 * @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...
235
	 *
236
	 * @return string|void
237
	 */
238
	public function render_button( $attrs, $content = null ) {
239
		Jetpack_Gutenberg::load_assets_as_required( self::$button_block_name, array( 'thickbox', 'wp-polyfill' ) );
240
241
		if ( empty( $attrs['planId'] ) ) {
242
			return;
243
		}
244
		$plan_id = (int) $attrs['planId'];
245
		$product = get_post( $plan_id );
246
		if ( ! $product || is_wp_error( $product ) ) {
247
			return;
248
		}
249
		if ( $product->post_type !== self::$post_type_plan || 'publish' !== $product->post_status ) {
250
			return;
251
		}
252
253
		add_thickbox();
254
255
		if ( ! empty( $content ) ) {
256
			$block_id      = esc_attr( wp_unique_id( 'recurring-payments-block-' ) );
257
			$content       = str_replace( 'recurring-payments-id', $block_id, $content );
258
			$subscribe_url = $this->get_subscription_url( $plan_id );
259
			return str_replace( 'href="#"', 'href="' . $subscribe_url . '"', $content );
260
		}
261
262
		return $this->deprecated_render_button_v1( $attrs, $plan_id );
263
	}
264
265
	/**
266
	 * Builds subscription URL for this membership using the current blog and
267
	 * supplied plan IDs.
268
	 *
269
	 * @param integer $plan_id - Unique ID for the plan being subscribed to.
270
	 * @return string
271
	 */
272
	public function get_subscription_url( $plan_id ) {
273
		global $wp;
274
275
		return add_query_arg(
276
			array(
277
				'blog'     => esc_attr( self::get_blog_id() ),
278
				'plan'     => esc_attr( $plan_id ),
279
				'lang'     => esc_attr( get_locale() ),
280
				'pid'      => esc_attr( get_the_ID() ), // Needed for analytics purposes.
281
				'redirect' => esc_attr( rawurlencode( home_url( $wp->request ) ) ), // Needed for redirect back in case of redirect-based flow.
282
			),
283
			'https://subscribe.wordpress.com/memberships/'
284
		);
285
	}
286
287
	/**
288
	 * Renders a deprecated legacy version of the button HTML.
289
	 *
290
	 * @param array   $attrs - Array containing the Recurring Payment block attributes.
291
	 * @param integer $plan_id - Unique plan ID the membership is for.
292
	 *
293
	 * @return string
294
	 */
295
	public function deprecated_render_button_v1( $attrs, $plan_id ) {
296
		$button_label = isset( $attrs['submitButtonText'] )
297
			? $attrs['submitButtonText']
298
			: __( 'Your contribution', 'jetpack' );
299
300
		$button_styles = array();
301 View Code Duplication
		if ( ! empty( $attrs['customBackgroundButtonColor'] ) ) {
302
			array_push(
303
				$button_styles,
304
				sprintf(
305
					'background-color: %s',
306
					sanitize_hex_color( $attrs['customBackgroundButtonColor'] )
307
				)
308
			);
309
		}
310 View Code Duplication
		if ( ! empty( $attrs['customTextButtonColor'] ) ) {
311
			array_push(
312
				$button_styles,
313
				sprintf(
314
					'color: %s',
315
					sanitize_hex_color( $attrs['customTextButtonColor'] )
316
				)
317
			);
318
		}
319
		$button_styles = implode( ';', $button_styles );
320
321
		return sprintf(
322
			'<div class="%1$s"><a role="button" %6$s href="%2$s" class="%3$s" style="%4$s">%5$s</a></div>',
323
			esc_attr(
324
				Jetpack_Gutenberg::block_classes(
325
					self::$button_block_name,
326
					$attrs,
327
					array( 'wp-block-button' )
328
				)
329
			),
330
			esc_url( $this->get_subscription_url( $plan_id ) ),
331
			isset( $attrs['submitButtonClasses'] ) ? esc_attr( $attrs['submitButtonClasses'] ) : 'wp-block-button__link',
332
			esc_attr( $button_styles ),
333
			wp_kses( $button_label, self::$tags_allowed_in_the_button ),
334
			isset( $attrs['submitButtonAttributes'] ) ? sanitize_text_field( $attrs['submitButtonAttributes'] ) : '' // Needed for arbitrary target=_blank on WPCOM VIP.
335
		);
336
	}
337
338
	/**
339
	 * Get current blog id.
340
	 *
341
	 * @return int
342
	 */
343
	public static function get_blog_id() {
344
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
345
			return get_current_blog_id();
346
		}
347
348
		return Jetpack_Options::get_option( 'id' );
349
	}
350
351
	/**
352
	 * Get the id of the connected payment acount (Stripe etc).
353
	 *
354
	 * @return int|void
355
	 */
356
	public static function get_connected_account_id() {
357
		return get_option( self::$connected_account_id_option_name );
358
	}
359
360
	/**
361
	 * Whether Recurring Payments are enabled.
362
	 *
363
	 * @return bool
364
	 */
365
	public static function is_enabled_jetpack_recurring_payments() {
366
		// For WPCOM sites.
367 View Code Duplication
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM && function_exists( 'has_any_blog_stickers' ) ) {
368
			$site_id = get_current_blog_id();
369
			return has_any_blog_stickers( array( 'personal-plan', 'premium-plan', 'business-plan', 'ecommerce-plan' ), $site_id );
370
		}
371
372
		// For Jetpack sites.
373
		return Jetpack::is_active() && (
374
			/** This filter is documented in class.jetpack-gutenberg.php */
375
			! apply_filters( 'jetpack_block_editor_enable_upgrade_nudge', false ) || // Remove when the default becomes `true`.
376
			Jetpack_Plan::supports( 'recurring-payments' )
377
		);
378
	}
379
380
	/**
381
	 * Register the Recurring Payments Gutenberg block
382
	 */
383
	public function register_gutenberg_block() {
384
		// This gate was introduced to prevent duplicate registration. A race condition exists where
385
		// the registration that happens via extensions/blocks/recurring-payments/recurring-payments.php
386
		// was adding the registration action after the action had been run in some contexts.
387
		if ( self::$has_registered_block ) {
388
			return;
389
		}
390
391
		if ( self::is_enabled_jetpack_recurring_payments() ) {
392
			Blocks::jetpack_register_block(
393
				'jetpack/recurring-payments',
394
				array(
395
					'render_callback' => array( $this, 'render_button' ),
396
				)
397
			);
398
		} else {
399
			Jetpack_Gutenberg::set_extension_unavailable(
400
				'jetpack/recurring-payments',
401
				'missing_plan',
402
				array(
403
					'required_feature' => 'memberships',
404
					'required_plan'    => self::$required_plan,
405
				)
406
			);
407
		}
408
409
		self::$has_registered_block = true;
410
	}
411
}
412
Jetpack_Memberships::get_instance();
413