WordPress.org

Make WordPress Core

source: trunk/wp-admin/import/wordpress.php @ 6870

Last change on this file since 6870 was 6870, checked in by westi, 13 years ago

Add translations. Fixes #5877 props hervada.

  • Property svn:eol-style set to native
File size: 23.1 KB
Line 
1<?php
2
3class WP_Import {
4
5        var $post_ids_processed = array ();
6        var $orphans = array ();
7        var $file;
8        var $id;
9        var $mtnames = array ();
10        var $newauthornames = array ();
11        var $allauthornames = array ();
12
13        var $author_ids = array ();
14        var $tags = array ();
15
16        var $j = -1;
17        var $fetch_attachments = false;
18        var $url_remap = array ();
19
20        function header() {
21                echo '<div class="wrap">';
22                echo '<h2>'.__('Import WordPress').'</h2>';
23        }
24
25        function footer() {
26                echo '</div>';
27        }
28
29        function unhtmlentities($string) { // From php.net for < 4.3 compat
30                $trans_tbl = get_html_translation_table(HTML_ENTITIES);
31                $trans_tbl = array_flip($trans_tbl);
32                return strtr($string, $trans_tbl);
33        }
34
35        function greet() {
36                echo '<div class="narrow">';
37                echo '<p>'.__('Howdy! Upload your WordPress eXtended RSS (WXR) file and we&#8217;ll import the posts, comments, custom fields, and categories into this blog.').'</p>';
38                echo '<p>'.__('Choose a WordPress WXR file to upload, then click Upload file and import.').'</p>';
39                wp_import_upload_form("admin.php?import=wordpress&amp;step=1");
40                echo '</div>';
41        }
42
43        function get_tag( $string, $tag ) {
44                global $wpdb;
45                preg_match("|<$tag.*?>(.*?)</$tag>|is", $string, $return);
46                $return = preg_replace('|^<!\[CDATA\[(.*)\]\]>$|s', '$1', $return[1]);
47                $return = $wpdb->escape( trim( $return ) );
48                return $return;
49        }
50
51        function has_gzip() {
52                return is_callable('gzopen');
53        }
54
55        function fopen($filename, $mode='r') {
56                if ( $this->has_gzip() )
57                        return gzopen($filename, $mode);
58                return fopen($filename, $mode);
59        }
60
61        function feof($fp) {
62                if ( $this->has_gzip() )
63                        return gzeof($fp);
64                return feof($fp);
65        }
66
67        function fgets($fp, $len=8192) {
68                if ( $this->has_gzip() )
69                        return gzgets($fp, $len);
70                return fgets($fp, $len);
71        }
72
73        function fclose($fp) {
74                if ( $this->has_gzip() )
75                        return gzclose($fp);
76                return fclose($fp);
77        }
78
79        function get_entries($process_post_func=NULL) {
80                set_magic_quotes_runtime(0);
81
82                $doing_entry = false;
83                $is_wxr_file = false;
84
85                $fp = $this->fopen($this->file, 'r');
86                if ($fp) {
87                        while ( !$this->feof($fp) ) {
88                                $importline = rtrim($this->fgets($fp));
89
90                                // this doesn't check that the file is perfectly valid but will at least confirm that it's not the wrong format altogether
91                                if ( !$is_wxr_file && preg_match('|xmlns:wp="http://wordpress[.]org/export/\d+[.]\d+/"|', $importline) )
92                                        $is_wxr_file = true;
93
94                                if ( false !== strpos($importline, '<wp:category>') ) {
95                                        preg_match('|<wp:category>(.*?)</wp:category>|is', $importline, $category);
96                                        $this->categories[] = $category[1];
97                                        continue;
98                                }
99                                if ( false !== strpos($importline, '<wp:tag>') ) {
100                                        preg_match('|<wp:tag>(.*?)</wp:tag>|is', $importline, $tag);
101                                        $this->tags[] = $tag[1];
102                                        continue;
103                                }
104                                if ( false !== strpos($importline, '<item>') ) {
105                                        $this->post = '';
106                                        $doing_entry = true;
107                                        continue;
108                                }
109                                if ( false !== strpos($importline, '</item>') ) {
110                                        $doing_entry = false;
111                                        if ($process_post_func)
112                                                call_user_func($process_post_func, $this->post);
113                                        continue;
114                                }
115                                if ( $doing_entry ) {
116                                        $this->post .= $importline . "\n";
117                                }
118                        }
119
120                        $this->fclose($fp);
121                }
122
123                return $is_wxr_file;
124
125        }
126
127        function get_wp_authors() {
128                // We need to find unique values of author names, while preserving the order, so this function emulates the unique_value(); php function, without the sorting.
129                $temp = $this->allauthornames;
130                $authors[0] = array_shift($temp);
131                $y = count($temp) + 1;
132                for ($x = 1; $x < $y; $x ++) {
133                        $next = array_shift($temp);
134                        if (!(in_array($next, $authors)))
135                                array_push($authors, "$next");
136                }
137
138                return $authors;
139        }
140
141        function get_authors_from_post() {
142                global $current_user;
143
144                // this will populate $this->author_ids with a list of author_names => user_ids
145
146                foreach ( $_POST['author_in'] as $i => $in_author_name ) {
147
148                        if ( !empty($_POST['user_select'][$i]) ) {
149                                // an existing user was selected in the dropdown list
150                                $user = get_userdata( intval($_POST['user_select'][$i]) );
151                                if ( isset($user->ID) )
152                                        $this->author_ids[$in_author_name] = $user->ID;
153                        }
154                        elseif ( $this->allow_create_users() ) {
155                                // nothing was selected in the dropdown list, so we'll use the name in the text field
156
157                                $new_author_name = trim($_POST['user_create'][$i]);
158                                // if the user didn't enter a name, assume they want to use the same name as in the import file
159                                if ( empty($new_author_name) )
160                                        $new_author_name = $in_author_name;
161
162                                $user_id = username_exists($new_author_name);
163                                if ( !$user_id ) {
164                                        $user_id = wp_create_user($new_author_name, 'changeme');
165                                }
166
167                                $this->author_ids[$in_author_name] = $user_id;
168                        }
169
170                        // failsafe: if the user_id was invalid, default to the current user
171                        if ( empty($this->author_ids[$in_author_name]) ) {
172                                $this->author_ids[$in_author_name] = intval($current_user->ID);
173                        }
174                }
175
176        }
177
178        function wp_authors_form() {
179?>
180<h2><?php _e('Assign Authors'); ?></h2>
181<p><?php _e('To make it easier for you to edit and save the imported posts and drafts, you may want to change the name of the author of the posts. For example, you may want to import all the entries as <code>admin</code>s entries.'); ?></p>
182<?php
183        if ( $this->allow_create_users() ) {
184                echo '<p>'.__('If a new user is created by WordPress, the password will be set, by default, to "changeme". Quite suggestive, eh? ;)')."</p>\n";
185        }
186
187
188                $authors = $this->get_wp_authors();
189                echo '<ol id="authors">';
190                echo '<form action="?import=wordpress&amp;step=2&amp;id=' . $this->id . '" method="post">';
191                wp_nonce_field('import-wordpress');
192                $j = -1;
193                foreach ($authors as $author) {
194                        ++ $j;
195                        echo '<li>'.__('Import author:').' <strong>'.$author.'</strong><br />';
196                        $this->users_form($j, $author);
197                        echo '</li>';
198                }
199
200                if ( $this->allow_fetch_attachments() ) {
201?>
202</ol>
203<h2><?php _e('Import Attachments'); ?></h2>
204<p>
205        <input type="checkbox" value="1" name="attachments" id="import-attachments" />
206        <label for="import-attachments"><?php _e('Download and import file attachments') ?></label>
207</p>
208
209<?php
210                }
211
212                echo '<input type="submit" value="'.attribute_escape( __('Submit') ).'">'.'<br />';
213                echo '</form>';
214
215        }
216
217        function users_form($n, $author) {
218
219                if ( $this->allow_create_users() ) {
220                        printf(__('Create user %1$s or map to existing'), ' <input type="text" value="'.$author.'" name="'.'user_create['.intval($n).']'.'" maxlength="30"> <br />');
221                }
222                else {
223                        echo __('Map to existing').'<br />';
224                }
225
226                // keep track of $n => $author name
227                echo '<input type="hidden" name="author_in['.intval($n).']" value="'.htmlspecialchars($author).'" />';
228
229                $users = get_users_of_blog();
230?><select name="user_select[<?php echo $n; ?>]">
231        <option value="0"><?php _e('- Select -'); ?></option>
232        <?php
233                foreach ($users as $user) {
234                        echo '<option value="'.$user->user_id.'">'.$user->user_login.'</option>';
235                }
236?>
237        </select>
238        <?php
239        }
240
241        function select_authors() {
242                $is_wxr_file = $this->get_entries(array(&$this, 'process_author'));
243                if ( $is_wxr_file ) {
244                        $this->wp_authors_form();
245                }
246                else {
247                        echo '<h2>'.__('Invalid file').'</h2>';
248                        echo '<p>'.__('Please upload a valid WXR (WordPress eXtended RSS) export file.').'</p>';
249                }
250        }
251
252        // fetch the user ID for a given author name, respecting the mapping preferences
253        function checkauthor($author) {
254                global $current_user;
255
256                if ( !empty($this->author_ids[$author]) )
257                        return $this->author_ids[$author];
258
259                // failsafe: map to the current user
260                return $current_user->ID;
261        }
262
263
264
265        function process_categories() {
266                global $wpdb;
267
268                $cat_names = (array) get_terms('category', 'fields=names');
269
270                while ( $c = array_shift($this->categories) ) {
271                        $cat_name = trim($this->get_tag( $c, 'wp:cat_name' ));
272
273                        // If the category exists we leave it alone
274                        if ( in_array($cat_name, $cat_names) )
275                                continue;
276
277                        $category_nicename      = $this->get_tag( $c, 'wp:category_nicename' );
278                        $posts_private          = (int) $this->get_tag( $c, 'wp:posts_private' );
279                        $links_private          = (int) $this->get_tag( $c, 'wp:links_private' );
280
281                        $parent = $this->get_tag( $c, 'wp:category_parent' );
282
283                        if ( empty($parent) )
284                                $category_parent = '0';
285                        else
286                                $category_parent = category_exists($parent);
287
288                        $catarr = compact('category_nicename', 'category_parent', 'posts_private', 'links_private', 'posts_private', 'cat_name');
289
290                        $cat_ID = wp_insert_category($catarr);
291                }
292        }
293
294        function process_tags() {
295                global $wpdb;
296
297                $tag_names = (array) get_terms('post_tag', 'fields=names');
298
299                while ( $c = array_shift($this->tags) ) {
300                        $tag_name = trim($this->get_tag( $c, 'wp:tag_name' ));
301
302                        // If the category exists we leave it alone
303                        if ( in_array($tag_name, $tag_names) )
304                                continue;
305
306                        $slug = $this->get_tag( $c, 'wp:tag_slug' );
307                        $description = $this->get_tag( $c, 'wp:tag_description' );
308
309                        $tagarr = compact('slug', 'description');
310
311                        $tag_ID = wp_insert_term($tag_name, 'post_tag', $tagarr);
312                }
313        }
314
315        function process_author($post) {
316                $author = $this->get_tag( $post, 'dc:creator' );
317                if ($author)
318                        $this->allauthornames[] = $author;
319        }
320
321        function process_posts() {
322                $i = -1;
323                echo '<ol>';
324
325                $this->get_entries(array(&$this, 'process_post'));
326
327                echo '</ol>';
328
329                wp_import_cleanup($this->id);
330                do_action('import_done', 'wordpress');
331
332                echo '<h3>'.sprintf(__('All done.').' <a href="%s">'.__('Have fun!').'</a>', get_option('home')).'</h3>';
333        }
334
335        function process_post($post) {
336                global $wpdb;
337
338                $post_ID = (int) $this->get_tag( $post, 'wp:post_id' );
339                if ( $post_ID && !empty($this->post_ids_processed[$post_ID]) ) // Processed already
340                        return 0;
341
342                // There are only ever one of these
343                $post_title     = $this->get_tag( $post, 'title' );
344                $post_date      = $this->get_tag( $post, 'wp:post_date' );
345                $post_date_gmt  = $this->get_tag( $post, 'wp:post_date_gmt' );
346                $comment_status = $this->get_tag( $post, 'wp:comment_status' );
347                $ping_status    = $this->get_tag( $post, 'wp:ping_status' );
348                $post_status    = $this->get_tag( $post, 'wp:status' );
349                $post_name      = $this->get_tag( $post, 'wp:post_name' );
350                $post_parent    = $this->get_tag( $post, 'wp:post_parent' );
351                $menu_order     = $this->get_tag( $post, 'wp:menu_order' );
352                $post_type      = $this->get_tag( $post, 'wp:post_type' );
353                $post_password  = $this->get_tag( $post, 'wp:post_password' );
354                $guid           = $this->get_tag( $post, 'guid' );
355                $post_author    = $this->get_tag( $post, 'dc:creator' );
356
357                $post_content = $this->get_tag( $post, 'content:encoded' );
358                $post_content = preg_replace('|<(/?[A-Z]+)|e', "'<' . strtolower('$1')", $post_content);
359                $post_content = str_replace('<br>', '<br />', $post_content);
360                $post_content = str_replace('<hr>', '<hr />', $post_content);
361
362                preg_match_all('|<category domain="tag">(.*?)</category>|is', $post, $tags);
363                $tags = $tags[1];
364
365                $tag_index = 0;
366                foreach ($tags as $tag) {
367                        $tags[$tag_index] = $wpdb->escape($this->unhtmlentities(str_replace(array ('<![CDATA[', ']]>'), '', $tag)));
368                        $tag_index++;
369                }
370
371                preg_match_all('|<category>(.*?)</category>|is', $post, $categories);
372                $categories = $categories[1];
373
374                $cat_index = 0;
375                foreach ($categories as $category) {
376                        $categories[$cat_index] = $wpdb->escape($this->unhtmlentities(str_replace(array ('<![CDATA[', ']]>'), '', $category)));
377                        $cat_index++;
378                }
379
380                $post_exists = post_exists($post_title, '', $post_date);
381
382                if ( $post_exists ) {
383                        echo '<li>';
384                        printf(__('Post <i>%s</i> already exists.'), stripslashes($post_title));
385                } else {
386
387                        // If it has parent, process parent first.
388                        $post_parent = (int) $post_parent;
389                        if ($post_parent) {
390                                // if we already know the parent, map it to the local ID
391                                if ( $parent = $this->post_ids_processed[$post_parent] ) {
392                                        $post_parent = $parent;  // new ID of the parent
393                                }
394                                else {
395                                        // record the parent for later
396                                        $this->orphans[intval($post_ID)] = $post_parent;
397                                }
398                        }
399
400                        echo '<li>';
401
402                        $post_author = $this->checkauthor($post_author); //just so that if a post already exists, new users are not created by checkauthor
403
404                        $postdata = compact('post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_title', 'post_status', 'post_name', 'comment_status', 'ping_status', 'guid', 'post_parent', 'menu_order', 'post_type', 'post_password');
405                        if ($post_type == 'attachment') {
406                                $remote_url = $this->get_tag( $post, 'wp:attachment_url' );
407                                if ( !$remote_url )
408                                        $remote_url = $guid;
409
410                                $comment_post_ID = $post_id = $this->process_attachment($postdata, $remote_url);
411                                if ( !$post_id or is_wp_error($post_id) )
412                                        return $post_id;
413                        }
414                        else {
415                                printf(__('Importing post <i>%s</i>...'), stripslashes($post_title));
416                                $comment_post_ID = $post_id = wp_insert_post($postdata);
417                        }
418
419                        if ( is_wp_error( $post_id ) )
420                                return $post_id;
421
422                        // Memorize old and new ID.
423                        if ( $post_id && $post_ID ) {
424                                $this->post_ids_processed[intval($post_ID)] = intval($post_id);
425                        }
426
427                        // Add categories.
428                        if (count($categories) > 0) {
429                                $post_cats = array();
430                                foreach ($categories as $category) {
431                                        $slug = sanitize_term_field('slug', $category, 0, 'category', 'db');
432                                        $cat = get_term_by('slug', $slug, 'category');
433                                        $cat_ID = 0;
434                                        if ( ! empty($cat) )
435                                                $cat_ID = $cat->term_id;
436                                        if ($cat_ID == 0) {
437                                                $category = $wpdb->escape($category);
438                                                $cat_ID = wp_insert_category(array('cat_name' => $category));
439                                        }
440                                        $post_cats[] = $cat_ID;
441                                }
442                                wp_set_post_categories($post_id, $post_cats);
443                        }
444
445                        // Add tags.
446                        if (count($tags) > 0) {
447                                $post_tags = array();
448                                foreach ($tags as $tag) {
449                                        $slug = sanitize_term_field('slug', $tag, 0, 'post_tag', 'db');
450                                        $tag_obj = get_term_by('slug', $slug, 'post_tag');
451                                        $tag_id = 0;
452                                        if ( ! empty($tag_obj) )
453                                                $tag_id = $tag_obj->term_id;
454                                        if ( $tag_id == 0 ) {
455                                                $tag = $wpdb->escape($tag);
456                                                $tag_id = wp_insert_term($tag, 'post_tag');
457                                                $tag_id = $tag_id['term_id'];
458                                        }
459                                        $post_tags[] = intval($tag_id);
460                                }
461                                wp_set_post_tags($post_id, $post_tags);
462                        }
463                }
464
465                // Now for comments
466                preg_match_all('|<wp:comment>(.*?)</wp:comment>|is', $post, $comments);
467                $comments = $comments[1];
468                $num_comments = 0;
469                if ( $comments) { foreach ($comments as $comment) {
470                        $comment_author       = $this->get_tag( $comment, 'wp:comment_author');
471                        $comment_author_email = $this->get_tag( $comment, 'wp:comment_author_email');
472                        $comment_author_IP    = $this->get_tag( $comment, 'wp:comment_author_IP');
473                        $comment_author_url   = $this->get_tag( $comment, 'wp:comment_author_url');
474                        $comment_date         = $this->get_tag( $comment, 'wp:comment_date');
475                        $comment_date_gmt     = $this->get_tag( $comment, 'wp:comment_date_gmt');
476                        $comment_content      = $this->get_tag( $comment, 'wp:comment_content');
477                        $comment_approved     = $this->get_tag( $comment, 'wp:comment_approved');
478                        $comment_type         = $this->get_tag( $comment, 'wp:comment_type');
479                        $comment_parent       = $this->get_tag( $comment, 'wp:comment_parent');
480
481                        // if this is a new post we can skip the comment_exists() check
482                        if ( !$post_exists || !comment_exists($comment_author, $comment_date) ) {
483                                $commentdata = compact('comment_post_ID', 'comment_author', 'comment_author_url', 'comment_author_email', 'comment_author_IP', 'comment_date', 'comment_date_gmt', 'comment_content', 'comment_approved', 'comment_type', 'comment_parent');
484                                wp_insert_comment($commentdata);
485                                $num_comments++;
486                        }
487                } }
488
489                if ( $num_comments )
490                        printf(' '.__ngettext('(%s comment)', '(%s comments)', $num_comments), $num_comments);
491
492                // Now for post meta
493                preg_match_all('|<wp:postmeta>(.*?)</wp:postmeta>|is', $post, $postmeta);
494                $postmeta = $postmeta[1];
495                if ( $postmeta) { foreach ($postmeta as $p) {
496                        $key   = $this->get_tag( $p, 'wp:meta_key' );
497                        $value = $this->get_tag( $p, 'wp:meta_value' );
498                        $value = stripslashes($value); // add_post_meta() will escape.
499
500                        $this->process_post_meta($post_id, $key, $value);
501
502                } }
503
504                do_action('import_post_added', $post_id);
505                print "</li>\n";
506        }
507
508        function process_post_meta($post_id, $key, $value) {
509                // the filter can return false to skip a particular metadata key
510                $_key = apply_filters('import_post_meta_key', $key);
511                if ( $_key ) {
512                        add_post_meta( $post_id, $_key, $value );
513                        do_action('import_post_meta', $post_id, $_key, $value);
514                }
515        }
516
517        function process_attachment($postdata, $remote_url) {
518                if ($this->fetch_attachments and $remote_url) {
519                        printf( __('Importing attachment <i>%s</i>... '), htmlspecialchars($remote_url) );
520                        $upload = $this->fetch_remote_file($postdata, $remote_url);
521                        if ( is_wp_error($upload) ) {
522                                printf( __('Remote file error: %s'), htmlspecialchars($upload->get_error_message()) );
523                                return $upload;
524                        }
525                        else {
526                                print '('.size_format(filesize($upload['file'])).')';
527                        }
528
529                        if ( $info = wp_check_filetype($upload['file']) ) {
530                                $postdata['post_mime_type'] = $info['type'];
531                        }
532                        else {
533                                print __('Invalid file type');
534                                return;
535                        }
536
537                        $postdata['guid'] = $upload['url'];
538
539                        // as per wp-admin/includes/upload.php
540                        $post_id = wp_insert_attachment($postdata, $upload['file']);
541                        wp_update_attachment_metadata( $post_id, wp_generate_attachment_metadata( $post_id, $upload['file'] ) );
542
543                        // remap the thumbnail url.  this isn't perfect because we're just guessing the original url.
544                        if ( preg_match('@^image/@', $info['type']) && $thumb_url = wp_get_attachment_thumb_url($post_id) ) {
545                                $parts = pathinfo($remote_url);
546                                $ext = $parts['extension'];
547                                $name = basename($parts['basename'], ".{$ext}");
548                                $this->url_remap[$parts['dirname'] . '/' . $name . '.thumbnail.' . $ext] = $thumb_url;
549                        }
550
551                        return $post_id;
552                }
553                else {
554                        printf( __('Skipping attachment <i>%s</i>'), htmlspecialchars($remote_url) );
555                }
556        }
557
558        function fetch_remote_file($post, $url) {
559                $upload = wp_upload_dir($post['post_date']);
560
561                // extract the file name and extension from the url
562                $file_name = basename($url);
563
564                // get placeholder file in the upload dir with a unique sanitized filename
565                $upload = wp_upload_bits( $file_name, 0, '', $post['post_date']);
566                if ( $upload['error'] ) {
567                        echo $upload['error'];
568                        return new WP_Error( 'upload_dir_error', $upload['error'] );
569                }
570
571                // fetch the remote url and write it to the placeholder file
572                $headers = wp_get_http($url, $upload['file']);
573
574                // make sure the fetch was successful
575                if ( $headers['response'] != '200' ) {
576                        @unlink($upload['file']);
577                        return new WP_Error( 'import_file_error', sprintf(__('Remote file returned error response %d'), intval($headers['response'])) );
578                }
579                elseif ( isset($headers['content-length']) && filesize($upload['file']) != $headers['content-length'] ) {
580                        @unlink($upload['file']);
581                        return new WP_Error( 'import_file_error', __('Remote file is incorrect size') );
582                }
583
584                $max_size = $this->max_attachment_size();
585                if ( !empty($max_size) and filesize($upload['file']) > $max_size ) {
586                        @unlink($upload['file']);
587                        return new WP_Error( 'import_file_error', sprintf(__('Remote file is too large, limit is %s', size_format($max_size))) );
588                }
589
590                // keep track of the old and new urls so we can substitute them later
591                $this->url_remap[$url] = $upload['url'];
592                // if the remote url is redirected somewhere else, keep track of the destination too
593                if ( $headers['x-final-location'] != $url )
594                        $this->url_remap[$headers['x-final-location']] = $upload['url'];
595
596                return $upload;
597
598        }
599
600        // sort by strlen, longest string first
601        function cmpr_strlen($a, $b) {
602                return strlen($b) - strlen($a);
603        }
604
605        // update url references in post bodies to point to the new local files
606        function backfill_attachment_urls() {
607
608                // make sure we do the longest urls first, in case one is a substring of another
609                uksort($this->url_remap, array(&$this, 'cmpr_strlen'));
610
611                global $wpdb;
612                foreach ($this->url_remap as $from_url => $to_url) {
613                        // remap urls in post_content
614                        $wpdb->query( $wpdb->prepare("UPDATE {$wpdb->posts} SET post_content = REPLACE(post_content, '%s', '%s')", $from_url, $to_url) );
615                        // remap enclosure urls
616                        $result = $wpdb->query( $wpdb->prepare("UPDATE {$wpdb->postmeta} SET meta_value = REPLACE(meta_value, '%s', '%s') WHERE meta_key='enclosure'", $from_url, $to_url) );
617                }
618        }
619
620        // update the post_parent of orphans now that we know the local id's of all parents
621        function backfill_parents() {
622                global $wpdb;
623
624                foreach ($this->orphans as $child_id => $parent_id) {
625                        $local_child_id = $this->post_ids_processed[$child_id];
626                        $local_parent_id = $this->post_ids_processed[$parent_id];
627                        if ($local_child_id and $local_parent_id) {
628                                $wpdb->query( $wpdb->prepare("UPDATE {$wpdb->posts} SET post_parent = %d WHERE ID = %d", $local_parent_id, $local_child_id));
629                        }
630                }
631        }
632
633        function is_valid_meta_key($key) {
634                // skip _wp_attached_file metadata since we'll regenerate it from scratch
635                if ( $key == '_wp_attached_file' )
636                        return false;
637                return $key;
638        }
639
640        // give the user the option of creating new users to represent authors in the import file?
641        function allow_create_users() {
642                return apply_filters('import_allow_create_users', true);
643        }
644
645        // give the user the option of downloading and importing attached files
646        function allow_fetch_attachments() {
647                return apply_filters('import_allow_fetch_attachments', true);
648        }
649
650        function max_attachment_size() {
651                // can be overridden with a filter - 0 means no limit
652                return apply_filters('import_attachment_size_limit', 0);
653        }
654
655        function import_start() {
656                wp_defer_term_counting(true);
657                wp_defer_comment_counting(true);
658                do_action('import_start');
659        }
660
661        function import_end() {
662                do_action('import_end');
663
664                // clear the caches after backfilling
665                foreach ($this->post_ids_processed as $post_id)
666                        clean_post_cache($post_id);
667
668                wp_defer_term_counting(false);
669                wp_defer_comment_counting(false);
670        }
671
672        function import($id, $fetch_attachments = false) {
673                $this->id = (int) $id;
674                $this->fetch_attachments = ($this->allow_fetch_attachments() && (bool) $fetch_attachments);
675
676                add_filter('import_post_meta_key', array($this, 'is_valid_meta_key'));
677                $file = get_attached_file($this->id);
678                $this->import_file($file);
679        }
680
681        function import_file($file) {
682                $this->file = $file;
683
684                $this->import_start();
685                $this->get_authors_from_post();
686                $this->get_entries();
687                $this->process_categories();
688                $this->process_tags();
689                $result = $this->process_posts();
690                $this->backfill_parents();
691                $this->backfill_attachment_urls();
692                $this->import_end();
693
694                if ( is_wp_error( $result ) )
695                        return $result;
696        }
697
698        function handle_upload() {
699                $file = wp_import_handle_upload();
700                if ( isset($file['error']) ) {
701                        echo '<p>'.__('Sorry, there has been an error.').'</p>';
702                        echo '<p><strong>' . $file['error'] . '</strong></p>';
703                        return false;
704                }
705                $this->file = $file['file'];
706                $this->id = (int) $file['id'];
707                return true;
708        }
709
710        function dispatch() {
711                if (empty ($_GET['step']))
712                        $step = 0;
713                else
714                        $step = (int) $_GET['step'];
715
716                $this->header();
717                switch ($step) {
718                        case 0 :
719                                $this->greet();
720                                break;
721                        case 1 :
722                                check_admin_referer('import-upload');
723                                if ( $this->handle_upload() )
724                                        $this->select_authors();
725                                break;
726                        case 2:
727                                check_admin_referer('import-wordpress');
728                                $result = $this->import( $_GET['id'], $_POST['attachments'] );
729                                if ( is_wp_error( $result ) )
730                                        echo $result->get_error_message();
731                                break;
732                }
733                $this->footer();
734        }
735
736        function WP_Import() {
737                // Nothing.
738        }
739}
740
741$wp_import = new WP_Import();
742
743register_importer('wordpress', 'WordPress', __('Import <strong>posts, comments, custom fields, pages, and categories</strong> from a WordPress export file'), array ($wp_import, 'dispatch'));
744
745?>
Note: See TracBrowser for help on using the repository browser.