服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - PHP教程 - PHP数据的提交与过滤基本操作实例详解

PHP数据的提交与过滤基本操作实例详解

2021-03-23 16:53codes PHP教程

这篇文章主要介绍了PHP数据的提交与过滤基本操作,简要说明了php数据过滤的基本方法并结合实例形式分析了php针对各种常见类型数据的过滤操作使用技巧,需要的朋友可以参考下

本文实例讲述了PHP数据的提交与过滤基本操作。分享给大家供大家参考,具体如下:

1、php提交数据过滤的基本原则

1)提交变量进数据库时,我们必须使用addslashes()进行过滤,像我们的注入问题,一个addslashes()也就搞定了。其实在涉及到变量取值时,intval()函数对字符串的过滤也是个不错的选择。

2)在php.ini中开启magic_quotes_gpc和magic_quotes_runtime。magic_quotes_gpc可以把get,post,cookie里的引号变为斜杠。
magic_quotes_runtime对于进出数据库的数据可以起到格式话的作用。其实,早在以前注入很疯狂时,这个参数就很流行了。

3)在使用系统函数时,必须使用escapeshellarg(),escapeshellcmd()参数去过滤,这样你也就可以放心的使用系统函数。

4)对于跨站,strip_tags(),htmlspecialchars()两个参数都不错,对于用户提交的的带有html和php的标记都将进行转换。比如尖括号"<"就将转化为 "<"这样无害的字符。

?
1
2
$new = htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES);
strip_tags($text,);

5)对于相关函数的过滤,就像先前的include(),unlink,fopen()等等,只要你把你所要执行操作的变量指定好或者对相关字符过滤严密,我想

这样也就无懈可击了。

2、PHP简单的数据过滤

1)入库:  trim($str),addslashes($str)

2)出库:  stripslashes($str)

3)显示:  htmlspecialchars(nl2br($str))

?
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
<?php
/**
 * global.func.php 公共函数库
 */
/**
 * 返回经addslashes处理过的字符串或数组
 * @param $string 需要处理的字符串或数组
 * @return mixed
 */
function new_addslashes($string){
 if(!is_array($string)) return addslashes($string);
 foreach($string as $key => $val) $string[$key] = new_addslashes($val);
 return $string;
}
/**
 * 返回经stripslashes处理过的字符串或数组
 * @param $string 需要处理的字符串或数组
 * @return mixed
 */
function new_stripslashes($string) {
 if(!is_array($string)) return stripslashes($string);
 foreach($string as $key => $val) $string[$key] = new_stripslashes($val);
 return $string;
}
/**
 * 返回经htmlspecialchars处理过的字符串或数组
 * @param $obj 需要处理的字符串或数组
 * @return mixed
 */
function new_html_special_chars($string) {
 $encoding = 'utf-8';
 if(strtolower(CHARSET)=='gbk') $encoding = 'ISO-8859-15';
 if(!is_array($string)) return htmlspecialchars($string,ENT_QUOTES,$encoding);
 foreach($string as $key => $val) $string[$key] = new_html_special_chars($val);
 return $string;
}
function new_html_entity_decode($string) {
 $encoding = 'utf-8';
 if(strtolower(CHARSET)=='gbk') $encoding = 'ISO-8859-15';
 return html_entity_decode($string,ENT_QUOTES,$encoding);
}
function new_htmlentities($string) {
 $encoding = 'utf-8';
 if(strtolower(CHARSET)=='gbk') $encoding = 'ISO-8859-15';
 return htmlentities($string,ENT_QUOTES,$encoding);
}
/**
 * 安全过滤函数
 *
 * @param $string
 * @return string
 */
function safe_replace($string) {
 $string = str_replace('%20','',$string);
 $string = str_replace('%27','',$string);
 $string = str_replace('%2527','',$string);
 $string = str_replace('*','',$string);
 $string = str_replace('"','&quot;',$string);
 $string = str_replace("'",'',$string);
 $string = str_replace('"','',$string);
 $string = str_replace(';','',$string);
 $string = str_replace('<','&lt;',$string);
 $string = str_replace('>','&gt;',$string);
 $string = str_replace("{",'',$string);
 $string = str_replace('}','',$string);
 $string = str_replace('\\','',$string);
 return $string;
}
/**
 * xss过滤函数
 *
 * @param $string
 * @return string
 */
function remove_xss($string) {
 $string = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/S', '', $string);
 $parm1 = Array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');
 $parm2 = Array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
 $parm = array_merge($parm1, $parm2);
 for ($i = 0; $i < sizeof($parm); $i++) {
  $pattern = '/';
  for ($j = 0; $j < strlen($parm[$i]); $j++) {
   if ($j > 0) {
    $pattern .= '(';
    $pattern .= '(&#[x|X]0([9][a][b]);?)?';
    $pattern .= '|(&#0([9][10][13]);?)?';
    $pattern .= ')?';
   }
   $pattern .= $parm[$i][$j];
  }
  $pattern .= '/i';
  $string = preg_replace($pattern, ' ', $string);
 }
 return $string;
}
/**
 * 过滤ASCII码从0-28的控制字符
 * @return String
 */
function trim_unsafe_control_chars($str) {
 $rule = '/[' . chr ( 1 ) . '-' . chr ( 8 ) . chr ( 11 ) . '-' . chr ( 12 ) . chr ( 14 ) . '-' . chr ( 31 ) . ']*/';
 return str_replace ( chr ( 0 ), '', preg_replace ( $rule, '', $str ) );
}
/**
 * 格式化文本域内容
 *
 * @param $string 文本域内容
 * @return string
 */
function trim_textarea($string) {
 $string = nl2br ( str_replace ( ' ', '&nbsp;', $string ) );
 return $string;
}
/**
 * 将文本格式成适合js输出的字符串
 * @param string $string 需要处理的字符串
 * @param intval $isjs 是否执行字符串格式化,默认为执行
 * @return string 处理后的字符串
 */
function format_js($string, $isjs = 1) {
 $string = addslashes(str_replace(array("\r", "\n", "\t"), array('', '', ''), $string));
 return $isjs ? 'document.write("'.$string.'");' : $string;
}
/**
 * 转义 javascript 代码标记
 *
 * @param $str
 * @return mixed
 */
 function trim_script($str) {
 if(is_array($str)){
  foreach ($str as $key => $val){
   $str[$key] = trim_script($val);
  }
  }else{
   $str = preg_replace ( '/\<([\/]?)script([^\>]*?)\>/si', '&lt;\\1script\\2&gt;', $str );
  $str = preg_replace ( '/\<([\/]?)iframe([^\>]*?)\>/si', '&lt;\\1iframe\\2&gt;', $str );
  $str = preg_replace ( '/\<([\/]?)frame([^\>]*?)\>/si', '&lt;\\1frame\\2&gt;', $str );
  $str = str_replace ( 'javascript:', 'javascript:', $str );
  }
 return $str;
}
/**
 * 获取当前页面完整URL地址
 */
function get_url() {
 $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
 $php_self = $_SERVER['PHP_SELF'] ? safe_replace($_SERVER['PHP_SELF']) : safe_replace($_SERVER['SCRIPT_NAME']);
 $path_info = isset($_SERVER['PATH_INFO']) ? safe_replace($_SERVER['PATH_INFO']) : '';
 $relate_url = isset($_SERVER['REQUEST_URI']) ? safe_replace($_SERVER['REQUEST_URI']) : $php_self.(isset($_SERVER['QUERY_STRING']) ? '?'.safe_replace($_SERVER['QUERY_STRING']) : $path_info);
 return $sys_protocal.(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '').$relate_url;
}
/**
 * 字符截取 支持UTF8/GBK
 * @param $string
 * @param $length
 * @param $dot
 */
function str_cut($string, $length, $dot = '...') {
 $strlen = strlen($string);
 if($strlen <= $length) return $string;
 $string = str_replace(array(' ','&nbsp;', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;'), array('∵',' ', '&', '"', "'", '', '', '', '<', '>', '·', '…'), $string);
 $strcut = '';
 if(strtolower(CHARSET) == 'utf-8') {
  $length = intval($length-strlen($dot)-$length/3);
  $n = $tn = $noc = 0;
  while($n < strlen($string)) {
   $t = ord($string[$n]);
   if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
    $tn = 1; $n++; $noc++;
   } elseif(194 <= $t && $t <= 223) {
    $tn = 2; $n += 2; $noc += 2;
   } elseif(224 <= $t && $t <= 239) {
    $tn = 3; $n += 3; $noc += 2;
   } elseif(240 <= $t && $t <= 247) {
    $tn = 4; $n += 4; $noc += 2;
   } elseif(248 <= $t && $t <= 251) {
    $tn = 5; $n += 5; $noc += 2;
   } elseif($t == 252 || $t == 253) {
    $tn = 6; $n += 6; $noc += 2;
   } else {
    $n++;
   }
   if($noc >= $length) {
    break;
   }
  }
  if($noc > $length) {
   $n -= $tn;
  }
  $strcut = substr($string, 0, $n);
  $strcut = str_replace(array('∵', '&', '"', "'", '', '', '', '<', '>', '·', ''), array(' ', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;'), $strcut);
 } else {
  $dotlen = strlen($dot);
  $maxi = $length - $dotlen - 1;
  $current_str = '';
  $search_arr = array('&',' ', '"', "'", '', '', '', '<', '>', '·', '','∵');
  $replace_arr = array('&amp;','&nbsp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;',' ');
  $search_flip = array_flip($search_arr);
  for ($i = 0; $i < $maxi; $i++) {
   $current_str = ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
   if (in_array($current_str, $search_arr)) {
    $key = $search_flip[$current_str];
    $current_str = str_replace($search_arr[$key], $replace_arr[$key], $current_str);
   }
   $strcut .= $current_str;
  }
 }
 return $strcut.$dot;
}
/**
 * 获取请求ip
 *
 * @return ip地址
 */
function ip() {
 if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
  $ip = getenv('HTTP_CLIENT_IP');
 } elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
  $ip = getenv('HTTP_X_FORWARDED_FOR');
 } elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
  $ip = getenv('REMOTE_ADDR');
 } elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
  $ip = $_SERVER['REMOTE_ADDR'];
 }
 return preg_match ( '/[\d\.]{7,15}/', $ip, $matches ) ? $matches [0] : '';
}
function get_cost_time() {
 $microtime = microtime ( TRUE );
 return $microtime - SYS_START_TIME;
}
/**
 * 程序执行时间
 *
 * @return int 单位ms
 */
function execute_time() {
 $stime = explode ( ' ', SYS_START_TIME );
 $etime = explode ( ' ', microtime () );
 return number_format ( ($etime [1] + $etime [0] - $stime [1] - $stime [0]), 6 );
}
/**
* 将字符串转换为数组
*
* @param string $data 字符串
* @return array 返回数组格式,如果,data为空,则返回空数组
*/
function string2array($data) {
 if($data == '') return array();
 $data = stripslashes($data);
 @eval("\$array = $data;");
 return $array;
}
/**
* 将数组转换为字符串
*
* @param array $data  数组
* @param bool $isformdata 如果为0,则不使用new_stripslashes处理,可选参数,默认为1
* @return string 返回字符串,如果,data为空,则返回空
*/
function array2string($data, $isformdata = 1) {
 if($data == '') return '';
 if($isformdata) $data = new_stripslashes($data);
 return addslashes(var_export($data, TRUE));
}
/**
* 转换字节数为其他单位
*
*
* @param string $filesize 字节大小
* @return string 返回大小
*/
function sizecount($filesize) {
 if ($filesize >= 1073741824) {
  $filesize = round($filesize / 1073741824 * 100) / 100 .' GB';
 } elseif ($filesize >= 1048576) {
  $filesize = round($filesize / 1048576 * 100) / 100 .' MB';
 } elseif($filesize >= 1024) {
  $filesize = round($filesize / 1024 * 100) / 100 . ' KB';
 } else {
  $filesize = $filesize.' Bytes';
 }
 return $filesize;
}
/**
* 字符串加密、解密函数
*
*
* @param string $txt  字符串
* @param string $operation ENCODE为加密,DECODE为解密,可选参数,默认为ENCODE,
* @param string $key  密钥:数字、字母、下划线
* @param string $expiry  过期时间
* @return string
*/
function sys_auth($string, $operation = 'ENCODE', $key = '', $expiry = 0) {
 $key_length = 4;
 $key = md5($key != '' ? $key : app_base::load_config('system', 'auth_key'));
 $fixedkey = md5($key);
 $egiskeys = md5(substr($fixedkey, 16, 16));
 $runtokey = $key_length ? ($operation == 'ENCODE' ? substr(md5(microtime(true)), -$key_length) : substr($string, 0, $key_length)) : '';
 $keys = md5(substr($runtokey, 0, 16) . substr($fixedkey, 0, 16) . substr($runtokey, 16) . substr($fixedkey, 16));
 $string = $operation == 'ENCODE' ? sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$egiskeys), 0, 16) . $string : base64_decode(substr($string, $key_length));
 $i = 0; $result = '';
 $string_length = strlen($string);
 for ($i = 0; $i < $string_length; $i++){
  $result .= chr(ord($string{$i}) ^ ord($keys{$i % 32}));
 }
 if($operation == 'ENCODE') {
  return $runtokey . str_replace('=', '', base64_encode($result));
 } else {
  if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$egiskeys), 0, 16)) {
   return substr($result, 26);
  } else {
   return '';
  }
 }
}
/**
* 语言文件处理
*
* @param string  $language 标示符
* @param array  $pars 转义的数组,二维数组 ,'key1'=>'value1','key2'=>'value2',
* @param string  $modules 多个模块之间用半角逗号隔开,如:member,guestbook
* @return string  语言字符
*/
function L($language = 'no_language',$pars = array(), $modules = '') {
 static $LANG = array();
 static $LANG_MODULES = array();
 static $lang = '';
 if(defined('IN_ADMIN')) {
  $lang = SYS_STYLE ? SYS_STYLE : 'zh-cn';
 } else {
  $lang = app_base::load_config('system','lang');
 }
 if(!$LANG) {
  require_once CODE_PATH.'languages'.DIRECTORY_SEPARATOR.$lang.DIRECTORY_SEPARATOR.'system.lang.php';
  if(defined('IN_ADMIN')) require_once CODE_PATH.'languages'.DIRECTORY_SEPARATOR.$lang.DIRECTORY_SEPARATOR.'system_menu.lang.php';
  if(file_exists(CODE_PATH.'languages'.DIRECTORY_SEPARATOR.$lang.DIRECTORY_SEPARATOR.ROUTE_M.'.lang.php')) require_once CODE_PATH.'languages'.DIRECTORY_SEPARATOR.$lang.DIRECTORY_SEPARATOR.ROUTE_M.'.lang.php';
 }
 if(!empty($modules)) {
  $modules = explode(',',$modules);
  foreach($modules AS $m) {
   if(!isset($LANG_MODULES[$m])) require_once CODE_PATH.'languages'.DIRECTORY_SEPARATOR.$lang.DIRECTORY_SEPARATOR.$m.'.lang.php';
  }
 }
 if(!array_key_exists($language,$LANG)) {
  return $language;
 } else {
  $language = $LANG[$language];
  if($pars) {
   foreach($pars AS $_k=>$_v) {
    $language = str_replace('{'.$_k.'}',$_v,$language);
   }
  }
  return $language;
 }
}
/**
 * 模板调用
 *
 * @param $module
 * @param $template
 * @param $istag
 * @return unknown_type
 */
function template($module = 'content', $template = 'index', $style = '') {
 if(strpos($module, 'plugin/')!== false) {
  $plugin = str_replace('plugin/', '', $module);
  return p_template($plugin, $template,$style);
 }
 $module = str_replace('/', DIRECTORY_SEPARATOR, $module);
 if(!empty($style) && preg_match('/([a-z0-9\-_]+)/is',$style)) {
 } elseif (empty($style) && !defined('STYLE')) {
  if(defined('SITEID')) {
   $siteid = SITEID;
  } else {
   $siteid = param::get_cookie('siteid');
  }
  if (!$siteid) $siteid = 1;
  $sitelist = getcache('sitelist','commons');
  if(!empty($siteid)) {
   $style = $sitelist[$siteid]['default_style'];
  }
 } elseif (empty($style) && defined('STYLE')) {
  $style = STYLE;
 } else {
  $style = 'default';
 }
 if(!$style) $style = 'default';
 $template_cache = app_base::load_sys_class('template_cache');
 $compiledtplfile = ROOT_PATH.'caches'.DIRECTORY_SEPARATOR.'caches_template'.DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.php';
 if(file_exists(CODE_PATH.'templates'.DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html')) {
  if(!file_exists($compiledtplfile) || (@filemtime(CODE_PATH.'templates'.DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html') > @filemtime($compiledtplfile))) {
   $template_cache->template_compile($module, $template, $style);
  }
 } else {
  $compiledtplfile = ROOT_PATH.'caches'.DIRECTORY_SEPARATOR.'caches_template'.DIRECTORY_SEPARATOR.'default'.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.php';
  if(!file_exists($compiledtplfile) || (file_exists(CODE_PATH.'templates'.DIRECTORY_SEPARATOR.'default'.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html') && filemtime(CODE_PATH.'templates'.DIRECTORY_SEPARATOR.'default'.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html') > filemtime($compiledtplfile))) {
   $template_cache->template_compile($module, $template, 'default');
  } elseif (!file_exists(CODE_PATH.'templates'.DIRECTORY_SEPARATOR.'default'.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html')) {
   showmessage('Template does not exist.'.DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html');
  }
 }
 return $compiledtplfile;
}
/**
 * 输出自定义错误
 *
 * @param $errno 错误号
 * @param $errstr 错误描述
 * @param $errfile 报错文件地址
 * @param $errline 错误行号
 * @return string 错误提示
 */
function my_error_handler($errno, $errstr, $errfile, $errline) {
 if($errno==8) return '';
 $errfile = str_replace(ROOT_PATH,'',$errfile);
 if(app_base::load_config('system','errorlog')) {
  error_log('<?php exit;?>'.date('m-d H:i:s',SYS_TIME).' | '.$errno.' | '.str_pad($errstr,30).' | '.$errfile.' | '.$errline."\r\n", 3, CACHE_PATH.'error_log.php');
 } else {
  $str = '<div style="font-size:12px;text-align:left; border-bottom:1px solid #9cc9e0; border-right:1px solid #9cc9e0;padding:1px 4px;color:#000000;font-family:Arial, Helvetica,sans-serif;"><span>errorno:' . $errno . ',str:' . $errstr . ',file:<font color="blue">' . $errfile . '</font>,line' . $errline .'<br />Need Help?</span></div>';
  echo $str;
 }
}
/**
 * 提示信息页面跳转,跳转地址如果传入数组,页面会提示多个地址供用户选择,默认跳转地址为数组的第一个值,时间为5秒。
 * showmessage('登录成功', array('默认跳转地址'=>'http://www.baidu.com'));
 * @param string $msg 提示信息
 * @param mixed(string/array) $url_forward 跳转地址
 * @param int $ms 跳转等待时间
 */
function showmessage($msg, $url_forward = 'goback', $ms = 1250, $dialog = '', $returnjs = '') {
 if(defined('IN_ADMIN')) {
  include(admin::admin_tpl('showmessage', 'admin'));
 } else {
  include(template('content', 'message'));
 }
 exit;
}
/**
 * 查询字符是否存在于某字符串
 *
 * @param $haystack 字符串
 * @param $needle 要查找的字符
 * @return bool
 */
function str_exists($haystack, $needle)
{
 return !(strpos($haystack, $needle) === FALSE);
}
/**
 * 取得文件扩展
 *
 * @param $filename 文件名
 * @return 扩展名
 */
function fileext($filename) {
 return strtolower(trim(substr(strrchr($filename, '.'), 1, 10)));
}
/**
 * 加载模板标签缓存
 * @param string $name 缓存名
 * @param integer $times 缓存时间
 */
function tpl_cache($name,$times = 0) {
 $filepath = 'tpl_data';
 $info = getcacheinfo($name, $filepath);
 if (SYS_TIME - $info['filemtime'] >= $times) {
  return false;
 } else {
  return getcache($name,$filepath);
 }
}
/**
 * 写入缓存,默认为文件缓存,不加载缓存配置。
 * @param $name 缓存名称
 * @param $data 缓存数据
 * @param $filepath 数据路径(模块名称) caches/cache_$filepath/
 * @param $type 缓存类型[file,memcache,apc]
 * @param $config 配置名称
 * @param $timeout 过期时间
 */
function setcache($name, $data, $filepath='', $type='file', $c AND ', $in_column = false) {
 if($in_column && is_array($data)) {
  $ids = '\''.implode('\',\'', $data).'\'';
  $sql = "$in_column IN ($ids)";
  return $sql;
 } else {
  if ($front == '') {
   $front = ' AND ';
  }
  if(is_array($data) && count($data) > 0) {
   $sql = '';
   foreach ($data as $key => $val) {
    $sql .= $sql ? " $front $key = '$val' " : " $key = '$val' ";
   }
   return $sql;
  } else {
   return $data;
  }
 }
}
/**
 * 分页函数
 *
 * @param $num 信息总数
 * @param $curr_page 当前分页
 * @param $perpage 每页显示数
 * @param $urlrule URL规则
 * @param $array 需要传递的数组,用于增加额外的方法
 * @return 分页
 */
function pages($num, $curr_page, $perpage = 20, $urlrule = '', $array = array(),$setpages = 10) {
 if(defined('URLRULE') && $urlrule == '') {
  $urlrule = URLRULE;
  $array = $GLOBALS['URL_ARRAY'];
 } elseif($urlrule == '') {
  $urlrule = url_par('page={$page}');
 }
 $multipage = '';
 if($num > $perpage) {
  $page = $setpages+1;
  $offset = ceil($setpages/2-1);
  $pages = ceil($num / $perpage);
  if (defined('IN_ADMIN') && !defined('PAGES')) define('PAGES', $pages);
  $from = $curr_page - $offset;
  $to = $curr_page + $offset;
  $more = 0;
  if($page >= $pages) {
   $from = 2;
   $to = $pages-1;
  } else {
   if($from <= 1) {
    $to = $page-1;
    $from = 2;
   } elseif($to >= $pages) {
    $from = $pages-($page-2);
    $to = $pages-1;
   }
   $more = 1;
  }
  //$multipage .= '<a class="a1">'.$num.L('page_item').'</a>';
  if($curr_page>0) {
   $multipage .= ' <a href="'.pageurl($urlrule, $curr_page-1, $array).'" class="a1">'.L('previous').'</a>';
   if($curr_page==1) {
    $multipage .= ' <span>1</span>';
   } elseif($curr_page>6 && $more) {
    $multipage .= ' <a href="'.pageurl($urlrule, 1, $array).'">1</a>..';
   } else {
    $multipage .= ' <a href="'.pageurl($urlrule, 1, $array).'">1</a>';
   }
  }
  for($i = $from; $i <= $to; $i++) {
   if($i != $curr_page) {
    $multipage .= ' <a href="'.pageurl($urlrule, $i, $array).'">'.$i.'</a>';
   } else {
    $multipage .= ' <span>'.$i.'</span>';
   }
  }
  if($curr_page<$pages) {
   if($curr_page<$pages-5 && $more) {
    $multipage .= ' ..<a href="'.pageurl($urlrule, $pages, $array).'">'.$pages.'</a> <a href="'.pageurl($urlrule, $curr_page+1, $array).'" class="a1">'.L('next').'</a>';
   } else {
    $multipage .= ' <a href="'.pageurl($urlrule, $pages, $array).'">'.$pages.'</a> <a href="'.pageurl($urlrule, $curr_page+1, $array).'" class="a1">'.L('next').'</a>';
   }
  } elseif($curr_page==$pages) {
   $multipage .= ' <span>'.$pages.'</span> <a href="'.pageurl($urlrule, $curr_page, $array).'" class="a1">'.L('next').'</a>';
  } else {
   $multipage .= ' <a href="'.pageurl($urlrule, $pages, $array).'">'.$pages.'</a> <a href="'.pageurl($urlrule, $curr_page+1, $array).'" class="a1">'.L('next').'</a>';
  }
 }
 return $multipage;
}
function pages1($num, $curr_page, $perpage = 20, $urlrule = '', $array = array(),$setpages = 10) {
 if(defined('URLRULE') && $urlrule == '') {
  $urlrule = URLRULE;
  $array = $GLOBALS['URL_ARRAY'];
 } elseif($urlrule == '') {
  $urlrule = url_par('page={$page}');
 }
 $multipage = '';
 if($num > $perpage) {
  $page = $setpages+1;
  $offset = ceil($setpages/2-1);
  $pages = ceil($num / $perpage);
  if (defined('IN_ADMIN') && !defined('PAGES')) define('PAGES', $pages);
  $from = $curr_page - $offset;
  $to = $curr_page + $offset;
  $more = 0;
  if($page >= $pages) {
   $from = 2;
   $to = $pages-1;
  } else {
   if($from <= 1) {
    $to = $page-1;
    $from = 2;
   } elseif($to >= $pages) {
    $from = $pages-($page-2);
    $to = $pages-1;
   }
   $more = 1;
  }
  //$multipage .= '<a class="a1">'.$num.L('page_item').'</a>';
  if($curr_page>0) {
   $multipage .= ' <a href="###" class="a1">'.L('previous').'</a>';
   if($curr_page==1) {
    $multipage .= ' <span>1</span>';
   } elseif($curr_page>6 && $more) {
    $multipage .= ' <a href="###" /a>..';
   } else {
    $multipage .= ' <a href="###" /a>';
   }
  }
  for($i = $from; $i <= $to; $i++) {
   if($i != $curr_page) {
    $multipage .= ' <a href="###" /a>';
   } else {
    $multipage .= ' <span>'.$i.'</span>';
   }
  }
  if($curr_page<$pages) {
   if($curr_page<$pages-5 && $more) {
    $multipage .= ' ..<a href="###" /a> <a href="###" class="a1">'.L('next').'</a>';
   } else {
    $multipage .= ' <a href="###" /a> <a href="###" class="a1">'.L('next').'</a>';
   }
  } elseif($curr_page==$pages) {
   $multipage .= ' <span>'.$pages.'</span> <a href="###" class="a1">'.L('next').'</a>';
  } else {
   $multipage .= ' <a href="###" /a> <a href="###" class="a1">'.L('next').'</a>';
  }
 }
 return $multipage;
}
function pages2($num, $curr_page, $pages, $urlrule = '', $array = array(),$setpages = 10) {
 if(defined('URLRULE') && $urlrule == '') {
  $urlrule = URLRULE;
  $array = $GLOBALS['URL_ARRAY'];
 } elseif($urlrule == '') {
  $urlrule = url_par('page={$page}');
 }
 $multipage = '';
 if($pages > 1) {
  $page = $setpages+1;
  $offset = ceil($setpages/2-1);
  if (defined('IN_ADMIN') && !defined('PAGES')) define('PAGES', $pages);
  $from = $curr_page - $offset;
  $to = $curr_page + $offset;
  $more = 0;
  if($page >= $pages) {
   $from = 2;
   $to = $pages-1;
  } else {
   if($from <= 1) {
    $to = $page-1;
    $from = 2;
   } elseif($to >= $pages) {
    $from = $pages-($page-2);
    $to = $pages-1;
   }
   $more = 1;
  }
  //$multipage .= '<a class="a1">'.$num.L('page_item').'</a>';
  if($curr_page>0) {
   $multipage .= ' <a href="###" class="a1">'.L('previous').'</a>';
   if($curr_page==1) {
    $multipage .= ' <span>1</span>';
   } elseif($curr_page>6 && $more) {
    $multipage .= ' <a href="###" /a>..';
   } else {
    $multipage .= ' <a href="###" /a>';
   }
  }
  for($i = $from; $i <= $to; $i++) {
   if($i != $curr_page) {
    $multipage .= ' <a href="###" /a>';
   } else {
    $multipage .= ' <span>'.$i.'</span>';
   }
  }
  if($curr_page<$pages) {
   if($curr_page<$pages-5 && $more) {
    $multipage .= ' ..<a href="###" /a> <a href="###" class="a1">'.L('next').'</a>';
   } else {
    $multipage .= ' <a href="###" /a> <a href="###" class="a1">'.L('next').'</a>';
   }
  } elseif($curr_page==$pages) {
   $multipage .= ' <span>'.$pages.'</span> <a href="###" class="a1">'.L('next').'</a>';
  } else {
   $multipage .= ' <a href="###" /a> <a href="###" class="a1">'.L('next').'</a>';
  }
 }
 return $multipage;
}
/**
 * 返回分页路径
 *
 * @param $urlrule 分页规则
 * @param $page 当前页
 * @param $array 需要传递的数组,用于增加额外的方法
 * @return 完整的URL路径
 */
function pageurl($urlrule, $page, $array = array()) {
 if(strpos($urlrule, '~')) {
  $urlrules = explode('~', $urlrule);
  $urlrule = $page < 2 ? $urlrules[0] : $urlrules[1];
 }
 $findme = array('{$page}');
 $replaceme = array($page);
 if (is_array($array)) foreach ($array as $k=>$v) {
  $findme[] = '{$'.$k.'}';
  $replaceme[] = $v;
 }
 $url = str_replace($findme, $replaceme, $urlrule);
 $url = str_replace(array('http://','//','~'), array('~','/','http://'), $url);
 return $url;
}
/**
 * URL路径解析,pages 函数的辅助函数
 *
 * @param $par 传入需要解析的变量 默认为,page={$page}
 * @param $url URL地址
 * @return URL
 */
function url_par($par, $url = '') {
 if($url == '') $url = get_url();
 $pos = strpos($url, '?');
 if($pos === false) {
  $url .= '?'.$par;
 } else {
  $querystring = substr(strstr($url, '?'), 1);
  parse_str($querystring, $pars);
  $query_array = array();
  foreach($pars as $k=>$v) {
   if($k != 'page') $query_array[$k] = $v;
  }
  $querystring = http_build_query($query_array).'&'.$par;
  $url = substr($url, 0, $pos).'?'.$querystring;
 }
 return $url;
}
/**
 * 判断email格式是否正确
 * @param $email
 */
function is_email($email) {
 return strlen($email) > 6 && preg_match("/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/", $email);
}
/**
 * iconv 编辑转换
 */
if (!function_exists('iconv')) {
 function iconv($in_charset, $out_charset, $str) {
  $in_charset = strtoupper($in_charset);
  $out_charset = strtoupper($out_charset);
  if (function_exists('mb_convert_encoding')) {
   return mb_convert_encoding($str, $out_charset, $in_charset);
  } else {
   app_base::load_sys_func('iconv');
   $in_charset = strtoupper($in_charset);
   $out_charset = strtoupper($out_charset);
   if ($in_charset == 'UTF-8' && ($out_charset == 'GBK' || $out_charset == 'GB2312')) {
    return utf8_to_gbk($str);
   }
   if (($in_charset == 'GBK' || $in_charset == 'GB2312') && $out_charset == 'UTF-8') {
    return gbk_to_utf8($str);
   }
   return $str;
  }
 }
}
/**
 * 代码广告展示函数
 * @param intval $siteid 所属站点
 * @param intval $id 广告ID
 * @return 返回广告代码
 */
function show_ad($siteid, $id) {
 $siteid = intval($siteid);
 $id = intval($id);
 if(!$id || !$siteid) return false;
 $p = app_base::load_model('poster_model');
 $r = $p->get_one(array('spaceid'=>$id, 'siteid'=>$siteid), 'disabled, setting', 'id ASC');
 if ($r['disabled']) return '';
 if ($r['setting']) {
  $c = string2array($r['setting']);
 } else {
  $r['code'] = '';
 }
 return $c['code'];
}
/**
 * 获取当前的站点ID
 */
function get_siteid() {
 static $siteid;
 if (!empty($siteid)) return $siteid;
 if (defined('IN_ADMIN')) {
  if ($d = param::get_cookie('siteid')) {
   $siteid = $d;
  } else {
   return '';
  }
 } else {
  $data = getcache('sitelist', 'commons');
  if(!is_array($data)) return '1';
  $site_url = SITE_PROTOCOL.SITE_URL;
  foreach ($data as $v) {
   if ($v['url'] == $site_url.'/') $siteid = $v['siteid'];
  }
 }
 if (empty($siteid)) $siteid = 1;
 return $siteid;
}
/**
 * 获取用户昵称
 * 不传入userid取当前用户nickname,如果nickname为空取username
 * 传入field,取用户$field字段信息
 */
function get_nickname($userid='', $field='') {
 $return = '';
 if(is_numeric($userid)) {
  $member_db = app_base::load_model('member_model');
  $memberinfo = $member_db->get_one(array('userid'=>$userid));
  if(!empty($field) && $field != 'nickname' && isset($memberinfo[$field]) &&!empty($memberinfo[$field])) {
   $return = $memberinfo[$field];
  } else {
   $return = isset($memberinfo['nickname']) && !empty($memberinfo['nickname']) ? $memberinfo['nickname'].'('.$memberinfo['username'].')' : $memberinfo['username'];
  }
 } else {
  if (param::get_cookie('_nickname')) {
   $return .= '('.param::get_cookie('_nickname').')';
  } else {
   $return .= '('.param::get_cookie('_username').')';
  }
 }
 return $return;
}
/**
 * 获取用户信息
 * 不传入$field返回用户所有信息,
 * 传入field,取用户$field字段信息
 */
function get_memberinfo($userid, $field='') {
 if(!is_numeric($userid)) {
  return false;
 } else {
  static $memberinfo;
  if (!isset($memberinfo[$userid])) {
   $member_db = app_base::load_model('member_model');
   $memberinfo[$userid] = $member_db->get_one(array('userid'=>$userid));
  }
  if(!empty($field) && !empty($memberinfo[$userid][$field])) {
   return $memberinfo[$userid][$field];
  } else {
   return $memberinfo[$userid];
  }
 }
}
/**
 * 通过 username 值,获取用户所有信息
 * 获取用户信息
 * 不传入$field返回用户所有信息,
 * 传入field,取用户$field字段信息
 */
function get_memberinfo_buyusername($username, $field='') {
 if(empty($username)){return false;}
 static $memberinfo;
 if (!isset($memberinfo[$username])) {
  $member_db = app_base::load_model('member_model');
  $memberinfo[$username] = $member_db->get_one(array('username'=>$username));
 }
 if(!empty($field) && !empty($memberinfo[$username][$field])) {
  return $memberinfo[$username][$field];
 } else {
  return $memberinfo[$username];
 }
}
/**
 * 调用关联菜单
 * @param $linkageid 联动菜单id
 * @param $id 生成联动菜单的样式id
 * @param $defaultvalue 默认值
 */
function menu_linkage($linkageid = 0, $id = 'linkid', $defaultvalue = 0, $defaultlabel = array()) {
 $linkageid = intval($linkageid);
 $datas = array();
 $datas = getcache($linkageid,'linkage');
 $infos = $datas['data'];
 if($datas['style']=='1') {
  $title = $datas['title'];
  $container = 'content'.create_randomnum(100, 999).date('is');
  if(!defined('DIALOG_INIT_1')) {
   define('DIALOG_INIT_1', 1);
   $string .= '<script type="text/javascript" src="'.JS_PATH.'dialog.js"></script>';
   //TODO $string .= '<link href="'.CSS_PATH.'dialog.css" rel="stylesheet" type="text/css">';
  }
  if(!defined('LINKAGE_INIT_1')) {
   define('LINKAGE_INIT_1', 1);
   $string .= '<script type="text/javascript" src="'.JS_PATH.'linkage/js/pop.js"></script>';
  }
  $var_div = $defaultvalue && (ROUTE_A=='edit' || ROUTE_A=='account_manage_info' || ROUTE_A=='info_publish' || ROUTE_A=='orderinfo') ? menu_linkage_level($defaultvalue,$linkageid,$infos) : $datas['title'];
  $var_input = $defaultvalue && (ROUTE_A=='edit' || ROUTE_A=='account_manage_info' || ROUTE_A=='info_publish') ? '<input type="hidden" name="info['.$id.']" value="'.$defaultvalue.'">' : '<input type="hidden" name="info['.$id.']" value="">';
  $string .= '<div name="'.$id.'" value="" id="'.$id.'" class="ib">'.$var_div.'</div>'.$var_input.' <input type="button" name="btn_'.$id.'" class="button" value="'.L('linkage_select').'" >  $string .= '<script type="text/javascript">';
  $string .= 'var returnid_'.$id.'= \''.$id.'\';';
  $string .= 'var returnkeyid_'.$id.' = \''.$linkageid.'\';';
  $string .= 'var '.$container.' = new Array(';
  foreach($infos AS $k=>$v) {
   if($v['parentid'] == 0) {
    $s[]='new Array(\''.$v['linkageid'].'\',\''.$v['name'].'\',\''.$v['parentid'].'\')';
   } else {
    continue;
   }
  }
  $s = implode(',',$s);
  $string .=$s;
  $string .= ')';
  $string .= '</script>';
 } elseif($datas['style']=='2') {
  if(!defined('LINKAGE_INIT_1')) {
   define('LINKAGE_INIT_1', 1);
   $string .= '<script type="text/javascript" src="'.JS_PATH.'linkage/js/jquery.ld.js"></script>';
  }
  $default_txt = '';
  if($defaultvalue) {
    $default_txt = menu_linkage_level($defaultvalue,$linkageid,$infos);
    $default_txt = '["'.str_replace(' > ','","',$default_txt).'"]';
  }
  $string .= $defaultvalue && (ROUTE_A=='edit' || ROUTE_A=='account_manage_info' || ROUTE_A=='info_publish') ? '<input type="hidden" name="info['.$id.']" id="'.$id.'" value="'.$defaultvalue.'">' : '<input type="hidden" name="info['.$id.']" id="'.$id.'" value="">';
  for($i=1;$i<=$datas['setting']['level'];$i++) {
   $txt = isset($defaultlabel[$i]) ? $defaultlabel[$i] : '请选择';
   $string .='<select class="pc-select-'.$id.'" name="'.$id.'-'.$i.'" id="'.$id.'-'.$i.'" width="100"><option value="">' . $txt . '</option></select> ';
  }
  $string .= '<script type="text/javascript">
     $(function(){
      var $ld5 = $(".pc-select-'.$id.'");
      $ld5.ld({ajaxOptions : {"url" : "'.APP_PATH.'api.php?op=get_linkage&act=ajax_select&keyid='.$linkageid.'"},defaultParentId : 0,style : {"width" : 120}})
      var ld5_api = $ld5.ld("api");
      //ld5_api.selected('.$default_txt.');
      $ld5.bind("change",onchange);
      function onchange(e){
       var $target = $(e.target);
       var index = $ld5.index($target);
       $("#'.$id.'-'.$i.'").remove();
       $("#'.$id.'").val($ld5.eq(index).show().val());
       index ++;
       $ld5.eq(index).show();        }
     })
  </script>';
 } else {
  $title = $defaultvalue ? $infos[$defaultvalue]['name'] : $datas['title'];
  $colObj = create_randomnum(100, 999).date('is');
  $string = '';
  if(!defined('LINKAGE_INIT')) {
   define('LINKAGE_INIT', 1);
   $string .= '<script type="text/javascript" src="'.JS_PATH.'linkage/js/mln.colselect.js"></script>';
   if(defined('IN_ADMIN')) {
    $string .= '<link href="'.JS_PATH.'linkage/style/admin.css" rel="stylesheet" type="text/css">';
   } else {
    $string .= '<link href="'.JS_PATH.'linkage/style/css.css" rel="stylesheet" type="text/css">';
   }
  }
  $string .= '<input type="hidden" name="info['.$id.']" value="1"><div id="'.$id.'"></div>';
  $string .= '<script type="text/javascript">';
  $string .= 'var colObj'.$colObj.' = {"Items":[';
  foreach($infos AS $k=>$v) {
   $s .= '{"name":"'.$v['name'].'","topid":"'.$v['parentid'].'","colid":"'.$k.'","value":"'.$k.'","fun":function(){}},';
  }
  $string .= substr($s, 0, -1);
  $string .= ']};';
  $string .= '$("#'.$id.'").mlnColsel(colObj'.$colObj.',{';
  $string .= 'title:"'.$title.'",';
  $string .= 'value:"'.$defaultvalue.'",';
  $string .= 'width:100';
  $string .= '});';
  $string .= '</script>';
 }
 return $string;
}
/**
 * 联动菜单层级
 */
function menu_linkage_level($linkageid,$keyid,$infos,$result=array()) {
 if(array_key_exists($linkageid,$infos)) {
  $result[]=$infos[$linkageid]['name'];
  return menu_linkage_level($infos[$linkageid]['parentid'],$keyid,$infos,$result);
 }
 krsort($result);
 return implode(' > ',$result);
}
/**
 * 通过catid获取显示菜单完整结构
 * @param $menuid 菜单ID
 * @param $cache_file 菜单缓存文件名称
 * @param $cache_path 缓存文件目录
 * @param $key 取得缓存值的键值名称
 * @param $parentkey 父级的ID
 * @param $linkstring 链接字符
 */
function menu_level($menuid, $cache_file, $cache_path = 'commons', $key = 'catname', $parentkey = 'parentid', $linkstring = ' > ', $result=array()) {
 $menu_arr = getcache($cache_file, $cache_path);
 if (array_key_exists($menuid, $menu_arr)) {
  $result[] = $menu_arr[$menuid][$key];
  return menu_level($menu_arr[$menuid][$parentkey], $cache_file, $cache_path, $key, $parentkey, $linkstring, $result);
 }
 krsort($result);
 return implode($linkstring, $result);
}
/**
 * 通过id获取显示联动菜单
 * @param $linkageid 联动菜单ID
 * @param $keyid 菜单keyid
 * @param $space 菜单间隔符
 * @param $tyoe 1 返回间隔符链接,完整路径名称 3 返回完整路径数组,2返回当前联动菜单名称,4 直接返回ID
 * @param $result 递归使用字段1
 * @param $infos 递归使用字段2
 */
function get_linkage($linkageid, $keyid, $space = '>', $type = 1, $result = array(), $infos = array()) {
 if($space=='' || !isset($space))$space = '>';
 if(!$infos) {
  $datas = getcache($keyid,'linkage');
  $infos = $datas['data'];
 }
 if($type == 1 || $type == 3 || $type == 4) {
  if(array_key_exists($linkageid,$infos)) {
   $result[]= ($type == 1) ? $infos[$linkageid]['name'] : (($type == 4) ? $linkageid :$infos[$linkageid]);
   return get_linkage($infos[$linkageid]['parentid'], $keyid, $space, $type, $result, $infos);
  } else {
   if(count($result)>0) {
    krsort($result);
    if($type == 1 || $type == 4) $result = implode($space,$result);
    return $result;
   } else {
    return $result;
   }
  }
 } else {
  return $infos[$linkageid]['name'];
 }
}
/**
 * IE浏览器判断
 */
function is_ie() {
 $useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
 if((strpos($useragent, 'opera') !== false) || (strpos($useragent, 'konqueror') !== false)) return false;
 if(strpos($useragent, 'msie ') !== false) return true;
 return false;
}
/**
 * 文件下载
 * @param $filepath 文件路径
 * @param $filename 文件名称
 */
function file_down($filepath, $filename = '') {
 if(!$filename) $filename = basename($filepath);
 if(is_ie()) $filename = rawurlencode($filename);
 $filetype = fileext($filename);
 $filesize = sprintf("%u", filesize($filepath));
 if(ob_get_length() !== false) @ob_end_clean();
 header('Pragma: public');
 header('Last-Modified: '.gmdate('D, d M Y H:i:s') . ' GMT');
 header('Cache-Control: no-store, no-cache, must-revalidate');
 header('Cache-Control: pre-check=0, post-check=0, max-age=0');
 header('Content-Transfer-Encoding: binary');
 header('Content-Encoding: none');
 header('Content-type: '.$filetype);
 header('Content-Disposition: attachment; filename="'.$filename.'"');
 header('Content-length: '.$filesize);
 readfile($filepath);
 exit;
}
/**
 * 判断字符串是否为utf8编码,英文和半角字符返回ture
 * @param $string
 * @return bool
 */
function is_utf8($string) {
 return preg_match('%^(?:
     [\x09\x0A\x0D\x20-\x7E] # ASCII
     | [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
     | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
     | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
     | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
     | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
     | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
     | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
     )*$%xs', $string);
}
/**
 * 组装生成ID号
 * @param $modules 模块名
 * @param $contentid 内容ID
 * @param $siteid 站点ID
 */
function id_encode($modules,$contentid, $siteid) {
 return urlencode($modules.'-'.$contentid.'-'.$siteid);
}
/**
 * 解析ID
 * @param $id 评论ID
 */
function id_decode($id) {
 return explode('-', $id);
}
/**
 * 对用户的密码进行加密
 * @param $password
 * @param $encrypt //传入加密串,在修改密码时做认证
 * @return array/password
 */
function password($password, $encrypt='') {
 $pwd = array();
 $pwd['encrypt'] = $encrypt ? $encrypt : create_randomstr();
 $pwd['password'] = md5(md5(trim($password)).$pwd['encrypt']);
 return $encrypt ? $pwd['password'] : $pwd;
}
/**
 * 生成随机字符串
 * @param string $lenth 长度
 * @return string 字符串
 */
function create_randomstr($lenth = 6) {
 //openssl_random_pseudo_bytes
 $fp = @fopen('/dev/urandom','rb');
 $pr_bits = '';
 if ($fp !== FALSE) {
  $pr_bits .= @fread($fp,$lenth/2);
  @fclose($fp);
 }
 return bin2hex($pr_bits);
 //return random($lenth, '123456789abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ');
}
/**
 * 生成随机数
 * @param string $lenth 长度
 * @return string 字符串
 */
function create_randomnum($min,$max) {
 //openssl_random_pseudo_bytes
 $difference = $max-$min;
 $bytesNeeded = ceil($difference/256);
 $fp = @fopen('/dev/urandom','rb');
 if ($fp !== FALSE) {
  $randomBytes = @fread($fp,$bytesNeeded);
  @fclose($fp);
 }
 $sum = 0;
 for ($a = 0; $a < $bytesNeeded; $a++){
  $sum += ord($randomBytes[$a]);
 }
 $sum = $sum % ($difference);
 return $sum + $min;
 //return random($lenth, '123456789abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ');
}
/**
 * 检查密码长度是否符合规定
 *
 * @param STRING $password
 * @return  TRUE or FALSE
 */
function is_password($password) {
 $strlen = strlen($password);
 if($strlen >= 6 && $strlen <= 20) return true;
 return false;
}
 /**
 * 检测输入中是否含有错误字符
 *
 * @param char $string 要检查的字符串名称
 * @return TRUE or FALSE
 */
function is_badword($string) {
 $badwords = array("\\",'&',' ',"'",'"','/','*',',','<','>',"\r","\t","\n","#");
 foreach($badwords as $value){
  if(strpos($string, $value) !== FALSE) {
   return TRUE;
  }
 }
 return FALSE;
}
/**
 * 检查用户名是否符合规定
 *
 * @param STRING $username 要检查的用户名
 * @return  TRUE or FALSE
 */
function is_username($username) {
 $strlen = strlen($username);
 if(is_badword($username) || !preg_match("/^[a-zA-Z0-9_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]+$/", $username)){
  return false;
 } elseif ( 20 < $strlen || $strlen < 2 ) {
  return false;
 }
 return true;
}
/**
 * 检查id是否存在于数组中
 *
 * @param $id
 * @param $ids
 * @param $s
 */
function check_in($id, $ids = '', $s = ',') {
 if(!$ids) return false;
 $ids = explode($s, $ids);
 return is_array($id) ? array_intersect($id, $ids) : in_array($id, $ids);
}
/**
 * 对数据进行编码转换
 * @param array/string $data  数组
 * @param string $input  需要转换的编码
 * @param string $output 转换后的编码
 */
function array_iconv($data, $input = 'gbk', $output = 'utf-8') {
 if (!is_array($data)) {
  return iconv($input, $output, $data);
 } else {
  foreach ($data as $key=>$val) {
   if(is_array($val)) {
    $data[$key] = array_iconv($val, $input, $output);
   } else {
    $data[$key] = iconv($input, $output, $val);
   }
  }
  return $data;
 }
}
/**
 * 生成缩略图函数
 * @param $imgurl 图片路径
 * @param $width 缩略图宽度
 * @param $height 缩略图高度
 * @param $autocut 是否自动裁剪 默认裁剪,当高度或宽度有一个数值为0是,自动关闭
 * @param $smallpic 无图片是默认图片路径
 */
function thumb($imgurl, $width = 100, $height = 100 ,$autocut = 1, $smallpic = 'nopic.gif') {
 global $image;
 $upload_url = app_base::load_config('system','upload_url');
 $upload_path = app_base::load_config('system','upload_path');
 if(empty($imgurl)) return IMG_PATH.$smallpic;
 $imgurl_replace= str_replace($upload_url, '', $imgurl);
 if(!extension_loaded('gd') || strpos($imgurl_replace, '://')) return $imgurl;
 if(!file_exists($upload_path.$imgurl_replace)) return IMG_PATH.$smallpic;
 list($width_t, $height_t, $type, $attr) = getimagesize($upload_path.$imgurl_replace);
 if($width>=$width_t || $height>=$height_t) return $imgurl;
 $newimgurl = dirname($imgurl_replace).'/thumb_'.$width.'_'.$height.'_'.basename($imgurl_replace);
 if(file_exists($upload_path.$newimgurl)) return $upload_url.$newimgurl;
 if(!is_object($image)) {
  app_base::load_sys_class('image','','0');
  $image = new image(1,0);
 }
 return $image->thumb($upload_path.$imgurl_replace, $upload_path.$newimgurl, $width, $height, '', $autocut) ? $upload_url.$newimgurl : $imgurl;
}
/**
 * 水印添加
 * @param $source 原图片路径
 * @param $target 生成水印图片途径,默认为空,覆盖原图
 * @param $siteid 站点id,系统需根据站点id获取水印信息
 */
function watermark($source, $target = '',$siteid) {
 global $image_w;
 if(empty($source)) return $source;
 if(!extension_loaded('gd') || strpos($source, '://')) return $source;
 if(!$target) $target = $source;
 if(!is_object($image_w)){
  app_base::load_sys_class('image','','0');
  $image_w = new image(0,$siteid);
 }
  $image_w->watermark($source, $target);
 return $target;
}
/**
 * 当前路径
 * 返回指定栏目路径层级
 * @param $catid 栏目id
 * @param $symbol 栏目间隔符
 */
function catpos($catid, $symbol=' > '){
 $category_arr = array();
 $siteids = getcache('category_content','commons');
 $siteid = $siteids[$catid];
 $category_arr = getcache('category_content_'.$siteid,'commons');
 if(!isset($category_arr[$catid])) return '';
 $pos = '';
 $siteurl = siteurl($category_arr[$catid]['siteid']);
 $arrparentid = array_filter(explode(',', $category_arr[$catid]['arrparentid'].','.$catid));
 foreach($arrparentid as $catid) {
  $url = $category_arr[$catid]['url'];
 // if(strpos($url, '://') === false) $url = $siteurl.$url;
  $pos .= '<a href="'.$url.'">'.$category_arr[$catid]['catname'].'</a>'.$symbol;
 }
 return $pos;
}
/**
 * 根据catid获取子栏目数据的sql语句
 * @param string $module 缓存文件名
 * @param intval $catid 栏目ID
 */
function get_sql_catid($file = 'category_content_1', $catid = 0, $module = 'commons') {
 $category = getcache($file,$module);
 $catid = intval($catid);
 if(!isset($category[$catid])) return false;
 return $category[$catid]['child'] ? " catid IN(".$category[$catid]['arrchildid'].") " : " catid=$catid ";
}
/**
 * 获取子栏目
 * @param $parentid 父级id
 * @param $type 栏目类型
 * @param $self 是否包含本身 0为不包含
 * @param $siteid 站点id
 */
function subcat($parentid = NULL, $type = NULL,$self = '0', $siteid = '') {
 if (empty($siteid)) $siteid = get_siteid();
 $category = getcache('category_content_'.$siteid,'commons');
 foreach($category as $id=>$cat) {
  if($cat['siteid'] == $siteid && ($parentid === NULL || $cat['parentid'] == $parentid) && ($type === NULL || $cat['type'] == $type)) $subcat[$id] = $cat;
  if($self == 1 && $cat['catid'] == $parentid && !$cat['child']) $subcat[$id] = $cat;
 }
 return $subcat;
}
/**
 * 获取内容地址
 * @param $catid 栏目ID
 * @param $id  文章ID
 * @param $allurl 是否以绝对路径返回
 */
function go($catid,$id, $allurl = 0) {
 static $category;
 if(empty($category)) {
  $siteids = getcache('category_content','commons');
  $siteid = $siteids[$catid];
  $category = getcache('category_content_'.$siteid,'commons');
 }
 $id = intval($id);
 if(!$id || !isset($category[$catid])) return '';
 $modelid = $category[$catid]['modelid'];
 if(!$modelid) return '';
 $db = app_base::load_model('content_model');
 $db->set_model($modelid);
 $r = $db->setCache()->get_one(array('id'=>$id), 'url');
 if (!empty($allurl)) {
  if (strpos($r['url'], '://')===false) {
   if (strpos($category[$catid]['url'], '://') === FALSE) {
    $site = siteinfo($category[$catid]['siteid']);
    $r['url'] = substr($site['domain'], 0, -1).$r['url'];
   } else {
    $r['url'] = $category[$catid]['url'].$r['url'];
   }
  }
 }
 return $r['url'];
}
/**
 * 将附件地址转换为绝对地址
 * @param $path 附件地址
 */
function atturl($path) {
 if(strpos($path, ':/')) {
  return $path;
 } else {
  $sitelist = getcache('sitelist','commons');
  $siteid = get_siteid();
  $siteurl = $sitelist[$siteid]['domain'];
  $domainlen = strlen($sitelist[$siteid]['domain'])-1;
  $path = $siteurl.$path;
  $path = substr_replace($path, '/', strpos($path, '//',$domainlen),2);
  return  $path;
 }
}
/**
 * 判断模块是否安装
 * @param $m 模块名称
 */
function module_exists($m = '') {
 if ($m=='admin') return true;
 $modules = getcache('modules', 'commons');
 $modules = array_keys($modules);
 return in_array($m, $modules);
}
/**
 * 生成SEO
 * @param $siteid  站点ID
 * @param $catid  栏目ID
 * @param $title  标题
 * @param $description 描述
 * @param $keyword  关键词
 */
function seo($siteid, $catid = '', $title = '', $description = '', $keyword = '') {
 if (!empty($title))$title = strip_tags($title);
 if (!empty($description)) $description = strip_tags($description);
 if (!empty($keyword)) $keyword = str_replace(' ', ',', strip_tags($keyword));
 $sites = getcache('sitelist', 'commons');
 $site = $sites[$siteid];
 $cat = array();
 if (!empty($catid)) {
  $siteids = getcache('category_content','commons');
  $siteid = $siteids[$catid];
  $categorys = getcache('category_content_'.$siteid,'commons');
  $cat = $categorys[$catid];
  $cat['setting'] = string2array($cat['setting']);
 }
 $seo['site_title'] =isset($site['site_title']) && !empty($site['site_title']) ? $site['site_title'] : $site['name'];
 $seo['keyword'] = !empty($keyword) ? $keyword : $site['keywords'];
 $seo['description'] = isset($description) && !empty($description) ? $description : (isset($cat['setting']['meta_description']) && !empty($cat['setting']['meta_description']) ? $cat['setting']['meta_description'] : (isset($site['description']) && !empty($site['description']) ? $site['description'] : ''));
 $seo['title'] = (isset($title) && !empty($title) ? $title.' - ' : '').(isset($cat['setting']['meta_title']) && !empty($cat['setting']['meta_title']) ? $cat['setting']['meta_title'].' - ' : (isset($cat['catname']) && !empty($cat['catname']) ? $cat['catname'].' - ' : ''));
 foreach ($seo as $k=>$v) {
  $seo[$k] = str_replace(array("\n","\r"), '', $v);
 }
 return $seo;
}
/**
 * 获取站点的信息
 * @param $siteid 站点ID
 */
function siteinfo($siteid) {
 static $sitelist;
 if (empty($sitelist)) $sitelist = getcache('sitelist','commons');
 return isset($sitelist[$siteid]) ? $sitelist[$siteid] : '';
}
/**
 * 生成CNZZ统计代码
 */
function tjcode() {
 if(!module_exists('cnzz')) return false;
 $config = getcache('cnzz', 'commons');
 if (empty($config)) {
  return false;
 } else {
  return '<script src=\'http://pw.cnzz.com/c.php?id='.$config['siteid'].'&l=2\' language=\'JavaScript\' charset=\'gb2312\'></script>';
 }
}
/**
 * 生成标题样式
 * @param $style 样式
 * @param $html 是否显示完整的STYLE
 */
function title_style($style, $html = 1) {
 $str = '';
 if ($html) $str = ' style="';
 $style_arr = explode(';',$style);
 if (!empty($style_arr[0])) $str .= 'color:'.$style_arr[0].';';
 if (!empty($style_arr[1])) $str .= 'font-weight:'.$style_arr[1].';';
 if ($html) $str .= '" ';
 return $str;
}
/**
 * 获取站点域名
 * @param $siteid 站点id
 */
function siteurl($siteid) {
 static $sitelist;
 return WEB_PATH;
// if(!$siteid) return WEB_PATH;
// if(empty($sitelist)) $sitelist = getcache('sitelist','commons');
// return substr($sitelist[$siteid]['domain'],0,-1);
}
/**
 * 生成上传附件验证
 * @param $args 参数
 * @param $operation 操作类型(加密解密)
 */
function upload_key($args) {
 $pc_auth_key = md5(app_base::load_config('system','auth_key').$_SERVER['HTTP_USER_AGENT']);
 $authkey = md5($args.$pc_auth_key);
 return $authkey;
}
/**
 * 文本转换为图片
 * @param string $txt 图形化文本内容
 * @param int $fonttype 无外部字体时生成文字大小,取值范围1-5
 * @param int $fontsize 引入外部字体时,字体大小
 * @param string $font 字体名称 字体请放于app\libs\data\font下
 * @param string $fontcolor 字体颜色 十六进制形式 如FFFFFF,FF0000
 */
function string2img($txt, $fonttype = 5, $fontsize = 16, $font = '', $fontcolor = 'FF0000',$transparent = '1') {
 if(empty($txt)) return false;
 if(function_exists("imagepng")) {
  $txt = urlencode(sys_auth($txt));
  $txt = '<img src="'.APP_PATH.'api.php?op=creatimg&txt='.$txt.'&f '.$version['pc_release'];
 }
}
/**
 * 运行钩子(插件使用)
 */
function runhook($method) {
 $time_start = getmicrotime();
 $data = '';
 $getpclass = FALSE;
 $hook_appid = getcache('hook','plugins');
 if(!empty($hook_appid)) {
  foreach($hook_appid as $appid => $p) {
   $pluginfilepath = CODE_PATH.'plugin'.DIRECTORY_SEPARATOR.$p.DIRECTORY_SEPARATOR.'hook.class.php';
   $getpclass = TRUE;
   include_once $pluginfilepath;
  }
  $hook_appid = array_flip($hook_appid);
  if($getpclass) {
   $pclass = new ReflectionClass('hook');
   foreach($pclass->getMethods() as $r) {
    $legalmethods[] = $r->getName();
   }
  }
  if(in_array($method,$legalmethods)) {
   foreach (get_declared_classes() as $class){
    $refclass = new ReflectionClass($class);
    if($refclass->isSubclassOf('hook')){
     if ($_method = $refclass->getMethod($method)) {
       $classname = $refclass->getName();
      if ($_method->isPublic() && $_method->isFinal()) {
       plugin_stat($hook_appid[$classname]);
       $data .= $_method->invoke(null);
      }
     }
    }
   }
  }
  return $data;
 }
}
function getmicrotime() {
 list($usec, $sec) = explode(" ",microtime());
 return ((float)$usec + (float)$sec);
}
/**
 * 插件前台模板加载
 * Enter description here ...
 * @param unknown_type $module
 * @param unknown_type $template
 * @param unknown_type $style
 */
function p_template($plugin = 'content', $template = 'index',$style='default') {
 if(!$style) $style = 'default';
 $template_cache = app_base::load_sys_class('template_cache');
 $compiledtplfile = ROOT_PATH.'caches'.DIRECTORY_SEPARATOR.'caches_template'.DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.'plugin'.DIRECTORY_SEPARATOR.$plugin.DIRECTORY_SEPARATOR.$template.'.php';
 if(!file_exists($compiledtplfile) || (file_exists(CODE_PATH.'plugin'.DIRECTORY_SEPARATOR.$plugin.DIRECTORY_SEPARATOR.'templates'.DIRECTORY_SEPARATOR.$template.'.html') && filemtime(CODE_PATH.'plugin'.DIRECTORY_SEPARATOR.$plugin.DIRECTORY_SEPARATOR.'templates'.DIRECTORY_SEPARATOR.$template.'.html') > filemtime($compiledtplfile))) {
  $template_cache->template_compile('plugin/'.$plugin, $template, 'default');
 } elseif (!file_exists(CODE_PATH.'plugin'.DIRECTORY_SEPARATOR.$plugin.DIRECTORY_SEPARATOR.'templates'.DIRECTORY_SEPARATOR.$template.'.html')) {
  showmessage('Template does not exist.'.DIRECTORY_SEPARATOR.'plugin'.DIRECTORY_SEPARATOR.$plugin.DIRECTORY_SEPARATOR.$template.'.html');
 }
 return $compiledtplfile;
}
/**
 * 读取缓存动态页面
 */
function cache_page_start() {
 $relate_url = isset($_SERVER['REQUEST_URI']) ? safe_replace($_SERVER['REQUEST_URI']) : $php_self.(isset($_SERVER['QUERY_STRING']) ? '?'.safe_replace($_SERVER['QUERY_STRING']) : $path_info);
 define('CACHE_PAGE_ID', md5($relate_url));
 $contents = getcache(CACHE_PAGE_ID, 'page_tmp/'.substr(CACHE_PAGE_ID, 0, 2));
 if($contents && intval(substr($contents, 15, 10)) > SYS_TIME) {
  echo substr($contents, 29);
  exit;
 }
 if (!defined('HTML')) define('HTML',true);
 return true;
}
/**
 * 写入缓存动态页面
 */
function cache_page($ttl = 360, $isjs = 0) {
 if($ttl == 0 || !defined('CACHE_PAGE_ID')) return false;
 $contents = ob_get_contents();
 if($isjs) $contents = format_js($contents);
 $contents = "<!--expiretime:".(SYS_TIME + $ttl)."-->\n".$contents;
 setcache(CACHE_PAGE_ID, $contents, 'page_tmp/'.substr(CACHE_PAGE_ID, 0, 2));
}
/**
 *
 * 获取远程内容
 * @param $url 接口url地址
 * @param $timeout 超时时间
 */
function pc_file_get_contents($url, $timeout=30) {
 $stream = stream_context_create(array('http' => array('timeout' => $timeout)));
 return @file_get_contents($url, 0, $stream);
}
/**
 * Function get_vid
 * 获取视频信息
 * @param int $contentid 内容ID 必须
 * @param int $catid 栏目id 取内容里面视频信息时必须
 * @param int $isspecial 是否取专题的视频信息
 */
function get_vid($contentid = 0, $catid = 0, $isspecial = 0) {
 static $categorys;
 if (!$contentid) return false;
 if (!$isspecial) {
  if (!$catid) return false;
  $contentid = intval($contentid);
  $catid = intval($catid);
  $siteid = get_siteid();
  if (!$categorys) {
   $categorys = getcache('category_content_'.$siteid, 'commons');
  }
  $modelid = $categorys[$catid]['modelid'];
  $video_content = app_base::load_model('video_content_model');
  $r = $video_content->get_one(array('contentid'=>$contentid, 'modelid'=>$modelid), 'videoid', 'listorder ASC');
  $video_store =app_base::load_model('video_store_model');
  return $video_store->get_one(array('videoid'=>$r['videoid']));
 } else {
  $special_content = app_base::load_model('special_content_model');
  $contentid = intval($contentid);
  $video_store =app_base::load_model('video_store_model');
  $r = $special_content->get_one(array('id'=>$contentid), 'videoid');
  return $video_store->get_one(array('videoid'=>$r['videoid']));
 }
}
/**
 * Function dataformat
 * 时间转换
 * @param $n INT时间
 */
 function dataformat($n) {
 $hours = floor($n/3600);
 $minite = floor($n%3600/60);
 $secend = floor($n%3600%60);
 $minite = $minite < 10 ? "0".$minite : $minite;
 $secend = $secend < 10 ? "0".$secend : $secend;
 if($n >= 3600){
  return $hours.":".$minite.":".$secend;
 }else{
  return $minite.":".$secend;
 }
 }
 function httpResponse($status, $msg=''){
  $m = app_base::load_model('category_model');
  $CATEGORYS = $m->select(array('parentid'=>0),'*','','listorder');
  include CODE_PATH . 'libs'.DIRECTORY_SEPARATOR.'data'.DIRECTORY_SEPARATOR.'http'.DIRECTORY_SEPARATOR.$status.'.php';
 }
 function array_change_key_case_recursive($arr)
 {
  if(! $arr || !is_array($arr))return array();
 return array_map(function($item){
  if(is_array($item))
   $item = array_change_key_case_recursive($item);
  return $item;
 },array_change_key_case($arr));
 }
 function visitauth(){
  $vtime = time();
 $vsign = md5("cuichuande@ideadata.com.cn#$%" . $vtime);
 return "tm={$vtime}&sn={$vsign}";
 }
?>

希望本文所述对大家PHP程序设计有所帮助。

延伸 · 阅读

精彩推荐