PluginProbe
WCPOS – Point of Sale (POS) plugin for WooCommerce / 1.10.21
WCPOS – Point of Sale (POS) plugin for WooCommerce v1.10.21
1.10.22 1.10.21 1.10.20 1.10.19 1.10.18 1.10.17 1.10.16 1.10.15 1.10.13 1.10.14 1.10.12 1.10.11 1.10.10 1.10.9 1.10.8 untagged-3d9b7ccddc54df87c672 1.10.7 1.10.6 1.10.5 1.10.3 1.10.4 1.10.2 1.10.1 1.10.0 1.9.17 All 166 releases
woocommerce-pos / includes / Activator.php

Activator.php in WCPOS – Point of Sale (POS) plugin for WooCommerce 1.10.21, at includes/Activator.php

749 lines 26.8 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Activation checks and set up.
4 *
5 * @author Paul Kilmurray <[email protected]>
6 *
7 * @see http://wcpos.com
8 * @package WCPOS\WooCommercePOS
9 */
10
11 namespace WCPOS\WooCommercePOS;
12
13 use WCPOS\WooCommercePOS\Admin\Consent;
14 use WCPOS\WooCommercePOS\Services\Lifecycle_Events;
15 use WCPOS\WooCommercePOS\Sync\Api as Sync_Api;
16 use WCPOS\WooCommercePOS\Sync\Health as Sync_Health;
17 use WCPOS\WooCommercePOS\Sync\Integrity_Digest;
18 use WCPOS\WooCommercePOS\Sync\Mutation_Store;
19 use WCPOS\WooCommercePOS\Sync\Sync_Journal;
20 use const DOING_AJAX;
21
22 /**
23 * Activator class.
24 */
25 class Activator {
26 /**
27 * Lock name used by WP_Upgrader::create_lock().
28 */
29 private const DB_UPGRADE_LOCK_NAME = 'woocommerce_pos_db_upgrade_lock';
30
31 /**
32 * Lock TTL in seconds.
33 */
34 private const DB_UPGRADE_LOCK_TTL = 600;
35
36 /**
37 * Constructor.
38 */
39 public function __construct() {
40 register_activation_hook( PLUGIN_FILE, array( $this, 'activate' ) );
41 add_action( 'wpmu_new_blog', array( $this, 'activate_new_site' ) );
42 // The staff-account rule (#1918, #2104) must hold even when WooCommerce is
43 // inactive and Init never starts; it depends on nothing from WooCommerce.
44 add_filter( 'map_meta_cap', array( Services\Permission_Rules::class, 'map_user_meta_caps' ), 10, 4 );
45 add_action( 'plugins_loaded', array( $this, 'init' ) );
46 }
47
48 /**
49 * Checks for valid install and begins execution of the plugin.
50 */
51 public function init(): void {
52 // Check for min requirements to run.
53 if ( $this->php_check() && $this->woocommerce_check() ) {
54 // Defer permalink check to admin_init so __() calls happen after
55 // after_setup_theme (WordPress 6.7+ triggers a notice otherwise).
56 if ( is_admin() && ( ! \defined( '\DOING_AJAX' ) || ! DOING_AJAX ) ) { // @phpstan-ignore-line
57 add_action(
58 'admin_init',
59 function () {
60 $this->permalink_check();
61 }
62 );
63 }
64
65 // Init update script if required.
66 $this->version_check();
67 $this->pro_version_check();
68
69 // resolve plugin plugins.
70 $this->plugin_check();
71
72 new Init();
73 }
74 }
75
76 /**
77 * Fired when the plugin is activated.
78 *
79 * @param bool $network_wide Whether to activate network-wide.
80 */
81 public function activate( $network_wide ): void {
82 if ( \function_exists( 'is_multisite' ) && is_multisite() ) {
83 if ( $network_wide ) {
84 // Get all blog ids.
85 $blog_ids = $this->get_blog_ids();
86
87 foreach ( $blog_ids as $blog_id ) {
88 switch_to_blog( $blog_id );
89 $this->single_activate();
90
91 restore_current_blog();
92 }
93 } else {
94 self::single_activate();
95 }
96 } else {
97 self::single_activate();
98 }
99 }
100
101 /**
102 * Fired when the plugin is activated.
103 *
104 * @param bool $install_sync_schema Whether to install the sync schema.
105 * @param bool $full_role_sync Whether to repair all default role capabilities.
106 */
107 public function single_activate( bool $install_sync_schema = true, bool $full_role_sync = true ): void {
108 $role_capabilities = self::role_capability_definition();
109 $capability_names = $role_capabilities;
110 $capability_names['cashier'] = array_merge( array( 'access_woocommerce_pos' ), array_keys( $role_capabilities['cashier'] ) );
111 $synced = get_option( 'woocommerce_pos_role_caps_synced', false );
112 if ( ! $full_role_sync && false === $synced && get_option( 'woocommerce_pos_role_caps_fingerprint' ) === $this->role_caps_fingerprint() ) {
113 $synced = $capability_names;
114 }
115 // An upgrade grants only capabilities new to the definition since the
116 // last sync, so a capability the merchant removed on the Access screen
117 // stays removed. Explicit activation still repairs every default.
118 $granted = $capability_names;
119 if ( ! $full_role_sync && \is_array( $synced ) ) {
120 foreach ( $granted as $slug => $capabilities ) {
121 $already = isset( $synced[ $slug ] ) && \is_array( $synced[ $slug ] ) ? $synced[ $slug ] : array();
122 $granted[ $slug ] = array_values( array_diff( $capabilities, $already ) );
123 }
124 }
125
126 // Reseed the default template terms on the next request: (re)activation
127 // is the repair a merchant reaches for after deleting a term by hand.
128 // This also runs once per upgrade (version_check re-activates to sync
129 // role caps), so one post-upgrade request pays the ~18 seeding queries.
130 delete_option( Templates::DEFAULT_TERMS_OPTION );
131
132 // Second, merchant-reachable trigger for the autoload repair: db_upgrade()
133 // only runs when version_check() trips on an admin load that reaches
134 // woocommerce_init, and a miss there is permanent once bump_versions() ran.
135 self::autoload_request_latches();
136 Admin\Permalink::ensure_default();
137
138 // create POS specific roles.
139 $this->create_pos_roles( $granted['cashier'] );
140
141 // add pos capabilities to non POS roles.
142 $this->add_pos_capability(
143 array(
144 'administrator' => $granted['administrator'],
145 'shop_manager' => $granted['shop_manager'],
146 )
147 );
148
149 $stored_roles = get_option( wp_roles()->role_key, array() );
150 $roles_are_persisted = is_array( $stored_roles );
151 if ( $roles_are_persisted ) {
152 foreach ( $granted as $slug => $capabilities ) {
153 if ( ! isset( $stored_roles[ $slug ] ) ) {
154 $roles_are_persisted = false;
155 break;
156 }
157 foreach ( $capabilities as $capability ) {
158 if ( empty( $stored_roles[ $slug ]['capabilities'][ $capability ] ) ) {
159 $roles_are_persisted = false;
160 break 2;
161 }
162 }
163 }
164 }
165
166 $obsolete_customer_create_cap = isset( $role_capabilities['cashier']['create_customers'] ) ? 'promote_users' : 'create_customers';
167 if ( $roles_are_persisted && empty( $stored_roles['cashier']['capabilities'][ $obsolete_customer_create_cap ] ) ) {
168 // Snapshot first: a fingerprint that advanced past a failed snapshot
169 // write would never retry it.
170 update_option( 'woocommerce_pos_role_caps_synced', $capability_names, true );
171 update_option( 'woocommerce_pos_role_caps_fingerprint', $this->role_caps_fingerprint(), true );
172 }
173
174 // Flag the consent pop-up for the next admin page load. Done here
175 // because the `activated_plugin` action in Admin\Consent fires
176 // inside the activation request, at which point our plugin's
177 // `plugins_loaded` callback hasn't yet instantiated Init on a
178 // fresh install.
179 //
180 // Read the option directly — woocommerce_pos_get_settings() lives in
181 // wcpos-functions.php which Init loads on `plugins_loaded`, but
182 // plugins_loaded has already fired by the time activation runs.
183 $general_settings = get_option( 'woocommerce_pos_settings_general', array() );
184 $tracking_consent = is_array( $general_settings ) && isset( $general_settings['tracking_consent'] )
185 ? $general_settings['tracking_consent']
186 : 'undecided';
187 if ( 'undecided' === $tracking_consent ) {
188 set_transient( Consent::MODAL_TRANSIENT, 1, Consent::MODAL_TRANSIENT_TTL );
189 }
190
191 if ( $install_sync_schema ) {
192 $this->install_sync_schema();
193 }
194
195 // Record the install for analytics. Consent is still `undecided` at this
196 // point, so the event is held until the user answers the pop-up flagged
197 // above; Lifecycle_Events owns that deferral and reports at most once.
198 ( new Lifecycle_Events() )->record_install();
199 }
200
201 /**
202 * Install the sync store and latch its aggregate schema version after verification.
203 */
204 public function install_sync_schema(): void {
205 $previous_schema = get_option( Sync_Api::SCHEMA_OPTION, null );
206
207 $journal = new Sync_Journal();
208 $journal->install();
209 ( new Integrity_Digest() )->install();
210 ( new Mutation_Store() )->install();
211
212 if ( ! Sync_Health::is_healthy() ) {
213 if ( Sync_Api::SCHEMA_VERSION === $previous_schema ) {
214 delete_option( Sync_Api::SCHEMA_OPTION );
215 }
216 return;
217 }
218
219 // Schema 3 (#1379): the customer space widened from role=customer to ALL users.
220 // Upgrading installs carry role-departure tombstones in the persisted stream that
221 // would replay against now-live users; compensating updates supersede them (see
222 // Sync_Journal::append_customer_updates_for_all_users). The old latch stays until
223 // migration succeeds, so retries may append duplicate but harmless superseding
224 // updates. Fresh installs (no previous latch) have no stream to repair.
225 if (
226 null !== $previous_schema
227 && version_compare( (string) $previous_schema, '3', '<' )
228 && ! $journal->append_customer_updates_for_all_users()
229 ) {
230 return;
231 }
232
233 // Autoloaded: the Init constructor reads this latch on every request.
234 // This flips an existing row only on WP 6.4+; older rows are flipped by
235 // autoload_request_latches() on upgrade.
236 update_option( Sync_Api::SCHEMA_OPTION, Sync_Api::SCHEMA_VERSION, true );
237
238 if ( null !== $previous_schema && version_compare( (string) $previous_schema, Sync_Api::SCHEMA_VERSION, '<' ) ) {
239 global $wpdb;
240 $wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}wcpos_sync_change_log" ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Known legacy table name.
241 $wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}wcpos_sync_order_index" ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Known legacy table name.
242 // The legacy Change_Log_Purge class is gone; its recurring cron event
243 // would otherwise survive the upgrade and fire a hook with no handler
244 // forever. Literal hook name — the constant was removed with the class.
245 wp_clear_scheduled_hook( 'wcpos_change_log_purge' );
246 }
247 }
248
249 /**
250 * Fired when a new site is activated with a WPMU environment.
251 *
252 * @param int $blog_id Blog ID.
253 */
254 public function activate_new_site( $blog_id ): void {
255 if ( 1 !== did_action( 'wpmu_new_blog' ) ) {
256 return;
257 }
258
259 switch_to_blog( $blog_id );
260 $this->single_activate();
261 restore_current_blog();
262 }
263
264 /**
265 * Check min version of PHP.
266 */
267 private function php_check() {
268 $php_version = PHP_VERSION;
269 if ( version_compare( $php_version, PHP_MIN_VERSION, '>' ) ) {
270 return true;
271 }
272
273 // Defer __() call to avoid "too early" warning in WordPress 6.7+.
274 add_action(
275 'admin_init',
276 function () {
277 $message = \sprintf(
278 // translators: 1: Minimum PHP version, 2: Update URL.
279 __( '<strong>WCPOS</strong> requires PHP %1$s or higher. Read more information about <a href="%2$s">how you can update</a>', 'woocommerce-pos' ),
280 PHP_MIN_VERSION,
281 'http://www.wpupdatephp.com/update/'
282 ) . ' &raquo;';
283
284 Admin\Notices::add( $message );
285 }
286 );
287 }
288
289 /**
290 * Check min version of WooCommerce installed.
291 */
292 private function woocommerce_check() {
293 if ( class_exists( '\WooCommerce' ) && version_compare( WC()->version, WC_MIN_VERSION, '>=' ) ) {
294 return true;
295 }
296
297 // Defer __() call to avoid "too early" warning in WordPress 6.7+.
298 add_action(
299 'admin_init',
300 function () {
301 $message = \sprintf(
302 // translators: 1: WooCommerce URL, 2: Minimum WC version, 3: Plugins URL.
303 __( '<strong>WCPOS</strong> requires <a href="%1$s">WooCommerce %2$s or higher</a>. Please <a href="%3$s">install and activate WooCommerce</a>', 'woocommerce-pos' ),
304 'http://wordpress.org/plugins/woocommerce/',
305 WC_MIN_VERSION,
306 admin_url( 'plugins.php' )
307 ) . ' &raquo;';
308
309 Admin\Notices::add( $message );
310 }
311 );
312 }
313
314 /**
315 * POS Frontend will give 404 if pretty permalinks not active.
316 */
317 private function permalink_check(): void {
318 $permalinks = get_option( 'permalink_structure' );
319
320 // early return.
321 if ( $permalinks ) {
322 return;
323 }
324
325 $message = /* translators: Plugin activation notice label. */ __( '<strong>WooCommerce REST API</strong> requires <em>pretty</em> permalinks to work correctly', 'woocommerce-pos' ) . '. ';
326 $message .= \sprintf( '<a href="%s">%s</a>', admin_url( 'options-permalink.php' ), /* translators: Plugin activation notice label. */ __( 'Enable permalinks', 'woocommerce-pos' ) ) . ' &raquo;';
327
328 Admin\Notices::add( $message );
329 }
330
331 /**
332 * Check version number, runs every admin page load.
333 */
334 private function version_check(): void {
335 $old = (string) Services\Settings::get_db_version();
336 $plugin_needs_upgrade = version_compare( $old, VERSION, '<' );
337 $sync_needs_upgrade = Sync_Api::SCHEMA_VERSION !== get_option( Sync_Api::SCHEMA_OPTION, null );
338
339 $role_caps_fingerprint = $this->role_caps_fingerprint();
340 $role_caps_need_sync = get_option( 'woocommerce_pos_role_caps_fingerprint' ) !== $role_caps_fingerprint
341 || false === get_option( 'woocommerce_pos_role_caps_synced' );
342 if ( ! $plugin_needs_upgrade && ! $sync_needs_upgrade && ! $role_caps_need_sync ) {
343 return;
344 }
345
346 if ( ! $this->acquire_db_upgrade_lock() ) {
347 return;
348 }
349
350 $locked_old = (string) Services\Settings::get_db_version();
351 $locked_plugin_needs_upgrade = version_compare( $locked_old, VERSION, '<' );
352 $locked_sync_needs_upgrade = Sync_Api::SCHEMA_VERSION !== get_option( Sync_Api::SCHEMA_OPTION, null );
353
354 $locked_role_caps_fingerprint = $this->role_caps_fingerprint();
355 $locked_role_caps_need_sync = get_option( 'woocommerce_pos_role_caps_fingerprint' ) !== $locked_role_caps_fingerprint
356 || false === get_option( 'woocommerce_pos_role_caps_synced' );
357 if ( ! $locked_plugin_needs_upgrade && ! $locked_sync_needs_upgrade && ! $locked_role_caps_need_sync ) {
358 $this->release_db_upgrade_lock();
359 return;
360 }
361
362 if ( $locked_plugin_needs_upgrade ) {
363 Services\Settings::bump_versions();
364 }
365
366 if ( $locked_plugin_needs_upgrade || $locked_role_caps_need_sync ) {
367 // Re-run activation to sync role capabilities. add_role() and add_cap()
368 // are both idempotent, so this is safe. Without this, capabilities added
369 // in newer versions would never reach existing installs because add_role()
370 // is a no-op when the role already exists.
371 // Deferred to 'init' because create_pos_roles() calls __() which
372 // requires translations to be loaded (WordPress 6.7+).
373 add_action(
374 'init',
375 function () {
376 $this->single_activate( false, false );
377 }
378 );
379 }
380
381 $lock_released = false;
382 $release_lock = function () use ( &$lock_released ): void {
383 if ( $lock_released ) {
384 return;
385 }
386
387 $lock_released = true;
388 $this->release_db_upgrade_lock();
389 };
390
391 // Safety net in case woocommerce_init does not fire for this request.
392 add_action( 'shutdown', $release_lock );
393
394 // Defer db_upgrade to woocommerce_init when WC is fully loaded.
395 // This prevents conflicts with plugins like WC Subscriptions that hook
396 // into before_delete_post and assume WC()->order_factory is available.
397 add_action(
398 'woocommerce_init',
399 function () use ( $locked_old, $locked_plugin_needs_upgrade, $locked_sync_needs_upgrade, $release_lock ) {
400 try {
401 $this->db_upgrade( $locked_old, VERSION );
402
403 // Report the upgrade only once the migration has actually
404 // completed — queueing it beside bump_versions() would claim a
405 // finished upgrade even when db_upgrade() threw or never ran.
406 // Still exactly-once: the version was bumped above, so the
407 // upgrade is not re-detected on the next request.
408 if ( $locked_plugin_needs_upgrade ) {
409 ( new Lifecycle_Events() )->record_upgrade( $locked_old, VERSION );
410 }
411 if ( $locked_sync_needs_upgrade && Sync_Api::SCHEMA_VERSION === get_option( Sync_Api::SCHEMA_OPTION, null ) ) {
412 ( new Sync_Journal() )->register_hooks();
413 ( new Integrity_Digest() )->register_hooks();
414 }
415 } finally {
416 $release_lock();
417 remove_action( 'shutdown', $release_lock );
418 }
419 }
420 );
421 }
422
423 /**
424 * Acquire the DB upgrade lock.
425 *
426 * @return bool True when this request owns the lock.
427 */
428 private function acquire_db_upgrade_lock(): bool {
429 require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
430
431 return \WP_Upgrader::create_lock( self::DB_UPGRADE_LOCK_NAME, self::DB_UPGRADE_LOCK_TTL );
432 }
433
434 /**
435 * Release the DB upgrade lock.
436 */
437 private function release_db_upgrade_lock(): void {
438 if ( ! class_exists( '\WP_Upgrader', false ) ) {
439 require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
440 }
441
442 \WP_Upgrader::release_lock( self::DB_UPGRADE_LOCK_NAME );
443 }
444
445 /**
446 * Plugin conflicts.
447 *
448 * - NextGEN Gallery is a terrible plugin. It buffers all content on 'init' action, priority -1 and inserts junk code.
449 */
450 private function plugin_check(): void {
451 // disable NextGEN Gallery resource manager
452 // if ( ! \defined( 'NGG_DISABLE_RESOURCE_MANAGER' ) ) {
453 // \define( 'NGG_DISABLE_RESOURCE_MANAGER', true );
454 // }.
455 }
456
457 /**
458 * Get all blog ids of blogs in the current network that are:
459 * - not archived
460 * - not spam
461 * - not deleted.
462 */
463 private function get_blog_ids() {
464 global $wpdb;
465
466 // get an array of blog ids.
467 $sql = "SELECT blog_id FROM $wpdb->blogs
468 WHERE archived = '0' AND spam = '0'
469 AND deleted = '0'";
470
471 return $wpdb->get_col( $sql ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Static query, no user input
472 }
473
474 /**
475 * Get the role capability definition.
476 *
477 * @return array<string, array<string, bool>|array<int, string>> Role capabilities keyed by role.
478 */
479 private static function role_capability_definition(): array {
480 // WC 9.9 replaced promote_users with create_customers for customer creation.
481 $customer_create_cap = \defined( 'WC_VERSION' ) && version_compare( WC_VERSION, '9.9', '>=' ) // @phpstan-ignore-line
482 ? 'create_customers'
483 : 'promote_users';
484
485 // Cashier role.
486 $cashier_capabilities = array(
487 'read' => true,
488 'read_private_products' => true,
489 'publish_products' => true,
490 'edit_product' => true,
491 'edit_products' => true,
492 'edit_published_products' => true,
493 'edit_private_products' => true,
494 'edit_others_products' => true,
495 'read_private_shop_orders' => true,
496 'publish_shop_orders' => true,
497 'edit_shop_orders' => true,
498 'edit_others_shop_orders' => true,
499 'list_users' => true,
500 $customer_create_cap => true,
501 'edit_users' => true,
502 'read_private_shop_coupons' => true,
503 'publish_shop_coupons' => true,
504 'edit_shop_coupons' => true,
505 'edit_published_shop_coupons' => true,
506 'edit_private_shop_coupons' => true,
507 'edit_others_shop_coupons' => true,
508 'manage_product_terms' => true,
509 );
510
511 return array(
512 'cashier' => $cashier_capabilities,
513 'administrator' => array(
514 'manage_woocommerce_pos',
515 'access_woocommerce_pos',
516 'edit_wcpos_store',
517 'read_wcpos_store',
518 'delete_wcpos_store',
519 'edit_wcpos_stores',
520 'edit_others_wcpos_stores',
521 'publish_wcpos_stores',
522 'read_private_wcpos_stores',
523 'delete_wcpos_stores',
524 'delete_private_wcpos_stores',
525 'delete_published_wcpos_stores',
526 'delete_others_wcpos_stores',
527 'edit_private_wcpos_stores',
528 'edit_published_wcpos_stores',
529 ),
530 'shop_manager' => array( 'manage_woocommerce_pos', 'access_woocommerce_pos' ),
531 );
532 }
533
534 /**
535 * Get the role-capabilities definition fingerprint.
536 */
537 private function role_caps_fingerprint(): string {
538 return md5( wp_json_encode( self::role_capability_definition() ) );
539 }
540
541 /**
542 * Add POS specific roles.
543 *
544 * @param string[]|null $capabilities Capability names to sync onto an existing role, or null for
545 * every default. A missing role is always created with the full set.
546 */
547 private function create_pos_roles( ?array $capabilities = null ): void {
548 $role_capabilities = self::role_capability_definition();
549 $cashier_capabilities = $role_capabilities['cashier'];
550
551 add_role(
552 'cashier',
553 /* translators: Plugin activation notice label. */
554 __( 'Cashier', 'woocommerce-pos' ),
555 // A missing role is created whole, access gate included, whatever
556 // subset an incremental upgrade asked to sync.
557 array_merge( array( 'access_woocommerce_pos' => true ), $cashier_capabilities )
558 );
559
560 $obsolete_customer_create_cap = isset( $cashier_capabilities['create_customers'] ) ? 'promote_users' : 'create_customers';
561 $cashier = get_role( 'cashier' );
562 if ( $cashier ) {
563 $cashier->remove_cap( $obsolete_customer_create_cap );
564 }
565
566 // Sync the requested capabilities to the role. add_role() is a no-op when
567 // the role already exists, so capabilities added in newer versions would
568 // never reach existing installs without this.
569 $this->add_pos_capability(
570 array(
571 'cashier' => $capabilities ?? array_merge(
572 array( 'access_woocommerce_pos' ),
573 array_keys( $cashier_capabilities )
574 ),
575 )
576 );
577 }
578
579 /**
580 * Add default pos capabilities to administrator and shop_manager roles.
581 *
582 * @param array $roles An array of arrays representing the roles and their POS capabilities.
583 */
584 private function add_pos_capability( $roles ): void {
585 foreach ( $roles as $slug => $caps ) {
586 $role = get_role( $slug );
587 if ( $role ) {
588 foreach ( $caps as $cap ) {
589 $role->add_cap( $cap );
590 }
591 }
592 }
593 }
594
595 /**
596 * Upgrade database.
597 *
598 * @param string $old Old version.
599 * @param string $current Current version.
600 */
601 private function db_upgrade( $old, $current ): void {
602 $db_updates = array(
603 '0.4' => 'updates/update-0.4.php',
604 '0.4.6' => 'updates/update-0.4.6.php',
605 '1.0.0-beta.1' => 'updates/update-1.0.0-beta.1.php',
606 '1.6.1' => 'updates/update-1.6.1.php',
607 '1.8.0' => 'updates/update-1.8.0.php',
608 '1.8.7' => 'updates/update-1.8.7.php',
609 '1.8.12' => 'updates/update-1.8.12.php',
610 '1.8.13' => 'updates/update-1.8.13.php',
611 '1.9.0' => 'updates/update-1.9.0.php',
612 '1.10.0' => 'updates/update-1.10.0.php',
613 );
614 foreach ( $db_updates as $version => $updater ) {
615 if ( version_compare( $version, $old, '>' ) &&
616 version_compare( $version, $current, '<=' ) ) {
617 include $updater;
618 }
619 }
620
621 if ( Sync_Api::SCHEMA_VERSION !== get_option( Sync_Api::SCHEMA_OPTION, null ) ) {
622 $this->install_sync_schema();
623 }
624
625 // Installs that predate 2026-09 wrote the per-request latches with
626 // autoload off; every upgrade re-asserts autoload so the flip is
627 // idempotent and needs no versioned update file.
628 self::autoload_request_latches();
629 Admin\Permalink::ensure_default();
630 }
631
632 /**
633 * Every option row that is read on EVERY request and must therefore ride in
634 * alloptions: the three sync latches the Init constructor reads, the permalink
635 * slug Template_Router reads, and each registered settings section that
636 * declares {@see Services\Settings\Abstract_Section::autoload()} — the
637 * sections are the extension point, so Pro's and extensions' sections join
638 * the repair by declaring it, without touching this file.
639 *
640 * Needed because core's update_option() returns early on an unchanged value
641 * WITHOUT touching the autoload column, so a writer alone never repairs a row
642 * an older release wrote with autoload off. Without a persistent object cache
643 * each such row cost one `SELECT option_value` per page load (measured
644 * 2026-09-03 on dev-next and dev-free).
645 *
646 * @return string[]
647 */
648 private static function request_option_names(): array {
649 $names = array(
650 Sync_Api::SCHEMA_OPTION,
651 \WCPOS\WooCommercePOS\Sync\Visibility_Observer::SEED_VERSION_OPTION,
652 \WCPOS\WooCommercePOS\Sync\Config_Fingerprint::CLEANUP_VERSION_OPTION,
653 Admin\Permalink::DB_KEY,
654 );
655 foreach ( Services\Settings::instance()->sections()->all() as $section ) {
656 if ( $section instanceof Services\Settings\Abstract_Section && $section->autoload() ) {
657 $names[] = $section->autoload_option_name();
658 }
659 }
660 return $names;
661 }
662
663 /**
664 * Flip the per-request rows to autoload in place, and seed the settings
665 * sections that are absent.
666 *
667 * One UPDATE on the flag column: never delete-and-recreate, because
668 * `Sync_Api::SCHEMA_OPTION` gates the sync observers on every request and a
669 * request landing in that gap would run with journaling off. 'yes' is
670 * accepted by every core version (6.6+ maps it alongside 'on'). Idempotent:
671 * already-autoloaded rows match nothing. Latches that were never written
672 * stay absent (their absence is the signal). An autoloaded settings section
673 * that was never saved is seeded as an autoloaded row — an absent option is
674 * queried on every request too. General also persists its migrated consent
675 * so the legacy row does not remain on the read path; other defaults stay
676 * dynamic.
677 */
678 public static function autoload_request_latches(): void {
679 global $wpdb;
680 // The key comes from the section itself (autoload_option_name()): Pro's
681 // License section stores under a Pro-prefixed key, so deriving it from
682 // id() flipped nothing for that row and seeded a stray free-prefixed one.
683 foreach ( Services\Settings::instance()->sections()->all() as $section ) {
684 if ( ! $section instanceof Services\Settings\Abstract_Section || ! $section->autoload() ) {
685 continue;
686 }
687 $option_name = $section->autoload_option_name();
688 if ( false === get_option( $option_name ) ) {
689 $value = $section instanceof Services\Settings\General_Section
690 ? array( 'tracking_consent' => $section->raw_tracking_consent() )
691 : array();
692 add_option( $option_name, $value, '', true );
693 }
694 }
695 $options = self::request_option_names();
696 $placeholders = implode( ', ', array_fill( 0, \count( $options ), '%s' ) );
697 $flipped = $wpdb->query( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- the flag column is the target; caches are cleared below.
698 $wpdb->prepare(
699 "UPDATE {$wpdb->options} SET autoload = 'yes' WHERE option_name IN ({$placeholders}) AND autoload NOT IN ('yes', 'on', 'auto-on')", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- placeholders are generated for the prepared values.
700 $options
701 )
702 );
703 if ( ! $flipped ) {
704 return;
705 }
706 foreach ( $options as $option ) {
707 wp_cache_delete( $option, 'options' );
708 }
709 wp_cache_delete( 'alloptions', 'options' );
710 }
711
712 /**
713 * If \WCPOS\WooCommercePOSPro\ is installed, check the version is above MIN_PRO_VERSION.
714 */
715 private function pro_version_check(): void {
716 if ( class_exists( '\WCPOS\WooCommercePOSPro\Activator' ) ) {
717 if ( version_compare( \WCPOS\WooCommercePOSPro\VERSION, MIN_PRO_VERSION, '<' ) ) { // @phpstan-ignore-line
718
719 /*
720 * NOTE: the deactivate_plugins function is not available in the frontend or ajax
721 * This is an extreme situation where the Pro plugin could crash the site, so we need to deactivate it
722 */
723 if ( ! \function_exists( 'deactivate_plugins' ) ) {
724 require_once ABSPATH . '/wp-admin/includes/plugin.php';
725 }
726
727 // WCPOS Pro is activated, but the version is too low - use the constant for dynamic folder name.
728 deactivate_plugins( \WCPOS\WooCommercePOSPro\PLUGIN_FILE ); // @phpstan-ignore-line
729
730 // Defer __() call to avoid "too early" warning in WordPress 6.7+.
731 add_action(
732 'admin_init',
733 function () {
734 $message = \sprintf(
735 // translators: 1: WCPOS Pro URL, 2: Minimum Pro version, 3: Plugins URL.
736 __( '<strong>WCPOS</strong> requires <a href="%1$s">WCPOS Pro %2$s or higher</a>. Please <a href="%3$s">install and activate WCPOS Pro</a>', 'woocommerce-pos' ),
737 'https://wcpos.com/my-account',
738 MIN_PRO_VERSION,
739 admin_url( 'plugins.php' )
740 ) . ' &raquo;';
741
742 Admin\Notices::add( $message );
743 }
744 );
745 }
746 }
747 }
748 }
749