class-studiou-wc-product-manage-product-export.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. <?php
  2. /**
  3. * Product export class
  4. *
  5. * Handles product export to 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_Export {
  16. /**
  17. * @var Studiou_WC_Product_Manage_Product_DB
  18. */
  19. private $db;
  20. /**
  21. * Constructor
  22. *
  23. * @param Studiou_WC_Product_Manage_Product_DB $db Database instance
  24. */
  25. public function __construct($db) {
  26. $this->db = $db;
  27. // v1.6.4 — gated download endpoint, mirroring the category export.
  28. add_action('admin_init', array($this, 'handle_export_download'));
  29. }
  30. /**
  31. * Return (and lazily create) the guarded export directory.
  32. *
  33. * @return string Absolute path with trailing slash.
  34. */
  35. private function get_export_dir() {
  36. $upload_dir = wp_upload_dir();
  37. $dir = trailingslashit($upload_dir['basedir']) . 'studiou-wcpcm-product-exports/';
  38. if (!file_exists($dir)) {
  39. wp_mkdir_p($dir);
  40. }
  41. // Guard against direct access. Cheap idempotent writes.
  42. $idx = $dir . 'index.php';
  43. if (!file_exists($idx)) {
  44. @file_put_contents($idx, '<?php // Silence is golden.');
  45. }
  46. $ht = $dir . '.htaccess';
  47. if (!file_exists($ht)) {
  48. @file_put_contents($ht, "Deny from all\n");
  49. }
  50. return $dir;
  51. }
  52. /**
  53. * Delete export files older than 24 hours. Called on every new export.
  54. */
  55. private function prune_old_exports() {
  56. $dir = $this->get_export_dir();
  57. $cutoff = time() - DAY_IN_SECONDS;
  58. $files = glob($dir . 'product-export-*.csv');
  59. if (!is_array($files)) { return; }
  60. foreach ($files as $f) {
  61. $mtime = @filemtime($f);
  62. if ($mtime !== false && $mtime < $cutoff) {
  63. @unlink($f);
  64. }
  65. }
  66. }
  67. /**
  68. * v1.6.4 — gated CSV download.
  69. *
  70. * Hooked on admin_init. Verifies nonce + manage_woocommerce capability +
  71. * that the requested file is a bare basename inside the export dir
  72. * (defends against path traversal), then streams via readfile().
  73. */
  74. public function handle_export_download() {
  75. if (!isset($_GET['page']) || $_GET['page'] !== 'studiou-product-export') {
  76. return;
  77. }
  78. if (!isset($_GET['action']) || $_GET['action'] !== 'studiou_wcpcm_download_product_export') {
  79. return;
  80. }
  81. if (!isset($_GET['_wpnonce']) || !wp_verify_nonce($_GET['_wpnonce'], 'studiou-wcpcm-product-export-download')) {
  82. return;
  83. }
  84. if (!current_user_can('manage_woocommerce')) {
  85. wp_die(__('You do not have sufficient permissions', 'studiou-wc-product-cat-manage'));
  86. }
  87. $requested = isset($_GET['file']) ? (string) $_GET['file'] : '';
  88. // Bare basename only — no slashes, no .., no directory components.
  89. if ($requested === '' || $requested !== basename($requested) || strpos($requested, '..') !== false) {
  90. wp_die(__('Invalid file', 'studiou-wc-product-cat-manage'));
  91. }
  92. // Only our own filename shape: product-export-<32 hex>.csv
  93. if (!preg_match('/^product-export-[a-f0-9]{32}\.csv$/', $requested)) {
  94. wp_die(__('Invalid file', 'studiou-wc-product-cat-manage'));
  95. }
  96. $dir = $this->get_export_dir();
  97. $path = $dir . $requested;
  98. if (!file_exists($path)) {
  99. wp_die(__('Export file not found. Please try exporting again.', 'studiou-wc-product-cat-manage'));
  100. }
  101. // Belt-and-braces realpath check to prevent symlink escape.
  102. $real_dir = realpath($dir);
  103. $real_path = realpath($path);
  104. if ($real_dir === false || $real_path === false || strpos($real_path, $real_dir) !== 0) {
  105. wp_die(__('Invalid file', 'studiou-wc-product-cat-manage'));
  106. }
  107. header('Content-Type: text/csv; charset=utf-8');
  108. header('Content-Disposition: attachment; filename=product-export-' . date('Y-m-d-H-i-s') . '.csv');
  109. header('Content-Length: ' . filesize($real_path));
  110. header('Pragma: no-cache');
  111. header('Expires: 0');
  112. readfile($real_path);
  113. exit;
  114. }
  115. /**
  116. * Export products by category IDs
  117. *
  118. * @param array $category_ids Array of category IDs
  119. * @return string CSV content
  120. */
  121. public function export_products($category_ids, &$row_count = null) {
  122. $product_ids = $this->db->get_products_by_categories($category_ids);
  123. if (empty($product_ids)) {
  124. return '';
  125. }
  126. // Define CSV header
  127. $header = array(
  128. 'ID', 'Typ', 'Katalogové číslo', 'Jméno', 'Nadřazené', 'Krátký popis', 'Popis',
  129. 'Název 1 vlastnosti', 'Hodnota(y) 1 vlastnosti', 'Kategorie', 'Obrázky', 'Běžná cena',
  130. 'Vlastnost 1 viditelnost', 'Vlastnost 1 globální', 'Vlastnost 1 varianta',
  131. 'Povolit zákaznické recenze?', 'Minimum Quantity', 'Maximum Quantity'
  132. );
  133. // Start CSV output
  134. $csv = '';
  135. $csv .= '"' . implode('","', $header) . '"' . "\n";
  136. // v1.7.1 — L2: accumulate the count during generation. The previous
  137. // substr_count("\n") - 1 over-counted whenever any field (typically
  138. // the product description) contained a newline.
  139. $count = 0;
  140. // Process each product
  141. foreach ($product_ids as $product_id) {
  142. $product = wc_get_product($product_id);
  143. if (!$product) {
  144. continue;
  145. }
  146. // Only export variable products and variations
  147. if (!$product->is_type('variable') && !$product->is_type('variation')) {
  148. continue;
  149. }
  150. $csv .= $this->format_product_row($product);
  151. $count++;
  152. }
  153. if (func_num_args() >= 2) {
  154. $row_count = $count;
  155. }
  156. return $csv;
  157. }
  158. /**
  159. * Format product data as CSV row
  160. *
  161. * @param WC_Product $product Product object
  162. * @return string CSV row
  163. */
  164. private function format_product_row($product) {
  165. $row = array();
  166. // ID
  167. $row[] = $product->get_id();
  168. // Typ (Type)
  169. $row[] = $product->is_type('variation') ? 'variation' : 'variable';
  170. // Katalogové číslo (SKU)
  171. $row[] = $product->get_sku();
  172. // Jméno (Name)
  173. $row[] = $product->get_name();
  174. // Nadřazené (Parent) - only for variations
  175. if ($product->is_type('variation')) {
  176. $parent_id = $product->get_parent_id();
  177. if ($parent_id) {
  178. $parent = wc_get_product($parent_id);
  179. $row[] = $parent ? $parent->get_sku() : '';
  180. } else {
  181. $row[] = '';
  182. }
  183. } else {
  184. $row[] = '';
  185. }
  186. // Krátký popis (Short description)
  187. $row[] = $product->get_short_description();
  188. // Popis (Description)
  189. $row[] = $product->get_description();
  190. // Název 1 vlastnosti (Attribute 1 name)
  191. // Hodnota(y) 1 vlastnosti (Attribute 1 value(s))
  192. $attributes = $product->get_attributes();
  193. $attribute_name = '';
  194. $attribute_values = '';
  195. $attribute_visible = '0';
  196. $attribute_global = '0';
  197. $attribute_variation = '0';
  198. if (!empty($attributes)) {
  199. $first_attribute = reset($attributes);
  200. if ($first_attribute instanceof WC_Product_Attribute) {
  201. $attribute_name = $first_attribute->get_name();
  202. // Remove 'pa_' prefix if present
  203. if (strpos($attribute_name, 'pa_') === 0) {
  204. $attribute_name = substr($attribute_name, 3);
  205. }
  206. // Get attribute values
  207. if ($product->is_type('variation')) {
  208. // For variations, get the specific value
  209. $variation_attributes = $product->get_variation_attributes();
  210. if (!empty($variation_attributes)) {
  211. $attribute_values = reset($variation_attributes);
  212. }
  213. } else {
  214. // For variable products, get all options
  215. $options = $first_attribute->get_options();
  216. if (is_array($options)) {
  217. $attribute_values = implode('|', $options);
  218. }
  219. }
  220. $attribute_visible = $first_attribute->get_visible() ? '1' : '0';
  221. $attribute_global = $first_attribute->is_taxonomy() ? '1' : '0';
  222. $attribute_variation = $first_attribute->get_variation() ? '1' : '0';
  223. }
  224. }
  225. $row[] = $attribute_name;
  226. $row[] = $attribute_values;
  227. // Kategorie (Categories) - with full hierarchy for subcategories
  228. $category_ids = $product->get_category_ids();
  229. $category_names = array();
  230. foreach ($category_ids as $cat_id) {
  231. $category_path = $this->get_category_path($cat_id);
  232. if ($category_path) {
  233. $category_names[] = $category_path;
  234. }
  235. }
  236. $row[] = implode('|', $category_names);
  237. // Obrázky (Images)
  238. $image_id = $product->get_image_id();
  239. $row[] = $image_id ? wp_get_attachment_url($image_id) : '';
  240. // Běžná cena (Regular price)
  241. $row[] = $product->get_regular_price();
  242. // Vlastnost 1 viditelnost (Attribute 1 visibility)
  243. $row[] = $attribute_visible;
  244. // Vlastnost 1 globální (Attribute 1 global)
  245. $row[] = $attribute_global;
  246. // Vlastnost 1 varianta (Attribute 1 variation)
  247. $row[] = $attribute_variation;
  248. // Povolit zákaznické recenze? (Enable reviews)
  249. $row[] = $product->get_reviews_allowed() ? '1' : '0';
  250. // Minimum Quantity
  251. $min_qty = $product->get_meta('_minimum_quantity');
  252. $row[] = $min_qty ? $min_qty : '';
  253. // Maximum Quantity
  254. $max_qty = $product->get_meta('_maximum_quantity');
  255. $row[] = $max_qty ? $max_qty : '';
  256. // Format as CSV row
  257. $formatted_row = array();
  258. foreach ($row as $value) {
  259. // Escape double quotes
  260. $value = str_replace('"', '""', $value);
  261. $formatted_row[] = '"' . $value . '"';
  262. }
  263. return implode(',', $formatted_row) . "\n";
  264. }
  265. /**
  266. * Get full category path (Parent > Child format for subcategories)
  267. *
  268. * @param int $category_id Category term ID
  269. * @return string Category path
  270. */
  271. private function get_category_path($category_id) {
  272. $term = get_term($category_id, 'product_cat');
  273. if (!$term || is_wp_error($term)) {
  274. return '';
  275. }
  276. // Build path from child to root
  277. $path = array($term->name);
  278. $current_term = $term;
  279. while ($current_term->parent != 0) {
  280. $parent_term = get_term($current_term->parent, 'product_cat');
  281. if (!$parent_term || is_wp_error($parent_term)) {
  282. break;
  283. }
  284. array_unshift($path, $parent_term->name);
  285. $current_term = $parent_term;
  286. }
  287. // Return full path with ">" separator if subcategory, otherwise just the name
  288. return count($path) > 1 ? implode(' > ', $path) : $path[0];
  289. }
  290. /**
  291. * Generate CSV file and return download URL
  292. *
  293. * @param array $category_ids Array of category IDs
  294. * @return array Result with download URL or error message
  295. */
  296. public function generate_export_file($category_ids) {
  297. // v1.7.1 — L2: ask export_products() to return both the CSV string
  298. // AND the row count it accumulated during generation. substr_count
  299. // on "\n" over-counted whenever any product description contained
  300. // a newline.
  301. $row_count = 0;
  302. $csv_content = $this->export_products($category_ids, $row_count);
  303. if (empty($csv_content)) {
  304. return array(
  305. 'success' => false,
  306. 'message' => __('No products found in selected categories', 'studiou-wc-product-cat-manage')
  307. );
  308. }
  309. // v1.6.4 — write into the guarded export dir and prune anything older
  310. // than 24 hours. Filename gets a 32-char random token so the file is
  311. // unguessable even if directory listing leaks.
  312. $export_dir = $this->get_export_dir();
  313. $this->prune_old_exports();
  314. $token = bin2hex(random_bytes(16)); // 32 hex chars
  315. $filename = 'product-export-' . $token . '.csv';
  316. $file_path = $export_dir . $filename;
  317. // Write CSV content to file with UTF-8 BOM so Excel double-click
  318. // opens it with the correct encoding (Policy A, v1.6.2 — match the
  319. // category exporter, which has always written the BOM).
  320. $result = file_put_contents($file_path, "\xEF\xBB\xBF" . $csv_content);
  321. if ($result === false) {
  322. return array(
  323. 'success' => false,
  324. 'message' => __('Failed to create export file', 'studiou-wc-product-cat-manage')
  325. );
  326. }
  327. // Return an admin URL routed through handle_export_download(),
  328. // which checks the nonce + capability + basename. The raw public
  329. // uploads URL is no longer exposed.
  330. $download_url = add_query_arg(
  331. array(
  332. 'page' => 'studiou-product-export',
  333. 'action' => 'studiou_wcpcm_download_product_export',
  334. 'file' => $filename,
  335. '_wpnonce' => wp_create_nonce('studiou-wcpcm-product-export-download'),
  336. ),
  337. admin_url('edit.php?post_type=product')
  338. );
  339. return array(
  340. 'success' => true,
  341. 'message' => sprintf(
  342. /* translators: %d: number of exported products */
  343. __('Export successful! %d products exported.', 'studiou-wc-product-cat-manage'),
  344. $row_count
  345. ),
  346. 'download_url' => $download_url
  347. );
  348. }
  349. }