class-db-manager.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  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. * Checks the first non-whitespace character (not just $value[0]) so
  159. * cells like " =CMD" — with leading whitespace some spreadsheet apps
  160. * strip before evaluating — are also defused.
  161. */
  162. private static function csv_escape($value) {
  163. if (!is_string($value)) {
  164. return $value;
  165. }
  166. if ($value === '') {
  167. return $value;
  168. }
  169. $trimmed = ltrim($value);
  170. if ($trimmed === '') {
  171. return $value;
  172. }
  173. $first = $trimmed[0];
  174. if (in_array($first, array('=', '+', '-', '@', "\t", "\r"), true)) {
  175. return "'" . $value;
  176. }
  177. return $value;
  178. }
  179. /**
  180. * Check that a table exists. `$wpdb->esc_like()` escapes the LIKE
  181. * wildcards (`_`, `%`) that show up in conventional `$wpdb->prefix`
  182. * values like `wp_test_` — otherwise the underscores would match any
  183. * single character and could produce false positives.
  184. */
  185. private static function table_exists($table) {
  186. global $wpdb;
  187. $like = $wpdb->esc_like($table);
  188. $found = $wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $like));
  189. return $found === $table;
  190. }
  191. /**
  192. * Bulk-set orders to "to-print", skipping orders in terminal states.
  193. *
  194. * @param int[] $order_ids
  195. * @return int Number of orders actually updated.
  196. */
  197. public static function set_orders_to_prepare_printing($order_ids) {
  198. return self::bulk_set_print_status($order_ids, 'to-print', 'to_print_date');
  199. }
  200. /**
  201. * Bulk-set orders to "in-print", skipping orders in terminal states.
  202. *
  203. * @param int[] $order_ids
  204. * @return int Number of orders actually updated.
  205. */
  206. public static function set_orders_to_in_printing($order_ids) {
  207. return self::bulk_set_print_status($order_ids, 'in-print', 'in_print_date');
  208. }
  209. private static function bulk_set_print_status($order_ids, $status_slug, $meta_key) {
  210. $updated_count = 0;
  211. $skipped = 0;
  212. // Explanatory note for the order activity feed. Mirrors the
  213. // "Marked … by … Protocol import." pattern used in the import
  214. // handlers so the audit trail consistently records *how* a
  215. // transition was triggered.
  216. //
  217. // Explicit map keyed by slug so a future contributor adding a
  218. // third status doesn't accidentally inherit the wrong note via
  219. // an else-implicit ternary.
  220. $notes = array(
  221. 'to-print' => __('Marked Prepare to Printing by bulk action.', 'studiou-wc-ord-print-statuses'),
  222. 'in-print' => __('Marked In Printing by bulk action.', 'studiou-wc-ord-print-statuses'),
  223. );
  224. $note = isset($notes[$status_slug]) ? $notes[$status_slug] : '';
  225. foreach ((array) $order_ids as $order_id) {
  226. $order_id = (int) $order_id;
  227. $order = wc_get_order($order_id);
  228. if (!$order) {
  229. UtilsLog::log('Order #' . $order_id . ' not found');
  230. continue;
  231. }
  232. if ($order->has_status(self::TERMINAL_STATUSES)) {
  233. UtilsLog::log('Order #' . $order_id . ' skipped (terminal status: ' . $order->get_status() . ')');
  234. $skipped++;
  235. continue;
  236. }
  237. $order->update_status($status_slug, $note);
  238. $order->update_meta_data($meta_key, current_time('mysql'));
  239. $order->save();
  240. $updated_count++;
  241. UtilsLog::log('Order #' . $order_id . ' marked as "' . $status_slug . '"');
  242. }
  243. if ($skipped > 0) {
  244. UtilsLog::message(
  245. sprintf(
  246. _n(
  247. '%d order skipped because its status is final (cancelled, refunded, failed, or completed).',
  248. '%d orders skipped because their status is final (cancelled, refunded, failed, or completed).',
  249. $skipped,
  250. 'studiou-wc-ord-print-statuses'
  251. ),
  252. $skipped
  253. ),
  254. 'warning'
  255. );
  256. }
  257. return $updated_count;
  258. }
  259. /**
  260. * Import an InPrint protocol CSV.
  261. *
  262. * @param array $csv_data Rows produced by parse_csv().
  263. * @return array{updated_count:int,errors:string[]}
  264. */
  265. public static function import_inprint_protocol($csv_data) {
  266. $updated_count = 0;
  267. $errors = array();
  268. foreach (self::dedupe_by_order_no($csv_data) as $row) {
  269. if (!isset($row['order_no']) || !isset($row['externalorder']) || !isset($row['externalorderdate'])) {
  270. $errors[] = __('Invalid row format in CSV.', 'studiou-wc-ord-print-statuses');
  271. continue;
  272. }
  273. $order = wc_get_order($row['order_no']);
  274. if (!$order) {
  275. UtilsLog::log('import_inprint_protocol: order ' . $row['order_no'] . ' not found');
  276. $errors[] = sprintf(__('Order %s not found.', 'studiou-wc-ord-print-statuses'), $row['order_no']);
  277. continue;
  278. }
  279. if ($order->has_status(self::TERMINAL_STATUSES)) {
  280. UtilsLog::log('import_inprint_protocol: order ' . $row['order_no'] . ' in terminal status ' . $order->get_status() . ' — skipped');
  281. $errors[] = sprintf(
  282. __('Order %s is in a final state and was not updated.', 'studiou-wc-ord-print-statuses'),
  283. $row['order_no']
  284. );
  285. continue;
  286. }
  287. $order->update_status(
  288. 'in-print',
  289. __('Marked In Printing by InPrint Protocol import.', 'studiou-wc-ord-print-statuses')
  290. );
  291. $order->update_meta_data('in_print_date', current_time('mysql'));
  292. $order->update_meta_data('external_ref_ord_no', sanitize_text_field($row['externalorder']));
  293. $order->update_meta_data('external_ref_ord_date', self::normalise_csv_date($row['externalorderdate']));
  294. $order->save();
  295. $updated_count++;
  296. UtilsLog::log('import_inprint_protocol: order ' . $row['order_no'] . ' marked "in-print"');
  297. }
  298. return array('updated_count' => $updated_count, 'errors' => $errors);
  299. }
  300. /**
  301. * Import a Delivered protocol CSV.
  302. *
  303. * @param array $csv_data Rows produced by parse_csv().
  304. * @return array{updated_count:int,errors:string[]}
  305. */
  306. public static function import_delivered_protocol($csv_data) {
  307. $updated_count = 0;
  308. $errors = array();
  309. // Statuses we should not silently flip to "completed". `completed`
  310. // itself is excluded from this list — re-running the same delivered
  311. // protocol on already-completed orders is a benign no-op transition.
  312. $non_completable = array('cancelled', 'refunded', 'failed');
  313. foreach (self::dedupe_by_order_no($csv_data) as $row) {
  314. if (!isset($row['order_no'])) {
  315. $errors[] = __('Invalid row format in CSV.', 'studiou-wc-ord-print-statuses');
  316. continue;
  317. }
  318. $order = wc_get_order($row['order_no']);
  319. if (!$order) {
  320. UtilsLog::log('import_delivered_protocol: order ' . $row['order_no'] . ' not found');
  321. $errors[] = sprintf(__('Order %s not found.', 'studiou-wc-ord-print-statuses'), $row['order_no']);
  322. continue;
  323. }
  324. if ($order->has_status($non_completable)) {
  325. UtilsLog::log('import_delivered_protocol: order ' . $row['order_no'] . ' in terminal status ' . $order->get_status() . ' — skipped');
  326. $errors[] = sprintf(
  327. __('Order %s is in a final state and was not updated.', 'studiou-wc-ord-print-statuses'),
  328. $row['order_no']
  329. );
  330. continue;
  331. }
  332. $order->update_status(
  333. 'completed',
  334. __('Marked completed by Delivered Protocol import.', 'studiou-wc-ord-print-statuses')
  335. );
  336. $order->update_meta_data('external_ref_ord_delivered', current_time('mysql'));
  337. $order->save();
  338. $updated_count++;
  339. UtilsLog::log('import_delivered_protocol: order ' . $row['order_no'] . ' marked "completed"');
  340. }
  341. return array('updated_count' => $updated_count, 'errors' => $errors);
  342. }
  343. /**
  344. * Parse a CSV file into an array of associative rows.
  345. * Headers are normalised (lowercased, whitespace stripped) so files prepared
  346. * to either the legacy spec casing ("Order No") or the documented lowercase
  347. * form ("order_no") both work. A leading UTF-8 BOM is stripped.
  348. *
  349. * @param string $file_path
  350. * @return array Empty array on failure.
  351. */
  352. public static function parse_csv($file_path) {
  353. $csv_data = array();
  354. $handle = fopen($file_path, 'r');
  355. if ($handle === false) {
  356. UtilsLog::log('parse_csv: failed to open ' . $file_path);
  357. return $csv_data;
  358. }
  359. try {
  360. // Strip a leading UTF-8 BOM if present so the first header parses
  361. // cleanly. The plugin's own exports include a BOM (for Excel),
  362. // and Notepad-saved CSVs frequently include one.
  363. $first_bytes = fread($handle, 3);
  364. if ($first_bytes !== "\xEF\xBB\xBF") {
  365. rewind($handle);
  366. }
  367. // Explicit empty-string escape suppresses the PHP 8.4 deprecation
  368. // notice for the implicit '\\' default.
  369. $headers = fgetcsv($handle, 0, ',', '"', '');
  370. if (!is_array($headers) || empty(array_filter($headers))) {
  371. UtilsLog::log('parse_csv: header row missing or empty');
  372. return $csv_data;
  373. }
  374. $headers = array_map(array(__CLASS__, 'normalise_header'), $headers);
  375. // Reject CSVs whose headers collide after normalisation (e.g.,
  376. // "Order No" and "order_no" both → "order_no"). array_combine
  377. // would silently let the later column's data overwrite the
  378. // earlier — losing one column's values entirely.
  379. if (count($headers) !== count(array_unique($headers))) {
  380. UtilsLog::log('parse_csv: duplicate column headers after normalisation: ' . implode(', ', $headers));
  381. return $csv_data;
  382. }
  383. while (($data = fgetcsv($handle, 0, ',', '"', '')) !== false) {
  384. if (count($data) !== count($headers)) {
  385. continue;
  386. }
  387. $csv_data[] = array_combine($headers, $data);
  388. }
  389. } finally {
  390. fclose($handle);
  391. }
  392. return $csv_data;
  393. }
  394. private static function normalise_header($header) {
  395. $header = strtolower(trim((string) $header));
  396. // Strip any UTF-8 BOM that survived the file-level guard.
  397. $header = preg_replace('/^\xEF\xBB\xBF/', '', $header);
  398. // Map "order no" → "order_no" by collapsing internal whitespace to underscore.
  399. $header = preg_replace('/\s+/', '_', $header);
  400. return $header;
  401. }
  402. private static function dedupe_by_order_no($rows) {
  403. $seen = array();
  404. $unique = array();
  405. foreach ($rows as $row) {
  406. $raw_key = isset($row['order_no']) ? trim((string) $row['order_no']) : '';
  407. if ($raw_key === '') {
  408. continue;
  409. }
  410. // Case-insensitive dedup so alphabetic order numbers
  411. // ("ord-12345" vs "ORD-12345") collapse to a single row.
  412. $key = strtolower($raw_key);
  413. if (isset($seen[$key])) {
  414. continue;
  415. }
  416. $seen[$key] = true;
  417. $unique[] = $row;
  418. }
  419. return $unique;
  420. }
  421. /**
  422. * Normalise a free-form date string into a MySQL datetime in WP local time.
  423. * Returns '' (and logs) on parse failure so the UI does not silently
  424. * carry unparseable raw values through the round-trip.
  425. *
  426. * Avoids strtotime() entirely. WordPress sets the PHP timezone to UTC
  427. * very early in its boot (date_default_timezone_set('UTC')), so
  428. * strtotime() interprets timezone-less inputs as UTC. Combining that
  429. * with wp_date() — which expects a UTC timestamp and formats in WP
  430. * timezone — shifted "2026-05-12 14:30" forward by the WP offset.
  431. *
  432. * Two paths:
  433. * - Fast: ISO-like "YYYY-MM-DD[T ]HH:MM[:SS]" with no explicit timezone
  434. * → pure string reformat, no shift. This is the common shape of
  435. * what the print shop sends.
  436. * - Fallback: DateTimeImmutable($raw, wp_timezone()) — interprets
  437. * timezone-less input as WP local; explicit-timezone input is honoured
  438. * by the constructor (second arg ignored in that case) and then
  439. * converted back to WP timezone via setTimezone() so the output is
  440. * always WP-local.
  441. */
  442. private static function normalise_csv_date($raw) {
  443. $raw = sanitize_text_field((string) $raw);
  444. if ($raw === '') {
  445. return '';
  446. }
  447. // Fast path — common ISO-ish shape with no explicit timezone.
  448. // checkdate() + h/m/s bounds reject structurally-valid but
  449. // semantically-out-of-range inputs (e.g., "2026-13-45T25:99")
  450. // so they fall through to the DateTimeImmutable path, which
  451. // will throw and route us to the catch.
  452. if (preg_match('/^(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2})(?::(\d{2}))?$/', $raw, $m)) {
  453. $year = (int) $m[1];
  454. $month = (int) $m[2];
  455. $day = (int) $m[3];
  456. $hour = (int) $m[4];
  457. $minute = (int) $m[5];
  458. $second = isset($m[6]) ? (int) $m[6] : 0;
  459. if (checkdate($month, $day, $year) && $hour <= 23 && $minute <= 59 && $second <= 59) {
  460. return $m[1] . '-' . $m[2] . '-' . $m[3] . ' ' . $m[4] . ':' . $m[5] . ':' . sprintf('%02d', $second);
  461. }
  462. }
  463. // Fallback — let DateTimeImmutable handle locale dates and explicit
  464. // timezones. Strict: throws ValueError on garbage (e.g. "foo").
  465. try {
  466. $dt = new DateTimeImmutable($raw, wp_timezone());
  467. $dt = $dt->setTimezone(wp_timezone());
  468. return $dt->format('Y-m-d H:i:s');
  469. } catch (Exception $e) {
  470. UtilsLog::log('normalise_csv_date: could not parse "' . $raw . '"');
  471. return '';
  472. }
  473. }
  474. }