-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.php
More file actions
1519 lines (1390 loc) · 43.8 KB
/
Copy pathindex.php
File metadata and controls
1519 lines (1390 loc) · 43.8 KB
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
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* thinklite
* @desc 极致简约的PHP开发框架
* @author play175
* @repo https://github.com/play175/thinklite
*/
define('CFG_DEBUG', 1); //是否打开调试模式
define('CFG_DATABASE', 'mysql://root:@127.0.0.1:3306/thinklite?prefix=yy_&charset=utf8'); //数据库链接,prefix是表名前缀
define('CFG_DEBUG_SQL', 1); //是否打开SQL调试选项
define('CFG_URL_MODE', 2); //URL模式,0:普通 1:pathinfo+get 2:pathinfo
define('CFG_APP_DIR', __DIR__ . '/app');
define('CFG_RUNTIME_DIR', __DIR__ . '/runtime');
define('CFG_AUTOLOAD_DIR', __DIR__);
/*******************************/
// ini_set( 'short_open_tag', '1' );
define('IS_AJAX', (!empty($_SERVER['HTTP_ACCEPT']) && strpos($_SERVER['HTTP_ACCEPT'], '/json') !== false));
/**
* 模拟三元操作符,用法如:$ret = iif($a,$b) //类似js的 let ret = a ? a : b 或者 let ret = a || b
*/
function iif(&$a, &$b)
{
if (empty($a)) {
return $b;
}
return $a;
}
/**
* 获取单个/多个输入参数
* @param $name 单个参数名称或者多个参数名称组成的数组
* @param $default 对应参数的默认值或者多个默认值组成的数组
* @param $maxLength 最大长度,仅针对单个字符串
*
* 示例:
* $v = $('id') //等价于:$_REQUEST['id']
* $v = $('get.id') //等价于:$_GET['id']
* $v = $('post.id')//等价于:$_POST['id']
* $v = $('cookie.name') //获取cookie值
* $v = $('id/d') //会把参数id格式化为数字类型,且如果传参不满足,会返回错误提示
* $v = $('ratio/float') //会把参数ratio格式化为数字类型,且如果传参不满足,会返回错误提示
* $v = $('name/4+') //参数name长度不能少于4个字符,否则会返回错误提示
* $v = $('len/d/1+') //数字类型参数len不能小于1,否则会返回错误提示
* $v = $('name/4') //参数name长度必须为4个字符,否则会返回错误提示
* $v = $('name/2+/姓名') //参数name长度不能少于2个字符,否则会返回错误提示,错误提示可能是:“姓名不能少于2个字符”
*/
function I($name, $default = null, $maxLength = 0)
{
if (is_array($name)) {
$values = [];
$errors = [];
foreach ($name as $k => &$v) {
if (is_array($v)) { //可传多个参数
list($key, $value, $error) = call_user_func_array('II', $v);
if ($error) {
$errors[] = $error;
}
$values[$key] = $value;
} else {
list($key, $value, $error) = II($v);
if ($error) {
$errors[] = $error;
}
$values[$key] = $value;
}
}
if (!empty($errors)) {
err($errors);exit;
}
return $values;
} else {
list($key, $value, $error) = II($name, $default, $maxLength);
if ($error) {
err($error);exit;
}
return $value;
}
}
/**
* 获取单个输入参数,被函数I调用,也可以单独使用
*/
function II($name, $default = null, $maxLength = 0)
{
preg_match("/(?:(get|post|request|cookie)\.)?([a-zA-Z0-9_-]+)(?:\/(double|float|int|string|date|datetime|d))?(?:\/([0-9\.-]+\+?))?(?:\/(.+))?/i", $name, $matches);
if (!empty($matches)) {
$from = strtolower(empty($matches[1]) ? 'request' : $matches[1]);
$key = isset($matches[2]) ? $matches[2] : null;
$type = empty($matches[3]) ? 'string' : strtolower($matches[3]);
$validate = isset($matches[4]) ? $matches[4] : null;
$alias = isset($matches[5]) ? $matches[5] : $key;
if (empty($key)) {
return [$key, $default, null];
}
$value = $default;
switch ($from) {
case 'get':
isset($_GET[$key]) && $value = $_GET[$key];
break;
case 'post':
isset($_POST[$key]) && $value = $_POST[$key];
break;
case 'cookie':
isset($_COOKIE[$key]) && $value = $_COOKIE[$key];
break;
default:
isset($_REQUEST[$key]) && $value = $_REQUEST[$key];
break;
}
$min = -1;
$max = PHP_INT_MAX;
if (!empty($validate)) {
//整数或者小数:2,0.3
preg_match("/^((?:[1-9]\d*|0)(?:\.\d{1,2})?)(\+)?$/i", $validate, $m2);
if (!empty($m2)) {
$min = $m2[1] + 0;
if (empty($m2[2])) {
$max = $min;
}
}
//两个整数或者小数:2-10,0.3-0.4,-0.2-0
preg_match("/^((?:[1-9]\d*|0)(?:\.\d{1,2})?)-((?:[1-9]\d*|0)(?:\.\d{1,2})?)$/i", $validate, $m2);
if (!empty($m2)) {
$min = $m2[1] + 0;
$max = $m2[2] + 0;
}
}
switch ($type) {
case 'double':
case 'float':
case 'd':
case 'int':
$value = is_numeric($value) ? $value + 0 : 0;
if ($type == 'int') {
$value = intval($value);
}
if (!empty($validate)) {
if ($min == $max && $value != $min) {
return [$key, $value, $alias . '必须等于' . $min];
}
if ($value < $min) {
return [$key, $value, $alias . '不能小于' . $min];
}
if ($value > $max) {
return [$key, $value, $alias . '不能大于' . $max];
}
}
break;
case 'date':
$time = strtotime($value);
if ($time === false) {
return [$key, null, null];
}
return [$key, date('Y-m-d', $time), null];
break;
case 'datetime':
$time = strtotime($value);
if ($time === false) {
return [$key, null, null];
}
return [$key, date('Y-m-d H:i:s', $time), null];
break;
default:
if (empty($validate) && $type != 'string') {
preg_match("/^((?:\-?[1-9]\d*|0)(?:\.\d{1,2})?)(\+)?$/i", $type, $m2);
if (!empty($m2)) {
$validate = $type;
$type = 'string';
$min = $m2[1] + 0;
if (empty($m2[2])) {
$max = $min;
}
}
preg_match("/^((?:\-?[1-9]\d*|0)(?:\.\d{1,2})?)-((?:\-?[1-9]\d*|0)(?:\.\d{1,2})?)$/i", $type, $m2);
if (!empty($m2)) {
$validate = $type;
$type = 'string';
$min = $m2[1] + 0;
$max = $m2[2] + 0;
}
}
// 将字符串分解为单元,解决中文字符长度问题
preg_match_all('/./us', $value, $mlen);
// 返回单元个数
$len = count($mlen[0]);
if (!empty($validate)) {
if ($min != -1 && $min == $max && $len != $min) {
return [$key, $value, $len == 0 ? '请填写' . $alias : ($alias . '必须' . $min . '个字符')];
}
if ($min != -1 && $len < $min) {
return [$key, $value, $len == 0 ? '请填写' . $alias : ($alias . '不能少于' . $min . '个字符')];
}
if ($max != -1 && $len > $max) {
return [$key, $value, $alias . '最多' . $max . '个字符'];
}
}
if ($maxLength > 0 && !empty($value) && $len > $maxLength) {
$value = mbsubstr($value, 0, $maxLength);
}
break;
}
return [$key, $value, null];
}
return [$key, $default, null];
}
/**
* 分割utf8字符串
*/
function mbsubstr($str, $start, $len)
{
$strlen = $start + $len;
for ($i = 0; $i < $strlen; $i++) {
if (ord(substr($str, $i, 1)) > 0xa0) {
$tmpstr .= substr($str, $i, 2);
$i++;
} else {
$tmpstr .= substr($str, $i, 1);
}
}
return $tmpstr;
}
/**
* 路由链接生成函数
* @param $uri 路由路径,如需要生成前往news控制器下的detail的action的URL,则:news/detail
* @param $params 参数数组
* @param $mode URL模式,0:普通 1:pathinfo+get 2:pathinfo,如果不传此参数,则读取全局配置CFG_URL_MODE
* @return 格式化后的URL
* 示例:U('news/detail',['id'=>1])
* 当 $mode = 0 时,则生成:/?c=news&a=detail&id=1
* 当 $mode = 1 时,则生成:/news/detail.html?id=1
* 当 $mode = 2 时,则生成:/news/detail/id/1.html
*/
function U($uri, $params = [], $mode = null)
{
if ($mode === null) {
$mode = CFG_URL_MODE;
}
$module = MODULE;
$controller = CONTROLLER;
$action = ACTION;
if (is_string($params)) {
$tmp = [];
parse_str($params, $tmp);
$params = $tmp;
}
if (!(empty($uri) || $uri == '.' || $uri == './' || $uri == '?')) {
list($module, $controller, $action, $_get) = parseUri($uri);
$params = array_merge($_get, $params);
} else {
$params = array_merge($_GET, $params);
}
if ($mode == 2) { //例:/news/index/page/3.html
$get_params = [];
$url = '/' . strtolower($controller) . '/';
if ($module != 'home') {
$url = '/' . $module . $url;
}
if (empty($params)) {
if ($action != 'index') {
$url .= $action . '.html';
}
} else {
$url .= $action . '/';
$n = 0;
foreach ($params as $k => &$v) {
if ($n > 0) {
$url .= '/';
}
if (strpos($v, '/') !== false) {
$get_params[$k] = $v;
continue;
}
$url .= $k . '/' . $v;
$n++;
}
$url = $url . '.html';
}
return $url . (!empty($get_params) ? '?' . http_build_query($get_params) : '');
}
if ($mode == 1) { //例:/news/index.html?page=3
$url = '/' . strtolower($controller) . '/';
if ($module != 'home') {
$url = '/' . $module . $url;
}
if ($action != 'index') {
$url .= $action . '.html';
}
return $url . (!empty($params) ? '?' . http_build_query($params) : '');
}
//例:/?m=home&c=news&a=index&page=3
$get['m'] = $module;
$get['c'] = strtolower($controller);
$get['a'] = $action;
$params = array_merge($get, $params);
return '/?' . http_build_query($params);
}
/**
* 路由链接解析函数,一般不需要关注,仅thinklite内部使用
*/
function parseUri($uri, $flat = false)
{
$pathsLen = 0;
if (!empty($uri)) {
if ($uri[0] == '/') {
$uri = substr($uri, 1);
}
$paths = explode("/", $uri);
$pathsLen = count($paths);
}
$module_name = 'home';
$controller_name = 'index';
$action_name = 'index';
$get = [];
if ($pathsLen >= 3) {
$module_name = $paths[0];
$controller_name = $paths[1];
$action_name = basename($paths[2], '.html');
$getOffset = 3;
if (!file_exists(CFG_APP_DIR . '/' . $module_name)) {
$module_name = 'home';
$controller_name = $paths[0];
$action_name = basename($paths[1], '.html');
$getOffset = 2;
}
$name = null;
for ($i = $getOffset; $i < $pathsLen; ++$i) {
if ($pathsLen - 1 == $i) {
$v = basename($paths[$i], '.html');
} else {
$v = $paths[$i];
}
if (!empty($name)) {
$get[$name] = $v;
if ($flat) {
$_REQUEST[$name] = $_GET[$name] = $v;
}
$name = null;
} else {
$name = $v;
}
}
if (!empty($name)) {
$get['__SLUG__'] = $name;
if ($flat) {
$_REQUEST['__SLUG__'] = $_GET['__SLUG__'] = $v;
}
}
} else if ($pathsLen == 2) {
$module_name = 'home';
$controller_name = $paths[0];
$action_name = basename($paths[1], '.html');
} else if ($pathsLen == 1) {
$action_name = basename($paths[0], '.html');
} else if ($flat) {
if (!empty($_GET['m'])) {
$module_name = $_GET['m'];
}
if (!empty($_GET['c'])) {
$controller_name = $_GET['c'];
}
if (!empty($_GET['a'])) {
$action_name = $_GET['a'];
}
}
if (CFG_URL_MODE == 0 && $flat) {
if (!empty($_GET['m'])) {
$module_name = $_GET['m'];
}
if (!empty($_GET['c'])) {
$controller_name = $_GET['c'];
}
if (!empty($_GET['a'])) {
$action_name = $_GET['a'];
}
}
if (empty($action_name)) {
$action_name = 'index';
}
$module_name = strtolower($module_name);
$controller_name = strtolower($controller_name);
$action_name = strtolower($action_name);
if ($flat) {
define('MODULE', $module_name);
define('CONTROLLER', ucfirst($controller_name));
define('ACTION', $action_name);
}
return [
$module_name,
$controller_name,
$action_name,
$get,
];
}
/**
* cookie读写函数
* @param $key cookie名称
* @param $value 要设置的值,传null时,则cookie会被删除
* @param $expire
* @param $path
* @param $domain
*/
function cookie($key, $value = '', $expire = null, $path = '/', $domain = null)
{
if ('' === $value) {
return isset($_COOKIE[$key]) ? $_COOKIE[$key] : null;
}
setcookie($key, $value, $expire, $path, $domain);
}
/**
* 抛出致命异常,致命异常只有CFG_DEBUG定义为1时才会抛出异常详情
*/
function fatal($msg, $code = -1)
{
if (defined('CFG_DEBUG') && CFG_DEBUG) {
err($msg, $code);
} else {
err('请求出错,请重试或返回', $code);
}
exit;
}
/**
* 抛出普通异常
*/
function err($msg, $code = -1)
{
global $self;
if (!empty($self)) {
$self->_err($msg, $code);
exit;
} else {
if (IS_AJAX) {
$output = array('status' => $code, 'msg' => $msg);
header("Content-type: text/json; charset=utf-8");
exit(json_encode($output, JSON_UNESCAPED_UNICODE));
} else {
header("Content-type: text/html; charset=utf-8");
exit('<pre>错误码:' . $code . '<br />错误信息:' . $msg . '</pre><a href="javascript:history.length>1?history.go(-1):window.close();">返回上一页</a><br /><a href="/">返回首页</a>');
}
}
}
/**
* 获取当前控制器的视图文件路径
*/
function getViewFile($view)
{
return CFG_APP_DIR . '/' . MODULE . '/' . VIEW . '/' . $view . '.php';
}
/**
* 导入其他模板
*/
function import($_view, $_view_params = null)
{
global $self;
extract($self->data);
!empty($_view_params) && extract($_view_params);
include getViewFile($_view);
}
/**
* 自定义异常捕获
*/
function customError($errno, $errstr, $errfile, $errline)
{
$errno = $errno & error_reporting();
if ($errno == 0) {
return;
}
if (!defined('E_STRICT')) {
define('E_STRICT', 2048);
}
if (!defined('E_RECOVERABLE_ERROR')) {
define('E_RECOVERABLE_ERROR', 4096);
}
$err = '';
switch ($errno) {
case E_ERROR:
$err .= "Error";
break;
case E_WARNING:
$err .= "Warning";
break;
case E_PARSE:
$err .= "Parse Error";
break;
case E_NOTICE:
$err .= "Notice";
break;
case E_CORE_ERROR:
$err .= "Core Error";
break;
case E_CORE_WARNING:
$err .= "Core Warning";
break;
case E_COMPILE_ERROR:
$err .= "Compile Error";
break;
case E_COMPILE_WARNING:
$err .= "Compile Warning";
break;
case E_USER_ERROR:
$err .= "User Error";
break;
case E_USER_WARNING:
$err .= "User Warning";
break;
case E_USER_NOTICE:
$err .= "User Notice";
break;
case E_STRICT:
$err .= "Strict Notice";
break;
case E_RECOVERABLE_ERROR:$err .= "Recoverable Error";
break;
default:$err .= "Unknown error ($errno)";
break;
}
$err .= ": $errstr in $errfile on line $errline" . PHP_EOL;
if (function_exists('debug_backtrace')) {
$backtrace = debug_backtrace();
array_shift($backtrace);
foreach ($backtrace as $i => $l) {
$err .= "[$i] in function " . (isset($l['class']) ? $l['class'] : '') . "" . (isset($l['type']) ? $l['type'] : '') . "{$l['function']}";
if (isset($l['file']) && $l['file']) {
$err .= " in {$l['file']}";
}
if (isset($l['line']) && $l['line']) {
$err .= " on line {$l['line']}";
}
$err .= PHP_EOL;
}
}
file_put_contents(CFG_RUNTIME_DIR . '/error.log', PHP_EOL . date('m-d H:i:s') . PHP_EOL . $err, FILE_APPEND);
// global $__view_rendering;
// if($__view_rendering){
// return;
// }
if (defined('CFG_DEBUG') && CFG_DEBUG) {
err($err);
}
}
set_error_handler("customError");
/**
* 自动加载class
*/
function __autoload($classname)
{
$filename = CFG_AUTOLOAD_DIR . '/' . str_replace('\\', '/', strtolower($classname)) . ".php";
include_once $filename;
}
/**
* 控制器基类
*/
abstract class Controller
{
public $data = [];
public $output = [
"status" => 1,
];
public $body_sent = false;
public $db;
public function __construct()
{
$this->db = new DB();
}
public function _initialize()
{
}
protected function assign($name, $value = '')
{
$this->data[$name] = $value;
}
public function _err($msg = '', $code = -1)
{
return $this->err($msg, $code);
}
protected function err($msg = '', $code = -1)
{
$this->output['msg'] = $msg;
$this->output['status'] = $code;
$this->output();
}
protected function ok($msg = '')
{
$this->output['msg'] = $msg;
$this->output['status'] = 1;
$this->output();
}
protected function ajaxReturn($output)
{
if (empty($output['msg']) && !empty($this->output['msg'])) {
$output['msg'] = $this->output['msg'];
}
header("Content-type: text/json; charset=utf-8");
exit(json_encode($output, JSON_UNESCAPED_UNICODE));
}
public function _output()
{
return $this->output();
}
protected function output($_view_file = null)
{
if (IS_AJAX) {
$this->outputJson();
} else {
$this->outputHtml($_view_file);
}
}
protected function outputJson()
{
$this->body_sent = true;
$this->output['result'] = empty($this->data) ? new StdClass() : $this->data;
$this->ajaxReturn($this->output);
}
protected function outputHtml($_view_file = null)
{
global $__view_rendering;
$this->body_sent = true;
if ($this->output['status'] != 1) {
if (file_exists(getViewFile('public/error'))) {
extract($this->output);
$__view_rendering = 1;
include getViewFile('public/error');
$__view_rendering = 0;
return;
}
exit($this->output['msg'] . "<br /><a href=\"javascript:history.length>1?history.go(-1):window.close();\">返回上一页</a>");
}
extract($this->data);
if ($_view_file == null) {
$_view_file = strtolower(CONTROLLER) . '/' . ACTION;
}
if (!file_exists(getViewFile($_view_file))) {
if (!empty($this->output['msg'])) {
if (file_exists(getViewFile('public/success'))) {
extract($this->output);
$__view_rendering = 1;
include getViewFile('public/success');
$__view_rendering = 0;
return;
}
}
fatal('对应的 view 不存在:' . getViewFile($_view_file), -410);
}
$__view_rendering = 1;
include getViewFile($_view_file);
$__view_rendering = 0;
}
}
/**
* 控制器衍生类,默认以json格式输出数据
*/
abstract class Api extends Controller
{
protected function output($_view_file = null)
{
$this->outputJson();
}
}
/**
* 控制器衍生类,默认以模板文件渲染数据
*/
abstract class Page extends Controller
{
protected function output($_view_file = null)
{
$this->outputHtml($_view_file);
}
}
/**
* 分页器
* @author Jason Grimes
* @source https://github.com/jasongrimes/php-paginator
*/
class Pager
{
const NUM_PLACEHOLDER = '__PAGE__';
protected $totalItems;
protected $numPages;
protected $itemsPerPage;
protected $currentPage;
protected $urlPattern;
protected $maxPagesToShow = 5;
protected $previousText = '上一页';
protected $nextText = '下一页';
/**
* @param int $totalItems The total number of items.
* @param int $itemsPerPage The number of items per page.
* @param int $currentPage The current page number.
* @param string $urlPattern A URL for each page, with (:num) as a placeholder for the page number. Ex. '/foo/page/(:num)'
*/
public function __construct($totalItems, $itemsPerPage, $currentPage, $urlPattern = '')
{
$this->totalItems = $totalItems;
$this->itemsPerPage = $itemsPerPage;
$this->currentPage = $currentPage;
$this->urlPattern = $urlPattern;
$this->updateNumPages();
}
protected function updateNumPages()
{
$this->numPages = ($this->itemsPerPage == 0 ? 0 : (int) ceil($this->totalItems / $this->itemsPerPage));
}
/**
* @param int $maxPagesToShow
* @throws \InvalidArgumentException if $maxPagesToShow is less than 3.
*/
public function setMaxPagesToShow($maxPagesToShow)
{
if ($maxPagesToShow < 3) {
throw new \InvalidArgumentException('maxPagesToShow cannot be less than 3.');
}
$this->maxPagesToShow = $maxPagesToShow;
}
/**
* @return int
*/
public function getMaxPagesToShow()
{
return $this->maxPagesToShow;
}
/**
* @param int $currentPage
*/
public function setCurrentPage($currentPage)
{
$this->currentPage = $currentPage;
}
/**
* @return int
*/
public function getCurrentPage()
{
return $this->currentPage;
}
/**
* @param int $itemsPerPage
*/
public function setItemsPerPage($itemsPerPage)
{
$this->itemsPerPage = $itemsPerPage;
$this->updateNumPages();
}
/**
* @return int
*/
public function getItemsPerPage()
{
return $this->itemsPerPage;
}
/**
* @param int $totalItems
*/
public function setTotalItems($totalItems)
{
$this->totalItems = $totalItems;
$this->updateNumPages();
}
/**
* @return int
*/
public function getTotalItems()
{
return $this->totalItems;
}
/**
* @return int
*/
public function getNumPages()
{
return $this->numPages;
}
/**
* @param string $urlPattern
*/
public function setUrlPattern($urlPattern)
{
$this->urlPattern = $urlPattern;
}
/**
* @return string
*/
public function getUrlPattern()
{
return $this->urlPattern;
}
/**
* @param int $pageNum
* @return string
*/
public function getPageUrl($pageNum)
{
return str_replace(self::NUM_PLACEHOLDER, $pageNum, $this->urlPattern);
}
public function getNextPage()
{
if ($this->currentPage < $this->numPages) {
return $this->currentPage + 1;
}
return null;
}
public function getPrevPage()
{
if ($this->currentPage > 1) {
return $this->currentPage - 1;
}
return null;
}
public function getNextUrl()
{
if (!$this->getNextPage()) {
return null;
}
return $this->getPageUrl($this->getNextPage());
}
/**
* @return string|null
*/
public function getPrevUrl()
{
if (!$this->getPrevPage()) {
return null;
}
return $this->getPageUrl($this->getPrevPage());
}
/**
* Get an array of paginated page data.
*
* Example:
* array(
* array ('num' => 1, 'url' => '/example/page/1', 'isCurrent' => false),
* array ('num' => '...', 'url' => NULL, 'isCurrent' => false),
* array ('num' => 3, 'url' => '/example/page/3', 'isCurrent' => false),
* array ('num' => 4, 'url' => '/example/page/4', 'isCurrent' => true ),
* array ('num' => 5, 'url' => '/example/page/5', 'isCurrent' => false),
* array ('num' => '...', 'url' => NULL, 'isCurrent' => false),
* array ('num' => 10, 'url' => '/example/page/10', 'isCurrent' => false),
* )
*
* @return array
*/
public function getPages()
{
$pages = array();
if ($this->numPages <= 1) {
return array();
}
if ($this->numPages <= $this->maxPagesToShow) {
for ($i = 1; $i <= $this->numPages; $i++) {
$pages[] = $this->createPage($i, $i == $this->currentPage);
}
} else {
// Determine the sliding range, centered around the current page.
$numAdjacents = (int) floor(($this->maxPagesToShow - 3) / 2);
if ($this->currentPage + $numAdjacents > $this->numPages) {
$slidingStart = $this->numPages - $this->maxPagesToShow + 2;
} else {
$slidingStart = $this->currentPage - $numAdjacents;
}
if ($slidingStart < 2) {
$slidingStart = 2;
}
$slidingEnd = $slidingStart + $this->maxPagesToShow - 3;
if ($slidingEnd >= $this->numPages) {
$slidingEnd = $this->numPages - 1;
}
// Build the list of pages.
$pages[] = $this->createPage(1, $this->currentPage == 1);
if ($slidingStart > 2) {
$pages[] = $this->createPageEllipsis();
}
for ($i = $slidingStart; $i <= $slidingEnd; $i++) {
$pages[] = $this->createPage($i, $i == $this->currentPage);
}
if ($slidingEnd < $this->numPages - 1) {
$pages[] = $this->createPageEllipsis();
}
$pages[] = $this->createPage($this->numPages, $this->currentPage == $this->numPages);
}
return $pages;
}
/**
* Create a page data structure.
*
* @param int $pageNum
* @param bool $isCurrent
* @return Array
*/
protected function createPage($pageNum, $isCurrent = false)
{
return array(
'num' => $pageNum,
'url' => $this->getPageUrl($pageNum),
'isCurrent' => $isCurrent,
);
}
/**
* @return array
*/
protected function createPageEllipsis()
{
return array(
'num' => '...',
'url' => null,
'isCurrent' => false,
);
}
/**
* Render an HTML pagination control.
*
* @return string
*/
public function toHtml()
{
if ($this->numPages <= 1) {
return '';
}
$html = '<ul class="pager">';
if ($this->getPrevUrl()) {
$html .= '<li><a href="' . $this->getPrevUrl() . '">« ' . $this->previousText . '</a></li>';
}
foreach ($this->getPages() as $page) {
if ($page['url']) {
$html .= '<li' . ($page['isCurrent'] ? ' class="active"' : '') . '><a href="' . $page['url'] . '">' . $page['num'] . '</a></li>';
} else {
$html .= '<li class="disabled"><span>' . $page['num'] . '</span></li>';
}
}
if ($this->getNextUrl()) {
$html .= '<li><a href="' . $this->getNextUrl() . '">' . $this->nextText . ' »</a></li>';
}