PageRenderTime 61ms CodeModel.GetById 38ms app.highlight 19ms RepoModel.GetById 1ms app.codeStats 0ms

/core/App.php

https://bitbucket.org/likeping/lkp
PHP | 339 lines | 244 code | 28 blank | 67 comment | 68 complexity | 67de4e883829de66e391c220d19e6467 MD5 | raw file
  1<?php
  2/**
  3 * App.php
  4 * 核心类,并初始化系统的基本设置
  5 */
  6
  7if (!defined('IN_FINECMS')) exit();
  8 
  9error_reporting(E_ALL^E_NOTICE);
 10
 11/**
 12 * 配置
 13 */
 14
 15define('SYS_ROOT',           dirname(__FILE__) . DIRECTORY_SEPARATOR);          //核心文件所在路径
 16define('SYS_START_TIME',     microtime(true));                                  //设置程序开始执行时间
 17define('CONTROLLER_DIR',     APP_ROOT . 'controllers' . DIRECTORY_SEPARATOR);   //controller目录的路径
 18define('MODEL_DIR',          APP_ROOT . 'models' . DIRECTORY_SEPARATOR);        //model目录的路径	
 19define('VIEW_DIR',           APP_ROOT . 'views' . DIRECTORY_SEPARATOR);         //view目录的路径
 20define('CONFIG_DIR',         APP_ROOT . 'config' . DIRECTORY_SEPARATOR);        //config目录的路径
 21define('EXTENSION_PATH',     'extensions');                                     //extension目录文件夹
 22define('EXTENSION_DIR',      APP_ROOT . EXTENSION_PATH . DIRECTORY_SEPARATOR);  //extension目录的路径
 23define('PLUGIN_DIR',         APP_ROOT . 'plugins' . DIRECTORY_SEPARATOR);       //插件目录文件夹
 24define('SYS_THEME_DIR',      $config['SITE_THEME'] . DIRECTORY_SEPARATOR);      //模板风格
 25define('DEFAULT_CONTROLLER', 'Index');                                          //设置系统默认的controller名称,默认为:Index
 26define('DEFAULT_ACTION',     'index');                                          //设置系统默认的action名称,默认为index
 27define('SYS_LOG',            $config['SYS_LOG']);                               //设置是否开启运行日志
 28define('SYS_DEBUG',          $config['SYS_DEBUG']);                             //设置是否开启调试模式.开启后,程序运行出现错误时,显示错误信息
 29define('SYS_DOMAIN',         $config['SYS_DOMAIN']);                            //域名目录,针对虚拟主机用户
 30define('URL_SEGEMENTATION',  '/');                                              //定义网址路由的分割符
 31define('ENTRY_SCRIPT_NAME',  'index.php');                                      //定义入口文件名
 32define('SITE_MEMBER_COOKIE', $config['SITE_MEMBER_COOKIE']);                    //会员登录Cookie随机字符码
 33define('SYS_ATTACK_LOG',     isset($config['SYS_ATTACK_LOG']) && $config['SYS_ATTACK_LOG']     ? $config['SYS_ATTACK_LOG']  : false);          //系统攻击日志开关
 34define('SYS_LANGUAGE',       isset($config['SYS_LANGUAGE']) && $config['SYS_LANGUAGE']         ? $config['SYS_LANGUAGE']    : 'zh-cn');        //网站语言设置
 35define('ADMIN_NAMESPACE',    isset($config['ADMIN_NAMESPACE']) && $config['ADMIN_NAMESPACE']   ? $config['ADMIN_NAMESPACE'] : 'admin');        //定义后台管理路径的名字
 36define('SYS_VAR_PREX',       isset($config['SYS_VAR_PREX']) && $config['SYS_VAR_PREX']         ? $config['SYS_VAR_PREX']    : 'finecms_');     //SESSION和COOKIE变量前缀
 37define('TIME_FORMAT',        isset($config['SITE_TIME_FORMAT']) && $config['SITE_TIME_FORMAT'] ? $config['SITE_TIME_FORMAT'] : 'Y-m-d H:i:s'); //输出时间格式化
 38define('SYS_TIME_ZONE',      'Etc/GMT' . ($config['SITE_TIMEZONE'] > 0 ? '-' : '+') . (abs($config['SITE_TIMEZONE'])));                        //时区
 39define('LANGUAGE_DIR',       EXTENSION_DIR . 'language' . DIRECTORY_SEPARATOR . SYS_LANGUAGE . DIRECTORY_SEPARATOR);                           //网站语言文件
 40
 41/**
 42 * 环境参数
 43 */
 44
 45if (!file_exists(LANGUAGE_DIR)) exit('语言目录不存在:' . LANGUAGE_DIR);
 46if (function_exists('ini_set'))  SYS_DEBUG ? ini_set('display_errors', true) : ini_set('display_errors', false);
 47if (function_exists('ini_set'))  ini_set('memory_limit', '1024M');
 48date_default_timezone_set(SYS_TIME_ZONE);
 49if (isset($config['SYS_GZIP']) && $config['SYS_GZIP'] && function_exists('ob_gzhandler')) ob_start('ob_gzhandler');
 50$language = require LANGUAGE_DIR . 'lang.php';
 51
 52/**
 53 * 系统核心全局控制类
 54 */
 55
 56abstract class App {
 57    
 58	public static $namespace;
 59	public static $controller;
 60	public static $action;
 61	public static $plugin;
 62	public static $_objects   = array();
 63	public static $_inc_files = array();
 64	public static $config     = array();
 65	
 66	/**
 67	 * 分析URL信息
 68	 */
 69	private static function parse_request() {
 70	    if (SYS_DOMAIN) {
 71		    $_SERVER['SCRIPT_NAME'] = str_replace('/' . SYS_DOMAIN, '', $_SERVER['SCRIPT_NAME']);
 72			$_SERVER['REQUEST_URI'] = str_replace('/' . SYS_DOMAIN, '', $_SERVER['REQUEST_URI']);
 73		}
 74		$path_url_string = isset($_SERVER['QUERY_STRING']) && $_SERVER['QUERY_STRING'] ? $_SERVER['QUERY_STRING'] : $_SERVER['REQUEST_URI'];
 75		$new_url_string  = '';
 76		if (!isset($_SERVER['QUERY_STRING']) || empty($_SERVER['QUERY_STRING'])) {
 77			$router_config_file = CONFIG_DIR . 'router.ini.php';
 78			if (is_file($router_config_file)) {
 79				$router_array   = require_once $router_config_file;
 80				if (is_array($router_array) && !empty($router_array)) {
 81					$path_url_router = str_replace(str_replace('/' . ENTRY_SCRIPT_NAME, '', $_SERVER['SCRIPT_NAME']), '', $_SERVER['REQUEST_URI']);
 82					$path_url_router = str_replace('/' . ENTRY_SCRIPT_NAME, '', $path_url_router);
 83					if (substr($path_url_router, 0, 1) == '/') $path_url_router = substr($path_url_router, 1);
 84					if ($path_url_router) {
 85						foreach ($router_array as $router_key=>$router_value) {									
 86							if (preg_match('#' . $router_key . '#', $path_url_router)) {
 87							    $new_url_string = preg_replace('#' . $router_key . '#', $router_value, $path_url_router);
 88								break;
 89							}
 90						}
 91						if (empty($new_url_string)) self::display_404_error(0);
 92					}
 93				}
 94			}
 95		}
 96		$path_url_string  = $new_url_string ? $new_url_string : $path_url_string;
 97		parse_str($path_url_string, $url_info_array);
 98		$namespace_name   = trim((isset($url_info_array['s']) && $url_info_array['s']) ? $url_info_array['s'] : '');
 99		$controller_name  = trim((isset($url_info_array['c']) && $url_info_array['c']) ? $url_info_array['c'] : DEFAULT_CONTROLLER);						
100		$action_name      = trim((isset($url_info_array['a']) && $url_info_array['a']) ? $url_info_array['a'] : DEFAULT_ACTION);
101		if ($namespace_name == 'admin' && ADMIN_NAMESPACE != 'admin') self::display_404_error(5);
102		$namespace_name   = $namespace_name == ADMIN_NAMESPACE ? 'admin' : $namespace_name;
103		self::$namespace  = strtolower($namespace_name);
104		self::$controller = ucfirst(strtolower($controller_name));
105		self::$action 	  = strtolower($action_name);
106		$_GET             = array_merge($_GET, $url_info_array);
107		return true;
108	}
109	
110	/**
111	 * 项目运行函数
112	 */
113	public static function run($config) {
114		static $_app    = array();
115		self::$config   = $config;
116		self::parse_request();
117		$app_id         = self::$controller . '_' . self::$action;
118		if (!isset($_app[$app_id]) || $_app[$app_id] == null) {
119			$namespace  = self::$namespace;
120			$controller = self::$controller . 'Controller';
121			$action     = self::$action . 'Action';
122			self::load_file(SYS_ROOT . 'Base.php');
123			self::load_file(SYS_ROOT . 'Controller.php');
124			self::load_file(CONTROLLER_DIR . 'Common.php');
125			if ($namespace && is_dir(CONTROLLER_DIR . $namespace)) {
126				$controller_file = CONTROLLER_DIR . $namespace . DIRECTORY_SEPARATOR . $controller . '.php';
127				if (!is_file($controller_file)) self::display_404_error(1);
128				if (is_file(CONTROLLER_DIR . $namespace . DIRECTORY_SEPARATOR . 'Common.php')) self::load_file(CONTROLLER_DIR . $namespace . DIRECTORY_SEPARATOR . 'Common.php');
129			    self::load_file($controller_file);
130			} elseif ($namespace && is_dir(PLUGIN_DIR . $namespace)) {
131			    $common_file      = PLUGIN_DIR . $namespace . DIRECTORY_SEPARATOR . 'controllers' . DIRECTORY_SEPARATOR . 'Common.php';
132				$controller_file  = PLUGIN_DIR . $namespace . DIRECTORY_SEPARATOR . 'controllers' . DIRECTORY_SEPARATOR . $controller . '.php';
133				if (is_file($common_file) && is_file($controller_file)) {
134				    self::$plugin =  strtolower($namespace);
135					self::load_file($common_file);
136					self::load_file($controller_file);
137				} else {
138					self::display_404_error(2);
139				}						
140			} elseif (is_file(CONTROLLER_DIR . $controller . '.php')) {	
141				self::load_file(CONTROLLER_DIR . $controller . '.php');				
142			} else {
143			    self::display_404_error(3);		
144			}
145			$app_object = new $controller();
146			if (method_exists($controller, $action)) {
147				$_app[$app_id] = $app_object->$action();
148			} else {
149				self::display_404_error(4);
150			}
151		}
152		return $_app[$app_id];
153	}
154	
155	/**
156	 * 显示404错误提示
157	 */
158	private static function display_404_error($id=0) {
159	    header('HTTP/1.1 404 Not Found');
160		require SYS_ROOT . 'html/error404.php';
161		exit();		
162	}
163	
164	/**
165     * 显示错误提示
166     */
167    public static function display_error($message, $back=0) {
168        if (!$message) return false;
169		require SYS_ROOT . 'html/message.php';
170        exit();
171    }
172	
173	/**
174	 * 核心类引导数组
175	 */
176	public static $core_class_array = array(
177		'Model'     		=> 'Model.php',
178		'Log'       		=> 'Log.php',
179		'View'				=> 'View.php',
180		'mysql'				=> 'lib/mysql.class.php',
181		'html'				=> 'lib/html.class.php',
182		'cache_file'		=> 'lib/cache_file.class.php',
183		'pagelist'			=> 'lib/pagelist.class.php',
184		'cookie'			=> 'lib/cookie.class.php',
185		'session'			=> 'lib/session.class.php',
186		'file_list'			=> 'lib/file_list.class.php',
187		'image_lib'			=> 'lib/image_lib.class.php',
188		'check'				=> 'lib/check.class.php',
189		'file_upload'		=> 'lib/file_upload.class.php',
190		'client'			=> 'lib/client.class.php',
191		'pinyin'			=> 'lib/pinyin.class.php',
192		'tree'				=> 'lib/tree.class.php',
193		'loader'			=> 'lib/loader.class.php',
194		'auth'              => 'lib/auth.class.php',
195		'mail'              => 'lib/mail.class.php',
196		'captcha'           => 'lib/captcha.class.php',
197		'pclzip'            => 'lib/pclzip.class.php',
198		'linkage_tree'      => 'lib/linkage_tree.class.php',
199	);
200	
201	/**
202	 * 项目文件的自动加载
203	 */
204	public static function auto_load($class_name) {
205		if (isset(self::$core_class_array[$class_name])) {				
206			self::load_file(SYS_ROOT . self::$core_class_array[$class_name]);			
207		} else if (substr($class_name, -5) == 'Model') {	
208			if (is_file(MODEL_DIR . $class_name . '.php')) {
209				self::load_file(MODEL_DIR . $class_name . '.php');
210			} elseif ((is_file(PLUGIN_DIR . self::$namespace. DIRECTORY_SEPARATOR . 'models' . DIRECTORY_SEPARATOR . $class_name . '.php'))) {
211			    self::load_file(PLUGIN_DIR . self::$namespace. DIRECTORY_SEPARATOR . 'models' . DIRECTORY_SEPARATOR . $class_name . '.php');
212			} else {
213				Controller::halt('The Model file: ' . $class_name . ' is not exists!');	
214			}
215		} else {
216			if (is_file(EXTENSION_DIR . $class_name . '.php')) {
217				self::load_file(EXTENSION_DIR . $class_name . '.php');
218			} else {
219				Controller::halt('The File:' . $class_name . '.php is not exists!');
220			}		
221		}
222	}
223	
224	/**
225	 * 获取当前运行的namespace名称
226	 */
227	public static function get_namespace_id() {
228		return strtolower(self::$namespace);
229	}
230	
231	/**
232	 * 获取当前运行的controller名称
233	 */
234	public static function get_controller_id() {
235		return strtolower(self::$controller);
236	}
237	
238	/**
239	 * 获取当前运行的action名称
240	 */
241	public static function get_action_id() {
242		return self::$action;
243	}
244	
245	/**
246	 * 获取配置信息
247	 */
248	public static function get_config() {
249	    $data = self::$config;
250		$data['PLUGIN_DIR'] = basename(PLUGIN_DIR);
251	    return $data;
252	}
253	
254   /**
255	 * 获取当前运行的plugin名称
256	 */
257	public static function get_plugin_id() {
258		return self::$plugin;
259	}
260	
261	/**
262	 * 单例模式
263	 */
264	public static function singleton($class_name) {
265		if (!$class_name) return false;
266		$key = strtolower($class_name);
267		if (isset(self::$_objects[$key])) return self::$_objects[$key];
268		return self::$_objects[$key] = new $class_name();
269	}
270	
271	/**
272	 * 返回插件模型的唯一实例(单例模式)
273	 */
274    public static function plugin_model($plugin, $table_name) {
275	    if (!$table_name || !$plugin) return false;
276		$model_name = ucfirst(strtolower($table_name)) . 'Model';
277	    $model_file = PLUGIN_DIR . $plugin . DIRECTORY_SEPARATOR . 'models' . DIRECTORY_SEPARATOR . $model_name . '.php';
278	    if (!is_file($model_file)) Controller::halt('The pluginModel(#' . $plugin . ') file:' . $model_name . '.php is not exists!');
279	    $key        = strtolower($model_name);
280	    if (isset(self::$_objects[$key])) return self::$_objects[$key];
281	    require $model_file;
282		return self::$_objects[$key] = new $model_name();
283	}
284	
285	/**
286	 * 静态加载文件
287	 */
288	public static function load_file($file_name) {
289		if (!$file_name) return false;
290		if (!isset(self::$_inc_files[$file_name]) || self::$_inc_files[$file_name] == false) {
291			if (!is_file($file_name)) Controller::halt('The file:' . $file_name . ' not found!');
292			include_once $file_name;
293			self::$_inc_files[$file_name] = true;
294		}
295		return self::$_inc_files[$file_name];
296	}
297}
298
299/**
300 * URL函数
301 */
302function url($route, $params = null) {
303	return Controller::create_url($route, $params);
304}
305
306/**
307 * 插件中的URL函数
308 */
309function purl($route, $params = null) {
310	$route = App::get_namespace_id() . '/' . $route;
311	return url($route, $params);
312}
313
314/**
315 * 语言调用函数
316 */
317function lang($name, $data=null) {
318    global $language;
319	$string   = isset($language[$name]) ? $language[$name] : '未知(#' . $name . ')';
320	if ($data) {
321	    foreach ($data as $r=>$t) {
322		    $string = str_replace('{' . $r . '}', $t, $string);
323		}
324	}
325	return $string;
326}
327
328/**
329 * 程序执行时间
330 */
331function runtime() {
332	$temptime = explode(' ', SYS_START_TIME);
333	$time     = $temptime[1] + $temptime[0];
334	$temptime = explode(' ', microtime());
335	$now      = $temptime[1] + $temptime[0];
336	return number_format($now - $time, 6);
337}
338
339spl_autoload_register(array('App', 'auto_load'));