forked from hissy/rs-csv-importer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rs-csv-importer.php
413 lines (352 loc) · 12 KB
/
rs-csv-importer.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
<?php
/*
Plugin Name: Really Simple CSV Importer
Plugin URI: http://wordpress.org/plugins/really-simple-csv-importer/
Description: Import posts, categories, tags, custom fields from simple csv file.
Author: Takuro Hishikawa, wokamoto
Author URI: https://en.digitalcube.jp/
Text Domain: rs-csv-importer
License: GPL version 2 or later - http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
Version: 0.6.2
*/
if ( !defined('WP_LOAD_IMPORTERS') )
return;
// Load Importer API
require_once ABSPATH . 'wp-admin/includes/import.php';
if ( !class_exists( 'WP_Importer' ) ) {
$class_wp_importer = ABSPATH . 'wp-admin/includes/class-wp-importer.php';
if ( file_exists( $class_wp_importer ) )
require_once $class_wp_importer;
}
// Load Helpers
require dirname( __FILE__ ) . '/rs-csv-helper.php';
require dirname( __FILE__ ) . '/wp_post_helper/class-wp_post_helper.php';
/**
* CSV Importer
*
* @package WordPress
* @subpackage Importer
*/
if ( class_exists( 'WP_Importer' ) ) {
class RS_CSV_Importer extends WP_Importer {
/** Sheet columns
* @value array
*/
public $column_indexes = array();
public $column_keys = array();
// User interface wrapper start
function header() {
echo '<div class="wrap">';
screen_icon();
echo '<h2>'.__('Import CSV', 'rs-csv-importer').'</h2>';
}
// User interface wrapper end
function footer() {
echo '</div>';
}
// Step 1
function greet() {
echo '<p>'.__( 'Choose a CSV (.csv) file to upload, then click Upload file and import.', 'rs-csv-importer' ).'</p>';
echo '<p>'.__( 'Excel-style CSV file is unconventional and not recommended. LibreOffice has enough export options and recommended for most users.', 'rs-csv-importer' ).'</p>';
echo '<p>'.__( 'Requirements:', 'rs-csv-importer' ).'</p>';
echo '<ol>';
echo '<li>'.__( 'Select UTF-8 as charset.', 'rs-csv-importer' ).'</li>';
echo '<li>'.sprintf( __( 'You must use field delimiter as "%s"', 'rs-csv-importer'), RS_CSV_Helper::DELIMITER ).'</li>';
echo '<li>'.__( 'You must quote all text cells.', 'rs-csv-importer' ).'</li>';
echo '</ol>';
echo '<p>'.__( 'Download example CSV files:', 'rs-csv-importer' );
echo ' <a href="'.plugin_dir_url( __FILE__ ).'sample/sample.csv">'.__( 'csv', 'rs-csv-importer' ).'</a>,';
echo ' <a href="'.plugin_dir_url( __FILE__ ).'sample/sample.ods">'.__( 'ods', 'rs-csv-importer' ).'</a>';
echo ' '.__('(OpenDocument Spreadsheet file format for LibreOffice. Please export as csv before import)', 'rs-csv-importer' );
echo '</p>';
wp_import_upload_form( add_query_arg('step', 1) );
}
// Step 2
function import() {
$file = wp_import_handle_upload();
if ( isset( $file['error'] ) ) {
echo '<p><strong>' . __( 'Sorry, there has been an error.', 'rs-csv-importer' ) . '</strong><br />';
echo esc_html( $file['error'] ) . '</p>';
return false;
} else if ( ! file_exists( $file['file'] ) ) {
echo '<p><strong>' . __( 'Sorry, there has been an error.', 'rs-csv-importer' ) . '</strong><br />';
printf( __( 'The export file could not be found at <code>%s</code>. It is likely that this was caused by a permissions problem.', 'rs-csv-importer' ), esc_html( $file['file'] ) );
echo '</p>';
return false;
}
$this->id = (int) $file['id'];
$this->file = get_attached_file($this->id);
$result = $this->process_posts();
if ( is_wp_error( $result ) )
return $result;
}
/**
* Insert post and postmeta using wp_post_helper.
*
* More information: https://gist.github.com/4084471
*
* @param array $post
* @param array $meta
* @param array $terms
* @param string $thumbnail The uri or path of thumbnail image.
* @param bool $is_update
* @return int|false Saved post id. If failed, return false.
*/
public function save_post($post,$meta,$terms,$thumbnail,$is_update) {
$ph = new wp_post_helper($post);
foreach ($meta as $key => $value) {
$is_cfs = 0;
$is_acf = 0;
$cfs_prefix = 'cfs_';
if (strpos($key, $cfs_prefix) === 0) {
$ph->add_cfs_field( substr($key, strlen($cfs_prefix)), $value );
$is_cfs = 1;
} else {
if (function_exists('get_field_object')) {
if (strpos($key, 'field_') === 0) {
$fobj = get_field_object($key);
if (is_array($fobj) && isset($fobj['key']) && $fobj['key'] == $key) {
$ph->add_field($key,$value);
$is_acf = 1;
}
}
}
}
if (!$is_acf && !$is_cfs)
$ph->add_meta($key,$value,true);
}
foreach ($terms as $key => $value) {
$ph->add_terms($key, $value);
}
if ($thumbnail) $ph->add_media($thumbnail,'','','',true);
if ($is_update)
$result = $ph->update();
else
$result = $ph->insert();
unset($ph);
return $result;
}
// process parse csv ind insert posts
function process_posts() {
$h = new RS_CSV_Helper;
$handle = $h->fopen($this->file, 'r');
if ( $handle == false ) {
echo '<p><strong>'.__( 'Failed to open file.', 'rs-csv-importer' ).'</strong></p>';
wp_import_cleanup($this->id);
return false;
}
$is_first = true;
echo '<ol>';
while (($data = $h->fgetcsv($handle)) !== FALSE) {
if ($is_first) {
$h->parse_columns( $this, $data );
$is_first = false;
} else {
echo '<li>';
$post = array();
$is_update = false;
$error = new WP_Error();
// (string) (required) post type
$post_type = $h->get_data($this,$data,'post_type');
if ($post_type) {
if (post_type_exists($post_type)) {
$post['post_type'] = $post_type;
} else {
$error->add( 'post_type_exists', sprintf(__('Invalid post type "%s".', 'rs-csv-importer'), $post_type) );
}
} else {
echo __('Note: Please include post_type value if that is possible.', 'rs-csv-importer').'<br>';
}
// (int) post id
$post_id = $h->get_data($this,$data,'ID');
$post_id = ($post_id) ? $post_id : $h->get_data($this,$data,'post_id');
if ($post_id) {
$post_exist = get_post($post_id);
if ( is_null( $post_exist ) ) { // if the post id is not exists
$post['import_id'] = $post_id;
} else {
if ( !$post_type || $post_exist->post_type == $post_type ) {
$post['ID'] = $post_id;
$is_update = true;
} else {
$error->add( 'post_type_check', sprintf(__('The post type value from your csv file does not match the existing data in your database. post_id: %d, post_type(csv): %s, post_type(db): %s', 'rs-csv-importer'), $post_id, $post_type, $post_exist->post_type) );
}
}
}
// (string) post slug
$post_name = $h->get_data($this,$data,'post_name');
if ($post_name) {
$post['post_name'] = $post_name;
}
// (login or ID) post_author
$post_author = $h->get_data($this,$data,'post_author');
if ($post_author) {
if (is_numeric($post_author)) {
$user = get_user_by('id',$post_author);
} else {
$user = get_user_by('login',$post_author);
}
if (isset($user) && is_object($user)) {
$post['post_author'] = $user->ID;
unset($user);
}
}
// (string) publish date
$post_date = $h->get_data($this,$data,'post_date');
if ($post_date) {
$post['post_date'] = date("Y-m-d H:i:s", strtotime($post_date));
}
// (string) post status
$post_status = $h->get_data($this,$data,'post_status');
if ($post_status) {
$post['post_status'] = $post_status;
}
// (string) post title
$post_title = $h->get_data($this,$data,'post_title');
if ($post_title) {
$post['post_title'] = $post_title;
}
// (string) post content
$post_content = $h->get_data($this,$data,'post_content');
if ($post_content) {
$post['post_content'] = $post_content;
}
// (string) post excerpt
$post_excerpt = $h->get_data($this,$data,'post_excerpt');
if ($post_excerpt) {
$post['post_excerpt'] = $post_excerpt;
}
// (int) post parent
$post_parent = $h->get_data($this,$data,'post_parent');
if ($post_parent) {
$post['post_parent'] = $post_parent;
}
// (int) menu order
$menu_order = $h->get_data($this,$data,'menu_order');
if ($menu_order) {
$post['menu_order'] = $menu_order;
}
// (string, comma separated) slug of post categories
$post_category = $h->get_data($this,$data,'post_category');
if ($post_category) {
$categories = preg_split("/,+/", $post_category);
if ($categories) {
$post['post_category'] = wp_create_categories($categories);
}
}
// (string, comma separated) name of post tags
$post_tags = $h->get_data($this,$data,'post_tags');
if ($post_tags) {
$post['post_tags'] = $post_tags;
}
// (string) post thumbnail image uri
$post_thumbnail = $h->get_data($this,$data,'post_thumbnail');
if (parse_url($post_thumbnail, PHP_URL_SCHEME))
$post_thumbnail = remote_get_file($post_thumbnail);
$meta = array();
$tax = array();
// add any other data to post meta
foreach ($data as $key => $value) {
if ($value !== false && isset($this->column_keys[$key])) {
// check if meta is custom taxonomy
if (substr($this->column_keys[$key], 0, 4) == 'tax_') {
// (string, comma divided) name of custom taxonomies
$customtaxes = preg_split("/,+/", $value);
$taxname = substr($this->column_keys[$key], 4);
$tax[$taxname] = array();
foreach($customtaxes as $key => $value ) {
$tax[$taxname][] = $value;
}
}
else {
$meta[$this->column_keys[$key]] = $value;
}
}
}
/**
* Filter post data.
*
* @param array $post (required)
* @param bool $is_update
*/
$post = apply_filters( 'really_simple_csv_importer_save_post', $post, $is_update );
/**
* Filter meta data.
*
* @param array $meta (required)
* @param array $post
* @param bool $is_update
*/
$meta = apply_filters( 'really_simple_csv_importer_save_meta', $meta, $post, $is_update );
/**
* Filter taxonomy data.
*
* @param array $tax (required)
* @param array $post
* @param bool $is_update
*/
$tax = apply_filters( 'really_simple_csv_importer_save_tax', $tax, $post, $is_update );
/**
* Option for dry run
*
* @param bool false
*/
$dry_run = apply_filters( 'really_simple_csv_importer_dry_run', false );
if (!$error->get_error_codes() && $dry_run == false) {
/**
* Get Alternative Importer Class name.
*
* @param string Class name to override Importer class. Default to null (do not override).
*/
$class = apply_filters( 'really_simple_csv_importer_class', null );
// save post data
if ($class && class_exists($class,false)) {
$importer = new $class;
$result = $importer->save_post($post,$meta,$tax,$post_thumbnail,$is_update);
} else {
$result = $this->save_post($post,$meta,$tax,$post_thumbnail,$is_update);
}
if ($result) {
echo esc_html(sprintf(__('Processing "%s" done.', 'rs-csv-importer'), $post_title));
} else {
$error->add( 'save_post', __('An error occurred while saving the post to database.', 'rs-csv-importer') );
}
}
// show error messages
foreach ($error->get_error_messages() as $message) {
echo esc_html($message).'<br>';
}
echo '</li>';
}
}
echo '</ol>';
$h->fclose($handle);
wp_import_cleanup($this->id);
echo '<h3>'.__('All Done.', 'rs-csv-importer').'</h3>';
}
// dispatcher
function dispatch() {
$this->header();
if (empty ($_GET['step']))
$step = 0;
else
$step = (int) $_GET['step'];
switch ($step) {
case 0 :
$this->greet();
break;
case 1 :
check_admin_referer('import-upload');
set_time_limit(0);
$result = $this->import();
if ( is_wp_error( $result ) )
echo $result->get_error_message();
break;
}
$this->footer();
}
}
// setup importer
$rs_csv_importer = new RS_CSV_Importer();
register_importer('csv', __('CSV', 'rs-csv-importer'), __('Import posts, categories, tags, custom fields from simple csv file.', 'rs-csv-importer'), array ($rs_csv_importer, 'dispatch'));
} // class_exists( 'WP_Importer' )