Failed Conditions
Push — develop ( 12386e...3e9729 )
by Remco
06:20
created

src/Extension.php (4 issues)

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