-
Notifications
You must be signed in to change notification settings - Fork 2k
/
Common.php
1513 lines (1363 loc) · 54.1 KB
/
Common.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
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
namespace {
use Typecho\I18n;
/**
* @deprecated use json_encode and json_decode directly
*/
class Json
{
/**
* @param $value
* @return string
*/
public static function encode($value): string
{
return json_encode($value);
}
/**
* @param string $string
* @param bool $assoc
* @return mixed
*/
public static function decode(string $string, bool $assoc = false)
{
return json_decode($string, $assoc);
}
}
/**
* I18n function
*
* @param string $string 需要翻译的文字
* @param mixed ...$args 参数
*
* @return string
*/
function _t(string $string, ...$args): string
{
if (empty($args)) {
return I18n::translate($string);
} else {
return vsprintf(I18n::translate($string), $args);
}
}
/**
* I18n function, translate and echo
*
* @param string $string 需要翻译的文字
* @param mixed ...$args 参数
*/
function _e(string $string, ...$args)
{
array_unshift($args, $string);
echo call_user_func_array('_t', $args);
}
/**
* 针对复数形式的翻译函数
*
* @param string $single 单数形式的翻译
* @param string $plural 复数形式的翻译
* @param integer $number 数字
*
* @return string
*/
function _n(string $single, string $plural, int $number): string
{
return str_replace('%d', $number, I18n::ngettext($single, $plural, $number));
}
}
namespace Typecho {
const PLUGIN_NAMESPACE = 'TypechoPlugin';
spl_autoload_register(function (string $className) {
$isDefinedAlias = defined('__TYPECHO_CLASS_ALIASES__');
$isNamespace = strpos($className, '\\') !== false;
$isAlias = $isDefinedAlias && isset(__TYPECHO_CLASS_ALIASES__[$className]);
$isPlugin = false;
// detect if class is predefined
if ($isNamespace) {
$isPlugin = strpos(ltrim($className, '\\'), PLUGIN_NAMESPACE . '\\') !== false;
if ($isPlugin) {
$realClassName = substr($className, strlen(PLUGIN_NAMESPACE) + 1);
$alias = Common::nativeClassName($realClassName);
$path = str_replace('\\', '/', $realClassName);
} else {
if ($isDefinedAlias) {
$alias = array_search('\\' . ltrim($className, '\\'), __TYPECHO_CLASS_ALIASES__);
}
$alias = empty($alias) ? Common::nativeClassName($className) : $alias;
$path = str_replace('\\', '/', $className);
}
} elseif (strpos($className, '_') !== false || $isAlias) {
$isPlugin = !$isAlias && !preg_match("/^(Typecho|Widget|IXR)_/", $className);
if ($isPlugin) {
$alias = '\\TypechoPlugin\\' . str_replace('_', '\\', $className);
$path = str_replace('_', '/', $className);
} else {
$alias = $isAlias ? __TYPECHO_CLASS_ALIASES__[$className]
: '\\' . str_replace('_', '\\', $className);
$path = str_replace('\\', '/', $alias);
}
} else {
$path = $className;
}
if (
isset($alias)
&& (class_exists($alias, false)
|| interface_exists($alias, false)
|| trait_exists($alias, false))
) {
class_alias($alias, $className, false);
return;
}
// load class file
$path .= '.php';
$defaultFile = __TYPECHO_ROOT_DIR__ . '/var/' . $path;
if (file_exists($defaultFile) && !$isPlugin) {
include_once $defaultFile;
} else {
$pluginFile = __TYPECHO_ROOT_DIR__ . __TYPECHO_PLUGIN_DIR__ . '/' . $path;
if (file_exists($pluginFile)) {
include_once $pluginFile;
} else {
return;
}
}
if (isset($alias)) {
$classLoaded = class_exists($className, false)
|| interface_exists($className, false)
|| trait_exists($className, false);
$aliasLoaded = class_exists($alias, false)
|| interface_exists($alias, false)
|| trait_exists($alias, false);
if ($classLoaded && !$aliasLoaded) {
class_alias($className, $alias);
} elseif ($aliasLoaded && !$classLoaded) {
class_alias($alias, $className);
}
}
});
/**
* Typecho公用方法
*
* @category typecho
* @package Common
* @copyright Copyright (c) 2008 Typecho team (http://www.typecho.org)
* @license GNU General Public License 2.0
*/
class Common
{
/** 程序版本 */
public const VERSION = '1.3.0';
/**
* 将路径转化为链接
*
* @access public
*
* @param string|null $path 路径
* @param string|null $prefix 前缀
*
* @return string
*/
public static function url(?string $path, ?string $prefix): string
{
$path = $path ?? '';
$path = (0 === strpos($path, './')) ? substr($path, 2) : $path;
return rtrim($prefix ?? '', '/') . '/'
. str_replace('//', '/', ltrim($path, '/'));
}
/**
* 程序初始化方法
*
* @access public
* @return void
*/
public static function init()
{
// init response
Response::getInstance()->enableAutoSendHeaders(false);
ob_start(function ($content) {
Response::getInstance()->sendHeaders();
return $content;
});
/** 设置异常截获函数 */
set_exception_handler(function (\Throwable $exception) {
echo '<pre><code>';
echo '<h1>' . htmlspecialchars($exception->getMessage()) . '</h1>';
echo htmlspecialchars($exception->__toString());
echo '</code></pre>';
exit;
});
}
/**
* 输出错误页面
*
* @param \Throwable $exception 错误信息
*/
public static function error(\Throwable $exception)
{
$code = $exception->getCode() ?: 500;
$message = $exception->getMessage();
if ($exception instanceof \Typecho\Db\Exception) {
$code = 500;
//覆盖原始错误信息
$message = 'Database Server Error';
if ($exception instanceof \Typecho\Db\Adapter\ConnectionException) {
$code = 503;
$message = 'Error establishing a database connection';
} elseif ($exception instanceof \Typecho\Db\Adapter\SQLException) {
$message = 'Database Query Error';
}
} elseif ($exception instanceof \Typecho\Widget\Exception) {
$message = $exception->getMessage();
} else {
$message = 'Server Error';
}
/** 设置http code */
if (is_numeric($code) && $code > 200) {
Response::getInstance()->setStatus($code);
}
$message = nl2br($message);
if (defined('__TYPECHO_EXCEPTION_FILE__')) {
require_once __TYPECHO_EXCEPTION_FILE__;
} else {
echo
<<<EOF
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{$code}</title>
<style>
html {
padding: 50px 10px;
font-size: 16px;
line-height: 1.4;
color: #666;
background: #F6F6F3;
-webkit-text-size-adjust: 100%;
-ms-text-size-adjust: 100%;
}
html,
input { font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; }
body {
max-width: 500px;
_width: 500px;
padding: 30px 20px;
margin: 0 auto;
background: #FFF;
}
ul {
padding: 0 0 0 40px;
}
.container {
max-width: 380px;
_width: 380px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="container">
{$message}
</div>
</body>
</html>
EOF;
}
exit(1);
}
/**
* @param string $className 类名
* @return boolean
* @deprecated
*/
public static function isAvailableClass(string $className): bool
{
return class_exists($className);
}
/**
* @param array $value
* @param $key
*
* @return array
* @deprecated use array_column instead
*
*/
public static function arrayFlatten(array $value, $key): array
{
return array_column($value, $key);
}
/**
* @param string $className
* @return string
*/
public static function nativeClassName(string $className): string
{
return trim(str_replace('\\', '_', $className), '_');
}
/**
* 根据count数目来输出字符
* <code>
* echo splitByCount(20, 10, 20, 30, 40, 50);
* </code>
*
* @param int $count
* @param int ...$sizes
* @return int
*/
public static function splitByCount(int $count, int ...$sizes): int
{
foreach ($sizes as $size) {
if ($count < $size) {
return $size;
}
}
return 0;
}
/**
* 自闭合html修复函数
* 使用方法:
* <code>
* $input = '这是一段被截断的html文本<a href="#"';
* echo Common::fixHtml($input);
* //output: 这是一段被截断的html文本
* </code>
*
* @param string|null $string 需要修复处理的字符串
* @return string|null
*/
public static function fixHtml(?string $string): ?string
{
//关闭自闭合标签
$startPos = strrpos($string, "<");
if (false == $startPos) {
return $string;
}
$trimString = substr($string, $startPos);
if (false === strpos($trimString, ">")) {
$string = substr($string, 0, $startPos);
}
//非自闭合html标签列表
preg_match_all("/<([_0-9a-zA-Z-:]+)\s*([^>]*)>/is", $string, $startTags);
preg_match_all("/<\/([_0-9a-zA-Z-:]+)>/is", $string, $closeTags);
if (!empty($startTags[1]) && is_array($startTags[1])) {
krsort($startTags[1]);
$closeTagsIsArray = is_array($closeTags[1]);
foreach ($startTags[1] as $key => $tag) {
$attrLength = strlen($startTags[2][$key]);
if ($attrLength > 0 && "/" == trim($startTags[2][$key][$attrLength - 1])) {
continue;
}
// 白名单
if (
preg_match(
"/^(area|base|br|col|embed|hr|img|input|keygen|link|meta|param|source|track|wbr)$/i",
$tag
)
) {
continue;
}
if (!empty($closeTags[1]) && $closeTagsIsArray) {
if (false !== ($index = array_search($tag, $closeTags[1]))) {
unset($closeTags[1][$index]);
continue;
}
}
$string .= "</{$tag}>";
}
}
return preg_replace("/<br\s*\/>\s*<\/p>/is", '</p>', $string);
}
/**
* 去掉字符串中的html标签
* 使用方法:
* <code>
* $input = '<a href="http://test/test.php" title="example">hello</a>';
* $output = Common::stripTags($input, <a href="">);
* echo $output;
* //display: '<a href="http://test/test.php">hello</a>'
* </code>
*
* @param string|null $html 需要处理的字符串
* @param string|null $allowableTags 需要忽略的html标签
* @return string
*/
public static function stripTags(?string $html, ?string $allowableTags = null): string
{
$normalizeTags = '';
$allowableAttributes = [];
if (!empty($allowableTags) && preg_match_all("/<([_a-z0-9-]+)([^>]*)>/is", $allowableTags, $tags)) {
$normalizeTags = '<' . implode('><', array_map('strtolower', $tags[1])) . '>';
$attributes = array_map('trim', $tags[2]);
foreach ($attributes as $key => $val) {
$allowableAttributes[strtolower($tags[1][$key])] =
array_map('strtolower', array_keys(self::parseAttrs($val)));
}
}
$html = strip_tags($html, $normalizeTags);
return preg_replace_callback(
"/<([_a-z0-9-]+)(\s+[^>]+)?>/is",
function ($matches) use ($allowableAttributes) {
if (!isset($matches[2])) {
return $matches[0];
}
$str = trim($matches[2]);
if (empty($str)) {
return $matches[0];
}
$attrs = self::parseAttrs($str);
$parsedAttrs = [];
$tag = strtolower($matches[1]);
foreach ($attrs as $key => $val) {
if (in_array($key, $allowableAttributes[$tag])) {
$parsedAttrs[] = " {$key}" . (empty($val) ? '' : "={$val}");
}
}
return '<' . $tag . implode('', $parsedAttrs) . '>';
},
$html
);
}
/**
* 过滤用于搜索的字符串
*
* @access public
*
* @param string|null $query 搜索字符串
*
* @return string
*/
public static function filterSearchQuery(?string $query): string
{
return isset($query) ? str_replace('-', ' ', self::slugName($query) ?? '') : '';
}
/**
* 生成缩略名
*
* @access public
*
* @param string|null $str 需要生成缩略名的字符串
* @param string $default 默认的缩略名
* @param integer $maxLength 缩略名最大长度
*
* @return string
*/
public static function slugName(?string $str, string $default = '', int $maxLength = 128): string
{
$str = trim($str ?? '');
if (!strlen($str)) {
return $default;
}
mb_regex_encoding('UTF-8');
mb_ereg_search_init($str, "[\w" . preg_quote('_-') . "]+");
$result = mb_ereg_search();
$return = '';
if ($result) {
$regs = mb_ereg_search_getregs();
$pos = 0;
do {
$return .= ($pos > 0 ? '-' : '') . $regs[0];
$pos++;
} while ($regs = mb_ereg_search_regs());
}
$str = trim($return, '-_');
$str = !strlen($str) ? $default : $str;
return substr($str, 0, $maxLength);
}
/**
* 将url中的非法字符串
*
* @param string $url 需要过滤的url
*
* @return string
*/
public static function safeUrl($url)
{
//~ 针对location的xss过滤, 因为其特殊性无法使用removeXSS函数
//~ fix issue 66
$params = parse_url(str_replace(["\r", "\n", "\t", ' '], '', $url));
/** 禁止非法的协议跳转 */
if (isset($params['scheme'])) {
if (!in_array($params['scheme'], ['http', 'https'])) {
return '/';
}
}
$params = array_map(function ($string) {
$string = str_replace(['%0d', '%0a'], '', strip_tags($string));
return preg_replace([
"/\(\s*([\"'])/i", //函数开头
"/([\"'])\s*\)/i", //函数结尾
], '', $string);
}, $params);
return self::buildUrl($params);
}
/**
* 根据parse_url的结果重新组合url
*
* @param array $params 解析后的参数
*
* @return string
*/
public static function buildUrl(array $params): string
{
return (isset($params['scheme']) ? $params['scheme'] . '://' : null)
. (isset($params['user']) ? $params['user']
. (isset($params['pass']) ? ':' . $params['pass'] : null) . '@' : null)
. ($params['host'] ?? null)
. (isset($params['port']) ? ':' . $params['port'] : null)
. ($params['path'] ?? null)
. (isset($params['query']) ? '?' . $params['query'] : null)
. (isset($params['fragment']) ? '#' . $params['fragment'] : null);
}
/**
* 处理XSS跨站攻击的过滤函数
*
* @param string|null $val 需要处理的字符串
* @return string
*/
public static function removeXSS(?string $val): string
{
// 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);
// @ @ 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 = ['javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script',
'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base'];
$ra2 = [
'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;
}
/**
* 宽字符串截字函数
*
* @param string $str 需要截取的字符串
* @param integer $start 开始截取的位置
* @param integer $length 需要截取的长度
* @param string $trim 截取后的截断标示符
*
* @return string
*/
public static function subStr(string $str, int $start, int $length, string $trim = "..."): string
{
if (!strlen($str)) {
return '';
}
$iLength = self::strLen($str) - $start;
$tLength = $length < $iLength ? ($length - self::strLen($trim)) : $length;
$str = mb_substr($str, $start, $tLength, 'UTF-8');
return $length < $iLength ? ($str . $trim) : $str;
}
/**
* 判断两个字符串是否为空并依次返回
*
* @param string|null $a
* @param string|null $b
* @return string|null
*/
public static function strBy(?string $a, ?string $b = null): ?string
{
return isset($a) && $a !== '' ? $a : $b;
}
/**
* 获取宽字符串长度函数
*
* @param string $str 需要获取长度的字符串
* @return integer
*/
public static function strLen(string $str): int
{
return mb_strlen($str, 'UTF-8');
}
/**
* 判断hash值是否相等
*
* @access public
*
* @param string|null $from 源字符串
* @param string|null $to 目标字符串
*
* @return boolean
*/
public static function hashValidate(?string $from, ?string $to): bool
{
if (!isset($from) || !isset($to)) {
return false;
}
if ('$T$' == substr($to, 0, 3)) {
$salt = substr($to, 3, 9);
return self::hash($from, $salt) === $to;
} else {
return md5($from) === $to;
}
}
/**
* 对字符串进行hash加密
*
* @access public
*
* @param string|null $string 需要hash的字符串
* @param string|null $salt 扰码
*
* @return string
*/
public static function hash(?string $string, ?string $salt = null): string
{
if (!isset($string)) {
return '';
}
/** 生成随机字符串 */
$salt = empty($salt) ? self::randString(9) : $salt;
$length = strlen($string);
if ($length == 0) {
return '';
}
$hash = '';
$last = ord($string[$length - 1]);
$pos = 0;
/** 判断扰码长度 */
if (strlen($salt) != 9) {
/** 如果不是9直接返回 */
return '';
}
while ($pos < $length) {
$asc = ord($string[$pos]);
$last = ($last * ord($salt[($last % $asc) % 9]) + $asc) % 95 + 32;
$hash .= chr($last);
$pos++;
}
return '$T$' . $salt . md5($hash);
}
/**
* 生成随机字符串
*
* @access public
*
* @param integer $length 字符串长度
* @param boolean $specialChars 是否有特殊字符
*
* @return string
*/
public static function randString(int $length, bool $specialChars = false): string
{
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
if ($specialChars) {
$chars .= '!@#$%^&*()';
}
$result = '';
$max = strlen($chars) - 1;
for ($i = 0; $i < $length; $i++) {
$result .= $chars[rand(0, $max)];
}
return $result;
}
/**
* 创建一个会过期的Token
*
* @param $secret
* @return string
*/
public static function timeToken($secret): string
{
return sha1($secret . '&' . time());
}
/**
* 在时间范围内验证token
*
* @param $token
* @param $secret
* @param int $timeout
* @return bool
*/
public static function timeTokenValidate($token, $secret, int $timeout = 5): bool
{
$now = time();
$from = $now - $timeout;
for ($i = $now; $i >= $from; $i--) {
if (sha1($secret . '&' . $i) == $token) {
return true;
}
}
return false;
}
/**
* 获取gravatar头像地址
*
* @param string|null $mail
* @param int $size
* @param string|null $rating
* @param string|null $default
* @param bool $isSecure
*
* @return string
*/
public static function gravatarUrl(
?string $mail,
int $size,
?string $rating = null,
?string $default = null,
bool $isSecure = true
): string {
if (defined('__TYPECHO_GRAVATAR_PREFIX__')) {
$url = __TYPECHO_GRAVATAR_PREFIX__;
} else {
$url = $isSecure ? 'https://secure.gravatar.com' : 'http://www.gravatar.com';
$url .= '/avatar/';
}
if (!empty($mail)) {
$url .= md5(strtolower(trim($mail)));
}
$url .= '?s=' . $size;
if (isset($rating)) {
$url .= '&r=' . $rating;
}
if (isset($default)) {
$url .= '&d=' . $default;
}
return $url;
}
/**
* 给javascript赋值加入扰码设计
*
* @param string $value
*
* @return string
*/
public static function shuffleScriptVar(string $value): string
{
$length = strlen($value);
$max = 3;
$offset = 0;
$result = [];
$cut = [];
while ($length > 0) {
$len = rand(0, min($max, $length));
$rand = "'" . self::randString(rand(1, $max)) . "'";
if ($len > 0) {
$val = "'" . substr($value, $offset, $len) . "'";
$result[] = rand(0, 1) ? "//{$rand}\n{$val}" : "{$val}//{$rand}\n";
} else {
if (rand(0, 1)) {
$result[] = rand(0, 1) ? "''///*{$rand}*/{$rand}\n" : "/* {$rand}//{$rand} */''";
} else {
$result[] = rand(0, 1) ? "//{$rand}\n{$rand}" : "{$rand}//{$rand}\n";
$cut[] = [$offset, strlen($rand) - 2 + $offset];
}
}
$offset += $len;
$length -= $len;
}
$name = '_' . self::randString(rand(3, 7));
$cutName = '_' . self::randString(rand(3, 7));
$var = implode('+', $result);
$cutVar = json_encode($cut);
return "(function () {
var {$name} = {$var}, {$cutName} = {$cutVar};
for (var i = 0; i < {$cutName}.length; i ++) {
{$name} = {$name}.substring(0, {$cutName}[i][0]) + {$name}.substring({$cutName}[i][1]);
}
return {$name};
})();";
}
/**
* 创建备份文件缓冲
*
* @param string $type
* @param string $header
* @param string $body
*
* @return string
*/
public static function buildBackupBuffer(string $type, string $header, string $body): string
{
$buffer = '';
$buffer .= pack('vvV', $type, strlen($header), strlen($body));
$buffer .= $header . $body;
$buffer .= md5($buffer);
return $buffer;
}
/**
* 从备份文件中解压
*
* @param resource $fp
* @param int|null $offset
* @param string $version
* @return array|bool
*/
public static function extractBackupBuffer($fp, ?int &$offset, string $version)
{
$realMetaLen = $version == 'FILE' ? 6 : 8;
$meta = fread($fp, $realMetaLen);
$offset += $realMetaLen;
$metaLen = strlen($meta);
if (false === $meta || $metaLen != $realMetaLen) {
return false;
}
[$type, $headerLen, $bodyLen]
= array_values(unpack($version == 'FILE' ? 'v3' : 'v1type/v1headerLen/V1bodyLen', $meta));
$header = @fread($fp, $headerLen);
$offset += $headerLen;
if (false === $header || strlen($header) != $headerLen) {
return false;
}
if ('FILE' == $version) {
$bodyLen = array_reduce(json_decode($header, true), function ($carry, $len) {
return null === $len ? $carry : $carry + $len;
}, 0);
}
$body = @fread($fp, $bodyLen);
$offset += $bodyLen;
if (false === $body || strlen($body) != $bodyLen) {
return false;
}
$md5 = @fread($fp, 32);
$offset += 32;
if (false === $md5 || $md5 != md5($meta . $header . $body)) {
return false;
}
return [$type, $header, $body];
}
/**
* 检查是否是一个安全的主机名
*
* @param string $host
* @return bool