attach_hooks(); $self->init_site_tracking(); } /** * Constructor: Initialize necessary managers. */ public function __construct() { $this->points_manager = new PointsManager(); $this->achievements_manager = new AchievementsManager(); } /** * Injects tracking code to detect site visits. */ public function init_site_tracking() { add_action('wp_head', function () { if (is_user_logged_in()) { global $post; $post_id = $post ? $post->ID : 0; do_action('gameengine_site_visit', get_current_user_id(), $post_id); } }); } /** * Dynamically attaches all registered triggers to their WordPress hooks. */ public function attach_hooks() { $triggers = TriggerRegistry::get_all_triggers(); foreach ($triggers as $key => $config) { if (empty($config['hook'])) continue; $args_count = isset($config['args_count']) ? (int) $config['args_count'] : 1; add_action($config['hook'], function () use ($key, $config) { $this->execute($key, $config, func_get_args()); }, 10, $args_count); } } /** * Main execution flow when a hook is fired. */ public function execute($trigger_key, $config, $hook_args) { global $wpdb; // Fallback to fetch config from registry if not provided if (empty($config) || !isset($config['get_user_id'])) { $config = TriggerRegistry::get($trigger_key); } if (!$config || !is_callable($config['get_user_id'])) { return; } // Identify the user associated with this hook $user_id = call_user_func_array($config['get_user_id'], $hook_args); $safe_user_id = absint($user_id); if ($safe_user_id <= 0) { return; } // Fetch all active requirements (rules) for this specific trigger // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared $rules = $wpdb->get_results($wpdb->prepare( "SELECT * FROM {$wpdb->prefix}gameengine_requirements WHERE trigger_key = %s AND is_active = 1 ORDER BY priority ASC, id ASC", sanitize_key($trigger_key) )); if (empty($rules)) { return; } $total_points_awarded = 0; $first_rule_processed = false; foreach ($rules as $rule) { $params = json_decode($rule->parameters, true); // A trigger that can only take points away, such as a refund, never // awards: a rule saved under Awards deducts its points instead, and // an achievement or level rule on it does nothing. $allowed_actions = TriggerRegistry::get_actions($config); if (!in_array($rule->action_type, $allowed_actions, true)) { if ('point_type' !== $rule->reward_type) { continue; } $rule->action_type = $allowed_actions[0]; } // Validate Time-Based restrictions (Pro Logic) if (!$this->check_timing_validity($params)) { continue; } // Validate Conditional Logic (Specific Post IDs, Products, or Roles) if (!$this->check_conditions($trigger_key, $params, $hook_args)) { continue; } // Calculate potential points if it's a point type reward. // Stays null for anything else, so process_single_rule reads the // amount off the rule itself — passing 0 as an "override" made // every deduction deduct nothing. $potential_points = null; if ($rule->reward_type === 'point_type' && $rule->action_type === 'award') { $base_points = isset($params['points']) ? intval($params['points']) : 0; $potential_points = apply_filters('gameengine_pro_point_amount', $base_points, $rule, $params, $hook_args); } // Process the actual Reward or Deduction. // An award worth nothing after filtering is skipped; deductions and // achievement/level rewards always run. if (null === $potential_points || $potential_points > 0) { $rule_success = $this->process_single_rule($rule, $safe_user_id, $config, $hook_args, $potential_points); if ($rule_success) { $first_rule_processed = true; if (null !== $potential_points) { $total_points_awarded += $potential_points; } } } } } /** * Validates if the action is occurring within allowed hours or days. */ private function check_timing_validity($params) { return apply_filters('gameengine_check_timing_validity', true, $params); } /** * Handles the rewarding or revoking logic for a single rule. * Updated to support Pro features via filters. * * @return bool Success status */ private function process_single_rule($rule, $user_id, $config, $hook_args, $points_override = null) { $params = json_decode($rule->parameters, true); $can_unlock = apply_filters('gameengine_can_user_unlock_reward', true, $user_id, $rule); if (!$can_unlock) { return false; } // Validate Pro Conditional Logic (Word Count, Min Spend, etc.) // This filter allows the Pro folder to stop the process if conditions aren't met. if (!apply_filters('gameengine_validate_pro_logic', true, $rule->trigger_key, $params, $hook_args)) { return false; } // Check frequency limits (Daily, Weekly, Monthly, etc.) if (!$this->check_limit_validity((int) $user_id, (int) $rule->id, $params)) { return false; } $success = false; $safe_user_id = absint($user_id); // A. Handle Point-based rewards/penalties if ($rule->reward_type === 'point_type') { $points = ($points_override !== null) ? $points_override : (isset($params['points']) ? intval($params['points']) : 0); // Only apply filters if no override was provided (override already // includes filtered/capped points). gameengine_pro_point_amount // shapes what a trigger pays out — multipliers, percentages, // bonuses — so a deduction takes exactly the amount configured. if ($points_override === null && 'award' === $rule->action_type) { $points = apply_filters('gameengine_pro_point_amount', $points, $rule, $params, $hook_args); } $args = [ 'description' => $params['log_label'] ?? ($params['label'] ?? $config['label']), 'requirement_id' => $rule->id, 'point_type_id' => $rule->reward_id ]; if ($rule->action_type === 'deduct') { $success = $this->points_manager->deduct($safe_user_id, $points, $rule->trigger_key, $args); } else { $success = $this->points_manager->add($safe_user_id, $points, $rule->trigger_key, $args); } } // Handle Achievement-based rewards/penalties elseif ($rule->reward_type === 'achievement') { if ($rule->action_type === 'deduct') { $success = $this->achievements_manager->revoke($safe_user_id, (int) $rule->reward_id); } else { $success = $this->achievements_manager->award($safe_user_id, (int) $rule->reward_id, $rule->trigger_key, ['requirement_id' => $rule->id]); } } // Handle Level-based rewards elseif ($rule->reward_type === 'level') { $levels_manager = new LevelsManager(); $success = $levels_manager->award($safe_user_id, (int) $rule->reward_id, $rule->trigger_key); } // If the transaction was successful, update the user progress record if ($success) { $this->update_requirement_progress($safe_user_id, (int) $rule->id, $rule, $params); } return (bool) $success; } /** * Validates specific conditions like Target Roles, Post IDs, or WooCommerce Product IDs. */ private function check_conditions($key, $params, $args) { // WordPress: Role Change Check if ($key === 'user_role_change') { $new_role = isset($args[1]) ? $args[1] : ''; $target_role = isset($params['target_role']) ? $params['target_role'] : ''; return (!empty($new_role) && $new_role === $target_role); } // Interaction: Specific Post Visit Check if ($key === 'visit_specific_post') { $current_post_id = isset($args[1]) ? (int) $args[1] : 0; $target_post_id = isset($params['post_id']) ? (int) $params['post_id'] : 0; $target_categories = isset($params['categories']) ? (array) $params['categories'] : []; // 1. Check for specific post match if ($target_post_id > 0 && $current_post_id === $target_post_id) { return true; } // 2. Check for category match if no specific post match was found if (!empty($target_categories)) { $post_categories = wp_get_post_categories($current_post_id); foreach ($target_categories as $cat_id) { if (in_array((int) $cat_id, $post_categories)) { return true; } } } return false; } // GameEngine: Specific Achievement Unlock Event if ($key === 'unlock_specific_achievement') { $unlocked_id = isset($args[1]) ? (int) $args[1] : 0; $target_id = isset($params['achievement_id']) ? (int) $params['achievement_id'] : 0; return ($unlocked_id > 0 && $unlocked_id === $target_id); } // WooCommerce: Specific Product Purchased or Refunded // Leaving product_id blank (0) makes the trigger fire for any product, // as the StoreEngine and LMS triggers do. A blank product used to fail // every order, so the rule silently paid nothing. if ($key === 'woocommerce_purchase_specific_product' || $key === 'woocommerce_refund_specific_product') { if (!function_exists('wc_get_order')) return false; $order = wc_get_order($args[0]); $target_id = isset($params['product_id']) ? (int) $params['product_id'] : 0; if (!$order) return false; if ($target_id <= 0) return true; foreach ($order->get_items() as $item) { if ((int) $item->get_product_id() === $target_id || (int) $item->get_variation_id() === $target_id) return true; } return false; } // WooCommerce: Refund Order takes back what a purchase earned. The // purchase triggers fire when an order is completed, so an order refunded // before that earned nothing and has nothing to take back. if ($key === 'woocommerce_refund_purchase') { if (!function_exists('wc_get_order')) return false; $order = wc_get_order($args[0]); return $order && null !== $order->get_date_completed(); } // WooCommerce: Specific Product Review Check if ($key === 'woocommerce_review_specific_product') { $comment = get_comment($args[0]); $target_id = isset($params['product_id']) ? (int) $params['product_id'] : 0; return ($comment && (int) $comment->comment_post_ID === $target_id); } // Academy LMS: Course ID Check (Completed or Enrolled) if ($key === 'academy_course_completed' || $key === 'academy_new_enrollment') { $current_course_id = isset($args[0]) ? absint($args[0]) : 0; $target_course_id = isset($params['course_id']) ? absint($params['course_id']) : 0; return (0 === $target_course_id || $current_course_id === $target_course_id); } // Academy LMS: Lesson ID Check if ($key === 'academy_lesson_completed') { $current_lesson_id = isset($args[2]) ? absint($args[2]) : 0; $target_lesson_id = isset($params['topic_id']) ? absint($params['topic_id']) : 0; return (0 === $target_lesson_id || $current_lesson_id === $target_lesson_id); } // Academy LMS: Quiz ID Check if ($key === 'academy_quiz_passed') { $attempt_data = $args[0]; $current_quiz_id = isset($attempt_data->quiz_id) ? absint($attempt_data->quiz_id) : 0; $target_quiz_id = isset($params['quiz_id']) ? absint($params['quiz_id']) : 0; return (0 === $target_quiz_id || $current_quiz_id === $target_quiz_id); } // ── Tutor LMS ──────────────────────────────────────────────────────── // Tutor LMS: Course ID Check (Completed or Enrolled) if ($key === 'tutor_course_completed' || $key === 'tutor_new_enrollment') { $current_course_id = isset($args[0]) ? absint($args[0]) : 0; $target_course_id = isset($params['course_id']) ? absint($params['course_id']) : 0; return (0 === $target_course_id || $current_course_id === $target_course_id); } // Tutor LMS: Lesson ID Check if ($key === 'tutor_lesson_completed') { $current_lesson_id = isset($args[0]) ? absint($args[0]) : 0; $target_lesson_id = isset($params['lesson_id']) ? absint($params['lesson_id']) : 0; return (0 === $target_lesson_id || $current_lesson_id === $target_lesson_id); } // Tutor LMS: Quiz ID Check (End or Passed) if ($key === 'tutor_quiz_ended' || $key === 'tutor_quiz_passed') { $attempt_id = isset($args[0]) ? absint($args[0]) : 0; $target_quiz_id = isset($params['quiz_id']) ? absint($params['quiz_id']) : 0; if (0 === $target_quiz_id) { return true; } if ($attempt_id > 0) { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Third-party LMS table has no API accessor; the value is read once per trigger evaluation and must be current. $quiz_id = $wpdb->get_var($wpdb->prepare("SELECT quiz_id FROM {$wpdb->prefix}tutor_quiz_attempts WHERE attempt_id = %d", $attempt_id)); return (absint($quiz_id) === $target_quiz_id); } return false; } // Tutor LMS: Assignment Submitted if ($key === 'tutor_assignment_submitted') { $current_assignment_id = isset($args[0]) ? absint($args[0]) : 0; $target_assignment_id = isset($params['assignment_id']) ? absint($params['assignment_id']) : 0; return (0 === $target_assignment_id || $current_assignment_id === $target_assignment_id); } // ── StoreEngine ─────────────────────────────────────────────────────── // StoreEngine: Purchase Specific Product // Hook args: ($order, $payload) — $args[0] is the SE Order object. // SE Order::get_items() returns objects with a public $product_id property. // Leaving product_id blank (0) makes the trigger fire for any product. if ($key === 'storeengine_purchase_specific_product') { $order = isset($args[0]) ? $args[0] : null; $target_id = isset($params['product_id']) ? absint($params['product_id']) : 0; if (!$order || !method_exists($order, 'get_items')) { return false; } // No product restriction configured — always pass. if ($target_id <= 0) { return true; } foreach ($order->get_items() as $item) { if (absint($item->product_id) === $target_id) { return true; } } return false; } // StoreEngine: Product Review on Specific Product // Hook args: ($comment_id, $comment_post_ID, $rating) — $args[1] is the product post ID. // Leaving product_id blank (0) makes the trigger fire for reviews on any SE product. if ($key === 'storeengine_product_review') { $target_id = isset($params['product_id']) ? absint($params['product_id']) : 0; $reviewed_product_id = isset($args[1]) ? absint($args[1]) : 0; return (0 === $target_id || $reviewed_product_id === $target_id); } return true; } /** * Validates if the user is allowed to earn rewards based on frequency limits. */ private function check_limit_validity($user_id, $requirement_id, $params) { global $wpdb; $limit_type = $params['limit'] ?? 'unlimited'; if ($limit_type === 'unlimited') return true; // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared $progress = $wpdb->get_row($wpdb->prepare( "SELECT * FROM {$wpdb->prefix}gameengine_requirement_progress WHERE user_id = %d AND requirement_id = %d", absint($user_id), absint($requirement_id) )); if (!$progress) return true; if ($limit_type === '1_time') return false; $last_update_time = strtotime($progress->last_updated); $current_time = current_time('timestamp'); // Check different time boundaries if ($limit_type === '1_per_day') return gmdate('Y-m-d', $last_update_time) !== gmdate('Y-m-d', $current_time); if ($limit_type === '1_per_week') return gmdate('W-Y', $last_update_time) !== gmdate('W-Y', $current_time); if ($limit_type === '1_per_month') return gmdate('m-Y', $last_update_time) !== gmdate('m-Y', $current_time); return true; } /** * Updates or creates the progress record for a specific requirement. * * @param int $user_id Acting user. * @param int $requirement_id Rule the user just satisfied. * @param object|null $rule The rule row, for the streak bonus. * @param array|null $params Decoded rule parameters. */ private function update_requirement_progress($user_id, $requirement_id, $rule = null, $params = null) { global $wpdb; $now = current_time('mysql'); $safe_uid = absint($user_id); $safe_rid = absint($requirement_id); // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared $progress = $wpdb->get_row($wpdb->prepare( "SELECT id, streak_count, streak_best, streak_last_at FROM {$wpdb->prefix}gameengine_requirement_progress WHERE user_id = %d AND requirement_id = %d", $safe_uid, $safe_rid )); $streak = $this->next_streak_state($safe_uid, $safe_rid, $progress, $params); if ($progress) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared $wpdb->query($wpdb->prepare( "UPDATE {$wpdb->prefix}gameengine_requirement_progress SET progress_count = progress_count + 1, streak_count = %d, streak_best = GREATEST(streak_best, %d), streak_last_at = %s, last_updated = %s WHERE id = %d", $streak['count'], $streak['count'], $streak['last_at'], $now, absint($progress->id) )); } else { // phpcs:ignore WordPress.DB.DirectDatabaseQuery $wpdb->insert($wpdb->prefix . 'gameengine_requirement_progress', [ 'user_id' => $safe_uid, 'requirement_id' => $safe_rid, 'progress_count' => 1, 'streak_count' => $streak['count'], 'streak_best' => $streak['count'], 'streak_last_at' => $streak['last_at'], 'last_updated' => $now ], ['%d', '%d', '%d', '%d', '%d', '%s', '%s']); } if ($streak['advanced']) { $this->maybe_award_streak_bonus($safe_uid, $rule, $params, $streak['count']); } } /** * The calendar bucket a moment falls in, counted from the epoch. * * Streaks are counted in calendar days and weeks, not in elapsed hours: * acting at 09:00 on Monday and 08:00 on Tuesday is two days in a row to * anyone looking at a calendar, but only 23 hours to a clock. Measuring * elapsed time meant a member who drifted a little earlier each day never * advanced, and eventually had the run broken while never missing a day. * This is also the unit the "Once Per Day" limit already uses, so the two * options sitting side by side now agree. * * @param int $timestamp Site-local timestamp. * @param string $interval 'daily' or 'weekly'. * @return int */ private static function streak_bucket($timestamp, $interval) { if ('weekly' !== $interval) { return (int) floor($timestamp / DAY_IN_SECONDS); } // The epoch was a Thursday (day 4), so shift the boundary onto the // site's own first day of the week before bucketing. $start_of_week = (int) get_option('start_of_week', 1); $offset = (4 - $start_of_week) * DAY_IN_SECONDS; return (int) floor(($timestamp + $offset) / WEEK_IN_SECONDS); } /** * Work out where a run of consecutive intervals stands after this firing. * * A trigger that fires twice inside one calendar interval only counts * once, a firing in the very next one extends the run, and skipping an * interval outright breaks it. * * @return array{count:int,last_at:string|null,advanced:bool} */ private function next_streak_state($user_id, $requirement_id, $progress, $params) { $interval = isset($params['streak_interval']) ? sanitize_key($params['streak_interval']) : 'off'; if ('daily' !== $interval && 'weekly' !== $interval) { return array( 'count' => $progress ? (int) $progress->streak_count : 0, 'last_at' => $progress ? $progress->streak_last_at : null, 'advanced' => false, ); } $now = current_time('timestamp'); $last_at = ($progress && ! empty($progress->streak_last_at)) ? strtotime($progress->streak_last_at) : 0; $previous = $progress ? (int) $progress->streak_count : 0; if (! $last_at || $previous < 1) { return array('count' => 1, 'last_at' => current_time('mysql'), 'advanced' => true); } $gap = self::streak_bucket($now, $interval) - self::streak_bucket($last_at, $interval); // Already counted for this day or week. if ($gap < 1) { return array('count' => $previous, 'last_at' => $progress->streak_last_at, 'advanced' => false); } if (1 === $gap) { return array('count' => $previous + 1, 'last_at' => current_time('mysql'), 'advanced' => true); } do_action('gameengine_streak_broken', $user_id, $requirement_id, $previous); return array('count' => 1, 'last_at' => current_time('mysql'), 'advanced' => true); } /** * Pay the streak bonus when the run lands on a multiple of the milestone. * * The bonus is its own points entry rather than an increase to the award * that triggered it, so the log keeps "you earned this" and "you kept it * up" apart. */ private function maybe_award_streak_bonus($user_id, $rule, $params, $count) { if (! $rule || 'point_type' !== $rule->reward_type || 'award' !== $rule->action_type) { return; } $milestone = isset($params['streak_milestone']) ? absint($params['streak_milestone']) : 0; if ($milestone < 1 || $count < 1 || 0 !== $count % $milestone) { return; } $bonus = isset($params['streak_bonus_points']) ? intval($params['streak_bonus_points']) : 0; /** * Filters the points paid for reaching a streak milestone. * * Deliberately not `gameengine_pro_point_amount`: that filter shapes * the award the trigger itself makes, and running a multiplier over * both would apply it twice. * * @param int $bonus Bonus points. * @param object $rule The rule that carries the streak options. * @param array $params Rule parameters. * @param int $count Length of the current run. */ $bonus = (int) apply_filters('gameengine_streak_bonus_points', $bonus, $rule, $params, $count); if ($bonus > 0) { $this->points_manager->add($user_id, $bonus, 'streak_milestone', array( 'point_type_id' => (int) $rule->reward_id, 'requirement_id' => (int) $rule->id, 'description' => sprintf( /* translators: 1: trigger label, 2: streak count */ __('%1$s streak milestone: %2$d in a row', 'gameengine'), $params['log_label'] ?? $rule->trigger_key, $count ), )); } /** * Fires when a user reaches a streak milestone on a trigger. * * @param int $user_id Acting user. * @param int $requirement_id The rule carrying the streak options. * @param int $count Length of the current run. */ do_action('gameengine_streak_milestone', $user_id, (int) $rule->id, $count); } /** * Every live run a user currently has going, for the profile shortcode. * * @param int $user_id User to report on. * @return array */ public static function get_user_streaks($user_id) { global $wpdb; $safe_uid = absint($user_id); if ($safe_uid <= 0) { return array(); } // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared $rows = $wpdb->get_results($wpdb->prepare( "SELECT r.trigger_key, r.parameters, p.streak_count, p.streak_best, p.streak_last_at FROM {$wpdb->prefix}gameengine_requirement_progress p JOIN {$wpdb->prefix}gameengine_requirements r ON r.id = p.requirement_id WHERE p.user_id = %d AND p.streak_count > 0 AND r.is_active = 1", $safe_uid ), ARRAY_A) ?: array(); $streaks = array(); foreach ($rows as $row) { $params = json_decode($row['parameters'], true); $interval = isset($params['streak_interval']) ? sanitize_key($params['streak_interval']) : 'off'; if ('daily' !== $interval && 'weekly' !== $interval) { continue; } // A run the user has already let lapse is not a live streak, even // though the row still holds its last count. $last_at = ! empty($row['streak_last_at']) ? strtotime($row['streak_last_at']) : 0; if (! $last_at) { continue; } $gap = self::streak_bucket(current_time('timestamp'), $interval) - self::streak_bucket($last_at, $interval); if ($gap > 1) { continue; } $streaks[] = array( 'label' => ! empty($params['log_label']) ? $params['log_label'] : $row['trigger_key'], 'interval' => $interval, 'count' => (int) $row['streak_count'], 'best' => (int) $row['streak_best'], 'milestone' => isset($params['streak_milestone']) ? absint($params['streak_milestone']) : 0, ); } return $streaks; } /** * Human label for the rule a streak event came from. * * The streak events carry a requirement id; this is what turns that back * into something worth putting in an email. * * @param int $requirement_id Rule id from a streak event. * @return string */ public static function get_streak_label($requirement_id) { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared $row = $wpdb->get_row($wpdb->prepare( "SELECT trigger_key, parameters FROM {$wpdb->prefix}gameengine_requirements WHERE id = %d", absint($requirement_id) ), ARRAY_A); if (! $row) { return ''; } $params = json_decode($row['parameters'], true); return ! empty($params['log_label']) ? $params['log_label'] : $row['trigger_key']; } /** * Zero out runs the user has let lapse, announcing each one. * * The break is also detected on the user's next firing, but that could be * weeks away; the daily sweep is what makes `gameengine_streak_broken` * arrive while it still means something to whoever is listening. */ public static function sweep_broken_streaks() { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared $rows = $wpdb->get_results( "SELECT p.id, p.user_id, p.requirement_id, p.streak_count, p.streak_last_at, r.parameters FROM {$wpdb->prefix}gameengine_requirement_progress p JOIN {$wpdb->prefix}gameengine_requirements r ON r.id = p.requirement_id WHERE p.streak_count > 0", ARRAY_A ) ?: array(); $now = current_time('timestamp'); foreach ($rows as $row) { $params = json_decode($row['parameters'], true); $interval = isset($params['streak_interval']) ? sanitize_key($params['streak_interval']) : 'off'; if ('daily' !== $interval && 'weekly' !== $interval) { continue; } $last_at = ! empty($row['streak_last_at']) ? strtotime($row['streak_last_at']) : 0; if ($last_at && (self::streak_bucket($now, $interval) - self::streak_bucket($last_at, $interval)) <= 1) { continue; } // phpcs:ignore WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared $wpdb->query($wpdb->prepare( "UPDATE {$wpdb->prefix}gameengine_requirement_progress SET streak_count = 0 WHERE id = %d", absint($row['id']) )); do_action('gameengine_streak_broken', (int) $row['user_id'], (int) $row['requirement_id'], (int) $row['streak_count']); } } }