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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225
  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 a test AJAX handler to verify AJAX is working
  37. add_action('wp_ajax_studiou_wcpcm_test', array($this, 'handle_test_ajax'));
  38. // Debug: Log that the handler is being registered
  39. if (defined('WP_DEBUG') && WP_DEBUG) {
  40. error_log('STUDIOU WC: AJAX handlers registered - move_products, batch_description, delete_products, and clear_media');
  41. }
  42. }
  43. /**
  44. * Handle AJAX batch description request
  45. */
  46. public function handle_batch_description_ajax() {
  47. // Clean all output buffers and prevent any output
  48. while (ob_get_level()) {
  49. ob_end_clean();
  50. }
  51. // Start a new output buffer to catch any unwanted output
  52. ob_start();
  53. // Suppress PHP errors/notices during AJAX to prevent JSON corruption
  54. $original_error_reporting = error_reporting();
  55. error_reporting(0);
  56. // Enable error logging only
  57. if (defined('WP_DEBUG') && WP_DEBUG) {
  58. error_log('STUDIOU WC: Batch description AJAX handler called');
  59. error_log('STUDIOU WC: POST data: ' . print_r($_POST, true));
  60. }
  61. try {
  62. // Check nonce
  63. if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'studiou-wcpcm-nonce')) {
  64. wp_send_json_error(array(
  65. 'message' => __('Security check failed', 'studiou-wc-product-cat-manage')
  66. ));
  67. }
  68. // Check permissions
  69. if (!current_user_can('manage_woocommerce')) {
  70. wp_send_json_error(array(
  71. 'message' => __('You do not have sufficient permissions', 'studiou-wc-product-cat-manage')
  72. ));
  73. }
  74. // Validate input
  75. if (!isset($_POST['selected_categories']) || !isset($_POST['description'])) {
  76. wp_send_json_error(array(
  77. 'message' => __('Missing required parameters', 'studiou-wc-product-cat-manage')
  78. ));
  79. }
  80. $selected_categories = array_map('intval', $_POST['selected_categories']);
  81. $description = sanitize_textarea_field($_POST['description']);
  82. // Debug logging
  83. if (defined('WP_DEBUG') && WP_DEBUG) {
  84. error_log('STUDIOU WC: Batch description operation started - Categories: ' . implode(', ', $selected_categories));
  85. error_log('STUDIOU WC: Description: ' . $description);
  86. }
  87. // Validate categories
  88. if (empty($selected_categories)) {
  89. wp_send_json_error(array(
  90. 'message' => __('Please select at least one category', 'studiou-wc-product-cat-manage')
  91. ));
  92. }
  93. // Execute batch description operation
  94. $result = $this->update_categories_description($selected_categories, $description);
  95. // Debug logging
  96. if (defined('WP_DEBUG') && WP_DEBUG) {
  97. error_log('STUDIOU WC: Batch description operation completed - Updated: ' . $result['updated_count'] . ' categories');
  98. error_log('STUDIOU WC: Sending success response: ' . print_r($result, true));
  99. }
  100. // Clean any output that might have been generated
  101. ob_clean();
  102. // Return success response
  103. wp_send_json_success(array(
  104. 'message' => $result['message'],
  105. 'updated_count' => $result['updated_count'],
  106. 'failed_count' => isset($result['failed_count']) ? $result['failed_count'] : 0
  107. ));
  108. } catch (Exception $e) {
  109. // Debug logging
  110. if (defined('WP_DEBUG') && WP_DEBUG) {
  111. error_log('STUDIOU WC: Batch description operation failed - ' . $e->getMessage());
  112. error_log('STUDIOU WC: Exception trace: ' . $e->getTraceAsString());
  113. }
  114. // Clean any output that might have been generated
  115. ob_clean();
  116. wp_send_json_error(array(
  117. 'message' => sprintf(
  118. __('Error during batch description operation: %s', 'studiou-wc-product-cat-manage'),
  119. $e->getMessage()
  120. )
  121. ));
  122. } finally {
  123. // Restore original error reporting
  124. error_reporting($original_error_reporting);
  125. // End the output buffer
  126. ob_end_clean();
  127. }
  128. }
  129. /**
  130. * Handle AJAX move products request
  131. */
  132. public function handle_move_products_ajax() {
  133. // Clean all output buffers and prevent any output
  134. while (ob_get_level()) {
  135. ob_end_clean();
  136. }
  137. // Start a new output buffer to catch any unwanted output
  138. ob_start();
  139. // Suppress PHP errors/notices during AJAX to prevent JSON corruption
  140. $original_error_reporting = error_reporting();
  141. error_reporting(0);
  142. // Enable error logging only
  143. if (defined('WP_DEBUG') && WP_DEBUG) {
  144. error_log('STUDIOU WC: AJAX handler called');
  145. error_log('STUDIOU WC: POST data: ' . print_r($_POST, true));
  146. }
  147. try {
  148. // Check nonce
  149. if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'studiou-wcpcm-nonce')) {
  150. wp_send_json_error(array(
  151. 'message' => __('Security check failed', 'studiou-wc-product-cat-manage')
  152. ));
  153. }
  154. // Check permissions
  155. if (!current_user_can('manage_woocommerce')) {
  156. wp_send_json_error(array(
  157. 'message' => __('You do not have sufficient permissions', 'studiou-wc-product-cat-manage')
  158. ));
  159. }
  160. // Validate input
  161. if (!isset($_POST['source_category']) || !isset($_POST['target_category'])) {
  162. wp_send_json_error(array(
  163. 'message' => __('Missing required parameters', 'studiou-wc-product-cat-manage')
  164. ));
  165. }
  166. $source_category_id = intval($_POST['source_category']);
  167. $target_category_id = intval($_POST['target_category']);
  168. // Debug logging
  169. if (defined('WP_DEBUG') && WP_DEBUG) {
  170. error_log('STUDIOU WC: Move operation started - Source: ' . $source_category_id . ', Target: ' . $target_category_id);
  171. }
  172. // Validate categories
  173. if ($source_category_id === $target_category_id) {
  174. wp_send_json_error(array(
  175. 'message' => __('Source and target categories must be different', 'studiou-wc-product-cat-manage')
  176. ));
  177. }
  178. if ($source_category_id <= 0 || $target_category_id <= 0) {
  179. wp_send_json_error(array(
  180. 'message' => __('Invalid category selection', 'studiou-wc-product-cat-manage')
  181. ));
  182. }
  183. // Execute move operation
  184. $result = $this->move_products_between_categories($source_category_id, $target_category_id);
  185. // Debug logging
  186. if (defined('WP_DEBUG') && WP_DEBUG) {
  187. error_log('STUDIOU WC: Move operation completed - Moved: ' . $result['moved_count'] . ' products');
  188. error_log('STUDIOU WC: Sending success response: ' . print_r($result, true));
  189. }
  190. // Clean any output that might have been generated
  191. ob_clean();
  192. // Return success response
  193. wp_send_json_success(array(
  194. 'message' => $result['message'],
  195. 'moved_count' => $result['moved_count'],
  196. 'source_count' => $result['source_count'],
  197. 'target_count' => $result['target_count'],
  198. 'failed_count' => isset($result['failed_count']) ? $result['failed_count'] : 0
  199. ));
  200. } catch (Exception $e) {
  201. // Debug logging
  202. if (defined('WP_DEBUG') && WP_DEBUG) {
  203. error_log('STUDIOU WC: Move operation failed - ' . $e->getMessage());
  204. error_log('STUDIOU WC: Exception trace: ' . $e->getTraceAsString());
  205. }
  206. // Clean any output that might have been generated
  207. ob_clean();
  208. wp_send_json_error(array(
  209. 'message' => sprintf(
  210. __('Error during move operation: %s', 'studiou-wc-product-cat-manage'),
  211. $e->getMessage()
  212. )
  213. ));
  214. } finally {
  215. // Restore original error reporting
  216. error_reporting($original_error_reporting);
  217. // End the output buffer
  218. ob_end_clean();
  219. }
  220. }
  221. /**
  222. * Move all products from source category to target category
  223. *
  224. * @param int $source_category_id Source category ID
  225. * @param int $target_category_id Target category ID
  226. * @return array Result with counts and message
  227. * @throws Exception On error
  228. */
  229. public function move_products_between_categories($source_category_id, $target_category_id) {
  230. // Get source and target category terms
  231. $source_category = get_term($source_category_id, 'product_cat');
  232. $target_category = get_term($target_category_id, 'product_cat');
  233. if (is_wp_error($source_category) || is_wp_error($target_category)) {
  234. throw new Exception(__('Invalid category specified', 'studiou-wc-product-cat-manage'));
  235. }
  236. // Get initial count of products in source category using direct DB query
  237. $initial_source_count = $this->get_category_product_count($source_category_id);
  238. // Check if source category has any products
  239. if ($initial_source_count === 0) {
  240. $message = sprintf(
  241. __('No products found in source category "%s". Nothing to move.', 'studiou-wc-product-cat-manage'),
  242. $source_category->name
  243. );
  244. return array(
  245. 'moved_count' => 0,
  246. 'source_count' => 0,
  247. 'target_count' => $this->get_category_product_count($target_category_id),
  248. 'message' => $message
  249. );
  250. }
  251. // Get all products in source category using direct DB query
  252. $products = $this->get_products_in_category($source_category_id);
  253. $moved_count = 0;
  254. $failed_count = 0;
  255. if (defined('WP_DEBUG') && WP_DEBUG) {
  256. error_log('STUDIOU WC: Found ' . count($products) . ' products in category ' . $source_category->name . ' for moving');
  257. }
  258. // Move each product
  259. foreach ($products as $product_id) {
  260. // Get current categories for the product
  261. $current_categories = wp_get_post_terms($product_id, 'product_cat', array('fields' => 'ids'));
  262. if (is_wp_error($current_categories)) {
  263. $failed_count++;
  264. if (defined('WP_DEBUG') && WP_DEBUG) {
  265. error_log('STUDIOU WC: Error getting categories for product ' . $product_id . ': ' . $current_categories->get_error_message());
  266. }
  267. continue;
  268. }
  269. // Remove source category and add target category
  270. $new_categories = array_diff($current_categories, array($source_category_id));
  271. $new_categories[] = $target_category_id;
  272. // Update product categories
  273. $result = wp_set_post_terms($product_id, $new_categories, 'product_cat');
  274. if (!is_wp_error($result)) {
  275. $moved_count++;
  276. if (defined('WP_DEBUG') && WP_DEBUG) {
  277. error_log('STUDIOU WC: Successfully moved product ' . $product_id . ' from category ' . $source_category_id . ' to ' . $target_category_id);
  278. }
  279. } else {
  280. $failed_count++;
  281. if (defined('WP_DEBUG') && WP_DEBUG) {
  282. error_log('STUDIOU WC: Error moving product ' . $product_id . ': ' . $result->get_error_message());
  283. }
  284. }
  285. }
  286. // Get updated counts using direct DB query
  287. $source_count = $this->get_category_product_count($source_category_id);
  288. $target_count = $this->get_category_product_count($target_category_id);
  289. // Generate detailed result message
  290. if ($moved_count === 0 && count($products) > 0) {
  291. $message = sprintf(
  292. __('Failed to move any products from "%s" to "%s". All %d products encountered errors during the move operation.', 'studiou-wc-product-cat-manage'),
  293. $source_category->name,
  294. $target_category->name,
  295. count($products)
  296. );
  297. } else {
  298. $message = sprintf(
  299. __('Moved %d products from "%s" to "%s". Source category now has %d products, target category now has %d products.', 'studiou-wc-product-cat-manage'),
  300. $moved_count,
  301. $source_category->name,
  302. $target_category->name,
  303. $source_count,
  304. $target_count
  305. );
  306. if ($failed_count > 0) {
  307. $message .= ' ' . sprintf(
  308. __('Note: %d products failed to move due to errors.', 'studiou-wc-product-cat-manage'),
  309. $failed_count
  310. );
  311. }
  312. }
  313. return array(
  314. 'moved_count' => $moved_count,
  315. 'source_count' => $source_count,
  316. 'target_count' => $target_count,
  317. 'failed_count' => $failed_count,
  318. 'message' => $message
  319. );
  320. }
  321. /**
  322. * Get product count for a category
  323. *
  324. * @param int $category_id Category ID
  325. * @return int Product count
  326. */
  327. private function get_category_product_count($category_id) {
  328. global $wpdb;
  329. // Use direct database query for more accurate counting
  330. $sql = "
  331. SELECT COUNT(DISTINCT p.ID)
  332. FROM {$wpdb->posts} p
  333. INNER JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id
  334. INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
  335. WHERE tt.term_id = %d
  336. AND tt.taxonomy = 'product_cat'
  337. AND p.post_type = 'product'
  338. AND p.post_status IN ('publish', 'private', 'draft')
  339. ";
  340. $count = $wpdb->get_var($wpdb->prepare($sql, $category_id));
  341. if (defined('WP_DEBUG') && WP_DEBUG) {
  342. error_log('STUDIOU WC: Category ' . $category_id . ' product count (direct DB query): ' . intval($count));
  343. }
  344. return intval($count);
  345. }
  346. /**
  347. * Get all products in a category
  348. *
  349. * @param int $category_id Category ID
  350. * @return array Array of product IDs
  351. */
  352. private function get_products_in_category($category_id) {
  353. global $wpdb;
  354. // Use direct database query to get products
  355. $sql = "
  356. SELECT DISTINCT p.ID
  357. FROM {$wpdb->posts} p
  358. INNER JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id
  359. INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
  360. WHERE tt.term_id = %d
  361. AND tt.taxonomy = 'product_cat'
  362. AND p.post_type = 'product'
  363. AND p.post_status IN ('publish', 'private', 'draft')
  364. ";
  365. $products = $wpdb->get_col($wpdb->prepare($sql, $category_id));
  366. if (defined('WP_DEBUG') && WP_DEBUG) {
  367. error_log('STUDIOU WC: Found ' . count($products) . ' products in category ' . $category_id . ' (direct DB query)');
  368. if (!empty($products)) {
  369. error_log('STUDIOU WC: Product IDs: ' . implode(', ', array_slice($products, 0, 10)) . (count($products) > 10 ? ' (showing first 10)' : ''));
  370. }
  371. }
  372. return $products ? array_map('intval', $products) : array();
  373. }
  374. /**
  375. * Update descriptions for multiple categories
  376. *
  377. * @param array $category_ids Array of category IDs
  378. * @param string $description New description for categories
  379. * @return array Result with counts and message
  380. * @throws Exception On error
  381. */
  382. public function update_categories_description($category_ids, $description) {
  383. $updated_count = 0;
  384. $failed_count = 0;
  385. $category_names = array();
  386. // Debug logging
  387. if (defined('WP_DEBUG') && WP_DEBUG) {
  388. error_log('STUDIOU WC: Starting batch description update for ' . count($category_ids) . ' categories');
  389. }
  390. // Update each category
  391. foreach ($category_ids as $category_id) {
  392. // Get category term
  393. $category = get_term($category_id, 'product_cat');
  394. if (is_wp_error($category) || !$category) {
  395. $failed_count++;
  396. if (defined('WP_DEBUG') && WP_DEBUG) {
  397. error_log('STUDIOU WC: Error getting category ' . $category_id . ': ' . ($category ? $category->get_error_message() : 'Category not found'));
  398. }
  399. continue;
  400. }
  401. // Update category description
  402. $result = wp_update_term($category_id, 'product_cat', array(
  403. 'description' => $description
  404. ));
  405. if (!is_wp_error($result)) {
  406. $updated_count++;
  407. $category_names[] = $category->name;
  408. if (defined('WP_DEBUG') && WP_DEBUG) {
  409. error_log('STUDIOU WC: Successfully updated description for category ' . $category_id . ' (' . $category->name . ')');
  410. }
  411. } else {
  412. $failed_count++;
  413. if (defined('WP_DEBUG') && WP_DEBUG) {
  414. error_log('STUDIOU WC: Error updating category ' . $category_id . ': ' . $result->get_error_message());
  415. }
  416. }
  417. }
  418. // Generate result message
  419. if ($updated_count === 0) {
  420. $message = sprintf(
  421. __('Failed to update any category descriptions. %d categories encountered errors.', 'studiou-wc-product-cat-manage'),
  422. $failed_count
  423. );
  424. } else {
  425. $message = sprintf(
  426. __('Successfully updated descriptions for %d categories: %s', 'studiou-wc-product-cat-manage'),
  427. $updated_count,
  428. implode(', ', array_slice($category_names, 0, 5)) . ($updated_count > 5 ? sprintf(__(', and %d more', 'studiou-wc-product-cat-manage'), $updated_count - 5) : '')
  429. );
  430. if ($failed_count > 0) {
  431. $message .= ' ' . sprintf(
  432. __('Note: %d categories failed to update due to errors.', 'studiou-wc-product-cat-manage'),
  433. $failed_count
  434. );
  435. }
  436. }
  437. return array(
  438. 'updated_count' => $updated_count,
  439. 'failed_count' => $failed_count,
  440. 'message' => $message
  441. );
  442. }
  443. /**
  444. * Get all categories with product counts for select lists
  445. *
  446. * @return array Array of categories with ID, name, and product count
  447. */
  448. public function get_categories_with_counts() {
  449. $args = array(
  450. 'taxonomy' => 'product_cat',
  451. 'orderby' => 'name',
  452. 'hide_empty' => false,
  453. );
  454. $categories = get_terms($args);
  455. $categories_with_counts = array();
  456. if (!is_wp_error($categories)) {
  457. foreach ($categories as $category) {
  458. $product_count = $this->get_category_product_count($category->term_id);
  459. $categories_with_counts[] = array(
  460. 'id' => $category->term_id,
  461. 'name' => $category->name,
  462. 'count' => $product_count,
  463. 'display_name' => sprintf('%s (%d products)', $category->name, $product_count)
  464. );
  465. }
  466. }
  467. return $categories_with_counts;
  468. }
  469. /**
  470. * Handle AJAX delete products request (initial request to get product IDs)
  471. */
  472. public function handle_delete_products_ajax() {
  473. // Clean all output buffers and prevent any output
  474. while (ob_get_level()) {
  475. ob_end_clean();
  476. }
  477. // Start a new output buffer to catch any unwanted output
  478. ob_start();
  479. // Suppress PHP errors/notices during AJAX to prevent JSON corruption
  480. $original_error_reporting = error_reporting();
  481. error_reporting(0);
  482. // Enable error logging only
  483. if (defined('WP_DEBUG') && WP_DEBUG) {
  484. error_log('STUDIOU WC: Delete products AJAX handler called');
  485. error_log('STUDIOU WC: POST data: ' . print_r($_POST, true));
  486. }
  487. try {
  488. // Check nonce
  489. if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'studiou-wcpcm-nonce')) {
  490. wp_send_json_error(array(
  491. 'message' => __('Security check failed', 'studiou-wc-product-cat-manage')
  492. ));
  493. }
  494. // Check permissions
  495. if (!current_user_can('manage_woocommerce')) {
  496. wp_send_json_error(array(
  497. 'message' => __('You do not have sufficient permissions', 'studiou-wc-product-cat-manage')
  498. ));
  499. }
  500. // Validate input
  501. if (!isset($_POST['delete_categories'])) {
  502. wp_send_json_error(array(
  503. 'message' => __('Missing required parameters', 'studiou-wc-product-cat-manage')
  504. ));
  505. }
  506. $category_ids = array_map('intval', $_POST['delete_categories']);
  507. // Debug logging
  508. if (defined('WP_DEBUG') && WP_DEBUG) {
  509. error_log('STUDIOU WC: Delete products operation started - Categories: ' . implode(', ', $category_ids));
  510. }
  511. // Validate categories
  512. if (empty($category_ids)) {
  513. wp_send_json_error(array(
  514. 'message' => __('Please select at least one category', 'studiou-wc-product-cat-manage')
  515. ));
  516. }
  517. // Get all products from selected categories
  518. $product_ids = $this->get_products_from_categories($category_ids);
  519. // Debug logging
  520. if (defined('WP_DEBUG') && WP_DEBUG) {
  521. error_log('STUDIOU WC: Found ' . count($product_ids) . ' products to delete');
  522. }
  523. // Clean any output that might have been generated
  524. ob_clean();
  525. // Return product IDs for batch processing
  526. wp_send_json_success(array(
  527. 'product_ids' => $product_ids,
  528. 'total_count' => count($product_ids),
  529. 'message' => sprintf(
  530. __('Found %d products to delete', 'studiou-wc-product-cat-manage'),
  531. count($product_ids)
  532. )
  533. ));
  534. } catch (Exception $e) {
  535. // Debug logging
  536. if (defined('WP_DEBUG') && WP_DEBUG) {
  537. error_log('STUDIOU WC: Delete products operation failed - ' . $e->getMessage());
  538. error_log('STUDIOU WC: Exception trace: ' . $e->getTraceAsString());
  539. }
  540. // Clean any output that might have been generated
  541. ob_clean();
  542. wp_send_json_error(array(
  543. 'message' => sprintf(
  544. __('Error during delete operation: %s', 'studiou-wc-product-cat-manage'),
  545. $e->getMessage()
  546. )
  547. ));
  548. } finally {
  549. // Restore original error reporting
  550. error_reporting($original_error_reporting);
  551. // End the output buffer
  552. ob_end_clean();
  553. }
  554. }
  555. /**
  556. * Handle AJAX delete products batch request (processes products in batches)
  557. */
  558. public function handle_delete_products_batch_ajax() {
  559. // Clean all output buffers and prevent any output
  560. while (ob_get_level()) {
  561. ob_end_clean();
  562. }
  563. // Start a new output buffer to catch any unwanted output
  564. ob_start();
  565. // Suppress PHP errors/notices during AJAX to prevent JSON corruption
  566. $original_error_reporting = error_reporting();
  567. error_reporting(0);
  568. // Enable error logging only
  569. if (defined('WP_DEBUG') && WP_DEBUG) {
  570. error_log('STUDIOU WC: Delete products batch AJAX handler called');
  571. error_log('STUDIOU WC: POST data: ' . print_r($_POST, true));
  572. }
  573. try {
  574. // Check nonce
  575. if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'studiou-wcpcm-nonce')) {
  576. wp_send_json_error(array(
  577. 'message' => __('Security check failed', 'studiou-wc-product-cat-manage')
  578. ));
  579. }
  580. // Check permissions
  581. if (!current_user_can('manage_woocommerce')) {
  582. wp_send_json_error(array(
  583. 'message' => __('You do not have sufficient permissions', 'studiou-wc-product-cat-manage')
  584. ));
  585. }
  586. // Validate input
  587. if (!isset($_POST['product_ids'])) {
  588. wp_send_json_error(array(
  589. 'message' => __('Missing required parameters', 'studiou-wc-product-cat-manage')
  590. ));
  591. }
  592. $product_ids = array_map('intval', $_POST['product_ids']);
  593. // Debug logging
  594. if (defined('WP_DEBUG') && WP_DEBUG) {
  595. error_log('STUDIOU WC: Processing batch of ' . count($product_ids) . ' products for deletion');
  596. }
  597. // Delete products in this batch
  598. $result = $this->delete_products_batch($product_ids);
  599. // Debug logging
  600. if (defined('WP_DEBUG') && WP_DEBUG) {
  601. error_log('STUDIOU WC: Batch deletion completed - Deleted: ' . $result['deleted_count'] . ', Failed: ' . $result['failed_count']);
  602. }
  603. // Clean any output that might have been generated
  604. ob_clean();
  605. // Return success response
  606. wp_send_json_success(array(
  607. 'deleted_count' => $result['deleted_count'],
  608. 'failed_count' => $result['failed_count'],
  609. 'failed_products' => $result['failed_products']
  610. ));
  611. } catch (Exception $e) {
  612. // Debug logging
  613. if (defined('WP_DEBUG') && WP_DEBUG) {
  614. error_log('STUDIOU WC: Delete products batch operation failed - ' . $e->getMessage());
  615. error_log('STUDIOU WC: Exception trace: ' . $e->getTraceAsString());
  616. }
  617. // Clean any output that might have been generated
  618. ob_clean();
  619. wp_send_json_error(array(
  620. 'message' => sprintf(
  621. __('Error during delete batch operation: %s', 'studiou-wc-product-cat-manage'),
  622. $e->getMessage()
  623. )
  624. ));
  625. } finally {
  626. // Restore original error reporting
  627. error_reporting($original_error_reporting);
  628. // End the output buffer
  629. ob_end_clean();
  630. }
  631. }
  632. /**
  633. * Get all products from multiple categories
  634. *
  635. * @param array $category_ids Array of category IDs
  636. * @return array Array of unique product IDs (including parent products with variants)
  637. */
  638. private function get_products_from_categories($category_ids) {
  639. global $wpdb;
  640. if (empty($category_ids)) {
  641. return array();
  642. }
  643. $placeholders = implode(',', array_fill(0, count($category_ids), '%d'));
  644. // Get all products from selected categories (both simple and parent products)
  645. $sql = "
  646. SELECT DISTINCT p.ID
  647. FROM {$wpdb->posts} p
  648. INNER JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id
  649. INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
  650. WHERE tt.term_id IN ($placeholders)
  651. AND tt.taxonomy = 'product_cat'
  652. AND p.post_type = 'product'
  653. AND p.post_status IN ('publish', 'private', 'draft', 'pending', 'trash')
  654. ";
  655. $products = $wpdb->get_col($wpdb->prepare($sql, $category_ids));
  656. if (defined('WP_DEBUG') && WP_DEBUG) {
  657. error_log('STUDIOU WC: Found ' . count($products) . ' products in categories ' . implode(', ', $category_ids));
  658. }
  659. return $products ? array_map('intval', $products) : array();
  660. }
  661. /**
  662. * Delete a batch of products and their variants
  663. *
  664. * @param array $product_ids Array of product IDs to delete
  665. * @return array Result with counts
  666. */
  667. private function delete_products_batch($product_ids) {
  668. $deleted_count = 0;
  669. $failed_count = 0;
  670. $failed_products = array();
  671. foreach ($product_ids as $product_id) {
  672. try {
  673. // Get the product object
  674. $product = wc_get_product($product_id);
  675. if (!$product) {
  676. $failed_count++;
  677. $failed_products[] = $product_id;
  678. if (defined('WP_DEBUG') && WP_DEBUG) {
  679. error_log('STUDIOU WC: Product ' . $product_id . ' not found');
  680. }
  681. continue;
  682. }
  683. // If it's a variable product, delete all variations first
  684. if ($product->is_type('variable')) {
  685. $variations = $product->get_children();
  686. if (defined('WP_DEBUG') && WP_DEBUG) {
  687. error_log('STUDIOU WC: Deleting ' . count($variations) . ' variations for product ' . $product_id);
  688. }
  689. foreach ($variations as $variation_id) {
  690. $variation = wc_get_product($variation_id);
  691. if ($variation) {
  692. $variation->delete(true); // true = force delete permanently
  693. }
  694. }
  695. }
  696. // Delete the product permanently
  697. $result = $product->delete(true); // true = force delete permanently
  698. if ($result) {
  699. $deleted_count++;
  700. if (defined('WP_DEBUG') && WP_DEBUG) {
  701. error_log('STUDIOU WC: Successfully deleted product ' . $product_id);
  702. }
  703. } else {
  704. $failed_count++;
  705. $failed_products[] = $product_id;
  706. if (defined('WP_DEBUG') && WP_DEBUG) {
  707. error_log('STUDIOU WC: Failed to delete product ' . $product_id);
  708. }
  709. }
  710. } catch (Exception $e) {
  711. $failed_count++;
  712. $failed_products[] = $product_id;
  713. if (defined('WP_DEBUG') && WP_DEBUG) {
  714. error_log('STUDIOU WC: Exception deleting product ' . $product_id . ': ' . $e->getMessage());
  715. }
  716. }
  717. }
  718. return array(
  719. 'deleted_count' => $deleted_count,
  720. 'failed_count' => $failed_count,
  721. 'failed_products' => $failed_products
  722. );
  723. }
  724. /**
  725. * Get all media categories with file counts for select lists
  726. *
  727. * @return array Array of media categories with ID, name, and file count
  728. */
  729. public function get_media_categories_with_counts() {
  730. $taxonomy = $this->get_media_category_taxonomy();
  731. if (!$taxonomy) {
  732. return array();
  733. }
  734. $args = array(
  735. 'taxonomy' => $taxonomy,
  736. 'orderby' => 'name',
  737. 'hide_empty' => false,
  738. );
  739. $categories = get_terms($args);
  740. $categories_with_counts = array();
  741. if (!is_wp_error($categories)) {
  742. foreach ($categories as $category) {
  743. $file_count = $this->get_media_category_file_count($category->term_id, $taxonomy);
  744. $categories_with_counts[] = array(
  745. 'id' => $category->term_id,
  746. 'name' => $category->name,
  747. 'count' => $file_count,
  748. 'display_name' => sprintf('%s (%d %s)', $category->name, $file_count, __('files', 'studiou-wc-product-cat-manage'))
  749. );
  750. }
  751. }
  752. return $categories_with_counts;
  753. }
  754. /**
  755. * Get the media category taxonomy name
  756. *
  757. * Checks for common media category taxonomies used by popular plugins
  758. *
  759. * @return string|false Taxonomy name or false if none found
  760. */
  761. private function get_media_category_taxonomy() {
  762. $possible_taxonomies = array(
  763. 'media_category',
  764. 'attachment_category',
  765. 'media-category',
  766. );
  767. foreach ($possible_taxonomies as $taxonomy) {
  768. if (taxonomy_exists($taxonomy)) {
  769. error_log('STUDIOU WC MEDIA: Detected media taxonomy: ' . $taxonomy);
  770. return $taxonomy;
  771. }
  772. }
  773. // Try to find any taxonomy registered for attachments
  774. $attachment_taxonomies = get_object_taxonomies('attachment', 'names');
  775. if (!empty($attachment_taxonomies)) {
  776. // Filter out built-in taxonomies
  777. $custom_taxonomies = array_filter($attachment_taxonomies, function($tax) {
  778. return !in_array($tax, array('post_tag', 'category', 'post_format'));
  779. });
  780. if (!empty($custom_taxonomies)) {
  781. $found = reset($custom_taxonomies);
  782. error_log('STUDIOU WC MEDIA: Auto-detected attachment taxonomy: ' . $found);
  783. return $found;
  784. }
  785. }
  786. error_log('STUDIOU WC MEDIA: No media category taxonomy found. Registered attachment taxonomies: ' . implode(', ', $attachment_taxonomies ?? array()));
  787. return false;
  788. }
  789. /**
  790. * Get file count for a media category
  791. *
  792. * @param int $category_id Category term ID
  793. * @param string $taxonomy Taxonomy name
  794. * @return int File count
  795. */
  796. private function get_media_category_file_count($category_id, $taxonomy) {
  797. global $wpdb;
  798. $sql = "
  799. SELECT COUNT(DISTINCT p.ID)
  800. FROM {$wpdb->posts} p
  801. INNER JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id
  802. INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
  803. WHERE tt.term_id = %d
  804. AND tt.taxonomy = %s
  805. AND p.post_type = 'attachment'
  806. ";
  807. $count = $wpdb->get_var($wpdb->prepare($sql, $category_id, $taxonomy));
  808. return intval($count);
  809. }
  810. /**
  811. * Get all media IDs from multiple media categories
  812. *
  813. * @param array $category_ids Array of category term IDs
  814. * @return array Array of unique attachment IDs
  815. */
  816. private function get_media_from_categories($category_ids) {
  817. global $wpdb;
  818. $taxonomy = $this->get_media_category_taxonomy();
  819. error_log('STUDIOU WC MEDIA: get_media_from_categories called - taxonomy: ' . ($taxonomy ?: 'false') . ', category_ids: ' . implode(', ', $category_ids));
  820. if (!$taxonomy || empty($category_ids)) {
  821. error_log('STUDIOU WC MEDIA: No taxonomy or empty category_ids, returning empty');
  822. return array();
  823. }
  824. $placeholders = implode(',', array_fill(0, count($category_ids), '%d'));
  825. $sql = "
  826. SELECT DISTINCT p.ID
  827. FROM {$wpdb->posts} p
  828. INNER JOIN {$wpdb->term_relationships} tr ON p.ID = tr.object_id
  829. INNER JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
  830. WHERE tt.term_id IN ($placeholders)
  831. AND tt.taxonomy = %s
  832. AND p.post_type = 'attachment'
  833. ";
  834. $params = array_merge($category_ids, array($taxonomy));
  835. $media = $wpdb->get_col($wpdb->prepare($sql, ...$params));
  836. error_log('STUDIOU WC MEDIA: Query found ' . ($media ? count($media) : 0) . ' media files');
  837. return $media ? array_map('intval', $media) : array();
  838. }
  839. /**
  840. * Delete a batch of media files permanently
  841. *
  842. * @param array $media_ids Array of attachment IDs to delete
  843. * @return array Result with counts
  844. */
  845. private function delete_media_batch($media_ids) {
  846. $deleted_count = 0;
  847. $failed_count = 0;
  848. $failed_media = array();
  849. $affected_term_ids = array();
  850. $taxonomy = $this->get_media_category_taxonomy();
  851. error_log('STUDIOU WC MEDIA: delete_media_batch called with ' . count($media_ids) . ' media IDs');
  852. foreach ($media_ids as $media_id) {
  853. try {
  854. $attachment = get_post($media_id);
  855. if (!$attachment || $attachment->post_type !== 'attachment') {
  856. $failed_count++;
  857. $failed_media[] = $media_id;
  858. error_log('STUDIOU WC MEDIA: Media file ' . $media_id . ' not found or not an attachment');
  859. continue;
  860. }
  861. // Collect affected term IDs before deletion for count update
  862. if ($taxonomy) {
  863. $terms = wp_get_object_terms($media_id, $taxonomy, array('fields' => 'ids'));
  864. if (!is_wp_error($terms)) {
  865. $affected_term_ids = array_merge($affected_term_ids, $terms);
  866. }
  867. }
  868. // Force delete attachment and its files from disk
  869. $result = wp_delete_attachment($media_id, true);
  870. if ($result) {
  871. $deleted_count++;
  872. error_log('STUDIOU WC MEDIA: Successfully deleted media file ' . $media_id);
  873. } else {
  874. $failed_count++;
  875. $failed_media[] = $media_id;
  876. error_log('STUDIOU WC MEDIA: Failed to delete media file ' . $media_id);
  877. }
  878. } catch (Exception $e) {
  879. $failed_count++;
  880. $failed_media[] = $media_id;
  881. error_log('STUDIOU WC MEDIA: Exception deleting media file ' . $media_id . ': ' . $e->getMessage());
  882. }
  883. }
  884. // Force update term counts for affected categories
  885. if ($taxonomy && !empty($affected_term_ids)) {
  886. $affected_term_ids = array_unique($affected_term_ids);
  887. wp_update_term_count_now($affected_term_ids, $taxonomy);
  888. error_log('STUDIOU WC MEDIA: Updated term counts for term IDs: ' . implode(', ', $affected_term_ids));
  889. }
  890. error_log('STUDIOU WC MEDIA: Batch result - deleted: ' . $deleted_count . ', failed: ' . $failed_count);
  891. return array(
  892. 'deleted_count' => $deleted_count,
  893. 'failed_count' => $failed_count,
  894. 'failed_media' => $failed_media
  895. );
  896. }
  897. /**
  898. * Handle AJAX clear media request (initial request to get media IDs)
  899. */
  900. public function handle_clear_media_ajax() {
  901. while (ob_get_level()) {
  902. ob_end_clean();
  903. }
  904. ob_start();
  905. $original_error_reporting = error_reporting();
  906. error_reporting(0);
  907. error_log('STUDIOU WC MEDIA: Clear media AJAX handler called');
  908. error_log('STUDIOU WC MEDIA: POST data: ' . print_r($_POST, true));
  909. try {
  910. if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'studiou-wcpcm-nonce')) {
  911. error_log('STUDIOU WC MEDIA: Nonce verification failed');
  912. wp_send_json_error(array(
  913. 'message' => __('Security check failed', 'studiou-wc-product-cat-manage')
  914. ));
  915. return;
  916. }
  917. if (!current_user_can('manage_woocommerce')) {
  918. error_log('STUDIOU WC MEDIA: Permission check failed');
  919. wp_send_json_error(array(
  920. 'message' => __('You do not have sufficient permissions', 'studiou-wc-product-cat-manage')
  921. ));
  922. return;
  923. }
  924. if (!isset($_POST['media_categories'])) {
  925. error_log('STUDIOU WC MEDIA: media_categories not in POST data');
  926. wp_send_json_error(array(
  927. 'message' => __('Missing required parameters', 'studiou-wc-product-cat-manage')
  928. ));
  929. return;
  930. }
  931. $category_ids = array_map('intval', $_POST['media_categories']);
  932. if (empty($category_ids)) {
  933. error_log('STUDIOU WC MEDIA: Empty category_ids after intval mapping');
  934. wp_send_json_error(array(
  935. 'message' => __('Please select at least one category', 'studiou-wc-product-cat-manage')
  936. ));
  937. return;
  938. }
  939. $media_ids = $this->get_media_from_categories($category_ids);
  940. error_log('STUDIOU WC MEDIA: Found ' . count($media_ids) . ' media files to delete from categories: ' . implode(', ', $category_ids));
  941. ob_clean();
  942. wp_send_json_success(array(
  943. 'media_ids' => $media_ids,
  944. 'total_count' => count($media_ids),
  945. 'message' => sprintf(
  946. __('Found %d media files to delete', 'studiou-wc-product-cat-manage'),
  947. count($media_ids)
  948. )
  949. ));
  950. } catch (Exception $e) {
  951. error_log('STUDIOU WC MEDIA: Clear media operation failed - ' . $e->getMessage());
  952. error_log('STUDIOU WC MEDIA: Exception trace: ' . $e->getTraceAsString());
  953. ob_clean();
  954. wp_send_json_error(array(
  955. 'message' => sprintf(
  956. __('Error during clear media operation: %s', 'studiou-wc-product-cat-manage'),
  957. $e->getMessage()
  958. )
  959. ));
  960. } finally {
  961. error_reporting($original_error_reporting);
  962. ob_end_clean();
  963. }
  964. }
  965. /**
  966. * Handle AJAX clear media batch request (processes media in batches)
  967. */
  968. public function handle_clear_media_batch_ajax() {
  969. while (ob_get_level()) {
  970. ob_end_clean();
  971. }
  972. ob_start();
  973. $original_error_reporting = error_reporting();
  974. error_reporting(0);
  975. error_log('STUDIOU WC MEDIA: Clear media batch AJAX handler called');
  976. try {
  977. if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'studiou-wcpcm-nonce')) {
  978. error_log('STUDIOU WC MEDIA: Batch nonce verification failed');
  979. wp_send_json_error(array(
  980. 'message' => __('Security check failed', 'studiou-wc-product-cat-manage')
  981. ));
  982. return;
  983. }
  984. if (!current_user_can('manage_woocommerce')) {
  985. error_log('STUDIOU WC MEDIA: Batch permission check failed');
  986. wp_send_json_error(array(
  987. 'message' => __('You do not have sufficient permissions', 'studiou-wc-product-cat-manage')
  988. ));
  989. return;
  990. }
  991. if (!isset($_POST['media_ids'])) {
  992. error_log('STUDIOU WC MEDIA: media_ids not in POST data');
  993. wp_send_json_error(array(
  994. 'message' => __('Missing required parameters', 'studiou-wc-product-cat-manage')
  995. ));
  996. return;
  997. }
  998. $media_ids = array_map('intval', $_POST['media_ids']);
  999. error_log('STUDIOU WC MEDIA: Processing batch of ' . count($media_ids) . ' media files for deletion');
  1000. $result = $this->delete_media_batch($media_ids);
  1001. error_log('STUDIOU WC MEDIA: Batch completed - Deleted: ' . $result['deleted_count'] . ', Failed: ' . $result['failed_count']);
  1002. ob_clean();
  1003. wp_send_json_success(array(
  1004. 'deleted_count' => $result['deleted_count'],
  1005. 'failed_count' => $result['failed_count'],
  1006. 'failed_media' => $result['failed_media']
  1007. ));
  1008. } catch (Exception $e) {
  1009. error_log('STUDIOU WC MEDIA: Clear media batch operation failed - ' . $e->getMessage());
  1010. error_log('STUDIOU WC MEDIA: Exception trace: ' . $e->getTraceAsString());
  1011. ob_clean();
  1012. wp_send_json_error(array(
  1013. 'message' => sprintf(
  1014. __('Error during clear media batch operation: %s', 'studiou-wc-product-cat-manage'),
  1015. $e->getMessage()
  1016. )
  1017. ));
  1018. } finally {
  1019. error_reporting($original_error_reporting);
  1020. ob_end_clean();
  1021. }
  1022. }
  1023. }