Completed
Push — master-stable ( a82972...9baba8 )
by
unknown
27:19 queued 17:47
created

Jetpack_Simple_Payments::output_shortcode()   B

Complexity

Conditions 3
Paths 4

Size

Total Lines 31
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 21
nc 4
nop 1
dl 0
loc 31
rs 8.8571
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() {
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
	}
39
	private function register_init_hook() {
40
		add_action( 'init', array( $this, 'init_hook_action' ) );
41
	}
42
	private function register_shortcode() {
43
		add_shortcode( self::$shortcode, array( $this, 'parse_shortcode' ) );
44
	}
45
46
	public function init_hook_action() {
47
		add_filter( 'rest_api_allowed_post_types', array( $this, 'allow_rest_api_types' ) );
48
		add_filter( 'jetpack_sync_post_meta_whitelist', array( $this, 'allow_sync_post_meta' ) );
49
		$this->register_scripts();
50
		$this->register_shortcode();
51
		$this->setup_cpts();
52
53
		add_filter( 'the_content', array( $this, 'remove_auto_paragraph_from_product_description' ), 0 );
54
	}
55
56
	function remove_auto_paragraph_from_product_description( $content ) {
57
		if ( get_post_type() === self::$post_type_product ) {
58
			remove_filter( 'the_content', 'wpautop' );
59
		}
60
61
		return $content;
62
	}
63
64
	function get_blog_id() {
65
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
66
			return get_current_blog_id();
67
		}
68
69
		return Jetpack_Options::get_option( 'id' );
70
	}
71
72
	function parse_shortcode( $attrs, $content = false ) {
73
		if ( empty( $attrs['id'] ) ) {
74
			return;
75
		}
76
		$product = get_post( $attrs['id'] );
77
		if ( ! $product || is_wp_error( $product ) ) {
78
			return;
79
		}
80
		if ( $product->post_type !== self::$post_type_product || 'trash' === $product->post_status ) {
81
			return;
82
		}
83
84
		// We allow for overriding the presentation labels
85
		$data = shortcode_atts( array(
86
			'blog_id'     => $this->get_blog_id(),
87
			'dom_id'      => uniqid( self::$css_classname_prefix . '-' . $product->ID . '_', true ),
88
			'class'       => self::$css_classname_prefix . '-' . $product->ID,
89
			'title'       => get_the_title( $product ),
90
			'description' => $product->post_content,
91
			'cta'         => get_post_meta( $product->ID, 'spay_cta', true ),
92
			'multiple'    => get_post_meta( $product->ID, 'spay_multiple', true ) || '0'
93
		), $attrs );
94
95
		$data['price'] = $this->format_price(
96
			get_post_meta( $product->ID, 'spay_formatted_price', true ),
97
			get_post_meta( $product->ID, 'spay_price', true ),
98
			get_post_meta( $product->ID, 'spay_currency', true ),
99
			$data
100
		);
101
102
		$data['id'] = $attrs['id'];
103
		if ( ! wp_script_is( 'paypal-express-checkout', 'enqueued' ) ) {
104
			wp_enqueue_script( 'paypal-express-checkout' );
105
		}
106
		if ( ! wp_style_is( 'simple-payments', 'enqueued' ) ) {
107
			wp_enqueue_style( 'simple-payments', plugins_url( 'simple-payments.css', __FILE__ ), array( 'dashicons' ) );
108
		}
109
110
		wp_add_inline_script( 'paypal-express-checkout', sprintf(
111
			"try{PaypalExpressCheckout.renderButton( '%d', '%d', '%s', '%d' );}catch(e){}",
112
			esc_js( $data['blog_id'] ),
113
			esc_js( $attrs['id'] ),
114
			esc_js( $data['dom_id'] ),
115
			esc_js( $data['multiple'] )
116
		) );
117
118
		return $this->output_shortcode( $data );
119
	}
120
121
	function output_shortcode( $data ) {
122
		$items = '';
123
		$css_prefix = self::$css_classname_prefix;
124
125
		if ( $data['multiple'] ) {
126
			$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...
127
				<input class='${css_prefix}-items-number' type='number' value='1' min='1' id='{$data['dom_id']}_number' />
128
			</div>";
129
		}
130
		$image = "";
131
		if( has_post_thumbnail( $data['id'] ) ) {
132
			$image = "<div class='${css_prefix}-product-image'><div class='${css_prefix}-image'>" . get_the_post_thumbnail( $data['id'], 'full' ) . "</div></div>";
133
		}
134
		return "
135
<div class='{$data['class']} ${css_prefix}-wrapper'>
136
	<div class='${css_prefix}-product'>
137
		{$image}
138
		<div class='${css_prefix}-details'>
139
			<div class='${css_prefix}-title'><p>{$data['title']}</p></div>
140
			<div class='${css_prefix}-description'><p>{$data['description']}</p></div>
141
			<div class='${css_prefix}-price'><p>{$data['price']}</p></div>
142
			<div class='${css_prefix}-purchase-message' id='{$data['dom_id']}-message-container'></div>
143
			<div class='${css_prefix}-purchase-box'>
144
				{$items}
145
				<div class='${css_prefix}-button' id='{$data['dom_id']}_button'></div>
146
			</div>
147
		</div>
148
	</div>
149
</div>
150
		";
151
	}
152
153
	function format_price( $formatted_price, $price, $currency, $all_data ) {
154
		if ( $formatted_price ) {
155
			return $formatted_price;
156
		}
157
		return "$price $currency";
158
	}
159
160
	/**
161
	 * Allows custom post types to be used by REST API.
162
	 * @param $post_types
163
	 * @see hook 'rest_api_allowed_post_types'
164
	 * @return array
165
	 */
166
	function allow_rest_api_types( $post_types ) {
167
		$post_types[] = self::$post_type_order;
168
		$post_types[] = self::$post_type_product;
169
		return $post_types;
170
	}
171
172
	function allow_sync_post_meta( $post_meta ) {
173
		return array_merge( $post_meta, array(
174
			'spay_paypal_id',
175
			'spay_status',
176
			'spay_product_id',
177
			'spay_quantity',
178
			'spay_price',
179
			'spay_customer_email',
180
			'spay_currency',
181
			'spay_cta',
182
			'spay_email',
183
			'spay_multiple',
184
			'spay_formatted_price',
185
		) );
186
	}
187
188
	/**
189
	 * Sets up the custom post types for the module.
190
	 */
191
	function setup_cpts() {
192
193
		/*
194
		 * ORDER data structure. holds:
195
		 * title = customer_name | 4xproduct_name
196
		 * excerpt = customer_name + customer contact info + customer notes from paypal form
197
		 * metadata:
198
		 * spay_paypal_id - paypal id of transaction
199
		 * spay_status
200
		 * spay_product_id - post_id of bought product
201
		 * spay_quantity - quantity of product
202
		 * spay_price - item price at the time of purchase
203
		 * spay_customer_email - customer email
204
		 * ... (WIP)
205
		 */
206
		$order_capabilities = array(
207
			'edit_post'             => 'edit_posts',
208
			'read_post'             => 'read_private_posts',
209
			'delete_post'           => 'delete_posts',
210
			'edit_posts'            => 'edit_posts',
211
			'edit_others_posts'     => 'edit_others_posts',
212
			'publish_posts'         => 'publish_posts',
213
			'read_private_posts'    => 'read_private_posts',
214
		);
215
		$order_args = array(
216
			'label'                 => esc_html__( 'Order', 'jetpack' ),
217
			'description'           => esc_html__( 'Simple Payments orders', 'jetpack' ),
218
			'supports'              => array( 'custom-fields', 'excerpt' ),
219
			'hierarchical'          => false,
220
			'public'                => false,
221
			'show_ui'               => false,
222
			'show_in_menu'          => false,
223
			'show_in_admin_bar'     => false,
224
			'show_in_nav_menus'     => false,
225
			'can_export'            => true,
226
			'has_archive'           => false,
227
			'exclude_from_search'   => true,
228
			'publicly_queryable'    => false,
229
			'rewrite'               => false,
230
			'capabilities'          => $order_capabilities,
231
			'show_in_rest'          => true,
232
		);
233
		register_post_type( self::$post_type_order, $order_args );
234
235
		/*
236
		 * PRODUCT data structure. Holds:
237
		 * title - title
238
		 * content - description
239
		 * thumbnail - image
240
		 * metadata:
241
		 * spay_price - price
242
		 * spay_formatted_price
243
		 * spay_currency - currency code
244
		 * spay_cta - text with "Buy" or other CTA
245
		 * spay_email - paypal email
246
		 * spay_multiple - allow for multiple items
247
		 * spay_status - status. { enabled | disabled }
248
		 */
249
		$product_capabilities = array(
250
			'edit_post'             => 'edit_posts',
251
			'read_post'             => 'read_private_posts',
252
			'delete_post'           => 'delete_posts',
253
			'edit_posts'            => 'edit_posts',
254
			'edit_others_posts'     => 'edit_others_posts',
255
			'publish_posts'         => 'publish_posts',
256
			'read_private_posts'    => 'read_private_posts',
257
		);
258
		$product_args = array(
259
			'label'                 => esc_html__( 'Product', 'jetpack' ),
260
			'description'           => esc_html__( 'Simple Payments products', 'jetpack' ),
261
			'supports'              => array( 'title', 'editor','thumbnail', 'custom-fields', 'author' ),
262
			'hierarchical'          => false,
263
			'public'                => false,
264
			'show_ui'               => false,
265
			'show_in_menu'          => false,
266
			'show_in_admin_bar'     => false,
267
			'show_in_nav_menus'     => false,
268
			'can_export'            => true,
269
			'has_archive'           => false,
270
			'exclude_from_search'   => true,
271
			'publicly_queryable'    => false,
272
			'rewrite'               => false,
273
			'capabilities'          => $product_capabilities,
274
			'show_in_rest'          => true,
275
		);
276
		register_post_type( self::$post_type_product, $product_args );
277
	}
278
279
}
280
Jetpack_Simple_Payments::getInstance();
281