整理了一些常用自定义函数

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
<?php
/**
* --------------------------------------------------------------------------
* 系统通用函数类
*
* --------------------------------------------------------------------------
*/

class General
{

/**
* 验证邮箱
*
* @static
* @access public
* @param string $email 邮箱
* @return int
*/
public static function validateEmail($email)
{
$pattern = "/^[0-9a-z]+(?:[\_\-\.][a-z0-9\-]+)*@[a-z0-9]+(?:[-.][a-z0-9]+)*\.[a-z]+$/i";
return preg_match($pattern, $email);
}


/**
* 将密码加密
*
* @static
* @access public
* @param string $password 要加密的密码原文
* @return string
*/
public static function encryptPassword($password)
{
$string = '';
for ($i=0; $i<10; $i++) {
$string .= self::rand();
}

$salt = substr(md5($string), 0, 5);

$password = md5($salt . $password) . ':' . $salt;

return $password;
}


/**
* 对密码进行验证
*
* @static
* @access public
* @param string $password 密码原文
* @param string $encrypted 加密后的密码
* @return string
*/
public static function validatePassword($password, $encrypted)
{
if (!empty($password) && !empty($encrypted)){
$arr = explode(':', $encrypted);
if (count($arr) != 2){
return false;
}
if (md5($arr[1].$password) == $arr[0]){
return true;
}
}
return false;
}


/**
* 产生随机数
*
* @static
* @access public
* @param int $min 随机数最小值范围
* @param int $max 随机数最大值范围
* @return string
*/
public static function rand($min = null, $max = null)
{
static $seed;
if (!isset($seed)){
mt_srand((double)microtime()*1000000);
$seeded = true;
}

if (isset($min) && isset($max)){
if ($min >= $max){
return $min;
}else{
return mt_rand($min, $max);
}
}else{
return mt_rand();
}
}


/**
* @desc 创建随机密码
* @static
* @access public
* @return string
*/
public static function randPassword(){
$salt = "46z3haZzegmn676PA3rUw2vrkhcLEn2p1c6gf7vp2ny4u3qqfqBh5j6kDhuLmyv9xf";
//srand((double)microtime()*1000000); 自PHP 4.2.0 起,不再需要用srand()给随机数发生器播种现在是由系统自动完成的
$password = '';
for ($x = 0; $x < 7; $x++) {
$num = rand() % 33;
$tmp = substr($salt, $num, 1);
$password = $password . $tmp;
}
return $password;
}


/**
* 获取访问者的IP地址
*
* @access stat
* @var resource
*/
public static function IP()
{
if (isset($_SERVER)) {
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
} else {
if (getenv('HTTP_X_FORWARDED_FOR')) {
$ip = getenv('HTTP_X_FORWARDED_FOR');
} elseif (getenv('HTTP_CLIENT_IP')) {
$ip = getenv('HTTP_CLIENT_IP');
} else {
$ip = getenv('REMOTE_ADDR');
}
}

return $ip;
}


/**
* 判断是否为手机浏览
*
* @access static
* @return bool
*/
public static function isMobile(){
// 如果有HTTP_X_WAP_PROFILE则一定是移动设备
if (isset ($_SERVER['HTTP_X_WAP_PROFILE'])) {
return true;
}

//如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
if (isset ($_SERVER['HTTP_VIA'])) {
//找不到为flase,否则为true
return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
}

if (isset($_SERVER['HTTP_USER_AGENT'])){
$keywords = array(
'nokia', 'sony', 'ericsson', 'mot', 'samsung', 'htc', 'sgh',
'lg', 'sharp', 'sie-', 'philips', 'panasonic', 'alcatel', 'lenovo',
'iphone', 'ipod', 'blackberry', 'meizu', 'android', 'netfront', 'symbian',
'ucweb', 'windowsce', 'palm', 'operamini', 'operamobi', 'openwave', 'nexusone',
'cldc', 'midp', 'wap', 'mobile',
);
if (preg_match("/(" . implode('|', $keywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))){
return true;
}
}

if (isset ($_SERVER['HTTP_ACCEPT'])) {
if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false)
&& (
strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false
|| (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html'))
)
){
return true;
}
}

return false;
}

/**
* @desc Return a products_id from a product ID with attributes
* @param string $uprid 格式:23689{28}365
*/
public static function getPidFromCombineId($uprid) {
$pieces = explode('{', $uprid);

if (is_numeric($pieces[0])) {
return $pieces[0];
} else {
return false;
}
}

/**
* 创建SQL IN 子句
*
* @param array $item_list ID组
* @param string $field_name 字段名称
* @param bool $is_int 是否是整形的数组,如果是 则不使用单引号处理数据项
* @return string
*/
public static function createSqlIn($item_list, $field_name = '',$is_int=false)
{
if (empty($item_list))
{
return $field_name . " IN ('') ";
}
else
{
if (!is_array($item_list))
{
$item_list = explode(',', $item_list);
}
$item_list = array_unique($item_list);
$item_list_tmp = '';
foreach ($item_list AS $item)
{
if ($item !== '')
{
if($is_int == true)
{
$item_list_tmp .= $item_list_tmp ? ",$item" : "$item";
}
else
{
$item_list_tmp .= $item_list_tmp ? ",'$item'" : "'$item'";
}
}
}
if (empty($item_list_tmp))
{
return $field_name . " IN ('') ";
}
else
{
return $field_name . ' IN (' . $item_list_tmp . ') ';
}
}
}


/**
* @desc 判断$value是否为null
* @param $value
* @return bool true:not null,false:null
*/
public static function isNotNull($value) {
if (is_array($value)) {
if (count($value) > 0) {
return true;
}
else {
return false;
}
}
else {
if (($value != '') && (strtolower($value) != 'null') && (strlen(trim($value)) > 0)) {
return true;
}
else {
return false;
}
}
}

/**
* @desc 根据指定精度进行四舍五入
* @param number $number 金额/其他数值
* @param int $precision 精度
* @return number 四舍五入后结果
*/
public static function roundByPrecision($number, $precision)
{
if (strpos($number, '.') && (strlen(substr($number, strpos($number, '.')+1)) > $precision))
{
$number = substr($number, 0, strpos($number, '.') + 1 + $precision + 1);
if (substr($number, -1) >= 5)
{
if ($precision > 1)
{
$number = substr($number, 0, -1) + ('0.' . str_repeat(0, $precision-1) . '1');
}
elseif ($precision == 1)
{
$number = substr($number, 0, -1) + 0.1;
}
else
{
$number = substr($number, 0, -1) + 1;
}
}
else
{
$number = substr($number, 0, -1);
}
}
return $number;
}

/**
* @desc html实体转换为html字符
* @return string 格式化后的字符串
*/
public static function decodeSpecialchars($string){
$string=str_replace('&gt;', '>', $string);
$string=str_replace('&lt;', '<', $string);
$string=str_replace('&#039;', "'", $string);
$string=str_replace('&quot;', "\"", $string);
$string=str_replace('&amp;', '&', $string);

return $string;
}


/**
* 把xml对象转换成数组
*
* @static
* @param object $xmlObj
* @return array
*/
public static function xmlObjToArray($xmlObj){
$result = array();
if (is_object($xmlObj)){
$arr = get_object_vars($xmlObj);
if ($arr){
foreach ($arr as $k => $v){
if (is_object($v)){
$result[$k] = self::xmlObjToArray($v);
}
elseif (is_array($v)){
foreach ($v as $vk => $vv){
$v[$vk] = self::xmlObjToArray($vv);
}
$result[$k] = $v;
}else{
$result[$k] = $v;
}
}
}else{
return '';
}

}
else
{
return $xmlObj;
}
return $result;
}



/**
* 获取当前日期
*
* @static
* @param bool $is_china 是否获取中国日期
* @param string $format 日期格式
* @param bool $is_time 是否返回时间戳
* @param int $time 可设置具体时间点
* @return string
*/
public static function nowDate($is_china = false, $format = 'Y-m-d H:i:s', $is_time = false, $time = null){
if ($is_china){
$default_zone = date_default_timezone_get();
$china_zone = 'Etc/GMT-8';
date_default_timezone_set($china_zone);
}
$time = intval($time);
$format = $format ? $format : 'Y-m-d H:i:s';
$date = $time > 0 ? date($format, $time) : date($format);
$date = $is_time ? strtotime($date) : $date;

if ($is_china){
date_default_timezone_set($default_zone);
}

return $date;
}


/**
* 把中国日期转换成服务器日期
*
* @static
* @param bool $china 中国日期
* @param string $format 日期格式
* @param bool $is_time 是否返回时间戳
* @return string
*/
public static function china2ServerDate($china_date, $format = 'Y-m-d H:i:s', $is_time = false){
//保存服务器时区
$default_zone = date_default_timezone_get();

//设置中国时区
$china_zone = 'Etc/GMT-8';
date_default_timezone_set($china_zone);
//按中国时区转换成时间戳
$time = strtotime($china_date);
//还原服务器时区
date_default_timezone_set($default_zone);

if ($is_time){
return $time;
}

$format = $format ? $format : 'Y-m-d H:i:s';
$date = date($format, $time);

return $date;
}





/**
* 简单模拟多线程请求
*
* @static
* @access public
* @param string $url_path 请求程序脚本地址
* @param string $host 请求域名
* @param int $port 请求端口号
* @param int $time 超时时间
* @return void
*/
public static function asynReuquest($url_path, $host, $port = 80, $time = 5){
$fp = @fsockopen($host, $port, &$errno, &$errstr, $time);
if (!$fp){
ZERROR::raiseWarning(404, 'Can not connect asyn host');
}
@fputs($fp, "GET $url_path\r\n");
@fclose($fp);
}


/**
* @desc 判断是否是异步请求
* @static
* @return bool
*/
public static function isAjaxRequest()
{
$isAjax = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] ==='XMLHttpRequest' ? true : false;

return $isAjax;
}


/**
* @desc 发送系统邮件
* @static
* @access public
* @param string $toName 收件人名称
* @param string $toEmail 收件人邮箱
* @param string $subject 邮件标题
* @param string $body 邮件内容
* @param string $fromName 发件人名称
* @param string $fromEmail 发件人邮箱
* @return mixed
*/
public static function sendMail($toName, $toEmail, $subject, $body, $fromName, $fromEmail){
$PHPMailer = &ZFactory::getPHPMailer();
$body = preg_replace('/\\\\/','', $body);//Strip backslashes
//设置发邮件类型
$PHPMailer->IsMail();
//设置收件人
$PHPMailer->ClearAddresses();
$PHPMailer->AddAddress($toEmail, $toName);
//设置发件人
$PHPMailer->SetFrom($fromEmail, $fromName);
//设置邮件标题
$PHPMailer->Subject = $subject;
$PHPMailer->WordWrap = 80; // set word wrap
//邮件内容
$PHPMailer->MsgHTML($body);

$result = true;

$ret = $PHPMailer->Send();
if (!$ret){
$result = $PHPMailer->ErrorInfo;
}
return $result;
}


/**
* @desc 404跳转
* @access public
* @return void
*/
public function redirect404(){
header("HTTP/1.0 404 Not Found");
//Nginx不支持
//header("Status: 404 Not Found");

//加载伪静态处理对象
$url = '404.php';
header( 'Location: ' . $url );exit;
}


/**
* @desc ob_start缓存压缩函数
* @static
* @access public
* @param string $buffer 缓存内容
* @return string
*/
public static function compress($buffer){
$buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
return $buffer;
}



/**
* @desc 压缩Html内容去掉空白无用的字符
* @static
* @access public
* @param string $string html内容
* @return string
*/
public static function compressHtml($string) {
$string = str_replace('\r\n', '', $string); //清除换行符
$string = str_replace('\n', '', $string); //清除换行符
$string = str_replace('\t', '', $string); //清除制表符
$pattern = array (
"/> *([^ ]*) *</", //去掉注释标记
"/[\s]+/",
"/<!--[^!]*-->/",
//"/\" /", // 防止如 \" src 标签合并
"/ \"/",
"'/\*[^*]*\*/'"
);
$replace = array (
">\\1<",
" ",
"",
//"\"",
"\"",
""
);
return preg_replace($pattern, $replace, $string);
}


}