diff --git a/classes/Multisite.php b/classes/Multisite.php new file mode 100644 index 0000000000..487430d430 --- /dev/null +++ b/classes/Multisite.php @@ -0,0 +1,223 @@ + + * @link https://themeum.com + * @since 4.3.0 + */ + +namespace TUTOR; + +defined( 'ABSPATH' ) || exit; + +use Tutor\Database\TableManager; + +/** + * Class Multisite + * + * @since 4.3.0 + */ +class Multisite { + + /** + * Constructor. + * + * @since 4.3.0 + */ + public function __construct() { + if ( ! is_multisite() ) { + return; + } + + 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' ) ); + } + + /** + * 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 { + if ( ! is_plugin_active_for_network( plugin_basename( TUTOR_FILE ) ) ) { + return; + } + + $blog_id = (int) $site->blog_id; + + self::run_in_site( + $blog_id, + function () use ( $blog_id, $site ) { + self::provision_site(); + + /** + * Action fired after a subsite is initialized with Tutor LMS. + * + * @param int $blog_id Blog ID. + * @param \WP_Site $site Site instance. + */ + do_action( 'tutor_multisite_subsite_initialized', $blog_id, $site ); + } + ); + } + + /** + * 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. + * + * @param bool $should_drop Whether to drop tables. Default true. + * @param int $blog_id Blog ID being deleted. + */ + if ( apply_filters( 'tutor_multisite_drop_tables_on_delete', true, $blog_id ) ) { + self::run_in_site( $blog_id, array( TableManager::class, 'drop_tables' ) ); + } + + /** + * 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. + * + * 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 { + self::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' ) || get_transient( 'tutor_provisioning' ) ) { + return; + } + + set_transient( 'tutor_provisioning', 1, MINUTE_IN_SECONDS ); + try { + self::provision_site(); + } finally { + delete_transient( 'tutor_provisioning' ); + } + } + + /** + * Ensure administrator users have required Tutor capabilities on the subsite. + * + * @since 4.3.0 + * + * @return void + */ + public function ensure_admin_capabilities(): void { + if ( User::is_admin() && ! current_user_can( tutor()->instructor_role ) ) { + $user = wp_get_current_user(); + if ( $user && $user->exists() ) { + $user->add_cap( 'manage_tutor' ); + $user->add_role( tutor()->instructor_role ); + } + } + } + + /** + * 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; + } + + // 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(); + 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 ( \Throwable $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 8ea61384f8..eecd57328a 100644 --- a/classes/Tutor.php +++ b/classes/Tutor.php @@ -14,6 +14,9 @@ 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; @@ -451,11 +454,17 @@ 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 */ global $wpdb; + + /** + * 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'; @@ -562,6 +571,15 @@ public function __construct() { */ new Migration(); + /** + * Multisite manager + * + * @since 4.3.0 + */ + if ( is_multisite() ) { + new Multisite(); + } + /** * Run Method * @@ -588,8 +606,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 ); } /** @@ -619,7 +635,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' ) ); } @@ -687,11 +703,22 @@ 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() { + 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(); @@ -769,324 +796,13 @@ public static function tutor_deactivation() { /** * Create database * + * @since 1.0.0 + * @since 4.3.0 Database table creation delegated to TableManager. + * * @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 ); } /** @@ -1289,54 +1005,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 @@ -1448,10 +1118,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 55cb13aad2..7028c39518 100644 --- a/classes/Upgrader.php +++ b/classes/Upgrader.php @@ -12,9 +12,12 @@ defined( 'ABSPATH' ) || exit; +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; -use Tutor\Helpers\QueryHelper; /** * Manage up grade @@ -45,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 ); } @@ -140,7 +141,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 ); @@ -149,7 +150,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 @@ -166,7 +167,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 } @@ -174,7 +175,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 } } @@ -196,7 +197,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. @@ -217,7 +218,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 } @@ -232,48 +233,18 @@ 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' ); - // 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. @@ -281,12 +252,12 @@ 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" ); + $wpdb->query( "ALTER TABLE {$cart_item_table} ADD {$detail_column} LONGTEXT AFTER course_id" ); } if ( ! $is_type_column_exists ) { @@ -325,59 +296,16 @@ 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', + ) + ); } } - /** - * 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 @@ -389,9 +317,8 @@ public function install_gradebook() { * @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' ) ) { + CouponUsagesTable::create( false ); } } @@ -409,36 +336,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\Tables\EmailQueueTable::class ) ) { + \TutorPro\Database\Tables\EmailQueueTable::create( false ); + } } } } 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/composer.json b/composer.json index 4551c139fa..ff6bc677f8 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/core/DB.php b/core/DB.php index 3457f0a410..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. * @@ -2085,22 +2101,41 @@ 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.3.0 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; + $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( $name, $prefix ) ) { + $name = substr( $name, strlen( $prefix ) ); + break; + } + } + + // Global tables use the network base prefix. + if ( in_array( $name, $db->tables( 'global', false ), true ) ) { + return $db->base_prefix . $name . $alias; } - return $table; + return $db->prefix . $name . $alias; } /** @@ -2220,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/TableManager.php b/database/TableManager.php new file mode 100644 index 0000000000..9859d27b84 --- /dev/null +++ b/database/TableManager.php @@ -0,0 +1,151 @@ + + * @link https://themeum.com + * @since 4.3.0 + */ + +namespace Tutor\Database; + +defined( 'ABSPATH' ) || exit; + +use Tutor\Database\Tables\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; + +/** + * Class TableManager + * + * @since 4.3.0 + */ +class TableManager { + + /** + * Core table classes created on initial installation or new subsite provisioning. + * + * @since 4.3.0 + * + * @var array> + */ + 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. + */ + protected static function get_table_classes(): array { + $classes = apply_filters( 'tutor_database_table_classes', self::CORE_TABLE_CLASSES ); + + /** + * 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, + fn( $class ) => is_string( $class ) && is_a( $class, Table::class, true ) + ) + ); + + return $classes; + } + + /** + * Get all known tables (Core + Addons + Pro via filter). + * + * @since 4.3.0 + * + * @return array Base table name => prefixed table name. + */ + public static function get_table_names(): array { + $table_names = array(); + foreach ( static::get_table_classes() as $class ) { + $table_names[ $class::get_base_name() ] = $class::get_name(); + } + + return apply_filters( 'tutor_database_tables', $table_names ); + } + + /** + * Create only the Core tables. + * + * @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 { + foreach ( self::CORE_TABLE_CLASSES as $table_class ) { + $table_class::create( $include_constraints ); + } + + do_action( 'tutor_database_core_tables_created', $include_constraints ); + } + + /** + * Safely drop all known Tutor tables. + * + * @since 4.3.0 + * + * @return void + */ + public static function drop_tables(): void { + global $wpdb; + $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' ); + + foreach ( $table_names as $table_name ) { + $wpdb->query( "DROP TABLE IF EXISTS `{$table_name}`" ); //phpcs:ignore + } + + $wpdb->query( 'SET FOREIGN_KEY_CHECKS = 1' ); + + do_action( 'tutor_database_tables_dropped' ); + } +} diff --git a/database/Tables/CartItemsTable.php b/database/Tables/CartItemsTable.php new file mode 100644 index 0000000000..9a03d3c0fe --- /dev/null +++ b/database/Tables/CartItemsTable.php @@ -0,0 +1,69 @@ + + * @link https://themeum.com + * @since 4.3.0 + */ + +namespace Tutor\Database\Tables; + +defined( 'ABSPATH' ) || exit; + +use Tutor\Core\DB; + +/** + * Class CartItemsTable + * + * @since 4.3.0 + */ +class CartItemsTable extends Table { + + /** + * Base table name. + * + * @since 4.3.0 + * + * @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 LONGTEXT, + 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..904691982f --- /dev/null +++ b/database/Tables/CartsTable.php @@ -0,0 +1,66 @@ + + * @link https://themeum.com + * @since 4.3.0 + */ + +namespace Tutor\Database\Tables; + +defined( 'ABSPATH' ) || exit; + +use Tutor\Core\DB; + +/** + * Class CartsTable + * + * @since 4.3.0 + */ +class CartsTable extends Table { + + /** + * Base table name. + * + * @since 4.3.0 + * + * @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..f97c8b8def --- /dev/null +++ b/database/Tables/CouponApplicationsTable.php @@ -0,0 +1,59 @@ + + * @link https://themeum.com + * @since 4.3.0 + */ + +namespace Tutor\Database\Tables; + +defined( 'ABSPATH' ) || exit; + +/** + * Class CouponApplicationsTable + * + * @since 4.3.0 + */ +class CouponApplicationsTable extends Table { + + /** + * Base table name. + * + * @since 4.3.0 + * + * @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..3a040f5c34 --- /dev/null +++ b/database/Tables/CouponUsagesTable.php @@ -0,0 +1,75 @@ + + * @link https://themeum.com + * @since 4.3.0 + */ + +namespace Tutor\Database\Tables; + +defined( 'ABSPATH' ) || exit; + +use Tutor\Core\DB; + +/** + * Class CouponUsagesTable + * + * @since 4.3.0 + */ +class CouponUsagesTable extends Table { + + /** + * Base table name. + * + * @since 4.3.0 + * + * @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..bbb2750841 --- /dev/null +++ b/database/Tables/CouponsTable.php @@ -0,0 +1,71 @@ + + * @link https://themeum.com + * @since 4.3.0 + */ + +namespace Tutor\Database\Tables; + +defined( 'ABSPATH' ) || exit; + +/** + * Class CouponsTable + * + * @since 4.3.0 + */ +class CouponsTable extends Table { + + /** + * Base table name. + * + * @since 4.3.0 + * + * @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..b127c39a0a --- /dev/null +++ b/database/Tables/CustomersTable.php @@ -0,0 +1,62 @@ + + * @link https://themeum.com + * @since 4.3.0 + */ + +namespace Tutor\Database\Tables; + +defined( 'ABSPATH' ) || exit; + +/** + * Class CustomersTable + * + * @since 4.3.0 + */ +class CustomersTable extends Table { + + /** + * Base table name. + * + * @since 4.3.0 + * + * @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..d13bd9b215 --- /dev/null +++ b/database/Tables/EarningsTable.php @@ -0,0 +1,70 @@ + + * @link https://themeum.com + * @since 4.3.0 + */ + +namespace Tutor\Database\Tables; + +defined( 'ABSPATH' ) || exit; + +/** + * Class EarningsTable + * + * @since 4.3.0 + */ +class EarningsTable extends Table { + + /** + * Base table name. + * + * @since 4.3.0 + * + * @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 {$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..81a727e74f --- /dev/null +++ b/database/Tables/OrderItemmetaTable.php @@ -0,0 +1,63 @@ + + * @link https://themeum.com + * @since 4.3.0 + */ + +namespace Tutor\Database\Tables; + +defined( 'ABSPATH' ) || exit; + +/** + * Class OrderItemmetaTable + * + * @since 4.3.0 + */ +class OrderItemmetaTable extends Table { + + /** + * Base table name. + * + * @since 4.3.0 + * + * @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..e7a948b797 --- /dev/null +++ b/database/Tables/OrderItemsTable.php @@ -0,0 +1,66 @@ + + * @link https://themeum.com + * @since 4.3.0 + */ + +namespace Tutor\Database\Tables; + +defined( 'ABSPATH' ) || exit; + +/** + * Class OrderItemsTable + * + * @since 4.3.0 + */ +class OrderItemsTable extends Table { + + /** + * Base table name. + * + * @since 4.3.0 + * + * @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..8b71aa958a --- /dev/null +++ b/database/Tables/OrdermetaTable.php @@ -0,0 +1,67 @@ + + * @link https://themeum.com + * @since 4.3.0 + */ + +namespace Tutor\Database\Tables; + +defined( 'ABSPATH' ) || exit; + +/** + * Class OrdermetaTable + * + * @since 4.3.0 + */ +class OrdermetaTable extends Table { + + /** + * Base table name. + * + * @since 4.3.0 + * + * @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..ec9d919589 --- /dev/null +++ b/database/Tables/OrdersTable.php @@ -0,0 +1,83 @@ + + * @link https://themeum.com + * @since 4.3.0 + */ + +namespace Tutor\Database\Tables; + +defined( 'ABSPATH' ) || exit; + +/** + * Class OrdersTable + * + * @since 4.3.0 + */ +class OrdersTable extends Table { + + /** + * Base table name. + * + * @since 4.3.0 + * + * @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) 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, + 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) COMMENT 'Tax percentage', + 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..c10ec0007a --- /dev/null +++ b/database/Tables/QuizAttemptAnswersTable.php @@ -0,0 +1,59 @@ + + * @link https://themeum.com + * @since 4.3.0 + */ + +namespace Tutor\Database\Tables; + +defined( 'ABSPATH' ) || exit; + +/** + * Class QuizAttemptAnswersTable + * + * @since 4.3.0 + */ +class QuizAttemptAnswersTable extends Table { + + /** + * Base table name. + * + * @since 4.3.0 + * + * @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..ebbe8600df --- /dev/null +++ b/database/Tables/QuizAttemptsTable.php @@ -0,0 +1,69 @@ + + * @link https://themeum.com + * @since 4.3.0 + */ + +namespace Tutor\Database\Tables; + +defined( 'ABSPATH' ) || exit; + +/** + * Class QuizAttemptsTable + * + * @since 4.3.0 + */ +class QuizAttemptsTable extends Table { + + /** + * Base table name. + * + * @since 4.3.0 + * + * @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..b1221f80a6 --- /dev/null +++ b/database/Tables/QuizQuestionAnswersTable.php @@ -0,0 +1,59 @@ + + * @link https://themeum.com + * @since 4.3.0 + */ + +namespace Tutor\Database\Tables; + +defined( 'ABSPATH' ) || exit; + +/** + * Class QuizQuestionAnswersTable + * + * @since 4.3.0 + */ +class QuizQuestionAnswersTable extends Table { + + /** + * Base table name. + * + * @since 4.3.0 + * + * @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..5cf70e1f81 --- /dev/null +++ b/database/Tables/QuizQuestionsTable.php @@ -0,0 +1,58 @@ + + * @link https://themeum.com + * @since 4.3.0 + */ + +namespace Tutor\Database\Tables; + +defined( 'ABSPATH' ) || exit; + +/** + * Class QuizQuestionsTable + * + * @since 4.3.0 + */ +class QuizQuestionsTable extends Table { + + /** + * Base table name. + * + * @since 4.3.0 + * + * @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 NULL, + 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..de3c26fa19 --- /dev/null +++ b/database/Tables/SchedulerTable.php @@ -0,0 +1,62 @@ + + * @link https://themeum.com + * @since 4.3.0 + */ + +namespace Tutor\Database\Tables; + +defined( 'ABSPATH' ) || exit; + +/** + * Class SchedulerTable + * + * @since 4.3.0 + */ +class SchedulerTable extends Table { + + /** + * Base table name. + * + * @since 4.3.0 + * + * @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/Table.php b/database/Tables/Table.php new file mode 100644 index 0000000000..24b357ccf4 --- /dev/null +++ b/database/Tables/Table.php @@ -0,0 +1,146 @@ + + * @link https://themeum.com + * @since 4.3.0 + */ + +namespace Tutor\Database\Tables; + +use Tutor\Core\DB; + +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 { + global $wpdb; + + if ( in_array( static::$table, $wpdb->tables( 'global', false ), true ) ) { + return $wpdb->base_prefix . static::$table; + } + + return $wpdb->prefix . 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'; + } + + // 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 ) ); + } + + /** + * 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/Tables/WithdrawsTable.php b/database/Tables/WithdrawsTable.php new file mode 100644 index 0000000000..fff6f739c1 --- /dev/null +++ b/database/Tables/WithdrawsTable.php @@ -0,0 +1,56 @@ + + * @link https://themeum.com + * @since 4.3.0 + */ + +namespace Tutor\Database\Tables; + +defined( 'ABSPATH' ) || exit; + +/** + * Class WithdrawsTable + * + * @since 4.3.0 + */ +class WithdrawsTable extends Table { + + /** + * Base table name. + * + * @since 4.3.0 + * + * @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 {$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/ecommerce/EmailController.php b/ecommerce/EmailController.php index cad50727ad..2f84b2e81b 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 * @@ -29,13 +27,6 @@ class EmailController { const TO_ADMIN = 'email_to_admin'; const ORDER_EMAILS = 'order_emails'; - /** - * Queue table - * - * @var string - */ - private $queue_table; - /** * Constructor. * @@ -50,25 +41,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 +107,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 +137,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 diff --git a/helpers/QueryHelper.php b/helpers/QueryHelper.php index 76ecd042d5..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. * @@ -1387,21 +1389,18 @@ 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.3.0 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; - } - - return $table_name; + return DB::prepare_table_name( $table_name ); } /** 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', diff --git a/tests/phpunit/CouponModelTest.php b/tests/phpunit/CouponModelTest.php index ca109fca28..486a853db4 100644 --- a/tests/phpunit/CouponModelTest.php +++ b/tests/phpunit/CouponModelTest.php @@ -1,9 +1,9 @@ assertSame( $wpdb, $method->invoke( null ) ); } + + // ─── prepare_table_name & prefixing ───────────────────────────────────── + + /** + * Test DB::prepare_table_name in single site environment. + * + * @since 4.3.0 + * + * @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.3.0 + * + * @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.3.0 + * + * @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.3.0 + * + * @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::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::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. + * + * @since 4.3.0 + * + * @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.3.0 + * + * @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..a882d60c2d 100644 --- a/tests/phpunit/QueryHelperTest.php +++ b/tests/phpunit/QueryHelperTest.php @@ -704,6 +704,198 @@ 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.3.0 + * + * @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.3.0 + * + * @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.3.0 + * + * @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.3.0 + * + * @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 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( ' ' ) ); + + // 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; + } + } + + /** + * Test get_table_prefix. + * + * @since 4.3.0 + * + * @return void + */ + public function test_get_table_prefix() { + global $wpdb; + $this->assertSame( $wpdb->prefix, QueryHelper::get_table_prefix() ); + } + // ─── get_valid_sort_order ─────────────────────────────────────────────── /**