<?php
/**
 * Wiki farm structure creator
 *
 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
 * @author     Etienne MELEARD <etienne.meleard@cru.fr>
 */

global $farmconf;
$farmconf = array();

global $lang;
$lang = array();

exit(); // NO EXECUTION SECURITY

// Copy or move recursively one folder's content, avoid items specified in $avoid
function cp_r($src, $dest, $mv=false, $avoid=array(), $lvl=0) {
	if(in_array($src, $avoid)) return true;
	if(@is_file($src)) {
		$r = copy($src, $dest);
		chmod($dest, fileperms($src));
		if($mv) $r &= unlink($src);
		return $r;
	}
	
	if(!@is_dir($dest)) mkdir($dest, fileperms($src));
	
	$r = true;
	foreach(scandir($src) as $i) {
		if($i == '.' || $i == '..') continue;
		$r &= cp_r($src.'/'.$i, $dest.'/'.$i, $mv, $avoid, $lvl+1);
	}
	
	if($mv && $lvl) $r &= rmdir($src);
	
	return $r;
}

// Get or updates version
function version($s = null) {
	global $farmconf;
	$file = null;
	if(@file_exists($farmconf['farmer'].'lib/plugins/farm/installed')) $file = $farmconf['farmer'].'lib/plugins/farm/installed';
	if(@file_exists('./lib/plugins/farm/installed')) $file = './lib/plugins/farm/installed';
	if(!$file) return '';
	if(!$s) return trim(@file_get_contents($file));
	if($fp = fopen($file, 'w')) {
		fwrite($fp, $s);
		fclose($fp);
	}else die('Could not update install step');
}

// Get lang
function getLang($code, $data = null) {
	global $lang;
	if(!isset($lang[$code])) return '{'.strtoupper($code).'}';
	$str = $lang[$code];
	if(!is_null($data)) if(!is_array($data)) $data = array($data);
	if(is_array($data)) foreach($data as $d) $str = preg_replace('`%s`', $d, $str, 1);
	return $str;
}

// Print messages / exit
global $out;
$out = array();
function out($error = null) {
	global $farmconf;
	global $out;
	echo '<html>'."\n";
	echo '	<head><title>'.getLang('structure_title').'</title></head>'."\n";
	echo '	<body>'."\n";
	echo '		<ul>'."\n";
	foreach($out as $o) echo '			<li>'.getLang($o).'</li>'."\n";
	echo '		</ul>'."\n";
	if($error) {
		echo '		<div style="border:2px solid red;background-color:tomato;padding:15px;margin:25px;font-size:1.5em;font-weight:bold">'."\n";
		echo '			'.getLang($error)."\n";
		echo '		</div>'."\n";
	}else{
		echo '		<div style="border:2px solid lime;padding:15px;margin:25px;font-weight:bold">'."\n";
		echo '			'.getLang('structure_success', $farmconf['farmwebroot'].$farmconf['farmer'].'?do=admin&page=farm')."\n";
		echo '		</div>'."\n";
	}
	echo '	</body>'."\n";
	echo '</html>';
	exit();
}

function aconvform($l) {
	global $out;
	echo '<html>'."\n";
	echo '	<head><title>'.getLang('structure_title').'</title></head>'."\n";
	echo '	<body>'."\n";
	echo '		<form action="?aconv" method="post">'."\n";
	echo '			<h2>'.getLang('structure_convert_to_animals')."</h2><br />\n";
	foreach($l as $i) echo '			<input id="id_'.$i.'" type="checkbox" name="aconv_'.$i.'" /><label for="id_'.$i.'"> <b>'.$i.'</b></label> : configure <select onchange="document.getElementById(\'id_'.$i.'\').checked=true;" name="aconf_'.$i.'"><option selected="selected" value="0">local.php</option><option value="1">local.protected.php</option></select><br />'."\n";
	echo '			<input type="submit" name="doaconv" value="'.getLang('btn_next').'" />'."\n";
	echo '			<input type="hidden" name="out" value="'.implode(',', $out).'" />'."\n";
	echo '		</form>'."\n";
	echo '	</body>'."\n";
	echo '</html>';
	exit();
}

switch(version(null)) {
	case '' :
		// Create directories
		$mvfarmer = false;
		if(!@is_dir(realpath($farmconf['farmfsroot'].$farmconf['farmer']))) {
			if(!@mkdir($farmconf['farmfsroot'].$farmconf['farmer'], 0755)) out('structure_cannotcreatefarmerdir_failure');
			$out[] = 'structure_farmerdircreated';
			$mvfarmer = true;
		}
		
		if((realpath($farmconf['farmfsroot'].$farmconf['barn']) != realpath($farmconf['farmfsroot'])) && !@is_dir(realpath($farmconf['farmfsroot'].$farmconf['barn']))) {
			if(!@mkdir($farmconf['farmfsroot'].$farmconf['barn'], 0755)) out('structure_cannotcreatebarndir_failure');
			$out[] = 'structure_barndircreated';
		}
		
		version('0.1');
	
	case '0.1' :
		// Move dokuwiki
		if($mvfarmer) {
			if(!cp_r(
				'.',
				$farmconf['farmfsroot'].$farmconf['farmer'],
				true,
				array('./'.basename(__FILE__), './'.trim($farmconf['farmer'], '/'), './'.trim($farmconf['barn'], '/'))
			)) out('structure_cannotmovedw_failure');
			$out[] = 'structure_dwmoved';
		}
		
		version('0.2');
	
	case '0.2' :
		// Updates DokuWiki htaccess
		$file = $farmconf['farmfsroot'].$farmconf['farmer'].'.htaccess';
		if(!@file_exists($file)) $file = $farmconf['farmfsroot'].$farmconf['farmer'].'.htaccess.dist';
		if(@file_exists($file)) {
			copy($file, $file.'.orig');
			if($htaccess = @file_get_contents($file)) {
				$wr = $farmconf['farmwebroot'].$farmconf['farmer'];
				if(preg_match('`^([^:]+://)?([^/]+)?/?(.*)$`i', $wr, $m)) $wr = $m[3];
				$htaccess = preg_replace('`RewriteBase\s+[a-zA-Z0-9/._-]+`', 'RewriteBase /'.trim($wr, '/'), $htaccess);
				if($fp = fopen($file, 'w')) {
					fwrite($fp, $htaccess);
					fclose($fp);
					$out[] = 'structure_rewritefileupdated';
				}else out('structure_couldnotupdaterewritefile');
			}else out('structure_couldnotloadrewritefile');
		}
		
		version('0.3');
	
	case '0.3' :
		// Copy preload file
		if(@file_exists($farmconf['farmfsroot'].$farmconf['farmer'].'inc/preload.php')) copy($farmconf['farmfsroot'].$farmconf['farmer'].'inc/preload.php', $farmconf['farmfsroot'].$farmconf['farmer'].'inc/preload.php.orig');
		if(!copy($farmconf['farmfsroot'].$farmconf['farmer'].'lib/plugins/farm/install/preload.php', $farmconf['farmfsroot'].$farmconf['farmer'].'inc/preload.php')) out('structure_couldnotcopypreloadfile');
		$out[] = 'structure_preloadfilecopied';
		
		version('0.4');
	
	case '0.4' :
		if(!@is_dir($farmconf['farmfsroot'].$farmconf['barn'].$farmconf['animaltemplate'])) {
			// Move animal default template
			if(!@mkdir($farmconf['farmfsroot'].$farmconf['barn'].$farmconf['animaltemplate'], 0755)) out('structure_couldnotcreateanimaltpldirectory');
			if(!cp_r(
				$farmconf['farmfsroot'].$farmconf['farmer'].'lib/plugins/farm/install/animaltemplate',
				$farmconf['farmfsroot'].$farmconf['barn'].$farmconf['animaltemplate']
			)) out('structure_couldnotcopyanimaltpl');
			$out[] = 'structure_animaltplcopied';
			
			// Create animal default template meta
			if($fp = fopen($farmconf['farmfsroot'].$farmconf['barn'].'/'.$farmconf['animaltemplate'].'/animal.meta', 'w')) {
				fwrite($fp, 'creation_date : '.time());
				fclose($fp);
				$out[] = 'structure_animaltplmetafilecreated';
			}else out('structure_couldnotcreateanimaltplmetafile');
		}
		
		$d = array();
		foreach(scandir($farmconf['farmfsroot'].$farmconf['barn']) as $i) {
			if($i == '.' || $i == '..') continue;
			if($i == $farmconf['animaltemplate']) continue;
			if(!@is_dir($farmconf['farmfsroot'].$farmconf['barn'].$i)) continue;
			if((realpath($farmconf['farmfsroot'].$farmconf['barn']) == realpath($farmconf['farmfsroot'])) && ($i == trim($farmconf['farmer'], '/'))) continue;
			$d[] = $i;
		}
		if(count($d)) { // barn already existed with animals directories ?
			if(isset($_POST['doaconv'])) {
				if(isset($_POST['out'])) $out = explode(',', $_POST['out']);
				foreach($d as $i) {
					if(isset($_POST['aconv_'.$i])) {
						if($fp = fopen($farmconf['farmfsroot'].$farmconf['barn'].'/'.$i.'/animal.meta', 'w')) {
							fwrite($fp, 'creation_date : '.time());
							fclose($fp);
						}
						$c = isset($_POST['aconf_'.$i]) ? ($_POST['aconf_'.$i] ? 'local.protected.php' : 'local.php') : 'local.php';
						
						$ctn = @file_get_contents($farmconf['farmfsroot'].$farmconf['barn'].'/'.$i.'/conf/'.$c);
						$fp = fopen($farmconf['farmfsroot'].$farmconf['barn'].'/'.$i.'/conf/'.$c, 'w');
						if($fp) {
							$added = false;
							foreach(explode("\n", $ctn) as $l) {
								if(preg_match('`^\s*\$conf\[\'basedir\'\]\s*\=\s*DOKU_ANIMAL_BASEDIR\s*\.\s*DOKU_FARM_ANIMAL;`', $l)) $added = true;
								if(!$added) {
									if(preg_match('`^\s*(include|require|\?>)`', $l)) {
										fwrite($fp, '$conf[\'basedir\'] = DOKU_ANIMAL_BASEDIR.DOKU_FARM_ANIMAL;');
										$added = true;
									}
								}
								fwrite($fp, $l."\n");
							}
							if(!$added) fwrite($fp, '$conf[\'basedir\'] = DOKU_ANIMAL_BASEDIR.DOKU_FARM_ANIMAL;');
							fclose($fp);
						}
					}
				}
			}else aconvform($d);
		}
		
		version('0.5');
	
	case '0.5' :
		// Remove structure creator script
		if(!@unlink(__FILE__)) out('structure_couldnotremovestructurecreatorscript');
		
		version('0.99'); // installation successfull !
}

out();

?>
