Make WordPress Core


Ignore:
Timestamp:
12/16/2007 09:34:48 PM (16 years ago)
Author:
ryan
Message:

Import file attachments. Props tellyworth. fixes #5466

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/wp-admin/import/wordpress.php

    r6376 r6390  
    1111    var $allauthornames = array ();
    1212    var $j = -1;
    13     var $another_pass = false;
     13    var $fetch_attachments = false;
     14    var $url_remap = array ();
    1415
    1516    function header() {
     
    190191            echo '</li>';
    191192        }
    192 
     193?> 
     194</ol>   
     195<h2><?php _e('Import Attachments'); ?></h2>
     196<p>
     197    <input type="checkbox" value="1" name="attachments" id="import-attachments" />
     198    <label for="import-attachments"><?php _e('Download and import file attachments') ?></label>
     199</p>
     200
     201<?php
    193202        echo '<input type="submit" value="Submit">'.'<br />';
    194203        echo '</form>';
    195         echo '</ol>';
    196204
    197205    }
     
    296304        $post_content = str_replace('<br>', '<br />', $post_content);
    297305        $post_content = str_replace('<hr>', '<hr />', $post_content);
    298 
     306       
    299307        preg_match_all('|<category domain="tag">(.*?)</category>|is', $post, $tags);
    300308        $tags = $tags[1];
     
    334342
    335343            echo '<li>';
    336             printf(__('Importing post <i>%s</i>...'), stripslashes($post_title));
    337344
    338345            $post_author = $this->checkauthor($post_author); //just so that if a post already exists, new users are not created by checkauthor
    339346
    340347            $postdata = compact('post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_title', 'post_excerpt', 'post_status', 'post_name', 'comment_status', 'ping_status', 'post_modified', 'post_modified_gmt', 'guid', 'post_parent', 'menu_order', 'post_type');
    341             $comment_post_ID = $post_id = wp_insert_post($postdata);
     348            if ($post_type == 'attachment') {
     349                $remote_url = $this->get_tag( $post, 'wp:attachment_url' );
     350                if ( !$remote_url )
     351                    $remote_url = $guid;
     352                   
     353                $comment_post_ID = $post_id = $this->process_attachment($postdata, $remote_url);
     354                if ( !$post_id or is_wp_error($post_id) )
     355                    return $post_id;
     356            }
     357            else {
     358                printf(__('Importing post <i>%s</i>...'), stripslashes($post_title));
     359                $comment_post_ID = $post_id = wp_insert_post($postdata);
     360            }
     361           
    342362            if ( is_wp_error( $post_id ) )
    343363                return $post_id;
     
    421441            add_post_meta( $post_id, $key, $value );
    422442        } }
     443       
     444        print "</li>\n";
     445    }
     446   
     447    function process_attachment($postdata, $remote_url) {
     448        if ($this->fetch_attachments and $remote_url) {
     449            printf( __('Importing attachment <i>%s</i>... '), htmlspecialchars($remote_url) );
     450            $upload = $this->fetch_remote_file($postdata, $remote_url);
     451            if ( is_wp_error($upload) ) {
     452                printf( __('Remote file error: %s'), htmlspecialchars($upload->get_error_message()) );
     453                return $upload;
     454            }
     455            else {
     456                print '('.size_format(filesize($upload['file'])).')';
     457            }
     458               
     459            $postdata['guid'] = $upload['url'];
     460
     461            // as per wp-admin/includes/upload.php
     462            $post_id = wp_insert_attachment($postdata, $upload['file']);
     463            wp_update_attachment_metadata( $post_id, wp_generate_attachment_metadata( $post_id, $upload['file'] ) );
     464            return $post_id;
     465        }
     466        else {
     467            printf( __('Skipping attachment <i>%s</i>'), htmlspecialchars($remote_url) );
     468        }
     469    }
     470   
     471    function fetch_remote_file($post, $url) {
     472        $upload = wp_upload_dir($post['post_date']);
     473       
     474        // extract the file name and extension from the url
     475        $file_name = basename($url);
     476
     477        // get placeholder file in the upload dir with a unique sanitized filename
     478        $upload = wp_upload_bits( $file_name, 0, '', $post['post_date']);
     479        if ( $upload['error'] ) {
     480            echo $upload['error'];
     481            return new WP_Error( 'upload_dir_error', $upload['error'] );
     482        }
     483       
     484        // fetch the remote url and write it to the placeholder file
     485        $headers = wp_get_http($url, $upload['file']);
     486       
     487        // make sure the fetch was successful
     488        if ( $headers['response'] != '200' )
     489            return new WP_Error( 'import_file_error', __(sprintf('Remote file returned error response %d', intval($headers['response']))) );
     490        elseif ( isset($headers['content-length']) && filesize($upload['file']) != $headers['content-length'] )
     491            return new WP_Error( 'import_file_error', __('Remote file is incorrect size') );
     492           
     493        // keep track of the old and new urls so we can substitute them later
     494        $this->url_remap[$url] = $upload['url'];
     495        // if the remote url is redirected somewhere else, keep track of the destination too
     496        if ( $headers['x-final-location'] != $url )
     497            $this->url_remap[$headers['x-final-location']] = $upload['url'];
     498       
     499        return $upload;
     500       
     501    }
     502   
     503    // update url references in post bodies to point to the new local files
     504    function backfill_attachment_urls() {
     505       
     506        // make sure we do the longest urls first, in case one is a substring of another
     507        function cmpr_strlen($a, $b) {
     508            return strlen($b) - strlen($a);
     509        }
     510        uksort($this->url_remap, 'cmpr_strlen');
     511               
     512        global $wpdb;
     513        foreach ($this->url_remap as $from_url => $to_url) {
     514            $wpdb->query( $wpdb->prepare("UPDATE {$wpdb->posts} SET post_content = REPLACE(post_content, '%s', '%s')", $from_url, $to_url) );
     515        }
    423516    }
    424517   
     
    436529    }
    437530
    438     function import($id) {
     531    function import($id, $fetch_attachments = false) {
    439532        $this->id = (int) $id;
     533        $this->fetch_attachments = (bool) $fetch_attachments;
    440534
    441535        $file = get_attached_file($this->id);
     
    453547        $result = $this->process_posts();
    454548        $this->backfill_parents();
     549        $this->backfill_attachment_urls();
    455550        wp_defer_term_counting(false);
    456551        if ( is_wp_error( $result ) )
     
    488583            case 2:
    489584                check_admin_referer('import-wordpress');
    490                 $result = $this->import( $_GET['id'] );
     585                $result = $this->import( $_GET['id'], $_POST['attachments'] );
    491586                if ( is_wp_error( $result ) )
    492587                    echo $result->get_error_message();
Note: See TracChangeset for help on using the changeset viewer.