<?php
/**
*
* @author Benjamin Gillissen <hide@address.com>
*
* **************************************************************
Copyright (C) 2009 Benjamin Gillissen
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 at:
http://www.gnu.org/copyleft/gpl.html
* **************************************************************
*/
class CORE {
const CACHEDEPS=TRUE;
private static $DEPS; //deps folder content cache
public function __construct(){ }
public static function platform(){
if (strtoupper(substr(PHP_OS, 0, 3)) == 'WIN') {
return 'WIN';
} else {
return 'UNIX';
}
}
public static function sapi(){
$sapi = php_sapi_name();
if ( substr($sapi, 0, 3) == 'cgi'
OR ereg('apache', $sapi)
OR ereg('httpd', $sapi) ){
return 'cgi';
} else {
return 'cli';
}
}
public static function isError($err){
if ( !is_object($err) ){ ;return FALSE; }
foreach( Array('getmsg', 'getlvl', 'getcontext', 'getbacktrace') as $method ){
if ( !method_exists($err, $method) ){ return FALSE; }
}
return TRUE;
}
public static function tempfile(){
if ( defined('PATH_TMP') ){ return tempnam(PATH_TMP, 'core_'); }
static $temp_dir;
if ( isset($temp_dir) ){ return tempnam($temp_dir, 'core_'); }
errors::raise('PATH_TMP is not defined, we try to find system temp folder', CORE_LOG_DEBUG, 'CORE');
if ( function_exists('sys_get_temp_dir') ){
$base = realpath( sys_get_temp_dir() );
$t = tempnam($base, 'core_');
if ( FALSE !== $t ){ $temp_dir = $base;unlink($t);return tempnam($base, 'core_'); }
errors::raise('Path returned by sys_get_temp_dir : '.$base.' has been rejected as temp folder', CORE_LOG_DEBUG, 'CORE');
}
$a = Array('TMP', 'TMPDIR', 'TEMP');
foreach($a as $k => $v){
if ( !empty($_ENV[$v]) ){
$base = realpath( $_ENV[$v] );
//we got one, let's try it.
$t = tempnam($base, 'core_');
if ( FALSE !== $t ){ $temp_dir = $base;unlink($t);return tempnam($base, 'core_'); }
errors::raise('$_ENV['.$v.'] : '.$_ENV[$v].' has been rejected as temp folder', CORE_LOG_DEBUG, 'CORE');
}
}
unset($a, $k, $v, $base, $t);
if ( self::platform() == 'UNIX' ){
$base='/tmp';
$t = tempnam($base, 'core_');
if ( FALSE !== $t ){ $temp_dir = $base;unlink($t);return tempnam($base, 'core_'); }
errors::raise('Default Unix Temp "/tmp" has been rejected as temp folder', CORE_LOG_DEBUG, 'CORE');
}
}
public static function Byteconvert(&$bytes){
$s = array('B', 'kB', 'MB', 'GB', 'TB');
if($bytes <= 0){ return Array(0, $s[0], 0); }
$con = 1024;
$e = (int)(log($bytes,$con));
if ( $e == 0){ $prec = 0; } elseif ( $e == 1 ) { $prec = 1; } else { $prec = 2; }
return Array($bytes/pow($con,$e), $s[$e], $prec);
}
public static function ElapsedTime(&$time){
$periode = (time() - $time);
if ( $periode <= 60 ){
return Array($periode, 'secondes');
} elseif( $periode <= 3600 ){
return Array(floor($periode/60), 'minutes');
} elseif( $periode <= 86400 ){
return Array(floor($periode/(60*60)), 'hours');
} else {
return Array(floor($periode/(24*60*60)), 'days');
}
}
public static function ToPercent($val, $tot, $prec=0){
if ( $tot == 0 ){
trigger_error('ToPercent Failed, total is Zero !', E_USER_WARNING);
return 0;
}
return round(($val/$tot)*100, $prec);
}
//----------------------------------------------------------------- PHP EXTENTION AUTOLOAD
public static function isphpModLoaded($mod){
return extension_loaded($mod);
}
public static function LoadphpMod($mod){
if ( !CORE::isphpModLoaded($mod) ) {
$prefix = (PHP_SHLIB_SUFFIX === 'dll') ? 'php_' : '';
if ( ! @dl($prefix.$mod.'.'.PHP_SHLIB_SUFFIX) ){
return FALSE;
}
}
return TRUE;
}
public static function getphpModLoaded(){
return get_loaded_extensions();
}
//----------------------------------------------------------------- PHP EXTENTION AUTOLOAD
//----------------------------------------------------------------- PHP AUTO INCLUDE
public static function inclass($class){
//echo 'including => '.$class."<br>";
$p = self::getdeps(PATH_LIBS, $class, NULL, 'class', 'php');
if ( FALSE === $p ){
errors::raise('Missing Librairy "'.$class.'", plz check your PATH_LIBS setting.', CORE_LOG_CRIT, 'CORE');
} elseif ( REDIRECT_PHP_ERRORS ){
if ( !assert('(FALSE !== include($p))') ){
errors::raise("Librairy '$class' contains an errors", CORE_LOG_CRIT, 'CORE');
echo 'assert failed for : '.$class.'<br>';
} else {
//echo 'assert ok for : '.$class.'<br>';
}
//echo 'post assert -- '.isset($result).'<br>';
} else {
include($p);
}
if ( FALSE === class_exists($class, FALSE) ){
errors::raise('Strange file "'.$p.'" has been included successfully, but the class "'.$class.'" has not been defined,
maybe wrong file/class names.', CORE_LOG_CRIT, 'CORE');
die('Strange file has been included successfully, but the class has not been defined,
you can try to enable php error redirection to get the assert result.');
return FALSE;
}
//errors::raise("Class $class included from file '$p'",CORE_LOG_NOTICE, 'CORE');
//echo "Class $class included from file '$p'\n";
return TRUE;
}
private static function dep_cache($path){
if ( !is_dir($path) ){ return FALSE;}
if ( ! $hdl = openDir($path) ) { return FALSE;}
//echo "dep_caching : $path<br>\n";
while( $dir = readDir($hdl) ){
if ( $dir != "." AND $dir != ".." ){
if ( is_dir($path.'/'.$dir) ){
//echo "folder for $path => $dir<br/>\n";
$o['folders'][$path.'/'.$dir] = self::dep_cache($path.'/'.$dir);
} else {
//echo "file for $path => $dir<br/>\n";
$o['files'][] = $dir;
}
}
}
closeDir($hdl);
return $o;
}
private static function dep_cache_search(&$base, $match, $folder){
//echo "dep_cache_search : $match in $folder<br>\n";
if ( !is_array($base) ){ return FALSE; }
if ( isset($base['files']) ){
foreach($base['files'] as $k => &$file ){
if ( $file == $match ){
//echo "FOUND file $file in $folder VS $match<br/>\n";
return $folder.'/'.$file;
}
}
}
if ( isset($base['folders']) ){
foreach($base['folders'] as $path => &$nbase ){
$t = self::dep_cache_search(&$nbase, $match, $path);
if ( FALSE !== $t ){ return $t; }
}
}
return FALSE;
}
private static function getcachedeps($path, $match){
foreach($path as $k => &$folder ){
if ( ! isset(self::$DEPS[$folder]) ){
self::$DEPS[$folder] = self::dep_cache($folder);
//echo "dep cached : $folder => ".print_r(self::$DEPS[$folder], TRUE)."<br>\n";
}
$o = self::dep_cache_search(&self::$DEPS[$folder], $match, $folder);
if ( FALSE !== $o ){ return $o; }
}
return FALSE;
}
public static function getdeps($path, $match, $pref=NULL, $suf=NULL, $ext=NULL){
if( FALSE === chrono::isinit('deps') ){ chrono::init('deps'); }
$fname = $match;
if ( $pref !== NULL ){ $fname = $pref.$fname; }
if ( $suf !== NULL ){ $fname .= ".$suf"; }
if ( $ext !== NULL ){ $fname .= ".$ext"; }
if ( !is_array($path) ){ $path = split(PATH_SEPARATOR, $path); }
if ( self::CACHEDEPS ){
$chrk = chrono::start('deps');
$o = self::getcachedeps($path, $fname);
chrono::pause('deps', $chrk);
return $o;
}
if ( count($path) > 1 ){
foreach($path as $k => $folder ){
$r = self::getdeps($folder, $match, $pref, $suf, $ext);
if ( FALSE !== $r ){ return $r; }
}
return FALSE;
} else {
$path = $path[0];
}
if ( !is_dir($path) ){ return FALSE;}
if ( ! $hdl = openDir($path) ) { return FALSE;}
$chrk = chrono::start('deps');
while( $dir = readDir($hdl) ){
if ( $dir != "." AND $dir != ".." ){
if ( file_exists($path.'/'.$fname) ){
closeDir($hdl);
chrono::pause('deps', $chrk);
return $path.'/'.$fname;
} elseif ( is_dir($path.'/'.$dir) ){
if ( FALSE !== ( $r = self::getdeps($path.'/'.$dir, $match, $pref, $suf, $ext)) ){
closeDir($hdl);
chrono::pause('deps', $chrk);
return $r;
}
}
}
}
closeDir($hdl);
chrono::pause('deps', $chrk);
return FALSE;
}
public static function searchdeps($path, $match, $pref=NULL, $suf=NULL, $ext=NULL){
if( FALSE === chrono::isinit('deps') ){ chrono::init('deps'); }
if ( !is_array($path) ){ $path = split(PATH_SEPARATOR, $path); }
if ( count($path) > 1 ){
$o= Array();
foreach($path as $k => $base ){
$r = self::searchdeps($base, $match, $pref, $suf, $ext);
if ( $r !== FALSE ){
$o = array_merge($o, $r);
}
}
if ( empty($o) ){ return FALSE; }
return $o;
} else {
$path = $path[0];
}
if ( !is_dir($path) ){ return FALSE;}
if ( ! $hdl = openDir($path) ) { return FALSE;}
$chrk = chrono::start('deps');
$o=Array();
while( $dir = readDir($hdl) ){
if ( $dir != "." AND $dir != ".." ){
if ( is_dir($path.'/'.$dir) ){
$r = self::searchdeps($path.'/'.$dir, $match, $pref, $suf, $ext);
if ( FALSE !== $r ){
$o = array_merge($o, $r); }
} elseif ( ereg('^'.$pref, $dir) AND ereg($suf.'.'.$ext.'$', $dir) ){
if (!empty($match) ){
if ( TRUE === ereg("$match", $dir) ){ $o[] = $path.'/'.$dir; }
} else {
$o[] = $path.'/'.$dir;
}
}
}
}
chrono::pause('deps', $chrk);
if ( empty($o) ){ return FALSE; }
return $o;
}
//----------------------------------------------------------------- PHP AUTO INCLUDE
public static function hash($str=NULL, $len=NULL){
if ( NULL === $str ){ $str = md5(time().microtime()/rand(1,20)); }
$str = md5($str);
if ( NULL === $len ){ return $str; }
return substr($str, 0, $len);
}
public static function getintcharset(){ return 'UTF-8'; }
} //END CORE classe
//Error levels constants
if ( !defined('CORE_LOG_NOTICE') ){ define('CORE_LOG_NOTICE', 0); }
if ( !defined('CORE_LOG_DEBUG') ){ define('CORE_LOG_DEBUG', 1); }
if ( !defined('CORE_LOG_WARNING') ){ define('CORE_LOG_WARNING', 2); }
if ( !defined('CORE_LOG_INFO') ){ define('CORE_LOG_INFO', 3); }
if ( !defined('CORE_LOG_ERROR') ){ define('CORE_LOG_ERROR', 4); }
if ( !defined('CORE_LOG_ERR') ){ define('CORE_LOG_ERR', 4); }
if ( !defined('CORE_LOG_ALERT') ){ define('CORE_LOG_ALERT', 5); }
if ( !defined('CORE_LOG_FATAL') ){ define('CORE_LOG_FATAL', 5); }
if ( !defined('CORE_LOG_CRIT') ){ define('CORE_LOG_CRIT', 6); }
if ( !defined('CORE_LOG_EMERG') ){ define('CORE_LOG_EMERG', 7); }
//PHP5 classes autoload feature.
function __autoload($class) { CORE::inclass($class); }
//PHP ERROR REDIRECTION
if ( !defined('REDIRECT_PHP_ERRORS') ){ define('REDIRECT_PHP_ERRORS', FALSE); }
//do we hidde events prefixed with the error suppression directive "@"
if ( !defined('FOLLOW_ERROR_DIRECTIVE') ){ define('FOLLOW_ERROR_DIRECTIVE', TRUE); }
//do we redirect php error to our errors object ?
if ( REDIRECT_PHP_ERRORS ){
//To prevent hangup on a ugly parse/compil error
assert_options(ASSERT_ACTIVE, 1);
assert_options(ASSERT_WARNING, 0);
assert_options(ASSERT_QUIET_EVAL, 0);
assert_options(ASSERT_BAIL, 0);
assert_options(ASSERT_CALLBACK, 'assert_error');
function assert_error($script, $line, $message) {
$msg = 'The script "'.$script.'" got a syntax error at line '.$line." : \n".$message;
errors::raise($msg, CORE_LOG_CRIT, 'ASSERT');
return TRUE;
}
/*
This function replace the default php error handler.
Translate the php error code to the coresponding core error code
It use the errors object to expose the event.
@return void
*/
function php_error($code, $msg, $file, $line){
//echo 'E-R :'.ini_get('error_reporting').'<br>';
if( FOLLOW_ERROR_DIRECTIVE && error_reporting() == 0 ){ return TRUE; }
//err type //core error code
$levels[E_NOTICE] = CORE_LOG_NOTICE;
$levels[E_WARNING] = CORE_LOG_WARNING;
$levels[E_ERROR] = CORE_LOG_ERR;
$levels[E_PARSE] = CORE_LOG_ERR;
$levels[E_STRICT] = CORE_LOG_NOTICE;
$levels[E_USER_NOTICE] = CORE_LOG_NOTICE;
$levels[E_USER_WARNING] = CORE_LOG_WARNING;
$levels[E_USER_ERROR] = CORE_LOG_ERR;
$levels[E_CORE_WARNING] = CORE_LOG_WARNING;
$levels[E_CORE_ERROR] = CORE_LOG_ERR;
$levels[E_COMPILE_WARNING] = CORE_LOG_WARNING;
$levels[E_COMPILE_ERROR] = CORE_LOG_ERR;
if ( class_exists('errors') ){
if ( !isset($levels[$code]) ){
$lvl = CORE_LOG_ERR;
} else {
$lvl = $levels[$code];
}
$err = new error($msg, $lvl, 'PHP');
$err->setline($line);
$err->setfile(basename($file));
errors::broadcast($err);
} else {
echo "PHPERR : $file:$line -- $msg<br>";
}
return TRUE;
}
//We change the php error handler to make it use the function just on top.
set_error_handler('php_error');
}
//PEAR ERROR REDIRECTION
if ( !defined('REDIRECT_PEAR_ERRORS') ){ define('REDIRECT_PEAR_ERRORS', FALSE); }
//do we redirect PEAR error to our errors object ?
if ( REDIRECT_PEAR_ERRORS ){
/*
@return void
*/
function pear_error($err){
errors::raise($err->message, $err->code, 'PEAR');
}
if ( class_exists('PEAR') ){
//We change the pear error handler to make it use our function.
PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, "pear_error");
}
}
if ( !function_exists('sys_get_temp_dir') ){
// Based on http://www.phpit.net/
// article/creating-zip-tar-archives-dynamically-php/2/
function sys_get_temp_dir(){
// Try to get from environment variable
if ( !empty($_ENV['TMP']) ){ return realpath( $_ENV['TMP'] );
} elseif ( !empty($_ENV['TMPDIR']) ){ return realpath( $_ENV['TMPDIR'] );
} elseif ( !empty($_ENV['TEMP']) ){ return realpath( $_ENV['TEMP'] ); }
static $temp_dir;
if ( isset($temp_dir) ){ return $temp_dir; }
// Detect by creating a temporary file
$temp_file = tempnam( md5(uniqid(rand(), TRUE)), '' );
if ( $temp_file ){
$temp_dir = realpath( dirname($temp_file) );
unlink( $temp_file );unset($temp_file);
} else {
$temp_dir = FALSE;
}
return $temp_dir;
}
}