/** * AJAX action for preview export row */ function pmxe_wp_ajax_wpae_preview() { if (!check_ajax_referer('wp_all_export_secure', 'security', false)) { exit(json_encode(array('html' => __('Security check', 'wp_all_export_plugin')))); } if (!current_user_can(PMXE_Plugin::$capabilities)) { exit(json_encode(array('html' => __('Security check', 'wp_all_export_plugin')))); } XmlExportEngine::$is_preview = true; $custom_xml_valid = true; ob_start(); $values = array(); parse_str($_POST['data'], $values); $export_id = isset($_GET['id']) ? stripcslashes($_GET['id']) : 0; $exportOptions = $values + (PMXE_Plugin::$session->has_session() ? PMXE_Plugin::$session->get_clear_session_data() : array()) + PMXE_Plugin::get_default_import_options(); $exportOptions['custom_xml_template'] = isset($_POST['custom_xml']) ? stripcslashes($_POST['custom_xml']) : ''; $exportOptions['custom_xml_template'] = str_replace('<ID>', '<id>', $exportOptions['custom_xml_template']); $exportOptions['custom_xml_template'] = str_replace('</ID>', '</id>', $exportOptions['custom_xml_template']); if (!empty($exportOptions['custom_xml_template'])) { $custom_xml_template_line_count = substr_count($exportOptions['custom_xml_template'], "\n"); } $errors = new WP_Error(); $engine = new XmlExportEngine($exportOptions, $errors); XmlExportEngine::$exportOptions = $exportOptions; XmlExportEngine::$is_user_export = $exportOptions['is_user_export']; XmlExportEngine::$is_comment_export = $exportOptions['is_comment_export']; XmlExportEngine::$exportID = $export_id; if (in_array(XmlExportEngine::$exportOptions['xml_template_type'], array('custom', 'XmlGoogleMerchants'))) { if (empty(XmlExportEngine::$exportOptions['custom_xml_template'])) { $errors->add('form-validation', __('XML template is empty.', 'wp_all_export_plugin')); } if (!empty(XmlExportEngine::$exportOptions['custom_xml_template'])) { $engine->init_additional_data(); $engine->init_available_data(); $result = $engine->parse_custom_xml_template(); $line_numbers = $result['line_numbers']; if (!$errors->get_error_codes()) { XmlExportEngine::$exportOptions = array_merge(XmlExportEngine::$exportOptions, $result); } $originalXmlTemplate = $exportOptions['custom_xml_template']; libxml_use_internal_errors(true); libxml_clear_errors(); //Add root se we make sure there is a root tag $result['original_post_loop'] = '<root>' . $result['original_post_loop'] . '</root>'; $custom_xml_template = simplexml_load_string($result['original_post_loop']); if ($custom_xml_template === false) { $custom_xml_template_errors = libxml_get_errors(); libxml_clear_errors(); $custom_xml_valid = false; // Remove one line because we added root $line_difference = $custom_xml_template_line_count - $line_numbers - 1; } $exportOptions['custom_xml_template'] = str_replace("<!-- BEGIN POST LOOP -->", "<!-- BEGIN LOOP -->", $exportOptions['custom_xml_template']); $exportOptions['custom_xml_template'] = str_replace("<!-- END POST LOOP -->", "<!-- END LOOP -->", $exportOptions['custom_xml_template']); } } if (isset($_GET['show_cdata'])) { XmlExportEngine::$exportOptions['show_cdata_in_preview'] = (bool) $_GET['show_cdata']; } else { XmlExportEngine::$exportOptions['show_cdata_in_preview'] = false; } if ($errors->get_error_codes()) { $msgs = $errors->get_error_messages(); if (!is_array($msgs)) { $msgs = array($msgs); } foreach ($msgs as $msg) { ?> <div class="error"><p><?php echo $msg; ?> </p></div> <?php } exit(json_encode(array('html' => ob_get_clean()))); } if ('advanced' == $exportOptions['export_type']) { if (XmlExportEngine::$is_user_export) { $exportQuery = eval('return new WP_User_Query(array(' . $exportOptions['wp_query'] . ', \'offset\' => 0, \'number\' => 10));'); } elseif (XmlExportEngine::$is_comment_export) { $exportQuery = eval('return new WP_Comment_Query(array(' . $exportOptions['wp_query'] . ', \'offset\' => 0, \'number\' => 10));'); } else { $exportQuery = eval('return new WP_Query(array(' . $exportOptions['wp_query'] . ', \'offset\' => 0, \'posts_per_page\' => 10));'); } } else { XmlExportEngine::$post_types = $exportOptions['cpt']; if (in_array('users', $exportOptions['cpt']) or in_array('shop_customer', $exportOptions['cpt'])) { add_action('pre_user_query', 'wp_all_export_pre_user_query', 10, 1); $exportQuery = new WP_User_Query(array('orderby' => 'ID', 'order' => 'ASC', 'number' => 10)); remove_action('pre_user_query', 'wp_all_export_pre_user_query'); } elseif (in_array('comments', $exportOptions['cpt'])) { add_action('comments_clauses', 'wp_all_export_comments_clauses', 10, 1); global $wp_version; if (version_compare($wp_version, '4.2.0', '>=')) { $exportQuery = new WP_Comment_Query(array('orderby' => 'comment_ID', 'order' => 'ASC', 'number' => 10)); } else { $exportQuery = get_comments(array('orderby' => 'comment_ID', 'order' => 'ASC', 'number' => 10)); } remove_action('comments_clauses', 'wp_all_export_comments_clauses'); } else { remove_all_actions('parse_query'); remove_all_actions('pre_get_posts'); remove_all_filters('posts_clauses'); add_filter('posts_join', 'wp_all_export_posts_join', 10, 1); add_filter('posts_where', 'wp_all_export_posts_where', 10, 1); $exportQuery = new WP_Query(array('post_type' => $exportOptions['cpt'], 'post_status' => 'any', 'orderby' => 'title', 'order' => 'ASC', 'posts_per_page' => 10)); remove_filter('posts_where', 'wp_all_export_posts_where'); remove_filter('posts_join', 'wp_all_export_posts_join'); } } XmlExportEngine::$exportQuery = $exportQuery; $engine->init_additional_data(); ?> <div id="post-preview" class="wpallexport-preview"> <p class="wpallexport-preview-title"><?php echo sprintf("Preview first 10 %s", wp_all_export_get_cpt_name($exportOptions['cpt'], 10)); ?> </p> <div class="wpallexport-preview-content"> <?php if (!$custom_xml_valid) { $error_msg = '<strong class="error">' . __('Invalid XML', 'wp_all_import_plugin') . '</strong><ul class="error">'; foreach ($custom_xml_template_errors as $error) { $error_msg .= '<li>'; $error_msg .= __('Line', 'wp_all_import_plugin') . ' ' . ($error->line + $line_difference) . ', '; $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>'; echo $error_msg; exit(json_encode(array('html' => ob_get_clean()))); } $wp_uploads = wp_upload_dir(); $functions = $wp_uploads['basedir'] . DIRECTORY_SEPARATOR . WP_ALL_EXPORT_UPLOADS_BASE_DIRECTORY . DIRECTORY_SEPARATOR . 'functions.php'; if (@file_exists($functions)) { require_once $functions; } switch ($exportOptions['export_to']) { case 'xml': $dom = new DOMDocument('1.0', $exportOptions['encoding']); libxml_use_internal_errors(true); try { $xml = XmlCsvExport::export_xml(true); } catch (WpaeMethodNotFoundException $e) { // Find the line where the function is $errorMessage = ''; $functionName = $e->getMessage(); $txtParts = explode("\n", $originalXmlTemplate); for ($i = 0, $length = count($txtParts); $i < $length; $i++) { $tmp = strstr($txtParts[$i], $functionName); if ($tmp) { $errorMessage .= 'Error parsing XML feed: Call to undefined function <em>"' . $functionName . '"</em> on Line ' . ($i + 1); } } $error_msg = '<span class="error">' . __($errorMessage, 'wp_all_import_plugin') . '</span>'; echo $error_msg; exit(json_encode(array('html' => ob_get_clean()))); } catch (WpaeInvalidStringException $e) { // Find the line where the function is $errorMessage = ''; $functionName = $e->getMessage(); $txtParts = explode("\n", $originalXmlTemplate); for ($i = 0, $length = count($txtParts); $i < $length; $i++) { $tmp = strstr($txtParts[$i], $functionName); if ($tmp) { $errorMessage .= 'Error parsing XML feed: Unterminated string on line ' . ($i + 1); } } $error_msg = '<span class="error">' . __($errorMessage, 'wp_all_import_plugin') . '</span>'; echo $error_msg; exit(json_encode(array('html' => ob_get_clean()))); } catch (WpaeTooMuchRecursionException $e) { $errorMessage = __('There was a problem parsing the custom XML template'); $error_msg = '<span class="error">' . __($errorMessage, 'wp_all_import_plugin') . '</span>'; echo $error_msg; exit(json_encode(array('html' => ob_get_clean()))); } $xml_errors = false; $main_xml_tag = ''; switch (XmlExportEngine::$exportOptions['xml_template_type']) { case 'custom': case 'XmlGoogleMerchants': require_once PMXE_ROOT_DIR . '/classes/XMLWriter.php'; $preview_xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" . "\n<Preview>\n" . $xml . "\n</Preview>"; $preview_xml = str_replace('<![CDATA[', 'CDATABEGIN', $preview_xml); $preview_xml = str_replace(']]>', 'CDATACLOSE', $preview_xml); $preview_xml = str_replace('&', '&', $preview_xml); $preview_xml = str_replace('&', '&', $preview_xml); $xml = PMXE_XMLWriter::preprocess_xml(XmlExportEngine::$exportOptions['custom_xml_template_header']) . "\n" . $xml . "\n" . PMXE_XMLWriter::preprocess_xml(XmlExportEngine::$exportOptions['custom_xml_template_footer']); $xml = str_replace('<![CDATA[', 'CDATABEGIN', $xml); $xml = str_replace(']]>', 'CDATACLOSE', $xml); $xml = str_replace('&', '&', $xml); $xml = str_replace('&', '&', $xml); // Determine XML root element preg_match_all("%<[\\w]+[\\s|>]{1}%", XmlExportEngine::$exportOptions['custom_xml_template_header'], $matches); if (!empty($matches[0])) { $main_xml_tag = preg_replace("%[\\s|<|>]%", "", array_shift($matches[0])); } libxml_clear_errors(); $dom->loadXML($xml); $xml_errors = libxml_get_errors(); libxml_clear_errors(); if (!$xml_errors) { $xpath = new DOMXPath($dom); if ($elements = @$xpath->query('/' . $main_xml_tag) and $elements->length) { pmxe_render_xml_element($elements->item(0), true); } else { $xml_errors = true; } } break; default: libxml_clear_errors(); $dom->loadXML($xml); $xml_errors = libxml_get_errors(); libxml_clear_errors(); $xpath = new DOMXPath($dom); // Determine XML root element $main_xml_tag = apply_filters('wp_all_export_main_xml_tag', $exportOptions['main_xml_tag'], XmlExportEngine::$exportID); $elements = @$xpath->query('/' . $main_xml_tag); if ($elements->length) { pmxe_render_xml_element($elements->item(0), true); $xml_errors = false; } else { $error_msg = '<strong>' . __('Can\'t preview the document.', 'wp_all_import_plugin') . '</strong><ul>'; $error_msg .= '<li>'; $error_msg .= __('You can continue export or try to use <data> tag as root element.', 'wp_all_import_plugin'); $error_msg .= '</li>'; $error_msg .= '</ul>'; echo $error_msg; exit(json_encode(array('html' => ob_get_clean()))); } break; } if ($xml_errors) { $preview_dom = new DOMDocument('1.0', $exportOptions['encoding']); libxml_clear_errors(); $preview_dom->loadXML($preview_xml); $preview_xml_errors = libxml_get_errors(); libxml_clear_errors(); if ($preview_xml_errors) { $error_msg = '<strong class="error">' . __('Invalid XML', 'wp_all_import_plugin') . '</strong><ul class="error">'; foreach ($preview_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>'; echo $error_msg; exit(json_encode(array('html' => ob_get_clean()))); } else { $xpath = new DOMXPath($preview_dom); if ($elements = @$xpath->query('/Preview') and $elements->length) { pmxe_render_xml_element($elements->item(0), true); } else { $error_msg = '<strong>' . __('Can\'t preview the document. Root element is not detected.', 'wp_all_import_plugin') . '</strong><ul>'; $error_msg .= '<li>'; $error_msg .= __('You can continue export or try to use <data> tag as root element.', 'wp_all_import_plugin'); $error_msg .= '</li>'; $error_msg .= '</ul>'; echo $error_msg; exit(json_encode(array('html' => ob_get_clean()))); } } } break; case 'csv': ?> <small> <?php $csv = XmlCsvExport::export_csv(true); if (!empty($csv)) { $csv_rows = array_filter(explode("\n", $csv)); if ($csv_rows) { ?> <table class="pmxe_preview" cellpadding="0" cellspacing="0"> <?php foreach ($csv_rows as $rkey => $row) { $cells = str_getcsv($row, $exportOptions['delimiter']); if ($cells) { ?> <tr> <?php foreach ($cells as $key => $value) { ?> <td> <?php if (!$rkey) { ?> <strong><?php } ?> <?php echo $value; ?> <?php if (!$rkey) { ?> </strong><?php } ?> </td> <?php } ?> </tr> <?php } } ?> </table> <?php } } else { _e('Data not found.', 'wp_all_export_plugin'); } ?> </small> <?php break; default: _e('This format is not supported.', 'wp_all_export_plugin'); break; } wp_reset_postdata(); ?> </div> </div> <?php exit(json_encode(array('html' => ob_get_clean()))); die; }
function pmxe_wp_loaded() { @ini_set("max_input_time", PMXE_Plugin::getInstance()->getOption('max_input_time')); @ini_set("max_execution_time", PMXE_Plugin::getInstance()->getOption('max_execution_time')); /* Check if cron is manualy, then execute export */ $cron_job_key = PMXE_Plugin::getInstance()->getOption('cron_job_key'); if (!empty($cron_job_key) and !empty($_GET['export_id']) and !empty($_GET['export_key']) and $_GET['export_key'] == $cron_job_key and !empty($_GET['action']) and in_array($_GET['action'], array('processing', 'trigger'))) { $logger = create_function('$m', 'echo "<p>$m</p>\\n";'); $export = new PMXE_Export_Record(); $ids = explode(',', $_GET['export_id']); if (!empty($ids) and is_array($ids)) { foreach ($ids as $id) { if (empty($id)) { continue; } $export->getById($id); if (!$export->isEmpty()) { switch ($_GET['action']) { case 'trigger': if ((int) $export->executing) { $logger and call_user_func($logger, sprintf(__('Export #%s is currently in manually process. Request skipped.', 'wp_all_export_plugin'), $id)); } elseif (!$export->processing and !$export->triggered) { $export->set(array('triggered' => 1, 'exported' => 0, 'last_activity' => date('Y-m-d H:i:s')))->update(); $logger and call_user_func($logger, sprintf(__('#%s Cron job triggered.', 'wp_all_export_plugin'), $id)); } elseif ($export->processing and !$export->triggered) { $logger and call_user_func($logger, sprintf(__('Export #%s currently in process. Request skipped.', 'wp_all_export_plugin'), $id)); } elseif (!$export->processing and $export->triggered) { $logger and call_user_func($logger, sprintf(__('Export #%s already triggered. Request skipped.', 'wp_all_export_plugin'), $id)); } break; case 'processing': if ($export->processing == 1 and time() - strtotime($export->registered_on) > 120) { // it means processor crashed, so it will reset processing to false, and terminate. Then next run it will work normally. $export->set(array('processing' => 0))->update(); } // start execution imports that is in the cron process if (!(int) $export->triggered) { $logger and call_user_func($logger, sprintf(__('Export #%s is not triggered. Request skipped.', 'wp_all_export_plugin'), $id)); } elseif ((int) $export->executing) { $logger and call_user_func($logger, sprintf(__('Export #%s is currently in manually process. Request skipped.', 'wp_all_export_plugin'), $id)); } elseif ((int) $export->triggered and !(int) $export->processing) { ob_start(); $export->set(array('canceled' => 0))->execute($logger, true); if (!(int) $export->exported) { $logger and call_user_func($logger, sprintf(__('Export #%s complete', 'wp_all_export_plugin'), $export->id)); } else { $logger and call_user_func($logger, sprintf(__('Records Processed %s', 'wp_all_export_plugin'), (int) $export->exported)); } } else { $logger and call_user_func($logger, sprintf(__('Export #%s already processing. Request skipped.', 'wp_all_export_plugin'), $id)); } break; } } } } } }
function pmxe_wp_ajax_generate_zapier_api_key() { if (!check_ajax_referer('wp_all_export_secure', 'security', false)) { exit(json_encode(array('html' => __('Security check', 'wp_all_export_plugin')))); } if (!current_user_can(PMXE_Plugin::$capabilities)) { exit(json_encode(array('html' => __('Security check', 'wp_all_export_plugin')))); } $api_key = wp_all_export_rand_char(32); PMXE_Plugin::getInstance()->updateOption('zapier_api_key', $api_key); exit(json_encode(array('api_key' => $api_key))); }
function wp_all_export_secure_file($targetDir, $ID = false) { $is_secure_import = PMXE_Plugin::getInstance()->getOption('secure'); if ($is_secure_import) { $dir = $targetDir . DIRECTORY_SEPARATOR . ($ID ? md5($ID . NONCE_SALT) : md5(time() . NONCE_SALT)); @mkdir($dir, 0755); if (@is_writable($dir) and @is_dir($dir)) { $targetDir = $dir; @touch($dir . DIRECTORY_SEPARATOR . 'index.php'); } } return $targetDir; }
/** * Register plugin specific admin menu */ function pmxe_admin_menu() { global $menu, $submenu; if (current_user_can('manage_options')) { // admin management options add_menu_page(__('WP All Export', 'wp_all_export_plugin'), __('All Export', 'wp_all_export_plugin'), 'manage_options', 'pmxe-admin-home', array(PMXE_Plugin::getInstance(), 'adminDispatcher'), PMXE_Plugin::ROOT_URL . '/static/img/xmlicon.png'); // workaround to rename 1st option to `Home` $submenu['pmxe-admin-home'] = array(); add_submenu_page('pmxe-admin-home', __('Export to XML', 'wp_all_export_plugin') . ' ‹ ' . __('WP All Export', 'wp_all_export_plugin'), __('New Export', 'wp_all_export_plugin'), 'manage_options', 'pmxe-admin-export', array(PMXE_Plugin::getInstance(), 'adminDispatcher')); add_submenu_page('pmxe-admin-home', __('Manage Exports', 'wp_all_export_plugin') . ' ‹ ' . __('WP All Export', 'wp_all_export_plugin'), __('Manage Exports', 'wp_all_export_plugin'), 'manage_options', 'pmxe-admin-manage', array(PMXE_Plugin::getInstance(), 'adminDispatcher')); add_submenu_page('pmxe-admin-home', __('Settings', 'wp_all_export_plugin') . ' ‹ ' . __('WP All Export', 'wp_all_export_plugin'), __('Settings', 'wp_all_export_plugin'), 'manage_options', 'pmxe-admin-settings', array(PMXE_Plugin::getInstance(), 'adminDispatcher')); //add_submenu_page('pmxe-admin-home', __('Support', 'wp_all_export_plugin') . ' ‹ ' . __('WP All Export', 'wp_all_export_plugin'), __('Support', 'wp_all_export_plugin'), 'manage_options', 'pmxe-admin-help', array(PMXE_Plugin::getInstance(), 'adminDispatcher')); } }
function wp_all_export_generate_export_file($export_id) { $is_secure_import = PMXE_Plugin::getInstance()->getOption('secure'); $wp_uploads = wp_upload_dir(); $target = $is_secure_import ? wp_all_export_secure_file($wp_uploads['basedir'] . DIRECTORY_SEPARATOR . PMXE_Plugin::UPLOADS_DIRECTORY, $export_id) : $wp_uploads['path']; $export = new PMXE_Export_Record(); $export->getById($export_id); if (!$export->isEmpty() and $export->options['creata_a_new_export_file']) { $export_file_name = sanitize_file_name($export->options['friendly_name']) . ' - ' . ($export->iteration + 1) . '.' . $export->options['export_to']; } else { $export_file_name = sanitize_file_name($export->options['friendly_name']) . '.' . $export->options['export_to']; } return $target . DIRECTORY_SEPARATOR . $export_file_name; }
function wp_all_export_generate_export_file($export_id) { $is_secure_import = PMXE_Plugin::getInstance()->getOption('secure'); $wp_uploads = wp_upload_dir(); $target = $is_secure_import ? wp_all_export_secure_file($wp_uploads['basedir'] . DIRECTORY_SEPARATOR . PMXE_Plugin::UPLOADS_DIRECTORY, $export_id) : $wp_uploads['path']; $export = new PMXE_Export_Record(); $export->getById($export_id); if (!$export->isEmpty()) { if ($export->options['creata_a_new_export_file'] and !XmlExportWooCommerceOrder::$is_active || $export->options['export_type'] != 'specific') { $export_file_name = sanitize_file_name($export->friendly_name) . ' - ' . ($export->iteration + 1) . '.' . $export->options['export_to']; } else { $export_file_name = sanitize_file_name($export->friendly_name) . '.' . $export->options['export_to']; } } return apply_filters('wp_all_export_export_file_name', $target . DIRECTORY_SEPARATOR . $export_file_name, $export_id); }
public function init_additional_data() { if (!self::$is_active) { return; } if (empty(self::$orders_data) or 'PMXE_Admin_Manage' == PMXE_Plugin::getInstance()->getAdminCurrentScreen()->base) { $in_orders = preg_replace("%(SQL_CALC_FOUND_ROWS|LIMIT.*)%", "", XmlExportEngine::$exportQuery->request); self::$orders_data = array(); global $wpdb; $table_prefix = $wpdb->prefix; self::$orders_data['line_items_max_count'] = $wpdb->get_var($wpdb->prepare("SELECT max(cnt) as line_items_count FROM ( \n\t\t\t\t\tSELECT order_id, COUNT(*) as cnt FROM {$table_prefix}woocommerce_order_items \n\t\t\t\t\t\tWHERE {$table_prefix}woocommerce_order_items.order_item_type = %s AND {$table_prefix}woocommerce_order_items.order_id IN (" . $in_orders . ") GROUP BY order_id) AS T3", 'line_item')); self::$orders_data['taxes'] = $wpdb->get_results($wpdb->prepare("SELECT order_item_id, order_id, order_item_name FROM {$table_prefix}woocommerce_order_items \n\t\t\t\t\t\tWHERE {$table_prefix}woocommerce_order_items.order_item_type = %s AND {$table_prefix}woocommerce_order_items.order_id IN (" . $in_orders . ") GROUP BY order_item_name", 'tax')); self::$orders_data['coupons'] = $wpdb->get_results($wpdb->prepare("SELECT order_item_id, order_id, order_item_name FROM {$table_prefix}woocommerce_order_items \n\t\t\t\t\t\tWHERE {$table_prefix}woocommerce_order_items.order_item_type = %s AND {$table_prefix}woocommerce_order_items.order_id IN (" . $in_orders . ") GROUP BY order_item_name", 'coupon')); self::$orders_data['fees'] = $wpdb->get_results($wpdb->prepare("SELECT order_item_id, order_id, order_item_name FROM {$table_prefix}woocommerce_order_items \n\t\t\t\t\t\tWHERE {$table_prefix}woocommerce_order_items.order_item_type = %s AND {$table_prefix}woocommerce_order_items.order_id IN (" . $in_orders . ") GROUP BY order_item_name", 'fee')); self::$orders_data['variations'] = $wpdb->get_results($wpdb->prepare("SELECT meta_key FROM {$table_prefix}woocommerce_order_itemmeta \n\t\t\t\t\t\tWHERE {$table_prefix}woocommerce_order_itemmeta.meta_key LIKE %s AND {$table_prefix}woocommerce_order_itemmeta.order_item_id IN (\n\t\t\t\t\t\t\tSELECT {$table_prefix}woocommerce_order_items.order_item_id FROM {$table_prefix}woocommerce_order_items \n\t\t\t\t\t\t\tWHERE {$table_prefix}woocommerce_order_items.order_item_type = %s AND {$table_prefix}woocommerce_order_items.order_id IN (" . $in_orders . ") ) GROUP BY meta_key", 'pa_%', 'line_item')); if (!empty(PMXE_Plugin::$session)) { PMXE_Plugin::$session->set('orders_data', self::$orders_data); PMXE_Plugin::$session->save_data(); } } }
/** * @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(); }
if ($list->isEmpty()) { ?> <tr> <td colspan="<?php echo count($columns) + 1; ?> "><?php _e('No previous exports found.', 'wp_all_export_plugin'); ?> </td> </tr> <?php } else { ?> <?php $is_secure_import = PMXE_Plugin::getInstance()->getOption('secure'); $class = ''; ?> <?php foreach ($list as $item) { ?> <?php $class = 'alternate' == $class ? '' : 'alternate'; ?> <tr class="<?php echo $class; ?> " valign="middle"> <th scope="row" class="check-column"> <input type="checkbox" id="item_<?php echo $item['id'];
public function __construct() { parent::__construct(); $this->setTable(PMXE_Plugin::getInstance()->getTablePrefix() . 'templates'); }
function pmxe_pmxe_after_export($export_id, $export) { if (!empty(PMXE_Plugin::$session) and PMXE_Plugin::$session->has_session()) { PMXE_Plugin::$session->set('file', ''); PMXE_Plugin::$session->save_data(); } if (!$export->isEmpty()) { $splitSize = $export->options['split_large_exports_count']; $exportOptions = $export->options; // remove previously genereted chunks if (!empty($exportOptions['split_files_list']) and !$export->options['creata_a_new_export_file']) { foreach ($exportOptions['split_files_list'] as $file) { @unlink($file); } } $is_secure_import = PMXE_Plugin::getInstance()->getOption('secure'); if (!$is_secure_import) { $filepath = get_attached_file($export->attch_id); } else { $filepath = wp_all_export_get_absolute_path($export->options['filepath']); } $is_export_csv_headers = apply_filters('wp_all_export_is_csv_headers_enabled', true, $export->id); // Remove headers row from CSV file if (!$is_export_csv_headers && @file_exists($filepath) && $export->options['export_to'] == 'csv') { $tmp_file = str_replace(basename($filepath), 'iteration_' . basename($filepath), $filepath); copy($filepath, $tmp_file); $in = fopen($tmp_file, 'r'); $out = fopen($filepath, 'w'); $headers = fgetcsv($in); if (is_resource($in)) { $lineNumber = 0; while (!feof($in)) { $data = fgetcsv($in, 0, XmlExportEngine::$exportOptions['delimiter']); if (empty($data)) { continue; } $data_assoc = array_combine($headers, array_values($data)); $line = array(); foreach ($headers as $header) { $line[$header] = isset($data_assoc[$header]) ? $data_assoc[$header] : ''; } if (!$lineNumber && XmlExportEngine::$exportOptions['include_bom']) { fwrite($out, chr(0xef) . chr(0xbb) . chr(0xbf)); fputcsv($out, $line, XmlExportEngine::$exportOptions['delimiter']); } else { fputcsv($out, $line, XmlExportEngine::$exportOptions['delimiter']); } apply_filters('wp_all_export_after_csv_line', $out, XmlExportEngine::$exportID); $lineNumber++; } fclose($in); } fclose($out); @unlink($tmp_file); } // Split large exports into chunks if ($export->options['split_large_exports'] and $splitSize < $export->exported) { $exportOptions['split_files_list'] = array(); if (@file_exists($filepath)) { switch ($export->options['export_to']) { case 'xml': $main_xml_tag = apply_filters('wp_all_export_main_xml_tag', $export->options['main_xml_tag'], $export->id); $record_xml_tag = apply_filters('wp_all_export_record_xml_tag', $export->options['record_xml_tag'], $export->id); $records_count = 0; $chunk_records_count = 0; $fileCount = 1; $feed = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" . "\n" . "<" . $main_xml_tag . ">"; $file = new PMXE_Chunk($filepath, array('element' => $record_xml_tag, 'encoding' => 'UTF-8')); // loop through the file until all lines are read while ($xml = $file->read()) { if (!empty($xml)) { $chunk = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" . "\n" . $xml; $dom = new DOMDocument('1.0', "UTF-8"); $old = libxml_use_internal_errors(true); $dom->loadXML($chunk); // FIX: libxml xpath doesn't handle default namespace properly, so remove it upon XML load libxml_use_internal_errors($old); $xpath = new DOMXPath($dom); $records_count++; $chunk_records_count++; $feed .= $xml; } if ($chunk_records_count == $splitSize or $records_count == $export->exported) { $feed .= "</" . $main_xml_tag . ">"; $outputFile = str_replace(basename($filepath), str_replace('.xml', '', basename($filepath)) . '-' . $fileCount++ . '.xml', $filepath); file_put_contents($outputFile, $feed); if (!in_array($outputFile, $exportOptions['split_files_list'])) { $exportOptions['split_files_list'][] = $outputFile; } $chunk_records_count = 0; $feed = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" . "\n" . "<" . $main_xml_tag . ">"; } } break; case 'csv': $in = fopen($filepath, 'r'); $rowCount = 0; $fileCount = 1; $headers = fgetcsv($in); while (!feof($in)) { $data = fgetcsv($in); if (empty($data)) { continue; } if ($rowCount % $splitSize == 0) { if ($rowCount > 0) { fclose($out); } $outputFile = str_replace(basename($filepath), str_replace('.csv', '', basename($filepath)) . '-' . $fileCount++ . '.csv', $filepath); if (!in_array($outputFile, $exportOptions['split_files_list'])) { $exportOptions['split_files_list'][] = $outputFile; } $out = fopen($outputFile, 'w'); } if ($data) { if ($rowCount % $splitSize == 0) { fputcsv($out, $headers); } fputcsv($out, $data); } $rowCount++; } fclose($in); fclose($out); break; default: break; } $export->set(array('options' => $exportOptions))->save(); } } // make a temporary copy of current file if (empty($export->parent_id) and @file_exists($filepath) and @copy($filepath, str_replace(basename($filepath), '', $filepath) . 'current-' . basename($filepath))) { $exportOptions = $export->options; $exportOptions['current_filepath'] = str_replace(basename($filepath), '', $filepath) . 'current-' . basename($filepath); $export->set(array('options' => $exportOptions))->save(); } // genereta export bundle $export->generate_bundle(); if (!empty($export->parent_id)) { $parent_export = new PMXE_Export_Record(); $parent_export->getById($export->parent_id); if (!$parent_export->isEmpty()) { $parent_export->generate_bundle(true); } } // clean session if (!empty(PMXE_Plugin::$session) and PMXE_Plugin::$session->has_session()) { PMXE_Plugin::$session->clean_session($export->id); } } }
/** * pre-dispatching logic for admin page controllers */ public function __adminInit() { // create history folder $uploads = wp_upload_dir(); $wpallimportDirs = array(WP_ALL_EXPORT_UPLOADS_BASE_DIRECTORY, self::TEMP_DIRECTORY, self::UPLOADS_DIRECTORY, self::CRON_DIRECTORY); foreach ($wpallimportDirs as $destination) { $dir = $uploads['basedir'] . DIRECTORY_SEPARATOR . $destination; if (!is_dir($dir)) { wp_mkdir_p($dir); } if (!@file_exists($dir . DIRECTORY_SEPARATOR . 'index.php')) { @touch($dir . DIRECTORY_SEPARATOR . 'index.php'); } } if (!is_dir($uploads['basedir'] . DIRECTORY_SEPARATOR . WP_ALL_EXPORT_UPLOADS_BASE_DIRECTORY) or !is_writable($uploads['basedir'] . DIRECTORY_SEPARATOR . WP_ALL_EXPORT_UPLOADS_BASE_DIRECTORY)) { die(sprintf(__('Uploads folder %s must be writable', 'wp_all_export_plugin'), $uploads['basedir'] . DIRECTORY_SEPARATOR . WP_ALL_EXPORT_UPLOADS_BASE_DIRECTORY)); } if (!is_dir($uploads['basedir'] . DIRECTORY_SEPARATOR . self::UPLOADS_DIRECTORY) or !is_writable($uploads['basedir'] . DIRECTORY_SEPARATOR . self::UPLOADS_DIRECTORY)) { die(sprintf(__('Uploads folder %s must be writable', 'wp_all_export_plugin'), $uploads['basedir'] . DIRECTORY_SEPARATOR . self::UPLOADS_DIRECTORY)); } self::$session = new PMXE_Handler(); $input = new PMXE_Input(); $page = strtolower($input->getpost('page', '')); if (preg_match('%^' . preg_quote(str_replace('_', '-', self::PREFIX), '%') . '([\\w-]+)$%', $page)) { //$this->adminDispatcher($page, strtolower($input->getpost('action', 'index'))); $action = strtolower($input->getpost('action', 'index')); // capitalize prefix and first letters of class name parts if (function_exists('preg_replace_callback')) { $controllerName = preg_replace_callback('%(^' . preg_quote(self::PREFIX, '%') . '|_).%', array($this, "replace_callback"), str_replace('-', '_', $page)); } else { $controllerName = preg_replace('%(^' . preg_quote(self::PREFIX, '%') . '|_).%e', 'strtoupper("$0")', str_replace('-', '_', $page)); } $actionName = str_replace('-', '_', $action); if (method_exists($controllerName, $actionName)) { if (!get_current_user_id() or !current_user_can('manage_options')) { // This nonce is not valid. die('Security check'); } else { $this->_admin_current_screen = (object) array('id' => $controllerName, 'base' => $controllerName, 'action' => $actionName, 'is_ajax' => strpos($_SERVER["HTTP_ACCEPT"], 'json') !== false, 'is_network' => is_network_admin(), 'is_user' => is_user_admin()); add_filter('current_screen', array($this, 'getAdminCurrentScreen')); add_filter('admin_body_class', create_function('', 'return "' . 'wpallexport-plugin";')); $controller = new $controllerName(); if (!$controller instanceof PMXE_Controller_Admin) { throw new Exception("Administration page `{$page}` matches to a wrong controller type."); } if ($this->_admin_current_screen->is_ajax) { // ajax request $controller->{$action}(); do_action('wpallexport_action_after'); die; // stop processing since we want to output only what controller is randered, nothing in addition } elseif (!$controller->isInline) { @ob_start(); $controller->{$action}(); self::$buffer = @ob_get_clean(); } else { self::$buffer_callback = array($controller, $action); } } } else { // redirect to dashboard if requested page and/or action don't exist wp_redirect(admin_url()); die; } } }
/** * AJAX action for preview export row */ function pmxe_wp_ajax_export_preview() { if (!check_ajax_referer('wp_all_export_secure', 'security', false)) { exit(json_encode(array('html' => __('Security check', 'wp_all_export_plugin')))); } if (!current_user_can(PMXE_Plugin::$capabilities)) { exit(json_encode(array('html' => __('Security check', 'wp_all_export_plugin')))); } ob_start(); $values = array(); parse_str($_POST['data'], $values); $export_id = isset($_GET['id']) ? stripcslashes($_GET['id']) : 0; $exportOptions = $values + (PMXE_Plugin::$session->has_session() ? PMXE_Plugin::$session->get_clear_session_data() : array()) + PMXE_Plugin::get_default_import_options(); $errors = new WP_Error(); $engine = new XmlExportEngine($exportOptions, $errors); XmlExportEngine::$exportOptions = $exportOptions; XmlExportEngine::$is_user_export = $exportOptions['is_user_export']; XmlExportEngine::$is_comment_export = $exportOptions['is_comment_export']; XmlExportEngine::$exportID = $export_id; if ('advanced' == $exportOptions['export_type']) { if (XmlExportEngine::$is_user_export) { $exportQuery = eval('return new WP_User_Query(array(' . $exportOptions['wp_query'] . ', \'offset\' => 0, \'number\' => 10));'); } elseif (XmlExportEngine::$is_comment_export) { $exportQuery = eval('return new WP_Comment_Query(array(' . $exportOptions['wp_query'] . ', \'offset\' => 0, \'number\' => 10));'); } else { $exportQuery = eval('return new WP_Query(array(' . $exportOptions['wp_query'] . ', \'offset\' => 0, \'posts_per_page\' => 10));'); } } else { XmlExportEngine::$post_types = $exportOptions['cpt']; if (in_array('users', $exportOptions['cpt']) or in_array('shop_customer', $exportOptions['cpt'])) { $exportQuery = new WP_User_Query(array('orderby' => 'ID', 'order' => 'ASC', 'number' => 10)); } elseif (in_array('comments', $exportOptions['cpt'])) { global $wp_version; if (version_compare($wp_version, '4.2.0', '>=')) { $exportQuery = new WP_Comment_Query(array('orderby' => 'comment_ID', 'order' => 'ASC', 'number' => 10)); } else { $exportQuery = get_comments(array('orderby' => 'comment_ID', 'order' => 'ASC', 'number' => 10)); } } else { remove_all_actions('parse_query'); remove_all_actions('pre_get_posts'); add_filter('posts_join', 'wp_all_export_posts_join', 10, 1); add_filter('posts_where', 'wp_all_export_posts_where', 10, 1); $exportQuery = new WP_Query(array('post_type' => $exportOptions['cpt'], 'post_status' => 'any', 'orderby' => 'title', 'order' => 'ASC', 'posts_per_page' => 10)); remove_filter('posts_where', 'wp_all_export_posts_where'); remove_filter('posts_join', 'wp_all_export_posts_join'); } } XmlExportEngine::$exportQuery = $exportQuery; ?> <div id="post-preview" class="wpallexport-preview"> <div class="wpallexport-preview-content"> <?php $wp_uploads = wp_upload_dir(); $functions = $wp_uploads['basedir'] . DIRECTORY_SEPARATOR . WP_ALL_EXPORT_UPLOADS_BASE_DIRECTORY . DIRECTORY_SEPARATOR . 'functions.php'; if (@file_exists($functions)) { require_once $functions; } switch ($exportOptions['export_to']) { case 'xml': $dom = new DOMDocument('1.0', $exportOptions['encoding']); $old = libxml_use_internal_errors(true); $xml = XmlCsvExport::export_xml(true); $dom->loadXML($xml); libxml_use_internal_errors($old); $xpath = new DOMXPath($dom); $main_xml_tag = apply_filters('wp_all_export_main_xml_tag', $exportOptions['main_xml_tag'], XmlExportEngine::$exportID); if ($elements = @$xpath->query('/' . $main_xml_tag) and $elements->length) { pmxe_render_xml_element($elements->item(0), true); } break; case 'csv': ?> <small> <?php $csv = XmlCsvExport::export_csv(true); if (!empty($csv)) { $csv_rows = array_filter(explode("\n", $csv)); if ($csv_rows) { ?> <table class="pmxe_preview" cellpadding="0" cellspacing="0"> <?php foreach ($csv_rows as $rkey => $row) { $cells = str_getcsv($row, $exportOptions['delimiter']); if ($cells) { ?> <tr> <?php foreach ($cells as $key => $value) { ?> <td> <?php if (!$rkey) { ?> <strong><?php } ?> <?php echo $value; ?> <?php if (!$rkey) { ?> </strong><?php } ?> </td> <?php } ?> </tr> <?php } } ?> </table> <?php } } else { _e('Data not found.', 'wp_all_export_plugin'); } ?> </small> <?php break; default: _e('This format is not supported.', 'wp_all_export_plugin'); break; } wp_reset_postdata(); ?> </div> </div> <?php exit(json_encode(array('html' => ob_get_clean()))); die; }
/** * Step #4: Export Processing */ 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)) { $friendly_name = 'Users Export - ' . date("Y F d H:i"); } elseif (in_array('shop_customer', $post_types)) { $friendly_name = 'Customers Export - ' . date("Y F d H:i"); } elseif (in_array('comments', $post_types)) { $friendly_name = 'Comments Export - ' . date("Y F d H:i"); } else { $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 = '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(); // create an import for this export PMXE_Wpallimport::create_an_import($export); PMXE_Plugin::$session->set('update_previous', $export->id); PMXE_Plugin::$session->save_data(); do_action('pmxe_before_export', $export->id); } $this->render(); }
/** * Initialize model instance * @param array[optional] $data Array of record data to initialize object with */ public function __construct($data = array()) { parent::__construct($data); $this->setTable(PMXE_Plugin::getInstance()->getTablePrefix() . 'posts'); }
/** * AJAX action for preview export row */ function pmxe_wp_ajax_export_preview() { if (!check_ajax_referer('wp_all_export_secure', 'security', false)) { exit(json_encode(array('html' => __('Security check', 'wp_all_export_plugin')))); } if (!current_user_can('manage_options')) { exit(json_encode(array('html' => __('Security check', 'wp_all_export_plugin')))); } ob_start(); $values = array(); parse_str($_POST['data'], $values); $exportOptions = $values + (PMXE_Plugin::$session->has_session() ? PMXE_Plugin::$session->get_clear_session_data() : array()) + PMXE_Plugin::get_default_import_options(); XmlExportEngine::$exportOptions = $exportOptions; XmlExportEngine::$is_user_export = $exportOptions['is_user_export']; 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\' => 0, \'posts_per_page\' => 10));'); } } 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' => 'title', 'order' => 'ASC', 'posts_per_page' => 10)); } 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; ?> <div id="post-preview" class="wpallexport-preview"> <div class="wpallexport-preview-content"> <?php switch ($exportOptions['export_to']) { case 'xml': $dom = new DOMDocument('1.0', $exportOptions['encoding']); $old = libxml_use_internal_errors(true); $xml = pmxe_export_xml($exportQuery, $exportOptions, true); $dom->loadXML($xml); libxml_use_internal_errors($old); $xpath = new DOMXPath($dom); if ($elements = @$xpath->query('/' . $exportOptions['main_xml_tag']) and $elements->length) { pmxe_render_xml_element($elements->item(0), true); } break; case 'csv': ?> <small> <?php $csv = pmxe_export_csv($exportQuery, $exportOptions, true); if (!empty($csv)) { $csv_rows = array_filter(explode("\n", $csv)); if ($csv_rows) { ?> <table class="pmxe_preview" cellpadding="0" cellspacing="0"> <?php foreach ($csv_rows as $rkey => $row) { $cells = str_getcsv($row, $exportOptions['delimiter']); if ($cells) { ?> <tr> <?php foreach ($cells as $key => $value) { ?> <td> <?php if (!$rkey) { ?> <strong><?php } ?> <?php echo $value; ?> <?php if (!$rkey) { ?> </strong><?php } ?> </td> <?php } ?> </tr> <?php } } ?> </table> <?php } } else { _e('Data not found.', 'pmxe_plugin'); } ?> </small> <?php break; default: _e('This format is not supported.', 'pmxe_plugin'); break; } wp_reset_postdata(); ?> </div> </div> <?php exit(json_encode(array('html' => ob_get_clean()))); die; }
/** * @see Controller::render() */ protected function render($viewPath = NULL) { // assume template file name depending on calling function if (is_null($viewPath)) { $trace = debug_backtrace(); $viewPath = str_replace('_', '/', preg_replace('%^' . preg_quote(PMXE_Plugin::PREFIX, '%') . '%', '', strtolower($trace[1]['class']))) . '/' . $trace[1]['function']; } // render contextual help automatically $viewHelpPath = $viewPath; // append file extension if not specified if (!preg_match('%\\.php$%', $viewHelpPath)) { $viewHelpPath .= '.php'; } $viewHelpPath = preg_replace('%\\.php$%', '-help.php', $viewHelpPath); $fileHelpPath = PMXE_Plugin::ROOT_DIR . '/views/' . $viewHelpPath; if (is_file($fileHelpPath)) { // there is help file defined ob_start(); include $fileHelpPath; add_contextual_help(PMXE_Plugin::getInstance()->getAdminCurrentScreen()->id, ob_get_clean()); } parent::render($viewPath); }
/** * Export CSV helper */ function pmxe_export_users_csv($exportQuery, $exportOptions, $preview = false, $is_cron = false, $file_path = false, $exported_by_cron = 0) { ob_start(); // Prepare headers $headers = array(); $stream = fopen("php://output", 'w'); $max_attach_count = 0; $max_images_count = 0; $cf = array(); $woo = array(); $acfs = array(); $taxes = array(); $attributes = array(); $articles = array(); $implode_delimiter = $exportOptions['delimiter'] == ',' ? '|' : ','; foreach ($exportQuery->results as $user) { $attach_count = 0; $images_count = 0; //$exportQuery->the_post(); //$record = get_post( get_the_ID() ); $article = array(); //$article['post_type'] = $record->post_type; $article['ID'] = apply_filters('pmxe_user_id', $user->ID); //$article['permalink'] = get_permalink(); if ($exportOptions['ids']) { if (wp_all_export_is_compatible() and $exportOptions['is_generate_import'] and $exportOptions['import_id']) { $postRecord = new PMXI_Post_Record(); $postRecord->clear(); $postRecord->getBy(array('post_id' => $user->ID, 'import_id' => $exportOptions['import_id'])); if ($postRecord->isEmpty()) { $postRecord->set(array('post_id' => $user->ID, 'import_id' => $exportOptions['import_id'], 'unique_key' => $user->ID))->save(); } unset($postRecord); } foreach ($exportOptions['ids'] as $ID => $value) { if (is_numeric($ID)) { if (empty($exportOptions['cc_name'][$ID]) or empty($exportOptions['cc_type'][$ID])) { continue; } $element_name = !empty($exportOptions['cc_name'][$ID]) ? $exportOptions['cc_name'][$ID] : 'untitled_' . $ID; $fieldSnipped = (!empty($exportOptions['cc_php'][$ID]) and !empty($exportOptions['cc_code'][$ID])) ? $exportOptions['cc_code'][$ID] : false; switch ($exportOptions['cc_type'][$ID]) { case 'id': $article[$element_name] = apply_filters('pmxe_user_id', pmxe_filter($user->ID, $fieldSnipped), $user->ID); break; case 'user_login': $article[$element_name] = apply_filters('pmxe_user_login', pmxe_filter($user->user_login, $fieldSnipped), $user->ID); break; case 'user_pass': $article[$element_name] = apply_filters('pmxe_user_pass', pmxe_filter($user->user_pass, $fieldSnipped), $user->ID); break; case 'user_email': $article[$element_name] = apply_filters('pmxe_user_email', pmxe_filter($user->user_email, $fieldSnipped), $user->ID); break; case 'user_nicename': $article[$element_name] = apply_filters('pmxe_user_nicename', pmxe_filter($user->user_nicename, $fieldSnipped), $user->ID); break; case 'user_url': $article[$element_name] = apply_filters('pmxe_user_url', pmxe_filter($user->user_url, $fieldSnipped), $user->ID); break; case 'user_activation_key': $article[$element_name] = apply_filters('pmxe_user_activation_key', pmxe_filter($user->user_activation_key, $fieldSnipped), $user->ID); break; case 'user_status': $article[$element_name] = apply_filters('pmxe_user_status', pmxe_filter($user->user_status, $fieldSnipped), $user->ID); break; case 'display_name': $article[$element_name] = apply_filters('pmxe_user_display_name', pmxe_filter($user->display_name, $fieldSnipped), $user->ID); break; case 'description': $val = apply_filters('pmxe_user_description', pmxe_filter($user->description, $fieldSnipped), $user->ID); $article[$element_name] = $preview ? trim(preg_replace('~[\\r\\n]+~', ' ', htmlspecialchars($val))) : $val; break; case 'user_registered': if (!empty($exportOptions['cc_options'][$ID])) { switch ($exportOptions['cc_options'][$ID]) { case 'unix': $post_date = strtotime($user->user_registered); break; default: $post_date = date($exportOptions['cc_options'][$ID], strtotime($user->user_registered)); break; } } else { $post_date = $user->user_registered; } $article[$element_name] = apply_filters('pmxe_user_registered', pmxe_filter($post_date, $fieldSnipped), $user->ID); break; case 'nickname': $article[$element_name] = apply_filters('pmxe_user_nickname', pmxe_filter($user->nickname, $fieldSnipped), $user->ID); break; case 'first_name': $article[$element_name] = apply_filters('pmxe_user_first_name', pmxe_filter($user->first_name, $fieldSnipped), $user->ID); break; case 'last_name': $article[$element_name] = apply_filters('pmxe_user_last_name', pmxe_filter($user->last_name, $fieldSnipped), $user->ID); break; case 'wp_capabilities': $article[$element_name] = apply_filters('pmxe_user_wp_capabilities', pmxe_filter(implode($implode_delimiter, $user->roles), $fieldSnipped), $user->ID); break; case 'cf': if (!empty($exportOptions['cc_value'][$ID])) { $cur_meta_values = get_user_meta($user->ID, $exportOptions['cc_value'][$ID]); if (!empty($cur_meta_values) and is_array($cur_meta_values)) { foreach ($cur_meta_values as $key => $cur_meta_value) { if (empty($article[$element_name])) { $article[$element_name] = apply_filters('pmxe_custom_field', pmxe_filter(maybe_serialize($cur_meta_value), $fieldSnipped), $exportOptions['cc_value'][$ID], $user->ID); if (!in_array($element_name, $cf)) { $cf[] = $element_name; } } else { $article[$element_name] = apply_filters('pmxe_custom_field', pmxe_filter($article[$element_name] . $implode_delimiter . maybe_serialize($cur_meta_value), $fieldSnipped), $exportOptions['cc_value'][$ID], $user->ID); } } } if (empty($cur_meta_values)) { if (empty($article[$element_name])) { $article[$element_name] = apply_filters('pmxe_custom_field', pmxe_filter('', $fieldSnipped), $exportOptions['cc_value'][$ID], $user->ID); if (!in_array($element_name, $cf)) { $cf[] = $element_name; } } // else{ // $article[$element_name . '_' . $key] = apply_filters('pmxe_custom_field', pmxe_filter('', $fieldSnipped), $exportOptions['cc_value'][$ID], get_the_ID()); // if (!in_array($element_name . '_' . $key, $cf)) $cf[] = $element_name . '_' . $key; // } } } break; case 'acf': if (!empty($exportOptions['cc_label'][$ID]) and class_exists('acf')) { global $acf; $field_options = unserialize($exportOptions['cc_options'][$ID]); switch ($field_options['type']) { case 'textarea': case 'oembed': case 'wysiwyg': case 'wp_wysiwyg': case 'date_time_picker': case 'date_picker': $field_value = get_field($exportOptions['cc_label'][$ID], $user->ID, false); break; default: $field_value = get_field($exportOptions['cc_label'][$ID], $user->ID); break; } pmxe_export_acf_field_csv($field_value, $exportOptions, $ID, $user->ID, $article, $acfs, $element_name, $fieldSnipped, $field_options['group_id'], $preview); } break; case 'sql': if (!empty($exportOptions['cc_sql'][$ID])) { global $wpdb; $val = $wpdb->get_var($wpdb->prepare(stripcslashes(str_replace("%%ID%%", "%d", $exportOptions['cc_sql'][$ID])), get_the_ID())); if (!empty($exportOptions['cc_php'][$ID]) and !empty($exportOptions['cc_code'][$ID])) { // if shortcode defined if (strpos($exportOptions['cc_code'][$ID], '[') === 0) { $val = do_shortcode(str_replace("%%VALUE%%", $val, $exportOptions['cc_code'][$ID])); } else { $val = eval('return ' . stripcslashes(str_replace("%%VALUE%%", $val, $exportOptions['cc_code'][$ID])) . ';'); } } $article[$element_name] = apply_filters('pmxe_sql_field', $val, $element_name, get_the_ID()); } break; default: # code... break; } } } } $articles[] = $article; if ($preview) { break; } } if ($exportOptions['ids']) { foreach ($exportOptions['ids'] as $ID => $value) { if (is_numeric($ID)) { if (empty($exportOptions['cc_name'][$ID]) or empty($exportOptions['cc_type'][$ID])) { continue; } $element_name = !empty($exportOptions['cc_name'][$ID]) ? $exportOptions['cc_name'][$ID] : 'untitled_' . $ID; switch ($exportOptions['cc_type'][$ID]) { case 'cf': if (!empty($cf)) { $headers[] = array_shift($cf); } break; case 'acf': if (!empty($acfs)) { $headers[] = array_shift($acfs); } break; default: $headers[] = $element_name; break; } } } } if ($is_cron) { if (!$exported_by_cron) { fputcsv($stream, $headers, $exportOptions['delimiter']); } } else { if ($preview or empty(PMXE_Plugin::$session->file)) { fputcsv($stream, $headers, $exportOptions['delimiter']); } } foreach ($articles as $article) { $line = array(); foreach ($headers as $header) { $line[$header] = isset($article[$header]) ? $article[$header] : ''; } fputcsv($stream, $line, $exportOptions['delimiter']); } if ($preview) { return ob_get_clean(); } if ($is_cron) { file_put_contents($file_path, ob_get_clean(), FILE_APPEND); return $file_path; } else { if (empty(PMXE_Plugin::$session->file)) { $is_secure_import = PMXE_Plugin::getInstance()->getOption('secure'); $wp_uploads = wp_upload_dir(); $target = $is_secure_import ? wp_all_export_secure_file($wp_uploads['basedir'] . DIRECTORY_SEPARATOR . PMXE_Plugin::UPLOADS_DIRECTORY) : $wp_uploads['path']; $export_file = $target . DIRECTORY_SEPARATOR . time() . '.' . $exportOptions['export_to']; file_put_contents($export_file, ob_get_clean()); PMXE_Plugin::$session->set('file', $export_file); PMXE_Plugin::$session->save_data(); } else { file_put_contents(PMXE_Plugin::$session->file, ob_get_clean(), FILE_APPEND); } return true; } }
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(); } } }
/** * Export CSV helper */ function pmxe_export_csv($exportQuery, $exportOptions, $preview = false, $is_cron = false, $file_path = false, $exported_by_cron = 0) { ob_start(); // Prepare headers $headers = array(); $stream = fopen("php://output", 'w'); $max_attach_count = 0; $max_images_count = 0; $cf = array(); $woo = array(); $woo_order = array(); $acfs = array(); $taxes = array(); $attributes = array(); $articles = array(); $implode_delimiter = $exportOptions['delimiter'] == ',' ? '|' : ','; while ($exportQuery->have_posts()) { $attach_count = 0; $images_count = 0; $exportQuery->the_post(); $record = get_post(get_the_ID()); $article = array(); $article['post_type'] = $record->post_type; $article['ID'] = apply_filters('pmxe_post_id', get_the_ID()); $article['permalink'] = get_permalink(); global $wpdb; $table_prefix = $wpdb->prefix; if ($exportOptions['ids']) { if (wp_all_export_is_compatible() and $exportOptions['is_generate_import'] and $exportOptions['import_id']) { $postRecord = new PMXI_Post_Record(); $postRecord->clear(); $postRecord->getBy(array('post_id' => $record->ID, 'import_id' => $exportOptions['import_id'])); if ($postRecord->isEmpty()) { $postRecord->set(array('post_id' => $record->ID, 'import_id' => $exportOptions['import_id'], 'unique_key' => $record->ID, 'product_key' => get_post_meta($record->ID, '_sku', true)))->save(); } unset($postRecord); } foreach ($exportOptions['ids'] as $ID => $value) { if (is_numeric($ID)) { if (empty($exportOptions['cc_name'][$ID]) or empty($exportOptions['cc_type'][$ID])) { continue; } $element_name = !empty($exportOptions['cc_name'][$ID]) ? $exportOptions['cc_name'][$ID] : 'untitled_' . $ID; $fieldSnipped = (!empty($exportOptions['cc_php'][$ID]) and !empty($exportOptions['cc_code'][$ID])) ? $exportOptions['cc_code'][$ID] : false; switch ($exportOptions['cc_type'][$ID]) { case 'id': $article[$element_name] = apply_filters('pmxe_post_id', pmxe_filter(get_the_ID(), $fieldSnipped), get_the_ID()); break; case 'permalink': $article[$element_name] = apply_filters('pmxe_post_guid', pmxe_filter(get_permalink(), $fieldSnipped), get_the_ID()); break; case 'post_type': $pType = get_post_type(); if ($pType == 'product_variation') { $pType = 'product'; } $article[$element_name] = apply_filters('pmxe_post_type', pmxe_filter($pType, $fieldSnipped), get_the_ID()); break; case 'title': $article[$element_name] = apply_filters('pmxe_post_title', pmxe_filter($record->post_title, $fieldSnipped), get_the_ID()); break; case 'content': $val = apply_filters('pmxe_post_content', pmxe_filter($record->post_content, $fieldSnipped), get_the_ID()); $article[$element_name] = $preview ? trim(preg_replace('~[\\r\\n]+~', ' ', htmlspecialchars($val))) : $val; break; case 'media': $attachment_ids = array(); $_featured_image = get_post_meta(get_the_ID(), '_thumbnail_id', true); if (!empty($_featured_image)) { $attachment_ids[] = $_featured_image; } $_gallery = get_post_meta(get_the_ID(), '_product_image_gallery', true); if (!empty($_gallery)) { $gallery = explode(',', $_gallery); if (!empty($gallery) and is_array($gallery)) { foreach ($gallery as $aid) { if (!in_array($aid, $attachment_ids)) { $attachment_ids[] = $aid; } } } } if (!empty($attachment_ids)) { $img_urls = array(); $img_titles = array(); $img_captions = array(); $img_alts = array(); $img_descriptions = array(); foreach ($attachment_ids as $key => $attach_id) { $attach = get_post($attach_id); if (wp_attachment_is_image($attach->ID)) { $val = wp_get_attachment_url($attach->ID); if (!empty($exportOptions['cc_options'][$ID])) { switch ($exportOptions['cc_options'][$ID]) { case 'filenames': $val = basename(wp_get_attachment_url($attach->ID)); break; case 'filepaths': $val = get_attached_file($attach->ID); break; default: # code... break; } } $img_urls[] = apply_filters('pmxe_attachment_url', $val, get_the_ID(), $attach->ID); $img_titles[] = apply_filters('pmxe_attachment_title', $attach->post_title, get_the_ID(), $attach->ID); $img_captions[] = apply_filters('pmxe_attachment_caption', $attach->post_excerpt, get_the_ID(), $attach->ID); $img_descriptions[] = apply_filters('pmxe_attachment_content', $attach->post_content, get_the_ID(), $attach->ID); $img_alts[] = apply_filters('pmxe_attachment_alt', get_post_meta($record->ID, '_wp_attachment_image_alt', true), get_the_ID(), $attach->ID); $images_count++; } } if (!empty($img_urls)) { $article[$element_name . '_images'] = implode($implode_delimiter, $img_urls); } if (!empty($img_titles)) { $article[$element_name . '_titles'] = implode($implode_delimiter, $img_titles); } if (!empty($img_captions)) { $article[$element_name . '_captions'] = implode($implode_delimiter, $img_captions); } if (!empty($img_alts)) { $article[$element_name . '_alts'] = implode($implode_delimiter, $img_alts); } if (!empty($img_descriptions)) { $article[$element_name . '_descriptions'] = implode($implode_delimiter, $img_descriptions); } if ($max_images_count > $images_count) { $max_images_count = $images_count; } } break; case 'date': if (!empty($exportOptions['cc_options'][$ID])) { switch ($exportOptions['cc_options'][$ID]) { case 'unix': $post_date = get_post_time('U', true); break; default: $post_date = date($exportOptions['cc_options'][$ID], get_post_time('U', true)); break; } } else { $post_date = date("Ymd", get_post_time('U', true)); } $article[$element_name] = apply_filters('pmxe_post_date', pmxe_filter($post_date, $fieldSnipped), get_the_ID()); break; case 'attachments': $attachment_imgs = get_posts(array('post_type' => 'attachment', 'posts_per_page' => -1, 'post_parent' => $record->ID)); if (!empty($attachment_imgs)) { $attachment_urls = array(); foreach ($attachment_imgs as $key => $attach) { if (!wp_attachment_is_image($attach->ID)) { $attachment_urls[] = apply_filters('pmxe_attachment_url', pmxe_filter(wp_get_attachment_url($attach->ID), $fieldSnipped), get_the_ID(), $attach->ID); $attach_count++; } } if (!empty($attachment_urls)) { $article[$element_name . '_attachments'] = implode($implode_delimiter, $attachment_urls); } if ($attach_count > $max_attach_count) { $max_attach_count = $attach_count; } } break; case 'parent': $article[$element_name] = apply_filters('pmxe_post_parent', pmxe_filter($record->post_parent, $fieldSnipped), get_the_ID()); break; case 'template': $article[$element_name] = apply_filters('pmxe_post_template', pmxe_filter(get_post_meta($record->ID, '_wp_page_template', true), $fieldSnipped), get_the_ID()); break; case 'order': $article[$element_name] = apply_filters('pmxe_menu_order', pmxe_filter($record->menu_order, $fieldSnipped), get_the_ID()); break; case 'status': $article[$element_name] = apply_filters('pmxe_post_status', pmxe_filter($record->post_status, $fieldSnipped), get_the_ID()); break; case 'format': $article[$element_name] = apply_filters('pmxe_post_format', pmxe_filter(get_post_format($record->ID), $fieldSnipped), get_the_ID()); break; case 'author': $article[$element_name] = apply_filters('pmxe_post_author', pmxe_filter($record->post_author, $fieldSnipped), get_the_ID()); break; case 'slug': $article[$element_name] = apply_filters('pmxe_post_slug', pmxe_filter($record->post_name, $fieldSnipped), get_the_ID()); break; case 'excerpt': $val = apply_filters('pmxe_post_excerpt', pmxe_filter($record->post_excerpt, $fieldSnipped), get_the_ID()); $article[$element_name] = $preview ? trim(preg_replace('~[\\r\\n]+~', ' ', htmlspecialchars($val))) : $val; break; case 'cf': if (!empty($exportOptions['cc_value'][$ID])) { $cur_meta_values = get_post_meta($record->ID, $exportOptions['cc_value'][$ID]); if (!empty($cur_meta_values) and is_array($cur_meta_values)) { foreach ($cur_meta_values as $key => $cur_meta_value) { if (empty($article[$element_name])) { $article[$element_name] = apply_filters('pmxe_custom_field', pmxe_filter(maybe_serialize($cur_meta_value), $fieldSnipped), $exportOptions['cc_value'][$ID], get_the_ID()); if (!in_array($element_name, $cf)) { $cf[] = $element_name; } } else { $article[$element_name] = apply_filters('pmxe_custom_field', pmxe_filter($article[$element_name] . $implode_delimiter . maybe_serialize($cur_meta_value), $fieldSnipped), $exportOptions['cc_value'][$ID], get_the_ID()); } } } if (empty($cur_meta_values)) { if (empty($article[$element_name])) { $article[$element_name] = apply_filters('pmxe_custom_field', pmxe_filter('', $fieldSnipped), $exportOptions['cc_value'][$ID], get_the_ID()); if (!in_array($element_name, $cf)) { $cf[] = $element_name; } } // else{ // $article[$element_name . '_' . $key] = apply_filters('pmxe_custom_field', pmxe_filter('', $fieldSnipped), $exportOptions['cc_value'][$ID], get_the_ID()); // if (!in_array($element_name . '_' . $key, $cf)) $cf[] = $element_name . '_' . $key; // } } } break; case 'acf': if (!empty($exportOptions['cc_label'][$ID]) and class_exists('acf')) { global $acf; $field_options = unserialize($exportOptions['cc_options'][$ID]); switch ($field_options['type']) { case 'textarea': case 'oembed': case 'wysiwyg': case 'wp_wysiwyg': case 'date_time_picker': case 'date_picker': $field_value = get_field($exportOptions['cc_label'][$ID], $record->ID, false); break; default: $field_value = get_field($exportOptions['cc_label'][$ID], $record->ID); break; } pmxe_export_acf_field_csv($field_value, $exportOptions, $ID, $record->ID, $article, $acfs, $element_name, $fieldSnipped, $field_options['group_id'], $preview); } break; case 'woo': //$element_name = 'woo' . $element_name; if (!empty($exportOptions['cc_value'][$ID])) { $cur_meta_values = get_post_meta($record->ID, $exportOptions['cc_value'][$ID]); if (!empty($cur_meta_values) and is_array($cur_meta_values)) { foreach ($cur_meta_values as $key => $cur_meta_value) { switch ($exportOptions['cc_label'][$ID]) { case '_downloadable_files': $files = maybe_unserialize($cur_meta_value); $file_paths = array(); $file_names = array(); if (!empty($files)) { foreach ($files as $key => $file) { $file_paths[] = $file['file']; $file_names[] = $file['name']; } $article[$element_name . '_paths'] = implode($implode_delimiter, $file_paths); if (!in_array($element_name, $woo)) { $woo[] = $element_name . '_paths'; } $article[$element_name . '_names'] = implode($implode_delimiter, $file_names); if (!in_array($element_name, $woo)) { $woo[] = $element_name . '_names'; } } break; case '_crosssell_ids': case '_upsell_ids': $_upsell_ids = maybe_unserialize($cur_meta_value); $_skus = array(); if (!empty($_upsell_ids)) { foreach ($_upsell_ids as $_upsell_id) { $_skus[] = get_post_meta($_upsell_id, '_sku', true); } $article[$element_name] = implode($implode_delimiter, $_skus); $woo[] = $element_name; } break; default: if (empty($article[$element_name])) { $article[$element_name] = apply_filters('pmxe_woo_field', pmxe_filter(maybe_serialize($cur_meta_value), $fieldSnipped), $exportOptions['cc_value'][$ID], get_the_ID()); if (!in_array($element_name, $woo)) { $woo[] = $element_name; } } else { $article[$element_name . '_' . $key] = apply_filters('pmxe_woo_field', pmxe_filter(maybe_serialize($cur_meta_value), $fieldSnipped), $exportOptions['cc_value'][$ID], get_the_ID()); if (!in_array($element_name . '_' . $key, $woo)) { $woo[] = $element_name . '_' . $key; } } break; } } } if (empty($cur_meta_values)) { if (empty($article[$element_name])) { $article[$element_name] = apply_filters('pmxe_woo_field', pmxe_filter('', $fieldSnipped), $exportOptions['cc_value'][$ID], get_the_ID()); if (!in_array($element_name, $woo)) { $woo[] = $element_name; } switch ($exportOptions['cc_label'][$ID]) { case '_downloadable_files': if (!in_array($element_name, $woo)) { $woo[] = $element_name . '_paths'; } if (!in_array($element_name, $woo)) { $woo[] = $element_name . '_names'; } break; } } } } break; case 'woo_order': XmlExportWooCommerceOrder::getInstance()->export_csv($article, $woo_order, $record, $exportOptions, $ID); break; case 'attr': //$element_name = 'woo_' . $element_name; if (!empty($exportOptions['cc_value'][$ID])) { if ($record->post_parent == 0) { // $is_variable_product = false; // $product_terms = wp_get_post_terms( $record->ID, 'product_type' ); // if( ! empty($product_terms)){ // if( ! is_wp_error( $product_terms )){ // foreach($product_terms as $term){ // if ('variable' == $term->slug){ // $is_variable_product = true; // break; // } // } // } // } $txes_list = get_the_terms($record->ID, $exportOptions['cc_value'][$ID]); if (!is_wp_error($txes_list) and !empty($txes_list)) { $attr_new = array(); foreach ($txes_list as $t) { $attr_new[] = $t->slug; } //$element_name = ($is_variable_product) ? $element_name : 'attribute_' . $element_name; $article[$element_name] = apply_filters('pmxe_woo_attribute', pmxe_filter(implode($implode_delimiter, $attr_new), $fieldSnipped), get_the_ID()); } if (!in_array($element_name, $attributes)) { $attributes[] = $element_name; } } else { $attribute_pa = get_post_meta($record->ID, 'attribute_' . $exportOptions['cc_value'][$ID], true); //if ( ! empty($attribute_pa)){ $article['attribute_' . $element_name] = $attribute_pa; //} if (!in_array('attribute_' . $element_name, $attributes)) { $attributes[] = 'attribute_' . $element_name; } } } break; case 'cats': if (!empty($exportOptions['cc_value'][$ID])) { $txes_list = get_the_terms($record->ID, $exportOptions['cc_value'][$ID]); if (!is_wp_error($txes_list) and !empty($txes_list)) { $txes_ids = array(); $hierarchy_groups = array(); foreach ($txes_list as $t) { $txes_ids[] = $t->term_id; } foreach ($txes_list as $t) { if (wp_all_export_check_children_assign($t->term_id, $exportOptions['cc_value'][$ID], $txes_ids)) { $ancestors = get_ancestors($t->term_id, $exportOptions['cc_value'][$ID]); if (count($ancestors) > 0) { $hierarchy_group = array(); for ($i = count($ancestors) - 1; $i >= 0; $i--) { $term = get_term_by('id', $ancestors[$i], $exportOptions['cc_value'][$ID]); if ($term) { $hierarchy_group[] = $term->slug; } } $hierarchy_group[] = $t->slug; $hierarchy_groups[] = implode('>', $hierarchy_group); } else { $hierarchy_groups[] = $t->slug; } } } if (!empty($hierarchy_groups)) { $article[$element_name] = apply_filters('pmxe_post_taxonomy', pmxe_filter(implode($implode_delimiter, $hierarchy_groups), $fieldSnipped), get_the_ID()); } } if (!in_array($element_name, $taxes)) { $taxes[] = $element_name; } if ($exportOptions['cc_label'][$ID] == 'product_type' and get_post_type() == 'product_variation') { $article[$element_name] = 'variable'; $article['parent_sku'] = get_post_meta($record->post_parent, '_sku', true); } } break; case 'sql': if (!empty($exportOptions['cc_sql'][$ID])) { $val = $wpdb->get_var($wpdb->prepare(stripcslashes(str_replace("%%ID%%", "%d", $exportOptions['cc_sql'][$ID])), get_the_ID())); if (!empty($exportOptions['cc_php'][$ID]) and !empty($exportOptions['cc_code'][$ID])) { // if shortcode defined if (strpos($exportOptions['cc_code'][$ID], '[') === 0) { $val = do_shortcode(str_replace("%%VALUE%%", $val, $exportOptions['cc_code'][$ID])); } else { $val = eval('return ' . stripcslashes(str_replace("%%VALUE%%", $val, $exportOptions['cc_code'][$ID])) . ';'); } } $article[$element_name] = apply_filters('pmxe_sql_field', $val, $element_name, get_the_ID()); } break; default: # code... break; } } } } $articles[] = $article; $articles = apply_filters('wp_all_export_csv_rows', $articles, $exportOptions); if ($preview) { break; } } if ($exportOptions['ids']) { foreach ($exportOptions['ids'] as $ID => $value) { if (is_numeric($ID)) { if (empty($exportOptions['cc_name'][$ID]) or empty($exportOptions['cc_type'][$ID])) { continue; } $element_name = !empty($exportOptions['cc_name'][$ID]) ? $exportOptions['cc_name'][$ID] : 'untitled_' . $ID; switch ($exportOptions['cc_type'][$ID]) { case 'media': $headers[] = $element_name . '_images'; $headers[] = $element_name . '_titles'; $headers[] = $element_name . '_captions'; $headers[] = $element_name . '_descriptions'; $headers[] = $element_name . '_alts'; break; case 'attachments': $headers[] = $element_name . '_attachments'; break; case 'cats': if (!empty($taxes)) { $tx = array_shift($taxes); $headers[] = $tx; if ($tx == 'product_type') { $headers[] = 'parent_sku'; } } break; case 'attr': if (!empty($attributes)) { $headers[] = array_shift($attributes); if (in_array('attribute_' . $element_name, $attributes)) { $headers[] = 'attribute_' . $element_name; foreach ($attributes as $akey => $avalue) { if ($avalue == 'attribute_' . $element_name) { unset($attributes[$akey]); break; } } } } break; case 'cf': if (!empty($cf)) { $headers[] = array_shift($cf); } break; case 'woo': if (!empty($woo)) { $headers[] = array_shift($woo); } break; case 'woo_order': XmlExportWooCommerceOrder::getInstance()->get_element_header($headers, $exportOptions, $ID); break; case 'acf': if (!empty($acfs)) { $headers[] = array_shift($acfs); } break; default: $headers[] = $element_name; break; } } } } if ($is_cron) { if (!$exported_by_cron) { fputcsv($stream, $headers, $exportOptions['delimiter']); } } else { if ($preview or empty(PMXE_Plugin::$session->file)) { fputcsv($stream, $headers, $exportOptions['delimiter']); } } foreach ($articles as $article) { $line = array(); foreach ($headers as $header) { $line[$header] = isset($article[$header]) ? $article[$header] : ''; } fputcsv($stream, $line, $exportOptions['delimiter']); } if ($preview) { return ob_get_clean(); } if ($is_cron) { file_put_contents($file_path, ob_get_clean(), FILE_APPEND); return $file_path; } else { if (empty(PMXE_Plugin::$session->file)) { $is_secure_import = PMXE_Plugin::getInstance()->getOption('secure'); $wp_uploads = wp_upload_dir(); $target = $is_secure_import ? wp_all_export_secure_file($wp_uploads['basedir'] . DIRECTORY_SEPARATOR . PMXE_Plugin::UPLOADS_DIRECTORY) : $wp_uploads['path']; $export_file = $target . DIRECTORY_SEPARATOR . time() . '.' . $exportOptions['export_to']; file_put_contents($export_file, ob_get_clean()); PMXE_Plugin::$session->set('file', $export_file); PMXE_Plugin::$session->save_data(); } else { file_put_contents(PMXE_Plugin::$session->file, ob_get_clean(), FILE_APPEND); } return true; } }
function pmxe_wp_ajax_export_filtering_count() { if (!check_ajax_referer('wp_all_export_secure', 'security', false)) { exit(json_encode(array('html' => __('Security check', 'wp_all_export_plugin')))); } if (!current_user_can(PMXE_Plugin::$capabilities)) { exit(json_encode(array('html' => __('Security check', 'wp_all_export_plugin')))); } ob_start(); $input = new PMXE_Input(); $post = $input->post('data', array()); $filter_args = array('filter_rules_hierarhy' => empty($post['filter_rules_hierarhy']) ? array() : $post['filter_rules_hierarhy'], 'product_matching_mode' => empty($post['product_matching_mode']) ? 'strict' : $post['product_matching_mode']); $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; } $export = new PMXE_Export_Record(); $export->getById($export_id); if (!$export->isEmpty()) { XmlExportEngine::$exportOptions = $export->options + PMXE_Plugin::get_default_import_options(); XmlExportEngine::$exportOptions['export_only_new_stuff'] = $post['export_only_new_stuff']; } XmlExportEngine::$is_user_export = ('users' == $post['cpt'] or 'shop_customer' == $post['cpt']) ? true : false; XmlExportEngine::$is_comment_export = 'comments' == $post['cpt'] ? true : false; XmlExportEngine::$post_types = array($post['cpt']); $filters = new XmlExportFiltering($filter_args); $filters->parseQuery(); PMXE_Plugin::$session->set('whereclause', $filters->get('queryWhere')); PMXE_Plugin::$session->set('joinclause', $filters->get('queryJoin')); PMXE_Plugin::$session->save_data(); $found_records = 0; $total_records = 0; $cpt = array($post['cpt']); $is_products_export = ($post['cpt'] == 'product' and class_exists('WooCommerce')); if ($post['export_type'] == 'advanced') { if (XmlExportEngine::$is_user_export) { // get total users $totalQuery = eval('return new WP_User_Query(array(' . PMXE_Plugin::$session->get('wp_query') . ', \'offset\' => 0, \'number\' => 10 ));'); if (!empty($totalQuery->results)) { $found_records = $total_records = $totalQuery->get_total(); } } elseif (XmlExportEngine::$is_comment_export) { // get total comments $totalQuery = eval('return new WP_Comment_Query(array(' . PMXE_Plugin::$session->get('wp_query') . ', \'number\' => 10, \'count\' => true ));'); $found_records = $total_records = $totalQuery->get_comments(); } else { remove_all_actions('parse_query'); remove_all_actions('pre_get_posts'); ob_start(); // get custom post type records depends on filters add_filter('posts_where', 'wp_all_export_posts_where', 10, 1); add_filter('posts_join', 'wp_all_export_posts_join', 10, 1); // get total custom post type records $totalQuery = eval('return new WP_Query(array(' . PMXE_Plugin::$session->get('wp_query') . ', \'offset\' => 0, \'posts_per_page\' => 10 ));'); if (!empty($totalQuery->found_posts)) { $found_records = $total_records = $totalQuery->found_posts; } wp_reset_postdata(); remove_filter('posts_join', 'wp_all_export_posts_join'); remove_filter('posts_where', 'wp_all_export_posts_where'); ob_get_clean(); } } else { if ('users' == $post['cpt'] or 'shop_customer' == $post['cpt']) { // get total users $totalQuery = new WP_User_Query(array('orderby' => 'ID', 'order' => 'ASC', 'number' => 10)); if (!empty($totalQuery->results)) { $found_records = $total_records = $totalQuery->get_total(); } } elseif ('comments' == $post['cpt']) { // get total comments global $wp_version; if (version_compare($wp_version, '4.2.0', '>=')) { $totalQuery = new WP_Comment_Query(array('orderby' => 'comment_ID', 'order' => 'ASC', 'number' => 10, 'count' => true)); $found_records = $total_records = $totalQuery->get_comments(); } else { $found_records = $total_records = get_comments(array('orderby' => 'comment_ID', 'order' => 'ASC', 'number' => 10, 'count' => true)); } } else { remove_all_actions('parse_query'); remove_all_actions('pre_get_posts'); $cpt = $is_products_export ? array('product', 'product_variation') : array($post['cpt']); ob_start(); // get custom post type records depends on filters add_filter('posts_where', 'wp_all_export_posts_where', 10, 1); add_filter('posts_join', 'wp_all_export_posts_join', 10, 1); // get total custom post type records $totalQuery = new WP_Query(array('post_type' => $cpt, 'post_status' => 'any', 'orderby' => 'ID', 'order' => 'ASC', 'posts_per_page' => 10)); if (!empty($totalQuery->found_posts)) { $found_records = $total_records = $totalQuery->found_posts; } wp_reset_postdata(); remove_filter('posts_join', 'wp_all_export_posts_join'); remove_filter('posts_where', 'wp_all_export_posts_where'); ob_end_clean(); } } if ($post['is_confirm_screen']) { ?> <?php if ($found_records > 0) { ?> <h3><?php _e('Your export is ready to run.', 'wp_all_export_plugin'); ?> </h3> <h4><?php printf(__('WP All Export will export %d %s.', 'wp_all_export_plugin'), $found_records, wp_all_export_get_cpt_name($cpt, $found_records)); ?> </h4> <?php } else { ?> <?php if (!$export->isEmpty() and $export->options['export_only_new_stuff']) { ?> <h3><?php _e('Nothing to export.', 'wp_all_export_plugin'); ?> </h3> <h4><?php printf(__("All %s have already been exported.", "wp_all_export_plugin"), wp_all_export_get_cpt_name($cpt)); ?> </h4> <?php } elseif ($total_records > 0) { ?> <h3><?php _e('Nothing to export.', 'wp_all_export_plugin'); ?> </h3> <h4><?php printf(__("No matching %s found for selected filter rules.", "wp_all_export_plugin"), wp_all_export_get_cpt_name($cpt)); ?> </h4> <?php } else { ?> <h3><?php _e('Nothing to export.', 'wp_all_export_plugin'); ?> </h3> <h4><?php printf(__("There aren't any %s to export.", "wp_all_export_plugin"), wp_all_export_get_cpt_name($cpt)); ?> </h4> <?php } ?> <?php } ?> <?php } elseif ($post['is_template_screen']) { ?> <?php if ($found_records > 0) { ?> <h3><span class="matches_count"><?php echo $found_records; ?> </span> <strong><?php echo wp_all_export_get_cpt_name($cpt, $found_records); ?> </strong> will be exported</h3> <h4><?php _e("Choose data to include in the export file.", "wp_all_export_plugin"); ?> </h4> <?php } else { ?> <?php if (!$export->isEmpty() and $export->options['export_only_new_stuff']) { ?> <h3><?php _e('Nothing to export.', 'wp_all_export_plugin'); ?> </h3> <h4><?php printf(__("All %s have already been exported.", "wp_all_export_plugin"), wp_all_export_get_cpt_name($cpt)); ?> </h4> <?php } elseif ($total_records > 0) { ?> <h3><?php _e('Nothing to export.', 'wp_all_export_plugin'); ?> </h3> <h4><?php printf(__("No matching %s found for selected filter rules.", "wp_all_export_plugin"), wp_all_export_get_cpt_name($cpt)); ?> </h4> <?php } else { ?> <h3><?php _e('Nothing to export.', 'wp_all_export_plugin'); ?> </h3> <h4><?php printf(__("There aren't any %s to export.", "wp_all_export_plugin"), wp_all_export_get_cpt_name($cpt)); ?> </h4> <?php } ?> <?php } ?> <?php } else { ?> <div class="founded_records"> <?php if ($found_records > 0) { ?> <?php if (XmlExportEngine::$is_user_export || XmlExportEngine::$is_comment_export) { ?> <h3><span class="matches_count"><?php echo $found_records; ?> </span> <strong><?php echo wp_all_export_get_cpt_name($cpt, $found_records); ?> </strong> can be exported</h3> <h4><?php printf(__('Upgrade to the professional edition of WP All Export to export %s.', 'wp_all_export_plugin'), wp_all_export_get_cpt_name($cpt)); ?> </h4> <?php } else { ?> <h3><span class="matches_count"><?php echo $found_records; ?> </span> <strong><?php echo wp_all_export_get_cpt_name($cpt, $found_records); ?> </strong> will be exported</h3> <h4><?php _e("Continue to configure and run your export.", "wp_all_export_plugin"); ?> </h4> <?php } ?> <?php } elseif ($total_records > 0) { ?> <h4 style="line-height:60px;"><?php printf(__("No matching %s found for selected filter rules.", "wp_all_export_plugin"), wp_all_export_get_cpt_name($cpt)); ?> </h4> <?php } else { ?> <h4 style="line-height:60px;"><?php printf(__("There aren't any %s to export.", "wp_all_export_plugin"), wp_all_export_get_cpt_name($cpt)); ?> </h4> <?php } ?> </div> <?php } exit(json_encode(array('html' => ob_get_clean(), 'found_records' => $found_records))); die; }
/** * 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(); }
/** * 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(PMXE_Plugin::$capabilities)) { 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::$is_comment_export = $exportOptions['is_comment_export']; XmlExportEngine::$exportID = $export_id; XmlExportEngine::$exportRecord = $export; $errors = new WP_Error(); $engine = new XmlExportEngine($exportOptions, $errors); $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 Pro edition of WP All Export to Export Users', 'wp_all_export_plugin')))); } elseif (XmlExportEngine::$is_comment_export) { exit(json_encode(array('html' => __('Upgrade to the Pro edition of WP All Export to Export Comments', 'wp_all_export_plugin')))); } else { remove_all_actions('parse_query'); remove_all_actions('pre_get_posts'); remove_all_filters('posts_clauses'); add_filter('posts_join', 'wp_all_export_posts_join', 10, 1); add_filter('posts_where', 'wp_all_export_posts_where', 10, 1); $exportQuery = eval('return new WP_Query(array(' . $exportOptions['wp_query'] . ', \'offset\' => ' . $export->exported . ', \'posts_per_page\' => ' . $posts_per_page . ' ));'); remove_filter('posts_where', 'wp_all_export_posts_where'); remove_filter('posts_join', 'wp_all_export_posts_join'); } } else { XmlExportEngine::$post_types = $exportOptions['cpt']; // $is_products_export = ($exportOptions['cpt'] == 'product' and class_exists('WooCommerce')); if (in_array('users', $exportOptions['cpt']) or in_array('shop_customer', $exportOptions['cpt'])) { exit(json_encode(array('html' => __('Upgrade to the Pro edition of WP All Export to Export Users', 'wp_all_export_plugin')))); } elseif (in_array('comments', $exportOptions['cpt'])) { exit(json_encode(array('html' => __('Upgrade to the Pro edition of WP All Export to Export Comments', 'wp_all_export_plugin')))); } else { remove_all_actions('parse_query'); remove_all_actions('pre_get_posts'); remove_all_filters('posts_clauses'); add_filter('posts_join', 'wp_all_export_posts_join', 10, 1); add_filter('posts_where', 'wp_all_export_posts_where', 10, 1); $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)); remove_filter('posts_where', 'wp_all_export_posts_where'); remove_filter('posts_join', 'wp_all_export_posts_join'); } } XmlExportEngine::$exportQuery = $exportQuery; $engine->init_additional_data(); // get total founded records if (XmlExportEngine::$is_comment_export) { } else { $foundPosts = !XmlExportEngine::$is_user_export ? $exportQuery->found_posts : $exportQuery->get_total(); $postCount = !XmlExportEngine::$is_user_export ? $exportQuery->post_count : count($exportQuery->get_results()); } // [ \get total founded records ] 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'])) { $exportOptions['filepath'] = ''; } PMXE_Plugin::$session->set('count', $foundPosts); PMXE_Plugin::$session->save_data(); } // if posts still exists then export them if ($postCount) { XmlCsvExport::export(); $export->set(array('exported' => $export->exported + $postCount, 'last_activity' => date('Y-m-d H:i:s')))->save(); } if ($posts_per_page != -1 and $postCount) { wp_send_json(array('export_id' => $export->id, 'queue_export' => false, 'exported' => $export->exported, 'percentage' => ceil($export->exported / $foundPosts * 100), 'done' => false, 'records_per_request' => $exportOptions['records_per_iteration'])); } else { if (file_exists(PMXE_Plugin::$session->file)) { if ($exportOptions['export_to'] == 'xml') { $main_xml_tag = apply_filters('wp_all_export_main_xml_tag', $exportOptions['main_xml_tag'], $export->id); file_put_contents(PMXE_Plugin::$session->file, '</' . $main_xml_tag . '>', FILE_APPEND); $xml_footer = apply_filters('wp_all_export_xml_footer', '', $export->id); if (!empty($xml_footer)) { file_put_contents(PMXE_Plugin::$session->file, $xml_footer, 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(); } } PMXE_Wpallimport::generateImportTemplate($export, PMXE_Plugin::$session->file, PMXE_Plugin::$session->count); } $export->set(array('executing' => 0, 'canceled' => 0, 'iteration' => ++$export->iteration))->save(); do_action('pmxe_after_export', $export->id, $export); $queue_exports = empty($export->parent_id) ? array() : get_option('wp_all_export_queue_' . $export->parent_id); if (!empty($queue_exports) and !empty($export->parent_id)) { array_shift($queue_exports); } if (empty($queue_exports)) { delete_option('wp_all_export_queue_' . (empty($export->parent_id) ? $export->id : $export->parent_id)); } else { update_option('wp_all_export_queue_' . (empty($export->parent_id) ? $export->id : $export->parent_id), $queue_exports); } wp_send_json(array('export_id' => $export->id, 'queue_export' => empty($queue_exports) ? false : $queue_exports[0], 'exported' => $export->exported, 'percentage' => 100, 'done' => true, 'records_per_request' => $exportOptions['records_per_iteration'])); } }
function pmxe_pmxe_after_export($export_id) { $export = new PMXE_Export_Record(); $export->getById($export_id); $splitSize = $export->options['split_large_exports_count']; if (!$export->isEmpty()) { $export->set(array('iteration' => $export->options['creata_a_new_export_file'] ? $export->iteration + 1 : 0))->update(); $exportOptions = $export->options; // remove previously genereted chunks if (!empty($exportOptions['split_files_list']) and !$export->options['creata_a_new_export_file']) { foreach ($exportOptions['split_files_list'] as $file) { @unlink($file); } } $is_secure_import = PMXE_Plugin::getInstance()->getOption('secure'); if (!$is_secure_import) { $filepath = get_attached_file($export->attch_id); } else { $filepath = wp_all_export_get_absolute_path($export->options['filepath']); } // Split large exports into chunks if ($export->options['split_large_exports'] and $splitSize < $export->exported) { $exportOptions['split_files_list'] = array(); if (@file_exists($filepath)) { switch ($export->options['export_to']) { case 'xml': $records_count = 0; $chunk_records_count = 0; $fileCount = 1; $feed = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" . "\n" . "<" . $export->options['main_xml_tag'] . ">"; $file = new PMXE_Chunk($filepath, array('element' => $export->options['record_xml_tag'], 'encoding' => 'UTF-8')); // loop through the file until all lines are read while ($xml = $file->read()) { if (!empty($xml)) { $chunk = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" . "\n" . $xml; $dom = new DOMDocument('1.0', "UTF-8"); $old = libxml_use_internal_errors(true); $dom->loadXML($chunk); // FIX: libxml xpath doesn't handle default namespace properly, so remove it upon XML load libxml_use_internal_errors($old); $xpath = new DOMXPath($dom); $records_count++; $chunk_records_count++; $feed .= $xml; } if ($chunk_records_count == $splitSize or $records_count == $export->exported) { $feed .= "</" . $export->options['main_xml_tag'] . ">"; $outputFile = str_replace(basename($filepath), str_replace('.xml', '', basename($filepath)) . '-' . $fileCount++ . '.xml', $filepath); file_put_contents($outputFile, $feed); if (!in_array($outputFile, $exportOptions['split_files_list'])) { $exportOptions['split_files_list'][] = $outputFile; } $chunk_records_count = 0; $feed = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" . "\n" . "<" . $export->options['main_xml_tag'] . ">"; } } break; case 'csv': $in = fopen($filepath, 'r'); $rowCount = 0; $fileCount = 1; $headers = fgetcsv($in); while (!feof($in)) { $data = fgetcsv($in); if (empty($data)) { continue; } if ($rowCount % $splitSize == 0) { if ($rowCount > 0) { fclose($out); } $outputFile = str_replace(basename($filepath), str_replace('.csv', '', basename($filepath)) . '-' . $fileCount++ . '.csv', $filepath); if (!in_array($outputFile, $exportOptions['split_files_list'])) { $exportOptions['split_files_list'][] = $outputFile; } $out = fopen($outputFile, 'w'); } if ($data) { if ($rowCount % $splitSize == 0) { fputcsv($out, $headers); } fputcsv($out, $data); } $rowCount++; } fclose($out); break; default: break; } $export->set(array('options' => $exportOptions))->save(); } } } }
public static function prepare_child_exports($export, $is_cron = false) { $queue_exports = array(); $exportList = new PMXE_Export_List(); global $wpdb; $table_prefix = $wpdb->prefix; $pmxe_prefix = PMXE_Plugin::getInstance()->getTablePrefix(); $in_orders = $wpdb->prepare("SELECT DISTINCT post_id FROM {$pmxe_prefix}posts WHERE export_id = %d AND iteration = %d", $export->id, $export->iteration - 1); foreach ($exportList->getBy('parent_id', $export->id)->convertRecords() as $child_export) { $whereClause = ""; switch ($child_export->export_post_type) { case 'product': if ($export->options['order_include_poducts']) { $queue_exports[] = $child_export->id; if (!$export->options['order_include_all_poducts']) { $in_products = $wpdb->prepare("SELECT order_item_meta.meta_value as product_id FROM {$table_prefix}posts as posts INNER JOIN {$pmxe_prefix}posts AS order_export ON posts.ID = post_id INNER JOIN {$table_prefix}woocommerce_order_items AS order_items ON posts.ID = order_id INNER JOIN {$table_prefix}woocommerce_order_itemmeta AS order_item_meta ON order_items.order_item_id = order_item_meta.order_item_id WHERE order_export.export_id = %d AND order_export.iteration = %d AND order_items.order_item_type = 'line_item' AND order_item_meta.meta_key = '_product_id' GROUP BY product_id", $export->id, $export->iteration - 1); $whereClause = " AND ({$table_prefix}posts.ID IN (" . $in_products . ") OR {$table_prefix}posts.post_parent IN (" . $in_products . "))"; } } break; case 'shop_coupon': if ($export->options['order_include_coupons']) { $queue_exports[] = $child_export->id; if (!$export->options['order_include_all_coupons']) { $whereClause = " AND {$table_prefix}posts.post_title IN (" . $wpdb->prepare("SELECT order_item_name FROM {$table_prefix}woocommerce_order_items \n\t\t\t\t\t\tWHERE {$table_prefix}woocommerce_order_items.order_item_type = %s AND {$table_prefix}woocommerce_order_items.order_id IN (" . $in_orders . ") GROUP BY order_item_name", 'coupon') . ")"; } } break; case 'shop_customer': if ($export->options['order_include_customers']) { $queue_exports[] = $child_export->id; if (!$export->options['order_include_all_customers']) { $whereClause = " AND {$table_prefix}users.ID IN (" . $wpdb->prepare("SELECT meta_value FROM {$table_prefix}postmeta WHERE meta_key = %s AND post_id IN (" . $in_orders . ") GROUP BY meta_value", "_customer_user") . ")"; } } break; default: # code... break; } $child_export_options = $child_export->options; $child_export_options['whereclause'] = $whereClause; $child_export->set(array('triggered' => $is_cron ? 1 : 0, 'processing' => 0, 'exported' => 0, 'executing' => $is_cron ? 0 : 1, 'canceled' => 0, 'options' => $child_export_options))->save(); } return $queue_exports; }
function pmxe_wp_ajax_export_filtering_count() { if (!check_ajax_referer('wp_all_export_secure', 'security', false)) { exit(json_encode(array('html' => __('Security check', 'wp_all_export_plugin')))); } if (!current_user_can('manage_options')) { exit(json_encode(array('html' => __('Security check', 'wp_all_export_plugin')))); } ob_start(); $input = new PMXE_Input(); $post = $input->post('data', array()); $filter_args = array('filter_rules_hierarhy' => $post['filter_rules_hierarhy'], 'product_matching_mode' => $post['product_matching_mode']); $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; } $export = new PMXE_Export_Record(); $export->getById($export_id); if (!$export->isEmpty()) { XmlExportEngine::$exportOptions = $export->options + PMXE_Plugin::get_default_import_options(); XmlExportEngine::$exportOptions['export_only_new_stuff'] = $post['export_only_new_stuff']; } XmlExportEngine::$is_user_export = 'users' == $post['cpt'] ? true : false; XmlExportEngine::$post_types = array($post['cpt']); $filters = new XmlExportFiltering($filter_args); $filters->parseQuery(); PMXE_Plugin::$session->set('whereclause', $filters->get('queryWhere')); PMXE_Plugin::$session->set('joinclause', $filters->get('queryJoin')); PMXE_Plugin::$session->save_data(); $found_records = 0; if ('users' == $post['cpt']) { add_action('pre_user_query', 'wp_all_export_pre_user_query', 10, 1); $exportQuery = new WP_User_Query(array('orderby' => 'ID', 'order' => 'ASC', 'number' => 10)); if (!empty($exportQuery->results)) { $found_records = $exportQuery->get_total(); } remove_action('pre_user_query', 'wp_all_export_pre_user_query'); } else { add_filter('posts_where', 'wp_all_export_posts_where', 10, 1); add_filter('posts_join', 'wp_all_export_posts_join', 10, 1); $cpt = $post['cpt'] == 'product' ? array('product', 'product_variation') : $post['cpt']; $exportQuery = new WP_Query(array('post_type' => $cpt, 'post_status' => 'any', 'orderby' => 'ID', 'order' => 'ASC', 'posts_per_page' => 10)); if (!empty($exportQuery->found_posts)) { $found_records = $exportQuery->found_posts; } remove_filter('posts_join', 'wp_all_export_posts_join'); remove_filter('posts_where', 'wp_all_export_posts_where'); } if ($post['is_confirm_screen']) { ?> <?php if ($found_records > 0) { ?> <h3><?php _e('Your export is ready to run.', 'wp_all_export_plugin'); ?> </h3> <h4><?php printf(__('WP All Export will export %d %s.', 'wp_all_export_plugin'), $found_records, wp_all_export_get_cpt_name(array($post['cpt']), $found_records)); ?> </h4> <?php } else { ?> <?php if (!$export->isEmpty() and $export->options['export_only_new_stuff']) { ?> <h3><?php _e('Nothing to export.', 'wp_all_export_plugin'); ?> </h3> <h4><?php printf(__("All %s have already been exported.", "wp_all_export_plugin"), wp_all_export_get_cpt_name(array($post['cpt']))); ?> </h4> <?php } else { ?> <h3><?php _e('Nothing to export.', 'wp_all_export_plugin'); ?> </h3> <h4><?php printf(__("No matching %s found for selected filter rules.", "wp_all_export_plugin"), wp_all_export_get_cpt_name(array($post['cpt']))); ?> </h4> <?php } ?> <?php } ?> <?php } else { ?> <div class="founded_records"> <?php if ($found_records > 0) { ?> <h3><span class="matches_count"><?php echo $found_records; ?> </span> <strong><?php echo wp_all_export_get_cpt_name(array($post['cpt']), $found_records); ?> </strong> will be exported</h3> <h4><?php _e("Continue to Step 2 to choose data to include in the export file.", "wp_all_export_plugin"); ?> </h4> <?php } else { ?> <h4 style="line-height:60px;"><?php printf(__("No matching %s found for selected filter rules.", "wp_all_export_plugin"), wp_all_export_get_cpt_name(array($post['cpt']))); ?> </h4> <?php } ?> </div> <?php } exit(json_encode(array('html' => ob_get_clean(), 'found_records' => $found_records))); die; }
public function dismiss() { PMXE_Plugin::getInstance()->updateOption("dismiss", 1); exit('OK'); }
public function init_additional_data() { if (!self::$is_active) { return; } if (empty(self::$products_data) or 'PMXE_Admin_Manage' == PMXE_Plugin::getInstance()->getAdminCurrentScreen()->base) { self::$products_data = array(); global $wpdb; $table_prefix = $wpdb->prefix; self::$products_data['attributes'] = $wpdb->get_results($wpdb->prepare("SELECT DISTINCT meta_key FROM {$table_prefix}postmeta \n\t\t\t\t\t\tWHERE {$table_prefix}postmeta.meta_key LIKE %s AND {$table_prefix}postmeta.meta_key NOT LIKE %s", 'attribute_%', 'attribute_pa_%')); if (!empty(PMXE_Plugin::$session)) { PMXE_Plugin::$session->set('products_data', self::$products_data); PMXE_Plugin::$session->save_data(); } } }
public function get_file() { $nonce = !empty($_REQUEST['_wpnonce']) ? $_REQUEST['_wpnonce'] : ''; if (!wp_verify_nonce($nonce, '_wpnonce-download_feed')) { die(__('Security check', 'wp_all_export_plugin')); } else { $is_secure_import = PMXE_Plugin::getInstance()->getOption('secure'); $id = $this->input->get('id'); $export = new PMXE_Export_Record(); $filepath = ''; if (!$export->getById($id)->isEmpty()) { if (!$is_secure_import) { $filepath = get_attached_file($export->attch_id); } else { $filepath = wp_all_export_get_absolute_path($export->options['filepath']); } if (@file_exists($filepath)) { switch ($export->options['export_to']) { case 'xml': PMXE_download::xml($filepath); break; case 'csv': PMXE_download::csv($filepath); break; default: wp_redirect(add_query_arg('pmxe_nt', urlencode(__('File format not supported', 'pmxe_plugin')), $this->baseUrl)); die; break; } } else { wp_redirect(add_query_arg('pmxe_nt', urlencode(__('The exported file is missing and can\'t be downloaded. Please re-run your export to re-generate it.', 'pmxe_plugin')), $this->baseUrl)); die; } } else { wp_redirect(add_query_arg('pmxe_nt', urlencode(__('The exported file is missing and can\'t be downloaded. Please re-run your export to re-generate it.', 'pmxe_plugin')), $this->baseUrl)); die; } } }