/** * Plugin Name: Therapy Theo Points * Description: Therapy Theo internal points foundation: account ledger and one-time downloadable-file upload bonuses. * Version: 0.2.0 * Requires at least: 6.8 * Requires PHP: 8.1 * Author: Therapy Theo * Text Domain: therapy-theo-points */ if ( ! defined( 'ABSPATH' ) ) { exit; } final class Therapy_Theo_Points { const VERSION = '0.2.0'; const BONUS_PER_FILE = 20; const TABLE_SUFFIX = 'tt_points_ledger'; const SHORTCODE = 'therapy_theo_points_balance'; public function __construct() { register_activation_hook( __FILE__, array( __CLASS__, 'activate' ) ); add_action( 'woocommerce_new_product', array( $this, 'maybe_award_upload_bonus' ), 30, 1 ); add_action( 'woocommerce_update_product', array( $this, 'maybe_award_upload_bonus' ), 30, 1 ); add_action( 'transition_post_status', array( $this, 'maybe_award_on_publish' ), 30, 3 ); add_shortcode( self::SHORTCODE, array( $this, 'balance_shortcode' ) ); add_action( 'admin_menu', array( $this, 'admin_menu' ) ); add_action( 'admin_notices', array( $this, 'dependency_notice' ) ); // Register the points-price metadata used by the MultiVendorX product editor. add_action( 'init', array( $this, 'register_points_price_meta' ) ); add_action( 'wp_enqueue_scripts', array( $this, 'add_multivendorx_product_price_field' ), 100 ); } public static function activate() { global $wpdb; require_once ABSPATH . 'wp-admin/includes/upgrade.php'; $table = $wpdb->prefix . self::TABLE_SUFFIX; $charset_collate = $wpdb->get_charset_collate(); $sql = "CREATE TABLE {$table} ( id bigint(20) unsigned NOT NULL AUTO_INCREMENT, user_id bigint(20) unsigned NOT NULL, amount bigint(20) NOT NULL, entry_type varchar(40) NOT NULL, reference_id bigint(20) unsigned NOT NULL DEFAULT 0, event_key varchar(191) NOT NULL, note text NULL, created_at datetime NOT NULL, PRIMARY KEY (id), UNIQUE KEY event_key (event_key), KEY user_id (user_id), KEY entry_type (entry_type), KEY created_at (created_at) ) {$charset_collate};"; dbDelta( $sql ); update_option( 'therapy_theo_points_db_version', self::VERSION ); // Mark files already present at activation as existing, so activation // does not retroactively award bonuses for old uploads. self::baseline_existing_downloads(); } private static function baseline_existing_downloads() { if ( ! function_exists( 'wc_get_product' ) ) { return; } $product_ids = get_posts( array( 'post_type' => 'product', 'post_status' => 'publish', 'posts_per_page' => -1, 'fields' => 'ids', 'meta_query' => array( array( 'key' => '_downloadable', 'value' => 'yes', 'compare' => '=', ), ), ) ); foreach ( $product_ids as $product_id ) { $product = wc_get_product( $product_id ); if ( ! $product || ! $product->is_downloadable() ) { continue; } $known = array(); foreach ( $product->get_downloads() as $download ) { if ( is_object( $download ) && method_exists( $download, 'get_file' ) ) { $identity = self::file_identity_static( $download->get_file() ); if ( $identity ) { $known[] = hash( 'sha256', $identity ); } } } update_post_meta( $product_id, '_tt_points_seen_downloads', array_values( array_unique( $known ) ) ); } } private function table_name() { global $wpdb; return $wpdb->prefix . self::TABLE_SUFFIX; } /** * Add a ledger entry exactly once. The unique event_key prevents duplicate awards. */ private function add_points_once( $user_id, $amount, $entry_type, $reference_id, $event_key, $note ) { global $wpdb; $user_id = absint( $user_id ); $amount = (int) $amount; $reference_id = absint( $reference_id ); if ( ! $user_id || $amount <= 0 || ! is_string( $event_key ) || '' === $event_key ) { return false; } $inserted = $wpdb->insert( $this->table_name(), array( 'user_id' => $user_id, 'amount' => $amount, 'entry_type' => sanitize_key( $entry_type ), 'reference_id' => $reference_id, 'event_key' => substr( sanitize_text_field( $event_key ), 0, 191 ), 'note' => sanitize_textarea_field( $note ), 'created_at' => current_time( 'mysql', true ), ), array( '%d', '%d', '%s', '%d', '%s', '%s', '%s' ) ); return ( 1 === $inserted ); } private function get_balance( $user_id ) { global $wpdb; $balance = $wpdb->get_var( $wpdb->prepare( "SELECT COALESCE(SUM(amount), 0) FROM {$this->table_name()} WHERE user_id = %d", absint( $user_id ) ) ); return (int) $balance; } /** * MultiVendorX 5.x uses Store Owners. We deliberately require a store-owner * capability/role so ordinary customer or administrator uploads do not earn bonuses. */ private function is_store_owner( $user_id ) { $user = get_user_by( 'id', absint( $user_id ) ); if ( ! $user ) { return false; } $known_roles = array( 'store_owner', 'dc_vendor', 'mvx_vendor' ); if ( array_intersect( $known_roles, (array) $user->roles ) ) { return true; } $known_caps = array( 'edit_stores', 'manage_store', 'manage_woocommerce_store' ); foreach ( $known_caps as $cap ) { if ( user_can( $user, $cap ) ) { return true; } } return false; } private static function file_identity_static( $file_url ) { $file_url = trim( (string) $file_url ); if ( '' === $file_url ) { return ''; } $uploads = wp_upload_dir(); $baseurl = isset( $uploads['baseurl'] ) ? untrailingslashit( $uploads['baseurl'] ) : ''; $basedir = isset( $uploads['basedir'] ) ? untrailingslashit( $uploads['basedir'] ) : ''; // For files in WordPress uploads, identify the actual file contents. if ( $baseurl && $basedir && 0 === strpos( $file_url, $baseurl . '/' ) ) { $relative = rawurldecode( substr( $file_url, strlen( $baseurl ) + 1 ) ); $path = realpath( $basedir . '/' . ltrim( $relative, '/' ) ); $root = realpath( $basedir ); if ( $path && $root && 0 === strpos( $path, $root . DIRECTORY_SEPARATOR ) && is_file( $path ) && is_readable( $path ) ) { $content_hash = hash_file( 'sha256', $path ); if ( $content_hash ) { return 'sha256:' . $content_hash; } } } // External/protected URLs: use a normalized URL identity. $normalized = esc_url_raw( $file_url ); return $normalized ? 'url:' . hash( 'sha256', $normalized ) : ''; } public function maybe_award_on_publish( $new_status, $old_status, $post ) { if ( 'publish' === $new_status && $post instanceof WP_Post && 'product' === $post->post_type ) { $this->maybe_award_upload_bonus( $post->ID ); } } public function maybe_award_upload_bonus( $product_id ) { if ( ! function_exists( 'wc_get_product' ) ) { return; } $product_id = absint( $product_id ); $product = wc_get_product( $product_id ); if ( ! $product || ! $product->is_downloadable() || 'publish' !== get_post_status( $product_id ) ) { return; } $author_id = absint( get_post_field( 'post_author', $product_id ) ); if ( ! $author_id || ! $this->is_store_owner( $author_id ) ) { return; } $downloads = $product->get_downloads(); if ( empty( $downloads ) || ! is_array( $downloads ) ) { return; } $seen = get_post_meta( $product_id, '_tt_points_seen_downloads', true ); $seen = is_array( $seen ) ? $seen : array(); foreach ( $downloads as $download ) { if ( ! is_object( $download ) || ! method_exists( $download, 'get_file' ) ) { continue; } $identity = self::file_identity_static( $download->get_file() ); if ( '' === $identity ) { continue; } $file_hash = hash( 'sha256', $identity ); if ( in_array( $file_hash, $seen, true ) ) { continue; } $event_key = 'upload_bonus_' . $author_id . '_' . $file_hash; $this->add_points_once( $author_id, self::BONUS_PER_FILE, 'upload_bonus', $product_id, $event_key, sprintf( '20-point upload bonus for downloadable file in product #%d', $product_id ) ); // Mark as seen even if this exact file was already rewarded in // another product by the same user; the ledger remains the source of truth. $seen[] = $file_hash; } update_post_meta( $product_id, '_tt_points_seen_downloads', array_values( array_unique( $seen ) ) ); } /** * Register a REST-visible product meta field for the vendor dashboard. */ public function register_points_price_meta() { register_post_meta( 'product', 'tt_price_points', array( 'type' => 'integer', 'single' => true, 'show_in_rest' => true, 'sanitize_callback' => 'absint', 'auth_callback' => function ( $allowed, $meta_key, $post_id ) { return current_user_can( 'edit_post', $post_id ); }, ) ); } /** * Add the "Price in points" field through MultiVendorX's documented JS filter. * The inline script is placed before the MultiVendorX dashboard bundle so * the filter exists before the React product editor is rendered. */ public function add_multivendorx_product_price_field() { if ( is_admin() || ! wp_script_is( 'multivendorx-dashboard-script', 'registered' ) ) { return; } $script = <<<'JS' (function (wp) { if (!wp || !wp.hooks || !wp.element) { return; } var createElement = wp.element.createElement; var Fragment = wp.element.Fragment; function addPointsPriceField(content, product, setProduct) { if (!product || typeof setProduct !== 'function') { return content; } var meta = Array.isArray(product.meta_data) ? product.meta_data : []; var saved = meta.find(function (item) { return item && item.key === 'tt_price_points'; }); var value = saved && saved.value !== undefined ? String(saved.value) : ''; var field = createElement( 'div', { className: 'form-group tt-points-price-field', style: { marginTop: '16px' } }, createElement( 'label', { className: 'settings-form-label', htmlFor: 'tt-price-in-points' }, 'Price in points' ), createElement( 'div', { className: 'settings-input-content' }, createElement('input', { id: 'tt-price-in-points', className: 'regular-text', name: 'tt_price_points', type: 'number', min: '1', step: '1', value: value, onChange: function (event) { var raw = event.target.value; setProduct(function (previous) { var current = Array.isArray(previous.meta_data) ? previous.meta_data : []; var updated = current.filter(function (item) { return !item || item.key !== 'tt_price_points'; }); if (raw !== '' && Number(raw) > 0) { updated.push({ key: 'tt_price_points', value: String(Math.floor(Number(raw))) }); } return Object.assign({}, previous, { meta_data: updated }); }); } }), createElement( 'div', { className: 'settings-metabox-description' }, 'Enter the number of points a customer must spend to download this file.' ) ) ); return createElement(Fragment, null, content, field); } wp.hooks.addFilter( 'multivendorx_add_product_middle_section', 'therapy-theo-points/price-in-points', addPointsPriceField, 20 ); })(window.wp); JS; wp_add_inline_script( 'multivendorx-dashboard-script', $script, 'before' ); } public function balance_shortcode() { if ( ! is_user_logged_in() ) { return '

' . esc_html__( 'Log in to view your points balance.', 'therapy-theo-points' ) . '

'; } $balance = $this->get_balance( get_current_user_id() ); return '
' . esc_html__( 'Your points balance:', 'therapy-theo-points' ) . ' ' . esc_html( number_format_i18n( $balance ) ) . '
'; } public function admin_menu() { add_menu_page( __( 'Therapy Theo Points', 'therapy-theo-points' ), __( 'Therapy Theo Points', 'therapy-theo-points' ), 'manage_options', 'therapy-theo-points', array( $this, 'render_admin_page' ), 'dashicons-awards', 58 ); } public function render_admin_page() { if ( ! current_user_can( 'manage_options' ) ) { return; } global $wpdb; $table = $this->table_name(); $rows = $wpdb->get_results( "SELECT l.*, u.user_login, u.display_name FROM {$table} l LEFT JOIN {$wpdb->users} u ON u.ID = l.user_id ORDER BY l.id DESC LIMIT 100" ); $balances = $wpdb->get_results( "SELECT user_id, SUM(amount) AS balance FROM {$table} GROUP BY user_id ORDER BY balance DESC LIMIT 100" ); echo '

' . esc_html__( 'Therapy Theo Points', 'therapy-theo-points' ) . '

'; echo '

' . esc_html__( 'Foundation version: balances are calculated from the transaction ledger. Each unique downloadable file earns its Store Owner 20 points once, after the product is published.', 'therapy-theo-points' ) . '

'; echo '

' . esc_html__( 'Account balances', 'therapy-theo-points' ) . '

'; echo ''; if ( $balances ) { foreach ( $balances as $balance ) { $user = get_user_by( 'id', (int) $balance->user_id ); echo ''; echo ''; echo ''; } } else { echo ''; } echo '
UserUser IDBalance
' . esc_html( $user ? $user->display_name : __( 'Deleted user', 'therapy-theo-points' ) ) . '' . esc_html( (string) $balance->user_id ) . '' . esc_html( number_format_i18n( (int) $balance->balance ) ) . '
' . esc_html__( 'No point transactions yet.', 'therapy-theo-points' ) . '
'; echo '

' . esc_html__( 'Latest transactions', 'therapy-theo-points' ) . '

'; echo ''; if ( $rows ) { foreach ( $rows as $row ) { echo ''; echo ''; echo ''; echo ''; echo ''; echo ''; } } else { echo ''; } echo '
Date (UTC)UserTypePointsReferenceNote
' . esc_html( $row->created_at ) . '' . esc_html( $row->display_name ? $row->display_name : $row->user_login ) . '' . esc_html( $row->entry_type ) . '' . esc_html( (string) $row->amount ) . '' . esc_html( (string) $row->reference_id ) . '' . esc_html( $row->note ) . '
' . esc_html__( 'No point transactions yet.', 'therapy-theo-points' ) . '
'; echo '

' . esc_html__( 'Important:', 'therapy-theo-points' ) . ' ' . esc_html__( 'This is the foundation only. Point-package purchases, spending points at checkout, seller transfers, refunds, and own-product purchase restrictions are not enabled in this version.', 'therapy-theo-points' ) . '

'; } public function dependency_notice() { if ( ! current_user_can( 'activate_plugins' ) || function_exists( 'wc_get_product' ) ) { return; } echo '

' . esc_html__( 'Therapy Theo Points requires WooCommerce to be active.', 'therapy-theo-points' ) . '

'; } } new Therapy_Theo_Points(); Therapy Theo – Study materials for OTs, PTs, SLTs and SETs
Knowledge That Matters

Knowledge That Matters

Share your personally created study materials and discover new ways of learning!

♥ Occupational Therapy
♥ Physiotherapy
♥ Special Education
♥ Speech-Language Pathology
You can upload in any language.
Check out our 50+ subject categories!