settings.php 26.8 KB
Newer Older
imac's avatar
imac committed
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 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787
<?php 
/**
 * Admin Statistics page
 * 
 * @author Pavel Kulbakin <p.kulbakin@gmail.com>
 */
class PMXI_Admin_Settings extends PMXI_Controller_Admin {

	public static $path;

	public static $upload_transient;

	public $slug = 'wp-all-import-pro';

	public function __construct(){	

		parent::__construct();

		self::$upload_transient = 'pmxi_uploads_path';		

		$uploads = wp_upload_dir();	

		$is_secure_import = PMXI_Plugin::getInstance()->getOption('secure');
		
		if ( ! $is_secure_import ){

			self::$path = wp_all_import_secure_file($uploads['basedir'] . DIRECTORY_SEPARATOR . PMXI_Plugin::UPLOADS_DIRECTORY );
			
		}
		else {			

			self::$path = get_transient( self::$upload_transient );

			if ( empty(self::$path) ) {
				self::$path = wp_all_import_secure_file($uploads['basedir'] . DIRECTORY_SEPARATOR . PMXI_Plugin::UPLOADS_DIRECTORY );
				set_transient( self::$upload_transient, self::$path);
			}

		}

	}
	
	public function index() {

		$this->data['post'] = $post = $this->input->post(PMXI_Plugin::getInstance()->getOption());

		/*$addons = new PMXI_Admin_Addons();

		$this->data['addons'] = $addons->get_premium_addons();*/

		$this->data['addons']['PMXI_Plugin'] = array(
			'title' => __('WP All Import', 'wp_all_import_plugin'),
			'active' => (class_exists('PMXI_Plugin') and defined('PMXI_EDITION') and PMXI_EDITION == 'paid')
		);

		$this->data['addons'] = array_reverse($this->data['addons']);

		$this->data['license_message'] = '';

		if ($this->input->post('is_license_submitted')) { // save license

			check_admin_referer('edit-license', '_wpnonce_edit-license');

			if ( ! $this->errors->get_error_codes()) { // no validation errors detected

				PMXI_Plugin::getInstance()->updateOption($post);

				if (empty($_POST['pmxi_license_activate']) and empty($_POST['pmxi_license_deactivate'])) {
					foreach ($this->data['addons'] as $class => $addon) {
						$post['statuses'][$class] = $this->check_license($class);
						if ($post['statuses'][$class] == 'valid'){
							$this->data['license_message'] = __('License activated.', 'wp_all_import_plugin');
						}
					}
					PMXI_Plugin::getInstance()->updateOption($post);
				}

				isset($_POST['pmxi_license_activate']) and $this->activate_licenses();
			}

			$this->data['post'] = $post = PMXI_Plugin::getInstance()->getOption();
		}

		$this->data['is_license_active'] = false;

		foreach ($this->data['addons'] as $class => $addon) {
			if( ! empty($post['statuses'][$class]) && $post['statuses'][$class] == 'valid' ){
				$this->data['is_license_active'] = true;
			}
		}

		if ($this->input->post('is_settings_submitted')) { // save settings form
			check_admin_referer('edit-settings', '_wpnonce_edit-settings');
			
			if ( ! preg_match('%^\d+$%', $post['history_file_count'])) {
				$this->errors->add('form-validation', __('History File Count must be a non-negative integer', 'wp_all_import_plugin'));
			}
			if ( ! preg_match('%^\d+$%', $post['history_file_age'])) {
				$this->errors->add('form-validation', __('History Age must be a non-negative integer', 'wp_all_import_plugin'));
			}
			if (empty($post['html_entities'])) $post['html_entities'] = 0;
			if (empty($post['utf8_decode'])) $post['utf8_decode'] = 0;
			
			if ( ! $this->errors->get_error_codes()) { // no validation errors detected

				PMXI_Plugin::getInstance()->updateOption($post);

				$files = new PMXI_File_List(); $files->sweepHistory(); // adjust file history to new settings specified
				
				wp_redirect(add_query_arg('pmxi_nt', urlencode(__('Settings saved', 'wp_all_import_plugin')), $this->baseUrl)); die();
			}
		}

		if ($this->input->post('is_templates_submitted')) { // delete templates form

			check_admin_referer('delete-templates', '_wpnonce_delete-templates');

			if ($this->input->post('import_templates')){

				if (!empty($_FILES)){
					$file_name = $_FILES['template_file']['name'];
					$file_size = $_FILES['template_file']['size'];
					$tmp_name  = $_FILES['template_file']['tmp_name'];										
					
					if(isset($file_name)) 
					{				
						
						$filename  = stripslashes($file_name);
						$extension = strtolower(pmxi_getExtension($filename));
										
						if (($extension != "txt")) 
						{							
							$this->errors->add('form-validation', __('Unknown File extension. Only txt files are permitted', 'wp_all_import_plugin'));
						}
						else {
							$import_data = @file_get_contents($tmp_name);
							if (!empty($import_data)){
								$templates_data = json_decode($import_data, true);
								
								if ( ! empty($templates_data) ){
									if ( ! empty($templates_data[0]['options']) && is_array($templates_data[0]['options'])){
										$templateOptions = $templates_data[0]['options'];
									}
									else{
										$templateOptions = empty($templates_data[0]['options']) ? false : unserialize($templates_data[0]['options']);
									}
									if ( empty($templateOptions) ){
										$this->errors->add('form-validation', __('The template is invalid. Options are missing.', 'wp_all_import_plugin'));
									}
									else{
										if (isset($templateOptions['is_user_export'])){
											$this->errors->add('form-validation', __('The template you\'ve uploaded is intended to be used with WP All Export plugin.', 'wp_all_import_plugin'));
										}
										else{
											$template = new PMXI_Template_Record();
											foreach ($templates_data as $template_data) {
												unset($template_data['id']);
												$template->clear()->set($template_data)->insert();
											}
											wp_redirect(add_query_arg('pmxi_nt', urlencode(sprintf(_n('%d template imported', '%d templates imported', count($templates_data), 'wp_all_import_plugin'), count($templates_data))), $this->baseUrl)); die();
										}
									}
								}
								else $this->errors->add('form-validation', __('Wrong imported data format', 'wp_all_import_plugin'));							
							}
							else $this->errors->add('form-validation', __('File is empty or doesn\'t exests', 'wp_all_import_plugin'));
						}
					}
					else $this->errors->add('form-validation', __('Undefined entry!', 'wp_all_import_plugin'));
				}
				else $this->errors->add('form-validation', __('Please select file.', 'wp_all_import_plugin'));

			}
			else{
				$templates_ids = $this->input->post('templates', array());
				if (empty($templates_ids)) {
					$this->errors->add('form-validation', __('Templates must be selected', 'wp_all_import_plugin'));
				}
				
				if ( ! $this->errors->get_error_codes()) { // no validation errors detected
					if ($this->input->post('delete_templates')){
						$template = new PMXI_Template_Record();
						foreach ($templates_ids as $template_id) {
							$template->clear()->set('id', $template_id)->delete();
						}
						wp_redirect(add_query_arg('pmxi_nt', urlencode(sprintf(_n('%d template deleted', '%d templates deleted', count($templates_ids), 'wp_all_import_plugin'), count($templates_ids))), $this->baseUrl)); die();
					}
					if ($this->input->post('export_templates')){
						$export_data = array();
						$template = new PMXI_Template_Record();
						foreach ($templates_ids as $template_id) {
							$export_data[] = $template->clear()->getBy('id', $template_id)->toArray(TRUE);
						}	
						
						$uploads = wp_upload_dir();
						$targetDir = $uploads['basedir'] . DIRECTORY_SEPARATOR . PMXI_Plugin::TEMP_DIRECTORY;
						$export_file_name = "templates_".uniqid().".txt";
						file_put_contents($targetDir . DIRECTORY_SEPARATOR . $export_file_name, json_encode($export_data));
						
						PMXI_download::csv($targetDir . DIRECTORY_SEPARATOR . $export_file_name);
						
					}				
				}
			}
		}
		
		$this->render();
	}

	/*
	*
	* Activate licenses for main plugin and all premium addons
	*
	*/
	protected function activate_licenses() {

		// listen for our activate button to be clicked
		if( isset( $_POST['pmxi_license_activate'] ) ) {			

			// retrieve the license from the database
			$options = PMXI_Plugin::getInstance()->getOption();

			global $wpdb;

			delete_transient(PMXI_Plugin::$cache_key);

			$wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->options WHERE option_name = %s", $this->slug . '_' . PMXI_Plugin::$cache_key) );
			$wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->options WHERE option_name = %s", $this->slug . '_timeout_' . PMXI_Plugin::$cache_key) );

			delete_site_transient('update_plugins');
			
			foreach ($_POST['pmxi_license_activate'] as $class => $val) {							

				if (!empty($options['licenses'][$class])){

					$product_name = (method_exists($class, 'getEddName')) ? call_user_func(array($class, 'getEddName')) : false;

					if ( $product_name !== false ){
						// data to send in our API request
						$api_params = array( 
							'edd_action'=> 'activate_license', 
							'license' 	=> $options['licenses'][$class], 
							'item_name' => urlencode( $product_name ) // the name of our product in EDD
						);								
						
						// Call the custom API.
						$response = wp_remote_get( add_query_arg( $api_params, $options['info_api_url'] ), array( 'timeout' => 15, 'sslverify' => false ) );						

						// make sure the response came back okay
						if ( is_wp_error( $response ) )
							continue;

						// decode the license data
						$license_data = json_decode( wp_remote_retrieve_body( $response ) );
						
						// $license_data->license will be either "active" or "inactive"

						$options['statuses'][$class] = $license_data->license;
						
						PMXI_Plugin::getInstance()->updateOption($options);	
					}
				}

			}				

		}
	}	

	/*
	*
	* Check plugin's license
	*
	*/
	public function check_license($class) {

		global $wp_version, $wpdb;

		delete_transient(PMXI_Plugin::$cache_key);

		$wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->options WHERE option_name = %s", $this->slug . '_' . PMXI_Plugin::$cache_key) );
		$wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->options WHERE option_name = %s", $this->slug . '_timeout_' . PMXI_Plugin::$cache_key) );

		delete_site_transient('update_plugins');

		$options = PMXI_Plugin::getInstance()->getOption();

		if (!empty($options['licenses'][$class])){

			$product_name = (method_exists($class, 'getEddName')) ? call_user_func(array($class, 'getEddName')) : false;

			if ( $product_name !== false ){

				$api_params = array( 
					'edd_action' => 'check_license', 
					'license' => $options['licenses'][$class], 
					'item_name' => urlencode( $product_name ) 
				);

				// Call the custom API.
				$response = wp_remote_get( add_query_arg( $api_params, $options['info_api_url'] ), array( 'timeout' => 15, 'sslverify' => false ) );

				if ( is_wp_error( $response ) )
					return false;

				$license_data = json_decode( wp_remote_retrieve_body( $response ) );

				return $license_data->license;
				
			}
		}

		return false;

	}
	
	public function cleanup( $is_cron = false ){

		$removedFiles = 0;

		$wp_uploads = wp_upload_dir();

		$dir = $wp_uploads['basedir'] . DIRECTORY_SEPARATOR . PMXI_Plugin::TEMP_DIRECTORY;

		$cacheDir = PMXI_Plugin::ROOT_DIR . '/libraries/cache';

		$files = array_diff(@scandir($dir), array('.','..'));

		$cacheFiles = @array_diff(@scandir($cacheDir), array('.','..'));

		$msg = __('Files not found', 'wp_all_import_plugin');

		if ( count($files) or count($cacheFiles)){

			wp_all_import_clear_directory( $dir );

			wp_all_import_clear_directory( $cacheDir );		

			$msg = __('Clean Up has been successfully completed.', 'wp_all_import_plugin');
		}

		// clean logs files
		$table = PMXI_Plugin::getInstance()->getTablePrefix() . 'history';
		global $wpdb;
		$histories = $wpdb->get_results("SELECT * FROM $table", ARRAY_A);

		if ( ! empty($histories) )
		{
			$importRecord = new PMXI_Import_Record();
			$importRecord->clear();
			foreach ($histories as $history) {
				$importRecord->getById($history['import_id']);
				if ( $importRecord->isEmpty() )
				{
					$historyRecord = new PMXI_History_Record();
					$historyRecord->getById($history['id']);
					if ( ! $historyRecord->isEmpty() ) {
						$historyRecord->delete();
					}
				}
				$importRecord->clear();
			}
		}

		// clean uploads folder
		$table = PMXI_Plugin::getInstance()->getTablePrefix() . 'files';		
		$files = $wpdb->get_results("SELECT * FROM $table", ARRAY_A);

		$required_dirs = array();

		if ( ! empty($files) )
		{
			$importRecord = new PMXI_Import_Record();
			$importRecord->clear();
			foreach ($files as $file) {
				$importRecord->getById($file['import_id']);				
				if ( $importRecord->isEmpty()){
					$fileRecord = new PMXI_File_Record();
					$fileRecord->getById($file['id']);					
					if ( ! $fileRecord->isEmpty() ) {						
						$fileRecord->delete();
					}
				}
				else
				{
					$path_parts = pathinfo(wp_all_import_get_absolute_path($file['path']));
					if ( ! empty($path_parts['dirname'])){
			            $path_all_parts = explode('/', $path_parts['dirname']);
			            $dirname = array_pop($path_all_parts);
			            if ( wp_all_import_isValidMd5($dirname)){    
			            	$required_dirs[] = $path_parts['dirname'];
			            }
			        }					
				}
				$importRecord->clear();
			}			
		}

		$uploads_dir = $wp_uploads['basedir'] . DIRECTORY_SEPARATOR . PMXI_Plugin::UPLOADS_DIRECTORY;

		if (($dir = @opendir($uploads_dir . DIRECTORY_SEPARATOR)) !== false or ($dir = @opendir($uploads_dir)) !== false) {				
			while(($file = @readdir($dir)) !== false) {
				$filePath = $uploads_dir . DIRECTORY_SEPARATOR . $file;									
				
				if ( is_dir($filePath) and ! in_array($filePath, $required_dirs) and ( ! in_array($file, array('.', '..'))))
				{
					wp_all_import_rmdir($filePath);								
				}						
			}
		}

		if ( $is_cron )
		{
			return true;
		}
		else
		{
			wp_redirect(add_query_arg('pmxi_nt', urlencode($msg), $this->baseUrl)); die();
		}		
	}

	public function dismiss(){

		PMXI_Plugin::getInstance()->updateOption("dismiss", 1);

		exit('OK');
	}

	public function dismiss_speed_up(){

		PMXI_Plugin::getInstance()->updateOption("dismiss_speed_up", 1);

		exit('OK');
	}
	
	public function meta_values(){

		if ( ! PMXI_Plugin::getInstance()->getAdminCurrentScreen()->is_ajax) { // call is only valid when send with ajax
			exit('nice try!');
		}				

		if ( ! check_ajax_referer( 'wp_all_import_secure', 'security', false ) ){
			exit( json_encode(array('meta_values' => array())) );
		}

		global $wpdb;

		$meta_key = $_POST['key'];

		$r = $wpdb->get_results("
			SELECT DISTINCT postmeta.meta_value
			FROM ".$wpdb->postmeta." as postmeta
			WHERE postmeta.meta_key='".$meta_key."' LIMIT 0,10
		", ARRAY_A);		

		$meta_values = array();
		
		if ( ! empty($r) ){
			foreach ($r as $key => $value) { if (empty($value['meta_value'])) continue;
				$meta_values[] = esc_html($value['meta_value']);
			}
		}

		exit( json_encode(array('meta_values' => $meta_values)) );
	}

	/**
	 * upload.php
	 *
	 * Copyright 2009, Moxiecode Systems AB
	 * Released under GPL License.
	 *
	 * License: http://www.plupload.com/license
	 * Contributing: http://www.plupload.com/contributing
	 */
	public function upload(){			

		if ( ! check_ajax_referer( 'wp_all_import_secure', '_wpnonce', false )){
			exit(json_encode(array("jsonrpc" => "2.0", "error" => array("code" => 100, "message" => __('Security check', 'wp_all_import_plugin')), "id" => "id")));
		}
		
		// HTTP headers for no cache etc
		// header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
		// header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
		// header("Cache-Control: no-store, no-cache, must-revalidate");
		// header("Cache-Control: post-check=0, pre-check=0", false);
		// header("Pragma: no-cache");

		// Settings
		//$targetDir = ini_get("upload_tmp_dir") . DIRECTORY_SEPARATOR . "plupload";
		//$uploads = wp_upload_dir();	

		$targetDir = self::$path;

		if (! is_dir($targetDir) || ! is_writable($targetDir)){
			delete_transient( self::$upload_transient );
			exit(json_encode(array("jsonrpc" => "2.0", "error" => array("code" => 100, "message" => __("Uploads folder is not writable.", "wp_all_import_plugin")), "id" => "id")));
		}

		$cleanupTargetDir = true; // Remove old files
		$maxFileAge = 5 * 3600; // Temp file age in seconds

		// 5 minutes execution time
		@set_time_limit(5 * 60);		

		// Uncomment this one to fake upload time
		// usleep(5000);

		// Get parameters
		$chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
		$chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0;
		$fileName = isset($_REQUEST["name"]) ? $_REQUEST["name"] : '';

		// Clean the fileName for security reasons
		$fileName = preg_replace('/[^\w\._]+/', '_', $fileName);

		if ( ! preg_match('%\W(xml|gzip|zip|csv|gz|json|txt|dat|psv|sql|xls|xlsx)$%i', trim(basename($fileName)))) {	
			exit(json_encode(array("jsonrpc" => "2.0", "error" => array("code" => 100, "message" => __("Uploaded file must be XML, CSV, ZIP, GZIP, GZ, JSON, SQL, TXT, DAT or PSV", "wp_all_import_plugin")), "id" => "id")));
		}

		// Make sure the fileName is unique but only if chunking is disabled
		if ($chunks < 2 && file_exists($targetDir . DIRECTORY_SEPARATOR . $fileName)) {
			$ext = strrpos($fileName, '.');
			$fileName_a = substr($fileName, 0, $ext);
			$fileName_b = substr($fileName, $ext);

			$count = 1;
			while (file_exists($targetDir . DIRECTORY_SEPARATOR . $fileName_a . '_' . $count . $fileName_b))
				$count++;

			$fileName = $fileName_a . '_' . $count . $fileName_b;
		}

		$filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;

		// Create target dir
		if (!file_exists($targetDir))
			@mkdir($targetDir);

		// Remove old temp files	
		if ($cleanupTargetDir && is_dir($targetDir) && ($dir = opendir($targetDir))) {
			while (($file = readdir($dir)) !== false) {
				$tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;

				// Remove temp file if it is older than the max age and is not the current file
				if (preg_match('/\.part$/', $file) && (filemtime($tmpfilePath) < time() - $maxFileAge) && ($tmpfilePath != "{$filePath}.part")) {
					@unlink($tmpfilePath);
				}
			}

			closedir($dir);
		} else{
			delete_transient( self::$upload_transient );
			exit(json_encode(array("jsonrpc" => "2.0", "error" => array("code" => 100, "message" => __("Failed to open temp directory.", "wp_all_import_plugin")), "id" => "id")));
		}
			

		// Look for the content type header
		if (isset($_SERVER["HTTP_CONTENT_TYPE"]))
			$contentType = $_SERVER["HTTP_CONTENT_TYPE"];

		if (isset($_SERVER["CONTENT_TYPE"]))
			$contentType = $_SERVER["CONTENT_TYPE"];

		// Handle non multipart uploads older WebKit versions didn't support multipart in HTML5
		if (strpos($contentType, "multipart") !== false) {			
			if (isset($_FILES['async-upload']['tmp_name']) && is_uploaded_file($_FILES['async-upload']['tmp_name'])) {
				// Open temp file
				$out = fopen("{$filePath}.part", $chunk == 0 ? "wb" : "ab");
				if ($out) {
					// Read binary input stream and append it to temp file
					$in = fopen($_FILES['async-upload']['tmp_name'], "rb");

					if ($in) {
						while ($buff = fread($in, 4096))
							fwrite($out, $buff);
					} else{
						delete_transient( self::$upload_transient );
						exit(json_encode(array("jsonrpc" => "2.0", "error" => array("code" => 101, "message" => __("Failed to open input stream.", "wp_all_import_plugin")), "id" => "id")));
					}
					fclose($in);
					fclose($out);
					@unlink($_FILES['async-upload']['tmp_name']);
				} else{
					delete_transient( self::$upload_transient );					
					exit(json_encode(array("jsonrpc" => "2.0", "error" => array("code" => 102, "message" => __("Failed to open output stream.", "wp_all_import_plugin")), "id" => "id")));
				}
			} else{
				delete_transient( self::$upload_transient );
				exit(json_encode(array("jsonrpc" => "2.0", "error" => array("code" => 103, "message" => __("Failed to move uploaded file.", "wp_all_import_plugin")), "id" => "id")));
			}
		} else {
			// Open temp file
			$out = fopen("{$filePath}.part", $chunk == 0 ? "wb" : "ab");
			if ($out) {
				// Read binary input stream and append it to temp file
				$in = fopen("php://input", "rb");

				if ($in) {
					while ($buff = fread($in, 4096))
						fwrite($out, $buff);
				} else{
					delete_transient( self::$upload_transient );
					exit(json_encode(array("jsonrpc" => "2.0", "error" => array("code" => 101, "message" => __("Failed to open input stream.", "wp_all_import_plugin")), "id" => "id")));
				}

				fclose($in);
				fclose($out);
			} else{
				delete_transient( self::$upload_transient );
				exit(json_encode(array("jsonrpc" => "2.0", "error" => array("code" => 102, "message" => __("Failed to open output stream.", "wp_all_import_plugin")), "id" => "id")));
			}
		}
		
		$post_type = false;

		$taxonomy_type = false;

		$notice = false;

		// Check if file has been uploaded
		if (!$chunks || $chunk == $chunks - 1) {
			// Strip the temp .part suffix off 
			rename("{$filePath}.part", $filePath); chmod($filePath, 0755);
			delete_transient( self::$upload_transient );

			$errors = new WP_Error;

			$uploader = new PMXI_Upload($filePath, $errors, rtrim(str_replace(basename($filePath), '', $filePath), '/'));			
			
			$upload_result = $uploader->upload();			

			if ($upload_result instanceof WP_Error){
				$errors = $upload_result;

				$msgs = $errors->get_error_messages();
				ob_start();
				?>
				<?php foreach ($msgs as $msg): ?>
					<p><?php echo $msg ?></p>
				<?php endforeach ?>
				<?php
				$response = ob_get_clean();

				exit(json_encode(array("jsonrpc" => "2.0", "error" => array("code" => 102, "message" => $response), "id" => "id")));
			}
			else 
			{
				
				if ( ! empty($upload_result['post_type'])) 
				{
					$post_type = $upload_result['post_type'];

					$taxonomy_type = $upload_result['taxonomy_type'];

					switch ( $post_type ) {

						case 'product':
						case 'shop_order':
							
							if ( ! class_exists('WooCommerce') ) {
								$notice = __('<p class="wpallimport-bundle-notice">The import bundle you are using requires WooCommerce.</p><a class="upgrade_link" href="https://wordpress.org/plugins/woocommerce/" target="_blank">Get WooCommerce</a>.', 'wp_all_import_plugin');							
							}
							else {

								if ( ! defined('PMWI_EDITION') ) {

									$notice = __('<p class="wpallimport-bundle-notice">The import bundle you are using requires the Pro version of the WooCommerce Add-On.</p><a href="http://www.wpallimport.com/checkout/?edd_action=add_to_cart&download_id=1529&edd_options%5Bprice_id%5D=1" class="upgrade_link" target="_blank">Purchase the WooCommerce Add-On</a>.', 'wp_all_import_plugin');

								}
								elseif ( PMWI_EDITION != 'paid' ) {

									$notice = __('<p class="wpallimport-bundle-notice">The import bundle you are using requires the Pro version of the WooCommerce Add-On, but you have the free version installed.</p><a href="http://www.wpallimport.com/checkout/?edd_action=add_to_cart&download_id=1529&edd_options%5Bprice_id%5D=1" target="_blank" class="upgrade_link">Purchase the WooCommerce Add-On</a>.', 'wp_all_import_plugin');

								}							
							}

							break;

						case 'import_users':

							if ( ! class_exists('PMUI_Plugin') ) {
								$notice = __('<p class="wpallimport-bundle-notice">The import bundle you are using requires the User Import Add-On.</p><a href="http://www.wpallimport.com/checkout/?edd_action=add_to_cart&download_id=1921&edd_options%5Bprice_id%5D=1" target="_blank" class="upgrade_link">Purchase the User Import Add-On</a>.', 'wp_all_import_plugin');
							}

							break;
						
						default:
							# code...
							break;
					}					
				}

				if ( ! empty($upload_result['is_empty_bundle_file']))
				{
					// Return JSON-RPC response
					exit(json_encode(array("jsonrpc" => "2.0", "error" => null, "result" => null, "id" => "id", "name" => $upload_result['filePath'], "post_type" => $post_type, "taxonomy_type" => $taxonomy_type, "notice" => $notice, "template" => $upload_result['template'], "url_bundle" => true)));
				}
				else
				{					
					// $root_element = wp_all_import_get_reader_engine( array($upload_result['filePath']), array('root_element' => $upload_result['root_element']) );	

					// if ( ! empty($root_element) and empty($upload_result['root_element']))
					// {
					// 	$upload_result['root_element'] = $root_element;
					// }

					// validate XML					
					$file = new PMXI_Chunk($upload_result['filePath'], array('element' => $upload_result['root_element']));										    					    					   												

					$is_valid = true;

					if ( ! empty($file->options['element']) ) 						
						$defaultXpath = "/". $file->options['element'];																			    		  
					else
						$is_valid = false;					

					if ( $is_valid ){

						while ($xml = $file->read()) {

					    	if ( ! empty($xml) ) { 

					      		//PMXI_Import_Record::preprocessXml($xml);
					      		$xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" . "\n" . $xml;
						      	$dom = new DOMDocument( '1.0', 'UTF-8' );
								$old = libxml_use_internal_errors(true);
								$dom->loadXML($xml);
								libxml_use_internal_errors($old);
								$xpath = new DOMXPath($dom);

								if (($elements = $xpath->query($defaultXpath)) and $elements->length){
									break;
								}	

						    }
						    /*else {
						    	$is_valid = false;
						    	break;
						    }*/

						}

						if ( empty($xml) ) $is_valid = false;
					}

					unset($file);

					if ( ! preg_match('%\W(xml)$%i', trim($upload_result['source']['path']))) @unlink($upload_result['filePath']);
					
					if ( ! $is_valid )
					{
						ob_start();					
						
						?>
						
						<div class="error inline"><p><?php _e('Please confirm you are importing a valid feed.<br/> Often, feed providers distribute feeds with invalid data, improperly wrapped HTML, line breaks where they should not be, faulty character encodings, syntax errors in the XML, and other issues.<br/><br/>WP All Import has checks in place to automatically fix some of the most common problems, but we can’t catch every single one.<br/><br/>It is also possible that there is a bug in WP All Import, and the problem is not with the feed.<br/><br/>If you need assistance, please contact support – <a href="mailto:support@wpallimport.com">support@wpallimport.com</a> – with your XML/CSV file. We will identify the problem and release a bug fix if necessary.', 'wp_all_import_plugin'); ?></p></div>
						
						<?php

						$response = ob_get_clean();

						$file_type = strtoupper(pmxi_getExtension($upload_result['source']['path']));

						$error_message = sprintf(__("This %s file has errors and is not valid.", "wp_all_import_plugin"), $file_type);

						exit(json_encode(array("jsonrpc" => "2.0", "error" => array("code" => 102, "message" => $error_message), "is_valid" => false, "id" => "id")));
					
					}
					else
					{
						$wp_uploads = wp_upload_dir();
						$uploads    = $wp_uploads['basedir'] . DIRECTORY_SEPARATOR . PMXI_Plugin::FILES_DIRECTORY . DIRECTORY_SEPARATOR;

						if ( ! file_exists($uploads . basename($filePath))) @copy($filePath, $uploads . basename($filePath));
					}
				}				
								
			}		

		}			

		// Return JSON-RPC response
		exit(json_encode(array("jsonrpc" => "2.0", "error" => null, "result" => null, "id" => "id", "name" => $filePath, "post_type" => $post_type, "taxonomy_type" => $taxonomy_type, "notice" => $notice)));

	}		

}