PluginProbe ʕ •ᴥ•ʔ
WP All Import – Drag & Drop Import for CSV, XML, Excel & Google Sheets / 4.1.1
WP All Import – Drag & Drop Import for CSV, XML, Excel & Google Sheets v4.1.1
4.1.1 3.9.5 3.9.6 4.0.0 4.0.1 4.1.0 trunk 2.12 2.13 2.14 3.0 3.0.1 3.0.2 3.0.3 3.0.4 3.1.0 3.1.1 3.1.2 3.1.3 3.1.4 3.1.5 3.2.0 3.2.1 3.2.2 3.2.3 3.2.4 3.2.5 3.2.6 3.2.7 3.2.8 3.2.9 3.3.0 3.3.1 3.3.2 3.3.3 3.3.4 3.3.5 3.3.6 3.3.7 3.3.8 3.3.9 3.4.0 3.4.1 3.4.2 3.4.3 3.4.4 3.4.5 3.4.6 3.4.7 3.4.8 3.4.9 3.5.0 3.5.1 3.5.2 3.5.3 3.5.4 3.5.5 3.5.6 3.5.7 3.5.8 3.5.9 3.6.0 3.6.1 3.6.2 3.6.3 3.6.4 3.6.5 3.6.6 3.6.7 3.6.8 3.6.9 3.7.0 3.7.1 3.7.2 3.7.3 3.7.3-beta-1.0 3.7.4 3.7.4-beta-1.0 3.7.5 3.7.6 3.7.7 3.7.8 3.7.9 3.8.0 3.9.0 3.9.1 3.9.2 3.9.3 3.9.4
wp-all-import / controllers / admin / settings.php
wp-all-import / controllers / admin Last commit date
addons.php 1 month ago help.php 8 years ago history.php 1 month ago home.php 8 years ago import.php 1 month ago manage.php 1 month ago partners.php 1 month ago settings.php 5 days ago
settings.php
848 lines
1 <?php
2 // phpcs:disable WordPress.NamingConventions.PrefixAllGlobals
3 /**
4 * Admin Settings page
5 *
6 * @author Maksym Tsypliakov <maksym.tsypliakov@gmail.com>
7 */
8 class PMXI_Admin_Settings extends PMXI_Controller_Admin {
9
10 public static $path;
11
12 public static $upload_transient;
13
14 public function __construct(){
15
16 parent::__construct();
17
18 self::$upload_transient = 'pmxi_uploads_path';
19
20 $uploads = wp_upload_dir();
21
22 $is_secure_import = PMXI_Plugin::getInstance()->getOption('secure');
23
24 if ( ! $is_secure_import ){
25
26 self::$path = wp_all_import_secure_file($uploads['basedir'] . DIRECTORY_SEPARATOR . PMXI_Plugin::UPLOADS_DIRECTORY );
27
28 }
29 else {
30
31 self::$path = get_transient( self::$upload_transient );
32
33 if ( empty(self::$path) ) {
34 self::$path = wp_all_import_secure_file($uploads['basedir'] . DIRECTORY_SEPARATOR . PMXI_Plugin::UPLOADS_DIRECTORY );
35 set_transient( self::$upload_transient, self::$path);
36 }
37 }
38
39 $sleep = apply_filters( 'wp_all_import_shard_delay', 0 );
40 usleep($sleep);
41 }
42
43 public function index() {
44
45 $this->data['post'] = $post = $this->input->post(PMXI_Plugin::getInstance()->getOption());
46
47 if ($this->input->post('is_settings_submitted')) { // save settings form
48 check_admin_referer('edit-settings', '_wpnonce_edit-settings');
49
50 if ( ! preg_match('%^\d+$%', $post['history_file_count'])) {
51 $this->errors->add('form-validation', __('History File Count must be a non-negative integer', 'wp-all-import'));
52 }
53 if ( ! preg_match('%^\d+$%', $post['history_file_age'])) {
54 $this->errors->add('form-validation', __('History Age must be a non-negative integer', 'wp-all-import'));
55 }
56 if (empty($post['html_entities'])) $post['html_entities'] = 0;
57 if (empty($post['utf8_decode'])) $post['utf8_decode'] = 0;
58
59 if ( ! $this->errors->get_error_codes()) { // no validation errors detected
60
61 PMXI_Plugin::getInstance()->updateOption($post);
62
63 if (!empty($this->data['addons']) && empty($_POST['pmxi_license_activate']) and empty($_POST['pmxi_license_deactivate'])) {
64 foreach ($this->data['addons'] as $class => $addon) {
65 $post['statuses'][$class] = $this->check_license($class);
66 }
67 PMXI_Plugin::getInstance()->updateOption($post);
68 }
69
70 isset( $_POST['pmxi_license_activate'] ) and $this->activate_licenses();
71
72 $files = new PMXI_File_List(); $files->sweepHistory(); // adjust file history to new settings specified
73
74 // phpcs:ignore WordPress.Security.SafeRedirect.wp_redirect_wp_redirect
75 wp_redirect(esc_url_raw(add_query_arg('pmxi_nt', urlencode(__('Settings saved', 'wp-all-import')), $this->baseUrl))); die();
76 }
77 }
78 /*else{
79
80 foreach ($this->data['addons'] as $class => $addon) {
81 $post['statuses'][$class] = $this->check_license($class);
82 }
83
84 PMXI_Plugin::getInstance()->updateOption($post);
85 }*/
86
87 if ($this->input->post('is_templates_submitted')) { // delete templates form
88
89 check_admin_referer('delete-templates', '_wpnonce_delete-templates');
90
91 if ($this->input->post('import_templates')){
92
93 if (!empty($_FILES)){
94 // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotValidated
95 $file_name = sanitize_file_name($_FILES['template_file']['name'] ?? '');
96 // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotValidated
97 $file_size = intval($_FILES['template_file']['size'] ?? 0);
98 // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotValidated, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
99 $tmp_name = realpath($_FILES['template_file']['tmp_name'] ?? '');
100
101 if(isset($file_name))
102 {
103
104 $filename = stripslashes($file_name);
105 $extension = strtolower(pmxi_getExtension($filename));
106
107 if (($extension != "txt"))
108 {
109 $this->errors->add('form-validation', __('Unknown File extension. Only txt files are permitted', 'wp-all-import'));
110 }
111 else {
112 $import_data = @file_get_contents($tmp_name);
113 if (!empty($import_data)){
114 $import_data = str_replace("\xEF\xBB\xBF", '', $import_data);
115 $templates_data = json_decode($import_data, true);
116
117 if ( ! empty($templates_data) ){
118 if ( ! empty($templates_data[0]['options']) && is_array($templates_data[0]['options'])){
119 $templateOptions = $templates_data[0]['options'];
120 }
121 else{
122 $templateOptions = empty($templates_data[0]['options']) ? false : \pmxi_maybe_unserialize($templates_data[0]['options']);
123 }
124 if ( empty($templateOptions) ){
125 $this->errors->add('form-validation', __('The template is invalid. Options are missing.', 'wp-all-import'));
126 }
127 else{
128 if (isset($templateOptions['is_user_export'])){
129 $this->errors->add('form-validation', __('The template you\'ve uploaded is intended to be used with WP All Export plugin.', 'wp-all-import'));
130 }
131 else{
132 $template = new PMXI_Template_Record();
133 foreach ($templates_data as $template_data) {
134 unset($template_data['id']);
135 $template->clear()->set($template_data)->insert();
136 }
137 /* translators: see placeholders in the string below */
138 wp_redirect(esc_url_raw(add_query_arg('pmxi_nt', urlencode(sprintf(_n('%d template imported', '%d templates imported', count($templates_data), 'wp-all-import'), count($templates_data))), $this->baseUrl))); die(); // phpcs:ignore WordPress.Security.SafeRedirect.wp_redirect_wp_redirect
139 }
140 }
141 }
142 else $this->errors->add('form-validation', __('Wrong imported data format', 'wp-all-import'));
143 }
144 else $this->errors->add('form-validation', __('File is empty or doesn\'t exests', 'wp-all-import'));
145 }
146 }
147 else $this->errors->add('form-validation', __('Undefined entry!', 'wp-all-import'));
148 }
149 else $this->errors->add('form-validation', __('Please select file.', 'wp-all-import'));
150
151 }
152 else{
153 $templates_ids = $this->input->post('templates', array());
154 if (empty($templates_ids)) {
155 $this->errors->add('form-validation', __('Templates must be selected', 'wp-all-import'));
156 }
157
158 if ( ! $this->errors->get_error_codes()) { // no validation errors detected
159 if ($this->input->post('delete_templates')){
160 $template = new PMXI_Template_Record();
161 foreach ($templates_ids as $template_id) {
162 $template->clear()->set('id', $template_id)->delete();
163 }
164 /* translators: see placeholders in the string below */
165 wp_redirect(esc_url_raw(add_query_arg('pmxi_nt', urlencode(sprintf(_n('%d template deleted', '%d templates deleted', count($templates_ids), 'wp-all-import'), count($templates_ids))), $this->baseUrl))); die(); // phpcs:ignore WordPress.Security.SafeRedirect.wp_redirect_wp_redirect
166 }
167 if ($this->input->post('export_templates')){
168 $export_data = array();
169 $template = new PMXI_Template_Record();
170 foreach ($templates_ids as $template_id) {
171 $export_data[] = $template->clear()->getBy('id', $template_id)->toArray(TRUE);
172 }
173
174 $uploads = wp_upload_dir();
175 $targetDir = $uploads['basedir'] . DIRECTORY_SEPARATOR . PMXI_Plugin::TEMP_DIRECTORY;
176 $export_file_name = "templates_".uniqid().".txt";
177 file_put_contents($targetDir . DIRECTORY_SEPARATOR . $export_file_name, json_encode($export_data));
178
179 PMXI_download::csv($targetDir . DIRECTORY_SEPARATOR . $export_file_name);
180
181 }
182 }
183 }
184 }
185
186 $this->render();
187 }
188
189 /*
190 *
191 * Activate licenses for main plugin and all premium addons
192 *
193 */
194 protected function activate_licenses() {
195
196 // listen for our activate button to be clicked
197 // phpcs:ignore WordPress.Security.NonceVerification.Missing
198 if( isset( $_POST['pmxi_license_activate'] ) ) {
199
200 // retrieve the license from the database
201 $options = PMXI_Plugin::getInstance()->getOption();
202
203 // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotValidated, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.MissingUnslash
204 foreach ($_POST['pmxi_license_activate'] as $class => $val) {
205
206 if (!empty($options['licenses'][$class])){
207
208 $product_name = (method_exists($class, 'getEddName')) ? call_user_func(array($class, 'getEddName')) : false;
209
210 if ( $product_name !== false ){
211 // data to send in our API request
212 $api_params = array(
213 'edd_action'=> 'activate_license',
214 'license' => $options['licenses'][$class],
215 'item_name' => urlencode( $product_name ) // the name of our product in EDD
216 );
217
218 // Call the custom API.
219 $response = wp_remote_get( esc_url_raw(add_query_arg( $api_params, $options['info_api_url'] ), array( 'timeout' => 15, 'sslverify' => false ) ));
220
221 // make sure the response came back okay
222 if ( is_wp_error( $response ) )
223 continue;
224
225 // decode the license data
226 $license_data = json_decode( wp_remote_retrieve_body( $response ) );
227
228 // $license_data->license will be either "active" or "inactive"
229
230 $options['statuses'][$class] = $license_data->license;
231
232 PMXI_Plugin::getInstance()->updateOption($options);
233 }
234 }
235
236 }
237
238 }
239 }
240
241 /*
242 *
243 * Check plugin's license
244 *
245 */
246 public static function check_license($class) {
247
248 global $wp_version;
249
250 $options = PMXI_Plugin::getInstance()->getOption();
251
252 if (!empty($options['licenses'][$class])){
253
254 $product_name = (method_exists($class, 'getEddName')) ? call_user_func(array($class, 'getEddName')) : false;
255
256 if ( $product_name !== false ){
257
258 $api_params = array(
259 'edd_action' => 'check_license',
260 'license' => $options['licenses'][$class],
261 'item_name' => urlencode( $product_name )
262 );
263
264 // Call the custom API.
265 $response = wp_remote_get( esc_url_raw(add_query_arg( $api_params, $options['info_api_url'] ), array( 'timeout' => 15, 'sslverify' => false ) ));
266
267 if ( is_wp_error( $response ) )
268 return false;
269
270 $license_data = json_decode( wp_remote_retrieve_body( $response ) );
271
272 return $license_data->license;
273
274 }
275 }
276
277 return false;
278
279 }
280
281 public function cleanup(){
282
283 // phpcs:ignore WordPress.Security.NonceVerification.Recommended
284 $nonce = (!empty($_REQUEST['_wpnonce'])) ? sanitize_text_field(wp_unslash($_REQUEST['_wpnonce'])) : '';
285 if ( ! wp_verify_nonce( $nonce, '_wpnonce-cleanup_logs' ) ) {
286 die( esc_html__('Security check', 'wp-all-import') );
287 }
288
289 $removedFiles = 0;
290
291 $wp_uploads = wp_upload_dir();
292
293 $dir = $wp_uploads['basedir'] . DIRECTORY_SEPARATOR . PMXI_Plugin::TEMP_DIRECTORY;
294
295 $cacheDir = PMXI_Plugin::ROOT_DIR . '/libraries/cache';
296
297 $files = array_diff(@scandir($dir), array('.','..'));
298
299 $cacheFiles = @scandir($cacheDir);
300 $cacheFiles = is_array($cacheFiles) ? @array_diff($cacheFiles, array('.','..')) : [];
301
302 $msg = __('Files not found', 'wp-all-import');
303
304 if ( count($files) or count($cacheFiles)){
305
306 wp_all_import_clear_directory( $dir );
307
308 wp_all_import_clear_directory( $cacheDir );
309
310 $msg = __('Clean Up has been successfully completed.', 'wp-all-import');
311 }
312
313 // clean logs files
314 $table = PMXI_Plugin::getInstance()->getTablePrefix() . 'history';
315 global $wpdb;
316 // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,PluginCheck.Security.DirectDB.UnescapedDBParameter
317 $histories = $wpdb->get_results("SELECT * FROM $table", ARRAY_A);
318
319 if ( ! empty($histories) )
320 {
321 $importRecord = new PMXI_Import_Record();
322 $importRecord->clear();
323 foreach ($histories as $history) {
324 $importRecord->getById($history['import_id']);
325 if ( $importRecord->isEmpty() )
326 {
327 $historyRecord = new PMXI_History_Record();
328 $historyRecord->getById($history['id']);
329 if ( ! $historyRecord->isEmpty() ) {
330 $historyRecord->delete();
331 }
332 }
333 $importRecord->clear();
334 }
335 }
336
337 // clean uploads folder
338 $table = PMXI_Plugin::getInstance()->getTablePrefix() . 'files';
339 // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,PluginCheck.Security.DirectDB.UnescapedDBParameter
340 $files = $wpdb->get_results("SELECT * FROM $table", ARRAY_A);
341
342 $required_dirs = array();
343
344 if ( ! empty($files) )
345 {
346 $importRecord = new PMXI_Import_Record();
347 $importRecord->clear();
348 foreach ($files as $file) {
349 $importRecord->getById($file['import_id']);
350 if ( $importRecord->isEmpty()){
351 $fileRecord = new PMXI_File_Record();
352 $fileRecord->getById($file['id']);
353 if ( ! $fileRecord->isEmpty() ) {
354 $fileRecord->delete();
355 }
356 }
357 else
358 {
359 $path_parts = pathinfo(wp_all_import_get_absolute_path($file['path']));
360 if ( ! empty($path_parts['dirname'])){
361 $path_all_parts = explode('/', $path_parts['dirname']);
362 $dirname = array_pop($path_all_parts);
363 if ( wp_all_import_isValidMd5($dirname)){
364 $required_dirs[] = $path_parts['dirname'];
365 }
366 }
367 }
368 $importRecord->clear();
369 }
370 }
371
372 $uploads_dir = $wp_uploads['basedir'] . DIRECTORY_SEPARATOR . PMXI_Plugin::UPLOADS_DIRECTORY;
373
374 if (($dir = @opendir($uploads_dir . DIRECTORY_SEPARATOR)) !== false or ($dir = @opendir($uploads_dir)) !== false) {
375 while(($file = @readdir($dir)) !== false) {
376 $filePath = $uploads_dir . DIRECTORY_SEPARATOR . $file;
377
378 if ( is_dir($filePath) and ! in_array($filePath, $required_dirs) and ( ! in_array($file, array('.', '..'))))
379 {
380 wp_all_import_rmdir($filePath);
381 }
382 }
383 }
384
385 // phpcs:ignore WordPress.Security.SafeRedirect.wp_redirect_wp_redirect
386 wp_redirect(esc_url_raw(add_query_arg('pmxi_nt', urlencode($msg), $this->baseUrl))); die();
387 }
388
389 public function dismiss(){
390
391 if ( ! check_ajax_referer( 'wp_all_import_secure', 'security', false )){
392 exit( esc_html__('Security check', 'wp-all-import'));
393 }
394
395 PMXI_Plugin::getInstance()->updateOption("dismiss", 1);
396
397 exit('OK');
398 }
399
400 public function dismiss_speed_up(){
401
402 if ( ! check_ajax_referer( 'wp_all_import_secure', 'security', false )){
403 exit( esc_html__('Security check', 'wp-all-import'));
404 }
405
406 PMXI_Plugin::getInstance()->updateOption("dismiss_speed_up", 1);
407
408 exit('OK');
409 }
410
411 public function dismiss_manage_top(){
412
413 if ( ! check_ajax_referer( 'wp_all_import_secure', 'security', false )){
414 exit( json_encode(array('result' => array(), 'failed_msgs' => array(__('Security check', 'wp-all-import')))));
415 }
416
417 PMXI_Plugin::getInstance()->updateOption("dismiss_manage_top", 1);
418
419 exit( json_encode(array('result' => 'OK')) );
420 }
421
422 public function dismiss_manage_bottom(){
423
424 if ( ! check_ajax_referer( 'wp_all_import_secure', 'security', false )){
425 exit( json_encode(array('result' => array(), 'failed_msgs' => array(__('Security check', 'wp-all-import')))));
426 }
427
428 PMXI_Plugin::getInstance()->updateOption("dismiss_manage_bottom", 1);
429
430 exit( json_encode(array('result' => 'OK')) );
431 }
432
433 public function meta_values(){
434
435 if ( ! PMXI_Plugin::getInstance()->getAdminCurrentScreen()->is_ajax) { // call is only valid when send with ajax
436 exit('nice try!');
437 }
438
439 if ( ! check_ajax_referer( 'wp_all_import_secure', 'security', false ) ){
440 exit( json_encode(array('meta_values' => array())) );
441 }
442
443 global $wpdb;
444
445 $meta_key = sanitize_text_field( wp_unslash( $_POST['key'] ) );
446
447 // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
448 $r = $wpdb->get_results($wpdb->prepare("SELECT DISTINCT postmeta.meta_value FROM {$wpdb->postmeta} as postmeta WHERE postmeta.meta_key = %s LIMIT 0,10", $meta_key), ARRAY_A);
449 // phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
450
451 $meta_values = array();
452
453 if ( ! empty($r) ){
454 foreach ($r as $key => $value) { if (empty($value['meta_value'])) continue;
455 $meta_values[] = esc_html($value['meta_value']);
456 }
457 }
458
459 exit( json_encode(array('meta_values' => $meta_values)) );
460 }
461
462 /**
463 * upload.php
464 *
465 * Copyright 2009, Moxiecode Systems AB
466 * Released under GPL License.
467 *
468 * License: http://www.plupload.com/license
469 * Contributing: http://www.plupload.com/contributing
470 */
471 public function upload(){
472
473 if ( ! check_ajax_referer( 'wp_all_import_secure', '_wpnonce', false )){
474 exit(json_encode(array("jsonrpc" => "2.0", "error" => array("code" => 100, "message" => __('Security check', 'wp-all-import')), "id" => "id")));
475 }
476
477 // HTTP headers for no cache etc
478 // header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
479 // header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
480 // header("Cache-Control: no-store, no-cache, must-revalidate");
481 // header("Cache-Control: post-check=0, pre-check=0", false);
482 // header("Pragma: no-cache");
483
484 // Settings
485 //$targetDir = ini_get("upload_tmp_dir") . DIRECTORY_SEPARATOR . "plupload";
486 //$uploads = wp_upload_dir();
487
488 $targetDir = self::$path;
489
490 // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_is_writable
491 if (! is_dir($targetDir) || ! is_writable($targetDir)){
492 delete_transient( self::$upload_transient );
493 exit(json_encode(array("jsonrpc" => "2.0", "error" => array("code" => 100, "message" => __("Uploads folder is not writable.", "wp-all-import")), "id" => "id")));
494 }
495
496 $cleanupTargetDir = true; // Remove old files
497 $maxFileAge = 5 * 3600; // Temp file age in seconds
498
499 // 5 minutes execution time
500 // phpcs:ignore Squiz.PHP.DiscouragedFunctions.Discouraged
501 @set_time_limit(5 * 60);
502
503 // Uncomment this one to fake upload time
504 // usleep(5000);
505
506 // Get parameters
507 $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
508 $chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0;
509 $fileName = isset($_REQUEST["name"]) ? sanitize_file_name(wp_unslash($_REQUEST["name"])) : '';
510
511 // Clean the fileName for security reasons
512 $fileName = preg_replace('/[^\w\._]+/', '_', $fileName);
513
514 if ( ! preg_match('%\W(xml|gzip|zip|csv|tsv|gz|json|txt|dat|psv|sql|xls|xlsx)$%i', trim(basename($fileName)))) {
515 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")), "id" => "id")));
516 }
517
518 // Make sure the fileName is unique but only if chunking is disabled
519 if ($chunks < 2 && file_exists($targetDir . DIRECTORY_SEPARATOR . $fileName)) {
520 $ext = strrpos($fileName, '.');
521 $fileName_a = substr($fileName, 0, $ext);
522 $fileName_b = substr($fileName, $ext);
523
524 $count = 1;
525 while (file_exists($targetDir . DIRECTORY_SEPARATOR . $fileName_a . '_' . $count . $fileName_b))
526 $count++;
527
528 $fileName = $fileName_a . '_' . $count . $fileName_b;
529 }
530
531 $filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;
532
533 // Create target dir
534 if (!file_exists($targetDir))
535 // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_mkdir
536 @mkdir($targetDir);
537
538 // Remove old temp files
539 if ($cleanupTargetDir && is_dir($targetDir) && ($dir = opendir($targetDir))) {
540 while (($file = readdir($dir)) !== false) {
541 $tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;
542
543 // Remove temp file if it is older than the max age and is not the current file
544 if (preg_match('/\.part$/', $file) && (filemtime($tmpfilePath) < time() - $maxFileAge) && ($tmpfilePath != "{$filePath}.part")) {
545 wp_delete_file($tmpfilePath);
546 }
547 }
548
549 closedir($dir);
550 } else{
551 delete_transient( self::$upload_transient );
552 exit(json_encode(array("jsonrpc" => "2.0", "error" => array("code" => 100, "message" => __("Failed to open temp directory.", "wp-all-import")), "id" => "id")));
553 }
554
555
556 // Look for the content type header
557 $contentType = '';
558 if (isset($_SERVER["HTTP_CONTENT_TYPE"]))
559 $contentType = sanitize_text_field(wp_unslash($_SERVER["HTTP_CONTENT_TYPE"]));
560
561 if (isset($_SERVER["CONTENT_TYPE"]))
562 $contentType = sanitize_text_field(wp_unslash($_SERVER["CONTENT_TYPE"]));
563
564 // phpcs:disable WordPress.WP.AlternativeFunctions.file_system_operations_fopen, WordPress.WP.AlternativeFunctions.file_system_operations_fread, WordPress.WP.AlternativeFunctions.file_system_operations_fwrite, WordPress.WP.AlternativeFunctions.file_system_operations_fclose, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
565 // Handle non multipart uploads older WebKit versions didn't support multipart in HTML5
566 if (strpos($contentType, "multipart") !== false) {
567 if (isset($_FILES['async-upload']['tmp_name']) && is_uploaded_file(realpath($_FILES['async-upload']['tmp_name']))) {
568 // Open temp file
569 $out = fopen("{$filePath}.part", $chunk == 0 ? "wb" : "ab");
570 if ($out) {
571 // Read binary input stream and append it to temp file
572 $in = fopen(realpath($_FILES['async-upload']['tmp_name']), "rb");
573
574 if ($in) {
575 while ($buff = fread($in, 4096))
576 fwrite($out, $buff);
577 } else{
578 delete_transient( self::$upload_transient );
579 exit(json_encode(array("jsonrpc" => "2.0", "error" => array("code" => 101, "message" => __("Failed to open input stream.", "wp-all-import")), "id" => "id")));
580 }
581 fclose($in);
582 fclose($out);
583 wp_delete_file(realpath($_FILES['async-upload']['tmp_name']));
584 } else{
585 delete_transient( self::$upload_transient );
586 exit(json_encode(array("jsonrpc" => "2.0", "error" => array("code" => 102, "message" => __("Failed to open output stream.", "wp-all-import")), "id" => "id")));
587 }
588 } else{
589 delete_transient( self::$upload_transient );
590 exit(json_encode(array("jsonrpc" => "2.0", "error" => array("code" => 103, "message" => __("Failed to move uploaded file.", "wp-all-import")), "id" => "id")));
591 }
592 } else {
593 // Open temp file
594 $out = fopen("{$filePath}.part", $chunk == 0 ? "wb" : "ab");
595 if ($out) {
596 // Read binary input stream and append it to temp file
597 $in = fopen("php://input", "rb");
598
599 if ($in) {
600 while ($buff = fread($in, 4096))
601 fwrite($out, $buff);
602 } else{
603 delete_transient( self::$upload_transient );
604 exit(json_encode(array("jsonrpc" => "2.0", "error" => array("code" => 101, "message" => __("Failed to open input stream.", "wp-all-import")), "id" => "id")));
605 }
606
607 fclose($in);
608 fclose($out);
609 } else{
610 delete_transient( self::$upload_transient );
611 exit(json_encode(array("jsonrpc" => "2.0", "error" => array("code" => 102, "message" => __("Failed to open output stream.", "wp-all-import")), "id" => "id")));
612 }
613 }
614 // phpcs:enable WordPress.WP.AlternativeFunctions.file_system_operations_fopen, WordPress.WP.AlternativeFunctions.file_system_operations_fread, WordPress.WP.AlternativeFunctions.file_system_operations_fwrite, WordPress.WP.AlternativeFunctions.file_system_operations_fclose, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
615
616 $post_type = false;
617
618 $notice = false;
619
620 $warning = false;
621
622 // Check if file has been uploaded
623 if (!$chunks || $chunk == $chunks - 1) {
624 // Strip the temp .part suffix off
625 // phpcs:ignore WordPress.WP.AlternativeFunctions.rename_rename
626 $res = rename("{$filePath}.part", $filePath);
627 if (!$res){
628 @copy("{$filePath}.part", $filePath);
629 wp_delete_file("{$filePath}.part");
630 }
631 // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_chmod
632 chmod($filePath, 0755);
633 delete_transient( self::$upload_transient );
634
635 $errors = new WP_Error;
636
637 // Check if alternative Excel processing is requested
638 if (!empty($_POST['use_alternative_excel']) && $_POST['use_alternative_excel'] === '1') {
639 global $wp_all_import_force_alternative_excel;
640 $wp_all_import_force_alternative_excel = true;
641
642 // Store in session for later use when import is created
643 if (!empty(PMXI_Plugin::$session)) {
644 PMXI_Plugin::$session->set('use_alternative_excel_processing', true);
645 PMXI_Plugin::$session->save_data();
646 }
647 }
648
649 $uploader = new PMXI_Upload($filePath, $errors, rtrim(str_replace(basename($filePath), '', $filePath), '/'));
650
651 $upload_result = $uploader->upload();
652
653 if ($upload_result instanceof WP_Error){
654 $errors = $upload_result;
655
656 $msgs = $errors->get_error_messages();
657 ob_start();
658 ?>
659 <?php foreach ($msgs as $msg): ?>
660 <p><?php echo wp_kses_post($msg); ?></p>
661 <?php endforeach ?>
662 <?php
663 $response = ob_get_clean();
664
665 exit(json_encode(array("jsonrpc" => "2.0", "error" => array("code" => 102, "message" => $response), "id" => "id")));
666 }
667 else
668 {
669 if ( ! empty($upload_result['post_type']))
670 {
671 $post_type = $upload_result['post_type'];
672
673 if ( ! empty($upload_result['template']) )
674 {
675
676 $template = json_decode($upload_result['template'], true);
677
678 if ( ! empty($template[0]['options']))
679 {
680 $is_show_cf_notice = ( ! empty($template[0]['options']['custom_name'])) ? true : false;
681
682 $is_show_images_notice = false;
683
684 if ( $post_type != 'product' && (
685 isset($template[0]['options']['download_featured_image']) && $template[0]['options']['download_featured_image'] != '' ||
686 isset($template[0]['options']['gallery_featured_image']) && $template[0]['options']['gallery_featured_image'] != '' ||
687 isset($template[0]['options']['featured_image']) && $template[0]['options']['featured_image'] != ''))
688 {
689 $is_show_images_notice = true;
690 }
691
692 if ( $is_show_cf_notice && $is_show_images_notice ){
693 $warning = __('<a class="upgrade_link" target="_blank" href="https://www.wpallimport.com/checkout/?edd_action=add_to_cart&download_id=5839966&edd_options%5Bprice_id%5D=1&discount=welcome-upgrade-99&utm_source=import-plugin-free&utm_medium=upgrade-notice&utm_campaign=images">Upgrade to the Pro edition of WP All Import to Import Images and Custom Fields</a> <p>If you already own it, remove the free edition and install the Pro edition.</p>', 'wp-all-import');
694 }
695 else if ( $is_show_cf_notice ){
696 $warning = __('<a class="upgrade_link" target="_blank" href="https://www.wpallimport.com/checkout/?edd_action=add_to_cart&download_id=5839966&edd_options%5Bprice_id%5D=1&discount=welcome-upgrade-99&utm_source=import-plugin-free&utm_medium=upgrade-notice&utm_campaign=custom-fields">Upgrade to the Pro edition of WP All Import to Import Custom Fields</a> <p>If you already own it, remove the free edition and install the Pro edition.</p>', 'wp-all-import');
697 }
698 else if ( $is_show_images_notice ) {
699 $warning = __('<a class="upgrade_link" target="_blank" href="https://www.wpallimport.com/checkout/?edd_action=add_to_cart&download_id=5839966&edd_options%5Bprice_id%5D=1&discount=welcome-upgrade-99&utm_source=import-plugin-free&utm_medium=upgrade-notice&utm_campaign=images">Upgrade to the Pro edition of WP All Import to Import Images</a> <p>If you already own it, remove the free edition and install the Pro edition.</p>', 'wp-all-import');
700 }
701 }
702 }
703
704 switch ( $post_type ) {
705
706 case 'shop_order':
707
708 if ( ! class_exists('WooCommerce') ) {
709 $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');
710 }
711 else {
712
713 if ( ! defined('PMWI_EDITION') ) {
714
715 $notice = __('<p class="wpallimport-bundle-notice">The import bundle you are using requires the Pro version of the WooCommerce Add-On.</p><a href="https://www.wpallimport.com/checkout/?edd_action=add_to_cart&download_id=5839961&edd_options%5Bprice_id%5D=1&discount=welcome-upgrade-169&utm_source=import-plugin-free&utm_medium=upgrade-notice&utm_campaign=import-wooco-bundle" class="upgrade_link" target="_blank">Purchase the WooCommerce Add-On</a>', 'wp-all-import');
716
717 }
718 elseif ( PMWI_EDITION != 'paid' ) {
719
720 $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="https://www.wpallimport.com/checkout/?edd_action=add_to_cart&download_id=5839961&edd_options%5Bprice_id%5D=1&discount=welcome-upgrade-169&utm_source=import-plugin-free&utm_medium=upgrade-notice&utm_campaign=import-wooco-bundle" target="_blank" class="upgrade_link">Purchase the WooCommerce Add-On</a>', 'wp-all-import');
721
722 }
723 }
724
725 break;
726
727 case 'import_users':
728
729 if ( ! class_exists('PMUI_Plugin') ) {
730 $notice = __('<p class="wpallimport-bundle-notice">The import bundle you are using requires the User Add-On.</p><a href="https://www.wpallimport.com/checkout/?edd_action=add_to_cart&download_id=5839963&edd_options%5Bprice_id%5D=1&discount=welcome-upgrade-169&utm_source=import-plugin-free&utm_medium=upgrade-notice&utm_campaign=import-users" target="_blank" class="upgrade_link">Purchase the User Add-On</a>.', 'wp-all-import');
731 }
732
733 break;
734
735
736 case 'shop_customer':
737
738 if ( ! class_exists('WooCommerce') ) {
739 $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');
740 }
741 elseif ( ! class_exists('PMUI_Plugin') ) {
742 $notice = __('<p class="wpallimport-bundle-notice">The import bundle you are using requires the User Add-On.</p><p class="wpallimport-upgrade-links-container"><a href="https://www.wpallimport.com/checkout/?edd_action=add_to_cart&download_id=5839963&edd_options%5Bprice_id%5D=1&discount=welcome-upgrade-169&utm_source=import-plugin-free&utm_medium=upgrade-notice&utm_campaign=import-users" target="_blank" class="upgrade_link">Purchase the User Add-On</a></p>', 'wp-all-import');
743 }
744
745 break;
746
747 default:
748 # code...
749 break;
750 }
751 }
752
753 if ( ! empty($upload_result['is_empty_bundle_file']))
754 {
755 // Return JSON-RPC response
756 exit(json_encode(array("jsonrpc" => "2.0", "error" => null, "result" => null, "id" => "id", "name" => $upload_result['filePath'], "post_type" => $post_type, "notice" => $notice, "template" => $upload_result['template'], "url_bundle" => true)));
757 }
758 else
759 {
760 // $root_element = wp_all_import_get_reader_engine( array($upload_result['filePath']), array('root_element' => $upload_result['root_element']) );
761
762 // if ( ! empty($root_element) and empty($upload_result['root_element']))
763 // {
764 // $upload_result['root_element'] = $root_element;
765 // }
766
767 // validate XML
768 $file = new PMXI_Chunk($upload_result['filePath'], array('element' => $upload_result['root_element']));
769
770 $is_valid = true;
771
772 if ( ! empty($file->options['element']) )
773 $defaultXpath = "/". $file->options['element'];
774 else
775 $is_valid = false;
776
777 if ( $is_valid ){
778
779 while ($xml = $file->read()) {
780
781 if ( ! empty($xml) ) {
782
783 //PMXI_Import_Record::preprocessXml($xml);
784 $xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" . "\n" . $xml;
785
786 $dom = new DOMDocument( '1.0', 'UTF-8' );
787 $old = libxml_use_internal_errors(true);
788 $dom->loadXML($xml);
789 libxml_use_internal_errors($old);
790 $xpath = new DOMXPath($dom);
791 if (($elements = $xpath->query($defaultXpath)) and $elements->length){
792 break;
793 }
794 }
795 /*else {
796 $is_valid = false;
797 break;
798 }*/
799
800 }
801
802 if ( empty($xml) ) $is_valid = false;
803 }
804
805 unset($file);
806
807 if ( ! preg_match('%\W(xml)$%i', trim($upload_result['source']['path']))) wp_delete_file($upload_result['filePath']);
808
809 if ( ! $is_valid )
810 {
811 ob_start();
812
813 ?>
814
815 <div class="error inline"><p><?php echo wp_kses( __('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'), array('br' => array(), 'a' => array('href' => array())) ); ?></p></div>
816
817 <?php
818
819 $response = ob_get_clean();
820
821 $file_type = strtoupper(pmxi_getExtension($upload_result['source']['path']));
822
823 /* translators: see placeholders in the string below */
824 $error_message = sprintf(__("Please verify that the file you uploading is a valid %s file.", "wp-all-import"), esc_attr($file_type));
825
826 exit(json_encode(array("jsonrpc" => "2.0", "error" => array("code" => 102, "message" => $error_message), "is_valid" => false, "id" => "id")));
827
828 }
829 else {
830 $copyFileAllowed = apply_filters('wp_all_import_copy_uploaded_file_into_files_folder', true);
831 if ($copyFileAllowed) {
832 $wp_uploads = wp_upload_dir();
833 $uploads = $wp_uploads['basedir'] . DIRECTORY_SEPARATOR . PMXI_Plugin::FILES_DIRECTORY . DIRECTORY_SEPARATOR;
834 if ( ! file_exists($uploads . basename($filePath))) {
835 @copy($filePath, $uploads . basename($filePath));
836 }
837 }
838 }
839 }
840 }
841 }
842
843 // Return JSON-RPC response
844 exit(json_encode(array("jsonrpc" => "2.0", "error" => null, "result" => null, "id" => "id", "name" => $filePath, "post_type" => $post_type, "notice" => $notice, "warning" => $warning)));
845
846 }
847
848 }