Below is a differential between the unpatched vulnerable code and the patched update, for reference.
--- a/tutor/classes/Admin.php
+++ b/tutor/classes/Admin.php
@@ -159,6 +159,8 @@
* @return void JSON response.
*/
public function ajax_dismiss_offer_notice() {
+ tutor_utils()->check_nonce();
+
if ( ! User::is_admin() ) {
$this->response_bad_request( tutor_utils()->error_message() );
}
@@ -522,41 +524,6 @@
}
/**
- * Tutor tools page (OLD)
- *
- * @since 1.0.0
- *
- * @return void
- */
- public function tutor_tools_old() {
- $tutor_admin_tools_page = Input::get( 'tutor_admin_tools_page' );
- if ( $tutor_admin_tools_page ) {
- include apply_filters( 'tutor_admin_tools_page', tutor()->path . "views/pages/{$tutor_admin_tools_page}.php", $tutor_admin_tools_page );
- } else {
- $pages = apply_filters(
- 'tutor_tool_pages',
- array(
- 'tutor_pages' => array( 'title' => __( 'Tutor Pages', 'tutor' ) ),
- 'status' => __( 'Status', 'tutor' ),
- )
- );
-
- $current_page = 'tutor_pages';
- $requested_page = Input::get( 'sub_page' );
- if ( $requested_page ) {
- $current_page = $requested_page;
- }
-
- $current_page = str_replace( '/', '', $current_page );
- $current_page = str_replace( '.', '', $current_page );
- $current_page = str_replace( '\', '', $current_page );
- $current_page = trim( $current_page );
-
- include tutor()->path . 'views/pages/tools.php';
- }
- }
-
- /**
* Show pro upgrade page
*
* @since 1.0.0
@@ -670,15 +637,24 @@
}
if ( ! empty( Input::get( 'post' ) ) ) {
- $get_post_id = Input::get( 'post', Input::TYPE_INT );
- $get_post = get_post( $get_post_id );
- $tutor_post_types = array( tutor()->course_post_type, tutor()->lesson_post_type );
+ $get_post_id = Input::get( 'post', 0, Input::TYPE_INT );
+ $get_post = get_post( $get_post_id );
+ if ( ! $get_post ) {
+ return;
+ }
+
+ $tutor_post_types = array_values( get_tutor_post_types() );
$current_user = get_current_user_id();
- if ( in_array( $get_post->post_type, $tutor_post_types ) && $get_post->post_author != $current_user ) {
+ if ( in_array( $get_post->post_type, $tutor_post_types, true ) && $get_post->post_author != $current_user ) {
global $wpdb;
+ // Resolve course id.
+ if ( tutor()->course_post_type !== $get_post->post_type ) {
+ $get_post_id = tutor_utils()->get_course_id_by_subcontent( $get_post_id );
+ }
+
$get_assigned_courses_ids = (int) $wpdb->get_var(
$wpdb->prepare(
"SELECT user_id
--- a/tutor/classes/Ajax.php
+++ b/tutor/classes/Ajax.php
@@ -12,6 +12,7 @@
defined( 'ABSPATH' ) || exit;
+use TutorCoreInput;
use TutorGDPRControllersLegalConsent;
use TutorHelpersHttpHelper;
use TutorModelsLessonModel;
@@ -79,7 +80,6 @@
$user_id = get_current_user_id();
$post_id = Input::post( 'post_id', 0, Input::TYPE_INT );
- $duration = Input::post( 'duration' );
$current_time = Input::post( 'currentTime' );
if ( ! tutor_utils()->has_enrolled_content_access( 'lesson', $post_id ) ) {
@@ -88,18 +88,6 @@
}
/**
- * Update posts attached video
- */
- $video = tutor_utils()->get_video( $post_id );
-
- if ( $duration ) {
- $video['duration_sec'] = $duration; // Duration in sec.
- $video['playtime'] = tutor_utils()->playtime_string( $duration );
- $video['runtime'] = tutor_utils()->playtime_array( $duration );
- }
- tutor_utils()->update_video( $post_id, $video );
-
- /**
* Sync Lesson Reading Info by Users
*/
@@ -274,7 +262,9 @@
*
* @since 1.0.0
* @since 2.6.2 added params user_id.
+ *
* @param int $user_id the user id.
+ *
* @return void|bool
*/
public function delete_tutor_review( $user_id = 0 ) {
@@ -282,7 +272,12 @@
tutor_utils()->checking_nonce();
}
- $review_id = Input::post( 'review_id' );
+ $review_id = Input::post( 'review_id', 0, Input::TYPE_INT );
+
+ $review = get_comment( $review_id );
+ if ( ! $review || 'tutor_course_rating' !== $review->comment_type ) {
+ wp_send_json_error( array( 'message' => __( 'Invalid review.', 'tutor' ) ) );
+ }
if ( ! tutor_utils()->can_user_manage( 'review', $review_id, tutils()->get_user_id( $user_id ) ) ) {
wp_send_json_error( array( 'message' => __( 'Permissioned Denied!', 'tutor' ) ) );
@@ -504,7 +499,7 @@
tutor_utils()->checking_nonce();
$error = array();
- $course_id = Input::post( 'tutor_announcement_course' );
+ $course_id = Input::post( 'tutor_announcement_course', 0, Input::TYPE_INT );
$announcement_title = Input::post( 'tutor_announcement_title' );
$announcement_summary = Input::post( 'tutor_announcement_summary', '', Input::TYPE_TEXTAREA );
@@ -522,12 +517,16 @@
'post_status' => 'publish',
);
+ $announcement_id = 0;
+
if ( Input::has( 'announcement_id' ) ) {
- $form_data['ID'] = Input::post( 'announcement_id' );
+ $form_data['ID'] = Input::post( 'announcement_id', 0, Input::TYPE_INT );
+ $announcement_id = $form_data['ID'];
}
- if ( ! empty( $form_data['ID'] ) ) {
- if ( ! tutor_utils()->can_user_manage( 'announcement', $form_data['ID'] ) ) {
+ if ( $announcement_id ) {
+ $announcement_post = get_post( $announcement_id );
+ if ( ! $announcement_post || tutor()->announcement_post_type !== $announcement_post->post_type || wp_get_post_parent_id( $announcement_post ) !== $course_id || ! tutor_utils()->can_user_manage( 'announcement', $announcement_id ) ) {
wp_send_json_error( array( 'message' => tutor_utils()->error_message() ) );
}
}
@@ -587,7 +586,14 @@
public function delete_announcement() {
tutor_utils()->checking_nonce();
- $announcement_id = Input::post( 'announcement_id' );
+ $user_id = get_current_user_id();
+ $announcement_id = Input::post( 'announcement_id', 0, Input::TYPE_INT );
+ $announcement = get_post( $announcement_id );
+ $course_id = wp_get_post_parent_id( $announcement_id );
+
+ if ( ! $announcement_id || ! $course_id || tutor()->announcement_post_type !== $announcement->post_type ) {
+ wp_send_json_error( array( 'message' => tutor_utils()->error_message( 'invalid_req' ) ) );
+ }
if ( ! tutor_utils()->can_user_manage( 'announcement', $announcement_id ) ) {
wp_send_json_error( array( 'message' => __( 'Access Denied', 'tutor' ) ) );
@@ -616,6 +622,10 @@
$this->json_response( __( 'Video ID is required', 'tutor' ), null, HttpHelper::STATUS_BAD_REQUEST );
}
+ if ( ! preg_match( '/^[a-zA-Z0-9_-]{11}$/', $video_id ) ) {
+ $this->json_response( __( 'Invalid YouTube Video ID', 'tutor' ), null, HttpHelper::STATUS_BAD_REQUEST );
+ }
+
tutor_utils()->check_current_user_capability( 'edit_tutor_courses' );
$api_key = tutor_utils()->get_option( 'lesson_video_duration_youtube_api_key', '' );
--- a/tutor/classes/Announcements.php
+++ b/tutor/classes/Announcements.php
@@ -12,6 +12,7 @@
defined( 'ABSPATH' ) || exit;
+use TutorCoreInput;
use TutorHelpersQueryHelper;
use TutorHelpersUrlHelper;
@@ -103,24 +104,33 @@
$action = Input::post( 'bulk-action', '' );
$bulk_ids = Input::post( 'bulk-ids', '' );
+ if ( 'delete' !== $action || empty( $bulk_ids ) ) {
+ wp_send_json_error( tutor_utils()->error_message() );
+ }
+
// prevent instructor to delete admin announcement.
$bulk_ids = array_filter(
- explode( ',', $bulk_ids ),
+ array_map( 'absint', explode( ',', $bulk_ids ) ),
function ( $announcement_id ) {
- return tutor_utils()->can_user_manage( 'announcement', $announcement_id );
+ return $this->can_manage_announcement( $announcement_id );
}
);
- $update = self::delete_announcements( $action, implode( ',', $bulk_ids ) );
+
+ if ( empty( $bulk_ids ) ) {
+ wp_send_json_error( tutor_utils()->error_message( 'invalid_req' ) );
+ }
+
+ $update = self::delete_announcements( $action, implode( ',', $bulk_ids ) );
return true === $update ? wp_send_json_success() : wp_send_json_error();
}
/**
- * Execute bulk action for enrolments ex: complete | cancel
+ * Execute bulk action for announcements deletion
*
* @since 2.0.0
*
- * @param string $action hold action.
- * @param string $bulk_ids comma separated ids.
+ * @param string $action hold action.
+ * @param string|array $bulk_ids comma separated ids or array of ids.
*
* @return bool
*/
@@ -138,6 +148,7 @@
);
return false === $delete ? false : true;
}
+
return false;
}
@@ -185,4 +196,20 @@
return $nav_items;
}
+
+ /**
+ * Check if the user can manage announcement
+ *
+ * @since 4.2.1
+ *
+ * @param int $post_id Announcement id.
+ * @param int $user_id Optional user id, default is current user id.
+ *
+ * @return bool
+ */
+ public function can_manage_announcement( int $post_id, int $user_id = 0 ): bool {
+ $post = get_post( $post_id );
+
+ return $post && tutor()->announcement_post_type === $post->post_type && tutor_utils()->can_user_manage( 'announcement', $post_id, $user_id );
+ }
}
--- a/tutor/classes/Assets.php
+++ b/tutor/classes/Assets.php
@@ -10,6 +10,7 @@
namespace TUTOR;
+use TutorCoreInput;
use TutorEcommerceCartController;
use TutorEcommerceCheckoutController;
use TutorEcommerceCouponController;
@@ -75,8 +76,6 @@
* @since 1.9.0
*/
add_action( 'admin_head', array( $this, 'tutor_add_mce_button' ) );
- add_filter( 'get_the_generator_html', array( $this, 'tutor_generator_tag' ), 10, 2 );
- add_filter( 'get_the_generator_xhtml', array( $this, 'tutor_generator_tag' ), 10, 2 );
/**
* Add translation support for external tinyMCE button
@@ -661,6 +660,13 @@
if ( ! current_user_can( 'edit_posts' ) && ! current_user_can( 'edit_pages' ) ) {
return;
}
+
+ // Exclude for Tutor post types (course, lesson, assignment, etc.).
+ $screen = get_current_screen();
+ if ( $screen && in_array( $screen->post_type, get_tutor_post_types(), true ) ) {
+ return;
+ }
+
// Check if WYSIWYG is enabled.
if ( 'true' == get_user_option( 'rich_editing' ) ) {
add_filter( 'mce_external_plugins', array( $this, 'tutor_add_tinymce_js' ) );
@@ -695,28 +701,6 @@
}
/**
- * Output generator tag to aid debugging.
- *
- * @since 1.0.0
- *
- * @param string $gen Generator.
- * @param string $type Type.
- *
- * @return string
- */
- public function tutor_generator_tag( $gen, $type ) {
- switch ( $type ) {
- case 'html':
- $gen .= "n" . '<meta name="generator" content="TutorLMS ' . TUTOR_VERSION . '">';
- break;
- case 'xhtml':
- $gen .= "n" . '<meta name="generator" content="TutorLMS ' . TUTOR_VERSION . '" />';
- break;
- }
- return $gen;
- }
-
- /**
* Load text domain handled script after all enqueue_scripts
* registered functions
*
@@ -816,7 +800,10 @@
$to_add[] = 'tutor-screen-backend-settings ';
}
if ( ! empty( $page ) ) {
- $to_add[] = 'tutor-backend-' . $page;
+ $sanitized_page = sanitize_html_class( $page );
+ if ( ! empty( $sanitized_page ) ) {
+ $to_add[] = 'tutor-backend-' . $sanitized_page;
+ }
}
}
}
@@ -1038,4 +1025,4 @@
}
return $html;
}
-}
+}
No newline at end of file
--- a/tutor/classes/Course.php
+++ b/tutor/classes/Course.php
@@ -1212,15 +1212,16 @@
$this->check_access( $course_id );
- $builder = Input::post( 'builder' );
+ $builder = Input::post( 'builder' );
+ $post_content = (string) get_post_field( 'post_content', $course_id, 'raw' );
if ( 'elementor' === $builder ) {
delete_post_meta( $course_id, '_elementor_edit_mode' );
} elseif ( 'droip' === $builder ) {
delete_post_meta( $course_id, 'droip_editor_mode' );
} elseif ( 'divi' === $builder ) {
- $old_post_content = get_post_meta( $course_id, '_et_pb_old_content', true );
+ $post_content = get_post_meta( $course_id, '_et_pb_old_content', true );
$course = get_post( $course_id );
- $course->post_content = $old_post_content;
+ $course->post_content = $post_content;
$result = wp_update_post( $course );
if ( $result && ! is_wp_error( $result ) ) {
@@ -1234,7 +1235,10 @@
$this->json_response(
__( 'Builder unlinked successfully.', 'tutor' ),
- $course_id,
+ array(
+ 'course_id' => $course_id,
+ 'post_content' => $post_content,
+ ),
HttpHelper::STATUS_OK
);
}
@@ -2213,6 +2217,10 @@
$course_id = Input::post( 'tutor_course_id', 0, Input::TYPE_INT );
+ if ( ! $course_id ) {
+ return;
+ }
+
/**
* TODO: need to check purchase information
*/
@@ -3190,7 +3198,8 @@
* @return void
*/
public function enroll_after_login_if_attempt( int $course_id, int $user_id ) {
- $course_id = sanitize_text_field( $course_id );
+ $course_id = sanitize_text_field( $course_id );
+
$is_allowed = apply_filters( 'tutor_allow_guest_attempt_enrollment', true, $course_id, $user_id );
if ( $course_id && $is_allowed ) {
--- a/tutor/classes/Dashboard.php
+++ b/tutor/classes/Dashboard.php
@@ -12,6 +12,7 @@
defined( 'ABSPATH' ) || exit;
+use TutorCoreInput;
use TutorHelpersUrlHelper;
/**
--- a/tutor/classes/DashboardSectionManager.php
+++ b/tutor/classes/DashboardSectionManager.php
@@ -15,6 +15,7 @@
defined( 'ABSPATH' ) || exit;
+use TutorCoreInput;
use TUTORInstructorMetricsAdapter;
use TutorTraitsJsonResponse;
@@ -225,6 +226,7 @@
$user_id = get_current_user_id();
$start_date = Input::post( 'start_date', '', Input::TYPE_STRING );
$end_date = Input::post( 'end_date', '', Input::TYPE_STRING );
+ $period = Input::post( 'period', '', Input::TYPE_STRING );
$type = Input::post( 'top_performing_course', Input::post( 'type', 'revenue', Input::TYPE_STRING ), Input::TYPE_STRING );
$type = in_array( $type, array( 'revenue', 'student' ), true ) ? $type : 'revenue';
@@ -233,6 +235,7 @@
$params = array(
'user_id' => $user_id,
+ 'period' => $period,
'start_date' => $start_date,
'end_date' => $end_date,
'top_performing_course' => $type,
--- a/tutor/classes/FormHandler.php
+++ b/tutor/classes/FormHandler.php
@@ -10,6 +10,8 @@
namespace TUTOR;
+use TutorCoreInput;
+
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
--- a/tutor/classes/Gutenberg.php
+++ b/tutor/classes/Gutenberg.php
@@ -10,6 +10,8 @@
namespace TUTOR;
+use TutorCoreInput;
+
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
--- a/tutor/classes/Instructor.php
+++ b/tutor/classes/Instructor.php
@@ -104,6 +104,19 @@
}
/**
+ * Check if applying to become an instructor is allowed.
+ *
+ * @since 4.2.1
+ *
+ * @return bool
+ */
+ public static function can_apply_for_instructor(): bool {
+ $is_enabled = (bool) tutor_utils()->get_option( 'enable_become_instructor_btn' );
+
+ return apply_filters( 'tutor_can_apply_for_instructor', $is_enabled );
+ }
+
+ /**
* Template Redirect Callback
* For Register new user and mark him as instructor
*
@@ -249,6 +262,10 @@
// Checking nonce.
tutor_utils()->checking_nonce();
+ if ( ! self::can_apply_for_instructor() ) {
+ wp_die( esc_html__( 'Become an instructor is currently disabled.', 'tutor' ), 403 );
+ }
+
$user_id = get_current_user_id();
if ( $user_id ) {
if ( tutor_utils()->is_instructor() ) {
--- a/tutor/classes/Instructors_List.php
+++ b/tutor/classes/Instructors_List.php
@@ -15,6 +15,7 @@
use TUTORStudents_List;
use TUTORBackend_Page_Trait;
use TutorCacheTutorCache;
+use TutorCoreInput;
use TutorHelpersQueryHelper;
/**
--- a/tutor/classes/Lesson.php
+++ b/tutor/classes/Lesson.php
@@ -12,6 +12,7 @@
defined( 'ABSPATH' ) || exit;
+use TutorCoreInput;
use TutorHelpersHttpHelper;
use TutorHelpersQueryHelper;
use TutorHelpersValidationHelper;
@@ -346,6 +347,22 @@
),
true
);
+
+ $duration_sec = absint( $video['duration_sec'] ?? 0 );
+ if ( ! empty( $video['runtime'] ) && is_array( $video['runtime'] ) ) {
+ $runtime = $video['runtime'];
+ $hours = absint( $runtime['hours'] ?? 0 );
+ $minutes = absint( $runtime['minutes'] ?? 0 );
+ $seconds = absint( $runtime['seconds'] ?? 0 );
+ $duration_sec = $hours * HOUR_IN_SECONDS + $minutes * MINUTE_IN_SECONDS + $seconds;
+ }
+
+ if ( $duration_sec > 0 ) {
+ $video['duration_sec'] = $duration_sec;
+ $video['playtime'] = tutor_utils()->playtime_string( $duration_sec );
+ $video['runtime'] = tutor_utils()->playtime_array( $duration_sec );
+ }
+
update_post_meta( $post_ID, '_video', tutor_utils()->filter_video_meta( $video ) );
}
--- a/tutor/classes/Post_types.php
+++ b/tutor/classes/Post_types.php
@@ -11,11 +11,11 @@
namespace TUTOR;
+defined( 'ABSPATH' ) || exit;
+
+use TutorCoreInput;
use TutorModelsCourseModel;
-if ( ! defined( 'ABSPATH' ) ) {
- exit;
-}
/**
* Register Tutor's post types
*
@@ -76,6 +76,17 @@
* @since v2.0.0
*/
add_action( 'admin_menu', array( $this, 'remove_course_post_menu' ) );
+
+ /**
+ * Block public listing of protected types lesson, assignment and quiz.
+ * Block scope: RSS, Comment feed and public query. outside single page.
+ *
+ * @since 4.2.1
+ */
+ add_action( 'pre_get_posts', array( $this, 'block_public_listing_of_protected_types' ) );
+ add_filter( 'comment_feed_where', array( $this, 'exclude_protected_types_from_comment_feed' ), 10, 2 );
+ add_filter( 'the_content', array( $this, 'strip_protected_content_outside_single' ), 1 );
+ add_filter( 'get_the_excerpt', array( $this, 'strip_protected_excerpt' ), 1, 2 );
}
/**
@@ -86,7 +97,6 @@
* @return void
*/
public function register_course_post_types() {
- $course_post_type = $this->course_post_type;
$labels = array(
'name' => _x( 'Courses', 'post type general name', 'tutor' ),
@@ -114,7 +124,7 @@
// 'show_in_menu' => 'tutor',
'query_var' => true,
'rewrite' => array(
- 'slug' => tutor_utils()->get_option( 'course_permalink_base', $course_post_type ),
+ 'slug' => tutor_utils()->get_option( 'course_permalink_base', tutor()->course_post_type ),
'with_front' => true,
),
'menu_icon' => 'dashicons-book-alt',
@@ -140,7 +150,7 @@
),
);
- register_post_type( $course_post_type, $args );
+ register_post_type( tutor()->course_post_type, $args );
/**
* Taxonomy
@@ -249,7 +259,7 @@
'rewrite' => array( 'slug' => $lesson_base_slug ),
'menu_icon' => 'dashicons-list-view',
'capability_type' => 'post',
- 'has_archive' => true,
+ 'has_archive' => false,
'hierarchical' => false,
'menu_position' => null,
'supports' => array( 'title', 'editor', 'comments' ),
@@ -316,7 +326,7 @@
'rewrite' => array( 'slug' => $this->lesson_post_type ),
'menu_icon' => 'dashicons-editor-help',
'capability_type' => 'post',
- 'has_archive' => true,
+ 'has_archive' => false,
'hierarchical' => false,
'menu_position' => null,
'supports' => array( 'title', 'editor' ),
@@ -334,7 +344,7 @@
),
);
- register_post_type( 'tutor_quiz', $args );
+ register_post_type( tutor()->quiz_post_type, $args );
}
/**
@@ -356,7 +366,7 @@
'hierarchical' => false,
'menu_position' => null,
);
- register_post_type( 'topics', $args );
+ register_post_type( tutor()->topics_post_type, $args );
}
/**
@@ -395,7 +405,7 @@
'rewrite' => array( 'slug' => $this->lesson_post_type ),
'menu_icon' => 'dashicons-editor-help',
'capability_type' => 'post',
- 'has_archive' => true,
+ 'has_archive' => false,
'hierarchical' => false,
'menu_position' => null,
'supports' => array( 'title', 'editor' ),
@@ -413,7 +423,7 @@
),
);
- register_post_type( 'tutor_assignments', $args );
+ register_post_type( tutor()->assignment_post_type, $args );
}
/**
@@ -479,14 +489,12 @@
* Gutenberg can edit post filter handler
*
* @since 1.0.0
+ * @since 1.3.4 Enable / Disable Gutenberg Editor.
*
* @param bool $can_edit use block editor.
* @param string $post_type post type.
*
* @return bool
- *
- * Enable / Disable Gutenberg Editor
- * @since v.1.3.4
*/
public function gutenberg_can_edit_post_type( $can_edit, $post_type ) {
$enable_gutenberg = (bool) tutor_utils()->get_option( 'enable_gutenberg_course_edit' );
@@ -510,16 +518,177 @@
'hierarchical' => false,
'menu_position' => null,
);
- register_post_type( 'tutor_enrolled', $args );
+ register_post_type( tutor()->enrollment_post_type, $args );
}
/**
* Remove course post menu
*
+ * @since 2.0.0
+ *
* @return void
- * @since v2.0.0
*/
public function remove_course_post_menu() {
remove_menu_page( 'edit.php?post_type=' . tutor()->course_post_type );
}
+
+ /**
+ * Post types whose content depends on course enrollment.
+ *
+ * @since 4.2.1
+ *
+ * @return string[]
+ */
+ private function get_protected_post_types() {
+ $post_types = array(
+ tutor()->lesson_post_type,
+ tutor()->quiz_post_type,
+ tutor()->assignment_post_type,
+ );
+
+ return apply_filters( 'tutor_content_protected_post_types', $post_types );
+ }
+
+ /**
+ * Remove enrollment-protected post types from archives, search and feeds.
+ *
+ * Mixed queries (e.g. ['courses', 'lesson']) keep working for the public
+ * types. The request is only 404'd when no public post type remains.
+ * Normal singular requests are left to the single-template enrollment check.
+ *
+ * @since 4.2.1
+ *
+ * @param WP_Query $query Query object.
+ *
+ * @return void
+ */
+ public function block_public_listing_of_protected_types( $query ) {
+ if ( is_admin() || ! $query->is_main_query() ) {
+ return;
+ }
+
+ $requested = array_filter( (array) $query->get( 'post_type' ) );
+ if ( empty( $requested ) ) {
+ return;
+ }
+
+ $protected = array_intersect( $requested, $this->get_protected_post_types() );
+ if ( empty( $protected ) ) {
+ return;
+ }
+
+ // Normal single lesson/quiz/assignment page: handled by the template flow.
+ if ( $query->is_singular() && ! $query->is_feed() && ! $query->is_comment_feed() ) {
+ return;
+ }
+
+ $remaining = array_values( array_diff( $requested, $protected ) );
+
+ if ( ! empty( $remaining ) ) {
+ $query->set( 'post_type', $remaining );
+ return;
+ }
+
+ $query->set_404();
+ $query->set( 'post__in', array( 0 ) );
+ status_header( 404 );
+ nocache_headers();
+ }
+
+ /**
+ * Keep comments (Q&A) on protected post types out of /comments/feed/.
+ *
+ * @since 4.2.1
+ *
+ * @param string $where SQL where clause.
+ * @param WP_Query $query Query object.
+ *
+ * @return string
+ */
+ public function exclude_protected_types_from_comment_feed( $where, $query ) {
+ global $wpdb;
+
+ if ( $query instanceof WP_Query && $query->is_singular ) {
+ return $where;
+ }
+
+ $post_types = $this->get_protected_post_types();
+
+ if ( empty( $post_types ) ) {
+ return $where;
+ }
+
+ $placeholders = implode( ', ', array_fill( 0, count( $post_types ), '%s' ) );
+
+ $where .= $wpdb->prepare(
+ //phpcs:ignore -- safely passed $placeholders variable.
+ " AND {$wpdb->posts}.post_type NOT IN ({$placeholders})",
+ $post_types
+ );
+
+ return $where;
+ }
+
+ /**
+ * Whether protected content of the given post may be view right now.
+ *
+ * True only when the post is the singular post being viewed (the
+ * enrollment check for that view lives in the single template flow),
+ * or when the current user can edit it (instructors, admins).
+ *
+ * @since 4.2.1
+ *
+ * @param WP_Post $post Post object.
+ *
+ * @return bool
+ */
+ private function can_view_protected_content( $post ) {
+ if ( is_admin() ) {
+ // Course builder, admin screens and admin-ajax.
+ return true;
+ }
+
+ if ( current_user_can( 'edit_post', $post->ID ) ) {
+ return true;
+ }
+
+ return is_singular( $post->post_type )
+ && ! is_feed()
+ && get_queried_object_id() === (int) $post->ID;
+ }
+
+ /**
+ * Never output protected post content or excerpts outside the single view.
+ *
+ * @since 4.2.1
+ *
+ * @param string $content Content or excerpt.
+ *
+ * @return string
+ */
+ public function strip_protected_content_outside_single( $content ) {
+ $post = get_post();
+ if ( ! $post || ! in_array( $post->post_type, $this->get_protected_post_types(), true ) ) {
+ return $content;
+ }
+
+ return $this->can_view_protected_content( $post ) ? $content : '';
+ }
+
+ /**
+ * Same rule for get_the_excerpt(), which block themes and Query Loop
+ * call directly without running the the_excerpt filter.
+ *
+ * @param string $excerpt Excerpt.
+ * @param WP_Post|null $post Post object.
+ * @return string
+ */
+ public function strip_protected_excerpt( $excerpt, $post = null ) {
+ $post = get_post( $post );
+ if ( ! $post || ! in_array( $post->post_type, $this->get_protected_post_types(), true ) ) {
+ return $excerpt;
+ }
+
+ return $this->can_view_protected_content( $post ) ? $excerpt : '';
+ }
}
--- a/tutor/classes/Q_And_A.php
+++ b/tutor/classes/Q_And_A.php
@@ -12,6 +12,8 @@
defined( 'ABSPATH' ) || exit;
+use TutorCoreDB;
+use TutorCoreInput;
use TutorHelpersQueryHelper;
use TutorHelpersUrlHelper;
use TutorModelsEnrollmentModel;
@@ -40,6 +42,15 @@
);
/**
+ * Comment type for Q&A
+ *
+ * @since 4.2.1
+ *
+ * @var string
+ */
+ const COMMENT_TYPE = 'tutor_q_and_a';
+
+ /**
* Register hooks
*
* @param boolean $register_hooks true/false to execute the hooks.
@@ -297,62 +308,78 @@
$this->response_bad_request( tutor_utils()->error_message( 'authorization' ) );
}
- $this->delete_qna_permanently( array( $question_id ) );
-
- $this->json_response( __( 'Comment deleted successfully.', 'tutor' ) );
+ if ( $this->delete_qna_permanently( array( $question_id ) ) ) {
+ $this->json_response( __( 'Question deleted successfully.', 'tutor' ) );
+ } else {
+ $this->response_bad_request( __( 'Question delete failed.', 'tutor' ) );
+ }
}
/**
- * Delete question permanently
+ * Delete questions permanently along with their replies and meta data.
+ *
+ * Unlike native WordPress comments, replies are intentionally NOT re-parented
+ * when a question is deleted. In Tutor LMS Q&A, a reply is an answer to its
+ * parent question and has no meaning without it, so promoting replies to
+ * top-level questions would leave orphaned, out-of-context entries.
+ * Replies are therefore deleted together with their question.
+ *
+ * Type guard: only comments with `comment_type = tutor_q_and_a` are touched.
+ * IDs are re-validated against the database, so regular post comments and
+ * lesson comments can never be deleted through this method, even if their
+ * IDs are passed in.
*
* @since 1.6.4
+ * @since 4.2.1 Refactored and added type guard checks with comments.
*
- * @param array $question_ids question ids.
+ * @param array $question_ids Question comment IDs.
*
- * @return void
+ * @return bool
*/
- public function delete_qna_permanently( $question_ids ) {
- if ( is_array( $question_ids ) && count( $question_ids ) ) {
- global $wpdb;
- // Prepare in clause.
- $question_ids = QueryHelper::prepare_in_clause( $question_ids );
-
- // Deleting question (comment), child question and question meta (comment meta).
- // phpcs:disable -- variable $question_ids is escaped.
- $wpdb->query(
- $wpdb->prepare(
- "DELETE
- FROM {$wpdb->comments}
- WHERE {$wpdb->comments}.comment_ID IN ($question_ids)
- AND 1 = %d
- ",
- 1
- )
- );
+ public function delete_qna_permanently( $question_ids ) : bool {
+ $question_ids = array_values( array_filter( array_map( 'absint', (array) $question_ids ) ) );
+ if ( empty( $question_ids ) ) {
+ return false;
+ }
- $wpdb->query(
- $wpdb->prepare(
- "DELETE
- FROM {$wpdb->comments}
- WHERE {$wpdb->comments}.comment_parent IN ($question_ids)
- AND 1 = %d
- ",
- 1
- )
- );
+ try {
+ return DB::transaction(
+ function () use ( $question_ids ) {
+ // Only IDs that really are Q&A questions.
+ $valid_ids = DB::table( 'comments' )
+ ->select( 'comment_ID' )
+ ->where( 'comment_type', self::COMMENT_TYPE )
+ ->where_in( 'comment_ID', $question_ids )
+ ->pluck( 'comment_ID' );
+
+ if ( empty( $valid_ids ) ) {
+ return;
+ }
+
+ $reply_ids = DB::table( 'comments' )
+ ->select( 'comment_ID' )
+ ->where( 'comment_type', self::COMMENT_TYPE )
+ ->where_in( 'comment_parent', $valid_ids )
+ ->pluck( 'comment_ID' );
+
+ $all_ids = array_map( 'intval', array_merge( $valid_ids, $reply_ids ) );
+
+ if ( tutor_utils()->count( $all_ids ) ) {
+ DB::table( 'commentmeta' )->where_in( 'comment_id', $all_ids )->delete();
+ DB::table( 'comments' )->where_in( 'comment_ID', $all_ids )->delete();
+
+ clean_comment_cache( $all_ids );
+ return true;
+ }
- $wpdb->query(
- $wpdb->prepare(
- "DELETE
- FROM {$wpdb->commentmeta}
- WHERE {$wpdb->commentmeta}.comment_id IN ($question_ids)
- AND 1 = %d
- ",
- 1
- )
+ return false;
+ }
);
- // phpcs:enable
+ } catch ( Throwable $e ) {
+ tutor_log( 'Q&A Delete Error: ' . $e->getMessage() );
}
+
+ return false;
}
/**
--- a/tutor/classes/Question_Answers_List.php
+++ b/tutor/classes/Question_Answers_List.php
@@ -10,6 +10,8 @@
namespace TUTOR;
+use TutorCoreInput;
+
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
--- a/tutor/classes/Quiz.php
+++ b/tutor/classes/Quiz.php
@@ -19,6 +19,7 @@
use TutorComponentsModal;
use TutorComponentsSvgIcon;
use TutorComponentsTable;
+use TutorCoreInput;
use TutorHelpersHttpHelper;
use TutorHelpersQueryHelper;
use TutorModelsCourseModel;
--- a/tutor/classes/QuizBuilder.php
+++ b/tutor/classes/QuizBuilder.php
@@ -14,6 +14,7 @@
exit;
}
+use TutorCoreInput;
use TutorHelpersHttpHelper;
use TutorHelpersQueryHelper;
use TutorHelpersValidationHelper;
--- a/tutor/classes/Quiz_Attempts_List.php
+++ b/tutor/classes/Quiz_Attempts_List.php
@@ -26,6 +26,7 @@
use TutorModelsQuizModel;
use TutorComponentsSvgIcon;
use TutorComponentsProgress;
+use TutorCoreInput;
/**
* Quiz attempt class
--- a/tutor/classes/Reviews.php
+++ b/tutor/classes/Reviews.php
@@ -10,6 +10,7 @@
namespace TUTOR;
+use TutorCoreInput;
use TutorHelpersQueryHelper;
use TutorHelpersUrlHelper;
--- a/tutor/classes/Rewrite_Rules.php
+++ b/tutor/classes/Rewrite_Rules.php
@@ -117,8 +117,9 @@
* @return string
*/
public function change_lesson_single_url( $post_link, $id = 0 ) {
- $post = get_post( $id );
- $course_base_slug = 'sample-course';
+ $post = get_post( $id );
+ $course_base_slug = 'sample-course';
+ $course_base_permalink = apply_filters( 'tutor_course_permalink_base', $this->course_base_permalink );
if ( is_object( $post ) && $post->post_type == $this->lesson_post_type ) {
// Lesson Permalink.
@@ -129,9 +130,9 @@
if ( $course ) {
$course_base_slug = $course->post_name;
}
- return home_url( "/{$this->course_base_permalink}/{$course_base_slug}/{$this->lesson_base_permalink}/" . $post->post_name . '/' );
+ return home_url( "/{$course_base_permalink}/{$course_base_slug}/{$this->lesson_base_permalink}/" . $post->post_name . '/' );
} else {
- return home_url( "/{$this->course_base_permalink}/sample-course/{$this->lesson_base_permalink}/" . $post->post_name . '/' );
+ return home_url( "/{$course_base_permalink}/sample-course/{$this->lesson_base_permalink}/" . $post->post_name . '/' );
}
} elseif ( is_object( $post ) && 'tutor_quiz' === $post->post_type ) {
// Quiz Permalink.
@@ -147,9 +148,9 @@
}
$course_post_name = isset( $course->post_name ) ? $course->post_name : 'sample-course';
- return home_url( "/{$this->course_base_permalink}/{$course_post_name}/{$this->quiz_base_permalink}/{$post->post_name}/" );
+ return home_url( "/{$course_base_permalink}/{$course_post_name}/{$this->quiz_base_permalink}/{$post->post_name}/" );
} else {
- return home_url( "/{$this->course_base_permalink}/sample-course/{$this->quiz_base_permalink}/{$post->post_name}/" );
+ return home_url( "/{$course_base_permalink}/sample-course/{$this->quiz_base_permalink}/{$post->post_name}/" );
}
}
return $post_link;
--- a/tutor/classes/Shortcode.php
+++ b/tutor/classes/Shortcode.php
@@ -10,6 +10,7 @@
namespace TUTOR;
+use TutorCoreInput;
use TutorModelsCourseModel;
if ( ! defined( 'ABSPATH' ) ) {
--- a/tutor/classes/Student.php
+++ b/tutor/classes/Student.php
@@ -10,6 +10,7 @@
namespace TUTOR;
+use TutorCoreInput;
use TutorGDPRControllersLegalConsent;
if ( ! defined( 'ABSPATH' ) ) {
--- a/tutor/classes/Students_List.php
+++ b/tutor/classes/Students_List.php
@@ -15,6 +15,7 @@
}
use TUTORBackend_Page_Trait;
+use TutorCoreInput;
use TutorHelpersQueryHelper;
use TutorProCourseBundleCustomPostsCourseBundle;
--- a/tutor/classes/Taxonomies.php
+++ b/tutor/classes/Taxonomies.php
@@ -10,6 +10,8 @@
namespace TUTOR;
+use TutorCoreInput;
+
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
--- a/tutor/classes/Template.php
+++ b/tutor/classes/Template.php
@@ -10,6 +10,7 @@
namespace TUTOR;
+use TutorCoreInput;
use TutorHelpersUrlHelper;
if ( ! defined( 'ABSPATH' ) ) {
@@ -142,7 +143,7 @@
add_filter( 'the_content', array( $this, 'convert_static_page_to_template' ) );
add_action( 'pre_get_posts', array( $this, 'limit_course_query_archive' ), 99 );
- add_filter( 'template_include', array( $this, 'load_learning_template' ) );
+ add_filter( 'template_include', array( $this, 'load_learning_template' ), 99 );
$this->shortcode_obj = new Shortcode( false );
}
--- a/tutor/classes/Tools_V2.php
+++ b/tutor/classes/Tools_V2.php
@@ -11,6 +11,7 @@
namespace Tutor;
use TUTORAdmin;
+use TutorCoreInput;
if ( ! defined( 'ABSPATH' ) ) {
exit;
--- a/tutor/classes/Tutor.php
+++ b/tutor/classes/Tutor.php
@@ -10,6 +10,7 @@
namespace TUTOR;
+use TutorCoreInput;
use TutorCoreSingleton;
use TutorModelsCourseModel;
use TutorEcommerceEcommerce;
--- a/tutor/classes/TutorEDD.php
+++ b/tutor/classes/TutorEDD.php
@@ -12,6 +12,7 @@
defined( 'ABSPATH' ) || exit;
+use TutorCoreInput;
use TutorHelpersQueryHelper;
use TutorHelpersUrlHelper;
use TutorModelsEnrollmentModel;
--- a/tutor/classes/Tutor_Setup.php
+++ b/tutor/classes/Tutor_Setup.php
@@ -10,6 +10,7 @@
namespace TUTOR;
+use TutorCoreInput;
use TutorHelpersHttpHelper;
use TutorTraitsJsonResponse;
--- a/tutor/classes/User.php
+++ b/tutor/classes/User.php
@@ -10,14 +10,13 @@
namespace TUTOR;
-use TutorModelsCourseModel;
-
defined( 'ABSPATH' ) || exit;
+use TutorCoreInput;
+use TutorModelsCourseModel;
use TutorHelpersHttpHelper;
use TutorModelsUserModel;
use TutorTraitsJsonResponse;
-use TUTORInstructorList;
/**
* User class
@@ -507,7 +506,7 @@
$timezone = Input::post( 'timezone', '' );
$_tutor_profile_job_title = Input::post( self::PROFILE_JOB_TITLE_META, '' );
- $_tutor_profile_bio = Input::post( self::PROFILE_BIO_META, '', Input::TYPE_KSES_POST );
+ $_tutor_profile_bio = wp_kses( Input::post( self::PROFILE_BIO_META, '', Input::TYPE_KSES_POST ), tutor_utils()->allowed_profile_bio_tags() );
$_tutor_profile_image = Input::post( self::PROFILE_PHOTO_META, '', Input::TYPE_KSES_POST );
update_user_meta( $user_id, self::PROFILE_JOB_TITLE_META, $_tutor_profile_job_title );
--- a/tutor/classes/UserPreference.php
+++ b/tutor/classes/UserPreference.php
@@ -16,6 +16,7 @@
defined( 'ABSPATH' ) || exit;
use TutorCacheTutorCache;
+use TutorCoreInput;
use TutorHelpersHttpHelper;
use TutorOptions_V2;
use TutorTraitsJsonResponse;
--- a/tutor/classes/Utils.php
+++ b/tutor/classes/Utils.php
@@ -13,6 +13,8 @@
defined( 'ABSPATH' ) || exit;
use TutorCacheTutorCache;
+use TutorCoreInput;
+use TutorCoreDB;
use TutorEcommerceEcommerce;
use TutorEcommerceOptionKeys;
use TutorEcommerceSettings;
@@ -3296,7 +3298,7 @@
*
* @since 1.0.0
*
- * @param int $course_id course id.
+ * @param int $course_id Course ID or Bundle ID.
*
* @return array|bool|null|object
*/
@@ -3349,7 +3351,7 @@
INNER JOIN {$wpdb->posts} course
ON _user.ID = course.post_author
AND course.ID = %d
- AND course.post_type = %s
+ AND course.post_type IN (%s, %s)
LEFT JOIN {$wpdb->usermeta} tutor_job_title
ON _user.ID = tutor_job_title.user_id
AND tutor_job_title.meta_key = %s
@@ -3362,6 +3364,7 @@
",
$course_id,
tutor()->course_post_type,
+ tutor()->bundle_post_type,
'_tutor_profile_job_title',
'_tutor_profile_bio',
'_tutor_profile_photo'
@@ -4176,8 +4179,8 @@
$course_filter = '';
if ( $course_id ) {
- $course_ids = is_array( $course_id ) ? $course_id : array( $course_id );
- $course_ids = array_filter( array_map( 'absint', $course_ids ) );
+ $course_ids = is_array( $course_id ) ? $course_id : array( $course_id );
+ $course_ids = array_filter( array_map( 'absint', $course_ids ) );
if ( ! empty( $course_ids ) ) {
$course_ids_str = QueryHelper::prepare_in_clause( $course_ids );
$course_filter = " AND _comment.comment_post_ID IN ($course_ids_str)";
@@ -7680,6 +7683,7 @@
* Return the course ID(s) by lession, quiz, answer etc.
*
* @since 1.7.9
+ * @since 4.2.1 tutor_announcements support added.
*
* @param int $content_id content id.
*
@@ -7687,15 +7691,16 @@
*/
public function get_course_id_by_subcontent( $content_id ) {
$mapping = array(
- 'tutor_assignments' => 'assignment',
- 'tutor_quiz' => 'quiz',
- 'lesson' => 'lesson',
- 'tutor_zoom_meeting' => 'zoom_meeting',
- 'tutor_zoom_lesson' => 'zoom_lesson',
- 'tutor_gm_course' => 'tutor_gm_course',
- 'tutor_gm_topic' => 'tutor_gm_topic',
- 'topics' => 'topic',
- 'cb-lesson' => 'cb-lesson',
+ 'tutor_assignments' => 'assignment',
+ 'tutor_quiz' => 'quiz',
+ 'lesson' => 'lesson',
+ 'tutor_zoom_meeting' => 'zoom_meeting',
+ 'tutor_zoom_lesson' => 'zoom_lesson',
+ 'tutor_gm_course' => 'tutor_gm_course',
+ 'tutor_gm_topic' => 'tutor_gm_topic',
+ 'topics' => 'topic',
+ 'cb-lesson' => 'cb-lesson',
+ 'tutor_announcements' => 'announcement',
);
$content_type = get_post_field( 'post_type', $content_id );
@@ -7759,14 +7764,15 @@
case 'review':
case 'qa_question':
// Just check if own content. Instructor privilege already checked in the earlier blocks.
- $id = $wpdb->get_var(
- $wpdb->prepare(
- "SELECT comment_ID
- FROM {$wpdb->comments} WHERE user_id = %d AND comment_ID=%d",
- $user_id,
- $object_id
- )
- );
+ $comment_type = 'qa_question' === $content
+ ? Q_And_A::COMMENT_TYPE
+ : Reviews::COURSE_RATING;
+
+ $id = DB::table( 'comments' )
+ ->where( 'comment_type', $comment_type )
+ ->where( 'user_id', $user_id )
+ ->where( 'comment_ID', $object_id )
+ ->value( 'comment_ID' );
return $id ? true : false;
}
--- a/tutor/classes/Withdraw.php
+++ b/tutor/classes/Withdraw.php
@@ -11,6 +11,7 @@
namespace TUTOR;
use Exception;
+use TutorCoreInput;
use TutorModelsWithdrawModel;
use TutorTraitsJsonResponse;
--- a/tutor/classes/Withdraw_Requests_List.php
+++ b/tutor/classes/Withdraw_Requests_List.php
@@ -10,6 +10,7 @@
namespace TUTOR;
+use TutorCoreInput;
use TutorModelsWithdrawModel;
if ( ! defined( 'ABSPATH' ) ) {
@@ -210,7 +211,7 @@
if ( 'rejected' === $status ) {
$withdraw = self::get_withdraw_by_id( $withdraw_id );
if ( $withdraw ) {
- $details = WithdrawModel::safe_unserialize_array( $withdraw->method_data );
+ $details = tutor_unserialize( $withdraw->method_data );
if ( empty( $details ) ) {
$details = array();
--- a/tutor/classes/WooCommerce.php
+++ b/tutor/classes/WooCommerce.php
@@ -12,6 +12,7 @@
defined( 'ABSPATH' ) || exit;
+use TutorCoreInput;
use TutorHelpersQueryHelper;
use TutorHelpersUrlHelper;
use TutorModelsEnrollmentModel;
--- a/tutor/components/DateFilter.php
+++ b/tutor/components/DateFilter.php
@@ -164,6 +164,15 @@
protected $clear_params = array();
/**
+ * Default preset to activate when no date range is selected.
+ *
+ * @since 4.2.1
+ *
+ * @var string|null
+ */
+ protected $default_preset = null;
+
+ /**
* Whether to operate in AJAX mode (dispatch event instead of full page reload).
*
* @since 4.1.0
@@ -297,6 +306,20 @@
}
/**
+ * Set default preset when no date range is selected.
+ *
+ * @since 4.2.1
+ *
+ * @param string|null $preset Preset key (e.g. 'all-time').
+ *
+ * @return self
+ */
+ public function default_preset( ?string $preset = 'all-time' ): self {
+ $this->default_preset = $preset;
+ return $this;
+ }
+
+ /**
* Render the component.
*
* @return string
@@ -308,11 +331,14 @@
$this->label = $this->calculate_label();
}
+ $default_preset = $this->default_preset ?? ( $this->hide_initial_label ? null : 'all-time' );
+
// Default settings based on type.
$calendar_options = array(
- 'type' => 'default',
- 'clearParams' => $this->clear_params,
- 'ajaxMode' => $this->ajax_mode,
+ 'type' => 'default',
+ 'clearParams' => $this->clear_params,
+ 'ajaxMode' => $this->ajax_mode,
+ 'defaultPreset' => $default_preset,
);
$button_classes = 'tutor-btn tutor-btn-outline';
@@ -330,6 +356,7 @@
'selectionDatesMode' => 'multiple-ranged',
'clearParams' => $this->clear_params,
'ajaxMode' => $this->ajax_mode,
+ 'defaultPreset' => $default_preset,
);
$popover_classes .= ' tutor-range-calendar-popover';
}
@@ -357,8 +384,8 @@
}"
<?php if ( $this->ajax_mode ) : ?>
@tutor:date-filter-changed.window="
- hasSelection = Boolean( $event.detail.startDate || $event.detail.endDate || $event.detail.date );
- label = $event.detail.label || <?php echo esc_attr( wp_json_encode( $this->hide_initial_label ? '' : __( 'All Time', 'tutor' ) ) ); ?>;
+ hasSelection = Boolean( $event.detail.startDate || $event.detail.endDate || $event.detail.date || $event.detail.period === 'all-time' );
+ label = hasSelection ? ( $event.detail.label || '' ) : <?php echo esc_attr( wp_json_encode( $this->hide_initial_label ? '' : __( 'All Time', 'tutor' ) ) ); ?>;
"
<?php endif; ?>
<?php echo $this->get_attributes_string(); //phpcs:ignore -- Sanitization is performed inside get_attributes_string. ?>
@@ -406,7 +433,7 @@
if ( self::TYPE_SINGLE === $this->type ) {
return ! empty( Input::get( 'date' ) );
}
- return ! empty( Input::get( 'start_date' ) ) && ! empty( Input::get( 'end_date' ) );
+ return ( ! empty( Input::get( 'start_date' ) ) && ! empty( Input::get( 'end_date' ) ) ) || 'all-time' === Input::get( 'period' );
}
/**
@@ -425,6 +452,11 @@
$start_date = Input::get( 'start_date' );
$end_date = Input::get( 'end_date' );
+ $period = Input::get( 'period' );
+
+ if ( 'all-time' === $period ) {
+ return __( 'All Time', 'tutor' );
+ }
if ( ! $start_date || ! $end_date ) {
return $this->hide_initial_label ? '' : __( 'All Time', 'tutor' );
--- a/tutor/components/Skeleton.php
+++ b/tutor/components/Skeleton.php
@@ -418,7 +418,7 @@
<div class="tutor-small">
<span class="tutor-skeleton" style="width: 170px; height: 18px; display: inline-block;"></span>
</div>
- <span class="tutor-skeleton tutor-rounded-md" style="width: 95px; height: 28px; display: inline-block;"></span>
+ <span class="tutor-skeleton tutor-rounded-md" style="width: 95px; height: 32px; display: inline-block;"></span>
</div>
<div class="tutor-dashboard-home-card-body tutor-gap-4">
<?php for ( $i = 0; $i < $this->count; $i++ ) : ?>
--- a/tutor/core/DB.php
+++ b/tutor/core/DB.php
@@ -34,6 +34,15 @@
class DB {
/**
+ * WordPress database instance.
+ *
+ * @since 4.2.0
+ *
+ * @var wpdb|null
+ */
+ protected static $db = null;
+
+ /**
* Table name (with prefix).
*
* @since 4.2.0
@@ -144,6 +153,24 @@
private $offset_value = 0;
/**
+ * Row locking clause (e.g., 'FOR UPDATE').
+ *
+ * @since 4.2.0
+ *
+ * @var string
+ */
+ private $lock = '';
+
+ /**
+ * Transaction nesting level.
+ *
+ * @since 4.2.0
+ *
+ * @var int
+ */
+ private static $transaction_level = 0;
+
+ /**
* Supported comparison operators.
*
* @since 4.2.0
@@ -169,10 +196,40 @@
);
// ─────────────────────────────────────────────
- // Factory
+ // Factory & Database Accessors
// ─────────────────────────────────────────────
/**
+ * Get the database instance, falling back to the global $wpdb.
+ *
+ * @since 4.2.0
+ *
+ * @return wpdb Database instance.
+ */
+ protected static function get_db(): wpdb {
+ if ( ! static::$db instanceof wpdb ) {
+ global $wpdb;
+ static::$db = $wpdb;
+ }
+
+ return static::$db;
+ }
+
+ /**
+ * Override the database instance (mainly for testing).
+ * Pass null to reset to the global $wpdb.
+ *
+ * @since 4.2.0
+ *
+ * @param wpdb|null $db Database instance.
+ *
+ * @return void
+ */
+ public static function set_db( ?wpdb $db = null ): void {
+ static::$db = $db;
+ }
+
+ /**
* Create a new DB query instance for the given table.
*
* The table name will be automatically prefixed with the WordPress
@@ -234,9 +291,8 @@
*/
public function select_raw( string $expression, array $bindings = array() ): self {
if ( ! empty( $bindings ) ) {
- global $wpdb;
// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- User-provided expression with bindings.
- $expression = $wpdb->prepare( $expression, $bindings );
+ $expression = self::get_db()->prepare( $expression, $bindings );
}
$this->raw_columns[] = $expression;
@@ -883,9 +939,8 @@
*/
public function having_raw( string $expression, array $bindings = array() ): self {
if ( ! empty( $bindings ) ) {
- global $wpdb;
// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Raw expression with user-controlled bindings.
- $expression = $wpdb->prepare( $expression, $bindings );
+ $expression = self::get_db()->prepare( $expression, $bindings );
}
$this->havings[] = $expression;
@@ -932,9 +987,8 @@
*/
public function order_by_raw( string $expression, array $bindings = array() ): self {
if ( ! empty( $bindings ) ) {
- global $wpdb;
// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
- $expression = $wpdb->prepare( $expression, $bindings );
+ $expression = self::get_db()->prepare( $expression, $bindings );
}
$this->order_by_clauses[] = $expression;
@@ -1003,6 +1057,38 @@
}
// ─────────────────────────────────────────────
+ // Row Locking
+ // ─────────────────────────────────────────────
+
+ /**
+ * Lock the selected rows for update ('FOR UPDATE').
+ *
+ * Appends 'FOR UPDATE' to the query. Locking is held within an active
+ * transaction. On database engines that do not support row locking
+ * (such as MyISAM or SQLite), the clause is safely omitted during execution.
+ *
+ * @since 4.2.0
+ *
+ * @return self
+ */
+ public function lock_for_update(): self {
+ $this->lock = 'FOR UPDATE';
+
+ return $this;
+ }
+
+ /**
+ * Check whether row locking is applied to the current query instance.
+ *
+ * @since 4.2.0
+ *
+ * @return bool True if lock_for_update has been applied.
+ */
+ public function is_locked(): bool {
+ return ! empty( $this->lock );
+ }
+
+ // ─────────────────────────────────────────────
// Terminal Methods (execute & return results)
// ─────────────────────────────────────────────
@@ -1016,12 +1102,10 @@
* @return array Array of result rows.
*/
public function get( string $output = 'OBJECT' ): array {
- global $wpdb;
-
$sql = $this->build_select_query();
// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- SQL built with prepare_value/prepare calls.
- $results = $wpdb->get_results( $sql, $output );
+ $results = self::get_db()->get_results( $sql, $output );
return is_array( $results ) ? $results : array();
}
@@ -1036,8 +1120,6 @@
* @return object|array|null Single row or null if not found.
*/
public function first( string $output = 'OBJECT' ) {
- global $wpdb;
-
// Temporarily set limit to 1.
$saved_limit = $this->limit_value;
$this->limit_value = 1;
@@ -1047,7 +1129,7 @@
$this->limit_value = $saved_limit;
// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
- return $wpdb->get_row( $sql, $output );
+ return self::get_db()->get_row( $sql, $output );
}
/**
@@ -1060,8 +1142,6 @@
* @return int Total matching row count.
*/
public function count( string $column = '*' ): int {
- global $wpdb;
-
if ( '*' !== $column && ! self::is_valid_column( $column ) ) {
$column = '*';
}
@@ -1073,9 +1153,11 @@
$saved_limit = $this->limit_value;
$saved_offset = $this->offset_value;
$saved_distinct = $this->is_distinct;
+ $saved_lock = $this->lock;
// Override for count.
$this->columns = array();
+ $this->lock = '';
if ( $saved_distinct ) {
if ( '*' !== $column ) {
@@ -1103,9 +1185,10 @@
$this->limit_value = $saved_limit;
$this->offset_value = $saved_offset;
$this->is_distinct = $saved_distinct;
+ $this->lock = $saved_lock;
// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
- return (int) $wpdb->get_var( $sql );
+ return (int) self::get_db()->get_var( $sql );
}
/**
@@ -1126,8 +1209,6 @@
* }
*/
public function paginate( int $per_page, int $current_page = 1, string $output = 'OBJECT' ): array {
- global $wpdb;
-
$current_page = max( 1, $current_page );
$per_page = max( 1, $per_page );
@@ -1137,10 +1218,10 @@
$sql = $this->build_select_query( true );
// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
- $results = $wpdb->get_results( $sql, $output );
+ $results = self::get_db()->get_results( $sql, $output );
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
- $total_count = (int) $wpdb->get_var( 'SELECT FOUND_ROWS()' );
+ $total_count = (int) self::get_db()->get_var( 'SELECT FOUND_ROWS()' );
$total_pages = (int) ceil( $total_count / $per_page );
return array(
@@ -1162,8 +1243,6 @@
* @return mixed|null The column value or null if not found.
*/
public function value( string $column ) {
- global $wpdb;
-
if ( ! self::is_valid_column( $column ) ) {
return null;
}
@@ -1186,7 +1265,7 @@
$this->limit_value = $saved_limit;
// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
- return $wpdb->get_var( $sql );
+ return self::get_db()->get_var( $sql );
}
/**
@@ -1299,16 +1378,16 @@
* @return int Inserted row ID.
*/
public function insert( array $data, array $format = array() ): int {
- global $wpdb;
+ $db = self::get_db();
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
- $result = $wpdb->insert( $this->table, $data, ! empty( $format ) ? $format : null );
+ $result = $db->insert( $this->table, $data, ! empty( $format ) ? $format : null );
if ( false === $result ) {
- throw new DatabaseException( esc_html( $wpdb->last_error ) );
+ throw new DatabaseException( esc_html( $db->last_error ) );
}
- return $wpdb->insert_id;
+ return $db->insert_id;
}
/**
@@ -1326,8 +1405,6 @@
* @return bool True on success.
*/
public function insert_multiple( array $rows ): bool {
- global $wpdb;
-
if ( empty( $rows ) ) {
return false;
}
@@ -1363,11 +1440,13 @@
$sql = "INSERT INTO {$this->table} ({$column_list}) VALUES " . implode( ', ', $value_groups );
+ $db = self::get_db();
+
// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Values prepared inline via prepare_value().
- $result = $wpdb->query( $sql );
+ $result = $db->query( $sql );
if ( false === $result ) {
- throw new DatabaseException( esc_html( $wpdb->last_error ) );
+ throw new DatabaseException( esc_html( $db->last_error ) );
}
return true;
@@ -1388,8 +1467,6 @@
* @return bool True on success.
*/
public function update( array $data ): bool {
- global $wpdb;
-
if ( empty( $data ) ) {
return false;
}
@@ -1421,11 +1498,13 @@
$sql .= " WHERE {$where_clause}";
}
+ $db = self::get_db();
+
// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Values prepared inline.
- $result = $wpdb->query( $sql );
+ $result = $db->query( $sql );
if ( false === $result ) {
- throw new DatabaseException( esc_html( $wpdb->last_error ) );
+ throw new DatabaseException( esc_html( $db->last_error ) );
}
return true;
@@ -1444,8 +1523,6 @@
* @return int Number of affected rows.
*/
public function delete(): int {
- global $wpdb;
-
$where_clause = $this->build_where_sql();
if ( ! empty( $this->alias ) ) {
@@ -1458,11 +1535,13 @@
$sql .= " WHERE {$where_clause}";
}
+ $db = self::get_db();
+
// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- WHERE values prepared inline.
- $result = $wpdb->query( $sql );
+ $result = $db->query( $sql );
if ( false === $result ) {
- throw new DatabaseException( esc_html( $wpdb->last_error ) );
+ throw new DatabaseException( esc_html( $db->last_error ) );
}
return (int) $result;
@@ -1483,12 +1562,11 @@
* @return string The generated SQL string.
*/
public function to_sql(): string {
- global $wpdb;
-
$sql = $this->build_select_query();
+ $db = self::get_db();
- if ( isset( $wpdb ) && method_exists( $wpdb, 'remove_placeholder_escape' ) ) {
- return $wpdb->remove_placeholder_escape( $sql );
+ if ( isset( $db ) && method_exists( $db, 'remove_placeholder_escape' ) ) {
+ return $db->remove_placeholder_escape( $sql );
}
return $sql;
@@ -1515,8 +1593,6 @@
* @return self
*/
private function add_where( string $column, $operator_or_value, $value, string $boolean, bool $is_two_arg ): self {
- global $wpdb;
-
if ( ! self::is_valid_column( $column ) ) {
return $this;
}
@@ -1625,14 +1701,14 @@
* @return self
*/
private function add_where_like( string $column, string $value, string $type, string $boolean ): self {
- global $wpdb;
-
if ( ! self::is_valid_column( $column ) ) {
return $this;
}
+ $db = self::get_db();
+
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Column validated, type is hardcoded.
- $sql = $wpdb->prepare( "{$column} {$type} %s", '%' . $wpdb->esc_like( $value ) . '%' );
+ $sql = $db->prepare( "{$column} {$type} %s", '%' . $db->esc_like( $value ) . '%' );
$this->wheres[] = array(
'sql' => $sql,
@@ -1655,9 +1731,8 @@
*/
private function add_where_raw( string $expression, array $bindings, string $boolean ): self {
if ( ! empty( $bindings ) ) {
- global $wpdb;
// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Raw expression with user-controlled bindings.
- $expression = $wpdb->prepare( $expression, $bindings );
+ $expression = self::get_db()->prepare( $expression, $bindings );
}
$this->wheres[] = array(
@@ -1728,6 +1803,10 @@
$parts[] = $limit;
}
+ if ( ! empty( $this->lock ) ) {
+ $parts[] = $this->lock;
+ }
+
return implode( ' ', $parts );
}
@@ -1957,18 +2036,18 @@
* @return string Escaped SQL value literal.
*/
public static function prepare_value( $value ): string {
- global $wpdb;
-
if ( is_null( $value ) ) {
return 'NULL';
}
+ $db = self::get_db();
+
if ( is_bool( $value ) ) {
- return $wpdb->prepare( '%d', $value ? 1 : 0 );
+ return $db->prepare( '%d', $value ? 1 : 0 );
}
if ( is_int( $value ) ) {
- return $wpdb->prepare( '%d', $value );
+ return $db->prepare( '%d', $value );
}
if ( is_float( $value ) ) {
@@ -1977,12 +2056,12 @@
if ( false !== $dot_pos ) {
$decimals = strlen( substr( $str_val, $dot_pos + 1 ) );
// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnsupportedPlaceholder, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare
- return $wpdb->prepare( '%.' . $decimals . 'f', $value );
+ return $db->prepare( '%.' . $decimals . 'f', $value );
}
- return $wpdb->prepare( '%f', $value );
+ return $db->prepare( '%f', $value );
}
- return $wpdb->prepare( '%s', $value );
+ return $db->prepare( '%s', $value );
}
/**
@@ -2015,9 +2094,8 @@
* @return string Prefixed table name.
*/
public static function prepare_table_name( string $table ): string {
- global $wpdb;
-
- $prefix = isset( $wpdb->prefix ) ? $wpdb->prefix : '';
+ $db = self::get_db();
+ $prefix = isset( $db->prefix ) ? $db->prefix : '';
if ( ! empty( $prefix ) && 0 !== strpos( $table, $prefix ) ) {
return $prefix . $table;
}
@@ -2033,9 +2111,9 @@
* @return string Table prefix.
*/
public static function get_table_prefix(): string {
- global $wpdb;
+ $db = self::get_db();
- return isset( $wpdb->prefix ) ? $wpdb->prefix : '';
+ return isset( $db->prefix ) ? $db->prefix : '';
}
/**
@@ -2046,8 +2124,299 @@
* @return string Last executed SQL query.
*/
public static function get_last_query(): string {
- global $wpdb;
+ $db = self::get_db();
+
+ return isset( $db->last_query ) ? $db->last_query : '';
+ }
+
+ // ─────────────────────────────────────────────
+ // Schema Validation Utilities
+ // ─────────────────────────────────────────────
+
+ /**
+ * Check whether a table exists in the database.
+ *
+ * Handles both prefixed and non-prefixed table names safely without
+ * SQL injection vulnerability.
+ *
+ * @since 4.2.0
+ *
+ * @param string $table Table name to check.
+ *
+ * @return bool True if table exists, false otherwise.
+ */
+ public static function has_table( string $table ): bool {
+ return null !== self::resolve_existing_table( $table );
+ }
+
+ /**
+ * Check whether a specific column exists in a table.
+ *
+ * @since 4.2.0
+ *
+ * @param string $table Table name.
+ * @param string $column Column name to check.
+ *
+ * @return bool True if column exists, false otherwise.
+ */
+ public static function has_column( string $table, string $column ): bool {
+ return self::has_columns( $table, array( $column ) );
+ }
+
+ /**
+ * Check whether all specified columns exist in a table.
+ *
+ * @since 4.2.0
+ *
+ * @param string $table Table name.
+ * @param array $columns Array of column names to check.
+ *
+ * @return bool True if all columns exist, false otherwise.
+ */
+ public static function has_columns( s