<?php
/*-------------------------------------------------------+
| PHP-Fusion Content Management System
| Copyright (C) PHP-Fusion Inc
| https://www.php-fusion.co.uk/
+--------------------------------------------------------+
| Filename: upgrade.php
| Author: PHP-Fusion Development Team
+--------------------------------------------------------+
| This program is released as free software under the
| Affero GPL license. You can redistribute it and/or
| modify it under the terms of this license which you
| can read by viewing the included agpl.txt or online
| at www.gnu.org/licenses/agpl.html. Removal of this
| copyright header is strictly prohibited without
| written permission from the original author(s).
+--------------------------------------------------------*/
require_once "../maincore.php";
if (!checkrights("U") || !defined("iAUTH") || !isset($_GET['aid']) || $_GET['aid'] != iAUTH) { redirect("../index.php"); }

require_once THEMES."templates/admin_header.php";
if (file_exists(LOCALE.LOCALESET."admin/upgrade.php")) {
	include LOCALE.LOCALESET."admin/upgrade.php";
} else {
	include LOCALE."English/admin/upgrade.php";
}
if (file_exists(LOCALE.LOCALESET."setup.php")) {
	include LOCALE.LOCALESET."setup.php";
} else {
	include LOCALE."English/setup.php";
}

// Some new DB check functions provided in 9, it needs to be decleared here in the upgrade.

if (!function_exists('fieldgenerator')) {
	function fieldgenerator($db) {
		$cresult = dbquery("SHOW COLUMNS FROM $db");
		$col_names = array();
		while ($cdata = dbarray($cresult)) {
			$col_names[] = $cdata['Field'];
		}
		return (array) $col_names;
	}
}

opentable($locale['400']);

echo "<div style='text-align:center'><br />\n";

// Execute Gallery migration script if called
if (isset($_GET['migrate_gallery'])) {
require_once ADMIN."upgrade/gallery_migrate.php";
echo "<div class='well'>Deine Fotoalben wurden verschoben.</div>";
}

// Execute Forum attachment migration script if called
if (isset($_GET['migrate_forum'])) {
require_once ADMIN."upgrade/forum_migrate.php";
echo "<div class='well'>Deine Foren Anh&auml;nge wurden verschoben.</div>";
}

if (str_replace(".", "", $settings['version']) == "90000") {
echo "<div class='text-center'><div class='btn-group'>";
	if (file_exists(IMAGES."photoalbum/index.php")) {
		echo "<a class='btn btn-default' href='".FUSION_SELF.$aidlink."&amp;migrate_gallery'>Alben in 9.0 Ordner verschieben</a>";
	}

	if (file_exists(BASEDIR."forum/attachments/index.php")) {
		echo "<a class='btn btn-default' href='".FUSION_SELF.$aidlink."&amp;migrate_forum'>Foren Anh&auml;nde in 9.0 Ordner verschieben</a>";
	}
echo "</div></div>";

}

if (str_replace(".", "", $settings['version']) < "90000") {
	echo "<form name='upgradeform' method='post' action='".FUSION_SELF.$aidlink."'>\n";
	$content = "";
	if ($settings['maintenance'] == 0) {
		if (isset($_POST['enable_maintenance'])) {
			dbquery("UPDATE ".DB_SETTINGS." SET settings_value='1' WHERE settings_name='maintenance'");
			redirect(FUSION_SELF.$aidlink);
			}
		$content .= "<div class='admin-message'>Wartungsmodus vor dem Seiten Update aktivieren</div>";
		$content .= "<input class='button btn btn-primary' type='submit' name='enable_maintenance' value='Wartungsmodus aktivieren'>";
	} elseif (isset($_GET['upgrade_ok'])) {
		$content .= "Update abgeschlossen. Weiter zur maintenance.php.\n";
	} else {
		switch (filter_input(INPUT_POST, 'stage', FILTER_VALIDATE_INT) ? : 1) {
			case 1:
			$content .= "<div style='width:100%; margin:15px auto;' class='tbl center'>\n";
			$content .= "Dieses Update kann etwas l&auml;nger dauern, je nach Inhalt deiner Seite.<br />";
			$content .= "Bitte gehe sicher, dass du ein komplettes Backup deines Systems besitzt, bevor du das Update startest.<br />";
			$content .= "Wenn das Update abgeschlossen ist, wirst du, automatisch auf die maintenance.php-Datei weitergeleitet.<br />";
			$content .= "Detail Informationen zu Schritt 2 findest du in der Readme-Datei!<br />";
			$content .= "<br /><br /><input type='hidden' name='stage' value='2'>\n";
			$content .= "<input type='submit' name='next' value='Weiter' class='button btn btn-primary'><br /><br />\n";
			$content .= "</div>";
			break;
			case 2:
				// Check if $pdo_enabled, SECRET_KEY and SECRET_KEY_SALT are set
				// Check config file formatting.
					if (!isset($pdo_enabled) || !defined('SECRET_KEY') || !defined('SECRET_KEY_SALT')) {
					// Generate random token keys
					function createRandomToken($length = 32) {
						$chars = array("abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ", "123456789");
						$count = array((strlen($chars[0])-1), (strlen($chars[1])-1));
						$key = "";
						for ($i = 0; $i < $length; $i++) {
							$type = mt_rand(0, 1);
							$key .= substr($chars[$type], mt_rand(0, $count[$type]), 1);
						}
						return $key;
					}

					$secret_key = createRandomToken();
					$secret_key_salt = createRandomToken();

					$content .= "<div style='width:850px; margin:15px auto;' class='tbl center'>\n";
					$content .= "Bevor es weitergeht, musst du deine <strong>config.php</strong> Datei bearbeiten, und zwar, die 3 folgenden Zeilen nach COOKIE_PREFIX einf&uuml;gen: <br />\n";
					$content .= "<div class='tbl-border' style='margin-top:10px; padding: 5px; text-align:left;'>\n";
					$content .= "\$pdo_enabled = \"0\"; <br />\n";
					$content .= "define(\"SECRET_KEY\", \"".$secret_key."\"); <br />\n";
					$content .= "define(\"SECRET_KEY_SALT\", \"".$secret_key_salt."\"); <br />\n";
					$content .= "</div><br />";
					$content .= "<strong>Hinweis!</strong> Um PDO zu aktivieren, musst du manuell die Zeile \$pdo_enabled = \"0\" zu \$pdo_enabled = \"1\" &auml:ndern.<br /><br />\n";
					$content .= "Wenn du die oberhalb stehenden Zeilen in deine <strong>config.php</strong> - Datei eingetragen hast, klicke bitte auf Weiter.<br /><br />\n";
					$content .= "<strong>Warnung!</strong>Solltest du Weiter klicken, ohne die oberhalb stehenden Zeilen in deine <strong>config.php</strong>-Datei einzutragen, musst du es sp&auml;ter wiederholen. <br />\n";
					$content .= "F&uuml;r jedes Neuladen werden die Keys no erstellt, solange diese nicht in der <strong>config.php</strong>-Datei hinterlegt wurden.<br /><br />\n";
					$content .= "<input type='hidden' name='stage' value='2'>\n";
					$content .= "<input type='submit' name='refresh' value='Weiter' class='button btn btn-primary' style='margin: 0px auto;'></div><br /><br />\n";
					} else {
					$content .= "<div style='width:850px; margin:15px auto;' class='tbl center'>\n";
					$content .= "Eine neue .htaccess-Datei mit speziellen Einstellungen, welche notwendig f&uuml;r PHP-Fusion sind, wird erstellt.<br />
								Bitte beachte, alle bis jetzt durchgef&uuml;hrte &Auml;nderungen an der .htaccess gehen verloren.";
					$content .= "</div>\n";
					$content .= "<input type='hidden' name='stage' value='3'>\n";
					$content .= "<input type='submit' name='write_htaccess' value='Weiter' class='button btn btn-primary'><br /><br />\n";
					}
				break;
			case 3:
				if (!isset($_POST['write_htaccess'])) {
					$content .= "<div style='width:850px; margin:15px auto;' class='tbl center'>\n";
					$content .= "Eine neue .htaccess-Datei mit speziellen Einstellungen, welche notwendig f&uuml;r PHP-Fusion sind, wird erstellt.<br />
								 Bitte beachte, alle bis jetzt durchgef&uuml;hrte &Auml;nderungen an der .htaccess gehen verloren.";
					$content .= "</div>\n";
					$content .= "<input type='hidden' name='stage' value='3'>\n";
					$content .= "<input type='submit' name='write_htaccess' value='Weiter' class='button btn btn-primary'><br /><br />\n";
					break;
				} else {
					// Wipe out all .htaccess rewrite rules and add error handler only
					$htc = "# Force utf-8 charset".PHP_EOL;
					$htc .= "AddDefaultCharset utf-8".PHP_EOL.PHP_EOL;
					$htc .= "# Security".PHP_EOL;
					$htc .= "ServerSignature Off".PHP_EOL.PHP_EOL;
					$htc .= "# Secure htaccess file".PHP_EOL;
					$htc .= "<Files .htaccess>".PHP_EOL;
					$htc .= "order allow,deny".PHP_EOL;
					$htc .= "deny from all".PHP_EOL;
					$htc .= "</Files>".PHP_EOL.PHP_EOL;
					$htc .= "# Protect config.php".PHP_EOL;
					$htc .= "<Files config.php>".PHP_EOL;
					$htc .= "order allow,deny".PHP_EOL;
					$htc .= "deny from all".PHP_EOL;
					$htc .= "</Files>".PHP_EOL.PHP_EOL;
					$htc .= "# Block Nasty Bots".PHP_EOL;
					$htc .= "<IfModule mod_setenvifno.c>".PHP_EOL;
					$htc .= "	SetEnvIfNoCase ^User-Agent$ .*(craftbot|download|extract|stripper|sucker|ninja|clshttp|webspider|leacher|collector|grabber|webpictures) HTTP_SAFE_BADBOT".PHP_EOL;
					$htc .= "	SetEnvIfNoCase ^User-Agent$ .*(libwww-perl|aesop_com_spiderman) HTTP_SAFE_BADBOT".PHP_EOL;
					$htc .= "	Deny from env=HTTP_SAFE_BADBOT".PHP_EOL;
					$htc .= "</IfModule>".PHP_EOL.PHP_EOL;
					$htc .= "# Disable directory listing".PHP_EOL;
					$htc .= "Options -Indexes".PHP_EOL.PHP_EOL;
					$htc .= "ErrorDocument 400 ".$settings['site_path']."error.php?code=400".PHP_EOL;
					$htc .= "ErrorDocument 401 ".$settings['site_path']."error.php?code=401".PHP_EOL;
					$htc .= "ErrorDocument 403 ".$settings['site_path']."error.php?code=403".PHP_EOL;
					$htc .= "ErrorDocument 404 ".$settings['site_path']."error.php?code=404".PHP_EOL;
					$htc .= "ErrorDocument 500 ".$settings['site_path']."error.php?code=500".PHP_EOL;
					// Create the .htaccess file
					if (!file_exists(BASEDIR.".htaccess")) {
						if (file_exists(BASEDIR."_htaccess") && function_exists("rename")) {
							@rename(BASEDIR."_htaccess", BASEDIR.".htaccess");
						} else {
							touch(BASEDIR.".htaccess");
						}
					}
					$temp = fopen(BASEDIR.".htaccess", "w");
					if (fwrite($temp, $htc)) {
						fclose($temp);
						echo "<div class='admin-message'>Der Inhalt der .htaccess-Datei wurde erfolgreich aktualisiert.</div>";
					}
				}
			case 4:
				$content .= "<div class='admin-message'>\n";
				$content .= "<p>Es werden einige Datenbank &Auml;nderungen durchgef&uuml;hrt. Je nach Inhalt kann dies einen Moment dauern.</p>\n";
				$content .= "<div class='alert alert-warning'></i>Wir empfehlen dir, ein <a target='_blank' href='db_backup.php".$aidlink."'>Datenbank Backup</a> zu erstellen, bevor du das Update ausf&uuml;hrst!</div>\n";
				$content .= "</div>\n";
				$disabled = FALSE; // true to disable.
				$content .= "<input type='hidden' name='stage' value='".($disabled ? 5 : 4)."'>\n";
				$content .= "<input type='submit' name='upgrade_database' value='Weiter' class='button btn btn-primary'><br /><br />\n";
				if (!$disabled && isset($_POST['upgrade_database'])) {
					// @todo: upgrade package shall be rolled out automatically
					include "upgrade/upgrade-7.02-9.00.php";
					dbquery("UPDATE ".DB_SETTINGS." SET settings_value='9.00.00' WHERE settings_name='version'");
					echo "<div class='admin-message'>Die Datenbank wurde erfolgreich aktualisiert.</div>";
					redirect(FUSION_SELF.$aidlink."&amp;upgrade_ok");
				}
				break;
		}
	}
	echo $content;
	echo "</form>";
} else {
	echo "<br />".$locale['401']."<br /><br />\n";
}
echo "</div>\n";
closetable();
require_once THEMES."templates/footer.php";