-
-
Notifications
You must be signed in to change notification settings - Fork 75
Expand file tree
/
Copy pathclass-membership-manager.php
More file actions
648 lines (513 loc) · 16.6 KB
/
class-membership-manager.php
File metadata and controls
648 lines (513 loc) · 16.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
<?php
/**
* Membership Manager
*
* Handles processes related to memberships.
*
* @package WP_Ultimo
* @subpackage Managers/Membership_Manager
* @since 2.0.0
*/
namespace WP_Ultimo\Managers;
use Psr\Log\LogLevel;
use WP_Ultimo\Database\Memberships\Membership_Status;
// Exit if accessed directly
defined('ABSPATH') || exit;
/**
* Handles processes related to memberships.
*
* @since 2.0.0
*/
class Membership_Manager extends Base_Manager {
use \WP_Ultimo\Apis\Rest_Api;
use \WP_Ultimo\Apis\WP_CLI;
use \WP_Ultimo\Apis\MCP_Abilities;
use \WP_Ultimo\Apis\Command_Palette;
use \WP_Ultimo\Traits\Singleton;
const LOG_FILE_NAME = 'memberships';
/**
* The manager slug.
*
* @since 2.0.0
* @var string
*/
protected $slug = 'membership';
/**
* The model class associated to this manager.
*
* @since 2.0.0
* @var string
*/
protected $model_class = \WP_Ultimo\Models\Membership::class;
/**
* Instantiate the necessary hooks.
*
* @since 2.0.0
* @return void
*/
public function init(): void {
$this->enable_rest_api();
$this->enable_wp_cli();
$this->enable_mcp_abilities();
$this->enable_command_palette();
add_action(
'init',
function () {
Event_Manager::register_model_events('membership', __('Membership', 'ultimate-multisite'), ['created', 'updated']);
}
);
add_action('wu_async_transfer_membership', [$this, 'async_transfer_membership'], 10, 2);
add_action('wu_async_delete_membership', [$this, 'async_delete_membership'], 10);
/*
* Transitions
*/
add_action('wu_transition_membership_status', [$this, 'mark_cancelled_date'], 10, 3);
add_action('wu_transition_membership_status', [$this, 'transition_membership_status'], 10, 3);
add_action('wu_transition_membership_status', [$this, 'handle_pending_site_on_cancellation'], 10, 3);
/*
* Deal with delayed/schedule swaps
*/
add_action('wu_async_membership_swap', [$this, 'async_membership_swap'], 10);
/*
* Deal with pending sites creation
*/
add_action('wp_ajax_wu_publish_pending_site', [$this, 'publish_pending_site']);
add_action('wp_ajax_wu_check_pending_site_created', [$this, 'check_pending_site_created']);
add_action('wu_async_publish_pending_site', [$this, 'async_publish_pending_site'], 10);
/*
* Reclaim orphaned pending_site when a WooCommerce order completes.
*/
add_action('woocommerce_order_status_completed', [$this, 'reclaim_pending_site_on_wc_order_completion']);
}
/**
* Processes a delayed site publish action.
*
* @since 2.0.11
*/
public function publish_pending_site(): void {
check_ajax_referer('wu_publish_pending_site');
ignore_user_abort(true);
// Send JSON response to client.
// Don't use wp_send_json because it will exit prematurely.
header('Content-Type: application/json; charset=' . get_option('blog_charset'));
echo wp_json_encode(['status' => 'creating-site']);
// Don't make the request block till we finish, if possible.
if (function_exists('fastcgi_finish_request')) {
fastcgi_finish_request();
// Response is sent, but the php process continues to run and update the site.
}
// Note: When fastcgi_finish_request is unavailable, the client will wait
// for the operation to complete but still receives the JSON response.
$membership_id = wu_request('membership_id');
$this->async_publish_pending_site($membership_id);
exit; // Just exit the request
}
/**
* Processes a delayed site publish action.
*
* @since 2.0.0
*
* @param int $membership_id The membership id.
* @return void
*/
public function async_publish_pending_site($membership_id) {
/*
* Allow unlimited execution time for site initialization.
*
* Complex site templates (Elementor kits, Freemius SDK, Rank Math,
* large database tables) can exceed PHP's default time limit,
* killing the process and leaving the Action Scheduler action
* stuck in-progress status.
*
* @since 2.4.13
*/
if (function_exists('set_time_limit')) {
set_time_limit(0);
}
$membership = wu_get_membership($membership_id);
if ( ! $membership) {
wu_log_add(self::LOG_FILE_NAME, __('An unexpected error happened.', 'ultimate-multisite'), LogLevel::ERROR);
return;
}
$status = $membership->publish_pending_site();
if (is_wp_error($status)) {
wu_log_add('site-errors', $status, LogLevel::ERROR);
}
}
/**
* Processes a delayed site publish action.
*
* Checks whether the pending site has been created. If is_publishing
* has been true for longer than 5 minutes, we assume the creation
* process was killed (PHP timeout, OOM, server restart) and reset
* the flag so the Action Scheduler retry can pick it up.
*
* @since 2.0.11
*/
public function check_pending_site_created() {
$membership_id = wu_request('membership_hash');
$membership = wu_get_membership_by_hash($membership_id);
if ( ! $membership) {
return new \WP_Error('error', __('An unexpected error happened.', 'ultimate-multisite'));
}
$pending_site = $membership->get_pending_site();
if ( ! $pending_site) {
/**
* We do not have a pending site, so we can assume the site was created.
*/
wp_send_json(['publish_status' => 'completed']);
exit;
}
/*
* Detect stale publishing state. When the PHP process that was
* creating the site gets killed mid-execution, is_publishing
* stays true forever — the AS retry sees the flag and bails
* out, creating an infinite loop. Reset the flag after 5 min
* so the next AS run or cron kick can retry site creation.
*
* @since 2.5.3
*/
if ($pending_site->is_publishing_stale()) {
$pending_site->set_publishing(false);
$membership->update_pending_site($pending_site);
wu_log_add(
self::LOG_FILE_NAME,
sprintf(
// translators: %d: membership ID.
__('Reset stale is_publishing flag for membership %d. The site creation process appears to have been killed before completing.', 'ultimate-multisite'),
$membership->get_id()
)
);
/*
* Return 'stopped' so the frontend polling loop retries.
* Do NOT also enqueue wu_async_publish_pending_site here —
* that would create two competing retry sources (Action
* Scheduler + frontend) and risk double site creation.
* The existing AS scheduled action will pick up the reset
* flag on its next run.
*/
wp_send_json(['publish_status' => 'stopped']);
exit;
}
wp_send_json(['publish_status' => $pending_site->is_publishing() ? 'running' : 'stopped']);
exit;
}
/**
* Processes a membership swap.
*
* @since 2.0.0
*
* @param int $membership_id The membership id.
* @return void
*/
public function async_membership_swap($membership_id) {
global $wpdb;
$membership = wu_get_membership($membership_id);
if ( ! $membership) {
wu_log_add(self::LOG_FILE_NAME, __('An unexpected error happened.', 'ultimate-multisite'), LogLevel::ERROR);
return;
}
$scheduled_swap = $membership->get_scheduled_swap();
if (empty($scheduled_swap)) {
wu_log_add(self::LOG_FILE_NAME, __('An unexpected error happened.', 'ultimate-multisite'), LogLevel::ERROR);
return;
}
$order = $scheduled_swap->order;
$wpdb->query('START TRANSACTION'); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
try {
$membership->swap($order);
$status = $membership->save();
if (is_wp_error($status)) {
$wpdb->query('ROLLBACK'); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
wu_log_add(self::LOG_FILE_NAME, $status->get_error_message(), LogLevel::ERROR);
return;
}
} catch (\Throwable $exception) {
$wpdb->query('ROLLBACK'); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
wu_log_add(self::LOG_FILE_NAME, $exception->getMessage(), LogLevel::ERROR);
return;
}
/*
* Clean up the membership swap order.
*/
$membership->delete_scheduled_swap();
$wpdb->query('COMMIT'); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
}
/**
* Watches the change in payment status to take action when needed.
*
* @todo Publishing sites should be done in async.
*
* @since 2.0.0
*
* @param string $old_status The old status of the membership.
* @param string $new_status The new status of the membership.
* @param integer $membership_id Payment ID.
* @return void
*/
public function transition_membership_status($old_status, $new_status, $membership_id): void {
$allowed_previous_status = [
Membership_Status::PENDING,
Membership_Status::ON_HOLD,
];
if ( ! in_array($old_status, $allowed_previous_status, true)) {
return;
}
$allowed_status = [
Membership_Status::ACTIVE,
Membership_Status::TRIALING,
];
if ( ! in_array($new_status, $allowed_status, true)) {
return;
}
/*
* Create pending sites.
*/
$membership = wu_get_membership($membership_id);
/*
* If the customer has not yet verified their email, hold off on
* publishing the pending site. The site will be published later
* when the customer completes email verification (handled in
* Customer_Manager::handle_email_verification()).
*/
$customer = $membership->get_customer();
if ($customer && $customer->get_email_verification() === 'pending') {
return;
}
$membership->publish_pending_site_async();
}
/**
* Mark the membership date of cancellation.
*
* @since 2.0.0
*
* @param string $old_value Old status value.
* @param string $new_value New status value.
* @param int $item_id The membership id.
* @return void
*/
public function mark_cancelled_date($old_value, $new_value, $item_id): void {
if ('cancelled' === $new_value && $new_value !== $old_value) {
$membership = wu_get_membership($item_id);
$membership->set_date_cancellation(wu_get_current_time('mysql', true));
$membership->save();
}
}
/**
* Preserve pending_site data in a transient when a membership is cancelled.
*
* When a membership transitions to `cancelled`, any orphaned pending_site
* stored in membership meta is moved to a 24-hour transient keyed by the
* customer's email hash. This allows a retry checkout flow to reclaim the
* pending site rather than losing it permanently.
*
* Transient key format: `wu_transferable_pending_` . md5( $email )
*
* @since 2.3.2
*
* @param string $old_status The previous membership status.
* @param string $new_status The new membership status.
* @param int $membership_id The ID of the membership.
* @return void
*/
public function handle_pending_site_on_cancellation($old_status, $new_status, $membership_id): void {
if ('cancelled' !== $new_status) {
return;
}
$membership = wu_get_membership($membership_id);
if ( ! $membership) {
return;
}
$pending_site = $membership->get_pending_site();
if ( ! $pending_site) {
return;
}
$customer = $membership->get_customer();
if ( ! $customer) {
$membership->delete_pending_site();
return;
}
$email = $customer->get_email_address();
$transient_key = 'wu_transferable_pending_' . md5($email);
set_transient($transient_key, $pending_site, DAY_IN_SECONDS);
$membership->delete_pending_site();
}
/**
* Reclaim an orphaned pending_site when a WooCommerce order completes.
*
* When a membership is cancelled, `handle_pending_site_on_cancellation`
* stores the pending_site in a 24-hour transient keyed by the customer's
* billing email hash. If the customer then completes a new WooCommerce
* order, this method reclaims the pending_site, reactivates their
* cancelled membership, triggers async site provisioning, and links the
* WC order to the membership via `_wu_membership_id` post meta.
*
* Transient key format: `wu_transferable_pending_` . md5( $email )
*
* @since 2.3.2
*
* @param int $order_id The WooCommerce order ID.
* @return void
*/
public function reclaim_pending_site_on_wc_order_completion($order_id): void {
if ( ! function_exists('wc_get_order')) {
return;
}
$order = wc_get_order($order_id);
if ( ! $order) {
return;
}
$billing_email = $order->get_billing_email();
if ( ! $billing_email) {
return;
}
$transient_key = 'wu_transferable_pending_' . md5($billing_email);
$pending_site = get_transient($transient_key);
if ( ! $pending_site) {
return;
}
$wp_user = get_user_by('email', $billing_email);
if ( ! $wp_user) {
return;
}
$customer = wu_get_customer_by_user_id($wp_user->ID);
if ( ! $customer) {
return;
}
$memberships = wu_get_memberships(
[
'customer_id' => $customer->get_id(),
'status' => Membership_Status::CANCELLED,
'number' => 1,
'orderby' => 'date_created',
'order' => 'DESC',
]
);
if (empty($memberships)) {
return;
}
$membership = $memberships[0];
$result = $membership->reactivate();
if (is_wp_error($result)) {
wu_log_add(self::LOG_FILE_NAME, $result->get_error_message(), LogLevel::ERROR);
return;
}
$membership->update_pending_site($pending_site);
update_post_meta(absint($order_id), '_wu_membership_id', $membership->get_id());
delete_transient($transient_key);
$membership->publish_pending_site_async();
}
/**
* Transfer a membership from a user to another.
*
* @since 2.0.0
*
* @param int $membership_id The ID of the membership being transferred.
* @param int $target_customer_id The new owner.
* @return void
*/
public function async_transfer_membership($membership_id, $target_customer_id) {
global $wpdb;
$membership = wu_get_membership($membership_id);
$target_customer = wu_get_customer($target_customer_id);
if ( ! $membership || ! $target_customer || absint($membership->get_customer_id()) === absint($target_customer->get_id())) {
wu_log_add(self::LOG_FILE_NAME, __('An unexpected error happened.', 'ultimate-multisite'), LogLevel::ERROR);
return;
}
$wpdb->query('START TRANSACTION'); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
try {
/*
* Get Sites and move them over.
*/
$sites = wu_get_sites(
[
'meta_query' => [ // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
'membership_id' => [
'key' => 'wu_membership_id',
'value' => $membership->get_id(),
],
],
]
);
foreach ($sites as $site) {
$site->set_customer_id($target_customer_id);
$saved = $site->save();
if (is_wp_error($saved)) {
$wpdb->query('ROLLBACK'); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
wu_log_add(self::LOG_FILE_NAME, $saved->get_error_message(), LogLevel::ERROR);
return;
}
}
/*
* Change the membership
*/
$membership->set_customer_id($target_customer_id);
$saved = $membership->save();
if (is_wp_error($saved)) {
$wpdb->query('ROLLBACK'); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
wu_log_add(self::LOG_FILE_NAME, $saved->get_error_message(), LogLevel::ERROR);
return;
}
$wpdb->query('COMMIT'); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
} catch (\Throwable $e) {
$wpdb->query('ROLLBACK'); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
wu_log_add(self::LOG_FILE_NAME, $e->getMessage(), LogLevel::ERROR);
} finally {
$membership->unlock();
}
}
/**
* Delete a membership.
*
* @since 2.0.0
*
* @param int $membership_id The ID of the membership being deleted.
* @return void
*/
public function async_delete_membership($membership_id) {
global $wpdb;
$membership = wu_get_membership($membership_id);
if ( ! $membership) {
wu_log_add(self::LOG_FILE_NAME, __('An unexpected error happened.', 'ultimate-multisite'), LogLevel::ERROR);
return;
}
$wpdb->query('START TRANSACTION'); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
try {
/*
* Get Sites and delete them.
*/
$sites = wu_get_sites(
[
'meta_query' => [ // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
'membership_id' => [
'key' => 'wu_membership_id',
'value' => $membership->get_id(),
],
],
]
);
foreach ($sites as $site) {
$saved = $site->delete();
if (is_wp_error($saved)) {
$wpdb->query('ROLLBACK'); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
wu_log_add(self::LOG_FILE_NAME, $saved->get_error_message(), LogLevel::ERROR);
return;
}
}
/*
* Delete the membership
*/
$saved = $membership->delete();
if (is_wp_error($saved)) {
$wpdb->query('ROLLBACK'); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
wu_log_add(self::LOG_FILE_NAME, $saved->get_error_message(), LogLevel::ERROR);
return;
}
} catch (\Throwable $e) {
$wpdb->query('ROLLBACK'); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
wu_log_add(self::LOG_FILE_NAME, $e->getMessage(), LogLevel::ERROR);
return;
}
$wpdb->query('COMMIT'); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
}
}