function import() { $post_date = $this->published; $post_content = $this->content; $post_title = $this->title; $post_author = $this->author; $post_status = $this->isDraft ? 'draft' : 'publish'; //AGC:24/10/2013 Turn off the pingbacks $post_pingback = Blogger_Importer::POST_PINGBACK; // N.B. Clean up of $post_content is now part of the sanitize class // Check for duplication part of calling function $post = compact('post_date', 'post_content', 'post_author', 'post_title', 'post_status', 'post_pingback'); $post_id = wp_insert_post($post); if (is_wp_error($post_id)) { return $post_id; } wp_create_categories(array_map('addslashes', $this->categories), $post_id); add_post_meta($post_id, 'blogger_blog', $this->blogurl, true); add_post_meta($post_id, 'blogger_author', $this->bloggerauthor, true); if (!$this->isDraft && isset($this->bookmark)) { add_post_meta($post_id, 'blogger_permalink', $this->bookmark, true); } add_post_meta($post_id, 'blogger_internal', $this->old_permalink, true); if (isset($this->geotags)) { add_post_meta($post_id, 'geo_latitude', $this->geotags['geo_latitude']); add_post_meta($post_id, 'geo_longitude', $this->geotags['geo_longitude']); add_post_meta($post_id, 'geo_public', 1); if (isset($this->geotags['geo_address'])) { add_post_meta($post_id, 'geo_address', $this->geotags['geo_address']); } } return $post_id; }
/** * Insert post * * @param array $post_object The post object. * @return mixed The post id or WP_Error object. * @since 0.1.0 */ public static function insert_post($post) { // unset all empty fields foreach ($post as $key => $value) { if (!is_array($value) && !strlen($value)) { unset($post[$key]); } elseif (is_array($value) && !count($value)) { unset($post[$key]); } } // insert and set category if (isset($post['post_category']) && is_array($post['post_category']) && count($post['post_category'])) { $post['post_category'] = wp_create_categories($post['post_category']); } if (isset($post['post_date']) && $post['post_date']) { $post['post_date'] = date("Y-m-d H:i:s", strtotime($post['post_date'])); } // setup author if (isset($post['post_author']) && !intval($post['post_author'])) { $field = apply_filters('acsv_get_user_by_field', 'login'); $u = get_user_by($field, $post['post_author']); if ($u) { $post['post_author'] = $u->ID; } else { unset($post['post_author']); } } // setup post ID if (isset($post['ID']) && !intval($post['ID'])) { unset($post['ID']); } // set default to the post. foreach (Defaults\Config::get_post_defaults() as $key => $value) { if (!isset($post[$key])) { $post[$key] = $value; } } $helper = new \Megumi\WP\Post\Helper($post); $post_id = $helper->insert(); if (is_wp_error($post_id)) { return $post_id; } else { do_action('acsv_after_insert_post', $post_id, $post, $helper); return $post_id; } }
function save_post(&$post, &$comments, &$pings) { // Reset the counter set_time_limit(30); $post = get_object_vars($post); $post = add_magic_quotes($post); $post = (object) $post; if ($post_id = post_exists($post->post_title, '', $post->post_date)) { echo '<li>'; printf(__('Post <em>%s</em> already exists.'), stripslashes($post->post_title)); } else { echo '<li>'; printf(__('Importing post <em>%s</em>...'), stripslashes($post->post_title)); if ('' != trim($post->extended)) { $post->post_content .= "\n<!--more-->\n{$post->extended}"; } $post->post_author = $this->checkauthor($post->post_author); //just so that if a post already exists, new users are not created by checkauthor $post_id = wp_insert_post($post); if (is_wp_error($post_id)) { return $post_id; } // Add categories. if (0 != count($post->categories)) { wp_create_categories($post->categories, $post_id); } // Add tags or keywords if (1 < strlen($post->post_keywords)) { // Keywords exist. printf(__('<br />Adding tags <i>%s</i>...'), stripslashes($post->post_keywords)); wp_add_post_tags($post_id, $post->post_keywords); } } $num_comments = 0; foreach ($comments as $comment) { $comment = get_object_vars($comment); $comment = add_magic_quotes($comment); if (!comment_exists($comment['comment_author'], $comment['comment_date'])) { $comment['comment_post_ID'] = $post_id; $comment = wp_filter_comment($comment); wp_insert_comment($comment); $num_comments++; } } if ($num_comments) { printf(' ' . __ngettext('(%s comment)', '(%s comments)', $num_comments), $num_comments); } $num_pings = 0; foreach ($pings as $ping) { $ping = get_object_vars($ping); $ping = add_magic_quotes($ping); if (!comment_exists($ping['comment_author'], $ping['comment_date'])) { $ping['comment_content'] = "<strong>{$ping['title']}</strong>\n\n{$ping['comment_content']}"; $ping['comment_post_ID'] = $post_id; $ping = wp_filter_comment($ping); wp_insert_comment($ping); $num_pings++; } } if ($num_pings) { printf(' ' . __ngettext('(%s ping)', '(%s pings)', $num_pings), $num_pings); } echo "</li>"; //ob_flush();flush(); }
function cfgp_do_categories($clone_id, $cur_cats_names) { /* $cur_cats_names should be an array of category names only */ if (!function_exists('wp_create_categories')) { /* INCLUDE ALL ADMIN FUNCTIONS */ require_once ABSPATH . 'wp-admin/includes/admin.php'; } /* This function creates the cats if they don't exist, and * then assigns them to the post ID that's passed. */ $cats_results = wp_create_categories($cur_cats_names, $clone_id); if (is_array($cats_results) && !empty($cats_results)) { return true; } else { return false; } }
function import_posts() { global $wpdb, $current_user; set_magic_quotes_runtime(0); $importdata = file($this->file); // Read the file into an array $importdata = implode('', $importdata); // squish it $importdata = str_replace(array ("\r\n", "\r"), "\n", $importdata); preg_match_all('|(<item[^>]+>(.*?)</item>)|is', $importdata, $posts); $posts = $posts[1]; unset($importdata); echo '<ol>'; foreach ($posts as $post) { flush(); preg_match('|<item type=\"(.*?)\">|is', $post, $post_type); $post_type = $post_type[1]; if($post_type == "photo") { preg_match('|<photoFilename>(.*?)</photoFilename>|is', $post, $post_title); } else { preg_match('|<title>(.*?)</title>|is', $post, $post_title); } $post_title = $wpdb->escape(trim($post_title[1])); preg_match('|<pubDate>(.*?)</pubDate>|is', $post, $post_date); $post_date = strtotime($post_date[1]); $post_date = gmdate('Y-m-d H:i:s', $post_date); preg_match_all('|<category>(.*?)</category>|is', $post, $categories); $categories = $categories[1]; $cat_index = 0; foreach ($categories as $category) { $categories[$cat_index] = $wpdb->escape($this->unhtmlentities($category)); $cat_index++; } if(strcasecmp($post_type, "photo") === 0) { preg_match('|<sizedPhotoUrl>(.*?)</sizedPhotoUrl>|is', $post, $post_content); $post_content = '<img src="'.trim($post_content[1]).'" />'; $post_content = $this->unhtmlentities($post_content); } else { preg_match('|<body>(.*?)</body>|is', $post, $post_content); $post_content = str_replace(array ('<![CDATA[', ']]>'), '', trim($post_content[1])); $post_content = $this->unhtmlentities($post_content); } // Clean up content $post_content = preg_replace('|<(/?[A-Z]+)|e', "'<' . strtolower('$1')", $post_content); $post_content = str_replace('<br>', '<br />', $post_content); $post_content = str_replace('<hr>', '<hr />', $post_content); $post_content = $wpdb->escape($post_content); $post_author = $current_user->ID; preg_match('|<postStatus>(.*?)</postStatus>|is', $post, $post_status); $post_status = trim($post_status[1]); echo '<li>'; if ($post_id = post_exists($post_title, $post_content, $post_date)) { printf(__('Post <em>%s</em> already exists.'), stripslashes($post_title)); } else { printf(__('Importing post <em>%s</em>...'), stripslashes($post_title)); $postdata = compact('post_author', 'post_date', 'post_content', 'post_title', 'post_status'); $post_id = wp_insert_post($postdata); if ( is_wp_error( $post_id ) ) { return $post_id; } if (!$post_id) { _e("Couldn't get post ID"); echo '</li>'; break; } if(0 != count($categories)) wp_create_categories($categories, $post_id); } preg_match_all('|<comment>(.*?)</comment>|is', $post, $comments); $comments = $comments[1]; if ( $comments ) { $comment_post_ID = (int) $post_id; $num_comments = 0; foreach ($comments as $comment) { preg_match('|<body>(.*?)</body>|is', $comment, $comment_content); $comment_content = str_replace(array ('<![CDATA[', ']]>'), '', trim($comment_content[1])); $comment_content = $this->unhtmlentities($comment_content); // Clean up content $comment_content = preg_replace('|<(/?[A-Z]+)|e', "'<' . strtolower('$1')", $comment_content); $comment_content = str_replace('<br>', '<br />', $comment_content); $comment_content = str_replace('<hr>', '<hr />', $comment_content); $comment_content = $wpdb->escape($comment_content); preg_match('|<pubDate>(.*?)</pubDate>|is', $comment, $comment_date); $comment_date = trim($comment_date[1]); $comment_date = date('Y-m-d H:i:s', strtotime($comment_date)); preg_match('|<author>(.*?)</author>|is', $comment, $comment_author); $comment_author = $wpdb->escape(trim($comment_author[1])); $comment_author_email = NULL; $comment_approved = 1; // Check if it's already there if (!comment_exists($comment_author, $comment_date)) { $commentdata = compact('comment_post_ID', 'comment_author', 'comment_author_email', 'comment_date', 'comment_content', 'comment_approved'); $commentdata = wp_filter_comment($commentdata); wp_insert_comment($commentdata); $num_comments++; } } } if ( $num_comments ) { echo ' '; printf( __ngettext('%s comment', '%s comments', $num_comments), $num_comments ); } echo '</li>'; flush(); ob_flush(); } echo '</ol>'; }
function process_posts() { ini_set("auto_detect_line_endings", true); $h = new RS_CSV_Helper(); $handle = $h->fopen($this->file, 'r'); if ($handle == false) { echo '<p><strong>' . __('Failed to open file.', 'really-simple-csv-importer') . '</strong></p>'; wp_import_cleanup($this->id); return false; } $is_first = true; $post_statuses = get_post_stati(); echo '<ol>'; while (($data = $h->fgetcsv($handle)) !== FALSE) { if ($is_first) { $h->parse_columns($this, $data); $is_first = false; } else { echo '<li>'; $post = array(); $is_update = false; $error = new WP_Error(); // (string) (required) post type $post_type = $h->get_data($this, $data, 'post_type'); if ($post_type) { if (post_type_exists($post_type)) { $post['post_type'] = $post_type; } else { $error->add('post_type_exists', sprintf(__('Invalid post type "%s".', 'really-simple-csv-importer'), $post_type)); } } else { echo __('Note: Please include post_type value if that is possible.', 'really-simple-csv-importer') . '<br>'; } // (int) post id $post_id = $h->get_data($this, $data, 'ID'); $post_id = $post_id ? $post_id : $h->get_data($this, $data, 'post_id'); if ($post_id) { $post_exist = get_post($post_id); if (is_null($post_exist)) { // if the post id is not exists $post['import_id'] = $post_id; } else { if (!$post_type || $post_exist->post_type == $post_type) { $post['ID'] = $post_id; $is_update = true; } else { $error->add('post_type_check', sprintf(__('The post type value from your csv file does not match the existing data in your database. post_id: %d, post_type(csv): %s, post_type(db): %s', 'really-simple-csv-importer'), $post_id, $post_type, $post_exist->post_type)); } } } // (string) post slug $post_name = $h->get_data($this, $data, 'post_name'); if ($post_name) { $post['post_name'] = $post_name; } // (login or ID) post_author $post_author = $h->get_data($this, $data, 'post_author'); if ($post_author) { if (is_numeric($post_author)) { $user = get_user_by('id', $post_author); } else { $user = get_user_by('login', $post_author); } if (isset($user) && is_object($user)) { $post['post_author'] = $user->ID; unset($user); } } // (string) publish date $post_date = $h->get_data($this, $data, 'post_date'); if ($post_date) { $post['post_date'] = date("Y-m-d H:i:s", strtotime($post_date)); } $post_date_gmt = $h->get_data($this, $data, 'post_date_gmt'); if ($post_date_gmt) { $post['post_date_gmt'] = date("Y-m-d H:i:s", strtotime($post_date_gmt)); } // (string) post status $post_status = $h->get_data($this, $data, 'post_status'); if ($post_status) { if (in_array($post_status, $post_statuses)) { $post['post_status'] = $post_status; } } // (string) post password $post_password = $h->get_data($this, $data, 'post_password'); if ($post_password) { $post['post_password'] = $post_password; } // (string) post title $post_title = $h->get_data($this, $data, 'post_title'); if ($post_title) { $post['post_title'] = $post_title; } // (string) post content $post_content = $h->get_data($this, $data, 'post_content'); if ($post_content) { $post['post_content'] = $post_content; } // (string) post excerpt $post_excerpt = $h->get_data($this, $data, 'post_excerpt'); if ($post_excerpt) { $post['post_excerpt'] = $post_excerpt; } // (int) post parent $post_parent = $h->get_data($this, $data, 'post_parent'); if ($post_parent) { $post['post_parent'] = $post_parent; } // (int) menu order $menu_order = $h->get_data($this, $data, 'menu_order'); if ($menu_order) { $post['menu_order'] = $menu_order; } // (string) comment status $comment_status = $h->get_data($this, $data, 'comment_status'); if ($comment_status) { $post['comment_status'] = $comment_status; } // (string, comma separated) slug of post categories $post_category = $h->get_data($this, $data, 'post_category'); if ($post_category) { $categories = preg_split("/,+/", $post_category); if ($categories) { $post['post_category'] = wp_create_categories($categories); } } // (string, comma separated) name of post tags $post_tags = $h->get_data($this, $data, 'post_tags'); if ($post_tags) { $post['post_tags'] = $post_tags; } // (string) post thumbnail image uri $post_thumbnail = $h->get_data($this, $data, 'post_thumbnail'); $meta = array(); $tax = array(); // add any other data to post meta foreach ($data as $key => $value) { if ($value !== false && isset($this->column_keys[$key])) { // check if meta is custom taxonomy if (substr($this->column_keys[$key], 0, 4) == 'tax_') { // (string, comma divided) name of custom taxonomies $customtaxes = preg_split("/,+/", $value); $taxname = substr($this->column_keys[$key], 4); $tax[$taxname] = array(); foreach ($customtaxes as $key => $value) { $tax[$taxname][] = $value; } } else { $meta[$this->column_keys[$key]] = $value; } } } /** * Filter post data. * * @param array $post (required) * @param bool $is_update */ $post = apply_filters('really_simple_csv_importer_save_post', $post, $is_update); /** * Filter meta data. * * @param array $meta (required) * @param array $post * @param bool $is_update */ $meta = apply_filters('really_simple_csv_importer_save_meta', $meta, $post, $is_update); /** * Filter taxonomy data. * * @param array $tax (required) * @param array $post * @param bool $is_update */ $tax = apply_filters('really_simple_csv_importer_save_tax', $tax, $post, $is_update); /** * Filter thumbnail URL or path. * * @since 1.3 * * @param string $post_thumbnail (required) * @param array $post * @param bool $is_update */ $post_thumbnail = apply_filters('really_simple_csv_importer_save_thumbnail', $post_thumbnail, $post, $is_update); /** * Option for dry run testing * * @since 0.5.7 * * @param bool false */ $dry_run = apply_filters('really_simple_csv_importer_dry_run', false); if (!$error->get_error_codes() && $dry_run == false) { /** * Get Alternative Importer Class name. * * @since 0.6 * * @param string Class name to override Importer class. Default to null (do not override). */ $class = apply_filters('really_simple_csv_importer_class', null); // save post data if ($class && class_exists($class, false)) { $importer = new $class(); $result = $importer->save_post($post, $meta, $tax, $post_thumbnail, $is_update); } else { $result = $this->save_post($post, $meta, $tax, $post_thumbnail, $is_update); } if ($result->isError()) { $error = $result->getError(); } else { $post_object = $result->getPost(); if (is_object($post_object)) { /** * Fires adter the post imported. * * @since 1.0 * * @param WP_Post $post_object */ do_action('really_simple_csv_importer_post_saved', $post_object); } echo esc_html(sprintf(__('Processing "%s" done.', 'really-simple-csv-importer'), $post_title)); } } // show error messages foreach ($error->get_error_messages() as $message) { echo esc_html($message) . '<br>'; } echo '</li>'; } } echo '</ol>'; $h->fclose($handle); wp_import_cleanup($this->id); echo '<h3>' . __('All Done.', 'really-simple-csv-importer') . '</h3>'; }
function import_posts() { echo '<ol>'; foreach ($this->posts as $post) { echo "<li>" . __('Importing post...', 'rss-importer'); extract($post); if ($post_id = post_exists($post_title, $post_content, $post_date)) { _e('Post already imported', 'rss-importer'); } else { $post_id = wp_insert_post($post); if (is_wp_error($post_id)) { return $post_id; } if (!$post_id) { _e('Couldn’t get post ID', 'rss-importer'); return; } if (0 != count($categories)) { wp_create_categories($categories, $post_id); } _e('Done!', 'rss-importer'); } echo '</li>'; } echo '</ol>'; }
function create_post($data) { $output = "<li>" . __('Importing post...'); $data = array_merge($this->defaults, $data); $status = isset($_POST['lightspeed_publish_state']) ? $_POST['lightspeed_publish_state'] : $this->defaults['lightspeed_publish_state']; $type = isset($_POST['lightspeed_post_type']) && $_POST['lightspeed_post_type'] !== '' ? $_POST['lightspeed_post_type'] : $this->defaults['lightspeed_post_type']; $language = isset($_POST['lightspeed_language']) && $_POST['lightspeed_language'] !== '' ? $_POST['lightspeed_language'] : $this->defaults['lightspeed_language']; $categories = array(); // Lightspeed has a different column for every category if ($data[$language . '_Category_1'] != '') { $categories[] = $this->create_category($data[$language . '_Category_1']); } if ($data[$language . '_Category_2'] != '') { $categories[] = $this->create_category($data[$language . '_Category_2']); } if ($data[$language . '_Category_3'] != '') { $categories[] = $this->create_category($data[$language . '_Category_3']); } $new_post = array('post_name' => wp_strip_all_tags($data[$language . '_Title_Short']), 'post_title' => wp_strip_all_tags($data[$language . '_Title_Long']), 'post_content' => convert_chars($data[$language . '_Description_Short']), 'post_status' => $status, 'post_type' => $type, 'post_category' => $categories); // We don't need to store this in the Custom Meta unset($data['Body (HTML)']); // pages don't have tags or categories if ('page' !== $type) { $new_post['tags_input'] = $data['Tags']; } if ($id = post_exists($new_post['post_title'], $new_post['post_content'])) { $new_post['ID'] = (int) $id; // Update Post $id = wp_update_post($new_post); if (is_wp_error($id)) { return $id; } if (!$id) { $output .= "Couldn't get post ID"; return false; } // Add Custom Fields //foreach($data as $key => $value) { update_post_meta($id, sanitize_user('Shopify '.$key), esc_attr($value)); } $output .= 'Updated !' . ' <a href="' . get_permalink($id) . '" target="blank">View ' . $data['Title'] . '</a>'; } else { // A post does not yet exist. // Create Post $id = wp_insert_post($new_post); // Add Custom Fields foreach ($data as $key => $value) { add_post_meta($id, sanitize_user('Shopify ' . $key), esc_attr($value)); } $output .= 'Done !' . ' <a href="' . get_permalink($id) . '">View ' . $data['Title'] . '</a>'; } // If you want to import categories, here we go! if (isset($_POST['shopify_importer_import_categories']) && $_POST['shopify_importer_import_categories'] == 'yes') { $categories = explode(',', $data['Vendor']); if (0 != count($categories)) { wp_create_categories($categories, $id); } } $output .= '</li>'; return $output; }
} <li>Add categories</li> <ol> <li>$wpdb->insert( $wpdb->terms, array('name' => $cat_name, 'slug' => $cat_slug, 'term_group' => 0) );</li> <li>$wpdb->insert( $wpdb->term_taxonomy, array('term_id' => '1', 'taxonomy' => 'category', 'description' => '', 'parent' => 0, 'count' => 1));</li> <li>A lot easier than this</li> <li>the cats won't show up in nav until posts are in cat</li> <li>Strangely, it seeems that the categories have the same ids across blogs.</li> </ol> <?php $catids = wp_create_categories($blcats); echo '<pre>'; print_r($catids); echo '</pre>'; ?> <li>Change theme in options table</li> <ol> <?php $curth = 'custom daily globe theme'; ?> <li>current_theme: <?php echo $curth; ?> </li> <?php $dgl = 'dailyglobe';
static function createPost($new_post, $post_custom, $post_category, $post_featured_image, $upload_dir, $post_tags) { global $current_user; $wprocket_fields = array('lazyload', 'lazyload_iframes', 'minify_html', 'minify_css', 'minify_js', 'cdn'); $wprocket_activated = false; if (MainWP_Child_WP_Rocket::isActivated()) { if (function_exists('get_rocket_option')) { $wprocket_activated = true; foreach ($wprocket_fields as $field) { if (!isset($post_custom['_rocket_exclude_' . $field])) { // check not exclude only if (!get_rocket_option($field)) { $post_custom['_rocket_exclude_' . $field] = array(true); // set as excluded } } } } } if (!$wprocket_activated) { foreach ($wprocket_fields as $field) { if (isset($post_custom['_rocket_exclude_' . $field])) { unset($post_custom['_rocket_exclude_' . $field]); } } } //Set up a new post (adding addition information) $usr = get_user_by('login', $_POST['user']); //$new_post['post_author'] = $current_user->ID; $is_robot_post = false; if (isset($_POST['isMainWPRobot']) && !empty($_POST['isMainWPRobot'])) { $is_robot_post = true; } $post_author = isset($new_post['post_author']) ? $new_post['post_author'] : $usr->ID; if ($is_robot_post) { if (1 === $post_author) { $new_post['post_author'] = $usr->ID; } else { if (!is_numeric($post_author)) { $user_author = get_user_by('login', $post_author); if ($user_author) { $post_author = $user_author->ID; } else { $random_password = wp_generate_password($length = 12, $include_standard_special_chars = false); $post_author = wp_create_user($post_author, $random_password, $post_author . '@asdf.com'); } } } } else { if (isset($new_post['custom_post_author']) && !empty($new_post['custom_post_author'])) { $_author = get_user_by('login', $new_post['custom_post_author']); if (!empty($_author)) { $new_post['post_author'] = $_author->ID; } else { $new_post['post_author'] = $usr->ID; } unset($new_post['custom_post_author']); } } $post_author = !empty($post_author) ? $post_author : $usr->ID; $new_post['post_author'] = $post_author; $is_ezine_post = !empty($post_custom['_ezine_post_article_source']) ? true : false; $terms = $new_post['_ezin_post_category']; unset($new_post['_ezin_post_category']); $is_post_plus = isset($post_custom['_mainwp_post_plus']) ? true : false; $wp_error = null; if ($is_ezine_post || $is_post_plus) { if (isset($new_post['post_date_gmt']) && !empty($new_post['post_date_gmt'])) { $post_date_timestamp = strtotime($new_post['post_date_gmt']) + get_option('gmt_offset') * 60 * 60; $new_post['post_date'] = date('Y-m-d H:i:s', $post_date_timestamp); $new_post['post_status'] = $post_date_timestamp <= current_time('timestamp') ? 'publish' : 'future'; } else { $new_post['post_status'] = 'publish'; } } $wpr_options = isset($_POST['wpr_options']) ? $_POST['wpr_options'] : array(); //Search for all the images added to the new post //some images have a href tag to click to navigate to the image.. we need to replace this too $foundMatches = preg_match_all('/(<a[^>]+href=\\"(.*?)\\"[^>]*>)?(<img[^>\\/]*src=\\"((.*?)(png|gif|jpg|jpeg))\\")/ix', $new_post['post_content'], $matches, PREG_SET_ORDER); if (($foundMatches > 0 || $is_robot_post && isset($wpr_options['wpr_save_images']) && 'Yes' === $wpr_options['wpr_save_images']) && !$is_ezine_post) { //We found images, now to download them so we can start balbal foreach ($matches as $match) { $hrefLink = $match[2]; $imgUrl = $match[4]; if (!isset($upload_dir['baseurl']) || 0 !== strripos($imgUrl, $upload_dir['baseurl'])) { continue; } if (preg_match('/-\\d{3}x\\d{3}\\.[a-zA-Z0-9]{3,4}$/', $imgUrl, $imgMatches)) { $search = $imgMatches[0]; $replace = '.' . $match[6]; $originalImgUrl = str_replace($search, $replace, $imgUrl); } else { $originalImgUrl = $imgUrl; } try { $downloadfile = MainWP_Helper::uploadImage($originalImgUrl); $localUrl = $downloadfile['url']; $linkToReplaceWith = dirname($localUrl); if ('' !== $hrefLink) { $server = get_option('mainwp_child_server'); $serverHost = parse_url($server, PHP_URL_HOST); if (!empty($serverHost) && strpos($hrefLink, $serverHost) !== false) { $serverHref = 'href="' . $serverHost; $replaceServerHref = 'href="' . parse_url($localUrl, PHP_URL_SCHEME) . '://' . parse_url($localUrl, PHP_URL_HOST); $new_post['post_content'] = str_replace($serverHref, $replaceServerHref, $new_post['post_content']); } else { if (strpos($hrefLink, 'http') !== false) { $lnkToReplace = dirname($hrefLink); if ('http:' !== $lnkToReplace && 'https:' !== $lnkToReplace) { $new_post['post_content'] = str_replace($lnkToReplace, $linkToReplaceWith, $new_post['post_content']); } } } } $lnkToReplace = dirname($imgUrl); if ('http:' !== $lnkToReplace && 'https:' !== $lnkToReplace) { $new_post['post_content'] = str_replace($lnkToReplace, $linkToReplaceWith, $new_post['post_content']); } } catch (Exception $e) { } } } if ($is_post_plus) { $random_publish_date = isset($post_custom['_saved_draft_random_publish_date']) ? $post_custom['_saved_draft_random_publish_date'] : false; $random_publish_date = is_array($random_publish_date) ? current($random_publish_date) : null; if (!empty($random_publish_date)) { $random_date_from = isset($post_custom['_saved_draft_publish_date_from']) ? $post_custom['_saved_draft_publish_date_from'] : 0; $random_date_from = is_array($random_date_from) ? current($random_date_from) : 0; $random_date_to = isset($post_custom['_saved_draft_publish_date_to']) ? $post_custom['_saved_draft_publish_date_to'] : 0; $random_date_to = is_array($random_date_to) ? current($random_date_to) : 0; $now = current_time('timestamp'); if (empty($random_date_from)) { $random_date_from = $now; } if (empty($random_date_to)) { $random_date_to = $now; } if ($random_date_from === $now && $random_date_from === $random_date_to) { $random_date_to = $now + 7 * 24 * 3600; } if ($random_date_from > $random_date_to) { $tmp = $random_date_from; $random_date_from = $random_date_to; $random_date_to = $tmp; } $random_timestamp = rand($random_date_from, $random_date_to); $post_status = $random_timestamp <= current_time('timestamp') ? 'publish' : 'future'; $new_post['post_status'] = $post_status; $new_post['post_date'] = date('Y-m-d H:i:s', $random_timestamp); } } if (isset($post_tags) && '' !== $post_tags) { $new_post['tags_input'] = $post_tags; } //Save the post to the wp remove_filter('content_save_pre', 'wp_filter_post_kses'); // to fix brake scripts or html $post_status = $new_post['post_status']; $new_post['post_status'] = 'auto-draft'; $new_post_id = wp_insert_post($new_post, $wp_error); //Show errors if something went wrong if (is_wp_error($wp_error)) { return $wp_error->get_error_message(); } if (empty($new_post_id)) { return 'Undefined error'; } wp_update_post(array('ID' => $new_post_id, 'post_status' => $post_status)); if (!empty($terms)) { wp_set_object_terms($new_post_id, array_map(intval, $terms), 'category'); } $permalink = get_permalink($new_post_id); $seo_ext_activated = false; if (class_exists('WPSEO_Meta') && class_exists('WPSEO_Admin')) { $seo_ext_activated = true; } //Set custom fields $not_allowed = array('_slug', '_tags', '_edit_lock', '_selected_sites', '_selected_groups', '_selected_by', '_categories', '_edit_last', '_sticky'); $not_allowed[] = '_mainwp_boilerplate_sites_posts'; $not_allowed[] = '_ezine_post_keyword'; $not_allowed[] = '_ezine_post_display_sig'; $not_allowed[] = '_ezine_post_remove_link'; $not_allowed[] = '_ezine_post_grab_image'; $not_allowed[] = '_ezine_post_grab_image_placement'; $not_allowed[] = '_ezine_post_template_id'; $not_allowed[] = '_mainwp_post_plus'; $not_allowed[] = '_saved_as_draft'; $not_allowed[] = '_saved_draft_categories'; $not_allowed[] = '_saved_draft_tags'; $not_allowed[] = '_saved_draft_random_privelege'; $not_allowed[] = '_saved_draft_random_category'; $not_allowed[] = '_saved_draft_random_publish_date'; $not_allowed[] = '_saved_draft_publish_date_from'; $not_allowed[] = '_saved_draft_publish_date_to'; $not_allowed[] = '_post_to_only_existing_categories'; $not_allowed[] = '_mainwp_robot_post_comments'; $post_to_only_existing_categories = false; foreach ($post_custom as $meta_key => $meta_values) { if (!in_array($meta_key, $not_allowed)) { foreach ($meta_values as $meta_value) { if (strpos($meta_key, "_mainwp_spinner_") === 0) { continue; } // not save if (!$seo_ext_activated) { // if Wordpress SEO plugin is not activated do not save yoast post meta if (strpos($meta_key, '_yoast_wpseo_') === false) { add_post_meta($new_post_id, $meta_key, $meta_value); } } else { add_post_meta($new_post_id, $meta_key, $meta_value); } } } else { if ('_sticky' === $meta_key) { foreach ($meta_values as $meta_value) { if ('sticky' === base64_decode($meta_value)) { stick_post($new_post_id); } } } else { if ('_post_to_only_existing_categories' === $meta_key) { if (isset($meta_values[0]) && $meta_values[0]) { $post_to_only_existing_categories = true; } } } } } // yoast seo extension if ($seo_ext_activated) { $_seo_opengraph_image = isset($post_custom[WPSEO_Meta::$meta_prefix . 'opengraph-image']) ? $post_custom[WPSEO_Meta::$meta_prefix . 'opengraph-image'] : array(); $_seo_opengraph_image = current($_seo_opengraph_image); $_server_domain = ''; $_server = get_option('mainwp_child_server'); if (preg_match('/(https?:\\/\\/[^\\/]+\\/).+/', $_server, $matchs)) { $_server_domain = isset($matchs[1]) ? $matchs[1] : ''; } // upload image if it on the server if (!empty($_seo_opengraph_image) && strpos($_seo_opengraph_image, $_server_domain) !== false) { try { $upload = MainWP_Helper::uploadImage($_seo_opengraph_image); //Upload image to WP if (null !== $upload) { update_post_meta($new_post_id, WPSEO_Meta::$meta_prefix . 'opengraph-image', $upload['url']); //Add the image to the post! } } catch (Exception $e) { } } } //If categories exist, create them (second parameter of wp_create_categories adds the categories to the post) include_once ABSPATH . 'wp-admin/includes/taxonomy.php'; //Contains wp_create_categories if (isset($post_category) && '' !== $post_category) { $categories = explode(',', $post_category); if (count($categories) > 0) { if (!$post_to_only_existing_categories) { $post_category = wp_create_categories($categories, $new_post_id); } else { $cat_ids = array(); foreach ($categories as $cat) { if ($id = category_exists($cat)) { $cat_ids[] = $id; } } if (count($cat_ids) > 0) { wp_set_post_categories($new_post_id, $cat_ids); } } } } //If featured image exists - set it if (null !== $post_featured_image) { try { $upload = MainWP_Helper::uploadImage($post_featured_image); //Upload image to WP if (null !== $upload) { update_post_meta($new_post_id, '_thumbnail_id', $upload['id']); //Add the thumbnail to the post! } } catch (Exception $e) { } } // post plus extension process if ($is_post_plus) { $random_privelege = isset($post_custom['_saved_draft_random_privelege']) ? $post_custom['_saved_draft_random_privelege'] : null; $random_privelege = is_array($random_privelege) ? current($random_privelege) : null; $random_privelege_base = base64_decode($random_privelege); $random_privelege = maybe_unserialize($random_privelege_base); if (is_array($random_privelege) && count($random_privelege) > 0) { $random_post_authors = array(); foreach ($random_privelege as $role) { $users = get_users(array('role' => $role)); foreach ($users as $user) { $random_post_authors[] = $user->ID; } } if (count($random_post_authors) > 0) { shuffle($random_post_authors); $key = array_rand($random_post_authors); wp_update_post(array('ID' => $new_post_id, 'post_author' => $random_post_authors[$key])); } } $random_category = isset($post_custom['_saved_draft_random_category']) ? $post_custom['_saved_draft_random_category'] : false; $random_category = is_array($random_category) ? current($random_category) : null; if (!empty($random_category)) { $cats = get_categories(array('type' => 'post', 'hide_empty' => 0)); $random_cats = array(); if (is_array($cats)) { foreach ($cats as $cat) { $random_cats[] = $cat->term_id; } } if (count($random_cats) > 0) { shuffle($random_cats); $key = array_rand($random_cats); wp_set_post_categories($new_post_id, array($random_cats[$key]), false); } } } // end of post plus // MainWP Robot if ($is_robot_post) { $all_comments = $post_custom['_mainwp_robot_post_comments']; MainWP_Child_Robot::Instance()->wpr_insertcomments($new_post_id, $all_comments); } $ret['success'] = true; $ret['link'] = $permalink; $ret['added_id'] = $new_post_id; return $ret; }
function import_post($entry) { global $importing_blog; foreach ($entry->links as $link) { // save the self link as meta if ($link['rel'] == 'self') { $postself = $link['href']; $parts = parse_url($link['href']); $entry->old_permalink = $parts['path']; } // get the old URI for the page when available if ($link['rel'] == 'alternate') { $parts = parse_url($link['href']); $entry->bookmark = $parts['path']; } // save the replies feed link as meta (ignore the comment form one) if ($link['rel'] == 'replies' && false === strpos($link['href'], '#comment-form')) { $postreplies = $link['href']; } } //Check if we are double cleaning here? Does the Simplepie already do all this? $post_date = $entry->published; $post_content = trim(addslashes($this->no_apos(@html_entity_decode($entry->content, ENT_COMPAT, get_option('blog_charset'))))); $post_title = trim(addslashes($this->no_apos($this->min_whitespace($entry->title)))); $post_status = $entry->isDraft ? 'draft' : 'publish'; // N.B. Clean up of $post_content is now part of the sanitize class // Checks for duplicates if (isset($this->blogs[$importing_blog]['posts'][$entry->old_permalink])) { $this->blogs[$importing_blog]['posts_skipped']++; } elseif ($post_id = post_exists($post_title, $post_content, $post_date)) { $this->blogs[$importing_blog]['posts'][$entry->old_permalink] = $post_id; $this->blogs[$importing_blog]['posts_skipped']++; } else { $post = compact('post_date', 'post_content', 'post_title', 'post_status'); $post_id = wp_insert_post($post); if (is_wp_error($post_id)) { return $post_id; } wp_create_categories(array_map('addslashes', $entry->categories), $post_id); $author = $this->no_apos(strip_tags($entry->author)); add_post_meta($post_id, 'blogger_blog', $this->blogs[$importing_blog]['host'], true); add_post_meta($post_id, 'blogger_author', $author, true); //Use the page id if available or the blogger internal id if it's a draft if ($entry->isDraft | !isset($entry->bookmark)) { add_post_meta($post_id, 'blogger_permalink', $entry->old_permalink, true); } else { add_post_meta($post_id, 'blogger_permalink', $entry->bookmark, true); } add_post_meta($post_id, '_blogger_self', $postself, true); if (isset($entry->geotags)) { add_post_meta($post_id, 'geo_latitude', $entry->geotags['geo_latitude']); add_post_meta($post_id, 'geo_longitude', $entry->geotags['geo_longitude']); if (isset($entry->geotags['geo_address'])) { add_post_meta($post_id, 'geo_address', $entry->geotags['geo_address']); } } $this->blogs[$importing_blog]['posts'][$entry->old_permalink] = $post_id; $this->blogs[$importing_blog]['posts_done']++; } $this->save_vars(); return; }
function process_posts() { $h = new RS_CSV_Helper(); $handle = $h->fopen($this->file, 'r'); if ($handle == false) { echo '<p><strong>' . __('Failed to open file.', 'rs-csv-importer') . '</strong></p>'; wp_import_cleanup($this->id); return false; } $is_first = true; echo '<ol>'; while (($data = $h->fgetcsv($handle)) !== FALSE) { if ($is_first) { $h->parse_columns($this, $data); $is_first = false; } else { echo '<li>'; $post = array(); $is_update = false; $error = new WP_Error(); // (string) (required) post type $post_type = $h->get_data($this, $data, 'post_type'); if ($post_type) { if (post_type_exists($post_type)) { $post['post_type'] = $post_type; } else { $error->add('post_type_exists', sprintf(__('The post type %s is not exists. Please check your csv data.', 'rs-csv-importer'), $post_type)); } } else { echo __('Note: Please include post_type value if that is possible.', 'rs-csv-importer') . '<br>'; } // (int) post id $post_id = $h->get_data($this, $data, 'ID'); $post_id = $post_id ? $post_id : $h->get_data($this, $data, 'post_id'); if ($post_id) { $post_exist = get_post($post_id); if (is_null($post_exist)) { // if the post id is not exists $post['import_id'] = $post_id; } else { if (!$post_type || $post_exist->post_type == $post_type) { $post['ID'] = $post_id; $is_update = true; } else { $error->add('post_type_check', sprintf(__('The post id %d is exists, but post types does not match.', 'rs-csv-importer'), $post_id)); } } } // (string) post slug $post_name = $h->get_data($this, $data, 'post_name'); if ($post_name) { $post['post_name'] = $post_name; } // (login or ID) post_author $post_author = $h->get_data($this, $data, 'post_author'); if ($post_author) { if (is_numeric($post_author)) { $user = get_user_by('id', $post_author); } else { $user = get_user_by('login', $post_author); } if (isset($user) && is_object($user)) { $post['post_author'] = $user->ID; unset($user); } } // (string) publish date $post_date = $h->get_data($this, $data, 'post_date'); if ($post_date) { $post['post_date'] = date("Y-m-d H:i:s", strtotime($post_date)); } // (string) post status $post_status = $h->get_data($this, $data, 'post_status'); if ($post_status) { $post['post_status'] = $post_status; } // (string) post title $post_title = $h->get_data($this, $data, 'post_title'); if ($post_title) { $post['post_title'] = $post_title; } // (string) post content $post_content = $h->get_data($this, $data, 'post_content'); if ($post_content) { $post['post_content'] = $post_content; } // (string) post excerpt $post_excerpt = $h->get_data($this, $data, 'post_excerpt'); if ($post_excerpt) { $post['post_excerpt'] = $post_excerpt; } // (int) post parent $post_parent = $h->get_data($this, $data, 'post_parent'); if ($post_parent) { $post['post_parent'] = $post_parent; } // (int) menu order $menu_order = $h->get_data($this, $data, 'menu_order'); if ($menu_order) { $post['menu_order'] = $menu_order; } // (string, comma divided) slug of post categories $post_category = $h->get_data($this, $data, 'post_category'); if ($post_category) { $categories = preg_split("/,+/", $post_category); if ($categories) { $post['post_category'] = wp_create_categories($categories); } } // (string, comma divided) name of post tags $post_tags = $h->get_data($this, $data, 'post_tags'); if ($post_tags) { $tags = preg_split("/,+/", $post_tags); if ($tags) { $post['post_tags'] = $tags; } } // (string) post thumbnail image uri $post_thumbnail = $h->get_data($this, $data, 'post_thumbnail'); if (parse_url($post_thumbnail, PHP_URL_SCHEME)) { $post_thumbnail = remote_get_file($post_thumbnail); } $meta = array(); $tax = array(); // add any other data to post meta foreach ($data as $key => $value) { if ($value !== false && isset($this->column_keys[$key])) { // check if meta is custom taxonomy if (substr($this->column_keys[$key], 0, 4) == 'tax_') { // (string, comma divided) name of custom taxonomies $customtaxes = preg_split("/,+/", $value); $taxname = substr($this->column_keys[$key], 4); $tax[$taxname] = array(); foreach ($customtaxes as $key => $value) { $tax[$taxname][] = $value; } } else { $meta[$this->column_keys[$key]] = $value; } } } /** * Filter post data. * * @param array $post (required) * @param bool $is_update */ $post = apply_filters('really_simple_csv_importer_save_post', $post, $is_update); /** * Filter meta data. * * @param array $meta (required) * @param array $post * @param bool $is_update */ $meta = apply_filters('really_simple_csv_importer_save_meta', $meta, $post, $is_update); /** * Filter taxonomy data. * * @param array $tax (required) * @param array $post * @param bool $is_update */ $tax = apply_filters('really_simple_csv_importer_save_tax', $tax, $post, $is_update); /** * Option for dry run * * @param bool false */ $dry_run = apply_filters('really_simple_csv_importer_dry_run', false); if (!$error->get_error_codes() && $dry_run == false) { // save post data $result = $this->save_post($post, $meta, $tax, $post_thumbnail, $is_update); if ($result) { echo esc_html(sprintf(__('Processing "%s" done.', 'rs-csv-importer'), $post_title)); } else { $error->add('save_post', __('An error occurred while saving the post to database.', 'rs-csv-importer')); } } // show error messages foreach ($error->get_error_messages() as $message) { echo esc_html($message) . '<br>'; } echo '</li>'; } } echo '</ol>'; $h->fclose($handle); wp_import_cleanup($this->id); echo '<h3>' . __('All Done.', 'rs-csv-importer') . '</h3>'; }
function tp_write_post($v, $opt) { $tpo = get_option('tp_options'); $post_template_excerpt = $tpo['excerpt']; $post_template_content = $tpo['content']; $post_status = !empty($tpo['status']) ? $tpo['status'] : 'publish'; $vid = !empty($v->id) ? $v->id : $opt['video_id']; $tp_tags = array("%tp_player%", "%tp_id%", "%tp_title%", "%tp_thumbnail%", "%tp_description%", "%tp_url%"); $tag_values = array(tp_player($vid), $vid, $v->snippet->title, $v->snippet->thumbnails->high->url, $v->snippet->description, "https://www.youtube.com/watch?v=" . $vid); $post_template_excerpt = str_replace($tp_tags, $tag_values, $post_template_excerpt); $post_template_content = str_replace($tp_tags, $tag_values, $post_template_content); $post_category = explode(',', trim($opt['cat'], " \n\t\r\v,")); $tp_post = array('post_title' => $v->snippet->title, 'post_content' => nl2br($post_template_content), 'post_status' => $post_status, 'post_type' => $tpo['type'], 'post_name' => sanitize_title($v->snippet->title), 'post_category' => $post_category, 'post_excerpt' => nl2br($post_template_excerpt)); $post_id = wp_insert_post($tp_post); if ($tpo['customfield']) { foreach ($tp_tags as $k => $meta_key) { add_post_meta($post_id, str_replace("%", "", $meta_key), $tag_values[$k]); } } wp_create_categories($post_category, $post_id); }
function create($args) { //$this->_log($args); global $wpdb; /** * algorithm * 1. create post using wp_insert_post (insert tags also here itself) * 2. use wp_create_categories() to create(not exists) and insert in the post * 3. insert meta values */ include_once ABSPATH . 'wp-admin/includes/taxonomy.php'; include_once ABSPATH . 'wp-admin/includes/image.php'; include_once ABSPATH . 'wp-admin/includes/file.php'; $post_struct = $args['post_data']; $post_data = $post_struct['post_data']; $new_custom = $post_struct['post_extras']['post_meta']; $post_categories = explode(',', $post_struct['post_extras']['post_categories']); $post_atta_img = $post_struct['post_extras']['post_atta_images']; $post_upload_dir = $post_struct['post_extras']['post_upload_dir']; $post_checksum = $post_struct['post_extras']['post_checksum']; $post_featured_img = $post_struct['post_extras']['featured_img']; $upload = wp_upload_dir(); // create dynamic url RegExp $iwp_base_url = parse_url($post_upload_dir['url']); $iwp_regexp_url = $iwp_base_url['host'] . $iwp_base_url['path']; $rep = array('/', '+', '.', ':', '?'); $with = array('\\/', '\\+', '\\.', '\\:', '\\?'); $iwp_regexp_url = str_replace($rep, $with, $iwp_regexp_url); // rename all src ../wp-content/ with hostname/wp-content/ $iwp_mmb_dot_url = '..' . $iwp_mmb_base_url['path']; $iwp_mmb_dot_url = str_replace($rep, $with, $iwp_mmb_dot_url); $dot_match_count = preg_match_all('/(<a[^>]+href=\\"([^"]+)\\"[^>]*>)?(<\\s*img.[^\\/>]*src="([^"]*' . $iwp_mmb_dot_url . '[^\\s]+\\.(jpg|jpeg|png|gif|bmp))"[^>]*>)/ixu', $post_data['post_content'], $dot_get_urls, PREG_SET_ORDER); if ($dot_match_count > 0) { foreach ($dot_get_urls as $dot_url) { $match_dot = '/' . str_replace($rep, $with, $dot_url[4]) . '/'; $replace_dot = 'http://' . $iwp_mmb_base_url['host'] . substr($dot_url[4], 2, strlen($dot_url[4])); $post_data['post_content'] = preg_replace($match_dot, $replace_dot, $post_data['post_content']); if ($dot_url[1] != '') { $match_dot_a = '/' . str_replace($rep, $with, $dot_url[2]) . '/'; $replace_dot_a = 'http://' . $iwp_mmb_base_url['host'] . substr($dot_url[2], 2, strlen($dot_url[2])); $post_data['post_content'] = preg_replace($match_dot_a, $replace_dot_a, $post_data['post_content']); } } } //to find all the images $match_count = preg_match_all('/(<a[^>]+href=\\"([^"]+)\\"[^>]*>)?(<\\s*img.[^\\/>]*src="([^"]+' . $iwp_mmb_regexp_url . '[^\\s]+\\.(jpg|jpeg|png|gif|bmp))"[^>]*>)/ixu', $post_data['post_content'], $get_urls, PREG_SET_ORDER); /////////// //$html = $params['postContent']; // // $doc = new DOMDocument(); // @$doc->loadHTML($html); // // $tags = $doc->getElementsByTagName('img'); // // foreach ($tags as $tag) { // $img[]['src'] = str_replace('\"','',$tag->getAttribute('src')); // } ///////////////// if ($match_count > 0) { $attachments = array(); $post_content = $post_data['post_content']; foreach ($get_urls as $get_url_k => $get_url) { // unset url in attachment array foreach ($post_atta_img as $atta_url_k => $atta_url_v) { $match_patt_url = '/' . str_replace($rep, $with, substr($atta_url_v['src'], 0, strrpos($atta_url_v['src'], '.'))) . '/'; if (preg_match($match_patt_url, $get_url[4])) { unset($post_atta_img[$atta_url_k]); } } $pic_from_other_site = $get_urls[$get_url_k][4]; /* if(strpos($pic_from_other_site,'exammple.com') === false){ continue; }*/ if (isset($get_urls[$get_url_k][6])) { // url have parent, don't download this url if ($get_url[1] != '') { // change src url $s_mmb_mp = '/' . str_replace($rep, $with, $get_url[4]) . '/'; $s_img_atta = wp_get_attachment_image_src($get_urls[$get_url_k][6]); $s_mmb_rp = $s_img_atta[0]; $post_content = preg_replace($s_mmb_mp, $s_mmb_rp, $post_content); // change attachment url if (preg_match('/attachment_id/i', $get_url[2])) { $iwp_mmb_mp = '/' . str_replace($rep, $with, $get_url[2]) . '/'; $iwp_mmb_rp = get_bloginfo('wpurl') . '/?attachment_id=' . $get_urls[$get_url_k][6]; $post_content = preg_replace($iwp_mmb_mp, $iwp_mmb_rp, $post_content); } } continue; } $no_thumb = ''; if (preg_match('/-\\d{3}x\\d{3}\\.[a-zA-Z0-9]{3,4}$/', $get_url[4])) { $no_thumb = preg_replace('/-\\d{3}x\\d{3}\\.[a-zA-Z0-9]{3,4}$/', '.' . $get_url[5], $get_url[4]); } else { $no_thumb = $get_url[4]; } if (isset($upload['error']) && !empty($upload['error'])) { return array('error' => $upload['error']); } $file_name = basename($no_thumb); $tmp_file = download_url($no_thumb); if (is_wp_error($tmp_file)) { return array('error' => $tmp_file->get_error_message()); } $attach_upload['url'] = $upload['url'] . '/' . $file_name; $attach_upload['path'] = $upload['path'] . '/' . $file_name; $renamed = @rename($tmp_file, $attach_upload['path']); if ($renamed === true) { $match_pattern = '/' . str_replace($rep, $with, $get_url[4]) . '/'; $replace_pattern = $attach_upload['url']; $post_content = preg_replace($match_pattern, $replace_pattern, $post_content); if (preg_match('/-\\d{3}x\\d{3}\\.[a-zA-Z0-9]{3,4}$/', $get_url[4])) { $match_pattern = '/' . str_replace($rep, $with, preg_replace('/-\\d{3}x\\d{3}\\.[a-zA-Z0-9]{3,4}$/', '.' . $get_url[5], $get_url[4])) . '/'; $post_content = preg_replace($match_pattern, $replace_pattern, $post_content); } $attachment = array('post_title' => $file_name, 'post_content' => '', 'post_type' => 'attachment', 'post_mime_type' => 'image/' . $get_url[5], 'guid' => $attach_upload['url']); // Save the data $attach_id = wp_insert_attachment($attachment, $attach_upload['path']); $attachments[$attach_id] = 0; // featured image if ($post_featured_img != '') { $feat_img_url = ''; if (preg_match('/-\\d{3}x\\d{3}\\.[a-zA-Z0-9]{3,4}$/', $post_featured_img)) { $feat_img_url = substr($post_featured_img, 0, strrpos($post_featured_img, '.') - 8); } else { $feat_img_url = substr($post_featured_img, 0, strrpos($post_featured_img, '.')); } $m_feat_url = '/' . str_replace($rep, $with, $feat_img_url) . '/'; if (preg_match($m_feat_url, $get_url[4])) { $post_featured_img = ''; $attachments[$attach_id] = $attach_id; } } // set $get_urls value[6] - parent atta_id foreach ($get_urls as $url_k => $url_v) { if ($get_url_k != $url_k) { $s_get_url = ''; if (preg_match('/-\\d{3}x\\d{3}\\.[a-zA-Z0-9]{3,4}$/', $url_v[4])) { $s_get_url = substr($url_v[4], 0, strrpos($url_v[4], '.') - 8); } else { $s_get_url = substr($url_v[4], 0, strrpos($url_v[4], '.')); } $m_patt_url = '/' . str_replace($rep, $with, $s_get_url) . '/'; if (preg_match($m_patt_url, $get_url[4])) { array_push($get_urls[$url_k], $attach_id); } } } $some_data = wp_generate_attachment_metadata($attach_id, $attach_upload['path']); wp_update_attachment_metadata($attach_id, $some_data); //changing href of a tag if ($get_url[1] != '') { $iwp_mmb_mp = '/' . str_replace($rep, $with, $get_url[2]) . '/'; if (preg_match('/attachment_id/i', $get_url[2])) { $iwp_mmb_rp = get_bloginfo('wpurl') . '/?attachment_id=' . $attach_id; $post_content = preg_replace($iwp_mmb_mp, $iwp_mmb_rp, $post_content); } } } else { @unlink($tmp_file); return array('error' => "Cannot create attachment file in " . $attach_upload['path'] . " Please set correct permissions."); } @unlink($tmp_file); } $post_data['post_content'] = $post_content; } if (count($post_atta_img)) { foreach ($post_atta_img as $img) { $file_name = basename($img['src']); if (isset($upload['error']) && !empty($upload['error'])) { return array('error' => $upload['error']); } $tmp_file = download_url($img['src']); if (is_wp_error($tmp_file)) { return array('error' => $tmp_file->get_error_message()); } $attach_upload['url'] = $upload['url'] . '/' . $file_name; $attach_upload['path'] = $upload['path'] . '/' . $file_name; $renamed = @rename($tmp_file, $attach_upload['path']); if ($renamed === true) { $atta_ext = end(explode('.', $file_name)); $attachment = array('post_title' => $file_name, 'post_content' => '', 'post_type' => 'attachment', 'post_mime_type' => 'image/' . $atta_ext, 'guid' => $attach_upload['url']); // Save the data $attach_id = wp_insert_attachment($attachment, $attach_upload['path']); wp_update_attachment_metadata($attach_id, wp_generate_attachment_metadata($attach_id, $attach_upload['path'])); $attachments[$attach_id] = 0; // featured image if ($post_featured_img != '') { $feat_img_url = ''; if (preg_match('/-\\d{3}x\\d{3}\\.[a-zA-Z0-9]{3,4}$/', $post_featured_img)) { $feat_img_url = substr($post_featured_img, 0, strrpos($post_featured_img, '.') - 8); } else { $feat_img_url = substr($post_featured_img, 0, strrpos($post_featured_img, '.')); } $m_feat_url = '/' . str_replace($rep, $with, $feat_img_url) . '/'; if (preg_match($m_feat_url, $img['src'])) { $post_featured_img = ''; $attachments[$attach_id] = $attach_id; } } } else { @unlink($tmp_file); return array('error' => "Cannot create attachment file in " . $attach_upload['path'] . " Please set correct permissions."); } @unlink($tmp_file); } } //Prepare post data and temporarily remove content filters before insert post $user = $this->iwp_mmb_get_user_info($args['username']); if ($user && $user->ID) { $post_data['post_author'] = $user->ID; } //remove filter which can brake scripts or html remove_filter('content_save_pre', 'wp_filter_post_kses'); //check for edit post $post_result = 0; if (isset($post_data['iwp_post_edit']) && $post_data['iwp_post_edit']) { if ($post_data['iwp_match_by'] == 'title') { $match_by = "post_title = '" . $post_data['post_title'] . "'"; } else { $match_by = "post_name = '" . $post_data['post_name'] . "'"; } $query = "SELECT ID FROM {$wpdb->posts} WHERE {$match_by} AND post_status NOT IN('inherit','auto-draft','draft') LIMIT 1"; $post_result = $wpdb->get_var($query); } if ($post_result) { //update existing post $post_data['ID'] = $post_result; $post_id = wp_update_post($post_data); //check for previous attachments $atta_allimages =& get_children('post_type=attachment&post_parent=' . $post_id); if (!empty($atta_allimages)) { foreach ($atta_allimages as $image) { wp_delete_attachment($image->ID); } } } else { if ($post_data['iwp_post_edit'] && $post_data['iwp_force_publish']) { $post_id = wp_insert_post($post_data); } elseif ($post_data['iwp_post_edit'] && !$post_data['iwp_force_publish']) { return array('error' => "Post not found."); } else { $post_id = wp_insert_post($post_data); } } if (count($attachments)) { foreach ($attachments as $atta_id => $featured_id) { $result = wp_update_post(array('ID' => $atta_id, 'post_parent' => $post_id)); if ($featured_id > 0) { $new_custom['_thumbnail_id'] = array($featured_id); } } } // featured image if ($post_featured_img != '') { $file_name = basename($post_featured_img); if (isset($upload['error']) && !empty($upload['error'])) { return array('error' => $upload['error']); } $tmp_file = download_url($post_featured_img); if (is_wp_error($tmp_file)) { return array('error' => $tmp_file->get_error_message()); } $attach_upload['url'] = $upload['url'] . '/' . $file_name; $attach_upload['path'] = $upload['path'] . '/' . $file_name; $renamed = @rename($tmp_file, $attach_upload['path']); if ($renamed === true) { $atta_ext = end(explode('.', $file_name)); $attachment = array('post_title' => $file_name, 'post_content' => '', 'post_type' => 'attachment', 'post_parent' => $post_id, 'post_mime_type' => 'image/' . $atta_ext, 'guid' => $attach_upload['url']); // Save the data $attach_id = wp_insert_attachment($attachment, $attach_upload['path']); wp_update_attachment_metadata($attach_id, wp_generate_attachment_metadata($attach_id, $attach_upload['path'])); $new_custom['_thumbnail_id'] = array($attach_id); } else { @unlink($tmp_file); return array('error' => "Cannot create attachment file in " . $attach_upload['path'] . " Please set correct permissions."); } @unlink($tmp_file); } if ($post_id && is_array($post_categories)) { //insert categories $cat_ids = wp_create_categories($post_categories, $post_id); } //get current custom fields $cur_custom = get_post_custom($post_id); //check which values doesnot exists in new custom fields $diff_values = array_diff_key($cur_custom, $new_custom); if (is_array($diff_values)) { foreach ($diff_values as $meta_key => $value) { delete_post_meta($post_id, $meta_key); } } //insert new post meta foreach ($new_custom as $meta_key => $value) { if (strpos($meta_key, '_mmb') === 0 || strpos($meta_key, '_edit') === 0) { continue; } else { update_post_meta($post_id, $meta_key, $value[0]); } } return $post_id; }
function import_posts() { echo '<ol>'; foreach ($this->posts as $post) { echo "<li>".__('Importing post...'); extract($post); if ($post_id = post_exists($post_title, $post_content, $post_date)) { _e('Post already imported'); } else { $post_id = wp_insert_post($post); if (!$post_id) { _e("Couldn't get post ID"); return; } if (0 != count($categories)) wp_create_categories($categories, $post_id); _e('Done !'); } echo '</li>'; } echo '</ol>'; }
function import_post($entry) { global $importing_blog; // The old permalink is all Blogger gives us to link comments to their posts. if (isset($entry->draft)) { $rel = 'self'; } else { $rel = 'alternate'; } foreach ($entry->links as $link) { if ($link['rel'] == $rel) { $parts = parse_url($link['href']); $entry->old_permalink = $parts['path']; break; } } $post_date = $this->convert_date($entry->published); $post_content = trim(addslashes($this->no_apos(html_entity_decode($entry->content)))); $post_title = trim(addslashes($this->no_apos($this->min_whitespace($entry->title)))); $post_status = isset($entry->draft) ? 'draft' : 'publish'; // Clean up content $post_content = preg_replace('|<(/?[A-Z]+)|e', "'<' . strtolower('\$1')", $post_content); $post_content = str_replace('<br>', '<br />', $post_content); $post_content = str_replace('<hr>', '<hr />', $post_content); // Checks for duplicates if (isset($this->blogs[$importing_blog]['posts'][$entry->old_permalink])) { ++$this->blogs[$importing_blog]['posts_skipped']; } elseif ($post_id = post_exists($post_title, $post_content, $post_date)) { $this->blogs[$importing_blog]['posts'][$entry->old_permalink] = $post_id; ++$this->blogs[$importing_blog]['posts_skipped']; } else { $post = compact('post_date', 'post_content', 'post_title', 'post_status'); $post_id = wp_insert_post($post); if (is_wp_error($post_id)) { return $post_id; } wp_create_categories(array_map('addslashes', $entry->categories), $post_id); $author = $this->no_apos(strip_tags($entry->author)); add_post_meta($post_id, 'blogger_blog', $this->blogs[$importing_blog]['host'], true); add_post_meta($post_id, 'blogger_author', $author, true); add_post_meta($post_id, 'blogger_permalink', $entry->old_permalink, true); $this->blogs[$importing_blog]['posts'][$entry->old_permalink] = $post_id; ++$this->blogs[$importing_blog]['posts_done']; } $this->save_vars(); return; }
function process_posts() { global $wpdb; $i = -1; echo '<ol>'; foreach ($this->posts as $post) { // There are only ever one of these $post_title = $this->get_tag($post, 'title'); $post_date = $this->get_tag($post, 'wp:post_date'); $post_date_gmt = $this->get_tag($post, 'wp:post_date_gmt'); $comment_status = $this->get_tag($post, 'wp:comment_status'); $ping_status = $this->get_tag($post, 'wp:ping_status'); $post_status = $this->get_tag($post, 'wp:status'); $post_parent = $this->get_tag($post, 'wp:post_parent'); $post_type = $this->get_tag($post, 'wp:post_type'); $guid = $this->get_tag($post, 'guid'); $post_author = $this->get_tag($post, 'dc:creator'); $post_content = $this->get_tag($post, 'content:encoded'); $post_content = str_replace(array('<![CDATA[', ']]>'), '', $post_content); $post_content = preg_replace('|<(/?[A-Z]+)|e', "'<' . strtolower('\$1')", $post_content); $post_content = str_replace('<br>', '<br />', $post_content); $post_content = str_replace('<hr>', '<hr />', $post_content); preg_match_all('|<category>(.*?)</category>|is', $post, $categories); $categories = $categories[1]; $cat_index = 0; foreach ($categories as $category) { $categories[$cat_index] = $wpdb->escape($this->unhtmlentities(str_replace(array('<![CDATA[', ']]>'), '', $category))); $cat_index++; } if ($post_id = post_exists($post_title, '', $post_date)) { echo '<li>'; printf(__('Post <i>%s</i> already exists.'), stripslashes($post_title)); } else { echo '<li>'; printf(__('Importing post <i>%s</i>...'), stripslashes($post_title)); $post_author = $this->checkauthor($post_author); //just so that if a post already exists, new users are not created by checkauthor $postdata = compact('post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_title', 'post_excerpt', 'post_status', 'comment_status', 'ping_status', 'post_modified', 'post_modified_gmt', 'guid', 'post_parent', 'post_type'); $comment_post_ID = $post_id = wp_insert_post($postdata); // Add categories. if (0 != count($categories)) { wp_create_categories($categories, $post_id); } } // Now for comments preg_match_all('|<wp:comment>(.*?)</wp:comment>|is', $post, $comments); $comments = $comments[1]; $num_comments = 0; if ($comments) { foreach ($comments as $comment) { $comment_author = $this->get_tag($comment, 'wp:comment_author'); $comment_author_email = $this->get_tag($comment, 'wp:comment_author_email'); $comment_author_IP = $this->get_tag($comment, 'wp:comment_author_IP'); $comment_author_url = $this->get_tag($comment, 'wp:comment_author_url'); $comment_date = $this->get_tag($comment, 'wp:comment_date'); $comment_date_gmt = $this->get_tag($comment, 'wp:comment_date_gmt'); $comment_content = $this->get_tag($comment, 'wp:comment_content'); $comment_approved = $this->get_tag($comment, 'wp:comment_approved'); $comment_type = $this->get_tag($comment, 'wp:comment_type'); $comment_parent = $this->get_tag($comment, 'wp:comment_parent'); if (!comment_exists($comment_author, $comment_date)) { $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'); wp_insert_comment($commentdata); $num_comments++; } } } if ($num_comments) { printf(' ' . __('(%s comments)'), $num_comments); } // Now for post meta preg_match_all('|<wp:postmeta>(.*?)</wp:postmeta>|is', $post, $postmeta); $postmeta = $postmeta[1]; if ($postmeta) { foreach ($postmeta as $p) { $key = $this->get_tag($p, 'wp:meta_key'); $value = $this->get_tag($p, 'wp:meta_value'); add_post_meta($post_id, $key, $value); } } $index++; } echo '</ol>'; wp_import_cleanup($this->id); echo '<h3>' . sprintf(__('All done.') . ' <a href="%s">' . __('Have fun!') . '</a>', get_option('home')) . '</h3>'; }
function process_posts() { global $wpdb; $i = -1; echo "<ol>"; foreach ($this->posts as $post) { if ('' != trim($post)) { ++$i; unset($post_categories); // Take the pings out first preg_match("|(-----\n\nPING:.*)|s", $post, $pings); $post = preg_replace("|(-----\n\nPING:.*)|s", '', $post); // Then take the comments out preg_match("|(-----\nCOMMENT:.*)|s", $post, $comments); $post = preg_replace("|(-----\nCOMMENT:.*)|s", '', $post); // We ignore the keywords $post = preg_replace("|(-----\nKEYWORDS:.*)|s", '', $post); // We want the excerpt preg_match("|-----\nEXCERPT:(.*)|s", $post, $excerpt); $excerpt = $wpdb->escape(trim($excerpt[1])); $post = preg_replace("|(-----\nEXCERPT:.*)|s", '', $post); // We're going to put extended body into main body with a more tag preg_match("|-----\nEXTENDED BODY:(.*)|s", $post, $extended); $extended = trim($extended[1]); if ('' != $extended) { $extended = "\n<!--more-->\n{$extended}"; } $post = preg_replace("|(-----\nEXTENDED BODY:.*)|s", '', $post); // Now for the main body preg_match("|-----\nBODY:(.*)|s", $post, $body); $body = trim($body[1]); $post_content = $wpdb->escape($body . $extended); $post = preg_replace("|(-----\nBODY:.*)|s", '', $post); // Grab the metadata from what's left $metadata = explode("\n", $post); foreach ($metadata as $line) { preg_match("/^(.*?):(.*)/", $line, $token); $key = trim($token[1]); $value = trim($token[2]); // Now we decide what it is and what to do with it switch ($key) { case '': break; case 'AUTHOR': $post_author = $value; break; case 'TITLE': $post_title = $wpdb->escape($value); break; case 'STATUS': // "publish" and "draft" enumeration items match up; no change required $post_status = $value; if (empty($post_status)) { $post_status = 'publish'; } break; case 'ALLOW COMMENTS': $post_allow_comments = $value; if ($post_allow_comments == 1) { $comment_status = 'open'; } else { $comment_status = 'closed'; } break; case 'CONVERT BREAKS': $post_convert_breaks = $value; break; case 'ALLOW PINGS': $post_allow_pings = trim($meta[2][0]); if ($post_allow_pings == 1) { $post_allow_pings = 'open'; } else { $post_allow_pings = 'closed'; } break; case 'PRIMARY CATEGORY': if (!empty($value)) { $post_categories[] = $wpdb->escape($value); } break; case 'CATEGORY': if (!empty($value)) { $post_categories[] = $wpdb->escape($value); } break; case 'DATE': $post_modified = strtotime($value); $post_modified = date('Y-m-d H:i:s', $post_modified); $post_modified_gmt = get_gmt_from_date("{$post_modified}"); $post_date = $post_modified; $post_date_gmt = $post_modified_gmt; break; default: // echo "\n$key: $value"; break; } // end switch } // End foreach // Let's check to see if it's in already if ($post_id = post_exists($post_title, '', $post_date)) { echo '<li>'; printf(__('Post <i>%s</i> already exists.'), stripslashes($post_title)); } else { echo '<li>'; printf(__('Importing post <i>%s</i>...'), stripslashes($post_title)); $post_author = $this->checkauthor($post_author); //just so that if a post already exists, new users are not created by checkauthor $postdata = compact('post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_title', 'post_excerpt', 'post_status', 'comment_status', 'ping_status', 'post_modified', 'post_modified_gmt'); $post_id = wp_insert_post($postdata); // Add categories. if (0 != count($post_categories)) { wp_create_categories($post_categories, $post_id); } } $comment_post_ID = $post_id; // Now for comments $comments = explode("-----\nCOMMENT:", $comments[0]); $num_comments = 0; foreach ($comments as $comment) { if ('' != trim($comment)) { // Author preg_match("|AUTHOR:(.*)|", $comment, $comment_author); $comment_author = $wpdb->escape(trim($comment_author[1])); $comment = preg_replace('|(\\n?AUTHOR:.*)|', '', $comment); preg_match("|EMAIL:(.*)|", $comment, $comment_author_email); $comment_author_email = $wpdb->escape(trim($comment_author_email[1])); $comment = preg_replace('|(\\n?EMAIL:.*)|', '', $comment); preg_match("|IP:(.*)|", $comment, $comment_author_IP); $comment_author_IP = trim($comment_author_IP[1]); $comment = preg_replace('|(\\n?IP:.*)|', '', $comment); preg_match("|URL:(.*)|", $comment, $comment_author_url); $comment_author_url = $wpdb->escape(trim($comment_author_url[1])); $comment = preg_replace('|(\\n?URL:.*)|', '', $comment); preg_match("|DATE:(.*)|", $comment, $comment_date); $comment_date = trim($comment_date[1]); $comment_date = date('Y-m-d H:i:s', strtotime($comment_date)); $comment = preg_replace('|(\\n?DATE:.*)|', '', $comment); $comment_content = $wpdb->escape(trim($comment)); $comment_content = str_replace('-----', '', $comment_content); // Check if it's already there if (!comment_exists($comment_author, $comment_date)) { $commentdata = compact('comment_post_ID', 'comment_author', 'comment_author_url', 'comment_author_email', 'comment_author_IP', 'comment_date', 'comment_content'); $commentdata = wp_filter_comment($commentdata); wp_insert_comment($commentdata); $num_comments++; } } } if ($num_comments) { printf(__('(%s comments)'), $num_comments); } // Finally the pings // fix the double newline on the first one $pings[0] = str_replace("-----\n\n", "-----\n", $pings[0]); $pings = explode("-----\nPING:", $pings[0]); $num_pings = 0; foreach ($pings as $ping) { if ('' != trim($ping)) { // 'Author' preg_match("|BLOG NAME:(.*)|", $ping, $comment_author); $comment_author = $wpdb->escape(trim($comment_author[1])); $ping = preg_replace('|(\\n?BLOG NAME:.*)|', '', $ping); preg_match("|IP:(.*)|", $ping, $comment_author_IP); $comment_author_IP = trim($comment_author_IP[1]); $ping = preg_replace('|(\\n?IP:.*)|', '', $ping); preg_match("|URL:(.*)|", $ping, $comment_author_url); $comment_author_url = $wpdb->escape(trim($comment_author_url[1])); $ping = preg_replace('|(\\n?URL:.*)|', '', $ping); preg_match("|DATE:(.*)|", $ping, $comment_date); $comment_date = trim($comment_date[1]); $comment_date = date('Y-m-d H:i:s', strtotime($comment_date)); $ping = preg_replace('|(\\n?DATE:.*)|', '', $ping); preg_match("|TITLE:(.*)|", $ping, $ping_title); $ping_title = $wpdb->escape(trim($ping_title[1])); $ping = preg_replace('|(\\n?TITLE:.*)|', '', $ping); $comment_content = $wpdb->escape(trim($ping)); $comment_content = str_replace('-----', '', $comment_content); $comment_content = "<strong>{$ping_title}</strong>\n\n{$comment_content}"; $comment_type = 'trackback'; // Check if it's already there if (!comment_exists($comment_author, $comment_date)) { $commentdata = compact('comment_post_ID', 'comment_author', 'comment_author_url', 'comment_author_email', 'comment_author_IP', 'comment_date', 'comment_content', 'comment_type'); $commentdata = wp_filter_comment($commentdata); wp_insert_comment($commentdata); $num_pings++; } } } if ($num_pings) { printf(__('(%s pings)'), $num_pings); } echo "</li>"; } flush(); } echo '</ol>'; wp_import_cleanup($this->id); echo '<h3>' . sprintf(__('All done. <a href="%s">Have fun!</a>'), get_option('home')) . '</h3>'; }
function _import_post_to_db($post) { extract($post); $post_id = wp_insert_post($post); if (is_wp_error($post_id)) { return $post_id; } if (!$post_id) { _e('Couldn’t get post ID', 'powerpress'); return false; } if (0 != count($categories)) { wp_create_categories($categories, $post_id); } if (!empty($enclosure['url'])) { $encstring = $enclosure['url'] . "\n" . $enclosure['length'] . "\n" . $enclosure['type']; $serialize = array(); if (!empty($enclosure['duration']) && function_exists('powerpress_raw_duration')) { $serialize['duration'] = powerpress_raw_duration($enclosure['duration']); } if (!empty($enclosure['keywords'])) { $serialize['keywords'] = $enclosure['keywords']; } if (!empty($enclosure['summary'])) { $serialize['summary'] = $enclosure['summary']; } if (!empty($enclosure['subtitle'])) { $serialize['subtitle'] = $enclosure['subtitle']; } if (!empty($enclosure['author'])) { $serialize['author'] = $enclosure['author']; } if (!empty($enclosure['itunes_image'])) { $serialize['itunes_image'] = $enclosure['itunes_image']; } if (!empty($enclosure['block'])) { $serialize['block'] = $enclosure['block']; } if (!empty($enclosure['cc'])) { $serialize['cc'] = $enclosure['cc']; } if (!empty($enclosure['order'])) { $serialize['order'] = $enclosure['order']; } if (!empty($enclosure['explicit'])) { $serialize['explicit'] = $enclosure['explicit']; } if (!empty($serialize)) { $encstring .= "\n" . serialize($serialize); } $meta_id = add_post_meta($post_id, 'enclosure', $encstring, true); if ($meta_id) { if (empty($GLOBALS['pp_migrate_media_urls'])) { $GLOBALS['pp_migrate_media_urls'] = array(); } $GLOBALS['pp_migrate_media_urls'][$meta_id] = $enclosure['url']; } } return true; }