class-studiou-wc-fpp-single-product.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. <?php
  2. if (!defined('WPINC')) {
  3. die;
  4. }
  5. class Studiou_WC_FPP_Single_Product {
  6. /** @var Studiou_WC_FPP_DB */
  7. private $db;
  8. public function __construct($db) {
  9. $this->db = $db;
  10. // Render upload cards UI at priority 35 on single product page.
  11. // Also suppress pvtfw's variant table + available-options button on FPP products.
  12. add_action('wp', array($this, 'maybe_suppress_pvtfw'), 5);
  13. add_action('woocommerce_single_product_summary', array($this, 'render_upload_area'), 35);
  14. // Add a body class on FPP product pages for CSS scoping
  15. add_filter('body_class', array($this, 'body_class'));
  16. // Server-side validation: block add-to-cart without photo (priority 1 = very early)
  17. add_filter('woocommerce_add_to_cart_validation', array($this, 'validate_add_to_cart'), 1, 6);
  18. // Safety net: if item was added without photo, remove it immediately
  19. add_action('woocommerce_add_to_cart', array($this, 'check_after_add_to_cart'), 10, 6);
  20. }
  21. /**
  22. * Detach pvtfw's variant-table + available-options-button hooks on FPP products.
  23. *
  24. * pvtfw assigns its singletons to `$pvtfw_print_table` / `$pvtfw_available_btn` at the
  25. * top of its class files, but the `require_once` call lives inside pvtfw's
  26. * PVTFW_TABLE::includes() method — so those assignments end up as method-locals, NOT
  27. * true globals. We therefore reach the singletons via their static ::instance()
  28. * (the same object pvtfw registered the actions with). The variant-table hook and
  29. * priority are derived from pvtfw's own pvtfw_variant_table_place option (default
  30. * woocommerce_after_single_product_summary_9) so admin-configured placements
  31. * remain supported.
  32. */
  33. public function maybe_suppress_pvtfw() {
  34. if (!function_exists('is_product') || !is_product()) {
  35. return;
  36. }
  37. $product_id = get_queried_object_id();
  38. if (!$product_id || !Studiou_WC_FPP_Product::is_fpp_product($product_id)) {
  39. return;
  40. }
  41. if (class_exists('PVTFW_PRINT_TABLE')) {
  42. $print_table = PVTFW_PRINT_TABLE::instance();
  43. $place = get_option('pvtfw_variant_table_place', 'woocommerce_after_single_product_summary_9');
  44. $tail = strrchr((string) $place, '_');
  45. if ($tail !== false && strlen($tail) > 1) {
  46. $priority = (int) ltrim($tail, '_');
  47. $hook = substr($place, 0, -strlen($tail));
  48. if ($hook) {
  49. remove_action($hook, array($print_table, 'print_table'), $priority);
  50. }
  51. }
  52. } elseif (defined('WP_DEBUG') && WP_DEBUG) {
  53. error_log('STUDIOU FPP: PVTFW_PRINT_TABLE class not found; cannot detach pvtfw variant table.');
  54. }
  55. // Note: pvtfw's class name has a typo ("AVAILABE" missing the L) — match it verbatim
  56. if (class_exists('PVTFW_AVAILABE_BTN')) {
  57. $available_btn = PVTFW_AVAILABE_BTN::instance();
  58. remove_action('woocommerce_single_product_summary', array($available_btn, 'available_options_btn'), 11);
  59. }
  60. }
  61. public function body_class($classes) {
  62. if (function_exists('is_product') && is_product()) {
  63. $product_id = get_queried_object_id();
  64. if ($product_id && Studiou_WC_FPP_Product::is_fpp_product($product_id)) {
  65. $classes[] = 'studiou-fpp-product-page';
  66. }
  67. }
  68. return $classes;
  69. }
  70. public function render_upload_area() {
  71. global $product;
  72. if (!$product || !Studiou_WC_FPP_Product::is_fpp_product($product->get_id())) {
  73. return;
  74. }
  75. wp_enqueue_style('studiou-wcfpp-frontend');
  76. wp_enqueue_script('studiou-wcfpp-frontend');
  77. $product_id = $product->get_id();
  78. $max_file_size = Studiou_WC_FPP_Product::get_product_max_file_size($product_id);
  79. $max_uploads = Studiou_WC_FPP_Product::get_product_max_uploads($product_id);
  80. // Variant list (id, label, base_price, tiers) — injected into the files-cards JS
  81. $variants = $this->build_variant_list($product);
  82. // Existing batch files (rehydrate the card stack across reloads)
  83. $batch_files = self::resolve_batch_files($this->db, $product_id);
  84. $batch_cards = array();
  85. $hero_preview_url = '';
  86. foreach ($batch_files as $row) {
  87. $att_id = (int) $row->attachment_id;
  88. $thumb = wp_get_attachment_image_src($att_id, 'thumbnail');
  89. $preview = wp_get_attachment_image_src($att_id, 'woocommerce_single');
  90. if ($hero_preview_url === '') {
  91. $hero_preview_url = $preview ? $preview[0] : ($thumb ? $thumb[0] : '');
  92. }
  93. $batch_cards[] = array(
  94. 'file_record_id' => (int) $row->id,
  95. 'attachment_id' => $att_id,
  96. 'file_name' => (string) $row->file_name,
  97. 'thumb_url' => $thumb ? $thumb[0] : ($preview ? $preview[0] : ''),
  98. 'preview_url' => $preview ? $preview[0] : ($thumb ? $thumb[0] : ''),
  99. 'variation_id' => (int) $row->variation_id,
  100. );
  101. }
  102. wp_localize_script('studiou-wcfpp-frontend', 'studiouFppCardData', array(
  103. 'productId' => $product_id,
  104. 'variants' => $variants,
  105. 'maxUploads' => $max_uploads,
  106. 'batchFiles' => $batch_cards,
  107. 'heroPreviewUrl' => $hero_preview_url,
  108. ));
  109. // Keep studiouWcfppSession populated for legacy JS code paths that still read it
  110. wp_localize_script('studiou-wcfpp-frontend', 'studiouWcfppSession', array());
  111. include STUDIOU_WCFPP_PLUGIN_DIR . 'views/single-product-upload.php';
  112. if (is_product() && Studiou_WC_FPP_Product::is_fpp_product($product_id)) {
  113. // Render the order-overview panel below the cards (see views/single-product-order-overview.php)
  114. $cart = function_exists('WC') ? WC()->cart : null;
  115. include STUDIOU_WCFPP_PLUGIN_DIR . 'views/single-product-order-overview.php';
  116. }
  117. }
  118. /**
  119. * Produce the array of variation descriptors consumed by the upload-card JS.
  120. * One entry per in-stock, purchasable variation: id, label, base_price, tiers.
  121. */
  122. private function build_variant_list($product) {
  123. if (!$product || !$product->is_type('variable')) {
  124. return array();
  125. }
  126. $variants = array();
  127. foreach ($product->get_children() as $variation_id) {
  128. $variation = wc_get_product($variation_id);
  129. if (!$variation || !$variation->is_purchasable() || !$variation->variation_is_visible()) {
  130. continue;
  131. }
  132. $base_price = get_post_meta($variation_id, '_price', true);
  133. $label_parts = array();
  134. foreach ($variation->get_attributes() as $attr_name => $attr_value) {
  135. if ($attr_value === '') {
  136. continue;
  137. }
  138. $taxonomy = str_replace('attribute_', '', $attr_name);
  139. $term = taxonomy_exists($taxonomy) ? get_term_by('slug', $attr_value, $taxonomy) : null;
  140. // Term names or non-tax values may carry HTML entities (&nbsp;, &#75;,
  141. // &aacute;, …) pasted in by admins. <option> text is literal, so entities
  142. // would render as-is. Decode before handing to JS.
  143. $raw = $term ? $term->name : urldecode((string) $attr_value);
  144. $label_parts[] = html_entity_decode($raw, ENT_QUOTES | ENT_HTML5, 'UTF-8');
  145. }
  146. $tiers = class_exists('Studiou_WC_FPP_Pricing')
  147. ? Studiou_WC_FPP_Pricing::get_tiers($variation_id)
  148. : array();
  149. $variants[] = array(
  150. 'id' => (int) $variation_id,
  151. 'label' => implode(' / ', $label_parts),
  152. 'base_price' => ($base_price !== '' && $base_price !== false) ? (float) $base_price : 0.0,
  153. 'tiers' => $tiers,
  154. 'in_stock' => $variation->is_in_stock(),
  155. );
  156. }
  157. return $variants;
  158. }
  159. /**
  160. * Resolve whether a product_id or its parent is FPP-enabled.
  161. */
  162. private function resolve_fpp_product_id($product_id, $variation_id = 0) {
  163. // Check direct product
  164. if (Studiou_WC_FPP_Product::is_fpp_product($product_id)) {
  165. return $product_id;
  166. }
  167. // Check parent of the product (in case product_id is variation)
  168. $product = wc_get_product($product_id);
  169. if ($product && $product->get_parent_id() && Studiou_WC_FPP_Product::is_fpp_product($product->get_parent_id())) {
  170. return $product->get_parent_id();
  171. }
  172. // Check variation_id's parent
  173. if ($variation_id && $variation_id !== $product_id) {
  174. $variation = wc_get_product($variation_id);
  175. if ($variation && $variation->get_parent_id() && Studiou_WC_FPP_Product::is_fpp_product($variation->get_parent_id())) {
  176. return $variation->get_parent_id();
  177. }
  178. }
  179. return false;
  180. }
  181. /**
  182. * Validate before add-to-cart: block if FPP product and no photo reference resolvable.
  183. *
  184. * 1.5.0: the per-card Add-to-Cart path pre-stamps $cart_item_data['studiou_fpp_file_record_id']
  185. * via our ajax_add_file_to_cart handler — accept that as the primary signal. Fall back to the
  186. * legacy visitor-level resolver for the shortcode path.
  187. */
  188. public function validate_add_to_cart($passed, $product_id, $quantity, $variation_id = 0, $variations = array(), $cart_item_data = array()) {
  189. $fpp_id = $this->resolve_fpp_product_id($product_id, $variation_id);
  190. if (!$fpp_id) {
  191. return $passed;
  192. }
  193. if (!empty($cart_item_data['studiou_fpp_file_record_id'])) {
  194. $record = $this->db->get_file_record((int) $cart_item_data['studiou_fpp_file_record_id']);
  195. if ($record && (int) $record->order_id === 0) {
  196. return $passed;
  197. }
  198. }
  199. if (self::resolve_uploaded_file($this->db)) {
  200. return $passed;
  201. }
  202. wc_add_notice(__('Please upload a photo before adding to cart.', 'studiou-wc-free-photo-product'), 'error');
  203. return false;
  204. }
  205. /**
  206. * Return all upload records belonging to the current visitor's batch
  207. * that are not yet attached to an order, optionally scoped to a product.
  208. *
  209. * @return array<int,object> list of DB rows, oldest first (ascending id)
  210. */
  211. public static function resolve_batch_files(Studiou_WC_FPP_DB $db, $product_id = 0) {
  212. $token = Studiou_WC_FPP_Upload::get_batch_token();
  213. if (empty($token)) {
  214. return array();
  215. }
  216. return $db->get_batch_files($token, (int) $product_id);
  217. }
  218. /**
  219. * Resolve the single "current" upload for callers that still think in single-file
  220. * terms (shortcode fallback, the validate_add_to_cart fallback branch). Returns the
  221. * oldest unbound file in the visitor's batch, or null if none.
  222. *
  223. * Since 1.5.3 this is just a thin wrapper on the batch transport — the legacy
  224. * WC-session and legacy `studiou_fpp_att_id` / `studiou_fpp_rec_id` cookies are gone.
  225. *
  226. * @return array{attachment_id:int,file_record_id:int,file_name:string,thumb_url:string}|null
  227. */
  228. public static function resolve_uploaded_file(Studiou_WC_FPP_DB $db) {
  229. $files = self::resolve_batch_files($db);
  230. if (empty($files)) {
  231. return null;
  232. }
  233. $first = $files[0];
  234. $att_id = (int) $first->attachment_id;
  235. $thumb = wp_get_attachment_image_src($att_id, 'thumbnail');
  236. return array(
  237. 'attachment_id' => $att_id,
  238. 'file_record_id' => (int) $first->id,
  239. 'file_name' => (string) $first->file_name,
  240. 'thumb_url' => $thumb ? $thumb[0] : (string) wp_get_attachment_url($att_id),
  241. );
  242. }
  243. /**
  244. * Safety net: if an FPP item was added without photo data, remove it.
  245. * This catches cases where validation was somehow bypassed.
  246. */
  247. public function check_after_add_to_cart($cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data) {
  248. $fpp_id = $this->resolve_fpp_product_id($product_id, $variation_id);
  249. if (!$fpp_id) {
  250. return;
  251. }
  252. // If the cart item has no FPP attachment, remove it
  253. if (empty($cart_item_data['studiou_fpp_attachment_id'])) {
  254. WC()->cart->remove_cart_item($cart_item_key);
  255. wc_add_notice(__('Please upload a photo before adding to cart.', 'studiou-wc-free-photo-product'), 'error');
  256. }
  257. }
  258. }