class-studiou-wc-product-cat-manage-manipulator.php 92 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365
  1. <?php
  2. /**
  3. * Category Manipulator class
  4. *
  5. * Handles manipulation operations for product categories
  6. *
  7. * @since 1.0.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_Cat_Manage_Manipulator {
  16. /**
  17. * Database handler
  18. *
  19. * @var Studiou_WC_Product_Cat_Manage_DB
  20. */
  21. private $db;
  22. /**
  23. * Constructor
  24. *
  25. * @param Studiou_WC_Product_Cat_Manage_DB $db Database handler
  26. */
  27. public function __construct($db) {
  28. $this->db = $db;
  29. // Register AJAX handlers
  30. // Legacy single-shot move (v1.0+). Kept for back-compat; JS now uses
  31. // the batched flow added in v1.7.0.
  32. add_action('wp_ajax_studiou_wcpcm_move_products', array($this, 'handle_move_products_ajax'));
  33. // v1.7.0 — M2: batched product move. Mirrors the delete-products
  34. // pattern: start returns the list of product IDs in the source
  35. // category; chunk processes 25 IDs per AJAX call. Removes the
  36. // single-shot timeout on large source categories.
  37. add_action('wp_ajax_studiou_wcpcm_move_products_start', array($this, 'handle_move_products_start_ajax'));
  38. add_action('wp_ajax_studiou_wcpcm_move_products_chunk', array($this, 'handle_move_products_chunk_ajax'));
  39. add_action('wp_ajax_studiou_wcpcm_batch_description', array($this, 'handle_batch_description_ajax'));
  40. add_action('wp_ajax_studiou_wcpcm_delete_products', array($this, 'handle_delete_products_ajax'));
  41. add_action('wp_ajax_studiou_wcpcm_delete_products_batch', array($this, 'handle_delete_products_batch_ajax'));
  42. add_action('wp_ajax_studiou_wcpcm_clear_media', array($this, 'handle_clear_media_ajax'));
  43. add_action('wp_ajax_studiou_wcpcm_clear_media_batch', array($this, 'handle_clear_media_batch_ajax'));
  44. add_action('wp_ajax_studiou_wcpcm_remove_unassigned_media', array($this, 'handle_remove_unassigned_media_ajax'));
  45. add_action('wp_ajax_studiou_wcpcm_remove_unassigned_media_batch', array($this, 'handle_remove_unassigned_media_batch_ajax'));
  46. add_action('wp_ajax_studiou_wcpcm_upvp_get_attributes', array($this, 'handle_upvp_get_attributes_ajax'));
  47. add_action('wp_ajax_studiou_wcpcm_upvp_get_attribute_values', array($this, 'handle_upvp_get_attribute_values_ajax'));
  48. add_action('wp_ajax_studiou_wcpcm_upvp_count', array($this, 'handle_upvp_count_ajax'));
  49. add_action('wp_ajax_studiou_wcpcm_upvp_apply', array($this, 'handle_upvp_apply_ajax'));
  50. // Tabbed manipulations page - load a tab partial on demand
  51. add_action('wp_ajax_studiou_wcpcm_load_tab', array($this, 'handle_load_tab_ajax'));
  52. // Invalidate the cached category/media counts whenever categories or
  53. // product <-> category relationships change.
  54. add_action('created_term', array($this, 'bust_count_cache'));
  55. add_action('edited_term', array($this, 'bust_count_cache'));
  56. add_action('delete_term', array($this, 'bust_count_cache'));
  57. add_action('set_object_terms', array($this, 'bust_count_cache'));
  58. add_action('deleted_term_relationships', array($this, 'bust_count_cache'));
  59. // Add a test AJAX handler to verify AJAX is working
  60. add_action('wp_ajax_studiou_wcpcm_test', array($this, 'handle_test_ajax'));
  61. // Debug: Log that the handler is being registered
  62. if (defined('WP_DEBUG') && WP_DEBUG) {
  63. error_log('STUDIOU WC: AJAX handlers registered - move_products, batch_description, delete_products, and clear_media');
  64. }
  65. }
  66. /**
  67. * Invalidate the cached category / media-category count data.
  68. *
  69. * Hooked to term and term-relationship changes so the counts shown on the
  70. * manipulations tabs stay accurate.
  71. */
  72. public function bust_count_cache() {
  73. delete_transient('studiou_wcpcm_category_counts');
  74. delete_transient('studiou_wcpcm_media_cat_counts');
  75. }
  76. /**
  77. * Handle AJAX request to render a Category Manipulations tab partial.
  78. *
  79. * Each tab partial fetches only its own data, so the manipulations page
  80. * shell can render instantly and heavy calculations run on demand.
  81. */
  82. public function handle_load_tab_ajax() {
  83. // Clean any output buffers to prevent JSON corruption
  84. while (ob_get_level()) {
  85. ob_end_clean();
  86. }
  87. // Check nonce
  88. if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'studiou-wcpcm-nonce')) {
  89. wp_send_json_error(array(
  90. 'message' => __('Security check failed', 'studiou-wc-product-cat-manage')
  91. ));
  92. return;
  93. }
  94. // Check permissions
  95. if (!current_user_can('manage_woocommerce')) {
  96. wp_send_json_error(array(
  97. 'message' => __('You do not have sufficient permissions', 'studiou-wc-product-cat-manage')
  98. ));
  99. return;
  100. }
  101. $tab = isset($_POST['tab']) ? sanitize_key($_POST['tab']) : '';
  102. $allowed = array('move', 'batch-description', 'delete-products', 'clear-media', 'remove-unassigned', 'upvp', 'notes');
  103. if (!in_array($tab, $allowed, true)) {
  104. wp_send_json_error(array(
  105. 'message' => __('Unknown tab', 'studiou-wc-product-cat-manage')
  106. ));
  107. return;
  108. }
  109. $partial = STUDIOU_WCPCM_PLUGIN_DIR . 'views/manipulations/tab-' . $tab . '.php';
  110. if (!file_exists($partial)) {
  111. wp_send_json_error(array(
  112. 'message' => __('Tab content not found', 'studiou-wc-product-cat-manage')
  113. ));
  114. return;
  115. }
  116. // Made available to the partial; each partial fetches only what it needs.
  117. $manipulator = $this;
  118. try {
  119. ob_start();
  120. include $partial;
  121. $html = ob_get_clean();
  122. wp_send_json_success(array(
  123. 'tab' => $tab,
  124. 'html' => $html
  125. ));
  126. } catch (Exception $e) {
  127. if (ob_get_level()) {
  128. ob_end_clean();
  129. }
  130. error_log('STUDIOU WC TABS: tab "' . $tab . '" render failed: ' . $e->getMessage());
  131. wp_send_json_error(array('message' => $e->getMessage()));
  132. }
  133. }
  134. /**
  135. * Handle AJAX batch description request
  136. */
  137. public function handle_batch_description_ajax() {
  138. // Clean all output buffers and prevent any output
  139. while (ob_get_level()) {
  140. ob_end_clean();
  141. }
  142. // Start a new output buffer to catch any unwanted output
  143. ob_start();
  144. // Suppress PHP errors/notices during AJAX to prevent JSON corruption
  145. $original_error_reporting = error_reporting();
  146. error_reporting(0);
  147. // Enable error logging only
  148. if (defined('WP_DEBUG') && WP_DEBUG) {
  149. error_log('STUDIOU WC: Batch description AJAX handler called');
  150. error_log('STUDIOU WC: POST data: ' . print_r($_POST, true));
  151. }
  152. try {
  153. // Check nonce
  154. if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'studiou-wcpcm-nonce')) {
  155. wp_send_json_error(array(
  156. 'message' => __('Security check failed', 'studiou-wc-product-cat-manage')
  157. ));
  158. }
  159. // Check permissions
  160. if (!current_user_can('manage_woocommerce')) {
  161. wp_send_json_error(array(
  162. 'message' => __('You do not have sufficient permissions', 'studiou-wc-product-cat-manage')
  163. ));
  164. }
  165. // Validate input
  166. if (!isset($_POST['selected_categories']) || !isset($_POST['description'])) {
  167. wp_send_json_error(array(
  168. 'message' => __('Missing required parameters', 'studiou-wc-product-cat-manage')
  169. ));
  170. }
  171. $selected_categories = array_map('intval', $_POST['selected_categories']);
  172. $description = sanitize_textarea_field($_POST['description']);
  173. // Debug logging
  174. if (defined('WP_DEBUG') && WP_DEBUG) {
  175. error_log('STUDIOU WC: Batch description operation started - Categories: ' . implode(', ', $selected_categories));
  176. error_log('STUDIOU WC: Description: ' . $description);
  177. }
  178. // Validate categories
  179. if (empty($selected_categories)) {
  180. wp_send_json_error(array(
  181. 'message' => __('Please select at least one category', 'studiou-wc-product-cat-manage')
  182. ));
  183. }
  184. // Execute batch description operation
  185. $result = $this->update_categories_description($selected_categories, $description);
  186. // Debug logging
  187. if (defined('WP_DEBUG') && WP_DEBUG) {
  188. error_log('STUDIOU WC: Batch description operation completed - Updated: ' . $result['updated_count'] . ' categories');
  189. error_log('STUDIOU WC: Sending success response: ' . print_r($result, true));
  190. }
  191. // Clean any output that might have been generated
  192. ob_clean();
  193. // Return success response
  194. wp_send_json_success(array(
  195. 'message' => $result['message'],
  196. 'updated_count' => $result['updated_count'],
  197. 'failed_count' => isset($result['failed_count']) ? $result['failed_count'] : 0
  198. ));
  199. } catch (Exception $e) {
  200. // Debug logging
  201. if (defined('WP_DEBUG') && WP_DEBUG) {
  202. error_log('STUDIOU WC: Batch description operation failed - ' . $e->getMessage());
  203. error_log('STUDIOU WC: Exception trace: ' . $e->getTraceAsString());
  204. }
  205. // Clean any output that might have been generated
  206. ob_clean();
  207. wp_send_json_error(array(
  208. 'message' => sprintf(
  209. __('Error during batch description operation: %s', 'studiou-wc-product-cat-manage'),
  210. $e->getMessage()
  211. )
  212. ));
  213. } finally {
  214. // Restore original error reporting
  215. error_reporting($original_error_reporting);
  216. // End the output buffer
  217. ob_end_clean();
  218. }
  219. }
  220. /**
  221. * Handle AJAX move products request
  222. */
  223. public function handle_move_products_ajax() {
  224. // Clean all output buffers and prevent any output
  225. while (ob_get_level()) {
  226. ob_end_clean();
  227. }
  228. // Start a new output buffer to catch any unwanted output
  229. ob_start();
  230. // Suppress PHP errors/notices during AJAX to prevent JSON corruption
  231. $original_error_reporting = error_reporting();
  232. error_reporting(0);
  233. // Enable error logging only
  234. if (defined('WP_DEBUG') && WP_DEBUG) {
  235. error_log('STUDIOU WC: AJAX handler called');
  236. error_log('STUDIOU WC: POST data: ' . print_r($_POST, true));
  237. }
  238. try {
  239. // Check nonce
  240. if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'studiou-wcpcm-nonce')) {
  241. wp_send_json_error(array(
  242. 'message' => __('Security check failed', 'studiou-wc-product-cat-manage')
  243. ));
  244. }
  245. // Check permissions
  246. if (!current_user_can('manage_woocommerce')) {
  247. wp_send_json_error(array(
  248. 'message' => __('You do not have sufficient permissions', 'studiou-wc-product-cat-manage')
  249. ));
  250. }
  251. // Validate input
  252. if (!isset($_POST['source_category']) || !isset($_POST['target_category'])) {
  253. wp_send_json_error(array(
  254. 'message' => __('Missing required parameters', 'studiou-wc-product-cat-manage')
  255. ));
  256. }
  257. $source_category_id = intval($_POST['source_category']);
  258. $target_category_id = intval($_POST['target_category']);
  259. // Debug logging
  260. if (defined('WP_DEBUG') && WP_DEBUG) {
  261. error_log('STUDIOU WC: Move operation started - Source: ' . $source_category_id . ', Target: ' . $target_category_id);
  262. }
  263. // Validate categories
  264. if ($source_category_id === $target_category_id) {
  265. wp_send_json_error(array(
  266. 'message' => __('Source and target categories must be different', 'studiou-wc-product-cat-manage')
  267. ));
  268. }
  269. if ($source_category_id <= 0 || $target_category_id <= 0) {
  270. wp_send_json_error(array(
  271. 'message' => __('Invalid category selection', 'studiou-wc-product-cat-manage')
  272. ));
  273. }
  274. // Execute move operation
  275. $result = $this->move_products_between_categories($source_category_id, $target_category_id);
  276. // Debug logging
  277. if (defined('WP_DEBUG') && WP_DEBUG) {
  278. error_log('STUDIOU WC: Move operation completed - Moved: ' . $result['moved_count'] . ' products');
  279. error_log('STUDIOU WC: Sending success response: ' . print_r($result, true));
  280. }
  281. // Clean any output that might have been generated
  282. ob_clean();
  283. // Return success response
  284. wp_send_json_success(array(
  285. 'message' => $result['message'],
  286. 'moved_count' => $result['moved_count'],
  287. 'source_count' => $result['source_count'],
  288. 'target_count' => $result['target_count'],
  289. 'failed_count' => isset($result['failed_count']) ? $result['failed_count'] : 0
  290. ));
  291. } catch (Exception $e) {
  292. // Debug logging
  293. if (defined('WP_DEBUG') && WP_DEBUG) {
  294. error_log('STUDIOU WC: Move operation failed - ' . $e->getMessage());
  295. error_log('STUDIOU WC: Exception trace: ' . $e->getTraceAsString());
  296. }
  297. // Clean any output that might have been generated
  298. ob_clean();
  299. wp_send_json_error(array(
  300. 'message' => sprintf(
  301. __('Error during move operation: %s', 'studiou-wc-product-cat-manage'),
  302. $e->getMessage()
  303. )
  304. ));
  305. } finally {
  306. // Restore original error reporting
  307. error_reporting($original_error_reporting);
  308. // End the output buffer
  309. ob_end_clean();
  310. }
  311. }
  312. /**
  313. * v1.7.0 — M2: batched product move, step 1 (start).
  314. *
  315. * Returns the list of product IDs in the source category. JS chunks
  316. * them and calls handle_move_products_chunk_ajax in batches.
  317. */
  318. public function handle_move_products_start_ajax() {
  319. while (ob_get_level()) { ob_end_clean(); }
  320. if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'studiou-wcpcm-nonce')) {
  321. wp_send_json_error(array('message' => __('Security check failed', 'studiou-wc-product-cat-manage')));
  322. }
  323. if (!current_user_can('manage_woocommerce')) {
  324. wp_send_json_error(array('message' => __('You do not have sufficient permissions', 'studiou-wc-product-cat-manage')));
  325. }
  326. $source = isset($_POST['source_category']) ? intval($_POST['source_category']) : 0;
  327. $target = isset($_POST['target_category']) ? intval($_POST['target_category']) : 0;
  328. if ($source <= 0 || $target <= 0) {
  329. wp_send_json_error(array('message' => __('Invalid category selection', 'studiou-wc-product-cat-manage')));
  330. }
  331. if ($source === $target) {
  332. wp_send_json_error(array('message' => __('Source and target categories must be different', 'studiou-wc-product-cat-manage')));
  333. }
  334. $source_term = get_term($source, 'product_cat');
  335. $target_term = get_term($target, 'product_cat');
  336. if (is_wp_error($source_term) || !$source_term || is_wp_error($target_term) || !$target_term) {
  337. wp_send_json_error(array('message' => __('Invalid category specified', 'studiou-wc-product-cat-manage')));
  338. }
  339. $product_ids = $this->get_products_in_category($source);
  340. wp_send_json_success(array(
  341. 'product_ids' => array_values(array_map('intval', $product_ids)),
  342. 'total' => count($product_ids),
  343. 'source_name' => $source_term->name,
  344. 'target_name' => $target_term->name,
  345. ));
  346. }
  347. /**
  348. * v1.7.0 — M2: batched product move, step 2 (chunk).
  349. *
  350. * Moves the supplied product IDs from source to target category.
  351. * wp_set_post_terms is idempotent, so a re-run of an already-moved
  352. * chunk (e.g. after a network retry) is safe.
  353. */
  354. public function handle_move_products_chunk_ajax() {
  355. while (ob_get_level()) { ob_end_clean(); }
  356. if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'studiou-wcpcm-nonce')) {
  357. wp_send_json_error(array('message' => __('Security check failed', 'studiou-wc-product-cat-manage')));
  358. }
  359. if (!current_user_can('manage_woocommerce')) {
  360. wp_send_json_error(array('message' => __('You do not have sufficient permissions', 'studiou-wc-product-cat-manage')));
  361. }
  362. $source = isset($_POST['source_category']) ? intval($_POST['source_category']) : 0;
  363. $target = isset($_POST['target_category']) ? intval($_POST['target_category']) : 0;
  364. $ids = isset($_POST['product_ids']) && is_array($_POST['product_ids'])
  365. ? array_values(array_map('intval', $_POST['product_ids']))
  366. : array();
  367. if ($source <= 0 || $target <= 0 || $source === $target || empty($ids)) {
  368. wp_send_json_error(array('message' => __('Invalid request', 'studiou-wc-product-cat-manage')));
  369. }
  370. $moved = 0;
  371. $failed = 0;
  372. foreach ($ids as $pid) {
  373. $current = wp_get_post_terms($pid, 'product_cat', array('fields' => 'ids'));
  374. if (is_wp_error($current)) {
  375. $failed++;
  376. continue;
  377. }
  378. $new = array_diff($current, array($source));
  379. $new[] = $target;
  380. $new = array_values(array_unique($new));
  381. $r = wp_set_post_terms($pid, $new, 'product_cat');
  382. if (is_wp_error($r)) {
  383. $failed++;
  384. } else {
  385. $moved++;
  386. }
  387. }
  388. wp_send_json_success(array(
  389. 'moved' => $moved,
  390. 'failed' => $failed,
  391. ));
  392. }
  393. /**
  394. * Move all products from source category to target category
  395. *
  396. * @param int $source_category_id Source category ID
  397. * @param int $target_category_id Target category ID
  398. * @return array Result with counts and message
  399. * @throws Exception On error
  400. */
  401. public function move_products_between_categories($source_category_id, $target_category_id) {
  402. // Get source and target category terms
  403. $source_category = get_term($source_category_id, 'product_cat');
  404. $target_category = get_term($target_category_id, 'product_cat');
  405. if (is_wp_error($source_category) || is_wp_error($target_category)) {
  406. throw new Exception(__('Invalid category specified', 'studiou-wc-product-cat-manage'));
  407. }
  408. // Get initial count of products in source category using direct DB query
  409. $initial_source_count = $this->get_category_product_count($source_category_id);
  410. // Check if source category has any products
  411. if ($initial_source_count === 0) {
  412. $message = sprintf(
  413. __('No products found in source category "%s". Nothing to move.', 'studiou-wc-product-cat-manage'),
  414. $source_category->name
  415. );
  416. return array(
  417. 'moved_count' => 0,
  418. 'source_count' => 0,
  419. 'target_count' => $this->get_category_product_count($target_category_id),
  420. 'message' => $message
  421. );
  422. }
  423. // Get all products in source category using direct DB query
  424. $products = $this->get_products_in_category($source_category_id);
  425. $moved_count = 0;
  426. $failed_count = 0;
  427. if (defined('WP_DEBUG') && WP_DEBUG) {
  428. error_log('STUDIOU WC: Found ' . count($products) . ' products in category ' . $source_category->name . ' for moving');
  429. }
  430. // Move each product
  431. foreach ($products as $product_id) {
  432. // Get current categories for the product
  433. $current_categories = wp_get_post_terms($product_id, 'product_cat', array('fields' => 'ids'));
  434. if (is_wp_error($current_categories)) {
  435. $failed_count++;
  436. if (defined('WP_DEBUG') && WP_DEBUG) {
  437. error_log('STUDIOU WC: Error getting categories for product ' . $product_id . ': ' . $current_categories->get_error_message());
  438. }
  439. continue;
  440. }
  441. // Remove source category and add target category
  442. $new_categories = array_diff($current_categories, array($source_category_id));
  443. $new_categories[] = $target_category_id;
  444. // Update product categories
  445. $result = wp_set_post_terms($product_id, $new_categories, 'product_cat');
  446. if (!is_wp_error($result)) {
  447. $moved_count++;
  448. if (defined('WP_DEBUG') && WP_DEBUG) {
  449. error_log('STUDIOU WC: Successfully moved product ' . $product_id . ' from category ' . $source_category_id . ' to ' . $target_category_id);
  450. }
  451. } else {
  452. $failed_count++;
  453. if (defined('WP_DEBUG') && WP_DEBUG) {
  454. error_log('STUDIOU WC: Error moving product ' . $product_id . ': ' . $result->get_error_message());
  455. }
  456. }
  457. }
  458. // Get updated counts using direct DB query
  459. $source_count = $this->get_category_product_count($source_category_id);
  460. $target_count = $this->get_category_product_count($target_category_id);
  461. // Generate detailed result message
  462. if ($moved_count === 0 && count($products) > 0) {
  463. $message = sprintf(
  464. __('Failed to move any products from "%s" to "%s". All %d products encountered errors during the move operation.', 'studiou-wc-product-cat-manage'),
  465. $source_category->name,
  466. $target_category->name,
  467. count($products)
  468. );
  469. } else {
  470. $message = sprintf(
  471. __('Moved %d products from "%s" to "%s". Source category now has %d products, target category now has %d products.', 'studiou-wc-product-cat-manage'),
  472. $moved_count,
  473. $source_category->name,
  474. $target_category->name,
  475. $source_count,
  476. $target_count
  477. );
  478. if ($failed_count > 0) {
  479. $message .= ' ' . sprintf(
  480. __('Note: %d products failed to move due to errors.', 'studiou-wc-product-cat-manage'),
  481. $failed_count
  482. );
  483. }
  484. }
  485. return array(
  486. 'moved_count' => $moved_count,
  487. 'source_count' => $source_count,
  488. 'target_count' => $target_count,
  489. 'failed_count' => $failed_count,
  490. 'message' => $message
  491. );
  492. }
  493. /**
  494. * Get product count for a category
  495. *
  496. * @param int $category_id Category ID
  497. * @return int Product count
  498. */
  499. private function get_category_product_count($category_id) {
  500. global $wpdb;
  501. // Use direct database query for more accurate counting
  502. $sql = "
  503. SELECT COUNT(DISTINCT p.ID)
  504. FROM {$wpdb->posts} p
  505. INNER JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id
  506. INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
  507. WHERE tt.term_id = %d
  508. AND tt.taxonomy = 'product_cat'
  509. AND p.post_type = 'product'
  510. AND p.post_status IN ('publish', 'private', 'draft')
  511. ";
  512. $count = $wpdb->get_var($wpdb->prepare($sql, $category_id));
  513. if (defined('WP_DEBUG') && WP_DEBUG) {
  514. error_log('STUDIOU WC: Category ' . $category_id . ' product count (direct DB query): ' . intval($count));
  515. }
  516. return intval($count);
  517. }
  518. /**
  519. * Get all products in a category
  520. *
  521. * @param int $category_id Category ID
  522. * @return array Array of product IDs
  523. */
  524. private function get_products_in_category($category_id) {
  525. global $wpdb;
  526. // Use direct database query to get products
  527. $sql = "
  528. SELECT DISTINCT p.ID
  529. FROM {$wpdb->posts} p
  530. INNER JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id
  531. INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
  532. WHERE tt.term_id = %d
  533. AND tt.taxonomy = 'product_cat'
  534. AND p.post_type = 'product'
  535. AND p.post_status IN ('publish', 'private', 'draft')
  536. ";
  537. $products = $wpdb->get_col($wpdb->prepare($sql, $category_id));
  538. if (defined('WP_DEBUG') && WP_DEBUG) {
  539. error_log('STUDIOU WC: Found ' . count($products) . ' products in category ' . $category_id . ' (direct DB query)');
  540. if (!empty($products)) {
  541. error_log('STUDIOU WC: Product IDs: ' . implode(', ', array_slice($products, 0, 10)) . (count($products) > 10 ? ' (showing first 10)' : ''));
  542. }
  543. }
  544. return $products ? array_map('intval', $products) : array();
  545. }
  546. /**
  547. * Update descriptions for multiple categories
  548. *
  549. * @param array $category_ids Array of category IDs
  550. * @param string $description New description for categories
  551. * @return array Result with counts and message
  552. * @throws Exception On error
  553. */
  554. public function update_categories_description($category_ids, $description) {
  555. $updated_count = 0;
  556. $failed_count = 0;
  557. $category_names = array();
  558. // Debug logging
  559. if (defined('WP_DEBUG') && WP_DEBUG) {
  560. error_log('STUDIOU WC: Starting batch description update for ' . count($category_ids) . ' categories');
  561. }
  562. // Update each category
  563. foreach ($category_ids as $category_id) {
  564. // Get category term
  565. $category = get_term($category_id, 'product_cat');
  566. if (is_wp_error($category) || !$category) {
  567. $failed_count++;
  568. if (defined('WP_DEBUG') && WP_DEBUG) {
  569. error_log('STUDIOU WC: Error getting category ' . $category_id . ': ' . ($category ? $category->get_error_message() : 'Category not found'));
  570. }
  571. continue;
  572. }
  573. // Update category description
  574. $result = wp_update_term($category_id, 'product_cat', array(
  575. 'description' => $description
  576. ));
  577. if (!is_wp_error($result)) {
  578. $updated_count++;
  579. $category_names[] = $category->name;
  580. if (defined('WP_DEBUG') && WP_DEBUG) {
  581. error_log('STUDIOU WC: Successfully updated description for category ' . $category_id . ' (' . $category->name . ')');
  582. }
  583. } else {
  584. $failed_count++;
  585. if (defined('WP_DEBUG') && WP_DEBUG) {
  586. error_log('STUDIOU WC: Error updating category ' . $category_id . ': ' . $result->get_error_message());
  587. }
  588. }
  589. }
  590. // Generate result message
  591. if ($updated_count === 0) {
  592. $message = sprintf(
  593. __('Failed to update any category descriptions. %d categories encountered errors.', 'studiou-wc-product-cat-manage'),
  594. $failed_count
  595. );
  596. } else {
  597. $message = sprintf(
  598. __('Successfully updated descriptions for %d categories: %s', 'studiou-wc-product-cat-manage'),
  599. $updated_count,
  600. implode(', ', array_slice($category_names, 0, 5)) . ($updated_count > 5 ? sprintf(__(', and %d more', 'studiou-wc-product-cat-manage'), $updated_count - 5) : '')
  601. );
  602. if ($failed_count > 0) {
  603. $message .= ' ' . sprintf(
  604. __('Note: %d categories failed to update due to errors.', 'studiou-wc-product-cat-manage'),
  605. $failed_count
  606. );
  607. }
  608. }
  609. return array(
  610. 'updated_count' => $updated_count,
  611. 'failed_count' => $failed_count,
  612. 'message' => $message
  613. );
  614. }
  615. /**
  616. * Get all categories with product counts for select lists.
  617. *
  618. * Transient-cached wrapper around get_categories_with_counts_uncached().
  619. * The N+1 per-category count queries are expensive on large stores, so the
  620. * result is cached for 5 minutes and busted on any category change.
  621. *
  622. * @return array Array of categories with ID, name, and product count
  623. */
  624. public function get_categories_with_counts() {
  625. $data = get_transient('studiou_wcpcm_category_counts');
  626. if (false === $data) {
  627. $data = $this->get_categories_with_counts_uncached();
  628. set_transient('studiou_wcpcm_category_counts', $data, 5 * MINUTE_IN_SECONDS);
  629. }
  630. return $data;
  631. }
  632. /**
  633. * Get all categories with product counts for select lists (uncached).
  634. *
  635. * Queries the product_cat terms directly via $wpdb instead of get_terms()
  636. * on purpose: the WooCommerce Protected Categories plugin filters
  637. * get_terms() and hides protected categories in admin-ajax / front-end
  638. * contexts. Since v1.6.0 the manipulations tabs fetch this list inside an
  639. * admin-ajax request, so get_terms() would drop protected categories from
  640. * the dropdowns. Admins must be able to see and operate on every category,
  641. * protected ones included, so we bypass the term-query filters entirely.
  642. *
  643. * @return array Array of categories with ID, name, and product count
  644. */
  645. public function get_categories_with_counts_uncached() {
  646. global $wpdb;
  647. $terms = $wpdb->get_results($wpdb->prepare("
  648. SELECT t.term_id, t.name
  649. FROM {$wpdb->terms} t
  650. INNER JOIN {$wpdb->term_taxonomy} tt ON t.term_id = tt.term_id
  651. WHERE tt.taxonomy = %s
  652. ORDER BY t.name ASC
  653. ", 'product_cat'));
  654. $categories_with_counts = array();
  655. if (!empty($terms)) {
  656. foreach ($terms as $term) {
  657. $product_count = $this->get_category_product_count($term->term_id);
  658. $categories_with_counts[] = array(
  659. 'id' => (int) $term->term_id,
  660. 'name' => $term->name,
  661. 'count' => $product_count,
  662. 'display_name' => sprintf('%s (%d products)', $term->name, $product_count)
  663. );
  664. }
  665. }
  666. return $categories_with_counts;
  667. }
  668. /**
  669. * Handle AJAX delete products request (initial request to get product IDs)
  670. */
  671. public function handle_delete_products_ajax() {
  672. // Clean all output buffers and prevent any output
  673. while (ob_get_level()) {
  674. ob_end_clean();
  675. }
  676. // Start a new output buffer to catch any unwanted output
  677. ob_start();
  678. // Suppress PHP errors/notices during AJAX to prevent JSON corruption
  679. $original_error_reporting = error_reporting();
  680. error_reporting(0);
  681. // Enable error logging only
  682. if (defined('WP_DEBUG') && WP_DEBUG) {
  683. error_log('STUDIOU WC: Delete products AJAX handler called');
  684. error_log('STUDIOU WC: POST data: ' . print_r($_POST, true));
  685. }
  686. try {
  687. // Check nonce
  688. if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'studiou-wcpcm-nonce')) {
  689. wp_send_json_error(array(
  690. 'message' => __('Security check failed', 'studiou-wc-product-cat-manage')
  691. ));
  692. }
  693. // Check permissions
  694. if (!current_user_can('manage_woocommerce')) {
  695. wp_send_json_error(array(
  696. 'message' => __('You do not have sufficient permissions', 'studiou-wc-product-cat-manage')
  697. ));
  698. }
  699. // Validate input
  700. if (!isset($_POST['delete_categories'])) {
  701. wp_send_json_error(array(
  702. 'message' => __('Missing required parameters', 'studiou-wc-product-cat-manage')
  703. ));
  704. }
  705. $category_ids = array_map('intval', $_POST['delete_categories']);
  706. // Debug logging
  707. if (defined('WP_DEBUG') && WP_DEBUG) {
  708. error_log('STUDIOU WC: Delete products operation started - Categories: ' . implode(', ', $category_ids));
  709. }
  710. // Validate categories
  711. if (empty($category_ids)) {
  712. wp_send_json_error(array(
  713. 'message' => __('Please select at least one category', 'studiou-wc-product-cat-manage')
  714. ));
  715. }
  716. // Get all products from selected categories
  717. $product_ids = $this->get_products_from_categories($category_ids);
  718. // Debug logging
  719. if (defined('WP_DEBUG') && WP_DEBUG) {
  720. error_log('STUDIOU WC: Found ' . count($product_ids) . ' products to delete');
  721. }
  722. // Clean any output that might have been generated
  723. ob_clean();
  724. // Return product IDs for batch processing
  725. wp_send_json_success(array(
  726. 'product_ids' => $product_ids,
  727. 'total_count' => count($product_ids),
  728. 'message' => sprintf(
  729. __('Found %d products to delete', 'studiou-wc-product-cat-manage'),
  730. count($product_ids)
  731. )
  732. ));
  733. } catch (Exception $e) {
  734. // Debug logging
  735. if (defined('WP_DEBUG') && WP_DEBUG) {
  736. error_log('STUDIOU WC: Delete products operation failed - ' . $e->getMessage());
  737. error_log('STUDIOU WC: Exception trace: ' . $e->getTraceAsString());
  738. }
  739. // Clean any output that might have been generated
  740. ob_clean();
  741. wp_send_json_error(array(
  742. 'message' => sprintf(
  743. __('Error during delete operation: %s', 'studiou-wc-product-cat-manage'),
  744. $e->getMessage()
  745. )
  746. ));
  747. } finally {
  748. // Restore original error reporting
  749. error_reporting($original_error_reporting);
  750. // End the output buffer
  751. ob_end_clean();
  752. }
  753. }
  754. /**
  755. * Handle AJAX delete products batch request (processes products in batches)
  756. */
  757. public function handle_delete_products_batch_ajax() {
  758. // Clean all output buffers and prevent any output
  759. while (ob_get_level()) {
  760. ob_end_clean();
  761. }
  762. // Start a new output buffer to catch any unwanted output
  763. ob_start();
  764. // Suppress PHP errors/notices during AJAX to prevent JSON corruption
  765. $original_error_reporting = error_reporting();
  766. error_reporting(0);
  767. // Enable error logging only
  768. if (defined('WP_DEBUG') && WP_DEBUG) {
  769. error_log('STUDIOU WC: Delete products batch AJAX handler called');
  770. error_log('STUDIOU WC: POST data: ' . print_r($_POST, true));
  771. }
  772. try {
  773. // Check nonce
  774. if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'studiou-wcpcm-nonce')) {
  775. wp_send_json_error(array(
  776. 'message' => __('Security check failed', 'studiou-wc-product-cat-manage')
  777. ));
  778. }
  779. // Check permissions
  780. if (!current_user_can('manage_woocommerce')) {
  781. wp_send_json_error(array(
  782. 'message' => __('You do not have sufficient permissions', 'studiou-wc-product-cat-manage')
  783. ));
  784. }
  785. // Validate input
  786. if (!isset($_POST['product_ids'])) {
  787. wp_send_json_error(array(
  788. 'message' => __('Missing required parameters', 'studiou-wc-product-cat-manage')
  789. ));
  790. }
  791. $product_ids = array_map('intval', $_POST['product_ids']);
  792. // Debug logging
  793. if (defined('WP_DEBUG') && WP_DEBUG) {
  794. error_log('STUDIOU WC: Processing batch of ' . count($product_ids) . ' products for deletion');
  795. }
  796. // Delete products in this batch
  797. $result = $this->delete_products_batch($product_ids);
  798. // Debug logging
  799. if (defined('WP_DEBUG') && WP_DEBUG) {
  800. error_log('STUDIOU WC: Batch deletion completed - Deleted: ' . $result['deleted_count'] . ', Failed: ' . $result['failed_count']);
  801. }
  802. // Clean any output that might have been generated
  803. ob_clean();
  804. // Return success response
  805. wp_send_json_success(array(
  806. 'deleted_count' => $result['deleted_count'],
  807. 'failed_count' => $result['failed_count'],
  808. 'failed_products' => $result['failed_products']
  809. ));
  810. } catch (Exception $e) {
  811. // Debug logging
  812. if (defined('WP_DEBUG') && WP_DEBUG) {
  813. error_log('STUDIOU WC: Delete products batch operation failed - ' . $e->getMessage());
  814. error_log('STUDIOU WC: Exception trace: ' . $e->getTraceAsString());
  815. }
  816. // Clean any output that might have been generated
  817. ob_clean();
  818. wp_send_json_error(array(
  819. 'message' => sprintf(
  820. __('Error during delete batch operation: %s', 'studiou-wc-product-cat-manage'),
  821. $e->getMessage()
  822. )
  823. ));
  824. } finally {
  825. // Restore original error reporting
  826. error_reporting($original_error_reporting);
  827. // End the output buffer
  828. ob_end_clean();
  829. }
  830. }
  831. /**
  832. * Get all products from multiple categories
  833. *
  834. * @param array $category_ids Array of category IDs
  835. * @return array Array of unique product IDs (including parent products with variants)
  836. */
  837. private function get_products_from_categories($category_ids) {
  838. global $wpdb;
  839. if (empty($category_ids)) {
  840. return array();
  841. }
  842. $placeholders = implode(',', array_fill(0, count($category_ids), '%d'));
  843. // Get all products from selected categories (both simple and parent products)
  844. $sql = "
  845. SELECT DISTINCT p.ID
  846. FROM {$wpdb->posts} p
  847. INNER JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id
  848. INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
  849. WHERE tt.term_id IN ($placeholders)
  850. AND tt.taxonomy = 'product_cat'
  851. AND p.post_type = 'product'
  852. AND p.post_status IN ('publish', 'private', 'draft', 'pending', 'trash')
  853. ";
  854. $products = $wpdb->get_col($wpdb->prepare($sql, $category_ids));
  855. if (defined('WP_DEBUG') && WP_DEBUG) {
  856. error_log('STUDIOU WC: Found ' . count($products) . ' products in categories ' . implode(', ', $category_ids));
  857. }
  858. return $products ? array_map('intval', $products) : array();
  859. }
  860. /**
  861. * Delete a batch of products and their variants
  862. *
  863. * @param array $product_ids Array of product IDs to delete
  864. * @return array Result with counts
  865. */
  866. private function delete_products_batch($product_ids) {
  867. $deleted_count = 0;
  868. $failed_count = 0;
  869. $failed_products = array();
  870. foreach ($product_ids as $product_id) {
  871. try {
  872. // Get the product object
  873. $product = wc_get_product($product_id);
  874. if (!$product) {
  875. $failed_count++;
  876. $failed_products[] = $product_id;
  877. if (defined('WP_DEBUG') && WP_DEBUG) {
  878. error_log('STUDIOU WC: Product ' . $product_id . ' not found');
  879. }
  880. continue;
  881. }
  882. // If it's a variable product, delete all variations first
  883. if ($product->is_type('variable')) {
  884. $variations = $product->get_children();
  885. if (defined('WP_DEBUG') && WP_DEBUG) {
  886. error_log('STUDIOU WC: Deleting ' . count($variations) . ' variations for product ' . $product_id);
  887. }
  888. foreach ($variations as $variation_id) {
  889. $variation = wc_get_product($variation_id);
  890. if ($variation) {
  891. $variation->delete(true); // true = force delete permanently
  892. }
  893. }
  894. }
  895. // Delete the product permanently
  896. $result = $product->delete(true); // true = force delete permanently
  897. if ($result) {
  898. $deleted_count++;
  899. if (defined('WP_DEBUG') && WP_DEBUG) {
  900. error_log('STUDIOU WC: Successfully deleted product ' . $product_id);
  901. }
  902. } else {
  903. $failed_count++;
  904. $failed_products[] = $product_id;
  905. if (defined('WP_DEBUG') && WP_DEBUG) {
  906. error_log('STUDIOU WC: Failed to delete product ' . $product_id);
  907. }
  908. }
  909. } catch (Exception $e) {
  910. $failed_count++;
  911. $failed_products[] = $product_id;
  912. if (defined('WP_DEBUG') && WP_DEBUG) {
  913. error_log('STUDIOU WC: Exception deleting product ' . $product_id . ': ' . $e->getMessage());
  914. }
  915. }
  916. }
  917. return array(
  918. 'deleted_count' => $deleted_count,
  919. 'failed_count' => $failed_count,
  920. 'failed_products' => $failed_products
  921. );
  922. }
  923. /**
  924. * Get all media categories with file counts for select lists.
  925. *
  926. * Transient-cached wrapper around get_media_categories_with_counts_uncached().
  927. *
  928. * @return array Array of media categories with ID, name, and file count
  929. */
  930. public function get_media_categories_with_counts() {
  931. $data = get_transient('studiou_wcpcm_media_cat_counts');
  932. if (false === $data) {
  933. $data = $this->get_media_categories_with_counts_uncached();
  934. set_transient('studiou_wcpcm_media_cat_counts', $data, 5 * MINUTE_IN_SECONDS);
  935. }
  936. return $data;
  937. }
  938. /**
  939. * Get all media categories with file counts for select lists (uncached).
  940. *
  941. * @return array Array of media categories with ID, name, and file count
  942. */
  943. public function get_media_categories_with_counts_uncached() {
  944. $taxonomy = $this->get_media_category_taxonomy();
  945. if (!$taxonomy) {
  946. return array();
  947. }
  948. $args = array(
  949. 'taxonomy' => $taxonomy,
  950. 'orderby' => 'name',
  951. 'hide_empty' => false,
  952. );
  953. $categories = get_terms($args);
  954. $categories_with_counts = array();
  955. if (!is_wp_error($categories)) {
  956. foreach ($categories as $category) {
  957. $file_count = $this->get_media_category_file_count($category->term_id, $taxonomy);
  958. $categories_with_counts[] = array(
  959. 'id' => $category->term_id,
  960. 'name' => $category->name,
  961. 'count' => $file_count,
  962. 'display_name' => sprintf('%s (%d %s)', $category->name, $file_count, __('files', 'studiou-wc-product-cat-manage'))
  963. );
  964. }
  965. }
  966. return $categories_with_counts;
  967. }
  968. /**
  969. * Get the media category taxonomy name
  970. *
  971. * Checks for common media category taxonomies used by popular plugins
  972. *
  973. * @return string|false Taxonomy name or false if none found
  974. */
  975. private function get_media_category_taxonomy() {
  976. $possible_taxonomies = array(
  977. 'media_category',
  978. 'attachment_category',
  979. 'media-category',
  980. );
  981. foreach ($possible_taxonomies as $taxonomy) {
  982. if (taxonomy_exists($taxonomy)) {
  983. error_log('STUDIOU WC MEDIA: Detected media taxonomy: ' . $taxonomy);
  984. return $taxonomy;
  985. }
  986. }
  987. // Try to find any taxonomy registered for attachments
  988. $attachment_taxonomies = get_object_taxonomies('attachment', 'names');
  989. if (!empty($attachment_taxonomies)) {
  990. // Filter out built-in taxonomies
  991. $custom_taxonomies = array_filter($attachment_taxonomies, function($tax) {
  992. return !in_array($tax, array('post_tag', 'category', 'post_format'));
  993. });
  994. if (!empty($custom_taxonomies)) {
  995. $found = reset($custom_taxonomies);
  996. error_log('STUDIOU WC MEDIA: Auto-detected attachment taxonomy: ' . $found);
  997. return $found;
  998. }
  999. }
  1000. error_log('STUDIOU WC MEDIA: No media category taxonomy found. Registered attachment taxonomies: ' . implode(', ', $attachment_taxonomies ?? array()));
  1001. return false;
  1002. }
  1003. /**
  1004. * Get file count for a media category
  1005. *
  1006. * @param int $category_id Category term ID
  1007. * @param string $taxonomy Taxonomy name
  1008. * @return int File count
  1009. */
  1010. private function get_media_category_file_count($category_id, $taxonomy) {
  1011. global $wpdb;
  1012. $sql = "
  1013. SELECT COUNT(DISTINCT p.ID)
  1014. FROM {$wpdb->posts} p
  1015. INNER JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id
  1016. INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
  1017. WHERE tt.term_id = %d
  1018. AND tt.taxonomy = %s
  1019. AND p.post_type = 'attachment'
  1020. ";
  1021. $count = $wpdb->get_var($wpdb->prepare($sql, $category_id, $taxonomy));
  1022. return intval($count);
  1023. }
  1024. /**
  1025. * Get all media IDs from multiple media categories
  1026. *
  1027. * @param array $category_ids Array of category term IDs
  1028. * @return array Array of unique attachment IDs
  1029. */
  1030. private function get_media_from_categories($category_ids) {
  1031. global $wpdb;
  1032. $taxonomy = $this->get_media_category_taxonomy();
  1033. error_log('STUDIOU WC MEDIA: get_media_from_categories called - taxonomy: ' . ($taxonomy ?: 'false') . ', category_ids: ' . implode(', ', $category_ids));
  1034. if (!$taxonomy || empty($category_ids)) {
  1035. error_log('STUDIOU WC MEDIA: No taxonomy or empty category_ids, returning empty');
  1036. return array();
  1037. }
  1038. $placeholders = implode(',', array_fill(0, count($category_ids), '%d'));
  1039. $sql = "
  1040. SELECT DISTINCT p.ID
  1041. FROM {$wpdb->posts} p
  1042. INNER JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id
  1043. INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
  1044. WHERE tt.term_id IN ($placeholders)
  1045. AND tt.taxonomy = %s
  1046. AND p.post_type = 'attachment'
  1047. ";
  1048. $params = array_merge($category_ids, array($taxonomy));
  1049. $media = $wpdb->get_col($wpdb->prepare($sql, ...$params));
  1050. error_log('STUDIOU WC MEDIA: Query found ' . ($media ? count($media) : 0) . ' media files');
  1051. return $media ? array_map('intval', $media) : array();
  1052. }
  1053. /**
  1054. * Delete a batch of media files permanently
  1055. *
  1056. * @param array $media_ids Array of attachment IDs to delete
  1057. * @return array Result with counts
  1058. */
  1059. private function delete_media_batch($media_ids) {
  1060. global $wpdb;
  1061. $deleted_count = 0;
  1062. $failed_count = 0;
  1063. $failed_media = array();
  1064. $affected_term_ids = array();
  1065. $taxonomy = $this->get_media_category_taxonomy();
  1066. // Ensure required file functions are loaded
  1067. if (!function_exists('wp_delete_attachment')) {
  1068. require_once ABSPATH . 'wp-admin/includes/post.php';
  1069. }
  1070. if (!function_exists('wp_delete_file')) {
  1071. require_once ABSPATH . 'wp-includes/functions.php';
  1072. }
  1073. error_log('STUDIOU WC MEDIA: delete_media_batch called with ' . count($media_ids) . ' media IDs');
  1074. foreach ($media_ids as $media_id) {
  1075. try {
  1076. $attachment = get_post($media_id);
  1077. if (!$attachment || $attachment->post_type !== 'attachment') {
  1078. $failed_count++;
  1079. $failed_media[] = $media_id;
  1080. error_log('STUDIOU WC MEDIA: Media file ' . $media_id . ' not found or not an attachment');
  1081. continue;
  1082. }
  1083. // Collect affected term IDs before deletion for count update
  1084. if ($taxonomy) {
  1085. $terms = wp_get_object_terms($media_id, $taxonomy, array('fields' => 'ids'));
  1086. if (!is_wp_error($terms)) {
  1087. $affected_term_ids = array_merge($affected_term_ids, $terms);
  1088. }
  1089. }
  1090. // Get file paths BEFORE deletion
  1091. $file = get_attached_file($media_id);
  1092. $meta = wp_get_attachment_metadata($media_id);
  1093. $upload_dir = wp_get_upload_dir();
  1094. error_log('STUDIOU WC MEDIA: Deleting media ID ' . $media_id . ', file: ' . ($file ?: 'none'));
  1095. // Attempt standard WordPress deletion
  1096. wp_delete_attachment($media_id, true);
  1097. // Verify the post was actually deleted
  1098. $still_exists = $wpdb->get_var($wpdb->prepare(
  1099. "SELECT ID FROM {$wpdb->posts} WHERE ID = %d",
  1100. $media_id
  1101. ));
  1102. if ($still_exists) {
  1103. error_log('STUDIOU WC MEDIA: wp_delete_attachment did not delete post ' . $media_id . ', forcing manual deletion');
  1104. // Force manual deletion: remove term relationships
  1105. $all_taxonomies = get_object_taxonomies('attachment');
  1106. if (!empty($all_taxonomies)) {
  1107. wp_delete_object_term_relationships($media_id, $all_taxonomies);
  1108. }
  1109. // Remove all post meta
  1110. $wpdb->delete($wpdb->postmeta, array('post_id' => $media_id));
  1111. // Remove the post itself
  1112. $wpdb->delete($wpdb->posts, array('ID' => $media_id));
  1113. // Clean cache
  1114. clean_post_cache($media_id);
  1115. }
  1116. // Delete physical files from disk
  1117. if ($file && file_exists($file)) {
  1118. @unlink($file);
  1119. error_log('STUDIOU WC MEDIA: Deleted main file: ' . $file);
  1120. }
  1121. // Delete thumbnail/intermediate sizes
  1122. if (!empty($meta['sizes']) && !empty($upload_dir['basedir'])) {
  1123. $file_dir = !empty($file) ? trailingslashit(dirname($file)) : '';
  1124. foreach ($meta['sizes'] as $size => $sizeinfo) {
  1125. if (!empty($sizeinfo['file'])) {
  1126. $intermediate_file = $file_dir . $sizeinfo['file'];
  1127. if (file_exists($intermediate_file)) {
  1128. @unlink($intermediate_file);
  1129. }
  1130. }
  1131. }
  1132. }
  1133. // Final verification
  1134. $final_check = $wpdb->get_var($wpdb->prepare(
  1135. "SELECT ID FROM {$wpdb->posts} WHERE ID = %d",
  1136. $media_id
  1137. ));
  1138. if (!$final_check) {
  1139. $deleted_count++;
  1140. error_log('STUDIOU WC MEDIA: Successfully deleted media file ' . $media_id);
  1141. } else {
  1142. $failed_count++;
  1143. $failed_media[] = $media_id;
  1144. error_log('STUDIOU WC MEDIA: FAILED to delete media file ' . $media_id . ' even after manual cleanup');
  1145. }
  1146. } catch (Exception $e) {
  1147. $failed_count++;
  1148. $failed_media[] = $media_id;
  1149. error_log('STUDIOU WC MEDIA: Exception deleting media file ' . $media_id . ': ' . $e->getMessage());
  1150. }
  1151. }
  1152. // Force update term counts for affected categories
  1153. if ($taxonomy && !empty($affected_term_ids)) {
  1154. $affected_term_ids = array_unique($affected_term_ids);
  1155. wp_update_term_count_now($affected_term_ids, $taxonomy);
  1156. error_log('STUDIOU WC MEDIA: Updated term counts for term IDs: ' . implode(', ', $affected_term_ids));
  1157. }
  1158. error_log('STUDIOU WC MEDIA: Batch result - deleted: ' . $deleted_count . ', failed: ' . $failed_count);
  1159. return array(
  1160. 'deleted_count' => $deleted_count,
  1161. 'failed_count' => $failed_count,
  1162. 'failed_media' => $failed_media
  1163. );
  1164. }
  1165. /**
  1166. * Handle AJAX clear media request (initial request to get media IDs)
  1167. */
  1168. public function handle_clear_media_ajax() {
  1169. while (ob_get_level()) {
  1170. ob_end_clean();
  1171. }
  1172. ob_start();
  1173. $original_error_reporting = error_reporting();
  1174. error_reporting(0);
  1175. error_log('STUDIOU WC MEDIA: Clear media AJAX handler called');
  1176. error_log('STUDIOU WC MEDIA: POST data: ' . print_r($_POST, true));
  1177. try {
  1178. if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'studiou-wcpcm-nonce')) {
  1179. error_log('STUDIOU WC MEDIA: Nonce verification failed');
  1180. wp_send_json_error(array(
  1181. 'message' => __('Security check failed', 'studiou-wc-product-cat-manage')
  1182. ));
  1183. return;
  1184. }
  1185. if (!current_user_can('manage_woocommerce')) {
  1186. error_log('STUDIOU WC MEDIA: Permission check failed');
  1187. wp_send_json_error(array(
  1188. 'message' => __('You do not have sufficient permissions', 'studiou-wc-product-cat-manage')
  1189. ));
  1190. return;
  1191. }
  1192. if (!isset($_POST['media_categories'])) {
  1193. error_log('STUDIOU WC MEDIA: media_categories not in POST data');
  1194. wp_send_json_error(array(
  1195. 'message' => __('Missing required parameters', 'studiou-wc-product-cat-manage')
  1196. ));
  1197. return;
  1198. }
  1199. $category_ids = array_map('intval', $_POST['media_categories']);
  1200. if (empty($category_ids)) {
  1201. error_log('STUDIOU WC MEDIA: Empty category_ids after intval mapping');
  1202. wp_send_json_error(array(
  1203. 'message' => __('Please select at least one category', 'studiou-wc-product-cat-manage')
  1204. ));
  1205. return;
  1206. }
  1207. $media_ids = $this->get_media_from_categories($category_ids);
  1208. error_log('STUDIOU WC MEDIA: Found ' . count($media_ids) . ' media files to delete from categories: ' . implode(', ', $category_ids));
  1209. ob_clean();
  1210. wp_send_json_success(array(
  1211. 'media_ids' => $media_ids,
  1212. 'total_count' => count($media_ids),
  1213. 'message' => sprintf(
  1214. __('Found %d media files to delete', 'studiou-wc-product-cat-manage'),
  1215. count($media_ids)
  1216. )
  1217. ));
  1218. } catch (Exception $e) {
  1219. error_log('STUDIOU WC MEDIA: Clear media operation failed - ' . $e->getMessage());
  1220. error_log('STUDIOU WC MEDIA: Exception trace: ' . $e->getTraceAsString());
  1221. ob_clean();
  1222. wp_send_json_error(array(
  1223. 'message' => sprintf(
  1224. __('Error during clear media operation: %s', 'studiou-wc-product-cat-manage'),
  1225. $e->getMessage()
  1226. )
  1227. ));
  1228. } finally {
  1229. error_reporting($original_error_reporting);
  1230. ob_end_clean();
  1231. }
  1232. }
  1233. /**
  1234. * Handle AJAX clear media batch request (processes media in batches)
  1235. */
  1236. public function handle_clear_media_batch_ajax() {
  1237. while (ob_get_level()) {
  1238. ob_end_clean();
  1239. }
  1240. ob_start();
  1241. $original_error_reporting = error_reporting();
  1242. error_reporting(0);
  1243. error_log('STUDIOU WC MEDIA: Clear media batch AJAX handler called');
  1244. try {
  1245. if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'studiou-wcpcm-nonce')) {
  1246. error_log('STUDIOU WC MEDIA: Batch nonce verification failed');
  1247. wp_send_json_error(array(
  1248. 'message' => __('Security check failed', 'studiou-wc-product-cat-manage')
  1249. ));
  1250. return;
  1251. }
  1252. if (!current_user_can('manage_woocommerce')) {
  1253. error_log('STUDIOU WC MEDIA: Batch permission check failed');
  1254. wp_send_json_error(array(
  1255. 'message' => __('You do not have sufficient permissions', 'studiou-wc-product-cat-manage')
  1256. ));
  1257. return;
  1258. }
  1259. if (!isset($_POST['media_ids'])) {
  1260. error_log('STUDIOU WC MEDIA: media_ids not in POST data');
  1261. wp_send_json_error(array(
  1262. 'message' => __('Missing required parameters', 'studiou-wc-product-cat-manage')
  1263. ));
  1264. return;
  1265. }
  1266. $media_ids = array_map('intval', $_POST['media_ids']);
  1267. error_log('STUDIOU WC MEDIA: Processing batch of ' . count($media_ids) . ' media files for deletion');
  1268. $result = $this->delete_media_batch($media_ids);
  1269. error_log('STUDIOU WC MEDIA: Batch completed - Deleted: ' . $result['deleted_count'] . ', Failed: ' . $result['failed_count']);
  1270. ob_clean();
  1271. wp_send_json_success(array(
  1272. 'deleted_count' => $result['deleted_count'],
  1273. 'failed_count' => $result['failed_count'],
  1274. 'failed_media' => $result['failed_media']
  1275. ));
  1276. } catch (Exception $e) {
  1277. error_log('STUDIOU WC MEDIA: Clear media batch operation failed - ' . $e->getMessage());
  1278. error_log('STUDIOU WC MEDIA: Exception trace: ' . $e->getTraceAsString());
  1279. ob_clean();
  1280. wp_send_json_error(array(
  1281. 'message' => sprintf(
  1282. __('Error during clear media batch operation: %s', 'studiou-wc-product-cat-manage'),
  1283. $e->getMessage()
  1284. )
  1285. ));
  1286. } finally {
  1287. error_reporting($original_error_reporting);
  1288. ob_end_clean();
  1289. }
  1290. }
  1291. /**
  1292. * Get count of unassigned unused media files
  1293. *
  1294. * @return int Count of media files not in any category and not referenced
  1295. */
  1296. public function get_unassigned_unused_media_count() {
  1297. $ids = $this->get_unassigned_unused_media_ids();
  1298. return count($ids);
  1299. }
  1300. /**
  1301. * Get IDs of media files that are not assigned to any media category
  1302. * and not used as featured image, product gallery image, or attached to any post.
  1303. *
  1304. * @return array Array of attachment IDs
  1305. */
  1306. public function get_unassigned_unused_media_ids() {
  1307. global $wpdb;
  1308. $taxonomy = $this->get_media_category_taxonomy();
  1309. // Base query: all attachments not used as featured image and not attached to a post
  1310. $sql = "
  1311. SELECT a.ID
  1312. FROM {$wpdb->posts} a
  1313. LEFT JOIN {$wpdb->postmeta} pm_thumb
  1314. ON a.ID = CAST(pm_thumb.meta_value AS UNSIGNED)
  1315. AND pm_thumb.meta_key = '_thumbnail_id'
  1316. WHERE a.post_type = 'attachment'
  1317. AND a.post_parent = 0
  1318. AND pm_thumb.meta_id IS NULL
  1319. ";
  1320. // If media category taxonomy exists, also exclude categorized media
  1321. if ($taxonomy) {
  1322. $sql .= $wpdb->prepare("
  1323. AND a.ID NOT IN (
  1324. SELECT tr.object_id
  1325. FROM {$wpdb->term_relationships} tr
  1326. INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
  1327. WHERE tt.taxonomy = %s
  1328. )
  1329. ", $taxonomy);
  1330. }
  1331. $media_ids = $wpdb->get_col($sql);
  1332. if (empty($media_ids)) {
  1333. return array();
  1334. }
  1335. $media_ids = array_map('intval', $media_ids);
  1336. // Filter out media used in WooCommerce product galleries (_product_image_gallery)
  1337. $gallery_meta = $wpdb->get_col(
  1338. "SELECT meta_value FROM {$wpdb->postmeta} WHERE meta_key = '_product_image_gallery' AND meta_value != ''"
  1339. );
  1340. if (!empty($gallery_meta)) {
  1341. $gallery_ids = array();
  1342. foreach ($gallery_meta as $gallery_value) {
  1343. $ids = array_map('intval', array_filter(explode(',', $gallery_value)));
  1344. $gallery_ids = array_merge($gallery_ids, $ids);
  1345. }
  1346. $gallery_ids = array_unique($gallery_ids);
  1347. if (!empty($gallery_ids)) {
  1348. $media_ids = array_diff($media_ids, $gallery_ids);
  1349. }
  1350. }
  1351. // v1.6.2 — narrow blast radius. The base query above does not see
  1352. // attachments referenced from term meta (WooCommerce product-category
  1353. // images are stored as termmeta 'thumbnail_id'), nor customizer images
  1354. // (custom logo, site icon, header image). Without these exclusions,
  1355. // running "Remove Not Assigned Media" silently destroys category
  1356. // artwork. NOTE: content-embedded, ACF/meta-field, and downloadable-
  1357. // product images are still NOT detected — see the warning in
  1358. // tab-remove-unassigned.php. The preview-list inversion (plan-02) is
  1359. // what makes the operation actually safe.
  1360. $extra_excluded = array();
  1361. $termmeta_ids = $wpdb->get_col(
  1362. "SELECT DISTINCT meta_value FROM {$wpdb->termmeta}
  1363. WHERE meta_key = 'thumbnail_id'
  1364. AND meta_value > 0"
  1365. );
  1366. foreach ($termmeta_ids as $tm_id) {
  1367. $tm_id = (int) $tm_id;
  1368. if ($tm_id) { $extra_excluded[$tm_id] = true; }
  1369. }
  1370. foreach (array(
  1371. (int) get_theme_mod('custom_logo'),
  1372. (int) get_option('site_icon'),
  1373. ) as $cust_id) {
  1374. if ($cust_id) { $extra_excluded[$cust_id] = true; }
  1375. }
  1376. $hdr = get_theme_mod('header_image_data');
  1377. if (is_object($hdr) && !empty($hdr->attachment_id)) {
  1378. $extra_excluded[(int) $hdr->attachment_id] = true;
  1379. }
  1380. if (!empty($extra_excluded)) {
  1381. $media_ids = array_diff($media_ids, array_keys($extra_excluded));
  1382. }
  1383. error_log('STUDIOU WC MEDIA: Found ' . count($media_ids) . ' unassigned unused media files');
  1384. return array_values($media_ids);
  1385. }
  1386. /**
  1387. * Handle AJAX remove unassigned media request (get IDs)
  1388. */
  1389. public function handle_remove_unassigned_media_ajax() {
  1390. while (ob_get_level()) {
  1391. ob_end_clean();
  1392. }
  1393. ob_start();
  1394. $original_error_reporting = error_reporting();
  1395. error_reporting(0);
  1396. error_log('STUDIOU WC MEDIA: Remove unassigned media AJAX handler called');
  1397. try {
  1398. if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'studiou-wcpcm-nonce')) {
  1399. wp_send_json_error(array('message' => __('Security check failed', 'studiou-wc-product-cat-manage')));
  1400. return;
  1401. }
  1402. if (!current_user_can('manage_woocommerce')) {
  1403. wp_send_json_error(array('message' => __('You do not have sufficient permissions', 'studiou-wc-product-cat-manage')));
  1404. return;
  1405. }
  1406. $media_ids = $this->get_unassigned_unused_media_ids();
  1407. error_log('STUDIOU WC MEDIA: Found ' . count($media_ids) . ' unassigned unused media files to delete');
  1408. ob_clean();
  1409. wp_send_json_success(array(
  1410. 'media_ids' => $media_ids,
  1411. 'total_count' => count($media_ids),
  1412. 'message' => sprintf(
  1413. __('Found %d unused uncategorized media files to delete', 'studiou-wc-product-cat-manage'),
  1414. count($media_ids)
  1415. )
  1416. ));
  1417. } catch (Exception $e) {
  1418. error_log('STUDIOU WC MEDIA: Remove unassigned media failed - ' . $e->getMessage());
  1419. ob_clean();
  1420. wp_send_json_error(array(
  1421. 'message' => sprintf(__('Error: %s', 'studiou-wc-product-cat-manage'), $e->getMessage())
  1422. ));
  1423. } finally {
  1424. error_reporting($original_error_reporting);
  1425. ob_end_clean();
  1426. }
  1427. }
  1428. /**
  1429. * Handle AJAX remove unassigned media batch request
  1430. */
  1431. public function handle_remove_unassigned_media_batch_ajax() {
  1432. while (ob_get_level()) {
  1433. ob_end_clean();
  1434. }
  1435. ob_start();
  1436. $original_error_reporting = error_reporting();
  1437. error_reporting(0);
  1438. error_log('STUDIOU WC MEDIA: Remove unassigned media batch AJAX handler called');
  1439. try {
  1440. if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'studiou-wcpcm-nonce')) {
  1441. wp_send_json_error(array('message' => __('Security check failed', 'studiou-wc-product-cat-manage')));
  1442. return;
  1443. }
  1444. if (!current_user_can('manage_woocommerce')) {
  1445. wp_send_json_error(array('message' => __('You do not have sufficient permissions', 'studiou-wc-product-cat-manage')));
  1446. return;
  1447. }
  1448. if (!isset($_POST['media_ids'])) {
  1449. wp_send_json_error(array('message' => __('Missing required parameters', 'studiou-wc-product-cat-manage')));
  1450. return;
  1451. }
  1452. $media_ids = array_map('intval', $_POST['media_ids']);
  1453. error_log('STUDIOU WC MEDIA: Processing batch of ' . count($media_ids) . ' unassigned media for deletion');
  1454. $result = $this->delete_media_batch($media_ids);
  1455. error_log('STUDIOU WC MEDIA: Unassigned batch completed - Deleted: ' . $result['deleted_count'] . ', Failed: ' . $result['failed_count']);
  1456. ob_clean();
  1457. wp_send_json_success(array(
  1458. 'deleted_count' => $result['deleted_count'],
  1459. 'failed_count' => $result['failed_count'],
  1460. 'failed_media' => $result['failed_media']
  1461. ));
  1462. } catch (Exception $e) {
  1463. error_log('STUDIOU WC MEDIA: Unassigned media batch failed - ' . $e->getMessage());
  1464. ob_clean();
  1465. wp_send_json_error(array(
  1466. 'message' => sprintf(__('Error: %s', 'studiou-wc-product-cat-manage'), $e->getMessage())
  1467. ));
  1468. } finally {
  1469. error_reporting($original_error_reporting);
  1470. ob_end_clean();
  1471. }
  1472. }
  1473. // ========================================================================
  1474. // Update Product Variant Prices (UPVP) — v1.5.3
  1475. // Bulk-update regular_price on product_variation records by category +
  1476. // attribute filter. Touches only product records; never order items, carts,
  1477. // or historical order data.
  1478. // ========================================================================
  1479. /**
  1480. * Get list of attribute "heads" usable for variations.
  1481. *
  1482. * Source 1: every wc_get_attribute_taxonomies() entry (global attributes)
  1483. * — key = 'pa_<slug>', is_taxonomy = true.
  1484. * Source 2: distinct meta_key starting with 'attribute_' on product_variation
  1485. * rows that are NOT global taxonomies (custom product-level
  1486. * attributes flagged for variations) — key = '<slug>',
  1487. * is_taxonomy = false.
  1488. *
  1489. * @return array [ ['key' => string, 'label' => string, 'is_taxonomy' => bool], ... ]
  1490. */
  1491. public function get_variation_attribute_heads() {
  1492. global $wpdb;
  1493. $heads = array();
  1494. $seen = array();
  1495. // Source 1: global taxonomies.
  1496. $taxonomies = function_exists('wc_get_attribute_taxonomies') ? wc_get_attribute_taxonomies() : array();
  1497. if (!empty($taxonomies)) {
  1498. foreach ($taxonomies as $tax) {
  1499. $key = 'pa_' . $tax->attribute_name;
  1500. if (isset($seen[$key])) {
  1501. continue;
  1502. }
  1503. $seen[$key] = true;
  1504. $heads[] = array(
  1505. 'key' => $key,
  1506. 'label' => !empty($tax->attribute_label) ? $tax->attribute_label : $tax->attribute_name,
  1507. 'is_taxonomy' => true,
  1508. );
  1509. }
  1510. }
  1511. // Source 2: existing variation postmeta (attribute_*).
  1512. $sql = "
  1513. SELECT DISTINCT pm.meta_key
  1514. FROM {$wpdb->postmeta} pm
  1515. INNER JOIN {$wpdb->posts} v ON v.ID = pm.post_id
  1516. WHERE v.post_type = 'product_variation'
  1517. AND v.post_status IN ('publish','private')
  1518. AND pm.meta_key LIKE %s
  1519. ";
  1520. $rows = $wpdb->get_col($wpdb->prepare($sql, $wpdb->esc_like('attribute_') . '%'));
  1521. if (!empty($rows)) {
  1522. foreach ($rows as $meta_key) {
  1523. $slug = substr($meta_key, strlen('attribute_'));
  1524. if ($slug === '' || isset($seen[$slug])) {
  1525. continue;
  1526. }
  1527. $seen[$slug] = true;
  1528. $heads[] = array(
  1529. 'key' => $slug,
  1530. 'label' => wc_attribute_label($slug),
  1531. 'is_taxonomy' => (strpos($slug, 'pa_') === 0) || taxonomy_exists($slug),
  1532. );
  1533. }
  1534. }
  1535. // Source 3: variable parent products' _product_attributes postmeta.
  1536. // Catches attributes flagged "Used for variations" on the product's
  1537. // Attributes tab, even when (a) the attribute is a custom non-global
  1538. // entry, or (b) no variations have been generated yet.
  1539. $sql_parents = "
  1540. SELECT pm.meta_value
  1541. FROM {$wpdb->postmeta} pm
  1542. INNER JOIN {$wpdb->posts} p ON p.ID = pm.post_id
  1543. WHERE p.post_type = 'product'
  1544. AND p.post_status IN ('publish','private','draft')
  1545. AND pm.meta_key = '_product_attributes'
  1546. ";
  1547. $serialized_rows = $wpdb->get_col($sql_parents);
  1548. if (!empty($serialized_rows)) {
  1549. foreach ($serialized_rows as $serialized) {
  1550. $attrs = maybe_unserialize($serialized);
  1551. if (!is_array($attrs)) {
  1552. continue;
  1553. }
  1554. foreach ($attrs as $attr_key => $attr_data) {
  1555. if (!is_array($attr_data) || empty($attr_data['is_variation'])) {
  1556. continue;
  1557. }
  1558. $is_taxonomy = !empty($attr_data['is_taxonomy']);
  1559. $name = isset($attr_data['name']) ? $attr_data['name'] : $attr_key;
  1560. $key = $is_taxonomy ? $name : sanitize_title($name);
  1561. if ($key === '' || isset($seen[$key])) {
  1562. continue;
  1563. }
  1564. $seen[$key] = true;
  1565. $heads[] = array(
  1566. 'key' => $key,
  1567. 'label' => $is_taxonomy ? wc_attribute_label($key) : $name,
  1568. 'is_taxonomy' => $is_taxonomy,
  1569. );
  1570. }
  1571. }
  1572. }
  1573. // Sort alphabetically by label.
  1574. usort($heads, function($a, $b) {
  1575. return strcasecmp($a['label'], $b['label']);
  1576. });
  1577. return $heads;
  1578. }
  1579. /**
  1580. * Get distinct values for the given attribute key, scoped to existing
  1581. * variations (and optionally to a set of parent product categories).
  1582. *
  1583. * For taxonomy attributes (pa_*) the meta_value is the term slug; we
  1584. * resolve labels via get_term_by('slug', ..., $taxonomy).
  1585. *
  1586. * @param string $attribute_key E.g. 'pa_color' or 'size'.
  1587. * @param int[] $category_ids Optional list of parent product_cat term IDs.
  1588. * @return array [ ['value' => string, 'label' => string], ... ]
  1589. */
  1590. public function get_variation_attribute_values($attribute_key, $category_ids = array()) {
  1591. global $wpdb;
  1592. $attribute_key = sanitize_text_field($attribute_key);
  1593. if ($attribute_key === '') {
  1594. return array();
  1595. }
  1596. $meta_key = 'attribute_' . wc_sanitize_taxonomy_name($attribute_key);
  1597. $params = array($meta_key);
  1598. $cat_join = '';
  1599. $cat_where = '';
  1600. if (!empty($category_ids)) {
  1601. $cat_ids = array_map('intval', $category_ids);
  1602. $cat_ids = array_filter($cat_ids, function($v) { return $v > 0; });
  1603. if (!empty($cat_ids)) {
  1604. $placeholders = implode(',', array_fill(0, count($cat_ids), '%d'));
  1605. $cat_join = "
  1606. INNER JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id
  1607. INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
  1608. ";
  1609. $cat_where = "
  1610. AND tt.taxonomy = 'product_cat'
  1611. AND tt.term_id IN ($placeholders)
  1612. ";
  1613. $params = array_merge($params, $cat_ids);
  1614. }
  1615. }
  1616. $sql = "
  1617. SELECT DISTINCT pm.meta_value
  1618. FROM {$wpdb->postmeta} pm
  1619. INNER JOIN {$wpdb->posts} v ON v.ID = pm.post_id
  1620. AND v.post_type = 'product_variation'
  1621. AND v.post_status IN ('publish','private')
  1622. INNER JOIN {$wpdb->posts} p ON p.ID = v.post_parent
  1623. AND p.post_type = 'product'
  1624. $cat_join
  1625. WHERE pm.meta_key = %s
  1626. AND pm.meta_value <> ''
  1627. $cat_where
  1628. ";
  1629. $values = $wpdb->get_col($wpdb->prepare($sql, ...$params));
  1630. $is_taxonomy = (strpos($attribute_key, 'pa_') === 0) || taxonomy_exists($attribute_key);
  1631. // Fallback: if SQL returned no values but the attribute exists on a
  1632. // variable parent's _product_attributes (e.g. variations not generated
  1633. // yet, or custom attribute), parse pipe-separated values from there.
  1634. if (empty($values)) {
  1635. $sanitized_key = $is_taxonomy
  1636. ? (strpos($attribute_key, 'pa_') === 0 ? $attribute_key : 'pa_' . $attribute_key)
  1637. : sanitize_title($attribute_key);
  1638. $sql_parents = "
  1639. SELECT pm.meta_value
  1640. FROM {$wpdb->postmeta} pm
  1641. INNER JOIN {$wpdb->posts} p ON p.ID = pm.post_id
  1642. WHERE p.post_type = 'product'
  1643. AND p.post_status IN ('publish','private','draft')
  1644. AND pm.meta_key = '_product_attributes'
  1645. ";
  1646. $rows = $wpdb->get_col($sql_parents);
  1647. $values = array();
  1648. if (!empty($rows)) {
  1649. foreach ($rows as $serialized) {
  1650. $attrs = maybe_unserialize($serialized);
  1651. if (!is_array($attrs) || !isset($attrs[$sanitized_key])) {
  1652. continue;
  1653. }
  1654. $entry = $attrs[$sanitized_key];
  1655. if (empty($entry['is_variation'])) {
  1656. continue;
  1657. }
  1658. if ($is_taxonomy) {
  1659. // Taxonomy custom values are stored as term IDs in 'value'.
  1660. $term_ids = !empty($entry['value']) ? wp_parse_id_list($entry['value']) : array();
  1661. if (empty($term_ids)) {
  1662. // Or the parent uses all terms — pull them from the taxonomy.
  1663. $tax_name = $sanitized_key;
  1664. $terms = get_terms(array('taxonomy' => $tax_name, 'hide_empty' => false));
  1665. if (!is_wp_error($terms)) {
  1666. foreach ($terms as $t) {
  1667. $values[] = $t->slug;
  1668. }
  1669. }
  1670. } else {
  1671. foreach ($term_ids as $tid) {
  1672. $term = get_term($tid, $sanitized_key);
  1673. if ($term && !is_wp_error($term)) {
  1674. $values[] = $term->slug;
  1675. }
  1676. }
  1677. }
  1678. } else {
  1679. $raw = isset($entry['value']) ? (string) $entry['value'] : '';
  1680. if ($raw !== '') {
  1681. $parts = array_map('trim', explode('|', $raw));
  1682. foreach ($parts as $p) {
  1683. if ($p !== '') {
  1684. $values[] = $p;
  1685. }
  1686. }
  1687. }
  1688. }
  1689. }
  1690. $values = array_values(array_unique($values));
  1691. }
  1692. }
  1693. if (empty($values)) {
  1694. return array();
  1695. }
  1696. $result = array();
  1697. foreach ($values as $value) {
  1698. $label = $value;
  1699. if ($is_taxonomy) {
  1700. $tax = (strpos($attribute_key, 'pa_') === 0) ? $attribute_key : 'pa_' . $attribute_key;
  1701. $term = get_term_by('slug', $value, $tax);
  1702. if ($term && !is_wp_error($term)) {
  1703. $label = $term->name;
  1704. }
  1705. }
  1706. $result[] = array(
  1707. 'value' => $value,
  1708. 'label' => $label,
  1709. );
  1710. }
  1711. usort($result, function($a, $b) {
  1712. return strcasecmp($a['label'], $b['label']);
  1713. });
  1714. return $result;
  1715. }
  1716. /**
  1717. * Find variations matching the filter.
  1718. *
  1719. * @param int[] $category_ids
  1720. * @param string $attribute_key
  1721. * @param string $attribute_value
  1722. * @return array ['count' => int, 'ids' => int[], 'sample' => array[]]
  1723. */
  1724. public function find_matching_variations($category_ids, $attribute_key, $attribute_value) {
  1725. global $wpdb;
  1726. $category_ids = array_filter(array_map('intval', (array) $category_ids), function($v) { return $v > 0; });
  1727. $attribute_key = sanitize_text_field($attribute_key);
  1728. $attribute_value = sanitize_text_field($attribute_value);
  1729. if (empty($category_ids) || $attribute_key === '' || $attribute_value === '') {
  1730. return array('count' => 0, 'ids' => array(), 'sample' => array());
  1731. }
  1732. $meta_key = 'attribute_' . wc_sanitize_taxonomy_name($attribute_key);
  1733. $placeholders = implode(',', array_fill(0, count($category_ids), '%d'));
  1734. $sql = "
  1735. SELECT DISTINCT v.ID
  1736. FROM {$wpdb->posts} v
  1737. INNER JOIN {$wpdb->posts} p ON p.ID = v.post_parent
  1738. INNER JOIN {$wpdb->postmeta} pm ON pm.post_id = v.ID
  1739. INNER JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id
  1740. INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
  1741. WHERE v.post_type = 'product_variation'
  1742. AND v.post_status IN ('publish','private')
  1743. AND p.post_type = 'product'
  1744. AND tt.taxonomy = 'product_cat'
  1745. AND tt.term_id IN ($placeholders)
  1746. AND pm.meta_key = %s
  1747. AND pm.meta_value = %s
  1748. ";
  1749. $params = array_merge($category_ids, array($meta_key, $attribute_value));
  1750. $ids = $wpdb->get_col($wpdb->prepare($sql, ...$params));
  1751. $ids = $ids ? array_map('intval', $ids) : array();
  1752. // Build a sample (up to 20).
  1753. $sample = array();
  1754. $slice = array_slice($ids, 0, 20);
  1755. foreach ($slice as $id) {
  1756. $variation = wc_get_product($id);
  1757. if (!$variation) {
  1758. continue;
  1759. }
  1760. $parent_id = $variation->get_parent_id();
  1761. $parent_name = '';
  1762. if ($parent_id) {
  1763. $parent = wc_get_product($parent_id);
  1764. if ($parent) {
  1765. $parent_name = $parent->get_name();
  1766. }
  1767. }
  1768. $sample[] = array(
  1769. 'id' => $id,
  1770. 'sku' => $variation->get_sku(),
  1771. 'name' => $variation->get_name(),
  1772. 'parent_name' => $parent_name,
  1773. 'current_price' => $variation->get_regular_price(),
  1774. );
  1775. }
  1776. return array(
  1777. 'count' => count($ids),
  1778. 'ids' => $ids,
  1779. 'sample' => $sample,
  1780. );
  1781. }
  1782. /**
  1783. * Apply new regular price to a list of variation IDs.
  1784. *
  1785. * @param int[] $variation_ids
  1786. * @param string $new_price
  1787. * @return array ['updated','failed','failed_ids','message']
  1788. */
  1789. public function apply_variant_price($variation_ids, $new_price) {
  1790. $variation_ids = array_filter(array_map('intval', (array) $variation_ids), function($v) { return $v > 0; });
  1791. // Validate price.
  1792. if (!is_numeric($new_price) || (float) $new_price < 0) {
  1793. return array(
  1794. 'updated' => 0,
  1795. 'failed' => 0,
  1796. 'failed_ids' => array(),
  1797. 'message' => __('Please enter a valid new price', 'studiou-wc-product-cat-manage'),
  1798. 'error' => true,
  1799. );
  1800. }
  1801. $formatted = wc_format_decimal($new_price);
  1802. $updated = 0;
  1803. $failed = 0;
  1804. $failed_ids = array();
  1805. $parent_ids = array();
  1806. foreach ($variation_ids as $id) {
  1807. try {
  1808. $variation = wc_get_product($id);
  1809. if (!$variation || !$variation->is_type('variation')) {
  1810. $failed++;
  1811. $failed_ids[] = $id;
  1812. error_log('STUDIOU WC UPVP: Variation ' . $id . ' not found or not a variation');
  1813. continue;
  1814. }
  1815. $variation->set_regular_price($formatted);
  1816. $variation->save();
  1817. $updated++;
  1818. $parent_id = $variation->get_parent_id();
  1819. if ($parent_id) {
  1820. $parent_ids[$parent_id] = true;
  1821. }
  1822. } catch (Exception $e) {
  1823. $failed++;
  1824. $failed_ids[] = $id;
  1825. error_log('STUDIOU WC UPVP: Exception updating variation ' . $id . ' - ' . $e->getMessage());
  1826. }
  1827. }
  1828. // Re-sync parent variable products so price-range cache reflects the new prices.
  1829. if (!empty($parent_ids) && class_exists('WC_Product_Variable')) {
  1830. foreach (array_keys($parent_ids) as $parent_id) {
  1831. try {
  1832. WC_Product_Variable::sync($parent_id);
  1833. if (function_exists('wc_delete_product_transients')) {
  1834. wc_delete_product_transients($parent_id);
  1835. }
  1836. } catch (Exception $e) {
  1837. error_log('STUDIOU WC UPVP: Failed to sync parent ' . $parent_id . ' - ' . $e->getMessage());
  1838. }
  1839. }
  1840. }
  1841. $message = sprintf(
  1842. __('Successfully updated %d variations.', 'studiou-wc-product-cat-manage'),
  1843. $updated
  1844. );
  1845. if ($failed > 0) {
  1846. $message .= ' ' . sprintf(
  1847. __('Failed to update %d variations.', 'studiou-wc-product-cat-manage'),
  1848. $failed
  1849. );
  1850. }
  1851. return array(
  1852. 'updated' => $updated,
  1853. 'failed' => $failed,
  1854. 'failed_ids' => $failed_ids,
  1855. 'message' => $message,
  1856. );
  1857. }
  1858. /**
  1859. * Common AJAX preflight: nonce + capability + output buffer setup.
  1860. * Returns false on failure (after sending JSON error), true on success.
  1861. */
  1862. private function upvp_preflight() {
  1863. while (ob_get_level()) {
  1864. ob_end_clean();
  1865. }
  1866. ob_start();
  1867. if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'studiou-wcpcm-nonce')) {
  1868. ob_clean();
  1869. wp_send_json_error(array('message' => __('Security check failed', 'studiou-wc-product-cat-manage')));
  1870. return false;
  1871. }
  1872. if (!current_user_can('manage_woocommerce')) {
  1873. ob_clean();
  1874. wp_send_json_error(array('message' => __('You do not have sufficient permissions', 'studiou-wc-product-cat-manage')));
  1875. return false;
  1876. }
  1877. return true;
  1878. }
  1879. /**
  1880. * AJAX: list variation attribute heads.
  1881. */
  1882. public function handle_upvp_get_attributes_ajax() {
  1883. if (!$this->upvp_preflight()) return;
  1884. $original_error_reporting = error_reporting();
  1885. error_reporting(0);
  1886. try {
  1887. $heads = $this->get_variation_attribute_heads();
  1888. ob_clean();
  1889. wp_send_json_success(array('attributes' => $heads));
  1890. } catch (Exception $e) {
  1891. error_log('STUDIOU WC UPVP: get_attributes failed - ' . $e->getMessage());
  1892. ob_clean();
  1893. wp_send_json_error(array('message' => $e->getMessage()));
  1894. } finally {
  1895. error_reporting($original_error_reporting);
  1896. ob_end_clean();
  1897. }
  1898. }
  1899. /**
  1900. * AJAX: list values for the chosen attribute (scoped to selected categories).
  1901. */
  1902. public function handle_upvp_get_attribute_values_ajax() {
  1903. if (!$this->upvp_preflight()) return;
  1904. $original_error_reporting = error_reporting();
  1905. error_reporting(0);
  1906. try {
  1907. $attribute_key = isset($_POST['attribute_key']) ? sanitize_text_field(wp_unslash($_POST['attribute_key'])) : '';
  1908. $category_ids = isset($_POST['category_ids']) ? array_map('intval', (array) $_POST['category_ids']) : array();
  1909. if ($attribute_key === '') {
  1910. ob_clean();
  1911. wp_send_json_error(array('message' => __('Please select an attribute', 'studiou-wc-product-cat-manage')));
  1912. return;
  1913. }
  1914. $values = $this->get_variation_attribute_values($attribute_key, $category_ids);
  1915. ob_clean();
  1916. wp_send_json_success(array('values' => $values));
  1917. } catch (Exception $e) {
  1918. error_log('STUDIOU WC UPVP: get_attribute_values failed - ' . $e->getMessage());
  1919. ob_clean();
  1920. wp_send_json_error(array('message' => $e->getMessage()));
  1921. } finally {
  1922. error_reporting($original_error_reporting);
  1923. ob_end_clean();
  1924. }
  1925. }
  1926. /**
  1927. * AJAX: count + sample of variations matching the current filter.
  1928. */
  1929. public function handle_upvp_count_ajax() {
  1930. if (!$this->upvp_preflight()) return;
  1931. $original_error_reporting = error_reporting();
  1932. error_reporting(0);
  1933. try {
  1934. $category_ids = isset($_POST['category_ids']) ? array_map('intval', (array) $_POST['category_ids']) : array();
  1935. $attribute_key = isset($_POST['attribute_key']) ? sanitize_text_field(wp_unslash($_POST['attribute_key'])) : '';
  1936. $attribute_value = isset($_POST['attribute_value']) ? sanitize_text_field(wp_unslash($_POST['attribute_value'])) : '';
  1937. if (empty($category_ids)) {
  1938. ob_clean();
  1939. wp_send_json_error(array('message' => __('Please select at least one category', 'studiou-wc-product-cat-manage')));
  1940. return;
  1941. }
  1942. if ($attribute_key === '') {
  1943. ob_clean();
  1944. wp_send_json_error(array('message' => __('Please select an attribute', 'studiou-wc-product-cat-manage')));
  1945. return;
  1946. }
  1947. if ($attribute_value === '') {
  1948. ob_clean();
  1949. wp_send_json_error(array('message' => __('Please select an attribute value', 'studiou-wc-product-cat-manage')));
  1950. return;
  1951. }
  1952. $result = $this->find_matching_variations($category_ids, $attribute_key, $attribute_value);
  1953. ob_clean();
  1954. wp_send_json_success(array(
  1955. 'count' => $result['count'],
  1956. 'sample' => $result['sample'],
  1957. ));
  1958. } catch (Exception $e) {
  1959. error_log('STUDIOU WC UPVP: count failed - ' . $e->getMessage());
  1960. ob_clean();
  1961. wp_send_json_error(array('message' => $e->getMessage()));
  1962. } finally {
  1963. error_reporting($original_error_reporting);
  1964. ob_end_clean();
  1965. }
  1966. }
  1967. /**
  1968. * AJAX: apply new regular price to all matching variations.
  1969. */
  1970. public function handle_upvp_apply_ajax() {
  1971. if (!$this->upvp_preflight()) return;
  1972. $original_error_reporting = error_reporting();
  1973. error_reporting(0);
  1974. try {
  1975. $category_ids = isset($_POST['category_ids']) ? array_map('intval', (array) $_POST['category_ids']) : array();
  1976. $attribute_key = isset($_POST['attribute_key']) ? sanitize_text_field(wp_unslash($_POST['attribute_key'])) : '';
  1977. $attribute_value = isset($_POST['attribute_value']) ? sanitize_text_field(wp_unslash($_POST['attribute_value'])) : '';
  1978. $new_price = isset($_POST['new_price']) ? sanitize_text_field(wp_unslash($_POST['new_price'])) : '';
  1979. if (empty($category_ids)) {
  1980. ob_clean();
  1981. wp_send_json_error(array('message' => __('Please select at least one category', 'studiou-wc-product-cat-manage')));
  1982. return;
  1983. }
  1984. if ($attribute_key === '' || $attribute_value === '') {
  1985. ob_clean();
  1986. wp_send_json_error(array('message' => __('Please select an attribute value', 'studiou-wc-product-cat-manage')));
  1987. return;
  1988. }
  1989. if ($new_price === '' || !is_numeric($new_price) || (float) $new_price < 0) {
  1990. ob_clean();
  1991. wp_send_json_error(array('message' => __('Please enter a valid new price', 'studiou-wc-product-cat-manage')));
  1992. return;
  1993. }
  1994. $matching = $this->find_matching_variations($category_ids, $attribute_key, $attribute_value);
  1995. if ($matching['count'] === 0) {
  1996. ob_clean();
  1997. wp_send_json_error(array('message' => __('No variations match the current filter.', 'studiou-wc-product-cat-manage')));
  1998. return;
  1999. }
  2000. $result = $this->apply_variant_price($matching['ids'], $new_price);
  2001. ob_clean();
  2002. wp_send_json_success(array(
  2003. 'updated' => $result['updated'],
  2004. 'failed' => $result['failed'],
  2005. 'failed_ids' => $result['failed_ids'],
  2006. 'message' => $result['message'],
  2007. ));
  2008. } catch (Exception $e) {
  2009. error_log('STUDIOU WC UPVP: apply failed - ' . $e->getMessage());
  2010. ob_clean();
  2011. wp_send_json_error(array('message' => $e->getMessage()));
  2012. } finally {
  2013. error_reporting($original_error_reporting);
  2014. ob_end_clean();
  2015. }
  2016. }
  2017. }