class-db-manager.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  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. $orders_table = $wpdb->prefix . 'wc_orders';
  48. if (!self::table_exists($orders_table)) {
  49. UtilsLog::log("get_orders_for_printing: required HPOS table {$orders_table} is missing. Is WooCommerce HPOS enabled?");
  50. UtilsLog::message(
  51. __('Export requires WooCommerce HPOS (custom order tables). Enable High-Performance Order Storage in WooCommerce → Settings → Advanced → Features, or contact support.', 'studiou-wc-ord-print-statuses'),
  52. 'error'
  53. );
  54. return array();
  55. }
  56. $lookup_table = $wpdb->prefix . 'wc_order_product_lookup';
  57. if (!self::table_exists($lookup_table)) {
  58. UtilsLog::log("get_orders_for_printing: required table {$lookup_table} is missing. Is WC analytics enabled?");
  59. UtilsLog::message(
  60. __('Export requires the WooCommerce analytics lookup table (wc_order_product_lookup). Enable WooCommerce Analytics or contact support.', 'studiou-wc-ord-print-statuses'),
  61. 'error'
  62. );
  63. return array();
  64. }
  65. $placeholders = implode(',', array_fill(0, count($order_ids), '%d'));
  66. // Raise the GROUP_CONCAT byte cap (default 1024) so multi-category
  67. // products with long names are not silently truncated. Use GREATEST
  68. // so we never *lower* a setting another piece of code may rely on.
  69. $wpdb->query("SET SESSION group_concat_max_len = GREATEST(@@SESSION.group_concat_max_len, 65535)");
  70. // Non-aggregated SELECT columns are wrapped in MIN()/SUM() to remain
  71. // compliant with MySQL's ONLY_FULL_GROUP_BY mode (default in 5.7+).
  72. // qty uses SUM() because a single (order, product, variation) group
  73. // may contain multiple lookup rows when a customer added the same
  74. // variation twice without cart-merge.
  75. $sql = "
  76. SELECT
  77. `orders`.`id` AS `order_no`,
  78. GROUP_CONCAT(DISTINCT `t`.`name` ORDER BY `t`.`name` SEPARATOR ', ') AS `prod_cat`,
  79. MIN(`products`.`post_title`) AS `prod_name`,
  80. MIN(`product_variations`.`post_title`) AS `prod_var`,
  81. MIN(`product_variations_name`.`name`) AS `prod_var_type`,
  82. MIN(`product_meta`.`meta_value`) AS `prod_img_id`,
  83. SUM(`order_products`.`product_qty`) AS `qty`,
  84. MIN(`orders`.`billing_email`) AS `email`
  85. FROM `{$wpdb->prefix}wc_orders` `orders`
  86. JOIN `{$wpdb->prefix}wc_order_product_lookup` `order_products`
  87. ON `orders`.`id` = `order_products`.`order_id`
  88. JOIN `{$wpdb->posts}` `products`
  89. ON `products`.`ID` = `order_products`.`product_id`
  90. LEFT JOIN `{$wpdb->posts}` `product_variations`
  91. ON `product_variations`.`ID` = `order_products`.`variation_id`
  92. LEFT JOIN `{$wpdb->postmeta}` `product_variations_attr`
  93. ON `product_variations_attr`.`post_id` = `product_variations`.`ID`
  94. AND `product_variations_attr`.`meta_key` = 'attribute_pa_format'
  95. LEFT JOIN `{$wpdb->terms}` `product_variations_name`
  96. ON `product_variations_name`.`slug` = `product_variations_attr`.`meta_value`
  97. LEFT JOIN `{$wpdb->postmeta}` `product_meta`
  98. ON `product_meta`.`post_id` = `products`.`ID`
  99. AND `product_meta`.`meta_key` = '_thumbnail_id'
  100. LEFT JOIN `{$wpdb->term_relationships}` `tr`
  101. ON `tr`.`object_id` = `products`.`ID`
  102. LEFT JOIN `{$wpdb->term_taxonomy}` `tt`
  103. ON `tt`.`term_taxonomy_id` = `tr`.`term_taxonomy_id`
  104. AND `tt`.`taxonomy` = 'product_cat'
  105. LEFT JOIN `{$wpdb->terms}` `t`
  106. ON `t`.`term_id` = `tt`.`term_id`
  107. WHERE `orders`.`id` IN ($placeholders)
  108. GROUP BY
  109. `orders`.`id`,
  110. `order_products`.`product_id`,
  111. `order_products`.`variation_id`
  112. ORDER BY `orders`.`id`
  113. ";
  114. $prepared = $wpdb->prepare($sql, $order_ids);
  115. $results = $wpdb->get_results($prepared);
  116. if ($results === false) {
  117. UtilsLog::log('SQL error in get_orders_for_printing: ' . $wpdb->last_error);
  118. return array();
  119. }
  120. // Resolve the attachment ID to a URL via WP's API — respects
  121. // offloaded-media plugins, multisite upload paths, and the
  122. // wp_get_attachment_url filter chain. Normalise integer-valued
  123. // qty (SUM returns DECIMAL → "2.0000") and CSV-escape every value
  124. // to neutralise Excel/LibreOffice formula injection.
  125. foreach ($results as $row) {
  126. $attachment_id = isset($row->prod_img_id) ? (int) $row->prod_img_id : 0;
  127. $row->prod_img_url = $attachment_id ? (string) wp_get_attachment_url($attachment_id) : '';
  128. unset($row->prod_img_id);
  129. if (isset($row->qty)) {
  130. $row->qty = self::format_quantity($row->qty);
  131. }
  132. foreach (get_object_vars($row) as $field => $value) {
  133. $row->$field = self::csv_escape($value);
  134. }
  135. }
  136. return $results;
  137. }
  138. /**
  139. * Drop trailing zeros and the decimal point when the quantity is whole,
  140. * keeping a sensible decimal representation when it isn't.
  141. */
  142. private static function format_quantity($value) {
  143. if (!is_numeric($value)) {
  144. return (string) $value;
  145. }
  146. $float = (float) $value;
  147. if ((float) (int) $float === $float) {
  148. return (string) (int) $float;
  149. }
  150. return rtrim(rtrim(sprintf('%.4F', $float), '0'), '.');
  151. }
  152. /**
  153. * Defuse Excel / LibreOffice / Google Sheets formula execution by
  154. * prefixing values that begin with =, +, -, @, tab, or CR with a single
  155. * quote. OWASP-recommended pattern. The leading quote is hidden by
  156. * Excel when displayed but disables formula evaluation.
  157. */
  158. private static function csv_escape($value) {
  159. if (!is_string($value)) {
  160. return $value;
  161. }
  162. if ($value === '') {
  163. return $value;
  164. }
  165. $first = $value[0];
  166. if (in_array($first, array('=', '+', '-', '@', "\t", "\r"), true)) {
  167. return "'" . $value;
  168. }
  169. return $value;
  170. }
  171. /**
  172. * Check that a table exists. `$wpdb->esc_like()` escapes the LIKE
  173. * wildcards (`_`, `%`) that show up in conventional `$wpdb->prefix`
  174. * values like `wp_test_` — otherwise the underscores would match any
  175. * single character and could produce false positives.
  176. */
  177. private static function table_exists($table) {
  178. global $wpdb;
  179. $like = $wpdb->esc_like($table);
  180. $found = $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $like));
  181. return $found === $table;
  182. }
  183. /**
  184. * Bulk-set orders to "to-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_prepare_printing($order_ids) {
  190. return self::bulk_set_print_status($order_ids, 'to-print', 'to_print_date');
  191. }
  192. /**
  193. * Bulk-set orders to "in-print", skipping orders in terminal states.
  194. *
  195. * @param int[] $order_ids
  196. * @return int Number of orders actually updated.
  197. */
  198. public static function set_orders_to_in_printing($order_ids) {
  199. return self::bulk_set_print_status($order_ids, 'in-print', 'in_print_date');
  200. }
  201. private static function bulk_set_print_status($order_ids, $status_slug, $meta_key) {
  202. $updated_count = 0;
  203. $skipped = 0;
  204. // Explanatory note for the order activity feed. Mirrors the
  205. // "Marked … by … Protocol import." pattern used in the import
  206. // handlers so the audit trail consistently records *how* a
  207. // transition was triggered.
  208. $note = ($status_slug === 'to-print')
  209. ? __('Marked Prepare to Printing by bulk action.', 'studiou-wc-ord-print-statuses')
  210. : __('Marked In Printing by bulk action.', 'studiou-wc-ord-print-statuses');
  211. foreach ((array) $order_ids as $order_id) {
  212. $order_id = (int) $order_id;
  213. $order = wc_get_order($order_id);
  214. if (!$order) {
  215. UtilsLog::log('Order #' . $order_id . ' not found');
  216. continue;
  217. }
  218. if ($order->has_status(self::TERMINAL_STATUSES)) {
  219. UtilsLog::log('Order #' . $order_id . ' skipped (terminal status: ' . $order->get_status() . ')');
  220. $skipped++;
  221. continue;
  222. }
  223. $order->update_status($status_slug, $note);
  224. $order->update_meta_data($meta_key, current_time('mysql'));
  225. $order->save();
  226. $updated_count++;
  227. UtilsLog::log('Order #' . $order_id . ' marked as "' . $status_slug . '"');
  228. }
  229. if ($skipped > 0) {
  230. UtilsLog::message(
  231. sprintf(
  232. _n(
  233. '%d order skipped because its status is final (cancelled, refunded, failed, or completed).',
  234. '%d orders skipped because their status is final (cancelled, refunded, failed, or completed).',
  235. $skipped,
  236. 'studiou-wc-ord-print-statuses'
  237. ),
  238. $skipped
  239. ),
  240. 'warning'
  241. );
  242. }
  243. return $updated_count;
  244. }
  245. /**
  246. * Import an InPrint protocol CSV.
  247. *
  248. * @param array $csv_data Rows produced by parse_csv().
  249. * @return array{updated_count:int,errors:string[]}
  250. */
  251. public static function import_inprint_protocol($csv_data) {
  252. $updated_count = 0;
  253. $errors = array();
  254. foreach (self::dedupe_by_order_no($csv_data) as $row) {
  255. if (!isset($row['order_no']) || !isset($row['externalorder']) || !isset($row['externalorderdate'])) {
  256. $errors[] = __('Invalid row format in CSV.', 'studiou-wc-ord-print-statuses');
  257. continue;
  258. }
  259. $order = wc_get_order($row['order_no']);
  260. if (!$order) {
  261. UtilsLog::log('import_inprint_protocol: order ' . $row['order_no'] . ' not found');
  262. $errors[] = sprintf(__('Order %s not found.', 'studiou-wc-ord-print-statuses'), $row['order_no']);
  263. continue;
  264. }
  265. if ($order->has_status(self::TERMINAL_STATUSES)) {
  266. UtilsLog::log('import_inprint_protocol: order ' . $row['order_no'] . ' in terminal status ' . $order->get_status() . ' — skipped');
  267. $errors[] = sprintf(
  268. __('Order %s is in a final state and was not updated.', 'studiou-wc-ord-print-statuses'),
  269. $row['order_no']
  270. );
  271. continue;
  272. }
  273. $order->update_status(
  274. 'in-print',
  275. __('Marked In Printing by InPrint Protocol import.', 'studiou-wc-ord-print-statuses')
  276. );
  277. $order->update_meta_data('in_print_date', current_time('mysql'));
  278. $order->update_meta_data('external_ref_ord_no', sanitize_text_field($row['externalorder']));
  279. $order->update_meta_data('external_ref_ord_date', self::normalise_csv_date($row['externalorderdate']));
  280. $order->save();
  281. $updated_count++;
  282. UtilsLog::log('import_inprint_protocol: order ' . $row['order_no'] . ' marked "in-print"');
  283. }
  284. return array('updated_count' => $updated_count, 'errors' => $errors);
  285. }
  286. /**
  287. * Import a Delivered protocol CSV.
  288. *
  289. * @param array $csv_data Rows produced by parse_csv().
  290. * @return array{updated_count:int,errors:string[]}
  291. */
  292. public static function import_delivered_protocol($csv_data) {
  293. $updated_count = 0;
  294. $errors = array();
  295. // Statuses we should not silently flip to "completed". `completed`
  296. // itself is excluded from this list — re-running the same delivered
  297. // protocol on already-completed orders is a benign no-op transition.
  298. $non_completable = array('cancelled', 'refunded', 'failed');
  299. foreach (self::dedupe_by_order_no($csv_data) as $row) {
  300. if (!isset($row['order_no'])) {
  301. $errors[] = __('Invalid row format in CSV.', 'studiou-wc-ord-print-statuses');
  302. continue;
  303. }
  304. $order = wc_get_order($row['order_no']);
  305. if (!$order) {
  306. UtilsLog::log('import_delivered_protocol: order ' . $row['order_no'] . ' not found');
  307. $errors[] = sprintf(__('Order %s not found.', 'studiou-wc-ord-print-statuses'), $row['order_no']);
  308. continue;
  309. }
  310. if ($order->has_status($non_completable)) {
  311. UtilsLog::log('import_delivered_protocol: order ' . $row['order_no'] . ' in terminal status ' . $order->get_status() . ' — skipped');
  312. $errors[] = sprintf(
  313. __('Order %s is in a final state and was not updated.', 'studiou-wc-ord-print-statuses'),
  314. $row['order_no']
  315. );
  316. continue;
  317. }
  318. $order->update_status(
  319. 'completed',
  320. __('Marked completed by Delivered Protocol import.', 'studiou-wc-ord-print-statuses')
  321. );
  322. $order->update_meta_data('external_ref_ord_delivered', current_time('mysql'));
  323. $order->save();
  324. $updated_count++;
  325. UtilsLog::log('import_delivered_protocol: order ' . $row['order_no'] . ' marked "completed"');
  326. }
  327. return array('updated_count' => $updated_count, 'errors' => $errors);
  328. }
  329. /**
  330. * Parse a CSV file into an array of associative rows.
  331. * Headers are normalised (lowercased, whitespace stripped) so files prepared
  332. * to either the legacy spec casing ("Order No") or the documented lowercase
  333. * form ("order_no") both work. A leading UTF-8 BOM is stripped.
  334. *
  335. * @param string $file_path
  336. * @return array Empty array on failure.
  337. */
  338. public static function parse_csv($file_path) {
  339. $csv_data = array();
  340. $handle = fopen($file_path, 'r');
  341. if ($handle === false) {
  342. UtilsLog::log('parse_csv: failed to open ' . $file_path);
  343. return $csv_data;
  344. }
  345. try {
  346. // Strip a leading UTF-8 BOM if present so the first header parses
  347. // cleanly. The plugin's own exports include a BOM (for Excel),
  348. // and Notepad-saved CSVs frequently include one.
  349. $first_bytes = fread($handle, 3);
  350. if ($first_bytes !== "\xEF\xBB\xBF") {
  351. rewind($handle);
  352. }
  353. // Explicit empty-string escape suppresses the PHP 8.4 deprecation
  354. // notice for the implicit '\\' default.
  355. $headers = fgetcsv($handle, 0, ',', '"', '');
  356. if (!is_array($headers) || empty(array_filter($headers))) {
  357. UtilsLog::log('parse_csv: header row missing or empty');
  358. return $csv_data;
  359. }
  360. $headers = array_map(array(__CLASS__, 'normalise_header'), $headers);
  361. while (($data = fgetcsv($handle, 0, ',', '"', '')) !== false) {
  362. if (count($data) !== count($headers)) {
  363. continue;
  364. }
  365. $csv_data[] = array_combine($headers, $data);
  366. }
  367. } finally {
  368. fclose($handle);
  369. }
  370. return $csv_data;
  371. }
  372. private static function normalise_header($header) {
  373. $header = strtolower(trim((string) $header));
  374. // Strip any UTF-8 BOM that survived the file-level guard.
  375. $header = preg_replace('/^\xEF\xBB\xBF/', '', $header);
  376. // Map "order no" → "order_no" by collapsing internal whitespace to underscore.
  377. $header = preg_replace('/\s+/', '_', $header);
  378. return $header;
  379. }
  380. private static function dedupe_by_order_no($rows) {
  381. $seen = array();
  382. $unique = array();
  383. foreach ($rows as $row) {
  384. $raw_key = isset($row['order_no']) ? trim((string) $row['order_no']) : '';
  385. if ($raw_key === '') {
  386. continue;
  387. }
  388. // Case-insensitive dedup so alphabetic order numbers
  389. // ("ord-12345" vs "ORD-12345") collapse to a single row.
  390. $key = strtolower($raw_key);
  391. if (isset($seen[$key])) {
  392. continue;
  393. }
  394. $seen[$key] = true;
  395. $unique[] = $row;
  396. }
  397. return $unique;
  398. }
  399. /**
  400. * Normalise a free-form date string into a MySQL datetime in WP local time.
  401. * Returns '' (and logs) on parse failure so the UI does not silently
  402. * carry unparseable raw values through the round-trip.
  403. *
  404. * Avoids strtotime() entirely. WordPress sets the PHP timezone to UTC
  405. * very early in its boot (date_default_timezone_set('UTC')), so
  406. * strtotime() interprets timezone-less inputs as UTC. Combining that
  407. * with wp_date() — which expects a UTC timestamp and formats in WP
  408. * timezone — shifted "2026-05-12 14:30" forward by the WP offset.
  409. *
  410. * Two paths:
  411. * - Fast: ISO-like "YYYY-MM-DD[T ]HH:MM[:SS]" with no explicit timezone
  412. * → pure string reformat, no shift. This is the common shape of
  413. * what the print shop sends.
  414. * - Fallback: DateTimeImmutable($raw, wp_timezone()) — interprets
  415. * timezone-less input as WP local; explicit-timezone input is honoured
  416. * by the constructor (second arg ignored in that case) and then
  417. * converted back to WP timezone via setTimezone() so the output is
  418. * always WP-local.
  419. */
  420. private static function normalise_csv_date($raw) {
  421. $raw = sanitize_text_field((string) $raw);
  422. if ($raw === '') {
  423. return '';
  424. }
  425. // Fast path — common ISO-ish shape with no explicit timezone.
  426. if (preg_match('/^(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2})(?::(\d{2}))?$/', $raw, $m)) {
  427. $second = isset($m[6]) ? $m[6] : '00';
  428. return $m[1] . '-' . $m[2] . '-' . $m[3] . ' ' . $m[4] . ':' . $m[5] . ':' . $second;
  429. }
  430. // Fallback — let DateTimeImmutable handle locale dates and explicit
  431. // timezones. Strict: throws ValueError on garbage (e.g. "foo").
  432. try {
  433. $dt = new DateTimeImmutable($raw, wp_timezone());
  434. $dt = $dt->setTimezone(wp_timezone());
  435. return $dt->format('Y-m-d H:i:s');
  436. } catch (Exception $e) {
  437. UtilsLog::log('normalise_csv_date: could not parse "' . $raw . '"');
  438. return '';
  439. }
  440. }
  441. }