Failed Conditions
Push — develop ( 3e1564...0432f0 )
by Reüel
05:46
created

Extension::subscription_pre_delete()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 21
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
cc 3
eloc 10
nc 3
nop 1
dl 0
loc 21
ccs 0
cts 13
cp 0
crap 12
rs 9.9332
c 0
b 0
f 0
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::$failed_str,
278
				MeprTransaction::$complete_str,
279
			)
280
		);
281
282
		// Allow successful recurring payments to update failed transaction.
283
		if ( $payment->get_recurring() && PaymentStatus::SUCCESS === $payment->get_status() && MeprTransaction::$failed_str === $transaction->status ) {
284
			$should_update = true;
285
		}
286
287
		if ( $should_update ) {
288
			$gateway = new Gateway();
289
290
			$gateway->pronamic_payment = $payment;
291
			$gateway->mp_txn           = $transaction;
292
293
			switch ( $payment->get_status() ) {
294
				case PaymentStatus::CANCELLED:
295
				case PaymentStatus::EXPIRED:
296
				case PaymentStatus::FAILURE:
297
					$gateway->record_payment_failure();
298
299
					// Cancel subscription if first payment is cancelled/expired/failed,
300
					// to prevent subsequent successful subscriptions from reactivating subscription.
301
					if ( ! $payment->get_recurring() ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $payment->get_recurring() of type boolean|null is loosely compared to false; this is ambiguous if the boolean can be false. You might want to explicitly use !== null instead.

If an expression can have both false, and null as possible values. It is generally a good practice to always use strict comparison to clearly distinguish between those two values.

$a = canBeFalseAndNull();

// Instead of
if ( ! $a) { }

// Better use one of the explicit versions:
if ($a !== null) { }
if ($a !== false) { }
if ($a !== null && $a !== false) { }
Loading history...
302
						$subscription = $payment->get_subscription();
303
304
						if ( null !== $subscription ) {
305
							$subscription->set_status( SubscriptionStatus::CANCELLED );
306
						}
307
					}
308
309
					break;
310
				case PaymentStatus::SUCCESS:
311
					if ( $payment->get_recurring() ) {
312
						$gateway->record_subscription_payment();
313
					} else {
314
						$gateway->record_payment();
315
					}
316
317
					break;
318
				case PaymentStatus::OPEN:
319
				default:
320
					break;
321
			}
322
		}
323
	}
324
325
	/**
326
	 * Subscription deleted.
327
	 *
328
	 * @param int $subscription_id MemberPress subscription id.
329
	 */
330
	public function subscription_pre_delete( $subscription_id ) {
331
		$subscription = get_pronamic_subscription_by_meta( '_pronamic_subscription_source_id', $subscription_id );
332
333
		if ( ! $subscription ) {
334
			return;
335
		}
336
337
		// Add note.
338
		$note = sprintf(
339
			/* translators: %s: MemberPress */
340
			__( '%s subscription deleted.', 'pronamic_ideal' ),
341
			__( 'MemberPress', 'pronamic_ideal' )
342
		);
343
344
		$subscription->add_note( $note );
345
346
		// The status of canceled or completed subscriptions will not be changed automatically.
347
		if ( ! in_array( $subscription->get_status(), array( SubscriptionStatus::CANCELLED, SubscriptionStatus::COMPLETED ), true ) ) {
348
			$subscription->set_status( SubscriptionStatus::CANCELLED );
349
350
			$subscription->save();
351
		}
352
	}
353
354
	/**
355
	 * Source text.
356
	 *
357
	 * @param string  $text    Source text.
358
	 * @param Payment $payment Payment to create the source text for.
359
	 *
360
	 * @return string
361
	 */
362
	public function source_text( $text, Payment $payment ) {
363
		$text = __( 'MemberPress', 'pronamic_ideal' ) . '<br />';
364
365
		$text .= sprintf(
366
			'<a href="%s">%s</a>',
367
			add_query_arg(
368
				array(
369
					'page'   => 'memberpress-trans',
370
					'action' => 'edit',
371
					'id'     => $payment->source_id,
372
				),
373
				admin_url( 'admin.php' )
374
			),
375
			/* translators: %s: payment source id */
376
			sprintf( __( 'Transaction %s', 'pronamic_ideal' ), $payment->source_id )
377
		);
378
379
		return $text;
380
	}
381
382
	/**
383
	 * Subscription source text.
384
	 *
385
	 * @param string       $text         Source text.
386
	 * @param Subscription $subscription Subscription to create the source text for.
387
	 *
388
	 * @return string
389
	 */
390
	public function subscription_source_text( $text, Subscription $subscription ) {
391
		$text = __( 'MemberPress', 'pronamic_ideal' ) . '<br />';
392
393
		$text .= sprintf(
394
			'<a href="%s">%s</a>',
395
			add_query_arg(
396
				array(
397
					'page'         => 'memberpress-subscriptions',
398
					'subscription' => $subscription->source_id,
399
				),
400
				admin_url( 'admin.php' )
401
			),
402
			/* translators: %s: payment source id */
403
			sprintf( __( 'Subscription %s', 'pronamic_ideal' ), $subscription->source_id )
404
		);
405
406
		return $text;
407
	}
408
409
	/**
410
	 * Source description.
411
	 *
412
	 * @param string  $description Description.
413
	 * @param Payment $payment     Payment to create the description for.
414
	 *
415
	 * @return string
416
	 */
417
	public function source_description( $description, Payment $payment ) {
418
		return __( 'MemberPress Transaction', 'pronamic_ideal' );
419
	}
420
421
	/**
422
	 * Subscription source description.
423
	 *
424
	 * @param string       $description  Description.
425
	 * @param Subscription $subscription Subscription to create the description for.
426
	 *
427
	 * @return string
428
	 */
429
	public function subscription_source_description( $description, Subscription $subscription ) {
430
		return __( 'MemberPress Subscription', 'pronamic_ideal' );
431
	}
432
433
	/**
434
	 * Source URL.
435
	 *
436
	 * @param string  $url     URL.
437
	 * @param Payment $payment The payment to create the source URL for.
438
	 *
439
	 * @return string
440
	 */
441
	public function source_url( $url, Payment $payment ) {
442
		$url = add_query_arg(
443
			array(
444
				'page'   => 'memberpress-trans',
445
				'action' => 'edit',
446
				'id'     => $payment->source_id,
447
			),
448
			admin_url( 'admin.php' )
449
		);
450
451
		return $url;
452
	}
453
454
	/**
455
	 * Subscription source URL.
456
	 *
457
	 * @param string       $url          URL.
458
	 * @param Subscription $subscription Subscription.
459
	 *
460
	 * @return string
461
	 */
462
	public function subscription_source_url( $url, Subscription $subscription ) {
463
		$url = add_query_arg(
464
			array(
465
				'page'         => 'memberpress-subscriptions',
466
				'subscription' => $subscription->source_id,
467
			),
468
			admin_url( 'admin.php' )
469
		);
470
471
		return $url;
472
	}
473
474
	/**
475
	 * MemberPress update subscription.
476
	 *
477
	 * @link https://github.com/wp-premium/memberpress-basic/blob/1.3.18/app/controllers/MeprSubscriptionsCtrl.php#L92-L111
478
	 * @link https://github.com/wp-premium/memberpress-basic/blob/1.3.18/app/models/MeprSubscription.php#L100-L123
479
	 * @link https://github.com/wp-premium/memberpress-basic/blob/1.3.18/app/models/MeprSubscription.php#L112
480
	 *
481
	 * @param string           $status_old               Old status identifier.
482
	 * @param string           $status_new               New status identifier.
483
	 * @param MeprSubscription $memberpress_subscription MemberPress subscription object.
484
	 */
485
	public function memberpress_subscription_transition_status( $status_old, $status_new, $memberpress_subscription ) {
486
		$subscription = get_pronamic_subscription_by_meta( '_pronamic_subscription_source_id', $memberpress_subscription->id );
487
488
		if ( empty( $subscription ) ) {
489
			return;
490
		}
491
492
		$status = SubscriptionStatuses::transform( $status_new );
493
494
		$subscription->set_status( $status );
495
496
		$subscription->save();
497
	}
498
}
499