PluginProbe ʕ •ᴥ•ʔ
WP All Import – Drag & Drop Import for CSV, XML, Excel & Google Sheets / trunk
WP All Import – Drag & Drop Import for CSV, XML, Excel & Google Sheets vtrunk
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 3 weeks ago help.php 8 years ago history.php 3 weeks ago home.php 8 years ago import.php 3 weeks ago manage.php 3 weeks ago partners.php 3 weeks ago settings.php 3 weeks ago
settings.php
853 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 // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotValidated
446 $meta_key = sanitize_key($_POST['key']);
447
448 // phpcs:disable WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,PluginCheck.Security.DirectDB.UnescapedDBParameter
449 $r = $wpdb->get_results("
450 SELECT DISTINCT postmeta.meta_value
451 FROM ".$wpdb->postmeta." as postmeta
452 WHERE postmeta.meta_key='".$meta_key."' LIMIT 0,10
453 ", ARRAY_A);
454 // phpcs:enable WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,PluginCheck.Security.DirectDB.UnescapedDBParameter
455
456 $meta_values = array();
457
458 if ( ! empty($r) ){
459 foreach ($r as $key => $value) { if (empty($value['meta_value'])) continue;
460 $meta_values[] = esc_html($value['meta_value']);
461 }
462 }
463
464 exit( json_encode(array('meta_values' => $meta_values)) );
465 }
466
467 /**
468 * upload.php
469 *
470 * Copyright 2009, Moxiecode Systems AB
471 * Released under GPL License.
472 *
473 * License: http://www.plupload.com/license
474 * Contributing: http://www.plupload.com/contributing
475 */
476 public function upload(){
477
478 if ( ! check_ajax_referer( 'wp_all_import_secure', '_wpnonce', false )){
479 exit(json_encode(array("jsonrpc" => "2.0", "error" => array("code" => 100, "message" => __('Security check', 'wp-all-import')), "id" => "id")));
480 }
481
482 // HTTP headers for no cache etc
483 // header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
484 // header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
485 // header("Cache-Control: no-store, no-cache, must-revalidate");
486 // header("Cache-Control: post-check=0, pre-check=0", false);
487 // header("Pragma: no-cache");
488
489 // Settings
490 //$targetDir = ini_get("upload_tmp_dir") . DIRECTORY_SEPARATOR . "plupload";
491 //$uploads = wp_upload_dir();
492
493 $targetDir = self::$path;
494
495 // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_is_writable
496 if (! is_dir($targetDir) || ! is_writable($targetDir)){
497 delete_transient( self::$upload_transient );
498 exit(json_encode(array("jsonrpc" => "2.0", "error" => array("code" => 100, "message" => __("Uploads folder is not writable.", "wp-all-import")), "id" => "id")));
499 }
500
501 $cleanupTargetDir = true; // Remove old files
502 $maxFileAge = 5 * 3600; // Temp file age in seconds
503
504 // 5 minutes execution time
505 // phpcs:ignore Squiz.PHP.DiscouragedFunctions.Discouraged
506 @set_time_limit(5 * 60);
507
508 // Uncomment this one to fake upload time
509 // usleep(5000);
510
511 // Get parameters
512 $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
513 $chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0;
514 $fileName = isset($_REQUEST["name"]) ? sanitize_file_name(wp_unslash($_REQUEST["name"])) : '';
515
516 // Clean the fileName for security reasons
517 $fileName = preg_replace('/[^\w\._]+/', '_', $fileName);
518
519 if ( ! preg_match('%\W(xml|gzip|zip|csv|tsv|gz|json|txt|dat|psv|sql|xls|xlsx)$%i', trim(basename($fileName)))) {
520 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")));
521 }
522
523 // Make sure the fileName is unique but only if chunking is disabled
524 if ($chunks < 2 && file_exists($targetDir . DIRECTORY_SEPARATOR . $fileName)) {
525 $ext = strrpos($fileName, '.');
526 $fileName_a = substr($fileName, 0, $ext);
527 $fileName_b = substr($fileName, $ext);
528
529 $count = 1;
530 while (file_exists($targetDir . DIRECTORY_SEPARATOR . $fileName_a . '_' . $count . $fileName_b))
531 $count++;
532
533 $fileName = $fileName_a . '_' . $count . $fileName_b;
534 }
535
536 $filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;
537
538 // Create target dir
539 if (!file_exists($targetDir))
540 // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_mkdir
541 @mkdir($targetDir);
542
543 // Remove old temp files
544 if ($cleanupTargetDir && is_dir($targetDir) && ($dir = opendir($targetDir))) {
545 while (($file = readdir($dir)) !== false) {
546 $tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;
547
548 // Remove temp file if it is older than the max age and is not the current file
549 if (preg_match('/\.part$/', $file) && (filemtime($tmpfilePath) < time() - $maxFileAge) && ($tmpfilePath != "{$filePath}.part")) {
550 wp_delete_file($tmpfilePath);
551 }
552 }
553
554 closedir($dir);
555 } else{
556 delete_transient( self::$upload_transient );
557 exit(json_encode(array("jsonrpc" => "2.0", "error" => array("code" => 100, "message" => __("Failed to open temp directory.", "wp-all-import")), "id" => "id")));
558 }
559
560
561 // Look for the content type header
562 $contentType = '';
563 if (isset($_SERVER["HTTP_CONTENT_TYPE"]))
564 $contentType = sanitize_text_field(wp_unslash($_SERVER["HTTP_CONTENT_TYPE"]));
565
566 if (isset($_SERVER["CONTENT_TYPE"]))
567 $contentType = sanitize_text_field(wp_unslash($_SERVER["CONTENT_TYPE"]));
568
569 // 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
570 // Handle non multipart uploads older WebKit versions didn't support multipart in HTML5
571 if (strpos($contentType, "multipart") !== false) {
572 if (isset($_FILES['async-upload']['tmp_name']) && is_uploaded_file(realpath($_FILES['async-upload']['tmp_name']))) {
573 // Open temp file
574 $out = fopen("{$filePath}.part", $chunk == 0 ? "wb" : "ab");
575 if ($out) {
576 // Read binary input stream and append it to temp file
577 $in = fopen(realpath($_FILES['async-upload']['tmp_name']), "rb");
578
579 if ($in) {
580 while ($buff = fread($in, 4096))
581 fwrite($out, $buff);
582 } else{
583 delete_transient( self::$upload_transient );
584 exit(json_encode(array("jsonrpc" => "2.0", "error" => array("code" => 101, "message" => __("Failed to open input stream.", "wp-all-import")), "id" => "id")));
585 }
586 fclose($in);
587 fclose($out);
588 wp_delete_file(realpath($_FILES['async-upload']['tmp_name']));
589 } else{
590 delete_transient( self::$upload_transient );
591 exit(json_encode(array("jsonrpc" => "2.0", "error" => array("code" => 102, "message" => __("Failed to open output stream.", "wp-all-import")), "id" => "id")));
592 }
593 } else{
594 delete_transient( self::$upload_transient );
595 exit(json_encode(array("jsonrpc" => "2.0", "error" => array("code" => 103, "message" => __("Failed to move uploaded file.", "wp-all-import")), "id" => "id")));
596 }
597 } else {
598 // Open temp file
599 $out = fopen("{$filePath}.part", $chunk == 0 ? "wb" : "ab");
600 if ($out) {
601 // Read binary input stream and append it to temp file
602 $in = fopen("php://input", "rb");
603
604 if ($in) {
605 while ($buff = fread($in, 4096))
606 fwrite($out, $buff);
607 } else{
608 delete_transient( self::$upload_transient );
609 exit(json_encode(array("jsonrpc" => "2.0", "error" => array("code" => 101, "message" => __("Failed to open input stream.", "wp-all-import")), "id" => "id")));
610 }
611
612 fclose($in);
613 fclose($out);
614 } else{
615 delete_transient( self::$upload_transient );
616 exit(json_encode(array("jsonrpc" => "2.0", "error" => array("code" => 102, "message" => __("Failed to open output stream.", "wp-all-import")), "id" => "id")));
617 }
618 }
619 // 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
620
621 $post_type = false;
622
623 $notice = false;
624
625 $warning = false;
626
627 // Check if file has been uploaded
628 if (!$chunks || $chunk == $chunks - 1) {
629 // Strip the temp .part suffix off
630 // phpcs:ignore WordPress.WP.AlternativeFunctions.rename_rename
631 $res = rename("{$filePath}.part", $filePath);
632 if (!$res){
633 @copy("{$filePath}.part", $filePath);
634 wp_delete_file("{$filePath}.part");
635 }
636 // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_chmod
637 chmod($filePath, 0755);
638 delete_transient( self::$upload_transient );
639
640 $errors = new WP_Error;
641
642 // Check if alternative Excel processing is requested
643 if (!empty($_POST['use_alternative_excel']) && $_POST['use_alternative_excel'] === '1') {
644 global $wp_all_import_force_alternative_excel;
645 $wp_all_import_force_alternative_excel = true;
646
647 // Store in session for later use when import is created
648 if (!empty(PMXI_Plugin::$session)) {
649 PMXI_Plugin::$session->set('use_alternative_excel_processing', true);
650 PMXI_Plugin::$session->save_data();
651 }
652 }
653
654 $uploader = new PMXI_Upload($filePath, $errors, rtrim(str_replace(basename($filePath), '', $filePath), '/'));
655
656 $upload_result = $uploader->upload();
657
658 if ($upload_result instanceof WP_Error){
659 $errors = $upload_result;
660
661 $msgs = $errors->get_error_messages();
662 ob_start();
663 ?>
664 <?php foreach ($msgs as $msg): ?>
665 <p><?php echo wp_kses_post($msg); ?></p>
666 <?php endforeach ?>
667 <?php
668 $response = ob_get_clean();
669
670 exit(json_encode(array("jsonrpc" => "2.0", "error" => array("code" => 102, "message" => $response), "id" => "id")));
671 }
672 else
673 {
674 if ( ! empty($upload_result['post_type']))
675 {
676 $post_type = $upload_result['post_type'];
677
678 if ( ! empty($upload_result['template']) )
679 {
680
681 $template = json_decode($upload_result['template'], true);
682
683 if ( ! empty($template[0]['options']))
684 {
685 $is_show_cf_notice = ( ! empty($template[0]['options']['custom_name'])) ? true : false;
686
687 $is_show_images_notice = false;
688
689 if ( $post_type != 'product' && (
690 isset($template[0]['options']['download_featured_image']) && $template[0]['options']['download_featured_image'] != '' ||
691 isset($template[0]['options']['gallery_featured_image']) && $template[0]['options']['gallery_featured_image'] != '' ||
692 isset($template[0]['options']['featured_image']) && $template[0]['options']['featured_image'] != ''))
693 {
694 $is_show_images_notice = true;
695 }
696
697 if ( $is_show_cf_notice && $is_show_images_notice ){
698 $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');
699 }
700 else if ( $is_show_cf_notice ){
701 $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');
702 }
703 else if ( $is_show_images_notice ) {
704 $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');
705 }
706 }
707 }
708
709 switch ( $post_type ) {
710
711 case 'shop_order':
712
713 if ( ! class_exists('WooCommerce') ) {
714 $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');
715 }
716 else {
717
718 if ( ! defined('PMWI_EDITION') ) {
719
720 $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');
721
722 }
723 elseif ( PMWI_EDITION != 'paid' ) {
724
725 $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');
726
727 }
728 }
729
730 break;
731
732 case 'import_users':
733
734 if ( ! class_exists('PMUI_Plugin') ) {
735 $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');
736 }
737
738 break;
739
740
741 case 'shop_customer':
742
743 if ( ! class_exists('WooCommerce') ) {
744 $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');
745 }
746 elseif ( ! class_exists('PMUI_Plugin') ) {
747 $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');
748 }
749
750 break;
751
752 default:
753 # code...
754 break;
755 }
756 }
757
758 if ( ! empty($upload_result['is_empty_bundle_file']))
759 {
760 // Return JSON-RPC response
761 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)));
762 }
763 else
764 {
765 // $root_element = wp_all_import_get_reader_engine( array($upload_result['filePath']), array('root_element' => $upload_result['root_element']) );
766
767 // if ( ! empty($root_element) and empty($upload_result['root_element']))
768 // {
769 // $upload_result['root_element'] = $root_element;
770 // }
771
772 // validate XML
773 $file = new PMXI_Chunk($upload_result['filePath'], array('element' => $upload_result['root_element']));
774
775 $is_valid = true;
776
777 if ( ! empty($file->options['element']) )
778 $defaultXpath = "/". $file->options['element'];
779 else
780 $is_valid = false;
781
782 if ( $is_valid ){
783
784 while ($xml = $file->read()) {
785
786 if ( ! empty($xml) ) {
787
788 //PMXI_Import_Record::preprocessXml($xml);
789 $xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" . "\n" . $xml;
790
791 $dom = new DOMDocument( '1.0', 'UTF-8' );
792 $old = libxml_use_internal_errors(true);
793 $dom->loadXML($xml);
794 libxml_use_internal_errors($old);
795 $xpath = new DOMXPath($dom);
796 if (($elements = $xpath->query($defaultXpath)) and $elements->length){
797 break;
798 }
799 }
800 /*else {
801 $is_valid = false;
802 break;
803 }*/
804
805 }
806
807 if ( empty($xml) ) $is_valid = false;
808 }
809
810 unset($file);
811
812 if ( ! preg_match('%\W(xml)$%i', trim($upload_result['source']['path']))) wp_delete_file($upload_result['filePath']);
813
814 if ( ! $is_valid )
815 {
816 ob_start();
817
818 ?>
819
820 <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>
821
822 <?php
823
824 $response = ob_get_clean();
825
826 $file_type = strtoupper(pmxi_getExtension($upload_result['source']['path']));
827
828 /* translators: see placeholders in the string below */
829 $error_message = sprintf(__("Please verify that the file you uploading is a valid %s file.", "wp-all-import"), esc_attr($file_type));
830
831 exit(json_encode(array("jsonrpc" => "2.0", "error" => array("code" => 102, "message" => $error_message), "is_valid" => false, "id" => "id")));
832
833 }
834 else {
835 $copyFileAllowed = apply_filters('wp_all_import_copy_uploaded_file_into_files_folder', true);
836 if ($copyFileAllowed) {
837 $wp_uploads = wp_upload_dir();
838 $uploads = $wp_uploads['basedir'] . DIRECTORY_SEPARATOR . PMXI_Plugin::FILES_DIRECTORY . DIRECTORY_SEPARATOR;
839 if ( ! file_exists($uploads . basename($filePath))) {
840 @copy($filePath, $uploads . basename($filePath));
841 }
842 }
843 }
844 }
845 }
846 }
847
848 // Return JSON-RPC response
849 exit(json_encode(array("jsonrpc" => "2.0", "error" => null, "result" => null, "id" => "id", "name" => $filePath, "post_type" => $post_type, "notice" => $notice, "warning" => $warning)));
850
851 }
852
853 }