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