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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  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. // AJAX: store uploaded file reference in WC session (legacy — shortcode path)
  21. add_action('wp_ajax_studiou_wcfpp_set_upload_session', array($this, 'ajax_set_upload_session'));
  22. add_action('wp_ajax_nopriv_studiou_wcfpp_set_upload_session', array($this, 'ajax_set_upload_session'));
  23. add_action('wp_ajax_studiou_wcfpp_clear_upload_session', array($this, 'ajax_clear_upload_session'));
  24. add_action('wp_ajax_nopriv_studiou_wcfpp_clear_upload_session', array($this, 'ajax_clear_upload_session'));
  25. }
  26. /**
  27. * Detach pvtfw's variant-table + available-options-button hooks on FPP products.
  28. * pvtfw exposes its instances as globals $pvtfw_print_table and $pvtfw_available_btn;
  29. * the table hook/priority is derived from the same option pvtfw itself reads
  30. * (pvtfw_variant_table_place, default woocommerce_after_single_product_summary_9).
  31. */
  32. public function maybe_suppress_pvtfw() {
  33. if (!function_exists('is_product') || !is_product()) {
  34. return;
  35. }
  36. $product_id = get_queried_object_id();
  37. if (!$product_id || !Studiou_WC_FPP_Product::is_fpp_product($product_id)) {
  38. return;
  39. }
  40. global $pvtfw_print_table, $pvtfw_available_btn;
  41. if ($pvtfw_print_table) {
  42. $place = get_option('pvtfw_variant_table_place', 'woocommerce_after_single_product_summary_9');
  43. $tail = strrchr((string) $place, '_');
  44. if ($tail !== false && strlen($tail) > 1) {
  45. $priority = (int) ltrim($tail, '_');
  46. $hook = substr($place, 0, -strlen($tail));
  47. if ($hook) {
  48. remove_action($hook, array($pvtfw_print_table, 'print_table'), $priority);
  49. }
  50. }
  51. } elseif (defined('WP_DEBUG') && WP_DEBUG) {
  52. error_log('STUDIOU FPP: $pvtfw_print_table not found; cannot detach pvtfw variant table.');
  53. }
  54. if ($pvtfw_available_btn) {
  55. remove_action('woocommerce_single_product_summary', array($pvtfw_available_btn, 'available_options_btn'), 11);
  56. }
  57. }
  58. public function body_class($classes) {
  59. if (function_exists('is_product') && is_product()) {
  60. $product_id = get_queried_object_id();
  61. if ($product_id && Studiou_WC_FPP_Product::is_fpp_product($product_id)) {
  62. $classes[] = 'studiou-fpp-product-page';
  63. }
  64. }
  65. return $classes;
  66. }
  67. public function render_upload_area() {
  68. global $product;
  69. if (!$product || !Studiou_WC_FPP_Product::is_fpp_product($product->get_id())) {
  70. return;
  71. }
  72. wp_enqueue_style('studiou-wcfpp-frontend');
  73. wp_enqueue_script('studiou-wcfpp-frontend');
  74. $product_id = $product->get_id();
  75. $max_file_size = Studiou_WC_FPP_Product::get_product_max_file_size($product_id);
  76. $max_uploads = Studiou_WC_FPP_Product::get_product_max_uploads($product_id);
  77. // Variant list (id, label, base_price, tiers) — injected into the files-cards JS
  78. $variants = $this->build_variant_list($product);
  79. // Existing batch files (rehydrate the card stack across reloads)
  80. $batch_files = self::resolve_batch_files($this->db, $product_id);
  81. $batch_cards = array();
  82. $hero_preview_url = '';
  83. foreach ($batch_files as $row) {
  84. $att_id = (int) $row->attachment_id;
  85. $thumb = wp_get_attachment_image_src($att_id, 'thumbnail');
  86. $preview = wp_get_attachment_image_src($att_id, 'woocommerce_single');
  87. if ($hero_preview_url === '') {
  88. $hero_preview_url = $preview ? $preview[0] : ($thumb ? $thumb[0] : '');
  89. }
  90. $batch_cards[] = array(
  91. 'file_record_id' => (int) $row->id,
  92. 'attachment_id' => $att_id,
  93. 'file_name' => (string) $row->file_name,
  94. 'thumb_url' => $thumb ? $thumb[0] : ($preview ? $preview[0] : ''),
  95. 'variation_id' => (int) $row->variation_id,
  96. );
  97. }
  98. wp_localize_script('studiou-wcfpp-frontend', 'studiouFppCardData', array(
  99. 'productId' => $product_id,
  100. 'variants' => $variants,
  101. 'maxUploads' => $max_uploads,
  102. 'batchFiles' => $batch_cards,
  103. 'heroPreviewUrl' => $hero_preview_url,
  104. ));
  105. // Keep studiouWcfppSession populated for legacy JS code paths that still read it
  106. wp_localize_script('studiou-wcfpp-frontend', 'studiouWcfppSession', array());
  107. include STUDIOU_WCFPP_PLUGIN_DIR . 'views/single-product-upload.php';
  108. if (is_product() && Studiou_WC_FPP_Product::is_fpp_product($product_id)) {
  109. // Render the order-overview panel below the cards (see views/single-product-order-overview.php)
  110. $cart = function_exists('WC') ? WC()->cart : null;
  111. include STUDIOU_WCFPP_PLUGIN_DIR . 'views/single-product-order-overview.php';
  112. }
  113. }
  114. /**
  115. * Produce the array of variation descriptors consumed by the upload-card JS.
  116. * One entry per in-stock, purchasable variation: id, label, base_price, tiers.
  117. */
  118. private function build_variant_list($product) {
  119. if (!$product || !$product->is_type('variable')) {
  120. return array();
  121. }
  122. $variants = array();
  123. foreach ($product->get_children() as $variation_id) {
  124. $variation = wc_get_product($variation_id);
  125. if (!$variation || !$variation->is_purchasable() || !$variation->variation_is_visible()) {
  126. continue;
  127. }
  128. $base_price = get_post_meta($variation_id, '_price', true);
  129. $label_parts = array();
  130. foreach ($variation->get_attributes() as $attr_name => $attr_value) {
  131. if ($attr_value === '') {
  132. continue;
  133. }
  134. $taxonomy = str_replace('attribute_', '', $attr_name);
  135. $term = taxonomy_exists($taxonomy) ? get_term_by('slug', $attr_value, $taxonomy) : null;
  136. $label_parts[] = $term ? $term->name : $attr_value;
  137. }
  138. $tiers = class_exists('Studiou_WC_FPP_Pricing')
  139. ? Studiou_WC_FPP_Pricing::get_tiers($variation_id)
  140. : array();
  141. $variants[] = array(
  142. 'id' => (int) $variation_id,
  143. 'label' => implode(' / ', $label_parts),
  144. 'base_price' => ($base_price !== '' && $base_price !== false) ? (float) $base_price : 0.0,
  145. 'tiers' => $tiers,
  146. 'in_stock' => $variation->is_in_stock(),
  147. );
  148. }
  149. return $variants;
  150. }
  151. /**
  152. * Resolve whether a product_id or its parent is FPP-enabled.
  153. */
  154. private function resolve_fpp_product_id($product_id, $variation_id = 0) {
  155. // Check direct product
  156. if (Studiou_WC_FPP_Product::is_fpp_product($product_id)) {
  157. return $product_id;
  158. }
  159. // Check parent of the product (in case product_id is variation)
  160. $product = wc_get_product($product_id);
  161. if ($product && $product->get_parent_id() && Studiou_WC_FPP_Product::is_fpp_product($product->get_parent_id())) {
  162. return $product->get_parent_id();
  163. }
  164. // Check variation_id's parent
  165. if ($variation_id && $variation_id !== $product_id) {
  166. $variation = wc_get_product($variation_id);
  167. if ($variation && $variation->get_parent_id() && Studiou_WC_FPP_Product::is_fpp_product($variation->get_parent_id())) {
  168. return $variation->get_parent_id();
  169. }
  170. }
  171. return false;
  172. }
  173. /**
  174. * Validate before add-to-cart: block if FPP product and no photo reference resolvable.
  175. *
  176. * 1.5.0: the per-card Add-to-Cart path pre-stamps $cart_item_data['studiou_fpp_file_record_id']
  177. * via our ajax_add_file_to_cart handler — accept that as the primary signal. Fall back to the
  178. * legacy visitor-level resolver for the shortcode path.
  179. */
  180. public function validate_add_to_cart($passed, $product_id, $quantity, $variation_id = 0, $variations = array(), $cart_item_data = array()) {
  181. $fpp_id = $this->resolve_fpp_product_id($product_id, $variation_id);
  182. if (!$fpp_id) {
  183. return $passed;
  184. }
  185. if (!empty($cart_item_data['studiou_fpp_file_record_id'])) {
  186. $record = $this->db->get_file_record((int) $cart_item_data['studiou_fpp_file_record_id']);
  187. if ($record && (int) $record->order_id === 0) {
  188. return $passed;
  189. }
  190. }
  191. if (self::resolve_uploaded_file($this->db)) {
  192. return $passed;
  193. }
  194. wc_add_notice(__('Please upload a photo before adding to cart.', 'studiou-wc-free-photo-product'), 'error');
  195. return false;
  196. }
  197. /**
  198. * Return all upload records belonging to the current visitor's batch
  199. * that are not yet attached to an order, optionally scoped to a product.
  200. *
  201. * @return array<int,object> list of DB rows, oldest first (ascending id)
  202. */
  203. public static function resolve_batch_files(Studiou_WC_FPP_DB $db, $product_id = 0) {
  204. $token = Studiou_WC_FPP_Upload::get_batch_token();
  205. if (empty($token)) {
  206. return array();
  207. }
  208. return $db->get_batch_files($token, (int) $product_id);
  209. }
  210. /**
  211. * Resolve the currently "attached" upload for this visitor (legacy single-file path).
  212. * Checks WC session first, then legacy cookie pair, and finally the first file in the
  213. * current batch as a last-resort fallback. Used only by the shortcode flow on 1.5+ —
  214. * the product-detail page uses resolve_batch_files() and pre-stamped file_record_id.
  215. *
  216. * @return array{attachment_id:int,file_record_id:int,file_name:string,thumb_url:string}|null
  217. */
  218. public static function resolve_uploaded_file(Studiou_WC_FPP_DB $db) {
  219. $attachment_id = 0;
  220. $file_record_id = 0;
  221. $file_name = '';
  222. $thumb_url = '';
  223. if (function_exists('WC') && WC()->session) {
  224. $attachment_id = (int) WC()->session->get('studiou_fpp_attachment_id');
  225. $file_record_id = (int) WC()->session->get('studiou_fpp_file_record_id');
  226. $file_name = (string) WC()->session->get('studiou_fpp_file_name');
  227. $thumb_url = (string) WC()->session->get('studiou_fpp_thumb_url');
  228. }
  229. if ($attachment_id <= 0 || $file_record_id <= 0) {
  230. $cookie_att = isset($_COOKIE[Studiou_WC_FPP_Upload::COOKIE_ATTACHMENT])
  231. ? (int) $_COOKIE[Studiou_WC_FPP_Upload::COOKIE_ATTACHMENT] : 0;
  232. $cookie_rec = isset($_COOKIE[Studiou_WC_FPP_Upload::COOKIE_RECORD])
  233. ? (int) $_COOKIE[Studiou_WC_FPP_Upload::COOKIE_RECORD] : 0;
  234. if ($cookie_att > 0 && $cookie_rec > 0) {
  235. $attachment_id = $cookie_att;
  236. $file_record_id = $cookie_rec;
  237. $file_name = '';
  238. $thumb_url = '';
  239. }
  240. }
  241. if ($attachment_id <= 0 || $file_record_id <= 0) {
  242. return null;
  243. }
  244. $record = $db->get_file_record($file_record_id);
  245. if (!$record) {
  246. return null;
  247. }
  248. if ((int) $record->attachment_id !== $attachment_id) {
  249. return null;
  250. }
  251. // A record already attached to an order is no longer "in flight" for add-to-cart
  252. if ((int) $record->order_id !== 0) {
  253. return null;
  254. }
  255. if ($file_name === '') {
  256. $file_name = (string) $record->file_name;
  257. }
  258. if ($thumb_url === '') {
  259. $thumb = wp_get_attachment_image_src($attachment_id, 'thumbnail');
  260. if ($thumb) {
  261. $thumb_url = $thumb[0];
  262. } else {
  263. $thumb_url = (string) wp_get_attachment_url($attachment_id);
  264. }
  265. }
  266. return array(
  267. 'attachment_id' => $attachment_id,
  268. 'file_record_id' => $file_record_id,
  269. 'file_name' => $file_name,
  270. 'thumb_url' => $thumb_url,
  271. );
  272. }
  273. /**
  274. * Safety net: if an FPP item was added without photo data, remove it.
  275. * This catches cases where validation was somehow bypassed.
  276. */
  277. public function check_after_add_to_cart($cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data) {
  278. $fpp_id = $this->resolve_fpp_product_id($product_id, $variation_id);
  279. if (!$fpp_id) {
  280. return;
  281. }
  282. // If the cart item has no FPP attachment, remove it
  283. if (empty($cart_item_data['studiou_fpp_attachment_id'])) {
  284. WC()->cart->remove_cart_item($cart_item_key);
  285. wc_add_notice(__('Please upload a photo before adding to cart.', 'studiou-wc-free-photo-product'), 'error');
  286. }
  287. }
  288. public function ajax_set_upload_session() {
  289. check_ajax_referer('studiou-wcfpp-front-nonce', 'nonce');
  290. $attachment_id = isset($_POST['attachment_id']) ? absint($_POST['attachment_id']) : 0;
  291. $file_record_id = isset($_POST['file_record_id']) ? absint($_POST['file_record_id']) : 0;
  292. $file_name = isset($_POST['file_name']) ? sanitize_text_field($_POST['file_name']) : '';
  293. if (!$attachment_id || !$file_record_id) {
  294. wp_send_json_error(array('message' => __('Invalid file data.', 'studiou-wc-free-photo-product')));
  295. return;
  296. }
  297. if (WC()->session) {
  298. WC()->session->set('studiou_fpp_attachment_id', $attachment_id);
  299. WC()->session->set('studiou_fpp_file_record_id', $file_record_id);
  300. WC()->session->set('studiou_fpp_file_name', $file_name);
  301. // Store thumbnail URL directly so it can be used in cart without wp_get_attachment lookup
  302. $thumb_url = '';
  303. $thumb = wp_get_attachment_image_src($attachment_id, 'thumbnail');
  304. if ($thumb) {
  305. $thumb_url = $thumb[0];
  306. } else {
  307. $thumb_url = wp_get_attachment_url($attachment_id);
  308. }
  309. WC()->session->set('studiou_fpp_thumb_url', $thumb_url ?: '');
  310. }
  311. wp_send_json_success();
  312. }
  313. public function ajax_clear_upload_session() {
  314. check_ajax_referer('studiou-wcfpp-front-nonce', 'nonce');
  315. if (WC()->session) {
  316. WC()->session->set('studiou_fpp_attachment_id', null);
  317. WC()->session->set('studiou_fpp_file_record_id', null);
  318. WC()->session->set('studiou_fpp_file_name', null);
  319. WC()->session->set('studiou_fpp_thumb_url', null);
  320. }
  321. Studiou_WC_FPP_Upload::clear_upload_cookies();
  322. wp_send_json_success();
  323. }
  324. }