· 7 years ago · Jul 08, 2018, 07:26 PM
1<?php
2/*
3Plugin Name: WooCommerce CSV Products
4Description: Automatically update CSV Products based on CSV files
5Version: 1.0
6Author: Admir Zatega
7*/
8
9include ('Diff.php');
10include ('settings-page.php');
11
12add_action('init', 'wcsv_init');
13
14function wcsv_get_product($key, $value){
15 global $wcsv_products;
16 foreach($wcsv_products as $product){
17 if($key == 'title' || $key == 'post_title'){
18 if($product->post_title == $value)
19 return $product;
20 }else{
21 if(get_post_meta($product->ID, $key, true) == $value)
22 return $product;
23 }
24 }
25 return array();
26}
27
28function wcsv_init(){
29 ini_set('max_execution_time', 300);
30
31 global $wp, $wcsv_products;
32
33 $path = $_SERVER['REQUEST_URI'];
34 $wcsv_path = get_option('wcsv_update_link');
35 if(substr($wcsv_path, 0, 1) != '/')
36 $wcsv_path = '/' . $wcsv_path;
37
38 if($path != $wcsv_path)
39 return;
40
41 $args = array('post_type' => 'product', 'posts_per_page' => -1);
42 $wcsv_products = get_posts($args);
43
44 $plugin_dir = ABSPATH . 'wp-content/plugins/wc-csv-products/';
45 $file_path = str_replace('{PLUGINPATH}', $plugin_dir, get_option('wcsv_csv_location'));
46
47 $wp_all_import = wcsv_update($plugin_dir . 'old-csv.csv', $file_path);
48 file_put_contents(ABSPATH . 'wp-content/uploads/wpallimport/files/csv-changes.csv', $wp_all_import);
49
50 $file = file_get_contents($file_path);
51 file_put_contents($plugin_dir . 'old-csv.csv', $file);
52
53 $secret_key = get_option('wcsv_wpimport_secret_key');
54 $import_id = get_option('wcsv_wpimport_import_id');
55 $wp_all_import_cron = get_home_url() . "/wp-cron.php?import_key={$secret_key}&import_id={$import_id}&action=trigger";
56
57 header('Location: ' . $wp_all_import_cron);
58 exit;
59}
60
61function wcsv_update($old_file, $new_file){
62 global $wp, $wcsv_products;
63 $diff = Diff::compareFiles($old_file, $new_file);
64 $wp_all_import = $diff[0][0] . "\n";
65
66 $len = count($diff);
67 $meta_keys = array_map('trim', explode(',', $diff[0][0]));;
68
69 foreach($diff as $key => $line){
70 if($key == 0)
71 continue;
72
73 if($line[1] == Diff::UNMODIFIED)
74 continue;
75
76 $line_args = explode(',', $line[0]);
77 $product = wcsv_get_product($meta_keys[0], $line_args[0]);
78
79 if($line[1] == Diff::DELETED){
80 // Check if there is an INSERTED line whose first argument is the same,
81 // if it is: ignore deletion, if not: delete
82 $found_equal = false;
83
84 foreach($diff as $key2 => $line2){
85 if($key2 == 0)
86 continue;
87 $line2_args = array_map('trim', explode(',', $line2[0]));
88
89 if($line2[1] == Diff::INSERTED){
90 if($line_args[0] == $line2_args[0]){
91 $found_equal = true;
92 break;
93 }
94 }
95 }
96
97 if(!$found_equal){
98 // Delete produuct
99 wp_delete_post($product->ID);
100 }
101 }
102 if($line[1] == Diff::INSERTED){
103 $wp_all_import .= $line[0] . "\n";
104 }
105 }
106
107 return $wp_all_import;
108}
109
110function wcsv_create_product($line){
111
112}