<?php
    $GLOBALS['mysqli'] = mysqli_connect(SQL_HOST, SQL_LOGIN, SQL_PASSWORD, SQL_DATABASE);
    if (!$GLOBALS['mysqli'])
    {
        die('Connect Error (' . mysqli_connect_errno($GLOBALS['mysqli']) . ') ' . mysqli_connect_error($GLOBALS['mysqli']));
    }
    mysqli_query_logged("SET NAMES utf8mb4");

    function mysqli_query_logged($query, $print = 0)
    {
        if ($print)
        {
            echo $query . '<br />';
        }
        $start_time = microtime(true);
        $return = mysqli_query($GLOBALS['mysqli'], $query);
        $end_time = microtime(true);
        $run_time = $end_time - $start_time;
        if (mysqli_errno($GLOBALS['mysqli']))
        {
            if ($handle = fopen('../logs/sql_error.txt', 'ab'))
            {
                if (fwrite($handle, '[' . date('Y-m-d H:i:s') . '] [' . (isset($GLOBALS['auth']['id']) ? $GLOBALS['auth']['id'] : '0') . '] [' . server('REMOTE_ADDR') . '] ' . RAVE . ' - ' . server('QUERY_STRING') . ' - ' . server('HTTP_REFERER') . ' - MYSQL ERROR #' . mysqli_errno($GLOBALS['mysqli']) . ' : ' . mysqli_errno($GLOBALS['connection']) . ' : ' . $query . ' (' . $run_time . ")\r\n") !== false)
                {
                    fclose($handle);
                }
            }
        }
        if ($run_time > 0.5)
        {
            if ($handle = fopen('../logs/sql_slow.txt', 'ab'))
            {
                if (fwrite($handle, '[' . date('Y-m-d H:i:s') . '] [' . (isset($GLOBALS['auth']['id']) ? $GLOBALS['auth']['id'] : '0') . '] [' . server('REMOTE_ADDR') . '] ' . RAVE . ' - ' . server('QUERY_STRING') . ' - ' . server('HTTP_REFERER') . ' : ' . $query . ' (' . $run_time . ")\r\n") !== false)
                {
                    fclose($handle);
                }
            }
        }
        return $return;
    }