<?php
///////////////////////////////////////////////////////////////////////////////////////////
///Script PHP/MYSQL of management of classifieds ads developed by Script PAG
///Script PAG all rights reserved. Use under license. http://www.script-pag.com
///////////////////////////////////////////////////////////////////////////////////////////

############################################################ 

class loader {
	/*** @var _paths array*/
	private $_paths = [];
	/*** @var _loader self*/
	private static $_loader;
	
	//// Class constructor
	private function __construct() {
		$this->_paths['modules'] = __DIR__ ? __DIR__.DIRECTORY_SEPARATOR.'functions' : null;
		spl_autoload_register(array($this, 'autoload'), true, true);
		set_include_path(implode(PATH_SEPARATOR, $this->_paths).PATH_SEPARATOR.get_include_path());
		spl_autoload_extensions('Class.php,Controller.php,Module.php,Model.php,CacheModel.php,.php,View.php,.php');
	}
	
	//// Auto load class function
	public function autoload($classname) {
		return spl_autoload($classname);
	}
	
	//// Return self instance after initialization after create it if not exists
	public static function init() {
		if(self::$_loader == null) self::$_loader = new self();
		return self::$_loader;
	}
	
	//// Inlude file function
	public static function load($file, $once = true) {
		$loaded = false;
		$filename = str_replace((DIRECTORY_SEPARATOR == '/' ? '\\' : '/'), DIRECTORY_SEPARATOR, self::path($file));
		if(file_exists($filename)) {
			if($once && $once == true) $loaded = require_once $filename;
			else $loaded = include self::path($filename);
		}
		return $loaded;
	}
	
	//// Test if the file / dir exists		
	public static function exists($file) {
		$filename = str_replace((DIRECTORY_SEPARATOR == '/' ? '\\' : '/'), DIRECTORY_SEPARATOR, self::path($file));
		return file_exists($filename) ? $filename : (file_exists($file) ? $file : false);
	}
	
	//// Return real file path
	public static function path($file) {
		$clean_file = self::clean($file);
		return self::$_loader->_paths['modules'].(substr($clean_file, 0, 1) != DIRECTORY_SEPARATOR ? DIRECTORY_SEPARATOR : '').$clean_file;
	}
	
	//// Return real file path for cache file
	public static function cachePath($file) {
		return self::$_loader->_paths['modules'].DIRECTORY_SEPARATOR.str_replace('/', DIRECTORY_SEPARATOR, str_replace('\\', DIRECTORY_SEPARATOR, self::clean($file)));
	}
	
	//// Remove unauthorized characters and clean path
	public static function clean($string) {
		$string = preg_replace('#[^\p{L}\p{N}_\-.\\\:@]#iu', '', str_replace('/', '\\', $string));
		return str_replace((DIRECTORY_SEPARATOR == '/' ? '\\' : '/'), DIRECTORY_SEPARATOR, $string);
	}
}