<?php 
// DEFAULT CONFIGURATION 
$add_camel_case_space="no";
$swop_words="no";
$removeme_string="";
$prefix="";

// NO ALTERING BEYOND THIS POINT

function print_page_top(){
	echo "
<html>
<head>
<title>Results</title>
<link rel=\"stylesheet\" type=\"text/css\" href=\"base.css\"/>
</head>
<body>";
}
function print_page_base(){
	echo "
	</body>
</html>";
}

function add_camel_case_spaces($camelword){
	//	$toreplace=preg_replace("[a-z][A-Z]","[a-z]\ [A-Z]",$camelword);
	$result="";
	preg_match_all('/[A-Z,���,-_]+[a-z,����,0-9-_]*/', $camelword, $matches);
        for ($i=0; $i<count($matches[0]); $i++) {
                if ($i>0) $result .=" ";
                $result .= $matches[0][$i];
        }
	return($result);		
}

function remove_underscores($term){
	// To be used to remove underscores in wiki words
	
	return ($term);
}
function do_swop_words($phrase){
	$tmpvar=split(' ',$phrase);
	if(sizeof($tmpvar)>2){
		$tmpvar2=$tmpvar[sizeof($tmpvar)];
		$tmpvar[sizeof($tmpvar)]=$tmpvar[0];
		$tmpvar[0]=$tmpvar2;
		$phrase=implode(" ",$tmpvar);
		$phrase=ltrim($phrase);
	}
	return ($phrase);
}

if(isset($HTTP_GET_VARS['addspace'])){
	if($HTTP_GET_VARS['addspace']=="true"){
		$add_camel_case_space="yes";
	}
}

if(isset($HTTP_GET_VARS['swopwords'])){
	if($HTTP_GET_VARS['swopwords']=="true"){
		$swop_words="yes";
	}
}


if(isset($HTTP_GET_VARS['rooturl'])){
  $urltodl=$HTTP_GET_VARS['rooturl'];
  $temp=split('/',$urltodl);
  $currenturlspace=str_replace($temp[sizeof($temp)-1],"",$urltodl);
  // if urltodl doesn't finish in ?raw=on, add it! 
  if(!preg_match('/\?raw=on$/',$urltodl)){
	$urltodl.="?raw=on";
  }

  if(!isset($HTTP_GET_VARS['prefix'])){
  	$prefix="";
  } else {
	$prefix=$HTTP_GET_VARS['prefix'];
  }
  if(!isset($HTTP_GET_VARS['removeme'])){
	$removeme_string="";
  } else {
	$removeme_string=$HTTP_GET_VARS['removeme'];
  }
  if(!$handle = fopen("$urltodl", "rb")){
	exit("<html><body><br/><b>Page $urltodl isn't readable (may not exist!)</b> \n<br/><a href=\"javascript:back()\">Go back</a></body></html>");
  }
  $contents = '';
  $contentofbox='';
  $linkpages=array();
  $resulttotal="";
  while (!feof($handle)) {
    $contents .= fread($handle, 8192);
  }
  fclose($handle);
  $mycontents=split('<textarea readonly="readonly" wrap="virtual" rows="17" cols="70">',$contents); 
  //print_r($mycontents);
  $mypagecontents=split('</textarea>',$mycontents[1]);
  //print $mypagecontents[0];

  $mylines=split("\n",$mypagecontents[0]);
  for ($i=0;$i<sizeof($mylines); $i++){
	$mylines[$i]=ltrim($mylines[$i]);
	$linkhandled=0; 
	// detect and fix ='s, which are basically strange italic thingies 
	preg_match_all("/\ =((\S|\ |^\*\ )+)=\ /U",$mylines[$i],$foo);
        if(sizeof($foo[0])>0){
                for($j=0;$j<sizeof($foo[0]);$j++){
                        $replaceme=$foo[0][$j];
                        $toreplace=preg_replace("/=/","''",$replaceme);
                        $mylines[$i]=str_replace($replaceme,$toreplace,$mylines[$i]);

                }
        }

	if(preg_match("/^---\+\+\ /",$mylines[$i])){
		//echo "Title!";
		$mylines[$i]="===".preg_replace("/^---\+\+\ /","",$mylines[$i])."===";
	} else if(preg_match("/^---\+\ /",$mylines[$i])){
		$mylines[$i]="==".preg_replace("/^---\+\ /","",$mylines[$i])."==";
	} else if (preg_match("/^---\+\+\+\ /",$mylines[$i])){
                $mylines[$i]="===".preg_replace("/^---\+\+\+\ /","",$mylines[$i])."===";
	}  else if (preg_match("/^---\+\+\+\+\ /",$mylines[$i])){
                $mylines[$i]="===".preg_replace("/^---\+\+\+\+\ /","",$mylines[$i])."===";
        }

	if(preg_match("/^\\$/",$mylines[$i])){
		$mylines[$i]=preg_replace("/^\\$/","*",$mylines[$i]);
	}

	// Catch bold (*bold*)
 	//preg_match_all("/\*((\w|\ |\:)+)\*/",$mylines[$i],$foo);
 	preg_match_all("/\*[^\ ]((\S|\ |^\*\ )+)\*/U",$mylines[$i],$foo);
	if(sizeof($foo[0])>0){
		for($j=0;$j<sizeof($foo[0]);$j++){
			$replaceme=$foo[0][$j];
			$toreplace=preg_replace("/\*/","'''",$replaceme);
			$mylines[$i]=str_replace($replaceme,$toreplace,$mylines[$i]);
			
		}
	} 
	

	
	// Catch italic (_italic_)
	preg_match_all("/\ \_((\S|\ )+)\_\ /U",$mylines[$i],$foo);
	if(sizeof($foo[0])>0){
	 	for($j=0;$j<sizeof($foo[0]);$j++){
                        $replaceme=$foo[0][$j];
                        $toreplace=preg_replace("/\_/","''",$replaceme);
                        $mylines[$i]=str_replace($replaceme,$toreplace,$mylines[$i]);

                }


	}

	// Detect and fix double includes :( :( 
	// This reduces named wiki links ([[foo][bar]] to their CamelCase base 
	// it has to be done this way because otherwise, it doesn't work at all...
	// media wiki just doesn't do this function at all

	preg_match_all("/\[\[[A-Z][a-z][a-z]+([A-Z]|[a-z])+\]\]/",$mylines[$i],$foo);
	if(sizeof($foo[0])>0){
		for($j=0;$j<sizeof($foo[0]);$j++){
			$replaceme=$foo[0][$j];
			$toreplace=str_replace("[[","",$foo[0][$j]);
			$toreplace=str_replace("]]","",$toreplace);
			$mylines[$i]=str_replace($replaceme,$toreplace,$mylines[$i]);
		}
	}	

	// catch ones that start in Normalword
	preg_match_all("/\[\[[A-Z]([a-z])+[A-Z]([A-Z]|[A-Z0-9a-z-])+\]\[([A-Z]|[A-Z0-9a-z-])+\]\]/",$mylines[$i],$foo);
	if(sizeof($foo[0])>0){
		for($j=0;$j<sizeof($foo[0]);$j++){

			//print $foo[0][$j]."\n<br/>";
			$tempvar0=$foo[0][$j];
			$replaceme=$foo[0][$j];
			$replaceme=remove_underscores($replaceme);
			$tempvar1=split('\]\[',$tempvar0);
			$mylines[$i]=str_replace($replaceme,$toreplace,$mylines[$i]);
			$toreplace0=str_replace("[","","$tempvar1[0]");
			$toreplace1=str_replace("]","","$tempvar1[1]");
			$toreplace="[[".$toreplace0."|".$toreplace1."]]";
			if($toreplace0==$toreplace1){
				if($add_camel_case_space=="yes"){
					$toreplace0=add_camel_case_spaces($toreplace0);
					
				}
				$toreplace0=trim($toreplace0);
				$toreplace="[[$toreplace0]]";
			}
			$mylines[$i]=str_replace($replaceme,$toreplace,$mylines[$i]);
			$linkhandled=1;
		}
	}	

	preg_match_all("/\[\[[A-Z][a-z]+[A-Z]([A-Z]|[A-Z0-9a-z-])+\]\[([A-Z]|[A-Z0-9a-z-])+\]\]/",$mylines[$i],$foo);
	if(sizeof($foo[0])>0){
		for($j=0;$j<sizeof($foo[0]);$j++){
			//print $foo[0][$j]."\n<br/>";
			$tempvar0=$foo[0][$j];
			$replaceme=$foo[0][$j];
			$replaceme=remove_underscores($replaceme);
			$tempvar1=split('\]\[',$tempvar0);
			$toreplace0=str_replace("[","","$tempvar1[0]");
			$toreplace1=str_replace("]","","$tempvar1[1]");
			$toreplace="[[".$toreplace0."|".$toreplace1."]]";
			if($toreplace0==$toreplace1){
				$toreplace0=trim($toreplace0);
				$toreplace="[[$toreplace0]]";
			}
			if($add_camel_case_space=="yes"){
				$toreplace=add_camel_case_spaces($toreplace);
			}
			$mylines[$i]=str_replace($replaceme,$toreplace,$mylines[$i]);
		}
		$linkhandled=1;
		// Deal with them
		//$tempvar1=split("][",$foo[0][0]);
	}

	// detect and fix includes:
	// %INCLUDE{"AboutStandardsDocument"}%
	//preg_match_all("/%INCLUDE{\"(\S)+\"}%/",$mylines[$i],$foo);
	preg_match_all("/&#037;INCLUDE{\"(\S)+\"}&#037;/",$mylines[$i],$foo);
	if(sizeof($foo[0])>0 && $linkhandled<1){
		for($j=0;$j<sizeof($foo[0]);$j++){
			$replaceme=$foo[0][$j];
			$replaceme=remove_underscores($replaceme);
			//preg_match_all("/[A-Z][a-z][a-z]+[A-Z]([A-Z]|[a-z])+/",$mylines[$i],$foo);
			preg_match_all("/[A-Z][a-z]+([A-Z]+|[a-z]+)+/",$replaceme,$myres);
			if($add_camel_case_space=="yes"){
				$myreplacable=add_camel_case_spaces($myres[0][0]);
			} else {
				$myreplacable=$myres[0][0];
			}
			if($swop_words=="yes"){
				$myreplacable=do_swop_words($myreplacable);
			}
			$myreplacable=trim($myreplacable);	
			array_push($linkpages,$myres[0][0]);
			$toreplace="{{".$prefix.":".$myreplacable."}}";
			$mylines[$i]=str_replace($replaceme,$toreplace,$mylines[$i]);
		}
		$linkhandled=1;
	} else {

		// If you have internal includes and camelcase terms in one line, sorry :(
		// detect and fix CamelCases (media wiki won't see them)
		//preg_match_all("/[A-Z][a-z][a-z]+[A-Z]([A-Z]|[a-z])+^(\])/",$mylines[$i],$foo);
		preg_match_all("/(\ |\()[A-Z][A-Za-z][A-Za-z]+[A-Z]([A-Z0-9]|[A-Za-z0-9\-])+/",$mylines[$i],$foo);
		//preg_match_all('/[A-Z,���]+[a-z,����,0-9]*/', $mylines[$i], $foo); 
		if(sizeof($foo[0])>0){
        	        for($j=0;$j<sizeof($foo[0]);$j++){
        	                $replaceme=$foo[0][$j];
				$replaceme=remove_underscores($replaceme);
				if($add_camel_case_space=="yes"){
					$toreplace=add_camel_case_spaces($replaceme);
					$toreplace=trim($toreplace);
				} else {
					$toreplace=trim($replaceme);
				}
				if($swop_words=="yes"){
					$toreplace=do_swop_words($toreplace);
				} 
			
				// remove the word that needs removing here? removeme_string
				$posstoreplace=str_replace($removeme_string." ","",$toreplace);
				$posstoreplace=ereg_replace("$removeme_string$","",$posstoreplace);
				
				$toreplace=trim($posstoreplace);
				array_push($linkpages,ltrim($replaceme));
				if($prefix!=""){
					$toreplace=" [[$prefix:$toreplace]]";
				} else {
					$toreplace=" [[$toreplace]]";
				}

		                $mylines[$i]=str_replace($replaceme,$toreplace,$mylines[$i]);
	
	                }
	
		$linkhandled=1;
	        }
	} 
	if($linkhandled<1){
	// Detect and fix links (media wiki just wants [ http://url A name ]
	preg_match_all("/\[\[(\S|\ )+\]\[(\S|\ |\")+\]\]/",$mylines[$i],$foo);
	//print_r($foo);
	if(sizeof($foo[0])>0){
		for($j=0;$j<sizeof($foo[0]);$j++){
			$replaceme = $foo[0][$j];
		//	print "$replaceme \n<br/>";
			// We can just assume the shape of the thing and do substrings?
			$toreplace=str_replace("[[","[","$replaceme");
			$toreplace=str_replace("]["," ","$toreplace");
			$toreplace=str_replace("]]","]","$toreplace");
			$mylines[$i]=str_replace($replaceme,$toreplace,$mylines[$i]);
		}
	}
	}	


	$resulttotal.=$mylines[$i]."\n";	
	}

$resulttotal.="\n[[category:$prefix]]\n";
for($tmp=0;$tmp<sizeof($linkpages);$tmp++){
	$linkpages[$tmp]=ltrim( $linkpages[$tmp],"(");
}

print_page_top();
print "<h2>twiki to wikipedia conversion</h2>";
print "<table><tr><td valign=\"top\">";
print "<textarea readonly=\"readonly\" wrap=\"virtual\" rows=\"17\" cols=\"70\">";
print $resulttotal;
print "</textarea>";
print "<div class=\"linkclass\"><a href=\"".$_SERVER['PHP_SELF']."\">Do another page</a></div>";
print "</td>";
if(sizeof($linkpages)>0){
print "<td valign=\"top\">";
print "<p>Pages linked from this one:</p>";
print "<div class=\"linkclass\">";
for($test=0;$test<sizeof($linkpages);$test++){
	print "<a href=\"".$_SERVER['PHP_SELF']."?prefix=".$prefix."&rooturl=$currenturlspace$linkpages[$test]?raw=on\"\>$linkpages[$test]</a><br/>";
}
print "</div>";
print "</td>";
}
print "</tr></table>";
print_page_base();

exit;
}
?>
<?php
print_page_top();
?>
<h2>Migrating twiki to mediawiki</h2>

<form name="rootform" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<div class="info">Please provide url of twiki page to be migrated:</div>
<input class="box" type="text" name="rooturl"/>
<div class="info">Please provide expected MediaWiki prefix, if any:</div>
<input class="box" type="text" name="prefix"/>
<br/>
<div class="info"><input type="checkbox" value="true" name="addspace" /> Add spaces to CamelCase wiki names?</div>
<br/>
<div class="info"><input type="checkbox" value="true" name="swopwords" /> Swap round words in wiki name?</div>
<br/>
<div class="info">Term to remove from all wiki words?:</div>
<input class="box" type="text" name="removeme"/>
<br/>
<input type="submit"/>
</form>

</body>
</html>
