<?php

// Only change these if you didn't put the pivot directory
// inside the wordpress directory
$pivotdir "../../pivot";
$dbdir "$pivotdir/db/";

// Stop changing stuff unless you really know what you're doing

// Start session and link it to a shorthand var
session_start();
//unset($_SESSION['importpivot']);
if (!isset($_SESSION['importpivot'])) $_SESSION['importpivot'] = new stdClass();
$s = &$_SESSION['importpivot'];

// Check for config file
if (!file_exists('../wp-config.php')) die("There doesn't seem to be a wp-config.php file. You must install WordPress before you import any entries.");
require(
'../wp-config.php');
require (
'upgrade-functions.php');
$s->wpusers $wpdb->get_results("SELECT ID, user_login FROM $wpdb->users");
$s->wpcats $wpdb->get_results("SELECT cat_ID, cat_name FROM $wpdb->categories");

$step $_GET['step'];
if (!
$step$step 0;

switch (
$step) {
    case 
"0":
        
_header();
?>
    <p>This script imports your entries from Pivot into WordPress, preserving as much info as we humanly can.</p>
    <p>The import will be done in three steps:</p>
    <ol>
        <li>Gather user info</li>
        <li>Gather category info</li>
        <li>Import the content</li>
    </ol>
    <p>Before we continue, make sure that you've got the <code>pivot/</code> directory (containing at least the <code>db/</code> directory structure and the <code>pv_cfg_settings.php</code> file) inside your <code>wordpress/</code> directory. If it's not there, please edit this file (<code>import-pivot.php</code>) before continuing!</p>
    <p>In fact, it's so important, I'll check right now and complain if anything is missing...</p>
<?php
        
if (!file_exists($pivotdir) || !file_exists($dbdir) || !file_exists("$pivotdir/pv_cfg_settings.php")) {
            die(
'<em>Danger, Will Robinson!<br />Please make sure that you move or copy the pivot directory structure inside wordpress, or edit this file and try again.</em>');
        } else {
?>
    <p>All right sparky! The files are there, we're ready to <a href="import-pivot.php?step=1">rock and roll!</a></p>
<?php
        _footer
();
        }
    break;

    case 
"1"/* Handle users */
        
_header();
        if (!
$_POST['matched']) {
?>
    <p>Allright, this is what we'll do: I'm going to show you a list of active users that I've found. You can tell me what I should do with every user: either match it to an existing WordPress user, or create a new WordPress user (keeping the Pivot username and password).</p>
    <p>At installation time, WordPress creates a user named <strong>admin</strong> with full privileges; you should map your Administration-user in Pivot to this user. You can always grant a higher userlevel to existing users after we're done importing.</p>
    <p>Also, you cannot create a new WordPress users from a Pivot user if the Pivot username already exists in WordPress. If I encounter two matching usernames, I'll pre-select the right WordPress users for you.</p>
    <form action="import-pivot.php?step=1" method="post"><input type="hidden" name="matched" value="1" />
    
    <ul>
<?php
        $wpuseroptions 
= array();
        
$s->pivotusers getPivotUsers();
        
        foreach (
$s->pivotusers as $user) {
?>
        <li>
            Match Pivot user '<?php echo $user->username?>' to
            <select name="matches[<?php echo $user->username?>]"><?php
        
echo "<option value=\"0\">a new user</option>";
        foreach (
$s->wpusers as $wpuser) {
            
$match = ($wpuser->user_login == $user->username) ? true false;
            echo 
"<option value=\"$wpuser->ID\"";
            if (
$match) echo ' selected="selected"';
            echo 
">WordPress user '$wpuser->user_login'</option>";
        }
?></select>
        </li>
<?php /* end foreach */ ?>
    </ul>
    <p>When you're done matching, <input type="submit" value="Continue to step 2" /></p>
    </form>
    <p><em>If I encounter more usernames during the import (which is possible, since Pivot lets you delete users while keeping their posts), I'll create new WordPress users to match; those users will not be able to log in or post to your weblog until you promote them and give them a sensible password.</em></p>

<?php
        
} else {

?>
    <p>If you get any error messages (especially database errors), you might want to <a href="import-pivot.php?step=1">go back</a> to the selection list and try the matching process again.</p>
<?php
            
// handle matches
            
foreach ($_POST['matches'] as $match => $id) {
                if (
$id 0) {
                    
$s->pivotusers[$match]->wp_id $id;
                    
//echo "Match! '$match' is '$id'<br />\n";
                
} else {
                    echo 
"<p>Trying to insert user $match...<br />";
                    
$id $s->pivotusers[$match]->wp_id insertuser($s->pivotusers[$match]);
                    
//echo "Insert! '$match' is '$id'<br />\n";
                    
if ($id) echo "...Succes!";
                    else echo 
"...seems to have failed!";
                    
                    echo 
"</p>\n";
                }
            }
?>
    <p>If there were no errors, we'll continue to the next step: importing the posts. Whenever you think you're ready, take a deap breath, buckle up, brace yourself, cover your ears, pet your lucky rabbit paw, and <a href="import-pivot.php?step=2"><b>let her rip</b></a>!</p>
<?php
        
// endif matched
        
    
break;
    
    case 
"2"/* Gathered all info, import them posts! */
        
_header();
?>
    <p>I'm going to import the posts, which might take a while. If you receive a timeout message, just hit the refresh / reload button in your browser, and I should be able to continue where I was interrupted.</p>
    
    <ul>
<?php
        $s
->handled_dirs = array();
        
$handled_count 0;
        
$dbdir_arr = array();
        
$i 0$j 0;
        if (
is_dir($dbdir)) {
            
$handle opendir($dbdir); 
            while (
false !== ($arcdir readdir($handle))) { 
                if (
preg_match('/^standard-/'$arcdir) && is_dir($dbdir $arcdir) && !in_array($arcdir$s->handled_dirs)) { 
                    
$i++;
                    
$handle2 opendir($dbdir.$arcdir);
                    while (
false !== ($file readdir($handle2))) {
                        if (
preg_match('/^\d+/'$file)) {
                            
ProcessPost(parseFile($dbdir $arcdir '/' $file));
                        }
                        
$j++;

                        
$handled_count++;
                        if (
$handled_count 20 == 0_scrollDown();
                    }
                    
closedir($handle2);
                    
$s->handled_dirs[] = $arcdir;
                }
            }
            
closedir($handle); 
        }
?>
    </ul>
    
    <p>We're done!</p>
<?
        
        
//print_r(parseFile("$dbdir/standard-00000/00008.php"));
    
break;

    case 
"s":
        echo 
'<pre>' print_r($s,true) . '</pre>';
        break;

}

function 
getPivotUsers () {
    global 
$pivotdir;

    
$config file("$pivotdir/pv_cfg_settings.php");
    foreach (
$config as $line) {
        if (
preg_match('/^user-([^!]+)!(.*)$/'$line$m)) {
            
$username = &$m[1];
            
$data explode('|-|'$m[2]);
            foreach (
$data as $datapart) {
                list(
$key,$val) = explode('|'$datapart);
                
$users[$username]->$key $val;
            }
        }
    }
    return 
$users;
}

function 
insertuser($user) {
    global 
$wpdb$s;
    
    
// if the user is there, return the ID
    
foreach ($s->wpusers as $wpuser) {
        if (
$wpuser->user_login == $user->username) {
            return 
$wpuser->ID;
        }
    }
    
    
// new user
    
$user_nice $user->nick sanitize_title($user->nick) : sanitize_title($user->username);
    
$idmode = ($user->nick && ($user->nick != $user->username)) ? 'nickname' 'login';
    
$now gmdate('Y-m-d H:i:s');
    
$level = isset($user->userlevel) ? $user->userlevel 0;
    
$level = ($level == 4) ? 10 1;
    
$wpdb->query("INSERT INTO $wpdb->users
        (user_login, user_pass, user_email, user_nickname, user_nicename,
        user_registered, user_level, user_idmode)
        VALUES
        ('$user->username', '$user->pass', '$user->email', '$user->nick', '$user_nice',
        '$now', $level, '$idmode')
    "
);
    
// update user cache
    
$s->wpusers $wpdb->get_results("SELECT ID,user_login FROM $wpdb->users");
    
    
// return
    
return $wpdb->insert_id;
}

function 
insertcategory ($category) {
    global 
$wpdb$s;

    
// if the category is there, just return the id and be done with it
    
foreach ($s->wpcats as $wpcat) {
        if (
$wpcat->cat_name == $category) return $wpcat->cat_ID;
    }

    
// Not there, insert and return insert_id
    
$cat_nicename sanitize_title($category);
    
$wpdb->query("INSERT INTO $wpdb->categories
        (cat_name, category_nicename, category_parent)
        VALUES ('$category', '$cat_nicename', 0)
    "
);
    
$s->wpcats $wpdb->get_results("SELECT cat_ID, cat_name FROM $wpdb->categories");

    
// return
    
return $wpdb->insert_id;
}
    

function 
parseFile ($theFile) {
    
$serialized_data trim(implode(""file($theFile)));
    
$serialized_data str_replace("<?php /* pivot */ die(); ?>"""$serialized_data);

    if (@
$data unserialize($serialized_data)) {
        return 
$data;
    } else {
        
$temp_serialized_data preg_replace("/\r\n/""\n"$serialized_data);
        if (@
$data unserialize($temp_serialized_data)) {
            return 
$data;
        } else {
            
$temp_serialized_data preg_replace("/\n/""\r\n"$serialized_data);
            if (@
$data unserialize($temp_serialized_data)) {
                return 
$data;
            } else {
                return 
false;
            }

        }
    }
}

function 
ProcessPost($theFile) {
    global 
$wpdb;
    
/*
        date_gmt
        post_content
        post_title
        post_category
        post_excerpt
        post_status (publish)
        comment_status (open)
        ping_status (open)
        post_password
        post_name
        to_ping
        pinged
        post_modified
        post_modified_gmt
        post_content_filtered
        post_parent
        guid
        menu_order
    */

    // date
    
$post_date $theFile['date'];
    
$post_date explode('-'$post_date);
    
$post_date_gmt date('Y-m-d H:i:s'mktime($post_date[3], $post_date[4], 0$post_date[1], $post_date[2], $post_date[0]) - 3600);
    
$post_date date('Y-m-d H:i:s'mktime($post_date[3], $post_date[4], 0$post_date[1], $post_date[2], $post_date[0]));

    
// body
    
$post_content addslashes($theFile['introduction']);
    if (
$theFile['body']) $post_content .= "\n\n<!--more-->" addslashes($theFile['body']);
    
    
// excerpt
    
$post_excerpt '';
    if (
$theFile['body'] && $theFile['introduction']) $post_excerpt addslashes($theFile['introduction']);
    
    
// title
    
$post_title addslashes($theFile['title']);
    
$post_name sanitize_title($post_title);

    
// author
    
if ($s->pivotusers[($theFile['user'])]->wp_id) {
        
$post_author $s->pivotusers[($theFile['user'])]->wp_id;
    } else {
        
// user not there, insert him
        // whip up a fake user first
        
$user->username $theFile['user'];
        
$user->pass '***';
        
$user->level 0;
        
        
// insert the user, add him to the list
        
$post_author insertuser($user);
        
$s->pivotusers[($theFile['user'])]->wp_id $post_author;
    }
    
    
// status
    
if ($theFile['status'] == 'hold') {
        
$status 'draft';
    } else {
        
$status 'publish';
    }
    
    
// Check
    
if (!$wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_title = '$post_title' AND post_date = '$post_date'")) {
        
// not in there
        
$query = ("INSERT INTO $wpdb->posts (
            post_author, post_date, post_date_gmt, post_content, post_title, post_excerpt,  post_status, comment_status, ping_status, post_name, post_modified, post_modified_gmt)
            VALUES 
            ('$post_author', '$post_date', '$post_date_gmt', '$post_content', '$post_title', '$excerpt', '$status', 'open', 'open', '$post_name','$post_date', '$post_date_gmt')
        "
);
        
//echo $query;
        
$wpdb->query($query);
        
$post_id $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_title = '$post_title' AND post_date = '$post_date'");
        echo 
"<li>Inserted $post_title... ";
        
$comment_post_ID $post_id;
        
        
// categories
        
$categories = &$theFile['category'];
        if (
count($categories) > 0) {
            foreach(
$categories as $category) {
                
//insert cat
                /* Old:
                if ($category == 'default') $category_id = 9;
                else $category_id = 8;
                */
                
$category_id insertcategory($category);
                
$wpdb->query("INSERT INTO $wpdb->post2cat (post_id, category_id) VALUES ($comment_post_ID, $category_id)");
            }
        }
        
        
// comments
        
$comments = &$theFile['comments'];
        if (
count($comments) > 0) {
            
$thiscommentcount 0;
            foreach(
$comments as $comment) {
                
// insert comment
                /* fields:
                    comment_ID
                    comment_post_ID
                    comment_author
                    comment_author_email
                    comment_author_url
                    comment_author_IP
                    comment_date
                    comment_date_gmt
                    comment_content
                    comment_karma
                    comment_approved
                    comment_agent
                    comment_type
                    comment_parent
                    user_id
                    comment_favicon_url
                */
                
$comment_author addslashes($comment['name']);
                
$comment_author_email addslashes($comment['email']);
                
$comment_author_url addslashes($comment['url']);
                
$comment_author_IP $comment['ip'];
                
                
$comment_date $comment['date'];
                
$comment_date explode('-'$comment_date);
                
$comment_date_gmt date('Y-m-d H:i:s'mktime($comment_date[3], $comment_date[4], 0$comment_date[1], $comment_date[2], $comment_date[0]) - 3600);
                
$comment_date date('Y-m-d H:i:s'mktime($comment_date[3], $comment_date[4], 0$comment_date[1], $comment_date[2], $comment_date[0]));
                
                
$comment_content addslashes($comment['comment']);
                
$wpdb->query("REPLACE INTO $wpdb->comments (
                    comment_post_ID, comment_author, comment_author_email, comment_author_url, comment_date, comment_date_gmt, comment_content)
                    VALUES ($comment_post_ID, '$comment_author', '$comment_author_email', '$comment_author_url',
                    '$comment_date', '$comment_date_gmt', '$comment_content') "
);
                

                
$thiscommentcount++;
            }
            echo 
"with $thiscommentcount comments.</li>\n";
        } else {
            echo 
"with no comments.</li>\n";
        }
    } else {
        echo 
"<li>Skipped post '$post_title' (already in database)</li>\n";
    }
        
    
//echo "$post_date :: $post_title ($post_name) :: $post_id<br />\n";
}

function 
_header() {
    @
header('Content-type: text/html; charset=UTF-8'); ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <title>WordPress &rsaquo; Pivot Import</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <style media="screen" type="text/css">
        body {
            font-family: Georgia, "Times New Roman", Times, serif;
            margin-left: 15%;
            margin-right: 15%;
        }
        #logo {
            margin: 0;
            padding: 0;
            background-image: url(http://wordpress.org/images/wordpress.gif);
            background-repeat: no-repeat;
            height: 60px;
            border-bottom: 4px solid #333;
        }
        #logo a {
            display: block;
            text-decoration: none;
            text-indent: -100em;
            height: 60px;
        }
        p {
            line-height: 140%;
        }
        </style>
    </head><body> 
    <h1 id="logo"><a href="http://wordpress.org">WordPress</a></h1> 
<?php
}

function 
_footer() {
?>
</body>
</html>
<?php
}

function 
_scrollDown() {
?>
<script>
window.scroll(1,500000);
</script>
<?php
}


/* $wpdb:
  [posts] => piv2wp_posts
    [users] => piv2wp_users
    [categories] => piv2wp_categories
    [post2cat] => piv2wp_post2cat
    [comments] => piv2wp_comments
    [links] => piv2wp_links
    [linkcategories] => piv2wp_linkcategories
    [options] => piv2wp_options
    [optiontypes] => 
    [optionvalues] => 
    [optiongroups] => 
    [optiongroup_options] => 
    [postmeta] => piv2wp_postmeta
*/

?>