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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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. *
  29. * pvtfw assigns its singletons to `$pvtfw_print_table` / `$pvtfw_available_btn` at the
  30. * top of its class files, but the `require_once` call lives inside pvtfw's
  31. * PVTFW_TABLE::includes() method — so those assignments end up as method-locals, NOT
  32. * true globals. We therefore reach the singletons via their static ::instance()
  33. * (the same object pvtfw registered the actions with). The variant-table hook and
  34. * priority are derived from pvtfw's own pvtfw_variant_table_place option (default
  35. * woocommerce_after_single_product_summary_9) so admin-configured placements
  36. * remain supported.
  37. */
  38. public function maybe_suppress_pvtfw() {
  39. if (!function_exists('is_product') || !is_product()) {
  40. return;
  41. }
  42. $product_id = get_queried_object_id();
  43. if (!$product_id || !Studiou_WC_FPP_Product::is_fpp_product($product_id)) {
  44. return;
  45. }
  46. if (class_exists('PVTFW_PRINT_TABLE')) {
  47. $print_table = PVTFW_PRINT_TABLE::instance();
  48. $place = get_option('pvtfw_variant_table_place', 'woocommerce_after_single_product_summary_9');
  49. $tail = strrchr((string) $place, '_');
  50. if ($tail !== false && strlen($tail) > 1) {
  51. $priority = (int) ltrim($tail, '_');
  52. $hook = substr($place, 0, -strlen($tail));
  53. if ($hook) {
  54. remove_action($hook, array($print_table, 'print_table'), $priority);
  55. }
  56. }
  57. } elseif (defined('WP_DEBUG') && WP_DEBUG) {
  58. error_log('STUDIOU FPP: PVTFW_PRINT_TABLE class not found; cannot detach pvtfw variant table.');
  59. }
  60. // Note: pvtfw's class name has a typo ("AVAILABE" missing the L) — match it verbatim
  61. if (class_exists('PVTFW_AVAILABE_BTN')) {
  62. $available_btn = PVTFW_AVAILABE_BTN::instance();
  63. remove_action('woocommerce_single_product_summary', array($available_btn, 'available_options_btn'), 11);
  64. }
  65. }
  66. public function body_class($classes) {
  67. if (function_exists('is_product') && is_product()) {
  68. $product_id = get_queried_object_id();
  69. if ($product_id && Studiou_WC_FPP_Product::is_fpp_product($product_id)) {
  70. $classes[] = 'studiou-fpp-product-page';
  71. }
  72. }
  73. return $classes;
  74. }
  75. public function render_upload_area() {
  76. global $product;
  77. if (!$product || !Studiou_WC_FPP_Product::is_fpp_product($product->get_id())) {
  78. return;
  79. }
  80. wp_enqueue_style('studiou-wcfpp-frontend');
  81. wp_enqueue_script('studiou-wcfpp-frontend');
  82. $product_id = $product->get_id();
  83. $max_file_size = Studiou_WC_FPP_Product::get_product_max_file_size($product_id);
  84. $max_uploads = Studiou_WC_FPP_Product::get_product_max_uploads($product_id);
  85. // Variant list (id, label, base_price, tiers) — injected into the files-cards JS
  86. $variants = $this->build_variant_list($product);
  87. // Existing batch files (rehydrate the card stack across reloads)
  88. $batch_files = self::resolve_batch_files($this->db, $product_id);
  89. $batch_cards = array();
  90. $hero_preview_url = '';
  91. foreach ($batch_files as $row) {
  92. $att_id = (int) $row->attachment_id;
  93. $thumb = wp_get_attachment_image_src($att_id, 'thumbnail');
  94. $preview = wp_get_attachment_image_src($att_id, 'woocommerce_single');
  95. if ($hero_preview_url === '') {
  96. $hero_preview_url = $preview ? $preview[0] : ($thumb ? $thumb[0] : '');
  97. }
  98. $batch_cards[] = array(
  99. 'file_record_id' => (int) $row->id,
  100. 'attachment_id' => $att_id,
  101. 'file_name' => (string) $row->file_name,
  102. 'thumb_url' => $thumb ? $thumb[0] : ($preview ? $preview[0] : ''),
  103. 'variation_id' => (int) $row->variation_id,
  104. );
  105. }
  106. wp_localize_script('studiou-wcfpp-frontend', 'studiouFppCardData', array(
  107. 'productId' => $product_id,
  108. 'variants' => $variants,
  109. 'maxUploads' => $max_uploads,
  110. 'batchFiles' => $batch_cards,
  111. 'heroPreviewUrl' => $hero_preview_url,
  112. ));
  113. // Keep studiouWcfppSession populated for legacy JS code paths that still read it
  114. wp_localize_script('studiou-wcfpp-frontend', 'studiouWcfppSession', array());
  115. include STUDIOU_WCFPP_PLUGIN_DIR . 'views/single-product-upload.php';
  116. if (is_product() && Studiou_WC_FPP_Product::is_fpp_product($product_id)) {
  117. // Render the order-overview panel below the cards (see views/single-product-order-overview.php)
  118. $cart = function_exists('WC') ? WC()->cart : null;
  119. include STUDIOU_WCFPP_PLUGIN_DIR . 'views/single-product-order-overview.php';
  120. }
  121. }
  122. /**
  123. * Produce the array of variation descriptors consumed by the upload-card JS.
  124. * One entry per in-stock, purchasable variation: id, label, base_price, tiers.
  125. */
  126. private function build_variant_list($product) {
  127. if (!$product || !$product->is_type('variable')) {
  128. return array();
  129. }
  130. $variants = array();
  131. foreach ($product->get_children() as $variation_id) {
  132. $variation = wc_get_product($variation_id);
  133. if (!$variation || !$variation->is_purchasable() || !$variation->variation_is_visible()) {
  134. continue;
  135. }
  136. $base_price = get_post_meta($variation_id, '_price', true);
  137. $label_parts = array();
  138. foreach ($variation->get_attributes() as $attr_name => $attr_value) {
  139. if ($attr_value === '') {
  140. continue;
  141. }
  142. $taxonomy = str_replace('attribute_', '', $attr_name);
  143. $term = taxonomy_exists($taxonomy) ? get_term_by('slug', $attr_value, $taxonomy) : null;
  144. $label_parts[] = $term ? $term->name : $attr_value;
  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 currently "attached" upload for this visitor (legacy single-file path).
  220. * Checks WC session first, then legacy cookie pair, and finally the first file in the
  221. * current batch as a last-resort fallback. Used only by the shortcode flow on 1.5+ —
  222. * the product-detail page uses resolve_batch_files() and pre-stamped file_record_id.
  223. *
  224. * @return array{attachment_id:int,file_record_id:int,file_name:string,thumb_url:string}|null
  225. */
  226. public static function resolve_uploaded_file(Studiou_WC_FPP_DB $db) {
  227. $attachment_id = 0;
  228. $file_record_id = 0;
  229. $file_name = '';
  230. $thumb_url = '';
  231. if (function_exists('WC') && WC()->session) {
  232. $attachment_id = (int) WC()->session->get('studiou_fpp_attachment_id');
  233. $file_record_id = (int) WC()->session->get('studiou_fpp_file_record_id');
  234. $file_name = (string) WC()->session->get('studiou_fpp_file_name');
  235. $thumb_url = (string) WC()->session->get('studiou_fpp_thumb_url');
  236. }
  237. if ($attachment_id <= 0 || $file_record_id <= 0) {
  238. $cookie_att = isset($_COOKIE[Studiou_WC_FPP_Upload::COOKIE_ATTACHMENT])
  239. ? (int) $_COOKIE[Studiou_WC_FPP_Upload::COOKIE_ATTACHMENT] : 0;
  240. $cookie_rec = isset($_COOKIE[Studiou_WC_FPP_Upload::COOKIE_RECORD])
  241. ? (int) $_COOKIE[Studiou_WC_FPP_Upload::COOKIE_RECORD] : 0;
  242. if ($cookie_att > 0 && $cookie_rec > 0) {
  243. $attachment_id = $cookie_att;
  244. $file_record_id = $cookie_rec;
  245. $file_name = '';
  246. $thumb_url = '';
  247. }
  248. }
  249. if ($attachment_id <= 0 || $file_record_id <= 0) {
  250. return null;
  251. }
  252. $record = $db->get_file_record($file_record_id);
  253. if (!$record) {
  254. return null;
  255. }
  256. if ((int) $record->attachment_id !== $attachment_id) {
  257. return null;
  258. }
  259. // A record already attached to an order is no longer "in flight" for add-to-cart
  260. if ((int) $record->order_id !== 0) {
  261. return null;
  262. }
  263. if ($file_name === '') {
  264. $file_name = (string) $record->file_name;
  265. }
  266. if ($thumb_url === '') {
  267. $thumb = wp_get_attachment_image_src($attachment_id, 'thumbnail');
  268. if ($thumb) {
  269. $thumb_url = $thumb[0];
  270. } else {
  271. $thumb_url = (string) wp_get_attachment_url($attachment_id);
  272. }
  273. }
  274. return array(
  275. 'attachment_id' => $attachment_id,
  276. 'file_record_id' => $file_record_id,
  277. 'file_name' => $file_name,
  278. 'thumb_url' => $thumb_url,
  279. );
  280. }
  281. /**
  282. * Safety net: if an FPP item was added without photo data, remove it.
  283. * This catches cases where validation was somehow bypassed.
  284. */
  285. public function check_after_add_to_cart($cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data) {
  286. $fpp_id = $this->resolve_fpp_product_id($product_id, $variation_id);
  287. if (!$fpp_id) {
  288. return;
  289. }
  290. // If the cart item has no FPP attachment, remove it
  291. if (empty($cart_item_data['studiou_fpp_attachment_id'])) {
  292. WC()->cart->remove_cart_item($cart_item_key);
  293. wc_add_notice(__('Please upload a photo before adding to cart.', 'studiou-wc-free-photo-product'), 'error');
  294. }
  295. }
  296. public function ajax_set_upload_session() {
  297. check_ajax_referer('studiou-wcfpp-front-nonce', 'nonce');
  298. $attachment_id = isset($_POST['attachment_id']) ? absint($_POST['attachment_id']) : 0;
  299. $file_record_id = isset($_POST['file_record_id']) ? absint($_POST['file_record_id']) : 0;
  300. $file_name = isset($_POST['file_name']) ? sanitize_text_field($_POST['file_name']) : '';
  301. if (!$attachment_id || !$file_record_id) {
  302. wp_send_json_error(array('message' => __('Invalid file data.', 'studiou-wc-free-photo-product')));
  303. return;
  304. }
  305. if (WC()->session) {
  306. WC()->session->set('studiou_fpp_attachment_id', $attachment_id);
  307. WC()->session->set('studiou_fpp_file_record_id', $file_record_id);
  308. WC()->session->set('studiou_fpp_file_name', $file_name);
  309. // Store thumbnail URL directly so it can be used in cart without wp_get_attachment lookup
  310. $thumb_url = '';
  311. $thumb = wp_get_attachment_image_src($attachment_id, 'thumbnail');
  312. if ($thumb) {
  313. $thumb_url = $thumb[0];
  314. } else {
  315. $thumb_url = wp_get_attachment_url($attachment_id);
  316. }
  317. WC()->session->set('studiou_fpp_thumb_url', $thumb_url ?: '');
  318. }
  319. wp_send_json_success();
  320. }
  321. public function ajax_clear_upload_session() {
  322. check_ajax_referer('studiou-wcfpp-front-nonce', 'nonce');
  323. if (WC()->session) {
  324. WC()->session->set('studiou_fpp_attachment_id', null);
  325. WC()->session->set('studiou_fpp_file_record_id', null);
  326. WC()->session->set('studiou_fpp_file_name', null);
  327. WC()->session->set('studiou_fpp_thumb_url', null);
  328. }
  329. Studiou_WC_FPP_Upload::clear_upload_cookies();
  330. wp_send_json_success();
  331. }
  332. }