Failed Conditions
Pull Request — master (#1)
by
unknown
08:13
created

src/Extension.php (3 issues)

1
<?php
2
/**
3
 * Extension
4
 *
5
 * @author    Pronamic <[email protected]>
6
 * @copyright 2005-2020 Pronamic
7
 * @license   GPL-3.0-or-later
8
 * @package   Pronamic\WordPress\Pay\Extensions\MemberPress
9
 */
10
11
namespace Pronamic\WordPress\Pay\Extensions\MemberPress;
12
13
use MeprDb;
14
use MeprOptions;
15
use MeprProduct;
16
use MeprSubscription;
17
use MeprTransaction;
18
use MeprUtils;
19
use Pronamic\WordPress\Pay\AbstractPluginIntegration;
20
use Pronamic\WordPress\Pay\Payments\PaymentStatus;
21
use Pronamic\WordPress\Pay\Extensions\MemberPress\Gateways\Gateway;
22
use Pronamic\WordPress\Pay\Payments\Payment;
23
use Pronamic\WordPress\Pay\Subscriptions\Subscription;
24
use Pronamic\WordPress\Pay\Subscriptions\SubscriptionStatus;
25
26
/**
27
 * WordPress pay MemberPress extension
28
 *
29
 * @author  Remco Tolsma
30
 * @version 2.0.4
31
 * @since   1.0.0
32
 */
33
class Extension extends AbstractPluginIntegration {
34
	/**
35
	 * The slug of this addon
36
	 *
37
	 * @var string
38
	 */
39
	const SLUG = 'memberpress';
40
41
	/**
42
	 * Construct MemberPress plugin integration.
43
	 */
44
	public function __construct() {
45
		parent::__construct(
46
			array(
47
				'name' => __( 'MemberPress', 'pronamic_ideal' ),
48
			)
49
		);
50
51
		// Dependencies.
52
		$dependencies = $this->get_dependencies();
53
54
		$dependencies->add( new MemberPressDependency() );
55
	}
56
57
	/**
58
	 * Setup.
59
	 */
60
	public function setup() {
61
		\add_filter( 'pronamic_subscription_source_description_' . self::SLUG, array( $this, 'subscription_source_description' ), 10, 2 );
62
		\add_filter( 'pronamic_payment_source_description_' . self::SLUG, array( $this, 'source_description' ), 10, 2 );
63
64
		// Check if dependencies are met and integration is active.
65
		if ( ! $this->is_active() ) {
66
			return;
67
		}
68
69
		// @link https://gitlab.com/pronamic/memberpress/blob/1.2.4/app/lib/MeprGatewayFactory.php#L48-50
70
		\add_filter( 'mepr-gateway-paths', array( $this, 'gateway_paths' ) );
71
72
		\add_filter( 'pronamic_payment_redirect_url_' . self::SLUG, array( $this, 'redirect_url' ), 10, 2 );
73
		\add_action( 'pronamic_payment_status_update_' . self::SLUG, array( $this, 'status_update' ), 10, 1 );
74
75
		\add_filter( 'pronamic_subscription_source_text_' . self::SLUG, array( $this, 'subscription_source_text' ), 10, 2 );
76
		\add_filter( 'pronamic_subscription_source_url_' . self::SLUG, array( $this, 'subscription_source_url' ), 10, 2 );
77
		\add_filter( 'pronamic_payment_source_text_' . self::SLUG, array( $this, 'source_text' ), 10, 2 );
78
		\add_filter( 'pronamic_payment_source_url_' . self::SLUG, array( $this, 'source_url' ), 10, 2 );
79
80
		\add_action( 'mepr_subscription_pre_delete', array( $this, 'subscription_pre_delete' ), 10, 1 );
81
82
		\add_action( 'mepr_subscription_transition_status', array( $this, 'memberpress_subscription_transition_status' ), 10, 3 );
83
84
		// Hide MemberPress columns for payments and subscriptions.
85
		\add_filter( 'registered_post_type', array( $this, 'post_type_columns_hide' ), 15, 1 );
86
87
		if ( \is_admin() ) {
88
			$this->admin_subscriptions = new Admin\AdminSubscriptions();
0 ignored issues
show
Bug Best Practice introduced by
The property admin_subscriptions does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
89
			$this->admin_transactions  = new Admin\AdminTransactions();
0 ignored issues
show
Bug Best Practice introduced by
The property admin_transactions does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
90
91
			$this->admin_subscriptions->setup();
92
			$this->admin_transactions->setup();
93
		}
94
	}
95
96
	/**
97
	 * Gateway paths.
98
	 *
99
	 * @link https://gitlab.com/pronamic/memberpress/blob/1.2.4/app/lib/MeprGatewayFactory.php#L48-50
100
	 *
101
	 * @param array $paths Array with gateway paths.
102
	 * @return array
103
	 */
104
	public function gateway_paths( $paths ) {
105
		$paths[] = dirname( __FILE__ ) . '/../gateways/';
106
107
		return $paths;
108
	}
109
110
	/**
111
	 * Hide MemberPress columns for payments and subscriptions.
112
	 *
113
	 * @link https://gitlab.com/pronamic/memberpress/blob/1.2.4/app/controllers/MeprAppCtrl.php#L129-146
114
	 *
115
	 * @param string $post_type Registered post type.
116
	 *
117
	 * @return void
118
	 */
119
	public function post_type_columns_hide( $post_type ) {
120
		if ( ! in_array( $post_type, array( 'pronamic_payment', 'pronamic_pay_subscr' ), true ) ) {
121
			return;
122
		}
123
124
		remove_filter( 'manage_edit-' . $post_type . '_columns', 'MeprAppCtrl::columns' );
125
	}
126
127
	/**
128
	 * Payment redirect URL filter.
129
	 *
130
	 * @since 1.0.1
131
	 *
132
	 * @param string  $url     Payment redirect URL.
133
	 * @param Payment $payment Payment to redirect for.
134
	 *
135
	 * @return string
136
	 */
137
	public function redirect_url( $url, Payment $payment ) {
138
		global $transaction;
139
140
		$transaction_id = $payment->get_source_id();
141
142
		$transaction = new MeprTransaction( $transaction_id );
143
144
		switch ( $payment->get_status() ) {
145
			case PaymentStatus::CANCELLED:
146
			case PaymentStatus::EXPIRED:
147
			case PaymentStatus::FAILURE:
148
				$product = $transaction->product();
149
150
				$url = add_query_arg(
151
					array(
152
						'action'   => 'payment_form',
153
						'txn'      => $transaction->trans_num,
154
						'errors'   => array(
155
							__( 'Payment failed. Please try again.', 'pronamic_ideal' ),
156
						),
157
						'_wpnonce' => wp_create_nonce( 'mepr_payment_form' ),
158
					),
159
					$product->url()
160
				);
161
162
				break;
163
			case PaymentStatus::SUCCESS:
164
				// @link https://gitlab.com/pronamic/memberpress/blob/1.2.4/app/models/MeprOptions.php#L768-782
165
				$mepr_options = MeprOptions::fetch();
166
167
				$product         = new MeprProduct( $transaction->product_id );
168
				$sanitized_title = sanitize_title( $product->post_title );
169
170
				$args = array(
171
					'membership_id' => $product->ID,
172
					'membership'    => $sanitized_title,
173
					'trans_num'     => $transaction->trans_num,
174
				);
175
176
				$url = $mepr_options->thankyou_page_url( http_build_query( $args ) );
177
178
				break;
179
			case PaymentStatus::OPEN:
180
			default:
181
				break;
182
		}
183
184
		return $url;
185
	}
186
187
	/**
188
	 * Update lead status of the specified payment.
189
	 *
190
	 * @link https://github.com/Charitable/Charitable/blob/1.1.4/includes/gateways/class-charitable-gateway-paypal.php#L229-L357
191
	 *
192
	 * @param Payment $payment The payment whose status is updated.
193
	 */
194
	public function status_update( Payment $payment ) {
195
		$transaction = new MeprTransaction( $payment->get_source_id() );
196
197
		if ( $payment->get_recurring() ) {
198
			$subscription_id = $payment->get_subscription()->get_source_id();
199
			$subscription    = new MeprSubscription( $subscription_id );
200
201
			// Same source ID and first transaction ID for recurring payment means we need to add a new transaction.
202
			if ( $payment->get_source_id() === $subscription->id ) {
203
				// First transaction.
204
				$first_txn = $subscription->first_txn();
205
206
				if ( false === $first_txn || ! ( $first_txn instanceof MeprTransaction ) ) {
207
					$first_txn             = new MeprTransaction();
208
					$first_txn->user_id    = $subscription->user_id;
209
					$first_txn->product_id = $subscription->product_id;
210
					$first_txn->coupon_id  = $subscription->coupon_id;
211
					$first_txn->gateway    = null;
212
				}
213
214
				// Transaction number.
215
				$trans_num = $payment->get_transaction_id();
216
217
				if ( empty( $trans_num ) ) {
218
					$trans_num = uniqid();
219
				}
220
221
				// New transaction.
222
				$transaction                  = new MeprTransaction();
223
				$transaction->created_at      = $payment->post->post_date_gmt;
224
				$transaction->user_id         = $first_txn->user_id;
225
				$transaction->product_id      = $first_txn->product_id;
226
				$transaction->coupon_id       = $first_txn->coupon_id;
227
				$transaction->gateway         = $first_txn->gateway;
228
				$transaction->trans_num       = $trans_num;
229
				$transaction->txn_type        = MeprTransaction::$payment_str;
230
				$transaction->status          = MeprTransaction::$pending_str;
231
				$transaction->expires_at      = MeprUtils::ts_to_mysql_date( $payment->get_end_date()->getTimestamp(), 'Y-m-d 23:59:59' );
0 ignored issues
show
Bug Best Practice introduced by
The property expires_at does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
232
				$transaction->subscription_id = $subscription->id;
233
234
				$transaction->set_gross( $payment->get_total_amount()->get_value() );
235
236
				$transaction->store();
237
238
				// Set source ID.
239
				$payment->set_meta( 'source_id', $transaction->id );
240
241
				$payment->source_id = $transaction->id;
242
243
				if ( MeprSubscription::$active_str === $subscription->status ) {
244
					/*
245
					 * We create a 'confirmed' 'subscription_confirmation'
246
					 * transaction for a grace period of 15 days.
247
					 *
248
					 * Transactions of type "subscription_confirmation" with a
249
					 * status of "confirmed" are hidden in the UI, and are used
250
					 * as a way to provide free trial periods and the 24 hour
251
					 * grace period on a recurring subscription signup.
252
					 *
253
					 * @link https://docs.memberpress.com/article/219-where-is-data-stored.
254
					 */
255
					$subscription_confirmation                  = new MeprTransaction();
256
					$subscription_confirmation->created_at      = $payment->post->post_date_gmt;
257
					$subscription_confirmation->user_id         = $first_txn->user_id;
258
					$subscription_confirmation->product_id      = $first_txn->product_id;
259
					$subscription_confirmation->coupon_id       = $first_txn->coupon_id;
260
					$subscription_confirmation->gateway         = $first_txn->gateway;
261
					$subscription_confirmation->trans_num       = $trans_num;
262
					$subscription_confirmation->txn_type        = MeprTransaction::$subscription_confirmation_str;
263
					$subscription_confirmation->status          = MeprTransaction::$confirmed_str;
264
					$subscription_confirmation->subscription_id = $subscription->id;
265
					$subscription_confirmation->expires_at      = MeprUtils::ts_to_mysql_date( strtotime( $payment->post->post_date_gmt ) + MeprUtils::days( 15 ), 'Y-m-d 23:59:59' );
266
267
					$subscription_confirmation->set_subtotal( 0.00 );
268
269
					$subscription_confirmation->store();
270
				}
271
			}
272
		}
273
274
		$should_update = ! MemberPress::transaction_has_status(
275
			$transaction,
276
			array(
277
				MeprTransaction::$complete_str,
278
			)
279
		);
280
281
		// Allow successful recurring payments to update failed transaction.
282
		if ( $payment->get_recurring() && PaymentStatus::SUCCESS === $payment->get_status() && MeprTransaction::$failed_str === $transaction->status ) {
283
			$should_update = true;
284
		}
285
286
		if ( $should_update ) {
287
			$gateway = new Gateway();
288
289
			$gateway->pronamic_payment = $payment;
290
			$gateway->mp_txn           = $transaction;
291
292
			switch ( $payment->get_status() ) {
293
				case PaymentStatus::CANCELLED:
294
				case PaymentStatus::EXPIRED:
295
				case PaymentStatus::FAILURE:
296
					$gateway->record_payment_failure();
297
298
					break;
299
				case PaymentStatus::SUCCESS:
300
					if ( $payment->get_recurring() ) {
301
						$gateway->record_subscription_payment();
302
					} else {
303
						$gateway->record_payment();
304
					}
305
306
					break;
307
				case PaymentStatus::OPEN:
308
				default:
309
					break;
310
			}
311
		}
312
	}
313
314
	/**
315
	 * Subscription deleted.
316
	 *
317
	 * @param int $subscription_id MemberPress subscription id.
318
	 */
319
	public function subscription_pre_delete( $subscription_id ) {
320
		$subscription = get_pronamic_subscription_by_meta( '_pronamic_subscription_source_id', $subscription_id );
321
322
		if ( ! $subscription ) {
323
			return;
324
		}
325
326
		// Add note.
327
		$note = sprintf(
328
			/* translators: %s: MemberPress */
329
			__( '%s subscription deleted.', 'pronamic_ideal' ),
330
			__( 'MemberPress', 'pronamic_ideal' )
331
		);
332
333
		$subscription->add_note( $note );
334
335
		// The status of canceled or completed subscriptions will not be changed automatically.
336
		if ( ! in_array( $subscription->get_status(), array( SubscriptionStatus::CANCELLED, SubscriptionStatus::COMPLETED ), true ) ) {
337
			$subscription->set_status( SubscriptionStatus::CANCELLED );
338
339
			$subscription->save();
340
		}
341
	}
342
343
	/**
344
	 * Source text.
345
	 *
346
	 * @param string  $text    Source text.
347
	 * @param Payment $payment Payment to create the source text for.
348
	 *
349
	 * @return string
350
	 */
351
	public function source_text( $text, Payment $payment ) {
352
		$text = __( 'MemberPress', 'pronamic_ideal' ) . '<br />';
353
354
		$text .= sprintf(
355
			'<a href="%s">%s</a>',
356
			add_query_arg(
357
				array(
358
					'page'   => 'memberpress-trans',
359
					'action' => 'edit',
360
					'id'     => $payment->source_id,
361
				),
362
				admin_url( 'admin.php' )
363
			),
364
			/* translators: %s: payment source id */
365
			sprintf( __( 'Transaction %s', 'pronamic_ideal' ), $payment->source_id )
366
		);
367
368
		return $text;
369
	}
370
371
	/**
372
	 * Subscription source text.
373
	 *
374
	 * @param string       $text         Source text.
375
	 * @param Subscription $subscription Subscription to create the source text for.
376
	 *
377
	 * @return string
378
	 */
379
	public function subscription_source_text( $text, Subscription $subscription ) {
380
		$text = __( 'MemberPress', 'pronamic_ideal' ) . '<br />';
381
382
		$text .= sprintf(
383
			'<a href="%s">%s</a>',
384
			add_query_arg(
385
				array(
386
					'page'         => 'memberpress-subscriptions',
387
					'subscription' => $subscription->source_id,
388
				),
389
				admin_url( 'admin.php' )
390
			),
391
			/* translators: %s: payment source id */
392
			sprintf( __( 'Subscription %s', 'pronamic_ideal' ), $subscription->source_id )
393
		);
394
395
		return $text;
396
	}
397
398
	/**
399
	 * Source description.
400
	 *
401
	 * @param string  $description Description.
402
	 * @param Payment $payment     Payment to create the description for.
403
	 *
404
	 * @return string
405
	 */
406
	public function source_description( $description, Payment $payment ) {
407
		return __( 'MemberPress Transaction', 'pronamic_ideal' );
408
	}
409
410
	/**
411
	 * Subscription source description.
412
	 *
413
	 * @param string       $description  Description.
414
	 * @param Subscription $subscription Subscription to create the description for.
415
	 *
416
	 * @return string
417
	 */
418
	public function subscription_source_description( $description, Subscription $subscription ) {
419
		return __( 'MemberPress Subscription', 'pronamic_ideal' );
420
	}
421
422
	/**
423
	 * Source URL.
424
	 *
425
	 * @param string  $url     URL.
426
	 * @param Payment $payment The payment to create the source URL for.
427
	 *
428
	 * @return string
429
	 */
430
	public function source_url( $url, Payment $payment ) {
431
		$url = add_query_arg(
432
			array(
433
				'page'   => 'memberpress-trans',
434
				'action' => 'edit',
435
				'id'     => $payment->source_id,
436
			),
437
			admin_url( 'admin.php' )
438
		);
439
440
		return $url;
441
	}
442
443
	/**
444
	 * Subscription source URL.
445
	 *
446
	 * @param string       $url          URL.
447
	 * @param Subscription $subscription Subscription.
448
	 *
449
	 * @return string
450
	 */
451
	public function subscription_source_url( $url, Subscription $subscription ) {
452
		$url = add_query_arg(
453
			array(
454
				'page'         => 'memberpress-subscriptions',
455
				'subscription' => $subscription->source_id,
456
			),
457
			admin_url( 'admin.php' )
458
		);
459
460
		return $url;
461
	}
462
463
	/**
464
	 * MemberPress update subscription.
465
	 *
466
	 * @link https://github.com/wp-premium/memberpress-basic/blob/1.3.18/app/controllers/MeprSubscriptionsCtrl.php#L92-L111
467
	 * @link https://github.com/wp-premium/memberpress-basic/blob/1.3.18/app/models/MeprSubscription.php#L100-L123
468
	 * @link https://github.com/wp-premium/memberpress-basic/blob/1.3.18/app/models/MeprSubscription.php#L112
469
	 *
470
	 * @param string           $status_old               Old status identifier.
471
	 * @param string           $status_new               New status identifier.
472
	 * @param MeprSubscription $memberpress_subscription MemberPress subscription object.
473
	 */
474
	public function memberpress_subscription_transition_status( $status_old, $status_new, $memberpress_subscription ) {
475
		$subscription = get_pronamic_subscription_by_meta( '_pronamic_subscription_source_id', $memberpress_subscription->id );
476
477
		if ( empty( $subscription ) ) {
478
			return;
479
		}
480
481
		$status = SubscriptionStatuses::transform( $status_new );
482
483
		$subscription->set_status( $status );
484
485
		$subscription->save();
486
	}
487
}
488