PageRenderTime 55ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-content/plugins/woocommerce-csvimport/include/woocommerce-csvimport-functions.php

https://bitbucket.org/sanders_nick/my-maxi-skirt
PHP | 340 lines | 235 code | 52 blank | 53 comment | 66 complexity | 3274198a7736d15b2608b7ab40988d24 MD5 | raw file
Possible License(s): GPL-2.0, BSD-3-Clause, AGPL-1.0, GPL-3.0, LGPL-2.1
  1. <?php
  2. function wppcsv_handle_csv_import_random () {
  3. try {
  4. //create temp directory
  5. $upload_dir = wp_upload_dir();
  6. $dir = $upload_dir['basedir'] .'/csvimport/' . woocsv_random_string() . '/';
  7. mkdir($dir);
  8. //handle upload
  9. if (!woocsv_handle_uploads ($dir))
  10. throw new Exception(__('Er is iets mis gegaan bij het uploaden'));
  11. $are_there_csv_files = glob($dir.'*.csv');
  12. if (count($are_there_csv_files) != 1) throw new Exception(__('Er is geen of meerdere csv bestand(en) gevonden'));
  13. //run the magic
  14. $result = woocsv_import_products_from_csv ($are_there_csv_files[0],$dir);
  15. } catch (Exception $e) {
  16. woocsv_admin_notice ('No CSV file is found');
  17. }
  18. }
  19. function woocsv_handle_zip_import () {
  20. //create temp directory
  21. try {
  22. $upload_dir = wp_upload_dir();
  23. $dir = $upload_dir['basedir'] .'/' . woocsv_random_string() . '/';
  24. mkdir($dir);
  25. $file = $_FILES['zip_file']['name'];
  26. move_uploaded_file( $_FILES['zip_file']['tmp_name'], $dir.$file );
  27. $zip = new ZipArchive;
  28. if ($zip->open($dir.$file) === TRUE) {
  29. $zip->extractTo($dir);
  30. $zip->close();
  31. } else throw new Exception(__('Kan de zip file niet uitpakken'));
  32. $are_there_csv_files = glob($dir.'*.csv');
  33. if (count($are_there_csv_files) != 1) throw new Exception(__('Er is geen of meerdere csv bestand(en) gevonden'));
  34. //run the magic
  35. $result = woocsv_import_products_from_csv ($are_there_csv_files[0],$dir);
  36. }
  37. catch (Exception $e) {
  38. woocsv_admin_notice ($e->getMessage());
  39. }
  40. }
  41. function woocsv_handle_fixed_import () {
  42. global $woocsv_options;
  43. //get the upload dir
  44. $upload_dir = wp_upload_dir();
  45. $dir = $upload_dir['basedir'] .$_POST['fixed_dir'] .'/';
  46. try {
  47. //check the existence of the directory
  48. if (!glob($dir)) throw new Exception(__('De directory bestaat niet'));
  49. //check to see if there are files in
  50. if ( count( scandir( $dir ) ) <= 2) throw new Exception(__('Er zijn geen bestanden aanwezig in de directory'));
  51. //now check to see if there is a csv in there
  52. $are_there_csv_files = glob($dir.'*.csv');
  53. if (count($are_there_csv_files) != 1) throw new Exception(__('Er is geen of meerdere csv bestand(en) gevonden'));
  54. //run the magic
  55. if ($woocsv_options['use_schedule_event'] == 0) {
  56. $result = woocsv_import_products_from_csv ($are_there_csv_files[0],$dir);
  57. } else {
  58. wp_schedule_single_event(time()-1, 'woocsv_schedule_import',array ($are_there_csv_files,$dir));
  59. }
  60. } catch (Exception $e) {
  61. woocsv_admin_notice ($e->getMessage());
  62. }
  63. }
  64. function woocsv_schedule_import($are_there_csv_files,$dir) {
  65. woocsv_import_products_from_csv ($are_there_csv_files[0],$dir);
  66. }
  67. add_action('woocsv_schedule_import','woocsv_schedule_import');
  68. //import the products
  69. function woocsv_import_products_from_csv ($file,$dir) {
  70. global $wpdb;
  71. $woocsv_options = get_option('csvimport-options');
  72. $fieldseperator = (isset($woocsv_options['fieldseperator'])) ? $woocsv_options['fieldseperator'] : ',';
  73. set_time_limit(0);
  74. $row = 0;
  75. if ( $woocsv_options['auto_detect_line_endings'] == 1 )
  76. ini_set('auto_detect_line_endings', true);
  77. if ($handle = fopen($file, 'r') == FALSE) throw new Exception(__('Can not open file!'));
  78. $handle = fopen($file, 'r');
  79. $csvcontent = '';
  80. while (($line = fgetcsv($handle,0,$woocsv_options['fieldseperator'])) !== FALSE) {
  81. if ($row <> 0 ) $csvcontent[] = $line;
  82. $row ++;
  83. }
  84. fclose($handle);
  85. if (!$csvcontent) {
  86. woocsv_admin_notice('No content in csv....check it (also the line endings!)');
  87. exit;
  88. }
  89. $content = $csvcontent;
  90. /*
  91. 0 title,
  92. 1 description,
  93. 2 short_description,
  94. 3 category
  95. 4 stock,
  96. 5 price,
  97. 6 regular_price,
  98. 7 sales_price,
  99. 8 weight,
  100. 9 length,
  101. 10 width,
  102. 11 height,
  103. 12 sku,
  104. 13 picture
  105. 14 tags
  106. 15 tax status ( taxable, shipping, none )
  107. 16 tax class
  108. */
  109. foreach ( $content as $data ) {
  110. $num = count($data);
  111. $row ++;
  112. $my_product = array(
  113. 'post_title' => wp_strip_all_tags( $data[0] ),
  114. 'post_content' => $data[1],
  115. 'post_excerpt' => $data[2],
  116. 'post_status' => 'publish' ,
  117. 'post_type' => 'product',
  118. );
  119. //check to see if the product already exists and add the ID if true
  120. $product_id = $wpdb->get_var($wpdb->prepare("SELECT post_id FROM $wpdb->postmeta
  121. WHERE meta_key='_sku' AND meta_value='%s' LIMIT 1", $data[12] ));
  122. ($product_id) ? $my_product['ID'] = $product_id : $my_product['ID'] = false;
  123. //now we create the product...ig the id is there is will update the product else it will make a new
  124. // wordpress 3.5 not allows anymore to use wp_update_post to insert as well!
  125. if (!$product_id)
  126. $post_id = wp_insert_post($my_product);
  127. else
  128. $post_id = wp_update_post($my_product);
  129. //set the attributes etc
  130. if ( isset($data[4]) && $data[4] )
  131. update_post_meta( $post_id, '_stock', $data[4] );
  132. //set the price and replace , by . if set
  133. if (isset($data[5]) && $data[5] ) {
  134. if ($woocsv_options['change_comma_to_dot'] == 1) $data[5] = str_replace(',', '.', $data[5]);
  135. update_post_meta( $post_id, '_price', $data[5] );
  136. }
  137. if ( isset($data[6]) && $data[6] ) {
  138. if ($woocsv_options['change_comma_to_dot'] == 1) $data[6] = str_replace(',', '.', $data[6]);
  139. update_post_meta( $post_id, '_regular_price', $data[6] );
  140. }
  141. if (isset($data[7]) && $data[7] ) {
  142. if ($woocsv_options['change_comma_to_dot'] == 1) $data[7] = str_replace(',', '.', $data[7]);
  143. update_post_meta( $post_id, '_sale_price', $data[7] );
  144. }
  145. //end prices
  146. //set the weight
  147. if (isset($data[8]) && $data[8])
  148. update_post_meta( $post_id, '_weight', $data[8] );
  149. //set the length
  150. if (isset($data[9]) && $data[9])
  151. update_post_meta( $post_id, '_length', $data[9] );
  152. //set the height
  153. if (isset($data[10]) && $data[10] )
  154. update_post_meta( $post_id, '_width', $data[10] );
  155. //set the height
  156. if (isset($data[12]) && $data[11] )
  157. update_post_meta( $post_id, '_height', $data[11] );
  158. //set the SKU
  159. if (isset($data[12]) && $data[12] )
  160. update_post_meta( $post_id, '_sku', $data[12] );
  161. update_post_meta( $post_id, '_manage_stock', 'yes' );
  162. update_post_meta( $post_id, '_visibility', 'visible' );
  163. //tax status taxable, shipping, none
  164. $tax_status = array ('taxable', 'shipping', 'none');
  165. if (isset($data[15]) && $data[15]) {
  166. //check if the data is in the array
  167. if (in_array($data[15], $tax_status))
  168. update_post_meta( $post_id, '_tax_status', $data[15] );
  169. }
  170. //tax class
  171. if (isset($data[16]) && $data[16])
  172. update_post_meta( $post_id, '_tax_class', $data[16] );
  173. //link the product to the category
  174. $cats = explode ( '|', $data[3] );
  175. foreach ($cats as $cat){
  176. $cat_taxs = explode( '->', $cat );
  177. $parent = false;
  178. foreach ( $cat_taxs as $cat_tax)
  179. {
  180. $new_cat = term_exists( $cat_tax, 'product_cat' );
  181. if ( ! is_array( $new_cat ) ) {
  182. $new_cat = wp_insert_term( $cat_tax, 'product_cat', array( 'slug' => $cat_tax, 'parent'=> $parent) );
  183. }
  184. $x = wp_set_object_terms( $post_id, (int)$new_cat['term_id'], 'product_cat', true );
  185. $parent = $new_cat['term_id'];
  186. //check out http://wordpress.stackexchange.com/questions/24498/wp-insert-term-parent-child-problem
  187. delete_option("product_cat_children");
  188. }
  189. unset($parent);
  190. }
  191. //handle tags
  192. if ( isset( $data[14] )){
  193. $tags = explode('|', $data[14]);
  194. wp_set_object_terms( $post_id, $tags, 'product_tag',true );
  195. }
  196. //get picture if there is one and add it as featured image
  197. if ( isset( $data[13] )) {
  198. woocsv_add_featured_image ( $post_id , $data[13], $dir );
  199. }
  200. }
  201. }
  202. function woocsv_add_featured_image($post_id,$image_array,$dir) {
  203. $options = get_option('csvimport-options');
  204. $upload_dir = wp_upload_dir();
  205. //delete images
  206. if ($options['deleteimages'] == 1) {
  207. //get the images
  208. $attachments = get_posts( array(
  209. 'post_type' => 'attachment',
  210. 'post_parent' => $post_id,
  211. ));
  212. foreach ($attachments as $attachment) {
  213. wp_delete_attachment ($attachment->ID);
  214. }
  215. }
  216. $images = explode('|', $image_array);
  217. if (count($images) > 0 && $images[0] !== "" ) {
  218. foreach ($images as $image) {
  219. if ( woocsv_isvalidurl( $image ) ) {
  220. $image_data = @file_get_contents($image);
  221. } else {
  222. $image_data = @file_get_contents($dir.$image);
  223. }
  224. if ( $image_data !== false ) {
  225. $filename = basename($image);
  226. if(wp_mkdir_p($upload_dir['path']))
  227. $file = $upload_dir['path'] . '/' . $filename;
  228. else
  229. $file = $upload_dir['basedir'] . '/' . $filename;
  230. if (file_put_contents($file, $image_data)) {
  231. $wp_filetype = wp_check_filetype($filename, null );
  232. $attachment = array(
  233. 'post_mime_type' => $wp_filetype['type'],
  234. 'post_title' => sanitize_file_name($filename),
  235. 'post_content' => '',
  236. 'post_status' => 'inherit'
  237. );
  238. $attach_id = wp_insert_attachment( $attachment, $file, $post_id );
  239. require_once(ABSPATH . 'wp-admin/includes/image.php');
  240. $attach_data = wp_generate_attachment_metadata( $attach_id, $file );
  241. wp_update_attachment_metadata( $attach_id, $attach_data );
  242. set_post_thumbnail( $post_id, $attach_id );
  243. }
  244. }
  245. }
  246. }
  247. }
  248. function woocsv_admin_notice($message=''){
  249. if ($message)
  250. echo '<div class="error"><p>'.$message.'</p></div>';
  251. }
  252. //well this doed what is does....create a reandom string
  253. function woocsv_random_string($length = 10) {
  254. $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVW';
  255. $string = '';
  256. for ($p = 0; $p < $length; $p++) {
  257. $string .= $characters[mt_rand(0, strlen($characters))];
  258. }
  259. return $string;
  260. }
  261. function woocsv_get_normalized_files()
  262. {
  263. $newfiles = array();
  264. foreach($_FILES as $fieldname => $fieldvalue)
  265. foreach($fieldvalue as $paramname => $paramvalue)
  266. foreach((array)$paramvalue as $index => $value)
  267. $newfiles[$fieldname][$index][$paramname] = $value;
  268. return $newfiles;
  269. }
  270. //handle file uploads
  271. function woocsv_handle_uploads ( $dir ){
  272. try {
  273. $files = woocsv_get_normalized_files();
  274. foreach ($files['all_files'] as $file) {
  275. $from_location = $file['tmp_name'];
  276. $to_location = $dir . $file['name'];
  277. //check if file is csv or jpg
  278. move_uploaded_file($from_location, $to_location);
  279. }
  280. return true;
  281. } catch (MyException $e) {
  282. return false;
  283. }
  284. }
  285. function woocsv_isvalidurl($url)
  286. {
  287. return preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $url);
  288. }