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

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