| @@ -45,11 +45,13 @@ | ||
| 45 | 45 | return apply_filters('ws_plugin__s2member_add_auto_eot_system', FALSE, get_defined_vars()); |
| 46 | 46 | } |
| 47 | 47 | else if(function_exists('wp_cron') /* Otherwise, we can schedule? */) |
| 48 | 48 | { |
| 49 | + //260823.1829 Verify the scheduled event itself because older WordPress versions supported by s2Member return no success value from wp_schedule_event(). | |
| 49 | 50 | wp_schedule_event(time(), 'every10m', 'ws_plugin__s2member_auto_eot_system__schedule'); |
| 51 | + $scheduled = (bool)wp_next_scheduled('ws_plugin__s2member_auto_eot_system__schedule') && wp_get_schedule('ws_plugin__s2member_auto_eot_system__schedule') === 'every10m'; | |
| 50 | 52 | |
| 51 | - return apply_filters('ws_plugin__s2member_add_auto_eot_system', TRUE, get_defined_vars()); | |
| 53 | + return apply_filters('ws_plugin__s2member_add_auto_eot_system', $scheduled, get_defined_vars()); | |
| 52 | 54 | } |
| 53 | 55 | else // Otherwise, it would appear that WP-Cron is not available. |
| 54 | 56 | { |
| 55 | 57 | return apply_filters('ws_plugin__s2member_add_auto_eot_system', FALSE, get_defined_vars()); |
| @@ -56,8 +58,53 @@ | ||
| 56 | 58 | } |
| 57 | 59 | } |
| 58 | 60 | |
| 59 | 61 | /** |
| 62 | + * Recreates a missing recurring Auto-EOT event while preserving any queued catch-up pass. | |
| 63 | + * | |
| 64 | + * @package s2Member\Auto_EOT_System | |
| 65 | + * @since 260819.0613 | |
| 66 | + * | |
| 67 | + * @return bool True when no repair is needed or the recurring event exists after repair; otherwise false. | |
| 68 | + */ | |
| 69 | + public static function ensure_auto_eot_system() | |
| 70 | + { | |
| 71 | + if(empty($GLOBALS['WS_PLUGIN__']['s2member']['o']['auto_eot_system_enabled']) || (string)$GLOBALS['WS_PLUGIN__']['s2member']['o']['auto_eot_system_enabled'] !== '1') | |
| 72 | + return TRUE; | |
| 73 | + | |
| 74 | + if(!function_exists('wp_cron')) | |
| 75 | + return FALSE; | |
| 76 | + | |
| 77 | + if(wp_next_scheduled('ws_plugin__s2member_auto_eot_system__schedule')) | |
| 78 | + return TRUE; | |
| 79 | + | |
| 80 | + //260820.0149 Preserve a pending catch-up pass because add_auto_eot_system() clears all Auto-EOT schedules before rebuilding the recurring one. | |
| 81 | + $continuation_at = wp_next_scheduled('ws_plugin__s2member_auto_eot_system__continuation'); | |
| 82 | + $scheduled = c_ws_plugin__s2member_auto_eots::add_auto_eot_system(); | |
| 83 | + if($scheduled && $continuation_at && !wp_next_scheduled('ws_plugin__s2member_auto_eot_system__continuation')) | |
| 84 | + wp_schedule_single_event(max(time() + 1, (int)$continuation_at), 'ws_plugin__s2member_auto_eot_system__continuation'); | |
| 85 | + | |
| 86 | + //260820.0149 Retain self-heal results for diagnostics, but throttle repeated failure writes on sites where WordPress rejects scheduling every request. | |
| 87 | + $state = get_option('ws_plugin__s2member_auto_eot_state'); | |
| 88 | + $state = is_array($state) ? $state : array(); | |
| 89 | + if($scheduled) | |
| 90 | + { | |
| 91 | + $state['last_schedule_repaired_at'] = time(); | |
| 92 | + $state['schedule_failure_count'] = 0; | |
| 93 | + update_option('ws_plugin__s2member_auto_eot_state', $state, FALSE); | |
| 94 | + } | |
| 95 | + else if(empty($state['last_schedule_failure_at']) || time() - (int)$state['last_schedule_failure_at'] >= 300) | |
| 96 | + { | |
| 97 | + $state['last_schedule_failure_at'] = time(); | |
| 98 | + $state['schedule_failure_count'] = !empty($state['schedule_failure_count']) ? (int)$state['schedule_failure_count'] + 1 : 1; | |
| 99 | + update_option('ws_plugin__s2member_auto_eot_state', $state, FALSE); | |
| 100 | + } | |
| 101 | + delete_transient('ws_plugin__s2member_auto_eot_health'); | |
| 102 | + | |
| 103 | + return $scheduled; | |
| 104 | + } | |
| 105 | + | |
| 106 | + /** | |
| 60 | 107 | * Deletes all scheduled tasks for s2Member's Auto-EOT System. |
| 61 | 108 | * |
| 62 | 109 | * @package s2Member\Auto_EOT_System |
| 63 | 110 | * @since 3.5 |
| @@ -70,8 +117,10 @@ | ||
| 70 | 117 | |
| 71 | 118 | if(function_exists('wp_cron') /* Is `wp_cron()` even available? */) |
| 72 | 119 | { |
| 73 | 120 | wp_clear_scheduled_hook('ws_plugin__s2member_auto_eot_system__schedule' /* Since v3.0.3. */); |
| 121 | + wp_clear_scheduled_hook('ws_plugin__s2member_auto_eot_system__continuation'); //260820.0056 Remove any pending catch-up pass when Auto-EOT scheduling is deleted. | |
| 122 | + delete_transient('ws_plugin__s2member_auto_eot_health'); //260820.0149 Invalidate schedule-dependent health data. | |
| 74 | 123 | |
| 75 | 124 | return apply_filters('ws_plugin__s2member_delete_auto_eot_system', TRUE, get_defined_vars()); |
| 76 | 125 | } |
| 77 | 126 | else // Otherwise, it would appear that WP-Cron is not available. |
| @@ -80,27 +129,796 @@ | ||
| 80 | 129 | } |
| 81 | 130 | } |
| 82 | 131 | |
| 83 | 132 | /** |
| 133 | + * Determines a safe wall-clock budget for one Auto-EOT pass. | |
| 134 | + * | |
| 135 | + * Automatic mode leaves more headroom in shared WP-Cron than in a dedicated external-cron request. | |
| 136 | + * Custom mode is still bounded below PHP's finite execution limit; the developer filter remains final. | |
| 137 | + * | |
| 138 | + * @package s2Member\Auto_EOT_System | |
| 139 | + * @since 260820.0056 | |
| 140 | + * | |
| 141 | + * @param bool|null $is_external_cron Optional explicit execution context; null auto-detects the external-cron endpoint. | |
| 142 | + * | |
| 143 | + * @return float Runtime budget in seconds. | |
| 144 | + */ | |
| 145 | + public static function auto_eot_system_runtime_budget($is_external_cron = NULL) | |
| 146 | + { | |
| 147 | + $php_max_execution_time = (int)ini_get('max_execution_time'); | |
| 148 | + if($is_external_cron === NULL) | |
| 149 | + $is_external_cron = !empty($_GET['s2member_auto_eot_system_via_cron']); | |
| 150 | + else | |
| 151 | + $is_external_cron = (bool)$is_external_cron; | |
| 152 | + | |
| 153 | + $automatic_budget = $php_max_execution_time > 0 ? floor($php_max_execution_time * ($is_external_cron ? 0.80 : 0.60)) : ($is_external_cron ? 60 : 30); | |
| 154 | + | |
| 155 | + //260820.0306 Custom runtime may raise/lower the automatic target, but keep 10% PHP headroom unless a developer deliberately overrides the final filter. | |
| 156 | + if((string)$GLOBALS['WS_PLUGIN__']['s2member']['o']['auto_eot_system_runtime_mode'] === 'custom') | |
| 157 | + { | |
| 158 | + $runtime_budget = max(1, (float)$GLOBALS['WS_PLUGIN__']['s2member']['o']['auto_eot_system_runtime_custom']); | |
| 159 | + if($php_max_execution_time > 0) | |
| 160 | + $runtime_budget = min($runtime_budget, max(1, floor($php_max_execution_time * 0.90))); | |
| 161 | + } | |
| 162 | + else | |
| 163 | + $runtime_budget = max(1, $automatic_budget); | |
| 164 | + | |
| 165 | + $runtime_budget = (float)apply_filters('ws_plugin__s2member_auto_eot_system_runtime', $runtime_budget, get_defined_vars()); | |
| 166 | + | |
| 167 | + return max(1, $runtime_budget); | |
| 168 | + } | |
| 169 | + | |
| 170 | + /** | |
| 171 | + * Describes legacy Auto-EOT per-process filters for diagnostics. | |
| 172 | + * | |
| 173 | + * This never executes the legacy filter. It only reports hooked callbacks and any effective cap | |
| 174 | + * recorded by the last Auto-EOT run, so an inherited customization is visible to site owners. | |
| 175 | + * | |
| 176 | + * @package s2Member\Auto_EOT_System | |
| 177 | + * @since 260820.0306 | |
| 178 | + * | |
| 179 | + * @return array Legacy filter information. | |
| 180 | + */ | |
| 181 | + public static function auto_eot_system_legacy_cap_info() | |
| 182 | + { | |
| 183 | + global $wp_filter; | |
| 184 | + | |
| 185 | + $hook = 'ws_plugin__s2member_auto_eot_system_per_process'; | |
| 186 | + $state = get_option('ws_plugin__s2member_auto_eot_state'); | |
| 187 | + $state = is_array($state) ? $state : array(); | |
| 188 | + $info = array( | |
| 189 | + 'detected' => has_filter($hook) !== FALSE, | |
| 190 | + 'sources' => array(), | |
| 191 | + 'last_hard_cap' => isset($state['last_hard_cap']) && $state['last_hard_cap'] !== NULL ? (int)$state['last_hard_cap'] : NULL, | |
| 192 | + 'last_hard_cap_source' => !empty($state['last_hard_cap_source']) ? (string)$state['last_hard_cap_source'] : '', | |
| 193 | + 'estimated_additional' => !empty($state['legacy_cap_estimated_additional']) ? (int)$state['legacy_cap_estimated_additional'] : 0, | |
| 194 | + 'last_stop_reason' => !empty($state['last_stop_reason']) ? (string)$state['last_stop_reason'] : '', | |
| 195 | + ); | |
| 196 | + | |
| 197 | + if(!$info['detected'] || empty($wp_filter[$hook]) || !is_object($wp_filter[$hook]) || empty($wp_filter[$hook]->callbacks)) | |
| 198 | + return $info; | |
| 199 | + | |
| 200 | + //260820.0306 Reflection is best-effort diagnostics only; unusual callback forms still count as detected even when their source cannot be identified. | |
| 201 | + foreach($wp_filter[$hook]->callbacks as $priority => $callbacks) | |
| 202 | + { | |
| 203 | + foreach((array)$callbacks as $callback_data) | |
| 204 | + { | |
| 205 | + if(empty($callback_data['function'])) | |
| 206 | + continue; | |
| 207 | + | |
| 208 | + $callback = $callback_data['function']; | |
| 209 | + $label = ''; | |
| 210 | + $reflection = NULL; | |
| 211 | + | |
| 212 | + try | |
| 213 | + { | |
| 214 | + if(is_string($callback)) | |
| 215 | + { | |
| 216 | + $label = $callback; | |
| 217 | + if(strpos($callback, '::') !== FALSE) | |
| 218 | + { | |
| 219 | + $_callback_parts = explode('::', $callback, 2); | |
| 220 | + $reflection = new ReflectionMethod($_callback_parts[0], $_callback_parts[1]); | |
| 221 | + unset($_callback_parts); | |
| 222 | + } | |
| 223 | + else | |
| 224 | + $reflection = new ReflectionFunction($callback); | |
| 225 | + } | |
| 226 | + else if(is_array($callback) && count($callback) === 2) | |
| 227 | + { | |
| 228 | + $label = (is_object($callback[0]) ? get_class($callback[0]) : (string)$callback[0]).'::'.$callback[1]; | |
| 229 | + $reflection = new ReflectionMethod($callback[0], $callback[1]); | |
| 230 | + } | |
| 231 | + else if($callback instanceof Closure) | |
| 232 | + { | |
| 233 | + $label = 'Closure'; | |
| 234 | + $reflection = new ReflectionFunction($callback); | |
| 235 | + } | |
| 236 | + else if(is_object($callback) && is_callable($callback)) | |
| 237 | + { | |
| 238 | + $label = get_class($callback).'::__invoke'; | |
| 239 | + $reflection = new ReflectionMethod($callback, '__invoke'); | |
| 240 | + } | |
| 241 | + } | |
| 242 | + catch(ReflectionException $e) | |
| 243 | + { | |
| 244 | + $reflection = NULL; | |
| 245 | + } | |
| 246 | + | |
| 247 | + $file = ($reflection && $reflection->getFileName()) ? wp_normalize_path($reflection->getFileName()) : ''; | |
| 248 | + if($file && strpos($file, wp_normalize_path(ABSPATH)) === 0) | |
| 249 | + $file = ltrim(substr($file, strlen(wp_normalize_path(ABSPATH))), '/'); | |
| 250 | + | |
| 251 | + $info['sources'][] = array( | |
| 252 | + 'priority' => (int)$priority, | |
| 253 | + 'callback' => $label, | |
| 254 | + 'file' => $file, | |
| 255 | + 'line' => ($reflection && $reflection->getStartLine()) ? (int)$reflection->getStartLine() : 0, | |
| 256 | + ); | |
| 257 | + } | |
| 258 | + } | |
| 259 | + return $info; | |
| 260 | + } | |
| 261 | + | |
| 262 | + /** | |
| 263 | + * Determines whether End-of-Term processing may irreversibly delete a WordPress user. | |
| 264 | + * | |
| 265 | + * The safe default is false: the stored `delete` behavior moves the account to Pending Deletion instead. | |
| 266 | + * Developers that intentionally require automatic account deletion can opt in through this filter. Keeping | |
| 267 | + * the decision centralized ensures scheduled Auto-EOT and immediate gateway-triggered EOTs use the same policy. | |
| 268 | + * | |
| 269 | + * @package s2Member\Auto_EOT_System | |
| 270 | + * @since 260822.0520 | |
| 271 | + * | |
| 272 | + * @param int $user_id WordPress user ID being processed. | |
| 273 | + * @param string $eot_del_type Prospective irreversible-deletion event type. | |
| 274 | + * | |
| 275 | + * @return bool True only when a developer explicitly allows irreversible End-of-Term deletion. | |
| 276 | + */ | |
| 277 | + public static function allow_eot_user_deletion($user_id = 0, $eot_del_type = '') | |
| 278 | + { | |
| 279 | + return (bool)apply_filters('ws_plugin__s2member_allow_eot_user_deletion', FALSE, get_defined_vars()); | |
| 280 | + } | |
| 281 | + | |
| 282 | + /** | |
| 283 | + * Applies the configured EOT role demotion to a user. | |
| 284 | + * | |
| 285 | + * @package s2Member\Auto_EOT_System | |
| 286 | + * @since 260916.2004 | |
| 287 | + * | |
| 288 | + * @param \WP_User $user WordPress user being demoted. | |
| 289 | + * @param string $demotion_to_role Role assigned after EOT. | |
| 290 | + * | |
| 291 | + * @return string Role before demotion, for EOT history. | |
| 292 | + */ | |
| 293 | + public static function demote_user_roles($user = NULL, $demotion_to_role = 'subscriber') | |
| 294 | + { | |
| 295 | + if(!is_object($user) || empty($user->ID) || !is_string($demotion_to_role) || !$demotion_to_role) | |
| 296 | + return ''; | |
| 297 | + | |
| 298 | + $existing_role = c_ws_plugin__s2member_user_access::user_access_role($user); | |
| 299 | + //260916.2030 Preserve the historical all-role path exactly; upgraded installations are explicitly seeded to this policy. | |
| 300 | + if($GLOBALS['WS_PLUGIN__']['s2member']['o']['eot_demotion_from'] === 'all') | |
| 301 | + { | |
| 302 | + if($existing_role !== $demotion_to_role) | |
| 303 | + $user->set_role($demotion_to_role); | |
| 304 | + return $existing_role; | |
| 305 | + } | |
| 306 | + | |
| 307 | + $eot_original_role = ''; | |
| 308 | + //260916.2030 The new default removes only explicit paid s2Member Level roles; Subscriber/Level 0 is a possible destination, never a Demote From role. | |
| 309 | + foreach((array)$user->roles as $role) | |
| 310 | + if(preg_match('/^s2member_level[1-9][0-9]*$/', $role)) | |
| 311 | + { | |
| 312 | + if(!$eot_original_role) | |
| 313 | + $eot_original_role = $role; | |
| 314 | + if($role !== $demotion_to_role) | |
| 315 | + $user->remove_role($role); | |
| 316 | + } | |
| 317 | + if(!in_array($demotion_to_role, (array)$user->roles, TRUE)) | |
| 318 | + $user->add_role($demotion_to_role); | |
| 319 | + | |
| 320 | + return $eot_original_role ?: $existing_role; | |
| 321 | + } | |
| 322 | + | |
| 323 | + /** | |
| 324 | + * Records when an End-of-Term action was processed and appends one compact history note. | |
| 325 | + * | |
| 326 | + * @package s2Member\Auto_EOT_System | |
| 327 | + * @since 260822.0653 | |
| 328 | + * | |
| 329 | + * @param int $user_id WordPress user ID that survived End-of-Term processing. | |
| 330 | + * @param array $details Named End-of-Term history details. | |
| 331 | + * | |
| 332 | + * @return null | |
| 333 | + */ | |
| 334 | + public static function record_eot_history($user_id = 0, $details = array()) | |
| 335 | + { | |
| 336 | + $user_id = (int)$user_id; | |
| 337 | + //260822.1458 Keep evolving EOT context named instead of positional so call sites cannot silently misorder history fields as this record grows. | |
| 338 | + $details = array_merge(array( | |
| 339 | + 'eot_time' => 0, | |
| 340 | + 'processed_at' => 0, | |
| 341 | + 'original_role' => '', | |
| 342 | + 'destination_role' => '', | |
| 343 | + 'removed_ccaps' => array(), | |
| 344 | + 'subscr_gateway' => '', | |
| 345 | + 'subscr_id' => '', | |
| 346 | + ), (array)$details); | |
| 347 | + $eot_time = (int)$details['eot_time']; | |
| 348 | + $processed_at = (int)$details['processed_at']; | |
| 349 | + $original_role = (string)$details['original_role']; | |
| 350 | + $destination_role = (string)$details['destination_role']; | |
| 351 | + $removed_ccaps = (array)$details['removed_ccaps']; | |
| 352 | + $subscr_gateway = (string)$details['subscr_gateway']; | |
| 353 | + $subscr_id = (string)$details['subscr_id']; | |
| 354 | + if(!$user_id || !$processed_at) | |
| 355 | + return; | |
| 356 | + | |
| 357 | + try | |
| 358 | + { | |
| 359 | + //260822.0653 Prefer WordPress' timezone object when available so historical EOT and processing timestamps each get the correct DST abbreviation. | |
| 360 | + if(function_exists('wp_timezone')) | |
| 361 | + $timezone = wp_timezone(); | |
| 362 | + else if(($timezone_string = (string)get_option('timezone_string'))) | |
| 363 | + $timezone = new DateTimeZone($timezone_string); | |
| 364 | + else | |
| 365 | + { | |
| 366 | + $offset = (float)get_option('gmt_offset', 0); | |
| 367 | + $offset_abs = abs($offset); | |
| 368 | + $timezone = new DateTimeZone(sprintf('%s%02d:%02d', $offset < 0 ? '-' : '+', floor($offset_abs), round(($offset_abs - floor($offset_abs)) * 60))); | |
| 369 | + } | |
| 370 | + $processed_date = new DateTime('@'.$processed_at); | |
| 371 | + $processed_date->setTimezone($timezone); | |
| 372 | + $eot_date = new DateTime('@'.($eot_time ?: $processed_at)); | |
| 373 | + $eot_date->setTimezone($timezone); | |
| 374 | + $processed_display = $processed_date->format('Y-m-d H:i T'); | |
| 375 | + $eot_display = $eot_date->format('Y-m-d H:i T'); | |
| 376 | + } | |
| 377 | + catch(Exception $exception) | |
| 378 | + { | |
| 379 | + //260822.0653 Invalid legacy timezone settings must not block EOT processing; UTC is the deterministic fallback for the audit note. | |
| 380 | + $processed_display = gmdate('Y-m-d H:i', $processed_at).' UTC'; | |
| 381 | + $eot_display = gmdate('Y-m-d H:i', $eot_time ?: $processed_at).' UTC'; | |
| 382 | + } | |
| 383 | + | |
| 384 | + global $wp_roles; | |
| 385 | + if(!is_object($wp_roles)) | |
| 386 | + $wp_roles = new WP_Roles(); | |
| 387 | + $role_labels = array(); | |
| 388 | + foreach(array($original_role, $destination_role) as $_role) | |
| 389 | + { | |
| 390 | + $_role = (string)$_role; | |
| 391 | + if(preg_match('/^s2member_level([0-9]+)$/', $_role, $_matches)) | |
| 392 | + { | |
| 393 | + //260829.0618 Keep EOT audit notes consistent with the administrator's forced s2Member labels, while retaining concise Level N names when label translation is disabled. | |
| 394 | + $_level = (int)$_matches[1]; | |
| 395 | + $_label_key = 'level'.$_level.'_label'; | |
| 396 | + $role_labels[$_role] = !empty($GLOBALS["WS_PLUGIN__"]["s2member"]["o"]["apply_label_translations"]) && !empty($GLOBALS["WS_PLUGIN__"]["s2member"]["o"][$_label_key]) | |
| 397 | + ? $GLOBALS["WS_PLUGIN__"]["s2member"]["o"][$_label_key] | |
| 398 | + : 'Level '.$_level; | |
| 399 | + } | |
| 400 | + else if($_role === 's2member_pending_deletion') | |
| 401 | + $role_labels[$_role] = 'Pending Deletion'; | |
| 402 | + else if($_role && isset($wp_roles->roles[$_role]['name'])) | |
| 403 | + $role_labels[$_role] = translate_user_role($wp_roles->roles[$_role]['name']); | |
| 404 | + else | |
| 405 | + $role_labels[$_role] = $_role ? ucwords(str_replace(array('-', '_'), ' ', $_role)) : 'Unknown Role'; | |
| 406 | + } | |
| 407 | + unset($_role, $_matches, $_level, $_label_key); | |
| 408 | + | |
| 409 | + $gateway_labels = array('paypal' => 'PayPal', 'authnet' => 'Authorize.Net', 'clickbank' => 'ClickBank', 'ccbill' => 'ccBill', 'alipay' => 'AliPay', 'google' => 'Google Wallet', 'stripe' => 'Stripe'); | |
| 410 | + $gateway_key = strtolower((string)$subscr_gateway); | |
| 411 | + $gateway_label = isset($gateway_labels[$gateway_key]) ? $gateway_labels[$gateway_key] : ucwords(str_replace(array('-', '_'), ' ', $gateway_key)); | |
| 412 | + $removed_ccaps = array_values(array_unique(array_filter(array_map('strval', (array)$removed_ccaps), 'strlen'))); | |
| 413 | + sort($removed_ccaps, SORT_STRING); | |
| 414 | + | |
| 415 | + //260829.0618 Avoid recording a misleading role transition when EOT processing finds the user already in the role selected under Demote To Role. | |
| 416 | + if($original_role === $destination_role) | |
| 417 | + $note = $processed_display.' s2Member: EOT processed, already '.$role_labels[(string)$original_role]; | |
| 418 | + else | |
| 419 | + $note = $processed_display.' s2Member: Demoted from '.$role_labels[(string)$original_role].' to '.$role_labels[(string)$destination_role]; | |
| 420 | + if($removed_ccaps) | |
| 421 | + $note .= ' (removed ccaps: '.implode(', ', $removed_ccaps).')'; | |
| 422 | + $note .= '.'; | |
| 423 | + if($subscr_gateway && $subscr_id) | |
| 424 | + $note .= ' '.$gateway_label.' '.$subscr_id.'.'; | |
| 425 | + $note .= ' EOT '.$eot_display.'.'; | |
| 426 | + | |
| 427 | + //260822.0653 Keep the action timestamp independent from the triggering EOT timestamp; delayed processing can make these materially different. | |
| 428 | + update_user_option($user_id, 's2member_last_auto_eot_processed_time', $processed_at); | |
| 429 | + c_ws_plugin__s2member_user_notes::append_user_notes($user_id, $note); | |
| 430 | + } | |
| 431 | + | |
| 432 | + /** | |
| 433 | + * Starts a best-effort upgrade backfill of historical EOT processing times. | |
| 434 | + * | |
| 435 | + * @package s2Member\Auto_EOT_System | |
| 436 | + * @since 260822.2048 | |
| 437 | + * | |
| 438 | + * @return null | |
| 439 | + */ | |
| 440 | + public static function start_eot_processed_time_backfill() | |
| 441 | + { | |
| 442 | + $state_option = 'ws_plugin__s2member_auto_eot_state'; | |
| 443 | + $state = get_option($state_option); | |
| 444 | + $state = is_array($state) ? $state : array(); | |
| 445 | + | |
| 446 | + //260822.2048 Reuse Auto-EOT's operational state for this temporary migration cursor; no separate migration option or table is needed. | |
| 447 | + if(!array_key_exists('processed_time_backfill_cursor_umeta_id', $state)) | |
| 448 | + { | |
| 449 | + $state['processed_time_backfill_cursor_umeta_id'] = 0; | |
| 450 | + update_option($state_option, $state, FALSE); | |
| 451 | + } | |
| 452 | + self::ensure_eot_processed_time_backfill(); | |
| 453 | + } | |
| 454 | + | |
| 455 | + /** | |
| 456 | + * Ensures that an unfinished historical EOT processing-time backfill has a continuation event. | |
| 457 | + * | |
| 458 | + * @package s2Member\Auto_EOT_System | |
| 459 | + * @since 260822.2048 | |
| 460 | + * | |
| 461 | + * @return null | |
| 462 | + */ | |
| 463 | + public static function ensure_eot_processed_time_backfill() | |
| 464 | + { | |
| 465 | + $state = get_option('ws_plugin__s2member_auto_eot_state'); | |
| 466 | + $hook = 'ws_plugin__s2member_eot_processed_time_backfill'; | |
| 467 | + | |
| 468 | + if(is_array($state) && array_key_exists('processed_time_backfill_cursor_umeta_id', $state) && !wp_next_scheduled($hook)) | |
| 469 | + wp_schedule_single_event(time() + 5, $hook); | |
| 470 | + } | |
| 471 | + | |
| 472 | + /** | |
| 473 | + * Backfills EOT processing times that can be recovered from legacy Administrative Notes. | |
| 474 | + * | |
| 475 | + * @package s2Member\Auto_EOT_System | |
| 476 | + * @since 260822.2048 | |
| 477 | + * | |
| 478 | + * @return null | |
| 479 | + */ | |
| 480 | + public static function backfill_eot_processed_times() | |
| 481 | + { | |
| 482 | + global $wpdb; | |
| 483 | + | |
| 484 | + $state_option = 'ws_plugin__s2member_auto_eot_state'; | |
| 485 | + $state = get_option($state_option); | |
| 486 | + $state = is_array($state) ? $state : array(); | |
| 487 | + if(!array_key_exists('processed_time_backfill_cursor_umeta_id', $state)) | |
| 488 | + return; | |
| 489 | + | |
| 490 | + $cursor_umeta_id = (int)$state['processed_time_backfill_cursor_umeta_id']; | |
| 491 | + $last_key = $wpdb->prefix.'s2member_last_auto_eot_time'; | |
| 492 | + $processed_key = $wpdb->prefix.'s2member_last_auto_eot_processed_time'; | |
| 493 | + $notes_key = $wpdb->prefix.'s2member_notes'; | |
| 494 | + $rows = $wpdb->get_results($wpdb->prepare( | |
| 495 | + "SELECT `last`.`umeta_id`, `last`.`user_id`, CAST(`last`.`meta_value` AS UNSIGNED) AS `eot_time`, `notes`.`meta_value` AS `notes` FROM `".$wpdb->usermeta."` `last` INNER JOIN `".$wpdb->usermeta."` `notes` ON `notes`.`user_id` = `last`.`user_id` AND `notes`.`meta_key` = %s LEFT JOIN `".$wpdb->usermeta."` `processed` ON `processed`.`user_id` = `last`.`user_id` AND `processed`.`meta_key` = %s WHERE `last`.`meta_key` = %s AND `last`.`umeta_id` > %d AND CAST(`last`.`meta_value` AS UNSIGNED) > 0 AND `processed`.`umeta_id` IS NULL AND `notes`.`meta_value` LIKE %s ORDER BY `last`.`umeta_id` ASC LIMIT 100", | |
| 496 | + $notes_key, $processed_key, $last_key, $cursor_umeta_id, '%Demoted by s2Member:%' | |
| 497 | + )); | |
| 498 | + $rows = is_array($rows) ? $rows : array(); | |
| 499 | + | |
| 500 | + foreach($rows as $row) | |
| 501 | + { | |
| 502 | + $cursor_umeta_id = (int)$row->umeta_id; | |
| 503 | + $lines = preg_split('/\r\n|\r|\n/', (string)$row->notes); | |
| 504 | + foreach(array_reverse((array)$lines) as $line) | |
| 505 | + if(preg_match('/^Demoted by s2Member:\s*(.+)$/', trim($line), $matches)) | |
| 506 | + { | |
| 507 | + $processed_at = strtotime($matches[1]); | |
| 508 | + //260822.2048 Legacy notes have minute precision; accept up to 59 seconds before an immediate EOT timestamp, but never guess from an older unrelated demotion note. | |
| 509 | + if($processed_at && $processed_at + MINUTE_IN_SECONDS >= (int)$row->eot_time) | |
| 510 | + { | |
| 511 | + $current_last_eot = $wpdb->get_var($wpdb->prepare("SELECT CAST(`meta_value` AS UNSIGNED) FROM `".$wpdb->usermeta."` WHERE `umeta_id` = %d AND `user_id` = %d AND `meta_key` = %s LIMIT 1", (int)$row->umeta_id, (int)$row->user_id, $last_key)); | |
| 512 | + $processed_exists = $wpdb->get_var($wpdb->prepare("SELECT 1 FROM `".$wpdb->usermeta."` WHERE `user_id` = %d AND `meta_key` = %s LIMIT 1", (int)$row->user_id, $processed_key)); | |
| 513 | + //260822.2259 Revalidate before writing legacy history; a newly processed EOT always wins over this best-effort upgrade backfill. | |
| 514 | + if($current_last_eot !== NULL && (int)$current_last_eot === (int)$row->eot_time && !$processed_exists) | |
| 515 | + add_user_meta((int)$row->user_id, $processed_key, $processed_at, TRUE); | |
| 516 | + break; | |
| 517 | + } | |
| 518 | + } | |
| 519 | + } | |
| 520 | + unset($row, $lines, $line, $matches, $processed_at); | |
| 521 | + | |
| 522 | + $state = get_option($state_option); | |
| 523 | + $state = is_array($state) ? $state : array(); | |
| 524 | + if(count($rows) === 100) | |
| 525 | + $state['processed_time_backfill_cursor_umeta_id'] = $cursor_umeta_id; | |
| 526 | + else | |
| 527 | + unset($state['processed_time_backfill_cursor_umeta_id']); | |
| 528 | + update_option($state_option, $state, FALSE); | |
| 529 | + | |
| 530 | + if(count($rows) === 100) | |
| 531 | + self::ensure_eot_processed_time_backfill(); | |
| 532 | + } | |
| 533 | + | |
| 534 | + /** | |
| 535 | + * Applies the effective `delete` End-of-Term behavior. | |
| 536 | + * | |
| 537 | + * @package s2Member\Auto_EOT_System | |
| 538 | + * @since 260822.0535 | |
| 539 | + * | |
| 540 | + * @param int $user_id WordPress user ID being processed. | |
| 541 | + * @param string $eot_del_type EOT/deletion event type. | |
| 542 | + * @param int $eot_time Unix timestamp that triggered this End-of-Term action. | |
| 543 | + * | |
| 544 | + * @return string `pending_deletion`, `deleted`, `removed`, or an empty string when no user was processed. | |
| 545 | + */ | |
| 546 | + public static function process_eot_deletion($user_id = 0, $eot_del_type = '', $eot_time = 0) | |
| 547 | + { | |
| 548 | + $user_id = (int)$user_id; | |
| 549 | + $eot_time = (int)$eot_time; | |
| 550 | + if(!$user_id || !is_object($user = new WP_User($user_id)) || !$user->ID) | |
| 551 | + return ''; | |
| 552 | + | |
| 553 | + if(self::allow_eot_user_deletion($user_id, $eot_del_type)) | |
| 554 | + { | |
| 555 | + //260822.0535 True deletion is deliberately opt-in; preserve the historical deletion/removal path only after the developer filter explicitly allows it. | |
| 556 | + $GLOBALS['ws_plugin__s2member_eot_del_type'] = (string)$eot_del_type; | |
| 557 | + if(is_multisite()) | |
| 558 | + { | |
| 559 | + $blog_id = get_current_blog_id(); | |
| 560 | + remove_user_from_blog($user_id, $blog_id); | |
| 561 | + c_ws_plugin__s2member_user_deletions::handle_ms_user_deletions($user_id, $blog_id, 's2says'); | |
| 562 | + return 'removed'; | |
| 563 | + } | |
| 564 | + include_once ABSPATH.'wp-admin/includes/admin.php'; | |
| 565 | + wp_delete_user($user_id); | |
| 566 | + return 'deleted'; | |
| 567 | + } | |
| 568 | + | |
| 569 | + $pending_role = 's2member_pending_deletion'; | |
| 570 | + $pending_meta = get_user_option('s2member_eot_pending_deletion', $user_id); | |
| 571 | + $already_pending = in_array($pending_role, (array)$user->roles, TRUE) && is_array($pending_meta) && isset($pending_meta['eot_time'], $pending_meta['processed_at'], $pending_meta['original_role']); | |
| 572 | + $original_role = $already_pending ? (string)$pending_meta['original_role'] : c_ws_plugin__s2member_user_access::user_access_role($user); | |
| 573 | + $processed_at = time(); | |
| 574 | + $removed_ccaps = $already_pending ? array() : c_ws_plugin__s2member_user_access::user_access_ccaps($user); | |
| 575 | + $subscr_gateway = $already_pending ? '' : get_user_option('s2member_subscr_gateway', $user_id); | |
| 576 | + $subscr_id = $already_pending ? '' : get_user_option('s2member_subscr_id', $user_id); | |
| 577 | + | |
| 578 | + //260822.0549 A surviving account can receive a replayed gateway event; preserve the first transition record and avoid duplicate EOT history/notifications when it is already safely pending. | |
| 579 | + if(!$already_pending) | |
| 580 | + update_user_option($user_id, 's2member_eot_pending_deletion', array( | |
| 581 | + 'eot_time' => $eot_time ?: $processed_at, | |
| 582 | + 'processed_at' => $processed_at, | |
| 583 | + 'original_role' => $original_role, | |
| 584 | + )); | |
| 585 | + delete_user_option($user_id, 's2member_auto_eot_time'); | |
| 586 | + delete_user_option($user_id, 's2member_auto_eot_details'); | |
| 587 | + | |
| 588 | + //260822.0535 Activation normally creates this role; the fallback keeps an EOT safe if role configuration has not yet been refreshed after an in-place update. | |
| 589 | + if(!get_role($pending_role)) | |
| 590 | + add_role($pending_role, 'Pending Deletion', array('read' => TRUE)); | |
| 591 | + if(!in_array($pending_role, (array)$user->roles, TRUE)) | |
| 592 | + $user->set_role($pending_role); | |
| 593 | + | |
| 594 | + //260822.0535 Pending Deletion must never retain user-specific s2Member Level or Custom Capability grants after the role change. | |
| 595 | + foreach($user->allcaps as $cap => $cap_enabled) | |
| 596 | + if($cap_enabled && preg_match('/^access_s2member_(?:level[0-9]+|ccap_)/', $cap)) | |
| 597 | + $user->remove_cap($cap); | |
| 598 | + | |
| 599 | + if(!$already_pending) | |
| 600 | + { | |
| 601 | + //260822.0653 Pending Deletion survives the EOT, so archive the triggering timestamp just like an ordinary demotion; this keeps Last EOT/reporting complete without clearing gateway metadata needed for review. | |
| 602 | + update_user_option($user_id, 's2member_last_auto_eot_time', $eot_time ?: $processed_at); | |
| 603 | + self::record_eot_history($user_id, array( | |
| 604 | + 'eot_time' => $eot_time ?: $processed_at, | |
| 605 | + 'processed_at' => $processed_at, | |
| 606 | + 'original_role' => $original_role, | |
| 607 | + 'destination_role' => $pending_role, | |
| 608 | + 'removed_ccaps' => $removed_ccaps, | |
| 609 | + 'subscr_gateway' => $subscr_gateway, | |
| 610 | + 'subscr_id' => $subscr_id, | |
| 611 | + )); | |
| 612 | + //260822.0535 A preserved account never reaches WordPress' deletion hook, so send the configured EOT/Deletion notifications explicitly instead of silently dropping them. | |
| 613 | + self::pending_deletion_notifications($user_id, $eot_del_type); | |
| 614 | + } | |
| 615 | + | |
| 616 | + return 'pending_deletion'; | |
| 617 | + } | |
| 618 | + | |
| 619 | + /** | |
| 620 | + * Sends configured EOT/Deletion notifications for an account preserved in Pending Deletion. | |
| 621 | + * | |
| 622 | + * @package s2Member\Auto_EOT_System | |
| 623 | + * @since 260822.0535 | |
| 624 | + * | |
| 625 | + * @param int $user_id WordPress user ID being preserved. | |
| 626 | + * @param string $eot_del_type EOT/deletion event type. | |
| 627 | + * | |
| 628 | + * @return null | |
| 629 | + */ | |
| 630 | + public static function pending_deletion_notifications($user_id = 0, $eot_del_type = '') | |
| 631 | + { | |
| 632 | + $user_id = (int)$user_id; | |
| 633 | + if(!$user_id || !is_object($user = new WP_User($user_id)) || !$user->ID) | |
| 634 | + return; | |
| 635 | + | |
| 636 | + $custom = get_user_option('s2member_custom', $user_id); | |
| 637 | + $subscr_id = get_user_option('s2member_subscr_id', $user_id); | |
| 638 | + $subscr_baid = get_user_option('s2member_subscr_baid', $user_id); | |
| 639 | + $subscr_cid = get_user_option('s2member_subscr_cid', $user_id); | |
| 640 | + $fields = get_user_option('s2member_custom_fields', $user_id); | |
| 641 | + $user_reg_ip = get_user_option('s2member_registration_ip', $user_id); | |
| 642 | + | |
| 643 | + if($GLOBALS['WS_PLUGIN__']['s2member']['o']['eot_del_notification_urls']) | |
| 644 | + { | |
| 645 | + foreach(preg_split("/[\r\n\t]+/", $GLOBALS['WS_PLUGIN__']['s2member']['o']['eot_del_notification_urls']) as $url) | |
| 646 | + if(($url = c_ws_plugin__s2member_utils_strings::fill_cvs($url, $custom, true)) && ($url = preg_replace('/%%eot_del_type%%/i', c_ws_plugin__s2member_utils_strings::esc_refs(urlencode($eot_del_type)), $url)) && ($url = preg_replace('/%%subscr_id%%/i', c_ws_plugin__s2member_utils_strings::esc_refs(urlencode($subscr_id)), $url))) | |
| 647 | + if(($url = preg_replace('/%%subscr_baid%%/i', c_ws_plugin__s2member_utils_strings::esc_refs(urlencode($subscr_baid)), $url)) && ($url = preg_replace('/%%subscr_cid%%/i', c_ws_plugin__s2member_utils_strings::esc_refs(urlencode($subscr_cid)), $url))) | |
| 648 | + if(($url = preg_replace('/%%user_first_name%%/i', c_ws_plugin__s2member_utils_strings::esc_refs(urlencode($user->first_name)), $url)) && ($url = preg_replace('/%%user_last_name%%/i', c_ws_plugin__s2member_utils_strings::esc_refs(urlencode($user->last_name)), $url))) | |
| 649 | + if(($url = preg_replace('/%%user_full_name%%/i', c_ws_plugin__s2member_utils_strings::esc_refs(urlencode(trim($user->first_name.' '.$user->last_name))), $url))) | |
| 650 | + if(($url = preg_replace('/%%user_email%%/i', c_ws_plugin__s2member_utils_strings::esc_refs(urlencode($user->user_email)), $url))) | |
| 651 | + if(($url = preg_replace('/%%user_login%%/i', c_ws_plugin__s2member_utils_strings::esc_refs(urlencode($user->user_login)), $url))) | |
| 652 | + if(($url = preg_replace('/%%user_ip%%/i', c_ws_plugin__s2member_utils_strings::esc_refs(urlencode($user_reg_ip)), $url))) | |
| 653 | + if(($url = preg_replace('/%%user_id%%/i', c_ws_plugin__s2member_utils_strings::esc_refs(urlencode($user_id)), $url))) | |
| 654 | + { | |
| 655 | + if(is_array($fields) && !empty($fields)) | |
| 656 | + foreach($fields as $var => $val) | |
| 657 | + if(!($url = preg_replace('/%%'.preg_quote($var, '/').'%%/i', c_ws_plugin__s2member_utils_strings::esc_refs(urlencode(maybe_serialize($val))), $url))) | |
| 658 | + break; | |
| 659 | + | |
| 660 | + if(($url = trim(preg_replace('/%%(.+?)%%/i', '', $url)))) | |
| 661 | + c_ws_plugin__s2member_utils_urls::remote($url); | |
| 662 | + } | |
| 663 | + } | |
| 664 | + if($GLOBALS['WS_PLUGIN__']['s2member']['o']['eot_del_notification_recipients']) | |
| 665 | + { | |
| 666 | + $email_configs_were_on = c_ws_plugin__s2member_email_configs::email_config_status(); | |
| 667 | + c_ws_plugin__s2member_email_configs::email_config_release(); | |
| 668 | + | |
| 669 | + $msg = $sbj = '(s2Member / API Notification Email) - EOT/Deletion'; | |
| 670 | + $msg .= "\n\n"; | |
| 671 | + | |
| 672 | + $msg .= 'eot_del_type: %%eot_del_type%%'."\n"; | |
| 673 | + $msg .= 'subscr_id: %%subscr_id%%'."\n"; | |
| 674 | + $msg .= 'subscr_baid: %%subscr_baid%%'."\n"; | |
| 675 | + $msg .= 'subscr_cid: %%subscr_cid%%'."\n"; | |
| 676 | + $msg .= 'user_first_name: %%user_first_name%%'."\n"; | |
| 677 | + $msg .= 'user_last_name: %%user_last_name%%'."\n"; | |
| 678 | + $msg .= 'user_full_name: %%user_full_name%%'."\n"; | |
| 679 | + $msg .= 'user_email: %%user_email%%'."\n"; | |
| 680 | + $msg .= 'user_login: %%user_login%%'."\n"; | |
| 681 | + $msg .= 'user_ip: %%user_ip%%'."\n"; | |
| 682 | + $msg .= 'user_id: %%user_id%%'."\n"; | |
| 683 | + | |
| 684 | + if(is_array($fields) && !empty($fields)) | |
| 685 | + foreach($fields as $var => $val) | |
| 686 | + $msg .= $var.': %%'.$var.'%%'."\n"; | |
| 687 | + | |
| 688 | + $msg .= 'cv0: %%cv0%%'."\n"; | |
| 689 | + $msg .= 'cv1: %%cv1%%'."\n"; | |
| 690 | + $msg .= 'cv2: %%cv2%%'."\n"; | |
| 691 | + $msg .= 'cv3: %%cv3%%'."\n"; | |
| 692 | + $msg .= 'cv4: %%cv4%%'."\n"; | |
| 693 | + $msg .= 'cv5: %%cv5%%'."\n"; | |
| 694 | + $msg .= 'cv6: %%cv6%%'."\n"; | |
| 695 | + $msg .= 'cv7: %%cv7%%'."\n"; | |
| 696 | + $msg .= 'cv8: %%cv8%%'."\n"; | |
| 697 | + $msg .= 'cv9: %%cv9%%'; | |
| 698 | + | |
| 699 | + if(($msg = c_ws_plugin__s2member_utils_strings::fill_cvs($msg, $custom)) && ($msg = preg_replace('/%%eot_del_type%%/i', c_ws_plugin__s2member_utils_strings::esc_refs($eot_del_type), $msg)) && ($msg = preg_replace('/%%subscr_id%%/i', c_ws_plugin__s2member_utils_strings::esc_refs($subscr_id), $msg))) | |
| 700 | + if(($msg = preg_replace('/%%subscr_baid%%/i', c_ws_plugin__s2member_utils_strings::esc_refs($subscr_baid), $msg)) && ($msg = preg_replace('/%%subscr_cid%%/i', c_ws_plugin__s2member_utils_strings::esc_refs($subscr_cid), $msg))) | |
| 701 | + if(($msg = preg_replace('/%%user_first_name%%/i', c_ws_plugin__s2member_utils_strings::esc_refs($user->first_name), $msg)) && ($msg = preg_replace('/%%user_last_name%%/i', c_ws_plugin__s2member_utils_strings::esc_refs($user->last_name), $msg))) | |
| 702 | + if(($msg = preg_replace('/%%user_full_name%%/i', c_ws_plugin__s2member_utils_strings::esc_refs(trim($user->first_name.' '.$user->last_name)), $msg))) | |
| 703 | + if(($msg = preg_replace('/%%user_email%%/i', c_ws_plugin__s2member_utils_strings::esc_refs($user->user_email), $msg))) | |
| 704 | + if(($msg = preg_replace('/%%user_login%%/i', c_ws_plugin__s2member_utils_strings::esc_refs($user->user_login), $msg))) | |
| 705 | + if(($msg = preg_replace('/%%user_ip%%/i', c_ws_plugin__s2member_utils_strings::esc_refs($user_reg_ip), $msg))) | |
| 706 | + if(($msg = preg_replace('/%%user_id%%/i', c_ws_plugin__s2member_utils_strings::esc_refs($user_id), $msg))) | |
| 707 | + { | |
| 708 | + if(is_array($fields) && !empty($fields)) | |
| 709 | + foreach($fields as $var => $val) | |
| 710 | + if(!($msg = preg_replace('/%%'.preg_quote($var, '/').'%%/i', c_ws_plugin__s2member_utils_strings::esc_refs(maybe_serialize($val)), $msg))) | |
| 711 | + break; | |
| 712 | + | |
| 713 | + if($sbj && ($msg = trim(preg_replace('/%%(.+?)%%/i', '', $msg)))) | |
| 714 | + foreach(c_ws_plugin__s2member_utils_strings::parse_emails($GLOBALS['WS_PLUGIN__']['s2member']['o']['eot_del_notification_recipients']) as $recipient) | |
| 715 | + wp_mail($recipient, apply_filters('ws_plugin__s2member_eot_del_notification_email_sbj', $sbj, get_defined_vars()), apply_filters('ws_plugin__s2member_eot_del_notification_email_msg', $msg, get_defined_vars()), 'Content-Type: text/plain; charset=UTF-8'); | |
| 716 | + } | |
| 717 | + if($email_configs_were_on) | |
| 718 | + c_ws_plugin__s2member_email_configs::email_config(); | |
| 719 | + } | |
| 720 | + } | |
| 721 | + | |
| 722 | + /** | |
| 723 | + * Returns a cached health snapshot for the Auto-EOT system. | |
| 724 | + * | |
| 725 | + * @package s2Member\Auto_EOT_System | |
| 726 | + * @since 260820.0149 | |
| 727 | + * | |
| 728 | + * @param bool $force_refresh Force a fresh usermeta/schedule check. | |
| 729 | + * | |
| 730 | + * @return array Auto-EOT health information for diagnostics and UI. | |
| 731 | + */ | |
| 732 | + public static function auto_eot_system_health($force_refresh = FALSE) | |
| 733 | + { | |
| 734 | + global $wpdb; | |
| 735 | + /** @var $wpdb \wpdb */ | |
| 736 | + | |
| 737 | + $cache_key = 'ws_plugin__s2member_auto_eot_health'; | |
| 738 | + if(!$force_refresh && is_array($health = get_transient($cache_key))) | |
| 739 | + return $health; | |
| 740 | + | |
| 741 | + $now = time(); | |
| 742 | + $mode = (string)$GLOBALS['WS_PLUGIN__']['s2member']['o']['auto_eot_system_enabled']; | |
| 743 | + $state = get_option('ws_plugin__s2member_auto_eot_state'); | |
| 744 | + $state = is_array($state) ? $state : array(); | |
| 745 | + $lock = get_option('ws_plugin__s2member_auto_eot_lock'); | |
| 746 | + $lock = is_array($lock) ? $lock : array(); | |
| 747 | + $meta_key = $wpdb->prefix.'s2member_auto_eot_time'; | |
| 748 | + | |
| 749 | + //260820.0149 One exact-meta-key aggregate supplies both pending volume and oldest overdue age without loading EOT rows into PHP. | |
| 750 | + $pending = $wpdb->get_row($wpdb->prepare("SELECT COUNT(*) AS `pending_count`, MIN(CAST(`meta_value` AS UNSIGNED)) AS `oldest_due_at` FROM `".$wpdb->usermeta."` WHERE `meta_key` = %s AND CAST(`meta_value` AS UNSIGNED) > 0 AND CAST(`meta_value` AS UNSIGNED) <= %d", $meta_key, $now)); | |
| 751 | + $pending_count = ($pending && !empty($pending->pending_count)) ? (int)$pending->pending_count : 0; | |
| 752 | + $oldest_due_at = ($pending && !empty($pending->oldest_due_at)) ? (int)$pending->oldest_due_at : 0; | |
| 753 | + $oldest_overdue_seconds = $oldest_due_at ? max(0, $now - $oldest_due_at) : 0; | |
| 754 | + | |
| 755 | + $recurring_at = ($mode === '1' && function_exists('wp_cron')) ? wp_next_scheduled('ws_plugin__s2member_auto_eot_system__schedule') : FALSE; | |
| 756 | + $continuation_at = ($mode === '1' && function_exists('wp_cron')) ? wp_next_scheduled('ws_plugin__s2member_auto_eot_system__continuation') : FALSE; | |
| 757 | + $issues = array(); | |
| 758 | + $critical = FALSE; | |
| 759 | + $last_completed_at = !empty($state['last_completed_at']) ? (int)$state['last_completed_at'] : 0; | |
| 760 | + $last_processed = isset($state['last_processed']) ? (int)$state['last_processed'] : 0; | |
| 761 | + $last_more_due_work = !empty($state['last_more_due_work']); | |
| 762 | + $runtime_budget = self::auto_eot_system_runtime_budget($mode === '2'); | |
| 763 | + $lock_stale_after = max(120, (int)ceil(($runtime_budget * 2) + 30)); | |
| 764 | + //260823.0021 A lock means active processing only while its heartbeat is inside the same stale window used by the worker; an abandoned lock must not mask health as current work. | |
| 765 | + $is_running = !empty($lock['heartbeat_at']) && $now - (int)$lock['heartbeat_at'] <= $lock_stale_after; | |
| 766 | + $catchup_fresh_after = ($mode === '2') ? 2 * HOUR_IN_SECONDS : 30 * MINUTE_IN_SECONDS; | |
| 767 | + //260822.0614 Catch-up is ordinary queue progress, not a separate incident: report it only while a recent productive pass says more due work remains. | |
| 768 | + $catching_up = $pending_count && $last_more_due_work && $last_processed > 0 && $last_completed_at && $now - $last_completed_at < $catchup_fresh_after; | |
| 769 | + | |
| 770 | + //260820.0149 Escalate scheduler failures independently of pending EOTs so a broken cron can be noticed before months of expirations accumulate. | |
| 771 | + if($mode === '1') | |
| 772 | + { | |
| 773 | + if(!function_exists('wp_cron') || !$recurring_at) | |
| 774 | + $issues['cron_missing'] = $critical = TRUE; | |
| 775 | + else if((int)$recurring_at < $now - HOUR_IN_SECONDS) | |
| 776 | + //260908.2031 An overdue WP-Cron event can be normal on a quiet site; keep it visible as Attention, while missing cron or an actual overdue EOT backlog remain critical. | |
| 777 | + $issues['cron_overdue'] = TRUE; | |
| 778 | + } | |
| 779 | + else if($mode === '2' && !empty($state['last_external_completed_at']) && $now - (int)$state['last_external_completed_at'] >= 2 * HOUR_IN_SECONDS) | |
| 780 | + $issues['external_cron_stale'] = $critical = TRUE; | |
| 781 | + | |
| 782 | + if(($mode === '1' || $mode === '2') && $pending_count) | |
| 783 | + { | |
| 784 | + if($catching_up) | |
| 785 | + $issues['catching_up'] = TRUE; | |
| 786 | + else if($oldest_overdue_seconds >= 2 * HOUR_IN_SECONDS) | |
| 787 | + $issues['eot_overdue'] = $critical = TRUE; | |
| 788 | + else if($oldest_overdue_seconds >= 30 * MINUTE_IN_SECONDS) | |
| 789 | + $issues['eot_delayed'] = TRUE; | |
| 790 | + } | |
| 791 | + | |
| 792 | + $consecutive_abandoned = !empty($state['consecutive_abandoned_runs']) ? (int)$state['consecutive_abandoned_runs'] : 0; | |
| 793 | + if(($mode === '1' || $mode === '2') && $consecutive_abandoned >= 2) | |
| 794 | + $issues['repeated_abandoned'] = $critical = TRUE; | |
| 795 | + else if(($mode === '1' || $mode === '2') && $consecutive_abandoned === 1) | |
| 796 | + $issues['abandoned'] = TRUE; | |
| 797 | + | |
| 798 | + $health = array( | |
| 799 | + 'generated_at' => $now, | |
| 800 | + 'mode' => $mode, | |
| 801 | + 'status' => !$mode ? 'disabled' : ($critical ? 'error' : ($is_running ? 'processing' : (isset($issues['catching_up']) && count($issues) === 1 ? 'catching_up' : ($issues ? 'attention' : 'healthy')))), | |
| 802 | + 'needs_admin_notice' => $critical ? 1 : 0, | |
| 803 | + 'issues' => array_keys($issues), | |
| 804 | + 'pending_count' => $pending_count, | |
| 805 | + 'oldest_due_at' => $oldest_due_at, | |
| 806 | + 'oldest_overdue_seconds' => $oldest_overdue_seconds, | |
| 807 | + 'recurring_at' => $recurring_at ? (int)$recurring_at : 0, | |
| 808 | + 'continuation_at' => $continuation_at ? (int)$continuation_at : 0, | |
| 809 | + 'is_running' => $is_running ? 1 : 0, | |
| 810 | + 'last_started_at' => !empty($state['last_started_at']) ? (int)$state['last_started_at'] : 0, | |
| 811 | + 'last_completed_at' => $last_completed_at, | |
| 812 | + 'last_runtime' => isset($state['last_runtime']) ? (float)$state['last_runtime'] : 0.0, | |
| 813 | + 'last_processed' => $last_processed, | |
| 814 | + 'last_more_due_work' => $last_more_due_work ? 1 : 0, | |
| 815 | + 'last_stop_reason' => !empty($state['last_stop_reason']) ? (string)$state['last_stop_reason'] : '', | |
| 816 | + 'last_abandoned_at' => !empty($state['last_abandoned_at']) ? (int)$state['last_abandoned_at'] : 0, | |
| 817 | + 'consecutive_abandoned_runs' => $consecutive_abandoned, | |
| 818 | + 'last_schedule_failure_at' => !empty($state['last_schedule_failure_at']) ? (int)$state['last_schedule_failure_at'] : 0, | |
| 819 | + 'schedule_failure_count' => !empty($state['schedule_failure_count']) ? (int)$state['schedule_failure_count'] : 0, | |
| 820 | + 'last_external_completed_at' => !empty($state['last_external_completed_at']) ? (int)$state['last_external_completed_at'] : 0, | |
| 821 | + ); | |
| 822 | + $health = apply_filters('ws_plugin__s2member_auto_eot_system_health', $health, get_defined_vars()); | |
| 823 | + | |
| 824 | + //260820.0149 Cache the admin-facing aggregate briefly; processing itself never relies on this snapshot. | |
| 825 | + set_transient($cache_key, $health, 5 * MINUTE_IN_SECONDS); | |
| 826 | + | |
| 827 | + return $health; | |
| 828 | + } | |
| 829 | + | |
| 830 | + /** | |
| 831 | + * Displays a site-wide administrative warning when Auto-EOT health becomes materially unsafe. | |
| 832 | + * | |
| 833 | + * @package s2Member\Auto_EOT_System | |
| 834 | + * @since 260820.0149 | |
| 835 | + * | |
| 836 | + * @return null | |
| 837 | + */ | |
| 838 | + public static function auto_eot_system_admin_notice() | |
| 839 | + { | |
| 840 | + if(!is_admin() || !current_user_can('manage_options')) | |
| 841 | + return; | |
| 842 | + | |
| 843 | + $health = self::auto_eot_system_health(); | |
| 844 | + if(empty($health['needs_admin_notice'])) | |
| 845 | + return; | |
| 846 | + | |
| 847 | + $reasons = array(); | |
| 848 | + if(in_array('cron_missing', $health['issues'], TRUE)) | |
| 849 | + $reasons[] = 'The recurring WP-Cron event is missing and s2Member could not restore it.'; | |
| 850 | + if(in_array('cron_overdue', $health['issues'], TRUE)) | |
| 851 | + $reasons[] = 'The recurring WP-Cron event is more than an hour overdue.'; | |
| 852 | + if(in_array('external_cron_stale', $health['issues'], TRUE)) | |
| 853 | + $reasons[] = 'The configured external cron has not completed an Auto-EOT pass in more than two hours.'; | |
| 854 | + if(in_array('eot_overdue', $health['issues'], TRUE)) | |
| 855 | + $reasons[] = number_format_i18n($health['pending_count']).' End-of-Term action'.($health['pending_count'] === 1 ? ' is' : 's are').' pending; the oldest has been overdue for '.human_time_diff($health['oldest_due_at'], time()).'.'; | |
| 856 | + if(in_array('repeated_abandoned', $health['issues'], TRUE)) | |
| 857 | + $reasons[] = number_format_i18n($health['consecutive_abandoned_runs']).' consecutive Automatic End-of-Term workers ended without reaching normal completion.'; | |
| 858 | + | |
| 859 | + //260908.2031 Open the collapsed EOT panel before scrolling to its setting; a hash alone targets a hidden control. | |
| 860 | + $settings_url = admin_url('/admin.php?page=ws-plugin--s2member-paypal-ops&s2member-open-panel=auto-eot').'#ws-plugin--s2member-auto-eot-system-enabled'; | |
| 861 | + $notice = '<strong>s2Member Automatic End-of-Term needs attention.</strong> '.esc_html(implode(' ', $reasons)).' <a href="'.esc_url($settings_url).'">Review Automatic End-of-Term settings</a>.'; | |
| 862 | + c_ws_plugin__s2member_admin_notices::display_admin_notice($notice, TRUE); | |
| 863 | + } | |
| 864 | + | |
| 865 | + /** | |
| 866 | + * Runs an Auto-EOT catch-up continuation. | |
| 867 | + * | |
| 868 | + * Catch-up passes drain overdue EOTs promptly while remaining separate from the historical | |
| 869 | + * collective after-hook, so Pro reminder/gateway polling is not multiplied during catch-up. | |
| 870 | + * | |
| 871 | + * @package s2Member\Auto_EOT_System | |
| 872 | + * @since 260820.0056 | |
| 873 | + * | |
| 874 | + * @return null | |
| 875 | + */ | |
| 876 | + public static function auto_eot_system_continuation() | |
| 877 | + { | |
| 878 | + self::auto_eot_system(10, TRUE); | |
| 879 | + } | |
| 880 | + | |
| 881 | + | |
| 882 | + /** | |
| 84 | 883 | * Processed by WP_Cron; this handles Auto-EOTs *(EOT = End Of Term)*. |
| 85 | 884 | * |
| 86 | - * If you have a HUGE userbase, increase the max EOTs per process. | |
| 87 | - * But NOTE, this runs ``$per_process`` *(per Blog)* on a Multisite Network. | |
| 88 | - * To increase, use: ``add_filter ('ws_plugin__s2member_auto_eot_system_per_process');``. | |
| 885 | + * Normal processing is runtime-adaptive. The historical `$per_process` argument/filter remains | |
| 886 | + * available as a legacy hard item cap when a caller supplies it explicitly or a filter is attached. | |
| 89 | 887 | * |
| 90 | 888 | * This function makes an important Hook available: `ws_plugin__s2member_after_auto_eot_system`. |
| 91 | 889 | * This Hook is used by some of s2Member Pro's Gateway integrations; allowing CRON processing |
| 92 | 890 | * to run for important communications; which poll Payment Gateway APIs for possible EOTs. |
| 891 | + * Internal catch-up continuations intentionally do not fire that collective after-hook. | |
| 93 | 892 | * |
| 893 | + * 260821.0626 `ws_plugin__s2member_auto_eot_lock` is a short-lived non-autoloaded option containing | |
| 894 | + * `token`, `started_at`, `heartbeat_at`, `processed`, and `current_user_id`. Timestamps are Unix timestamps; | |
| 895 | + * counters/IDs are integers. A surviving stale lock is evidence that a worker did not reach normal cleanup. | |
| 896 | + * | |
| 897 | + * `ws_plugin__s2member_auto_eot_state` is non-autoloaded operational state. Fields are added when relevant: | |
| 898 | + * - Run: `last_started_at`, `active_run_token`, `last_completed_at`, `last_runtime`, `last_runtime_budget`, | |
| 899 | + * `last_processed`, `last_stop_reason`, `last_invocation`, `last_external_completed_at`. | |
| 900 | + * Stop reasons are `queue_empty`, `runtime_budget`, or `legacy_item_cap`; invocation is `continuation`, | |
| 901 | + * `external_cron`, `wp_cron`, or `direct`. | |
| 902 | + * - Pending work: `last_more_due_work`, `last_pending_count`, `last_oldest_due_at`, `last_oldest_overdue_seconds`. | |
| 903 | + * - Legacy cap: `last_hard_cap` (int|null), `last_hard_cap_source` (`filter` or `explicit`), | |
| 904 | + * `legacy_cap_estimated_additional`. | |
| 905 | + * - Abandoned run: `last_abandoned_at`, `last_abandoned_started_at`, `last_abandoned_heartbeat_at`, | |
| 906 | + * `last_abandoned_processed`, `last_abandoned_user_id`, `consecutive_abandoned_runs`. | |
| 907 | + * - Scheduler repair: `last_schedule_repaired_at`, `last_schedule_failure_at`, `schedule_failure_count`. | |
| 908 | + * 260822.0614 Catch-up health is derived from ordinary pending/run state; there is no separate incident, cutoff, | |
| 909 | + * backlog audit, or review-role state that can change how overdue users are processed. | |
| 910 | + * Performance timing is descriptive for the last pass only; it is never persistent runtime-learning input. | |
| 911 | + * | |
| 94 | 912 | * @package s2Member\Auto_EOT_System |
| 95 | 913 | * @since 3.5 |
| 96 | 914 | * |
| 97 | - * @param int $per_process Number of database records to process each time. | |
| 98 | - * Can also be Filtered with `ws_plugin__s2member_auto_eot_system_per_process`. | |
| 915 | + * @param int $per_process Legacy maximum database records to process in this pass when explicitly supplied or filtered. | |
| 916 | + * @param bool $is_continuation Internal catch-up continuation; skips the collective after-hook. | |
| 99 | 917 | * |
| 100 | 918 | * @return null |
| 101 | 919 | */ |
| 102 | - public static function auto_eot_system($per_process = 6) | |
| 920 | + public static function auto_eot_system($per_process = 10, $is_continuation = FALSE) | |
| 103 | 921 | { |
| 104 | 922 | global $wpdb; |
| 105 | 923 | /** @var $wpdb \wpdb */ |
| 106 | 924 | global $current_site, $current_blog; |
| @@ -106,9 +924,9 @@ | ||
| 106 | 924 | global $current_site, $current_blog; |
| 107 | 925 | |
| 108 | 926 | include_once ABSPATH.'wp-admin/includes/admin.php'; |
| 109 | 927 | |
| 110 | - @set_time_limit(0); // Make time for processing a larger userbase. | |
| 928 | + //260820.0056 Do not disable PHP's execution limit here; the adaptive engine deliberately works inside a measured wall-clock budget. | |
| 111 | 929 | @ini_set('memory_limit', apply_filters('admin_memory_limit', WP_MAX_MEMORY_LIMIT)); |
| 112 | 930 | |
| 113 | 931 | foreach(array_keys(get_defined_vars()) as $__v) $__refs[$__v] =& $$__v; |
| 114 | 932 | do_action('ws_plugin__s2member_before_auto_eot_system', get_defined_vars()); |
| @@ -113,22 +931,166 @@ | ||
| 113 | 931 | foreach(array_keys(get_defined_vars()) as $__v) $__refs[$__v] =& $$__v; |
| 114 | 932 | do_action('ws_plugin__s2member_before_auto_eot_system', get_defined_vars()); |
| 115 | 933 | unset($__refs, $__v); // Housekeeping. |
| 116 | 934 | |
| 935 | + //260823.0421 !!! TO-DO: Revisit disabled Auto-EOT lifecycle semantics. Consider archiving an elapsed current EOT as Last EOT with an explicit skip/no-change outcome while leaving membership access untouched, instead of keeping it pending for later demotion/deletion when processing is re-enabled. This requires a safe lifecycle trigger while the action worker is disabled and must preserve reminder/provenance history correctly. | |
| 117 | 936 | if($GLOBALS['WS_PLUGIN__']['s2member']['o']['auto_eot_system_enabled'] /* Enabled? */) |
| 118 | 937 | { |
| 938 | + //260820.0056 Count the budget from the request start, not merely this callback, so WordPress bootstrap/earlier cron work consumes its share too. | |
| 939 | + $runtime_budget = self::auto_eot_system_runtime_budget(); | |
| 940 | + $request_started = isset($_SERVER['REQUEST_TIME_FLOAT']) && is_numeric($_SERVER['REQUEST_TIME_FLOAT']) ? (float)$_SERVER['REQUEST_TIME_FLOAT'] : microtime(TRUE); | |
| 941 | + $run_started = microtime(TRUE); | |
| 942 | + $deadline = $request_started + $runtime_budget; | |
| 943 | + | |
| 944 | + //260820.0056 Reserve padding beyond the predicted next user's cost; cap that reserve at 25% so short runtime budgets still retain useful processing time. | |
| 945 | + $safety_buffer = min($runtime_budget * 0.25, max(0.25, (float)apply_filters('ws_plugin__s2member_auto_eot_system_runtime_safety_buffer', 1.0, get_defined_vars()))); | |
| 946 | + | |
| 947 | + //260820.0056 A small non-autoloaded lock detects overlap and leaves evidence when a worker dies before reaching normal cleanup. | |
| 948 | + $run_token = function_exists('wp_generate_uuid4') ? wp_generate_uuid4() : uniqid('s2-eot-', TRUE); | |
| 949 | + $lock_option = 'ws_plugin__s2member_auto_eot_lock'; | |
| 950 | + $state_option = 'ws_plugin__s2member_auto_eot_state'; | |
| 951 | + $lock_stale_after = max(120, (int)ceil(($runtime_budget * 2) + 30)); | |
| 952 | + $existing_lock = get_option($lock_option); | |
| 953 | + | |
| 954 | + //260820.0149 Discard malformed leftover state before evaluating whether another worker is active. | |
| 955 | + if($existing_lock !== FALSE && (!is_array($existing_lock) || empty($existing_lock['heartbeat_at']))) | |
| 956 | + { | |
| 957 | + delete_option($lock_option); | |
| 958 | + delete_transient('ws_plugin__s2member_auto_eot_health'); | |
| 959 | + $existing_lock = FALSE; | |
| 960 | + } | |
| 961 | + | |
| 962 | + //260820.0056 A stale marker means the previous process never reached cleanup; preserve the useful evidence without guessing whether it was timeout, OOM, fatal error, etc. | |
| 963 | + if(is_array($existing_lock) && !empty($existing_lock['heartbeat_at']) && time() - (int)$existing_lock['heartbeat_at'] > $lock_stale_after) | |
| 964 | + { | |
| 965 | + $state = get_option($state_option); | |
| 966 | + $state = is_array($state) ? $state : array(); | |
| 967 | + $state['last_abandoned_at'] = time(); | |
| 968 | + $state['last_abandoned_started_at'] = !empty($existing_lock['started_at']) ? (int)$existing_lock['started_at'] : 0; | |
| 969 | + $state['last_abandoned_heartbeat_at'] = !empty($existing_lock['heartbeat_at']) ? (int)$existing_lock['heartbeat_at'] : 0; | |
| 970 | + $state['last_abandoned_processed'] = !empty($existing_lock['processed']) ? (int)$existing_lock['processed'] : 0; | |
| 971 | + $state['last_abandoned_user_id'] = !empty($existing_lock['current_user_id']) ? (int)$existing_lock['current_user_id'] : 0; | |
| 972 | + $state['consecutive_abandoned_runs'] = !empty($state['consecutive_abandoned_runs']) ? (int)$state['consecutive_abandoned_runs'] + 1 : 1; | |
| 973 | + update_option($state_option, $state, FALSE); | |
| 974 | + delete_option($lock_option); | |
| 975 | + delete_transient('ws_plugin__s2member_auto_eot_health'); | |
| 976 | + $existing_lock = FALSE; | |
| 977 | + } | |
| 978 | + | |
| 979 | + //260820.0056 A fresh marker belongs to another worker that should still be alive; never process the same overdue population concurrently. | |
| 980 | + if(is_array($existing_lock) && !empty($existing_lock['heartbeat_at'])) | |
| 981 | + return; | |
| 982 | + | |
| 983 | + //260820.0056 Use add_option() for lock acquisition so two workers racing here cannot both believe they acquired it. | |
| 984 | + $lock = array('token' => $run_token, 'started_at' => time(), 'heartbeat_at' => time(), 'processed' => 0, 'current_user_id' => 0); | |
| 985 | + if(!add_option($lock_option, $lock, '', FALSE)) | |
| 986 | + return; // Another worker acquired the lock between our read and add. | |
| 987 | + | |
| 988 | + //260820.0056 Persist only operational health between runs; performance timing remains local to each pass so it adapts organically to current conditions. | |
| 989 | + $state = get_option($state_option); | |
| 990 | + $state = is_array($state) ? $state : array(); | |
| 991 | + $state['last_started_at'] = time(); | |
| 992 | + $state['active_run_token'] = $run_token; | |
| 993 | + update_option($state_option, $state, FALSE); | |
| 994 | + delete_transient('ws_plugin__s2member_auto_eot_health'); //260820.0149 Invalidate any cached pre-run status. | |
| 995 | + | |
| 996 | + //260820.0056 The historical count becomes a hard cap only when code explicitly supplies/filters it; the untouched default no longer throttles normal installations. | |
| 997 | + $per_process_filter_attached = has_filter('ws_plugin__s2member_auto_eot_system_per_process') !== FALSE; | |
| 998 | + $per_process_was_explicit = func_num_args() > 0 && !$is_continuation; | |
| 119 | 999 | $per_process = apply_filters('ws_plugin__s2member_auto_eot_system_per_process', $per_process, get_defined_vars()); |
| 1000 | + $hard_cap = ($per_process_filter_attached || $per_process_was_explicit) ? max(0, (int)$per_process) : NULL; | |
| 1001 | + $hard_cap_source = $per_process_filter_attached ? 'filter' : ($per_process_was_explicit ? 'explicit' : ''); | |
| 120 | 1002 | |
| 121 | - //260414 Ignore zero/negative Auto-EOT values here. We had real PayPal Pro subscribers demoted | |
| 122 | - // because a stored `s2member_auto_eot_time` of `0` matched the old `<= now` query. | |
| 123 | - if(is_array($eots = $wpdb->get_results("SELECT `user_id` AS `ID` FROM `".$wpdb->usermeta."` WHERE `meta_key` = '".$wpdb->prefix."s2member_auto_eot_time' AND `meta_value` != '' AND `meta_value` > '0' AND `meta_value` <= '".esc_sql(strtotime("now"))."' LIMIT ".$per_process))) | |
| 1003 | + //260820.0056 Fetch modest ordered chunks from MySQL; 100 is only a query-buffer size, never the normal processing throttle. | |
| 1004 | + $chunk_size = 100; | |
| 1005 | + $processed_count = 0; | |
| 1006 | + $item_total_duration = 0.0; | |
| 1007 | + $last_item_duration = 0.0; | |
| 1008 | + $last_heartbeat = microtime(TRUE); | |
| 1009 | + $cursor_time = 0; | |
| 1010 | + $cursor_umeta_id = 0; | |
| 1011 | + $stop_reason = 'queue_empty'; | |
| 1012 | + $meta_key = $wpdb->prefix.'s2member_auto_eot_time'; | |
| 1013 | + | |
| 1014 | + while(TRUE) | |
| 124 | 1015 | { |
| 125 | - foreach($eots as $eot) // Go through the array of EOTS. We need to (demote|delete) each of them. | |
| 1016 | + //260820.0056 Honor an intentional legacy ceiling before doing another query or user operation. | |
| 1017 | + if($hard_cap !== NULL && $processed_count >= $hard_cap) | |
| 126 | 1018 | { |
| 127 | - if(($user_id = $eot->ID) && is_object($user = new WP_User ($user_id)) && $user->ID) | |
| 1019 | + $stop_reason = 'legacy_item_cap'; | |
| 1020 | + break; | |
| 1021 | + } | |
| 1022 | + | |
| 1023 | + //260820.0056 Near the deadline, use only this run's last/average item times to decide whether another EOT is likely to fit safely. | |
| 1024 | + $remaining_runtime = $deadline - microtime(TRUE); | |
| 1025 | + $average_item_duration = $processed_count ? $item_total_duration / $processed_count : 0.0; | |
| 1026 | + $estimated_next_duration = max($last_item_duration, $average_item_duration); | |
| 1027 | + if($remaining_runtime <= $safety_buffer + $estimated_next_duration) | |
| 1028 | + { | |
| 1029 | + $stop_reason = 'runtime_budget'; | |
| 1030 | + break; | |
| 1031 | + } | |
| 1032 | + | |
| 1033 | + //260820.0056 A legacy hard cap may make the final SQL chunk smaller, but otherwise query size and processing capacity remain independent. | |
| 1034 | + $query_limit = $chunk_size; | |
| 1035 | + if($hard_cap !== NULL) | |
| 1036 | + $query_limit = min($query_limit, max(0, $hard_cap - $processed_count)); | |
| 1037 | + if($query_limit < 1) | |
| 1038 | + { | |
| 1039 | + $stop_reason = 'legacy_item_cap'; | |
| 1040 | + break; | |
| 1041 | + } | |
| 1042 | + | |
| 1043 | + //260820.0056 Query only due EOT metadata, oldest timestamp first; `umeta_id` makes equal timestamps deterministic and provides cursor pagination without OFFSET. | |
| 1044 | + $now = time(); | |
| 1045 | + $sql = "SELECT `umeta_id`, `user_id` AS `ID`, CAST(`meta_value` AS UNSIGNED) AS `auto_eot_time` FROM `".$wpdb->usermeta."` WHERE `meta_key` = %s AND CAST(`meta_value` AS UNSIGNED) > 0 AND CAST(`meta_value` AS UNSIGNED) <= %d"; | |
| 1046 | + $sql_args = array($meta_key, $now); | |
| 1047 | + | |
| 1048 | + //260820.0056 Continue strictly after the previous timestamp/umeta_id pair, avoiding increasingly expensive SQL OFFSET pagination. | |
| 1049 | + if($cursor_time || $cursor_umeta_id) | |
| 1050 | + { | |
| 1051 | + $sql .= " AND (CAST(`meta_value` AS UNSIGNED) > %d OR (CAST(`meta_value` AS UNSIGNED) = %d AND `umeta_id` > %d))"; | |
| 1052 | + $sql_args[] = $cursor_time; | |
| 1053 | + $sql_args[] = $cursor_time; | |
| 1054 | + $sql_args[] = $cursor_umeta_id; | |
| 1055 | + } | |
| 1056 | + $sql .= " ORDER BY CAST(`meta_value` AS UNSIGNED) ASC, `umeta_id` ASC LIMIT ".(int)$query_limit; | |
| 1057 | + $eots = $wpdb->get_results($wpdb->prepare($sql, $sql_args)); | |
| 1058 | + | |
| 1059 | + if(!is_array($eots) || !$eots) | |
| 1060 | + break; | |
| 1061 | + | |
| 1062 | + foreach($eots as $eot) // Oldest overdue EOT first; equal timestamps are deterministic by `umeta_id`. | |
| 1063 | + { | |
| 1064 | + $cursor_time = (int)$eot->auto_eot_time; | |
| 1065 | + $cursor_umeta_id = (int)$eot->umeta_id; | |
| 1066 | + | |
| 1067 | + //260820.0056 Recheck both stopping conditions inside the chunk because each user's hooks/notifications can materially change elapsed time. | |
| 1068 | + if($hard_cap !== NULL && $processed_count >= $hard_cap) | |
| 128 | 1069 | { |
| 129 | - $auto_eot_time = (integer)get_user_option('s2member_auto_eot_time', $user_id); | |
| 1070 | + $stop_reason = 'legacy_item_cap'; | |
| 1071 | + break 2; | |
| 1072 | + } | |
| 1073 | + $remaining_runtime = $deadline - microtime(TRUE); | |
| 1074 | + $average_item_duration = $processed_count ? $item_total_duration / $processed_count : 0.0; | |
| 1075 | + $estimated_next_duration = max($last_item_duration, $average_item_duration); | |
| 1076 | + if($remaining_runtime <= $safety_buffer + $estimated_next_duration) | |
| 1077 | + { | |
| 1078 | + $stop_reason = 'runtime_budget'; | |
| 1079 | + break 2; | |
| 1080 | + } | |
| 130 | 1081 | |
| 1082 | + //260820.0056 Re-read only the exact selected row immediately before destructive work; skip it if its EOT was changed/deleted after selection. | |
| 1083 | + $current_eot = $wpdb->get_row($wpdb->prepare("SELECT `user_id`, `meta_key`, `meta_value` FROM `".$wpdb->usermeta."` WHERE `umeta_id` = %d LIMIT 1", $cursor_umeta_id)); | |
| 1084 | + if(!$current_eot || (int)$current_eot->user_id !== (int)$eot->ID || (string)$current_eot->meta_key !== $meta_key || (int)$current_eot->meta_value !== $cursor_time || (int)$current_eot->meta_value <= 0 || (int)$current_eot->meta_value > time()) | |
| 1085 | + continue; | |
| 1086 | + | |
| 1087 | + //260820.0056 Time the complete per-user EOT operation, including hooks/notifications, because extension work may dominate the actual cost. | |
| 1088 | + $item_started = microtime(TRUE); | |
| 1089 | + $user_id = (int)$eot->ID; | |
| 1090 | + $auto_eot_time = (int)$current_eot->meta_value; | |
| 1091 | + if($user_id && is_object($user = new WP_User ($user_id)) && $user->ID) | |
| 1092 | + { | |
| 131 | 1093 | $log_entry = array('user' => (array)$user); // Intialize. |
| 132 | 1094 | $log_entry['auto_eot_time'] = $auto_eot_time; // Record EOT time. |
| 133 | 1095 | |
| 134 | 1096 | //260414 Keep a minimal pre-demotion subscription snapshot in the log so we can tell later |
| @@ -145,10 +1107,20 @@ | ||
| 145 | 1107 | c_ws_plugin__s2member_utils_logs::log_entry('auto-eot-system', $log_entry); |
| 146 | 1108 | continue; |
| 147 | 1109 | } |
| 148 | 1110 | |
| 1111 | + //260821.0626 `s2member_auto_eot_details` and `s2member_last_auto_eot_details` share the provenance format | |
| 1112 | + // `array('time' => EOT Unix timestamp, 'source' => string, 'updated_at' => Unix timestamp)`. `time` must | |
| 1113 | + // exactly match the corresponding current/archived EOT; otherwise the details are stale and ignored. | |
| 1114 | + // `source` currently uses `refund_reversal` for payment exceptions that must not be treated as renewal opportunities. | |
| 1115 | + $auto_eot_details = get_user_option('s2member_auto_eot_details', $user_id); | |
| 1116 | + if(!is_array($auto_eot_details) || empty($auto_eot_details['time']) || (int)$auto_eot_details['time'] !== $auto_eot_time) | |
| 1117 | + $auto_eot_details = array(); | |
| 1118 | + | |
| 149 | 1119 | delete_user_option($user_id, 's2member_last_auto_eot_time'); |
| 1120 | + delete_user_option($user_id, 's2member_last_auto_eot_details'); | |
| 150 | 1121 | delete_user_option($user_id, 's2member_auto_eot_time'); |
| 1122 | + delete_user_option($user_id, 's2member_auto_eot_details'); | |
| 151 | 1123 | |
| 152 | 1124 | if(!$user->has_cap('administrator') /* Do NOT process Administrator accounts. */) |
| 153 | 1125 | { |
| 154 | 1126 | if($GLOBALS['WS_PLUGIN__']['s2member']['o']['membership_eot_behavior'] === 'demote') |
| @@ -166,8 +1138,9 @@ | ||
| 166 | 1138 | $ipn_signup_vars = get_user_option('s2member_ipn_signup_vars', $user_id); |
| 167 | 1139 | |
| 168 | 1140 | $demotion_role = c_ws_plugin__s2member_option_forces::force_demotion_role('subscriber'); |
| 169 | 1141 | $existing_role = c_ws_plugin__s2member_user_access::user_access_role($user); |
| 1142 | + $removed_ccaps = array(); | |
| 170 | 1143 | |
| 171 | 1144 | foreach(array_keys(get_defined_vars()) as $__v) $__refs[$__v] =& $$__v; |
| 172 | 1145 | do_action('ws_plugin__s2member_during_auto_eot_system_during_before_demote', get_defined_vars()); |
| 173 | 1146 | do_action('ws_plugin__s2member_during_collective_mods', $user_id, get_defined_vars(), $eot_del_type, 'modification', $demotion_role); |
| @@ -173,15 +1146,18 @@ | ||
| 173 | 1146 | do_action('ws_plugin__s2member_during_collective_mods', $user_id, get_defined_vars(), $eot_del_type, 'modification', $demotion_role); |
| 174 | 1147 | do_action('ws_plugin__s2member_during_collective_eots', $user_id, get_defined_vars(), $eot_del_type, 'modification'); |
| 175 | 1148 | unset($__refs, $__v); // Housekeeping. |
| 176 | 1149 | |
| 177 | - if($existing_role !== $demotion_role /* Only if NOT the existing Role. */) | |
| 178 | - $user->set_role($demotion_role /* Give User the demotion Role. */); | |
| 1150 | + //260916.2004 New installs replace only the s2Member Level role; upgraded sites retain legacy all-role replacement until the administrator changes it. | |
| 1151 | + $eot_membership_role = self::demote_user_roles($user, $demotion_role); | |
| 179 | 1152 | |
| 180 | 1153 | if(apply_filters('ws_plugin__s2member_remove_ccaps_during_eot_events', (bool)$GLOBALS['WS_PLUGIN__']['s2member']['o']['eots_remove_ccaps'], get_defined_vars())) |
| 181 | 1154 | foreach($user->allcaps as $cap => $cap_enabled) |
| 182 | 1155 | if(preg_match('/^access_s2member_ccap_/', $cap)) |
| 1156 | + { | |
| 1157 | + $removed_ccaps[] = preg_replace('/^access_s2member_ccap_/', '', $cap); | |
| 183 | 1158 | $user->remove_cap($ccap = $cap); |
| 1159 | + } | |
| 184 | 1160 | |
| 185 | 1161 | delete_user_option($user_id, 's2member_subscr_gateway'); |
| 186 | 1162 | delete_user_option($user_id, 's2member_subscr_id'); |
| 187 | 1163 | delete_user_option($user_id, 's2member_subscr_baid'); |
| @@ -194,18 +1170,31 @@ | ||
| 194 | 1170 | delete_user_option($user_id, 's2member_last_status_scan'); |
| 195 | 1171 | delete_user_option($user_id, 's2member_first_payment_txn_id'); |
| 196 | 1172 | delete_user_option($user_id, 's2member_last_payment_time'); |
| 197 | 1173 | delete_user_option($user_id, 's2member_last_auto_eot_time'); |
| 1174 | + delete_user_option($user_id, 's2member_last_auto_eot_details'); | |
| 198 | 1175 | delete_user_option($user_id, 's2member_auto_eot_time'); |
| 1176 | + delete_user_option($user_id, 's2member_auto_eot_details'); | |
| 199 | 1177 | |
| 200 | 1178 | delete_user_option($user_id, 's2member_file_download_access_log'); |
| 201 | 1179 | delete_user_option($user_id, 's2member_authnet_payment_failures'); |
| 202 | 1180 | |
| 1181 | + $processed_at = time(); | |
| 203 | 1182 | update_user_option($user_id, 's2member_last_auto_eot_time', $auto_eot_time); |
| 1183 | + //260821.0057 Preserve only matching provenance (e.g., refund/reversal) alongside the archived EOT. | |
| 1184 | + if($auto_eot_details) | |
| 1185 | + update_user_option($user_id, 's2member_last_auto_eot_details', $auto_eot_details); | |
| 204 | 1186 | |
| 205 | - c_ws_plugin__s2member_user_notes::append_user_notes($user_id, 'Demoted by s2Member: '.date('D M j, Y g:i a T')); | |
| 206 | - if($subscr_gateway && $subscr_id) // Also note the Paid Subscr. Gateway/ID so there is a reference left behind here. | |
| 207 | - c_ws_plugin__s2member_user_notes::append_user_notes($user_id, 'Paid Subscr. ID @ time of demotion: '.$subscr_gateway.' → '.$subscr_id); | |
| 1187 | + //260822.0653 Record the triggering EOT separately from when this worker actually completed the demotion, using the pre-cleanup role/payment snapshot above. | |
| 1188 | + self::record_eot_history($user_id, array( | |
| 1189 | + 'eot_time' => $auto_eot_time, | |
| 1190 | + 'processed_at' => $processed_at, | |
| 1191 | + 'original_role' => $eot_membership_role, | |
| 1192 | + 'destination_role' => $demotion_role, | |
| 1193 | + 'removed_ccaps' => $removed_ccaps, | |
| 1194 | + 'subscr_gateway' => $subscr_gateway, | |
| 1195 | + 'subscr_id' => $subscr_id, | |
| 1196 | + )); | |
| 208 | 1197 | |
| 209 | 1198 | if($GLOBALS['WS_PLUGIN__']['s2member']['o']['eot_del_notification_urls']) |
| 210 | 1199 | { |
| 211 | 1200 | foreach(preg_split('/['."\r\n\t".']+/', $GLOBALS['WS_PLUGIN__']['s2member']['o']['eot_del_notification_urls']) as $url) // Handle EOT Notifications. |
| @@ -288,10 +1277,10 @@ | ||
| 288 | 1277 | unset($__refs, $__v); // Housekeeping. |
| 289 | 1278 | } |
| 290 | 1279 | else if($GLOBALS['WS_PLUGIN__']['s2member']['o']['membership_eot_behavior'] === 'delete') |
| 291 | 1280 | { |
| 292 | - $eot_del_type = $GLOBALS['ws_plugin__s2member_eot_del_type'] = 'auto-eot-cancellation-expiration-deletion'; | |
| 293 | - $log_entry['eot_del_type'] = $eot_del_type; // Deleting user in this case. | |
| 1281 | + $eot_del_type = 'auto-eot-cancellation-expiration-deletion'; | |
| 1282 | + $log_entry['eot_del_type'] = $eot_del_type; | |
| 294 | 1283 | |
| 295 | 1284 | foreach(array_keys(get_defined_vars()) as $__v) $__refs[$__v] =& $$__v; |
| 296 | 1285 | do_action('ws_plugin__s2member_during_auto_eot_system_during_before_delete', get_defined_vars()); |
| 297 | 1286 | do_action('ws_plugin__s2member_during_collective_eots', $user_id, get_defined_vars(), $eot_del_type, 'removal-deletion'); |
| @@ -296,17 +1285,11 @@ | ||
| 296 | 1285 | do_action('ws_plugin__s2member_during_auto_eot_system_during_before_delete', get_defined_vars()); |
| 297 | 1286 | do_action('ws_plugin__s2member_during_collective_eots', $user_id, get_defined_vars(), $eot_del_type, 'removal-deletion'); |
| 298 | 1287 | unset($__refs, $__v); // Housekeeping. |
| 299 | 1288 | |
| 300 | - if(is_multisite()/* Multisite does NOT actually delete; ONLY removes. */) | |
| 301 | - { | |
| 302 | - remove_user_from_blog($user_id, $current_blog->blog_id); | |
| 303 | - // This will automatically trigger `eot_del_notification_urls`. | |
| 304 | - c_ws_plugin__s2member_user_deletions::handle_ms_user_deletions($user_id, $current_blog->blog_id, 's2says'); | |
| 305 | - } | |
| 306 | - else // Otherwise, we can actually delete them. | |
| 307 | - // This will automatically trigger `eot_del_notification_urls` | |
| 308 | - wp_delete_user($user_id /* `c_ws_plugin__s2member_user_deletions::handle_user_deletions()` */); | |
| 1289 | + //260822.0535 One operation now owns both safe Pending Deletion and the explicit developer opt-in for historical irreversible deletion. | |
| 1290 | + $eot_delete_action = self::process_eot_deletion($user_id, $eot_del_type, $auto_eot_time); | |
| 1291 | + $log_entry['eot_delete_action'] = $eot_delete_action; | |
| 309 | 1292 | |
| 310 | 1293 | foreach(array_keys(get_defined_vars()) as $__v) $__refs[$__v] =& $$__v; |
| 311 | 1294 | do_action('ws_plugin__s2member_during_auto_eot_system_during_delete', get_defined_vars()); |
| 312 | 1295 | unset($__refs, $__v); // Housekeeping. |
| @@ -316,16 +1299,95 @@ | ||
| 316 | 1299 | unset($__refs, $__v); // Housekeeping. |
| 317 | 1300 | |
| 318 | 1301 | c_ws_plugin__s2member_utils_logs::log_entry('auto-eot-system', $log_entry); |
| 319 | 1302 | } |
| 1303 | + | |
| 320 | 1304 | } |
| 1305 | + | |
| 1306 | + //260820.0056 Feed the completed item's wall-clock cost into this pass only; no timing average is persisted between runs. | |
| 1307 | + $last_item_duration = max(0, microtime(TRUE) - $item_started); | |
| 1308 | + $item_total_duration += $last_item_duration; | |
| 1309 | + $processed_count++; | |
| 1310 | + | |
| 1311 | + //260820.0056 Refresh the lock periodically rather than per user, preserving useful crash evidence without creating unnecessary option writes. | |
| 1312 | + if($processed_count % 5 === 0 || microtime(TRUE) - $last_heartbeat >= 5) | |
| 1313 | + { | |
| 1314 | + $lock['heartbeat_at'] = time(); | |
| 1315 | + $lock['processed'] = $processed_count; | |
| 1316 | + $lock['current_user_id'] = $user_id; | |
| 1317 | + update_option($lock_option, $lock, FALSE); | |
| 1318 | + $last_heartbeat = microtime(TRUE); | |
| 1319 | + } | |
| 321 | 1320 | } |
| 1321 | + | |
| 1322 | + //260820.0056 A short chunk means the ordered query reached the end of the due rows visible during this pass; otherwise fetch the next cursor chunk. | |
| 1323 | + if(count($eots) < $query_limit) | |
| 1324 | + break; | |
| 322 | 1325 | } |
| 1326 | + | |
| 1327 | + //260820.0149 One aggregate gives both catch-up state and the pending/oldest values needed by diagnostics. | |
| 1328 | + $run_runtime = max(0, microtime(TRUE) - $run_started); | |
| 1329 | + $pending = $wpdb->get_row($wpdb->prepare("SELECT COUNT(*) AS `pending_count`, MIN(CAST(`meta_value` AS UNSIGNED)) AS `oldest_due_at` FROM `".$wpdb->usermeta."` WHERE `meta_key` = %s AND CAST(`meta_value` AS UNSIGNED) > 0 AND CAST(`meta_value` AS UNSIGNED) <= %d", $meta_key, time())); | |
| 1330 | + $pending_count = ($pending && !empty($pending->pending_count)) ? (int)$pending->pending_count : 0; | |
| 1331 | + $oldest_due_at = ($pending && !empty($pending->oldest_due_at)) ? (int)$pending->oldest_due_at : 0; | |
| 1332 | + $more_due_work = $pending_count > 0; | |
| 1333 | + | |
| 1334 | + //260820.0056 Preserve enough current-run timing information to explain when a legacy item cap, rather than runtime, unnecessarily constrained throughput. | |
| 1335 | + $average_item_duration = $processed_count ? $item_total_duration / $processed_count : 0.0; | |
| 1336 | + $estimated_next_duration = max($last_item_duration, $average_item_duration); | |
| 1337 | + $remaining_safe_runtime = max(0, ($deadline - microtime(TRUE)) - $safety_buffer); | |
| 1338 | + $legacy_cap_estimated_additional = ($stop_reason === 'legacy_item_cap' && $more_due_work && $estimated_next_duration > 0) ? (int)floor($remaining_safe_runtime / $estimated_next_duration) : 0; | |
| 1339 | + | |
| 1340 | + //260820.0056 Save compact operational health for diagnostics/UI; these are run results, not persistent performance-learning values. | |
| 1341 | + $state = get_option($state_option); | |
| 1342 | + $state = is_array($state) ? $state : array(); | |
| 1343 | + $state['last_completed_at'] = time(); | |
| 1344 | + $state['last_runtime'] = $run_runtime; | |
| 1345 | + $state['last_runtime_budget'] = $runtime_budget; | |
| 1346 | + $state['last_processed'] = $processed_count; | |
| 1347 | + $state['last_stop_reason'] = $stop_reason; | |
| 1348 | + $state['last_hard_cap'] = $hard_cap; | |
| 1349 | + $state['last_hard_cap_source'] = $hard_cap_source; | |
| 1350 | + $state['last_more_due_work'] = $more_due_work ? 1 : 0; | |
| 1351 | + $state['last_pending_count'] = $pending_count; | |
| 1352 | + $state['last_oldest_due_at'] = $oldest_due_at; | |
| 1353 | + $state['last_oldest_overdue_seconds'] = $oldest_due_at ? max(0, time() - $oldest_due_at) : 0; | |
| 1354 | + $state['legacy_cap_estimated_additional'] = $legacy_cap_estimated_additional; | |
| 1355 | + $state['last_invocation'] = $is_continuation ? 'continuation' : (!empty($_GET['s2member_auto_eot_system_via_cron']) ? 'external_cron' : ((defined('DOING_CRON') && DOING_CRON) ? 'wp_cron' : 'direct')); | |
| 1356 | + if($state['last_invocation'] === 'external_cron') | |
| 1357 | + $state['last_external_completed_at'] = time(); | |
| 1358 | + $state['consecutive_abandoned_runs'] = 0; //260820.0149 A clean completion breaks the abandoned-run sequence. | |
| 1359 | + $state['active_run_token'] = ''; | |
| 1360 | + | |
| 1361 | + update_option($state_option, $state, FALSE); | |
| 1362 | + | |
| 1363 | + //260820.0056 Delete the lock only after state is safely recorded; if PHP dies earlier, the surviving lock is what lets a future pass detect the abandoned run. | |
| 1364 | + delete_option($lock_option); | |
| 1365 | + | |
| 1366 | + //260820.0056 In WP-Cron mode, continue soon while overdue EOTs remain; external-cron installations already control their own invocation cadence. | |
| 1367 | + if((string)$GLOBALS['WS_PLUGIN__']['s2member']['o']['auto_eot_system_enabled'] === '1' && $more_due_work && ($hard_cap === NULL || $hard_cap > 0)) | |
| 1368 | + { | |
| 1369 | + if(!wp_next_scheduled('ws_plugin__s2member_auto_eot_system__continuation')) | |
| 1370 | + wp_schedule_single_event(time() + 60, 'ws_plugin__s2member_auto_eot_system__continuation'); | |
| 1371 | + } | |
| 1372 | + else if(!$more_due_work) | |
| 1373 | + wp_clear_scheduled_hook('ws_plugin__s2member_auto_eot_system__continuation'); | |
| 1374 | + | |
| 1375 | + delete_transient('ws_plugin__s2member_auto_eot_health'); //260820.0149 Run completion changes the health snapshot. | |
| 323 | 1376 | } |
| 324 | 1377 | c_ws_plugin__s2member_utils_logs::cleanup_expired_s2m_transients(); |
| 325 | 1378 | |
| 326 | - foreach(array_keys(get_defined_vars()) as $__v) $__refs[$__v] =& $$__v; | |
| 327 | - do_action('ws_plugin__s2member_after_auto_eot_system', get_defined_vars()); | |
| 328 | - unset($__refs, $__v); // Housekeeping. | |
| 1379 | + //260820.0056 The historical collective after-hook runs only on normal passes; otherwise every one-minute catch-up pass would also multiply Pro reminders/gateway API polling. | |
| 1380 | + if(!$is_continuation) | |
| 1381 | + { | |
| 1382 | + foreach(array_keys(get_defined_vars()) as $__v) $__refs[$__v] =& $$__v; | |
| 1383 | + do_action('ws_plugin__s2member_after_auto_eot_system', get_defined_vars()); | |
| 1384 | + unset($__refs, $__v); // Housekeeping. | |
| 1385 | + } | |
| 1386 | + else | |
| 1387 | + { | |
| 1388 | + //260820.0056 Continuations still repair the recurring Auto-EOT event directly because they deliberately skip the collective after-hook that normally performs this check. | |
| 1389 | + self::ensure_auto_eot_system(); | |
| 1390 | + } | |
| 329 | 1391 | } |
| 330 | 1392 | } |
| 331 | 1393 | } |