Completed
Push — test/travis-parallel-testing ( 1c8199...2a2329 )
by
unknown
295:13 queued 279:27
created

is_enabled_jetpack_simple_payments()   B

Complexity

Conditions 7
Paths 5

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
nc 5
nop 0
dl 0
loc 21
rs 8.6506
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';
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $post_type_order.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
10
	static $post_type_product = 'jp_pay_product';
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $post_type_product.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
11
12
	static $shortcode = 'simple-payment';
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $shortcode.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
13
14
	static $css_classname_prefix = 'jetpack-simple-payments';
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $css_classname_prefix.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
15
16
	// Increase this number each time there's a change in CSS or JS to bust cache.
17
	static $version = '0.25';
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $version.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

To learn more about the PSR-2, please see the PHP-FIG site on the PSR-2.

Loading history...
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
		if ( ! $this->is_enabled_jetpack_simple_payments() ) {
51
			add_shortcode( self::$shortcode, array( $this, 'ignore_shortcode' ) );
52
			return;
53
		}
54
55
		add_filter( 'rest_api_allowed_post_types', array( $this, 'allow_rest_api_types' ) );
56
		add_filter( 'jetpack_sync_post_meta_whitelist', array( $this, 'allow_sync_post_meta' ) );
57
		$this->register_scripts_and_styles();
58
		$this->register_shortcode();
59
		$this->setup_cpts();
60
61
		add_filter( 'the_content', array( $this, 'remove_auto_paragraph_from_product_description' ), 0 );
62
	}
63
64
	function remove_auto_paragraph_from_product_description( $content ) {
65
		if ( get_post_type() === self::$post_type_product ) {
66
			remove_filter( 'the_content', 'wpautop' );
67
		}
68
69
		return $content;
70
	}
71
72
	function get_blog_id() {
73
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
74
			return get_current_blog_id();
75
		}
76
77
		return Jetpack_Options::get_option( 'id' );
78
	}
79
80
	/**
81
	 * Used to check whether Simple Payments are enabled for given site.
82
	 *
83
	 * @return bool True if Simple Payments are enabled, false otherwise.
84
	 */
85
	function is_enabled_jetpack_simple_payments() {
86
		/**
87
		 * Can be used by plugin authors to disable the conflicting output of Simple Payments.
88
		 *
89
		 * @since 6.3.0
90
		 *
91
		 * @param bool True if Simple Payments should be disabled, false otherwise.
92
		 */
93
		if ( apply_filters( 'jetpack_disable_simple_payments', false ) ) {
94
			return false;
95
		}
96
97
		// For WPCOM sites
98
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM && function_exists( 'has_blog_sticker' ) ) {
99
			$site_id = $this->get_blog_id();
100
			return has_blog_sticker( 'premium-plan', $site_id ) || has_blog_sticker( 'business-plan', $site_id );
101
		}
102
103
		// For all Jetpack sites
104
		return Jetpack::is_active() && Jetpack::active_plan_supports( 'simple-payments');
105
	}
106
107
	function parse_shortcode( $attrs, $content = false ) {
108
		if ( empty( $attrs['id'] ) ) {
109
			return;
110
		}
111
		$product = get_post( $attrs['id'] );
112
		if ( ! $product || is_wp_error( $product ) ) {
113
			return;
114
		}
115
		if ( $product->post_type !== self::$post_type_product || 'trash' === $product->post_status ) {
116
			return;
117
		}
118
119
		// We allow for overriding the presentation labels
120
		$data = shortcode_atts( array(
121
			'blog_id'     => $this->get_blog_id(),
122
			'dom_id'      => uniqid( self::$css_classname_prefix . '-' . $product->ID . '_', true ),
123
			'class'       => self::$css_classname_prefix . '-' . $product->ID,
124
			'title'       => get_the_title( $product ),
125
			'description' => $product->post_content,
126
			'cta'         => get_post_meta( $product->ID, 'spay_cta', true ),
127
			'multiple'    => get_post_meta( $product->ID, 'spay_multiple', true ) || '0'
128
		), $attrs );
129
130
		$data['price'] = $this->format_price(
131
			get_post_meta( $product->ID, 'spay_formatted_price', true ),
132
			get_post_meta( $product->ID, 'spay_price', true ),
133
			get_post_meta( $product->ID, 'spay_currency', true ),
134
			$data
135
		);
136
137
		$data['id'] = $attrs['id'];
138
139
		if( ! wp_style_is( 'jetpack-simple-payments', 'enqueue' ) ) {
140
			wp_enqueue_style( 'jetpack-simple-payments' );
141
		}
142
143
		if ( ! wp_script_is( 'paypal-express-checkout', 'enqueued' ) ) {
144
			wp_enqueue_script( 'paypal-express-checkout' );
145
		}
146
147
		wp_add_inline_script( 'paypal-express-checkout', sprintf(
148
			"try{PaypalExpressCheckout.renderButton( '%d', '%d', '%s', '%d' );}catch(e){}",
149
			esc_js( $data['blog_id'] ),
150
			esc_js( $attrs['id'] ),
151
			esc_js( $data['dom_id'] ),
152
			esc_js( $data['multiple'] )
153
		) );
154
155
		return $this->output_shortcode( $data );
156
	}
157
158
	function ignore_shortcode() { return; }
159
160
	function output_shortcode( $data ) {
161
		$items = '';
162
		$css_prefix = self::$css_classname_prefix;
163
164
		if ( $data['multiple'] ) {
165
			$items="<div class='${css_prefix}-items'>
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned correctly; expected 1 space but found 0 spaces

This check looks for improperly formatted assignments.

Every assignment must have exactly one space before and one space after the equals operator.

To illustrate:

$a = "a";
$ab = "ab";
$abc = "abc";

will have no issues, while

$a   = "a";
$ab  = "ab";
$abc = "abc";

will report issues in lines 1 and 2.

Loading history...
166
				<input class='${css_prefix}-items-number' type='number' value='1' min='1' id='{$data['dom_id']}_number' />
167
			</div>";
168
		}
169
		$image = "";
170
		if( has_post_thumbnail( $data['id'] ) ) {
171
			$image = "<div class='${css_prefix}-product-image'><div class='${css_prefix}-image'>" . get_the_post_thumbnail( $data['id'], 'full' ) . "</div></div>";
172
		}
173
		return "
174
<div class='{$data['class']} ${css_prefix}-wrapper'>
175
	<div class='${css_prefix}-product'>
176
		{$image}
177
		<div class='${css_prefix}-details'>
178
			<div class='${css_prefix}-title'><p>{$data['title']}</p></div>
179
			<div class='${css_prefix}-description'><p>{$data['description']}</p></div>
180
			<div class='${css_prefix}-price'><p>{$data['price']}</p></div>
181
			<div class='${css_prefix}-purchase-message' id='{$data['dom_id']}-message-container'></div>
182
			<div class='${css_prefix}-purchase-box'>
183
				{$items}
184
				<div class='${css_prefix}-button' id='{$data['dom_id']}_button'></div>
185
			</div>
186
		</div>
187
	</div>
188
</div>
189
		";
190
	}
191
192
	function format_price( $formatted_price, $price, $currency, $all_data ) {
193
		if ( $formatted_price ) {
194
			return $formatted_price;
195
		}
196
		return "$price $currency";
197
	}
198
199
	/**
200
	 * Allows custom post types to be used by REST API.
201
	 * @param $post_types
202
	 * @see hook 'rest_api_allowed_post_types'
203
	 * @return array
204
	 */
205
	function allow_rest_api_types( $post_types ) {
206
		$post_types[] = self::$post_type_order;
207
		$post_types[] = self::$post_type_product;
208
		return $post_types;
209
	}
210
211
	function allow_sync_post_meta( $post_meta ) {
212
		return array_merge( $post_meta, array(
213
			'spay_paypal_id',
214
			'spay_status',
215
			'spay_product_id',
216
			'spay_quantity',
217
			'spay_price',
218
			'spay_customer_email',
219
			'spay_currency',
220
			'spay_cta',
221
			'spay_email',
222
			'spay_multiple',
223
			'spay_formatted_price',
224
		) );
225
	}
226
227
	/**
228
	 * Sets up the custom post types for the module.
229
	 */
230
	function setup_cpts() {
231
232
		/*
233
		 * ORDER data structure. holds:
234
		 * title = customer_name | 4xproduct_name
235
		 * excerpt = customer_name + customer contact info + customer notes from paypal form
236
		 * metadata:
237
		 * spay_paypal_id - paypal id of transaction
238
		 * spay_status
239
		 * spay_product_id - post_id of bought product
240
		 * spay_quantity - quantity of product
241
		 * spay_price - item price at the time of purchase
242
		 * spay_customer_email - customer email
243
		 * ... (WIP)
244
		 */
245
		$order_capabilities = array(
246
			'edit_post'             => 'edit_posts',
247
			'read_post'             => 'read_private_posts',
248
			'delete_post'           => 'delete_posts',
249
			'edit_posts'            => 'edit_posts',
250
			'edit_others_posts'     => 'edit_others_posts',
251
			'publish_posts'         => 'publish_posts',
252
			'read_private_posts'    => 'read_private_posts',
253
		);
254
		$order_args = array(
255
			'label'                 => esc_html_x( 'Order', 'noun: a quantity of goods or items purchased or sold', 'jetpack' ),
256
			'description'           => esc_html__( 'Simple Payments orders', 'jetpack' ),
257
			'supports'              => array( 'custom-fields', 'excerpt' ),
258
			'hierarchical'          => false,
259
			'public'                => false,
260
			'show_ui'               => false,
261
			'show_in_menu'          => false,
262
			'show_in_admin_bar'     => false,
263
			'show_in_nav_menus'     => false,
264
			'can_export'            => true,
265
			'has_archive'           => false,
266
			'exclude_from_search'   => true,
267
			'publicly_queryable'    => false,
268
			'rewrite'               => false,
269
			'capabilities'          => $order_capabilities,
270
			'show_in_rest'          => true,
271
		);
272
		register_post_type( self::$post_type_order, $order_args );
273
274
		/*
275
		 * PRODUCT data structure. Holds:
276
		 * title - title
277
		 * content - description
278
		 * thumbnail - image
279
		 * metadata:
280
		 * spay_price - price
281
		 * spay_formatted_price
282
		 * spay_currency - currency code
283
		 * spay_cta - text with "Buy" or other CTA
284
		 * spay_email - paypal email
285
		 * spay_multiple - allow for multiple items
286
		 * spay_status - status. { enabled | disabled }
287
		 */
288
		$product_capabilities = array(
289
			'edit_post'             => 'edit_posts',
290
			'read_post'             => 'read_private_posts',
291
			'delete_post'           => 'delete_posts',
292
			'edit_posts'            => 'edit_posts',
293
			'edit_others_posts'     => 'edit_others_posts',
294
			'publish_posts'         => 'publish_posts',
295
			'read_private_posts'    => 'read_private_posts',
296
		);
297
		$product_args = array(
298
			'label'                 => esc_html__( 'Product', 'jetpack' ),
299
			'description'           => esc_html__( 'Simple Payments products', 'jetpack' ),
300
			'supports'              => array( 'title', 'editor','thumbnail', 'custom-fields', 'author' ),
301
			'hierarchical'          => false,
302
			'public'                => false,
303
			'show_ui'               => false,
304
			'show_in_menu'          => false,
305
			'show_in_admin_bar'     => false,
306
			'show_in_nav_menus'     => false,
307
			'can_export'            => true,
308
			'has_archive'           => false,
309
			'exclude_from_search'   => true,
310
			'publicly_queryable'    => false,
311
			'rewrite'               => false,
312
			'capabilities'          => $product_capabilities,
313
			'show_in_rest'          => true,
314
		);
315
		register_post_type( self::$post_type_product, $product_args );
316
	}
317
318
}
319
Jetpack_Simple_Payments::getInstance();
320