wordpress-importer.php 44 KB

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