<?php
if (file_exists('.indexprepend.php')) {
    include_once '.indexprepend.php';
}

// Define path to application directory
defined('APPLICATION_PATH')
|| define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));

// define version of the application
defined('APPLICATION_VERSION')
|| define('APPLICATION_VERSION', "evolution");

// Define application environment
defined('APPLICATION_ENV')
|| define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'production'));

require_once __DIR__ . '/../customer-version.php';

require_once 'Zend/Config/Ini.php';

/**
 * Handle maintenance page
 */

if (file_exists(APPLICATION_PATH . '/../maintenance.ini')) {
    $mtSettings = new Zend_Config_Ini(APPLICATION_PATH . '/../maintenance.ini');
    $mtSettings = $mtSettings->toArray();

    if (array_key_exists('active', $mtSettings) && 1 == $mtSettings['active']) {
        require_once('Zend/Session.php');

        Zend_Session::start();
        $sess = new Zend_Session_Namespace('maintenance');

        $overrideCode = isset($mtSettings['overridecode']) ? $mtSettings['overridecode'] : '1';

        if (!isset($sess->override)) {
            $sess->override = false;
        }

        $overrideCookieName = 'lmsmoverride';

        if(array_key_exists($overrideCookieName, $_COOKIE) && $overrideCode == $_COOKIE[$overrideCookieName]) {
            $sess->override = true;
        }
        elseif (array_key_exists('maintenanceoverride', $_REQUEST)) {
            if ($overrideCode == $_REQUEST['maintenanceoverride']) {
                setcookie($overrideCookieName, $overrideCode, 0, "", "", true, true);
                $sess->override = true;
            } else {
                $sess->override = false;
            }
        }

        if (!$sess->override && isset($mtSettings['page'])) {
            include $mtSettings['page'];
            exit;
        } elseif (!$sess->override) {
            echo "The application is currently not available due to planned system maintenance";
            exit;
        }
    }
}

/**
 * Symfony integration.
 * If a matching route is found in Symfony, the request will be terminated after the includes.
 * Any following code will not be executed!
 */
if ('development' === APPLICATION_ENV) {
    include_once __DIR__ . '/app_dev.php';
} else {
    include_once __DIR__ . '/app.php';
}
//*************** End of Symfony integegration


// Workaround: Symfony resets the Cache-Control and Pragma headers:
header('Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0');

// Define application cache namespace
defined('APPLICATION_CACHE_NS')
|| define('APPLICATION_CACHE_NS',
    (getenv('APPLICATION_CACHE_NS') ? getenv('APPLICATION_CACHE_NS') : 'n' . md5(APPLICATION_PATH) . '_'));

// Ensure library/ is on include_path
set_include_path(get_include_path()
    . PATH_SEPARATOR . APPLICATION_PATH . '/../library'
);

/* Hostnamebezogene application.ini */
$configDir = APPLICATION_PATH . DIRECTORY_SEPARATOR . 'configs' . DIRECTORY_SEPARATOR;
$hostConfigPath = $configDir . 'application-' . $_SERVER['SERVER_NAME'] . '.ini';

if (file_exists($hostConfigPath)) {
    $configIniPath = $hostConfigPath;
} else {
    $configIniPath = $configDir . 'application.ini';
}

/* Load configuration */
$apcPresent = function_exists('apc_fetch');


$config = false;

if ($apcPresent) {
    if (array_key_exists('clearcache', $_REQUEST) && '1' == $_REQUEST['clearcache']) {
        apc_clear_cache();
        apc_clear_cache('user');
    }

    $config = apc_fetch(APPLICATION_CACHE_NS . 'applicationConfig');
}

if (!$config) {
    $serverConfig = new Zend_Config_Ini($configIniPath, null, true);
    $config = new Zend_Config_Ini(APPLICATION_PATH . '/configs/application-common.ini', null, true);
    $config->merge($serverConfig);

    if ($apcPresent) {
        $ttl = 60;
        if (isset($config->settings->applicationConfigTtl)) {
            $ttl = (int)$config->settings->applicationConfigTtl;
        }

        apc_store(APPLICATION_CACHE_NS . 'applicationConfig', $config, $ttl);
    }
}

// set cookie domain to share (session) cookies on subdomains
if (isset($config->settings->cookie->domain)) {
    $cookieParams = session_get_cookie_params();
    session_set_cookie_params($cookieParams['lifetime'], $cookieParams['path'], $config->settings->cookie->domain,
        $cookieParams['secure'], $cookieParams['httponly']);
}


$applicationSection = APPLICATION_ENV;

/* Register configuation */
require_once 'Zend/Registry.php';
Zend_Registry::set('applicationConfig', $config);

Zend_Registry::set('Symfony_Kernel', $kernel);
Zend_Registry::set('Symfony_Request', $request);
Zend_Registry::set('Symfony_Response', $response);

/** Zend_Application */
require_once 'Zend/Application.php';

require_once('FirePHP/Init.php');
FirePHP_Init::init();

require_once('FirePHP/Errorhandler.php');


$tmStartTime = null;
$tmLastTst = null;
$tmBaseDir = dirname(__DIR__);
$tmBaseDirLen = strlen($tmBaseDir);

function tm($file, $line, $msg = null)
{
    global $tmStartTime, $tmLastTst, $tmBaseDir, $tmBaseDirLen;
    $now = microtime(true);

    $logPath = APPLICATION_PATH . '/logs/timemeasure.log';

    $first = false;

    if (null === $tmLastTst) {
        $first = true;
        $tmStartTime = $now;
    }

    if (substr($file, 0, $tmBaseDirLen) === $tmBaseDir) {
        $file = substr($file, $tmBaseDirLen + 1);
    }

    if ($first) {
        file_put_contents($logPath, "### " . $_SERVER['REQUEST_URI'] . " ###\n", FILE_APPEND);
        $fromStart = '-';
        $fromLast = '-';
    } else {
        $fromStart = str_pad(round(($now - $tmStartTime) * 1000, 2) . 'ms', 16, ' ', STR_PAD_LEFT);
        $fromLast = str_pad(round(($now - $tmLastTst) * 1000, 2) . 'ms', 16, ' ', STR_PAD_LEFT);
    }

    $msg = str_pad($fromStart, 16, ' ', STR_PAD_LEFT)
        . ' ' . str_pad($fromLast, 16, ' ', STR_PAD_LEFT)
        . ' ' . $file . ", " . $line . ((null !== $msg) ? ' ' . trim((string)$msg) : '') . "\n";

    $tmLastTst = $now;
    file_put_contents($logPath, $msg, FILE_APPEND);
}


try {
    $application = new Zend_Application(
        APPLICATION_ENV,
        $config->$applicationSection
    );

    Zend_Registry::set('Zend_Application', $application);

    $application->bootstrap()
        ->run();
} catch (Exception $e) {
    throw $e; // Make sure the exception is thrown again to appear in logs
}
