Below is a differential between the unpatched vulnerable code and the patched update, for reference.
--- a/learnpress/inc/Ajax/AI/AIAssistantAjax.php
+++ b/learnpress/inc/Ajax/AI/AIAssistantAjax.php
@@ -26,6 +26,14 @@
* @since 4.3.5
*/
class AIAssistantAjax extends AbstractAjax {
+ /**
+ * Methods allowed to call via 'lp-load-ajax'.
+ *
+ * @var string[]
+ */
+ protected static $actions = [
+ 'openai_assistant_chat',
+ ];
/**
* Handle assistant chat request from a logged-in learner.
--- a/learnpress/inc/Ajax/AI/OpenAiAjax.php
+++ b/learnpress/inc/Ajax/AI/OpenAiAjax.php
@@ -32,6 +32,21 @@
*/
class OpenAiAjax extends AbstractAjax {
/**
+ * Methods allowed to call via 'lp-load-ajax'.
+ *
+ * @var string[]
+ */
+ protected static $actions = [
+ 'openai_generate_prompt_course',
+ 'openai_generate_data_course',
+ 'openai_create_course',
+ 'openai_generate_prompt',
+ 'openai_generate_data',
+ 'openai_generate_image',
+ 'openai_apply_image_feature',
+ ];
+
+ /**
* Generate prompt course with AI
*/
public function openai_generate_prompt_course() {
@@ -47,6 +62,7 @@
$data_str = LP_Request::get_param( 'data' );
$params = LP_Helper::json_decode( $data_str, true );
$prompt = Config::instance()->get( 'prompt-create-course', 'settings/openAi', compact( 'params' ) );
+ $prompt = apply_filters( 'lp-openai-prompt-create-course', $prompt, $params );
$response->data = $prompt;
$response->status = 'success';
@@ -261,6 +277,8 @@
break;
}
+ $prompt = apply_filters( 'lp-openai-prompt-generated', $prompt, $params, $lp_prompt_type );
+
$response->data = $prompt;
$response->status = 'success';
$response->message = __( 'Generate prompt successfully!', 'learnpress' );
--- a/learnpress/inc/Ajax/AbstractAjax.php
+++ b/learnpress/inc/Ajax/AbstractAjax.php
@@ -8,6 +8,7 @@
namespace LearnPressAjax;
+use LearnPressHelpersResponse;
use LP_Request;
/**
@@ -17,16 +18,43 @@
* Because not specify a specific class.
*/
abstract class AbstractAjax {
+ /**
+ * Methods allowed to call via param 'lp-load-ajax'.
+ * Empty: any public method is allowed (backward compatible for addons not declared yet).
+ *
+ * @var string[]
+ * @since 4.5.1
+ */
+ protected static $actions = [];
+
+ /**
+ * Nonce action of class (besides the general 'wp_rest'), required for all actions of class.
+ * Empty: not required.
+ * Nonce must be printed only in HTML of page use it (not in LP_Assets, not in HTML return via AJAX),
+ * JS sends it via field 'lp_action_nonce' of 'data'.
+ * So a JS on another page (ex: post content) can't call these actions, even if user has permission.
+ *
+ * @var string
+ * @since 4.5.1
+ */
+ protected static $action_nonce = '';
+
+ /**
+ * Field name of 'data' contains nonce of action.
+ */
+ const FIELD_ACTION_NONCE = 'lp_action_nonce';
+
public static function catch_lp_ajax() {
if ( ! empty( $_REQUEST['lp-load-ajax'] ) ) {
$action = LP_Request::get_param( 'lp-load-ajax' );
$nonce = LP_Request::get_param( 'nonce' );
- $class = new static();
- if ( ! method_exists( $class, $action ) ) {
+ if ( ! static::is_action_allowed( $action ) ) {
return;
}
+ $class = new static();
+
/**
* For case cache HTML, nonce of guest is cached (expired), so is not required.
* Only apply for guest: nonce of guest is public, not protect anything.
@@ -46,9 +74,86 @@
}
}
+ if ( ! static::verify_action_nonce() ) {
+ $response = new Response();
+ $response->message = __(
+ 'Your session has expired, please reload the page and try again.',
+ 'learnpress'
+ );
+ wp_send_json( $response );
+ return;
+ }
+
if ( is_callable( [ $class, $action ] ) ) {
call_user_func( [ $class, $action ] );
}
}
}
+
+ /**
+ * Create nonce of class to print in HTML of page use it.
+ *
+ * @return string empty if class not declare $action_nonce.
+ * @since 4.5.1
+ */
+ public static function create_action_nonce(): string {
+ if ( empty( static::$action_nonce ) ) {
+ return '';
+ }
+
+ return wp_create_nonce( static::$action_nonce );
+ }
+
+ /**
+ * Verify nonce of class sent via field 'lp_action_nonce' of 'data', if class declares $action_nonce.
+ *
+ * @return bool
+ * @since 4.5.1
+ */
+ public static function verify_action_nonce(): bool {
+ if ( empty( static::$action_nonce ) ) {
+ return true;
+ }
+
+ $data = LP_Request::get_param( 'data', '', 'trim' );
+ $params = is_string( $data ) ? json_decode( $data, true ) : null;
+ $nonce = is_array( $params ) ? ( $params[ self::FIELD_ACTION_NONCE ] ?? '' ) : '';
+ if ( ! is_string( $nonce ) || '' === $nonce ) {
+ return false;
+ }
+
+ return false !== wp_verify_nonce( sanitize_text_field( $nonce ), static::$action_nonce );
+ }
+
+ /**
+ * Check action can call via 'lp-load-ajax'.
+ *
+ * @param mixed $action
+ *
+ * @return bool
+ * @since 4.5.1
+ */
+ public static function is_action_allowed( $action ): bool {
+ if ( ! is_string( $action ) || '' === $action ) {
+ return false;
+ }
+
+ if ( ! empty( static::$actions ) ) {
+ return in_array( $action, static::$actions, true );
+ }
+
+ // Methods of dispatcher must never call via request (ex: catch_lp_ajax call itself is infinite recursion).
+ $methods_dispatcher = [
+ 'catch_lp_ajax',
+ 'is_action_allowed',
+ 'create_action_nonce',
+ 'verify_action_nonce',
+ '__construct',
+ ];
+ if ( in_array( strtolower( $action ), $methods_dispatcher, true ) ) {
+ return false;
+ }
+
+ return method_exists( static::class, $action );
+ }
}
--- a/learnpress/inc/Ajax/AddonsAjax.php
+++ b/learnpress/inc/Ajax/AddonsAjax.php
@@ -6,7 +6,7 @@
* via the LearnPress AJAX dispatcher.
*
* @since 4.4.7
- * @version 1.0.0
+ * @version 1.0.1
*/
namespace LearnPressAjax;
@@ -29,6 +29,20 @@
*/
class AddonsAjax extends AbstractAjax {
/**
+ * Methods allowed to call via 'lp-load-ajax'.
+ *
+ * @var string[]
+ */
+ protected static $actions = [
+ 'addon_action',
+ ];
+
+ /**
+ * Nonce action for addon_action, only print on LearnPress Add-ons page.
+ */
+ const NONCE_ACTION = 'lp_addon_action';
+
+ /**
* @var AddonService
*/
private $addon_service;
@@ -45,7 +59,7 @@
*
* @return void
* @since 4.4.9
- * @version 1.0.3
+ * @version 1.0.4
*/
public function addon_action() {
$response = new Response();
@@ -64,16 +78,32 @@
throw new Exception( __( 'Params is invalid!', 'learnpress' ) );
}
+ // Security: require nonce for this action, the general nonce 'wp_rest' is not enough.
+ if ( ! wp_verify_nonce(
+ sanitize_text_field( $params['nonce_addon_action'] ?? '' ),
+ self::NONCE_ACTION
+ ) ) {
+ throw new Exception( __( 'Invalid request!', 'learnpress' ) );
+ }
+
$action = sanitize_key( $params['action_type'] ?? '' );
if ( empty( $action ) ) {
throw new Exception( __( 'Action is invalid!', 'learnpress' ) );
}
- $addon = $params['addon'] ?? [];
- if ( empty( $addon ) || ! is_array( $addon ) ) {
+ $addon_request = $params['addon'] ?? [];
+ if ( empty( $addon_request ) || ! is_array( $addon_request ) ) {
throw new Exception( __( 'Params is invalid!', 'learnpress' ) );
}
+ // Security: only accept add-on from LearnPress add-ons list (server side), not data from request.
+ $addon = $this->addon_service->get_addon_by_slug(
+ sanitize_key( $addon_request['slug'] ?? '' )
+ );
+ if ( empty( $addon ) ) {
+ throw new Exception( __( 'Add-on is invalid!', 'learnpress' ) );
+ }
+
$purchase_code = sanitize_text_field( $params['purchase_code'] ?? '' );
switch ( $action ) {
@@ -162,6 +192,10 @@
);
break;
case 'deactivate':
+ if ( ! current_user_can( 'activate_plugins' ) ) {
+ throw new Exception( __( 'You do not have permission to deactivate plugins.', 'learnpress' ) );
+ }
+
$this->addon_service->deactivate( $addon );
$message = sprintf(
/* translators: %s: addon name */
--- a/learnpress/inc/Ajax/CourseBuilder/CBEditCourseAjax.php
+++ b/learnpress/inc/Ajax/CourseBuilder/CBEditCourseAjax.php
@@ -29,6 +29,16 @@
class CBEditCourseAjax extends AbstractAjax {
/**
+ * Methods allowed to call via 'lp-load-ajax'.
+ *
+ * @var string[]
+ */
+ protected static $actions = [
+ 'cb_save_course',
+ 'cb_quick_edit_save_course',
+ ];
+
+ /**
* Check permissions and validate parameters.
*
* @throws Exception
--- a/learnpress/inc/Ajax/CourseBuilder/CourseBuilderAjax.php
+++ b/learnpress/inc/Ajax/CourseBuilder/CourseBuilderAjax.php
@@ -40,6 +40,38 @@
class CourseBuilderAjax extends AbstractAjax {
/**
+ * Methods allowed to call via 'lp-load-ajax'.
+ *
+ * @var string[]
+ */
+ protected static $actions = [
+ 'save_courses',
+ 'save_course_settings',
+ 'duplicate_course',
+ 'move_trash_course',
+ 'add_course_category',
+ 'add_course_tag',
+ 'duplicate_lesson',
+ 'builder_update_lesson',
+ 'move_trash_lesson',
+ 'builder_update_quiz',
+ 'duplicate_quiz',
+ 'move_trash_quiz',
+ 'duplicate_question',
+ 'builder_update_question',
+ 'move_trash_question',
+ 'save_global_settings',
+ ];
+
+ /**
+ * Nonce required for all actions of class, see AbstractAjax::$action_nonce.
+ * Printed on wrapper of Course Builder page (CourseBuilderTemplate::layout).
+ *
+ * @var string
+ */
+ protected static $action_nonce = 'lp_course_builder_nonce';
+
+ /**
* Check permissions and validate parameters.
*
* @throws Exception
@@ -623,16 +655,41 @@
}
}
+ // Level must be one of the registered levels.
+ if ( isset( $data['_lp_level'] ) ) {
+ $level = sanitize_key( (string) $data['_lp_level'] );
+ if ( '' === $level || array_key_exists( $level, lp_course_level() ) ) {
+ $courseModel->meta_data->{CoursePostModel::META_KEY_LEVEL} = $level;
+ }
+ }
+
$simple_fields = [
'_lp_course_repurchase_option' => CoursePostModel::META_KEY_COURSE_REPURCHASE_OPTION,
- '_lp_level' => CoursePostModel::META_KEY_LEVEL,
'_lp_featured_review' => CoursePostModel::META_KEY_FEATURED_REVIEW,
- '_lp_external_link_buy_course' => CoursePostModel::META_KEY_EXTERNAL_LINK_BY_COURSE,
];
+ // External link must be a valid URL; never persist serialized payloads (PHP Object Injection).
+ if ( isset( $data['_lp_external_link_buy_course'] ) ) {
+ $external_link = trim( (string) $data['_lp_external_link_buy_course'] );
+ if ( '' === $external_link ) {
+ $courseModel->meta_data->{CoursePostModel::META_KEY_EXTERNAL_LINK_BY_COURSE} = '';
+ } elseif ( ! is_serialized( $external_link ) ) {
+ $external_link = esc_url_raw( $external_link, [ 'http', 'https' ] );
+ if ( '' !== $external_link ) {
+ $courseModel->meta_data->{CoursePostModel::META_KEY_EXTERNAL_LINK_BY_COURSE} = $external_link;
+ }
+ }
+ }
+
foreach ( $simple_fields as $key => $meta_key ) {
if ( isset( $data[ $key ] ) ) {
- $courseModel->meta_data->{$meta_key} = sanitize_text_field( $data[ $key ] );
+ $value = sanitize_text_field( (string) $data[ $key ] );
+ // Never persist PHP-serialized payloads (PHP Object Injection).
+ if ( is_serialized( $value ) ) {
+ continue;
+ }
+
+ $courseModel->meta_data->{$meta_key} = $value;
}
}
@@ -1234,11 +1291,7 @@
}*/
if ( $course_id ) {
- $courseModelCache = CourseModel::find( $course_id, true );
- if ( $courseModelCache ) {
- $courseModelCache->sections_items = null;
- $courseModelCache->save();
- }
+ $this->clean_course_curriculum_cache( (int) $course_id );
}
$response->message = __( 'Update lesson successfully', 'learnpress' );
@@ -1248,11 +1301,6 @@
$this->save_lesson_settings_to_model( $lesson_model, $data );
}
- // Remove lesson from curriculum if status is not public
- if ( ! empty( $target_status ) && $target_status !== 'publish' ) {
- $this->remove_course_item_from_curriculum( $lesson_id, $course_id );
- }
-
$response->status = 'success';
$response->data->status = $lesson_model->post_status;
$response->data->button_title = $lesson_model->post_status === 'publish' ?
@@ -1285,10 +1333,11 @@
if ( $course_id ) {
$courseModelForHtml = CourseModel::find( $course_id, true );
if ( $courseModelForHtml && $lesson_model_for_html ) {
- $item = new stdClass();
- $item->item_id = $lesson_id;
- $item->title = $lesson_model_for_html->post_title;
- $item->item_type = LP_LESSON_CPT;
+ $item = new stdClass();
+ $item->item_id = $lesson_id;
+ $item->title = $lesson_model_for_html->post_title;
+ $item->item_type = LP_LESSON_CPT;
+ $item->post_status = $lesson_model_for_html->post_status;
AdminEditCurriculumTemplate::instance()->context_data = [ 'is_course_builder' => true ];
$response->data->section_item_html = AdminEditCurriculumTemplate::instance()->html_section_item( $courseModelForHtml, $item );
}
@@ -1395,8 +1444,10 @@
$saved_lesson_status = $status;
}
- if ( $saved_lesson_status !== 'publish' ) {
+ if ( 'delete' === $status ) {
$this->remove_course_item_from_curriculum( $lesson_id, $course_id );
+ } elseif ( $course_id > 0 ) {
+ $this->clean_course_curriculum_cache( $course_id );
}
$response->data->status = $saved_lesson_status;
@@ -1613,11 +1664,7 @@
$quiz_model->save();
if ( $course_id ) {
- $courseModelCache = CourseModel::find( $course_id, true );
- if ( $courseModelCache ) {
- $courseModelCache->sections_items = null;
- $courseModelCache->save();
- }
+ $this->clean_course_curriculum_cache( (int) $course_id );
}
$response->message = __( 'Update quiz successfully', 'learnpress' );
@@ -1627,11 +1674,6 @@
$this->save_quiz_settings_to_model( $quiz_model, $data );
}
- // Remove quiz from curriculum if status is not public
- if ( $target_status !== 'publish' ) {
- $this->remove_course_item_from_curriculum( $quiz_id, $course_id );
- }
-
$response->status = 'success';
$response->data->status = $quiz_model->post_status;
$response->data->button_title = $quiz_model->post_status === 'publish' ?
@@ -1667,10 +1709,11 @@
if ( $course_id ) {
$courseModelForHtml = CourseModel::find( $course_id, true );
if ( $courseModelForHtml && $quiz_model_for_html ) {
- $item = new stdClass();
- $item->item_id = $quiz_id;
- $item->title = $quiz_model_for_html->post_title;
- $item->item_type = LP_QUIZ_CPT;
+ $item = new stdClass();
+ $item->item_id = $quiz_id;
+ $item->title = $quiz_model_for_html->post_title;
+ $item->item_type = LP_QUIZ_CPT;
+ $item->post_status = $quiz_model_for_html->post_status;
AdminEditCurriculumTemplate::instance()->context_data = [ 'is_course_builder' => true ];
$response->data->section_item_html = AdminEditCurriculumTemplate::instance()->html_section_item( $courseModelForHtml, $item );
}
@@ -1816,8 +1859,10 @@
$saved_quiz_status = $status;
}
- if ( $saved_quiz_status !== 'publish' ) {
+ if ( 'delete' === $status ) {
$this->remove_course_item_from_curriculum( $quiz_id, $course_id );
+ } elseif ( $course_id > 0 ) {
+ $this->clean_course_curriculum_cache( $course_id );
}
$response->data->status = $saved_quiz_status;
@@ -2159,8 +2204,10 @@
return;
}
- $courseModel->sections_items = null;
- $courseModel->total_items = null;
+ $courseModel->sections_items = null;
+ $courseModel->sections_items_edit = null;
+ $courseModel->total_items = null;
+ $courseModel->first_item_id = null;
$courseModel->save( true );
} catch ( Throwable $e ) {
error_log( __METHOD__ . ': ' . $e->getMessage() );
--- a/learnpress/inc/Ajax/CourseToolsAjax.php
+++ b/learnpress/inc/Ajax/CourseToolsAjax.php
@@ -32,6 +32,23 @@
*/
class CourseToolsAjax extends AbstractAjax {
/**
+ * Methods allowed to call via 'lp-load-ajax'.
+ *
+ * @var string[]
+ */
+ protected static $actions = [
+ 'reset_progress_courses',
+ 'reset_progress_items_course',
+ ];
+
+ /**
+ * Nonce required for all actions of class, see AbstractAjax::$action_nonce.
+ *
+ * @var string
+ */
+ protected static $action_nonce = 'lp_course_tools_nonce';
+
+ /**
* Register AJAX callbacks with the abstract dispatcher.
*
* @return void
--- a/learnpress/inc/Ajax/EditCurriculumAjax.php
+++ b/learnpress/inc/Ajax/EditCurriculumAjax.php
@@ -24,6 +24,24 @@
class EditCurriculumAjax extends AbstractAjax {
/**
+ * Methods allowed to call via 'lp-load-ajax'.
+ *
+ * @var string[]
+ */
+ protected static $actions = [
+ 'course_add_section',
+ 'course_update_section',
+ 'course_delete_section',
+ 'course_update_section_position',
+ 'create_item_add_to_section',
+ 'add_items_to_section',
+ 'delete_item_from_section',
+ 'update_item_section_and_position',
+ 'update_item_of_section',
+ 'update_item_preview',
+ ];
+
+ /**
* Check permissions and validate parameters.
*
* @throws Exception
@@ -230,7 +248,9 @@
*/
$itemModel = $courseModel->get_item_model(
$courseSectionItemModel->item_id,
- $courseSectionItemModel->item_type
+ $courseSectionItemModel->item_type,
+ true,
+ true
);
$response->data->item_link = $itemModel ? $itemModel->get_edit_link() : '';
@@ -290,7 +310,9 @@
$courseSectionItemAlias = (object) get_object_vars( $courseSectionItem );
$itemModel = $courseModel->get_item_model(
$courseSectionItem->item_id,
- $courseSectionItem->item_type
+ $courseSectionItem->item_type,
+ true,
+ true
);
$courseSectionItemAlias->title = $itemModel ? $itemModel->get_the_title() : '';
$response->data->html .= AdminEditCurriculumTemplate::instance()->html_section_item(
@@ -424,8 +446,9 @@
/**
* @var $itemModel PostModel
+ * @var $courseModel CourseModel
*/
- $itemModel = $courseModel->get_item_model( $item_id, $item_type );
+ $itemModel = $courseModel->get_item_model( $item_id, $item_type, true, true );
if ( ! $itemModel ) {
throw new Exception( __( 'Item not found', 'learnpress' ) );
}
@@ -469,8 +492,9 @@
/**
* @var $itemModel LessonPostModel
+ * @var $courseModel CourseModel
*/
- $itemModel = $courseModel->get_item_model( $item_id, $item_type );
+ $itemModel = $courseModel->get_item_model( $item_id, $item_type, true, true );
if ( ! $itemModel ) {
throw new Exception( __( 'Item not found', 'learnpress' ) );
}
--- a/learnpress/inc/Ajax/EditQuestionAjax.php
+++ b/learnpress/inc/Ajax/EditQuestionAjax.php
@@ -32,6 +32,16 @@
*/
class EditQuestionAjax extends AbstractAjax {
/**
+ * Methods allowed to call via 'lp-load-ajax'.
+ *
+ * @var string[]
+ */
+ protected static $actions = [
+ 'update_question',
+ 'update_question_answers_config',
+ ];
+
+ /**
* Check permissions and validate parameters.
*
* @throws Exception
--- a/learnpress/inc/Ajax/EditQuizAjax.php
+++ b/learnpress/inc/Ajax/EditQuizAjax.php
@@ -27,6 +27,18 @@
*/
class EditQuizAjax extends AbstractAjax {
/**
+ * Methods allowed to call via 'lp-load-ajax'.
+ *
+ * @var string[]
+ */
+ protected static $actions = [
+ 'create_question_add_to_quiz',
+ 'add_questions_to_quiz',
+ 'remove_question_from_quiz',
+ 'update_questions_position',
+ ];
+
+ /**
* Check permissions and validate parameters.
*
* @throws Exception
--- a/learnpress/inc/Ajax/LessonAjax.php
+++ b/learnpress/inc/Ajax/LessonAjax.php
@@ -24,6 +24,15 @@
class LessonAjax extends AbstractAjax {
/**
+ * Methods allowed to call via 'lp-load-ajax'.
+ *
+ * @var string[]
+ */
+ protected static $actions = [
+ 'user_complete_lesson',
+ ];
+
+ /**
* User complete lesson ajax handler.
*
* @since 4.2.7.6
--- a/learnpress/inc/Ajax/LoadContentViaAjax.php
+++ b/learnpress/inc/Ajax/LoadContentViaAjax.php
@@ -19,6 +19,15 @@
* @version 1.0.2
*/
class LoadContentViaAjax extends AbstractAjax {
+ /**
+ * Methods allowed to call via 'lp-load-ajax'.
+ *
+ * @var string[]
+ */
+ protected static $actions = [
+ 'load_content_via_ajax',
+ ];
+
public function load_content_via_ajax() {
$response = new Response();
--- a/learnpress/inc/Ajax/MCP/McpApiKeysAjax.php
+++ b/learnpress/inc/Ajax/MCP/McpApiKeysAjax.php
@@ -16,6 +16,24 @@
*/
class McpApiKeysAjax extends AbstractAjax {
/**
+ * Methods allowed to call via 'lp-load-ajax'.
+ *
+ * @var string[]
+ */
+ protected static $actions = [
+ 'mcp_create_api_key',
+ 'mcp_update_api_key',
+ 'mcp_regenerate_api_key',
+ ];
+
+ /**
+ * Nonce required for all actions of class, see AbstractAjax::$action_nonce.
+ *
+ * @var string
+ */
+ protected static $action_nonce = 'lp_mcp_api_keys_nonce';
+
+ /**
* @var string
*/
protected static $required_capability = 'manage_options';
--- a/learnpress/inc/Ajax/NoteAjax.php
+++ b/learnpress/inc/Ajax/NoteAjax.php
@@ -22,6 +22,15 @@
* @since 4.4.9.2
*/
class NoteAjax extends AbstractAjax {
+ /**
+ * Methods allowed to call via 'lp-load-ajax'.
+ *
+ * @var string[]
+ */
+ protected static $actions = [
+ 'lp_note_save',
+ 'lp_note_delete',
+ ];
/**
* Create or update a note of the current user.
--- a/learnpress/inc/Ajax/Order/ExportOrderCSVAjax.php
+++ b/learnpress/inc/Ajax/Order/ExportOrderCSVAjax.php
@@ -26,6 +26,15 @@
*/
class ExportOrderCSVAjax extends AbstractAjax {
/**
+ * Methods allowed to call via 'lp-load-ajax'.
+ *
+ * @var string[]
+ */
+ protected static $actions = [
+ 'export_order_csv',
+ ];
+
+ /**
* Export orders to CSV file, action call from js file: export-order.js
*
* @return void
--- a/learnpress/inc/Ajax/Order/RefundOrderAjax.php
+++ b/learnpress/inc/Ajax/Order/RefundOrderAjax.php
@@ -22,6 +22,16 @@
*/
class RefundOrderAjax extends AbstractAjax {
/**
+ * Methods allowed to call via 'lp-load-ajax'.
+ *
+ * @var string[]
+ */
+ protected static $actions = [
+ 'request_refund_order',
+ 'admin_handle_request_refund',
+ ];
+
+ /**
* Customer request refund order from profile page.
*
* @since 4.4.0
--- a/learnpress/inc/Ajax/SampleDataAJAX.php
+++ b/learnpress/inc/Ajax/SampleDataAJAX.php
@@ -27,6 +27,23 @@
*/
class SampleDataAJAX extends AbstractAjax {
/**
+ * Methods allowed to call via 'lp-load-ajax'.
+ *
+ * @var string[]
+ */
+ protected static $actions = [
+ 'lp_install_sample_data',
+ 'lp_uninstall_sample_data',
+ ];
+
+ /**
+ * Nonce required for all actions of class, see AbstractAjax::$action_nonce.
+ *
+ * @var string
+ */
+ protected static $action_nonce = 'lp_sample_data_nonce';
+
+ /**
* Install sample course data via AJAX.
*
* @return void
--- a/learnpress/inc/Ajax/SendEmailAjax.php
+++ b/learnpress/inc/Ajax/SendEmailAjax.php
@@ -45,6 +45,26 @@
class SendEmailAjax extends AbstractAjax {
/**
+ * Methods allowed to call via 'lp-load-ajax'.
+ *
+ * @var string[]
+ */
+ protected static $actions = [
+ 'send_mail_order_status_pending_to_processing',
+ 'send_mail_order_status_pending_to_completed',
+ 'send_mail_order_status_update_to_completed',
+ 'send_mail_order_status_update_to_cancelled',
+ 'send_mail_order_status_update_to_refunded',
+ 'send_mail_order_refund_requested',
+ 'send_mail_users_enrolled_courses',
+ 'send_mail_user_enrolled_course',
+ 'send_mail_user_course_finished',
+ 'send_mail_become_a_teacher_request',
+ 'send_mail_become_a_teacher_accept',
+ 'send_mail_become_a_teacher_deny',
+ ];
+
+ /**
* Send mail when order status update to complete
*
* @since 4.2.9.1
--- a/learnpress/inc/Ajax/SetupWizardAjax.php
+++ b/learnpress/inc/Ajax/SetupWizardAjax.php
@@ -28,6 +28,23 @@
*/
class SetupWizardAjax extends AbstractAjax {
/**
+ * Methods allowed to call via 'lp-load-ajax'.
+ *
+ * @var string[]
+ */
+ protected static $actions = [
+ 'lp_setup_wizard_save_step',
+ 'lp_setup_import_demo_course',
+ ];
+
+ /**
+ * Nonce required for all actions of class, see AbstractAjax::$action_nonce.
+ *
+ * @var string
+ */
+ protected static $action_nonce = 'lp_setup_wizard_nonce';
+
+ /**
* Save the current wizard step.
*
* @return void
--- a/learnpress/inc/Ajax/UserItem/UserCourseAjax.php
+++ b/learnpress/inc/Ajax/UserItem/UserCourseAjax.php
@@ -0,0 +1,252 @@
+<?php
+/**
+ * Class UserCourseAjax
+ *
+ * Handle user actions on course: enroll, purchase, retake.
+ * Replace REST API lp/v1/courses/enroll-course, purchase-course, retake-course.
+ * JS (assets/src/js/frontend/single-course.js) reads data-send of buttons
+ * (SingleCourseTemplate::html_btn_enroll_course, html_btn_purchase_course, UserCourseTemplate::html_btn_retake)
+ * and calls window.lpAJAXG.fetchAJAX.
+ *
+ * Nonce 'wp_rest' and nonce of class ($action_nonce) are verified on AbstractAjax::catch_lp_ajax.
+ *
+ * @since 4.5.1
+ * @version 1.0.0
+ */
+
+namespace LearnPressAjaxUserItem;
+
+use Exception;
+use LearnPressAjaxAbstractAjax;
+use LearnPressHelpersResponse;
+use LearnPressModelsCourseModel;
+use LearnPressModelsUserItemsUserCourseModel;
+use LearnPressModelsUserModel;
+use LearnPressServicesUserCourseService;
+use LP_Debug;
+use LP_Helper;
+use LP_Request;
+use Throwable;
+
+defined( 'ABSPATH' ) || exit;
+
+class UserCourseAjax extends AbstractAjax {
+ /**
+ * Methods allowed to call via 'lp-load-ajax'.
+ *
+ * @var string[]
+ */
+ protected static $actions = [
+ 'user_enroll_course',
+ 'user_purchase_course',
+ 'user_retake_course',
+ ];
+
+ /**
+ * Nonce of class, printed on form retake (UserCourseTemplate::html_btn_retake),
+ * JS sends it via field 'lp_action_nonce' of 'data'.
+ *
+ * @var string
+ */
+ protected static $action_nonce = 'lp_user_course_nonce';
+
+ /**
+ * Verify nonce of class only for user logged in.
+ * Guest (enroll, purchase): nonce of guest is same for all guests (public), not protect anything,
+ * and HTML of guest can be cached (nonce expired). Same rule 'wp_rest' nonce on AbstractAjax::catch_lp_ajax.
+ *
+ * @return bool
+ * @since 4.5.1
+ */
+ public static function verify_action_nonce(): bool {
+ if ( ! is_user_logged_in() ) {
+ return true;
+ }
+
+ return parent::verify_action_nonce();
+ }
+
+ /**
+ * User enroll course.
+ * Guest: course is added to cart, redirect to checkout page.
+ *
+ * @return void
+ * @since 4.5.1
+ * @version 1.0.0
+ */
+ public function user_enroll_course() {
+ $response = new Response();
+
+ try {
+ $courseModel = $this->get_course_model( $this->get_params() );
+ $userModel = UserModel::find( get_current_user_id(), true );
+
+ $result = $this->get_user_course_service()->enroll( $courseModel, $userModel );
+
+ $response->status = Response::STATUS_SUCCESS;
+ $response->message = $result['message'];
+ $response->data->redirect = esc_url_raw( $result['redirect'] );
+ } catch ( Throwable $e ) {
+ $response->message = $this->get_error_message( $e );
+ }
+
+ wp_send_json( $response );
+ }
+
+ /**
+ * User purchase course: add to cart, redirect to checkout page.
+ * Course allow repurchase (type popup): return HTML options, JS shows popup and sends again with 'repurchase_type'.
+ *
+ * @return void
+ * @since 4.5.1
+ * @version 1.0.0
+ */
+ public function user_purchase_course() {
+ $response = new Response();
+
+ try {
+ $params = $this->get_params();
+ $courseModel = $this->get_course_model( $params );
+ $userModel = UserModel::find( get_current_user_id(), true );
+
+ // Fields of form purchase (addons can add), save to cart item.
+ $item_data = $params['form_data'] ?? [];
+ $item_data = is_array( $item_data ) ? map_deep( $item_data, 'sanitize_text_field' ) : [];
+ unset( $item_data[ self::FIELD_ACTION_NONCE ] );
+
+ $repurchase_type = $params['repurchase_type'] ?? '';
+ $repurchase_type = is_string( $repurchase_type ) ? sanitize_key( $repurchase_type ) : '';
+
+ $result = $this->get_user_course_service()->purchase( $courseModel, $userModel, $item_data, $repurchase_type );
+
+ $response->status = Response::STATUS_SUCCESS;
+ if ( ( $result['type'] ?? '' ) === 'allow_repurchase' ) {
+ $response->data->type = 'allow_repurchase';
+ $response->data->html = $result['html'];
+ $response->data->title_popup = $result['title'];
+ } else {
+ $response->message = $result['message'];
+ $response->data->redirect = esc_url_raw( $result['redirect'] );
+ }
+ } catch ( Throwable $e ) {
+ $response->message = $this->get_error_message( $e );
+ }
+
+ wp_send_json( $response );
+ }
+
+ /**
+ * User retake course.
+ *
+ * @return void
+ * @since 4.5.1
+ * @version 1.0.0
+ */
+ public function user_retake_course() {
+ $response = new Response();
+
+ try {
+ $courseModel = $this->get_course_model( $this->get_params() );
+
+ $userModel = UserModel::find( get_current_user_id(), true );
+ if ( ! $userModel instanceof UserModel ) {
+ throw new Exception( esc_html__( 'You have to log in to retake the course.', 'learnpress' ) );
+ }
+
+ $userCourseModel = UserCourseModel::find( $userModel->get_id(), $courseModel->get_id(), true );
+ if ( ! $userCourseModel instanceof UserCourseModel ) {
+ throw new Exception( esc_html__( 'User not enrolled course!', 'learnpress' ) );
+ }
+
+ $userCourseModel->handle_retake();
+
+ $item_continue = $userCourseModel->get_item_continue();
+ if ( $item_continue ) {
+ $url_redirect = $courseModel->get_item_link( $item_continue->ID );
+ } else {
+ $url_redirect = $courseModel->get_permalink();
+ }
+
+ $response->status = Response::STATUS_SUCCESS;
+ $response->message = esc_html__( 'Now you can begin this course', 'learnpress' );
+ $response->data->url_redirect = esc_url_raw( $url_redirect );
+ } catch ( Throwable $e ) {
+ $response->message = $this->get_error_message( $e );
+ }
+
+ wp_send_json( $response );
+ }
+
+ /**
+ * Get course from param 'course_id'.
+ *
+ * @param array $params
+ *
+ * @return CourseModel
+ * @throws Exception
+ * @since 4.5.1
+ * @version 1.0.0
+ */
+ protected function get_course_model( array $params ): CourseModel {
+ $course_id = absint( $params['course_id'] ?? 0 );
+ if ( ! $course_id ) {
+ throw new Exception( esc_html__( 'Params invalid!', 'learnpress' ) );
+ }
+
+ $courseModel = CourseModel::find( $course_id, true );
+ if ( ! $courseModel instanceof CourseModel ) {
+ throw new Exception( esc_html__( 'The course is invalid', 'learnpress' ) );
+ }
+
+ return $courseModel;
+ }
+
+ /**
+ * @return UserCourseService
+ */
+ protected function get_user_course_service(): UserCourseService {
+ return UserCourseService::instance();
+ }
+
+ /**
+ * Message of Exception is shown to user,
+ * other errors (PHP Error...) are logged, not show to avoid exposing file paths.
+ *
+ * @param Throwable $e
+ *
+ * @return string
+ * @since 4.5.1
+ * @version 1.0.0
+ */
+ protected function get_error_message( Throwable $e ): string {
+ if ( $e instanceof Exception ) {
+ return $e->getMessage();
+ }
+
+ LP_Debug::error_log( $e );
+
+ return esc_html__( 'Something went wrong, please try again!', 'learnpress' );
+ }
+
+ /**
+ * Get params from request, key 'data' is JSON string sent by window.lpAJAXG.fetchAJAX.
+ *
+ * @return array
+ * @throws Exception
+ * @since 4.5.1
+ * @version 1.0.0
+ */
+ protected function get_params(): array {
+ $data = LP_Request::get_param(
+ 'data',
+ '',
+ 'wp_check_invalid_utf8'
+ );
+ $params = is_string( $data ) ? LP_Helper::json_decode( $data, true ) : null;
+ if ( ! is_array( $params ) ) {
+ throw new Exception( esc_html__( 'Params invalid!', 'learnpress' ) );
+ }
+
+ return $params;
+ }
+}
--- a/learnpress/inc/Ajax/UserQuizAjax.php
+++ b/learnpress/inc/Ajax/UserQuizAjax.php
@@ -37,6 +37,18 @@
class UserQuizAjax extends AbstractAjax {
/**
+ * Methods allowed to call via 'lp-load-ajax'.
+ *
+ * @var string[]
+ */
+ protected static $actions = [
+ 'user_start_quiz',
+ 'user_retake_quiz',
+ 'user_submit_quiz',
+ 'user_check_answer_question',
+ ];
+
+ /**
* User start quiz.
* Guest (course no required enroll) is not saved, only get HTML doing quiz.
*
--- a/learnpress/inc/Ajax/Webhook/WebhooksAjax.php
+++ b/learnpress/inc/Ajax/Webhook/WebhooksAjax.php
@@ -18,6 +18,25 @@
*/
class WebhooksAjax extends AbstractAjax {
/**
+ * Methods allowed to call via 'lp-load-ajax'.
+ *
+ * @var string[]
+ */
+ protected static $actions = [
+ 'create_webhook',
+ 'update_webhook',
+ 'delete_webhook',
+ 'regenerate_webhook_secret',
+ ];
+
+ /**
+ * Nonce required for all actions of class, see AbstractAjax::$action_nonce.
+ *
+ * @var string
+ */
+ protected static $action_nonce = 'lp_webhooks_nonce';
+
+ /**
* @var string
*/
protected static $required_capability = 'manage_options';
--- a/learnpress/inc/Cache/LPCache.php
+++ b/learnpress/inc/Cache/LPCache.php
@@ -263,10 +263,13 @@
*/
public function save_cache_keys( string $key_group, string $key_cache_new ) {
try {
- $keys = $this->get_cache( $key_group );
- $keys_cache = false === $keys ? array() : $keys;
+ $keys = $this->get_cache( $key_group, 'array' );
+ if ( is_string( $keys ) ) {
+ $keys = json_decode( $keys, true );
+ }
+ $keys_cache = is_array( $keys ) ? $keys : array();
- if ( in_array( $key_cache_new, $keys_cache ) ) {
+ if ( in_array( $key_cache_new, $keys_cache, true ) ) {
return;
}
@@ -292,8 +295,16 @@
return;
}
- foreach ( $keys as $key ) {
- $this->clear( $key );
+ if ( is_string( $keys ) ) {
+ $keys = json_decode( $keys, true );
+ }
+
+ if ( is_array( $keys ) ) {
+ foreach ( $keys as $key ) {
+ if ( is_string( $key ) && '' !== $key ) {
+ $this->clear( $key );
+ }
+ }
}
$this->clear( $key_group );
--- a/learnpress/inc/Cache/class-lp-cache.php
+++ b/learnpress/inc/Cache/class-lp-cache.php
@@ -155,10 +155,13 @@
public function save_cache_keys( string $key_group, string $key_cache_new ) {
try {
$keys = $this->get_cache( $key_group );
- if ( false === $keys ) {
- $keys_cache = array();
- } else {
- $keys_cache = is_array( $keys ) ? $keys : LP_Helper::json_decode( $keys, true );
+ if ( is_string( $keys ) ) {
+ $keys = json_decode( $keys, true );
+ }
+ $keys_cache = is_array( $keys ) ? $keys : array();
+
+ if ( in_array( $key_cache_new, $keys_cache, true ) ) {
+ return;
}
$keys_cache[] = $key_cache_new;
--- a/learnpress/inc/Cache/class-lp-course-cache.php
+++ b/learnpress/inc/Cache/class-lp-course-cache.php
@@ -1,74 +0,0 @@
-<?php
-
-/**
- * Class LP_Course_Cache
- *
- * @author tungnx
- * @since 4.0.9
- * @version 1.0.0
- */
-defined( 'ABSPATH' ) || exit();
-
-class LP_Course_Cache extends LP_Cache {
- protected static $instance;
- protected $key_group_child = 'course';
- protected $key_total_students_enrolled = 'total-students-enrolled';
- protected $key_total_students_enrolled_or_purchased = 'total-students-enrolled-or-purchased';
-
- /**
- * Get instance
- *
- * @return self
- */
- public static function instance(): self {
- if ( is_null( self::$instance ) ) {
- self::$instance = new self();
- }
-
- return self::$instance;
- }
-
- public function __construct( $has_thim_cache = false ) {
- parent::__construct( $has_thim_cache );
- }
-
- public function set_total_students_enrolled( $course_id, $total ) {
- $key = "{$course_id}/{$this->key_total_students_enrolled}";
- $this->set_cache( $key, $total );
- }
-
- public function get_total_students_enrolled( $course_id ) {
- $key = "{$course_id}/{$this->key_total_students_enrolled}";
- return $this->get_cache( $key );
- }
-
- public function clean_total_students_enrolled( $course_id ) {
- $key = "{$course_id}/{$this->key_total_students_enrolled}";
- $this->clear( $key );
- }
-
- public function set_total_students_enrolled_or_purchased( $course_id, $total ) {
- $key = "{$course_id}/{$this->key_total_students_enrolled_or_purchased}";
- $this->set_cache( $key, $total );
- LP_Cache::cache_load_first( 'set', $key, $total );
- }
-
- public function get_total_students_enrolled_or_purchased( $course_id ) {
- $key = "{$course_id}/{$this->key_total_students_enrolled_or_purchased}";
- $total = LP_Cache::cache_load_first( 'get', $key );
- if ( false !== $total ) {
- return $total;
- }
-
- $total = $this->get_cache( $key );
- LP_Cache::cache_load_first( 'set', $key, $total );
-
- return $total;
- }
-
- public function clean_total_students_enrolled_or_purchased( $course_id ) {
- $key = "{$course_id}/{$this->key_total_students_enrolled_or_purchased}";
- $this->clear( $key );
- LP_Cache::cache_load_first( 'clear', $key );
- }
-}
--- a/learnpress/inc/Cache/class-lp-user-items-cache.php
+++ b/learnpress/inc/Cache/class-lp-user-items-cache.php
@@ -1,7 +1,7 @@
<?php
/**
- * Class LP_Course_Cache
+ * Class LP_User_Items_Cache
*
* @author tungnx
* @since 4.0.9
--- a/learnpress/inc/Databases/Course/CourseJsonDB.php
+++ b/learnpress/inc/Databases/Course/CourseJsonDB.php
@@ -68,8 +68,10 @@
$filter->where[] = $this->wpdb->prepare( "AND $ca.post_status IN (" . $post_status_format . ')', $filter->post_status );
}
- // Exclude status auto-draft, because Admin of WP not show auto-draft in list post, so all front-end and back-end of LP also not show auto-draft
- if ( ! in_array( 'auto-draft', $filter->post_status, true ) ) {
+ // Exclude status auto-draft on list queries, because Admin of WP not show auto-draft in list post, so all front-end and back-end of LP also not show auto-draft.
+ // Keep auto-draft reachable when looking up directly by ID (e.g. CourseModel::find/save checking row existence).
+ if ( empty( $filter->ID )
+ && ! in_array( 'auto-draft', $filter->post_status, true ) ) {
$filter->where[] = $this->wpdb->prepare( "AND $ca.post_status != %s", 'auto-draft' );
}
@@ -86,8 +88,8 @@
// Course ids
if ( ! empty( $filter->ids ) ) {
- $ids = array_map( 'absint', $filter->ids );
- $ids_format = join( ',', $ids );
+ $ids = array_map( 'absint', $filter->ids );
+ $ids_format = join( ',', $ids );
$filter->where[] = "AND $ca.ID IN ($ids_format)";
}
--- a/learnpress/inc/Databases/Course/CourseSectionItemsDB.php
+++ b/learnpress/inc/Databases/Course/CourseSectionItemsDB.php
@@ -5,6 +5,7 @@
use Exception;
use LearnPressDatabasesDataBase;
use LearnPressFiltersCourseCourseSectionItemsFilter;
+use LearnPressModelsCourseModel;
use LP_Helper;
if ( ! defined( 'ABSPATH' ) ) {
@@ -120,6 +121,96 @@
}
/**
+ * Get first item id of course
+ *
+ * @param int $course_id
+ *
+ * @return int
+ * @throws Exception
+ * @since 4.5.1
+ * @version 1.0.0
+ */
+ public function get_first_item_id( int $course_id ): int {
+ $filter = new CourseSectionItemsFilter();
+ $filter->only_fields = [ 'si.item_id' ];
+ $filter->limit = 1;
+ $filter->run_query_count = false;
+ $filter->order_by = 's.section_order ASC, si.item_order';
+ $filter->order = 'ASC';
+ $filter->join[] = "INNER JOIN $this->tb_lp_sections AS s ON si.section_id = s.section_id";
+ $filter->join[] = "INNER JOIN $this->tb_posts AS p ON si.item_id = p.ID";
+ $filter->where[] = $this->wpdb->prepare( 'AND s.section_course_id = %d', $course_id );
+ $filter->where[] = "AND p.post_status = 'publish'";
+
+ $items = $this->get_section_items( $filter );
+
+ return ! empty( $items ) ? (int) $items[0]->item_id : 0;
+ }
+
+ /**
+ * Get total items of course
+ *
+ * @param int $course_id
+ *
+ * @return array|null|object
+ * @throws Exception
+ * @since 4.5.1
+ * @version 1.0.0
+ */
+ public function get_total_items( int $course_id = 0 ) {
+ $item_types = CourseModel::item_types_support();
+
+ $filter = new CourseSectionItemsFilter();
+ $filter->collection = $this->tb_lp_section_items;
+ $filter->collection_alias = 'si';
+ $filter->run_query_count = false;
+ $filter->join[] = "INNER JOIN $this->tb_lp_sections AS s ON s.section_id = si.section_id";
+ $filter->join[] = "INNER JOIN $this->tb_posts AS p ON si.item_id = p.ID";
+ $filter->where[] = $this->wpdb->prepare( 'AND s.section_course_id = %d', $course_id );
+ $filter->where[] = "AND p.post_status = 'publish'";
+ $filter->limit = 1;
+
+ $filter->fields[] = 'COUNT(si.item_id) AS count_items';
+ foreach ( $item_types as $item_type ) {
+ $item_type_safe = sanitize_key( (string) $item_type );
+ if ( '' === $item_type_safe ) {
+ continue;
+ }
+
+ $filter->fields[] = $this->wpdb->prepare(
+ "SUM(si.item_type = %s) AS `{$item_type_safe}`",
+ $item_type_safe
+ );
+ }
+
+ $rows = $this->execute( $filter );
+
+ return $rows[0] ?? null;
+ }
+
+ /**
+ * Delete items of course not in table posts (deleted permanently).
+ * Items not publish (draft, pending, private, future, trash) keep position in sections.
+ *
+ * @param int $course_id
+ *
+ * @throws Exception
+ * @since 4.5.1
+ * @version 1.0.0
+ */
+ public function delete_item_not_in_tb_post( int $course_id ) {
+ $filter = new CourseSectionItemsFilter();
+ $filter->collection = $this->tb_lp_section_items;
+ $filter->collection_alias = 'si';
+ $filter->join[] = "INNER JOIN $this->tb_lp_sections AS s ON si.section_id = s.section_id";
+ $filter->join[] = "LEFT JOIN $this->tb_posts AS p ON si.item_id = p.ID";
+ $filter->where[] = $this->wpdb->prepare( 'AND s.section_course_id = %d', $course_id );
+ $filter->where[] = 'AND p.ID IS NULL';
+
+ $this->delete_execute( $filter );
+ }
+
+ /**
* Update table
*
* @throws Exception
--- a/learnpress/inc/Databases/CourseSectionDB.php
+++ b/learnpress/inc/Databases/CourseSectionDB.php
@@ -4,15 +4,9 @@
use Exception;
use LearnPressFiltersCourseSectionFilter;
-use LearnPressModelsCourseModel;
-use LearnPressModelsCourseSectionItemModel;
-use LearnPressModelsCourseSectionModel;
-use LearnPressModelsPostModel;
use LP_Helper;
-if ( ! defined( 'ABSPATH' ) ) {
- exit; // Exit if accessed directly
-}
+defined( 'ABSPATH' ) || exit;
/**
* Class CourseSectionDB
@@ -20,7 +14,7 @@
* Refactor of LP_Section_DB
*
* @since 4.3.0
- * @version 1.0.0
+ * @version 1.0.1
*/
class CourseSectionDB extends DataBase {
public static $_instance;
@@ -85,6 +79,67 @@
}
/**
+ * Get all sections of course (include sections empty items), order by section_order.
+ *
+ * @param int $course_id
+ *
+ * @return array
+ * @throws Exception
+ * @since 4.5.1
+ * @version 1.0.0
+ */
+ public function get_sections_of_course( int $course_id ): array {
+ $filter = new CourseSectionFilter();
+ $filter->section_course_id = $course_id;
+ $filter->limit = -1;
+ $filter->run_query_count = false;
+
+ $sections = $this->get_sections( $filter );
+
+ return is_array( $sections ) ? $sections : [];
+ }
+
+ /**
+ * Get sections join items of course, order by section_order, item_order.
+ * Each row has fields of section, item and post_status, post_title of item.
+ *
+ * @param int $course_id
+ * @param bool $for_edit false: only items publish (frontend), true: items of all statuses (edit curriculum).
+ *
+ * @return array
+ * @throws Exception
+ * @since 4.5.1
+ * @version 1.0.0
+ */
+ public function get_sections_items_of_course( int $course_id, bool $for_edit = false ): array {
+ $filter = new CourseSectionFilter();
+ $filter->section_course_id = $course_id;
+ $filter->limit = -1;
+ $filter->run_query_count = false;
+ $filter->only_fields = [
+ 'st.section_id',
+ 'st.section_course_id',
+ 'st.section_name',
+ 'st.section_order',
+ 'st.section_description',
+ 'si.item_id',
+ 'si.item_order',
+ 'si.item_type',
+ 'p.post_status',
+ 'p.post_title',
+ ];
+ $filter->join[] = "INNER JOIN {$this->tb_lp_section_items} AS si ON si.section_id = st.section_id";
+ $filter->join[] = "INNER JOIN {$this->tb_posts} AS p ON si.item_id = p.ID"
+ . ( $for_edit ? '' : " AND p.post_status = 'publish'" );
+ $filter->order_by = 'st.section_order ASC, si.item_order';
+ $filter->order = 'ASC';
+
+ $sections_items = $this->get_sections( $filter );
+
+ return is_array( $sections_items ) ? $sections_items : [];
+ }
+
+ /**
* Get last section order of course
*
* @param int $course_id
--- a/learnpress/inc/Databases/DataBase.php
+++ b/learnpress/inc/Databases/DataBase.php
@@ -730,6 +730,14 @@
$INNER_JOIN = apply_filters( 'lp/query/delete/inner_join', $INNER_JOIN, $filter );
$INNER_JOIN = implode( ' ', array_unique( $INNER_JOIN ) );
+ // Single-table DELETE with alias not supported on MySQL < 8.0.16,
+ if ( ! empty( $filter->collection_alias ) ) {
+ $COLLECTION .= ' AS ' . $filter->collection_alias;
+ if ( '' === $table ) {
+ $table = $filter->collection_alias;
+ }
+ }
+
$query = "
DELETE $table FROM $COLLECTION
$INNER_JOIN
@@ -796,7 +804,7 @@
throw new Exception( __( 'Table name is required!', 'learnpress' ) . ' | ' . __FUNCTION__ );
}
- if ( empty( $key_auto_increment ) || ! is_string( $key_auto_increment ) ) {
+ if ( ! is_string( $key_auto_increment ) ) {
throw new Exception( __( 'Key auto increment must be a string!', 'learnpress' ) . ' | ' . __FUNCTION__ );
}
@@ -806,8 +814,10 @@
}
}
- // unset key is auto increment.
- unset( $data[ $key_auto_increment ] );
+ // Unset key is auto increment. Empty key for table without auto increment (key must keep in data).
+ if ( '' !== $key_auto_increment ) {
+ unset( $data[ $key_auto_increment ] );
+ }
$this->wpdb->insert( $table_name, $data );
--- a/learnpress/inc/Databases/UserItemsDB.php
+++ b/learnpress/inc/Databases/UserItemsDB.php
@@ -4,7 +4,9 @@
use Exception;
use LearnPressFiltersUserItemsFilter;
+use LearnPressModelsCourseModel;
use LP_Helper;
+use stdClass;
defined( 'ABSPATH' ) || exit();
@@ -12,7 +14,7 @@
* Class UserItemsDB
*
* @since 4.2.9.3
- * @version 1.0.0
+ * @version 1.0.1
*/
class UserItemsDB extends DataBase {
private static $_instance;
@@ -141,4 +143,90 @@
return $total;
}
+
+ /**
+ * Count items of user course by status and graduation.
+ * Only count items currently assigned to the course's sections and having post_status = 'publish'.
+ *
+ * @param UserItemsFilter $filter {parent_id, ref_id|item_id, user_id, status, graduation}
+ *
+ * @return object|string|null
+ * @throws Exception
+ * @since 4.5.1
+ * @version 1.0.0
+ */
+ public function count_items_of_course_with_status( UserItemsFilter $filter ) {
+ if ( empty( $filter->parent_id ) ) {
+ return new stdClass();
+ }
+
+ $item_types = CourseModel::item_types_support();
+ $course_id = (int) ( $filter->ref_id ?: $filter->item_id );
+ $status_raw = (string) $filter->status;
+ $graduation_raw = (string) $filter->graduation;
+ $status_key = sanitize_key( $status_raw );
+ $graduation_key = sanitize_key( $graduation_raw );
+
+ $only_fields = [];
+ $only_fields[] = $this->wpdb->prepare( 'SUM(ui.status = %s) AS count_status', $status_raw );
+
+ foreach ( $item_types as $item_type ) {
+ $item_type_safe = sanitize_key( (string) $item_type );
+ if ( '' === $item_type_safe ) {
+ continue;
+ }
+
+ if ( '' !== $status_key ) {
+ $alias_status = "{$item_type_safe}_status_{$status_key}";
+ $only_fields[] = $this->wpdb->prepare(
+ "SUM(ui.status = %s AND ui.item_type = %s) AS `{$alias_status}`",
+ $status_raw,
+ $item_type_safe
+ );
+ }
+
+ if ( '' !== $graduation_key ) {
+ $alias_grad = "{$item_type_safe}_graduation_{$graduation_key}";
+ $only_fields[] = $this->wpdb->prepare(
+ "SUM(ui.graduation = %s AND ui.item_type = %s) AS `{$alias_grad}`",
+ $graduation_raw,
+ $item_type_safe
+ );
+ }
+ }
+
+ if ( empty( $filter->collection ) ) {
+ $filter->collection = $this->tb_lp_user_items;
+ }
+ if ( empty( $filter->collection_alias ) ) {
+ $filter->collection_alias = 'ui';
+ }
+
+ $filter->only_fields = $only_fields;
+ $filter->run_query_count = false;
+ $filter->limit = 1;
+
+ $filter->join[] = "INNER JOIN {$this->tb_lp_section_items} AS si ON ui.item_id = si.item_id";
+ $filter->join[] = "INNER JOIN {$this->tb_lp_sections} AS s ON si.section_id = s.section_id";
+ $filter->join[] = "INNER JOIN {$this->tb_posts} AS p ON ui.item_id = p.ID";
+ $filter->where[] = $this->wpdb->prepare( 'AND ui.parent_id = %d', (int) $filter->parent_id );
+ if ( $course_id > 0 ) {
+ $filter->where[] = $this->wpdb->prepare( 'AND s.section_course_id = %d', $course_id );
+ } else {
+ $filter->where[] = 'AND s.section_course_id = ui.ref_id';
+ }
+ if ( ! empty( $filter->user_id ) ) {
+ $filter->where[] = $this->wpdb->prepare( 'AND ui.user_id = %d', (int) $filter->user_id );
+ }
+ $filter->where[] = "AND p.post_status = 'publish'";
+
+ $filter = apply_filters( 'lp/user_items/count_items_of_course/filter', $filter );
+
+ $rows = $this->execute( $filter );
+ if ( ! is_array( $rows ) ) {
+ return $rows;
+ }
+
+ return $rows[0] ?? new stdClass();
+ }
}
--- a/learnpress/inc/Databases/class-lp-course-db.php
+++ b/learnpress/inc/Databases/class-lp-course-db.php
@@ -6,6 +6,7 @@
* @since 3.2.7.5
*/
+use LearnPressCacheLPCourseCache;
use LearnPressModelsCourseModel;
defined( 'ABSPATH' ) || exit();
@@ -38,7 +39,7 @@
*/
public function get_course_by_item_id( $item_id = 0 ): int {
// Get cache
- $lp_course_cache = LP_Course_Cache::instance();
+ $lp_course_cache = new LPCourseCache();
$key_cache = "$item_id/course_id_of_item_id";
$course_id = $lp_course_cache->get_cache( $key_cache );
--- a/learnpress/inc/Databases/class-lp-section-items-db.php
+++ b/learnpress/inc/Databases/class-lp-section-items-db.php
@@ -134,31 +134,6 @@
}
/**
- * Delete item on section of course not in table posts.
- *
- * @param int $course_id
- *
- * @throws Exception
- * @since 4.2.6.4
- * @version 1.0.0
- */
- public function delete_item_not_in_tb_post( int $course_id ) {
- $filter_section = $this->wpdb->prepare(
- "DELETE si
- FROM $this->tb_lp_section_items AS si
- INNER JOIN $this->tb_lp_sections AS s ON si.section_id = s.section_id
- AND s.section_course_id = %d
- WHERE item_id NOT IN (SELECT ID FROM $this->tb_posts WHERE post_status = 'publish')
- ",
- $course_id
- );
-
- $this->wpdb->query( $filter_section );
-
- $this->check_execute_has_error();
- }
-
- /**
* Insert data
*
* @param array $data
--- a/learnpress/inc/Databases/class-lp-user-items-db.php
+++ b/learnpress/inc/Databases/class-lp-user-items-db.php
@@ -213,13 +213,17 @@
}
/**
- * Remove items' of course and user learned
+ * Remove items' of course and user learned.
*
- * @param LP_User_Items_Filter|UserItemsFilter $filter .
+ * Deletes the child rows (lessons, quizzes...) of a user course and their user_itemmeta.
+ * The user course row and its meta (e.g. _lp_retaken_count) are kept.
*
- * @return bool|int
+ * @param LP_User_Items_Filter|UserItemsFilter $filter $filter->parent_id, $filter->user_id, $filter->limit
+ *
+ * @return bool|int Number of child rows deleted, or false on error.
* @throws Exception .
- * @TODO tungnx - recheck this function
+ * @since 4.0.0
+ * @version 1.0.1
*/
public function remove_items_of_user_course( $filter ) {
$query_extra = '';
@@ -230,18 +234,31 @@
}
if ( - 1 < $filter->limit ) {
- $query_extra .= " LIMIT $filter->limit";
+ $query_extra .= ' LIMIT ' . absint( $filter->limit );
}
- $query = $this->wpdb->prepare(
- "DELETE FROM {$this->tb_lp_user_items}
- WHERE parent_id = %d
- $query_extra;
- ",
- $filter->parent_id
+ $child_ids = $this->wpdb->get_col(
+ $this->wpdb->prepare(
+ "SELECT user_item_id FROM {$this->tb_lp_user_items}
+ WHERE parent_id = %d
+ $query_extra
+ ",
+ $filter->parent_id
+ )
);
- return $this->wpdb->query( $query );
+ if ( empty( $child_ids ) ) {
+ return 0;
+ }
+
+ $filter_delete = new LP_User_Items_Filter();
+ $filter_delete->user_id = $filter->user_id;
+ $filter_delete->user_item_ids = array_map( 'absint', $child_ids );
+
+ // Delete meta of child rows first, so no orphan user_itemmeta is left.
+ $this->remove_user_itemmeta( $filter_delete );
+
+ return $this->remove_user_item_ids( $filter_delete );
}
/*public function get_item_status( $item_id, $course_id ) {
--- a/learnpress/inc/Filters/UserItemsFilter.php
+++ b/learnpress/inc/Filters/UserItemsFilter.php
@@ -8,7 +8,7 @@
* Filter query for learnpress_user_items table
*
* @since 4.2.9.3
- * @version 1.0.0
+ * @version 1.0.1
*/
class UserItemsFilter extends FilterBase {
const COL_USER_ITEM_ID = 'user_item_id';
@@ -22,6 +22,7 @@
const COL_REF_ID = 'ref_id';
const COL_REF_TYPE = 'ref_type';
const COL_PARENT_ID = 'parent_id';
+ const COL_EXTRA_DATA = 'extra_data';
/**
* @var string[] all fields of table
*/
@@ -37,6 +38,7 @@
self::COL_REF_ID,
self::COL_REF_TYPE,
self::COL_PARENT_ID,
+ self::COL_EXTRA_DATA,
];
/**
* @var int
--- a/learnpress/inc/Gutenberg/Blocks/AbstractBlockType.php
+++ b/learnpress/inc/Gutenberg/Blocks/AbstractBlockType.php
@@ -2,6 +2,7 @@
namespace LearnPressGutenbergBlocks;
use LearnPressGutenbergUtilsStyleAttributes;
+use LearnPressHelpersTemplate;
use WP_Block;
use WP_Block_Type;
@@ -41,6 +42,14 @@
* @var string Class hash - Field of LP
*/
protected $class_hash = '';
+ /**
+ * Output of block can contain request data (URL params...), encode shortcode brackets on get_output().
+ * Block render callback runs on do_blocks (the_content priority 9), before do_shortcode (priority 11).
+ *
+ * @var bool
+ * @since 4.3.2.6
+ */
+ protected $neutralize_shortcode_output = false;
public function __construct() {
$this->source_js = $this->get_source_js();
@@ -123,8 +132,44 @@
return $this->namespace . '/' . $this->block_name;
}
+ protected function get_min_suffix(): string {
+ $base_path = LP_PLUGIN_PATH . 'assets/js/dist/blocks/' . $this->block_name;
+ $is_debug = class_exists( LP_Debug::class ) && LP_Debug::is_debug();
+
+ if ( $is_debug && file_exists( $base_path . '.js' ) ) {
+ return '';
+ }
+
+ return file_exists( $base_path . '.min.js' ) ? '.min' : '';
+ }
+
protected function get_source_js() {
- return LP_PLUGIN_URL . 'assets/js/dist/blocks/' . $this->block_name . '.js';
+ return LP_PLUGIN_URL . 'assets/js/dist/blocks/' . $this->block_name . $this->get_min_suffix() . '.js';
+ }
+
+ /**
+ * Read Webpack-generated .asset.php metadata (dependencies & content-hash version) for this block.
+ *
+ * @return array{dependencies: array<int, string>, version: string}
+ */
+ public function get_asset_metadata(): array {
+ $default_version = defined( 'LEARNPRESS_VERSION' ) ? (string) LEARNPRESS_VERSION : '1.0.0';
+ $asset_file = LP_PLUGIN_PATH . 'assets/js/dist/blocks/' . $this->block_name . $this->get_min_suffix() . '.asset.php';
+
+ if ( file_exists( $asset_file ) ) {
+ $asset = include $asset_file;
+ if ( is_array( $asset ) ) {
+ return [
+ 'dependencies' => is_array( $asset['dependencies'] ?? null ) ? $asset['dependencies'] : [],
+ 'version' => ! empty( $asset['version'] ) ? (string) $asset['version'] : $default_version,
+ ];
+ }
+ }
+
+ return [
+ 'dependencies' => [],
+ 'version' => $default_version,
+ ];
}
protected function get_class_hash() {
@@ -147,11 +192,18 @@
*/
protected function get_output( string $content, string $tag = 'div', array $extra_attributes = [] ): string {
$wrapper = get_block_wrapper_attributes( $extra_attributes );
- return sprintf(
+ $output = sprintf(
"<$tag %s>%s</$tag>",
$wrapper,
$content
);
+
+ // Security: block output contains request data, prevent shortcode injection.
+ if ( $this->neutralize_shortcode_output ) {
+ $output = Template::neutralize_shortcode_brackets( $output );
+ }
+
+ return $output;
}
protected function get_output_with_class_hash( $attributes, $content, $properties = array(), $exclude = array() ) {
@@ -163,8 +215,12 @@
$class = $class_default ? $class_default : '';
$style = '';
- if ( ! empty( $classes ) ) {
- $class .= ' ' . $classes;
+ if ( ! empty( $classes ) && is_string( $classes ) ) {
+ // className comes from stored block markup (user-controlled), sanitize each token.
+ $class_tokens = array_filter( array_map( 'sanitize_html_class', preg_split( '/s+/', $classes ) ) );
+ if ( ! empty( $class_tokens ) ) {
+ $class .= ' ' . implode( ' ', $class_tokens );
+ }
}
if ( ! empty( $class_hash ) ) {
@@ -175,16 +231,16 @@
$class .= ' ' . $border_classes_and_styles['classes'];
}
- if ( ! empty( $border_classes_and_styles['classes'] ) ) {
- $style = sprintf( 'style="%s"', $border_classes_and_styles['styles'] );
+ if ( ! empty( $border_classes_and_styles['styles'] ) ) {
+ $style = sprintf( 'style="%s"', esc_attr( $border_classes_and_styles['styles'] ) );
}
ob_start();
- echo sprintf(
+ printf(
'<div class="%s" %s>%s</div>',
- $class,
- $style,
- $content
+ esc_attr( $class ),
+ $style, // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- value escaped above.
+ $content // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- block content rendered by the block itself.
);
$output = ob_get_clean();
return $output;
--- a/learnpress/inc/Gutenberg/Blocks/Breadcrumb/BreadcrumbBlockType.php
+++ b/learnpress/inc/Gutenberg/Blocks/Breadcrumb/BreadcrumbBlockType.php
@@ -14,6 +14,8 @@
*/
class BreadcrumbBlockType extends AbstractBlockType {
public $block_name = 'breadcrumb';
+ // Security: output contains c_search from URL, encode shortcode brackets.
+ protected $neutralize_shortcode_output = true;
public function get_supports(): array {
return [
@@ -61,6 +63,7 @@
$template = new LP_Template_General();
$template->breadcrumb( $args );
$html_breadcrumb = ob_get_clean();*/
+ // Security: neutralize shortcode brackets via get_output() ($neutralize_shortcode_output).
$html = $this->get_output( Template::html_breadcrumb( $args ) );
} catch ( Throwable $e ) {
LP_Debug::error_log( $e );
--- a/learnpress/inc/Gutenberg/Blocks/CourseFilter/CourseFilterBlockType.php
+++ b/learnpress/inc/Gutenberg/Blocks/CourseFilter/CourseFilterBlockType.php
@@ -13,6 +13,8 @@
*/
class CourseFilterBlockType extends AbstractBlockType {
public $block_name = 'course-filter';
+ // Security: output contains c_search from URL, encode shortcode brackets.
+ protected $neutralize_shortcode_output = true;
/**
* Render content of block tag
--- a/learnpress/inc/Gutenberg/Blocks/Courses/CourseSearchBlockType.php
+++ b/learnpress/inc/Gutenberg/Blocks/Courses/CourseSearchBlockType.php
@@ -14,6 +14,8 @@
*/
class CourseSearchBlockType extends AbstractBlockType {
public $block_name = 'course-search';
+ // Security: output contains c_search from URL, encode shortcode brackets.
+ protected $neutralize_shortcode_output = true;
public function get_supports(): array {
return [
--- a/learnpress/inc/Gutenberg/Blocks/SingleCourseElements/CourseButtonBlockType.php
+++ b/learnpress/inc/Gutenberg/Blocks/SingleCourseElements/CourseButtonBlockType.php
@@ -134,7 +134,7 @@
preg_match( '#