Make WordPress Core


Ignore:
Timestamp:
09/15/2005 11:37:54 PM (21 years ago)
Author:
ryan
Message:

Blogger importer from skeltoac. fixes #1680

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/wp-admin/import/blogger.php

    r2800 r2880  
     1<?php
     2
     3class Blogger_Import {
     4       
     5        var $import = array();
     6        var $template = '<br />
     7<br />
     8<br />
     9<MainPage>
     10<p>Are you looking for %title%? It is temporarily out of service. Please try again in an hour. Meanwhile, discover <a href="http://wordpress.org">a better blogging tool</a>.</p>
     11<BloggerArchives>
     12<a class="archive" href="<$BlogArchiveURL$>"><$BlogArchiveName$></a><br />
     13</BloggerArchives>
     14</MainPage>
     15<ArchivePage>
     16<Blogger><wordpresspost><$BlogItemDateTime$>|W|P|<$BlogItemAuthorNickname$>|W|P|<$BlogItemBody$>|W|P|<$BlogItemNumber$>|W|P|<$BlogItemTitle$>|W|P|<$BlogItemAuthorEmail$><BlogItemCommentsEnabled><BlogItemComments><wordpresscomment><$BlogCommentDateTime$>|W|P|<$BlogCommentAuthor$>|W|P|<$BlogCommentBody$></BlogItemComments></BlogItemCommentsEnabled></Blogger>
     17</ArchivePage>';
     18
     19        // Shows the welcome screen and the magic iframe.
     20        function greet() {
     21                echo '<div class="wrap">';
     22                echo '<h2>'.__('Import Blogger').'</h2>';
     23                _e("<p>Howdy! This importer allows you to import posts and comments from your Blogger account into your WordPress blog.</p>
     24<p>Before you get started, you may want to back up your Blogger template by copying and pasting it into a text file on your computer. This script has to modify your template and other Blogger settings so it can get your posts and comments. It should restore everything afterwards but if you have put a lot of work into your template, it would be a good idea to make your own backup first.</p>
     25<p>When you are ready to begin, enter your Blogger username and password below and click Start. Do not close this window until the process is complete.</p>");
     26                echo "<iframe src='admin.php?import=blogger&noheader=true' height='350px' width = '99%'></iframe>";
     27                echo "<p><a href='admin.php?import=blogger&amp;restart=true&amp;noheader=true' onclick='return confirm(\"This will delete everything saved by the Blogger importer. Are you sure you want to do this?\")'>Reset this importer</a></p>";
     28                echo '</div>';
     29        }
     30
     31        // Deletes saved data and redirect.
     32        function restart() {
     33                delete_option('import-blogger');
     34                header("Location: admin.php?import=blogger");
     35                die();
     36        }
     37
     38        // Generates a string that will make the page reload in a specified interval.
     39        function refresher($msec) {
     40                return "<html><head><script type='text/javascript'>window.onload=setInterval('window.location.reload()', $msec);</script>\n</head>\n<body>";
     41        }
     42
     43        // Returns associative array of code, header, cookies, body. Based on code from php.net.
     44        function parse_response($this_response) {
     45                // Split response into header and body sections
     46                list($response_headers, $response_body) = explode("\r\n\r\n", $this_response, 2);
     47                $response_header_lines = explode("\r\n", $response_headers);
     48
     49                // First line of headers is the HTTP response code
     50                $http_response_line = array_shift($response_header_lines);
     51                if(preg_match('@^HTTP/[0-9]\.[0-9] ([0-9]{3})@',$http_response_line, $matches)) { $response_code = $matches[1]; }
     52
     53                // put the rest of the headers in an array
     54                $response_header_array = array();
     55                foreach($response_header_lines as $header_line) {
     56                        list($header,$value) = explode(': ', $header_line, 2);
     57                        $response_header_array[$header] .= $value."\n";
     58                }
     59
     60                $cookie_array = array();
     61                $cookies = explode("\n", $response_header_array["Set-Cookie"]);
     62                foreach($cookies as $this_cookie) { array_push($cookie_array, "Cookie: ".$this_cookie); }
     63
     64                return array("code" => $response_code, "header" => $response_header_array, "cookies" => $cookie_array, "body" => $response_body);
     65        }
     66
     67        // Prints a form for the user to enter Blogger creds.
     68        function login_form($text='') {
     69                echo "<h1>Log in to Blogger</h1>\n<p>$text</p>\n";
     70                die("<form method='post' action='admin.php?import=blogger&amp;noheader=true&amp;step=0'><input type='text' name='user' /><input type='password' name='pass' /><input type='submit' value='Start' /></form>");
     71        }
     72
     73        // Sends creds to Blogger, returns the session cookies an array of headers.
     74        function login_blogger($user, $pass) {
     75                $_url = 'http://www.blogger.com/login.do';
     76                $params = "username=$user&password=$pass";
     77                $ch = curl_init();
     78                curl_setopt($ch, CURLOPT_POST,1);
     79                curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
     80                curl_setopt($ch, CURLOPT_URL,$_url);
     81                curl_setopt($ch, CURLOPT_USERAGENT, 'Developing Blogger Exporter');
     82                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
     83                curl_setopt($ch, CURLOPT_HEADER,1);
     84                curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
     85                $response = curl_exec ($ch);
     86
     87                $response = $this->parse_response($response);
     88
     89                return $response['cookies'];
     90        }
     91
     92        // Requests page from Blogger, returns the response array.
     93        function get_blogger($url, $header = '', $user=false, $pass=false) {
     94                $ch = curl_init();
     95                if ($user && $pass) curl_setopt($ch, CURLOPT_USERPWD,"{$user}:{$pass}");
     96                curl_setopt($ch, CURLOPT_URL,$url);
     97                curl_setopt($ch, CURLOPT_TIMEOUT, 10);
     98                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     99                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
     100                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
     101                curl_setopt($ch, CURLOPT_HEADER,1);
     102                if (is_array($header)) curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
     103                $response = curl_exec ($ch);
     104
     105                $response = $this->parse_response($response);
     106                $response['url'] = $url;
     107
     108                if (curl_errno($ch)) {
     109                        print curl_error($ch);
     110                } else {
     111                        curl_close($ch);
     112                }
     113
     114                return $response;
     115        }
     116
     117        // Posts data to Blogger, returns response array.
     118        function post_blogger($url, $header = false, $paramary = false, $parse=true) {
     119                $params = '';
     120                if ( is_array($paramary) ) {
     121                        foreach($paramary as $key=>$value)
     122                                if($key && $value != '')
     123                                        $params.=$key."=".urlencode(stripslashes($value))."&";
     124                }
     125                if ($user && $pass) $params .= "username=$user&password=$pass";
     126                $params = trim($params,'&');
     127        //echo addslashes(print_r(array('url'=>$url,'header'=>$header,'params'=>$params),1));
     128                $ch = curl_init();
     129                curl_setopt($ch, CURLOPT_POST,1);
     130                curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
     131                if ($user && $pass) curl_setopt($ch, CURLOPT_USERPWD,"{$user}:{$pass}");
     132                curl_setopt($ch, CURLOPT_URL,$url);
     133                curl_setopt($ch, CURLOPT_USERAGENT, 'Developing Blogger Exporter');
     134                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
     135                curl_setopt($ch, CURLOPT_HEADER,$parse);
     136                curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
     137                if ($header) curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
     138                $response = curl_exec ($ch);
     139       
     140                if ($parse) {
     141                        $response = $this->parse_response($response);
     142                        $response['url'] = $url;
     143                        return $response;
     144                }
     145       
     146                return $response;
     147        }
     148
     149        // Prints the list of blogs for import.
     150        function show_blogs() {
     151                global $import;
     152                echo "<h1>Selecting a Blog</h1>\n<ul>";
     153                foreach ( $this->import['blogs'] as $blog ) {
     154                        if (9 == $blog['nextstep']) $status = "100%";
     155                        elseif (8 == $blog['nextstep']) $status = "90%";
     156                        elseif (7 == $blog['nextstep']) $status = "82.5%";
     157                        elseif (6 == $blog['nextstep']) $status = "75%";
     158                        elseif (5 == $blog['nextstep']) $status = "57%";
     159                        elseif (4 == $blog['nextstep']) $status = "28%";
     160                        elseif (3 == $blog['nextstep']) $status = "14%";
     161                        else $status = "0%";
     162                        echo "\t<li><a href='admin.php?import=blogger&amp;noheader=true&amp;blog={$blog['id']}'>{$blog['title']}</a> $status</li>\n";
     163                }
     164                die("</ul>\n");
     165        }
     166
     167        // Publishes.
     168        function publish_blogger($i) {
     169                if ( ! $this->import['blogs'][$_GET['blog']]['publish'][$i] ) {
     170                        // First call. Start the publish process.
     171                        $paramary = array('blogID' => $_GET['blog'], 'all' => '1', 'republishAll' => 'Republish Entire Blog', 'publish' => '1', 'redirectUrl' => "/publish.do?blogID={$_GET['blog']}&inprogress=true");
     172                        $response = $this->post_blogger("http://www.blogger.com/publish.do?blogID={$_GET['blog']}", $this->import['cookies'], $paramary);
     173                        if ( $response['code'] == '302' ) {
     174                                $url = str_replace('publish.g', 'publish-body.g', $response['header']['Location']);
     175                                $this->import['blogs'][$_GET['blog']]['publish'][$i] = $url;
     176                                update_option('import-blogger', $this->import);
     177                                $response = $this->get_blogger($url, $this->import['cookies']);
     178                                if ( preg_match('#<p class="progressIndicator">.*</p>#U', $response['body'], $matches) ) {
     179                                        $progress = $matches[0];
     180                                        die($progress);
     181                                } else {
     182                                        echo "matches:<pre>" . print_r($matches,1) . "</pre>\n";
     183                                }
     184                        } else {
     185                                echo "<h1>Publish error: No 302</h1><p>Please tell the devs.</p><pre>" . addslashes(print_r($response,1)) . "</pre>\n";
     186                        }
     187                        die();
     188                } else {
     189                        // Subsequent call. Keep checking status until Blogger reports publish complete.
     190                        $url = $this->import['blogs'][$_GET['blog']]['publish'][$i];
     191                        $response = $this->get_blogger($url, $this->import['cookies']);
     192                        if ( preg_match('#<p class="progressIndicator">.*</p>#U', $response['body'], $matches) ) {
     193                                $progress = $matches[0];
     194                                if ( strstr($progress, '100%') )
     195                                        $this->set_next_step($i);
     196                                die($progress);
     197                        } else {
     198                                echo "<h1>Publish error: No matches</h1><p>Please tell the devs.</p><pre>" . print_r($matches,1) . "</pre>\n";
     199                        }
     200                }
     201        }
     202
     203        // Sets next step, saves options
     204        function set_next_step($step) {
     205                $this->import['blogs'][$_GET['blog']]['nextstep'] = $step;
     206                update_option('import-blogger', $this->import);
     207        }
     208       
     209        // Redirects to next step
     210        function do_next_step() {
     211                header("Location: admin.php?import=blogger&noheader=true&blog={$_GET['blog']}");
     212                die();
     213        }
     214
     215        // Step 0: Do Blogger login, get userid and blogid/title pairs.
     216        function do_login() {
     217                if ( ( ! $this->import['user'] && ! is_array($this->import['cookies']) ) ) {
     218                        // The user must provide a Blogger username and password.
     219                        if ( ! ( $_POST['user'] && $_POST['pass'] ) ) {
     220                                $this->login_form("Please log in using your Blogger credentials.");
     221                        }
     222               
     223                        // Try logging in. If we get an array of cookies back, we at least connected.           
     224                        $this->import['cookies'] = $this->login_blogger($_POST['user'], $_POST['pass']);
     225                        if ( !is_array( $this->import['cookies'] ) ) {
     226                                $this->login_form("Login failed. Please enter your credentials again.");
     227                        }
     228                       
     229                        // Save the password so we can log the browser in when it's time to publish.
     230                        $this->import['pass'] = $_POST['pass'];
     231                        $this->import['user'] = $_POST['user'];
     232
     233                        // Get the blog numbers so we can give the user a choice.
     234                        $response = $this->get_blogger('https://www.blogger.com/atom','',$_POST['user'],$_POST['pass']);
     235                        $blogger = $response['body'];
     236
     237                        // Save the userID if we got one from Blogger, otherwise re-login.
     238                        $useridary = array();
     239                        preg_match('#>(\d+)</userid#', $blogger, $useridary);
     240
     241                        if (! $this->import['userid'] = $useridary[1]) $this->login_form("Login failed. Please re-enter your username and password.");
     242                        unset($useridary);
     243
     244                        // Save the blogs
     245                        $blogsary = array();
     246                        preg_match_all('#/atom/(\d+)" rel\="service.feed" title="([^"]+)"#', $blogger, $blogsary);
     247                        if ( ! is_array( $blogsary[1] ) )
     248                                die('No blogs found for this user.');
     249                        $this->import['blogs'] = array();
     250                        foreach ( $blogsary[1] as $key => $id ) {
     251                                // Define the required Blogger options.
     252                                $blog_opts = array(
     253                                        'blog-options-basic' => false,
     254                                        'blog-formatting' => array('timeStampFormat' => '0', 'encoding'=>'UTF-8', 'convertLineBreaks'=>'false', 'floatAlignment'=>'false'),
     255                                        'blog-comments' => array('commentsTimeStampFormat' => '0'),
     256                                        'blog-options-archiving' => array('archiveFrequency' => 'm'),
     257                                        'template-edit' => array( 'templateText' =>  str_replace('%title%', $blogsary[2][$key], $this->template) ),
     258                                        'blog-publishing' => array('publishMode'=>'0', 'blogID' => "$id", 'subdomain' => mt_rand().mt_rand(), 'pingWeblogs' => 'false')
     259                                );
     260
     261                                // Build the blog options array template
     262                                foreach ($blog_opts as $blog_opt => $modify)
     263                                        $new_opts["$blog_opt"] = array('backup'=>false, 'modify' => $modify, 'error'=>false);
     264
     265                                $this->import['blogs']["$id"] = array(
     266                                        'id' => $id,
     267                                        'title' => $blogsary[2][$key],
     268                                        'options' => $new_opts,
     269                                        'url' => false,
     270                                        'publish_cookies' => false,
     271                                        'published' => false,
     272                                        'archives' => false,
     273                                        'newusers' => array(),
     274                                        'lump_authors' => false,
     275                                        'newusers' => 0,
     276                                        'nextstep' => 2
     277                                );
     278                        }
     279                        update_option('import-blogger', $this->import);
     280                        header("Location: admin.php?import=blogger&noheader=true&step=1");
     281                }
     282                die();
     283        }
     284
     285        // Step 1: Select one of the blogs belonging to the user logged in.
     286        function select_blog() {
     287                if ( is_array($this->import['blogs']) ) {
     288                        $this->show_blogs();
     289                        die();
     290                } else {
     291                        $this->restart();
     292                }
     293        }
     294
     295        // Step 2: Backup the Blogger options pages, updating some of them.
     296        function backup_settings() {
     297                $output.= "<h1>Backing up Blogger options</h1>\n";
     298                $form = false;
     299                foreach ($this->import['blogs'][$_GET['blog']]['options'] as $blog_opt => $optary) {
     300                        if ( $blog_opt == $_GET['form'] ) {
     301                                // Make sure not to overwrite any existing backups!
     302                                if ( $this->import['blogs'][$_GET['blog']]['options']["$blog_opt"]['backup'] ) continue;
     303
     304                                // Save the posted form data
     305                                $this->import['blogs'][$_GET['blog']]['options']["$blog_opt"]['backup'] = $_POST;
     306                                update_option('import-blogger',$this->import);
     307
     308                                // Post the modified form data to Blogger
     309                                if ( $optary['modify'] ) {
     310                                        $posturl = "http://www.blogger.com/{$blog_opt}.do";
     311                                        $headers = array_merge($this->import['blogs'][$_GET['blog']]['options']["$blog_opt"]['cookies'], $this->import['cookies']);
     312                                        switch ($blog_opt) {
     313                                        case 'blog-publishing':
     314                                                if ( $_POST['publishMode'] > 0 ) {
     315                                                        $response = $this->get_blogger("http://www.blogger.com/blog-publishing.g?blogID={$_GET['blog']}&publishMode=0", $headers);
     316                                                        if ( $response['code'] >= 400 )
     317                                                                die('<h2>Failed attempt to change publishMode:</h2><pre>' . addslashes(print_r($headers, 1)) . addslashes(print_r($response, 1)) . '</pre>');
     318                                                        $this->import['blogs'][$_GET['blog']]['url'] = 'http://' . $optary['modify']['subdomain'] . '.blogspot.com/';
     319                                                } else {
     320                                                        $this->import['blogs'][$_GET['blog']]['url'] = 'http://' . $_POST['subdomain'] . '.blogspot.com/';
     321                                                        update_option('import-blogger', $this->import);
     322                                                        continue 2;
     323                                                }
     324                                                $paramary = $optary['modify'];
     325                                                break;
     326                                        case 'template-edit':
     327                                                $this->import['blogs'][$_GET['blog']]['publish_cookies'] = $headers;
     328                                                update_option('import-blogger', $this->import);
     329                                        default:
     330                                                $paramary = array_merge($_POST, $optary['modify']);
     331                                        }
     332                                        $response = $this->post_blogger($posturl, $headers, $paramary);
     333                                        if ( $response['code'] >= 400 || strstr($response['body'], 'There are errors on this form') )
     334                                                die( "<p>Error on form submission. Refresh/Reload and click YES to resubmit.</p>" . addslashes(print_r($response, 1)));
     335                                        //header("Location: admin.php?import=blogger&noheader=true&step=2&blog={$_GET['blog']}");
     336                                        //die();
     337                                }
     338                                $output .= "<del><p>$blog_opt</p></del>\n";
     339                        } elseif ( is_array($this->import['blogs'][$_GET['blog']]['options']["$blog_opt"]['backup']) ) {
     340                                // This option set has already been backed up.
     341                                $output .= "<del><p>$blog_opt</p></del>\n";
     342                        } elseif ( ! $form ) {
     343                                // This option page needs to be downloaded and given to the browser for submission back to this script.
     344                                $response = $this->get_blogger("http://www.blogger.com/{$blog_opt}.g?blogID={$_GET['blog']}", $this->import['cookies']);
     345                                $this->import['blogs'][$_GET['blog']]['options']["$blog_opt"]['cookies'] = $response['cookies'];
     346                                update_option('import-blogger',$this->import);
     347                                $body = $response['body'];
     348                                $body = preg_replace("|\<!DOCTYPE.*\<body[^>]*>|ms","",$body);
     349                                $body = preg_replace("|/?{$blog_opt}.do|","admin.php?import=blogger&amp;noheader=true&amp;step=2&amp;blog={$_GET['blog']}&amp;form={$blog_opt}",$body);
     350                                $body = str_replace("name='submit'","name='supermit'",$body);
     351                                $body = str_replace('name="submit"','name="supermit"',$body);
     352                                $body = str_replace('</body>','',str_replace('</html>','',$body));
     353                                $form = "<div style='height:0px;width:0px;overflow:hidden;'>";
     354                                $form.= $body;
     355                                $form.= "</div><script type='text/javascript'>forms=document.getElementsByTagName('form');for(i=0;i<forms.length;i++){if(forms[i].action.search('{$blog_opt}')){forms[i].submit();break;}}</script>";
     356                                $output.= "<p><strong>$blog_opt</strong> in progress, please wait...</p>\n";
     357                        } else {
     358                                $output.= "<p>$blog_opt</p>\n";
     359                        }
     360                }
     361                if ( $form )
     362                        die($output . $form);
     363
     364                $this->set_next_step(3);
     365                $this->do_next_step();
     366        }
     367
     368        // Step 3: Publish with the new template and settings.
     369        function publish_blog() {
     370                echo $this->refresher(2400) . "<h1>Publishing with new template and options</h1>\n";
     371                $this->publish_blogger(5);
     372        }
     373
     374        // Step 4: Deprecated. :-D
     375
     376        // Step 5: Get the archive URLs from the new blog.
     377        function get_archive_urls() {
     378                $bloghtml = file($this->import['blogs'][$_GET['blog']]['url']);
     379                if (! is_array($bloghtml) ) die('Trouble connecting to your blog. Try reloading this page.');
     380                preg_match_all('#<a class="archive" href="([^"]*)"#', implode('',$bloghtml), $archives);
     381                if ( count($archives[1]) == 0 ) die ("That's odd. No archives were found. Does <a href='{$import['blogs'][$_GET['blog']]['url']}'>your blog</a> say Temporary Template?");
     382                foreach ($archives[1] as $archive) {
     383                        $this->import['blogs'][$_GET['blog']]['archives'][$archive] = false;
     384                }
     385                $this->set_next_step(6);
     386                $this->do_next_step();
     387        }
     388
     389        // Step 6: Get each monthly archive, import it, mark it done.
     390        function get_archive() {
     391                global $wpdb;
     392                $output = "<h2>Importing Blogger archives into WordPress</h2>\n";
     393                $did_one = false;
     394                foreach ( $this->import['blogs'][$_GET['blog']]['archives'] as $url => $status ) {
     395                        $archivename = substr(basename($url),0,7);
     396                        if ( $status || $did_one ) {
     397                                $foo = 'bar';
     398                                // Do nothing.
     399                        } else {
     400                                // Import the selected month
     401                                $postcount = 0;
     402                                $skippedpostcount = 0;
     403                                $commentcount = 0;
     404                                $skippedcommentcount = 0;
     405                                $status = '';
     406                                $archive = implode('',file($url));
     407       
     408                                $posts = explode('<wordpresspost>', $archive);
     409                                for ($i = 1; $i < count($posts); $i = $i + 1) {
     410                                        $postparts = explode('<wordpresscomment>', $posts[$i]);
     411                                        $postinfo = explode('|W|P|', $postparts[0]);
     412                                        $post_date = $postinfo[0];
     413                                        $post_content = $postinfo[2];
     414                                        // Don't try to re-use the original numbers
     415                                        // because the new, longer numbers are too
     416                                        // big to handle as ints.
     417                                        //$post_number = $postinfo[3];
     418                                        $post_title = ( $postinfo[4] != '' ) ? $postinfo[4] : $postinfo[3];
     419                                        $post_author = trim($wpdb->escape($postinfo[1]));
     420                                        $post_author_name = trim(addslashes($postinfo[1]));
     421                                        $post_author_email = $postinfo[5] ? $postinfo[5] : 'no@email.com';
     422       
     423                                        if ( $this->import['blogs'][$_GET['blog']]['lump_authors'] ) {
     424                                                // Ignore Blogger authors. Use the current user_ID for all posts imported.
     425                                                $post_author = $GLOBALS['user_ID']; // For WPMU only. Assume all posts belong to the current user.
     426                                        } else {
     427                                                // Add a user for each new author encountered.
     428                                                if (! username_exists($post_author_name) ) {
     429                                                        $user_joindate = '1979-06-06 00:41:00'; // that's my birthdate (gmt+1) - I could choose any other date. You could change the date too. Just remember the year must be >=1970 or the world would just randomly fall on your head (everything might look fine, and then blam! major headache!)
     430                                                        $user_login = $wpdb->escape($post_author_name);
     431                                                        $pass1 = $wpdb->escape('password');
     432                                                        $user_email = $wpdb->escape($post_author_email);
     433                                                        $user_url = $wpdb->escape('');
     434                                                        $user_joindate = $wpdb->escape($user_joindate);
     435                                                        $user_password = substr(md5(uniqid(microtime())), 0, 6);
     436                                                        $result = wp_create_user( $user_login, $user_password, $user_email );
     437                                                        $status.= "Registered user <strong>$user_login</strong>. ";
     438                                                        ++$this->import['blogs'][$_GET['blog']]['newusers'];
     439                                                }
     440                                                $userdata = get_userdatabylogin( $post_author_name );
     441                                                $post_author = $userdata->ID;
     442                                        }
     443                                        $post_date = explode(' ', $post_date);
     444                                        $post_date_Ymd = explode('/', $post_date[0]);
     445                                        $postyear = $post_date_Ymd[2];
     446                                        $postmonth = zeroise($post_date_Ymd[0], 2);
     447                                        $postday = zeroise($post_date_Ymd[1], 2);
     448                                        $post_date_His = explode(':', $post_date[1]);
     449                                        $posthour = zeroise($post_date_His[0], 2);
     450                                        $postminute = zeroise($post_date_His[1], 2);
     451                                        $postsecond = zeroise($post_date_His[2], 2);
     452       
     453                                        if (($post_date[2] == 'PM') && ($posthour != '12'))
     454                                                $posthour = $posthour + 12;
     455                                        else if (($post_date[2] == 'AM') && ($posthour == '12'))
     456                                                $posthour = '00';
     457       
     458                                        $post_date = "$postyear-$postmonth-$postday $posthour:$postminute:$postsecond";
     459       
     460                                        $post_content = addslashes($post_content);
     461                                        $post_content = str_replace('<br>', '<br />', $post_content); // the XHTML touch... ;)
     462       
     463                                        $post_title = addslashes($post_title);
     464                       
     465                                        $post_status = 'publish';
     466       
     467                                        if ( post_exists($post_title, '', $post_date) ) {
     468                                                $skippedpostcount++;
     469                                                $comment_post_ID = $dupcheck[0]['ID'];
     470                                        } else {
     471                                                $post_array = compact('post_author', 'post_content', 'post_title', 'post_category', 'post_author', 'post_date', 'post_status');
     472                                                $comment_post_ID = wp_insert_post($post_array);
     473                                        }
     474                                       
     475                                        // Import any comments attached to this post.
     476                                        if ($postparts[1]) :
     477                                        for ($j = 1; $j < count($postparts); $j = $j + 1) {
     478                                                $commentinfo = explode('|W|P|', $postparts[$j]);
     479                                                $comment_date = explode(' ', $commentinfo[0]);
     480                                                $comment_date_Ymd = explode('/', $comment_date[0]);
     481                                                $commentyear = $comment_date_Ymd[2];
     482                                                $commentmonth = zeroise($comment_date_Ymd[0], 2);
     483                                                $commentday = zeroise($comment_date_Ymd[1], 2);
     484                                                $comment_date_His = explode(':', $comment_date[1]);
     485                                                $commenthour = zeroise($comment_date_His[0], 2);
     486                                                $commentminute = zeroise($comment_date_His[1], 2);
     487                                                $commentsecond = '00';
     488                                                if (($comment_date[2] == 'PM') && ($commenthour != '12'))
     489                                                        $commenthour = $commenthour + 12;
     490                                                else if (($comment_date[2] == 'AM') && ($commenthour == '12'))
     491                                                        $commenthour = '00';
     492                                                $comment_date = "$commentyear-$commentmonth-$commentday $commenthour:$commentminute:$commentsecond";
     493                                                $comment_author = addslashes(strip_tags(html_entity_decode($commentinfo[1]))); // Believe it or not, Blogger allows a user to call himself "Mr. Hell's Kitchen" which, as a string, really confuses SQL.
     494                                                if ( strpos($commentinfo[1], 'a href') ) {
     495                                                        $comment_author_parts = explode('&quot;', htmlentities($commentinfo[1]));
     496                                                        $comment_author_url = $comment_author_parts[1];
     497                                                } else $comment_author_url = '';
     498                                                $comment_content = addslashes($commentinfo[2]);
     499                                                $comment_content = str_replace('<br>', '<br />', $comment_content);
     500                                                if ( $comment_post_ID == comment_exists($comment_author, $comment_date) ) {
     501                                                        $skippedcommentcount++;
     502                                                } else {
     503                                                        $result = $wpdb->query("
     504                                                        INSERT INTO $wpdb->comments
     505                                                        (comment_post_ID,comment_author,comment_author_url,comment_date,comment_content)
     506                                                        VALUES
     507                                                                ('$comment_post_ID','$comment_author','$comment_author_url','$comment_date','$comment_content')
     508                                                ");
     509                                                }
     510                                                $commentcount++;
     511                                        }
     512                                        endif;
     513                                        $postcount++;
     514                                }
     515                                $status = "$postcount post(s) parsed, $skippedpostcount skipped... $commentcount comment(s) parsed, $skippedcommentcount skipped... <strong>Done</strong>";
     516                                $import = $this->import;
     517                                $import['blogs'][$_GET['blog']]['archives']["$url"] = $status;
     518                                update_option('import-blogger', $import);
     519                                $did_one = true;
     520                        }
     521                        $output.= "<p>$archivename $status</p>\n";
     522                }
     523                if ( ! $did_one )
     524                        $this->set_next_step(7);
     525                die( $this->refresher(5000) . $output );
     526        }
     527
     528        // Step 7: Restore the backed-up settings to Blogger
     529        function restore_settings() {
     530                $output = "<h1>Restoring your Blogger options</h1>\n";
     531                $did_one = false;
     532                foreach ( $this->import['blogs'][$_GET['blog']]['options'] as $blog_opt => $optary ) {
     533                        if ( $did_one ) {
     534                                $output .= "<p>$blog_opt</p>\n";
     535                        } elseif ( $optary['restored'] ) {
     536                                $output .= "<p><del>$blog_opt</del></p>\n";
     537                        } elseif ( ! $optary['modify'] ) {
     538                                $output .= "<p><del>$blog_opt</del></p>\n";
     539                        } else {
     540                                $posturl = "http://www.blogger.com/{$blog_opt}.do";
     541                                $headers = array_merge($this->import['blogs'][$_GET['blog']]['options']["$blog_opt"]['cookies'], $this->import['cookies']);
     542                                if ( 'blog-publishing' == $blog_opt) {
     543                                        if ( $optary['backup']['publishMode'] > 0 ) {
     544                                                $response = $this->get_blogger("http://www.blogger.com/blog-publishing.g?blogID={$_GET['blog']}&publishMode={$optary['backup']['publishMode']}", $headers);
     545                                                if ( $response['code'] >= 400 )
     546                                                        die('<h1>Error restoring publishMode.</h1><p>Please tell the devs.</p>' . addslashes(print_r($response, 1)) );
     547                                        }
     548                                }
     549                                if ( $optary['backup'] != $optary['modify'] ) {
     550                                        $response = $this->post_blogger($posturl, $headers, $optary['backup']);
     551                                        if ( $response['code'] >= 400 || strstr($response['body'], 'There are errors on this form') )
     552                                                die( "<h1>Error on form submission in Step 7.</h1><p>Please tell the devs.</p>" . addslashes(print_r($response, 1)));
     553                                }
     554                                $this->import['blogs'][$_GET['blog']]['options']["$blog_opt"]['restored'] = true;
     555                                update_option('import-blogger', $this->import);
     556                                $did_one = true;
     557                                $output .= "<p><strong>$blog_opt</strong> in progress. Please wait...";
     558                        }
     559                }
     560
     561                if ( $did_one ) {
     562                        die( $this->refresher(1000) . $output );
     563                }
     564
     565                $this->set_next_step(8);
     566                $this->do_next_step();
     567        }
     568
     569        // Step 8: Republish, all back to normal
     570        function republish_blog() {
     571                echo $this->refresher(2400) . "<h1>Publishing with original template and options</h1>\n";
     572                $this->publish_blogger(9);
     573        }
     574
     575        // Step 9: Congratulate the user
     576        function congrats() {
     577                echo "<h1>Congratulations!</h1>
     578<p>Now that you have imported your Blogger blog into WordPress, what are you going to do? Here are some suggestions:</p>
     579<ul>
     580<li>That was hard work! Take a break.</li>
     581";
     582                if ( count($this->import['blogs']) > 1 )
     583                        echo "<li>In case you haven't done it already, you can import the posts from any other blogs you may have:" . $this->show_blogs() . "</li>\n";
     584                if ( $n = count($this->import['blogs'][$_GET['blog']]['newusers']) )
     585                        echo "<li>Since we had to create $n new users, you probably want to go to <a href='users.php' target='_parent'>Authors & Users</a>, where you can give them new passwords or delete them. If you want to make all of the imported posts yours, you will be given that option when you delete the new authors.</li>\n";
     586               
     587                echo "\n<ul>";
     588        }
     589
     590        // Figures out what to do, then does it.
     591        function start() {
     592                if ( $_GET['restart'] == 'true' ) {
     593                        $this->restart();
     594                }
     595               
     596                if ( isset($_GET['noheader']) ) {
     597                        $this->import = get_settings('import-blogger');
     598
     599                        if ( isset($_GET['step']) ) {
     600                                $step = (int) $_GET['step'];
     601                        } elseif ( isset($_GET['blog']) ) {
     602                                $step = $this->import['blogs'][$_GET['blog']]['nextstep'];
     603                        } elseif ( is_array($this->import['blogs']) ) {
     604                                $step = 1;
     605                        } else {
     606                                $step = 0;
     607                        }
     608                        switch ($step) {
     609                                case 0 :
     610                                        $this->do_login();
     611                                        break;
     612                                case 1 :
     613                                        $this->select_blog();
     614                                        break;
     615                                case 2 :
     616                                        $this->backup_settings();
     617                                        break;
     618                                case 3 :
     619                                        $this->publish_blog();
     620                                        break;
     621                                case 4 :
     622                                case 5 :
     623                                        $this->get_archive_urls();
     624                                        break;
     625                                case 6 :
     626                                        $this->get_archive();
     627                                        break;
     628                                case 7 :
     629                                        $this->restore_settings();
     630                                        break;
     631                                case 8 :
     632                                        $this->republish_blog();
     633                                        break;
     634                                case 9 :
     635                                        $this->congrats();
     636                                        break;
     637                        }
     638
     639                        die;
     640
     641                } else {
     642                        $this->greet();
     643                }
     644        }
     645
     646        function Blogger_Import() {
     647                // This space intentionally left blank.
     648        }
     649}
     650
     651$blogger_import = new Blogger_Import();
     652
     653register_importer('blogger', 'Blogger', __('Import posts and comments from a Blogger account'), array ($blogger_import, 'start'));
     654?>
Note: See TracChangeset for help on using the changeset viewer.