From 1310114b07205dce710c66e8c3810f642cec0d10 Mon Sep 17 00:00:00 2001 From: "Md.Harun-Ur-Rashid" Date: Tue, 3 Nov 2026 12:51:54 +0600 Subject: [PATCH 01/36] update: prepare table name method now support multi-site too --- core/DB.php | 23 +++- helpers/QueryHelper.php | 22 +++- tests/phpunit/DBTest.php | 192 ++++++++++++++++++++++++++++++ tests/phpunit/QueryHelperTest.php | 143 ++++++++++++++++++++++ 4 files changed, 369 insertions(+), 11 deletions(-) diff --git a/core/DB.php b/core/DB.php index 3457f0a410..4098288dbe 100644 --- a/core/DB.php +++ b/core/DB.php @@ -2085,22 +2085,33 @@ function ( $value ) { } /** - * Prepare table name with WordPress prefix if not already prefixed. + * Prepare table name with the appropriate prefix. + * Supports both single-site and multisite installations. * * @since 4.2.0 + * @since 4.2.1 Added multisite base prefix support. * * @param string $table Table name. * * @return string Prefixed table name. */ public static function prepare_table_name( string $table ): string { - $db = self::get_db(); - $prefix = isset( $db->prefix ) ? $db->prefix : ''; - if ( ! empty( $prefix ) && 0 !== strpos( $table, $prefix ) ) { - return $prefix . $table; + $db = self::get_db(); + + // Remove an existing prefix (site prefix first). + foreach ( array_unique( array( $db->prefix, $db->base_prefix ) ) as $prefix ) { + if ( '' !== $prefix && 0 === strpos( $table, $prefix ) ) { + $table = substr( $table, strlen( $prefix ) ); + break; + } + } + + // Global tables use the network base prefix. + if ( in_array( $table, $db->tables( 'global', false ), true ) ) { + return $db->base_prefix . $table; } - return $table; + return $db->prefix . $table; } /** diff --git a/helpers/QueryHelper.php b/helpers/QueryHelper.php index 76ecd042d5..238db42f80 100644 --- a/helpers/QueryHelper.php +++ b/helpers/QueryHelper.php @@ -1387,21 +1387,33 @@ public static function get_table_prefix() { } /** - * Prepare table name with prefix. + * Prepare table name with the appropriate prefix. + * Supports both single-site and multisite installations. * * @since 3.7.0 + * @since 4.2.1 Added multisite base prefix support. * * @param string $table_name table name. * * @return string */ public static function prepare_table_name( string $table_name ) { - $table_prefix = self::get_table_prefix(); - if ( strpos( $table_name, $table_prefix ) !== 0 ) { - $table_name = $table_prefix . $table_name; + global $wpdb; + + // Remove an existing prefix (site prefix first). + foreach ( array_unique( array( $wpdb->prefix, $wpdb->base_prefix ) ) as $prefix ) { + if ( '' !== $prefix && 0 === strpos( $table_name, $prefix ) ) { + $table_name = substr( $table_name, strlen( $prefix ) ); + break; + } + } + + // Global tables use the network base prefix. + if ( in_array( $table_name, $wpdb->tables( 'global', false ), true ) ) { + return $wpdb->base_prefix . $table_name; } - return $table_name; + return $wpdb->prefix . $table_name; } /** diff --git a/tests/phpunit/DBTest.php b/tests/phpunit/DBTest.php index a31b861c97..a4194dbba2 100644 --- a/tests/phpunit/DBTest.php +++ b/tests/phpunit/DBTest.php @@ -1301,4 +1301,196 @@ public function test_db_set_and_get() { DB::set_db( null ); $this->assertSame( $wpdb, $method->invoke( null ) ); } + + // ─── prepare_table_name & prefixing ───────────────────────────────────── + + /** + * Test DB::prepare_table_name in single site environment. + * + * @since 4.2.1 + * + * @return void + */ + public function test_prepare_table_name_single_site() { + global $wpdb; + + // Unprefixed site tables. + $this->assertSame( $wpdb->prefix . 'posts', DB::prepare_table_name( 'posts' ) ); + $this->assertSame( $wpdb->prefix . 'tutor_orders', DB::prepare_table_name( 'tutor_orders' ) ); + + // Already prefixed site tables (no double-prefix). + $this->assertSame( $wpdb->prefix . 'posts', DB::prepare_table_name( $wpdb->prefix . 'posts' ) ); + $this->assertSame( $wpdb->prefix . 'tutor_orders', DB::prepare_table_name( $wpdb->prefix . 'tutor_orders' ) ); + + // Global tables in single site. + $this->assertSame( $wpdb->base_prefix . 'users', DB::prepare_table_name( 'users' ) ); + $this->assertSame( $wpdb->base_prefix . 'usermeta', DB::prepare_table_name( 'usermeta' ) ); + $this->assertSame( $wpdb->base_prefix . 'users', DB::prepare_table_name( $wpdb->base_prefix . 'users' ) ); + $this->assertSame( $wpdb->base_prefix . 'usermeta', DB::prepare_table_name( $wpdb->base_prefix . 'usermeta' ) ); + } + + /** + * Test DB::prepare_table_name for site-specific tables in multisite. + * + * @since 4.2.1 + * + * @return void + */ + public function test_prepare_table_name_multisite_site_specific_tables() { + global $wpdb; + + $orig_prefix = $wpdb->prefix; + $orig_base_prefix = $wpdb->base_prefix; + + try { + // Simulate multisite subsite (e.g. blog_id = 2). + $wpdb->base_prefix = 'wp_'; + $wpdb->prefix = 'wp_2_'; + + // Unprefixed site-specific tables get site prefix. + $this->assertSame( 'wp_2_posts', DB::prepare_table_name( 'posts' ) ); + $this->assertSame( 'wp_2_tutor_orders', DB::prepare_table_name( 'tutor_orders' ) ); + + // Already site-prefixed table does not double prefix. + $this->assertSame( 'wp_2_posts', DB::prepare_table_name( 'wp_2_posts' ) ); + $this->assertSame( 'wp_2_tutor_orders', DB::prepare_table_name( 'wp_2_tutor_orders' ) ); + + // Site prefix precedence: 'wp_2_' is stripped first, not 'wp_' leaving '2_posts'. + $this->assertSame( 'wp_2_posts', DB::prepare_table_name( 'wp_2_posts' ) ); + $this->assertSame( 'wp_2_custom_table', DB::prepare_table_name( 'wp_2_custom_table' ) ); + } finally { + $wpdb->prefix = $orig_prefix; + $wpdb->base_prefix = $orig_base_prefix; + } + } + + /** + * Test DB::prepare_table_name for global tables in multisite. + * + * @since 4.2.1 + * + * @return void + */ + public function test_prepare_table_name_multisite_global_tables() { + global $wpdb; + + $orig_prefix = $wpdb->prefix; + $orig_base_prefix = $wpdb->base_prefix; + + try { + // Simulate multisite subsite (e.g. blog_id = 2). + $wpdb->base_prefix = 'wp_'; + $wpdb->prefix = 'wp_2_'; + + // Global tables must use base_prefix, never subsite prefix. + $this->assertSame( 'wp_users', DB::prepare_table_name( 'users' ) ); + $this->assertSame( 'wp_usermeta', DB::prepare_table_name( 'usermeta' ) ); + + // Already base-prefixed global tables remain base-prefixed. + $this->assertSame( 'wp_users', DB::prepare_table_name( 'wp_users' ) ); + $this->assertSame( 'wp_usermeta', DB::prepare_table_name( 'wp_usermeta' ) ); + + // If incorrectly given subsite prefix, global table is normalized to base prefix. + $this->assertSame( 'wp_users', DB::prepare_table_name( 'wp_2_users' ) ); + $this->assertSame( 'wp_usermeta', DB::prepare_table_name( 'wp_2_usermeta' ) ); + + // Verify all registered global tables dynamically. + $global_tables = $wpdb->tables( 'global', false ); + foreach ( $global_tables as $global_table ) { + $this->assertSame( + 'wp_' . $global_table, + DB::prepare_table_name( $global_table ), + "Global table {$global_table} should have base_prefix." + ); + $this->assertSame( + 'wp_' . $global_table, + DB::prepare_table_name( 'wp_2_' . $global_table ), + "Subsite-prefixed global table wp_2_{$global_table} should normalize to base_prefix." + ); + } + } finally { + $wpdb->prefix = $orig_prefix; + $wpdb->base_prefix = $orig_base_prefix; + } + } + + /** + * Test DB::prepare_table_name for custom tables starting with global table names. + * + * @since 4.2.1 + * + * @return void + */ + public function test_prepare_table_name_custom_table_similar_to_global_table() { + global $wpdb; + + $orig_prefix = $wpdb->prefix; + $orig_base_prefix = $wpdb->base_prefix; + + try { + $wpdb->base_prefix = 'wp_'; + $wpdb->prefix = 'wp_2_'; + + // Tables like 'users_archive' or 'usermeta_backup' are NOT global tables. + $this->assertSame( 'wp_2_users_archive', DB::prepare_table_name( 'users_archive' ) ); + $this->assertSame( 'wp_2_users_archive', DB::prepare_table_name( 'wp_2_users_archive' ) ); + $this->assertSame( 'wp_2_usermeta_backup', DB::prepare_table_name( 'usermeta_backup' ) ); + $this->assertSame( 'wp_2_usermeta_backup', DB::prepare_table_name( 'wp_2_usermeta_backup' ) ); + } finally { + $wpdb->prefix = $orig_prefix; + $wpdb->base_prefix = $orig_base_prefix; + } + } + + /** + * Test DB::table() query generation under multisite conditions. + * + * @since 4.2.1 + * + * @return void + */ + public function test_table_multisite_prefixing() { + global $wpdb; + + $orig_prefix = $wpdb->prefix; + $orig_base_prefix = $wpdb->base_prefix; + + try { + $wpdb->base_prefix = 'wp_'; + $wpdb->prefix = 'wp_2_'; + + // Site table. + $this->assertSame( 'SELECT * FROM wp_2_posts', DB::table( 'posts' )->to_sql() ); + $this->assertSame( 'SELECT * FROM wp_2_posts', DB::table( 'wp_2_posts' )->to_sql() ); + + // Global table. + $this->assertSame( 'SELECT * FROM wp_users', DB::table( 'users' )->to_sql() ); + $this->assertSame( 'SELECT * FROM wp_users', DB::table( 'wp_users' )->to_sql() ); + $this->assertSame( 'SELECT * FROM wp_users', DB::table( 'wp_2_users' )->to_sql() ); + } finally { + $wpdb->prefix = $orig_prefix; + $wpdb->base_prefix = $orig_base_prefix; + } + } + + /** + * Test DB::get_table_prefix. + * + * @since 4.2.1 + * + * @return void + */ + public function test_get_table_prefix() { + global $wpdb; + + $this->assertSame( $wpdb->prefix, DB::get_table_prefix() ); + + $orig_prefix = $wpdb->prefix; + try { + $wpdb->prefix = 'wp_custom_'; + $this->assertSame( 'wp_custom_', DB::get_table_prefix() ); + } finally { + $wpdb->prefix = $orig_prefix; + } + } } diff --git a/tests/phpunit/QueryHelperTest.php b/tests/phpunit/QueryHelperTest.php index 297e904b6e..de182dda2e 100644 --- a/tests/phpunit/QueryHelperTest.php +++ b/tests/phpunit/QueryHelperTest.php @@ -704,6 +704,149 @@ public function test_prepare_table_name_no_double_prefix() { $this->assertSame( $already_prefixed, $result ); } + /** + * Test prepare_table_name handles global tables in single site. + * + * @since 4.2.1 + * + * @return void + */ + public function test_prepare_table_name_single_site_global_tables() { + global $wpdb; + + // Unprefixed global tables. + $this->assertSame( $wpdb->base_prefix . 'users', QueryHelper::prepare_table_name( 'users' ) ); + $this->assertSame( $wpdb->base_prefix . 'usermeta', QueryHelper::prepare_table_name( 'usermeta' ) ); + + // Already prefixed global tables. + $this->assertSame( $wpdb->base_prefix . 'users', QueryHelper::prepare_table_name( $wpdb->base_prefix . 'users' ) ); + $this->assertSame( $wpdb->base_prefix . 'usermeta', QueryHelper::prepare_table_name( $wpdb->base_prefix . 'usermeta' ) ); + } + + /** + * Test prepare_table_name for site-specific tables in multisite. + * + * @since 4.2.1 + * + * @return void + */ + public function test_prepare_table_name_multisite_site_specific_tables() { + global $wpdb; + + $orig_prefix = $wpdb->prefix; + $orig_base_prefix = $wpdb->base_prefix; + + try { + // Simulate multisite subsite (e.g. blog_id = 2). + $wpdb->base_prefix = 'wp_'; + $wpdb->prefix = 'wp_2_'; + + // Unprefixed site-specific tables get site prefix. + $this->assertSame( 'wp_2_posts', QueryHelper::prepare_table_name( 'posts' ) ); + $this->assertSame( 'wp_2_tutor_earnings', QueryHelper::prepare_table_name( 'tutor_earnings' ) ); + + // Already site-prefixed table does not double prefix. + $this->assertSame( 'wp_2_posts', QueryHelper::prepare_table_name( 'wp_2_posts' ) ); + $this->assertSame( 'wp_2_tutor_earnings', QueryHelper::prepare_table_name( 'wp_2_tutor_earnings' ) ); + + // Ensure site prefix precedence: 'wp_2_' is stripped first, not 'wp_' leaving '2_posts'. + $this->assertSame( 'wp_2_custom_table', QueryHelper::prepare_table_name( 'wp_2_custom_table' ) ); + } finally { + $wpdb->prefix = $orig_prefix; + $wpdb->base_prefix = $orig_base_prefix; + } + } + + /** + * Test prepare_table_name for global tables in multisite. + * + * @since 4.2.1 + * + * @return void + */ + public function test_prepare_table_name_multisite_global_tables() { + global $wpdb; + + $orig_prefix = $wpdb->prefix; + $orig_base_prefix = $wpdb->base_prefix; + + try { + // Simulate multisite subsite (e.g. blog_id = 2). + $wpdb->base_prefix = 'wp_'; + $wpdb->prefix = 'wp_2_'; + + // Global tables must use base_prefix, never subsite prefix. + $this->assertSame( 'wp_users', QueryHelper::prepare_table_name( 'users' ) ); + $this->assertSame( 'wp_usermeta', QueryHelper::prepare_table_name( 'usermeta' ) ); + + // Already base-prefixed global tables remain base-prefixed. + $this->assertSame( 'wp_users', QueryHelper::prepare_table_name( 'wp_users' ) ); + $this->assertSame( 'wp_usermeta', QueryHelper::prepare_table_name( 'wp_usermeta' ) ); + + // If incorrectly given subsite prefix, global table is normalized to base prefix. + $this->assertSame( 'wp_users', QueryHelper::prepare_table_name( 'wp_2_users' ) ); + $this->assertSame( 'wp_usermeta', QueryHelper::prepare_table_name( 'wp_2_usermeta' ) ); + + // Verify all registered global tables dynamically. + $global_tables = $wpdb->tables( 'global', false ); + foreach ( $global_tables as $global_table ) { + $this->assertSame( + 'wp_' . $global_table, + QueryHelper::prepare_table_name( $global_table ), + "Global table {$global_table} should have base_prefix." + ); + $this->assertSame( + 'wp_' . $global_table, + QueryHelper::prepare_table_name( 'wp_2_' . $global_table ), + "Subsite-prefixed global table wp_2_{$global_table} should normalize to base_prefix." + ); + } + } finally { + $wpdb->prefix = $orig_prefix; + $wpdb->base_prefix = $orig_base_prefix; + } + } + + /** + * Test prepare_table_name for custom tables starting with global table names. + * + * @since 4.2.1 + * + * @return void + */ + public function test_prepare_table_name_custom_table_similar_to_global_table() { + global $wpdb; + + $orig_prefix = $wpdb->prefix; + $orig_base_prefix = $wpdb->base_prefix; + + try { + $wpdb->base_prefix = 'wp_'; + $wpdb->prefix = 'wp_2_'; + + // Tables like 'users_backup' or 'usermeta_archive' are NOT global tables. + $this->assertSame( 'wp_2_users_backup', QueryHelper::prepare_table_name( 'users_backup' ) ); + $this->assertSame( 'wp_2_users_backup', QueryHelper::prepare_table_name( 'wp_2_users_backup' ) ); + $this->assertSame( 'wp_2_usermeta_archive', QueryHelper::prepare_table_name( 'usermeta_archive' ) ); + $this->assertSame( 'wp_2_usermeta_archive', QueryHelper::prepare_table_name( 'wp_2_usermeta_archive' ) ); + } finally { + $wpdb->prefix = $orig_prefix; + $wpdb->base_prefix = $orig_base_prefix; + } + } + + /** + * Test get_table_prefix. + * + * @since 4.2.1 + * + * @return void + */ + public function test_get_table_prefix() { + global $wpdb; + $this->assertSame( $wpdb->prefix, QueryHelper::get_table_prefix() ); + } + // ─── get_valid_sort_order ─────────────────────────────────────────────── /** From 9c6f50d871abab3aa7c383567cdbe3bc7217c4ea Mon Sep 17 00:00:00 2001 From: "Md.Harun-Ur-Rashid" Date: Thu, 5 Nov 2026 15:55:29 +0600 Subject: [PATCH 02/36] refactor: use WordPress wpdb properties for postmeta and users tables --- classes/WooCommerce.php | 3 +-- models/WithdrawModel.php | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/classes/WooCommerce.php b/classes/WooCommerce.php index e22ffb3309..4ec56ae67d 100644 --- a/classes/WooCommerce.php +++ b/classes/WooCommerce.php @@ -947,8 +947,7 @@ public function tutor_update_product_url( $permalink, $cart_item ) { if ( isset( $product_meta['_tutor_product'] ) && $product_meta['_tutor_product'][0] ) { global $wpdb; - $table = $wpdb->base_prefix . 'postmeta'; - $post_id = $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM {$table} WHERE meta_key = '_tutor_course_product_id' AND meta_value = %d ", $woo_product_id ) ); //phpcs:ignore + $post_id = $wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = '_tutor_course_product_id' AND meta_value = %d ", $woo_product_id ) ); if ( $post_id ) { $data = get_post_permalink( $post_id ); diff --git a/models/WithdrawModel.php b/models/WithdrawModel.php index 1b851b619f..b885345f98 100644 --- a/models/WithdrawModel.php +++ b/models/WithdrawModel.php @@ -195,7 +195,7 @@ public static function get_withdraw_summary( $instructor_id, $args = array() ) { HAVING user_id = u.ID ),0) total_matured - FROM {$wpdb->prefix}users u WHERE u.ID=%d + FROM {$wpdb->users} u WHERE u.ID=%d ) a", 'completed', From 59df5980fd6a4a19a459f7bb49bb5001dbca2ebd Mon Sep 17 00:00:00 2001 From: "Md.Harun-Ur-Rashid" Date: Mon, 9 Nov 2026 15:55:30 +0600 Subject: [PATCH 03/36] email table creation moved to addon --- classes/Upgrader.php | 85 +++----------------------------------------- 1 file changed, 4 insertions(+), 81 deletions(-) diff --git a/classes/Upgrader.php b/classes/Upgrader.php index 3f44436271..7fd5db5b5b 100644 --- a/classes/Upgrader.php +++ b/classes/Upgrader.php @@ -10,6 +10,7 @@ namespace TUTOR; +use Tutor\Database\TableManager; use Tutor\Ecommerce\CartController; use Tutor\Ecommerce\CheckoutController; use Tutor\Helpers\QueryHelper; @@ -47,8 +48,6 @@ public function __construct() { /** * Installing Gradebook Addon from TutorPro */ - add_action( 'tutor_addon_before_enable_tutor-pro/addons/gradebook/gradebook.php', array( $this, 'install_gradebook' ) ); - add_action( 'tutor_addon_before_enable_tutor-pro/addons/tutor-email/tutor-email.php', array( $this, 'install_tutor_email_queue' ) ); add_action( 'upgrader_process_complete', array( $this, 'init_email_table_deployment' ), 10, 2 ); } @@ -331,55 +330,6 @@ public function upgrade_to_3_8_2() { } } - /** - * Installing Gradebook if Tutor Pro exists - * - * @since v1.4.2 - * - * @return void - */ - public function install_gradebook() { - global $wpdb; - - $exists_gradebook_table = $wpdb->query( "SHOW TABLES LIKE '{$wpdb->tutor_gradebooks}';" ); - $exists_gradebook_results_table = $wpdb->query( "SHOW TABLES LIKE '{$wpdb->tutor_gradebooks_results}';" ); - $charset_collate = $wpdb->get_charset_collate(); - - require_once ABSPATH . 'wp-admin/includes/upgrade.php'; - - if ( ! $exists_gradebook_table ) { - $gradebook_table = "CREATE TABLE IF NOT EXISTS {$wpdb->tutor_gradebooks} ( - gradebook_id bigint(20) NOT NULL AUTO_INCREMENT, - grade_name varchar(50) DEFAULT NULL, - grade_point varchar(20) DEFAULT NULL, - grade_point_to varchar(20) DEFAULT NULL, - percent_from int(3) DEFAULT NULL, - percent_to int(3) DEFAULT NULL, - grade_config longtext, - PRIMARY KEY (gradebook_id) - ) $charset_collate;"; - dbDelta( $gradebook_table ); - } - if ( ! $exists_gradebook_results_table ) { - $gradebook_results = "CREATE TABLE IF NOT EXISTS {$wpdb->tutor_gradebooks_results} ( - gradebook_result_id bigint(20) NOT NULL AUTO_INCREMENT, - user_id bigint(20) DEFAULT NULL, - course_id bigint(20) DEFAULT NULL, - quiz_id bigint(20) DEFAULT NULL, - assignment_id bigint(20) DEFAULT NULL, - gradebook_id bigint(20) DEFAULT NULL, - result_for varchar(50) DEFAULT NULL, - grade_name varchar(50) DEFAULT NULL, - grade_point varchar(20) DEFAULT NULL, - earned_grade_point varchar(20) DEFAULT NULL, - earned_percent int(3) DEFAULT NULL, - generate_date datetime NOT NULL DEFAULT '0000-00-00 00:00:00', - update_date datetime NOT NULL DEFAULT '0000-00-00 00:00:00', - PRIMARY KEY (gradebook_result_id) - ) {$charset_collate};"; - dbDelta( $gradebook_results ); - } - } /** * Upgrade to version 4.2.0 @@ -411,36 +361,9 @@ public function init_email_table_deployment( $upgrader_object, $options ) { $addon_config = tutor_utils()->get_addon_config( 'tutor-pro/addons/tutor-email/tutor-email.php' ); $is_enable = (bool) tutor_utils()->avalue_dot( 'is_enable', $addon_config ); - $is_enable ? $this->install_tutor_email_queue() : 0; - } - } - - /** - * Installing email addon if Tutor Pro exists - * - * @since 1.8.6 - * - * @return void - */ - public function install_tutor_email_queue() { - - global $wpdb; - $charset_collate = $wpdb->get_charset_collate(); - - require_once ABSPATH . 'wp-admin/includes/upgrade.php'; - - if ( ! QueryHelper::table_exists( $wpdb->tutor_email_queue ) ) { - $table = "CREATE TABLE IF NOT EXISTS {$wpdb->tutor_email_queue} ( - id bigint(20) unsigned NOT NULL AUTO_INCREMENT, - mail_to varchar(255) NOT NULL, - subject text NOT NULL, - message text NOT NULL, - headers text NOT NULL, - batch varchar(50) NULL, - PRIMARY KEY (id) - ) {$charset_collate};"; - - dbDelta( $table ); + if ( $is_enable && class_exists( \TutorPro\Database\Schema::class ) ) { + TableManager::create_table( \TutorPro\Database\Schema::get_email_queue_table_schema( false ) ); + } } } } From f320800cd400b6621fde85b441102b69b1fbe6dd Mon Sep 17 00:00:00 2001 From: "Md.Harun-Ur-Rashid" Date: Mon, 9 Nov 2026 16:47:55 +0600 Subject: [PATCH 04/36] feat: add WordPress multisite support and modular database management --- classes/Multisite.php | 171 ++++++++ classes/Tutor.php | 369 ++--------------- classes/Upgrader.php | 7 +- composer.json | 1 + database/Schema.php | 667 ++++++++++++++++++++++++++++++ database/TableManager.php | 161 ++++++++ tests/phpunit/CouponModelTest.php | 3 +- 7 files changed, 1037 insertions(+), 342 deletions(-) create mode 100644 classes/Multisite.php create mode 100644 database/Schema.php create mode 100644 database/TableManager.php diff --git a/classes/Multisite.php b/classes/Multisite.php new file mode 100644 index 0000000000..c63a36251c --- /dev/null +++ b/classes/Multisite.php @@ -0,0 +1,171 @@ + + * @link https://themeum.com + * @since 4.3.0 + */ + +namespace TUTOR; + +use Tutor\Database\TableManager; + +defined( 'ABSPATH' ) || exit; + +/** + * Class Multisite + * + * @since 4.3.0 + */ +class Multisite { + + /** + * Constructor. + * + * @since 4.3.0 + */ + public function __construct() { + if ( ! is_multisite() ) { + return; + } + + // Modern site initialization hook (WP 5.1+). + add_action( 'wp_initialize_site', array( $this, 'on_initialize_site' ), 10, 2 ); + + // Site deletion hook. + add_action( 'wp_uninitialize_site', array( $this, 'on_uninitialize_site' ) ); + + // Ensure administrator capabilities on active subsite. + add_action( 'init', array( $this, 'ensure_admin_capabilities' ) ); + } + + /** + * Initialize Tutor on a newly created subsite. + * + * @since 4.3.0 + * + * @param \WP_Site $site New site object. + * @param array $args Setup arguments. + * @return void + */ + public function on_initialize_site( \WP_Site $site, array $args = array() ): void { + $blog_id = (int) $site->blog_id; + + switch_to_blog( $blog_id ); + + // 1. Create all tables. + TableManager::create_tables( true ); + + // 2. Default options. + $default_options = Tutor::default_options(); + update_option( 'tutor_option', $default_options ); + update_option( 'tutor_version', TUTOR_VERSION ); + + // 3. User roles & permissions. + Tutor::manage_tutor_roles_and_permissions(); + + // 4. Default pages. + Tutor::save_data(); + + /** + * Action fired after a subsite is initialized with Tutor LMS. + * + * @since 4.3.0 + * + * @param int $blog_id Blog ID. + * @param \WP_Site $site Site instance. + */ + do_action( 'tutor_multisite_subsite_initialized', $blog_id, $site ); + + restore_current_blog(); + } + + /** + * Clean up tables on subsite deletion. + * + * @since 4.3.0 + * + * @param \WP_Site $site Site being uninitialized. + * @return void + */ + public function on_uninitialize_site( \WP_Site $site ): void { + $blog_id = (int) $site->blog_id; + + /** + * Filter whether to drop Tutor tables when a subsite is deleted. + * + * @since 4.3.0 + * + * @param bool $should_drop Whether to drop tables. Default true. + * @param int $blog_id Blog ID being deleted. + */ + $should_drop = apply_filters( 'tutor_multisite_drop_tables_on_delete', true, $blog_id ); + if ( $should_drop ) { + switch_to_blog( $blog_id ); + TableManager::drop_tables(); + restore_current_blog(); + } + + /** + * Action fired after subsite tables have been cleaned up. + * + * @since 4.3.0 + * + * @param int $blog_id Blog ID. + * @param \WP_Site $site Site instance. + */ + do_action( 'tutor_multisite_subsite_deleted', $blog_id, $site ); + } + + /** + * Network activation runner to provision all existing sites in network. + * + * @since 4.3.0 + * + * @return void + */ + public static function activate_network(): void { + $site_ids = get_sites( + array( + 'fields' => 'ids', + 'number' => 0, + ) + ); + + foreach ( $site_ids as $blog_id ) { + switch_to_blog( (int) $blog_id ); + + TableManager::create_tables( true ); + + $version = get_option( 'tutor_version' ); + if ( ! $version ) { + update_option( 'tutor_option', Tutor::default_options() ); + Tutor::manage_tutor_roles_and_permissions(); + Tutor::save_data(); + update_option( 'tutor_version', TUTOR_VERSION ); + } + + restore_current_blog(); + } + } + + /** + * Ensure administrator users have required Tutor capabilities on the subsite. + * + * @since 4.3.0 + * + * @return void + */ + public function ensure_admin_capabilities(): void { + if ( current_user_can( 'administrator' ) && ! current_user_can( tutor()->instructor_role ) ) { + $user = wp_get_current_user(); + if ( $user && $user->exists() ) { + $user->add_role( 'manage_tutor' ); + $user->add_role( tutor()->instructor_role ); + } + } + } +} + diff --git a/classes/Tutor.php b/classes/Tutor.php index c236fb5e74..4a6474e6de 100644 --- a/classes/Tutor.php +++ b/classes/Tutor.php @@ -10,8 +10,11 @@ namespace TUTOR; +use Tutor\Core\DB; use Tutor\Core\Input; use Tutor\Core\Singleton; +use Tutor\Database\Schema; +use Tutor\Database\TableManager; use Tutor\Models\CourseModel; use Tutor\Ecommerce\Ecommerce; use Tutor\GDPR\GDPR; @@ -453,28 +456,16 @@ public function __construct() { $this->basename = plugin_basename( TUTOR_FILE ); /** - * Adding Tutor Database table to $wpdb; + * Adding Tutor Database tables to $wpdb; * * @since 1.4.2 + * @since 4.3.0 Dynamically registered from TableRegistry with multisite awareness. */ global $wpdb; - $wpdb->tutor_earnings = $wpdb->prefix . 'tutor_earnings'; - $wpdb->tutor_gradebooks = $wpdb->prefix . 'tutor_gradebooks'; - $wpdb->tutor_gradebooks_results = $wpdb->prefix . 'tutor_gradebooks_results'; - $wpdb->tutor_quiz_attempts = $wpdb->prefix . 'tutor_quiz_attempts'; - $wpdb->tutor_quiz_attempt_answers = $wpdb->prefix . 'tutor_quiz_attempt_answers'; - $wpdb->tutor_quiz_questions = $wpdb->prefix . 'tutor_quiz_questions'; - $wpdb->tutor_quiz_question_answers = $wpdb->prefix . 'tutor_quiz_question_answers'; - $wpdb->tutor_withdraws = $wpdb->prefix . 'tutor_withdraws'; - $wpdb->tutor_email_queue = $wpdb->prefix . 'tutor_email_queue'; - $wpdb->tutor_order_items = $wpdb->prefix . 'tutor_order_items'; - $wpdb->tutor_orders = $wpdb->prefix . 'tutor_orders'; - $wpdb->tutor_ordermeta = $wpdb->prefix . 'tutor_ordermeta'; - $wpdb->tutor_subscription_plan_items = $wpdb->prefix . 'tutor_subscription_plan_items'; - $wpdb->tutor_subscription_plans = $wpdb->prefix . 'tutor_subscription_plans'; - $wpdb->tutor_subscriptions = $wpdb->prefix . 'tutor_subscriptions'; - $wpdb->tutor_subscriptionmeta = $wpdb->prefix . 'tutor_subscriptionmeta'; - $wpdb->tutor_order_itemmeta = $wpdb->prefix . 'tutor_order_itemmeta'; + foreach ( TableManager::get_tables() as $key => $table_base_name ) { + $prop = 'tutor_' . $key; + $wpdb->$prop = DB::prepare_table_name( $table_base_name ); + } /** * Changing default wp doing ajax return based on tutor ajax action @@ -564,6 +555,15 @@ public function __construct() { */ new Migration(); + /** + * Multisite manager + * + * @since 4.3.0 + */ + if ( is_multisite() ) { + new Multisite(); + } + /** * Run Method * @@ -693,7 +693,13 @@ public function init_action() { * * @since 4.0.0 Flush rewrite rules on activation. */ - public static function tutor_activate() { + public static function tutor_activate( $network_wide = false ) { + // Network-wide activation in Multisite. + if ( is_multisite() && $network_wide ) { + Multisite::activate_network(); + return; + } + // Rewrite Flush. Permalink::set_permalink_flag(); @@ -771,324 +777,13 @@ public static function tutor_deactivation() { /** * Create database * + * @since 1.0.0 + * @since 4.3.0 Delegated to SchemaManager for multisite support. + * * @return void */ public static function create_database() { - global $wpdb; - - $charset_collate = $wpdb->get_charset_collate(); - - /** - * Table SQL - * - * {$wpdb->prefix}tutor_quiz_attempts - * {$wpdb->prefix}tutor_quiz_attempt_answers - * {$wpdb->prefix}tutor_quiz_questions - * {$wpdb->prefix}tutor_quiz_question_answers - * {$wpdb->prefix}tutor_earnings - * {$wpdb->prefix}tutor_withdraws - * - * @since 1.0.0 - */ - $quiz_attempts_sql = "CREATE TABLE {$wpdb->prefix}tutor_quiz_attempts ( - attempt_id bigint(20) NOT NULL AUTO_INCREMENT, - course_id bigint(20) DEFAULT NULL, - quiz_id bigint(20) DEFAULT NULL, - user_id bigint(20) DEFAULT NULL, - total_questions int(11) DEFAULT NULL, - total_answered_questions int(11) DEFAULT NULL, - total_marks decimal(9,2) DEFAULT NULL, - earned_marks decimal(9,2) DEFAULT NULL, - attempt_info text, - attempt_status varchar(50) DEFAULT NULL, - attempt_ip varchar(250) DEFAULT NULL, - attempt_started_at datetime DEFAULT NULL, - attempt_ended_at datetime DEFAULT NULL, - is_manually_reviewed int(1) DEFAULT NULL, - manually_reviewed_at datetime DEFAULT NULL, - result varchar(10) DEFAULT NULL, - PRIMARY KEY (attempt_id), - INDEX (course_id), - INDEX (quiz_id), - INDEX (user_id), - INDEX (result) - ) $charset_collate;"; - - $quiz_attempt_answers = "CREATE TABLE {$wpdb->prefix}tutor_quiz_attempt_answers ( - attempt_answer_id bigint(20) NOT NULL AUTO_INCREMENT, - user_id bigint(20) DEFAULT NULL, - quiz_id bigint(20) DEFAULT NULL, - question_id bigint(20) DEFAULT NULL, - quiz_attempt_id bigint(20) DEFAULT NULL, - given_answer longtext, - question_mark decimal(8,2) DEFAULT NULL, - achieved_mark decimal(8,2) DEFAULT NULL, - minus_mark decimal(8,2) DEFAULT NULL, - is_correct tinyint(4) DEFAULT NULL, - PRIMARY KEY (attempt_answer_id) - ) $charset_collate;"; - - $tutor_quiz_questions = "CREATE TABLE {$wpdb->prefix}tutor_quiz_questions ( - question_id bigint(20) NOT NULL AUTO_INCREMENT, - quiz_id bigint(20) DEFAULT NULL, - question_title text, - question_description longtext, - answer_explanation longtext DEFAULT '', - question_type varchar(50) DEFAULT NULL, - question_mark decimal(9,2) DEFAULT NULL, - question_settings longtext, - question_order int(11) DEFAULT NULL, - PRIMARY KEY (question_id) - ) $charset_collate;"; - - $tutor_quiz_question_answers = "CREATE TABLE {$wpdb->prefix}tutor_quiz_question_answers ( - answer_id bigint(20) NOT NULL AUTO_INCREMENT, - belongs_question_id bigint(20) DEFAULT NULL, - belongs_question_type varchar(250) DEFAULT NULL, - answer_title text, - is_correct tinyint(4) DEFAULT NULL, - image_id bigint(20) DEFAULT NULL, - answer_two_gap_match text, - answer_view_format varchar(250) DEFAULT NULL, - answer_settings text, - answer_order int(11) DEFAULT '0', - PRIMARY KEY (answer_id) - ) $charset_collate;"; - - $earning_table = "CREATE TABLE IF NOT EXISTS {$wpdb->prefix}tutor_earnings ( - earning_id bigint(20) NOT NULL AUTO_INCREMENT, - user_id bigint(20) DEFAULT NULL, - course_id bigint(20) DEFAULT NULL, - order_id bigint(20) DEFAULT NULL, - order_status varchar(50) DEFAULT NULL, - course_price_total decimal(16,2) DEFAULT NULL, - course_price_grand_total decimal(16,2) DEFAULT NULL, - instructor_amount decimal(16,2) DEFAULT NULL, - instructor_rate decimal(16,2) DEFAULT NULL, - admin_amount decimal(16,2) DEFAULT NULL, - admin_rate decimal(16,2) DEFAULT NULL, - commission_type varchar(20) DEFAULT NULL, - deduct_fees_amount decimal(16,2) DEFAULT NULL, - deduct_fees_name varchar(250) DEFAULT NULL, - deduct_fees_type varchar(20) DEFAULT NULL, - process_by varchar(20) DEFAULT NULL, - created_at datetime DEFAULT NULL, - PRIMARY KEY (earning_id), - INDEX (user_id), - INDEX (course_id), - INDEX (order_id), - INDEX (process_by) - ) $charset_collate;"; - - $withdraw_table = "CREATE TABLE IF NOT EXISTS {$wpdb->prefix}tutor_withdraws ( - withdraw_id bigint(20) NOT NULL AUTO_INCREMENT, - user_id bigint(20) DEFAULT NULL, - amount decimal(16,2) DEFAULT NULL, - method_data text DEFAULT NULL, - status varchar(50) DEFAULT NULL, - updated_at datetime DEFAULT NULL, - created_at datetime DEFAULT NULL, - PRIMARY KEY (withdraw_id) - ) $charset_collate;"; - - $orders_table = "CREATE TABLE {$wpdb->prefix}tutor_orders ( - id BIGINT(20) UNSIGNED AUTO_INCREMENT, - parent_id BIGINT(20) UNSIGNED DEFAULT 0, -- for subscription order, store subscription record id - transaction_id VARCHAR(255) COMMENT 'Transaction id from payment gateway', - user_id BIGINT(20) UNSIGNED NOT NULL, - order_type VARCHAR(50) NOT NULL, -- single_order, subscription - order_status VARCHAR(50) NOT NULL, - payment_status VARCHAR(50) NOT NULL, - subtotal_price DECIMAL(13, 2) NOT NULL, -- price calculation based on course sale price - pre_tax_price DECIMAL(13, 2) NOT NULL, -- total price before adding tax - tax_type VARCHAR(50), - tax_rate DECIMAL(13, 2) COMMENT 'Tax percentage', - tax_amount DECIMAL(13, 2), - total_price DECIMAL(13, 2) NOT NULL, -- final price - net_payment DECIMAL(13, 2) NOT NULL, -- calculated price if any refund is done else same as total_price - coupon_code VARCHAR(255), - coupon_amount DECIMAL(13, 2), - discount_type ENUM('percentage', 'flat') DEFAULT NULL, - discount_amount DECIMAL(13, 2), - discount_reason TEXT, - fees DECIMAL(13, 2), -- payment gateway fees - earnings DECIMAL(13, 2), -- net earning - refund_amount DECIMAL(13, 2), -- Refund amount - payment_method VARCHAR(255), - payment_payloads LONGTEXT, - note TEXT, - created_at_gmt DATETIME NOT NULL, - created_by BIGINT(20) UNSIGNED NOT NULL, - updated_at_gmt DATETIME, - updated_by BIGINT(20) UNSIGNED NOT NULL, - PRIMARY KEY (id), - KEY user_id (user_id), - KEY order_type (order_type), - KEY payment_status (payment_status), - KEY order_status (order_status), - KEY transaction_id (transaction_id) - ) $charset_collate;"; - - $order_meta_table = "CREATE TABLE {$wpdb->prefix}tutor_ordermeta ( - id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, - order_id BIGINT(20) UNSIGNED NOT NULL, - meta_key VARCHAR(255) NOT NULL, - meta_value LONGTEXT NOT NULL, - created_at_gmt DATETIME NOT NULL, - created_by BIGINT(20) UNSIGNED NOT NULL, - updated_at_gmt DATETIME, - updated_by BIGINT(20) UNSIGNED NOT NULL, - PRIMARY KEY (id), - KEY order_id (order_id), - KEY meta_key (meta_key), - CONSTRAINT fk_tutor_ordermeta_order_id FOREIGN KEY (order_id) REFERENCES {$wpdb->prefix}tutor_orders(id) ON DELETE CASCADE - ) $charset_collate;"; - - $order_items_table = "CREATE TABLE {$wpdb->prefix}tutor_order_items ( - id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, - order_id BIGINT(20) UNSIGNED NOT NULL, - item_id BIGINT(20) UNSIGNED NOT NULL, -- course id/plan id - regular_price DECIMAL(13, 2) NOT NULL, -- course regular price - sale_price VARCHAR(13) DEFAULT NULL, -- course sale price - discount_price VARCHAR(13) DEFAULT NULL, -- course discount price - coupon_code VARCHAR(255) DEFAULT NULL, -- coupon code - PRIMARY KEY (id), - KEY order_id (order_id), - KEY item_id (item_id), - CONSTRAINT fk_tutor_order_item_order_id FOREIGN KEY (order_id) REFERENCES {$wpdb->prefix}tutor_orders(id) ON DELETE CASCADE - ) $charset_collate;"; - - $coupons_table = "CREATE TABLE {$wpdb->prefix}tutor_coupons ( - id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, - coupon_status VARCHAR(50), - coupon_type VARCHAR(100) DEFAULT 'code', -- coupon type 'code' or 'automatic' - coupon_code VARCHAR(50) NOT NULL, - coupon_title VARCHAR(255) NOT NULL, - coupon_description TEXT, - discount_type ENUM('percentage', 'flat') NOT NULL, - discount_amount DECIMAL(13, 2) NOT NULL, - applies_to VARCHAR(100) DEFAULT 'all_courses_and_bundles', -- possible values 'all_courses_and_bundles', 'all_courses', 'all_bundles', 'specific_courses', 'specific_bundles', 'specific_category' - total_usage_limit INT(10) UNSIGNED DEFAULT NULL, -- null for unlimited usage - per_user_usage_limit TINYINT(4) UNSIGNED DEFAULT NULL, -- null for unlimited usage - purchase_requirement VARCHAR(50) DEFAULT 'no_minimum', -- possible values 'no_minimum', 'minimum_purchase', 'minimum_quantity' - purchase_requirement_value DECIMAL(13, 2), - start_date_gmt DATETIME NOT NULL, - expire_date_gmt DATETIME DEFAULT NULL, - created_at_gmt DATETIME NOT NULL, - created_by BIGINT(20) UNSIGNED NOT NULL, - updated_at_gmt DATETIME, - updated_by BIGINT(20) UNSIGNED NOT NULL, - PRIMARY KEY (id), - UNIQUE KEY coupon_code (coupon_code), - KEY start_date_gmt (start_date_gmt), - KEY expire_date_gmt (expire_date_gmt) - ) $charset_collate;"; - - $coupon_applications_table = "CREATE TABLE {$wpdb->prefix}tutor_coupon_applications ( - coupon_code VARCHAR(50) NOT NULL, - reference_id BIGINT(20) UNSIGNED NOT NULL, - KEY coupon_code (coupon_code), - KEY reference_id (reference_id), - CONSTRAINT fk_tutor_coupon_application_coupon_code FOREIGN KEY (coupon_code) REFERENCES {$wpdb->prefix}tutor_coupons(coupon_code) ON DELETE CASCADE - ) $charset_collate;"; - - $coupon_usage_table = self::get_coupon_usage_table_schema( true ); - - $cart_table = "CREATE TABLE {$wpdb->prefix}tutor_carts ( - id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, - user_id BIGINT(20) UNSIGNED DEFAULT NULL, - coupon_code VARCHAR(50) DEFAULT NULL, - created_at_gmt DATETIME NOT NULL, - updated_at_gmt DATETIME, - PRIMARY KEY (id), - KEY user_id (user_id), - KEY coupon_code (coupon_code), - CONSTRAINT fk_tutor_cart_user_id FOREIGN KEY (user_id) REFERENCES {$wpdb->prefix}users(ID) ON DELETE CASCADE - ) $charset_collate;"; - - $cart_items_table = "CREATE TABLE {$wpdb->prefix}tutor_cart_items ( - id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, - cart_id BIGINT(20) UNSIGNED NOT NULL, - course_id BIGINT(20) UNSIGNED NOT NULL, - PRIMARY KEY (id), - KEY cart_id (cart_id), - KEY course_id (course_id), - CONSTRAINT fk_tutor_cart_item_cart_id FOREIGN KEY (cart_id) REFERENCES {$wpdb->prefix}tutor_carts(id) ON DELETE CASCADE, - CONSTRAINT fk_tutor_cart_item_course_id FOREIGN KEY (course_id) REFERENCES {$wpdb->prefix}posts(ID) ON DELETE CASCADE - ) $charset_collate;"; - - $customer_table = "CREATE TABLE {$wpdb->prefix}tutor_customers ( - id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, - user_id BIGINT(20) UNSIGNED DEFAULT NULL, - billing_first_name VARCHAR(255) NOT NULL, - billing_last_name VARCHAR(255) NOT NULL, - billing_email VARCHAR(255) NOT NULL, - billing_phone VARCHAR(20) NOT NULL, - billing_zip_code VARCHAR(20) NOT NULL, - billing_address TEXT NOT NULL, - billing_country VARCHAR(100) NOT NULL, - billing_state VARCHAR(100) NOT NULL, - billing_city VARCHAR(100) NOT NULL, - PRIMARY KEY (id), - KEY user_id (user_id), - KEY billing_email (billing_email) - ) $charset_collate;"; - - require_once ABSPATH . 'wp-admin/includes/upgrade.php'; - dbDelta( $quiz_attempts_sql ); - dbDelta( $quiz_attempt_answers ); - dbDelta( $tutor_quiz_questions ); - dbDelta( $tutor_quiz_question_answers ); - dbDelta( $earning_table ); - dbDelta( $withdraw_table ); - dbDelta( $orders_table ); - dbDelta( $order_meta_table ); - dbDelta( $order_items_table ); - dbDelta( $coupons_table ); - dbDelta( $coupon_applications_table ); - dbDelta( $coupon_usage_table ); - dbDelta( $cart_table ); - dbDelta( $cart_items_table ); - dbDelta( $customer_table ); - } - - /** - * Get coupon usage table schema. - * - * @since 4.2.0 - * - * @param bool $include_constraints Whether to include FOREIGN KEY constraints (for fresh installs). - * - * @return string - */ - public static function get_coupon_usage_table_schema( bool $include_constraints = true ): string { - global $wpdb; - - $charset_collate = $wpdb->get_charset_collate(); - $status_consumed = 'consumed'; - - $constraints = ''; - if ( $include_constraints ) { - $constraints = ", - CONSTRAINT fk_tutor_coupon_usage_coupon_code FOREIGN KEY (coupon_code) REFERENCES {$wpdb->prefix}tutor_coupons(coupon_code) ON DELETE CASCADE, - CONSTRAINT fk_tutor_coupon_usage_user_id FOREIGN KEY (user_id) REFERENCES {$wpdb->prefix}users(ID) ON DELETE CASCADE"; - } - - return "CREATE TABLE {$wpdb->prefix}tutor_coupon_usages ( - id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, - coupon_code VARCHAR(50) NOT NULL, - user_id BIGINT(20) UNSIGNED NOT NULL, - order_id BIGINT(20) UNSIGNED DEFAULT NULL, - status VARCHAR(20) NOT NULL DEFAULT '{$status_consumed}', - expires_at_gmt DATETIME DEFAULT NULL, - created_at_gmt DATETIME NOT NULL, - PRIMARY KEY (id), - UNIQUE KEY coupon_order (coupon_code, order_id), - KEY coupon_code (coupon_code), - KEY user_id (user_id), - KEY order_id (order_id), - KEY status (status){$constraints} - ) {$charset_collate};"; + TableManager::create_core_tables( true ); } /** @@ -1450,10 +1145,8 @@ public static function erase_tutor_data() { $wpdb->delete( $wpdb->usermeta, array( 'meta_key' => '_is_tutor_instructor' ) ); $wpdb->query( "DELETE FROM {$wpdb->usermeta} WHERE meta_key LIKE '%_tutor_completed_lesson_id_%' " ); - // Deleting Table. - $prefix = $wpdb->prefix; - //phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared - $wpdb->query( "DROP TABLE IF EXISTS {$prefix}tutor_quiz_attempts, {$prefix}tutor_quiz_attempt_answers, {$prefix}tutor_quiz_questions, {$prefix}tutor_quiz_question_answers, {$prefix}tutor_earnings, {$prefix}tutor_withdraws " ); + // Deleting Tables. + TableManager::drop_tables(); } } diff --git a/classes/Upgrader.php b/classes/Upgrader.php index 7fd5db5b5b..ae21b70348 100644 --- a/classes/Upgrader.php +++ b/classes/Upgrader.php @@ -10,6 +10,8 @@ namespace TUTOR; +use Tutor\Core\DB; +use Tutor\Database\Schema; use Tutor\Database\TableManager; use Tutor\Ecommerce\CartController; use Tutor\Ecommerce\CheckoutController; @@ -341,9 +343,8 @@ public function upgrade_to_3_8_2() { * @return void */ public function upgrade_to_4_2_0() { - if ( QueryHelper::table_exists( 'tutor_coupon_usages' ) && ! QueryHelper::column_exist( 'tutor_coupon_usages', 'order_id' ) ) { - require_once ABSPATH . 'wp-admin/includes/upgrade.php'; - dbDelta( Tutor::get_coupon_usage_table_schema( false ) ); + if ( DB::has_table( 'tutor_coupon_usages' ) && ! DB::has_column( 'tutor_coupon_usages', 'order_id' ) ) { + TableManager::create_table( Schema::get_coupon_usages_schema( false ) ); } } diff --git a/composer.json b/composer.json index 0760a57abc..5c215fcccb 100644 --- a/composer.json +++ b/composer.json @@ -5,6 +5,7 @@ "autoload": { "psr-4": { "TUTOR\\": "classes/", + "Tutor\\Database\\": "database/", "Tutor\\Core\\": "core/", "Tutor\\Components\\": "components/", "Tutor\\Cache\\": "cache/", diff --git a/database/Schema.php b/database/Schema.php new file mode 100644 index 0000000000..66d2c9f9e7 --- /dev/null +++ b/database/Schema.php @@ -0,0 +1,667 @@ + + * @link https://themeum.com + * @since 4.3.0 + */ + +namespace Tutor\Database; + +use Tutor\Core\DB; + +defined( 'ABSPATH' ) || exit; + +/** + * Class Schemas + * + * @since 4.3.0 + */ +class Schema { + + /** + * Generate unique constraint name per blog prefix. + * Truncates to 64 chars (MySQL max identifier length) using md5 hash if needed. + * + * @since 4.3.0 + * + * @param string $name Base constraint name. + * + * @return string Unique constraint identifier. + */ + public static function fk_name( string $name ): string { + global $wpdb; + $fk = $wpdb->prefix . $name; + return strlen( $fk ) <= 64 ? $fk : 'fk_' . substr( md5( $fk ), 0, 32 ); + } + + /** + * Get only the Core schemas needed for initial site creation. + * Addon tables (gradebook, email queue, subscriptions) are excluded here. + * + * @since 4.3.0 + * + * @param bool $include_constraints Whether to include foreign key constraints. + * + * @return array + */ + public static function get_core_schemas( bool $include_constraints = true ): array { + return array( + self::get_quiz_attempts_schema( $include_constraints ), + self::get_quiz_attempt_answers_schema( $include_constraints ), + self::get_quiz_questions_schema( $include_constraints ), + self::get_quiz_question_answers_schema( $include_constraints ), + self::get_earnings_schema( $include_constraints ), + self::get_withdraws_schema( $include_constraints ), + self::get_orders_schema( $include_constraints ), + self::get_ordermeta_schema( $include_constraints ), + self::get_order_items_schema( $include_constraints ), + self::get_order_itemmeta_schema( $include_constraints ), + self::get_coupons_schema( $include_constraints ), + self::get_coupon_applications_schema( $include_constraints ), + self::get_coupon_usages_schema( $include_constraints ), + self::get_carts_schema( $include_constraints ), + self::get_cart_items_schema( $include_constraints ), + self::get_customers_schema( $include_constraints ), + self::get_scheduler_schema( $include_constraints ), + ); + } + + /** + * Get all tutor database schemas. + * + * @since 4.3.0 + * + * @param bool $include_constraints Whether to include foreign key constraints. + * + * @return array + */ + public static function get_all_schema( $include_constraints = true ): array { + $core_schema = static::get_core_schemas( $include_constraints ); + return apply_filters( 'tutor_database_schemas', $core_schema, $include_constraints ); + } + + /* ---------------- Core Schemas ---------------- */ + + /** + * Get quiz attempts schema. + * + * @since 4.3.0 + * + * @param bool $include_constraints Whether to include foreign key constraints. + * @return string + */ + public static function get_quiz_attempts_schema( bool $include_constraints = true ): string { + global $wpdb; + $table = DB::prepare_table_name( 'tutor_quiz_attempts' ); + $collate = $wpdb->get_charset_collate(); + + return "CREATE TABLE {$table} ( + attempt_id bigint(20) NOT NULL AUTO_INCREMENT, + course_id bigint(20) DEFAULT NULL, + quiz_id bigint(20) DEFAULT NULL, + user_id bigint(20) DEFAULT NULL, + total_questions int(11) DEFAULT NULL, + total_answered_questions int(11) DEFAULT NULL, + total_marks decimal(9,2) DEFAULT NULL, + earned_marks decimal(9,2) DEFAULT NULL, + attempt_info text, + attempt_status varchar(50) DEFAULT NULL, + attempt_ip varchar(250) DEFAULT NULL, + attempt_started_at datetime DEFAULT NULL, + attempt_ended_at datetime DEFAULT NULL, + is_manually_reviewed int(1) DEFAULT NULL, + manually_reviewed_at datetime DEFAULT NULL, + result varchar(10) DEFAULT NULL, + PRIMARY KEY (attempt_id), + INDEX (course_id), + INDEX (quiz_id), + INDEX (user_id), + INDEX (result) + ) {$collate};"; + } + + /** + * Get quiz attempt answers schema. + * + * @since 4.3.0 + * + * @param bool $include_constraints Whether to include foreign key constraints. + * @return string + */ + public static function get_quiz_attempt_answers_schema( bool $include_constraints = true ): string { + global $wpdb; + $table = DB::prepare_table_name( 'tutor_quiz_attempt_answers' ); + $collate = $wpdb->get_charset_collate(); + + return "CREATE TABLE {$table} ( + attempt_answer_id bigint(20) NOT NULL AUTO_INCREMENT, + user_id bigint(20) DEFAULT NULL, + quiz_id bigint(20) DEFAULT NULL, + question_id bigint(20) DEFAULT NULL, + quiz_attempt_id bigint(20) DEFAULT NULL, + given_answer longtext, + question_mark decimal(8,2) DEFAULT NULL, + achieved_mark decimal(8,2) DEFAULT NULL, + minus_mark decimal(8,2) DEFAULT NULL, + is_correct tinyint(4) DEFAULT NULL, + PRIMARY KEY (attempt_answer_id) + ) {$collate};"; + } + + /** + * Get quiz questions schema. + * + * @since 4.3.0 + * + * @param bool $include_constraints Whether to include foreign key constraints. + * @return string + */ + public static function get_quiz_questions_schema( bool $include_constraints = true ): string { + global $wpdb; + $table = DB::prepare_table_name( 'tutor_quiz_questions' ); + $collate = $wpdb->get_charset_collate(); + + return "CREATE TABLE {$table} ( + question_id bigint(20) NOT NULL AUTO_INCREMENT, + quiz_id bigint(20) DEFAULT NULL, + question_title text, + question_description longtext, + answer_explanation longtext DEFAULT '', + question_type varchar(50) DEFAULT NULL, + question_mark decimal(9,2) DEFAULT NULL, + question_settings longtext, + question_order int(11) DEFAULT NULL, + PRIMARY KEY (question_id) + ) {$collate};"; + } + + /** + * Get quiz question answers schema. + * + * @since 4.3.0 + * + * @param bool $include_constraints Whether to include foreign key constraints. + * @return string + */ + public static function get_quiz_question_answers_schema( bool $include_constraints = true ): string { + global $wpdb; + $table = DB::prepare_table_name( 'tutor_quiz_question_answers' ); + $collate = $wpdb->get_charset_collate(); + + return "CREATE TABLE {$table} ( + answer_id bigint(20) NOT NULL AUTO_INCREMENT, + belongs_question_id bigint(20) DEFAULT NULL, + belongs_question_type varchar(250) DEFAULT NULL, + answer_title text, + is_correct tinyint(4) DEFAULT NULL, + image_id bigint(20) DEFAULT NULL, + answer_two_gap_match text, + answer_view_format varchar(250) DEFAULT NULL, + answer_settings text, + answer_order int(11) DEFAULT '0', + PRIMARY KEY (answer_id) + ) {$collate};"; + } + + /** + * Get earnings schema. + * + * @since 4.3.0 + * + * @param bool $include_constraints Whether to include foreign key constraints. + * @return string + */ + public static function get_earnings_schema( bool $include_constraints = true ): string { + global $wpdb; + $table = DB::prepare_table_name( 'tutor_earnings' ); + $collate = $wpdb->get_charset_collate(); + + return "CREATE TABLE IF NOT EXISTS {$table} ( + earning_id bigint(20) NOT NULL AUTO_INCREMENT, + user_id bigint(20) DEFAULT NULL, + course_id bigint(20) DEFAULT NULL, + order_id bigint(20) DEFAULT NULL, + order_status varchar(50) DEFAULT NULL, + course_price_total decimal(16,2) DEFAULT NULL, + course_price_grand_total decimal(16,2) DEFAULT NULL, + instructor_amount decimal(16,2) DEFAULT NULL, + instructor_rate decimal(16,2) DEFAULT NULL, + admin_amount decimal(16,2) DEFAULT NULL, + admin_rate decimal(16,2) DEFAULT NULL, + commission_type varchar(20) DEFAULT NULL, + deduct_fees_amount decimal(16,2) DEFAULT NULL, + deduct_fees_name varchar(250) DEFAULT NULL, + deduct_fees_type varchar(20) DEFAULT NULL, + process_by varchar(20) DEFAULT NULL, + created_at datetime DEFAULT NULL, + PRIMARY KEY (earning_id), + INDEX (user_id), + INDEX (course_id), + INDEX (order_id), + INDEX (process_by) + ) {$collate};"; + } + + /** + * Get withdraws schema. + * + * @since 4.3.0 + * + * @param bool $include_constraints Whether to include foreign key constraints. + * @return string + */ + public static function get_withdraws_schema( bool $include_constraints = true ): string { + global $wpdb; + $table = DB::prepare_table_name( 'tutor_withdraws' ); + $collate = $wpdb->get_charset_collate(); + + return "CREATE TABLE IF NOT EXISTS {$table} ( + withdraw_id bigint(20) NOT NULL AUTO_INCREMENT, + user_id bigint(20) DEFAULT NULL, + amount decimal(16,2) DEFAULT NULL, + method_data text DEFAULT NULL, + status varchar(50) DEFAULT NULL, + updated_at datetime DEFAULT NULL, + created_at datetime DEFAULT NULL, + PRIMARY KEY (withdraw_id) + ) {$collate};"; + } + + /** + * Get orders schema. + * + * @since 4.3.0 + * + * @param bool $include_constraints Whether to include foreign key constraints. + * @return string + */ + public static function get_orders_schema( bool $include_constraints = true ): string { + global $wpdb; + $table = DB::prepare_table_name( 'tutor_orders' ); + $collate = $wpdb->get_charset_collate(); + + return "CREATE TABLE {$table} ( + id BIGINT(20) UNSIGNED AUTO_INCREMENT, + parent_id BIGINT(20) UNSIGNED DEFAULT 0, + transaction_id VARCHAR(255), + user_id BIGINT(20) UNSIGNED NOT NULL, + order_type VARCHAR(50) NOT NULL, + order_status VARCHAR(50) NOT NULL, + payment_status VARCHAR(50) NOT NULL, + subtotal_price DECIMAL(13, 2) NOT NULL, + pre_tax_price DECIMAL(13, 2) NOT NULL, + tax_type VARCHAR(50), + tax_rate DECIMAL(13, 2), + tax_amount DECIMAL(13, 2), + total_price DECIMAL(13, 2) NOT NULL, + net_payment DECIMAL(13, 2) NOT NULL, + coupon_code VARCHAR(255), + coupon_amount DECIMAL(13, 2), + discount_type ENUM('percentage', 'flat') DEFAULT NULL, + discount_amount DECIMAL(13, 2), + discount_reason TEXT, + fees DECIMAL(13, 2), + earnings DECIMAL(13, 2), + refund_amount DECIMAL(13, 2), + payment_method VARCHAR(255), + payment_payloads LONGTEXT, + note TEXT, + created_at_gmt DATETIME NOT NULL, + created_by BIGINT(20) UNSIGNED NOT NULL, + updated_at_gmt DATETIME, + updated_by BIGINT(20) UNSIGNED NOT NULL, + PRIMARY KEY (id), + KEY user_id (user_id), + KEY order_type (order_type), + KEY payment_status (payment_status), + KEY order_status (order_status), + KEY transaction_id (transaction_id) + ) {$collate};"; + } + + /** + * Get ordermeta schema. + * + * @since 4.3.0 + * + * @param bool $include_constraints Whether to include foreign key constraints. + * @return string + */ + public static function get_ordermeta_schema( bool $include_constraints = true ): string { + global $wpdb; + $table = DB::prepare_table_name( 'tutor_ordermeta' ); + $orders_table = DB::prepare_table_name( 'tutor_orders' ); + $collate = $wpdb->get_charset_collate(); + + $constraints = ''; + if ( $include_constraints ) { + $fk_name = self::fk_name( 'fk_tutor_ordermeta_order_id' ); + $constraints = ", CONSTRAINT {$fk_name} FOREIGN KEY (order_id) REFERENCES {$orders_table}(id) ON DELETE CASCADE"; + } + + return "CREATE TABLE {$table} ( + id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, + order_id BIGINT(20) UNSIGNED NOT NULL, + meta_key VARCHAR(255) NOT NULL, + meta_value LONGTEXT NOT NULL, + created_at_gmt DATETIME NOT NULL, + created_by BIGINT(20) UNSIGNED NOT NULL, + updated_at_gmt DATETIME, + updated_by BIGINT(20) UNSIGNED NOT NULL, + PRIMARY KEY (id), + KEY order_id (order_id), + KEY meta_key (meta_key){$constraints} + ) {$collate};"; + } + + /** + * Get order items schema. + * + * @since 4.3.0 + * + * @param bool $include_constraints Whether to include foreign key constraints. + * @return string + */ + public static function get_order_items_schema( bool $include_constraints = true ): string { + global $wpdb; + $table = DB::prepare_table_name( 'tutor_order_items' ); + $orders_table = DB::prepare_table_name( 'tutor_orders' ); + $collate = $wpdb->get_charset_collate(); + + $constraints = ''; + if ( $include_constraints ) { + $fk_name = self::fk_name( 'fk_tutor_order_item_order_id' ); + $constraints = ", CONSTRAINT {$fk_name} FOREIGN KEY (order_id) REFERENCES {$orders_table}(id) ON DELETE CASCADE"; + } + + return "CREATE TABLE {$table} ( + id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, + order_id BIGINT(20) UNSIGNED NOT NULL, + item_id BIGINT(20) UNSIGNED NOT NULL, + regular_price DECIMAL(13, 2) NOT NULL, + sale_price VARCHAR(13) DEFAULT NULL, + discount_price VARCHAR(13) DEFAULT NULL, + coupon_code VARCHAR(255) DEFAULT NULL, + PRIMARY KEY (id), + KEY order_id (order_id), + KEY item_id (item_id){$constraints} + ) {$collate};"; + } + + /** + * Get order itemmeta schema. + * + * @since 4.3.0 + * + * @param bool $include_constraints Whether to include foreign key constraints. + * @return string + */ + public static function get_order_itemmeta_schema( bool $include_constraints = true ): string { + global $wpdb; + $table = DB::prepare_table_name( 'tutor_order_itemmeta' ); + $order_items_table = DB::prepare_table_name( 'tutor_order_items' ); + $collate = $wpdb->get_charset_collate(); + + $constraints = ''; + if ( $include_constraints ) { + $fk_name = self::fk_name( 'fk_tutor_itemmeta' ); + $constraints = ", CONSTRAINT {$fk_name} FOREIGN KEY (item_id) REFERENCES {$order_items_table}(id) ON DELETE CASCADE"; + } + + return "CREATE TABLE {$table} ( + id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, + item_id BIGINT(20) UNSIGNED NOT NULL, + meta_key VARCHAR(255) NOT NULL, + meta_value LONGTEXT NOT NULL, + PRIMARY KEY (id), + KEY item_id (item_id), + KEY meta_key (meta_key){$constraints} + ) {$collate};"; + } + + /** + * Get coupons schema. + * + * @since 4.3.0 + * + * @param bool $include_constraints Whether to include foreign key constraints. + * @return string + */ + public static function get_coupons_schema( bool $include_constraints = true ): string { + global $wpdb; + $table = DB::prepare_table_name( 'tutor_coupons' ); + $collate = $wpdb->get_charset_collate(); + + return "CREATE TABLE {$table} ( + id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, + coupon_status VARCHAR(50), + coupon_type VARCHAR(100) DEFAULT 'code', + coupon_code VARCHAR(50) NOT NULL, + coupon_title VARCHAR(255) NOT NULL, + coupon_description TEXT, + discount_type ENUM('percentage', 'flat') NOT NULL, + discount_amount DECIMAL(13, 2) NOT NULL, + applies_to VARCHAR(100) DEFAULT 'all_courses_and_bundles', + total_usage_limit INT(10) UNSIGNED DEFAULT NULL, + per_user_usage_limit TINYINT(4) UNSIGNED DEFAULT NULL, + purchase_requirement VARCHAR(50) DEFAULT 'no_minimum', + purchase_requirement_value DECIMAL(13, 2), + start_date_gmt DATETIME NOT NULL, + expire_date_gmt DATETIME DEFAULT NULL, + created_at_gmt DATETIME NOT NULL, + created_by BIGINT(20) UNSIGNED NOT NULL, + updated_at_gmt DATETIME, + updated_by BIGINT(20) UNSIGNED NOT NULL, + PRIMARY KEY (id), + UNIQUE KEY coupon_code (coupon_code), + KEY start_date_gmt (start_date_gmt), + KEY expire_date_gmt (expire_date_gmt) + ) {$collate};"; + } + + /** + * Get coupon applications schema. + * + * @since 4.3.0 + * + * @param bool $include_constraints Whether to include foreign key constraints. + * @return string + */ + public static function get_coupon_applications_schema( bool $include_constraints = true ): string { + global $wpdb; + $table = DB::prepare_table_name( 'tutor_coupon_applications' ); + $coupons_table = DB::prepare_table_name( 'tutor_coupons' ); + $collate = $wpdb->get_charset_collate(); + + $constraints = ''; + if ( $include_constraints ) { + $fk_name = self::fk_name( 'fk_tutor_coupon_application_coupon_code' ); + $constraints = ", CONSTRAINT {$fk_name} FOREIGN KEY (coupon_code) REFERENCES {$coupons_table}(coupon_code) ON DELETE CASCADE"; + } + + return "CREATE TABLE {$table} ( + coupon_code VARCHAR(50) NOT NULL, + reference_id BIGINT(20) UNSIGNED NOT NULL, + KEY coupon_code (coupon_code), + KEY reference_id (reference_id){$constraints} + ) {$collate};"; + } + + /** + * Get coupon usages schema. + * + * @since 4.3.0 + * + * @param bool $include_constraints Whether to include foreign key constraints. + * @return string + */ + public static function get_coupon_usages_schema( bool $include_constraints = true ): string { + global $wpdb; + $table = DB::prepare_table_name( 'tutor_coupon_usages' ); + $coupons_table = DB::prepare_table_name( 'tutor_coupons' ); + $users_table = DB::prepare_table_name( 'users' ); + $collate = $wpdb->get_charset_collate(); + $status_consumed = 'consumed'; + + $constraints = ''; + if ( $include_constraints ) { + $fk_coupon = self::fk_name( 'fk_tutor_coupon_usage_coupon_code' ); + $fk_user = self::fk_name( 'fk_tutor_coupon_usage_user_id' ); + $constraints = ", + CONSTRAINT {$fk_coupon} FOREIGN KEY (coupon_code) REFERENCES {$coupons_table}(coupon_code) ON DELETE CASCADE, + CONSTRAINT {$fk_user} FOREIGN KEY (user_id) REFERENCES {$users_table}(ID) ON DELETE CASCADE"; + } + + return "CREATE TABLE {$table} ( + id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, + coupon_code VARCHAR(50) NOT NULL, + user_id BIGINT(20) UNSIGNED NOT NULL, + order_id BIGINT(20) UNSIGNED DEFAULT NULL, + status VARCHAR(20) NOT NULL DEFAULT '{$status_consumed}', + expires_at_gmt DATETIME DEFAULT NULL, + created_at_gmt DATETIME NOT NULL, + PRIMARY KEY (id), + UNIQUE KEY coupon_order (coupon_code, order_id), + KEY coupon_code (coupon_code), + KEY user_id (user_id), + KEY order_id (order_id), + KEY status (status){$constraints} + ) {$collate};"; + } + + /** + * Get carts schema. + * + * @since 4.3.0 + * + * @param bool $include_constraints Whether to include foreign key constraints. + * @return string + */ + public static function get_carts_schema( bool $include_constraints = true ): string { + global $wpdb; + $table = DB::prepare_table_name( 'tutor_carts' ); + $users_table = DB::prepare_table_name( 'users' ); + $collate = $wpdb->get_charset_collate(); + + $constraints = ''; + if ( $include_constraints ) { + $fk_user = self::fk_name( 'fk_tutor_cart_user_id' ); + $constraints = ", CONSTRAINT {$fk_user} FOREIGN KEY (user_id) REFERENCES {$users_table}(ID) ON DELETE CASCADE"; + } + + return "CREATE TABLE {$table} ( + id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, + user_id BIGINT(20) UNSIGNED DEFAULT NULL, + coupon_code VARCHAR(50) DEFAULT NULL, + created_at_gmt DATETIME NOT NULL, + updated_at_gmt DATETIME, + PRIMARY KEY (id), + KEY user_id (user_id), + KEY coupon_code (coupon_code){$constraints} + ) {$collate};"; + } + + /** + * Get cart items schema. + * + * @since 4.3.0 + * + * @param bool $include_constraints Whether to include foreign key constraints. + * @return string + */ + public static function get_cart_items_schema( bool $include_constraints = true ): string { + global $wpdb; + $table = DB::prepare_table_name( 'tutor_cart_items' ); + $carts_table = DB::prepare_table_name( 'tutor_carts' ); + $posts_table = DB::prepare_table_name( 'posts' ); + $collate = $wpdb->get_charset_collate(); + + $constraints = ''; + if ( $include_constraints ) { + $fk_cart = self::fk_name( 'fk_tutor_cart_item_cart_id' ); + $fk_post = self::fk_name( 'fk_tutor_cart_item_course_id' ); + $constraints = ", + CONSTRAINT {$fk_cart} FOREIGN KEY (cart_id) REFERENCES {$carts_table}(id) ON DELETE CASCADE, + CONSTRAINT {$fk_post} FOREIGN KEY (course_id) REFERENCES {$posts_table}(ID) ON DELETE CASCADE"; + } + + return "CREATE TABLE {$table} ( + id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, + cart_id BIGINT(20) UNSIGNED NOT NULL, + course_id BIGINT(20) UNSIGNED NOT NULL, + item_type VARCHAR(255), + item_details JSON, + PRIMARY KEY (id), + KEY cart_id (cart_id), + KEY course_id (course_id){$constraints} + ) {$collate};"; + } + + /** + * Get customers schema. + * + * @since 4.3.0 + * + * @param bool $include_constraints Whether to include foreign key constraints. + * @return string + */ + public static function get_customers_schema( bool $include_constraints = true ): string { + global $wpdb; + $table = DB::prepare_table_name( 'tutor_customers' ); + $collate = $wpdb->get_charset_collate(); + + return "CREATE TABLE {$table} ( + id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, + user_id BIGINT(20) UNSIGNED DEFAULT NULL, + billing_first_name VARCHAR(255) NOT NULL, + billing_last_name VARCHAR(255) NOT NULL, + billing_email VARCHAR(255) NOT NULL, + billing_phone VARCHAR(20) NOT NULL, + billing_zip_code VARCHAR(20) NOT NULL, + billing_address TEXT NOT NULL, + billing_country VARCHAR(100) NOT NULL, + billing_state VARCHAR(100) NOT NULL, + billing_city VARCHAR(100) NOT NULL, + PRIMARY KEY (id), + KEY user_id (user_id), + KEY billing_email (billing_email) + ) {$collate};"; + } + + /** + * Get scheduler schema. + * + * @since 4.3.0 + * + * @param bool $include_constraints Whether to include foreign key constraints. + * @return string + */ + public static function get_scheduler_schema( bool $include_constraints = true ): string { + global $wpdb; + $table = DB::prepare_table_name( 'tutor_scheduler' ); + $collate = $wpdb->get_charset_collate(); + + return "CREATE TABLE {$table} ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + type VARCHAR(50) NOT NULL COMMENT 'Type of schedule, e.g., gift, email, reminder', + reference_id VARCHAR(255) NOT NULL COMMENT 'Unique reference id, token, etc', + scheduled_at_gmt DATETIME NOT NULL COMMENT 'When the action should be executed', + status VARCHAR(255) NOT NULL DEFAULT 'processing', + payload LONGTEXT, + created_at_gmt DATETIME, + updated_at_gmt DATETIME, + scheduled_by BIGINT UNSIGNED COMMENT 'User who scheduled the action', + scheduled_for BIGINT UNSIGNED COMMENT 'Target user of the scheduled action', + PRIMARY KEY (id), + KEY idx_context_status (type, status), + KEY idx_status (status), + KEY idx_scheduled_at_gmt (scheduled_at_gmt) + ) {$collate};"; + } +} diff --git a/database/TableManager.php b/database/TableManager.php new file mode 100644 index 0000000000..cad9a9cde6 --- /dev/null +++ b/database/TableManager.php @@ -0,0 +1,161 @@ + + * @link https://themeum.com + * @since 4.3.0 + */ + +namespace Tutor\Database; + +use Tutor\Core\DB; + +defined( 'ABSPATH' ) || exit; + +/** + * Class SchemaManager + * + * @since 4.3.0 + */ +class TableManager { + /** + * Core tables created on initial installation or new subsite provisioning. + * + * @var array Key => table base name + */ + const CORE_TABLES = array( + 'quiz_attempts' => 'tutor_quiz_attempts', + 'quiz_attempt_answers' => 'tutor_quiz_attempt_answers', + 'quiz_questions' => 'tutor_quiz_questions', + 'quiz_question_answers' => 'tutor_quiz_question_answers', + 'earnings' => 'tutor_earnings', + 'withdraws' => 'tutor_withdraws', + 'orders' => 'tutor_orders', + 'ordermeta' => 'tutor_ordermeta', + 'order_items' => 'tutor_order_items', + 'order_itemmeta' => 'tutor_order_itemmeta', + 'coupons' => 'tutor_coupons', + 'coupon_applications' => 'tutor_coupon_applications', + 'coupon_usages' => 'tutor_coupon_usages', + 'carts' => 'tutor_carts', + 'cart_items' => 'tutor_cart_items', + 'customers' => 'tutor_customers', + 'scheduler' => 'tutor_scheduler', + ); + + /** + * Get all known tables (Core + Addons + Pro via filter). + * Used for drop/cleanup operations across single-site and multisite. + * + * @since 4.3.0 + * + * @return array Key => base name + */ + public static function get_tables(): array { + /** + * Filter to register additional addon tables from Pro and third-party addons. + * + * @since 4.3.0 + * + * @param array $all_tables Array of key => base table name. + */ + return apply_filters( 'tutor_database_tables', self::CORE_TABLES ); + } + + /** + * Create or update a single table using dbDelta. + * Reused across core tables, upgrade routines, and addon installers. + * + * @since 4.3.0 + * + * @param string $schema CREATE TABLE SQL statement. + * + * @return void + */ + public static function create_table( string $schema ): void { + require_once ABSPATH . 'wp-admin/includes/upgrade.php'; + dbDelta( $schema ); + } + + /** + * Create only the Core tables for the current active blog context. + * Called on plugin activation and new subsite provisioning. + * + * @since 4.3.0 + * + * @param bool $include_constraints Whether to include foreign key constraints. + * + * @return void + */ + public static function create_core_tables( bool $include_constraints = true ): void { + $schemas = Schema::get_core_schemas( $include_constraints ); + + foreach ( $schemas as $sql ) { + self::create_table( $sql ); + } + + /** + * Action fired after all Tutor Core tables have been created for the current blog. + * + * @since 4.3.0 + * + * @param bool $include_constraints Whether foreign key constraints were included. + */ + do_action( 'tutor_database_core_tables_created', $include_constraints ); + } + + /** + * Create all tutor and tutor-pro (filtered by) table. + * + * @since 4.3.0 + * + * @param bool $include_constraints Whether to include foreign key constraints. + * + * @return void + */ + public static function create_tables( bool $include_constraints = true ):void { + $schemas = Schema::get_all_schema( $include_constraints ); + foreach ( $schemas as $sql ) { + self::create_table( $sql ); + } + + do_action( 'tutor_database_tables_created', $include_constraints ); + } + + /** + * Safely drop all known Tutor tables for the current active blog context. + * Drops both Core and Addon tables using SET FOREIGN_KEY_CHECKS = 0. + * + * @since 4.3.0 + * + * @return void + */ + public static function drop_tables(): void { + global $wpdb; + + $tables = self::get_tables(); + + // Temporarily disable FK checks to cleanly drop without constraint order issues. + $wpdb->query( 'SET FOREIGN_KEY_CHECKS = 0' ); + + foreach ( $tables as $base_name ) { + $table_name = DB::prepare_table_name( $base_name ); + $wpdb->query( "DROP TABLE IF EXISTS `{$table_name}`" ); //phpcs:ignore + } + + $wpdb->query( 'SET FOREIGN_KEY_CHECKS = 1' ); + + /** + * Action fired after Tutor tables have been dropped for the current blog. + * + * @since 4.3.0 + */ + do_action( 'tutor_database_tables_dropped' ); + } +} + diff --git a/tests/phpunit/CouponModelTest.php b/tests/phpunit/CouponModelTest.php index 7f00635698..532b20a4e1 100644 --- a/tests/phpunit/CouponModelTest.php +++ b/tests/phpunit/CouponModelTest.php @@ -1,6 +1,7 @@ Date: Mon, 9 Nov 2026 16:59:45 +0600 Subject: [PATCH 05/36] refactor: update table registration and core table creation methods in TableManager --- classes/Multisite.php | 4 +-- classes/Tutor.php | 5 ++-- database/TableManager.php | 59 +++++++++++++++------------------------ 3 files changed, 26 insertions(+), 42 deletions(-) diff --git a/classes/Multisite.php b/classes/Multisite.php index c63a36251c..87dfc95ec9 100644 --- a/classes/Multisite.php +++ b/classes/Multisite.php @@ -56,7 +56,7 @@ public function on_initialize_site( \WP_Site $site, array $args = array() ): voi switch_to_blog( $blog_id ); // 1. Create all tables. - TableManager::create_tables( true ); + TableManager::create_core_tables( true ); // 2. Default options. $default_options = Tutor::default_options(); @@ -137,7 +137,7 @@ public static function activate_network(): void { foreach ( $site_ids as $blog_id ) { switch_to_blog( (int) $blog_id ); - TableManager::create_tables( true ); + TableManager::create_core_tables( true ); $version = get_option( 'tutor_version' ); if ( ! $version ) { diff --git a/classes/Tutor.php b/classes/Tutor.php index 4a6474e6de..30c7c59e73 100644 --- a/classes/Tutor.php +++ b/classes/Tutor.php @@ -462,9 +462,8 @@ public function __construct() { * @since 4.3.0 Dynamically registered from TableRegistry with multisite awareness. */ global $wpdb; - foreach ( TableManager::get_tables() as $key => $table_base_name ) { - $prop = 'tutor_' . $key; - $wpdb->$prop = DB::prepare_table_name( $table_base_name ); + foreach ( TableManager::get_tables() as $table_name ) { + $wpdb->$table_name = DB::prepare_table_name( $table_name ); } /** diff --git a/database/TableManager.php b/database/TableManager.php index cad9a9cde6..b4d896fe74 100644 --- a/database/TableManager.php +++ b/database/TableManager.php @@ -26,26 +26,26 @@ class TableManager { /** * Core tables created on initial installation or new subsite provisioning. * - * @var array Key => table base name + * @var array table name. */ const CORE_TABLES = array( - 'quiz_attempts' => 'tutor_quiz_attempts', - 'quiz_attempt_answers' => 'tutor_quiz_attempt_answers', - 'quiz_questions' => 'tutor_quiz_questions', - 'quiz_question_answers' => 'tutor_quiz_question_answers', - 'earnings' => 'tutor_earnings', - 'withdraws' => 'tutor_withdraws', - 'orders' => 'tutor_orders', - 'ordermeta' => 'tutor_ordermeta', - 'order_items' => 'tutor_order_items', - 'order_itemmeta' => 'tutor_order_itemmeta', - 'coupons' => 'tutor_coupons', - 'coupon_applications' => 'tutor_coupon_applications', - 'coupon_usages' => 'tutor_coupon_usages', - 'carts' => 'tutor_carts', - 'cart_items' => 'tutor_cart_items', - 'customers' => 'tutor_customers', - 'scheduler' => 'tutor_scheduler', + 'tutor_quiz_attempts', + 'tutor_quiz_attempt_answers', + 'tutor_quiz_questions', + 'tutor_quiz_question_answers', + 'tutor_earnings', + 'tutor_withdraws', + 'tutor_orders', + 'tutor_ordermeta', + 'tutor_order_items', + 'tutor_order_itemmeta', + 'tutor_coupons', + 'tutor_coupon_applications', + 'tutor_coupon_usages', + 'tutor_carts', + 'tutor_cart_items', + 'tutor_customers', + 'tutor_scheduler', ); /** @@ -78,7 +78,10 @@ public static function get_tables(): array { * @return void */ public static function create_table( string $schema ): void { - require_once ABSPATH . 'wp-admin/includes/upgrade.php'; + if ( ! function_exists( 'dbDelta' ) ) { + require_once ABSPATH . 'wp-admin/includes/upgrade.php'; + } + dbDelta( $schema ); } @@ -109,24 +112,6 @@ public static function create_core_tables( bool $include_constraints = true ): v do_action( 'tutor_database_core_tables_created', $include_constraints ); } - /** - * Create all tutor and tutor-pro (filtered by) table. - * - * @since 4.3.0 - * - * @param bool $include_constraints Whether to include foreign key constraints. - * - * @return void - */ - public static function create_tables( bool $include_constraints = true ):void { - $schemas = Schema::get_all_schema( $include_constraints ); - foreach ( $schemas as $sql ) { - self::create_table( $sql ); - } - - do_action( 'tutor_database_tables_created', $include_constraints ); - } - /** * Safely drop all known Tutor tables for the current active blog context. * Drops both Core and Addon tables using SET FOREIGN_KEY_CHECKS = 0. From 35ce716d6c30f7c88c939a15b41a86a909422c05 Mon Sep 17 00:00:00 2001 From: "Md.Harun-Ur-Rashid" Date: Tue, 10 Nov 2026 12:34:07 +0600 Subject: [PATCH 06/36] refactor: refactor database schemas into modular Table classes --- classes/Tutor.php | 17 +- classes/Upgrader.php | 9 +- core/Table.php | 134 ++++ database/Schema.php | 667 ------------------- database/TableManager.php | 113 +++- database/Tables/CartItemsTable.php | 67 ++ database/Tables/CartsTable.php | 63 ++ database/Tables/CouponApplicationsTable.php | 58 ++ database/Tables/CouponUsagesTable.php | 73 ++ database/Tables/CouponsTable.php | 70 ++ database/Tables/CustomersTable.php | 61 ++ database/Tables/EarningsTable.php | 69 ++ database/Tables/OrderItemmetaTable.php | 61 ++ database/Tables/OrderItemsTable.php | 64 ++ database/Tables/OrdermetaTable.php | 65 ++ database/Tables/OrdersTable.php | 82 +++ database/Tables/QuizAttemptAnswersTable.php | 58 ++ database/Tables/QuizAttemptsTable.php | 68 ++ database/Tables/QuizQuestionAnswersTable.php | 58 ++ database/Tables/QuizQuestionsTable.php | 57 ++ database/Tables/SchedulerTable.php | 61 ++ database/Tables/WithdrawsTable.php | 55 ++ tests/phpunit/CouponModelTest.php | 4 +- 23 files changed, 1318 insertions(+), 716 deletions(-) create mode 100644 core/Table.php delete mode 100644 database/Schema.php create mode 100644 database/Tables/CartItemsTable.php create mode 100644 database/Tables/CartsTable.php create mode 100644 database/Tables/CouponApplicationsTable.php create mode 100644 database/Tables/CouponUsagesTable.php create mode 100644 database/Tables/CouponsTable.php create mode 100644 database/Tables/CustomersTable.php create mode 100644 database/Tables/EarningsTable.php create mode 100644 database/Tables/OrderItemmetaTable.php create mode 100644 database/Tables/OrderItemsTable.php create mode 100644 database/Tables/OrdermetaTable.php create mode 100644 database/Tables/OrdersTable.php create mode 100644 database/Tables/QuizAttemptAnswersTable.php create mode 100644 database/Tables/QuizAttemptsTable.php create mode 100644 database/Tables/QuizQuestionAnswersTable.php create mode 100644 database/Tables/QuizQuestionsTable.php create mode 100644 database/Tables/SchedulerTable.php create mode 100644 database/Tables/WithdrawsTable.php diff --git a/classes/Tutor.php b/classes/Tutor.php index 30c7c59e73..5d51aeb62b 100644 --- a/classes/Tutor.php +++ b/classes/Tutor.php @@ -10,10 +10,11 @@ namespace TUTOR; +defined( 'ABSPATH' ) || exit; + use Tutor\Core\DB; use Tutor\Core\Input; use Tutor\Core\Singleton; -use Tutor\Database\Schema; use Tutor\Database\TableManager; use Tutor\Models\CourseModel; use Tutor\Ecommerce\Ecommerce; @@ -21,10 +22,6 @@ use Tutor\Helpers\QueryHelper; use Tutor\Migrations\Migration; -if ( ! defined( 'ABSPATH' ) ) { - exit; -} - /** * Tutor final class * @@ -460,10 +457,16 @@ public function __construct() { * * @since 1.4.2 * @since 4.3.0 Dynamically registered from TableRegistry with multisite awareness. + * @since 4.3.0 Registering tables dynamically like before. + * Example: + * $wpdb->tutor_courses = $wpdb->prefix . 'tutor_courses'; + * $wpdb->tutor_lessons = $wpdb->prefix . 'tutor_lessons'; + * $wpdb->tutor_quizzes = $wpdb->prefix . 'tutor_quizzes'; + * ... etc */ global $wpdb; - foreach ( TableManager::get_tables() as $table_name ) { - $wpdb->$table_name = DB::prepare_table_name( $table_name ); + foreach ( TableManager::get_table_classes() as $table_class ) { + $wpdb->{$table_class::get_base_name()} = $table_class::get_name(); } /** diff --git a/classes/Upgrader.php b/classes/Upgrader.php index ae21b70348..f74b7cc58b 100644 --- a/classes/Upgrader.php +++ b/classes/Upgrader.php @@ -11,8 +11,7 @@ namespace TUTOR; use Tutor\Core\DB; -use Tutor\Database\Schema; -use Tutor\Database\TableManager; +use Tutor\Database\Tables\CouponUsagesTable; use Tutor\Ecommerce\CartController; use Tutor\Ecommerce\CheckoutController; use Tutor\Helpers\QueryHelper; @@ -344,7 +343,7 @@ public function upgrade_to_3_8_2() { */ public function upgrade_to_4_2_0() { if ( DB::has_table( 'tutor_coupon_usages' ) && ! DB::has_column( 'tutor_coupon_usages', 'order_id' ) ) { - TableManager::create_table( Schema::get_coupon_usages_schema( false ) ); + CouponUsagesTable::create( false ); } } @@ -362,8 +361,8 @@ public function init_email_table_deployment( $upgrader_object, $options ) { $addon_config = tutor_utils()->get_addon_config( 'tutor-pro/addons/tutor-email/tutor-email.php' ); $is_enable = (bool) tutor_utils()->avalue_dot( 'is_enable', $addon_config ); - if ( $is_enable && class_exists( \TutorPro\Database\Schema::class ) ) { - TableManager::create_table( \TutorPro\Database\Schema::get_email_queue_table_schema( false ) ); + if ( $is_enable && class_exists( \TutorPro\Database\Tables\EmailQueueTable::class ) ) { + \TutorPro\Database\Tables\EmailQueueTable::create( false ); } } } diff --git a/core/Table.php b/core/Table.php new file mode 100644 index 0000000000..c5db445027 --- /dev/null +++ b/core/Table.php @@ -0,0 +1,134 @@ + + * @link https://themeum.com + * @since 4.3.0 + */ + +namespace Tutor\Core; + +defined( 'ABSPATH' ) || exit; + +/** + * Abstract Class Table + * + * @since 4.3.0 + */ +abstract class Table { + + /** + * Base table name without prefix (e.g. 'tutor_orders'). + * + * @since 4.3.0 + * + * @var string + */ + protected static $table = ''; + + /** + * Get the un-prefixed base table name (e.g. 'tutor_orders'). + * + * @since 4.3.0 + * + * @return string + */ + public static function get_base_name(): string { + return static::$table; + } + + /** + * Get the prefixed table name for the active blog context. + * Resolves global tables to base_prefix and subsite tables to blog prefix. + * + * @since 4.3.0 + * + * @return string + */ + public static function get_name(): string { + return DB::prepare_table_name( static::$table ); + } + + /** + * Get the database charset collate. + * + * @since 4.3.0 + * + * @return string + */ + public static function get_charset_collate(): string { + global $wpdb; + return $wpdb->get_charset_collate(); + } + + /** + * Get CREATE TABLE SQL DDL schema. + * + * @since 4.3.0 + * + * @param bool $include_constraints Whether to include foreign key constraints. + * @return string + */ + abstract public static function get_schema( bool $include_constraints = true ): string; + + /** + * Helper to generate a unique foreign key constraint name per blog prefix (<= 64 chars). + * + * @since 4.3.0 + * + * @param string $name Constraint base name. + * @return string + */ + public static function fk_name( string $name ): string { + global $wpdb; + $fk = $wpdb->prefix . $name; + return strlen( $fk ) <= 64 ? $fk : 'fk_' . substr( md5( $fk ), 0, 32 ); + } + + /** + * Create or update this table using dbDelta. + * + * @since 4.3.0 + * + * @param bool $include_constraints Whether to include foreign key constraints. + * @return void + */ + public static function create( bool $include_constraints = true ): void { + if ( ! function_exists( 'dbDelta' ) ) { + require_once ABSPATH . 'wp-admin/includes/upgrade.php'; + } + + dbDelta( static::get_schema( $include_constraints ) ); + } + + /** + * Drop this table if it exists. + * + * @since 4.3.0 + * + * @return void + */ + public static function drop(): void { + global $wpdb; + $table_name = static::get_name(); + // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared + $wpdb->query( "DROP TABLE IF EXISTS `{$table_name}`" ); + } + + /** + * Check if this table exists in the database. + * + * @since 4.3.0 + * + * @return bool + */ + public static function exists(): bool { + return DB::has_table( static::get_name() ); + } +} + diff --git a/database/Schema.php b/database/Schema.php deleted file mode 100644 index 66d2c9f9e7..0000000000 --- a/database/Schema.php +++ /dev/null @@ -1,667 +0,0 @@ - - * @link https://themeum.com - * @since 4.3.0 - */ - -namespace Tutor\Database; - -use Tutor\Core\DB; - -defined( 'ABSPATH' ) || exit; - -/** - * Class Schemas - * - * @since 4.3.0 - */ -class Schema { - - /** - * Generate unique constraint name per blog prefix. - * Truncates to 64 chars (MySQL max identifier length) using md5 hash if needed. - * - * @since 4.3.0 - * - * @param string $name Base constraint name. - * - * @return string Unique constraint identifier. - */ - public static function fk_name( string $name ): string { - global $wpdb; - $fk = $wpdb->prefix . $name; - return strlen( $fk ) <= 64 ? $fk : 'fk_' . substr( md5( $fk ), 0, 32 ); - } - - /** - * Get only the Core schemas needed for initial site creation. - * Addon tables (gradebook, email queue, subscriptions) are excluded here. - * - * @since 4.3.0 - * - * @param bool $include_constraints Whether to include foreign key constraints. - * - * @return array - */ - public static function get_core_schemas( bool $include_constraints = true ): array { - return array( - self::get_quiz_attempts_schema( $include_constraints ), - self::get_quiz_attempt_answers_schema( $include_constraints ), - self::get_quiz_questions_schema( $include_constraints ), - self::get_quiz_question_answers_schema( $include_constraints ), - self::get_earnings_schema( $include_constraints ), - self::get_withdraws_schema( $include_constraints ), - self::get_orders_schema( $include_constraints ), - self::get_ordermeta_schema( $include_constraints ), - self::get_order_items_schema( $include_constraints ), - self::get_order_itemmeta_schema( $include_constraints ), - self::get_coupons_schema( $include_constraints ), - self::get_coupon_applications_schema( $include_constraints ), - self::get_coupon_usages_schema( $include_constraints ), - self::get_carts_schema( $include_constraints ), - self::get_cart_items_schema( $include_constraints ), - self::get_customers_schema( $include_constraints ), - self::get_scheduler_schema( $include_constraints ), - ); - } - - /** - * Get all tutor database schemas. - * - * @since 4.3.0 - * - * @param bool $include_constraints Whether to include foreign key constraints. - * - * @return array - */ - public static function get_all_schema( $include_constraints = true ): array { - $core_schema = static::get_core_schemas( $include_constraints ); - return apply_filters( 'tutor_database_schemas', $core_schema, $include_constraints ); - } - - /* ---------------- Core Schemas ---------------- */ - - /** - * Get quiz attempts schema. - * - * @since 4.3.0 - * - * @param bool $include_constraints Whether to include foreign key constraints. - * @return string - */ - public static function get_quiz_attempts_schema( bool $include_constraints = true ): string { - global $wpdb; - $table = DB::prepare_table_name( 'tutor_quiz_attempts' ); - $collate = $wpdb->get_charset_collate(); - - return "CREATE TABLE {$table} ( - attempt_id bigint(20) NOT NULL AUTO_INCREMENT, - course_id bigint(20) DEFAULT NULL, - quiz_id bigint(20) DEFAULT NULL, - user_id bigint(20) DEFAULT NULL, - total_questions int(11) DEFAULT NULL, - total_answered_questions int(11) DEFAULT NULL, - total_marks decimal(9,2) DEFAULT NULL, - earned_marks decimal(9,2) DEFAULT NULL, - attempt_info text, - attempt_status varchar(50) DEFAULT NULL, - attempt_ip varchar(250) DEFAULT NULL, - attempt_started_at datetime DEFAULT NULL, - attempt_ended_at datetime DEFAULT NULL, - is_manually_reviewed int(1) DEFAULT NULL, - manually_reviewed_at datetime DEFAULT NULL, - result varchar(10) DEFAULT NULL, - PRIMARY KEY (attempt_id), - INDEX (course_id), - INDEX (quiz_id), - INDEX (user_id), - INDEX (result) - ) {$collate};"; - } - - /** - * Get quiz attempt answers schema. - * - * @since 4.3.0 - * - * @param bool $include_constraints Whether to include foreign key constraints. - * @return string - */ - public static function get_quiz_attempt_answers_schema( bool $include_constraints = true ): string { - global $wpdb; - $table = DB::prepare_table_name( 'tutor_quiz_attempt_answers' ); - $collate = $wpdb->get_charset_collate(); - - return "CREATE TABLE {$table} ( - attempt_answer_id bigint(20) NOT NULL AUTO_INCREMENT, - user_id bigint(20) DEFAULT NULL, - quiz_id bigint(20) DEFAULT NULL, - question_id bigint(20) DEFAULT NULL, - quiz_attempt_id bigint(20) DEFAULT NULL, - given_answer longtext, - question_mark decimal(8,2) DEFAULT NULL, - achieved_mark decimal(8,2) DEFAULT NULL, - minus_mark decimal(8,2) DEFAULT NULL, - is_correct tinyint(4) DEFAULT NULL, - PRIMARY KEY (attempt_answer_id) - ) {$collate};"; - } - - /** - * Get quiz questions schema. - * - * @since 4.3.0 - * - * @param bool $include_constraints Whether to include foreign key constraints. - * @return string - */ - public static function get_quiz_questions_schema( bool $include_constraints = true ): string { - global $wpdb; - $table = DB::prepare_table_name( 'tutor_quiz_questions' ); - $collate = $wpdb->get_charset_collate(); - - return "CREATE TABLE {$table} ( - question_id bigint(20) NOT NULL AUTO_INCREMENT, - quiz_id bigint(20) DEFAULT NULL, - question_title text, - question_description longtext, - answer_explanation longtext DEFAULT '', - question_type varchar(50) DEFAULT NULL, - question_mark decimal(9,2) DEFAULT NULL, - question_settings longtext, - question_order int(11) DEFAULT NULL, - PRIMARY KEY (question_id) - ) {$collate};"; - } - - /** - * Get quiz question answers schema. - * - * @since 4.3.0 - * - * @param bool $include_constraints Whether to include foreign key constraints. - * @return string - */ - public static function get_quiz_question_answers_schema( bool $include_constraints = true ): string { - global $wpdb; - $table = DB::prepare_table_name( 'tutor_quiz_question_answers' ); - $collate = $wpdb->get_charset_collate(); - - return "CREATE TABLE {$table} ( - answer_id bigint(20) NOT NULL AUTO_INCREMENT, - belongs_question_id bigint(20) DEFAULT NULL, - belongs_question_type varchar(250) DEFAULT NULL, - answer_title text, - is_correct tinyint(4) DEFAULT NULL, - image_id bigint(20) DEFAULT NULL, - answer_two_gap_match text, - answer_view_format varchar(250) DEFAULT NULL, - answer_settings text, - answer_order int(11) DEFAULT '0', - PRIMARY KEY (answer_id) - ) {$collate};"; - } - - /** - * Get earnings schema. - * - * @since 4.3.0 - * - * @param bool $include_constraints Whether to include foreign key constraints. - * @return string - */ - public static function get_earnings_schema( bool $include_constraints = true ): string { - global $wpdb; - $table = DB::prepare_table_name( 'tutor_earnings' ); - $collate = $wpdb->get_charset_collate(); - - return "CREATE TABLE IF NOT EXISTS {$table} ( - earning_id bigint(20) NOT NULL AUTO_INCREMENT, - user_id bigint(20) DEFAULT NULL, - course_id bigint(20) DEFAULT NULL, - order_id bigint(20) DEFAULT NULL, - order_status varchar(50) DEFAULT NULL, - course_price_total decimal(16,2) DEFAULT NULL, - course_price_grand_total decimal(16,2) DEFAULT NULL, - instructor_amount decimal(16,2) DEFAULT NULL, - instructor_rate decimal(16,2) DEFAULT NULL, - admin_amount decimal(16,2) DEFAULT NULL, - admin_rate decimal(16,2) DEFAULT NULL, - commission_type varchar(20) DEFAULT NULL, - deduct_fees_amount decimal(16,2) DEFAULT NULL, - deduct_fees_name varchar(250) DEFAULT NULL, - deduct_fees_type varchar(20) DEFAULT NULL, - process_by varchar(20) DEFAULT NULL, - created_at datetime DEFAULT NULL, - PRIMARY KEY (earning_id), - INDEX (user_id), - INDEX (course_id), - INDEX (order_id), - INDEX (process_by) - ) {$collate};"; - } - - /** - * Get withdraws schema. - * - * @since 4.3.0 - * - * @param bool $include_constraints Whether to include foreign key constraints. - * @return string - */ - public static function get_withdraws_schema( bool $include_constraints = true ): string { - global $wpdb; - $table = DB::prepare_table_name( 'tutor_withdraws' ); - $collate = $wpdb->get_charset_collate(); - - return "CREATE TABLE IF NOT EXISTS {$table} ( - withdraw_id bigint(20) NOT NULL AUTO_INCREMENT, - user_id bigint(20) DEFAULT NULL, - amount decimal(16,2) DEFAULT NULL, - method_data text DEFAULT NULL, - status varchar(50) DEFAULT NULL, - updated_at datetime DEFAULT NULL, - created_at datetime DEFAULT NULL, - PRIMARY KEY (withdraw_id) - ) {$collate};"; - } - - /** - * Get orders schema. - * - * @since 4.3.0 - * - * @param bool $include_constraints Whether to include foreign key constraints. - * @return string - */ - public static function get_orders_schema( bool $include_constraints = true ): string { - global $wpdb; - $table = DB::prepare_table_name( 'tutor_orders' ); - $collate = $wpdb->get_charset_collate(); - - return "CREATE TABLE {$table} ( - id BIGINT(20) UNSIGNED AUTO_INCREMENT, - parent_id BIGINT(20) UNSIGNED DEFAULT 0, - transaction_id VARCHAR(255), - user_id BIGINT(20) UNSIGNED NOT NULL, - order_type VARCHAR(50) NOT NULL, - order_status VARCHAR(50) NOT NULL, - payment_status VARCHAR(50) NOT NULL, - subtotal_price DECIMAL(13, 2) NOT NULL, - pre_tax_price DECIMAL(13, 2) NOT NULL, - tax_type VARCHAR(50), - tax_rate DECIMAL(13, 2), - tax_amount DECIMAL(13, 2), - total_price DECIMAL(13, 2) NOT NULL, - net_payment DECIMAL(13, 2) NOT NULL, - coupon_code VARCHAR(255), - coupon_amount DECIMAL(13, 2), - discount_type ENUM('percentage', 'flat') DEFAULT NULL, - discount_amount DECIMAL(13, 2), - discount_reason TEXT, - fees DECIMAL(13, 2), - earnings DECIMAL(13, 2), - refund_amount DECIMAL(13, 2), - payment_method VARCHAR(255), - payment_payloads LONGTEXT, - note TEXT, - created_at_gmt DATETIME NOT NULL, - created_by BIGINT(20) UNSIGNED NOT NULL, - updated_at_gmt DATETIME, - updated_by BIGINT(20) UNSIGNED NOT NULL, - PRIMARY KEY (id), - KEY user_id (user_id), - KEY order_type (order_type), - KEY payment_status (payment_status), - KEY order_status (order_status), - KEY transaction_id (transaction_id) - ) {$collate};"; - } - - /** - * Get ordermeta schema. - * - * @since 4.3.0 - * - * @param bool $include_constraints Whether to include foreign key constraints. - * @return string - */ - public static function get_ordermeta_schema( bool $include_constraints = true ): string { - global $wpdb; - $table = DB::prepare_table_name( 'tutor_ordermeta' ); - $orders_table = DB::prepare_table_name( 'tutor_orders' ); - $collate = $wpdb->get_charset_collate(); - - $constraints = ''; - if ( $include_constraints ) { - $fk_name = self::fk_name( 'fk_tutor_ordermeta_order_id' ); - $constraints = ", CONSTRAINT {$fk_name} FOREIGN KEY (order_id) REFERENCES {$orders_table}(id) ON DELETE CASCADE"; - } - - return "CREATE TABLE {$table} ( - id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, - order_id BIGINT(20) UNSIGNED NOT NULL, - meta_key VARCHAR(255) NOT NULL, - meta_value LONGTEXT NOT NULL, - created_at_gmt DATETIME NOT NULL, - created_by BIGINT(20) UNSIGNED NOT NULL, - updated_at_gmt DATETIME, - updated_by BIGINT(20) UNSIGNED NOT NULL, - PRIMARY KEY (id), - KEY order_id (order_id), - KEY meta_key (meta_key){$constraints} - ) {$collate};"; - } - - /** - * Get order items schema. - * - * @since 4.3.0 - * - * @param bool $include_constraints Whether to include foreign key constraints. - * @return string - */ - public static function get_order_items_schema( bool $include_constraints = true ): string { - global $wpdb; - $table = DB::prepare_table_name( 'tutor_order_items' ); - $orders_table = DB::prepare_table_name( 'tutor_orders' ); - $collate = $wpdb->get_charset_collate(); - - $constraints = ''; - if ( $include_constraints ) { - $fk_name = self::fk_name( 'fk_tutor_order_item_order_id' ); - $constraints = ", CONSTRAINT {$fk_name} FOREIGN KEY (order_id) REFERENCES {$orders_table}(id) ON DELETE CASCADE"; - } - - return "CREATE TABLE {$table} ( - id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, - order_id BIGINT(20) UNSIGNED NOT NULL, - item_id BIGINT(20) UNSIGNED NOT NULL, - regular_price DECIMAL(13, 2) NOT NULL, - sale_price VARCHAR(13) DEFAULT NULL, - discount_price VARCHAR(13) DEFAULT NULL, - coupon_code VARCHAR(255) DEFAULT NULL, - PRIMARY KEY (id), - KEY order_id (order_id), - KEY item_id (item_id){$constraints} - ) {$collate};"; - } - - /** - * Get order itemmeta schema. - * - * @since 4.3.0 - * - * @param bool $include_constraints Whether to include foreign key constraints. - * @return string - */ - public static function get_order_itemmeta_schema( bool $include_constraints = true ): string { - global $wpdb; - $table = DB::prepare_table_name( 'tutor_order_itemmeta' ); - $order_items_table = DB::prepare_table_name( 'tutor_order_items' ); - $collate = $wpdb->get_charset_collate(); - - $constraints = ''; - if ( $include_constraints ) { - $fk_name = self::fk_name( 'fk_tutor_itemmeta' ); - $constraints = ", CONSTRAINT {$fk_name} FOREIGN KEY (item_id) REFERENCES {$order_items_table}(id) ON DELETE CASCADE"; - } - - return "CREATE TABLE {$table} ( - id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, - item_id BIGINT(20) UNSIGNED NOT NULL, - meta_key VARCHAR(255) NOT NULL, - meta_value LONGTEXT NOT NULL, - PRIMARY KEY (id), - KEY item_id (item_id), - KEY meta_key (meta_key){$constraints} - ) {$collate};"; - } - - /** - * Get coupons schema. - * - * @since 4.3.0 - * - * @param bool $include_constraints Whether to include foreign key constraints. - * @return string - */ - public static function get_coupons_schema( bool $include_constraints = true ): string { - global $wpdb; - $table = DB::prepare_table_name( 'tutor_coupons' ); - $collate = $wpdb->get_charset_collate(); - - return "CREATE TABLE {$table} ( - id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, - coupon_status VARCHAR(50), - coupon_type VARCHAR(100) DEFAULT 'code', - coupon_code VARCHAR(50) NOT NULL, - coupon_title VARCHAR(255) NOT NULL, - coupon_description TEXT, - discount_type ENUM('percentage', 'flat') NOT NULL, - discount_amount DECIMAL(13, 2) NOT NULL, - applies_to VARCHAR(100) DEFAULT 'all_courses_and_bundles', - total_usage_limit INT(10) UNSIGNED DEFAULT NULL, - per_user_usage_limit TINYINT(4) UNSIGNED DEFAULT NULL, - purchase_requirement VARCHAR(50) DEFAULT 'no_minimum', - purchase_requirement_value DECIMAL(13, 2), - start_date_gmt DATETIME NOT NULL, - expire_date_gmt DATETIME DEFAULT NULL, - created_at_gmt DATETIME NOT NULL, - created_by BIGINT(20) UNSIGNED NOT NULL, - updated_at_gmt DATETIME, - updated_by BIGINT(20) UNSIGNED NOT NULL, - PRIMARY KEY (id), - UNIQUE KEY coupon_code (coupon_code), - KEY start_date_gmt (start_date_gmt), - KEY expire_date_gmt (expire_date_gmt) - ) {$collate};"; - } - - /** - * Get coupon applications schema. - * - * @since 4.3.0 - * - * @param bool $include_constraints Whether to include foreign key constraints. - * @return string - */ - public static function get_coupon_applications_schema( bool $include_constraints = true ): string { - global $wpdb; - $table = DB::prepare_table_name( 'tutor_coupon_applications' ); - $coupons_table = DB::prepare_table_name( 'tutor_coupons' ); - $collate = $wpdb->get_charset_collate(); - - $constraints = ''; - if ( $include_constraints ) { - $fk_name = self::fk_name( 'fk_tutor_coupon_application_coupon_code' ); - $constraints = ", CONSTRAINT {$fk_name} FOREIGN KEY (coupon_code) REFERENCES {$coupons_table}(coupon_code) ON DELETE CASCADE"; - } - - return "CREATE TABLE {$table} ( - coupon_code VARCHAR(50) NOT NULL, - reference_id BIGINT(20) UNSIGNED NOT NULL, - KEY coupon_code (coupon_code), - KEY reference_id (reference_id){$constraints} - ) {$collate};"; - } - - /** - * Get coupon usages schema. - * - * @since 4.3.0 - * - * @param bool $include_constraints Whether to include foreign key constraints. - * @return string - */ - public static function get_coupon_usages_schema( bool $include_constraints = true ): string { - global $wpdb; - $table = DB::prepare_table_name( 'tutor_coupon_usages' ); - $coupons_table = DB::prepare_table_name( 'tutor_coupons' ); - $users_table = DB::prepare_table_name( 'users' ); - $collate = $wpdb->get_charset_collate(); - $status_consumed = 'consumed'; - - $constraints = ''; - if ( $include_constraints ) { - $fk_coupon = self::fk_name( 'fk_tutor_coupon_usage_coupon_code' ); - $fk_user = self::fk_name( 'fk_tutor_coupon_usage_user_id' ); - $constraints = ", - CONSTRAINT {$fk_coupon} FOREIGN KEY (coupon_code) REFERENCES {$coupons_table}(coupon_code) ON DELETE CASCADE, - CONSTRAINT {$fk_user} FOREIGN KEY (user_id) REFERENCES {$users_table}(ID) ON DELETE CASCADE"; - } - - return "CREATE TABLE {$table} ( - id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, - coupon_code VARCHAR(50) NOT NULL, - user_id BIGINT(20) UNSIGNED NOT NULL, - order_id BIGINT(20) UNSIGNED DEFAULT NULL, - status VARCHAR(20) NOT NULL DEFAULT '{$status_consumed}', - expires_at_gmt DATETIME DEFAULT NULL, - created_at_gmt DATETIME NOT NULL, - PRIMARY KEY (id), - UNIQUE KEY coupon_order (coupon_code, order_id), - KEY coupon_code (coupon_code), - KEY user_id (user_id), - KEY order_id (order_id), - KEY status (status){$constraints} - ) {$collate};"; - } - - /** - * Get carts schema. - * - * @since 4.3.0 - * - * @param bool $include_constraints Whether to include foreign key constraints. - * @return string - */ - public static function get_carts_schema( bool $include_constraints = true ): string { - global $wpdb; - $table = DB::prepare_table_name( 'tutor_carts' ); - $users_table = DB::prepare_table_name( 'users' ); - $collate = $wpdb->get_charset_collate(); - - $constraints = ''; - if ( $include_constraints ) { - $fk_user = self::fk_name( 'fk_tutor_cart_user_id' ); - $constraints = ", CONSTRAINT {$fk_user} FOREIGN KEY (user_id) REFERENCES {$users_table}(ID) ON DELETE CASCADE"; - } - - return "CREATE TABLE {$table} ( - id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, - user_id BIGINT(20) UNSIGNED DEFAULT NULL, - coupon_code VARCHAR(50) DEFAULT NULL, - created_at_gmt DATETIME NOT NULL, - updated_at_gmt DATETIME, - PRIMARY KEY (id), - KEY user_id (user_id), - KEY coupon_code (coupon_code){$constraints} - ) {$collate};"; - } - - /** - * Get cart items schema. - * - * @since 4.3.0 - * - * @param bool $include_constraints Whether to include foreign key constraints. - * @return string - */ - public static function get_cart_items_schema( bool $include_constraints = true ): string { - global $wpdb; - $table = DB::prepare_table_name( 'tutor_cart_items' ); - $carts_table = DB::prepare_table_name( 'tutor_carts' ); - $posts_table = DB::prepare_table_name( 'posts' ); - $collate = $wpdb->get_charset_collate(); - - $constraints = ''; - if ( $include_constraints ) { - $fk_cart = self::fk_name( 'fk_tutor_cart_item_cart_id' ); - $fk_post = self::fk_name( 'fk_tutor_cart_item_course_id' ); - $constraints = ", - CONSTRAINT {$fk_cart} FOREIGN KEY (cart_id) REFERENCES {$carts_table}(id) ON DELETE CASCADE, - CONSTRAINT {$fk_post} FOREIGN KEY (course_id) REFERENCES {$posts_table}(ID) ON DELETE CASCADE"; - } - - return "CREATE TABLE {$table} ( - id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, - cart_id BIGINT(20) UNSIGNED NOT NULL, - course_id BIGINT(20) UNSIGNED NOT NULL, - item_type VARCHAR(255), - item_details JSON, - PRIMARY KEY (id), - KEY cart_id (cart_id), - KEY course_id (course_id){$constraints} - ) {$collate};"; - } - - /** - * Get customers schema. - * - * @since 4.3.0 - * - * @param bool $include_constraints Whether to include foreign key constraints. - * @return string - */ - public static function get_customers_schema( bool $include_constraints = true ): string { - global $wpdb; - $table = DB::prepare_table_name( 'tutor_customers' ); - $collate = $wpdb->get_charset_collate(); - - return "CREATE TABLE {$table} ( - id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, - user_id BIGINT(20) UNSIGNED DEFAULT NULL, - billing_first_name VARCHAR(255) NOT NULL, - billing_last_name VARCHAR(255) NOT NULL, - billing_email VARCHAR(255) NOT NULL, - billing_phone VARCHAR(20) NOT NULL, - billing_zip_code VARCHAR(20) NOT NULL, - billing_address TEXT NOT NULL, - billing_country VARCHAR(100) NOT NULL, - billing_state VARCHAR(100) NOT NULL, - billing_city VARCHAR(100) NOT NULL, - PRIMARY KEY (id), - KEY user_id (user_id), - KEY billing_email (billing_email) - ) {$collate};"; - } - - /** - * Get scheduler schema. - * - * @since 4.3.0 - * - * @param bool $include_constraints Whether to include foreign key constraints. - * @return string - */ - public static function get_scheduler_schema( bool $include_constraints = true ): string { - global $wpdb; - $table = DB::prepare_table_name( 'tutor_scheduler' ); - $collate = $wpdb->get_charset_collate(); - - return "CREATE TABLE {$table} ( - id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, - type VARCHAR(50) NOT NULL COMMENT 'Type of schedule, e.g., gift, email, reminder', - reference_id VARCHAR(255) NOT NULL COMMENT 'Unique reference id, token, etc', - scheduled_at_gmt DATETIME NOT NULL COMMENT 'When the action should be executed', - status VARCHAR(255) NOT NULL DEFAULT 'processing', - payload LONGTEXT, - created_at_gmt DATETIME, - updated_at_gmt DATETIME, - scheduled_by BIGINT UNSIGNED COMMENT 'User who scheduled the action', - scheduled_for BIGINT UNSIGNED COMMENT 'Target user of the scheduled action', - PRIMARY KEY (id), - KEY idx_context_status (type, status), - KEY idx_status (status), - KEY idx_scheduled_at_gmt (scheduled_at_gmt) - ) {$collate};"; - } -} diff --git a/database/TableManager.php b/database/TableManager.php index b4d896fe74..ccfbdc290d 100644 --- a/database/TableManager.php +++ b/database/TableManager.php @@ -13,58 +13,106 @@ namespace Tutor\Database; -use Tutor\Core\DB; +use Tutor\Core\Table; +use Tutor\Database\Tables\QuizAttemptsTable; +use Tutor\Database\Tables\QuizAttemptAnswersTable; +use Tutor\Database\Tables\QuizQuestionsTable; +use Tutor\Database\Tables\QuizQuestionAnswersTable; +use Tutor\Database\Tables\EarningsTable; +use Tutor\Database\Tables\WithdrawsTable; +use Tutor\Database\Tables\OrdersTable; +use Tutor\Database\Tables\OrdermetaTable; +use Tutor\Database\Tables\OrderItemsTable; +use Tutor\Database\Tables\OrderItemmetaTable; +use Tutor\Database\Tables\CouponsTable; +use Tutor\Database\Tables\CouponApplicationsTable; +use Tutor\Database\Tables\CouponUsagesTable; +use Tutor\Database\Tables\CartsTable; +use Tutor\Database\Tables\CartItemsTable; +use Tutor\Database\Tables\CustomersTable; +use Tutor\Database\Tables\SchedulerTable; defined( 'ABSPATH' ) || exit; /** - * Class SchemaManager + * Class TableManager * * @since 4.3.0 */ class TableManager { + /** - * Core tables created on initial installation or new subsite provisioning. + * Core table classes created on initial installation or new subsite provisioning. * - * @var array table name. + * @var array> */ - const CORE_TABLES = array( - 'tutor_quiz_attempts', - 'tutor_quiz_attempt_answers', - 'tutor_quiz_questions', - 'tutor_quiz_question_answers', - 'tutor_earnings', - 'tutor_withdraws', - 'tutor_orders', - 'tutor_ordermeta', - 'tutor_order_items', - 'tutor_order_itemmeta', - 'tutor_coupons', - 'tutor_coupon_applications', - 'tutor_coupon_usages', - 'tutor_carts', - 'tutor_cart_items', - 'tutor_customers', - 'tutor_scheduler', + const CORE_TABLE_CLASSES = array( + QuizAttemptsTable::class, + QuizAttemptAnswersTable::class, + QuizQuestionsTable::class, + QuizQuestionAnswersTable::class, + EarningsTable::class, + WithdrawsTable::class, + OrdersTable::class, + OrdermetaTable::class, + OrderItemsTable::class, + OrderItemmetaTable::class, + CouponsTable::class, + CouponApplicationsTable::class, + CouponUsagesTable::class, + CartsTable::class, + CartItemsTable::class, + CustomersTable::class, + SchedulerTable::class, ); + /** + * Get all table classes (Core + Addons + Pro via filter). + * + * @since 4.3.0 + * + * @return array> Array of table classes. + */ + public static function get_table_classes(): array { + $core_classes = self::CORE_TABLE_CLASSES; + + /** + * Filter to register additional addon tables from Pro and third-party addons. + * + * @since 4.3.0 + * + * @param array> $all_classes Array of table classes. + */ + $all_classes = apply_filters( 'tutor_database_table_classes', $core_classes ); + + // Filter is instance of Table. + $all_classes = array_filter( $all_classes, fn( $class ) => $class instanceof Table ); + + return $all_classes; + } + /** * Get all known tables (Core + Addons + Pro via filter). * Used for drop/cleanup operations across single-site and multisite. * * @since 4.3.0 * - * @return array Key => base name + * @return array Array of base table names. */ - public static function get_tables(): array { + public static function get_table_names(): array { + $table_names = array_map( + fn( $class ) => $class::get_name(), + static::get_table_classes() + ); + /** * Filter to register additional addon tables from Pro and third-party addons. * * @since 4.3.0 * - * @param array $all_tables Array of key => base table name. + * @param array $all_tables Array of base table names. */ - return apply_filters( 'tutor_database_tables', self::CORE_TABLES ); + return apply_filters( 'tutor_database_tables', $table_names ); } /** @@ -96,10 +144,8 @@ public static function create_table( string $schema ): void { * @return void */ public static function create_core_tables( bool $include_constraints = true ): void { - $schemas = Schema::get_core_schemas( $include_constraints ); - - foreach ( $schemas as $sql ) { - self::create_table( $sql ); + foreach ( self::CORE_TABLE_CLASSES as $table_class ) { + $table_class::create( $include_constraints ); } /** @@ -122,14 +168,12 @@ public static function create_core_tables( bool $include_constraints = true ): v */ public static function drop_tables(): void { global $wpdb; - - $tables = self::get_tables(); + $table_names = self::get_table_names(); // Temporarily disable FK checks to cleanly drop without constraint order issues. $wpdb->query( 'SET FOREIGN_KEY_CHECKS = 0' ); - foreach ( $tables as $base_name ) { - $table_name = DB::prepare_table_name( $base_name ); + foreach ( $table_names as $table_name ) { $wpdb->query( "DROP TABLE IF EXISTS `{$table_name}`" ); //phpcs:ignore } @@ -143,4 +187,3 @@ public static function drop_tables(): void { do_action( 'tutor_database_tables_dropped' ); } } - diff --git a/database/Tables/CartItemsTable.php b/database/Tables/CartItemsTable.php new file mode 100644 index 0000000000..e7f6ddf0dc --- /dev/null +++ b/database/Tables/CartItemsTable.php @@ -0,0 +1,67 @@ + + * @link https://themeum.com + * @since 4.3.0 + */ + +namespace Tutor\Database\Tables; + +defined( 'ABSPATH' ) || exit; + +use Tutor\Core\DB; +use Tutor\Core\Table; + +/** + * Class CartItemsTable + * + * @since 4.3.0 + */ +class CartItemsTable extends Table { + + /** + * Base table name. + * + * @var string + */ + protected static $table = 'tutor_cart_items'; + + /** + * Get CREATE TABLE SQL DDL schema. + * + * @since 4.3.0 + * + * @param bool $include_constraints Whether to include foreign key constraints. + * @return string + */ + public static function get_schema( bool $include_constraints = true ): string { + $table = static::get_name(); + $carts_table = CartsTable::get_name(); + $posts_table = DB::prepare_table_name( 'posts' ); + $collate = static::get_charset_collate(); + + $constraints = ''; + if ( $include_constraints ) { + $fk_cart = static::fk_name( 'fk_tutor_cart_item_cart_id' ); + $fk_post = static::fk_name( 'fk_tutor_cart_item_course_id' ); + $constraints = ", + CONSTRAINT {$fk_cart} FOREIGN KEY (cart_id) REFERENCES {$carts_table}(id) ON DELETE CASCADE, + CONSTRAINT {$fk_post} FOREIGN KEY (course_id) REFERENCES {$posts_table}(ID) ON DELETE CASCADE"; + } + + return "CREATE TABLE {$table} ( + id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, + cart_id BIGINT(20) UNSIGNED NOT NULL, + course_id BIGINT(20) UNSIGNED NOT NULL, + item_type VARCHAR(255), + item_details JSON, + PRIMARY KEY (id), + KEY cart_id (cart_id), + KEY course_id (course_id){$constraints} + ) {$collate};"; + } +} + diff --git a/database/Tables/CartsTable.php b/database/Tables/CartsTable.php new file mode 100644 index 0000000000..d95404aafb --- /dev/null +++ b/database/Tables/CartsTable.php @@ -0,0 +1,63 @@ + + * @link https://themeum.com + * @since 4.3.0 + */ + +namespace Tutor\Database\Tables; + +defined( 'ABSPATH' ) || exit; + +use Tutor\Core\DB; +use Tutor\Core\Table; + +/** + * Class CartsTable + * + * @since 4.3.0 + */ +class CartsTable extends Table { + + /** + * Base table name. + * + * @var string + */ + protected static $table = 'tutor_carts'; + + /** + * Get CREATE TABLE SQL DDL schema. + * + * @since 4.3.0 + * + * @param bool $include_constraints Whether to include foreign key constraints. + * @return string + */ + public static function get_schema( bool $include_constraints = true ): string { + $table = static::get_name(); + $users_table = DB::prepare_table_name( 'users' ); + $collate = static::get_charset_collate(); + + $constraints = ''; + if ( $include_constraints ) { + $fk_user = static::fk_name( 'fk_tutor_cart_user_id' ); + $constraints = ", CONSTRAINT {$fk_user} FOREIGN KEY (user_id) REFERENCES {$users_table}(ID) ON DELETE CASCADE"; + } + + return "CREATE TABLE {$table} ( + id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, + user_id BIGINT(20) UNSIGNED DEFAULT NULL, + coupon_code VARCHAR(50) DEFAULT NULL, + created_at_gmt DATETIME NOT NULL, + updated_at_gmt DATETIME, + PRIMARY KEY (id), + KEY user_id (user_id), + KEY coupon_code (coupon_code){$constraints} + ) {$collate};"; + } +} + diff --git a/database/Tables/CouponApplicationsTable.php b/database/Tables/CouponApplicationsTable.php new file mode 100644 index 0000000000..871c8b609d --- /dev/null +++ b/database/Tables/CouponApplicationsTable.php @@ -0,0 +1,58 @@ + + * @link https://themeum.com + * @since 4.3.0 + */ + +namespace Tutor\Database\Tables; + +defined( 'ABSPATH' ) || exit; + +use Tutor\Core\Table; + +/** + * Class CouponApplicationsTable + * + * @since 4.3.0 + */ +class CouponApplicationsTable extends Table { + + /** + * Base table name. + * + * @var string + */ + protected static $table = 'tutor_coupon_applications'; + + /** + * Get CREATE TABLE SQL DDL schema. + * + * @since 4.3.0 + * + * @param bool $include_constraints Whether to include foreign key constraints. + * @return string + */ + public static function get_schema( bool $include_constraints = true ): string { + $table = static::get_name(); + $coupons_table = CouponsTable::get_name(); + $collate = static::get_charset_collate(); + + $constraints = ''; + if ( $include_constraints ) { + $fk_name = static::fk_name( 'fk_tutor_coupon_application_coupon_code' ); + $constraints = ", CONSTRAINT {$fk_name} FOREIGN KEY (coupon_code) REFERENCES {$coupons_table}(coupon_code) ON DELETE CASCADE"; + } + + return "CREATE TABLE {$table} ( + coupon_code VARCHAR(50) NOT NULL, + reference_id BIGINT(20) UNSIGNED NOT NULL, + KEY coupon_code (coupon_code), + KEY reference_id (reference_id){$constraints} + ) {$collate};"; + } +} + diff --git a/database/Tables/CouponUsagesTable.php b/database/Tables/CouponUsagesTable.php new file mode 100644 index 0000000000..5dc29724b0 --- /dev/null +++ b/database/Tables/CouponUsagesTable.php @@ -0,0 +1,73 @@ + + * @link https://themeum.com + * @since 4.3.0 + */ + +namespace Tutor\Database\Tables; + +defined( 'ABSPATH' ) || exit; + +use Tutor\Core\DB; +use Tutor\Core\Table; + +/** + * Class CouponUsagesTable + * + * @since 4.3.0 + */ +class CouponUsagesTable extends Table { + + /** + * Base table name. + * + * @var string + */ + protected static $table = 'tutor_coupon_usages'; + + /** + * Get CREATE TABLE SQL DDL schema. + * + * @since 4.3.0 + * + * @param bool $include_constraints Whether to include foreign key constraints. + * @return string + */ + public static function get_schema( bool $include_constraints = true ): string { + $table = static::get_name(); + $coupons_table = CouponsTable::get_name(); + $users_table = DB::prepare_table_name( 'users' ); + $collate = static::get_charset_collate(); + $status_consumed = 'consumed'; + + $constraints = ''; + if ( $include_constraints ) { + $fk_coupon = static::fk_name( 'fk_tutor_coupon_usage_coupon_code' ); + $fk_user = static::fk_name( 'fk_tutor_coupon_usage_user_id' ); + $constraints = ", + CONSTRAINT {$fk_coupon} FOREIGN KEY (coupon_code) REFERENCES {$coupons_table}(coupon_code) ON DELETE CASCADE, + CONSTRAINT {$fk_user} FOREIGN KEY (user_id) REFERENCES {$users_table}(ID) ON DELETE CASCADE"; + } + + return "CREATE TABLE {$table} ( + id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, + coupon_code VARCHAR(50) NOT NULL, + user_id BIGINT(20) UNSIGNED NOT NULL, + order_id BIGINT(20) UNSIGNED DEFAULT NULL, + status VARCHAR(20) NOT NULL DEFAULT '{$status_consumed}', + expires_at_gmt DATETIME DEFAULT NULL, + created_at_gmt DATETIME NOT NULL, + PRIMARY KEY (id), + UNIQUE KEY coupon_order (coupon_code, order_id), + KEY coupon_code (coupon_code), + KEY user_id (user_id), + KEY order_id (order_id), + KEY status (status){$constraints} + ) {$collate};"; + } +} + diff --git a/database/Tables/CouponsTable.php b/database/Tables/CouponsTable.php new file mode 100644 index 0000000000..bf20a56a1b --- /dev/null +++ b/database/Tables/CouponsTable.php @@ -0,0 +1,70 @@ + + * @link https://themeum.com + * @since 4.3.0 + */ + +namespace Tutor\Database\Tables; + +defined( 'ABSPATH' ) || exit; + +use Tutor\Core\Table; + +/** + * Class CouponsTable + * + * @since 4.3.0 + */ +class CouponsTable extends Table { + + /** + * Base table name. + * + * @var string + */ + protected static $table = 'tutor_coupons'; + + /** + * Get CREATE TABLE SQL DDL schema. + * + * @since 4.3.0 + * + * @param bool $include_constraints Whether to include foreign key constraints. + * @return string + */ + public static function get_schema( bool $include_constraints = true ): string { + $table = static::get_name(); + $collate = static::get_charset_collate(); + + return "CREATE TABLE {$table} ( + id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, + coupon_status VARCHAR(50), + coupon_type VARCHAR(100) DEFAULT 'code', + coupon_code VARCHAR(50) NOT NULL, + coupon_title VARCHAR(255) NOT NULL, + coupon_description TEXT, + discount_type ENUM('percentage', 'flat') NOT NULL, + discount_amount DECIMAL(13, 2) NOT NULL, + applies_to VARCHAR(100) DEFAULT 'all_courses_and_bundles', + total_usage_limit INT(10) UNSIGNED DEFAULT NULL, + per_user_usage_limit TINYINT(4) UNSIGNED DEFAULT NULL, + purchase_requirement VARCHAR(50) DEFAULT 'no_minimum', + purchase_requirement_value DECIMAL(13, 2), + start_date_gmt DATETIME NOT NULL, + expire_date_gmt DATETIME DEFAULT NULL, + created_at_gmt DATETIME NOT NULL, + created_by BIGINT(20) UNSIGNED NOT NULL, + updated_at_gmt DATETIME, + updated_by BIGINT(20) UNSIGNED NOT NULL, + PRIMARY KEY (id), + UNIQUE KEY coupon_code (coupon_code), + KEY start_date_gmt (start_date_gmt), + KEY expire_date_gmt (expire_date_gmt) + ) {$collate};"; + } +} + diff --git a/database/Tables/CustomersTable.php b/database/Tables/CustomersTable.php new file mode 100644 index 0000000000..1fad9902c8 --- /dev/null +++ b/database/Tables/CustomersTable.php @@ -0,0 +1,61 @@ + + * @link https://themeum.com + * @since 4.3.0 + */ + +namespace Tutor\Database\Tables; + +defined( 'ABSPATH' ) || exit; + +use Tutor\Core\Table; + +/** + * Class CustomersTable + * + * @since 4.3.0 + */ +class CustomersTable extends Table { + + /** + * Base table name. + * + * @var string + */ + protected static $table = 'tutor_customers'; + + /** + * Get CREATE TABLE SQL DDL schema. + * + * @since 4.3.0 + * + * @param bool $include_constraints Whether to include foreign key constraints. + * @return string + */ + public static function get_schema( bool $include_constraints = true ): string { + $table = static::get_name(); + $collate = static::get_charset_collate(); + + return "CREATE TABLE {$table} ( + id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, + user_id BIGINT(20) UNSIGNED DEFAULT NULL, + billing_first_name VARCHAR(255) NOT NULL, + billing_last_name VARCHAR(255) NOT NULL, + billing_email VARCHAR(255) NOT NULL, + billing_phone VARCHAR(20) NOT NULL, + billing_zip_code VARCHAR(20) NOT NULL, + billing_address TEXT NOT NULL, + billing_country VARCHAR(100) NOT NULL, + billing_state VARCHAR(100) NOT NULL, + billing_city VARCHAR(100) NOT NULL, + PRIMARY KEY (id), + KEY user_id (user_id), + KEY billing_email (billing_email) + ) {$collate};"; + } +} + diff --git a/database/Tables/EarningsTable.php b/database/Tables/EarningsTable.php new file mode 100644 index 0000000000..1bfdd1cde2 --- /dev/null +++ b/database/Tables/EarningsTable.php @@ -0,0 +1,69 @@ + + * @link https://themeum.com + * @since 4.3.0 + */ + +namespace Tutor\Database\Tables; + +defined( 'ABSPATH' ) || exit; + +use Tutor\Core\Table; + +/** + * Class EarningsTable + * + * @since 4.3.0 + */ +class EarningsTable extends Table { + + /** + * Base table name. + * + * @var string + */ + protected static $table = 'tutor_earnings'; + + /** + * Get CREATE TABLE SQL DDL schema. + * + * @since 4.3.0 + * + * @param bool $include_constraints Whether to include foreign key constraints. + * @return string + */ + public static function get_schema( bool $include_constraints = true ): string { + $table = static::get_name(); + $collate = static::get_charset_collate(); + + return "CREATE TABLE IF NOT EXISTS {$table} ( + earning_id bigint(20) NOT NULL AUTO_INCREMENT, + user_id bigint(20) DEFAULT NULL, + course_id bigint(20) DEFAULT NULL, + order_id bigint(20) DEFAULT NULL, + order_status varchar(50) DEFAULT NULL, + course_price_total decimal(16,2) DEFAULT NULL, + course_price_grand_total decimal(16,2) DEFAULT NULL, + instructor_amount decimal(16,2) DEFAULT NULL, + instructor_rate decimal(16,2) DEFAULT NULL, + admin_amount decimal(16,2) DEFAULT NULL, + admin_rate decimal(16,2) DEFAULT NULL, + commission_type varchar(20) DEFAULT NULL, + deduct_fees_amount decimal(16,2) DEFAULT NULL, + deduct_fees_name varchar(250) DEFAULT NULL, + deduct_fees_type varchar(20) DEFAULT NULL, + process_by varchar(20) DEFAULT NULL, + created_at datetime DEFAULT NULL, + PRIMARY KEY (earning_id), + INDEX (user_id), + INDEX (course_id), + INDEX (order_id), + INDEX (process_by) + ) {$collate};"; + } +} + diff --git a/database/Tables/OrderItemmetaTable.php b/database/Tables/OrderItemmetaTable.php new file mode 100644 index 0000000000..61b3b0fae3 --- /dev/null +++ b/database/Tables/OrderItemmetaTable.php @@ -0,0 +1,61 @@ + + * @link https://themeum.com + * @since 4.3.0 + */ + +namespace Tutor\Database\Tables; + +defined( 'ABSPATH' ) || exit; + +use Tutor\Core\Table; + +/** + * Class OrderItemmetaTable + * + * @since 4.3.0 + */ +class OrderItemmetaTable extends Table { + + /** + * Base table name. + * + * @var string + */ + protected static $table = 'tutor_order_itemmeta'; + + /** + * Get CREATE TABLE SQL DDL schema. + * + * @since 4.3.0 + * + * @param bool $include_constraints Whether to include foreign key constraints. + * @return string + */ + public static function get_schema( bool $include_constraints = true ): string { + $table = static::get_name(); + $order_items_table = OrderItemsTable::get_name(); + $collate = static::get_charset_collate(); + + $constraints = ''; + if ( $include_constraints ) { + $fk_name = static::fk_name( 'fk_tutor_itemmeta' ); + $constraints = ", CONSTRAINT {$fk_name} FOREIGN KEY (item_id) REFERENCES {$order_items_table}(id) ON DELETE CASCADE"; + } + + return "CREATE TABLE {$table} ( + id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, + item_id BIGINT(20) UNSIGNED NOT NULL, + meta_key VARCHAR(255) NOT NULL, + meta_value LONGTEXT NOT NULL, + PRIMARY KEY (id), + KEY item_id (item_id), + KEY meta_key (meta_key){$constraints} + ) {$collate};"; + } +} + diff --git a/database/Tables/OrderItemsTable.php b/database/Tables/OrderItemsTable.php new file mode 100644 index 0000000000..a2bbad2ae8 --- /dev/null +++ b/database/Tables/OrderItemsTable.php @@ -0,0 +1,64 @@ + + * @link https://themeum.com + * @since 4.3.0 + */ + +namespace Tutor\Database\Tables; + +defined( 'ABSPATH' ) || exit; + +use Tutor\Core\Table; + +/** + * Class OrderItemsTable + * + * @since 4.3.0 + */ +class OrderItemsTable extends Table { + + /** + * Base table name. + * + * @var string + */ + protected static $table = 'tutor_order_items'; + + /** + * Get CREATE TABLE SQL DDL schema. + * + * @since 4.3.0 + * + * @param bool $include_constraints Whether to include foreign key constraints. + * @return string + */ + public static function get_schema( bool $include_constraints = true ): string { + $table = static::get_name(); + $orders_table = OrdersTable::get_name(); + $collate = static::get_charset_collate(); + + $constraints = ''; + if ( $include_constraints ) { + $fk_name = static::fk_name( 'fk_tutor_order_item_order_id' ); + $constraints = ", CONSTRAINT {$fk_name} FOREIGN KEY (order_id) REFERENCES {$orders_table}(id) ON DELETE CASCADE"; + } + + return "CREATE TABLE {$table} ( + id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, + order_id BIGINT(20) UNSIGNED NOT NULL, + item_id BIGINT(20) UNSIGNED NOT NULL, + regular_price DECIMAL(13, 2) NOT NULL, + sale_price VARCHAR(13) DEFAULT NULL, + discount_price VARCHAR(13) DEFAULT NULL, + coupon_code VARCHAR(255) DEFAULT NULL, + PRIMARY KEY (id), + KEY order_id (order_id), + KEY item_id (item_id){$constraints} + ) {$collate};"; + } +} + diff --git a/database/Tables/OrdermetaTable.php b/database/Tables/OrdermetaTable.php new file mode 100644 index 0000000000..f712a0e0e2 --- /dev/null +++ b/database/Tables/OrdermetaTable.php @@ -0,0 +1,65 @@ + + * @link https://themeum.com + * @since 4.3.0 + */ + +namespace Tutor\Database\Tables; + +defined( 'ABSPATH' ) || exit; + +use Tutor\Core\Table; + +/** + * Class OrdermetaTable + * + * @since 4.3.0 + */ +class OrdermetaTable extends Table { + + /** + * Base table name. + * + * @var string + */ + protected static $table = 'tutor_ordermeta'; + + /** + * Get CREATE TABLE SQL DDL schema. + * + * @since 4.3.0 + * + * @param bool $include_constraints Whether to include foreign key constraints. + * @return string + */ + public static function get_schema( bool $include_constraints = true ): string { + $table = static::get_name(); + $orders_table = OrdersTable::get_name(); + $collate = static::get_charset_collate(); + + $constraints = ''; + if ( $include_constraints ) { + $fk_name = static::fk_name( 'fk_tutor_ordermeta_order_id' ); + $constraints = ", CONSTRAINT {$fk_name} FOREIGN KEY (order_id) REFERENCES {$orders_table}(id) ON DELETE CASCADE"; + } + + return "CREATE TABLE {$table} ( + id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, + order_id BIGINT(20) UNSIGNED NOT NULL, + meta_key VARCHAR(255) NOT NULL, + meta_value LONGTEXT NOT NULL, + created_at_gmt DATETIME NOT NULL, + created_by BIGINT(20) UNSIGNED NOT NULL, + updated_at_gmt DATETIME, + updated_by BIGINT(20) UNSIGNED NOT NULL, + PRIMARY KEY (id), + KEY order_id (order_id), + KEY meta_key (meta_key){$constraints} + ) {$collate};"; + } +} + diff --git a/database/Tables/OrdersTable.php b/database/Tables/OrdersTable.php new file mode 100644 index 0000000000..bde5319bf2 --- /dev/null +++ b/database/Tables/OrdersTable.php @@ -0,0 +1,82 @@ + + * @link https://themeum.com + * @since 4.3.0 + */ + +namespace Tutor\Database\Tables; + +defined( 'ABSPATH' ) || exit; + +use Tutor\Core\Table; + +/** + * Class OrdersTable + * + * @since 4.3.0 + */ +class OrdersTable extends Table { + + /** + * Base table name. + * + * @var string + */ + protected static $table = 'tutor_orders'; + + /** + * Get CREATE TABLE SQL DDL schema. + * + * @since 4.3.0 + * + * @param bool $include_constraints Whether to include foreign key constraints. + * @return string + */ + public static function get_schema( bool $include_constraints = true ): string { + $table = static::get_name(); + $collate = static::get_charset_collate(); + + return "CREATE TABLE {$table} ( + id BIGINT(20) UNSIGNED AUTO_INCREMENT, + parent_id BIGINT(20) UNSIGNED DEFAULT 0, + transaction_id VARCHAR(255), + user_id BIGINT(20) UNSIGNED NOT NULL, + order_type VARCHAR(50) NOT NULL, + order_status VARCHAR(50) NOT NULL, + payment_status VARCHAR(50) NOT NULL, + subtotal_price DECIMAL(13, 2) NOT NULL, + pre_tax_price DECIMAL(13, 2) NOT NULL, + tax_type VARCHAR(50), + tax_rate DECIMAL(13, 2), + tax_amount DECIMAL(13, 2), + total_price DECIMAL(13, 2) NOT NULL, + net_payment DECIMAL(13, 2) NOT NULL, + coupon_code VARCHAR(255), + coupon_amount DECIMAL(13, 2), + discount_type ENUM('percentage', 'flat') DEFAULT NULL, + discount_amount DECIMAL(13, 2), + discount_reason TEXT, + fees DECIMAL(13, 2), + earnings DECIMAL(13, 2), + refund_amount DECIMAL(13, 2), + payment_method VARCHAR(255), + payment_payloads LONGTEXT, + note TEXT, + created_at_gmt DATETIME NOT NULL, + created_by BIGINT(20) UNSIGNED NOT NULL, + updated_at_gmt DATETIME, + updated_by BIGINT(20) UNSIGNED NOT NULL, + PRIMARY KEY (id), + KEY user_id (user_id), + KEY order_type (order_type), + KEY payment_status (payment_status), + KEY order_status (order_status), + KEY transaction_id (transaction_id) + ) {$collate};"; + } +} + diff --git a/database/Tables/QuizAttemptAnswersTable.php b/database/Tables/QuizAttemptAnswersTable.php new file mode 100644 index 0000000000..95d3384999 --- /dev/null +++ b/database/Tables/QuizAttemptAnswersTable.php @@ -0,0 +1,58 @@ + + * @link https://themeum.com + * @since 4.3.0 + */ + +namespace Tutor\Database\Tables; + +defined( 'ABSPATH' ) || exit; + +use Tutor\Core\Table; + +/** + * Class QuizAttemptAnswersTable + * + * @since 4.3.0 + */ +class QuizAttemptAnswersTable extends Table { + + /** + * Base table name. + * + * @var string + */ + protected static $table = 'tutor_quiz_attempt_answers'; + + /** + * Get CREATE TABLE SQL DDL schema. + * + * @since 4.3.0 + * + * @param bool $include_constraints Whether to include foreign key constraints. + * @return string + */ + public static function get_schema( bool $include_constraints = true ): string { + $table = static::get_name(); + $collate = static::get_charset_collate(); + + return "CREATE TABLE {$table} ( + attempt_answer_id bigint(20) NOT NULL AUTO_INCREMENT, + user_id bigint(20) DEFAULT NULL, + quiz_id bigint(20) DEFAULT NULL, + question_id bigint(20) DEFAULT NULL, + quiz_attempt_id bigint(20) DEFAULT NULL, + given_answer longtext, + question_mark decimal(8,2) DEFAULT NULL, + achieved_mark decimal(8,2) DEFAULT NULL, + minus_mark decimal(8,2) DEFAULT NULL, + is_correct tinyint(4) DEFAULT NULL, + PRIMARY KEY (attempt_answer_id) + ) {$collate};"; + } +} + diff --git a/database/Tables/QuizAttemptsTable.php b/database/Tables/QuizAttemptsTable.php new file mode 100644 index 0000000000..bf2d9d7424 --- /dev/null +++ b/database/Tables/QuizAttemptsTable.php @@ -0,0 +1,68 @@ + + * @link https://themeum.com + * @since 4.3.0 + */ + +namespace Tutor\Database\Tables; + +defined( 'ABSPATH' ) || exit; + +use Tutor\Core\Table; + +/** + * Class QuizAttemptsTable + * + * @since 4.3.0 + */ +class QuizAttemptsTable extends Table { + + /** + * Base table name. + * + * @var string + */ + protected static $table = 'tutor_quiz_attempts'; + + /** + * Get CREATE TABLE SQL DDL schema. + * + * @since 4.3.0 + * + * @param bool $include_constraints Whether to include foreign key constraints. + * @return string + */ + public static function get_schema( bool $include_constraints = true ): string { + $table = static::get_name(); + $collate = static::get_charset_collate(); + + return "CREATE TABLE {$table} ( + attempt_id bigint(20) NOT NULL AUTO_INCREMENT, + course_id bigint(20) DEFAULT NULL, + quiz_id bigint(20) DEFAULT NULL, + user_id bigint(20) DEFAULT NULL, + total_questions int(11) DEFAULT NULL, + total_answered_questions int(11) DEFAULT NULL, + total_marks decimal(9,2) DEFAULT NULL, + earned_marks decimal(9,2) DEFAULT NULL, + attempt_info text, + attempt_status varchar(50) DEFAULT NULL, + attempt_ip varchar(250) DEFAULT NULL, + attempt_started_at datetime DEFAULT NULL, + attempt_ended_at datetime DEFAULT NULL, + is_manually_reviewed int(1) DEFAULT NULL, + manually_reviewed_at datetime DEFAULT NULL, + result varchar(10) DEFAULT NULL, + PRIMARY KEY (attempt_id), + INDEX (course_id), + INDEX (quiz_id), + INDEX (user_id), + INDEX (result) + ) {$collate};"; + } +} + diff --git a/database/Tables/QuizQuestionAnswersTable.php b/database/Tables/QuizQuestionAnswersTable.php new file mode 100644 index 0000000000..8282b8b378 --- /dev/null +++ b/database/Tables/QuizQuestionAnswersTable.php @@ -0,0 +1,58 @@ + + * @link https://themeum.com + * @since 4.3.0 + */ + +namespace Tutor\Database\Tables; + +defined( 'ABSPATH' ) || exit; + +use Tutor\Core\Table; + +/** + * Class QuizQuestionAnswersTable + * + * @since 4.3.0 + */ +class QuizQuestionAnswersTable extends Table { + + /** + * Base table name. + * + * @var string + */ + protected static $table = 'tutor_quiz_question_answers'; + + /** + * Get CREATE TABLE SQL DDL schema. + * + * @since 4.3.0 + * + * @param bool $include_constraints Whether to include foreign key constraints. + * @return string + */ + public static function get_schema( bool $include_constraints = true ): string { + $table = static::get_name(); + $collate = static::get_charset_collate(); + + return "CREATE TABLE {$table} ( + answer_id bigint(20) NOT NULL AUTO_INCREMENT, + belongs_question_id bigint(20) DEFAULT NULL, + belongs_question_type varchar(250) DEFAULT NULL, + answer_title text, + is_correct tinyint(4) DEFAULT NULL, + image_id bigint(20) DEFAULT NULL, + answer_two_gap_match text, + answer_view_format varchar(250) DEFAULT NULL, + answer_settings text, + answer_order int(11) DEFAULT '0', + PRIMARY KEY (answer_id) + ) {$collate};"; + } +} + diff --git a/database/Tables/QuizQuestionsTable.php b/database/Tables/QuizQuestionsTable.php new file mode 100644 index 0000000000..bd9b588e45 --- /dev/null +++ b/database/Tables/QuizQuestionsTable.php @@ -0,0 +1,57 @@ + + * @link https://themeum.com + * @since 4.3.0 + */ + +namespace Tutor\Database\Tables; + +defined( 'ABSPATH' ) || exit; + +use Tutor\Core\Table; + +/** + * Class QuizQuestionsTable + * + * @since 4.3.0 + */ +class QuizQuestionsTable extends Table { + + /** + * Base table name. + * + * @var string + */ + protected static $table = 'tutor_quiz_questions'; + + /** + * Get CREATE TABLE SQL DDL schema. + * + * @since 4.3.0 + * + * @param bool $include_constraints Whether to include foreign key constraints. + * @return string + */ + public static function get_schema( bool $include_constraints = true ): string { + $table = static::get_name(); + $collate = static::get_charset_collate(); + + return "CREATE TABLE {$table} ( + question_id bigint(20) NOT NULL AUTO_INCREMENT, + quiz_id bigint(20) DEFAULT NULL, + question_title text, + question_description longtext, + answer_explanation longtext DEFAULT '', + question_type varchar(50) DEFAULT NULL, + question_mark decimal(9,2) DEFAULT NULL, + question_settings longtext, + question_order int(11) DEFAULT NULL, + PRIMARY KEY (question_id) + ) {$collate};"; + } +} + diff --git a/database/Tables/SchedulerTable.php b/database/Tables/SchedulerTable.php new file mode 100644 index 0000000000..75f72edfa3 --- /dev/null +++ b/database/Tables/SchedulerTable.php @@ -0,0 +1,61 @@ + + * @link https://themeum.com + * @since 4.3.0 + */ + +namespace Tutor\Database\Tables; + +defined( 'ABSPATH' ) || exit; + +use Tutor\Core\Table; + +/** + * Class SchedulerTable + * + * @since 4.3.0 + */ +class SchedulerTable extends Table { + + /** + * Base table name. + * + * @var string + */ + protected static $table = 'tutor_scheduler'; + + /** + * Get CREATE TABLE SQL DDL schema. + * + * @since 4.3.0 + * + * @param bool $include_constraints Whether to include foreign key constraints. + * @return string + */ + public static function get_schema( bool $include_constraints = true ): string { + $table = static::get_name(); + $collate = static::get_charset_collate(); + + return "CREATE TABLE {$table} ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + type VARCHAR(50) NOT NULL COMMENT 'Type of schedule, e.g., gift, email, reminder', + reference_id VARCHAR(255) NOT NULL COMMENT 'Unique reference id, token, etc', + scheduled_at_gmt DATETIME NOT NULL COMMENT 'When the action should be executed', + status VARCHAR(255) NOT NULL DEFAULT 'processing', + payload LONGTEXT, + created_at_gmt DATETIME, + updated_at_gmt DATETIME, + scheduled_by BIGINT UNSIGNED COMMENT 'User who scheduled the action', + scheduled_for BIGINT UNSIGNED COMMENT 'Target user of the scheduled action', + PRIMARY KEY (id), + KEY idx_context_status (type, status), + KEY idx_status (status), + KEY idx_scheduled_at_gmt (scheduled_at_gmt) + ) {$collate};"; + } +} + diff --git a/database/Tables/WithdrawsTable.php b/database/Tables/WithdrawsTable.php new file mode 100644 index 0000000000..68dd49f45a --- /dev/null +++ b/database/Tables/WithdrawsTable.php @@ -0,0 +1,55 @@ + + * @link https://themeum.com + * @since 4.3.0 + */ + +namespace Tutor\Database\Tables; + +defined( 'ABSPATH' ) || exit; + +use Tutor\Core\Table; + +/** + * Class WithdrawsTable + * + * @since 4.3.0 + */ +class WithdrawsTable extends Table { + + /** + * Base table name. + * + * @var string + */ + protected static $table = 'tutor_withdraws'; + + /** + * Get CREATE TABLE SQL DDL schema. + * + * @since 4.3.0 + * + * @param bool $include_constraints Whether to include foreign key constraints. + * @return string + */ + public static function get_schema( bool $include_constraints = true ): string { + $table = static::get_name(); + $collate = static::get_charset_collate(); + + return "CREATE TABLE IF NOT EXISTS {$table} ( + withdraw_id bigint(20) NOT NULL AUTO_INCREMENT, + user_id bigint(20) DEFAULT NULL, + amount decimal(16,2) DEFAULT NULL, + method_data text DEFAULT NULL, + status varchar(50) DEFAULT NULL, + updated_at datetime DEFAULT NULL, + created_at datetime DEFAULT NULL, + PRIMARY KEY (withdraw_id) + ) {$collate};"; + } +} + diff --git a/tests/phpunit/CouponModelTest.php b/tests/phpunit/CouponModelTest.php index 532b20a4e1..4eeb0e1462 100644 --- a/tests/phpunit/CouponModelTest.php +++ b/tests/phpunit/CouponModelTest.php @@ -1,7 +1,7 @@ Date: Tue, 10 Nov 2026 12:53:22 +0600 Subject: [PATCH 07/36] fix: validate table class names before checking instance in TableManager --- database/TableManager.php | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/database/TableManager.php b/database/TableManager.php index ccfbdc290d..e0612899b8 100644 --- a/database/TableManager.php +++ b/database/TableManager.php @@ -86,7 +86,10 @@ public static function get_table_classes(): array { $all_classes = apply_filters( 'tutor_database_table_classes', $core_classes ); // Filter is instance of Table. - $all_classes = array_filter( $all_classes, fn( $class ) => $class instanceof Table ); + $all_classes = array_filter( + $all_classes, + fn( $class ) => is_string( $class ) && is_a( $class, Table::class, true ) + ); return $all_classes; } From a5a0f2a0c2b3c8f3760efd8e535507b5c55f33c0 Mon Sep 17 00:00:00 2001 From: "Md.Harun-Ur-Rashid" Date: Tue, 10 Nov 2026 13:37:56 +0600 Subject: [PATCH 08/36] refactor: improve code style and phpdoc formatting across database and multisite classes --- classes/Multisite.php | 6 ++++-- database/TableManager.php | 6 +++--- database/Tables/CartItemsTable.php | 1 + database/Tables/CartsTable.php | 1 + database/Tables/CouponApplicationsTable.php | 1 + database/Tables/CouponUsagesTable.php | 1 + database/Tables/CouponsTable.php | 1 + database/Tables/CustomersTable.php | 1 + database/Tables/EarningsTable.php | 1 + database/Tables/OrderItemmetaTable.php | 1 + database/Tables/OrderItemsTable.php | 1 + database/Tables/OrdermetaTable.php | 1 + database/Tables/OrdersTable.php | 1 + database/Tables/QuizAttemptAnswersTable.php | 1 + database/Tables/QuizAttemptsTable.php | 1 + database/Tables/QuizQuestionAnswersTable.php | 1 + database/Tables/QuizQuestionsTable.php | 1 + database/Tables/SchedulerTable.php | 1 + database/Tables/WithdrawsTable.php | 1 + 19 files changed, 24 insertions(+), 5 deletions(-) diff --git a/classes/Multisite.php b/classes/Multisite.php index 87dfc95ec9..22ff125140 100644 --- a/classes/Multisite.php +++ b/classes/Multisite.php @@ -10,10 +10,10 @@ namespace TUTOR; -use Tutor\Database\TableManager; - defined( 'ABSPATH' ) || exit; +use Tutor\Database\TableManager; + /** * Class Multisite * @@ -48,6 +48,7 @@ public function __construct() { * * @param \WP_Site $site New site object. * @param array $args Setup arguments. + * * @return void */ public function on_initialize_site( \WP_Site $site, array $args = array() ): void { @@ -88,6 +89,7 @@ public function on_initialize_site( \WP_Site $site, array $args = array() ): voi * @since 4.3.0 * * @param \WP_Site $site Site being uninitialized. + * * @return void */ public function on_uninitialize_site( \WP_Site $site ): void { diff --git a/database/TableManager.php b/database/TableManager.php index e0612899b8..6d138a3e72 100644 --- a/database/TableManager.php +++ b/database/TableManager.php @@ -1,6 +1,6 @@ Date: Tue, 10 Nov 2026 17:29:23 +0600 Subject: [PATCH 09/36] refactor: replace QueryHelper with DB class methods in Upgrader --- classes/Upgrader.php | 39 +++++++++++++++++++++------------------ 1 file changed, 21 insertions(+), 18 deletions(-) diff --git a/classes/Upgrader.php b/classes/Upgrader.php index f74b7cc58b..b6a4e5277b 100644 --- a/classes/Upgrader.php +++ b/classes/Upgrader.php @@ -10,15 +10,12 @@ namespace TUTOR; +defined( 'ABSPATH' ) || exit; + use Tutor\Core\DB; use Tutor\Database\Tables\CouponUsagesTable; use Tutor\Ecommerce\CartController; use Tutor\Ecommerce\CheckoutController; -use Tutor\Helpers\QueryHelper; - -if ( ! defined( 'ABSPATH' ) ) { - exit; -} /** * Manage up grade @@ -142,7 +139,7 @@ public function upgrade_to_3_0_0() { if ( version_compare( $this->installed_version, '3.0.0', '<' ) ) { $table_name = $wpdb->prefix . 'tutor_orders'; - if ( ! QueryHelper::table_exists( $table_name ) ) { + if ( ! DB::has_table( $table_name ) ) { Tutor::tutor_activate(); } update_option( 'tutor_version', TUTOR_VERSION ); @@ -151,7 +148,7 @@ public function upgrade_to_3_0_0() { // Beta upgrade. if ( version_compare( TUTOR_VERSION, '3.0.0-beta2', '>=' ) ) { $order_items_table = $wpdb->prefix . 'tutor_order_items'; - if ( QueryHelper::table_exists( $order_items_table ) && ! QueryHelper::column_exist( $order_items_table, 'discount_price' ) ) { + if ( DB::has_table( $order_items_table ) && ! DB::has_column( $order_items_table, 'discount_price' ) ) { // If 'discount_price' does not exist, alter the table to add 'discount_price' and 'coupon_code', and update 'sale_price'. $wpdb->query( //phpcs:ignore @@ -168,7 +165,7 @@ public function upgrade_to_3_0_0() { $order_table = $wpdb->prefix . 'tutor_orders'; $coupon_amount = 'coupon_amount'; - if ( QueryHelper::table_exists( $order_table ) && ! QueryHelper::column_exist( $order_table, $coupon_amount ) ) { + if ( DB::has_table( $order_table ) && ! DB::has_column( $order_table, $coupon_amount ) ) { $wpdb->query( "ALTER TABLE {$order_table} ADD COLUMN $coupon_amount DECIMAL(13, 2) DEFAULT NULL AFTER coupon_code" );//phpcs:ignore } @@ -176,7 +173,7 @@ public function upgrade_to_3_0_0() { * Tax Type: inclusive, exclusive */ $tax_type = 'tax_type'; - if ( QueryHelper::table_exists( $order_table ) && ! QueryHelper::column_exist( $order_table, $tax_type ) ) { + if ( DB::has_table( $order_table ) && ! DB::has_column( $order_table, $tax_type ) ) { $wpdb->query( "ALTER TABLE {$order_table} ADD COLUMN $tax_type VARCHAR(50) DEFAULT NULL AFTER pre_tax_price" );//phpcs:ignore } } @@ -198,7 +195,7 @@ public function upgrade_to_3_7_1() { */ $result = 'result'; $attempt_table = $wpdb->tutor_quiz_attempts; - if ( QueryHelper::table_exists( $attempt_table ) && ! QueryHelper::column_exist( $attempt_table, $result ) ) { + if ( DB::has_table( $attempt_table ) && ! DB::has_column( $attempt_table, $result ) ) { $wpdb->query( "ALTER TABLE {$attempt_table} ADD COLUMN result VARCHAR(10);" ); //phpcs:ignore // Index Added to improve query performance. @@ -219,7 +216,7 @@ public function upgrade_to_3_7_1() { * @since 3.7.0 */ $question_table = $wpdb->prefix . 'tutor_quiz_questions'; - if ( QueryHelper::table_exists( $question_table ) && ! QueryHelper::column_exist( $question_table, 'content_id' ) ) { + if ( DB::has_table( $question_table ) && ! DB::has_column( $question_table, 'content_id' ) ) { $wpdb->query( "ALTER TABLE {$question_table} ADD COLUMN content_id BIGINT UNSIGNED DEFAULT NULL AFTER question_id" ); //phpcs:ignore $wpdb->query( "ALTER TABLE {$question_table} ADD INDEX content_id(content_id)" );//phpcs:ignore } @@ -234,13 +231,13 @@ public function upgrade_to_3_8_0() { if ( version_compare( TUTOR_VERSION, '3.8.0', '>=' ) ) { global $wpdb; $order_table = $wpdb->prefix . 'tutor_orders'; - if ( QueryHelper::table_exists( $order_table ) && ! QueryHelper::column_exist( $order_table, 'pre_tax_price' ) ) { + if ( DB::has_table( $order_table ) && ! DB::has_column( $order_table, 'pre_tax_price' ) ) { $wpdb->query( "ALTER TABLE {$order_table} ADD COLUMN pre_tax_price DECIMAL(13, 2) NOT NULL AFTER subtotal_price" ); //phpcs:ignore } $charset_collate = $wpdb->get_charset_collate(); - $scheduler_table = QueryHelper::table_exists( $wpdb->prefix . 'tutor_scheduler' ); - $item_meta_table = QueryHelper::table_exists( $wpdb->prefix . 'tutor_order_itemmeta' ); + $scheduler_table = DB::has_table( $wpdb->prefix . 'tutor_scheduler' ); + $item_meta_table = DB::has_table( $wpdb->prefix . 'tutor_order_itemmeta' ); // Create tutor_scheduler table. if ( ! $scheduler_table ) { @@ -283,9 +280,9 @@ public function upgrade_to_3_8_0() { $detail_column = 'item_details'; $type_column = 'item_type'; - if ( QueryHelper::table_exists( $cart_item_table ) ) { - $is_detail_column_exists = QueryHelper::column_exist( $cart_item_table, $detail_column ); - $is_type_column_exists = QueryHelper::column_exist( $cart_item_table, $type_column ); + if ( DB::has_table( $cart_item_table ) ) { + $is_detail_column_exists = DB::has_column( $cart_item_table, $detail_column ); + $is_type_column_exists = DB::has_column( $cart_item_table, $type_column ); if ( ! $is_detail_column_exists ) { $wpdb->query( "ALTER TABLE {$cart_item_table} ADD {$detail_column} JSON AFTER course_id" ); @@ -327,7 +324,13 @@ public function upgrade_to_3_8_2() { /** * Update process by to 'tutor' where it is 'Tutor' */ - QueryHelper::update( $earnings_table, array( 'process_by' => 'tutor' ), array( 'process_by' => 'Tutor' ) ); + DB::table( $earnings_table ) + ->where( 'process_by', 'Tutor' ) + ->update( + array( + 'process_by' => 'tutor', + ) + ); } } From 098bf93e33498d6b64f9c852c55b3f7af6b12c0a Mon Sep 17 00:00:00 2001 From: "Md.Harun-Ur-Rashid" Date: Wed, 11 Nov 2026 11:46:53 +0600 Subject: [PATCH 10/36] refactor: optimize database table registration and naming in TableManager and Tutor classes --- classes/Tutor.php | 11 ++++--- database/TableManager.php | 63 ++++++++++----------------------------- 2 files changed, 21 insertions(+), 53 deletions(-) diff --git a/classes/Tutor.php b/classes/Tutor.php index 5d51aeb62b..350741b2ef 100644 --- a/classes/Tutor.php +++ b/classes/Tutor.php @@ -456,17 +456,16 @@ public function __construct() { * Adding Tutor Database tables to $wpdb; * * @since 1.4.2 - * @since 4.3.0 Dynamically registered from TableRegistry with multisite awareness. * @since 4.3.0 Registering tables dynamically like before. * Example: - * $wpdb->tutor_courses = $wpdb->prefix . 'tutor_courses'; - * $wpdb->tutor_lessons = $wpdb->prefix . 'tutor_lessons'; - * $wpdb->tutor_quizzes = $wpdb->prefix . 'tutor_quizzes'; + * $wpdb->tutor_courses = $wpdb->prefix . 'tutor_courses'; + * $wpdb->tutor_lessons = $wpdb->prefix . 'tutor_lessons'; + * $wpdb->tutor_quizzes = $wpdb->prefix . 'tutor_quizzes'; * ... etc */ global $wpdb; - foreach ( TableManager::get_table_classes() as $table_class ) { - $wpdb->{$table_class::get_base_name()} = $table_class::get_name(); + foreach ( TableManager::get_table_names() as $base_name => $prefixed_name ) { + $wpdb->{$base_name} = $prefixed_name; } /** diff --git a/database/TableManager.php b/database/TableManager.php index 6d138a3e72..58d3d9e065 100644 --- a/database/TableManager.php +++ b/database/TableManager.php @@ -73,54 +73,37 @@ class TableManager { * * @return array> Array of table classes. */ - public static function get_table_classes(): array { - $core_classes = self::CORE_TABLE_CLASSES; - - /** - * Filter to register additional addon tables from Pro and third-party addons. - * - * @since 4.3.0 - * - * @param array> $all_classes Array of table classes. - */ - $all_classes = apply_filters( 'tutor_database_table_classes', $core_classes ); + protected static function get_table_classes(): array { + $classes = apply_filters( 'tutor_database_table_classes', self::CORE_TABLE_CLASSES ); // Filter is instance of Table. - $all_classes = array_filter( - $all_classes, - fn( $class ) => is_string( $class ) && is_a( $class, Table::class, true ) + $classes = array_unique( + array_filter( + $classes, + fn( $class ) => is_string( $class ) && is_a( $class, Table::class, true ) + ) ); - return $all_classes; + return $classes; } /** * Get all known tables (Core + Addons + Pro via filter). - * Used for drop/cleanup operations across single-site and multisite. * * @since 4.3.0 * - * @return array Array of base table names. + * @return array Base table name => prefixed table name. */ public static function get_table_names(): array { - $table_names = array_map( - fn( $class ) => $class::get_name(), - static::get_table_classes() - ); + $table_names = array(); + foreach ( static::get_table_classes() as $class ) { + $table_names[ $class::get_base_name() ] = $class::get_name(); + } - /** - * Filter to register additional addon tables from Pro and third-party addons. - * - * @since 4.3.0 - * - * @param array $all_tables Array of base table names. - */ return apply_filters( 'tutor_database_tables', $table_names ); } - /** * Create or update a single table using dbDelta. - * Reused across core tables, upgrade routines, and addon installers. * * @since 4.3.0 * @@ -137,8 +120,7 @@ public static function create_table( string $schema ): void { } /** - * Create only the Core tables for the current active blog context. - * Called on plugin activation and new subsite provisioning. + * Create only the Core tables. * * @since 4.3.0 * @@ -151,19 +133,11 @@ public static function create_core_tables( bool $include_constraints = true ): v $table_class::create( $include_constraints ); } - /** - * Action fired after all Tutor Core tables have been created for the current blog. - * - * @since 4.3.0 - * - * @param bool $include_constraints Whether foreign key constraints were included. - */ do_action( 'tutor_database_core_tables_created', $include_constraints ); } /** - * Safely drop all known Tutor tables for the current active blog context. - * Drops both Core and Addon tables using SET FOREIGN_KEY_CHECKS = 0. + * Safely drop all known Tutor tables. * * @since 4.3.0 * @@ -171,7 +145,7 @@ public static function create_core_tables( bool $include_constraints = true ): v */ public static function drop_tables(): void { global $wpdb; - $table_names = self::get_table_names(); + $table_names = array_values( self::get_table_names() ); // Temporarily disable FK checks to cleanly drop without constraint order issues. $wpdb->query( 'SET FOREIGN_KEY_CHECKS = 0' ); @@ -182,11 +156,6 @@ public static function drop_tables(): void { $wpdb->query( 'SET FOREIGN_KEY_CHECKS = 1' ); - /** - * Action fired after Tutor tables have been dropped for the current blog. - * - * @since 4.3.0 - */ do_action( 'tutor_database_tables_dropped' ); } } From d29691d8820aa3b23f2137e9461678f7369b95b4 Mon Sep 17 00:00:00 2001 From: "Md.Harun-Ur-Rashid" Date: Wed, 11 Nov 2026 12:22:03 +0600 Subject: [PATCH 11/36] refactor: refactor multisite site provisioning and table management helpers --- classes/Multisite.php | 119 ++++++++++++++++++++++---------------- classes/Tutor.php | 7 ++- database/TableManager.php | 6 +- 3 files changed, 79 insertions(+), 53 deletions(-) diff --git a/classes/Multisite.php b/classes/Multisite.php index 22ff125140..9fd39a7318 100644 --- a/classes/Multisite.php +++ b/classes/Multisite.php @@ -31,13 +31,8 @@ public function __construct() { return; } - // Modern site initialization hook (WP 5.1+). add_action( 'wp_initialize_site', array( $this, 'on_initialize_site' ), 10, 2 ); - - // Site deletion hook. add_action( 'wp_uninitialize_site', array( $this, 'on_uninitialize_site' ) ); - - // Ensure administrator capabilities on active subsite. add_action( 'init', array( $this, 'ensure_admin_capabilities' ) ); } @@ -54,33 +49,22 @@ public function __construct() { public function on_initialize_site( \WP_Site $site, array $args = array() ): void { $blog_id = (int) $site->blog_id; - switch_to_blog( $blog_id ); - - // 1. Create all tables. - TableManager::create_core_tables( true ); - - // 2. Default options. - $default_options = Tutor::default_options(); - update_option( 'tutor_option', $default_options ); - update_option( 'tutor_version', TUTOR_VERSION ); - - // 3. User roles & permissions. - Tutor::manage_tutor_roles_and_permissions(); - - // 4. Default pages. - Tutor::save_data(); - - /** - * Action fired after a subsite is initialized with Tutor LMS. - * - * @since 4.3.0 - * - * @param int $blog_id Blog ID. - * @param \WP_Site $site Site instance. - */ - do_action( 'tutor_multisite_subsite_initialized', $blog_id, $site ); - - restore_current_blog(); + self::run_in_site( + $blog_id, + function () use ( $blog_id, $site ) { + self::provision_site(); + + /** + * Action fired after a subsite is initialized with Tutor LMS. + * + * @since 4.3.0 + * + * @param int $blog_id Blog ID. + * @param \WP_Site $site Site instance. + */ + do_action( 'tutor_multisite_subsite_initialized', $blog_id, $site ); + } + ); } /** @@ -103,11 +87,8 @@ public function on_uninitialize_site( \WP_Site $site ): void { * @param bool $should_drop Whether to drop tables. Default true. * @param int $blog_id Blog ID being deleted. */ - $should_drop = apply_filters( 'tutor_multisite_drop_tables_on_delete', true, $blog_id ); - if ( $should_drop ) { - switch_to_blog( $blog_id ); - TableManager::drop_tables(); - restore_current_blog(); + if ( apply_filters( 'tutor_multisite_drop_tables_on_delete', true, $blog_id ) ) { + self::run_in_site( $blog_id, array( TableManager::class, 'drop_tables' ) ); } /** @@ -137,19 +118,7 @@ public static function activate_network(): void { ); foreach ( $site_ids as $blog_id ) { - switch_to_blog( (int) $blog_id ); - - TableManager::create_core_tables( true ); - - $version = get_option( 'tutor_version' ); - if ( ! $version ) { - update_option( 'tutor_option', Tutor::default_options() ); - Tutor::manage_tutor_roles_and_permissions(); - Tutor::save_data(); - update_option( 'tutor_version', TUTOR_VERSION ); - } - - restore_current_blog(); + self::run_in_site( (int) $blog_id, array( __CLASS__, 'provision_site' ) ); } } @@ -169,5 +138,53 @@ public function ensure_admin_capabilities(): void { } } } -} + /** + * Create tables and seed defaults for the current site. + * + * Tables are always created or updated so missing ones are restored. + * Default options, roles and pages are seeded only on a fresh install, + * so existing settings are never overwritten. + * + * @since 4.3.0 + * + * @return void + */ + private static function provision_site(): void { + $is_installed = (bool) get_option( 'tutor_version' ); + + TableManager::create_core_tables( ! $is_installed ); + + if ( $is_installed ) { + return; + } + + update_option( 'tutor_option', Tutor::default_options() ); + Tutor::manage_tutor_roles_and_permissions(); + Tutor::save_data(); + update_option( 'tutor_version', TUTOR_VERSION ); + } + + /** + * Run a callback in the context of a given site, always restoring the previous one. + * + * @since 4.3.0 + * + * @param int $blog_id Blog ID. + * @param callable $callback Callback to run. + * + * @return void + */ + private static function run_in_site( int $blog_id, callable $callback ): void { + switch_to_blog( $blog_id ); + try { + $callback(); + } catch ( \Exception $e ) { + error_log( + sprintf( 'Tutor: site initialization failed for blog ID %d: %s', $blog_id, $e->getMessage() ) + ); + } finally { + restore_current_blog(); + } + } +} diff --git a/classes/Tutor.php b/classes/Tutor.php index 350741b2ef..22d31b0e48 100644 --- a/classes/Tutor.php +++ b/classes/Tutor.php @@ -690,9 +690,14 @@ public function init_action() { } /** - * Do some task during plugin activation + * Do some task during plugin activation. * * @since 4.0.0 Flush rewrite rules on activation. + * @since 4.3.0 Param $network_wide added for multisite. + * + * @param bool $network_wide If true, network-wide activation. + * + * @return void */ public static function tutor_activate( $network_wide = false ) { // Network-wide activation in Multisite. diff --git a/database/TableManager.php b/database/TableManager.php index 58d3d9e065..0b54b418ca 100644 --- a/database/TableManager.php +++ b/database/TableManager.php @@ -76,7 +76,11 @@ class TableManager { protected static function get_table_classes(): array { $classes = apply_filters( 'tutor_database_table_classes', self::CORE_TABLE_CLASSES ); - // Filter is instance of Table. + /** + * Validate the filtered list: + * 1. Keep only strings that are subclasses of Tutor\Core\Table. + * 2. Remove duplicates in case a class is registered more than once. + */ $classes = array_unique( array_filter( $classes, From d1528bdab2eb925025b5a011b45f149ba4900ffc Mon Sep 17 00:00:00 2001 From: "Md.Harun-Ur-Rashid" Date: Wed, 11 Nov 2026 12:28:28 +0600 Subject: [PATCH 12/36] remove commented out REST API privacy filter hook in Tutor class --- classes/Tutor.php | 2 -- 1 file changed, 2 deletions(-) diff --git a/classes/Tutor.php b/classes/Tutor.php index 22d31b0e48..02ab91e14b 100644 --- a/classes/Tutor.php +++ b/classes/Tutor.php @@ -591,8 +591,6 @@ public function __construct() { * @since 2.8.0 */ add_action( 'admin_init', array( $this, 'redirect_to_setup_page' ) ); - - // add_filter( 'rest_request_before_callbacks', array( $this, 'enforce_courses_privacy_rest_api' ), 10, 3 ); } /** From 384866a56d37f06e013c7b1d0401b9adc5402921 Mon Sep 17 00:00:00 2001 From: "Md.Harun-Ur-Rashid" Date: Wed, 11 Nov 2026 12:29:21 +0600 Subject: [PATCH 13/36] fix: prepend global namespace to WP_CLI constant check --- classes/Tutor.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/classes/Tutor.php b/classes/Tutor.php index 02ab91e14b..c1859ad9fb 100644 --- a/classes/Tutor.php +++ b/classes/Tutor.php @@ -620,7 +620,7 @@ public function redirect_to_setup_page() { if ( ( ! get_option( 'tutor_wizard' ) ) && version_compare( TUTOR_VERSION, '1.5.6', '>' ) ) { if ( ! wp_doing_ajax() ) { update_option( 'tutor_wizard', 'active' ); - $is_wp_cli = defined( 'WP_CLI' ) && WP_CLI; + $is_wp_cli = defined( 'WP_CLI' ) && \WP_CLI; if ( ! $is_wp_cli ) { wp_safe_redirect( admin_url( 'admin.php?page=tutor-setup' ) ); } From 8c7a206b1a60f053203308e2f7ce37851b67959f Mon Sep 17 00:00:00 2001 From: "Md.Harun-Ur-Rashid" Date: Thu, 26 Nov 2026 12:28:26 +0600 Subject: [PATCH 14/36] docs: add since 4.3.0 version tags to database tables and manager classes --- database/TableManager.php | 2 ++ database/Tables/CartItemsTable.php | 2 ++ database/Tables/CartsTable.php | 2 ++ database/Tables/CouponApplicationsTable.php | 2 ++ database/Tables/CouponUsagesTable.php | 2 ++ database/Tables/CouponsTable.php | 2 ++ database/Tables/CustomersTable.php | 2 ++ database/Tables/EarningsTable.php | 2 ++ database/Tables/OrderItemmetaTable.php | 2 ++ database/Tables/OrderItemsTable.php | 2 ++ database/Tables/OrdermetaTable.php | 2 ++ database/Tables/OrdersTable.php | 2 ++ database/Tables/QuizAttemptAnswersTable.php | 2 ++ database/Tables/QuizAttemptsTable.php | 2 ++ database/Tables/QuizQuestionAnswersTable.php | 2 ++ database/Tables/QuizQuestionsTable.php | 2 ++ database/Tables/SchedulerTable.php | 2 ++ database/Tables/WithdrawsTable.php | 2 ++ 18 files changed, 36 insertions(+) diff --git a/database/TableManager.php b/database/TableManager.php index 0b54b418ca..a372e6cdfe 100644 --- a/database/TableManager.php +++ b/database/TableManager.php @@ -44,6 +44,8 @@ class TableManager { /** * Core table classes created on initial installation or new subsite provisioning. * + * @since 4.3.0 + * * @var array> */ const CORE_TABLE_CLASSES = array( diff --git a/database/Tables/CartItemsTable.php b/database/Tables/CartItemsTable.php index 0d4c041b58..68887b2424 100644 --- a/database/Tables/CartItemsTable.php +++ b/database/Tables/CartItemsTable.php @@ -25,6 +25,8 @@ class CartItemsTable extends Table { /** * Base table name. * + * @since 4.3.0 + * * @var string */ protected static $table = 'tutor_cart_items'; diff --git a/database/Tables/CartsTable.php b/database/Tables/CartsTable.php index 0ec3fb1ba0..c4d5c823c0 100644 --- a/database/Tables/CartsTable.php +++ b/database/Tables/CartsTable.php @@ -25,6 +25,8 @@ class CartsTable extends Table { /** * Base table name. * + * @since 4.3.0 + * * @var string */ protected static $table = 'tutor_carts'; diff --git a/database/Tables/CouponApplicationsTable.php b/database/Tables/CouponApplicationsTable.php index d549b83683..48190d319b 100644 --- a/database/Tables/CouponApplicationsTable.php +++ b/database/Tables/CouponApplicationsTable.php @@ -24,6 +24,8 @@ class CouponApplicationsTable extends Table { /** * Base table name. * + * @since 4.3.0 + * * @var string */ protected static $table = 'tutor_coupon_applications'; diff --git a/database/Tables/CouponUsagesTable.php b/database/Tables/CouponUsagesTable.php index 9cccef609d..ce5551bbb3 100644 --- a/database/Tables/CouponUsagesTable.php +++ b/database/Tables/CouponUsagesTable.php @@ -25,6 +25,8 @@ class CouponUsagesTable extends Table { /** * Base table name. * + * @since 4.3.0 + * * @var string */ protected static $table = 'tutor_coupon_usages'; diff --git a/database/Tables/CouponsTable.php b/database/Tables/CouponsTable.php index 1677507fd7..a06d9d58a0 100644 --- a/database/Tables/CouponsTable.php +++ b/database/Tables/CouponsTable.php @@ -24,6 +24,8 @@ class CouponsTable extends Table { /** * Base table name. * + * @since 4.3.0 + * * @var string */ protected static $table = 'tutor_coupons'; diff --git a/database/Tables/CustomersTable.php b/database/Tables/CustomersTable.php index 6414cbca82..3b92850666 100644 --- a/database/Tables/CustomersTable.php +++ b/database/Tables/CustomersTable.php @@ -24,6 +24,8 @@ class CustomersTable extends Table { /** * Base table name. * + * @since 4.3.0 + * * @var string */ protected static $table = 'tutor_customers'; diff --git a/database/Tables/EarningsTable.php b/database/Tables/EarningsTable.php index 5819c93853..97dd4d7599 100644 --- a/database/Tables/EarningsTable.php +++ b/database/Tables/EarningsTable.php @@ -24,6 +24,8 @@ class EarningsTable extends Table { /** * Base table name. * + * @since 4.3.0 + * * @var string */ protected static $table = 'tutor_earnings'; diff --git a/database/Tables/OrderItemmetaTable.php b/database/Tables/OrderItemmetaTable.php index 0f6c665ed7..0dcccede61 100644 --- a/database/Tables/OrderItemmetaTable.php +++ b/database/Tables/OrderItemmetaTable.php @@ -24,6 +24,8 @@ class OrderItemmetaTable extends Table { /** * Base table name. * + * @since 4.3.0 + * * @var string */ protected static $table = 'tutor_order_itemmeta'; diff --git a/database/Tables/OrderItemsTable.php b/database/Tables/OrderItemsTable.php index 4a42509465..306931b5c0 100644 --- a/database/Tables/OrderItemsTable.php +++ b/database/Tables/OrderItemsTable.php @@ -24,6 +24,8 @@ class OrderItemsTable extends Table { /** * Base table name. * + * @since 4.3.0 + * * @var string */ protected static $table = 'tutor_order_items'; diff --git a/database/Tables/OrdermetaTable.php b/database/Tables/OrdermetaTable.php index 952bb72793..b6073d2e8d 100644 --- a/database/Tables/OrdermetaTable.php +++ b/database/Tables/OrdermetaTable.php @@ -24,6 +24,8 @@ class OrdermetaTable extends Table { /** * Base table name. * + * @since 4.3.0 + * * @var string */ protected static $table = 'tutor_ordermeta'; diff --git a/database/Tables/OrdersTable.php b/database/Tables/OrdersTable.php index d5c214c186..6f5c6d1ae2 100644 --- a/database/Tables/OrdersTable.php +++ b/database/Tables/OrdersTable.php @@ -24,6 +24,8 @@ class OrdersTable extends Table { /** * Base table name. * + * @since 4.3.0 + * * @var string */ protected static $table = 'tutor_orders'; diff --git a/database/Tables/QuizAttemptAnswersTable.php b/database/Tables/QuizAttemptAnswersTable.php index f677b21479..c9fc9c2fad 100644 --- a/database/Tables/QuizAttemptAnswersTable.php +++ b/database/Tables/QuizAttemptAnswersTable.php @@ -24,6 +24,8 @@ class QuizAttemptAnswersTable extends Table { /** * Base table name. * + * @since 4.3.0 + * * @var string */ protected static $table = 'tutor_quiz_attempt_answers'; diff --git a/database/Tables/QuizAttemptsTable.php b/database/Tables/QuizAttemptsTable.php index 86dda9f980..56f459cbcd 100644 --- a/database/Tables/QuizAttemptsTable.php +++ b/database/Tables/QuizAttemptsTable.php @@ -24,6 +24,8 @@ class QuizAttemptsTable extends Table { /** * Base table name. * + * @since 4.3.0 + * * @var string */ protected static $table = 'tutor_quiz_attempts'; diff --git a/database/Tables/QuizQuestionAnswersTable.php b/database/Tables/QuizQuestionAnswersTable.php index c89e84ea33..b6d5b1c9c0 100644 --- a/database/Tables/QuizQuestionAnswersTable.php +++ b/database/Tables/QuizQuestionAnswersTable.php @@ -24,6 +24,8 @@ class QuizQuestionAnswersTable extends Table { /** * Base table name. * + * @since 4.3.0 + * * @var string */ protected static $table = 'tutor_quiz_question_answers'; diff --git a/database/Tables/QuizQuestionsTable.php b/database/Tables/QuizQuestionsTable.php index 8c5d7287e7..2c57eab9fa 100644 --- a/database/Tables/QuizQuestionsTable.php +++ b/database/Tables/QuizQuestionsTable.php @@ -24,6 +24,8 @@ class QuizQuestionsTable extends Table { /** * Base table name. * + * @since 4.3.0 + * * @var string */ protected static $table = 'tutor_quiz_questions'; diff --git a/database/Tables/SchedulerTable.php b/database/Tables/SchedulerTable.php index aabd507332..47a960c729 100644 --- a/database/Tables/SchedulerTable.php +++ b/database/Tables/SchedulerTable.php @@ -24,6 +24,8 @@ class SchedulerTable extends Table { /** * Base table name. * + * @since 4.3.0 + * * @var string */ protected static $table = 'tutor_scheduler'; diff --git a/database/Tables/WithdrawsTable.php b/database/Tables/WithdrawsTable.php index ec3fb8196a..cecd3a31fd 100644 --- a/database/Tables/WithdrawsTable.php +++ b/database/Tables/WithdrawsTable.php @@ -24,6 +24,8 @@ class WithdrawsTable extends Table { /** * Base table name. * + * @since 4.3.0 + * * @var string */ protected static $table = 'tutor_withdraws'; From 7caefaeed5088e49c2dda6de536b486c2861b804 Mon Sep 17 00:00:00 2001 From: "Md.Harun-Ur-Rashid" Date: Thu, 26 Nov 2026 12:45:00 +0600 Subject: [PATCH 15/36] refactor: migrate earnings and withdraws table creation to dedicated classes --- classes/Tutor.php | 52 ++++------------------------------------------- 1 file changed, 4 insertions(+), 48 deletions(-) diff --git a/classes/Tutor.php b/classes/Tutor.php index 5b1c5ae86e..49040f78e3 100644 --- a/classes/Tutor.php +++ b/classes/Tutor.php @@ -15,6 +15,8 @@ use Tutor\Core\Input; use Tutor\Core\Singleton; use Tutor\Database\TableManager; +use Tutor\Database\Tables\EarningsTable; +use Tutor\Database\Tables\WithdrawsTable; use Tutor\Models\CourseModel; use Tutor\Ecommerce\Ecommerce; use Tutor\GDPR\GDPR; @@ -989,54 +991,8 @@ public static function default_options() { * @since 1.2.0 */ public static function create_withdraw_database() { - global $wpdb; - - $charset_collate = $wpdb->get_charset_collate(); - - /** - * Table SQL - * - * {$wpdb->prefix}tutor_earnings - * {$wpdb->prefix}tutor_withdraws - * - * @since 1.2.0 - */ - - $earning_table = "CREATE TABLE IF NOT EXISTS {$wpdb->prefix}tutor_earnings ( - earning_id bigint(20) NOT NULL AUTO_INCREMENT, - user_id bigint(20) DEFAULT NULL, - course_id bigint(20) DEFAULT NULL, - order_id bigint(20) DEFAULT NULL, - order_status varchar(50) DEFAULT NULL, - course_price_total decimal(16,2) DEFAULT NULL, - course_price_grand_total decimal(16,2) DEFAULT NULL, - instructor_amount decimal(16,2) DEFAULT NULL, - instructor_rate decimal(16,2) DEFAULT NULL, - admin_amount decimal(16,2) DEFAULT NULL, - admin_rate decimal(16,2) DEFAULT NULL, - commission_type varchar(20) DEFAULT NULL, - deduct_fees_amount decimal(16,2) DEFAULT NULL, - deduct_fees_name varchar(250) DEFAULT NULL, - deduct_fees_type varchar(20) DEFAULT NULL, - process_by varchar(20) DEFAULT NULL, - created_at datetime DEFAULT NULL, - PRIMARY KEY (earning_id) - ) $charset_collate;"; - - $withdraw_table = "CREATE TABLE IF NOT EXISTS {$wpdb->prefix}tutor_withdraws ( - withdraw_id bigint(20) NOT NULL AUTO_INCREMENT, - user_id bigint(20) DEFAULT NULL, - amount decimal(16,2) DEFAULT NULL, - method_data text DEFAULT NULL, - status varchar(50) DEFAULT NULL, - updated_at datetime DEFAULT NULL, - created_at datetime DEFAULT NULL, - PRIMARY KEY (withdraw_id) - ) $charset_collate;"; - - require_once ABSPATH . 'wp-admin/includes/upgrade.php'; - dbDelta( $earning_table ); - dbDelta( $withdraw_table ); + EarningsTable::create(); + WithdrawsTable::create(); /** * Setting previous dashboard to new dashboard From acfd0c26ce5e3cf96ade2026ca1070341e85cb17 Mon Sep 17 00:00:00 2001 From: "Md.Harun-Ur-Rashid" Date: Thu, 26 Nov 2026 13:06:49 +0600 Subject: [PATCH 16/36] chore: update version tags to 4.3.0 for multisite table prefix support --- core/DB.php | 2 +- helpers/QueryHelper.php | 2 +- tests/phpunit/DBTest.php | 12 ++++++------ tests/phpunit/QueryHelperTest.php | 10 +++++----- 4 files changed, 13 insertions(+), 13 deletions(-) diff --git a/core/DB.php b/core/DB.php index 4098288dbe..75ac56ceb9 100644 --- a/core/DB.php +++ b/core/DB.php @@ -2089,7 +2089,7 @@ function ( $value ) { * Supports both single-site and multisite installations. * * @since 4.2.0 - * @since 4.2.1 Added multisite base prefix support. + * @since 4.3.0 Added multisite base prefix support. * * @param string $table Table name. * diff --git a/helpers/QueryHelper.php b/helpers/QueryHelper.php index 238db42f80..f7c75b286a 100644 --- a/helpers/QueryHelper.php +++ b/helpers/QueryHelper.php @@ -1391,7 +1391,7 @@ public static function get_table_prefix() { * Supports both single-site and multisite installations. * * @since 3.7.0 - * @since 4.2.1 Added multisite base prefix support. + * @since 4.3.0 Added multisite base prefix support. * * @param string $table_name table name. * diff --git a/tests/phpunit/DBTest.php b/tests/phpunit/DBTest.php index a4194dbba2..ae6b6592dd 100644 --- a/tests/phpunit/DBTest.php +++ b/tests/phpunit/DBTest.php @@ -1307,7 +1307,7 @@ public function test_db_set_and_get() { /** * Test DB::prepare_table_name in single site environment. * - * @since 4.2.1 + * @since 4.3.0 * * @return void */ @@ -1332,7 +1332,7 @@ public function test_prepare_table_name_single_site() { /** * Test DB::prepare_table_name for site-specific tables in multisite. * - * @since 4.2.1 + * @since 4.3.0 * * @return void */ @@ -1367,7 +1367,7 @@ public function test_prepare_table_name_multisite_site_specific_tables() { /** * Test DB::prepare_table_name for global tables in multisite. * - * @since 4.2.1 + * @since 4.3.0 * * @return void */ @@ -1417,7 +1417,7 @@ public function test_prepare_table_name_multisite_global_tables() { /** * Test DB::prepare_table_name for custom tables starting with global table names. * - * @since 4.2.1 + * @since 4.3.0 * * @return void */ @@ -1445,7 +1445,7 @@ public function test_prepare_table_name_custom_table_similar_to_global_table() { /** * Test DB::table() query generation under multisite conditions. * - * @since 4.2.1 + * @since 4.3.0 * * @return void */ @@ -1476,7 +1476,7 @@ public function test_table_multisite_prefixing() { /** * Test DB::get_table_prefix. * - * @since 4.2.1 + * @since 4.3.0 * * @return void */ diff --git a/tests/phpunit/QueryHelperTest.php b/tests/phpunit/QueryHelperTest.php index de182dda2e..cb223b07b1 100644 --- a/tests/phpunit/QueryHelperTest.php +++ b/tests/phpunit/QueryHelperTest.php @@ -707,7 +707,7 @@ public function test_prepare_table_name_no_double_prefix() { /** * Test prepare_table_name handles global tables in single site. * - * @since 4.2.1 + * @since 4.3.0 * * @return void */ @@ -726,7 +726,7 @@ public function test_prepare_table_name_single_site_global_tables() { /** * Test prepare_table_name for site-specific tables in multisite. * - * @since 4.2.1 + * @since 4.3.0 * * @return void */ @@ -760,7 +760,7 @@ public function test_prepare_table_name_multisite_site_specific_tables() { /** * Test prepare_table_name for global tables in multisite. * - * @since 4.2.1 + * @since 4.3.0 * * @return void */ @@ -810,7 +810,7 @@ public function test_prepare_table_name_multisite_global_tables() { /** * Test prepare_table_name for custom tables starting with global table names. * - * @since 4.2.1 + * @since 4.3.0 * * @return void */ @@ -838,7 +838,7 @@ public function test_prepare_table_name_custom_table_similar_to_global_table() { /** * Test get_table_prefix. * - * @since 4.2.1 + * @since 4.3.0 * * @return void */ From 5752e3ea936262a6e473827ea02a401eda19e566 Mon Sep 17 00:00:00 2001 From: "Md.Harun-Ur-Rashid" Date: Thu, 26 Nov 2026 15:27:15 +0600 Subject: [PATCH 17/36] docs: update since version description for database creation method --- classes/Tutor.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/classes/Tutor.php b/classes/Tutor.php index 49040f78e3..713743d87a 100644 --- a/classes/Tutor.php +++ b/classes/Tutor.php @@ -783,7 +783,7 @@ public static function tutor_deactivation() { * Create database * * @since 1.0.0 - * @since 4.3.0 Delegated to SchemaManager for multisite support. + * @since 4.3.0 Database table creation delegated to TableManager. * * @return void */ From f7af5fd2a1cc02752c886adc9b43a9d78f3fb9e8 Mon Sep 17 00:00:00 2001 From: "Md.Harun-Ur-Rashid" Date: Thu, 26 Nov 2026 16:01:10 +0600 Subject: [PATCH 18/36] refactor: clean up unused properties, hooks, and test methods in EmailController --- ecommerce/EmailController.php | 18 +++--------------- 1 file changed, 3 insertions(+), 15 deletions(-) diff --git a/ecommerce/EmailController.php b/ecommerce/EmailController.php index cad50727ad..738e727ac1 100644 --- a/ecommerce/EmailController.php +++ b/ecommerce/EmailController.php @@ -10,13 +10,11 @@ namespace Tutor\Ecommerce; +defined( 'ABSPATH' ) || exit; + use Tutor\Models\OrderModel; use TutorPro\Subscription\Models\PlanModel; -if ( ! defined( 'ABSPATH' ) ) { - exit; -} - /** * EmailController class * @@ -50,25 +48,16 @@ class EmailController { * @return void */ public function __construct( $register_hooks = true ) { - global $wpdb; - $this->queue_table = $wpdb->tutor_email_queue; - if ( ! $register_hooks ) { return; } - add_action( 'wp_ajax_tutor_send_mail_test', array( $this, 'send_test_mail' ) ); add_action( 'tutor_order_placed', array( $this, 'order_placed' ) ); add_action( 'tutor_order_payment_status_changed', array( $this, 'order_updated' ), 10, 4 ); add_filter( 'tutor_pro/email/list', array( $this, 'setup_email_config' ) ); } - // @TODO: Will be removed later. - public function send_test_mail() { - $this->order_placed( get_current_user_id() ); - } - /** * Send E-Mail Notification for Tutor Event. * @@ -125,7 +114,7 @@ private function enqueue_email( $to, $subject, $message, $headers, $attachments foreach ( $to as $email ) { $insert_data = array_merge( $data, array( 'mail_to' => $email ) ); - $wpdb->insert( $this->queue_table, $insert_data ); + $wpdb->insert( $wpdb->tutor_email_queue, $insert_data ); } } @@ -155,7 +144,6 @@ public function send_mail( $mails ) { * Load email template. * * @param string $template template. - * @param boolean $pro is pro. * @param array $extra extra data. * * @return void From c498fba3d86efd68b709ee4456cd2f6192d72430 Mon Sep 17 00:00:00 2001 From: "Md.Harun-Ur-Rashid" Date: Thu, 26 Nov 2026 17:20:38 +0600 Subject: [PATCH 19/36] fix: foreign key issue on site delete --- classes/Multisite.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/classes/Multisite.php b/classes/Multisite.php index 9fd39a7318..ca010b39c6 100644 --- a/classes/Multisite.php +++ b/classes/Multisite.php @@ -32,7 +32,7 @@ public function __construct() { } add_action( 'wp_initialize_site', array( $this, 'on_initialize_site' ), 10, 2 ); - add_action( 'wp_uninitialize_site', array( $this, 'on_uninitialize_site' ) ); + add_action( 'wp_uninitialize_site', array( $this, 'on_uninitialize_site' ), 5 ); add_action( 'init', array( $this, 'ensure_admin_capabilities' ) ); } From c5b21d02b29705526d2a8b0f53e42abc52b36ed8 Mon Sep 17 00:00:00 2001 From: "Md.Harun-Ur-Rashid" Date: Fri, 27 Nov 2026 11:58:24 +0600 Subject: [PATCH 20/36] fix: set default value of answer_explanation to null in QuizQuestionsTable --- database/Tables/QuizQuestionsTable.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/database/Tables/QuizQuestionsTable.php b/database/Tables/QuizQuestionsTable.php index 2c57eab9fa..eb68359e46 100644 --- a/database/Tables/QuizQuestionsTable.php +++ b/database/Tables/QuizQuestionsTable.php @@ -48,7 +48,7 @@ public static function get_schema( bool $include_constraints = true ): string { quiz_id bigint(20) DEFAULT NULL, question_title text, question_description longtext, - answer_explanation longtext DEFAULT '', + answer_explanation longtext DEFAULT NULL, question_type varchar(50) DEFAULT NULL, question_mark decimal(9,2) DEFAULT NULL, question_settings longtext, From 9e5c782268a2e60d4f318aae7f16199b8840d7af Mon Sep 17 00:00:00 2001 From: "Md.Harun-Ur-Rashid" Date: Fri, 27 Nov 2026 12:06:57 +0600 Subject: [PATCH 21/36] fix: remove unused queue_table property in EmailController --- ecommerce/EmailController.php | 7 ------- 1 file changed, 7 deletions(-) diff --git a/ecommerce/EmailController.php b/ecommerce/EmailController.php index 738e727ac1..2f84b2e81b 100644 --- a/ecommerce/EmailController.php +++ b/ecommerce/EmailController.php @@ -27,13 +27,6 @@ class EmailController { const TO_ADMIN = 'email_to_admin'; const ORDER_EMAILS = 'order_emails'; - /** - * Queue table - * - * @var string - */ - private $queue_table; - /** * Constructor. * From cd4e27c7f06405b2b85fa409ca0a5f38d5435be1 Mon Sep 17 00:00:00 2001 From: "Md.Harun-Ur-Rashid" Date: Mon, 30 Nov 2026 13:47:13 +0600 Subject: [PATCH 22/36] fix: prepare table name error when it has alias --- core/DB.php | 20 ++++++++++----- helpers/QueryHelper.php | 19 +++----------- tests/phpunit/DBTest.php | 42 +++++++++++++++++++++++++++++++ tests/phpunit/QueryHelperTest.php | 42 +++++++++++++++++++++++++++++++ 4 files changed, 101 insertions(+), 22 deletions(-) diff --git a/core/DB.php b/core/DB.php index 75ac56ceb9..4610a51302 100644 --- a/core/DB.php +++ b/core/DB.php @@ -2096,22 +2096,30 @@ function ( $value ) { * @return string Prefixed table name. */ public static function prepare_table_name( string $table ): string { - $db = self::get_db(); + $table = trim( $table ); + if ( '' === $table ) { + return ''; + } + + $db = self::get_db(); + $parts = preg_split( '/\s+/', $table, 2 ); + $name = $parts[0]; + $alias = isset( $parts[1] ) ? ' ' . $parts[1] : ''; // Remove an existing prefix (site prefix first). foreach ( array_unique( array( $db->prefix, $db->base_prefix ) ) as $prefix ) { - if ( '' !== $prefix && 0 === strpos( $table, $prefix ) ) { - $table = substr( $table, strlen( $prefix ) ); + if ( '' !== $prefix && 0 === strpos( $name, $prefix ) ) { + $name = substr( $name, strlen( $prefix ) ); break; } } // Global tables use the network base prefix. - if ( in_array( $table, $db->tables( 'global', false ), true ) ) { - return $db->base_prefix . $table; + if ( in_array( $name, $db->tables( 'global', false ), true ) ) { + return $db->base_prefix . $name . $alias; } - return $db->prefix . $table; + return $db->prefix . $name . $alias; } /** diff --git a/helpers/QueryHelper.php b/helpers/QueryHelper.php index f7c75b286a..07319c2346 100644 --- a/helpers/QueryHelper.php +++ b/helpers/QueryHelper.php @@ -9,6 +9,8 @@ namespace Tutor\Helpers; +use Tutor\Core\DB; + /** * Do the common db operations through helper methods. * @@ -1398,22 +1400,7 @@ public static function get_table_prefix() { * @return string */ public static function prepare_table_name( string $table_name ) { - global $wpdb; - - // Remove an existing prefix (site prefix first). - foreach ( array_unique( array( $wpdb->prefix, $wpdb->base_prefix ) ) as $prefix ) { - if ( '' !== $prefix && 0 === strpos( $table_name, $prefix ) ) { - $table_name = substr( $table_name, strlen( $prefix ) ); - break; - } - } - - // Global tables use the network base prefix. - if ( in_array( $table_name, $wpdb->tables( 'global', false ), true ) ) { - return $wpdb->base_prefix . $table_name; - } - - return $wpdb->prefix . $table_name; + return DB::prepare_table_name( $table_name ); } /** diff --git a/tests/phpunit/DBTest.php b/tests/phpunit/DBTest.php index ae6b6592dd..e49f31550f 100644 --- a/tests/phpunit/DBTest.php +++ b/tests/phpunit/DBTest.php @@ -1442,6 +1442,48 @@ public function test_prepare_table_name_custom_table_similar_to_global_table() { } } + /** + * Test DB::prepare_table_name preserves table aliases and applies base prefix for global tables. + * + * @since 4.3.0 + * + * @return void + */ + public function test_prepare_table_name_with_alias_multisite() { + global $wpdb; + + $orig_prefix = $wpdb->prefix; + $orig_base_prefix = $wpdb->base_prefix; + + try { + $wpdb->base_prefix = 'tms_'; + $wpdb->prefix = 'tms_2_'; + + // Global tables with alias must use base_prefix. + $this->assertSame( 'tms_users u', DB::prepare_table_name( 'users u' ) ); + $this->assertSame( 'tms_users u', DB::prepare_table_name( 'tms_users u' ) ); + $this->assertSame( 'tms_users u', DB::prepare_table_name( 'tms_2_users u' ) ); + $this->assertSame( 'tms_users AS u', DB::prepare_table_name( 'users AS u' ) ); + $this->assertSame( 'tms_users AS u', DB::prepare_table_name( 'tms_users AS u' ) ); + $this->assertSame( 'tms_usermeta um', DB::prepare_table_name( 'tms_usermeta um' ) ); + + // Site-specific tables with alias must use site prefix. + $this->assertSame( 'tms_2_posts p', DB::prepare_table_name( 'posts p' ) ); + $this->assertSame( 'tms_2_posts p', DB::prepare_table_name( 'tms_2_posts p' ) ); + $this->assertSame( 'tms_2_posts AS p', DB::prepare_table_name( 'posts AS p' ) ); + + // Custom tables starting with global table names with alias are NOT global tables. + $this->assertSame( 'tms_2_users_archive ua', DB::prepare_table_name( 'users_archive ua' ) ); + + // Empty or whitespace-only table names return empty string. + $this->assertSame( '', DB::prepare_table_name( '' ) ); + $this->assertSame( '', DB::prepare_table_name( ' ' ) ); + } finally { + $wpdb->prefix = $orig_prefix; + $wpdb->base_prefix = $orig_base_prefix; + } + } + /** * Test DB::table() query generation under multisite conditions. * diff --git a/tests/phpunit/QueryHelperTest.php b/tests/phpunit/QueryHelperTest.php index cb223b07b1..25334e2a5f 100644 --- a/tests/phpunit/QueryHelperTest.php +++ b/tests/phpunit/QueryHelperTest.php @@ -835,6 +835,48 @@ public function test_prepare_table_name_custom_table_similar_to_global_table() { } } + /** + * Test prepare_table_name preserves table aliases and applies base prefix for global tables. + * + * @since 4.3.0 + * + * @return void + */ + public function test_prepare_table_name_with_alias_multisite() { + global $wpdb; + + $orig_prefix = $wpdb->prefix; + $orig_base_prefix = $wpdb->base_prefix; + + try { + $wpdb->base_prefix = 'tms_'; + $wpdb->prefix = 'tms_2_'; + + // Global tables with alias must use base_prefix. + $this->assertSame( 'tms_users u', QueryHelper::prepare_table_name( 'users u' ) ); + $this->assertSame( 'tms_users u', QueryHelper::prepare_table_name( 'tms_users u' ) ); + $this->assertSame( 'tms_users u', QueryHelper::prepare_table_name( 'tms_2_users u' ) ); + $this->assertSame( 'tms_users AS u', QueryHelper::prepare_table_name( 'users AS u' ) ); + $this->assertSame( 'tms_users AS u', QueryHelper::prepare_table_name( 'tms_users AS u' ) ); + $this->assertSame( 'tms_usermeta um', QueryHelper::prepare_table_name( 'tms_usermeta um' ) ); + + // Site-specific tables with alias must use site prefix. + $this->assertSame( 'tms_2_posts p', QueryHelper::prepare_table_name( 'posts p' ) ); + $this->assertSame( 'tms_2_posts p', QueryHelper::prepare_table_name( 'tms_2_posts p' ) ); + $this->assertSame( 'tms_2_posts AS p', QueryHelper::prepare_table_name( 'posts AS p' ) ); + + // Custom tables starting with global table names with alias are NOT global tables. + $this->assertSame( 'tms_2_users_backup ub', QueryHelper::prepare_table_name( 'users_backup ub' ) ); + + // Empty or whitespace-only table names return empty string. + $this->assertSame( '', QueryHelper::prepare_table_name( '' ) ); + $this->assertSame( '', QueryHelper::prepare_table_name( ' ' ) ); + } finally { + $wpdb->prefix = $orig_prefix; + $wpdb->base_prefix = $orig_base_prefix; + } + } + /** * Test get_table_prefix. * From b92bba1a25f2da38736375d7ba9cd99ef7c5ce58 Mon Sep 17 00:00:00 2001 From: "Md.Harun-Ur-Rashid" Date: Mon, 30 Nov 2026 13:51:12 +0600 Subject: [PATCH 23/36] revert old code for review request --- classes/Tutor.php | 32 +++++++++++++++++++++++--------- 1 file changed, 23 insertions(+), 9 deletions(-) diff --git a/classes/Tutor.php b/classes/Tutor.php index 713743d87a..eecd57328a 100644 --- a/classes/Tutor.php +++ b/classes/Tutor.php @@ -457,17 +457,31 @@ public function __construct() { * Adding Tutor Database tables to $wpdb; * * @since 1.4.2 - * @since 4.3.0 Registering tables dynamically like before. - * Example: - * $wpdb->tutor_courses = $wpdb->prefix . 'tutor_courses'; - * $wpdb->tutor_lessons = $wpdb->prefix . 'tutor_lessons'; - * $wpdb->tutor_quizzes = $wpdb->prefix . 'tutor_quizzes'; - * ... etc */ global $wpdb; - foreach ( TableManager::get_table_names() as $base_name => $prefixed_name ) { - $wpdb->{$base_name} = $prefixed_name; - } + + /** + * TODO: Dynamically register all table names using + * TableManager::get_table_names() in the future. + */ + + $wpdb->tutor_earnings = $wpdb->prefix . 'tutor_earnings'; + $wpdb->tutor_gradebooks = $wpdb->prefix . 'tutor_gradebooks'; + $wpdb->tutor_gradebooks_results = $wpdb->prefix . 'tutor_gradebooks_results'; + $wpdb->tutor_quiz_attempts = $wpdb->prefix . 'tutor_quiz_attempts'; + $wpdb->tutor_quiz_attempt_answers = $wpdb->prefix . 'tutor_quiz_attempt_answers'; + $wpdb->tutor_quiz_questions = $wpdb->prefix . 'tutor_quiz_questions'; + $wpdb->tutor_quiz_question_answers = $wpdb->prefix . 'tutor_quiz_question_answers'; + $wpdb->tutor_withdraws = $wpdb->prefix . 'tutor_withdraws'; + $wpdb->tutor_email_queue = $wpdb->prefix . 'tutor_email_queue'; + $wpdb->tutor_order_items = $wpdb->prefix . 'tutor_order_items'; + $wpdb->tutor_orders = $wpdb->prefix . 'tutor_orders'; + $wpdb->tutor_ordermeta = $wpdb->prefix . 'tutor_ordermeta'; + $wpdb->tutor_subscription_plan_items = $wpdb->prefix . 'tutor_subscription_plan_items'; + $wpdb->tutor_subscription_plans = $wpdb->prefix . 'tutor_subscription_plans'; + $wpdb->tutor_subscriptions = $wpdb->prefix . 'tutor_subscriptions'; + $wpdb->tutor_subscriptionmeta = $wpdb->prefix . 'tutor_subscriptionmeta'; + $wpdb->tutor_order_itemmeta = $wpdb->prefix . 'tutor_order_itemmeta'; /** * Changing default wp doing ajax return based on tutor ajax action From 0e7d0c519f7ff7a353bf96abf973140c40014f72 Mon Sep 17 00:00:00 2001 From: "Md.Harun-Ur-Rashid" Date: Mon, 30 Nov 2026 15:09:53 +0600 Subject: [PATCH 24/36] added table schema comment --- database/Tables/OrdersTable.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/database/Tables/OrdersTable.php b/database/Tables/OrdersTable.php index 6f5c6d1ae2..02ada9b47a 100644 --- a/database/Tables/OrdersTable.php +++ b/database/Tables/OrdersTable.php @@ -46,7 +46,7 @@ public static function get_schema( bool $include_constraints = true ): string { return "CREATE TABLE {$table} ( id BIGINT(20) UNSIGNED AUTO_INCREMENT, parent_id BIGINT(20) UNSIGNED DEFAULT 0, - transaction_id VARCHAR(255), + transaction_id VARCHAR(255) COMMENT 'Transaction id from payment gateway', user_id BIGINT(20) UNSIGNED NOT NULL, order_type VARCHAR(50) NOT NULL, order_status VARCHAR(50) NOT NULL, @@ -54,7 +54,7 @@ public static function get_schema( bool $include_constraints = true ): string { subtotal_price DECIMAL(13, 2) NOT NULL, pre_tax_price DECIMAL(13, 2) NOT NULL, tax_type VARCHAR(50), - tax_rate DECIMAL(13, 2), + tax_rate DECIMAL(13, 2) COMMENT 'Tax percentage', tax_amount DECIMAL(13, 2), total_price DECIMAL(13, 2) NOT NULL, net_payment DECIMAL(13, 2) NOT NULL, From 40b4ba8999a92ea34f1033386bb91c59800fafa2 Mon Sep 17 00:00:00 2001 From: "Md.Harun-Ur-Rashid" Date: Mon, 30 Nov 2026 15:22:14 +0600 Subject: [PATCH 25/36] cs fix --- database/Tables/CouponApplicationsTable.php | 1 - 1 file changed, 1 deletion(-) diff --git a/database/Tables/CouponApplicationsTable.php b/database/Tables/CouponApplicationsTable.php index 48190d319b..fb8f5303ed 100644 --- a/database/Tables/CouponApplicationsTable.php +++ b/database/Tables/CouponApplicationsTable.php @@ -58,4 +58,3 @@ public static function get_schema( bool $include_constraints = true ): string { ) {$collate};"; } } - From 2853a76d4d6cef50bda9678246410eeca13fad33 Mon Sep 17 00:00:00 2001 From: "Md.Harun-Ur-Rashid" Date: Mon, 30 Nov 2026 15:22:41 +0600 Subject: [PATCH 26/36] refactor: removed unused method --- database/TableManager.php | 16 ---------------- 1 file changed, 16 deletions(-) diff --git a/database/TableManager.php b/database/TableManager.php index a372e6cdfe..0d02a5d93c 100644 --- a/database/TableManager.php +++ b/database/TableManager.php @@ -108,22 +108,6 @@ public static function get_table_names(): array { return apply_filters( 'tutor_database_tables', $table_names ); } - /** - * Create or update a single table using dbDelta. - * - * @since 4.3.0 - * - * @param string $schema CREATE TABLE SQL statement. - * - * @return void - */ - public static function create_table( string $schema ): void { - if ( ! function_exists( 'dbDelta' ) ) { - require_once ABSPATH . 'wp-admin/includes/upgrade.php'; - } - - dbDelta( $schema ); - } /** * Create only the Core tables. From a4fd629ae896ff40be1a6ef17b14c5ecc3177a2e Mon Sep 17 00:00:00 2001 From: "Md.Harun-Ur-Rashid" Date: Mon, 30 Nov 2026 15:32:57 +0600 Subject: [PATCH 27/36] missing code added on provision a site --- classes/Multisite.php | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/classes/Multisite.php b/classes/Multisite.php index ca010b39c6..d423322cf1 100644 --- a/classes/Multisite.php +++ b/classes/Multisite.php @@ -159,6 +159,20 @@ private static function provision_site(): void { return; } + // Rewrite Flush. + Permalink::set_permalink_flag(); + + // Set scheduler. + if ( ! wp_next_scheduled( 'tutor_once_in_day_run_schedule' ) ) { + wp_schedule_event( tutor_time(), 'twicedaily', 'tutor_once_in_day_run_schedule' ); + } + + // Save First activation Time. + $first_activation_date = get_option( 'tutor_first_activation_time' ); + if ( ! $first_activation_date ) { + update_option( 'tutor_first_activation_time', tutor_time() ); + } + update_option( 'tutor_option', Tutor::default_options() ); Tutor::manage_tutor_roles_and_permissions(); Tutor::save_data(); From 29daa9786e4550a722623bec65e9180be461e2a8 Mon Sep 17 00:00:00 2001 From: "Md.Harun-Ur-Rashid" Date: Mon, 30 Nov 2026 15:43:12 +0600 Subject: [PATCH 28/36] update: add cap instead of add role --- classes/Multisite.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/classes/Multisite.php b/classes/Multisite.php index d423322cf1..79d9f7d4f5 100644 --- a/classes/Multisite.php +++ b/classes/Multisite.php @@ -130,10 +130,10 @@ public static function activate_network(): void { * @return void */ public function ensure_admin_capabilities(): void { - if ( current_user_can( 'administrator' ) && ! current_user_can( tutor()->instructor_role ) ) { + if ( User::is_admin() && ! current_user_can( tutor()->instructor_role ) ) { $user = wp_get_current_user(); if ( $user && $user->exists() ) { - $user->add_role( 'manage_tutor' ); + $user->add_cap( 'manage_tutor' ); $user->add_role( tutor()->instructor_role ); } } From 7187636244268ee3e28e1d4802155aeba3d72c5c Mon Sep 17 00:00:00 2001 From: "Md.Harun-Ur-Rashid" Date: Mon, 30 Nov 2026 15:46:19 +0600 Subject: [PATCH 29/36] catched trowable instead of exception --- classes/Multisite.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/classes/Multisite.php b/classes/Multisite.php index 79d9f7d4f5..59efa3016c 100644 --- a/classes/Multisite.php +++ b/classes/Multisite.php @@ -193,7 +193,7 @@ private static function run_in_site( int $blog_id, callable $callback ): void { switch_to_blog( $blog_id ); try { $callback(); - } catch ( \Exception $e ) { + } catch ( \Throwable $e ) { error_log( sprintf( 'Tutor: site initialization failed for blog ID %d: %s', $blog_id, $e->getMessage() ) ); From 405f0de574eaf260c7b7a017743aed29f5b5c4fd Mon Sep 17 00:00:00 2001 From: "Md.Harun-Ur-Rashid" Date: Mon, 30 Nov 2026 15:49:41 +0600 Subject: [PATCH 30/36] refactor: used table schema class instead of inline sql --- classes/Upgrader.php | 40 ++++++---------------------------------- 1 file changed, 6 insertions(+), 34 deletions(-) diff --git a/classes/Upgrader.php b/classes/Upgrader.php index b6a4e5277b..c53c14590e 100644 --- a/classes/Upgrader.php +++ b/classes/Upgrader.php @@ -14,6 +14,8 @@ use Tutor\Core\DB; use Tutor\Database\Tables\CouponUsagesTable; +use Tutor\Database\Tables\OrderItemmetaTable; +use Tutor\Database\Tables\SchedulerTable; use Tutor\Ecommerce\CartController; use Tutor\Ecommerce\CheckoutController; @@ -235,44 +237,14 @@ public function upgrade_to_3_8_0() { $wpdb->query( "ALTER TABLE {$order_table} ADD COLUMN pre_tax_price DECIMAL(13, 2) NOT NULL AFTER subtotal_price" ); //phpcs:ignore } - $charset_collate = $wpdb->get_charset_collate(); - $scheduler_table = DB::has_table( $wpdb->prefix . 'tutor_scheduler' ); - $item_meta_table = DB::has_table( $wpdb->prefix . 'tutor_order_itemmeta' ); - // Create tutor_scheduler table. - if ( ! $scheduler_table ) { - $table_schema = "CREATE TABLE {$wpdb->prefix}tutor_scheduler ( - id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, - type VARCHAR(50) NOT NULL COMMENT 'Type of schedule, e.g., gift, email, reminder', - reference_id VARCHAR(255) NOT NULL COMMENT 'Unique reference id, token, etc', - scheduled_at_gmt DATETIME NOT NULL COMMENT 'When the action should be executed', - status VARCHAR(255) NOT NULL DEFAULT 'processing', - payload LONGTEXT, - created_at_gmt DATETIME, - updated_at_gmt DATETIME, - scheduled_by BIGINT UNSIGNED COMMENT 'User who scheduled the action', - scheduled_for BIGINT UNSIGNED COMMENT 'Target user of the scheduled action', - PRIMARY KEY (id), - KEY idx_context_status (type, status), - KEY idx_status (status), - KEY idx_scheduled_at_gmt (scheduled_at_gmt) - ) $charset_collate;"; - dbDelta( $table_schema ); + if ( ! SchedulerTable::exists() ) { + SchedulerTable::create(); } // Create order_item_meta table. - if ( ! $item_meta_table ) { - $item_meta_table = "CREATE TABLE {$wpdb->prefix}tutor_order_itemmeta ( - id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, - item_id BIGINT(20) UNSIGNED NOT NULL, - meta_key VARCHAR(255) NOT NULL, - meta_value LONGTEXT NOT NULL, - PRIMARY KEY (id), - KEY item_id (item_id), - KEY meta_key (meta_key), - CONSTRAINT fk_tutor_itemmeta FOREIGN KEY (item_id) REFERENCES {$wpdb->prefix}tutor_order_items(id) ON DELETE CASCADE - ) $charset_collate;"; - dbDelta( $item_meta_table ); + if ( ! OrderItemmetaTable::exists() ) { + OrderItemmetaTable::create(); } // Check if the column already exists. From 4a6f45a0c12037ca442bb10994585b12094794b6 Mon Sep 17 00:00:00 2001 From: "Md.Harun-Ur-Rashid" Date: Mon, 30 Nov 2026 16:00:05 +0600 Subject: [PATCH 31/36] override include constraints for existing table --- core/Table.php | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/core/Table.php b/core/Table.php index c5db445027..da42da0a7e 100644 --- a/core/Table.php +++ b/core/Table.php @@ -103,6 +103,10 @@ public static function create( bool $include_constraints = true ): void { require_once ABSPATH . 'wp-admin/includes/upgrade.php'; } + // Avoid foreign key errors: dbDelta() cannot add FOREIGN KEY constraints + // to existing tables, so include them only when creating new tables. + $include_constraints = $include_constraints && ! static::exists(); + dbDelta( static::get_schema( $include_constraints ) ); } From 1e9bb18bd5cc24b06f1404df8f2c5003ebaf4db9 Mon Sep 17 00:00:00 2001 From: "Md.Harun-Ur-Rashid" Date: Mon, 30 Nov 2026 16:19:40 +0600 Subject: [PATCH 32/36] refactor: remove unused Table class imports from database table classes --- database/Tables/CartItemsTable.php | 1 - database/Tables/CartsTable.php | 1 - database/Tables/CouponApplicationsTable.php | 2 -- database/Tables/CouponUsagesTable.php | 1 - database/Tables/CouponsTable.php | 2 -- database/Tables/CustomersTable.php | 2 -- database/Tables/EarningsTable.php | 2 -- database/Tables/OrderItemmetaTable.php | 2 -- database/Tables/OrderItemsTable.php | 2 -- database/Tables/OrdermetaTable.php | 2 -- database/Tables/OrdersTable.php | 2 -- database/Tables/QuizAttemptAnswersTable.php | 2 -- database/Tables/QuizAttemptsTable.php | 2 -- database/Tables/QuizQuestionAnswersTable.php | 2 -- database/Tables/QuizQuestionsTable.php | 2 -- database/Tables/SchedulerTable.php | 2 -- {core => database/Tables}/Table.php | 4 +++- database/Tables/WithdrawsTable.php | 2 -- 18 files changed, 3 insertions(+), 32 deletions(-) rename {core => database/Tables}/Table.php (98%) diff --git a/database/Tables/CartItemsTable.php b/database/Tables/CartItemsTable.php index 68887b2424..971985de38 100644 --- a/database/Tables/CartItemsTable.php +++ b/database/Tables/CartItemsTable.php @@ -13,7 +13,6 @@ defined( 'ABSPATH' ) || exit; use Tutor\Core\DB; -use Tutor\Core\Table; /** * Class CartItemsTable diff --git a/database/Tables/CartsTable.php b/database/Tables/CartsTable.php index c4d5c823c0..664127dece 100644 --- a/database/Tables/CartsTable.php +++ b/database/Tables/CartsTable.php @@ -13,7 +13,6 @@ defined( 'ABSPATH' ) || exit; use Tutor\Core\DB; -use Tutor\Core\Table; /** * Class CartsTable diff --git a/database/Tables/CouponApplicationsTable.php b/database/Tables/CouponApplicationsTable.php index fb8f5303ed..84bbce8abe 100644 --- a/database/Tables/CouponApplicationsTable.php +++ b/database/Tables/CouponApplicationsTable.php @@ -12,8 +12,6 @@ defined( 'ABSPATH' ) || exit; -use Tutor\Core\Table; - /** * Class CouponApplicationsTable * diff --git a/database/Tables/CouponUsagesTable.php b/database/Tables/CouponUsagesTable.php index ce5551bbb3..3a040f5c34 100644 --- a/database/Tables/CouponUsagesTable.php +++ b/database/Tables/CouponUsagesTable.php @@ -13,7 +13,6 @@ defined( 'ABSPATH' ) || exit; use Tutor\Core\DB; -use Tutor\Core\Table; /** * Class CouponUsagesTable diff --git a/database/Tables/CouponsTable.php b/database/Tables/CouponsTable.php index a06d9d58a0..bbb2750841 100644 --- a/database/Tables/CouponsTable.php +++ b/database/Tables/CouponsTable.php @@ -12,8 +12,6 @@ defined( 'ABSPATH' ) || exit; -use Tutor\Core\Table; - /** * Class CouponsTable * diff --git a/database/Tables/CustomersTable.php b/database/Tables/CustomersTable.php index 3b92850666..b127c39a0a 100644 --- a/database/Tables/CustomersTable.php +++ b/database/Tables/CustomersTable.php @@ -12,8 +12,6 @@ defined( 'ABSPATH' ) || exit; -use Tutor\Core\Table; - /** * Class CustomersTable * diff --git a/database/Tables/EarningsTable.php b/database/Tables/EarningsTable.php index 97dd4d7599..cc21e43f70 100644 --- a/database/Tables/EarningsTable.php +++ b/database/Tables/EarningsTable.php @@ -12,8 +12,6 @@ defined( 'ABSPATH' ) || exit; -use Tutor\Core\Table; - /** * Class EarningsTable * diff --git a/database/Tables/OrderItemmetaTable.php b/database/Tables/OrderItemmetaTable.php index 0dcccede61..2b22ba097b 100644 --- a/database/Tables/OrderItemmetaTable.php +++ b/database/Tables/OrderItemmetaTable.php @@ -12,8 +12,6 @@ defined( 'ABSPATH' ) || exit; -use Tutor\Core\Table; - /** * Class OrderItemmetaTable * diff --git a/database/Tables/OrderItemsTable.php b/database/Tables/OrderItemsTable.php index 306931b5c0..d899a3d9a1 100644 --- a/database/Tables/OrderItemsTable.php +++ b/database/Tables/OrderItemsTable.php @@ -12,8 +12,6 @@ defined( 'ABSPATH' ) || exit; -use Tutor\Core\Table; - /** * Class OrderItemsTable * diff --git a/database/Tables/OrdermetaTable.php b/database/Tables/OrdermetaTable.php index b6073d2e8d..704cc55a1b 100644 --- a/database/Tables/OrdermetaTable.php +++ b/database/Tables/OrdermetaTable.php @@ -12,8 +12,6 @@ defined( 'ABSPATH' ) || exit; -use Tutor\Core\Table; - /** * Class OrdermetaTable * diff --git a/database/Tables/OrdersTable.php b/database/Tables/OrdersTable.php index 02ada9b47a..ec9d919589 100644 --- a/database/Tables/OrdersTable.php +++ b/database/Tables/OrdersTable.php @@ -12,8 +12,6 @@ defined( 'ABSPATH' ) || exit; -use Tutor\Core\Table; - /** * Class OrdersTable * diff --git a/database/Tables/QuizAttemptAnswersTable.php b/database/Tables/QuizAttemptAnswersTable.php index c9fc9c2fad..c10ec0007a 100644 --- a/database/Tables/QuizAttemptAnswersTable.php +++ b/database/Tables/QuizAttemptAnswersTable.php @@ -12,8 +12,6 @@ defined( 'ABSPATH' ) || exit; -use Tutor\Core\Table; - /** * Class QuizAttemptAnswersTable * diff --git a/database/Tables/QuizAttemptsTable.php b/database/Tables/QuizAttemptsTable.php index 56f459cbcd..ebbe8600df 100644 --- a/database/Tables/QuizAttemptsTable.php +++ b/database/Tables/QuizAttemptsTable.php @@ -12,8 +12,6 @@ defined( 'ABSPATH' ) || exit; -use Tutor\Core\Table; - /** * Class QuizAttemptsTable * diff --git a/database/Tables/QuizQuestionAnswersTable.php b/database/Tables/QuizQuestionAnswersTable.php index b6d5b1c9c0..b1221f80a6 100644 --- a/database/Tables/QuizQuestionAnswersTable.php +++ b/database/Tables/QuizQuestionAnswersTable.php @@ -12,8 +12,6 @@ defined( 'ABSPATH' ) || exit; -use Tutor\Core\Table; - /** * Class QuizQuestionAnswersTable * diff --git a/database/Tables/QuizQuestionsTable.php b/database/Tables/QuizQuestionsTable.php index eb68359e46..5cf70e1f81 100644 --- a/database/Tables/QuizQuestionsTable.php +++ b/database/Tables/QuizQuestionsTable.php @@ -12,8 +12,6 @@ defined( 'ABSPATH' ) || exit; -use Tutor\Core\Table; - /** * Class QuizQuestionsTable * diff --git a/database/Tables/SchedulerTable.php b/database/Tables/SchedulerTable.php index 47a960c729..de3c26fa19 100644 --- a/database/Tables/SchedulerTable.php +++ b/database/Tables/SchedulerTable.php @@ -12,8 +12,6 @@ defined( 'ABSPATH' ) || exit; -use Tutor\Core\Table; - /** * Class SchedulerTable * diff --git a/core/Table.php b/database/Tables/Table.php similarity index 98% rename from core/Table.php rename to database/Tables/Table.php index da42da0a7e..a0e929a472 100644 --- a/core/Table.php +++ b/database/Tables/Table.php @@ -11,7 +11,9 @@ * @since 4.3.0 */ -namespace Tutor\Core; +namespace Tutor\Database\Tables; + +use Tutor\Core\DB; defined( 'ABSPATH' ) || exit; diff --git a/database/Tables/WithdrawsTable.php b/database/Tables/WithdrawsTable.php index cecd3a31fd..200d33ca44 100644 --- a/database/Tables/WithdrawsTable.php +++ b/database/Tables/WithdrawsTable.php @@ -12,8 +12,6 @@ defined( 'ABSPATH' ) || exit; -use Tutor\Core\Table; - /** * Class WithdrawsTable * From 08408987cca18ca1a169ac76db554618f9e59159 Mon Sep 17 00:00:00 2001 From: "Md.Harun-Ur-Rashid" Date: Mon, 30 Nov 2026 16:20:40 +0600 Subject: [PATCH 33/36] docs: remove outdated since tags from multisite hooks --- classes/Multisite.php | 4 ---- 1 file changed, 4 deletions(-) diff --git a/classes/Multisite.php b/classes/Multisite.php index 59efa3016c..e966336509 100644 --- a/classes/Multisite.php +++ b/classes/Multisite.php @@ -57,8 +57,6 @@ function () use ( $blog_id, $site ) { /** * Action fired after a subsite is initialized with Tutor LMS. * - * @since 4.3.0 - * * @param int $blog_id Blog ID. * @param \WP_Site $site Site instance. */ @@ -82,8 +80,6 @@ public function on_uninitialize_site( \WP_Site $site ): void { /** * Filter whether to drop Tutor tables when a subsite is deleted. * - * @since 4.3.0 - * * @param bool $should_drop Whether to drop tables. Default true. * @param int $blog_id Blog ID being deleted. */ From 07ba985513445311486ca452dca68fb0278e74ec Mon Sep 17 00:00:00 2001 From: "Md.Harun-Ur-Rashid" Date: Mon, 30 Nov 2026 17:09:41 +0600 Subject: [PATCH 34/36] fix: improve database table prefixing, multisite provisioning, and JSON column types --- classes/Multisite.php | 32 +++++++++++++++------ classes/Upgrader.php | 2 +- database/TableManager.php | 2 +- database/Tables/CartItemsTable.php | 2 +- database/Tables/CartsTable.php | 2 +- database/Tables/CouponApplicationsTable.php | 2 +- database/Tables/EarningsTable.php | 2 +- database/Tables/OrderItemmetaTable.php | 2 +- database/Tables/OrderItemsTable.php | 2 +- database/Tables/OrdermetaTable.php | 2 +- database/Tables/Table.php | 8 +++++- database/Tables/WithdrawsTable.php | 2 +- 12 files changed, 40 insertions(+), 20 deletions(-) diff --git a/classes/Multisite.php b/classes/Multisite.php index e966336509..e639e8c595 100644 --- a/classes/Multisite.php +++ b/classes/Multisite.php @@ -33,6 +33,7 @@ public function __construct() { add_action( 'wp_initialize_site', array( $this, 'on_initialize_site' ), 10, 2 ); add_action( 'wp_uninitialize_site', array( $this, 'on_uninitialize_site' ), 5 ); + add_action( 'init', array( $this, 'maybe_provision_current_site' ), 1 ); add_action( 'init', array( $this, 'ensure_admin_capabilities' ) ); } @@ -99,23 +100,36 @@ public function on_uninitialize_site( \WP_Site $site ): void { } /** - * Network activation runner to provision all existing sites in network. + * Network activation runner. + * + * Provisions the current site immediately; remaining subsites are lazily + * provisioned on their first request via {@see maybe_provision_current_site()} + * to avoid timeouts on large networks. * * @since 4.3.0 * * @return void */ public static function activate_network(): void { - $site_ids = get_sites( - array( - 'fields' => 'ids', - 'number' => 0, - ) - ); + self::provision_site(); + } - foreach ( $site_ids as $blog_id ) { - self::run_in_site( (int) $blog_id, array( __CLASS__, 'provision_site' ) ); + /** + * Lazily provision the current subsite if Tutor has not been initialized on it yet. + * + * Covers existing subsites after network activation as well as sites created + * while the plugin was inactive. + * + * @since 4.3.0 + * + * @return void + */ + public function maybe_provision_current_site(): void { + if ( wp_installing() || get_option( 'tutor_version' ) ) { + return; } + + self::provision_site(); } /** diff --git a/classes/Upgrader.php b/classes/Upgrader.php index c53c14590e..7028c39518 100644 --- a/classes/Upgrader.php +++ b/classes/Upgrader.php @@ -257,7 +257,7 @@ public function upgrade_to_3_8_0() { $is_type_column_exists = DB::has_column( $cart_item_table, $type_column ); if ( ! $is_detail_column_exists ) { - $wpdb->query( "ALTER TABLE {$cart_item_table} ADD {$detail_column} JSON AFTER course_id" ); + $wpdb->query( "ALTER TABLE {$cart_item_table} ADD {$detail_column} LONGTEXT AFTER course_id" ); } if ( ! $is_type_column_exists ) { diff --git a/database/TableManager.php b/database/TableManager.php index 0d02a5d93c..9859d27b84 100644 --- a/database/TableManager.php +++ b/database/TableManager.php @@ -15,7 +15,7 @@ defined( 'ABSPATH' ) || exit; -use Tutor\Core\Table; +use Tutor\Database\Tables\Table; use Tutor\Database\Tables\QuizAttemptsTable; use Tutor\Database\Tables\QuizAttemptAnswersTable; use Tutor\Database\Tables\QuizQuestionsTable; diff --git a/database/Tables/CartItemsTable.php b/database/Tables/CartItemsTable.php index 971985de38..9a03d3c0fe 100644 --- a/database/Tables/CartItemsTable.php +++ b/database/Tables/CartItemsTable.php @@ -59,7 +59,7 @@ public static function get_schema( bool $include_constraints = true ): string { cart_id BIGINT(20) UNSIGNED NOT NULL, course_id BIGINT(20) UNSIGNED NOT NULL, item_type VARCHAR(255), - item_details JSON, + item_details LONGTEXT, PRIMARY KEY (id), KEY cart_id (cart_id), KEY course_id (course_id){$constraints} diff --git a/database/Tables/CartsTable.php b/database/Tables/CartsTable.php index 664127dece..228bcc268a 100644 --- a/database/Tables/CartsTable.php +++ b/database/Tables/CartsTable.php @@ -47,7 +47,7 @@ public static function get_schema( bool $include_constraints = true ): string { $constraints = ''; if ( $include_constraints ) { $fk_user = static::fk_name( 'fk_tutor_cart_user_id' ); - $constraints = ", CONSTRAINT {$fk_user} FOREIGN KEY (user_id) REFERENCES {$users_table}(ID) ON DELETE CASCADE"; + $constraints = ",\n\t\t\tCONSTRAINT {$fk_user} FOREIGN KEY (user_id) REFERENCES {$users_table}(ID) ON DELETE CASCADE"; } return "CREATE TABLE {$table} ( diff --git a/database/Tables/CouponApplicationsTable.php b/database/Tables/CouponApplicationsTable.php index 84bbce8abe..7276486a00 100644 --- a/database/Tables/CouponApplicationsTable.php +++ b/database/Tables/CouponApplicationsTable.php @@ -45,7 +45,7 @@ public static function get_schema( bool $include_constraints = true ): string { $constraints = ''; if ( $include_constraints ) { $fk_name = static::fk_name( 'fk_tutor_coupon_application_coupon_code' ); - $constraints = ", CONSTRAINT {$fk_name} FOREIGN KEY (coupon_code) REFERENCES {$coupons_table}(coupon_code) ON DELETE CASCADE"; + $constraints = ",\n\t\t\tCONSTRAINT {$fk_name} FOREIGN KEY (coupon_code) REFERENCES {$coupons_table}(coupon_code) ON DELETE CASCADE"; } return "CREATE TABLE {$table} ( diff --git a/database/Tables/EarningsTable.php b/database/Tables/EarningsTable.php index cc21e43f70..d13bd9b215 100644 --- a/database/Tables/EarningsTable.php +++ b/database/Tables/EarningsTable.php @@ -41,7 +41,7 @@ public static function get_schema( bool $include_constraints = true ): string { $table = static::get_name(); $collate = static::get_charset_collate(); - return "CREATE TABLE IF NOT EXISTS {$table} ( + return "CREATE TABLE {$table} ( earning_id bigint(20) NOT NULL AUTO_INCREMENT, user_id bigint(20) DEFAULT NULL, course_id bigint(20) DEFAULT NULL, diff --git a/database/Tables/OrderItemmetaTable.php b/database/Tables/OrderItemmetaTable.php index 2b22ba097b..9f9f658de8 100644 --- a/database/Tables/OrderItemmetaTable.php +++ b/database/Tables/OrderItemmetaTable.php @@ -45,7 +45,7 @@ public static function get_schema( bool $include_constraints = true ): string { $constraints = ''; if ( $include_constraints ) { $fk_name = static::fk_name( 'fk_tutor_itemmeta' ); - $constraints = ", CONSTRAINT {$fk_name} FOREIGN KEY (item_id) REFERENCES {$order_items_table}(id) ON DELETE CASCADE"; + $constraints = ",\n\t\t\tCONSTRAINT {$fk_name} FOREIGN KEY (item_id) REFERENCES {$order_items_table}(id) ON DELETE CASCADE"; } return "CREATE TABLE {$table} ( diff --git a/database/Tables/OrderItemsTable.php b/database/Tables/OrderItemsTable.php index d899a3d9a1..bfbac453d5 100644 --- a/database/Tables/OrderItemsTable.php +++ b/database/Tables/OrderItemsTable.php @@ -45,7 +45,7 @@ public static function get_schema( bool $include_constraints = true ): string { $constraints = ''; if ( $include_constraints ) { $fk_name = static::fk_name( 'fk_tutor_order_item_order_id' ); - $constraints = ", CONSTRAINT {$fk_name} FOREIGN KEY (order_id) REFERENCES {$orders_table}(id) ON DELETE CASCADE"; + $constraints = ",\n\t\t\tCONSTRAINT {$fk_name} FOREIGN KEY (order_id) REFERENCES {$orders_table}(id) ON DELETE CASCADE"; } return "CREATE TABLE {$table} ( diff --git a/database/Tables/OrdermetaTable.php b/database/Tables/OrdermetaTable.php index 704cc55a1b..67977b96ee 100644 --- a/database/Tables/OrdermetaTable.php +++ b/database/Tables/OrdermetaTable.php @@ -45,7 +45,7 @@ public static function get_schema( bool $include_constraints = true ): string { $constraints = ''; if ( $include_constraints ) { $fk_name = static::fk_name( 'fk_tutor_ordermeta_order_id' ); - $constraints = ", CONSTRAINT {$fk_name} FOREIGN KEY (order_id) REFERENCES {$orders_table}(id) ON DELETE CASCADE"; + $constraints = ",\n\t\t\tCONSTRAINT {$fk_name} FOREIGN KEY (order_id) REFERENCES {$orders_table}(id) ON DELETE CASCADE"; } return "CREATE TABLE {$table} ( diff --git a/database/Tables/Table.php b/database/Tables/Table.php index a0e929a472..24b357ccf4 100644 --- a/database/Tables/Table.php +++ b/database/Tables/Table.php @@ -53,7 +53,13 @@ public static function get_base_name(): string { * @return string */ public static function get_name(): string { - return DB::prepare_table_name( static::$table ); + global $wpdb; + + if ( in_array( static::$table, $wpdb->tables( 'global', false ), true ) ) { + return $wpdb->base_prefix . static::$table; + } + + return $wpdb->prefix . static::$table; } /** diff --git a/database/Tables/WithdrawsTable.php b/database/Tables/WithdrawsTable.php index 200d33ca44..fff6f739c1 100644 --- a/database/Tables/WithdrawsTable.php +++ b/database/Tables/WithdrawsTable.php @@ -41,7 +41,7 @@ public static function get_schema( bool $include_constraints = true ): string { $table = static::get_name(); $collate = static::get_charset_collate(); - return "CREATE TABLE IF NOT EXISTS {$table} ( + return "CREATE TABLE {$table} ( withdraw_id bigint(20) NOT NULL AUTO_INCREMENT, user_id bigint(20) DEFAULT NULL, amount decimal(16,2) DEFAULT NULL, From 9406f32baaa86f250eec5d58a37f7f59a99bfea6 Mon Sep 17 00:00:00 2001 From: "Md.Harun-Ur-Rashid" Date: Mon, 30 Nov 2026 17:18:16 +0600 Subject: [PATCH 35/36] fix: add support for table names starting with digits in database helpers --- core/DB.php | 18 +++++++++- database/Tables/CartsTable.php | 3 +- database/Tables/CouponApplicationsTable.php | 3 +- database/Tables/OrderItemmetaTable.php | 3 +- database/Tables/OrderItemsTable.php | 3 +- database/Tables/OrdermetaTable.php | 3 +- tests/phpunit/DBTest.php | 39 +++++++++++++++++++++ tests/phpunit/QueryHelperTest.php | 7 ++++ 8 files changed, 73 insertions(+), 6 deletions(-) diff --git a/core/DB.php b/core/DB.php index 4610a51302..afab2ff178 100644 --- a/core/DB.php +++ b/core/DB.php @@ -1985,6 +1985,22 @@ public static function is_valid_identifier( string $identifier ): bool { return (bool) preg_match( '/^[A-Za-z_][A-Za-z0-9_]*$/', $identifier ); } + /** + * Validate a SQL table name identifier (allows leading digits, e.g. '2fa_posts'). + * + * WordPress allows table prefixes starting with digits (`wpdb::set_prefix()` + * permits `[a-z0-9_]`), so table name validation must accept leading digits. + * + * @since 4.3.0 + * + * @param string $table_name Table name to validate. + * + * @return bool True if valid. + */ + public static function is_valid_table_name( string $table_name ): bool { + return (bool) preg_match( '/^[A-Za-z0-9_]+$/', $table_name ); + } + /** * Check whether a comparison operator is supported. * @@ -2239,7 +2255,7 @@ private static function resolve_existing_table( string $table ): ?string { // Check prefixed table name first. $prefixed = self::prepare_table_name( $table ); - if ( self::is_valid_identifier( $prefixed ) && self::table_exists_in_db( $prefixed ) ) { + if ( self::is_valid_table_name( $prefixed ) && self::table_exists_in_db( $prefixed ) ) { return $prefixed; } diff --git a/database/Tables/CartsTable.php b/database/Tables/CartsTable.php index 228bcc268a..904691982f 100644 --- a/database/Tables/CartsTable.php +++ b/database/Tables/CartsTable.php @@ -47,7 +47,8 @@ public static function get_schema( bool $include_constraints = true ): string { $constraints = ''; if ( $include_constraints ) { $fk_user = static::fk_name( 'fk_tutor_cart_user_id' ); - $constraints = ",\n\t\t\tCONSTRAINT {$fk_user} FOREIGN KEY (user_id) REFERENCES {$users_table}(ID) ON DELETE CASCADE"; + $constraints = ", + CONSTRAINT {$fk_user} FOREIGN KEY (user_id) REFERENCES {$users_table}(ID) ON DELETE CASCADE"; } return "CREATE TABLE {$table} ( diff --git a/database/Tables/CouponApplicationsTable.php b/database/Tables/CouponApplicationsTable.php index 7276486a00..f97c8b8def 100644 --- a/database/Tables/CouponApplicationsTable.php +++ b/database/Tables/CouponApplicationsTable.php @@ -45,7 +45,8 @@ public static function get_schema( bool $include_constraints = true ): string { $constraints = ''; if ( $include_constraints ) { $fk_name = static::fk_name( 'fk_tutor_coupon_application_coupon_code' ); - $constraints = ",\n\t\t\tCONSTRAINT {$fk_name} FOREIGN KEY (coupon_code) REFERENCES {$coupons_table}(coupon_code) ON DELETE CASCADE"; + $constraints = ", + CONSTRAINT {$fk_name} FOREIGN KEY (coupon_code) REFERENCES {$coupons_table}(coupon_code) ON DELETE CASCADE"; } return "CREATE TABLE {$table} ( diff --git a/database/Tables/OrderItemmetaTable.php b/database/Tables/OrderItemmetaTable.php index 9f9f658de8..81a727e74f 100644 --- a/database/Tables/OrderItemmetaTable.php +++ b/database/Tables/OrderItemmetaTable.php @@ -45,7 +45,8 @@ public static function get_schema( bool $include_constraints = true ): string { $constraints = ''; if ( $include_constraints ) { $fk_name = static::fk_name( 'fk_tutor_itemmeta' ); - $constraints = ",\n\t\t\tCONSTRAINT {$fk_name} FOREIGN KEY (item_id) REFERENCES {$order_items_table}(id) ON DELETE CASCADE"; + $constraints = ", + CONSTRAINT {$fk_name} FOREIGN KEY (item_id) REFERENCES {$order_items_table}(id) ON DELETE CASCADE"; } return "CREATE TABLE {$table} ( diff --git a/database/Tables/OrderItemsTable.php b/database/Tables/OrderItemsTable.php index bfbac453d5..e7a948b797 100644 --- a/database/Tables/OrderItemsTable.php +++ b/database/Tables/OrderItemsTable.php @@ -45,7 +45,8 @@ public static function get_schema( bool $include_constraints = true ): string { $constraints = ''; if ( $include_constraints ) { $fk_name = static::fk_name( 'fk_tutor_order_item_order_id' ); - $constraints = ",\n\t\t\tCONSTRAINT {$fk_name} FOREIGN KEY (order_id) REFERENCES {$orders_table}(id) ON DELETE CASCADE"; + $constraints = ", + CONSTRAINT {$fk_name} FOREIGN KEY (order_id) REFERENCES {$orders_table}(id) ON DELETE CASCADE"; } return "CREATE TABLE {$table} ( diff --git a/database/Tables/OrdermetaTable.php b/database/Tables/OrdermetaTable.php index 67977b96ee..8b71aa958a 100644 --- a/database/Tables/OrdermetaTable.php +++ b/database/Tables/OrdermetaTable.php @@ -45,7 +45,8 @@ public static function get_schema( bool $include_constraints = true ): string { $constraints = ''; if ( $include_constraints ) { $fk_name = static::fk_name( 'fk_tutor_ordermeta_order_id' ); - $constraints = ",\n\t\t\tCONSTRAINT {$fk_name} FOREIGN KEY (order_id) REFERENCES {$orders_table}(id) ON DELETE CASCADE"; + $constraints = ", + CONSTRAINT {$fk_name} FOREIGN KEY (order_id) REFERENCES {$orders_table}(id) ON DELETE CASCADE"; } return "CREATE TABLE {$table} ( diff --git a/tests/phpunit/DBTest.php b/tests/phpunit/DBTest.php index e49f31550f..ff0dbfaf44 100644 --- a/tests/phpunit/DBTest.php +++ b/tests/phpunit/DBTest.php @@ -1484,6 +1484,45 @@ public function test_prepare_table_name_with_alias_multisite() { } } + /** + * Test DB::has_table() and DB::has_column() support table names starting with digits. + * + * @since 4.3.0 + * + * @return void + */ + public function test_has_table_and_column_with_digit_prefixed_table() { + global $wpdb; + + $orig_prefix = $wpdb->prefix; + $orig_base_prefix = $wpdb->base_prefix; + $table_name = '2fa_tutor_digit_test'; + + // WP_UnitTestCase rewrites CREATE/DROP TABLE to TEMPORARY, which SHOW TABLES LIKE hides. + remove_filter( 'query', array( $this, '_create_temporary_tables' ) ); + remove_filter( 'query', array( $this, '_drop_temporary_tables' ) ); + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared + $wpdb->query( "CREATE TABLE IF NOT EXISTS `{$table_name}` (id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT, PRIMARY KEY (id))" ); + + try { + $wpdb->base_prefix = '2fa_'; + $wpdb->prefix = '2fa_'; + + $this->assertTrue( DB::is_valid_table_name( $table_name ) ); + $this->assertTrue( DB::has_table( $table_name ) ); + $this->assertTrue( DB::has_table( 'tutor_digit_test' ) ); + $this->assertTrue( DB::has_column( $table_name, 'id' ) ); + $this->assertFalse( DB::has_column( $table_name, 'non_existent' ) ); + } finally { + $wpdb->prefix = $orig_prefix; + $wpdb->base_prefix = $orig_base_prefix; + // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared + $wpdb->query( "DROP TABLE IF EXISTS `{$table_name}`" ); + add_filter( 'query', array( $this, '_create_temporary_tables' ) ); + add_filter( 'query', array( $this, '_drop_temporary_tables' ) ); + } + } + /** * Test DB::table() query generation under multisite conditions. * diff --git a/tests/phpunit/QueryHelperTest.php b/tests/phpunit/QueryHelperTest.php index 25334e2a5f..a882d60c2d 100644 --- a/tests/phpunit/QueryHelperTest.php +++ b/tests/phpunit/QueryHelperTest.php @@ -871,6 +871,13 @@ public function test_prepare_table_name_with_alias_multisite() { // Empty or whitespace-only table names return empty string. $this->assertSame( '', QueryHelper::prepare_table_name( '' ) ); $this->assertSame( '', QueryHelper::prepare_table_name( ' ' ) ); + + // Prefix matching leading substring of base table name must not strip base name. + $wpdb->base_prefix = 'tutor_'; + $wpdb->prefix = 'tutor_'; + $this->assertSame( 'tutor_tutor_orders', QueryHelper::prepare_table_name( 'tutor_orders' ) ); + $this->assertSame( 'tutor_tutor_orders o', QueryHelper::prepare_table_name( 'tutor_orders o' ) ); + $this->assertSame( 'tutor_tutor_orders', QueryHelper::prepare_table_name( 'tutor_tutor_orders' ) ); } finally { $wpdb->prefix = $orig_prefix; $wpdb->base_prefix = $orig_base_prefix; From 95edaaf065dd8f3a48c81ac2c4182d0fe26cf5be Mon Sep 17 00:00:00 2001 From: "Md.Harun-Ur-Rashid" Date: Mon, 30 Nov 2026 19:57:05 +0600 Subject: [PATCH 36/36] fix: prevent duplicate multisite provisioning and check network activation --- classes/Multisite.php | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/classes/Multisite.php b/classes/Multisite.php index e639e8c595..487430d430 100644 --- a/classes/Multisite.php +++ b/classes/Multisite.php @@ -48,6 +48,10 @@ public function __construct() { * @return void */ public function on_initialize_site( \WP_Site $site, array $args = array() ): void { + if ( ! is_plugin_active_for_network( plugin_basename( TUTOR_FILE ) ) ) { + return; + } + $blog_id = (int) $site->blog_id; self::run_in_site( @@ -125,11 +129,16 @@ public static function activate_network(): void { * @return void */ public function maybe_provision_current_site(): void { - if ( wp_installing() || get_option( 'tutor_version' ) ) { + if ( wp_installing() || get_option( 'tutor_version' ) || get_transient( 'tutor_provisioning' ) ) { return; } - self::provision_site(); + set_transient( 'tutor_provisioning', 1, MINUTE_IN_SECONDS ); + try { + self::provision_site(); + } finally { + delete_transient( 'tutor_provisioning' ); + } } /**