<?php
set_time_limit('240');
function addRelease($input) {
	$debug = false;
	// D�finition des variables de travail
	$lastVersions_e = explode('|', file_get_contents('lastVersions.txt'));
	$lastVersions_e_backup = $lastVersions_e;
	if ($input == 'r') {
		$lastVersions_e[1] = 'UP';
	} else {
		$lastVersions_e[3] = 'UP';
	}
	// Enregistrement des donn�es d'ajout
	$lastVersions_e[0] = time();
	$lastVersions_txt = fopen('lastVersions.txt', 'w');
	fwrite($lastVersions_txt, implode('|', $lastVersions_e));
	fclose($lastVersions_txt);
	if ($input == 'r') {
		$type = 'r';
		$url = 'http://s3.amazonaws.com/MinecraftDownload/minecraft.jar';
	} else {
		$type = 'apr';
		$url = 'http://assets.minecraft.net/'.$input.'/minecraft.jar';
	}
	
	// Chargement du XML
	$data = new DomDocument();
	$data->load('data.xml');
	$dataNode = $data->getElementsByTagName('data')->item(0);
	$mcupdatesNode = $dataNode->getElementsByTagName('mcupdates')->item(0);
	$id = $mcupdatesNode->getAttribute('total')+1;
	$releaseS = $mcupdatesNode->getElementsByTagName('release');
	$release = $releaseS->item($releaseS->length-1);
	
	// Creation du noeud XML
	$releaseNode = $data->createElement('release');
	$mcupdatesNode->appendChild($releaseNode);
	$infosNode = $data->createElement('infos');
	$releaseNode->appendChild($infosNode);
	$files = $data->createElement('files');
	$releaseNode->appendChild($files);
	
	// Extraction et copie de minecraft.jar
	$directory = $id.' - '.$lastVersions_e[0].' ('.rand(1, 1000).')';
	if (!mkdir($directory) OR !copy($url, $directory.'/minecraft.jar')) { return 'ERREUR Impossible de copier le fichier ou de cr�er un nouveau dossier.';}
    $zip = new ZipArchive;
    if ($zip->open($directory.'/minecraft.jar') AND mkdir($directory.'/content')) {
        $zip->extractTo($directory.'/content');
        $zip->close();
    } else {
        return 'ERREUR Impossible d\'extraire le fichier ou de cr�er un nouveau dossier.';
    }
	$md5 = md5_file($directory.'/minecraft.jar');
	directoryConstruct($directory.'/content', $files, $data, directoryOld($release));
	
	// Detection de $givenName
	// Code par @EphysPatato
	$minecraft_class = file_get_contents($directory.'/content/net/minecraft/client/Minecraft.class');
	$givenName = 'false';
	if (preg_match('/Minecraft Minecraft (.+)Minecraft main/', $minecraft_class, $matches)) {
		$givenName = '';
		$givenName_w = $matches[count($matches)-1];
		for( $i = 0 ; $i < strlen($givenName_w) ; $i++ )
		{
			$givenName_cw = substr($givenName_w, $i, 1);
			if(($givenName_cw >= 'a' && $givenName_cw <= 'z') || ($givenName_cw >= 'A' && $givenName_cw <= 'Z') || ($givenName_cw >= '0' && $givenName_cw <= '9') || $givenName_cw == '|' || $givenName_cw == '.' || $givenName_cw == '_' || $givenName_cw == '-')
				$givenName .= $givenName_cw;
		}
	}
	// Sp�cifications selon le type de release
	if ($type == 'r') {
		$name = $givenName;
		$lastVersions_e[1] = $name;
		$lastVersions_e[2] = $md5;
		$infosNode->setAttribute('wiki', 'http://www.minecraftwiki.net/wiki/Version_history#'.$name);	
	} else {
		$name = $input;
		$lastVersions_e[3] = $name;
		$lastVersions_e[4] = $md5;
		$infosNode->setAttribute('wiki', 'http://www.minecraftwiki.net/wiki/Version_history/Development_versions#'.$name);
	}
	
	// Mise des infos dans le XML
	$releaseNode->setAttribute('id', $id);
	$releaseNode->setAttribute('name', $name);	
	$releaseNode->setAttribute('type', $type);
	$infosNode->setAttribute('givenName', $givenName);
	$infosNode->setAttribute('directory', $directory);
	$infosNode->setAttribute('link', $url);
	$infosNode->setAttribute('size', filesize($directory.'/minecraft.jar'));
	$infosNode->setAttribute('md5', $md5);
	$infosNode->setAttribute('sha1', sha1_file($directory.'/minecraft.jar'));
	$infosNode->setAttribute('date', $lastVersions_e[0]);
	$infosNode->setAttribute('shortDescription', 'false');
	$mcupdatesNode->setAttribute('total', $id);
	
	// Sauvegarde finale
	$lastVersions_e[0] = time();
	$lastVersions_e[5] = $id;
	$lastVersions_e[6] = $name;
	$lastVersions_e[7] = $type;
	$id = $mcupdatesNode->setAttribute('total', $id);
	$lastVersions_f = fopen('lastVersions.txt', 'w');
	$lastError = error_get_last();
	if ($debug) { echo substr($lastError['file'], -14); }
	if ($lastError /*AND $lastError['type']!= 2 */AND substr($lastError['file'], -14) == 'addrelease.php') {
		fwrite($lastVersions_f, implode('|', $lastVersions_e_backup));
		rrmdir($directory);
		return 'ERREUR "'.$lastError['message'].'" (type : '.$lastError['type'].') dans '.$lastError['file'].' ligne '.$lastError['line'].'.';
	} else {
		$data->save('data.xml');
		fwrite($lastVersions_f, implode('|', $lastVersions_e));
		fclose($lastVersions_f);
		return implode('|', $lastVersions_e);
	}
}
function directoryConstruct($directoryName, $XML, $data, $array) {
	$directory = opendir($directoryName); 
	while($file = readdir($directory)) {
		if ($file != '.' AND $file != '..') {
			if (is_dir($directoryName.'/'.$file)) {
				$newDirectory = $data->createElement('dir');
				$XML->appendChild($newDirectory);
				$newDirectory->setAttribute('name', $file);
				if (isset($array[$file])) {
					$newDirectory->setAttribute('comparaison', 'same');
					directoryConstruct($directoryName.'/'.$file, $newDirectory, $data, $array[$file]);
				} else {
					$newDirectory->setAttribute('comparaison', 'added');
					directoryConstruct($directoryName.'/'.$file, $newDirectory, $data, array());
				}
			} else {
				$fileXML = $data->createElement('file');
				$XML->appendChild($fileXML);
				$fileXML->setAttribute('name', $file);
				$fileXML->setAttribute('md5', md5_file($directoryName.'/'.$file));
				if (isset($array[$file])) {
					if ($array[$file] == md5_file($directoryName.'/'.$file)) {
						$fileXML->setAttribute('comparaison', 'same');
					} else {
						$fileXML->setAttribute('comparaison', 'change');
					}
				} else {
					$fileXML->setAttribute('comparaison', 'added');
				}
				// TODO Verifier si un fichier a �t� supprim�	
			}
		}
	}
}
function directoryOld($XML) {
$array = array();
	$dirS = $XML->getElementsByTagName('dir');
	for ($c = $dirS->length, $i = 0; $i < $c; $i++) {
		$dir = $dirS->item($i);
		$array[$dir->getAttribute('name')]= directoryOld($dir);
	}
	$fileS = $XML->getElementsByTagName('file');
	for ($c = $fileS->length, $i = 0; $i < $c; $i++) {
		$file = $fileS->item($i);
		$array[$file->getAttribute('name')] = $file->getAttribute('md5');
	}
	return $array;
}
function rrmdir($dir) { // Par holger1@NOSPAMzentralplan.de
   if (is_dir($dir)) { 
     $objects = scandir($dir); 
     foreach ($objects as $object) { 
       if ($object != "." && $object != "..") { 
         if (filetype($dir."/".$object) == "dir") rrmdir($dir."/".$object); else unlink($dir."/".$object); 
       } 
     } 
     reset($objects); 
     rmdir($dir); 
   } 
 } 
?>