/**
* Imports user selected chapters from an instance of PB
*
* @param array $chapters
* Array(
[5] => Array(
[222] => chapter
)
[14] => Array(
[164] => front-matter
)
)
* @return type
*/
function import(array $chapters)
{
$this->chapters = $chapters;
$chapters_to_import = $this->getChapters();
libxml_use_internal_errors(true);
foreach ($chapters_to_import as $new_post) {
// Load HTMl snippet into DOMDocument using UTF-8 hack
$utf8_hack = '<?xml version="1.0" encoding="UTF-8"?>';
$doc = new \DOMDocument();
$doc->loadHTML($utf8_hack . $new_post['post_content']);
// Download images, change image paths
$doc = $this->scrapeAndKneadImages($doc);
$html = $doc->saveXML($doc->documentElement);
// Remove auto-created <html> <body> and <!DOCTYPE> tags.
$html = preg_replace('/^<!DOCTYPE.+?>/', '', str_replace(array('<html>', '</html>', '<body>', '</body>'), array('', '', '', ''), $html));
$import_post = array('post_title' => $new_post['post_title'], 'post_content' => $html, 'post_type' => $new_post['post_type'], 'post_status' => $new_post['post_status']);
// set post parent
if ('chapter' == $new_post['post_type']) {
$post_parent = $this->getChapterParent();
$import_post['post_parent'] = $post_parent;
}
// woot, woot!
$pid = wp_insert_post($import_post);
// check for errors, redirect and record
if (is_wp_error($pid)) {
error_log('\\PBT\\Import\\PBImport()->import error at `wp_insert_post()`: ' . $pid->get_error_message());
\PBT\Search\ApiSearch::revokeCurrentImport();
\Pressbooks\Redirect\location(get_bloginfo('url') . '/wp-admin/admin.php?page=api_search_import');
}
// set post metadata
$this->setPostMeta($pid, $new_post);
\Pressbooks\Book::consolidatePost($pid, get_post($pid));
}
return \PBT\Search\ApiSearch::revokeCurrentImport();
}