<?php
ini_set("display_errors", "on");
error_reporting(E_ALL ^ E_NOTICE);
require ('commonFunctions.php');

function getItemListing($n) {
    $repIn = array("<br />");
    $repOut = array("&lt;br /&gt;");
	$cm = "/\<text xml:space=\"preserve\" bytes=\"[0-9]+\"\>/";
	$ma = array();
	preg_match_all($cm, $n, $ma);
	$om = array();
	$nm = array();
	foreach ($ma as $mb) {
		foreach ($mb as $mc) {
			array_push($om, $mc);
		}
	}
	$n = str_replace($om, '<text-p>', $n);
    $n = str_replace($repIn, $repOut, $n);
    $breaks = array("\r\n<br />", "<br />\r\n", "\r<br />", "<br />\r", "\n<br />", "<br />\n", "\r\n", "\r", "\n");
    $n = str_replace($breaks, '[br]', $n);
    $titlePattern = "/\<title\>.+\<\/title\>/";
    $textPattern = "/\<text-p\>.+\<\/text\>/m";
    $ta = array();
	$splode = explode('<page>', $n);
    array_shift($splode);
    foreach ($splode as $sp) {
        $spl = explode('</page>', $sp);
        $sp = $spl[0];
        $ti = array();
        $te = array();
        preg_match_all($titlePattern, $sp, $ti);
        preg_match_all($textPattern, $sp, $te);
		foreach ($ti as $tp) {
            foreach ($tp as $tt) {
                if (strpos($tt, "<title>") !== false) {
                    $tr = str_replace(array("<title>", "</title>"), '', $tt);
                }
            }
        }
        foreach ($te as $tq) {
            foreach ($tq as $ts) {
				if (strpos($ts, "<text-p>") !== false) {
					$ts = str_replace('[br]', "\r\n<br />", $ts);
					$dr = str_replace(array("<text-p>", "</text>"), '', $ts);
				}
            }
        }
		array_push($ta, array($tr, $dr));
    }
    return ($ta);
}

function removeRedundantLinks($l) {
    $pattern = "/\[\[([a-zA-Z0-9 .\+\?\"':()-]+)\|([a-zA-Z0-9 .\+\?\"':()-]+)\]\]/";
	$l = str_replace(' Plus ', ' +', $l);
	$match = array();
    $prematch = array();
    $rematch = array();
	$linkOut = array("[[", "]]");
    preg_match_all($pattern, $l, $match);
    if (count($match) > 0) {
        //print_r($match);
        //print "\r\n<br />";
        foreach ($match as $m) {
            foreach ($m as $n) {
                if (strpos($n, '|') !== false && array_search($n, $prematch) === false) {
				    $rep = str_replace($linkOut, '', $n);
				    $splode = explode('|', $rep);
					if (trim($splode[0]) == trim($splode[1])) {
						$o = "[[" . $splode[0] . ']]';
						array_push($prematch, $n);
                        array_push($rematch, $o);
					} else {
                        //array_push($prematch, $n);
                        //$o = str_replace('|', '{{!}}', $n);
                        //array_push($rematch, $o);
					}
                }
            }
        }
        //print_r ($prematch);
        //print "\r\n<br />";
        //print_r ($rematch);
        //print "\r\n<br /><br /><br />";
        $l = str_replace($prematch, $rematch, $l);
    }
	return($l);
}

function getReplacement($r, $p, $subbr=false, $f='', $rp='', $rm='') {
    $bracketsIn = array("{{!}}", "{{Fire}}", "{{Ice}}", "{{Wind}}", "{{Wir}}", "{{Earth}}", "{{Thunder}}", "{{Lightning}}", "{{Water}}", "{{Light}}", "{{Dark}}");
	$bracketsOut = array("[%!%]", "[%fire%]", "[%ice%]", "[%wind%]", "[%wind%]", "[%earth%]", "[%thunder%]", "[%thunder%]", "[%water%]", "[%light%]", "[%dark%]");
	$itembracketsIn = array("{{Item Info}}", "{{Item Image}}");
	
	$re = removeRedundantLinks($r);
	$re = str_replace("&quot;", '"', $re);
	$itemInfo = (strpos($re, "{{Item Info}}") !== false && $rm != "{{Item Info}}") ? "\r\n<br />{{Item Info}}" : '';
	$check = false;
	if ($rm == "{{Item Info}}" && strpos($re, "{{Item Info}}") !== false) {
		$check = true;
	}
	$re = str_ireplace($bracketsIn, $bracketsOut, $re);
	$re = str_replace($itembracketsIn, '', $re);
	$re = str_replace("[[category:", "[[Category:", $re);
	$patterns = array();
	$patterns[0] = "/\{\{item[^}]+\}\}/";
	$patterns[0] = "/\{\{item[^}]+\}\}/";
	$patterns[1] = "/\{\{usable item[^}]+\}\}/";
	$patterns[2] = "/\{\{weapon[^}]+\}\}/";
	$patterns[3] = "/\{\{armor[^}]+\}\}/";
	$patterns[4] = "/\{\{enchantment[^}]+\}\}/";
	
	$match = array();
    $prematch = array();
    foreach($patterns as $k => $pat) {
	    preg_match_all($pat, $re, $match);
		//print_r ($match);
		//print "\r\n<br />Count = " . count($match) . "\r\n<br />";
    
		if (count($match[0]) > 0) {
		    array_push($prematch, $match[0][0]);
		}
	}
	$mac = count($prematch);
	//print_r ($prematch);
    //print "\r\n<br />";
	//print "$p\r\n<br /><br />";
	$sp = explode('|', $p);
	$wikiName = $sp[2];
    $re = str_replace($prematch, '', $re);
	$re = str_replace($bracketsOut, $bracketsIn, $re);
	$re = trim($re);
	
	$breaks = array("\r\n<br />", "<br />\r\n", "\r<br />", "<br />\r", "\n<br />", "<br />\n", "<br />", "\r\n", "\r", "\n");
	$re = str_replace($breaks, "[br]", $re);
	//$re = str_replace($breaks, $breaksOut, $re);
	$re = str_replace("[br][br][br][br][br]", "[br]", $re);
	$re = str_replace("[br][br][br][br]", "[br]", $re);
	$re = str_replace("[br][br][br]", "[br]", $re);
	
	for ($i=0; $i<$mac; $i++) {
		if (substr($re, 0, 4) == "[br]") {
			$re = substr($re, 4);
		}
	}
	
	$re = str_replace("[br]", "\r\n<br />", $re);
	
	$otest = implode("\r\n<br />", $prematch);
	$otest = str_replace($bracketsOut, $bracketsIn, $otest);
	$newHeader = writeTemplate($p, false, false, true);
	$newHeader = str_replace('{{Item Info}}', '', $newHeader);
	//$catPat = "/\[\[Category:([a-zA-Z0-9 .\+\?\"':()-\|]+)\]\]/";
	$catPat = "/\[\[Category:(^])+\]\]/";
	$catPat = "/\[\[Category:(.)+\]\]/";
	$match1 = array();
    $prematch1 = array();
    preg_match_all($catPat, $newHeader, $match1);
    if (count($match1) > 0) {
        //print_r($match1);
        //print "\r\n<br />";
        foreach ($match1 as $m) {
            foreach ($m as $n) {
                if (strpos($n, 'Category:') !== false && array_search($n, $prematch1) === false) {
				    array_push($prematch1, $n);
                }
            }
        }
        //print_r ($prematch1);
        //print "\r\n<br />";
        $newHeader = str_replace($prematch1, '', $newHeader);
    }
	
	$otest = str_replace($breaks, " ", $otest);
	$ntest = str_replace($breaks, " ", $newHeader);
	$otest = str_replace("  ", " ", $otest);
	$ntest = str_replace("  ", " ", $ntest);
	$otest = trim($otest);
	$ntest = trim($ntest);
	$match2 = array();
    $prematch2 = array();
	preg_match_all($catPat, $re, $match2);
    if (count($match2) > 0) {
        //print_r($match2);
        //print "\r\n<br />";
        foreach ($match2 as $m) {
            foreach ($m as $n) {
                if (strpos($n, 'Category:') !== false && array_search($n, $prematch2) === false) {
				    array_push($prematch2, $n);
                }
            }
        }
        //print_r ($prematch2);
        //print "\r\n<br />";
        $re = str_replace($prematch2, '', $re);
    }
	$prematch1 = implode(' ', $prematch1);
	$prematch2 = implode(' ', $prematch2);
	$prematch = $prematch1 . " " . $prematch2;
	$prematcha = explode('[[', $prematch);
	$prematch = array();
	foreach ($prematcha as $k => $p) {
		if (strlen($p) > 0) {
			array_push($prematch, '[['.trim($p));
		}
	}
	
	$prematch = array_unique($prematch);
	$categories = implode(' ', $prematch);
	$categories = (strlen($categories) > 0) ? "\r\n<br />$categories" : '';
	$re = trim($re);
	if (substr($categories, -10) == "\r\n<br />") {
		$categories = substr($categories, 0, -10);
	}
	if (substr($re, 0, 4) == "[br]") {
		$re = substr($re, 4);
	}
	$re = $newHeader . $re . $categories . $itemInfo;
	$re = str_replace("\r\n\r\n", "\r\n", $re);
	$re = str_replace("\r\n<br />\r\n<br />\r\n<br />", "\r\n<br />\r\n<br />", $re);
	$re = str_replace("\r\n<br />\r\n<br />\r\n<br />", "\r\n<br />\r\n<br />", $re);
	$re = str_replace("\r\n<br />\r\n<br />{{Item Info}}", "\r\n<br />{{Item Info}}", $re);
	$re = str_replace('"', '""', $re);
	if (strlen($f) > 0 && strlen($rm) > 0 && strpos($re, $f) !== false) {
		$check = true;
		$re = str_replace($f, $rp, $re);
	}
	if (strlen($rm) > 0 && strpos($re, $rm) !== false) {
		$check = true;
		$re = str_replace($rm, '', $re);
	}
	if (substr($re, -6) == "<br />") {
		$re = substr($re, 0, -6);
	}
	if ($subbr == true) {
		$re = str_replace($breaks, "[br]", $re);
		$re = str_replace('[br]', "\r\n", $re);
	}
	$re = trim($re);
	if ($otest != $ntest || $check == true) {
		if ($subbr == 'yes') {
			$safeNameIn = array(' ', '.');
			$sameNameOut = array('_', '_');
			$name = str_replace($safeNameIn, $safeNameOut, $wikiName);
			$name = urlencode($name);
			print "<p><b>$wikiName</b> <input type=\"checkbox\" name=\"" . $name . "_omit\" value=\"yes\">Omit entry\r\n<br /><textarea name=\"$name\" id=\"$name\" cols=\"76\" rows=\"20\">";
			global $nameList;
			array_push($nameList, $name);
		}
		
		$wikiName = str_replace(' ', '_', $wikiName);
		print urlencode($wikiName) . ", \"$re\"";
		if ($subbr != true) {
			print "\r\n<br />";
		} else {
			print "</textarea>\r\n</p>";
		}
		return 1;
	} else {
		return 0;
	}
}

$action = $_GET['action'];
$textListing = $_POST['textListing'];
$individual = $_POST['individual'];
$find = $_POST['find'];
$replace = $_POST['replace'];
$remove = $_POST['remove'];
$nameList = $_POST['nameList'];

if (strlen($action) == 0) {
    print "Updates item pages with new item, usable item, weapon, armor, and enchantment templates.
	Handy for version update changes where many, many items are updates.<br />
	Copy XML from the export utility into the box below.
  <form id=\"form1\" name=\"form1\" method=\"post\" action=\"Item-Rewrite-O-Tron.php?action=readList\">
  <p><label>Text Listing<br />
  <textarea name=\"textListing\" id=\"textListing\" cols=\"76\" rows=\"20\"></textarea>
  </label>
  </p>
  <p><input type=\"checkbox\" name=\"individual\" value=\"yes\">Edit pages indivudually.
  </p>
  <p><label>Find and replace<br />
  <textarea name=\"find\" id=\"textListing\" cols=\"35\" rows=\"10\"></textarea><textarea name=\"replace\" id=\"textListing\" cols=\"35\" rows=\"10\"></textarea>
  </label>
  </p>
  <p><label>Remove<br />
  <textarea name=\"remove\" id=\"textListing\" cols=\"35\" rows=\"10\"></textarea>
  </label>
  </p>
  <p>
    <label>
    <input type=\"submit\" name=\"Submit\" id=\"Submit\" value=\"Submit\" />
    </label>
    <label>
    <input type=\"reset\" name=\"Reset\" id=\"Reset\" value=\"Reset\" />
    </label>
  </p>
</form>";
} elseif ($action == 'readItems') {
	$names = explode("|$", $nameList);
	$fields = array();
	$c = 0;
	foreach($names as $n) {
		$fields[$n] = $_POST[$n];
		$omit = '';
		$omit = $_POST[$n . "_omit"];
		//print "$n | $omit \r\n<br />";
		$fields[$m] = trim($fields[$n]);
		if (substr($fields[$n], -4) == "\r\n") {
			$fields[$n] = substr($fields[$n], 0, -4);
		}
		$fields[$n] = str_replace("\r\n", "\r\n<br />", $fields[$n]);
		if (strlen($omit) == 0 && strlen($fields[$n]) > 0) {
			print $fields[$n] . "\r\n<br />";
			$c++;
		}
	}
	$it = ($c == 1) ? '' : 's';
	print "\r\n<br /><br /><b>iMacros- $c iteration$it.</b>";
} else {
	$c = 0;
	$itemArray = getItemListing($textListing);
	$array = @file('ultimateParse.txt');
    $itemList = array();
	$nameList = array();
	if ($individual == 'yes') {
		print "<form id=\"form1\" name=\"form1\" method=\"post\" action=\"Item-Rewrite-O-Tron.php?action=readItems\">";
	}
    foreach ($array as $line) {
        $sp = explode('|', $line);
	    $itemList[$sp[2]] = $line;
    }
	$sb = ($individual == 'yes') ? true : false;
	foreach($itemArray as $page) {
	    $raw = $itemList[$page[0]];
		if (strlen($raw) > 0) {
			$original = $page[1];
			$t = getReplacement($original, $raw, $sb, $find, $replace, $remove);
			$c += $t;
		}
	}
	if ($c > 0 && $individual != 'yes') {
		$it = ($c == 1) ? '' : 's';
		print "\r\n<br /><br /><b>iMacros- $c iteration$it.</b>";
	} elseif ($individual == 'yes') {
		$nameList = implode('|$', $nameList);
		print "<p>
	<input type=\"hidden\" name=\"nameList\" id=\"nameList\" value=\"$nameList\">
    <label>
    <input type=\"submit\" name=\"Submit\" id=\"Submit\" value=\"Submit\" />
    </label>
    <label>
    <input type=\"reset\" name=\"Reset\" id=\"Reset\" value=\"Reset\" />
    </label>
  </p>
</form>";
	}
}
?>
