<?php

/**
 * @version     backend/classes/auditprocess.php 2015-03-26 14:15:00 UTC pav
 * @authorUrl   https://watchful.li
 * @copyright   Copyright (c) 2012-2015 watchful.li
 * @license     GNU/GPL v3 or later
 * @copyright   Copyright (c) 2012-2015 watchful.li
 * @license     GNU/GPL v3 or later
 */
defined('_JEXEC') or die;
defined('WATCHFULLI_PATH') or die;

/**
 * watchfulliScanner class.
 */
abstract class WatchfulliAuditProcess
{

    const _DEFAULT_TIMEEXECUTION_LIMIT = 10;

    private $max_execution_time;
    private $start_time;
    public $cache;
    public $db;

    public function __construct()
    {
        $this->start_time = $this->microtime_float();
        $this->cache = JFactory::getCache();
        $this->cache->setCaching(1);
        $this->cache->setCaching(6 * 3600);
        $this->db = JFactory::getDBO();
        $this->max_execution_time = $this->CalculateMaxExecutionTime();
    }

    /**
     * Get the maximum execution time from the system
     * @return int
     */
    private function CalculateMaxExecutionTime()
    {

        $input = JFactory::getApplication()->input;
        $max_executiontime_set_by_master = $input->get('max_execution_time', 0);

        if ($max_executiontime_set_by_master)
        {
            return $max_executiontime_set_by_master;
        }

        $php_execution_time = (int) ini_get("max_execution_time");

        if (!$php_execution_time)
        {
            return self::_DEFAULT_TIMEEXECUTION_LIMIT;
        }

        return $php_execution_time - 2; //extra security;

    }
    
    public function getMaxExecutionTime()
    {
        return $this->max_execution_time;
    }

    /**
     * Calculate if we have 1 second left
     * @return boolean
     */
    public function haveTime()
    {  
        $availableTime = $this->max_execution_time - $this->haveRun();
        return $availableTime > 1;
    }

    /**
     * Nomber of second from the start of the script
     * @return decimal
     */
    private function haveRun()
    {
        return $this->microtime_float() - $this->start_time;
    }

    /**
     * Simple function to replicate PHP 5 behaviour
     * @return decimal
     */
    private function microtime_float()
    {
        list ($usec, $sec) = explode(" ", microtime());

        return ((float) $usec + (float) $sec);
    }

}
