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

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