function pmxi_wp_ajax_nested_merge()
{
    if (!check_ajax_referer('wp_all_import_secure', 'security', false)) {
        exit(json_encode(array('success' => false, 'msg' => __('Security check', 'wp_all_import_plugin'))));
    }
    if (!current_user_can(PMXI_Plugin::$capabilities)) {
        exit(json_encode(array('success' => false, 'msg' => __('Security check', 'wp_all_import_plugin'))));
    }
    $input = new PMXI_Input();
    $post = $input->post(array('filePath' => ''));
    PMXI_Plugin::$session = PMXI_Session::get_instance();
    /*$nested_file = array(
    		'file' => $filePath,
    		'source' => $realPath,
    		'xpath' => $customXpath,
    		'root_element' => $root_element,
    		'main_xml_field' => $main_xml_field,
    		'child_xml_field' => $child_xml_field
    	);		*/
    $nested_files = empty(PMXI_Plugin::$session->options['nested_files']) ? array() : json_decode(PMXI_Plugin::$session->options['nested_files'], true);
    $nested_files[] = $post['filePath'];
    $options = PMXI_Plugin::$session->options;
    $options['nested_files'] = json_encode($nested_files);
    PMXI_Plugin::$session->set('options', $options);
    PMXI_Plugin::$session->save_data();
    exit(json_encode(array('success' => true, 'nested_files' => $nested_files)));
    die;
}
Exemplo n.º 2
0
function pmxi_admin_notices()
{
    // notify user if history folder is not writable
    $uploads = wp_upload_dir();
    if (!@is_dir($uploads['basedir'] . '/wpallimport_history') or !@is_writable($uploads['basedir'] . '/wpallimport_history')) {
        ?>
		<div class="error"><p>
			<?php 
        printf(__('<b>%s Plugin</b>: History folder %s must be writable for the plugin to function properly. Please deactivate the plugin, set proper permissions to the folder and activate the plugin again.', 'pmxi_plugin'), PMXI_Plugin::getInstance()->getName(), $uploads['basedir'] . '/wpallimport_history');
        ?>
		</p></div>
		<?php 
    }
    // notify user
    if (!PMXI_Plugin::getInstance()->getOption('dismiss') and strpos($_SERVER['REQUEST_URI'], 'pmxi-admin') !== false) {
        ?>
		<div class="updated"><p>
			<?php 
        printf(__('Welcome to WP All Import. We hope you like it. Please send all support requests and feedback to <a href="mailto:support@soflyy.com">support@soflyy.com</a>.<br/><br/><a href="javascript:void(0);" id="dismiss">dismiss</a>', 'pmxi_plugin'));
        ?>
		</p></div>
		<?php 
    }
    if (class_exists('PMWI_Plugin') and (defined('PMWI_VERSION') and version_compare(PMWI_VERSION, '1.2.8') <= 0 and PMWI_EDITION == 'paid' or defined('PMWI_FREE_VERSION') and version_compare(PMWI_FREE_VERSION, '1.1.1') <= 0 and PMWI_EDITION == 'free')) {
        ?>
		<div class="error"><p>
			<?php 
        printf(__('<b>%s Plugin</b>: Please update your WP All Import WooCommerce add-on to the latest version</a>', 'pmwi_plugin'), PMWI_Plugin::getInstance()->getName());
        ?>
		</p></div>
		<?php 
        if (defined('PMWI_EDITION') and PMWI_EDITION == 'paid') {
            deactivate_plugins(PMWI_ROOT_DIR . '/plugin.php');
        } else {
            deactivate_plugins(PMWI_FREE_ROOT_DIR . '/plugin.php');
        }
    }
    $input = new PMXI_Input();
    $messages = $input->get('pmxi_nt', array());
    if ($messages) {
        is_array($messages) or $messages = array($messages);
        foreach ($messages as $type => $m) {
            in_array((string) $type, array('updated', 'error')) or $type = 'updated';
            ?>
			<div class="<?php 
            echo $type;
            ?>
"><p><?php 
            echo $m;
            ?>
</p></div>
			<?php 
        }
    }
}
function pmxi_wp_session_garbage_collection()
{
    global $wpdb;
    if (defined('WP_SETUP_CONFIG')) {
        return;
    }
    $session_mode = PMXI_Plugin::getInstance()->getOption('session_mode');
    if (!defined('WP_INSTALLING')) {
        if ($session_mode == 'database') {
            $expiration_keys = $wpdb->get_results("SELECT option_name, option_value FROM {$wpdb->options} WHERE option_name LIKE '_pmxi_session_expires_%'");
            $now = time();
            $expired_sessions = array();
            foreach ($expiration_keys as $expiration) {
                // If the session has expired
                if ($now > intval($expiration->option_value)) {
                    // Get the session ID by parsing the option_name
                    $session_id = str_replace("_pmxi_session_expires_", "", $expiration->option_name);
                    $expired_sessions[] = $expiration->option_name;
                    $expired_sessions[] = "_pmxi_session_{$session_id}";
                }
            }
            // Delete all expired sessions in a single query
            if (!empty($expired_sessions)) {
                $option_names = implode("','", $expired_sessions);
                $wpdb->query("DELETE FROM {$wpdb->options} WHERE option_name IN ('{$option_names}')");
            }
        } elseif ($session_mode == 'files') {
            $session_files = scandir(PMXI_ROOT_DIR . '/sessions');
            if (!empty($session_files)) {
                $now = time();
                $expired_sessions = array();
                foreach ($session_files as $key => $file) {
                    if (strpos($file, "_pmxi_session_expires_") !== false) {
                        $expiration_value = @file_get_contents(PMXI_ROOT_DIR . "/sessions/" . $file);
                        if ($now > intval($expiration_value)) {
                            $session_id = str_replace("_pmxi_session_expires_", "", $file);
                            $expired_sessions[] = $file;
                            $expired_sessions[] = "_pmxi_session_{$session_id}";
                        }
                    }
                }
                // Delete all expired sessions in a single query
                if (!empty($expired_sessions)) {
                    foreach ($expired_sessions as $key => $file) {
                        @unlink(PMXI_ROOT_DIR . "/sessions/" . $file);
                    }
                }
            }
        }
    }
    // Allow other plugins to hook in to the garbage collection process.
    do_action('pmxi_session_cleanup');
}
 function wp_all_import_secure_file($targetDir, $importID = false)
 {
     $is_secure_import = PMXI_Plugin::getInstance()->getOption('secure');
     if ($is_secure_import) {
         $dir = $targetDir . DIRECTORY_SEPARATOR . ($importID ? md5($importID . NONCE_SALT) : md5(time() . NONCE_SALT));
         @mkdir($dir, 0755);
         if (@is_writable($dir) and @is_dir($dir)) {
             $targetDir = $dir;
             @touch($dir . DIRECTORY_SEPARATOR . 'index.php');
         }
     }
     return $targetDir;
 }
Exemplo n.º 5
0
/**
 * Register plugin specific admin menu
 */
function pmxi_admin_menu()
{
    global $menu, $submenu;
    if (current_user_can('manage_options')) {
        // admin management options
        $wpai_menu = array(array('pmxi-admin-import', __('New Import', 'pmxi_plugin')), array('pmxi-admin-manage', __('Manage Imports', 'pmxi_plugin')), array('pmxi-admin-settings', __('Settings', 'pmxi_plugin')), array('pmxi-admin-history', __('History', 'pmxi_plugin')));
        $wpai_menu = apply_filters('pmxi_admin_menu', $wpai_menu);
        add_menu_page(__('WP All Import', 'pmxi_plugin'), __('All Import', 'pmxi_plugin'), 'manage_options', 'pmxi-admin-home', array(PMXI_Plugin::getInstance(), 'adminDispatcher'), PMXI_Plugin::ROOT_URL . '/static/img/xmlicon.png');
        // workaround to rename 1st option to `Home`
        $submenu['pmxi-admin-home'] = array();
        foreach ($wpai_menu as $key => $value) {
            add_submenu_page('pmxi-admin-home', $value[1], $value[1], 'manage_options', $value[0], array(PMXI_Plugin::getInstance(), 'adminDispatcher'));
        }
    }
}
Exemplo n.º 6
0
function pmxi_wp_ajax_unmerge_file()
{
    extract($_POST);
    PMXI_Plugin::$session = PMXI_Session::get_instance();
    if (!empty(PMXI_Plugin::$session->options['nested_files'])) {
        $nested_files = json_decode(PMXI_Plugin::$session->options['nested_files'], true);
        unset($nested_files[$source]);
        $options = PMXI_Plugin::$session->options;
        $options['nested_files'] = json_encode($nested_files);
        PMXI_Plugin::$session->set('options', $options);
        PMXI_Plugin::$session->save_data();
        exit(json_encode(array('success' => true, 'nested_files' => $nested_files)));
        die;
    }
    exit(json_encode(array('success' => false)));
    die;
}
 function wp_all_import_secure_file($targetDir, $importID = false, $remove_dir = false)
 {
     $is_secure_import = PMXI_Plugin::getInstance()->getOption('secure');
     if ($is_secure_import) {
         $dir = $targetDir . DIRECTORY_SEPARATOR . ($importID ? md5($importID . NONCE_SALT) : md5(time() . NONCE_SALT));
         if (@is_dir($dir) and $remove_dir) {
             wp_all_import_remove_source($dir . DIRECTORY_SEPARATOR . 'index.php');
         }
         @wp_mkdir_p($dir);
         if (@is_writable($dir) and @is_dir($dir)) {
             $targetDir = $dir;
             if (!@file_exists($dir . DIRECTORY_SEPARATOR . 'index.php')) {
                 @touch($dir . DIRECTORY_SEPARATOR . 'index.php');
             }
         }
     }
     return $targetDir;
 }
Exemplo n.º 8
0
 /**
  * Default constructor.
  * Will rebuild the session collection from the given session ID if it exists. Otherwise, will
  * create a new session with that ID.
  *
  * @param $session_id
  * @uses apply_filters Calls `wp_session_expiration` to determine how long until sessions expire.
  */
 protected function __construct()
 {
     if (version_compare(phpversion(), '5.4.0') >= 0 and session_status() == PHP_SESSION_DISABLED or 'default' == PMXI_Plugin::getInstance()->getOption('session_mode') and !session_id() and !@session_start()) {
         PMXI_Plugin::getInstance()->updateOption(array('session_mode' => 'files'));
     }
     $this->session_mode = PMXI_Plugin::getInstance()->getOption('session_mode');
     if ($this->session_mode != 'default') {
         if (isset($_COOKIE[PMXI_SESSION_COOKIE])) {
             $cookie = stripslashes($_COOKIE[PMXI_SESSION_COOKIE]);
             $cookie_crumbs = explode('||', $cookie);
             $this->session_id = !empty($cookie_crumbs[0]) ? $cookie_crumbs[0] : $this->generate_id();
             $this->expires = $cookie_crumbs[1];
             $this->exp_variant = $cookie_crumbs[2];
             // Update the session expiration if we're past the variant time
             if (time() > $this->exp_variant) {
                 $this->set_expiration();
                 if ($this->session_mode == 'database') {
                     update_option("_pmxi_session_expires_{$this->session_id}", $this->expires);
                 } elseif ($this->session_mode == 'files') {
                     @file_put_contents(PMXI_ROOT_DIR . "/sessions/_pmxi_session_expires_{$this->session_id}.txt", $this->expires);
                 }
             }
         } else {
             $this->session_id = $this->generate_id();
             $this->set_expiration();
         }
     } else {
         try {
             $path = @session_save_path();
             if (!@is_dir($path) or !@is_writable($path)) {
                 @ini_set("session.save_handler", "files");
                 @session_save_path(sys_get_temp_dir());
             }
         } catch (XmlImportException $e) {
         }
         // enable sessions
         if (!session_id()) {
             @session_start();
         }
     }
     $this->read_data();
     $this->set_cookie();
 }
Exemplo n.º 9
0
function pmxi_wp_ajax_nested_merge()
{
    extract($_POST);
    PMXI_Plugin::$session = PMXI_Session::get_instance();
    /*$nested_file = array(
    		'file' => $filePath,
    		'source' => $realPath,
    		'xpath' => $customXpath,
    		'root_element' => $root_element,
    		'main_xml_field' => $main_xml_field,
    		'child_xml_field' => $child_xml_field
    	);		*/
    $nested_files = empty(PMXI_Plugin::$session->options['nested_files']) ? array() : json_decode(PMXI_Plugin::$session->options['nested_files'], true);
    $nested_files[] = $filePath;
    $options = PMXI_Plugin::$session->options;
    $options['nested_files'] = json_encode($nested_files);
    PMXI_Plugin::$session->set('options', $options);
    PMXI_Plugin::$session->save_data();
    exit(json_encode(array('success' => true, 'nested_files' => $nested_files)));
    die;
}
Exemplo n.º 10
0
 /**
  * Sweep history files in accordance with plugin settings
  * @return PMXI_File_List
  * @chainable
  */
 public function sweepHistory()
 {
     $age = PMXI_Plugin::getInstance()->getOption('history_file_age');
     if ($age > 0) {
         $date = new DateTime();
         $date->modify('-' . $age . ' day');
         foreach ($this->getBy('registered_on <', $date->format('Y-m-d'))->convertRecords() as $f) {
             $f->delete();
         }
     }
     $count = PMXI_Plugin::getInstance()->getOption('history_file_count');
     if ($count > 0) {
         $count_actual = $this->countBy();
         if ($count_actual > $count) {
             foreach ($this->getBy(NULL, 'registered_on', 1, $count_actual - $count)->convertRecords() as $f) {
                 $f->delete();
             }
         }
     }
     return $this;
 }
function pmxi_wp_ajax_unmerge_file()
{
    if (!check_ajax_referer('wp_all_import_secure', 'security', false)) {
        exit(json_encode(array('success' => false, 'msg' => __('Security check', 'wp_all_import_plugin'))));
    }
    if (!current_user_can('manage_options')) {
        exit(json_encode(array('success' => false, 'msg' => __('Security check', 'wp_all_import_plugin'))));
    }
    $input = new PMXI_Input();
    $post = $input->post(array('source' => ''));
    PMXI_Plugin::$session = PMXI_Session::get_instance();
    if (!empty(PMXI_Plugin::$session->options['nested_files']) and !empty($post['source'])) {
        $nested_files = json_decode(PMXI_Plugin::$session->options['nested_files'], true);
        unset($nested_files[$post['source']]);
        $options = PMXI_Plugin::$session->options;
        $options['nested_files'] = json_encode($nested_files);
        PMXI_Plugin::$session->set('options', $options);
        PMXI_Plugin::$session->save_data();
        exit(json_encode(array('success' => true, 'nested_files' => $nested_files)));
        die;
    }
    exit(json_encode(array('success' => false)));
    die;
}
Exemplo n.º 12
0
 /**
  * data load initialize
  *
  * @param mixed $filename please look at the load() method
  *
  * @access public
  * @see load()
  * @return void
  */
 public function __construct($options = array('filename' => null, 'xpath' => '', 'delimiter' => '', 'encoding' => '', 'xml_path' => '', 'targetDir' => false))
 {
     PMXI_Plugin::$csv_path = $options['filename'];
     $this->xpath = !empty($options['xpath']) ? $options['xpath'] : (!empty($_POST['xpath']) ? $_POST['xpath'] : '/node');
     if (!empty($options['delimiter'])) {
         $this->delimiter = $options['delimiter'];
     } else {
         $input = new PMXI_Input();
         $id = $input->get('id', 0);
         if (!$id) {
             $id = $input->get('import_id', 0);
         }
         if ($id) {
             $import = new PMXI_Import_Record();
             $import->getbyId($id);
             if (!$import->isEmpty()) {
                 $this->delimiter = $import->options['delimiter'];
             }
         }
     }
     if (!empty($options['encoding'])) {
         $this->csv_encoding = $options['encoding'];
         $this->auto_encoding = false;
     }
     if (!empty($options['xml_path'])) {
         $this->xml_path = $options['xml_path'];
     }
     @ini_set("display_errors", 0);
     @ini_set('auto_detect_line_endings', true);
     $file_params = self::analyse_file($options['filename'], 1);
     $this->set_settings(array('delimiter' => $file_params['delimiter']['value'], 'eol' => $file_params['line_ending']['value']));
     unset($file_params);
     $wp_uploads = wp_upload_dir();
     $this->targetDir = empty($options['targetDir']) ? wp_all_import_secure_file($wp_uploads['basedir'] . DIRECTORY_SEPARATOR . PMXI_Plugin::UPLOADS_DIRECTORY) : $options['targetDir'];
     $this->load($options['filename']);
 }
Exemplo n.º 13
0
function pmxi_wp_loaded()
{
    @ini_set("max_input_time", PMXI_Plugin::getInstance()->getOption('max_input_time'));
    @ini_set("max_execution_time", PMXI_Plugin::getInstance()->getOption('max_execution_time'));
    $table = PMXI_Plugin::getInstance()->getTablePrefix() . 'imports';
    global $wpdb;
    $imports = $wpdb->get_results("SELECT `id`, `name`, `path` FROM {$table} WHERE `path` IS NULL", ARRAY_A);
    if (!empty($imports)) {
        $importRecord = new PMXI_Import_Record();
        $importRecord->clear();
        foreach ($imports as $imp) {
            $importRecord->getById($imp['id']);
            if (!$importRecord->isEmpty()) {
                $importRecord->delete(true);
            }
            $importRecord->clear();
        }
    }
    /* Check if cron is manualy, then execute import */
    $cron_job_key = PMXI_Plugin::getInstance()->getOption('cron_job_key');
    if (!empty($cron_job_key) and !empty($_GET['import_id']) and !empty($_GET['import_key']) and $_GET['import_key'] == $cron_job_key and !empty($_GET['action']) and in_array($_GET['action'], array('processing', 'trigger', 'pipe'))) {
        $logger = create_function('$m', 'echo "<p>$m</p>\\n";');
        $import = new PMXI_Import_Record();
        $ids = explode(',', $_GET['import_id']);
        if (!empty($ids) and is_array($ids)) {
            foreach ($ids as $id) {
                if (empty($id)) {
                    continue;
                }
                $import->getById($id);
                if (!$import->isEmpty()) {
                    if (!in_array($import->type, array('url', 'ftp', 'file'))) {
                        $logger and call_user_func($logger, sprintf(__('Scheduling update is not working with "upload" import type. Import #%s.', 'wp_all_import_plugin'), $id));
                    }
                    switch ($_GET['action']) {
                        case 'trigger':
                            if ((int) $import->executing) {
                                $logger and call_user_func($logger, sprintf(__('Import #%s is currently in manually process. Request skipped.', 'wp_all_import_plugin'), $id));
                            } elseif (!$import->processing and !$import->triggered) {
                                $import->set(array('triggered' => 1, 'imported' => 0, 'created' => 0, 'updated' => 0, 'skipped' => 0, 'deleted' => 0, 'queue_chunk_number' => 0, 'last_activity' => date('Y-m-d H:i:s')))->update();
                                $history_log = new PMXI_History_Record();
                                $history_log->set(array('import_id' => $import->id, 'date' => date('Y-m-d H:i:s'), 'type' => 'trigger', 'summary' => __("triggered by cron", "wp_all_import_plugin")))->save();
                                $logger and call_user_func($logger, sprintf(__('#%s Cron job triggered.', 'wp_all_import_plugin'), $id));
                            } elseif ($import->processing and !$import->triggered) {
                                $logger and call_user_func($logger, sprintf(__('Import #%s currently in process. Request skipped.', 'wp_all_import_plugin'), $id));
                            } elseif (!$import->processing and $import->triggered) {
                                $logger and call_user_func($logger, sprintf(__('Import #%s already triggered. Request skipped.', 'wp_all_import_plugin'), $id));
                            }
                            break;
                        case 'processing':
                            if ($import->processing == 1 and time() - strtotime($import->registered_on) > (PMXI_Plugin::getInstance()->getOption('cron_processing_time_limit') ? PMXI_Plugin::getInstance()->getOption('cron_processing_time_limit') : 120)) {
                                // it means processor crashed, so it will reset processing to false, and terminate. Then next run it will work normally.
                                $import->set(array('processing' => 0))->update();
                            }
                            // start execution imports that is in the cron process
                            if (!(int) $import->triggered) {
                                $logger and call_user_func($logger, sprintf(__('Import #%s is not triggered. Request skipped.', 'wp_all_import_plugin'), $id));
                            } elseif ((int) $import->executing) {
                                $logger and call_user_func($logger, sprintf(__('Import #%s is currently in manually process. Request skipped.', 'wp_all_import_plugin'), $id));
                            } elseif ((int) $import->triggered and !(int) $import->processing) {
                                $log_storage = (int) PMXI_Plugin::getInstance()->getOption('log_storage');
                                // unlink previous logs
                                $by = array();
                                $by[] = array(array('import_id' => $id, 'type NOT LIKE' => 'trigger'), 'AND');
                                $historyLogs = new PMXI_History_List();
                                $historyLogs->setColumns('id', 'import_id', 'type', 'date')->getBy($by, 'id ASC');
                                if ($historyLogs->count() and $historyLogs->count() >= $log_storage) {
                                    $logsToRemove = $historyLogs->count() - $log_storage;
                                    foreach ($historyLogs as $i => $file) {
                                        $historyRecord = new PMXI_History_Record();
                                        $historyRecord->getBy('id', $file['id']);
                                        if (!$historyRecord->isEmpty()) {
                                            $historyRecord->delete();
                                        }
                                        // unlink history file only
                                        if ($i == $logsToRemove) {
                                            break;
                                        }
                                    }
                                }
                                $history_log = new PMXI_History_Record();
                                $history_log->set(array('import_id' => $import->id, 'date' => date('Y-m-d H:i:s'), 'type' => 'processing', 'summary' => __("cron processing", "wp_all_import_plugin")))->save();
                                if ($log_storage) {
                                    $wp_uploads = wp_upload_dir();
                                    $log_file = wp_all_import_secure_file($wp_uploads['basedir'] . DIRECTORY_SEPARATOR . PMXI_Plugin::LOGS_DIRECTORY, $history_log->id) . DIRECTORY_SEPARATOR . $history_log->id . '.html';
                                    if (@file_exists($log_file)) {
                                        wp_all_import_remove_source($log_file, false);
                                    }
                                }
                                ob_start();
                                $import->set(array('canceled' => 0, 'failed' => 0))->execute($logger, true, $history_log->id);
                                $log_data = ob_get_clean();
                                if ($log_storage) {
                                    $log = @fopen($log_file, 'a+');
                                    @fwrite($log, $log_data);
                                    @fclose($log);
                                }
                                if (!(int) $import->queue_chunk_number) {
                                    $logger and call_user_func($logger, sprintf(__('Import #%s complete', 'wp_all_import_plugin'), $import->id));
                                } else {
                                    $logger and call_user_func($logger, sprintf(__('Records Count %s', 'wp_all_import_plugin'), (int) $import->count));
                                    $logger and call_user_func($logger, sprintf(__('Records Processed %s', 'wp_all_import_plugin'), (int) $import->queue_chunk_number));
                                }
                            } else {
                                $logger and call_user_func($logger, sprintf(__('Import #%s already processing. Request skipped.', 'wp_all_import_plugin'), $id));
                            }
                            break;
                        case 'pipe':
                            $import->execute($logger);
                            break;
                    }
                }
            }
        }
    }
}
Exemplo n.º 14
0
 /**
  * Re-run import
  */
 public function update()
 {
     $id = $this->input->get('id');
     PMXI_Plugin::$session->clean_session($id);
     $action_type = false;
     $this->data['import'] = $item = new PMXI_Import_Record();
     if (!$id or $item->getById($id)->isEmpty()) {
         wp_redirect($this->baseUrl);
         die;
     }
     $this->data['isWizard'] = false;
     $default = PMXI_Plugin::get_default_import_options();
     $DefaultOptions = $item->options + $default;
     foreach (PMXI_Admin_Addons::get_active_addons() as $class) {
         if (class_exists($class)) {
             $DefaultOptions += call_user_func(array($class, "get_default_import_options"));
         }
     }
     $this->data['post'] =& $DefaultOptions;
     $this->data['source'] = array('path' => $item->path, 'root_element' => $item->root_element);
     $this->data['xpath'] = $item->xpath;
     $this->data['count'] = $item->count;
     $history = new PMXI_File_List();
     $history->setColumns('id', 'name', 'registered_on', 'path')->getBy(array('import_id' => $item->id), 'id DESC');
     if ($history->count()) {
         foreach ($history as $file) {
             if (@file_exists($file['path'])) {
                 $this->data['locfilePath'] = $file['path'];
                 break;
             }
         }
     }
     $chunks = 0;
     if ($this->input->post('is_confirmed') and check_admin_referer('confirm', '_wpnonce_confirm')) {
         $continue = $this->input->post('is_continue', 'no');
         // mark action type ad continue
         if ($continue == 'yes') {
             $action_type = 'continue';
         }
         $filePath = '';
         // upload new file in case when import is not continue
         if (empty(PMXI_Plugin::$session->chunk_number)) {
             if ($item->type == 'upload') {
                 // retrieve already uploaded file
                 $uploader = new PMXI_Upload(trim($item->path), $this->errors, rtrim(str_replace(basename($item->path), '', $item->path), '/'));
                 $upload_result = $uploader->upload();
                 if ($upload_result instanceof WP_Error) {
                     $this->errors = $upload_result;
                 } else {
                     $filePath = $upload_result['filePath'];
                 }
             }
             if (empty($item->options['encoding'])) {
                 $currentOptions = $item->options;
                 $currentOptions['encoding'] = 'UTF-8';
                 $item->set(array('options' => $currentOptions))->update();
             }
             @set_time_limit(0);
             $local_paths = !empty($local_paths) ? $local_paths : array($filePath);
             foreach ($local_paths as $key => $path) {
                 if (!empty($action_type) and $action_type == 'continue') {
                     $chunks = $item->count;
                 } else {
                     $file = new PMXI_Chunk($path, array('element' => $item->root_element, 'encoding' => $item->options['encoding']));
                     while ($xml = $file->read()) {
                         if (!empty($xml)) {
                             PMXI_Import_Record::preprocessXml($xml);
                             $xml = "<?xml version=\"1.0\" encoding=\"" . $item->options['encoding'] . "\"?>" . "\n" . $xml;
                             $dom = new DOMDocument('1.0', !empty($item->options['encoding']) ? $item->options['encoding'] : 'UTF-8');
                             $old = libxml_use_internal_errors(true);
                             $dom->loadXML($xml);
                             // FIX: libxml xpath doesn't handle default namespace properly, so remove it upon XML load
                             libxml_use_internal_errors($old);
                             $xpath = new DOMXPath($dom);
                             if ($elements = @$xpath->query($item->xpath) and !empty($elements) and !empty($elements->length)) {
                                 $chunks += $elements->length;
                             }
                             unset($dom, $xpath, $elements);
                         }
                     }
                     unset($file);
                 }
                 !$key and $filePath = $path;
             }
             if (empty($chunks)) {
                 $this->errors->add('form-validation', __('No matching elements found for Root element and XPath expression specified', 'wp_all_import_plugin'));
             }
         }
         if ($chunks) {
             // xml is valid
             if (!PMXI_Plugin::is_ajax() and empty(PMXI_Plugin::$session->chunk_number)) {
                 // compose data to look like result of wizard steps
                 $sesson_data = array('filePath' => $filePath, 'source' => array('name' => $item->name, 'type' => $item->type, 'path' => $item->path, 'root_element' => $item->root_element), 'feed_type' => $item->feed_type, 'update_previous' => $item->id, 'parent_import_id' => $item->parent_import_id, 'xpath' => $item->xpath, 'options' => $item->options, 'encoding' => !empty($item->options['encoding']) ? $item->options['encoding'] : 'UTF-8', 'is_csv' => !empty($item->options['delimiter']) ? $item->options['delimiter'] : PMXI_Plugin::$is_csv, 'csv_path' => PMXI_Plugin::$csv_path, 'chunk_number' => 1, 'log' => '', 'warnings' => 0, 'errors' => 0, 'start_time' => 0, 'pointer' => 1, 'count' => isset($chunks) ? $chunks : 0, 'local_paths' => !empty($local_paths) ? $local_paths : array(), 'action' => (!empty($action_type) and $action_type == 'continue') ? 'continue' : 'update', 'nonce' => wp_create_nonce('import'));
                 foreach ($sesson_data as $key => $value) {
                     PMXI_Plugin::$session->set($key, $value);
                 }
                 PMXI_Plugin::$session->save_data();
             }
             $item->set(array('canceled' => 0, 'failed' => 0))->update();
             // deligate operation to other controller
             $controller = new PMXI_Admin_Import();
             $controller->data['update_previous'] = $item;
             $controller->process();
             return;
         }
     }
     $this->render('admin/import/confirm');
 }
Exemplo n.º 15
0
 /**
  * Clear associations with posts via Ajax
  * @param bool[optional] $keepPosts When set to false associated wordpress posts will be deleted as well
  * @return PMXI_Import_Record
  * @chainable
  */
 public function deletePostsAjax($keepPosts = TRUE, $is_deleted_images = 'auto', $is_delete_attachments = 'auto')
 {
     $postList = new PMXI_Post_List();
     if (!$keepPosts) {
         $missing_ids = array();
         $missingPosts = $postList->getBy(array('import_id' => $this->id));
         if (!$missingPosts->isEmpty()) {
             foreach ($missingPosts as $missingPost) {
                 $missing_ids[] = $missingPost['post_id'];
             }
         }
         // Delete posts from database
         if (!empty($missing_ids) && is_array($missing_ids)) {
             $missing_ids_arr = array_chunk($missing_ids, $this->options['records_per_request']);
             foreach ($missing_ids_arr as $key => $ids) {
                 if (!empty($ids)) {
                     $this->deleteRecords($is_delete_attachments, $is_deleted_images, $ids);
                     // Delete record form pmxi_posts
                     $sql = "DELETE FROM " . PMXI_Plugin::getInstance()->getTablePrefix() . "posts WHERE post_id IN (" . implode(',', $ids) . ") AND import_id = %d";
                     $this->wpdb->query($this->wpdb->prepare($sql, $this->id));
                     $this->set(array('deleted' => $this->deleted + count($ids)))->update();
                 }
                 break;
             }
             return count($missing_ids_arr) > 1 ? false : true;
         }
     }
     return true;
 }
Exemplo n.º 16
0
 /**
  * __construct
  * 
  * Builds the Chunk object
  *
  * @param string $file The filename to work with
  * @param array $options The options with which to parse the file
  * @author Dom Hastings
  * @access public
  */
 public function __construct($file, $options = array(), $debug = false)
 {
     // merge the options together
     $this->options = array_merge($this->options, is_array($options) ? $options : array());
     $this->options['chunkSize'] *= PMXI_Plugin::getInstance()->getOption('chunk_size');
     // set the filename
     $this->file = $file;
     $is_html = false;
     $f = @fopen($file, "rb");
     while (!@feof($f)) {
         $chunk = @fread($f, 1024);
         if (strpos($chunk, "<!DOCTYPE") === 0) {
             $is_html = true;
         }
         break;
     }
     @fclose($f);
     if ($is_html) {
         $path = $this->get_file_path();
         $this->is_404 = true;
         $this->reader = new XMLReader();
         @$this->reader->open($path);
         @$this->reader->setParserProperty(XMLReader::VALIDATE, false);
         return;
     }
     if (empty($this->options['element']) or $this->options['get_cloud']) {
         $path = $this->get_file_path();
         $reader = new XMLReader();
         $reader->open($path);
         $reader->setParserProperty(XMLReader::VALIDATE, false);
         while (@$reader->read()) {
             switch ($reader->nodeType) {
                 case XMLREADER::ELEMENT:
                     $localName = str_replace("_colon_", ":", $reader->localName);
                     if (array_key_exists(str_replace(":", "_", $localName), $this->cloud)) {
                         $this->cloud[str_replace(":", "_", $localName)]++;
                     } else {
                         $this->cloud[str_replace(":", "_", $localName)] = 1;
                     }
                     break;
                 default:
                     break;
             }
         }
         unset($reader);
         if (!empty($this->cloud) and empty($this->options['element'])) {
             arsort($this->cloud);
             $main_elements = array('node', 'product', 'job', 'deal', 'entry', 'item', 'property', 'listing', 'hotel', 'record', 'article', 'post', 'book', 'item_0');
             foreach ($this->cloud as $element_name => $value) {
                 if (in_array(strtolower($element_name), $main_elements)) {
                     $this->options['element'] = $element_name;
                     break;
                 }
             }
             if (empty($this->options['element'])) {
                 foreach ($this->cloud as $el => $count) {
                     $this->options['element'] = $el;
                     break;
                 }
             }
         }
     }
     $path = $this->get_file_path();
     $this->reader = new XMLReader();
     @$this->reader->open($path);
     @$this->reader->setParserProperty(XMLReader::VALIDATE, false);
 }
Exemplo n.º 17
0
 /**
  * pre-dispatching logic for admin page controllers
  */
 public function __adminInit()
 {
     // create history folder
     $uploads = wp_upload_dir();
     $wpallimportDirs = array(WP_ALL_IMPORT_UPLOADS_BASE_DIRECTORY, self::LOGS_DIRECTORY, self::FILES_DIRECTORY, self::TEMP_DIRECTORY, self::UPLOADS_DIRECTORY, self::HISTORY_DIRECTORY);
     foreach ($wpallimportDirs as $destination) {
         $dir = $uploads['basedir'] . DIRECTORY_SEPARATOR . $destination;
         if (!is_dir($dir)) {
             wp_mkdir_p($dir);
         }
         if (!@file_exists($dir . DIRECTORY_SEPARATOR . 'index.php')) {
             @touch($dir . DIRECTORY_SEPARATOR . 'index.php');
         }
     }
     self::$session = new PMXI_Handler();
     $input = new PMXI_Input();
     $page = strtolower($input->getpost('page', ''));
     if (preg_match('%^' . preg_quote(str_replace('_', '-', self::PREFIX), '%') . '([\\w-]+)$%', $page)) {
         //$this->adminDispatcher($page, strtolower($input->getpost('action', 'index')));
         $action = strtolower($input->getpost('action', 'index'));
         // capitalize prefix and first letters of class name parts
         if (function_exists('preg_replace_callback')) {
             $controllerName = preg_replace_callback('%(^' . preg_quote(self::PREFIX, '%') . '|_).%', array($this, "replace_callback"), str_replace('-', '_', $page));
         } else {
             $controllerName = preg_replace('%(^' . preg_quote(self::PREFIX, '%') . '|_).%e', 'strtoupper("$0")', str_replace('-', '_', $page));
         }
         $actionName = str_replace('-', '_', $action);
         if (method_exists($controllerName, $actionName)) {
             @ini_set("max_input_time", PMXI_Plugin::getInstance()->getOption('max_input_time'));
             @ini_set("max_execution_time", PMXI_Plugin::getInstance()->getOption('max_execution_time'));
             if (!get_current_user_id() or !current_user_can('manage_options')) {
                 // This nonce is not valid.
                 die('Security check');
             } else {
                 $this->_admin_current_screen = (object) array('id' => $controllerName, 'base' => $controllerName, 'action' => $actionName, 'is_ajax' => strpos($_SERVER["HTTP_ACCEPT"], 'json') !== false, 'is_network' => is_network_admin(), 'is_user' => is_user_admin());
                 add_filter('current_screen', array($this, 'getAdminCurrentScreen'));
                 add_filter('admin_body_class', create_function('', 'return "' . 'wpallimport-plugin";'));
                 $controller = new $controllerName();
                 if (!$controller instanceof PMXI_Controller_Admin) {
                     throw new Exception("Administration page `{$page}` matches to a wrong controller type.");
                 }
                 if ($this->_admin_current_screen->is_ajax) {
                     // ajax request
                     $controller->{$action}();
                     do_action('pmxi_action_after');
                     die;
                     // stop processing since we want to output only what controller is randered, nothing in addition
                 } elseif (!$controller->isInline) {
                     @ob_start();
                     $controller->{$action}();
                     self::$buffer = @ob_get_clean();
                 } else {
                     self::$buffer_callback = array($controller, $action);
                 }
             }
         } else {
             // redirect to dashboard if requested page and/or action don't exist
             wp_redirect(admin_url());
             die;
         }
     }
 }
Exemplo n.º 18
0
    /**
     * Import processing step (status console)
     */
    public function process($save_history = true)
    {
        $wp_uploads = wp_upload_dir();
        $import = $this->data['update_previous'];
        $logger = create_function('$m', 'echo "<div class=\\"progress-msg\\">$m</div>\\n"; if ( "" != strip_tags(pmxi_strip_tags_content($m)) and !empty(PMXI_Plugin::$session[\'pmxi_import\'][\'log\'])) { PMXI_Plugin::$session[\'pmxi_import\'][\'log\'] .= "<p>".strip_tags(pmxi_strip_tags_content($m))."</p>"; flush(); }');
        if (!PMXI_Plugin::is_ajax()) {
            $import->set((empty(PMXI_Plugin::$session->data['pmxi_import']['source']) ? array() : PMXI_Plugin::$session->data['pmxi_import']['source']) + array('xpath' => PMXI_Plugin::$session->data['pmxi_import']['xpath'], 'template' => PMXI_Plugin::$session->data['pmxi_import']['template'], 'options' => PMXI_Plugin::$session->data['pmxi_import']['options'], 'count' => PMXI_Plugin::$session->data['pmxi_import']['count'], 'friendly_name' => PMXI_Plugin::$session->data['pmxi_import']['options']['friendly_name'], 'feed_type' => PMXI_Plugin::$session->data['pmxi_import']['feed_type'], 'parent_import_id' => $this->data['update_previous']->isEmpty() ? PMXI_Plugin::$session->data['pmxi_import']['parent_import_id'] : $this->data['update_previous']->parent_import_id, 'queue_chunk_number' => 0, 'triggered' => 0, 'processing' => 0, 'iteration' => !empty($import->iteration) ? $import->iteration : 0))->save();
            if (PMXI_Plugin::$session->data['pmxi_import']['action'] != 'continue') {
                // store import info in database
                $import->set(array('imported' => 0, 'created' => 0, 'updated' => 0, 'skipped' => 0))->update();
            }
            foreach (get_taxonomies() as $tax) {
                delete_transient("pmxi_{$tax}_terms");
            }
            do_action('pmxi_before_xml_import', $import->id);
            PMXI_Plugin::$session['pmxi_import']['update_previous'] = $import->id;
            // unlick previous files
            $history = new PMXI_File_List();
            $history->setColumns('id', 'name', 'registered_on', 'path')->getBy(array('import_id' => $import->id), 'id DESC');
            if ($history->count()) {
                foreach ($history as $file) {
                    if (@file_exists($file['path']) and $file['path'] != PMXI_Plugin::$session->data['pmxi_import']['filePath']) {
                        @unlink($file['path']);
                    }
                    $history_file = new PMXI_File_Record();
                    $history_file->getBy('id', $file['id']);
                    if (!$history_file->isEmpty()) {
                        $history_file->delete();
                    }
                }
            }
            if ($save_history) {
                $history_file = new PMXI_File_Record();
                $history_file->set(array('name' => $import->name, 'import_id' => $import->id, 'path' => PMXI_Plugin::$session->data['pmxi_import']['filePath'], 'contents' => $this->get_xml(), 'registered_on' => date('Y-m-d H:i:s')))->save();
            }
            /*
            	Split file up into 1000 record chunks.			
            	This option will decrease the amount of slowdown experienced at the end of large imports. 
            	The slowdown is partially caused by the need for WP All Import to read deeper and deeper into the file on each successive iteration. 
            	Splitting the file into pieces means that, for example, instead of having to read 19000 records into a 20000 record file when importing the last 1000 records, 
            	WP All Import will just split it into 20 chunks, and then read the last chunk from the beginning.
            */
            if ("ajax" == $import->options['import_processing'] and $import->count > PMXI_Plugin::getInstance()->getOption('large_feed_limit') and $import->options['chuncking']) {
                $chunk_files = array();
                if (!empty(PMXI_Plugin::$session->data['pmxi_import']['local_paths'])) {
                    $records_count = 0;
                    $chunk_records_count = 0;
                    $feed = "<?xml version=\"1.0\" encoding=\"" . $import->options['encoding'] . "\"?>" . "\n" . "<pmxi_records>";
                    foreach (PMXI_Plugin::$session->data['pmxi_import']['local_paths'] as $key => $path) {
                        $file = new PMXI_Chunk($path, array('element' => $import->root_element, 'encoding' => $import->options['encoding']));
                        // loop through the file until all lines are read
                        while ($xml = $file->read()) {
                            if (!empty($xml)) {
                                PMXI_Import_Record::preprocessXml($xml);
                                $chunk = "<?xml version=\"1.0\" encoding=\"" . $import->options['encoding'] . "\"?>" . "\n" . $xml;
                                $dom = new DOMDocument('1.0', $import->options['encoding']);
                                $old = libxml_use_internal_errors(true);
                                $dom->loadXML($chunk);
                                // FIX: libxml xpath doesn't handle default namespace properly, so remove it upon XML load
                                libxml_use_internal_errors($old);
                                $xpath = new DOMXPath($dom);
                                if ($elements = @$xpath->query($import->xpath) and $elements->length) {
                                    $records_count += $elements->length;
                                    $chunk_records_count += $elements->length;
                                    $feed .= $xml;
                                }
                            }
                            if ($chunk_records_count == PMXI_Plugin::getInstance()->getOption('large_feed_limit') or $records_count == $import->count) {
                                $feed .= "</pmxi_records>";
                                $chunk_file_path = $wp_uploads['path'] . "/pmxi_chunk_" . count($chunk_files) . "_" . basename($path);
                                file_put_contents($chunk_file_path, $feed);
                                $chunk_files[] = $chunk_file_path;
                                $chunk_records_count = 0;
                                $feed = "<?xml version=\"1.0\" encoding=\"" . $import->options['encoding'] . "\"?>" . "\n" . "<pmxi_records>";
                            }
                        }
                    }
                    PMXI_Plugin::$session['pmxi_import']['local_paths'] = $chunk_files;
                }
            }
            pmxi_session_commit();
            $this->render();
            wp_ob_end_flush_all();
            flush();
            @set_time_limit(0);
            if ("ajax" == $import->options['import_processing']) {
                die;
            }
        } elseif (empty($import->id)) {
            $import = new PMXI_Import_Record();
            $import->getById(PMXI_Plugin::$session->data['pmxi_import']['update_previous']);
        }
        $ajax_processing = "ajax" == $import->options['import_processing'] ? true : false;
        PMXI_Plugin::$session['pmxi_import']['start_time'] = empty(PMXI_Plugin::$session->data['pmxi_import']['start_time']) ? time() : PMXI_Plugin::$session->data['pmxi_import']['start_time'];
        wp_cache_flush();
        if (PMXI_Plugin::is_ajax() or !$ajax_processing) {
            if ("ajax" == $import->options['import_processing']) {
                // 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");
            }
            $loop = 0;
            $pointer = 0;
            $records = array();
            if ($import->options['is_import_specified']) {
                foreach (preg_split('% *, *%', $import->options['import_specified'], -1, PREG_SPLIT_NO_EMPTY) as $chank) {
                    if (preg_match('%^(\\d+)-(\\d+)$%', $chank, $mtch)) {
                        $records = array_merge($records, range(intval($mtch[1]), intval($mtch[2])));
                    } else {
                        $records = array_merge($records, array(intval($chank)));
                    }
                }
            }
            $records_to_import = empty($records) ? $import->count : $records[count($records) - 1];
            $records_per_request = (!$ajax_processing and $import->options['records_per_request'] < 50) ? 50 : $import->options['records_per_request'];
            if (!empty(PMXI_Plugin::$session->data['pmxi_import']['local_paths'])) {
                $feed = "<?xml version=\"1.0\" encoding=\"" . $import->options['encoding'] . "\"?>" . "\n" . "<pmxi_records>";
                foreach (PMXI_Plugin::$session->data['pmxi_import']['local_paths'] as $key => $path) {
                    $import_done = $import->imported + $import->skipped + PMXI_Plugin::$session->data['pmxi_import']['errors'] == $records_to_import ? true : false;
                    if ($import_done) {
                        if (strpos($path, "pmxi_chunk_") !== false and @file_exists($path)) {
                            @unlink($path);
                        }
                        PMXI_Plugin::$session['pmxi_import']['local_paths'] = array();
                        pmxi_session_commit();
                        break;
                    }
                    $file = new PMXI_Chunk($path, array('element' => $import->root_element, 'encoding' => $import->options['encoding'], 'pointer' => PMXI_Plugin::$session->data['pmxi_import']['pointer']));
                    // loop through the file until all lines are read
                    while ($xml = $file->read()) {
                        if (!empty($xml)) {
                            PMXI_Import_Record::preprocessXml($xml);
                            $chunk = "<?xml version=\"1.0\" encoding=\"" . $import->options['encoding'] . "\"?>" . "\n" . $xml;
                            $dom = new DOMDocument('1.0', $import->options['encoding']);
                            $old = libxml_use_internal_errors(true);
                            $dom->loadXML($chunk);
                            // FIX: libxml xpath doesn't handle default namespace properly, so remove it upon XML load
                            libxml_use_internal_errors($old);
                            $xpath = new DOMXPath($dom);
                            $pointer++;
                            if ($this->data['elements'] = $elements = @$xpath->query($import->xpath) and $elements->length) {
                                // continue action
                                if ($import->imported + $import->skipped >= PMXI_Plugin::$session->data['pmxi_import']['chunk_number'] + $elements->length - 1) {
                                    PMXI_Plugin::$session['pmxi_import']['chunk_number'] = PMXI_Plugin::$session->data['pmxi_import']['chunk_number'] + $elements->length;
                                    pmxi_session_commit();
                                    continue;
                                }
                                if (!$loop and $ajax_processing) {
                                    ob_start();
                                }
                                $feed .= $xml;
                                $loop += $elements->length;
                                $processed_records = $import->imported + $import->skipped + PMXI_Plugin::$session->data['pmxi_import']['errors'];
                                if ($loop == $records_per_request or $processed_records + $loop == $records_to_import or $processed_records == $records_to_import) {
                                    $feed .= "</pmxi_records>";
                                    $import->process($feed, $logger, PMXI_Plugin::$session->data['pmxi_import']['chunk_number'], false, '/pmxi_records');
                                    unset($dom, $xpath);
                                    if (!$ajax_processing) {
                                        $feed = "<?xml version=\"1.0\" encoding=\"" . $import->options['encoding'] . "\"?>" . "\n" . "<pmxi_records>";
                                        $loop = 0;
                                    } else {
                                        unset($file);
                                        PMXI_Plugin::$session['pmxi_import']['pointer'] = PMXI_Plugin::$session->data['pmxi_import']['pointer'] + $pointer;
                                        pmxi_session_commit();
                                        wp_send_json(array('created' => $import->created, 'updated' => $import->updated, 'percentage' => ceil($processed_records / $import->count * 100), 'warnings' => PMXI_Plugin::$session->data['pmxi_import']['warnings'], 'errors' => PMXI_Plugin::$session->data['pmxi_import']['errors'], 'log' => ob_get_clean(), 'done' => false));
                                    }
                                }
                            }
                        }
                    }
                    // Move to the next file, set pointer to first element
                    if ($ajax_processing) {
                        if (strpos($path, "pmxi_chunk_") !== false and @file_exists($path)) {
                            @unlink($path);
                        }
                        PMXI_Plugin::$session['pmxi_import']['pointer'] = 1;
                        $pointer = 0;
                        array_shift(PMXI_Plugin::$session->data['pmxi_import']['local_paths']);
                        PMXI_Plugin::$session['pmxi_import']['local_paths'] = PMXI_Plugin::$session->data['pmxi_import']['local_paths'];
                        pmxi_session_commit();
                    } else {
                        break;
                    }
                }
            }
        }
        if (PMXI_Plugin::is_ajax() and empty(PMXI_Plugin::$session->data['pmxi_import']['local_paths']) or !$ajax_processing) {
            // Save import process log
            $log_file = $wp_uploads['basedir'] . '/wpallimport_logs/' . $import->id . '.html';
            if (file_exists($log_file)) {
                unlink($log_file);
            }
            @file_put_contents($log_file, PMXI_Plugin::$session->data['pmxi_import']['log']);
            if (!empty(PMXI_Plugin::$session->data['pmxi_import'])) {
                do_action('pmxi_after_xml_import', $import->id);
            }
            wp_cache_flush();
            foreach (get_taxonomies() as $tax) {
                delete_option("{$tax}_children");
                _get_term_hierarchy($tax);
            }
            $import->set('registered_on', date('Y-m-d H:i:s'))->update();
            // clear import session
            pmxi_session_unset();
            // clear session data (prevent from reimporting the same data on page refresh)
            // [indicate in header process is complete]
            $msg = addcslashes(__('Complete', 'pmxi_plugin'), "\n\r");
            if ($ajax_processing) {
                ob_start();
            }
            $import->options['is_import_specified'] and $logger and call_user_func($logger, 'Done');
            echo <<<COMPLETE
<script type="text/javascript">
//<![CDATA[
(function(\$){\t
\t\$('#status').html('{$msg}');
\t\$('#import_finished').show();
\twindow.onbeforeunload = false;
})(jQuery);
//]]>
</script>
COMPLETE;
            // [/indicate in header process is complete]
            if ($ajax_processing) {
                wp_send_json(array('created' => $import->created, 'updated' => $import->updated, 'percentage' => 100, 'warnings' => PMXI_Plugin::$session->data['pmxi_import']['warnings'], 'errors' => PMXI_Plugin::$session->data['pmxi_import']['errors'], 'log' => ob_get_clean(), 'done' => true));
            }
        }
    }
Exemplo n.º 19
0
</option>
				<?php 
}
?>
			</select>
			<input type="submit" value="<?php 
esc_attr_e('Apply', 'wp_all_import_plugin');
?>
" name="doaction2" id="doaction2" class="button-secondary action" />
		</div>
	</div>
	<div class="clear"></div>

	<?php 
// notify user
if (!PMXI_Plugin::getInstance()->getOption('dismiss_manage_bottom')) {
    ?>
		<div class="updated_bottom"><p>
			<?php 
    printf(__('<a href="https://wordpress.org/support/view/plugin-reviews/wp-all-import#postform" target="_blank">If our plugin helped you, please rate us on WordPress.org. It would really help us!</a> <a href="https://wordpress.org/support/view/plugin-reviews/wp-all-import#postform" class="pmxi_stars" target="_blank"></a> <br/><br/><a href="javascript:void(0);" id="dismiss_manage_bottom">dismiss</a>', 'wp_all_import_plugin'));
    ?>
		</p></div>
		<?php 
}
?>

	<p style='font-size: 1.3em; font-weight: bold;'><a href="http://www.wpallimport.com/upgrade-to-pro/?utm_source=free-plugin&utm_medium=in-plugin&utm_campaign=manage" target="_blank" class="upgrade_link"><?php 
_e('Find out more about the professional edition of WP All Import.', 'wp_all_import_plugin');
?>
</a></p>	
	
Exemplo n.º 20
0
    /**
     * Import processing step (status console)
     */
    public function process($save_history = true)
    {
        $wp_uploads = wp_upload_dir();
        $import = $this->data['update_previous'];
        $history_log = new PMXI_History_Record();
        $input = new PMXI_Input();
        if (!empty(PMXI_Plugin::$session->history_id)) {
            $history_log->getById(PMXI_Plugin::$session->history_id);
        }
        $log_storage = (int) PMXI_Plugin::getInstance()->getOption('log_storage');
        if (!PMXI_Plugin::is_ajax()) {
            $import->set((empty(PMXI_Plugin::$session->source) ? array() : PMXI_Plugin::$session->source) + array('xpath' => PMXI_Plugin::$session->xpath, 'options' => PMXI_Plugin::$session->options, 'count' => PMXI_Plugin::$session->count, 'friendly_name' => PMXI_Plugin::$session->options['friendly_name'], 'feed_type' => PMXI_Plugin::$session->feed_type, 'parent_import_id' => $this->data['update_previous']->isEmpty() ? PMXI_Plugin::$session->parent_import_id : $this->data['update_previous']->parent_import_id, 'queue_chunk_number' => 0, 'triggered' => 0, 'processing' => 0, 'executing' => 1, 'iteration' => !empty($import->iteration) ? $import->iteration : 0))->save();
            if (PMXI_Plugin::$session->action != 'continue') {
                // store import info in database
                $import->set(array('imported' => 0, 'created' => 0, 'updated' => 0, 'skipped' => 0, 'deleted' => 0))->update();
            }
            // add history log
            $custom_type = get_post_type_object($import->options['custom_type']);
            // unlink previous logs
            $by = array();
            $by[] = array(array('import_id' => $import->id, 'type NOT LIKE' => 'trigger'), 'AND');
            $historyLogs = new PMXI_History_List();
            $historyLogs->setColumns('id', 'import_id', 'type', 'date')->getBy($by, 'id ASC');
            if ($historyLogs->count() and $historyLogs->count() >= $log_storage) {
                $logsToRemove = $historyLogs->count() - $log_storage;
                foreach ($historyLogs as $i => $file) {
                    $historyRecord = new PMXI_History_Record();
                    $historyRecord->getBy('id', $file['id']);
                    if (!$historyRecord->isEmpty()) {
                        $historyRecord->delete();
                    }
                    // unlink history file only
                    if ($i == $logsToRemove) {
                        break;
                    }
                }
            }
            $history_log->set(array('import_id' => $import->id, 'date' => date('Y-m-d H:i:s'), 'type' => PMXI_Plugin::$session->action != 'continue' ? 'manual' : 'continue', 'summary' => sprintf(__("%d %ss created %d updated %d deleted %d skipped", "pmxi_plugin"), $import->created, $custom_type->labels->singular_name, $import->updated, $import->deleted, $import->skipped)))->save();
            PMXI_Plugin::$session->set('history_id', $history_log->id);
            foreach (get_taxonomies() as $tax) {
                delete_transient("pmxi_{$tax}_terms");
            }
            do_action('pmxi_before_xml_import', $import->id);
            PMXI_Plugin::$session->set('update_previous', $import->id);
            if (empty($import->options['encoding'])) {
                $currentOptions = $import->options;
                $currentOptions['encoding'] = 'UTF-8';
                $import->set(array('options' => $currentOptions))->update();
            }
            // unlink previous files
            $history = new PMXI_File_List();
            $history->setColumns('id', 'name', 'registered_on', 'path')->getBy(array('import_id' => $import->id), 'id DESC');
            if ($history->count()) {
                foreach ($history as $file) {
                    $history_file_path = wp_all_import_get_absolute_path($file['path']);
                    if (@file_exists($history_file_path) and $history_file_path != PMXI_Plugin::$session->filePath) {
                        if (in_array($import->type, array('upload'))) {
                            wp_all_import_remove_source($history_file_path, false);
                        } else {
                            wp_all_import_remove_source($history_file_path);
                        }
                    }
                    $history_file = new PMXI_File_Record();
                    $history_file->getBy('id', $file['id']);
                    if (!$history_file->isEmpty()) {
                        $history_file->delete();
                    }
                }
            }
            if ($save_history) {
                $history_file = new PMXI_File_Record();
                $history_file->set(array('name' => $import->name, 'import_id' => $import->id, 'path' => wp_all_import_get_relative_path(PMXI_Plugin::$session->filePath), 'registered_on' => date('Y-m-d H:i:s')))->save();
            }
            /*
            	Split file up into 1000 record chunks.			
            	This option will decrease the amount of slowdown experienced at the end of large imports. 
            	The slowdown is partially caused by the need for WP All Import to read deeper and deeper into the file on each successive iteration. 
            	Splitting the file into pieces means that, for example, instead of having to read 19000 records into a 20000 record file when importing the last 1000 records, 
            	WP All Import will just split it into 20 chunks, and then read the last chunk from the beginning.
            */
            if ("ajax" == $import->options['import_processing'] and $import->count > PMXI_Plugin::getInstance()->getOption('large_feed_limit') and $import->options['chuncking']) {
                $chunk_files = array();
                if (!empty(PMXI_Plugin::$session->local_paths)) {
                    $records_count = 0;
                    $chunk_records_count = 0;
                    $feed = "<?xml version=\"1.0\" encoding=\"" . $import->options['encoding'] . "\"?>" . "\n" . "<pmxi_records>";
                    foreach (PMXI_Plugin::$session->local_paths as $key => $path) {
                        $file = new PMXI_Chunk($path, array('element' => $import->root_element, 'encoding' => $import->options['encoding']));
                        // loop through the file until all lines are read
                        while ($xml = $file->read()) {
                            if (!empty($xml)) {
                                PMXI_Import_Record::preprocessXml($xml);
                                $chunk = "<?xml version=\"1.0\" encoding=\"" . $import->options['encoding'] . "\"?>" . "\n" . $xml;
                                $dom = new DOMDocument('1.0', $import->options['encoding']);
                                $old = libxml_use_internal_errors(true);
                                $dom->loadXML($chunk);
                                // FIX: libxml xpath doesn't handle default namespace properly, so remove it upon XML load
                                libxml_use_internal_errors($old);
                                $xpath = new DOMXPath($dom);
                                if ($elements = @$xpath->query($import->xpath) and $elements->length) {
                                    $records_count += $elements->length;
                                    $chunk_records_count += $elements->length;
                                    $feed .= $xml;
                                }
                            }
                            if ($chunk_records_count == PMXI_Plugin::getInstance()->getOption('large_feed_limit') or $records_count == $import->count) {
                                $feed .= "</pmxi_records>";
                                $chunk_file_path = wp_all_import_secure_file($wp_uploads['basedir'] . DIRECTORY_SEPARATOR . PMXI_Plugin::TEMP_DIRECTORY) . DIRECTORY_SEPARATOR . "pmxi_chunk_" . count($chunk_files) . "_" . basename($path);
                                file_put_contents($chunk_file_path, $feed);
                                $chunk_files[] = $chunk_file_path;
                                $chunk_records_count = 0;
                                $feed = "<?xml version=\"1.0\" encoding=\"" . $import->options['encoding'] . "\"?>" . "\n" . "<pmxi_records>";
                            }
                        }
                    }
                    PMXI_Plugin::$session->set('local_paths', $chunk_files);
                }
            }
            PMXI_Plugin::$session->save_data();
            if ($log_storage) {
                $log_file = wp_all_import_secure_file($wp_uploads['basedir'] . DIRECTORY_SEPARATOR . PMXI_Plugin::LOGS_DIRECTORY, $history_log->id) . DIRECTORY_SEPARATOR . $history_log->id . '.html';
                if (PMXI_Plugin::$session->action != 'continue') {
                    if (file_exists($log_file)) {
                        wp_all_import_remove_source($log_file, false);
                    }
                    //@file_put_contents($log_file, sprintf(__('<p>Source path `%s`</p>', 'wp_all_import_plugin'), $import->path));
                }
            }
            $this->data['ajax_processing'] = "ajax" == $import->options['import_processing'] ? true : false;
            $this->render();
            wp_ob_end_flush_all();
            flush();
            @set_time_limit(0);
            $import_id = $input->get('id', 0);
            if ("ajax" == $import->options['import_processing'] and !$import_id) {
                PMXI_Plugin::$session->convertData($import->id);
                //die();
            }
        } elseif (empty($import->id)) {
            $import = new PMXI_Import_Record();
            $import_id = $input->get('id', PMXI_Plugin::$session->update_previous);
            $import->getById($import_id);
        }
        $ajax_processing = "ajax" == $import->options['import_processing'] ? true : false;
        if (PMXI_Plugin::is_ajax() and $ajax_processing and !check_ajax_referer('wp_all_import_secure', 'security', false)) {
            exit(__('Security check', 'wp_all_import_plugin'));
        }
        if ($ajax_processing) {
            $logger = create_function('$m', 'echo "<div class=\\"progress-msg\\">$m</div>\\n"; flush();');
        } else {
            $logger = create_function('$m', 'echo "<div class=\\"progress-msg\\">$m</div>\\n"; if ( "" != strip_tags(wp_all_import_strip_tags_content($m))) { PMXI_Plugin::$session->log .= "<p>".strip_tags(wp_all_import_strip_tags_content($m))."</p>"; flush(); }');
        }
        PMXI_Plugin::$session->set('start_time', empty(PMXI_Plugin::$session->start_time) ? time() : PMXI_Plugin::$session->start_time);
        wp_cache_flush();
        if (PMXI_Plugin::is_ajax() or !$ajax_processing) {
            $iteration_start_time = time();
            if ($log_storage) {
                $log_file = wp_all_import_secure_file($wp_uploads['basedir'] . DIRECTORY_SEPARATOR . PMXI_Plugin::LOGS_DIRECTORY, $history_log->id) . DIRECTORY_SEPARATOR . $history_log->id . '.html';
            }
            if ($ajax_processing) {
                // 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");
            }
            $loop = 0;
            $pointer = 0;
            $records = array();
            if ($import->options['is_import_specified']) {
                foreach (preg_split('% *, *%', $import->options['import_specified'], -1, PREG_SPLIT_NO_EMPTY) as $chank) {
                    if (preg_match('%^(\\d+)-(\\d+)$%', $chank, $mtch)) {
                        $records = array_merge($records, range(intval($mtch[1]), intval($mtch[2])));
                    } else {
                        $records = array_merge($records, array(intval($chank)));
                    }
                }
            }
            $records_to_import = empty($records) ? $import->count : $records[count($records) - 1];
            $failures = $input->get('failures', 0);
            // auto decrease records per iteration option
            if ($failures) {
                $options = $import->options;
                $options['records_per_request'] = ceil($options['records_per_request'] / 2) ? ceil($options['records_per_request'] / 2) : 1;
                $import->set(array('options' => $options))->update();
            }
            $records_per_request = (!$ajax_processing and $import->options['records_per_request'] < 50) ? 50 : $import->options['records_per_request'];
            if (!empty(PMXI_Plugin::$session->local_paths)) {
                $feed = "<?xml version=\"1.0\" encoding=\"" . $import->options['encoding'] . "\"?>" . "\n" . "<pmxi_records>";
                foreach (PMXI_Plugin::$session->local_paths as $key => $path) {
                    $import_done = $import->imported + $import->skipped == $records_to_import ? true : false;
                    if ($import_done) {
                        if (strpos($path, "pmxi_chunk_") !== false and @file_exists($path)) {
                            wp_all_import_remove_source($path, false);
                        }
                        PMXI_Plugin::$session->set('local_paths', array());
                        PMXI_Plugin::$session->save_data();
                        break;
                    }
                    $file = new PMXI_Chunk($path, array('element' => $import->root_element, 'encoding' => $import->options['encoding'], 'pointer' => PMXI_Plugin::$session->pointer, 'filter' => true));
                    // loop through the file until all lines are read
                    while ($xml = $file->read() and empty($import->canceled)) {
                        if (!empty($xml)) {
                            if (!$import->options['chuncking']) {
                                PMXI_Import_Record::preprocessXml($xml);
                            }
                            $chunk = "<?xml version=\"1.0\" encoding=\"" . $import->options['encoding'] . "\"?>" . "\n" . $xml;
                            $dom = new DOMDocument('1.0', $import->options['encoding']);
                            $old = libxml_use_internal_errors(true);
                            $dom->loadXML($chunk);
                            // FIX: libxml xpath doesn't handle default namespace properly, so remove it upon XML load
                            libxml_use_internal_errors($old);
                            $xpath = new DOMXPath($dom);
                            $pointer++;
                            if ($this->data['elements'] = $elements = @$xpath->query($import->xpath) and $elements->length) {
                                /* Merge nested XML/CSV files */
                                /*$nested_files = json_decode($import->options['nested_files'], true);
                                		if ( ! empty($nested_files) and is_array($nested_files)){										
                                			$merger = new PMXI_Nested($dom, $nested_files, $xml, $import->xpath, $elements);
                                			$merger->merge();
                                			$xml = $merger->get_xml();
                                			unset($merger);
                                		}	*/
                                // continue action
                                if ($import->imported + $import->skipped >= PMXI_Plugin::$session->chunk_number + $elements->length - 1) {
                                    PMXI_Plugin::$session->set('chunk_number', PMXI_Plugin::$session->chunk_number + $elements->length);
                                    PMXI_Plugin::$session->save_data();
                                    continue;
                                }
                                if (!$loop and $ajax_processing) {
                                    ob_start();
                                }
                                $feed .= $xml;
                                $loop += $elements->length;
                                $processed_records = $import->imported + $import->skipped;
                                if ($loop == $records_per_request or $processed_records + $loop == $records_to_import or $processed_records == $records_to_import) {
                                    $feed .= "</pmxi_records>";
                                    $import->process($feed, $logger, PMXI_Plugin::$session->chunk_number, false, '/pmxi_records', $loop);
                                    unset($dom, $xpath);
                                    if (!$ajax_processing) {
                                        $feed = "<?xml version=\"1.0\" encoding=\"" . $import->options['encoding'] . "\"?>" . "\n" . "<pmxi_records>";
                                        $loop = 0;
                                    } else {
                                        if (!$history_log->isEmpty()) {
                                            $custom_type = get_post_type_object($import->options['custom_type']);
                                            $history_log->set(array('time_run' => time() - strtotime($history_log->date), 'summary' => sprintf(__("%d %ss created %d updated %d deleted %d skipped", "pmxi_plugin"), $import->created, $custom_type->labels->singular_name, $import->updated, $import->deleted, $import->skipped)))->update();
                                        }
                                        unset($file);
                                        PMXI_Plugin::$session->set('pointer', PMXI_Plugin::$session->pointer + $pointer);
                                        PMXI_Plugin::$session->save_data();
                                        $log_data = ob_get_clean();
                                        if ($log_storage) {
                                            $log = @fopen($log_file, 'a+');
                                            @fwrite($log, $log_data);
                                            @fclose($log);
                                        }
                                        $iteration_execution_time = time() - $iteration_start_time;
                                        wp_send_json(array('imported' => $import->imported, 'created' => $import->created, 'updated' => $import->updated, 'percentage' => ceil($processed_records / $import->count * 100), 'warnings' => PMXI_Plugin::$session->warnings, 'errors' => PMXI_Plugin::$session->errors, 'log' => $log_data, 'done' => false, 'records_per_request' => $import->options['records_per_request']));
                                    }
                                }
                            }
                        }
                    }
                    // Move to the next file, set pointer to first element
                    if ($ajax_processing) {
                        if (strpos($path, "pmxi_chunk_") !== false and @file_exists($path)) {
                            @unlink($path);
                        }
                        PMXI_Plugin::$session->set('pointer', 1);
                        $pointer = 0;
                        $lp = PMXI_Plugin::$session->local_paths;
                        array_shift($lp);
                        PMXI_Plugin::$session->set('local_paths', $lp);
                        PMXI_Plugin::$session->save_data();
                    } else {
                        break;
                    }
                }
            }
        }
        if (PMXI_Plugin::is_ajax() and empty(PMXI_Plugin::$session->local_paths) or !$ajax_processing or !empty($import->canceled)) {
            if ("ajax" != $import->options['import_processing'] and $log_storage) {
                $log_file = wp_all_import_secure_file($wp_uploads['basedir'] . DIRECTORY_SEPARATOR . PMXI_Plugin::LOGS_DIRECTORY, $history_log->id) . DIRECTORY_SEPARATOR . $history_log->id . '.html';
                if (PMXI_Plugin::$session->action != 'continue') {
                    @file_put_contents($log_file, PMXI_Plugin::$session->log);
                } else {
                    $log = @fopen($log_file, 'a+');
                    @fwrite($log, PMXI_Plugin::$session->log);
                    @fclose($log);
                }
            }
            wp_cache_flush();
            foreach (get_taxonomies() as $tax) {
                delete_option("{$tax}_children");
                _get_term_hierarchy($tax);
            }
            $import->set(array('registered_on' => date('Y-m-d H:i:s'), 'executing' => 0))->update();
            // add history log
            $custom_type = get_post_type_object($import->options['custom_type']);
            $history_log->set(array('time_run' => time() - strtotime($history_log->date), 'summary' => sprintf(__("%d %ss created %d updated %d deleted %d skipped", "pmxi_plugin"), $import->created, $custom_type->labels->singular_name, $import->updated, $import->deleted, $import->skipped)))->update();
            // clear import session
            PMXI_Plugin::$session->clean_session($import->id);
            // clear session data (prevent from reimporting the same data on page refresh)
            // [indicate in header process is complete]
            $msg = !empty($import->canceled) ? addcslashes(__('Canceled', 'wp_all_import_plugin'), "\n\r") : addcslashes(__('Complete', 'wp_all_import_plugin'), "\n\r");
            if ($ajax_processing) {
                ob_start();
            }
            do_action('pmxi_after_xml_import', $import->id);
            $import->options['is_import_specified'] and $logger and call_user_func($logger, 'Done');
            echo <<<COMPLETE
<script type="text/javascript">
//<![CDATA[
(function(\$){\t
\t\$('#status').html('{$msg}');\t
\twindow.onbeforeunload = false;
})(jQuery);
//]]>
</script>
COMPLETE;
            // [/indicate in header process is complete]
            if ($ajax_processing) {
                wp_send_json(array('imported' => $import->imported, 'created' => $import->created, 'updated' => $import->updated, 'percentage' => 100, 'warnings' => PMXI_Plugin::$session->warnings, 'errors' => PMXI_Plugin::$session->errors, 'log' => ob_get_clean(), 'done' => true, 'records_per_request' => $import->options['records_per_request']));
            }
        }
    }
Exemplo n.º 21
0
 /**
  * @see Controller::render()
  */
 protected function render($viewPath = NULL)
 {
     // assume template file name depending on calling function
     if (is_null($viewPath)) {
         $trace = debug_backtrace();
         $viewPath = str_replace('_', '/', preg_replace('%^' . preg_quote(PMXI_Plugin::PREFIX, '%') . '%', '', strtolower($trace[1]['class']))) . '/' . $trace[1]['function'];
     }
     // render contextual help automatically
     $viewHelpPath = $viewPath;
     // append file extension if not specified
     if (!preg_match('%\\.php$%', $viewHelpPath)) {
         $viewHelpPath .= '.php';
     }
     $viewHelpPath = preg_replace('%\\.php$%', '-help.php', $viewHelpPath);
     $fileHelpPath = PMXI_Plugin::ROOT_DIR . '/views/' . $viewHelpPath;
     if (is_file($fileHelpPath)) {
         // there is help file defined
         ob_start();
         include $fileHelpPath;
         add_contextual_help(PMXI_Plugin::getInstance()->getAdminCurrentScreen()->id, ob_get_clean());
     }
     parent::render($viewPath);
 }
Exemplo n.º 22
0
<div class="wrap">
	<?php 
$homeurl = "http://www.wpallimport.com/adminpanel/index.php?v=" . urlencode(PMXI_Plugin::getInstance()->getVersion());
$contents = @file_get_contents($homeurl);
if (!$contents) {
    ?>
			<iframe src='<?php 
    echo $homeurl;
    ?>
' width='600'></iframe><br />
			<?php 
} else {
    echo $contents;
}
?>
</div>



Exemplo n.º 23
0
 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("\n\t\t\tSELECT DISTINCT postmeta.meta_value\n\t\t\tFROM " . $wpdb->postmeta . " as postmeta\n\t\t\tWHERE postmeta.meta_key='" . $meta_key . "' LIMIT 0,10\n\t\t", 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)));
 }
Exemplo n.º 24
0
 function toXML($fixBrokenSymbols = false)
 {
     $c = 0;
     $d = "" != $this->delimiter ? $this->delimiter : $this->settings['delimiter'];
     $e = $this->settings['escape'];
     $l = $this->settings['length'];
     PMXI_Plugin::$is_csv = $d;
     $res = fopen($this->_filename, 'rb');
     $xmlWriter = new XMLWriter();
     $xmlWriter->openURI($this->xml_path);
     $xmlWriter->setIndent(true);
     $xmlWriter->setIndentString("\t");
     $xmlWriter->startDocument('1.0', $this->csv_encoding);
     $xmlWriter->startElement('data');
     $create_new_headers = false;
     while ($keys = fgetcsv($res, $l, $d, $e)) {
         if ($c == 0) {
             $buf_keys = $keys;
             foreach ($keys as $key => $value) {
                 if (!$create_new_headers and (preg_match('%\\W(http:|https:|ftp:)$%i', $value) or is_numeric($value))) {
                     $create_new_headers = true;
                 }
                 $value = trim(strtolower(preg_replace('/^[0-9]{1}/', 'el_', preg_replace('/[^a-z0-9_]/i', '', $value))));
                 $keys[$key] = !empty($value) ? $value : 'undefined' . $key;
             }
             $this->headers = $keys;
             if ($create_new_headers) {
                 $this->createHeaders('column');
                 $keys = $buf_keys;
             }
         }
         if ($c or $create_new_headers) {
             if (!empty($keys)) {
                 $chunk = array();
                 foreach ($this->headers as $key => $header) {
                     $chunk[$header] = $this->fixEncoding($keys[$key]);
                 }
                 if (!empty($chunk)) {
                     $xmlWriter->startElement('node');
                     foreach ($chunk as $header => $value) {
                         $xmlWriter->startElement($header);
                         if ($fixBrokenSymbols) {
                             // Remove non ASCII symbols and write CDATA
                             $xmlWriter->writeCData(preg_replace('/[^\\x{0009}\\x{000a}\\x{000d}\\x{0020}-\\x{D7FF}\\x{E000}-\\x{FFFD}]+/u', ' ', $value));
                         } else {
                             $xmlWriter->writeCData($value);
                         }
                         $xmlWriter->endElement();
                     }
                     $xmlWriter->endElement();
                 }
             }
         }
         $c++;
     }
     fclose($res);
     $xmlWriter->endElement();
     $xmlWriter->flush(true);
     return true;
 }
Exemplo n.º 25
0
 /**
  * Initialize model instance
  * @param array[optional] $data Array of record data to initialize object with
  */
 public function __construct($data = array())
 {
     parent::__construct($data);
     $this->setTable(PMXI_Plugin::getInstance()->getTablePrefix() . 'imports');
 }
Exemplo n.º 26
0
 /**
  * Perform import operation
  * @param string $xml XML string to import
  * @param callback[optional] $logger Method where progress messages are submmitted
  * @return PMXI_Import_Record
  * @chainable
  */
 public function process($xml, $logger = NULL, $chunk = false, $is_cron = false, $xpath_prefix = '', $loop = 0)
 {
     add_filter('user_has_cap', array($this, '_filter_has_cap_unfiltered_html'));
     kses_init();
     // do not perform special filtering for imported content
     kses_remove_filters();
     $cxpath = $xpath_prefix . $this->xpath;
     $this->options += PMXI_Plugin::get_default_import_options();
     // make sure all options are defined
     $avoid_pingbacks = PMXI_Plugin::getInstance()->getOption('pingbacks');
     $cron_sleep = (int) PMXI_Plugin::getInstance()->getOption('cron_sleep');
     if ($avoid_pingbacks and !defined('WP_IMPORTING')) {
         define('WP_IMPORTING', true);
     }
     $postRecord = new PMXI_Post_Record();
     $tmp_files = array();
     // compose records to import
     $records = array();
     $is_import_complete = false;
     try {
         $chunk == 1 and $logger and call_user_func($logger, __('Composing titles...', 'wp_all_import_plugin'));
         if (!empty($this->options['title'])) {
             $titles = XmlImportParser::factory($xml, $cxpath, $this->options['title'], $file)->parse($records);
             $tmp_files[] = $file;
         } else {
             $loop and $titles = array_fill(0, $loop, '');
         }
         $chunk == 1 and $logger and call_user_func($logger, __('Composing excerpts...', 'wp_all_import_plugin'));
         $post_excerpt = array();
         if (!empty($this->options['post_excerpt'])) {
             $post_excerpt = XmlImportParser::factory($xml, $cxpath, $this->options['post_excerpt'], $file)->parse($records);
             $tmp_files[] = $file;
         } else {
             count($titles) and $post_excerpt = array_fill(0, count($titles), '');
         }
         if ("xpath" == $this->options['status']) {
             $chunk == 1 and $logger and call_user_func($logger, __('Composing statuses...', 'wp_all_import_plugin'));
             $post_status = array();
             if (!empty($this->options['status_xpath'])) {
                 $post_status = XmlImportParser::factory($xml, $cxpath, $this->options['status_xpath'], $file)->parse($records);
                 $tmp_files[] = $file;
             } else {
                 count($titles) and $post_status = array_fill(0, count($titles), '');
             }
         }
         if ("xpath" == $this->options['comment_status']) {
             $chunk == 1 and $logger and call_user_func($logger, __('Composing comment statuses...', 'wp_all_import_plugin'));
             $comment_status = array();
             if (!empty($this->options['comment_status_xpath'])) {
                 $comment_status = XmlImportParser::factory($xml, $cxpath, $this->options['comment_status_xpath'], $file)->parse($records);
                 $tmp_files[] = $file;
             } else {
                 count($titles) and $comment_status = array_fill(0, count($titles), 'open');
             }
         }
         if ("xpath" == $this->options['ping_status']) {
             $chunk == 1 and $logger and call_user_func($logger, __('Composing ping statuses...', 'wp_all_import_plugin'));
             $ping_status = array();
             if (!empty($this->options['ping_status_xpath'])) {
                 $ping_status = XmlImportParser::factory($xml, $cxpath, $this->options['ping_status_xpath'], $file)->parse($records);
                 $tmp_files[] = $file;
             } else {
                 count($titles) and $ping_status = array_fill(0, count($titles), 'open');
             }
         }
         if ("xpath" == $this->options['post_format']) {
             $chunk == 1 and $logger and call_user_func($logger, __('Composing post formats...', 'wp_all_import_plugin'));
             $post_format = array();
             if (!empty($this->options['post_format_xpath'])) {
                 $post_format = XmlImportParser::factory($xml, $cxpath, $this->options['post_format_xpath'], $file)->parse($records);
                 $tmp_files[] = $file;
             } else {
                 count($titles) and $post_format = array_fill(0, count($titles), 'open');
             }
         }
         if ("no" == $this->options['is_multiple_page_template']) {
             $chunk == 1 and $logger and call_user_func($logger, __('Composing page templates...', 'wp_all_import_plugin'));
             $page_template = array();
             if (!empty($this->options['single_page_template'])) {
                 $page_template = XmlImportParser::factory($xml, $cxpath, $this->options['single_page_template'], $file)->parse($records);
                 $tmp_files[] = $file;
             } else {
                 count($titles) and $page_template = array_fill(0, count($titles), 'default');
             }
         }
         if ($this->options['is_override_post_type'] and !empty($this->options['post_type_xpath'])) {
             $chunk == 1 and $logger and call_user_func($logger, __('Composing post types...', 'wp_all_import_plugin'));
             $post_type = array();
             $post_type = XmlImportParser::factory($xml, $cxpath, $this->options['post_type_xpath'], $file)->parse($records);
             $tmp_files[] = $file;
         } else {
             if ('post' == $this->options['type'] and '' != $this->options['custom_type']) {
                 $pType = $this->options['custom_type'];
             } else {
                 $pType = $this->options['type'];
             }
             count($titles) and $post_type = array_fill(0, count($titles), $pType);
         }
         if ("no" == $this->options['is_multiple_page_parent']) {
             $chunk == 1 and $logger and call_user_func($logger, __('Composing page parent...', 'wp_all_import_plugin'));
             $page_parent = array();
             if (!empty($this->options['single_page_parent'])) {
                 $page_parent = XmlImportParser::factory($xml, $cxpath, $this->options['single_page_parent'], $file)->parse($records);
                 $tmp_files[] = $file;
                 foreach ($page_parent as $key => $identity) {
                     $page = 0;
                     switch ($this->options['type']) {
                         case 'post':
                             if (!empty($identity)) {
                                 if (ctype_digit($identity)) {
                                     $page = get_post($identity);
                                 } else {
                                     $page = get_page_by_title($identity, OBJECT, $post_type[$key]);
                                     if (empty($page)) {
                                         $args = array('name' => $identity, 'post_type' => $post_type[$key], 'post_status' => 'any', 'numberposts' => 1);
                                         $my_posts = get_posts($args);
                                         if ($my_posts) {
                                             $page = $my_posts[0];
                                         }
                                     }
                                 }
                             }
                             break;
                         case 'page':
                             $page = get_page_by_title($identity) or $page = get_page_by_path($identity) or ctype_digit($identity) and $page = get_post($identity);
                             break;
                         default:
                             # code...
                             break;
                     }
                     $page_parent[$key] = !empty($page) ? $page->ID : 0;
                 }
             } else {
                 count($titles) and $page_parent = array_fill(0, count($titles), 0);
             }
         }
         $chunk == 1 and $logger and call_user_func($logger, __('Composing authors...', 'wp_all_import_plugin'));
         $post_author = array();
         $current_user = wp_get_current_user();
         if (!empty($this->options['author'])) {
             $post_author = XmlImportParser::factory($xml, $cxpath, $this->options['author'], $file)->parse($records);
             $tmp_files[] = $file;
             foreach ($post_author as $key => $author) {
                 $user = get_user_by('login', $author) or $user = get_user_by('slug', $author) or $user = get_user_by('email', $author) or ctype_digit($author) and $user = get_user_by('id', $author);
                 $post_author[$key] = !empty($user) ? $user->ID : $current_user->ID;
             }
         } else {
             count($titles) and $post_author = array_fill(0, count($titles), $current_user->ID);
         }
         $chunk == 1 and $logger and call_user_func($logger, __('Composing slugs...', 'wp_all_import_plugin'));
         $post_slug = array();
         if (!empty($this->options['post_slug'])) {
             $post_slug = XmlImportParser::factory($xml, $cxpath, $this->options['post_slug'], $file)->parse($records);
             $tmp_files[] = $file;
         } else {
             count($titles) and $post_slug = array_fill(0, count($titles), '');
         }
         $chunk == 1 and $logger and call_user_func($logger, __('Composing menu order...', 'wp_all_import_plugin'));
         $menu_order = array();
         if (!empty($this->options['order'])) {
             $menu_order = XmlImportParser::factory($xml, $cxpath, $this->options['order'], $file)->parse($records);
             $tmp_files[] = $file;
         } else {
             count($titles) and $menu_order = array_fill(0, count($titles), '');
         }
         $chunk == 1 and $logger and call_user_func($logger, __('Composing contents...', 'wp_all_import_plugin'));
         if (!empty($this->options['content'])) {
             $contents = XmlImportParser::factory((!empty($this->options['is_keep_linebreaks']) and intval($this->options['is_keep_linebreaks'])) ? $xml : preg_replace('%\\r\\n?|\\n%', ' ', $xml), $cxpath, $this->options['content'], $file)->parse($records);
             $tmp_files[] = $file;
         } else {
             count($titles) and $contents = array_fill(0, count($titles), '');
         }
         $chunk == 1 and $logger and call_user_func($logger, __('Composing dates...', 'wp_all_import_plugin'));
         if ('specific' == $this->options['date_type']) {
             $dates = XmlImportParser::factory($xml, $cxpath, $this->options['date'], $file)->parse($records);
             $tmp_files[] = $file;
             $warned = array();
             // used to prevent the same notice displaying several times
             foreach ($dates as $i => $d) {
                 if ($d == 'now') {
                     $d = current_time('mysql');
                 }
                 // Replace 'now' with the WordPress local time to account for timezone offsets (WordPress references its local time during publishing rather than the server’s time so it should use that)
                 $time = strtotime($d);
                 if (FALSE === $time) {
                     in_array($d, $warned) or $logger and call_user_func($logger, sprintf(__('<b>WARNING</b>: unrecognized date format `%s`, assigning current date', 'wp_all_import_plugin'), $warned[] = $d));
                     $logger and !$is_cron and PMXI_Plugin::$session->warnings++;
                     $time = time();
                 }
                 $dates[$i] = date('Y-m-d H:i:s', $time);
             }
         } else {
             $dates_start = XmlImportParser::factory($xml, $cxpath, $this->options['date_start'], $file)->parse($records);
             $tmp_files[] = $file;
             $dates_end = XmlImportParser::factory($xml, $cxpath, $this->options['date_end'], $file)->parse($records);
             $tmp_files[] = $file;
             $warned = array();
             // used to prevent the same notice displaying several times
             foreach ($dates_start as $i => $d) {
                 $time_start = strtotime($dates_start[$i]);
                 if (FALSE === $time_start) {
                     in_array($dates_start[$i], $warned) or $logger and call_user_func($logger, sprintf(__('<b>WARNING</b>: unrecognized date format `%s`, assigning current date', 'wp_all_import_plugin'), $warned[] = $dates_start[$i]));
                     $logger and !$is_cron and PMXI_Plugin::$session->warnings++;
                     $time_start = time();
                 }
                 $time_end = strtotime($dates_end[$i]);
                 if (FALSE === $time_end) {
                     in_array($dates_end[$i], $warned) or $logger and call_user_func($logger, sprintf(__('<b>WARNING</b>: unrecognized date format `%s`, assigning current date', 'wp_all_import_plugin'), $warned[] = $dates_end[$i]));
                     $logger and !$is_cron and PMXI_Plugin::$session->warnings++;
                     $time_end = time();
                 }
                 $dates[$i] = date('Y-m-d H:i:s', mt_rand($time_start, $time_end));
             }
         }
         // [custom taxonomies]
         require_once ABSPATH . 'wp-admin/includes/taxonomy.php';
         $taxonomies = array();
         $exclude_taxonomies = apply_filters('pmxi_exclude_taxonomies', class_exists('PMWI_Plugin') ? array('post_format', 'product_type', 'product_shipping_class') : array('post_format'));
         $post_taxonomies = array_diff_key(get_taxonomies_by_object_type(array($this->options['custom_type']), 'object'), array_flip($exclude_taxonomies));
         if (!empty($post_taxonomies)) {
             foreach ($post_taxonomies as $ctx) {
                 if ("" == $ctx->labels->name or class_exists('PMWI_Plugin') and strpos($ctx->name, "pa_") === 0 and $this->options['custom_type'] == "product") {
                     continue;
                 }
                 $chunk == 1 and $logger and call_user_func($logger, sprintf(__('Composing terms for `%s` taxonomy...', 'wp_all_import_plugin'), $ctx->labels->name));
                 $tx_name = $ctx->name;
                 $mapping_rules = !empty($this->options['tax_mapping'][$tx_name]) ? json_decode($this->options['tax_mapping'][$tx_name], true) : false;
                 $taxonomies[$tx_name] = array();
                 if (!empty($this->options['tax_logic'][$tx_name]) and !empty($this->options['tax_assing'][$tx_name])) {
                     switch ($this->options['tax_logic'][$tx_name]) {
                         case 'single':
                             if (!empty($this->options['tax_single_xpath'][$tx_name])) {
                                 $txes = XmlImportParser::factory($xml, $cxpath, $this->options['tax_single_xpath'][$tx_name], $file)->parse($records);
                                 $tmp_files[] = $file;
                                 foreach ($txes as $i => $tx) {
                                     $taxonomies[$tx_name][$i][] = wp_all_import_ctx_mapping(array('name' => $tx, 'parent' => false, 'assign' => isset($this->options['term_assing'][$tx_name]) ? $this->options['term_assing'][$tx_name] : true, 'is_mapping' => !empty($this->options['tax_enable_mapping'][$tx_name]), 'hierarchy_level' => 1, 'max_hierarchy_level' => 1), $mapping_rules, $tx_name);
                                 }
                             }
                             break;
                         case 'multiple':
                             if (!empty($this->options['tax_multiple_xpath'][$tx_name])) {
                                 $txes = XmlImportParser::factory($xml, $cxpath, $this->options['tax_multiple_xpath'][$tx_name], $file)->parse($records);
                                 $tmp_files[] = $file;
                                 foreach ($txes as $i => $tx) {
                                     $_tx = $tx;
                                     // apply mapping rules before splitting via separator symbol
                                     if (!empty($this->options['tax_enable_mapping'][$tx_name]) and !empty($this->options['tax_logic_mapping'][$tx_name])) {
                                         if (!empty($mapping_rules)) {
                                             foreach ($mapping_rules as $rule) {
                                                 if (!empty($rule[trim($_tx)])) {
                                                     $_tx = trim($rule[trim($_tx)]);
                                                     break;
                                                 }
                                             }
                                         }
                                     }
                                     $delimeted_taxonomies = explode(!empty($this->options['tax_multiple_delim'][$tx_name]) ? $this->options['tax_multiple_delim'][$tx_name] : ',', $_tx);
                                     if (!empty($delimeted_taxonomies)) {
                                         foreach ($delimeted_taxonomies as $cc) {
                                             $taxonomies[$tx_name][$i][] = wp_all_import_ctx_mapping(array('name' => $cc, 'parent' => false, 'assign' => isset($this->options['multiple_term_assing'][$tx_name]) ? $this->options['multiple_term_assing'][$tx_name] : true, 'is_mapping' => !empty($this->options['tax_enable_mapping'][$tx_name]) and empty($this->options['tax_logic_mapping'][$tx_name]), 'hierarchy_level' => 1, 'max_hierarchy_level' => 1), $mapping_rules, $tx_name);
                                         }
                                     }
                                 }
                             }
                             break;
                         case 'hierarchical':
                             if (!empty($this->options['tax_hierarchical_logic_entire'][$tx_name])) {
                                 if (!empty($this->options['tax_hierarchical_xpath'][$tx_name]) and is_array($this->options['tax_hierarchical_xpath'][$tx_name])) {
                                     count($titles) and $iterator = array_fill(0, count($titles), 0);
                                     $taxonomies_hierarchy_groups = array_fill(0, count($titles), array());
                                     // separate hierarchy groups via symbol
                                     if (!empty($this->options['is_tax_hierarchical_group_delim'][$tx_name]) and !empty($this->options['tax_hierarchical_group_delim'][$tx_name])) {
                                         foreach ($this->options['tax_hierarchical_xpath'][$tx_name] as $k => $tx_xpath) {
                                             if (empty($tx_xpath)) {
                                                 continue;
                                             }
                                             $txes = XmlImportParser::factory($xml, $cxpath, $tx_xpath, $file)->parse($records);
                                             $tmp_files[] = $file;
                                             foreach ($txes as $i => $tx) {
                                                 $_tx = $tx;
                                                 // apply mapping rules before splitting via separator symbol
                                                 if (!empty($this->options['tax_enable_mapping'][$tx_name]) and !empty($this->options['tax_logic_mapping'][$tx_name])) {
                                                     if (!empty($mapping_rules)) {
                                                         foreach ($mapping_rules as $rule) {
                                                             if (!empty($rule[trim($_tx)])) {
                                                                 $_tx = trim($rule[trim($_tx)]);
                                                                 break;
                                                             }
                                                         }
                                                     }
                                                 }
                                                 $delimeted_groups = explode($this->options['tax_hierarchical_group_delim'][$tx_name], $_tx);
                                                 if (!empty($delimeted_groups) and is_array($delimeted_groups)) {
                                                     foreach ($delimeted_groups as $group) {
                                                         if (!empty($group)) {
                                                             array_push($taxonomies_hierarchy_groups[$i], $group);
                                                         }
                                                     }
                                                 }
                                             }
                                         }
                                     } else {
                                         foreach ($this->options['tax_hierarchical_xpath'][$tx_name] as $k => $tx_xpath) {
                                             if (empty($tx_xpath)) {
                                                 continue;
                                             }
                                             $txes = XmlImportParser::factory($xml, $cxpath, $tx_xpath, $file)->parse($records);
                                             $tmp_files[] = $file;
                                             foreach ($txes as $i => $tx) {
                                                 array_push($taxonomies_hierarchy_groups[$i], $tx);
                                             }
                                         }
                                     }
                                     foreach ($taxonomies_hierarchy_groups as $i => $groups) {
                                         if (empty($groups)) {
                                             continue;
                                         }
                                         foreach ($groups as $kk => $tx) {
                                             $_tx = $tx;
                                             // apply mapping rules before splitting via separator symbol
                                             if (!empty($this->options['tax_enable_mapping'][$tx_name]) and !empty($this->options['tax_logic_mapping'][$tx_name])) {
                                                 if (!empty($mapping_rules)) {
                                                     foreach ($mapping_rules as $rule) {
                                                         if (!empty($rule[trim($_tx)])) {
                                                             $_tx = trim($rule[trim($_tx)]);
                                                             break;
                                                         }
                                                     }
                                                 }
                                             }
                                             $delimeted_taxonomies = explode(!empty($this->options['tax_hierarchical_delim'][$tx_name]) ? $this->options['tax_hierarchical_delim'][$tx_name] : ',', $_tx);
                                             if (!empty($delimeted_taxonomies)) {
                                                 foreach ($delimeted_taxonomies as $j => $cc) {
                                                     $is_assign_term = isset($this->options['tax_hierarchical_assing'][$tx_name][$k]) ? $this->options['tax_hierarchical_assing'][$tx_name][$k] : true;
                                                     if (!empty($this->options['tax_hierarchical_last_level_assign'][$tx_name])) {
                                                         $is_assign_term = count($delimeted_taxonomies) == $j + 1 ? 1 : 0;
                                                     }
                                                     $taxonomies[$tx_name][$i][] = wp_all_import_ctx_mapping(array('name' => $cc, 'parent' => (!empty($taxonomies[$tx_name][$i][$iterator[$i] - 1]) and $j) ? $taxonomies[$tx_name][$i][$iterator[$i] - 1] : false, 'assign' => $is_assign_term, 'is_mapping' => !empty($this->options['tax_enable_mapping'][$tx_name]) and empty($this->options['tax_logic_mapping'][$tx_name]), 'hierarchy_level' => $j + 1, 'max_hierarchy_level' => count($delimeted_taxonomies)), $mapping_rules, $tx_name);
                                                     $iterator[$i]++;
                                                 }
                                             }
                                         }
                                     }
                                 }
                             }
                             if (!empty($this->options['tax_hierarchical_logic_manual'][$tx_name])) {
                                 if (!empty($this->options['post_taxonomies'][$tx_name])) {
                                     $taxonomies_hierarchy = json_decode($this->options['post_taxonomies'][$tx_name], true);
                                     foreach ($taxonomies_hierarchy as $k => $taxonomy) {
                                         if ("" == $taxonomy['xpath']) {
                                             continue;
                                         }
                                         $txes_raw = XmlImportParser::factory($xml, $cxpath, $taxonomy['xpath'], $file)->parse($records);
                                         $tmp_files[] = $file;
                                         $warned = array();
                                         foreach ($txes_raw as $i => $cc) {
                                             $_tx = $cc;
                                             // apply mapping rules before splitting via separator symbol
                                             if (!empty($this->options['tax_enable_mapping'][$tx_name]) and !empty($this->options['tax_logic_mapping'][$tx_name])) {
                                                 if (!empty($mapping_rules)) {
                                                     foreach ($mapping_rules as $rule) {
                                                         if (!empty($rule[trim($_tx)])) {
                                                             $_tx = trim($rule[trim($_tx)]);
                                                             break;
                                                         }
                                                     }
                                                 }
                                             }
                                             if (!empty($this->options['tax_manualhierarchy_delim'][$tx_name])) {
                                                 $delimeted_taxonomies = explode($this->options['tax_manualhierarchy_delim'][$tx_name], $_tx);
                                             }
                                             if (empty($delimeted_taxonomies)) {
                                                 continue;
                                             }
                                             if (empty($taxonomies_hierarchy[$k]['txn_names'][$i])) {
                                                 $taxonomies_hierarchy[$k]['txn_names'][$i] = array();
                                             }
                                             if (empty($taxonomies[$tx_name][$i])) {
                                                 $taxonomies[$tx_name][$i] = array();
                                             }
                                             $count_cats = count($taxonomies[$tx_name][$i]);
                                             foreach ($delimeted_taxonomies as $j => $dc) {
                                                 if (!empty($taxonomy['parent_id'])) {
                                                     foreach ($taxonomies_hierarchy as $key => $value) {
                                                         if ($value['item_id'] == $taxonomy['parent_id'] and !empty($value['txn_names'][$i])) {
                                                             foreach ($value['txn_names'][$i] as $parent) {
                                                                 $taxonomies[$tx_name][$i][] = wp_all_import_ctx_mapping(array('name' => trim($dc), 'parent' => $parent, 'assign' => isset($taxonomy['assign']) ? $taxonomy['assign'] : true, 'is_mapping' => !empty($this->options['tax_enable_mapping'][$tx_name]) and empty($this->options['tax_logic_mapping'][$tx_name]), 'hierarchy_level' => 1, 'max_hierarchy_level' => 1), $mapping_rules, $tx_name);
                                                             }
                                                         }
                                                     }
                                                 } else {
                                                     $taxonomies[$tx_name][$i][] = wp_all_import_ctx_mapping(array('name' => trim($dc), 'parent' => false, 'assign' => isset($taxonomy['assign']) ? $taxonomy['assign'] : true, 'is_mapping' => !empty($this->options['tax_enable_mapping'][$tx_name]) and empty($this->options['tax_logic_mapping'][$tx_name]), 'hierarchy_level' => 1, 'max_hierarchy_level' => 1), $mapping_rules, $tx_name);
                                                 }
                                                 if ($count_cats < count($taxonomies[$tx_name][$i])) {
                                                     $taxonomies_hierarchy[$k]['txn_names'][$i][] = $taxonomies[$tx_name][$i][count($taxonomies[$tx_name][$i]) - 1];
                                                 }
                                             }
                                         }
                                     }
                                 }
                             }
                             break;
                         default:
                             break;
                     }
                 }
             }
         }
         // [/custom taxonomies]
         // Composing featured images
         $image_sections = apply_filters('wp_all_import_image_sections', array(array('slug' => '', 'title' => __('Images', 'wp_all_import_plugin'), 'type' => 'images')));
         if (!(($uploads = wp_upload_dir()) && false === $uploads['error'])) {
             $logger and call_user_func($logger, __('<b>WARNING</b>', 'wp_all_import_plugin') . ': ' . $uploads['error']);
             $logger and call_user_func($logger, __('<b>WARNING</b>: No featured images will be created. Uploads folder is not found.', 'wp_all_import_plugin'));
             $logger and !$is_cron and PMXI_Plugin::$session->warnings++;
         } else {
             $images_bundle = array();
             foreach ($image_sections as $section) {
                 $chunk == 1 and $logger and call_user_func($logger, __('Composing URLs for ' . strtolower($section['title']) . '...', 'wp_all_import_plugin'));
                 $featured_images = array();
                 if ("no" == $this->options[$section['slug'] . 'download_images']) {
                     if ($this->options[$section['slug'] . 'featured_image']) {
                         $featured_images = XmlImportParser::factory($xml, $cxpath, $this->options[$section['slug'] . 'featured_image'], $file)->parse($records);
                         $tmp_files[] = $file;
                     } else {
                         count($titles) and $featured_images = array_fill(0, count($titles), '');
                     }
                 } else {
                     if ($this->options[$section['slug'] . 'download_featured_image']) {
                         $featured_images = XmlImportParser::factory($xml, $cxpath, $this->options[$section['slug'] . 'download_featured_image'], $file)->parse($records);
                         $tmp_files[] = $file;
                     } else {
                         count($titles) and $featured_images = array_fill(0, count($titles), '');
                     }
                 }
                 $images_bundle[empty($section['slug']) ? 'pmxi_gallery_image' : $section['slug']] = array('type' => $section['type'], 'files' => $featured_images);
                 // Composing images meta titles
                 $image_meta_titles_bundle = array();
                 if ($this->options[$section['slug'] . 'set_image_meta_title']) {
                     $chunk == 1 and $logger and call_user_func($logger, __('Composing ' . strtolower($section['title']) . ' meta data (titles)...', 'wp_all_import_plugin'));
                     $image_meta_titles = array();
                     if ($this->options[$section['slug'] . 'image_meta_title']) {
                         $image_meta_titles = XmlImportParser::factory($xml, $cxpath, $this->options[$section['slug'] . 'image_meta_title'], $file)->parse($records);
                         $tmp_files[] = $file;
                     } else {
                         count($titles) and $image_meta_titles = array_fill(0, count($titles), '');
                     }
                     $image_meta_titles_bundle[empty($section['slug']) ? 'pmxi_gallery_image' : $section['slug']] = $image_meta_titles;
                 }
                 // Composing images meta captions
                 $image_meta_captions_bundle = array();
                 if ($this->options[$section['slug'] . 'set_image_meta_caption']) {
                     $chunk == 1 and $logger and call_user_func($logger, __('Composing ' . strtolower($section['title']) . ' meta data (captions)...', 'wp_all_import_plugin'));
                     $image_meta_captions = array();
                     if ($this->options[$section['slug'] . 'image_meta_caption']) {
                         $image_meta_captions = XmlImportParser::factory($xml, $cxpath, $this->options[$section['slug'] . 'image_meta_caption'], $file)->parse($records);
                         $tmp_files[] = $file;
                     } else {
                         count($titles) and $image_meta_captions = array_fill(0, count($titles), '');
                     }
                     $image_meta_captions_bundle[empty($section['slug']) ? 'pmxi_gallery_image' : $section['slug']] = $image_meta_captions;
                 }
                 // Composing images meta alt text
                 $image_meta_alts_bundle = array();
                 if ($this->options[$section['slug'] . 'set_image_meta_alt']) {
                     $chunk == 1 and $logger and call_user_func($logger, __('Composing ' . strtolower($section['title']) . ' meta data (alt text)...', 'wp_all_import_plugin'));
                     $image_meta_alts = array();
                     if ($this->options[$section['slug'] . 'image_meta_alt']) {
                         $image_meta_alts = XmlImportParser::factory($xml, $cxpath, $this->options[$section['slug'] . 'image_meta_alt'], $file)->parse($records);
                         $tmp_files[] = $file;
                     } else {
                         count($titles) and $image_meta_alts = array_fill(0, count($titles), '');
                     }
                     $image_meta_alts_bundle[empty($section['slug']) ? 'pmxi_gallery_image' : $section['slug']] = $image_meta_alts;
                 }
                 // Composing images meta description
                 $image_meta_descriptions_bundle = array();
                 if ($this->options[$section['slug'] . 'set_image_meta_description']) {
                     $chunk == 1 and $logger and call_user_func($logger, __('Composing ' . strtolower($section['title']) . ' meta data (description)...', 'wp_all_import_plugin'));
                     $image_meta_descriptions = array();
                     if ($this->options[$section['slug'] . 'image_meta_description']) {
                         $image_meta_descriptions = XmlImportParser::factory($xml, $cxpath, $this->options[$section['slug'] . 'image_meta_description'], $file)->parse($records);
                         $tmp_files[] = $file;
                     } else {
                         count($titles) and $image_meta_descriptions = array_fill(0, count($titles), '');
                     }
                     $image_meta_descriptions_bundle[empty($section['slug']) ? 'pmxi_gallery_image' : $section['slug']] = $image_meta_descriptions;
                 }
                 $auto_rename_images_bundle = array();
                 $auto_extensions_bundle = array();
                 if ("yes" == $this->options[$section['slug'] . 'download_images']) {
                     // Composing images suffix
                     $chunk == 1 and $this->options[$section['slug'] . 'auto_rename_images'] and $logger and call_user_func($logger, __('Composing ' . strtolower($section['title']) . ' suffix...', 'wp_all_import_plugin'));
                     $auto_rename_images = array();
                     if ($this->options[$section['slug'] . 'auto_rename_images'] and !empty($this->options[$section['slug'] . 'auto_rename_images_suffix'])) {
                         $auto_rename_images = XmlImportParser::factory($xml, $cxpath, $this->options[$section['slug'] . 'auto_rename_images_suffix'], $file)->parse($records);
                         $tmp_files[] = $file;
                     } else {
                         count($titles) and $auto_rename_images = array_fill(0, count($titles), '');
                     }
                     $auto_rename_images_bundle[empty($section['slug']) ? 'pmxi_gallery_image' : $section['slug']] = $auto_rename_images;
                     // Composing images extensions
                     $chunk == 1 and $this->options[$section['slug'] . 'auto_set_extension'] and $logger and call_user_func($logger, __('Composing ' . strtolower($section['title']) . ' extensions...', 'wp_all_import_plugin'));
                     $auto_extensions = array();
                     if ($this->options[$section['slug'] . 'auto_set_extension'] and !empty($this->options[$section['slug'] . 'new_extension'])) {
                         $auto_extensions = XmlImportParser::factory($xml, $cxpath, $this->options[$section['slug'] . 'new_extension'], $file)->parse($records);
                         $tmp_files[] = $file;
                     } else {
                         count($titles) and $auto_extensions = array_fill(0, count($titles), '');
                     }
                     $auto_extensions_bundle[empty($section['slug']) ? 'pmxi_gallery_image' : $section['slug']] = $auto_extensions;
                 }
             }
         }
         // Composing attachments
         if (!(($uploads = wp_upload_dir()) && false === $uploads['error'])) {
             $logger and call_user_func($logger, __('<b>WARNING</b>', 'wp_all_import_plugin') . ': ' . $uploads['error']);
             $logger and call_user_func($logger, __('<b>WARNING</b>: No attachments will be created', 'wp_all_import_plugin'));
             $logger and !$is_cron and PMXI_Plugin::$session->warnings++;
         } else {
             $chunk == 1 and $logger and call_user_func($logger, __('Composing URLs for attachments files...', 'wp_all_import_plugin'));
             $attachments = array();
             if ($this->options['attachments']) {
                 // Detect if attachments is separated by comma
                 $atchs = explode(',', $this->options['attachments']);
                 if (!empty($atchs)) {
                     $parse_multiple = true;
                     foreach ($atchs as $atch) {
                         if (!preg_match("/{.*}/", trim($atch))) {
                             $parse_multiple = false;
                         }
                     }
                     if ($parse_multiple) {
                         foreach ($atchs as $atch) {
                             $posts_attachments = XmlImportParser::factory($xml, $cxpath, trim($atch), $file)->parse($records);
                             $tmp_files[] = $file;
                             foreach ($posts_attachments as $i => $val) {
                                 $attachments[$i][] = $val;
                             }
                         }
                     } else {
                         $attachments = XmlImportParser::factory($xml, $cxpath, $this->options['attachments'], $file)->parse($records);
                         $tmp_files[] = $file;
                     }
                 }
             } else {
                 count($titles) and $attachments = array_fill(0, count($titles), '');
             }
         }
         $chunk == 1 and $logger and call_user_func($logger, __('Composing unique keys...', 'wp_all_import_plugin'));
         if (!empty($this->options['unique_key'])) {
             $unique_keys = XmlImportParser::factory($xml, $cxpath, $this->options['unique_key'], $file)->parse($records);
             $tmp_files[] = $file;
         } else {
             count($titles) and $unique_keys = array_fill(0, count($titles), '');
         }
         $chunk == 1 and $logger and call_user_func($logger, __('Processing posts...', 'wp_all_import_plugin'));
         $addons = array();
         $addons_data = array();
         // data parsing for WP All Import add-ons
         $chunk == 1 and $logger and call_user_func($logger, __('Data parsing via add-ons...', 'wp_all_import_plugin'));
         $parsingData = array('import' => $this, 'count' => count($titles), 'xml' => $xml, 'logger' => $logger, 'chunk' => $chunk, 'xpath_prefix' => $xpath_prefix);
         $parse_functions = apply_filters('wp_all_import_addon_parse', array());
         foreach (PMXI_Admin_Addons::get_active_addons() as $class) {
             $model_class = str_replace("_Plugin", "_Import_Record", $class);
             if (class_exists($model_class)) {
                 $addons[$class] = new $model_class();
                 $addons_data[$class] = method_exists($addons[$class], 'parse') ? $addons[$class]->parse($parsingData) : false;
             } else {
                 if (!empty($parse_functions[$class])) {
                     if (is_array($parse_functions[$class]) and is_callable($parse_functions[$class]) or !is_array($parse_functions[$class]) and function_exists($parse_functions[$class])) {
                         $addons_data[$class] = call_user_func($parse_functions[$class], $parsingData);
                     }
                 }
             }
         }
         // save current import state to variables before import
         $created = $this->created;
         $updated = $this->updated;
         $skipped = $this->skipped;
         $specified_records = array();
         if ($this->options['is_import_specified']) {
             $chunk == 1 and $logger and call_user_func($logger, __('Calculate specified records to import...', 'wp_all_import_plugin'));
             foreach (preg_split('% *, *%', $this->options['import_specified'], -1, PREG_SPLIT_NO_EMPTY) as $chank) {
                 if (preg_match('%^(\\d+)-(\\d+)$%', $chank, $mtch)) {
                     $specified_records = array_merge($specified_records, range(intval($mtch[1]), intval($mtch[2])));
                 } else {
                     $specified_records = array_merge($specified_records, array(intval($chank)));
                 }
             }
         }
         $simpleXml = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
         $rootNodes = $simpleXml->xpath($cxpath);
         foreach ($titles as $i => $void) {
             $custom_type_details = get_post_type_object($post_type[$i]);
             if ($is_cron and $cron_sleep) {
                 sleep($cron_sleep);
             }
             $logger and call_user_func($logger, __('---', 'wp_all_import_plugin'));
             $logger and call_user_func($logger, sprintf(__('Record #%s', 'wp_all_import_plugin'), $this->imported + $this->skipped + $i + 1));
             wp_cache_flush();
             $logger and call_user_func($logger, __('<b>ACTION</b>: pmxi_before_post_import ...', 'wp_all_import_plugin'));
             do_action('pmxi_before_post_import', $this->id);
             if (empty($titles[$i])) {
                 if (!empty($addons_data['PMWI_Plugin']) and !empty($addons_data['PMWI_Plugin']['single_product_parent_ID'][$i])) {
                     $titles[$i] = $addons_data['PMWI_Plugin']['single_product_parent_ID'][$i] . ' Product Variation';
                 } else {
                     $logger and call_user_func($logger, __('<b>WARNING</b>: title is empty.', 'wp_all_import_plugin'));
                     $logger and !$is_cron and PMXI_Plugin::$session->warnings++;
                 }
             }
             if ($this->options['custom_type'] == 'import_users') {
                 $articleData = array('user_pass' => $addons_data['PMUI_Plugin']['pmui_pass'][$i], 'user_login' => $addons_data['PMUI_Plugin']['pmui_logins'][$i], 'user_nicename' => $addons_data['PMUI_Plugin']['pmui_nicename'][$i], 'user_url' => $addons_data['PMUI_Plugin']['pmui_url'][$i], 'user_email' => $addons_data['PMUI_Plugin']['pmui_email'][$i], 'display_name' => $addons_data['PMUI_Plugin']['pmui_display_name'][$i], 'user_registered' => $addons_data['PMUI_Plugin']['pmui_registered'][$i], 'first_name' => $addons_data['PMUI_Plugin']['pmui_first_name'][$i], 'last_name' => $addons_data['PMUI_Plugin']['pmui_last_name'][$i], 'description' => $addons_data['PMUI_Plugin']['pmui_description'][$i], 'nickname' => $addons_data['PMUI_Plugin']['pmui_nickname'][$i], 'role' => '' == $addons_data['PMUI_Plugin']['pmui_role'][$i] ? 'subscriber' : strtolower($addons_data['PMUI_Plugin']['pmui_role'][$i]));
                 $logger and call_user_func($logger, sprintf(__('Combine all data for user %s...', 'wp_all_import_plugin'), $articleData['user_login']));
             } else {
                 $articleData = array('post_type' => $post_type[$i], 'post_status' => "xpath" == $this->options['status'] ? $post_status[$i] : $this->options['status'], 'comment_status' => "xpath" == $this->options['comment_status'] ? $comment_status[$i] : $this->options['comment_status'], 'ping_status' => "xpath" == $this->options['ping_status'] ? $ping_status[$i] : $this->options['ping_status'], 'post_title' => !empty($this->options['is_leave_html']) ? html_entity_decode($titles[$i]) : $titles[$i], 'post_excerpt' => apply_filters('pmxi_the_excerpt', !empty($this->options['is_leave_html']) ? html_entity_decode($post_excerpt[$i]) : $post_excerpt[$i], $this->id), 'post_name' => $post_slug[$i], 'post_content' => apply_filters('pmxi_the_content', !empty($this->options['is_leave_html']) ? html_entity_decode($contents[$i]) : $contents[$i], $this->id), 'post_date' => $dates[$i], 'post_date_gmt' => get_gmt_from_date($dates[$i]), 'post_author' => $post_author[$i], 'menu_order' => (int) $menu_order[$i], 'post_parent' => "no" == $this->options['is_multiple_page_parent'] ? (int) $page_parent[$i] : (int) $this->options['parent']);
                 $logger and call_user_func($logger, sprintf(__('Combine all data for post `%s`...', 'wp_all_import_plugin'), $articleData['post_title']));
             }
             // Re-import Records Matching
             $post_to_update = false;
             $post_to_update_id = false;
             // if Auto Matching re-import option selected
             if ("manual" != $this->options['duplicate_matching']) {
                 // find corresponding article among previously imported
                 $logger and call_user_func($logger, sprintf(__('Find corresponding article among previously imported for post `%s`...', 'wp_all_import_plugin'), $articleData['post_title']));
                 $postRecord->clear();
                 $postRecord->getBy(array('unique_key' => $unique_keys[$i], 'import_id' => $this->id));
                 if (!$postRecord->isEmpty()) {
                     $logger and call_user_func($logger, sprintf(__('Duplicate post was founded for post %s with unique key `%s`...', 'wp_all_import_plugin'), $articleData['post_title'], $unique_keys[$i]));
                     if ($this->options['custom_type'] == 'import_users') {
                         $post_to_update = get_user_by('id', $post_to_update_id = $postRecord->post_id);
                     } else {
                         $post_to_update = get_post($post_to_update_id = $postRecord->post_id);
                     }
                 } else {
                     $logger and call_user_func($logger, sprintf(__('Duplicate post wasn\'t founded with unique key `%s`...', 'wp_all_import_plugin'), $unique_keys[$i]));
                 }
                 // if Manual Matching re-import option seleted
             } else {
                 if ('custom field' == $this->options['duplicate_indicator']) {
                     $custom_duplicate_value = XmlImportParser::factory($xml, $cxpath, $this->options['custom_duplicate_value'], $file)->parse($records);
                     $tmp_files[] = $file;
                     $custom_duplicate_name = XmlImportParser::factory($xml, $cxpath, $this->options['custom_duplicate_name'], $file)->parse($records);
                     $tmp_files[] = $file;
                 } else {
                     count($titles) and $custom_duplicate_name = $custom_duplicate_value = array_fill(0, count($titles), '');
                 }
                 $logger and call_user_func($logger, sprintf(__('Find corresponding article among database for post `%s`...', 'wp_all_import_plugin'), $articleData['post_title']));
                 // handle duplicates according to import settings
                 if ($duplicates = pmxi_findDuplicates($articleData, $custom_duplicate_name[$i], $custom_duplicate_value[$i], $this->options['duplicate_indicator'])) {
                     $duplicate_id = array_shift($duplicates);
                     if ($duplicate_id) {
                         $logger and call_user_func($logger, sprintf(__('Duplicate post was founded for post `%s`...', 'wp_all_import_plugin'), $articleData['post_title']));
                         if ($this->options['custom_type'] == 'import_users') {
                             $post_to_update = get_user_by('id', $post_to_update_id = $duplicate_id);
                         } else {
                             $post_to_update = get_post($post_to_update_id = $duplicate_id);
                         }
                     } else {
                         $logger and call_user_func($logger, sprintf(__('Duplicate post wasn\'n founded for post `%s`...', 'wp_all_import_plugin'), $articleData['post_title']));
                     }
                 }
             }
             if (!empty($specified_records)) {
                 if (!in_array($created + $updated + $skipped + 1, $specified_records)) {
                     if (!$postRecord->isEmpty()) {
                         $postRecord->set(array('iteration' => $this->iteration))->update();
                     }
                     $skipped++;
                     $logger and call_user_func($logger, __('<b>SKIPPED</b>: by specified records option', 'wp_all_import_plugin'));
                     $logger and !$is_cron and PMXI_Plugin::$session->warnings++;
                     $logger and !$is_cron and PMXI_Plugin::$session->chunk_number++;
                     $logger and !$is_cron and PMXI_Plugin::$session->save_data();
                     continue;
                 }
             }
             // Duplicate record is founded
             if ($post_to_update) {
                 $continue_import = true;
                 $continue_import = apply_filters('wp_all_import_is_post_to_update', $post_to_update_id, wp_all_import_xml2array($rootNodes[$i]));
                 if (!$continue_import) {
                     if (!$postRecord->isEmpty()) {
                         $postRecord->set(array('iteration' => $this->iteration))->update();
                     }
                     $skipped++;
                     $logger and call_user_func($logger, sprintf(__('<b>SKIPPED</b>: By filter wp_all_import_is_post_to_update `%s`', 'wp_all_import_plugin'), $articleData['post_title']));
                     $logger and !$is_cron and PMXI_Plugin::$session->warnings++;
                     $logger and !$is_cron and PMXI_Plugin::$session->chunk_number++;
                     $logger and !$is_cron and PMXI_Plugin::$session->save_data();
                     continue;
                 }
                 //$logger and call_user_func($logger, sprintf(__('Duplicate record is founded for `%s`', 'wp_all_import_plugin'), $articleData['post_title']));
                 // Do not update already existing records option selected
                 if ("yes" == $this->options['is_keep_former_posts']) {
                     if (!$postRecord->isEmpty()) {
                         $postRecord->set(array('iteration' => $this->iteration))->update();
                     }
                     do_action('pmxi_do_not_update_existing', $post_to_update_id, $this->id, $this->iteration);
                     $skipped++;
                     $logger and call_user_func($logger, sprintf(__('<b>SKIPPED</b>: Previously imported record found for `%s`', 'wp_all_import_plugin'), $articleData['post_title']));
                     $logger and !$is_cron and PMXI_Plugin::$session->warnings++;
                     $logger and !$is_cron and PMXI_Plugin::$session->chunk_number++;
                     $logger and !$is_cron and PMXI_Plugin::$session->save_data();
                     continue;
                 }
                 $articleData['ID'] = $post_to_update_id;
                 // Choose which data to update
                 if ($this->options['update_all_data'] == 'no') {
                     if (!in_array($this->options['custom_type'], array('import_users'))) {
                         // preserve date of already existing article when duplicate is found
                         if (!$this->options['is_update_categories'] and (is_object_in_taxonomy($post_type[$i], 'category') or is_object_in_taxonomy($post_type[$i], 'post_tag')) or $this->options['is_update_categories'] and $this->options['update_categories_logic'] != "full_update") {
                             $logger and call_user_func($logger, sprintf(__('Preserve taxonomies of already existing article for `%s`', 'wp_all_import_plugin'), $articleData['post_title']));
                             $existing_taxonomies = array();
                             foreach (array_keys($taxonomies) as $tx_name) {
                                 $txes_list = get_the_terms($articleData['ID'], $tx_name);
                                 if (is_wp_error($txes_list)) {
                                     $logger and call_user_func($logger, sprintf(__('<b>WARNING</b>: Unable to get current taxonomies for article #%d, updating with those read from XML file', 'wp_all_import_plugin'), $articleData['ID']));
                                     $logger and !$is_cron and PMXI_Plugin::$session->warnings++;
                                 } else {
                                     $txes_new = array();
                                     if (!empty($txes_list)) {
                                         foreach ($txes_list as $t) {
                                             $txes_new[] = $t->term_taxonomy_id;
                                         }
                                     }
                                     $existing_taxonomies[$tx_name][$i] = $txes_new;
                                 }
                             }
                         }
                         if (!$this->options['is_update_dates']) {
                             // preserve date of already existing article when duplicate is found
                             $articleData['post_date'] = $post_to_update->post_date;
                             $articleData['post_date_gmt'] = $post_to_update->post_date_gmt;
                             $logger and call_user_func($logger, sprintf(__('Preserve date of already existing article for `%s`', 'wp_all_import_plugin'), $articleData['post_title']));
                         }
                         if (!$this->options['is_update_status']) {
                             // preserve status and trashed flag
                             $articleData['post_status'] = $post_to_update->post_status;
                             $logger and call_user_func($logger, sprintf(__('Preserve status of already existing article for `%s`', 'wp_all_import_plugin'), $articleData['post_title']));
                         }
                         if (!$this->options['is_update_content']) {
                             $articleData['post_content'] = $post_to_update->post_content;
                             $logger and call_user_func($logger, sprintf(__('Preserve content of already existing article for `%s`', 'wp_all_import_plugin'), $articleData['post_title']));
                         }
                         if (!$this->options['is_update_title']) {
                             $articleData['post_title'] = $post_to_update->post_title;
                             $logger and call_user_func($logger, sprintf(__('Preserve title of already existing article for `%s`', 'wp_all_import_plugin'), $articleData['post_title']));
                         }
                         if (!$this->options['is_update_slug']) {
                             $articleData['post_name'] = $post_to_update->post_name;
                             $logger and call_user_func($logger, sprintf(__('Preserve slug of already existing article for `%s`', 'wp_all_import_plugin'), $articleData['post_title']));
                         }
                         if (!$this->options['is_update_excerpt']) {
                             $articleData['post_excerpt'] = $post_to_update->post_excerpt;
                             $logger and call_user_func($logger, sprintf(__('Preserve excerpt of already existing article for `%s`', 'wp_all_import_plugin'), $articleData['post_title']));
                         }
                         if (!$this->options['is_update_menu_order']) {
                             $articleData['menu_order'] = $post_to_update->menu_order;
                             $logger and call_user_func($logger, sprintf(__('Preserve menu order of already existing article for `%s`', 'wp_all_import_plugin'), $articleData['post_title']));
                         }
                         if (!$this->options['is_update_parent']) {
                             $articleData['post_parent'] = $post_to_update->post_parent;
                             $logger and call_user_func($logger, sprintf(__('Preserve post parent of already existing article for `%s`', 'wp_all_import_plugin'), $articleData['post_title']));
                         }
                         if (!$this->options['is_update_author']) {
                             $articleData['post_author'] = $post_to_update->post_author;
                             $logger and call_user_func($logger, sprintf(__('Preserve post author of already existing article for `%s`', 'wp_all_import_plugin'), $articleData['post_title']));
                         }
                     } else {
                         if (!$this->options['is_update_first_name']) {
                             $articleData['first_name'] = $post_to_update->first_name;
                         }
                         if (!$this->options['is_update_last_name']) {
                             $articleData['last_name'] = $post_to_update->last_name;
                         }
                         if (!$this->options['is_update_role']) {
                             unset($articleData['role']);
                         }
                         if (!$this->options['is_update_nickname']) {
                             $articleData['nickname'] = get_user_meta($post_to_update->ID, 'nickname', true);
                         }
                         if (!$this->options['is_update_description']) {
                             $articleData['description'] = get_user_meta($post_to_update->ID, 'description', true);
                         }
                         if (!$this->options['is_update_login']) {
                             $articleData['user_login'] = $post_to_update->user_login;
                         }
                         if (!$this->options['is_update_password']) {
                             unset($articleData['user_pass']);
                         }
                         if (!$this->options['is_update_nicename']) {
                             $articleData['user_nicename'] = $post_to_update->user_nicename;
                         }
                         if (!$this->options['is_update_email']) {
                             $articleData['user_email'] = $post_to_update->user_email;
                         }
                         if (!$this->options['is_update_registered']) {
                             $articleData['user_registered'] = $post_to_update->user_registered;
                         }
                         if (!$this->options['is_update_display_name']) {
                             $articleData['display_name'] = $post_to_update->display_name;
                         }
                         if (!$this->options['is_update_url']) {
                             $articleData['user_url'] = $post_to_update->user_url;
                         }
                     }
                     $logger and call_user_func($logger, sprintf(__('Applying filter `pmxi_article_data` for `%s`', 'wp_all_import_plugin'), $articleData['post_title']));
                     $articleData = apply_filters('pmxi_article_data', $articleData, $this, $post_to_update);
                 }
                 if (!in_array($this->options['custom_type'], array('import_users'))) {
                     if ($this->options['update_all_data'] == 'yes' or $this->options['update_all_data'] == 'no' and $this->options['is_update_attachments']) {
                         $logger and call_user_func($logger, sprintf(__('Deleting attachments for `%s`', 'wp_all_import_plugin'), $articleData['post_title']));
                         wp_delete_attachments($articleData['ID'], true, 'files');
                     }
                     // handle obsolete attachments (i.e. delete or keep) according to import settings
                     if ($this->options['update_all_data'] == 'yes' or $this->options['update_all_data'] == 'no' and $this->options['is_update_images'] and $this->options['update_images_logic'] == "full_update") {
                         $logger and call_user_func($logger, sprintf(__('Deleting images for `%s`', 'wp_all_import_plugin'), $articleData['post_title']));
                         wp_delete_attachments($articleData['ID'], !$this->options['do_not_remove_images'], 'images');
                     }
                 }
             } elseif (!$postRecord->isEmpty()) {
                 // existing post not found though it's track was found... clear the leftover, plugin will continue to treat record as new
                 $postRecord->clear();
             }
             // no new records are created. it will only update posts it finds matching duplicates for
             if (!$this->options['create_new_records'] and empty($articleData['ID'])) {
                 if (!$postRecord->isEmpty()) {
                     $postRecord->set(array('iteration' => $this->iteration))->update();
                 }
                 $logger and call_user_func($logger, __('<b>SKIPPED</b>: by do not create new posts option.', 'wp_all_import_plugin'));
                 $logger and !$is_cron and PMXI_Plugin::$session->warnings++;
                 $logger and !$is_cron and PMXI_Plugin::$session->chunk_number++;
                 $skipped++;
                 $logger and !$is_cron and PMXI_Plugin::$session->save_data();
                 continue;
             }
             // cloak urls with `WP Wizard Cloak` if corresponding option is set
             if (!empty($this->options['is_cloak']) and class_exists('PMLC_Plugin')) {
                 if (preg_match_all('%<a\\s[^>]*href=(?(?=")"([^"]*)"|(?(?=\')\'([^\']*)\'|([^\\s>]*)))%is', $articleData['post_content'], $matches, PREG_PATTERN_ORDER)) {
                     $hrefs = array_unique(array_merge(array_filter($matches[1]), array_filter($matches[2]), array_filter($matches[3])));
                     foreach ($hrefs as $url) {
                         if (preg_match('%^\\w+://%i', $url)) {
                             // mask only links having protocol
                             // try to find matching cloaked link among already registered ones
                             $list = new PMLC_Link_List();
                             $linkTable = $list->getTable();
                             $rule = new PMLC_Rule_Record();
                             $ruleTable = $rule->getTable();
                             $dest = new PMLC_Destination_Record();
                             $destTable = $dest->getTable();
                             $list->join($ruleTable, "{$ruleTable}.link_id = {$linkTable}.id")->join($destTable, "{$destTable}.rule_id = {$ruleTable}.id")->setColumns("{$linkTable}.*")->getBy(array("{$linkTable}.destination_type =" => 'ONE_SET', "{$linkTable}.is_trashed =" => 0, "{$linkTable}.preset =" => '', "{$linkTable}.expire_on =" => '0000-00-00', "{$ruleTable}.type =" => 'ONE_SET', "{$destTable}.weight =" => 100, "{$destTable}.url LIKE" => $url), NULL, 1, 1)->convertRecords();
                             if ($list->count()) {
                                 // matching link found
                                 $link = $list[0];
                             } else {
                                 // register new cloaked link
                                 global $wpdb;
                                 $slug = max(intval($wpdb->get_var("SELECT MAX(CONVERT(name, SIGNED)) FROM {$linkTable}")), intval($wpdb->get_var("SELECT MAX(CONVERT(slug, SIGNED)) FROM {$linkTable}")), 0);
                                 $i = 0;
                                 do {
                                     is_int(++$slug) and $slug > 0 or $slug = 1;
                                     $is_slug_found = !intval($wpdb->get_var("SELECT COUNT(*) FROM {$linkTable} WHERE name = '{$slug}' OR slug = '{$slug}'"));
                                 } while (!$is_slug_found and $i++ < 100000);
                                 if ($is_slug_found) {
                                     $link = new PMLC_Link_Record(array('name' => strval($slug), 'slug' => strval($slug), 'header_tracking_code' => '', 'footer_tracking_code' => '', 'redirect_type' => '301', 'destination_type' => 'ONE_SET', 'preset' => '', 'forward_url_params' => 1, 'no_global_tracking_code' => 0, 'expire_on' => '0000-00-00', 'created_on' => date('Y-m-d H:i:s'), 'is_trashed' => 0));
                                     $link->insert();
                                     $rule = new PMLC_Rule_Record(array('link_id' => $link->id, 'type' => 'ONE_SET', 'rule' => ''));
                                     $rule->insert();
                                     $dest = new PMLC_Destination_Record(array('rule_id' => $rule->id, 'url' => $url, 'weight' => 100));
                                     $dest->insert();
                                 } else {
                                     $logger and call_user_func($logger, sprintf(__('<b>WARNING</b>: Unable to create cloaked link for %s', 'wp_all_import_plugin'), $url));
                                     $logger and !$is_cron and PMXI_Plugin::$session->warnings++;
                                     $link = NULL;
                                 }
                             }
                             if ($link) {
                                 // cloaked link is found or created for url
                                 $articleData['post_content'] = preg_replace('%' . preg_quote($url, '%') . '(?=([\\s\'"]|$))%i', $link->getUrl(), $articleData['post_content']);
                             }
                         }
                     }
                 }
             }
             // insert article being imported
             if ($this->options['is_fast_mode']) {
                 foreach (array('transition_post_status', 'save_post', 'pre_post_update', 'add_attachment', 'edit_attachment', 'edit_post', 'post_updated', 'wp_insert_post', 'save_post_' . $post_type[$i]) as $act) {
                     remove_all_actions($act);
                 }
             }
             if (!in_array($this->options['custom_type'], array('import_users'))) {
                 if (empty($articleData['ID'])) {
                     $logger and call_user_func($logger, sprintf(__('<b>CREATING</b> `%s` `%s`', 'wp_all_import_plugin'), $articleData['post_title'], $custom_type_details->labels->singular_name));
                 } else {
                     $logger and call_user_func($logger, sprintf(__('<b>UPDATING</b> `%s` `%s`', 'wp_all_import_plugin'), $articleData['post_title'], $custom_type_details->labels->singular_name));
                 }
                 $pid = wp_insert_post($articleData, true);
             } else {
                 $pid = empty($articleData['ID']) ? wp_insert_user($articleData) : wp_update_user($articleData);
                 $articleData['post_title'] = $articleData['user_login'];
             }
             if (is_wp_error($pid)) {
                 $logger and call_user_func($logger, __('<b>ERROR</b>', 'wp_all_import_plugin') . ': ' . $pid->get_error_message());
                 $logger and !$is_cron and PMXI_Plugin::$session->errors++;
                 $skipped++;
             } else {
                 if ("manual" != $this->options['duplicate_matching'] or empty($articleData['ID'])) {
                     // associate post with import
                     $postRecord->isEmpty() and $postRecord->set(array('post_id' => $pid, 'import_id' => $this->id, 'unique_key' => $unique_keys[$i], 'product_key' => ($post_type[$i] == "product" and PMXI_Admin_Addons::get_addon('PMWI_Plugin')) ? $addons_data['PMWI_Plugin']['single_product_ID'][$i] : ''))->insert();
                     $postRecord->set(array('iteration' => $this->iteration))->update();
                     $logger and call_user_func($logger, sprintf(__('Associate post `%s` with current import ...', 'wp_all_import_plugin'), $articleData['post_title']));
                 }
                 // [post format]
                 if (current_theme_supports('post-formats') && post_type_supports($post_type[$i], 'post-formats')) {
                     set_post_format($pid, "xpath" == $this->options['post_format'] ? $post_format[$i] : $this->options['post_format']);
                     $logger and call_user_func($logger, sprintf(__('Associate post `%s` with post format %s ...', 'wp_all_import_plugin'), $articleData['post_title'], "xpath" == $this->options['post_format'] ? $post_format[$i] : $this->options['post_format']));
                 }
                 // [/post format]
                 // [addons import]
                 // prepare data for import
                 $importData = array('pid' => $pid, 'i' => $i, 'import' => $this, 'articleData' => $articleData, 'xml' => $xml, 'is_cron' => $is_cron, 'logger' => $logger, 'xpath_prefix' => $xpath_prefix, 'post_type' => $post_type[$i]);
                 $import_functions = apply_filters('wp_all_import_addon_import', array());
                 // deligate operation to addons
                 foreach (PMXI_Admin_Addons::get_active_addons() as $class) {
                     if (class_exists($class)) {
                         if (method_exists($addons[$class], 'import')) {
                             $addons[$class]->import($importData);
                         }
                     } else {
                         if (!empty($import_functions[$class])) {
                             if (is_array($import_functions[$class]) and is_callable($import_functions[$class]) or !is_array($import_functions[$class]) and function_exists($import_functions[$class])) {
                                 call_user_func($import_functions[$class], $importData, $addons_data[$class]);
                             }
                         }
                     }
                 }
                 // [/addons import]
                 // Page Template
                 if ('page' == $articleData['post_type'] and wp_all_import_is_update_cf('_wp_page_template', $this->options) and (!empty($this->options['page_template']) or "no" == $this->options['is_multiple_page_template'])) {
                     update_post_meta($pid, '_wp_page_template', "no" == $this->options['is_multiple_page_template'] ? $page_template[$i] : $this->options['page_template']);
                 }
                 // [featured image]
                 $is_allow_import_images = apply_filters('wp_all_import_is_allow_import_images', false, $articleData['post_type']);
                 if (!empty($uploads) and false === $uploads['error'] and ($articleData['post_type'] == "product" and class_exists('PMWI_Plugin') or $is_allow_import_images) and (empty($articleData['ID']) or $this->options['update_all_data'] == "yes" or $this->options['update_all_data'] == "no" and $this->options['is_update_images'])) {
                     if (!empty($images_bundle)) {
                         $is_show_add_new_images = apply_filters('wp_all_import_is_show_add_new_images', true, $post_type[$i]);
                         foreach ($images_bundle as $slug => $bundle_data) {
                             $featured_images = $bundle_data['files'];
                             $option_slug = $slug == 'pmxi_gallery_image' ? '' : $slug;
                             if (!empty($featured_images[$i])) {
                                 $targetDir = $uploads['path'];
                                 $targetUrl = $uploads['url'];
                                 $logger and call_user_func($logger, __('<b>IMAGES:</b>', 'wp_all_import_plugin'));
                                 if (!@is_writable($targetDir)) {
                                     $logger and call_user_func($logger, sprintf(__('<b>ERROR</b>: Target directory %s is not writable', 'wp_all_import_plugin'), $targetDir));
                                 } else {
                                     require_once ABSPATH . 'wp-admin/includes/image.php';
                                     $success_images = false;
                                     $gallery_attachment_ids = array();
                                     $imgs = array();
                                     $featured_delim = "yes" == $this->options[$option_slug . 'download_images'] ? $this->options[$option_slug . 'download_featured_delim'] : $this->options[$option_slug . 'featured_delim'];
                                     $line_imgs = explode("\n", $featured_images[$i]);
                                     if (!empty($line_imgs)) {
                                         foreach ($line_imgs as $line_img) {
                                             $imgs = array_merge($imgs, !empty($featured_delim) ? str_getcsv($line_img, $featured_delim) : array($line_img));
                                         }
                                     }
                                     // keep existing and add newest images
                                     if (!empty($articleData['ID']) and $this->options['is_update_images'] and $this->options['update_images_logic'] == "add_new" and $this->options['update_all_data'] == "no" and $is_show_add_new_images) {
                                         $logger and call_user_func($logger, __('- Keep existing and add newest images ...', 'wp_all_import_plugin'));
                                         $attachment_imgs = get_attached_media('image', $pid);
                                         if ($post_type[$i] == "product") {
                                             $gallery_attachment_ids = array_filter(explode(",", get_post_meta($pid, '_product_image_gallery', true)));
                                         }
                                         if ($attachment_imgs) {
                                             foreach ($attachment_imgs as $attachment_img) {
                                                 $post_thumbnail_id = get_post_thumbnail_id($pid);
                                                 if (empty($post_thumbnail_id) and $this->options[$option_slug . 'is_featured']) {
                                                     set_post_thumbnail($pid, $attachment_img->ID);
                                                 } elseif (!in_array($attachment_img->ID, $gallery_attachment_ids) and $post_thumbnail_id != $attachment_img->ID) {
                                                     $gallery_attachment_ids[] = $attachment_img->ID;
                                                 }
                                             }
                                             $success_images = true;
                                         }
                                         if (!empty($gallery_attachment_ids)) {
                                             foreach ($gallery_attachment_ids as $aid) {
                                                 do_action($slug, $pid, $aid, wp_get_attachment_url($aid), 'update_images');
                                             }
                                         }
                                     }
                                     if (!empty($imgs)) {
                                         if ($this->options[$option_slug . 'set_image_meta_title'] and !empty($image_meta_titles_bundle[$slug])) {
                                             $img_titles = array();
                                             $line_img_titles = explode("\n", $image_meta_titles_bundle[$slug][$i]);
                                             if (!empty($line_img_titles)) {
                                                 foreach ($line_img_titles as $line_img_title) {
                                                     $img_titles = array_merge($img_titles, !empty($this->options[$option_slug . 'image_meta_title_delim']) ? str_getcsv($line_img_title, $this->options[$option_slug . 'image_meta_title_delim']) : array($line_img_title));
                                                 }
                                             }
                                         }
                                         if ($this->options[$option_slug . 'set_image_meta_caption'] and !empty($image_meta_captions_bundle[$slug])) {
                                             $img_captions = array();
                                             $line_img_captions = explode("\n", $image_meta_captions_bundle[$slug][$i]);
                                             if (!empty($line_img_captions)) {
                                                 foreach ($line_img_captions as $line_img_caption) {
                                                     $img_captions = array_merge($img_captions, !empty($this->options[$option_slug . 'image_meta_caption_delim']) ? str_getcsv($line_img_caption, $this->options[$option_slug . 'image_meta_caption_delim']) : array($line_img_caption));
                                                 }
                                             }
                                         }
                                         if ($this->options[$option_slug . 'set_image_meta_alt'] and !empty($image_meta_alts_bundle[$slug])) {
                                             $img_alts = array();
                                             $line_img_alts = explode("\n", $image_meta_alts_bundle[$slug][$i]);
                                             if (!empty($line_img_alts)) {
                                                 foreach ($line_img_alts as $line_img_alt) {
                                                     $img_alts = array_merge($img_alts, !empty($this->options[$option_slug . 'image_meta_alt_delim']) ? str_getcsv($line_img_alt, $this->options[$option_slug . 'image_meta_alt_delim']) : array($line_img_alt));
                                                 }
                                             }
                                         }
                                         if ($this->options[$option_slug . 'set_image_meta_description'] and !empty($image_meta_descriptions_bundle[$slug])) {
                                             $img_descriptions = array();
                                             $line_img_descriptions = explode("\n", $image_meta_descriptions_bundle[$slug][$i]);
                                             if (!empty($line_img_descriptions)) {
                                                 foreach ($line_img_descriptions as $line_img_description) {
                                                     $img_descriptions = array_merge($img_descriptions, !empty($this->options[$option_slug . 'image_meta_description_delim']) ? str_getcsv($line_img_description, $this->options[$option_slug . 'image_meta_description_delim']) : array($line_img_description));
                                                 }
                                             }
                                         }
                                         $is_keep_existing_images = (!empty($articleData['ID']) and $this->options['is_update_images'] and $this->options['update_images_logic'] == "add_new" and $this->options['update_all_data'] == "no" and $is_show_add_new_images);
                                         foreach ($imgs as $k => $img_url) {
                                             if (empty($img_url)) {
                                                 continue;
                                             }
                                             $attid = false;
                                             $attch = null;
                                             $url = str_replace(" ", "%20", trim($img_url));
                                             $bn = basename($url);
                                             if ("yes" == $this->options[$option_slug . 'download_images'] and !empty($auto_extensions_bundle[$slug][$i]) and preg_match('%^(jpg|jpeg|png|gif)$%i', $auto_extensions_bundle[$slug][$i])) {
                                                 $img_ext = $auto_extensions_bundle[$slug][$i];
                                             } else {
                                                 $img_ext = pmxi_getExtensionFromStr($url);
                                                 $default_extension = pmxi_getExtension($bn);
                                                 if ($img_ext == "") {
                                                     $img_ext = pmxi_get_remote_image_ext($url);
                                                 }
                                             }
                                             $logger and call_user_func($logger, sprintf(__('- Importing image `%s` for `%s` ...', 'wp_all_import_plugin'), $img_url, $articleData['post_title']));
                                             // generate local file name
                                             $image_name = urldecode(($this->options[$option_slug . 'auto_rename_images'] and !empty($auto_rename_images_bundle[$slug][$i])) ? sanitize_file_name($img_ext ? str_replace("." . $default_extension, "", $auto_rename_images_bundle[$slug][$i]) : $auto_rename_images_bundle[$slug][$i]) : sanitize_file_name($img_ext ? str_replace("." . $default_extension, "", $bn) : $bn)) . ("" != $img_ext ? '.' . $img_ext : '');
                                             // if wizard store image data to custom field
                                             $create_image = false;
                                             $download_image = true;
                                             $wp_filetype = false;
                                             if ($bundle_data['type'] == 'images' and base64_decode($url, true) !== false) {
                                                 $img = @imagecreatefromstring(base64_decode($url));
                                                 if ($img) {
                                                     $logger and call_user_func($logger, __('- Founded base64_encoded image', 'wp_all_import_plugin'));
                                                     $image_filename = md5(time()) . '.jpg';
                                                     $image_filepath = $targetDir . '/' . $image_filename;
                                                     imagejpeg($img, $image_filepath);
                                                     if (!($image_info = @getimagesize($image_filepath)) or !in_array($image_info[2], array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG))) {
                                                         $logger and call_user_func($logger, sprintf(__('- <b>WARNING</b>: File %s is not a valid image and cannot be set as featured one', 'wp_all_import_plugin'), $image_filepath));
                                                         $logger and !$is_cron and PMXI_Plugin::$session->warnings++;
                                                     } else {
                                                         $create_image = true;
                                                     }
                                                 }
                                             } else {
                                                 $image_filename = wp_unique_filename($targetDir, $image_name);
                                                 $image_filepath = $targetDir . '/' . $image_filename;
                                                 // keep existing and add newest images
                                                 if ($is_keep_existing_images) {
                                                     $attch = $this->wpdb->get_row($this->wpdb->prepare("SELECT * FROM " . $this->wpdb->posts . " WHERE (post_title = %s OR post_title = %s OR post_name = %s) AND post_type = %s AND post_parent = %d;", $image_name, preg_replace('/\\.[^.\\s]{3,4}$/', '', $image_name), sanitize_title($image_name), "attachment", $pid));
                                                     if ($attch != null) {
                                                         $post_thumbnail_id = get_post_thumbnail_id($pid);
                                                         if ($post_thumbnail_id == $attch->ID or in_array($attch->ID, $gallery_attachment_ids)) {
                                                             continue;
                                                         }
                                                     } elseif (file_exists($targetDir . '/' . $image_name)) {
                                                         if ($bundle_data['type'] == 'images' and $img_meta = wp_read_image_metadata($targetDir . '/' . $image_name)) {
                                                             if (trim($img_meta['title']) && !is_numeric(sanitize_title($img_meta['title']))) {
                                                                 $img_title = $img_meta['title'];
                                                                 $attch = $this->wpdb->get_row($this->wpdb->prepare("SELECT * FROM " . $this->wpdb->posts . " WHERE post_title = %s AND post_type = %s AND post_parent = %d;", $img_title, "attachment", $pid));
                                                                 if ($attch != null) {
                                                                     $post_thumbnail_id = get_post_thumbnail_id($pid);
                                                                     if ($post_thumbnail_id == $attch->ID or in_array($attch->ID, $gallery_attachment_ids)) {
                                                                         continue;
                                                                     }
                                                                 }
                                                             }
                                                         }
                                                     }
                                                 }
                                                 // search existing attachment
                                                 if ($this->options[$option_slug . 'search_existing_images']) {
                                                     $image_filename = $image_name;
                                                     $attch = $this->wpdb->get_row($this->wpdb->prepare("SELECT * FROM " . $this->wpdb->posts . " WHERE (post_title = %s OR post_title = %s OR post_name = %s) AND post_type = %s;", $image_name, preg_replace('/\\.[^.\\s]{3,4}$/', '', $image_name), sanitize_title($image_name), "attachment"));
                                                     if ($attch != null) {
                                                         $download_image = false;
                                                         $attid = $attch->ID;
                                                     } elseif (@file_exists($targetDir . '/' . $image_name)) {
                                                         if ($bundle_data['type'] == 'images' and $img_meta = wp_read_image_metadata($targetDir . '/' . $image_name)) {
                                                             if (trim($img_meta['title']) && !is_numeric(sanitize_title($img_meta['title']))) {
                                                                 $img_title = $img_meta['title'];
                                                                 $attch = $this->wpdb->get_row($this->wpdb->prepare("SELECT * FROM " . $this->wpdb->posts . " WHERE post_title = %s AND post_type = %s AND post_parent = %d;", $img_title, "attachment", $pid));
                                                                 if ($attch != null) {
                                                                     $download_image = false;
                                                                     $attid = $attch->ID;
                                                                 }
                                                             }
                                                         }
                                                     }
                                                 }
                                                 if ($download_image) {
                                                     // do not download images
                                                     if ("yes" != $this->options[$option_slug . 'download_images']) {
                                                         $image_filename = $image_name;
                                                         $image_filepath = $targetDir . '/' . $image_filename;
                                                         $wpai_uploads = $uploads['basedir'] . DIRECTORY_SEPARATOR . PMXI_Plugin::FILES_DIRECTORY . DIRECTORY_SEPARATOR;
                                                         $wpai_image_path = $wpai_uploads . str_replace('%20', ' ', $url);
                                                         $logger and call_user_func($logger, sprintf(__('- Searching for existing image `%s` in `%s` folder', 'wp_all_import_plugin'), $wpai_image_path, $wpai_uploads));
                                                         if (@file_exists($wpai_image_path) and @copy($wpai_image_path, $image_filepath)) {
                                                             $download_image = false;
                                                             // valdate import attachments
                                                             if ($bundle_data['type'] == 'files') {
                                                                 if (!($wp_filetype = wp_check_filetype(basename($image_filepath), null))) {
                                                                     $logger and call_user_func($logger, sprintf(__('- <b>WARNING</b>: Can\'t detect attachment file type %s', 'wp_all_import_plugin'), trim($image_filepath)));
                                                                     $logger and !$is_cron and PMXI_Plugin::$session->warnings++;
                                                                     @unlink($image_filepath);
                                                                 } else {
                                                                     $create_image = true;
                                                                     $logger and call_user_func($logger, sprintf(__('- File `%s` has been successfully founded', 'wp_all_import_plugin'), $wpai_image_path));
                                                                 }
                                                             } elseif ($bundle_data['type'] == 'images') {
                                                                 if (!($image_info = @getimagesize($image_filepath)) or !in_array($image_info[2], array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG))) {
                                                                     $logger and call_user_func($logger, sprintf(__('- <b>WARNING</b>: File %s is not a valid image and cannot be set as featured one', 'wp_all_import_plugin'), $image_filepath));
                                                                     $logger and !$is_cron and PMXI_Plugin::$session->warnings++;
                                                                     @unlink($image_filepath);
                                                                 } else {
                                                                     $create_image = true;
                                                                     $logger and call_user_func($logger, sprintf(__('- Image `%s` has been successfully founded', 'wp_all_import_plugin'), $wpai_image_path));
                                                                 }
                                                             }
                                                         }
                                                     } else {
                                                         $logger and call_user_func($logger, sprintf(__('- Downloading image from `%s`', 'wp_all_import_plugin'), $url));
                                                         $request = get_file_curl($url, $image_filepath);
                                                         if ((is_wp_error($request) or $request === false) and !@file_put_contents($image_filepath, @file_get_contents($url))) {
                                                             @unlink($image_filepath);
                                                             // delete file since failed upload may result in empty file created
                                                         } else {
                                                             if ($bundle_data['type'] == 'images') {
                                                                 if ($image_info = @getimagesize($image_filepath) and in_array($image_info[2], array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG))) {
                                                                     $create_image = true;
                                                                     $logger and call_user_func($logger, sprintf(__('- Image `%s` has been successfully downloaded', 'wp_all_import_plugin'), $url));
                                                                 }
                                                             } elseif ($bundle_data['type'] == 'files') {
                                                                 if ($wp_filetype = wp_check_filetype(basename($image_filepath), null)) {
                                                                     $create_image = true;
                                                                     $logger and call_user_func($logger, sprintf(__('- File `%s` has been successfully downloaded', 'wp_all_import_plugin'), $url));
                                                                 }
                                                             }
                                                         }
                                                         if (!$create_image) {
                                                             $url = str_replace(" ", "%20", trim(pmxi_convert_encoding($img_url)));
                                                             $request = get_file_curl($url, $image_filepath);
                                                             if ((is_wp_error($request) or $request === false) and !@file_put_contents($image_filepath, @file_get_contents($url))) {
                                                                 $logger and call_user_func($logger, sprintf(__('- <b>WARNING</b>: File %s cannot be saved locally as %s', 'wp_all_import_plugin'), $url, $image_filepath));
                                                                 $logger and !$is_cron and PMXI_Plugin::$session->warnings++;
                                                                 @unlink($image_filepath);
                                                                 // delete file since failed upload may result in empty file created
                                                             } else {
                                                                 if ($bundle_data['type'] == 'images') {
                                                                     if (!($image_info = @getimagesize($image_filepath)) or !in_array($image_info[2], array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG))) {
                                                                         $logger and call_user_func($logger, sprintf(__('- <b>WARNING</b>: File %s is not a valid image and cannot be set as featured one', 'wp_all_import_plugin'), $url));
                                                                         $logger and !$is_cron and PMXI_Plugin::$session->warnings++;
                                                                         @unlink($image_filepath);
                                                                     } else {
                                                                         $create_image = true;
                                                                         $logger and call_user_func($logger, sprintf(__('- Image `%s` has been successfully downloaded', 'wp_all_import_plugin'), $url));
                                                                     }
                                                                 } elseif ($bundle_data['type'] == 'files') {
                                                                     if (!($wp_filetype = wp_check_filetype(basename($image_filepath), null))) {
                                                                         $logger and call_user_func($logger, sprintf(__('- <b>WARNING</b>: Can\'t detect attachment file type %s', 'wp_all_import_plugin'), trim($url)));
                                                                         $logger and !$is_cron and PMXI_Plugin::$session->warnings++;
                                                                         @unlink($image_filepath);
                                                                     } else {
                                                                         $create_image = true;
                                                                         $logger and call_user_func($logger, sprintf(__('- File `%s` has been successfully founded', 'wp_all_import_plugin'), $url));
                                                                     }
                                                                 }
                                                             }
                                                         }
                                                     }
                                                 }
                                             }
                                             if ($create_image) {
                                                 $logger and call_user_func($logger, sprintf(__('- Creating an attachment for image `%s`', 'wp_all_import_plugin'), $targetUrl . '/' . $image_filename));
                                                 $attachment = array('post_mime_type' => $bundle_data['type'] == 'images' ? image_type_to_mime_type($image_info[2]) : $wp_filetype['type'], 'guid' => $targetUrl . '/' . $image_filename, 'post_title' => $image_name, 'post_content' => '', 'post_author' => $post_author[$i]);
                                                 if ($bundle_data['type'] == 'images' and $image_meta = wp_read_image_metadata($image_filepath)) {
                                                     if (trim($image_meta['title']) && !is_numeric(sanitize_title($image_meta['title']))) {
                                                         $attachment['post_title'] = $image_meta['title'];
                                                     }
                                                     if (trim($image_meta['caption'])) {
                                                         $attachment['post_content'] = $image_meta['caption'];
                                                     }
                                                 }
                                                 $attid = wp_insert_attachment($attachment, $image_filepath, $pid);
                                                 if (is_wp_error($attid)) {
                                                     $logger and call_user_func($logger, __('- <b>WARNING</b>', 'wp_all_import_plugin') . ': ' . $attid->get_error_message());
                                                     $logger and !$is_cron and PMXI_Plugin::$session->warnings++;
                                                 } else {
                                                     // you must first include the image.php file
                                                     // for the function wp_generate_attachment_metadata() to work
                                                     require_once ABSPATH . 'wp-admin/includes/image.php';
                                                     wp_update_attachment_metadata($attid, wp_generate_attachment_metadata($attid, $image_filepath));
                                                     $update_attachment_meta = array();
                                                     if ($this->options[$option_slug . 'set_image_meta_title'] and !empty($img_titles[$k])) {
                                                         $update_attachment_meta['post_title'] = $img_titles[$k];
                                                     }
                                                     if ($this->options[$option_slug . 'set_image_meta_caption'] and !empty($img_captions[$k])) {
                                                         $update_attachment_meta['post_excerpt'] = $img_captions[$k];
                                                     }
                                                     if ($this->options[$option_slug . 'set_image_meta_description'] and !empty($img_descriptions[$k])) {
                                                         $update_attachment_meta['post_content'] = $img_descriptions[$k];
                                                     }
                                                     if ($this->options[$option_slug . 'set_image_meta_alt'] and !empty($img_alts[$k])) {
                                                         update_post_meta($attid, '_wp_attachment_image_alt', $img_alts[$k]);
                                                     }
                                                     if (!empty($update_attachment_meta)) {
                                                         $this->wpdb->update($this->wpdb->posts, $update_attachment_meta, array('ID' => $attid));
                                                     }
                                                 }
                                             }
                                             if ($attid) {
                                                 if ($attch != null and empty($attch->post_parent)) {
                                                     wp_update_post(array('ID' => $attch->ID, 'post_parent' => $pid));
                                                 }
                                                 $logger and call_user_func($logger, __('- <b>ACTION</b>: ' . $slug, 'wp_all_import_plugin'));
                                                 do_action($slug, $pid, $attid, $image_filepath, $is_keep_existing_images ? 'add_images' : 'update_images');
                                                 $success_images = true;
                                                 $post_thumbnail_id = get_post_thumbnail_id($pid);
                                                 if ($bundle_data['type'] == 'images' and empty($post_thumbnail_id) and $this->options[$option_slug . 'is_featured']) {
                                                     set_post_thumbnail($pid, $attid);
                                                 } elseif (!in_array($attid, $gallery_attachment_ids) and $post_thumbnail_id != $attid) {
                                                     $gallery_attachment_ids[] = $attid;
                                                 }
                                                 $logger and call_user_func($logger, sprintf(__('- Attachment has been successfully created for image `%s`', 'wp_all_import_plugin'), $targetUrl . '/' . $image_filename));
                                             }
                                         }
                                     }
                                     // Set product gallery images
                                     if ($post_type[$i] == "product") {
                                         update_post_meta($pid, '_product_image_gallery', !empty($gallery_attachment_ids) ? implode(',', $gallery_attachment_ids) : '');
                                     }
                                     // Create entry as Draft if no images are downloaded successfully
                                     if (!$success_images and "yes" == $this->options[$option_slug . 'create_draft']) {
                                         $this->wpdb->update($this->wpdb->posts, array('post_status' => 'draft'), array('ID' => $pid));
                                         $logger and call_user_func($logger, sprintf(__('- Post `%s` saved as Draft, because no images are downloaded successfully', 'wp_all_import_plugin'), $articleData['post_title']));
                                     }
                                 }
                             } else {
                                 // Create entry as Draft if no images are downloaded successfully
                                 if ("yes" == $this->options[$option_slug . 'create_draft']) {
                                     $this->wpdb->update($this->wpdb->posts, array('post_status' => 'draft'), array('ID' => $pid));
                                     $logger and call_user_func($logger, sprintf(__('Post `%s` saved as Draft, because no images are downloaded successfully', 'wp_all_import_plugin'), $articleData['post_title']));
                                 }
                             }
                         }
                     }
                 } else {
                     if (!empty($images_bundle)) {
                         foreach ($images_bundle as $slug => $bundle_data) {
                             if (!empty($bundle_data['images'][$i])) {
                                 $imgs = array();
                                 $featured_delim = "yes" == $this->options[$option_slug . 'download_images'] ? $this->options[$option_slug . 'download_featured_delim'] : $this->options[$option_slug . 'featured_delim'];
                                 $line_imgs = explode("\n", $bundle_data['images'][$i]);
                                 if (!empty($line_imgs)) {
                                     foreach ($line_imgs as $line_img) {
                                         $imgs = array_merge($imgs, !empty($featured_delim) ? str_getcsv($line_img, $featured_delim) : array($line_img));
                                     }
                                 }
                                 foreach ($imgs as $img) {
                                     do_action($slug, $pid, false, $img, false);
                                 }
                             }
                         }
                     }
                 }
                 // [/featured image]
                 // [attachments]
                 if (!empty($uploads) and false === $uploads['error'] and !empty($attachments[$i]) and (empty($articleData['ID']) or $this->options['update_all_data'] == "yes" or $this->options['update_all_data'] == "no" and $this->options['is_update_attachments'])) {
                     $targetDir = $uploads['path'];
                     $targetUrl = $uploads['url'];
                     $logger and call_user_func($logger, __('<b>ATTACHMENTS:</b>', 'wp_all_import_plugin'));
                     if (!@is_writable($targetDir)) {
                         $logger and call_user_func($logger, sprintf(__('- <b>ERROR</b>: Target directory %s is not writable', 'wp_all_import_plugin'), trim($targetDir)));
                     } else {
                         // you must first include the image.php file
                         // for the function wp_generate_attachment_metadata() to work
                         require_once ABSPATH . 'wp-admin/includes/image.php';
                         if (!is_array($attachments[$i])) {
                             $attachments[$i] = array($attachments[$i]);
                         }
                         $logger and call_user_func($logger, sprintf(__('- Importing attachments for `%s` ...', 'wp_all_import_plugin'), $articleData['post_title']));
                         foreach ($attachments[$i] as $attachment) {
                             if ("" == $attachment) {
                                 continue;
                             }
                             $atchs = str_getcsv($attachment, $this->options['atch_delim']);
                             if (!empty($atchs)) {
                                 foreach ($atchs as $atch_url) {
                                     if (empty($atch_url)) {
                                         continue;
                                     }
                                     $download_file = true;
                                     $atch_url = str_replace(" ", "%20", trim($atch_url));
                                     $attachment_filename = urldecode(basename(parse_url(trim($atch_url), PHP_URL_PATH)));
                                     $attachment_filepath = $targetDir . '/' . sanitize_file_name($attachment_filename);
                                     if ($this->options['is_search_existing_attach']) {
                                         // search existing attachment
                                         $attch = $this->wpdb->get_row($this->wpdb->prepare("SELECT * FROM " . $this->wpdb->posts . " WHERE (post_title = %s OR post_title = %s OR post_name = %s OR post_name = %s) AND post_type = %s;", $attachment_filename, preg_replace('/\\.[^.\\s]{3,4}$/', '', $attachment_filename), sanitize_title($attachment_filename), sanitize_title(preg_replace('/\\.[^.\\s]{3,4}$/', '', $attachment_filename)), "attachment"));
                                         if ($attch != null) {
                                             $download_file = false;
                                             $attach_id = $attch->ID;
                                         }
                                     }
                                     if ($download_file) {
                                         $attachment_filename = wp_unique_filename($targetDir, $attachment_filename);
                                         $attachment_filepath = $targetDir . '/' . sanitize_file_name($attachment_filename);
                                         $logger and call_user_func($logger, sprintf(__('- Filename for attachment was generated as %s', 'wp_all_import_plugin'), $attachment_filename));
                                         $request = get_file_curl(trim($atch_url), $attachment_filepath);
                                         if ((is_wp_error($request) or $request === false) and !@file_put_contents($attachment_filepath, @file_get_contents(trim($atch_url)))) {
                                             $logger and call_user_func($logger, sprintf(__('- <b>WARNING</b>: Attachment file %s cannot be saved locally as %s', 'wp_all_import_plugin'), trim($atch_url), $attachment_filepath));
                                             is_wp_error($request) and $logger and call_user_func($logger, sprintf(__('- <b>WP Error</b>: %s', 'wp_all_import_plugin'), $request->get_error_message()));
                                             $logger and !$is_cron and PMXI_Plugin::$session->warnings++;
                                             unlink($attachment_filepath);
                                             // delete file since failed upload may result in empty file created
                                         } elseif (!($wp_filetype = wp_check_filetype(basename($attachment_filename), null))) {
                                             $logger and call_user_func($logger, sprintf(__('- <b>WARNING</b>: Can\'t detect attachment file type %s', 'wp_all_import_plugin'), trim($atch_url)));
                                             $logger and !$is_cron and PMXI_Plugin::$session->warnings++;
                                         } else {
                                             $logger and call_user_func($logger, sprintf(__('- File %s has been successfully downloaded', 'wp_all_import_plugin'), $atch_url));
                                             $attachment_data = array('guid' => $targetUrl . '/' . basename($attachment_filepath), 'post_mime_type' => $wp_filetype['type'], 'post_title' => preg_replace('/\\.[^.]+$/', '', basename($attachment_filepath)), 'post_content' => '', 'post_status' => 'inherit', 'post_author' => $post_author[$i]);
                                             $attach_id = wp_insert_attachment($attachment_data, $attachment_filepath, $pid);
                                             if (is_wp_error($attach_id)) {
                                                 $logger and call_user_func($logger, __('- <b>WARNING</b>', 'wp_all_import_plugin') . ': ' . $pid->get_error_message());
                                                 $logger and !$is_cron and PMXI_Plugin::$session->warnings++;
                                             } else {
                                                 wp_update_attachment_metadata($attach_id, wp_generate_attachment_metadata($attach_id, $attachment_filepath));
                                                 $logger and call_user_func($logger, sprintf(__('- Attachment has been successfully created for post `%s`', 'wp_all_import_plugin'), $articleData['post_title']));
                                                 $logger and call_user_func($logger, __('- <b>ACTION</b>: pmxi_attachment_uploaded', 'wp_all_import_plugin'));
                                                 do_action('pmxi_attachment_uploaded', $pid, $attach_id, $attachment_filepath);
                                             }
                                         }
                                     } else {
                                         $logger and call_user_func($logger, __('- <b>ACTION</b>: pmxi_attachment_uploaded', 'wp_all_import_plugin'));
                                         do_action('pmxi_attachment_uploaded', $pid, $attach_id, $attachment_filepath);
                                     }
                                 }
                             }
                         }
                     }
                 }
                 // [/attachments]
                 // [custom taxonomies]
                 if (!empty($taxonomies)) {
                     $logger and call_user_func($logger, __('<b>TAXONOMIES:</b>', 'wp_all_import_plugin'));
                     foreach ($taxonomies as $tx_name => $txes) {
                         // Skip updating product attributes
                         if (PMXI_Admin_Addons::get_addon('PMWI_Plugin') and strpos($tx_name, "pa_") === 0) {
                             continue;
                         }
                         if (empty($articleData['ID']) or $this->options['update_all_data'] == "yes" or $this->options['update_all_data'] == "no" and $this->options['is_update_categories']) {
                             $logger and call_user_func($logger, sprintf(__('- Importing taxonomy `%s` ...', 'wp_all_import_plugin'), $tx_name));
                             if (!empty($this->options['tax_logic'][$tx_name]) and $this->options['tax_logic'][$tx_name] == 'hierarchical' and !empty($this->options['tax_hierarchical_logic'][$tx_name]) and $this->options['tax_hierarchical_logic'][$tx_name] == 'entire') {
                                 $logger and call_user_func($logger, sprintf(__('- Auto-nest enabled with separator `%s` ...', 'wp_all_import_plugin'), !empty($this->options['tax_hierarchical_delim'][$tx_name]) ? $this->options['tax_hierarchical_delim'][$tx_name] : ','));
                             }
                             if (!empty($articleData['ID'])) {
                                 if ($this->options['update_all_data'] == "no" and $this->options['update_categories_logic'] == "all_except" and !empty($this->options['taxonomies_list']) and is_array($this->options['taxonomies_list']) and in_array($tx_name, $this->options['taxonomies_list'])) {
                                     $logger and call_user_func($logger, sprintf(__('- %s %s `%s` has been skipped attempted to `Leave these taxonomies alone, update all others`...', 'wp_all_import_plugin'), $custom_type_details->labels->singular_name, $tx_name, $single_tax['name']));
                                     continue;
                                 }
                                 if ($this->options['update_all_data'] == "no" and $this->options['update_categories_logic'] == "only" and (!empty($this->options['taxonomies_list']) and is_array($this->options['taxonomies_list']) and !in_array($tx_name, $this->options['taxonomies_list']) or empty($this->options['taxonomies_list']))) {
                                     $logger and call_user_func($logger, sprintf(__('- %s %s `%s` has been skipped attempted to `Update only these taxonomies, leave the rest alone`...', 'wp_all_import_plugin'), $custom_type_details->labels->singular_name, $tx_name, $single_tax['name']));
                                     continue;
                                 }
                             }
                             $assign_taxes = array();
                             if ($this->options['update_categories_logic'] == "add_new" and !empty($existing_taxonomies[$tx_name][$i])) {
                                 $assign_taxes = $existing_taxonomies[$tx_name][$i];
                                 unset($existing_taxonomies[$tx_name][$i]);
                             } elseif (!empty($existing_taxonomies[$tx_name][$i])) {
                                 unset($existing_taxonomies[$tx_name][$i]);
                             }
                             // create term if not exists
                             if (!empty($txes[$i])) {
                                 foreach ($txes[$i] as $key => $single_tax) {
                                     $is_created_term = false;
                                     if (is_array($single_tax) and !empty($single_tax['name'])) {
                                         $parent_id = !empty($single_tax['parent']) ? pmxi_recursion_taxes($single_tax['parent'], $tx_name, $txes[$i], $key) : '';
                                         $term = empty($this->options['tax_is_full_search_' . $this->options['tax_logic'][$tx_name]][$tx_name]) ? term_exists($single_tax['name'], $tx_name, (int) $parent_id) : term_exists($single_tax['name'], $tx_name);
                                         if (empty($term) and !is_wp_error($term)) {
                                             $term = empty($this->options['tax_is_full_search_' . $this->options['tax_logic'][$tx_name]][$tx_name]) ? term_exists(htmlspecialchars($single_tax['name']), $tx_name, (int) $parent_id) : term_exists(htmlspecialchars($single_tax['name']), $tx_name);
                                             if (empty($term) and !is_wp_error($term)) {
                                                 $term_attr = array('parent' => !empty($parent_id) ? $parent_id : 0);
                                                 $term = wp_insert_term($single_tax['name'], $tx_name, $term_attr);
                                                 if (!is_wp_error($term)) {
                                                     $is_created_term = true;
                                                     if (empty($parent_id)) {
                                                         $logger and call_user_func($logger, sprintf(__('- Creating parent %s %s `%s` ...', 'wp_all_import_plugin'), $custom_type_details->labels->singular_name, $tx_name, $single_tax['name']));
                                                     } else {
                                                         $logger and call_user_func($logger, sprintf(__('- Creating child %s %s for %s named `%s` ...', 'wp_all_import_plugin'), $custom_type_details->labels->singular_name, $tx_name, is_array($single_tax['parent']) ? $single_tax['parent']['name'] : $single_tax['parent'], $single_tax['name']));
                                                     }
                                                 }
                                             }
                                         }
                                         if (is_wp_error($term)) {
                                             $logger and call_user_func($logger, sprintf(__('- <b>WARNING</b>: `%s`', 'wp_all_import_plugin'), $term->get_error_message()));
                                             $logger and !$is_cron and PMXI_Plugin::$session->warnings++;
                                         } elseif (!empty($term)) {
                                             $cat_id = $term['term_id'];
                                             if ($cat_id and $single_tax['assign']) {
                                                 $term = get_term_by('id', $cat_id, $tx_name);
                                                 if ($term->parent != '0' and !empty($this->options['tax_is_full_search_' . $this->options['tax_logic'][$tx_name]][$tx_name]) and empty($this->options['tax_assign_to_one_term_' . $this->options['tax_logic'][$tx_name]][$tx_name])) {
                                                     $parent_ids = wp_all_import_get_parent_terms($cat_id, $tx_name);
                                                     if (!empty($parent_ids)) {
                                                         foreach ($parent_ids as $p) {
                                                             if (!in_array($p, $assign_taxes)) {
                                                                 $assign_taxes[] = $p;
                                                             }
                                                         }
                                                     }
                                                 }
                                                 if (!in_array($term->term_taxonomy_id, $assign_taxes)) {
                                                     $assign_taxes[] = $term->term_taxonomy_id;
                                                 }
                                                 if (!$is_created_term) {
                                                     if (empty($parent_id)) {
                                                         $logger and call_user_func($logger, sprintf(__('- Attempted to create parent %s %s `%s`, duplicate detected. Importing %s to existing `%s` %s, ID %d, slug `%s` ...', 'wp_all_import_plugin'), $custom_type_details->labels->singular_name, $tx_name, $single_tax['name'], $custom_type_details->labels->singular_name, $term->name, $tx_name, $term->term_id, $term->slug));
                                                     } else {
                                                         $logger and call_user_func($logger, sprintf(__('- Attempted to create child %s %s `%s`, duplicate detected. Importing %s to existing `%s` %s, ID %d, slug `%s` ...', 'wp_all_import_plugin'), $custom_type_details->labels->singular_name, $tx_name, $single_tax['name'], $custom_type_details->labels->singular_name, $term->name, $tx_name, $term->term_id, $term->slug));
                                                     }
                                                 }
                                             }
                                         }
                                     }
                                 }
                             }
                             // associate taxes with post
                             $this->associate_terms($pid, empty($assign_taxes) ? false : $assign_taxes, $tx_name, $logger, $is_cron);
                         } else {
                             $logger and call_user_func($logger, sprintf(__('- %s %s `%s` has been skipped attempted to `Do not update Taxonomies (incl. Categories and Tags)`...', 'wp_all_import_plugin'), $custom_type_details->labels->singular_name, $tx_name, $single_tax['name']));
                         }
                     }
                     if ($this->options['update_all_data'] == "no" and ($this->options['is_update_categories'] and $this->options['update_categories_logic'] != 'full_update' or !$this->options['is_update_categories'] and (is_object_in_taxonomy($post_type[$i], 'category') or is_object_in_taxonomy($post_type[$i], 'post_tag')))) {
                         if (!empty($existing_taxonomies)) {
                             foreach ($existing_taxonomies as $tx_name => $txes) {
                                 // Skip updating product attributes
                                 if (PMXI_Admin_Addons::get_addon('PMWI_Plugin') and strpos($tx_name, "pa_") === 0) {
                                     continue;
                                 }
                                 if (!empty($txes[$i])) {
                                     $this->associate_terms($pid, $txes[$i], $tx_name, $logger, $is_cron);
                                 }
                             }
                         }
                     }
                 }
                 // [/custom taxonomies]
                 if (empty($articleData['ID'])) {
                     $logger and call_user_func($logger, sprintf(__('<b>CREATED</b> `%s` `%s` (ID: %s)', 'wp_all_import_plugin'), $articleData['post_title'], $custom_type_details->labels->singular_name, $pid));
                 } else {
                     $logger and call_user_func($logger, sprintf(__('<b>UPDATED</b> `%s` `%s` (ID: %s)', 'wp_all_import_plugin'), $articleData['post_title'], $custom_type_details->labels->singular_name, $pid));
                 }
                 // fire important hooks after custom fields are added
                 if (!$this->options['is_fast_mode'] and $this->options['custom_type'] != 'import_users') {
                     $post_object = get_post($pid);
                     $is_update = !empty($articleData['ID']);
                     do_action("save_post_" . $articleData['post_type'], $pid, $post_object, $is_update);
                     do_action('save_post', $pid, $post_object, $is_update);
                     do_action('wp_insert_post', $pid, $post_object, $is_update);
                 }
                 // [addons import]
                 // prepare data for import
                 $importData = array('pid' => $pid, 'import' => $this, 'logger' => $logger);
                 $saved_functions = apply_filters('wp_all_import_addon_saved_post', array());
                 // deligate operation to addons
                 foreach (PMXI_Admin_Addons::get_active_addons() as $class) {
                     if (class_exists($class)) {
                         if (method_exists($addons[$class], 'saved_post')) {
                             $addons[$class]->saved_post($importData);
                         }
                     } else {
                         if (!empty($saved_functions[$class])) {
                             if (is_array($saved_functions[$class]) and is_callable($saved_functions[$class]) or !is_array($saved_functions[$class]) and function_exists($saved_functions[$class])) {
                                 call_user_func($saved_functions[$class], $importData);
                             }
                         }
                     }
                 }
                 // [/addons import]
                 $logger and call_user_func($logger, __('<b>ACTION</b>: pmxi_saved_post', 'wp_all_import_plugin'));
                 do_action('pmxi_saved_post', $pid, $rootNodes[$i]);
                 // hook that was triggered immediately after post saved
                 if (empty($articleData['ID'])) {
                     $created++;
                 } else {
                     $updated++;
                 }
                 if (!$is_cron and "default" == $this->options['import_processing']) {
                     $processed_records = $created + $updated + $skipped;
                     $logger and call_user_func($logger, sprintf(__('<span class="processing_info"><span class="created_count">%s</span><span class="updated_count">%s</span><span class="percents_count">%s</span></span>', 'wp_all_import_plugin'), $created, $updated, ceil($processed_records / $this->count * 100)));
                 }
             }
             $logger and call_user_func($logger, __('<b>ACTION</b>: pmxi_after_post_import', 'wp_all_import_plugin'));
             do_action('pmxi_after_post_import', $this->id);
             $logger and !$is_cron and PMXI_Plugin::$session->chunk_number++;
         }
         wp_cache_flush();
         $this->set(array('imported' => $created + $updated, 'created' => $created, 'updated' => $updated, 'skipped' => $skipped, 'last_activity' => date('Y-m-d H:i:s')))->update();
         if (!$is_cron) {
             PMXI_Plugin::$session->save_data();
             $records_count = $this->created + $this->updated + $this->skipped;
             $is_import_complete = $records_count == $this->count;
             // Delete posts that are no longer present in your file
             if ($is_import_complete and !empty($this->options['is_delete_missing']) and $this->options['duplicate_matching'] == 'auto') {
                 $logger and call_user_func($logger, __('Removing previously imported posts which are no longer actual...', 'wp_all_import_plugin'));
                 $postList = new PMXI_Post_List();
                 $missing_ids = array();
                 $missingPosts = $postList->getBy(array('import_id' => $this->id, 'iteration !=' => $this->iteration));
                 if (!$missingPosts->isEmpty()) {
                     foreach ($missingPosts as $missingPost) {
                         $missing_ids[] = $missingPost['post_id'];
                     }
                 }
                 // Delete posts from database
                 if (!empty($missing_ids) && is_array($missing_ids)) {
                     $logger and call_user_func($logger, __('<b>ACTION</b>: pmxi_delete_post', 'wp_all_import_plugin'));
                     $logger and call_user_func($logger, __('Deleting posts from database', 'wp_all_import_plugin'));
                     $missing_ids_arr = array_chunk($missing_ids, 100);
                     foreach ($missing_ids_arr as $key => $ids) {
                         if (!empty($ids)) {
                             foreach ($ids as $k => $id) {
                                 $to_delete = true;
                                 // Instead of deletion, set Custom Field
                                 if ($this->options['is_update_missing_cf']) {
                                     update_post_meta($id, $this->options['update_missing_cf_name'], $this->options['update_missing_cf_value']);
                                     $to_delete = false;
                                     $logger and call_user_func($logger, sprintf(__('Instead of deletion post with ID `%s`, set Custom Field `%s` to value `%s`', 'wp_all_import_plugin'), $id, $this->options['update_missing_cf_name'], $this->options['update_missing_cf_value']));
                                 }
                                 // Instead of deletion, change post status to Draft
                                 if ($this->options['set_missing_to_draft']) {
                                     $this->wpdb->update($this->wpdb->posts, array('post_status' => 'draft'), array('ID' => $id));
                                     $to_delete = false;
                                     $logger and call_user_func($logger, sprintf(__('Instead of deletion, change post with ID `%s` status to Draft', 'wp_all_import_plugin'), $id));
                                 }
                                 if ($to_delete) {
                                     // Remove attachments
                                     empty($this->options['is_keep_attachments']) and wp_delete_attachments($id, true, 'files');
                                     // Remove images
                                     empty($this->options['is_keep_imgs']) and wp_delete_attachments($id, true, 'images');
                                     // Clear post's relationships
                                     if ($post_type[$i] != "import_users") {
                                         wp_delete_object_term_relationships($id, get_object_taxonomies('' != $this->options['custom_type'] ? $this->options['custom_type'] : 'post'));
                                     }
                                 } else {
                                     unset($ids[$k]);
                                 }
                             }
                             if (!empty($ids)) {
                                 do_action('pmxi_delete_post', $ids);
                                 if ($this->options['custom_type'] == "import_users") {
                                     $sql = "delete a,b\n\t\t\t\t\t\t\t\t\t\tFROM " . $this->wpdb->users . " a\n\t\t\t\t\t\t\t\t\t\tLEFT JOIN " . $this->wpdb->usermeta . " b ON ( a.ID = b.user_id )\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\tWHERE a.ID IN (" . implode(',', $ids) . ");";
                                 } else {
                                     $sql = "delete a,b,c\n\t\t\t\t\t\t\t\t\t\tFROM " . $this->wpdb->posts . " a\n\t\t\t\t\t\t\t\t\t\tLEFT JOIN " . $this->wpdb->term_relationships . " b ON ( a.ID = b.object_id )\n\t\t\t\t\t\t\t\t\t\tLEFT JOIN " . $this->wpdb->postmeta . " c ON ( a.ID = c.post_id )\t\t\t\t\n\t\t\t\t\t\t\t\t\t\tWHERE a.ID IN (" . implode(',', $ids) . ");";
                                 }
                                 $this->wpdb->query($sql);
                                 // Delete record form pmxi_posts
                                 $sql = "DELETE FROM " . PMXI_Plugin::getInstance()->getTablePrefix() . "posts WHERE post_id IN (" . implode(',', $ids) . ") AND import_id = %d";
                                 $this->wpdb->query($this->wpdb->prepare($sql, $this->id));
                                 $this->set(array('deleted' => $this->deleted + count($ids)))->update();
                             }
                         }
                     }
                 }
             }
             // Set out of stock status for missing records [Woocommerce add-on option]
             if ($is_import_complete and empty($this->options['is_delete_missing']) and $post_type[$i] == "product" and class_exists('PMWI_Plugin') and !empty($this->options['missing_records_stock_status'])) {
                 $logger and call_user_func($logger, __('Update stock status previously imported posts which are no longer actual...', 'wp_all_import_plugin'));
                 $postList = new PMXI_Post_List();
                 $missingPosts = $postList->getBy(array('import_id' => $this->id, 'iteration !=' => $this->iteration));
                 if (!$missingPosts->isEmpty()) {
                     foreach ($missingPosts as $missingPost) {
                         update_post_meta($missingPost['post_id'], '_stock_status', 'outofstock');
                         update_post_meta($missingPost['post_id'], '_stock', 0);
                         $missingPostRecord = new PMXI_Post_Record();
                         $missingPostRecord->getBy('id', $missingPost['id']);
                         if (!$missingPostRecord->isEmpty()) {
                             $missingPostRecord->set(array('iteration' => $this->iteration))->update();
                         }
                         unset($missingPostRecord);
                     }
                 }
             }
         }
     } catch (XmlImportException $e) {
         $logger and call_user_func($logger, __('<b>ERROR</b>', 'wp_all_import_plugin') . ': ' . $e->getMessage());
         $logger and !$is_cron and PMXI_Plugin::$session->errors++;
     }
     $logger and $is_import_complete and call_user_func($logger, __('Cleaning temporary data...', 'wp_all_import_plugin'));
     foreach ($tmp_files as $file) {
         // remove all temporary files created
         @unlink($file);
     }
     if (($is_cron or $is_import_complete) and $this->options['is_delete_source']) {
         $logger and call_user_func($logger, __('Deleting source XML file...', 'wp_all_import_plugin'));
         // Delete chunks
         foreach (PMXI_Helper::safe_glob($uploads['basedir'] . DIRECTORY_SEPARATOR . PMXI_Plugin::TEMP_DIRECTORY . DIRECTORY_SEPARATOR . 'pmxi_chunk_*', PMXI_Helper::GLOB_RECURSE | PMXI_Helper::GLOB_PATH) as $filePath) {
             $logger and call_user_func($logger, __('Deleting chunks files...', 'wp_all_import_plugin'));
             @file_exists($filePath) and wp_all_import_remove_source($filePath, false);
         }
         if ($this->type != "ftp") {
             if (!@unlink($this->path)) {
                 $logger and call_user_func($logger, sprintf(__('<b>WARNING</b>: Unable to remove %s', 'wp_all_import_plugin'), $this->path));
             }
         } else {
             $file_path_array = PMXI_Helper::safe_glob($this->path, PMXI_Helper::GLOB_NODIR | PMXI_Helper::GLOB_PATH);
             if (!empty($file_path_array)) {
                 foreach ($file_path_array as $path) {
                     if (!@unlink($path)) {
                         $logger and call_user_func($logger, sprintf(__('<b>WARNING</b>: Unable to remove %s', 'wp_all_import_plugin'), $path));
                     }
                 }
             }
         }
     }
     if (!$is_cron and $is_import_complete) {
         $this->set(array('processing' => 0, 'triggered' => 0, 'queue_chunk_number' => 0, 'registered_on' => date('Y-m-d H:i:s'), 'iteration' => ++$this->iteration))->update();
         $logger and call_user_func($logger, 'Done');
     }
     remove_filter('user_has_cap', array($this, '_filter_has_cap_unfiltered_html'));
     kses_init();
     // return any filtering rules back if they has been disabled for import procedure
     return $this;
 }
Exemplo n.º 27
0
						<?php 
    } else {
        ?>
						<p><?php 
        printf(__('Piece By Piece Processing enabled. %s records will be processed each iteration. If it takes longer than your server\'s max_execution_time to process %s records, your import will fail.', 'wp_all_import_plugin'), $post['records_per_request'], $post['records_per_request']);
        ?>
</p>
						<?php 
    }
    ?>
						
						<?php 
    if ($post['chuncking'] and "default" != $post['import_processing']) {
        ?>
						<p><?php 
        printf(__('Your file will be split into %s records chunks before processing.', 'wp_all_import_plugin'), PMXI_Plugin::getInstance()->getOption('large_feed_limit'));
        ?>
</p>
						<?php 
    }
    ?>

						<?php 
    if ($post['is_fast_mode']) {
        ?>
						<p><?php 
        _e('do_action calls will be disabled in wp_insert_post and wp_insert_attachment during the import.', 'wp_all_import_plugin');
        ?>
</p>
						<?php 
    }
Exemplo n.º 28
0
 /**
  * __construct
  * 
  * Builds the Chunk object
  *
  * @param string $file The filename to work with
  * @param array $options The options with which to parse the file
  * @author Dom Hastings
  * @access public
  */
 public function __construct($file, $options = array())
 {
     // merge the options together
     $this->options = array_merge($this->options, is_array($options) ? $options : array());
     $this->options['chunkSize'] *= PMXI_Plugin::getInstance()->getOption('chunk_size');
     // set the filename
     $this->file = $file;
     $is_html = false;
     $f = @fopen($file, "rb");
     while (!@feof($f)) {
         $chunk = @fread($f, 1024);
         if (strpos($chunk, "<!DOCTYPE") === 0) {
             $is_html = true;
         }
         break;
     }
     @fclose($f);
     if ($is_html) {
         return;
     }
     if (empty($this->options['element']) or $this->options['get_cloud']) {
         //$founded_tags = array();
         if (function_exists('stream_filter_register') and $this->options['filter']) {
             stream_filter_register('preprocessxml', 'preprocessXml_filter');
             $path = 'php://filter/read=preprocessxml/resource=' . $this->file;
         } else {
             $path = $this->file;
         }
         $reader = new XMLReader();
         $reader->open($path);
         $reader->setParserProperty(XMLReader::VALIDATE, false);
         while (@$reader->read()) {
             switch ($reader->nodeType) {
                 case XMLREADER::ELEMENT:
                     if (array_key_exists(str_replace(":", "_", $reader->localName), $this->cloud)) {
                         $this->cloud[str_replace(":", "_", $reader->localName)]++;
                     } else {
                         $this->cloud[str_replace(":", "_", $reader->localName)] = 1;
                     }
                     //array_push($founded_tags, str_replace(":", "_", $reader->localName));
                     break;
                 default:
                     break;
             }
         }
         unset($reader);
         /*if (!empty($founded_tags)) {            
             $element_counts = array_count_values($founded_tags);                          
             if (!empty($element_counts)){
               foreach ($element_counts as $tag => $count)
                 if (strpos($tag, ":") === false)
                     $this->cloud[$tag] = $count;                
               
               arsort($element_counts);           
             }              
           } */
         if (!empty($this->cloud) and empty($this->options['element'])) {
             arsort($this->cloud);
             $main_elements = array('node', 'product', 'job', 'deal', 'entry', 'item', 'property', 'listing', 'hotel', 'record', 'article', 'post', 'book');
             foreach ($this->cloud as $element_name => $value) {
                 if (in_array(strtolower($element_name), $main_elements)) {
                     $this->options['element'] = $element_name;
                     break;
                 }
             }
             if (empty($this->options['element'])) {
                 foreach ($this->cloud as $el => $count) {
                     $this->options['element'] = $el;
                     break;
                 }
             }
         }
     }
     if (function_exists('stream_filter_register') and $this->options['filter']) {
         stream_filter_register('preprocessxml', 'preprocessXml_filter');
         $path = 'php://filter/read=preprocessxml/resource=' . $this->file;
     } else {
         $path = $this->file;
     }
     $this->reader = new XMLReader();
     @$this->reader->open($path);
     @$this->reader->setParserProperty(XMLReader::VALIDATE, false);
 }
Exemplo n.º 29
0
" /> <?php 
_e('records', 'pmxi_plugin');
?>
										<a href="#help" class="wpallimport-help" style="position: relative; top: -2px;" title="<?php 
_e('WP All Import must be able to process this many records in less than your server\'s timeout settings. If your import fails before completion, to troubleshoot you should lower this number. If you are importing images, especially high resolution images, high numbers here are probably a bad idea, since downloading the images can take lots of time - for example, 20 posts with 5 images each = 100 images. At 500Kb per image that\'s 50Mb that needs to be downloaded. Can your server download that before timing out? If not, the import will fail.', 'pmxi_plugin');
?>
">?</a>							
									</div>
									<div class="input pl17" style="margin:5px 0px;">
										<input type="hidden" name="chuncking" value="0" />
										<input type="checkbox" id="chuncking" name="chuncking" value="1" class="fix_checkbox" <?php 
echo $post['chuncking'] ? 'checked="checked"' : '';
?>
/>
										<label for="chuncking"><?php 
_e('Split file up into <strong>' . PMXI_Plugin::getInstance()->getOption('large_feed_limit') . '</strong> record chunks.', 'pmxi_plugin');
?>
</label> 
										<a href="#help" class="wpallimport-help" style="position: relative; top: -2px;" title="<?php 
_e('This option will decrease the amount of slowdown experienced at the end of large imports. The slowdown is partially caused by the need for WP All Import to read deeper and deeper into the file on each successive iteration. Splitting the file into pieces means that, for example, instead of having to read 19000 records into a 20000 record file when importing the last 1000 records, WP All Import will just split it into 20 chunks, and then read the last chunk from the beginning.', 'pmxi_plugin');
?>
">?</a>							
									</div>							
								</span>									
							</div>				
							<div class="input">
								<input type="hidden" name="is_fast_mode" value="0" />
								<input type="checkbox" id="is_fast_mode" name="is_fast_mode" value="1" class="fix_checkbox" <?php 
echo $post['is_fast_mode'] ? 'checked="checked"' : '';
?>
/>
 /**
  *
  *	Init addons' view
  *
  */
 private function init_addon_fields()
 {
     global $wpdb;
     $table = PMXI_Plugin::getInstance()->getTablePrefix() . 'imports';
     $imports = $wpdb->get_results("SELECT * FROM {$table} WHERE `parent_import_id` = 0", ARRAY_A);
     if (empty($imports)) {
         $this->wpml_addon->add_text("This is your first import. Default language will be choosen automatically ( " . $this->get_flag_html($this->default_language) . $this->wpml->get_display_language_name($this->default_language, 'en') . " ).");
     }
     $langs = $this->wpml->get_active_languages();
     if (!empty($langs)) {
         // prepare active languages list
         $language_list = array();
         foreach ($langs as $code => $langInfo) {
             $language_list[$code] = $this->get_flag_html($code) . $langInfo['display_name'];
             if ($code == $this->default_language) {
                 $language_list[$code] .= ' ( <strong>default</strong> )';
             }
         }
         $this->wpml_addon->add_field('lng', 'Content Language', 'radio', $language_list);
         if (!empty($imports)) {
             // prepare active imports list
             $import_list = array();
             foreach ($imports as $import) {
                 if (!empty($_GET['id']) and $_GET['id'] == $import['id']) {
                     continue;
                 }
                 $import_options = unserialize($import['options']);
                 $import_list[$import['id']] = '[ ID: ' . $import['id'] . ' ] ' . (!empty($import_options['wpml_addon']['lng']) ? $this->get_flag_html($import_options['wpml_addon']['lng']) : '') . (!empty($import['friendly_name']) ? $import['friendly_name'] : $import['name']);
             }
             $this->wpml_addon->add_options(null, 'Automatic Record Matching to Translate', array($this->wpml_addon->add_field('matching_logic', 'Records matching logic', 'radio', array('' => '<strong>Import data in main language (' . $this->wpml->get_display_language_name($this->default_language, 'en') . ')</strong>', 'auto' => array('Define parent import', $this->wpml_addon->add_field('import', 'Import to translate', 'radio', $import_list), $this->wpml_addon->add_field('unique_key', 'Unique Key', 'text', null, 'To inform WPML that this new post is translation of another post put the same unique key like you did for post in main language.'))))));
             // Aditional Options [ TODO: taxonomies options, media options, etc. ]
             // $this->wpml_addon->add_options(
             // 	null,
             // 	'Advanced Settings',
             // 	array(
             // 		$this->wpml_addon->add_field('translate_taxes', 'Translate taxonomies', 'radio', array('' => 'No', '1' => 'Yes'))
             // 	)
             // );
         }
         return;
     }
     $this->wpml_addon->add_text('Please set up site languages before using \'WP All Import - WPML add-on.\'');
 }