Example #1
0
 /**
  * Step #1: Choose File
  */
 public function index($post_type = 'post')
 {
     $default = PMAI_Plugin::get_default_import_options();
     $this->data['id'] = $id = $this->input->get('id');
     $this->data['import'] = $import = new PMXI_Import_Record();
     if (!$id or $import->getById($id)->isEmpty()) {
         // specified import is not found
         $post = $this->input->post((isset(PMXI_Plugin::$session->options) ? PMXI_Plugin::$session->options : array()) + $default);
     } else {
         $post = $this->input->post($this->data['import']->options + $default);
     }
     $this->data['is_loaded_template'] = !empty(PMXI_Plugin::$session->is_loaded_template) ? PMXI_Plugin::$session->is_loaded_template : false;
     $load_options = $this->input->post('load_template');
     if ($load_options) {
         // init form with template selected
         $template = new PMXI_Template_Record();
         if (!$template->getById($this->data['is_loaded_template'])->isEmpty()) {
             $post = (!empty($template->options) ? $template->options : array()) + $default;
         }
     } elseif ($load_options == -1) {
         $post = $default;
     }
     $this->data['post_type'] = $post_type;
     $this->data['post'] =& $post;
     $this->render();
 }
function pmwi_pmxi_after_xml_import($import_id)
{
    $import = new PMXI_Import_Record();
    $import->getById($import_id);
    if (!$import->isEmpty() and in_array($import->options['custom_type'], array('product', 'product_variation')) and $import->options['is_keep_former_posts'] == 'no' and ($import->options['update_all_data'] == 'yes' or $import->options['is_update_categories'])) {
        $product_cats = get_terms('product_cat', array('hide_empty' => false, 'fields' => 'id=>parent'));
        _wc_term_recount($product_cats, get_taxonomy('product_cat'), true, false);
        $product_tags = get_terms('product_tag', array('hide_empty' => false, 'fields' => 'id=>parent'));
        _wc_term_recount($product_tags, get_taxonomy('product_tag'), true, false);
    }
}
Example #3
0
 /**
  * Validate XML to be valid for import
  * @param string $xml
  * @param WP_Error[optional] $errors
  * @return bool Validation status
  */
 public static function validateXml(&$xml, $errors = NULL)
 {
     if (FALSE === $xml or '' == $xml) {
         $errors and $errors->add('form-validation', __('WP All Import can\'t read your file.<br/><br/>Probably, you are trying to import an invalid XML feed. Try opening the XML feed in a web browser (Google Chrome is recommended for opening XML files) to see if there is an error message.<br/>Alternatively, run the feed through a validator: http://validator.w3.org/<br/>99% of the time, the reason for this error is because your XML feed isn\'t valid.<br/>If you are 100% sure you are importing a valid XML feed, please contact WP All Import support.', 'wp_all_import_plugin'));
     } else {
         PMXI_Import_Record::preprocessXml($xml);
         if (function_exists('simplexml_load_string')) {
             libxml_use_internal_errors(true);
             libxml_clear_errors();
             $_x = @simplexml_load_string($xml);
             $xml_errors = libxml_get_errors();
             libxml_clear_errors();
             if ($xml_errors) {
                 $error_msg = '<strong>' . __('Invalid XML', 'wp_all_import_plugin') . '</strong><ul>';
                 foreach ($xml_errors as $error) {
                     $error_msg .= '<li>';
                     $error_msg .= __('Line', 'wp_all_import_plugin') . ' ' . $error->line . ', ';
                     $error_msg .= __('Column', 'wp_all_import_plugin') . ' ' . $error->column . ', ';
                     $error_msg .= __('Code', 'wp_all_import_plugin') . ' ' . $error->code . ': ';
                     $error_msg .= '<em>' . trim(esc_html($error->message)) . '</em>';
                     $error_msg .= '</li>';
                 }
                 $error_msg .= '</ul>';
                 $errors and $errors->add('form-validation', $error_msg);
             } else {
                 return true;
             }
         } else {
             $errors and $errors->add('form-validation', __('Required PHP components are missing.', 'wp_all_import_plugin'));
             $errors and $errors->add('form-validation', __('WP All Import requires the SimpleXML PHP module to be installed. This is a standard feature of PHP, and is necessary for WP All Import to read the files you are trying to import.<br/>Please contact your web hosting provider and ask them to install and activate the SimpleXML PHP module.', 'wp_all_import_plugin'));
         }
     }
     return false;
 }
Example #4
0
 /**
  * Validate XML to be valid for import
  * @param string $xml
  * @param WP_Error[optional] $errors
  * @return bool Validation status
  */
 public static function validateXml(&$xml, $errors = NULL)
 {
     if (FALSE === $xml or '' == $xml) {
         $errors and $errors->add('form-validation', __('XML file does not exist, not accessible or empty', 'pmxi_plugin'));
     } else {
         PMXI_Import_Record::preprocessXml($xml);
         if (function_exists('simplexml_load_string')) {
             libxml_use_internal_errors(true);
             libxml_clear_errors();
             $_x = @simplexml_load_string($xml);
             $xml_errors = libxml_get_errors();
             libxml_clear_errors();
             if ($xml_errors) {
                 $error_msg = '<strong>' . __('Invalid XML', 'pmxi_plugin') . '</strong><ul>';
                 foreach ($xml_errors as $error) {
                     $error_msg .= '<li>';
                     $error_msg .= __('Line', 'pmxi_plugin') . ' ' . $error->line . ', ';
                     $error_msg .= __('Column', 'pmxi_plugin') . ' ' . $error->column . ', ';
                     $error_msg .= __('Code', 'pmxi_plugin') . ' ' . $error->code . ': ';
                     $error_msg .= '<em>' . trim(esc_html($error->message)) . '</em>';
                     $error_msg .= '</li>';
                 }
                 $error_msg .= '</ul>';
                 $errors and $errors->add('form-validation', $error_msg);
             } else {
                 return true;
             }
         } else {
             $errors and $errors->add('form-validation', __('simplexml module is disabled on your server', 'pmxi_plugin'));
         }
     }
     return false;
 }
function pmxi_wp_ajax_delete_import()
{
    if (!check_ajax_referer('wp_all_import_secure', 'security', false)) {
        exit(json_encode(array('result' => false, 'msg' => __('Security check', 'wp_all_import_plugin'))));
    }
    if (!current_user_can('manage_options')) {
        exit(json_encode(array('result' => false, 'msg' => __('Security check', 'wp_all_import_plugin'))));
    }
    $input = new PMXI_Input();
    $post = $input->post(array('data' => ''));
    $get = $input->get(array('iteration' => 1));
    $params = array();
    parse_str($post['data'], $params);
    $response = array('result' => false, 'msg' => '', 'redirect' => add_query_arg('pmxi_nt', urlencode(__('Import deleted', 'wp_all_import_plugin')), $params['base_url']));
    if (!empty($params['import_ids'])) {
        foreach ($params['import_ids'] as $key => $id) {
            $import = new PMXI_Import_Record();
            $import->getById($id);
            if (!$import->isEmpty()) {
                if ((int) $get['iteration'] === 1) {
                    $import->set(array('deleted' => 0))->update();
                }
                $is_all_records_deleted = $import->deletePostsAjax(!$params['is_delete_posts'], $params['is_delete_images'], $params['is_delete_attachments']);
                $response['result'] = empty($params['import_ids'][$key + 1]) ? $is_all_records_deleted : false;
                $response['msg'] = sprintf(__('Import #%d - %d records deleted', 'wp_all_import_plugin'), $import->id, $import->deleted);
                if ($is_all_records_deleted === true) {
                    $import->delete(!$params['is_delete_posts'], $params['is_delete_images'], $params['is_delete_attachments']);
                }
            }
        }
    }
    exit(json_encode($response));
}
Example #6
0
 public function merge()
 {
     /* Merge nested XML/CSV files */
     if (!empty($this->nested_files)) {
         $tmp_files = array();
         foreach ($this->nested_files as $key => $nfile) {
             $nested_fileURL = array_shift(XmlImportParser::factory($this->xml, $this->xpath, $nfile, $tmp_file)->parse());
             $tmp_files[] = $tmp_file;
             if (!empty($nested_fileURL)) {
                 $errors = new WP_Error();
                 $uploader = new PMXI_Upload($nested_fileURL, $errors);
                 $upload_result = $uploader->url();
                 if ($upload_result instanceof WP_Error) {
                     $errors = $upload_result;
                 } else {
                     $source = $upload_result['source'];
                     $filePath = $upload_result['filePath'];
                     if (!empty($upload_result['root_element'])) {
                         $root_element = $upload_result['root_element'];
                     } else {
                         $root_element = '';
                     }
                     $feed_type = $upload_result['feed_type'];
                 }
                 unset($uploader);
                 $nested_xml = file_get_contents($filePath);
                 if (!empty($nested_xml)) {
                     PMXI_Import_Record::preprocessXml($nested_xml);
                     if (PMXI_Import_Record::validateXml($nested_xml) === true) {
                         $nestedDom = new DOMDocument('1.0', 'UTF-8');
                         $nestedold = libxml_use_internal_errors(true);
                         $nestedDom->loadXML($nested_xml);
                         libxml_use_internal_errors($nestedold);
                         $second = $nestedDom->documentElement;
                         if ($second->hasChildNodes()) {
                             foreach ($second->childNodes as $node) {
                                 $importNode = $this->dom->importNode($node, true);
                                 $this->dom->documentElement->appendChild($importNode);
                             }
                             $this->xml = $this->elements ? $this->dom->saveXML($this->elements->item(0)) : $this->dom->saveXML();
                         }
                         unset($nestedDom);
                     }
                 }
             }
         }
         foreach ($tmp_files as $tmp_file) {
             // remove all temporary files created
             @unlink($tmp_file);
         }
     }
 }
function pmxi_wp_ajax_nested_xpath()
{
    if (!check_ajax_referer('wp_all_import_secure', 'security', false)) {
        exit(json_encode(array('result' => array(), 'msg' => __('Security check', 'wp_all_import_plugin'))));
    }
    if (!current_user_can(PMXI_Plugin::$capabilities)) {
        exit(json_encode(array('result' => array(), 'msg' => __('Security check', 'wp_all_import_plugin'))));
    }
    extract($_POST);
    $result = array();
    if (@file_exists($filePath)) {
        $file = new PMXI_Chunk($filePath, array('element' => $root_element, 'encoding' => 'UTF-8'));
        $tagno = 0;
        $loop = 0;
        $count = 0;
        $xml_tree = '';
        while ($xml = $file->read()) {
            if (!empty($xml)) {
                PMXI_Import_Record::preprocessXml($xml);
                $xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" . "\n" . $xml;
                if ('' != $customXpath) {
                    $dom = new DOMDocument('1.0', 'UTF-8');
                    $old = libxml_use_internal_errors(true);
                    $dom->loadXML($xml);
                    libxml_use_internal_errors($old);
                    $xpath = new DOMXPath($dom);
                    if ($elements = $xpath->query($customXpath) and $elements->length) {
                        $loop++;
                        $count += $elements->length;
                        if (!$tagno or $loop == $tagno) {
                            ob_start();
                            PMXI_Render::render_xml_element($elements->item(0), true);
                            $xml_tree = ob_get_clean();
                            $tagno = 1;
                        }
                    }
                } else {
                    exit(json_encode(array('success' => false, 'msg' => __('XPath is required', 'wp_all_import_plugin'))));
                    die;
                }
            }
        }
        unset($file);
    } else {
        exit(json_encode(array('success' => false, 'msg' => 'File path is required', 'wp_all_import_plugin')));
        die;
    }
    exit(json_encode(array('success' => true, 'xml_tree' => $xml_tree, 'count' => $count ? sprintf("<p class='green pmxi_counter'>" . __('Elements found', 'pmxi_pligun') . " <strong>%s</strong></p>", $count) : "<p class='red pmxi_counter'>" . __('Elements not found', 'pmxi_pligun') . "</p>")));
    die;
}
Example #8
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']);
 }
Example #9
0
 /**
  * @see parent::delete()	 
  */
 public function delete()
 {
     $this->deletePosts();
     if (!empty($this->options['import_id']) and wp_all_export_is_compatible()) {
         $import = new PMXI_Import_Record();
         $import->getById($this->options['import_id']);
         if (!$import->isEmpty() and $import->parent_import_id == 99999) {
             $import->delete();
         }
     }
     $export_file_path = wp_all_export_get_absolute_path($this->options['filepath']);
     if (@file_exists($export_file_path)) {
         wp_all_export_remove_source($export_file_path);
     }
     if (!empty($this->attch_id)) {
         wp_delete_attachment($this->attch_id, true);
     }
     $wp_uploads = wp_upload_dir();
     $file_for_remote_access = $wp_uploads['basedir'] . DIRECTORY_SEPARATOR . PMXE_Plugin::UPLOADS_DIRECTORY . DIRECTORY_SEPARATOR . md5(PMXE_Plugin::getInstance()->getOption('cron_job_key') . $this->id) . '.' . $this->options['export_to'];
     if (@file_exists($file_for_remote_access)) {
         @unlink($file_for_remote_access);
     }
     return parent::delete();
 }
Example #10
0
 function filter($in, $out, &$consumed, $closing)
 {
     while ($bucket = stream_bucket_make_writeable($in)) {
         PMXI_Import_Record::preprocessXml($bucket->data);
         $consumed += $bucket->datalen;
         stream_bucket_append($out, $bucket);
     }
     return PSFS_PASS_ON;
 }
/**
*
*	Ajax action that will parse nested XML/CSV files
*
*/
function pmxi_wp_ajax_parse_nested_file()
{
    extract($_POST);
    $result = array();
    $wp_uploads = wp_upload_dir();
    if (!empty($_POST['nested_type'])) {
        $root_element = '';
        $feed_type = '';
        $errors = new WP_Error();
        switch ($_POST['nested_type']) {
            case 'upload':
                $uploader = new PMXI_Upload($_POST['nested_filepath'], $errors);
                $upload_result = $uploader->upload();
                if ($upload_result instanceof WP_Error) {
                    $errors = $upload_result;
                } else {
                    $source = $upload_result['source'];
                    $filePath = $upload_result['filePath'];
                    if (!empty($upload_result['root_element'])) {
                        $root_element = $upload_result['root_element'];
                    }
                }
                break;
            case 'url':
                $uploader = new PMXI_Upload($_POST['nested_url'], $errors);
                $upload_result = $uploader->url();
                if ($upload_result instanceof WP_Error) {
                    $errors = $upload_result;
                } else {
                    $source = $upload_result['source'];
                    $filePath = $upload_result['filePath'];
                    if (!empty($upload_result['root_element'])) {
                        $root_element = $upload_result['root_element'];
                    }
                    $feed_type = $upload_result['feed_type'];
                }
                break;
            case 'file':
                $uploader = new PMXI_Upload($_POST['nested_file'], $errors);
                $upload_result = $uploader->file();
                if ($upload_result instanceof WP_Error) {
                    $errors = $upload_result;
                } else {
                    $source = $upload_result['source'];
                    $filePath = $upload_result['filePath'];
                    if (!empty($upload_result['root_element'])) {
                        $root_element = $upload_result['root_element'];
                    }
                }
                break;
        }
    }
    if ($errors->get_error_codes()) {
        $msgs = $errors->get_error_messages();
        ob_start();
        ?>
		<?php 
        foreach ($msgs as $msg) {
            ?>
			<div class="error"><p><?php 
            echo $msg;
            ?>
</p></div>
		<?php 
        }
        ?>
		<?php 
        exit(json_encode(array('success' => false, 'errors' => ob_get_clean())));
        die;
    } else {
        $xml_tree = '';
        if (@file_exists($filePath)) {
            $file = new PMXI_Chunk($filePath, array('element' => $root_element));
            if (!empty($file->options['element'])) {
                $customXpath = "/" . $file->options['element'];
                $elements_cloud = $file->cloud;
            }
            $root_element = $file->options['element'];
            $file = new PMXI_Chunk($filePath, array('element' => $root_element, 'encoding' => 'UTF-8'));
            $tagno = 0;
            $loop = 0;
            $count = 0;
            while ($xml = $file->read()) {
                if (!empty($xml)) {
                    PMXI_Import_Record::preprocessXml($xml);
                    $xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" . "\n" . $xml;
                    if ('' != $customXpath) {
                        $dom = new DOMDocument('1.0', 'UTF-8');
                        $old = libxml_use_internal_errors(true);
                        $dom->loadXML($xml);
                        libxml_use_internal_errors($old);
                        $xpath = new DOMXPath($dom);
                        if ($elements = $xpath->query($customXpath) and $elements->length) {
                            $loop++;
                            $count += $elements->length;
                            if (!$tagno or $loop == $tagno) {
                                ob_start();
                                PMXI_Render::render_xml_element($elements->item(0), true);
                                $xml_tree = ob_get_clean();
                                $tagno = 1;
                            }
                        }
                    } else {
                        break;
                    }
                }
            }
            unset($file);
        }
        exit(json_encode(array('success' => true, 'source' => $source, 'realpath' => $source['path'], 'filePath' => $filePath, 'root_element' => $root_element, 'xml_tree' => $xml_tree, 'xpath' => $customXpath, 'count' => $count ? sprintf("<p class='green pmxi_counter'>" . __('Elements founded', 'pmxi_pligun') . " <strong>%s</strong></p>", $count) : "<p class='red pmxi_counter'>" . __('Elements not found', 'pmxi_pligun') . "</p>")));
        die;
    }
}
/**
*	AJAX action export processing
*/
function pmxe_wp_ajax_wpallexport()
{
    if (!check_ajax_referer('wp_all_export_secure', 'security', false)) {
        exit(__('Security check', 'wp_all_export_plugin'));
    }
    if (!current_user_can('manage_options')) {
        exit(__('Security check', 'wp_all_export_plugin'));
    }
    $input = new PMXE_Input();
    $export_id = $input->get('id', 0);
    if (empty($export_id)) {
        $export_id = !empty(PMXE_Plugin::$session->update_previous) ? PMXE_Plugin::$session->update_previous : 0;
    }
    $wp_uploads = wp_upload_dir();
    $export = new PMXE_Export_Record();
    $export->getById($export_id);
    if ($export->isEmpty()) {
        exit(__('Export is not defined.', 'wp_all_export_plugin'));
    }
    $exportOptions = $export->options + PMXE_Plugin::get_default_import_options();
    wp_reset_postdata();
    XmlExportEngine::$exportOptions = $exportOptions;
    XmlExportEngine::$is_user_export = $exportOptions['is_user_export'];
    XmlExportEngine::$exportID = $export_id;
    $posts_per_page = $exportOptions['records_per_iteration'];
    if ('advanced' == $exportOptions['export_type']) {
        if (XmlExportEngine::$is_user_export) {
            exit(json_encode(array('html' => __('Upgrade to the professional edition of WP All Export to export users.', 'wp_all_export_plugin'))));
        } else {
            $exportQuery = eval('return new WP_Query(array(' . $exportOptions['wp_query'] . ', \'offset\' => ' . $export->exported . ', \'posts_per_page\' => ' . $posts_per_page . ' ));');
        }
    } else {
        XmlExportEngine::$post_types = $exportOptions['cpt'];
        if (!in_array('users', $exportOptions['cpt'])) {
            $exportQuery = new WP_Query(array('post_type' => $exportOptions['cpt'], 'post_status' => 'any', 'orderby' => 'ID', 'order' => 'ASC', 'offset' => $export->exported, 'posts_per_page' => $posts_per_page));
        } else {
            exit(json_encode(array('html' => __('Upgrade to the professional edition of WP All Export to export users.', 'wp_all_export_plugin'))));
        }
    }
    XmlExportEngine::$exportQuery = $exportQuery;
    $foundPosts = !XmlExportEngine::$is_user_export ? $exportQuery->found_posts : $exportQuery->get_total();
    $postCount = !XmlExportEngine::$is_user_export ? $exportQuery->post_count : count($exportQuery->get_results());
    if (!$export->exported) {
        $attachment_list = $export->options['attachment_list'];
        if (!empty($attachment_list)) {
            foreach ($attachment_list as $attachment) {
                if (!is_numeric($attachment)) {
                    @unlink($attachment);
                }
            }
        }
        $exportOptions['attachment_list'] = array();
        $export->set(array('options' => $exportOptions))->save();
        $is_secure_import = PMXE_Plugin::getInstance()->getOption('secure');
        if ($is_secure_import and !empty($exportOptions['filepath'])) {
            // if 'Create a new file each time export is run' disabled remove all previously generated source files
            // if ( ! $exportOptions['creata_a_new_export_file'] or ! $export->iteration ){
            // 	wp_all_export_remove_source(wp_all_export_get_absolute_path($exportOptions['filepath']));
            // }
            $exportOptions['filepath'] = '';
        }
        PMXE_Plugin::$session->set('count', $foundPosts);
        PMXE_Plugin::$session->save_data();
    }
    // if posts still exists then export them
    if ($postCount) {
        switch ($exportOptions['export_to']) {
            case 'xml':
                pmxe_export_xml($exportQuery, $exportOptions);
                break;
            case 'csv':
                pmxe_export_csv($exportQuery, $exportOptions);
                break;
            default:
                # code...
                break;
        }
        wp_reset_postdata();
    }
    if ($postCount) {
        $export->set(array('exported' => $export->exported + $postCount))->save();
    }
    if ($posts_per_page != -1 and $postCount) {
        wp_send_json(array('exported' => $export->exported, 'percentage' => ceil($export->exported / $foundPosts * 100), 'done' => false, 'records_per_request' => $exportOptions['records_per_iteration']));
    } else {
        wp_reset_postdata();
        if (file_exists(PMXE_Plugin::$session->file)) {
            if ($exportOptions['export_to'] == 'xml') {
                file_put_contents(PMXE_Plugin::$session->file, '</' . $exportOptions['main_xml_tag'] . '>', FILE_APPEND);
            }
            $is_secure_import = PMXE_Plugin::getInstance()->getOption('secure');
            if (!$is_secure_import) {
                if (!$export->isEmpty()) {
                    $wp_filetype = wp_check_filetype(basename(PMXE_Plugin::$session->file), null);
                    $attachment_data = array('guid' => $wp_uploads['baseurl'] . '/' . _wp_relative_upload_path(PMXE_Plugin::$session->file), 'post_mime_type' => $wp_filetype['type'], 'post_title' => preg_replace('/\\.[^.]+$/', '', basename(PMXE_Plugin::$session->file)), 'post_content' => '', 'post_status' => 'inherit');
                    if (empty($export->attch_id)) {
                        $attach_id = wp_insert_attachment($attachment_data, PMXE_Plugin::$session->file);
                    } elseif ($export->options['creata_a_new_export_file']) {
                        $attach_id = wp_insert_attachment($attachment_data, PMXE_Plugin::$session->file);
                    } else {
                        $attach_id = $export->attch_id;
                        $attachment = get_post($attach_id);
                        if ($attachment) {
                            update_attached_file($attach_id, PMXE_Plugin::$session->file);
                            wp_update_attachment_metadata($attach_id, $attachment_data);
                        } else {
                            $attach_id = wp_insert_attachment($attachment_data, PMXE_Plugin::$session->file);
                        }
                    }
                    if (!in_array($attach_id, $exportOptions['attachment_list'])) {
                        $exportOptions['attachment_list'][] = $attach_id;
                    }
                    $export->set(array('attch_id' => $attach_id, 'options' => $exportOptions))->save();
                }
            } else {
                $exportOptions['filepath'] = wp_all_export_get_relative_path(PMXE_Plugin::$session->file);
                if (!$export->isEmpty()) {
                    $export->set(array('options' => $exportOptions))->save();
                }
            }
            // Generate templa for WP All Import
            if ($exportOptions['is_generate_templates']) {
                $custom_type = empty($exportOptions['cpt']) ? 'post' : $exportOptions['cpt'][0];
                $templateOptions = array('type' => (!empty($exportOptions['cpt']) and $exportOptions['cpt'][0] == 'page') ? 'page' : 'post', 'wizard_type' => 'new', 'deligate' => 'wpallexport', 'custom_type' => XmlExportEngine::$is_user_export ? 'import_users' : $custom_type, 'status' => 'xpath', 'is_multiple_page_parent' => 'no', 'unique_key' => '', 'acf' => array(), 'fields' => array(), 'is_multiple_field_value' => array(), 'multiple_value' => array(), 'fields_delimiter' => array(), 'update_all_data' => 'no', 'is_update_status' => 0, 'is_update_title' => 0, 'is_update_author' => 0, 'is_update_slug' => 0, 'is_update_content' => 0, 'is_update_excerpt' => 0, 'is_update_dates' => 0, 'is_update_menu_order' => 0, 'is_update_parent' => 0, 'is_update_attachments' => 0, 'is_update_acf' => 0, 'update_acf_logic' => 'only', 'acf_list' => '', 'is_update_product_type' => 1, 'is_update_attributes' => 0, 'update_attributes_logic' => 'only', 'attributes_list' => '', 'is_update_images' => 0, 'is_update_custom_fields' => 0, 'update_custom_fields_logic' => 'only', 'custom_fields_list' => '', 'is_update_categories' => 0, 'update_categories_logic' => 'only', 'taxonomies_list' => '', 'export_id' => $export->id);
                if (in_array('product', $exportOptions['cpt'])) {
                    $templateOptions['_virtual'] = 1;
                    $templateOptions['_downloadable'] = 1;
                    $templateOptions['put_variation_image_to_gallery'] = 1;
                    $templateOptions['disable_auto_sku_generation'] = 1;
                }
                if (XmlExportEngine::$is_user_export) {
                    $templateOptions['is_update_first_name'] = 0;
                    $templateOptions['is_update_last_name'] = 0;
                    $templateOptions['is_update_role'] = 0;
                    $templateOptions['is_update_nickname'] = 0;
                    $templateOptions['is_update_description'] = 0;
                    $templateOptions['is_update_login'] = 0;
                    $templateOptions['is_update_password'] = 0;
                    $templateOptions['is_update_nicename'] = 0;
                    $templateOptions['is_update_email'] = 0;
                    $templateOptions['is_update_registered'] = 0;
                    $templateOptions['is_update_display_name'] = 0;
                    $templateOptions['is_update_url'] = 0;
                }
                if ('xml' == $exportOptions['export_to']) {
                    wp_all_export_prepare_template_xml($exportOptions, $templateOptions);
                } else {
                    wp_all_export_prepare_template_csv($exportOptions, $templateOptions);
                }
                //$template = new PMXI_Template_Record();
                $tpl_options = $templateOptions;
                if ('csv' == $exportOptions['export_to']) {
                    $tpl_options['delimiter'] = $exportOptions['delimiter'];
                }
                $tpl_options['update_all_data'] = 'yes';
                $tpl_options['is_update_status'] = 1;
                $tpl_options['is_update_title'] = 1;
                $tpl_options['is_update_author'] = 1;
                $tpl_options['is_update_slug'] = 1;
                $tpl_options['is_update_content'] = 1;
                $tpl_options['is_update_excerpt'] = 1;
                $tpl_options['is_update_dates'] = 1;
                $tpl_options['is_update_menu_order'] = 1;
                $tpl_options['is_update_parent'] = 1;
                $tpl_options['is_update_attachments'] = 1;
                $tpl_options['is_update_acf'] = 1;
                $tpl_options['update_acf_logic'] = 'full_update';
                $tpl_options['acf_list'] = '';
                $tpl_options['is_update_product_type'] = 1;
                $tpl_options['is_update_attributes'] = 1;
                $tpl_options['update_attributes_logic'] = 'full_update';
                $tpl_options['attributes_list'] = '';
                $tpl_options['is_update_images'] = 1;
                $tpl_options['is_update_custom_fields'] = 1;
                $tpl_options['update_custom_fields_logic'] = 'full_update';
                $tpl_options['custom_fields_list'] = '';
                $tpl_options['is_update_categories'] = 1;
                $tpl_options['update_categories_logic'] = 'full_update';
                $tpl_options['taxonomies_list'] = '';
                $tpl_data = array('name' => $exportOptions['template_name'], 'is_keep_linebreaks' => 0, 'is_leave_html' => 0, 'fix_characters' => 0, 'options' => $tpl_options);
                $exportOptions['tpl_data'] = $tpl_data;
                $export->set(array('options' => $exportOptions))->save();
                // if ( ! empty($exportOptions['template_name'])) { // save template in database
                // 	$template->getByName($exportOptions['template_name'])->set($tpl_data)->save();
                // }
            }
            // associate exported posts with new import
            if (wp_all_export_is_compatible() and $exportOptions['is_generate_import']) {
                $options = $templateOptions + PMXI_Plugin::get_default_import_options();
                $import = new PMXI_Import_Record();
                $import->getById($exportOptions['import_id']);
                if (!$import->isEmpty() and $import->parent_import_id == 99999) {
                    $xmlPath = PMXE_Plugin::$session->file;
                    $root_element = '';
                    $historyPath = PMXE_Plugin::$session->file;
                    if ('csv' == $exportOptions['export_to']) {
                        $options['delimiter'] = $exportOptions['delimiter'];
                        include_once PMXI_Plugin::ROOT_DIR . '/libraries/XmlImportCsvParse.php';
                        $path_info = pathinfo($xmlPath);
                        $path_parts = explode(DIRECTORY_SEPARATOR, $path_info['dirname']);
                        $security_folder = array_pop($path_parts);
                        $target = $is_secure_import ? $wp_uploads['basedir'] . DIRECTORY_SEPARATOR . PMXE_Plugin::UPLOADS_DIRECTORY . DIRECTORY_SEPARATOR . $security_folder : $wp_uploads['path'];
                        $csv = new PMXI_CsvParser(array('filename' => $xmlPath, 'targetDir' => $target));
                        if (!in_array($xmlPath, $exportOptions['attachment_list'])) {
                            $exportOptions['attachment_list'][] = $csv->xml_path;
                        }
                        $historyPath = $csv->xml_path;
                        $root_element = 'node';
                    } else {
                        $root_element = 'post';
                    }
                    $import->set(array('xpath' => '/' . $root_element, 'type' => 'upload', 'options' => $options, 'root_element' => $root_element, 'path' => $xmlPath, 'name' => basename($xmlPath), 'imported' => 0, 'created' => 0, 'updated' => 0, 'skipped' => 0, 'deleted' => 0, 'iteration' => 1, 'count' => PMXE_Plugin::$session->count))->save();
                    $history_file = new PMXI_File_Record();
                    $history_file->set(array('name' => $import->name, 'import_id' => $import->id, 'path' => $historyPath, 'registered_on' => date('Y-m-d H:i:s')))->save();
                    $exportOptions['import_id'] = $import->id;
                    $export->set(array('options' => $exportOptions))->save();
                }
            }
        }
        $export->set(array('executing' => 0, 'canceled' => 0))->save();
        do_action('pmxe_after_export', $export->id);
        wp_send_json(array('exported' => $export->exported, 'percentage' => 100, 'done' => true, 'records_per_request' => $exportOptions['records_per_iteration'], 'file' => PMXE_Plugin::$session->file));
    }
}
Example #13
0
    /**
     * upload.php
     *
     * Copyright 2009, Moxiecode Systems AB
     * Released under GPL License.
     *
     * License: http://www.plupload.com/license
     * Contributing: http://www.plupload.com/contributing
     */
    public function upload()
    {
        if (!check_ajax_referer('wp_all_import_secure', '_wpnonce', false)) {
            exit(json_encode(array("jsonrpc" => "2.0", "error" => array("code" => 100, "message" => __('Security check', 'wp_all_import_plugin')), "id" => "id")));
        }
        // HTTP headers for no cache etc
        // header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
        // header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
        // header("Cache-Control: no-store, no-cache, must-revalidate");
        // header("Cache-Control: post-check=0, pre-check=0", false);
        // header("Pragma: no-cache");
        // Settings
        //$targetDir = ini_get("upload_tmp_dir") . DIRECTORY_SEPARATOR . "plupload";
        //$uploads = wp_upload_dir();
        $targetDir = self::$path;
        if (!is_dir($targetDir) || !is_writable($targetDir)) {
            delete_transient(self::$upload_transient);
            exit(json_encode(array("jsonrpc" => "2.0", "error" => array("code" => 100, "message" => __("Uploads folder is not writable.", "wp_all_import_plugin")), "id" => "id")));
        }
        $cleanupTargetDir = true;
        // Remove old files
        $maxFileAge = 5 * 3600;
        // Temp file age in seconds
        // 5 minutes execution time
        @set_time_limit(5 * 60);
        // Uncomment this one to fake upload time
        // usleep(5000);
        // Get parameters
        $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
        $chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0;
        $fileName = isset($_REQUEST["name"]) ? $_REQUEST["name"] : '';
        // Clean the fileName for security reasons
        $fileName = preg_replace('/[^\\w\\._]+/', '_', $fileName);
        if (!preg_match('%\\W(xml|gzip|zip|csv|gz|json|txt|dat|psv|sql|xls|xlsx)$%i', trim(basename($fileName)))) {
            exit(json_encode(array("jsonrpc" => "2.0", "error" => array("code" => 100, "message" => __("Uploaded file must be XML, CSV, ZIP, GZIP, GZ, JSON, SQL, TXT, DAT or PSV", "wp_all_import_plugin")), "id" => "id")));
        }
        // Make sure the fileName is unique but only if chunking is disabled
        if ($chunks < 2 && file_exists($targetDir . DIRECTORY_SEPARATOR . $fileName)) {
            $ext = strrpos($fileName, '.');
            $fileName_a = substr($fileName, 0, $ext);
            $fileName_b = substr($fileName, $ext);
            $count = 1;
            while (file_exists($targetDir . DIRECTORY_SEPARATOR . $fileName_a . '_' . $count . $fileName_b)) {
                $count++;
            }
            $fileName = $fileName_a . '_' . $count . $fileName_b;
        }
        $filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;
        // Create target dir
        if (!file_exists($targetDir)) {
            @mkdir($targetDir);
        }
        // Remove old temp files
        if ($cleanupTargetDir && is_dir($targetDir) && ($dir = opendir($targetDir))) {
            while (($file = readdir($dir)) !== false) {
                $tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;
                // Remove temp file if it is older than the max age and is not the current file
                if (preg_match('/\\.part$/', $file) && filemtime($tmpfilePath) < time() - $maxFileAge && $tmpfilePath != "{$filePath}.part") {
                    @unlink($tmpfilePath);
                }
            }
            closedir($dir);
        } else {
            delete_transient(self::$upload_transient);
            exit(json_encode(array("jsonrpc" => "2.0", "error" => array("code" => 100, "message" => __("Failed to open temp directory.", "wp_all_import_plugin")), "id" => "id")));
        }
        // Look for the content type header
        if (isset($_SERVER["HTTP_CONTENT_TYPE"])) {
            $contentType = $_SERVER["HTTP_CONTENT_TYPE"];
        }
        if (isset($_SERVER["CONTENT_TYPE"])) {
            $contentType = $_SERVER["CONTENT_TYPE"];
        }
        // Handle non multipart uploads older WebKit versions didn't support multipart in HTML5
        if (strpos($contentType, "multipart") !== false) {
            if (isset($_FILES['file']['tmp_name']) && is_uploaded_file($_FILES['file']['tmp_name'])) {
                // Open temp file
                $out = fopen("{$filePath}.part", $chunk == 0 ? "wb" : "ab");
                if ($out) {
                    // Read binary input stream and append it to temp file
                    $in = fopen($_FILES['file']['tmp_name'], "rb");
                    if ($in) {
                        while ($buff = fread($in, 4096)) {
                            fwrite($out, $buff);
                        }
                    } else {
                        delete_transient(self::$upload_transient);
                        exit(json_encode(array("jsonrpc" => "2.0", "error" => array("code" => 101, "message" => __("Failed to open input stream.", "wp_all_import_plugin")), "id" => "id")));
                    }
                    fclose($in);
                    fclose($out);
                    @unlink($_FILES['file']['tmp_name']);
                } else {
                    delete_transient(self::$upload_transient);
                    exit(json_encode(array("jsonrpc" => "2.0", "error" => array("code" => 102, "message" => __("Failed to open output stream.", "wp_all_import_plugin")), "id" => "id")));
                }
            } else {
                delete_transient(self::$upload_transient);
                exit(json_encode(array("jsonrpc" => "2.0", "error" => array("code" => 103, "message" => __("Failed to move uploaded file.", "wp_all_import_plugin")), "id" => "id")));
            }
        } else {
            // Open temp file
            $out = fopen("{$filePath}.part", $chunk == 0 ? "wb" : "ab");
            if ($out) {
                // Read binary input stream and append it to temp file
                $in = fopen("php://input", "rb");
                if ($in) {
                    while ($buff = fread($in, 4096)) {
                        fwrite($out, $buff);
                    }
                } else {
                    delete_transient(self::$upload_transient);
                    exit(json_encode(array("jsonrpc" => "2.0", "error" => array("code" => 101, "message" => __("Failed to open input stream.", "wp_all_import_plugin")), "id" => "id")));
                }
                fclose($in);
                fclose($out);
            } else {
                delete_transient(self::$upload_transient);
                exit(json_encode(array("jsonrpc" => "2.0", "error" => array("code" => 102, "message" => __("Failed to open output stream.", "wp_all_import_plugin")), "id" => "id")));
            }
        }
        $post_type = false;
        // Check if file has been uploaded
        if (!$chunks || $chunk == $chunks - 1) {
            // Strip the temp .part suffix off
            rename("{$filePath}.part", $filePath);
            chmod($filePath, 0755);
            delete_transient(self::$upload_transient);
            $errors = new WP_Error();
            $uploader = new PMXI_Upload($filePath, $errors, rtrim(str_replace(basename($filePath), '', $filePath), '/'));
            $upload_result = $uploader->upload();
            if ($upload_result instanceof WP_Error) {
                $errors = $upload_result;
                $msgs = $errors->get_error_messages();
                ob_start();
                ?>
				<?php 
                foreach ($msgs as $msg) {
                    ?>
					<div class="error inline"><p><?php 
                    echo $msg;
                    ?>
</p></div>
				<?php 
                }
                ?>
				<?php 
                $response = ob_get_clean();
                exit(json_encode(array("jsonrpc" => "2.0", "error" => array("code" => 102, "message" => $response), "id" => "id")));
            } else {
                // validate XML
                $file = new PMXI_Chunk($upload_result['filePath'], array('element' => $upload_result['root_element']));
                $is_valid = true;
                if (!empty($file->options['element'])) {
                    $defaultXpath = "/" . $file->options['element'];
                } else {
                    $is_valid = false;
                }
                if ($is_valid) {
                    while ($xml = $file->read()) {
                        if (!empty($xml)) {
                            PMXI_Import_Record::preprocessXml($xml);
                            $xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" . "\n" . $xml;
                            $dom = new DOMDocument('1.0', 'UTF-8');
                            $old = libxml_use_internal_errors(true);
                            $dom->loadXML($xml);
                            libxml_use_internal_errors($old);
                            $xpath = new DOMXPath($dom);
                            if ($elements = $xpath->query($defaultXpath) and $elements->length) {
                                break;
                            }
                        }
                        /*else {
                          	$is_valid = false;
                          	break;
                          }*/
                    }
                    if (empty($xml)) {
                        $is_valid = false;
                    }
                }
                unset($file);
                if (!preg_match('%\\W(xml)$%i', trim($upload_result['source']['path']))) {
                    @unlink($upload_result['filePath']);
                }
                if (!$is_valid) {
                    ob_start();
                    ?>
					
					<div class="error inline"><p><?php 
                    _e('Please confirm you are importing a valid feed.<br/> Often, feed providers distribute feeds with invalid data, improperly wrapped HTML, line breaks where they should not be, faulty character encodings, syntax errors in the XML, and other issues.<br/><br/>WP All Import has checks in place to automatically fix some of the most common problems, but we can’t catch every single one.<br/><br/>It is also possible that there is a bug in WP All Import, and the problem is not with the feed.<br/><br/>If you need assistance, please contact support – <a href="mailto:support@wpallimport.com">support@wpallimport.com</a> – with your XML/CSV file. We will identify the problem and release a bug fix if necessary.', 'wp_all_import_plugin');
                    ?>
</p></div>
					
					<?php 
                    $response = ob_get_clean();
                    exit(json_encode(array("jsonrpc" => "2.0", "error" => array("code" => 102, "message" => $response), "id" => "id")));
                } else {
                    $wp_uploads = wp_upload_dir();
                    $uploads = $wp_uploads['basedir'] . DIRECTORY_SEPARATOR . PMXI_Plugin::FILES_DIRECTORY . DIRECTORY_SEPARATOR;
                    if (!file_exists($uploads . basename($filePath))) {
                        @copy($filePath, $uploads . basename($filePath));
                    }
                }
                if (!empty($upload_result['post_type'])) {
                    $post_type = $upload_result['post_type'];
                }
            }
        }
        // Return JSON-RPC response
        exit(json_encode(array("jsonrpc" => "2.0", "error" => null, "result" => null, "id" => "id", "name" => $filePath, "post_type" => $post_type)));
    }
Example #14
0
 function filter($in, $out, &$consumed, $closing)
 {
     while ($bucket = stream_bucket_make_writeable($in)) {
         PMXI_Import_Record::preprocessXml($bucket->data);
         $is_remove_colons_from_rss = apply_filters('wp_all_import_remove_colons_from_rss', true);
         if ($is_remove_colons_from_rss) {
             $bucket->data = $this->replace_colons($bucket->data);
         }
         $consumed += $bucket->datalen;
         stream_bucket_append($out, $bucket);
     }
     return PSFS_PASS_ON;
 }
Example #15
0
 public static function link_template_to_import(&$export, $file_path, $foundPosts)
 {
     $exportOptions = $export->options;
     // associate exported posts with new import
     if (wp_all_export_is_compatible()) {
         $options = self::$templateOptions + PMXI_Plugin::get_default_import_options();
         $import = new PMXI_Import_Record();
         $import->getById($exportOptions['import_id']);
         if (!$import->isEmpty() and $import->parent_import_id == 99999) {
             $xmlPath = $file_path;
             $root_element = '';
             $historyPath = $file_path;
             if ('csv' == $exportOptions['export_to']) {
                 $is_secure_import = PMXE_Plugin::getInstance()->getOption('secure');
                 $options['delimiter'] = $exportOptions['delimiter'];
                 include_once PMXI_Plugin::ROOT_DIR . '/libraries/XmlImportCsvParse.php';
                 $path_info = pathinfo($xmlPath);
                 $path_parts = explode(DIRECTORY_SEPARATOR, $path_info['dirname']);
                 $security_folder = array_pop($path_parts);
                 $wp_uploads = wp_upload_dir();
                 $target = $is_secure_import ? $wp_uploads['basedir'] . DIRECTORY_SEPARATOR . PMXE_Plugin::UPLOADS_DIRECTORY . DIRECTORY_SEPARATOR . $security_folder : $wp_uploads['path'];
                 $csv = new PMXI_CsvParser(array('filename' => $xmlPath, 'targetDir' => $target));
                 if (!in_array($xmlPath, $exportOptions['attachment_list'])) {
                     $exportOptions['attachment_list'][] = $csv->xml_path;
                 }
                 $historyPath = $csv->xml_path;
                 $root_element = 'node';
             } else {
                 $root_element = apply_filters('wp_all_export_record_xml_tag', $exportOptions['record_xml_tag'], $export->id);
             }
             $import->set(array('xpath' => '/' . $root_element, 'type' => 'upload', 'options' => $options, 'root_element' => $root_element, 'path' => $xmlPath, 'name' => basename($xmlPath), 'imported' => 0, 'created' => 0, 'updated' => 0, 'skipped' => 0, 'deleted' => 0, 'iteration' => 1, 'count' => $foundPosts))->save();
             $history_file = new PMXI_File_Record();
             $history_file->set(array('name' => $import->name, 'import_id' => $import->id, 'path' => $historyPath, 'registered_on' => date('Y-m-d H:i:s')))->save();
             $exportOptions['import_id'] = $import->id;
             $export->set(array('options' => $exportOptions))->save();
         }
     }
 }
Example #16
0
 public function cleanup()
 {
     $removedFiles = 0;
     $wp_uploads = wp_upload_dir();
     $dir = $wp_uploads['basedir'] . DIRECTORY_SEPARATOR . PMXI_Plugin::TEMP_DIRECTORY;
     $cacheDir = PMXI_Plugin::ROOT_DIR . '/libraries/cache';
     $files = array_diff(@scandir($dir), array('.', '..'));
     $cacheFiles = @array_diff(@scandir($cacheDir), array('.', '..'));
     $msg = __('Files not found', 'wp_all_import_plugin');
     if (count($files) or count($cacheFiles)) {
         wp_all_import_clear_directory($dir);
         wp_all_import_clear_directory($cacheDir);
         $msg = __('Clean Up has been successfully completed.', 'wp_all_import_plugin');
     }
     // clean logs files
     $table = PMXI_Plugin::getInstance()->getTablePrefix() . 'history';
     global $wpdb;
     $histories = $wpdb->get_results("SELECT * FROM {$table}", ARRAY_A);
     if (!empty($histories)) {
         $importRecord = new PMXI_Import_Record();
         $importRecord->clear();
         foreach ($histories as $history) {
             $importRecord->getById($history['import_id']);
             if ($importRecord->isEmpty()) {
                 $historyRecord = new PMXI_History_Record();
                 $historyRecord->getById($history['id']);
                 if (!$historyRecord->isEmpty()) {
                     $historyRecord->delete();
                 }
             }
             $importRecord->clear();
         }
     }
     // clean uploads folder
     $table = PMXI_Plugin::getInstance()->getTablePrefix() . 'files';
     $files = $wpdb->get_results("SELECT * FROM {$table}", ARRAY_A);
     $required_dirs = array();
     if (!empty($files)) {
         $importRecord = new PMXI_Import_Record();
         $importRecord->clear();
         foreach ($files as $file) {
             $importRecord->getById($file['import_id']);
             if ($importRecord->isEmpty()) {
                 $fileRecord = new PMXI_File_Record();
                 $fileRecord->getById($file['id']);
                 if (!$fileRecord->isEmpty()) {
                     $fileRecord->delete();
                 }
             } else {
                 $path_parts = pathinfo(wp_all_import_get_absolute_path($file['path']));
                 if (!empty($path_parts['dirname'])) {
                     $path_all_parts = explode('/', $path_parts['dirname']);
                     $dirname = array_pop($path_all_parts);
                     if (wp_all_import_isValidMd5($dirname)) {
                         $required_dirs[] = $path_parts['dirname'];
                     }
                 }
             }
             $importRecord->clear();
         }
     }
     $uploads_dir = $wp_uploads['basedir'] . DIRECTORY_SEPARATOR . PMXI_Plugin::UPLOADS_DIRECTORY;
     if (($dir = @opendir($uploads_dir . DIRECTORY_SEPARATOR)) !== false or ($dir = @opendir($uploads_dir)) !== false) {
         while (($file = @readdir($dir)) !== false) {
             $filePath = $uploads_dir . DIRECTORY_SEPARATOR . $file;
             if (is_dir($filePath) and !in_array($filePath, $required_dirs) and !in_array($file, array('.', '..'))) {
                 wp_all_import_rmdir($filePath);
             }
         }
     }
     wp_redirect(add_query_arg('pmxi_nt', urlencode($msg), $this->baseUrl));
     die;
 }
 /**
  *
  *	Fires after wp_insert_post/wp_update_post
  *
  */
 public function import($post_id, $data, $import, $articleData, $logger)
 {
     // return if this is a basic post ( not a translation )
     if (empty($import['options']['wpml_addon']['matching_logic']) or empty($import['options']['wpml_addon']['import'])) {
         return;
     }
     // search for post to translate
     $parentImport = new PMXI_Import_Record();
     $parentImport->getById($import['options']['wpml_addon']['import']);
     if (!$parentImport->isEmpty()) {
         // post is that must be translated
         $parent_post_id = false;
         $postRecord = new PMXI_Post_Record();
         $postRecord->clear();
         $postRecord->getBy(array('unique_key' => $data['unique_key'], 'import_id' => $import['options']['wpml_addon']['import']));
         if (!$postRecord->isEmpty()) {
             $parent_post_id = $postRecord->post_id;
         }
         if ($parent_post_id) {
             $post_type = in_array(get_post_type($post_id), array('product', 'product_variation')) ? 'post_product' : 'post_' . get_post_type($post_id);
             $trid = $this->wpml->get_element_trid($parent_post_id, $post_type);
             if ($trid) {
                 global $wpdb;
                 // sync translation slug
                 $parent_post = get_post($parent_post_id);
                 if (!empty($parent_post) and $parent_post->post_title == $articleData['post_title']) {
                     $wpdb->update($wpdb->posts, array('post_name' => $parent_post->post_name), array('ID' => $post_id));
                 }
                 // create a translation
                 $tid = $this->wpml->set_element_language_details($post_id, $post_type, $trid, $import->options['wpml_addon']['lng'], $parentImport->options['wpml_addon']['lng']);
                 if (is_wp_error($tid)) {
                     $logger and call_user_func($logger, __('<b>ERROR</b>', 'wpml-all-import') . ': ' . $tid->get_error_message());
                 } else {
                     $logger and call_user_func($logger, sprintf(__('- Created `%s` translation for `%s`', 'wpml-all-import'), $import->options['wpml_addon']['lng'], $parent_post->post_title));
                 }
             }
         }
     }
 }
function pmxi_wp_ajax_upload_resource()
{
    if (!check_ajax_referer('wp_all_import_secure', 'security', false)) {
        exit(json_encode(array('success' => false, 'errors' => '<div class="error inline"><p>' . __('Security check', 'wp_all_import_plugin') . '</p></div>')));
    }
    if (!current_user_can('manage_options')) {
        exit(json_encode(array('success' => false, 'errors' => '<div class="error inline"><p>' . __('Security check', 'wp_all_import_plugin') . '</p></div>')));
    }
    $input = new PMXI_Input();
    $post = $input->post(array('type' => '', 'file' => ''));
    $response = array('success' => true, 'errors' => false, 'upload_result' => '', 'filesize' => 0);
    if ($post['type'] == 'url') {
        $filesXML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<data><node></node></data>";
        $files = XmlImportParser::factory($filesXML, '/data/node', $post['file'], $file)->parse();
        $tmp_files[] = $file;
        foreach ($tmp_files as $tmp_file) {
            // remove all temporary files created
            @unlink($tmp_file);
        }
        $file_to_import = $post['file'];
        if (!empty($files) and is_array($files)) {
            $file_to_import = array_shift($files);
        }
        $errors = new WP_Error();
        $uploader = new PMXI_Upload(trim($file_to_import), $errors);
        $upload_result = $uploader->url('', $post['file']);
        if ($upload_result instanceof WP_Error) {
            $errors = $upload_result;
            $msgs = $errors->get_error_messages();
            ob_start();
            ?>
			<?php 
            foreach ($msgs as $msg) {
                ?>
				<div class="error inline"><p><?php 
                echo $msg;
                ?>
</p></div>
			<?php 
            }
            ?>
			<?php 
            $response = array('success' => false, 'errors' => ob_get_clean());
        } else {
            // validate XML
            $file = new PMXI_Chunk($upload_result['filePath'], array('element' => $upload_result['root_element']));
            $is_valid = true;
            if (!empty($file->options['element'])) {
                $defaultXpath = "/" . $file->options['element'];
            } else {
                $is_valid = false;
            }
            if ($is_valid) {
                while ($xml = $file->read()) {
                    if (!empty($xml)) {
                        PMXI_Import_Record::preprocessXml($xml);
                        $xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" . "\n" . $xml;
                        $dom = new DOMDocument('1.0', 'UTF-8');
                        $old = libxml_use_internal_errors(true);
                        $dom->loadXML($xml);
                        libxml_use_internal_errors($old);
                        $xpath = new DOMXPath($dom);
                        if ($elements = $xpath->query($defaultXpath) and $elements->length) {
                            break;
                        }
                    }
                    /*else {
                      	$is_valid = false;
                      	break;
                      }*/
                }
                if (empty($xml)) {
                    $is_valid = false;
                }
            }
            unset($file);
            if (!$is_valid) {
                ob_start();
                ?>
				
				<div class="error inline"><p><?php 
                _e('Please confirm you are importing a valid feed.<br/> Often, feed providers distribute feeds with invalid data, improperly wrapped HTML, line breaks where they should not be, faulty character encodings, syntax errors in the XML, and other issues.<br/><br/>WP All Import has checks in place to automatically fix some of the most common problems, but we can’t catch every single one.<br/><br/>It is also possible that there is a bug in WP All Import, and the problem is not with the feed.<br/><br/>If you need assistance, please contact support – <a href="mailto:support@wpallimport.com">support@wpallimport.com</a> – with your XML/CSV file. We will identify the problem and release a bug fix if necessary.', 'wp_all_import_plugin');
                ?>
</p></div>
				
				<?php 
                $response = array('success' => false, 'errors' => ob_get_clean());
            } else {
                $response['upload_result'] = $upload_result;
                $response['filesize'] = filesize($upload_result['filePath']);
            }
        }
    }
    exit(json_encode($response));
}
Example #19
0
 /**
  * Step #3: Export
  */
 public function process()
 {
     @set_time_limit(0);
     $export = $this->data['update_previous'];
     if (!PMXE_Plugin::is_ajax()) {
         if ("" == PMXE_Plugin::$session->friendly_name) {
             $friendly_name = '';
             $post_types = PMXE_Plugin::$session->get('cpt');
             if (!empty($post_types)) {
                 if (!in_array('users', $post_types)) {
                     $post_type_details = get_post_type_object(array_shift($post_types));
                     $friendly_name = $post_type_details->labels->name . ' Export - ' . date("Y F d H:i");
                 } else {
                     $friendly_name = 'Users Export - ' . date("Y F d H:i");
                 }
             } else {
                 $friendly_name = 'WP_Query Export - ' . date("Y F d H:i");
             }
             PMXE_Plugin::$session->set('friendly_name', $friendly_name);
         }
         PMXE_Plugin::$session->set('file', '');
         PMXE_Plugin::$session->save_data();
         $export->set(array('triggered' => 0, 'processing' => 0, 'exported' => 0, 'executing' => 1, 'canceled' => 0, 'options' => PMXE_Plugin::$session->get_clear_session_data(), 'friendly_name' => PMXE_Plugin::$session->friendly_name, 'scheduled' => PMXE_Plugin::$session->is_scheduled ? PMXE_Plugin::$session->scheduled_period : '', 'registered_on' => date('Y-m-d H:i:s'), 'last_activity' => date('Y-m-d H:i:s')))->save();
         $options = $export->options;
         if ($options['is_generate_import'] and wp_all_export_is_compatible()) {
             $import = new PMXI_Import_Record();
             if (!empty($options['import_id'])) {
                 $import->getById($options['import_id']);
             }
             if ($import->isEmpty()) {
                 $import->set(array('parent_import_id' => 99999, 'xpath' => '/', 'type' => 'upload', 'options' => array('empty'), 'root_element' => 'root', 'path' => 'path', 'imported' => 0, 'created' => 0, 'updated' => 0, 'skipped' => 0, 'deleted' => 0, 'iteration' => 1))->save();
                 PMXE_Plugin::$session->set('import_id', $import->id);
                 $options['import_id'] = $import->id;
                 $export->set(array('options' => $options))->save();
             } else {
                 if ($import->parent_import_id != 99999) {
                     $newImport = new PMXI_Import_Record();
                     $newImport->set(array('parent_import_id' => 99999, 'xpath' => '/', 'type' => 'upload', 'options' => array('empty'), 'root_element' => 'root', 'path' => 'path', 'imported' => 0, 'created' => 0, 'updated' => 0, 'skipped' => 0, 'deleted' => 0, 'iteration' => 1))->save();
                     PMXE_Plugin::$session->set('import_id', $newImport->id);
                     $options['import_id'] = $newImport->id;
                     $export->set(array('options' => $options))->save();
                 }
             }
         }
         PMXE_Plugin::$session->set('update_previous', $export->id);
         PMXE_Plugin::$session->save_data();
     }
     $this->render();
 }
Example #20
0
 /**
  * Delete an import
  */
 public function delete()
 {
     $id = $this->input->get('id');
     $this->data['item'] = $item = new PMXI_Import_Record();
     if (!$id or $item->getById($id)->isEmpty()) {
         wp_redirect($this->baseUrl);
         die;
     }
     if ($this->input->post('is_confirmed')) {
         check_admin_referer('delete-import', '_wpnonce_delete-import');
         do_action('pmxi_before_import_delete', $item, $this->input->post('is_delete_posts'));
         $item->delete(!$this->input->post('is_delete_posts'));
         wp_redirect(add_query_arg('pmxi_nt', urlencode(__('Import deleted', 'wp_all_import_plugin')), $this->baseUrl));
         die;
     }
     $this->render();
 }
Example #21
0
 protected function get_xml($tagno = 0, $debug = false)
 {
     $xml = '';
     $update_previous = new PMXI_Import_Record();
     if (!empty(PMXI_Plugin::$session->update_previous)) {
         $update_previous->getById(PMXI_Plugin::$session->update_previous);
     }
     $local_paths = empty(PMXI_Plugin::$session->local_paths) ? array() : PMXI_Plugin::$session->local_paths;
     if (empty($local_paths) and !$update_previous->isEmpty()) {
         $history_file = new PMXI_File_Record();
         $history_file->getBy(array('import_id' => $update_previous->id), 'id DESC');
         $local_paths = !$history_file->isEmpty() ? array(wp_all_import_get_absolute_path($history_file->path)) : array();
     }
     if (!empty($local_paths)) {
         $loop = 0;
         foreach ($local_paths as $key => $path) {
             if (@file_exists($path)) {
                 $root_element = !$update_previous->isEmpty() ? $update_previous->root_element : PMXI_Plugin::$session->source['root_element'];
                 $file = new PMXI_Chunk($path, array('element' => $root_element, 'encoding' => PMXI_Plugin::$session->encoding));
                 while ($xml = $file->read()) {
                     if (!empty($xml)) {
                         PMXI_Import_Record::preprocessXml($xml);
                         $xml = "<?xml version=\"1.0\" encoding=\"" . PMXI_Plugin::$session->encoding . "\"?>" . "\n" . $xml;
                         if (PMXI_Plugin::$session->xpath) {
                             $dom = new DOMDocument('1.0', PMXI_Plugin::$session->encoding);
                             $old = libxml_use_internal_errors(true);
                             $dom->loadXML($xml);
                             libxml_use_internal_errors($old);
                             $xpath = new DOMXPath($dom);
                             if ($elements = $xpath->query(PMXI_Plugin::$session->xpath) and $elements->length) {
                                 $this->data['dom'] = $dom;
                                 $loop++;
                                 if (!$tagno or $loop == $tagno) {
                                     break;
                                 }
                             }
                         } else {
                             break;
                         }
                     }
                 }
                 unset($file);
             }
         }
     }
     return $xml;
 }
 function wp_all_import_get_url($filePath, $targetDir = false, $contentType = false, $contentEncoding = false, $detect = false)
 {
     $type = $contentType;
     $uploads = wp_upload_dir();
     $targetDir = !$targetDir ? wp_all_import_secure_file($uploads['basedir'] . DIRECTORY_SEPARATOR . PMXI_Plugin::UPLOADS_DIRECTORY) : $targetDir;
     $tmpname = wp_unique_filename($targetDir, ($type and strlen(basename($filePath)) < 30) ? basename($filePath) : time());
     $localPath = $targetDir . '/' . urldecode(sanitize_file_name($tmpname)) . (!$type ? '.tmp' : '');
     if ($contentEncoding == 'gzip') {
         $file = @fopen($filePath);
     } else {
         $file = @fopen($filePath, "rb");
     }
     $is_valid = false;
     if (is_resource($file)) {
         $fp = @fopen($localPath, 'w');
         $first_chunk = true;
         while (!@feof($file)) {
             $chunk = @fread($file, 1024);
             if (!$type and $first_chunk and (strpos($chunk, "<?") !== false or strpos($chunk, "<rss") !== false) or strpos($chunk, "xmlns") !== false) {
                 $type = 'xml';
             } elseif (!$type and $first_chunk) {
                 $type = 'csv';
             }
             // if it's a 1st chunk, then chunk <? symbols to detect XML file
             $first_chunk = false;
             @fwrite($fp, $chunk);
         }
         @fclose($file);
         @fclose($fp);
         $chunk = new PMXI_Chunk($localPath);
         $is_valid = true;
         if (!empty($chunk->options['element'])) {
             $defaultXpath = "/" . $chunk->options['element'];
         } else {
             $is_valid = false;
         }
         if ($is_valid) {
             while ($xml = $chunk->read()) {
                 if (!empty($xml)) {
                     PMXI_Import_Record::preprocessXml($xml);
                     $xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" . "\n" . $xml;
                     $dom = new DOMDocument('1.0', 'UTF-8');
                     $old = libxml_use_internal_errors(true);
                     $dom->loadXML($xml);
                     libxml_use_internal_errors($old);
                     $xpath = new DOMXPath($dom);
                     if ($elements = $xpath->query($defaultXpath) and $elements->length) {
                         break;
                     }
                 }
             }
             if (empty($xml)) {
                 $is_valid = false;
             }
         }
         unset($chunk);
     }
     if (!$is_valid) {
         $request = get_file_curl($filePath, $localPath);
         if (!is_wp_error($request)) {
             if (!$type) {
                 if ($contentEncoding == 'gzip') {
                     $file = @fopen($localPath);
                 } else {
                     $file = @fopen($localPath, "rb");
                 }
                 while (!@feof($file)) {
                     $chunk = @fread($file, 1024);
                     if (strpos($chunk, "<?") !== false or strpos($chunk, "<rss") !== false or strpos($chunk, "xmlns") !== false) {
                         $type = 'xml';
                     } else {
                         $type = 'csv';
                     }
                     // if it's a 1st chunk, then chunk <? symbols to detect XML file
                     break;
                 }
                 @fclose($file);
             }
         } else {
             return $request;
         }
     }
     if (!preg_match('%\\W(' . $type . ')$%i', basename($localPath))) {
         if (@rename($localPath, $localPath . '.' . $type)) {
             $localPath = $localPath . '.' . $type;
         }
     }
     return $detect ? array('type' => $type, 'localPath' => $localPath) : $localPath;
 }
Example #23
0
 /**
  * Delete an import
  */
 public function delete()
 {
     $id = $this->input->get('id');
     $this->data['item'] = $item = new PMXI_Import_Record();
     if (!$id or $item->getById($id)->isEmpty()) {
         wp_redirect($this->baseUrl);
         die;
     }
     if ($this->input->post('is_confirmed')) {
         check_admin_referer('delete-import', '_wpnonce_delete-import');
         $is_deleted_images = $this->input->post('is_delete_images');
         $is_delete_attachments = $this->input->post('is_delete_attachments');
         $is_delete_import = $this->input->post('is_delete_import', false);
         $is_delete_posts = $this->input->post('is_delete_posts', false);
         if (!$is_delete_import and !$is_delete_posts) {
             wp_redirect(add_query_arg('pmxi_nt', urlencode(__('Nothing to delete.', 'wp_all_import_plugin')), $this->baseUrl));
             die;
         }
         do_action('pmxi_before_import_delete', $item, $is_delete_posts);
         $item->delete(!$is_delete_posts, $is_deleted_images, $is_delete_attachments, $is_delete_import);
         $redirect_msg = '';
         if ($is_delete_import and !$is_delete_posts) {
             $redirect_msg = __('Import deleted', 'wp_all_import_plugin');
         } elseif (!$is_delete_import and $is_delete_posts) {
             $redirect_msg = __('All associated posts deleted.', 'wp_all_import_plugin');
         } elseif ($is_delete_import and $is_delete_posts) {
             $redirect_msg = __('Import and all associated posts deleted.', 'wp_all_import_plugin');
         }
         wp_redirect(add_query_arg('pmxi_nt', urlencode($redirect_msg), $this->baseUrl));
         die;
     }
     $postList = new PMXI_Post_List();
     $this->data['associated_posts'] = count($postList->getBy(array('import_id' => $item->id)));
     $this->render();
 }
Example #24
0
 public static function removeColonsFromRSS($feed)
 {
     $feed = str_replace("_colon_", ":", $feed);
     // pull out colons from start tags
     // (<\w+):(\w+>)
     $pattern = '/(<\\w+):([\\w+|\\.|-]+[ |>]{1})/i';
     $replacement = '$1_$2';
     $feed = preg_replace($pattern, $replacement, $feed);
     // pull out colons from end tags
     // (<\/\w+):(\w+>)
     $pattern = '/(<\\/\\w+):([\\w+|\\.|-]+>)/i';
     $replacement = '$1_$2';
     $feed = preg_replace($pattern, $replacement, $feed);
     // pull out colons from attributes
     $pattern = '/(\\s+\\w+):(\\w+[=]{1})/i';
     $replacement = '$1_$2';
     $feed = preg_replace($pattern, $replacement, $feed);
     // pull colons from single element
     // (<\w+):(\w+\/>)
     $pattern = '/(<\\w+):([\\w+|\\.|-]+\\/>)/i';
     $replacement = '$1_$2';
     $feed = preg_replace($pattern, $replacement, $feed);
     $is_preprocess_enabled = apply_filters('is_xml_preprocess_enabled', true);
     if ($is_preprocess_enabled) {
         // replace temporary word _ampersand_ back to & symbol
         $feed = str_replace("_ampersand_", "&", $feed);
     }
     // replace all standalone & symbols ( which is not in htmlentities e.q. &nbsp; and not wrapped in CDATA section ) to &amp;
     PMXI_Import_Record::preprocessXml($feed);
     return $feed;
 }
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;
                    }
                }
            }
        }
    }
}
Example #26
0
 /**
  * Import all files matched by path
  * @param callback[optional] $logger Method where progress messages are submmitted
  * @return PMXI_Import_Record
  * @chainable
  */
 public function execute($logger = NULL, $cron = true, $history_log_id = false)
 {
     $uploads = wp_upload_dir();
     if ($this->path) {
         $files = array($this->path);
         foreach ($files as $ind => $path) {
             $filePath = '';
             if ($this->queue_chunk_number == 0 and $this->processing == 0) {
                 $this->set(array('processing' => 1))->update();
                 // lock cron requests
                 if ($this->type == 'ftp') {
                     $this->set(array('processing' => 0))->update();
                     return array('status' => 500, 'message' => sprintf(__('This import appears to be using FTP. Unfortunately WP All Import no longer supports the FTP protocol. Please contact <a href="mailto:support@wpallimport.com">%s</a> if you have any questions.', 'wp_all_import_plugin'), '*****@*****.**'));
                     //$logger and call_user_func($logger, sprintf(__('This import appears to be using FTP. Unfortunately WP All Import no longer supports the FTP protocol. Please contact <a href="mailto:support@wpallimport.com">%s</a> if you have any questions.', 'wp_all_import_plugin'), '*****@*****.**'));
                     die;
                 } elseif ($this->type == 'url') {
                     $filesXML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<data><node></node></data>";
                     $filePaths = XmlImportParser::factory($filesXML, '/data/node', $this->path, $file)->parse();
                     $tmp_files[] = $file;
                     foreach ($tmp_files as $tmp_file) {
                         // remove all temporary files created
                         @unlink($tmp_file);
                     }
                     $file_to_import = $this->path;
                     if (!empty($filePaths) and is_array($filePaths)) {
                         $file_to_import = array_shift($filePaths);
                     }
                     $uploader = new PMXI_Upload(trim($file_to_import), $this->errors);
                     $upload_result = $uploader->url($this->feed_type, $this->path);
                     if ($upload_result instanceof WP_Error) {
                         $this->errors = $upload_result;
                     } else {
                         $filePath = $upload_result['filePath'];
                     }
                 } elseif ($this->type == 'file') {
                     $uploader = new PMXI_Upload(trim(basename($this->path)), $this->errors);
                     $upload_result = $uploader->file();
                     if ($upload_result instanceof WP_Error) {
                         $this->errors = $upload_result;
                     } else {
                         $filePath = $upload_result['filePath'];
                     }
                 } elseif (!in_array($this->type, array('ftp'))) {
                     // retrieve already uploaded file
                     $uploader = new PMXI_Upload(trim($this->path), $this->errors, rtrim(str_replace(basename($this->path), '', $this->path), '/'));
                     $upload_result = $uploader->upload();
                     if ($upload_result instanceof WP_Error) {
                         $this->errors = $upload_result;
                     } else {
                         $filePath = $upload_result['filePath'];
                     }
                 }
                 if (!$this->errors->get_error_codes() and "" != $filePath) {
                     $this->set(array('queue_chunk_number' => 1))->update();
                 } elseif ($this->errors->get_error_codes()) {
                     $msgs = $this->errors->get_error_messages();
                     if (!is_array($msgs)) {
                         $msgs = array($msgs);
                     }
                     // foreach ($msgs as $msg){
                     // 	$logger and call_user_func($logger, sprintf(__('ERROR: %s', 'wp_all_import_plugin'), $msg));
                     // }
                     $this->set(array('processing' => 0))->update();
                     return array('status' => 500, 'message' => $msgs);
                     die;
                 }
                 $this->set(array('processing' => 0))->update();
                 // unlock cron requests
             }
             // if empty file path, than it's mean feed in cron process. Take feed path from history.
             if (empty($filePath)) {
                 $history = new PMXI_File_List();
                 $history->setColumns('id', 'name', 'registered_on', 'path')->getBy(array('import_id' => $this->id), 'id DESC');
                 if ($history->count()) {
                     $history_file = new PMXI_File_Record();
                     $history_file->getBy('id', $history[0]['id']);
                     $filePath = wp_all_import_get_absolute_path($history_file->path);
                 }
             }
             // if feed path found
             if (!empty($filePath) and @file_exists($filePath)) {
                 if ($this->queue_chunk_number === 1 and $this->processing == 0) {
                     // import first cron request
                     $this->set(array('processing' => 1))->update();
                     // lock cron requests
                     if (empty($this->options['encoding'])) {
                         $currentOptions = $this->options;
                         $currentOptions['encoding'] = 'UTF-8';
                         $this->set(array('options' => $currentOptions))->update();
                     }
                     set_time_limit(0);
                     $file = new PMXI_Chunk($filePath, array('element' => $this->root_element, 'encoding' => $this->options['encoding']));
                     // chunks counting
                     $chunks = 0;
                     $history_xml = '';
                     while ($xml = $file->read()) {
                         if (!empty($xml)) {
                             PMXI_Import_Record::preprocessXml($xml);
                             $xml = "<?xml version=\"1.0\" encoding=\"" . $this->options['encoding'] . "\"?>" . "\n" . $xml;
                             $dom = new DOMDocument('1.0', !empty($this->options['encoding']) ? $this->options['encoding'] : 'UTF-8');
                             $old = libxml_use_internal_errors(true);
                             $dom->loadXML($xml);
                             libxml_use_internal_errors($old);
                             $xpath = new DOMXPath($dom);
                             if ($elements = @$xpath->query($this->xpath) and $elements->length) {
                                 $chunks += $elements->length;
                                 if ("" == $history_xml) {
                                     $history_xml = $xml;
                                 }
                             }
                             unset($dom, $xpath, $elements);
                         }
                     }
                     unset($file);
                     if (!$chunks) {
                         //$logger and call_user_func($logger, sprintf(__('#%s No matching elements found for Root element and XPath expression specified', 'wp_all_import_plugin'), $this->id));
                         $this->set(array('queue_chunk_number' => 0, 'processing' => 0, 'imported' => 0, 'created' => 0, 'updated' => 0, 'skipped' => 0, 'deleted' => 0, 'triggered' => 0))->update();
                         return array('status' => 500, 'message' => sprintf(__('#%s No matching elements found for Root element and XPath expression specified', 'wp_all_import_plugin'), $this->id));
                         die;
                     }
                     // unlick previous files
                     $history = new PMXI_File_List();
                     $history->setColumns('id', 'name', 'registered_on', 'path')->getBy(array('import_id' => $this->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 != $filePath) {
                                 if (in_array($this->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($history_file_path != $filePath);
                             }
                         }
                     }
                     // update history
                     $history_file = new PMXI_File_Record();
                     $history_file->set(array('name' => $this->name, 'import_id' => $this->id, 'path' => wp_all_import_get_relative_path($filePath), 'registered_on' => date('Y-m-d H:i:s')))->insert();
                     do_action('pmxi_before_xml_import', $this->id);
                     $this->set(array('count' => $chunks, 'processing' => 0))->update();
                     // set pointer to the first chunk, updates feed elements count and unlock cron process
                 }
                 // compose data to look like result of wizard steps
                 if ($this->queue_chunk_number and $this->processing == 0) {
                     $this->set(array('processing' => 1))->update();
                     // lock cron requests
                     @set_time_limit(0);
                     $file = new PMXI_Chunk($filePath, array('element' => $this->root_element, 'encoding' => $this->options['encoding'], 'pointer' => $this->queue_chunk_number));
                     $feed = "<?xml version=\"1.0\" encoding=\"" . $this->options['encoding'] . "\"?>" . "\n" . "<pmxi_records>";
                     $loop = 0;
                     $xml = '';
                     $processing_time_limit = PMXI_Plugin::getInstance()->getOption('cron_processing_time_limit') ? PMXI_Plugin::getInstance()->getOption('cron_processing_time_limit') : 120;
                     $start_rocessing_time = time();
                     $chunk_number = $this->queue_chunk_number;
                     $functions = $uploads['basedir'] . DIRECTORY_SEPARATOR . WP_ALL_IMPORT_UPLOADS_BASE_DIRECTORY . DIRECTORY_SEPARATOR . 'functions.php';
                     if (@file_exists($functions)) {
                         require_once $functions;
                     }
                     while ($xml = $file->read() and $this->processing == 1 and time() - $start_rocessing_time <= $processing_time_limit) {
                         if (!empty($xml)) {
                             $chunk_number++;
                             PMXI_Import_Record::preprocessXml($xml);
                             $xml_chunk = "<?xml version=\"1.0\" encoding=\"" . $this->options['encoding'] . "\"?>" . "\n" . $xml;
                             $dom = new DOMDocument('1.0', !empty($this->options['encoding']) ? $this->options['encoding'] : 'UTF-8');
                             $old = libxml_use_internal_errors(true);
                             $dom->loadXML($xml_chunk);
                             libxml_use_internal_errors($old);
                             $xpath = new DOMXPath($dom);
                             if ($elements = @$xpath->query($this->xpath) and $elements->length) {
                                 $feed .= $xml;
                                 $loop += $elements->length;
                             }
                             unset($dom, $xpath, $elements);
                         }
                         if ($loop == $this->options['records_per_request'] or $this->count == $this->imported + $this->skipped or $this->count == $loop + $this->imported + $this->skipped) {
                             // skipping scheduled imports if any for the next hit
                             $feed .= "</pmxi_records>";
                             $this->process($feed, $logger, $chunk_number, $cron, '/pmxi_records', $loop);
                             // set last update
                             $this->set(array('registered_on' => date('Y-m-d H:i:s'), 'queue_chunk_number' => $chunk_number))->update();
                             $loop = 0;
                             $feed = "<?xml version=\"1.0\" encoding=\"" . $this->options['encoding'] . "\"?>" . "\n" . "<pmxi_records>";
                         }
                     }
                     unset($file);
                     // delect, if cron process if finished
                     if ((int) $this->count <= (int) $this->imported + (int) $this->skipped) {
                         // Delete posts that are no longer present in your file
                         if (!empty($this->options['is_delete_missing']) and $this->options['duplicate_matching'] == 'auto') {
                             $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)) {
                                 $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;
                                             }
                                             // Instead of deletion, change post status to Draft
                                             $final_post_type = get_post_type($pid);
                                             if ($this->options['set_missing_to_draft'] and $final_post_type != 'product_variation') {
                                                 $this->wpdb->update($this->wpdb->posts, array('post_status' => 'draft'), array('ID' => $id));
                                                 $to_delete = false;
                                             }
                                             // Delete posts that are no longer present in your file
                                             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 ($this->options['custom_type'] != "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\t\t\t\tFROM " . $this->wpdb->users . " a\n\t\t\t\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\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\t\t\t\tFROM " . $this->wpdb->posts . " a\n\t\t\t\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\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\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 (empty($this->options['is_delete_missing']) and $this->options['custom_type'] == "product" and class_exists('PMWI_Plugin') and !empty($this->options['missing_records_stock_status'])) {
                             $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);
                                     $postRecord = new PMXI_Post_Record();
                                     $postRecord->getBy('id', $missingPost['id']);
                                     if (!$postRecord->isEmpty()) {
                                         $postRecord->set(array('iteration' => $this->iteration))->update();
                                     }
                                     unset($postRecord);
                                 }
                             }
                         }
                         $this->set(array('processing' => 0, 'triggered' => 0, 'queue_chunk_number' => 0, 'registered_on' => date('Y-m-d H:i:s'), 'iteration' => ++$this->iteration))->update();
                         wp_cache_flush();
                         foreach (get_taxonomies() as $tax) {
                             delete_option("{$tax}_children");
                             _get_term_hierarchy($tax);
                         }
                         if ($history_log_id) {
                             $history_log = new PMXI_History_Record();
                             $history_log->getById($history_log_id);
                             if (!$history_log->isEmpty()) {
                                 $custom_type = get_post_type_object($this->options['custom_type']);
                                 $history_log->set(array('time_run' => time() - strtotime($history_log->date), 'summary' => sprintf(__("import finished & cron un-triggered<br>%s %s created %s updated %s deleted %s skipped", "pmxi_plugin"), $this->created, $custom_type->labels->name, $this->updated, $this->deleted, $this->skipped)))->save();
                             }
                         }
                         do_action('pmxi_after_xml_import', $this->id);
                         return array('status' => 200, 'message' => sprintf(__('Import #%s complete', 'wp_all_import_plugin'), $this->id));
                         //$logger and call_user_func($logger, sprintf(__('Import #%s complete', 'wp_all_import_plugin'), $this->id));
                     } else {
                         $this->set(array('processing' => 0))->update();
                         if ($history_log_id) {
                             $history_log = new PMXI_History_Record();
                             $history_log->getById($history_log_id);
                             if (!$history_log->isEmpty()) {
                                 $custom_type = get_post_type_object($this->options['custom_type']);
                                 $history_log->set(array('time_run' => time() - strtotime($history_log->date), 'summary' => sprintf(__("%d %s created %d updated %d deleted %d skipped", "pmxi_plugin"), $this->created, $custom_type->labels->name, $this->updated, $this->deleted, $this->skipped)))->save();
                             }
                         }
                         return array('status' => 200, 'message' => sprintf(__('Records Processed %s. Records Count %s.', 'wp_all_import_plugin'), (int) $this->queue_chunk_number, (int) $this->count));
                         // $logger and call_user_func($logger, sprintf(__('Records Count %s', 'wp_all_import_plugin'), (int) $this->count));
                         // $logger and call_user_func($logger, sprintf(__('Records Processed %s', 'wp_all_import_plugin'), (int) $this->imported + (int) $this->skipped));
                     }
                 }
             } else {
                 $this->set(array('processing' => 0, 'triggered' => 0, 'queue_chunk_number' => 0, 'imported' => 0, 'created' => 0, 'updated' => 0, 'skipped' => 0, 'deleted' => 0))->update();
                 return array('status' => 500, 'message' => sprintf(__('#%s source file not found', 'wp_all_import_plugin'), $this->id));
                 //$logger and call_user_func($logger, sprintf(__('#%s source file not found', 'wp_all_import_plugin'), $this->id));
                 die;
             }
         }
     }
     return $this;
 }
 function helper_current_field_values($default = array())
 {
     if (empty($default)) {
         $options = array('mapping' => array(), 'xpaths' => array());
         foreach ($this->fields as $field_slug => $field_params) {
             $options[$field_slug] = '';
             if (!empty($field_params['enum_values'])) {
                 foreach ($field_params['enum_values'] as $key => $value) {
                     $options[$field_slug] = is_numeric($key) ? (int) $key : $key;
                     break;
                 }
             }
         }
         $default = array($this->slug => $options);
     }
     $input = new PMXI_Input();
     $id = $input->get('id');
     $import = new PMXI_Import_Record();
     if (!$id or $import->getById($id)->isEmpty()) {
         // specified import is not found
         $post = $input->post($default);
     } else {
         $post = $input->post($import->options + $default);
     }
     $is_loaded_template = !empty(PMXI_Plugin::$session->is_loaded_template) ? PMXI_Plugin::$session->is_loaded_template : false;
     $load_options = $input->post('load_template');
     if ($load_options) {
         // init form with template selected
         $template = new PMXI_Template_Record();
         if (!$template->getById($is_loaded_template)->isEmpty()) {
             $post = (!empty($template->options) ? $template->options : array()) + $default;
         }
     } elseif ($load_options == -1) {
         $post = $default;
     }
     return $post;
 }
Example #28
0
function pmai_wp_ajax_get_acf()
{
    if (!check_ajax_referer('wp_all_import_secure', 'security', false)) {
        exit(json_encode(array('html' => __('Security check', 'wp_all_import_plugin'))));
    }
    if (!current_user_can('manage_options')) {
        exit(json_encode(array('html' => __('Security check', 'wp_all_import_plugin'))));
    }
    global $acf;
    $version = $acf ? $acf->settings['version'] : false;
    ob_start();
    $acf_groups = PMXI_Plugin::$session->acf_groups;
    $acf_obj = false;
    if (!empty($acf_groups)) {
        foreach ($acf_groups as $key => $group) {
            if ($group['ID'] == $_GET['acf']) {
                $acf_obj = $group;
                break;
            }
        }
    }
    $import = new PMXI_Import_Record();
    if (!empty($_GET['id'])) {
        $import->getById($_GET['id']);
    }
    $is_loaded_template = !empty(PMXI_Plugin::$session->is_loaded_template) ? PMXI_Plugin::$session->is_loaded_template : false;
    if ($is_loaded_template) {
        $default = PMAI_Plugin::get_default_import_options();
        $template = new PMXI_Template_Record();
        if (!$template->getById($is_loaded_template)->isEmpty()) {
            $options = (!empty($template->options) ? $template->options : array()) + $default;
        }
    } else {
        if (!$import->isEmpty()) {
            $options = $import->options;
        } else {
            $options = PMXI_Plugin::$session->options;
        }
    }
    ?>
	<div class="postbox  acf_postbox default acf_signle_group rad4" rel="<?php 
    echo $acf_obj['ID'];
    ?>
">
		<h3 class="hndle" style="margin-top:0;"><span><?php 
    echo $acf_obj['title'];
    ?>
</span></h3>
		<div class="inside">
		<?php 
    if ($version and version_compare($version, '5.0.0') >= 0) {
        if (is_numeric($acf_obj['ID'])) {
            $acf_fields = get_posts(array('posts_per_page' => -1, 'post_type' => 'acf-field', 'post_parent' => $_GET['acf'], 'post_status' => 'publish', 'orderby' => 'menu_order', 'order' => 'ASC'));
            if (!empty($acf_fields)) {
                foreach ($acf_fields as $field) {
                    $fieldData = !empty($field->post_content) ? unserialize($field->post_content) : array();
                    $fieldData['ID'] = $field->ID;
                    $fieldData['id'] = $field->ID;
                    $fieldData['label'] = $field->post_title;
                    $fieldData['key'] = $field->post_name;
                    if (empty($fieldData['name'])) {
                        $fieldData['name'] = $field->post_excerpt;
                    }
                    echo pmai_render_field($fieldData, !empty($options) ? $options : array());
                }
            }
        } else {
            $fields = acf_local()->fields;
            if (!empty($fields)) {
                foreach ($fields as $key => $field) {
                    if ($field['parent'] == $acf_obj['key']) {
                        $fieldData = $field;
                        $fieldData['id'] = uniqid();
                        $fieldData['label'] = $field['label'];
                        $fieldData['key'] = $field['key'];
                        echo pmai_render_field($fieldData, !empty($options) ? $options : array());
                    }
                }
            }
        }
    } else {
        if (is_numeric($acf_obj['ID'])) {
            $fields = array();
            foreach (get_post_meta($acf_obj['ID'], '') as $cur_meta_key => $cur_meta_val) {
                if (strpos($cur_meta_key, 'field_') !== 0) {
                    continue;
                }
                $fields[] = !empty($cur_meta_val[0]) ? unserialize($cur_meta_val[0]) : array();
            }
            if (count($fields)) {
                $sortArray = array();
                foreach ($fields as $field) {
                    foreach ($field as $key => $value) {
                        if (!isset($sortArray[$key])) {
                            $sortArray[$key] = array();
                        }
                        $sortArray[$key][] = $value;
                    }
                }
                $orderby = "order_no";
                array_multisort($sortArray[$orderby], SORT_ASC, $fields);
                foreach ($fields as $field) {
                    echo pmai_render_field($field, !empty($options) ? $options : array());
                }
            }
        } else {
            global $acf_register_field_group;
            if (!empty($acf_register_field_group)) {
                foreach ($acf_register_field_group as $key => $group) {
                    if ($group['id'] == $acf_obj['ID']) {
                        foreach ($group['fields'] as $field) {
                            echo pmai_render_field($field, !empty($options) ? $options : array());
                        }
                    }
                }
            }
        }
    }
    ?>
								
		</div>
	</div>
	<?php 
    exit(json_encode(array('html' => ob_get_clean())));
    die;
}