class-studiou-wc-fpp-upload.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. <?php
  2. if (!defined('WPINC')) {
  3. die;
  4. }
  5. class Studiou_WC_FPP_Upload {
  6. /** @var Studiou_WC_FPP_DB */
  7. private $db;
  8. public function __construct($db) {
  9. $this->db = $db;
  10. add_action('wp_ajax_studiou_wcfpp_upload_chunk', array($this, 'handle_chunk_upload'));
  11. add_action('wp_ajax_nopriv_studiou_wcfpp_upload_chunk', array($this, 'handle_chunk_upload'));
  12. add_action('wp_ajax_studiou_wcfpp_remove_upload', array($this, 'handle_remove_upload'));
  13. add_action('wp_ajax_nopriv_studiou_wcfpp_remove_upload', array($this, 'handle_remove_upload'));
  14. }
  15. private function get_chunks_dir() {
  16. $upload_dir = wp_upload_dir();
  17. return $upload_dir['basedir'] . '/studiou-fpp-chunks';
  18. }
  19. private function get_allowed_mime_types() {
  20. return array(
  21. 'jpg|jpeg|jpe' => 'image/jpeg',
  22. 'png' => 'image/png',
  23. 'tiff|tif' => 'image/tiff',
  24. 'bmp' => 'image/bmp',
  25. 'psd' => 'image/vnd.adobe.photoshop',
  26. 'cr2' => 'image/x-canon-cr2',
  27. 'nef' => 'image/x-nikon-nef',
  28. 'arw' => 'image/x-sony-arw',
  29. 'dng' => 'image/x-adobe-dng',
  30. 'orf' => 'image/x-olympus-orf',
  31. 'rw2' => 'image/x-panasonic-rw2',
  32. 'raf' => 'image/x-fuji-raf',
  33. 'webp' => 'image/webp',
  34. );
  35. }
  36. public function handle_chunk_upload() {
  37. // Clean output buffers
  38. while (ob_get_level()) {
  39. ob_end_clean();
  40. }
  41. check_ajax_referer('studiou-wcfpp-front-nonce', 'nonce');
  42. $product_id = isset($_POST['product_id']) ? absint($_POST['product_id']) : 0;
  43. $upload_id = isset($_POST['upload_id']) ? sanitize_text_field($_POST['upload_id']) : '';
  44. $chunk_index = isset($_POST['chunk_index']) ? absint($_POST['chunk_index']) : 0;
  45. $total_chunks = isset($_POST['total_chunks']) ? absint($_POST['total_chunks']) : 0;
  46. $file_name = isset($_POST['file_name']) ? sanitize_file_name($_POST['file_name']) : '';
  47. $file_size = isset($_POST['file_size']) ? absint($_POST['file_size']) : 0;
  48. // Validate product
  49. if (!$product_id || !Studiou_WC_FPP_Product::is_fpp_product($product_id)) {
  50. wp_send_json_error(array('message' => __('Invalid product.', 'studiou-wc-free-photo-product')));
  51. return;
  52. }
  53. // Validate file size
  54. $max_size = Studiou_WC_FPP_Product::get_product_max_file_size($product_id);
  55. if ($file_size > ($max_size * 1024 * 1024)) {
  56. wp_send_json_error(array('message' => sprintf(
  57. __('File is too large. Maximum size: %s MB', 'studiou-wc-free-photo-product'),
  58. $max_size
  59. )));
  60. return;
  61. }
  62. // Validate upload_id format (should be alphanumeric)
  63. if (!preg_match('/^[a-zA-Z0-9_-]+$/', $upload_id)) {
  64. wp_send_json_error(array('message' => __('Invalid upload ID.', 'studiou-wc-free-photo-product')));
  65. return;
  66. }
  67. // Validate chunk file exists
  68. if (!isset($_FILES['chunk']) || $_FILES['chunk']['error'] !== UPLOAD_ERR_OK) {
  69. wp_send_json_error(array('message' => __('Chunk upload failed.', 'studiou-wc-free-photo-product')));
  70. return;
  71. }
  72. // Resolve/mint batch token — a stable per-visitor identifier that survives classic
  73. // cookie <-> Store API Cart-Token session splits. Write it to the cookie once.
  74. $batch_token = self::resolve_or_mint_batch_token();
  75. // Enforce per-product max-uploads cap on the first chunk of a new file.
  76. if ($chunk_index === 0) {
  77. $max_uploads = Studiou_WC_FPP_Product::get_product_max_uploads($product_id);
  78. if ($max_uploads > 0) {
  79. $current_count = $this->db->count_batch_files($batch_token, $product_id);
  80. if ($current_count >= $max_uploads) {
  81. wp_send_json_error(array('message' => sprintf(
  82. __('Maximum number of uploads reached (%d). Remove a photo before uploading another.', 'studiou-wc-free-photo-product'),
  83. $max_uploads
  84. )));
  85. return;
  86. }
  87. }
  88. }
  89. $chunks_dir = $this->get_chunks_dir();
  90. if (!file_exists($chunks_dir)) {
  91. wp_mkdir_p($chunks_dir);
  92. }
  93. // Store the chunk
  94. $chunk_file = $chunks_dir . '/' . $upload_id . '_chunk_' . $chunk_index;
  95. if (!move_uploaded_file($_FILES['chunk']['tmp_name'], $chunk_file)) {
  96. wp_send_json_error(array('message' => __('Failed to store chunk.', 'studiou-wc-free-photo-product')));
  97. return;
  98. }
  99. // If this is the last chunk, assemble the file
  100. if ($chunk_index === $total_chunks - 1) {
  101. // Clean any output that may have been generated
  102. while (ob_get_level()) {
  103. ob_end_clean();
  104. }
  105. $result = $this->assemble_chunks($upload_id, $total_chunks, $file_name, $product_id, $batch_token);
  106. // Clean again before sending JSON
  107. while (ob_get_level()) {
  108. ob_end_clean();
  109. }
  110. if (is_wp_error($result)) {
  111. wp_send_json_error(array('message' => $result->get_error_message()));
  112. return;
  113. }
  114. // Since 1.5.3 the batch_token cookie (set by resolve_or_mint_batch_token above
  115. // and persisted in the DB row's batch_token column) is the sole transport —
  116. // no more WC-session writes, no more legacy per-upload cookies.
  117. wp_send_json_success(array(
  118. 'complete' => true,
  119. 'attachment_id' => $result['attachment_id'],
  120. 'file_record_id' => $result['file_record_id'],
  121. 'thumbnail_url' => $result['thumbnail_url'],
  122. 'preview_url' => $result['preview_url'],
  123. 'file_name' => $result['file_name'],
  124. ));
  125. return;
  126. }
  127. wp_send_json_success(array(
  128. 'complete' => false,
  129. 'chunk_index' => $chunk_index,
  130. ));
  131. }
  132. private function assemble_chunks($upload_id, $total_chunks, $file_name, $product_id, $batch_token = '') {
  133. $chunks_dir = $this->get_chunks_dir();
  134. $upload_dir = wp_upload_dir();
  135. // Create a subdirectory for free photo uploads
  136. $fpp_dir = $upload_dir['path'] . '/free-photo';
  137. if (!file_exists($fpp_dir)) {
  138. wp_mkdir_p($fpp_dir);
  139. }
  140. // Generate unique filename
  141. $ext = pathinfo($file_name, PATHINFO_EXTENSION);
  142. $base = sanitize_file_name(pathinfo($file_name, PATHINFO_FILENAME));
  143. $unique_name = $base . '_' . uniqid() . '.' . $ext;
  144. $assembled_path = $fpp_dir . '/' . $unique_name;
  145. // Assemble chunks
  146. $output = fopen($assembled_path, 'wb');
  147. if (!$output) {
  148. $this->cleanup_chunks($upload_id, $total_chunks);
  149. return new WP_Error('assemble_failed', __('Failed to create output file.', 'studiou-wc-free-photo-product'));
  150. }
  151. for ($i = 0; $i < $total_chunks; $i++) {
  152. $chunk_file = $chunks_dir . '/' . $upload_id . '_chunk_' . $i;
  153. if (!file_exists($chunk_file)) {
  154. fclose($output);
  155. unlink($assembled_path);
  156. $this->cleanup_chunks($upload_id, $total_chunks);
  157. return new WP_Error('chunk_missing', sprintf(
  158. __('Missing chunk %d.', 'studiou-wc-free-photo-product'),
  159. $i
  160. ));
  161. }
  162. $chunk_data = file_get_contents($chunk_file);
  163. fwrite($output, $chunk_data);
  164. }
  165. fclose($output);
  166. // Clean up chunk files
  167. $this->cleanup_chunks($upload_id, $total_chunks);
  168. // Validate file extension
  169. $allowed = $this->get_allowed_mime_types();
  170. $ext_lower = strtolower($ext);
  171. $valid = false;
  172. foreach ($allowed as $exts => $mime) {
  173. $ext_list = explode('|', $exts);
  174. if (in_array($ext_lower, $ext_list)) {
  175. $valid = true;
  176. break;
  177. }
  178. }
  179. if (!$valid) {
  180. unlink($assembled_path);
  181. return new WP_Error('invalid_type', __('File type not allowed.', 'studiou-wc-free-photo-product'));
  182. }
  183. // Validate image resolution (if limits are set)
  184. $res_error = $this->validate_image_resolution($assembled_path, $product_id);
  185. if (is_wp_error($res_error)) {
  186. unlink($assembled_path);
  187. return $res_error;
  188. }
  189. // Create WP attachment
  190. $relative_path = str_replace($upload_dir['basedir'] . '/', '', $assembled_path);
  191. $filetype = wp_check_filetype($unique_name, $allowed);
  192. $attachment_data = array(
  193. 'post_mime_type' => $filetype['type'] ?: 'application/octet-stream',
  194. 'post_title' => sanitize_file_name($file_name),
  195. 'post_content' => '',
  196. 'post_status' => 'inherit',
  197. 'post_parent' => $product_id,
  198. );
  199. $attachment_id = wp_insert_attachment($attachment_data, $assembled_path, $product_id);
  200. if (is_wp_error($attachment_id)) {
  201. unlink($assembled_path);
  202. return $attachment_id;
  203. }
  204. // Generate metadata (wrapped in output buffer to prevent stray output corrupting JSON)
  205. require_once(ABSPATH . 'wp-admin/includes/image.php');
  206. ob_start();
  207. try {
  208. @set_time_limit(120);
  209. $metadata = @wp_generate_attachment_metadata($attachment_id, $assembled_path);
  210. if (!empty($metadata)) {
  211. wp_update_attachment_metadata($attachment_id, $metadata);
  212. }
  213. } catch (\Throwable $e) {
  214. if (defined('WP_DEBUG') && WP_DEBUG) {
  215. error_log('STUDIOU FPP: metadata generation failed - ' . $e->getMessage());
  216. }
  217. }
  218. ob_end_clean();
  219. // Assign media category
  220. $media_cat_id = Studiou_WC_FPP_Product::get_product_media_category($product_id);
  221. if ($media_cat_id) {
  222. wp_set_object_terms($attachment_id, array((int) $media_cat_id), 'studiou_media_category');
  223. }
  224. // Get thumbnail URL (small - for upload preview)
  225. $thumbnail_url = '';
  226. $image_src = wp_get_attachment_image_src($attachment_id, 'thumbnail');
  227. if ($image_src) {
  228. $thumbnail_url = $image_src[0];
  229. } else {
  230. $thumbnail_url = wp_mime_type_icon($attachment_id);
  231. }
  232. // Get preview URL (larger - for product gallery replacement)
  233. $preview_url = '';
  234. $preview_src = wp_get_attachment_image_src($attachment_id, 'woocommerce_single');
  235. if ($preview_src) {
  236. $preview_url = $preview_src[0];
  237. } elseif ($image_src) {
  238. $preview_url = $image_src[0];
  239. }
  240. // Get session key for guests
  241. $session_key = '';
  242. if (!is_user_logged_in()) {
  243. if (WC()->session) {
  244. $session_key = WC()->session->get_customer_id();
  245. }
  246. }
  247. // Insert file record
  248. $file_record_id = $this->db->insert_file_record(array(
  249. 'product_id' => $product_id,
  250. 'attachment_id' => $attachment_id,
  251. 'customer_id' => get_current_user_id(),
  252. 'session_key' => $session_key,
  253. 'batch_token' => $batch_token,
  254. 'file_name' => $file_name,
  255. ));
  256. if (!$file_record_id) {
  257. wp_delete_attachment($attachment_id, true);
  258. return new WP_Error('record_failed', __('Failed to create file record.', 'studiou-wc-free-photo-product'));
  259. }
  260. return array(
  261. 'attachment_id' => $attachment_id,
  262. 'file_record_id' => $file_record_id,
  263. 'thumbnail_url' => $thumbnail_url,
  264. 'preview_url' => $preview_url,
  265. 'file_name' => $file_name,
  266. );
  267. }
  268. /**
  269. * Validate image resolution against product limits.
  270. * Width/height are commutable — a 3000x2000 image matches both 3000x2000 and 2000x3000 limits.
  271. */
  272. private function validate_image_resolution($file_path, $product_id) {
  273. $limits = Studiou_WC_FPP_Product::get_product_resolution_limits($product_id);
  274. // Skip if no limits set
  275. $has_min = ($limits['min_width'] > 0 || $limits['min_height'] > 0);
  276. $has_max = ($limits['max_width'] > 0 || $limits['max_height'] > 0);
  277. if (!$has_min && !$has_max) {
  278. return true;
  279. }
  280. // Get image dimensions
  281. $size = @getimagesize($file_path);
  282. if (!$size || !isset($size[0], $size[1])) {
  283. // Cannot determine dimensions (e.g. RAW files) — skip validation
  284. return true;
  285. }
  286. $img_w = $size[0];
  287. $img_h = $size[1];
  288. // Normalize: always compare min(w,h) vs min(limit_w,limit_h) and max(w,h) vs max(limit_w,limit_h)
  289. // This makes portrait/landscape interchangeable
  290. $img_short = min($img_w, $img_h);
  291. $img_long = max($img_w, $img_h);
  292. // Minimum resolution check
  293. if ($has_min) {
  294. $min_short = min($limits['min_width'] ?: 0, $limits['min_height'] ?: 0);
  295. $min_long = max($limits['min_width'] ?: 0, $limits['min_height'] ?: 0);
  296. // If only one dimension is set, use it for both
  297. if ($min_short === 0) $min_short = $min_long;
  298. if ($img_short < $min_short || $img_long < $min_long) {
  299. return new WP_Error('resolution_too_small', sprintf(
  300. __('Image resolution %1$dx%2$d px is too small. Minimum required: %3$dx%4$d px.', 'studiou-wc-free-photo-product'),
  301. $img_w, $img_h, $limits['min_width'] ?: $limits['min_height'], $limits['min_height'] ?: $limits['min_width']
  302. ));
  303. }
  304. }
  305. // Maximum resolution check
  306. if ($has_max) {
  307. $max_short = min($limits['max_width'] ?: PHP_INT_MAX, $limits['max_height'] ?: PHP_INT_MAX);
  308. $max_long = max($limits['max_width'] ?: PHP_INT_MAX, $limits['max_height'] ?: PHP_INT_MAX);
  309. if ($max_short === PHP_INT_MAX) $max_short = $max_long;
  310. if ($img_short > $max_short || $img_long > $max_long) {
  311. return new WP_Error('resolution_too_large', sprintf(
  312. __('Image resolution %1$dx%2$d px is too large. Maximum allowed: %3$dx%4$d px.', 'studiou-wc-free-photo-product'),
  313. $img_w, $img_h, $limits['max_width'] ?: $limits['max_height'], $limits['max_height'] ?: $limits['max_width']
  314. ));
  315. }
  316. }
  317. return true;
  318. }
  319. private function cleanup_chunks($upload_id, $total_chunks) {
  320. $chunks_dir = $this->get_chunks_dir();
  321. for ($i = 0; $i < $total_chunks; $i++) {
  322. $chunk_file = $chunks_dir . '/' . $upload_id . '_chunk_' . $i;
  323. if (file_exists($chunk_file)) {
  324. unlink($chunk_file);
  325. }
  326. }
  327. }
  328. public function handle_remove_upload() {
  329. check_ajax_referer('studiou-wcfpp-front-nonce', 'nonce');
  330. $file_record_id = isset($_POST['file_record_id']) ? absint($_POST['file_record_id']) : 0;
  331. if (!$file_record_id) {
  332. wp_send_json_error(array('message' => __('Invalid file.', 'studiou-wc-free-photo-product')));
  333. return;
  334. }
  335. $record = $this->db->get_file_record($file_record_id);
  336. if (!$record) {
  337. wp_send_json_error(array('message' => __('File not found.', 'studiou-wc-free-photo-product')));
  338. return;
  339. }
  340. // Only allow removal if not yet linked to an order
  341. if ($record->order_id > 0) {
  342. wp_send_json_error(array('message' => __('Cannot remove a file linked to an order.', 'studiou-wc-free-photo-product')));
  343. return;
  344. }
  345. // Verify ownership
  346. $current_user_id = get_current_user_id();
  347. if ($current_user_id > 0 && (int) $record->customer_id !== $current_user_id) {
  348. wp_send_json_error(array('message' => __('Permission denied.', 'studiou-wc-free-photo-product')));
  349. return;
  350. }
  351. $this->db->delete_file_record($file_record_id);
  352. wp_send_json_success(array('message' => __('File removed.', 'studiou-wc-free-photo-product')));
  353. }
  354. const COOKIE_BATCH = 'studiou_fpp_batch';
  355. /**
  356. * Return the current visitor's batch token, minting + persisting a new one if absent.
  357. * Reads / writes the studiou_fpp_batch cookie.
  358. */
  359. public static function resolve_or_mint_batch_token() {
  360. if (!empty($_COOKIE[self::COOKIE_BATCH])) {
  361. $raw = preg_replace('/[^A-Za-z0-9]/', '', (string) $_COOKIE[self::COOKIE_BATCH]);
  362. if (strlen($raw) >= 16 && strlen($raw) <= 64) {
  363. return $raw;
  364. }
  365. }
  366. $token = wp_generate_password(32, false);
  367. $options = self::cookie_options(time() + DAY_IN_SECONDS);
  368. @setcookie(self::COOKIE_BATCH, $token, $options);
  369. $_COOKIE[self::COOKIE_BATCH] = $token;
  370. return $token;
  371. }
  372. public static function get_batch_token() {
  373. if (!empty($_COOKIE[self::COOKIE_BATCH])) {
  374. $raw = preg_replace('/[^A-Za-z0-9]/', '', (string) $_COOKIE[self::COOKIE_BATCH]);
  375. if (strlen($raw) >= 16 && strlen($raw) <= 64) {
  376. return $raw;
  377. }
  378. }
  379. return '';
  380. }
  381. public static function clear_batch_cookie() {
  382. $options = self::cookie_options(time() - DAY_IN_SECONDS);
  383. @setcookie(self::COOKIE_BATCH, '', $options);
  384. unset($_COOKIE[self::COOKIE_BATCH]);
  385. }
  386. private static function cookie_options($expires) {
  387. $path = defined('COOKIEPATH') && COOKIEPATH ? COOKIEPATH : '/';
  388. return array(
  389. 'expires' => (int) $expires,
  390. 'path' => $path,
  391. 'domain' => defined('COOKIE_DOMAIN') ? COOKIE_DOMAIN : '',
  392. 'secure' => is_ssl(),
  393. 'httponly' => true,
  394. 'samesite' => 'Lax',
  395. );
  396. }
  397. }