Advertisement
rcain

wordpress-importer.php - v0.6 - image attachment fixes

Apr 5th, 2012
1,367
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 43.53 KB | None | 0 0
  1. <?php
  2. /*
  3. Plugin Name: WordPress Importer
  4. Plugin URI: http://wordpress.org/extend/plugins/wordpress-importer/
  5. Description: Import posts, pages, comments, custom fields, categories, tags and more from a WordPress export file.
  6. Author: wordpressdotorg
  7. Author URI: http://wordpress.org/
  8. Version: 0.6
  9. Text Domain: wordpress-importer
  10. License: GPL version 2 or later - http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  11. */
  12. /*mod jrc 050412 - modified to deal also with stray relative url's for attachments - see mod marks 'mod jrc 300312', 'mod jrc 050412' - see also: http://wordpress.org/support/topic/plugin-wordpress-importer-not-importing-any-images-at-all - (esp. useful when importing multiple batches and using plugin: http://wordpress.org/extend/plugins/advanced-export-for-wp-wpmu/ (modified version - see also: http://wordpress.org/support/topic/plugin-advanced-export-for-wp-wpmu-how-to-export-attachments-only)) */
  13.  
  14. if ( ! defined( 'WP_LOAD_IMPORTERS' ) )
  15.     return;
  16.  
  17. /** Display verbose errors*/
  18. define( 'IMPORT_DEBUG', false );
  19.  
  20. // Load Importer API
  21. require_once ABSPATH . 'wp-admin/includes/import.php';
  22.  
  23. if ( ! class_exists( 'WP_Importer' ) ) {
  24.     $class_wp_importer = ABSPATH . 'wp-admin/includes/class-wp-importer.php';
  25.     if ( file_exists( $class_wp_importer ) )
  26.         require $class_wp_importer;
  27. }
  28.  
  29. // include WXR file parsers
  30. require dirname( __FILE__ ) . '/parsers.php';
  31.  
  32. /**
  33.  * WordPress Importer class for managing the import process of a WXR file
  34.  *
  35.  * @package WordPress
  36.  * @subpackage Importer
  37.  */
  38. if ( class_exists( 'WP_Importer' ) ) {
  39. class WP_Import extends WP_Importer {
  40.     var $max_wxr_version = 1.2; // max. supported WXR version
  41.  
  42.     var $id; // WXR attachment ID
  43.  
  44.     // information to import from WXR file
  45.     var $version;
  46.     var $authors = array();
  47.     var $posts = array();
  48.     var $terms = array();
  49.     var $categories = array();
  50.     var $tags = array();
  51.     var $base_url = '';
  52.  
  53.     // mappings from old information to new
  54.     var $processed_authors = array();
  55.     var $author_mapping = array();
  56.     var $processed_terms = array();
  57.     var $processed_posts = array();
  58.     var $post_orphans = array();
  59.     var $processed_menu_items = array();
  60.     var $menu_item_orphans = array();
  61.     var $missing_menu_items = array();
  62.  
  63.     var $fetch_attachments = false;
  64.     var $url_remap = array();
  65.     var $featured_images = array();
  66.  
  67.     function WP_Import() { /* nothing */ }
  68.  
  69.     /**
  70.      * Registered callback function for the WordPress Importer
  71.      *
  72.      * Manages the three separate stages of the WXR import process
  73.      */
  74.     function dispatch() {
  75.         $this->header();
  76.  
  77.         $step = empty( $_GET['step'] ) ? 0 : (int) $_GET['step'];
  78.         switch ( $step ) {
  79.             case 0:
  80.                 $this->greet();
  81.                 break;
  82.             case 1:
  83.                 check_admin_referer( 'import-upload' );
  84.                 if ( $this->handle_upload() )
  85.                     $this->import_options();
  86.                 break;
  87.             case 2:
  88.                 check_admin_referer( 'import-wordpress' );
  89.                 $this->fetch_attachments = ( ! empty( $_POST['fetch_attachments'] ) && $this->allow_fetch_attachments() );
  90.                 $this->id = (int) $_POST['import_id'];
  91.                 $file = get_attached_file( $this->id );
  92.                 set_time_limit(0);
  93.                 $this->import( $file );
  94.                 break;
  95.         }
  96.  
  97.         $this->footer();
  98.     }
  99.  
  100.     /**
  101.      * The main controller for the actual import stage.
  102.      *
  103.      * @param string $file Path to the WXR file for importing
  104.      */
  105.     function import( $file ) {
  106.         add_filter( 'import_post_meta_key', array( $this, 'is_valid_meta_key' ) );
  107.         add_filter( 'http_request_timeout', array( &$this, 'bump_request_timeout' ) );
  108.  
  109.         $this->import_start( $file );
  110.  
  111.         $this->get_author_mapping();
  112.  
  113.         wp_suspend_cache_invalidation( true );
  114.         $this->process_categories();
  115.         $this->process_tags();
  116.         $this->process_terms();
  117.         $this->process_posts();
  118.         wp_suspend_cache_invalidation( false );
  119.  
  120.         // update incorrect/missing information in the DB
  121.         $this->backfill_parents();
  122.         $this->backfill_attachment_urls();
  123.         $this->remap_featured_images();
  124.  
  125.         $this->import_end();
  126.     }
  127.  
  128.     /**
  129.      * Parses the WXR file and prepares us for the task of processing parsed data
  130.      *
  131.      * @param string $file Path to the WXR file for importing
  132.      */
  133.     function import_start( $file ) {
  134.         if ( ! is_file($file) ) {
  135.             echo '<p><strong>' . __( 'Sorry, there has been an error.', 'wordpress-importer' ) . '</strong><br />';
  136.             echo __( 'The file does not exist, please try again.', 'wordpress-importer' ) . '</p>';
  137.             $this->footer();
  138.             die();
  139.         }
  140.  
  141.         $import_data = $this->parse( $file );
  142.  
  143.         if ( is_wp_error( $import_data ) ) {
  144.             echo '<p><strong>' . __( 'Sorry, there has been an error.', 'wordpress-importer' ) . '</strong><br />';
  145.             echo esc_html( $import_data->get_error_message() ) . '</p>';
  146.             $this->footer();
  147.             die();
  148.         }
  149.  
  150.         $this->version = $import_data['version'];
  151.         $this->get_authors_from_import( $import_data );
  152.         $this->posts = $import_data['posts'];
  153.         $this->terms = $import_data['terms'];
  154.         $this->categories = $import_data['categories'];
  155.         $this->tags = $import_data['tags'];
  156.         $this->base_url = esc_url( $import_data['base_url'] );
  157.  
  158.         wp_defer_term_counting( true );
  159.         wp_defer_comment_counting( true );
  160.  
  161.         do_action( 'import_start' );
  162.     }
  163.  
  164.     /**
  165.      * Performs post-import cleanup of files and the cache
  166.      */
  167.     function import_end() {
  168.         wp_import_cleanup( $this->id );
  169.  
  170.         wp_cache_flush();
  171.         foreach ( get_taxonomies() as $tax ) {
  172.             delete_option( "{$tax}_children" );
  173.             _get_term_hierarchy( $tax );
  174.         }
  175.  
  176.         wp_defer_term_counting( false );
  177.         wp_defer_comment_counting( false );
  178.  
  179.         echo '<p>' . __( 'All done.', 'wordpress-importer' ) . ' <a href="' . admin_url() . '">' . __( 'Have fun!', 'wordpress-importer' ) . '</a>' . '</p>';
  180.         echo '<p>' . __( 'Remember to update the passwords and roles of imported users.', 'wordpress-importer' ) . '</p>';
  181.  
  182.         do_action( 'import_end' );
  183.     }
  184.  
  185.     /**
  186.      * Handles the WXR upload and initial parsing of the file to prepare for
  187.      * displaying author import options
  188.      *
  189.      * @return bool False if error uploading or invalid file, true otherwise
  190.      */
  191.     function handle_upload() {
  192.         $file = wp_import_handle_upload();
  193.  
  194.         if ( isset( $file['error'] ) ) {
  195.             echo '<p><strong>' . __( 'Sorry, there has been an error.', 'wordpress-importer' ) . '</strong><br />';
  196.             echo esc_html( $file['error'] ) . '</p>';
  197.             return false;
  198.         } else if ( ! file_exists( $file['file'] ) ) {
  199.             echo '<p><strong>' . __( 'Sorry, there has been an error.', 'wordpress-importer' ) . '</strong><br />';
  200.             printf( __( 'The export file could not be found at <code>%s</code>. It is likely that this was caused by a permissions problem.', 'wordpress-importer' ), esc_html( $file['file'] ) );
  201.             echo '</p>';
  202.             return false;
  203.         }
  204.  
  205.         $this->id = (int) $file['id'];
  206.         $import_data = $this->parse( $file['file'] );
  207.         if ( is_wp_error( $import_data ) ) {
  208.             echo '<p><strong>' . __( 'Sorry, there has been an error.', 'wordpress-importer' ) . '</strong><br />';
  209.             echo esc_html( $import_data->get_error_message() ) . '</p>';
  210.             return false;
  211.         }
  212.  
  213.         $this->version = $import_data['version'];
  214.         if ( $this->version > $this->max_wxr_version ) {
  215.             echo '<div class="error"><p><strong>';
  216.             printf( __( 'This WXR file (version %s) may not be supported by this version of the importer. Please consider updating.', 'wordpress-importer' ), esc_html($import_data['version']) );
  217.             echo '</strong></p></div>';
  218.         }
  219.  
  220.         $this->get_authors_from_import( $import_data );
  221.  
  222.         return true;
  223.     }
  224.  
  225.     /**
  226.      * Retrieve authors from parsed WXR data
  227.      *
  228.      * Uses the provided author information from WXR 1.1 files
  229.      * or extracts info from each post for WXR 1.0 files
  230.      *
  231.      * @param array $import_data Data returned by a WXR parser
  232.      */
  233.     function get_authors_from_import( $import_data ) {
  234.         if ( ! empty( $import_data['authors'] ) ) {
  235.             $this->authors = $import_data['authors'];
  236.         // no author information, grab it from the posts
  237.         } else {
  238.             foreach ( $import_data['posts'] as $post ) {
  239.                 $login = sanitize_user( $post['post_author'], true );
  240.                 if ( empty( $login ) ) {
  241.                     printf( __( 'Failed to import author %s. Their posts will be attributed to the current user.', 'wordpress-importer' ), esc_html( $post['post_author'] ) );
  242.                     echo '<br />';
  243.                     continue;
  244.                 }
  245.  
  246.                 if ( ! isset($this->authors[$login]) )
  247.                     $this->authors[$login] = array(
  248.                         'author_login' => $login,
  249.                         'author_display_name' => $post['post_author']
  250.                     );
  251.             }
  252.         }
  253.     }
  254.  
  255.     /**
  256.      * Display pre-import options, author importing/mapping and option to
  257.      * fetch attachments
  258.      */
  259.     function import_options() {
  260.         $j = 0;
  261. ?>
  262. <form action="<?php echo admin_url( 'admin.php?import=wordpress&amp;step=2' ); ?>" method="post">
  263.     <?php wp_nonce_field( 'import-wordpress' ); ?>
  264.     <input type="hidden" name="import_id" value="<?php echo $this->id; ?>" />
  265.  
  266. <?php if ( ! empty( $this->authors ) ) : ?>
  267.     <h3><?php _e( 'Assign Authors', 'wordpress-importer' ); ?></h3>
  268.     <p><?php _e( 'To make it easier for you to edit and save the imported content, you may want to reassign the author of the imported item to an existing user of this site. For example, you may want to import all the entries as <code>admin</code>s entries.', 'wordpress-importer' ); ?></p>
  269. <?php if ( $this->allow_create_users() ) : ?>
  270.     <p><?php printf( __( 'If a new user is created by WordPress, a new password will be randomly generated and the new user&#8217;s role will be set as %s. Manually changing the new user&#8217;s details will be necessary.', 'wordpress-importer' ), esc_html( get_option('default_role') ) ); ?></p>
  271. <?php endif; ?>
  272.     <ol id="authors">
  273. <?php foreach ( $this->authors as $author ) : ?>
  274.         <li><?php $this->author_select( $j++, $author ); ?></li>
  275. <?php endforeach; ?>
  276.     </ol>
  277. <?php endif; ?>
  278.  
  279. <?php if ( $this->allow_fetch_attachments() ) : ?>
  280.     <h3><?php _e( 'Import Attachments', 'wordpress-importer' ); ?></h3>
  281.     <p>
  282.         <input type="checkbox" value="1" name="fetch_attachments" id="import-attachments" />
  283.         <label for="import-attachments"><?php _e( 'Download and import file attachments', 'wordpress-importer' ); ?></label>
  284.     </p>
  285. <?php endif; ?>
  286.  
  287.     <p class="submit"><input type="submit" class="button" value="<?php esc_attr_e( 'Submit', 'wordpress-importer' ); ?>" /></p>
  288. </form>
  289. <?php
  290.     }
  291.  
  292.     /**
  293.      * Display import options for an individual author. That is, either create
  294.      * a new user based on import info or map to an existing user
  295.      *
  296.      * @param int $n Index for each author in the form
  297.      * @param array $author Author information, e.g. login, display name, email
  298.      */
  299.     function author_select( $n, $author ) {
  300.         _e( 'Import author:', 'wordpress-importer' );
  301.         echo ' <strong>' . esc_html( $author['author_display_name'] );
  302.         if ( $this->version != '1.0' ) echo ' (' . esc_html( $author['author_login'] ) . ')';
  303.         echo '</strong><br />';
  304.  
  305.         if ( $this->version != '1.0' )
  306.             echo '<div style="margin-left:18px">';
  307.  
  308.         $create_users = $this->allow_create_users();
  309.         if ( $create_users ) {
  310.             if ( $this->version != '1.0' ) {
  311.                 _e( 'or create new user with login name:', 'wordpress-importer' );
  312.                 $value = '';
  313.             } else {
  314.                 _e( 'as a new user:', 'wordpress-importer' );
  315.                 $value = esc_attr( sanitize_user( $author['author_login'], true ) );
  316.             }
  317.  
  318.             echo ' <input type="text" name="user_new['.$n.']" value="'. $value .'" /><br />';
  319.         }
  320.  
  321.         if ( ! $create_users && $this->version == '1.0' )
  322.             _e( 'assign posts to an existing user:', 'wordpress-importer' );
  323.         else
  324.             _e( 'or assign posts to an existing user:', 'wordpress-importer' );
  325.         wp_dropdown_users( array( 'name' => "user_map[$n]", 'multi' => true, 'show_option_all' => __( '- Select -', 'wordpress-importer' ) ) );
  326.         echo '<input type="hidden" name="imported_authors['.$n.']" value="' . esc_attr( $author['author_login'] ) . '" />';
  327.  
  328.         if ( $this->version != '1.0' )
  329.             echo '</div>';
  330.     }
  331.  
  332.     /**
  333.      * Map old author logins to local user IDs based on decisions made
  334.      * in import options form. Can map to an existing user, create a new user
  335.      * or falls back to the current user in case of error with either of the previous
  336.      */
  337.     function get_author_mapping() {
  338.         if ( ! isset( $_POST['imported_authors'] ) )
  339.             return;
  340.  
  341.         $create_users = $this->allow_create_users();
  342.  
  343.         foreach ( (array) $_POST['imported_authors'] as $i => $old_login ) {
  344.             // Multisite adds strtolower to sanitize_user. Need to sanitize here to stop breakage in process_posts.
  345.             $santized_old_login = sanitize_user( $old_login, true );
  346.             $old_id = isset( $this->authors[$old_login]['author_id'] ) ? intval($this->authors[$old_login]['author_id']) : false;
  347.  
  348.             if ( ! empty( $_POST['user_map'][$i] ) ) {
  349.                 $user = get_userdata( intval($_POST['user_map'][$i]) );
  350.                 if ( isset( $user->ID ) ) {
  351.                     if ( $old_id )
  352.                         $this->processed_authors[$old_id] = $user->ID;
  353.                     $this->author_mapping[$santized_old_login] = $user->ID;
  354.                 }
  355.             } else if ( $create_users ) {
  356.                 if ( ! empty($_POST['user_new'][$i]) ) {
  357.                     $user_id = wp_create_user( $_POST['user_new'][$i], wp_generate_password() );
  358.                 } else if ( $this->version != '1.0' ) {
  359.                     $user_data = array(
  360.                         'user_login' => $old_login,
  361.                         'user_pass' => wp_generate_password(),
  362.                         'user_email' => isset( $this->authors[$old_login]['author_email'] ) ? $this->authors[$old_login]['author_email'] : '',
  363.                         'display_name' => $this->authors[$old_login]['author_display_name'],
  364.                         'first_name' => isset( $this->authors[$old_login]['author_first_name'] ) ? $this->authors[$old_login]['author_first_name'] : '',
  365.                         'last_name' => isset( $this->authors[$old_login]['author_last_name'] ) ? $this->authors[$old_login]['author_last_name'] : '',
  366.                     );
  367.                     $user_id = wp_insert_user( $user_data );
  368.                 }
  369.  
  370.                 if ( ! is_wp_error( $user_id ) ) {
  371.                     if ( $old_id )
  372.                         $this->processed_authors[$old_id] = $user_id;
  373.                     $this->author_mapping[$santized_old_login] = $user_id;
  374.                 } else {
  375.                     printf( __( 'Failed to create new user for %s. Their posts will be attributed to the current user.', 'wordpress-importer' ), esc_html($this->authors[$old_login]['author_display_name']) );
  376.                     if ( defined('IMPORT_DEBUG') && IMPORT_DEBUG )
  377.                         echo ' ' . $user_id->get_error_message();
  378.                     echo '<br />';
  379.                 }
  380.             }
  381.  
  382.             // failsafe: if the user_id was invalid, default to the current user
  383.             if ( ! isset( $this->author_mapping[$santized_old_login] ) ) {
  384.                 if ( $old_id )
  385.                     $this->processed_authors[$old_id] = (int) get_current_user_id();
  386.                 $this->author_mapping[$santized_old_login] = (int) get_current_user_id();
  387.             }
  388.         }
  389.     }
  390.  
  391.     /**
  392.      * Create new categories based on import information
  393.      *
  394.      * Doesn't create a new category if its slug already exists
  395.      */
  396.     function process_categories() {
  397.         if ( empty( $this->categories ) )
  398.             return;
  399.  
  400.         foreach ( $this->categories as $cat ) {
  401.             // if the category already exists leave it alone
  402.             $term_id = term_exists( $cat['category_nicename'], 'category' );
  403.             if ( $term_id ) {
  404.                 if ( is_array($term_id) ) $term_id = $term_id['term_id'];
  405.                 if ( isset($cat['term_id']) )
  406.                     $this->processed_terms[intval($cat['term_id'])] = (int) $term_id;
  407.                 continue;
  408.             }
  409.  
  410.             $category_parent = empty( $cat['category_parent'] ) ? 0 : category_exists( $cat['category_parent'] );
  411.             $category_description = isset( $cat['category_description'] ) ? $cat['category_description'] : '';
  412.             $catarr = array(
  413.                 'category_nicename' => $cat['category_nicename'],
  414.                 'category_parent' => $category_parent,
  415.                 'cat_name' => $cat['cat_name'],
  416.                 'category_description' => $category_description
  417.             );
  418.  
  419.             $id = wp_insert_category( $catarr );
  420.             if ( ! is_wp_error( $id ) ) {
  421.                 if ( isset($cat['term_id']) )
  422.                     $this->processed_terms[intval($cat['term_id'])] = $id;
  423.             } else {
  424.                 printf( __( 'Failed to import category %s', 'wordpress-importer' ), esc_html($cat['category_nicename']) );
  425.                 if ( defined('IMPORT_DEBUG') && IMPORT_DEBUG )
  426.                     echo ': ' . $id->get_error_message();
  427.                 echo '<br />';
  428.                 continue;
  429.             }
  430.         }
  431.  
  432.         unset( $this->categories );
  433.     }
  434.  
  435.     /**
  436.      * Create new post tags based on import information
  437.      *
  438.      * Doesn't create a tag if its slug already exists
  439.      */
  440.     function process_tags() {
  441.         if ( empty( $this->tags ) )
  442.             return;
  443.  
  444.         foreach ( $this->tags as $tag ) {
  445.             // if the tag already exists leave it alone
  446.             $term_id = term_exists( $tag['tag_slug'], 'post_tag' );
  447.             if ( $term_id ) {
  448.                 if ( is_array($term_id) ) $term_id = $term_id['term_id'];
  449.                 if ( isset($tag['term_id']) )
  450.                     $this->processed_terms[intval($tag['term_id'])] = (int) $term_id;
  451.                 continue;
  452.             }
  453.  
  454.             $tag_desc = isset( $tag['tag_description'] ) ? $tag['tag_description'] : '';
  455.             $tagarr = array( 'slug' => $tag['tag_slug'], 'description' => $tag_desc );
  456.  
  457.             $id = wp_insert_term( $tag['tag_name'], 'post_tag', $tagarr );
  458.             if ( ! is_wp_error( $id ) ) {
  459.                 if ( isset($tag['term_id']) )
  460.                     $this->processed_terms[intval($tag['term_id'])] = $id['term_id'];
  461.             } else {
  462.                 printf( __( 'Failed to import post tag %s', 'wordpress-importer' ), esc_html($tag['tag_name']) );
  463.                 if ( defined('IMPORT_DEBUG') && IMPORT_DEBUG )
  464.                     echo ': ' . $id->get_error_message();
  465.                 echo '<br />';
  466.                 continue;
  467.             }
  468.         }
  469.  
  470.         unset( $this->tags );
  471.     }
  472.  
  473.     /**
  474.      * Create new terms based on import information
  475.      *
  476.      * Doesn't create a term its slug already exists
  477.      */
  478.     function process_terms() {
  479.         if ( empty( $this->terms ) )
  480.             return;
  481.  
  482.         foreach ( $this->terms as $term ) {
  483.             // if the term already exists in the correct taxonomy leave it alone
  484.             $term_id = term_exists( $term['slug'], $term['term_taxonomy'] );
  485.             if ( $term_id ) {
  486.                 if ( is_array($term_id) ) $term_id = $term_id['term_id'];
  487.                 if ( isset($term['term_id']) )
  488.                     $this->processed_terms[intval($term['term_id'])] = (int) $term_id;
  489.                 continue;
  490.             }
  491.  
  492.             if ( empty( $term['term_parent'] ) ) {
  493.                 $parent = 0;
  494.             } else {
  495.                 $parent = term_exists( $term['term_parent'], $term['term_taxonomy'] );
  496.                 if ( is_array( $parent ) ) $parent = $parent['term_id'];
  497.             }
  498.             $description = isset( $term['term_description'] ) ? $term['term_description'] : '';
  499.             $termarr = array( 'slug' => $term['slug'], 'description' => $description, 'parent' => intval($parent) );
  500.  
  501.             $id = wp_insert_term( $term['term_name'], $term['term_taxonomy'], $termarr );
  502.             if ( ! is_wp_error( $id ) ) {
  503.                 if ( isset($term['term_id']) )
  504.                     $this->processed_terms[intval($term['term_id'])] = $id['term_id'];
  505.             } else {
  506.                 printf( __( 'Failed to import %s %s', 'wordpress-importer' ), esc_html($term['term_taxonomy']), esc_html($term['term_name']) );
  507.                 if ( defined('IMPORT_DEBUG') && IMPORT_DEBUG )
  508.                     echo ': ' . $id->get_error_message();
  509.                 echo '<br />';
  510.                 continue;
  511.             }
  512.         }
  513.  
  514.         unset( $this->terms );
  515.     }
  516.  
  517.     /**
  518.      * Create new posts based on import information
  519.      *
  520.      * Posts marked as having a parent which doesn't exist will become top level items.
  521.      * Doesn't create a new post if: the post type doesn't exist, the given post ID
  522.      * is already noted as imported or a post with the same title and date already exists.
  523.      * Note that new/updated terms, comments and meta are imported for the last of the above.
  524.      */
  525.     function process_posts() {
  526.         foreach ( $this->posts as $post ) {
  527.             if ( ! post_type_exists( $post['post_type'] ) ) {
  528.                 printf( __( 'Failed to import &#8220;%s&#8221;: Invalid post type %s', 'wordpress-importer' ),
  529.                     esc_html($post['post_title']), esc_html($post['post_type']) );
  530.                 echo '<br />';
  531.                 continue;
  532.             }
  533.  
  534.             if ( isset( $this->processed_posts[$post['post_id']] ) && ! empty( $post['post_id'] ) )
  535.                 continue;
  536.  
  537.             if ( $post['status'] == 'auto-draft' )
  538.                 continue;
  539.  
  540.             if ( 'nav_menu_item' == $post['post_type'] ) {
  541.                 $this->process_menu_item( $post );
  542.                 continue;
  543.             }
  544.  
  545.             $post_type_object = get_post_type_object( $post['post_type'] );
  546.  
  547.             $post_exists = post_exists( $post['post_title'], '', $post['post_date'] );
  548.             if ( $post_exists && get_post_type( $post_exists ) == $post['post_type'] ) {
  549.                 printf( __('%s &#8220;%s&#8221; already exists.', 'wordpress-importer'), $post_type_object->labels->singular_name, esc_html($post['post_title']) );
  550.                 echo '<br />';
  551.                 $comment_post_ID = $post_id = $post_exists;
  552.             } else {
  553.                 $post_parent = (int) $post['post_parent'];
  554.                 if ( $post_parent ) {
  555.                     // if we already know the parent, map it to the new local ID
  556.                     if ( isset( $this->processed_posts[$post_parent] ) ) {
  557.                         $post_parent = $this->processed_posts[$post_parent];
  558.                     // otherwise record the parent for later
  559.                     } else {
  560.                         $this->post_orphans[intval($post['post_id'])] = $post_parent;
  561.                         $post_parent = 0;
  562.                     }
  563.                 }
  564.  
  565.                 // map the post author
  566.                 $author = sanitize_user( $post['post_author'], true );
  567.                 if ( isset( $this->author_mapping[$author] ) )
  568.                     $author = $this->author_mapping[$author];
  569.                 else
  570.                     $author = (int) get_current_user_id();
  571.  
  572.                 $postdata = array(
  573.                     'import_id' => $post['post_id'], 'post_author' => $author, 'post_date' => $post['post_date'],
  574.                     'post_date_gmt' => $post['post_date_gmt'], 'post_content' => $post['post_content'],
  575.                     'post_excerpt' => $post['post_excerpt'], 'post_title' => $post['post_title'],
  576.                     'post_status' => $post['status'], 'post_name' => $post['post_name'],
  577.                     'comment_status' => $post['comment_status'], 'ping_status' => $post['ping_status'],
  578.                     'guid' => $post['guid'], 'post_parent' => $post_parent, 'menu_order' => $post['menu_order'],
  579.                     'post_type' => $post['post_type'], 'post_password' => $post['post_password']
  580.                 );
  581.  
  582.                 if ( 'attachment' == $postdata['post_type'] ) {
  583.                     $remote_url = ! empty($post['attachment_url']) ? $post['attachment_url'] : $post['guid'];
  584.  
  585.                     // try to use _wp_attached file for upload folder placement to ensure the same location as the export site
  586.                     // e.g. location is 2003/05/image.jpg but the attachment post_date is 2010/09, see media_handle_upload()
  587.                     $postdata['upload_date'] = $post['post_date'];
  588.                     if ( isset( $post['postmeta'] ) ) {
  589.                         foreach( $post['postmeta'] as $meta ) {
  590.                             if ( $meta['key'] == '_wp_attached_file' ) {
  591.                                 if ( preg_match( '%^[0-9]{4}/[0-9]{2}%', $meta['value'], $matches ) )
  592.                                     $postdata['upload_date'] = $matches[0];
  593.                                 break;
  594.                             }
  595.                         }
  596.                     }
  597.                     $comment_post_ID = $post_id = $this->process_attachment( $postdata, $remote_url );
  598.                 } else {
  599.                     $comment_post_ID = $post_id = wp_insert_post( $postdata, true );
  600.                 }
  601.  
  602.                 if ( is_wp_error( $post_id ) ) {
  603.                     printf( __( 'Failed to import %s &#8220;%s&#8221;', 'wordpress-importer' ),
  604.                         $post_type_object->labels->singular_name, esc_html($post['post_title']) );
  605.                     if ( defined('IMPORT_DEBUG') && IMPORT_DEBUG )
  606.                         echo ': ' . $post_id->get_error_message();
  607.                     echo '<br />';
  608.                     continue;
  609.                 }
  610.  
  611.                 if ( $post['is_sticky'] == 1 )
  612.                     stick_post( $post_id );
  613.             }
  614.  
  615.             // map pre-import ID to local ID
  616.             $this->processed_posts[intval($post['post_id'])] = (int) $post_id;
  617.  
  618.             // add categories, tags and other terms
  619.             if ( ! empty( $post['terms'] ) ) {
  620.                 $terms_to_set = array();
  621.                 foreach ( $post['terms'] as $term ) {
  622.                     // back compat with WXR 1.0 map 'tag' to 'post_tag'
  623.                     $taxonomy = ( 'tag' == $term['domain'] ) ? 'post_tag' : $term['domain'];
  624.                     $term_exists = term_exists( $term['slug'], $taxonomy );
  625.                     $term_id = is_array( $term_exists ) ? $term_exists['term_id'] : $term_exists;
  626.                     if ( ! $term_id ) {
  627.                         $t = wp_insert_term( $term['name'], $taxonomy, array( 'slug' => $term['slug'] ) );
  628.                         if ( ! is_wp_error( $t ) ) {
  629.                             $term_id = $t['term_id'];
  630.                         } else {
  631.                             printf( __( 'Failed to import %s %s', 'wordpress-importer' ), esc_html($taxonomy), esc_html($term['name']) );
  632.                             if ( defined('IMPORT_DEBUG') && IMPORT_DEBUG )
  633.                                 echo ': ' . $t->get_error_message();
  634.                             echo '<br />';
  635.                             continue;
  636.                         }
  637.                     }
  638.                     $terms_to_set[$taxonomy][] = intval( $term_id );
  639.                 }
  640.  
  641.                 foreach ( $terms_to_set as $tax => $ids ) {
  642.                     $tt_ids = wp_set_post_terms( $post_id, $ids, $tax );
  643.                 }
  644.                 unset( $post['terms'], $terms_to_set );
  645.             }
  646.  
  647.             // add/update comments
  648.             if ( ! empty( $post['comments'] ) ) {
  649.                 $num_comments = 0;
  650.                 $inserted_comments = array();
  651.                 foreach ( $post['comments'] as $comment ) {
  652.                     $comment_id = $comment['comment_id'];
  653.                     $newcomments[$comment_id]['comment_post_ID']      = $comment_post_ID;
  654.                     $newcomments[$comment_id]['comment_author']       = $comment['comment_author'];
  655.                     $newcomments[$comment_id]['comment_author_email'] = $comment['comment_author_email'];
  656.                     $newcomments[$comment_id]['comment_author_IP']    = $comment['comment_author_IP'];
  657.                     $newcomments[$comment_id]['comment_author_url']   = $comment['comment_author_url'];
  658.                     $newcomments[$comment_id]['comment_date']         = $comment['comment_date'];
  659.                     $newcomments[$comment_id]['comment_date_gmt']     = $comment['comment_date_gmt'];
  660.                     $newcomments[$comment_id]['comment_content']      = $comment['comment_content'];
  661.                     $newcomments[$comment_id]['comment_approved']     = $comment['comment_approved'];
  662.                     $newcomments[$comment_id]['comment_type']         = $comment['comment_type'];
  663.                     $newcomments[$comment_id]['comment_parent']       = $comment['comment_parent'];
  664.                     $newcomments[$comment_id]['commentmeta']          = isset( $comment['commentmeta'] ) ? $comment['commentmeta'] : array();
  665.                     if ( isset( $this->processed_authors[$comment['comment_user_id']] ) )
  666.                         $newcomments[$comment_id]['user_id'] = $this->processed_authors[$comment['comment_user_id']];
  667.                 }
  668.                 ksort( $newcomments );
  669.  
  670.                 foreach ( $newcomments as $key => $comment ) {
  671.                     // if this is a new post we can skip the comment_exists() check
  672.                     if ( ! $post_exists || ! comment_exists( $comment['comment_author'], $comment['comment_date'] ) ) {
  673.                         if ( isset( $inserted_comments[$comment['comment_parent']] ) )
  674.                             $comment['comment_parent'] = $inserted_comments[$comment['comment_parent']];
  675.                         $comment = wp_filter_comment( $comment );
  676.                         $inserted_comments[$key] = wp_insert_comment( $comment );
  677.  
  678.                         foreach( $comment['commentmeta'] as $meta ) {
  679.                             $value = maybe_unserialize( $meta['value'] );
  680.                             add_comment_meta( $inserted_comments[$key], $meta['key'], $value );
  681.                         }
  682.  
  683.                         $num_comments++;
  684.                     }
  685.                 }
  686.                 unset( $newcomments, $inserted_comments, $post['comments'] );
  687.             }
  688.  
  689.             // add/update post meta
  690.             if ( isset( $post['postmeta'] ) ) {
  691.                 foreach ( $post['postmeta'] as $meta ) {
  692.                     $key = apply_filters( 'import_post_meta_key', $meta['key'] );
  693.                     $value = false;
  694.  
  695.                     if ( '_edit_last' == $key ) {
  696.                         if ( isset( $this->processed_authors[intval($meta['value'])] ) )
  697.                             $value = $this->processed_authors[intval($meta['value'])];
  698.                         else
  699.                             $key = false;
  700.                     }
  701.  
  702.                     if ( $key ) {
  703.                         // export gets meta straight from the DB so could have a serialized string
  704.                         if ( ! $value )
  705.                             $value = maybe_unserialize( $meta['value'] );
  706.  
  707.                         add_post_meta( $post_id, $key, $value );
  708.                         do_action( 'import_post_meta', $post_id, $key, $value );
  709.  
  710.                         // if the post has a featured image, take note of this in case of remap
  711.                         if ( '_thumbnail_id' == $key )
  712.                             $this->featured_images[$post_id] = (int) $value;
  713.                     }
  714.                 }
  715.             }
  716.         }
  717.  
  718.         unset( $this->posts );
  719.     }
  720.  
  721.     /**
  722.      * Attempt to create a new menu item from import data
  723.      *
  724.      * Fails for draft, orphaned menu items and those without an associated nav_menu
  725.      * or an invalid nav_menu term. If the post type or term object which the menu item
  726.      * represents doesn't exist then the menu item will not be imported (waits until the
  727.      * end of the import to retry again before discarding).
  728.      *
  729.      * @param array $item Menu item details from WXR file
  730.      */
  731.     function process_menu_item( $item ) {
  732.         // skip draft, orphaned menu items
  733.         if ( 'draft' == $item['status'] )
  734.             return;
  735.  
  736.         $menu_slug = false;
  737.         if ( isset($item['terms']) ) {
  738.             // loop through terms, assume first nav_menu term is correct menu
  739.             foreach ( $item['terms'] as $term ) {
  740.                 if ( 'nav_menu' == $term['domain'] ) {
  741.                     $menu_slug = $term['slug'];
  742.                     break;
  743.                 }
  744.             }
  745.         }
  746.  
  747.         // no nav_menu term associated with this menu item
  748.         if ( ! $menu_slug ) {
  749.             _e( 'Menu item skipped due to missing menu slug', 'wordpress-importer' );
  750.             echo '<br />';
  751.             return;
  752.         }
  753.  
  754.         $menu_id = term_exists( $menu_slug, 'nav_menu' );
  755.         if ( ! $menu_id ) {
  756.             printf( __( 'Menu item skipped due to invalid menu slug: %s', 'wordpress-importer' ), esc_html( $menu_slug ) );
  757.             echo '<br />';
  758.             return;
  759.         } else {
  760.             $menu_id = is_array( $menu_id ) ? $menu_id['term_id'] : $menu_id;
  761.         }
  762.  
  763.         foreach ( $item['postmeta'] as $meta )
  764.             $$meta['key'] = $meta['value'];
  765.  
  766.         if ( 'taxonomy' == $_menu_item_type && isset( $this->processed_terms[intval($_menu_item_object_id)] ) ) {
  767.             $_menu_item_object_id = $this->processed_terms[intval($_menu_item_object_id)];
  768.         } else if ( 'post_type' == $_menu_item_type && isset( $this->processed_posts[intval($_menu_item_object_id)] ) ) {
  769.             $_menu_item_object_id = $this->processed_posts[intval($_menu_item_object_id)];
  770.         } else if ( 'custom' != $_menu_item_type ) {
  771.             // associated object is missing or not imported yet, we'll retry later
  772.             $this->missing_menu_items[] = $item;
  773.             return;
  774.         }
  775.  
  776.         if ( isset( $this->processed_menu_items[intval($_menu_item_menu_item_parent)] ) ) {
  777.             $_menu_item_menu_item_parent = $this->processed_menu_items[intval($_menu_item_menu_item_parent)];
  778.         } else if ( $_menu_item_menu_item_parent ) {
  779.             $this->menu_item_orphans[intval($item['post_id'])] = (int) $_menu_item_menu_item_parent;
  780.             $_menu_item_menu_item_parent = 0;
  781.         }
  782.  
  783.         // wp_update_nav_menu_item expects CSS classes as a space separated string
  784.         $_menu_item_classes = maybe_unserialize( $_menu_item_classes );
  785.         if ( is_array( $_menu_item_classes ) )
  786.             $_menu_item_classes = implode( ' ', $_menu_item_classes );
  787.  
  788.         $args = array(
  789.             'menu-item-object-id' => $_menu_item_object_id,
  790.             'menu-item-object' => $_menu_item_object,
  791.             'menu-item-parent-id' => $_menu_item_menu_item_parent,
  792.             'menu-item-position' => intval( $item['menu_order'] ),
  793.             'menu-item-type' => $_menu_item_type,
  794.             'menu-item-title' => $item['post_title'],
  795.             'menu-item-url' => $_menu_item_url,
  796.             'menu-item-description' => $item['post_content'],
  797.             'menu-item-attr-title' => $item['post_excerpt'],
  798.             'menu-item-target' => $_menu_item_target,
  799.             'menu-item-classes' => $_menu_item_classes,
  800.             'menu-item-xfn' => $_menu_item_xfn,
  801.             'menu-item-status' => $item['status']
  802.         );
  803.  
  804.         $id = wp_update_nav_menu_item( $menu_id, 0, $args );
  805.         if ( $id && ! is_wp_error( $id ) )
  806.             $this->processed_menu_items[intval($item['post_id'])] = (int) $id;
  807.     }
  808.  
  809.     /**
  810.      * If fetching attachments is enabled then attempt to create a new attachment
  811.      *
  812.      * @param array $post Attachment post details from WXR
  813.      * @param string $url URL to fetch attachment from
  814.      * @return int|WP_Error Post ID on success, WP_Error otherwise
  815.      */
  816.     function process_attachment( $post, $url ) {
  817.         if ( ! $this->fetch_attachments )
  818.             return new WP_Error( 'attachment_processing_error',
  819.                 __( 'Fetching attachments is not enabled', 'wordpress-importer' ) );
  820.  
  821.         // if the URL is absolute, but does not contain address, then upload it assuming base_site_url
  822. //mod jrc 300312 - more reliable matching - esp. for wpmu 2.8 paths - eg: 'files/2009/12/myfile.jpg' (note: no leading '/') Vs 'http://dmionline.net/files/2009/12/myfile.jpg' - as output by advanced-export-for-wp-wpmu plugin (http://wordpress.org/extend/plugins/advanced-export-for-wp-wpmu/) working on wpmu V2.8/V2.9 and earlier
  823. //orig:
  824. //      if ( preg_match( '|^/[\w\W]+$|', $url ) )
  825. //          $url = rtrim( $this->base_url, '/' ) . $url;
  826. //new:
  827.         if (stripos($url,'www.') === 0) {
  828.             $url = 'http://' . $url;           
  829.         }
  830.         if (!(stripos($url,'http://') === 0 )) {
  831.             if (strpos($url,'/') === 0)  {
  832.                 $url = rtrim( $this->base_url, '/' ) . $url;
  833.             } else {
  834.                 $url = $this->base_url . $url;
  835.             }              
  836.         }
  837. //end mod jrc 300312
  838.  
  839.         $upload = $this->fetch_remote_file( $url, $post );
  840.         if ( is_wp_error( $upload ) )
  841.             return $upload;
  842.  
  843.         if ( $info = wp_check_filetype( $upload['file'] ) )
  844.             $post['post_mime_type'] = $info['type'];
  845.         else
  846.             return new WP_Error( 'attachment_processing_error', __('Invalid file type', 'wordpress-importer') );
  847.  
  848.         $post['guid'] = $upload['url'];
  849.  
  850.         // as per wp-admin/includes/upload.php
  851.         $post_id = wp_insert_attachment( $post, $upload['file'] );
  852.         wp_update_attachment_metadata( $post_id, wp_generate_attachment_metadata( $post_id, $upload['file'] ) );
  853.  
  854.         // remap resized image URLs, works by stripping the extension and remapping the URL stub.
  855.         if ( preg_match( '!^image/!', $info['type'] ) ) {
  856. //mod jrc 050412 - also prepare to substitute any stray relative paths to the attachment, as well as absolute paths found in content by backfill_attachment_urls
  857. //note: if importing multiple batches be sure to a) load ALL posts before attatchments b) import all attachments as single batch, (if at all possible).
  858. //orig:
  859. /*
  860.             $parts = pathinfo( $url );
  861.             $name = basename( $parts['basename'], ".{$parts['extension']}" ); // PATHINFO_FILENAME in PHP 5.2
  862.  
  863.             $parts_new = pathinfo( $upload['url'] );
  864.             $name_new = basename( $parts_new['basename'], ".{$parts_new['extension']}" );
  865.  
  866.             $this->url_remap[$parts['dirname'] . '/' . $name] = $parts_new['dirname'] . '/' . $name_new;
  867. */
  868. //new:
  869.             $url_from_parts = parse_url($url);
  870.             $path_from_parts = pathinfo($url_from_parts['path']);
  871.             if (!defined('PATHINFO_FILENAME')) $path_from_parts['filename'] = basename( $path_from_parts['basename'], '.' . $path_from_parts['extension'] ); //php < 5.2 fix for pathinfo
  872.  
  873.             $url_from_str = (isset($url_from_parts['scheme']))? $url_from_parts['scheme'] . '://' . $url_from_parts['host'] . $path_from_parts['dirname'] . '/' . $path_from_parts['filename'] : '';
  874.             $path_from_str = ltrim($path_from_parts['dirname'] . '/' . $path_from_parts['filename'],'/');
  875.  
  876.             $url_to_parts = parse_url($upload['url']);
  877.             $path_to_parts = pathinfo($url_to_parts['path']);
  878.             if (!defined('PATHINFO_FILENAME')) $path_to_parts['filename'] = basename( $path_to_parts['basename'], '.' . $path_to_parts['extension'] ); //php < 5.2 fix for pathinfo
  879.  
  880.             $url_to_str = (isset($url_to_parts['scheme']))? $url_to_parts['scheme'] . '://' . $url_to_parts['host'] . $path_to_parts['dirname'] . '/' . $path_to_parts['filename'] : '';
  881.             $path_to_str = ltrim($path_to_parts['dirname'] . '/' . $path_to_parts['filename'],'/');
  882.  
  883.             if (!empty($url_from_str)) $this->url_remap[$url_from_str] = $url_to_str;
  884.             if (strcmp($path_from_str,$path_to_str) !== 0) $this->url_remap[$path_from_str] = $path_to_str;
  885. //end mod jrc 050412
  886.         }
  887.  
  888.         return $post_id;
  889.     }
  890.  
  891.     /**
  892.      * Attempt to download a remote file attachment
  893.      *
  894.      * @param string $url URL of item to fetch
  895.      * @param array $post Attachment details
  896.      * @return array|WP_Error Local file location details on success, WP_Error otherwise
  897.      */
  898.     function fetch_remote_file( $url, $post ) {
  899.         // extract the file name and extension from the url
  900.         $file_name = basename( $url );
  901.  
  902.         // get placeholder file in the upload dir with a unique, sanitized filename
  903.         $upload = wp_upload_bits( $file_name, 0, '', $post['upload_date'] );
  904.         if ( $upload['error'] )
  905.             return new WP_Error( 'upload_dir_error', $upload['error'] );
  906.  
  907.         // fetch the remote url and write it to the placeholder file
  908.         $headers = wp_get_http( $url, $upload['file'] );
  909.  
  910.         // request failed
  911.         if ( ! $headers ) {
  912.             @unlink( $upload['file'] );
  913.             return new WP_Error( 'import_file_error', __('Remote server did not respond', 'wordpress-importer') );
  914.         }
  915.  
  916.         // make sure the fetch was successful
  917.         if ( $headers['response'] != '200' ) {
  918.             @unlink( $upload['file'] );
  919.             return new WP_Error( 'import_file_error', sprintf( __('Remote server returned error response %1$d %2$s', 'wordpress-importer'), esc_html($headers['response']), get_status_header_desc($headers['response']) ) );
  920.         }
  921.  
  922.         $filesize = filesize( $upload['file'] );
  923.  
  924.         if ( isset( $headers['content-length'] ) && $filesize != $headers['content-length'] ) {
  925.             @unlink( $upload['file'] );
  926.             return new WP_Error( 'import_file_error', __('Remote file is incorrect size', 'wordpress-importer') );
  927.         }
  928.  
  929.         if ( 0 == $filesize ) {
  930.             @unlink( $upload['file'] );
  931.             return new WP_Error( 'import_file_error', __('Zero size file downloaded', 'wordpress-importer') );
  932.         }
  933.  
  934.         $max_size = (int) $this->max_attachment_size();
  935.         if ( ! empty( $max_size ) && $filesize > $max_size ) {
  936.             @unlink( $upload['file'] );
  937.             return new WP_Error( 'import_file_error', sprintf(__('Remote file is too large, limit is %s', 'wordpress-importer'), size_format($max_size) ) );
  938.         }
  939.  
  940.         // keep track of the old and new urls so we can substitute them later
  941.         $this->url_remap[$url] = $upload['url'];
  942.         $this->url_remap[$post['guid']] = $upload['url']; // r13735, really needed?
  943.         // keep track of the destination if the remote url is redirected somewhere else
  944.         if ( isset($headers['x-final-location']) && $headers['x-final-location'] != $url )
  945.             $this->url_remap[$headers['x-final-location']] = $upload['url'];
  946.  
  947.         return $upload;
  948.     }
  949.  
  950.     /**
  951.      * Attempt to associate posts and menu items with previously missing parents
  952.      *
  953.      * An imported post's parent may not have been imported when it was first created
  954.      * so try again. Similarly for child menu items and menu items which were missing
  955.      * the object (e.g. post) they represent in the menu
  956.      */
  957.     function backfill_parents() {
  958.         global $wpdb;
  959.  
  960.         // find parents for post orphans
  961.         foreach ( $this->post_orphans as $child_id => $parent_id ) {
  962.             $local_child_id = $local_parent_id = false;
  963.             if ( isset( $this->processed_posts[$child_id] ) )
  964.                 $local_child_id = $this->processed_posts[$child_id];
  965.             if ( isset( $this->processed_posts[$parent_id] ) )
  966.                 $local_parent_id = $this->processed_posts[$parent_id];
  967.  
  968.             if ( $local_child_id && $local_parent_id )
  969.                 $wpdb->update( $wpdb->posts, array( 'post_parent' => $local_parent_id ), array( 'ID' => $local_child_id ), '%d', '%d' );
  970.         }
  971.  
  972.         // all other posts/terms are imported, retry menu items with missing associated object
  973.         $missing_menu_items = $this->missing_menu_items;
  974.         foreach ( $missing_menu_items as $item )
  975.             $this->process_menu_item( $item );
  976.  
  977.         // find parents for menu item orphans
  978.         foreach ( $this->menu_item_orphans as $child_id => $parent_id ) {
  979.             $local_child_id = $local_parent_id = 0;
  980.             if ( isset( $this->processed_menu_items[$child_id] ) )
  981.                 $local_child_id = $this->processed_menu_items[$child_id];
  982.             if ( isset( $this->processed_menu_items[$parent_id] ) )
  983.                 $local_parent_id = $this->processed_menu_items[$parent_id];
  984.  
  985.             if ( $local_child_id && $local_parent_id )
  986.                 update_post_meta( $local_child_id, '_menu_item_menu_item_parent', (int) $local_parent_id );
  987.         }
  988.     }
  989.  
  990.     /**
  991.      * Use stored mapping information to update old attachment URLs
  992.      */
  993.     function backfill_attachment_urls() {
  994.         global $wpdb;
  995.         // make sure we do the longest urls first, in case one is a substring of another
  996.         uksort( $this->url_remap, array(&$this, 'cmpr_strlen') );
  997.  
  998.         foreach ( $this->url_remap as $from_url => $to_url ) {
  999.             // remap urls in post_content
  1000.             $wpdb->query( $wpdb->prepare("UPDATE {$wpdb->posts} SET post_content = REPLACE(post_content, %s, %s)", $from_url, $to_url) );
  1001.             // remap enclosure urls
  1002.             $result = $wpdb->query( $wpdb->prepare("UPDATE {$wpdb->postmeta} SET meta_value = REPLACE(meta_value, %s, %s) WHERE meta_key='enclosure'", $from_url, $to_url) );
  1003.         }
  1004.     }
  1005.  
  1006.     /**
  1007.      * Update _thumbnail_id meta to new, imported attachment IDs
  1008.      */
  1009.     function remap_featured_images() {
  1010.         // cycle through posts that have a featured image
  1011.         foreach ( $this->featured_images as $post_id => $value ) {
  1012.             if ( isset( $this->processed_posts[$value] ) ) {
  1013.                 $new_id = $this->processed_posts[$value];
  1014.                 // only update if there's a difference
  1015.                 if ( $new_id != $value )
  1016.                     update_post_meta( $post_id, '_thumbnail_id', $new_id );
  1017.             }
  1018.         }
  1019.     }
  1020.  
  1021.     /**
  1022.      * Parse a WXR file
  1023.      *
  1024.      * @param string $file Path to WXR file for parsing
  1025.      * @return array Information gathered from the WXR file
  1026.      */
  1027.     function parse( $file ) {
  1028.         $parser = new WXR_Parser();
  1029.         return $parser->parse( $file );
  1030.     }
  1031.  
  1032.     // Display import page title
  1033.     function header() {
  1034.         echo '<div class="wrap">';
  1035.         screen_icon();
  1036.         echo '<h2>' . __( 'Import WordPress', 'wordpress-importer' ) . '</h2>';
  1037.  
  1038.         $updates = get_plugin_updates();
  1039.         $basename = plugin_basename(__FILE__);
  1040.         if ( isset( $updates[$basename] ) ) {
  1041.             $update = $updates[$basename];
  1042.             echo '<div class="error"><p><strong>';
  1043.             printf( __( 'A new version of this importer is available. Please update to version %s to ensure compatibility with newer export files.', 'wordpress-importer' ), $update->update->new_version );
  1044.             echo '</strong></p></div>';
  1045.         }
  1046.     }
  1047.  
  1048.     // Close div.wrap
  1049.     function footer() {
  1050.         echo '</div>';
  1051.     }
  1052.  
  1053.     /**
  1054.      * Display introductory text and file upload form
  1055.      */
  1056.     function greet() {
  1057.         echo '<div class="narrow">';
  1058.         echo '<p>'.__( 'Howdy! Upload your WordPress eXtended RSS (WXR) file and we&#8217;ll import the posts, pages, comments, custom fields, categories, and tags into this site.', 'wordpress-importer' ).'</p>';
  1059.         echo '<p>'.__( 'Choose a WXR (.xml) file to upload, then click Upload file and import.', 'wordpress-importer' ).'</p>';
  1060.         wp_import_upload_form( 'admin.php?import=wordpress&amp;step=1' );
  1061.         echo '</div>';
  1062.     }
  1063.  
  1064.     /**
  1065.      * Decide if the given meta key maps to information we will want to import
  1066.      *
  1067.      * @param string $key The meta key to check
  1068.      * @return string|bool The key if we do want to import, false if not
  1069.      */
  1070.     function is_valid_meta_key( $key ) {
  1071.         // skip attachment metadata since we'll regenerate it from scratch
  1072.         // skip _edit_lock as not relevant for import
  1073.         if ( in_array( $key, array( '_wp_attached_file', '_wp_attachment_metadata', '_edit_lock' ) ) )
  1074.             return false;
  1075.         return $key;
  1076.     }
  1077.  
  1078.     /**
  1079.      * Decide whether or not the importer is allowed to create users.
  1080.      * Default is true, can be filtered via import_allow_create_users
  1081.      *
  1082.      * @return bool True if creating users is allowed
  1083.      */
  1084.     function allow_create_users() {
  1085.         return apply_filters( 'import_allow_create_users', true );
  1086.     }
  1087.  
  1088.     /**
  1089.      * Decide whether or not the importer should attempt to download attachment files.
  1090.      * Default is true, can be filtered via import_allow_fetch_attachments. The choice
  1091.      * made at the import options screen must also be true, false here hides that checkbox.
  1092.      *
  1093.      * @return bool True if downloading attachments is allowed
  1094.      */
  1095.     function allow_fetch_attachments() {
  1096.         return apply_filters( 'import_allow_fetch_attachments', true );
  1097.     }
  1098.  
  1099.     /**
  1100.      * Decide what the maximum file size for downloaded attachments is.
  1101.      * Default is 0 (unlimited), can be filtered via import_attachment_size_limit
  1102.      *
  1103.      * @return int Maximum attachment file size to import
  1104.      */
  1105.     function max_attachment_size() {
  1106.         return apply_filters( 'import_attachment_size_limit', 0 );
  1107.     }
  1108.  
  1109.     /**
  1110.      * Added to http_request_timeout filter to force timeout at 60 seconds during import
  1111.      * @return int 60
  1112.      */
  1113.     function bump_request_timeout() {
  1114.         return 60;
  1115.     }
  1116.  
  1117.     // return the difference in length between two strings
  1118.     function cmpr_strlen( $a, $b ) {
  1119.         return strlen($b) - strlen($a);
  1120.     }
  1121. }
  1122.  
  1123. } // class_exists( 'WP_Importer' )
  1124.  
  1125. function wordpress_importer_init() {
  1126.     load_plugin_textdomain( 'wordpress-importer', false, dirname( plugin_basename( __FILE__ ) ) . '/languages' );
  1127.  
  1128.     /**
  1129.      * WordPress Importer object for registering the import callback
  1130.      * @global WP_Import $wp_import
  1131.      */
  1132.     $GLOBALS['wp_import'] = new WP_Import();
  1133.     register_importer( 'wordpress', 'WordPress', __('Import <strong>posts, pages, comments, custom fields, categories, and tags</strong> from a WordPress export file.', 'wordpress-importer'), array( $GLOBALS['wp_import'], 'dispatch' ) );
  1134. }
  1135. add_action( 'admin_init', 'wordpress_importer_init' );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement