<?PHP
/**
 * This file collects generally, often used functions in the public frontend for museum-digital
 *
 * @file
 * @author Stefan Rohde-Enslin <s.rohde-enslin@museum-digital.de>
 * @author Joshua Ramon Enslin <joshua@jrenslin.de>
 */
declare(strict_types = 1);

/**
 * Autoloader for museum-digital.org.
 *
 * @param string $className Name of the class to load.
 *
 * @return void
 */
function mdConcAutoloader(string $className):void {

    // Fallback: Load classes by autoload directories

    foreach (AUTOLOAD_DIRS as $classDir) {
        if (\file_exists("$classDir/$className.php")) {
            include "$classDir/$className.php";
            return;
        }
    }

}

/**
 * Own error handler: Set to enforce exit on any error.
 *
 * @param integer $errno  Error number.
 * @param string  $string Error message.
 * @param string  $file   File in which the error occured.
 * @param integer $line   Line number.
 *
 * @return boolean
 */
function mdConcErrorHandler(int $errno, string $string, string $file, int $line):bool {

    $getStr = [];
    foreach ($_GET as $key => $value) {
        if (is_array($value)) $getStr[] = "$key\[\]={$value[0]}";
        else $getStr[] = $key . "=" . $value;
    }

    if (!empty($_SERVER) and !empty($_SERVER['HTTP_HOST'])) {
        $errorPage = $_SERVER['PHP_SELF'] . "?" . \implode("&", $getStr);
        $errorPageFull   = "https://" . $_SERVER["HTTP_HOST"] . $errorPage;

        $errorMsg  = "*$errno (<a href='https://www.google.de/search?q=php+" . \str_replace(" ", "+", $string) . "'>$string</a>) at $file: line_ $line _";
        $errorMsg .= " |-- Error generating page: <a href='$errorPageFull'>$errorPage</a>";
        $errorMsg .= " |-- Used RAM / Peak RAM / Allowed: " . MD_STD::human_filesize(\memory_get_usage()) . " / " . MD_STD::human_filesize(\memory_get_peak_usage()) . " / " . ini_get("memory_limit");
        if (isset($_SESSION['anmnam'])) $errorMsg .= " |-- User: " . $_SESSION["anmnam"];
        if (isset($_SESSION['username'])) $errorMsg .= " (" . $_SESSION["username"] . ")";

        $errorMsg = \str_replace(PHP_EOL, " ", $errorMsg);
    }
    else {
        $errorMsg  = "*$errno (<a href='https://www.google.de/search?q=php+" . \str_replace(" ", "+", $string) . "'>$string</a>) at $file: line_ $line _";
        $errorMsg .= " |-- Used RAM / Peak RAM / Allowed: " . MD_STD::human_filesize(\memory_get_usage()) . " / " . MD_STD::human_filesize(\memory_get_peak_usage()) . " / " . ini_get("memory_limit");
    }

    $errorMsg = \str_replace(PHP_EOL, " ", $errorMsg);

    \error_log($errorMsg);

    if ($errno === E_ERROR) exit;
    return false;

}

/**
 * Exception handler to also be able to handle custom exceptions.
 *
 * @param Throwable $exception Exception.
 *
 * @return void
 */
function mdConcExceptionHandler(Throwable $exception):void {

    if (ob_get_level() !== 0) {
        ob_end_clean();
    }
    $errorReporter = new MDErrorReporter("md:frontend", "bugs-frontend@museum-digital.de");
    # $errorCategory = MDErrorReporter::categorizeError($exception);

    if (headers_sent() === false) {
        http_response_code(404);
    }
    if (PHP_SAPI !== 'cli') {

        header('Content-type: text/plain');
        if ($exception instanceof MDParserIncomplete) {
            echo 'Parser incomplete - Encountered a field that is thus far unknown / unhandled' . PHP_EOL;
        }
        echo $exception->getMessage();

    }
    $errorReporter->sendErrorReport($exception, "joshua@museum-digital.de");

}
