Advertisement
Guest User

Untitled

a guest
May 22nd, 2017
525
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 11.71 KB | None | 0 0
  1. <?php
  2. /*
  3. Plugin Name: CSV Importer
  4. 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>.
  5. Version: 0.2.4
  6. Author: Denis Kobozev
  7. */
  8.  
  9. /**
  10.  * LICENSE: The MIT License {{{
  11.  *
  12.  * Copyright (c) <2009> <Denis Kobozev>
  13.  *
  14.  * Permission is hereby granted, free of charge, to any person obtaining a copy
  15.  * of this software and associated documentation files (the "Software"), to deal
  16.  * in the Software without restriction, including without limitation the rights
  17.  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  18.  * copies of the Software, and to permit persons to whom the Software is
  19.  * furnished to do so, subject to the following conditions:
  20.  *
  21.  * The above copyright notice and this permission notice shall be included in
  22.  * all copies or substantial portions of the Software.
  23.  *
  24.  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  25.  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  26.  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  27.  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  28.  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  29.  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  30.  * THE SOFTWARE.
  31.  *
  32.  * @author    Denis Kobozev <d.v.kobozev@gmail.com>
  33.  * @copyright 2009 Denis Kobozev
  34.  * @license   The MIT License
  35.  * }}}
  36.  */
  37.  
  38. class CSVImporterPlugin {
  39.     var $reserved_fields = array(
  40.         'csv_post_title',
  41.         'csv_post_post',
  42.         'csv_post_excerpt',
  43.         'csv_post_date',
  44.         'csv_post_tags',
  45.         'csv_post_categories',
  46.         'csv_post_author',
  47.         'csv_post_slug',
  48.     );
  49.  
  50.     // option name => default value
  51.     var $options = array(
  52.         'csv_importer_import_as_draft' => 'publish',
  53.         'csv_importer_import_post_type' => 'post',
  54.         'csv_importer_cat' => 0
  55.     );
  56.  
  57.     var $log = array();
  58.  
  59.     // A bit of abstraction above WordPress option saving mechanism to
  60.     // make our life easier
  61.     function save_options($request) {
  62.         foreach ($this->options as $opt_name => $default) {
  63.             $value = $default;
  64.             if (array_key_exists($opt_name, $request)) {
  65.                 $value = $request[$opt_name];
  66.             }
  67.             if (false === get_option($opt_name)) {
  68.                 add_option($opt_name, $value);
  69.             } else {
  70.                 update_option($opt_name, $value);
  71.             }
  72.         }
  73.     }
  74.  
  75.     function get_option($opt_name) {
  76.         if (($value = get_option($opt_name)) === false) {
  77.             $value = $this->options[$opt_name];
  78.         }
  79.         return $value;
  80.     }
  81.  
  82.     // Plugin's interface
  83.     function form() {
  84.         if ('POST' == $_SERVER['REQUEST_METHOD']) {
  85.             $this->save_options($_POST);
  86.             $this->post();
  87.         }
  88.  
  89.         $opt_draft = $this->get_option('csv_importer_import_as_draft');
  90.         $opt_type = $this->get_option('csv_importer_import_post_type');
  91.         $opt_cat = $this->get_option('csv_importer_cat');
  92.  
  93.         // form HTML {{{
  94. ?>
  95.        
  96. <div class="wrap">
  97.     <h2>Import CSV</h2>
  98.     <form class="add:the-list: validate" method="post" enctype="multipart/form-data">
  99.         <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>
  100.         <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>
  101.         <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/>
  102.             <small>This will create new categories inside the category parent you choose.</small></p>
  103.         <p><label for="csv_import">Upload file:</label><br/>
  104.             <input name="csv_import" id="csv_import" type="file" value="" aria-required="true" /></p>
  105.         <p class="submit"><input type="submit" class="button" name="submit" value="Import" /></p>
  106.     </form>
  107. </div><!-- end wrap -->
  108.  
  109. <?php
  110.         // end form HTML }}}
  111.  
  112.     }
  113.  
  114.     function print_messages() {
  115.         if (!empty($this->log)) {
  116.  
  117.         // messages HTML {{{
  118. ?>
  119.  
  120. <div class="wrap">
  121.     <?php if (!empty($this->log['error'])): ?>
  122.  
  123.     <div class="error">    
  124.  
  125.         <?php foreach ($this->log['error'] as $error): ?>
  126.             <p><?php echo $error; ?></p>
  127.         <?php endforeach; ?>
  128.  
  129.     </div>
  130.  
  131.     <?php endif; ?>
  132.  
  133.     <?php if (!empty($this->log['notice'])): ?>
  134.  
  135.     <div class="updated fade">
  136.  
  137.         <?php foreach ($this->log['notice'] as $notice): ?>
  138.             <p><?php echo $notice; ?></p>
  139.         <?php endforeach; ?>
  140.  
  141.     </div>
  142.  
  143.     <?php endif; ?>
  144. </div><!-- end wrap -->
  145.  
  146. <?php
  147.         // end messages HTML }}}
  148.  
  149.             $this->log = array();
  150.         }
  151.     }
  152.  
  153.     // Handle POST submission
  154.     function post() {
  155.         if (empty($_FILES['csv_import']['tmp_name'])) {
  156.             $this->log['error'][] = 'No file uploaded, aborting.';
  157.             $this->print_messages();
  158.             return;
  159.         }
  160.  
  161.         require_once 'File_CSV_DataSource/DataSource.php';
  162.  
  163.         $time_start = microtime(true);
  164.         $csv = new File_CSV_DataSource;
  165.         $file = $_FILES['csv_import']['tmp_name'];
  166.         $this->stripBOM($file);
  167.  
  168.         if (!$csv->load($file)) {
  169.             $this->log['error'][] = 'Failed to load file, aborting.';
  170.             $this->print_messages();
  171.             return;
  172.         }
  173.  
  174.         // pad shorter rows with empty values
  175.         $csv->symmetrize();
  176.  
  177.         $skipped = 0;
  178.         $imported = 0;
  179.         foreach ($csv->connect() as $csv_data) {
  180.             if ($post_id = $this->create_post($csv_data)) {
  181.                 $imported++;
  182.                 $this->create_custom_fields($post_id, $csv_data);
  183.             } else {
  184.                 $skipped++;
  185.             }
  186.         }
  187.  
  188.         if (file_exists($file)) {
  189.             @unlink($file);
  190.         }
  191.  
  192.         $exec_time = microtime(true) - $time_start;
  193.  
  194.         if ($skipped) {
  195.             $this->log['notice'][] = "<b>Skipped {$skipped} posts (most likely due to empty title, body and excerpt).</b>";
  196.         }
  197.         $this->log['notice'][] = sprintf("<b>Imported {$imported} posts in %.2f seconds.</b>", $exec_time);
  198.         $this->print_messages();
  199.     }
  200.  
  201.     function create_post($data) {
  202.         $status = $this->get_option('csv_importer_import_as_draft');
  203.         $type = $this->get_option('csv_importer_import_post_type');
  204.  
  205.         $defaults = array();
  206.         foreach ($this->reserved_fields as $k) {
  207.             $defaults[$k] = null;
  208.         }
  209.         $data = array_merge($defaults, $data);
  210.  
  211.         $new_post = array(
  212.             'post_title' => convert_chars($data['csv_post_title']),
  213.             'post_content' => wpautop(convert_chars($data['csv_post_post'])),
  214.             'post_status' => $status,
  215.             'post_type' => $type,
  216.             'post_date' => $this->parse_date($data),
  217.             'post_excerpt' => "<img style='float: left; padding: 5px;' src='{$data['custom_field_1']}'/>" . convert_chars($data['csv_post_excerpt']),
  218.             'post_name' => $data['csv_post_slug'],
  219.             'post_author' => $this->get_auth_id($data['csv_post_author']),
  220.         );
  221.  
  222.         if ('post' == $type) {
  223.             $new_post['tags_input'] = $data['csv_post_tags'];
  224.  
  225.             // setup categories before inserting
  226.             $cats = $this->create_categories($data);
  227.             $new_post['post_category'] = array_merge($cats['old'], $cats['new']);
  228.         }
  229.  
  230.         // create!
  231.         $id = wp_insert_post($new_post);
  232.  
  233.         if ('post' == $type && !$id) {
  234.             // cleanup new categories on failure
  235.             foreach ($cats['new'] as $c) {
  236.                 wp_delete_term($c, 'category');
  237.             }
  238.         }
  239.         return $id;
  240.     }
  241.  
  242.     // Lookup existing categories or create new ones
  243.     function create_categories($data) {
  244.         $opt_cat = $this->get_option('csv_importer_cat');
  245.         $ids = array(
  246.             'old' => array(),
  247.             'new' => array(),
  248.         );
  249.         $category_names = explode(',', $data['csv_post_categories']);
  250.         foreach ($category_names as $cat_name) {
  251.             $cat_name = trim($cat_name);
  252.  
  253.             if (!empty($cat_name)) {
  254.                 // Searching or creating the category
  255.                 if (is_numeric($cat_name)) {
  256.                     // it's an id, not a name
  257.                     if (null !== get_category($cat_name)) {
  258.                         $ids['old'][] = $cat_name;
  259.                     } else {
  260.                         $this->log['error'][] = "There is no category with id {$cat_name}.";
  261.                     }
  262.                 } else {
  263.                     $term = is_term($cat_name, 'category', $opt_cat);
  264.                     if (!$term) {
  265.                         $category = array(
  266.                             'cat_name' => $cat_name,
  267.                             'category_description' => '',
  268.                             'category_nicename' => sanitize_title($cat_name),
  269.                             'category_parent' => $opt_cat,
  270.                         );
  271.                         $cat_id = wp_insert_category($category);
  272.                         $ids['new'][] = $cat_id;
  273.                     } else {
  274.                         $ids['old'][] = $term['term_id'];
  275.                     }
  276.                 }
  277.             }
  278.         }
  279.         return $ids;
  280.     }
  281.  
  282.     function create_custom_fields($post_id, $data) {
  283.         foreach ($data as $k => $v) {
  284.             if ((array_search($k, $this->reserved_fields) === false) && $v != '' && $k != '') {
  285.                 add_post_meta($post_id, $k, $v);
  286.             }
  287.         }
  288.     }
  289.    
  290.     function get_auth_id($author) {
  291.         if (is_numeric($author)) return $author;
  292.         $author_data = get_userdatabylogin($author);
  293.         return (!$author_data) ? 0 : $author_data->ID;
  294.     }
  295.  
  296.     // Convert date in CSV file to 1999-12-31 23:52:00 format
  297.     function parse_date($data) {
  298.         $timestamp = strtotime($data['csv_post_date']);
  299.         if (false === $timestamp) {
  300.             return '';
  301.         } else {
  302.             return date('Y-m-d H:i:s', $timestamp);
  303.         }
  304.     }
  305.  
  306.     // delete BOM from UTF-8 file
  307.     function stripBOM($fname) {
  308.         $res = fopen($fname, 'rb');
  309.         if (false !== $res) {
  310.             $bytes = fread($res, 3);
  311.             if ($bytes == pack('CCC', 0xef, 0xbb, 0xbf)) {
  312.                 $this->log['notice'][] = 'Getting rid of byte order mark...';
  313.                 fclose($res);
  314.  
  315.                 $contents = file_get_contents($fname);
  316.                 if (false === $contents) {
  317.                     trigger_error('Failed to get file contents.', E_USER_WARNING);
  318.                 }
  319.                 $contents = substr($contents, 3);
  320.                 $success = file_put_contents($fname, $contents);
  321.                 if (false === $success) {
  322.                     trigger_error('Failed to put file contents.', E_USER_WARNING);
  323.                 }
  324.             } else {
  325.                 fclose($res);
  326.             }
  327.         } else {
  328.             $this->log['error'][] = 'Failed to open file, aborting.';
  329.         }
  330.     }
  331. }
  332.  
  333.  
  334. function csv_admin_menu() {
  335.     require_once ABSPATH . '/wp-admin/admin-functions.php';
  336.     $plugin = new CSVImporterPlugin;
  337.     add_management_page('edit.php', 'CSV Importer', 9, __FILE__, array($plugin, 'form'));
  338. }
  339.  
  340. add_action('admin_menu', 'csv_admin_menu');
  341.  
  342. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement