<?php
//////////////////////////////////////////////////////////////////////////////
//  MT 2.6x to BLOG:CMS 3.0 (2.5) blog conversion tool. Mysql connectivity required.
//        USE AT YOUR OWN RISK
//
// Save this file, edit the parameters and upload to your site with extension php	
// 
// Entries and comments are imported. Wizard styled: you need only to set
// the database connection parameters, the rest (BLOG:CMS db prefix,
// blogs, authors and categories conversion) are interactively obtained if needed.
// You MUST create previously the (empty) BLOG:CMS blog, and SHOULD create
// authors and categories from the BLOG:CMS administration forms. 
// More info at the bottom of the page, or clicking the Instructions link.
//
// By Hernan J. Gonzalez  (leonbloy) http://www.hjg.com.ar/   22-May-2004
// (based on an older script written by Olli Savolainen, http://pilpi.net/ )
// You can contact me at hgonzalez@gmail.com     
//
// Revision 0.4 17-Jul-2004
//   - Fixed entries closed-for-comments issue (thanks Noble Baker)
//   - Fixed problem with quotes and newlines in comments
//   - Added: delete entries and comments from BLOG:CMS blog (useful for retries)
//   - Changed file organization: info (html) in a separate page.
// Revision 0.32 11-Jul-2004
//   - Fixed problem with mysql_insert_id which caused comments to be unlinked in some cases
// Revision 0.31 30-May-2004
//   - Cosmetic and doc changes  
//   - Added 'coward' flag
// Revision 0.3  25-May-2004 
//   - added newlines convertion for items and comments when corresponds
//   - respect comment status (open/closed items) 
//   - doc (info)
//
//////////////////////////////////////////////////////////////////////////////

//////////// Begin Manual configuration ////////////////////////////////////////

// SOURCE DATA (MOVABLE TYPE) - THIS DATABASE WONT BE ALTERED, ONLY READ
$MT_DBHOST = "localhost";       
$MT_DBUSER = "";
$MT_DBPASS = "";
$MT_DBNAME = "";		 

// DESTINATION (BLOG:CMS) - THIS DATABASE WILL BE MODIFIED 
$NUCLEUS_DBHOST = "localhost";
$NUCLEUS_DBUSER = "";
$NUCLEUS_DBPASS = "";
$NUCLEUS_DBNAME = "";  

//////////// End Manual configuration ///////////////////////////////////

///// You should not modify the following lines /////////////////////////////////

?>

<html><head> <title>MT to BLOG:CMS conversion</title> 
<style> body , td { font: 11px Verdana } td {text-align:center;}</style></head>
<body><b><big>Movable Type to BLOG:CMS conversion tool</big></b>

<?php
if(isset($_REQUEST['info'])) { info(); exit; }
?>

&nbsp; [<?php echo infolink(); ?>]
<p>
<small><a href="?">[Lets re-start over]</a> Do not press the Back Button,
do not press Refresh (or F5). <br>In case of doubt, restart the process by
clicking the link above.</small></p><hr>
<form method=post>

<?php

$FLAG_COWARD=1; // if BLOG:CMS db seems to be filled, just refuse to import and die
$FLAG_COMMIT=1; // escribo en la DB?

// constantes
$MT_PUBLISHED_STATUS=2;
$NUCLEUS_PUBLISHED_STATUS=0;
$NUCLEUS_DRAFT_STATUS=1;

$MT_COMMENTS_NOCOMMENTS=0;
$MT_COMMENTS_OPEN=1;
$MT_COMMENTS_CLOSED=2;
$NUCLEUS_COMMENTS_OPEN=0;
$NUCLEUS_COMMENTS_CLOSED=1;

$MT_DONT_CONVERT_NEWLINES=0; // en el item 


///////////////////////////////

$mt_category_default=0; // autocomputed

$form_vars=array(); // variables que se pasan de formulario a formulario

$doit = (isset( $_REQUEST['Go']));
flush();ob_end_flush();

if(!$MT_DBNAME ) exit("Hey.... you <b>must</b> edit this file to set the database parameters. ");

$my_nuc = mysql_connect($NUCLEUS_DBHOST, $NUCLEUS_DBUSER, $NUCLEUS_DBPASS)	or exit('<p>Could not connect to NUCLEUS database ');
mysql_select_db($NUCLEUS_DBNAME,$my_nuc) 	or exit('<p>Could not connect to NUCLEUS database. Check the parameters ');
$my_mt = mysql_connect($MT_DBHOST, $MT_DBUSER, $MT_DBPASS)	or exit('<p>Could not connect to MT database. Check the parameters ');
mysql_select_db($MT_DBNAME,$my_mt) 	or exit('<p>Could not connect to MT database ');
	
echo "Connecting to MT and BLOG:CMS databases... ok<br>";
// BLOG:CMS prefix ?
$nuc_prefix = get_nuc_prefix(); //print_r($nucleus_prefixes);
echo "BLOG:CMS DB prefix: '$nuc_prefix'<br>\n";

list($nuc_blog_id,$nuc_blog_name) = get_nuc_blog(); 
echo "<br><big>BLOG:CMS blog (destination) : <b>$nuc_blog_name</b> (<i>id=$nuc_blog_id</i>) </big><br>\n";
list($mt_blog_id,$mt_blog_name,$mt_comments_newlines) = get_mt_blog(); 
echo "<big>MT blog (origin): <b>$mt_blog_name</b> (<i>id=$mt_blog_id</i>)</big><br>\n";
//echo "--hjg -- mt_comments_newlines: $mt_comments_newlines<br>\n";

if($_REQUEST['delete'])
{
	if(! $_REQUEST['confirm'])
	{
		$nuc_blog_id = $_REQUEST['nuc_blog_id'];
		echo "<hr><br> <b><font color=red>DELETING ENTRIES AND COMMENTS</font></b><br>ARE YOU SURE???<br>\n";
		echo "ALL your <b>posts and comments</b> will be <b>deleted</b> from your BLOG:CMS blog,";
		echo "and they can'be be recovered<br><br>";
		$varsurl = vars_url();
		echo "<a href=\"?delete=1&confirm=1$varsurl\">";
		echo "<b>I'm sure! Go ahead and delete all!</b></a> &nbsp; &nbsp; &nbsp;";
		echo "<a href=\"?\">Cancel</a>";
		exit;
	}	
	delete_entries();
	exit;
}


if(! $doit)
{
echo "<p>Specify <b>authors</b> conversion:(perhaps you might want to create more <br>authors in your BLOG:CMS blog before proceeding...)\n";
echo get_authors();

echo "<p>Specify <b>categories</b> conversion: (perhaps you might want to create more <br>categories in your BLOG:CMS blog before proceeding...)<br>\n";
echo get_categories();
echo "<hr>";
echo get_summary();
}

echo hidden_vars();

if(! $doit)
	exit("<hr><b>Proceed</b> <br><input type=\"submit\" name='Go' value=' Go! '> Press only once, and cross your fingers ... </form>");

// doit !!!!!!
echo "<hr><font color=\"red\"> CONVERTING FROM MT TO BLOG:CMS.... PLEASE WAIT!</font> ...<br>...<br>";	
flush();

$authors = authors_translation();
$categories = categories_translation();
//print_r($authors);print_r($categories);

////////// funciones

function hidden_vars()
{
	global $form_vars;
	$s='';
	foreach ($form_vars as $name => $val)
	{
		$name = htmlspecialchars($name);
		$val  = htmlspecialchars($val);
		$s .= "<input type='hidden' name='$name' value='$val'>\n";
	}
	return $s;
}

// fabrica query string con los valores principales. no incluye & inicial ni final
function vars_url()
{
	global $form_vars;
	$s='';
	$s .= 'nuc_prefix=' . $form_vars[nuc_prefix];
	$s .= '&nuc_blog_id=' . $form_vars[nuc_blog_id];
	$s .= '&mt_blog_id=' . $form_vars[mt_blog_id];
	return $s;	
}

function delete_entries()
{
	global $NUCLEUS_DBNAME,$my_nuc,$nuc_prefix,$nuc_blog_id;
	echo "Deleting entries .... ";
	$query="DELETE FROM $NUCLEUS_DBNAME." . $nuc_prefix ."item where iblog = $nuc_blog_id" ;
	mysql_query($query,$my_nuc) or die ("Error - query : ". $query . " :  " . mysql_error());
	echo mysql_affected_rows($my_nuc)  . " entries deleted!<br>\n";
	$query="DELETE FROM $NUCLEUS_DBNAME." . $nuc_prefix ."comment where cblog = $nuc_blog_id ";
	mysql_query($query,$my_nuc) or die ("Error - query : ". $query . " :  " .  mysql_error());
	echo mysql_affected_rows($my_nuc)  . " comments deleted!<br>\n";
	echo "<hr>";
	$varsurl = vars_url();
	echo "<a href=\"?$varsurl\">Restart migration</a>";
}

function get_authors()
{
	global $NUCLEUS_DBNAME,$my_nuc,$MT_DBNAME,$my_mt,$form_vars,$nuc_prefix;
	// usuairos de nuc
	$result = mysql_query("SELECT mnumber, mname, mrealname  FROM $NUCLEUS_DBNAME." . $nuc_prefix . "member",$my_nuc) or exit("<p>fatal error in query : " .mysql_error());	
	$select_autnuc='';
	$cont_nuc_aut = 0;
	while ($row = mysql_fetch_row($result)) { 
			$cont_nuc_aut++;
			$select_autnuc .= "<option value='$row[0]'>$row[1] ($row[2])<br>";
	}
	$result = mysql_query("SELECT author_id,author_name,author_nickname FROM $MT_DBNAME.mt_author ",$my_mt) or exit("<p>fatal error in query (IS $MT_DBNAME a MOVABLE TYPE DATABASE??) : " .mysql_error());	
	$txt='<table border=0 width=500>';
	$txt .= '<tr bgcolor="#ccccff"><td>MT (old) author</td><td>BLOG:CMS (new) author</td></tr>';
	$cont_mt_aut = 0;
	while ($row = mysql_fetch_row($result)) { 
		$varname= 'aut_' . $row[0];
		$cont_mt_aut  ++;
		$txt .= 	"<tr bgcolor=\"#eeeeee\"><td>id=$row[0]: $row[1] ($row[2])</td><td><select name='$varname'>$select_autnuc</select></td></tr>\n";
	}
	$txt .="</table>\n";
	if($cont_mt_aut > $cont_nuc_aut) 
		$txt.= "(<font color='red'>There are $cont_mt_aut authors in MT blog, but only $cont_nuc_aut in Nuclueus. "
			. "Perhaps you should add some authors to your BLOG:CMS blog before proceeding </font><br>\n";
	return $txt;
}

function authors_translation()
{
	$aut = array();
	foreach ($_REQUEST as $name => $val)
	{
		$pieces = explode("_", $name);
		if($pieces[0] == 'aut') $aut[$pieces[1]] = $val;
	}	
	return $aut;
}

function get_categories()
{
	global $NUCLEUS_DBNAME,$my_nuc,$MT_DBNAME,$my_mt,$form_vars,$nuc_prefix,$nuc_blog_id,$mt_blog_id,$mt_category_default;
	$result = mysql_query("SELECT catid , cname FROM $NUCLEUS_DBNAME." . $nuc_prefix . "category ".
		"where cblog=$nuc_blog_id",$my_nuc) or exit("<p>fatal error in query : " .mysql_error());	
	$select_catnuc='';
	$cont_nuc_cat=0;
	while ($row = mysql_fetch_row($result)) { 
			$select_catnuc .= "<option value='$row[0]'>$row[1]<br>";
			$cont_nuc_cat++;
			if($cont_nuc_cat ==1) $mt_category_default = $row[0];
	}
	$txt='<table border=0 width=500 cellspacing=2 cellpadding=2>';
	$txt .= '<tr bgcolor="#ccccff"><td>MT (old) category</td><td>BLOG:CMS (new) category</td></tr>';
		
	$result = mysql_query("SELECT category_id,category_label FROM $MT_DBNAME.mt_category " .
		" where category_blog_id=$mt_blog_id ",$my_mt) or exit("<p>fatal error in query  : " .mysql_error());	
	$cont_mt_cat=0;
	while ($row = mysql_fetch_row($result)) { 
		$cont_mt_cat++;
		$varname= 'cat_' . $row[0]; $default = '';
		if(! $mt_category_default) { $mt_category_default = $row[0]; $default = '(default)';}
		$txt .= 	"<tr bgcolor=\"#eeeeee\"><td>id=$row[0]: $row[1] $default</td><td><select name='$varname'>$select_catnuc</select></td></tr>\n";
	}
	if($cont_mt_cat==0) { $txt .="<tr bgcolor=\"#ffeecc\"><td colspan=2>no categories in MT blog</td></tr>";}
	$txt .="</table>\n";
	if($cont_nuc_cat==0) 
		exit("You must create some categories in your BLOG:CMS blog before proceeding");
	if($cont_mt_cat > $cont_nuc_cat) 
		$txt.= "(<font color='red'>There are $cont_mt_cat categories in MT blog, but only $cont_nuc_cat in BLOG:CMS. "
			. "Perhaps you should add some categories to your BLOG:CMS blog before proceeding </font><br>\n";
	return $txt;
}

function categories_translation()
{
	$cat = array();
	foreach ($_REQUEST as $name => $val)
	{
		$pieces = explode("_", $name);
		if($pieces[0] == 'cat') $cat[$pieces[1]] = $val;
	}	
	return $cat;
}


function get_summary($check_mode=0)
{
	global $NUCLEUS_DBNAME,$my_nuc,$MT_DBNAME,$my_mt,$form_vars,$nuc_prefix,$nuc_blog_id,$mt_blog_id,$FLAG_COWARD;
	$txt = 'We are about to migrate from MT to BLOG:CMS:<br>';
	
	
	$txt .= "<br>BLOG:CMS (new; destination) blog $nuc_blog_id has :<br>\n";
	
	$result = mysql_query("SELECT count(*) FROM $NUCLEUS_DBNAME." . $nuc_prefix . "item where iblog=$nuc_blog_id",$my_nuc) or exit("<p>fatal error in query : " .mysql_error());	
	$row = mysql_fetch_row($result);
	$nuc_items = $row[0];
	$txt .= "<li><b>$nuc_items</b> items (posts).<br>";
	mysql_free_result($result);
	$varsurl = vars_url();
	$link_del = "You can choose to <a href=\"?delete=1&$varsurl\">delete all entries and comments</a> from the BLOG:CMS blog <br>\n";
	if($nuc_items > 2 ) $txt .= '<font color="red"><b>BLOG:CMS (new destination) blog is not empty ... are you sure ?</b></font><br>' . $link_del;
	
	
	$txt .= "<br>MT (old ; source) blog $mt_blog_id has : <br>";
	
	$result = mysql_query("SELECT count(*) FROM $MT_DBNAME.mt_entry where entry_blog_id =$mt_blog_id ",$my_mt) or exit("<p>fatal error in query  : " .mysql_error());	
	$row = mysql_fetch_row($result);
	$mt_items = $row[0];
	$txt .= "<li><b>$mt_items items</b> (posts) that will be exported to BLOG:CMS.<br>";
	mysql_free_result($result);
	$result = mysql_query("SELECT count(*) FROM $MT_DBNAME.mt_comment where comment_blog_id =$mt_blog_id ",$my_mt) or exit("<p>fatal error in query  : " .mysql_error());	
	$row = mysql_fetch_row($result);
	$txt .= "<li><b>$row[0] comments</b> that will be exported to BLOG:CMS.<br>";
	mysql_free_result($result);
	
	if($check_mode) // vuelve a leer en nuc; checkea que no haya variado la cantidad de posts, y que sea menor que mt
	{
		$link_del = "You can choose to <a href=\"?delete=1&$varsurl\">delete all entries and comments</a> from the BLOG:CMS blog <br>\n";
		if($nuc_items >= $mt_items )  {
			if($FLAG_COWARD)	die("<br>sorry ... aborting !<br> BLOG:CMS database has more entries than mt ... are you sure you're not migrating twice? <br>$link_del");
			else					echo("<br>mmmmmmm... be careful!<br> BLOG:CMS database has more entries than mt ... are you sure you're not migrating twice? \n");
		}
		for($i=0;$i<5;$i++) { sleep(1); echo ".";flush();} // sleep ... 
		$result = mysql_query("SELECT count(*) FROM $NUCLEUS_DBNAME." . $nuc_prefix . "item where iblog=$nuc_blog_id",$my_nuc) or exit("<p>fatal error in query : " .mysql_error());	
		$row = mysql_fetch_row($result);
		$nuc_items2 = $row[0];
		if($nuc_items2 > $nuc_items) die("aborting ; BLOG:CMS database is being modified");
		mysql_free_result($result);
	}
		
	return $txt;
}

// el prefijo se devuelve completo, con el _
function get_nuc_prefix()
{
	global $NUCLEUS_DBNAME,$my_nuc,$form_vars;
	$prefijos = array();
	$cont=0; 
	$result = mysql_query("SHOW TABLES FROM $NUCLEUS_DBNAME",$my_nuc) or exit("<p>fatal error in query (IS $NUCLEUS_DBNAME a BLOG:CMS 3.0 DATABASE??) : " .mysql_error());	
	$prefijo="";
	while ($row = mysql_fetch_row($result)) { // testigo: nucleus_plugin_option_desc  => prefijo= nucleus_
   	 	$l = strpos($row[0],'plugin_option_desc');
   	 	if($l === FALSE)   	 	continue;
   	 	$cont++; 
   	 	$prefijo = substr($row[0],0,$l);
   	 	$prefijo_name = $prefijo ? $prefijo : '(none)';
   	 	$select .= "<input type=\"radio\" name=\"nuc_prefix\" value=\"$prefijo\">$prefijo_name<br>\n";
   }
	if($cont<1) exit("$NUCLEUS_DBNAME does not seem to be a BLOG:CMS 3.0 DATABASE!!");
	if($cont>1)
	{
		if(isset($_REQUEST['nuc_prefix']))
			$prefijo = $_REQUEST['nuc_prefix'];
		else { 	// formulario para elegir prefix
			echo "<HR>Ambiguous BLOG:CMS DB prefix : choose one to continue: <br><form>$select <input type=\"submit\" value=\"Next &gt;&gt;\"></form>	";
			exit;
		}
	}
	$form_vars['nuc_prefix'] = $prefijo;
	return $prefijo;
}

// 
function get_nuc_blog()
{
	global $NUCLEUS_DBNAME,$my_nuc,$form_vars,$nuc_prefix;
	$cont=0; 
	$blogs = array();
	$result = mysql_query("SELECT bnumber, bname FROM $NUCLEUS_DBNAME." . $nuc_prefix ."blog ",$my_nuc) or exit("<p>fatal error in query (IS $NUCLEUS_DBNAME a BLOG:CMS 3.0 DATABASE??) : " .mysql_error());	
	while ($row = mysql_fetch_row($result)) { // testigo: nucleus_plugin_option_desc  => prefijo= nucleus_
			$cont++;
			$blogid = $row[0];
   	 	$blogs[$blogid]=$row[1];
   	 	$select .= "<option value=\"$row[0]\">$row[1]<br>\n";
   }
	if($cont<1) exit("NO BLOG:CMS BLOG FOUND! ");
	if($cont>1)	{
		if(isset($_REQUEST['nuc_blog_id']))
			$blogid = $_REQUEST['nuc_blog_id'];
		else { 	// formulario para elegir blog
			echo "<HR>Ambiguous BLOG:CMS (destination) blog.<br> Choose one to continue: <form><select name='nuc_blog_id'>$select</select> <br>" . 
				hidden_vars() . "<input type=\"submit\" value=\"Next &gt;&gt;\"></form>	";
			exit;
		}
	}
	$form_vars['nuc_blog_id'] = $blogid;
	return array($blogid,$blogs[$blogid]);
}

// 
function get_mt_blog()
{
	global $MT_DBNAME,$my_mt,$form_vars;
	$myblogid = $_REQUEST['mt_blog_id']; // la primera vez no vendrá seteado
	$cont=0; 
	$blogname='';
	$blog_pref_comments_newlines='';
	$result = mysql_query("SELECT blog_id, blog_name, blog_convert_paras_comments "
			. "FROM $MT_DBNAME.mt_blog ",$my_mt) 
			or exit("<p>fatal error in query (IS $MT_DBNAME a MOVABLE TYPE DATABASE??) : " 
			.mysql_error());	
	while ($row = mysql_fetch_row($result)) { 
			if( isset($myblogid) && $row[0] != $myblogid ) 
				continue;
			$blogid=$row[0];
			$blogname=$row[1];
   	 	$blog_pref_comments_newlines = $row[2];
   	 	$cont++;
  	 	 	$select .= "<option value=\"$blogid\">$blogname<br>\n";
   }
	if($cont<1) exit("NO MT BLOG FOUND! ");
	if($cont>1)	{
		if(isset($myblogid)) die ("fatal anomalityt getting mt blogs ??"); // impossible
		// formulario para elegir blog
		echo "<HR>Ambiguous <b>Movable Type (source) blog</b>.<br>Choose one to continue: <form><select name='mt_blog_id'>$select</select> <br>" . 
			hidden_vars() . "<input type=\"submit\" value=\"Next &gt;&gt;\"></form>	";
		exit;
		}
	$form_vars['mt_blog_id'] = $blogid;
	return array($blogid,$blogname,$blog_pref_comments_newlines);
}

////////////////////////////////////////////////////////////////////////////////////////////////

echo " here we go ! \n";
get_summary(1); // check

// get entries from Movable Type
$query="SELECT entry_id,entry_text, entry_status, entry_category_id, entry_title, " .
	" entry_text_more, entry_created_on , entry_author_id,entry_convert_breaks,entry_allow_comments  " .
	" FROM $MT_DBNAME.mt_entry where entry_blog_id = $mt_blog_id ORDER BY entry_id ASC";
$result = mysql_query($query,$my_mt) or die ("Error - query : ". $query . " :  " . mysql_error());
$nposts=0;
$ncomments=0;
echo "\n<br>selecting posts from mt...<br>\n";
while ($row = mysql_fetch_assoc($result)) 
{
    $nposts++;
    $postid = $row['entry_id'];
    if( ! ($row['entry_convert_breaks'] == "0" ))     {
    		$row['entry_text'] = str_replace("\n","<br />\n", $row['entry_text']);
    		$row['entry_text_more'] = str_replace("\n","<br />\n", $row['entry_text_more']);
    }
    
   // MT categories : placement table 
   $placement_query="SELECT placement_entry_id,placement_category_id FROM $MT_DBNAME.mt_placement " . 
   	"WHERE placement_entry_id='$postid' ORDER BY placement_is_primary DESC";
   $placement_result = mysql_query($placement_query,$my_mt)  or die ("Error - query : ". $placement_query . " :  " . mysql_error());
   if(mysql_num_rows($placement_result) == 0)
   	$catid_mt = $mt_category_default;
   else   {
   	$placement_row = mysql_fetch_assoc($placement_result);
   	$catid_mt = $placement_row['placement_category_id'];
	}
	mysql_free_result($placement_result);
   $catid_nuc=$categories[$catid_mt]; 
   if(! $catid_nuc) $catid_nuc = 1; // por las dudas...
   
   $authorid_nuc = $authors[$row['entry_author_id']]; 
   if(! $authorid_nuc) $authorid_nuc = 1; // por las dudas...
   
   // if it's a draft in MT...
   if ($row['entry_status']==$MT_PUBLISHED_STATUS)       $draft_flag=$NUCLEUS_PUBLISHED_STATUS;
   else      															$draft_flag=$NUCLEUS_DRAFT_STATUS;
   
   // if it's not open for comments...
   if ($row['entry_allow_comments']==$MT_COMMENTS_OPEN )       $closed_flag=$NUCLEUS_COMMENTS_OPEN;
   else      																	$closed_flag=$NUCLEUS_COMMENTS_CLOSED;
   
   $insert_query ="INSERT into $NUCLEUS_DBNAME." . $nuc_prefix ."item " 
   	. "(ititle,ibody,imore,iblog,iauthor,itime,idraft,icat, iclosed,ikarmapos,ikarmaneg) VALUES ('"
   	. mysql_escape_string($row['entry_title'])      . "','" 
   	. mysql_escape_string($row['entry_text'] )      . "','" 
   	. mysql_escape_string($row['entry_text_more'])  . "','" 
   	. $nuc_blog_id . "','" 	. $authorid_nuc         . "','" 
   	. $row['entry_created_on'] . "','". $draft_flag . "','" 
   	. $catid_nuc . "','" . $closed_flag . "','0','0')"; 
   
   mysql_query($insert_query,$my_nuc)   or die("Could not insert item [$insert_query] : " . mysql_error());
       // get the inserted entry's new id to be used while inserting
       // the comments of the entry
       $citem=mysql_insert_id($my_nuc);
       echo "Entry: ".$row['entry_id']."=&gt;$citem";
       if( $citem ==0)  { echo " <b>ERROR!!! </b> The comments for this item will not be linked! <br>\n"; } 
       echo " title: \"".$row['entry_title']."\"<br />";
     
   $comments_query = "SELECT comment_entry_id,comment_ip,comment_author,comment_email,comment_url, "
   		. "comment_text,comment_created_on FROM $MT_DBNAME.mt_comment " 
   		. " WHERE comment_entry_id='".$row['entry_id']."'";
   $comments_result = mysql_query($comments_query,$my_mt)  or die ("# error getting comments: [$comments_query] " . mysql_error());
   
   // process all the comments for a particular entry
   while ($comments_row = mysql_fetch_assoc($comments_result)){
       $ncomments++;
       $cmember="";$cuser="";$cmail="";
     //  foreach ($comments_row as $a=>$b) {
     //      $comments_row[$a]=mysql_escape_string($b); // does it need html_entity_decode ??
     //  }
       
       $cip=$comments_row['comment_ip'];
       $cmember=0;
       $cuser=$comments_row['comment_author'];
       if (strcmp($comments_row['comment_url'],""))  $cmail=$comments_row['comment_email'];
       else 											      $cmail=$comments_row['comment_url'];
       
       if(! ($mt_comments_newlines == "0")) // convierto newlines
       	$comments_row['comment_text'] = str_replace("\n","<br />\n", $comments_row['comment_text']);
       
       // the INSERT query for the comment
       $insert_c_query="INSERT into $NUCLEUS_DBNAME." . $nuc_prefix ."comment "
          	. "(cbody,cuser,cmail,cmember,citem,ctime,cip,cblog) VALUES ('"
       		. mysql_escape_string($comments_row['comment_text']) .  "','"
       		. mysql_escape_string($cuser) . "','" . mysql_escape_string($cmail) .   "','" 
       		. $cmember  . "','" . $citem  . "','" . $comments_row['comment_created_on'].  "','"  
       		. mysql_escape_string($cip)   . "','" . $nuc_blog_id  .  "')";
  
       echo "Comment at: ";
       echo $comments_row['comment_created_on']."<br />\n";
       mysql_query($insert_c_query,$my_nuc) or die("Could not insert comment: [$insert_c_query] - " .  mysql_error());
   }
   mysql_free_result($comments_result);
}

mysql_free_result($result);
echo "</p>";
echo "<p> Conversion successful:  $nposts entries and $ncomments comments have been imported.</p>";
echo '<p> I\'d appreciate if you send me a mail to hgonzalez@gmail.com to inform me (a simple "it worked" or "it didnt work" would suffice")</p>';
echo "<b>Enjoy BLOG:CMS!</b><hr>";

?>

</body></html>


<?php

/////////////////////////////////// info ////////////////////////////////////
function infolink()
{
	return "<a href=\"?info=1\">Instructions</a>";
}

function  info()
{
	print <<<EOINFO
<div style="width: 500px;margin-left:20px;line-height:130%">
<br>
This little php script imports blog contents from 
MT (Movable Type) into BLOG:CMS. It is meant to be
used by people who intend to migrate a MT blog to
a new BLOG:CMS blog. It provides a simple wizard 
to set some parameters. <br>
  <p><b>
Requirements and limitations 
  </b></p><ul><li>
Needs <b>Mysql connection</b> to both blogs. In most cases, this
means that both your "old" (MT) and "new (BLOG:CMS)
blogs should reside in the same server (not strictly necessary, though).
And, of course, your MT blog <i>must</i> use Mysql!
	<li>
Only <b>imports posts and comments</b>. Does not import authors or
cathegories (they should be created beforehand in your BLOG:CMS blog),
nor trackbacks.
	<li>
Programmed for <b>Movable Type 2.6x</b> and <b>BLOG:CMS 3.0x</b>. 
Might work with other versions, I suppose.
	<li>
Does not know anything about charset encodings: you'd better have the same
settings in both blogs, or strange things might happen. <br>
The same goes for time-zone offsets.
<li> As usual: I don't assume any responsability, blah blah , use this tool
at your own risk blah blah blah...
	</ul>
	<p><b>
Instructions
	</b></p><ul><li>
Create a new -empty- BLOG:CMS blog. The script will
cowardly refuse to import into a populated blog, i.e. a blog 
with more posts than the MT one (You can alter this behaviour by
editing the FLAG_COWARD variable.)
	<li>
Add (manually, from your BLOG:CMS admin page) authors and categories to
your new blog.
They should mimic those of the MT blog, but they're not required to be
exactly the same. Later the script will allow you to map the 'old' authors 
and cathegories to the new ones.
	<li>
Download the script, open the file in a text-only editor and 
fill the database settings for both blogs. 
(You know what we're speaking about, dont you?)
	<li>
Upload the file, with name <b>movabletype.php</b>, to your server.
The location is unimportant, as long as you can access it from the web.
	<li>
Point your browser to the uploaded script and follow the directives.
The script won't try to write anything until you press the button <b>Go!</b>.
<li>
For obvious security reasons, delete afterwards the script from your server.
	</ul><p>
In case of trouble, you might try to contact me at hgonzalez@gmail.com
<br><br>
I'll also appreciate any report (successfull or not) for the usage of this script.
<br>
</div>
EOINFO;
}
?>