class-studiou-wc-product-manage-product-import.php 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042
  1. <?php
  2. /**
  3. * Product import class
  4. *
  5. * Handles product import from CSV files
  6. *
  7. * @since 1.4.0
  8. * @package Studiou_WC_Product_Cat_Manage
  9. * @subpackage Studiou_WC_Product_Cat_Manage/includes
  10. */
  11. // If this file is called directly, abort.
  12. if (!defined('WPINC')) {
  13. die;
  14. }
  15. class Studiou_WC_Product_Manage_Product_Import {
  16. /**
  17. * @var Studiou_WC_Product_Manage_Product_DB
  18. */
  19. private $db;
  20. /**
  21. * In-request cache of trimmed source URL => attachment ID, so the same URL
  22. * appearing multiple times within one AJAX batch costs at most one DB lookup.
  23. *
  24. * @var array<string,int>
  25. */
  26. private static $url_cache = array();
  27. /**
  28. * Constructor
  29. *
  30. * @param Studiou_WC_Product_Manage_Product_DB $db Database instance
  31. */
  32. public function __construct($db) {
  33. $this->db = $db;
  34. }
  35. /**
  36. * v1.7.0 — Return (and lazily create) the guarded staging directory used
  37. * by both the product and category importers. Replaces the transient-
  38. * based staging that capped at max_allowed_packet (M4).
  39. *
  40. * @return string Absolute path with trailing slash.
  41. */
  42. public static function get_staging_dir() {
  43. $upload_dir = wp_upload_dir();
  44. $dir = trailingslashit($upload_dir['basedir']) . 'studiou-wcpcm-staging/';
  45. if (!file_exists($dir)) {
  46. wp_mkdir_p($dir);
  47. }
  48. $idx = $dir . 'index.php';
  49. if (!file_exists($idx)) {
  50. @file_put_contents($idx, '<?php // Silence is golden.');
  51. }
  52. $ht = $dir . '.htaccess';
  53. if (!file_exists($ht)) {
  54. @file_put_contents($ht, "Deny from all\n");
  55. }
  56. return $dir;
  57. }
  58. /**
  59. * v1.7.0 — Prune staging files older than 24h.
  60. */
  61. public static function prune_staging() {
  62. $dir = self::get_staging_dir();
  63. $cutoff = time() - DAY_IN_SECONDS;
  64. $files = glob($dir . '*.json');
  65. if (!is_array($files)) { return; }
  66. foreach ($files as $f) {
  67. $mtime = @filemtime($f);
  68. if ($mtime !== false && $mtime < $cutoff) {
  69. @unlink($f);
  70. }
  71. }
  72. }
  73. /**
  74. * v1.7.0 — Stage an array of rows to a token-named JSON file. Returns
  75. * the token, or false on write failure.
  76. *
  77. * @param array $rows
  78. * @param string $prefix e.g. 'product' or 'category'
  79. * @return string|false
  80. */
  81. public static function stage_rows($rows, $prefix = 'product') {
  82. self::prune_staging();
  83. $token = $prefix . '-' . bin2hex(random_bytes(16));
  84. $path = self::get_staging_dir() . $token . '.json';
  85. $encoded = wp_json_encode($rows);
  86. if ($encoded === false || file_put_contents($path, $encoded) === false) {
  87. return false;
  88. }
  89. return $token;
  90. }
  91. /**
  92. * v1.7.0 — Read a slice of a staged file.
  93. *
  94. * @param string $token
  95. * @param int $offset
  96. * @param int $batch_size
  97. * @return array|null array{total:int,batch:array} or null if missing/unreadable
  98. */
  99. public static function read_stage_slice($token, $offset, $batch_size) {
  100. // Validate the token shape (defends against path traversal).
  101. if (!preg_match('/^(product|category)-[a-f0-9]{32}$/', $token)) {
  102. return null;
  103. }
  104. $path = self::get_staging_dir() . $token . '.json';
  105. if (!file_exists($path)) { return null; }
  106. $raw = file_get_contents($path);
  107. if ($raw === false) { return null; }
  108. $rows = json_decode($raw, true);
  109. if (!is_array($rows)) { return null; }
  110. return array(
  111. 'total' => count($rows),
  112. 'batch' => array_slice($rows, $offset, $batch_size),
  113. );
  114. }
  115. /**
  116. * v1.7.0 — Delete a staged file (e.g. on completion).
  117. *
  118. * @param string $token
  119. */
  120. public static function delete_stage($token) {
  121. if (!preg_match('/^(product|category)-[a-f0-9]{32}$/', $token)) {
  122. return;
  123. }
  124. @unlink(self::get_staging_dir() . $token . '.json');
  125. }
  126. /**
  127. * Parse CSV file and store data for batch processing
  128. *
  129. * @param string $file_path Path to CSV file
  130. * @return array Result with total count and transient key
  131. */
  132. public function parse_csv_for_batch($file_path) {
  133. if (!file_exists($file_path)) {
  134. return array('error' => __('File not found', 'studiou-wc-product-cat-manage'));
  135. }
  136. // Open CSV file
  137. $handle = fopen($file_path, 'r');
  138. if (!$handle) {
  139. return array('error' => __('Could not open file', 'studiou-wc-product-cat-manage'));
  140. }
  141. // M3 — strip UTF-8 BOM if present so the first header cell isn't
  142. // "\xEF\xBB\xBFID", which would make every row miss the ID key and
  143. // be treated as new (and then likely skipped by SKU-uniqueness).
  144. $bom = fread($handle, 3);
  145. if ($bom !== "\xEF\xBB\xBF") {
  146. rewind($handle);
  147. }
  148. // Read header row
  149. $header = fgetcsv($handle, 0, ',', '"');
  150. if (!$header) {
  151. fclose($handle);
  152. return array('error' => __('Invalid CSV format', 'studiou-wc-product-cat-manage'));
  153. }
  154. $header_count = count($header);
  155. // Read all data rows
  156. $rows = array();
  157. $skipped_rows = array();
  158. $row_number = 1;
  159. while (($row = fgetcsv($handle, 0, ',', '"')) !== false) {
  160. $row_number++;
  161. // Skip empty rows
  162. if (empty(array_filter($row))) {
  163. continue;
  164. }
  165. // H4 — guard array_combine: on PHP 8+ it throws ValueError when
  166. // the row width doesn't match the header. ValueError extends
  167. // Error (not Exception), so the surrounding catches miss it and
  168. // the whole import dies with a bare 500. Pad short rows (likely
  169. // trailing empty cells from Excel); skip and report over-long
  170. // rows (an unescaped comma we can't safely recover).
  171. $row_count = count($row);
  172. if ($row_count < $header_count) {
  173. $row = array_pad($row, $header_count, '');
  174. } elseif ($row_count > $header_count) {
  175. $padded_for_failed = array_pad($row, $header_count, '');
  176. $padded_for_failed = array_slice($padded_for_failed, 0, $header_count);
  177. $skipped_rows[] = array(
  178. 'row_number' => $row_number,
  179. 'data' => array_combine($header, $padded_for_failed),
  180. 'reason' => sprintf(
  181. /* translators: 1: row number, 2: actual column count, 3: expected column count */
  182. __('Row %1$d: column count mismatch (%2$d found, %3$d expected) — likely an unescaped comma. Row skipped.', 'studiou-wc-product-cat-manage'),
  183. $row_number,
  184. $row_count,
  185. $header_count
  186. ),
  187. );
  188. continue;
  189. }
  190. // Combine header with row data
  191. $data = array_combine($header, $row);
  192. $rows[] = array(
  193. 'row_number' => $row_number,
  194. 'data' => $data
  195. );
  196. }
  197. fclose($handle);
  198. // M4 (guard) — set_transient returns false when the serialized
  199. // payload exceeds max_allowed_packet or storage fails for any
  200. // other reason. The downstream batch handler then reports
  201. // "Import data not found or expired", which is misleading — the
  202. // upload was fine, the store just couldn't take it. Surface a
  203. // clear, actionable message instead. The disk-staging rework that
  204. // actually removes this ceiling lands in Phase D.
  205. // v1.7.0 — M4 rework: stage rows on disk instead of in a transient.
  206. // The transient was a single wp_options row; large CSVs overflowed
  207. // max_allowed_packet and set_transient returned false, surfacing as
  208. // the misleading "Import data not found or expired" downstream.
  209. // Disk staging has no such ceiling. The staging file is guarded
  210. // (index.php + .htaccess), token-named, and pruned at 24h.
  211. $payload = array(
  212. 'rows' => $rows,
  213. 'skipped' => $skipped_rows,
  214. );
  215. $token = self::stage_rows($payload, 'product');
  216. if ($token === false) {
  217. return array('error' => __('Failed to stage import data on disk (write error).', 'studiou-wc-product-cat-manage'));
  218. }
  219. return array(
  220. // Legacy field name preserved so the JS keeps working without
  221. // changes; the value is now a disk-staging token, not a
  222. // transient key. process_batch reads from disk via the token.
  223. 'transient_key' => $token,
  224. 'total' => count($rows),
  225. );
  226. }
  227. /**
  228. * Process batch of products
  229. *
  230. * @param string $transient_key Transient key with CSV data
  231. * @param int $offset Starting offset
  232. * @param int $batch_size Number of items to process
  233. * @return array Result with statistics
  234. */
  235. public function process_batch($transient_key, $offset = 0, $batch_size = 5) {
  236. // v1.7.0 — read from disk-staging instead of the WP transient.
  237. // First load the full payload so we know total + skipped rows.
  238. $dir = self::get_staging_dir();
  239. if (!preg_match('/^product-[a-f0-9]{32}$/', $transient_key)) {
  240. return array('error' => __('Import data not found or expired', 'studiou-wc-product-cat-manage'));
  241. }
  242. $path = $dir . $transient_key . '.json';
  243. if (!file_exists($path)) {
  244. return array('error' => __('Import data not found or expired', 'studiou-wc-product-cat-manage'));
  245. }
  246. $raw = file_get_contents($path);
  247. if ($raw === false) {
  248. return array('error' => __('Import data not found or expired', 'studiou-wc-product-cat-manage'));
  249. }
  250. $payload = json_decode($raw, true);
  251. if (!is_array($payload) || !isset($payload['rows'])) {
  252. return array('error' => __('Import data not found or expired', 'studiou-wc-product-cat-manage'));
  253. }
  254. $rows = $payload['rows'];
  255. $skipped_at_parse = isset($payload['skipped']) ? $payload['skipped'] : array();
  256. $result = array(
  257. 'success' => 0,
  258. 'failed' => 0,
  259. 'skipped' => 0,
  260. 'failed_items' => array(),
  261. 'messages' => array(),
  262. 'processed' => 0,
  263. 'total' => count($rows)
  264. );
  265. // Get batch of rows to process
  266. $batch = array_slice($rows, $offset, $batch_size);
  267. // On the final batch, fold in any ragged-row skips from the parse
  268. // step (set by parse_csv_for_batch when row width != header width)
  269. // so they appear in the failed-CSV download and the messages list.
  270. $is_final_batch = ($offset + count($batch)) >= count($rows);
  271. if ($is_final_batch && !empty($skipped_at_parse)) {
  272. foreach ($skipped_at_parse as $skip) {
  273. $result['skipped']++;
  274. $result['messages'][] = $skip['reason'];
  275. $result['failed_items'][] = $skip['data'];
  276. }
  277. }
  278. foreach ($batch as $item) {
  279. $row_number = $item['row_number'];
  280. $data = $item['data'];
  281. // Process the product
  282. $process_result = $this->process_product_row($data, $row_number);
  283. if ($process_result['status'] === 'success') {
  284. $result['success']++;
  285. // Don't add success messages to log
  286. } elseif ($process_result['status'] === 'skipped') {
  287. $result['skipped']++;
  288. $result['messages'][] = sprintf(
  289. __('Row %d: SKIPPED - %s', 'studiou-wc-product-cat-manage'),
  290. $row_number,
  291. $process_result['message']
  292. );
  293. // Add to failed items for re-processing
  294. $result['failed_items'][] = $data;
  295. } else {
  296. $result['failed']++;
  297. $result['messages'][] = sprintf(
  298. __('Row %d: FAILED - %s', 'studiou-wc-product-cat-manage'),
  299. $row_number,
  300. $process_result['message']
  301. );
  302. // Add to failed items
  303. $result['failed_items'][] = $data;
  304. }
  305. }
  306. $result['processed'] = $offset + count($batch);
  307. // v1.7.0 — delete the staging file when the import is complete so
  308. // we don't leak token-named JSON files into uploads/. (Pruning at
  309. // 24h would catch them eventually, but cleaning at completion is
  310. // the precise time.)
  311. if ($is_final_batch) {
  312. self::delete_stage($transient_key);
  313. }
  314. return $result;
  315. }
  316. /**
  317. * Process single product row
  318. *
  319. * @param array $data Product data
  320. * @param int $row_number Row number for error reporting
  321. * @return array Result with status and message
  322. */
  323. private function process_product_row($data, $row_number) {
  324. // Validate required fields
  325. if (!isset($data['Typ']) || empty($data['Typ'])) {
  326. return array(
  327. 'status' => 'skipped',
  328. 'message' => __('Missing product type', 'studiou-wc-product-cat-manage')
  329. );
  330. }
  331. // Rule 3: Only allow "variable" or "variation" types
  332. $type = trim($data['Typ']);
  333. if (!in_array($type, array('variable', 'variation'))) {
  334. return array(
  335. 'status' => 'skipped',
  336. 'message' => sprintf(
  337. __('Invalid product type: %s (only "variable" or "variation" allowed)', 'studiou-wc-product-cat-manage'),
  338. $type
  339. )
  340. );
  341. }
  342. // Get product ID
  343. $product_id = isset($data['ID']) ? intval($data['ID']) : 0;
  344. $sku = isset($data['Katalogové číslo']) ? trim($data['Katalogové číslo']) : '';
  345. // Rule 4: SKU must be unique
  346. if (empty($sku)) {
  347. return array(
  348. 'status' => 'skipped',
  349. 'message' => __('Missing SKU (Katalogové číslo)', 'studiou-wc-product-cat-manage')
  350. );
  351. }
  352. if (!$this->db->is_sku_unique($sku, $product_id)) {
  353. return array(
  354. 'status' => 'skipped',
  355. 'message' => sprintf(
  356. __('SKU "%s" already exists', 'studiou-wc-product-cat-manage'),
  357. $sku
  358. )
  359. );
  360. }
  361. // Rule 5: Validate image URL if provided
  362. $image_url = isset($data['Obrázky']) ? trim($data['Obrázky']) : '';
  363. if (!empty($image_url) && !$this->db->validate_image_url($image_url)) {
  364. return array(
  365. 'status' => 'skipped',
  366. 'message' => sprintf(
  367. __('Invalid image URL: %s', 'studiou-wc-product-cat-manage'),
  368. $image_url
  369. )
  370. );
  371. }
  372. // Process based on product type
  373. if ($type === 'variation') {
  374. return $this->process_variation($data, $product_id);
  375. } else {
  376. return $this->process_variable_product($data, $product_id);
  377. }
  378. }
  379. /**
  380. * Process variable product
  381. *
  382. * @param array $data Product data
  383. * @param int $product_id Product ID (0 for new product)
  384. * @return array Result with status and message
  385. */
  386. private function process_variable_product($data, $product_id) {
  387. try {
  388. // Create or update product
  389. if ($product_id == 0) {
  390. $product = new WC_Product_Variable();
  391. } else {
  392. $product = wc_get_product($product_id);
  393. if (!$product || !$product->is_type('variable')) {
  394. return array(
  395. 'status' => 'error',
  396. 'message' => sprintf(
  397. __('Product ID %d is not a variable product', 'studiou-wc-product-cat-manage'),
  398. $product_id
  399. )
  400. );
  401. }
  402. }
  403. // Set basic data
  404. $product->set_name(isset($data['Jméno']) ? $data['Jméno'] : '');
  405. $product->set_sku(isset($data['Katalogové číslo']) ? $data['Katalogové číslo'] : '');
  406. $product->set_short_description(isset($data['Krátký popis']) ? $data['Krátký popis'] : '');
  407. $product->set_description(isset($data['Popis']) ? $data['Popis'] : '');
  408. // v1.7.1 — M7: gate success-path logging behind WP_DEBUG so a
  409. // normal production import doesn't write dozens of lines per
  410. // row to error.log. Failure-path logs stay always-on (matches
  411. // the documented "Only logs failures" policy).
  412. $debug = defined('WP_DEBUG') && WP_DEBUG;
  413. if (isset($data['Kategorie']) && !empty($data['Kategorie'])) {
  414. $categories = array_map('trim', explode('|', $data['Kategorie']));
  415. $category_ids = array();
  416. if ($debug) {
  417. error_log('STUDIOU WC IMPORT: Processing categories for product: ' . $product->get_name());
  418. error_log('STUDIOU WC IMPORT: Categories string from CSV: ' . $data['Kategorie']);
  419. }
  420. foreach ($categories as $category_name) {
  421. if (empty($category_name)) {
  422. continue;
  423. }
  424. $category_id = $this->find_category_by_name($category_name);
  425. if ($debug) {
  426. error_log('STUDIOU WC IMPORT: Looking for category "' . $category_name . '" - Result: ' . ($category_id ? 'FOUND ID=' . $category_id : 'NOT FOUND'));
  427. }
  428. if ($category_id) {
  429. $category_ids[] = $category_id;
  430. }
  431. }
  432. if ($debug) {
  433. error_log('STUDIOU WC IMPORT: Total category IDs found: ' . count($category_ids) . ' - IDs: ' . implode(',', $category_ids));
  434. }
  435. if (!empty($category_ids)) {
  436. $product->set_category_ids($category_ids);
  437. if ($debug) {
  438. error_log('STUDIOU WC IMPORT: Categories assigned to product via set_category_ids()');
  439. }
  440. } else {
  441. // Always-on: a row that names categories but resolves zero is a real failure worth logging.
  442. error_log('STUDIOU WC IMPORT: WARNING - No valid category IDs found for: ' . $data['Kategorie']);
  443. }
  444. } else if ($debug) {
  445. error_log('STUDIOU WC IMPORT: No categories in CSV for product: ' . $product->get_name());
  446. }
  447. // Handle image
  448. if (isset($data['Obrázky']) && !empty($data['Obrázky'])) {
  449. $image_id = $this->upload_image_from_url($data['Obrázky']);
  450. if ($image_id) {
  451. $product->set_image_id($image_id);
  452. }
  453. }
  454. // Set reviews enabled
  455. $reviews_enabled = isset($data['Povolit zákaznické recenze?']) && $data['Povolit zákaznické recenze?'] === '1';
  456. $product->set_reviews_allowed($reviews_enabled);
  457. // v1.6.3 — Handle product attribute (taxonomy vs. custom).
  458. //
  459. // Pre-1.6.3 behaviour ignored the `Vlastnost 1 globální` column and
  460. // forced every attribute into a global pa_ taxonomy: it called
  461. // create_attribute_if_not_exists() unconditionally, set the
  462. // attribute name via wc_attribute_taxonomy_name(), and passed raw
  463. // name strings to set_options(). Result: custom (product-level)
  464. // attributes silently became global taxonomies; for variations,
  465. // raw names landed where slugs were required, so the storefront
  466. // couldn't match the customer's selection ("No matching variation").
  467. //
  468. // Branch on the global flag and, for the taxonomy path, resolve
  469. // each value to a term (creating it if missing), pass term IDs to
  470. // set_options(), remember the slugs so process_variation() can
  471. // store the correct value, and link the terms via
  472. // wp_set_object_terms after the product save.
  473. //
  474. // Hand-built CSVs that omit `Vlastnost 1 globální` default to the
  475. // custom branch.
  476. //
  477. // LIVE-TEST GATE: §5.B.0 of review-00-plan-00.md asks for a real
  478. // storefront round-trip before deploy. Verify both the taxonomy
  479. // and custom paths there.
  480. $term_ids_for_link = array();
  481. $taxonomy_for_link = '';
  482. if (isset($data['Název 1 vlastnosti']) && !empty($data['Název 1 vlastnosti'])) {
  483. $attribute_name = trim($data['Název 1 vlastnosti']);
  484. $attribute_values = isset($data['Hodnota(y) 1 vlastnosti']) ? $data['Hodnota(y) 1 vlastnosti'] : '';
  485. $is_visible = isset($data['Vlastnost 1 viditelnost']) && $data['Vlastnost 1 viditelnost'] === '1';
  486. $is_variation = isset($data['Vlastnost 1 varianta']) && $data['Vlastnost 1 varianta'] === '1';
  487. $is_global = isset($data['Vlastnost 1 globální']) && $data['Vlastnost 1 globální'] === '1';
  488. $values = array_map('trim', explode('|', $attribute_values));
  489. $values = array_values(array_filter($values, function($v) { return $v !== ''; }));
  490. $attribute = new WC_Product_Attribute();
  491. if ($is_global) {
  492. // Taxonomy attribute — register, resolve/create terms,
  493. // pass term IDs (not names) to set_options.
  494. $this->db->create_attribute_if_not_exists($attribute_name);
  495. $taxonomy = wc_attribute_taxonomy_name($attribute_name);
  496. if (!taxonomy_exists($taxonomy)) {
  497. register_taxonomy($taxonomy, 'product');
  498. }
  499. $term_ids = array();
  500. foreach ($values as $value) {
  501. $term = get_term_by('name', $value, $taxonomy);
  502. if (!$term) {
  503. $inserted = wp_insert_term($value, $taxonomy);
  504. if (is_wp_error($inserted)) {
  505. error_log('STUDIOU WC IMPORT: failed to insert term "' . $value . '" into ' . $taxonomy . ': ' . $inserted->get_error_message());
  506. continue;
  507. }
  508. $term = get_term($inserted['term_id'], $taxonomy);
  509. }
  510. if ($term && !is_wp_error($term)) {
  511. $term_ids[] = (int) $term->term_id;
  512. }
  513. }
  514. $attribute->set_id(wc_attribute_taxonomy_id_by_name($attribute_name));
  515. $attribute->set_name($taxonomy);
  516. $attribute->set_options($term_ids);
  517. $attribute->set_visible($is_visible);
  518. $attribute->set_variation($is_variation);
  519. $product->set_attributes(array($attribute));
  520. // Defer term-relationship linkage until after save() so we
  521. // have a real product ID.
  522. $term_ids_for_link = $term_ids;
  523. $taxonomy_for_link = $taxonomy;
  524. } else {
  525. // Custom (product-level) attribute — no taxonomy, store
  526. // the raw display name and the raw values.
  527. $attribute->set_id(0);
  528. $attribute->set_name($attribute_name);
  529. $attribute->set_options($values);
  530. $attribute->set_visible($is_visible);
  531. $attribute->set_variation($is_variation);
  532. $product->set_attributes(array($attribute));
  533. }
  534. }
  535. // Handle minimum/maximum quantity
  536. if (isset($data['Minimum Quantity']) && !empty($data['Minimum Quantity'])) {
  537. $product->update_meta_data('_minimum_quantity', intval($data['Minimum Quantity']));
  538. }
  539. if (isset($data['Maximum Quantity']) && !empty($data['Maximum Quantity'])) {
  540. $product->update_meta_data('_maximum_quantity', intval($data['Maximum Quantity']));
  541. }
  542. // Save product
  543. $saved_id = $product->save();
  544. // Belt-and-braces: link the attribute terms to the freshly-saved
  545. // product. Modern WC CRUD typically does this on save() when
  546. // set_options() receives term IDs, but the link is cheap and
  547. // makes the import robust against WC internals changes.
  548. if (!empty($term_ids_for_link) && $taxonomy_for_link !== '' && $saved_id) {
  549. wp_set_object_terms($saved_id, $term_ids_for_link, $taxonomy_for_link, false);
  550. }
  551. $message = $product_id == 0 ?
  552. sprintf(__('Created variable product: %s', 'studiou-wc-product-cat-manage'), $product->get_name()) :
  553. sprintf(__('Updated variable product: %s', 'studiou-wc-product-cat-manage'), $product->get_name());
  554. return array(
  555. 'status' => 'success',
  556. 'message' => $message
  557. );
  558. } catch (Exception $e) {
  559. return array(
  560. 'status' => 'error',
  561. 'message' => $e->getMessage()
  562. );
  563. }
  564. }
  565. /**
  566. * Process product variation
  567. *
  568. * @param array $data Product data
  569. * @param int $variation_id Variation ID (0 for new variation)
  570. * @return array Result with status and message
  571. */
  572. private function process_variation($data, $variation_id) {
  573. try {
  574. // Rule 6: Must have parent reference
  575. if (!isset($data['Nadřazené']) || empty($data['Nadřazené'])) {
  576. return array(
  577. 'status' => 'skipped',
  578. 'message' => __('Missing parent product reference (Nadřazené)', 'studiou-wc-product-cat-manage')
  579. );
  580. }
  581. // Rule 7: Must have regular price
  582. if (!isset($data['Běžná cena']) || empty($data['Běžná cena'])) {
  583. return array(
  584. 'status' => 'skipped',
  585. 'message' => __('Missing regular price (Běžná cena)', 'studiou-wc-product-cat-manage')
  586. );
  587. }
  588. // Find parent product by SKU
  589. $parent_sku = trim($data['Nadřazené']);
  590. $parent_product = $this->db->get_product_by_sku($parent_sku);
  591. if (!$parent_product || !$parent_product->is_type('variable')) {
  592. return array(
  593. 'status' => 'skipped',
  594. 'message' => sprintf(
  595. __('Parent product with SKU "%s" not found or not variable', 'studiou-wc-product-cat-manage'),
  596. $parent_sku
  597. )
  598. );
  599. }
  600. // Create or update variation
  601. if ($variation_id == 0) {
  602. $variation = new WC_Product_Variation();
  603. $variation->set_parent_id($parent_product->get_id());
  604. } else {
  605. $variation = wc_get_product($variation_id);
  606. if (!$variation || !$variation->is_type('variation')) {
  607. return array(
  608. 'status' => 'error',
  609. 'message' => sprintf(
  610. __('Product ID %d is not a variation', 'studiou-wc-product-cat-manage'),
  611. $variation_id
  612. )
  613. );
  614. }
  615. }
  616. // Set basic data
  617. $variation->set_name(isset($data['Jméno']) ? $data['Jméno'] : '');
  618. $variation->set_sku(isset($data['Katalogové číslo']) ? $data['Katalogové číslo'] : '');
  619. $variation->set_description(isset($data['Popis']) ? $data['Popis'] : '');
  620. $variation->set_regular_price($data['Běžná cena']);
  621. // Handle image
  622. if (isset($data['Obrázky']) && !empty($data['Obrázky'])) {
  623. $image_id = $this->upload_image_from_url($data['Obrázky']);
  624. if ($image_id) {
  625. $variation->set_image_id($image_id);
  626. }
  627. }
  628. // v1.6.3 — Variation attribute (taxonomy vs. custom).
  629. //
  630. // Pre-1.6.3 stored the raw value (e.g. "Red") under the taxonomy
  631. // meta key (e.g. attribute_pa_color). WC matches variations by
  632. // term slug ("red"), so the variation was unreachable on the
  633. // storefront. Now: for taxonomy attributes resolve the value to
  634. // its term slug; for custom attributes store the literal value
  635. // under attribute_<sanitized name>.
  636. if (isset($data['Název 1 vlastnosti']) && !empty($data['Název 1 vlastnosti']) &&
  637. isset($data['Hodnota(y) 1 vlastnosti']) && !empty($data['Hodnota(y) 1 vlastnosti'])) {
  638. $attribute_name = trim($data['Název 1 vlastnosti']);
  639. $attribute_value = trim($data['Hodnota(y) 1 vlastnosti']);
  640. $is_global = isset($data['Vlastnost 1 globální']) && $data['Vlastnost 1 globální'] === '1';
  641. if ($is_global) {
  642. $taxonomy = wc_attribute_taxonomy_name($attribute_name);
  643. $term = get_term_by('name', $attribute_value, $taxonomy);
  644. if (!$term) {
  645. // The variation row may arrive before its parent's
  646. // taxonomy terms exist (rare but possible on hand-built
  647. // CSVs). Create it so the variation is selectable.
  648. if (!taxonomy_exists($taxonomy)) {
  649. $this->db->create_attribute_if_not_exists($attribute_name);
  650. register_taxonomy($taxonomy, 'product');
  651. }
  652. $inserted = wp_insert_term($attribute_value, $taxonomy);
  653. if (!is_wp_error($inserted)) {
  654. $term = get_term($inserted['term_id'], $taxonomy);
  655. }
  656. }
  657. $slug = ($term && !is_wp_error($term)) ? $term->slug : sanitize_title($attribute_value);
  658. $variation->set_attributes(array($taxonomy => $slug));
  659. } else {
  660. $variation->set_attributes(array(
  661. sanitize_title($attribute_name) => $attribute_value,
  662. ));
  663. }
  664. }
  665. // Handle minimum/maximum quantity
  666. if (isset($data['Minimum Quantity']) && !empty($data['Minimum Quantity'])) {
  667. $variation->update_meta_data('_minimum_quantity', intval($data['Minimum Quantity']));
  668. }
  669. if (isset($data['Maximum Quantity']) && !empty($data['Maximum Quantity'])) {
  670. $variation->update_meta_data('_maximum_quantity', intval($data['Maximum Quantity']));
  671. }
  672. // Save variation
  673. $saved_id = $variation->save();
  674. $message = $variation_id == 0 ?
  675. sprintf(__('Created variation: %s', 'studiou-wc-product-cat-manage'), $variation->get_name()) :
  676. sprintf(__('Updated variation: %s', 'studiou-wc-product-cat-manage'), $variation->get_name());
  677. return array(
  678. 'status' => 'success',
  679. 'message' => $message
  680. );
  681. } catch (Exception $e) {
  682. return array(
  683. 'status' => 'error',
  684. 'message' => $e->getMessage()
  685. );
  686. }
  687. }
  688. /**
  689. * Find an attachment previously imported from this exact source URL.
  690. *
  691. * Uses get_posts (not a raw $wpdb query) so a row whose attachment post was
  692. * deleted but whose meta was somehow orphaned can't resolve to a missing post.
  693. * Orders by ID ascending so the earliest (canonical) attachment wins
  694. * deterministically if more than one ever carries the same source URL.
  695. *
  696. * @param string $url Trimmed source URL.
  697. * @return int Attachment ID, or 0 if none.
  698. */
  699. private function find_attachment_by_source_url($url) {
  700. $ids = get_posts(array(
  701. 'post_type' => 'attachment',
  702. 'post_status' => 'inherit',
  703. 'posts_per_page' => 1,
  704. 'orderby' => 'ID',
  705. 'order' => 'ASC',
  706. 'fields' => 'ids',
  707. 'no_found_rows' => true,
  708. 'update_post_meta_cache' => false,
  709. 'update_post_term_cache' => false,
  710. 'meta_query' => array(
  711. array(
  712. 'key' => '_studiou_wcpcm_source_url',
  713. 'value' => $url,
  714. 'compare' => '=',
  715. ),
  716. ),
  717. ));
  718. return !empty($ids) ? (int) $ids[0] : 0;
  719. }
  720. /**
  721. * Upload an image from a URL, deduplicating by source URL.
  722. *
  723. * A given source URL is downloaded at most once: an in-request static cache
  724. * absorbs repeats within a batch, and a `_studiou_wcpcm_source_url` postmeta
  725. * lookup reuses attachments across batches and across imports.
  726. *
  727. * @param string $url Image URL (raw value from the Obrázky column).
  728. * @return int|null Attachment ID, or null on empty input / download failure.
  729. */
  730. private function upload_image_from_url($url) {
  731. // Normalize the key. process_product_row() validates a *trimmed* URL but
  732. // the callers pass the raw cell, so trim here to keep the cache key, the
  733. // DB lookup, the download, and the stored postmeta all identical to the
  734. // value that was validated (and to collapse whitespace-only variants).
  735. $url = is_string($url) ? trim($url) : '';
  736. if ($url === '') {
  737. return null;
  738. }
  739. // Layer 2 — in-request static cache.
  740. if (isset(self::$url_cache[$url])) {
  741. if (defined('WP_DEBUG') && WP_DEBUG) {
  742. error_log('STUDIOU WC IMPORT: image cache HIT (request) ' . $url . ' -> ' . self::$url_cache[$url]);
  743. }
  744. return self::$url_cache[$url];
  745. }
  746. // Layer 1 — persistent postmeta lookup (across batches and re-imports).
  747. $existing = $this->find_attachment_by_source_url($url);
  748. if ($existing) {
  749. self::$url_cache[$url] = $existing;
  750. if (defined('WP_DEBUG') && WP_DEBUG) {
  751. error_log('STUDIOU WC IMPORT: image cache HIT (db) ' . $url . ' -> ' . $existing);
  752. }
  753. return $existing;
  754. }
  755. // Layer 0 — fresh sideload.
  756. require_once(ABSPATH . 'wp-admin/includes/media.php');
  757. require_once(ABSPATH . 'wp-admin/includes/file.php');
  758. require_once(ABSPATH . 'wp-admin/includes/image.php');
  759. // Suppress intermediate sizes for import speed. Use the stable
  760. // '__return_empty_array' callable (not a fresh closure) so remove_filter()
  761. // can actually match it, and detach it in finally so it can never leak
  762. // into later media operations in this request.
  763. add_filter('intermediate_image_sizes_advanced', '__return_empty_array');
  764. try {
  765. // download_url()'s second arg sets the request timeout (30s); no
  766. // http_request_timeout filter is needed.
  767. $tmp = download_url($url, 30);
  768. if (is_wp_error($tmp)) {
  769. error_log('STUDIOU WC IMPORT: image download failed for ' . $url . ' - ' . $tmp->get_error_message());
  770. return null;
  771. }
  772. // Derive a clean on-disk filename. parse_url() strips any query string
  773. // (img.jpg?v=2 -> img.jpg) so wp_unique_filename() doesn't fold the
  774. // query into the basename. Null-safe: parse_url() may return null/false
  775. // and basename(null) is deprecated on PHP 8.1+ (we require 8.2).
  776. $path = parse_url($url, PHP_URL_PATH);
  777. $name = (is_string($path) && $path !== '') ? basename($path) : '';
  778. if ($name === '') {
  779. $name = 'image-' . md5($url) . '.jpg';
  780. }
  781. $file_array = array(
  782. 'name' => $name,
  783. 'tmp_name' => $tmp,
  784. );
  785. $id = media_handle_sideload($file_array, 0);
  786. if (is_wp_error($id)) {
  787. @unlink($tmp);
  788. error_log('STUDIOU WC IMPORT: image sideload failed for ' . $url . ' - ' . $id->get_error_message());
  789. return null;
  790. }
  791. // Tag the attachment so future rows / batches / imports dedup on it.
  792. update_post_meta($id, '_studiou_wcpcm_source_url', $url);
  793. self::$url_cache[$url] = (int) $id;
  794. if (defined('WP_DEBUG') && WP_DEBUG) {
  795. error_log('STUDIOU WC IMPORT: image sideloaded ' . $url . ' -> ' . $id);
  796. }
  797. return (int) $id;
  798. } catch (Exception $e) {
  799. error_log('STUDIOU WC IMPORT: image upload exception for ' . $url . ' - ' . $e->getMessage());
  800. return null;
  801. } finally {
  802. remove_filter('intermediate_image_sizes_advanced', '__return_empty_array');
  803. }
  804. }
  805. /**
  806. * v1.7.1 — M8: per-request cache of the entire product_cat term list.
  807. * Populated lazily on first miss-path call to get_terms(); reused for
  808. * every subsequent row in the same AJAX batch. Resets naturally when
  809. * the request ends, so changes mid-import (e.g. categories we just
  810. * created) are picked up — wp_insert_term + cache append is handled
  811. * inline below.
  812. *
  813. * @var array<int,object>|null Terms keyed by term_id, or null if not loaded.
  814. */
  815. private static $all_product_cats_cache = null;
  816. /**
  817. * v1.7.1 — M8: thin alias of find_or_create_category_by_name() so
  818. * existing call sites keep compiling. The rename clarifies that this
  819. * method also CREATES the term as a side effect, which used to be
  820. * surprising for a function called "find".
  821. *
  822. * @param string $category_name
  823. * @return int|null
  824. */
  825. private function find_category_by_name($category_name) {
  826. return $this->find_or_create_category_by_name($category_name);
  827. }
  828. /**
  829. * Find a category by name; create it if missing.
  830. *
  831. * @param string $category_name
  832. * @return int|null Term ID or null if creation failed.
  833. */
  834. private function find_or_create_category_by_name($category_name) {
  835. $debug = defined('WP_DEBUG') && WP_DEBUG;
  836. $category_name = trim($category_name);
  837. if (empty($category_name)) {
  838. return null;
  839. }
  840. if ($debug) {
  841. error_log('STUDIOU WC IMPORT: find_or_create_category_by_name() called for: "' . $category_name . '"');
  842. }
  843. // Method 1: Exact name match
  844. $term = get_term_by('name', $category_name, 'product_cat');
  845. if ($term) {
  846. if ($debug) { error_log('STUDIOU WC IMPORT: Found by exact name match - ID: ' . $term->term_id); }
  847. return $term->term_id;
  848. }
  849. // Method 2: Try by slug
  850. $slug = sanitize_title($category_name);
  851. if ($debug) { error_log('STUDIOU WC IMPORT: Exact name failed, trying slug: "' . $slug . '"'); }
  852. $term = get_term_by('slug', $slug, 'product_cat');
  853. if ($term) {
  854. if ($debug) { error_log('STUDIOU WC IMPORT: Found by slug match - ID: ' . $term->term_id); }
  855. return $term->term_id;
  856. }
  857. // Method 3: Search case-insensitively through all categories. Pre-1.7.1
  858. // this called get_terms() on EVERY miss-path row — O(N) categories per
  859. // miss, O(N*M) overall on a multi-row import. Now we load once per
  860. // request and reuse.
  861. if (self::$all_product_cats_cache === null) {
  862. $loaded = get_terms(array(
  863. 'taxonomy' => 'product_cat',
  864. 'hide_empty' => false,
  865. ));
  866. self::$all_product_cats_cache = is_array($loaded) ? $loaded : array();
  867. }
  868. if ($debug) {
  869. error_log('STUDIOU WC IMPORT: Slug failed, searching ' . count(self::$all_product_cats_cache) . ' categories case-insensitively');
  870. }
  871. foreach (self::$all_product_cats_cache as $t) {
  872. if (strcasecmp($t->name, $category_name) === 0) {
  873. if ($debug) { error_log('STUDIOU WC IMPORT: Found by case-insensitive match - ID: ' . $t->term_id . ', name: "' . $t->name . '"'); }
  874. return $t->term_id;
  875. }
  876. }
  877. // Not found — create it (always-on log because category creation is a real side effect).
  878. error_log('STUDIOU WC IMPORT: Category NOT FOUND: "' . $category_name . '" - Attempting to create it');
  879. $new_term = wp_insert_term($category_name, 'product_cat', array('slug' => $slug));
  880. if (is_wp_error($new_term)) {
  881. error_log('STUDIOU WC IMPORT: Failed to create category "' . $category_name . '": ' . $new_term->get_error_message());
  882. if ($debug) {
  883. error_log('STUDIOU WC IMPORT: Total available categories: ' . count(self::$all_product_cats_cache));
  884. $sample_cats = array_slice(self::$all_product_cats_cache, 0, 20);
  885. foreach ($sample_cats as $cat) {
  886. error_log('STUDIOU WC IMPORT: Available: "' . $cat->name . '" (ID: ' . $cat->term_id . ', slug: ' . $cat->slug . ')');
  887. }
  888. }
  889. return null;
  890. }
  891. $term_id = (int) $new_term['term_id'];
  892. // Append the new term to the cache so subsequent rows see it
  893. // without re-running get_terms().
  894. $fresh = get_term($term_id, 'product_cat');
  895. if ($fresh && !is_wp_error($fresh)) {
  896. self::$all_product_cats_cache[] = $fresh;
  897. }
  898. if ($debug) {
  899. error_log('STUDIOU WC IMPORT: Successfully created category "' . $category_name . '" with ID: ' . $term_id);
  900. }
  901. return $term_id;
  902. }
  903. /**
  904. * Generate CSV with failed items
  905. *
  906. * @param array $failed_items Array of failed product data
  907. * @return string CSV content
  908. */
  909. public function generate_failed_csv($failed_items) {
  910. if (empty($failed_items)) {
  911. return '';
  912. }
  913. // Define CSV header
  914. $header = array(
  915. 'ID', 'Typ', 'Katalogové číslo', 'Jméno', 'Nadřazené', 'Krátký popis', 'Popis',
  916. 'Název 1 vlastnosti', 'Hodnota(y) 1 vlastnosti', 'Kategorie', 'Obrázky', 'Běžná cena',
  917. 'Vlastnost 1 viditelnost', 'Vlastnost 1 globální', 'Vlastnost 1 varianta',
  918. 'Povolit zákaznické recenze?', 'Minimum Quantity', 'Maximum Quantity'
  919. );
  920. // Start CSV output
  921. $csv = '';
  922. $csv .= '"' . implode('","', $header) . '"' . "\n";
  923. // Add failed items
  924. foreach ($failed_items as $item) {
  925. $row = array();
  926. foreach ($header as $column) {
  927. $value = isset($item[$column]) ? $item[$column] : '';
  928. $row[] = '"' . str_replace('"', '""', $value) . '"';
  929. }
  930. $csv .= implode(',', $row) . "\n";
  931. }
  932. return $csv;
  933. }
  934. }