class-db-manager.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. <?php
  2. /**
  3. * Database operations and CSV-protocol processing for the
  4. * Studiou WC Order Print Statuses plugin.
  5. */
  6. defined('ABSPATH') || exit;
  7. class Studiou_DB_Manager {
  8. /**
  9. * Order statuses that block automated print-pipeline transitions.
  10. * Cancelled / refunded orders should not be silently reactivated by a bulk
  11. * action; completed orders are already finished.
  12. */
  13. const TERMINAL_STATUSES = array('cancelled', 'refunded', 'failed', 'completed');
  14. /**
  15. * Return one row per (order × line-item) for the print-shop export.
  16. *
  17. * Design notes:
  18. * - Multiple product categories are concatenated into prod_cat instead of
  19. * multiplying the row.
  20. * - Simple (non-variable) products are included via LEFT JOIN; their
  21. * prod_var / prod_var_type fields will be NULL.
  22. * - The image URL is resolved in PHP via wp_get_attachment_url() rather
  23. * than reading wp_posts.guid, which the codex warns is not guaranteed
  24. * to be a URL (breaks under offloaded media / multisite uploads paths).
  25. * - The variation attribute is joined on terms.slug — WC stores the slug
  26. * in `attribute_pa_format` postmeta, not the term name.
  27. * - qty is summed across duplicate line items (a customer adding the
  28. * same variation twice without merging produces two rows in the
  29. * lookup table; MIN() would silently undercount).
  30. *
  31. * @param int[] $order_ids
  32. * @return array Each element is an stdClass with fields:
  33. * order_no, prod_cat, prod_name, prod_var, prod_var_type,
  34. * prod_img_url, qty, email.
  35. */
  36. public static function get_orders_for_printing($order_ids) {
  37. global $wpdb;
  38. // Explicit callback so the filter doesn't accidentally drop legitimate
  39. // zero values if this helper is ever repurposed for non-ID lists.
  40. $order_ids = array_filter(
  41. array_map('intval', (array) $order_ids),
  42. function ($id) { return $id > 0; }
  43. );
  44. if (empty($order_ids)) {
  45. return array();
  46. }
  47. $lookup_table = $wpdb->prefix . 'wc_order_product_lookup';
  48. if (!self::table_exists($lookup_table)) {
  49. UtilsLog::log("get_orders_for_printing: required table {$lookup_table} is missing. Is WC analytics enabled?");
  50. UtilsLog::message(
  51. __('Export requires the WooCommerce analytics lookup table (wc_order_product_lookup). Enable WooCommerce Analytics or contact support.', 'studiou-wc-ord-print-statuses'),
  52. 'error'
  53. );
  54. return array();
  55. }
  56. $placeholders = implode(',', array_fill(0, count($order_ids), '%d'));
  57. // Raise the GROUP_CONCAT byte cap (default 1024) so multi-category
  58. // products with long names are not silently truncated. Use GREATEST
  59. // so we never *lower* a setting another piece of code may rely on.
  60. $wpdb->query("SET SESSION group_concat_max_len = GREATEST(@@SESSION.group_concat_max_len, 65535)");
  61. // Non-aggregated SELECT columns are wrapped in MIN()/SUM() to remain
  62. // compliant with MySQL's ONLY_FULL_GROUP_BY mode (default in 5.7+).
  63. // qty uses SUM() because a single (order, product, variation) group
  64. // may contain multiple lookup rows when a customer added the same
  65. // variation twice without cart-merge.
  66. $sql = "
  67. SELECT
  68. `orders`.`id` AS `order_no`,
  69. GROUP_CONCAT(DISTINCT `t`.`name` ORDER BY `t`.`name` SEPARATOR ', ') AS `prod_cat`,
  70. MIN(`products`.`post_title`) AS `prod_name`,
  71. MIN(`product_variations`.`post_title`) AS `prod_var`,
  72. MIN(`product_variations_name`.`name`) AS `prod_var_type`,
  73. MIN(`product_meta`.`meta_value`) AS `prod_img_id`,
  74. SUM(`order_products`.`product_qty`) AS `qty`,
  75. MIN(`orders`.`billing_email`) AS `email`
  76. FROM `{$wpdb->prefix}wc_orders` `orders`
  77. JOIN `{$wpdb->prefix}wc_order_product_lookup` `order_products`
  78. ON `orders`.`id` = `order_products`.`order_id`
  79. JOIN `{$wpdb->posts}` `products`
  80. ON `products`.`ID` = `order_products`.`product_id`
  81. LEFT JOIN `{$wpdb->posts}` `product_variations`
  82. ON `product_variations`.`ID` = `order_products`.`variation_id`
  83. LEFT JOIN `{$wpdb->postmeta}` `product_variations_attr`
  84. ON `product_variations_attr`.`post_id` = `product_variations`.`ID`
  85. AND `product_variations_attr`.`meta_key` = 'attribute_pa_format'
  86. LEFT JOIN `{$wpdb->terms}` `product_variations_name`
  87. ON `product_variations_name`.`slug` = `product_variations_attr`.`meta_value`
  88. LEFT JOIN `{$wpdb->postmeta}` `product_meta`
  89. ON `product_meta`.`post_id` = `products`.`ID`
  90. AND `product_meta`.`meta_key` = '_thumbnail_id'
  91. LEFT JOIN `{$wpdb->term_relationships}` `tr`
  92. ON `tr`.`object_id` = `products`.`ID`
  93. LEFT JOIN `{$wpdb->term_taxonomy}` `tt`
  94. ON `tt`.`term_taxonomy_id` = `tr`.`term_taxonomy_id`
  95. AND `tt`.`taxonomy` = 'product_cat'
  96. LEFT JOIN `{$wpdb->terms}` `t`
  97. ON `t`.`term_id` = `tt`.`term_id`
  98. WHERE `orders`.`id` IN ($placeholders)
  99. GROUP BY
  100. `orders`.`id`,
  101. `order_products`.`product_id`,
  102. `order_products`.`variation_id`
  103. ORDER BY `orders`.`id`
  104. ";
  105. $prepared = $wpdb->prepare($sql, $order_ids);
  106. $results = $wpdb->get_results($prepared);
  107. if ($results === false) {
  108. UtilsLog::log('SQL error in get_orders_for_printing: ' . $wpdb->last_error);
  109. return array();
  110. }
  111. // Resolve the attachment ID to a URL via WP's API — respects
  112. // offloaded-media plugins, multisite upload paths, and the
  113. // wp_get_attachment_url filter chain. Normalise integer-valued
  114. // qty (SUM returns DECIMAL → "2.0000") and CSV-escape every value
  115. // to neutralise Excel/LibreOffice formula injection.
  116. foreach ($results as $row) {
  117. $attachment_id = isset($row->prod_img_id) ? (int) $row->prod_img_id : 0;
  118. $row->prod_img_url = $attachment_id ? (string) wp_get_attachment_url($attachment_id) : '';
  119. unset($row->prod_img_id);
  120. if (isset($row->qty)) {
  121. $row->qty = self::format_quantity($row->qty);
  122. }
  123. foreach (get_object_vars($row) as $field => $value) {
  124. $row->$field = self::csv_escape($value);
  125. }
  126. }
  127. return $results;
  128. }
  129. /**
  130. * Drop trailing zeros and the decimal point when the quantity is whole,
  131. * keeping a sensible decimal representation when it isn't.
  132. */
  133. private static function format_quantity($value) {
  134. if (!is_numeric($value)) {
  135. return (string) $value;
  136. }
  137. $float = (float) $value;
  138. if ((float) (int) $float === $float) {
  139. return (string) (int) $float;
  140. }
  141. return rtrim(rtrim(sprintf('%.4F', $float), '0'), '.');
  142. }
  143. /**
  144. * Defuse Excel / LibreOffice / Google Sheets formula execution by
  145. * prefixing values that begin with =, +, -, @, tab, or CR with a single
  146. * quote. OWASP-recommended pattern. The leading quote is hidden by
  147. * Excel when displayed but disables formula evaluation.
  148. */
  149. private static function csv_escape($value) {
  150. if (!is_string($value)) {
  151. return $value;
  152. }
  153. if ($value === '') {
  154. return $value;
  155. }
  156. $first = $value[0];
  157. if (in_array($first, array('=', '+', '-', '@', "\t", "\r"), true)) {
  158. return "'" . $value;
  159. }
  160. return $value;
  161. }
  162. /**
  163. * Check that a table exists. `$wpdb->esc_like()` escapes the LIKE
  164. * wildcards (`_`, `%`) that show up in conventional `$wpdb->prefix`
  165. * values like `wp_test_` — otherwise the underscores would match any
  166. * single character and could produce false positives.
  167. */
  168. private static function table_exists($table) {
  169. global $wpdb;
  170. $like = $wpdb->esc_like($table);
  171. $found = $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $like));
  172. return $found === $table;
  173. }
  174. /**
  175. * Bulk-set orders to "to-print", skipping orders in terminal states.
  176. *
  177. * @param int[] $order_ids
  178. * @return int Number of orders actually updated.
  179. */
  180. public static function set_orders_to_prepare_printing($order_ids) {
  181. return self::bulk_set_print_status($order_ids, 'to-print', 'to_print_date');
  182. }
  183. /**
  184. * Bulk-set orders to "in-print", skipping orders in terminal states.
  185. *
  186. * @param int[] $order_ids
  187. * @return int Number of orders actually updated.
  188. */
  189. public static function set_orders_to_in_printing($order_ids) {
  190. return self::bulk_set_print_status($order_ids, 'in-print', 'in_print_date');
  191. }
  192. private static function bulk_set_print_status($order_ids, $status_slug, $meta_key) {
  193. $updated_count = 0;
  194. $skipped = 0;
  195. foreach ((array) $order_ids as $order_id) {
  196. $order_id = (int) $order_id;
  197. $order = wc_get_order($order_id);
  198. if (!$order) {
  199. UtilsLog::log('Order #' . $order_id . ' not found');
  200. continue;
  201. }
  202. if ($order->has_status(self::TERMINAL_STATUSES)) {
  203. UtilsLog::log('Order #' . $order_id . ' skipped (terminal status: ' . $order->get_status() . ')');
  204. $skipped++;
  205. continue;
  206. }
  207. $order->update_status($status_slug);
  208. $order->update_meta_data($meta_key, current_time('mysql'));
  209. $order->save();
  210. $updated_count++;
  211. UtilsLog::log('Order #' . $order_id . ' marked as "' . $status_slug . '"');
  212. }
  213. if ($skipped > 0) {
  214. UtilsLog::message(
  215. sprintf(
  216. _n(
  217. '%d order skipped because its status is final (cancelled, refunded, failed, or completed).',
  218. '%d orders skipped because their status is final (cancelled, refunded, failed, or completed).',
  219. $skipped,
  220. 'studiou-wc-ord-print-statuses'
  221. ),
  222. $skipped
  223. ),
  224. 'warning'
  225. );
  226. }
  227. return $updated_count;
  228. }
  229. /**
  230. * Import an InPrint protocol CSV.
  231. *
  232. * @param array $csv_data Rows produced by parse_csv().
  233. * @return array{updated_count:int,errors:string[]}
  234. */
  235. public static function import_inprint_protocol($csv_data) {
  236. $updated_count = 0;
  237. $errors = array();
  238. foreach (self::dedupe_by_order_no($csv_data) as $row) {
  239. if (!isset($row['order_no']) || !isset($row['externalorder']) || !isset($row['externalorderdate'])) {
  240. $errors[] = __('Invalid row format in CSV.', 'studiou-wc-ord-print-statuses');
  241. continue;
  242. }
  243. $order = wc_get_order($row['order_no']);
  244. if (!$order) {
  245. UtilsLog::log('import_inprint_protocol: order ' . $row['order_no'] . ' not found');
  246. $errors[] = sprintf(__('Order %s not found.', 'studiou-wc-ord-print-statuses'), $row['order_no']);
  247. continue;
  248. }
  249. if ($order->has_status(self::TERMINAL_STATUSES)) {
  250. UtilsLog::log('import_inprint_protocol: order ' . $row['order_no'] . ' in terminal status ' . $order->get_status() . ' — skipped');
  251. $errors[] = sprintf(
  252. __('Order %s is in a final state and was not updated.', 'studiou-wc-ord-print-statuses'),
  253. $row['order_no']
  254. );
  255. continue;
  256. }
  257. $order->update_status(
  258. 'in-print',
  259. __('Marked In Printing by InPrint Protocol import.', 'studiou-wc-ord-print-statuses')
  260. );
  261. $order->update_meta_data('in_print_date', current_time('mysql'));
  262. $order->update_meta_data('external_ref_ord_no', sanitize_text_field($row['externalorder']));
  263. $order->update_meta_data('external_ref_ord_date', self::normalise_csv_date($row['externalorderdate']));
  264. $order->save();
  265. $updated_count++;
  266. UtilsLog::log('import_inprint_protocol: order ' . $row['order_no'] . ' marked "in-print"');
  267. }
  268. return array('updated_count' => $updated_count, 'errors' => $errors);
  269. }
  270. /**
  271. * Import a Delivered protocol CSV.
  272. *
  273. * @param array $csv_data Rows produced by parse_csv().
  274. * @return array{updated_count:int,errors:string[]}
  275. */
  276. public static function import_delivered_protocol($csv_data) {
  277. $updated_count = 0;
  278. $errors = array();
  279. // Statuses we should not silently flip to "completed". `completed`
  280. // itself is excluded from this list — re-running the same delivered
  281. // protocol on already-completed orders is a benign no-op transition.
  282. $non_completable = array('cancelled', 'refunded', 'failed');
  283. foreach (self::dedupe_by_order_no($csv_data) as $row) {
  284. if (!isset($row['order_no'])) {
  285. $errors[] = __('Invalid row format in CSV.', 'studiou-wc-ord-print-statuses');
  286. continue;
  287. }
  288. $order = wc_get_order($row['order_no']);
  289. if (!$order) {
  290. UtilsLog::log('import_delivered_protocol: order ' . $row['order_no'] . ' not found');
  291. $errors[] = sprintf(__('Order %s not found.', 'studiou-wc-ord-print-statuses'), $row['order_no']);
  292. continue;
  293. }
  294. if ($order->has_status($non_completable)) {
  295. UtilsLog::log('import_delivered_protocol: order ' . $row['order_no'] . ' in terminal status ' . $order->get_status() . ' — skipped');
  296. $errors[] = sprintf(
  297. __('Order %s is in a final state and was not updated.', 'studiou-wc-ord-print-statuses'),
  298. $row['order_no']
  299. );
  300. continue;
  301. }
  302. $order->update_status(
  303. 'completed',
  304. __('Marked completed by Delivered Protocol import.', 'studiou-wc-ord-print-statuses')
  305. );
  306. $order->update_meta_data('external_ref_ord_delivered', current_time('mysql'));
  307. $order->save();
  308. $updated_count++;
  309. UtilsLog::log('import_delivered_protocol: order ' . $row['order_no'] . ' marked "completed"');
  310. }
  311. return array('updated_count' => $updated_count, 'errors' => $errors);
  312. }
  313. /**
  314. * Parse a CSV file into an array of associative rows.
  315. * Headers are normalised (lowercased, whitespace stripped) so files prepared
  316. * to either the legacy spec casing ("Order No") or the documented lowercase
  317. * form ("order_no") both work. A leading UTF-8 BOM is stripped.
  318. *
  319. * @param string $file_path
  320. * @return array Empty array on failure.
  321. */
  322. public static function parse_csv($file_path) {
  323. $csv_data = array();
  324. $handle = fopen($file_path, 'r');
  325. if ($handle === false) {
  326. UtilsLog::log('parse_csv: failed to open ' . $file_path);
  327. return $csv_data;
  328. }
  329. try {
  330. // Strip a leading UTF-8 BOM if present so the first header parses
  331. // cleanly. The plugin's own exports include a BOM (for Excel),
  332. // and Notepad-saved CSVs frequently include one.
  333. $first_bytes = fread($handle, 3);
  334. if ($first_bytes !== "\xEF\xBB\xBF") {
  335. rewind($handle);
  336. }
  337. // Explicit empty-string escape suppresses the PHP 8.4 deprecation
  338. // notice for the implicit '\\' default.
  339. $headers = fgetcsv($handle, 0, ',', '"', '');
  340. if (!is_array($headers) || empty(array_filter($headers))) {
  341. UtilsLog::log('parse_csv: header row missing or empty');
  342. return $csv_data;
  343. }
  344. $headers = array_map(array(__CLASS__, 'normalise_header'), $headers);
  345. while (($data = fgetcsv($handle, 0, ',', '"', '')) !== false) {
  346. if (count($data) !== count($headers)) {
  347. continue;
  348. }
  349. $csv_data[] = array_combine($headers, $data);
  350. }
  351. } finally {
  352. fclose($handle);
  353. }
  354. return $csv_data;
  355. }
  356. private static function normalise_header($header) {
  357. $header = strtolower(trim((string) $header));
  358. // Strip any UTF-8 BOM that survived the file-level guard.
  359. $header = preg_replace('/^\xEF\xBB\xBF/', '', $header);
  360. // Map "order no" → "order_no" by collapsing internal whitespace to underscore.
  361. $header = preg_replace('/\s+/', '_', $header);
  362. return $header;
  363. }
  364. private static function dedupe_by_order_no($rows) {
  365. $seen = array();
  366. $unique = array();
  367. foreach ($rows as $row) {
  368. $raw_key = isset($row['order_no']) ? trim((string) $row['order_no']) : '';
  369. if ($raw_key === '') {
  370. continue;
  371. }
  372. // Case-insensitive dedup so alphabetic order numbers
  373. // ("ord-12345" vs "ORD-12345") collapse to a single row.
  374. $key = strtolower($raw_key);
  375. if (isset($seen[$key])) {
  376. continue;
  377. }
  378. $seen[$key] = true;
  379. $unique[] = $row;
  380. }
  381. return $unique;
  382. }
  383. /**
  384. * Normalise a free-form date string into a MySQL datetime in WP local time.
  385. * Returns '' (and logs) on parse failure so the UI does not silently
  386. * carry unparseable raw values through the round-trip.
  387. *
  388. * Uses wp_date() so the resulting string is consistent with
  389. * current_time('mysql') — both reflect WP local time, not server PHP
  390. * timezone. Previously this used date(), which interpreted the timestamp
  391. * in server timezone and produced an asymmetry between import-side
  392. * external_ref_ord_date and every other meta key.
  393. */
  394. private static function normalise_csv_date($raw) {
  395. $raw = sanitize_text_field((string) $raw);
  396. if ($raw === '') {
  397. return '';
  398. }
  399. $timestamp = strtotime($raw);
  400. if (!$timestamp) {
  401. UtilsLog::log('normalise_csv_date: could not parse "' . $raw . '"');
  402. return '';
  403. }
  404. return wp_date('Y-m-d H:i:s', $timestamp);
  405. }
  406. }