common.php
20.1 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
<?php
// 公共助手函数
if (!function_exists('__')) {
/**
* 获取语言变量值
* @param string $name 语言变量名
* @param array $vars 动态变量值
* @param string $lang 语言
* @return mixed
*/
function __($name, $vars = [], $lang = '')
{
if (is_numeric($name) || !$name) {
return $name;
}
if (!is_array($vars)) {
$vars = func_get_args();
array_shift($vars);
$lang = '';
}
return \think\Lang::get($name, $vars, $lang);
}
}
if (!function_exists('format_bytes')) {
/**
* 将字节转换为可读文本
* @param int $size 大小
* @param string $delimiter 分隔符
* @return string
*/
function format_bytes($size, $delimiter = '')
{
$units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
for ($i = 0; $size >= 1024 && $i < 6; $i++) {
$size /= 1024;
}
return round($size, 2) . $delimiter . $units[$i];
}
}
if (!function_exists('datetime')) {
/**
* 将时间戳转换为日期时间
* @param int $time 时间戳
* @param string $format 日期时间格式
* @return string
*/
function datetime($time, $format = 'Y-m-d H:i:s')
{
$time = is_numeric($time) ? $time : strtotime($time);
return date($format, $time);
}
}
if (!function_exists('human_date')) {
/**
* 获取语义化时间
* @param int $time 时间
* @param int $local 本地时间
* @return string
*/
function human_date($time, $local = null)
{
return \fast\Date::human($time, $local);
}
}
if (!function_exists('cdnurl')) {
/**
* 获取上传资源的CDN的地址
* @param string $url 资源相对地址
* @param boolean $domain 是否显示域名 或者直接传入域名
* @return string
*/
function cdnurl($url, $domain = false)
{
$regex = "/^((?:[a-z]+:)?\/\/|data:image\/)(.*)/i";
$url = preg_match($regex, $url) ? $url : \think\Config::get('upload.cdnurl') . $url;
if ($domain && !preg_match($regex, $url)) {
$domain = is_bool($domain) ? request()->domain() : $domain;
$url = $domain . $url;
}
return $url;
}
}
if (!function_exists('is_really_writable')) {
/**
* 判断文件或文件夹是否可写
* @param string $file 文件或目录
* @return bool
*/
function is_really_writable($file)
{
if (DIRECTORY_SEPARATOR === '/') {
return is_writable($file);
}
if (is_dir($file)) {
$file = rtrim($file, '/') . '/' . md5(mt_rand());
if (($fp = @fopen($file, 'ab')) === false) {
return false;
}
fclose($fp);
@chmod($file, 0777);
@unlink($file);
return true;
} elseif (!is_file($file) or ($fp = @fopen($file, 'ab')) === false) {
return false;
}
fclose($fp);
return true;
}
}
if (!function_exists('rmdirs')) {
/**
* 删除文件夹
* @param string $dirname 目录
* @param bool $withself 是否删除自身
* @return boolean
*/
function rmdirs($dirname, $withself = true)
{
if (!is_dir($dirname)) {
return false;
}
$files = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($dirname, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::CHILD_FIRST
);
foreach ($files as $fileinfo) {
$todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
$todo($fileinfo->getRealPath());
}
if ($withself) {
@rmdir($dirname);
}
return true;
}
}
if (!function_exists('copydirs')) {
/**
* 复制文件夹
* @param string $source 源文件夹
* @param string $dest 目标文件夹
*/
function copydirs($source, $dest)
{
if (!is_dir($dest)) {
mkdir($dest, 0755, true);
}
foreach (
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS),
RecursiveIteratorIterator::SELF_FIRST
) as $item
) {
if ($item->isDir()) {
$sontDir = $dest . DS . $iterator->getSubPathName();
if (!is_dir($sontDir)) {
mkdir($sontDir, 0755, true);
}
} else {
copy($item, $dest . DS . $iterator->getSubPathName());
}
}
}
}
if (!function_exists('mb_ucfirst')) {
function mb_ucfirst($string)
{
return mb_strtoupper(mb_substr($string, 0, 1)) . mb_strtolower(mb_substr($string, 1));
}
}
if (!function_exists('addtion')) {
/**
* 附加关联字段数据
* @param array $items 数据列表
* @param mixed $fields 渲染的来源字段
* @return array
*/
function addtion($items, $fields)
{
if (!$items || !$fields) {
return $items;
}
$fieldsArr = [];
if (!is_array($fields)) {
$arr = explode(',', $fields);
foreach ($arr as $k => $v) {
$fieldsArr[$v] = ['field' => $v];
}
} else {
foreach ($fields as $k => $v) {
if (is_array($v)) {
$v['field'] = isset($v['field']) ? $v['field'] : $k;
} else {
$v = ['field' => $v];
}
$fieldsArr[$v['field']] = $v;
}
}
foreach ($fieldsArr as $k => &$v) {
$v = is_array($v) ? $v : ['field' => $v];
$v['display'] = isset($v['display']) ? $v['display'] : str_replace(['_ids', '_id'], ['_names', '_name'], $v['field']);
$v['primary'] = isset($v['primary']) ? $v['primary'] : '';
$v['column'] = isset($v['column']) ? $v['column'] : 'name';
$v['model'] = isset($v['model']) ? $v['model'] : '';
$v['table'] = isset($v['table']) ? $v['table'] : '';
$v['name'] = isset($v['name']) ? $v['name'] : str_replace(['_ids', '_id'], '', $v['field']);
}
unset($v);
$ids = [];
$fields = array_keys($fieldsArr);
foreach ($items as $k => $v) {
foreach ($fields as $m => $n) {
if (isset($v[$n])) {
$ids[$n] = array_merge(isset($ids[$n]) && is_array($ids[$n]) ? $ids[$n] : [], explode(',', $v[$n]));
}
}
}
$result = [];
foreach ($fieldsArr as $k => $v) {
if ($v['model']) {
$model = new $v['model'];
} else {
$model = $v['name'] ? \think\Db::name($v['name']) : \think\Db::table($v['table']);
}
$primary = $v['primary'] ? $v['primary'] : $model->getPk();
$result[$v['field']] = $model->where($primary, 'in', $ids[$v['field']])->column("{$primary},{$v['column']}");
}
foreach ($items as $k => &$v) {
foreach ($fields as $m => $n) {
if (isset($v[$n])) {
$curr = array_flip(explode(',', $v[$n]));
$v[$fieldsArr[$n]['display']] = implode(',', array_intersect_key($result[$n], $curr));
}
}
}
return $items;
}
}
if (!function_exists('var_export_short')) {
/**
* 返回打印数组结构
* @param string $var 数组
* @param string $indent 缩进字符
* @return string
*/
function var_export_short($var, $indent = "")
{
switch (gettype($var)) {
case "string":
return '"' . addcslashes($var, "\\\$\"\r\n\t\v\f") . '"';
case "array":
$indexed = array_keys($var) === range(0, count($var) - 1);
$r = [];
foreach ($var as $key => $value) {
$r[] = "$indent "
. ($indexed ? "" : var_export_short($key) . " => ")
. var_export_short($value, "$indent ");
}
return "[\n" . implode(",\n", $r) . "\n" . $indent . "]";
case "boolean":
return $var ? "TRUE" : "FALSE";
default:
return var_export($var, true);
}
}
}
if (!function_exists('letter_avatar')) {
/**
* 首字母头像
* @param $text
* @return string
*/
function letter_avatar($text)
{
$total = unpack('L', hash('adler32', $text, true))[1];
$hue = $total % 360;
list($r, $g, $b) = hsv2rgb($hue / 360, 0.3, 0.9);
$bg = "rgb({$r},{$g},{$b})";
$color = "#ffffff";
$first = mb_strtoupper(mb_substr($text, 0, 1));
$src = base64_encode('<svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="100" width="100"><rect fill="' . $bg . '" x="0" y="0" width="100" height="100"></rect><text x="50" y="50" font-size="50" text-copy="fast" fill="' . $color . '" text-anchor="middle" text-rights="admin" alignment-baseline="central">' . $first . '</text></svg>');
$value = 'data:image/svg+xml;base64,' . $src;
return $value;
}
}
if (!function_exists('hsv2rgb')) {
function hsv2rgb($h, $s, $v)
{
$r = $g = $b = 0;
$i = floor($h * 6);
$f = $h * 6 - $i;
$p = $v * (1 - $s);
$q = $v * (1 - $f * $s);
$t = $v * (1 - (1 - $f) * $s);
switch ($i % 6) {
case 0:
$r = $v;
$g = $t;
$b = $p;
break;
case 1:
$r = $q;
$g = $v;
$b = $p;
break;
case 2:
$r = $p;
$g = $v;
$b = $t;
break;
case 3:
$r = $p;
$g = $q;
$b = $v;
break;
case 4:
$r = $t;
$g = $p;
$b = $v;
break;
case 5:
$r = $v;
$g = $p;
$b = $q;
break;
}
return [
floor($r * 255),
floor($g * 255),
floor($b * 255)
];
}
}
if (!function_exists('createNoncestr')) {
/**
* 作用:产生随机字符串,不长于32位
*/
function createNoncestr($length = 32)
{
// $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
$chars = "abcdef0123456789";
$str = "";
for ($i = 0; $i < $length; $i++) {
$str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
}
return $str;
}
}
if (!function_exists('createNoncestrInt')) {
/**
* 作用:产生随机整数字符串,不长于32位
*/
function createNoncestrInt($length = 32)
{
// $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
$chars = "0123456789";
$str = "";
for ($i = 0; $i < $length; $i++) {
$str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
}
return $str;
}
}
if (!function_exists('reverseChar')) {
/**
* 将一个字符按比特位进行反转 eg: 65 (01000001) --> 130(10000010)
* @param $char
* @return $char
*/
function reverseChar($char)
{
$byte = ord($char);
$tmp = 0;
for ($i = 0; $i < 8; ++$i) {
if ($byte & (1 << $i)) {
$tmp |= (1 << (7 - $i));
}
}
return chr($tmp);
}
}
if (!function_exists('reverseString')) {
/**
* 将一个字节流按比特位反转 eg: 'AB'(01000001 01000010) --> '\x42\x82'(01000010 10000010)
* @param $str
*/
function reverseString($str)
{
$m = 0;
$n = strlen($str) - 1;
while ($m <= $n) {
if ($m == $n) {
$str{$m} = reverseChar($str{$m});
break;
}
$ord1 = reverseChar($str{$m});
$ord2 = reverseChar($str{$n});
$str{$m} = $ord2;
$str{$n} = $ord1;
$m++;
$n--;
}
return $str;
}
}
if (!function_exists('crc16')) {
/**
* @param string $str 待校验字符串
* @param int $polynomial 二项式
* @param int $initValue 初始值
* @param int $xOrValue 输出结果前异或的值
* @param bool $inputReverse 输入字符串是否每个字节按比特位反转
* @param bool $outputReverse 输出是否整体按比特位反转
* @return int
*/
function crc16($str, $polynomial = 0x8005, $initValue = 0xffff, $xOrValue = 0, $inputReverse = true, $outputReverse = true)
{
$crc = $initValue;
for ($i = 0; $i < strlen($str); $i++) {
if ($inputReverse) {
// 输入数据每个字节按比特位逆转
$c = ord(reverseChar($str{$i}));
} else {
$c = ord($str{$i});
}
$crc ^= ($c << 8);
for ($j = 0; $j < 8; ++$j) {
if ($crc & 0x8000) {
$crc = (($crc << 1) & 0xffff) ^ $polynomial;
} else {
$crc = ($crc << 1) & 0xffff;
}
}
}
if ($outputReverse) {
// 把低地址存低位,即采用小端法将整数转换为字符串
$ret = pack('cc', $crc & 0xff, ($crc >> 8) & 0xff);
// 输出结果按比特位逆转整个字符串
$ret = reverseString($ret);
// 再把结果按小端法重新转换成整数
$arr = unpack('vshort', $ret);
$crc = $arr['short'];
}
return $crc ^ $xOrValue;
}
}
if (!function_exists('jinzhih_1')) {
//2、8、16、36、62进制转10进制
function jinzhih_1($zifu, $jinzhi)
{
$shu = 0;
for ($i = 0; $i <= strlen($zifu) - 1; $i++) {
$linshi = substr($zifu, $i, 1);
switch ($jinzhi) {
case 2:
$shu = bindec($zifu);
$i = strlen($zifu) + 1;
break;
case 8:
$shu = octdec($zifu);
$i = strlen($zifu) + 1;
break;
case 16:
$shu = hexdec($zifu);
$i = strlen($zifu) + 1;
break;
case 36:
if (ord($linshi) <= 57) {
$shu += (ord($linshi) - 48) * pow($jinzhi, strlen($zifu) - $i - 1);
} else {
$shu = $shu + (ord($linshi) - 55) * pow($jinzhi, strlen($zifu) - $i - 1);
}
break;
case 62:
if (ord($linshi) <= 57) {
$shu += $linshi * pow($jinzhi, strlen($zifu) - $i - 1);
} elseif ((ord($linshi) >= 65) && (ord($linshi) <= 90)) {
$shu += (ord($linshi) - 55) * pow($jinzhi, strlen($zifu) - $i - 1);
} else {
$shu += (ord($linshi) - 61) * pow($jinzhi, strlen($zifu) - $i - 1);
}
break;
}
}
return $shu;
}
}
if (!function_exists('getAddress')) {
function getAddress($position)
{
$position = explode('E',str_replace('N',"", $position));
$lat = $position[0];//经度
$lng = $position[1];//纬度
$key = "SINBZ-7NG66-W4SSS-MEUYB-ZHVTV-IDFQN";
$url = "http://apis.map.qq.com/ws/geocoder/v1/?location=$lat,$lng&key=$key";
$result = http_get($url);
$data = json_decode($result,true);
if($data['status'] != 0){
return $data['message'];
}
return $data['result']['address'];
}
}
if(!function_exists('httpGet')){
function http_get($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
$result = curl_exec($ch);
// grab URL, and print
if(curl_errno($ch)){
print curl_error($ch);
}
curl_close($ch);
return $result;
}
}
if (!function_exists('RemoveXSS')) {
function RemoveXSS($val)
{
// remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed
// this prevents some character re-spacing such as <java\0script>
// note that you have to handle splits with \n, \r, and \t later since they *are* allowed in some inputs
$val = preg_replace('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/', '', $val);
// straight replacements, the user should never need these since they're normal characters
// this prevents like <IMG SRC=@avascript:alert('XSS')>
$search = 'abcdefghijklmnopqrstuvwxyz';
$search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$search .= '1234567890!@#$%^&*()';
$search .= '~`";:?+/={}[]-_|\'\\';
for ($i = 0; $i < strlen($search); $i++) {
// ;? matches the ;, which is optional
// 0{0,7} matches any padded zeros, which are optional and go up to 8 chars
// @ @ search for the hex values
$val = preg_replace('/(&#[xX]0{0,8}' . dechex(ord($search[$i])) . ';?)/i', $search[$i], $val); // with a ;
// @ @ 0{0,7} matches '0' zero to seven times
$val = preg_replace('/(�{0,8}' . ord($search[$i]) . ';?)/', $search[$i], $val); // with a ;
}
// now the only remaining whitespace attacks are \t, \n, and \r
$ra1 = Array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');
$ra2 = 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');
$ra = array_merge($ra1, $ra2);
$found = true; // keep replacing as long as the previous round replaced something
while ($found == true) {
$val_before = $val;
for ($i = 0; $i < sizeof($ra); $i++) {
$pattern = '/';
for ($j = 0; $j < strlen($ra[$i]); $j++) {
if ($j > 0) {
$pattern .= '(';
$pattern .= '(&#[xX]0{0,8}([9ab]);)';
$pattern .= '|';
$pattern .= '|(�{0,8}([9|10|13]);)';
$pattern .= ')*';
}
$pattern .= $ra[$i][$j];
}
$pattern .= '/i';
$replacement = substr($ra[$i], 0, 2) . '<x>' . substr($ra[$i], 2); // add in <> to nerf the tag
$val = preg_replace($pattern, $replacement, $val); // filter out the hex tags
if ($val_before == $val) {
// no replacements were made, so exit the loop
$found = false;
}
}
}
return $val;
}
}