<?php
$profile_time_start = microtime(1);
$profile_timestamps = array();

date_default_timezone_set('Europe/Berlin');

require_once realpath(dirname(__FILE__) . '/../vendor/autoload.php');

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

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

// Define application ID
defined('APPLICATION_ID')
|| define('APPLICATION_ID', (getenv('APPLICATION_ID') ? getenv('APPLICATION_ID') : md5(dirname(__FILE__))));

// Define user suffix
defined('USER_SUFFIX')
    || define('USER_SUFFIX', (getenv('USER_SUFFIX') ? getenv('USER_SUFFIX') : ''));
    
// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
    realpath(APPLICATION_PATH . '/../library'),
    //get_include_path(),
)));

// Only allow session cookie to be sent back over https in case of a https connection
if ((isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') ||
    (isset($_SERVER["HTTP_CLOUDFRONT_FORWARDED_PROTO"]) && $_SERVER["HTTP_CLOUDFRONT_FORWARDED_PROTO"] == 'https'))
    ini_set('session.cookie_secure', 'on');

// Catch php errors and change http response code to 500
function shutdown()
{
    $error = error_get_last();
    if ($error && !headers_sent() && $error['type'] & (E_ERROR | E_USER_ERROR | E_PARSE | E_CORE_ERROR | E_COMPILE_ERROR | E_RECOVERABLE_ERROR))
        header('Status: 500 Internal Server Error');
}

register_shutdown_function('shutdown');

// Initializ correlation id before instantiating application object
require_once 'Zend/Registry.php';
$corrId = filter_input(INPUT_SERVER, 'HTTP_X_CORRELATION_ID', FILTER_VALIDATE_REGEXP, [
    'options' => ['regexp' => '/^[a-fA-F0-9_-]+$/']
]);
$corrId = $corrId ? $corrId : strtr(uniqid('', true), '.', '-');
Zend_Registry::set('correlation_id', $corrId);

// Create application object with options
require_once 'Zend/Application.php';
$application = new Zend_Application(APPLICATION_ENV, parse_ini_file(APPLICATION_PATH . '/configs/config.ini'));
$options = Cms_Options::initFromEnv($application->getOptions());
$application->setOptions($options);

// Bootstrap and run application
$application->bootstrap()
            ->run();
