<?php

/*
This Import Script is written by Aaron Brazell of Technosailor.com

It was developed using a large blog running Textpattern 4.0.2 and
  successfully imported nearly 3000 records at a time.  Higher
  scalability is uncertain.
  
  BACKUP YOUR DATABASE PRIOR TO RUNNING THIS IMPORT SCRIPT
*/

// BEGIN EDITING

// $txpconfig options can be found in the Textpattern %textpattern%/config.php file
$txpcfg['db'] = 'wordpress';
$txpcfg['user'] = 'root';
$txpcfg['pass'] = '';
$txpcfg['host'] = 'localhost';
$txpcfg['table_prefix'] = '';

// STOP EDITING

add_option('tpre',$txpcfg['table_prefix']);

class Textpattern_Import {

	var $posts = array ();
	var $file;

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

	function footer() 
	{
		echo '</div>';
	}
	
	function greet() 
	{
		global $txpcfg;
		
		_e('<p>Howdy! This importer allows you to extract posts from any Textpattern 4.0.2+ into your blog. This has not been tested on previous versions of Textpattern.  Mileage may vary.</p>');
		_e('<p>Your Textpattern Configuration settings are as follows:</p>');
		_e('<ul><li><strong>Textpattern Database Name:</strong> '.$txpcfg['db'].'</li>');
		_e('<li><strong>Textpattern Database User:</strong> '.$txpcfg['user'].'</li>');
		_e('<li><strong>Textpattern Database Password:</strong> '.$txpcfg['pass'].'</li>');
		_e('<li><strong>Textpattern Database Host:</strong> '.$txpcfg['host'].'</li>');
		_e('</ul>');
		_e('<p>If this is incorrect, please modify settings in wp-admin/import/textpattern.php</p>');
		_e('<form action="admin.php?import=textpattern&amp;step=1" method="post">');
		_e('<input type="submit" name="submit" value="Next Step" />');
		_e('</form>');
	}

	function get_txp_cats() 
	{
		
		// General Housekeeping
		global $txpdb;
		set_magic_quotes_runtime(0);
		$prefix = get_option('tpre');
		
		// Get Categories
		$cats = $txpdb->get_results('SELECT id,
										name,
										title
							   		FROM '.$prefix.'txp_category 
							   		WHERE type = "article"
							   		', ARRAY_A);
		return $cats;
	}
	
	function get_txp_posts()
	{
		// General Housekeeping
		global $txpdb;
		set_magic_quotes_runtime(0);
		$prefix = get_option('tpre');
		
		// Get Posts
		$posts = $txpdb->get_results('SELECT 
										ID,
										Posted,
										AuthorID,
										LastMod,
										Title,
										Body,
										Excerpt,
										Category1,
										Category2,
										Status,
										Keywords,
										url_title,
										comments_count,
										ADDDATE(Posted, "INTERVAL '.get_settings('gmt_offset').' HOURS") AS post_date_gmt,
										ADDDATE(LastMod, "INTERVAL '.get_settings('gmt_offset').' HOURS") AS post_modified_gmt
							   		FROM '.$prefix.'textpattern
							   		', ARRAY_A);
		return $posts;
	}
	
	function get_txp_comments()
	{
		// General Housekeeping
		global $txpdb;
		set_magic_quotes_runtime(0);
		$prefix = get_option('tpre');
		
		// Get Comments
		$comments = $txpdb->get_results('SELECT * FROM '.$prefix.'txp_discuss', ARRAY_A);
		return $comments;
	}
	
	function get_txp_users()
	{
		// General Housekeeping
		global $txpdb;
		set_magic_quotes_runtime(0);
		$prefix = get_option('tpre');
		
		// Get Users
		$users = $txpdb->get_results('SELECT
										user_id,
										name,
										RealName,
										email,
										privs
							   		FROM '.$prefix.'txp_users', ARRAY_A);
		return $users;
	}
	
	function users2wp($users='')
	{
		// General Housekeeping
		global $wpdb;
		// Clear WordPress User table
		$wpdb->query('DELETE FROM '.$wpdb->users);
		$wpdb->query('DELETE FROM '.$wpdb->usermeta);
		
		// Midnight Mojo
		if(is_array($users))
		{
			echo __('<p>Importing Users...<br /><br /></p>');
			foreach($users as $user)
			{
				$count++;
				extract($user);
				// Do some Role Stuff
				$user = new WP_User($user_id);
				
				switch ( $privs )
				{
					case 1 :		
						$user->set_role('administrator');				
						$wpdb->query('INSERT INTO '.$wpdb->usermeta.' SET 
											user_id 	= '.$user_id.',
											meta_key 	= "wp_user_level",
											meta_value	="10"');
						$wpdb->query('INSERT INTO '.$wpdb->usermeta.' SET 
											user_id 	= '.$user_id.',
											meta_key 	= "rich_editing",
											meta_value	= "false"');
						break;
					case 2 :
						$user->set_role('editor');
						$wpdb->query('INSERT INTO '.$wpdb->usermeta.' SET 
											user_id 	= '.$user_id.',
											meta_key 	= "wp_user_level",
											meta_value	= "9"');
						$wpdb->query('INSERT INTO '.$wpdb->usermeta.' SET 
											user_id 	= '.$user_id.',
											meta_key 	= "rich_editing",
											meta_value	= "false"');
						break;
					case 3 :
						$user->set_role('editor');
						$wpdb->query('INSERT INTO '.$wpdb->usermeta.' SET 
											user_id 	= '.$user_id.',
											meta_key 	= "wp_user_level",
											meta_value	=  "5"');
						$wpdb->query('INSERT INTO '.$wpdb->usermeta.' SET 
											user_id 	= '.$user_id.',
											meta_key 	= "rich_editing",
											meta_value	= "false"');
						break;
					case 4 :
						$user->set_role('author');
						$wpdb->query('INSERT INTO '.$wpdb->usermeta.' SET 
											user_id 	= '.$user_id.',
											meta_key 	= "wp_user_level",
											meta_value	= "4"');
						$wpdb->query('INSERT INTO '.$wpdb->usermeta.' SET 
											user_id 	= '.$user_id.',
											meta_key 	= "rich_editing",
											meta_value	= "false"');
						break;
					case 5 :
						$user->set_role('contributor');
						$wpdb->query('INSERT INTO '.$wpdb->usermeta.' SET 
											user_id 	= '.$user_id.',
											meta_key 	= "wp_user_level",
											meta_value	=  "3"');
						$wpdb->query('INSERT INTO '.$wpdb->usermeta.' SET 
											user_id 	= '.$user_id.',
											meta_key 	= "rich_editing",
											meta_value	= "false"');
						break;
					case 6 :
						$user->set_role('contributor');
						$wpdb->query('INSERT INTO '.$wpdb->usermeta.' SET 
											user_id 	= '.$user_id.',
											meta_key 	= "wp_user_level",
											meta_value	= "2"');
						$wpdb->query('INSERT INTO '.$wpdb->usermeta.' SET 
											user_id 	= '.$user_id.',
											meta_key 	= "rich_editing",
											meta_value	= "false"');
						break;
					default :
						$user->set_role('contributor');
						$wpdb->query('INSERT INTO '.$wpdb->usermeta.' SET 
											user_id 	= '.$user_id.',
											meta_key 	= "wp_user_level",
											meta_value	= "0"');
						break;
				} 
				
				// Insert

				$wpdb->query('INSERT INTO '.$wpdb->users.' SET
									ID				= '.$user_id.',
									user_login		= "'.$wpdb->escape($name).'",
									user_pass		= "'.md5('password123').'",
									user_nicename	= "'.$wpdb->escape($RealName).'",
									user_email		= "$email",
									user_url		= "http://",
									display_name	= "'.$wpdb->escape($name).'"
							');
			}// End foreach($users as $user)
			echo __('<p>Done! <strong>'.$count.'</strong> users imported.<br /><br /></p>');
			
		}// End if(is_array($users)
		return false;
		
	}// End function user2wp()
	
	function cat2wp($categories='') 
	{
		// General Housekeeping
		global $wpdb;
		$wpdb->query('DELETE FROM '.$wpdb->categories);
		
		// Do the Magic
		if(is_array($categories))
		{
			echo __('<p>Importing Categories...<br /><br /></p>');
			foreach ($categories as $category) 
			{
				$count++;
				extract($category);
				
				if(category_exists($name))
					echo __('Category already Imported');
				else
				{
					$wpdb->query('INSERT INTO '.$wpdb->categories.' SET
								  		cat_ID					= '.$id.',
								  		category_nicename		= "'.$name.'",
								  		cat_name				= "'.$title.'",
								  		category_parent			= 0,
								 		category_description	= ""
								');
			
				}
			}
			echo __('<p>Done! <strong>'.$count.'</strong> categories imported.<br /><br /></p>');
			return true;
		}
		else 
		{
			return false;
		}
	}
	
	function posts2wp($posts='')
	{
		// General Housekeeping
		global $wpdb;
		// Empty the Tables for new data
		$wpdb->query('DELETE FROM '.$wpdb->post2cat);				
		$wpdb->query('DELETE FROM '.$wpdb->posts);
			
		$catarr = get_option('txp_cats');
		
		// Do the Magic
		if(is_array($posts))
		{
			echo __('<p>Importing Posts...<br /><br /></p>');
			foreach($posts as $post)
			{
				$count++;
				extract($post);
				
				if(post_exists($wpdb->escape($Title)))
					echo __('Post Already Imported');
				else 
				{
					// WordPressify Textpattern data 
					$cat1 = (in_array($post['Category1'], $catarr)) ? array_search($post['Category1'], $catarr) : '';
					$cat2 = (in_array($post['Category2'], $catarr)) ? array_search($post['Category2'], $catarr) : '';
					$author = $wpdb->get_row('SELECT * FROM '.$wpdb->users.' WHERE user_nicename = "$AuthorID" OR user_login = "$AuthorID"',ARRAY_A);
					$authorid = ($author) ? $author['ID'] : 1;
				
					switch ( $Status )
					{
						case 1 :							# TXP Status: Draft
						case 3 :							# TXP Status: Pending
							$post_status = 'draft';
							break;
						case 2 :							# TXP Status: Hidden
							$post_status = 'private';
							break;
						case 4 :							# TXP Status: Live
						case 5 :							# TXP Status: Static
						default :
							$post_status = 'publish';
							break;
					}
					
					
					// Make Post-to-Category associations
					
					if($cat1 != '')
					{
						$wpdb->query('INSERT INTO '.$wpdb->post2cat.' SET 
									   		post_id 			= $ID,
									   		category_id		= $cat1
									 ');
					}
					if($cat2 != '')
					{
						$wpdb->query('INSERT INTO '.$wpdb->post2cat.' SET 
									   		post_id 			= $ID,
									   		category_id		= $cat2
									 ');
					}
					// Import Post data into WordPress
					$wpdb->query('INSERT INTO '.$wpdb->posts.' SET
								   		ID					= '.$ID.',
								   		post_date			= "'.$Posted.'",
								   		post_date_gmt		= "'.$post_date_gmt.'",
								   		post_author			= '.$authorid.',
								   		post_modified		= "'.$LastMod.'",
								   		post_modified_gmt	= "'.$post_modified_gmt.'",
								   		post_title			= "'.$wpdb->escape($Title).'",
								   		post_content		= "'.$wpdb->escape($Body).'",
								   		post_excerpt		= "'.$wpdb->escape($Excerpt).'",
								   		post_status			= "'.$post_status.'",
								   		post_name			= "'.$url_title.'",
								   		comment_count		= '.$comments_count);
				}
			}
			echo __('<p>Done! <strong>'.$count.'</strong> posts imported.<br /><br /></p>');
			return true;	
		}
		else 
		{
			return false;
		}
	}
	
	function comments2wp($comments='')
	{
		// General Housekeeping
		global $wpdb;
		// Clear Comments table
		$wpdb->query('DELETE FROM '.$wpdb->comments);
		
		// Magic Mojo
		if(is_array($comments))
		{
			echo __('<p>Importing Comments...<br /><br /></p>');
			foreach($comments as $comment)
			{
				$count++;
				extract($comment);
				
				if(comment_exists($wpdb->escape($comment['name']), $wpdb->escape($comment['posted'])))
				{
					echo __('Comment Already Imported...');
				}
				
				// WordPressify Data
				$comment_ID = ltrim($discussid, '0');
				$comment_approved = (1 == $visible) ? 1 : 0;
				
				// The query
				$wpdb->query('INSERT INTO '.$wpdb->comments.' SET
							   		comment_ID				= '.$comment_ID.',
							   		comment_post_ID			= '.$parentid.',
							   		comment_author			= "'.$wpdb->escape($name).'",
							  	 	comment_author_email	= "'.$wpdb->escape($email).'",
							   		comment_author_url		= "'.$wpdb->escape($web).'",
							   		comment_author_ip		= "'.$ip.'",
							   		comment_date			= "'.$posted.'",
							   		comment_content			= "'.$wpdb->escape($message).'",
							   		comment_approved		= "'.$comment_approved.'"
							 ');
			}
			echo __('<p>Done! <strong>'.$count.'</strong> comments imported.<br /><br /></p>');
			return true;
		}
		else 
		{
			return false;
		}
		
	}

	function import_categories() 
	{	
		// Category Import	
		$cats = $this->get_txp_cats();
		$this->cat2wp($cats);
		add_option('txp_cats', $cats);
			
		_e('<form action="admin.php?import=textpattern&amp;step=3" method="post">');
		_e('<input type="submit" name="submit" value="Next Step" />');
		_e('</form>');

	}
	
	function import_posts()
	{
		// Post Import
		$posts = $this->get_txp_posts();
		$this->posts2wp($posts);
		
		_e('<form action="admin.php?import=textpattern&amp;step=4" method="post">');
		_e('<input type="submit" name="submit" value="Next Step" />');
		_e('</form>');
	}

	function import_comments()
	{
		// Comment Import
		$comments = $this->get_txp_comments();
		$this->comments2wp($comments);
		
		_e('<form action="admin.php?import=textpattern&amp;step=5" method="post">');
		_e('<input type="submit" name="submit" value="Finish" />');
		_e('</form>');
	}

	function import_users()
	{
		// User Import
		$users = $this->get_txp_users(); 
		$this->users2wp($users);
		
		_e('<form action="admin.php?import=textpattern&amp;step=2" method="post">');
		_e('<input type="submit" name="submit" value="Next Step" />');
		_e('</form>');
		

	}
	
	function cleanup_txpimport()
	{
		delete_option('tpre');
		delete_option('txp_cats');
		$this->tips();
	}
	
	function tips()
	{
		echo'<p>Welcome to WordPress.  We hope (and expect!) that you will find this platform incredibly rewarding!  As a new WordPress user coming from Textpattern, there are some things that we would like to point out.  Hopefully, they will help your transition go as smoothly as possible.</p>';
		echo'<h3>Users</h3>';
		echo'<p>You have already setup WordPress and have been assigned an administrative login and password.  Forget it.  You didn\'t have that login in Textpattern, why should you have it here?  Instead we have taken care to import all of your users into our system.  Unfortunately there is one downside.  Because both WordPress and Textpattern uses a strong encryption hash with passwords, it is impossible to decrypt it and we are forced to assign temporary passwords to all your users.  <strong>Every user has the same username, but their passwords are reset to password123.</strong>  This includes you.  So <a href="/wp-login.php">Login</a> and change it.</p>';
		echo'<h3>Preserving Authors</h3>';
		echo'<p>Secondly, we have attempted to preserve post authors.  If you are the only author or contributor to your blog, then you are safe.  In most cases, we are successful in this preservation endeavor.  However, if we cannot ascertain the name of the writer due to discrepancies between database tables, we assign it to you, the administrative user.</p>';
		echo'<h3>Textile</h3>';
		echo'<p>Also, since you\'re coming from Textpattern, you probably have been using Textile to format your comments and posts.  If this is the case, we recommend downloading and installing <a href="http://www.huddledmasses.org/2004/04/19/wordpress-plugin-textile-20/">Textile for WordPress</a>.  Trust me... You\'ll want it.</p>';
		echo'<h3>WordPress Resources</h3>';
		echo'<p>Finally, there are numerous WordPress resources around the internet.  Some of them are:</p>';
		echo'<ul>';
		echo'<li><a href="http://www.wordpress.org">The official WordPress site</a></li>';
		echo'<li><a href="http://wordpress.org/support/">The WordPress support forums</li>';
		echo'<li><a href="http://codex.wordpress.org">The Codex (In other words, the WordPress Bible)</a></li>';
		echo'</ul>';
		echo'<p>That\'s it! What are you waiting for? Go <a href="/wp-login.php">login</a>!</p>';
	}
	
	function dispatch() 
	{
		if (empty ($_GET['step']))
			$step = 0;
		else
			$step = (int) $_GET['step'];

		$this->header();
		
		switch ($step) 
		{
			default:
			case 0 :
				$this->greet();
				break;
			case 1 :
				$this->import_users();
				break;
			case 2 :
				$this->import_categories();
				break;
			case 3 :
				$this->import_posts();
				break;
			case 4 :
				$this->import_comments();
				break;
			case 5 :
				$this->cleanup_txpimport();
				break;
		}
		
		$this->footer();
	}

	function Textpattern_Import() 
	{
		// Nothing.	
	}
}

$txpdb = new wpdb($txpcfg['user'], $txpcfg['pass'], $txpcfg['db'], $txpcfg['host']);

$txp_import = new Textpattern_Import();
register_importer('textpattern', 'Textpattern', __('Import posts from a Textpattern Blog'), array ($txp_import, 'dispatch'));
?>
