| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383 |
- <?php
- if (!defined('WPINC')) {
- die;
- }
- class Studiou_WC_FPP_Single_Product {
- /** @var Studiou_WC_FPP_DB */
- private $db;
- public function __construct($db) {
- $this->db = $db;
- // Render upload cards UI at priority 35 on single product page.
- // Also suppress pvtfw's variant table + available-options button on FPP products.
- add_action('wp', array($this, 'maybe_suppress_pvtfw'), 5);
- add_action('woocommerce_single_product_summary', array($this, 'render_upload_area'), 35);
- // Add a body class on FPP product pages for CSS scoping
- add_filter('body_class', array($this, 'body_class'));
- // Server-side validation: block add-to-cart without photo (priority 1 = very early)
- add_filter('woocommerce_add_to_cart_validation', array($this, 'validate_add_to_cart'), 1, 6);
- // Safety net: if item was added without photo, remove it immediately
- add_action('woocommerce_add_to_cart', array($this, 'check_after_add_to_cart'), 10, 6);
- // AJAX: store uploaded file reference in WC session (legacy — shortcode path)
- add_action('wp_ajax_studiou_wcfpp_set_upload_session', array($this, 'ajax_set_upload_session'));
- add_action('wp_ajax_nopriv_studiou_wcfpp_set_upload_session', array($this, 'ajax_set_upload_session'));
- add_action('wp_ajax_studiou_wcfpp_clear_upload_session', array($this, 'ajax_clear_upload_session'));
- add_action('wp_ajax_nopriv_studiou_wcfpp_clear_upload_session', array($this, 'ajax_clear_upload_session'));
- }
- /**
- * Detach pvtfw's variant-table + available-options-button hooks on FPP products.
- *
- * pvtfw assigns its singletons to `$pvtfw_print_table` / `$pvtfw_available_btn` at the
- * top of its class files, but the `require_once` call lives inside pvtfw's
- * PVTFW_TABLE::includes() method — so those assignments end up as method-locals, NOT
- * true globals. We therefore reach the singletons via their static ::instance()
- * (the same object pvtfw registered the actions with). The variant-table hook and
- * priority are derived from pvtfw's own pvtfw_variant_table_place option (default
- * woocommerce_after_single_product_summary_9) so admin-configured placements
- * remain supported.
- */
- public function maybe_suppress_pvtfw() {
- if (!function_exists('is_product') || !is_product()) {
- return;
- }
- $product_id = get_queried_object_id();
- if (!$product_id || !Studiou_WC_FPP_Product::is_fpp_product($product_id)) {
- return;
- }
- if (class_exists('PVTFW_PRINT_TABLE')) {
- $print_table = PVTFW_PRINT_TABLE::instance();
- $place = get_option('pvtfw_variant_table_place', 'woocommerce_after_single_product_summary_9');
- $tail = strrchr((string) $place, '_');
- if ($tail !== false && strlen($tail) > 1) {
- $priority = (int) ltrim($tail, '_');
- $hook = substr($place, 0, -strlen($tail));
- if ($hook) {
- remove_action($hook, array($print_table, 'print_table'), $priority);
- }
- }
- } elseif (defined('WP_DEBUG') && WP_DEBUG) {
- error_log('STUDIOU FPP: PVTFW_PRINT_TABLE class not found; cannot detach pvtfw variant table.');
- }
- // Note: pvtfw's class name has a typo ("AVAILABE" missing the L) — match it verbatim
- if (class_exists('PVTFW_AVAILABE_BTN')) {
- $available_btn = PVTFW_AVAILABE_BTN::instance();
- remove_action('woocommerce_single_product_summary', array($available_btn, 'available_options_btn'), 11);
- }
- }
- public function body_class($classes) {
- if (function_exists('is_product') && is_product()) {
- $product_id = get_queried_object_id();
- if ($product_id && Studiou_WC_FPP_Product::is_fpp_product($product_id)) {
- $classes[] = 'studiou-fpp-product-page';
- }
- }
- return $classes;
- }
- public function render_upload_area() {
- global $product;
- if (!$product || !Studiou_WC_FPP_Product::is_fpp_product($product->get_id())) {
- return;
- }
- wp_enqueue_style('studiou-wcfpp-frontend');
- wp_enqueue_script('studiou-wcfpp-frontend');
- $product_id = $product->get_id();
- $max_file_size = Studiou_WC_FPP_Product::get_product_max_file_size($product_id);
- $max_uploads = Studiou_WC_FPP_Product::get_product_max_uploads($product_id);
- // Variant list (id, label, base_price, tiers) — injected into the files-cards JS
- $variants = $this->build_variant_list($product);
- // Existing batch files (rehydrate the card stack across reloads)
- $batch_files = self::resolve_batch_files($this->db, $product_id);
- $batch_cards = array();
- $hero_preview_url = '';
- foreach ($batch_files as $row) {
- $att_id = (int) $row->attachment_id;
- $thumb = wp_get_attachment_image_src($att_id, 'thumbnail');
- $preview = wp_get_attachment_image_src($att_id, 'woocommerce_single');
- if ($hero_preview_url === '') {
- $hero_preview_url = $preview ? $preview[0] : ($thumb ? $thumb[0] : '');
- }
- $batch_cards[] = array(
- 'file_record_id' => (int) $row->id,
- 'attachment_id' => $att_id,
- 'file_name' => (string) $row->file_name,
- 'thumb_url' => $thumb ? $thumb[0] : ($preview ? $preview[0] : ''),
- 'variation_id' => (int) $row->variation_id,
- );
- }
- wp_localize_script('studiou-wcfpp-frontend', 'studiouFppCardData', array(
- 'productId' => $product_id,
- 'variants' => $variants,
- 'maxUploads' => $max_uploads,
- 'batchFiles' => $batch_cards,
- 'heroPreviewUrl' => $hero_preview_url,
- ));
- // Keep studiouWcfppSession populated for legacy JS code paths that still read it
- wp_localize_script('studiou-wcfpp-frontend', 'studiouWcfppSession', array());
- include STUDIOU_WCFPP_PLUGIN_DIR . 'views/single-product-upload.php';
- if (is_product() && Studiou_WC_FPP_Product::is_fpp_product($product_id)) {
- // Render the order-overview panel below the cards (see views/single-product-order-overview.php)
- $cart = function_exists('WC') ? WC()->cart : null;
- include STUDIOU_WCFPP_PLUGIN_DIR . 'views/single-product-order-overview.php';
- }
- }
- /**
- * Produce the array of variation descriptors consumed by the upload-card JS.
- * One entry per in-stock, purchasable variation: id, label, base_price, tiers.
- */
- private function build_variant_list($product) {
- if (!$product || !$product->is_type('variable')) {
- return array();
- }
- $variants = array();
- foreach ($product->get_children() as $variation_id) {
- $variation = wc_get_product($variation_id);
- if (!$variation || !$variation->is_purchasable() || !$variation->variation_is_visible()) {
- continue;
- }
- $base_price = get_post_meta($variation_id, '_price', true);
- $label_parts = array();
- foreach ($variation->get_attributes() as $attr_name => $attr_value) {
- if ($attr_value === '') {
- continue;
- }
- $taxonomy = str_replace('attribute_', '', $attr_name);
- $term = taxonomy_exists($taxonomy) ? get_term_by('slug', $attr_value, $taxonomy) : null;
- $label_parts[] = $term ? $term->name : $attr_value;
- }
- $tiers = class_exists('Studiou_WC_FPP_Pricing')
- ? Studiou_WC_FPP_Pricing::get_tiers($variation_id)
- : array();
- $variants[] = array(
- 'id' => (int) $variation_id,
- 'label' => implode(' / ', $label_parts),
- 'base_price' => ($base_price !== '' && $base_price !== false) ? (float) $base_price : 0.0,
- 'tiers' => $tiers,
- 'in_stock' => $variation->is_in_stock(),
- );
- }
- return $variants;
- }
- /**
- * Resolve whether a product_id or its parent is FPP-enabled.
- */
- private function resolve_fpp_product_id($product_id, $variation_id = 0) {
- // Check direct product
- if (Studiou_WC_FPP_Product::is_fpp_product($product_id)) {
- return $product_id;
- }
- // Check parent of the product (in case product_id is variation)
- $product = wc_get_product($product_id);
- if ($product && $product->get_parent_id() && Studiou_WC_FPP_Product::is_fpp_product($product->get_parent_id())) {
- return $product->get_parent_id();
- }
- // Check variation_id's parent
- if ($variation_id && $variation_id !== $product_id) {
- $variation = wc_get_product($variation_id);
- if ($variation && $variation->get_parent_id() && Studiou_WC_FPP_Product::is_fpp_product($variation->get_parent_id())) {
- return $variation->get_parent_id();
- }
- }
- return false;
- }
- /**
- * Validate before add-to-cart: block if FPP product and no photo reference resolvable.
- *
- * 1.5.0: the per-card Add-to-Cart path pre-stamps $cart_item_data['studiou_fpp_file_record_id']
- * via our ajax_add_file_to_cart handler — accept that as the primary signal. Fall back to the
- * legacy visitor-level resolver for the shortcode path.
- */
- public function validate_add_to_cart($passed, $product_id, $quantity, $variation_id = 0, $variations = array(), $cart_item_data = array()) {
- $fpp_id = $this->resolve_fpp_product_id($product_id, $variation_id);
- if (!$fpp_id) {
- return $passed;
- }
- if (!empty($cart_item_data['studiou_fpp_file_record_id'])) {
- $record = $this->db->get_file_record((int) $cart_item_data['studiou_fpp_file_record_id']);
- if ($record && (int) $record->order_id === 0) {
- return $passed;
- }
- }
- if (self::resolve_uploaded_file($this->db)) {
- return $passed;
- }
- wc_add_notice(__('Please upload a photo before adding to cart.', 'studiou-wc-free-photo-product'), 'error');
- return false;
- }
- /**
- * Return all upload records belonging to the current visitor's batch
- * that are not yet attached to an order, optionally scoped to a product.
- *
- * @return array<int,object> list of DB rows, oldest first (ascending id)
- */
- public static function resolve_batch_files(Studiou_WC_FPP_DB $db, $product_id = 0) {
- $token = Studiou_WC_FPP_Upload::get_batch_token();
- if (empty($token)) {
- return array();
- }
- return $db->get_batch_files($token, (int) $product_id);
- }
- /**
- * Resolve the currently "attached" upload for this visitor (legacy single-file path).
- * Checks WC session first, then legacy cookie pair, and finally the first file in the
- * current batch as a last-resort fallback. Used only by the shortcode flow on 1.5+ —
- * the product-detail page uses resolve_batch_files() and pre-stamped file_record_id.
- *
- * @return array{attachment_id:int,file_record_id:int,file_name:string,thumb_url:string}|null
- */
- public static function resolve_uploaded_file(Studiou_WC_FPP_DB $db) {
- $attachment_id = 0;
- $file_record_id = 0;
- $file_name = '';
- $thumb_url = '';
- if (function_exists('WC') && WC()->session) {
- $attachment_id = (int) WC()->session->get('studiou_fpp_attachment_id');
- $file_record_id = (int) WC()->session->get('studiou_fpp_file_record_id');
- $file_name = (string) WC()->session->get('studiou_fpp_file_name');
- $thumb_url = (string) WC()->session->get('studiou_fpp_thumb_url');
- }
- if ($attachment_id <= 0 || $file_record_id <= 0) {
- $cookie_att = isset($_COOKIE[Studiou_WC_FPP_Upload::COOKIE_ATTACHMENT])
- ? (int) $_COOKIE[Studiou_WC_FPP_Upload::COOKIE_ATTACHMENT] : 0;
- $cookie_rec = isset($_COOKIE[Studiou_WC_FPP_Upload::COOKIE_RECORD])
- ? (int) $_COOKIE[Studiou_WC_FPP_Upload::COOKIE_RECORD] : 0;
- if ($cookie_att > 0 && $cookie_rec > 0) {
- $attachment_id = $cookie_att;
- $file_record_id = $cookie_rec;
- $file_name = '';
- $thumb_url = '';
- }
- }
- if ($attachment_id <= 0 || $file_record_id <= 0) {
- return null;
- }
- $record = $db->get_file_record($file_record_id);
- if (!$record) {
- return null;
- }
- if ((int) $record->attachment_id !== $attachment_id) {
- return null;
- }
- // A record already attached to an order is no longer "in flight" for add-to-cart
- if ((int) $record->order_id !== 0) {
- return null;
- }
- if ($file_name === '') {
- $file_name = (string) $record->file_name;
- }
- if ($thumb_url === '') {
- $thumb = wp_get_attachment_image_src($attachment_id, 'thumbnail');
- if ($thumb) {
- $thumb_url = $thumb[0];
- } else {
- $thumb_url = (string) wp_get_attachment_url($attachment_id);
- }
- }
- return array(
- 'attachment_id' => $attachment_id,
- 'file_record_id' => $file_record_id,
- 'file_name' => $file_name,
- 'thumb_url' => $thumb_url,
- );
- }
- /**
- * Safety net: if an FPP item was added without photo data, remove it.
- * This catches cases where validation was somehow bypassed.
- */
- public function check_after_add_to_cart($cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data) {
- $fpp_id = $this->resolve_fpp_product_id($product_id, $variation_id);
- if (!$fpp_id) {
- return;
- }
- // If the cart item has no FPP attachment, remove it
- if (empty($cart_item_data['studiou_fpp_attachment_id'])) {
- WC()->cart->remove_cart_item($cart_item_key);
- wc_add_notice(__('Please upload a photo before adding to cart.', 'studiou-wc-free-photo-product'), 'error');
- }
- }
- public function ajax_set_upload_session() {
- check_ajax_referer('studiou-wcfpp-front-nonce', 'nonce');
- $attachment_id = isset($_POST['attachment_id']) ? absint($_POST['attachment_id']) : 0;
- $file_record_id = isset($_POST['file_record_id']) ? absint($_POST['file_record_id']) : 0;
- $file_name = isset($_POST['file_name']) ? sanitize_text_field($_POST['file_name']) : '';
- if (!$attachment_id || !$file_record_id) {
- wp_send_json_error(array('message' => __('Invalid file data.', 'studiou-wc-free-photo-product')));
- return;
- }
- if (WC()->session) {
- WC()->session->set('studiou_fpp_attachment_id', $attachment_id);
- WC()->session->set('studiou_fpp_file_record_id', $file_record_id);
- WC()->session->set('studiou_fpp_file_name', $file_name);
- // Store thumbnail URL directly so it can be used in cart without wp_get_attachment lookup
- $thumb_url = '';
- $thumb = wp_get_attachment_image_src($attachment_id, 'thumbnail');
- if ($thumb) {
- $thumb_url = $thumb[0];
- } else {
- $thumb_url = wp_get_attachment_url($attachment_id);
- }
- WC()->session->set('studiou_fpp_thumb_url', $thumb_url ?: '');
- }
- wp_send_json_success();
- }
- public function ajax_clear_upload_session() {
- check_ajax_referer('studiou-wcfpp-front-nonce', 'nonce');
- if (WC()->session) {
- WC()->session->set('studiou_fpp_attachment_id', null);
- WC()->session->set('studiou_fpp_file_record_id', null);
- WC()->session->set('studiou_fpp_file_name', null);
- WC()->session->set('studiou_fpp_thumb_url', null);
- }
- Studiou_WC_FPP_Upload::clear_upload_cookies();
- wp_send_json_success();
- }
- }
|