Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /*
- Plugin Name: CSV Importer
- Description: Import data as posts from a CSV file. <em>You can reach the author at <a href="mailto:d.v.kobozev@gmail.com">d.v.kobozev@gmail.com</a></em>.
- Version: 0.2.4
- Author: Denis Kobozev
- */
- /**
- * LICENSE: The MIT License {{{
- *
- * Copyright (c) <2009> <Denis Kobozev>
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- *
- * @author Denis Kobozev <d.v.kobozev@gmail.com>
- * @copyright 2009 Denis Kobozev
- * @license The MIT License
- * }}}
- */
- class CSVImporterPlugin {
- var $reserved_fields = array(
- 'csv_post_title',
- 'csv_post_post',
- 'csv_post_excerpt',
- 'csv_post_date',
- 'csv_post_tags',
- 'csv_post_categories',
- 'csv_post_author',
- 'csv_post_slug',
- );
- // option name => default value
- var $options = array(
- 'csv_importer_import_as_draft' => 'publish',
- 'csv_importer_import_post_type' => 'post',
- 'csv_importer_cat' => 0
- );
- var $log = array();
- // A bit of abstraction above WordPress option saving mechanism to
- // make our life easier
- function save_options($request) {
- foreach ($this->options as $opt_name => $default) {
- $value = $default;
- if (array_key_exists($opt_name, $request)) {
- $value = $request[$opt_name];
- }
- if (false === get_option($opt_name)) {
- add_option($opt_name, $value);
- } else {
- update_option($opt_name, $value);
- }
- }
- }
- function get_option($opt_name) {
- if (($value = get_option($opt_name)) === false) {
- $value = $this->options[$opt_name];
- }
- return $value;
- }
- // Plugin's interface
- function form() {
- if ('POST' == $_SERVER['REQUEST_METHOD']) {
- $this->save_options($_POST);
- $this->post();
- }
- $opt_draft = $this->get_option('csv_importer_import_as_draft');
- $opt_type = $this->get_option('csv_importer_import_post_type');
- $opt_cat = $this->get_option('csv_importer_cat');
- // form HTML {{{
- ?>
- <div class="wrap">
- <h2>Import CSV</h2>
- <form class="add:the-list: validate" method="post" enctype="multipart/form-data">
- <p><label><input name="csv_importer_import_as_draft" type="checkbox" <?php if ('draft' == $opt_draft) { echo 'checked="checked"'; } ?> value="draft" /> Import posts as drafts</label></p>
- <p><label><input name="csv_importer_import_post_type" type="checkbox" <?php if ('page' == $opt_type) { echo 'checked="checked"'; } ?> value="page" /> Import rows as pages, not posts</label></p>
- <p>Organize into category <?php wp_dropdown_categories(array('show_option_all' => 'Select one ...', 'hide_empty' => 0, 'hierarchical' => 1, 'show_count' => 0, 'name' => 'csv_importer_cat', 'orderby' => 'name', 'selected' => $opt_cat));?><br/>
- <small>This will create new categories inside the category parent you choose.</small></p>
- <p><label for="csv_import">Upload file:</label><br/>
- <input name="csv_import" id="csv_import" type="file" value="" aria-required="true" /></p>
- <p class="submit"><input type="submit" class="button" name="submit" value="Import" /></p>
- </form>
- </div><!-- end wrap -->
- <?php
- // end form HTML }}}
- }
- function print_messages() {
- if (!empty($this->log)) {
- // messages HTML {{{
- ?>
- <div class="wrap">
- <?php if (!empty($this->log['error'])): ?>
- <div class="error">
- <?php foreach ($this->log['error'] as $error): ?>
- <p><?php echo $error; ?></p>
- <?php endforeach; ?>
- </div>
- <?php endif; ?>
- <?php if (!empty($this->log['notice'])): ?>
- <div class="updated fade">
- <?php foreach ($this->log['notice'] as $notice): ?>
- <p><?php echo $notice; ?></p>
- <?php endforeach; ?>
- </div>
- <?php endif; ?>
- </div><!-- end wrap -->
- <?php
- // end messages HTML }}}
- $this->log = array();
- }
- }
- // Handle POST submission
- function post() {
- if (empty($_FILES['csv_import']['tmp_name'])) {
- $this->log['error'][] = 'No file uploaded, aborting.';
- $this->print_messages();
- return;
- }
- require_once 'File_CSV_DataSource/DataSource.php';
- $time_start = microtime(true);
- $csv = new File_CSV_DataSource;
- $file = $_FILES['csv_import']['tmp_name'];
- $this->stripBOM($file);
- if (!$csv->load($file)) {
- $this->log['error'][] = 'Failed to load file, aborting.';
- $this->print_messages();
- return;
- }
- // pad shorter rows with empty values
- $csv->symmetrize();
- $skipped = 0;
- $imported = 0;
- foreach ($csv->connect() as $csv_data) {
- if ($post_id = $this->create_post($csv_data)) {
- $imported++;
- $this->create_custom_fields($post_id, $csv_data);
- } else {
- $skipped++;
- }
- }
- if (file_exists($file)) {
- @unlink($file);
- }
- $exec_time = microtime(true) - $time_start;
- if ($skipped) {
- $this->log['notice'][] = "<b>Skipped {$skipped} posts (most likely due to empty title, body and excerpt).</b>";
- }
- $this->log['notice'][] = sprintf("<b>Imported {$imported} posts in %.2f seconds.</b>", $exec_time);
- $this->print_messages();
- }
- function create_post($data) {
- $status = $this->get_option('csv_importer_import_as_draft');
- $type = $this->get_option('csv_importer_import_post_type');
- $defaults = array();
- foreach ($this->reserved_fields as $k) {
- $defaults[$k] = null;
- }
- $data = array_merge($defaults, $data);
- $new_post = array(
- 'post_title' => convert_chars($data['csv_post_title']),
- 'post_content' => wpautop(convert_chars($data['csv_post_post'])),
- 'post_status' => $status,
- 'post_type' => $type,
- 'post_date' => $this->parse_date($data),
- 'post_excerpt' => "<img style='float: left; padding: 5px;' src='{$data['custom_field_1']}'/>" . convert_chars($data['csv_post_excerpt']),
- 'post_name' => $data['csv_post_slug'],
- 'post_author' => $this->get_auth_id($data['csv_post_author']),
- );
- if ('post' == $type) {
- $new_post['tags_input'] = $data['csv_post_tags'];
- // setup categories before inserting
- $cats = $this->create_categories($data);
- $new_post['post_category'] = array_merge($cats['old'], $cats['new']);
- }
- // create!
- $id = wp_insert_post($new_post);
- if ('post' == $type && !$id) {
- // cleanup new categories on failure
- foreach ($cats['new'] as $c) {
- wp_delete_term($c, 'category');
- }
- }
- return $id;
- }
- // Lookup existing categories or create new ones
- function create_categories($data) {
- $opt_cat = $this->get_option('csv_importer_cat');
- $ids = array(
- 'old' => array(),
- 'new' => array(),
- );
- $category_names = explode(',', $data['csv_post_categories']);
- foreach ($category_names as $cat_name) {
- $cat_name = trim($cat_name);
- if (!empty($cat_name)) {
- // Searching or creating the category
- if (is_numeric($cat_name)) {
- // it's an id, not a name
- if (null !== get_category($cat_name)) {
- $ids['old'][] = $cat_name;
- } else {
- $this->log['error'][] = "There is no category with id {$cat_name}.";
- }
- } else {
- $term = is_term($cat_name, 'category', $opt_cat);
- if (!$term) {
- $category = array(
- 'cat_name' => $cat_name,
- 'category_description' => '',
- 'category_nicename' => sanitize_title($cat_name),
- 'category_parent' => $opt_cat,
- );
- $cat_id = wp_insert_category($category);
- $ids['new'][] = $cat_id;
- } else {
- $ids['old'][] = $term['term_id'];
- }
- }
- }
- }
- return $ids;
- }
- function create_custom_fields($post_id, $data) {
- foreach ($data as $k => $v) {
- if ((array_search($k, $this->reserved_fields) === false) && $v != '' && $k != '') {
- add_post_meta($post_id, $k, $v);
- }
- }
- }
- function get_auth_id($author) {
- if (is_numeric($author)) return $author;
- $author_data = get_userdatabylogin($author);
- return (!$author_data) ? 0 : $author_data->ID;
- }
- // Convert date in CSV file to 1999-12-31 23:52:00 format
- function parse_date($data) {
- $timestamp = strtotime($data['csv_post_date']);
- if (false === $timestamp) {
- return '';
- } else {
- return date('Y-m-d H:i:s', $timestamp);
- }
- }
- // delete BOM from UTF-8 file
- function stripBOM($fname) {
- $res = fopen($fname, 'rb');
- if (false !== $res) {
- $bytes = fread($res, 3);
- if ($bytes == pack('CCC', 0xef, 0xbb, 0xbf)) {
- $this->log['notice'][] = 'Getting rid of byte order mark...';
- fclose($res);
- $contents = file_get_contents($fname);
- if (false === $contents) {
- trigger_error('Failed to get file contents.', E_USER_WARNING);
- }
- $contents = substr($contents, 3);
- $success = file_put_contents($fname, $contents);
- if (false === $success) {
- trigger_error('Failed to put file contents.', E_USER_WARNING);
- }
- } else {
- fclose($res);
- }
- } else {
- $this->log['error'][] = 'Failed to open file, aborting.';
- }
- }
- }
- function csv_admin_menu() {
- require_once ABSPATH . '/wp-admin/admin-functions.php';
- $plugin = new CSVImporterPlugin;
- add_management_page('edit.php', 'CSV Importer', 9, __FILE__, array($plugin, 'form'));
- }
- add_action('admin_menu', 'csv_admin_menu');
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement