Completed
Push — update/composer-lock ( 4bc3dc...ab53f1 )
by Jeremy
08:14
created

is_enabled_jetpack_recurring_payments()   A

Complexity

Conditions 6
Paths 4

Size

Total Lines 14

Duplication

Lines 4
Ratio 28.57 %

Importance

Changes 0
Metric Value
cc 6
nc 4
nop 0
dl 4
loc 14
rs 9.2222
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
/**
10
 * Class Jetpack_Memberships
11
 * This class represents the Memberships functionality.
12
 */
13
class Jetpack_Memberships {
14
	/**
15
	 * CSS class prefix to use in the styling.
16
	 *
17
	 * @var string
18
	 */
19
	public static $css_classname_prefix = 'jetpack-memberships';
20
	/**
21
	 * Our CPT type for the product (plan).
22
	 *
23
	 * @var string
24
	 */
25
	public static $post_type_plan = 'jp_mem_plan';
26
	/**
27
	 * Option that will store currently set up account (Stripe etc) id for memberships.
28
	 *
29
	 * @var string
30
	 */
31
	public static $connected_account_id_option_name = 'jetpack-memberships-connected-account-id';
32
	/**
33
	 * Button block type to use.
34
	 *
35
	 * @var string
36
	 */
37
	private static $button_block_name = 'recurring-payments';
38
39
	/**
40
	 * These are defaults for wp_kses ran on the membership button.
41
	 *
42
	 * @var array
43
	 */
44
	private static $tags_allowed_in_the_button = array( 'br' => array() );
45
46
	/**
47
	 * The minimum required plan for this Gutenberg block.
48
	 *
49
	 * @var string Plan slug
50
	 */
51
	private static $required_plan;
52
53
	/**
54
	 * Track recurring payments block registration.
55
	 *
56
	 * @var boolean True if block registration has been executed.
57
	 */
58
	private static $has_registered_block = false;
59
60
	/**
61
	 * Classic singleton pattern
62
	 *
63
	 * @var Jetpack_Memberships
64
	 */
65
	private static $instance;
66
67
	/**
68
	 * Jetpack_Memberships constructor.
69
	 */
70
	private function __construct() {}
71
72
	/**
73
	 * The actual constructor initializing the object.
74
	 *
75
	 * @return Jetpack_Memberships
76
	 */
77 View Code Duplication
	public static function get_instance() {
78
		if ( ! self::$instance ) {
79
			self::$instance = new self();
80
			self::$instance->register_init_hook();
81
			// Yes, `personal-bundle` with a dash, `jetpack_personal` with an underscore. Check the v1.5 endpoint to verify.
82
			self::$required_plan = ( defined( 'IS_WPCOM' ) && IS_WPCOM ) ? 'personal-bundle' : 'jetpack_personal';
83
		}
84
85
		return self::$instance;
86
	}
87
	/**
88
	 * Get the map that defines the shape of CPT post. keys are names of fields and
89
	 * 'meta' is the name of actual WP post meta field that corresponds.
90
	 *
91
	 * @return array
92
	 */
93
	private static function get_plan_property_mapping() {
94
		$meta_prefix = 'jetpack_memberships_';
95
		$properties  = array(
96
			'price'    => array(
97
				'meta' => $meta_prefix . 'price',
98
			),
99
			'currency' => array(
100
				'meta' => $meta_prefix . 'currency',
101
			),
102
		);
103
		return $properties;
104
	}
105
106
	/**
107
	 * Inits further hooks on init hook.
108
	 */
109
	private function register_init_hook() {
110
		add_action( 'init', array( $this, 'init_hook_action' ) );
111
		add_action( 'jetpack_register_gutenberg_extensions', array( $this, 'register_gutenberg_block' ) );
112
	}
113
114
	/**
115
	 * Actual hooks initializing on init.
116
	 */
117
	public function init_hook_action() {
118
		add_filter( 'rest_api_allowed_post_types', array( $this, 'allow_rest_api_types' ) );
119
		add_filter( 'jetpack_sync_post_meta_whitelist', array( $this, 'allow_sync_post_meta' ) );
120
		$this->setup_cpts();
121
	}
122
123
	/**
124
	 * Sets up the custom post types for the module.
125
	 */
126
	private function setup_cpts() {
127
		/*
128
		 * PLAN data structure.
129
		 */
130
		$capabilities = array(
131
			'edit_post'          => 'edit_posts',
132
			'read_post'          => 'read_private_posts',
133
			'delete_post'        => 'delete_posts',
134
			'edit_posts'         => 'edit_posts',
135
			'edit_others_posts'  => 'edit_others_posts',
136
			'publish_posts'      => 'publish_posts',
137
			'read_private_posts' => 'read_private_posts',
138
		);
139
		$order_args   = array(
140
			'label'               => esc_html__( 'Plan', 'jetpack' ),
141
			'description'         => esc_html__( 'Recurring Payments plans', 'jetpack' ),
142
			'supports'            => array( 'title', 'custom-fields', 'content' ),
143
			'hierarchical'        => false,
144
			'public'              => false,
145
			'show_ui'             => false,
146
			'show_in_menu'        => false,
147
			'show_in_admin_bar'   => false,
148
			'show_in_nav_menus'   => false,
149
			'can_export'          => true,
150
			'has_archive'         => false,
151
			'exclude_from_search' => true,
152
			'publicly_queryable'  => false,
153
			'rewrite'             => false,
154
			'capabilities'        => $capabilities,
155
			'show_in_rest'        => false,
156
		);
157
		register_post_type( self::$post_type_plan, $order_args );
158
	}
159
160
	/**
161
	 * Allows custom post types to be used by REST API.
162
	 *
163
	 * @param array $post_types - other post types.
164
	 *
165
	 * @see hook 'rest_api_allowed_post_types'
166
	 * @return array
167
	 */
168
	public function allow_rest_api_types( $post_types ) {
169
		$post_types[] = self::$post_type_plan;
170
171
		return $post_types;
172
	}
173
174
	/**
175
	 * Allows custom meta fields to sync.
176
	 *
177
	 * @param array $post_meta - previously changet post meta.
178
	 *
179
	 * @return array
180
	 */
181
	public function allow_sync_post_meta( $post_meta ) {
182
		$meta_keys = array_map(
183
			array( $this, 'return_meta' ),
184
			$this->get_plan_property_mapping()
185
		);
186
		return array_merge( $post_meta, array_values( $meta_keys ) );
187
	}
188
189
	/**
190
	 * This returns meta attribute of passet array.
191
	 * Used for array functions.
192
	 *
193
	 * @param array $map - stuff.
194
	 *
195
	 * @return mixed
196
	 */
197
	public function return_meta( $map ) {
198
		return $map['meta'];
199
	}
200
	/**
201
	 * Callback that parses the membership purchase shortcode.
202
	 *
203
	 * @param array $attrs - attributes in the shortcode. `id` here is the CPT id of the plan.
204
	 *
205
	 * @return string|void
206
	 */
207
	public function render_button( $attrs ) {
208
		Jetpack_Gutenberg::load_assets_as_required( self::$button_block_name, array( 'thickbox', 'wp-polyfill' ) );
209
210
		if ( empty( $attrs['planId'] ) ) {
211
			return;
212
		}
213
		$id      = intval( $attrs['planId'] );
214
		$product = get_post( $id );
215
		if ( ! $product || is_wp_error( $product ) ) {
216
			return;
217
		}
218
		if ( $product->post_type !== self::$post_type_plan || 'publish' !== $product->post_status ) {
219
			return;
220
		}
221
222
		$data = array(
223
			'blog_id'      => self::get_blog_id(),
224
			'id'           => $id,
225
			'button_label' => __( 'Your contribution', 'jetpack' ),
226
			'powered_text' => __( 'Powered by WordPress.com', 'jetpack' ),
227
		);
228
229
		$classes = Jetpack_Gutenberg::block_classes(
230
			self::$button_block_name,
231
			$attrs,
232
			array(
233
				'wp-block-button__link',
234
				'components-button',
235
				'is-primary',
236
				'is-button',
237
				self::$css_classname_prefix . '-' . $data['id'],
238
			)
239
		);
240
241
		if ( isset( $attrs['submitButtonText'] ) ) {
242
			$data['button_label'] = $attrs['submitButtonText'];
243
		}
244
		$button_styles = array();
245 View Code Duplication
		if ( ! empty( $attrs['customBackgroundButtonColor'] ) ) {
246
			array_push(
247
				$button_styles,
248
				sprintf(
249
					'background-color: %s',
250
					sanitize_hex_color( $attrs['customBackgroundButtonColor'] )
251
				)
252
			);
253
		}
254 View Code Duplication
		if ( ! empty( $attrs['customTextButtonColor'] ) ) {
255
			array_push(
256
				$button_styles,
257
				sprintf(
258
					'color: %s',
259
					sanitize_hex_color( $attrs['customTextButtonColor'] )
260
				)
261
			);
262
		}
263
		$button_styles = implode( ';', $button_styles );
264
		add_thickbox();
265
		return sprintf(
266
			'<button data-blog-id="%d" data-powered-text="%s" data-plan-id="%d" data-lang="%s" class="%s" style="%s">%s</button>',
267
			esc_attr( $data['blog_id'] ),
268
			esc_attr( $data['powered_text'] ),
269
			esc_attr( $data['id'] ),
270
			esc_attr( get_locale() ),
271
			esc_attr( $classes ),
272
			esc_attr( $button_styles ),
273
			wp_kses( $data['button_label'], self::$tags_allowed_in_the_button )
274
		);
275
	}
276
277
	/**
278
	 * Get current blog id.
279
	 *
280
	 * @return int
281
	 */
282
	public static function get_blog_id() {
283
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
284
			return get_current_blog_id();
285
		}
286
287
		return Jetpack_Options::get_option( 'id' );
288
	}
289
290
	/**
291
	 * Get the id of the connected payment acount (Stripe etc).
292
	 *
293
	 * @return int|void
294
	 */
295
	public static function get_connected_account_id() {
296
		return get_option( self::$connected_account_id_option_name );
297
	}
298
299
	/**
300
	 * Whether Recurring Payments are enabled.
301
	 *
302
	 * @return bool
303
	 */
304
	public static function is_enabled_jetpack_recurring_payments() {
305
		// For WPCOM sites.
306 View Code Duplication
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM && function_exists( 'has_any_blog_stickers' ) ) {
307
			$site_id = get_current_blog_id();
308
			return has_any_blog_stickers( array( 'personal-plan', 'premium-plan', 'business-plan', 'ecommerce-plan' ), $site_id );
309
		}
310
311
		// For Jetpack sites.
312
		return Jetpack::is_active() && (
313
			/** This filter is documented in class.jetpack-gutenberg.php */
314
			! apply_filters( 'jetpack_block_editor_enable_upgrade_nudge', false ) || // Remove when the default becomes `true`.
315
			Jetpack_Plan::supports( 'recurring-payments' )
316
		);
317
	}
318
319
	/**
320
	 * Register the Recurring Payments Gutenberg block
321
	 */
322
	public function register_gutenberg_block() {
323
		// This gate was introduced to prevent duplicate registration. A race condition exists where
324
		// the registration that happens via extensions/blocks/recurring-payments/recurring-payments.php
325
		// was adding the registration action after the action had been run in some contexts.
326
		if ( self::$has_registered_block ) {
327
			return;
328
		}
329
330
		if ( self::is_enabled_jetpack_recurring_payments() ) {
331
			jetpack_register_block(
332
				'jetpack/recurring-payments',
333
				array(
334
					'render_callback' => array( $this, 'render_button' ),
335
				)
336
			);
337
		} else {
338
			Jetpack_Gutenberg::set_extension_unavailable(
339
				'jetpack/recurring-payments',
340
				'missing_plan',
341
				array(
342
					'required_feature' => 'memberships',
343
					'required_plan'    => self::$required_plan,
344
				)
345
			);
346
		}
347
348
		self::$has_registered_block = true;
349
	}
350
}
351
Jetpack_Memberships::get_instance();
352