Completed
Push — feature/assets-cdn ( 13f9d8...5f1be1 )
by George
103:49 queued 72:28
created

Jetpack_Simple_Payments::output_shortcode()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 31

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
nc 4
nop 1
dl 0
loc 31
rs 9.424
c 0
b 0
f 0
1
<?php
2
/*
3
 * Simple Payments lets users embed a PayPal button fully integrated with wpcom to sell products on the site.
4
 * This is not a proper module yet, because not all the pieces are in place. Until everything is shipped, it can be turned
5
 * into module that can be enabled/disabled.
6
*/
7
class Jetpack_Simple_Payments {
8
	// These have to be under 20 chars because that is CPT limit.
9
	static $post_type_order = 'jp_pay_order';
10
	static $post_type_product = 'jp_pay_product';
11
12
	static $shortcode = 'simple-payment';
13
14
	static $css_classname_prefix = 'jetpack-simple-payments';
15
16
	// Increase this number each time there's a change in CSS or JS to bust cache.
17
	static $version = '0.25';
18
19
	// Classic singleton pattern:
20
	private static $instance;
21
	private function __construct() {}
22
	static function getInstance() {
23
		if ( ! self::$instance ) {
24
			self::$instance = new self();
25
			self::$instance->register_init_hook();
26
		}
27
		return self::$instance;
28
	}
29
30
	private function register_scripts_and_styles() {
31
		/**
32
		 * Paypal heavily discourages putting that script in your own server:
33
		 * @see https://developer.paypal.com/docs/integration/direct/express-checkout/integration-jsv4/add-paypal-button/
34
		 */
35
		wp_register_script( 'paypal-checkout-js', 'https://www.paypalobjects.com/api/checkout.js', array(), null, true );
36
		wp_register_script( 'paypal-express-checkout', plugins_url( '/paypal-express-checkout.js', __FILE__ ),
37
			array( 'jquery', 'paypal-checkout-js' ), self::$version );
38
		wp_register_style( 'jetpack-simple-payments', plugins_url( '/simple-payments.css', __FILE__ ), array( 'dashicons' ) );
39
	}
40
41
	private function register_init_hook() {
42
		add_action( 'init', array( $this, 'init_hook_action' ) );
43
	}
44
45
	private function register_shortcode() {
46
		add_shortcode( self::$shortcode, array( $this, 'parse_shortcode' ) );
47
	}
48
49
	public function init_hook_action() {
50
		add_filter( 'rest_api_allowed_post_types', array( $this, 'allow_rest_api_types' ) );
51
		add_filter( 'jetpack_sync_post_meta_whitelist', array( $this, 'allow_sync_post_meta' ) );
52
		$this->register_scripts_and_styles();
53
		$this->register_shortcode();
54
		$this->setup_cpts();
55
56
		add_filter( 'the_content', array( $this, 'remove_auto_paragraph_from_product_description' ), 0 );
57
	}
58
59
	function remove_auto_paragraph_from_product_description( $content ) {
60
		if ( get_post_type() === self::$post_type_product ) {
61
			remove_filter( 'the_content', 'wpautop' );
62
		}
63
64
		return $content;
65
	}
66
67
	function get_blog_id() {
68
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
69
			return get_current_blog_id();
70
		}
71
72
		return Jetpack_Options::get_option( 'id' );
73
	}
74
75
	/**
76
	 * Used to check whether Simple Payments are enabled for given site.
77
	 *
78
	 * @return bool True if Simple Payments are enabled, false otherwise.
79
	 */
80
	function is_enabled_jetpack_simple_payments() {
81
		/**
82
		 * Can be used by plugin authors to disable the conflicting output of Simple Payments.
83
		 *
84
		 * @since 6.3.0
85
		 *
86
		 * @param bool True if Simple Payments should be disabled, false otherwise.
87
		 */
88
		if ( apply_filters( 'jetpack_disable_simple_payments', false ) ) {
89
			return false;
90
		}
91
92
		// For WPCOM sites
93
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM && function_exists( 'has_blog_sticker' ) ) {
94
			$site_id = $this->get_blog_id();
95
			return has_blog_sticker( 'premium-plan', $site_id ) || has_blog_sticker( 'business-plan', $site_id );
96
		}
97
98
		// For all Jetpack sites
99
		return Jetpack::is_active() && Jetpack::active_plan_supports( 'simple-payments');
100
	}
101
102
	function parse_shortcode( $attrs, $content = false ) {
103
		if ( empty( $attrs['id'] ) ) {
104
			return;
105
		}
106
		$product = get_post( $attrs['id'] );
107
		if ( ! $product || is_wp_error( $product ) ) {
108
			return;
109
		}
110
		if ( $product->post_type !== self::$post_type_product || 'trash' === $product->post_status ) {
111
			return;
112
		}
113
114
		// We allow for overriding the presentation labels
115
		$data = shortcode_atts( array(
116
			'blog_id'     => $this->get_blog_id(),
117
			'dom_id'      => uniqid( self::$css_classname_prefix . '-' . $product->ID . '_', true ),
118
			'class'       => self::$css_classname_prefix . '-' . $product->ID,
119
			'title'       => get_the_title( $product ),
120
			'description' => $product->post_content,
121
			'cta'         => get_post_meta( $product->ID, 'spay_cta', true ),
122
			'multiple'    => get_post_meta( $product->ID, 'spay_multiple', true ) || '0'
123
		), $attrs );
124
125
		$data['price'] = $this->format_price(
126
			get_post_meta( $product->ID, 'spay_formatted_price', true ),
127
			get_post_meta( $product->ID, 'spay_price', true ),
128
			get_post_meta( $product->ID, 'spay_currency', true ),
129
			$data
130
		);
131
132
		$data['id'] = $attrs['id'];
133
134
		if( ! wp_style_is( 'jetpack-simple-payments', 'enqueue' ) ) {
135
			wp_enqueue_style( 'jetpack-simple-payments' );
136
		}
137
138
		if ( ! $this->is_enabled_jetpack_simple_payments() ) {
139
			return $this->output_admin_warning( $data );
140
		}
141
142
		if ( ! wp_script_is( 'paypal-express-checkout', 'enqueued' ) ) {
143
			wp_enqueue_script( 'paypal-express-checkout' );
144
		}
145
146
		wp_add_inline_script( 'paypal-express-checkout', sprintf(
147
			"try{PaypalExpressCheckout.renderButton( '%d', '%d', '%s', '%d' );}catch(e){}",
148
			esc_js( $data['blog_id'] ),
149
			esc_js( $attrs['id'] ),
150
			esc_js( $data['dom_id'] ),
151
			esc_js( $data['multiple'] )
152
		) );
153
154
		return $this->output_shortcode( $data );
155
	}
156
157
	function output_admin_warning( $data ) {
158
		if ( ! current_user_can( 'manage_options' ) ) {
159
			return;
160
		}
161
		$css_prefix = self::$css_classname_prefix;
162
163
		$support_url = ( defined( 'IS_WPCOM' ) && IS_WPCOM )
164
			? 'https://support.wordpress.com/simple-payments/'
165
			: 'https://jetpack.com/support/simple-payment-button/';
166
167
		$warning = sprintf(
168
			wp_kses(
169
				__( 'Your plan doesn\'t include Simple Payments. <a href="%s" rel="noopener noreferrer" target="_blank">Learn more and upgrade</a>.', 'jetpack' ),
170
				array( 'a' => array( 'href' => array(), 'rel' => array(), 'target' => array() ) )
171
			),
172
			esc_url( $support_url )
173
		);
174
175
		return "
176
<div class='{$data['class']} ${css_prefix}-wrapper'>
177
	<div class='${css_prefix}-product'>
178
		<div class='${css_prefix}-details'>
179
			<div class='${css_prefix}-purchase-message show error' id='{$data['dom_id']}-message-container'>
180
				<p>${warning}</p>
181
				<p>" . esc_html__( '(Only administrators will see this message.)', 'jetpack' ) . "</p>
182
			</div>
183
		</div>
184
	</div>
185
</div>
186
		";
187
	}
188
189
	function output_shortcode( $data ) {
190
		$items = '';
191
		$css_prefix = self::$css_classname_prefix;
192
193
		if ( $data['multiple'] ) {
194
			$items="<div class='${css_prefix}-items'>
195
				<input class='${css_prefix}-items-number' type='number' value='1' min='1' id='{$data['dom_id']}_number' />
196
			</div>";
197
		}
198
		$image = "";
199
		if( has_post_thumbnail( $data['id'] ) ) {
200
			$image = "<div class='${css_prefix}-product-image'><div class='${css_prefix}-image'>" . get_the_post_thumbnail( $data['id'], 'full' ) . "</div></div>";
201
		}
202
		return "
203
<div class='{$data['class']} ${css_prefix}-wrapper'>
204
	<div class='${css_prefix}-product'>
205
		{$image}
206
		<div class='${css_prefix}-details'>
207
			<div class='${css_prefix}-title'><p>{$data['title']}</p></div>
208
			<div class='${css_prefix}-description'><p>{$data['description']}</p></div>
209
			<div class='${css_prefix}-price'><p>{$data['price']}</p></div>
210
			<div class='${css_prefix}-purchase-message' id='{$data['dom_id']}-message-container'></div>
211
			<div class='${css_prefix}-purchase-box'>
212
				{$items}
213
				<div class='${css_prefix}-button' id='{$data['dom_id']}_button'></div>
214
			</div>
215
		</div>
216
	</div>
217
</div>
218
		";
219
	}
220
221
	function format_price( $formatted_price, $price, $currency, $all_data ) {
222
		if ( $formatted_price ) {
223
			return $formatted_price;
224
		}
225
		return "$price $currency";
226
	}
227
228
	/**
229
	 * Allows custom post types to be used by REST API.
230
	 * @param $post_types
231
	 * @see hook 'rest_api_allowed_post_types'
232
	 * @return array
233
	 */
234
	function allow_rest_api_types( $post_types ) {
235
		$post_types[] = self::$post_type_order;
236
		$post_types[] = self::$post_type_product;
237
		return $post_types;
238
	}
239
240
	function allow_sync_post_meta( $post_meta ) {
241
		return array_merge( $post_meta, array(
242
			'spay_paypal_id',
243
			'spay_status',
244
			'spay_product_id',
245
			'spay_quantity',
246
			'spay_price',
247
			'spay_customer_email',
248
			'spay_currency',
249
			'spay_cta',
250
			'spay_email',
251
			'spay_multiple',
252
			'spay_formatted_price',
253
		) );
254
	}
255
256
	/**
257
	 * Sets up the custom post types for the module.
258
	 */
259
	function setup_cpts() {
260
261
		/*
262
		 * ORDER data structure. holds:
263
		 * title = customer_name | 4xproduct_name
264
		 * excerpt = customer_name + customer contact info + customer notes from paypal form
265
		 * metadata:
266
		 * spay_paypal_id - paypal id of transaction
267
		 * spay_status
268
		 * spay_product_id - post_id of bought product
269
		 * spay_quantity - quantity of product
270
		 * spay_price - item price at the time of purchase
271
		 * spay_customer_email - customer email
272
		 * ... (WIP)
273
		 */
274
		$order_capabilities = array(
275
			'edit_post'             => 'edit_posts',
276
			'read_post'             => 'read_private_posts',
277
			'delete_post'           => 'delete_posts',
278
			'edit_posts'            => 'edit_posts',
279
			'edit_others_posts'     => 'edit_others_posts',
280
			'publish_posts'         => 'publish_posts',
281
			'read_private_posts'    => 'read_private_posts',
282
		);
283
		$order_args = array(
284
			'label'                 => esc_html_x( 'Order', 'noun: a quantity of goods or items purchased or sold', 'jetpack' ),
285
			'description'           => esc_html__( 'Simple Payments orders', 'jetpack' ),
286
			'supports'              => array( 'custom-fields', 'excerpt' ),
287
			'hierarchical'          => false,
288
			'public'                => false,
289
			'show_ui'               => false,
290
			'show_in_menu'          => false,
291
			'show_in_admin_bar'     => false,
292
			'show_in_nav_menus'     => false,
293
			'can_export'            => true,
294
			'has_archive'           => false,
295
			'exclude_from_search'   => true,
296
			'publicly_queryable'    => false,
297
			'rewrite'               => false,
298
			'capabilities'          => $order_capabilities,
299
			'show_in_rest'          => true,
300
		);
301
		register_post_type( self::$post_type_order, $order_args );
302
303
		/*
304
		 * PRODUCT data structure. Holds:
305
		 * title - title
306
		 * content - description
307
		 * thumbnail - image
308
		 * metadata:
309
		 * spay_price - price
310
		 * spay_formatted_price
311
		 * spay_currency - currency code
312
		 * spay_cta - text with "Buy" or other CTA
313
		 * spay_email - paypal email
314
		 * spay_multiple - allow for multiple items
315
		 * spay_status - status. { enabled | disabled }
316
		 */
317
		$product_capabilities = array(
318
			'edit_post'             => 'edit_posts',
319
			'read_post'             => 'read_private_posts',
320
			'delete_post'           => 'delete_posts',
321
			'edit_posts'            => 'edit_posts',
322
			'edit_others_posts'     => 'edit_others_posts',
323
			'publish_posts'         => 'publish_posts',
324
			'read_private_posts'    => 'read_private_posts',
325
		);
326
		$product_args = array(
327
			'label'                 => esc_html__( 'Product', 'jetpack' ),
328
			'description'           => esc_html__( 'Simple Payments products', 'jetpack' ),
329
			'supports'              => array( 'title', 'editor','thumbnail', 'custom-fields', 'author' ),
330
			'hierarchical'          => false,
331
			'public'                => false,
332
			'show_ui'               => false,
333
			'show_in_menu'          => false,
334
			'show_in_admin_bar'     => false,
335
			'show_in_nav_menus'     => false,
336
			'can_export'            => true,
337
			'has_archive'           => false,
338
			'exclude_from_search'   => true,
339
			'publicly_queryable'    => false,
340
			'rewrite'               => false,
341
			'capabilities'          => $product_capabilities,
342
			'show_in_rest'          => true,
343
		);
344
		register_post_type( self::$post_type_product, $product_args );
345
	}
346
347
}
348
Jetpack_Simple_Payments::getInstance();
349