<?php


# if the function filter_var does not exists create a replacement function as fallback
if(!function_exists("filter_var") ){
    # define the labels..
    define("FILTER_SANITIZE_STRING","FILTER_SANITIZE_STRING");
    define("FILTER_SANITIZE_URL","FILTER_SANITIZE_URL");
    define("FILTER_VALIDATE_EMAIL","FILTER_VALIDATE_EMAIL");

    # create the fallback function for filter_var ** Return False on error!
    function filter_var($variable,$filter){

        # Strip tags, optionally strip or encode special characters
        if($filter == FILTER_SANITIZE_STRING){
            return strip_tags($variable);
        }

        # This filter allows all letters, digits and $-_.+!*'(),{}|\\^~[]`"><#%;/?:@&=
        if($filter == FILTER_SANITIZE_URL){
            $regex = "[^a-zA-z-0-9\$\-\_\.\+\!\*\'\(\)\,\{\}\|\\\^\~\[\]\`\"\>\<\#\%\;\/\?\:\@\&\=]";
             return preg_replace("/$regex/i","",$variable);
            return false;
        }

        # Validate value as e-mail
        if($filter == FILTER_VALIDATE_EMAIL){
            $regex = "^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$";
            if(preg_match("/$regex/i", $variable)) {
                return $variable;
            } else {
                return FALSE;
            }
        }
        return $variable;
    }

    # create a fallback for filter_var_array if filter_var does not exists
    function filter_var_array($variable,$filter){
        $temp = [];
        foreach($variable as $k => $v){
            $temp[$k] = filter_var($v,$filter);
        }
        return $temp;
    }
}

# this adds json support to PHP versions that don't have it
if(!function_exists('json_encode')) {
    include_once("components/json/JSON.php");
    $GLOBALS['JSON_OBJECT'] = new Services_JSON();
    function json_encode($value)
    {
        return $GLOBALS['JSON_OBJECT']->encode($value); 
    }
    
    function json_decode($value, $assoc = false)
    {
        if ($assoc == true) {
            return stdToAssoc($GLOBALS['JSON_OBJECT']->decode($value));
        } else {
            return $GLOBALS['JSON_OBJECT']->decode($value);
        }
    }
}

# if memory usage does not exists return 0
if (!function_exists('memory_get_usage')){
	function memory_get_usage(){
		return 0;
	}
}

if(!function_exists("stdToAssoc")){
    function stdToAssoc($obj) {
        $array = [];

        if(empty($obj)){
            return null;
        }
        foreach($obj as $key => $value) {
            if(is_object($value) == true || is_array($value) == true) {
                $array[$key] = stdToAssoc($value);
            } else {
                $array[$key] = $value;
            }
        }
        
        return $array;
    }
}
?>