<?php
/**
 * Import class for Tumblr blogs
 *
 * @author Martin Jansen (http://martinjansen.com/)
 */
class Tumblr_Import {

    function header() {
        echo "<div class=\"wrap\">";
        echo "<h2>" . __("Import Tumblr") . "</h2>";
    }

    function footer() {
        echo "</div>";
    }

    function greet() {
        echo "<div class=\"narrow\">";
        echo "<p>" . __("Howdy! Tell us your Tumblr blog name and we&#8217;ll import the posts into this blog.") . "</p>";

        echo "<form action=\"admin.php?import=tumblr&amp;step=1\" method=\"post\">";
        wp_nonce_field("import-tumblr");
        echo "<table class=\"form-table\">";
        printf("<tr><th><label for=\"blogname\">%s</label></th><td><input type=\"text\" name=\"blogname\" id=\"blogname\" /> (<code>http://&lt;blogname&gt;.tumblr.com/</code>)</td></tr>", __("Tumblr blog name:"));
        echo "</table>";
        echo "<p class=\"submit\"><input type=\"submit\" name=\"submit\" value=\"" . attribute_escape(__("Import")) . "\" /></p>";
        echo "</form>";
    }

    function import_posts($start) {
        global $current_user;

        $url = "http://" . $_POST['blogname'] . ".tumblr.com/api/read?start=" . $start . "&num=50";

        $contents = @file_get_contents($url);
        if ($contents === false) {
            _e("ups, something is wrong with the response from Tumblr.");
            return false;
        }

        /* At the moment we are using SimpleXML here, which requires PHP 5.
         * This should probably be changed to something that is supported in
         * PHP 4 as well.
         */
        $xml = @simplexml_load_string($contents);

        if ($xml === false) {
            _e("ups, something is wrong with the response from Tumblr.");
            return false;
        }
        
        $post_author = $current_user->ID;
        $post_status = "publish";
        
        foreach ($xml->posts->post as $post) {
            echo "<li>";
            $post_title = $post_content = "";

            $post_date = date("Y-m-d H:i:s", strtotime($post['date']));
            $post_date_gmt = gmdate("Y-m-d H:i:s", strtotime($post['date-gmt']));
            
            switch ($post['type']) {
                case "regular" :
                    $post_title = (string)$post->{"regular-title"};
                    $post_content = (string)$post->{"regular-body"};

                    break;
                    
                case "link" :
                    $post_title = (string)$post->{"link-text"};
                    $post_content = sprintf("<a href=\"%s\">%s</a>",
                        (string)$post->{"link-url"},
                        (string)$post->{"link-text"});
                    $post_content .= "<p>" . (string)$post->{"link-description"} . "</p>";

                    break;
                    
                case "quote" :
                    $post_content = "<blockquote>" . (string)$post->{"quote-text"} . "</blockquote>";
                    $post_content .= "<p>" . (string)$post->{"quote-source"} . "</p>";
                    
                    break;
                    
                case "photo" :
                    $upload_dir = wp_upload_dir();
                    if (get_option("uploads_use_yearmonth_folders")) {
                        $dir = sprintf("%s/%02d/%02d",
                            $upload_dir['basedir'],
                            date("Y", strtotime($post['date'])),
                            date("m", strtotime($post['date'])));
                        $subdir = sprintf("/%s/%02d/%02d/",
                            get_option("upload_path"),
                            date("Y", strtotime($post['date'])),
                            date("m", strtotime($post['date'])));
                    } else {
                        $dir = $upload_dir['basedir'];
                        $subdir = get_option("upload_path") . "/" . $upload_dir['subdir'];
                    }
                    
                    list($url) = $post->xpath("photo-url[@max-width=500]");
                    list($width, $height) = getimagesize($url);
                    
                    if (!is_dir($dir)) {
                        mkdir($dir, 0777, true);
                    }
                    file_put_contents($dir . "/" . basename($url), fopen($url, "r"));
                    
                    $post_content = sprintf("<img src=\"%s\" alt=\"\" width=\"%d\" height=\"%d\" />",
                        $subdir . basename($url),
                        $width,
                        $height);
                    $post_content .= "<p>" . (string)$post->{"photo-caption"} . "</p>";

                    break;
  
                case "conversation" :
                    /* We are making the assumption here that people want
                     * their conversations to be renderer as an unorderer list.
                     */
                    $classes = array("even", "odd");
                    $post_content = "<ul class=\"conversation\">\n";
                    foreach ($post->{"conversation-line"} as $line) {
                        $post_content .= "<li class=\"" . $classes[++$i % 2] . "\"><span class=\"label\">" . $line['label'] . "</span> " . (string)$line . "</li>\n";
                    }
                    $post_content .= "</ul>\n";
                    break;
                    
                case "video" :
                    $post_content = (string)$post->{"video-player"} . (string)$post->{"video-caption"};
                    break;
                    
                case "audio" :
                    $post_content = (string)$post->{"audio-player"} . (string)$post->{"audio-caption"};
                    break;

                default :
                    printf(__("Found a <em>%s</em> post that we cannot process yet."), stripslashes($post['type']));
                    continue 2;
                    break;
            }

            $postdata = compact("post_author", "post_date", "post_date_gmt", "post_content", "post_title", "post_status");

            $post_id = $this->insert_artifact($postdata);
            if (!$post_id) {
                _e("Unable to save post");
            } else {
                add_post_meta($post_id, "imported_from", "tumblr", true);
                add_post_meta($post_id, "tumblr_type", (string)$post['type'], true);
                add_post_meta($post_id, "tumblr_id", (string)$post['id'], true);
                add_post_meta($post_id, "tumblr_url", (string)$post['url'], true);
            }

            echo "</li>";
        }
        
        if ((int)$xml->posts['total'] > ($start + 1) * 50) {
            $this->import_posts(($start + 1) * 50);
        }
    }

    function insert_artifact(&$postdata) {
        global $wpdb;
        
        if ($post_id = post_exists($postdata['post_title'], $postdata['post_content'], $postdata['post_date'])) {
            printf(__("Post <em>%s</em> already exists."), stripslashes($postdata['post_title']));

            return -1;
        } else {
            $postdata['post_title']   = $wpdb->escape($postdata['post_title']);
            $postdata['post_content'] = $wpdb->escape($postdata['post_content']);

            printf(__("Importing post <em>%s</em>..."), stripslashes($postdata['post_title']));

            $post_id = wp_insert_post($postdata);
            if (is_wp_error($post_id)) {
                return false;
            }

            return $post_id;
        }
    }
    
    function import() {
        echo "<ol>";
        $result = $this->import_posts(0);
        echo "</ol>";
        if (is_wp_error($result)) {
            return $result;
        }
        do_action("import_done", "tumblr");

        echo "<h3>";
        printf(__("All done. <a href=\"%s\">Have fun!</a>"), get_option("home"));
        echo "</h3>";
    }

    function dispatch() {
        $step = (!empty($_GET['step'])? (int)$_GET['step'] : 0);

        $this->header();

        switch ($step) {
            case 0 :
                $this->greet();
                break;

            case 1 :
                check_admin_referer("import-tumblr");
                $result = $this->import();
                if (is_wp_error($result)) {
                    echo $result->get_error_message();
                }
                break;
        }

        $this->footer();
    }
}

$tumblr_import = new Tumblr_Import();

register_importer("tumblr", __("Tumblr"), __("Import posts from a Tumblr blog."), array($tumblr_import, "dispatch"));
