<?php
/***********************************************
* File      :   debug.php
* Descr     :   Debuging functions
*
*
* Original by Zarafa Deutschland GmbH released under GPLv2.
* Modifications by Atmail published under GPLv2
* Consult LICENSE file for details
************************************************/

function atmail_error_handler($errno, $errstr, $errfile, $errline, $errcontext) {
    if(DEBUGGING) errorLog("$errfile:$errline $errstr ($errno)\n");

    // If we return true here php wont execute internal error handler
    return !DEBUGGING;
}

if(DEBUGGING)
    error_reporting(-1);
else
    error_reporting(0);

function exception_handler($exception) {
    errorLog( "Uncaught exception: " . $exception->getMessage() . "\n");

    // If we return true here php wont execute internal exception handler
    return !DEBUGGING;
}

function atmail_fatal_handler() {
    $errfile = "unknown file";
    $errstr  = "shutdown";
    $errno   = E_CORE_ERROR;
    $errline = 0;

    $error = error_get_last();

    if( $error !== NULL) {
        $errno   = $error["type"];
        $errfile = $error["file"];
        $errline = $error["line"];
        $errstr  = $error["message"];
        errorLog("errno = $errno\nerrstr = $errstr\nerrfile = $errfile\nerrline = $errline\n", true);
    }
}


if(function_exists('set_exception_handler'))
    set_exception_handler('exception_handler');
if(function_exists('set_error_handler'))
    set_error_handler("atmail_error_handler");
if(function_exists('register_shutdown_function'))
    register_shutdown_function('atmail_fatal_handler');

function debugLog($message)
{
    if( !DEBUGGING )
        return;
    @$fp = fopen(BASE_PATH . "/../log/pushdebug.log","a");
    @$date = strftime("%x %X");
    @fwrite($fp, "$date [". getmypid() ."] $message\n");
    @fclose($fp);
}

function errorLog($message, $fatal = false)
{
    $message = "ActiveSync [" . ($fatal ? "FATAL " : "") . "ERROR]\n" . $message;
    if( DEBUGGING )
    {
        @$fp = fopen(BASE_PATH . "/../log/pushdebug.log","a");
        @$date = strftime("%x %X");
        @fwrite($fp, "$date [". getmypid() ."] $message\n");
        @fclose($fp);
    }
    else
    {
        file_put_contents("php://stderr", $message . "\n");
    }
}