class-studiou-wc-product-cat-manage-db.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. <?php
  2. /**
  3. * Database operations class
  4. *
  5. * Handles database operations related to 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_DB {
  16. /**
  17. * Constructor
  18. */
  19. public function __construct() {
  20. }
  21. /**
  22. * Get all product categories
  23. *
  24. * @return array Array of product categories with all required properties
  25. */
  26. public function get_all_product_categories() {
  27. // Get all categories regardless of hierarchy, including empty ones
  28. $args = array(
  29. 'taxonomy' => 'product_cat',
  30. 'orderby' => 'term_id', // Order by ID to maintain creation order
  31. 'hide_empty' => false,
  32. 'hierarchical' => false, // Don't nest them, get a flat list
  33. 'get' => 'all', // Get all fields
  34. );
  35. $categories = get_terms($args);
  36. $formatted_categories = array();
  37. if (!is_wp_error($categories) && !empty($categories)) {
  38. // Sort by hierarchy: parent categories first, then children
  39. $sorted_categories = $this->sort_categories_by_hierarchy($categories);
  40. foreach ($sorted_categories as $category) {
  41. $formatted_categories[] = $this->format_category($category);
  42. }
  43. }
  44. return $formatted_categories;
  45. }
  46. /**
  47. * Sort categories by hierarchy - parents first, then children
  48. *
  49. * @param array $categories Array of WP_Term objects
  50. * @return array Sorted array of categories
  51. */
  52. private function sort_categories_by_hierarchy($categories) {
  53. $parents = array();
  54. $children = array();
  55. // Separate parents and children
  56. foreach ($categories as $category) {
  57. if ($category->parent == 0) {
  58. $parents[] = $category;
  59. } else {
  60. $children[] = $category;
  61. }
  62. }
  63. // Sort parents alphabetically
  64. usort($parents, function($a, $b) {
  65. return strcmp($a->name, $b->name);
  66. });
  67. // Recursively add children after their parents
  68. $sorted = array();
  69. foreach ($parents as $parent) {
  70. $sorted[] = $parent;
  71. $sorted = array_merge($sorted, $this->get_children_recursive($parent->term_id, $children));
  72. }
  73. // Add any orphaned children (categories with non-existent parents)
  74. foreach ($children as $child) {
  75. if (!$this->is_child_added($child, $sorted)) {
  76. $sorted[] = $child;
  77. }
  78. }
  79. return $sorted;
  80. }
  81. /**
  82. * Recursively get children of a category
  83. *
  84. * @param int $parent_id Parent category ID
  85. * @param array $all_children Array of all child categories
  86. * @return array Array of child categories
  87. */
  88. private function get_children_recursive($parent_id, $all_children) {
  89. $result = array();
  90. $direct_children = array();
  91. // Find direct children of this parent
  92. foreach ($all_children as $child) {
  93. if ($child->parent == $parent_id) {
  94. $direct_children[] = $child;
  95. }
  96. }
  97. // Sort direct children alphabetically
  98. usort($direct_children, function($a, $b) {
  99. return strcmp($a->name, $b->name);
  100. });
  101. // Add each child and its descendants
  102. foreach ($direct_children as $child) {
  103. $result[] = $child;
  104. $result = array_merge($result, $this->get_children_recursive($child->term_id, $all_children));
  105. }
  106. return $result;
  107. }
  108. /**
  109. * Check if a child category has already been added to the sorted array
  110. *
  111. * @param WP_Term $child Child category to check
  112. * @param array $sorted Array of already sorted categories
  113. * @return bool True if child is already in sorted array
  114. */
  115. private function is_child_added($child, $sorted) {
  116. foreach ($sorted as $category) {
  117. if ($category->term_id == $child->term_id) {
  118. return true;
  119. }
  120. }
  121. return false;
  122. }
  123. /**
  124. * Format category data
  125. *
  126. * @param object $category WP_Term object
  127. * @return array Formatted category data
  128. */
  129. private function format_category($category) {
  130. // Get parent category name
  131. $parent_name = '';
  132. if ($category->parent > 0) {
  133. $parent = get_term($category->parent, 'product_cat');
  134. if (!is_wp_error($parent)) {
  135. $parent_name = $parent->name;
  136. }
  137. }
  138. // Get display type
  139. $display_type = get_term_meta($category->term_id, 'display_type', true);
  140. if (empty($display_type)) {
  141. $display_type = 'default';
  142. }
  143. // Get protected category data
  144. $visibility = 'public';
  145. $protected_passwords = '';
  146. // Check if WooCommerce Protected Categories plugin is active
  147. // The debug shows the Barn2 Util class exists, so let's use it first
  148. if (class_exists('\\Barn2\\Plugin\\WC_Protected_Categories\\Util')) {
  149. try {
  150. $visibility_obj = \Barn2\Plugin\WC_Protected_Categories\Util::get_category_visibility($category->term_id);
  151. if ($visibility_obj && method_exists($visibility_obj, 'get_visibility')) {
  152. $visibility = $visibility_obj->get_visibility();
  153. // Get passwords using the utility method
  154. if ($visibility === 'protected') {
  155. $passwords = \Barn2\Plugin\WC_Protected_Categories\Util::get_term_passwords($category->term_id);
  156. if (!empty($passwords) && is_array($passwords)) {
  157. $protected_passwords = implode('|', $passwords);
  158. }
  159. }
  160. }
  161. } catch (Exception $e) {
  162. // Fallback to direct meta access if Util methods fail
  163. $visibility = 'public';
  164. $protected_passwords = '';
  165. }
  166. }
  167. // Fallback to direct meta access if the Util class didn't work
  168. if ($visibility === 'public') {
  169. // Get visibility from meta
  170. $visibility = get_term_meta($category->term_id, 'visibility', true);
  171. if (empty($visibility)) {
  172. $visibility = 'public';
  173. }
  174. // Get passwords if protected
  175. if ($visibility === 'protected') {
  176. $password_meta = get_term_meta($category->term_id, 'password', true);
  177. if (!empty($password_meta)) {
  178. // The debug shows passwords are stored as serialized arrays
  179. // like: a:1:{i:0;s:8:"jH7xK9pF";}
  180. // First, check if it's already an array (unserialized)
  181. if (is_array($password_meta)) {
  182. $passwords = $password_meta;
  183. } else {
  184. // If it's a string, try to unserialize it
  185. $passwords = maybe_unserialize($password_meta);
  186. }
  187. // Now extract the actual passwords
  188. if (is_array($passwords)) {
  189. // Filter out empty values and get the actual password strings
  190. $password_array = array();
  191. foreach ($passwords as $password) {
  192. if (!empty($password)) {
  193. $password_array[] = $password;
  194. }
  195. }
  196. if (!empty($password_array)) {
  197. $protected_passwords = implode('|', $password_array);
  198. }
  199. } elseif (is_string($passwords) && !empty($passwords)) {
  200. // If it's a simple string, use it directly
  201. $protected_passwords = $passwords;
  202. }
  203. }
  204. }
  205. }
  206. return array(
  207. 'name' => $category->name,
  208. 'url-name' => $category->slug,
  209. 'parent-name' => $parent_name,
  210. 'description' => $category->description,
  211. 'display-type' => $display_type,
  212. 'visibility' => $visibility,
  213. 'protected-passwords' => $protected_passwords,
  214. 'operation' => 'U' // Default operation for existing categories
  215. );
  216. }
  217. /**
  218. * Find category by name
  219. *
  220. * @param string $name Category name
  221. * @return WP_Term|null Category term object or null if not found
  222. */
  223. public function find_category_by_name($name) {
  224. $args = array(
  225. 'taxonomy' => 'product_cat',
  226. 'name' => $name,
  227. 'hide_empty' => false,
  228. );
  229. $categories = get_terms($args);
  230. if (!is_wp_error($categories) && !empty($categories)) {
  231. return $categories[0];
  232. }
  233. return null;
  234. }
  235. /**
  236. * Create product category
  237. *
  238. * @param array $category_data Category data
  239. * @return array Result with status and message
  240. */
  241. public function create_category($category_data) {
  242. // Check if category already exists
  243. $existing = $this->find_category_by_name($category_data['name']);
  244. if ($existing) {
  245. return array(
  246. 'status' => 'skipped',
  247. 'message' => sprintf(
  248. __("Product category '%s' already exists. Skipped.", 'studiou-wc-product-cat-manage'),
  249. $category_data['name']
  250. )
  251. );
  252. }
  253. // Find parent category ID if parent name is provided
  254. $parent_id = 0;
  255. if (!empty($category_data['parent-name'])) {
  256. $parent = $this->find_category_by_name($category_data['parent-name']);
  257. if ($parent) {
  258. $parent_id = $parent->term_id;
  259. } else {
  260. return array(
  261. 'status' => 'error',
  262. 'message' => sprintf(
  263. __("Parent category '%s' not found.", 'studiou-wc-product-cat-manage'),
  264. $category_data['parent-name']
  265. )
  266. );
  267. }
  268. }
  269. // Create category
  270. $args = array(
  271. 'description' => $category_data['description'],
  272. 'parent' => $parent_id,
  273. 'slug' => $category_data['url-name'],
  274. );
  275. $result = wp_insert_term($category_data['name'], 'product_cat', $args);
  276. if (is_wp_error($result)) {
  277. return array(
  278. 'status' => 'error',
  279. 'message' => $result->get_error_message()
  280. );
  281. }
  282. $term_id = $result['term_id'];
  283. // Set display type
  284. update_term_meta($term_id, 'display_type', $category_data['display-type']);
  285. // Set visibility and password protection if WC Protected Categories is active
  286. if (class_exists('WC_Protected_Categories') || function_exists('wc_protected_categories')) {
  287. // Set visibility
  288. update_term_meta($term_id, 'visibility', $category_data['visibility']);
  289. // Set password protection if visibility is protected and passwords are provided
  290. if ($category_data['visibility'] === 'protected' && !empty($category_data['protected-passwords'])) {
  291. $passwords = explode('|', $category_data['protected-passwords']);
  292. // Filter out empty passwords
  293. $passwords = array_filter($passwords);
  294. if (empty($passwords)) {
  295. // If no valid passwords after filtering, set a default one
  296. $passwords = ['password123'];
  297. }
  298. // Store the passwords array as a single meta entry
  299. update_term_meta($term_id, 'password', $passwords);
  300. }
  301. }
  302. return array(
  303. 'status' => 'created',
  304. 'message' => sprintf(
  305. __("Product category '%s' created.", 'studiou-wc-product-cat-manage'),
  306. $category_data['name']
  307. )
  308. );
  309. }
  310. /**
  311. * Update product category
  312. *
  313. * @param array $category_data Category data
  314. * @return array Result with status and message
  315. */
  316. public function update_category($category_data) {
  317. // Check if category exists
  318. $existing = $this->find_category_by_name($category_data['name']);
  319. if (!$existing) {
  320. return array(
  321. 'status' => 'error',
  322. 'message' => sprintf(
  323. __("Product category '%s' not found.", 'studiou-wc-product-cat-manage'),
  324. $category_data['name']
  325. )
  326. );
  327. }
  328. // M5 (v1.6.2) — tri-state parent handling on update:
  329. // * blank `parent-name` → leave the existing parent untouched
  330. // (previously silently re-parented to root)
  331. // * literal `__ROOT__` → explicitly move to root
  332. // * any other non-blank name → resolve and set as before
  333. // `parent-name` is still a required header; only the value semantics
  334. // change on the update path. `A` (add) still treats blank as root,
  335. // since a brand-new category has nothing to "leave alone."
  336. $raw_parent = isset($category_data['parent-name']) ? trim($category_data['parent-name']) : '';
  337. $parent_provided = ($raw_parent !== '');
  338. $parent_id = 0;
  339. if ($parent_provided) {
  340. if ($raw_parent === '__ROOT__') {
  341. $parent_id = 0;
  342. } else {
  343. $parent = $this->find_category_by_name($raw_parent);
  344. if ($parent) {
  345. $parent_id = $parent->term_id;
  346. } else {
  347. return array(
  348. 'status' => 'error',
  349. 'message' => sprintf(
  350. __("Parent category '%s' not found.", 'studiou-wc-product-cat-manage'),
  351. $raw_parent
  352. )
  353. );
  354. }
  355. }
  356. }
  357. // Update category — only include `parent` in the args when the CSV
  358. // actually asked us to manage it. Otherwise wp_update_term would
  359. // silently re-parent every updated child to root on any partial CSV.
  360. $args = array(
  361. 'description' => $category_data['description'],
  362. 'slug' => $category_data['url-name'],
  363. );
  364. if ($parent_provided) {
  365. $args['parent'] = $parent_id;
  366. }
  367. $result = wp_update_term($existing->term_id, 'product_cat', $args);
  368. if (is_wp_error($result)) {
  369. return array(
  370. 'status' => 'error',
  371. 'message' => $result->get_error_message()
  372. );
  373. }
  374. // Set display type
  375. update_term_meta($existing->term_id, 'display_type', $category_data['display-type']);
  376. // Set visibility and password protection if WC Protected Categories is active
  377. if (class_exists('WC_Protected_Categories') || function_exists('wc_protected_categories')) {
  378. // First remove existing protection meta
  379. delete_term_meta($existing->term_id, 'password');
  380. delete_term_meta($existing->term_id, 'user_roles');
  381. delete_term_meta($existing->term_id, 'users');
  382. // Set visibility
  383. update_term_meta($existing->term_id, 'visibility', $category_data['visibility']);
  384. // Set password protection if visibility is protected and passwords are provided
  385. if ($category_data['visibility'] === 'protected' && !empty($category_data['protected-passwords'])) {
  386. $passwords = explode('|', $category_data['protected-passwords']);
  387. // Filter out empty passwords
  388. $passwords = array_filter($passwords);
  389. if (empty($passwords)) {
  390. // If no valid passwords after filtering, set a default one
  391. $passwords = ['password123'];
  392. }
  393. // Store the passwords array as a single meta entry
  394. update_term_meta($existing->term_id, 'password', $passwords);
  395. }
  396. }
  397. return array(
  398. 'status' => 'updated',
  399. 'message' => sprintf(
  400. __("Product category '%s' updated.", 'studiou-wc-product-cat-manage'),
  401. $category_data['name']
  402. )
  403. );
  404. }
  405. /**
  406. * Delete product category
  407. *
  408. * @param string $category_name Category name
  409. * @return array Result with status and message
  410. */
  411. public function delete_category($category_name) {
  412. // Check if category exists
  413. $existing = $this->find_category_by_name($category_name);
  414. if (!$existing) {
  415. return array(
  416. 'status' => 'error',
  417. 'message' => sprintf(
  418. __("Product category '%s' not found.", 'studiou-wc-product-cat-manage'),
  419. $category_name
  420. )
  421. );
  422. }
  423. // Delete category
  424. $result = wp_delete_term($existing->term_id, 'product_cat');
  425. if (is_wp_error($result)) {
  426. return array(
  427. 'status' => 'error',
  428. 'message' => $result->get_error_message()
  429. );
  430. }
  431. return array(
  432. 'status' => 'deleted',
  433. 'message' => sprintf(
  434. __("Product category '%s' deleted.", 'studiou-wc-product-cat-manage'),
  435. $category_name
  436. )
  437. );
  438. }
  439. }