<?php
/********************************************************************************
 * (c)1337 aheadware.com - All rights reserved
 ********************************************************************************/

/**
 * Class AHDB_Utils_Log
 */
class AHDB_Utils_Log {

    protected $logile = NULL;
    protected $logfileHandle = false;

    // Constructor
    public function __construct( $logfile = NULL ) {
        if ( !is_null( $logfile ) ) {
            $this->logfile = $logfile;
            $this->logfileHandle = @fopen( $this->logfile, "a+t" );
        }
    }

    /**
     * Log given data
     *
     * @param mixed $data
     */
    public function log( $data ) {
        $logTxt = '[' . date( "d-m-Y H:i:s" ) . '] ';
        if ( $data instanceof Exception ) {
            $logTxt .= $data->getMessage() . "\n";
            $logTxt .= $data->getTraceAsString() . "\n";
        } else {
            $logTxt .= '' . $data . "\n";
        }

        $logTxt .= '#######################################################################' . "\n";

        // Logout
        if ( $this->logfileHandle ) {
            @fputs( $this->logfileHandle, $logTxt );
        }
    }

    /**
     * Clear the log file
     */
    public function clearLogfile() {
        if ( $this->logfileHandle ) {
            @ftruncate( $this->logfileHandle, 0 );
        }
    }

    /**
     * Get content of logfile
     *
     * @return string
     */
    public function getContent() {
        if ( $this->logfileHandle && 0 < filesize( $this->logfile ) ) {
            @fseek( $this->logfileHandle, 0 );
            return @fread( $this->logfileHandle, filesize( $this->logfile  ) );
        } else {
            return '';
        }
    }
} 