Below is a differential between the unpatched vulnerable code and the patched update, for reference.
--- a/tutor/classes/Course.php
+++ b/tutor/classes/Course.php
@@ -10,11 +10,11 @@
namespace TUTOR;
+defined( 'ABSPATH' ) || exit;
+
use Exception;
use InvalidArgumentException;
-defined( 'ABSPATH' ) || exit;
-
use TutorComponentsButton;
use TutorComponentsConstantsSize;
use TutorComponentsConstantsVariant;
@@ -24,6 +24,7 @@
use TutorHelpersHttpHelper;
use TutorModelsCourseModel;
use TutorComponentsTooltip;
+use TutorCoreInput;
use TutorEcommerceEcommerce;
use TutorHelpersDateTimeHelper;
use TutorTraitsJsonResponse;
@@ -331,7 +332,7 @@
global $wp_query;
$course_coming_soon_enabled = (int) get_post_meta( $content->ID, '_tutor_course_enable_coming_soon', true );
$is_instructor = tutor_utils()->is_instructor_of_this_course( get_current_user_id(), $content->ID, true );
- if ( ! CourseModel::get_post_types( $content ) || current_user_can( 'administrator' ) || $is_instructor || $course_coming_soon_enabled ) {
+ if ( ! CourseModel::get_post_types( $content ) || User::is_admin() || $is_instructor || $course_coming_soon_enabled ) {
return $content;
}
@@ -626,6 +627,32 @@
}
/**
+ * Validate WC product author
+ *
+ * @since 4.2.2
+ *
+ * @param int $product_id product id.
+ * @param int $course_id course id.
+ *
+ * @return bool
+ */
+ public function is_valid_wc_product_author( $product_id, $course_id ) {
+ if ( User::is_admin() ) {
+ return true;
+ }
+ $product_author = (int) get_post_field( 'post_author', $product_id );
+ $current_user_id = get_current_user_id();
+ if ( $product_author === $current_user_id ) {
+ return true;
+ }
+ $course_author = (int) get_post_field( 'post_author', $course_id );
+ if ( $product_author === $course_author && tutor_utils()->is_instructor_of_this_course( $current_user_id, $course_id ) ) {
+ return true;
+ }
+ return false;
+ }
+
+ /**
* Validate price
*
* @since 3.0.0
@@ -651,6 +678,10 @@
$product_id = isset( $params['pricing']['product_id'] ) ? (int) $params['pricing']['product_id'] : 0;
if ( $product_id ) {
+ if ( ! $this->is_valid_wc_product_author( $product_id, $course_id ) ) {
+ $errors['pricing'] = __( 'You are not authorized to use this product', 'tutor' );
+ }
+
$product = wc_get_product( $product_id );
if ( is_a( $product, 'WC_Product' ) ) {
if ( $course_product_id !== $product_id ) {
@@ -1111,8 +1142,10 @@
true
);
- $course_id = (int) $params['course_id'];
- if ( ! $course_id ) {
+ $current_user_id = get_current_user_id();
+ $course_id = (int) $params['course_id'];
+ $course = get_post( $course_id );
+ if ( ! $course_id || ! $course || tutor()->course_post_type !== $course->post_type ) {
$this->response_bad_request( __( 'Invalid course id', 'tutor' ) );
}
@@ -1144,26 +1177,17 @@
$this->json_response( __( 'Invalid input', 'tutor' ), $errors, HttpHelper::STATUS_UNPROCESSABLE_ENTITY );
}
- /**
- * Can trash a course when user is admin or option `instructor_can_delete_course` is turned on.
- */
- if ( CourseModel::STATUS_TRASH === $params['post_status'] ) {
- if ( User::is_admin() || tutor_utils()->get_option( 'instructor_can_delete_course', false ) ) {
- $params['post_status'] = CourseModel::STATUS_TRASH;
- } else {
- unset( $params['post_status'] );
+ if ( isset( $params['post_status'] ) ) {
+ $current_status = get_post_status( $course_id );
+ if ( $params['post_status'] !== $current_status ) {
+ if ( ! CourseModel::can_user_update_status( $course_id, $params['post_status'] ) ) {
+ $params['post_status'] = CourseModel::STATUS_PENDING;
+ }
}
}
- /**
- * Can publish a course when user is admin or option `instructor_can_publish_course` is turned on.
- * If instructor_can_publish_course is turned off then course status will be pending.
- */
- if ( CourseModel::STATUS_PUBLISH === $params['post_status'] ) {
- $is_instructor_allowed_to_publish = (bool) tutor_utils()->get_option( 'instructor_can_publish_course', false );
- if ( ! User::is_admin() && ! $is_instructor_allowed_to_publish ) {
- $params['post_status'] = CourseModel::STATUS_PENDING;
- }
+ if ( ! User::is_admin() || ! CourseModel::is_main_instructor( $course_id, $current_user_id ) ) {
+ $params['post_author'] = $course->post_author;
}
$is_error = apply_filters( 'tutor_is_error_before_course_update', false, $params );
@@ -1569,12 +1593,14 @@
'instructor_can_publish_course',
'instructor_can_change_course_author',
'instructor_can_manage_co_instructors',
+ 'course_completion_process',
+ 'control_video_lesson_completion',
);
- $full_settings = get_option( 'tutor_option', array() );
- $settings = Options_V2::get_only( $required_options );
- $logo_id = absint( $full_settings['brand_logo_light'] ?? $full_settings['tutor_frontend_course_page_logo_id'] ?? 0 );
- $settings['brand_logo_light'] = $logo_id > 0 ? wp_get_attachment_image_url( $logo_id, 'full' ) : '';
+ $full_settings = get_option( 'tutor_option', array() );
+ $settings = Options_V2::get_only( $required_options );
+ $logo_id = absint( $full_settings['brand_logo_light'] ?? $full_settings['tutor_frontend_course_page_logo_id'] ?? 0 );
+ $settings['brand_logo_light'] = $logo_id > 0 ? wp_get_attachment_image_url( $logo_id, 'full' ) : '';
$settings['youtube_api_key_exist'] = ! empty( $full_settings['lesson_video_duration_youtube_api_key'] ?? '' );
@@ -1731,7 +1757,7 @@
*/
public function get_wc_product() {
tutor_utils()->checking_nonce();
- $course_id = Input::post( 'course_id', 0, Input::TYPE_INT );
+ $course_id = Input::post( 'course_id', 0, Input::TYPE_INT );
$this->check_access( $course_id );
$product_id = Input::post( 'product_id' );
@@ -2119,6 +2145,13 @@
wp_send_json_error( array( 'message' => __( 'Access Denied', 'tutor' ) ) );
}
+ if ( $topic_id ) {
+ $existing_topic = get_post( $topic_id );
+ if ( ! $existing_topic || tutor()->topics_post_type !== $existing_topic->post_type || (int) $existing_topic->post_parent !== $course_id ) {
+ wp_send_json_error( array( 'message' => __( 'Access Denied', 'tutor' ) ) );
+ }
+ }
+
// Create payload to create/update the topic.
$post_arr = array(
'post_type' => 'topics',
@@ -2163,7 +2196,44 @@
tutor_utils()->check_nonce();
$topic_id = Input::post( 'topic_id', 0, Input::TYPE_INT );
- if ( ! $topic_id || ! is_numeric( $topic_id ) || ! tutor_utils()->can_user_manage( 'topic', $topic_id ) ) {
+ if ( ! $topic_id ) {
+ $this->json_response(
+ __( 'Invalid topic id', 'tutor' ),
+ null,
+ HttpHelper::STATUS_BAD_REQUEST
+ );
+ }
+
+ $topic = get_post( $topic_id );
+ if ( ! $topic || tutor()->topics_post_type !== $topic->post_type ) {
+ $this->json_response(
+ __( 'Invalid topic id', 'tutor' ),
+ null,
+ HttpHelper::STATUS_BAD_REQUEST
+ );
+ }
+
+ $course_id = (int) $topic->post_parent;
+ $provided_course_id = Input::post( 'course_id', 0, Input::TYPE_INT );
+
+ if ( $provided_course_id > 0 && $provided_course_id !== $course_id ) {
+ $this->json_response(
+ tutor_utils()->error_message(),
+ null,
+ HttpHelper::STATUS_FORBIDDEN
+ );
+ }
+
+ if ( ! $course_id || tutor()->course_post_type !== get_post_type( $course_id ) ) {
+ $this->json_response(
+ __( 'Invalid course id', 'tutor' ),
+ null,
+ HttpHelper::STATUS_BAD_REQUEST
+ );
+ }
+
+ $current_user_id = get_current_user_id();
+ if ( ! tutor_utils()->can_user_edit_course( $current_user_id, $course_id ) || ! tutor_utils()->can_user_manage( 'topic', $topic_id ) ) {
$this->json_response(
tutor_utils()->error_message(),
null,
@@ -2174,10 +2244,10 @@
global $wpdb;
// Assign course ID to orphan content IDs since the topic will be deleted.
- $course_id = tutor_utils()->get_course_id_by( 'topic', $topic_id );
$content_ids = tutor_utils()->get_course_content_ids_by( null, 'topic', $topic_id );
foreach ( $content_ids as $content_id ) {
update_post_meta( $content_id, '_tutor_course_id_for_lesson', $course_id );
+ clean_post_cache( $content_id );
// Actually all kind of contents.
// This keyword '_tutor_course_id_for_lesson' used just to support backward compatibility.
}
@@ -2221,16 +2291,22 @@
return;
}
+ $course = get_post( $course_id );
+ if ( ! ( $course instanceof WP_Post ) ) {
+ return;
+ }
+
/**
* TODO: need to check purchase information
*/
$is_purchasable = tutor_utils()->is_course_purchasable( $course_id );
-
- $course = get_post( $course_id );
-
if ( 'private' === $course->post_status && ! current_user_can( 'read_private_tutor_courses' ) ) {
- wp_send_json_error( __( 'You do not have permission to enroll in this course', 'tutor' ) );
+ $message = __( 'You do not have permission to enroll in this course', 'tutor' );
+ if ( wp_doing_ajax() ) {
+ wp_send_json_error( $message );
+ }
+ wp_die( esc_html( $message ), 403 );
}
/**
@@ -2439,40 +2515,14 @@
tutor_utils()->checking_nonce();
$course_id = Input::post( 'course_id', 0, Input::TYPE_INT );
- if ( ! tutor_utils()->can_user_manage( 'course', $course_id ) ) {
- wp_send_json_error( array( 'message' => __( 'Access Denied', 'tutor' ) ) );
- }
- /**
- * Co-instructor can not delete a course
- *
- * @since 2.1.6
- */
- if ( false === CourseModel::is_main_instructor( $course_id ) ) {
- wp_send_json_error( array( 'message' => __( 'Only main instructor can delete this course', 'tutor' ) ) );
- }
-
- // Check if user is only an instructor.
- if ( ! User::is_admin() ) {
- // Check if instructor can trash course.
- $can_trash_post = tutor_utils()->get_option( 'instructor_can_delete_course' );
-
- if ( ! $can_trash_post ) {
- wp_send_json_error( tutor_utils()->error_message() );
- }
- }
+ $deleted = CourseModel::delete_course( $course_id, false );
- $trash_course = wp_update_post(
- array(
- 'ID' => $course_id,
- 'post_status' => CourseModel::STATUS_TRASH,
- )
- );
-
- if ( $trash_course ) {
+ if ( $deleted ) {
wp_send_json_success( __( 'Course has been trashed successfully ', 'tutor' ) );
}
- wp_send_json_success();
+
+ wp_send_json_error( tutor_utils()->error_message() );
}
/**
@@ -2497,7 +2547,7 @@
/**
* Only admin can change main author
*/
- if ( $courses_post_type === $post_type && ! current_user_can( 'administrator' ) ) {
+ if ( $courses_post_type === $post_type && ! User::is_admin() ) {
global $wpdb;
$post_ID = (int) tutor_utils()->avalue_dot( 'ID', $postarr );
$post_author = (int) $wpdb->get_var( $wpdb->prepare( "SELECT post_author FROM {$wpdb->posts} WHERE ID = %d ", $post_ID ) );
@@ -2569,8 +2619,7 @@
update_post_meta( $post_ID, self::COURSE_PRICE_TYPE_META, self::PRICE_TYPE_PAID );
if ( 'wc' === $monetize_by ) {
-
- $is_update = ( $product_id && wc_get_product( $product_id ) ) ? true : false;
+ $is_update = ( $product_id && wc_get_product( $product_id ) && $this->is_valid_wc_product_author( $product_id, $post_ID ) ) ? true : false;
if ( $is_update ) {
update_post_meta( $post_ID, self::COURSE_PRODUCT_ID_META, $product_id );
@@ -3275,6 +3324,10 @@
* @return void
*/
public static function redirect_to_course_list_page( int $post_id ): void {
+ if ( wp_doing_ajax() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) || ( defined( 'WP_CLI' ) && WP_CLI ) || headers_sent() ) {
+ return;
+ }
+
$post = get_post( $post_id );
if ( tutor()->course_post_type === $post->post_type ) {
$is_gutenberg_enabled = tutor_utils()->get_option( 'enable_gutenberg_course_edit' );
@@ -3476,11 +3529,15 @@
*
* @since 4.0.0
*
- * @param int $course_id course id.
+ * @param int $course_id course id.
*
* @return void
*/
public function render_course_action_btn( int $course_id ) {
+ if ( ! EnrollmentModel::is_enrolled( $course_id, get_current_user_id() ) ) {
+ return;
+ }
+
$is_completed = tutor_utils()->is_completed_course( $course_id );
if ( $is_completed ) {
$certificate_addon_active = tutor_utils()->is_addon_enabled( 'tutor-certificate' );
@@ -3658,8 +3715,15 @@
}
if ( ! empty( $content_parent ) ) {
- $provided_topic_ids[] = $content_parent['parent_topic_id'];
- $provided_content_ids[] = $content_parent['content_id'];
+ $parents = ( isset( $content_parent[0] ) && is_array( $content_parent[0] ) ) ? $content_parent : array( $content_parent );
+ foreach ( $parents as $item ) {
+ if ( isset( $item['parent_topic_id'] ) ) {
+ $provided_topic_ids[] = (int) $item['parent_topic_id'];
+ }
+ if ( isset( $item['content_id'] ) ) {
+ $provided_content_ids[] = (int) $item['content_id'];
+ }
+ }
}
$provided_topic_ids = array_values( array_unique( array_filter( $provided_topic_ids ) ) );
--- a/tutor/classes/Course_List.php
+++ b/tutor/classes/Course_List.php
@@ -12,6 +12,7 @@
defined( 'ABSPATH' ) || exit;
+use TutorCoreInput;
use TutorHelpersQueryHelper;
use TutorModelsCourseModel;
@@ -186,7 +187,7 @@
'url' => $url . '&data=trash',
),
);
- if ( ! tutor_utils()->get_option( 'instructor_can_delete_course' ) && ! current_user_can( 'administrator' ) ) {
+ if ( ! tutor_utils()->get_option( 'instructor_can_delete_course' ) && ! User::is_admin() ) {
unset( $tabs[7] );
}
return apply_filters( 'tutor_course_tabs', $tabs );
@@ -225,7 +226,7 @@
}
// Author query.
- if ( 'mine' === $status || ! current_user_can( 'administrator' ) ) {
+ if ( 'mine' === $status || ! User::is_admin() ) {
$args['author'] = $user_id;
}
@@ -285,32 +286,6 @@
$action = Input::post( 'bulk-action', '' );
$bulk_ids = Input::post( 'bulk-ids', '' );
- // Check if user is privileged.
- if ( ! User::is_admin() ) {
- $course_ids = explode( ',', $bulk_ids );
-
- if ( current_user_can( 'edit_tutor_courses' ) ) {
- $can_publish_course = tutor_utils()->get_option( 'instructor_can_publish_course' );
-
- if ( CourseModel::STATUS_PUBLISH === $action && ! $can_publish_course ) {
- wp_send_json_error( tutor_utils()->error_message() );
- }
- } else {
- wp_send_json_error( tutor_utils()->error_message() );
- }
-
- // Check if the course ids are instructors own course.
- $course_ids = array_filter(
- $course_ids,
- function ( $course_id ) {
- return tutor_utils()->is_instructor_of_this_course( get_current_user_id(), $course_id );
- }
- );
-
- $bulk_ids = implode( ',', $course_ids );
-
- }
-
if ( '' === $action || '' === $bulk_ids ) {
wp_send_json_error( array( 'message' => __( 'Please select appropriate action', 'tutor' ) ) );
exit;
@@ -320,7 +295,8 @@
// Do action before delete.
do_action( 'before_tutor_course_bulk_action_delete', $bulk_ids );
- $delete_courses = self::bulk_delete_course( $bulk_ids );
+ $force_delete = User::is_admin();
+ $delete_courses = CourseModel::bulk_delete_course( $bulk_ids, $force_delete );
do_action( 'after_tutor_course_bulk_action_delete', $bulk_ids );
$delete_courses ? wp_send_json_success() : wp_send_json_error( array( 'message' => __( 'Could not delete selected courses', 'tutor' ) ) );
@@ -335,7 +311,7 @@
*/
do_action( 'before_tutor_course_bulk_action_update', $action, $bulk_ids );
- $update_status = self::update_course_status( $action, $bulk_ids );
+ $update_status = CourseModel::bulk_update_course_status( $bulk_ids, $action );
do_action( 'after_tutor_course_bulk_action_update', $action, $bulk_ids );
@@ -356,52 +332,18 @@
$status = Input::post( 'status' );
$id = Input::post( 'id', 0, Input::TYPE_INT );
- $course = get_post( $id );
-
- // Check if user is privileged.
- if ( ! User::is_admin() ) {
- if ( ! tutor_utils()->can_user_edit_course( get_current_user_id(), $course->ID ) ) {
- wp_send_json_error( tutor_utils()->error_message() );
- }
-
- $can_delete_course = tutor_utils()->get_option( 'instructor_can_delete_course' );
- $can_publish_course = tutor_utils()->get_option( 'instructor_can_publish_course' );
-
- if ( CourseModel::STATUS_PUBLISH === $status && ! $can_publish_course ) {
- wp_send_json_error( tutor_utils()->error_message() );
- }
+ $updated = CourseModel::update_course_status( $id, $status );
- if ( CourseModel::STATUS_TRASH === $status && $can_delete_course ) {
- $args = array(
- 'ID' => $id,
- 'post_status' => $status,
- );
- $trash_post = wp_update_post( $args );
-
- if ( $trash_post ) {
- wp_send_json_success( __( 'Course trashed successfully', 'tutor' ) );
- }
+ if ( $updated ) {
+ if ( CourseModel::STATUS_TRASH === $status ) {
+ wp_send_json_success( __( 'Course trashed successfully', 'tutor' ) );
}
- }
-
- if ( ! CourseModel::get_post_types( $course ) ) {
+ wp_send_json_success();
+ } else {
wp_send_json_error( tutor_utils()->error_message() );
}
- $args = array(
- 'ID' => $id,
- 'post_status' => $status,
- );
-
- if ( CourseModel::STATUS_FUTURE === $course->post_status && CourseModel::STATUS_PUBLISH === $status ) {
- $args['post_status'] = CourseModel::STATUS_PUBLISH;
- $args['post_date'] = current_time( 'mysql' );
- $args['post_date_gmt'] = current_time( 'mysql', 1 );
- }
-
- wp_update_post( $args );
- wp_send_json_success();
exit;
}
@@ -415,15 +357,10 @@
public static function tutor_course_delete() {
tutor_utils()->checking_nonce();
- $user_id = get_current_user_id();
- $course_id = Input::post( 'id', 0, Input::TYPE_INT );
+ $course_id = Input::post( 'id', 0, Input::TYPE_INT );
+ $force_delete = User::is_admin() && 'trash' === get_post_status( $course_id );
- // Check if user is privileged.
- if ( ! tutor_utils()->can_user_edit_course( $user_id, $course_id ) ) {
- wp_send_json_error( tutor_utils()->error_message() );
- }
-
- $delete = CourseModel::delete_course( $course_id );
+ $delete = CourseModel::delete_course( $course_id, $force_delete );
if ( $delete ) {
wp_send_json_success( __( 'Course has been deleted ', 'tutor' ) );
@@ -444,13 +381,7 @@
* @return bool
*/
public static function bulk_delete_course( $bulk_ids ): bool {
- $bulk_ids = explode( ',', sanitize_text_field( $bulk_ids ) );
-
- foreach ( $bulk_ids as $post_id ) {
- CourseModel::delete_course( $post_id );
- }
-
- return true;
+ return CourseModel::bulk_delete_course( $bulk_ids, User::is_admin() );
}
/**
@@ -464,22 +395,7 @@
* @return bool
*/
public static function update_course_status( string $status, $bulk_ids ): bool {
- global $wpdb;
- $post_table = $wpdb->posts;
- $status = sanitize_text_field( $status );
- $bulk_ids = sanitize_text_field( $bulk_ids );
-
- $ids = array_map( 'intval', explode( ',', $bulk_ids ) );
- $in_clause = QueryHelper::prepare_in_clause( $ids );
-
- $wpdb->query(
- $wpdb->prepare(
- "UPDATE {$post_table} SET post_status = %s WHERE ID IN ($in_clause)", //phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
- $status
- )
- );
-
- return true;
+ return CourseModel::bulk_update_course_status( $bulk_ids, $status );
}
/**
--- a/tutor/classes/Course_Settings_Tabs.php
+++ b/tutor/classes/Course_Settings_Tabs.php
@@ -10,9 +10,9 @@
namespace TUTOR;
-if ( ! defined( 'ABSPATH' ) ) {
- exit;
-}
+defined( 'ABSPATH' ) || exit;
+
+use TutorCoreInput;
/**
* Course Settings Tabs Class
--- a/tutor/classes/Course_Widget.php
+++ b/tutor/classes/Course_Widget.php
@@ -10,11 +10,9 @@
namespace TUTOR;
-use TutorModelsCourseModel;
+defined( 'ABSPATH' ) || exit;
-if ( ! defined( 'ABSPATH' ) ) {
- exit;
-}
+use TutorModelsCourseModel;
/**
* Course Widget Class
--- a/tutor/classes/Custom_Validation.php
+++ b/tutor/classes/Custom_Validation.php
@@ -10,6 +10,8 @@
namespace TUTOR;
+defined( 'ABSPATH' ) || exit;
+
/**
* Custom Validation Trait
*
--- a/tutor/classes/Dashboard.php
+++ b/tutor/classes/Dashboard.php
@@ -77,7 +77,7 @@
tutor_utils()->tutor_dashboard_url( self::WISHLIST_PAGE_SLUG ) => tutor_utils()->tutor_dashboard_url( 'courses/wishlist' ),
tutor_utils()->tutor_dashboard_url( self::MY_QUIZ_ATTEMPTS_SUBPAGE_SLUG ) => tutor_utils()->tutor_dashboard_url( 'courses/my-quiz-attempts' ),
tutor_utils()->tutor_dashboard_url( self::ENROLLED_COURSES_PAGE_SLUG ) => tutor_utils()->tutor_dashboard_url( self::COURSES_PAGE_SLUG ),
- tutor_utils()->get_tutor_dashboard_page_permalink( 'logout' ) => UrlHelper::add_query_params( wp_logout_url(), array( '_wpnonce' => wp_create_nonce( 'log-out' ) ) ),
+ tutor_utils()->get_tutor_dashboard_page_permalink( 'logout' ) => wp_logout_url(),
);
if ( ! isset( $redirect_mappings[ $current_url ] ) ) {
--- a/tutor/classes/DashboardSectionManager.php
+++ b/tutor/classes/DashboardSectionManager.php
@@ -16,6 +16,7 @@
defined( 'ABSPATH' ) || exit;
use TutorCoreInput;
+use TutorHelpersDateTimeHelper;
use TUTORInstructorMetricsAdapter;
use TutorTraitsJsonResponse;
@@ -87,11 +88,15 @@
*/
public static function get_section_data( string $section_id, array $params = array() ) {
$user_id = isset( $params['user_id'] ) ? (int) $params['user_id'] : get_current_user_id();
- $start_date = ! empty( $params['start_date'] ) ? sanitize_text_field( $params['start_date'] ) : '';
- $end_date = ! empty( $params['end_date'] ) ? sanitize_text_field( $params['end_date'] ) : '';
$type = ! empty( $params['type'] ) ? sanitize_text_field( $params['type'] ) : 'revenue';
$type = in_array( $type, array( 'revenue', 'student' ), true ) ? $type : 'revenue';
$limit = isset( $params['limit'] ) ? (int) $params['limit'] : 3;
+ $start_date = ! empty( $params['start_date'] )
+ ? DateTimeHelper::create( $params['start_date'] )->start_of_day()->to_date_time_string()
+ : '';
+ $end_date = ! empty( $params['end_date'] )
+ ? DateTimeHelper::create( $params['end_date'] )->end_of_day()->to_date_time_string()
+ : '';
switch ( $section_id ) {
case 'current_stats':
@@ -209,7 +214,7 @@
public function ajax_get_dashboard_section() {
tutor_utils()->check_nonce();
- if ( ! User::is_admin() && ! tutor_utils()->is_instructor() ) {
+ if ( ! User::is_admin() && ! User::is_instructor() ) {
$this->response_bad_request( tutor_utils()->error_message() );
}
--- a/tutor/classes/Earnings.php
+++ b/tutor/classes/Earnings.php
@@ -10,6 +10,9 @@
namespace TUTOR;
+defined( 'ABSPATH' ) || exit;
+
+use TutorCoreDB;
use TutorEcommerceEcommerce;
use TutorCoreSingleton;
use TutorModelsOrderModel;
@@ -85,6 +88,8 @@
*/
public function prepare_order_earnings( int $order_id ) {
$this->order_id = $order_id;
+ // Ensure never carry rows over from a previous order.
+ $this->earning_data = array();
$order_model = new OrderModel();
$order_details = $order_model->get_order_by_id( $order_id );
@@ -221,26 +226,7 @@
$instructor_rate = $sharing_enabled ? tutor_utils()->get_option( 'earning_instructor_commission' ) : 0;
$admin_rate = $sharing_enabled ? tutor_utils()->get_option( 'earning_admin_commission' ) : 100;
$commission_type = 'percent';
-
- // Course author id.
- $user_id = get_post_field( 'post_author', $course_id );
-
- // (Use Pro Filter - Start)
- // The response must be same array structure.
- // Do not change used variable names here, or change in both of here and pro plugin
- $pro_arg = array(
- 'user_id' => $user_id,
- 'instructor_rate' => $instructor_rate,
- 'admin_rate' => $admin_rate,
- 'instructor_amount' => max( 0, $instructor_amount ),
- 'admin_amount' => max( 0, $admin_amount ),
- 'course_price_grand_total' => $course_price_grand_total,
- 'commission_type' => $commission_type,
- );
-
- $pro_calculation = apply_filters( 'tutor_pro_earning_calculator', $pro_arg );
- extract( $pro_calculation ); //phpcs:ignore
- // (Use Pro Filter - End).
+ $user_id = empty( $course_id ) ? tutor_utils()->get_admin_user_id() : get_post_field( 'post_author', $course_id );
// Prepare insertable earning data.
$earning_data = array(
@@ -260,8 +246,17 @@
'process_by' => self::get_process_by(),
'created_at' => current_time( 'mysql', true ),
);
+
$earning_data = apply_filters( 'tutor_new_earning_data', array_merge( $earning_data, $fees_deduct_data ) );
+ /**
+ * Ensure instructor and admin amount are not negative.
+ *
+ * @since 4.2.2
+ */
+ $earning_data['instructor_amount'] = max( 0, $earning_data['instructor_amount'] ?? 0 );
+ $earning_data['admin_amount'] = max( 0, $earning_data['admin_amount'] ?? 0 );
+
return $earning_data;
}
@@ -354,7 +349,7 @@
);
if ( $update ) {
- $this->earning_data = null;
+ $this->earning_data = array();
}
return $update;
@@ -399,23 +394,31 @@
*
* @since 3.0.0
*
- * @throws Exception If earning_data is empty.
+ * @throws Exception If earning data is empty or the operation fails.
*
- * @return int On success inserted id will be returned
+ * @return int On success inserted id will be returned.
*/
public function remove_before_store_earnings() {
if ( empty( $this->earning_data ) ) {
throw new Exception( self::INVALID_DATA_MSG );
}
- if ( $this->is_exist_order_earning( $this->order_id ) ) {
- $this->delete_earning_by_order( $this->order_id );
- }
+ $earning_id = 0;
try {
- return $this->store_earnings();
- } catch ( Throwable $th ) {
+ DB::begin_transaction();
+ if ( $this->is_exist_order_earning( $this->order_id ) ) {
+ $this->delete_earning_by_order( $this->order_id );
+ }
+
+ $earning_id = $this->store_earnings();
+ DB::commit();
+ } catch ( Exception $th ) {
+ DB::rollback();
tutor_log( $th );
+ throw $th;
}
+
+ return $earning_id;
}
}
--- a/tutor/classes/FormHandler.php
+++ b/tutor/classes/FormHandler.php
@@ -10,11 +10,9 @@
namespace TUTOR;
-use TutorCoreInput;
+defined( 'ABSPATH' ) || exit;
-if ( ! defined( 'ABSPATH' ) ) {
- exit;
-}
+use TutorCoreInput;
/**
* FormHandler class
@@ -45,6 +43,8 @@
public function tutor_retrieve_password() {
tutils()->checking_nonce();
+ $user_data = false;
+
/**
* To check spam or other logic before form process.
*
@@ -74,7 +74,7 @@
$errors = new WP_Error();
- do_action( 'lostpassword_post', $errors );
+ do_action( 'lostpassword_post', $errors, $user_data );
if ( $errors->get_error_code() ) {
tutor_flash_set( 'danger', $errors->get_error_message() );
@@ -137,29 +137,37 @@
public function tutor_process_reset_password() {
tutils()->checking_nonce();
- $reset_key = Input::post( 'reset_key' );
- $user_id = Input::post( 'user_id', 0, Input::TYPE_INT );
- $password = Input::post( 'password' );
- $confirm_password = Input::post( 'confirm_password' );
+ $reset_key = Input::post( 'reset_key' );
+ $user_id = Input::post( 'user_id', 0, Input::TYPE_INT );
+
+ // phpcs:disable -- Passwords are unslashed and not sanitized, as sanitization may alter valid password characters. Ex: ab<c%41 to ab<c
+ $password = wp_unslash( $_POST['password'] ?? '' );
+ $confirm_password = wp_unslash( $_POST['confirm_password'] ?? '' );
+ // phpcs:enable
+
+ if ( ! $password ) {
+ tutor_flash_set( 'danger', __( 'Please enter your password.', 'tutor' ) );
+ return false;
+ }
+
+ if ( $password !== $confirm_password ) {
+ tutor_flash_set( 'danger', __( 'Passwords do not match.', 'tutor' ) );
+ return false;
+ }
$user = get_user_by( 'ID', $user_id );
- $user = check_password_reset_key( $reset_key, $user->user_login );
+ if ( ! $user ) {
+ tutor_flash_set( 'danger', __( 'Invalid Request.', 'tutor' ) );
+ return false;
+ }
+ $user = check_password_reset_key( $reset_key, $user->user_login );
if ( is_wp_error( $user ) ) {
tutor_flash_set( 'danger', __( 'This key is invalid or has already been used. Please reset your password again if needed.', 'tutor' ) );
return false;
}
if ( $user instanceof WP_User ) {
- if ( ! $password ) {
- tutor_flash_set( 'danger', __( 'Please enter your password.', 'tutor' ) );
- return false;
- }
-
- if ( $password !== $confirm_password ) {
- tutor_flash_set( 'danger', __( 'Passwords do not match.', 'tutor' ) );
- return false;
- }
tutils()->reset_password( $user, $password );
--- a/tutor/classes/Frontend.php
+++ b/tutor/classes/Frontend.php
@@ -10,11 +10,9 @@
namespace TUTOR;
-use TutorModelsCourseModel;
+defined( 'ABSPATH' ) || exit;
-if ( ! defined( 'ABSPATH' ) ) {
- exit;
-}
+use TutorModelsCourseModel;
/**
* Frontend class
@@ -39,7 +37,7 @@
add_action( 'wp_head', array( new Utils(), 'handle_flash_message' ), 999 );
add_action( 'tutor_course/single/before/wrap', array( $this, 'do_auto_course_complete' ) );
- add_filter( 'body_class', array( $this, 'add_kids_mode_attribute' ) );
+ add_filter( 'language_attributes', array( $this, 'add_kids_mode_attribute' ) );
}
/**
@@ -126,22 +124,17 @@
}
/**
- * Add kids mode data attribute to the <body> tag.
- *
- * Note: body_class filter only accepts class names, not attributes.
+ * Add kids mode data attribute to the html tag.
*
* @since 4.0.0
*
- * @param array $classes Body classes.
+ * @param string $output language attribute output.
*
- * @return array
+ * @return string
*/
- public function add_kids_mode_attribute( $classes ) {
- if ( ! tutor_utils()->is_kids_mode() ) {
- return $classes;
- }
-
- echo ' data-tutor-ui="kids"';
- return $classes;
+ public function add_kids_mode_attribute( $output ) {
+ return tutor_utils()->is_kids_mode()
+ ? $output . ' data-tutor-ui="kids"'
+ : $output;
}
}
--- a/tutor/classes/Gutenberg.php
+++ b/tutor/classes/Gutenberg.php
@@ -10,11 +10,9 @@
namespace TUTOR;
-use TutorCoreInput;
+defined( 'ABSPATH' ) || exit;
-if ( ! defined( 'ABSPATH' ) ) {
- exit;
-}
+use TutorCoreInput;
/**
* Gutenberg class
@@ -51,7 +49,7 @@
*/
public function author_list_dropdown( $prepared_args, $request ) {
$url = $request->get_header( 'referer' );
- $parts = parse_url( $url );
+ $parts = wp_parse_url( $url );
if ( ! isset( $parts['query'] ) ) {
return $prepared_args;
}
@@ -63,9 +61,11 @@
return $prepared_args;
}
- $post = get_post( $post_id );
+ $post = $post_id ? get_post( $post_id ) : null;
- if ( tutor()->course_post_type === $post->post_type && tutor_utils()->get_option( 'enable_gutenberg_course_edit' ) === true ) {
+ if ( $post
+ && tutor()->course_post_type === $post->post_type
+ && tutor_utils()->get_option( 'enable_gutenberg_course_edit' ) === true ) {
// Modify the wp/v2/users endpoint request from gutenberg editor.
unset( $prepared_args['who'] );
$prepared_args['role__in'] = array( 'administrator', 'tutor_instructor' );
--- a/tutor/classes/Icon.php
+++ b/tutor/classes/Icon.php
@@ -10,6 +10,8 @@
namespace TUTOR;
+defined( 'ABSPATH' ) || exit;
+
/**
* Icon class for Icon Names.
*
@@ -179,6 +181,7 @@
const EMAIL = 'email';
const EMAIL_NOTIFICATION = 'email-notification';
const ENERGY = 'energy';
+ const ENROLL = 'enroll';
const ENROLLED = 'enrolled';
const ENTER = 'enter';
const ERASER = 'eraser';
--- a/tutor/classes/Instructor.php
+++ b/tutor/classes/Instructor.php
@@ -117,6 +117,20 @@
}
/**
+ * Check if new instructor registration is allowed.
+ * Requires both WordPress user registration and Tutor become-instructor to be enabled.
+ *
+ * @since 4.2.2
+ *
+ * @return bool
+ */
+ public static function can_register_as_instructor(): bool {
+ $can_register = (bool) get_option( 'users_can_register', false ) && self::can_apply_for_instructor();
+
+ return apply_filters( 'tutor_can_register_as_instructor', $can_register );
+ }
+
+ /**
* Template Redirect Callback
* For Register new user and mark him as instructor
*
@@ -125,7 +139,7 @@
*/
public function register_instructor() {
// Here tutor_action checking required before nonce checking.
- if ( 'tutor_register_instructor' !== Input::post( 'tutor_action' ) || ! get_option( 'users_can_register', false ) ) {
+ if ( 'tutor_register_instructor' !== Input::post( 'tutor_action' ) || ! self::can_register_as_instructor() ) {
return;
}
@@ -160,6 +174,7 @@
}
}
+ //phpcs:ignore WordPress.Security.NonceVerification.Missing
$validate_consent = LegalConsent::validate_consent( LegalConsent::DISPLAY_ON_INS_REG, $_POST );
if ( is_wp_error( $validate_consent ) ) {
$validation_errors[ $validate_consent->get_error_code() ] = $validate_consent->get_error_message();
@@ -169,7 +184,12 @@
$validation_errors['email'] = __( 'Valid E-Mail is required', 'tutor' );
}
- if ( tutor_utils()->input_old( 'password' ) !== tutor_utils()->input_old( 'password_confirmation' ) ) {
+ // phpcs:disable -- Passwords are unslashed and not sanitized, as sanitization may alter valid password characters. Ex: ab<c%41 to ab<c
+ $password = wp_unslash( $_POST['password'] ?? '' );
+ $password_confirmation = wp_unslash( $_POST['password_confirmation'] ?? '' );
+ // phpcs:enable
+
+ if ( $password !== $password_confirmation ) {
$validation_errors['password_confirmation'] = __( 'Your passwords should match each other. Please recheck.', 'tutor' );
}
@@ -183,7 +203,6 @@
$last_name = sanitize_text_field( wp_strip_all_tags( wp_specialchars_decode( tutor_utils()->input_old( 'last_name' ), ENT_QUOTES ) ) );
$email = sanitize_text_field( tutor_utils()->input_old( 'email' ) );
$user_login = sanitize_text_field( tutor_utils()->input_old( 'user_login' ) );
- $password = sanitize_text_field( tutor_utils()->input_old( 'password' ) );
$userdata = array(
'user_login' => $user_login,
@@ -197,6 +216,7 @@
$wpdb->query( 'START TRANSACTION' );
$user_id = wp_insert_user( $userdata );
if ( is_wp_error( $user_id ) ) {
+ $wpdb->query( 'ROLLBACK' );
$this->error_msgs = $user_id->get_error_messages();
add_filter( 'tutor_instructor_register_validation_errors', array( $this, 'tutor_instructor_form_validation_errors' ) );
return;
@@ -206,13 +226,13 @@
$is_req_email_verification = apply_filters( 'tutor_require_email_verification', false );
if ( $is_req_email_verification ) {
- do_action( 'tutor_send_verification_mail', get_userdata( $user_id ), 'instructor-registration' );
$reg_done = apply_filters( 'tutor_registration_done', true );
if ( ! $reg_done ) {
$wpdb->query( 'ROLLBACK' );
return;
} else {
$wpdb->query( 'COMMIT' );
+ do_action( 'tutor_send_verification_mail', get_userdata( $user_id ), 'instructor-registration' );
}
} else {
/**
@@ -281,7 +301,7 @@
die( esc_html__( 'Permission denied', 'tutor' ) );
}
- wp_redirect( tutor_utils()->input_old( '_wp_http_referer' ) );
+ wp_safe_redirect( tutor_utils()->input_old( '_wp_http_referer' ) );
die();
}
@@ -322,7 +342,13 @@
if ( ! filter_var( tutor_utils()->input_old( 'email' ), FILTER_VALIDATE_EMAIL ) ) {
$validation_errors['email'] = __( 'Valid E-Mail is required', 'tutor' );
}
- if ( tutor_utils()->input_old( 'password' ) !== tutor_utils()->input_old( 'password_confirmation' ) ) {
+
+ // phpcs:disable -- Passwords are unslashed and not sanitized, as sanitization may alter valid password characters. Ex: ab<c%41 to ab<c
+ $password = wp_unslash( $_POST['password'] ?? '' );
+ $password_confirmation = wp_unslash( $_POST['password_confirmation'] ?? '' );
+ // phpcs:enable
+
+ if ( $password !== $password_confirmation ) {
$validation_errors['password_confirmation'] = __( 'Your passwords should match each other. Please recheck.', 'tutor' );
}
@@ -335,7 +361,6 @@
$email = sanitize_text_field( tutor_utils()->input_old( 'email' ) );
$user_login = sanitize_text_field( tutor_utils()->input_old( 'user_login' ) );
$phone_number = sanitize_text_field( tutor_utils()->input_old( 'phone_number' ) );
- $password = sanitize_text_field( tutor_utils()->input_old( 'password' ) );
$tutor_profile_bio = Input::post( 'tutor_profile_bio', '', Input::TYPE_KSES_POST );
$tutor_profile_job_title = sanitize_text_field( wp_strip_all_tags( wp_specialchars_decode( tutor_utils()->input_old( 'tutor_profile_job_title' ), ENT_QUOTES ) ) );
@@ -759,8 +784,8 @@
$instructor_course_ids
);
- // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
$row = $wpdb->get_row(
+ // phpcs:ignore -- sql are safely prepared.
$wpdb->prepare( $sql, $prepare_args ),
ARRAY_A
);
--- a/tutor/classes/Instructors_List.php
+++ b/tutor/classes/Instructors_List.php
@@ -174,9 +174,9 @@
do_action( 'tutor_after_instructor_delete', $bulk_ids );
}
- $message = 'Instructor status updated';
+ $message = __( 'Instructor status updated', 'tutor' );
- return true === $response ? wp_send_json_success( array( 'status' => $message ) ) : wp_send_json_error();
+ return true === $response ? wp_send_json_success( array( 'message' => $message ) ) : wp_send_json_error();
}
/**
@@ -423,6 +423,7 @@
{$order_clause}
LIMIT %d, %d;
";
+
$result = TutorCache::get( self::INSTRUCTOR_LIST_CACHE_KEY );
if ( false === $result ) {
TutorCache::set(
--- a/tutor/classes/Lesson.php
+++ b/tutor/classes/Lesson.php
@@ -272,7 +272,7 @@
$this->response_bad_request( __( 'Invalid comment ID', 'tutor' ) );
}
- $comment_content = Input::post( 'comment', '', Input::TYPE_KSES_POST );
+ $comment_content = wp_kses( Input::post( 'comment', '', Input::TYPE_TEXTAREA ), array() );
$user_id = get_current_user_id();
$lesson_id = $comment->comment_post_ID;
@@ -875,7 +875,7 @@
<div class="tutor-actual-comment tutor-mb-12">
<div class="tutor-comment-author">
<span class="tutor-fs-6 tutor-fw-bold">
- <?php echo esc_html( $reply->comment_author ); ?>
+ <?php echo esc_html( tutor_utils()->display_name( $reply->user_id ) ); ?>
</span>
<span class="tutor-fs-7 tutor-ml-0 tutor-ml-sm-10">
<?php echo esc_html( human_time_diff( strtotime( $reply->comment_date ), tutor_time() ) . __( ' ago', 'tutor' ) ); ?>
@@ -947,6 +947,11 @@
'comment_agent' => 'Tutor',
);
$comment_data = wp_parse_args( $request, $default_data );
+
+ if ( ! empty( $comment_data['comment_content'] ) ) {
+ $comment_data['comment_content'] = wp_kses( $comment_data['comment_content'], array() );
+ }
+
return wp_insert_comment( $comment_data );
}
--- a/tutor/classes/Permalink.php
+++ b/tutor/classes/Permalink.php
@@ -10,9 +10,7 @@
namespace TUTOR;
-if ( ! defined( 'ABSPATH' ) ) {
- exit;
-}
+defined( 'ABSPATH' ) || exit;
/**
* Permalink Class
--- a/tutor/classes/Post_types.php
+++ b/tutor/classes/Post_types.php
@@ -87,6 +87,8 @@
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 );
+
+ add_filter( 'map_meta_cap', array( $this, 'enforce_content_ownership' ), 10, 4 );
}
/**
@@ -513,10 +515,29 @@
'public' => false,
'publicly_queryable' => false,
'show_ui' => false,
+ 'show_in_rest' => false,
'query_var' => false,
'has_archive' => false,
'hierarchical' => false,
'menu_position' => null,
+ 'capability_type' => 'tutor_enrolled',
+ 'map_meta_cap' => true,
+ 'capabilities' => array(
+ 'edit_post' => 'edit_tutor_enrolled',
+ 'read_post' => 'read_tutor_enrolled',
+ 'delete_post' => 'delete_tutor_enrolled',
+ 'edit_posts' => 'manage_tutor',
+ 'edit_others_posts' => 'manage_tutor',
+ 'publish_posts' => 'manage_tutor',
+ 'read_private_posts' => 'manage_tutor',
+ 'create_posts' => 'manage_tutor',
+ 'delete_posts' => 'manage_tutor',
+ 'delete_others_posts' => 'manage_tutor',
+ 'delete_private_posts' => 'manage_tutor',
+ 'delete_published_posts' => 'manage_tutor',
+ 'edit_published_posts' => 'manage_tutor',
+ 'edit_private_posts' => 'manage_tutor',
+ ),
);
register_post_type( tutor()->enrollment_post_type, $args );
}
@@ -691,4 +712,79 @@
return $this->can_view_protected_content( $post ) ? $excerpt : '';
}
+
+ /**
+ * Enforce course-level ownership for lessons, quizzes and assignments.
+ *
+ * These post types have `map_meta_cap` disabled because Tutor LMS manages
+ * permissions through its own course-instructor relationships. Enabling
+ * `map_meta_cap` would make WordPress rely on post-author ownership, which
+ * does not account for co-instructors who are not the post author.
+ *
+ * Use this filter to enforce Tutor LMS ownership checks while preserving
+ * existing capabilities for authorized users.
+ *
+ * Also protects content without an associated course by allowing only
+ * the original post author to manage it.
+ *
+ * @since 4.2.2
+ *
+ * @param string[] $caps Primitive capabilities required.
+ * @param string $cap Capability being checked.
+ * @param int $user_id User ID.
+ * @param array $args Additional arguments; $args[0] is the post ID.
+ *
+ * @return string[] Required capabilities.
+ */
+ public function enforce_content_ownership( $caps, $cap, $user_id, $args ) {
+ if ( ! isset( $args[0] ) || ! is_numeric( $args[0] ) ) {
+ return $caps;
+ }
+
+ $post = get_post( (int) $args[0] );
+ if ( ! $post ) {
+ return $caps;
+ }
+
+ $content_types = array(
+ tutor()->lesson_post_type => 'lesson',
+ tutor()->quiz_post_type => 'quiz',
+ tutor()->assignment_post_type => 'assignment',
+ );
+
+ if ( ! isset( $content_types[ $post->post_type ] ) ) {
+ return $caps;
+ }
+
+ $pto = get_post_type_object( $post->post_type );
+ if ( ! $pto ) {
+ return $caps;
+ }
+
+ $guarded_caps = array(
+ 'edit_post',
+ 'delete_post',
+ $pto->cap->edit_post,
+ $pto->cap->delete_post,
+ );
+
+ if ( ! in_array( $cap, array_unique( $guarded_caps ), true ) ) {
+ return $caps;
+ }
+
+ $user_id = (int) $user_id;
+
+ if ( User::is_admin( $user_id ) ) {
+ return $caps;
+ }
+
+ $content_type = $content_types[ $post->post_type ];
+ $course_id = (int) tutor_utils()->get_course_id_by( $content_type, $post->ID );
+
+ $is_owner = $course_id
+ ? tutor_utils()->can_user_manage( $content_type, $post->ID, $user_id, false )
+ : (int) $post->post_author === $user_id;
+
+ return $is_owner ? $caps : array( 'do_not_allow' );
+ }
}
--- a/tutor/classes/Private_Course_Access.php
+++ b/tutor/classes/Private_Course_Access.php
@@ -10,14 +10,12 @@
namespace TUTOR;
+defined( 'ABSPATH' ) || exit;
+
use TutorCacheTutorCache;
use TutorModelsCourseModel;
use TutorModelsEnrollmentModel;
-if ( ! defined( 'ABSPATH' ) ) {
- exit;
-}
-
/**
* Register Tutor's post types
*
--- a/tutor/classes/Question_Answers_List.php
+++ b/tutor/classes/Question_Answers_List.php
@@ -10,11 +10,9 @@
namespace TUTOR;
-use TutorCoreInput;
+defined( 'ABSPATH' ) || exit;
-if ( ! defined( 'ABSPATH' ) ) {
- exit;
-}
+use TutorCoreInput;
/**
* Question_Answers_List
--- a/tutor/classes/Quiz.php
+++ b/tutor/classes/Quiz.php
@@ -652,6 +652,50 @@
}
/**
+ * Check if the quiz has questions that can be attempted in the current learning mode.
+ *
+ * @since 4.2.2
+ *
+ * @param int $quiz_id Quiz ID.
+ *
+ * @return bool
+ */
+ public static function has_supported_questions( $quiz_id ) {
+ return tutor_utils()->count( tutor_utils()->get_questions_by_quiz( $quiz_id ) ) > 0;
+ }
+
+ /**
+ * Message displayed when a quiz cannot be attempted.
+ *
+ * @since 4.2.2
+ *
+ * @return string
+ */
+ public static function unavailable_quiz_message() {
+ return __( 'This quiz is currently unavailable. Please contact the site administrator.', 'tutor' );
+ }
+
+ /**
+ * Render notice when a quiz cannot be attempted.
+ *
+ * @since 4.2.2
+ *
+ * @param string $class Additional CSS classes.
+ *
+ * @return void
+ */
+ public static function render_unavailable_quiz_notice( $class = '' ) {
+ ?>
+ <div class="tutor-alert tutor-warning <?php echo esc_attr( $class ); ?>">
+ <div class="tutor-alert-text">
+ <span class="tutor-icon-circle-info tutor-alert-icon tutor-mr-12" aria-hidden="true"></span>
+ <span><?php echo esc_html( self::unavailable_quiz_message() ); ?></span>
+ </div>
+ </div>
+ <?php
+ }
+
+ /**
* Start Quiz from here...
*
* @since 1.0.0
@@ -680,6 +724,10 @@
// Check & die if don't have quiz access.
QuizModel::has_quiz_access( $quiz_id, $course->id );
+ if ( ! self::has_supported_questions( $quiz_id ) ) {
+ wp_die( esc_html( self::unavailable_quiz_message() ) );
+ }
+
self::quiz_attempt( $course->ID, $quiz_id, $user_id );
wp_safe_redirect( get_permalink( $quiz_id ) );
die();
@@ -795,6 +843,7 @@
}
tutor_utils()->checking_nonce();
+
// submit quiz attempts.
if ( self::tutor_quiz_attempt_submit() ) {
wp_send_json_success();
@@ -843,6 +892,17 @@
$attempt = self::validate_attempt( $attempt_id, $user_id );
if ( ! $attempt ) {
+ $quiz_id = Input::post( 'quiz_id', 0, Input::TYPE_INT );
+ if ( $quiz_id ) {
+ $started = tutor_utils()->is_started_quiz( $quiz_id );
+ if ( is_object( $started ) && (int) $started->user_id === $user_id ) {
+ $attempt = $started;
+ $attempt_id = (int) $started->attempt_id;
+ }
+ }
+ }
+
+ if ( ! $attempt ) {
die( 'Operation not allowed, attempt not found or permission denied' );
}
@@ -883,6 +943,8 @@
do_action( 'tutor_quiz/attempt_analysing/before', $attempt_id );
// Single quiz can have multiple question. So multiple answer should be saved.
+ $attempt_info = null;
+
foreach ( $attempt_answers as $posted_attempt_id => $attempt_answer ) {
if ( (int) $posted_attempt_id !== (int) $attempt_id ) {
die( 'Operation not allowed, attempt mismatch' );
@@ -1141,12 +1203,24 @@
'attempt_status' => $review_required ? QuizModel::REVIEW_REQUIRED : QuizModel::ATTEMPT_ENDED,
'attempt_ended_at' => date( 'Y-m-d H:i:s', tutor_time() ), //phpcs:ignore
);
+ }
- $wpdb->update( $wpdb->tutor_quiz_attempts, $attempt_info, array( 'attempt_id' => $attempt_id ) );
+ // No answers posted, e.g. legacy mode rendered no supported question: end with existing stats.
+ if ( ! $attempt_info ) {
+ $stats = QuizModel::get_attempt_answers_stats( (int) $attempt_id );
- QuizModel::update_attempt_result( $attempt_id );
+ $attempt_info = array(
+ 'total_answered_questions' => (int) $stats->total_answered_count,
+ 'earned_marks' => max( 0.0, (float) $stats->total_earned_marks ),
+ 'attempt_status' => QuizModel::ATTEMPT_ENDED,
+ 'attempt_ended_at' => date( 'Y-m-d H:i:s', tutor_time() ), //phpcs:ignore
+ );
}
+ $wpdb->update( $wpdb->prefix . 'tutor_quiz_attempts', $attempt_info, array( 'attempt_id' => $attempt_id ) );
+
+ QuizModel::update_attempt_result( $attempt_id );
+
// After hook.
do_action( 'tutor_quiz/attempt_ended', $attempt_id, $course_id, $user_id );
}
--- a/tutor/classes/QuizBuilder.php
+++ b/tutor/classes/QuizBuilder.php
@@ -10,10 +10,9 @@
namespace TUTOR;
-if ( ! defined( 'ABSPATH' ) ) {
- exit;
-}
+defined( 'ABSPATH' ) || exit;
+use TutorCoreDB;
use TutorCoreInput;
use TutorHelpersHttpHelper;
use TutorHelpersQueryHelper;
@@ -21,7 +20,6 @@
use TutorModelsQuizModel;
use TutorTraitsJsonResponse;
use TUTOR_PROQuizImageStorage;
-use WP_Error;
/**
* Class QuizBuilder
@@ -29,6 +27,12 @@
* @since 1.0.0
*/
class QuizBuilder {
+ use JsonResponse;
+
+ const TRACKING_KEY = '_data_status';
+ const FLAG_NEW = 'new';
+ const FLAG_UPDATE = 'update';
+ const FLAG_NO_CHANGE = 'no_change';
/**
* Store question ids of current quiz.
@@ -49,6 +53,15 @@
private $current_quiz_answer_ids = null;
/**
+ * Store question to answer ids mapping of current quiz.
+ *
+ * @since 4.2.2
+ *
+ * @var array<int, array<int>>
+ */
+ private $current_quiz_question_answers_map = array();
+
+ /**
* Store current quiz details
*
* @since 4.0.5
@@ -57,13 +70,6 @@
*/
private $current_quiz = null;
- use JsonResponse;
-
- const TRACKING_KEY = '_data_status';
- const FLAG_NEW = 'new';
- const FLAG_UPDATE = 'update';
- const FLAG_NO_CHANGE = 'no_change';
-
/**
* Register hooks and dependencies.
*
@@ -178,16 +184,22 @@
// Update answer.
if ( self::FLAG_UPDATE === $data_status ) {
- $answer_id = $answer['answer_id'];
+ $answer_id = (int) $answer['answer_id'];
$old_mask = '';
if ( $this->is_mask_image_question_type( $question_type ) ) {
- $old_answer = QueryHelper::get_row( $answers_table, array( 'answer_id' => (int) $answer_id ), 'answer_id' );
+ $old_answer = DB::table( 'tutor_quiz_question_answers' )
+ ->where( 'answer_id', $answer_id )
+ ->where( 'belongs_question_id', (int) $question_id )
+ ->first();
$old_mask = is_object( $old_answer ) ? (string) ( $old_answer->answer_two_gap_match ?? '' ) : '';
}
$wpdb->update(
$answers_table,
$answer_data,
- array( 'answer_id' => $answer_id )
+ array(
+ 'answer_id' => $answer_id,
+ 'belongs_question_id' => (int) $question_id,
+ )
);
if ( $this->is_mask_image_question_type( $question_type ) ) {
$new_mask = (string) ( $answer_data['answer_two_gap_match'] ?? '' );
@@ -196,7 +208,7 @@
}
if ( self::FLAG_NO_CHANGE === $data_status ) {
- $answer_id = $answer['answer_id'];
+ $answer_id = (int) $answer['answer_id'];
}
// Save sort order.
@@ -204,7 +216,10 @@
$wpdb->update(
$answers_table,
array( 'answer_order' => $answer_order ),
- array( 'answer_id' => $answer_id )
+ array(
+ 'answer_id' => $answer_id,
+ 'belongs_question_id' => (int) $question_id,
+ )
);
}
}
@@ -331,7 +346,18 @@
}
if ( self::FLAG_NO_CHANGE === $data_status ) {
- $question_id = $question['question_id'];
+ $question_id = (int) $question['question_id'];
+ }
+
+ // Verify existing question belongs to this quiz before updating order or saving answers.
+ if ( self::FLAG_NEW !== $data_status ) {
+ $belongs = DB::table( 'tutor_quiz_questions' )
+ ->where( 'question_id', $question_id )
+ ->where( 'quiz_id', $quiz_id )
+ ->exists();
+ if ( ! $belongs ) {
+ continue;
+ }
}
// Save sort order.
@@ -369,7 +395,7 @@
$errors['payload'] = __( 'Invalid payload', 'tutor' );
}
- $quiz_id = (int) $payload['ID'] ?? 0;
+ $quiz_id = (int) ( $payload['ID'] ?? 0 );
$questions = $payload['questions'] ?? array();
$quiz = get_post( $quiz_id );
@@ -378,7 +404,7 @@
$errors['ID'][] = __( 'Invalid quiz id provided', 'tutor' );
}
- if ( $quiz && ! current_user_can( 'edit_post', $quiz_id ) ) {
+ if ( $quiz && ! tutor_utils()->can_user_manage( 'quiz', $quiz_id ) ) {
$success = false;
$errors['permission'][] = __( 'You do not have permission to edit this quiz', 'tutor' );
}
@@ -903,30 +929,31 @@
* @return void
*/
private function set_current_quiz_questions_answer_ids( int $quiz_id ) {
- if ( ! $quiz_id ) {
+ $this->current_quiz = null;
+ $this->current_quiz_question_ids = array();
+ $this->current_quiz_answer_ids = array();
+ $this->current_quiz_question_answers_map = array();
+
+ $quiz_details = $quiz_id ? QuizModel::get_quiz_details( $quiz_id ) : null;
+ if ( ! $quiz_details ) {
return;
}
- if ( is_null( $this->current_quiz ) ) {
- $quiz_details = QuizModel::get_quiz_details( $quiz_id );
- if ( $quiz_details ) {
- $this->current_quiz = $quiz_details;
- }
- }
+ $this->current_quiz = $quiz_details;
+ $questions = is_array( $quiz_details->questions ?? null ) ? $quiz_details->questions : array();
- if ( is_null( $this->current_quiz_question_ids ) && $this->current_quiz ) {
- $questions = $this->current_quiz->questions;
- if ( $questions ) {
- $this->current_quiz_question_ids = wp_list_pluck( $questions, 'question_id' );
- }
+ // Build the map first: question id => answer ids.
+ foreach ( $questions as $question ) {
+ $answers = is_array( $question->question_answers ?? null ) ? $question->question_answers : array();
+
+ $this->current_quiz_question_answers_map[ (int) $question->question_id ] = array_map( 'intval', wp_list_pluck( $answers, 'answer_id' ) );
}
- if ( is_null( $this->current_quiz_answer_ids ) && $this->current_quiz ) {
- $quiz_details = $this->current_quiz->questions;
+ // Derive the flat lists from the map.
+ $map = $this->current_quiz_question_answers_map;
- $quiz_question_answer = wp_list_pluck( $quiz_details, 'question_answers' );
- $this->current_quiz_answer_ids = wp_list_pluck( array_merge( ...$quiz_question_answer ), 'answer_id' );
- }
+ $this->current_quiz_question_ids = array_keys( $map );
+ $this->current_quiz_answer_ids = array_values( array_unique( array_merge( array(), ...array_values( $map ) ) ) );
}
/**
@@ -941,41 +968,60 @@
* @return bool true True if everything is fine
*/
public function is_valid_quiz_question_answer_payload( array $payload ): bool {
- $payload_question_ids = wp_list_pluck( $payload, 'question_id' );
- $payload_question_answers = wp_list_pluck( $payload, 'question_answers', 'question_id' );
+ $valid_question_ids = is_array( $this->current_quiz_question_ids ) ? $this->current_quiz_question_ids : array();
+ $valid_answer_ids = is_array( $this->current_quiz_answer_ids ) ? $this->current_quiz_answer_ids : array();
+ $is_new_quiz = is_null( $this->current_quiz );
- $is_cb_question = array();
foreach ( $payload as $question ) {
- if ( isset( $question['question_id'] ) ) {
- $is_cb_question[ $question['question_id'] ] = ! empty( $question['is_cb_question'] );
- }
- }
-
- // Remove content bank answers.
- $payload_question_answers = array_filter( $payload_question_answers, fn( $question_id ) => empty( $is_cb_question[ $question_id ] ), ARRAY_FILTER_USE_KEY );
- $payload_question_answers = array_filter( array_values( $payload_question_answers ) ); // Filter out empty array.
- $payload_answer_ids = wp_list_pluck( array_merge( ...$payload_question_answers ), 'answer_id' );
+ $answers = $question['question_answers'] ?? array();
- // Remove the hash id.
- $payload_question_ids = array_filter( $payload_question_ids, fn( $id ) => is_numeric( $id ) && empty( $is_cb_question[ $id ] ) );
- $payload_answer_ids = array_filter( $payload_answer_ids, fn( $id ) => is_numeric( $id ) );
+ /**
+ * For a new quiz, current_quiz is null.
+ * There should not be any existing question or answer updates.
+ *
+ * @since 4.2.2
+ */
+ if ( $is_new_quiz ) {
+ foreach ( array_merge( array( $question ), $answers ) as $item ) {
+ if ( self::FLAG_NEW !== ( $item[ self::TRACKING_KEY ] ?? self::FLAG_NEW ) ) {
+ throw new Exception( esc_html__( 'Invalid question or answer id found', 'tutor' ), 1 );
+ }
+ }
+ continue;
+ }
- // For the new quiz current_quiz is null, in this there should not be any numeric question or answer id.
- if ( is_null( $this->current_quiz ) && ( count( $payload_question_ids ) || count( $payload_answer_ids ) ) ) {
- throw new Exception( esc_html__( 'Invalid question or answer id found', 'tutor' ), 1 );
- }
+ // New question: all of its answers must be new too.
+ if ( self::FLAG_NEW === ( $question[ self::TRACKING_KEY ] ?? self::FLAG_NO_CHANGE ) ) {
+ foreach ( $answers as $answer ) {
+ if ( self::FLAG_NEW !== ( $answer[ self::TRACKING_KEY ] ?? self::FLAG_NO_CHANGE ) ) {
+ throw new Exception( esc_html__( 'Invalid answer id found', 'tutor' ), 1 );
+ }
+ }
+ continue;
+ }
- if ( $this->current_quiz_question_ids ) {
- $has_question_diff = array_diff( $payload_question_ids, $this->current_quiz_question_ids );
- if ( $has_question_diff ) {
+ // Existing question: it must belong to the target quiz.
+ $q_id = $question['question_id'] ?? null;
+ if ( ! is_numeric( $q_id ) || ! in_array( (int) $q_id, $valid_question_ids, true ) ) {
throw new Exception( esc_html__( 'Invalid question id found', 'tutor' ), 1 );
}
- }
- if ( $this->current_quiz_answer_ids ) {
- $has_answer_diff = array_diff( $payload_answer_ids, $this->current_quiz_answer_ids );
- if ( $has_answer_diff ) {
- throw new Exception( esc_html__( 'Invalid answer id found', 'tutor' ), 1 );
+ // Existing answers must belong to this question. New answers are allowed.
+ $allowed_q_answers = $this->current_quiz_question_answers_map[ (int) $q_id ] ?? array();
+
+ foreach ( $answers as $answer ) {
+ if ( self::FLAG_NEW === ( $answer[ self::TRACKING_KEY ] ?? self::FLAG_NO_CHANGE ) ) {
+ continue;
+ }
+
+ $a_id = $answer['answer_id'] ?? null;
+ if (
+ ! is_numeric( $a_id )
+ || ! in_array( (int) $a_id, $valid_answer_ids, true )
+ || ! in_array( (int) $a_id, $allowed_q_answers, true )
+ ) {
+ throw new Exception( esc_html__( 'Invalid answer id found', 'tutor' ), 1 );
+ }
}
}
--- a/tutor/classes/Quiz_Attempts_List.php
+++ b/tutor/classes/Quiz_Attempts_List.php
@@ -10,9 +10,7 @@
namespace TUTOR;
-if ( ! defined( 'ABSPATH' ) ) {
- exit;
-}
+defined( 'ABSPATH' ) || exit;
use TUTORUser;
use TutorCacheQuizAttempts;
@@ -672,14 +670,20 @@
$static_items = array(
'correct' => array(
'class' => 'correct',
- /* translators: %1$s: number of correct answers, wrapped in markup. */
- 'label' => $format_count_label( $answer_counts['correct'], __( '%1$s correct', 'tutor' ) ),
+ 'label' => $format_count_label(
+ $answer_counts['correct'],
+ /* translators: %1$s: number of correct answers, wrapped in markup. */
+ _n( '%1$s correct', '%1$s correct', $answer_counts['correct'], 'tutor' )
+ ),
'count' => (int) $answer_counts['correct'],
),
'incorrect' => array(
'class' => 'incorrect',
- /* translators: %1$s: number of incorrect answers, wrapped in markup. */
- 'label' => $format_count_label( $answer_counts['incorrect'], __( '%1$s incorrect', 'tutor' ) ),
+ 'label' => $format_count_label(
+ $answer_counts['incorrect'],
+ /* translators: %1$s: number of incorrect answers, wrapped in markup. */
+ _n( '%1$s incorrect', '%1$s incorrect', $answer_counts['incorrect'], 'tutor' )
+ ),
'count' => (int) $answer_counts['incorrect'],
),
'total' => array(
@@ -735,7 +739,7 @@
} elseif ( QuizModel::RESULT_PENDING === $attempt['result'] ) {
Badge::make()->label( __( 'Pending', 'tutor' ) )->variant( Badge::WARNING )->rounded()->render();
} else {
- Badge::make()->label( 'Failed' )->variant( Badge::ERROR )->rounded()->render();
+ Badge::make()->label( __( 'Failed', 'tutor' ) )->variant( Badge::ERROR )->rounded()->render();
}
}
--- a/tutor/classes/RestAPI.php
+++ b/tutor/classes/RestAPI.php
@@ -10,11 +10,9 @@
namespace TUTOR;
-use TutorHelpersHttpHelper;
+defined( 'ABSPATH' ) || exit;
-if ( ! defined( 'ABSPATH' ) ) {
-