/includes/api/legacy/v2/class-wc-api-products.php

  1. <?php 
  2. /** 
  3. * WooCommerce API Products Class 
  4. * 
  5. * Handles requests to the /products endpoint 
  6. * 
  7. * @author WooThemes 
  8. * @category API 
  9. * @package WooCommerce/API 
  10. * @since 2.1 
  11. * @version 3.0 
  12. */ 
  13.  
  14. if ( ! defined( 'ABSPATH' ) ) { 
  15. exit; // Exit if accessed directly 
  16.  
  17. class WC_API_Products extends WC_API_Resource { 
  18.  
  19. /** @var string $base the route base */ 
  20. protected $base = '/products'; 
  21.  
  22. /** 
  23. * Register the routes for this class 
  24. * 
  25. * GET/POST /products 
  26. * GET /products/count 
  27. * GET/PUT/DELETE /products/<id> 
  28. * GET /products/<id>/reviews 
  29. * 
  30. * @since 2.1 
  31. * @param array $routes 
  32. * @return array 
  33. */ 
  34. public function register_routes( $routes ) { 
  35.  
  36. # GET/POST /products 
  37. $routes[ $this->base ] = array( 
  38. array( array( $this, 'get_products' ), WC_API_Server::READABLE ),  
  39. array( array( $this, 'create_product' ), WC_API_SERVER::CREATABLE | WC_API_Server::ACCEPT_DATA ),  
  40. ); 
  41.  
  42. # GET /products/count 
  43. $routes[ $this->base . '/count' ] = array( 
  44. array( array( $this, 'get_products_count' ), WC_API_Server::READABLE ),  
  45. ); 
  46.  
  47. # GET/PUT/DELETE /products/<id> 
  48. $routes[ $this->base . '/(?P<id>\d+)' ] = array( 
  49. array( array( $this, 'get_product' ), WC_API_Server::READABLE ),  
  50. array( array( $this, 'edit_product' ), WC_API_Server::EDITABLE | WC_API_Server::ACCEPT_DATA ),  
  51. array( array( $this, 'delete_product' ), WC_API_Server::DELETABLE ),  
  52. ); 
  53.  
  54. # GET /products/<id>/reviews 
  55. $routes[ $this->base . '/(?P<id>\d+)/reviews' ] = array( 
  56. array( array( $this, 'get_product_reviews' ), WC_API_Server::READABLE ),  
  57. ); 
  58.  
  59. # GET /products/<id>/orders 
  60. $routes[ $this->base . '/(?P<id>\d+)/orders' ] = array( 
  61. array( array( $this, 'get_product_orders' ), WC_API_Server::READABLE ),  
  62. ); 
  63.  
  64. # GET /products/categories 
  65. $routes[ $this->base . '/categories' ] = array( 
  66. array( array( $this, 'get_product_categories' ), WC_API_Server::READABLE ),  
  67. ); 
  68.  
  69. # GET /products/categories/<id> 
  70. $routes[ $this->base . '/categories/(?P<id>\d+)' ] = array( 
  71. array( array( $this, 'get_product_category' ), WC_API_Server::READABLE ),  
  72. ); 
  73.  
  74. # GET/POST /products/attributes 
  75. $routes[ $this->base . '/attributes' ] = array( 
  76. array( array( $this, 'get_product_attributes' ), WC_API_Server::READABLE ),  
  77. array( array( $this, 'create_product_attribute' ), WC_API_SERVER::CREATABLE | WC_API_Server::ACCEPT_DATA ),  
  78. ); 
  79.  
  80. # GET/PUT/DELETE /attributes/<id> 
  81. $routes[ $this->base . '/attributes/(?P<id>\d+)' ] = array( 
  82. array( array( $this, 'get_product_attribute' ), WC_API_Server::READABLE ),  
  83. array( array( $this, 'edit_product_attribute' ), WC_API_Server::EDITABLE | WC_API_Server::ACCEPT_DATA ),  
  84. array( array( $this, 'delete_product_attribute' ), WC_API_Server::DELETABLE ),  
  85. ); 
  86.  
  87. # GET /products/sku/<product sku> 
  88. $routes[ $this->base . '/sku/(?P<sku>\w[\w\s\-]*)' ] = array( 
  89. array( array( $this, 'get_product_by_sku' ), WC_API_Server::READABLE ),  
  90. ); 
  91.  
  92. # POST|PUT /products/bulk 
  93. $routes[ $this->base . '/bulk' ] = array( 
  94. array( array( $this, 'bulk' ), WC_API_Server::EDITABLE | WC_API_Server::ACCEPT_DATA ),  
  95. ); 
  96.  
  97. return $routes; 
  98.  
  99. /** 
  100. * Get all products 
  101. * 
  102. * @since 2.1 
  103. * @param string $fields 
  104. * @param string $type 
  105. * @param array $filter 
  106. * @param int $page 
  107. * @return array 
  108. */ 
  109. public function get_products( $fields = null, $type = null, $filter = array(), $page = 1 ) { 
  110.  
  111. if ( ! empty( $type ) ) { 
  112. $filter['type'] = $type; 
  113.  
  114. $filter['page'] = $page; 
  115.  
  116. $query = $this->query_products( $filter ); 
  117.  
  118. $products = array(); 
  119.  
  120. foreach ( $query->posts as $product_id ) { 
  121.  
  122. if ( ! $this->is_readable( $product_id ) ) { 
  123. continue; 
  124.  
  125. $products[] = current( $this->get_product( $product_id, $fields ) ); 
  126.  
  127. $this->server->add_pagination_headers( $query ); 
  128.  
  129. return array( 'products' => $products ); 
  130.  
  131. /** 
  132. * Get the product for the given ID 
  133. * 
  134. * @since 2.1 
  135. * @param int $id the product ID 
  136. * @param string $fields 
  137. * @return array 
  138. */ 
  139. public function get_product( $id, $fields = null ) { 
  140.  
  141. $id = $this->validate_request( $id, 'product', 'read' ); 
  142.  
  143. if ( is_wp_error( $id ) ) { 
  144. return $id; 
  145.  
  146. $product = wc_get_product( $id ); 
  147.  
  148. // add data that applies to every product type 
  149. $product_data = $this->get_product_data( $product ); 
  150.  
  151. // add variations to variable products 
  152. if ( $product->is_type( 'variable' ) && $product->has_child() ) { 
  153. $product_data['variations'] = $this->get_variation_data( $product ); 
  154.  
  155. // add the parent product data to an individual variation 
  156. if ( $product->is_type( 'variation' ) && $product->get_parent_id() ) { 
  157. $_product = wc_get_product( $product->get_parent_id() ); 
  158. $product_data['parent'] = $this->get_product_data( $_product ); 
  159.  
  160. return array( 'product' => apply_filters( 'woocommerce_api_product_response', $product_data, $product, $fields, $this->server ) ); 
  161.  
  162. /** 
  163. * Get the total number of products 
  164. * 
  165. * @since 2.1 
  166. * @param string $type 
  167. * @param array $filter 
  168. * @return array 
  169. */ 
  170. public function get_products_count( $type = null, $filter = array() ) { 
  171. try { 
  172. if ( ! current_user_can( 'read_private_products' ) ) { 
  173. throw new WC_API_Exception( 'woocommerce_api_user_cannot_read_products_count', __( 'You do not have permission to read the products count', 'woocommerce' ), 401 ); 
  174.  
  175. if ( ! empty( $type ) ) { 
  176. $filter['type'] = $type; 
  177.  
  178. $query = $this->query_products( $filter ); 
  179.  
  180. return array( 'count' => (int) $query->found_posts ); 
  181. } catch ( WC_API_Exception $e ) { 
  182. return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) ); 
  183.  
  184. /** 
  185. * Create a new product 
  186. * 
  187. * @since 2.2 
  188. * @param array $data posted data 
  189. * @return array 
  190. */ 
  191. public function create_product( $data ) { 
  192. $id = 0; 
  193.  
  194. try { 
  195. if ( ! isset( $data['product'] ) ) { 
  196. throw new WC_API_Exception( 'woocommerce_api_missing_product_data', sprintf( __( 'No %1$s data specified to create %1$s', 'woocommerce' ), 'product' ), 400 ); 
  197.  
  198. $data = $data['product']; 
  199.  
  200. // Check permissions 
  201. if ( ! current_user_can( 'publish_products' ) ) { 
  202. throw new WC_API_Exception( 'woocommerce_api_user_cannot_create_product', __( 'You do not have permission to create products', 'woocommerce' ), 401 ); 
  203.  
  204. $data = apply_filters( 'woocommerce_api_create_product_data', $data, $this ); 
  205.  
  206. // Check if product title is specified 
  207. if ( ! isset( $data['title'] ) ) { 
  208. throw new WC_API_Exception( 'woocommerce_api_missing_product_title', sprintf( __( 'Missing parameter %s', 'woocommerce' ), 'title' ), 400 ); 
  209.  
  210. // Check product type 
  211. if ( ! isset( $data['type'] ) ) { 
  212. $data['type'] = 'simple'; 
  213.  
  214. // Set visible visibility when not sent 
  215. if ( ! isset( $data['catalog_visibility'] ) ) { 
  216. $data['catalog_visibility'] = 'visible'; 
  217.  
  218. // Validate the product type 
  219. if ( ! in_array( wc_clean( $data['type'] ), array_keys( wc_get_product_types() ) ) ) { 
  220. throw new WC_API_Exception( 'woocommerce_api_invalid_product_type', sprintf( __( 'Invalid product type - the product type must be any of these: %s', 'woocommerce' ), implode( ', ', array_keys( wc_get_product_types() ) ) ), 400 ); 
  221.  
  222. // Enable description html tags. 
  223. $post_content = isset( $data['description'] ) ? wc_clean( $data['description'] ) : ''; 
  224. if ( $post_content && isset( $data['enable_html_description'] ) && true === $data['enable_html_description'] ) { 
  225.  
  226. $post_content = $data['description']; 
  227.  
  228. // Enable short description html tags. 
  229. $post_excerpt = isset( $data['short_description'] ) ? wc_clean( $data['short_description'] ) : ''; 
  230. if ( $post_excerpt && isset( $data['enable_html_short_description'] ) && true === $data['enable_html_short_description'] ) { 
  231. $post_excerpt = $data['short_description']; 
  232.  
  233. $classname = WC_Product_Factory::get_classname_from_product_type( $data['type'] ); 
  234. if ( ! class_exists( $classname ) ) { 
  235. $classname = 'WC_Product_Simple'; 
  236. $product = new $classname(); 
  237.  
  238. $product->set_name( wc_clean( $data['title'] ) ); 
  239. $product->set_status( isset( $data['status'] ) ? wc_clean( $data['status'] ) : 'publish' ); 
  240. $product->set_short_description( isset( $data['short_description'] ) ? $post_excerpt : '' ); 
  241. $product->set_description( isset( $data['description'] ) ? $post_content : '' ); 
  242.  
  243. // Attempts to create the new product. 
  244. $product->save(); 
  245. $id = $product->get_id(); 
  246.  
  247. // Checks for an error in the product creation 
  248. if ( 0 >= $id ) { 
  249. throw new WC_API_Exception( 'woocommerce_api_cannot_create_product', $id->get_error_message(), 400 ); 
  250.  
  251. // Check for featured/gallery images, upload it and set it 
  252. if ( isset( $data['images'] ) ) { 
  253. $product = $this->save_product_images( $product, $data['images'] ); 
  254.  
  255. // Save product meta fields 
  256. $product = $this->save_product_meta( $product, $data ); 
  257. $product->save(); 
  258.  
  259. // Save variations 
  260. if ( isset( $data['type'] ) && 'variable' == $data['type'] && isset( $data['variations'] ) && is_array( $data['variations'] ) ) { 
  261. $this->save_variations( $product, $data ); 
  262.  
  263. do_action( 'woocommerce_api_create_product', $id, $data ); 
  264.  
  265. // Clear cache/transients 
  266. wc_delete_product_transients( $id ); 
  267.  
  268. $this->server->send_status( 201 ); 
  269.  
  270. return $this->get_product( $id ); 
  271. } catch ( WC_Data_Exception $e ) { 
  272. $this->clear_product( $id ); 
  273. return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) ); 
  274. } catch ( WC_API_Exception $e ) { 
  275. $this->clear_product( $id ); 
  276. return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) ); 
  277.  
  278. /** 
  279. * Edit a product 
  280. * 
  281. * @since 2.2 
  282. * @param int $id the product ID 
  283. * @param array $data 
  284. * @return array 
  285. */ 
  286. public function edit_product( $id, $data ) { 
  287. try { 
  288. if ( ! isset( $data['product'] ) ) { 
  289. throw new WC_API_Exception( 'woocommerce_api_missing_product_data', sprintf( __( 'No %1$s data specified to edit %1$s', 'woocommerce' ), 'product' ), 400 ); 
  290.  
  291. $data = $data['product']; 
  292.  
  293. $id = $this->validate_request( $id, 'product', 'edit' ); 
  294.  
  295. if ( is_wp_error( $id ) ) { 
  296. return $id; 
  297.  
  298. $product = wc_get_product( $id ); 
  299.  
  300. $data = apply_filters( 'woocommerce_api_edit_product_data', $data, $this ); 
  301.  
  302. // Product title. 
  303. if ( isset( $data['title'] ) ) { 
  304. $product->set_name( wc_clean( $data['title'] ) ); 
  305.  
  306. // Product name (slug). 
  307. if ( isset( $data['name'] ) ) { 
  308. $product->set_slug( wc_clean( $data['name'] ) ); 
  309.  
  310. // Product status. 
  311. if ( isset( $data['status'] ) ) { 
  312. $product->set_status( wc_clean( $data['status'] ) ); 
  313.  
  314. // Product short description. 
  315. if ( isset( $data['short_description'] ) ) { 
  316. // Enable short description html tags. 
  317. $post_excerpt = ( isset( $data['enable_html_short_description'] ) && true === $data['enable_html_short_description'] ) ? $data['short_description'] : wc_clean( $data['short_description'] ); 
  318. $product->set_short_description( $post_excerpt ); 
  319.  
  320. // Product description. 
  321. if ( isset( $data['description'] ) ) { 
  322. // Enable description html tags. 
  323. $post_content = ( isset( $data['enable_html_description'] ) && true === $data['enable_html_description'] ) ? $data['description'] : wc_clean( $data['description'] ); 
  324. $product->set_description( $post_content ); 
  325.  
  326. // Validate the product type
  327. if ( isset( $data['type'] ) && ! in_array( wc_clean( $data['type'] ), array_keys( wc_get_product_types() ) ) ) { 
  328. throw new WC_API_Exception( 'woocommerce_api_invalid_product_type', sprintf( __( 'Invalid product type - the product type must be any of these: %s', 'woocommerce' ), implode( ', ', array_keys( wc_get_product_types() ) ) ), 400 ); 
  329.  
  330. // Check for featured/gallery images, upload it and set it
  331. if ( isset( $data['images'] ) ) { 
  332. $product = $this->save_product_images( $product, $data['images'] ); 
  333.  
  334. // Save product meta fields
  335. $product = $this->save_product_meta( $product, $data ); 
  336.  
  337. // Save variations
  338. if ( $product->is_type( 'variable' ) ) { 
  339. if ( isset( $data['variations'] ) && is_array( $data['variations'] ) ) { 
  340. $this->save_variations( $product, $data ); 
  341. } else { 
  342. // Just sync variations. 
  343. $product = WC_Product_Variable::sync( $product, false ); 
  344.  
  345. $product->save(); 
  346.  
  347. do_action( 'woocommerce_api_edit_product', $id, $data ); 
  348.  
  349. // Clear cache/transients
  350. wc_delete_product_transients( $id ); 
  351.  
  352. return $this->get_product( $id ); 
  353. } catch ( WC_Data_Exception $e ) { 
  354. return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) ); 
  355. } catch ( WC_API_Exception $e ) { 
  356. return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) ); 
  357.  
  358. /** 
  359. * Delete a product. 
  360. * 
  361. * @since 2.2 
  362. * @param int $id the product ID. 
  363. * @param bool $force true to permanently delete order, false to move to trash. 
  364. * @return array 
  365. */ 
  366. public function delete_product( $id, $force = false ) { 
  367.  
  368. $id = $this->validate_request( $id, 'product', 'delete' ); 
  369.  
  370. if ( is_wp_error( $id ) ) { 
  371. return $id; 
  372.  
  373. $product = wc_get_product( $id ); 
  374.  
  375. do_action( 'woocommerce_api_delete_product', $id, $this ); 
  376.  
  377. // If we're forcing, then delete permanently. 
  378. if ( $force ) { 
  379. if ( $product->is_type( 'variable' ) ) { 
  380. foreach ( $product->get_children() as $child_id ) { 
  381. $child = wc_get_product( $child_id ); 
  382. $child->delete( true ); 
  383. } elseif ( $product->is_type( 'grouped' ) ) { 
  384. foreach ( $product->get_children() as $child_id ) { 
  385. $child = wc_get_product( $child_id ); 
  386. $child->set_parent_id( 0 ); 
  387. $child->save(); 
  388.  
  389. $product->delete( true ); 
  390. $result = $product->get_id() > 0 ? false : true; 
  391. } else { 
  392. $product->delete(); 
  393. $result = 'trash' === $product->get_status(); 
  394.  
  395. if ( ! $result ) { 
  396. return new WP_Error( 'woocommerce_api_cannot_delete_product', sprintf( __( 'This %s cannot be deleted', 'woocommerce' ), 'product' ), array( 'status' => 500 ) ); 
  397.  
  398. // Delete parent product transients. 
  399. if ( $parent_id = wp_get_post_parent_id( $id ) ) { 
  400. wc_delete_product_transients( $parent_id ); 
  401.  
  402. if ( $force ) { 
  403. return array( 'message' => sprintf( __( 'Permanently deleted %s', 'woocommerce' ), 'product' ) ); 
  404. } else { 
  405. $this->server->send_status( '202' ); 
  406.  
  407. return array( 'message' => sprintf( __( 'Deleted %s', 'woocommerce' ), 'product' ) ); 
  408.  
  409. /** 
  410. * Get the reviews for a product 
  411. * 
  412. * @since 2.1 
  413. * @param int $id the product ID to get reviews for 
  414. * @param string $fields fields to include in response 
  415. * @return array 
  416. */ 
  417. public function get_product_reviews( $id, $fields = null ) { 
  418.  
  419. $id = $this->validate_request( $id, 'product', 'read' ); 
  420.  
  421. if ( is_wp_error( $id ) ) { 
  422. return $id; 
  423.  
  424. $comments = get_approved_comments( $id ); 
  425. $reviews = array(); 
  426.  
  427. foreach ( $comments as $comment ) { 
  428.  
  429. $reviews[] = array( 
  430. 'id' => intval( $comment->comment_ID ),  
  431. 'created_at' => $this->server->format_datetime( $comment->comment_date_gmt ),  
  432. 'review' => $comment->comment_content,  
  433. 'rating' => get_comment_meta( $comment->comment_ID, 'rating', true ),  
  434. 'reviewer_name' => $comment->comment_author,  
  435. 'reviewer_email' => $comment->comment_author_email,  
  436. 'verified' => wc_review_is_from_verified_owner( $comment->comment_ID ),  
  437. ); 
  438.  
  439. return array( 'product_reviews' => apply_filters( 'woocommerce_api_product_reviews_response', $reviews, $id, $fields, $comments, $this->server ) ); 
  440.  
  441. /** 
  442. * Get the orders for a product 
  443. * 
  444. * @since 2.4.0 
  445. * @param int $id the product ID to get orders for 
  446. * @param string fields fields to retrieve 
  447. * @param string $filter filters to include in response 
  448. * @param string $status the order status to retrieve 
  449. * @param $page $page page to retrieve 
  450. * @return array 
  451. */ 
  452. public function get_product_orders( $id, $fields = null, $filter = array(), $status = null, $page = 1 ) { 
  453. global $wpdb; 
  454.  
  455. $id = $this->validate_request( $id, 'product', 'read' ); 
  456.  
  457. if ( is_wp_error( $id ) ) { 
  458. return $id; 
  459.  
  460. $order_ids = $wpdb->get_col( $wpdb->prepare( " 
  461. SELECT order_id 
  462. FROM {$wpdb->prefix}woocommerce_order_items 
  463. WHERE order_item_id IN ( SELECT order_item_id FROM {$wpdb->prefix}woocommerce_order_itemmeta WHERE meta_key = '_product_id' AND meta_value = %d ) 
  464. AND order_item_type = 'line_item' 
  465. ", $id ) ); 
  466.  
  467. if ( empty( $order_ids ) ) { 
  468. return array( 'orders' => array() ); 
  469.  
  470. $filter = array_merge( $filter, array( 
  471. 'in' => implode( ', ', $order_ids ),  
  472. ) ); 
  473.  
  474. $orders = WC()->api->WC_API_Orders->get_orders( $fields, $filter, $status, $page ); 
  475.  
  476. return array( 'orders' => apply_filters( 'woocommerce_api_product_orders_response', $orders['orders'], $id, $filter, $fields, $this->server ) ); 
  477.  
  478. /** 
  479. * Get a listing of product categories 
  480. * 
  481. * @since 2.2 
  482. * @param string|null $fields fields to limit response to 
  483. * @return array 
  484. */ 
  485. public function get_product_categories( $fields = null ) { 
  486. try { 
  487. // Permissions check 
  488. if ( ! current_user_can( 'manage_product_terms' ) ) { 
  489. throw new WC_API_Exception( 'woocommerce_api_user_cannot_read_product_categories', __( 'You do not have permission to read product categories', 'woocommerce' ), 401 ); 
  490.  
  491. $product_categories = array(); 
  492.  
  493. $terms = get_terms( 'product_cat', array( 'hide_empty' => false, 'fields' => 'ids' ) ); 
  494.  
  495. foreach ( $terms as $term_id ) { 
  496. $product_categories[] = current( $this->get_product_category( $term_id, $fields ) ); 
  497.  
  498. return array( 'product_categories' => apply_filters( 'woocommerce_api_product_categories_response', $product_categories, $terms, $fields, $this ) ); 
  499. } catch ( WC_API_Exception $e ) { 
  500. return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) ); 
  501.  
  502. /** 
  503. * Get the product category for the given ID 
  504. * 
  505. * @since 2.2 
  506. * @param string $id product category term ID 
  507. * @param string|null $fields fields to limit response to 
  508. * @return array 
  509. */ 
  510. public function get_product_category( $id, $fields = null ) { 
  511. try { 
  512. $id = absint( $id ); 
  513.  
  514. // Validate ID 
  515. if ( empty( $id ) ) { 
  516. throw new WC_API_Exception( 'woocommerce_api_invalid_product_category_id', __( 'Invalid product category ID', 'woocommerce' ), 400 ); 
  517.  
  518. // Permissions check 
  519. if ( ! current_user_can( 'manage_product_terms' ) ) { 
  520. throw new WC_API_Exception( 'woocommerce_api_user_cannot_read_product_categories', __( 'You do not have permission to read product categories', 'woocommerce' ), 401 ); 
  521.  
  522. $term = get_term( $id, 'product_cat' ); 
  523.  
  524. if ( is_wp_error( $term ) || is_null( $term ) ) { 
  525. throw new WC_API_Exception( 'woocommerce_api_invalid_product_category_id', __( 'A product category with the provided ID could not be found', 'woocommerce' ), 404 ); 
  526.  
  527. $term_id = intval( $term->term_id ); 
  528.  
  529. // Get category display type 
  530. $display_type = get_woocommerce_term_meta( $term_id, 'display_type' ); 
  531.  
  532. // Get category image 
  533. $image = ''; 
  534. if ( $image_id = get_woocommerce_term_meta( $term_id, 'thumbnail_id' ) ) { 
  535. $image = wp_get_attachment_url( $image_id ); 
  536.  
  537. $product_category = array( 
  538. 'id' => $term_id,  
  539. 'name' => $term->name,  
  540. 'slug' => $term->slug,  
  541. 'parent' => $term->parent,  
  542. 'description' => $term->description,  
  543. 'display' => $display_type ? $display_type : 'default',  
  544. 'image' => $image ? esc_url( $image ) : '',  
  545. 'count' => intval( $term->count ),  
  546. ); 
  547.  
  548. return array( 'product_category' => apply_filters( 'woocommerce_api_product_category_response', $product_category, $id, $fields, $term, $this ) ); 
  549. } catch ( WC_API_Exception $e ) { 
  550. return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) ); 
  551.  
  552. /** 
  553. * Helper method to get product post objects 
  554. * 
  555. * @since 2.1 
  556. * @param array $args request arguments for filtering query 
  557. * @return WP_Query 
  558. */ 
  559. private function query_products( $args ) { 
  560.  
  561. // Set base query arguments 
  562. $query_args = array( 
  563. 'fields' => 'ids',  
  564. 'post_type' => 'product',  
  565. 'post_status' => 'publish',  
  566. 'meta_query' => array(),  
  567. ); 
  568.  
  569. if ( ! empty( $args['type'] ) ) { 
  570.  
  571. $types = explode( ', ', $args['type'] ); 
  572.  
  573. $query_args['tax_query'] = array( 
  574. array( 
  575. 'taxonomy' => 'product_type',  
  576. 'field' => 'slug',  
  577. 'terms' => $types,  
  578. ),  
  579. ); 
  580.  
  581. unset( $args['type'] ); 
  582.  
  583. // Filter products by category 
  584. if ( ! empty( $args['category'] ) ) { 
  585. $query_args['product_cat'] = $args['category']; 
  586.  
  587. // Filter by specific sku 
  588. if ( ! empty( $args['sku'] ) ) { 
  589. if ( ! is_array( $query_args['meta_query'] ) ) { 
  590. $query_args['meta_query'] = array(); 
  591.  
  592. $query_args['meta_query'][] = array( 
  593. 'key' => '_sku',  
  594. 'value' => $args['sku'],  
  595. 'compare' => '=',  
  596. ); 
  597.  
  598. $query_args['post_type'] = array( 'product', 'product_variation' ); 
  599.  
  600. $query_args = $this->merge_query_args( $query_args, $args ); 
  601.  
  602. return new WP_Query( $query_args ); 
  603.  
  604. /** 
  605. * Get standard product data that applies to every product type 
  606. * 
  607. * @since 2.1 
  608. * @param WC_Product|int $product 
  609. * @return WC_Product 
  610. */ 
  611. private function get_product_data( $product ) { 
  612. if ( is_numeric( $product ) ) { 
  613. $product = wc_get_product( $product ); 
  614.  
  615. $prices_precision = wc_get_price_decimals(); 
  616. return array( 
  617. 'title' => $product->get_name(),  
  618. 'id' => $product->get_id(),  
  619. 'created_at' => $this->server->format_datetime( $product->get_date_created(), false, true ),  
  620. 'updated_at' => $this->server->format_datetime( $product->get_date_modified(), false, true ),  
  621. 'type' => $product->get_type(),  
  622. 'status' => $product->get_status(),  
  623. 'downloadable' => $product->is_downloadable(),  
  624. 'virtual' => $product->is_virtual(),  
  625. 'permalink' => $product->get_permalink(),  
  626. 'sku' => $product->get_sku(),  
  627. 'price' => wc_format_decimal( $product->get_price(), $prices_precision ),  
  628. 'regular_price' => wc_format_decimal( $product->get_regular_price(), $prices_precision ),  
  629. 'sale_price' => $product->get_sale_price() ? wc_format_decimal( $product->get_sale_price(), $prices_precision ) : null,  
  630. 'price_html' => $product->get_price_html(),  
  631. 'taxable' => $product->is_taxable(),  
  632. 'tax_status' => $product->get_tax_status(),  
  633. 'tax_class' => $product->get_tax_class(),  
  634. 'managing_stock' => $product->managing_stock(),  
  635. 'stock_quantity' => $product->get_stock_quantity(),  
  636. 'in_stock' => $product->is_in_stock(),  
  637. 'backorders_allowed' => $product->backorders_allowed(),  
  638. 'backordered' => $product->is_on_backorder(),  
  639. 'sold_individually' => $product->is_sold_individually(),  
  640. 'purchaseable' => $product->is_purchasable(),  
  641. 'featured' => $product->is_featured(),  
  642. 'visible' => $product->is_visible(),  
  643. 'catalog_visibility' => $product->get_catalog_visibility(),  
  644. 'on_sale' => $product->is_on_sale(),  
  645. 'product_url' => $product->is_type( 'external' ) ? $product->get_product_url() : '',  
  646. 'button_text' => $product->is_type( 'external' ) ? $product->get_button_text() : '',  
  647. 'weight' => $product->get_weight() ? wc_format_decimal( $product->get_weight(), 2 ) : null,  
  648. 'dimensions' => array( 
  649. 'length' => $product->get_length(),  
  650. 'width' => $product->get_width(),  
  651. 'height' => $product->get_height(),  
  652. 'unit' => get_option( 'woocommerce_dimension_unit' ),  
  653. ),  
  654. 'shipping_required' => $product->needs_shipping(),  
  655. 'shipping_taxable' => $product->is_shipping_taxable(),  
  656. 'shipping_class' => $product->get_shipping_class(),  
  657. 'shipping_class_id' => ( 0 !== $product->get_shipping_class_id() ) ? $product->get_shipping_class_id() : null,  
  658. 'description' => wpautop( do_shortcode( $product->get_description() ) ),  
  659. 'short_description' => apply_filters( 'woocommerce_short_description', $product->get_short_description() ),  
  660. 'reviews_allowed' => $product->get_reviews_allowed(),  
  661. 'average_rating' => wc_format_decimal( $product->get_average_rating(), 2 ),  
  662. 'rating_count' => $product->get_rating_count(),  
  663. 'related_ids' => array_map( 'absint', array_values( wc_get_related_products( $product->get_id() ) ) ),  
  664. 'upsell_ids' => array_map( 'absint', $product->get_upsell_ids() ),  
  665. 'cross_sell_ids' => array_map( 'absint', $product->get_cross_sell_ids() ),  
  666. 'parent_id' => $product->get_parent_id(),  
  667. 'categories' => wc_get_object_terms( $product->get_id(), 'product_cat', 'name' ),  
  668. 'tags' => wc_get_object_terms( $product->get_id(), 'product_tag', 'name' ),  
  669. 'images' => $this->get_images( $product ),  
  670. 'featured_src' => wp_get_attachment_url( get_post_thumbnail_id( $product->get_id() ) ),  
  671. 'attributes' => $this->get_attributes( $product ),  
  672. 'downloads' => $this->get_downloads( $product ),  
  673. 'download_limit' => $product->get_download_limit(),  
  674. 'download_expiry' => $product->get_download_expiry(),  
  675. 'download_type' => 'standard',  
  676. 'purchase_note' => wpautop( do_shortcode( wp_kses_post( $product->get_purchase_note() ) ) ),  
  677. 'total_sales' => $product->get_total_sales(),  
  678. 'variations' => array(),  
  679. 'parent' => array(),  
  680. ); 
  681.  
  682. /** 
  683. * Get an individual variation's data 
  684. * 
  685. * @since 2.1 
  686. * @param WC_Product $product 
  687. * @return array 
  688. */ 
  689. private function get_variation_data( $product ) { 
  690. $prices_precision = wc_get_price_decimals(); 
  691. $variations = array(); 
  692.  
  693. foreach ( $product->get_children() as $child_id ) { 
  694.  
  695. $variation = wc_get_product( $child_id ); 
  696.  
  697. if ( ! $variation || ! $variation->exists() ) { 
  698. continue; 
  699.  
  700. $variations[] = array( 
  701. 'id' => $variation->get_id(),  
  702. 'created_at' => $this->server->format_datetime( $variation->get_date_created(), false, true ),  
  703. 'updated_at' => $this->server->format_datetime( $variation->get_date_modified(), false, true ),  
  704. 'downloadable' => $variation->is_downloadable(),  
  705. 'virtual' => $variation->is_virtual(),  
  706. 'permalink' => $variation->get_permalink(),  
  707. 'sku' => $variation->get_sku(),  
  708. 'price' => wc_format_decimal( $variation->get_price(), $prices_precision ),  
  709. 'regular_price' => wc_format_decimal( $variation->get_regular_price(), $prices_precision ),  
  710. 'sale_price' => $variation->get_sale_price() ? wc_format_decimal( $variation->get_sale_price(), $prices_precision ) : null,  
  711. 'taxable' => $variation->is_taxable(),  
  712. 'tax_status' => $variation->get_tax_status(),  
  713. 'tax_class' => $variation->get_tax_class(),  
  714. 'managing_stock' => $variation->managing_stock(),  
  715. 'stock_quantity' => (int) $variation->get_stock_quantity(),  
  716. 'in_stock' => $variation->is_in_stock(),  
  717. 'backordered' => $variation->is_on_backorder(),  
  718. 'purchaseable' => $variation->is_purchasable(),  
  719. 'visible' => $variation->variation_is_visible(),  
  720. 'on_sale' => $variation->is_on_sale(),  
  721. 'weight' => $variation->get_weight() ? wc_format_decimal( $variation->get_weight(), 2 ) : null,  
  722. 'dimensions' => array( 
  723. 'length' => $variation->get_length(),  
  724. 'width' => $variation->get_width(),  
  725. 'height' => $variation->get_height(),  
  726. 'unit' => get_option( 'woocommerce_dimension_unit' ),  
  727. ),  
  728. 'shipping_class' => $variation->get_shipping_class(),  
  729. 'shipping_class_id' => ( 0 !== $variation->get_shipping_class_id() ) ? $variation->get_shipping_class_id() : null,  
  730. 'image' => $this->get_images( $variation ),  
  731. 'attributes' => $this->get_attributes( $variation ),  
  732. 'downloads' => $this->get_downloads( $variation ),  
  733. 'download_limit' => (int) $product->get_download_limit(),  
  734. 'download_expiry' => (int) $product->get_download_expiry(),  
  735. ); 
  736.  
  737. return $variations; 
  738.  
  739. /** 
  740. * Save default attributes. 
  741. * 
  742. * @since 3.0.0 
  743. * @param WC_Product $product 
  744. * @param array $request 
  745. * @return WC_Product 
  746. */ 
  747. protected function save_default_attributes( $product, $request ) { 
  748. // Update default attributes options setting. 
  749. if ( isset( $request['default_attribute'] ) ) { 
  750. $request['default_attributes'] = $request['default_attribute']; 
  751.  
  752. if ( isset( $request['default_attributes'] ) && is_array( $request['default_attributes'] ) ) { 
  753. $attributes = $product->get_attributes(); 
  754. $default_attributes = array(); 
  755.  
  756. foreach ( $request['default_attributes'] as $default_attr_key => $default_attr ) { 
  757. if ( ! isset( $default_attr['name'] ) ) { 
  758. continue; 
  759.  
  760. $taxonomy = sanitize_title( $default_attr['name'] ); 
  761.  
  762. if ( isset( $default_attr['slug'] ) ) { 
  763. $taxonomy = $this->get_attribute_taxonomy_by_slug( $default_attr['slug'] ); 
  764.  
  765. if ( isset( $attributes[ $taxonomy ] ) ) { 
  766. $_attribute = $attributes[ $taxonomy ]; 
  767.  
  768. if ( $_attribute['is_variation'] ) { 
  769. $value = ''; 
  770.  
  771. if ( isset( $default_attr['option'] ) ) { 
  772. if ( $_attribute['is_taxonomy'] ) { 
  773. // Don't use wc_clean as it destroys sanitized characters. 
  774. $value = sanitize_title( trim( stripslashes( $default_attr['option'] ) ) ); 
  775. } else { 
  776. $value = wc_clean( trim( stripslashes( $default_attr['option'] ) ) ); 
  777.  
  778. if ( $value ) { 
  779. $default_attributes[ $taxonomy ] = $value; 
  780.  
  781. $product->set_default_attributes( $default_attributes ); 
  782.  
  783. return $product; 
  784.  
  785. /** 
  786. * Save product meta 
  787. * 
  788. * @since 2.2 
  789. * @param WC_Product $product 
  790. * @param array $data 
  791. * @return WC_Product 
  792. * @throws WC_API_Exception 
  793. */ 
  794. protected function save_product_meta( $product, $data ) { 
  795. global $wpdb; 
  796.  
  797. // Virtual 
  798. if ( isset( $data['virtual'] ) ) { 
  799. $product->set_virtual( $data['virtual'] ); 
  800.  
  801. // Tax status 
  802. if ( isset( $data['tax_status'] ) ) { 
  803. $product->set_tax_status( wc_clean( $data['tax_status'] ) ); 
  804.  
  805. // Tax Class 
  806. if ( isset( $data['tax_class'] ) ) { 
  807. $product->set_tax_class( wc_clean( $data['tax_class'] ) ); 
  808.  
  809. // Catalog Visibility 
  810. if ( isset( $data['catalog_visibility'] ) ) { 
  811. $product->set_catalog_visibility( wc_clean( $data['catalog_visibility'] ) ); 
  812.  
  813. // Purchase Note 
  814. if ( isset( $data['purchase_note'] ) ) { 
  815. $product->set_purchase_note( wc_clean( $data['purchase_note'] ) ); 
  816.  
  817. // Featured Product 
  818. if ( isset( $data['featured'] ) ) { 
  819. $product->set_featured( $data['featured'] ); 
  820.  
  821. // Shipping data 
  822. $product = $this->save_product_shipping_data( $product, $data ); 
  823.  
  824. // SKU 
  825. if ( isset( $data['sku'] ) ) { 
  826. $sku = $product->get_sku(); 
  827. $new_sku = wc_clean( $data['sku'] ); 
  828.  
  829. if ( '' == $new_sku ) { 
  830. $product->set_sku( '' ); 
  831. } elseif ( $new_sku !== $sku ) { 
  832. if ( ! empty( $new_sku ) ) { 
  833. $unique_sku = wc_product_has_unique_sku( $product->get_id(), $new_sku ); 
  834. if ( ! $unique_sku ) { 
  835. throw new WC_API_Exception( 'woocommerce_api_product_sku_already_exists', __( 'The SKU already exists on another product.', 'woocommerce' ), 400 ); 
  836. } else { 
  837. $product->set_sku( $new_sku ); 
  838. } else { 
  839. $product->set_sku( '' ); 
  840.  
  841. // Attributes 
  842. if ( isset( $data['attributes'] ) ) { 
  843. $attributes = array(); 
  844.  
  845. foreach ( $data['attributes'] as $attribute ) { 
  846. $is_taxonomy = 0; 
  847. $taxonomy = 0; 
  848.  
  849. if ( ! isset( $attribute['name'] ) ) { 
  850. continue; 
  851.  
  852. $attribute_slug = sanitize_title( $attribute['name'] ); 
  853.  
  854. if ( isset( $attribute['slug'] ) ) { 
  855. $taxonomy = $this->get_attribute_taxonomy_by_slug( $attribute['slug'] ); 
  856. $attribute_slug = sanitize_title( $attribute['slug'] ); 
  857.  
  858. if ( $taxonomy ) { 
  859. $is_taxonomy = 1; 
  860.  
  861. if ( $is_taxonomy ) { 
  862.  
  863. $attribute_id = wc_attribute_taxonomy_id_by_name( $attribute['name'] ); 
  864.  
  865. if ( isset( $attribute['options'] ) ) { 
  866. $options = $attribute['options']; 
  867.  
  868. if ( ! is_array( $attribute['options'] ) ) { 
  869. // Text based attributes - Posted values are term names 
  870. $options = explode( WC_DELIMITER, $options ); 
  871.  
  872. $values = array_map( 'wc_sanitize_term_text_based', $options ); 
  873. $values = array_filter( $values, 'strlen' ); 
  874. } else { 
  875. $values = array(); 
  876.  
  877. // Update post terms 
  878. if ( taxonomy_exists( $taxonomy ) ) { 
  879. wp_set_object_terms( $product->get_id(), $values, $taxonomy ); 
  880.  
  881. if ( ! empty( $values ) ) { 
  882. // Add attribute to array, but don't set values. 
  883. $attribute_object = new WC_Product_Attribute(); 
  884. $attribute_object->set_id( $attribute_id ); 
  885. $attribute_object->set_name( $taxonomy ); 
  886. $attribute_object->set_options( $values ); 
  887. $attribute_object->set_position( isset( $attribute['position'] ) ? absint( $attribute['position'] ) : 0 ); 
  888. $attribute_object->set_visible( ( isset( $attribute['visible'] ) && $attribute['visible'] ) ? 1 : 0 ); 
  889. $attribute_object->set_variation( ( isset( $attribute['variation'] ) && $attribute['variation'] ) ? 1 : 0 ); 
  890. $attributes[] = $attribute_object; 
  891. } elseif ( isset( $attribute['options'] ) ) { 
  892. // Array based 
  893. if ( is_array( $attribute['options'] ) ) { 
  894. $values = $attribute['options']; 
  895.  
  896. // Text based, separate by pipe 
  897. } else { 
  898. $values = array_map( 'wc_clean', explode( WC_DELIMITER, $attribute['options'] ) ); 
  899.  
  900. // Custom attribute - Add attribute to array and set the values. 
  901. $attribute_object = new WC_Product_Attribute(); 
  902. $attribute_object->set_name( $attribute['name'] ); 
  903. $attribute_object->set_options( $values ); 
  904. $attribute_object->set_position( isset( $attribute['position'] ) ? absint( $attribute['position'] ) : 0 ); 
  905. $attribute_object->set_visible( ( isset( $attribute['visible'] ) && $attribute['visible'] ) ? 1 : 0 ); 
  906. $attribute_object->set_variation( ( isset( $attribute['variation'] ) && $attribute['variation'] ) ? 1 : 0 ); 
  907. $attributes[] = $attribute_object; 
  908.  
  909. uasort( $attributes, 'wc_product_attribute_uasort_comparison' ); 
  910.  
  911. $product->set_attributes( $attributes ); 
  912.  
  913. // Sales and prices 
  914. if ( in_array( $product->get_type(), array( 'variable', 'grouped' ) ) ) { 
  915.  
  916. // Variable and grouped products have no prices. 
  917. $product->set_regular_price( '' ); 
  918. $product->set_sale_price( '' ); 
  919. $product->set_date_on_sale_to( '' ); 
  920. $product->set_date_on_sale_from( '' ); 
  921. $product->set_price( '' ); 
  922.  
  923. } else { 
  924.  
  925. // Regular Price 
  926. if ( isset( $data['regular_price'] ) ) { 
  927. $regular_price = ( '' === $data['regular_price'] ) ? '' : $data['regular_price']; 
  928. } else { 
  929. $regular_price = $product->get_regular_price(); 
  930.  
  931. // Sale Price 
  932. if ( isset( $data['sale_price'] ) ) { 
  933. $sale_price = ( '' === $data['sale_price'] ) ? '' : $data['sale_price']; 
  934. } else { 
  935. $sale_price = $product->get_sale_price(); 
  936.  
  937. $product->set_regular_price( $regular_price ); 
  938. $product->set_sale_price( $sale_price ); 
  939.  
  940. if ( isset( $data['sale_price_dates_from'] ) ) { 
  941. $date_from = $data['sale_price_dates_from']; 
  942. } else { 
  943. $date_from = $product->get_date_on_sale_from() ? date( 'Y-m-d', $product->get_date_on_sale_from()->getTimestamp() ) : ''; 
  944.  
  945. if ( isset( $data['sale_price_dates_to'] ) ) { 
  946. $date_to = $data['sale_price_dates_to']; 
  947. } else { 
  948. $date_to = $product->get_date_on_sale_to() ? date( 'Y-m-d', $product->get_date_on_sale_to()->getTimestamp() ) : ''; 
  949.  
  950. if ( $date_to && ! $date_from ) { 
  951. $date_from = strtotime( 'NOW', current_time( 'timestamp', true ) ); 
  952.  
  953. $product->set_date_on_sale_to( $date_to ); 
  954. $product->set_date_on_sale_from( $date_from ); 
  955. if ( $product->is_on_sale() ) { 
  956. $product->set_price( $product->get_sale_price() ); 
  957. } else { 
  958. $product->set_price( $product->get_regular_price() ); 
  959.  
  960. // Product parent ID for groups 
  961. if ( isset( $data['parent_id'] ) ) { 
  962. $product->set_parent_id( absint( $data['parent_id'] ) ); 
  963.  
  964. // Sold Individually 
  965. if ( isset( $data['sold_individually'] ) ) { 
  966. $product->set_sold_individually( true === $data['sold_individually'] ? 'yes' : '' ); 
  967.  
  968. // Stock status 
  969. if ( isset( $data['in_stock'] ) ) { 
  970. $stock_status = ( true === $data['in_stock'] ) ? 'instock' : 'outofstock'; 
  971. } else { 
  972. $stock_status = $product->get_stock_status(); 
  973.  
  974. if ( '' === $stock_status ) { 
  975. $stock_status = 'instock'; 
  976.  
  977. // Stock Data 
  978. if ( 'yes' == get_option( 'woocommerce_manage_stock' ) ) { 
  979. // Manage stock 
  980. if ( isset( $data['managing_stock'] ) ) { 
  981. $managing_stock = ( true === $data['managing_stock'] ) ? 'yes' : 'no'; 
  982. $product->set_manage_stock( $managing_stock ); 
  983. } else { 
  984. $managing_stock = $product->get_manage_stock() ? 'yes' : 'no'; 
  985.  
  986. // Backorders 
  987. if ( isset( $data['backorders'] ) ) { 
  988. if ( 'notify' == $data['backorders'] ) { 
  989. $backorders = 'notify'; 
  990. } else { 
  991. $backorders = ( true === $data['backorders'] ) ? 'yes' : 'no'; 
  992.  
  993. $product->set_backorders( $backorders ); 
  994. } else { 
  995. $backorders = $product->get_backorders(); 
  996.  
  997. if ( $product->is_type( 'grouped' ) ) { 
  998. $product->set_manage_stock( 'no' ); 
  999. $product->set_backorders( 'no' ); 
  1000. $product->set_stock_quantity( '' ); 
  1001. $product->set_stock_status( $stock_status ); 
  1002. } elseif ( $product->is_type( 'external' ) ) { 
  1003. $product->set_manage_stock( 'no' ); 
  1004. $product->set_backorders( 'no' ); 
  1005. $product->set_stock_quantity( '' ); 
  1006. $product->set_stock_status( 'instock' ); 
  1007. } elseif ( 'yes' == $managing_stock ) { 
  1008. $product->set_backorders( $backorders ); 
  1009.  
  1010. // Stock status is always determined by children so sync later. 
  1011. if ( ! $product->is_type( 'variable' ) ) { 
  1012. $product->set_stock_status( $stock_status ); 
  1013.  
  1014. // Stock quantity 
  1015. if ( isset( $data['stock_quantity'] ) ) { 
  1016. $product->set_stock_quantity( wc_stock_amount( $data['stock_quantity'] ) ); 
  1017. } else { 
  1018. // Don't manage stock. 
  1019. $product->set_manage_stock( 'no' ); 
  1020. $product->set_backorders( $backorders ); 
  1021. $product->set_stock_quantity( '' ); 
  1022. $product->set_stock_status( $stock_status ); 
  1023. } elseif ( ! $product->is_type( 'variable' ) ) { 
  1024. $product->set_stock_status( $stock_status ); 
  1025.  
  1026. // Upsells 
  1027. if ( isset( $data['upsell_ids'] ) ) { 
  1028. $upsells = array(); 
  1029. $ids = $data['upsell_ids']; 
  1030.  
  1031. if ( ! empty( $ids ) ) { 
  1032. foreach ( $ids as $id ) { 
  1033. if ( $id && $id > 0 ) { 
  1034. $upsells[] = $id; 
  1035.  
  1036. $product->set_upsell_ids( $upsells ); 
  1037. } else { 
  1038. $product->set_upsell_ids( array() ); 
  1039.  
  1040. // Cross sells 
  1041. if ( isset( $data['cross_sell_ids'] ) ) { 
  1042. $crosssells = array(); 
  1043. $ids = $data['cross_sell_ids']; 
  1044.  
  1045. if ( ! empty( $ids ) ) { 
  1046. foreach ( $ids as $id ) { 
  1047. if ( $id && $id > 0 ) { 
  1048. $crosssells[] = $id; 
  1049.  
  1050. $product->set_cross_sell_ids( $crosssells ); 
  1051. } else { 
  1052. $product->set_cross_sell_ids( array() ); 
  1053.  
  1054. // Product categories 
  1055. if ( isset( $data['categories'] ) && is_array( $data['categories'] ) ) { 
  1056. $product->set_category_ids( $data['categories'] ); 
  1057.  
  1058. // Product tags 
  1059. if ( isset( $data['tags'] ) && is_array( $data['tags'] ) ) { 
  1060. $product->set_tag_ids( $data['tags'] ); 
  1061.  
  1062. // Downloadable 
  1063. if ( isset( $data['downloadable'] ) ) { 
  1064. $is_downloadable = ( true === $data['downloadable'] ) ? 'yes' : 'no'; 
  1065. $product->set_downloadable( $is_downloadable ); 
  1066. } else { 
  1067. $is_downloadable = $product->get_downloadable() ? 'yes' : 'no'; 
  1068.  
  1069. // Downloadable options 
  1070. if ( 'yes' == $is_downloadable ) { 
  1071.  
  1072. // Downloadable files 
  1073. if ( isset( $data['downloads'] ) && is_array( $data['downloads'] ) ) { 
  1074. $product = $this->save_downloadable_files( $product, $data['downloads'] ); 
  1075.  
  1076. // Download limit 
  1077. if ( isset( $data['download_limit'] ) ) { 
  1078. $product->set_download_limit( $data['download_limit'] ); 
  1079.  
  1080. // Download expiry 
  1081. if ( isset( $data['download_expiry'] ) ) { 
  1082. $product->set_download_expiry( $data['download_expiry'] ); 
  1083.  
  1084. // Product url 
  1085. if ( $product->is_type( 'external' ) ) { 
  1086. if ( isset( $data['product_url'] ) ) { 
  1087. $product->set_product_url( $data['product_url'] ); 
  1088.  
  1089. if ( isset( $data['button_text'] ) ) { 
  1090. $product->set_button_text( $data['button_text'] ); 
  1091.  
  1092. // Reviews allowed 
  1093. if ( isset( $data['reviews_allowed'] ) ) { 
  1094. $product->set_reviews_allowed( $data['reviews_allowed'] ); 
  1095.  
  1096. // Save default attributes for variable products. 
  1097. if ( $product->is_type( 'variable' ) ) { 
  1098. $product = $this->save_default_attributes( $product, $data ); 
  1099.  
  1100. // Do action for product type 
  1101. do_action( 'woocommerce_api_process_product_meta_' . $product->get_type(), $product->get_id(), $data ); 
  1102.  
  1103. return $product; 
  1104.  
  1105. /** 
  1106. * Save variations 
  1107. * 
  1108. * @since 2.2 
  1109. * @param WC_Product $product 
  1110. * @param array $request 
  1111. * @return WC_Product 
  1112. * @throws WC_API_Exception 
  1113. */ 
  1114. protected function save_variations( $product, $request ) { 
  1115. global $wpdb; 
  1116.  
  1117. $id = $product->get_id(); 
  1118. $attributes = $product->get_attributes(); 
  1119.  
  1120. foreach ( $request['variations'] as $menu_order => $data ) { 
  1121. $variation_id = isset( $data['id'] ) ? absint( $data['id'] ) : 0; 
  1122. $variation = new WC_Product_Variation( $variation_id ); 
  1123.  
  1124. // Create initial name and status. 
  1125. if ( ! $variation->get_slug() ) { 
  1126. /** translators: 1: variation id 2: product name */ 
  1127. $variation->set_name( sprintf( __( 'Variation #%1$s of %2$s', 'woocommerce' ), $variation->get_id(), $product->get_name() ) ); 
  1128. $variation->set_status( isset( $data['visible'] ) && false === $data['visible'] ? 'private' : 'publish' ); 
  1129.  
  1130. // Parent ID. 
  1131. $variation->set_parent_id( $product->get_id() ); 
  1132.  
  1133. // Menu order. 
  1134. $variation->set_menu_order( $menu_order ); 
  1135.  
  1136. // Status. 
  1137. if ( isset( $data['visible'] ) ) { 
  1138. $variation->set_status( false === $data['visible'] ? 'private' : 'publish' ); 
  1139.  
  1140. // SKU
  1141. if ( isset( $data['sku'] ) ) { 
  1142. $variation->set_sku( wc_clean( $data['sku'] ) ); 
  1143.  
  1144. // Thumbnail. 
  1145. if ( isset( $data['image'] ) && is_array( $data['image'] ) ) { 
  1146. $image = current( $data['image'] ); 
  1147. if ( is_array( $image ) ) { 
  1148. $image['position'] = 0; 
  1149.  
  1150. $variation = $this->save_product_images( $variation, array( $image ) ); 
  1151.  
  1152. // Virtual variation. 
  1153. if ( isset( $data['virtual'] ) ) { 
  1154. $variation->set_virtual( $data['virtual'] ); 
  1155.  
  1156. // Downloadable variation. 
  1157. if ( isset( $data['downloadable'] ) ) { 
  1158. $is_downloadable = $data['downloadable']; 
  1159. $variation->set_downloadable( $is_downloadable ); 
  1160. } else { 
  1161. $is_downloadable = $variation->get_downloadable(); 
  1162.  
  1163. // Downloads. 
  1164. if ( $is_downloadable ) { 
  1165. // Downloadable files. 
  1166. if ( isset( $data['downloads'] ) && is_array( $data['downloads'] ) ) { 
  1167. $variation = $this->save_downloadable_files( $variation, $data['downloads'] ); 
  1168.  
  1169. // Download limit
  1170. if ( isset( $data['download_limit'] ) ) { 
  1171. $variation->set_download_limit( $data['download_limit'] ); 
  1172.  
  1173. // Download expiry
  1174. if ( isset( $data['download_expiry'] ) ) { 
  1175. $variation->set_download_expiry( $data['download_expiry'] ); 
  1176.  
  1177. // Shipping data
  1178. $variation = $this->save_product_shipping_data( $variation, $data ); 
  1179.  
  1180. // Stock handling. 
  1181. $manage_stock = (bool) $variation->get_manage_stock(); 
  1182. if ( isset( $data['managing_stock'] ) ) { 
  1183. $manage_stock = $data['managing_stock']; 
  1184. $variation->set_manage_stock( $manage_stock ); 
  1185.  
  1186. $stock_status = $variation->get_stock_status(); 
  1187. if ( isset( $data['in_stock'] ) ) { 
  1188. $stock_status = true === $data['in_stock'] ? 'instock' : 'outofstock'; 
  1189. $variation->set_stock_status( $stock_status ); 
  1190.  
  1191. $backorders = $variation->get_backorders(); 
  1192. if ( isset( $data['backorders'] ) ) { 
  1193. $backorders = $data['backorders']; 
  1194. $variation->set_backorders( $backorders ); 
  1195.  
  1196. if ( $manage_stock ) { 
  1197. if ( isset( $data['stock_quantity'] ) ) { 
  1198. $variation->set_stock_quantity( $data['stock_quantity'] ); 
  1199. } else { 
  1200. $variation->set_backorders( 'no' ); 
  1201. $variation->set_stock_quantity( '' ); 
  1202.  
  1203. // Regular Price
  1204. if ( isset( $data['regular_price'] ) ) { 
  1205. $variation->set_regular_price( $data['regular_price'] ); 
  1206.  
  1207. // Sale Price
  1208. if ( isset( $data['sale_price'] ) ) { 
  1209. $variation->set_sale_price( $data['sale_price'] ); 
  1210.  
  1211. if ( isset( $data['sale_price_dates_from'] ) ) { 
  1212. $variation->set_date_on_sale_from( $data['sale_price_dates_from'] ); 
  1213.  
  1214. if ( isset( $data['sale_price_dates_to'] ) ) { 
  1215. $variation->set_date_on_sale_to( $data['sale_price_dates_to'] ); 
  1216.  
  1217. // Tax class. 
  1218. if ( isset( $data['tax_class'] ) ) { 
  1219. $variation->set_tax_class( $data['tax_class'] ); 
  1220.  
  1221. // Update taxonomies. 
  1222. if ( isset( $data['attributes'] ) ) { 
  1223. $_attributes = array(); 
  1224.  
  1225. foreach ( $data['attributes'] as $attribute_key => $attribute ) { 
  1226. if ( ! isset( $attribute['name'] ) ) { 
  1227. continue; 
  1228.  
  1229. $taxonomy = 0; 
  1230. $_attribute = array(); 
  1231.  
  1232. if ( isset( $attribute['slug'] ) ) { 
  1233. $taxonomy = $this->get_attribute_taxonomy_by_slug( $attribute['slug'] ); 
  1234.  
  1235. if ( ! $taxonomy ) { 
  1236. $taxonomy = sanitize_title( $attribute['name'] ); 
  1237.  
  1238. if ( isset( $attributes[ $taxonomy ] ) ) { 
  1239. $_attribute = $attributes[ $taxonomy ]; 
  1240.  
  1241. if ( isset( $_attribute['is_variation'] ) && $_attribute['is_variation'] ) { 
  1242. $_attribute_key = sanitize_title( $_attribute['name'] ); 
  1243.  
  1244. if ( isset( $_attribute['is_taxonomy'] ) && $_attribute['is_taxonomy'] ) { 
  1245. // Don't use wc_clean as it destroys sanitized characters 
  1246. $_attribute_value = isset( $attribute['option'] ) ? sanitize_title( stripslashes( $attribute['option'] ) ) : ''; 
  1247. } else { 
  1248. $_attribute_value = isset( $attribute['option'] ) ? wc_clean( stripslashes( $attribute['option'] ) ) : ''; 
  1249.  
  1250. $_attributes[ $_attribute_key ] = $_attribute_value; 
  1251.  
  1252. $variation->set_attributes( $_attributes ); 
  1253.  
  1254. $variation->save(); 
  1255.  
  1256. do_action( 'woocommerce_api_save_product_variation', $variation_id, $menu_order, $variation ); 
  1257.  
  1258. return true; 
  1259.  
  1260. /** 
  1261. * Save product shipping data 
  1262. * 
  1263. * @since 2.2 
  1264. * @param WC_Product $product 
  1265. * @param array $data 
  1266. * @return WC_Product 
  1267. */ 
  1268. private function save_product_shipping_data( $product, $data ) { 
  1269. if ( isset( $data['weight'] ) ) { 
  1270. $product->set_weight( '' === $data['weight'] ? '' : wc_format_decimal( $data['weight'] ) ); 
  1271.  
  1272. // Product dimensions 
  1273. if ( isset( $data['dimensions'] ) ) { 
  1274. // Height 
  1275. if ( isset( $data['dimensions']['height'] ) ) { 
  1276. $product->set_height( '' === $data['dimensions']['height'] ? '' : wc_format_decimal( $data['dimensions']['height'] ) ); 
  1277.  
  1278. // Width 
  1279. if ( isset( $data['dimensions']['width'] ) ) { 
  1280. $product->set_width( '' === $data['dimensions']['width'] ? '' : wc_format_decimal( $data['dimensions']['width'] ) ); 
  1281.  
  1282. // Length 
  1283. if ( isset( $data['dimensions']['length'] ) ) { 
  1284. $product->set_length( '' === $data['dimensions']['length'] ? '' : wc_format_decimal( $data['dimensions']['length'] ) ); 
  1285.  
  1286. // Virtual 
  1287. if ( isset( $data['virtual'] ) ) { 
  1288. $virtual = ( true === $data['virtual'] ) ? 'yes' : 'no'; 
  1289.  
  1290. if ( 'yes' == $virtual ) { 
  1291. $product->set_weight( '' ); 
  1292. $product->set_height( '' ); 
  1293. $product->set_length( '' ); 
  1294. $product->set_width( '' ); 
  1295.  
  1296. // Shipping class 
  1297. if ( isset( $data['shipping_class'] ) ) { 
  1298. $data_store = $product->get_data_store(); 
  1299. $shipping_class_id = $data_store->get_shipping_class_id_by_slug( wc_clean( $data['shipping_class'] ) ); 
  1300. if ( $shipping_class_id ) { 
  1301. $product->set_shipping_class_id( $shipping_class_id ); 
  1302.  
  1303. return $product; 
  1304.  
  1305. /** 
  1306. * Save downloadable files 
  1307. * 
  1308. * @since 2.2 
  1309. * @param WC_Product $product 
  1310. * @param array $downloads 
  1311. * @param int $deprecated Deprecated since 3.0. 
  1312. * @return WC_Product 
  1313. */ 
  1314. private function save_downloadable_files( $product, $downloads, $deprecated = 0 ) { 
  1315. if ( $deprecated ) { 
  1316. wc_deprecated_argument( 'variation_id', '3.0', 'save_downloadable_files() does not require a variation_id anymore.' ); 
  1317.  
  1318. $files = array(); 
  1319. foreach ( $downloads as $key => $file ) { 
  1320. if ( isset( $file['url'] ) ) { 
  1321. $file['file'] = $file['url']; 
  1322.  
  1323. if ( empty( $file['file'] ) ) { 
  1324. continue; 
  1325.  
  1326. $download = new WC_Product_Download(); 
  1327. $download->set_id( $key ); 
  1328. $download->set_name( $file['name'] ? $file['name'] : wc_get_filename_from_url( $file['file'] ) ); 
  1329. $download->set_file( apply_filters( 'woocommerce_file_download_path', $file['file'], $product, $key ) ); 
  1330. $files[] = $download; 
  1331. $product->set_downloads( $files ); 
  1332.  
  1333. return $product; 
  1334.  
  1335. /** 
  1336. * Get attribute taxonomy by slug. 
  1337. * 
  1338. * @since 2.2 
  1339. * @param string $slug 
  1340. * @return string|null 
  1341. */ 
  1342. private function get_attribute_taxonomy_by_slug( $slug ) { 
  1343. $taxonomy = null; 
  1344. $attribute_taxonomies = wc_get_attribute_taxonomies(); 
  1345.  
  1346. foreach ( $attribute_taxonomies as $key => $tax ) { 
  1347. if ( $slug == $tax->attribute_name ) { 
  1348. $taxonomy = 'pa_' . $tax->attribute_name; 
  1349.  
  1350. break; 
  1351.  
  1352. return $taxonomy; 
  1353.  
  1354. /** 
  1355. * Get the images for a product or product variation 
  1356. * 
  1357. * @since 2.1 
  1358. * @param WC_Product|WC_Product_Variation $product 
  1359. * @return array 
  1360. */ 
  1361. private function get_images( $product ) { 
  1362. $images = $attachment_ids = array(); 
  1363. $product_image = $product->get_image_id(); 
  1364.  
  1365. // Add featured image. 
  1366. if ( ! empty( $product_image ) ) { 
  1367. $attachment_ids[] = $product_image; 
  1368.  
  1369. // Add gallery images. 
  1370. $attachment_ids = array_merge( $attachment_ids, $product->get_gallery_image_ids() ); 
  1371.  
  1372. // Build image data. 
  1373. foreach ( $attachment_ids as $position => $attachment_id ) { 
  1374.  
  1375. $attachment_post = get_post( $attachment_id ); 
  1376.  
  1377. if ( is_null( $attachment_post ) ) { 
  1378. continue; 
  1379.  
  1380. $attachment = wp_get_attachment_image_src( $attachment_id, 'full' ); 
  1381.  
  1382. if ( ! is_array( $attachment ) ) { 
  1383. continue; 
  1384.  
  1385. $images[] = array( 
  1386. 'id' => (int) $attachment_id,  
  1387. 'created_at' => $this->server->format_datetime( $attachment_post->post_date_gmt ),  
  1388. 'updated_at' => $this->server->format_datetime( $attachment_post->post_modified_gmt ),  
  1389. 'src' => current( $attachment ),  
  1390. 'title' => get_the_title( $attachment_id ),  
  1391. 'alt' => get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ),  
  1392. 'position' => (int) $position,  
  1393. ); 
  1394.  
  1395. // Set a placeholder image if the product has no images set. 
  1396. if ( empty( $images ) ) { 
  1397.  
  1398. $images[] = array( 
  1399. 'id' => 0,  
  1400. 'created_at' => $this->server->format_datetime( time() ), // Default to now. 
  1401. 'updated_at' => $this->server->format_datetime( time() ),  
  1402. 'src' => wc_placeholder_img_src(),  
  1403. 'title' => __( 'Placeholder', 'woocommerce' ),  
  1404. 'alt' => __( 'Placeholder', 'woocommerce' ),  
  1405. 'position' => 0,  
  1406. ); 
  1407.  
  1408. return $images; 
  1409.  
  1410. /** 
  1411. * Save product images 
  1412. * 
  1413. * @since 2.2 
  1414. * @param WC_Product $product 
  1415. * @param array $images 
  1416. * @throws WC_API_Exception 
  1417. */ 
  1418. protected function save_product_images( $product, $images ) { 
  1419. if ( is_array( $images ) ) { 
  1420. $gallery = array(); 
  1421.  
  1422. foreach ( $images as $image ) { 
  1423. if ( isset( $image['position'] ) && 0 == $image['position'] ) { 
  1424. $attachment_id = isset( $image['id'] ) ? absint( $image['id'] ) : 0; 
  1425.  
  1426. if ( 0 === $attachment_id && isset( $image['src'] ) ) { 
  1427. $upload = $this->upload_product_image( esc_url_raw( $image['src'] ) ); 
  1428.  
  1429. if ( is_wp_error( $upload ) ) { 
  1430. throw new WC_API_Exception( 'woocommerce_api_cannot_upload_product_image', $upload->get_error_message(), 400 ); 
  1431.  
  1432. $attachment_id = $this->set_product_image_as_attachment( $upload, $product->get_id() ); 
  1433.  
  1434. $product->set_image_id( $attachment_id ); 
  1435. } else { 
  1436. $attachment_id = isset( $image['id'] ) ? absint( $image['id'] ) : 0; 
  1437.  
  1438. if ( 0 === $attachment_id && isset( $image['src'] ) ) { 
  1439. $upload = $this->upload_product_image( esc_url_raw( $image['src'] ) ); 
  1440.  
  1441. if ( is_wp_error( $upload ) ) { 
  1442. throw new WC_API_Exception( 'woocommerce_api_cannot_upload_product_image', $upload->get_error_message(), 400 ); 
  1443.  
  1444. $gallery[] = $this->set_product_image_as_attachment( $upload, $product->get_id() ); 
  1445. } else { 
  1446. $gallery[] = $attachment_id; 
  1447.  
  1448. if ( ! empty( $gallery ) ) { 
  1449. $product->set_gallery_image_ids( $gallery ); 
  1450. } else { 
  1451. $product->set_image_id( '' ); 
  1452. $product->set_gallery_image_ids( array() ); 
  1453.  
  1454. return $product; 
  1455.  
  1456. /** 
  1457. * Upload image from URL 
  1458. * 
  1459. * @since 2.2 
  1460. * @param string $image_url 
  1461. * @return int|WP_Error attachment id 
  1462. * @throws WC_API_Exception 
  1463. */ 
  1464. public function upload_product_image( $image_url ) { 
  1465. $file_name = basename( current( explode( '?', $image_url ) ) ); 
  1466. $parsed_url = @parse_url( $image_url ); 
  1467.  
  1468. // Check parsed URL 
  1469. if ( ! $parsed_url || ! is_array( $parsed_url ) ) { 
  1470. throw new WC_API_Exception( 'woocommerce_api_invalid_product_image', sprintf( __( 'Invalid URL %s.', 'woocommerce' ), $image_url ), 400 ); 
  1471.  
  1472. // Ensure url is valid 
  1473. $image_url = str_replace( ' ', '%20', $image_url ); 
  1474.  
  1475. // Get the file 
  1476. $response = wp_safe_remote_get( $image_url, array( 
  1477. 'timeout' => 10,  
  1478. ) ); 
  1479.  
  1480. if ( is_wp_error( $response ) ) { 
  1481. throw new WC_API_Exception( 'woocommerce_api_invalid_remote_product_image', sprintf( __( 'Error getting remote image %s.', 'woocommerce' ), $image_url ) . ' ' . sprintf( __( 'Error: %s.', 'woocommerce' ), $response->get_error_message() ), 400 ); 
  1482. } elseif ( 200 !== wp_remote_retrieve_response_code( $response ) ) { 
  1483. throw new WC_API_Exception( 'woocommerce_api_invalid_remote_product_image', sprintf( __( 'Error getting remote image %s.', 'woocommerce' ), $image_url ), 400 ); 
  1484.  
  1485. // Ensure we have a file name and type 
  1486. $wp_filetype = wp_check_filetype( $file_name, wc_rest_allowed_image_mime_types() ); 
  1487.  
  1488. if ( ! $wp_filetype['type'] ) { 
  1489. $headers = wp_remote_retrieve_headers( $response ); 
  1490. if ( isset( $headers['content-disposition'] ) && strstr( $headers['content-disposition'], 'filename=' ) ) { 
  1491. $disposition = end( explode( 'filename=', $headers['content-disposition'] ) ); 
  1492. $disposition = sanitize_file_name( $disposition ); 
  1493. $file_name = $disposition; 
  1494. } elseif ( isset( $headers['content-type'] ) && strstr( $headers['content-type'], 'image/' ) ) { 
  1495. $file_name = 'image.' . str_replace( 'image/', '', $headers['content-type'] ); 
  1496. unset( $headers ); 
  1497.  
  1498. // Recheck filetype 
  1499. $wp_filetype = wp_check_filetype( $file_name, wc_rest_allowed_image_mime_types() ); 
  1500.  
  1501. if ( ! $wp_filetype['type'] ) { 
  1502. throw new WC_API_Exception( 'woocommerce_api_invalid_product_image', __( 'Invalid image type.', 'woocommerce' ), 400 ); 
  1503.  
  1504. // Upload the file 
  1505. $upload = wp_upload_bits( $file_name, '', wp_remote_retrieve_body( $response ) ); 
  1506.  
  1507. if ( $upload['error'] ) { 
  1508. throw new WC_API_Exception( 'woocommerce_api_product_image_upload_error', $upload['error'], 400 ); 
  1509.  
  1510. // Get filesize 
  1511. $filesize = filesize( $upload['file'] ); 
  1512.  
  1513. if ( 0 == $filesize ) { 
  1514. @unlink( $upload['file'] ); 
  1515. unset( $upload ); 
  1516. throw new WC_API_Exception( 'woocommerce_api_product_image_upload_file_error', __( 'Zero size file downloaded.', 'woocommerce' ), 400 ); 
  1517.  
  1518. unset( $response ); 
  1519.  
  1520. return $upload; 
  1521.  
  1522. /** 
  1523. * Sets product image as attachment and returns the attachment ID. 
  1524. * 
  1525. * @since 2.2 
  1526. * @param array $upload 
  1527. * @param int $id 
  1528. * @return int 
  1529. */ 
  1530. protected function set_product_image_as_attachment( $upload, $id ) { 
  1531. $info = wp_check_filetype( $upload['file'] ); 
  1532. $title = ''; 
  1533. $content = ''; 
  1534.  
  1535. if ( $image_meta = @wp_read_image_metadata( $upload['file'] ) ) { 
  1536. if ( trim( $image_meta['title'] ) && ! is_numeric( sanitize_title( $image_meta['title'] ) ) ) { 
  1537. $title = wc_clean( $image_meta['title'] ); 
  1538. if ( trim( $image_meta['caption'] ) ) { 
  1539. $content = wc_clean( $image_meta['caption'] ); 
  1540.  
  1541. $attachment = array( 
  1542. 'post_mime_type' => $info['type'],  
  1543. 'guid' => $upload['url'],  
  1544. 'post_parent' => $id,  
  1545. 'post_title' => $title,  
  1546. 'post_content' => $content,  
  1547. ); 
  1548.  
  1549. $attachment_id = wp_insert_attachment( $attachment, $upload['file'], $id ); 
  1550. if ( ! is_wp_error( $attachment_id ) ) { 
  1551. wp_update_attachment_metadata( $attachment_id, wp_generate_attachment_metadata( $attachment_id, $upload['file'] ) ); 
  1552.  
  1553. return $attachment_id; 
  1554.  
  1555. /** 
  1556. * Get attribute options. 
  1557. * 
  1558. * @param int $product_id 
  1559. * @param array $attribute 
  1560. * @return array 
  1561. */ 
  1562. protected function get_attribute_options( $product_id, $attribute ) { 
  1563. if ( isset( $attribute['is_taxonomy'] ) && $attribute['is_taxonomy'] ) { 
  1564. return wc_get_product_terms( $product_id, $attribute['name'], array( 'fields' => 'names' ) ); 
  1565. } elseif ( isset( $attribute['value'] ) ) { 
  1566. return array_map( 'trim', explode( '|', $attribute['value'] ) ); 
  1567.  
  1568. return array(); 
  1569.  
  1570. /** 
  1571. * Get the attributes for a product or product variation 
  1572. * 
  1573. * @since 2.1 
  1574. * @param WC_Product|WC_Product_Variation $product 
  1575. * @return array 
  1576. */ 
  1577. private function get_attributes( $product ) { 
  1578.  
  1579. $attributes = array(); 
  1580.  
  1581. if ( $product->is_type( 'variation' ) ) { 
  1582.  
  1583. // variation attributes 
  1584. foreach ( $product->get_variation_attributes() as $attribute_name => $attribute ) { 
  1585.  
  1586. // taxonomy-based attributes are prefixed with `pa_`, otherwise simply `attribute_` 
  1587. $attributes[] = array( 
  1588. 'name' => wc_attribute_label( str_replace( 'attribute_', '', $attribute_name ) ),  
  1589. 'slug' => str_replace( 'attribute_', '', str_replace( 'pa_', '', $attribute_name ) ),  
  1590. 'option' => $attribute,  
  1591. ); 
  1592. } else { 
  1593.  
  1594. foreach ( $product->get_attributes() as $attribute ) { 
  1595. $attributes[] = array( 
  1596. 'name' => wc_attribute_label( $attribute['name'] ),  
  1597. 'slug' => str_replace( 'pa_', '', $attribute['name'] ),  
  1598. 'position' => (int) $attribute['position'],  
  1599. 'visible' => (bool) $attribute['is_visible'],  
  1600. 'variation' => (bool) $attribute['is_variation'],  
  1601. 'options' => $this->get_attribute_options( $product->get_id(), $attribute ),  
  1602. ); 
  1603.  
  1604. return $attributes; 
  1605.  
  1606. /** 
  1607. * Get the downloads for a product or product variation 
  1608. * 
  1609. * @since 2.1 
  1610. * @param WC_Product|WC_Product_Variation $product 
  1611. * @return array 
  1612. */ 
  1613. private function get_downloads( $product ) { 
  1614.  
  1615. $downloads = array(); 
  1616.  
  1617. if ( $product->is_downloadable() ) { 
  1618.  
  1619. foreach ( $product->get_downloads() as $file_id => $file ) { 
  1620.  
  1621. $downloads[] = array( 
  1622. 'id' => $file_id, // do not cast as int as this is a hash 
  1623. 'name' => $file['name'],  
  1624. 'file' => $file['file'],  
  1625. ); 
  1626.  
  1627. return $downloads; 
  1628.  
  1629. /** 
  1630. * Get a listing of product attributes 
  1631. * 
  1632. * @since 2.4.0 
  1633. * @param string|null $fields fields to limit response to 
  1634. * @return array 
  1635. */ 
  1636. public function get_product_attributes( $fields = null ) { 
  1637. try { 
  1638. // Permissions check 
  1639. if ( ! current_user_can( 'manage_product_terms' ) ) { 
  1640. throw new WC_API_Exception( 'woocommerce_api_user_cannot_read_product_attributes', __( 'You do not have permission to read product attributes', 'woocommerce' ), 401 ); 
  1641.  
  1642. $product_attributes = array(); 
  1643. $attribute_taxonomies = wc_get_attribute_taxonomies(); 
  1644.  
  1645. foreach ( $attribute_taxonomies as $attribute ) { 
  1646. $product_attributes[] = array( 
  1647. 'id' => intval( $attribute->attribute_id ),  
  1648. 'name' => $attribute->attribute_label,  
  1649. 'slug' => wc_attribute_taxonomy_name( $attribute->attribute_name ),  
  1650. 'type' => $attribute->attribute_type,  
  1651. 'order_by' => $attribute->attribute_orderby,  
  1652. 'has_archives' => (bool) $attribute->attribute_public,  
  1653. ); 
  1654.  
  1655. return array( 'product_attributes' => apply_filters( 'woocommerce_api_product_attributes_response', $product_attributes, $attribute_taxonomies, $fields, $this ) ); 
  1656. } catch ( WC_API_Exception $e ) { 
  1657. return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) ); 
  1658.  
  1659. /** 
  1660. * Get the product attribute for the given ID 
  1661. * 
  1662. * @since 2.4.0 
  1663. * @param string $id product attribute term ID 
  1664. * @param string|null $fields fields to limit response to 
  1665. * @return array 
  1666. */ 
  1667. public function get_product_attribute( $id, $fields = null ) { 
  1668. global $wpdb; 
  1669.  
  1670. try { 
  1671. $id = absint( $id ); 
  1672.  
  1673. // Validate ID 
  1674. if ( empty( $id ) ) { 
  1675. throw new WC_API_Exception( 'woocommerce_api_invalid_product_attribute_id', __( 'Invalid product attribute ID', 'woocommerce' ), 400 ); 
  1676.  
  1677. // Permissions check 
  1678. if ( ! current_user_can( 'manage_product_terms' ) ) { 
  1679. throw new WC_API_Exception( 'woocommerce_api_user_cannot_read_product_categories', __( 'You do not have permission to read product attributes', 'woocommerce' ), 401 ); 
  1680.  
  1681. $attribute = $wpdb->get_row( $wpdb->prepare( " 
  1682. SELECT * 
  1683. FROM {$wpdb->prefix}woocommerce_attribute_taxonomies 
  1684. WHERE attribute_id = %d 
  1685. ", $id ) ); 
  1686.  
  1687. if ( is_wp_error( $attribute ) || is_null( $attribute ) ) { 
  1688. throw new WC_API_Exception( 'woocommerce_api_invalid_product_attribute_id', __( 'A product attribute with the provided ID could not be found', 'woocommerce' ), 404 ); 
  1689.  
  1690. $product_attribute = array( 
  1691. 'id' => intval( $attribute->attribute_id ),  
  1692. 'name' => $attribute->attribute_label,  
  1693. 'slug' => wc_attribute_taxonomy_name( $attribute->attribute_name ),  
  1694. 'type' => $attribute->attribute_type,  
  1695. 'order_by' => $attribute->attribute_orderby,  
  1696. 'has_archives' => (bool) $attribute->attribute_public,  
  1697. ); 
  1698.  
  1699. return array( 'product_attribute' => apply_filters( 'woocommerce_api_product_attribute_response', $product_attribute, $id, $fields, $attribute, $this ) ); 
  1700. } catch ( WC_API_Exception $e ) { 
  1701. return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) ); 
  1702.  
  1703. /** 
  1704. * Validate attribute data. 
  1705. * 
  1706. * @since 2.4.0 
  1707. * @param string $name 
  1708. * @param string $slug 
  1709. * @param string $type 
  1710. * @param string $order_by 
  1711. * @param bool $new_data 
  1712. * @return bool 
  1713. * @throws WC_API_Exception 
  1714. */ 
  1715. protected function validate_attribute_data( $name, $slug, $type, $order_by, $new_data = true ) { 
  1716. if ( empty( $name ) ) { 
  1717. throw new WC_API_Exception( 'woocommerce_api_missing_product_attribute_name', sprintf( __( 'Missing parameter %s', 'woocommerce' ), 'name' ), 400 ); 
  1718.  
  1719. if ( strlen( $slug ) >= 28 ) { 
  1720. throw new WC_API_Exception( 'woocommerce_api_invalid_product_attribute_slug_too_long', sprintf( __( 'Slug "%s" is too long (28 characters max). Shorten it, please.', 'woocommerce' ), $slug ), 400 ); 
  1721. } elseif ( wc_check_if_attribute_name_is_reserved( $slug ) ) { 
  1722. throw new WC_API_Exception( 'woocommerce_api_invalid_product_attribute_slug_reserved_name', sprintf( __( 'Slug "%s" is not allowed because it is a reserved term. Change it, please.', 'woocommerce' ), $slug ), 400 ); 
  1723. } elseif ( $new_data && taxonomy_exists( wc_attribute_taxonomy_name( $slug ) ) ) { 
  1724. throw new WC_API_Exception( 'woocommerce_api_invalid_product_attribute_slug_already_exists', sprintf( __( 'Slug "%s" is already in use. Change it, please.', 'woocommerce' ), $slug ), 400 ); 
  1725.  
  1726. // Validate the attribute type 
  1727. if ( ! in_array( wc_clean( $type ), array_keys( wc_get_attribute_types() ) ) ) { 
  1728. throw new WC_API_Exception( 'woocommerce_api_invalid_product_attribute_type', sprintf( __( 'Invalid product attribute type - the product attribute type must be any of these: %s', 'woocommerce' ), implode( ', ', array_keys( wc_get_attribute_types() ) ) ), 400 ); 
  1729.  
  1730. // Validate the attribute order by 
  1731. if ( ! in_array( wc_clean( $order_by ), array( 'menu_order', 'name', 'name_num', 'id' ) ) ) { 
  1732. throw new WC_API_Exception( 'woocommerce_api_invalid_product_attribute_order_by', sprintf( __( 'Invalid product attribute order_by type - the product attribute order_by type must be any of these: %s', 'woocommerce' ), implode( ', ', array( 'menu_order', 'name', 'name_num', 'id' ) ) ), 400 ); 
  1733.  
  1734. return true; 
  1735.  
  1736. /** 
  1737. * Create a new product attribute 
  1738. * 
  1739. * @since 2.4.0 
  1740. * @param array $data posted data 
  1741. * @return array 
  1742. */ 
  1743. public function create_product_attribute( $data ) { 
  1744. global $wpdb; 
  1745.  
  1746. try { 
  1747. if ( ! isset( $data['product_attribute'] ) ) { 
  1748. throw new WC_API_Exception( 'woocommerce_api_missing_product_attribute_data', sprintf( __( 'No %1$s data specified to create %1$s', 'woocommerce' ), 'product_attribute' ), 400 ); 
  1749.  
  1750. $data = $data['product_attribute']; 
  1751.  
  1752. // Check permissions 
  1753. if ( ! current_user_can( 'manage_product_terms' ) ) { 
  1754. throw new WC_API_Exception( 'woocommerce_api_user_cannot_create_product_attribute', __( 'You do not have permission to create product attributes', 'woocommerce' ), 401 ); 
  1755.  
  1756. $data = apply_filters( 'woocommerce_api_create_product_attribute_data', $data, $this ); 
  1757.  
  1758. if ( ! isset( $data['name'] ) ) { 
  1759. $data['name'] = ''; 
  1760.  
  1761. // Set the attribute slug 
  1762. if ( ! isset( $data['slug'] ) ) { 
  1763. $data['slug'] = wc_sanitize_taxonomy_name( stripslashes( $data['name'] ) ); 
  1764. } else { 
  1765. $data['slug'] = preg_replace( '/^pa\_/', '', wc_sanitize_taxonomy_name( stripslashes( $data['slug'] ) ) ); 
  1766.  
  1767. // Set attribute type when not sent 
  1768. if ( ! isset( $data['type'] ) ) { 
  1769. $data['type'] = 'select'; 
  1770.  
  1771. // Set order by when not sent 
  1772. if ( ! isset( $data['order_by'] ) ) { 
  1773. $data['order_by'] = 'menu_order'; 
  1774.  
  1775. // Validate the attribute data 
  1776. $this->validate_attribute_data( $data['name'], $data['slug'], $data['type'], $data['order_by'], true ); 
  1777.  
  1778. $insert = $wpdb->insert( 
  1779. $wpdb->prefix . 'woocommerce_attribute_taxonomies',  
  1780. array( 
  1781. 'attribute_label' => $data['name'],  
  1782. 'attribute_name' => $data['slug'],  
  1783. 'attribute_type' => $data['type'],  
  1784. 'attribute_orderby' => $data['order_by'],  
  1785. 'attribute_public' => isset( $data['has_archives'] ) && true === $data['has_archives'] ? 1 : 0,  
  1786. ),  
  1787. array( '%s', '%s', '%s', '%s', '%d' ) 
  1788. ); 
  1789.  
  1790. // Checks for an error in the product creation 
  1791. if ( is_wp_error( $insert ) ) { 
  1792. throw new WC_API_Exception( 'woocommerce_api_cannot_create_product_attribute', $insert->get_error_message(), 400 ); 
  1793.  
  1794. $id = $wpdb->insert_id; 
  1795.  
  1796. do_action( 'woocommerce_api_create_product_attribute', $id, $data ); 
  1797.  
  1798. // Clear transients 
  1799. delete_transient( 'wc_attribute_taxonomies' ); 
  1800.  
  1801. $this->server->send_status( 201 ); 
  1802.  
  1803. return $this->get_product_attribute( $id ); 
  1804. } catch ( WC_API_Exception $e ) { 
  1805. return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) ); 
  1806.  
  1807. /** 
  1808. * Edit a product attribute 
  1809. * 
  1810. * @since 2.4.0 
  1811. * @param int $id the attribute ID 
  1812. * @param array $data 
  1813. * @return array 
  1814. */ 
  1815. public function edit_product_attribute( $id, $data ) { 
  1816. global $wpdb; 
  1817.  
  1818. try { 
  1819. if ( ! isset( $data['product_attribute'] ) ) { 
  1820. throw new WC_API_Exception( 'woocommerce_api_missing_product_attribute_data', sprintf( __( 'No %1$s data specified to edit %1$s', 'woocommerce' ), 'product_attribute' ), 400 ); 
  1821.  
  1822. $id = absint( $id ); 
  1823. $data = $data['product_attribute']; 
  1824.  
  1825. // Check permissions 
  1826. if ( ! current_user_can( 'manage_product_terms' ) ) { 
  1827. throw new WC_API_Exception( 'woocommerce_api_user_cannot_edit_product_attribute', __( 'You do not have permission to edit product attributes', 'woocommerce' ), 401 ); 
  1828.  
  1829. $data = apply_filters( 'woocommerce_api_edit_product_attribute_data', $data, $this ); 
  1830. $attribute = $this->get_product_attribute( $id ); 
  1831.  
  1832. if ( is_wp_error( $attribute ) ) { 
  1833. return $attribute; 
  1834.  
  1835. $attribute_name = isset( $data['name'] ) ? $data['name'] : $attribute['product_attribute']['name']; 
  1836. $attribute_type = isset( $data['type'] ) ? $data['type'] : $attribute['product_attribute']['type']; 
  1837. $attribute_order_by = isset( $data['order_by'] ) ? $data['order_by'] : $attribute['product_attribute']['order_by']; 
  1838.  
  1839. if ( isset( $data['slug'] ) ) { 
  1840. $attribute_slug = wc_sanitize_taxonomy_name( stripslashes( $data['slug'] ) ); 
  1841. } else { 
  1842. $attribute_slug = $attribute['product_attribute']['slug']; 
  1843. $attribute_slug = preg_replace( '/^pa\_/', '', $attribute_slug ); 
  1844.  
  1845. if ( isset( $data['has_archives'] ) ) { 
  1846. $attribute_public = true === $data['has_archives'] ? 1 : 0; 
  1847. } else { 
  1848. $attribute_public = $attribute['product_attribute']['has_archives']; 
  1849.  
  1850. // Validate the attribute data 
  1851. $this->validate_attribute_data( $attribute_name, $attribute_slug, $attribute_type, $attribute_order_by, false ); 
  1852.  
  1853. $update = $wpdb->update( 
  1854. $wpdb->prefix . 'woocommerce_attribute_taxonomies',  
  1855. array( 
  1856. 'attribute_label' => $attribute_name,  
  1857. 'attribute_name' => $attribute_slug,  
  1858. 'attribute_type' => $attribute_type,  
  1859. 'attribute_orderby' => $attribute_order_by,  
  1860. 'attribute_public' => $attribute_public,  
  1861. ),  
  1862. array( 'attribute_id' => $id ),  
  1863. array( '%s', '%s', '%s', '%s', '%d' ),  
  1864. array( '%d' ) 
  1865. ); 
  1866.  
  1867. // Checks for an error in the product creation 
  1868. if ( false === $update ) { 
  1869. throw new WC_API_Exception( 'woocommerce_api_cannot_edit_product_attribute', __( 'Could not edit the attribute', 'woocommerce' ), 400 ); 
  1870.  
  1871. do_action( 'woocommerce_api_edit_product_attribute', $id, $data ); 
  1872.  
  1873. // Clear transients 
  1874. delete_transient( 'wc_attribute_taxonomies' ); 
  1875.  
  1876. return $this->get_product_attribute( $id ); 
  1877. } catch ( WC_API_Exception $e ) { 
  1878. return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) ); 
  1879.  
  1880. /** 
  1881. * Delete a product attribute 
  1882. * 
  1883. * @since 2.4.0 
  1884. * @param int $id the product attribute ID 
  1885. * @return array 
  1886. */ 
  1887. public function delete_product_attribute( $id ) { 
  1888. global $wpdb; 
  1889.  
  1890. try { 
  1891. // Check permissions 
  1892. if ( ! current_user_can( 'manage_product_terms' ) ) { 
  1893. throw new WC_API_Exception( 'woocommerce_api_user_cannot_delete_product_attribute', __( 'You do not have permission to delete product attributes', 'woocommerce' ), 401 ); 
  1894.  
  1895. $id = absint( $id ); 
  1896.  
  1897. $attribute_name = $wpdb->get_var( $wpdb->prepare( " 
  1898. SELECT attribute_name 
  1899. FROM {$wpdb->prefix}woocommerce_attribute_taxonomies 
  1900. WHERE attribute_id = %d 
  1901. ", $id ) ); 
  1902.  
  1903. if ( is_null( $attribute_name ) ) { 
  1904. throw new WC_API_Exception( 'woocommerce_api_invalid_product_attribute_id', __( 'A product attribute with the provided ID could not be found', 'woocommerce' ), 404 ); 
  1905.  
  1906. $deleted = $wpdb->delete( 
  1907. $wpdb->prefix . 'woocommerce_attribute_taxonomies',  
  1908. array( 'attribute_id' => $id ),  
  1909. array( '%d' ) 
  1910. ); 
  1911.  
  1912. if ( false === $deleted ) { 
  1913. throw new WC_API_Exception( 'woocommerce_api_cannot_delete_product_attribute', __( 'Could not delete the attribute', 'woocommerce' ), 401 ); 
  1914.  
  1915. $taxonomy = wc_attribute_taxonomy_name( $attribute_name ); 
  1916.  
  1917. if ( taxonomy_exists( $taxonomy ) ) { 
  1918. $terms = get_terms( $taxonomy, 'orderby=name&hide_empty=0' ); 
  1919. foreach ( $terms as $term ) { 
  1920. wp_delete_term( $term->term_id, $taxonomy ); 
  1921.  
  1922. do_action( 'woocommerce_attribute_deleted', $id, $attribute_name, $taxonomy ); 
  1923. do_action( 'woocommerce_api_delete_product_attribute', $id, $this ); 
  1924.  
  1925. // Clear transients 
  1926. delete_transient( 'wc_attribute_taxonomies' ); 
  1927.  
  1928. return array( 'message' => sprintf( __( 'Deleted %s', 'woocommerce' ), 'product_attribute' ) ); 
  1929. } catch ( WC_API_Exception $e ) { 
  1930. return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) ); 
  1931.  
  1932. /** 
  1933. * Get product by SKU 
  1934. * 
  1935. * @deprecated 2.4.0 
  1936. * 
  1937. * @since 2.3.0 
  1938. * @param int $sku the product SKU 
  1939. * @param string $fields 
  1940. * @return array 
  1941. */ 
  1942. public function get_product_by_sku( $sku, $fields = null ) { 
  1943. try { 
  1944. $id = wc_get_product_id_by_sku( $sku ); 
  1945.  
  1946. if ( empty( $id ) ) { 
  1947. throw new WC_API_Exception( 'woocommerce_api_invalid_product_sku', __( 'Invalid product SKU', 'woocommerce' ), 404 ); 
  1948.  
  1949. return $this->get_product( $id, $fields ); 
  1950. } catch ( WC_API_Exception $e ) { 
  1951. return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) ); 
  1952.  
  1953. /** 
  1954. * Clear product 
  1955. */ 
  1956. protected function clear_product( $product_id ) { 
  1957. if ( ! is_numeric( $product_id ) || 0 >= $product_id ) { 
  1958. return; 
  1959.  
  1960. // Delete product attachments 
  1961. $attachments = get_children( array( 
  1962. 'post_parent' => $product_id,  
  1963. 'post_status' => 'any',  
  1964. 'post_type' => 'attachment',  
  1965. ) ); 
  1966.  
  1967. foreach ( (array) $attachments as $attachment ) { 
  1968. wp_delete_attachment( $attachment->ID, true ); 
  1969.  
  1970. // Delete product 
  1971. $product = wc_get_product( $product_id ); 
  1972. $product->delete(); 
  1973.  
  1974. /** 
  1975. * Bulk update or insert products 
  1976. * Accepts an array with products in the formats supported by 
  1977. * WC_API_Products->create_product() and WC_API_Products->edit_product() 
  1978. * 
  1979. * @since 2.4.0 
  1980. * @param array $data 
  1981. * @return array 
  1982. */ 
  1983. public function bulk( $data ) { 
  1984.  
  1985. try { 
  1986. if ( ! isset( $data['products'] ) ) { 
  1987. throw new WC_API_Exception( 'woocommerce_api_missing_products_data', sprintf( __( 'No %1$s data specified to create/edit %1$s', 'woocommerce' ), 'products' ), 400 ); 
  1988.  
  1989. $data = $data['products']; 
  1990. $limit = apply_filters( 'woocommerce_api_bulk_limit', 100, 'products' ); 
  1991.  
  1992. // Limit bulk operation 
  1993. if ( count( $data ) > $limit ) { 
  1994. throw new WC_API_Exception( 'woocommerce_api_products_request_entity_too_large', sprintf( __( 'Unable to accept more than %s items for this request.', 'woocommerce' ), $limit ), 413 ); 
  1995.  
  1996. $products = array(); 
  1997.  
  1998. foreach ( $data as $_product ) { 
  1999. $product_id = 0; 
  2000. $product_sku = ''; 
  2001.  
  2002. // Try to get the product ID 
  2003. if ( isset( $_product['id'] ) ) { 
  2004. $product_id = intval( $_product['id'] ); 
  2005.  
  2006. if ( ! $product_id && isset( $_product['sku'] ) ) { 
  2007. $product_sku = wc_clean( $_product['sku'] ); 
  2008. $product_id = wc_get_product_id_by_sku( $product_sku ); 
  2009.  
  2010. if ( $product_id ) { 
  2011.  
  2012. // Product exists / edit product 
  2013. $edit = $this->edit_product( $product_id, array( 'product' => $_product ) ); 
  2014.  
  2015. if ( is_wp_error( $edit ) ) { 
  2016. $products[] = array( 
  2017. 'id' => $product_id,  
  2018. 'sku' => $product_sku,  
  2019. 'error' => array( 'code' => $edit->get_error_code(), 'message' => $edit->get_error_message() ),  
  2020. ); 
  2021. } else { 
  2022. $products[] = $edit['product']; 
  2023. } else { 
  2024.  
  2025. // Product don't exists / create product 
  2026. $new = $this->create_product( array( 'product' => $_product ) ); 
  2027.  
  2028. if ( is_wp_error( $new ) ) { 
  2029. $products[] = array( 
  2030. 'id' => $product_id,  
  2031. 'sku' => $product_sku,  
  2032. 'error' => array( 'code' => $new->get_error_code(), 'message' => $new->get_error_message() ),  
  2033. ); 
  2034. } else { 
  2035. $products[] = $new['product']; 
  2036.  
  2037. return array( 'products' => apply_filters( 'woocommerce_api_products_bulk_response', $products, $this ) ); 
  2038. } catch ( WC_API_Exception $e ) { 
  2039. return new WP_Error( $e->getErrorCode(), $e->getMessage(), array( 'status' => $e->getCode() ) ); 
.