enabled()) { if (wp_next_scheduled('afop_stock_daily_check')) { wp_clear_scheduled_hook('afop_stock_daily_check'); } if (wp_next_scheduled('afop_stock_changed_check')) { wp_clear_scheduled_hook('afop_stock_changed_check'); } return; } if (!wp_next_scheduled('afop_stock_daily_check')) { wp_schedule_event(time() + MINUTE_IN_SECONDS, 'daily', 'afop_stock_daily_check'); } } /** Coalesce stock changes; never send email inside a checkout request. */ public function stock_changed() { $this->results = array(); if ($this->enabled() && !wp_next_scheduled('afop_stock_changed_check')) { wp_schedule_single_event(time() + 30, 'afop_stock_changed_check'); } } /** * WooCommerce's stock lookup avoids scanning the entire catalog in PHP. * The own-stock meta check excludes variations inheriting a parent's stock. * Draft/private/trashed products and children of unpublished parents are omitted. */ public function low_stock($page = 1, $limit = 20) { if (!$this->enabled()) { return array('products' => array(), 'total' => 0); } $page = max(1, (int) $page); $limit = max(1, min(100, (int) $limit)); $key = $this->threshold() . ':' . $page . ':' . $limit; if (isset($this->results[$key])) { return $this->results[$key]; } global $wpdb; $lookup = $wpdb->prefix . 'wc_product_meta_lookup'; $from = $wpdb->prepare( "FROM %i AS inventory INNER JOIN %i AS product ON product.ID = inventory.product_id WHERE product.post_type IN ('product', 'product_variation') AND product.post_status = 'publish' AND inventory.stock_quantity IS NOT NULL AND inventory.stock_quantity <= %d AND EXISTS (SELECT 1 FROM %i AS stock_setting WHERE stock_setting.post_id = product.ID AND stock_setting.meta_key = '_manage_stock' AND stock_setting.meta_value = 'yes') AND (product.post_type = 'product' OR EXISTS (SELECT 1 FROM %i AS parent WHERE parent.ID = product.post_parent AND parent.post_status = 'publish' AND parent.post_type = 'product'))", $lookup, $wpdb->posts, $this->threshold(), $wpdb->postmeta, $wpdb->posts ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.NotPrepared -- Fully prepared lookup query; inventory must reflect current quantities in this request. $total = (int) $wpdb->get_var('SELECT COUNT(*) ' . $from); $pagination = $wpdb->prepare(' ORDER BY inventory.stock_quantity ASC, product.ID ASC LIMIT %d OFFSET %d', $limit, ($page - 1) * $limit); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.PreparedSQL.NotPrepared -- Both SQL fragments are prepared above; bounded IDs hydrate through WooCommerce CRUD. $ids = $wpdb->get_col('SELECT product.ID ' . $from . $pagination); $products = array(); foreach ($ids as $id) { $product = wc_get_product($id); if ($product && $product->get_manage_stock('edit') === true && $product->get_stock_quantity('edit') !== null && $product->get_stock_quantity('edit') <= $this->threshold()) { $products[] = $product; } } $this->results[$key] = array('products' => $products, 'total' => $total); return $this->results[$key]; } public function register_menu() { add_submenu_page('afop-settings', __('Low Stock & Alerts', 'advance-fake-order-protector'), __('Stock Alerts', 'advance-fake-order-protector'), 'manage_woocommerce', 'afop-stock-alerts', array($this, 'render_page')); } private function page_url() { return admin_url('admin.php?page=afop-stock-alerts'); } private function edit_url($product) { $id = $product->is_type('variation') ? $product->get_parent_id() : $product->get_id(); return admin_url('post.php?post=' . absint($id) . '&action=edit'); } public function save_settings() { if (!current_user_can('manage_woocommerce')) { wp_die(esc_html__('You cannot manage stock alerts.', 'advance-fake-order-protector'), '', array('response' => 403)); } check_admin_referer('afop_save_stock_alerts'); $email = isset($_POST['afop_stock_alert_email']) ? sanitize_email(wp_unslash($_POST['afop_stock_alert_email'])) : ''; $raw_email = isset($_POST['afop_stock_alert_email']) ? trim(sanitize_text_field(wp_unslash($_POST['afop_stock_alert_email']))) : ''; if ($raw_email !== '' && (!is_email($email) || $email !== $raw_email)) { wp_safe_redirect(add_query_arg('afop_stock_error', 'email', $this->page_url())); exit; } $threshold = isset($_POST['afop_stock_alert_threshold']) ? max(0, min(1000000, (int) $_POST['afop_stock_alert_threshold'])) : 20; update_option('afop_stock_alert_threshold', $threshold, false); update_option('afop_stock_alert_email', $email, false); update_option('afop_stock_alerts_enabled', isset($_POST['afop_stock_alerts_enabled']) ? 'yes' : 'no', false); $this->results = array(); $this->sync_schedule(); $this->stock_changed(); wp_safe_redirect(add_query_arg('afop_stock_saved', '1', $this->page_url())); exit; } public function render_page() { if (!current_user_can('manage_woocommerce')) { return; } // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only pagination; access is checked above and all settings writes require a nonce. $page = isset($_GET['paged']) ? max(1, absint($_GET['paged'])) : 1; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- This flag only displays a fixed confirmation message; it changes no settings. $saved = isset($_GET['afop_stock_saved']); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- This flag only displays a fixed validation message; it changes no settings. $error = isset($_GET['afop_stock_error']); $data = $this->low_stock($page); ?>
v


enabled() ? __('Active', 'advance-fake-order-protector') : __('Off', 'advance-fake-order-protector')); ?>
threshold()); ?>

enabled()) : ?>

threshold())); ?>

get_name()); ?> #get_id()); ?>get_sku() ?: '—'); ?>get_stock_quantity('edit'), $product)); ?> is_type('variation') ? $product->get_parent_id() : $product->get_id(); ?>

add_query_arg('paged', '%#%', $this->page_url()), 'format' => '', 'current' => $page, 'total' => max(1, (int) ceil($data['total'] / 20))))); ?>

enabled() || !current_user_can('manage_woocommerce')) { return; } wp_enqueue_style('afop-stock-notice', AFOP_PLUGIN_URL . 'assets/css/afop-stock-alerts.css', array(), AFOP_VERSION); wp_enqueue_script('afop-stock-alerts', AFOP_PLUGIN_URL . 'assets/js/afop-stock-alerts.js', array('jquery'), AFOP_VERSION, true); wp_localize_script('afop-stock-alerts', 'afopStockAlerts', array('url' => admin_url('admin-ajax.php'), 'nonce' => wp_create_nonce('afop_dismiss_stock_notice'))); } public function render_notice() { if (!$this->enabled() || !current_user_can('manage_woocommerce') || get_user_meta(get_current_user_id(), 'afop_stock_notice_dismissed', true) === $this->today()) { return; } $data = $this->low_stock(1, 5); if (!$data['products']) { return; } ?>

__('Not allowed.', 'advance-fake-order-protector')), 403); } check_ajax_referer('afop_dismiss_stock_notice', 'nonce'); update_user_meta(get_current_user_id(), 'afop_stock_notice_dismissed', $this->today()); wp_send_json_success(); } /** A site-wide atomic lock and local-calendar date prevent duplicate digests. */ public function send_daily_email() { if (!$this->enabled()) { return; } $lock = get_option('afop_stock_email_lock'); if (is_array($lock) && isset($lock['time']) && (int) $lock['time'] < time() - 5 * MINUTE_IN_SECONDS) { delete_option('afop_stock_email_lock'); } $token = array('time' => time(), 'token' => wp_generate_uuid4()); if (!add_option('afop_stock_email_lock', $token, '', false)) { return; } try { if (get_option('afop_stock_email_sent_day') === $this->today() || !$this->enabled()) { return; } $this->results = array(); $data = $this->low_stock(1, 100); if (!$data['products']) { return; } $recipient = get_option('afop_stock_alert_email', ''); if ($recipient === '') { $recipient = get_option('admin_email'); } if (!is_email($recipient)) { return; } $site = wp_specialchars_decode(get_bloginfo('name'), ENT_QUOTES); $site = str_replace(array("\r", "\n"), ' ', $site); $subject = sprintf(/* translators: %s: site name. */ __('[%s] Low stock reminder', 'advance-fake-order-protector'), $site); $lines = array( sprintf(/* translators: %d: stock threshold. */ __('Your store has products with %d units or fewer. Please review and replenish stock.', 'advance-fake-order-protector'), $this->threshold()), '', ); foreach ($data['products'] as $product) { $lines[] = sprintf(/* translators: 1: product name, 2: product ID, 3: SKU, 4: remaining quantity. */ __('%1$s (ID: %2$d, SKU: %3$s) — stock remaining: %4$s', 'advance-fake-order-protector'), wp_strip_all_tags($product->get_name(), true), $product->get_id(), $product->get_sku(), $product->get_stock_quantity('edit')); $lines[] = $this->edit_url($product); $lines[] = ''; } $lines[] = __('View all low-stock products / change or disable alerts:', 'advance-fake-order-protector'); $lines[] = $this->page_url(); $lines[] = __('This digest lists up to 100 products. The admin list includes all matching products. At most one email is sent per site calendar day.', 'advance-fake-order-protector'); if (wp_mail($recipient, $subject, implode("\n", $lines), array('Content-Type: text/plain; charset=UTF-8'))) { update_option('afop_stock_email_sent_day', $this->today(), false); } } finally { if (get_option('afop_stock_email_lock') === $token) { delete_option('afop_stock_email_lock'); } } } }