class-wc-admin-importers.php 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. <?php
  2. /**
  3. * Init WooCommerce data importers.
  4. *
  5. * @package WooCommerce/Admin
  6. */
  7. defined( 'ABSPATH' ) || exit;
  8. /**
  9. * WC_Admin_Importers Class.
  10. */
  11. class WC_Admin_Importers {
  12. /**
  13. * Array of importer IDs.
  14. *
  15. * @var string[]
  16. */
  17. protected $importers = array();
  18. /**
  19. * Constructor.
  20. */
  21. public function __construct() {
  22. if ( ! $this->import_allowed() ) {
  23. return;
  24. }
  25. add_action( 'admin_menu', array( $this, 'add_to_menus' ) );
  26. add_action( 'admin_init', array( $this, 'register_importers' ) );
  27. add_action( 'admin_head', array( $this, 'hide_from_menus' ) );
  28. add_action( 'admin_enqueue_scripts', array( $this, 'admin_scripts' ) );
  29. add_action( 'wp_ajax_woocommerce_do_ajax_product_import', array( $this, 'do_ajax_product_import' ) );
  30. // Register WooCommerce importers.
  31. $this->importers['product_importer'] = array(
  32. 'menu' => 'edit.php?post_type=product',
  33. 'name' => __( 'Product Import', 'woocommerce' ),
  34. 'capability' => 'import',
  35. 'callback' => array( $this, 'product_importer' ),
  36. );
  37. }
  38. /**
  39. * Return true if WooCommerce imports are allowed for current user, false otherwise.
  40. *
  41. * @return bool Whether current user can perform imports.
  42. */
  43. protected function import_allowed() {
  44. return current_user_can( 'edit_products' ) && current_user_can( 'import' );
  45. }
  46. /**
  47. * Add menu items for our custom importers.
  48. */
  49. public function add_to_menus() {
  50. foreach ( $this->importers as $id => $importer ) {
  51. add_submenu_page( $importer['menu'], $importer['name'], $importer['name'], $importer['capability'], $id, $importer['callback'] );
  52. }
  53. }
  54. /**
  55. * Hide menu items from view so the pages exist, but the menu items do not.
  56. */
  57. public function hide_from_menus() {
  58. global $submenu;
  59. foreach ( $this->importers as $id => $importer ) {
  60. if ( isset( $submenu[ $importer['menu'] ] ) ) {
  61. foreach ( $submenu[ $importer['menu'] ] as $key => $menu ) {
  62. if ( $id === $menu[2] ) {
  63. unset( $submenu[ $importer['menu'] ][ $key ] );
  64. }
  65. }
  66. }
  67. }
  68. }
  69. /**
  70. * Register importer scripts.
  71. */
  72. public function admin_scripts() {
  73. $suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min';
  74. wp_register_script( 'wc-product-import', WC()->plugin_url() . '/assets/js/admin/wc-product-import' . $suffix . '.js', array( 'jquery' ), WC_VERSION );
  75. }
  76. /**
  77. * The product importer.
  78. *
  79. * This has a custom screen - the Tools > Import item is a placeholder.
  80. * If we're on that screen, redirect to the custom one.
  81. */
  82. public function product_importer() {
  83. if ( defined( 'WP_LOAD_IMPORTERS' ) ) {
  84. wp_safe_redirect( admin_url( 'edit.php?post_type=product&page=product_importer' ) );
  85. exit;
  86. }
  87. include_once WC_ABSPATH . 'includes/import/class-wc-product-csv-importer.php';
  88. include_once WC_ABSPATH . 'includes/admin/importers/class-wc-product-csv-importer-controller.php';
  89. $importer = new WC_Product_CSV_Importer_Controller();
  90. $importer->dispatch();
  91. }
  92. /**
  93. * Register WordPress based importers.
  94. */
  95. public function register_importers() {
  96. if ( defined( 'WP_LOAD_IMPORTERS' ) ) {
  97. add_action( 'import_start', array( $this, 'post_importer_compatibility' ) );
  98. register_importer( 'woocommerce_product_csv', __( 'WooCommerce products (CSV)', 'woocommerce' ), __( 'Import <strong>products</strong> to your store via a csv file.', 'woocommerce' ), array( $this, 'product_importer' ) );
  99. register_importer( 'woocommerce_tax_rate_csv', __( 'WooCommerce tax rates (CSV)', 'woocommerce' ), __( 'Import <strong>tax rates</strong> to your store via a csv file.', 'woocommerce' ), array( $this, 'tax_rates_importer' ) );
  100. }
  101. }
  102. /**
  103. * The tax rate importer which extends WP_Importer.
  104. */
  105. public function tax_rates_importer() {
  106. require_once ABSPATH . 'wp-admin/includes/import.php';
  107. if ( ! class_exists( 'WP_Importer' ) ) {
  108. $class_wp_importer = ABSPATH . 'wp-admin/includes/class-wp-importer.php';
  109. if ( file_exists( $class_wp_importer ) ) {
  110. require $class_wp_importer;
  111. }
  112. }
  113. require dirname( __FILE__ ) . '/importers/class-wc-tax-rate-importer.php';
  114. $importer = new WC_Tax_Rate_Importer();
  115. $importer->dispatch();
  116. }
  117. /**
  118. * When running the WP XML importer, ensure attributes exist.
  119. *
  120. * WordPress import should work - however, it fails to import custom product attribute taxonomies.
  121. * This code grabs the file before it is imported and ensures the taxonomies are created.
  122. */
  123. public function post_importer_compatibility() {
  124. global $wpdb;
  125. if ( empty( $_POST['import_id'] ) || ! class_exists( 'WXR_Parser' ) ) { // PHPCS: input var ok, CSRF ok.
  126. return;
  127. }
  128. $id = absint( $_POST['import_id'] ); // PHPCS: input var ok.
  129. $file = get_attached_file( $id );
  130. $parser = new WXR_Parser();
  131. $import_data = $parser->parse( $file );
  132. if ( isset( $import_data['posts'] ) && ! empty( $import_data['posts'] ) ) {
  133. foreach ( $import_data['posts'] as $post ) {
  134. if ( 'product' === $post['post_type'] && ! empty( $post['terms'] ) ) {
  135. foreach ( $post['terms'] as $term ) {
  136. if ( strstr( $term['domain'], 'pa_' ) ) {
  137. if ( ! taxonomy_exists( $term['domain'] ) ) {
  138. $attribute_name = wc_sanitize_taxonomy_name( str_replace( 'pa_', '', $term['domain'] ) );
  139. // Create the taxonomy.
  140. if ( ! in_array( $attribute_name, wc_get_attribute_taxonomies(), true ) ) {
  141. wc_create_attribute(
  142. array(
  143. 'name' => $attribute_name,
  144. 'slug' => $attribute_name,
  145. 'type' => 'select',
  146. 'order_by' => 'menu_order',
  147. 'has_archives' => false,
  148. )
  149. );
  150. }
  151. // Register the taxonomy now so that the import works!
  152. register_taxonomy(
  153. $term['domain'],
  154. apply_filters( 'woocommerce_taxonomy_objects_' . $term['domain'], array( 'product' ) ),
  155. apply_filters(
  156. 'woocommerce_taxonomy_args_' . $term['domain'], array(
  157. 'hierarchical' => true,
  158. 'show_ui' => false,
  159. 'query_var' => true,
  160. 'rewrite' => false,
  161. )
  162. )
  163. );
  164. }
  165. }
  166. }
  167. }
  168. }
  169. }
  170. }
  171. /**
  172. * Ajax callback for importing one batch of products from a CSV.
  173. */
  174. public function do_ajax_product_import() {
  175. global $wpdb;
  176. check_ajax_referer( 'wc-product-import', 'security' );
  177. if ( ! $this->import_allowed() || ! isset( $_POST['file'] ) ) { // PHPCS: input var ok.
  178. wp_send_json_error( array( 'message' => __( 'Insufficient privileges to import products.', 'woocommerce' ) ) );
  179. }
  180. include_once WC_ABSPATH . 'includes/admin/importers/class-wc-product-csv-importer-controller.php';
  181. include_once WC_ABSPATH . 'includes/import/class-wc-product-csv-importer.php';
  182. $file = wc_clean( wp_unslash( $_POST['file'] ) ); // PHPCS: input var ok.
  183. $params = array(
  184. 'delimiter' => ! empty( $_POST['delimiter'] ) ? wc_clean( wp_unslash( $_POST['delimiter'] ) ) : ',', // PHPCS: input var ok.
  185. 'start_pos' => isset( $_POST['position'] ) ? absint( $_POST['position'] ) : 0, // PHPCS: input var ok.
  186. 'mapping' => isset( $_POST['mapping'] ) ? (array) wc_clean( wp_unslash( $_POST['mapping'] ) ) : array(), // PHPCS: input var ok.
  187. 'update_existing' => isset( $_POST['update_existing'] ) ? (bool) $_POST['update_existing'] : false, // PHPCS: input var ok.
  188. 'lines' => apply_filters( 'woocommerce_product_import_batch_size', 30 ),
  189. 'parse' => true,
  190. );
  191. // Log failures.
  192. if ( 0 !== $params['start_pos'] ) {
  193. $error_log = array_filter( (array) get_user_option( 'product_import_error_log' ) );
  194. } else {
  195. $error_log = array();
  196. }
  197. $importer = WC_Product_CSV_Importer_Controller::get_importer( $file, $params );
  198. $results = $importer->import();
  199. $percent_complete = $importer->get_percent_complete();
  200. $error_log = array_merge( $error_log, $results['failed'], $results['skipped'] );
  201. update_user_option( get_current_user_id(), 'product_import_error_log', $error_log );
  202. if ( 100 === $percent_complete ) {
  203. // @codingStandardsIgnoreStart.
  204. $wpdb->delete( $wpdb->postmeta, array( 'meta_key' => '_original_id' ) );
  205. $wpdb->delete( $wpdb->posts, array(
  206. 'post_type' => 'product',
  207. 'post_status' => 'importing',
  208. ) );
  209. $wpdb->delete( $wpdb->posts, array(
  210. 'post_type' => 'product_variation',
  211. 'post_status' => 'importing',
  212. ) );
  213. // @codingStandardsIgnoreEnd.
  214. // Clean up orphaned data.
  215. $wpdb->query( "
  216. DELETE {$wpdb->posts}.* FROM {$wpdb->posts}
  217. LEFT JOIN {$wpdb->posts} wp ON wp.ID = {$wpdb->posts}.post_parent
  218. WHERE wp.ID IS NULL AND {$wpdb->posts}.post_type = 'product_variation'
  219. " );
  220. $wpdb->query( "
  221. DELETE {$wpdb->postmeta}.* FROM {$wpdb->postmeta}
  222. LEFT JOIN {$wpdb->posts} wp ON wp.ID = {$wpdb->postmeta}.post_id
  223. WHERE wp.ID IS NULL
  224. " );
  225. // @codingStandardsIgnoreStart.
  226. $wpdb->query( "
  227. DELETE tr.* FROM {$wpdb->term_relationships} tr
  228. LEFT JOIN {$wpdb->posts} wp ON wp.ID = tr.object_id
  229. LEFT JOIN {$wpdb->term_taxonomy} tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
  230. WHERE wp.ID IS NULL
  231. AND tt.taxonomy IN ( '" . implode( "','", array_map( 'esc_sql', get_object_taxonomies( 'product' ) ) ) . "' )
  232. " );
  233. // @codingStandardsIgnoreEnd.
  234. // Send success.
  235. wp_send_json_success(
  236. array(
  237. 'position' => 'done',
  238. 'percentage' => 100,
  239. 'url' => add_query_arg( array( 'nonce' => wp_create_nonce( 'product-csv' ) ), admin_url( 'edit.php?post_type=product&page=product_importer&step=done' ) ),
  240. 'imported' => count( $results['imported'] ),
  241. 'failed' => count( $results['failed'] ),
  242. 'updated' => count( $results['updated'] ),
  243. 'skipped' => count( $results['skipped'] ),
  244. )
  245. );
  246. } else {
  247. wp_send_json_success(
  248. array(
  249. 'position' => $importer->get_file_position(),
  250. 'percentage' => $percent_complete,
  251. 'imported' => count( $results['imported'] ),
  252. 'failed' => count( $results['failed'] ),
  253. 'updated' => count( $results['updated'] ),
  254. 'skipped' => count( $results['skipped'] ),
  255. )
  256. );
  257. }
  258. }
  259. }
  260. new WC_Admin_Importers();