-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtinyPHP.class.php
565 lines (499 loc) · 13.4 KB
/
tinyPHP.class.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
<?php
/**
* tinyPHP.class.php
*
* 框架核心文件
*
*/
function DB() {
static $db;
if(!is_object($db)) {
global $_config;
if (!isset($_config['db'])) {
system_error('无效的数据库配置');
}
$db = new db_driver_mysql($_config['db']);
}
return $db;
}
/**
* xss攻击检测
*/
function _xss_check() {
static $check = array('"', '>', '<', '\'', '(', ')', 'CONTENT-TRANSFER-ENCODING');
if($_SERVER['REQUEST_METHOD'] == 'GET' ) {
$temp = $_SERVER['REQUEST_URI'];
} else {
$temp = $_SERVER['REQUEST_URI'].file_get_contents('php://input');
}
$temp = strtoupper(urldecode(urldecode($temp)));
foreach ($check as $str) {
if(strpos($temp, $str) !== false) {
system_error('request_tainting');
}
}
return true;
}
class tinyPHP {
/**
* 应用实例
* @var SinglePHP
*/
private static $_app;
/**
* 框架核心参数
* @var array
*/
var $var = array();
/**
* 创建应用实例
* @return SinglePHP
*/
public static function creatapp() {
if(!is_object(self::$_app)) {
self::$_app = new self();
}
return self::$_app;
}
/**
* 打印错误信息
*/
public static function handleError($errno, $errstr, $errfile, $errline) {
if($errno) {
system_error($errstr.' ['.$errfile.' on '.$errline.']');
}
}
/**
* 构造函数
*/
public function __construct() {
$this->_init_env();
$this->_init_uri();
}
/**
* 初始化框架运行环境
*/
private function _init_env() {
global $_config;
if(empty($_config['debug'])) {
error_reporting(E_ALL);
} elseif($_config['debug'] === 1 || $_config['debug'] === 2) {
error_reporting(E_ERROR);
if($_config['debug'] === 2) {
error_reporting(E_ALL);
}
} else {
error_reporting(0);
}
if (function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()) {
$_GET = tiny_stripslashes($_GET);
$_POST = tiny_stripslashes($_POST);
$_COOKIE = tiny_stripslashes($_COOKIE);
}
$allowgzip = is_allowgzip();
if(!ob_start($allowgzip ? 'ob_gzhandler' : null)) {
ob_start();
}
header('Content-Type: text/html; charset=utf-8');
$this->var = & $_config;
}
/**
* uri路由初始化
*/
private function _init_uri() {
$this->var['uri_model'] = empty($this->var['uri_model']) ? 1 : $this->var['uri_model'];
$this->var['controller_identifier'] = empty($this->var['controller_identifier']) ? "c" : $this->var['controller_identifier'];
$this->var['action_identifier'] = empty($this->var['action_identifier']) ? "m" : $this->var['action_identifier'];
$this->var['controller_default'] = empty($this->var['controller_default']) ? "index" : $this->var['controller_default'];
$this->var['action_default'] = empty($this->var['action_default']) ? "index" : $this->var['action_default'];
if ($this->var['uri_model'] == 1) {
$this->var['controller'] = empty($_GET[$this->var['controller_identifier']]) ? $this->var['controller_default'] : $_GET[$this->var['controller_identifier']];
$this->var['action'] = empty($_GET[$this->var['action_identifier']]) ? $this->var['action_default'] : $_GET[$this->var['action_identifier']];
} elseif ($this->var['uri_model'] == 2) {
$php_file = trim($_SERVER['SCRIPT_NAME'], "/");
$request_uri = explode("/", trim(str_replace("?".trim($_SERVER['QUERY_STRING']), "", trim($_SERVER['REQUEST_URI'])), "/"));
if ($request_uri[0] == $php_file || empty($request_uri[0])) {
array_shift($request_uri);
}
if (empty($request_uri)) {
$this->var['controller'] = $this->var['controller_default'];
$this->var['action'] = $this->var['action_default'];
} else {
$this->var['controller'] = $request_uri[0];
$this->var['action'] = empty($request_uri[1]) ? $this->var['action_default'] : $request_uri[1];
}
} else {
system_error("Oops! Invalid uri_model!");
}
}
/**
* 运行实例
*/
public function run() {
set_error_handler(array('tinyPHP', 'handleError'));
$controller_file = dirname(__FILE__).$this->var['app_path'].'/controller/'.$this->var['controller'].'.php';
if (file_exists($controller_file)) {
include $controller_file;
$_class = $this->var['controller'].'_controller';
$_obj = new $_class();
if (method_exists($_obj, $_action = $this->var['action'])) {
$_obj->$_action();
} else {
system_error("Call to undefined method ".$_class."::".$this->var['action']."()");
}
} else {
system_error("Lost file [".$controller_file."]");
}
}
}
class db_driver_mysql
{
var $curlink;
var $config = array();
var $_lastsql;
/**
* 构造函数
* @param array $config 配置数组
*/
function __construct($config = array()) {
$this->config = $config;
if(empty($this->config)) {
$this->halt('config_db_not_found');
}
$this->curlink = $this->_dbconnect(
$this->config['host'],
$this->config['user'],
$this->config['password'],
$this->config['charset'],
$this->config['dbname']
);
}
/**
* 链接数据库
* @param string $dbhost 服务器
* @param string $dbuser 用户名
* @param string $dbpw 密码
* @param string $dbcharset 字符集
* @param string $dbname 数据库名
* @return db_link
*/
private function _dbconnect($dbhost, $dbuser, $dbpw, $dbcharset, $dbname, $halt = true) {
$link = @mysql_connect($dbhost, $dbuser, $dbpw, 1, MYSQL_CLIENT_COMPRESS);
if(!$link) {
$halt && $this->halt('数据库连接失败');
}
if (!@mysql_select_db($dbname, $link)) {
$halt && $this->halt('数据库选择失败');
}
@mysql_set_charset($dbcharset);
return $link;
}
/**
* 查询
* @param string $sql 要查询的sql
* @return bool|objeact 查询结果
*/
public function query($sql) {
$this->_lastsql = $sql;
if(!($query = mysql_query($sql, $this->curlink))) {
$this->halt('errno '.$this->errno().' : '.$this->error());
}
return $query;
}
/**
* 查询结果集
* @param string $sql 要查询的sql
* @return array 查询结果
*/
public function fetch_all($sql) {
$data = array();
$res = $this->query($sql);
while($row = $this->fetch_array($res)) {
$data[] = $row;
}
$this->free_result($res);
return $data;
}
/**
* 查询结果集, 单行
* @param string $sql 要查询的sql
* @return array 查询结果
*/
public function fetch_row($sql) {
$res = $this->query($sql);
$ret = $this->fetch_array($res);
$this->free_result($res);
return $ret ? $ret : array();
}
/**
* 查询结果集, 字段
* @param string $sql 要查询的sql
* @return string 查询结果
*/
public function fetch_field($sql) {
$res = $this->query($sql);
$ret = mysql_result($res, 0);
$this->free_result($res);
return $ret;
}
/**
* 插入
* @param string $table 表名
* @param array $data 插入数据(字段名=>字段值)
* @param bool $return_id 是否返回插入ID
* @return bool|string 查询结果
*/
public function insert($table, $data = array(), $return_id = false) {
$sql = $this->implode($data);
$res = $this->query("INSERT INTO $table SET $sql");
if($res && $return_id) return mysql_insert_id($this->curlink);
else return $res;
}
/**
* 更新
* @param string $table 表名
* @param array $data 待更新数据(字段名=>字段值)
* @param string|array $condition 条件
* @return bool 查询结果
*/
public function update($table, $data = array(), $condition) {
$sql = $this->implode($data);
$where = '';
if (empty($condition)) {
$where = '1';
} elseif (is_array($condition)) {
$where = $this->implode($condition, ' AND ');
} else {
$where = $condition;
}
return $this->query("UPDATE $table SET $sql WHERE $where");
}
/**
* 删除
* @param string $table 表名
* @param string|array $condition 条件
* @return bool 查询结果
*/
public function delete($table, $condition) {
if (empty($condition)) {
$this->halt("危险操作:没有设置删除条件");
return false;
} elseif (is_array($condition)) {
$where = $this->implode($condition, ' AND ');
} else {
$where = $condition;
}
return $this->query("DELETE FROM $table WHERE $where ");
}
/**
* 获取结果集
* @param $query 数据指针
* @param string $result_type 结果集类型
* @return array 结果
*/
private function fetch_array($query, $result_type = MYSQL_ASSOC) {
return mysql_fetch_array($query, $result_type);
}
/**
* 释放结果内存
* @param $query 数据指针
* @return bool
*/
private function free_result($query) {
return mysql_free_result($query);
}
/**
* 组装sql
* @param array $array 数组
* @return string
*/
private function implode($array = array(), $glue = ',') {
$sql = $comma = '';
$glue = ' ' . trim($glue) . ' ';
foreach ($array as $k => $v) {
$sql .= $comma . '`'.$k.'`' . '=' . '\'' . addcslashes($v, "\n\r\\'\"\032") . '\'';
$comma = $glue;
}
return $sql;
}
/**
* 获取错误
* @return string 错误信息
*/
private function error() {
return (($this->curlink) ? mysql_error($this->curlink) : mysql_error());
}
/**
* 获取错误码
* @return int 错误码
*/
private function errno() {
return intval(($this->curlink) ? mysql_errno($this->curlink) : mysql_errno());
}
/**
* 打印错误信息
* @param string 错误信息
*/
private function halt($message) {
system_error($message);
}
}
class tiny_controller {
function view($data, $tpl = "") {
global $_config;
$tpl = $tpl ? (file_exists($tpl) ? $tpl : dirname(__FILE__).$_config['app_path'].'/view/'.$tpl.'.php') : dirname(__FILE__).$_config['app_path'].'/view/'.$_config['action'].'.php';
if (file_exists($tpl)) {
include $tpl;
} else {
system_error('Lost file ['.$tpl.']');
}
}
}
function system_error($message) {
ob_end_clean();
$gzip = is_allowgzip();
ob_start($gzip ? 'ob_gzhandler' : null);
$host = $_SERVER['HTTP_HOST'];
echo <<<EOT
<!DOCTYPE html>
<html>
<head>
<title>$host - System Error</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="ROBOTS" content="NOINDEX,NOFOLLOW,NOARCHIVE" />
<style type="text/css">
<!--
body {
background-color: #fff;
margin: 40px;
font: 13px/20px normal Helvetica, Arial, sans-serif;
color: #4F5155;
}
h1 {
color: #000;
font-weight: 800;
font-size: 36px;
line-height: 40px;
}
code {
font-family: Consolas, Monaco, Courier New, Courier, monospace;
font-size: 14px;
color: #333;
display: block;
}
#body {
margin: 10% 15px;
}
p.footer {
font-size: 11px;
border-top: 1px solid #D0D0D0;
line-height: 32px;
}
-->
</style>
</head>
<body>
<div id="body">
<h1>$message</h1>
EOT;
if($phpmsg = debug_backtrace()) {
if(is_array($phpmsg)) {
foreach($phpmsg as $k => $msg) {
$k++;
echo '<code>'.$k.'. ';
if ($msg['file']) {
echo '[Line: '.$msg['line'].']'.$msg['file'];
}
echo '('.$msg['function'].')</code>';
}
} else {
echo $phpmsg;
}
}
echo <<<EOT
<p class="footer">tinyPHP Version 0.0.1</p>
</body>
</html>
EOT;
exit();
}
function is_allowgzip() {
if(!empty($_SERVER['HTTP_ACCEPT_ENCODING']) && strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') === false) {
return false;
} else
return true;
}
function tiny_stripslashes($string) {
if(empty($string)) return $string;
if(is_array($string)) {
foreach($string as $key => $val) {
$string[$key] = tiny_stripslashes($val);
}
} else {
$string = stripslashes($string);
}
return $string;
}
function tiny_addslashes($string, $force = 1) {
if(is_array($string)) {
$keys = array_keys($string);
foreach($keys as $key) {
$val = $string[$key];
unset($string[$key]);
$string[addslashes($key)] = tiny_addslashes($val, $force);
}
} else {
$string = addslashes($string);
}
return $string;
}
function tiny_htmlspecialchars($string, $flags = null) {
if(is_array($string)) {
foreach($string as $key => $val) {
$string[$key] = tiny_htmlspecialchars($val, $flags);
}
} else {
if($flags === null) {
$string = str_replace(array('&', '"', '<', '>'), array('&', '"', '<', '>'), $string);
if(strpos($string, '&#') !== false) {
$string = preg_replace('/&((#(\d{3,5}|x[a-fA-F0-9]{4}));)/', '&\\1', $string);
}
} else {
if(PHP_VERSION < '5.4.0') {
$string = htmlspecialchars($string, $flags);
} else {
if(strtolower(CHARSET) == 'utf-8') {
$charset = 'UTF-8';
} else {
$charset = 'ISO-8859-1';
}
$string = htmlspecialchars($string, $flags, $charset);
}
}
}
return $string;
}
function dump($var, $echo=true,$label=null, $strict=true) {
$label = ($label===null) ? '' : rtrim($label) . ' ';
if(!$strict) {
if (ini_get('html_errors')) {
$output = print_r($var, true);
$output = "<pre>".$label.htmlspecialchars($output,ENT_QUOTES)."</pre>";
} else {
$output = $label . print_r($var, true);
}
}else {
ob_start();
var_dump($var);
$output = ob_get_clean();
if(!extension_loaded('xdebug')) {
$output = preg_replace("/\]\=\>\n(\s+)/m", "] => ", $output);
$output = '<pre>'. $label. htmlspecialchars($output, ENT_QUOTES). '</pre>';
}
}
if ($echo) {
echo($output);
return null;
}else
return $output;
}