<?php
function rmove($src, $dest) {
	// If source is not a directory stop processing
	if(!is_dir($src)) return false;

	// If the destination directory does not exist create it
	if(!is_dir($dest)) {
		if(!mkdir($dest)) {
		return false;
		}
	}

	// Open the source directory to read in files
	$i = new DirectoryIterator($src);
	foreach($i as $f) {
		if($f->isFile()) {
		rename($f->getRealPath(), "$dest/" . $f->getFilename());
		}
		else if(!$f->isDot() && $f->isDir()) {
			rmove($f->getRealPath(), "$dest/$f");
			unlink($f->getRealPath());
		}
	}
	rmdir($src);
}

if(!isset($_POST['mysql_host'])) {
	?>
<!DOCTYPE HTML>
<html>
	<head>
		<title>WP-ADI</title>
		<link rel='stylesheet' id='open-sans-css'  href='https://fonts.googleapis.com/css?family=Open+Sans%3A300italic%2C400italic%2C600italic%2C300%2C400%2C600&#038;subset=latin%2Clatin-ext&#038;ver=4.4.1' type='text/css' media='all' />
		<link rel='stylesheet' id='install-css'  href='https://pdkwebs.nl/install.min.css?ver=4.4.1' type='text/css' media='all' />
	</head>
	<body>
		<a href="https://pdkwebs.nl" target="_blank" /><img src="https://pdkwebs.nl/wp-content/uploads/2013/03/logoPDKwebs.png" style="float:right;width:50px;" /></a>
		<h1>WP-ADI</h1>
		Welcome to WP-ADI: WordPress Auto Download & Install. This little PHP-script makes downloading and installing WordPress faster and easier than ever before with just 3 clicks.
		
		<h1>Needed information</h1>
		Please fill in your MySQL information, your desired table-prefix and the WordPress language you want to download and install. When clicking "WP-ADI", this script will automatically download and install the newest available version of WordPress for you. You will be redirected to the last step of the WordPress installation.<br /><br />
		All temporary files will be removed after installation, including this file (wp-adi.php).
		<br /><br />
		<form action="" method="post">
			<table>
				<tr>
					<td>MySQL Host:</td>
					<td><input type="text" name="mysql_host" value="<?php if(isset($_POST['mysql_host'])) { echo $_POST['mysql_host']; } else { echo 'localhost'; } ?>" /></td>
				</tr>
				<tr>
					<td>MySQL Database:</td>
					<td><input type="text" name="mysql_database" value="<?php if(isset($_POST['mysql_host'])) { echo $_POST['mysql_database']; } ?>" /></td>
				</tr>
				<tr>
					<td>MySQL Username:</td>
					<td><input type="text" name="mysql_username" value="<?php if(isset($_POST['mysql_host'])) { echo $_POST['mysql_username']; } ?>" /></td>
				</tr>
				<tr>
					<td>MySQL Password:</td>
					<td><input type="password" name="mysql_password" value="<?php if(isset($_POST['mysql_host'])) { echo $_POST['mysql_password']; } ?>" /></td>
				</tr>
				<tr>
					<td>WordPress Prefix:</td>
					<td><input type="text" name="wordpress_prefix" value="wp_" value="<?php if(isset($_POST['mysql_host'])) { echo $_POST['wordpress_prefix']; } else { echo 'wp_'; } ?>" /></td>
				</tr>
				<tr>
					<td>WordPress Language:</td>
					<td>
						<select name="wordpress_language">
							<option value="en"<?php if(isset($_POST['mysql_host'])) { if($_POST['wordpress_language'] == 'en') { echo ' SELECTED'; } } ?> />English</option>
							<option value="nl"<?php if(isset($_POST['mysql_host'])) { if($_POST['wordpress_language'] == 'nl') { echo ' SELECTED'; } } ?> />Dutch</option>
						</select>
					</td>
				</tr>
				<tr>
					<td><input type="submit" value="WP-ADI" /></td>
					<td></td>
				</tr>
			</table>
		</form>
	</body>
</html>
	<?php
}
else if(isset($_POST['mysql_host']) && $_POST['mysql_host'] != ''
&& $_POST['mysql_database'] != ''
&& $_POST['mysql_username'] != ''
&& $_POST['mysql_password'] != ''
&& $_POST['wordpress_prefix'] != ''
&& $_POST['wordpress_language'] != '') {
	if($_POST['wordpress_language'] == 'en') {
		$download_url = 'https://wordpress.org/latest.tar.gz';
	}
	else if($_POST['wordpress_language'] == 'nl') {
		$releases_content = file_get_contents('https://nl.wordpress.org/releases/');
		$releases_content_part = explode('<table class="releases latest">',$releases_content);
		$releases_content_part = explode('https://nl.wordpress.org/wordpress-',$releases_content_part[1]);
		$releases_content_part = str_replace(".zip'>zip</a> <small>(<a href='",'',$releases_content_part[1]);
		$download_url = 'https://nl.wordpress.org/wordpress-'.$releases_content_part.'.tar.gz';
	}
	
	if($download_url == '') {
		echo 'Error: Could not get the right download URL for WordPress';
	}
	else if($download_url != '') {
		### Check DIR content
		if(file_exists('index.php')) {
			echo 'Error: Directory not empty!';
		}
		else {
			### Check MySQL Connection
			$conn = new mysqli($_POST['mysql_host'],$_POST['mysql_username'],$_POST['mysql_password'],$_POST['mysql_database']);
			$conn_passed = True;
			if($conn->connect_error) {
				$conn_passed = False;
			}
			if(!$conn_passed) {
				echo 'Error: Could not connect to your MySQL Database';
			}
			else if($conn_passed) {
				$prefix = $conn->real_escape_string($_POST['wordpress_prefix']);
				
				### Check DB Contents
				$result = $conn->query('SELECT * FROM '.$prefix.'users');
				if($result->num_rows == 0) {
					$dbcontents_passed = True;
				}
				if(!$dbcontents_passed) {
					echo 'Error: There is already a table named wp_users in this database!';
				}
				else if($dbcontents_passed) {
					### Download WordPress tar.gz
					$temp_file = 'temp.tar.gz';
					$file = fopen($temp_file,'w');
					fwrite($file,file_get_contents($download_url));
					fclose($file);
					
					if(!file_exists($temp_file)) {
						echo 'Error: Unable to download the Wordpress Installation File';
					}
					else if(file_exists($temp_file)) {
						### Extract WordPress files
						$phar = new PharData($temp_file);
						$phar->extractTo(getcwd());
						
						### Remove installation files
						unlink($temp_file);
						if(file_exists($temp_file)) {
							echo 'Notice: Unable to remove installation file: <i>'.$temp_file.'</i>';
						}
						
						### Move recursive from 'wordpress' to root folder
						rmove(getcwd().'/wordpress',getcwd());
						
						### Edit wp-config.php
						rename('wp-config-sample.php','wp-config-sample');
						$salts = file_get_contents('https://api.wordpress.org/secret-key/1.1/salt/');

						$wpconfig_content = "<?php
define('DB_NAME', '".$_POST['mysql_database']."');
define('DB_USER', '".$_POST['mysql_username']."');
define('DB_PASSWORD', '".$_POST['mysql_password']."');
define('DB_HOST', '".$_POST['mysql_host']."');
define('DB_CHARSET', 'utf8');
define('DB_COLLATE', '');
".$salts.'
$table_prefix  = \''.$_POST['wordpress_prefix']."';
define('WP_DEBUG', false);
if ( !defined('ABSPATH') )
	define('ABSPATH', dirname(__FILE__) . '/');
require_once(ABSPATH . 'wp-settings.php');
?>";

						$file = fopen('wp-config.php','w');
						fwrite($file,$wpconfig_content);
						fclose($file);
						
						### Clean up installation files
						unlink('wp-adi.php');
						
						### Run wp installation
						header('Location: wp-admin/install.php');
					}
				}
			}
		}
	}
}
else {
	echo "Please fill in all the required fields!";
}
?>