<?php
/******************************************************************************
 *  SiteBar 3 - The Bookmark Server for Personal and Team Use.                *
 *  Copyright (C) 2003,2004  Ondrej Brablc <http://brablc.com/mailto?o>       *
 *                                                                            *
 *  This program is free software; you can redistribute it and/or modify      *
 *  it under the terms of the GNU General Public License as published by      *
 *  the Free Software Foundation; either version 2 of the License, or         *
 *  (at your option) any later version.                                       *
 *                                                                            *
 *  This program is distributed in the hope that it will be useful,           *
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of            *
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the             *
 *  GNU General Public License for more details.                              *
 *                                                                            *
 *  You should have received a copy of the GNU General Public License         *
 *  along with this program; if not, write to the Free Software               *
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA *
 ******************************************************************************/

// Show in development or when debugging
// define("SHOW_PHP_ERRORS", true);

// When not defined then no logging performed
// define("LOG_FILE_PATH", "sitebar.log");

if (defined("SHOW_PHP_ERRORS") && SHOW_PHP_ERRORS)
{
    error_reporting(E_ALL); // We want to see all errors, regardless of php.ini
}

// This should be a static class variable, if PHP 4 were OO language :-)
$errorHandler__errorCount = 0;
$errorHandler__warnCount = 0;
$errorHandler__messages = array();

$errorHandler__phpHandlerUsed = 0;
$errorHandler__phpHandlerSet = 0;

function safeVal(&$ascArr, $field, $default = null)
{
    if (isset($ascArr[$field]))
    {
        return $ascArr[$field];
    }
    return $default;
}

function errorHandler_handler($errno, $errstr, $errfile, $errline)
{
    if (!defined("SHOW_PHP_ERRORS") || !SHOW_PHP_ERRORS)
    {
        return;
    }

    global $errorHandler__phpHandlerUsed;
    $errorHandler__phpHandlerUsed++;

    $errHandler = new ErrorHandler();
    $pathParts = pathinfo($errfile);
    $location = $pathParts['basename'] . ' line ' . $errline;

    switch ($errno)
    {
        case E_ERROR:
            $errHandler->error("%s [%s]", array($errstr, $location));
            break;

        case E_WARNING:
        default:
            $errHandler->warn("%s [%s]", array($errstr, $location));
            break;
    }
}

require_once('./inc/localizer.inc.php');

class StopWatch
{
    var $started = 0;
    var $elapsed = 0;

    function StopWatch()
    {
        $this->start();
    }

    function start()
    {
        $this->elapsed = 0;
        $this->cont();
    }

    function cont()
    {
        $this->started = $this->getMicroTime();
    }

    function pause()
    {
        $this->elapsed += $this->getMicroTime() - $this->started;
        return $this->elapsed;
    }

    function stop()
    {
        return $this->pause();
    }

    function getMicroTime()
    {
        list($usec, $sec) = explode(" ",microtime());
        return ((float)$usec + (float)$sec);
    }
}

class ErrorHandler
{
    function useHandler($sbHandler = true)
    {
        global $errorHandler__phpHandlerSet;

        if ($sbHandler)
        {
            if (!$errorHandler__phpHandlerSet)
            {
                set_error_handler("errorHandler_handler");
            }
            $errorHandler__phpHandlerSet++;
        }
        else
        {
            if ($errorHandler__phpHandlerSet)
            {
                restore_error_handler();
            }
            $errorHandler__phpHandlerSet--;
        }
    }

    /**
    * Issue error
    */
    function error($msg, $arr=null)
    {
        global $errorHandler__errorCount;
        $errorHandler__errorCount++;
        $errors =& ErrorHandler::getErrors();
        $errors[] = array(E_ERROR,ErrorHandler::formatError($msg, $arr));
    }

    /**
    * Issue warning
    */
    function warn($msg, $arr=null)
    {
        global $errorHandler__warnCount;
        $errorHandler__warnCount++;
        $errors =& ErrorHandler::getErrors();
        $errors[] = array(E_WARNING,ErrorHandler::formatError($msg, $arr));
    }

    /**
    * Fatal error
    */
    function fatal($msg, $arr=null)
    {
        ErrorHandler::error($msg, $arr);
        ErrorHandler::writeErrors();
        die();
    }

    function formatError($msg, $arr=null)
    {
        $txt = '';

        if (!$msg) // No formatting
        {
            $txt = $arr;
        }
        else
        {
            $txt = T($msg,$arr);
        }

        return $this->log("\nE:", $txt);
    }

    /**
    * Returns any possible errors
    */
    function & getErrors()
    {
        global $errorHandler__messages;
        return $errorHandler__messages;
    }

    /**
    * Tells wheter there were php errors handled
    */
    function hasHandledErrors()
    {
        global $errorHandler__phpHandlerUsed;
        return $errorHandler__phpHandlerUsed;
    }

    /**
    * Tells wheter there are errors to be reported
    */
    function hasErrors($type=null)
    {
        global $errorHandler__errorCount, $errorHandler__warnCount;

        switch ($type)
        {
            case E_ERROR:
                return $errorHandler__errorCount;

            case E_WARNING:
                return $errorHandler__warnCount;

            default:
                return count(ErrorHandler::getErrors());
        }
    }

    /**
    * Write errors as UL
    */
    function writeErrors($fulldetails = true)
    {
        if (ErrorHandler::hasHandledErrors())
        {
            $fulldetails = true;
        }

        foreach (ErrorHandler::getErrors() as $err)
        {
            $el = "";
            switch($err[0])
            {
                case E_ERROR:
                    $el = T('Error');
                    break;

                case E_WARNING:
                    $el = T('Warning');
                    break;

                default:
                    $el = T('Unknown');
            }

            echo "<p>";
            if ($fulldetails)
            {
                echo $el . ": ";
            }
            echo $err[1];
        }
    }

    function log($prefix, $data=null)
    {
        if (defined("LOG_FILE_PATH"))
        {
            $file = LOG_FILE_PATH;
            $this->useHandler(false);
            if (($log = @fopen($file, "a")))
            {
                fwrite ($log, $prefix.$data);
                fclose($log);
                chmod($file,0666);
            }
            $this->useHandler();
        }
        return $data;
    }

    function dump($expr,$inscript=0)
    {
        if ($inscript) echo "</script>";
        echo "<pre>";
        var_dump($expr);
        echo "</pre>";
        if ($inscript) echo "<script>";
    }
}

ErrorHandler::useHandler();

?>