Aucune description

class-wc-admin-importers.php 10KB

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