<?php

/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

/**
 * This file sets up important stuff like loading settings, database, libraries, and dependencies.
 * It's intended to be the first thing a script runs before responding to a request.
 */
ob_start(); // allow sending headers after content
// Unicode, solves almost all stupid encoding problems
header('Content-Type: text/html; charset=utf-8');

// Strip PHP version
header('X-Powered-By: PHP');

// Security
header('X-Content-Type-Options: nosniff');
header('X-XSS-Protection: 1; mode=block');
header('X-Frame-Options: "DENY"');
header('Referrer-Policy: "no-referrer, strict-origin-when-cross-origin"');
header("Access-Control-Allow-Origin: *");

//
// Composer
require __DIR__ . '/vendor/autoload.php';

\Sentry\init(['dsn' => 'https://1cb615831d87433c941e1bd7e7df3d0b@bugs.netsyms.net/3']);

// Settings
require __DIR__ . '/env.php';

// Load in other code
$libs = glob(__DIR__ . "/lib/*.lib.php");
foreach ($libs as $lib) {
    require_once $lib;
}
unset($libs, $lib);

// Set timezone
if (envhas("timezone")) {
    date_default_timezone_set(env("timezone", "UTC"));
}

// Initialize database driver
use Medoo\Medoo;

$database;
try {
    $database = new Medoo(env("database", []));
} catch (Exception $ex) {
    if (env("require_database")) {
        http_response_code(500);
        Logger::log("Database error: $ex");
        exit("Database error.");
    }
}

$memcacheconfig = env("memcached", [
    "enable" => false,
    "server" => "127.0.0.1",
    "port" => 11211,
    "prefix" => "apiserver"
        ]);
$memcache = new MemcacheDriver($memcacheconfig["enable"], $memcacheconfig["server"], $memcacheconfig["port"], $memcacheconfig["prefix"]);
unset($memcacheconfig);

if (env("debugmode", false)) {
    error_reporting(E_ALL);
    ini_set('display_errors', 'On');
} else {
    error_reporting(0);
    ini_set('display_errors', 'Off');
}