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

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