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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
<?php
/*
 * ImportPostWp.class.php
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301, USA.
 *
 * @author Mario Spada <spadamar@spadamar.com> 
 * @copyright Copyright (c) 2015 Mario Spada
 * @license http://opensource.org/licenses/GPL-2.0 GNU Public License
 * @package ImportPostWp
 * @version 0.1.0 2015/06/28
 */
 
/**
 * ImportPostWp
 * This class allows to import bulk posts into Wordpress from array
 * 
 * @author Mario Spada <spadamar@spadamar.com> 
 * @copyright Copyright (c) 2015 Mario Spada
 * @license http://opensource.org/licenses/GPL-2.0 GNU Public License
 * @package ImportPostWp
 * @version 0.1.0 2015/06/28
 */

class ImportPostWp {

   	/**
	 * Path of Wordpress root directory
	 * @var string
	 */
	public $wp_path = ".";
   	/**
	 * Timezone as defined in http://php.net/manual/en/timezones.php
	 * @var string
	 */	
	public $time_zone = "Europe/Rome";
   	/**
	 * Switch on debug
	 * @var boolean
	 */	
	public $debug = false;
   	/**
	 * Total elapsed time in seconds
	 * @var int
	 */	
	protected $time_elapsed = 0;
   	/**
	 * Array containing each row number of the failed insert
	 * @var array
	 */		
	protected $insert_errors = array();
   	/**
	 * Array containing the list of the fields to insert
	 * @var array
	 */		
	protected $fields_list = array('post_title','post_content','post_name',
							'post_status','post_type','guid','post_excerpt',
							'post_date','post_date_gmt','ping_status',
							'comment_status','post_author','categories');
   	/**
	 * Array containing the default field values
	 * @var array
	 */	
	protected $default_post_values = array('post_status' => 'publish',
										   'post_type'=> 'post', 
										   'ping_status'=> 'closed',
										   'comment_status'=> 'closed',
										   'post_author'=> 1 );
   	/**
	 * Array containing data
	 * @var array
	 */	
	protected $posts = array();
   	/**
	 * The number of rows of data array
	 * @var int
	 */	
	protected $nPosts = 0;

	/**
	 * @param array $data data array
	 * @param string $wpPath The path to Wordpress directory
	 */
	function __construct($data,$wpPath = "."){
		$this->wp_path = rtrim($wpPath, '/') . '/';
		$this->posts = $data;
		$this->nPosts = count($data);
		require_once($this->wp_path."wp-load.php");
	}

	/**
	 * reset elapsed time
	 */	
	public function reset_time() {
		$this->time_elapsed = 0;
	}
	
	/**
	 * Get elapsed time
	 */	
	public function get_elapsed_time() {
		return $this->time_elapsed;
	}
	/**
	 * Return data array
	 * If $print is true, prints out data array
	 * 
	 * @param bool $print
	 * @return array
	 */	
	public function get_data ($print=false) {
		if ($print) {
			echo "<pre>";
			print_r($this->posts);
			echo "</pre>";
		}
		return $this->posts;
	}

	/**
	 * Return default values for the optional field list
	 * If $print is true, prints out array
	 * 
	 * @param bool $print
	 * @return array
	 */	
	public function get_default_post_values ($print=false) {
		if ($print) {
			echo "<pre>";
			print_r($this->default_post_values);
			echo "</pre>";
		}
		return $this->default_post_values;
	}
	/**
	 * Return an array of the not inserted rows
	 * If $print is true, prints out array
	 * 
	 * @param bool $print
	 * @return array
	 */	
	public function get_insert_errors ($print=false) {
		if ($print) {
			echo "<pre>";
			print_r($this->insert_errors);
			echo "</pre>";
		}
		return $this->insert_errors;
	}
	/**
	 * Return the field name list
	 * If $print is true, prints out array
	 * 
	 * @param bool $print
	 * @return array
	 */	
	public function get_field_list ($print=false) {
		if ($print) {
			echo "<pre>";
			print_r($this->fields_list);
			echo "</pre>";
		}
		return $this->fields_list;
	}
	/**
	 * Set default values for the field 'post_status'
	 * Possible values: [ 'draft' | 'publish' | 'pending'| 'future' | 'private' | custom registered status ]
	 * default = 'publish'
	 * 
	 * @param string $val
	 */
	public function set_default_post_status ($val) {
		$this->default_post_values['post_status'] = $val;
	}
	/**
	 * Set default values for the field 'post_type'
	 * Possible values: [ 'post' | 'page' | 'link' | 'nav_menu_item' | custom post type ]
	 * default = 'post'
	 * 
	 * @param string $val
	 */
	public function set_default_post_type ($val) {
		$this->default_post_values['post_type'] = $val;
	}
	/**
	 * Set default values for the field 'ping_status'
	 * Possible values: [ 'closed' | 'open' ]
	 * default = 'closed'
	 * 
	 * @param string $val
	 */
	public function set_default_ping_status ($val) {
		$this->default_post_values['ping_status'] = $val;
	}
	/**
	 * Set default values for the field 'comment_status'
	 * Possible values: [ 'closed' | 'open' ]
	 * default = 'closed'
	 * 
	 * @param string $val
	 */	
	public function set_default_comment_status ($val) {
		$this->default_post_values['comment_status'] = $val;
	}
	/**
	 * Set default values for the field 'post_author'
	 * Possible values: [ <user ID> ] // The user ID number of the author.
	 * default = 1
	 * 
	 * @param string $val
	 */		
	public function set_default_post_author ($val) {
		$this->default_post_values['post_author'] = $val;
	}
	/**
	 * Loop through data and search ID categories on WP database.
	 * If the category doesn't exist, it will be created.
	 * Substitute all category string with IDs in the data array.
	 * If empty category is provided, the value will be the ID of the default category
	 */			
	protected function prepare_categories () {
		require_once($this->wp_path . 'wp-admin/includes/taxonomy.php');
		$start = microtime(true);
		for  ($i=0;$i < $this->nPosts;$i++) {

			if (empty($this->posts[$i]['categories'])) {
				$tmp = get_option('default_category');
				$this->posts[$i]['categories'] = $tmp; 
			}

			$cats = explode(",",$this->posts[$i]['categories']);

			$newCats = array();
			foreach ($cats as $cat) {
				if (!is_numeric($cat)) {
					$cat_ID = get_cat_ID(trim($cat));
					if (empty($cat_ID)) {
						$new_cat = array('cat_name' => trim($cat), 
										'category_description' => trim($cat), 
										'category_nicename' => sanitize_title(trim($cat))
										);
						$cat_ID = wp_insert_category($new_cat);						
					}
				} else {
					$cat_ID = (int) $cat;
				}
				$newCats[] = $cat_ID;
			}
			$this->posts[$i]['categories'] = implode(",",$newCats);
		}
		$this->time_elapsed += microtime(true) - $start;
	}
	/**
	 * Delete all post of a specific category. It cleans also all
	 * relationship records.
	 * Accept both category name or category ID
	 * The number of affected record will twice the number of affected posts
	 * 
	 * @param int|string $cat
	 * @return int number of affected records
	 */	
	public function delete_posts($cat) {
		$start = microtime(true);		
		$cat_ID = is_numeric($cat) ? $cat : get_cat_ID(trim($cat));
		
		if (empty($cat_ID)) 
			return 0;
		
		$q = "delete a,b,c
			FROM wp_posts a
			LEFT JOIN wp_term_relationships b ON ( a.ID = b.object_id )
			LEFT JOIN wp_postmeta c ON ( a.ID = c.post_id )
			LEFT JOIN wp_term_taxonomy d ON ( d.term_taxonomy_id = b.term_taxonomy_id )
			LEFT JOIN wp_terms e ON ( e.term_id = d.term_id )
			WHERE e.term_id =".$cat_ID.";";

		$q2 = "DELETE tr FROM wp_term_relationships tr
		INNER JOIN wp_term_taxonomy tt ON (tr.term_taxonomy_id = tt.term_taxonomy_id)
		WHERE tt.taxonomy != 'link_category'
		AND tr.object_id NOT IN (SELECT ID FROM wp_posts);";

		global $wpdb;

		if ($this->debug)
			$wpdb->show_errors();
					
		$wpdb->query( $q );
		$results = $wpdb->rows_affected;

		if ($results > 1) {
			$wpdb->query( $q1 );
		}
		$this->time_elapsed += microtime(true) - $start;
		return $results;
	}

	/**
	 * Insert all posts in Wordpress DB. 
	 * It uses native WP function: wp_insert_post
	 * It is slow, but it performs a lot of security control before inserting
	 * 
	 * @return int number of successfully inserted records
	 */
	public function insert_posts() {
		$this->prepare_categories();
		$i = 0;
		$start = microtime(true);
		wp_suspend_cache_addition(true);
		wp_defer_term_counting( true );

		foreach ($this->posts as $key => $row) {
			$cats = explode(",",$row['categories']);
			$post_status = empty($row['post_status']) ? $this->default_post_values['post_status'] : $row['post_status'];
			$post_type = empty($row['post_type']) ? $this->default_post_values['post_type'] : $row['post_type'];
			$post_author = empty($row['post_author']) ? $this->default_post_values['post_author'] : (int) $row['post_author'];
			$post_date = empty($row['post_date']) ? date("Y-m-d H:i:s") : $row['post_date'];
			
			$new_post = array(
			  'post_title'    => $row['post_title'],
			  'post_content'  => $row['post_content'],
			  'post_status'   => $post_status,
			  'post_type'     => $post_type,
			  'post_date'      => $post_date,
			  'post_author'    => $post_author,
			  'post_category'  => $cats
			);
			
			if (!empty($row['post_excerpt'])) {
				$new_post['post_excerpt'] = $row['post_excerpt'];
			}
			if (!empty($row['comment_status']) && in_array($row['comment_status'],array('open','closed'))) {
				$new_post['comment_status'] = $row['comment_status'];
			} else {
				$new_post['comment_status'] = $this->default_post_values['comment_status'];
			}
			if (!empty($row['ping_status']) && in_array($row['ping_status'],array('open','closed'))) {
				$new_post['ping_status'] = $row['ping_status'];
			} else {
				$new_post['ping_status'] = $this->default_post_values['ping_status'];
			}

			
			$post_id = wp_insert_post( $new_post, false );
			if (empty($post_id)){
				$this->insert_errors[] = $key;
			}  else {
				$i++;
			}
		}
		$this->time_elapsed += microtime(true) - $start;
		wp_suspend_cache_addition(false);
		wp_defer_term_counting( false );
		
		return $i;
	}

	/**
	 * Insert all posts in Wordpress DB. 
	 * It uses raw SQL queries
	 * It is much faster than insert_posts, but it doesn't perform 
	 * security control before inserting
	 * 
	 * @return int number of successfully inserted records
	 */
	public function raw_insert_posts () {		
		global $wpdb;
		$this->prepare_categories();
		if ($this->debug)
			$wpdb->show_errors();
		date_default_timezone_set($this->time_zone);
		$i = 0;
		$start = microtime(true);	
		foreach ($this->posts as $key => $row) {
			$cats = explode(",",$row['categories']);

				$post_name = sanitize_title_with_dashes($row['post_title']);
				$guid = site_url()."/".$post_name;
				$post_date = empty($row['post_date']) ? date("Y-m-d H:i:s") : $row['post_date'];
				$post_date_gmt = gmdate("Y-m-d H:i:s",strtotime($post_date));
				$post_status = empty($row['post_status']) ? $this->default_post_values['post_status'] : $row['post_status'];
				$post_type = empty($row['post_type']) ? $this->default_post_values['post_type'] : $row['post_type'];
				$post_author = empty($row['post_author']) ? $this->default_post_values['post_author'] : (int) $row['post_author'];
				if (!empty($row['comment_status']) && in_array($row['comment_status'],array('open','closed'))) {
					$comment_status = $row['comment_status'];
				} else {
					$comment_status = $this->default_post_values['comment_status'];
				}
				if (!empty($row['ping_status']) && in_array($row['ping_status'],array('open','closed'))) {
					$ping_status = $row['ping_status'];
				} else {
					$ping_status = $this->default_post_values['ping_status'];
				}
				if (!empty($row['post_excerpt'])) {
					$post_excerpt = $row['post_excerpt'];
				} else {
					$post_excerpt = "";
				}
				$query = "INSERT INTO $wpdb->posts 
							(post_title,post_content,post_name,post_status,
							post_type,guid,post_author,post_date,post_date_gmt,
							comment_status,ping_status,post_excerpt) 
						  VALUES (%s, %s, %s, %s, %s, %s, %d, %s, %s, %s, %s, %s)";
				$wpdb->query($wpdb->prepare($query,
											$row['post_title'],
											$row['post_content'],
											$post_name,
											$post_status,
											$post_type,
											$guid,
											$post_author,
											$post_date,
											$post_date_gmt,
											$comment_status,
											$ping_status,
											$post_excerpt));
				$lastID = $wpdb->insert_id;
				$i += (int) $wpdb->rows_affected;
				
				$query = "INSERT INTO $wpdb->term_relationships (object_id,term_taxonomy_id) VALUES ";
				foreach ($cats as $cat) {
					$cat = (int) $cat;
					$query .= "({$lastID}, {$cat}),";
				}
				$query = rtrim($query,",");
				$wpdb->query($query);
		}
		
		$q = "UPDATE wp_term_taxonomy tt
				SET count =
				(SELECT count(p.ID) FROM  wp_term_relationships tr
				LEFT JOIN wp_posts p
				ON (p.ID = tr.object_id AND p.post_type = 'post' AND p.post_status = 'publish')
				WHERE tr.term_taxonomy_id = tt.term_taxonomy_id
				)";
		$wpdb->query($q);
		$time_elapsed_secs = microtime(true) - $start;	
		return $i;
	}

}

?>