<?php

define('INSTALLATIONLOG', "userData/install.log");

// Server settings
error_reporting(E_ALL);
//error_reporting(E_STRICT);


require_once ("version.php");
require_once ("files/helper.inc");
require_once ("files/settings.php");

loadSettings("");

require_once ("files/Model.inc");

define('BASEDIR', dirname(__FILE__) . '/');

function getContentList()
{
	global $directories;
	global $settings;
	$extensions_image = $settings['imageextensions'];
	$file_extensions = $extensions_image;

	$contentList = array();
	$handle = opendir($directories['photos']);
	while (($temp = readdir($handle)) !== false)
	{
		for ($i = 0; $i < count($file_extensions); $i++)
		{
			if (0 == substr_compare($temp, $file_extensions[$i], (strlen($temp) - strlen($file_extensions[$i])) ))
			{
				$contentList[] = $temp;
			}
		}
	}
	closedir($handle);
	return $contentList;
}


function handleCommands()
{
    global $plugIns;
    global $control;

	if (array_key_exists('command', $control))
	{
		$pendingCmd = null;
		if ($control["command"])
		{
			foreach($plugIns as $thisPlugin)
			{
				if (method_exists($thisPlugin, "handleCommand"))
				{
					$thisPlugin->handleCommand($control["command"]);
				}
			}
		}
	}
}

function renderContent()
{
    global $plugIns;
    foreach($plugIns as $thisPlugin)
    {
        if (method_exists($thisPlugin, "render"))
        {
            $thisPlugin->render();
        }
    }
}


function initPlugIns($view)
{
	global $plugIns;

	foreach($plugIns as $plugIn)
	{
		if (method_exists($plugIn, "onInit"))
		{
			$plugIn->onInit($view);
		}
	}
}


function checkInstallationStatus()
{
	global $plugIns;
	$pluginState = array();

	if (file_exists(INSTALLATIONLOG))
	{
		$installationState = simplexml_load_file(INSTALLATIONLOG);
		if (array_key_exists('plugins', $installationState))
		{
			$pluginState = $installationState->plugins;
		}
		else
		{
			$pluginState = $installationState->addChild('plugins');
		}
	}
	else
	{
		// not installed yet!
		$installationState = simplexml_load_string('<installation></installation>');
		$pluginState = $installationState->addChild('plugins');
	}

	foreach(array_keys($plugIns) as $thisPlugin)
	{
		$installed = FALSE;
		foreach($pluginState->plugin as $pi)
		{
			if (array_key_exists('name', $pi))
			{
				if ($pi->name == $thisPlugin)
				{
					$installed = TRUE;
				}
			}
		}
		if ($installed == TRUE)
		{
		}
		else
		{
			echo $thisPlugin . " has not been installed yet!<br>\n";
			$thisPluginState = $pluginState->addChild('plugin');
			$thisPluginState->addChild('name', $thisPlugin);

			if (method_exists($plugIns[$thisPlugin], "onInstall"))
			{
				$plugIns[$thisPlugin]->onInstall();
			}
		}
	}

	//
	// convert to dom document to pretty print and save
	//
	$doc = new DOMDocument('1.0');
	$doc->formatOutput = true;
	$domnode = dom_import_simplexml($installationState);
	$domnode = $doc->importNode($domnode, true);
	$domnode = $doc->appendChild($domnode);

	$doc->save(INSTALLATIONLOG);
}


function getImageName()
{
	global $path_prefix;

	if (isset($_SERVER["PATH_INFO"]))
	{
		# expect all info in url: "http://ujap.de/wiki/index.php/bla"
		$page = substr($_SERVER["PATH_INFO"], 1);
		$path_prefix = "../";
		if (strpos($page, "/") !== FALSE)
		{
			$path_prefix .= "../";
		}
	}
	else if (isset($_SERVER["ORIG_PATH_INFO"]))
	{
		# this is a workaround for 1und1 webhosting. they always set this variable.
		# if a path is given after the script name, this var is waht we'd expect,
		# else it's the script name
		if (strpos($_SERVER["SCRIPT_NAME"], $_SERVER["ORIG_PATH_INFO"]) !== 0)
		{
			# a path was given
			$page = substr($_SERVER["ORIG_PATH_INFO"], 1);
			$path_prefix="../";
			if (strpos($page, "/") !== FALSE)
			{
				$path_prefix .= "../";
			}
		}
		else
		{
			# no path, no page
			if (isset($defaultName))
			{
				$page = $defaultName;
			}
		}
	}
	else
	{
		#no path given
		$path_prefix = "";
	}
	# if we still have no valid page:
	if (empty($page))
	{
		# TODO use default image
		$page = NULL;
	}
	return $page;
}


// Start
@session_start();
setlocale(LC_TIME, $settings['locale']);

$defTimeZone = ini_get("date.timezone");
if (empty($defTimeZone)) {
	date_default_timezone_set("Europe/Berlin");
}

// global Variables:
$plugIns = array();

$control = array();
$control = array_merge($_GET, $_POST);

if ($extensions = glob($directories["extensions"] . "/*.php")) {
	foreach ($extensions as $thisExt) {
		include_once($thisExt);
	}
}

checkInstallationStatus();


if (array_key_exists('view', $control))
{
	$view = $control["view"];
}
else
{
	$view = "view";
}

// we have to build the model (and initialize the plug ins twice:
// the first time to handle commands
// the second time to reflect the changes the commands did before display.
// @todo do second run only when a command applied!
$model = new Model(getImageName(), $view);
initPlugIns("");

handleCommands();

$masterKeyList = getContentList();
$model = new Model(getImageName(), $view);
initPlugIns($view);

renderContent();
// Do output

$viewFileBaseName = $view . ".php";

$validViewName = preg_match("!^\w[\w]+!", $viewFileBaseName);

if ($validViewName)
{
	$viewFileCompleteName = $directories["templates"]. "/" . $viewFileBaseName;

	if (file_exists($viewFileCompleteName))
	{
		$fp = fopen('log.txt', 'a');
		$time = date('Y-m-d H-i-s');
		$current = $model->getCurrent();
		if (isset($_SERVER['HTTP_REFERER']))
		{
			$referer = $_SERVER['HTTP_REFERER'];
		}
		else
		{
			$referer = "<unknown>";
		}
		if (isset($_SERVER['REMOTE_ADDR']))
		{
			$remote = $_SERVER['REMOTE_ADDR'];
		}
		else
		{
			$remote = "<unknown>";
		}
		fwrite($fp, "time = $time : view = $view : photo = $current : from = $remote : via = $referer\n");
		fclose($fp);				

		include($viewFileCompleteName);
		
	}
	else
	{
		header("Status: 404 Not Found");
		?>
		<body>Requested <?php echo $viewFileBaseName; ?> document not found!</body>
		<?php
	}
}


?>


