initphp.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775
  1. <?php
  2. /*********************************************************************************
  3. * InitPHP 3.8.1 国产PHP开发框架 框架入口文件 核心框架文件
  4. *-------------------------------------------------------------------------------
  5. * 版权所有: CopyRight By initphp.com
  6. * 您可以自由使用该源码,但是在使用过程中,请保留作者信息。尊重他人劳动成果就是尊重自己
  7. *-------------------------------------------------------------------------------
  8. * Author:zhuli Dtime:2014-11-25
  9. ***********************************************************************************/
  10. require_once('init/core.init.php'); //导入核心类文件
  11. require_once('init/exception.init.php'); //导入核心类文件
  12. require_once('init/interceptorInterface.init.php'); //导入拦截器接口
  13. define("ERROR", "ERROR");
  14. define("WARN", "WARN");
  15. define("DEBUG", "DEBUG");
  16. define("INFO", "INFO");
  17. class InitPHP extends coreInit {
  18. public static $time;
  19. /**
  20. * debug模式打印所有PHP错误信息
  21. */
  22. private static function isDebug() {
  23. $InitPHP_conf = InitPHP::getConfig();
  24. if (isset($InitPHP_conf['is_debug']) && $InitPHP_conf['is_debug'] == true && isset($InitPHP_conf['show_all_error']) && $InitPHP_conf['show_all_error'] == true) {
  25. error_reporting(E_ALL^E_NOTICE);
  26. }
  27. }
  28. /**
  29. * 运行InitPHP开发框架 - 框架运行核心函
  30. * 1. 在index.php中实例化InitPHP启动类 InitPHP::init();
  31. * 2. 初始化网站路由,运行框架
  32. * 3. 全局使用方法:InitPHP::init();
  33. * @return object
  34. */
  35. public static function init() {
  36. self::isDebug();
  37. try {
  38. require(INITPHP_PATH . '/init/dispatcher.init.php');
  39. require(INITPHP_PATH . '/init/run.init.php');
  40. require(INITPHP_PATH . '/init/interceptor.init.php'); //拦截器
  41. $dispacher = InitPHP::loadclass('dispatcherInit');
  42. $dispacher->dispatcher();
  43. $run = InitPHP::loadclass('runInit');
  44. $run->run();
  45. } catch (exceptionInit $e) {
  46. exceptionInit::errorTpl($e);
  47. } catch (Exception $e) {
  48. exceptionInit::errorTpl($e);
  49. }
  50. }
  51. /**
  52. * 命令行模式运行php
  53. * 1. 例如:/usr/lib/php /usr/local/web/www/index.php index test sq
  54. * 2. index 控制器名称 test Action名称 sql controller/文件夹下的文件名称
  55. * 3. 全局使用方法:InitPHP::cli_init();
  56. * @return object
  57. */
  58. public static function cli_init($argv) {
  59. self::isDebug();
  60. try {
  61. $InitPHP_conf = InitPHP::getConfig();
  62. $argv[1] = ($argv[1] == '') ? '' : trim($argv[1]) . $InitPHP_conf['controller']['controller_postfix'];
  63. $argv[2] = ($argv[2] == '') ? '' : trim($argv[2]) . $InitPHP_conf['controller']['action_postfix'];
  64. $argv[3] = ($argv[3] == '') ? '' : trim($argv[3]);
  65. InitPHP::getController($argv[1], $argv[2], $params = array(), "");
  66. } catch (exceptionInit $e) {
  67. exceptionInit::cliErrorTpl($e);
  68. } catch (Exception $e) {
  69. exceptionInit::cliErrorTpl($e);
  70. }
  71. }
  72. /**
  73. * 启动RPC服务
  74. * 1. 最好只支持内网服务器之间的服务调用
  75. * 2. 开启RPC调用后,不同的程序可以直接调用Service的方法。
  76. * 3. 返回code=405 :调用失败,调用失败原因和调用的方式有关系
  77. * 4. 返回code=200 : 调用成功,返回业务结果
  78. * 5. 返回code=500 : 业务层面抛出异常
  79. *
  80. */
  81. public static function rpc_init() {
  82. self::isDebug();
  83. $ret = array();
  84. $params = json_decode(urldecode($_POST['params']), true);
  85. if (!is_array($params) || !$params['class'] || !$params['method']) {
  86. return InitPHP::rpc_ret(405, "params is error");
  87. }
  88. $class = $params['class']; //类名称
  89. $method = $params['method']; //方法名称
  90. $path = $params['path']; //方法名称
  91. $args = $params['args']; //参数数组
  92. //判断是否允许访问
  93. $InitPHP_conf = InitPHP::getConfig();
  94. $fullClass = ($path != "") ? rtrim($path, '/') . '/' . $class : $class;
  95. if (!isset($InitPHP_conf['provider']['allow']) || !in_array($fullClass, $InitPHP_conf['provider']['allow'])) {
  96. return InitPHP::rpc_ret(405, "This class is not allow to access");
  97. }
  98. //判断IP地址
  99. $ipLib = InitPHP::getLibrarys("ip");
  100. $ip = $ipLib->get_ip();
  101. $isAllowIp = true;
  102. if (isset($InitPHP_conf['provider']['allow_ip']) && is_array($InitPHP_conf['provider']['allow_ip'])) {
  103. $isAllowIp = false;
  104. foreach ($InitPHP_conf['provider']['allow_ip'] as $v) {
  105. if ($ip == $v) {
  106. $isAllowIp = true;
  107. break;
  108. } else {
  109. //IP段匹配
  110. if ($ipLib->ip_in_range($ip, $v) == true) {
  111. $isAllowIp = true;
  112. break;
  113. }
  114. }
  115. }
  116. }
  117. if ($isAllowIp == false) {
  118. return InitPHP::rpc_ret(405, "This ip address is not allow to access");
  119. }
  120. //判断类是否存在
  121. $obj = InitPHP::getService($class, $path);
  122. if (!$obj) {
  123. return InitPHP::rpc_ret(405, "can not find this class");
  124. }
  125. //调用方法
  126. $InitPHP_conf = InitPHP::getConfig();
  127. $classFullName = $class . $InitPHP_conf['service']['service_postfix'];
  128. if (!method_exists($obj, $method)) {
  129. return InitPHP::rpc_ret(405, "can not find this method");
  130. }
  131. $method = new ReflectionMethod($classFullName, $method);
  132. if (!$method || !$method->isPublic()) {
  133. return InitPHP::rpc_ret(405, "can not find this method");
  134. }
  135. try {
  136. if ($args == "" || !is_array($args)) {
  137. $result = $method->invoke($obj);
  138. } else {
  139. $result = $method->invokeArgs($obj, $args); //有参数的调用方式
  140. }
  141. return InitPHP::rpc_ret(200, "SUCCESS", $result);
  142. } catch (Exception $e) {
  143. return InitPHP::rpc_ret(500, "Exception", $e->getMessage());
  144. }
  145. }
  146. /**
  147. * RPC 返回结果
  148. * @param $code 错误码
  149. * @param $msg 错误信息
  150. * @param $data 错误内容
  151. */
  152. public static function rpc_ret($code, $msg, $data = null) {
  153. $ret = array();
  154. $ret['code'] = $code;
  155. $ret['msg'] = $msg;
  156. $ret['data'] = $data;
  157. exit(json_encode($ret));
  158. }
  159. /**
  160. * 框架加载文件函数 - 核心加载文
  161. * 1. 自定义文件路径,加载文件
  162. * 2. 自定义文件路径数组,自动查询,找到文件返回TRUE,找不到返回false
  163. * 3. 只需要文件名,import会自动加上APP_PATH
  164. * 全局使用方法:InitPHP::import($filename, $pathArr);
  165. * @param $filename 文件名称
  166. * @param $pathArr 文件路径
  167. * @return file
  168. */
  169. public static function import($filename_old, array $pathArr = array()) {
  170. $filename = InitPHP::getAppPath($filename_old);
  171. $temp_name = md5($filename);
  172. if (isset(parent::$instance['importfile'][$temp_name])) return true; //已经加载该文件,则不重复加载
  173. if (@is_readable($filename) == true && empty($pathArr)) {
  174. require($filename);
  175. parent::$instance['importfile'][$temp_name] = true; //设置已加载
  176. return true;
  177. } else {
  178. /* 自动搜索文件夹 */
  179. foreach ($pathArr as $val) {
  180. $new_filename = rtrim($val, '/') . '/' . $filename_old;
  181. $new_filename = InitPHP::getAppPath($new_filename);
  182. if (isset(parent::$instance['importfile'][$temp_name])) return true;
  183. if (@is_readable($new_filename)) {
  184. require($new_filename);// 载入文件
  185. parent::$instance['importfile'][$temp_name] = true;
  186. return true;
  187. }
  188. }
  189. }
  190. return false;
  191. }
  192. /**
  193. * 框架实例化php类函数,单例模式
  194. * 1. 单例模式-单例 实例化一个
  195. * 2. 可强制重新实例化
  196. * 全局使用方法:InitPHP::loadclass($classname, $force = false)
  197. * @param string $classname
  198. * @return object
  199. */
  200. public static function loadclass($classname, $force = false) {
  201. if (preg_match('/[^a-z0-9\-_.]/i', $classname)) InitPHP::initError('invalid classname');
  202. if ($force == true) unset(parent::$instance['loadclass'][$classname]);
  203. if (!isset(parent::$instance['loadclass'][$classname])) {
  204. if (!class_exists($classname)) InitPHP::initError($classname . ' is not exist!');
  205. $Init_class = new $classname;
  206. parent::$instance['loadclass'][$classname] = $Init_class;
  207. }
  208. return parent::$instance['loadclass'][$classname];
  209. }
  210. /**
  211. * 框架hook插件机制
  212. * 1. 采用钩子挂载机制,一个钩子上可以挂载多个执行
  213. * 2. hook机制需要配置框架配置文件运行
  214. * 全局使用方法:InitPHP::hook($hookname, $data = '');
  215. * @param string $hookname 挂钩名称
  216. * @param string $data 传递的参数
  217. * @return
  218. */
  219. public static function hook($hookname, $data = '') {
  220. $InitPHP_conf = InitPHP::getConfig();
  221. $hookconfig = $InitPHP_conf['hook']['path'] . '/' . $InitPHP_conf['hook']['config']; //配置文件
  222. $hookconfig = InitPHP::getAppPath($hookconfig);
  223. if (!isset(parent::$instance['inithookconfig']) && file_exists($hookconfig)) {
  224. parent::$instance['inithookconfig'] = require_once($hookconfig);
  225. }
  226. if (!isset(parent::$instance['inithookconfig'][$hookname])) return false;
  227. if (!is_array(parent::$instance['inithookconfig'][$hookname])) {
  228. self::_hook(parent::$instance['inithookconfig'][$hookname][0], parent::$instance['inithookconfig'][$hookname][1], $data);
  229. } else {
  230. foreach (parent::$instance['inithookconfig'][$hookname] as $v) {
  231. self::_hook($v[0], $v[1], $data);
  232. }
  233. }
  234. }
  235. /**
  236. * 框架hook插件机制-私有
  237. * @param string $class 钩子的类名
  238. * @param array $function 钩子方法名称
  239. * @param string $data 传递的参数
  240. * @return object
  241. */
  242. private static function _hook($class, $function, $data = '') {
  243. $InitPHP_conf = InitPHP::getConfig();
  244. if (preg_match('/[^a-z0-9\-_.]/i', $class)) return false;
  245. $file_name = $InitPHP_conf['hook']['path'] . '/' . $class . $InitPHP_conf['hook']['file_postfix'];
  246. $file_name = InitPHP::getAppPath($file_name);
  247. $class_name = $class . $InitPHP_conf['hook']['class_postfix']; //类名
  248. if (!file_exists($file_name)) return false;
  249. if (!isset(parent::$instance['inithook'][$class_name])) {
  250. require_once($file_name);
  251. if (!class_exists($class_name)) return false;
  252. $init_class = new $class_name;
  253. parent::$instance['inithook'][$class_name] = $init_class;
  254. }
  255. if (!method_exists($class_name, $function)) return false;
  256. return parent::$instance['inithook'][$class_name]->$function($data);
  257. }
  258. /**
  259. * XSS过滤,输出内容过滤
  260. * 1. 框架支持全局XSS过滤机制-全局开启将消耗PHP运行
  261. * 2. 手动添加XSS过滤函数,在模板页面中直接调用
  262. * 全局使用方法:InitPHP::output($string, $type = 'encode');
  263. * @param string $string 需要过滤的字符串
  264. * @param string $type encode HTML处理 | decode 反处理
  265. * @return string
  266. */
  267. public static function output($string, $type = 'encode') {
  268. $html = array("&", '"', "'", "<", ">", "%3C", "%3E");
  269. $html_code = array("&amp;", "&quot;", "&#039;", "&lt;", "&gt;", "&lt;", "&gt;");
  270. if ($type == 'encode') {
  271. if (function_exists('htmlspecialchars')) return htmlspecialchars($string);
  272. $str = str_replace($html, $html_code, $string);
  273. } else {
  274. if (function_exists('htmlspecialchars_decode')) return htmlspecialchars_decode($string);
  275. $str = str_replace($html_code, $html, $string);
  276. }
  277. return $str;
  278. }
  279. /**
  280. * 获取Service-实例并且单例模式获取Service
  281. * 1.单例模式获取
  282. * 2.可以选定对应Service路径path
  283. * 3. service需要在配置文件中配置参数,$path对应service目录中的子目录
  284. * 全局使用方法:InitPHP::getService($servicename, $path = '')
  285. * @param string $servicename 服务名称
  286. * @param string $path 模块名称
  287. * @return object
  288. */
  289. public static function getService($servicename, $path = '') {
  290. $InitPHP_conf = InitPHP::getConfig();
  291. $path = ($path == '') ? '' : $path . '/';
  292. $class = $servicename . $InitPHP_conf['service']['service_postfix'];
  293. $file = rtrim($InitPHP_conf['service']['path'], '/') . '/' . $path . $class . '.php';
  294. if (!InitPHP::import($file)) return false;
  295. return InitPHP::loadclass($class);
  296. }
  297. /**
  298. * 静态方式调用扩展库中的类
  299. * 单例模式,和$this->getLibrary方法是一样的
  300. * 全局使用方法:InitPHP::getLibrarys("curl")
  301. * @param $className 例如调用curlInit类,则$className = curl,不需要后缀 Init
  302. * @return object
  303. */
  304. public static function getLibrarys($className) {
  305. $classPath = INITPHP_PATH . "/library/" . $className . '.init.php';
  306. $classFullName = $className . "Init";
  307. if (!file_exists($classPath)) InitPHP::initError('file '. $class_name . '.php is not exist!');
  308. if (!isset(parent::$instance['initphp']['l'][$classFullName])) {
  309. require_once($classPath);
  310. if (!class_exists($classFullName)) InitPHP::initError('class' . $classFullName . ' is not exist!');
  311. $initClass = new $classFullName;
  312. parent::$instance['initphp']['l'][$classFullName] = $initClass;
  313. }
  314. return parent::$instance['initphp']['l'][$classFullName];
  315. }
  316. /**
  317. * 静态方式调用工具库中的类
  318. * 单例模式,和$this->getUtil方法是一样的
  319. * 全局使用方法:InitPHP::getUtils("queue")
  320. * @param $className 例如调用queueInit类,则$className = queue,不需要后缀 Init
  321. * @return object
  322. */
  323. public static function getUtils($className) {
  324. $classPath = INITPHP_PATH . "/core/util/" . $className . '.init.php';
  325. $classFullName = $className . "Init";
  326. if (!file_exists($classPath)) InitPHP::initError('file '. $class_name . '.php is not exist!');
  327. if (!isset(parent::$instance['initphp']['u'][$classFullName])) {
  328. require_once($classPath);
  329. if (!class_exists($classFullName)) InitPHP::initError('class' . $classFullName . ' is not exist!');
  330. $initClass = new $classFullName;
  331. parent::$instance['initphp']['u'][$classFullName] = $initClass;
  332. }
  333. return parent::$instance['initphp']['u'][$classFullName];
  334. }
  335. /**
  336. * 通过工具库中的日志类来记录日志
  337. * 全局使用方法:InitPHP::log("queue")
  338. * @param string $message 日志信息
  339. * @param string $log_type 日志类型 ERROR WARN DEBUG IN
  340. */
  341. public static function log($message, $log_type = 'DEBUG') {
  342. $log = InitPHP::getUtils("log"); //获取logInit对象实例
  343. $log->write($message, $log_type);
  344. }
  345. /**
  346. * 调用远程内网Service服务
  347. * 1. 如果调用成功,则返回结果
  348. * 2. 如果业务层异常,则抛出 Exception 异常信息,需要外部捕获处理
  349. * 3. 调用服务异常,则抛出 exceptionInit 异常信息,需要外部捕获处理
  350. * @param $class 类名称,例如userService,则user
  351. * @param $method 方法名称,例如 getUse
  352. * @param $args 参数,按照参数排序
  353. * @param $group 参数,分组参数
  354. * @param $path Service的模块名称
  355. * @param $timeout 最长请求时间
  356. */
  357. public static function getRemoteService($class, $method, $args = array(), $group = "default", $path = "", $timeout = 5) {
  358. $InitPHP_conf = InitPHP::getConfig();
  359. if (!isset($InitPHP_conf['customer']) || !isset($InitPHP_conf['customer'][$group])) {
  360. throw new exceptionInit("Please check your config:InitPHP_conf['customer']!", 405);
  361. }
  362. $i = rand(0,(count($InitPHP_conf['customer'][$group]['host']) - 1));
  363. $host = $InitPHP_conf['customer'][$group]['host'][$i];
  364. $file = $InitPHP_conf['customer'][$group]['file'];
  365. $url = "http://" . $host ."/" . ltrim($file, "/");
  366. $classPath = INITPHP_PATH . "/library/curl.init.php";
  367. require_once($classPath);
  368. $curl = new curlInit();
  369. $temp = array(
  370. "class" => $class,
  371. "method" => $method,
  372. "args" => $args,
  373. "path" => $path
  374. );
  375. $params = urlencode(json_encode($temp));
  376. try {
  377. $json = $curl->post($url, array("params" => $params), null, $timeout);
  378. } catch (Exception $e) {
  379. throw new exceptionInit("Curl call fail!", 405);
  380. }
  381. $ret = json_decode($json, true);
  382. //服务层调用失败,抛出exceptionInit异常
  383. if (!ret) {
  384. throw new exceptionInit("Rpc call fail!", 405);
  385. }
  386. if ($ret["code"] == 405) {
  387. throw new exceptionInit($ret['msg'], 405);
  388. }
  389. //业务层抛出异常
  390. if ($ret['code'] == 500) {
  391. throw new Exception($ret['data'], 500);
  392. }
  393. return $ret['data'];
  394. }
  395. /**
  396. * 获取Dao-实例并且单例模式获取Dao
  397. * 1.单例模式获取
  398. * 2.可以选定Dao路径path
  399. * 3. dao需要在配置文件中配置参数,$path对应dao目录中的子目录
  400. * 全局使用方法:InitPHP::getDao($daoname, $path = '')
  401. * @param string $daoname 服务名称
  402. * @param string $path 模块名称
  403. * @return object
  404. */
  405. public static function getDao($daoname, $path = '') {
  406. $InitPHP_conf = InitPHP::getConfig();
  407. $path = ($path == '') ? '' : $path . '/';
  408. $class = $daoname . $InitPHP_conf['dao']['dao_postfix'];
  409. $file = rtrim($InitPHP_conf['dao']['path'], '/') . '/' . $path . $class . '.php';
  410. if (!InitPHP::import($file)) return false;
  411. $obj = InitPHP::loadclass($class);
  412. return $obj;
  413. }
  414. /**
  415. * 组装URL
  416. * default:index.php?m=user&c=index&a=run
  417. * rewrite:/user/index/run/?id=100
  418. * path: /user/index/run/id/100
  419. * html: user-index-run.htm?uid=100
  420. * 全局使用方法:InitPHP::url('user|delete', array('id' => 100))
  421. * @param String $action m,c,a参数,一般写成 cms|user|add 这样的m|c|a结构
  422. * @param array $params URL中其它参数
  423. * @param String $baseUrl 是否有默认URL,如果有,则
  424. */
  425. public static function url($action, $params = array(), $baseUrl = '') {
  426. $InitPHP_conf = InitPHP::getConfig();
  427. $action = explode("|", $action);
  428. $baseUrl = ($baseUrl == '') ? rtrim($InitPHP_conf['url'], "/") . "/" : $baseUrl;
  429. $ismodule = $InitPHP_conf['ismodule'];
  430. switch ($InitPHP_conf['isuri']) {
  431. case 'rewrite' :
  432. $actionStr = implode('/', $action);
  433. $paramsStr = '';
  434. if ($params) {
  435. $paramsStr = '?' . http_build_query($params);
  436. }
  437. return $baseUrl . $actionStr . $paramsStr;
  438. break;
  439. case 'path' :
  440. $actionStr = implode('/', $action);
  441. $paramsStr = '';
  442. if ($params) {
  443. foreach ($params as $k => $v) {
  444. $paramsStr .= $k . '/' . $v . '/';
  445. }
  446. $paramsStr = '/' . $paramsStr;
  447. }
  448. return $baseUrl . $actionStr . $paramsStr;
  449. break;
  450. case 'html' :
  451. $actionStr = implode('-', $action);
  452. $actionStr = $actionStr . '.htm';
  453. $paramsStr = '';
  454. if ($params) {
  455. $paramsStr = '?' . http_build_query($params);
  456. }
  457. return $baseUrl . $actionStr . $paramsStr;
  458. break;
  459. default:
  460. $actionStr = '';
  461. if ($ismodule === true) {
  462. $actionStr .= 'm=' . $action[0];
  463. $actionStr .= '&c=' . $action[1];
  464. $actionStr .= '&a=' . $action[2] . '&';
  465. } else {
  466. $actionStr .= 'c=' . $action[0];
  467. $actionStr .= '&a=' . $action[1] . '&';
  468. }
  469. $actionStr = '?' . $actionStr;
  470. $paramsStr = '';
  471. if ($params) {
  472. $paramsStr = http_build_query($params);
  473. }
  474. return $baseUrl . $actionStr . $paramsStr;
  475. break;
  476. }
  477. }
  478. /**
  479. * 获取时间戳
  480. * 1. 静态时间戳函数
  481. * 全局使用方法:InitPHP::getTime();
  482. * @param $msg
  483. * @return html
  484. */
  485. public static function getTime() {
  486. if (self::$time > 0) return self::$time;
  487. self::$time = time();
  488. return self::$time;
  489. }
  490. /**
  491. * 框架控制访问器,主要用来控制是否有权限访问该模块
  492. * 1. InitPHP 页面访问主要通过3个参数来实现,m=模型,c=控制器,a=Action。m模型需要在应用开启模型的情况下执行
  493. * 2. $config是用户具体业务逻辑中,包含的用户访问权限白名单,我们根据白名单列表去判断用户是否具备权限
  494. * 3. 具备访问权限,返回true,否则false
  495. * 4. 返回false之后的具体业务逻辑需要用户自己做相应处理
  496. * 5. 开启$InitPHP_conf['ismodule']配置结构
  497. * array(
  498. * '模型名称' => array(
  499. * '控制器名称' => array('run', 'test', 'Action名称')
  500. * )
  501. * )
  502. * 6. 关闭$InitPHP_conf['ismodule']配置结构
  503. * array(
  504. * '控制器名称' => array('run', 'Action名称')
  505. * )
  506. * 7. 默认为空,则全部有权限
  507. * @param array $config
  508. */
  509. public static function acl($config = array()) {
  510. $InitPHP_conf = InitPHP::getConfig();
  511. if (!is_array($config) || empty($config)) return true;
  512. $c = ($_GET['c']) ? $_GET['c'] : $InitPHP_conf['controller']['default_controller'];
  513. $a = ($_GET['a']) ? $_GET['a'] : $InitPHP_conf['controller']['default_action'];
  514. if ($InitPHP_conf['ismodule']) {
  515. $m = $_GET['m'];
  516. if (isset($config[$m]) && isset($config[$m][$c]) && in_array($a, $config[$c])) {
  517. return true;
  518. }
  519. return false;
  520. } else {
  521. if (isset($config[$c]) && in_array($a, $config[$c]))
  522. return true;
  523. return false;
  524. }
  525. }
  526. /**
  527. * 获取全局配置文件
  528. * 全局使用方法:InitPHP::getConfig()
  529. * @param $msg
  530. * @return Array
  531. */
  532. public static function getConfig() {
  533. global $InitPHP_conf;
  534. return $InitPHP_conf;
  535. }
  536. /**
  537. * 设置配置文件,框架意外慎用!
  538. * @param $key
  539. * @param $value
  540. */
  541. public static function setConfig($key, $value) {
  542. global $InitPHP_conf;
  543. $InitPHP_conf[$key] = $value;
  544. return $InitPHP_conf;
  545. }
  546. /**
  547. * 获取项目路径
  548. * 全局使用方法:InitPHP::getAppPath('data/file.php')
  549. * @param $path
  550. * @return String
  551. */
  552. public static function getAppPath($path = '') {
  553. $tag = "INITPHP_OUT_PATH:";
  554. $ret = strstr($path, $tag);
  555. if ($ret != false) {
  556. return ltrim($path, $tag);
  557. }
  558. if (!defined('APP_PATH')) return $path;
  559. return rtrim(APP_PATH, '/') . '/' . $path;
  560. }
  561. /**
  562. * 框架错误机制
  563. * 1. 框架的错误信息输出函数,尽量不要使用在项目中
  564. * 全局使用方法:InitPHP::initError($msg)
  565. * @param $msg
  566. * @return html
  567. */
  568. public static function initError($msg, $code = 10000) {
  569. throw new exceptionInit($msg, $code);
  570. }
  571. /**
  572. * 调用其它Controller中的方法
  573. * 1. 一般不建议采用Controller调用另外一个Controller中的方法
  574. * 2. 该函数可以用于接口聚集,将各种接口聚集到一个接口中使用
  575. * 全局使用方法:InitPHP::getController($controllerName, $functionName)
  576. * @param $controllerName 控制器名称
  577. * @param $functionName 方法名称
  578. * @param $params 方法参数
  579. * @param $controllerPath 控制器文件夹名称,例如在控制器文件夹目录中,还有一层目录,user/则,该参数需要填写
  580. * @return
  581. */
  582. public function getController($controllerName, $functionName, $params = array(), $controllerPath = '') {
  583. $InitPHP_conf = InitPHP::getConfig();
  584. $controllerPath = ($controllerPath == '') ? '' : rtrim($controllerPath, '/') . '/';
  585. $path = rtrim($InitPHP_conf['controller']['path'], '/') . '/' . $controllerPath . $controllerName . '.php';
  586. InitPHP::import($path);
  587. $controller = InitPHP::loadclass($controllerName);
  588. if (!$controller)
  589. return InitPHP::initError('can not loadclass : ' . $controllerName);
  590. if (!method_exists($controller, $functionName))
  591. return InitPHP::initError('function is not exists : ' . $controllerName);
  592. if (!$params) {
  593. $controller->$functionName();
  594. } else {
  595. call_user_func_array(array($controller, $functionName), $params);
  596. }
  597. }
  598. /**
  599. * 返回404错误页面
  600. */
  601. public static function return404() {
  602. header('HTTP/1.1 404 Not Found');
  603. header("status: 404 Not Found");
  604. self::_error_page("404 Not Found");
  605. exit;
  606. }
  607. /**
  608. * 返回405错误页面
  609. */
  610. public static function return405() {
  611. header('HTTP/1.1 405 Method not allowed');
  612. header("status: 405 Method not allowed");
  613. self::_error_page("405 Method not allowed");
  614. exit;
  615. }
  616. /**
  617. * 返回500错误页面
  618. */
  619. public static function return500() {
  620. header('HTTP/1.1 500 Internal Server Error');
  621. header("status: 500 Internal Server Error");
  622. self::_error_page("500 Internal Server Error");
  623. exit;
  624. }
  625. private static function _error_page($msg) {
  626. $html = "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">
  627. <html>
  628. <head><title>".$msg."</title></head>
  629. <body bgcolor=\"white\">
  630. <h1>".$msg."</h1>
  631. <p>The requested URL was ".$msg." on this server. Sorry for the inconvenience.<br/>
  632. Please report this message and include the following information to us.<br/>
  633. Thank you very much!</p>
  634. <table>
  635. <tr>
  636. <td>Date:</td>
  637. <td>".date("Y-m-d H:i:s")."</td>
  638. </tr>
  639. </table>
  640. <hr/>Powered by InitPHP/3.8</body>
  641. </html>";
  642. echo $html;
  643. }
  644. }
  645. /**
  646. * 控制器Controller基类
  647. * 1. 每个控制器都需要继承这个基类
  648. * 2. 通过继承这个基类,就可以直接调用框架中的方法
  649. * 3. 控制器中可以直接调用$this->contorller 和 $this->vie
  650. * @author zhuli
  651. */
  652. class Controller extends coreInit {
  653. /**
  654. * @var controllerInit
  655. */
  656. protected $controller;
  657. /**
  658. * @var viewInit
  659. */
  660. protected $view;
  661. /**
  662. * 初始化
  663. */
  664. public function __construct() {
  665. parent::__construct();
  666. $InitPHP_conf = InitPHP::getConfig();
  667. $this->controller = $this->load('controller', 'c'); //导入Controller
  668. $this->view = $this->load('view', 'v'); //导入View
  669. $this->view->set_template_config($InitPHP_conf['template']); //设置模板
  670. $this->view->assign('init_token', $this->controller->get_token()); //全局输出init_token标记
  671. //注册全局变量,这样在Service和Dao中通过$this->common也能调用Controller中的类
  672. $this->register_global('common', $this->controller);
  673. InitPHP::import('dao/commonDao.php'); //数据层基类
  674. }
  675. }
  676. /**
  677. * 服务Service基类
  678. * 1. 每个Service都需要继承这个基类
  679. * 2. 通过继承这个基类,就可以直接调用框架中的方法
  680. * 3. Service中可以直接调用$this->service
  681. * @author zhuli
  682. */
  683. class Service extends coreInit {
  684. /**
  685. * @var serviceInit
  686. */
  687. protected $service;
  688. /**
  689. * 初始化
  690. */
  691. public function __construct() {
  692. parent::__construct();
  693. $this->service = $this->load('service', 's'); //导入Service
  694. }
  695. }
  696. /**
  697. * 数据层Dao基类
  698. * 1. 每个Dao都需要继承这个基类
  699. * 2. 通过继承这个基类,就可以直接调用框架中的方法
  700. * 3. Dao中可以直接调用$this->dao
  701. * 4. $this->dao->db DB方法库
  702. * 5. $this->dao->cache Cache方法库
  703. * @author zhuli
  704. */
  705. class Dao extends coreInit {
  706. /**
  707. * @var daoInit
  708. */
  709. protected $dao;
  710. /**
  711. * 初始化
  712. */
  713. public function __construct() {
  714. $this->dao = $this->load('dao', 'd'); //导入D
  715. $this->dao->run_db(); //初始化db
  716. $this->dao->run_cache(); //初始化cahce
  717. }
  718. /**
  719. * 分库初始化DB
  720. * 如果有多数据库链接的情况下,会调用该函数来自动切换DB link
  721. * @param string $db
  722. * @return dbInit
  723. */
  724. public function init_db($db = 'default') {
  725. $this->dao->db->init_db($db);
  726. return $this->dao->db;
  727. }
  728. }